Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add fal.ai as an image generation backend
[._.]/ Adam Eivydbd9556263c9
diff --git a/client/src/components/imageGen/FalModelSelect.jsx b/client/src/components/imageGen/FalModelSelect.jsxnew file mode 100644index 0000000000..af84c22138--- /dev/null+++ b/client/src/components/imageGen/FalModelSelect.jsx@@ -0,0 +1,30 @@+import { FAL_IMAGE_MODEL_OPTIONS, falImageFamily } from '../../lib/imageGenBackends';++// The fal.ai image model picker. A select over the curated catalog rather than+// a text box: every id is a different price, and the server refuses an id the+// catalog does not list — a typo would otherwise only surface as a failed render.+// Either endpoint id of a family (text or /edit) selects that family's row; the+// provider picks the endpoint per render. A saved id outside the catalog (a+// hand edit, or a model a later build dropped) stays visible and selectable so+// the select never paints a pin the server is still reading as blank.+export default function FalModelSelect({+ id, value = '', onChange, defaultLabel = 'Settings default', ariaLabel, className = '', disabled = false,+}) {+ const family = falImageFamily(value);+ const selected = family ? family.textEndpoint : (value || '');+ const orphaned = selected && !family;+ return (+ <select+ id={id}+ value={selected}+ onChange={(e) => onChange(e.target.value || null)}+ aria-label={ariaLabel}+ disabled={disabled}+ className={className}+ >+ <option value="">{defaultLabel}</option>+ {orphaned && <option value={selected}>{`${selected} (not in the fal.ai catalog)`}</option>}+ {FAL_IMAGE_MODEL_OPTIONS.map((o) => <option key={o.id} value={o.id}>{o.label}</option>)}+ </select>+ );+}diff --git a/client/src/components/imageGen/ImageGenControls.jsx b/client/src/components/imageGen/ImageGenControls.jsxindex 20dd2bbfad..594bf4ce6e 100644--- a/client/src/components/imageGen/ImageGenControls.jsx+++ b/client/src/components/imageGen/ImageGenControls.jsx@@ -58,7 +58,8 @@ export default function ImageGenControls({// than shipping a control whose value the host would silently drop. No mode// check here: the host owns which backends it supplies a catalog for (see// supportsCloudModelOverride), so a second CLI backend is a caller change,- // not an edit to this shared component.+ // not an edit to this shared component. Entries are plain ids, or+ // `{ id, label }` rows for a catalog whose ids need a human label (fal.ai).cloudModels = [],cloudModel = '',onCloudModelChange,@@ -118,7 +119,10 @@ export default function ImageGenControls({<option value="">{cloudModelDefaultLabel ? `Settings default (${cloudModelDefaultLabel})` : 'Settings default'}</option>- {cloudModels.map((id) => <option key={id} value={id}>{id}</option>)}+ {cloudModels.map((m) => {+ const id = typeof m === 'string' ? m : m.id;+ return <option key={id} value={id}>{typeof m === 'string' ? m : (m.label || m.id)}</option>;+ })}</select></FormField>)}diff --git a/client/src/components/imageGen/ImageGenFormEditor.jsx b/client/src/components/imageGen/ImageGenFormEditor.jsxindex 3e92884127..7b73cfee91 100644--- a/client/src/components/imageGen/ImageGenFormEditor.jsx+++ b/client/src/components/imageGen/ImageGenFormEditor.jsx@@ -13,7 +13,9 @@ import InitImagePicker from './InitImagePicker';import LoraPicker from './LoraPicker';import ReferenceImagePicker from './ReferenceImagePicker';import { appendTriggerWords } from '../../lib/loraTriggers';-import { AGY_IMAGEGEN_DEFAULT_MODEL, IMAGE_GEN_MODE } from '../../lib/imageGenBackends';+import {+ AGY_IMAGEGEN_DEFAULT_MODEL, FAL_IMAGE_DEFAULT_MODEL, FAL_IMAGE_MODEL_OPTIONS, IMAGE_GEN_MODE, falImageFamily,+} from '../../lib/imageGenBackends';const ERROR_HEADINGS = {gated_repo: 'Model access required',@@ -36,8 +38,10 @@ export default function ImageGenFormEditor({ form, backend, generation }) {effectiveMode,isLocalMode,isAgyMode,+ isFalMode,remoteTarget,effectiveAgyModel,+ effectiveFalModel,} = backend;const {generating,@@ -226,11 +230,13 @@ export default function ImageGenFormEditor({ form, backend, generation }) {modelStatus={isLocalMode ? modelDownload.getStatus(fields.modelId) : null}onModelDownload={isLocalMode ? modelDownload.start : undefined}onModelDownloadCancel={modelDownload.cancel}- cloudModels={isAgyMode ? backend.agy.models : []}- cloudModel={effectiveAgyModel}- onCloudModelChange={fields.setAgyModel}- cloudModelLabel="Agent model"- cloudModelDefaultLabel={settings.savedAgyModel || AGY_IMAGEGEN_DEFAULT_MODEL}+ cloudModels={isAgyMode ? backend.agy.models : isFalMode ? FAL_IMAGE_MODEL_OPTIONS : []}+ cloudModel={isFalMode ? effectiveFalModel : effectiveAgyModel}+ onCloudModelChange={isFalMode ? fields.setFalModel : fields.setAgyModel}+ cloudModelLabel={isFalMode ? 'fal.ai model' : 'Agent model'}+ cloudModelDefaultLabel={isFalMode+ ? falImageFamily(settings.savedFalModel || FAL_IMAGE_DEFAULT_MODEL)?.label || FAL_IMAGE_DEFAULT_MODEL+ : settings.savedAgyModel || AGY_IMAGEGEN_DEFAULT_MODEL}/>{isAgyMode && backend.agy.error && (<p role="status" className="text-xs text-port-warning">diff --git a/client/src/components/imageGen/ImageGenHeader.jsx b/client/src/components/imageGen/ImageGenHeader.jsxindex 3f73ee0369..20a2340c12 100644--- a/client/src/components/imageGen/ImageGenHeader.jsx+++ b/client/src/components/imageGen/ImageGenHeader.jsx@@ -12,6 +12,7 @@ const CONNECTED_MODE_LABELS = {[IMAGE_GEN_MODE.CODEX]: 'codex CLI',[IMAGE_GEN_MODE.GROK]: 'grok CLI',[IMAGE_GEN_MODE.AGY]: 'agy CLI',+ [IMAGE_GEN_MODE.FAL]: 'fal.ai',};export default function ImageGenHeader({ status, backends, remix, actions }) {diff --git a/client/src/components/imageGen/ImageGenSettingsForm.jsx b/client/src/components/imageGen/ImageGenSettingsForm.jsxindex d5204eb9d8..8d8e2a831f 100644--- a/client/src/components/imageGen/ImageGenSettingsForm.jsx+++ b/client/src/components/imageGen/ImageGenSettingsForm.jsx@@ -59,6 +59,7 @@ export default function ImageGenSettingsForm({const isCodex = cfg.mode === IMAGE_GEN_MODE.CODEX;const isGrok = cfg.mode === IMAGE_GEN_MODE.GROK;const isAgy = cfg.mode === IMAGE_GEN_MODE.AGY;+ const isFal = cfg.mode === IMAGE_GEN_MODE.FAL;const isLocal = cfg.mode === IMAGE_GEN_MODE.LOCAL;const labelCls = 'block text-xs font-medium text-gray-400 mb-1';const textareaCls = '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 disabled:opacity-50 min-h-[60px]';@@ -95,6 +96,12 @@ export default function ImageGenSettingsForm({and supports text-to-image only. The model in Settings is the <em>agent</em> that drives thetool. Style fields apply; resolution maps to the nearest supported aspect ratio.</p>+ ) : isFal ? (+ <p className="text-[10px] text-gray-500 mt-1">+ fal.ai renders on the model chosen in Settings → Image Gen → fal.ai (or this surface’s+ render pin) and is billed per image. Reference images route to that model’s edit+ endpoint; resolution maps to the model’s nearest supported size.+ </p>) : null}</div>) : null;diff --git a/client/src/components/imageGen/RecordRenderPinRow.jsx b/client/src/components/imageGen/RecordRenderPinRow.jsxindex 49d9e963e2..ff5e7e3fa1 100644--- a/client/src/components/imageGen/RecordRenderPinRow.jsx+++ b/client/src/components/imageGen/RecordRenderPinRow.jsx@@ -1,4 +1,5 @@import ModelSelect from '../ModelSelect';+import FalModelSelect from './FalModelSelect';import {IMAGE_GEN_MODE, RENDER_TARGET_BACKEND_AUTO, localModelSelectOptions, modeLabel,supportsCloudModelOverride,@@ -6,7 +7,7 @@ import {import useFieldDraft from '../../hooks/useFieldDraft';import useLocalImageModels from '../../hooks/useLocalImageModels';-const DEFAULT_MODES = [IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK, IMAGE_GEN_MODE.AGY];+const DEFAULT_MODES = [IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK, IMAGE_GEN_MODE.AGY, IMAGE_GEN_MODE.FAL];const FIELD = 'w-full max-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';// Per-record render pin editor (#3231 Phase 3) — one row pinning a record's@@ -22,7 +23,9 @@ const FIELD = 'w-full max-w-full bg-port-bg border border-port-border rounded-lg// pin resolves to) rather than passed down, so every surface hosting this row// gets the same picker without threading two props through — a text box would// only invite a typo the render 400s on. Nothing is fetched until a local pin-// is actually selected. Grok, which accepts no model override, gets neither.+// is actually selected. A fal.ai pin takes a select over the curated fal+// catalog for the same reason. Grok, which accepts no model override, gets+// neither.//// `onChange` always receives BOTH keys (`{ imageMode, imageModelId }`), with// null for "no pin" — key-present-with-null is the intentional clear per the@@ -69,6 +72,15 @@ export default function RecordRenderPinRow({value={imageModelId}onChange={(modelId) => onChange({ imageMode: pinnedMode, imageModelId: modelId })}/>+ ) : pinnedMode === IMAGE_GEN_MODE.FAL ? (+ <FalModelSelect+ id={`${idPrefix}-model`}+ ariaLabel={`${label} model`}+ value={imageModelId || ''}+ defaultLabel="Default (Settings)"+ onChange={(modelId) => onChange({ imageMode: pinnedMode, imageModelId: modelId })}+ className={`${FIELD} sm:w-52`}+ />) : supportsCloudModelOverride(pinnedMode) ? (<inputid={`${idPrefix}-model`}diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsxindex a13c0c341b..a0ae544e44 100644--- a/client/src/components/media/MediaJobsQueue.jsx+++ b/client/src/components/media/MediaJobsQueue.jsx@@ -115,7 +115,9 @@ function modelLabel(params, renderer) {// provider owns, so the row must name the provider rather than fall through// to the local-engine badge below (grok video is caught by the mode branch// above, which adds its aspect ratio).- const cloudModel = (params.modelId || '').trim();+ // Video jobs carry `modelId`; a fal.ai IMAGE job (same 'fal' literal)+ // carries its catalog id in `model`.+ const cloudModel = (params.modelId || params.model || '').trim();const provider = modeLabel(params.mode);return cloudModel ? `${provider} / ${cloudModel}` : provider;}diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsxindex aabc998f05..b996cd57c0 100644--- a/client/src/components/settings/ImageGenTab.jsx+++ b/client/src/components/settings/ImageGenTab.jsx@@ -28,7 +28,8 @@ import {saveHfToken, clearHfToken,getCredentialInventory, saveCredential,} from '../../services/api';-import { deriveAvailableBackends, imageGenReadiness, isCloudCliMode, IMAGE_GEN_MODE, LOCAL_IMAGEGEN_DEFAULT_MODEL, AGY_IMAGEGEN_DEFAULT_MODEL, AGY_IMAGEGEN_IMAGE_MODEL, CODEX_IMAGEGEN_DEFAULT_EFFORT, CODEX_IMAGEGEN_DEFAULT_MODEL, GROK_ASPECT_RATIOS, RENDER_TARGET_BACKEND_AUTO, RENDER_TARGET_OPTIONS, VIDEO_RENDER_MODES, localModelSelectOptions, modeLabel, normalizeRenderPinValue, supportsCloudModelOverride } from '../../lib/imageGenBackends';+import FalModelSelect from '../imageGen/FalModelSelect';+import { deriveAvailableBackends, imageGenReadiness, isCloudCliMode, IMAGE_GEN_MODE, FAL_IMAGE_DEFAULT_MODEL, falImageFamily, LOCAL_IMAGEGEN_DEFAULT_MODEL, AGY_IMAGEGEN_DEFAULT_MODEL, AGY_IMAGEGEN_IMAGE_MODEL, CODEX_IMAGEGEN_DEFAULT_EFFORT, CODEX_IMAGEGEN_DEFAULT_MODEL, GROK_ASPECT_RATIOS, RENDER_TARGET_BACKEND_AUTO, RENDER_TARGET_OPTIONS, VIDEO_RENDER_MODES, localModelSelectOptions, modeLabel, normalizeRenderPinValue, supportsCloudModelOverride } from '../../lib/imageGenBackends';import { resolveCleanersFromConfig } from '../../lib/imageCleaners';import { withUnlistedOption } from '../../lib/withUnlistedOption';import { useMediaJobSse } from '../../hooks/useMediaJobSse';@@ -75,6 +76,7 @@ export const MEDIA_TABS = [{ id: 'codex', label: 'Codex CLI', icon: Terminal, probeMode: IMAGE_GEN_MODE.CODEX },{ id: 'grok', label: 'Grok CLI', icon: Zap, probeMode: IMAGE_GEN_MODE.GROK },{ id: 'agy', label: 'Agy CLI', icon: Bot, probeMode: IMAGE_GEN_MODE.AGY },+ { id: 'fal', label: 'fal.ai', icon: Sparkles, probeMode: IMAGE_GEN_MODE.FAL },{ id: 'tokens', label: 'Tokens', icon: Key },{ id: 'expose', label: 'Expose', icon: Globe },{ id: 'test', label: 'Test', icon: FlaskConical },@@ -171,6 +173,12 @@ export function ImageGenTab() {const [agyEnabled, setAgyEnabled] = useState(false);const [agyPath, setAgyPath] = useState('');const [agyModel, setAgyModel] = useState('');+ // fal.ai image backend — a metered API, gated by its own toggle like the+ // CLIs. The API key is NOT part of this slice: it is the fal.ai credential+ // the video backend already owns (the Defaults tab's key row).+ const [falEnabled, setFalEnabled] = useState(false);+ // '' = no pin → FAL_IMAGE_DEFAULT_MODEL server-side.+ const [falModel, setFalModel] = useState('');// Per-provider cleaner toggles. Both run after the PNG lands and before// the SSE complete event so subscribers see the cleaned bytes. SynthID// (the gpt-image / Imagen / Gemini pixel-level watermark) is unaffected@@ -180,8 +188,8 @@ export function ImageGenTab() {// provenance chunk. Lossless — pixels untouched.// - denoise (default OFF): median(3) + sharpen pass for AI-artifact// reduction. LOSSY: blurs annotation text and small details.- const [cleanC2PAByMode, setCleanC2PAByMode] = useState({ external: true, local: true, codex: true, grok: false, agy: false });- const [denoiseByMode, setDenoiseByMode] = useState({ external: false, local: false, codex: false, grok: false, agy: false });+ const [cleanC2PAByMode, setCleanC2PAByMode] = useState({ external: true, local: true, codex: true, grok: false, agy: false, fal: false });+ const [denoiseByMode, setDenoiseByMode] = useState({ external: false, local: false, codex: false, grok: false, agy: false, fal: false });const setCleanC2PAFor = (m) => (v) => setCleanC2PAByMode((p) => ({ ...p, [m]: v }));const setDenoiseFor = (m) => (v) => setDenoiseByMode((p) => ({ ...p, [m]: v }));// Raw string held while the user is typing in the parallel-limit input.@@ -202,6 +210,7 @@ export function ImageGenTab() {const agyPathId = useId();const agyModelId = useId();const agyModelsListId = useId();+ const falModelId = useId();// Snapshot of saved values so we can show the "dirty" stateconst [saved, setSaved] = useState({@@ -209,8 +218,9 @@ export function ImageGenTab() {codexEnabled: false, codexPath: '', codexModel: '', codexEffort: '', codexParallelLimit: 1,grokEnabled: false, grokPath: '', grokAspectRatio: '',agyEnabled: false, agyPath: '', agyModel: '',- cleanC2PAByMode: { external: true, local: true, codex: true, grok: false, agy: false },- denoiseByMode: { external: false, local: false, codex: false, grok: false, agy: false },+ falEnabled: false, falModel: '',+ cleanC2PAByMode: { external: true, local: true, codex: true, grok: false, agy: false, fal: false },+ denoiseByMode: { external: false, local: false, codex: false, grok: false, agy: false, fal: false },renderDefaultsJson: '{}',videoGenMode: '',localVideoModelId: '',@@ -360,15 +370,19 @@ export function ImageGenTab() {const ayEnabled = ay.enabled === true;const ayPath = ay.agyPath || '';const ayModel = ay.model || '';+ const fl = ig.fal || {};+ const flEnabled = fl.enabled === true;+ const flModel = fl.model || '';// Per-mode cleaner reads via the shared helper (mirrored from// server/lib/imageClean.js).const codexClean = resolveCleanersFromConfig(cx, IMAGE_GEN_MODE.CODEX);const grokClean = resolveCleanersFromConfig(gk, IMAGE_GEN_MODE.GROK);const agyClean = resolveCleanersFromConfig(ay, IMAGE_GEN_MODE.AGY);+ const falClean = resolveCleanersFromConfig(fl, IMAGE_GEN_MODE.FAL);const localClean = resolveCleanersFromConfig(ig.local, IMAGE_GEN_MODE.LOCAL);const externalClean = resolveCleanersFromConfig(ig.external, IMAGE_GEN_MODE.EXTERNAL);- const c2 = { codex: codexClean.cleanC2PA, grok: grokClean.cleanC2PA, agy: agyClean.cleanC2PA, local: localClean.cleanC2PA, external: externalClean.cleanC2PA };- const dn = { codex: codexClean.denoise, grok: grokClean.denoise, agy: agyClean.denoise, local: localClean.denoise, external: externalClean.denoise };+ const c2 = { codex: codexClean.cleanC2PA, grok: grokClean.cleanC2PA, agy: agyClean.cleanC2PA, fal: falClean.cleanC2PA, local: localClean.cleanC2PA, external: externalClean.cleanC2PA };+ const dn = { codex: codexClean.denoise, grok: grokClean.denoise, agy: agyClean.denoise, fal: falClean.denoise, local: localClean.denoise, external: externalClean.denoise };setMode(m);setRenderDefaults(rd);setVideoGenMode(vgMode);@@ -392,6 +406,8 @@ export function ImageGenTab() {setAgyEnabled(ayEnabled);setAgyPath(ayPath);setAgyModel(ayModel);+ setFalEnabled(flEnabled);+ setFalModel(flModel);setCleanC2PAByMode(c2);setDenoiseByMode(dn);setSaved({@@ -400,6 +416,7 @@ export function ImageGenTab() {codexParallelLimit: cxParallel,grokEnabled: gkEnabled, grokPath: gkPath, grokAspectRatio: gkRatio,agyEnabled: ayEnabled, agyPath: ayPath, agyModel: ayModel,+ falEnabled: flEnabled, falModel: flModel,cleanC2PAByMode: c2, denoiseByMode: dn,renderDefaultsJson: JSON.stringify(rd),videoGenMode: vgMode,@@ -482,6 +499,7 @@ export function ImageGenTab() {codex: { enabled: saved.codexEnabled },grok: { enabled: saved.grokEnabled },agy: { enabled: saved.agyEnabled },+ fal: { enabled: saved.falEnabled },external: { sdapiUrl: saved.sdapiUrl },},});@@ -515,6 +533,10 @@ export function ImageGenTab() {|| agyEnabled !== saved.agyEnabled|| agyPath !== saved.agyPath|| agyModel !== saved.agyModel+ || falEnabled !== saved.falEnabled+ || falModel !== saved.falModel+ || cleanC2PAByMode.fal !== saved.cleanC2PAByMode.fal+ || denoiseByMode.fal !== saved.denoiseByMode.fal|| cleanC2PAByMode.agy !== saved.cleanC2PAByMode.agy|| denoiseByMode.agy !== saved.denoiseByMode.agy|| cleanC2PAByMode.grok !== saved.cleanC2PAByMode.grok@@ -568,6 +590,10 @@ export function ImageGenTab() {enabled: agyEnabled, agyPath: ayPath, model: ayModel,cleanC2PA: cleanC2PAByMode.agy, denoise: denoiseByMode.agy,},+ fal: {+ enabled: falEnabled, model: falModel || undefined,+ cleanC2PA: cleanC2PAByMode.fal, denoise: denoiseByMode.fal,+ },expose: { a1111: exposeA1111 },// Keep the legacy field populated so anything still reading// `imageGen.sdapiUrl` directly stays working.@@ -602,6 +628,7 @@ export function ImageGenTab() {codexParallelLimit: cxParallel,grokEnabled, grokPath: gkPath || '', grokAspectRatio: gkRatio || '',agyEnabled, agyPath: ayPath || '', agyModel: ayModel || '',+ falEnabled, falModel,cleanC2PAByMode, denoiseByMode,renderDefaultsJson: JSON.stringify(patch.renderDefaults),videoGenMode,@@ -796,7 +823,7 @@ export function ImageGenTab() {generation with local Python runtimes, including mflux and diffusers. You can alsoexpose this PortOS as an A1111-compatible endpoint for other tailnet boxes.</p>- <div className={`grid grid-cols-1 sm:grid-cols-2 ${(codexEnabled || grokEnabled || agyEnabled) ? 'lg:grid-cols-3' : ''} gap-3`}>+ <div className={`grid grid-cols-1 sm:grid-cols-2 ${(codexEnabled || grokEnabled || agyEnabled || falEnabled) ? 'lg:grid-cols-3' : ''} gap-3`}><buttontype="button"onClick={() => setMode(IMAGE_GEN_MODE.EXTERNAL)}@@ -858,6 +885,19 @@ export function ImageGenTab() {<p className="text-xs text-gray-500 mt-1">Text-to-image through Antigravity's generate_image tool and your selected model.</p></button>)}+ {falEnabled && (+ <button+ type="button"+ onClick={() => setMode(IMAGE_GEN_MODE.FAL)}+ className={`text-left p-4 rounded-lg border transition-colors ${mode === IMAGE_GEN_MODE.FAL ? 'border-port-accent bg-port-accent/10 text-white' : 'border-port-border text-gray-400 hover:bg-port-border/30 hover:text-white'}`}+ >+ <div className="flex items-center gap-2">+ <Sparkles className="w-4 h-4" />+ <span className="font-medium text-sm">fal.ai</span>+ </div>+ <p className="text-xs text-gray-500 mt-1">Hosted image and reference-edit models through fal.ai's API. Billed per image to your fal.ai account.</p>+ </button>+ )}</div></div>)}@@ -875,7 +915,7 @@ export function ImageGenTab() {Each surface below follows the install default backend unless pinned here. A pinnedbackend that is disabled (or unconfigured) falls back to whatever that surface wouldhave used anyway — enable the backend on its own tab to make a pin take effect. A- model can be pinned for backends that accept one (Codex, Agy); Grok and Local pick+ model can be pinned for backends that accept one (Codex, Agy, fal.ai); Grok and Local picktheir models elsewhere. Surfaces that also render video get a video backend pin.The default local video model is set on the Local tab, and a render's explicit modelchoice takes precedence.@@ -918,8 +958,8 @@ export function ImageGenTab() {{id: 'fal', label: 'fal.ai API key', input: falKeyInput, setInput: setFalKeyInput,placeholder: 'fal-key-...', envLabel: 'FAL_KEY',- hint: '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.',- missing: 'No fal.ai key configured — the fal.ai video backend will be unavailable.',+ hint: 'Enables the fal.ai queue video backend on the Video Gen page and in FableLoom, and the fal.ai image backend (fal.ai tab). Get a key at fal.ai/dashboard/keys, or set the FAL_KEY environment variable instead.',+ missing: 'No fal.ai key configured — the fal.ai video and image backends will be unavailable.',},{id: 'reactor', label: 'reactor.inc API key', input: reactorKeyInput, setInput: setReactorKeyInput,@@ -1024,12 +1064,22 @@ export function ImageGenTab() {className="bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent sm:w-44"><option value="">Auto (install default)</option>- {[IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK, IMAGE_GEN_MODE.AGY].map((m) => (+ {[IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK, IMAGE_GEN_MODE.AGY, IMAGE_GEN_MODE.FAL].map((m) => (<option key={m} value={m}>{modeLabel(m)}</option>))}</select></FormField>- {supportsCloudModelOverride(pinnedMode) ? (+ {pinnedMode === IMAGE_GEN_MODE.FAL ? (+ <FormField label={`${label} model`} labelClassName="sr-only" className="contents">+ <FalModelSelect+ id={modelInputId}+ value={entry.imageModel || ''}+ onChange={(v) => setPin('imageModel', v)}+ defaultLabel="Model: fal.ai default"+ className="bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent sm:w-52"+ />+ </FormField>+ ) : supportsCloudModelOverride(pinnedMode) ? (<FormField label={`${label} model`} labelClassName="sr-only" className="contents"><inputid={modelInputId}@@ -1485,6 +1535,78 @@ export function ImageGenTab() {</div>)}+ {mediaTab === 'fal' && (+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-4">+ <div className="flex items-center gap-2 text-white">+ <Sparkles size={18} />+ <h2 className="text-lg font-semibold">fal.ai Imagegen</h2>+ </div>+ <p className="text-xs text-gray-500">+ Render through fal.ai’s hosted image models. Renders with reference or source images+ go to the chosen model’s edit endpoint, so mood-board references condition the result.+ Every render is billed to your fal.ai account; the gallery records each image’s estimated cost.+ </p>+ {/* Key presence comes from the shared credential inventory — the key+ itself is write-only and lives on the Defaults tab with the fal.ai+ video key it is shared with. */}+ {credentialRows.fal == null ? (+ <div className="text-xs text-gray-500"><BrailleSpinner text="Checking fal.ai key" /></div>+ ) : credentialRows.fal.configured ? (+ <div className="flex items-center gap-2 text-xs text-port-success">+ <Check size={14} />+ <span>fal.ai API key configured (shared with the fal.ai video backend)</span>+ </div>+ ) : (+ <div className="flex flex-wrap items-center gap-2 text-xs text-port-warning">+ <AlertTriangle size={14} />+ <span>No fal.ai API key — set it under the Defaults tab (fal.ai API key, shared with Video Gen) first.</span>+ <button type="button" onClick={() => setMediaTab('defaults')} className="text-port-accent hover:underline">+ Open Defaults+ </button>+ </div>+ )}+ <label className="flex items-center gap-3 cursor-pointer">+ <input+ type="checkbox"+ checked={falEnabled}+ onChange={(e) => {+ const enabled = e.target.checked;+ setFalEnabled(enabled);+ if (!enabled && mode === IMAGE_GEN_MODE.FAL) {+ setMode(pythonPath?.trim() ? IMAGE_GEN_MODE.LOCAL : IMAGE_GEN_MODE.EXTERNAL);+ }+ }}+ className="rounded"+ />+ <span className="text-sm text-gray-300">Enable fal.ai Imagegen</span>+ </label>+ {falEnabled && (+ <div className="space-y-3 pl-6 border-l-2 border-port-border">+ <FormField label="Default model" labelClassName="block text-xs font-medium text-gray-400 mb-1">+ <FalModelSelect+ id={falModelId}+ value={falModel}+ onChange={(v) => setFalModel(v || '')}+ defaultLabel={`${falImageFamily(FAL_IMAGE_DEFAULT_MODEL)?.label} (default)`}+ 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>+ <p className="text-xs text-gray-500">+ Prices are fal.ai’s published per-image rates (Nano Banana charges more at 4K; FLUX.2 bills+ output plus reference megapixels). Renders can pick a different model per queue item on the+ Image Gen page, and each surface can pin one under Defaults.+ </p>+ <CleanersToggles+ cleanC2PA={cleanC2PAByMode.fal}+ denoise={denoiseByMode.fal}+ onCleanC2PAChange={setCleanC2PAFor(IMAGE_GEN_MODE.FAL)}+ onDenoiseChange={setDenoiseFor(IMAGE_GEN_MODE.FAL)}+ />+ </div>+ )}+ </div>+ )}+{/* HuggingFace token — used by local Flux models (FLUX.1-dev, FLUX.2-klein).Independent of the mode picker because the token persists in settingsand applies whenever local image gen runs. */}diff --git a/client/src/components/settings/ImageGenTab.test.jsx b/client/src/components/settings/ImageGenTab.test.jsxindex c6ab6f7b9b..690af81b06 100644--- a/client/src/components/settings/ImageGenTab.test.jsx+++ b/client/src/components/settings/ImageGenTab.test.jsx@@ -601,6 +601,35 @@ describe('ImageGenTab — Grok CLI section (#2859)', () => {});});+describe('ImageGenTab — fal.ai section', () => {+ it('points at the shared fal.ai key when none is configured', async () => {+ await renderTab();+ fireEvent.click(screen.getByRole('tab', { name: /fal\.ai/i }));+ expect(await screen.findByText(/No fal\.ai API key — set it under the Defaults tab/i)).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: /Open Defaults/i }));+ expect(screen.getByRole('tab', { name: /Defaults/i }).getAttribute('aria-selected')).toBe('true');+ expect(document.getElementById('fal-api-key')).toBeTruthy();+ });++ it('saves the enable toggle and a catalog model under imageGen.fal, and adds a backend tile', async () => {+ getCredentialInventory.mockResolvedValue({+ headline: '', credentials: [{ id: 'fal', label: 'fal.ai', configured: true, source: 'settings', editable: true }],+ });+ await renderTab();+ fireEvent.click(screen.getByRole('tab', { name: /fal\.ai/i }));+ expect(await screen.findByText(/fal\.ai API key configured/i)).toBeTruthy();+ fireEvent.click(screen.getByLabelText(/Enable fal\.ai Imagegen/i));+ fireEvent.change(screen.getByLabelText(/Default model/i), { target: { value: 'fal-ai/bytedance/seedream/v5/lite/text-to-image' } });+ fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));+ await waitFor(() => expect(updateSettings).toHaveBeenCalled());+ expect(updateSettings.mock.calls[0][0].imageGen.fal).toEqual(expect.objectContaining({+ enabled: true, model: 'fal-ai/bytedance/seedream/v5/lite/text-to-image',+ }));+ fireEvent.click(screen.getByRole('tab', { name: /Backend/i }));+ expect(screen.getByText(/Hosted image and reference-edit models through fal\.ai/i)).toBeTruthy();+ });+});+// The packages panel above the card only ever probes the mflux interpreter, so// on its own it told a machine whose selected default renders through the// shared torch venv that everything was installed — while the Image Gen pagediff --git a/client/src/hooks/useImageGenForm.js b/client/src/hooks/useImageGenForm.jsindex 28f39fa375..64665bd8be 100644--- a/client/src/hooks/useImageGenForm.js+++ b/client/src/hooks/useImageGenForm.js@@ -85,6 +85,10 @@ export function useImageGenForm({ searchParams, setSearchParams, backend }) {const [selectedLoras, setSelectedLoras] = useState([]);const [agyModel, setAgyModel] = useState('');const [savedAgyModel, setSavedAgyModel] = useState('');+ // Per-render fal.ai model ('' = the Settings default) and that default, for+ // the picker's "Settings default (…)" row.+ const [falModel, setFalModel] = useState('');+ const [savedFalModel, setSavedFalModel] = useState('');const [savedLocalModelId, setSavedLocalModelId] = useState(null);const [initImage, setInitImage] = useState({ source: null, file: null, name: null, previewUrl: null });const initImagePreviewRef = useRef(initImage.previewUrl);@@ -119,6 +123,7 @@ export function useImageGenForm({ searchParams, setSearchParams, backend }) {codex: resolveCleanersFromConfig(settings?.imageGen?.codex, IMAGE_GEN_MODE.CODEX),grok: resolveCleanersFromConfig(settings?.imageGen?.grok, IMAGE_GEN_MODE.GROK),agy: resolveCleanersFromConfig(settings?.imageGen?.agy, IMAGE_GEN_MODE.AGY),+ fal: resolveCleanersFromConfig(settings?.imageGen?.fal, IMAGE_GEN_MODE.FAL),};const c2 = {external: perMode.external.cleanC2PA,@@ -126,6 +131,7 @@ export function useImageGenForm({ searchParams, setSearchParams, backend }) {codex: perMode.codex.cleanC2PA,grok: perMode.grok.cleanC2PA,agy: perMode.agy.cleanC2PA,+ fal: perMode.fal.cleanC2PA,};const dn = {external: perMode.external.denoise,@@ -133,10 +139,12 @@ export function useImageGenForm({ searchParams, setSearchParams, backend }) {codex: perMode.codex.denoise,grok: perMode.grok.denoise,agy: perMode.agy.denoise,+ fal: perMode.fal.denoise,};const saved = settings?.imageGen?.mode || IMAGE_GEN_MODE.EXTERNAL;const next = configureBackends(backends, saved);setSavedAgyModel(settings?.imageGen?.agy?.model || '');+ setSavedFalModel(settings?.imageGen?.fal?.model || '');setSavedLocalModelId(settings?.imageGen?.local?.modelId || '');setSavedCleanC2PAByMode(c2);setSavedDenoiseByMode(dn);@@ -464,11 +472,15 @@ export function useImageGenForm({ searchParams, setSearchParams, backend }) {const editImageMissing = isLocalMode && isEditOnlyModel && initImage.source == null;const isQwen21Model = currentModel?.pipelineClass === 'QwenImage21Pipeline';const i2iCapable = isI2iCapableMode(effectiveMode);+ const isFalMode = effectiveMode === IMAGE_GEN_MODE.FAL;const referenceSlotCount = referenceSlotsFor(effectiveMode, {hasInitImage: initImage.source != null,- maxSlots: isLocalMode && isQwen21Model ? REFERENCE_SLOT_COUNT : 4,+ // fal.ai's edit models take 9–14 references (a mood board is the point),+ // so it gets every form slot; the per-model cap below still bounds it.+ maxSlots: (isLocalMode && isQwen21Model) || isFalMode ? REFERENCE_SLOT_COUNT : 4,localSupportsReferences: isFlux2Model || isQwen21Model,localInputCap: isQwen21Model ? 10 : null,+ cloudModelId: isFalMode ? (falModel || savedFalModel || null) : null,});const activeStylePresets = useMemo(() => [selectedUniverse ? universeStylePreset(selectedUniverse) : null,@@ -693,6 +705,8 @@ export function useImageGenForm({ searchParams, setSearchParams, backend }) {setSelectedLoras,agyModel,setAgyModel,+ falModel,+ setFalModel,batchCount,setBatchCount,cleanC2PA,@@ -706,6 +720,7 @@ export function useImageGenForm({ searchParams, setSearchParams, backend }) {},settings: {savedAgyModel,+ savedFalModel,savedCleanC2PAByMode,savedDenoiseByMode,reloadBackends,diff --git a/client/src/hooks/useImageGenPageRuntime.js b/client/src/hooks/useImageGenPageRuntime.jsindex 742325f3be..f67522068f 100644--- a/client/src/hooks/useImageGenPageRuntime.js+++ b/client/src/hooks/useImageGenPageRuntime.js@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';import { useNavigate, useSearchParams } from 'react-router';import { composeStyledPrompt } from '../lib/composeStyledPrompt';import {+ FAL_IMAGE_MODEL_IDS,IMAGE_GEN_MODE,isCloudCliMode,modeLabel,@@ -58,6 +59,7 @@ function useImageGenBackendRuntime() {const isCloudMode = isCloudCliMode(effectiveMode);const cloudModeLabel = modeLabel(effectiveMode);const isAgyMode = effectiveMode === IMAGE_GEN_MODE.AGY;+ const isFalMode = effectiveMode === IMAGE_GEN_MODE.FAL;const remoteTarget = useFederatedMediaTarget('image');const remoteTargetActive = effectiveMode !== IMAGE_GEN_MODE.GROK && remoteTarget.isRemote;const localBackendPending = statusLoading && !remoteTargetActive;@@ -100,6 +102,7 @@ function useImageGenBackendRuntime() {isCloudMode,cloudModeLabel,isAgyMode,+ isFalMode,remoteTarget,remoteTargetActive,localBackendPending,@@ -147,6 +150,9 @@ export function useImageGenPageRuntime() {const { fields, derived, images, actions } = form;const { effectiveMode, isCloudMode, remoteTargetActive } = backend;const effectiveAgyModel = backend.agy.models.includes(fields.agyModel) ? fields.agyModel : '';+ // Only a catalog id is ever sent — the server refuses anything else.+ const effectiveFalModel = FAL_IMAGE_MODEL_IDS.includes(fields.falModel) ? fields.falModel : '';+ const effectiveCloudModel = backend.isAgyMode ? effectiveAgyModel : backend.isFalMode ? effectiveFalModel : '';useEffect(() => {if (!effectiveMode) return;@@ -261,7 +267,7 @@ export function useImageGenPageRuntime() {width,height,mode: effectiveMode,- ...(effectiveAgyModel ? { cloudModel: effectiveAgyModel } : {}),+ ...(effectiveCloudModel ? { cloudModel: effectiveCloudModel } : {}),cleanC2PA: fields.cleanC2PA,denoise: fields.denoise,} : {@@ -480,7 +486,7 @@ export function useImageGenPageRuntime() {return {form,- backend: { ...backend, effectiveAgyModel },+ backend: { ...backend, effectiveAgyModel, effectiveFalModel },generation: {handleGenerate,handleCancel,diff --git a/client/src/lib/imageGenBackends.js b/client/src/lib/imageGenBackends.jsindex e1072d7570..d61d3e8d4a 100644--- a/client/src/lib/imageGenBackends.js+++ b/client/src/lib/imageGenBackends.js@@ -6,7 +6,7 @@* per-mode lucide icons and the settings-driven backend derivation.*/-import { Cpu, Terminal, Cloud, Sparkles } from 'lucide-react';+import { Cpu, Terminal, Cloud, Sparkles, Zap } from 'lucide-react';import { IMAGE_GEN_MODE, IMAGE_RUNTIME_READINESS, MODE_LABELS } from './imageGenModes.js';export * from './imageGenModes.js';@@ -16,6 +16,7 @@ const MODE_ICONS = {[IMAGE_GEN_MODE.CODEX]: Terminal,[IMAGE_GEN_MODE.GROK]: Sparkles,[IMAGE_GEN_MODE.AGY]: Sparkles,+ [IMAGE_GEN_MODE.FAL]: Zap,[IMAGE_GEN_MODE.EXTERNAL]: Cloud,};@@ -40,6 +41,8 @@ export function deriveAvailableBackends(settings, { excludeExternal = false } =out.push({ id: IMAGE_GEN_MODE.GROK, ...metaFor(IMAGE_GEN_MODE.GROK) });if (ig.agy?.enabled === true)out.push({ id: IMAGE_GEN_MODE.AGY, ...metaFor(IMAGE_GEN_MODE.AGY) });+ if (ig.fal?.enabled === true)+ out.push({ id: IMAGE_GEN_MODE.FAL, ...metaFor(IMAGE_GEN_MODE.FAL) });if (!excludeExternal && (ig.external?.sdapiUrl || ig.sdapiUrl || '').trim())out.push({ id: IMAGE_GEN_MODE.EXTERNAL, ...metaFor(IMAGE_GEN_MODE.EXTERNAL) });return out;diff --git a/client/src/lib/imageGenBackends.test.js b/client/src/lib/imageGenBackends.test.jsindex 6b55bb9a30..43f0e896f1 100644--- a/client/src/lib/imageGenBackends.test.js+++ b/client/src/lib/imageGenBackends.test.js@@ -27,7 +27,7 @@ describe('imageGenReadiness', () => {describe('I2I_CAPABLE_MODES / isI2iCapableMode', () => {it('treats every generation backend as i2i-capable, but not external', () => {expect(I2I_CAPABLE_MODES).toEqual([- IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK, IMAGE_GEN_MODE.AGY,+ IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK, IMAGE_GEN_MODE.AGY, IMAGE_GEN_MODE.FAL,]);expect(isI2iCapableMode(IMAGE_GEN_MODE.LOCAL)).toBe(true);expect(isI2iCapableMode(IMAGE_GEN_MODE.CODEX)).toBe(true);@@ -67,6 +67,16 @@ describe('input-image capability helpers', () => {expect(referenceSlotsFor(IMAGE_GEN_MODE.GROK, { hasInitImage: false })).toBe(4);});+ it('caps fal.ai per model — the chosen model\'s limit, else the smallest in the catalog', () => {+ const options = { maxSlots: 10, hasInitImage: true };+ // FLUX.2 [pro] edit takes 9 images total; an init image leaves 8 refs.+ expect(referenceSlotsFor(IMAGE_GEN_MODE.FAL, { ...options, cloudModelId: 'fal-ai/flux-2-pro' })).toBe(8);+ // Nano Banana takes 14, so the form's own 10 slots are the ceiling.+ expect(referenceSlotsFor(IMAGE_GEN_MODE.FAL, { ...options, cloudModelId: 'fal-ai/nano-banana-pro' })).toBe(10);+ // Unknown model → the catalog floor, never a slot some fal model would drop.+ expect(referenceSlotsFor(IMAGE_GEN_MODE.FAL, options)).toBe(8);+ });+it('reserves the init slot within Qwen’s ten inputs', () => {const options = { localSupportsReferences: true, localInputCap: 10, maxSlots: 10 };expect(referenceSlotsFor(IMAGE_GEN_MODE.LOCAL, options)).toBe(10);diff --git a/client/src/lib/imageGenModes.js b/client/src/lib/imageGenModes.jsindex 2055578dcd..e2119c65cd 100644--- a/client/src/lib/imageGenModes.js+++ b/client/src/lib/imageGenModes.js@@ -4,7 +4,7 @@* parity suite (`server/lib/renderTargets.parity.test.js`) and the server CI* job import this module directly, where client-only packages (lucide-react)* are not installed. Nothing here may import React, icons, or any package —- * the only imports allowed are the three dependency-free server leaves below,+ * the only imports allowed are the dependency-free server leaves below,* the same way `Layout.jsx` reads `server/lib/navManifest.js`. Icon metadata* and settings-driven backend derivation stay in `imageGenBackends.js`, which* re-exports everything below so client consumers keep a single import site.@@ -62,6 +62,13 @@ import {IMAGE_RUNTIME_READINESS,IMAGE_RUNTIME_REMEDY,} from '../../../server/lib/imageRuntimeRemedies.js';+import {+ FAL_IMAGE_DEFAULT_MODEL,+ FAL_IMAGE_FAMILIES,+ FAL_IMAGE_MODEL_IDS,+ falImageFamily,+ falImagePriceLabel,+} from '../../../server/lib/falImageModels.js';export {// Shipped per-backend defaults, so a UI that displays "the model/effort a job@@ -76,6 +83,14 @@ export {CLOUD_IMAGE_GEN_MODES,CODEX_IMAGEGEN_DEFAULT_EFFORT,CODEX_IMAGEGEN_DEFAULT_MODEL,+ // The curated fal.ai image catalog — the ONLY ids a fal `cloudModel` or+ // `imageGen.fal.model` may name (the server 400s anything else), so every+ // fal model picker is built from these rather than a free-text field.+ FAL_IMAGE_DEFAULT_MODEL,+ FAL_IMAGE_FAMILIES,+ FAL_IMAGE_MODEL_IDS,+ falImageFamily,+ falImagePriceLabel,// The ratios grok's image tools accept — the Settings default-ratio picker.GROK_ASPECT_RATIOS,// Backends that support image-to-image, ordered best-first: what the i2i-only@@ -152,7 +167,9 @@ export const RENDER_TARGET_OPTIONS = Object.freeze([export const isCloudVideoMode = (mode) => CLOUD_VIDEO_GEN_MODES.includes(mode);// Human-facing backend names — the pure half of imageGenBackends' per-mode-// metadata (its icon half stays there with the lucide import).+// metadata (its icon half stays there with the lucide import). 'fal' is one+// entry for both media kinds: IMAGE_GEN_MODE.FAL and VIDEO_GEN_MODE.FAL are the+// same literal.export const MODE_LABELS = Object.freeze({[IMAGE_GEN_MODE.LOCAL]: 'Local',[IMAGE_GEN_MODE.CODEX]: 'Codex',@@ -163,6 +180,15 @@ export const MODE_LABELS = Object.freeze({[VIDEO_GEN_MODE.REACTOR]: 'Reactor.inc',});+// The fal.ai model picker rows — one per catalog family, keyed by its+// text-to-image endpoint (the provider switches to the family's /edit endpoint+// on its own whenever a render carries input images), labeled with its price+// because each choice is a different cost per image.+export const FAL_IMAGE_MODEL_OPTIONS = Object.freeze(FAL_IMAGE_FAMILIES.map((family) => Object.freeze({+ id: family.textEndpoint,+ label: `${family.label} (${falImagePriceLabel(family)}, up to ${family.maxInputImages} refs)`,+})));+// True for a cloud-CLI backend: one that picks model/steps/seed internally,// runs through the media queue's parallel cloud lane, and needs a prompt for// text-to-image. Use this instead of hand-rolled `mode === CODEX || mode ===@@ -317,13 +343,16 @@ export function pickI2iMode(backends) {* references ride a separate runner flag from the init image). Qwen 2.1 shares* its ten-input cap with the init image. Unsupported models take none.*/-export function referenceSlotsFor(mode, { hasInitImage = false, maxSlots = 4, localSupportsReferences = false, localInputCap = null } = {}) {+export function referenceSlotsFor(mode, {+ hasInitImage = false, maxSlots = 4, localSupportsReferences = false, localInputCap = null, cloudModelId = null,+} = {}) {if (mode === IMAGE_GEN_MODE.LOCAL) {if (!localSupportsReferences) return 0;return Math.min(maxSlots, (localInputCap ?? Infinity) - (hasInitImage ? 1 : 0));}if (!isCloudCliMode(mode)) return 0;- const cap = maxInputImages(mode) ?? Infinity;+ // `cloudModelId` refines the cap for a backend whose limit is per model (fal.ai).+ const cap = maxInputImages(mode, cloudModelId) ?? Infinity;return Math.min(maxSlots, cap - (hasInitImage ? 1 : 0));}diff --git a/server/lib/README.md b/server/lib/README.mdindex 839f02dd54..f3857b1e7a 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -36,6 +36,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `sharedSchemas.js` | Cross-domain Zod fragments that `validation.js` and the per-domain `*Validation.js` files both need, kept in a leaf module so the domain files never import back through `validation.js` (its hoisted `export * from` lines would TDZ). `grokVideoDurationSchema` (grok clip-length union), `cloudModelIdString(message)` (cloud-CLI model-id charset/bounds), `recordRenderPinFields` (the `imageMode`/`imageModelId` per-record render pin pair), and `isSafeSubdirFilter(v)` (relative path with no wildcard, `..` segment, or leading `/`), and `csvIdsParam({ max, maxIdLength, truncate })` (the `?ids=a,b,c` batch-by-id query param: trims, drops empties, reads all-blank as absent, and either 400s or silently slices an over-cap batch). Also the backup-exclude anchoring rule (#7241): `anchorUserExclude` / `anchorUserExcludes` prepend the rsync root anchor (`/`) to any user pattern that is not already anchored and is not deliberately `*`/`**`-led, and `isSafeExcludePattern` (defined as `anchorUserExclude(x) !== null`, so the two can never disagree) rejects a `..` segment, a NUL, or a pattern longer than `EXCLUDE_PATTERN_MAX_LENGTH` once anchored — one rule shared by `backupConfigSchema` and `services/backup.js#computeEffectiveExcludes`, since an unanchored `cache/` is an rsync filter that matches at EVERY depth. Mirrored to `client/src/lib/backupExcludes.js`. Also `resolveAutoUpdateConfig(settings.autoUpdate)` + the channel/interval constants — same sparse-slice rule for the automatic self-update: omitted `enabled` means OFF, omitted `channel` means `release`, `minIntervalHours` clamps into `[1, 720]`, `resolveBlockersWithAgent` defaults on — shared by `autoUpdateSettingsSchema`, `services/autoUpdateScheduler.js`, and the settings GET projection. || `generationModes.js` | Shared immutable image/video render-backend alphabets (`IMAGE_GEN_MODE[S]`, `QUEUEABLE_IMAGE_MODES`, `VIDEO_GEN_MODE[S]`, and cloud subsets) plus `mediaJobExecutionLane({ kind, mode, remote })` / `MEDIA_JOB_EXECUTION_LANES` — THE media-queue lane rule the scheduler and the public job projection share, kept below both validation and generation services so schemas never import orchestration modules. || `imageGenCapabilities.js` | Per-backend image-gen capability literals, a dependency-free leaf beside `generationModes.js`: `EDIT_INCAPABLE_IMAGE_MODES`/`isEditCapableMode` and the derived `I2I_CAPABLE_MODES`, the shipped defaults (`CODEX_IMAGEGEN_DEFAULT_MODEL`/`_EFFORT`, `AGY_IMAGEGEN_DEFAULT_MODEL`, `AGY_IMAGEGEN_IMAGE_MODEL`), the `AGY_`/`GROK_ASPECT_RATIOS` alphabets, and `IMAGE_GEN_PROVIDER_CAPABILITIES` (`supportsModelOverride`, `maxInputImages`, `promptRequiredWithInputImage`) with its `supportsCloudModelOverride`/`maxInputImages`/`cloudPromptRequired` readers. The `services/imageGen/*` modules re-export these, and `client/src/lib/imageGenModes.js` imports them instead of copying them (#6590). |+| `falImageModels.js` | Curated fal.ai image model catalog, a dependency-free leaf the client imports: `FAL_IMAGE_FAMILIES` (text + `/edit` endpoint per family, per-model reference cap, sizing alphabet, pricing), `FAL_IMAGE_DEFAULT_MODEL`, `FAL_IMAGE_MODEL_IDS` (the only ids a fal `cloudModel` may name), `falImageFamily`/`isFalImageModel`, `falImagePriceLabel`, `buildFalImageRequest` (routes to `/edit` when input images are present; maps width/height to aspect-ratio + resolution tier or pixel `image_size`) and `estimateFalImageCostUsd` (with `FAL_MEGAPIXEL`, fal.ai's binary megapixel). || `imageRuntimeRemedies.js` | Local image-runtime vocabulary, a dependency-free leaf beside `imageGenCapabilities.js`: `IMAGE_RUNTIME_READINESS` (ready/unavailable/unknown), `IMAGE_RUNTIME` + `IMAGE_RUNTIME_LABELS` (the shared torch venv vs. the configurable mflux interpreter), `IMAGE_RUNTIME_REMEDY` (the one action that fixes each unavailable state), and `IMAGE_RUNTIME_UNAVAILABLE_CODE`. `services/imageGen/localRuntime.js` builds the diagnosis from these, `services/imageGen/local.js` tags its pre-flight render refusal with the same remedy, and `client/src/lib/imageGenModes.js` re-exports them so no component hand-copies a remedy kind. || `renderModeLadder.js` | `resolveRenderPins` and `resolveRenderTargetPins` share backend-scoped model candidate inheritance across browser and server. Image-gen mode resolution ladder (#6815), a dependency-free leaf beside `generationModes.js`/`renderTargets.js` so the client imports it directly instead of hand-copying it: `isModeUsable(settings, mode)` (queueable + enabled gate, no per-provider spec lookup), `pickUsableMode(settings, candidates)` (first usable candidate, falling through disabled pins to the cloud-then-local tail), `renderTargetDefaults(settings, target)` (the normalized `settings.renderDefaults[target]` pin), and `imageModeCandidates(settings, target, record)` (the shared `[recordPin, targetPin, installDefault]` candidate order, declared once so a UI's own "what will Auto resolve to" display can't drift from the resolver). `services/imageGen/cloudProviderConfig.js` re-exports the first three for its existing callers. || `fableLoomLimits.js` | FableLoom record caps (`LOOM_LIMITS`) — the single source of truth shared by the route schemas and the record sanitizer. A leaf module, below both. |diff --git a/server/lib/credentialRegistry.js b/server/lib/credentialRegistry.jsindex 4f1a8ea4f5..3e04680fc0 100644--- a/server/lib/credentialRegistry.js+++ b/server/lib/credentialRegistry.js@@ -34,7 +34,7 @@ export const CREDENTIALS = Object.freeze([}),Object.freeze({id: 'fal', label: 'fal.ai', privateStore: true,- unlocks: 'Video generation through fal.ai.', tier: 'metered',+ unlocks: 'Video and image generation through fal.ai.', tier: 'metered',getUrl: 'https://fal.ai/dashboard/keys', envVars: Object.freeze(['FAL_KEY']),settingsPath: 'videoGen.fal.apiKey', configurePath: '/settings/credentials',}),diff --git a/server/lib/falImageModels.js b/server/lib/falImageModels.jsnew file mode 100644index 0000000000..4aad2e7535--- /dev/null+++ b/server/lib/falImageModels.js@@ -0,0 +1,256 @@+/**+ * fal.ai image model catalog — the curated set of fal.ai endpoints the+ * `fal` image backend (services/imageGen/fal.js) may call, with one request+ * builder and one cost estimator per model family.+ *+ * A dependency-free leaf (like `imageGenCapabilities.js`, which reads the+ * per-model reference caps from here) so the Settings model picker and the+ * Image Gen page offer exactly the ids the server accepts — `cloudModel` for a+ * fal render is validated against THIS list, never passed through as free+ * text, because every id is a different price.+ *+ * Every family is a text-to-image endpoint plus its `/edit` sibling. The user+ * picks a FAMILY (either endpoint id names it); the provider routes to the+ * edit endpoint whenever the render carries any input image, so mood-board+ * references reach a model that actually conditions on them.+ *+ * Input schemas and prices were read from fal.ai's per-endpoint OpenAPI+ * (`fal.ai/api/openapi/queue/openapi.json?endpoint_id=…`), the pricing API+ * (`api.fal.ai/v1/models/pricing`) and the model pages on 2026-09-29. None of+ * these models takes a negative prompt, so it is folded into the prompt as an+ * "Avoid:" clause — the same fallback the fal.ai video backend uses. Safety+ * knobs (`safety_tolerance`, `enable_safety_checker`) are left at fal.ai's+ * defaults on purpose: PortOS does not pick a moderation posture for the user.+ */++/** How a family takes its output geometry. */+export const FAL_IMAGE_SIZING = Object.freeze({+ // `aspect_ratio` enum + `resolution` tier (Gemini-backed nano-banana models).+ ASPECT_RATIO: 'aspect-ratio',+ // `image_size: { width, height }` in pixels (Seedream, FLUX.2).+ PIXELS: 'pixels',+});++const NANO_BANANA_ASPECT_RATIOS = Object.freeze(['21:9', '16:9', '3:2', '4:3', '5:4', '1:1', '4:5', '3:4', '2:3', '9:16']);++/**+ * The curated families. Per family:+ * - `textEndpoint` / `editEndpoint` — the two fal.ai endpoint ids.+ * - `maxInputImages` — the documented reference cap of the edit endpoint+ * (nano-banana: "up to 14 reference images"; Seedream v5 lite: "up to 10+ * image inputs … only the last 10 will be used"; FLUX.2 [pro]: "up to 9+ * reference images"). None of the OpenAPI schemas declare `maxItems`, so+ * these come from the model pages — re-read them, don't raise on a whim.+ * - `sizing` — FAL_IMAGE_SIZING; aspect-ratio families also list their+ * `aspectRatios` and `resolutions` alphabets.+ * - `alignTo` — pixel-size families whose dimensions must be a multiple of N.+ * - `seed` — whether the schema accepts `seed` (Seedream v5 lite does not).+ * - `outputFormat` — the `output_format` to request, or null when the+ * endpoint has no such field (the provider transcodes whatever arrives).+ * - `pricing` — `{ unit: 'image', usd, resolutionMultipliers? }` or+ * `{ unit: 'megapixel', firstMegapixelUsd, extraMegapixelUsd }`.+ */+export const FAL_IMAGE_FAMILIES = Object.freeze([+ Object.freeze({+ id: 'nano-banana-pro',+ label: 'Nano Banana Pro',+ textEndpoint: 'fal-ai/nano-banana-pro',+ editEndpoint: 'fal-ai/nano-banana-pro/edit',+ maxInputImages: 14,+ sizing: FAL_IMAGE_SIZING.ASPECT_RATIO,+ aspectRatios: NANO_BANANA_ASPECT_RATIOS,+ resolutions: Object.freeze(['1K', '2K', '4K']),+ seed: true,+ outputFormat: 'png',+ // "4K outputs will be charged at double the standard rate"; 1K and 2K+ // cost the same.+ pricing: Object.freeze({ unit: 'image', usd: 0.15, resolutionMultipliers: Object.freeze({ '4K': 2 }) }),+ }),+ Object.freeze({+ id: 'nano-banana-2',+ label: 'Nano Banana 2',+ textEndpoint: 'fal-ai/nano-banana-2',+ editEndpoint: 'fal-ai/nano-banana-2/edit',+ maxInputImages: 14,+ sizing: FAL_IMAGE_SIZING.ASPECT_RATIO,+ // The extreme 4:1 / 1:4 / 8:1 / 1:8 ratios this model also accepts are+ // deliberately left out: nearest-ratio mapping of an ordinary PortOS canvas+ // never wants them, and a banner-shaped surprise is worse than 21:9.+ aspectRatios: NANO_BANANA_ASPECT_RATIOS,+ resolutions: Object.freeze(['0.5K', '1K', '2K', '4K']),+ seed: true,+ outputFormat: 'png',+ // "2K and 4K outputs will be charged at 1.5 times and 2 times the+ // standard rate … 0.5K (512px) … 0.75 times".+ pricing: Object.freeze({ unit: 'image', usd: 0.08, resolutionMultipliers: Object.freeze({ '0.5K': 0.75, '2K': 1.5, '4K': 2 }) }),+ }),+ Object.freeze({+ id: 'seedream-v5-lite',+ label: 'Seedream 5.0 Lite',+ textEndpoint: 'fal-ai/bytedance/seedream/v5/lite/text-to-image',+ editEndpoint: 'fal-ai/bytedance/seedream/v5/lite/edit',+ maxInputImages: 10,+ // "Total pixels must be between 2560x1440 and 4096x4096" — fal.ai rescales+ // anything outside that band itself, so the requested geometry is sent+ // as-is and only its aspect ratio is guaranteed.+ sizing: FAL_IMAGE_SIZING.PIXELS,+ seed: false,+ outputFormat: null,+ pricing: Object.freeze({ unit: 'image', usd: 0.035 }),+ }),+ Object.freeze({+ id: 'flux-2-pro',+ label: 'FLUX.2 [pro]',+ textEndpoint: 'fal-ai/flux-2-pro',+ editEndpoint: 'fal-ai/flux-2-pro/edit',+ maxInputImages: 9,+ sizing: FAL_IMAGE_SIZING.PIXELS,+ // FLUX latents are 16-px aligned; send an aligned size so fal.ai never+ // has to round a dimension the caller chose.+ alignTo: 16,+ seed: true,+ // Defaults to jpeg; ask for png so the gallery gets lossless bytes.+ outputFormat: 'png',+ // "$0.03 for the first megapixel of output, plus $0.015 per extra+ // megapixel of input and output, rounded up to the nearest megapixel."+ pricing: Object.freeze({ unit: 'megapixel', firstMegapixelUsd: 0.03, extraMegapixelUsd: 0.015 }),+ }),+]);++/** What a fal render uses when neither the request nor Settings names a model. */+export const FAL_IMAGE_DEFAULT_MODEL = FAL_IMAGE_FAMILIES[0].textEndpoint;++/** Every endpoint id a `cloudModel` / `imageGen.fal.model` may name. */+export const FAL_IMAGE_MODEL_IDS = Object.freeze(+ FAL_IMAGE_FAMILIES.flatMap((f) => [f.textEndpoint, f.editEndpoint]),+);++/**+ * The smallest reference cap across the catalog — the mode-level+ * `maxInputImages` for a caller that does not know which fal model will+ * render, so it never offers a slot some fal model would drop.+ */+export const FAL_IMAGE_MIN_INPUT_IMAGES = Math.min(...FAL_IMAGE_FAMILIES.map((f) => f.maxInputImages));++/** The family an endpoint id belongs to (text or edit id), or null. */+export const falImageFamily = (modelId) => (typeof modelId === 'string'+ ? FAL_IMAGE_FAMILIES.find((f) => f.textEndpoint === modelId.trim() || f.editEndpoint === modelId.trim()) || null+ : null);++export const isFalImageModel = (modelId) => falImageFamily(modelId) !== null;++/** Human price tag for a picker row: "$0.15/image", "~$0.03/MP". */+export const falImagePriceLabel = (family) => (family.pricing.unit === 'megapixel'+ ? `~$${family.pricing.firstMegapixelUsd}/MP`+ : `$${family.pricing.usd}/image`);++// Nominal long side of each resolution tier. Gemini's tiers name the SHORT+// side of a square — a 1K 16:9 frame is ~1376 px wide — so a requested long+// side up to 1.4× the nominal still lands on that tier rather than paying for+// the next one.+const RESOLUTION_LONG_SIDE = Object.freeze({ '0.5K': 512, '1K': 1024, '2K': 2048, '4K': 4096 });+const RESOLUTION_SLACK = 1.4;++const validDims = (width, height) => {+ const w = Number(width);+ const h = Number(height);+ return Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0 ? { w: Math.round(w), h: Math.round(h) } : null;+};++function nearestRatio(w, h, ratios) {+ const target = w / h;+ let best = null;+ let bestDelta = Infinity;+ for (const ratio of ratios) {+ const [rw, rh] = ratio.split(':').map(Number);+ const delta = Math.abs((rw / rh) - target);+ if (delta < bestDelta) {+ bestDelta = delta;+ best = ratio;+ }+ }+ return best;+}++function resolutionTier(w, h, tiers) {+ const longSide = Math.max(w, h);+ return tiers.find((tier) => RESOLUTION_LONG_SIDE[tier] * RESOLUTION_SLACK >= longSide) || tiers[tiers.length - 1];+}++const align = (n, step) => Math.max(step, Math.round(n / step) * step);++// fal.ai's megapixel is binary — its own worked example bills a 1024×1024+// output as exactly one megapixel and a 1920×1080 one as two.+export const FAL_MEGAPIXEL = 1024 * 1024;++/**+ * Estimated USD for one render. An ESTIMATE — recorded in the sidecar so a+ * gallery image can say roughly what it cost, not a billing record.+ * `inputMegapixels` is the total size of the input images in FAL_MEGAPIXEL+ * units (FLUX.2 bills them);+ * `outputPixels` is `{ w, h }` when known.+ */+export function estimateFalImageCostUsd(family, { resolution = null, outputPixels = null, inputMegapixels = 0 } = {}) {+ const { pricing } = family;+ if (pricing.unit === 'megapixel') {+ // FLUX.2's defaults when no size was sent: t2i renders landscape_4_3+ // (1024×768), and edit `auto` follows the input — call it one megapixel.+ const outMp = outputPixels ? (outputPixels.w * outputPixels.h) / FAL_MEGAPIXEL : 1;+ const billedMp = Math.max(1, Math.ceil(outMp)) + Math.ceil(inputMegapixels);+ return Math.round((pricing.firstMegapixelUsd + (billedMp - 1) * pricing.extraMegapixelUsd) * 10000) / 10000;+ }+ const multiplier = (resolution && pricing.resolutionMultipliers?.[resolution]) || 1;+ return Math.round(pricing.usd * multiplier * 10000) / 10000;+}++/**+ * Build the fal.ai request for one render.+ *+ * @param {object} opts+ * @param {string} opts.modelId - any catalog endpoint id (text or edit)+ * @param {string} opts.prompt+ * @param {string} [opts.negativePrompt]+ * @param {number} [opts.width] - requested canvas; absent → the model's default geometry+ * @param {number} [opts.height]+ * @param {string[]} [opts.imageUrls] - input images (URLs or data URIs), init image first+ * @param {number} [opts.inputMegapixels] - their combined size, for the cost estimate+ * @param {number} [opts.seed]+ * @returns {{ family, endpointId, body, resolution, estimatedCostUsd }|null}+ * null when `modelId` is not in the catalog.+ */+export function buildFalImageRequest({+ modelId, prompt = '', negativePrompt = '', width, height, imageUrls = [], inputMegapixels = 0, seed,+}) {+ const family = falImageFamily(modelId);+ if (!family) return null;+ const refs = (Array.isArray(imageUrls) ? imageUrls : []).filter(Boolean).slice(0, family.maxInputImages);+ const endpointId = refs.length ? family.editEndpoint : family.textEndpoint;+ const avoid = typeof negativePrompt === 'string' && negativePrompt.trim() ? `\nAvoid: ${negativePrompt.trim()}` : '';+ // `num_images` is left at every endpoint's default of 1 (FLUX.2 [pro] has+ // no such field at all) — one PortOS render is one image.+ const body = { prompt: `${String(prompt).trim()}${avoid}` };+ if (refs.length) body.image_urls = refs;+ if (family.outputFormat) body.output_format = family.outputFormat;+ // A negative seed is PortOS's "random" sentinel — let fal.ai pick one.+ const seedNum = typeof seed === 'number' ? seed : (typeof seed === 'string' && seed.trim() ? Number(seed) : NaN);+ if (family.seed && Number.isInteger(seedNum) && seedNum >= 0) body.seed = seedNum;++ const dims = validDims(width, height);+ let resolution = null;+ let outputPixels = null;+ if (dims && family.sizing === FAL_IMAGE_SIZING.ASPECT_RATIO) {+ body.aspect_ratio = nearestRatio(dims.w, dims.h, family.aspectRatios);+ resolution = resolutionTier(dims.w, dims.h, family.resolutions);+ body.resolution = resolution;+ } else if (dims) {+ outputPixels = family.alignTo ? { w: align(dims.w, family.alignTo), h: align(dims.h, family.alignTo) } : dims;+ body.image_size = { width: outputPixels.w, height: outputPixels.h };+ }+ return {+ family,+ endpointId,+ body,+ resolution,+ estimatedCostUsd: estimateFalImageCostUsd(family, { resolution, outputPixels, inputMegapixels: refs.length ? inputMegapixels : 0 }),+ };+}diff --git a/server/lib/falImageModels.test.js b/server/lib/falImageModels.test.jsnew file mode 100644index 0000000000..67d5f2c68f--- /dev/null+++ b/server/lib/falImageModels.test.js@@ -0,0 +1,57 @@+import { describe, it, expect } from 'vitest';+import {+ FAL_IMAGE_FAMILIES, FAL_IMAGE_MODEL_IDS, buildFalImageRequest, falImageFamily,+} from './falImageModels.js';++// The provider suite (services/imageGen/fal.test.js) drives a nano-banana and a+// FLUX.2 render end to end; this pins the per-family mapping matrix the wire+// body and the recorded cost depend on, which one render per family can't.+describe('falImageModels — request mapping and cost', () => {+ const build = (modelId, extra = {}) => buildFalImageRequest({ modelId, prompt: 'p', ...extra });++ it('names every catalog family by either endpoint id and refuses anything else', () => {+ for (const family of FAL_IMAGE_FAMILIES) {+ expect(falImageFamily(family.textEndpoint)).toBe(family);+ expect(falImageFamily(family.editEndpoint)).toBe(family);+ }+ expect(FAL_IMAGE_MODEL_IDS).toHaveLength(FAL_IMAGE_FAMILIES.length * 2);+ expect(build('fal-ai/flux-pro')).toBeNull();+ });++ it.each([+ // [model, width, height, aspect_ratio, resolution, cost]+ ['fal-ai/nano-banana-pro', 1344, 768, '16:9', '1K', 0.15],+ ['fal-ai/nano-banana-pro', 2560, 1440, '16:9', '2K', 0.15],+ ['fal-ai/nano-banana-pro', 4096, 4096, '1:1', '4K', 0.3],+ ['fal-ai/nano-banana-2', 512, 512, '1:1', '0.5K', 0.06],+ ['fal-ai/nano-banana-2', 832, 1216, '2:3', '1K', 0.08],+ ['fal-ai/nano-banana-2', 3840, 1600, '21:9', '4K', 0.16],+ ])('%s at %ix%i → %s / %s ≈ $%s', (modelId, width, height, aspect, resolution, cost) => {+ const req = build(modelId, { width, height });+ expect(req.body).toMatchObject({ aspect_ratio: aspect, resolution });+ expect(req.estimatedCostUsd).toBe(cost);+ });++ it('omits geometry entirely when no size was asked for, so each endpoint applies its own default', () => {+ const req = build('fal-ai/nano-banana-pro');+ expect(req.body).not.toHaveProperty('aspect_ratio');+ expect(req.body).not.toHaveProperty('resolution');+ expect(build('fal-ai/flux-2-pro').body).not.toHaveProperty('image_size');+ });++ it('sends Seedream pixel geometry and no seed/output_format fields its schema lacks', () => {+ const req = build('fal-ai/bytedance/seedream/v5/lite/text-to-image', { width: 2560, height: 1440, seed: 7 });+ expect(req.endpointId).toBe('fal-ai/bytedance/seedream/v5/lite/text-to-image');+ expect(req.body).toEqual({ prompt: 'p', image_size: { width: 2560, height: 1440 } });+ expect(req.estimatedCostUsd).toBe(0.035);+ });++ it('bills FLUX.2 by output plus input megapixels, rounded up', () => {+ // 1 MP output, no inputs → the first-megapixel price.+ expect(build('fal-ai/flux-2-pro', { width: 1024, height: 1024 }).estimatedCostUsd).toBe(0.03);+ // 2 MP output (1920×1088 aligned) + 1.2 MP of references → 2 + 2 billed MP.+ const edit = build('fal-ai/flux-2-pro', { width: 1920, height: 1080, imageUrls: ['a', 'b'], inputMegapixels: 1.2 });+ expect(edit.endpointId).toBe('fal-ai/flux-2-pro/edit');+ expect(edit.estimatedCostUsd).toBe(0.075);+ });+});diff --git a/server/lib/generationModes.js b/server/lib/generationModes.jsindex 08e9ff92ff..4a9b57c781 100644--- a/server/lib/generationModes.js+++ b/server/lib/generationModes.js@@ -12,16 +12,21 @@ export const IMAGE_GEN_MODE = Object.freeze({CODEX: 'codex',GROK: 'grok',AGY: 'agy',+ // fal.ai's metered queue REST API (services/imageGen/fal.js) — the same+ // literal as VIDEO_GEN_MODE.FAL below: one provider, one key, one id.+ FAL: 'fal',});export const IMAGE_GEN_MODES = Object.freeze(Object.values(IMAGE_GEN_MODE));-// Cloud-CLI image backends spend remote quota and run through the media queue's-// parallel cloud lane rather than the local accelerator lane.+// Cloud image backends spend remote quota (or money, for fal.ai) and run+// through the media queue's parallel cloud lane rather than the local+// accelerator lane.export const CLOUD_IMAGE_GEN_MODES = Object.freeze([IMAGE_GEN_MODE.CODEX,IMAGE_GEN_MODE.GROK,IMAGE_GEN_MODE.AGY,+ IMAGE_GEN_MODE.FAL,]);// The external SD-API backend remains synchronous; every other image backend@@ -33,13 +38,12 @@ 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 and REACTOR have no image-gen counterpart (issues #6213/#6214 are-// video-only), so they are video-only literals rather than re-exports of an-// IMAGE_GEN_MODE entry.+// REACTOR has no image-gen counterpart (issue #6214 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',+ FAL: IMAGE_GEN_MODE.FAL,REACTOR: 'reactor',});diff --git a/server/lib/generationModes.test.js b/server/lib/generationModes.test.jsindex 5f89eee241..3cdee1ec5e 100644--- a/server/lib/generationModes.test.js+++ b/server/lib/generationModes.test.js@@ -11,9 +11,9 @@ import {describe('generation mode alphabets', () => {it('derives immutable image mode lists from the shared discriminator', () => {- expect(IMAGE_GEN_MODES).toEqual(['external', 'local', 'codex', 'grok', 'agy']);- expect(CLOUD_IMAGE_GEN_MODES).toEqual(['codex', 'grok', 'agy']);- expect(QUEUEABLE_IMAGE_MODES).toEqual(['local', 'codex', 'grok', 'agy']);+ expect(IMAGE_GEN_MODES).toEqual(['external', 'local', 'codex', 'grok', 'agy', 'fal']);+ expect(CLOUD_IMAGE_GEN_MODES).toEqual(['codex', 'grok', 'agy', 'fal']);+ expect(QUEUEABLE_IMAGE_MODES).toEqual(['local', 'codex', 'grok', 'agy', 'fal']);expect([IMAGE_GEN_MODE,IMAGE_GEN_MODES,@@ -22,9 +22,9 @@ describe('generation mode alphabets', () => {].every(Object.isFrozen)).toBe(true);});- it('keeps the video backend alphabet in the image discriminator namespace, plus fal/reactor as video-only extras', () => {+ it('keeps the video backend alphabet in the image discriminator namespace, plus reactor as a video-only extra', () => {expect(VIDEO_GEN_MODE).toEqual({- LOCAL: IMAGE_GEN_MODE.LOCAL, GROK: IMAGE_GEN_MODE.GROK, FAL: 'fal', REACTOR: 'reactor',+ LOCAL: IMAGE_GEN_MODE.LOCAL, GROK: IMAGE_GEN_MODE.GROK, FAL: IMAGE_GEN_MODE.FAL, REACTOR: 'reactor',});expect(VIDEO_GEN_MODES).toEqual(['local', 'grok', 'fal', 'reactor']);expect(CLOUD_VIDEO_GEN_MODES).toEqual(['grok', 'fal', 'reactor']);diff --git a/server/lib/imageGenCapabilities.js b/server/lib/imageGenCapabilities.jsindex 59af546899..39b326d961 100644--- a/server/lib/imageGenCapabilities.js+++ b/server/lib/imageGenCapabilities.js@@ -11,8 +11,9 @@* a server-side parity suite bound three of the copies. The shipped defaults* and the aspect-ratio alphabets were unbound and could drift silently.*- * Nothing here may import anything but `generationModes.js`: the moment this- * file reaches a service module, the client copies come back.+ * Nothing here may import anything but `generationModes.js` and the equally+ * dependency-free `falImageModels.js` catalog: the moment this file reaches a+ * service module, the client copies come back.** The three service modules re-export their old bindings, so every existing* server import site is untouched — the same compatibility pattern `modes.js`@@ -20,6 +21,7 @@*/import { CLOUD_IMAGE_GEN_MODES, IMAGE_GEN_MODE, IMAGE_GEN_MODES } from './generationModes.js';+import { FAL_IMAGE_MIN_INPUT_IMAGES, falImageFamily } from './falImageModels.js';// Backends that cannot take an input image at all (#3243). Every *queueable*// backend now can: local (mflux/diffusers `--image-path` + FLUX.2 references),@@ -188,6 +190,18 @@ export const IMAGE_GEN_PROVIDER_CAPABILITIES = Object.freeze({// render has nothing to send.promptRequiredWithInputImage: true,}),+ [IMAGE_GEN_MODE.FAL]: Object.freeze({+ // The model IS the product here — each catalog family is a different+ // price and look (lib/falImageModels.js), and a per-render override is+ // validated against that catalog.+ supportsModelOverride: true,+ // The cap is per MODEL (14 / 10 / 9); `maxInputImages(mode, modelId)`+ // below reads it from the catalog. This mode-level value is the smallest+ // of them, for a caller that does not know which fal model will render.+ maxInputImages: FAL_IMAGE_MIN_INPUT_IMAGES,+ // Every catalog edit endpoint lists `prompt` as required.+ promptRequiredWithInputImage: true,+ }),});// Cloud CLIs that accept a per-render `cloudModel` override. Kept as data so a@@ -205,8 +219,17 @@ export const supportsCloudModelOverride = (mode) => MODEL_OVERRIDE_CAPABLE_MODES* image tool accepts. `null` for a non-cloud mode: the local runner's ceiling* is the form's own slot count, and external takes none at all (it never* reaches the resolver — `isEditCapableMode` rejects it first).+ *+ * `modelId` refines the answer for a backend whose cap depends on the model+ * (fal.ai); an unknown or absent model falls back to the mode-level value.*/-export const maxInputImages = (mode) => IMAGE_GEN_PROVIDER_CAPABILITIES[mode]?.maxInputImages ?? null;+export const maxInputImages = (mode, modelId = null) => {+ if (mode === IMAGE_GEN_MODE.FAL) {+ const family = falImageFamily(modelId);+ if (family) return family.maxInputImages;+ }+ return IMAGE_GEN_PROVIDER_CAPABILITIES[mode]?.maxInputImages ?? null;+};/*** Does a cloud-CLI render need a text prompt, given whether it carries an inputdiff --git a/server/lib/index.js b/server/lib/index.jsindex b747f544bc..362b07bd26 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -583,6 +583,7 @@ export * from './renderTargets.js';export * from './renderTiming.js';export * from './generationModes.js';export * from './imageGenCapabilities.js';+export * from './falImageModels.js';export * from './imageRuntimeRemedies.js';export * from './renderModeLadder.js';export * from './spriteVocabulary.js';diff --git a/server/lib/musicVideoAutomation.js b/server/lib/musicVideoAutomation.jsindex 99a6a3388d..fa87958d0b 100644--- a/server/lib/musicVideoAutomation.js+++ b/server/lib/musicVideoAutomation.js@@ -21,6 +21,7 @@ const IMAGE_TOOL_LABELS = {[IMAGE_GEN_MODE.CODEX]: 'Codex image gen',[IMAGE_GEN_MODE.GROK]: 'Grok image gen',[IMAGE_GEN_MODE.AGY]: 'Antigravity image gen',+ [IMAGE_GEN_MODE.FAL]: 'fal.ai image gen',[IMAGE_GEN_MODE.EXTERNAL]: 'External SD API',};const VIDEO_TOOL_LABELS = {diff --git a/server/lib/sseUtils.js b/server/lib/sseUtils.jsindex 39a9ffad51..60819cf380 100644--- a/server/lib/sseUtils.js+++ b/server/lib/sseUtils.js@@ -118,8 +118,8 @@ export const closeJobAfterDelay = (jobs, jobId, delay = SSE_CLEANUP_DELAY_MS, ex}, delay);};-// Shared "this job died" finalizer for the six media-generation backends-// (imageGen/{agy,codex,grok}.js, videoGen/{grok,fal,reactor}.js). Each used to+// Shared "this job died" finalizer for the media-generation backends+// (imageGen/{agy,codex,grok,fal}.js, videoGen/{grok,fal,reactor}.js). Each used to// carry a private ~10-line `finalizeError` doing the same eight things —// idempotency guard, clear the active-slot map, stamp `job.status = 'error'`,// drop from `activeJobs`, log, broadcast an SSE error frame, emit `failed`,diff --git a/server/lib/validation.js b/server/lib/validation.jsindex e357eb4fdd..ca07830a78 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -13,6 +13,7 @@ import { APP_FEATURE_IDS, INSTANCE_FEATURE_IDS, INSTANCE_FEATURE_GROUP_IDS } froimport { MAX_MONTHLY_COST } from './subscriptionSavings.js';import { MAX_PLAN_TIER_LENGTH } from './subscriptionPlanTiers.js';import { QUEUEABLE_IMAGE_MODES, VIDEO_GEN_MODES } from './generationModes.js';+import { FAL_IMAGE_MODEL_IDS } from './falImageModels.js';import { RENDER_TARGETS, RENDER_TARGET_BACKEND_AUTO } from './renderTargets.js';import {grokVideoDurationSchema, cloudModelIdString, recordRenderPinFields, isSafeSnapshotSource, isSafeSubdirFilter, csvIdsParam,@@ -2093,6 +2094,18 @@ export const videoModelTermsSchema = z.object({accepted: z.boolean(),});+// fal.ai Imagegen settings slice (`imageGen.fal`). The API key is NOT here —+// it is the fal.ai credential the video backend already owns (write-only via+// PUT /api/settings/credentials/fal). `model` must name a catalog endpoint+// (lib/falImageModels.js): each id is a different price, so free text is+// refused rather than persisted and discovered at render time.+export const imageGenFalSettingsSchema = z.object({+ enabled: z.boolean().optional(),+ model: z.preprocess((v) => (v === '' ? undefined : v), z.enum(FAL_IMAGE_MODEL_IDS).optional()),+ cleanC2PA: z.boolean().optional(),+ denoise: z.boolean().optional(),+});+export const imageGenAgySettingsSchema = z.object({enabled: z.boolean().optional(),agyPath: z.preprocess((v) => (v === '' ? undefined : v), z.string().trim().max(500).optional()),diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex 2682873c5d..1cf204bb67 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -19,7 +19,7 @@ import {import { optionalUploadFields, optionalUpload } from '../lib/multipart.js';import * as imageGen from '../services/imageGen/index.js';import { local, IMAGE_GEN_MODE, IMAGE_GEN_MODES } from '../services/imageGen/index.js';-import { resolveCloudProviderConfig } from '../services/imageGen/cloudProviderConfig.js';+import { maxInputImages, resolveCloudProviderConfig } from '../services/imageGen/cloudProviderConfig.js';import setupRouter from './imageGenSetup.js';import { enqueueJob, attachSseClient as attachQueueSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';import { recordUserAction } from '../services/userActions.js';@@ -479,7 +479,9 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {capability: fableLoomImageCapabilities({mode: providerMode,model,- inputBudget: mode === IMAGE_GEN_MODE.AGY ? 3 : MAX_REFERENCE_IMAGES,+ // The backend's own input cap (per model for fal.ai), never above+ // the form ceiling.+ inputBudget: Math.min(maxInputImages(mode, cloud?.modelId) ?? MAX_REFERENCE_IMAGES, MAX_REFERENCE_IMAGES),}),authoredPrompt: params.prompt,authoredNegativePrompt: params.negativePrompt,diff --git a/server/routes/settings.js b/server/routes/settings.jsindex 1dcbe50449..8299071aaa 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -26,7 +26,7 @@ import { storableAutoUpdateConfig } from '../lib/sharedSchemas.js';import { DEFAULT_UNTRUSTED_CONTENT_POLICY, untrustedContentSettingsSchema } from '../lib/untrustedContent.js';import { agentContextSettingsSchema } from '../lib/agentContextValidation.js';import { EFFORT_LEVELS } from '../lib/providerModels.js';-import { privateCredentialParamsSchema, privateCredentialInputSchema, backupConfigSchema, autoUpdateSettingsSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, hideFirstRunCardSchema, networkSetupPreferenceSchema, settingsEmbeddingsSchema, localLlmSettingsSchema, imessageConfigSchema, signalConfigSchema, beeperSettingsSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, instanceFeatureSettingsSchema, instanceFeatureIdSchema, instanceFeatureUpdateSchema, instanceFeatureGroupSettingsSchema, instanceFeatureGroupIdSchema, instanceFeatureGroupUpdateSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, federationSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, subscriptionPlanTiersMapSchema, usageApiBilledInstanceIdsSchema, namedOrchestrationProfileSchema, orchestrationProfilesSettingsSchema, harnessSettingsSchema, credentialBootstrapsSettingsSchema, validateRequest } from '../lib/validation.js';+import { privateCredentialParamsSchema, privateCredentialInputSchema, backupConfigSchema, autoUpdateSettingsSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, hideFirstRunCardSchema, networkSetupPreferenceSchema, settingsEmbeddingsSchema, localLlmSettingsSchema, imessageConfigSchema, signalConfigSchema, beeperSettingsSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, instanceFeatureSettingsSchema, instanceFeatureIdSchema, instanceFeatureUpdateSchema, instanceFeatureGroupSettingsSchema, instanceFeatureGroupIdSchema, instanceFeatureGroupUpdateSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, federationSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, imageGenFalSettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, subscriptionPlanTiersMapSchema, usageApiBilledInstanceIdsSchema, namedOrchestrationProfileSchema, orchestrationProfilesSettingsSchema, harnessSettingsSchema, credentialBootstrapsSettingsSchema, validateRequest } from '../lib/validation.js';const router = Router();@@ -578,6 +578,9 @@ router.put('/', asyncHandler(async (req, res) => {if (req.body?.imageGen?.agy !== undefined) {validateRequest(imageGenAgySettingsSchema.partial(), req.body.imageGen.agy);}+ if (req.body?.imageGen?.fal !== undefined) {+ validateRequest(imageGenFalSettingsSchema.partial(), req.body.imageGen.fal);+ }// Every local media lane spawns this interpreter (and image gen spawns the// `mflux-generate` beside it), so hold it to the guard the setup routes use:// a python basename, never an arbitrary binary (#8751). A cleared valuediff --git a/server/services/fableLoom/visualConditioning.js b/server/services/fableLoom/visualConditioning.jsindex bc323859d9..eebf98b5e1 100644--- a/server/services/fableLoom/visualConditioning.js+++ b/server/services/fableLoom/visualConditioning.js@@ -17,6 +17,7 @@ import {} from '../../lib/scenePrompt.js';import { resolveFableLoomProtagonistPresence } from '../../lib/fableLoomPlayback.js';import { REACTOR_MAX_PROMPT_LENGTH } from '../../lib/reactorVideoClip.js';+import { CLOUD_IMAGE_GEN_MODES } from '../../lib/generationModes.js';import {mergeNegativePromptTokens, stripStyleClause, universeStylePreset, universeVisualStyleTokens,} from '../../lib/universeVisualStyle.js';@@ -461,7 +462,8 @@ export async function compileFableLoomVisualRequest({export function fableLoomImageCapabilities({ mode, model = null, inputBudget = 4 }) {const localFlux2 = mode === 'local' && model?.runner === 'flux2';- const cloudEdit = ['codex', 'grok', 'agy'].includes(mode);+ // Every cloud image backend accepts reference images (imageGenCapabilities.js).+ const cloudEdit = CLOUD_IMAGE_GEN_MODES.includes(mode);return Object.freeze({version: 1, kind: 'image', backend: mode, modelId: model?.id || null,modelRevision: model?.revision || null,diff --git a/server/services/falQueue.js b/server/services/falQueue.jsnew file mode 100644index 0000000000..06f15828bd--- /dev/null+++ b/server/services/falQueue.js@@ -0,0 +1,231 @@+/**+ * fal.ai queue REST API — the transport shared by every fal.ai backend.+ *+ * fal.ai runs every model behind the same queue contract: POST the input to+ * `queue.fal.run/{endpoint}`, poll the returned `status_url` until COMPLETED,+ * then GET `response_url` for the output (which names a CDN URL for each file).+ * `videoGen/fal.js` (#6213) grew this transport inline; the image backend+ * (`imageGen/fal.js`) needs the exact same submit/poll/retrieve/cancel rules,+ * so they live here once rather than as two copies free to drift on the+ * retry/cancel semantics #8340 and #8564 had to fix.+ *+ * Only the transport is shared. Each caller keeps its own job map, SSE/event+ * vocabulary and output finalization — the `onPoll`/`onStatus` hooks on+ * `awaitFalCompletion` are how it reports progress in its own terms.+ */++import { readFile } from 'fs/promises';+import { ServerError } from '../lib/errorHandler.js';+import { describeFetchError } from '../lib/fetchErrorChain.js';+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';+import { detectImageFormat } from '../lib/mimeTypes.js';++export const FAL_QUEUE_BASE = 'https://queue.fal.run';++export const FAL_SUBMIT_TIMEOUT_MS = 30_000;+export const FAL_POLL_TIMEOUT_MS = 15_000;+export const FAL_POLL_INTERVAL_MS = 3000;+// A transient status-fetch failure (network blip, fal.ai 5xx) gets this many+// additional attempts — on the same FAL_POLL_INTERVAL_MS cadence, never+// resubmitting the paid generation — before the run is abandoned (#8340).+export const FAL_MAX_STATUS_RETRIES = 2;+const FAL_MAX_READ_RETRIES = 2;++/**+ * 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).+ *+ * The settings value lives under `videoGen.fal.apiKey` because the video+ * backend introduced it; `privateKeyStore.js` hydrates it there server-side.+ * The image backend deliberately reuses the SAME key — one fal.ai account, one+ * credential row — rather than growing an `imageGen.fal.apiKey` twin.+ */+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;+}++/** Read a local file into a `data:` URI — how fal.ai accepts inline inputs. */+export async function fileToDataUri(filePath) {+ const buf = await readFile(filePath);+ const detected = detectImageFormat(buf);+ const mime = detected?.mime || 'image/png';+ return `data:${mime};base64,${buf.toString('base64')}`;+}++/**+ * The per-request bookkeeping `cancelFalRequest` and `awaitFalCompletion`+ * share. `cancelUrl` is filled in once the submit returns.+ */+export const createFalRequestEntry = (apiKey) => ({+ apiKey, controller: new AbortController(), aborted: false, cancelUrl: null, canceledRemote: false, remoteTerminal: false,+});++// Best-effort, idempotent cancellation of the remote fal.ai request — shared+// by explicit user cancellation (cancel()/cancelAll()) and every local+// abandonment path (exhausted status retries, the render deadline) so an+// already-known cancel_url is never left unsent (#8340). A caught failure is+// logged for diagnosis but never rethrown: the local job still finalizes as+// failed/canceled either way. Guarded so it never re-sends once fired, and+// never fires once the remote request already reached a fal-reported+// terminal state (COMPLETED/ERROR) — there is nothing left to cancel there.+export async function cancelFalRequest(entry) {+ if (!entry || entry.canceledRemote || entry.remoteTerminal || !entry.cancelUrl || !entry.apiKey) return;+ entry.canceledRemote = true;+ try {+ const res = await fetchWithTimeout(entry.cancelUrl, {+ method: 'PUT',+ headers: { Authorization: `Key ${entry.apiKey}` },+ }, FAL_POLL_TIMEOUT_MS);+ if (!res.ok) console.error(`❌ fal.ai cancellation request failed: HTTP ${res.status}`);+ } catch (err) {+ console.error(`❌ fal.ai cancellation request failed: ${err?.message || err}`);+ }+}++/**+ * Submit one paid request. Resolves to the queue receipt with every URL the+ * rest of the run needs, falling back to the documented URL shapes when a+ * receipt omits one.+ */+export async function submitFalRequest({ 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' });+ }+ const requestBase = `${FAL_QUEUE_BASE}/${modelId}/requests/${payload.request_id}`;+ return {+ ...payload,+ cancel_url: payload.cancel_url || `${requestBase}/cancel`,+ status_url: payload.status_url || `${requestBase}/status`,+ response_url: payload.response_url || requestBase,+ };+}++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();+}++/**+ * Poll a submitted request until fal.ai reports it terminal, the caller+ * cancels it (`entry.aborted`), or `deadline` passes. Resolves to+ * `{ outcome: 'completed' | 'canceled' | 'failed', reason? }` and never+ * throws — every abandonment path has already sent the remote cancel.+ *+ * - `onPoll()` fires before every status request (the video lane uses it as+ * its watchdog activity heartbeat).+ * - `onStatus(status)` fires for every non-terminal status fal.ai reports+ * (`IN_QUEUE` / `IN_PROGRESS`), for the caller's progress wording.+ * - `timeoutMs` only names the budget in the deadline message.+ */+export async function awaitFalCompletion({+ entry, statusUrl, apiKey, deadline, timeoutMs, onPoll = () => {}, onStatus = () => {},+}) {+ let statusFailures = 0;+ while (Date.now() < deadline) {+ if (entry.aborted) return { outcome: 'canceled' };+ onPoll();+ let status;+ try {+ status = await pollFalStatus({ statusUrl, apiKey });+ } catch (err) {+ statusFailures += 1;+ if (statusFailures > FAL_MAX_STATUS_RETRIES) {+ await cancelFalRequest(entry);+ return { outcome: 'failed', reason: `fal.ai status checks failed ${statusFailures} times in a row: ${err?.message || err}` };+ }+ await new Promise((r) => setTimeout(r, FAL_POLL_INTERVAL_MS));+ continue;+ }+ statusFailures = 0;+ if (status.status === 'COMPLETED') {+ entry.remoteTerminal = true;+ break;+ }+ if (status.status === 'ERROR') {+ entry.remoteTerminal = true;+ return { outcome: 'failed', reason: `fal.ai render failed: ${status.error || 'unknown error'}` };+ }+ onStatus(status.status);+ await new Promise((r) => setTimeout(r, FAL_POLL_INTERVAL_MS));+ }+ if (entry.aborted) return { outcome: 'canceled' };+ if (Date.now() >= deadline) {+ await cancelFalRequest(entry);+ return { outcome: 'failed', reason: `fal.ai did not finish within ${Math.round(timeoutMs / 1000)}s` };+ }+ return { outcome: 'completed' };+}++/** A short, single-line reason from a fal error response body (`detail` string or validation list), or ''. */+async function falErrorDetail(response) {+ const text = typeof response.text === 'function' ? await response.text().catch(() => '') : '';+ if (!text) return '';+ let reason = text;+ try {+ const body = JSON.parse(text);+ const detail = body?.detail ?? body?.error ?? body?.message;+ reason = Array.isArray(detail)+ ? detail.map((d) => [d?.loc?.slice?.(-1)?.[0], d?.msg || d?.type].filter(Boolean).join(': ')).join('; ')+ : typeof detail === 'string' ? detail : JSON.stringify(detail ?? body);+ } catch { /* not JSON: keep the text */ }+ return reason.replace(/\s+/g, ' ').trim().slice(0, 300);+}++/**+ * Read the result of an already-paid render — the `response_url` JSON, or+ * (with `binary: true`) an output file's bytes. Retries only transient reads,+ * including body consumption; schema/JSON errors and permanent HTTP failures+ * must not enter this loop. `apiKey` is omitted for CDN downloads, which are+ * public URLs.+ */+export async function readCompletedFalResult(url, { apiKey, signal, deadline, binary = false, binaryTimeoutMs, label }) {+ const what = label || (binary ? 'download' : 'result retrieval');+ for (let attempt = 0; ; attempt += 1) {+ signal.throwIfAborted();+ const remaining = deadline - Date.now();+ if (remaining <= 0) throw new Error('fal.ai retrieval deadline exceeded');+ let response;+ try {+ response = await fetchWithTimeout(url, {+ ...(apiKey ? { headers: { Authorization: `Key ${apiKey}` } } : {}),+ signal,+ }, Math.min(remaining, binary ? binaryTimeoutMs : FAL_POLL_TIMEOUT_MS));+ if (!response.ok) {+ const transientRead = response.status === 408 || response.status === 429 || (response.status >= 500 && response.status <= 599);+ // A permanent failure on the result read is how fal reports a job that+ // failed on its side (a 422 with a `detail` naming the input or policy+ // violation). Keep that reason — without it the job just says "HTTP 422".+ const detail = !transientRead && !binary ? await falErrorDetail(response) : '';+ const error = new Error(`fal.ai ${what} failed: HTTP ${response.status}${detail ? ` — ${detail}` : ''}`);+ error.transientRead = transientRead;+ throw error;+ }+ const value = await (binary ? response.arrayBuffer() : response.json());+ signal.throwIfAborted();+ return value;+ } catch (err) {+ // Release error responses without waiting for an error body to download.+ // A rejected consumer has already released its fetch deadline.+ if (response?.body && !response.bodyUsed) void response.body.cancel().catch(() => {});+ signal.throwIfAborted();+ if (err instanceof SyntaxError) throw new Error('fal.ai did not return valid result JSON');+ const transient = err.transientRead ?? (err.name === 'AbortError' || err.name === 'TimeoutError' ||+ /ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|EAI_AGAIN|UND_ERR_(SOCKET|CONNECT_TIMEOUT|HEADERS_TIMEOUT|BODY_TIMEOUT)|fetch failed|network error|socket hang up/i.test(describeFetchError(err)));+ if (!transient || attempt >= FAL_MAX_READ_RETRIES) throw err;+ await new Promise((resolve) => setTimeout(resolve, Math.min(500 * (2 ** attempt), Math.max(0, deadline - Date.now()))));+ }+ }+}diff --git a/server/services/imageGen/cloudProviderConfig.js b/server/services/imageGen/cloudProviderConfig.jsindex d25ad86bd6..8b99f0487d 100644--- a/server/services/imageGen/cloudProviderConfig.js+++ b/server/services/imageGen/cloudProviderConfig.js@@ -9,7 +9,8 @@** `resolveCloudProviderConfig(settings, mode)` collapses all of it into one* call. The per-provider knowledge lives in `CLOUD_PROVIDER_SPECS` below, so- * adding a third cloud CLI is one spec entry instead of a sweep.+ * adding a cloud backend is one spec entry instead of a sweep — fal.ai (a+ * metered REST API rather than a CLI) was added exactly that way.** Deliberately a sibling of `modes.js` rather than part of it: modes.js is the* no-dependency enum module both provider modules import, and this file needs@@ -28,12 +29,20 @@ import {renderTargetDefaults,resolveRenderTargetPins,} from '../../lib/renderModeLadder.js';+import { FAL_IMAGE_DEFAULT_MODEL, FAL_IMAGE_MODEL_IDS, isFalImageModel } from '../../lib/falImageModels.js';import {AGY_IMAGEGEN_DEFAULT_MODEL,CODEX_IMAGEGEN_DEFAULT_MODEL,IMAGE_GEN_MODE,} from './modes.js';+// A saved `imageGen.fal.model` outside the catalog (hand-edited settings, or a+// model a later build retired) degrades to the shipped default rather than+// bricking every fal render; an explicit per-render override is refused+// instead — see `knownModels` below.+const falModelFrom = (c, override) => override+ || (isFalImageModel(c.model) ? c.model.trim() : FAL_IMAGE_DEFAULT_MODEL);+// The pure capability half of the specs below, plus the two predicates that// read it, live in the dependency-free `lib/imageGenCapabilities.js` leaf so// the client shares them instead of re-typing them. Re-exported here because@@ -54,6 +63,11 @@ export { isModeUsable, pickUsableMode, renderTargetDefaults };* - `label` — user-facing provider name used in every disabled message.* - `modelId` — the *effective* model id for display/metadata (codex and* agy default to their cheap tiers; grok's backend is fixed).+ * - `knownModels` — optional catalog for a per-render override. A+ * provider whose model ids are prices (fal.ai) must not let a+ * typo or a stale pin from another backend reach the wire, so+ * an override it rejects is a 400 (`unknownModelCode`)+ * rather than a silent fallback.* - `params` — the provider's knob bundle for a queue job / direct call.* Codex's `model` carries the effective (defaulted) id so the* queue row reports what actually renders; the provider@@ -112,6 +126,18 @@ export const CLOUD_PROVIDER_SPECS = Object.freeze({modelIsShippedDefault: overrideIsShippedDefault || (!override && !a.model),}),}),+ [IMAGE_GEN_MODE.FAL]: Object.freeze({+ ...IMAGE_GEN_PROVIDER_CAPABILITIES[IMAGE_GEN_MODE.FAL],+ label: 'fal.ai Imagegen',+ errorCode: 'FAL_IMAGEGEN_DISABLED',+ knownModels: FAL_IMAGE_MODEL_IDS,+ unknownModelCode: 'FAL_IMAGE_MODEL_UNKNOWN',+ modelId: falModelFrom,+ // No key in here: the queue persists job params in plaintext, so the+ // provider re-resolves the fal.ai key from live settings at dispatch —+ // the same rule videoGen/fal.js follows.+ params: (c, override) => ({ model: falModelFrom(c, override) }),+ }),});/**@@ -151,6 +177,12 @@ export function resolveCloudProviderConfig(settings, mode, overrides = {}) {const enabled = config.enabled === true;const requestedModel = typeof overrides.model === 'string' ? overrides.model.trim() : '';const modelOverride = spec.supportsModelOverride && requestedModel ? requestedModel : null;+ if (modelOverride && spec.knownModels && !spec.knownModels.includes(modelOverride)) {+ throw new ServerError(+ `${spec.label} has no model "${modelOverride}" — choose one of: ${spec.knownModels.join(', ')}`,+ { status: 400, code: spec.unknownModelCode },+ );+ }// Only meaningful ALONGSIDE an override: it says the id the caller handed in// is one this resolver itself produced from the shipped default a moment ago,// not a choice. Without an override the spec answers from the config as itdiff --git a/server/services/imageGen/cloudProviderConfig.test.js b/server/services/imageGen/cloudProviderConfig.test.jsindex a5573a9bb5..8633b9455e 100644--- a/server/services/imageGen/cloudProviderConfig.test.js+++ b/server/services/imageGen/cloudProviderConfig.test.js@@ -13,6 +13,7 @@ import {resolveQueueImageMode,} from './modes.js';import { recordRenderPin } from '../../lib/renderTargets.js';+import { FAL_IMAGE_DEFAULT_MODEL } from '../../lib/falImageModels.js';const settingsWith = (imageGen) => ({ imageGen });@@ -159,6 +160,41 @@ describe('resolveCloudProviderConfig', () => {});});+describe('resolveCloudProviderConfig — fal.ai', () => {+ it('defaults to Nano Banana Pro and bundles only the model — never the API key', () => {+ const cloud = resolveCloudProviderConfig(settingsWith({ fal: { enabled: true } }), IMAGE_GEN_MODE.FAL);+ expect(cloud.enabled).toBe(true);+ expect(cloud.modelId).toBe(FAL_IMAGE_DEFAULT_MODEL);+ expect(cloud.jobParams).toEqual({ mode: IMAGE_GEN_MODE.FAL, model: 'fal-ai/nano-banana-pro' });+ });++ it('honors a saved catalog model, and a per-render catalog override over it', () => {+ const settings = settingsWith({ fal: { enabled: true, model: 'fal-ai/flux-2-pro' } });+ expect(resolveCloudProviderConfig(settings, IMAGE_GEN_MODE.FAL).modelId).toBe('fal-ai/flux-2-pro');+ const overridden = resolveCloudProviderConfig(settings, IMAGE_GEN_MODE.FAL, {+ model: 'fal-ai/bytedance/seedream/v5/lite/edit',+ });+ expect(overridden.providerParams).toEqual({ model: 'fal-ai/bytedance/seedream/v5/lite/edit' });+ });++ it('refuses a per-render model outside the catalog instead of paying for a guess', () => {+ const settings = settingsWith({ fal: { enabled: true } });+ expect(() => resolveCloudProviderConfig(settings, IMAGE_GEN_MODE.FAL, { model: 'gpt-5.6-luna' }))+ .toThrow(expect.objectContaining({ status: 400, code: 'FAL_IMAGE_MODEL_UNKNOWN' }));+ });++ it('degrades a hand-edited saved model outside the catalog to the shipped default', () => {+ const cloud = resolveCloudProviderConfig(settingsWith({ fal: { enabled: true, model: 'fal-ai/unknown' } }), IMAGE_GEN_MODE.FAL);+ expect(cloud.modelId).toBe(FAL_IMAGE_DEFAULT_MODEL);+ });++ it('is disabled until the toggle is on', () => {+ const cloud = resolveCloudProviderConfig(settingsWith({}), IMAGE_GEN_MODE.FAL);+ expect(cloud.enabled).toBe(false);+ expect(cloud.disabledError).toMatchObject({ status: 400, code: 'FAL_IMAGEGEN_DISABLED' });+ });+});+describe('isModeUsable', () => {it('gates cloud modes on their enable toggle', () => {const s = settingsWith({ codex: { enabled: true }, grok: { enabled: false }, agy: { enabled: true } });diff --git a/server/services/imageGen/fal.js b/server/services/imageGen/fal.jsnew file mode 100644index 0000000000..219a29bcdb--- /dev/null+++ b/server/services/imageGen/fal.js@@ -0,0 +1,409 @@+/**+ * Image Gen — fal.ai queue REST API provider.+ *+ * The one image backend that is a metered HTTP API rather than a local CLI:+ * it submits to fal.ai's queue (`services/falQueue.js`, the transport the+ * fal.ai video backend also uses), polls until the render completes, downloads+ * the output, and lands it in the gallery with the same job/SSE/event contract+ * as `grok.js` / `agy.js` / `codex.js` — so the media queue dispatches it on+ * the parallel cloud lane exactly like them.+ *+ * Why it exists: strong reference-conditioned EDIT models (nano-banana, Seedream,+ * FLUX.2) are what make a consistent character sheet or set plate out of a+ * mood board. Any render that carries an input image routes to the chosen+ * family's `/edit` endpoint with the images attached as `image_urls`; a+ * text-only render goes to the family's text-to-image endpoint. The catalog,+ * per-model request builders and prices live in `lib/falImageModels.js`.+ *+ * Money: every submit is billed. The dispatcher refuses unless+ * `imageGen.fal.enabled` is on, `checkConnection` never submits (it reads the+ * free pricing endpoint), the model is validated against the curated catalog+ * rather than passed through as free text, and each render records its+ * estimated cost in the gallery sidecar.+ *+ * The API key is the same one the fal.ai video backend uses (settings+ * `videoGen.fal.apiKey`, hydrated from the private key store, or `FAL_KEY`).+ * It is re-resolved from live settings at dispatch and never rides in the+ * persisted queue job params.+ */++import { randomUUID } from 'crypto';+import { readFile } from 'fs/promises';+import { join } from 'path';+import sharp from 'sharp';+import { atomicWrite, detectImageFormat, ensureDir, PATHS, unlinkGuarded } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { withAbortTimeout } from '../../lib/abortTimeout.js';+import { anyAbortSignal } from '../../lib/requestAbort.js';+import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';+import { autoCleanGeneratedImage } from '../../lib/imageClean.js';+import { renderTimingFields } from '../../lib/renderTiming.js';+import {+ FAL_IMAGE_DEFAULT_MODEL, FAL_MEGAPIXEL, buildFalImageRequest, falImageFamily,+} from '../../lib/falImageModels.js';+import {+ broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, createJobFailureFinalizer, dispatchTerminalEvent,+} from '../../lib/sseUtils.js';+import { imageGenEvents } from '../imageGenEvents.js';+import { getSettings } from '../settings.js';+import {+ awaitFalCompletion, cancelFalRequest, createFalRequestEntry, readCompletedFalResult, resolveFalApiKey,+ submitFalRequest,+} from '../falQueue.js';+import { IMAGE_GEN_MODE, describeFidelity, visualReferenceRole } from './modes.js';+import { resolveInputImages } from './inputImages.js';+import { cloudPromptRequired } from './cloudProviderConfig.js';+import { rejectDegenerateFrame } from './frameGuard.js';++const MODE = IMAGE_GEN_MODE.FAL;++// An image render normally finishes in well under a minute, but fal.ai's queue+// can hold a request behind other tenants' work before it starts. Generous,+// and inside the media queue's cloud-lane watchdog (the poll loop emits+// 'activity' every few seconds, so that watchdog's idle clock never trips on a+// healthy wait). Env-overridable like the other cloud providers' caps.+const FAL_IMAGE_TIMEOUT_MS = (() => {+ const n = Number(process.env.FAL_IMAGE_TIMEOUT_MS);+ return Number.isFinite(n) && n > 0 ? n : 15 * 60 * 1000;+})();+// Bounds result retrieval plus the whole image download (headers and body).+const FAL_IMAGE_DOWNLOAD_TIMEOUT_MS = 5 * 60 * 1000;+const FAL_PRICING_URL = 'https://api.fal.ai/v1/models/pricing';+const FAL_PRICING_TIMEOUT_MS = 10_000;++// Inputs travel inline as base64 data URIs (the pattern the video backend+// uses — no separate upload step, nothing left behind on fal.ai's storage).+// A mood board can hold full-resolution photos, and up to 14 of them ride in+// one JSON body, so an input bigger than this is downscaled first. No model in+// the catalog conditions on more detail than this anyway.+const INPUT_MAX_LONG_SIDE = 2048;+const INPUT_MAX_BYTES = 4 * 1024 * 1024;++const jobs = new Map();+// jobId → the fal.ai request entry (falQueue.createFalRequestEntry), so+// cancel() can stop the poll loop AND cancel the billed remote request.+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);++// Cancel one specific render. jobId is required — with parallel renders an+// anonymous cancel would stop every in-flight one; use cancelAll() for that.+export const cancel = (jobId) => {+ if (!jobId) {+ throw new Error('imageGen/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;+ entry.controller.abort();+ cancelFalRequest(entry);+ return true;+};++export const cancelAll = () => {+ const ids = [...activeRequests.keys()];+ if (ids.length === 0) return false;+ for (const id of ids) cancel(id);+ return true;+};++const noKeyReason = 'No fal.ai API key configured — add it under Settings → Image Gen → Defaults (shared with the fal.ai video backend) or set FAL_KEY';++/**+ * Connection probe that never spends money: confirm a key is configured, then+ * ask fal.ai's FREE pricing endpoint for the chosen model — an authenticated+ * read that proves the key works and doubles as the price shown to the user.+ */+export async function checkConnection({ model } = {}) {+ const family = falImageFamily(model) || falImageFamily(FAL_IMAGE_DEFAULT_MODEL);+ const settings = await getSettings().catch(() => null);+ const apiKey = resolveFalApiKey(settings);+ if (!apiKey) return { connected: false, mode: MODE, reason: noKeyReason };+ const url = `${FAL_PRICING_URL}?endpoint_id=${encodeURIComponent(family.textEndpoint)}`;+ const res = await fetchWithTimeout(url, { headers: { Authorization: `Key ${apiKey}` } }, FAL_PRICING_TIMEOUT_MS)+ .catch((err) => ({ ok: false, status: 0, error: err }));+ if (res.status === 401 || res.status === 403) {+ return { connected: false, mode: MODE, reason: `fal.ai rejected the API key (HTTP ${res.status})` };+ }+ if (!res.ok) {+ const detail = res.error ? res.error.message : `HTTP ${res.status}`;+ return { connected: false, mode: MODE, reason: `fal.ai pricing check failed: ${detail}` };+ }+ const payload = await res.json().catch(() => null);+ const price = payload?.prices?.find((p) => p?.endpoint_id === family.textEndpoint);+ const priceLabel = price ? ` — $${price.unit_price}/${price.unit === 'images' ? 'image' : price.unit}` : '';+ return { connected: true, mode: MODE, model: `${family.label}${priceLabel}`, modelId: family.textEndpoint };+}++/**+ * The prompt a fal.ai edit model receives. These models read the attached+ * images in order and take plain-language direction about them, so the+ * init/reference roles the CLI providers spell out as tool arguments are+ * spelled out here as prose, with the same fidelity + reference wording the+ * CLI prompt builders share (describeFidelity / visualReferenceRole).+ */+export function buildFalPrompt({ prompt, hasInitImage = false, initImageStrength, referenceCount = 0 }) {+ const lines = [prompt.trim()];+ if (hasInitImage) {+ lines.push(`The first attached image is the source image to edit — ${describeFidelity(initImageStrength)}.`);+ if (referenceCount) {+ lines.push(`The remaining attached ${referenceCount === 1 ? 'image is' : 'images are'} ${visualReferenceRole(referenceCount)}.`);+ }+ } else if (referenceCount) {+ lines.push(`Use the attached ${referenceCount === 1 ? 'image' : 'images'} as ${visualReferenceRole(referenceCount)}.`);+ }+ return lines.join('\n\n');+}++// Read one input image into a data URI — the original bytes when they are a+// web format within the size budget, else a downscaled re-encode — and report+// its size in megapixels (FLUX.2 bills input megapixels).+async function encodeInputImage(filePath) {+ const metadata = await sharp(filePath).metadata();+ const longSide = Math.max(metadata.width || 0, metadata.height || 0);+ const passThrough = longSide <= INPUT_MAX_LONG_SIDE+ && (metadata.size ?? 0) <= INPUT_MAX_BYTES+ && ['png', 'jpeg', 'webp'].includes(metadata.format);+ if (passThrough) {+ const buffer = await readFile(filePath);+ const mime = detectImageFormat(buffer)?.mime || `image/${metadata.format}`;+ return { dataUri: `data:${mime};base64,${buffer.toString('base64')}`, megapixels: ((metadata.width || 0) * (metadata.height || 0)) / FAL_MEGAPIXEL };+ }+ const resized = sharp(filePath)+ .rotate()+ .resize({ width: INPUT_MAX_LONG_SIDE, height: INPUT_MAX_LONG_SIDE, fit: 'inside', withoutEnlargement: true });+ // Keep an alpha channel lossless; everything else goes JPEG to keep the+ // request body small.+ const mime = metadata.hasAlpha ? 'image/png' : 'image/jpeg';+ const { data, info } = await (metadata.hasAlpha ? resized.png() : resized.jpeg({ quality: 90 }))+ .toBuffer({ resolveWithObject: true });+ return { dataUri: `data:${mime};base64,${data.toString('base64')}`, megapixels: (info.width * info.height) / FAL_MEGAPIXEL };+}++// The first image URL in a fal.ai image result. Every catalog model answers+// `{ images: [{ url, … }] }`.+const firstImageUrl = (result) => {+ const url = Array.isArray(result?.images) ? result.images[0]?.url : null;+ return typeof url === 'string' && url.trim() ? url : null;+};++export async function generateImage({+ model, prompt = '', negativePrompt, width, height, seed,+ initImagePath, initImageStrength, referenceImagePaths = [],+ visualConditioning = null,+ jobId: providedJobId = null,+ cleanC2PA = false,+ denoise = false,+ apiKey: providedApiKey = null,+ settings = null,+}) {+ // The ingestion instant `renderTimingFields` measures from — see+ // lib/renderTiming.js.+ const renderStartedAtMs = Date.now();+ await ensureDir(PATHS.images);++ // The dispatcher / route already validated `model` against the catalog+ // (resolveCloudProviderConfig), and the queue persists the validated id.+ // This guard covers a direct caller and a job persisted by a build whose+ // catalog has since dropped the id — a paid call is never made against a+ // model the catalog does not describe.+ const family = falImageFamily(model || FAL_IMAGE_DEFAULT_MODEL);+ if (!family) {+ throw new ServerError(`fal.ai Imagegen has no model "${model}"`, { status: 400, code: 'FAL_IMAGE_MODEL_UNKNOWN' });+ }++ // Re-anchored to the allowed input roots and capped to THIS model's+ // reference limit (14 / 10 / 9) — see inputImages.js.+ const inputImages = resolveInputImages({+ mode: MODE, initImagePath, referenceImagePaths, modelId: family.textEndpoint,+ });+ if (cloudPromptRequired(MODE, inputImages.paths.length > 0) && !prompt?.trim()) {+ throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });+ }++ // Never threaded through job params (they persist in plaintext) — resolved+ // from live settings at dispatch, same as videoGen/fal.js.+ const effectiveSettings = settings || (providedApiKey ? null : await getSettings().catch(() => null));+ const apiKey = providedApiKey || resolveFalApiKey(effectiveSettings);+ if (!apiKey) {+ throw new ServerError(noKeyReason, { status: 400, code: 'FAL_NOT_CONFIGURED' });+ }++ const endpointId = inputImages.paths.length ? family.editEndpoint : family.textEndpoint;+ const jobId = providedJobId || randomUUID();+ const filename = `${jobId}.png`;+ const outputPath = join(PATHS.images, filename);+ const fullPrompt = buildFalPrompt({+ prompt,+ hasInitImage: Boolean(inputImages.initPath),+ initImageStrength,+ referenceCount: inputImages.referencePaths.length,+ });++ const meta = {+ id: jobId, prompt: prompt.trim(), negativePrompt: negativePrompt || '',+ width: width ? Number(width) : null, height: height ? Number(height) : null,+ filename, mode: MODE,+ // The endpoint that actually rendered (text vs /edit), plus the family the+ // user chose — a gallery reader should not have to re-derive either.+ model: endpointId,+ modelFamily: family.id,+ ...(inputImages.paths.length ? { inputImageCount: inputImages.paths.length } : {}),+ ...(visualConditioning ? { visualConditioning } : {}),+ createdAt: new Date().toISOString(),+ };+ const job = { ...meta, clients: [], status: 'running', renderStartedAtMs };+ jobs.set(jobId, job);++ console.log(`🎨 Generating image [${jobId.slice(0, 8)}] fal (${endpointId}): ${prompt.slice(0, 60)}…`);+ imageGenEvents.emit('started', { generationId: jobId, totalSteps: 1 });+ activeJobs.set(jobId, { ...meta, generationId: jobId, totalSteps: 1, step: 0, progress: 0, currentImage: null });+ broadcastSse(job, { type: 'status', message: 'Submitting to fal.ai…' });++ // Returns the job descriptor synchronously; the paid request runs+ // out-of-band while the client attaches to the per-job SSE stream.+ runFal(job, jobId, {+ apiKey, family, fullPrompt, negativePrompt, width, height, seed,+ inputPaths: inputImages.paths, outputPath, filename, meta, cleanC2PA, denoise,+ }).catch((err) => {+ console.error(`❌ fal image run failed [${jobId.slice(0, 8)}]: ${err?.message}`);+ });++ return {+ jobId, filename, path: `/data/images/${filename}`, generationId: jobId,+ mode: MODE,+ status: 'running',+ };+}++async function runFal(job, jobId, {+ apiKey, family, fullPrompt, negativePrompt, width, height, seed,+ inputPaths, outputPath, filename, meta, cleanC2PA = false, denoise = false,+}) {+ const entry = createFalRequestEntry(apiKey);+ activeRequests.set(jobId, entry);+ const deadline = Date.now() + FAL_IMAGE_TIMEOUT_MS;+ let wroteOutput = false;+ try {+ const encoded = [];+ for (const path of inputPaths) encoded.push(await encodeInputImage(path));+ const request = buildFalImageRequest({+ modelId: family.textEndpoint,+ prompt: fullPrompt,+ negativePrompt,+ width,+ height,+ seed,+ imageUrls: encoded.map((e) => e.dataUri),+ inputMegapixels: encoded.reduce((sum, e) => sum + e.megapixels, 0),+ });+ // Cancelled while the inputs were being encoded: nothing was submitted,+ // so there is nothing to pay for or cancel remotely.+ if (entry.aborted) return finalizeCanceled(job, jobId);++ const submitted = await submitFalRequest({ apiKey, modelId: request.endpointId, body: request.body });+ entry.cancelUrl = submitted.cancel_url;+ broadcastSse(job, { type: 'status', message: 'Queued at fal.ai…' });++ const polled = await awaitFalCompletion({+ entry, statusUrl: submitted.status_url, apiKey, deadline, timeoutMs: FAL_IMAGE_TIMEOUT_MS,+ onPoll: () => imageGenEvents.emit('activity', { generationId: jobId }),+ onStatus: (status) => broadcastSse(job, {+ type: 'status', message: status === 'IN_PROGRESS' ? 'Rendering…' : 'Queued at fal.ai…',+ }),+ });+ if (polled.outcome === 'canceled') return finalizeCanceled(job, jobId);+ if (polled.outcome === 'failed') return finalizeJobFailure(job, jobId, null, polled.reason);++ const { result, bytes } = await withAbortTimeout(FAL_IMAGE_DOWNLOAD_TIMEOUT_MS, async (timeoutSignal) => {+ const signal = anyAbortSignal([timeoutSignal, entry.controller.signal]);+ const retrievalDeadline = Date.now() + FAL_IMAGE_DOWNLOAD_TIMEOUT_MS;+ const response = await readCompletedFalResult(submitted.response_url, { apiKey, signal, deadline: retrievalDeadline });+ const imageUrl = firstImageUrl(response);+ if (!imageUrl) throw new Error('fal.ai completed but returned no image URL');+ broadcastSse(job, { type: 'status', message: 'Downloading image…' });+ const downloaded = await readCompletedFalResult(imageUrl, {+ signal, deadline: retrievalDeadline, binary: true, binaryTimeoutMs: FAL_IMAGE_DOWNLOAD_TIMEOUT_MS, label: 'image download',+ });+ return { result: response, bytes: Buffer.from(downloaded) };+ });+ if (entry.aborted) return finalizeCanceled(job, jobId);++ // Signature-sniff before anything reaches the gallery: an error page or+ // truncated body must never be accepted as an image. The gallery serves+ // by extension and sidecars assume PNG, so a JPEG/WebP result is+ // transcoded rather than shipped mislabeled.+ const format = detectImageFormat(bytes)?.format;+ if (!format) return finalizeJobFailure(job, jobId, null, 'fal.ai returned a file that is not an image');+ await atomicWrite(outputPath, format === 'png' ? bytes : await sharp(bytes).png().toBuffer());+ wroteOutput = true;+ if (entry.aborted) {+ await unlinkGuarded(outputPath).catch(() => {});+ return finalizeCanceled(job, jobId);+ }++ // Degenerate-frame gate (#4173) — a moderated/blank result must fail+ // here, not become a gallery record.+ const emptyFrame = await rejectDegenerateFrame(outputPath);+ if (emptyFrame) {+ await unlinkGuarded(outputPath).catch(() => {});+ return finalizeJobFailure(job, jobId, null, emptyFrame);+ }++ const sidecar = join(PATHS.images, `${jobId}.metadata.json`);+ const actualSeed = Number.isInteger(result?.seed) ? result.seed : (request.body.seed ?? null);+ await atomicWrite(sidecar, {+ ...meta,+ ...(request.body.aspect_ratio ? { aspectRatio: request.body.aspect_ratio } : {}),+ ...(request.resolution ? { resolution: request.resolution } : {}),+ ...(actualSeed != null ? { seed: actualSeed } : {}),+ // An ESTIMATE from the catalog's published prices — fal.ai bills the+ // account; this only lets a gallery record say roughly what it cost.+ estimatedCostUsd: request.estimatedCostUsd,+ ...renderTimingFields(job.renderStartedAtMs),+ }).catch(() => {});+ // Cleaners run BEFORE the SSE complete + completed events so subscribers+ // see the cleaned bytes.+ await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath: outputPath, sidecarPath: sidecar, mode: MODE });+ job.status = 'complete';+ if (activeRequests.get(jobId) === entry) activeRequests.delete(jobId);+ activeJobs.delete(jobId);+ console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename} (fal ${request.endpointId}, ~$${request.estimatedCostUsd})`);+ const done = { filename, path: `/data/images/${filename}` };+ dispatchTerminalEvent(+ jobId,+ () => broadcastSse(job, { type: 'complete', result: done }),+ () => imageGenEvents.emit('completed', { mode: MODE, generationId: jobId, path: done.path, filename }),+ );+ closeJobAfterDelay(jobs, jobId);+ } catch (err) {+ // An unanticipated throw (input encode, retrieval, transcode) may still+ // leave the remote request queued or running — cancel it. cancelFalRequest+ // no-ops once fal.ai reported a terminal state or before anything was+ // submitted. `force` because the success tail stamps 'complete' before its+ // last awaits.+ await cancelFalRequest(entry);+ if (wroteOutput && job.status !== 'complete') await unlinkGuarded(outputPath).catch(() => {});+ if (entry.aborted) return finalizeCanceled(job, jobId);+ finalizeJobFailure(job, jobId, null, `fal.ai image generation failed: ${err?.message || err}`, { force: true });+ }+}++const finalizeJobFailure = createJobFailureFinalizer({+ jobs,+ activeJobs,+ activeSlots: activeRequests,+ label: 'fal image generation',+ events: imageGenEvents,+ failedPayload: (jobId, reason) => ({ mode: MODE, generationId: jobId, error: reason }),+});+const finalizeCanceled = finalizeJobFailure.canceled;++// Test-only handles.+export const _internals = { encodeInputImage, firstImageUrl };diff --git a/server/services/imageGen/fal.test.js b/server/services/imageGen/fal.test.jsnew file mode 100644index 0000000000..2b1cea4ada--- /dev/null+++ b/server/services/imageGen/fal.test.js@@ -0,0 +1,242 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { mkdir, rm, readFile, writeFile } from 'fs/promises';+import { existsSync } from 'fs';+import { join } from 'path';+import { tmpdir } from 'os';+import sharp from 'sharp';++const TEST_ROOT = join(tmpdir(), `portos-fal-image-test-${process.pid}-${Date.now()}`);+const FAKE_IMAGES_DIR = join(TEST_ROOT, 'data-images');++vi.mock('../../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../../lib/fileUtils.js');+ actual.PATHS.images = FAKE_IMAGES_DIR;+ return {+ ...actual,+ ensureDir: vi.fn(async (dir) => mkdir(dir, { recursive: true })),+ };+});++const getSettingsMock = vi.fn();+vi.mock('../settings.js', () => ({ getSettings: getSettingsMock }));++const fal = await import('./fal.js');+const { imageGenEvents } = await import('../imageGenEvents.js');++const QUEUE = 'https://queue.fal.run';+const CDN_URL = 'https://cdn.example.com/out';++// A frame with real content — the degenerate-frame guard rejects flat canvases.+const noiseImage = (width, height, format = 'png') => {+ const raw = Buffer.alloc(width * height * 3);+ for (let i = 0; i < raw.length; i += 1) raw[i] = (i * 37 + (i % 7) * 91) % 256;+ const img = sharp(raw, { raw: { width, height, channels: 3 } });+ return (format === 'jpeg' ? img.jpeg() : img.png()).toBuffer();+};++const jsonResponse = (body, ok = true, status = 200) => ({ ok, status, json: async () => body });+const binaryResponse = (buf) => ({+ ok: true, status: 200, arrayBuffer: async () => buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength),+});++/**+ * A scripted fal.ai: records every call, answers the submit with a receipt,+ * the status poll from `statuses` (last one repeats), the response URL with an+ * images[] result, and the CDN with `output` bytes.+ */+const fakeFal = ({ endpoint, statuses = ['COMPLETED'], output, result = {}, onStatus } = {}) => {+ const calls = [];+ const requestBase = `${QUEUE}/${endpoint}/requests/req-1`;+ let statusIndex = 0;+ const fetchMock = vi.fn(async (url, opts = {}) => {+ calls.push({ url, method: opts.method || 'GET', body: opts.body ? JSON.parse(opts.body) : null, headers: opts.headers });+ if (url === `${QUEUE}/${endpoint}` && opts.method === 'POST') {+ return jsonResponse({+ request_id: 'req-1', status_url: `${requestBase}/status`, response_url: requestBase, cancel_url: `${requestBase}/cancel`,+ });+ }+ if (url === `${requestBase}/status`) {+ const status = statuses[Math.min(statusIndex, statuses.length - 1)];+ statusIndex += 1;+ await onStatus?.(status);+ return jsonResponse(typeof status === 'string' ? { status } : status);+ }+ if (url === `${requestBase}/cancel`) return jsonResponse({});+ if (url === requestBase) return jsonResponse({ images: [{ url: CDN_URL }], ...result });+ if (url === CDN_URL) return binaryResponse(output);+ throw new Error(`unexpected fetch: ${opts.method || 'GET'} ${url}`);+ });+ vi.stubGlobal('fetch', fetchMock);+ return { calls, submits: () => calls.filter((c) => c.method === 'POST') };+};++const terminal = new Map();+const waitForTerminal = async (jobId) => {+ await vi.waitFor(() => expect(terminal.get(jobId)).toBeTruthy(), { timeout: 5000 });+ return terminal.get(jobId);+};++beforeEach(async () => {+ imageGenEvents.removeAllListeners();+ terminal.clear();+ for (const type of ['completed', 'failed']) {+ imageGenEvents.on(type, (event) => terminal.set(event.generationId, { type, ...event }));+ }+ await rm(TEST_ROOT, { recursive: true, force: true }).catch(() => {});+ await mkdir(FAKE_IMAGES_DIR, { recursive: true });+ getSettingsMock.mockReset().mockResolvedValue({ videoGen: { fal: { apiKey: 'test-key' } } });+});++afterEach(async () => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ imageGenEvents.removeAllListeners();+ await rm(TEST_ROOT, { recursive: true, force: true }).catch(() => {});+});++describe('imageGen/fal — generateImage', () => {+ it('renders text-only on the family text endpoint, transcodes to PNG, and records model + cost in the sidecar', async () => {+ const started = vi.fn();+ imageGenEvents.on('started', started);+ const { calls, submits } = fakeFal({+ endpoint: 'fal-ai/nano-banana-2', output: await noiseImage(64, 36, 'jpeg'), result: { seed: 42 },+ });++ const job = await fal.generateImage({+ model: 'fal-ai/nano-banana-2', prompt: ' a neon harbour ', negativePrompt: 'blurry', width: 1920, height: 1080,+ });+ expect(job).toMatchObject({ mode: 'fal', status: 'running', filename: `${job.jobId}.png`, path: `/data/images/${job.jobId}.png` });+ expect(started).toHaveBeenCalledWith(expect.objectContaining({ generationId: job.jobId }));++ const event = await waitForTerminal(job.jobId);+ expect(event).toMatchObject({ type: 'completed', mode: 'fal', filename: `${job.jobId}.png` });++ expect(submits()).toHaveLength(1);+ expect(submits()[0].headers.Authorization).toBe('Key test-key');+ expect(submits()[0].body).toEqual({+ prompt: 'a neon harbour\nAvoid: blurry', output_format: 'png', aspect_ratio: '16:9', resolution: '2K',+ });+ // The CDN download is public — the key must not ride along to it.+ expect(calls.find((c) => c.url === CDN_URL).headers).toBeUndefined();++ const png = await readFile(join(FAKE_IMAGES_DIR, `${job.jobId}.png`));+ expect(png.subarray(1, 4).toString()).toBe('PNG');+ const sidecar = JSON.parse(await readFile(join(FAKE_IMAGES_DIR, `${job.jobId}.metadata.json`), 'utf8'));+ expect(sidecar).toMatchObject({+ mode: 'fal', model: 'fal-ai/nano-banana-2', modelFamily: 'nano-banana-2', prompt: 'a neon harbour',+ aspectRatio: '16:9', resolution: '2K', seed: 42,+ // $0.08 × 1.5 for a 2K render.+ estimatedCostUsd: 0.12,+ });+ expect(sidecar.renderMs).toEqual(expect.any(Number));+ });++ it('routes a render with references to the /edit endpoint as data URIs, capped at the model\'s reference limit', async () => {+ const refs = [];+ for (let i = 0; i < 11; i += 1) {+ const name = `ref-${i}.png`;+ await writeFile(join(FAKE_IMAGES_DIR, name), await noiseImage(16, 16));+ refs.push(name);+ }+ const { submits } = fakeFal({ endpoint: 'fal-ai/flux-2-pro/edit', output: await noiseImage(32, 48) });++ const job = await fal.generateImage({+ model: 'fal-ai/flux-2-pro', prompt: 'character sheet', width: 1000, height: 1500, referenceImagePaths: refs,+ });+ expect((await waitForTerminal(job.jobId)).type).toBe('completed');++ const { body } = submits()[0];+ // FLUX.2 [pro] edit takes at most 9 references; the surplus is dropped+ // before anything is encoded or billed.+ expect(body.image_urls).toHaveLength(9);+ expect(body.image_urls.every((u) => u.startsWith('data:image/png;base64,'))).toBe(true);+ expect(body.image_size).toEqual({ width: 1008, height: 1504 });+ expect(body.prompt).toContain('character sheet');+ expect(body.prompt).toContain('visual references for style, characters, and subject matter');+ expect(body).not.toHaveProperty('num_images');+ const sidecar = JSON.parse(await readFile(join(FAKE_IMAGES_DIR, `${job.jobId}.metadata.json`), 'utf8'));+ expect(sidecar).toMatchObject({ model: 'fal-ai/flux-2-pro/edit', inputImageCount: 9 });+ });++ it('defaults to Nano Banana Pro and switches to its /edit endpoint when an init image is attached', async () => {+ await writeFile(join(FAKE_IMAGES_DIR, 'source.png'), await noiseImage(16, 16));+ const { submits } = fakeFal({ endpoint: 'fal-ai/nano-banana-pro/edit', output: await noiseImage(16, 16) });+ const job = await fal.generateImage({ prompt: 'make it dusk', initImagePath: 'source.png', initImageStrength: 0.1 });+ expect((await waitForTerminal(job.jobId)).type).toBe('completed');+ expect(submits()[0].body.image_urls).toHaveLength(1);+ expect(submits()[0].body.prompt).toContain('The first attached image is the source image to edit');+ });++ it('refuses before any paid call when the model is outside the catalog or no key is configured', async () => {+ const { calls } = fakeFal({ endpoint: 'fal-ai/nano-banana-pro' });+ await expect(fal.generateImage({ model: 'fal-ai/not-curated', prompt: 'x' }))+ .rejects.toMatchObject({ status: 400, code: 'FAL_IMAGE_MODEL_UNKNOWN' });+ getSettingsMock.mockResolvedValue({});+ const prevEnv = process.env.FAL_KEY;+ delete process.env.FAL_KEY;+ await expect(fal.generateImage({ prompt: 'x' })).rejects.toMatchObject({ status: 400, code: 'FAL_NOT_CONFIGURED' });+ if (prevEnv !== undefined) process.env.FAL_KEY = prevEnv;+ expect(calls).toHaveLength(0);+ });++ it('fails without writing anything or sending a cancel when fal.ai reports ERROR', async () => {+ const { calls } = fakeFal({ endpoint: 'fal-ai/nano-banana-pro', statuses: [{ status: 'ERROR', error: 'content policy' }] });+ const job = await fal.generateImage({ prompt: 'x' });+ const event = await waitForTerminal(job.jobId);+ expect(event).toMatchObject({ type: 'failed', mode: 'fal', error: expect.stringContaining('content policy') });+ expect(calls.some((c) => c.url.endsWith('/cancel'))).toBe(false);+ expect(existsSync(join(FAKE_IMAGES_DIR, `${job.jobId}.png`))).toBe(false);+ });++ it('cancel(jobId) stops polling, cancels the billed remote request once, and lands nothing in the gallery', async () => {+ vi.useFakeTimers();+ const { calls } = fakeFal({ endpoint: 'fal-ai/nano-banana-pro', statuses: ['IN_PROGRESS'] });+ const job = await fal.generateImage({ prompt: 'x' });+ await vi.waitFor(() => expect(calls.some((c) => c.url.endsWith('/status'))).toBe(true));++ expect(fal.cancel(job.jobId)).toBe(true);+ expect(fal.cancel(job.jobId)).toBe(true);+ await vi.advanceTimersByTimeAsync(3000);+ const event = await waitForTerminal(job.jobId);++ expect(event).toMatchObject({ type: 'failed', error: 'Canceled' });+ const cancels = calls.filter((c) => c.url.endsWith('/cancel'));+ expect(cancels).toHaveLength(1);+ expect(cancels[0].method).toBe('PUT');+ expect(calls.some((c) => c.url === CDN_URL)).toBe(false);+ expect(existsSync(join(FAKE_IMAGES_DIR, `${job.jobId}.png`))).toBe(false);+ expect(fal.cancel(job.jobId)).toBe(false);+ });+});++describe('imageGen/fal — checkConnection', () => {+ it('reports a missing key without touching the network', async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+ getSettingsMock.mockResolvedValue({});+ const prevEnv = process.env.FAL_KEY;+ delete process.env.FAL_KEY;+ const status = await fal.checkConnection({});+ if (prevEnv !== undefined) process.env.FAL_KEY = prevEnv;+ expect(status).toMatchObject({ connected: false, mode: 'fal', reason: expect.stringContaining('No fal.ai API key') });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('verifies the key on the free pricing endpoint and never submits a paid request', async () => {+ const fetchMock = vi.fn(async (url) => jsonResponse({+ prices: [{ endpoint_id: 'fal-ai/bytedance/seedream/v5/lite/text-to-image', unit_price: 0.035, unit: 'images', currency: 'USD' }],+ }));+ vi.stubGlobal('fetch', fetchMock);+ const status = await fal.checkConnection({ model: 'fal-ai/bytedance/seedream/v5/lite/edit' });+ expect(status).toMatchObject({ connected: true, mode: 'fal', model: 'Seedream 5.0 Lite — $0.035/image' });+ expect(fetchMock).toHaveBeenCalledTimes(1);+ const [url, opts] = fetchMock.mock.calls[0];+ expect(url).toBe('https://api.fal.ai/v1/models/pricing?endpoint_id=fal-ai%2Fbytedance%2Fseedream%2Fv5%2Flite%2Ftext-to-image');+ expect(opts.method ?? 'GET').toBe('GET');+ });++ it('reports a rejected key as not connected', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ detail: 'nope' }, false, 401)));+ expect(await fal.checkConnection({})).toMatchObject({ connected: false, reason: expect.stringContaining('HTTP 401') });+ });+});diff --git a/server/services/imageGen/index.js b/server/services/imageGen/index.jsindex ec81d6e43d..885ca55991 100644--- a/server/services/imageGen/index.js+++ b/server/services/imageGen/index.js@@ -2,8 +2,9 @@* Image Gen — Mode-aware dispatcher.** Reads settings.imageGen.mode (default 'external' for backward compat) and- * routes generate/status calls to one of three providers: external SD-API,- * local mflux/diffusers, or the Codex CLI built-in image_gen tool.+ * routes generate/status calls to a provider: external SD-API, local+ * mflux/diffusers, one of the cloud CLIs (codex / grok / agy), or fal.ai's+ * metered queue API.** Per-request mode override: callers (the route, the voice tool) may pass* `params.mode` to force a specific backend without changing the saved@@ -20,6 +21,7 @@ import * as local from './local.js';import * as codex from './codex.js';import * as grok from './grok.js';import * as agy from './agy.js';+import * as fal from './fal.js';import {IMAGE_GEN_MODE, IMAGE_GEN_MODES, CLOUD_IMAGE_GEN_MODES, isEditCapableMode,} from './modes.js';@@ -36,6 +38,7 @@ const CLOUD_PROVIDERS = {[IMAGE_GEN_MODE.CODEX]: codex,[IMAGE_GEN_MODE.GROK]: grok,[IMAGE_GEN_MODE.AGY]: agy,+ [IMAGE_GEN_MODE.FAL]: fal,};// Re-export the enum + array so the existing import surface from this module@@ -146,7 +149,8 @@ export async function generateImage(params) {delete normalized.cloudModelIsShippedDefault;// Input images are supported by local (mflux/diffusers --image-path plus// FLUX.2 --reference-images), codex (image_gen.referenced_image_paths via the- // CLI's -i flag), grok (image_edit.image) and agy (generate_image.ImagePaths).+ // CLI's -i flag), grok (image_edit.image), agy (generate_image.ImagePaths) and+ // fal.ai (the model family's /edit endpoint's image_urls).// External SD-API has no input-image wiring in this codebase, so drop them// there rather than failing the whole render — the prompt still produces a// useful txt2img. (The route/prepareParams path rejects instead, because it@@ -233,7 +237,7 @@ export async function generateAvatar({ name, characterClass, prompt }) {// Callers wanting all of them can read individual providers via the// re-exports below.export async function getActiveJob() {- const jobs = [local.getActiveJob(), external.getActiveJob(), codex.getActiveJob(), grok.getActiveJob(), agy.getActiveJob()].filter(Boolean);+ const jobs = [local.getActiveJob(), external.getActiveJob(), codex.getActiveJob(), grok.getActiveJob(), agy.getActiveJob(), fal.getActiveJob()].filter(Boolean);if (!jobs.length) return null;return jobs.sort((a, b) => {const ta = a.createdAt ? Date.parse(a.createdAt) : 0;@@ -250,6 +254,7 @@ export const attachSseClient = (jobId, res) => {if (codex.attachSseClient(jobId, res)) return true;if (grok.attachSseClient(jobId, res)) return true;if (agy.attachSseClient(jobId, res)) return true;+ if (fal.attachSseClient(jobId, res)) return true;return false;};@@ -264,10 +269,11 @@ export const cancel = () => {const codexCancelled = codex.cancelAll();const grokCancelled = grok.cancelAll();const agyCancelled = agy.cancelAll();- return localCancelled || codexCancelled || grokCancelled || agyCancelled;+ const falCancelled = fal.cancelAll();+ return localCancelled || codexCancelled || grokCancelled || agyCancelled || falCancelled;};// Re-exports so routes can hit a specific backend directly when the request// is shape-specific (gallery, LoRAs). The dispatcher is for the generic// generate/status flow used by all modes.-export { local, external, codex, grok, agy };+export { local, external, codex, grok, agy, fal };diff --git a/server/services/imageGen/inputImages.js b/server/services/imageGen/inputImages.jsindex d7e8ab393a..54ba62ab36 100644--- a/server/services/imageGen/inputImages.js+++ b/server/services/imageGen/inputImages.js@@ -3,9 +3,9 @@* `initImagePath` + `referenceImagePaths` into the ordered, re-anchored,* per-backend-capped list a CLI hands to its image tool.*- * All three cloud CLIs take their input images as a single ordered array- * (codex `referenced_image_paths`, grok `image_edit.image`, agy `ImagePaths`),- * so they share one resolution rule: the init image, if any, leads — it is the+ * Every cloud backend takes its input images as a single ordered array+ * (codex `referenced_image_paths`, grok `image_edit.image`, agy `ImagePaths`,+ * fal.ai `image_urls`), so they share one resolution rule: the init image, if any, leads — it is the* one the fidelity phrase describes — followed by the reference slots in submit* order. Only the per-backend ceiling differs, and that lives on the provider* spec (`maxInputImages` in cloudProviderConfig.js) with the rest of the@@ -28,13 +28,15 @@ const asPathList = (value) => (Array.isArray(value) ? value : [])* @param {string} opts.mode - IMAGE_GEN_MODE key (picks the cap)* @param {string|null} opts.initImagePath - primary source image, if any* @param {string[]} opts.referenceImagePaths - additional reference images+ * @param {string|null} opts.modelId - the model that will render, for a+ * backend whose cap is per model (fal.ai); ignored by the others* @returns {{ paths: string[], initPath: string|null, referencePaths: string[] }}* `paths` is what the tool receives (init first). `initPath` is non-null only* when a valid init image survived, so callers can pick the edit-vs-reference* wording without re-deriving the ordering; `referencePaths` is the same list* minus that leading source image.*/-export function resolveInputImages({ mode, initImagePath = null, referenceImagePaths = [] } = {}) {+export function resolveInputImages({ mode, initImagePath = null, referenceImagePaths = [], modelId = null } = {}) {const rawInit = (typeof initImagePath === 'string' && initImagePath.trim()) ? initImagePath : null;// An unresolvable path drops out rather than failing the render — the caller// still gets a usable (possibly text-only) generation instead of a 500.@@ -46,7 +48,7 @@ export function resolveInputImages({ mode, initImagePath = null, referenceImagePconst ordered = [...(resolvedInit ? [resolvedInit] : []), ...resolvedRefs];// A mode with no declared cap (a direct caller passing something odd) gets no// truncation rather than a silent truncation to zero.- const limit = maxInputImages(mode) ?? ordered.length;+ const limit = maxInputImages(mode, modelId) ?? ordered.length;const paths = ordered.slice(0, limit);if (ordered.length > paths.length) {console.log(`⚠️ ${mode} accepts at most ${limit} input images — dropping ${ordered.length - paths.length} reference(s)`);diff --git a/server/services/imageGen/modes.js b/server/services/imageGen/modes.jsindex 0a63fbf3ec..08892a8ccc 100644--- a/server/services/imageGen/modes.js+++ b/server/services/imageGen/modes.js@@ -100,6 +100,7 @@ const MODE_LABELS = Object.freeze({[IMAGE_GEN_MODE.CODEX]: 'Codex',[IMAGE_GEN_MODE.GROK]: 'Grok',[IMAGE_GEN_MODE.AGY]: 'Agy',+ [IMAGE_GEN_MODE.FAL]: 'fal.ai',[IMAGE_GEN_MODE.EXTERNAL]: 'External',});@@ -174,8 +175,9 @@ export const nearestAgyAspectRatio = (width, height) => nearestAspectRatio(width/*** Resolve the queue-capable image mode for a render request: the per-request* override (honored only when that backend is enabled/available), else the- * saved dispatcher default, else codex → grok → agy → local. External never- * queues. Hoisted from the pipeline visual stages (#2896) so sprite renders and+ * saved dispatcher default, else the first enabled cloud backend in+ * CLOUD_IMAGE_GEN_MODES order (codex → grok → agy → fal) → local. External+ * never queues. Hoisted from the pipeline visual stages (#2896) so sprite renders and* any future queued surface share one enable-gating ladder — see issue #2881* for the wider param-assembly consolidation.*@@ -184,20 +186,11 @@ export const nearestAgyAspectRatio = (width, height) => nearestAspectRatio(width* this exact same ladder.*/export function resolveQueueImageMode(requested, settings) {- const codexEnabled = settings?.imageGen?.codex?.enabled === true;- const grokEnabled = settings?.imageGen?.grok?.enabled === true;- const agyEnabled = settings?.imageGen?.agy?.enabled === true;- if (requested === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;- if (requested === IMAGE_GEN_MODE.GROK && grokEnabled) return IMAGE_GEN_MODE.GROK;- if (requested === IMAGE_GEN_MODE.AGY && agyEnabled) return IMAGE_GEN_MODE.AGY;+ const cloudEnabled = (mode) => CLOUD_IMAGE_GEN_MODES.includes(mode) && settings?.imageGen?.[mode]?.enabled === true;+ if (cloudEnabled(requested)) return requested;if (requested === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;const settingsMode = settings?.imageGen?.mode;- if (settingsMode === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;- if (settingsMode === IMAGE_GEN_MODE.GROK && grokEnabled) return IMAGE_GEN_MODE.GROK;- if (settingsMode === IMAGE_GEN_MODE.AGY && agyEnabled) return IMAGE_GEN_MODE.AGY;+ if (cloudEnabled(settingsMode)) return settingsMode;if (settingsMode === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;- if (codexEnabled) return IMAGE_GEN_MODE.CODEX;- if (grokEnabled) return IMAGE_GEN_MODE.GROK;- if (agyEnabled) return IMAGE_GEN_MODE.AGY;- return IMAGE_GEN_MODE.LOCAL;+ return CLOUD_IMAGE_GEN_MODES.find(cloudEnabled) || IMAGE_GEN_MODE.LOCAL;}diff --git a/server/services/imageGenQuota.js b/server/services/imageGenQuota.jsindex 3bb110137c..dc6ddcaf7c 100644--- a/server/services/imageGenQuota.js+++ b/server/services/imageGenQuota.js@@ -32,7 +32,7 @@*/import { join } from 'path';-import { CLOUD_IMAGE_GEN_MODES, IMAGE_TOOL_NAMES, modeLabel } from './imageGen/modes.js';+import { CLOUD_IMAGE_GEN_MODES, IMAGE_GEN_MODE, IMAGE_TOOL_NAMES, modeLabel } from './imageGen/modes.js';import { imageGenEvents } from './imageGenEvents.js';import { atomicWrite, PATHS, readJSONFileStrict } from '../lib/fileUtils.js';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';@@ -56,7 +56,12 @@ const UNKNOWN_BLOCK_TTL_MS = 60 * 60 * 1000;// hand-maintained list, so a 4th cloud backend is tracked the moment it is// added there. Display names come from `modeLabel` for the same reason — one// backend must not appear under two names across the UI.-export const isQuotaTrackedImageMode = (mode) => CLOUD_IMAGE_GEN_MODES.includes(mode);+//+// fal.ai is the one cloud backend excluded: it is billed per image on a metered+// account, not drawn from a subscription quota window, so there is no reset to+// observe and its failures (content policy, bad input) are not quota blocks.+// Its spend is recorded per render instead (`estimatedCostUsd` in the sidecar).+export const isQuotaTrackedImageMode = (mode) => CLOUD_IMAGE_GEN_MODES.includes(mode) && mode !== IMAGE_GEN_MODE.FAL;/** Card id for the image-gen quota card, in the same namespace as the provider* family ids in providerUsage.js — a per-family read has to be able to name it. */diff --git a/server/services/imageGenQuota.test.js b/server/services/imageGenQuota.test.jsindex b434b6de08..20e3f37749 100644--- a/server/services/imageGenQuota.test.js+++ b/server/services/imageGenQuota.test.js@@ -143,6 +143,8 @@ describe('isQuotaTrackedImageMode', () => {// Local renders on the user's own GPU — there is no remote quota to report.expect(isQuotaTrackedImageMode('local')).toBe(false);expect(isQuotaTrackedImageMode('external')).toBe(false);+ // fal.ai is metered per image — no subscription window to report.+ expect(isQuotaTrackedImageMode('fal')).toBe(false);});});diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex a3839634d1..0885348aee 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -194,6 +194,7 @@ function getGenModuleForJob(job) {if (job.kind === 'image' && job.params?.mode === IMAGE_GEN_MODE.CODEX) return import('../imageGen/codex.js');if (job.kind === 'image' && job.params?.mode === IMAGE_GEN_MODE.GROK) return import('../imageGen/grok.js');if (job.kind === 'image' && job.params?.mode === IMAGE_GEN_MODE.AGY) return import('../imageGen/agy.js');+ if (job.kind === 'image' && job.params?.mode === IMAGE_GEN_MODE.FAL) return import('../imageGen/fal.js');if (job.kind === 'image') return import('../imageGen/local.js');return Promise.resolve(null);}diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex 43557becb3..9b64f876ad 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -63,6 +63,7 @@ const stubs = {generateChainedVideo: vi.fn(async () => ({ jobId: 'whatever' })),generateImage: vi.fn(async () => ({ jobId: 'whatever' })),generateImageCodex: vi.fn(async () => ({ jobId: 'whatever' })),+ generateImageFal: vi.fn(async () => ({ jobId: 'whatever' })),generateAudio: vi.fn(async () => ({ jobId: 'whatever' })),generateAudioRemote: vi.fn(async () => ({ jobId: 'whatever' })),generateImageRemote: vi.fn(async () => ({ jobId: 'whatever' })),@@ -128,6 +129,11 @@ vi.mock('../imageGen/codex.js', () => ({cancel: (...args) => stubs.cancelImageCodex(...args),}));+vi.mock('../imageGen/fal.js', () => ({+ generateImage: (...args) => stubs.generateImageFal(...args),+ cancel: (...args) => stubs.cancelImageCodex(...args),+}));+vi.mock('../audioGen/local.js', () => ({generateAudio: (...args) => stubs.generateAudio(...args),cancel: (...args) => stubs.cancelAudio(...args),@@ -1630,6 +1636,35 @@ describe('Codex lane', () => {);});+ it('dispatches a fal.ai image job to imageGen/fal.js on the cloud lane, beside a running GPU job', async () => {+ stubs.generateVideo.mockImplementation(() => new Promise(() => {}));+ stubs.generateImageFal.mockImplementation(() => new Promise(() => {}));++ const videoJob = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'video' } });+ const falJob = await mediaJobQueue.enqueueJob({+ kind: 'image',+ params: { prompt: 'fal plate', mode: 'fal', model: 'fal-ai/nano-banana-pro' },+ });+ // The GPU slot is taken by the video job, so the fal job can only have+ // started if it was classified onto the cloud lane.+ await waitFor(+ () => stubs.generateVideo.mock.calls.length === 1 && stubs.generateImageFal.mock.calls.length === 1,+ );+ expect(stubs.generateImageFal).toHaveBeenCalledWith(+ expect.objectContaining({ jobId: falJob.jobId, mode: 'fal', model: 'fal-ai/nano-banana-pro' }),+ );+ expect(stubs.generateImage).not.toHaveBeenCalled();+ expect(stubs.generateImageCodex).not.toHaveBeenCalled();++ videoGenEvents.emit('failed', { generationId: videoJob.jobId, error: 'cleanup' });+ imageGenEvents.emit('failed', { generationId: falJob.jobId, error: 'cleanup' });+ await waitFor(+ () =>+ mediaJobQueue.getJob(videoJob.jobId).status !== 'running' &&+ mediaJobQueue.getJob(falJob.jobId).status !== 'running',+ );+ });+it('queued Codex job reports position within the Codex lane (not counting GPU jobs)', async () => {// GPU job hangs so the GPU slot is occupied but separate from the Codex lane.stubs.generateVideo.mockImplementation(() => new Promise(() => {}));diff --git a/server/services/modelPinAudit.js b/server/services/modelPinAudit.jsindex 5bcc539b0a..14be690f54 100644--- a/server/services/modelPinAudit.js+++ b/server/services/modelPinAudit.js@@ -98,6 +98,18 @@ const pinnedModeProviderId = (mode) => (typeof mode === 'string' && PINNED_IMAGE/** Exported for the coverage guard above — not a runtime dependency. */export const PINNED_IMAGE_MODE_IDS = Object.freeze(Object.keys(PINNED_IMAGE_MODES));++/**+ * Override-capable modes deliberately NOT audited here, each with its reason —+ * the coverage guard accepts a mode in exactly one of the two lists.+ *+ * fal.ai: its model ids come from PortOS's own curated catalog+ * (lib/falImageModels.js), not a provider record whose catalog a vendor+ * refresh can retire. `resolveCloudProviderConfig` already refuses a per-render+ * id outside it and degrades a stale saved one to the shipped default, so+ * there is no provider catalog to reconcile a pin against.+ */+export const CATALOG_VALIDATED_IMAGE_MODE_IDS = Object.freeze([IMAGE_GEN_MODE.FAL]);export { MODEL_OVERRIDE_CAPABLE_MODES };const trimmed = (value) => (typeof value === 'string' ? value.trim() : '');diff --git a/server/services/modelPinAudit.test.js b/server/services/modelPinAudit.test.jsindex 978026a3f6..faae140635 100644--- a/server/services/modelPinAudit.test.js+++ b/server/services/modelPinAudit.test.js@@ -23,7 +23,7 @@ const { getActiveApps, updateAppTaskTypeOverride } = await import('./apps.js');const { collectRecordPins, clearRecordPin } = await import('./modelPinRecords.js');const { getAllTemplates, updateTemplate } = await import('./taskTemplates.js');const {- auditModelPins, clearModelPin, MODEL_OVERRIDE_CAPABLE_MODES, PINNED_IMAGE_MODE_IDS,+ auditModelPins, clearModelPin, MODEL_OVERRIDE_CAPABLE_MODES, PINNED_IMAGE_MODE_IDS, CATALOG_VALIDATED_IMAGE_MODE_IDS,} = await import('./modelPinAudit.js');// The retirement that motivated #7315: `gemini-3.5-flash-low` is gone, the@@ -71,7 +71,9 @@ describe('image-gen pin coverage', () => {it('audits every cloud mode that can carry a model override', () => {// Without this, a third override-capable backend lands a capability entry// and is then silently un-audited — its pins would never surface.- expect([...PINNED_IMAGE_MODE_IDS].sort()).toEqual([...MODEL_OVERRIDE_CAPABLE_MODES].sort());+ // A mode may instead be listed as catalog-validated (its ids are PortOS's+ // own, not a provider record's) — but never in both, and never in neither.+ expect([...PINNED_IMAGE_MODE_IDS, ...CATALOG_VALIDATED_IMAGE_MODE_IDS].sort()).toEqual([...MODEL_OVERRIDE_CAPABLE_MODES].sort());});});diff --git a/server/services/providerUsage.js b/server/services/providerUsage.jsindex f3dc634e3a..07d0c61af7 100644--- a/server/services/providerUsage.js+++ b/server/services/providerUsage.js@@ -16,7 +16,7 @@ import { createSingleFlight } from '../lib/singleFlight.js';import { readFileTail } from '../lib/fileUtils.js';import { codexHomeDir, readCodexRoutingOverride } from '../lib/codexUserConfig.js';import { getSettings } from './settings.js';-import { getImageGenQuota, IMAGE_GEN_FAMILY } from './imageGenQuota.js';+import { getImageGenQuota, IMAGE_GEN_FAMILY, isQuotaTrackedImageMode } from './imageGenQuota.js';import { mergeFleetQuotaCards } from '../lib/fleetQuotas.js';import { getFleetQuotaEntries } from './peerUsage.js';import { recordLocalQuotaCards } from './providerQuotaShare.js';@@ -949,8 +949,9 @@ const fetchImageGenQuota = async () => {console.error(`❌ Image-gen quota card: could not read settings (${err?.message || err}) — card omitted`);return null;});- const enabledModes = enabledCloudImageModes(settings);- if (!enabledModes.length) return null; // no cloud image backend → no card+ // Only quota-window backends — a fal.ai-only install has no quota to show.+ const enabledModes = enabledCloudImageModes(settings).filter(isQuotaTrackedImageMode);+ if (!enabledModes.length) return null; // no quota-tracked cloud image backend → no cardreturn getImageGenQuota({ enabledModes }).catch((err) => {console.error(`❌ Image-gen quota card failed: ${err?.message || err}`);return null;diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.jsindex 6f612a4c98..509e915288 100644--- a/server/services/sprites/reference.js+++ b/server/services/sprites/reference.js@@ -578,7 +578,7 @@ function resolveReferenceRenderRoute(settings, body, mode, spritePin) {status: 400, code: 'IMAGE_GEN_UNKNOWN_MODEL',});}- const effectiveModel = mode === IMAGE_GEN_MODE.CODEX || mode === IMAGE_GEN_MODE.AGY+ const effectiveModel = cloud?.supportsModelOverride? cloud.modelId: mode === IMAGE_GEN_MODE.LOCAL? selectedLocalModel.iddiff --git a/server/services/videoGen/fal.js b/server/services/videoGen/fal.jsindex eaf2f5954e..359c2483ef 100644--- a/server/services/videoGen/fal.js+++ b/server/services/videoGen/fal.js@@ -30,22 +30,28 @@ import { ensureDir, PATHS } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { withAbortTimeout } from '../../lib/abortTimeout.js';import { anyAbortSignal } from '../../lib/requestAbort.js';-import { describeFetchError } from '../../lib/fetchErrorChain.js';-import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';-import { detectImageFormat } from '../../lib/mimeTypes.js';-import { probeVideoDuration, probeVideoGeometry } from '../../lib/ffmpeg.js';import {FAL_DEFAULT_IMAGE_VIDEO_MODEL,FAL_DEFAULT_TEXT_VIDEO_MODEL,buildFalVideoRequest,getFalVideoModel,} from '../../lib/falVideoModels.js';+import { probeVideoDuration, probeVideoGeometry } from '../../lib/ffmpeg.js';import { attachSseClient as attachSse, closeJobAfterDelay, createJobFailureFinalizer } from '../../lib/sseUtils.js';import { videoGenEvents } from './events.js';import { finalizeGeneratedVideo, emitCloudRenderStatus, CLOUD_RENDER_PHASE } from './generateVideoHelpers.js';import { mutateVideoHistory } from './history.js';import { getSettings } from '../settings.js';import { nearestAspectRatio } from '../imageGen/modes.js';+import {+ FAL_QUEUE_BASE, awaitFalCompletion, cancelFalRequest, createFalRequestEntry, fileToDataUri,+ readCompletedFalResult, resolveFalApiKey, submitFalRequest,+} from '../falQueue.js';++// The queue transport (submit / poll / retrieve / cancel) is shared with the+// fal.ai image backend in `services/falQueue.js`. Re-exported so existing+// importers of the key resolver and base URL keep their path.+export { FAL_QUEUE_BASE, resolveFalApiKey };// The aspect_ratio set the LEGACY body sends for a model outside the curated// catalog — matches the free-tool automation's FAL_ASPECT_RATIOS@@ -54,21 +60,11 @@ import { nearestAspectRatio } from '../imageGen/modes.js';export const FAL_ASPECT_RATIOS = Object.freeze(['16:9', '9:16', '1:1']);export const deriveAspectRatio = (width, height) => nearestAspectRatio(width, height, FAL_ASPECT_RATIOS);-export const FAL_QUEUE_BASE = 'https://queue.fal.run';-// The defaults when a request names no model, one text-first and one// image-first (MiniMax Hailuo-02 standard) — owned by the catalog.export const FAL_DEFAULT_TEXT_MODEL = FAL_DEFAULT_TEXT_VIDEO_MODEL;export const FAL_DEFAULT_IMAGE_MODEL = FAL_DEFAULT_IMAGE_VIDEO_MODEL;-const FAL_SUBMIT_TIMEOUT_MS = 30_000;-const FAL_POLL_TIMEOUT_MS = 15_000;-const FAL_POLL_INTERVAL_MS = 3000;-// A transient status-fetch failure (network blip, fal.ai 5xx) gets this many-// additional attempts — on the same FAL_POLL_INTERVAL_MS cadence, never-// resubmitting the paid generation — before the run is abandoned (#8340).-const FAL_MAX_STATUS_RETRIES = 2;-const FAL_MAX_READ_RETRIES = 2;// Bounds completed-result retrieval, backoff, and the WHOLE download — headers and every byte of the video — now that// `fetchWithTimeout` holds its deadline through body consumption. It used to// bound only the headers, which left the multi-MB transfer itself with no@@ -98,39 +94,6 @@ export const getActiveJob = () => {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;-}--// Best-effort, idempotent cancellation of the remote fal.ai request — shared-// by explicit user cancellation (cancel()/cancelAll()) and every local-// abandonment path (exhausted status retries, the render deadline) so an-// already-known cancel_url is never left unsent (#8340). A caught failure is-// logged for diagnosis but never rethrown: the local job still finalizes as-// failed/canceled either way. Guarded so it never re-sends once fired, and-// never fires once the remote request already reached a fal-reported-// terminal state (COMPLETED/ERROR) — there is nothing left to cancel there.-async function cancelFalRequest(entry) {- if (!entry || entry.canceledRemote || entry.remoteTerminal || !entry.cancelUrl || !entry.apiKey) return;- entry.canceledRemote = true;- try {- const res = await fetchWithTimeout(entry.cancelUrl, {- method: 'PUT',- headers: { Authorization: `Key ${entry.apiKey}` },- }, FAL_POLL_TIMEOUT_MS);- if (!res.ok) console.error(`❌ fal.ai cancellation request failed: HTTP ${res.status}`);- } catch (err) {- console.error(`❌ fal.ai cancellation request failed: ${err?.message || err}`);- }-}-export const cancel = (jobId) => {if (!jobId) {throw new Error("videoGen/fal.cancel requires a jobId — use cancelAll() to terminate every in-flight render");@@ -150,13 +113,6 @@ export const cancelAll = () => {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')}`;-}-// Legacy source-audio body for a lip-sync model id outside the catalog; the// curated MiniMax H3 lip-sync route (#8977) builds through the catalog, which// also sends its output resolution. Neither takes a prompt, duration or aspect@@ -182,83 +138,6 @@ function buildRequestBody({ prompt, negativePrompt, duration, aspectRatio, imagereturn 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();-}--/** A short, single-line reason from a fal error response body (`detail` string or validation list), or ''. */-async function falErrorDetail(response) {- const text = typeof response.text === 'function' ? await response.text().catch(() => '') : '';- if (!text) return '';- let reason = text;- try {- const body = JSON.parse(text);- const detail = body?.detail ?? body?.error ?? body?.message;- reason = Array.isArray(detail)- ? detail.map((d) => [d?.loc?.slice?.(-1)?.[0], d?.msg || d?.type].filter(Boolean).join(': ')).join('; ')- : typeof detail === 'string' ? detail : JSON.stringify(detail ?? body);- } catch { /* not JSON: keep the text */ }- return reason.replace(/\s+/g, ' ').trim().slice(0, 300);-}--// Retry only reads of the already-paid render, including body consumption.-// Schema/JSON errors and permanent HTTP failures must not enter this loop.-async function readCompletedRender(url, { apiKey, signal, deadline, video = false }) {- for (let attempt = 0; ; attempt += 1) {- signal.throwIfAborted();- const remaining = deadline - Date.now();- if (remaining <= 0) throw new Error('fal.ai retrieval deadline exceeded');- let response;- try {- response = await fetchWithTimeout(url, {- ...(apiKey ? { headers: { Authorization: `Key ${apiKey}` } } : {}),- signal,- }, Math.min(remaining, video ? FAL_DOWNLOAD_TIMEOUT_MS : FAL_POLL_TIMEOUT_MS));- if (!response.ok) {- const transientRead = response.status === 408 || response.status === 429 || (response.status >= 500 && response.status <= 599);- // A permanent failure on the result read is how fal reports a job that- // failed on its side (a 422 with a `detail` naming the input or policy- // violation). Keep that reason — without it the job just says "HTTP 422".- const detail = !transientRead && !video ? await falErrorDetail(response) : '';- const error = new Error(`fal.ai ${video ? 'video download' : 'result retrieval'} failed: HTTP ${response.status}${detail ? ` — ${detail}` : ''}`);- error.transientRead = transientRead;- throw error;- }- const value = await (video ? response.arrayBuffer() : response.json());- signal.throwIfAborted();- return value;- } catch (err) {- // Release error responses without waiting for an error body to download.- // A rejected consumer has already released its fetch deadline.- if (response?.body && !response.bodyUsed) void response.body.cancel().catch(() => {});- signal.throwIfAborted();- if (err instanceof SyntaxError) throw new Error('fal.ai did not return valid result JSON');- const transient = err.transientRead ?? (err.name === 'AbortError' || err.name === 'TimeoutError' ||- /ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|EAI_AGAIN|UND_ERR_(SOCKET|CONNECT_TIMEOUT|HEADERS_TIMEOUT|BODY_TIMEOUT)|fetch failed|network error|socket hang up/i.test(describeFetchError(err)));- if (!transient || attempt >= FAL_MAX_READ_RETRIES) throw err;- await new Promise((resolve) => setTimeout(resolve, Math.min(500 * (2 ** attempt), Math.max(0, deadline - Date.now()))));- }- }-}-export async function generateVideo({apiKey: providedApiKey, settings, modelId: requestedModelId,prompt = '', negativePrompt, duration, aspectRatio, width, height,@@ -381,13 +260,11 @@ async function runFalVideo(job, jobId, {apiKey, modelId, prompt, negativePrompt, duration, aspectRatio, sourceImagePath, outputPath, filename, meta,audioFilePath = null, enableTranscription = false, requestSpec = null,}) {- const entry = {- apiKey, controller: new AbortController(), aborted: false, cancelUrl: null, canceledRemote: false, remoteTerminal: false,- };+ const entry = createFalRequestEntry(apiKey);activeRequests.set(jobId, entry);const deadline = Date.now() + FAL_RENDER_TIMEOUT_MS;try {- const imageDataUri = sourceImagePath ? await toDataUri(sourceImagePath) : null;+ const imageDataUri = sourceImagePath ? await fileToDataUri(sourceImagePath) : null;const audioDataUri = audioFilePath? `data:audio/wav;base64,${(await readFile(audioFilePath)).toString('base64')}`: null;@@ -399,59 +276,35 @@ async function runFalVideo(job, jobId, {// Cancelled while the inputs were being read: nothing was submitted, so// there is nothing to pay for or cancel remotely.if (entry.aborted) return finalizeCanceled(job, jobId);- 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}`;+ const submitted = await submitFalRequest({ apiKey, modelId, body });+ entry.cancelUrl = submitted.cancel_url;+ const responseUrl = submitted.response_url;- let statusFailures = 0;- while (Date.now() < deadline) {- if (entry.aborted) return finalizeCanceled(job, jobId);- videoGenEvents.emit('activity', { generationId: jobId });- let status;- try {- status = await pollFalStatus({ statusUrl, apiKey });- } catch (err) {- statusFailures += 1;- if (statusFailures > FAL_MAX_STATUS_RETRIES) {- await cancelFalRequest(entry);- return finalizeJobFailure(job, jobId, null, `fal.ai status checks failed ${statusFailures} times in a row: ${err?.message || err}`);- }- await new Promise((r) => setTimeout(r, FAL_POLL_INTERVAL_MS));- continue;- }- statusFailures = 0;- if (status.status === 'COMPLETED') {- entry.remoteTerminal = true;- break;- }- if (status.status === 'ERROR') {- entry.remoteTerminal = true;- return finalizeJobFailure(job, jobId, null, `fal.ai render failed: ${status.error || 'unknown error'}`);- }+ const polled = await awaitFalCompletion({+ entry, statusUrl: submitted.status_url, apiKey, deadline, timeoutMs: FAL_RENDER_TIMEOUT_MS,+ onPoll: () => videoGenEvents.emit('activity', { generationId: jobId }),// fal's own queue maps to SUBMIT rather than to the queued step: the// ladder's `queued` is PortOS's local queue, and stepping back to it// after the handover would read as the render having lost its place.- if (status.status === 'IN_PROGRESS') emitCloudRenderStatus(job, jobId, CLOUD_RENDER_PHASE.RENDER, 'Rendering…');- else emitCloudRenderStatus(job, jobId, CLOUD_RENDER_PHASE.SUBMIT, 'Queued at fal.ai…');- await new Promise((r) => setTimeout(r, FAL_POLL_INTERVAL_MS));- }- if (entry.aborted) return finalizeCanceled(job, jobId);- if (Date.now() >= deadline) {- await cancelFalRequest(entry);- return finalizeJobFailure(job, jobId, null, `fal.ai did not finish within ${Math.round(FAL_RENDER_TIMEOUT_MS / 1000)}s`);- }+ onStatus: (status) => (status === 'IN_PROGRESS'+ ? emitCloudRenderStatus(job, jobId, CLOUD_RENDER_PHASE.RENDER, 'Rendering…')+ : emitCloudRenderStatus(job, jobId, CLOUD_RENDER_PHASE.SUBMIT, 'Queued at fal.ai…')),+ });+ if (polled.outcome === 'canceled') return finalizeCanceled(job, jobId);+ if (polled.outcome === 'failed') return finalizeJobFailure(job, jobId, null, polled.reason);const buffer = await withAbortTimeout(FAL_DOWNLOAD_TIMEOUT_MS, async (timeoutSignal) => {const signal = anyAbortSignal([timeoutSignal, entry.controller.signal]);const retrievalDeadline = Date.now() + FAL_DOWNLOAD_TIMEOUT_MS;- const result = await readCompletedRender(responseUrl, { apiKey, signal, deadline: retrievalDeadline });+ const result = await readCompletedFalResult(responseUrl, { apiKey, signal, deadline: retrievalDeadline });const videoUrl = result?.video?.url || result?.video_url || result?.output?.video?.url;if (typeof videoUrl !== 'string' || !videoUrl.trim()) {throw new Error('fal.ai completed but returned no video URL');}emitCloudRenderStatus(job, jobId, CLOUD_RENDER_PHASE.FETCH, 'Downloading video…');- return Buffer.from(await readCompletedRender(videoUrl, { signal, deadline: retrievalDeadline, video: true }));+ return Buffer.from(await readCompletedFalResult(videoUrl, {+ signal, deadline: retrievalDeadline, binary: true, binaryTimeoutMs: FAL_DOWNLOAD_TIMEOUT_MS, label: 'video download',+ }));});if (entry.aborted) return finalizeCanceled(job, jobId);await writeFile(outputPath, buffer);@@ -504,5 +357,5 @@ const finalizeCanceled = finalizeJobFailure.canceled;// Test-only handles.export const _internals = {buildRequestBody,- toDataUri,+ toDataUri: fileToDataUri,};diff --git a/server/services/voice/tools/media.js b/server/services/voice/tools/media.jsindex 03fb362ce4..861b1d5584 100644--- a/server/services/voice/tools/media.js+++ b/server/services/voice/tools/media.js@@ -16,7 +16,7 @@ export const MEDIA_TOOLS = [{name: 'image_generate',description:- 'Generate an image from a text prompt and save it to the user\'s gallery. Defaults to the user\'s saved Image Gen backend. Pass `provider` to override per-call: "local", "external", "codex", "grok", or text-to-image-only "agy". Cloud CLI providers must be enabled in Settings. Returns the saved file path.',+ 'Generate an image from a text prompt and save it to the user\'s gallery. Defaults to the user\'s saved Image Gen backend. Pass `provider` to override per-call: "local", "external", "codex", "grok", "agy", or the metered (paid per image) "fal". Cloud providers must be enabled in Settings. Returns the saved file path.',parameters: {type: 'object',properties: {