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: let a creative commission pin the backend that renders it (#3135)
[._.]/ Adam Eivy1161e8709bc9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d039cfaea1..9a93f50964 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -105,8 +105,17 @@- The chart renders as a labelled, bar-gridded kit sheet in hand-rolled SVG — no engraving library, theme-aware ink in both light and dark, beat boundaries emphasized so a 16th-note row still reads in fours, and each bar scrolling as a unit on a phone. Play mode adds a transport bar: a practice-tempo input + slider (20–320) seeded from the chart's own `tempo:`, percent-of-written buttons (50/75/90/100/110%), a count-in of up to 2 bars, a loop toggle with a from/to bar range, and a metronome click layered over the kit on the same clock. A playhead column tracks the sounding step and the screen stays awake while it plays; space plays/stops, `+`/`-` nudge the tempo, `[`/`]` set the loop ends at the bar you're on.- The kit is synthesized, so nothing is downloaded and no samples ship. The practice tempo is remembered per song on the machine you set it on — it is never written into the record, so it can't sync over a peer's own practice speed. Non-drum songs are untouched: transpose, chord diagrams and autoscroll behave exactly as before, and the transpose/voicing controls simply hide for a kit chart where they'd mean nothing. Pasting a drum chart into the importer auto-selects the format and previews it on the grid, and one example groove ("Example Rock Beat") ships as the format's worked reference — existing installs receive it on upgrade without ever overwriting a copy you've edited or deleted.+<<<<<<< HEAD## Sprite Manager corrections- **[issue-3134] Every sprite regeneration surface now takes a correction note, so a bad result can be described instead of re-rolled and hoped over.** The turnaround sheet and the 7 directional anchors already worked this way; the main reference, a place/object's ambient reference, and the walk-cycle / scanner-action / ambient-loop videos could only be re-rolled blind — same prompt, new random seed. Each of those five now shows the same optional note ("the legs barely lift", "the trunk leans too far right") and appends it to the prompt as an explicit, high-priority correction on the next Generate. Leaving it empty is byte-for-byte the regenerate you get today, so nothing changes until you type something.- The note lives in one place per sprite, so one typed on a workflow panel is visible on the matching asset card and rides whichever Regenerate you click. Notes are scoped to the thing they describe, though: a still-image fix written against the east anchor never leaks into the east walk video's prompt, and the ambient reference and its loop keep separate notes. Notes reset when you switch sprites.- The correction that produced a given re-roll is recorded with it and shown in the existing prompt provenance (Asset Inspector / lightbox), matching how anchors and the turnaround already behave. A scanner clip's provenance also now rebuilds from the scanner's own prompt rather than reporting the walk prompt it was never rendered with.+=======+## Creative Commissions++- **[issue-3135] A creative commission can now pin the backend that actually renders it — local diffusion, Codex, or Grok — instead of taking whatever the planner happened to pick.** Which backend a scheduled image/video commission rendered on used to be an accidental side effect: the Creative Director's planner LLM writes the render job's parameters freehand, it never set a backend, and so every commission silently landed on local diffusion no matter what you wanted. Image commissions now carry an **Image backend** picker (Auto / Local diffusion / Codex / Grok), video commissions a **Video backend** picker (Auto / Local / Grok), and a music video carries both; pinning Local also lets you name the model to render with. The pin travels to the render itself and overrides the planner, so "this one always renders on Grok" actually holds.+- **Auto is the default and changes nothing.** Every existing commission reads as Auto and resolves your install's Image Gen default exactly as before — same backend, same parameters, byte for byte. Nothing needs migrating and no commission starts spending remote quota it wasn't already spending. Enabling Grok for *images* likewise never redirects your unpinned *video* renders to it, since a Grok clip costs remote quota and only comes in 6- or 10-second lengths.+- A pin is re-checked against your live settings each run rather than trusted blindly: if you later turn off the Codex or Grok toggle in Settings, the affected commission quietly falls back to a backend that works instead of failing every nightly fire. The form says so too — a pin whose backend is currently disabled is flagged in place rather than silently dropped, so you can see why your choice stopped applying.+- Commissions federate, so the pin syncs across your machines; the commission sync version was raised to keep an older peer from silently stripping the field and pushing the un-pinned version back.+>>>>>>> f8a772e60 (feat: let a creative commission pin the backend that renders it (#3135))diff --git a/client/src/components/creative-commission/CommissionConfigForm.jsx b/client/src/components/creative-commission/CommissionConfigForm.jsxindex 8995baa6e5..c432367af2 100644--- a/client/src/components/creative-commission/CommissionConfigForm.jsx+++ b/client/src/components/creative-commission/CommissionConfigForm.jsx@@ -14,10 +14,12 @@import { useEffect, useMemo, useState } from 'react';import ProviderModelSelector from '../ProviderModelSelector';import { isProcessProvider } from '../../utils/providers';-import { getProviders } from '../../services/api';+import { getProviders, getSettings, listImageModels, listVideoModels } from '../../services/api';+import { deriveAvailableBackends } from '../../lib/imageGenBackends';import {WEEKDAYS, inputCls, labelCls, describeSchedule,ABILITY_OPTIONS, GENERATION_FIELDS_BY_ABILITY, mergeGenerationForAbility,+ backendFieldsForAbility, RENDER_BACKEND_AUTO,} from './commissionForm.js';export default function CommissionConfigForm({ form, patchForm, saving, onSave, onCancel, saveLabel = 'Save' }) {@@ -183,6 +185,9 @@ export default function CommissionConfigForm({ form, patchForm, saving, onSave,{/* Generation — fields adapt to the selected output type (#2769) */}<GenerationSection ability={form.targetAbility} generation={form.generation} patchForm={patchForm} />+ {/* Render backend — which image/video backend actually renders (#3135) */}+ <RenderBackendSection ability={form.targetAbility} generation={form.generation} patchForm={patchForm} />+{/* AI provider & model — who processes this commission */}<section className="space-y-2 border-t border-port-border pt-4"><h3 className="text-sm font-semibold text-gray-200">AI provider & model</h3>@@ -237,7 +242,11 @@ export default function CommissionConfigForm({ form, patchForm, saving, onSave,// share one layout — a select for enum fields, a bounded number input otherwise.// The label names the type so it's clear which output these knobs drive.function GenerationSection({ ability, generation, patchForm }) {- const fields = GENERATION_FIELDS_BY_ABILITY[ability] || GENERATION_FIELDS_BY_ABILITY.video;+ // Backend pins (#3135) are rendered by RenderBackendSection — they need a+ // conditional model picker and live availability data the generic grid has no+ // room for, so they're excluded here rather than squeezed into a bare select.+ const fields = (GENERATION_FIELDS_BY_ABILITY[ability] || GENERATION_FIELDS_BY_ABILITY.video)+ .filter((f) => f.type !== 'backend');const abilityLabel = (ABILITY_OPTIONS.find((o) => o.id === ability) || ABILITY_OPTIONS[0]).label;return (<section className="space-y-3 border-t border-port-border pt-4">@@ -277,6 +286,123 @@ function GenerationSection({ ability, generation, patchForm }) {);}+// Which backend a mode's model picker reads its catalog from.+const MODEL_LOADERS = { image: listImageModels, video: listVideoModels };++/**+ * Render-backend pin for the selected output type (#3135) — a mode selector plus+ * a conditional model picker, mirroring the UX already shipped for pipeline+ * visual stages (VisualGenSettings.jsx). Rendered only for abilities that+ * actually enqueue that kind of render (image / video / music-video); `music` and+ * `series` declare no backend fields, so the whole section disappears.+ *+ * 'Auto' is the default and a true no-op: the scheduled fire resolves the+ * install-wide default exactly as it did before pins existed.+ */+function RenderBackendSection({ ability, generation, patchForm }) {+ const fields = backendFieldsForAbility(ability);+ const [settings, setSettings] = useState(null);+ const [models, setModels] = useState({ image: [], video: [] });++ useEffect(() => {+ let cancelled = false;+ // Silent: an unavailable list degrades to "Auto only + a Default model+ // option", which is still a usable form — no toast for that.+ getSettings({ silent: true })+ .then((s) => { if (!cancelled) setSettings(s); })+ .catch(() => { /* availability hints omitted */ });+ return () => { cancelled = true; };+ }, []);++ // Load a catalog per model-bearing kind actually on screen, so a music/series+ // commission fetches nothing and an image commission never pulls the video list.+ const modelKinds = fields.map((f) => f.modelKind).join(',');+ useEffect(() => {+ let cancelled = false;+ for (const kind of modelKinds ? modelKinds.split(',') : []) {+ MODEL_LOADERS[kind]?.({ silent: true })+ .then((list) => {+ if (!cancelled) setModels((prev) => ({ ...prev, [kind]: Array.isArray(list) ? list : [] }));+ })+ .catch(() => { /* picker falls back to the default-only option */ });+ }+ return () => { cancelled = true; };+ }, [modelKinds]);++ // Which backends this install can actually render on. Used to warn (not to+ // hide) — a pin for a currently-disabled backend must stay visible and editable,+ // otherwise the user can't tell why their choice stopped applying.+ const availableIds = useMemo(+ () => new Set(deriveAvailableBackends(settings, { excludeExternal: true }).map((b) => b.id)),+ [settings],+ );++ if (fields.length === 0) return null;++ return (+ <section className="space-y-3 border-t border-port-border pt-4">+ <h3 className="text-sm font-semibold text-gray-200">Render backend</h3>+ <p className="text-xs text-gray-500">+ Which backend actually renders each run. Leave on <strong className="text-gray-400">Auto</strong> to+ follow your install's Image Gen default.+ </p>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ {fields.map((field) => {+ const modeId = `commission-gen-${field.key}`;+ const modelId = `commission-gen-${field.modelKey}`;+ const mode = generation?.[field.key] || RENDER_BACKEND_AUTO;+ const showModel = field.modelModes.includes(mode);+ const list = models[field.modelKind] || [];+ // Only warn about a cloud CLI the settings say is off. `local` is+ // reported unavailable purely for a missing pythonPath, which the+ // local-model picker below already makes obvious.+ const unavailable = mode !== RENDER_BACKEND_AUTO && mode !== 'local' && settings && !availableIds.has(mode);+ return (+ <div key={field.key} className="space-y-2">+ <div>+ <label className={labelCls} htmlFor={modeId}>{field.label}</label>+ <select+ id={modeId}+ className={inputCls}+ value={mode}+ onChange={(e) => {+ const next = e.target.value;+ patchForm(['generation', field.key], next);+ // Drop a stale model id when moving to a backend that has no+ // model knob, so the form never shows a pin that can't apply.+ if (!field.modelModes.includes(next)) patchForm(['generation', field.modelKey], null);+ }}+ >+ {field.options.map(([val, lbl]) => <option key={val} value={val}>{lbl}</option>)}+ </select>+ {unavailable && (+ <p className="text-xs text-port-warning mt-1">+ This backend is disabled in Settings → Image Gen — runs fall back to the default until you enable it.+ </p>+ )}+ </div>+ {showModel && (+ <div>+ <label className={labelCls} htmlFor={modelId}>{field.modelLabel}</label>+ <select+ id={modelId}+ className={inputCls}+ value={generation?.[field.modelKey] || ''}+ onChange={(e) => patchForm(['generation', field.modelKey], e.target.value || null)}+ >+ <option value="">Default ({list.find((m) => m.default)?.name || list[0]?.name || 'install default'})</option>+ {list.map((m) => <option key={m.id} value={m.id}>{m.name || m.id}</option>)}+ </select>+ </div>+ )}+ </div>+ );+ })}+ </div>+ </section>+ );+}+// AI provider/model picker for the commission's CD cognitive stages (treatment +// plan). Mirrors SeriesLlmPicker: fetches the provider list, drives the shared// ProviderModelSelector, and reports changes up to form state via `onChange`.diff --git a/client/src/components/creative-commission/commissionForm.js b/client/src/components/creative-commission/commissionForm.jsindex 16a1cbfd63..a1e0f616e4 100644--- a/client/src/components/creative-commission/commissionForm.js+++ b/client/src/components/creative-commission/commissionForm.js@@ -26,6 +26,42 @@ const QUALITY_FIELD = { key: 'quality', label: 'Quality', type: 'select', optionconst ASPECT_FIELD = { key: 'aspectRatio', label: 'Aspect ratio', type: 'select', options: [['16:9', '16:9'], ['9:16', '9:16'], ['1:1', '1:1']] };const DURATION_FIELD = { key: 'targetDurationSeconds', label: 'Duration (sec)', type: 'number', min: 5, max: 600 };+// Render-backend pin (#3135) — the client mirror of the server's+// CREATIVE_COMMISSION_IMAGE_MODES / _VIDEO_MODES. `auto` is the default and means+// "no pin": the scheduled fire resolves the install-wide default exactly as it did+// before the pin existed. `type: 'backend'` fields render as a mode picker plus a+// conditional model picker (see CommissionConfigForm's RenderBackendSection),+// mirroring the pipeline's VisualGenSettings UX; the generic field renderer in+// GenerationSection skips them.+export const RENDER_BACKEND_AUTO = 'auto';++export const IMAGE_BACKEND_OPTIONS = [+ [RENDER_BACKEND_AUTO, 'Auto (install default)'],+ ['local', 'Local diffusion'],+ ['codex', 'Codex'],+ ['grok', 'Grok'],+];++export const VIDEO_BACKEND_OPTIONS = [+ [RENDER_BACKEND_AUTO, 'Auto (install default)'],+ ['local', 'Local (MLX)'],+ ['grok', 'Grok'],+];++// `modelKind` names which media-model catalog the conditional model picker reads,+// and `modelModes` lists the modes that HAVE a model knob — the cloud CLIs pick+// their own model, so the picker only appears for local.+const IMAGE_BACKEND_FIELD = {+ key: 'imageMode', modelKey: 'imageModelId', label: 'Image backend', type: 'backend',+ options: IMAGE_BACKEND_OPTIONS, modelKind: 'image', modelModes: ['local'],+ modelLabel: 'Local image model',+};+const VIDEO_BACKEND_FIELD = {+ key: 'videoMode', modelKey: 'videoModelId', label: 'Video backend', type: 'backend',+ options: VIDEO_BACKEND_OPTIONS, modelKind: 'video', modelModes: ['local'],+ modelLabel: 'Local video model',+};+// Per-ability generation field descriptors — the client mirror of the server's// GENERATION_KEY_DEFS / ABILITY_GENERATION_SPEC (server/lib/creativeCommissionValidation.js).// The config form renders exactly these fields for the selected type. There is no@@ -34,10 +70,10 @@ const DURATION_FIELD = { key: 'targetDurationSeconds', label: 'Duration (sec)',// client-internal invariant (every field has a matching default), not server↔client// parity.export const GENERATION_FIELDS_BY_ABILITY = {- video: [QUALITY_FIELD, ASPECT_FIELD, DURATION_FIELD],- image: [QUALITY_FIELD, ASPECT_FIELD, { key: 'imageCount', label: 'Image count', type: 'number', min: 1, max: 6 }],+ video: [QUALITY_FIELD, ASPECT_FIELD, DURATION_FIELD, VIDEO_BACKEND_FIELD],+ image: [QUALITY_FIELD, ASPECT_FIELD, { key: 'imageCount', label: 'Image count', type: 'number', min: 1, max: 6 }, IMAGE_BACKEND_FIELD],music: [{ key: 'lengthSeconds', label: 'Length (sec)', type: 'number', min: 5, max: 600 }],- 'music-video': [QUALITY_FIELD, ASPECT_FIELD, DURATION_FIELD],+ 'music-video': [QUALITY_FIELD, ASPECT_FIELD, DURATION_FIELD, VIDEO_BACKEND_FIELD, IMAGE_BACKEND_FIELD],series: [{ key: 'episodeCount', label: 'Episodes', type: 'number', min: 1, max: 6 }],};@@ -45,13 +81,22 @@ export const GENERATION_FIELDS_BY_ABILITY = {// project a stored record into the form and to seed the fields when the user// switches output type.export const GENERATION_DEFAULTS_BY_ABILITY = {- video: { quality: 'standard', aspectRatio: '16:9', targetDurationSeconds: 10 },- image: { quality: 'standard', aspectRatio: '16:9', imageCount: 1 },+ video: { quality: 'standard', aspectRatio: '16:9', targetDurationSeconds: 10, videoMode: RENDER_BACKEND_AUTO, videoModelId: null },+ image: { quality: 'standard', aspectRatio: '16:9', imageCount: 1, imageMode: RENDER_BACKEND_AUTO, imageModelId: null },music: { lengthSeconds: 30 },- 'music-video': { quality: 'standard', aspectRatio: '16:9', targetDurationSeconds: 10 },+ 'music-video': {+ quality: 'standard', aspectRatio: '16:9', targetDurationSeconds: 10,+ videoMode: RENDER_BACKEND_AUTO, videoModelId: null, imageMode: RENDER_BACKEND_AUTO, imageModelId: null,+ },series: { episodeCount: 1 },};+// The render-backend descriptors for an ability, in field order. Drives the+// dedicated backend section; the generic field grid skips `type: 'backend'`.+export function backendFieldsForAbility(ability) {+ return (GENERATION_FIELDS_BY_ABILITY[abilityOr(ability)] || []).filter((f) => f.type === 'backend');+}+function abilityOr(ability) {return GENERATION_DEFAULTS_BY_ABILITY[ability] ? ability : 'video';}@@ -86,6 +131,19 @@ export function generationToPayload(ability, generation) {const out = {};for (const field of fields) {const v = generation?.[field.key];+ if (field.type === 'backend') {+ // A backend descriptor owns TWO record keys. The model id only travels when+ // the pinned mode actually has a model knob — otherwise a stale id left over+ // from a previous local pin would ride along on a cloud pin and confuse the+ // stored record. Send `null` (not omit) so clearing a pin clears the id too:+ // the server merges `generation` shallowly, and an omitted key would preserve+ // the stale value (the absent-vs-empty rule).+ const mode = v || RENDER_BACKEND_AUTO;+ const model = generation?.[field.modelKey];+ out[field.key] = mode;+ out[field.modelKey] = field.modelModes.includes(mode) && model ? model : null;+ continue;+ }out[field.key] = field.type === 'number' ? Number(v) : v;}return out;diff --git a/client/src/components/creative-commission/commissionForm.test.js b/client/src/components/creative-commission/commissionForm.test.jsindex 612cc87e84..70df515048 100644--- a/client/src/components/creative-commission/commissionForm.test.js+++ b/client/src/components/creative-commission/commissionForm.test.js@@ -4,6 +4,7 @@ import {describeSchedule, describeAssignment,ABILITY_OPTIONS, GENERATION_FIELDS_BY_ABILITY, GENERATION_DEFAULTS_BY_ABILITY,generationToForm, mergeGenerationForAbility, generationToPayload,+ backendFieldsForAbility, RENDER_BACKEND_AUTO,} from './commissionForm.js';describe('commissionForm helpers', () => {@@ -16,7 +17,10 @@ describe('commissionForm helpers', () => {expect(f.brief).toEqual({ intent: '', genre: '', styleSpec: '' });expect(f.schedule.kind).toBe('DAILY');expect(f.schedule.atLocalTime).toBe('02:00');- expect(f.generation).toEqual({ quality: 'standard', aspectRatio: '16:9', targetDurationSeconds: 10 });+ expect(f.generation).toEqual({+ quality: 'standard', aspectRatio: '16:9', targetDurationSeconds: 10,+ videoMode: 'auto', videoModelId: null,+ });expect(f.assignment).toEqual({ providerId: '', model: '' });expect(f.feedbackWindow).toBe(5);});@@ -133,9 +137,13 @@ describe('commissionForm helpers', () => {});it('generationToForm fills the ability defaults and keeps only that ability keys', () => {- expect(generationToForm('image', {})).toEqual({ quality: 'standard', aspectRatio: '16:9', imageCount: 1 });+ expect(generationToForm('image', {})).toEqual({+ quality: 'standard', aspectRatio: '16:9', imageCount: 1, imageMode: 'auto', imageModelId: null,+ });// A stored video key is ignored when projecting as image.- expect(generationToForm('image', { imageCount: 4, targetDurationSeconds: 30 })).toEqual({ quality: 'standard', aspectRatio: '16:9', imageCount: 4 });+ expect(generationToForm('image', { imageCount: 4, targetDurationSeconds: 30 })).toEqual({+ quality: 'standard', aspectRatio: '16:9', imageCount: 4, imageMode: 'auto', imageModelId: null,+ });expect(generationToForm('music', { lengthSeconds: 60 })).toEqual({ lengthSeconds: 60 });});@@ -148,7 +156,7 @@ describe('commissionForm helpers', () => {it('mergeGenerationForAbility carries overlapping keys across a type switch', () => {// video → image keeps quality/aspectRatio, seeds imageCount default, drops duration.expect(mergeGenerationForAbility('image', { quality: 'high', aspectRatio: '9:16', targetDurationSeconds: 20 }))- .toEqual({ quality: 'high', aspectRatio: '9:16', imageCount: 1 });+ .toEqual({ quality: 'high', aspectRatio: '9:16', imageCount: 1, imageMode: 'auto', imageModelId: null });// image → music keeps nothing overlapping, just the music default.expect(mergeGenerationForAbility('music', { imageCount: 4 })).toEqual({ lengthSeconds: 30 });});@@ -156,7 +164,7 @@ describe('commissionForm helpers', () => {it('generationToPayload emits only the ability keys and coerces numbers', () => {// number inputs arrive as strings from the DOM.expect(generationToPayload('image', { quality: 'standard', aspectRatio: '1:1', imageCount: '3' }))- .toEqual({ quality: 'standard', aspectRatio: '1:1', imageCount: 3 });+ .toEqual({ quality: 'standard', aspectRatio: '1:1', imageCount: 3, imageMode: 'auto', imageModelId: null });expect(generationToPayload('music', { lengthSeconds: '45' })).toEqual({ lengthSeconds: 45 });});@@ -164,7 +172,16 @@ describe('commissionForm helpers', () => {const form = toForm({ name: 'Daily Stills', targetAbility: 'image', brief: { intent: 'x' }, generation: { imageCount: 2 } });const payload = toPayload(form);expect(payload.targetAbility).toBe('image');- expect(payload.generation).toEqual({ quality: 'standard', aspectRatio: '16:9', imageCount: 2 });+ expect(payload.generation).toEqual({+ quality: 'standard', aspectRatio: '16:9', imageCount: 2, imageMode: 'auto', imageModelId: null,+ });+ });++ it('validateForm ignores the non-numeric backend fields', () => {+ // A backend descriptor has no min/max — the numeric guard must skip it or+ // every image commission would fail validation on `imageMode`.+ const form = { ...blankForm(), name: 'x', brief: { intent: 'y' }, targetAbility: 'image', generation: generationToForm('image', {}) };+ expect(validateForm(form)).toBeNull();});it('validateForm rejects an out-of-range per-ability number', () => {@@ -177,4 +194,66 @@ describe('commissionForm helpers', () => {expect(validateForm(clearedMusic)).toMatch(/Length/);});});++ describe('render-backend pin (#3135)', () => {+ it('declares backend fields only for the abilities that enqueue that render kind', () => {+ expect(backendFieldsForAbility('image').map((f) => f.key)).toEqual(['imageMode']);+ expect(backendFieldsForAbility('video').map((f) => f.key)).toEqual(['videoMode']);+ // A music video renders both a video and (potentially) stills for it.+ expect(backendFieldsForAbility('music-video').map((f) => f.key)).toEqual(['videoMode', 'imageMode']);+ expect(backendFieldsForAbility('music')).toEqual([]);+ expect(backendFieldsForAbility('series')).toEqual([]);+ });++ it('defaults to auto with no model id — the pre-#3135 behavior', () => {+ const f = toForm({ targetAbility: 'image', brief: { intent: 'x' } });+ expect(f.generation.imageMode).toBe(RENDER_BACKEND_AUTO);+ expect(f.generation.imageModelId).toBeNull();+ expect(toPayload(f).generation.imageMode).toBe('auto');+ expect(toPayload(f).generation.imageModelId).toBeNull();+ });++ it('projects a stored pin (mode + model) back onto the form', () => {+ const f = toForm({+ targetAbility: 'image', brief: { intent: 'x' },+ generation: { imageMode: 'local', imageModelId: 'example-model' },+ });+ expect(f.generation.imageMode).toBe('local');+ expect(f.generation.imageModelId).toBe('example-model');+ });++ it('sends the model id for a model-bearing backend', () => {+ const payload = generationToPayload('image', {+ quality: 'standard', aspectRatio: '16:9', imageCount: 1, imageMode: 'local', imageModelId: 'example-model',+ });+ expect(payload.imageMode).toBe('local');+ expect(payload.imageModelId).toBe('example-model');+ });++ it('nulls a stale model id when the pinned backend has no model knob', () => {+ // Cloud CLIs pick their own model — a leftover local model id must not ride+ // along, and must be sent as null (not omitted) so the server merge clears it.+ const payload = generationToPayload('image', {+ quality: 'standard', aspectRatio: '16:9', imageCount: 1, imageMode: 'grok', imageModelId: 'example-model',+ });+ expect(payload.imageMode).toBe('grok');+ expect(payload.imageModelId).toBeNull();+ expect('imageModelId' in payload).toBe(true);+ });++ it('emits both video and image pins for a music-video commission', () => {+ const payload = generationToPayload('music-video', {+ quality: 'standard', aspectRatio: '16:9', targetDurationSeconds: 10,+ videoMode: 'grok', videoModelId: null, imageMode: 'local', imageModelId: 'example-model',+ });+ expect(payload.videoMode).toBe('grok');+ expect(payload.imageMode).toBe('local');+ expect(payload.imageModelId).toBe('example-model');+ });++ it('never emits a backend key for an ability that has none', () => {+ const payload = generationToPayload('music', { lengthSeconds: 30, imageMode: 'grok' });+ expect(payload).toEqual({ lengthSeconds: 30 });+ });+ });});diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.jsindex 672ecf5907..200010c15f 100644--- a/client/src/services/apiImageVideo.js+++ b/client/src/services/apiImageVideo.js@@ -3,7 +3,7 @@ import { request, API_BASE, maybeRedirectToLogin } from './apiCore.js';// Image gen — local backend extras (gallery, models, LoRAs, cancel, delete).// generateImage / getImageGenStatus / generateAvatar live in apiSystem.js for// backward compatibility with existing call sites.-export const listImageModels = () => request('/image-gen/models');+export const listImageModels = (options) => request('/image-gen/models', options);// Per-model download status: `[{ id, repo, cached, sizeBytes }]`. Drives the// inline Available/Download badge on the image gen form.export const getImageModelStatuses = () => request('/image-gen/models/status', { silent: true });diff --git a/server/lib/creativeCommissionValidation.js b/server/lib/creativeCommissionValidation.jsindex 2bdb5fb8c6..3178b2508c 100644--- a/server/lib/creativeCommissionValidation.js+++ b/server/lib/creativeCommissionValidation.js@@ -1,4 +1,6 @@import { z } from 'zod';+import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';+import { VIDEO_GEN_MODES } from '../services/videoGen/modes.js';// =============================================================================// CREATIVE COMMISSION SCHEMAS (Autonomous Creation Engine — #2657, Phase 1)@@ -32,6 +34,38 @@ export const CREATIVE_COMMISSION_SCHEDULE_KINDS = Object.freeze(['DAILY', 'WEEKLexport const CREATIVE_COMMISSION_QUALITIES = Object.freeze(['draft', 'standard', 'high']);export const CREATIVE_COMMISSION_ASPECT_RATIOS = Object.freeze(['16:9', '9:16', '1:1']);+// Per-commission render-backend pin (#3135). Before this, which backend actually+// rendered a commission's image/video was an accidental side effect of whatever+// the Creative Director planner LLM happened to write into the job params — in+// practice always local, because nothing ever set `params.mode`. These enums let+// a commission SAY "always render on Grok" (or Codex, or local) and have the+// scheduled fire honor it.+//+// `AUTO` is the default and the no-op: it means "resolve at fire time the way+// this install already would" (settings.imageGen.mode / the local video default),+// so an existing commission that never sets the field behaves exactly as before.+// It is deliberately NOT a member of the backend enums — it is the absence of a+// pin, mirroring the `'auto'` sentinel the pipeline visual stages already ship+// (client/src/components/pipeline/stages/VisualGenSettings.jsx).+export const COMMISSION_RENDER_BACKEND_AUTO = 'auto';++// Image backends a commission may pin: the queueable image modes (local / codex+// / grok — `external` never queues) plus the auto sentinel. Derived from+// QUEUEABLE_IMAGE_MODES so a new backend needs no edit here.+export const CREATIVE_COMMISSION_IMAGE_MODES = Object.freeze([+ COMMISSION_RENDER_BACKEND_AUTO, ...QUEUEABLE_IMAGE_MODES,+]);++// Video backends a commission may pin: local (MLX runtimes) or grok, plus auto.+export const CREATIVE_COMMISSION_VIDEO_MODES = Object.freeze([+ COMMISSION_RENDER_BACKEND_AUTO, ...VIDEO_GEN_MODES,+]);++// A model id is a free string (the media-models registry is user-editable, so an+// enum here would reject a legitimately-installed model). Bounded like the+// existing `generation.model`.+export const COMMISSION_RENDER_MODEL_MAX = 64;+// Per-KEY generation descriptor — the SINGLE SOURCE OF TRUTH for a generation// param's type, bounds, and default. Everything else derives from this: the Zod// superset (`creativeCommissionGenerationSchema`), the per-ability key lists +@@ -40,6 +74,10 @@ export const CREATIVE_COMMISSION_ASPECT_RATIOS = Object.freeze(['16:9', '9:16',// the adapter AND the client) is what stops the four-way drift. The client// (commissionForm.js) mirrors these values in its own package — kept in sync by// hand; there is no cross-package import.+// `type: 'id'` is a nullable free-string model id: absent/blank normalizes to+// `null` (= "the install's default model"), which is why its `default` is null+// rather than a string. Distinct from the `enum`/`int` numeric-or-member kinds so+// the Zod builder and the adapter coercion both stay data-driven.export const GENERATION_KEY_DEFS = Object.freeze({quality: { type: 'enum', values: CREATIVE_COMMISSION_QUALITIES, default: 'standard' },aspectRatio: { type: 'enum', values: CREATIVE_COMMISSION_ASPECT_RATIOS, default: '16:9' },@@ -47,16 +85,35 @@ export const GENERATION_KEY_DEFS = Object.freeze({imageCount: { type: 'int', min: 1, max: 6, default: 1 },lengthSeconds: { type: 'int', min: 5, max: 600, default: 30 },episodeCount: { type: 'int', min: 1, max: 6, default: 1 },+ // Render-backend pin (#3135) — `auto` = no pin (today's behavior).+ imageMode: { type: 'enum', values: CREATIVE_COMMISSION_IMAGE_MODES, default: COMMISSION_RENDER_BACKEND_AUTO },+ videoMode: { type: 'enum', values: CREATIVE_COMMISSION_VIDEO_MODES, default: COMMISSION_RENDER_BACKEND_AUTO },+ // Optional model id, only meaningful when the matching mode is pinned to a+ // backend that HAS a model knob (local diffusion / local video runtimes; the+ // cloud CLIs pick their own model). null = the install default.+ //+ // NOT a replacement for the universal `generation.model` below it: that one maps+ // onto the CD project's `modelId` (the LTX variant the legacy treatment/scene+ // flow renders with, `sceneRunner.js`) and is left untouched by #3135. These two+ // are the PLAN-driven path's per-backend pins, which the scene flow never reads.+ imageModelId: { type: 'id', max: COMMISSION_RENDER_MODEL_MAX, default: null },+ videoModelId: { type: 'id', max: COMMISSION_RENDER_MODEL_MAX, default: null },});// Which keys each output type carries (the universal `model` is added separately// — every type accepts an optional engine/model override). The adapter fills// these keys' defaults and preserves only them.+//+// The backend pins (#3135) are scoped to the abilities that actually enqueue that+// kind of render: `imageMode` on `image`, `videoMode` on `video`, and BOTH on+// `music-video` (its plan renders a video, and the planner may render stills for+// it too). `music` and `series` carry neither — a series' per-issue renders are+// pinned on the pipeline series/stage records, not here.const ABILITY_GENERATION_KEYS = Object.freeze({- video: ['quality', 'aspectRatio', 'targetDurationSeconds'],- image: ['quality', 'aspectRatio', 'imageCount'],+ video: ['quality', 'aspectRatio', 'targetDurationSeconds', 'videoMode', 'videoModelId'],+ image: ['quality', 'aspectRatio', 'imageCount', 'imageMode', 'imageModelId'],music: ['lengthSeconds'],- 'music-video': ['quality', 'aspectRatio', 'targetDurationSeconds'],+ 'music-video': ['quality', 'aspectRatio', 'targetDurationSeconds', 'videoMode', 'videoModelId', 'imageMode', 'imageModelId'],series: ['episodeCount'],});@@ -79,10 +136,12 @@ export function generationKeysForAbility(ability) {// Build a Zod field for one generation-key descriptor (optional in the superset;// per-ability strictness is applied by the create-path superRefine, not here).+// `id` fields accept null so a client can CLEAR a pinned model id explicitly+// (the absent-vs-empty distinction: absent preserves, null clears).function generationFieldSchema(def) {- return def.type === 'enum'- ? z.enum(def.values).optional()- : z.number().int().min(def.min).max(def.max).optional();+ if (def.type === 'enum') return z.enum(def.values).optional();+ if (def.type === 'id') return z.string().trim().max(def.max).nullable().optional();+ return z.number().int().min(def.min).max(def.max).optional();}export const COMMISSION_NAME_MAX = 200;diff --git a/server/lib/creativeDirectorValidation.js b/server/lib/creativeDirectorValidation.jsindex ac284e1e1e..8d6884024e 100644--- a/server/lib/creativeDirectorValidation.js+++ b/server/lib/creativeDirectorValidation.js@@ -90,6 +90,30 @@ export const creativeDirectorModelOverridesSchema = z.object({evaluation: creativeDirectorStagePinSchema.optional(),}).strict();+// Per-project RENDER-backend pin (#3135) — which image/video backend the+// project's enqueued media jobs actually render on (local diffusion / Codex+// imagegen / Grok), as opposed to `modelOverrides` above, which pins the LLM that+// *thinks*. Set from a creative commission's `generation.imageMode`/`.videoMode`+// (the pin has to ride the project because the planner's enqueue tool only sees+// `ctx.projectId`); a hand-made project leaves it null and the enqueue resolves+// the install-wide default exactly as before.+//+// Values stay permissive strings rather than a re-typed enum: the forcing step in+// `creative/tools/media.js` validates the mode against the live backend enums ++// enable toggles at dispatch (`resolveQueueImageMode` / `resolveVideoMode`), so an+// unusable pin degrades to the default instead of failing a render. Additive on+// the project record (round-trips through the JSONB `data` column verbatim), so+// it needs no `creativeDirectorProjects` schema-version bump.+const creativeDirectorRenderPinSchema = z.object({+ mode: z.string().max(32).nullable().optional(),+ modelId: z.string().max(64).nullable().optional(),+}).strict();++export const creativeDirectorRenderBackendSchema = z.object({+ image: creativeDirectorRenderPinSchema.optional(),+ video: creativeDirectorRenderPinSchema.optional(),+}).strict();+export const creativeDirectorProjectCreateSchema = z.object({name: z.string().min(1).max(200),aspectRatio: creativeDirectorAspectRatioSchema,@@ -124,6 +148,9 @@ export const creativeDirectorProjectCreateSchema = z.object({// Optional per-project provider/model pins for the treatment/plan/evaluation// stages. Absent → every stage inherits the global AI Assignment.modelOverrides: creativeDirectorModelOverridesSchema.optional(),+ // Optional per-project image/video RENDER-backend pin (#3135). Absent → each+ // enqueued media job resolves the install-wide default.+ renderBackend: creativeDirectorRenderBackendSchema.nullable().optional(),});// Autonomous auto-cast (#1810). `types` narrows the catalog search to a set ofdiff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 572b57d14e..1a02bd335d 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -450,7 +450,15 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// receive — and could push the video-shaped downgrade back via LWW. The bump// gates mixed-version transfers of this category so a v1 peer never mangles a v2// brief (compareSchemaVersions marks a v2 sender "ahead" of a v1 receiver).- creativeCommissions: 2,+ // v3 = per-commission render-backend pin (#3135): `generation` gained+ // `imageMode`/`videoMode` (+ optional `imageModelId`/`videoModelId`), naming the+ // backend (local diffusion / Codex / Grok) a scheduled fire must render on.+ // Exactly the #2769 failure mode: `generation` is a FEDERATED field, and a v2+ // peer's `ABILITY_GENERATION_KEYS` doesn't list these keys — its+ // `sanitizeGenerationFor` keeps only the keys it knows, so it would silently+ // strip the user's pinned backend on receive and then push the un-pinned+ // downgrade back via LWW.+ creativeCommissions: 3,// v1 = standalone media-library federation (#1566). NOT a record kind — it's// the wire contract for the library-level asset manifest a full-sync peer// advertises at GET /api/peer-sync/library-manifest. The receiver-pull sweepdiff --git a/server/routes/creativeCommissions.test.js b/server/routes/creativeCommissions.test.jsindex 20d0c71c7f..95c2da351d 100644--- a/server/routes/creativeCommissions.test.js+++ b/server/routes/creativeCommissions.test.js@@ -102,6 +102,52 @@ describe('POST /api/creative-commission', () => {expect(svc.createCommission).not.toHaveBeenCalled();});+ it('accepts an image-backend pin with a model id (#3135)', async () => {+ svc.createCommission.mockResolvedValue({ id: 'commission-3', name: 'Daily Stills' });+ const res = await request(buildApp()).post('/api/creative-commission')+ .send({ ...validBody(), targetAbility: 'image', generation: { imageMode: 'grok', imageModelId: null } });+ expect(res.status).toBe(201);+ expect(svc.createCommission).toHaveBeenCalledWith(expect.objectContaining({+ generation: expect.objectContaining({ imageMode: 'grok', imageModelId: null }),+ }));+ });++ it('accepts a video-backend pin on a video commission (#3135)', async () => {+ svc.createCommission.mockResolvedValue({ id: 'commission-4' });+ const res = await request(buildApp()).post('/api/creative-commission')+ .send({ ...validBody(), targetAbility: 'video', generation: { videoMode: 'local', videoModelId: 'example-model' } });+ expect(res.status).toBe(201);+ });++ it('rejects an unknown render backend with 400 (#3135)', async () => {+ const res = await request(buildApp()).post('/api/creative-commission')+ .send({ ...validBody(), targetAbility: 'image', generation: { imageMode: 'midjourney' } });+ expect(res.status).toBe(400);+ expect(svc.createCommission).not.toHaveBeenCalled();+ });++ it('rejects a video-backend pin on an IMAGE commission with 400 (#3135)', async () => {+ // videoMode is not an image knob — the per-ability superRefine catches it.+ const res = await request(buildApp()).post('/api/creative-commission')+ .send({ ...validBody(), targetAbility: 'image', generation: { videoMode: 'grok' } });+ expect(res.status).toBe(400);+ expect(svc.createCommission).not.toHaveBeenCalled();+ });++ it('rejects a render-backend pin on a MUSIC commission with 400 (#3135)', async () => {+ const res = await request(buildApp()).post('/api/creative-commission')+ .send({ ...validBody(), targetAbility: 'music', generation: { imageMode: 'grok' } });+ expect(res.status).toBe(400);+ expect(svc.createCommission).not.toHaveBeenCalled();+ });++ it('accepts both pins on a music-video commission (#3135)', async () => {+ svc.createCommission.mockResolvedValue({ id: 'commission-5' });+ const res = await request(buildApp()).post('/api/creative-commission')+ .send({ ...validBody(), targetAbility: 'music-video', generation: { videoMode: 'grok', imageMode: 'codex' } });+ expect(res.status).toBe(201);+ });+it('rejects an invalid IANA timezone with 400 (before it can wedge the scheduler)', async () => {const res = await request(buildApp()).post('/api/creative-commission').send({ ...validBody(), schedule: { kind: 'DAILY', atLocalTime: '02:00', timezone: 'Not/AZone' } });diff --git a/server/services/creative/tools/media.js b/server/services/creative/tools/media.jsindex 1875abca8c..938edfe1d2 100644--- a/server/services/creative/tools/media.js+++ b/server/services/creative/tools/media.js@@ -7,6 +7,10 @@import { z } from 'zod';import { enqueueJob } from '../../mediaJobQueue/index.js';import { ASPECT_PRESETS, QUALITY_PRESETS, presetToRenderParams } from '../../../lib/creativeDirectorPresets.js';+import { getSettings } from '../../settings.js';+import { IMAGE_GEN_MODE, resolveQueueImageMode } from '../../imageGen/modes.js';+import { resolveCloudProviderConfig } from '../../imageGen/cloudProviderConfig.js';+import { VIDEO_GEN_MODE, resolveVideoMode } from '../../videoGen/modes.js';import { COST_RENDER, resolveOwner } from './shared.js';const paramsSchema = z.object({ params: z.record(z.any()).default({}), owner: z.string().optional() });@@ -28,10 +32,7 @@ const paramsSchema = z.object({ params: z.record(z.any()).default({}), owner: z.* unrecognized aspect/quality (hand-edited/legacy project) falls through to the* LLM's params untouched — best-effort, never throws.*/-async function enforceVideoRenderPreset(params, ctx) {- if (!ctx?.projectId) return params;- const { getProject } = await import('../../creativeDirector/local.js');- const project = await getProject(ctx.projectId).catch(() => null);+async function enforceVideoRenderPreset(params, project) {// Only a directive-driven CD project locks a preset; a bare enqueue (no// recognized aspect/quality) keeps the caller's params as-is.if (!project || !ASPECT_PRESETS[project.aspectRatio] || !QUALITY_PRESETS[project.quality]) {@@ -81,6 +82,92 @@ function attachMusicBedTag(params, ctx) {return { ...params, creativeDirectorMusicBed: { projectId: ctx.projectId } };}+/**+ * Force an image/video render onto the project's PINNED render backend (#3135),+ * overriding whatever `mode` the planner LLM authored.+ *+ * Backend dispatch in the media job queue is purely `job.params.mode`-driven+ * (`mediaJobQueue/index.js#getGenModuleForJob`). The planner writes these params+ * freehand and — before #3135 — never set `mode` at all, so every plan-driven+ * render silently landed on local diffusion regardless of the user's intent. A+ * creative commission can now pin the backend per commission+ * (`generation.imageMode` / `.videoMode`); `buildRenderBackendPin` carries it onto+ * the project as `renderBackend`, and this is where it beats the LLM.+ *+ * No pin (the default, and every pre-#3135 project) ⇒ returns `params`+ * UNTOUCHED — not "auto-resolved to something", untouched — so the enqueued job+ * is byte-identical to today and dispatch falls through to the install-wide+ * default the same way it always has.+ *+ * A pin is re-resolved against LIVE settings rather than trusted verbatim: the+ * cloud backends are gated on their `imageGen.<mode>.enabled` toggle, which the+ * user can flip off long after pinning. `resolveQueueImageMode` /+ * `resolveVideoMode` degrade an unusable pin to a usable backend (never throw) —+ * a nightly commission must still produce something rather than failing every+ * fire because a toggle moved. Cloud modes additionally need their provider knob+ * bundle (`codexPath`/`model`/`effort`, `grokPath`/`aspectRatio`) in the job+ * params, since the queue dispatches straight to the provider module and skips+ * the imageGen dispatcher that would otherwise assemble them.+ *+ * Deliberately NOT resolved here: the saved `cleanC2PA`/`denoise` post-processing+ * settings (which `pipeline/visualStageHelpers.js#enqueueImageJob` does resolve,+ * for the same skips-the-dispatcher reason). No planner-enqueued render has ever+ * carried them — pinned or not — so resolving them only on the pinned path would+ * make the same commission post-process differently depending on whether a+ * backend happens to be pinned. Fixing it for BOTH paths would break the "auto is+ * byte-identical" contract this change rests on, so it's a separate concern.+ */+async function enforceRenderBackendPin(kind, params, project) {+ const pin = project?.renderBackend?.[kind];+ if (!pin?.mode) return params;+ const settings = await getSettings().catch(() => null);+ if (!settings) return params;++ if (kind === 'video') {+ const mode = resolveVideoMode(pin.mode, settings);+ if (mode !== VIDEO_GEN_MODE.GROK) {+ // Local video: `params.mode` is the t2v/i2v SEMANTIC for this lane (see+ // videoGen/modes.js), so it must not be stamped with the backend name —+ // absence of the 'grok' discriminator IS "render locally". Only the model+ // pin travels, and only when the planner didn't name one itself.+ return pin.modelId && !params?.modelId ? { ...params, modelId: pin.modelId } : params;+ }+ const grok = settings.imageGen?.grok || {};+ // videoGen/grok.js reads the same `imageGen.grok` slice the image path does+ // (one CLI, one config). `videoMode` carries the semantic the local lane+ // keeps in `mode`, matching what routes/videoGen.js enqueues.+ return {+ ...params,+ mode: VIDEO_GEN_MODE.GROK,+ videoMode: params?.sourceImagePath ? 'image' : 'text',+ grokPath: grok.grokPath,+ ...(grok.aspectRatio ? { aspectRatio: grok.aspectRatio } : {}),+ };+ }++ const mode = resolveQueueImageMode(pin.mode, settings);+ const cloud = resolveCloudProviderConfig(settings, mode);+ if (cloud) return { ...params, ...cloud.jobParams };+ return {+ ...params,+ mode: IMAGE_GEN_MODE.LOCAL,+ pythonPath: settings.imageGen?.local?.pythonPath || null,+ // The planner's own modelId wins if it named one; otherwise the pin's.+ ...(pin.modelId && !params?.modelId ? { modelId: pin.modelId } : {}),+ };+}++// Load the owning CD project ONCE per enqueue — both the video preset+// reconciliation and the render-backend pin read from it, and re-reading would+// double the store round-trips per plan step. Null outside a project context (a+// bare enqueue) or when the read fails: both forcing steps treat that as "no+// project locks anything" and pass the caller's params through.+async function loadOwningProject(ctx) {+ if (!ctx?.projectId) return null;+ const { getProject } = await import('../../creativeDirector/local.js');+ return getProject(ctx.projectId).catch(() => null);+}+const mediaTool = (kind, label) => ({name: `media_enqueue${label}Job`,description: `Enqueue a ${kind} media job. Long-running: returns a job handle; completion arrives via media-job events. Tags the job owner to the calling project.`,@@ -97,8 +184,15 @@ const mediaTool = (kind, label) => ({},execute: async (args, ctx) => {let params = args.params || {};- if (kind === 'video') params = await enforceVideoRenderPreset(params, ctx);- else if (kind === 'audio') params = attachMusicBedTag(params, ctx);+ if (kind === 'audio') {+ params = attachMusicBedTag(params, ctx);+ } else {+ // Image + video both consult the owning project: video for its locked+ // geometry preset, both for a pinned render backend (#3135).+ const project = await loadOwningProject(ctx);+ if (kind === 'video') params = await enforceVideoRenderPreset(params, project);+ params = await enforceRenderBackendPin(kind, params, project);+ }return enqueueJob({ kind, params, owner: resolveOwner(args, ctx) });},});diff --git a/server/services/creative/tools/media.test.js b/server/services/creative/tools/media.test.jsnew file mode 100644index 0000000000..4f2d1fb748--- /dev/null+++ b/server/services/creative/tools/media.test.js@@ -0,0 +1,172 @@+import { describe, it, expect, vi, beforeEach } 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+// `job.params.mode` is the ONLY thing mediaJobQueue routes the backend on.+vi.mock('../../mediaJobQueue/index.js', () => ({ enqueueJob: vi.fn(() => ({ jobId: 'mj-test' })) }));+vi.mock('../../settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));+vi.mock('../../creativeDirector/local.js', () => ({ getProject: vi.fn(async () => null) }));++import { enqueueJob } from '../../mediaJobQueue/index.js';+import { getSettings } from '../../settings.js';+import { getProject } from '../../creativeDirector/local.js';+import { MEDIA_TOOLS } from './media.js';++const tool = (name) => MEDIA_TOOLS.find((t) => t.name === name);+const run = (name, params, ctx = {}) => tool(name).execute({ params }, ctx);+const enqueued = () => enqueueJob.mock.calls.at(-1)[0];++// A project with no locked geometry preset, so enforceVideoRenderPreset is a+// no-op and each test isolates the render-backend pin.+const projectWithPin = (renderBackend) => ({ id: 'cd-1', renderBackend });++beforeEach(() => {+ vi.clearAllMocks();+ getSettings.mockResolvedValue({});+ getProject.mockResolvedValue(null);+});++describe('render-backend pin — the auto/unpinned path is a strict no-op (#3135)', () => {+ it('leaves image params untouched with no owning project', async () => {+ await run('media_enqueueImageJob', { prompt: 'a lighthouse' });+ expect(enqueued().params).toEqual({ prompt: 'a lighthouse' });+ // No project ⇒ no settings read at all.+ expect(getSettings).not.toHaveBeenCalled();+ });++ it('leaves image params untouched when the project has no pin', async () => {+ getProject.mockResolvedValue(projectWithPin(null));+ await run('media_enqueueImageJob', { prompt: 'p' }, { projectId: 'cd-1' });+ expect(enqueued().params).toEqual({ prompt: 'p' });+ expect(getSettings).not.toHaveBeenCalled();+ });++ it('leaves video params untouched when the project has no pin', async () => {+ getProject.mockResolvedValue(projectWithPin(null));+ await run('media_enqueueVideoJob', { prompt: 'p', mode: 'image' }, { projectId: 'cd-1' });+ // The local lane's `mode` is the t2v/i2v SEMANTIC — it must survive untouched.+ expect(enqueued().params).toEqual({ prompt: 'p', mode: 'image' });+ });++ 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' });+ expect(getProject).toHaveBeenCalledTimes(1);+ });+});++describe('render-backend pin — image (#3135)', () => {+ it('forces a codex pin onto the job params, overriding the planner LLM', async () => {+ getSettings.mockResolvedValue({ imageGen: { codex: { enabled: true, codexPath: '/bin/codex', model: 'example-model', effort: 'low' } } });+ getProject.mockResolvedValue(projectWithPin({ image: { mode: 'codex' } }));+ // The planner authored `mode: 'local'`; the pin must win.+ await run('media_enqueueImageJob', { prompt: 'p', mode: 'local' }, { projectId: 'cd-1' });+ expect(enqueued().params.mode).toBe('codex');+ expect(enqueued().params.codexPath).toBe('/bin/codex');+ // Creative params the planner owns are preserved.+ expect(enqueued().params.prompt).toBe('p');+ });++ it('forces a grok pin with the provider knob bundle the queue needs', async () => {+ getSettings.mockResolvedValue({ imageGen: { grok: { enabled: true, grokPath: '/bin/grok', aspectRatio: '16:9' } } });+ getProject.mockResolvedValue(projectWithPin({ image: { mode: 'grok' } }));+ await run('media_enqueueImageJob', { prompt: 'p' }, { projectId: 'cd-1' });+ expect(enqueued().params.mode).toBe('grok');+ expect(enqueued().params.grokPath).toBe('/bin/grok');+ });++ it('degrades a pin whose backend the user has since DISABLED', async () => {+ // Grok pinned but the toggle is off — a nightly commission must still render+ // something rather than failing every fire because a setting moved.+ getSettings.mockResolvedValue({ imageGen: { grok: { enabled: false }, local: { pythonPath: '/py' } } });+ getProject.mockResolvedValue(projectWithPin({ image: { mode: 'grok' } }));+ await run('media_enqueueImageJob', { prompt: 'p' }, { projectId: 'cd-1' });+ expect(enqueued().params.mode).toBe('local');+ expect(enqueued().params.pythonPath).toBe('/py');+ });++ it('applies a local pin with its model id, but the planner model wins if it named one', async () => {+ getSettings.mockResolvedValue({ imageGen: { local: { pythonPath: '/py' } } });+ getProject.mockResolvedValue(projectWithPin({ image: { mode: 'local', modelId: 'pinned-model' } }));++ await run('media_enqueueImageJob', { prompt: 'p' }, { projectId: 'cd-1' });+ expect(enqueued().params.modelId).toBe('pinned-model');++ await run('media_enqueueImageJob', { prompt: 'p', modelId: 'planner-model' }, { projectId: 'cd-1' });+ expect(enqueued().params.modelId).toBe('planner-model');+ });++ it('falls through untouched when settings are unreadable', async () => {+ getSettings.mockRejectedValue(new Error('settings unavailable'));+ getProject.mockResolvedValue(projectWithPin({ image: { mode: 'grok' } }));+ await run('media_enqueueImageJob', { prompt: 'p' }, { projectId: 'cd-1' });+ expect(enqueued().params).toEqual({ prompt: 'p' });+ });+});++describe('render-backend pin — video (#3135)', () => {+ it('forces a grok pin with the grok discriminator + the semantic in videoMode', async () => {+ getSettings.mockResolvedValue({ imageGen: { grok: { enabled: true, grokPath: '/bin/grok', aspectRatio: '9:16' } } });+ getProject.mockResolvedValue(projectWithPin({ video: { mode: 'grok' } }));+ await run('media_enqueueVideoJob', { prompt: 'p' }, { projectId: 'cd-1' });+ expect(enqueued().params.mode).toBe('grok');+ // Text-to-video (no source frame) — the semantic never collides with the+ // 'grok' discriminator, which is why they can share the `mode` namespace.+ expect(enqueued().params.videoMode).toBe('text');+ expect(enqueued().params.grokPath).toBe('/bin/grok');+ expect(enqueued().params.aspectRatio).toBe('9:16');+ });++ it('marks a grok video with a source frame as image-to-video', async () => {+ getSettings.mockResolvedValue({ imageGen: { grok: { enabled: true, grokPath: '/bin/grok' } } });+ getProject.mockResolvedValue(projectWithPin({ video: { mode: 'grok' } }));+ await run('media_enqueueVideoJob', { prompt: 'p', sourceImagePath: '/tmp/frame.png' }, { projectId: 'cd-1' });+ expect(enqueued().params.videoMode).toBe('image');+ });++ it('a local video pin carries only the model id — never a backend name in `mode`', async () => {+ getSettings.mockResolvedValue({ imageGen: {} });+ getProject.mockResolvedValue(projectWithPin({ video: { mode: 'local', modelId: 'pinned-video-model' } }));+ await run('media_enqueueVideoJob', { prompt: 'p', mode: 'fflf' }, { projectId: 'cd-1' });+ // Stamping `mode: 'local'` here would destroy the t2v/i2v semantic and make+ // the runner render text-only, silently dropping the caller's keyframes.+ expect(enqueued().params.mode).toBe('fflf');+ expect(enqueued().params.modelId).toBe('pinned-video-model');+ });++ it('degrades a grok video pin to local when the grok toggle is off', async () => {+ getSettings.mockResolvedValue({ imageGen: { grok: { enabled: false } } });+ getProject.mockResolvedValue(projectWithPin({ video: { mode: 'grok' } }));+ await run('media_enqueueVideoJob', { prompt: 'p' }, { projectId: 'cd-1' });+ expect(enqueued().params).toEqual({ prompt: 'p' });+ });++ it('applies the video pin alongside the locked geometry preset', async () => {+ getSettings.mockResolvedValue({ imageGen: { grok: { enabled: true, grokPath: '/bin/grok' } } });+ getProject.mockResolvedValue({+ id: 'cd-1', aspectRatio: '9:16', quality: 'high', targetDurationSeconds: 10,+ renderBackend: { video: { mode: 'grok' } },+ });+ await run('media_enqueueVideoJob', { prompt: 'p', aspectRatio: '16:9' }, { projectId: 'cd-1' });+ // Both forcing steps applied: geometry from the preset, backend from the pin.+ expect(enqueued().params.width).toBe(432);+ expect(enqueued().params.height).toBe(768);+ expect(enqueued().params.mode).toBe('grok');+ });++ it('an image-only pin does not touch a video enqueue (and vice versa)', async () => {+ getSettings.mockResolvedValue({ imageGen: { grok: { enabled: true, grokPath: '/bin/grok' } } });+ getProject.mockResolvedValue(projectWithPin({ image: { mode: 'grok' } }));+ await run('media_enqueueVideoJob', { prompt: 'p' }, { projectId: 'cd-1' });+ expect(enqueued().params).toEqual({ prompt: 'p' });+ });+});++describe('audio enqueues never consult the render-backend pin', () => {+ it('tags the music bed without reading the project or settings', async () => {+ await run('media_enqueueAudioJob', { prompt: 'a mournful synth score' }, { projectId: 'cd-1' });+ expect(enqueued().params.creativeDirectorMusicBed).toEqual({ projectId: 'cd-1' });+ expect(getProject).not.toHaveBeenCalled();+ expect(getSettings).not.toHaveBeenCalled();+ });+});diff --git a/server/services/creativeCommissions/abilityAdapters.js b/server/services/creativeCommissions/abilityAdapters.jsindex f1b85ddf16..1c4510be55 100644--- a/server/services/creativeCommissions/abilityAdapters.js+++ b/server/services/creativeCommissions/abilityAdapters.js@@ -32,6 +32,7 @@import { renderFeedbackDigest, composeDirectiveGoal } from './directive.js';import {ABILITY_GENERATION_SPEC, GENERATION_KEY_DEFS, CREATIVE_COMMISSION_ABILITIES,+ COMMISSION_RENDER_BACKEND_AUTO,} from '../../lib/creativeCommissionValidation.js';const isStr = (v) => typeof v === 'string';@@ -49,6 +50,10 @@ function coerceGenerationValue(key, raw) {const def = GENERATION_KEY_DEFS[key];const v = raw?.[key];if (def.type === 'enum') return def.values.includes(v) ? v : def.default;+ // A model id (#3135): trim to a non-empty string, else null. A blank/absent id+ // means "the install's default model", which is a real, meaningful value — not+ // a validation failure — so it normalizes rather than erroring.+ if (def.type === 'id') return isStr(v) && v.trim() ? v.trim().slice(0, def.max) : def.default;return Number.isInteger(v) && v >= def.min && v <= def.max ? v : def.default;}@@ -85,16 +90,55 @@ function genValue(commission, key) {return coerceGenerationValue(key, commission?.generation);}+/**+ * Translate a commission's backend pins (#3135) into the CD project's+ * `renderBackend` field — the durable carrier that gets the pin from the+ * commission record to the enqueue site.+ *+ * Why via the project: the actual `enqueueJob` happens inside the planner's+ * `media_enqueueImageJob`/`media_enqueueVideoJob` tool call, which only knows+ * `ctx.projectId` — it has no reference back to the commission that minted the+ * project. Stamping the pin on the project lets the tool's forcing step+ * (`enforceRenderBackendPin` in creative/tools/media.js) override whatever the+ * planner LLM authored, and gives every plan-driven CD project the same knob for+ * free, not just commission-spawned ones.+ *+ * Returns `null` when nothing is pinned (every mode `auto`), so an unpinned+ * commission adds no key at all and the enqueued params stay byte-identical to+ * pre-#3135 behavior. A `modelId` alone is never a pin — the mode has to name a+ * backend for a model id to mean anything.+ */+export function buildRenderBackendPin(commission) {+ const gen = commission?.generation;+ if (!gen || typeof gen !== 'object') return null;+ const out = {};+ for (const [kind, modeKey, modelKey] of [+ ['image', 'imageMode', 'imageModelId'],+ ['video', 'videoMode', 'videoModelId'],+ ]) {+ const mode = gen[modeKey];+ if (!isStr(mode) || mode === COMMISSION_RENDER_BACKEND_AUTO) continue;+ const modelId = isStr(gen[modelKey]) && gen[modelKey].trim() ? gen[modelKey].trim() : null;+ out[kind] = { mode, modelId };+ }+ return Object.keys(out).length ? out : null;+}+// Video geometry the CD project always carries. For non-video types the planner// ignores it (no media_enqueueVideoJob steps), so these are harmless defaults.// Shared by every adapter's buildProjectParams today.function buildVideoGeometryParams(commission, { defaultVideoModelId } = {}) {const gen = commission?.generation;+ const renderBackend = buildRenderBackendPin(commission);return {aspectRatio: gen?.aspectRatio || '16:9',quality: gen?.quality || 'standard',modelId: gen?.model || (typeof defaultVideoModelId === 'function' ? defaultVideoModelId() : undefined),targetDurationSeconds: gen?.targetDurationSeconds || 10,+ // Only present when the commission actually pinned a backend (#3135) — an+ // unpinned commission must not even carry the key, so createProject stores+ // the same `null` a hand-made project gets.+ ...(renderBackend ? { renderBackend } : {}),};}diff --git a/server/services/creativeCommissions/abilityAdapters.test.js b/server/services/creativeCommissions/abilityAdapters.test.jsindex c2f4a56007..4f83b21cca 100644--- a/server/services/creativeCommissions/abilityAdapters.test.js+++ b/server/services/creativeCommissions/abilityAdapters.test.js@@ -1,6 +1,6 @@import { describe, it, expect } from 'vitest';import {- ABILITY_ADAPTERS, getAbilityAdapter, buildCommissionDirective,+ ABILITY_ADAPTERS, getAbilityAdapter, buildCommissionDirective, buildRenderBackendPin,} from './abilityAdapters.js';import { CREATIVE_COMMISSION_ABILITIES, ABILITY_GENERATION_SPEC } from '../../lib/creativeCommissionValidation.js';@@ -115,11 +115,17 @@ describe('per-ability directives steer the planner to the right tools', () => {describe('sanitizeGeneration — fills defaults and preserves only the type keys', () => {it('video keeps its keys and drops off-type ones', () => {const g = getAbilityAdapter('video').sanitizeGeneration({ quality: 'high', aspectRatio: '9:16', targetDurationSeconds: 20, imageCount: 5, model: ' ltx ' });- expect(g).toEqual({ model: 'ltx', quality: 'high', aspectRatio: '9:16', targetDurationSeconds: 20 });+ expect(g).toEqual({+ model: 'ltx', quality: 'high', aspectRatio: '9:16', targetDurationSeconds: 20,+ videoMode: 'auto', videoModelId: null,+ });});it('image fills defaults for missing keys and clamps an out-of-range count', () => {- expect(getAbilityAdapter('image').sanitizeGeneration({})).toEqual({ model: null, quality: 'standard', aspectRatio: '16:9', imageCount: 1 });+ expect(getAbilityAdapter('image').sanitizeGeneration({})).toEqual({+ model: null, quality: 'standard', aspectRatio: '16:9', imageCount: 1,+ imageMode: 'auto', imageModelId: null,+ });expect(getAbilityAdapter('image').sanitizeGeneration({ imageCount: 99 }).imageCount).toBe(1);expect(getAbilityAdapter('image').sanitizeGeneration({ imageCount: 4 }).imageCount).toBe(4);});@@ -158,3 +164,43 @@ describe('buildProjectParams — every type yields well-formed render settings',}});});++describe('buildRenderBackendPin — per-commission render backend (#3135)', () => {+ it('returns null when nothing is pinned (auto = no key at all)', () => {+ // The hard back-compat criterion: an auto/absent pin must not add a+ // renderBackend key, so createProject stores exactly what it stored before.+ expect(buildRenderBackendPin({ generation: { imageMode: 'auto', imageModelId: null } })).toBeNull();+ expect(buildRenderBackendPin({ generation: {} })).toBeNull();+ expect(buildRenderBackendPin({})).toBeNull();+ expect(buildRenderBackendPin(null)).toBeNull();+ });++ it('a model id alone is not a pin — the mode has to name a backend', () => {+ expect(buildRenderBackendPin({ generation: { imageMode: 'auto', imageModelId: 'example-model' } })).toBeNull();+ });++ it('carries a pinned image backend and its model id', () => {+ expect(buildRenderBackendPin({ generation: { imageMode: 'local', imageModelId: ' example-model ' } }))+ .toEqual({ image: { mode: 'local', modelId: 'example-model' } });+ });++ it('carries a cloud pin with a null model id (cloud CLIs pick their own model)', () => {+ expect(buildRenderBackendPin({ generation: { imageMode: 'grok', imageModelId: null } }))+ .toEqual({ image: { mode: 'grok', modelId: null } });+ });++ it('carries both kinds for a music-video commission', () => {+ expect(buildRenderBackendPin({+ generation: { videoMode: 'grok', videoModelId: null, imageMode: 'codex', imageModelId: null },+ })).toEqual({ video: { mode: 'grok', modelId: null }, image: { mode: 'codex', modelId: null } });+ });++ it('is reflected in buildProjectParams only when pinned', () => {+ const ctx = { defaultVideoModelId: () => 'ltx-default' };+ const unpinned = getAbilityAdapter('image').buildProjectParams({ generation: { imageMode: 'auto' } }, ctx);+ expect(unpinned).not.toHaveProperty('renderBackend');++ const pinned = getAbilityAdapter('image').buildProjectParams({ generation: { imageMode: 'grok' } }, ctx);+ expect(pinned.renderBackend).toEqual({ image: { mode: 'grok', modelId: null } });+ });+});diff --git a/server/services/creativeCommissions/store.test.js b/server/services/creativeCommissions/store.test.jsindex f886e162ec..0bbe2e7606 100644--- a/server/services/creativeCommissions/store.test.js+++ b/server/services/creativeCommissions/store.test.js@@ -93,7 +93,10 @@ describe('sanitizeCommission', () => {const img = sanitizeCommission({ id: 'c1', targetAbility: 'image', generation: { imageCount: 4, targetDurationSeconds: 30 } });expect(img.targetAbility).toBe('image');// Keeps the image key; drops the off-type video duration key.- expect(img.generation).toEqual({ model: null, quality: 'standard', aspectRatio: '16:9', imageCount: 4 });+ expect(img.generation).toEqual({+ model: null, quality: 'standard', aspectRatio: '16:9', imageCount: 4,+ imageMode: 'auto', imageModelId: null,+ });const music = sanitizeCommission({ id: 'c2', targetAbility: 'music', generation: { lengthSeconds: 60 } });expect(music.generation).toEqual({ model: null, lengthSeconds: 60 });@@ -102,6 +105,36 @@ describe('sanitizeCommission', () => {expect(series.generation).toEqual({ model: null, episodeCount: 2 });});+ it('round-trips a render-backend pin and normalizes a blank model id to null (#3135)', () => {+ const pinned = sanitizeCommission({+ id: 'c-pin', targetAbility: 'image',+ generation: { imageMode: 'grok', imageModelId: ' ' },+ });+ expect(pinned.generation.imageMode).toBe('grok');+ // A blank id means "the install default" — a real value, normalized not rejected.+ expect(pinned.generation.imageModelId).toBeNull();++ const localPin = sanitizeCommission({+ id: 'c-pin2', targetAbility: 'video',+ generation: { videoMode: 'local', videoModelId: ' example-model ' },+ });+ expect(localPin.generation.videoMode).toBe('local');+ expect(localPin.generation.videoModelId).toBe('example-model');+ });++ it('defaults a legacy (pre-#3135) record to the auto sentinel — no behavior change', () => {+ // The hard back-compat criterion: an existing commission with no pin reads as+ // `auto`, which buildRenderBackendPin turns into no project pin at all.+ const legacy = sanitizeCommission({ id: 'c-legacy', targetAbility: 'image', generation: { imageCount: 2 } });+ expect(legacy.generation.imageMode).toBe('auto');+ expect(legacy.generation.imageModelId).toBeNull();+ });++ it('falls back to auto for an unrecognized backend value (a hand-edited row)', () => {+ const bad = sanitizeCommission({ id: 'c-bad', targetAbility: 'image', generation: { imageMode: 'midjourney' } });+ expect(bad.generation.imageMode).toBe('auto');+ });+it('preserves an unknown (forward-version) output type verbatim so a newer peer record round-trips (#2769)', () => {// A newer peer might sync an output type this install does not know yet.// Rewriting it to `video` would corrupt the newer brief on read (and coulddiff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.jsindex fb6cb96bd8..c173b2e0ba 100644--- a/server/services/creativeDirector/projectsLogic.js+++ b/server/services/creativeDirector/projectsLogic.js@@ -44,6 +44,29 @@ export function normalizeModelOverrides(raw) {return out;}+// Per-project RENDER-backend pin (#3135) — `renderBackend.{image,video}`, each an+// optional `{ mode, modelId }`. Distinct from `modelOverrides` above: that pins the+// LLM that THINKS, this pins the backend that RENDERS. Only kinds that name a+// non-empty `mode` are kept, and the whole field normalizes to `null` when nothing+// is pinned — so an unpinned project stores exactly what it stored pre-#3135 and+// the enqueue-time forcing step has one falsy check instead of three.+export const RENDER_BACKEND_KINDS = ['image', 'video'];++export function normalizeRenderBackend(raw) {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;+ const out = {};+ for (const kind of RENDER_BACKEND_KINDS) {+ const v = raw[kind];+ if (!v || typeof v !== 'object' || Array.isArray(v)) continue;+ const mode = isStr(v.mode) ? v.mode.trim() : '';+ const modelId = isStr(v.modelId) ? v.modelId.trim() : '';+ // A modelId with no mode can't be dispatched (the queue routes on mode+ // first), so drop a mode-less pin — it would resolve to the default anyway.+ if (mode) out[kind] = { mode, ...(modelId ? { modelId } : {}) };+ }+ return Object.keys(out).length ? out : null;+}+/*** Resolve the effective provider/model pin for one CD cognitive stage. The* per-project override wins when it names a providerId; otherwise the global@@ -130,7 +153,7 @@ export function buildProjectRecord(input, { id, now, collectionId }) {styleSpec = '', startingImageFile = null, userStory = null,disableAudio = true, autoAcceptScenes = false, sourceIssueId = null,cast = [], generateFirstPass = false, directive = null,- modelOverrides = {},+ modelOverrides = {}, renderBackend = null,} = input;return {id,@@ -190,6 +213,14 @@ export function buildProjectRecord(input, { id, now, collectionId }) {// global AI Assignment. Additive — round-trips through the JSONB column// verbatim, so no schema-version bump is needed for federation.modelOverrides: normalizeModelOverrides(modelOverrides),+ // Which image/video BACKEND this project's enqueued media jobs render on+ // (#3135) — `{ image?: { mode, modelId? }, video?: { … } }`, or null for "use+ // the install default", which is what every pre-#3135 project has. Set from a+ // creative commission's `generation.imageMode`/`.videoMode` so a scheduled+ // fire can't have its pinned backend silently overridden by the planner LLM's+ // freehand job params. Additive — the whole record round-trips through the+ // JSONB column verbatim, so this needs no schema-version bump.+ renderBackend: normalizeRenderBackend(renderBackend),runs: [],// Soft-delete / LWW tombstone trio (#1564) — projects federate across peers// via the per-record push pipeline (record kind `creativeDirectorProject`,diff --git a/server/services/creativeDirector/projectsLogic.test.js b/server/services/creativeDirector/projectsLogic.test.jsindex 9c3a97410b..12306c0801 100644--- a/server/services/creativeDirector/projectsLogic.test.js+++ b/server/services/creativeDirector/projectsLogic.test.js@@ -22,6 +22,7 @@ import {mergeProjectRecord,startingImageFilename,normalizeModelOverrides,+ normalizeRenderBackend,resolveStagePin,} from './projectsLogic.js';@@ -114,6 +115,41 @@ describe('buildProjectRecord', () => {);expect(bad.cast).toEqual([]);});++ it('defaults renderBackend to null and persists a supplied pin (#3135)', () => {+ const ctx = { id: 'cd-1', now: '2026-06-07T00:00:00.000Z', collectionId: 'col-1' };+ const base = { name: 'X', aspectRatio: '1:1', quality: 'draft', modelId: 'm', targetDurationSeconds: 9 };+ // A hand-made project stores exactly what it stored pre-#3135.+ expect(buildProjectRecord(base, ctx).renderBackend).toBeNull();++ const pinned = buildProjectRecord(+ { ...base, renderBackend: { image: { mode: 'grok', modelId: null }, video: { mode: 'local', modelId: 'example-model' } } },+ ctx,+ );+ expect(pinned.renderBackend).toEqual({ image: { mode: 'grok' }, video: { mode: 'local', modelId: 'example-model' } });+ });+});++describe('normalizeRenderBackend (#3135)', () => {+ it('returns null for anything that pins nothing', () => {+ expect(normalizeRenderBackend(null)).toBeNull();+ expect(normalizeRenderBackend('nope')).toBeNull();+ expect(normalizeRenderBackend([])).toBeNull();+ expect(normalizeRenderBackend({})).toBeNull();+ // A mode-less pin can't be dispatched (the queue routes on mode first).+ expect(normalizeRenderBackend({ image: { modelId: 'example-model' } })).toBeNull();+ expect(normalizeRenderBackend({ image: { mode: ' ' } })).toBeNull();+ });++ it('keeps only kinds that name a mode, and drops an empty model id', () => {+ expect(normalizeRenderBackend({ image: { mode: ' grok ', modelId: '' }, video: null, bogus: { mode: 'x' } }))+ .toEqual({ image: { mode: 'grok' } });+ });++ it('trims and keeps a real model id', () => {+ expect(normalizeRenderBackend({ video: { mode: 'local', modelId: ' example-model ' } }))+ .toEqual({ video: { mode: 'local', modelId: 'example-model' } });+ });});describe('applyProjectPatch', () => {diff --git a/server/services/videoGen/modes.js b/server/services/videoGen/modes.jsnew file mode 100644index 0000000000..eca11d3da9--- /dev/null+++ b/server/services/videoGen/modes.js@@ -0,0 +1,71 @@+/**+ * Video Gen — render-backend mode enum (#3135).+ *+ * The video lane of the media job queue has always discriminated its backend on+ * `job.params.mode`, but only INLINE against the *image* module's constant:+ * `mediaJobQueue/index.js` reads `params.mode === IMAGE_GEN_MODE.GROK` to pick+ * `videoGen/grok.js` over `videoGen/local.js`, and `routes/videoGen.js` stamps+ * that same image constant onto a grok video job. That reuse is correct (the two+ * lanes deliberately share one discriminator namespace) but it left video with+ * no enumerable alphabet — so a Zod schema, a UI picker, or a resolver had+ * nothing to derive from and had to hand-copy `['local', 'grok']`.+ *+ * This module is that alphabet. The values are DERIVED from `IMAGE_GEN_MODE`+ * rather than re-typed, so the queue's discriminator can never drift from what a+ * schema validates.+ *+ * Careful: local video renders ALSO use a `params.mode` for the t2v/i2v semantic+ * ('text' | 'image' | 'fflf' | 'a2v' | 'extend' | an IC-LoRA remix id — see+ * `videoGen/local.js`'s `helperMode`). That namespace never collides with the+ * 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.+ */++import { IMAGE_GEN_MODE } from '../imageGen/modes.js';++export const VIDEO_GEN_MODE = Object.freeze({+ LOCAL: IMAGE_GEN_MODE.LOCAL,+ GROK: IMAGE_GEN_MODE.GROK,+});++export const VIDEO_GEN_MODES = Object.freeze(Object.values(VIDEO_GEN_MODE));++// Cloud-CLI video backends — each render shells out to an external child that+// spends remote quota, so the queue routes them through its parallel cloud lane+// instead of serializing on the MLX runtime.+export const CLOUD_VIDEO_GEN_MODES = Object.freeze([VIDEO_GEN_MODE.GROK]);++/**+ * Is `mode` a video backend this install can actually render on right now?+ *+ * Grok video runs through the SAME `imageGen.grok.enabled` opt-in as grok image+ * gen (one CLI, one toggle — see the gate in `routes/videoGen.js` and the note+ * at the top of `videoGen/grok.js`). Local is always "usable" here; its own+ * pythonPath/model validation happens per call site in `generateVideo`.+ */+export function isVideoModeUsable(settings, mode) {+ if (mode === VIDEO_GEN_MODE.GROK) return settings?.imageGen?.grok?.enabled === true;+ return mode === VIDEO_GEN_MODE.LOCAL;+}++/**+ * Resolve the video backend for a render: the per-request/per-record override+ * when that backend is usable, else the install-wide default.+ *+ * 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+ * 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.+ */+export function resolveVideoMode(requested, settings) {+ if (requested && isVideoModeUsable(settings, requested)) return requested;+ return VIDEO_GEN_MODE.LOCAL;+}diff --git a/server/services/videoGen/modes.test.js b/server/services/videoGen/modes.test.jsnew file mode 100644index 0000000000..b161d31752--- /dev/null+++ b/server/services/videoGen/modes.test.js@@ -0,0 +1,58 @@+import { describe, it, expect } from 'vitest';+import {+ VIDEO_GEN_MODE, VIDEO_GEN_MODES, CLOUD_VIDEO_GEN_MODES,+ isVideoModeUsable, resolveVideoMode,+} from './modes.js';+import { IMAGE_GEN_MODE } from '../imageGen/modes.js';++describe('VIDEO_GEN_MODE', () => {+ it('derives its values from the queue discriminator the image lane already uses', () => {+ // The queue routes video on `params.mode === IMAGE_GEN_MODE.GROK`; deriving+ // rather than re-typing is what keeps a schema from drifting from dispatch.+ expect(VIDEO_GEN_MODE.LOCAL).toBe(IMAGE_GEN_MODE.LOCAL);+ expect(VIDEO_GEN_MODE.GROK).toBe(IMAGE_GEN_MODE.GROK);+ expect(VIDEO_GEN_MODES).toEqual(['local', 'grok']);+ expect(CLOUD_VIDEO_GEN_MODES).toEqual(['grok']);+ expect(Object.isFrozen(VIDEO_GEN_MODE)).toBe(true);+ });+});++describe('isVideoModeUsable', () => {+ it('gates grok on the shared imageGen.grok.enabled toggle', () => {+ expect(isVideoModeUsable({ imageGen: { grok: { enabled: true } } }, 'grok')).toBe(true);+ expect(isVideoModeUsable({ imageGen: { grok: { enabled: false } } }, 'grok')).toBe(false);+ // Strict boolean — a truthy non-true value is not an opt-in.+ expect(isVideoModeUsable({ imageGen: { grok: { enabled: 'yes' } } }, 'grok')).toBe(false);+ expect(isVideoModeUsable({}, 'grok')).toBe(false);+ expect(isVideoModeUsable(null, 'grok')).toBe(false);+ });++ it('always accepts local and rejects anything else', () => {+ expect(isVideoModeUsable(null, 'local')).toBe(true);+ expect(isVideoModeUsable({}, 'codex')).toBe(false);+ expect(isVideoModeUsable({}, 'external')).toBe(false);+ expect(isVideoModeUsable({}, undefined)).toBe(false);+ });+});++describe('resolveVideoMode', () => {+ const grokOn = { imageGen: { grok: { enabled: true } } };++ it('honors a usable request', () => {+ expect(resolveVideoMode('grok', grokOn)).toBe('grok');+ expect(resolveVideoMode('local', grokOn)).toBe('local');+ });++ it('falls back to local for an absent, unknown, or unusable request', () => {+ expect(resolveVideoMode(null, grokOn)).toBe('local');+ expect(resolveVideoMode('hologram', grokOn)).toBe('local');+ expect(resolveVideoMode('grok', { imageGen: { grok: { enabled: false } } })).toBe('local');+ });++ it('does NOT upgrade an unpinned render to grok just because grok is enabled', () => {+ // Deliberate divergence from the image ladder (which prefers an enabled cloud+ // backend): grok video spends remote quota and only delivers 6s/10s clips, so+ // enabling it for IMAGES must not silently redirect every video render to it.+ expect(resolveVideoMode(undefined, grokOn)).toBe('local');+ });+});