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(video-gen): fal.ai video model catalog, per-model request bodies and cost estimates (#9230)
[._.]/1da4d8e21be0
diff --git a/client/src/components/musicVideo/ProductionPanel.jsx b/client/src/components/musicVideo/ProductionPanel.jsxindex a127c7aa74..5900fa261a 100644--- a/client/src/components/musicVideo/ProductionPanel.jsx+++ b/client/src/components/musicVideo/ProductionPanel.jsx@@ -136,7 +136,7 @@ function StartForm({ project, production }) {<div className="space-y-2"><p className="text-port-text-muted">Plans the board, generates the missing frames and clips, renders and reviews the draft, and revises failed sections — on the server, so you can close this tab.- Only the routes you allow are ever used, and it never exceeds the limits below. Metered routes have no known price, so a dollar cap refuses them.+ Only the routes you allow are ever used, and it never exceeds the limits below. fal.ai video is charged each take's estimated list price (its model, length and resolution); other metered routes have no known price, so a dollar cap refuses them.</p><fieldset className="min-w-0" aria-labelledby={idFor('pool-label')}><span id={idFor('pool-label')} className="block text-[11px] text-port-text-muted mb-1">Allowed image and video routes</span>diff --git a/client/src/components/musicVideo/SceneCard.jsx b/client/src/components/musicVideo/SceneCard.jsxindex f3f72ed789..5eeb1c245b 100644--- a/client/src/components/musicVideo/SceneCard.jsx+++ b/client/src/components/musicVideo/SceneCard.jsx@@ -1,6 +1,6 @@import { useRef, useState } from 'react';import { Trash2, Activity, ArrowUp, ArrowDown, Image as ImageIcon, Video, Maximize2, AlertTriangle, ImagePlus, Clapperboard, Scissors } from 'lucide-react';-import { formatDurationSec } from '../../utils/formatters.js';+import { formatDurationSec, formatUsd } from '../../utils/formatters.js';import { useVideoFileSrc } from '../../hooks/useVideoFileSrc.js';import SceneTakeStrip from './SceneTakeStrip.jsx';import { MUSIC_VIDEO_VISUAL_LAYERS, sceneHasAuthoredSpan } from '../../lib/musicVideoLayers.js';@@ -9,8 +9,13 @@ import { MUSIC_VIDEO_VISUAL_LAYERS, sceneHasAuthoredSpan } from '../../lib/musicconst LAYER_LABELS = { footage: 'Footage', still: 'Still image', card: 'Title card' };const STILL_MOVE_LABELS = [['hold', 'Hold'], ['push', 'Push in'], ['pan', 'Pan']];import {- grokCoverage, isPerformanceScene, performanceBlockedReason, performanceCapability, planPerformanceWindow, shotSplitLimit,+ falSceneTake, grokCoverage, isPerformanceScene, performanceBlockedReason, performanceCapability, planPerformanceWindow, shotSplitLimit,} from '../../lib/musicVideoShotTiming.js';+import { getFalVideoModel } from '../../lib/falVideoModels.js';++// "est. $0.81 (5.05s at 1080P)" — or null when the take cannot be priced.+const falEstimate = (take) => (take?.costUsd == null ? null+ : `est. ${formatUsd(take.costUsd)} (${take.seconds}s${take.resolution ? ` at ${take.resolution}` : ''})`);// The two timeline-bound scene fields rendered as identical number inputs.const SCENE_TIME_FIELDS = [['Start', 'startSec'], ['End', 'endSec']];@@ -43,6 +48,9 @@ const COVERAGE_TOLERANCE_SEC = 0.25;* verified source-audio conditioning is blocked here with the reason, and a* capable one names the provider, model, song window and cost before the* director spends anything. `songDurationSec` bounds the planned window.+ * `falVideoSettings` (the project's saved render pins) prices a fal take with+ * `falSceneTake` — the same answer the submit payload is built from — so the+ * card shows each take's estimated cost before it is paid for.* A shot longer than that lane renders in one take (the lip-sync audio window,* or Grok's longest clip) offers `onSplit(sceneId, backend)`, which cuts it* into contiguous scenes at lyric pauses / phrase boundaries server-side.@@ -53,7 +61,7 @@ export default function SceneCard({onMove, onDelete, onEditLocal, onSave,onGenerateFrame, onGenerateVideo, onContinueVideo,onOpenPreview, onSelectTake, onReviewTake, onImportTake, onImportClipTake, takeBusy = false, layered = false,- lipSyncBackend = '', songDurationSec = null, onSplit,+ lipSyncBackend = '', songDurationSec = null, onSplit, falVideoSettings = null,}) {// Pause the inline clip before opening the lightbox so the user can't hear// two desynced copies — MediaLightbox autoplays unmuted, and the thumb's@@ -94,6 +102,11 @@ export default function SceneCard({? (capability ? (plan.ok ? null : plan.message) : performanceBlockedReason(lipSyncBackend)): null;const grokPlan = !performance && lipSyncBackend === 'grok' && timedSpan != null ? grokCoverage(timedSpan) : null;+ const falTake = lipSyncBackend === 'fal' && layer === 'footage'+ ? falSceneTake({ scene, videoSettings: falVideoSettings || {}, songDurationSec })+ : null;+ const falCost = falEstimate(falTake);+ const performanceCost = falTake?.performance ? (falCost || capability?.costLabel) : capability?.costLabel;const splitLimit = layer === 'footage' ? shotSplitLimit(scene, lipSyncBackend) : null;const canSplit = splitLimit != null && timedSpan != null && timedSpan > splitLimit + 1e-6;const shotModeId = `mv-shot-mode-${scene.sceneId}`;@@ -225,7 +238,13 @@ export default function SceneCard({{performance && !performanceBlocked && (<p className="text-[11px] text-port-text-muted break-words" data-testid="performance-plan">Lip-sync via {capability.label} ({capability.modelId}) · song {formatDurationSec(plan.windowStartSec)}–{formatDurationSec(plan.windowEndSec)}- {plan.editInSec > 0 ? ` · shot starts ${plan.editInSec.toFixed(2)}s into the take` : ''} · {capability.costLabel}+ {plan.editInSec > 0 ? ` · shot starts ${plan.editInSec.toFixed(2)}s into the take` : ''} · {performanceCost}+ </p>+ )}+ {falTake && !falTake.performance && (+ <p className="text-[11px] text-port-text-muted break-words" data-testid="fal-cutaway-plan">+ fal.ai renders {falTake.seconds != null ? `a ${falTake.seconds}s ` : 'a '}clip on {getFalVideoModel(falTake.modelId)?.label || falTake.modelId}+ {' · '}{falCost || 'cost unknown — billed to your fal.ai account'}</p>)}{grokPlan && (@@ -343,7 +362,7 @@ export default function SceneCard({className="flex items-center gap-1 bg-port-border hover:bg-port-border/70 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0 whitespace-nowrap"title={videoBlockedReason || performanceBlocked|| (!scene.referenceImageId ? 'Generate a reference frame first'- : performance ? `Lip-sync this scene's frame to the song via ${capability.label} — ${capability.costLabel}`+ : performance ? `Lip-sync this scene's frame to the song via ${capability.label} — ${performanceCost}`: "Generate this scene's video from its reference frame (i2v)")}>{generatingVideo ? <Activity size={14} className="animate-spin" /> : <Video size={14} />}{generatingVideo ? 'Generating video…' : (scene.videoHistoryId ? 'New video take' : 'Generate video')}diff --git a/client/src/components/musicVideo/VideoRenderSettings.jsx b/client/src/components/musicVideo/VideoRenderSettings.jsxindex 6a00002478..de9093b248 100644--- a/client/src/components/musicVideo/VideoRenderSettings.jsx+++ b/client/src/components/musicVideo/VideoRenderSettings.jsx@@ -1,4 +1,14 @@import { GROK_VIDEO_DURATIONS } from '../../lib/grokVideoClip.js';+import {+ FAL_DEFAULT_IMAGE_VIDEO_MODEL, FAL_IMAGE_VIDEO_MODELS, describeFalVideoRate, falVideoResolutions, getFalVideoModel,+} from '../../lib/falVideoModels.js';+import { SOURCE_AUDIO_LIPSYNC } from '../../lib/musicVideoShotTiming.js';++const falSelectCls = 'w-full max-w-full bg-port-bg border border-port-border rounded px-1.5 py-1.5 text-sm disabled:opacity-50 sm:w-auto';+const falOptionLabel = (model) => {+ const rate = describeFalVideoRate(model.id);+ return rate ? `${model.label} · ${rate}` : model.label;+};// The project's saved scene-video render pins (backend → generation mode →// model → audio-reactive LoRA/strength, or Grok clip duration). Every control@@ -12,12 +22,18 @@ export default function VideoRenderSettings({ videoSettings, generating }) {audioReactiveReady, audioReactiveSelected, change,} = videoSettings;// fal.ai (#8968) is image-to-video only here — every scene render already- // starts from the director's chosen reference frame, so no generation-mode- // picker or model knob is exposed; the server resolves fal.ai's verified- // image-to-video model by default (videoGen/fal.js#FAL_DEFAULT_IMAGE_MODEL).+ // starts from the director's chosen reference frame, so the model picker+ // offers the curated start-frame models (lib/falVideoModels.js), each with+ // its list rate; blank is the default (Hailuo-02 image-to-video). The+ // resolution alphabet is per model, so a model change clears the pin.+ // Performance (lip-sync) takes always render on the lip-sync route, with+ // their own resolution pin (default 1080P).// The audio-reactive lane stays local-only (root AGENTS.md's environmental-// motion contract needs an independently verified provider capability).const locked = saving || generating;+ const falModel = getFalVideoModel(settings.falModelId || FAL_DEFAULT_IMAGE_VIDEO_MODEL);+ const falResolutions = falVideoResolutions(falModel);+ const lipSync = SOURCE_AUDIO_LIPSYNC.fal;return (<><label htmlFor="mv-video-backend" className="sr-only">Scene video renderer</label>@@ -147,6 +163,43 @@ export default function VideoRenderSettings({ videoSettings, generating }) {)}{settings.backend === 'fal' && (<>+ <label htmlFor="mv-fal-model" className="sr-only">fal.ai cutaway model</label>+ <select+ id="mv-fal-model"+ value={settings.falModelId || ''}+ onChange={(e) => change({ falModelId: e.target.value || null, falResolution: null })}+ disabled={locked}+ title="fal.ai image-to-video model for this project's cutaway scenes (list price per generated second)"+ className={`${falSelectCls} sm:max-w-[280px]`}+ >+ <option value="">{`Default · ${falOptionLabel(getFalVideoModel(FAL_DEFAULT_IMAGE_VIDEO_MODEL))}`}</option>+ {FAL_IMAGE_VIDEO_MODELS.filter((model) => model.id !== FAL_DEFAULT_IMAGE_VIDEO_MODEL).map((model) => (+ <option key={model.id} value={model.id}>{falOptionLabel(model)}</option>+ ))}+ {/* A model pinned on a peer with a newer catalog: kept, but it+ cannot be priced here. */}+ {settings.falModelId && !falModel && (+ <option value={settings.falModelId}>{`${settings.falModelId} · cost unknown`}</option>+ )}+ </select>+ {falResolutions.length > 0 && (+ <>+ <label htmlFor="mv-fal-resolution" className="sr-only">fal.ai cutaway resolution</label>+ <select+ id="mv-fal-resolution"+ value={falResolutions.includes(settings.falResolution) ? settings.falResolution : ''}+ onChange={(e) => change({ falResolution: e.target.value || null })}+ disabled={locked}+ title="Output resolution for fal.ai cutaway renders — higher costs more per second"+ className={falSelectCls}+ >+ <option value="">{`${falModel.resolution.default} (model default)`}</option>+ {falResolutions.map((res) => (+ <option key={res} value={res}>{`${res} · ${describeFalVideoRate(falModel.id, res)}`}</option>+ ))}+ </select>+ </>+ )}<label htmlFor="mv-fal-duration" className="sr-only">fal.ai scene clip duration</label><inputid="mv-fal-duration"@@ -156,10 +209,24 @@ export default function VideoRenderSettings({ videoSettings, generating }) {value={settings.falDuration ?? ''}onChange={(e) => change({ falDuration: e.target.value === '' ? null : Number(e.target.value) })}disabled={locked}- placeholder="model default"- title="Clip length in seconds for this project's fal.ai scene renders (blank uses the model's default)"+ placeholder="shot length"+ title="Clip length in seconds for this project's fal.ai cutaway renders. Blank renders the shortest length the model offers that covers each shot (the model default for an untimed scene)."className="w-full max-w-full bg-port-bg border border-port-border rounded px-1.5 py-1.5 text-sm disabled:opacity-50 sm:w-24"/>+ <label htmlFor="mv-fal-lipsync-resolution" className="sr-only">fal.ai lip-sync resolution</label>+ <select+ id="mv-fal-lipsync-resolution"+ value={settings.falLipSyncResolution || ''}+ onChange={(e) => change({ falLipSyncResolution: e.target.value || null })}+ disabled={locked}+ title={`Output resolution for performance (lip-sync) takes on ${lipSync.label}`}+ className={falSelectCls}+ >+ <option value="">{`Lip-sync ${lipSync.defaultResolution} (default)`}</option>+ {lipSync.resolutions.map((res) => (+ <option key={res} value={res}>{`Lip-sync ${res} · ${describeFalVideoRate(lipSync.modelId, res)}`}</option>+ ))}+ </select></>)}</>diff --git a/client/src/hooks/useMusicVideoModelSettings.js b/client/src/hooks/useMusicVideoModelSettings.jsindex 33cad98cd6..ce1412c537 100644--- a/client/src/hooks/useMusicVideoModelSettings.js+++ b/client/src/hooks/useMusicVideoModelSettings.js@@ -67,6 +67,12 @@ export default function useMusicVideoModelSettings({ project, onProjectPatch } =// null/absent means "use fal's model default duration" — distinct from an// explicit pin, same null-means-unset contract as modelId above.falDuration: project?.videoSettings?.falDuration ?? null,+ // fal cutaway model / its resolution, and the lip-sync take resolution —+ // null means "the default" (Hailuo-02 image-to-video / that model's own /+ // MUSIC_VIDEO_LIPSYNC_DEFAULT_RESOLUTION), resolved by falSceneTake.+ falModelId: project?.videoSettings?.falModelId ?? null,+ falResolution: project?.videoSettings?.falResolution ?? null,+ falLipSyncResolution: project?.videoSettings?.falLipSyncResolution ?? null,generationMode: project?.videoSettings?.generationMode || 'image',audioReactiveLora: project?.videoSettings?.audioReactiveLora || '',audioReactiveScale: project?.videoSettings?.audioReactiveScale ?? 1.2,diff --git a/client/src/hooks/useMusicVideoSceneMedia.js b/client/src/hooks/useMusicVideoSceneMedia.jsindex 28b291300a..66d1549851 100644--- a/client/src/hooks/useMusicVideoSceneMedia.js+++ b/client/src/hooks/useMusicVideoSceneMedia.js@@ -7,7 +7,7 @@ import useSceneRenderLifecycle from './useSceneRenderLifecycle.js';import { isLtx2FamilyRuntime } from '../lib/runnerFamilies';import { sceneVisualLayer } from '../lib/musicVideoLayers.js';import {- approximateMotionCues, grokCoverage, isPerformanceScene, performanceBlockedReason,+ approximateMotionCues, falSceneTake, falTakeRequestFields, grokCoverage, isPerformanceScene, performanceBlockedReason,} from '../lib/musicVideoShotTiming.js';// Audio-reactive generation conditions motion on the song itself, so the prompt@@ -245,12 +245,14 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS// Request the 6/10s clip that COVERS this shot; the saved pin is only// the fallback for a scene not yet timed on the song.? { grokDuration: spanSec != null ? grokCoverage(spanSec).requestSec : settings.grokDuration }- // fal.ai (#8968) — image-to-video only (see VideoRenderSettings); an- // absent falDuration lets the server fall back to the resolved- // model's own default rather than forcing a value.+ // fal.ai (#8968) — image-to-video only (see VideoRenderSettings). The+ // request is exactly the take the scene card prices (falSceneTake):+ // a cutaway names its model, the length covering the shot (or the+ // pinned length) and its resolution; a performance clip's length+ // follows its song slice (server-side), so it sends only the lip-sync+ // resolution.: settings.backend === 'fal'- // A performance clip's length follows its song slice (server-side).- ? (performance ? {} : { falDuration: settings.falDuration || undefined })+ ? falTakeRequestFields(falSceneTake({ scene, videoSettings: settings, songDurationSec: project?.audioAnalysis?.durationSec ?? null })): settings.backend === 'local'? { modelId: settings.modelId || undefined, disableAudio: true }// A named model is local-only machinery at the server boundary anddiff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 828d163bf2..35890c30f3 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -61,7 +61,7 @@ grep -i "what you want to do" client/src/lib/README.md| `beatGrid.js` | Music-video beat-quantized timeline arranger (#1854). `buildBeatGridPoints(audioAnalysis)` merges beats/downbeats/section edges into one ranked snap-point list; `snapTimeToGrid(timeSec, gridPoints, toleranceSec)` finds the nearest point within tolerance; `computeSceneSpans(scenes, durationSec)` lays out scenes without a persisted `startSec`/`endSec` contiguously as a display-only fallback; `computeDragSpan({kind, startSpan, deltaSec, gridPoints, ...})` resolves a timeline drag gesture (`'move'` or `'right'` — no `'left'`, since the render can only trim from a clip's own frame 0) into a new span; `shouldMarkBeatAligned({kind, snapped, wasPersisted})` gates the `beatAligned` flag so a reposition-only drag can't silently promote an unpersisted scene's placeholder fallback duration into a "saved exactly" render duration; `autoArrangeScenes(scenes, audioAnalysis)` proposes a full `{ sceneId, startSec, endSec, beatAligned }[]` arrangement by distributing scenes across song sections weighted by each section's `energy` (#1915). Used by `components/musicVideo/BeatTimeline.jsx` and `pages/MusicVideo.jsx`. || `musicVideoLayers.js` | Music-video per-scene visual layers (#8985), re-exported from `server/lib/musicVideoLayers.js`: `MUSIC_VIDEO_VISUAL_LAYERS`, `MUSIC_VIDEO_STILL_MOVES`, `sceneVisualLayer(scene, { layered })`, `sceneHasAuthoredSpan`, `sceneRenderReady(scene, { layered })`. Used by `components/musicVideo/SceneCard.jsx`, `ProjectToolbar.jsx` and `hooks/useMusicVideoSceneMedia.js`. || `musicVideoTakes.js` | Music-video scene takes view helpers (#8965): `sceneTakeList(scene, kind)` lists a scene's image/video takes with an un-materialized pre-takes selection appended as a read-only `legacy` take; `takePreviewKey`, `takeThumbUrl`, `takeProvenance`; `TAKE_SLOT` maps a take kind to its selection field. Used by `components/musicVideo/SceneTakeStrip.jsx` and `pages/MusicVideo.jsx`. |-| `musicVideoShotTiming.js` | Re-export of `server/lib/musicVideoShotTiming.js` (#8977) — shot modes, the verified source-audio lip-sync capability table, `performanceBlockedReason`, `planPerformanceWindow`, `grokCoverage`, `approximateMotionCues`, `shotSplitLimit` (when a scene offers a lyric-boundary split). Used by `hooks/useMusicVideoSceneMedia.js` and `components/musicVideo/SceneCard.jsx`. |+| `musicVideoShotTiming.js` | Re-export of `server/lib/musicVideoShotTiming.js` (#8977) — shot modes, the verified source-audio lip-sync capability table, `performanceBlockedReason`, `planPerformanceWindow`, `grokCoverage`, `approximateMotionCues`, `shotSplitLimit` (when a scene offers a lyric-boundary split), `falSceneTake` (a fal take's model, length, resolution and estimated cost). Used by `hooks/useMusicVideoSceneMedia.js` and `components/musicVideo/SceneCard.jsx`. || `musicVideoUniverseRefs.js` | `pullUniverseCanonReferences(universe, existingReferences)` (#8978) maps a linked universe's characters/places/objects to visual-spec references (character/set/prop roles), skipping images already present and capping at `MUSIC_VIDEO_MAX_REFERENCES` (24, mirrors the server schema). Returns `{ next, added, skipped }`; the caller persists `next` via the ordinary visualSpec PATCH. Used by `components/musicVideo/VisualSpecPanel.jsx`. (The style snapshots are derived server-side, #9105.) || `musicVideoAutomation.js` | Music Video automation brief, client half: re-exports the server tool catalog (`MUSIC_VIDEO_AUTOMATION_TOOLS` / `_TOOL_IDS`), `DEFAULT_AUTOMATION_TOOLS` (the unmetered tools), and the form mapping `automationDraftFrom(automation)` / `automationFromDraft(draft)` (empty budget = no cap). Used by the create drawer and `AutomationPanel`. || `bibleLimits.js` | `BIBLE_LIMITS` re-exported from the pure leaf `server/lib/bibleLimits.js`, plus the client-only `capImageRefs` / `appendImageRefById` for the optimistic imageRefs-append paths. |@@ -150,6 +150,7 @@ grep -i "what you want to do" client/src/lib/README.md| `quotaBurnPatch.js` | `mergeQuotaBurnPatch(base, patch)` — mirrors the server's quota-burn config merge (top-level + per-family keys merge, a family's `jobs` array replaces) so the Quota Burn page can apply an edit optimistically and accumulate debounced edits into one PUT body. `quotaBurnJobIsSpent(job, ranAt)` — whether a `run once` step has had its one dispatch, gated on the optimistic config's own `runOnce` so a just-ticked checkbox reads as spent before the save round-trips (the client mirror of the server's `jobIsSpent`). `UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap(cap)` / `dispatchCapInput(value)` — the -1 "no dispatch cap" sentinel (the default), mirrored from the server. || `quotaBurnTasks.js` | `MAINTENANCE_TASK_ORDER` / `MAINTENANCE_ORDER_GUIDANCE` document the default ladder; `maintenanceSequence` populates audit and claim-drain references; `maintenancePrerequisites` lists missing saved settings and scoped setup patches for the selected mode and claim policy. The Quota Burn page's view of the SHARED scheduled-task catalog. `buildQuotaBurnTaskCatalog({ schedule, jobs, apps })` groups PortOS built-in task types and app custom jobs into the picker's two groups (dropping what a burn may never invoke, and stamping a `blockedReason` on what is merely disabled or untargetable); `searchTaskCatalog` / `flattenTaskCatalog` / `findTaskEntry` query it. `taskRefKey` / `stepFromTaskEntry` / `taskEntryNeedsApp` build and address a step's `taskRef`. `effectiveQuotaBurnSettings(step, saved)` mirrors the server's `effectiveSettings` (overrides layered over the task's saved settings, params merged key-by-key). `quotaBurnStepPayload(job)` reduces a step to what the strict PUT schema accepts, dropping the top-level override mirrors that would otherwise outrank the `overrides` bag. `taskSourceHref(entry)` / `CREATE_TASK_HREF` link out to the source task. || `clipboard.js` | `copyToClipboard`, `writeClipboardSilently`, `readClipboard` — safe across insecure-origin contexts. Use these instead of `navigator.clipboard.writeText` inline. |+| `falVideoModels.js` | Re-export of `server/lib/falVideoModels.js` — the curated fal.ai video model catalog, per-model request rules and `estimateFalVideoCostUsd()`. Used by the Music Video fal model picker (`components/musicVideo/VideoRenderSettings.jsx`) and the Video Gen page's fal model suggestions. || `falVideoHandoff.js` | `buildFalH3MaxPrompt(prompt, negativePrompt)` composes the provider-neutral shot prompt fal's free MiniMax H3 Max tool is driven with; `FAL_H3_MAX_FREE_URL` and `FAL_H3_MAX_FREE_ALLOWANCE_NOTE` carry the tool URL and current vendor allowance copy. The free web allowance is deliberately a handoff, not the separately metered fal API. || `compareHelpers.js` | `equalByKeys(a, b, keys)` / `equalListByKeys(a, b, keys)` — typed key-based equality for `useAutoRefetch`'s `compare`. Keys are property names, dotted paths (`'context.running'`), or `(item) => value` accessors. The typed alternative to `sameJsonShape` when a monotonic timestamp or unrendered field would break stringify-equality dedup. || `consoleFilters.js` | `installConsoleFilters()` — drops a small allow-list of known-noise console strings (THREE.js `Clock` deprecation, expected WebGL `Context Lost.`) from `console.{warn,log,debug}`. Idempotent; auto-installed on import. Imported for its side effect from `main.jsx`. |diff --git a/client/src/lib/falVideoModels.js b/client/src/lib/falVideoModels.jsnew file mode 100644index 0000000000..da800925e4--- /dev/null+++ b/client/src/lib/falVideoModels.js@@ -0,0 +1,17 @@+/**+ * Curated fal.ai video model catalog.+ *+ * Re-export of `server/lib/falVideoModels.js` — the one definition of each fal+ * model's request rules and list price, imported rather than copied so the+ * board's cost estimate and the server's request body cannot drift.+ */+export {+ FAL_DEFAULT_IMAGE_VIDEO_MODEL,+ FAL_DEFAULT_TEXT_VIDEO_MODEL,+ FAL_IMAGE_VIDEO_MODELS,+ FAL_VIDEO_MODELS,+ describeFalVideoRate,+ estimateFalVideoCostUsd,+ falVideoResolutions,+ getFalVideoModel,+} from '../../../server/lib/falVideoModels.js';diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 1e988a2711..533ba6f69c 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -45,6 +45,7 @@ export * from './eidoverseDraftReconcile.js';export * from './eidoverseWorldReset.js';export * from './federatedMediaReadiness.js';export * from './falVideoHandoff.js';+export * from './falVideoModels.js';export * from './fableLoomReadiness.js';export * from './glbFailure.js';export * from './grokVideoClip.js';diff --git a/client/src/lib/musicVideoShotTiming.js b/client/src/lib/musicVideoShotTiming.jsindex e2457de01d..171add9f78 100644--- a/client/src/lib/musicVideoShotTiming.js+++ b/client/src/lib/musicVideoShotTiming.js@@ -10,6 +10,8 @@ export {MUSIC_VIDEO_SHOT_MODES,SOURCE_AUDIO_LIPSYNC,approximateMotionCues,+ falSceneTake,+ falTakeRequestFields,grokCoverage,isPerformanceScene,performanceBlockedReason,diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 10b1b7d499..de80bb7e05 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -891,6 +891,7 @@ export default function MusicVideo() {videoBlockedReason={videoSettings.videoBlockedReason}lipSyncBackend={videoSettings.audioReactiveSelected ? 'local' : videoSettings.settings.backend}songDurationSec={selected.audioAnalysis?.durationSec ?? null}+ falVideoSettings={videoSettings.settings}canContinueShot={canContinueShot}onMove={moveScene}onDelete={handleDeleteScene}diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex e8dcfcbf84..f9d40e42fd 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -691,10 +691,14 @@ describe('MusicVideo project video renderer', () => {});expect(await screen.findByLabelText('fal.ai scene clip duration')).toHaveProperty('value', '6');+ // No model pin: the default Hailuo-02 image-to-video take, priced before it is paid for.+ expect((await screen.findByTestId('fal-cutaway-plan')).textContent).toContain('est. $0.27 (6s at 768P)');fireEvent.click(await findEnabledByRole('button', { name: /^Generate video$/ }));await waitFor(() => expect(generateVideo).toHaveBeenCalledWith(expect.objectContaining({backend: 'fal',falDuration: 6,+ falModelId: 'fal-ai/minimax/hailuo-02/standard/image-to-video',+ falResolution: '768P',mode: 'image',sourceImageFile: 'img1',})));@@ -702,6 +706,33 @@ describe('MusicVideo project video renderer', () => {expect(generateVideo.mock.calls.at(-1)[0]).not.toHaveProperty('disableAudio');});+ it('renders a cutaway on the picked fal.ai model at the shot-covering length, sending exactly the take it prices', async () => {+ getVideoGenStatus.mockResolvedValueOnce({ connected: true, defaultModel: '', falEnabled: true, models: [] });+ generateVideo.mockResolvedValue({ jobId: 'fal-h3-job' });+ await openProject({+ ...PROJECT_NO_CLIP,+ videoSettings: { backend: 'fal', falModelId: 'minimax/h3-max/image-to-video', falResolution: '1080P' },+ scenes: [{ ...PROJECT_NO_CLIP.scenes[0], startSec: 0, endSec: 7.2 }],+ });++ // A 7.2s shot on H3 Max (5–15s whole seconds) renders 8s at $0.16/s.+ expect((await screen.findByTestId('fal-cutaway-plan')).textContent).toContain('est. $1.28 (8s at 1080P)');+ fireEvent.click(await findEnabledByRole('button', { name: /^Generate video$/ }));+ await waitFor(() => expect(generateVideo).toHaveBeenCalledWith(expect.objectContaining({+ backend: 'fal', falModelId: 'minimax/h3-max/image-to-video', falDuration: 8, falResolution: '1080P',+ })));++ // Switching model clears the resolution pin — its alphabet is per model.+ fireEvent.change(await screen.findByLabelText('fal.ai cutaway model'), {+ target: { value: 'fal-ai/kling-video/v3/pro/image-to-video' },+ });+ await waitFor(() => expect(updateMusicVideoProject).toHaveBeenCalledWith(+ 'mv-2',+ { videoSettings: { falModelId: 'fal-ai/kling-video/v3/pro/image-to-video', falResolution: null } },+ { silent: true },+ ));+ });+it('blocks fal.ai scene generation with a clear preflight reason when no API key is configured', async () => {// getVideoGenStatus's default mock omits falEnabled, so it resolves false —// exactly the "no fal.ai API key configured" install this covers.@@ -737,7 +768,7 @@ describe('MusicVideo project video renderer', () => {expect(generateVideo).not.toHaveBeenCalled();});- it('names the lip-sync provider, model, song window and cost, then renders on fal.ai without a clip-length pin', async () => {+ it('names the lip-sync provider, model, song window and estimated cost, then renders on fal.ai without a clip-length pin', async () => {getVideoGenStatus.mockResolvedValueOnce({connected: true, defaultModel: 'ltx23_distilled_q4', falEnabled: true,models: [{ id: 'ltx23_distilled_q4', name: 'LTX-2.3 Distilled Q4', runtime: 'ltx2' }],@@ -748,12 +779,14 @@ describe('MusicVideo project video renderer', () => {const plan = await screen.findByTestId('performance-plan');expect(plan.textContent).toContain('minimax/h3-max/lip-sync/image-to-video');expect(plan.textContent).toMatch(/shot starts 1\.7[78]s into the take/);- expect(plan.textContent).toContain('cost unknown');+ // The padded 5.05s window at the 1080P lip-sync default ($0.16/s).+ expect(plan.textContent).toContain('est. $0.81 (5.05s at 1080P)');fireEvent.click(await findEnabledByRole('button', { name: /^Generate video$/ }));await waitFor(() => expect(generateVideo).toHaveBeenCalledWith(expect.objectContaining({- backend: 'fal', mode: 'image', sourceImageFile: 'img1',+ backend: 'fal', mode: 'image', sourceImageFile: 'img1', falResolution: '1080P',})));expect(generateVideo.mock.calls.at(-1)[0]).not.toHaveProperty('falDuration');+ expect(generateVideo.mock.calls.at(-1)[0]).not.toHaveProperty('falModelId');});it('persists a scene switched to a performance shot', async () => {@@ -767,11 +800,13 @@ describe('MusicVideo project video renderer', () => {});it('offers a lyric-boundary split for a shot longer than one lip-sync take and applies the split board', async () => {- const longShot = { ...PERFORMANCE_SCENE, startSec: 2, endSec: 26 };- const project = { ...performanceProject({ backend: 'fal' }), scenes: [longShot] };+ // 38s: past one ~30s lip-sync take.+ const longShot = { ...PERFORMANCE_SCENE, startSec: 2, endSec: 40 };+ const base = performanceProject({ backend: 'fal' });+ const project = { ...base, audioAnalysis: { ...base.audioAnalysis, durationSec: 60 }, scenes: [longShot] };const pieces = [- { ...longShot, label: 'Verse · 1/2', endSec: 14 },- { ...longShot, sceneId: 's1b', order: 1, label: 'Verse · 2/2', startSec: 14, videoHistoryId: null },+ { ...longShot, label: 'Verse · 1/2', endSec: 21 },+ { ...longShot, sceneId: 's1b', order: 1, label: 'Verse · 2/2', startSec: 21, videoHistoryId: null },];splitMusicVideoScene.mockResolvedValue({ project: { ...project, scenes: pieces }, scenes: pieces });await openProject(project);diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex 24b8c7b99c..f4295d3bd1 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -97,10 +97,13 @@ import { loomEpisodeToDraftScenes } from '../lib/episodeSceneImport.js';import LoraPicker from '../components/imageGen/LoraPicker';import { VIDEO_RESOLUTIONS, resolutionOptionsForModel } from '../lib/videoGenResolutions';import { GROK_VIDEO_DURATIONS } from '../lib/grokVideoClip.js';+import {+ FAL_DEFAULT_IMAGE_VIDEO_MODEL, FAL_DEFAULT_TEXT_VIDEO_MODEL, FAL_VIDEO_MODELS, estimateFalVideoCostUsd,+} from '../lib/falVideoModels.js';import { REACTOR_MAX_PROMPT_LENGTH } from '../lib/reactorVideoClip.js';import { styledVideoPrompt } from '../lib/videoGenSubmission.js';import ReactorPanel from '../components/videoGen/ReactorPanel';-import { formatCount, timeAgo } from '../utils/formatters';+import { formatCount, formatUsd, timeAgo } from '../utils/formatters';import ResolutionField from '../components/media/ResolutionField';import { VIDEO_EDGE_BOUNDS, videoEdgeBoundsForModel, IC_LORA_MODES } from '../lib/videoGenParams.js';import { finishTargetForRecord, isDeliveryVideoModel } from '../lib/videoFinish.js';@@ -1607,13 +1610,22 @@ export default function VideoGen() {) : isFal ? (<div className="grid grid-cols-2 gap-3"><FormField label="fal.ai model" labelClassName="block text-xs font-medium text-gray-400 mb-1">+ {/* Free text stays: any fal endpoint id renders (on the legacy+ body, cost unknown); the list suggests the curated ones+ whose request body and price PortOS knows. */}<inputtype="text"+ list="fal-video-model-suggestions"value={falModelId}onChange={(e) => setFalModelId(e.target.value)}- placeholder="fal-ai/minimax/hailuo-02/standard/text-to-video"+ placeholder={mode === 'image' ? FAL_DEFAULT_IMAGE_VIDEO_MODEL : FAL_DEFAULT_TEXT_VIDEO_MODEL}className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent"/>+ <datalist id="fal-video-model-suggestions">+ {FAL_VIDEO_MODELS.filter((m) => m.kind === (mode === 'image' ? 'i2v' : 't2v')).map((m) => (+ <option key={m.id} value={m.id}>{m.label}</option>+ ))}+ </datalist></FormField><FormField label="Clip length (sec)" labelClassName="block text-xs font-medium text-gray-400 mb-1"><input@@ -1627,7 +1639,17 @@ export default function VideoGen() {/></FormField><p className="col-span-2 text-[11px] text-gray-500 leading-snug">- Renders on fal.ai's queue API — leave the model blank to use PortOS's default (text-to-video, or image-to-video in Image mode). Counts against your fal.ai balance.+ Renders on fal.ai's queue API — leave the model blank to use PortOS's default (text-to-video, or image-to-video in Image mode). Counts against your fal.ai balance+ {(() => {+ const estimate = estimateFalVideoCostUsd({+ modelId: falModelId?.trim() || (mode === 'image' ? FAL_DEFAULT_IMAGE_VIDEO_MODEL : FAL_DEFAULT_TEXT_VIDEO_MODEL),+ seconds: falDuration === '' ? null : Number(falDuration),+ width, height,+ });+ return estimate == null+ ? ' — cost unknown for this model.'+ : ` — about ${formatUsd(estimate)} at list price, at the model's default resolution with provider audio off.`;+ })()}</p></div>) : isReactor ? (diff --git a/server/lib/README.md b/server/lib/README.mdindex e6bc3e2138..3f0e1eb910 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -299,8 +299,9 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `codex.js` | OpenAI Codex CLI (`codex`) provider helpers — the `CODEX_COMMAND`/`CODEX_CLI_ID` constants, the `isCodexCommand` and `isVisionCapableCodexTuiProvider` predicates, and `ensureCodexTuiArgs` (injects `--dangerously-bypass-approvals-and-sandbox` + disables the startup update-check config, skipped when the argv already declares an approval/sandbox posture via `argvHasFlag`). Extracted from `tuiHandshake.js` (#3618) to match the one-file-per-vendor shape of `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`, which `providerVendors.js` consumes as registry rows. Also owns `buildCodexOssArgs` — the `--oss --local-provider <ns>` pair emitted from a record's `ollamaBacked` marker, so the Codex harness runs on a local model without rewriting the user's `~/.codex/config.toml` (the record-classification half of that lives in `providerModels.js`, so `providerPrerequisites.js` can classify a codex record without importing a vendor argv module). || `cursor.js` | Cursor Agent (`cursor-agent`) provider helpers — the `CURSOR_COMMAND` binary constant, the `isCursorCommand` predicate, and the `ensureCursorHeadlessArgs` (`--print --force`, folding any pinned reasoning effort into `--model`) / `ensureCursorTuiArgs` (`--force`) argv builders. `--force` is load-bearing beyond approvals: it also clears cursor's workspace-trust gate, which otherwise EXITS a headless run before any work happens. The prompt rides raw stdin (like claude/codex, unlike grok/kimi), and cursor needs no configured-default sentinel — its `auto` router is a real model id passed straight to `--model`. || `grok.js` | xAI Grok Build (`grok`) provider helpers — id/endpoint constants (`GROK_API_ID`/`GROK_CLI_ID`/`GROK_TUI_ID`/`GROK_API_ENDPOINT`), `isGrokCommand`/`isGrokCliProvider`/`isGrokTuiProvider` predicates, `ensureGrokHeadlessArgs`/`ensureGrokTuiArgs` argv builders (grok reads its prompt from `--prompt-file /dev/stdin`, not raw stdin; model selection uses the `GROK_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Antigravity), and `prepareGrokPromptFile` (Windows temp-file delivery fallback). |+| `falVideoModels.js` | Curated fal.ai VIDEO model catalog — `FAL_VIDEO_MODELS` (Hailuo-02 standard t2v/i2v default, MiniMax H3 Max/Max Turbo i2v, H3 reference-to-video, H3 lip-sync, Seedance 2.5 t2v/i2v/reference, Kling v3 Pro i2v, Veo 3.1 Fast i2v) with per-model duration rules (enum/range/audio), resolutions, aspect ratios, optional inputs and list prices verified on `FAL_VIDEO_PRICING_VERIFIED_AT`; `getFalVideoModel()`, `coerceFalVideoSeconds()` (round UP to a covering length), `resolveFalVideoResolution()`, `buildFalVideoRequest()` (the exact queue body per model; null for an uncurated id, which keeps the legacy body), `estimateFalVideoCostUsd()` (null = unknown), `describeFalVideoRate()`. Dependency-free; the client re-exports it. || `grokVideoClip.js` | Clip lengths grok's `image_to_video` actually delivers — `GROK_VIDEO_DURATIONS` (`[6, 10]`, measured in #3022: a 2s/3s request returns the same 6.04s clip), `GROK_VIDEO_DEFAULT_DURATION`, `resolveGrokDuration()` (validate an already-grok-shaped request, else default), and `nearestGrokDuration()` (round a length authored against another backend's continuous contract UP to the shortest clip that covers it — for translating a CD/commission `targetDurationSeconds`). Dependency-free so `validation.js` / `routes/videoGen.js` can derive their schemas from the same list the services gate on. |-| `musicVideoShotTiming.js` | Music Video shot modes (#8977): `MUSIC_VIDEO_SHOT_MODES` (`cutaway`/`performance`), `isPerformanceScene`, `selectedPerformanceInstruction(scene)` (the selected take's shot instruction, performance scenes only), `SOURCE_AUDIO_LIPSYNC` (verified source-audio lip-sync lanes — only fal.ai MiniMax H3 lip-sync, 5–14.8s), `performanceCapability(backend)`, `performanceBlockedReason(backend)` (Grok is cutaway-only), `planPerformanceWindow()` (provider-bounded audio window + clip-relative edit in/out points; refuses over-long shots instead of relying on provider truncation), `clipRelativeCues()`, `grokCoverage(spanSec)` (covering 6/10s request, flags spans needing a split), `approximateMotionCues()`, `shotSplitLimit(scene, backend)` (per-take limit: lip-sync window or Grok's longest clip), `planShotSplit()` (contiguous pieces cut at lyric pauses → line/phrase boundaries → beats; one extra piece at most to avoid cutting a sung line). Dependency-free; the client re-exports it. |+| `musicVideoShotTiming.js` | Music Video shot modes (#8977): `MUSIC_VIDEO_SHOT_MODES` (`cutaway`/`performance`), `isPerformanceScene`, `selectedPerformanceInstruction(scene)` (the selected take's shot instruction, performance scenes only), `SOURCE_AUDIO_LIPSYNC` (verified source-audio lip-sync lanes — only fal.ai MiniMax H3 lip-sync, 5–30s per take, default 1080P), `falSceneTake()` (the fal model/length/resolution a scene take requests and its estimated cost — shared by the board, the submit path and the autopilot spend cap) + `falTakeRequestFields(take)` (that take as `/api/video-gen` fields), `performanceCapability(backend)`, `performanceBlockedReason(backend)` (Grok is cutaway-only), `planPerformanceWindow()` (provider-bounded audio window + clip-relative edit in/out points; refuses over-long shots instead of relying on provider truncation), `clipRelativeCues()`, `grokCoverage(spanSec)` (covering 6/10s request, flags spans needing a split), `approximateMotionCues()`, `shotSplitLimit(scene, backend)` (per-take limit: lip-sync window or Grok's longest clip), `planShotSplit()` (contiguous pieces cut at lyric pauses → line/phrase boundaries → beats; one extra piece at most to avoid cutting a sung line). Dependency-free; the client re-exports it. || `reactorStartingFrame.js` | Fits a reactor.inc `starting_frame` to the fast-h3 session canvas before it is uploaded. `readImageSize(path)` → `{width,height}` or `null` (never a guessed dimension), and `prepareReactorStartingFrame(sourceImagePath, requestedAspect, outputPath)` → `{ aspect, canvas, framePath, fittedPath }`: an absent `requestedAspect` DERIVES the canvas from the frame's own shape (`nearestReactorAspect`), then centre cover-crops the frame to that canvas's exact pixel size so reactor's own "fitted to the session canvas" step is a no-op. `fittedPath` is the temp file the caller deletes; `null` means the original was uploaded unchanged. A frame sharp cannot decode (or a resize that fails) passes through untouched on the default canvas rather than failing a render PortOS merely could not measure — reactor decodes more containers than sharp does. || `reactorVideoClip.js` | The reactor.inc `fast-h3` clip contract, dependency-free so the route schema, the FableLoom prompt compiler and the VideoGen picker all read one copy — `REACTOR_MAX_PROMPT_LENGTH` (800; the API rejects a longer prompt rather than truncating it), `REACTOR_MIN_CLIP_SECONDS` / `REACTOR_MAX_CLIP_SECONDS` (5.167–14.375, i.e. 124–345 frames at the `REACTOR_CLIP_FPS` 24 it delivers), `REACTOR_MAX_CLIP_ID_LENGTH`, and the picker list `REACTOR_CLIP_LENGTHS` + `REACTOR_DEFAULT_CLIP_LENGTH` + `reactorClipLengthLabel()` (the two exact endpoints plus every whole second between them, since the accepted range is continuous but starts and ends off a round number). Also the CANVAS contract `set_canvas` accepts: `REACTOR_CANVASES` (`16:9` 1344×768, `4:3` 1024×768, `1:1` 768×768, `9:16` 768×1344 — every one a 768px short edge, so the aspect string is the whole choice), `REACTOR_ASPECTS`, `REACTOR_DEFAULT_ASPECT`, `reactorCanvas(aspect)` and `nearestReactorAspect(width, height)` (closest canvas in log-ratio space; anything unmeasurable answers the default rather than deriving one). Mirrored to `client/src/lib/reactorVideoClip.js`, parity pinned by `reactorVideoClip.test.js`. || `kimi.js` | Moonshot AI Kimi Code (`kimi`) provider helpers — id constants (`KIMI_CLI_ID`/`KIMI_TUI_ID`), `isKimiCommand`/`isKimiCliProvider`/`isKimiTuiProvider` predicates, `ensureKimiHeadlessArgs` (model flag only — non-interactive mode is implicit in `--prompt`, and kimi has no `--print`/`--afk` and refuses approval flags alongside `--prompt`) / `ensureKimiTuiArgs` (`--yolo`) argv builders (model selection uses the `KIMI_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Grok/Antigravity), and `prepareKimiPrompt` (delivers the prompt as the `--prompt <value>` argv, not stdin). |diff --git a/server/lib/falVideoModels.js b/server/lib/falVideoModels.jsnew file mode 100644index 0000000000..aa13fa6e30--- /dev/null+++ b/server/lib/falVideoModels.js@@ -0,0 +1,398 @@+/**+ * Curated fal.ai VIDEO model catalog (#8977 follow-up) — what PortOS knows+ * about each fal video endpoint it offers: the request-body shape (parameter+ * names and wire types differ per family), the duration / resolution / aspect+ * rules, which optional inputs it accepts, and its published price.+ *+ * Every entry was checked against fal's own queue OpenAPI schema+ * (`https://fal.ai/api/openapi/queue/openapi.json?endpoint_id=<id>`) and the+ * model page's pricing text on FAL_VIDEO_PRICING_VERIFIED_AT. fal changes these;+ * when a render is rejected with a 422 or a bill disagrees with an estimate,+ * re-check the schema and pricing text for that endpoint and edit its row.+ *+ * A model id NOT in this catalog (the Video Gen page keeps a free-text model+ * box) still renders — `buildFalVideoRequest()` returns null and the provider+ * falls back to the legacy Hailuo-shaped body — but its cost is unknown (null),+ * so a USD spend cap refuses it rather than guessing.+ *+ * Pricing is deliberately the LIST price. Two MiniMax H3 image-to-video routes+ * were on a 50%-off launch promotion when this was written; an estimate that+ * assumed the promo would under-count spend the day it ends, and an estimate+ * feeds the Music Video autopilot's dollar cap. Over-estimating a cap is safe;+ * under-estimating it is not.+ *+ * Dependency-free so `client/src/lib/falVideoModels.js` can re-export it and the+ * board, the provider and the autopilot price a take identically.+ */++/** Date the schemas and prices below were last verified against fal.ai. */+export const FAL_VIDEO_PRICING_VERIFIED_AT = '2026-09-29';++/** What an entry renders from: text, a start frame, reference assets, or a frame + source audio. */+export const FAL_VIDEO_KINDS = Object.freeze(['t2v', 'i2v', 'ref2v', 'lipsync']);++export const FAL_DEFAULT_TEXT_VIDEO_MODEL = 'fal-ai/minimax/hailuo-02/standard/text-to-video';+export const FAL_DEFAULT_IMAGE_VIDEO_MODEL = 'fal-ai/minimax/hailuo-02/standard/image-to-video';+export const FAL_LIPSYNC_VIDEO_MODEL = 'minimax/h3-max/lip-sync/image-to-video';++const H3_RESOLUTIONS = Object.freeze(['480P', '768P', '1080P']);+const SEEDANCE_RESOLUTIONS = Object.freeze(['480p', '720p', '1080p']);+const WIDE_ASPECTS = Object.freeze(['21:9', '16:9', '4:3', '1:1', '3:4', '9:16']);+// H3 Max list rates (the lip-sync and reference routes are billed at these; the+// image-to-video route was 50% off at launch — see the header on list prices).+const H3_MAX_RATES = Object.freeze({ '480P': 0.05, '768P': 0.08, '1080P': 0.16 });+// Seedance 2.5 bills video tokens: ≈ width × height × 24fps × seconds / 1024 at+// $0.0214 per 1,000 (480p/720p) or $0.0234 (1080p). fal publishes the resulting+// per-second price for a 16:9 output; those published figures are used (they+// run ~2% above the nominal-pixel formula, i.e. the provider pads the canvas).+const SEEDANCE_PER_SEC_16X9 = Object.freeze({ '480p': 0.2205, '720p': 0.473, '1080p': 1.164 });++const seedance = (id, kind, label, extra) => ({+ id, kind, label, family: 'seedance-2.5',+ prompt: kind === 'i2v' ? 'optional' : 'required',+ // 'auto' lets the model pick 4–30s from the prompt — an unbounded bill for a+ // cap to reason about, so PortOS always pins an explicit length.+ duration: { kind: 'range', min: 4, max: 30, wire: 'string', defaultSec: 5 },+ resolution: { param: 'resolution', options: SEEDANCE_RESOLUTIONS, default: '720p' },+ negativePrompt: 'fold',+ // Same price with or without audio; PortOS still asks for silence by+ // default because a Music Video's master song is its only soundtrack.+ audio: { param: 'generate_audio', providerDefault: true },+ pricing: { videoTokensPerSec16x9: SEEDANCE_PER_SEC_16X9 },+ ...extra,+});++const h3 = (id, label, rates, extra = {}) => ({+ id, kind: 'i2v', label, family: 'minimax-h3',+ prompt: 'required',+ image: { param: 'image_url', required: false },+ endImage: { param: 'end_image_url' },+ duration: { kind: 'range', min: 5, max: 15, wire: 'integer', defaultSec: 5 },+ resolution: { param: 'resolution', options: H3_RESOLUTIONS, default: '768P' },+ // The output canvas follows the start frame — there is no aspect parameter.+ aspectRatio: null,+ negativePrompt: 'fold',+ seed: 'seed',+ // Listed as required by the schema (with a default): send it explicitly.+ fixed: { prompt_expansion_mode: 'balanced' },+ pricing: { perSecond: rates },+ ...extra,+});++/** The curated catalog, one frozen row per fal endpoint. */+export const FAL_VIDEO_MODELS = Object.freeze([+ {+ id: FAL_DEFAULT_IMAGE_VIDEO_MODEL, kind: 'i2v', label: 'MiniMax Hailuo-02 Standard (image)', family: 'hailuo-02',+ prompt: 'required',+ image: { param: 'image_url', required: true },+ endImage: { param: 'end_image_url' },+ duration: { kind: 'enum', values: [6, 10], wire: 'string', defaultSec: 6 },+ resolution: { param: 'resolution', options: ['512P', '768P'], default: '768P' },+ aspectRatio: null,+ negativePrompt: 'fold',+ pricing: { perSecond: { '512P': 0.017, '768P': 0.045 } },+ },+ {+ id: FAL_DEFAULT_TEXT_VIDEO_MODEL, kind: 't2v', label: 'MiniMax Hailuo-02 Standard (text)', family: 'hailuo-02',+ prompt: 'required',+ duration: { kind: 'enum', values: [6, 10], wire: 'string', defaultSec: 6 },+ // Fixed 768P output; the text route takes neither resolution nor aspect ratio.+ resolution: null,+ aspectRatio: null,+ negativePrompt: 'fold',+ pricing: { perSecond: 0.045 },+ },+ h3('minimax/h3-max/image-to-video', 'MiniMax H3 Max (image)', H3_MAX_RATES),+ h3('minimax/h3-max-turbo/image-to-video', 'MiniMax H3 Max Turbo (image)', { '480P': 0.025, '768P': 0.04, '1080P': 0.08 }),+ {+ id: 'minimax/h3-max/reference-to-video', kind: 'ref2v', label: 'MiniMax H3 Max (reference)', family: 'minimax-h3',+ prompt: 'required',+ // Referenced in the prompt as "Image 1", "Audio 1", … in list order.+ referenceImages: { param: 'reference_image_urls', max: 9 },+ referenceAudio: { param: 'reference_audio_urls', max: 3, minSec: 2, maxSec: 15 },+ duration: { kind: 'range', min: 5, max: 15, wire: 'integer', defaultSec: 5 },+ resolution: { param: 'resolution', options: H3_RESOLUTIONS, default: '768P' },+ aspectRatio: { param: 'aspect_ratio', options: WIDE_ASPECTS, auto: 'adaptive' },+ negativePrompt: 'fold',+ seed: 'seed',+ fixed: { prompt_expansion_mode: 'balanced' },+ // Each request includes 4,096 reference tokens (four square images); beyond+ // that fal adds $0.02 per 1,000 tokens, which this estimate does not model.+ pricing: { perSecond: H3_MAX_RATES },+ },+ {+ id: FAL_LIPSYNC_VIDEO_MODEL, kind: 'lipsync', label: 'MiniMax H3 Max lip-sync', family: 'minimax-h3',+ // No prompt field at all: the frame and the audio are the whole request.+ prompt: 'none',+ image: { param: 'image_url', required: true },+ // fal accepts 5s to 15 minutes; the output length follows the audio.+ audioInput: { param: 'audio_url', minSec: 5, maxSec: 900 },+ duration: { kind: 'audio' },+ resolution: { param: 'resolution', options: [...H3_RESOLUTIONS, '2K'], default: '768P' },+ aspectRatio: null,+ negativePrompt: null,+ transcription: 'enable_transcription',+ seed: 'seed',+ // "A 1.2x multiplier is added to videos over 15 seconds" — the whole take.+ pricing: { perSecond: { ...H3_MAX_RATES, '2K': 0.32 }, longTake: { overSec: 15, factor: 1.2 } },+ },+ seedance('bytedance/seedance-2.5/image-to-video', 'i2v', 'Seedance 2.5 (image)', {+ image: { param: 'image_url', required: true },+ endImage: { param: 'end_image_url' },+ // "Always auto for image-to-video": the canvas follows the start frame.+ aspectRatio: null,+ }),+ seedance('bytedance/seedance-2.5/text-to-video', 't2v', 'Seedance 2.5 (text)', {+ aspectRatio: { param: 'aspect_ratio', options: WIDE_ASPECTS, auto: 'auto' },+ }),+ seedance('bytedance/seedance-2.5/reference-to-video', 'ref2v', 'Seedance 2.5 (reference)', {+ // Referenced in the prompt as @Image1 / @Audio1. Audio references let a+ // singer follow supplied audio, but each clip is capped at 30.2s.+ referenceImages: { param: 'image_urls', max: 30 },+ referenceAudio: { param: 'audio_urls', max: 10, minSec: 1.8, maxSec: 30.2 },+ aspectRatio: { param: 'aspect_ratio', options: WIDE_ASPECTS, auto: 'auto' },+ seed: 'seed',+ }),+ {+ id: 'fal-ai/kling-video/v3/pro/image-to-video', kind: 'i2v', label: 'Kling v3 Pro (image)', family: 'kling-v3',+ prompt: 'required',+ image: { param: 'start_image_url', required: true },+ endImage: { param: 'end_image_url' },+ duration: { kind: 'range', min: 3, max: 15, wire: 'string', defaultSec: 5 },+ resolution: null,+ aspectRatio: null,+ negativePrompt: 'native',+ audio: { param: 'generate_audio', providerDefault: true },+ pricing: { perSecond: 0.112, perSecondWithAudio: 0.168 },+ },+ {+ id: 'fal-ai/veo3.1/fast/image-to-video', kind: 'i2v', label: 'Veo 3.1 Fast (image)', family: 'veo-3.1',+ prompt: 'required',+ image: { param: 'image_url', required: true },+ duration: { kind: 'enum', values: [4, 6, 8], wire: 'seconds-suffix', defaultSec: 8 },+ resolution: { param: 'resolution', options: ['720p', '1080p', '4k'], default: '720p' },+ // Only 16:9 and 9:16; a start frame of another shape is cropped to fit.+ aspectRatio: { param: 'aspect_ratio', options: ['16:9', '9:16'], auto: 'auto' },+ negativePrompt: 'native',+ audio: { param: 'generate_audio', providerDefault: true },+ seed: 'seed',+ pricing: {+ perSecond: { '720p': 0.1, '1080p': 0.1, '4k': 0.3 },+ perSecondWithAudio: { '720p': 0.15, '1080p': 0.15, '4k': 0.35 },+ },+ },+].map((model) => Object.freeze(model)));++const BY_ID = new Map(FAL_VIDEO_MODELS.map((m) => [m.id, m]));++/** The catalog row for `modelId`, or null for a model PortOS has not curated. */+export const getFalVideoModel = (modelId) => (typeof modelId === 'string' ? BY_ID.get(modelId.trim()) || null : null);++/**+ * Models that animate a start frame (the Music Video cutaway lane's choices).+ * Reference-to-video models are left out: they take the frame as a loose+ * reference the prompt must name ("Image 1" / @Image1), which a scene's shot+ * prompt does not do.+ */+export const FAL_IMAGE_VIDEO_MODELS = Object.freeze(FAL_VIDEO_MODELS.filter((m) => m.kind === 'i2v'));++/** Resolution choices a model offers (empty when it has no resolution parameter). */+export const falVideoResolutions = (model) => (model?.resolution?.options ? [...model.resolution.options] : []);++/**+ * The model's spelling of `requested` (matched case-insensitively — fal writes+ * '1080P' for MiniMax and '1080p' for Seedance/Veo), else its default. Null when+ * the model has no resolution parameter.+ */+export function resolveFalVideoResolution(model, requested) {+ if (!model?.resolution) return null;+ const want = typeof requested === 'string' ? requested.trim().toLowerCase() : '';+ return model.resolution.options.find((o) => o.toLowerCase() === want) || model.resolution.default;+}++/**+ * The clip length (seconds) `model` will render for a request of `seconds`: the+ * shortest supported length that still COVERS it, else the longest — a Music+ * Video shot must not be under-covered (the renderer refuses a clip more than a+ * frame short) and nothing loops or stretches footage. An absent / invalid+ * request gets the model's default. Null for a lip-sync model, whose length+ * follows its audio.+ */+export function coerceFalVideoSeconds(model, seconds) {+ const rule = model?.duration;+ if (!rule || rule.kind === 'audio') return null;+ const n = Number(seconds);+ if (seconds == null || seconds === '' || !Number.isFinite(n) || n <= 0) return rule.defaultSec;+ if (rule.kind === 'enum') {+ return rule.values.find((v) => v >= n - 1e-6) ?? rule.values[rule.values.length - 1];+ }+ return Math.min(rule.max, Math.max(rule.min, Math.ceil(n - 1e-6)));+}++const wireDuration = (rule, sec) => (+ rule.wire === 'integer' ? sec : rule.wire === 'seconds-suffix' ? `${sec}s` : String(sec)+);++const ratioOf = (r) => { const [w, h] = String(r).split(':').map(Number); return w / h; };++function pickAspectRatio(rule, { aspectRatio, width, height }) {+ if (!rule) return null;+ if (rule.options.includes(aspectRatio)) return aspectRatio;+ const w = Number(width);+ const h = Number(height);+ if (!(w > 0 && h > 0)) return null; // the provider's own auto/adaptive default+ const target = w / h;+ let best = null;+ for (const option of rule.options) {+ if (!best || Math.abs(ratioOf(option) - target) < Math.abs(ratioOf(best) - target)) best = option;+ }+ return best;+}++function perSecondRate(model, resolution, withAudio) {+ const { pricing } = model;+ const table = withAudio && pricing.perSecondWithAudio != null ? pricing.perSecondWithAudio : pricing.perSecond;+ if (typeof table === 'number') return table;+ return table?.[resolution] ?? null;+}++const round4 = (n) => Math.round(n * 1e4) / 1e4;++/**+ * Estimated USD for one fal render, or null when the model is not curated or+ * the inputs cannot be priced. `seconds` is what the caller asks for; it is+ * coerced exactly as the request body will be (a lip-sync take is billed on+ * its audio length). `width`/`height` only matter for token-priced models+ * (Seedance), where a canvas wider than 16:9 costs proportionally more; a+ * narrower one is still priced at the 16:9 figure so the estimate never+ * undershoots. `generateAudio` selects the audio-on rate where one exists.+ */+export function estimateFalVideoCostUsd({ modelId, seconds, resolution, width, height, generateAudio = false } = {}) {+ const model = getFalVideoModel(modelId);+ if (!model) return null;+ let billedSec;+ if (model.duration.kind === 'audio') {+ billedSec = Number(seconds);+ if (!Number.isFinite(billedSec) || billedSec <= 0) return null;+ billedSec = Math.max(billedSec, model.audioInput.minSec);+ } else {+ billedSec = coerceFalVideoSeconds(model, seconds);+ }+ const res = resolveFalVideoResolution(model, resolution);+ let perSec;+ if (model.pricing.videoTokensPerSec16x9) {+ perSec = model.pricing.videoTokensPerSec16x9[res] ?? null;+ const w = Number(width);+ const h = Number(height);+ if (perSec != null && w > 0 && h > 0) perSec *= Math.max(1, (Math.max(w, h) / Math.min(w, h)) / (16 / 9));+ } else {+ perSec = perSecondRate(model, res, generateAudio === true && !!model.audio);+ }+ if (perSec == null) return null;+ const long = model.pricing.longTake;+ const factor = long && billedSec > long.overSec ? long.factor : 1;+ return round4(perSec * billedSec * factor);+}++/** A one-line human rate for `model` at `resolution`, e.g. "$0.16/s at 1080P (×1.2 over 15s)". */+export function describeFalVideoRate(modelId, resolution) {+ const model = getFalVideoModel(modelId);+ if (!model) return null;+ const res = resolveFalVideoResolution(model, resolution);+ if (model.pricing.videoTokensPerSec16x9) {+ const perSec = model.pricing.videoTokensPerSec16x9[res];+ return perSec == null ? null : `≈$${perSec.toFixed(4)}/s at ${res} (16:9)`;+ }+ const perSec = perSecondRate(model, res, false);+ if (perSec == null) return null;+ const long = model.pricing.longTake;+ return `$${perSec}/s${res ? ` at ${res}` : ''}${long ? ` (×${long.factor} over ${long.overSec}s)` : ''}`;+}++/**+ * Build the fal queue request body for a curated model, or return null for an+ * uncurated id (the caller keeps its legacy body). Returns `{ body, model,+ * seconds, resolution, generateAudio, estimatedCostUsd }` — `seconds` is the+ * coerced clip length (null for lip-sync, whose length is `audioSec`).+ *+ * Inputs a model cannot take are dropped rather than sent (fal ignores unknown+ * keys, which would bill a render that silently disregarded them); a missing+ * REQUIRED input throws an Error with `code = 'FAL_MODEL_INPUT'` so the caller+ * refuses before anything is paid for.+ *+ * `generateAudio` defaults to false: PortOS's video renders are cutaways for a+ * master soundtrack (Music Video) or silent-by-default clips; a caller asks for+ * provider audio explicitly.+ */+export function buildFalVideoRequest({+ modelId, prompt = '', negativePrompt = '', seconds, audioSec, aspectRatio, width, height, resolution,+ imageUrl = null, endImageUrl = null, referenceImageUrls = [], audioUrl = null, referenceAudioUrls = [],+ generateAudio = false, enableTranscription = false, seed,+} = {}) {+ const model = getFalVideoModel(modelId);+ if (!model) return null;+ const refuse = (message) => Object.assign(new Error(message), { code: 'FAL_MODEL_INPUT' });+ const body = {};+ const text = typeof prompt === 'string' ? prompt.trim() : '';+ const avoid = typeof negativePrompt === 'string' ? negativePrompt.trim() : '';++ if (model.prompt !== 'none') {+ if (model.prompt === 'required' && !text) throw refuse(`${model.label} needs a prompt`);+ // No native field: fold the negative prompt into the prompt as an "Avoid:"+ // clause — the same fallback grok.js uses for a provider without one.+ const folded = model.negativePrompt === 'fold' && avoid ? `${text}\nAvoid: ${avoid}` : text;+ if (folded) body.prompt = folded;+ if (model.negativePrompt === 'native' && avoid) body.negative_prompt = avoid;+ }++ if (model.image) {+ if (imageUrl) body[model.image.param] = imageUrl;+ else if (model.image.required) throw refuse(`${model.label} renders from a start frame — supply a source image`);+ } else if (model.referenceImages) {+ // A PortOS start frame becomes the first reference ("Image 1" / @Image1).+ const refs = [imageUrl, ...(Array.isArray(referenceImageUrls) ? referenceImageUrls : [])].filter(Boolean);+ if (refs.length > model.referenceImages.max) throw refuse(`${model.label} takes at most ${model.referenceImages.max} reference images`);+ if (refs.length) body[model.referenceImages.param] = refs;+ } else if (imageUrl) {+ throw refuse(`${model.label} is text-to-video — it cannot use a source image`);+ }+ if (endImageUrl) {+ if (!model.endImage) throw refuse(`${model.label} takes no end frame`);+ body[model.endImage.param] = endImageUrl;+ }+ const audioRefs = (Array.isArray(referenceAudioUrls) ? referenceAudioUrls : []).filter(Boolean);+ if (audioRefs.length) {+ if (!model.referenceAudio) throw refuse(`${model.label} takes no reference audio`);+ if (audioRefs.length > model.referenceAudio.max) throw refuse(`${model.label} takes at most ${model.referenceAudio.max} reference audio clips`);+ body[model.referenceAudio.param] = audioRefs;+ }+ if (model.audioInput) {+ if (!audioUrl) throw refuse(`${model.label} needs the source audio to synchronize to`);+ body[model.audioInput.param] = audioUrl;+ if (model.transcription && enableTranscription) body[model.transcription] = true;+ } else if (audioUrl) {+ throw refuse(`${model.label} does not synchronize to source audio`);+ }++ const coercedSec = coerceFalVideoSeconds(model, seconds);+ if (coercedSec != null) body.duration = wireDuration(model.duration, coercedSec);+ const res = resolveFalVideoResolution(model, resolution);+ if (res) body[model.resolution.param] = res;+ const aspect = pickAspectRatio(model.aspectRatio, { aspectRatio, width, height });+ if (aspect) body[model.aspectRatio.param] = aspect;+ const wantsAudio = generateAudio === true && !!model.audio;+ if (model.audio) body[model.audio.param] = wantsAudio;+ if (model.seed && Number.isInteger(seed) && seed >= 0) body[model.seed] = seed;+ Object.assign(body, model.fixed || {});++ return {+ body,+ model,+ seconds: coercedSec,+ resolution: res,+ generateAudio: wantsAudio,+ estimatedCostUsd: estimateFalVideoCostUsd({+ modelId: model.id, seconds: coercedSec ?? audioSec, resolution: res, width, height, generateAudio: wantsAudio,+ }),+ };+}diff --git a/server/lib/falVideoModels.test.js b/server/lib/falVideoModels.test.jsnew file mode 100644index 0000000000..69016a21a6--- /dev/null+++ b/server/lib/falVideoModels.test.js@@ -0,0 +1,127 @@+import { describe, it, expect } from 'vitest';+import {+ FAL_LIPSYNC_VIDEO_MODEL,+ FAL_VIDEO_MODELS,+ buildFalVideoRequest,+ coerceFalVideoSeconds,+ estimateFalVideoCostUsd,+ getFalVideoModel,+} from './falVideoModels.js';++// The catalog is a serialization boundary with a real per-family matrix: each+// fal family spells duration, resolution, image and audio differently, and a+// wrong type is either a 422 or — worse — a silently ignored key on a billed+// render. These pin the wire bodies against fal's OpenAPI schemas and the+// estimates against fal's published prices (FAL_VIDEO_PRICING_VERIFIED_AT).++const build = (modelId, extra = {}) => buildFalVideoRequest({ modelId, prompt: 'a lighthouse at dusk', imageUrl: 'data:image/png;base64,AA==', ...extra });++describe('buildFalVideoRequest — per-family wire bodies', () => {+ it('Hailuo-02: string enum duration covering the request, resolution enum, no aspect_ratio or audio key', () => {+ const { body, seconds } = build('fal-ai/minimax/hailuo-02/standard/image-to-video', { seconds: 7.5, width: 1920, height: 1080, negativePrompt: 'blur' });+ expect(seconds).toBe(10);+ expect(body).toEqual({+ prompt: 'a lighthouse at dusk\nAvoid: blur', image_url: 'data:image/png;base64,AA==', duration: '10', resolution: '768P',+ });+ });++ it('MiniMax H3: integer duration clamped to 5–15, case-insensitive resolution, the required prompt_expansion_mode', () => {+ expect(build('minimax/h3-max/image-to-video', { seconds: 3, resolution: '1080p' }).body).toEqual({+ prompt: 'a lighthouse at dusk', image_url: 'data:image/png;base64,AA==', duration: 5, resolution: '1080P', prompt_expansion_mode: 'balanced',+ });+ expect(build('minimax/h3-max-turbo/image-to-video', { seconds: 40 }).body.duration).toBe(15);+ });++ it('Kling v3 Pro: start_image_url, string duration, native negative prompt, provider audio off unless asked', () => {+ expect(build('fal-ai/kling-video/v3/pro/image-to-video', { seconds: 4.2, negativePrompt: 'text overlay' }).body).toEqual({+ prompt: 'a lighthouse at dusk', negative_prompt: 'text overlay', start_image_url: 'data:image/png;base64,AA==',+ duration: '5', generate_audio: false,+ });+ expect(build('fal-ai/kling-video/v3/pro/image-to-video', { generateAudio: true }).body.generate_audio).toBe(true);+ });++ it('Veo 3.1 Fast: "Ns" duration enum and the nearest of its two aspect ratios', () => {+ expect(build('fal-ai/veo3.1/fast/image-to-video', { seconds: 5, width: 1080, height: 1920 }).body).toMatchObject({+ duration: '6s', aspect_ratio: '9:16', resolution: '720p', generate_audio: false,+ });+ });++ it('Seedance 2.5: always an explicit length (never "auto"), no aspect for image-to-video, 21:9 for text-to-video', () => {+ const i2v = build('bytedance/seedance-2.5/image-to-video');+ expect(i2v.body).toEqual({+ prompt: 'a lighthouse at dusk', image_url: 'data:image/png;base64,AA==', duration: '5', resolution: '720p', generate_audio: false,+ });+ const t2v = buildFalVideoRequest({ modelId: 'bytedance/seedance-2.5/text-to-video', prompt: 'x', seconds: 12, aspectRatio: '21:9' });+ expect(t2v.body).toMatchObject({ duration: '12', aspect_ratio: '21:9' });+ });++ it('reference-to-video: the start frame becomes the first reference, audio references ride their own list', () => {+ const { body } = build('bytedance/seedance-2.5/reference-to-video', {+ referenceImageUrls: ['https://example.com/b.png'], referenceAudioUrls: ['https://example.com/a.wav'],+ });+ expect(body.image_urls).toEqual(['data:image/png;base64,AA==', 'https://example.com/b.png']);+ expect(body.audio_urls).toEqual(['https://example.com/a.wav']);+ expect(body).not.toHaveProperty('image_url');+ expect(build('minimax/h3-max/reference-to-video', { width: 1080, height: 1350 }).body).toMatchObject({+ reference_image_urls: ['data:image/png;base64,AA=='], aspect_ratio: '3:4', duration: 5,+ });+ });++ it('lip-sync: frame + audio + resolution only — no prompt field even when one is supplied', () => {+ const req = buildFalVideoRequest({+ modelId: FAL_LIPSYNC_VIDEO_MODEL, prompt: 'singer', imageUrl: 'i', audioUrl: 'a', audioSec: 12, resolution: '2k', enableTranscription: true,+ });+ expect(req.body).toEqual({ image_url: 'i', audio_url: 'a', enable_transcription: true, resolution: '2K' });+ expect(req.seconds).toBeNull();+ expect(req.estimatedCostUsd).toBe(3.84);+ });++ it('refuses a request the model cannot honor before anything is paid for; an uncurated id is not built', () => {+ const refused = (fn) => { try { fn(); } catch (err) { return err.code; } return null; };+ expect(refused(() => buildFalVideoRequest({ modelId: 'fal-ai/kling-video/v3/pro/image-to-video', prompt: 'x' }))).toBe('FAL_MODEL_INPUT');+ expect(refused(() => buildFalVideoRequest({ modelId: 'fal-ai/minimax/hailuo-02/standard/text-to-video', prompt: 'x', imageUrl: 'i' }))).toBe('FAL_MODEL_INPUT');+ expect(refused(() => buildFalVideoRequest({ modelId: FAL_LIPSYNC_VIDEO_MODEL, imageUrl: 'i' }))).toBe('FAL_MODEL_INPUT');+ expect(refused(() => build('fal-ai/veo3.1/fast/image-to-video', { prompt: '' }))).toBe('FAL_MODEL_INPUT');+ expect(buildFalVideoRequest({ modelId: 'example/uncurated-model', prompt: 'x' })).toBeNull();+ });+});++describe('estimateFalVideoCostUsd — list prices per family', () => {+ it('prices each family from its published rate, billing the coerced length', () => {+ // Hailuo-02: $0.045/s at 768P — a 7s request renders (and bills) 10s.+ expect(estimateFalVideoCostUsd({ modelId: 'fal-ai/minimax/hailuo-02/standard/image-to-video', seconds: 7 })).toBe(0.45);+ expect(estimateFalVideoCostUsd({ modelId: 'fal-ai/minimax/hailuo-02/standard/image-to-video', seconds: 6, resolution: '512P' })).toBe(0.102);+ // H3 Max at list price (not the launch promo), H3 Turbo half that.+ expect(estimateFalVideoCostUsd({ modelId: 'minimax/h3-max/image-to-video', seconds: 6, resolution: '1080P' })).toBe(0.96);+ expect(estimateFalVideoCostUsd({ modelId: 'minimax/h3-max-turbo/image-to-video', seconds: 5, resolution: '480P' })).toBe(0.125);+ // Kling / Veo: audio-off vs audio-on rates.+ expect(estimateFalVideoCostUsd({ modelId: 'fal-ai/kling-video/v3/pro/image-to-video', seconds: 5 })).toBe(0.56);+ expect(estimateFalVideoCostUsd({ modelId: 'fal-ai/kling-video/v3/pro/image-to-video', seconds: 5, generateAudio: true })).toBe(0.84);+ expect(estimateFalVideoCostUsd({ modelId: 'fal-ai/veo3.1/fast/image-to-video', seconds: 8, resolution: '4k', generateAudio: true })).toBe(2.8);+ });++ it('Seedance bills video tokens: the 16:9 per-second figure, scaled up (never down) for a wider canvas', () => {+ expect(estimateFalVideoCostUsd({ modelId: 'bytedance/seedance-2.5/image-to-video', seconds: 5, resolution: '720p' })).toBe(2.365);+ expect(estimateFalVideoCostUsd({ modelId: 'bytedance/seedance-2.5/text-to-video', seconds: 4, resolution: '480p', width: 1080, height: 1080 })).toBe(0.882);+ expect(estimateFalVideoCostUsd({ modelId: 'bytedance/seedance-2.5/text-to-video', seconds: 4, resolution: '1080p', width: 2520, height: 1080 })).toBeCloseTo(4 * 1.164 * (21 / 9) / (16 / 9), 3);+ });++ it('lip-sync bills its audio length (at least the 5s minimum), ×1.2 past 15s', () => {+ expect(estimateFalVideoCostUsd({ modelId: FAL_LIPSYNC_VIDEO_MODEL, seconds: 5.05, resolution: '1080P' })).toBe(0.808);+ expect(estimateFalVideoCostUsd({ modelId: FAL_LIPSYNC_VIDEO_MODEL, seconds: 3, resolution: '768P' })).toBe(0.4);+ expect(estimateFalVideoCostUsd({ modelId: FAL_LIPSYNC_VIDEO_MODEL, seconds: 20, resolution: '768P' })).toBe(1.92);+ });++ it('reports unknown (null) rather than guessing: uncurated model, lip-sync with no audio length', () => {+ expect(estimateFalVideoCostUsd({ modelId: 'example/uncurated-model', seconds: 6 })).toBeNull();+ expect(estimateFalVideoCostUsd({ modelId: FAL_LIPSYNC_VIDEO_MODEL })).toBeNull();+ });++ it('every curated model prices its default request', () => {+ for (const model of FAL_VIDEO_MODELS) {+ const seconds = model.duration.kind === 'audio' ? 10 : coerceFalVideoSeconds(model, null);+ expect(estimateFalVideoCostUsd({ modelId: model.id, seconds }), model.id).toBeGreaterThan(0);+ expect(getFalVideoModel(model.id)).toBe(model);+ }+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 19f92e1abd..4cf56c1f39 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -187,6 +187,7 @@ export * from './codexCliOutput.js';export * from './contextBudget.js';export * from './cursor.js';export * from './grok.js';+export * from './falVideoModels.js';export * from './grokVideoClip.js';export * from './musicVideoShotTiming.js';export * from './reactorStartingFrame.js';diff --git a/server/lib/musicVideoShotTiming.js b/server/lib/musicVideoShotTiming.jsindex 61a48b9001..b3b36110b2 100644--- a/server/lib/musicVideoShotTiming.js+++ b/server/lib/musicVideoShotTiming.js@@ -10,8 +10,8 @@** - `SOURCE_AUDIO_LIPSYNC` — the capability snapshot per backend. Only fal.ai's* documented MiniMax H3 lip-sync route (image_url + audio_url, at least 5s of- * audio, silently clipped beyond 14.8s, output length follows the clipped- * audio) is listed. Grok's CLI image_to_video lane takes no audio at all, so+ * audio, output length follows the audio, priced per output second by+ * resolution — lib/falVideoModels.js) is listed. Grok's CLI image_to_video lane takes no audio at all, so* it is cutaway-only here until an actual adapter proves exact-source-audio* conditioning — REST documentation for a different Grok surface is not that* proof. Local runtimes are absent for the same reason.@@ -26,12 +26,27 @@* contiguous pieces within the lane's per-take limit, cut at a pause between* sung lines, a lyric/phrase boundary or a beat (in that order).*- * Dependency-free (only grokVideoClip.js, itself dependency-free) so the client+ * - `falSceneTake` — the fal.ai request (model, length, resolution) a scene+ * take makes on the fal lane and its estimated cost, shared by the board,+ * the submit path and the production autopilot's spend cap.+ *+ * Dependency-free (only grokVideoClip.js and falVideoModels.js, themselves+ * dependency-free) so the client* re-exports it from `client/src/lib/musicVideoShotTiming.js` and the two sides* cannot drift.*/import { GROK_VIDEO_DURATIONS, nearestGrokDuration } from './grokVideoClip.js';+import {+ FAL_DEFAULT_IMAGE_VIDEO_MODEL,+ FAL_LIPSYNC_VIDEO_MODEL,+ coerceFalVideoSeconds,+ describeFalVideoRate,+ estimateFalVideoCostUsd,+ falVideoResolutions,+ getFalVideoModel,+ resolveFalVideoResolution,+} from './falVideoModels.js';export const MUSIC_VIDEO_SHOT_MODES = Object.freeze(['cutaway', 'performance']);@@ -63,18 +78,38 @@ export function selectedPerformanceInstruction(scene) {// or over the maximum (silently clipped by the provider).export const PERFORMANCE_WINDOW_MARGIN_SEC = 0.05;-/** Verified source-audio lip-sync lanes, keyed by Music Video backend. */+/**+ * Default output resolution of a Music Video performance take. fal's own+ * default is 768P; a sung close-up is the shot a viewer scrutinizes most, so+ * the board asks for 1080P unless the project pins another+ * (`videoSettings.falLipSyncResolution`).+ */+export const MUSIC_VIDEO_LIPSYNC_DEFAULT_RESOLUTION = '1080P';++/**+ * Verified source-audio lip-sync lanes, keyed by Music Video backend.+ *+ * `maxAudioSec` is PortOS's per-take ceiling, not the provider's: fal accepts+ * up to 15 minutes of audio. A performance take is one shot of the edit, and a+ * flawed take can only be re-rolled whole, so a take is kept to about one+ * sung phrase — 30s — and a longer shot is split on a lyric boundary. 30s also+ * matches Seedance 2.5's audio-reference ceiling (30.2s), so a shot split for+ * one lip-sync lane fits the other. Takes past 15s are billed at 1.2×; the+ * cost label says so, and a director who wants to avoid it splits shorter.+ */export const SOURCE_AUDIO_LIPSYNC = Object.freeze({fal: Object.freeze({provider: 'fal',label: 'fal.ai MiniMax H3 lip-sync',- modelId: 'minimax/h3-max/lip-sync/image-to-video',+ modelId: FAL_LIPSYNC_VIDEO_MODEL,minAudioSec: 5,- maxAudioSec: 14.8,+ maxAudioSec: 30,transcription: true,- // fal.ai publishes no per-request price PortOS can read; say so plainly- // rather than inventing an estimate.- costLabel: 'cost unknown — billed to your fal.ai account',+ resolutions: Object.freeze(falVideoResolutions(getFalVideoModel(FAL_LIPSYNC_VIDEO_MODEL))),+ defaultResolution: MUSIC_VIDEO_LIPSYNC_DEFAULT_RESOLUTION,+ // The published rate at the default resolution; the board shows each+ // take's own estimate beside it (falSceneTake).+ costLabel: `${describeFalVideoRate(FAL_LIPSYNC_VIDEO_MODEL, MUSIC_VIDEO_LIPSYNC_DEFAULT_RESOLUTION)} — billed to your fal.ai account`,}),});@@ -336,3 +371,66 @@ export function planShotSplit({ startSec, endSec, maxSec, lyricCues, phrases, be}return { ok: true, pieces: chosen.pieces };}++/**+ * The fal.ai request one take of `scene` makes on the fal lane, and its+ * estimated cost — the single answer the board's cost line, the submit+ * payload and the production autopilot's dollar cap all read, so what the+ * director is shown is what is sent and what is charged against the cap.+ *+ * A performance scene renders on the lip-sync route for its planned audio+ * window at `videoSettings.falLipSyncResolution` (default 1080P). A cutaway+ * renders on `videoSettings.falModelId` (default Hailuo-02 image-to-video) at+ * `falResolution` (default: the model's), for the pinned `falDuration` or else+ * the shot's span — rounded UP to a length the model delivers, so the clip+ * covers the shot. An uncurated model keeps the legacy contract (only an+ * explicit pin is sent) and reports cost unknown.+ *+ * Returns `{ performance, modelId, seconds, resolution, costUsd }`; `seconds`+ * and `costUsd` are null when unknown (an untimed or unplannable performance,+ * an uncurated model).+ */+export function falSceneTake({ scene, videoSettings = {}, songDurationSec = null } = {}) {+ const settings = videoSettings || {};+ if (isPerformanceScene(scene)) {+ const capability = SOURCE_AUDIO_LIPSYNC.fal;+ const model = getFalVideoModel(capability.modelId);+ const resolution = resolveFalVideoResolution(model, settings.falLipSyncResolution || capability.defaultResolution);+ const plan = planPerformanceWindow({+ startSec: scene.startSec, endSec: scene.endSec, songDurationSec: songDurationSec ?? Infinity, capability,+ });+ const seconds = plan.ok ? plan.windowSec : null;+ return {+ performance: true,+ modelId: capability.modelId,+ seconds,+ resolution,+ costUsd: seconds == null ? null : estimateFalVideoCostUsd({ modelId: capability.modelId, seconds, resolution }),+ };+ }+ const modelId = settings.falModelId || FAL_DEFAULT_IMAGE_VIDEO_MODEL;+ const model = getFalVideoModel(modelId);+ if (!model) {+ return { performance: false, modelId, seconds: settings.falDuration || null, resolution: settings.falResolution || null, costUsd: null };+ }+ const spanSec = typeof scene?.startSec === 'number' && typeof scene?.endSec === 'number' && scene.endSec > scene.startSec+ ? scene.endSec - scene.startSec+ : null;+ const seconds = coerceFalVideoSeconds(model, settings.falDuration || spanSec);+ const resolution = resolveFalVideoResolution(model, settings.falResolution);+ return { performance: false, modelId, seconds, resolution, costUsd: estimateFalVideoCostUsd({ modelId, seconds, resolution }) };+}++/**+ * A `falSceneTake` as `/api/video-gen` fields. A performance take sends only+ * its lip-sync resolution — its length follows the song slice the server cuts;+ * a cutaway names its model, length and resolution. Unknown values stay absent+ * so the server resolves its own defaults (an uncurated model's legacy body).+ */+export const falTakeRequestFields = (take) => (take.performance+ ? (take.resolution ? { falResolution: take.resolution } : {})+ : {+ falModelId: take.modelId,+ ...(take.seconds != null ? { falDuration: take.seconds } : {}),+ ...(take.resolution ? { falResolution: take.resolution } : {}),+ });diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex c9e9fe7191..d18cddd36a 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -10,7 +10,7 @@import { z } from 'zod';import { MUSIC_VIDEO_STILL_MOVES, MUSIC_VIDEO_VISUAL_LAYERS } from './musicVideoLayers.js';-import { MUSIC_VIDEO_SHOT_MODES } from './musicVideoShotTiming.js';+import { MUSIC_VIDEO_SHOT_MODES, SOURCE_AUDIO_LIPSYNC } from './musicVideoShotTiming.js';import {MUSIC_VIDEO_AUTOMATION_BUDGET_MAX_USD,MUSIC_VIDEO_AUTOMATION_GUIDANCE_MAX,@@ -62,6 +62,17 @@ export const musicVideoVideoSettingsSchema = z.object({// not PortOS, owns the set of valid durations per model. null/omitted lets// the backend's model default apply.falDuration: z.number().min(1).max(60).nullable().optional(),+ // fal.ai cutaway model (lib/falVideoModels.js) and its output resolution.+ // Loosely validated like routes/videoGen.js's falModelId/falResolution: a+ // peer on a newer catalog may pin a model this install does not curate yet,+ // and the resolution alphabet is per model — the provider resolves both (an+ // uncurated id renders on the legacy body with its cost reported unknown).+ // null/omitted = the default model (Hailuo-02 image-to-video) / its default.+ falModelId: z.string().min(1).max(200).nullable().optional(),+ falResolution: z.string().min(1).max(16).nullable().optional(),+ // Output resolution of a performance (lip-sync) take — fal's own alphabet+ // for the lip-sync route. null/omitted = MUSIC_VIDEO_LIPSYNC_DEFAULT_RESOLUTION.+ falLipSyncResolution: z.enum(SOURCE_AUDIO_LIPSYNC.fal.resolutions).nullable().optional(),generationMode: z.enum(['image', 'audioReactive']).optional(),audioReactiveLora: z.string().max(255).regex(/^[^/\\]+\.safetensors$/i).nullable().optional(),audioReactiveScale: z.number().min(0).max(2).optional(),diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.jsindex a08b61c791..e866dafcdd 100644--- a/server/routes/musicVideo.test.js+++ b/server/routes/musicVideo.test.js@@ -198,17 +198,20 @@ describe('musicVideo routes', () => {expect(svc.updateProject).toHaveBeenCalledWith('mv-1', { videoSettings });});- it('PATCH /:id accepts the fal.ai video backend with a bounded clip duration (#8968)', async () => {- const videoSettings = { backend: 'fal', falDuration: 6 };+ it('PATCH /:id accepts the fal.ai video backend with a bounded clip duration, model and resolutions (#8968)', async () => {+ const videoSettings = {+ backend: 'fal', falDuration: 6, falModelId: 'minimax/h3-max/image-to-video', falResolution: '1080P', falLipSyncResolution: '2K',+ };const r = await request(app).patch('/api/music-video/mv-1').send({ videoSettings });expect(r.status).toBe(200);expect(svc.updateProject).toHaveBeenCalledWith('mv-1', { videoSettings });});- it('PATCH /:id rejects an out-of-range fal.ai clip duration', async () => {- const r = await request(app).patch('/api/music-video/mv-1')- .send({ videoSettings: { backend: 'fal', falDuration: 90 } });- expect(r.status).toBe(400);+ it('PATCH /:id rejects an out-of-range fal.ai clip duration or a lip-sync resolution fal does not offer', async () => {+ for (const videoSettings of [{ backend: 'fal', falDuration: 90 }, { backend: 'fal', falLipSyncResolution: '720p' }]) {+ const r = await request(app).patch('/api/music-video/mv-1').send({ videoSettings });+ expect(r.status).toBe(400);+ }expect(svc.updateProject).not.toHaveBeenCalled();});diff --git a/server/routes/musicVideoSceneSplit.test.js b/server/routes/musicVideoSceneSplit.test.jsindex ef7490eb05..be8890b2a2 100644--- a/server/routes/musicVideoSceneSplit.test.js+++ b/server/routes/musicVideoSceneSplit.test.js@@ -27,9 +27,9 @@ app.use('/api/music-video', musicVideoRoutes);app.use(errorMiddleware);const LYRICS = [- { text: 'first line', startSec: 30, endSec: 37 },- { text: 'second line', startSec: 39, endSec: 46 },- { text: 'third line', startSec: 47.5, endSec: 55 },+ { text: 'first line', startSec: 30, endSec: 45 },+ { text: 'second line', startSec: 47, endSec: 68 },+ { text: 'third line', startSec: 70, endSec: 85 },];let project;@@ -49,18 +49,18 @@ describe('POST /:id/scenes/:sceneId/split', () => {it('splits an over-long performance shot at the lyric pauses, keeping the original id, takes and neighbours', async () => {const before = await projects.addProjectScene(project.id, { label: 'Intro', startSec: 0, endSec: 30 });const shot = await projects.addProjectScene(project.id, {- label: 'Verse', prompt: 'singer at the mic', startSec: 30, endSec: 56, shotMode: 'performance', loop: false,+ label: 'Verse', prompt: 'singer at the mic', startSec: 30, endSec: 86, shotMode: 'performance', loop: false,});- const after = await projects.addProjectScene(project.id, { label: 'Outro', startSec: 56, endSec: 70 });+ const after = await projects.addProjectScene(project.id, { label: 'Outro', startSec: 86, endSec: 100 });await projects.updateScene(project.id, shot.sceneId, { referenceImageId: 'singer.png', videoHistoryId: 'clip-whole-verse' });// No backend in the body: the project's pinned fal lane bounds the take.const res = await split(shot.sceneId);expect(res.status).toBe(200);const pieces = res.body.scenes;- // 26s over a ~14.75s lip-sync window fits two takes, but any two-way cut+ // 56s over the ~29.95s lip-sync take fits two takes, but any two-way cut// lands inside "second line" — so it takes a third and cuts in both pauses.- expect(pieces.map((p) => [p.startSec, p.endSec])).toEqual([[30, 38], [38, 46.75], [46.75, 56]]);+ expect(pieces.map((p) => [p.startSec, p.endSec])).toEqual([[30, 46], [46, 69], [69, 86]]);expect(pieces[0].sceneId).toBe(shot.sceneId);expect(pieces.map((p) => p.label)).toEqual(['Verse · 1/3', 'Verse · 2/3', 'Verse · 3/3']);expect(pieces.map((p) => p.lyricText)).toEqual(['first line', 'second line', 'third line']);@@ -71,7 +71,7 @@ describe('POST /:id/scenes/:sceneId/split', () => {expect(stored.scenes.map((s) => [s.sceneId, s.order])).toEqual([[before.sceneId, 0], [shot.sceneId, 1], [pieces[1].sceneId, 2], [pieces[2].sceneId, 3], [after.sceneId, 4],]);- // The lip-synced clip was generated for 30–56s: it stays a candidate take+ // The lip-synced clip was generated for 30–86s: it stays a candidate take// but is no longer selected, so the render never re-cuts it.expect(stored.scenes[1].videoHistoryId).toBeNull();expect(stored.scenes[1].takes.map((t) => t.assetId)).toEqual(['singer.png', 'clip-whole-verse']);diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 228a708a34..f5c4cb87f1 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -300,6 +300,18 @@ const generateBodySchema = z.object({(v) => (v == null || v === '' ? undefined : Number(v)),optionalNum(1, 60, 'falDuration'),),+ // Output resolution for a curated fal model (lib/falVideoModels.js). Loosely+ // validated: the alphabet is per model ('768P' vs '720p'), so the provider+ // resolves it against the chosen model and falls back to that model's+ // default rather than 400ing a render over a stale pin.+ falResolution: z.preprocess((v) => (v === '' ? undefined : v), z.string().min(1).max(16).optional()),+ // Ask a fal model that can synthesize audio to do so. Off by default: a+ // PortOS clip is silent unless the caller wants provider audio (a Music+ // Video's master song is its only soundtrack).+ falGenerateAudio: z.preprocess(+ (v) => (v === 'true' ? true : v === 'false' || v === '' ? undefined : v),+ z.boolean().optional(),+ ),// reactor.inc fast-h3 (#6214): the clip id to chain from// (continue_from_clip_id — frame-accurate continuation, unlike fal/grok// which start a fresh render each time) and clip length in seconds. Thediff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex 5bf390063e..80bc3130dc 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -868,9 +868,11 @@ describe('videoGen routes', () => {{ backend: 'grok', input: { grokDuration: 10 },minimal: { grokPath: '/example/grok', aspectRatio: '16:9', width: undefined, height: undefined, duration: undefined },tagged: { grokPath: '/example/grok', aspectRatio: '9:16', width: 576, height: 1024, duration: 10 } },- { backend: 'fal', input: { falModelId: 'example/model', falDuration: 6 },+ // The chosen model, its resolution and an explicit audio request thread+ // through to the queued job (videoGen/fal.js resolves them per model).+ { backend: 'fal', input: { falModelId: 'bytedance/seedance-2.5/image-to-video', falDuration: 6, falResolution: '1080p', falGenerateAudio: 'true' },minimal: { modelId: undefined, aspectRatio: undefined, width: undefined, height: undefined, duration: undefined },- tagged: { modelId: 'example/model', aspectRatio: '9:16', width: 576, height: 1024, duration: 6 } },+ tagged: { modelId: 'bytedance/seedance-2.5/image-to-video', aspectRatio: '9:16', width: 576, height: 1024, duration: 6, resolution: '1080p', generateAudio: true } },{ backend: 'reactor', input: { reactorClipId: 'example-clip', reactorSeconds: 6, reactorSeed: 0, reactorAspect: '9:16' },minimal: { continueFromClipId: undefined, seconds: undefined, seed: undefined, aspect: undefined },tagged: { continueFromClipId: 'example-clip', seconds: 6, seed: 0, aspect: '9:16' } },diff --git a/server/services/musicVideo/performanceShot.js b/server/services/musicVideo/performanceShot.jsindex 6cf8a26501..9f7102aee5 100644--- a/server/services/musicVideo/performanceShot.js+++ b/server/services/musicVideo/performanceShot.js@@ -38,6 +38,7 @@ import { basename, join } from 'path';import { ServerError } from '../../lib/errorHandler.js';import { ensureDir, PATHS } from '../../lib/fileUtils.js';import { findFfmpeg, probeVideoDuration, runFfmpegProcess } from '../../lib/ffmpeg.js';+import { getFalVideoModel } from '../../lib/falVideoModels.js';import {clipRelativeCues,isPerformanceScene,@@ -122,11 +123,14 @@ export async function findStalePerformanceTakes(project, masterPath) {* Prepare a Music Video scene render's performance inputs.** Returns `null` for a cutaway scene (nothing to add), or- * `{ audioFilePath, shotInstruction, modelId, enableTranscription }` for a- * performance scene on a capable backend. Throws a 4xx ServerError when the- * scene is a performance shot the backend or its timing cannot deliver.+ * `{ audioFilePath, shotInstruction, modelId, resolution, enableTranscription }`+ * for a performance scene on a capable backend. `resolution` is the take's+ * output resolution: the request's own when the lip-sync route offers it, else+ * the project's `videoSettings.falLipSyncResolution`, else the capability+ * default (1080P). Throws a 4xx ServerError when the scene is a performance+ * shot the backend or its timing cannot deliver.*/-export async function preparePerformanceShot({ musicVideo, backend, sourceImagePath, mode }) {+export async function preparePerformanceShot({ musicVideo, backend, sourceImagePath, mode, resolution = null }) {if (!musicVideo?.projectId || !musicVideo?.sceneId) return null;const project = await getProject(musicVideo.projectId);const scene = project?.scenes?.find((s) => s.sceneId === musicVideo.sceneId);@@ -150,6 +154,9 @@ export async function preparePerformanceShot({ musicVideo, backend, sourceImagePif (songDurationSec == null) throw refuse('Could not read the song duration for this performance shot', 'MUSIC_VIDEO_AUDIO_UNREADABLE');const plan = planPerformanceWindow({ startSec: scene.startSec, endSec: scene.endSec, songDurationSec, capability });if (!plan.ok) throw refuse(plan.message, plan.code);+ const offered = getFalVideoModel(capability.modelId)?.resolution?.options || capability.resolutions || [];+ const pick = (value) => (typeof value === 'string' ? offered.find((o) => o.toLowerCase() === value.trim().toLowerCase()) : null);+ const takeResolution = pick(resolution) || pick(project.videoSettings?.falLipSyncResolution) || capability.defaultResolution;// An optional vocal stem conditions the provider in place of the mix. It// is re-checked here because the file could have been replaced on disk or@@ -199,6 +206,7 @@ export async function preparePerformanceShot({ musicVideo, backend, sourceImagePminAudioSec: capability.minAudioSec,maxAudioSec: capability.maxAudioSec,transcription: capability.transcription,+ resolution: takeResolution,},// The provider's output length follows the submitted audio.generatedCoverageSec: plan.windowSec,@@ -207,6 +215,7 @@ export async function preparePerformanceShot({ musicVideo, backend, sourceImagePaudioFilePath,shotInstruction,modelId: capability.modelId,+ resolution: takeResolution,enableTranscription: capability.transcription === true,};}diff --git a/server/services/musicVideo/performanceShot.test.js b/server/services/musicVideo/performanceShot.test.jsindex 2da1b9f8ad..97d083b5c3 100644--- a/server/services/musicVideo/performanceShot.test.js+++ b/server/services/musicVideo/performanceShot.test.js@@ -116,7 +116,10 @@ describe.skipIf(!ffmpeg)('music-video performance shot through the fal lip-syncexpect(si.audio.sha256).toMatch(/^[0-9a-f]{64}$/);expect(si.audio.conditioning).toEqual({ source: 'master', sha256: si.audio.sha256 });expect(si).toMatchObject({ referenceImageId: 'frame.png', performance: 'sings the held note', generatedCoverageSec: 5.05 });- expect(si.capability).toMatchObject({ provider: 'fal', minAudioSec: 5, maxAudioSec: 14.8 });+ // The take's own resolution defaults to 1080P for a music video (fal's own+ // default is 768P) and is recorded on the immutable instruction.+ expect(si.capability).toMatchObject({ provider: 'fal', minAudioSec: 5, maxAudioSec: 30, resolution: '1080P' });+ expect(prepared.resolution).toBe('1080P');// Sample-exact window content: exactly 5.05s of samples, the song marker at// the in-point, and the slice staged where the queue will clean it up.@@ -128,8 +131,9 @@ describe.skipIf(!ffmpeg)('music-video performance shot through the fal lip-syncfor (let i = 1; i < samples.length / 2; i++) if (samples.readInt16LE(i * 2) > samples.readInt16LE(peak * 2)) peak = i;expect(peak).toBe(Math.round((MARKER_SEC - 18.225) * RATE));- // Generation payload: the reference frame plus these exact bytes, with no- // prompt/duration a lip-sync route would contradict. Submitted exactly once.+ // Generation payload: the reference frame plus these exact bytes at the+ // take's resolution, with no prompt/duration a lip-sync route would+ // contradict — and no prompt is required to submit one. Submitted once.await mkdir(PATHS.images, { recursive: true });await writeFile(join(PATHS.images, 'frame.png'), Buffer.from('89504e470d0a1a0a', 'hex'));const deliveredPath = join(PATHS.data, 'delivered.mp4');@@ -147,14 +151,21 @@ describe.skipIf(!ffmpeg)('music-video performance shot through the fal lip-syncthrow new Error(`unexpected fetch: ${url}`);}));const job = await fal.generateVideo({- apiKey: 'test-key', modelId: prepared.modelId, prompt: 'singer at the mic',+ apiKey: 'test-key', modelId: prepared.modelId, resolution: prepared.resolution,sourceImagePath: join(PATHS.images, 'frame.png'), audioFilePath: prepared.audioFilePath,lipSync: { enableTranscription: prepared.enableTranscription }, shotInstruction: si,});expect(await waitForTerminal(job.jobId)).toMatchObject({ type: 'completed' });expect(posts).toHaveLength(1);expect(posts[0].url).toBe('https://queue.fal.run/minimax/h3-max/lip-sync/image-to-video');- expect(Object.keys(posts[0].body).sort()).toEqual(['audio_url', 'enable_transcription', 'image_url']);+ expect(Object.keys(posts[0].body).sort()).toEqual(['audio_url', 'enable_transcription', 'image_url', 'resolution']);+ expect(posts[0].body.resolution).toBe('1080P');+ // The history record carries what was rendered and what it should cost:+ // 5.05s at the 1080P list rate of $0.16/s.+ const { loadHistory } = await import('../videoGen/history.js');+ expect((await loadHistory()).find((h) => h.id === job.jobId)).toMatchObject({+ modelId: 'fal:minimax/h3-max/lip-sync/image-to-video', resolution: '1080P', estimatedCostUsd: 0.808, lipSync: true,+ });expect(Buffer.from(posts[0].body.audio_url.replace(/^data:audio\/wav;base64,/, ''), 'base64').equals(sliceWav)).toBe(true);// Final timeline: the take lands with its instruction, the renderer reads@@ -223,17 +234,23 @@ describe.skipIf(!ffmpeg)('music-video performance shot through the fal lip-syncexpect(existsSync(PATHS.uploads) ? await readdir(PATHS.uploads) : []).toEqual([]);});- it('uses the full span of a long shot and stays under the provider maximum', async () => {- getProject.mockResolvedValue(project({ startSec: 10, endSec: 24.7 }));- const { shotInstruction: si } = await preparePerformanceShot({- musicVideo: { projectId: 'mv-1', sceneId: 'mvs-1' }, backend: 'fal', sourceImagePath: '/x/frame.png', mode: 'image',- });- expect(si.audioWindow).toEqual({ startSec: 10, endSec: 24.7, durationSec: 14.7 });- expect(si.edit.inSec).toBe(0);+ it('uses the full span of a long shot in one take, at the project\'s lip-sync resolution pin', async () => {+ // 26s: past the old 14.8s cap (fal accepts up to 15 minutes; PortOS keeps+ // a take to 30s so it stays one editable phrase).+ getProject.mockResolvedValue({ ...project({ startSec: 2, endSec: 28 }), videoSettings: { backend: 'fal', falLipSyncResolution: '768P' } });+ const args = { musicVideo: { projectId: 'mv-1', sceneId: 'mvs-1' }, backend: 'fal', sourceImagePath: '/x/frame.png', mode: 'image' };+ const pinned = await preparePerformanceShot(args);+ expect(pinned.shotInstruction.audioWindow).toEqual({ startSec: 2, endSec: 28, durationSec: 26 });+ expect(pinned.shotInstruction.edit.inSec).toBe(0);+ expect(pinned.resolution).toBe('768P');+ // A request naming a resolution the lip-sync route offers wins over the+ // pin; one it does not (a cutaway model's '720p') falls back to the pin.+ expect((await preparePerformanceShot({ ...args, resolution: '2k' })).resolution).toBe('2K');+ expect((await preparePerformanceShot({ ...args, resolution: '720p' })).resolution).toBe('768P');});it('refuses a shot longer than the provider synchronizes instead of letting it truncate', async () => {- getProject.mockResolvedValue(project({ startSec: 5, endSec: 20 }));+ getProject.mockResolvedValue(project({ startSec: 0, endSec: 30 }));await expect(preparePerformanceShot({musicVideo: { projectId: 'mv-1', sceneId: 'mvs-1' }, backend: 'fal', sourceImagePath: '/x/frame.png',})).rejects.toMatchObject({ status: 400, code: 'MUSIC_VIDEO_PERFORMANCE_TOO_LONG' });diff --git a/server/services/musicVideo/production.js b/server/services/musicVideo/production.jsindex 7a1376eb9c..d457ccc226 100644--- a/server/services/musicVideo/production.js+++ b/server/services/musicVideo/production.js@@ -312,10 +312,12 @@ export function nextProductionStep(project, run, { jobs = [], processId = null }* 409 when the run is not running in this process, the slot already has a* live step (a concurrent advance or a double submit), or a limit would be* exceeded — so a job past the budget is refused before it is paid for.+ * `costUsd` is the step's own estimate when the caller can price the scene+ * (a fal take); absent, the route's start-time price applies.* Returns `{ project, run, step }`.*/export function reserveProductionStep(project, runId, {- kind, sceneId, revisionId = null, route, rationale = '', processId,+ kind, sceneId, revisionId = null, route, rationale = '', processId, costUsd: stepCostUsd = null,}, now = new Date().toISOString()) {let step = null;const out = mutateRun(project, runId, (run) => {@@ -329,7 +331,9 @@ export function reserveProductionStep(project, runId, {if (run.usage.generations >= run.limits.maxGenerations) {throw productionError(409, 'PRODUCTION_SPEND_LIMIT', `This production run reached its ${run.limits.maxGenerations}-generation limit`);}- const price = run.pricing?.[routeKey(route)];+ // A scene-specific estimate (a fal take priced by its own length and+ // resolution) wins over the route's flat start-time price.+ const price = typeof stepCostUsd === 'number' ? stepCostUsd : run.pricing?.[routeKey(route)];const costUsd = typeof price === 'number' ? price : null;if (run.limits.spendCapUsd !== null) {if (costUsd === null) throw productionError(409, 'PRODUCTION_COST_UNKNOWN', 'This route has no known price, so the dollar cap cannot bound it');diff --git a/server/services/musicVideo/productionDispatch.js b/server/services/musicVideo/productionDispatch.jsindex 9b3ceb6e6e..c038e16841 100644--- a/server/services/musicVideo/productionDispatch.js+++ b/server/services/musicVideo/productionDispatch.js@@ -23,9 +23,9 @@import { ServerError } from '../../lib/errorHandler.js';import { resolveGalleryImage } from '../../lib/pathSafety.js';import { RENDER_TARGET } from '../../lib/renderTargets.js';-import { approximateMotionCues, grokCoverage } from '../../lib/musicVideoShotTiming.js';+import { approximateMotionCues, falSceneTake, falTakeRequestFields, grokCoverage } from '../../lib/musicVideoShotTiming.js';import { sceneFramePrompt, sceneShotPrompt } from './handoff.js';-import { conditioningReferences } from './productionPool.js';+import { conditioningReferences, falRouteVideoSettings } from './productionPool.js';const unprompted = (scene, what) => new ServerError(`"${scene.label || scene.sceneId}" has no ${what} prompt to generate from`,@@ -70,6 +70,17 @@ async function dispatchFrame({ project, scene, route, tag, settings }) {return { jobId };}+/**+ * The fal request fields for a scene clip — built from the same `falSceneTake`+ * that productionPool.stepPriceUsd charged the step, so the run pays for exactly+ * what it submits.+ */+const falClipParams = (project, scene, route) => falTakeRequestFields(falSceneTake({+ scene,+ videoSettings: falRouteVideoSettings(project, route),+ songDurationSec: project.audioAnalysis?.durationSec ?? null,+}));+/** Enqueue a scene's i2v clip on exactly `route` through the video submit service. Returns `{ jobId }`. */async function dispatchClip({ project, scene, route, tag }) {if (!scene.referenceImageId) {@@ -84,8 +95,7 @@ async function dispatchClip({ project, scene, route, tag }) {const byBackend = {local: { modelId: route.model, disableAudio: true },grok: { grokDuration: spanSec != null ? grokCoverage(spanSec).requestSec : (project.videoSettings?.grokDuration || 10), disableAudio: true },- // A performance clip's length follows its song slice (server-side).- fal: { ...(route.model ? { falModelId: route.model } : {}), ...(scene.shotMode === 'performance' || !project.videoSettings?.falDuration ? {} : { falDuration: project.videoSettings.falDuration }) },+ fal: falClipParams(project, scene, route),reactor: { disableAudio: true },};const { submitVideoGenJob } = await import('../videoGen/submitJob.js');diff --git a/server/services/musicVideo/productionDispatch.test.js b/server/services/musicVideo/productionDispatch.test.jsindex 0e51dfc373..ca830657a5 100644--- a/server/services/musicVideo/productionDispatch.test.js+++ b/server/services/musicVideo/productionDispatch.test.js@@ -60,4 +60,23 @@ describe('production scene dispatch (#9066)', () => {backend: 'grok', mode: 'image', sourceImageFile: 'frame-example.png', grokDuration: 6, musicVideo: clipTag,}), {});});++ it('submits a fal clip as exactly the take the step was priced for (falSceneTake)', async () => {+ const clipTag = { ...tag, productionStepKey: 'clip:mvs-a:base:1' };+ const falProject = { ...project, videoSettings: { backend: 'fal', falModelId: 'fal-ai/veo3.1/fast/image-to-video', falResolution: '1080p' } };+ // A 4s cutaway on Veo 3.1 Fast (4/6/8s clips) renders 4s at the pinned resolution.+ await dispatchProductionStep({ stepKind: 'clip', project: falProject, scene, route: { kind: 'video', mode: 'fal', model: null }, tag: clipTag, settings });+ expect(submitVideoGenJob.mock.calls[0][0]).toMatchObject({+ backend: 'fal', falModelId: 'fal-ai/veo3.1/fast/image-to-video', falDuration: 4, falResolution: '1080p',+ });+ // A performance take sends only its lip-sync resolution: its length follows the song slice.+ await dispatchProductionStep({+ stepKind: 'clip', project: falProject, scene: { ...scene, shotMode: 'performance' },+ route: { kind: 'video', mode: 'fal', model: null }, tag: clipTag, settings,+ });+ const performance = submitVideoGenJob.mock.calls[1][0];+ expect(performance).toMatchObject({ backend: 'fal', falResolution: '1080P' });+ expect(performance).not.toHaveProperty('falDuration');+ expect(performance).not.toHaveProperty('falModelId');+ });});diff --git a/server/services/musicVideo/productionPool.js b/server/services/musicVideo/productionPool.jsindex 089d2fd766..d85d02bbe4 100644--- a/server/services/musicVideo/productionPool.js+++ b/server/services/musicVideo/productionPool.js@@ -15,15 +15,19 @@* that cannot serve a scene is skipped for that scene with the reason* recorded; when no pool route can, the run halts with every reason listed.*- * `metered` routes spend money or remote quota. PortOS has no price catalog- * for any of them, so their price is unknown (null) and a run with a dollar- * cap refuses them; local routes cost $0.+ * `metered` routes spend money or remote quota. fal.ai video routes are priced+ * from the curated fal catalog (lib/falVideoModels.js via `falSceneTake`): the+ * run's start-time price is a cutaway take on the project's fal model, and each+ * step is charged its own scene's estimate (a lip-sync take costs by its audio+ * window and resolution). Other metered routes have no price catalog, so their+ * price is unknown (null) and a run with a dollar cap refuses them; local+ * routes cost $0.*/import { ServerError } from '../../lib/errorHandler.js';import { QUEUEABLE_IMAGE_MODES, VIDEO_GEN_MODES } from '../../lib/generationModes.js';import { MUSIC_VIDEO_AUTOMATION_TOOLS } from '../../lib/musicVideoAutomation.js';-import { isPerformanceScene, performanceBlockedReason } from '../../lib/musicVideoShotTiming.js';+import { falSceneTake, isPerformanceScene, performanceBlockedReason } from '../../lib/musicVideoShotTiming.js';import { maxInputImages, supportsCloudModelOverride } from '../../lib/imageGenCapabilities.js';import { isHardwareCompatible } from '../../lib/systemCapabilities.js';import { RUNNER_FAMILIES } from '../../lib/runners.js';@@ -36,11 +40,47 @@ const MAX_CONDITIONING_REFERENCES = 4;const describe = (route) => `${route.kind} ${route.mode}${route.model ? ` (${route.model})` : ''}`;const isMetered = (route) => MUSIC_VIDEO_AUTOMATION_TOOLS.some((t) => t.id === `${route.kind}:${route.mode}` && t.metered);-/** The price per generation this install can vouch for: 0 for local, null (unknown) for metered. */-const routePriceUsd = (route) => (isMetered(route) ? null : 0);+/**+ * The render settings a fal route renders a scene with: the project's fal pins,+ * with a route that names its own model overriding the cutaway model.+ */+export const falRouteVideoSettings = (project, route) => ({+ ...(project?.videoSettings || {}),+ ...(route?.model ? { falModelId: route.model } : {}),+});++/**+ * The price per generation this install can vouch for: 0 for local, the+ * catalog estimate of a default-length cutaway take for a fal video route+ * (null when its model is uncurated), null (unknown) for other metered routes.+ */+function routePriceUsd(route, project = null) {+ if (!isMetered(route)) return 0;+ if (route.kind === 'video' && route.mode === 'fal') {+ return falSceneTake({ scene: null, videoSettings: falRouteVideoSettings(project, route) }).costUsd;+ }+ return null;+}++/**+ * What ONE step on `route` for `scene` should cost — the figure a step is+ * charged against the dollar cap. For a fal clip it is that scene's own take+ * (a performance by its audio window and lip-sync resolution, a cutaway by the+ * length that covers the shot); otherwise the route's flat price.+ */+export function stepPriceUsd({ route, project, scene, stepKind }) {+ if (stepKind !== 'frame' && route?.kind === 'video' && route.mode === 'fal' && scene) {+ return falSceneTake({+ scene,+ videoSettings: falRouteVideoSettings(project, route),+ songDurationSec: project?.audioAnalysis?.durationSec ?? null,+ }).costUsd;+ }+ return routePriceUsd(route, project);+}-/** routeKey → price map for a pool. */-export const poolPricing = (pool) => Object.fromEntries(pool.map((r) => [routeKey(r), routePriceUsd(r)]));+/** routeKey → price map for a pool (fal routes priced for `project`). */+export const poolPricing = (pool, project = null) => Object.fromEntries(pool.map((r) => [routeKey(r), routePriceUsd(r, project)]));/** The visual-spec references a frame is conditioned on (capped to the backend limit). */export const conditioningReferences = (project) => (project?.visualSpec?.references || [])diff --git a/server/services/musicVideo/productionService.js b/server/services/musicVideo/productionService.jsindex 2fe43aad1d..50fb94cdd0 100644--- a/server/services/musicVideo/productionService.js+++ b/server/services/musicVideo/productionService.js@@ -50,6 +50,7 @@ import {chooseProductionRoute,loadPoolEnv,poolPricing,+ stepPriceUsd,sceneRequirement,} from './productionPool.js';@@ -130,6 +131,7 @@ async function dispatchSlot(projectId, runId, { stepKind, sceneId, revisionId =const reserved = await mutateProjectRecord(projectId, (current) => reserveProductionStep(current, runId, {kind: stepKind, sceneId, revisionId, route: choice.route, rationale: choice.rationale, processId: PROCESS_ID,+ costUsd: stepPriceUsd({ route: choice.route, project, scene, stepKind }),})).catch((err) => ({ error: err }));if (reserved.error) {const code = reserved.error.code;@@ -283,7 +285,7 @@ export async function startProduction(projectId, { directive, pool: requested, lconst pool = normalizeProductionPool(requested);await assertPoolEligible(pool, await deps.loadEnv());const out = await mutateProjectRecord(projectId, (current) => startProductionOnProject(current, {- directive, pool, limits, reviewer, processId: PROCESS_ID, pricing: poolPricing(pool),+ directive, pool, limits, reviewer, processId: PROCESS_ID, pricing: poolPricing(pool, current),}));console.log(`🎬 Music Video production ${short(out.run.id)} started: ${out.run.pool.length} allowed route(s), ≤${out.run.limits.maxGenerations} generations, ≤${out.run.limits.maxReviewAttempts} reviews`);advanceInBackground(projectId, out.run.id);diff --git a/server/services/musicVideo/productionService.test.js b/server/services/musicVideo/productionService.test.jsindex d4608ff844..200d1d9326 100644--- a/server/services/musicVideo/productionService.test.js+++ b/server/services/musicVideo/productionService.test.js@@ -325,6 +325,34 @@ describe('music video production run (#9066)', () => {expect(theRun().limits.spendCapUsd).toBe(5);});+ it('prices fal.ai clips from the catalog so a dollar cap bounds them, charging each scene its own take', async () => {+ // Scene A is a 4s performance (lip-sync window padded to 5.05s), B a 4s+ // cutaway on H3 Max (covered by its 5s minimum), both at 1080P list rates.+ seedProject({+ videoSettings: { backend: 'fal', falModelId: 'minimax/h3-max/image-to-video', falResolution: '1080P' },+ audioAnalysis: { sections: [{ startSec: 0, endSec: 8, label: 'Verse' }], durationSec: 30 },+ });+ store.get('mv-example').scenes[0].shotMode = 'performance';+ const falPool = [POOL[0], { kind: 'video', mode: 'fal', model: null }];+ const usable = env.isVideoModeUsable;+ env.isVideoModeUsable = (_settings, mode) => mode === 'local' || mode === 'fal';+ try {+ await start({ pool: falPool, limits: { ...LIMITS, spendCapUsd: 1.5 } });+ // The run's start-time price for the route: a default-length cutaway.+ expect(theRun().pricing).toEqual({ 'image:local:flux2-dev': 0, 'video:fal:': 0.8 });+ completeJob('job-1');+ completeJob('job-2');+ await settle();+ } finally {+ env.isVideoModeUsable = usable;+ }+ const clips = theRun().steps.filter((s) => s.kind === 'clip');+ // A's lip-sync take is charged 5.05s × $0.16; B's $0.80 would pass the cap.+ expect(clips.map((s) => [s.sceneId, s.costUsd])).toEqual([['mvs-a', 0.808]]);+ expect(theRun()).toMatchObject({ status: 'limit-reached', usage: { spentUsd: 0.808 }, stopReason: expect.stringMatching(/\$1\.5 cap/) });+ expect(dispatch.mock.calls.filter(([a]) => a.stepKind === 'clip').map(([a]) => a.scene.sceneId)).toEqual(['mvs-a']);+ });+it('after a restart nothing dispatches until an explicit resume, which neither duplicates live jobs nor re-charges them', async () => {seedProject();await start();diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.jsindex d61e7751f6..34d7391428 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -121,6 +121,9 @@ export function buildProjectRecord(input, { id, now }) {modelId: videoSettings.modelId ?? null,grokDuration: videoSettings.grokDuration ?? 10,falDuration: videoSettings.falDuration ?? null,+ falModelId: videoSettings.falModelId ?? null,+ falResolution: videoSettings.falResolution ?? null,+ falLipSyncResolution: videoSettings.falLipSyncResolution ?? null,generationMode: videoSettings.generationMode ?? 'image',audioReactiveLora: videoSettings.audioReactiveLora ?? null,audioReactiveScale: videoSettings.audioReactiveScale ?? 1.2,@@ -280,6 +283,9 @@ export function applyProjectPatch(project, patch) {modelId: null,grokDuration: 10,falDuration: null,+ falModelId: null,+ falResolution: null,+ falLipSyncResolution: null,generationMode: 'image',audioReactiveLora: null,audioReactiveScale: 1.2,diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.jsindex d90106905a..a27ef0f6eb 100644--- a/server/services/musicVideo/projectsLogic.test.js+++ b/server/services/musicVideo/projectsLogic.test.js@@ -322,6 +322,9 @@ describe('applyProjectPatch', () => {modelId: null,grokDuration: 6,falDuration: null,+ falModelId: null,+ falResolution: null,+ falLipSyncResolution: null,generationMode: 'image',audioReactiveLora: null,audioReactiveScale: 1.2,@@ -335,6 +338,9 @@ describe('applyProjectPatch', () => {modelId: 'ltx23_distilled_q4',grokDuration: 6,falDuration: null,+ falModelId: null,+ falResolution: null,+ falLipSyncResolution: null,generationMode: 'image',audioReactiveLora: null,audioReactiveScale: 1.2,diff --git a/server/services/videoGen/fal.js b/server/services/videoGen/fal.jsindex 6f7def7401..94ec68ee1a 100644--- a/server/services/videoGen/fal.js+++ b/server/services/videoGen/fal.js@@ -14,6 +14,13 @@* download the resulting MP4 and hand it to the shared `finalizeGeneratedVideo`* helper — same streaming optimization, thumbnail, and history entry as every* other video backend.+ *+ * The request body is built per model from the curated catalog+ * (lib/falVideoModels.js): parameter names and wire types differ per family+ * (Hailuo's string "6", H3's integer 5, Veo's "8s", Kling's start_image_url),+ * and a lip-sync route takes no prompt at all. A model id outside the catalog+ * keeps the legacy Hailuo-shaped body so a free-text id still renders; its+ * cost is recorded as unknown.*/import { randomUUID } from 'crypto';@@ -26,7 +33,13 @@ 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 { probeVideoGeometry } from '../../lib/ffmpeg.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 { attachSseClient as attachSse, closeJobAfterDelay, createJobFailureFinalizer } from '../../lib/sseUtils.js';import { videoGenEvents } from './events.js';import { finalizeGeneratedVideo, emitCloudRenderStatus, CLOUD_RENDER_PHASE } from './generateVideoHelpers.js';@@ -34,19 +47,19 @@ import { mutateVideoHistory } from './history.js';import { getSettings } from '../settings.js';import { nearestAspectRatio } from '../imageGen/modes.js';-// fal.ai's aspect_ratio set for the minimax hailuo-02 models this provider-// targets — matches the free-tool automation's FAL_ASPECT_RATIOS-// (services/fableLoom/falVideoAutomation.js) so both fal.ai paths agree on-// what the backend actually accepts.+// The aspect_ratio set the LEGACY body sends for a model outside the curated+// catalog — matches the free-tool automation's FAL_ASPECT_RATIOS+// (services/fableLoom/falVideoAutomation.js). Curated models carry their own+// aspect rules (or none: an image-to-video canvas follows its start frame).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 two models the issue names, one text-first and one image-first. Both-// accept `prompt`; the image-to-video variant additionally takes `image_url`.-export const FAL_DEFAULT_TEXT_MODEL = 'fal-ai/minimax/hailuo-02/standard/text-to-video';-export const FAL_DEFAULT_IMAGE_MODEL = 'fal-ai/minimax/hailuo-02/standard/image-to-video';+// 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;@@ -144,10 +157,10 @@ async function toDataUri(imagePath) {return `data:${mime};base64,${buf.toString('base64')}`;}-// Source-audio lip-sync (#8977, fal's MiniMax H3 lip-sync route): the request-// is the reference frame plus the exact song slice. The route takes no prompt,-// duration or aspect ratio — its output length follows the submitted audio, and-// the frame's own aspect ratio carries through.+// 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+// ratio — output length follows the submitted audio.function buildLipSyncRequestBody({ imageDataUri, audioDataUri, enableTranscription }) {return {image_url: imageDataUri,@@ -156,6 +169,7 @@ function buildLipSyncRequestBody({ imageDataUri, audioDataUri, enableTranscripti};}+// Legacy Hailuo-shaped body for a model id outside the curated catalog.function buildRequestBody({ prompt, negativePrompt, duration, aspectRatio, imageDataUri }) {// fal.ai's queue REST API has no dedicated negative-prompt field for these// models — fold it into the prompt as an "Avoid:" clause, same fallback@@ -230,11 +244,18 @@ export async function generateVideo({prompt = '', negativePrompt, duration, aspectRatio, width, height,sourceImagePath = null, jobId: providedJobId = null,audioFilePath = null, lipSync = null, shotInstruction = null,+ resolution = null, generateAudio = false,}) {await ensureDir(PATHS.videos);const renderStartedAtMs = Date.now();- if (!prompt?.trim()) {+ const modelId = requestedModelId || (sourceImagePath ? FAL_DEFAULT_IMAGE_MODEL : FAL_DEFAULT_TEXT_MODEL);+ const catalogModel = getFalVideoModel(modelId);+ // A lip-sync route has no prompt field at all — the frame and the song slice+ // are the whole request — so only a prompted model (or an uncurated id, whose+ // legacy body always carries one) requires it.+ const promptRequired = catalogModel ? catalogModel.prompt === 'required' : !audioFilePath;+ if (promptRequired && !prompt?.trim()) {throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });}// A lip-sync render conditions a reference frame on source audio; either@@ -253,22 +274,58 @@ export async function generateVideo({throw new ServerError('No fal.ai API key configured — set it in Settings > Video Gen or the FAL_KEY env var', { status: 400, code: 'FAL_NOT_CONFIGURED' });}- const modelId = requestedModelId || (sourceImagePath ? FAL_DEFAULT_IMAGE_MODEL : FAL_DEFAULT_TEXT_MODEL);const jobId = providedJobId || randomUUID();const filename = `${jobId}.mp4`;const outputPath = join(PATHS.videos, filename);// An explicit aspectRatio always wins (e.g. FableLoom's visualConditioning// render parameters); otherwise derive the nearest fal-supported ratio from- // the request's width/height, same as grok's deriveAspectRatio.+ // the request's width/height, same as grok's deriveAspectRatio. Legacy body+ // only — a curated model resolves its own aspect rule.const effectiveAspectRatio = FAL_ASPECT_RATIOS.includes(aspectRatio) ? aspectRatio : deriveAspectRatio(width, height);+ // A lip-sync take is billed on its audio length: the shot instruction's+ // planned window, else the staged slice itself.+ const audioSec = audioFilePath+ ? (shotInstruction?.audioWindow?.durationSec || await probeVideoDuration(audioFilePath).catch(() => null))+ : null;+ const requestSpec = {+ modelId, prompt, negativePrompt, seconds: duration, audioSec, aspectRatio, width, height, resolution,+ generateAudio: generateAudio === true, enableTranscription: lipSync?.enableTranscription === true,+ };+ // Dry-run the curated body with placeholder media before anything is read or+ // paid for: a missing required input refuses here as a 400, and the result+ // carries the coerced length, resolution and estimate the history records.+ let planned = null;+ try {+ planned = buildFalVideoRequest({+ ...requestSpec,+ imageUrl: sourceImagePath ? 'pending:image' : null,+ audioUrl: audioFilePath ? 'pending:audio' : null,+ });+ } catch (err) {+ if (err?.code !== 'FAL_MODEL_INPUT') throw err;+ throw new ServerError(err.message, { status: 400, code: 'VALIDATION_ERROR' });+ }+const meta = {id: jobId,- prompt: prompt.trim(),+ prompt: (prompt || '').trim(),negativePrompt: negativePrompt || '',modelId: `fal:${modelId}`,- ...(duration ? { duration } : {}),- ...(effectiveAspectRatio ? { aspectRatio: effectiveAspectRatio } : {}),+ ...(planned+ ? {+ ...(planned.seconds != null ? { duration: planned.seconds } : {}),+ ...(planned.body.aspect_ratio ? { aspectRatio: planned.body.aspect_ratio } : {}),+ ...(planned.resolution ? { resolution: planned.resolution } : {}),+ ...(planned.model.audio ? { generateAudio: planned.generateAudio } : {}),+ }+ : {+ ...(duration ? { duration } : {}),+ ...(effectiveAspectRatio ? { aspectRatio: effectiveAspectRatio } : {}),+ }),+ // What PortOS expected this render to cost at fal's list price, or null for+ // an uncurated model — recorded so spend can be audited per clip.+ estimatedCostUsd: planned?.estimatedCostUsd ?? null,filename,createdAt: new Date().toISOString(),mode: sourceImagePath ? 'image' : 'text',@@ -278,7 +335,8 @@ export async function generateVideo({const job = { ...meta, clients: [], status: 'running', renderStartedAtMs };jobs.set(jobId, job);- console.log(`🎬 Generating video [${jobId.slice(0, 8)}] fal (${modelId}): ${prompt.slice(0, 60)}…`);+ const costNote = meta.estimatedCostUsd != null ? ` ~$${meta.estimatedCostUsd.toFixed(2)}` : ' cost unknown';+ console.log(`🎬 Generating video [${jobId.slice(0, 8)}] fal (${modelId}${meta.resolution ? ` ${meta.resolution}` : ''}${costNote}): ${(prompt || '(lip-sync)').slice(0, 60)}…`);videoGenEvents.emit('started', { generationId: jobId, totalSteps: 1, ...meta });activeJobs.set(jobId, { ...meta, generationId: jobId, totalSteps: 1, step: 0, progress: 0 });emitCloudRenderStatus(job, jobId, CLOUD_RENDER_PHASE.SUBMIT, 'Submitting to fal.ai…');@@ -286,6 +344,7 @@ export async function generateVideo({runFalVideo(job, jobId, {apiKey, modelId, prompt, negativePrompt, duration, aspectRatio: effectiveAspectRatio, sourceImagePath, outputPath, filename, meta,audioFilePath, enableTranscription: lipSync?.enableTranscription === true,+ requestSpec: planned ? requestSpec : null,}).catch((err) => {console.error(`❌ fal video run failed [${jobId.slice(0, 8)}]: ${err?.message}`);@@ -300,7 +359,7 @@ export async function generateVideo({async function runFalVideo(job, jobId, {apiKey, modelId, prompt, negativePrompt, duration, aspectRatio, sourceImagePath, outputPath, filename, meta,- audioFilePath = null, enableTranscription = false,+ audioFilePath = null, enableTranscription = false, requestSpec = null,}) {const entry = {apiKey, controller: new AbortController(), aborted: false, cancelUrl: null, canceledRemote: false, remoteTerminal: false,@@ -309,13 +368,14 @@ async function runFalVideo(job, jobId, {const deadline = Date.now() + FAL_RENDER_TIMEOUT_MS;try {const imageDataUri = sourceImagePath ? await toDataUri(sourceImagePath) : null;- const body = audioFilePath- ? buildLipSyncRequestBody({- imageDataUri,- audioDataUri: `data:audio/wav;base64,${(await readFile(audioFilePath)).toString('base64')}`,- enableTranscription,- })- : buildRequestBody({ prompt, negativePrompt, duration, aspectRatio, imageDataUri });+ const audioDataUri = audioFilePath+ ? `data:audio/wav;base64,${(await readFile(audioFilePath)).toString('base64')}`+ : null;+ const body = requestSpec+ ? buildFalVideoRequest({ ...requestSpec, imageUrl: imageDataUri, audioUrl: audioDataUri }).body+ : audioFilePath+ ? buildLipSyncRequestBody({ imageDataUri, audioDataUri, enableTranscription })+ : buildRequestBody({ prompt, negativePrompt, duration, aspectRatio, imageDataUri });// 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);diff --git a/server/services/videoGen/fal.test.js b/server/services/videoGen/fal.test.jsindex 91d6c0765f..ebd1279cb8 100644--- a/server/services/videoGen/fal.test.js+++ b/server/services/videoGen/fal.test.js@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-import { mkdir, rm, readFile } from 'fs/promises';+import { mkdir, rm, readFile, writeFile } from 'fs/promises';import { join } from 'path';import { tmpdir } from 'os';@@ -128,6 +128,49 @@ describe('videoGen/fal — _internals.buildRequestBody', () => {});describe('videoGen/fal — generateVideo', () => {+ // A curated model builds its own body (lib/falVideoModels.js) — names and+ // wire types per family — and the history records what was rendered and its+ // list-price estimate. One family end to end; the per-family matrix is+ // pinned in lib/falVideoModels.test.js.+ it('builds a curated model\'s body through the catalog and records model, resolution and estimate', async () => {+ const framePath = join(TEST_ROOT, 'frame.png');+ await writeFile(framePath, Buffer.from('89504e470d0a1a0a', 'hex'));+ const posted = [];+ vi.stubGlobal('fetch', vi.fn(async (url, opts) => {+ if (opts?.method === 'POST') {+ posted.push({ url, body: JSON.parse(opts.body) });+ return jsonResponse({ request_id: 'rk', status_url: 'https://queue.fal.run/s', response_url: 'https://queue.fal.run/r' });+ }+ if (url === 'https://queue.fal.run/s') return jsonResponse({ status: 'COMPLETED' });+ if (url === 'https://queue.fal.run/r') return jsonResponse({ video: { url: 'https://cdn.example.com/out.mp4' } });+ if (url === 'https://cdn.example.com/out.mp4') return { ok: true, status: 200, arrayBuffer: async () => Uint8Array.from(Buffer.from('mp4')).buffer };+ throw new Error(`unexpected fetch: ${url}`);+ }));++ const job = await fal.generateVideo({+ apiKey: 'test-key', modelId: 'fal-ai/kling-video/v3/pro/image-to-video',+ prompt: 'waves roll in', negativePrompt: 'text', duration: 7.4, width: 1080, height: 1920, sourceImagePath: framePath,+ });+ expect(await waitForTerminal(job.jobId)).toMatchObject({ type: 'completed' });+ expect(posted).toHaveLength(1);+ expect(posted[0].url).toBe('https://queue.fal.run/fal-ai/kling-video/v3/pro/image-to-video');+ expect(posted[0].body).toEqual({+ prompt: 'waves roll in', negative_prompt: 'text', start_image_url: expect.stringMatching(/^data:image\/png;base64,/),+ duration: '8', generate_audio: false,+ });+ const [entry] = await loadHistory();+ // 8s (the covering length) × $0.112/s audio off.+ expect(entry).toMatchObject({ modelId: 'fal:fal-ai/kling-video/v3/pro/image-to-video', duration: 8, generateAudio: false, estimatedCostUsd: 0.896 });+ });++ it('refuses a start-frame-only model without a frame before submitting anything', async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+ await expect(fal.generateVideo({ apiKey: 'test-key', modelId: 'fal-ai/veo3.1/fast/image-to-video', prompt: 'a fox' }))+ .rejects.toMatchObject({ status: 400, code: 'VALIDATION_ERROR' });+ expect(fetchMock).not.toHaveBeenCalled();+ });+it('submits, polls to completion, downloads the result, and finalizes history', async () => {const requestId = 'req-123';const statusUrl = `https://queue.fal.run/fal-ai/x/requests/${requestId}/status`;@@ -164,6 +207,8 @@ describe('videoGen/fal — generateVideo', () => {expect(history[0].id).toBe(job.jobId);expect(history[0].modelId).toBe('fal:fal-ai/x');+ // An uncurated id keeps the legacy body and cannot be priced.+ expect(history[0].estimatedCostUsd).toBeNull();});it('derives aspect_ratio from width/height when none is supplied explicitly', async () => {diff --git a/server/services/videoGen/hostedSubmission.js b/server/services/videoGen/hostedSubmission.jsindex 88b2e3c470..9615208c79 100644--- a/server/services/videoGen/hostedSubmission.js+++ b/server/services/videoGen/hostedSubmission.js@@ -28,12 +28,17 @@ export const HOSTED_VIDEO_SUBMISSIONS = {}),errorCode: 'FAL_NOT_CONFIGURED',errorMessage: 'No fal.ai API key configured — set it in Settings → Video Gen (or the FAL_KEY env var) first',+ // The model, resolution and audio flag are resolved against the curated+ // catalog by videoGen/fal.js (an unsupported resolution falls back to the+ // model's default there); provider audio is off unless asked for.buildParams: (body) => ({modelId: body.falModelId,aspectRatio: body.visualConditioning?.render?.parameters?.aspectRatio,width: body.width,height: body.height,duration: body.falDuration,+ ...(body.falResolution ? { resolution: body.falResolution } : {}),+ ...(body.falGenerateAudio === true ? { generateAudio: true } : {}),}),},[VIDEO_GEN_MODE.REACTOR]: {diff --git a/server/services/videoGen/submitJob.js b/server/services/videoGen/submitJob.jsindex cfcd7215e3..2590f855ff 100644--- a/server/services/videoGen/submitJob.js+++ b/server/services/videoGen/submitJob.js@@ -174,6 +174,7 @@ const submitValidatedVideoGenJob = async (body, uploads) => {backend,sourceImagePath: prepared.sourceImagePath,mode: body.mode,+ resolution: body.falResolution,}).catch(async (error) => {await cleanupStaged();throw error;@@ -185,6 +186,10 @@ const submitValidatedVideoGenJob = async (body, uploads) => {// would contradict it, so none is sent.duration: undefined,audioFilePath: performance.audioFilePath,+ // The lip-sync route's own output resolution (a cutaway resolution pin+ // names another model's alphabet, so the performance plan resolves it).+ resolution: performance.resolution,+ generateAudio: undefined,lipSync: { enableTranscription: performance.enableTranscription },shotInstruction: performance.shotInstruction,} : null;diff --git a/server/services/videoGen/submitJob.test.js b/server/services/videoGen/submitJob.test.jsindex 235500a880..6f913e683d 100644--- a/server/services/videoGen/submitJob.test.js+++ b/server/services/videoGen/submitJob.test.js@@ -203,20 +203,26 @@ describe('submitVideoGenJob', () => {mocks.prepareVideoGenParams.mockResolvedValue(falPrepared());mocks.preparePerformanceShot.mockResolvedValue({audioFilePath: '/example/uploads/mv-performance-1.wav', shotInstruction,- modelId: 'minimax/h3-max/lip-sync/image-to-video', enableTranscription: true,+ modelId: 'minimax/h3-max/lip-sync/image-to-video', resolution: '1080P', enableTranscription: true,});- await submitVideoGenJob({ prompt: 'singer', backend: 'fal', falDuration: 6, musicVideo, mode: 'image' }, {});+ // A cutaway model/resolution pin and an audio request ride the same body;+ // the performance plan's lip-sync model and resolution replace them.+ await submitVideoGenJob({+ prompt: 'singer', backend: 'fal', falDuration: 6, falModelId: 'minimax/h3-max/image-to-video',+ falResolution: '1080p', falGenerateAudio: true, musicVideo, mode: 'image',+ }, {});expect(mocks.preparePerformanceShot).toHaveBeenCalledWith({- musicVideo, backend: 'fal', sourceImagePath: '/example/images/frame.png', mode: 'image',+ musicVideo, backend: 'fal', sourceImagePath: '/example/images/frame.png', mode: 'image', resolution: '1080p',});const { params } = mocks.enqueueJob.mock.calls[0][0];expect(params).toMatchObject({- mode: 'fal', modelId: 'minimax/h3-max/lip-sync/image-to-video',+ mode: 'fal', modelId: 'minimax/h3-max/lip-sync/image-to-video', resolution: '1080P',audioFilePath: '/example/uploads/mv-performance-1.wav',lipSync: { enableTranscription: true }, shotInstruction, musicVideo,});expect(params.duration).toBeUndefined();+ expect(params.generateAudio).toBeUndefined();});it('refuses a performance shot the backend cannot render and releases what was staged', async () => {