Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: stream FableLoom fal video progress without browser polling (#8545)

[._.]/ Adam Eivy854e75c71ec9
diff --git a/client/src/components/fableloom/LoomMediaJobWatchers.jsx b/client/src/components/fableloom/LoomMediaJobWatchers.jsx
index a2f47292f4..aa51d4eae6 100644
--- a/client/src/components/fableloom/LoomMediaJobWatchers.jsx
+++ b/client/src/components/fableloom/LoomMediaJobWatchers.jsx
@@ -10,9 +10,8 @@
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;
+import socket from '../../services/socket';
+import { subscribeVisibility } from '../../hooks/useVisibilityEvent';
function LoomMediaJobWatcher({ nodeId, kind, job, onUpdate, onTerminal }) {
const progress = useMediaJobProgress(job.jobId, { kind });
@@ -36,50 +35,60 @@ function LoomMediaJobWatcher({ nodeId, kind, job, onUpdate, onTerminal }) {
function LoomFalBrowserJobWatcher({ nodeId, kind, job, onUpdate, onTerminal }) {
const reportedTerminalRef = useRef(null);
+ const callbacks = useRef({ onUpdate, onTerminal });
+ callbacks.current = { onUpdate, onTerminal };
useEffect(() => {
let canceled = false;
- let timer = null;
- let failures = 0;
-
- const poll = () => {
+ let revision = 0;
+ const matches = (progress) => progress?.id === job.jobId
+ && progress.loomId === job.loomId && progress.episodeId === job.episodeId
+ && progress.nodeId === nodeId;
+ const apply = (progress) => {
+ if (canceled || !matches(progress) || reportedTerminalRef.current === job.jobId) return;
+ const terminal = progress.status === 'failed' || progress.status === 'completed';
+ // Latch before callbacks: parent updates may unmount this watcher.
+ if (terminal) reportedTerminalRef.current = job.jobId;
+ callbacks.current.onUpdate(nodeId, kind, job.jobId, progress);
+ if (terminal) callbacks.current.onTerminal(nodeId, kind, job.jobId, progress);
+ };
+ const read = () => {
+ if (canceled || reportedTerminalRef.current === job.jobId) return;
+ const started = ++revision;
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);
+ if (started === revision) apply(progress);
})
.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);
+ // A failed status read is not a failed render. Keep listening and
+ // retry at the next reconnect or tab show, without a polling timer.
});
};
+ const onChange = (progress) => {
+ if (!matches(progress)) return;
+ revision += 1; // An older HTTP snapshot must not overwrite this event.
+ apply(progress);
+ };
+ const onConnect = () => {
+ if (document.visibilityState !== 'hidden') read();
+ };
+ let lastVisibility = document.visibilityState;
+ const unsubscribeVisibility = subscribeVisibility((state) => {
+ const changed = state !== lastVisibility;
+ lastVisibility = state;
+ if (changed && state === 'visible') read();
+ });
- poll();
+ socket.on('fableloom:fal-video:changed', onChange);
+ socket.on('connect', onConnect);
+ read();
return () => {
canceled = true;
- clearTimeout(timer);
+ unsubscribeVisibility();
+ socket.off('fableloom:fal-video:changed', onChange);
+ socket.off('connect', onConnect);
};
- }, [job.episodeId, job.jobId, job.loomId, kind, nodeId, onTerminal, onUpdate]);
+ }, [job.episodeId, job.jobId, job.loomId, kind, nodeId]);
return null;
}
diff --git a/client/src/components/fableloom/LoomMediaJobWatchers.test.jsx b/client/src/components/fableloom/LoomMediaJobWatchers.test.jsx
index c422a66fbe..2470e1624a 100644
--- a/client/src/components/fableloom/LoomMediaJobWatchers.test.jsx
+++ b/client/src/components/fableloom/LoomMediaJobWatchers.test.jsx
@@ -1,5 +1,5 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { render, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, cleanup, render, waitFor } from '@testing-library/react';
const hookState = vi.hoisted(() => ({
value: { status: 'queued', progress: 0, filename: null, error: null },
@@ -10,11 +10,48 @@ vi.mock('../../services/api', () => ({
getLoomFalVideo: (...args) => apiMocks.getLoomFalVideo(...args),
}));
+const socketMock = vi.hoisted(() => {
+ const listeners = new Map();
+ return {
+ on: vi.fn((name, fn) => {
+ if (!listeners.has(name)) listeners.set(name, new Set());
+ listeners.get(name).add(fn);
+ }),
+ off: vi.fn((name, fn) => listeners.get(name)?.delete(fn)),
+ receive: (name, data) => listeners.get(name)?.forEach(fn => fn(data)),
+ };
+});
+vi.mock('../../services/socket', () => ({ default: socketMock }));
+
+const snapshot = (patch = {}) => ({
+ id: 'fal-job-1', source: 'fal-browser', loomId: 'loom-1', episodeId: 'ep-1',
+ nodeId: 'node-1', status: 'running', progress: 0.3, ...patch,
+});
+const propsFor = (jobId = 'fal-job-1') => ({
+ jobs: { 'node-1': { video: {
+ jobId, source: 'fal-browser', loomId: 'loom-1', episodeId: 'ep-1', status: 'queued',
+ } } },
+ onUpdate: vi.fn(),
+ onTerminal: vi.fn(),
+});
+const push = async (data) => act(async () => socketMock.receive('fableloom:fal-video:changed', data));
+const visibility = async (state) => {
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: state });
+ await act(async () => document.dispatchEvent(new Event('visibilitychange')));
+};
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
import LoomMediaJobWatchers from './LoomMediaJobWatchers';
describe('LoomMediaJobWatchers', () => {
beforeEach(() => {
vi.clearAllMocks();
+ apiMocks.getLoomFalVideo.mockReset().mockResolvedValue(snapshot());
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });
hookState.value = { status: 'queued', progress: 0, filename: null, error: null };
});
@@ -42,48 +79,101 @@ describe('LoomMediaJobWatchers', () => {
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',
- });
+ it('streams progress to two tabs and forwards durable completion once without polling', async () => {
+ vi.useFakeTimers();
+ const first = propsFor();
+ const second = propsFor();
+ render(<><LoomMediaJobWatchers {...first} /><LoomMediaJobWatchers {...second} /></>);
+ await act(async () => {});
+ expect(apiMocks.getLoomFalVideo).toHaveBeenCalledTimes(2);
+ await push(snapshot({ progress: 0.8, statusMsg: 'Downloading' }));
+ for (const props of [first, second]) {
+ expect(props.onUpdate).toHaveBeenLastCalledWith('node-1', 'video', 'fal-job-1',
+ expect.objectContaining({ progress: 0.8, statusMsg: 'Downloading' }));
+ }
+ await act(async () => vi.advanceTimersByTimeAsync(60_000));
+ expect(apiMocks.getLoomFalVideo).toHaveBeenCalledTimes(2);
+ const completed = snapshot({ status: 'completed', progress: 1, videoHistoryId: 'upload-ab12cd34' });
+ await push(completed);
+ await push(completed);
+ await push(snapshot());
+ for (const props of [first, second]) {
+ expect(props.onTerminal).toHaveBeenCalledExactlyOnceWith('node-1', 'video', 'fal-job-1', completed);
+ expect(props.onUpdate).toHaveBeenLastCalledWith('node-1', 'video', 'fal-job-1', completed);
+ }
+ await act(async () => socketMock.receive('connect'));
+ expect(apiMocks.getLoomFalVideo).toHaveBeenCalledTimes(2);
+ });
- 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}
- />,
- );
+ it('hydrates an already completed job and does not reread for callback changes', async () => {
+ apiMocks.getLoomFalVideo.mockResolvedValue(snapshot({ status: 'completed', videoHistoryId: 'upload-ab12cd34' }));
+ const props = propsFor();
+ const { rerender } = render(<LoomMediaJobWatchers {...props} />);
+ await waitFor(() => expect(props.onTerminal).toHaveBeenCalledTimes(1));
+ rerender(<LoomMediaJobWatchers {...props} onUpdate={vi.fn()} />);
+ expect(apiMocks.getLoomFalVideo).toHaveBeenCalledExactlyOnceWith(
+ 'loom-1', 'ep-1', 'node-1', 'fal-job-1', { silent: true });
+ });
- 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 },
- );
+ it('reports failure once and ignores other jobs or scenes', async () => {
+ const props = propsFor();
+ render(<LoomMediaJobWatchers {...props} />);
+ await act(async () => {});
+ props.onUpdate.mockClear();
+ for (const patch of [{ id: 'old-job' }, { loomId: 'other' }, { episodeId: 'other' }, { nodeId: 'other' }]) {
+ await push(snapshot({ ...patch, status: 'failed' }));
+ }
+ expect(props.onUpdate).not.toHaveBeenCalled();
+ const failed = snapshot({ status: 'failed', error: 'Free allowance exhausted' });
+ await push(failed);
+ await push(failed);
+ expect(props.onTerminal).toHaveBeenCalledExactlyOnceWith('node-1', 'video', 'fal-job-1', failed);
+ });
- 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);
+ it('recovers on reconnect and tab reshow after a failed snapshot without inventing failure', async () => {
+ apiMocks.getLoomFalVideo.mockRejectedValueOnce(new Error('offline'));
+ const props = propsFor();
+ render(<LoomMediaJobWatchers {...props} />);
+ await act(async () => {});
+ expect(props.onTerminal).not.toHaveBeenCalled();
+ await act(async () => socketMock.receive('connect'));
+ expect(apiMocks.getLoomFalVideo).toHaveBeenCalledTimes(2);
+ await visibility('hidden');
+ await act(async () => socketMock.receive('connect'));
+ expect(apiMocks.getLoomFalVideo).toHaveBeenCalledTimes(2);
+ apiMocks.getLoomFalVideo.mockResolvedValue(snapshot({ status: 'completed', videoHistoryId: 'upload-ab12cd34' }));
+ await visibility('visible');
+ await visibility('visible');
+ expect(apiMocks.getLoomFalVideo).toHaveBeenCalledTimes(3);
+ expect(props.onTerminal).toHaveBeenCalledTimes(1);
+ });
+
+ it('drops HTTP responses overtaken by events, newer reads, a new job or unmount', async () => {
+ const pending = [];
+ apiMocks.getLoomFalVideo.mockImplementation(() => new Promise(resolve => pending.push(resolve)));
+ const props = propsFor();
+ const { rerender, unmount } = render(<LoomMediaJobWatchers {...props} />);
+ await push(snapshot({ progress: 0.8 }));
+ await act(async () => pending[0](snapshot({ progress: 0.1 })));
+ expect(props.onUpdate).toHaveBeenLastCalledWith('node-1', 'video', 'fal-job-1',
+ expect.objectContaining({ progress: 0.8 }));
+ await act(async () => socketMock.receive('connect'));
+ await visibility('hidden');
+ await visibility('visible');
+ await act(async () => pending[2](snapshot({ progress: 0.9 })));
+ await act(async () => pending[1](snapshot({ progress: 0.2 })));
+ expect(props.onUpdate).toHaveBeenLastCalledWith('node-1', 'video', 'fal-job-1',
+ expect.objectContaining({ progress: 0.9 }));
+ await act(async () => socketMock.receive('connect'));
+ const next = propsFor('fal-job-2');
+ rerender(<LoomMediaJobWatchers {...next} />);
+ await act(async () => pending[3](snapshot({ status: 'completed' })));
+ await push(snapshot({ status: 'completed' }));
+ expect(props.onTerminal).not.toHaveBeenCalled();
+ expect(next.onTerminal).not.toHaveBeenCalled();
+ unmount();
+ await act(async () => pending[4](snapshot({ id: 'fal-job-2', status: 'failed' })));
+ await push(snapshot({ id: 'fal-job-2', status: 'failed' }));
+ expect(next.onUpdate).not.toHaveBeenCalled();
});
});
diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.js
index 81cf8b6de3..3accf52756 100644
--- a/server/lib/socketEventContracts.js
+++ b/server/lib/socketEventContracts.js
@@ -31,6 +31,32 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({
'app:update': input(appUpdateSchema, 'Run the update lifecycle for one registered app.'),
'detect:start': input(detectStartSchema, 'Start streamed application detection.'),
'error:recover': input(errorRecoverSchema, 'Request a bounded recovery task for a reported error.'),
+ 'fableloom:fal-video:changed': Object.freeze({
+ direction: 'server-to-client',
+ summary: 'Public browser video job snapshot on queue, progress and terminal transitions; completion follows durable gallery and scene attachment.',
+ payloadSchema: {
+ type: 'object',
+ required: ['id', 'source', 'loomId', 'episodeId', 'nodeId', 'status', 'statusMsg', 'progress',
+ 'createdAt', 'startedAt', 'completedAt', 'error', 'videoHistoryId', 'filename'],
+ properties: {
+ id: { type: 'string' },
+ source: { type: 'string', enum: ['fal-browser'] },
+ loomId: { type: 'string' },
+ episodeId: { type: 'string' },
+ nodeId: { type: 'string' },
+ status: { type: 'string', enum: ['queued', 'running', 'completed', 'failed'] },
+ statusMsg: { type: 'string' },
+ progress: { type: 'number', minimum: 0, maximum: 1 },
+ createdAt: { type: 'string' },
+ startedAt: { type: ['string', 'null'] },
+ completedAt: { type: ['string', 'null'] },
+ error: { type: ['string', 'null'] },
+ videoHistoryId: { type: ['string', 'null'] },
+ filename: { type: ['string', 'null'] },
+ },
+ additionalProperties: false,
+ },
+ }),
'iterm:attach': input(itermSessionRefSchema, 'Start viewing one live iTerm2 session.'),
'iterm:detach': input(itermSessionRefSchema, 'Stop viewing one live iTerm2 session.'),
'iterm:input': input(itermInputSchema, 'Type bytes into one live iTerm2 session.'),
diff --git a/server/routes/fableLoom.js b/server/routes/fableLoom.js
index 203e558bb0..9488e3e0e1 100644
--- a/server/routes/fableLoom.js
+++ b/server/routes/fableLoom.js
@@ -275,7 +275,7 @@ router.post('/:id/episodes/:episodeId/nodes/:nodeId/fal-video', asyncHandler(asy
req.params.id,
req.params.episodeId,
req.params.nodeId,
- input,
+ { ...input, io: req.app.get('io') },
));
}));
diff --git a/server/routes/fableLoom.test.js b/server/routes/fableLoom.test.js
index db7a1d1d49..92a971b95d 100644
--- a/server/routes/fableLoom.test.js
+++ b/server/routes/fableLoom.test.js
@@ -286,14 +286,17 @@ describe('FableLoom routes', () => {
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())
+ const app = makeApp();
+ const io = { emit: vi.fn() };
+ app.set('io', io);
+ const created = await request(app)
.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',
+ prompt: 'One continuous example shot.', aspectRatio: '9:16', io,
});
fableLoom.getFalVideoAutomation.mockReturnValueOnce({ ...job, status: 'running' });
diff --git a/server/services/fableLoom/falVideoAutomation.js b/server/services/fableLoom/falVideoAutomation.js
index ab6e54e6e8..c7f48731c7 100644
--- a/server/services/fableLoom/falVideoAutomation.js
+++ b/server/services/fableLoom/falVideoAutomation.js
@@ -62,6 +62,16 @@ const publicJob = (job) => ({
filename: job.filename,
});
+// Socket delivery must never turn a durably attached video into a failed job
+// or break the serialized browser queue. Disconnected clients recover by GET.
+const emitJob = (job) => {
+ try {
+ job.io?.emit('fableloom:fal-video:changed', publicJob(job));
+ } catch {
+ console.error('❌ Could not broadcast fal.ai browser job status');
+ }
+};
+
const pruneJobs = () => {
const cutoff = Date.now() - FAL_JOB_TTL_MS;
for (const [id, job] of jobs) {
@@ -76,6 +86,7 @@ const setJobProgress = (job, statusMsg, progress) => {
job.status = 'running';
job.statusMsg = statusMsg;
job.progress = progress;
+ emitJob(job);
};
const falAspectRatio = (requested) => {
@@ -395,6 +406,7 @@ const executeJob = async (job) => {
job.statusMsg = 'Scene video ready';
job.progress = 1;
job.completedAt = new Date().toISOString();
+ emitJob(job);
console.log(`🎬 fal.ai scene video attached: ${galleryVideo.id}`);
} catch (error) {
const message = safeFailureMessage(error);
@@ -404,6 +416,7 @@ const executeJob = async (job) => {
job.statusMsg = 'fal.ai video failed';
job.error = message;
job.completedAt = new Date().toISOString();
+ emitJob(job);
console.error(`❌ fal.ai scene video failed: ${message} (${diagnostic} during ${failedStage})`);
} finally {
// Keep a real fal.ai page open for login/CAPTCHA inspection, but do not
@@ -425,12 +438,14 @@ const executeJob = async (job) => {
* @param {object} options - Generation options.
* @param {string} options.prompt - Authored video generation prompt and camera direction.
* @param {'16:9'|'9:16'|'1:1'} [options.aspectRatio='16:9'] - Target video aspect ratio.
+ * @param {object} [options.io] - Private application Socket.IO emitter.
* @returns {Promise<object>} Public job status descriptor.
* @throws {ServerError} When scene/image is missing or browser is unavailable.
*/
export async function startFalVideoAutomation(loomId, episodeId, nodeId, {
prompt,
aspectRatio = '16:9',
+ io = null,
}) {
pruneJobs();
const key = sceneKey(loomId, episodeId, nodeId);
@@ -458,6 +473,7 @@ export async function startFalVideoAutomation(loomId, episodeId, nodeId, {
const job = {
id: `fal-${randomUUID()}`,
+ io,
loomId,
episodeId,
nodeId,
@@ -476,6 +492,7 @@ export async function startFalVideoAutomation(loomId, episodeId, nodeId, {
};
jobs.set(job.id, job);
latestJobByScene.set(key, job.id);
+ emitJob(job);
// The free tool exposes one form in one persistent browser profile. Keep
// every user-requested scene job, but serialize them so a later click
diff --git a/server/services/fableLoom/falVideoAutomation.test.js b/server/services/fableLoom/falVideoAutomation.test.js
index a4206d5a3a..1d2051245e 100644
--- a/server/services/fableLoom/falVideoAutomation.test.js
+++ b/server/services/fableLoom/falVideoAutomation.test.js
@@ -34,6 +34,8 @@ vi.mock('./records.js', () => ({
getLoom: (...args) => mocks.getLoom(...args),
}));
+import { SOCKET_EVENT_CONTRACTS } from '../../lib/socketEventContracts.js';
+
import {
_resetFalVideoAutomations,
FAL_H3_MAX_FREE_URL,
@@ -190,6 +192,62 @@ describe('FableLoom fal.ai browser automation', () => {
expect(mocks.browserClose).toHaveBeenCalledTimes(1);
});
+ it('emits only public snapshots and completes once after both durable writes settle', async () => {
+ makeBrowser();
+ const io = { emit: vi.fn() };
+ let save, attach;
+ mocks.saveUploadedGalleryVideoBuffer.mockImplementationOnce(() => new Promise(resolve => { save = resolve; }));
+ mocks.attachNodeVideo.mockImplementationOnce(() => new Promise(resolve => { attach = resolve; }));
+ const queued = await startFalVideoAutomation('loom-1', 'ep-1', 'node-1', { prompt: 'Example direction', io });
+ const frames = () => io.emit.mock.calls.map(([event, data]) => {
+ expect(event).toBe('fableloom:fal-video:changed');
+ return data;
+ });
+ await vi.waitFor(() => expect(save).toBeTypeOf('function'));
+ expect(frames()[0]).toEqual(queued);
+ expect(frames().at(-1)).toMatchObject({ status: 'running', progress: 0.9 });
+ expect(frames().some(frame => frame.status === 'completed')).toBe(false);
+ save({ id: 'upload-ab12cd34', filename: 'upload-ab12cd34.mp4' });
+ await vi.waitFor(() => expect(attach).toBeTypeOf('function'));
+ expect(frames().some(frame => frame.status === 'completed')).toBe(false);
+ attach({ id: 'node-1', videoHistoryId: 'upload-ab12cd34' });
+ const completed = await waitForTerminalJob(queued);
+ expect(frames().filter(frame => frame.status === 'completed')).toEqual([completed]);
+ expect(mocks.saveUploadedGalleryVideoBuffer).toHaveBeenCalledTimes(1);
+ expect(mocks.attachNodeVideo).toHaveBeenCalledTimes(1);
+ const contract = SOCKET_EVENT_CONTRACTS['fableloom:fal-video:changed'].payloadSchema;
+ for (const frame of frames()) {
+ expect(Object.keys(frame).sort()).toEqual([...contract.required].sort());
+ expect(frame).not.toHaveProperty('prompt');
+ expect(frame).not.toHaveProperty('imageFilename');
+ expect(frame).not.toHaveProperty('io');
+ }
+ });
+
+ it('emits one failure and no completion when durable attachment rejects', async () => {
+ makeBrowser();
+ const io = { emit: vi.fn() };
+ mocks.attachNodeVideo.mockRejectedValueOnce(new Error('Synthetic storage failure'));
+ const queued = await startFalVideoAutomation('loom-1', 'ep-1', 'node-1', { prompt: 'Example direction', io });
+ const failed = await waitForTerminalJob(queued);
+ const terminal = io.emit.mock.calls.map(([, data]) => data)
+ .filter(data => ['completed', 'failed'].includes(data.status));
+ expect(terminal).toEqual([failed]);
+ expect(failed.status).toBe('failed');
+ expect(mocks.attachNodeVideo).toHaveBeenCalledTimes(1);
+ });
+
+ it('preserves durable completion when socket delivery throws', async () => {
+ makeBrowser();
+ const io = { emit: vi.fn(() => { throw new Error('Synthetic socket failure'); }) };
+ const queued = await startFalVideoAutomation('loom-1', 'ep-1', 'node-1', { prompt: 'Example direction', io });
+ await expect(waitForTerminalJob(queued)).resolves.toMatchObject({
+ status: 'completed', videoHistoryId: 'upload-ab12cd34',
+ });
+ expect(mocks.attachNodeVideo).toHaveBeenCalledTimes(1);
+ expect(io.emit.mock.calls.filter(([, data]) => data.status === 'failed')).toHaveLength(0);
+ });
+
it('dismisses a privacy prompt that appears after controls load before filling the scene', async () => {
const { page, privacy, prompt, setPrivacyConsent } = makeBrowser();
privacy.waitFor.mockImplementationOnce(async ({ state, timeout }) => {