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: address review (claude): harden fal job lifecycle

Adam Eivy51f185ad1a32
diff --git a/client/src/components/fableloom/LoomCanvas.test.jsx b/client/src/components/fableloom/LoomCanvas.test.jsx
index 5f13cd484a..374f139949 100644
--- a/client/src/components/fableloom/LoomCanvas.test.jsx
+++ b/client/src/components/fableloom/LoomCanvas.test.jsx
@@ -127,6 +127,36 @@ describe('LoomCanvas', () => {
expect(screen.getAllByRole('button', { name: 'Generate image' })[0]).toBeEnabled();
});
+ it('preserves numeric progress for local video jobs and uses fal browser stage messages', () => {
+ const { rerender } = render(
+ <LoomCanvas
+ episode={episode()}
+ selectedNodeId={null}
+ onSelectNode={() => {}}
+ onGenerateVideo={() => {}}
+ mediaJobs={{ n1: { video: {
+ jobId: 'video-1', status: 'running', progress: 0.42, statusMsg: 'Sampling frames',
+ } } }}
+ />,
+ );
+ expect(screen.getByText('Generating video 42%')).toBeInTheDocument();
+ expect(screen.queryByText('Sampling frames')).not.toBeInTheDocument();
+
+ rerender(
+ <LoomCanvas
+ episode={episode()}
+ selectedNodeId={null}
+ onSelectNode={() => {}}
+ onGenerateVideo={() => {}}
+ mediaJobs={{ n1: { video: {
+ jobId: 'fal-1', source: 'fal-browser', status: 'running', progress: 0.3,
+ statusMsg: 'Generating the scene video on fal.ai…',
+ } } }}
+ />,
+ );
+ expect(screen.getByText('Generating the scene video on fal.ai…')).toBeInTheDocument();
+ });
+
it('uses absolute SVG coordinates for compact media so WebKit keeps it inside the card', () => {
const { rerender } = render(
<LoomCanvas
diff --git a/client/src/components/fableloom/LoomSceneMedia.jsx b/client/src/components/fableloom/LoomSceneMedia.jsx
index 0fd42e769e..6ecaf22151 100644
--- a/client/src/components/fableloom/LoomSceneMedia.jsx
+++ b/client/src/components/fableloom/LoomSceneMedia.jsx
@@ -30,7 +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;
+ if (job.source === 'fal-browser' && job.statusMsg) return job.statusMsg;
const pct = progressPercent(job);
return job.status === 'submitting'
? `Starting ${noun}…`
diff --git a/server/services/fableLoom/falVideoAutomation.js b/server/services/fableLoom/falVideoAutomation.js
index 1537a55566..327c1e42f5 100644
--- a/server/services/fableLoom/falVideoAutomation.js
+++ b/server/services/fableLoom/falVideoAutomation.js
@@ -32,6 +32,7 @@ const FAL_ASPECT_RATIOS = new Set(['16:9', '9:16', '1:1']);
const jobs = new Map();
const latestJobByScene = new Map();
+const pendingJobByScene = new Map();
let runTail = Promise.resolve();
const sceneKey = (loomId, episodeId, nodeId) => JSON.stringify([loomId, episodeId, nodeId]);
@@ -102,10 +103,10 @@ 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 challengeFrames = await page.locator([
- 'iframe[src*="captcha" i]',
- 'iframe[src*="challenge" i]',
- 'iframe[title*="captcha" i]',
- 'iframe[title*="challenge" i]',
+ 'iframe[src*="captcha" i]:visible',
+ 'iframe[src*="challenge" i]:visible',
+ 'iframe[title*="captcha" i]:visible',
+ 'iframe[title*="challenge" i]:visible',
].join(', ')).count().catch(() => 0);
if (challengeFrames > 0 || /captcha|verify (?:that )?you are human|human verification/i.test(message)) {
return 'fal.ai needs human verification in the PortOS Browser. Complete it there, then retry.';
@@ -139,7 +140,10 @@ const waitForFalResult = async (page, resultVideo, previousSourceUrl) => {
const remaining = deadline - Date.now();
const visible = await resultVideo.waitFor({
state: 'visible',
- timeout: Math.min(FAL_RESULT_POLL_MS, remaining),
+ // Playwright interprets zero as "no timeout". The clock can reach the
+ // deadline between the loop check and this calculation, so keep the
+ // final probe finite instead of wedging the global job queue forever.
+ timeout: Math.max(1, Math.min(FAL_RESULT_POLL_MS, remaining)),
}).then(() => true).catch(() => false);
if (visible) {
const sourceUrl = await readVideoSource(resultVideo);
@@ -279,6 +283,16 @@ const executeJob = async (job) => {
job.videoHistoryId = galleryVideo.id;
job.filename = galleryVideo.filename;
+ // FableLoom scenes still address a gallery clip as `${historyId}.mp4`.
+ // Keep any valid alternate container in Media History, but do not attach
+ // a record whose scene preview URL cannot resolve.
+ if (galleryVideo.filename !== `${galleryVideo.id}.mp4`) {
+ throw new ServerError(
+ 'fal.ai returned a non-MP4 video. It is saved in Media History but was not attached.',
+ { status: 502, code: 'FAL_VIDEO_UNSUPPORTED_CONTAINER' },
+ );
+ }
+
const latestBeforeAttach = await getLoom(job.loomId);
const { node: sceneBeforeAttach } = findScene(latestBeforeAttach, job.episodeId, job.nodeId);
if (!sceneBeforeAttach || sceneBeforeAttach.image !== job.imageFilename) {
@@ -328,44 +342,60 @@ export async function startFalVideoAutomation(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 pending = pendingJobByScene.get(key);
+ if (pending) return await pending;
+
+ // Reserve this scene before the first lookup yields. Without this promise,
+ // two POSTs arriving in the same render can both pass the active-job check
+ // and spend two free fal.ai allowances before either job is registered.
+ const createJob = (async () => {
+ 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);
+ 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));
+ // Snapshot the queued state before the serialized runner can advance it;
+ // both same-scene callers receive the same initial API contract.
+ return publicJob(job);
+ })();
+ pendingJobByScene.set(key, createJob);
+ try {
+ return await createJob;
+ } finally {
+ if (pendingJobByScene.get(key) === createJob) pendingJobByScene.delete(key);
+ }
}
export function getFalVideoAutomation(loomId, episodeId, nodeId, jobId) {
@@ -380,5 +410,6 @@ export function getFalVideoAutomation(loomId, episodeId, nodeId, jobId) {
export function _resetFalVideoAutomations() {
jobs.clear();
latestJobByScene.clear();
+ pendingJobByScene.clear();
runTail = Promise.resolve();
}
diff --git a/server/services/fableLoom/falVideoAutomation.test.js b/server/services/fableLoom/falVideoAutomation.test.js
index 61079adee3..d5fb1bcaa8 100644
--- a/server/services/fableLoom/falVideoAutomation.test.js
+++ b/server/services/fableLoom/falVideoAutomation.test.js
@@ -50,6 +50,7 @@ const makeBrowser = ({
resultError = null,
errorTexts = [],
gotoError = null,
+ hiddenChallengeFrame = false,
previousVideoUrl = '',
resultVideoUrl = 'https://v3.fal.media/files/example.mp4',
} = {}) => {
@@ -67,7 +68,6 @@ const makeBrowser = ({
video.first.mockReturnValue(video);
const errorLocator = {
allInnerTexts: vi.fn(async () => errorTexts),
- count: vi.fn(async () => 0),
};
const controls = new Map(['16:9', '9:16', '1:1', '5s', 'Generate'].map((name) => [name, {
click: vi.fn(async () => {}),
@@ -89,6 +89,10 @@ const makeBrowser = ({
if (selector.startsWith('textarea')) return prompt;
if (selector.startsWith('input')) return image;
if (selector === 'video[src]') return video;
+ if (selector.includes('iframe[')) {
+ const visibleOnly = selector.split(',').every((part) => part.trim().endsWith(':visible'));
+ return { count: vi.fn(async () => hiddenChallengeFrame && !visibleOnly ? 1 : 0) };
+ }
return errorLocator;
}),
url: vi.fn(() => 'about:blank'),
@@ -172,12 +176,16 @@ describe('FableLoom fal.ai browser automation', () => {
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', {
+ let resolveLookup;
+ mocks.getLoom.mockImplementationOnce(() => new Promise((resolve) => { resolveLookup = resolve; }));
+ const firstRequest = 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', {
+ const secondRequest = startFalVideoAutomation('loom-1', 'ep-1', 'node-1', {
prompt: 'A duplicate click.', aspectRatio: '16:9',
});
+ resolveLookup(loomWithImage());
+ const [first, second] = await Promise.all([firstRequest, secondRequest]);
expect(second.id).toBe(first.id);
await waitForTerminalJob(first);
@@ -219,6 +227,44 @@ describe('FableLoom fal.ai browser automation', () => {
expect(mocks.sleep).toHaveBeenCalledWith(2000);
});
+ it('keeps the final result probe finite when the render deadline is reached between checks', async () => {
+ const { video } = makeBrowser();
+ const now = vi.spyOn(Date, 'now')
+ .mockReturnValueOnce(0)
+ .mockReturnValueOnce(0)
+ .mockReturnValueOnce(0)
+ .mockReturnValueOnce((20 * 60 * 1000) - 1)
+ .mockReturnValue(20 * 60 * 1000);
+ try {
+ const queued = await startFalVideoAutomation('loom-1', 'ep-1', 'node-1', {
+ prompt: 'The example door opens.', aspectRatio: '16:9',
+ });
+
+ await expect(waitForTerminalJob(queued)).resolves.toMatchObject({ status: 'completed' });
+ expect(video.waitFor).toHaveBeenCalledWith({ state: 'visible', timeout: 1 });
+ } finally {
+ now.mockRestore();
+ }
+ });
+
+ it('ignores a hidden challenge iframe injected during an ordinary fal.ai render', async () => {
+ const { video } = makeBrowser({
+ hiddenChallengeFrame: true,
+ previousVideoUrl: 'https://v3.fal.media/files/prior-scene.mp4',
+ resultVideoUrl: 'https://v3.fal.media/files/current-scene.mp4',
+ });
+ video.evaluate
+ .mockReset()
+ .mockResolvedValueOnce('https://v3.fal.media/files/prior-scene.mp4')
+ .mockResolvedValueOnce('https://v3.fal.media/files/prior-scene.mp4')
+ .mockResolvedValue('https://v3.fal.media/files/current-scene.mp4');
+ const queued = await startFalVideoAutomation('loom-1', 'ep-1', 'node-1', {
+ prompt: 'The example door opens.', aspectRatio: '16:9',
+ });
+
+ await expect(waitForTerminalJob(queued)).resolves.toMatchObject({ status: 'completed' });
+ });
+
it('closes a newly created blank tab when fal.ai navigation fails', async () => {
const { page } = makeBrowser({ gotoError: new Error('navigation failed') });
const queued = await startFalVideoAutomation('loom-1', 'ep-1', 'node-1', {
@@ -258,6 +304,25 @@ describe('FableLoom fal.ai browser automation', () => {
expect(mocks.attachNodeVideo).not.toHaveBeenCalled();
});
+ it('keeps a non-MP4 fal result in Media History without attaching an unplayable scene id', async () => {
+ makeBrowser();
+ mocks.saveUploadedGalleryVideoBuffer.mockResolvedValueOnce({
+ id: 'upload-ab12cd34', filename: 'upload-ab12cd34.webm',
+ });
+ 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',
+ filename: 'upload-ab12cd34.webm',
+ 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'),