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: automate fal.ai scene video production
Adam Eivy87c756a91c52
diff --git a/client/src/components/fableloom/LoomCanvas.jsx b/client/src/components/fableloom/LoomCanvas.jsxindex 7fffba6005..8e6091d0b2 100644--- a/client/src/components/fableloom/LoomCanvas.jsx+++ b/client/src/components/fableloom/LoomCanvas.jsx@@ -40,7 +40,7 @@ export default function LoomCanvas({episode, selectedNodeId, onSelectNode, onMoveNode,viewportWidth: viewportWidthProp, orientation: orientationProp,mediaJobs = {}, onGenerateImage, onGenerateVideo,- onOpenFalVideo,+ onAutomateFalVideo,generationDisabled = false, generationDisabledReason = '',}) {// An in-flight drag lives entirely outside React state: the dragged <g>'s@@ -329,7 +329,7 @@ export default function LoomCanvas({jobs={mediaJobs[node.id]}onGenerateImage={onGenerateImage}onGenerateVideo={onGenerateVideo}- onOpenFalVideo={onOpenFalVideo}+ onAutomateFalVideo={onAutomateFalVideo}compactgenerationDisabled={generationDisabled}generationDisabledReason={generationDisabledReason}diff --git a/client/src/components/fableloom/LoomCanvas.test.jsx b/client/src/components/fableloom/LoomCanvas.test.jsxindex e6d2b0d504..5f13cd484a 100644--- a/client/src/components/fableloom/LoomCanvas.test.jsx+++ b/client/src/components/fableloom/LoomCanvas.test.jsx@@ -72,7 +72,7 @@ describe('LoomCanvas', () => {it('keeps media controls in each visual node and gives a finished video preview precedence', () => {const onGenerateImage = vi.fn();const onGenerateVideo = vi.fn();- const onOpenFalVideo = vi.fn();+ const onAutomateFalVideo = vi.fn();const withMedia = episode();withMedia.nodes[0] = {...withMedia.nodes[0], image: 'scene.png', videoHistoryId: 'video-1',@@ -84,7 +84,7 @@ describe('LoomCanvas', () => {onSelectNode={() => {}}onGenerateImage={onGenerateImage}onGenerateVideo={onGenerateVideo}- onOpenFalVideo={onOpenFalVideo}+ onAutomateFalVideo={onAutomateFalVideo}/>,);@@ -92,10 +92,10 @@ describe('LoomCanvas', () => {expect(screen.queryByAltText('The Gate image preview')).toBeNull();fireEvent.click(screen.getByRole('button', { name: 'Regenerate image' }));fireEvent.click(screen.getByRole('button', { name: 'Regenerate video' }));- fireEvent.click(screen.getAllByRole('button', { name: 'fal.ai free' })[0]);+ fireEvent.click(screen.getAllByRole('button', { name: 'Automate fal.ai' })[0]);expect(onGenerateImage).toHaveBeenCalledWith(withMedia.nodes[0]);expect(onGenerateVideo).toHaveBeenCalledWith(withMedia.nodes[0]);- expect(onOpenFalVideo).toHaveBeenCalledWith(withMedia.nodes[0]);+ expect(onAutomateFalVideo).toHaveBeenCalledWith(withMedia.nodes[0]);});it('shows live image progress and retains an actionable failed indicator', () => {diff --git a/client/src/components/fableloom/LoomMediaJobWatchers.jsx b/client/src/components/fableloom/LoomMediaJobWatchers.jsxindex bbd3dd9956..a2f47292f4 100644--- a/client/src/components/fableloom/LoomMediaJobWatchers.jsx+++ b/client/src/components/fableloom/LoomMediaJobWatchers.jsx@@ -9,6 +9,10 @@import { useEffect, useRef } from 'react';import useMediaJobProgress from '../../hooks/useMediaJobProgress';+import { getLoomFalVideo } from '../../services/api';++const FAL_POLL_MS = 2000;+const FAL_POLL_FAILURE_LIMIT = 3;function LoomMediaJobWatcher({ nodeId, kind, job, onUpdate, onTerminal }) {const progress = useMediaJobProgress(job.jobId, { kind });@@ -30,19 +34,80 @@ function LoomMediaJobWatcher({ nodeId, kind, job, onUpdate, onTerminal }) {return null;}+function LoomFalBrowserJobWatcher({ nodeId, kind, job, onUpdate, onTerminal }) {+ const reportedTerminalRef = useRef(null);++ useEffect(() => {+ let canceled = false;+ let timer = null;+ let failures = 0;++ const poll = () => {+ getLoomFalVideo(job.loomId, job.episodeId, nodeId, job.jobId, { silent: true })+ .then((progress) => {+ if (canceled) return;+ failures = 0;+ onUpdate(nodeId, kind, job.jobId, progress);+ const terminal = progress.status === 'failed' || progress.status === 'completed';+ const terminalKey = terminal ? `${job.jobId}:${progress.status}` : null;+ if (terminalKey && reportedTerminalRef.current !== terminalKey) {+ reportedTerminalRef.current = terminalKey;+ onTerminal(nodeId, kind, job.jobId, progress);+ return;+ }+ timer = setTimeout(poll, FAL_POLL_MS);+ })+ .catch(() => {+ if (canceled) return;+ failures += 1;+ if (failures < FAL_POLL_FAILURE_LIMIT) {+ timer = setTimeout(poll, FAL_POLL_MS);+ return;+ }+ const failed = {+ ...job,+ status: 'failed',+ error: 'Could not read fal.ai browser automation status',+ };+ onUpdate(nodeId, kind, job.jobId, failed);+ onTerminal(nodeId, kind, job.jobId, failed);+ });+ };++ poll();+ return () => {+ canceled = true;+ clearTimeout(timer);+ };+ }, [job.episodeId, job.jobId, job.loomId, kind, nodeId, onTerminal, onUpdate]);++ return null;+}+export default function LoomMediaJobWatchers({ jobs, onUpdate, onTerminal }) {return Object.entries(jobs).flatMap(([nodeId, nodeJobs]) => (['image', 'video'].map((kind) => {const job = nodeJobs?.[kind];return job?.jobId ? (- <LoomMediaJobWatcher- key={`${nodeId}:${kind}:${job.jobId}`}- nodeId={nodeId}- kind={kind}- job={job}- onUpdate={onUpdate}- onTerminal={onTerminal}- />+ job.source === 'fal-browser' ? (+ <LoomFalBrowserJobWatcher+ key={`${nodeId}:${kind}:${job.jobId}`}+ nodeId={nodeId}+ kind={kind}+ job={job}+ onUpdate={onUpdate}+ onTerminal={onTerminal}+ />+ ) : (+ <LoomMediaJobWatcher+ key={`${nodeId}:${kind}:${job.jobId}`}+ nodeId={nodeId}+ kind={kind}+ job={job}+ onUpdate={onUpdate}+ onTerminal={onTerminal}+ />+ )) : null;})));diff --git a/client/src/components/fableloom/LoomMediaJobWatchers.test.jsx b/client/src/components/fableloom/LoomMediaJobWatchers.test.jsxindex c0ead25bd2..c422a66fbe 100644--- a/client/src/components/fableloom/LoomMediaJobWatchers.test.jsx+++ b/client/src/components/fableloom/LoomMediaJobWatchers.test.jsx@@ -1,14 +1,23 @@-import { describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';import { render, waitFor } from '@testing-library/react';const hookState = vi.hoisted(() => ({value: { status: 'queued', progress: 0, filename: null, error: null },}));vi.mock('../../hooks/useMediaJobProgress', () => ({ default: () => hookState.value }));+const apiMocks = vi.hoisted(() => ({ getLoomFalVideo: vi.fn() }));+vi.mock('../../services/api', () => ({+ getLoomFalVideo: (...args) => apiMocks.getLoomFalVideo(...args),+}));import LoomMediaJobWatchers from './LoomMediaJobWatchers';describe('LoomMediaJobWatchers', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ hookState.value = { status: 'queued', progress: 0, filename: null, error: null };+ });+it('forwards a failed terminal media job exactly once', async () => {const onUpdate = vi.fn();const onTerminal = vi.fn();@@ -32,4 +41,49 @@ describe('LoomMediaJobWatchers', () => {rerender(<LoomMediaJobWatchers {...props} />);expect(onTerminal).toHaveBeenCalledTimes(1);});++ it('polls a fal browser job and forwards its durable video history id once', async () => {+ const onUpdate = vi.fn();+ const onTerminal = vi.fn();+ apiMocks.getLoomFalVideo.mockResolvedValue({+ id: 'fal-job-1',+ source: 'fal-browser',+ loomId: 'loom-1',+ episodeId: 'ep-1',+ nodeId: 'node-1',+ status: 'completed',+ videoHistoryId: 'upload-ab12cd34',+ });++ const { rerender } = render(+ <LoomMediaJobWatchers+ jobs={{ 'node-1': { video: {+ jobId: 'fal-job-1', source: 'fal-browser', loomId: 'loom-1', episodeId: 'ep-1', status: 'queued',+ } } }}+ onUpdate={onUpdate}+ onTerminal={onTerminal}+ />,+ );++ await waitFor(() => expect(onTerminal).toHaveBeenCalledWith(+ 'node-1',+ 'video',+ 'fal-job-1',+ expect.objectContaining({ status: 'completed', videoHistoryId: 'upload-ab12cd34' }),+ ));+ expect(apiMocks.getLoomFalVideo).toHaveBeenCalledWith(+ 'loom-1', 'ep-1', 'node-1', 'fal-job-1', { silent: true },+ );++ rerender(+ <LoomMediaJobWatchers+ jobs={{ 'node-1': { video: {+ jobId: 'fal-job-1', source: 'fal-browser', loomId: 'loom-1', episodeId: 'ep-1', status: 'queued',+ } } }}+ onUpdate={onUpdate}+ onTerminal={onTerminal}+ />,+ );+ expect(onTerminal).toHaveBeenCalledTimes(1);+ });});diff --git a/client/src/components/fableloom/LoomNodeEditor.jsx b/client/src/components/fableloom/LoomNodeEditor.jsxindex a81171f37e..0179ad5ebc 100644--- a/client/src/components/fableloom/LoomNodeEditor.jsx+++ b/client/src/components/fableloom/LoomNodeEditor.jsx@@ -69,7 +69,7 @@ const characterReferenceInfo = (character) => {export default function LoomNodeEditor({loom, episode, node, universe, onLoomUpdate, onClearSelection, onMakeStart,- mediaJobs = {}, onGenerateImage, onGenerateVideo, onOpenFalVideo,+ mediaJobs = {}, onGenerateImage, onGenerateVideo, onAutomateFalVideo,generationDisabled = false, generationDisabledReason = '',}) {const [form, setForm] = useState(null);@@ -248,22 +248,19 @@ export default function LoomNodeEditor({});};- const runOpenFalVideo = () => {+ const runAutomateFalVideo = async () => {const authoredPrompt = form.videoPrompt.trim() || form.prose.trim();if (!authoredPrompt) {toast.error('Write the scene first');return;}- // Keep window.open under the originating click. The free-tool handoff does- // not read server state, so persisting an unsaved prompt can finish after- // the new tab opens without risking a popup blocker.- onOpenFalVideo?.({+ await saveField('videoPrompt', form.videoPrompt);+ await onAutomateFalVideo?.({...node,prose: form.prose,videoPrompt: form.videoPrompt,cameraMovement: form.cameraMovement,});- void saveField('videoPrompt', form.videoPrompt);};const attachGalleryVideo = async (_targetNode, item) => {@@ -703,12 +700,12 @@ export default function LoomNodeEditor({jobs={mediaJobs}onGenerateImage={runGenerateImage}onGenerateVideo={runGenerateVideo}- onOpenFalVideo={runOpenFalVideo}+ onAutomateFalVideo={runAutomateFalVideo}onAttachVideo={attachGalleryVideo}generationDisabled={aiBlocked || generationDisabled}generationDisabledReason={aiBlocked ? 'Wait for scene changes to save' : generationDisabledReason}- falDisabled={generationDisabled}- falDisabledReason={generationDisabledReason}+ falDisabled={aiBlocked || generationDisabled}+ falDisabledReason={aiBlocked ? 'Wait for scene changes to save' : generationDisabledReason}/></div>diff --git a/client/src/components/fableloom/LoomNodeEditor.test.jsx b/client/src/components/fableloom/LoomNodeEditor.test.jsxindex a60f3b7c6a..3973f9711f 100644--- a/client/src/components/fableloom/LoomNodeEditor.test.jsx+++ b/client/src/components/fableloom/LoomNodeEditor.test.jsx@@ -54,7 +54,7 @@ const renderEditor = (transitions = [existingPath]) => {const onLoomUpdate = vi.fn();const onGenerateImage = vi.fn().mockResolvedValue({ jobId: 'image-1' });const onGenerateVideo = vi.fn().mockResolvedValue({ jobId: 'video-1' });- const onOpenFalVideo = vi.fn();+ const onAutomateFalVideo = vi.fn();render(<MemoryRouter><LoomNodeEditor@@ -71,11 +71,11 @@ const renderEditor = (transitions = [existingPath]) => {onClearSelection={() => {}}onGenerateImage={onGenerateImage}onGenerateVideo={onGenerateVideo}- onOpenFalVideo={onOpenFalVideo}+ onAutomateFalVideo={onAutomateFalVideo}/></MemoryRouter>,);- return { onLoomUpdate, onGenerateImage, onGenerateVideo, onOpenFalVideo };+ return { onLoomUpdate, onGenerateImage, onGenerateVideo, onAutomateFalVideo };};const renderHelperEditor = () => {@@ -324,19 +324,23 @@ describe('LoomNodeEditor scene media', () => {}));});- it('hands the current scene direction to the fal free tool without waiting on a save', async () => {+ it('saves and hands the current scene direction to fal browser automation', async () => {const user = userEvent.setup();- const { onOpenFalVideo } = renderEditor();+ updateLoomNode.mockResolvedValue({ id: 'loom-1' });+ const { onAutomateFalVideo } = renderEditor();await user.clear(screen.getByLabelText('Video prompt'));await user.type(screen.getByLabelText('Video prompt'), 'A fast practical-effects reveal.');- await user.click(screen.getByRole('button', { name: 'fal.ai free' }));+ await user.tab();+ await waitFor(() => expect(updateLoomNode).toHaveBeenCalledWith(+ 'loom-1', 'ep-1', 'n1', { videoPrompt: 'A fast practical-effects reveal.' }, { silent: true },+ ));+ await waitFor(() => expect(screen.getByRole('button', { name: 'Automate fal.ai' })).toBeEnabled());+ await user.click(screen.getByRole('button', { name: 'Automate fal.ai' }));- expect(onOpenFalVideo).toHaveBeenCalledWith(expect.objectContaining({- id: 'n1',- videoPrompt: 'A fast practical-effects reveal.',- cameraMovement: 'slow-dolly-in',- }));+ await waitFor(() => expect(onAutomateFalVideo).toHaveBeenCalledWith(expect.objectContaining({+ id: 'n1', videoPrompt: 'A fast practical-effects reveal.', cameraMovement: 'slow-dolly-in',+ })));});it('attaches an uploaded fal MP4 through the durable gallery history id', async () => {diff --git a/client/src/components/fableloom/LoomSceneMedia.jsx b/client/src/components/fableloom/LoomSceneMedia.jsxindex b15e0c0eee..3b49d1f14f 100644--- a/client/src/components/fableloom/LoomSceneMedia.jsx+++ b/client/src/components/fableloom/LoomSceneMedia.jsx@@ -8,7 +8,7 @@*/import { useState } from 'react';-import { AlertCircle, ExternalLink, ImagePlus, Loader2, Upload, Video } from 'lucide-react';+import { AlertCircle, ImagePlus, Loader2, Sparkles, Upload, Video } from 'lucide-react';import MediaImage from '../MediaImage';import GalleryVideoPicker from '../videoGen/GalleryVideoPicker';@@ -30,6 +30,7 @@ const jobStateLabel = (kind, job) => {if (job.status === 'failed') return `${noun[0].toUpperCase()}${noun.slice(1)} failed`;if (job.status === 'canceled') return `${noun[0].toUpperCase()}${noun.slice(1)} canceled`;if (!isActive(job)) return null;+ if (job.statusMsg) return job.statusMsg;const pct = progressPercent(job);return job.status === 'submitting'? `Starting ${noun}…`@@ -41,7 +42,7 @@ export default function LoomSceneMedia({jobs = {},onGenerateImage,onGenerateVideo,- onOpenFalVideo,+ onAutomateFalVideo,onAttachVideo,compact = false,generationDisabled = false,@@ -51,11 +52,15 @@ export default function LoomSceneMedia({}) {const [videoPickerOpen, setVideoPickerOpen] = useState(false);const imageJob = jobs.image || null;- const freeToolDisabled = falDisabled ?? generationDisabled;- const freeToolDisabledReason = falDisabledReason ?? generationDisabledReason;const videoJob = jobs.video || null;const imageActive = isActive(imageJob);const videoActive = isActive(videoJob);+ const falActive = videoActive && videoJob?.source === 'fal-browser';+ const falRequiresImage = !node.image;+ const freeToolDisabled = (falDisabled ?? generationDisabled) || videoActive || falRequiresImage;+ const configuredFalDisabledReason = falDisabledReason ?? generationDisabledReason;+ const freeToolDisabledReason = configuredFalDisabledReason+ || (falRequiresImage ? 'Generate a scene image first so fal.ai has a starting frame' : '');const activeJob = videoActive ? videoJob : imageActive ? imageJob : null;const activeKind = videoActive ? 'video' : imageActive ? 'image' : null;const failedJob = videoJob?.status === 'failed'@@ -180,13 +185,15 @@ export default function LoomSceneMedia({</button><buttontype="button"- onClick={() => onOpenFalVideo?.(node)}- disabled={freeToolDisabled || !onOpenFalVideo}- title={freeToolDisabledReason || 'Copy this scene prompt and open fal H3 Max (up to 15 free browser renders per day with an account)'}+ onClick={() => onAutomateFalVideo?.(node)}+ disabled={freeToolDisabled || !onAutomateFalVideo}+ title={freeToolDisabledReason || 'Upload the scene image and prompt to fal.ai H3 Max, then save the finished video here'}className={buttonClass}>- <ExternalLink size={compact ? 10 : 12} aria-hidden="true" />- <span className="truncate">fal.ai free</span>+ {falActive+ ? <Loader2 size={compact ? 10 : 12} className="animate-spin" aria-hidden="true" />+ : <Sparkles size={compact ? 10 : 12} aria-hidden="true" />}+ <span className="truncate">{falActive ? 'Running fal.ai' : 'Automate fal.ai'}</span></button>{!compact && (<button@@ -211,6 +218,11 @@ export default function LoomSceneMedia({{generationDisabledReason && !noticeLabel && !compact && (<p className="text-xs text-port-text-muted" role="status">{generationDisabledReason}</p>)}+ {!generationDisabledReason && falRequiresImage && !noticeLabel && !compact && (+ <p className="text-xs text-port-text-muted" role="status">+ Generate a scene image first to use it as fal.ai's starting frame.+ </p>+ )}{!compact && (<GalleryVideoPickeropen={videoPickerOpen}diff --git a/client/src/pages/FableLoomStory.jsx b/client/src/pages/FableLoomStory.jsxindex 4aeddb5633..9e55650756 100644--- a/client/src/pages/FableLoomStory.jsx+++ b/client/src/pages/FableLoomStory.jsx@@ -43,19 +43,19 @@ import LoomSettingsDrawer from '../components/fableloom/LoomSettingsDrawer';import LoomSeriesPlan from '../components/fableloom/LoomSeriesPlan';import LoomValidationPanel from '../components/fableloom/LoomValidationPanel';import LoomAiRunStatus from '../components/fableloom/LoomAiRunStatus';-import FalH3MaxPromptFallback from '../components/videoGen/FalH3MaxPromptFallback';import { fieldClass, labelClass } from '../components/fableloom/fieldStyles';import {buildFableLoomImageRequest, buildFableLoomVideoRequest,} from '../components/fableloom/sceneMediaRequests';import { universeStylePreset } from '../lib/universeStylePreset';import { fableLoomMediaReadiness } from '../lib/fableLoomReadiness';-import { openFalH3MaxFreeTool } from '../lib/falVideoHandoff';+import { buildFalH3MaxPrompt } from '../lib/falVideoHandoff';import { LOOM_ORIENTATION, LOOM_STACK_WIDTH } from '../lib/loomLayout';+import { asFableLoomRenderSettings } from '../../../server/lib/fableLoomProduction.js';import {addLoomEpisode, addLoomNode, deleteLoomEpisode, generateImage, generateVideo,getLoom, getPipelineSeries, getUniverse, updateLoomEpisode, updateLoomNode,- weaveLoomEpisode,+ startLoomFalVideo, weaveLoomEpisode,} from '../services/api';// Phone-first sizing: a 44px touch target next to the overflow trigger, then@@ -85,7 +85,6 @@ export default function FableLoomStory({ view = 'graph' }) {const [notFound, setNotFound] = useState(false);const [setupOpen, setSetupOpen] = useState(false);const [settingsOpen, setSettingsOpen] = useState(false);- const [falManualPrompt, setFalManualPrompt] = useState('');const playOpen = searchParams.get('play') === '1';useScrollLock(playOpen);const seriesPlanOpen = episodeId === 'plan';@@ -240,10 +239,10 @@ export default function FableLoomStory({ view = 'graph' }) {if (kind === 'image') {applySceneMedia(targetNodeId, { image: progress.filename, imageJobId: jobId });} else {- applySceneMedia(targetNodeId, { videoHistoryId: jobId });+ applySceneMedia(targetNodeId, { videoHistoryId: progress.videoHistoryId || jobId });}setSceneMediaJob(targetNodeId, kind, null);- toast.success(`Scene ${label} ready`);+ toast.success(progress.source === 'fal-browser' ? 'Scene video ready from fal.ai' : `Scene ${label} ready`);}, [applySceneMedia, setSceneMediaJob]);const queueSceneImage = useCallback(async (targetNode) => {@@ -347,28 +346,56 @@ export default function FableLoomStory({ view = 'graph' }) {return queued;}, [episodeId, generationDisabledReason, loom, mediaReadiness.reason, mediaWorkflowBlocked, sceneStylePreset, setSceneMediaJob, styleContextLoading, styleContextUnavailable]);- const openFalSceneVideo = useCallback((targetNode) => {+ const automateFalSceneVideo = useCallback(async (targetNode) => {const prompt = (targetNode?.videoPrompt || '').trim() || (targetNode?.prose || '').trim();if (!prompt) {toast.error('Write the scene first');- return false;+ return null;+ }+ if (!targetNode?.image) {+ toast.error('Generate a scene image first so fal.ai has a starting frame');+ return null;}if (mediaWorkflowBlocked) {toast.error(mediaReadiness.reason);- return false;+ return null;}if (styleContextLoading || styleContextUnavailable) {toast.error(generationDisabledReason || 'Scene style is not ready');- return false;+ return null;}const request = buildFableLoomVideoRequest({loom, episodeId, node: targetNode, stylePreset: sceneStylePreset,});- return openFalH3MaxFreeTool({- ...request,- onCopyFailure: setFalManualPrompt,+ const fullPrompt = buildFalH3MaxPrompt(request.prompt, request.negativePrompt);+ const render = asFableLoomRenderSettings(loom?.renderSettings);+ setSceneMediaJob(targetNode.id, 'video', {+ jobId: null,+ source: 'fal-browser',+ status: 'submitting',+ statusMsg: 'Starting fal.ai browser automation…',});- }, [episodeId, generationDisabledReason, loom, mediaReadiness.reason, mediaWorkflowBlocked, sceneStylePreset, styleContextLoading, styleContextUnavailable]);+ const queued = await startLoomFalVideo(+ loom.id,+ episodeId,+ targetNode.id,+ { prompt: fullPrompt, aspectRatio: render.aspectRatio },+ { silent: true },+ ).catch((error) => {+ setSceneMediaJob(targetNode.id, 'video', {+ jobId: null,+ source: 'fal-browser',+ status: 'failed',+ error: error.message || 'Could not start fal.ai browser automation',+ });+ toast.error(`Could not start fal.ai video: ${error.message || 'Browser automation failed'}`);+ return null;+ });+ if (!queued) return null;+ setSceneMediaJob(targetNode.id, 'video', { ...queued, jobId: queued.id });+ toast.success(queued.status === 'queued' ? 'fal.ai scene video queued' : 'fal.ai scene video already running');+ return queued;+ }, [episodeId, generationDisabledReason, loom, mediaReadiness.reason, mediaWorkflowBlocked, sceneStylePreset, setSceneMediaJob, styleContextLoading, styleContextUnavailable]);const basePath = `/fableloom/${loomId}`;const episodePath = useCallback(@@ -612,7 +639,7 @@ export default function FableLoomStory({ view = 'graph' }) {mediaJobs={mediaJobs}onGenerateImage={queueSceneImage}onGenerateVideo={queueSceneVideo}- onOpenFalVideo={openFalSceneVideo}+ onAutomateFalVideo={automateFalSceneVideo}generationDisabled={styleContextLoading || styleContextUnavailable || mediaWorkflowBlocked}generationDisabledReason={mediaGenerationDisabledReason}/>@@ -683,7 +710,7 @@ export default function FableLoomStory({ view = 'graph' }) {mediaJobs={mediaJobs[node.id]}onGenerateImage={queueSceneImage}onGenerateVideo={queueSceneVideo}- onOpenFalVideo={openFalSceneVideo}+ onAutomateFalVideo={automateFalSceneVideo}generationDisabled={styleContextLoading || styleContextUnavailable || mediaWorkflowBlocked}generationDisabledReason={mediaGenerationDisabledReason}onMakeStart={node.id !== episode.startNodeId ? async () => {@@ -752,10 +779,6 @@ export default function FableLoomStory({ view = 'graph' }) {</Modal>)}- <FalH3MaxPromptFallback- prompt={falManualPrompt}- onClose={() => setFalManualPrompt('')}- /></div>);}diff --git a/client/src/pages/FableLoomStory.test.jsx b/client/src/pages/FableLoomStory.test.jsxindex e609984571..a9a5423db3 100644--- a/client/src/pages/FableLoomStory.test.jsx+++ b/client/src/pages/FableLoomStory.test.jsx@@ -15,6 +15,7 @@ vi.mock('../services/api', () => ({getLoom: vi.fn(),getPipelineSeries: vi.fn(),getUniverse: vi.fn(),+ startLoomFalVideo: vi.fn(),updateLoomEpisode: vi.fn(),updateLoom: vi.fn(),updateLoomNode: vi.fn(),@@ -24,7 +25,7 @@ vi.mock('../services/api', () => ({// Keep the graph lightweight while exposing its page-owned scene-media action// and state. The canvas component itself covers preview/button rendering.vi.mock('../components/fableloom/LoomCanvas', () => ({- default: ({ episode, mediaJobs, onGenerateImage, generationDisabled }) => (+ default: ({ episode, mediaJobs, onGenerateImage, onAutomateFalVideo, generationDisabled }) => (<div><buttontype="button"@@ -44,24 +45,53 @@ vi.mock('../components/fableloom/LoomCanvas', () => ({)}<span data-testid="canvas-image-status">{mediaJobs[episode.nodes[0].id]?.image?.status || 'idle'}</span><span data-testid="canvas-image-filename">{episode.nodes[0].image || 'none'}</span>+ <button+ type="button"+ disabled={generationDisabled || !episode.nodes[0].image}+ onClick={() => onAutomateFalVideo(episode.nodes[0])}+ >+ Canvas automate fal.ai+ </button>+ <span data-testid="canvas-video-status">{mediaJobs[episode.nodes[0].id]?.video?.status || 'idle'}</span>+ <span data-testid="canvas-video-id">{episode.nodes[0].videoHistoryId || 'none'}</span></div>),}));vi.mock('../components/fableloom/LoomMediaJobWatchers', () => ({default: ({ jobs, onUpdate, onTerminal }) => {const image = jobs['node-1']?.image;- if (!image?.jobId) return null;+ const falVideo = jobs['node-1']?.video?.source === 'fal-browser' ? jobs['node-1'].video : null;return (- <button- type="button"- onClick={() => {- const failed = { ...image, status: 'failed', error: 'Synthetic provider failure' };- onUpdate('node-1', 'image', image.jobId, failed);- onTerminal('node-1', 'image', image.jobId, failed);- }}- >- Simulate image failure- </button>+ <>+ {image?.jobId && (+ <button+ type="button"+ onClick={() => {+ const failed = { ...image, status: 'failed', error: 'Synthetic provider failure' };+ onUpdate('node-1', 'image', image.jobId, failed);+ onTerminal('node-1', 'image', image.jobId, failed);+ }}+ >+ Simulate image failure+ </button>+ )}+ {falVideo?.jobId && (+ <button+ type="button"+ onClick={() => {+ const completed = {+ ...falVideo,+ status: 'completed',+ videoHistoryId: 'upload-ab12cd34',+ };+ onUpdate('node-1', 'video', falVideo.jobId, completed);+ onTerminal('node-1', 'video', falVideo.jobId, completed);+ }}+ >+ Simulate fal.ai completion+ </button>+ )}+ </>);},}));@@ -496,4 +526,50 @@ describe('FableLoomStory scene media lifecycle', () => {'Could not start scene image: Canon conditioning unavailable',);});++ it('automates fal.ai with the starting image context and attaches the finished browser render', async () => {+ const user = userEvent.setup();+ api.getLoom.mockResolvedValue(loom({+ styleNotes: 'blue dusk lighting',+ episodes: [episode({+ nodes: [{+ id: 'node-1',+ title: 'Threshold',+ prose: 'You stand before the first door.',+ videoPrompt: 'The door opens in one uninterrupted practical-effects reveal.',+ image: 'threshold.png',+ transitions: [],+ }],+ })],+ }));+ api.startLoomFalVideo.mockResolvedValue({+ id: 'fal-job-1',+ source: 'fal-browser',+ loomId: 'loom-1',+ episodeId: 'ep-1',+ nodeId: 'node-1',+ status: 'queued',+ statusMsg: 'Waiting for the fal.ai browser…',+ });+ renderEditor('/fableloom/loom-1/ep-1');++ await user.click(await screen.findByRole('button', { name: 'Canvas automate fal.ai' }));++ await waitFor(() => expect(api.startLoomFalVideo).toHaveBeenCalledWith(+ 'loom-1',+ 'ep-1',+ 'node-1',+ {+ prompt: 'The door opens in one uninterrupted practical-effects reveal.\n\nStyle: blue dusk lighting',+ aspectRatio: '16:9',+ },+ { silent: true },+ ));+ expect(screen.getByTestId('canvas-video-status')).toHaveTextContent('queued');++ await user.click(screen.getByRole('button', { name: 'Simulate fal.ai completion' }));+ await waitFor(() => expect(screen.getByTestId('canvas-video-id')).toHaveTextContent('upload-ab12cd34'));+ expect(screen.getByTestId('canvas-video-status')).toHaveTextContent('idle');+ expect(toastMocks.success).toHaveBeenCalledWith('Scene video ready from fal.ai');+ });});diff --git a/client/src/services/apiFableLoom.js b/client/src/services/apiFableLoom.jsindex 9d845cb58d..8420da948d 100644--- a/client/src/services/apiFableLoom.js+++ b/client/src/services/apiFableLoom.js@@ -91,6 +91,14 @@ export const deleteLoomNode = (id, episodeId, nodeId, options = {}) => request(nmethod: 'DELETE', ...options,});+export const startLoomFalVideo = (id, episodeId, nodeId, body, options = {}) =>+ request(nodePath(id, episodeId, nodeId, '/fal-video'), {+ method: 'POST', body: JSON.stringify(body), ...options,+ });++export const getLoomFalVideo = (id, episodeId, nodeId, jobId, options = {}) =>+ request(nodePath(id, episodeId, nodeId, `/fal-video/${encodeURIComponent(jobId)}`), options);+// One path out of a scene per call. `addLoomTransition` resolves to// `{ loom, transition }` — the row carries its server-minted id, so the editor// never has to reconcile ids back into locally-added rows. The node PATCH'sdiff --git a/client/src/services/apiFableLoom.test.js b/client/src/services/apiFableLoom.test.jsindex 2ea59c852f..7daf0f5fce 100644--- a/client/src/services/apiFableLoom.test.js+++ b/client/src/services/apiFableLoom.test.js@@ -34,6 +34,20 @@ describe('apiFableLoom', () => {});});+ it('starts and polls one encoded fal.ai browser job path', async () => {+ const body = { prompt: 'One continuous example shot.', aspectRatio: '9:16' };+ await api.startLoomFalVideo('loom/1', 'ep/1', 'node/1', body, { silent: true });+ expect(request).toHaveBeenCalledWith('/fableloom/loom%2F1/episodes/ep%2F1/nodes/node%2F1/fal-video', {+ method: 'POST', body: JSON.stringify(body), silent: true,+ });++ await api.getLoomFalVideo('loom/1', 'ep/1', 'node/1', 'fal/1', { silent: true });+ expect(request).toHaveBeenCalledWith(+ '/fableloom/loom%2F1/episodes/ep%2F1/nodes/node%2F1/fal-video/fal%2F1',+ { silent: true },+ );+ });+it('posts weave options to the episode weave lane', async () => {await api.weaveLoomEpisode('loom-1', 'ep-1', { guidance: 'darker', replace: true });expect(request).toHaveBeenCalledWith('/fableloom/loom-1/episodes/ep-1/weave', {diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex 9ea379bdc5..dc730eaec5 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -8802,7 +8802,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 107+ "line": 110}]},@@ -8813,7 +8813,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 114+ "line": 117}]},@@ -8824,7 +8824,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 130+ "line": 133}]},@@ -8835,7 +8835,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 119+ "line": 122}]},@@ -8846,7 +8846,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 125+ "line": 128}]},@@ -8857,7 +8857,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 182+ "line": 185}]},@@ -8868,7 +8868,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 190+ "line": 193}]},@@ -8879,7 +8879,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 169+ "line": 172}]},@@ -8890,7 +8890,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 175+ "line": 178}]},@@ -8901,7 +8901,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 159+ "line": 162}]},@@ -8912,7 +8912,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 200+ "line": 203}]},@@ -8923,7 +8923,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 210+ "line": 213}]},@@ -8934,7 +8934,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 205+ "line": 208}]},@@ -8945,7 +8945,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 410+ "line": 435}]},@@ -8956,7 +8956,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 327+ "line": 352}]},@@ -8967,7 +8967,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 248+ "line": 251}]},@@ -8978,7 +8978,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 258+ "line": 261}]},@@ -8989,7 +8989,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 253+ "line": 256}]},@@ -9000,7 +9000,29 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 314+ "line": 339+ }+ ]+ },+ {+ "method": "POST",+ "path": "/api/fableloom/:id/episodes/:episodeId/nodes/:nodeId/fal-video",+ "mountPath": "/api/fableloom",+ "sources": [+ {+ "source": "server/routes/fableLoom.js",+ "line": 268+ }+ ]+ },+ {+ "method": "GET",+ "path": "/api/fableloom/:id/episodes/:episodeId/nodes/:nodeId/fal-video/:jobId",+ "mountPath": "/api/fableloom",+ "sources": [+ {+ "source": "server/routes/fableLoom.js",+ "line": 278}]},@@ -9011,7 +9033,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 237+ "line": 240}]},@@ -9022,7 +9044,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 271+ "line": 296}]},@@ -9033,7 +9055,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 283+ "line": 308}]},@@ -9044,7 +9066,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 276+ "line": 301}]},@@ -9055,7 +9077,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 299+ "line": 324}]},@@ -9066,7 +9088,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 309+ "line": 334}]},@@ -9077,7 +9099,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 304+ "line": 329}]},@@ -9088,7 +9110,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 332+ "line": 357}]},@@ -9099,7 +9121,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 381+ "line": 406}]},@@ -9110,7 +9132,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 386+ "line": 411}]},@@ -9121,7 +9143,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 394+ "line": 419}]},@@ -9132,7 +9154,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 402+ "line": 427}]},@@ -9143,7 +9165,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 376+ "line": 401}]},@@ -9154,7 +9176,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 343+ "line": 368}]},@@ -9165,7 +9187,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 319+ "line": 344}]},@@ -9176,7 +9198,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 354+ "line": 379}]},@@ -9187,7 +9209,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 350+ "line": 375}]},@@ -9198,7 +9220,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 221+ "line": 224}]},@@ -9209,7 +9231,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 291+ "line": 316}]},@@ -9220,7 +9242,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 215+ "line": 218}]},@@ -9231,7 +9253,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 152+ "line": 155}]},@@ -9242,7 +9264,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 137+ "line": 140}]},@@ -9253,7 +9275,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 142+ "line": 145}]},@@ -9264,7 +9286,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 164+ "line": 167}]},@@ -9275,7 +9297,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 147+ "line": 150}]},@@ -9286,7 +9308,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 370+ "line": 395}]},@@ -9297,7 +9319,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 359+ "line": 384}]},@@ -9308,7 +9330,7 @@"sources": [{"source": "server/routes/fableLoom.js",- "line": 365+ "line": 390}]},@@ -23709,8 +23731,8 @@],"stats": {"mounts": 146,- "operations": 2139,- "declarations": 2142,+ "operations": 2141,+ "declarations": 2144,"sourceFiles": 226}}diff --git a/server/lib/fableLoomValidation.js b/server/lib/fableLoomValidation.jsindex 720c60bbeb..62c5329bfc 100644--- a/server/lib/fableLoomValidation.js+++ b/server/lib/fableLoomValidation.js@@ -301,6 +301,13 @@ export const nodeCreateSchema = z.object({export const nodePatchSchema = z.object(nodeFields);+export const falVideoAutomationSchema = z.object({+ // This is the fully composed browser-tool prompt (scene direction, camera,+ // style, and avoid block), not just the persisted node.videoPrompt leaf.+ prompt: z.string().trim().min(1).max(12_000),+ aspectRatio: z.enum(['16:9', '9:16', '1:1', '4:3']).optional(),+});+// A per-call pick carries the same three dimensions as the saved pin.const llmPickFields = llmRoutePinSchema.shape;const aiRunFields = { ...llmPickFields, operationId: z.string().uuid().optional() };diff --git a/server/package-lock.json b/server/package-lock.jsonindex f0cc2eb2e3..a664726166 100644--- a/server/package-lock.json+++ b/server/package-lock.json@@ -18,6 +18,7 @@"node-pty": "1.2.0-beta.15","pdf-lib": "^1.17.1","pg": "8.23.0",+ "playwright-core": "1.62.1","pm2": "7.0.4","sharp": "0.35.4","socket.io": "4.8.3",@@ -3790,6 +3791,18 @@"integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==","license": "MIT"},+ "node_modules/playwright-core": {+ "version": "1.62.1",+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.1.tgz",+ "integrity": "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==",+ "license": "Apache-2.0",+ "bin": {+ "playwright-core": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ },"node_modules/pm2": {"version": "7.0.4","resolved": "https://registry.npmjs.org/pm2/-/pm2-7.0.4.tgz",diff --git a/server/package.json b/server/package.jsonindex b1a5b7db1d..977bd984d3 100644--- a/server/package.json+++ b/server/package.json@@ -31,6 +31,7 @@"node-pty": "1.2.0-beta.15","pdf-lib": "^1.17.1","pg": "8.23.0",+ "playwright-core": "1.62.1","pm2": "7.0.4","sharp": "0.35.4","socket.io": "4.8.3",diff --git a/server/routes/fableLoom.js b/server/routes/fableLoom.jsindex e8e70b724e..d363727e8c 100644--- a/server/routes/fableLoom.js+++ b/server/routes/fableLoom.js@@ -16,6 +16,7 @@ import {episodeCreateSchema,episodePatchSchema,feedbackSchema,+ falVideoAutomationSchema,loomCreateSchema,loomListQuerySchema,loomPatchSchema,@@ -67,6 +68,7 @@ import {feedbackSeriesPlan,generateEpisodeOutline,generateSeriesPlan,+ getFalVideoAutomation,getEpisodeProductionBatch,getHostedSession,getLoom,@@ -81,6 +83,7 @@ import {reviewSeriesPlan,reviewSeriesTeleplay,startEpisodeProductionBatch,+ startFalVideoAutomation,updateEpisode,updateHostedSession,updateLoom,@@ -259,6 +262,28 @@ router.delete('/:id/episodes/:episodeId/nodes/:nodeId', asyncHandler(async (req,res.json(await deleteNode(req.params.id, req.params.episodeId, req.params.nodeId));}));+// The free fal.ai allowance is browser-only. A direct user click starts one+// serialized Playwright job against PortOS's persistent CDP browser; the job+// owns the eventual gallery write + scene attachment even if the page closes.+router.post('/:id/episodes/:episodeId/nodes/:nodeId/fal-video', asyncHandler(async (req, res) => {+ const input = validateRequest(falVideoAutomationSchema, req.body);+ res.status(202).json(await startFalVideoAutomation(+ req.params.id,+ req.params.episodeId,+ req.params.nodeId,+ input,+ ));+}));++router.get('/:id/episodes/:episodeId/nodes/:nodeId/fal-video/:jobId', asyncHandler(async (req, res) => {+ res.json(getFalVideoAutomation(+ req.params.id,+ req.params.episodeId,+ req.params.nodeId,+ req.params.jobId,+ ));+}));+// --- Transitions ------------------------------------------------------------//// One edge per request. The node PATCH still accepts a whole `transitions`diff --git a/server/routes/fableLoom.test.js b/server/routes/fableLoom.test.jsindex 78e5aaf0ba..7e1fc5ea43 100644--- a/server/routes/fableLoom.test.js+++ b/server/routes/fableLoom.test.js@@ -18,6 +18,7 @@ vi.mock('../services/fableLoom/index.js', () => ({feedbackSeriesPlan: vi.fn(),generateEpisodeOutline: vi.fn(),generateSeriesPlan: vi.fn(),+ getFalVideoAutomation: vi.fn(),getFableLoomEditorialAutopilot: vi.fn(),getLatestFableLoomEditorialAutopilot: vi.fn(),getLoom: vi.fn(),@@ -45,6 +46,7 @@ vi.mock('../services/fableLoom/index.js', () => ({endHostedSession: vi.fn(),planEpisodeProduction: vi.fn(),startEpisodeProductionBatch: vi.fn(),+ startFalVideoAutomation: vi.fn(),getEpisodeProductionBatch: vi.fn(),cancelEpisodeProductionBatch: vi.fn(),resumeEpisodeProductionBatch: vi.fn(),@@ -265,6 +267,40 @@ describe('FableLoom routes', () => {expect(fableLoom.deleteNode).toHaveBeenCalledWith('loom-1', 'ep-1', 'node-1');});+ it('starts and reads a validated fal.ai browser job for one scene', async () => {+ const job = {+ id: 'fal-job-1', source: 'fal-browser', loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-1', status: 'queued',+ };+ fableLoom.startFalVideoAutomation.mockResolvedValueOnce(job);+ const created = await request(makeApp())+ .post('/api/fableloom/loom-1/episodes/ep-1/nodes/node-1/fal-video')+ .send({ prompt: 'One continuous example shot.', aspectRatio: '9:16' });++ expect(created.status).toBe(202);+ expect(created.body).toEqual(job);+ expect(fableLoom.startFalVideoAutomation).toHaveBeenCalledWith('loom-1', 'ep-1', 'node-1', {+ prompt: 'One continuous example shot.', aspectRatio: '9:16',+ });++ fableLoom.getFalVideoAutomation.mockReturnValueOnce({ ...job, status: 'running' });+ const status = await request(makeApp())+ .get('/api/fableloom/loom-1/episodes/ep-1/nodes/node-1/fal-video/fal-job-1');+ expect(status.status).toBe(200);+ expect(status.body.status).toBe('running');+ expect(fableLoom.getFalVideoAutomation).toHaveBeenCalledWith(+ 'loom-1', 'ep-1', 'node-1', 'fal-job-1',+ );+ });++ it('rejects an empty fal.ai scene prompt before browser automation starts', async () => {+ const response = await request(makeApp())+ .post('/api/fableloom/loom-1/episodes/ep-1/nodes/node-1/fal-video')+ .send({ prompt: ' ', aspectRatio: '16:9' });++ expect(response.status).toBe(400);+ expect(fableLoom.startFalVideoAutomation).not.toHaveBeenCalled();+ });+it('POST transitions mints one path and answers with the loom plus the row', async () => {fableLoom.addNodeTransition.mockResolvedValueOnce({loom: { id: 'loom-1' }, transition: { id: 'tr-1', targetNodeId: 'node-2', intent: 'press on' },diff --git a/server/services/fableLoom/README.md b/server/services/fableLoom/README.mdindex 427b4cc11e..c49c122354 100644--- a/server/services/fableLoom/README.md+++ b/server/services/fableLoom/README.md@@ -16,6 +16,7 @@ intent to a transition and moves them through the graph until an ending.| `formats.js` | Scene formats (`prose` / `teleplay`) and the prompt contracts each generative stage renders for them. || `hostedSession.js` | Scoped QR-hosted play session lifecycle, HTTPS readiness preflight, token hashing, live voice gate revalidation, and half-duplex turn taking (#5383). || `production.js` | Episodic production orchestration: batch planning, DAG generation, cancellable batch runs, and user-triggered episodic continuity review (#5384). |+| `falVideoAutomation.js` | User-triggered, serialized Playwright automation over the persistent PortOS CDP browser: uploads a scene still + full shot prompt to fal.ai H3 Max, downloads the finished MP4 into shared video history, and attaches it to the originating scene. || `store.js` | PostgreSQL/file backend facade (`fableloom_stories`; collectionStore escape hatch for tests). || `db.js` | PostgreSQL leaf I/O. |diff --git a/server/services/fableLoom/falVideoAutomation.js b/server/services/fableLoom/falVideoAutomation.jsnew file mode 100644index 0000000000..e8752dd8e0--- /dev/null+++ b/server/services/fableLoom/falVideoAutomation.js@@ -0,0 +1,368 @@+/**+ * User-triggered fal.ai H3 Max browser automation for one FableLoom scene.+ *+ * Jobs run serially against PortOS's persistent CDP browser so two scene+ * requests cannot overwrite the same free-tool form. The browser keeps the+ * user's fal.ai session; Playwright only fills the authored prompt, uploads+ * the scene's current storyboard still, starts the render, and downloads the+ * finished clip. The durable gallery write + scene attachment happen here,+ * independent of whether the initiating client stays mounted.+ */++import { randomUUID } from 'node:crypto';+import { chromium } from 'playwright-core';+import { ServerError } from '../../lib/errorHandler.js';+import { resolveGalleryImage } from '../../lib/pathSafety.js';+import { getHealthStatus, launchBrowser } from '../browserService.js';+import {+ MAX_GALLERY_VIDEO_UPLOAD_BYTES,+ saveUploadedGalleryVideoBuffer,+} from '../videoUpload.js';+import { attachNodeVideo, getLoom } from './records.js';++export const FAL_H3_MAX_FREE_URL = 'https://fal.ai/tools/minimax-h3-max';++const FAL_RENDER_TIMEOUT_MS = 20 * 60 * 1000;+const FAL_CONTROL_TIMEOUT_MS = 2 * 60 * 1000;+const FAL_RESULT_POLL_MS = 2000;+const FAL_JOB_TTL_MS = 24 * 60 * 60 * 1000;+const ACTIVE_STATUSES = new Set(['queued', 'running']);+const FAL_ASPECT_RATIOS = new Set(['16:9', '9:16', '1:1']);++const jobs = new Map();+const latestJobByScene = new Map();+let runTail = Promise.resolve();++const sceneKey = (loomId, episodeId, nodeId) => JSON.stringify([loomId, episodeId, nodeId]);++const findScene = (loom, episodeId, nodeId) => {+ const episode = loom?.episodes?.find((item) => item.id === episodeId);+ const node = episode?.nodes?.find((item) => item.id === nodeId);+ return { episode, node };+};++const publicJob = (job) => ({+ id: job.id,+ source: 'fal-browser',+ loomId: job.loomId,+ episodeId: job.episodeId,+ nodeId: job.nodeId,+ status: job.status,+ statusMsg: job.statusMsg,+ progress: job.progress,+ createdAt: job.createdAt,+ startedAt: job.startedAt,+ completedAt: job.completedAt,+ error: job.error,+ videoHistoryId: job.videoHistoryId,+ filename: job.filename,+});++const pruneJobs = () => {+ const cutoff = Date.now() - FAL_JOB_TTL_MS;+ for (const [id, job] of jobs) {+ if (ACTIVE_STATUSES.has(job.status) || new Date(job.completedAt || job.createdAt).getTime() >= cutoff) continue;+ jobs.delete(id);+ const key = sceneKey(job.loomId, job.episodeId, job.nodeId);+ if (latestJobByScene.get(key) === id) latestJobByScene.delete(key);+ }+};++const setJobProgress = (job, statusMsg, progress) => {+ job.status = 'running';+ job.statusMsg = statusMsg;+ job.progress = progress;+};++const falAspectRatio = (requested) => {+ if (FAL_ASPECT_RATIOS.has(requested)) return requested;+ // fal's free tool has no 4:3 option. Preserve landscape orientation rather+ // than silently rotating or square-cropping a classic FableLoom frame.+ return '16:9';+};++const cdpEndpoint = async () => {+ let health = await getHealthStatus();+ if (!health.connected) health = await launchBrowser();+ if (!health.connected) {+ throw new ServerError('PortOS Browser is unavailable. Start it in Settings > Browser, then retry.', {+ status: 503,+ code: 'PORTOS_BROWSER_UNAVAILABLE',+ });+ }+ const host = health.cdpHost === '0.0.0.0' || health.cdpHost === '::'+ ? '127.0.0.1'+ : health.cdpHost;+ const endpointHost = host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;+ return `http://${endpointHost}:${health.cdpPort}`;+};++const visibleFalFailure = async (page) => {+ const text = await page.locator('[role="alert"]:visible, .text-error:visible').allInnerTexts().catch(() => []);+ const message = text.map((item) => item.trim()).find(Boolean) || '';+ const bodyText = await page.locator('body').innerText().catch(() => '');+ const combined = `${message}\n${bodyText}`;+ if (/captcha|verify (?:that )?you are human|human verification/i.test(combined)) {+ return 'fal.ai needs human verification in the PortOS Browser. Complete it there, then retry.';+ }+ if (/daily limit|free (?:video )?limit|quota|too many requests/i.test(combined)) {+ return 'fal.ai reports that the free video allowance is exhausted. Retry when the allowance resets.';+ }+ if (/sign in (?:to|with)|log in (?:to|with)/i.test(message)) {+ return 'fal.ai needs a signed-in session. Sign in through the PortOS Browser, then retry.';+ }+ return /error|fail(?:ed|ure)?|unable|invalid|unsupported|try again/i.test(message)+ ? `fal.ai could not generate the video: ${message.slice(0, 240)}`+ : null;+};++const safeFailureMessage = (error) => {+ if (error instanceof ServerError) return error.message;+ if (error?.name === 'TimeoutError') {+ return 'fal.ai did not expose the expected controls in the PortOS Browser. Inspect the tab, then retry.';+ }+ return 'fal.ai browser automation failed. Inspect the PortOS Browser tab, then retry.';+};++const readVideoSource = (resultVideo) => resultVideo+ .evaluate((video) => video.currentSrc || video.src || '')+ .catch(() => '');++const waitForFalResult = async (page, resultVideo, previousSourceUrl) => {+ const deadline = Date.now() + FAL_RENDER_TIMEOUT_MS;+ while (Date.now() < deadline) {+ const remaining = deadline - Date.now();+ const visible = await resultVideo.waitFor({+ state: 'visible',+ timeout: Math.min(FAL_RESULT_POLL_MS, remaining),+ }).then(() => true).catch(() => false);+ if (visible) {+ const sourceUrl = await readVideoSource(resultVideo);+ if (sourceUrl && sourceUrl !== previousSourceUrl) return sourceUrl;+ }++ // fal.ai can reject a request immediately (quota, auth, or CAPTCHA). Check+ // between short visibility waits so the scene reports that outcome now,+ // rather than looking busy until the full render timeout expires.+ const failure = await visibleFalFailure(page);+ if (failure) {+ throw new ServerError(failure, { status: 502, code: 'FAL_VIDEO_GENERATION_FAILED' });+ }+ }+ throw new ServerError(+ 'fal.ai did not finish the video before the 20-minute timeout. Inspect the PortOS Browser tab, then retry.',+ { status: 504, code: 'FAL_VIDEO_TIMEOUT' },+ );+};++const readFalVideo = async (context, sourceUrl) => {+ if (!/^https?:\/\//i.test(sourceUrl)) {+ throw new ServerError('fal.ai finished, but did not expose a downloadable video URL.', {+ status: 502,+ code: 'FAL_VIDEO_DOWNLOAD_FAILED',+ });+ }++ // fal.ai's own Download action fetches this result URL before creating its+ // anchor. Fetch through Playwright's browser-context request client instead:+ // it shares the persistent profile's cookies and returns the bytes directly+ // to PortOS even when an attached default CDP context does not emit download+ // events for browser-managed anchor downloads.+ const response = await context.request.get(sourceUrl, {+ failOnStatusCode: false,+ timeout: FAL_CONTROL_TIMEOUT_MS,+ });+ if (!response.ok()) {+ await response.dispose();+ throw new ServerError(`fal.ai video download failed with status ${response.status()}.`, {+ status: 502,+ code: 'FAL_VIDEO_DOWNLOAD_FAILED',+ });+ }+ const declaredSize = Number(response.headers()['content-length']);+ if (Number.isFinite(declaredSize) && declaredSize > MAX_GALLERY_VIDEO_UPLOAD_BYTES) {+ await response.dispose();+ throw new ServerError('fal.ai returned a video that is too large for the PortOS media gallery.', {+ status: 400,+ code: 'FILE_TOO_LARGE',+ });+ }+ const buffer = await response.body().finally(() => response.dispose().catch(() => {}));+ if (buffer.length > MAX_GALLERY_VIDEO_UPLOAD_BYTES) {+ throw new ServerError('fal.ai returned a video that is too large for the PortOS media gallery.', {+ status: 400,+ code: 'FILE_TOO_LARGE',+ });+ }+ return buffer;+};++const executeJob = async (job) => {+ let browser = null;+ try {+ job.startedAt = new Date().toISOString();+ setJobProgress(job, 'Opening the PortOS Browser…', 0.05);++ const latestAtStart = await getLoom(job.loomId);+ const { node: sceneAtStart } = findScene(latestAtStart, job.episodeId, job.nodeId);+ if (!sceneAtStart || sceneAtStart.image !== job.imageFilename) {+ throw new ServerError('The scene image changed before fal.ai started. Retry with the current image.', {+ status: 409,+ code: 'FAL_SCENE_IMAGE_CHANGED',+ });+ }+ const imagePath = resolveGalleryImage(job.imageFilename);+ if (!imagePath) {+ throw new ServerError('The scene image is no longer available. Generate or restore it, then retry.', {+ status: 409,+ code: 'FAL_SCENE_IMAGE_UNAVAILABLE',+ });+ }++ browser = await chromium.connectOverCDP(await cdpEndpoint(), {+ isLocal: true,+ noDefaults: true,+ timeout: 30_000,+ });+ const context = browser.contexts()[0];+ if (!context) {+ throw new ServerError('PortOS Browser has no usable profile context.', {+ status: 503,+ code: 'PORTOS_BROWSER_UNAVAILABLE',+ });+ }+ const page = context.pages().find((candidate) => candidate.url().includes('/tools/minimax-h3-max'))+ || await context.newPage();+ await page.goto(FAL_H3_MAX_FREE_URL, { waitUntil: 'domcontentloaded', timeout: FAL_CONTROL_TIMEOUT_MS });++ const promptInput = page.locator('textarea[placeholder^="Describe the video you want"]').first();+ const imageInput = page.locator('input[type="file"][accept*="image"]').first();+ await promptInput.waitFor({ state: 'visible', timeout: FAL_CONTROL_TIMEOUT_MS });++ setJobProgress(job, 'Uploading the scene image to fal.ai…', 0.15);+ await imageInput.setInputFiles(imagePath, { timeout: FAL_CONTROL_TIMEOUT_MS });+ await promptInput.fill(job.prompt);+ await page.getByRole('button', { name: falAspectRatio(job.aspectRatio), exact: true }).click();+ await page.getByRole('button', { name: '5s', exact: true }).click();++ const generate = page.getByRole('button', { name: 'Generate', exact: true });+ await generate.waitFor({ state: 'visible', timeout: FAL_CONTROL_TIMEOUT_MS });+ const resultVideo = page.locator('video[src]').first();+ // A persistent fal.ai tab can still show the prior scene's completed+ // video. Snapshot it before submitting so that only a new result URL can+ // satisfy this job.+ const previousSourceUrl = await readVideoSource(resultVideo);+ await generate.click({ timeout: FAL_CONTROL_TIMEOUT_MS });++ setJobProgress(job, 'Generating the scene video on fal.ai…', 0.3);+ const sourceUrl = await waitForFalResult(page, resultVideo, previousSourceUrl);++ setJobProgress(job, 'Downloading the fal.ai video…', 0.8);+ const videoBuffer = await readFalVideo(context, sourceUrl);++ setJobProgress(job, 'Saving the video to FableLoom…', 0.9);+ const galleryVideo = await saveUploadedGalleryVideoBuffer(+ videoBuffer,+ 'fal.ai H3 Max scene video.mp4',+ );+ job.videoHistoryId = galleryVideo.id;+ job.filename = galleryVideo.filename;++ const latestBeforeAttach = await getLoom(job.loomId);+ const { node: sceneBeforeAttach } = findScene(latestBeforeAttach, job.episodeId, job.nodeId);+ if (!sceneBeforeAttach || sceneBeforeAttach.image !== job.imageFilename) {+ throw new ServerError('The scene image changed while fal.ai was rendering. The video is saved in Media History but was not attached.', {+ status: 409,+ code: 'FAL_SCENE_IMAGE_CHANGED',+ });+ }+ const attached = await attachNodeVideo(job.loomId, job.episodeId, job.nodeId, {+ videoHistoryId: galleryVideo.id,+ });+ if (!attached) {+ throw new ServerError('The scene was removed while fal.ai was rendering. The video is saved in Media History but was not attached.', {+ status: 409,+ code: 'FAL_SCENE_UNAVAILABLE',+ });+ }++ job.status = 'completed';+ job.statusMsg = 'Scene video ready';+ job.progress = 1;+ job.completedAt = new Date().toISOString();+ console.log(`🎬 fal.ai scene video attached: ${galleryVideo.id}`);+ } catch (error) {+ const message = safeFailureMessage(error);+ job.status = 'failed';+ job.statusMsg = 'fal.ai video failed';+ job.error = message;+ job.completedAt = new Date().toISOString();+ console.error(`❌ fal.ai scene video failed: ${message}`);+ } finally {+ if (browser) await browser.close().catch(() => {});+ }+};++export async function startFalVideoAutomation(loomId, episodeId, nodeId, {+ prompt,+ aspectRatio = '16:9',+}) {+ pruneJobs();+ const key = sceneKey(loomId, episodeId, nodeId);+ const prior = jobs.get(latestJobByScene.get(key));+ if (prior && ACTIVE_STATUSES.has(prior.status)) return publicJob(prior);++ const loom = await getLoom(loomId);+ const { node } = findScene(loom, episodeId, nodeId);+ if (!node) {+ throw new ServerError('Scene not found', { status: 404, code: 'NOT_FOUND' });+ }+ if (!node.image || !resolveGalleryImage(node.image)) {+ throw new ServerError('Generate a scene image before starting fal.ai video automation.', {+ status: 409,+ code: 'FAL_SCENE_IMAGE_REQUIRED',+ });+ }++ const job = {+ id: `fal-${randomUUID()}`,+ loomId,+ episodeId,+ nodeId,+ prompt,+ aspectRatio,+ imageFilename: node.image,+ status: 'queued',+ statusMsg: 'Waiting for the fal.ai browser…',+ progress: 0,+ createdAt: new Date().toISOString(),+ startedAt: null,+ completedAt: null,+ error: null,+ videoHistoryId: null,+ filename: null,+ };+ jobs.set(job.id, job);+ latestJobByScene.set(key, job.id);++ // The free tool exposes one form in one persistent browser profile. Keep+ // every user-requested scene job, but serialize them so a later click cannot+ // replace the prompt/image of an in-flight render.+ runTail = runTail.then(() => executeJob(job));+ return publicJob(job);+}++export function getFalVideoAutomation(loomId, episodeId, nodeId, jobId) {+ pruneJobs();+ const job = jobs.get(jobId);+ if (!job || job.loomId !== loomId || job.episodeId !== episodeId || job.nodeId !== nodeId) {+ throw new ServerError('fal.ai scene video job not found', { status: 404, code: 'NOT_FOUND' });+ }+ return publicJob(job);+}++export function _resetFalVideoAutomations() {+ jobs.clear();+ latestJobByScene.clear();+ runTail = Promise.resolve();+}diff --git a/server/services/fableLoom/falVideoAutomation.test.js b/server/services/fableLoom/falVideoAutomation.test.jsnew file mode 100644index 0000000000..056c1525a3--- /dev/null+++ b/server/services/fableLoom/falVideoAutomation.test.js@@ -0,0 +1,258 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ attachNodeVideo: vi.fn(),+ browserClose: vi.fn(),+ connectOverCDP: vi.fn(),+ getHealthStatus: vi.fn(),+ getLoom: vi.fn(),+ launchBrowser: vi.fn(),+ resolveGalleryImage: vi.fn(),+ saveUploadedGalleryVideoBuffer: vi.fn(),+}));++vi.mock('playwright-core', () => ({+ chromium: { connectOverCDP: (...args) => mocks.connectOverCDP(...args) },+}));+vi.mock('../browserService.js', () => ({+ getHealthStatus: (...args) => mocks.getHealthStatus(...args),+ launchBrowser: (...args) => mocks.launchBrowser(...args),+}));+vi.mock('../../lib/pathSafety.js', () => ({+ resolveGalleryImage: (...args) => mocks.resolveGalleryImage(...args),+}));+vi.mock('../videoUpload.js', () => ({+ MAX_GALLERY_VIDEO_UPLOAD_BYTES: 50 * 1024 * 1024,+ saveUploadedGalleryVideoBuffer: (...args) => mocks.saveUploadedGalleryVideoBuffer(...args),+}));+vi.mock('./records.js', () => ({+ attachNodeVideo: (...args) => mocks.attachNodeVideo(...args),+ getLoom: (...args) => mocks.getLoom(...args),+}));++import {+ _resetFalVideoAutomations,+ FAL_H3_MAX_FREE_URL,+ getFalVideoAutomation,+ startFalVideoAutomation,+} from './falVideoAutomation.js';++const loomWithImage = (image = 'scene.png') => ({+ id: 'loom-1',+ episodes: [{ id: 'ep-1', nodes: [{ id: 'node-1', image }] }],+});++const makeBrowser = ({+ resultError = null,+ errorTexts = [],+ previousVideoUrl = '',+ resultVideoUrl = 'https://v3.fal.media/files/example.mp4',+} = {}) => {+ const prompt = { waitFor: vi.fn(async () => {}), fill: vi.fn(async () => {}), first: vi.fn() };+ prompt.first.mockReturnValue(prompt);+ const image = { setInputFiles: vi.fn(async () => {}), first: vi.fn() };+ image.first.mockReturnValue(image);+ const video = {+ waitFor: resultError ? vi.fn(async () => { throw resultError; }) : vi.fn(async () => {}),+ evaluate: vi.fn()+ .mockResolvedValueOnce(previousVideoUrl)+ .mockResolvedValue(resultVideoUrl),+ first: vi.fn(),+ };+ video.first.mockReturnValue(video);+ const errorLocator = {+ allInnerTexts: vi.fn(async () => errorTexts),+ };+ const bodyLocator = { innerText: vi.fn(async () => errorTexts.join('\n')) };+ const controls = new Map(['16:9', '9:16', '1:1', '5s', 'Generate'].map((name) => [name, {+ click: vi.fn(async () => {}),+ waitFor: vi.fn(async () => {}),+ }]));+ const apiResponse = {+ body: vi.fn(async () => Buffer.from('example mp4 bytes')),+ dispose: vi.fn(async () => {}),+ headers: vi.fn(() => ({ 'content-length': '17' })),+ ok: vi.fn(() => true),+ status: vi.fn(() => 200),+ };+ const request = { get: vi.fn(async () => apiResponse) };+ const page = {+ getByRole: vi.fn((_role, { name }) => controls.get(name)),+ goto: vi.fn(async () => {}),+ locator: vi.fn((selector) => {+ if (selector.startsWith('textarea')) return prompt;+ if (selector.startsWith('input')) return image;+ if (selector === 'video[src]') return video;+ if (selector === 'body') return bodyLocator;+ return errorLocator;+ }),+ url: vi.fn(() => 'about:blank'),+ };+ const context = {+ newPage: vi.fn(async () => page),+ pages: vi.fn(() => []),+ request,+ };+ const browser = {+ close: (...args) => mocks.browserClose(...args),+ contexts: vi.fn(() => [context]),+ };+ mocks.connectOverCDP.mockResolvedValue(browser);+ return { apiResponse, browser, context, controls, image, page, prompt, request, video };+};++const waitForTerminalJob = async (job) => {+ let latest = null;+ await vi.waitFor(() => {+ latest = getFalVideoAutomation(job.loomId, job.episodeId, job.nodeId, job.id);+ expect(['completed', 'failed']).toContain(latest.status);+ });+ return latest;+};++beforeEach(() => {+ vi.clearAllMocks();+ _resetFalVideoAutomations();+ vi.spyOn(console, 'log').mockImplementation(() => {});+ vi.spyOn(console, 'error').mockImplementation(() => {});+ mocks.browserClose.mockResolvedValue(undefined);+ mocks.getHealthStatus.mockResolvedValue({ connected: true, cdpHost: '127.0.0.1', cdpPort: 5556 });+ mocks.getLoom.mockResolvedValue(loomWithImage());+ mocks.resolveGalleryImage.mockReturnValue('/example/images/scene.png');+ mocks.saveUploadedGalleryVideoBuffer.mockResolvedValue({+ id: 'upload-ab12cd34', filename: 'upload-ab12cd34.mp4',+ });+ mocks.attachNodeVideo.mockResolvedValue({ id: 'node-1', videoHistoryId: 'upload-ab12cd34' });+});++describe('FableLoom fal.ai browser automation', () => {+ it('uploads the scene still and full prompt, downloads the result, and attaches the gallery video', async () => {+ const { apiResponse, controls, image, page, prompt, request } = makeBrowser();+ const queued = await startFalVideoAutomation('loom-1', 'ep-1', 'node-1', {+ prompt: 'One uninterrupted reveal.\n\nAvoid: cuts, logos',+ aspectRatio: '9:16',+ });++ expect(queued).toMatchObject({ source: 'fal-browser', status: 'queued' });+ expect(queued).not.toHaveProperty('prompt');+ const completed = await waitForTerminalJob(queued);++ expect(completed).toMatchObject({+ status: 'completed', videoHistoryId: 'upload-ab12cd34', filename: 'upload-ab12cd34.mp4',+ });+ expect(mocks.connectOverCDP).toHaveBeenCalledWith('http://127.0.0.1:5556', {+ isLocal: true, noDefaults: true, timeout: 30_000,+ });+ expect(page.goto).toHaveBeenCalledWith(FAL_H3_MAX_FREE_URL, expect.any(Object));+ expect(image.setInputFiles).toHaveBeenCalledWith('/example/images/scene.png', expect.any(Object));+ expect(prompt.fill).toHaveBeenCalledWith('One uninterrupted reveal.\n\nAvoid: cuts, logos');+ expect(controls.get('9:16').click).toHaveBeenCalledTimes(1);+ expect(controls.get('5s').click).toHaveBeenCalledTimes(1);+ expect(controls.get('Generate').click).toHaveBeenCalledTimes(1);+ expect(request.get).toHaveBeenCalledWith('https://v3.fal.media/files/example.mp4', {+ failOnStatusCode: false,+ timeout: 120_000,+ });+ expect(apiResponse.dispose).toHaveBeenCalledTimes(1);+ expect(mocks.saveUploadedGalleryVideoBuffer).toHaveBeenCalledWith(+ Buffer.from('example mp4 bytes'),+ 'fal.ai H3 Max scene video.mp4',+ );+ expect(mocks.attachNodeVideo).toHaveBeenCalledWith('loom-1', 'ep-1', 'node-1', {+ videoHistoryId: 'upload-ab12cd34',+ });+ expect(mocks.browserClose).toHaveBeenCalledTimes(1);+ });++ it('coalesces repeated clicks for one scene instead of spending the free allowance twice', async () => {+ makeBrowser();+ const first = await startFalVideoAutomation('loom-1', 'ep-1', 'node-1', {+ prompt: 'The example door opens.', aspectRatio: '16:9',+ });+ const second = await startFalVideoAutomation('loom-1', 'ep-1', 'node-1', {+ prompt: 'A duplicate click.', aspectRatio: '16:9',+ });++ expect(second.id).toBe(first.id);+ await waitForTerminalJob(first);+ expect(mocks.connectOverCDP).toHaveBeenCalledTimes(1);+ });++ it('waits for a new result instead of downloading a video left in the persistent tab', async () => {+ const { request, video } = makeBrowser({+ previousVideoUrl: 'https://v3.fal.media/files/prior-scene.mp4',+ resultVideoUrl: 'https://v3.fal.media/files/current-scene.mp4',+ });+ const queued = await startFalVideoAutomation('loom-1', 'ep-1', 'node-1', {+ prompt: 'The current scene begins.', aspectRatio: '16:9',+ });++ await expect(waitForTerminalJob(queued)).resolves.toMatchObject({ status: 'completed' });+ expect(video.evaluate).toHaveBeenCalledTimes(2);+ expect(request.get).toHaveBeenCalledWith(+ 'https://v3.fal.media/files/current-scene.mp4',+ expect.any(Object),+ );+ });++ it('requires a current storyboard image before it consumes fal.ai', async () => {+ mocks.getLoom.mockResolvedValueOnce(loomWithImage(null));++ await expect(startFalVideoAutomation('loom-1', 'ep-1', 'node-1', {+ prompt: 'A text-only request.', aspectRatio: '16:9',+ })).rejects.toMatchObject({ code: 'FAL_SCENE_IMAGE_REQUIRED' });+ expect(mocks.connectOverCDP).not.toHaveBeenCalled();+ });++ it('keeps a finished clip in Media History instead of attaching it to a newly changed still', async () => {+ makeBrowser();+ mocks.getLoom+ .mockResolvedValueOnce(loomWithImage('scene.png'))+ .mockResolvedValueOnce(loomWithImage('scene.png'))+ .mockResolvedValueOnce(loomWithImage('replacement.png'));+ const queued = await startFalVideoAutomation('loom-1', 'ep-1', 'node-1', {+ prompt: 'The example door opens.', aspectRatio: '16:9',+ });++ const failed = await waitForTerminalJob(queued);+ expect(failed).toMatchObject({+ status: 'failed',+ videoHistoryId: 'upload-ab12cd34',+ error: expect.stringContaining('saved in Media History but was not attached'),+ });+ expect(mocks.attachNodeVideo).not.toHaveBeenCalled();+ });++ it('surfaces a free-allowance failure without saving or attaching a video', async () => {+ makeBrowser({+ resultError: new Error('result did not appear'),+ errorTexts: ['Daily free limit reached'],+ });+ const queued = await startFalVideoAutomation('loom-1', 'ep-1', 'node-1', {+ prompt: 'The example door opens.', aspectRatio: '16:9',+ });++ const failed = await waitForTerminalJob(queued);+ expect(failed).toMatchObject({+ status: 'failed',+ error: expect.stringContaining('free video allowance is exhausted'),+ });+ expect(mocks.saveUploadedGalleryVideoBuffer).not.toHaveBeenCalled();+ expect(mocks.attachNodeVideo).not.toHaveBeenCalled();+ });++ it('rejects an oversized result before buffering it into the media gallery', async () => {+ const { apiResponse } = makeBrowser();+ apiResponse.headers.mockReturnValue({ 'content-length': String((50 * 1024 * 1024) + 1) });+ const queued = await startFalVideoAutomation('loom-1', 'ep-1', 'node-1', {+ prompt: 'The example door opens.', aspectRatio: '16:9',+ });++ const failed = await waitForTerminalJob(queued);+ expect(failed).toMatchObject({ status: 'failed', error: expect.stringContaining('too large') });+ expect(apiResponse.body).not.toHaveBeenCalled();+ expect(apiResponse.dispose).toHaveBeenCalledTimes(1);+ expect(mocks.saveUploadedGalleryVideoBuffer).not.toHaveBeenCalled();+ expect(mocks.attachNodeVideo).not.toHaveBeenCalled();+ });+});diff --git a/server/services/fableLoom/index.js b/server/services/fableLoom/index.jsindex a3a8363d30..4abebbdac6 100644--- a/server/services/fableLoom/index.js+++ b/server/services/fableLoom/index.js@@ -111,3 +111,9 @@ export {resumeEpisodeProductionBatch,startEpisodeProductionBatch,} from './production.js';+export {+ FAL_H3_MAX_FREE_URL,+ _resetFalVideoAutomations,+ getFalVideoAutomation,+ startFalVideoAutomation,+} from './falVideoAutomation.js';diff --git a/server/services/videoUpload.js b/server/services/videoUpload.jsindex 7acf39e6bb..d2509c68b6 100644--- a/server/services/videoUpload.js+++ b/server/services/videoUpload.js@@ -67,8 +67,10 @@ export function buildUploadHistoryEntry({ id, filename, thumbnail, durationSec,* entry (`{ id, filename, thumbnail, source: 'upload', … }`); the served file* is `/data/videos/<filename>`.*/-export async function saveUploadedGalleryVideo(base64Data, originalName = '') {- const buffer = Buffer.from(base64Data, 'base64');+export async function saveUploadedGalleryVideoBuffer(buffer, originalName = '') {+ if (!Buffer.isBuffer(buffer)) {+ throw new ServerError('Invalid video upload', { status: 400, code: 'VALIDATION_ERROR' });+ }if (buffer.length === 0) {throw new ServerError('Empty video upload', { status: 400, code: 'VALIDATION_ERROR' });}@@ -109,3 +111,7 @@ export async function saveUploadedGalleryVideo(base64Data, originalName = '') {throw err;}}++export async function saveUploadedGalleryVideo(base64Data, originalName = '') {+ return saveUploadedGalleryVideoBuffer(Buffer.from(base64Data, 'base64'), originalName);+}diff --git a/server/services/videoUpload.test.js b/server/services/videoUpload.test.jsindex be92fae047..272b80c274 100644--- a/server/services/videoUpload.test.js+++ b/server/services/videoUpload.test.js@@ -11,6 +11,7 @@ import {detectVideoContainer,buildUploadHistoryEntry,saveUploadedGalleryVideo,+ saveUploadedGalleryVideoBuffer,MAX_GALLERY_VIDEO_UPLOAD_BYTES,} from './videoUpload.js';@@ -59,6 +60,9 @@ describe('buildUploadHistoryEntry', () => {});describe('saveUploadedGalleryVideo validation', () => {+ it('requires a byte buffer for internal browser downloads', async () => {+ await expect(saveUploadedGalleryVideoBuffer('not-a-buffer')).rejects.toThrow(/invalid/i);+ });it('rejects an empty upload before touching disk', async () => {await expect(saveUploadedGalleryVideo('')).rejects.toThrow(/empty/i);});