Skip to content

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

feat([issue-3231]): video render parity — settings.videoGen.mode pin, per-target videoMode, Music Video image lane

[._.]/ Adam Eivy0c9bc3ad4b42
diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsx
index 666053cb2e..9b85eb9ac2 100644
--- a/client/src/components/settings/ImageGenTab.jsx
+++ b/client/src/components/settings/ImageGenTab.jsx
@@ -22,7 +22,7 @@ import {
registerTool, updateTool, getToolsList,
saveHfToken, clearHfToken,
} from '../../services/api';
-import { isCloudCliMode, IMAGE_GEN_MODE, AGY_IMAGEGEN_DEFAULT_MODEL, AGY_IMAGEGEN_IMAGE_MODEL, CODEX_IMAGEGEN_DEFAULT_EFFORT, GROK_ASPECT_RATIOS, RENDER_TARGET_BACKEND_AUTO, RENDER_TARGET_OPTIONS, modeLabel, supportsCloudModelOverride } from '../../lib/imageGenBackends';
+import { isCloudCliMode, IMAGE_GEN_MODE, AGY_IMAGEGEN_DEFAULT_MODEL, AGY_IMAGEGEN_IMAGE_MODEL, CODEX_IMAGEGEN_DEFAULT_EFFORT, GROK_ASPECT_RATIOS, RENDER_TARGET_BACKEND_AUTO, RENDER_TARGET_OPTIONS, VIDEO_RENDER_MODES, modeLabel, supportsCloudModelOverride } from '../../lib/imageGenBackends';
import { resolveCleanersFromConfig } from '../../lib/imageCleaners';
import { useMediaJobSse } from '../../hooks/useMediaJobSse';
import { useAgyModels } from '../../hooks/useAgyModels';
@@ -104,6 +104,12 @@ export function ImageGenTab() {
// Per-surface render defaults (#3231) — `{ [target]: { imageMode, imageModel } }`.
// Only pinned entries are kept; an absent target means "auto".
const [renderDefaults, setRenderDefaults] = useState({});
+ // Install-wide video backend pin (`settings.videoGen.mode`, #3231 Phase 4).
+ // '' = no pin (local). The full loaded `videoGen` slice is kept so the save
+ // can round-trip sibling keys (defaultModelId) — the settings PUT replaces
+ // top-level slices wholesale.
+ const [videoGenMode, setVideoGenMode] = useState('');
+ const [videoGenSlice, setVideoGenSlice] = useState({});
const [sdapiUrl, setSdapiUrl] = useState('');
const [pythonPath, setPythonPath] = useState('');
const [exposeA1111, setExposeA1111] = useState(false);
@@ -166,6 +172,7 @@ export function ImageGenTab() {
cleanC2PAByMode: { external: true, local: true, codex: true, grok: false, agy: false },
denoiseByMode: { external: false, local: false, codex: false, grok: false, agy: false },
renderDefaultsJson: '{}',
+ videoGenMode: '',
});
const [status, setStatus] = useState(null);
@@ -223,11 +230,16 @@ export function ImageGenTab() {
Promise.all([getSettings({ silent: true }), getToolsList({ silent: true })])
.then(([s, tools]) => {
const ig = s?.imageGen || {};
- // Round-trip the FULL renderDefaults object (including videoMode /
- // videoModel keys this tab doesn't edit yet) — the server replaces the
- // top-level slice wholesale on save, so dropping unedited keys here
- // would erase them.
+ // Round-trip the FULL renderDefaults object (including videoModel keys
+ // this tab doesn't edit) — the server replaces the top-level slice
+ // wholesale on save, so dropping unedited keys here would erase them.
const rd = (s?.renderDefaults && typeof s.renderDefaults === 'object') ? s.renderDefaults : {};
+ // Video pin: keep the whole slice for round-trip; normalize the mode
+ // ('auto'/blank → '', i.e. no pin) for the select.
+ const vg = (s?.videoGen && typeof s.videoGen === 'object') ? s.videoGen : {};
+ const vgMode = (typeof vg.mode === 'string' && vg.mode.trim() && vg.mode !== RENDER_TARGET_BACKEND_AUTO)
+ ? vg.mode
+ : '';
const m = ig.mode || IMAGE_GEN_MODE.EXTERNAL;
const url = normalizeUrl(ig.external?.sdapiUrl || ig.sdapiUrl);
const py = ig.local?.pythonPath || '';
@@ -261,6 +273,8 @@ export function ImageGenTab() {
const dn = { codex: codexClean.denoise, grok: grokClean.denoise, agy: agyClean.denoise, local: localClean.denoise, external: externalClean.denoise };
setMode(m);
setRenderDefaults(rd);
+ setVideoGenMode(vgMode);
+ setVideoGenSlice(vg);
setSdapiUrl(url);
setPythonPath(py);
setExposeA1111(expose);
@@ -286,6 +300,7 @@ export function ImageGenTab() {
agyEnabled: ayEnabled, agyPath: ayPath, agyModel: ayModel,
cleanC2PAByMode: c2, denoiseByMode: dn,
renderDefaultsJson: JSON.stringify(rd),
+ videoGenMode: vgMode,
});
setToolRegistered(tools.some((t) => t.id === SDAPI_TOOL_ID));
setCodexToolRegistered(tools.some((t) => t.id === CODEX_TOOL_ID));
@@ -345,7 +360,8 @@ export function ImageGenTab() {
|| denoiseByMode.codex !== saved.denoiseByMode.codex
|| denoiseByMode.local !== saved.denoiseByMode.local
|| denoiseByMode.external !== saved.denoiseByMode.external
- || JSON.stringify(renderDefaults) !== saved.renderDefaultsJson;
+ || JSON.stringify(renderDefaults) !== saved.renderDefaultsJson
+ || videoGenMode !== saved.videoGenMode;
const handleSave = async () => {
setSaving(true);
@@ -388,6 +404,9 @@ export function ImageGenTab() {
(v) => typeof v === 'string' && v.trim() && v !== RENDER_TARGET_BACKEND_AUTO,
)),
),
+ // Install-wide video pin (#3231 Phase 4). Spread over the loaded slice so
+ // sibling keys (defaultModelId) survive the wholesale slice replace.
+ videoGen: { ...videoGenSlice, mode: videoGenMode || null },
};
try {
await updateSettings(patch, { silent: true });
@@ -403,10 +422,12 @@ export function ImageGenTab() {
agyEnabled, agyPath: ayPath || '', agyModel: ayModel || '',
cleanC2PAByMode, denoiseByMode,
renderDefaultsJson: JSON.stringify(patch.renderDefaults),
+ videoGenMode,
});
// Reflect the pruned no-op entries back into the editor state so the
// dirty check compares like against like after a save.
setRenderDefaults(patch.renderDefaults);
+ setVideoGenSlice(patch.videoGen);
if (cxParallel !== codexParallelLimit) {
setCodexParallelLimit(cxParallel);
setParallelLimitDraft(String(cxParallel));
@@ -670,14 +691,38 @@ export function ImageGenTab() {
backend that is disabled (or unconfigured) falls back to whatever that surface would
have used anyway — enable the backend on its own tab to make a pin take effect. A
model can be pinned for backends that accept one (Codex, Agy); Grok and Local pick
- their models elsewhere.
+ their models elsewhere. Surfaces that also render video get a video backend pin —
+ backend only, since Grok video has no model choice and local video models are picked
+ on the surface itself.
</p>
+ <div className="grid grid-cols-1 sm:grid-cols-[1fr_auto] gap-2 sm:items-center border border-port-border rounded-lg px-3 py-2 bg-port-bg/40">
+ <label htmlFor="video-default-mode" className="text-sm text-gray-300">
+ Default video backend
+ <span className="block text-xs text-gray-500 mt-0.5">
+ Used when a video render names no backend and its surface has no pin. Grok clips
+ render at 6s or 10s on xAI&rsquo;s fixed video backend.
+ </span>
+ </label>
+ <select
+ id="video-default-mode"
+ value={videoGenMode}
+ onChange={(e) => setVideoGenMode(e.target.value)}
+ className="bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent sm:w-44"
+ >
+ <option value="">Auto (Local)</option>
+ {VIDEO_RENDER_MODES.map((m) => (
+ <option key={m} value={m}>{modeLabel(m)}</option>
+ ))}
+ </select>
+ </div>
<div className="space-y-3">
- {RENDER_TARGET_OPTIONS.map(({ id, label }) => {
+ {RENDER_TARGET_OPTIONS.map(({ id, label, video }) => {
const entry = renderDefaults[id] || {};
const pinnedMode = entry.imageMode && entry.imageMode !== RENDER_TARGET_BACKEND_AUTO ? entry.imageMode : '';
+ const pinnedVideoMode = entry.videoMode && entry.videoMode !== RENDER_TARGET_BACKEND_AUTO ? entry.videoMode : '';
const modeSelectId = `render-default-mode-${id}`;
const modelInputId = `render-default-model-${id}`;
+ const videoSelectId = `render-default-video-${id}`;
const setPin = (key, value) => setRenderDefaults((rd) => {
const nextEntry = { ...(rd[id] || {}) };
if (value) nextEntry[key] = value; else delete nextEntry[key];
@@ -686,7 +731,7 @@ export function ImageGenTab() {
return next;
});
return (
- <div key={id} className="grid grid-cols-1 sm:grid-cols-[1fr_auto_auto] gap-2 sm:items-center border border-port-border rounded-lg px-3 py-2">
+ <div key={id} className={`grid grid-cols-1 ${video ? 'sm:grid-cols-[1fr_auto_auto_auto]' : 'sm:grid-cols-[1fr_auto_auto]'} gap-2 sm:items-center border border-port-border rounded-lg px-3 py-2`}>
<label htmlFor={modeSelectId} className="text-sm text-gray-300">{label}</label>
<select
id={modeSelectId}
@@ -719,6 +764,21 @@ export function ImageGenTab() {
className="bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent sm:w-52"
/>
) : <span className="hidden sm:block sm:w-52" />}
+ {video && (
+ <select
+ id={videoSelectId}
+ value={pinnedVideoMode}
+ onChange={(e) => setPin('videoMode', e.target.value || null)}
+ aria-label={`${label} video backend`}
+ title="Video backend for this surface — no model choice (Grok video has none; local video models are picked on the surface)"
+ className="bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent sm:w-44"
+ >
+ <option value="">Video: Auto</option>
+ {VIDEO_RENDER_MODES.map((m) => (
+ <option key={m} value={m}>Video: {modeLabel(m)}</option>
+ ))}
+ </select>
+ )}
</div>
);
})}
diff --git a/client/src/lib/imageGenBackends.js b/client/src/lib/imageGenBackends.js
index 11659abacb..a6a0c364b5 100644
--- a/client/src/lib/imageGenBackends.js
+++ b/client/src/lib/imageGenBackends.js
@@ -32,9 +32,14 @@ export const AGY_IMAGEGEN_IMAGE_MODEL = 'imagen-3.0-generate-002';
// Client mirror of the server's render-target alphabet
// (server/lib/renderTargets.js, #3231) — the surfaces whose default backend +
// model are pinnable via settings.renderDefaults. Only targets whose resolver
-// is LIVE are listed here (music-video ships with the Phase 4 video lane) —
-// showing a pin no resolver reads would be a control that silently does
-// nothing. Labels are the Settings-UI display names.
+// is LIVE are listed here — showing a pin no resolver reads would be a control
+// that silently does nothing. Labels are the Settings-UI display names.
+// `video: true` marks the targets whose VIDEO lane also consults
+// `renderDefaults[target].videoMode` (#3231 Phase 4): music-video (scene clips
+// + new-project backend seeding) and creative-agent (commission video steps).
+// Video pins are backend-only — grok video has no model knob
+// (supportsModelOverride: false) and local video models are picked on the
+// surface itself, so no video-model control is offered anywhere.
export const RENDER_TARGET_BACKEND_AUTO = 'auto';
export const RENDER_TARGET_OPTIONS = Object.freeze([
{ id: 'universe-bible', label: 'Universe Bible batch renders' },
@@ -42,10 +47,16 @@ export const RENDER_TARGET_OPTIONS = Object.freeze([
{ id: 'series-first-pass', label: 'Series first-pass portraits & frames' },
{ id: 'sprite-reference', label: 'Sprite references & anchors' },
{ id: 'pipeline-visual', label: 'Pipeline visuals (storyboards, comics, covers)' },
+ { id: 'music-video', label: 'Music Video scene frames & clips', video: true },
{ id: 'lora-dataset', label: 'LoRA training datasets' },
- { id: 'creative-agent', label: 'Creative agent renders' },
+ { id: 'creative-agent', label: 'Creative agent renders', video: true },
]);
+// Client mirror of the server's VIDEO_GEN_MODES (services/videoGen/modes.js) —
+// the backend alphabet for the video pin controls above and the install-wide
+// `settings.videoGen.mode` pin.
+export const VIDEO_RENDER_MODES = Object.freeze(['local', 'grok']);
+
// Client mirror of the server's GROK_ASPECT_RATIOS (imageGen/grok.js) — the
// aspect ratios grok's image_gen/image_edit tools accept, offered as the
// default-ratio picker in Settings → Image Gen → Grok.
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index 53522a9eda..0611b0a99c 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -33,6 +33,7 @@ import { generateImage } from '../services/apiSystem.js';
import { generateVideo, getVideoGenStatus, listLorasFull } from '../services/apiImageVideo.js';
import { listTracks, trackAudioUrl } from '../services/apiTracks.js';
import BeatTimeline from '../components/musicVideo/BeatTimeline.jsx';
+import RecordRenderPinRow from '../components/imageGen/RecordRenderPinRow.jsx';
import { autoArrangeScenes } from '../lib/beatGrid.js';
import useSceneRenderLifecycle from '../hooks/useSceneRenderLifecycle.js';
import { useVideoFileSrc } from '../hooks/useVideoFileSrc.js';
@@ -628,6 +629,28 @@ export default function MusicVideo() {
.finally(() => setVideoSettingsSaving(false));
};
+ // #3231 Phase 4 — per-project frame-render pin (`imageMode`/`imageModelId`),
+ // the image-side sibling of the video renderer select above. Scene
+ // reference-frame renders send no explicit mode, so the server resolves this
+ // record pin directly (imageGen/prepareParams) — no client seeding needed.
+ // Optimistic-local + silent PATCH, rollback + toast on failure.
+ const handleFramePinChange = ({ imageMode, imageModelId }) => {
+ if (!selected) return;
+ const projectId = selected.id;
+ const previous = { imageMode: selected.imageMode ?? null, imageModelId: selected.imageModelId ?? null };
+ setProjects((prev) => prev.map((p) => (p.id === projectId ? { ...p, imageMode, imageModelId } : p)));
+ updateMusicVideoProject(projectId, { imageMode, imageModelId }, { silent: true })
+ .then((project) => {
+ setProjects((prev) => prev.map((current) => (current.id === projectId
+ ? { ...current, imageMode: project.imageMode ?? null, imageModelId: project.imageModelId ?? null, updatedAt: project.updatedAt }
+ : current)));
+ })
+ .catch((err) => {
+ setProjects((prev) => prev.map((p) => (p.id === projectId ? { ...p, ...previous } : p)));
+ toast.error(err?.message || 'Failed to save frame renderer');
+ });
+ };
+
// Project-level concept/style (issue #3168) — optimistic-local + silent-PATCH on
// commit, same as commitSceneTiming below. Sends only the changed sub-field;
// the server merges it into the existing concept (applyProjectPatch), so a
@@ -974,6 +997,13 @@ export default function MusicVideo() {
className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0 disabled:opacity-50">
<Wand2 size={15} /> {arranging ? 'Arranging…' : 'Auto-arrange'}
</button>
+ <RecordRenderPinRow
+ idPrefix="mv-frame-pin"
+ label="Frames"
+ imageMode={selected.imageMode ?? null}
+ imageModelId={selected.imageModelId ?? null}
+ onChange={handleFramePinChange}
+ />
<label htmlFor="mv-video-backend" className="sr-only">Scene video renderer</label>
<select
id="mv-video-backend"
diff --git a/server/lib/renderTargets.parity.test.js b/server/lib/renderTargets.parity.test.js
index 58f885f1f1..a838b41cf6 100644
--- a/server/lib/renderTargets.parity.test.js
+++ b/server/lib/renderTargets.parity.test.js
@@ -15,16 +15,16 @@
*/
import { describe, it, expect } from 'vitest';
-import { RENDER_TARGET, RENDER_TARGETS, RENDER_TARGET_BACKEND_AUTO } from './renderTargets.js';
+import { RENDER_TARGETS, RENDER_TARGET_BACKEND_AUTO } from './renderTargets.js';
import {
RENDER_TARGET_OPTIONS as CLIENT_OPTIONS,
RENDER_TARGET_BACKEND_AUTO as CLIENT_AUTO,
} from '../../client/src/lib/imageGenBackends.js';
-// Targets the Settings UI deliberately does NOT list yet — a pin nobody's
-// resolver reads would be a control that silently does nothing. Shrink this
-// as phases land (music-video ships with the Phase 4 video lane).
-const DELIBERATELY_UNLISTED = new Set([RENDER_TARGET.MUSIC_VIDEO]);
+// Targets the Settings UI deliberately does NOT list — a pin nobody's
+// resolver reads would be a control that silently does nothing. Empty since
+// the Phase 4 video lane wired music-video (the last unlisted target).
+const DELIBERATELY_UNLISTED = new Set([]);
describe('render-target client mirror parity (#3231)', () => {
it('every client option id is a real server render target', () => {
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 16c5bb210f..c26ab7f360 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1017,6 +1017,21 @@ export const renderDefaultsSettingsSchema = z.object(
Object.fromEntries(RENDER_TARGETS.map((t) => [t, renderTargetEntrySchema.optional()])),
);
+// Install-wide video render pin (`settings.videoGen`, #3231 Phase 4) — the
+// third rung in resolveVideoMode's ladder (request → target pin → THIS →
+// local). `'auto'`/`''`/null all mean "no pin — local". Tolerant of unknown
+// keys for the same rollback/forward-compat reason as renderDefaults above.
+// `defaultModelId` predates this schema (pipeline storyboards/episodeVideo
+// read it as the local-model default) — typed here so a Settings save can't
+// write junk to it.
+export const videoGenSettingsSchema = z.object({
+ mode: z.enum([RENDER_TARGET_BACKEND_AUTO, ...VIDEO_GEN_MODES]).nullable().optional(),
+ defaultModelId: z.preprocess(
+ (v) => (v === '' ? null : v),
+ z.string().trim().max(64).nullable().optional(),
+ ),
+});
+
// Per-RECORD render pin (#3231 Phase 3) — the flat `imageMode`/`imageModelId`
// field pair persisted on universe / series / sprite records, following the
// creative-commission shape. Spread into a record's create + patch schemas.
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index 113379c650..51cf6447b9 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -21,6 +21,7 @@ import {
musicVideoPlanRequestSchema,
musicVideoManualAnalysisSchema,
musicVideoTranscribeMidiRequestSchema,
+ recordRenderPinFields,
} from '../lib/validation.js';
import { PATHS } from '../lib/fileUtils.js';
import { safeUnder } from '../lib/ffmpeg.js';
@@ -50,6 +51,15 @@ import { getTrack } from '../services/tracks/index.js';
const router = Router();
+// #3231 Phase 4 — the per-record image render pin (`imageMode`/`imageModelId`,
+// the shared universe/series/sprite field pair) on Music Video projects: scene
+// reference-frame renders resolve through it (imageGen/prepareParams.js).
+// Extended at the route layer — the same pattern as routes/universeBuilder.js —
+// because musicVideoValidation.js can't import recordRenderPinFields from
+// validation.js without a circular import (validation.js re-exports it).
+const projectCreateSchema = musicVideoProjectCreateSchema.extend(recordRenderPinFields);
+const projectUpdateSchema = musicVideoProjectUpdateSchema.extend(recordRenderPinFields);
+
router.get('/', asyncHandler(async (_req, res) => {
res.json(await listProjects());
}));
@@ -61,7 +71,7 @@ router.get('/:id', asyncHandler(async (req, res) => {
}));
router.post('/', asyncHandler(async (req, res) => {
- const data = validateRequest(musicVideoProjectCreateSchema, req.body);
+ const data = validateRequest(projectCreateSchema, req.body);
const project = await createProject(data);
res.status(201).json(project);
}));
@@ -72,7 +82,7 @@ router.post('/:id/clone', asyncHandler(async (req, res) => {
}));
router.patch('/:id', asyncHandler(async (req, res) => {
- const data = validateRequest(musicVideoProjectUpdateSchema, req.body);
+ const data = validateRequest(projectUpdateSchema, req.body);
const updated = await updateProject(req.params.id, data);
res.json(updated);
}));
diff --git a/server/routes/settings.js b/server/routes/settings.js
index aace01c8a3..754c781886 100644
--- a/server/routes/settings.js
+++ b/server/routes/settings.js
@@ -10,7 +10,7 @@ import {
} from '../services/mediaJobQueue/index.js';
import { asyncHandler } from '../lib/errorHandler.js';
import { isPlainObject } from '../lib/objects.js';
-import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, renderDefaultsSettingsSchema, validateRequest } from '../lib/validation.js';
+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, validateRequest } from '../lib/validation.js';
const router = Router();
@@ -226,6 +226,11 @@ router.put('/', asyncHandler(async (req, res) => {
if (req.body?.renderDefaults !== undefined) {
validateRequest(renderDefaultsSettingsSchema, req.body.renderDefaults);
}
+ // Install-wide video render pin (#3231 Phase 4) — validate when present so a
+ // non-enum backend can't persist a mode resolveVideoMode would choke on.
+ if (req.body?.videoGen !== undefined) {
+ validateRequest(videoGenSettingsSchema, req.body.videoGen);
+ }
// Install-level Layered Intelligence settings (#2515) — validate the slice when
// present so a malformed `trustShellSources` can't persist and silently unlock
// full-shell custom `cmd` sources install-wide.
diff --git a/server/routes/settings.test.js b/server/routes/settings.test.js
index 150bca9655..9c9568e373 100644
--- a/server/routes/settings.test.js
+++ b/server/routes/settings.test.js
@@ -200,4 +200,43 @@ describe('Settings routes — renderDefaults slice (#3231)', () => {
.send({ renderDefaults: { 'universe-bible': { imageModel: 'x; rm -rf /' } } });
expect(shell.status).toBe(400);
});
+
+ it('accepts a per-target video backend pin and rejects a non-video backend (#3231 Phase 4)', async () => {
+ const ok = await request(buildApp())
+ .put('/api/settings')
+ .send({ renderDefaults: { 'music-video': { videoMode: 'grok' } } });
+ expect(ok.status).toBe(200);
+ expect(ok.body.renderDefaults['music-video']).toEqual({ videoMode: 'grok' });
+ const bad = await request(buildApp())
+ .put('/api/settings')
+ .send({ renderDefaults: { 'music-video': { videoMode: 'codex' } } });
+ expect(bad.status).toBe(400);
+ });
+});
+
+describe('Settings routes — videoGen slice (#3231 Phase 4)', () => {
+ beforeEach(() => {
+ store = {};
+ vi.clearAllMocks();
+ });
+
+ it('accepts the install-wide video pin and preserves sibling keys', async () => {
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ videoGen: { mode: 'grok', defaultModelId: 'ltx23_distilled_q4' } });
+ expect(res.status).toBe(200);
+ expect(res.body.videoGen).toEqual({ mode: 'grok', defaultModelId: 'ltx23_distilled_q4' });
+ // Clearing via null is the intentional no-pin state.
+ const cleared = await request(buildApp())
+ .put('/api/settings')
+ .send({ videoGen: { mode: null } });
+ expect(cleared.status).toBe(200);
+ });
+
+ it('rejects a non-video backend as the install-wide video pin', async () => {
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ videoGen: { mode: 'codex' } });
+ expect(res.status).toBe(400);
+ });
});
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 62e9d06dc1..74d817ceba 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -20,6 +20,8 @@ import { PATHS, ensureDir, resolveGalleryImage } from '../lib/fileUtils.js';
import { safeUnder } from '../lib/ffmpeg.js';
import { grokVideoDurationSchema } from '../lib/validation.js';
import { IMAGE_GEN_MODE } from '../services/imageGen/modes.js';
+import { VIDEO_GEN_MODE, resolveVideoMode } from '../services/videoGen/modes.js';
+import { RENDER_TARGET } from '../lib/renderTargets.js';
import { getSettings } from '../services/settings.js';
import { getProject as getMusicVideoProject } from '../services/musicVideo/projects.js';
import { getTrack } from '../services/tracks/index.js';
@@ -750,6 +752,26 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
}
const body = parsed.data;
const s = await getSettings();
+ // #3231 Phase 4 — the video pin ladder. An explicit `body.backend` always
+ // wins (the VideoGen page and the MV director board both send one); when
+ // absent, consult the music-video target pin (for director-board renders)
+ // and the install-wide `settings.videoGen.mode` via resolveVideoMode. A pin
+ // is honored only for a grok-DELIVERABLE request shape — the grok lane reads
+ // only prompt/dims/source-image/duration, so a request carrying local-only
+ // machinery (a semantic mode beyond text/image, keyframes, audio, IC refs,
+ // extend, LoRAs, a last frame) stays local rather than silently dropping
+ // those inputs. A pin degrades; only an explicit backend request errors.
+ const grokDeliverable = (!body.mode || body.mode === 'text' || body.mode === 'image')
+ && !uploads.lastImage && !body.lastImageFile
+ && !uploads.audioFile
+ && !uploads.icReference && !body.icReferenceVideoIds?.length && !body.icReferenceImageFiles?.length
+ && !body.extendFromVideoId
+ && !body.keyframes?.length
+ && !body.loraFilenames?.length;
+ const backend = body.backend
+ || (grokDeliverable
+ ? resolveVideoMode(null, s, { target: body.musicVideo ? RENDER_TARGET.MUSIC_VIDEO : null })
+ : VIDEO_GEN_MODE.LOCAL);
const pythonPath = s.imageGen?.local?.pythonPath || null;
// Resolve the effective model up front — both the modelId-exists check
// below AND the a2v runtime guard further down need the model entry,
@@ -777,7 +799,7 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
// shared with services/videoGen/local.js so the route and worker stay
// in sync.
const runtimeBringsOwnVenv = effectiveModel && BYOV_VIDEO_RUNTIMES.has(effectiveModel.runtime);
- if (!pythonPath && !runtimeBringsOwnVenv && body.backend !== 'grok') {
+ if (!pythonPath && !runtimeBringsOwnVenv && backend !== 'grok') {
await cleanupTempUploads();
throw new ServerError(
'Local video generation is not configured (settings.imageGen.local.pythonPath is missing).',
@@ -1023,8 +1045,9 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
// local-runtime machinery grok doesn't use. sourceImagePath (upload or
// gallery pick) is already resolved above, so an i2v render animates that
// frame and a plain prompt runs the image-first image_gen → image_to_video
- // flow inside the provider.
- if (body.backend === 'grok') {
+ // flow inside the provider. `backend` (not `body.backend`) so the #3231
+ // pin ladder routes an unpinned-request grok default through here too.
+ if (backend === 'grok') {
const g = s.imageGen?.grok || {};
if (!g.enabled) {
await cleanupAllStaged();
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index 1326a5d270..5ed5cf4988 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -307,6 +307,60 @@ describe('videoGen routes', () => {
});
});
+ describe('POST / — video pin ladder (#3231 Phase 4)', () => {
+ const grokReady = { grok: { enabled: true, grokPath: '/opt/grok' } };
+
+ it('routes an unpinned-request render to grok via settings.videoGen.mode', async () => {
+ const { getSettings } = await import('../services/settings.js');
+ getSettings.mockResolvedValueOnce({ imageGen: grokReady, videoGen: { mode: 'grok' } });
+ const r = await request(app).post('/api/video-gen/').send({ prompt: 'a fox' });
+ expect(r.status).toBe(200);
+ expect(r.body.mode).toBe('grok');
+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({
+ kind: 'video',
+ params: expect.objectContaining({ mode: 'grok', videoMode: 'text', grokPath: '/opt/grok' }),
+ }));
+ });
+
+ it('an explicit backend outranks the install pin', async () => {
+ const { getSettings } = await import('../services/settings.js');
+ getSettings.mockResolvedValueOnce({
+ imageGen: { ...grokReady, local: { pythonPath: '/usr/bin/python3' } },
+ videoGen: { mode: 'grok' },
+ });
+ const r = await request(app).post('/api/video-gen/').send({ prompt: 'a fox', backend: 'local' });
+ expect(r.status).toBe(200);
+ const [call] = mediaJobQueue.enqueueJob.mock.calls;
+ expect(call[0].params.mode).not.toBe('grok');
+ });
+
+ it('a grok pin degrades to local when the request carries local-only machinery', async () => {
+ const { getSettings } = await import('../services/settings.js');
+ getSettings.mockResolvedValueOnce({
+ imageGen: { ...grokReady, local: { pythonPath: '/usr/bin/python3' } },
+ videoGen: { mode: 'grok' },
+ });
+ // 'fflf' is a local-runtime semantic — the pin must not hijack it to grok
+ // (which would silently drop the keyframe machinery).
+ const r = await request(app).post('/api/video-gen/').send({ prompt: 'a fox', mode: 'fflf' });
+ expect(r.status).toBe(200);
+ const [call] = mediaJobQueue.enqueueJob.mock.calls;
+ expect(call[0].params.mode).not.toBe('grok');
+ });
+
+ it('a disabled grok install pin degrades to local instead of erroring', async () => {
+ const { getSettings } = await import('../services/settings.js');
+ getSettings.mockResolvedValueOnce({
+ imageGen: { grok: { enabled: false }, local: { pythonPath: '/usr/bin/python3' } },
+ videoGen: { mode: 'grok' },
+ });
+ const r = await request(app).post('/api/video-gen/').send({ prompt: 'a fox' });
+ expect(r.status).toBe(200);
+ const [call] = mediaJobQueue.enqueueJob.mock.calls;
+ expect(call[0].params.mode).not.toBe('grok');
+ });
+ });
+
describe('POST /', () => {
it('rejects missing prompt', async () => {
const r = await request(app).post('/api/video-gen/').send({ width: 512 });
diff --git a/server/services/creative/tools/media.js b/server/services/creative/tools/media.js
index 3c099a9c9b..86996e0d06 100644
--- a/server/services/creative/tools/media.js
+++ b/server/services/creative/tools/media.js
@@ -10,7 +10,7 @@ import { ASPECT_PRESETS, QUALITY_PRESETS, presetToRenderParams } from '../../../
import { getSettings } from '../../settings.js';
import { IMAGE_GEN_MODE, resolveQueueImageMode, resolveQueueImageEditMode } from '../../imageGen/modes.js';
import { renderTargetDefaults, resolveRenderTargetConfig } from '../../imageGen/cloudProviderConfig.js';
-import { RENDER_TARGET } from '../../../lib/renderTargets.js';
+import { RENDER_TARGET, normalizeRenderPinValue } from '../../../lib/renderTargets.js';
import { VIDEO_GEN_MODE, VIDEO_GEN_MODES, resolveVideoMode } from '../../videoGen/modes.js';
import { nearestGrokDuration } from '../../../lib/grokVideoClip.js';
import { COST_RENDER, resolveOwner } from './shared.js';
@@ -121,21 +121,23 @@ function attachMusicBedTag(params, ctx) {
*/
async function enforceRenderBackendPin(kind, params, project) {
const pin = project?.renderBackend?.[kind];
- // The image lane has TWO pin sources: the project's own renderBackend pin
- // (per-record, wins) and the install-wide creative-agent renderDefaults pin
- // (#3231). The video lane stays project-pin-only until the Phase 4 video
- // wiring lands. When NEITHER source pins, params pass through untouched —
- // the "auto is byte-identical" contract above.
- if (!pin?.mode && kind !== 'image') return params;
const settings = await getSettings().catch(() => null);
if (!settings) return params;
- if (!pin?.mode && kind === 'image'
- && !renderTargetDefaults(settings, RENDER_TARGET.CREATIVE_AGENT).imageMode) {
+ const targetDefaults = renderTargetDefaults(settings, RENDER_TARGET.CREATIVE_AGENT);
+ // Each lane has a pin ladder (#3231): the project's own renderBackend pin
+ // (per-record, wins) → the install-wide creative-agent renderDefaults pin
+ // → (video only, Phase 4) the install-wide `settings.videoGen.mode` pin.
+ // When NO source pins the lane, params pass through untouched — the "auto
+ // is byte-identical" contract above.
+ if (kind === 'image') {
+ if (!pin?.mode && !targetDefaults.imageMode) return params;
+ } else if (!pin?.mode && !targetDefaults.videoMode
+ && !normalizeRenderPinValue(settings.videoGen?.mode)) {
return params;
}
if (kind === 'video') {
- const mode = resolveVideoMode(pin.mode, settings);
+ const mode = resolveVideoMode(pin?.mode, settings, { target: RENDER_TARGET.CREATIVE_AGENT });
if (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
@@ -154,8 +156,12 @@ async function enforceRenderBackendPin(kind, params, project) {
? (({ 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.
- return pin.modelId ? { ...base, modelId: pin.modelId } : base;
+ // 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.
+ const pinnedModelId = pin?.modelId || targetDefaults.videoModel;
+ return pinnedModelId ? { ...base, modelId: pinnedModelId } : base;
}
const grok = settings.imageGen?.grok || {};
// videoGen/grok.js reads the same `imageGen.grok` slice the image path does
@@ -186,8 +192,7 @@ async function enforceRenderBackendPin(kind, params, project) {
// Project pin (explicit, per-record) → creative-agent renderDefaults pin —
// both usability-laddered so a disabled backend degrades instead of failing
// a nightly commission.
- const requested = pin?.mode
- || renderTargetDefaults(settings, RENDER_TARGET.CREATIVE_AGENT).imageMode;
+ const requested = pin?.mode || targetDefaults.imageMode;
const mode = wantsEdit
? resolveQueueImageEditMode(requested, settings)
: resolveQueueImageMode(requested, settings);
diff --git a/server/services/creative/tools/media.test.js b/server/services/creative/tools/media.test.js
index b5f34bf49c..e25917e702 100644
--- a/server/services/creative/tools/media.test.js
+++ b/server/services/creative/tools/media.test.js
@@ -68,6 +68,50 @@ describe('render-backend pin — the auto/unpinned path is a strict no-op (#3135
expect(enqueued().params).toEqual({ prompt: 'p', mode: 'image' });
});
+ it('applies the creative-agent renderDefaults VIDEO pin when the project has none (#3231 Phase 4)', async () => {
+ getSettings.mockResolvedValue({
+ imageGen: { grok: { enabled: true, grokPath: '/bin/grok' } },
+ renderDefaults: { 'creative-agent': { videoMode: 'grok' } },
+ });
+ await run('media_enqueueVideoJob', { prompt: 'p' });
+ expect(enqueued().params).toEqual(expect.objectContaining({ mode: 'grok', videoMode: 'text', grokPath: '/bin/grok' }));
+ });
+
+ it('applies the install-wide settings.videoGen.mode pin when nothing else pins (#3231 Phase 4)', async () => {
+ getSettings.mockResolvedValue({
+ imageGen: { grok: { enabled: true, grokPath: '/bin/grok' } },
+ videoGen: { mode: 'grok' },
+ });
+ await run('media_enqueueVideoJob', { prompt: 'p' });
+ expect(enqueued().params).toEqual(expect.objectContaining({ mode: 'grok' }));
+ });
+
+ it('the project video pin outranks the target video pin', async () => {
+ getSettings.mockResolvedValue({
+ imageGen: { grok: { enabled: true, grokPath: '/bin/grok' } },
+ renderDefaults: { 'creative-agent': { videoMode: 'grok' } },
+ });
+ getProject.mockResolvedValue(projectWithPin({ video: { mode: 'local' } }));
+ await run('media_enqueueVideoJob', { prompt: 'p', mode: 'image' }, { projectId: 'cd-1' });
+ expect(enqueued().params.mode).toBe('image'); // local pin → semantic survives, no grok discriminator
+ });
+
+ it('a disabled grok video pin degrades to local (never fails the commission)', async () => {
+ getSettings.mockResolvedValue({
+ renderDefaults: { 'creative-agent': { videoMode: 'grok' } },
+ });
+ await run('media_enqueueVideoJob', { prompt: 'p', mode: 'image' });
+ expect(enqueued().params).toEqual(expect.objectContaining({ mode: 'image', prompt: 'p' }));
+ });
+
+ it('the target videoModel rides a local resolution when the project pins no model', async () => {
+ getSettings.mockResolvedValue({
+ renderDefaults: { 'creative-agent': { videoMode: 'local', videoModel: 'target-video-model' } },
+ });
+ await run('media_enqueueVideoJob', { prompt: 'p', mode: 'image' });
+ expect(enqueued().params.modelId).toBe('target-video-model');
+ });
+
it('reads the owning project exactly once per enqueue', async () => {
getProject.mockResolvedValue(projectWithPin({ image: { mode: 'local' } }));
await run('media_enqueueVideoJob', { prompt: 'p' }, { projectId: 'cd-1' });
diff --git a/server/services/imageGen/prepareParams.js b/server/services/imageGen/prepareParams.js
index 983d21a4b2..4773c9475b 100644
--- a/server/services/imageGen/prepareParams.js
+++ b/server/services/imageGen/prepareParams.js
@@ -28,6 +28,9 @@ import { ServerError } from '../../lib/errorHandler.js';
import { PATHS, ensureDir, resolveGalleryImage } from '../../lib/fileUtils.js';
import { getSettings } from '../settings.js';
import { IMAGE_GEN_MODE, CLOUD_IMAGE_GEN_MODES, resolveImageCleaners } from './index.js';
+import { resolveRenderTargetConfig } from './cloudProviderConfig.js';
+import { RENDER_TARGET, recordRenderPin } from '../../lib/renderTargets.js';
+import { getProject as getMusicVideoProject } from '../musicVideo/projects.js';
import { getImageModels, isFlux2 } from '../../lib/mediaModels.js';
// Only the formats mflux can decode — mirrors the route's MIME_TO_EXT map
@@ -77,7 +80,28 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
// while the actual generation silently ignored them. (Reading settings here
// is cheap — it's already read again below for the per-mode dispatch.)
const settings = await getSettings();
- const mode = data.mode || settings.imageGen?.mode || IMAGE_GEN_MODE.EXTERNAL;
+ let mode = data.mode || settings.imageGen?.mode || IMAGE_GEN_MODE.EXTERNAL;
+ // #3231 Phase 4 — Music Video scene-frame renders resolve through the
+ // render-target ladder: per-request mode → the owning project's record pin
+ // (`imageMode`/`imageModelId`) → `renderDefaults['music-video']` → the
+ // install default above. The director board sends NO mode with its frame
+ // renders, so the record/target pins are live without any client seeding
+ // (unlike the universe batch form). The layered model is stamped onto
+ // `data.cloudModel` so the route/dispatch resolution downstream picks it up;
+ // an explicit per-request cloudModel wins untouched.
+ if (data.musicVideo?.projectId) {
+ const project = await getMusicVideoProject(data.musicVideo.projectId).catch(() => null);
+ const pin = recordRenderPin(project || {});
+ const resolved = resolveRenderTargetConfig(settings, RENDER_TARGET.MUSIC_VIDEO, {
+ mode: data.mode || null,
+ model: data.cloudModel || null,
+ recordMode: pin.mode,
+ recordModel: pin.modelId,
+ fallbackMode: settings.imageGen?.mode || IMAGE_GEN_MODE.EXTERNAL,
+ });
+ mode = resolved.mode;
+ if (!data.cloudModel && resolved.cloud?.modelId) data.cloudModel = resolved.cloud.modelId;
+ }
if (mode === IMAGE_GEN_MODE.AGY && (initUpload || data.initImageFile)) {
cleanupReqFilesTemp();
throw new ServerError('Agy Imagegen supports text-to-image only', {
diff --git a/server/services/imageGen/prepareParams.test.js b/server/services/imageGen/prepareParams.test.js
new file mode 100644
index 0000000000..e79dd637df
--- /dev/null
+++ b/server/services/imageGen/prepareParams.test.js
@@ -0,0 +1,72 @@
+/**
+ * prepareGenerateParams — Music Video render-target resolution (#3231 Phase 4).
+ *
+ * Scene reference-frame renders arrive with a `musicVideo` tag and NO mode, so
+ * the mode must come from the render-target ladder (record pin →
+ * renderDefaults['music-video'] → install default) and the layered model must
+ * land on `data.cloudModel`, which is what the route's dispatch resolution
+ * reads. Only the ladder inputs are mocked; the resolver itself runs for real.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const getSettings = vi.fn(async () => ({}));
+vi.mock('../settings.js', () => ({ getSettings: (...a) => getSettings(...a) }));
+
+const getProject = vi.fn(async () => null);
+vi.mock('../musicVideo/projects.js', () => ({ getProject: (...a) => getProject(...a) }));
+
+const { prepareGenerateParams } = await import('./prepareParams.js');
+
+const CODEX_ON = { codex: { enabled: true, codexPath: '/bin/codex' } };
+const run = (data) => prepareGenerateParams({ data, files: undefined, referenceImageFields: [] });
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getSettings.mockResolvedValue({});
+ getProject.mockResolvedValue(null);
+});
+
+describe('music-video render-target resolution (#3231 Phase 4)', () => {
+ it('resolves the owning project record pin and stamps its model onto cloudModel', async () => {
+ getSettings.mockResolvedValue({ imageGen: { mode: 'local', ...CODEX_ON } });
+ getProject.mockResolvedValue({ id: 'mv-1', imageMode: 'codex', imageModelId: 'record-model' });
+ const { data, mode } = await run({ prompt: 'p', musicVideo: { projectId: 'mv-1', sceneId: 's1' } });
+ expect(getProject).toHaveBeenCalledWith('mv-1');
+ expect(mode).toBe('codex');
+ expect(data.cloudModel).toBe('record-model');
+ });
+
+ it("resolves renderDefaults['music-video'] when the record has no pin", async () => {
+ getSettings.mockResolvedValue({
+ imageGen: { mode: 'local', ...CODEX_ON },
+ renderDefaults: { 'music-video': { imageMode: 'codex', imageModel: 'target-model' } },
+ });
+ getProject.mockResolvedValue({ id: 'mv-1' });
+ const { data, mode } = await run({ prompt: 'p', musicVideo: { projectId: 'mv-1', sceneId: 's1' } });
+ expect(mode).toBe('codex');
+ expect(data.cloudModel).toBe('target-model');
+ });
+
+ it('an explicit request mode outranks the record pin (and its model does not leak)', async () => {
+ getSettings.mockResolvedValue({ imageGen: { mode: 'external', ...CODEX_ON } });
+ getProject.mockResolvedValue({ id: 'mv-1', imageMode: 'codex', imageModelId: 'record-model' });
+ const { data, mode } = await run({ prompt: 'p', mode: 'local', musicVideo: { projectId: 'mv-1', sceneId: 's1' } });
+ expect(mode).toBe('local');
+ expect(data.cloudModel).toBeUndefined();
+ });
+
+ it('falls through to the install default with no pins, and a missing project is harmless', async () => {
+ getSettings.mockResolvedValue({ imageGen: { mode: 'external' } });
+ getProject.mockRejectedValue(new Error('gone'));
+ const { mode } = await run({ prompt: 'p', musicVideo: { projectId: 'mv-x', sceneId: 's1' } });
+ expect(mode).toBe('external');
+ });
+
+ it('renders without a musicVideo tag never touch the project store', async () => {
+ getSettings.mockResolvedValue({ imageGen: { mode: 'external' } });
+ const { mode } = await run({ prompt: 'p' });
+ expect(mode).toBe('external');
+ expect(getProject).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/musicVideo/projects.js b/server/services/musicVideo/projects.js
index 480198e75e..ee60e7e382 100644
--- a/server/services/musicVideo/projects.js
+++ b/server/services/musicVideo/projects.js
@@ -23,6 +23,9 @@
import { createRecordStoreBackendSelector } from '../../lib/pgFileFacade.js';
import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';
+import { RENDER_TARGET } from '../../lib/renderTargets.js';
+import { VIDEO_GEN_MODE, resolveVideoMode } from '../videoGen/modes.js';
+import { getSettings } from '../settings.js';
// Shared dispatcher (#2899). ensureSchema() runs inside the selector (mirroring
// memoryBackend.js) so the backend is self-sufficient regardless of boot ordering.
@@ -63,8 +66,26 @@ export async function listProjectIds(options = {}) {
return (await selectBackend()).listProjectIds(options);
}
+// #3231 Phase 4 — seed a new project's video backend from the video pin ladder
+// (`renderDefaults['music-video'].videoMode` → `settings.videoGen.mode`). The
+// director board always sends the record's `videoSettings.backend` with each
+// clip render (an explicit `body.backend`), so a target/install video pin can
+// only take effect HERE, at record creation — the same explicit-body seeding
+// trap the universe batch form and sprites page picker hit on the image side.
+// resolveVideoMode usability-gates the pin (a disabled grok pin seeds local);
+// an input that names a backend explicitly wins untouched.
+async function seedVideoBackendDefault(input) {
+ if (input?.videoSettings?.backend) return input;
+ const settings = await getSettings().catch(() => null);
+ if (!settings) return input;
+ const backend = resolveVideoMode(null, settings, { target: RENDER_TARGET.MUSIC_VIDEO });
+ // Local is buildProjectRecord's own default — leave the input byte-identical.
+ if (backend === VIDEO_GEN_MODE.LOCAL) return input;
+ return { ...input, videoSettings: { ...(input?.videoSettings || {}), backend } };
+}
+
export async function createProject(input) {
- const project = await (await selectBackend()).createProject(input);
+ const project = await (await selectBackend()).createProject(await seedVideoBackendDefault(input));
announceNewProject(project.id);
return project;
}
diff --git a/server/services/musicVideo/projects.test.js b/server/services/musicVideo/projects.test.js
index 86ec488fb6..04d767621d 100644
--- a/server/services/musicVideo/projects.test.js
+++ b/server/services/musicVideo/projects.test.js
@@ -27,6 +27,11 @@ vi.mock('../sharing/recordEvents.js', () => ({
autoSubscribeRecordToAllPeers: (...a) => autoSubscribeRecordToAllPeers(...a),
}));
+// Settings feed the create-time video-backend seed (#3231 Phase 4) — mocked so
+// each test controls the pin ladder deterministically.
+const getSettings = vi.fn(async () => ({}));
+vi.mock('../settings.js', () => ({ getSettings: (...a) => getSettings(...a) }));
+
const projects = await import('./projects.js');
function reset() {
@@ -34,6 +39,8 @@ function reset() {
emitRecordUpdated.mockClear();
emitRecordDeleted.mockClear();
autoSubscribeRecordToAllPeers.mockClear();
+ getSettings.mockClear();
+ getSettings.mockResolvedValue({});
}
beforeEach(reset);
afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
@@ -92,3 +99,43 @@ describe('musicVideo dispatcher — record-event emit (#1770)', () => {
expect(typeof projects.listProjectIds).toBe('function');
});
});
+
+describe('create-time video-backend seeding (#3231 Phase 4)', () => {
+ const grokPinned = (pins) => ({
+ imageGen: { grok: { enabled: true } },
+ ...pins,
+ });
+
+ it('seeds videoSettings.backend from renderDefaults[music-video].videoMode', async () => {
+ getSettings.mockResolvedValue(grokPinned({ renderDefaults: { 'music-video': { videoMode: 'grok' } } }));
+ const p = await projects.createProject({ name: 'A' });
+ expect(p.videoSettings.backend).toBe('grok');
+ });
+
+ it('seeds from settings.videoGen.mode when no target pin exists', async () => {
+ getSettings.mockResolvedValue(grokPinned({ videoGen: { mode: 'grok' } }));
+ const p = await projects.createProject({ name: 'A' });
+ expect(p.videoSettings.backend).toBe('grok');
+ });
+
+ it('an explicit input backend wins over every pin', async () => {
+ getSettings.mockResolvedValue(grokPinned({ videoGen: { mode: 'grok' } }));
+ const p = await projects.createProject({ name: 'A', videoSettings: { backend: 'local' } });
+ expect(p.videoSettings.backend).toBe('local');
+ });
+
+ it('defaults to local with no pin anywhere — and a disabled grok pin degrades', async () => {
+ const p1 = await projects.createProject({ name: 'A' });
+ expect(p1.videoSettings.backend).toBe('local');
+ // Pin present but the grok toggle is off → usability gate degrades to local.
+ getSettings.mockResolvedValue({ renderDefaults: { 'music-video': { videoMode: 'grok' } } });
+ const p2 = await projects.createProject({ name: 'B' });
+ expect(p2.videoSettings.backend).toBe('local');
+ });
+
+ it('a settings read failure leaves creation working (seed is best-effort)', async () => {
+ getSettings.mockRejectedValue(new Error('boom'));
+ const p = await projects.createProject({ name: 'A' });
+ expect(p.videoSettings.backend).toBe('local');
+ });
+});
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index 613e7ba35f..a79c8c56f9 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -25,6 +25,7 @@ import {
} from '../../lib/validation.js';
import { compareNewerWins } from '../../lib/lwwTimestamp.js';
import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';
+import { persistedRenderPinFields } from '../../lib/renderTargets.js';
// Re-exported for the PG backend's typed mirror columns (mirrors the CD store).
export { mirrorTimestamp } from '../../lib/pgTimestamp.js';
@@ -83,6 +84,10 @@ export function buildProjectRecord(input, { id, now }) {
audioReactiveLora: videoSettings.audioReactiveLora ?? null,
audioReactiveScale: videoSettings.audioReactiveScale ?? 1.2,
},
+ // #3231 Phase 4 — per-record image render pin for scene reference-frame
+ // renders (the shared universe/series/sprite field pair). Present only
+ // when set, so existing records keep their on-disk shape byte-stable.
+ ...persistedRenderPinFields(input),
audioAnalysis: null,
midiTranscription: null,
scenes: [],
diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.js
index 079c2d89d3..717dc79146 100644
--- a/server/services/musicVideo/projectsLogic.test.js
+++ b/server/services/musicVideo/projectsLogic.test.js
@@ -36,6 +36,35 @@ describe('buildProjectRecord', () => {
expect(p.mode).toBe('autonomous');
expect(p.concept).toEqual({ prompt: 'noir' });
});
+
+ it('persists the image render pin only when set (#3231 Phase 4)', () => {
+ const pinned = buildProjectRecord(
+ { name: 'A', imageMode: 'codex', imageModelId: 'example-model' },
+ { id: 'mv-3', now: 'n' },
+ );
+ expect(pinned.imageMode).toBe('codex');
+ expect(pinned.imageModelId).toBe('example-model');
+ // No pin → the keys are absent entirely, keeping the on-disk shape
+ // byte-stable for existing records.
+ const unpinned = buildProjectRecord({ name: 'B' }, { id: 'mv-4', now: 'n' });
+ expect('imageMode' in unpinned).toBe(false);
+ expect('imageModelId' in unpinned).toBe(false);
+ // The 'auto' sentinel and blanks collapse to no pin.
+ const auto = buildProjectRecord({ name: 'C', imageMode: 'auto', imageModelId: '' }, { id: 'mv-5', now: 'n' });
+ expect('imageMode' in auto).toBe(false);
+ expect('imageModelId' in auto).toBe(false);
+ });
+
+ it('a patch sets and clears the image render pin (#3231 Phase 4)', () => {
+ const p = baseProject();
+ const pinned = applyProjectPatch(p, { imageMode: 'agy', imageModelId: 'example-model' });
+ expect(pinned.imageMode).toBe('agy');
+ expect(pinned.imageModelId).toBe('example-model');
+ // Key-present-with-null is the intentional clear (absent-vs-empty rule).
+ const cleared = applyProjectPatch(pinned, { imageMode: null, imageModelId: null });
+ expect(cleared.imageMode).toBeNull();
+ expect(cleared.imageModelId).toBeNull();
+ });
});
describe('cloneProjectRecord', () => {
diff --git a/server/services/videoGen/modes.js b/server/services/videoGen/modes.js
index eca11d3da9..3a479e80cb 100644
--- a/server/services/videoGen/modes.js
+++ b/server/services/videoGen/modes.js
@@ -20,11 +20,13 @@
* literal 'grok', which is exactly why the cloud discriminator can share the
* key; a grok job carries the semantic separately as `videoMode`.
*
- * Dependency-free apart from the image enum (which is itself a leaf), so
- * `lib/validation.js` and the commission validation leaf can both import it.
+ * Dependency-free apart from the image enum and the render-target leaf (both
+ * leaves themselves), so `lib/validation.js` and the commission validation
+ * leaf can both import it.
*/
import { IMAGE_GEN_MODE } from '../imageGen/modes.js';
+import { normalizeRenderPinValue } from '../../lib/renderTargets.js';
export const VIDEO_GEN_MODE = Object.freeze({
LOCAL: IMAGE_GEN_MODE.LOCAL,
@@ -52,20 +54,31 @@ export function isVideoModeUsable(settings, mode) {
}
/**
- * Resolve the video backend for a render: the per-request/per-record override
- * when that backend is usable, else the install-wide default.
+ * Resolve the video backend for a render through the video pin ladder (#3231
+ * Phase 4): per-request/per-record override → the surface's saved
+ * `renderDefaults[target].videoMode` pin → the install-wide
+ * `settings.videoGen.mode` pin → LOCAL. Every rung is usability-gated (a
+ * pinned grok whose `imageGen.grok.enabled` toggle is off degrades instead of
+ * bricking the render — same contract as the image side's
+ * resolveRenderTargetConfig).
*
* Mirrors `pickUsableMode` (imageGen/cloudProviderConfig.js) in shape and
- * intent, but the DEFAULT differs deliberately: image gen prefers an enabled
- * cloud backend, while video defaults to LOCAL. A local video render is free and
- * fully controllable (model/frames/fps/LoRAs); grok video spends remote quota
- * and only delivers 6s or 10s clips (see lib/grokVideoClip.js). Silently
+ * intent, but the FALLBACK differs deliberately: image gen prefers an enabled
+ * cloud backend, while video falls back to LOCAL. A local video render is free
+ * and fully controllable (model/frames/fps/LoRAs); grok video spends remote
+ * quota and only delivers 6s or 10s clips (see lib/grokVideoClip.js). Silently
* upgrading every unpinned video render to a paid backend because the user
- * enabled grok for IMAGES would be a surprise spend, so grok video stays opt-in
- * per record. There is no `settings.videoGen.mode` install-wide pin today; when
- * one lands it belongs as the second candidate here.
+ * enabled grok for IMAGES would be a surprise spend — grok video renders only
+ * when a request, record, or explicit user pin names it.
*/
-export function resolveVideoMode(requested, settings) {
- if (requested && isVideoModeUsable(settings, requested)) return requested;
+export function resolveVideoMode(requested, settings, { target = null } = {}) {
+ const candidates = [
+ requested,
+ target ? normalizeRenderPinValue(settings?.renderDefaults?.[target]?.videoMode) : null,
+ normalizeRenderPinValue(settings?.videoGen?.mode),
+ ];
+ for (const mode of candidates) {
+ if (mode && isVideoModeUsable(settings, mode)) return mode;
+ }
return VIDEO_GEN_MODE.LOCAL;
}
diff --git a/server/services/videoGen/modes.test.js b/server/services/videoGen/modes.test.js
index b161d31752..69514f6e79 100644
--- a/server/services/videoGen/modes.test.js
+++ b/server/services/videoGen/modes.test.js
@@ -56,3 +56,54 @@ describe('resolveVideoMode', () => {
expect(resolveVideoMode(undefined, grokOn)).toBe('local');
});
});
+
+describe('resolveVideoMode — pin ladder (#3231 Phase 4)', () => {
+ const grokOn = { imageGen: { grok: { enabled: true } } };
+ const withPins = (extra) => ({ ...grokOn, ...extra });
+
+ it('consults renderDefaults[target].videoMode when no request names a backend', () => {
+ const settings = withPins({ renderDefaults: { 'music-video': { videoMode: 'grok' } } });
+ expect(resolveVideoMode(null, settings, { target: 'music-video' })).toBe('grok');
+ // A different target's pin does not leak.
+ expect(resolveVideoMode(null, settings, { target: 'creative-agent' })).toBe('local');
+ // No target → the target rung is skipped entirely.
+ expect(resolveVideoMode(null, settings)).toBe('local');
+ });
+
+ it('consults settings.videoGen.mode after the target pin', () => {
+ const settings = withPins({ videoGen: { mode: 'grok' } });
+ expect(resolveVideoMode(null, settings)).toBe('grok');
+ expect(resolveVideoMode(null, settings, { target: 'music-video' })).toBe('grok');
+ // The target pin outranks the install pin.
+ const both = withPins({
+ renderDefaults: { 'music-video': { videoMode: 'local' } },
+ videoGen: { mode: 'grok' },
+ });
+ expect(resolveVideoMode(null, both, { target: 'music-video' })).toBe('local');
+ });
+
+ it('an explicit request outranks every pin', () => {
+ const settings = withPins({
+ renderDefaults: { 'music-video': { videoMode: 'grok' } },
+ videoGen: { mode: 'grok' },
+ });
+ expect(resolveVideoMode('local', settings, { target: 'music-video' })).toBe('local');
+ });
+
+ it("normalizes the 'auto' sentinel and blanks to no-pin on every rung", () => {
+ expect(resolveVideoMode(null, withPins({ videoGen: { mode: 'auto' } }))).toBe('local');
+ expect(resolveVideoMode(null, withPins({ videoGen: { mode: ' ' } }))).toBe('local');
+ expect(resolveVideoMode(null, withPins({
+ renderDefaults: { 'music-video': { videoMode: 'auto' } },
+ }), { target: 'music-video' })).toBe('local');
+ });
+
+ it('usability-gates each pin rung — a disabled grok pin degrades to local', () => {
+ const grokOff = { imageGen: { grok: { enabled: false } } };
+ expect(resolveVideoMode(null, {
+ ...grokOff,
+ renderDefaults: { 'music-video': { videoMode: 'grok' } },
+ }, { target: 'music-video' })).toBe('local');
+ expect(resolveVideoMode(null, { ...grokOff, videoGen: { mode: 'grok' } })).toBe('local');
+ });
+});