Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: honor Reactor and fal pins in Creative Director renders (#6543)

[._.]/ Adam Eivyb694e1429d5a
diff --git a/server/services/creative/tools/media.js b/server/services/creative/tools/media.js
index b0b91cde94..d33b999038 100644
--- a/server/services/creative/tools/media.js
+++ b/server/services/creative/tools/media.js
@@ -11,8 +11,8 @@ import { getSettings } from '../../settings.js';
import { IMAGE_GEN_MODE, resolveQueueImageMode } from '../../imageGen/modes.js';
import { renderTargetDefaults, resolveRenderTargetConfig } from '../../imageGen/cloudProviderConfig.js';
import { RENDER_TARGET } from '../../../lib/renderTargets.js';
-import { VIDEO_GEN_MODE, VIDEO_GEN_MODES } from '../../videoGen/modes.js';
-import { grokVideoJobParams, resolveVideoBackendPin } from '../../videoGen/backendPin.js';
+import { CLOUD_VIDEO_GEN_MODES } from '../../videoGen/modes.js';
+import { videoBackendJobParams, resolveVideoBackendPin } from '../../videoGen/backendPin.js';
import { getDefaultVideoModelId, getVideoModels } from '../../../lib/mediaModels.js';
import { COST_RENDER, resolveOwner } from './shared.js';
@@ -251,42 +251,9 @@ async function enforceRenderBackendPin(kind, params, project) {
// videoGen/backendPin.js, so the two enqueue surfaces resolve identically.
const videoPin = resolveVideoBackendPin(project, settings);
if (!videoPin.pinned) return params;
- if (videoPin.mode !== VIDEO_GEN_MODE.GROK) {
- // Local video: `params.mode` is the t2v/i2v SEMANTIC for this lane (see
- // videoGen/modes.js), so a local pin must NOT stamp the backend name over
- // it — overwriting a real semantic ('fflf', 'a2v', 'extend', an IC-LoRA id)
- // would silently drop the caller's keyframes/audio.
- //
- // But the backend discriminator and the semantic SHARE this one key, so a
- // planner-authored BACKEND token has to go: 'grok' would dispatch to grok
- // in defiance of the pin (and defeat the grok-disabled fallback), and
- // 'local' is worse than useless — local.js treats an unrecognized non-empty
- // mode as plain text-to-video, so it would silently ignore the step's
- // sourceImagePath/keyframes. Dropping the key entirely is the correct
- // repair for both: an unset mode makes local.js INFER the semantic from
- // keyframes → sourceImagePath → text.
- const base = VIDEO_GEN_MODES.includes(params?.mode)
- ? (({ mode: _backendToken, ...rest }) => rest)(params)
- : (params || {});
- // The user's pinned model wins over the planner's freehand guess — that
- // asymmetry is the whole point of a pin. The project pin's model wins
- // over the target default's (same precedence as the mode ladder); local
- // is the only video backend that consumes a model id, so no cross-
- // provider leak guard is needed here.
- return videoPin.modelId ? { ...base, modelId: videoPin.modelId } : base;
- }
- // Clip length crosses a contract boundary into the grok lane (see
- // grokVideoJobParams). Prefer an explicit `duration` if some caller already
- // set one; else the step's `durationSeconds` (what the planner writes and
- // what enforceVideoRenderPreset reconciles); else the project's target.
- const requestedSeconds = params?.duration ?? params?.durationSeconds ?? project?.targetDurationSeconds;
- return {
- ...params,
- ...grokVideoJobParams(settings, {
- sourceImagePath: params?.sourceImagePath,
- durationSeconds: requestedSeconds,
- }),
- };
+ return videoBackendJobParams(settings, videoPin, params, {
+ durationSeconds: project?.targetDurationSeconds,
+ });
}
const pin = project?.renderBackend?.[kind];
@@ -364,7 +331,7 @@ const mediaTool = (kind, label) => ({
// then happily ship a job the peer renders with audio; a dropped
// `negativePrompt` just silently changes the render.
if (kind === 'video'
- && params?.mode !== VIDEO_GEN_MODE.GROK
+ && !CLOUD_VIDEO_GEN_MODES.includes(params?.mode)
&& !(await hasConfiguredMediaRoute('video'))) {
params = reconcileVideoParamsWithModel(params, project);
}
diff --git a/server/services/creative/tools/media.test.js b/server/services/creative/tools/media.test.js
index c590342d48..c2608f1aba 100644
--- a/server/services/creative/tools/media.test.js
+++ b/server/services/creative/tools/media.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// Mock only what the media tools reach for. The queue is the observable
// boundary — every assertion here is about the params that land on it, because
@@ -48,6 +48,8 @@ beforeEach(() => {
getCommissionMusicContextForProject.mockResolvedValue(null);
});
+afterEach(() => vi.unstubAllEnvs());
+
describe('model-aware autonomous video controls', () => {
it('uses the same H3 options as Video Gen and drops controls its UI disables', () => {
const params = reconcileVideoParamsWithModel({
@@ -301,7 +303,7 @@ describe('render-backend pin — video (#3135)', () => {
getSettings.mockResolvedValue({ imageGen: {} });
getProject.mockResolvedValue(projectWithPin({ video: { mode: 'local' } }));
- for (const backendToken of ['grok', 'local']) {
+ for (const backendToken of ['grok', 'local', 'fal', 'reactor']) {
await run('media_enqueueVideoJob', { prompt: 'p', mode: backendToken, sourceImagePath: '/tmp/f.png' }, { projectId: 'cd-1' });
expect(enqueued().params).toEqual({ prompt: 'p', sourceImagePath: '/tmp/f.png' });
}
@@ -563,3 +565,88 @@ describe('routed video keeps the controls its guard inspects (#4348)', () => {
expect(enqueued().params.disableAudio).toBe(true);
});
});
+
+
+describe('cloud video pins reach the queue without local model reconciliation', () => {
+ const cloudProject = (video) => ({
+ ...projectWithPin({ video }),
+ aspectRatio: '9:16', quality: 'standard', targetDurationSeconds: 8,
+ modelId: 'local-project-model',
+ });
+
+ it('preserves Reactor duration, portrait canvas and starting frame despite planner backend guesses', async () => {
+ getSettings.mockResolvedValue({
+ videoGen: { reactor: { apiKey: 'example-test-key' } },
+ renderDefaults: { 'creative-agent': { videoModel: 'local-default-model' } },
+ });
+ getProject.mockResolvedValue(cloudProject({ mode: 'reactor' }));
+ await run('media_enqueueVideoJob', {
+ prompt: 'An example lighthouse', mode: 'grok', modelId: 'local-planner-model',
+ sourceImagePath: '/tmp/example-frame.png', durationSeconds: 8,
+ }, { projectId: 'cd-1' });
+
+ const { params } = enqueued();
+ expect(params).toMatchObject({
+ mode: 'reactor', videoMode: 'image', seconds: 8, aspect: '9:16',
+ sourceImagePath: '/tmp/example-frame.png',
+ });
+ expect(params.height).toBeGreaterThan(params.width);
+ for (const key of ['modelId', 'pythonPath', 'numFrames', 'fps', 'steps', 'apiKey', 'settings']) {
+ expect(params).not.toHaveProperty(key);
+ }
+ });
+
+ it('preserves Reactor native continuation parameters', async () => {
+ getSettings.mockResolvedValue({ videoGen: { reactor: { apiKey: 'example-test-key' } } });
+ getProject.mockResolvedValue(projectWithPin({ video: { mode: 'reactor' } }));
+ await run('media_enqueueVideoJob', {
+ prompt: 'Continue the example shot', continueFromClipId: 'example-clip', seconds: 9,
+ aspect: '4:3', seed: 0,
+ }, { projectId: 'cd-1' });
+ expect(enqueued().params).toMatchObject({ mode: 'reactor', continueFromClipId: 'example-clip', seconds: 9, aspect: '4:3', seed: 0 });
+ });
+
+ it('uses the fal endpoint pin without borrowing a local model or dropping the clip duration', async () => {
+ getSettings.mockResolvedValue({
+ videoGen: { fal: { apiKey: 'example-test-key' } },
+ renderDefaults: { 'creative-agent': { videoModel: 'local-default-model' } },
+ });
+ getProject.mockResolvedValue(cloudProject({ mode: 'fal', modelId: 'fal-ai/example/text-to-video' }));
+ await run('media_enqueueVideoJob', { prompt: 'An example scene', modelId: 'local-planner-model' }, { projectId: 'cd-1' });
+ expect(enqueued().params).toMatchObject({ mode: 'fal', videoMode: 'text', modelId: 'fal-ai/example/text-to-video', duration: 8 });
+ expect(enqueued().params).not.toHaveProperty('numFrames');
+ });
+
+ it('lets fal choose its image model when only the backend is pinned globally', async () => {
+ getSettings.mockResolvedValue({
+ videoGen: { mode: 'fal', fal: { apiKey: 'example-test-key' } },
+ renderDefaults: { 'creative-agent': { videoModel: 'local-default-model' } },
+ });
+ getProject.mockResolvedValue(cloudProject(null));
+ await run('media_enqueueVideoJob', { prompt: 'An example scene', modelId: 'local-planner-model', sourceImagePath: '/tmp/example.png' }, { projectId: 'cd-1' });
+ expect(enqueued().params).toMatchObject({ mode: 'fal', videoMode: 'image', duration: 8 });
+ expect(enqueued().params).not.toHaveProperty('modelId');
+ });
+
+ it('does not reuse a fal endpoint model when a legacy unavailable pin falls back to local', async () => {
+ vi.stubEnv('FAL_KEY', '');
+ getSettings.mockResolvedValue({ renderDefaults: { 'creative-agent': { videoModel: 'example-local-model' } } });
+ getProject.mockResolvedValue(projectWithPin({ video: { mode: 'fal', modelId: 'fal-ai/example/text-to-video' } }));
+ await run('media_enqueueVideoJob', { prompt: 'An example scene', mode: 'fal' }, { projectId: 'cd-1' });
+ expect(enqueued().params).toEqual({ prompt: 'An example scene', modelId: 'example-local-model' });
+ });
+
+ it.each([
+ { mode: 'fflf', keyframes: [{ frame: 0, filename: 'example.png' }] },
+ { mode: 'reactor', videoMode: 'a2v', audioFilePath: '/tmp/example.wav' },
+ { mode: 'text', disableAudio: true },
+ { mode: 'text', batchSize: 2 },
+ { mode: 'image', sourceImagePath: '/tmp/example.png', loras: [{ path: '/tmp/example.safetensors', scale: 1 }] },
+ ])('rejects unsupported cloud conditioning before enqueue: %j', async (params) => {
+ getSettings.mockResolvedValue({ videoGen: { reactor: { apiKey: 'example-test-key' } } });
+ getProject.mockResolvedValue(cloudProject({ mode: 'reactor' }));
+ await expect(run('media_enqueueVideoJob', { prompt: 'An example scene', ...params }, { projectId: 'cd-1' }))
+ .rejects.toMatchObject({ code: 'VIDEO_BACKEND_INPUT_UNSUPPORTED' });
+ expect(enqueueJob).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/creativeDirector/sceneRunner.backend.test.js b/server/services/creativeDirector/sceneRunner.backend.test.js
index 9d8f9d1096..1c6af3db66 100644
--- a/server/services/creativeDirector/sceneRunner.backend.test.js
+++ b/server/services/creativeDirector/sceneRunner.backend.test.js
@@ -41,10 +41,16 @@ vi.mock('../videoGen/local.js', () => ({
vi.mock('./completionHook.js', () => ({ advanceAfterSceneSettled: vi.fn(async () => {}) }));
vi.mock('../../lib/ffmpeg.js', () => ({ verifyVideoPlayable: vi.fn(async () => ({ ok: true })) }));
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => ({
+ ...await importOriginal(),
+ resolveGalleryImage: vi.fn(() => null),
+}));
+
import { runSceneRender } from './sceneRunner.js';
import { enqueueJob } from '../mediaJobQueue/index.js';
import { getSettings } from '../settings.js';
-import { updateScene } from './local.js';
+import { updateScene, getProject } from './local.js';
+import { resolveGalleryImage } from '../../lib/fileUtils.js';
const LOCAL_READY = { imageGen: { local: { pythonPath: '/usr/bin/python3' } } };
const GROK_READY = { imageGen: { grok: { enabled: true, grokPath: '/usr/local/bin/grok' } } };
@@ -62,7 +68,11 @@ const scene = (over = {}) => ({
const enqueuedParams = () => enqueueJob.mock.calls[0][0].params;
-beforeEach(() => vi.clearAllMocks());
+beforeEach(() => {
+ vi.clearAllMocks();
+ getProject.mockResolvedValue(null);
+ resolveGalleryImage.mockReturnValue(null);
+});
describe('runSceneRender — unpinned (local) behavior is unchanged', () => {
it('builds local MLX params when nothing is pinned', async () => {
@@ -180,3 +190,48 @@ describe('runSceneRender — local model pin', () => {
expect(enqueuedParams().modelId).toBe('target-default-model');
});
});
+
+
+describe('runSceneRender — Reactor and fal pins', () => {
+ it('queues a Reactor starting-frame scene without local Python or local model knobs', async () => {
+ getSettings.mockResolvedValue({ videoGen: { reactor: { apiKey: 'example-test-key' } } });
+ resolveGalleryImage.mockReturnValue('/tmp/example-frame.png');
+ const jobId = await runSceneRender(
+ project({ aspectRatio: '9:16', renderBackend: { video: { mode: 'reactor' } } }),
+ scene({ sourceImageFile: 'example-frame.png' }),
+ );
+ expect(jobId).toBe('job-1');
+ expect(enqueuedParams()).toMatchObject({
+ mode: 'reactor', videoMode: 'image', seconds: 8, aspect: '9:16',
+ sourceImagePath: '/tmp/example-frame.png',
+ creativeDirector: { projectId: 'proj-1', sceneId: 'scene-1' },
+ });
+ for (const key of ['pythonPath', 'modelId', 'numFrames', 'steps', 'apiKey', 'settings']) {
+ expect(enqueuedParams()).not.toHaveProperty(key);
+ }
+ });
+
+ it('queues fal with its pinned endpoint and scene duration when no local Python exists', async () => {
+ getSettings.mockResolvedValue({ videoGen: { fal: { apiKey: 'example-test-key' } } });
+ const jobId = await runSceneRender(
+ project({ renderBackend: { video: { mode: 'fal', modelId: 'fal-ai/example/text-to-video' } } }),
+ scene(),
+ );
+ expect(jobId).toBe('job-1');
+ expect(enqueuedParams()).toMatchObject({ mode: 'fal', videoMode: 'text', duration: 8, modelId: 'fal-ai/example/text-to-video' });
+ expect(enqueuedParams()).not.toHaveProperty('pythonPath');
+ expect(enqueuedParams()).not.toHaveProperty('numFrames');
+ });
+
+ it('fails unsupported output once with a repair message instead of retrying an impossible render', async () => {
+ getSettings.mockResolvedValue({ videoGen: { reactor: { apiKey: 'example-test-key' } } });
+ const selected = project({ disableAudio: true, renderBackend: { video: { mode: 'reactor' } }, treatment: { scenes: [scene()] } });
+ getProject.mockResolvedValue(selected);
+ expect(await runSceneRender(selected, scene())).toBeNull();
+ expect(enqueueJob).not.toHaveBeenCalled();
+ expect(updateScene).toHaveBeenLastCalledWith('proj-1', 'scene-1', expect.objectContaining({
+ status: 'failed', evaluation: expect.objectContaining({ notes: expect.stringContaining('audio-disabled output') }),
+ }));
+ expect(updateScene.mock.calls.filter(([, , patch]) => patch.status === 'rendering')).toHaveLength(1);
+ });
+});
diff --git a/server/services/creativeDirector/sceneRunner.js b/server/services/creativeDirector/sceneRunner.js
index a01de638f7..241524b7be 100644
--- a/server/services/creativeDirector/sceneRunner.js
+++ b/server/services/creativeDirector/sceneRunner.js
@@ -35,7 +35,7 @@ import { presetToRenderParams } from '../../lib/creativeDirectorPresets.js';
import { CD_MAX_SCENE_RETRIES } from '../creativeDirectorPrompts.js';
import { extractLastFrame, sampleEvaluationFrames } from '../videoGen/local.js';
import { VIDEO_GEN_MODE } from '../videoGen/modes.js';
-import { grokVideoJobParams, resolveVideoBackendPin } from '../videoGen/backendPin.js';
+import { videoBackendJobParams, resolveVideoBackendPin } from '../videoGen/backendPin.js';
import { mediaJobEvents } from '../mediaJobQueue/index.js';
import { enqueueUnattendedMediaJob, hasConfiguredMediaRoute } from '../federatedMedia/defaultRouting.js';
import { getSettings } from '../settings.js';
@@ -82,7 +82,7 @@ export async function runSceneRender(project, scene) {
// to Grok still rendered every scene on the MLX runtime, and the pythonPath
// guard below failed the whole project even when Grok was the pinned backend.
const videoPin = resolveVideoBackendPin(project, settings);
- const useGrok = videoPin.mode === VIDEO_GEN_MODE.GROK;
+ const useLocal = videoPin.mode === VIDEO_GEN_MODE.LOCAL;
const pythonPath = settings.imageGen?.local?.pythonPath || null;
// Fail fast when local video gen isn't configured. Without this guard the
@@ -91,12 +91,12 @@ export async function runSceneRender(project, scene) {
// — none of which can ever succeed without operator intervention. Mark
// the scene failed and let advanceAfterSceneSettled flag the project so
// the user can configure pythonPath and Resume from the UI. Only the local
- // lane needs it — a Grok render shells out to the CLI and never touches
- // Python (the media-job queue gates its own pythonPath check the same way).
+ // lane needs this runtime — cloud backends provision/use their own execution
+ // path (the media-job queue gates local readiness the same way).
// A routed video render never touches local Python — on a machine that
// routes precisely BECAUSE it cannot render locally, this gate would fail
// every scene the provider was going to handle (#4348).
- if (!useGrok && !pythonPath && !(await hasConfiguredMediaRoute('video'))) {
+ if (useLocal && !pythonPath && !(await hasConfiguredMediaRoute('video'))) {
// A pin that named a cloud backend but resolved to local means the ladder
// degraded it (the backend's `enabled` toggle is off). Say so — otherwise
// the user reads "configure Python" on a project they explicitly pinned to
@@ -209,24 +209,13 @@ export async function runSceneRender(project, scene) {
height: renderParams.height,
sourceImagePath,
};
- const params = useGrok
- ? {
- ...shared,
- // Scene duration is authored in the local lane's continuous seconds;
- // grokVideoJobParams snaps it up to a length Grok actually delivers.
- // Geometry rides along in `shared` — grok.js reads it to derive the
- // project's aspect ratio for the base image.
- ...grokVideoJobParams(settings, { sourceImagePath, durationSeconds: scene.durationSeconds }),
- creativeDirector: { projectId: project.id, sceneId: scene.sceneId },
- }
- : {
- ...shared,
+ const sceneParams = {
+ ...shared,
+ creativeDirector: { projectId: project.id, sceneId: scene.sceneId },
+ disableAudio: project.disableAudio === true,
+ ...(useLocal ? {
pythonPath,
- // A pinned local model (the commission's `generation.videoModelId`, or the
- // creative-agent render default) wins over the project's own modelId —
- // the project's is the creation-time default, the pin is the user's
- // explicit later choice.
- modelId: videoPin.modelId || project.modelId,
+ modelId: project.modelId,
numFrames: renderParams.numFrames,
fps: renderParams.fps,
steps: renderParams.steps,
@@ -234,16 +223,8 @@ export async function runSceneRender(project, scene) {
tiling: 'auto',
mode: sourceImagePath ? 'image' : 'text',
imageStrength: effectiveImageStrength,
- // Smoke-test / dev knob: skips the mlx_video audio-gen pass to cut
- // wall-clock per scene roughly in half. Project-level so every scene
- // in the project inherits the same setting.
- disableAudio: project.disableAudio === true,
- creativeDirector: { projectId: project.id, sceneId: scene.sceneId },
- };
-
- if (useGrok) {
- console.log(`☁️ CD scene ${scene.sceneId} rendering on grok (${params.duration}s clip)`);
- }
+ } : {}),
+ };
const owner = `cd:${project.id}:${scene.sceneId}`;
// The scene is ALREADY persisted as 'rendering' by this point, and the
@@ -254,10 +235,13 @@ export async function runSceneRender(project, scene) {
// advance the project. Settle it through the normal failure path instead.
let jobId;
try {
+ const params = videoBackendJobParams(settings, videoPin, sceneParams, { durationSeconds: scene.durationSeconds });
({ jobId } = await enqueueUnattendedMediaJob({ kind: 'video', params, owner }));
} catch (error) {
console.error(`❌ CD scene ${scene.sceneId}: could not queue the render: ${error.message}`);
- await handleRenderFailed(project.id, scene.sceneId, error.message || 'could not queue the render');
+ await handleRenderFailed(project.id, scene.sceneId, error.message || 'could not queue the render', {
+ retry: error.code !== 'VIDEO_BACKEND_INPUT_UNSUPPORTED' && error.code !== 'VIDEO_BACKEND_UNSUPPORTED',
+ });
return null;
}
@@ -453,13 +437,13 @@ async function handleRenderCanceled(projectId, sceneId) {
await advanceAfterSceneSettled(projectId);
}
-async function handleRenderFailed(projectId, sceneId, errorMsg) {
+async function handleRenderFailed(projectId, sceneId, errorMsg, { retry = true } = {}) {
const fresh = await getProject(projectId);
if (!fresh) return;
const scene = fresh.treatment?.scenes?.find((s) => s.sceneId === sceneId);
if (!scene) return;
const nextRetry = (scene.retryCount || 0) + 1;
- if (nextRetry <= CD_MAX_SCENE_RETRIES) {
+ if (retry && nextRetry <= CD_MAX_SCENE_RETRIES) {
console.log(`🔁 CD scene ${sceneId} render failed (${errorMsg}) — retry ${nextRetry}/${CD_MAX_SCENE_RETRIES}`);
await updateScene(projectId, sceneId, { status: 'pending', retryCount: nextRetry });
const updated = { ...scene, retryCount: nextRetry };
diff --git a/server/services/videoGen/backendPin.js b/server/services/videoGen/backendPin.js
index 2c9e491925..608b0d7a45 100644
--- a/server/services/videoGen/backendPin.js
+++ b/server/services/videoGen/backendPin.js
@@ -20,17 +20,19 @@
* scene on the local MLX runtime, and an install with no `imageGen.local
* .pythonPath` failed the whole project up front even though Grok was
* configured, enabled, and explicitly pinned. This module is the ONE place the
- * resolution ladder and the Grok param shape live, so the two surfaces cannot
+ * resolution ladder and backend job shapes live, so the two surfaces cannot
* drift apart again.
*
- * Both helpers take `settings` rather than reading them, so the callers keep
+ * The helpers take `settings` rather than reading them, so the callers keep
* their existing single settings read per enqueue.
*/
import { RENDER_TARGET, normalizeRenderPinValue } from '../../lib/renderTargets.js';
import { nearestGrokDuration } from '../../lib/grokVideoClip.js';
+import { nearestReactorAspect } from '../../lib/reactorVideoClip.js';
+import { ServerError } from '../../lib/errorHandler.js';
import { renderTargetDefaults } from '../imageGen/cloudProviderConfig.js';
-import { VIDEO_GEN_MODE, resolveVideoMode, hasVideoPin } from './modes.js';
+import { VIDEO_GEN_MODE, VIDEO_GEN_MODES, resolveVideoMode, hasVideoPin } from './modes.js';
/**
* Resolve the video backend for a CD project through the pin ladder: the
@@ -45,11 +47,9 @@ import { VIDEO_GEN_MODE, resolveVideoMode, hasVideoPin } from './modes.js';
* nothing is pinned" contract (enforceRenderBackendPin) return the caller's
* params untouched instead of re-deriving them.
*
- * `modelId` is the pinned LOCAL model: the project pin's own id wins over the
- * target default's, matching the mode ladder's precedence. Local is the only
- * video backend with a model knob (the cloud CLIs pick their own), so there is
- * no cross-provider leak to guard against — but callers must still only apply
- * it on the local branch.
+ * `modelId` belongs to the resolved backend: local catalog pins follow the
+ * existing project → target precedence; fal endpoint pins come only from an
+ * explicit fal project pin. Grok and Reactor use their renderer's own model.
*/
export function resolveVideoBackendPin(project, settings, { target = RENDER_TARGET.CREATIVE_AGENT } = {}) {
const raw = project?.renderBackend?.video || null;
@@ -61,7 +61,17 @@ export function resolveVideoBackendPin(project, settings, { target = RENDER_TARG
// it), but a hand-made or peer-synced project can carry the sentinel.
const mode = normalizeRenderPinValue(raw?.mode);
const targetDefaults = renderTargetDefaults(settings, target);
- const modelId = normalizeRenderPinValue(raw?.modelId) || targetDefaults.videoModel || null;
+ const resolvedMode = resolveVideoMode(mode, settings, { target });
+ // The target videoModel and project.modelId are local catalog choices. fal
+ // accepts an endpoint model only from its own explicit project pin; Reactor
+ // and Grok choose their models in the renderer. A lapsed fal pin must not
+ // pass its endpoint id into the legacy local fallback either.
+ const cloudModelPin = mode === VIDEO_GEN_MODE.FAL || mode === VIDEO_GEN_MODE.REACTOR;
+ const localModelId = (!cloudModelPin && normalizeRenderPinValue(raw?.modelId))
+ || targetDefaults.videoModel || null;
+ const modelId = resolvedMode === VIDEO_GEN_MODE.LOCAL ? localModelId
+ : resolvedMode === VIDEO_GEN_MODE.FAL && mode === VIDEO_GEN_MODE.FAL
+ ? normalizeRenderPinValue(raw?.modelId) : null;
return {
// A model pin counts as a pin even with no mode beside it. Naming a local
// video model IS a configured choice, and the resolved mode for an
@@ -78,7 +88,7 @@ export function resolveVideoBackendPin(project, settings, { target = RENDER_TARG
// degraded an unusable pin, and only the caller has the context to decide
// whether that's worth reporting.
requested: mode,
- mode: resolveVideoMode(mode, settings, { target }),
+ mode: resolvedMode,
modelId,
};
}
@@ -117,3 +127,81 @@ export function grokVideoJobParams(settings, { sourceImagePath = null, durationS
...(grok.aspectRatio ? { aspectRatio: grok.aspectRatio } : {}),
};
}
+
+/**
+ * Apply a resolved creative video pin to the queue's renderer contract. Both
+ * planner tools and direct scenes use this boundary so cloud backend tokens
+ * cannot fall into local text/image mode or local-model reconciliation.
+ *
+ * Local params keep their semantic mode and conditioning intact. Cloud workers
+ * accept a first frame, not local keyframe/audio/LoRA machinery; refuse those
+ * requests before enqueue instead of producing an unconditioned paid clip.
+ * Backend workers retain their own duration/prompt validation before submission
+ * (in particular Reactor's shared short-clip limits, never a project-length clip).
+ */
+export function videoBackendJobParams(settings, pin, params = {}, { durationSeconds } = {}) {
+ if (pin.mode === VIDEO_GEN_MODE.LOCAL) {
+ const base = VIDEO_GEN_MODES.includes(params.mode)
+ ? (({ mode: _backend, ...rest }) => rest)(params)
+ : params;
+ return pin.modelId ? { ...base, modelId: pin.modelId } : base;
+ }
+
+ const semantic = VIDEO_GEN_MODES.includes(params.mode) ? params.videoMode : params.mode;
+ const hasInput = (value) => Array.isArray(value) ? value.length > 0 : Boolean(value);
+ const unsupported = [
+ 'keyframes', 'lastImagePath', 'lastImageFile', 'audioFilePath', 'audioFile',
+ 'extendFromVideoId', 'extendFromVideoPath', 'icReferencePaths',
+ 'icReferenceVideoIds', 'icReferenceImageFiles', 'loras', 'loraPaths', 'loraFilenames',
+ ].filter((key) => hasInput(params[key]));
+ if (semantic && semantic !== 'text' && semantic !== 'image') unsupported.push(`mode ${semantic}`);
+ if (Number(params.chunks) > 1) unsupported.push('chained chunks');
+ if (Number(params.batchSize) > 1) unsupported.push('batched clips');
+ if (params.disableAudio === true) unsupported.push('audio-disabled output');
+ if (params.i2vReferenceMode && params.i2vReferenceMode !== 'anchor') unsupported.push('inspire reference mode');
+ if (params.continueFromClipId && pin.mode !== VIDEO_GEN_MODE.REACTOR) unsupported.push('Reactor clip continuation');
+ if (unsupported.length) {
+ throw new ServerError(
+ `The ${pin.mode} video backend cannot honor ${unsupported.join(', ')}. Remove those inputs or choose a compatible local render backend.`,
+ { status: 400, code: 'VIDEO_BACKEND_INPUT_UNSUPPORTED' },
+ );
+ }
+
+ // Keep attribution, geometry and source references, but never carry local
+ // runtime/model knobs into a paid renderer with a different model namespace.
+ const {
+ modelId: _model, pythonPath: _python, numFrames: _frames, fps: _fps,
+ steps: _steps, guidanceScale: _guidance, tiling: _tiling,
+ imageStrength: _strength, disableAudio: _audio, ...base
+ } = params;
+ const sourceImagePath = params.sourceImagePath || null;
+ const duration = params.duration ?? params.durationSeconds ?? durationSeconds;
+ if (pin.mode === VIDEO_GEN_MODE.GROK) {
+ return { ...base, ...grokVideoJobParams(settings, { sourceImagePath, durationSeconds: duration }) };
+ }
+ if (pin.mode === VIDEO_GEN_MODE.FAL) {
+ return {
+ ...base,
+ mode: VIDEO_GEN_MODE.FAL,
+ videoMode: sourceImagePath ? 'image' : 'text',
+ ...(pin.modelId ? { modelId: pin.modelId } : {}),
+ ...(duration != null ? { duration } : {}),
+ };
+ }
+ if (pin.mode === VIDEO_GEN_MODE.REACTOR) {
+ const seconds = params.seconds ?? duration;
+ const aspect = Number(params.width) > 0 && Number(params.height) > 0
+ ? nearestReactorAspect(params.width, params.height)
+ : params.aspect ?? params.aspectRatio;
+ return {
+ ...base,
+ mode: VIDEO_GEN_MODE.REACTOR,
+ videoMode: sourceImagePath ? 'image' : 'text',
+ ...(seconds != null ? { seconds } : {}),
+ ...(aspect ? { aspect } : {}),
+ };
+ }
+ throw new ServerError('Unknown video backend; choose a configured render backend.', {
+ status: 400, code: 'VIDEO_BACKEND_UNSUPPORTED',
+ });
+}