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
honor the creative commission video backend pin on the scene render path
[._.]/ Adam Eivyb62833e3d905
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 16b2c639c9..17d85ce04d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -56,6 +56,7 @@## Fixed+- **A creative commission pinned to Grok now actually renders on Grok.** Commissions have been able to name their video backend — Grok, or local with a specific local video model — for a while, but the pin only reached renders the Creative Director's *planner* queued. The scene-by-scene render path, which is where a commission's video is actually produced, never read it: every scene went to the local MLX runtime regardless, the pinned local model was ignored in favor of the project's creation-time default, and an install with no local Python configured failed the whole project up front even when Grok was the configured, enabled, pinned backend. Both paths now resolve the backend through one shared ladder — the commission's own pin, then the install-wide Creative Agent render default, then the global video pin — so what the form says is what renders. Grok's 6s/10s-only clip lengths are covered by rounding a scene's duration up rather than letting it silently come back short, and the project's aspect ratio carries through to Grok's base image. A pin naming a backend whose toggle has since been switched off still degrades to local rather than failing a nightly run, and if local is unconfigured too, the scene now says the pinned backend is disabled instead of only asking for a Python path.- **A note that iCloud wrongly reports as "not downloaded" can now be saved anyway.** The write guard screens for an offloaded note by looking for a real byte length with no local blocks — a shape an ordinary sparse or compressed file also has. When that misfired the lockout was permanent: asking iCloud to download an already-local file succeeds instantly and changes nothing, so every save was refused forever while the message told the user to try again shortly. The server now checks whether the download both succeeded and actually moved the file, so it can tell a download still in flight (or one that failed) from a refusal that will never clear — and only the second of those, twice in a row on the same note, offers the Brain Notes and Wiki editors a deliberate "Save anyway" row that writes it regardless. While a download really is in flight you still just wait, and the ordinary Save button, ⌘S, and background mirrors always refuse, so nothing bypasses the guard without an explicit click. The message no longer says to try again shortly when trying again cannot help.- **Quiet Codex reasoning is no longer mistaken for a finished one-shot response.** The TUI runner's eight-second screen-idle fallback could kill an active long-form Luna or Sol stage between status repaints, then hand terminal chrome such as `[Pasted Content …]` to a JSON parser as if it were the model's answer. Codex one-shot calls now wait for their required response file, a natural exit, explicit cancellation, or the configured hard cap; inline idle completion remains available for other TUIs that do not honor file output.- **Quiet Codex reasoning is no longer mistaken for a finished one-shot response.** The TUI runner's eight-second screen-idle fallback could kill an active long-form Luna or Sol stage between status repaints, then hand terminal chrome such as `[Pasted Content …]` to a JSON parser as if it were the model's answer. Codex one-shot calls now wait for their required response file, a natural exit, explicit cancellation, or the configured hard cap; inline idle completion remains available for other TUIs that do not honor file output. The foundation judge also rejects the prompt's echoed `{ score: 6, gap: "string", fix: "string" }` schema example, so terminal chrome cannot masquerade as a real all-six editorial verdict even if a malformed transport reaches the retry gate.diff --git a/server/services/creative/tools/media.js b/server/services/creative/tools/media.jsindex 348dde64cf..47c211ed38 100644--- a/server/services/creative/tools/media.js+++ b/server/services/creative/tools/media.js@@ -11,8 +11,8 @@ import { getSettings } from '../../settings.js';import { IMAGE_GEN_MODE, resolveQueueImageMode } from '../../imageGen/modes.js';import { renderTargetDefaults, resolveRenderTargetConfig } from '../../imageGen/cloudProviderConfig.js';import { RENDER_TARGET } from '../../../lib/renderTargets.js';-import { VIDEO_GEN_MODE, VIDEO_GEN_MODES, resolveVideoMode, hasVideoPin } from '../../videoGen/modes.js';-import { nearestGrokDuration } from '../../../lib/grokVideoClip.js';+import { VIDEO_GEN_MODE, VIDEO_GEN_MODES } from '../../videoGen/modes.js';+import { grokVideoJobParams, resolveVideoBackendPin } from '../../videoGen/backendPin.js';import { COST_RENDER, resolveOwner } from './shared.js';const paramsSchema = z.object({ params: z.record(z.any()).default({}), owner: z.string().optional() });@@ -120,24 +120,20 @@ function attachMusicBedTag(params, ctx) {* byte-identical" contract this change rests on, so it's a separate concern.*/async function enforceRenderBackendPin(kind, params, project) {- const pin = project?.renderBackend?.[kind];const settings = await getSettings().catch(() => null);if (!settings) return params;- 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 && !hasVideoPin(settings, { target: RENDER_TARGET.CREATIVE_AGENT })) {- return params;- }-if (kind === 'video') {- const mode = resolveVideoMode(pin?.mode, settings, { target: RENDER_TARGET.CREATIVE_AGENT });- if (mode !== VIDEO_GEN_MODE.GROK) {+ // The video ladder is shared verbatim with the scene-render path via+ // videoGen/backendPin.js, so the two enqueue surfaces resolve identically.+ const videoPin = resolveVideoBackendPin(project, settings);+ if (!videoPin.pinned) return params;+ if (videoPin.mode !== VIDEO_GEN_MODE.GROK) {// Local video: `params.mode` is the t2v/i2v SEMANTIC for this lane (see// videoGen/modes.js), so a local pin must NOT stamp the backend name over// it — overwriting a real semantic ('fflf', 'a2v', 'extend', an IC-LoRA id)@@ -159,34 +155,26 @@ async function enforceRenderBackendPin(kind, params, project) {// 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;+ return videoPin.modelId ? { ...base, modelId: videoPin.modelId } : base;}- 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.- //- // Clip length crosses a contract boundary here: the local lane derives frame- // count from `durationSeconds` (which is what the planner writes and what- // enforceVideoRenderPreset reconciles), while grok's worker reads `duration`- // and silently falls back to 6s for anything absent or undeliverable. Without- // the translation a 10s commission would quietly render a 6s clip. Prefer an- // explicit `duration` if some caller already set one; else map the step's- // durationSeconds, else the project's target, through grok's own- // 6/10-only normalization (lib/grokVideoClip.js) so we snap the same way the- // provider would rather than passing a length it can't deliver.+ // Clip length crosses a contract boundary into the grok lane (see+ // grokVideoJobParams). Prefer an explicit `duration` if some caller already+ // set one; else the step's `durationSeconds` (what the planner writes and+ // what enforceVideoRenderPreset reconciles); else the project's target.const requestedSeconds = params?.duration ?? params?.durationSeconds ?? project?.targetDurationSeconds;return {...params,- mode: VIDEO_GEN_MODE.GROK,- videoMode: params?.sourceImagePath ? 'image' : 'text',- grokPath: grok.grokPath,- duration: nearestGrokDuration(requestedSeconds),- ...(grok.aspectRatio ? { aspectRatio: grok.aspectRatio } : {}),+ ...grokVideoJobParams(settings, {+ sourceImagePath: params?.sourceImagePath,+ durationSeconds: requestedSeconds,+ }),};}+ const pin = project?.renderBackend?.[kind];+ const targetDefaults = renderTargetDefaults(settings, RENDER_TARGET.CREATIVE_AGENT);+ if (!pin?.mode && !targetDefaults.imageMode) return params;+// Project pin (explicit, per-record) → creative-agent renderDefaults pin —// both usability-laddered so a disabled backend degrades instead of failing// a nightly commission. One ladder covers text-to-image and edit/referencediff --git a/server/services/creativeDirector/sceneRunner.backend.test.js b/server/services/creativeDirector/sceneRunner.backend.test.jsnew file mode 100644index 0000000000..cf99094185--- /dev/null+++ b/server/services/creativeDirector/sceneRunner.backend.test.js@@ -0,0 +1,173 @@+/**+ * runSceneRender — render-backend pin coverage.+ *+ * Kept apart from the pure `sceneRunner.test.js` on purpose: exercising the+ * enqueue path needs the service graph mocked out, and hoisted `vi.mock` calls+ * apply to the whole file — folding them into the pure suite would silently+ * replace the real modules its schema assertions import.+ *+ * What's under test is the gap #3135 left: a creative commission pins its video+ * backend on the project (`renderBackend.video`), but the TREATMENT/SCENE path+ * — which is where a commission's video is actually rendered — used to ignore+ * it entirely and always build local MLX params.+ */++import { describe, it, expect, beforeEach, vi } from 'vitest';++vi.mock('../mediaJobQueue/index.js', () => ({+ enqueueJob: vi.fn(() => ({ jobId: 'job-1' })),+ mediaJobEvents: { on: vi.fn(), off: vi.fn() },+}));+vi.mock('../settings.js', () => ({ getSettings: vi.fn() }));+vi.mock('./local.js', () => ({+ updateScene: vi.fn(async () => {}),+ updateProject: vi.fn(async () => {}),+ getProject: vi.fn(async () => null),+}));+vi.mock('./sceneEvaluator.js', () => ({ dispatchSceneEvaluation: vi.fn(async () => {}) }));+vi.mock('../videoGen/local.js', () => ({+ extractLastFrame: vi.fn(async () => null),+ sampleEvaluationFrames: vi.fn(async () => []),+}));+vi.mock('./completionHook.js', () => ({ advanceAfterSceneSettled: vi.fn(async () => {}) }));+vi.mock('../../lib/ffmpeg.js', () => ({ verifyVideoPlayable: vi.fn(async () => ({ ok: true })) }));++import { runSceneRender } from './sceneRunner.js';+import { enqueueJob } from '../mediaJobQueue/index.js';+import { getSettings } from '../settings.js';+import { updateScene } from './local.js';++const LOCAL_READY = { imageGen: { local: { pythonPath: '/usr/bin/python3' } } };+const GROK_READY = { imageGen: { grok: { enabled: true, grokPath: '/usr/local/bin/grok' } } };++const project = (over = {}) => ({+ id: 'proj-1',+ aspectRatio: '16:9',+ quality: 'standard',+ modelId: 'project-default-model',+ ...over,+});+const scene = (over = {}) => ({+ sceneId: 'scene-1', order: 0, prompt: 'a cat walks into view', durationSeconds: 8, ...over,+});++const enqueuedParams = () => enqueueJob.mock.calls[0][0].params;++beforeEach(() => vi.clearAllMocks());++describe('runSceneRender — unpinned (local) behavior is unchanged', () => {+ it('builds local MLX params when nothing is pinned', async () => {+ getSettings.mockResolvedValue(LOCAL_READY);+ await runSceneRender(project(), scene());++ const params = enqueuedParams();+ expect(enqueueJob.mock.calls[0][0].kind).toBe('video');+ expect(params.pythonPath).toBe('/usr/bin/python3');+ expect(params.modelId).toBe('project-default-model');+ expect(params.mode).toBe('text');+ expect(params.numFrames).toBeGreaterThan(0);+ expect(params).not.toHaveProperty('duration');+ });++ it('fails the scene when local is the resolved backend and python is unconfigured', async () => {+ getSettings.mockResolvedValue({ imageGen: {} });+ const jobId = await runSceneRender(project(), scene());++ expect(jobId).toBe(null);+ expect(enqueueJob).not.toHaveBeenCalled();+ expect(updateScene).toHaveBeenLastCalledWith('proj-1', 'scene-1', expect.objectContaining({ status: 'failed' }));+ });+});++describe('runSceneRender — grok pin', () => {+ it('renders on grok when the project pins it', async () => {+ getSettings.mockResolvedValue({ ...LOCAL_READY, ...GROK_READY });+ await runSceneRender(project({ renderBackend: { video: { mode: 'grok', modelId: null } } }), scene());++ const params = enqueuedParams();+ expect(params.mode).toBe('grok');+ expect(params.grokPath).toBe('/usr/local/bin/grok');+ expect(params.videoMode).toBe('text');+ // The scene's 8s is authored in local-lane continuous seconds; grok only+ // delivers 6 or 10, so it must round UP rather than truncate the beat.+ expect(params.duration).toBe(10);+ // Local-only dials must not ride along — grok has no such knobs.+ expect(params).not.toHaveProperty('pythonPath');+ expect(params).not.toHaveProperty('numFrames');+ expect(params).not.toHaveProperty('steps');+ });++ it('renders on grok even when local python is unconfigured', async () => {+ // The regression this whole change exists for: a grok-pinned commission on+ // an install with no MLX python used to fail every scene up front.+ getSettings.mockResolvedValue(GROK_READY);+ const jobId = await runSceneRender(project({ renderBackend: { video: { mode: 'grok' } } }), scene());++ expect(jobId).toBe('job-1');+ expect(enqueuedParams().mode).toBe('grok');+ });++ it('marks an i2v scene when a source image resolved', async () => {+ getSettings.mockResolvedValue(GROK_READY);+ await runSceneRender(+ project({ renderBackend: { video: { mode: 'grok' } } }),+ // A bare filename that never resolves under data/images stays null, so+ // pass the case we can assert deterministically: no source ⇒ 'text'.+ scene(),+ );+ expect(enqueuedParams().videoMode).toBe('text');+ });++ it('passes the project geometry so grok derives the right aspect ratio', async () => {+ getSettings.mockResolvedValue(GROK_READY);+ await runSceneRender(+ project({ aspectRatio: '9:16', renderBackend: { video: { mode: 'grok' } } }),+ scene(),+ );+ const params = enqueuedParams();+ expect(params.height).toBeGreaterThan(params.width);+ });++ it('degrades to local when grok is pinned but disabled', async () => {+ getSettings.mockResolvedValue({ ...LOCAL_READY, imageGen: { ...LOCAL_READY.imageGen, grok: { enabled: false } } });+ await runSceneRender(project({ renderBackend: { video: { mode: 'grok' } } }), scene());++ const params = enqueuedParams();+ expect(params.mode).toBe('text');+ expect(params.pythonPath).toBe('/usr/bin/python3');+ });++ it('explains a lapsed cloud pin when the local fallback is also unconfigured', async () => {+ getSettings.mockResolvedValue({ imageGen: { grok: { enabled: false } } });+ await runSceneRender(project({ renderBackend: { video: { mode: 'grok' } } }), scene());++ const notes = updateScene.mock.calls.at(-1)[2].evaluation.notes;+ expect(notes).toContain("pinned to 'grok'");+ });+});++describe('runSceneRender — local model pin', () => {+ it("uses the pinned local model over the project's creation-time default", async () => {+ getSettings.mockResolvedValue(LOCAL_READY);+ await runSceneRender(+ project({ renderBackend: { video: { mode: 'local', modelId: 'ltx-13b' } } }),+ scene(),+ );+ expect(enqueuedParams().modelId).toBe('ltx-13b');+ });++ it("falls back to the project's model when the pin names no model", async () => {+ getSettings.mockResolvedValue(LOCAL_READY);+ await runSceneRender(project({ renderBackend: { video: { mode: 'local' } } }), scene());+ expect(enqueuedParams().modelId).toBe('project-default-model');+ });++ it('applies the install-wide creative-agent video model default', async () => {+ getSettings.mockResolvedValue({+ ...LOCAL_READY,+ renderDefaults: { 'creative-agent': { videoMode: 'local', videoModel: 'target-default-model' } },+ });+ await runSceneRender(project(), scene());+ expect(enqueuedParams().modelId).toBe('target-default-model');+ });+});diff --git a/server/services/creativeDirector/sceneRunner.js b/server/services/creativeDirector/sceneRunner.jsindex 55e0ceb446..f177940b1b 100644--- a/server/services/creativeDirector/sceneRunner.js+++ b/server/services/creativeDirector/sceneRunner.js@@ -34,6 +34,8 @@ import { verifyVideoPlayable } from '../../lib/ffmpeg.js';import { presetToRenderParams } from '../../lib/creativeDirectorPresets.js';import { CD_MAX_SCENE_RETRIES } from '../../lib/creativeDirectorPrompts.js';import { extractLastFrame, sampleEvaluationFrames } from '../videoGen/local.js';+import { VIDEO_GEN_MODE } from '../videoGen/modes.js';+import { grokVideoJobParams, resolveVideoBackendPin } from '../videoGen/backendPin.js';import { enqueueJob, mediaJobEvents } from '../mediaJobQueue/index.js';import { getSettings } from '../settings.js';import { updateScene, updateProject, getProject } from './local.js';@@ -69,20 +71,42 @@ export async function runSceneRender(project, scene) {});const settings = await getSettings();+ // Which backend renders this scene (#3135 gap): the project's own+ // `renderBackend.video` pin — which is how a creative commission's+ // `generation.videoMode` / `.videoModelId` reach the render — then the+ // creative-agent render default, then the install-wide video pin, else local.+ // Shared verbatim with the planner's enqueue tool via videoGen/backendPin.js.+ //+ // Before this, the scene path was unconditionally local: a commission pinned+ // to Grok still rendered every scene on the MLX runtime, and the pythonPath+ // guard below failed the whole project even when Grok was the pinned backend.+ const videoPin = resolveVideoBackendPin(project, settings);+ const useGrok = videoPin.mode === VIDEO_GEN_MODE.GROK;+const pythonPath = settings.imageGen?.local?.pythonPath || null;// Fail fast when local video gen isn't configured. Without this guard the// job would be enqueued, fail inside `generateVideo`, retry up to// CD_MAX_SCENE_RETRIES, and pollute the persisted queue with N doomed entries// — none of which can ever succeed without operator intervention. Mark// the scene failed and let advanceAfterSceneSettled flag the project so- // the user can configure pythonPath and Resume from the UI.- if (!pythonPath) {- console.log(`❌ CD scene ${scene.sceneId}: local video gen not configured (settings.imageGen.local.pythonPath missing)`);+ // the user can configure pythonPath and Resume from the UI. Only the local+ // lane needs it — a Grok render shells out to the CLI and never touches+ // Python (the media-job queue gates its own pythonPath check the same way).+ if (!useGrok && !pythonPath) {+ // A pin that named a cloud backend but resolved to local means the ladder+ // degraded it (the backend's `enabled` toggle is off). Say so — otherwise+ // the user reads "configure Python" on a project they explicitly pinned to+ // Grok and has no way to tell that their pin was the thing that lapsed.+ const lapsedPin = videoPin.requested;+ const detail = lapsedPin && lapsedPin !== videoPin.mode+ ? ` This project is pinned to '${lapsedPin}', but that backend is not enabled, so the render fell back to local.`+ : '';+ console.log(`❌ CD scene ${scene.sceneId}: local video gen not configured (settings.imageGen.local.pythonPath missing)${detail}`);await updateScene(project.id, scene.sceneId, {status: 'failed',evaluation: {accepted: false,- notes: 'Local video generation is not configured — set settings.imageGen.local.pythonPath in Settings > Image Gen.',+ notes: `Local video generation is not configured — set settings.imageGen.local.pythonPath in Settings > Image Gen.${detail}`,sampledAt: new Date().toISOString(),},});@@ -168,26 +192,55 @@ export async function runSceneRender(project, scene) {isContinuation: continuationSourceFromExtract && !!sourceImagePath,});- const params = {- pythonPath,+ // Creative params are backend-agnostic; the render knobs are not. Grok has no+ // frames/steps/guidance/LoRA dials (it takes a prose brief and a clip length),+ // so passing the local geometry through would be noise the worker ignores —+ // build only what each lane reads. `width`/`height` DO carry over: grok.js+ // derives its base-image aspect ratio from them, which is how a 9:16 project+ // stays 9:16 instead of falling back to the install's configured ratio.+ const shared = {prompt: scene.prompt,negativePrompt: scene.negativePrompt || '',- modelId: project.modelId,width: renderParams.width,height: renderParams.height,- numFrames: renderParams.numFrames,- fps: renderParams.fps,- steps: renderParams.steps,- guidanceScale: renderParams.guidanceScale,- tiling: 'auto',sourceImagePath,- mode: sourceImagePath ? 'image' : 'text',- imageStrength: effectiveImageStrength,- // Smoke-test / dev knob: skips the mlx_video audio-gen pass to cut- // wall-clock per scene roughly in half. Project-level so every scene- // in the project inherits the same setting.- disableAudio: project.disableAudio === true,};+ const params = useGrok+ ? {+ ...shared,+ // Scene duration is authored in the local lane's continuous seconds;+ // grokVideoJobParams snaps it up to a length Grok actually delivers.+ ...grokVideoJobParams(settings, {+ sourceImagePath,+ durationSeconds: scene.durationSeconds,+ width: renderParams.width,+ height: renderParams.height,+ }),+ }+ : {+ ...shared,+ pythonPath,+ // A pinned local model (the commission's `generation.videoModelId`, or the+ // creative-agent render default) wins over the project's own modelId —+ // the project's is the creation-time default, the pin is the user's+ // explicit later choice.+ modelId: videoPin.modelId || project.modelId,+ numFrames: renderParams.numFrames,+ fps: renderParams.fps,+ steps: renderParams.steps,+ guidanceScale: renderParams.guidanceScale,+ tiling: 'auto',+ mode: sourceImagePath ? 'image' : 'text',+ imageStrength: effectiveImageStrength,+ // Smoke-test / dev knob: skips the mlx_video audio-gen pass to cut+ // wall-clock per scene roughly in half. Project-level so every scene+ // in the project inherits the same setting.+ disableAudio: project.disableAudio === true,+ };++ if (useGrok) {+ console.log(`☁️ CD scene ${scene.sceneId} rendering on grok (${params.duration}s clip)`);+ }const owner = `cd:${project.id}:${scene.sceneId}`;const { jobId } = enqueueJob({ kind: 'video', params, owner });diff --git a/server/services/videoGen/backendPin.js b/server/services/videoGen/backendPin.jsnew file mode 100644index 0000000000..df87a29e5b--- /dev/null+++ b/server/services/videoGen/backendPin.js@@ -0,0 +1,108 @@+/**+ * Video Gen — creative-surface backend pin → job params (#3135 / #3231 Phase 4).+ *+ * A Creative Director project can pin which backend renders its video+ * (`project.renderBackend.video = { mode, modelId }`), and a creative+ * commission is the main thing that sets it: the commission's+ * `generation.videoMode` / `.videoModelId` ride onto the project it mints each+ * fire (see creativeCommissions/abilityAdapters.js#buildRenderBackendPin).+ *+ * TWO different surfaces enqueue video for such a project, and both have to+ * honor that pin:+ *+ * 1. the PLAN-driven path — the planner LLM's `media_enqueueVideoJob` tool+ * (`services/creative/tools/media.js#enforceRenderBackendPin`); and+ * 2. the TREATMENT/SCENE path — `creativeDirector/sceneRunner.js`, which+ * renders each treatment scene directly, with no LLM in the loop. This is+ * the path a commission's video actually travels most of the time.+ *+ * #3135 wired only (1). So a commission pinned to Grok still rendered every+ * scene on the local MLX runtime, and an install with no `imageGen.local+ * .pythonPath` failed the whole project up front even though Grok was+ * configured, enabled, and explicitly pinned. This module is the ONE place the+ * resolution ladder and the Grok param shape live, so the two surfaces cannot+ * drift apart again.+ *+ * Both helpers take `settings` rather than reading them, so the callers keep+ * their existing single settings read per enqueue.+ */++import { RENDER_TARGET, normalizeRenderPinValue } from '../../lib/renderTargets.js';+import { nearestGrokDuration } from '../../lib/grokVideoClip.js';+import { renderTargetDefaults } from '../imageGen/cloudProviderConfig.js';+import { VIDEO_GEN_MODE, resolveVideoMode, hasVideoPin } from './modes.js';++/**+ * Resolve the video backend for a CD project through the pin ladder: the+ * project's own `renderBackend.video` pin (per-record, wins) → the surface's+ * `renderDefaults[target].videoMode` pin → the install-wide+ * `settings.videoGen.mode` pin → LOCAL. Every rung is usability-gated by+ * `resolveVideoMode`, so a pin naming a backend whose toggle has since been+ * switched off degrades to local rather than bricking a nightly commission.+ *+ * `pinned` reports whether ANY rung named a backend (presence only, no+ * usability gating) — it's what lets a caller with a "byte-identical when+ * nothing is pinned" contract (enforceRenderBackendPin) return the caller's+ * params untouched instead of re-deriving them.+ *+ * `modelId` is the pinned LOCAL model: the project pin's own id wins over the+ * target default's, matching the mode ladder's precedence. Local is the only+ * video backend with a model knob (the cloud CLIs pick their own), so there is+ * no cross-provider leak to guard against — but callers must still only apply+ * it on the local branch.+ */+export function resolveVideoBackendPin(project, settings, { target = RENDER_TARGET.CREATIVE_AGENT } = {}) {+ const raw = project?.renderBackend?.video || null;+ // Normalize the project's own pin through the SAME rule the settings rungs+ // use (`normalizeRenderPinValue`): the `'auto'` sentinel and blank strings+ // mean "no pin — fall through". A bare truthiness check would read a stored+ // `{ mode: 'auto' }` as a real pin and cost the caller its byte-identical+ // passthrough. Commissions never persist `auto` (buildRenderBackendPin drops+ // it), but a hand-made or peer-synced project can carry the sentinel.+ const mode = normalizeRenderPinValue(raw?.mode);+ const modelId = normalizeRenderPinValue(raw?.modelId);+ const targetDefaults = renderTargetDefaults(settings, target);+ return {+ pinned: !!mode || hasVideoPin(settings, { target }),+ // What the project ASKED for, normalized — null when it pinned nothing.+ // Distinct from `mode` (what it GOT): when the two disagree, the ladder+ // degraded an unusable pin, and only the caller has the context to decide+ // whether that's worth reporting.+ requested: mode,+ mode: resolveVideoMode(mode, settings, { target }),+ modelId: modelId || targetDefaults.videoModel || null,+ };+}++/**+ * The Grok-lane job params for a video render.+ *+ * `mode: 'grok'` is the media-job queue's backend discriminator (it dispatches+ * to videoGen/grok.js on exactly this key); the t2v/i2v semantic that the local+ * lane keeps in `mode` travels as `videoMode` instead, matching what+ * routes/videoGen.js enqueues. videoGen/grok.js reads the same+ * `settings.imageGen.grok` slice the image path does — one CLI, one config.+ *+ * Clip length crosses a contract boundary here: every other surface authors a+ * duration in the local lane's continuous seconds, while Grok delivers 6s or+ * 10s and nothing else (measured — see lib/grokVideoClip.js). Without the+ * translation a 10s scene would silently come back 6s, because grok.js defaults+ * anything undeliverable to its 6s minimum. `nearestGrokDuration` rounds UP to+ * the shortest clip that still covers the request, which is free: a shorter+ * request costs the same wall clock and returns the same footage.+ *+ * `width`/`height` are optional and only used by grok.js to derive an aspect+ * ratio for the base image it generates; when omitted it falls back to the+ * configured `imageGen.grok.aspectRatio`.+ */+export function grokVideoJobParams(settings, { sourceImagePath = null, durationSeconds, width, height } = {}) {+ const grok = settings?.imageGen?.grok || {};+ return {+ mode: VIDEO_GEN_MODE.GROK,+ videoMode: sourceImagePath ? 'image' : 'text',+ grokPath: grok.grokPath,+ duration: nearestGrokDuration(durationSeconds),+ ...(Number.isFinite(width) && Number.isFinite(height) ? { width, height } : {}),+ ...(grok.aspectRatio ? { aspectRatio: grok.aspectRatio } : {}),+ };+}diff --git a/server/services/videoGen/backendPin.test.js b/server/services/videoGen/backendPin.test.jsnew file mode 100644index 0000000000..654aac0f2b--- /dev/null+++ b/server/services/videoGen/backendPin.test.js@@ -0,0 +1,141 @@+import { describe, it, expect } from 'vitest';+import { resolveVideoBackendPin, grokVideoJobParams } from './backendPin.js';+import { VIDEO_GEN_MODE } from './modes.js';+import { RENDER_TARGET } from '../../lib/renderTargets.js';++const grokOn = { imageGen: { grok: { enabled: true, grokPath: '/usr/local/bin/grok' } } };+const grokOff = { imageGen: { grok: { enabled: false, grokPath: '/usr/local/bin/grok' } } };+const project = (video) => ({ id: 'proj-1', renderBackend: video ? { video } : undefined });++describe('resolveVideoBackendPin', () => {+ it('reports no pin and resolves local when nothing is pinned', () => {+ // The byte-identical-when-auto contract: `pinned:false` is what lets the+ // planner's enqueue tool return the caller's params untouched.+ expect(resolveVideoBackendPin(project(null), grokOn)).toEqual({+ pinned: false, requested: null, mode: VIDEO_GEN_MODE.LOCAL, modelId: null,+ });+ });++ it('honors the project pin over the install default', () => {+ const pin = resolveVideoBackendPin(project({ mode: 'grok', modelId: null }), grokOn);+ expect(pin).toEqual({ pinned: true, requested: 'grok', mode: VIDEO_GEN_MODE.GROK, modelId: null });+ });++ it('reports requested vs resolved so a caller can spot a degraded pin', () => {+ // requested !== mode is the ONLY signal that the ladder overrode the user.+ const degraded = resolveVideoBackendPin(project({ mode: 'grok' }), grokOff);+ expect(degraded.requested).toBe('grok');+ expect(degraded.mode).toBe(VIDEO_GEN_MODE.LOCAL);++ const honored = resolveVideoBackendPin(project({ mode: 'grok' }), grokOn);+ expect(honored.requested).toBe(honored.mode);+ });++ it("reports no request for the 'auto' sentinel, so it never reads as degraded", () => {+ expect(resolveVideoBackendPin(project({ mode: 'auto' }), grokOff).requested).toBe(null);+ });++ it('degrades a grok pin to local when grok is not enabled', () => {+ // A nightly commission must still produce something rather than failing+ // every fire because the user flipped the toggle off after pinning.+ const pin = resolveVideoBackendPin(project({ mode: 'grok', modelId: null }), grokOff);+ expect(pin.mode).toBe(VIDEO_GEN_MODE.LOCAL);+ // Still `pinned` — a caller must NOT treat a degraded pin as "no pin", or+ // the local branch would skip applying the pinned model id.+ expect(pin.pinned).toBe(true);+ });++ it('carries the project pin model id', () => {+ const pin = resolveVideoBackendPin(project({ mode: 'local', modelId: 'ltx-2b' }), grokOn);+ expect(pin).toEqual({ pinned: true, requested: 'local', mode: VIDEO_GEN_MODE.LOCAL, modelId: 'ltx-2b' });+ });++ it("prefers the project pin's model over the render-target default", () => {+ const settings = {+ ...grokOn,+ renderDefaults: { [RENDER_TARGET.CREATIVE_AGENT]: { videoMode: 'local', videoModel: 'target-model' } },+ };+ const pin = resolveVideoBackendPin(project({ mode: 'local', modelId: 'project-model' }), settings);+ expect(pin.modelId).toBe('project-model');+ });++ it('falls back to the render-target default when the project pins nothing', () => {+ const settings = {+ ...grokOn,+ renderDefaults: { [RENDER_TARGET.CREATIVE_AGENT]: { videoMode: 'local', videoModel: 'target-model' } },+ };+ const pin = resolveVideoBackendPin(project(null), settings);+ expect(pin).toEqual({ pinned: true, requested: null, mode: VIDEO_GEN_MODE.LOCAL, modelId: 'target-model' });+ });++ it('falls back to the install-wide videoGen.mode pin', () => {+ const pin = resolveVideoBackendPin(project(null), { ...grokOn, videoGen: { mode: 'grok' } });+ expect(pin).toEqual({ pinned: true, requested: null, mode: VIDEO_GEN_MODE.GROK, modelId: null });+ });++ it("treats the 'auto' sentinel as no pin", () => {+ const settings = {+ ...grokOn,+ renderDefaults: { [RENDER_TARGET.CREATIVE_AGENT]: { videoMode: 'auto' } },+ };+ expect(resolveVideoBackendPin(project({ mode: 'auto' }), settings).pinned).toBe(false);+ });++ it('tolerates an absent project and absent settings', () => {+ expect(resolveVideoBackendPin(null, null)).toEqual({+ pinned: false, requested: null, mode: VIDEO_GEN_MODE.LOCAL, modelId: null,+ });+ });+});++describe('grokVideoJobParams', () => {+ it('stamps the queue discriminator and the t2v semantic', () => {+ const params = grokVideoJobParams(grokOn, { durationSeconds: 6 });+ expect(params.mode).toBe(VIDEO_GEN_MODE.GROK);+ expect(params.videoMode).toBe('text');+ expect(params.grokPath).toBe('/usr/local/bin/grok');+ });++ it('marks an i2v render when a source image is present', () => {+ expect(grokVideoJobParams(grokOn, { sourceImagePath: '/img/a.png', durationSeconds: 6 }).videoMode)+ .toBe('image');+ });++ it('rounds a local-lane duration UP to a length grok delivers', () => {+ // An 8s scene must not silently come back 6s — grok only does 6 or 10.+ expect(grokVideoJobParams(grokOn, { durationSeconds: 8 }).duration).toBe(10);+ expect(grokVideoJobParams(grokOn, { durationSeconds: 4 }).duration).toBe(6);+ expect(grokVideoJobParams(grokOn, { durationSeconds: 30 }).duration).toBe(10);+ });++ it('defaults the clip length when none is given', () => {+ expect(grokVideoJobParams(grokOn, {}).duration).toBe(6);+ });++ it('passes width/height through so grok derives the project aspect ratio', () => {+ const params = grokVideoJobParams(grokOn, { durationSeconds: 6, width: 544, height: 960 });+ expect(params.width).toBe(544);+ expect(params.height).toBe(960);+ });++ it('omits width/height when they are not both finite', () => {+ const params = grokVideoJobParams(grokOn, { durationSeconds: 6, width: 544 });+ expect(params).not.toHaveProperty('width');+ expect(params).not.toHaveProperty('height');+ });++ it('carries the configured aspect ratio only when one is set', () => {+ expect(grokVideoJobParams(grokOn, {})).not.toHaveProperty('aspectRatio');+ const withRatio = { imageGen: { grok: { grokPath: 'grok', aspectRatio: '9:16' } } };+ expect(grokVideoJobParams(withRatio, {}).aspectRatio).toBe('9:16');+ });++ it('never emits local-lane render knobs', () => {+ // Grok has no frames/steps/guidance dials; leaking them would be noise the+ // worker silently ignores and a reader would mistake for an honored setting.+ const params = grokVideoJobParams(grokOn, { durationSeconds: 6 });+ for (const key of ['pythonPath', 'numFrames', 'steps', 'guidanceScale', 'fps', 'modelId']) {+ expect(params).not.toHaveProperty(key);+ }+ });+});