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): guard fal browser lifecycle

Adam Eivy5510428e97da
diff --git a/client/src/components/fableloom/LoomSceneMedia.jsx b/client/src/components/fableloom/LoomSceneMedia.jsx
index 3b49d1f14f..0fd42e769e 100644
--- a/client/src/components/fableloom/LoomSceneMedia.jsx
+++ b/client/src/components/fableloom/LoomSceneMedia.jsx
@@ -60,7 +60,8 @@ export default function LoomSceneMedia({
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' : '');
+ || (falRequiresImage ? 'Generate a scene image first so fal.ai has a starting frame' : '')
+ || (videoActive ? 'A scene video is already rendering' : '');
const activeJob = videoActive ? videoJob : imageActive ? imageJob : null;
const activeKind = videoActive ? 'video' : imageActive ? 'image' : null;
const failedJob = videoJob?.status === 'failed'
diff --git a/server/services/fableLoom/falVideoAutomation.js b/server/services/fableLoom/falVideoAutomation.js
index e8752dd8e0..1537a55566 100644
--- a/server/services/fableLoom/falVideoAutomation.js
+++ b/server/services/fableLoom/falVideoAutomation.js
@@ -12,6 +12,7 @@
import { randomUUID } from 'node:crypto';
import { chromium } from 'playwright-core';
import { ServerError } from '../../lib/errorHandler.js';
+import { sleep } from '../../lib/fileUtils.js';
import { resolveGalleryImage } from '../../lib/pathSafety.js';
import { getHealthStatus, launchBrowser } from '../browserService.js';
import {
@@ -100,12 +101,16 @@ const cdpEndpoint = async () => {
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)) {
+ const challengeFrames = await page.locator([
+ 'iframe[src*="captcha" i]',
+ 'iframe[src*="challenge" i]',
+ 'iframe[title*="captcha" i]',
+ 'iframe[title*="challenge" i]',
+ ].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.';
}
- if (/daily limit|free (?:video )?limit|quota|too many requests/i.test(combined)) {
+ if (/daily limit|free (?:video )?limit|quota|too many requests/i.test(message)) {
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)) {
@@ -148,6 +153,7 @@ const waitForFalResult = async (page, resultVideo, previousSourceUrl) => {
if (failure) {
throw new ServerError(failure, { status: 502, code: 'FAL_VIDEO_GENERATION_FAILED' });
}
+ await sleep(Math.min(FAL_RESULT_POLL_MS, Math.max(0, deadline - Date.now())));
}
throw new ServerError(
'fal.ai did not finish the video before the 20-minute timeout. Inspect the PortOS Browser tab, then retry.',
@@ -199,6 +205,7 @@ const readFalVideo = async (context, sourceUrl) => {
const executeJob = async (job) => {
let browser = null;
+ let createdPage = null;
try {
job.startedAt = new Date().toISOString();
setJobProgress(job, 'Opening the PortOS Browser…', 0.05);
@@ -231,12 +238,16 @@ const executeJob = async (job) => {
code: 'PORTOS_BROWSER_UNAVAILABLE',
});
}
- const page = context.pages().find((candidate) => candidate.url().includes('/tools/minimax-h3-max'))
- || await context.newPage();
+ const existingPage = context.pages()
+ .find((candidate) => candidate.url().includes('/tools/minimax-h3-max'));
+ createdPage = existingPage ? null : await context.newPage();
+ const page = existingPage || createdPage;
+ setJobProgress(job, 'Loading the fal.ai video tool…', 0.1);
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();
+ setJobProgress(job, 'Waiting for fal.ai controls…', 0.12);
await promptInput.waitFor({ state: 'visible', timeout: FAL_CONTROL_TIMEOUT_MS });
setJobProgress(job, 'Uploading the scene image to fal.ai…', 0.15);
@@ -293,12 +304,17 @@ const executeJob = async (job) => {
console.log(`🎬 fal.ai scene video attached: ${galleryVideo.id}`);
} catch (error) {
const message = safeFailureMessage(error);
+ const diagnostic = [error?.name || 'Error', error?.code].filter(Boolean).join('/');
+ const failedStage = job.statusMsg || 'fal.ai automation';
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}`);
+ 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
+ // accumulate blank tabs when navigation itself failed.
+ if (createdPage?.url() === 'about:blank') await createdPage.close().catch(() => {});
if (browser) await browser.close().catch(() => {});
}
};
diff --git a/server/services/fableLoom/falVideoAutomation.test.js b/server/services/fableLoom/falVideoAutomation.test.js
index 056c1525a3..61079adee3 100644
--- a/server/services/fableLoom/falVideoAutomation.test.js
+++ b/server/services/fableLoom/falVideoAutomation.test.js
@@ -9,6 +9,7 @@ const mocks = vi.hoisted(() => ({
launchBrowser: vi.fn(),
resolveGalleryImage: vi.fn(),
saveUploadedGalleryVideoBuffer: vi.fn(),
+ sleep: vi.fn(),
}));
vi.mock('playwright-core', () => ({
@@ -21,6 +22,9 @@ vi.mock('../browserService.js', () => ({
vi.mock('../../lib/pathSafety.js', () => ({
resolveGalleryImage: (...args) => mocks.resolveGalleryImage(...args),
}));
+vi.mock('../../lib/fileUtils.js', () => ({
+ sleep: (...args) => mocks.sleep(...args),
+}));
vi.mock('../videoUpload.js', () => ({
MAX_GALLERY_VIDEO_UPLOAD_BYTES: 50 * 1024 * 1024,
saveUploadedGalleryVideoBuffer: (...args) => mocks.saveUploadedGalleryVideoBuffer(...args),
@@ -45,6 +49,7 @@ const loomWithImage = (image = 'scene.png') => ({
const makeBrowser = ({
resultError = null,
errorTexts = [],
+ gotoError = null,
previousVideoUrl = '',
resultVideoUrl = 'https://v3.fal.media/files/example.mp4',
} = {}) => {
@@ -62,8 +67,8 @@ const makeBrowser = ({
video.first.mockReturnValue(video);
const errorLocator = {
allInnerTexts: vi.fn(async () => errorTexts),
+ count: vi.fn(async () => 0),
};
- 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 () => {}),
@@ -77,13 +82,13 @@ const makeBrowser = ({
};
const request = { get: vi.fn(async () => apiResponse) };
const page = {
+ close: vi.fn(async () => {}),
getByRole: vi.fn((_role, { name }) => controls.get(name)),
- goto: vi.fn(async () => {}),
+ goto: gotoError ? vi.fn(async () => { throw gotoError; }) : 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'),
@@ -119,6 +124,7 @@ beforeEach(() => {
mocks.getHealthStatus.mockResolvedValue({ connected: true, cdpHost: '127.0.0.1', cdpPort: 5556 });
mocks.getLoom.mockResolvedValue(loomWithImage());
mocks.resolveGalleryImage.mockReturnValue('/example/images/scene.png');
+ mocks.sleep.mockResolvedValue(undefined);
mocks.saveUploadedGalleryVideoBuffer.mockResolvedValue({
id: 'upload-ab12cd34', filename: 'upload-ab12cd34.mp4',
});
@@ -195,6 +201,35 @@ describe('FableLoom fal.ai browser automation', () => {
);
});
+ it('paces polling while a stale persistent-tab result remains visible', async () => {
+ const { video } = makeBrowser({
+ 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 current scene begins.', aspectRatio: '16:9',
+ });
+
+ await expect(waitForTerminalJob(queued)).resolves.toMatchObject({ status: 'completed' });
+ expect(mocks.sleep).toHaveBeenCalledWith(2000);
+ });
+
+ 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', {
+ prompt: 'The current scene begins.', aspectRatio: '16:9',
+ });
+
+ await expect(waitForTerminalJob(queued)).resolves.toMatchObject({ status: 'failed' });
+ expect(page.close).toHaveBeenCalledTimes(1);
+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('during Loading the fal.ai video tool'));
+ });
+
it('requires a current storyboard image before it consumes fal.ai', async () => {
mocks.getLoom.mockResolvedValueOnce(loomWithImage(null));