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

feat: add fal.ai queue REST API video backend to MediaGen and FableLoom (#6213)

[._.]/ Adam Eivye7d8921a44aa
diff --git a/.env.example b/.env.example
index 7883c2ded6..9f2ba7e57d 100644
--- a/.env.example
+++ b/.env.example
@@ -110,6 +110,11 @@ PGPASSWORD=portos
# GROK_TIMEOUT_MS — keep it above the 20-minute cloud-lane idle watchdog.
# GROK_VIDEO_TIMEOUT_MS=1800000
+# Maximum fal.ai queue video-generation runtime in milliseconds (videoGen/fal.js;
+# default: 1200000 / 20 minutes) — a queue render can sit behind other tenants'
+# jobs before it starts, so this bounds the whole submit→poll→download run.
+# FAL_VIDEO_TIMEOUT_MS=1200000
+
# Maximum Antigravity image-generation runtime in milliseconds (default: 1200000 / 20 minutes)
# AGY_IMAGEGEN_TIMEOUT_MS=1200000
@@ -150,6 +155,10 @@ PGPASSWORD=portos
# CivitAI API key for LoRA / model downloads from civitai.com
# CIVITAI_API_KEY=your_civitai_api_key_here
+# fal.ai API key for the fal.ai queue video backend (Video Gen page, FableLoom).
+# Settings > Video Gen's stored key wins when both are set.
+# FAL_KEY=your_fal_api_key_here
+
# Absolute path to the bash binary used to run PortOS's bundled *.sh scripts
# (e.g. scripts/db.sh). Auto-detected if unset; on Windows it prefers Git Bash,
# because a bare `bash` often resolves to WSL, which can't see drive paths.
diff --git a/client/src/components/fableloom/LoomSettingsDrawer.jsx b/client/src/components/fableloom/LoomSettingsDrawer.jsx
index a588e1909b..69cdf3d544 100644
--- a/client/src/components/fableloom/LoomSettingsDrawer.jsx
+++ b/client/src/components/fableloom/LoomSettingsDrawer.jsx
@@ -51,6 +51,7 @@ const VIDEO_RENDER_BACKENDS = [
{ id: 'auto', label: 'Auto', icon: Layers },
{ id: 'local', label: 'Local', icon: Cpu },
{ id: 'grok', label: 'Grok', icon: Cloud },
+ { id: 'fal', label: 'fal.ai', icon: Cloud },
];
const modelOptions = (models, selected) => {
diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsx
index 132cd08e6d..ab091439fd 100644
--- a/client/src/components/settings/ImageGenTab.jsx
+++ b/client/src/components/settings/ImageGenTab.jsx
@@ -112,6 +112,10 @@ export function ImageGenTab() {
// (defaultModelId) survive the settings PUT's wholesale slice replace.
const [videoGenMode, setVideoGenMode] = useState('');
const [videoGenDisplaySleep, setVideoGenDisplaySleep] = useState(true);
+ // fal.ai queue REST API key (#6213) — usability-gated on this being set
+ // (settings, or the FAL_KEY env var server-side). No enabled toggle: the
+ // key's presence IS the opt-in, same shape as loras.js's Civitai key.
+ const [falApiKey, setFalApiKey] = useState('');
const videoGenSliceRef = useRef({});
const [sdapiUrl, setSdapiUrl] = useState('');
const [pythonPath, setPythonPath] = useState('');
@@ -177,6 +181,7 @@ export function ImageGenTab() {
renderDefaultsJson: '{}',
videoGenMode: '',
videoGenDisplaySleep: true,
+ falApiKey: '',
});
const [status, setStatus] = useState(null);
@@ -249,6 +254,7 @@ export function ImageGenTab() {
const vg = (s?.videoGen && typeof s.videoGen === 'object') ? s.videoGen : {};
const vgMode = normalizeRenderPinValue(vg.mode) || '';
const vgDisplaySleep = vg.displaySleep !== false;
+ const vgFalApiKey = vg.fal?.apiKey || '';
const m = ig.mode || IMAGE_GEN_MODE.EXTERNAL;
const url = normalizeUrl(ig.external?.sdapiUrl || ig.sdapiUrl);
const py = ig.local?.pythonPath || '';
@@ -284,6 +290,7 @@ export function ImageGenTab() {
setRenderDefaults(rd);
setVideoGenMode(vgMode);
setVideoGenDisplaySleep(vgDisplaySleep);
+ setFalApiKey(vgFalApiKey);
videoGenSliceRef.current = vg;
setSdapiUrl(url);
setPythonPath(py);
@@ -312,6 +319,7 @@ export function ImageGenTab() {
renderDefaultsJson: JSON.stringify(rd),
videoGenMode: vgMode,
videoGenDisplaySleep: vgDisplaySleep,
+ falApiKey: vgFalApiKey,
});
setToolRegistered(tools.some((t) => t.id === SDAPI_TOOL_ID));
setCodexToolRegistered(tools.some((t) => t.id === CODEX_TOOL_ID));
@@ -403,7 +411,8 @@ export function ImageGenTab() {
|| denoiseByMode.external !== saved.denoiseByMode.external
|| JSON.stringify(renderDefaults) !== saved.renderDefaultsJson
|| videoGenMode !== saved.videoGenMode
- || videoGenDisplaySleep !== saved.videoGenDisplaySleep;
+ || videoGenDisplaySleep !== saved.videoGenDisplaySleep
+ || falApiKey !== saved.falApiKey;
const handleSave = async () => {
setSaving(true);
@@ -448,7 +457,12 @@ export function ImageGenTab() {
),
// Install-wide video pin (#3231 Phase 4). Spread over the loaded slice so
// sibling keys (defaultModelId) survive the wholesale slice replace.
- videoGen: { ...videoGenSliceRef.current, mode: videoGenMode || null, displaySleep: videoGenDisplaySleep },
+ videoGen: {
+ ...videoGenSliceRef.current,
+ mode: videoGenMode || null,
+ displaySleep: videoGenDisplaySleep,
+ fal: { ...videoGenSliceRef.current.fal, apiKey: falApiKey.trim() },
+ },
};
try {
await updateSettings(patch, { silent: true });
@@ -466,6 +480,7 @@ export function ImageGenTab() {
renderDefaultsJson: JSON.stringify(patch.renderDefaults),
videoGenMode,
videoGenDisplaySleep,
+ falApiKey: falApiKey.trim(),
});
// Reflect the pruned no-op entries back into the editor state so the
// dirty check compares like against like after a save.
@@ -770,6 +785,20 @@ export function ImageGenTab() {
<span className="block text-xs text-gray-500 mt-0.5">Keeps the system awake while reducing WindowServer GPU contention on affected Apple silicon. Turn off only when another headless workflow manages display power.</span>
</span>
</label>
+ <FormField
+ label={<>fal.ai API key<span className="block text-xs text-gray-500 mt-0.5">Enables the fal.ai queue video backend on the Video Gen page and in FableLoom. Get a key at fal.ai/dashboard/keys, or set the FAL_KEY environment variable instead.</span></>}
+ labelClassName="text-sm text-gray-300"
+ >
+ <input
+ id="fal-api-key"
+ type="password"
+ autoComplete="off"
+ value={falApiKey}
+ onChange={(e) => setFalApiKey(e.target.value)}
+ placeholder="fal-key-..."
+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"
+ />
+ </FormField>
<div className="space-y-3">
{RENDER_TARGET_OPTIONS.map(({ id, label, video }) => {
const entry = renderDefaults[id] || {};
diff --git a/client/src/components/settings/ImageGenTab.test.jsx b/client/src/components/settings/ImageGenTab.test.jsx
index 1644e91f04..05b9588692 100644
--- a/client/src/components/settings/ImageGenTab.test.jsx
+++ b/client/src/components/settings/ImageGenTab.test.jsx
@@ -244,7 +244,9 @@ describe('ImageGenTab grouped tabs', () => {
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
await waitFor(() => expect(updateSettings).toHaveBeenCalled());
const patch = updateSettings.mock.calls[0][0];
- expect(patch.videoGen).toEqual({ mode: 'local', defaultModelId: 'ltx23_distilled_q4', displaySleep: true });
+ expect(patch.videoGen).toEqual({
+ mode: 'local', defaultModelId: 'ltx23_distilled_q4', displaySleep: true, fal: { apiKey: '' },
+ });
});
});
diff --git a/client/src/hooks/useVideoGenFieldState.js b/client/src/hooks/useVideoGenFieldState.js
index 479e07514e..c8922517da 100644
--- a/client/src/hooks/useVideoGenFieldState.js
+++ b/client/src/hooks/useVideoGenFieldState.js
@@ -21,6 +21,8 @@ export function useVideoGenFieldState({
}) {
const [backend, setBackend] = useState('local');
const [grokDuration, setGrokDuration] = useState(GROK_VIDEO_DEFAULT_DURATION);
+ const [falDuration, setFalDuration] = useState('');
+ const [falModelId, setFalModelId] = useState('');
const [mode, setMode] = useState(incomingAudioFilename ? 'a2v' : (incomingSourceImage ? 'image' : 'text'));
const [prompt, setPrompt] = useState(incomingPrompt || '');
const [negativePrompt, setNegativePrompt] = useState(incomingNegativePrompt || '');
@@ -82,6 +84,8 @@ export function useVideoGenFieldState({
extendFromVideoId, setExtendFromVideoId,
fps, setFps,
grokDuration, setGrokDuration,
+ falDuration, setFalDuration,
+ falModelId, setFalModelId,
guidanceScale, setGuidanceScale,
height, setHeight,
i2vReferenceMode, setI2vReferenceMode,
diff --git a/client/src/hooks/useVideoGenForm.js b/client/src/hooks/useVideoGenForm.js
index 79be036303..3d13904e8f 100644
--- a/client/src/hooks/useVideoGenForm.js
+++ b/client/src/hooks/useVideoGenForm.js
@@ -71,7 +71,9 @@ const editableRemixModel = (models, defaultModelId) => {
* wire accepts — kept here rather than in the page so there stays exactly
* one builder for what `server/routes/videoGen.js` validates.
*/
-export function useVideoGenForm({ models, modelContext, availableLoras, grokEnabled, remoteSubmissionFields = null }) {
+export function useVideoGenForm({
+ models, modelContext, availableLoras, grokEnabled, falEnabled = false, remoteSubmissionFields = null,
+}) {
const [searchParams, setSearchParams] = useSearchParams();
const incomingSourceImage = searchParams.get('sourceImageFile');
const incomingAudioFilename = searchParams.get('audioFilename');
@@ -92,6 +94,8 @@ export function useVideoGenForm({ models, modelContext, availableLoras, grokEnab
extendFromVideoId, setExtendFromVideoId,
fps, setFps,
grokDuration, setGrokDuration,
+ falDuration, setFalDuration,
+ falModelId, setFalModelId,
guidanceScale, setGuidanceScale,
height, setHeight,
i2vReferenceMode, setI2vReferenceMode,
@@ -586,7 +590,12 @@ export function useVideoGenForm({ models, modelContext, availableLoras, grokEnab
// lane reads only prompt/dims/source-image/duration, so its image_to_video
// always anchors and the promise has to collapse to the default there.
const isGrok = grokEnabled && backend === 'grok';
- const referenceModeApplies = mode === 'image' && !isGrok;
+ // fal.ai's queue REST API is usability-gated on a configured API key
+ // (`falEnabled`, mirrored from the server's isVideoModeUsable check), not a
+ // toggle — same short-circuit shape as grok: only prompt/dims/source-image
+ // and a duration reach the provider.
+ const isFal = falEnabled && backend === 'fal';
+ const referenceModeApplies = mode === 'image' && !isGrok && !isFal;
// The strength the render will actually use, for the slider readout — an
// untouched slider under Inspire still resolves to the contract's low default
// rather than the pipeline's 1.0, and the panel must say so.
@@ -870,7 +879,7 @@ export function useVideoGenForm({ models, modelContext, availableLoras, grokEnab
// clip survives the switch and reappears if the user flips back.
const handleBackendChange = (id) => {
setBackend(id);
- if (id === 'grok' && mode !== 'text' && mode !== 'image') {
+ if ((id === 'grok' || id === 'fal') && mode !== 'text' && mode !== 'image') {
handleModeChange((sourceImageFile || sourceImageUpload) ? 'image' : 'text');
}
};
@@ -1160,6 +1169,12 @@ export function useVideoGenForm({ models, modelContext, availableLoras, grokEnab
setBackend('grok');
setMode(p.videoMode === 'image' ? 'image' : 'text');
if (p.duration) setGrokDuration(p.duration);
+ } else if (p.mode === 'fal') {
+ // fal.ai job: same discriminator shape as grok above.
+ setBackend('fal');
+ setMode(p.videoMode === 'image' ? 'image' : 'text');
+ if (p.duration) setFalDuration(p.duration);
+ if (p.modelId) setFalModelId(p.modelId);
} else if (p.mode) setMode(p.mode);
if (p.chunks && p.chunks > 1) setChunks(p.chunks);
// 0 is a real restored value ("last frame only"), so this can't gate on
@@ -1232,7 +1247,7 @@ export function useVideoGenForm({ models, modelContext, availableLoras, grokEnab
// Snapshot the current validated state into a wire payload. The submit flow
// stays pure so all three backend contracts can be tested independently.
const submissionState = {
- isGrok, grokDuration, remoteSubmissionFields,
+ isGrok, grokDuration, isFal, falDuration, falModelId, remoteSubmissionFields,
prompt, negativePrompt, stylePreset, selectedUniverse,
width, height, mode, sourceImageFile, sourceImageUpload,
numFrames, fps, steps, guidanceScale, seed,
@@ -1248,8 +1263,10 @@ export function useVideoGenForm({ models, modelContext, availableLoras, grokEnab
return {
// Backend + mode
- backend, isGrok, handleBackendChange,
+ backend, isGrok, isFal, handleBackendChange,
grokDuration, setGrokDuration,
+ falDuration, setFalDuration,
+ falModelId, setFalModelId,
mode, handleModeChange,
// Prompt + style
prompt, setPrompt,
diff --git a/client/src/lib/imageGenModes.js b/client/src/lib/imageGenModes.js
index 61b05aea0d..6a87d0bd4b 100644
--- a/client/src/lib/imageGenModes.js
+++ b/client/src/lib/imageGenModes.js
@@ -71,7 +71,7 @@ export const RENDER_TARGET_OPTIONS = Object.freeze([
// Client mirror of the server's VIDEO_GEN_MODES (services/videoGen/modes.js) —
// the backend alphabet for the video pin controls above and the install-wide
// `settings.videoGen.mode` pin.
-export const VIDEO_RENDER_MODES = Object.freeze(['local', 'grok']);
+export const VIDEO_RENDER_MODES = Object.freeze(['local', 'grok', 'fal']);
// Client mirror of the server's normalizeRenderPinValue
// (server/lib/renderTargets.js) — THE one render-pin normalization rule: trim;
@@ -94,6 +94,7 @@ export const MODE_LABELS = Object.freeze({
[IMAGE_GEN_MODE.GROK]: 'Grok',
[IMAGE_GEN_MODE.AGY]: 'Agy',
[IMAGE_GEN_MODE.EXTERNAL]: 'External',
+ fal: 'fal.ai',
});
// Client mirror of the server's CLOUD_IMAGE_GEN_MODES (imageGen/modes.js) —
diff --git a/client/src/lib/videoGenSubmission.js b/client/src/lib/videoGenSubmission.js
index 2c85fa6955..e454c778ab 100644
--- a/client/src/lib/videoGenSubmission.js
+++ b/client/src/lib/videoGenSubmission.js
@@ -34,7 +34,7 @@ export function envelopVideoPrompt(text, {
}
export function buildVideoGenSubmission({
- isGrok, grokDuration, remoteSubmissionFields,
+ isGrok, grokDuration, isFal, falDuration, falModelId, remoteSubmissionFields,
prompt, negativePrompt, stylePreset, selectedUniverse,
width, height, mode, sourceImageFile, sourceImageUpload,
numFrames, fps, steps, guidanceScale, seed,
@@ -71,6 +71,21 @@ export function buildVideoGenSubmission({
};
}
+ if (isFal) {
+ return {
+ backend: 'fal',
+ prompt: composed.prompt,
+ negativePrompt: composed.negativePrompt,
+ falDuration,
+ falModelId: falModelId || undefined,
+ width: clampImageEdge(width, VIDEO_EDGE_BOUNDS),
+ height: clampImageEdge(height, VIDEO_EDGE_BOUNDS),
+ mode: mode === 'image' ? 'image' : 'text',
+ sourceImageFile: mode === 'image' ? (sourceImageFile || '') : '',
+ sourceImage: mode === 'image' ? (sourceImageUpload || '') : '',
+ };
+ }
+
if (remoteSubmissionFields) {
return {
backend: 'local',
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 8e7aa73b41..b3054d6b28 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -134,13 +134,19 @@ export default function VideoGen() {
// user enabled Grok in Settings → Image Gen (one toggle covers image +
// video). 'local' keeps every existing flow untouched.
const [grokEnabled, setGrokEnabled] = useState(false);
+ // fal.ai queue REST video backend (#6213) — surfaced only when an API key is
+ // configured (Settings → Video Gen, or the FAL_KEY env var).
+ const [falEnabled, setFalEnabled] = useState(false);
// The jobId of the render this tab's Generate button currently owns —
// threaded into cancelVideoGen so cancellation is job-scoped.
const activeJobIdRef = useRef(null);
const models = useMemo(() => modelContext?.models || [], [modelContext]);
const refreshGrokEnabled = useCallback(() => {
getSettings({ silent: true })
- .then((sv) => setGrokEnabled(sv?.imageGen?.grok?.enabled === true))
+ .then((sv) => {
+ setGrokEnabled(sv?.imageGen?.grok?.enabled === true);
+ setFalEnabled(Boolean(sv?.videoGen?.fal?.apiKey));
+ })
.catch(() => {});
}, []);
useEffect(() => { refreshGrokEnabled(); }, [refreshGrokEnabled]);
@@ -157,7 +163,8 @@ export default function VideoGen() {
// Every field the form submits, plus the payload builder both submit paths
// share. See client/src/hooks/useVideoGenForm.js.
const {
- backend, isGrok, handleBackendChange, grokDuration, setGrokDuration,
+ backend, isGrok, isFal, handleBackendChange, grokDuration, setGrokDuration,
+ falDuration, setFalDuration, falModelId, setFalModelId,
mode, handleModeChange,
prompt, setPrompt, envelopedPrompt, negativePrompt, setNegativePrompt, stylePreset, setStylePreset,
selectedUniverse, setSelectedUniverse, remixModelFallback,
@@ -192,7 +199,7 @@ export default function VideoGen() {
icStrength, setIcStrength, icSkipStage2, setIcSkipStage2,
applyRemix, applyFinish, applyResumedParams, buildGeneratePayload,
} = useVideoGenForm({
- models, modelContext, availableLoras, grokEnabled,
+ models, modelContext, availableLoras, grokEnabled, falEnabled,
remoteSubmissionFields: remoteTarget.isRemote ? remoteTarget.submissionFields : null,
});
@@ -216,6 +223,7 @@ export default function VideoGen() {
const model = remoteTarget.model;
const present = [
['the Grok backend', isGrok],
+ ['the fal.ai backend', isFal],
// Each remaining pipeline semantic has its own input listed below, but the
// mode can be set before that input is filled — so gate the mode too
// rather than letting an a2v render reach the peer as plain text-to-video.
@@ -242,7 +250,7 @@ export default function VideoGen() {
return `${model?.modelName || 'The selected peer model'} renders only from a source image — add a start frame, or pick a text-to-video model.`;
}
return null;
- }, [remoteTarget.isRemote, remoteTarget.model, remoteTarget.acceptsInput, isGrok, mode, sourceImageFile, sourceImageUpload,
+ }, [remoteTarget.isRemote, remoteTarget.model, remoteTarget.acceptsInput, isGrok, isFal, mode, sourceImageFile, sourceImageUpload,
lastImageFile, lastImageUpload, keyframesActive, extendFromVideoId, audioFile, icReferenceFile,
icReferenceVideoId, icReferenceImageFiles, selectedLoras, chunks]);
// One reading for the Generate button, the enqueue guard and the caption.
@@ -606,14 +614,14 @@ export default function VideoGen() {
startEncoderWhenIdle(option && !option.builtIn ? textEncoderDownloadId(id) : null);
}, [setTextEncoderId, textEncoderOptions, startEncoderWhenIdle]);
const icWeightStatus = icSpec ? modelDownload.getStatus(icSpec.mode) : null;
- const modelWeightsBlocked = !isGrok
+ const modelWeightsBlocked = !isGrok && !isFal
&& (statusLoading || !modelId || !currentModel || modelDownload.loading
|| modelStatus === null || modelStatus?.cached === false);
- const textEncoderWeightsBlocked = !isGrok && usesSharedTextEncoder
+ const textEncoderWeightsBlocked = !isGrok && !isFal && usesSharedTextEncoder
&& (modelDownload.loading || textEncoderStatus === null || textEncoderStatus?.cached === false);
- const icWeightsBlocked = !isGrok && icModeActive
+ const icWeightsBlocked = !isGrok && !isFal && icModeActive
&& (modelDownload.loading || icWeightStatus === null || icWeightStatus?.cached === false);
- const textEncoderOptionBlocked = !isGrok && !!textEncoderOptionDownloadId
+ const textEncoderOptionBlocked = !isGrok && !isFal && !!textEncoderOptionDownloadId
&& (modelDownload.loading || textEncoderOptionStatus === null || textEncoderOptionStatus?.cached === false);
const weightsGateBlocked = modelWeightsBlocked || textEncoderWeightsBlocked
|| textEncoderOptionBlocked || icWeightsBlocked;
@@ -686,7 +694,7 @@ export default function VideoGen() {
// actually apply it (macOS, and the user hasn't opted out).
const rendersSleepDisplay = !!status?.displaySleepOnRender
&& !!currentModel?.sleepsDisplayDuringRender
- && !remoteTarget.isRemote && !isGrok;
+ && !remoteTarget.isRemote && !isGrok && !isFal;
// Run a single payload through the SSE pipeline. Returns a promise that
// resolves when the job completes (or rejects on error / cancel). The
@@ -836,7 +844,7 @@ export default function VideoGen() {
// will actually run on.
const canEnqueue = prompt.trim() && (remoteTarget.isRemote
? remoteBlocked === null
- : (isGrok || (!notConnected && !extendModeBlocked
+ : (isGrok || isFal || (!notConnected && !extendModeBlocked
&& !a2vModeBlocked && !icLoraModeBlocked && !byovGateBlocked
&& !weightsGateBlocked && !keyframesBlocked)));
@@ -911,12 +919,16 @@ export default function VideoGen() {
})()}
{/* Backend switch — shown only when the user enabled Grok in Settings →
- Image Gen. Grok's image_to_video supports text (image-first) and
- image modes only, so switching to it snaps an unsupported mode back
- to the nearest one. */}
- {grokEnabled && (
+ Image Gen and/or configured a fal.ai API key. Both cloud backends'
+ image-to-video only supports text (image-first) and image modes, so
+ switching to either snaps an unsupported mode back to the nearest one. */}
+ {(grokEnabled || falEnabled) && (
<div className="bg-port-card border border-port-border rounded-xl p-1 flex gap-1" role="group" aria-label="Video generation backend">
- {[{ id: 'local', label: 'Local' }, { id: 'grok', label: 'Grok' }].map(({ id, label }) => (
+ {[
+ { id: 'local', label: 'Local' },
+ ...(grokEnabled ? [{ id: 'grok', label: 'Grok' }] : []),
+ ...(falEnabled ? [{ id: 'fal', label: 'fal.ai' }] : []),
+ ].map(({ id, label }) => (
<button
key={id}
type="button"
@@ -925,7 +937,11 @@ export default function VideoGen() {
className={`flex-1 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-colors ${
backend === id ? 'bg-port-accent text-white shadow' : 'text-gray-400 hover:text-white hover:bg-port-border/40'
}`}
- title={id === 'grok' ? 'Render via the Grok Build CLI (image_gen → image_to_video). Counts against your Grok plan.' : 'Render on this machine with the local runtimes.'}
+ title={id === 'grok'
+ ? 'Render via the Grok Build CLI (image_gen → image_to_video). Counts against your Grok plan.'
+ : id === 'fal'
+ ? 'Render via the fal.ai queue API. Counts against your fal.ai balance.'
+ : 'Render on this machine with the local runtimes.'}
>
{label}
</button>
@@ -939,7 +955,7 @@ export default function VideoGen() {
WAI-ARIA Tabs, since the mode-specific inputs aren't structured as
tabpanels and we don't implement roving-tabindex/arrow-key focus. */}
<div className="bg-port-card border border-port-border rounded-xl p-1 flex flex-wrap gap-1" role="group" aria-label="Video generation mode">
- {(isGrok ? MODES.filter((m) => m.id === 'text' || m.id === 'image') : MODES).map(({ id, label, icon: Icon, desc }) => {
+ {((isGrok || isFal) ? MODES.filter((m) => m.id === 'text' || m.id === 'image') : MODES).map(({ id, label, icon: Icon, desc }) => {
const active = mode === id;
return (
<button
@@ -963,7 +979,7 @@ export default function VideoGen() {
<form onSubmit={handleGenerate} className="grid grid-cols-1 lg:grid-cols-[3fr_2fr] gap-4">
<div className="bg-port-card border border-port-border rounded-xl p-4 space-y-3">
- {!isGrok && byovRuntimeMissing && (
+ {!isGrok && !isFal && byovRuntimeMissing && (
<div className="rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-3 text-xs text-port-warning flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
<div>
<strong className="font-semibold">{byovStatus.label}</strong> {byovStatus.upgradeAvailable ? 'has an update available.' : "isn't installed yet."}
@@ -1064,10 +1080,10 @@ export default function VideoGen() {
<AutoSizeTextarea
value={negativePrompt}
onChange={(e) => setNegativePrompt(e.target.value)}
- disabled={!isGrok && currentModel?.supportsNegativePrompt === false}
+ disabled={!isGrok && !isFal && currentModel?.supportsNegativePrompt === false}
rows={3}
className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50 min-h-[80px]"
- placeholder={!isGrok && currentModel?.supportsNegativePrompt === false
+ placeholder={!isGrok && !isFal && currentModel?.supportsNegativePrompt === false
? 'This CFG-distilled model does not use a negative prompt.'
: 'What to avoid...'}
/>
@@ -1251,6 +1267,32 @@ export default function VideoGen() {
<code className="text-gray-400"> image_to_video </code> tool. Model, frames, and seed are chosen by Grok; renders count against your Grok plan.
</p>
</div>
+ ) : isFal ? (
+ <div className="grid grid-cols-2 gap-3">
+ <FormField label="fal.ai model" labelClassName="block text-xs font-medium text-gray-400 mb-1">
+ <input
+ type="text"
+ value={falModelId}
+ onChange={(e) => setFalModelId(e.target.value)}
+ placeholder="fal-ai/minimax/hailuo-02/standard/text-to-video"
+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent"
+ />
+ </FormField>
+ <FormField label="Clip length (sec)" labelClassName="block text-xs font-medium text-gray-400 mb-1">
+ <input
+ type="number"
+ min={1}
+ max={60}
+ value={falDuration}
+ onChange={(e) => setFalDuration(e.target.value)}
+ placeholder="model default"
+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent"
+ />
+ </FormField>
+ <p className="col-span-2 text-[11px] text-gray-500 leading-snug">
+ Renders on fal.ai's queue API — leave the model blank to use PortOS's default (text-to-video, or image-to-video in Image mode). Counts against your fal.ai balance.
+ </p>
+ </div>
) : (
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
{/* The peer advertises its own models; the local list would name
@@ -1400,11 +1442,11 @@ export default function VideoGen() {
<ModelDisclosure
backend={backend}
backendDisclosures={status?.backendDisclosures}
- model={isGrok ? null : currentModel}
+ model={(isGrok || isFal) ? null : currentModel}
systemMemoryGb={modelContext?.systemMemoryGb}
/>
- {!isGrok && (
+ {!isGrok && !isFal && (
<AdvancedParamsPanel
mode={mode}
currentModel={currentModel}
diff --git a/server/lib/generationModes.js b/server/lib/generationModes.js
index c448e9085b..92b3ec1ef6 100644
--- a/server/lib/generationModes.js
+++ b/server/lib/generationModes.js
@@ -33,10 +33,13 @@ export const QUEUEABLE_IMAGE_MODES = Object.freeze([
// Video deliberately shares the image backend discriminator namespace. Local
// video's text/image/fflf modes are a separate semantic value carried elsewhere.
+// FAL has no image-gen counterpart (issue #6213 is video-only), so it is a
+// video-only literal rather than a re-export of an IMAGE_GEN_MODE entry.
export const VIDEO_GEN_MODE = Object.freeze({
LOCAL: IMAGE_GEN_MODE.LOCAL,
GROK: IMAGE_GEN_MODE.GROK,
+ FAL: 'fal',
});
export const VIDEO_GEN_MODES = Object.freeze(Object.values(VIDEO_GEN_MODE));
-export const CLOUD_VIDEO_GEN_MODES = Object.freeze([VIDEO_GEN_MODE.GROK]);
+export const CLOUD_VIDEO_GEN_MODES = Object.freeze([VIDEO_GEN_MODE.GROK, VIDEO_GEN_MODE.FAL]);
diff --git a/server/lib/generationModes.test.js b/server/lib/generationModes.test.js
index ab0fe1267e..7f44009b95 100644
--- a/server/lib/generationModes.test.js
+++ b/server/lib/generationModes.test.js
@@ -22,10 +22,10 @@ describe('generation mode alphabets', () => {
].every(Object.isFrozen)).toBe(true);
});
- it('keeps the video backend alphabet in the image discriminator namespace', () => {
- expect(VIDEO_GEN_MODE).toEqual({ LOCAL: IMAGE_GEN_MODE.LOCAL, GROK: IMAGE_GEN_MODE.GROK });
- expect(VIDEO_GEN_MODES).toEqual(['local', 'grok']);
- expect(CLOUD_VIDEO_GEN_MODES).toEqual(['grok']);
+ it('keeps the video backend alphabet in the image discriminator namespace, plus fal as a video-only extra', () => {
+ expect(VIDEO_GEN_MODE).toEqual({ LOCAL: IMAGE_GEN_MODE.LOCAL, GROK: IMAGE_GEN_MODE.GROK, FAL: 'fal' });
+ expect(VIDEO_GEN_MODES).toEqual(['local', 'grok', 'fal']);
+ expect(CLOUD_VIDEO_GEN_MODES).toEqual(['grok', 'fal']);
expect([VIDEO_GEN_MODE, VIDEO_GEN_MODES, CLOUD_VIDEO_GEN_MODES].every(Object.isFrozen)).toBe(true);
});
});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 2a7463d17b..555a1a32a1 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1644,6 +1644,11 @@ export const videoGenSettingsSchema = z.object({
// POST /api/video-gen/model-terms; typed here so a Settings save can't put
// junk where the render gate reads authorization from.
acceptedModelTerms: z.array(z.string().trim().min(1).max(128)).max(50).optional(),
+ // fal.ai queue REST provider (#6213) — settings-stored key wins over the
+ // FAL_KEY env var (same precedence as loras.js's Civitai key).
+ fal: z.object({
+ apiKey: z.preprocess((v) => (v === '' ? undefined : v), z.string().trim().max(200).optional()),
+ }).optional(),
});
// POST /api/video-gen/model-terms — record (or withdraw) the acknowledgement of
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 659dea1dac..321d442882 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -243,12 +243,12 @@ export const LOCAL_ONLY_VIDEO_PARAMS = Object.freeze({
});
const generateBodySchema = z.object({
- // Render backend: the local runtimes (default) or the Grok Build CLI's
- // image-first image_to_video flow (#2859 phase 2). Grok ignores the
- // local-only knobs below; it reads prompt/negativePrompt, width/height
- // (mapped to an aspect ratio), sourceImageFile/sourceImage, and
- // grokDuration.
- backend: z.enum(['local', 'grok']).optional(),
+ // Render backend: the local runtimes (default), the Grok Build CLI's
+ // image-first image_to_video flow (#2859 phase 2), or fal.ai's queue REST
+ // API (#6213). Grok and fal both ignore the local-only knobs below; they
+ // read prompt/negativePrompt, width/height (mapped to an aspect ratio),
+ // sourceImageFile/sourceImage, and their own duration field.
+ backend: z.enum(['local', 'grok', 'fal']).optional(),
// Grok image_to_video clip length in seconds — the shared schema (see
// lib/grokVideoClip.js for which lengths grok actually delivers). Multipart
// bodies arrive as strings, so coerce first.
@@ -256,6 +256,14 @@ const generateBodySchema = z.object({
(v) => (v == null || v === '' ? undefined : Number(v)),
grokVideoDurationSchema.optional(),
),
+ // fal.ai model id (e.g. 'fal-ai/minimax/hailuo-02/standard/text-to-video')
+ // and clip duration in seconds — loosely validated since fal's own model
+ // catalog, not PortOS, owns the set of valid ids/durations per model.
+ falModelId: z.string().min(1).max(200).optional(),
+ falDuration: z.preprocess(
+ (v) => (v == null || v === '' ? undefined : Number(v)),
+ optionalNum(1, 60, 'falDuration'),
+ ),
prompt: z.string().min(1).max(8000),
negativePrompt: z.string().max(8000).optional(),
modelId: z.string().max(64).optional(),
diff --git a/server/services/fableLoom/production.js b/server/services/fableLoom/production.js
index e13152477b..549b20e2db 100644
--- a/server/services/fableLoom/production.js
+++ b/server/services/fableLoom/production.js
@@ -469,6 +469,12 @@ function resolveVideoBackend(settings, render, recordedConditioning = null) {
code: 'GROK_VIDEO_DISABLED',
});
}
+ if (requested === VIDEO_GEN_MODE.FAL && mode !== VIDEO_GEN_MODE.FAL) {
+ throw new ServerError('No fal.ai API key configured — set it in Settings → Video Gen first', {
+ status: 400,
+ code: 'FAL_VIDEO_DISABLED',
+ });
+ }
return mode;
}
@@ -606,7 +612,9 @@ async function prepareVideoJob(run, asset) {
backend,
model: backend === VIDEO_GEN_MODE.LOCAL
? model
- : { id: 'grok-video', supportedModes: ['image'] },
+ : backend === VIDEO_GEN_MODE.FAL
+ ? { id: 'fal-video', supportedModes: ['text', 'image'] }
+ : { id: 'grok-video', supportedModes: ['image'] },
});
const requestedSourceImagePath = imageInputForNode(run, asset);
const conditioned = await conditionRequest(run, asset, 'video', capability, requestedSourceImagePath);
@@ -653,6 +661,25 @@ async function prepareVideoJob(run, asset) {
};
}
+ if (backend === VIDEO_GEN_MODE.FAL) {
+ return {
+ kind: 'video',
+ provider: backend,
+ modelId: recordedConditioning?.capability?.modelId || null,
+ modelRevision: capability.modelRevision || null,
+ params: {
+ mode: VIDEO_GEN_MODE.FAL,
+ videoMode: sourceImagePath ? 'image' : 'text',
+ prompt: conditioned?.prompt || asset.prompt,
+ negativePrompt: conditioned?.negativePrompt || '',
+ ...replayParameters,
+ sourceImagePath,
+ visualConditioning: conditioned?.visualConditioning || null,
+ fableLoom: productionTag(run, asset),
+ },
+ };
+ }
+
const cloud = resolveRenderTargetConfig(settings, RENDER_TARGET.FABLELOOM_PRODUCTION, {
mode: IMAGE_GEN_MODE.GROK,
model: recordedConditioning?.capability?.modelId || null,
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 1dbaa92dad..1b1d0211e7 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -45,6 +45,7 @@ import { trainingEvents } from '../loraTraining/events.js';
import { audioGenEvents } from '../audioGen/events.js';
import { getSettings } from '../settings.js';
import { IMAGE_GEN_MODE, CLOUD_IMAGE_GEN_MODES } from '../imageGen/modes.js';
+import { VIDEO_GEN_MODE } from '../../lib/generationModes.js';
import { REMOTE_MEDIA_MODULES, isRemoteMediaJob } from './remoteMediaJob.js';
import { routedJobParams } from '../federatedMedia/routedJobParams.js';
@@ -57,7 +58,7 @@ import { routedJobParams } from '../federatedMedia/routedJobParams.js';
// renders combined).
const isCloudImageJob = (j) =>
(j.kind === 'image' && CLOUD_IMAGE_GEN_MODES.includes(j.params?.mode))
- || (j.kind === 'video' && j.params?.mode === IMAGE_GEN_MODE.GROK);
+ || (j.kind === 'video' && (j.params?.mode === IMAGE_GEN_MODE.GROK || j.params?.mode === VIDEO_GEN_MODE.FAL));
// The federated-kind map and its predicate live in ./remoteMediaJob.js so light
// consumers (sanitizeJob, route handlers) can ask "is this routed?" without
@@ -161,6 +162,7 @@ function getGenModuleForJob(job) {
// machine.
if (isRemoteMediaJob(job)) return REMOTE_MEDIA_MODULES[job.kind]();
if (job.kind === 'video' && job.params?.mode === IMAGE_GEN_MODE.GROK) return import('../videoGen/grok.js');
+ if (job.kind === 'video' && job.params?.mode === VIDEO_GEN_MODE.FAL) return import('../videoGen/fal.js');
if (job.kind === 'video') return import('../videoGen/local.js');
if (job.kind === 'training') return import('../loraTraining/index.js');
if (job.kind === 'audio') return import('../audioGen/local.js');
@@ -195,7 +197,7 @@ async function resolveLiveParams(job, safeParams) {
// mflux training runs in the same venv as local image renders, so the
// live settings pythonPath wins there too. flux2 training resolves its
// own venv (resolveFlux2Python) inside runTraining — skip it here.
- const usesLocalPython = (job.kind === 'video' && job.params?.mode !== IMAGE_GEN_MODE.GROK)
+ const usesLocalPython = (job.kind === 'video' && job.params?.mode !== IMAGE_GEN_MODE.GROK && job.params?.mode !== VIDEO_GEN_MODE.FAL)
|| (job.kind === 'image' && !CLOUD_IMAGE_GEN_MODES.includes(job.params?.mode))
|| (job.kind === 'training' && job.params?.runtime === 'mflux');
if (!usesLocalPython) return;
diff --git a/server/services/videoGen/fal.js b/server/services/videoGen/fal.js
new file mode 100644
index 0000000000..cc8bdffbf0
--- /dev/null
+++ b/server/services/videoGen/fal.js
@@ -0,0 +1,273 @@
+/**
+ * Video Gen — fal.ai queue REST API provider (#6213).
+ *
+ * FableLoom already talks to fal.ai's free `minimax-h3-max` web tool through
+ * brittle Playwright CDP automation (`services/fableLoom/falVideoAutomation.js`)
+ * that breaks on CAPTCHAs, cookie modals, and DOM changes. This module is a
+ * first-class MediaGen video backend that instead calls fal.ai's metered
+ * queue REST API directly with `FAL_KEY` — no browser required. It mirrors
+ * `videoGen/grok.js`'s job-map/SSE contract (cloud lane, no local child
+ * process) so `mediaJobQueue` can dispatch to it the same way.
+ *
+ * Flow: POST the prompt (and an optional base64-encoded source image) to
+ * `queue.fal.run/{model}`, poll the returned status URL until COMPLETED, then
+ * download the resulting MP4 and hand it to the shared `finalizeGeneratedVideo`
+ * helper — same streaming optimization, thumbnail, and history entry as every
+ * other video backend.
+ */
+
+import { randomUUID } from 'crypto';
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { ensureDir, PATHS } from '../../lib/fileUtils.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';
+import { detectImageFormat } from '../../lib/mimeTypes.js';
+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
+import { videoGenEvents } from './events.js';
+import { finalizeGeneratedVideo } from './generateVideoHelpers.js';
+import { mutateVideoHistory } from './history.js';
+import { getSettings } from '../settings.js';
+
+export const FAL_QUEUE_BASE = 'https://queue.fal.run';
+
+// The two models the issue names, one text-first and one image-first. Both
+// accept `prompt`; the image-to-video variant additionally takes `image_url`.
+export const FAL_DEFAULT_TEXT_MODEL = 'fal-ai/minimax/hailuo-02/standard/text-to-video';
+export const FAL_DEFAULT_IMAGE_MODEL = 'fal-ai/minimax/hailuo-02/standard/image-to-video';
+
+const FAL_SUBMIT_TIMEOUT_MS = 30_000;
+const FAL_POLL_TIMEOUT_MS = 15_000;
+const FAL_POLL_INTERVAL_MS = 3000;
+const FAL_DOWNLOAD_TIMEOUT_MS = 5 * 60 * 1000;
+// A cloud queue render can sit behind other tenants' jobs before it starts —
+// generously bounded, same order of magnitude as grok's image-first cap.
+const FAL_RENDER_TIMEOUT_MS = (() => {
+ const n = Number(process.env.FAL_VIDEO_TIMEOUT_MS);
+ return Number.isFinite(n) && n > 0 ? n : 20 * 60 * 1000;
+})();
+
+// Per-job state — keyed by jobId (cloud lane allows parallel renders). Same
+// client shape as videoGen/grok.js so attachSseClient/broadcastSse work.
+const jobs = new Map();
+// Tracks the fal.ai request so cancel() can both stop our poll loop and ask
+// fal.ai to cancel the queued/running render.
+const activeRequests = new Map();
+const activeJobs = new Map();
+
+export const getActiveJob = () => {
+ const entries = [...activeJobs.values()];
+ return entries.length ? entries[entries.length - 1] : null;
+};
+
+export const attachSseClient = (jobId, res) => attachSse(jobs, jobId, res);
+
+/**
+ * Resolve the fal.ai API key: settings override, else the `FAL_KEY` env var
+ * (same settings-wins-over-env precedence as `loras.js`'s Civitai key).
+ */
+export function resolveFalApiKey(settings) {
+ const fromSettings = (settings?.videoGen?.fal?.apiKey || '').trim();
+ if (fromSettings) return fromSettings;
+ const fromEnv = (process.env.FAL_KEY || '').trim();
+ return fromEnv || null;
+}
+
+export const cancel = (jobId) => {
+ if (!jobId) {
+ throw new Error("videoGen/fal.cancel requires a jobId — use cancelAll() to terminate every in-flight render");
+ }
+ const entry = activeRequests.get(jobId);
+ if (!entry) return false;
+ entry.aborted = true;
+ if (entry.cancelUrl && entry.apiKey) {
+ fetchWithTimeout(entry.cancelUrl, {
+ method: 'PUT',
+ headers: { Authorization: `Key ${entry.apiKey}` },
+ }, FAL_POLL_TIMEOUT_MS).catch(() => {});
+ }
+ return true;
+};
+
+export const cancelAll = () => {
+ const ids = [...activeRequests.keys()];
+ if (ids.length === 0) return false;
+ for (const id of ids) cancel(id);
+ return true;
+};
+
+async function toDataUri(imagePath) {
+ const buf = await readFile(imagePath);
+ const detected = detectImageFormat(buf);
+ const mime = detected?.mime || 'image/png';
+ return `data:${mime};base64,${buf.toString('base64')}`;
+}
+
+function buildRequestBody({ prompt, duration, aspectRatio, imageDataUri }) {
+ const body = { prompt: prompt.trim() };
+ if (duration) body.duration = String(duration);
+ if (aspectRatio) body.aspect_ratio = aspectRatio;
+ if (imageDataUri) body.image_url = imageDataUri;
+ return body;
+}
+
+async function submitFalJob({ apiKey, modelId, body }) {
+ const res = await fetchWithTimeout(`${FAL_QUEUE_BASE}/${modelId}`, {
+ method: 'POST',
+ headers: { Authorization: `Key ${apiKey}`, 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ }, FAL_SUBMIT_TIMEOUT_MS);
+ const payload = await res.json().catch(() => null);
+ if (!res.ok || !payload?.request_id) {
+ const reason = payload?.detail ? JSON.stringify(payload.detail) : `HTTP ${res.status}`;
+ throw new ServerError(`fal.ai rejected the request: ${reason}`, { status: 502, code: 'FAL_SUBMIT_FAILED' });
+ }
+ return payload;
+}
+
+async function pollFalStatus({ statusUrl, apiKey }) {
+ const res = await fetchWithTimeout(statusUrl, {
+ headers: { Authorization: `Key ${apiKey}` },
+ }, FAL_POLL_TIMEOUT_MS);
+ if (!res.ok) throw new ServerError(`fal.ai status check failed: HTTP ${res.status}`, { status: 502, code: 'FAL_STATUS_FAILED' });
+ return res.json();
+}
+
+async function fetchFalResult({ responseUrl, apiKey }) {
+ const res = await fetchWithTimeout(responseUrl, {
+ headers: { Authorization: `Key ${apiKey}` },
+ }, FAL_POLL_TIMEOUT_MS);
+ const payload = await res.json().catch(() => null);
+ if (!res.ok || !payload) {
+ throw new ServerError('fal.ai did not return a usable result', { status: 502, code: 'FAL_RESULT_FAILED' });
+ }
+ return payload;
+}
+
+export async function generateVideo({
+ apiKey: providedApiKey, settings, modelId: requestedModelId,
+ prompt = '', negativePrompt, duration, aspectRatio,
+ sourceImagePath = null, jobId: providedJobId = null,
+}) {
+ await ensureDir(PATHS.videos);
+ const renderStartedAtMs = Date.now();
+
+ if (!prompt?.trim()) {
+ throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ // The queue only persists the resolved provider CONFIG a job needs (mirrors
+ // grokPath on the grok lane) — never a secret — so the key is re-resolved
+ // from live settings here, exactly like mediaJobQueue's own pythonPath
+ // re-resolution on every dispatch, rather than threaded through job.params
+ // where it would sit in plaintext in media-jobs.json.
+ const effectiveSettings = settings || (providedApiKey ? null : await getSettings().catch(() => null));
+ const apiKey = providedApiKey || resolveFalApiKey(effectiveSettings);
+ if (!apiKey) {
+ throw new ServerError('No fal.ai API key configured — set it in Settings > Video Gen or the FAL_KEY env var', { status: 400, code: 'FAL_NOT_CONFIGURED' });
+ }
+
+ const modelId = requestedModelId || (sourceImagePath ? FAL_DEFAULT_IMAGE_MODEL : FAL_DEFAULT_TEXT_MODEL);
+ const jobId = providedJobId || randomUUID();
+ const filename = `${jobId}.mp4`;
+ const outputPath = join(PATHS.videos, filename);
+
+ const meta = {
+ id: jobId,
+ prompt: prompt.trim(),
+ negativePrompt: negativePrompt || '',
+ modelId: `fal:${modelId}`,
+ ...(duration ? { duration } : {}),
+ ...(aspectRatio ? { aspectRatio } : {}),
+ filename,
+ createdAt: new Date().toISOString(),
+ mode: sourceImagePath ? 'image' : 'text',
+ };
+ const job = { ...meta, clients: [], status: 'running', renderStartedAtMs };
+ jobs.set(jobId, job);
+
+ console.log(`🎬 Generating video [${jobId.slice(0, 8)}] fal (${modelId}): ${prompt.slice(0, 60)}…`);
+ videoGenEvents.emit('started', { generationId: jobId, totalSteps: 1, ...meta });
+ activeJobs.set(jobId, { ...meta, generationId: jobId, totalSteps: 1, step: 0, progress: 0 });
+ broadcastSse(job, { type: 'status', message: 'Submitting to fal.ai…' });
+
+ runFalVideo(job, jobId, { apiKey, modelId, prompt, duration, aspectRatio, sourceImagePath, outputPath, filename, meta })
+ .catch((err) => {
+ console.log(`❌ fal video run failed [${jobId.slice(0, 8)}]: ${err?.message}`);
+ });
+
+ return {
+ jobId, filename, path: `/data/videos/${filename}`, generationId: jobId,
+ mode: 'fal',
+ status: 'running',
+ };
+}
+
+async function runFalVideo(job, jobId, { apiKey, modelId, prompt, duration, aspectRatio, sourceImagePath, outputPath, filename, meta }) {
+ const entry = { apiKey, aborted: false, cancelUrl: null };
+ activeRequests.set(jobId, entry);
+ const deadline = Date.now() + FAL_RENDER_TIMEOUT_MS;
+ try {
+ const imageDataUri = sourceImagePath ? await toDataUri(sourceImagePath) : null;
+ const body = buildRequestBody({ prompt, duration, aspectRatio, imageDataUri });
+ const submitted = await submitFalJob({ apiKey, modelId, body });
+ entry.cancelUrl = submitted.cancel_url || `${FAL_QUEUE_BASE}/${modelId}/requests/${submitted.request_id}/cancel`;
+ const statusUrl = submitted.status_url || `${FAL_QUEUE_BASE}/${modelId}/requests/${submitted.request_id}/status`;
+ const responseUrl = submitted.response_url || `${FAL_QUEUE_BASE}/${modelId}/requests/${submitted.request_id}`;
+
+ while (Date.now() < deadline) {
+ if (entry.aborted) return finalizeCanceled(job, jobId);
+ videoGenEvents.emit('activity', { generationId: jobId });
+ const status = await pollFalStatus({ statusUrl, apiKey });
+ if (status.status === 'COMPLETED') break;
+ if (status.status === 'ERROR') {
+ return finalizeError(job, jobId, `fal.ai render failed: ${status.error || 'unknown error'}`);
+ }
+ broadcastSse(job, { type: 'status', message: status.status === 'IN_PROGRESS' ? 'Rendering…' : 'Queued…' });
+ await new Promise((r) => setTimeout(r, FAL_POLL_INTERVAL_MS));
+ }
+ if (entry.aborted) return finalizeCanceled(job, jobId);
+ if (Date.now() >= deadline) {
+ return finalizeError(job, jobId, `fal.ai did not finish within ${Math.round(FAL_RENDER_TIMEOUT_MS / 1000)}s`);
+ }
+
+ const result = await fetchFalResult({ responseUrl, apiKey });
+ const videoUrl = result?.video?.url || result?.video_url || result?.output?.video?.url;
+ if (!videoUrl) {
+ return finalizeError(job, jobId, 'fal.ai completed but returned no video URL');
+ }
+
+ broadcastSse(job, { type: 'status', message: 'Downloading video…' });
+ const videoRes = await fetchWithTimeout(videoUrl, {}, FAL_DOWNLOAD_TIMEOUT_MS);
+ if (!videoRes.ok) {
+ return finalizeError(job, jobId, `fal.ai video download failed: HTTP ${videoRes.status}`);
+ }
+ const buffer = Buffer.from(await videoRes.arrayBuffer());
+ await writeFile(outputPath, buffer);
+
+ activeRequests.delete(jobId);
+ activeJobs.delete(jobId);
+ await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed: null, mutateHistory: mutateVideoHistory });
+ closeJobAfterDelay(jobs, jobId);
+ } catch (err) {
+ finalizeError(job, jobId, `fal.ai video generation failed: ${err?.message || err}`);
+ }
+}
+
+const finalizeCanceled = (job, jobId) => finalizeError(job, jobId, 'Canceled', { force: true });
+
+const finalizeError = (job, jobId, reason, { force = false } = {}) => {
+ if (!force && (job.status === 'error' || job.status === 'complete')) return;
+ activeRequests.delete(jobId);
+ activeJobs.delete(jobId);
+ job.status = 'error';
+ console.log(`❌ fal video generation failed [${jobId.slice(0, 8)}]: ${reason.split('\n')[0]}`);
+ broadcastSse(job, { type: 'error', error: reason });
+ videoGenEvents.emit('failed', { generationId: jobId, error: reason });
+ closeJobAfterDelay(jobs, jobId);
+};
+
+// Test-only handles.
+export const _internals = {
+ buildRequestBody,
+ toDataUri,
+};
diff --git a/server/services/videoGen/fal.test.js b/server/services/videoGen/fal.test.js
new file mode 100644
index 0000000000..1cccc988d5
--- /dev/null
+++ b/server/services/videoGen/fal.test.js
@@ -0,0 +1,188 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { mkdir, rm, readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { tmpdir } from 'os';
+
+const TEST_ROOT = join(tmpdir(), `portos-fal-video-test-${process.pid}-${Date.now()}`);
+const FAKE_VIDEOS_DIR = join(TEST_ROOT, 'data-videos');
+const FAKE_DATA_DIR = join(TEST_ROOT, 'data');
+
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ actual.PATHS.videos = FAKE_VIDEOS_DIR;
+ actual.PATHS.data = FAKE_DATA_DIR;
+ return {
+ ...actual,
+ ensureDir: vi.fn(async (dir) => mkdir(dir, { recursive: true })),
+ };
+});
+
+vi.mock('../../lib/ffmpeg.js', async () => {
+ const actual = await vi.importActual('../../lib/ffmpeg.js');
+ return {
+ ...actual,
+ optimizeForStreaming: vi.fn(async () => {}),
+ generateThumbnail: vi.fn(async (_p, jobId) => `${jobId}.jpg`),
+ };
+});
+
+const getSettingsMock = vi.fn();
+vi.mock('../settings.js', () => ({ getSettings: getSettingsMock }));
+
+const fal = await import('./fal.js');
+const { videoGenEvents } = await import('./events.js');
+const { loadHistory } = await import('./history.js');
+
+const flush = () => new Promise((r) => setTimeout(r, 10));
+
+const jsonResponse = (body, ok = true, status = 200) => ({
+ ok, status,
+ json: async () => body,
+});
+
+beforeEach(async () => {
+ videoGenEvents.removeAllListeners();
+ await rm(TEST_ROOT, { recursive: true, force: true }).catch(() => {});
+ await mkdir(FAKE_DATA_DIR, { recursive: true });
+ getSettingsMock.mockReset().mockResolvedValue({});
+ vi.restoreAllMocks();
+});
+
+afterEach(async () => {
+ await rm(TEST_ROOT, { recursive: true, force: true }).catch(() => {});
+});
+
+describe('videoGen/fal — resolveFalApiKey', () => {
+ it('prefers the settings-stored key over the FAL_KEY env var', () => {
+ const prevEnv = process.env.FAL_KEY;
+ process.env.FAL_KEY = 'env-key';
+ expect(fal.resolveFalApiKey({ videoGen: { fal: { apiKey: ' settings-key ' } } })).toBe('settings-key');
+ if (prevEnv === undefined) delete process.env.FAL_KEY; else process.env.FAL_KEY = prevEnv;
+ });
+
+ it('falls back to FAL_KEY when settings carry no key', () => {
+ const prevEnv = process.env.FAL_KEY;
+ process.env.FAL_KEY = 'env-key';
+ expect(fal.resolveFalApiKey({})).toBe('env-key');
+ if (prevEnv === undefined) delete process.env.FAL_KEY; else process.env.FAL_KEY = prevEnv;
+ });
+
+ it('returns null when neither settings nor env carry a key', () => {
+ const prevEnv = process.env.FAL_KEY;
+ delete process.env.FAL_KEY;
+ expect(fal.resolveFalApiKey({})).toBeNull();
+ if (prevEnv !== undefined) process.env.FAL_KEY = prevEnv;
+ });
+});
+
+describe('videoGen/fal — _internals.buildRequestBody', () => {
+ it('includes only the fields that were actually supplied', () => {
+ expect(fal._internals.buildRequestBody({ prompt: ' a fox running ' })).toEqual({ prompt: 'a fox running' });
+ expect(fal._internals.buildRequestBody({
+ prompt: 'pan', duration: 10, aspectRatio: '16:9', imageDataUri: 'data:image/png;base64,AA==',
+ })).toEqual({
+ prompt: 'pan', duration: '10', aspect_ratio: '16:9', image_url: 'data:image/png;base64,AA==',
+ });
+ });
+});
+
+describe('videoGen/fal — generateVideo', () => {
+ it('submits, polls to completion, downloads the result, and finalizes history', async () => {
+ const requestId = 'req-123';
+ const statusUrl = `https://queue.fal.run/fal-ai/x/requests/${requestId}/status`;
+ const responseUrl = `https://queue.fal.run/fal-ai/x/requests/${requestId}`;
+ const fetchMock = vi.fn(async (url, opts) => {
+ if (url === 'https://queue.fal.run/fal-ai/x') {
+ expect(opts.method).toBe('POST');
+ expect(JSON.parse(opts.body)).toEqual({ prompt: 'a fox running' });
+ return jsonResponse({ request_id: requestId, status_url: statusUrl, response_url: responseUrl });
+ }
+ if (url === statusUrl) return jsonResponse({ status: 'COMPLETED' });
+ if (url === responseUrl) return jsonResponse({ video: { url: 'https://cdn.fal.ai/out.mp4' } });
+ if (url === 'https://cdn.fal.ai/out.mp4') {
+ // Buffer.from(str).buffer is the pooled backing ArrayBuffer (larger
+ // than the string, and may carry unrelated pool bytes) — Uint8Array.from
+ // allocates a fresh, exactly-sized buffer instead.
+ return { ok: true, status: 200, arrayBuffer: async () => Uint8Array.from(Buffer.from('fake-mp4-bytes')).buffer };
+ }
+ throw new Error(`unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ const job = await fal.generateVideo({ apiKey: 'test-key', modelId: 'fal-ai/x', prompt: 'a fox running' });
+ expect(job.mode).toBe('fal');
+ expect(job.status).toBe('running');
+ expect(job.filename).toMatch(/^[0-9a-f-]{36}\.mp4$/);
+
+ // Let the async run loop (submit → poll → download → finalize, including
+ // the serialized history-write tail) settle.
+ const outputPath = join(FAKE_VIDEOS_DIR, job.filename);
+ let history = [];
+ for (let i = 0; i < 50 && history.length === 0; i += 1) {
+ await flush();
+ history = await loadHistory();
+ }
+
+ const written = await readFile(outputPath);
+ expect(written.toString()).toBe('fake-mp4-bytes');
+
+ expect(history[0].id).toBe(job.jobId);
+ expect(history[0].modelId).toBe('fal:fal-ai/x');
+ vi.unstubAllGlobals();
+ });
+
+ it('resolves the API key from live settings when the caller supplies neither apiKey nor settings (the mediaJobQueue dispatch shape)', async () => {
+ getSettingsMock.mockResolvedValue({ videoGen: { fal: { apiKey: 'live-key' } } });
+ const fetchMock = vi.fn(async (url, opts) => {
+ if (url === 'https://queue.fal.run/fal-ai/x') {
+ expect(opts.headers.Authorization).toBe('Key live-key');
+ return jsonResponse({ request_id: 'r1', status_url: 'https://queue.fal.run/fal-ai/x/requests/r1/status', response_url: 'https://queue.fal.run/fal-ai/x/requests/r1' });
+ }
+ if (url === 'https://queue.fal.run/fal-ai/x/requests/r1/status') return jsonResponse({ status: 'COMPLETED' });
+ if (url === 'https://queue.fal.run/fal-ai/x/requests/r1') return jsonResponse({ video: { url: 'https://cdn.fal.ai/out.mp4' } });
+ if (url === 'https://cdn.fal.ai/out.mp4') {
+ return { ok: true, status: 200, arrayBuffer: async () => Uint8Array.from(Buffer.from('bytes')).buffer };
+ }
+ throw new Error(`unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ // No apiKey, no settings — exactly what mediaJobQueue's runJob spreads
+ // job.params into (job params never carry the secret; see the comment in
+ // generateVideo).
+ const job = await fal.generateVideo({ modelId: 'fal-ai/x', prompt: 'x' });
+ for (let i = 0; i < 50 && fetchMock.mock.calls.length < 1; i += 1) await flush();
+ await flush();
+ expect(getSettingsMock).toHaveBeenCalled();
+ expect(job.status).toBe('running');
+ vi.unstubAllGlobals();
+ });
+
+ it('rejects when no API key is configured', async () => {
+ const prevEnv = process.env.FAL_KEY;
+ delete process.env.FAL_KEY;
+ await expect(fal.generateVideo({ prompt: 'x', settings: {} })).rejects.toThrow(/No fal\.ai API key/);
+ if (prevEnv !== undefined) process.env.FAL_KEY = prevEnv;
+ });
+
+ it('emits failed and does not write output when fal.ai reports ERROR', async () => {
+ const requestId = 'req-err';
+ const statusUrl = `https://queue.fal.run/fal-ai/x/requests/${requestId}/status`;
+ const fetchMock = vi.fn(async (url) => {
+ if (url === 'https://queue.fal.run/fal-ai/x') {
+ return jsonResponse({ request_id: requestId, status_url: statusUrl, response_url: `https://queue.fal.run/fal-ai/x/requests/${requestId}` });
+ }
+ if (url === statusUrl) return jsonResponse({ status: 'ERROR', error: 'model overloaded' });
+ throw new Error(`unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ const failed = vi.fn();
+ videoGenEvents.on('failed', failed);
+ const job = await fal.generateVideo({ apiKey: 'test-key', modelId: 'fal-ai/x', prompt: 'x' });
+ for (let i = 0; i < 20 && failed.mock.calls.length < 1; i += 1) await flush();
+
+ expect(failed).toHaveBeenCalledWith(expect.objectContaining({ generationId: job.jobId, error: expect.stringContaining('model overloaded') }));
+ vi.unstubAllGlobals();
+ });
+});
diff --git a/server/services/videoGen/modes.js b/server/services/videoGen/modes.js
index 769da8fd56..3afc388c35 100644
--- a/server/services/videoGen/modes.js
+++ b/server/services/videoGen/modes.js
@@ -41,6 +41,12 @@ export { CLOUD_VIDEO_GEN_MODES, VIDEO_GEN_MODE, VIDEO_GEN_MODES };
*/
export function isVideoModeUsable(settings, mode) {
if (mode === VIDEO_GEN_MODE.GROK) return settings?.imageGen?.grok?.enabled === true;
+ // fal.ai is a metered REST API rather than an opt-in-toggle CLI, so
+ // usability is gated on an API key actually being configured (settings or
+ // FAL_KEY env) — see videoGen/fal.js#resolveFalApiKey.
+ if (mode === VIDEO_GEN_MODE.FAL) {
+ return Boolean((settings?.videoGen?.fal?.apiKey || '').trim() || (process.env.FAL_KEY || '').trim());
+ }
return mode === VIDEO_GEN_MODE.LOCAL;
}
diff --git a/server/services/videoGen/modes.test.js b/server/services/videoGen/modes.test.js
index 69514f6e79..74427aba50 100644
--- a/server/services/videoGen/modes.test.js
+++ b/server/services/videoGen/modes.test.js
@@ -11,8 +11,8 @@ describe('VIDEO_GEN_MODE', () => {
// rather than re-typing is what keeps a schema from drifting from dispatch.
expect(VIDEO_GEN_MODE.LOCAL).toBe(IMAGE_GEN_MODE.LOCAL);
expect(VIDEO_GEN_MODE.GROK).toBe(IMAGE_GEN_MODE.GROK);
- expect(VIDEO_GEN_MODES).toEqual(['local', 'grok']);
- expect(CLOUD_VIDEO_GEN_MODES).toEqual(['grok']);
+ expect(VIDEO_GEN_MODES).toEqual(['local', 'grok', 'fal']);
+ expect(CLOUD_VIDEO_GEN_MODES).toEqual(['grok', 'fal']);
expect(Object.isFrozen(VIDEO_GEN_MODE)).toBe(true);
});
});
@@ -33,6 +33,16 @@ describe('isVideoModeUsable', () => {
expect(isVideoModeUsable({}, 'external')).toBe(false);
expect(isVideoModeUsable({}, undefined)).toBe(false);
});
+
+ it('gates fal on a configured API key, settings or env', () => {
+ expect(isVideoModeUsable({ videoGen: { fal: { apiKey: 'key' } } }, 'fal')).toBe(true);
+ expect(isVideoModeUsable({ videoGen: { fal: { apiKey: ' ' } } }, 'fal')).toBe(false);
+ expect(isVideoModeUsable({}, 'fal')).toBe(false);
+ const prevEnv = process.env.FAL_KEY;
+ process.env.FAL_KEY = 'env-key';
+ expect(isVideoModeUsable({}, 'fal')).toBe(true);
+ if (prevEnv === undefined) delete process.env.FAL_KEY; else process.env.FAL_KEY = prevEnv;
+ });
});
describe('resolveVideoMode', () => {
diff --git a/server/services/videoGen/prepareParams.js b/server/services/videoGen/prepareParams.js
index 6559813578..b6e1ad06f1 100644
--- a/server/services/videoGen/prepareParams.js
+++ b/server/services/videoGen/prepareParams.js
@@ -50,7 +50,7 @@ import {
import { getSettings } from '../settings.js';
import { getProject as getMusicVideoProject } from '../musicVideo/projects.js';
import { getTrack } from '../tracks/index.js';
-import { VIDEO_GEN_MODE, resolveVideoMode } from './modes.js';
+import { VIDEO_GEN_MODE, resolveVideoMode, isVideoModeUsable } from './modes.js';
import { isDefaultI2vReferenceMode } from '../../lib/videoReferenceModes.js';
import {
listVideoModels,
@@ -350,7 +350,7 @@ export async function prepareVideoGenParams({ body, uploads, localOnlyParamKeys
// shared with services/videoGen/local.js so the route and worker stay
// in sync.
const runtimeBringsOwnVenv = effectiveModel && BYOV_VIDEO_RUNTIMES.has(effectiveModel.runtime);
- if (!pythonPath && !runtimeBringsOwnVenv && backend !== 'grok') {
+ if (!pythonPath && !runtimeBringsOwnVenv && backend !== VIDEO_GEN_MODE.GROK && backend !== VIDEO_GEN_MODE.FAL) {
await cleanupMultipartTemp(uploads);
throw new ServerError(
'Local video generation is not configured (settings.imageGen.local.pythonPath is missing).',
@@ -472,10 +472,10 @@ async function resolvePreparedParams({
// plain grok render with the reference clip silently dropped. The client's
// mode bar snaps grok back to text/image, but reject explicitly so a direct
// caller gets an error instead of a wrong-looking clip.
- if (body.backend === 'grok') {
+ if (body.backend === VIDEO_GEN_MODE.GROK || body.backend === VIDEO_GEN_MODE.FAL) {
await cleanupStaged();
throw new ServerError(
- `${icSpec.label} mode runs on the local ltx2 runtime — it isn't available on the Grok backend.`,
+ `${icSpec.label} mode runs on the local ltx2 runtime — it isn't available on the ${body.backend} backend.`,
{ status: 400, code: 'IC_LORA_REQUIRES_LOCAL_BACKEND' },
);
}
@@ -760,6 +760,28 @@ async function resolvePreparedParams({
};
}
+ // fal.ai short-circuit (#6213): mirrors the grok branch above — the queue
+ // REST provider reads only prompt/dims/source-image/duration, so every
+ // local-runtime knob past this point is irrelevant to it.
+ if (backend === VIDEO_GEN_MODE.FAL) {
+ if (!isVideoModeUsable(settings, VIDEO_GEN_MODE.FAL)) {
+ await cleanupStaged();
+ throw new ServerError(
+ 'No fal.ai API key configured — set it in Settings → Video Gen (or the FAL_KEY env var) first',
+ { status: 400, code: 'FAL_NOT_CONFIGURED' },
+ );
+ }
+ return {
+ backend,
+ fal: settings.videoGen?.fal || {},
+ effectiveModel: { id: 'fal', supportedModes: ['text', 'image'] },
+ sourceImagePath,
+ uploadedTempPath,
+ discardSourceImage,
+ cleanupStaged,
+ };
+ }
+
if (uploads.lastImage) {
lastImagePath = await stageUploadDurable(uploads.lastImage, 'last');
extraUploadedTempPaths.push(lastImagePath);
diff --git a/server/services/videoGen/submitJob.js b/server/services/videoGen/submitJob.js
index 2082d05643..017a104e66 100644
--- a/server/services/videoGen/submitJob.js
+++ b/server/services/videoGen/submitJob.js
@@ -19,6 +19,7 @@ import {
fableLoomVideoCapabilities,
} from '../fableLoom/visualConditioning.js';
import { IMAGE_GEN_MODE } from '../imageGen/modes.js';
+import { VIDEO_GEN_MODE } from './modes.js';
import { enqueueJob } from '../mediaJobQueue/index.js';
import {
cleanupMultipartTemp,
@@ -115,7 +116,9 @@ const submitValidatedVideoGenJob = async (body, uploads) => {
if (body.fableLoom) {
const conditioningModel = backend === IMAGE_GEN_MODE.GROK
? { id: 'grok-video', supportedModes: ['image'] }
- : prepared.effectiveModel;
+ : backend === VIDEO_GEN_MODE.FAL
+ ? { id: 'fal-video', supportedModes: ['text', 'image'] }
+ : prepared.effectiveModel;
const compiled = await compileFableLoomVisualRequest({
tag: body.fableLoom,
kind: 'video',
@@ -189,6 +192,33 @@ const submitValidatedVideoGenJob = async (body, uploads) => {
};
}
+ if (backend === VIDEO_GEN_MODE.FAL) {
+ const { sourceImagePath, uploadedTempPath } = prepared;
+ const { jobId, position, status } = await enqueue({
+ mode: VIDEO_GEN_MODE.FAL,
+ videoMode: sourceImagePath ? 'image' : 'text',
+ modelId: body.falModelId,
+ aspectRatio: body.visualConditioning?.render?.parameters?.aspectRatio,
+ prompt: body.prompt,
+ negativePrompt: body.negativePrompt || '',
+ duration: body.falDuration,
+ sourceImagePath,
+ uploadedTempPath,
+ ...(body.musicVideo ? { musicVideo: body.musicVideo } : {}),
+ ...(body.fableLoom ? { fableLoom: body.fableLoom } : {}),
+ ...(body.visualConditioning ? { visualConditioning: body.visualConditioning } : {}),
+ });
+ return {
+ jobId,
+ generationId: jobId,
+ filename: `${jobId}.mp4`,
+ model: 'fal',
+ mode: 'fal',
+ status,
+ position,
+ };
+ }
+
const {
pythonPath, effectiveModelId, effectiveNumFrames, mode,
sourceImagePath, lastImagePath, audioFilePath, icReferencePaths,