Skip to content

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

feat: add music-video media modes and rich code-authored choreography

[._.]/ Adam Eivyda5a53576197
diff --git a/.claude/skills/portos-music-video-code/SKILL.md b/.claude/skills/portos-music-video-code/SKILL.md
index ab13998f6f..8394af3d63 100644
--- a/.claude/skills/portos-music-video-code/SKILL.md
+++ b/.claude/skills/portos-music-video-code/SKILL.md
@@ -11,11 +11,21 @@ PortOS assembles the functions into an immutable candidate version of its layere
Author each `function render(ctx, env)` as a deterministic drawing function of song time. `env.t` is absolute song time; `env.localT` is time since this section began; `env.frame` is the integer frame for seeded motion. Use `env.song.beats`, `env.song.downbeats`, lyric word times, the safe inset and the approved palette. A seek to the same time must draw the same pixels regardless of prior seeks. Change repeated hook direction, staging or seed deliberately while preserving motif and color identity. Keep the host's lyric pass readable: leave negative space and avoid painting over words at the bottom of a scene.
-The host draws selected stills and clips according to each scene's explicit visual layer, then invokes the section function. Add restrained graphics over those assets; for a card scene, draw the entire background. The host resolves only selected project assets and seeks video asynchronously using the chosen performance in/out edit. Do not use network requests, remote URLs, arbitrary paths, dynamic imports, clocks, entropy, or DOM loading in section code. PortOS stages local assets through `window.PORTOS_MV`, owns the sandbox, and renders previews, excerpts and final output from the same song clock.
+The Canvas document host draws selected stills and clips according to each scene's explicit visual layer, then invokes the section function. Compose purposeful subject/prop graphics, camera staging, typography and transitions at the energy specified in the approved choreography; do not treat restrained overlays as the universal goal. Preserve the meaning and readability of selected media. For procedural/card scenes, author the whole animated world, characters, props and action rather than a background with incidental particles. The host resolves only selected project assets and seeks video asynchronously using the chosen performance in/out edit. Do not use network requests, remote URLs, arbitrary paths, dynamic imports, clocks, entropy, or DOM loading in section code. PortOS stages local assets through `window.PORTOS_MV`, owns the sandbox, and renders previews, excerpts and final output from the same song clock.
-Manual ZIP/folder documents and code-only videos have separate controls. The mixed-media action does not alter them until the generated candidate is accepted.
+Manual ZIP/folder documents and native Code videos have separate controls. Code-only is a media policy and can use rich composition documents. Generation keeps the active document selected until the candidate is accepted.
+## Timed choreography and playback review
+
+Before authoring, save **Production review → Edit visual guide and storyboard → Timed choreography and energy plan** in the existing motion-language field. Start with a chosen energy target (for example, restrained verse into driving chorus, or explosive throughout), justified by the song and director's intent. Do not assume subtle motion is good direction. The implementation/feasibility field explains how the selected renderer will execute the plan; it does not replace the choreography.
+
+For each section or shot, record time ranges and music anchors (downbeats, beat counts, lyric words or section entries), then specify subject/prop actions, pose changes and travel, camera path, typography timing, and the entry/exit handoff. Keep intentional still holds distinct from missing motion. On repeated choruses, preserve visual identity while deliberately escalating or transforming action, staging, camera depth, pose range or transition scale. Save corresponding action, staging, camera and transition details in the storyboard and bind lyric anchors. UI authoring and autopilot receive these saved fields as the human-reviewed choreography; changing them invalidates the associated review basis.
+
+Render and watch a continuous chorus proof with its entry and exit, normal-speed playback and master audio. Compare the saved energy target against the result: do major subject/prop actions read, do accents land on the chosen beats/words, do camera and typography support the action, are holds readable, and does the next chorus develop rather than merely repeat? Check motion throughout the interval, including transitions; attractive stills, changing pixels, deterministic seeks and a valid render contract cannot establish choreography quality. If the proof is static or sluggish against an energetic plan, revise the authored actions and test playback again before approving. Record actionable feedback by time range and intended versus observed action. Fill the proof review’s energy comparison and timestamped playback notes (for example, `0:04` or `4.5s`); they are saved against that exact excerpt and filename. A replacement proof needs fresh notes and acknowledgement. Acknowledge audio playback against the saved choreography only after making that comparison; keep the server's revision-bound art, storyboard and proof gates intact.
+
+Respect renderer capabilities while pursuing this direction: native Code uses its documented Canvas restrictions and native output size; composition documents support richer local fonts, authored worlds and the deterministic `seek(t)` contract. Code-only prohibits imagegen for guides as well as output. Build its guides and proofs from code-rendered scenes. A limitation is a reason to revise the implementation plan or choose a supported renderer, not to silently substitute raster assets or remote dependencies.
+
## Revisions and footage variants
Use **Fork vN** before revising a finished code video when the original must stay independently editable. For manual composition documents, **Export ZIP**, edit the HTML/JS locally, then import the revised ZIP/folder into the fork. Imports write immutable versions; unreferenced versions may be pruned, so fork before replacing a document you want to keep. Code-only sections also remain editable through the composition API and the section regeneration action.
@@ -23,3 +33,13 @@ Use **Fork vN** before revising a finished code video when the original must sta
Use **Fork for video generation** to adapt a code or document video into footage. It preserves song, analysis, timed lyrics, storyboard, parent/root lineage and immutable document/development artifact references. It starts in Composed mode with footage scenes, a fresh Cast & Sets stage and no selected mood board, reference images or video takes. Source publishing outputs and active runs are not carried into the fork. The source project is unchanged and forking calls no providers.
In the new project, choose the new mood board, prepare its photographic cast and set sheets, review the retained storyboard and prompts for the new medium, and select the image/video services and generation budget before starting production. Old sheets remain development references, not approval of the new cast. The original code document stays available for export or switching back to Document mode; retain the source project as the code version.
+
+## Whole-scene media modes and rich worlds
+
+Choose **Design and composition media** independently of **Authoring renderer**. Code only admits procedural code, local fonts and the master audio: never request imagegen for guides, mood exploration, storyboards or final frames. Develop visual guides from code-rendered candidate frames. Code + images admits stills throughout planning and composition; Code + images + video also admits footage. Tool selections and budgets remain additional limits. Existing code-only tool briefs migrate restrictively; historical assets remain stored and must be deselected before use under a narrower mode.
+
+In **Compose → Document**, choose **Three.js authored worlds → Generate authored 3D composition** for complete geometry scenes. Each section's `render(ctx, env)` receives `ctx.THREE`, a fresh `ctx.scene`, a perspective `ctx.camera`, and the transparent Canvas2D `ctx.text`. Author environments, articulated characters, props, lights, camera movement and dramatic actions from absolute song time. Every seek creates a fresh world; do not integrate physics or depend on earlier frames. This generated renderer currently composes geometry and typography only. Use the Canvas layered renderer or an imported document for selected images/video. Native **Code** remains a separate 720p Canvas capability, not the definition of code-only.
+
+PortOS packages installed Three.js, license, local fonts, validated author functions and a dependency hash manifest in the immutable document version. It does not install packages, load CDNs or grant network access. Preview supports acyclic local static ES-module graphs (including inline module entrypoints); remote/bare/dynamic imports are unsupported. The same `portosComposition.seek(t)` drives preview, excerpt and final capture, normally 1080p24. Imported documents may declare supported motion blur; export honors that contract. A valid contract proves execution, not art quality: inspect authored characters/action and changing frames, then the existing treatment/proof workflow decides readiness.
+
+Code-only autopilot preserves text direction and defaults to this document authoring path, retaining explicitly saved legacy Code choices. It never requests image guides or an image/video provider. Code-rendered prototypes and visual planning remain required by the production review workflow; skipping raster moodboard assets is not approval to skip art direction.
diff --git a/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.jsx b/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.jsx
index 5a1dcd4f3d..0a1db1e8e4 100644
--- a/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.jsx
+++ b/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.jsx
@@ -1,3 +1,5 @@
+import CodeAuthoringPicker from '../../../musicVideo/CodeAuthoringPicker.jsx';
+import MediaModePicker from '../../../musicVideo/MediaModePicker.jsx';
import { useEffect, useState } from 'react';
import ToggleChip from '../../../ui/ToggleChip';
import ProviderModelSelector from '../../../ProviderModelSelector';
@@ -59,7 +61,7 @@ export default function MusicVideoAutopilotSettings({ taskType, config, onUpdate
return (
<form onSubmit={handleSave} className="space-y-4">
<p className="text-xs text-gray-500">
- Each run turns the oldest unused Brain idea into a fully autonomous music video with these settings. Use Run Now under Global defaults to start one immediately.
+ Each run turns the oldest unused Brain idea into an authored music video with these settings, pausing for art, storyboard and animated proof approvals. Use Run Now under Global defaults to start one immediately.
</p>
<div>
@@ -71,6 +73,8 @@ export default function MusicVideoAutopilotSettings({ taskType, config, onUpdate
<ToggleChip id="mv-ap-instrumental" label="Instrumental (no vocals)" checked={draft.instrumental} onToggle={() => patch({ instrumental: !draft.instrumental })} />
+ <MediaModePicker id="mv-auto-media-mode" value={draft.mediaMode} onChange={(mediaMode) => patch({ mediaMode })} />
+ <CodeAuthoringPicker value={draft.authoring} onChange={(authoring) => patch({ authoring })} disabled={updating} />
<ToolPicker idPrefix="mv-ap" tools={draft.tools} models={draft.models} onChange={patch} />
<MoodBoardPicker id="mv-ap-mood-board" value={draft.moodBoardId} onChange={(moodBoardId) => patch({ moodBoardId })} />
diff --git a/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.test.jsx b/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.test.jsx
index 2691302cbc..f0b8dc61fa 100644
--- a/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.test.jsx
+++ b/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.test.jsx
@@ -5,8 +5,9 @@ vi.mock('../../../../services/apiMoodBoard.js', () => ({
listMoodBoardNames: vi.fn(async () => [{ id: 'mb-1', name: 'Neon Rain' }]),
}));
vi.mock('../../../../hooks/useProviderModels', () => ({
- default: () => ({
- providers: [], selectedProviderId: '', selectedModel: '', availableModels: [],
+ default: ({ filter } = {}) => ({
+ providers: filter ? [{ id: 'fixture-api', name: 'Fixture API', type: 'api', enabled: true, defaultModel: 'fixture-model', models: ['fixture-model'] }].filter(filter) : [],
+ selectedProviderId: '', selectedModel: '', availableModels: filter ? ['fixture-model'] : [],
setSelectedProviderId: () => {}, setSelectedModel: () => {},
}),
}));
@@ -32,12 +33,15 @@ describe('MusicVideoAutopilotSettings', () => {
fireEvent.change(screen.getByLabelText('Budget cap (USD)'), { target: { value: '8' } });
fireEvent.click(screen.getByLabelText('Instrumental (no vocals)'));
+ fireEvent.change(screen.getByLabelText('Design and composition media'), { target: { value: 'code-images' } });
+ fireEvent.change(screen.getByLabelText('Code authoring provider'), { target: { value: 'fixture-api' } });
fireEvent.click(screen.getByText('Save settings'));
await waitFor(() => expect(onUpdate).toHaveBeenCalledTimes(1));
const [type, payload] = onUpdate.mock.calls[0];
expect(type).toBe('music-video-autopilot');
expect(payload.taskMetadata.musicVideoAutopilot).toMatchObject({
+ mediaMode: 'code-images', authoring: { providerId: 'fixture-api', model: 'fixture-model' },
tools: ['image:local'], budgetUsd: 8, instrumental: true, ideaTags: ['song'], moodBoardId: 'mb-1',
limits: { maxGenerations: 10, maxReviewAttempts: 5 },
});
@@ -45,21 +49,23 @@ describe('MusicVideoAutopilotSettings', () => {
it('round-trips the song source and the Suno fallback opt-in through the saved params', async () => {
const onUpdate = vi.fn(async () => {});
- const config = { taskMetadata: { musicVideoAutopilot: { songSource: 'suno', localFallback: true } } };
+ const config = { taskMetadata: { musicVideoAutopilot: { tools: ['code:render'], songSource: 'suno', localFallback: true } } };
render(<MusicVideoAutopilotSettings taskType="music-video-autopilot" config={config} onUpdate={onUpdate} updating={false} setUpdating={() => {}} />);
expect(screen.getByLabelText('Render locally if Suno is unavailable').checked).toBe(true);
+ expect(screen.getByLabelText('Design and composition media').value).toBe('code-only');
fireEvent.change(screen.getByLabelText('Song source'), { target: { value: 'local' } });
fireEvent.click(screen.getByText('Save settings'));
await waitFor(() => expect(onUpdate).toHaveBeenCalled());
- expect(onUpdate.mock.calls[0][1].taskMetadata.musicVideoAutopilot).toMatchObject({ songSource: 'local', localFallback: false });
+ expect(onUpdate.mock.calls[0][1].taskMetadata.musicVideoAutopilot).toMatchObject({ mediaMode: 'code-only', songSource: 'local', localFallback: false });
});
it('keeps a saved writer-LLM pin when saved before the provider catalog loads', async () => {
const onUpdate = vi.fn(async () => {});
- const config = { taskMetadata: { musicVideoAutopilot: { llm: { providerId: 'prov-1', model: 'm-1' } } } };
+ const config = { taskMetadata: { musicVideoAutopilot: { authoring: { providerId: 'saved-author', model: 'saved-model', effort: 'high' }, llm: { providerId: 'prov-1', model: 'm-1' } } } };
render(<MusicVideoAutopilotSettings taskType="music-video-autopilot" config={config} onUpdate={onUpdate} updating={false} setUpdating={() => {}} />);
fireEvent.click(screen.getByText('Save settings'));
await waitFor(() => expect(onUpdate).toHaveBeenCalled());
expect(onUpdate.mock.calls[0][1].taskMetadata.musicVideoAutopilot.llm).toEqual({ providerId: 'prov-1', model: 'm-1' });
+ expect(onUpdate.mock.calls[0][1].taskMetadata.musicVideoAutopilot.authoring).toEqual({ providerId: 'saved-author', model: 'saved-model', effort: 'high' });
});
});
diff --git a/client/src/components/musicVideo/AutonomousRunPanel.test.jsx b/client/src/components/musicVideo/AutonomousRunPanel.test.jsx
index 6ec5e6fddc..54c79393c7 100644
--- a/client/src/components/musicVideo/AutonomousRunPanel.test.jsx
+++ b/client/src/components/musicVideo/AutonomousRunPanel.test.jsx
@@ -24,8 +24,12 @@ vi.mock('../../services/apiMusicVideo.js', () => ({
vi.mock('../../services/apiMoodBoard.js', () => ({ listMoodBoardNames: vi.fn(async () => [{ id: 'mb-1', name: 'Neon Rain' }]) }));
vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), info: vi.fn(), error: vi.fn() } }));
vi.mock('../../hooks/useProviderModels.js', () => ({
- default: () => ({
- providers: [], selectedProviderId: '', selectedModel: '', availableModels: [],
+ default: ({ filter } = {}) => ({
+ providers: filter ? [
+ { id: 'fixture-api', name: 'Fixture API', type: 'api', enabled: true, defaultModel: 'fixture-model', models: ['fixture-model'] },
+ { id: 'fixture-tui', name: 'Fixture TUI', type: 'tui', enabled: true },
+ { id: 'fixture-cli', name: 'Unverified CLI', type: 'cli', enabled: true },
+ ].filter(filter) : [], selectedProviderId: '', selectedModel: '', availableModels: filter ? ['fixture-model'] : [],
setSelectedProviderId: () => {}, setSelectedModel: () => {},
}),
}));
@@ -189,7 +193,7 @@ describe('AutonomousRunPanel stage output', () => {
});
describe('AutonomousStartDrawer', () => {
- it('starts a run from the prompt alone, sending the free tools, no checkpoints and no blank optionals', async () => {
+ it('requires an explicit compatible code author before starting with the free tools', async () => {
api.startAutonomousMusicVideo.mockResolvedValue({ project: { id: 'mv-new', name: 'New' }, run: baseRun() });
const onStarted = vi.fn();
render(<AutonomousStartDrawer open onClose={() => {}} onStarted={onStarted} />);
@@ -197,14 +201,19 @@ describe('AutonomousStartDrawer', () => {
const submit = screen.getByRole('button', { name: /start autonomous video/i });
expect(submit.disabled).toBe(true);
fireEvent.change(screen.getByLabelText('Prompt'), { target: { value: ' a courier crosses a rainy city ' } });
+ expect(submit.disabled).toBe(true);
+ expect(screen.queryByRole('option', { name: 'Fixture TUI' })).toBeNull();
+ expect(screen.queryByRole('option', { name: 'Unverified CLI' })).toBeNull();
+ fireEvent.change(screen.getByLabelText('Code authoring provider'), { target: { value: 'fixture-api' } });
fireEvent.click(submit);
await waitFor(() => expect(onStarted).toHaveBeenCalledWith({ id: 'mv-new', name: 'New' }));
const [body, options] = api.startAutonomousMusicVideo.mock.calls[0];
expect(options).toEqual({ silent: true });
expect(body).toEqual({
- prompt: 'a courier crosses a rainy city', songSource: 'suno', localFallback: false, instrumental: false, tools: ['image:local', 'video:local'],
+ prompt: 'a courier crosses a rainy city', mediaMode: 'code-images-video', songSource: 'suno', localFallback: false, instrumental: false, tools: ['image:local', 'video:local'],
budgetUsd: null, limits: { maxGenerations: 40 }, checkpoints: [],
+ authoring: { providerId: 'fixture-api', model: 'fixture-model' },
});
});
@@ -217,6 +226,7 @@ describe('AutonomousStartDrawer', () => {
fireEvent.change(screen.getByLabelText(/budget cap/i), { target: { value: '12' } });
await waitFor(() => expect(screen.getByRole('option', { name: 'Neon Rain' })).toBeTruthy());
fireEvent.change(screen.getByLabelText('Mood board'), { target: { value: 'mb-1' } });
+ fireEvent.change(screen.getByLabelText('Code authoring provider'), { target: { value: 'fixture-api' } });
fireEvent.click(screen.getByRole('button', { name: /start autonomous video/i }));
await waitFor(() => expect(api.startAutonomousMusicVideo).toHaveBeenCalled());
expect(api.startAutonomousMusicVideo.mock.calls[0][0]).toMatchObject({
@@ -229,6 +239,7 @@ describe('AutonomousStartDrawer', () => {
render(<AutonomousStartDrawer open onClose={() => {}} onStarted={() => {}} />);
fireEvent.change(screen.getByLabelText('Prompt'), { target: { value: 'p' } });
fireEvent.click(screen.getByLabelText(/render locally if suno is unavailable/i));
+ fireEvent.change(screen.getByLabelText('Code authoring provider'), { target: { value: 'fixture-api' } });
fireEvent.click(screen.getByRole('button', { name: /start autonomous video/i }));
await waitFor(() => expect(api.startAutonomousMusicVideo).toHaveBeenCalledTimes(1));
expect(api.startAutonomousMusicVideo.mock.calls[0][0]).toMatchObject({ songSource: 'suno', localFallback: true });
@@ -236,6 +247,7 @@ describe('AutonomousStartDrawer', () => {
fireEvent.change(screen.getByLabelText('Song source'), { target: { value: 'local' } });
expect(screen.queryByLabelText(/render locally if suno is unavailable/i)).toBeNull();
fireEvent.change(screen.getByLabelText('Prompt'), { target: { value: 'p' } });
+ fireEvent.change(screen.getByLabelText('Code authoring provider'), { target: { value: 'fixture-api' } });
fireEvent.click(screen.getByRole('button', { name: /start autonomous video/i }));
await waitFor(() => expect(api.startAutonomousMusicVideo).toHaveBeenCalledTimes(2));
// The stale fallback tick must not ride along once Suno is no longer the source.
diff --git a/client/src/components/musicVideo/AutonomousStartDrawer.jsx b/client/src/components/musicVideo/AutonomousStartDrawer.jsx
index 9238f08971..7392db495f 100644
--- a/client/src/components/musicVideo/AutonomousStartDrawer.jsx
+++ b/client/src/components/musicVideo/AutonomousStartDrawer.jsx
@@ -1,3 +1,5 @@
+import CodeAuthoringPicker from './CodeAuthoringPicker.jsx';
+import MediaModePicker from './MediaModePicker.jsx';
import { useState } from 'react';
import { Wand2 } from 'lucide-react';
import Drawer from '../Drawer.jsx';
@@ -25,13 +27,14 @@ const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded
export default function AutonomousStartDrawer({ open, onClose, onStarted }) {
const [draft, setDraft] = useState(emptyAutonomousDraft);
const [submitting, setSubmitting] = useState(false);
+ const [authoringReady, setAuthoringReady] = useState(false);
const llm = useProviderModels({ allowDefault: true, silent: true, withEffort: true });
const [effort, setEffort] = useState('');
const patch = (next) => setDraft((d) => ({ ...d, ...next }));
const toggleCheckpoint = (id) => patch({
checkpoints: AUTONOMOUS_CHECKPOINT_IDS.filter((c) => (c === id ? !draft.checkpoints.includes(c) : draft.checkpoints.includes(c))),
});
- const valid = draft.prompt.trim().length > 0;
+ const valid = draft.prompt.trim().length > 0 && authoringReady;
const handleSubmit = (e) => {
e.preventDefault();
@@ -56,7 +59,7 @@ export default function AutonomousStartDrawer({ open, onClose, onStarted }) {
onClose={onClose}
size="md"
title="Autonomous music video"
- subtitle="One prompt in — lyrics, a song, a mood board and the video out"
+ subtitle="One prompt in — lyrics, a song, visual direction and an authored video"
closeOnEsc={false}
closeOnBackdrop={false}
>
@@ -73,7 +76,7 @@ export default function AutonomousStartDrawer({ open, onClose, onStarted }) {
className={inputClass}
/>
<p className="text-[11px] text-port-text-muted mt-1">
- The agent also builds its own mood board and visual style from this prompt.
+ The agent develops visual direction from this prompt within your selected media mode.
</p>
</div>
@@ -81,6 +84,8 @@ export default function AutonomousStartDrawer({ open, onClose, onStarted }) {
<ToggleChip id="mv-auto-instrumental" label="Instrumental (no vocals)" checked={draft.instrumental} onToggle={() => patch({ instrumental: !draft.instrumental })} />
+ <MediaModePicker id="mv-auto-media-mode" value={draft.mediaMode} onChange={(mediaMode) => patch({ mediaMode })} />
+ <CodeAuthoringPicker value={draft.authoring} onChange={(authoring) => patch({ authoring })} onValidityChange={setAuthoringReady} disabled={submitting} />
<ToolPicker tools={draft.tools} models={draft.models} onChange={patch} />
<MoodBoardPicker id="mv-auto-mood-board" value={draft.moodBoardId} onChange={(moodBoardId) => patch({ moodBoardId })} />
@@ -122,7 +127,7 @@ export default function AutonomousStartDrawer({ open, onClose, onStarted }) {
/>
))}
</div>
- <p className="text-[11px] text-port-text-muted mt-1">With none picked the run is fully unattended.</p>
+ <p className="text-[11px] text-port-text-muted mt-1">Production still pauses for your art, storyboard and animated proof approvals.</p>
</fieldset>
{llm.providers.length > 0 && (
diff --git a/client/src/components/musicVideo/AutopilotPanel.jsx b/client/src/components/musicVideo/AutopilotPanel.jsx
index 136a8d55bb..35850ac4ff 100644
--- a/client/src/components/musicVideo/AutopilotPanel.jsx
+++ b/client/src/components/musicVideo/AutopilotPanel.jsx
@@ -2,6 +2,7 @@ import { useState } from 'react';
import { Bot, Clapperboard, Pause, Play, X } from 'lucide-react';
import AutomationBriefFields from './AutomationBriefFields.jsx';
import Pill from '../ui/Pill.jsx';
+import { supportsToolFreeOneShot, toolFreeOneShotSelectionPolicy } from '../../utils/providerSelection.js';
import useProviderModels from '../../hooks/useProviderModels.js';
import ProviderModelSelector from '../ProviderModelSelector.jsx';
import ToggleChip from '../ui/ToggleChip.jsx';
@@ -34,10 +35,6 @@ const briefToolLabel = new Map(MUSIC_VIDEO_AUTOMATION_TOOLS.map((t) => [t.id, t.
const actionClass = 'text-sm text-port-accent min-h-[44px] sm:min-h-0 px-1';
const routeLabel = (route) => `${toolLabel.get(`${route.kind}:${route.mode}`) || `${route.kind} ${route.mode}`}${route.model ? ` · ${route.model}` : ''}`;
-// Code authoring runs one-shot and tool-free (server: isToolFreeOneShotProvider), which a
-// TUI provider never is — offering one here only sets up a refusal at Start.
-const AUTHORING_PROVIDERS = (provider) => provider.enabled !== false && provider.type !== 'tui';
-
const ROUTE_LABELS = [['plan', 'Shot planning'], ['castAndSets', 'Cast & Sets direction']];
const initialPool = (project) => {
@@ -158,7 +155,7 @@ function RunView({ run, production, codeFirst, project }) {
function StartForm({ project, production }) {
const assets = codeFirstProductionAssets(project);
- const author = useProviderModels({ allowDefault: false, silent: true, withEffort: true, filter: AUTHORING_PROVIDERS });
+ const author = useProviderModels({ allowDefault: false, silent: true, withEffort: true, filter: Boolean });
const [authorEffort, setAuthorEffort] = useState('');
const [pool, setPool] = useState(() => initialPool(project));
const [directive, setDirective] = useState('');
@@ -174,7 +171,7 @@ function StartForm({ project, production }) {
const hasImage = pool.some((id) => id.startsWith('image:'));
const hasVideo = pool.some((id) => id.startsWith('video:'));
const routesValid = assets ? (!assets.requiredRoutes.image || hasImage) && (!assets.requiredRoutes.video || hasVideo) : hasImage && hasVideo;
- const valid = routesValid && (!assets || (project.scenes?.length > 0 && assets.conflicts.length === 0 && author.selectedProviderId && author.selectedModel))
+ const valid = routesValid && (!assets || (project.scenes?.length > 0 && assets.conflicts.length === 0 && supportsToolFreeOneShot(author.providers.find((entry) => entry.id === author.selectedProviderId)) && author.selectedProviderId && author.selectedModel))
&& Number.isInteger(maxGenerations) && maxGenerations >= 1 && maxGenerations <= 500
&& Number.isInteger(maxReviewAttempts) && maxReviewAttempts >= 1 && maxReviewAttempts <= 10
&& (capValue == null || (Number.isFinite(capValue) && capValue >= 0));
@@ -245,12 +242,12 @@ function StartForm({ project, production }) {
onModelChange={author.setSelectedModel}
effort={authorEffort}
onEffortChange={setAuthorEffort}
- label="Code authoring"
+ selectionPolicy={toolFreeOneShotSelectionPolicy} label="Code authoring"
disabled={production.busy}
modelDisabled={author.availableModels.length === 0}
compact
/>}
- {assets && <p className="text-port-text-muted">Authoring calls consume the generation limit. Unknown authoring prices require no dollar cap; a free/local authoring provider can use a cap. Reviews have a separate call limit.</p>}
+ {assets && <p className="text-port-text-muted">Choose an API provider or a server-verified tool-free CLI; TUI sessions cannot author. Authoring calls consume the generation limit. Unknown authoring prices require no dollar cap; a free/local authoring provider can use a cap. Reviews have a separate call limit.</p>}
{providers.length > 0 && (
<ProviderModelSelector
providers={providers}
diff --git a/client/src/components/musicVideo/AutopilotPanel.test.jsx b/client/src/components/musicVideo/AutopilotPanel.test.jsx
index 873164c4db..bacdf5b254 100644
--- a/client/src/components/musicVideo/AutopilotPanel.test.jsx
+++ b/client/src/components/musicVideo/AutopilotPanel.test.jsx
@@ -23,9 +23,11 @@ vi.mock('../../services/apiMusicVideo.js', () => ({
cancelMusicVideoProduction: vi.fn(),
}));
vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), info: vi.fn(), error: vi.fn() } }));
+const authorProvider = vi.hoisted(() => ({ type: 'api', toolFreeOneShot: true }));
vi.mock('../../hooks/useProviderModels.js', () => ({
default: (options) => options.allowDefault === false ? {
- providers: [{ id: 'local-fixture', name: 'Local fixture', models: ['fixture-model'] }], selectedProviderId: 'local-fixture', selectedModel: 'fixture-model', availableModels: ['fixture-model'],
+ providers: [{ id: 'local-fixture', name: 'Local fixture', models: ['fixture-model'], ...authorProvider }], selectedProviderId: 'local-fixture', selectedModel: 'fixture-model', availableModels: ['fixture-model'],
+ selectedProvider: { providerId: 'local-fixture', model: 'fixture-model' },
setSelectedProviderId: () => {}, setSelectedModel: () => {},
} : ({
providers: [], selectedProviderId: '', selectedModel: '', availableModels: [],
@@ -178,7 +180,11 @@ function ProductionHarness({ initial }) {
}
describe('AutopilotPanel production run', () => {
- beforeEach(() => { vi.clearAllMocks(); listeners.clear(); });
+ beforeEach(() => {
+ Object.assign(authorProvider, { type: 'api', toolFreeOneShot: true });
+ vi.clearAllMocks();
+ listeners.clear();
+ });
it('shows a zero-allowance plan and requires an approved scene plan before Start', () => {
render(<ProductionHarness initial={{ id: 'p1', productionRuns: [],
@@ -190,6 +196,21 @@ describe('AutopilotPanel production run', () => {
expect(screen.getByRole('button', { name: /Start production/ })).toBeDisabled();
});
+ it('blocks an unsupported selected CLI before starting production and keeps its pin visible', () => {
+ Object.assign(authorProvider, { type: 'cli', toolFreeOneShot: false });
+ render(<ProductionHarness initial={{ id: 'p1', productionRuns: [],
+ productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 },
+ composition: { mode: 'document' }, audioAnalysis: { durationSec: 8 },
+ scenes: [{ sceneId: 'code', startSec: 0, endSec: 8 }],
+ treatment: { revision: 1, appliedRevision: 1, shotDirections: [{ sceneId: 'code', medium: 'procedural', mediumRationale: 'Typography' }] },
+ }} />);
+ expect(screen.getByRole('option', { name: 'Local fixture (not permitted here)' }).disabled).toBe(true);
+ const start = screen.getByRole('button', { name: 'Start production' });
+ expect(start.disabled).toBe(true);
+ fireEvent.click(start);
+ expect(api.startMusicVideoProduction).not.toHaveBeenCalled();
+ });
+
it('starts a code-only plan with a separate authoring model and an empty image/video pool', async () => {
api.startMusicVideoProduction.mockResolvedValueOnce({});
render(<ProductionHarness initial={{ id: 'p1', productionRuns: [],
diff --git a/client/src/components/musicVideo/CodeAuthoringPicker.jsx b/client/src/components/musicVideo/CodeAuthoringPicker.jsx
new file mode 100644
index 0000000000..e55d53bf1d
--- /dev/null
+++ b/client/src/components/musicVideo/CodeAuthoringPicker.jsx
@@ -0,0 +1,37 @@
+import { useEffect } from 'react';
+import ProviderModelSelector from '../ProviderModelSelector.jsx';
+import { supportsToolFreeOneShot, toolFreeOneShotSelectionPolicy } from '../../utils/providerSelection.js';
+import useProviderModels from '../../hooks/useProviderModels.js';
+
+/** Explicit authoring pin, separate from the brief/lyrics provider (which may be a TUI). */
+export default function CodeAuthoringPicker({ value, onChange, onValidityChange, disabled = false }) {
+ const author = useProviderModels({ allowDefault: true, silent: true, withEffort: true, filter: Boolean });
+ const current = value || { providerId: '', model: '', effort: '' };
+ const { setSelectedProviderId, setSelectedModel } = author;
+ useEffect(() => {
+ setSelectedProviderId(current.providerId || '');
+ setSelectedModel(current.model || '');
+ }, [current.providerId, current.model, setSelectedProviderId, setSelectedModel]);
+ const selected = author.providers.find((provider) => provider.id === current.providerId);
+ const valid = !author.loading && supportsToolFreeOneShot(selected) && Boolean(current.providerId && current.model);
+ useEffect(() => { onValidityChange?.(valid); }, [valid, onValidityChange]);
+ const pickProvider = (providerId) => {
+ const provider = author.providers.find((entry) => entry.id === providerId);
+ // An explicit provider choice pins its configured model, never an unshown
+ // active-provider fallback. A provider without a default needs a model pick.
+ onChange({ providerId, model: provider?.defaultModel || '', effort: '' });
+ };
+ return <div className="min-w-0 space-y-1">
+ <ProviderModelSelector
+ providers={author.providers} selectedProviderId={current.providerId || ''}
+ selectedModel={current.model || ''} availableModels={author.availableModels}
+ onProviderChange={pickProvider} onModelChange={(model) => onChange({ ...current, model })}
+ effort={current.effort || ''} onEffortChange={(effort) => onChange({ ...current, effort })}
+ selectionPolicy={toolFreeOneShotSelectionPolicy} label="Code authoring provider" modelLabel="Code authoring model"
+ emptyProviderOption="Choose an authoring provider" emptyModelOption="Choose an authoring model"
+ includeDefaultModel disabled={disabled} loading={author.loading} compact alwaysShowModel
+ />
+ <p className="text-xs text-port-text-muted">Required for every media mode. Choose an API provider or a supported headless CLI that disables tools. TUI sessions cannot author composition documents. The server rechecks compatibility before generation.</p>
+ {!author.loading && !valid && <p className="text-xs text-port-warning" role="status">Select an available code authoring provider and model before starting a run. Saved unavailable pins are retained until you replace them.</p>}
+ </div>;
+}
diff --git a/client/src/components/musicVideo/CreateProjectDrawer.jsx b/client/src/components/musicVideo/CreateProjectDrawer.jsx
index 358cd41200..6b751537ec 100644
--- a/client/src/components/musicVideo/CreateProjectDrawer.jsx
+++ b/client/src/components/musicVideo/CreateProjectDrawer.jsx
@@ -1,3 +1,4 @@
+import MediaModePicker from './MediaModePicker.jsx';
import { Bot, Clapperboard, Plus, Music, Sparkles, FileText, CheckCircle2 } from 'lucide-react';
import Drawer from '../Drawer.jsx';
import YoutubeImportControls from './YoutubeImportControls.jsx';
@@ -125,6 +126,7 @@ export default function CreateProjectDrawer({ open, onClose, form, onFormChange,
{/* 2. Project Name */}
<div>
+ <MediaModePicker value={form.mediaMode} onChange={(mediaMode) => onFormChange({ mediaMode })} />
<label htmlFor="mv-name" className="block text-xs text-port-text-muted mb-1">Name</label>
<input
id="mv-name"
diff --git a/client/src/components/musicVideo/DocumentCompositionPanel.jsx b/client/src/components/musicVideo/DocumentCompositionPanel.jsx
index a67334c998..4b30ca86f1 100644
--- a/client/src/components/musicVideo/DocumentCompositionPanel.jsx
+++ b/client/src/components/musicVideo/DocumentCompositionPanel.jsx
@@ -1,3 +1,6 @@
+import { supportsToolFreeOneShot, toolFreeOneShotSelectionPolicy } from '../../utils/providerSelection.js';
+import MediaModePicker from './MediaModePicker.jsx';
+import { musicVideoMediaMode, musicVideoDocumentRenderer } from '../../../../server/lib/musicVideoMediaPolicy.js';
import { useEffect, useState } from 'react';
import FilePickerButton from '../ui/FilePickerButton.jsx';
import { Download, FileArchive, FolderInput, LayoutTemplate, Unlink, Film, RotateCcw } from 'lucide-react';
@@ -136,7 +139,7 @@ export default function DocumentCompositionPanel({ project, audioUrl, onProject,
const {
providers, selectedProviderId, selectedModel, availableModels, selectedProvider,
setSelectedProviderId, setSelectedModel,
- } = useProviderModels({ preselectDefaults: true, silent: true });
+ } = useProviderModels({ preselectDefaults: true, silent: true, filter: Boolean });
useEffect(() => {
let active = true;
@@ -172,6 +175,7 @@ export default function DocumentCompositionPanel({ project, audioUrl, onProject,
});
const detach = confirmFirst('detach', () => run('detach', () => detachMusicVideoCompositionDocument(project.id, { silent: true }), 'Composition document detached'));
const effectiveModel = selectedModel || selectedProvider?.defaultModel || '';
+ const authoringValid = supportsToolFreeOneShot(providers.find((entry) => entry.id === selectedProviderId)) && Boolean(selectedProviderId && effectiveModel);
const provider = { providerId: selectedProviderId, model: effectiveModel };
const selectedSectionValid = candidate?.sections?.some((section) => section.id === selectedSection) || false;
const generate = () => run('generate', () => generateMusicVideoMixedMediaDocument(project.id, provider, { silent: true }), 'Candidate ready to review');
@@ -226,19 +230,27 @@ export default function DocumentCompositionPanel({ project, audioUrl, onProject,
</button>
</div>
<div className="space-y-2 rounded border border-port-border p-2">
+ <MediaModePicker value={musicVideoMediaMode(project)} disabled={!!busy} onChange={(mediaMode) => run('policy', () => updateMusicVideoProject(project.id, { mediaMode }, { silent: true }).then((project) => ({ project })), 'Media mode saved')} />
+ <label htmlFor="mv-doc-renderer" className="block text-xs text-port-text-muted">Authoring renderer</label>
+ <select id="mv-doc-renderer" disabled={!!busy} value={musicVideoDocumentRenderer(project)} className={inputCls}
+ onChange={(event) => run('renderer', () => updateMusicVideoProject(project.id, { composition: { ...compositionDraft(project), authoringRenderer: event.target.value } }, { silent: true }).then((project) => ({ project })), 'Renderer saved')}>
+ <option value="three">Three.js authored worlds</option><option value="canvas">Canvas layered scenes</option>
+ </select>
+ <p className="text-xs text-port-text-muted">Three.js: modeled geometry, lighting, articulated characters and camera, with a local font overlay. Generated Three.js worlds use geometry only; selected images/video require Canvas or an imported document. Preview and export share deterministic seek(t), 1080p at 24 fps by default. Native Code mode remains the limited 720p Canvas renderer. Local ES modules and fonts are packaged; remote imports are blocked. Document motion blur is honored on export.</p>
<NarrativeEventsEditor key={`${project.id}-${JSON.stringify([project.composition?.narrativeEvents, project.composition?.reactiveSections])}`}
project={project} sections={candidate?.sections || []} disabled={!!busy} onSave={saveEvents} onPendingChange={setEventPending} />
<p className="text-xs text-port-text-muted">Generate from the approved treatment, song timing and selected project assets. Missing media is reported before any provider call.</p>
{providers.length > 0 && <ProviderModelSelector
providers={providers} selectedProviderId={selectedProviderId} selectedModel={selectedModel}
availableModels={availableModels} onProviderChange={setSelectedProviderId} onModelChange={setSelectedModel}
- label="Mixed-media code provider" disabled={!!busy} modelDisabled={availableModels.length === 0}
+ selectionPolicy={toolFreeOneShotSelectionPolicy} label="Mixed-media code provider" disabled={!!busy} modelDisabled={availableModels.length === 0}
compact alwaysShowModel
/>}
- <p className="text-xs text-port-text-muted">Code authoring uses {selectedProvider?.name || selectedProviderId || 'no provider selected'} / {effectiveModel || 'no model selected'}. Nothing is sent until you click.</p>
+ <p className="text-xs text-port-text-muted">Code authoring uses {selectedProvider?.name || selectedProviderId || 'no provider selected'} / {effectiveModel || 'no model selected'}. Nothing is sent until you click. API providers and server-verified tool-free CLIs can author; TUI sessions cannot.</p>
+ {!authoringValid && <p className="text-xs text-port-warning" role="status">Choose a compatible code authoring provider and model before generation.</p>}
<div className="flex flex-wrap items-end gap-2">
- <button type="button" className={`${buttonCls} bg-port-accent text-white`} disabled={!!busy || eventPending || !selectedProviderId || !effectiveModel} onClick={generate}>
- <Film size={14} /> {busy === 'generate' ? 'Generating…' : 'Generate mixed-media composition'}
+ <button type="button" className={`${buttonCls} bg-port-accent text-white`} disabled={!!busy || eventPending || !authoringValid} onClick={generate}>
+ <Film size={14} /> {busy === 'generate' ? 'Generating…' : musicVideoDocumentRenderer(project) === 'three' ? 'Generate authored 3D composition' : 'Generate mixed-media composition'}
</button>
{candidate?.source && <>
<div>
@@ -248,10 +260,10 @@ export default function DocumentCompositionPanel({ project, audioUrl, onProject,
{candidate.sections.map((section) => <option key={section.id} value={section.id}>{section.label || section.id} · {section.startSec}s</option>)}
</select>
</div>
- <button type="button" className={buttonCls} disabled={!!busy || eventPending || !selectedSectionValid || candidate.stale || !selectedProviderId || !effectiveModel} onClick={regenerate}>
+ <button type="button" className={buttonCls} disabled={!!busy || eventPending || !selectedSectionValid || candidate.stale || !authoringValid} onClick={regenerate}>
<RotateCcw size={14} /> {busy === 'regenerate' ? 'Regenerating…' : 'Regenerate section'}
</button>
- <button type="button" className={buttonCls} disabled={!!busy || eventPending || !candidate.eventRevisionAvailable || !selectedProviderId || !effectiveModel} onClick={reviseEvents}>
+ <button type="button" className={buttonCls} disabled={!!busy || eventPending || !candidate.eventRevisionAvailable || !authoringValid} onClick={reviseEvents}>
{busy === 'event-revision' ? 'Revising events…' : 'Revise events only'}
</button>
</>}
diff --git a/client/src/components/musicVideo/DocumentCompositionPanel.test.jsx b/client/src/components/musicVideo/DocumentCompositionPanel.test.jsx
index b9b23d28d5..d376b44a0b 100644
--- a/client/src/components/musicVideo/DocumentCompositionPanel.test.jsx
+++ b/client/src/components/musicVideo/DocumentCompositionPanel.test.jsx
@@ -17,10 +17,11 @@ const api = vi.hoisted(() => ({
updateMusicVideoProject: vi.fn(),
}));
vi.mock('../../services/apiMusicVideo.js', () => api);
+const authorProvider = vi.hoisted(() => ({ type: 'api', toolFreeOneShot: true }));
vi.mock('../../hooks/useProviderModels.js', () => ({ default: () => ({
- providers: [{ id: 'stub-provider', name: 'Stub Provider', models: ['fixture-model'] }],
+ providers: [{ id: 'stub-provider', name: 'Stub Provider', models: ['fixture-model'], ...authorProvider }],
selectedProviderId: 'stub-provider', selectedModel: 'fixture-model', availableModels: ['fixture-model'],
- selectedProvider: { id: 'stub-provider', name: 'Stub Provider' },
+ selectedProvider: { providerId: 'stub-provider', model: 'fixture-model' },
setSelectedProviderId: vi.fn(), setSelectedModel: vi.fn(),
}) }));
vi.mock('./CompositionPreviewPlayer.jsx', () => ({ default: () => <div>Candidate preview</div> }));
@@ -35,12 +36,55 @@ const generated = { ...DOCUMENT, directory: 'music-video/mv-1/composition/doc-ge
const withCandidate = { ...bare, composition: { mode: 'document', document: DOCUMENT, documentDraft: generated } };
beforeEach(() => {
+ Object.assign(authorProvider, { type: 'api', toolFreeOneShot: true });
for (const fn of Object.values(api)) fn.mockReset();
api.startMusicVideoCompositionTemplate.mockResolvedValue({ project: attached, document: DOCUMENT });
api.detachMusicVideoCompositionDocument.mockResolvedValue({ project: bare });
});
describe('DocumentCompositionPanel', () => {
+ it('keeps an unsupported selected author visible but blocks generation until its CLI capability is verified', async () => {
+ Object.assign(authorProvider, { type: 'cli', toolFreeOneShot: false });
+ const props = { project: bare, onProject: vi.fn(), onSave: vi.fn() };
+ const view = render(<DocumentCompositionPanel {...props} />);
+ expect(screen.getByRole('option', { name: 'Stub Provider (not permitted here)' }).disabled).toBe(true);
+ expect(screen.queryByRole('option', { name: /Custom combination/ })).toBeNull();
+ const generate = screen.getByRole('button', { name: 'Generate mixed-media composition' });
+ expect(generate.disabled).toBe(true);
+ fireEvent.click(generate);
+ expect(api.generateMusicVideoMixedMediaDocument).not.toHaveBeenCalled();
+ Object.assign(authorProvider, { type: 'tui', toolFreeOneShot: true });
+ view.rerender(<DocumentCompositionPanel {...props} />);
+ expect(generate.disabled).toBe(true);
+ authorProvider.type = 'cli';
+ view.rerender(<DocumentCompositionPanel {...props} />);
+ expect(generate.disabled).toBe(false);
+ api.generateMusicVideoMixedMediaDocument.mockResolvedValue({ project: bare });
+ fireEvent.click(generate);
+ await waitFor(() => expect(api.generateMusicVideoMixedMediaDocument).toHaveBeenCalledWith('mv-1', { providerId: 'stub-provider', model: 'fixture-model' }, { silent: true }));
+ });
+
+ it('selects code-only and authors, previews and accepts a Three.js scene candidate', async () => {
+ const saved = { ...bare, mediaMode: 'code-only' };
+ api.updateMusicVideoProject.mockResolvedValue(saved);
+ api.generateMusicVideoMixedMediaDocument.mockResolvedValue({ project: { ...saved, composition: { ...saved.composition, documentDraft: generated } } });
+ api.getMusicVideoMixedMediaCandidate.mockResolvedValue({ candidate: generated, source: generated, stale: false, sections: [{ id: 'world', label: 'World' }] });
+ api.acceptMusicVideoMixedMediaDocument.mockResolvedValue({ project: { ...saved, composition: { ...saved.composition, document: generated } } });
+ const onProject = vi.fn();
+ const view = render(<DocumentCompositionPanel project={bare} onProject={onProject} onSave={vi.fn()} />);
+ fireEvent.change(screen.getByLabelText('Design and composition media'), { target: { value: 'code-only' } });
+ await waitFor(() => expect(onProject).toHaveBeenCalledWith(saved));
+ view.rerender(<DocumentCompositionPanel project={saved} onProject={onProject} onSave={vi.fn()} />);
+ expect(screen.getByLabelText('Authoring renderer').value).toBe('three');
+ fireEvent.click(screen.getByRole('button', { name: 'Generate authored 3D composition' }));
+ await waitFor(() => expect(api.generateMusicVideoMixedMediaDocument).toHaveBeenCalledWith('mv-1', { providerId: 'stub-provider', model: 'fixture-model' }, { silent: true }));
+ const next = onProject.mock.calls.at(-1)[0];
+ view.rerender(<DocumentCompositionPanel project={next} onProject={onProject} onSave={vi.fn()} />);
+ await screen.findByText('Candidate preview');
+ fireEvent.click(await screen.findByRole('button', { name: /Accept/ }));
+ await waitFor(() => expect(api.acceptMusicVideoMixedMediaDocument).toHaveBeenCalled());
+ });
+
it('gates authoring on saved event bindings and sends an event-only revision against the reviewed document', async () => {
api.getMusicVideoMixedMediaCandidate.mockResolvedValue({ candidate: generated, source: generated, stale: true, eventRevisionAvailable: true,
sections: [{ id: 'verse', label: 'Verse', startSec: 0, endSec: 10 }] });
diff --git a/client/src/components/musicVideo/MediaModePicker.jsx b/client/src/components/musicVideo/MediaModePicker.jsx
new file mode 100644
index 0000000000..b8f22b5f4a
--- /dev/null
+++ b/client/src/components/musicVideo/MediaModePicker.jsx
@@ -0,0 +1,11 @@
+import { MUSIC_VIDEO_MEDIA_MODES, MUSIC_VIDEO_MEDIA_MODE_LABELS } from '../../../../server/lib/musicVideoMediaPolicy.js';
+
+export default function MediaModePicker({ value = 'code-images-video', onChange, disabled = false, id = 'mv-media-mode' }) {
+ return <div className="min-w-0 space-y-1">
+ <label htmlFor={id} className="block text-xs text-port-text-muted">Design and composition media</label>
+ <select id={id} value={value} disabled={disabled} onChange={(event) => onChange(event.target.value)} className="max-w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm">
+ {MUSIC_VIDEO_MEDIA_MODES.map((mode) => <option key={mode} value={mode}>{MUSIC_VIDEO_MEDIA_MODE_LABELS[mode]}</option>)}
+ </select>
+ <p className="text-xs text-port-text-muted">Code authors the world, characters, camera, typography and timing. Code only excludes imported or generated images and video, including planning guides. Audio and local fonts remain available. Tool choices and budgets still constrain generation.</p>
+ </div>;
+}
diff --git a/client/src/components/musicVideo/ProductionReviewPanel.jsx b/client/src/components/musicVideo/ProductionReviewPanel.jsx
index cffe0659a8..2cfe7643b5 100644
--- a/client/src/components/musicVideo/ProductionReviewPanel.jsx
+++ b/client/src/components/musicVideo/ProductionReviewPanel.jsx
@@ -1,4 +1,5 @@
-import { useState } from 'react';
+import { useEffect, useState } from 'react';
+import { formatTimecode } from '../../utils/formatters.js';
const EMPTY = { cast: '', environments: '', visualLanguage: '', motionLanguage: '', guideArtifactId: null,
lyricsMode: 'vocal', timingStatus: 'provisional', timingNotes: '', storyboard: [] };
@@ -17,7 +18,7 @@ export default function ProductionReviewPanel({ project, review, onOpenArtifact
const [feedback, setFeedback] = useState({ stage: 'art', target: '', text: '', decision: 'request-changes' });
const [resolutions, setResolutions] = useState({});
const [importError, setImportError] = useState(null);
- const [watched, setWatched] = useState(null);
+ const [playbackReview, setPlaybackReview] = useState({ identity: null, watched: false, energyComparison: '', timecodedNotes: '' });
const [startSec, setStartSec] = useState(project.productionReview?.proof?.startSec || 0);
const [endSec, setEndSec] = useState(project.productionReview?.proof?.endSec || Math.min(20, project.audioAnalysis?.durationSec || 20));
const ready = review.readiness;
@@ -30,7 +31,23 @@ export default function ProductionReviewPanel({ project, review, onOpenArtifact
const blocked = dirty || review.busy || !ready;
const prototype = project.excerpts?.find(e => e.id === project.productionReview?.prototype?.excerptId);
const excerpt = project.excerpts?.find(e => e.id === project.productionReview?.proof?.excerptId);
- const approve = stage => { const secret = password; setPassword(''); return review.approve(stage, secret); };
+ const proofIdentity = JSON.stringify([project.id, ready?.basis.proof ?? project.productionReview?.proof?.basis ?? null, excerpt?.id, excerpt?.filename]);
+ const recordedProofReview = project.productionReview?.approvals?.proof?.proofReview;
+ const matchingRecordedReview = ready?.proof.approved && recordedProofReview?.excerptId === excerpt?.id
+ && recordedProofReview?.filename === excerpt?.filename ? recordedProofReview : null;
+ useEffect(() => { setPlaybackReview(current => current.identity === proofIdentity ? current
+ : { identity: proofIdentity, watched: false, energyComparison: '', timecodedNotes: '' }); }, [proofIdentity]);
+ const playback = playbackReview.identity === proofIdentity ? playbackReview : { watched: false, energyComparison: '', timecodedNotes: '' };
+ const setPlayback = patch => setPlaybackReview({ ...playback, identity: proofIdentity, ...patch });
+ const playbackBlocked = blocked || review.proof.active || !!ready?.proof.problems.length || excerpt?.status !== 'complete' || !excerpt.filename;
+ const playbackComplete = playback.watched && !!playback.energyComparison.trim()
+ && /(?:\b\d{1,2}:\d{2}(?:\.\d+)?\b|\b\d+(?:\.\d+)?s\b)/.test(playback.timecodedNotes);
+ const approve = stage => {
+ const secret = password; setPassword('');
+ return review.approve(stage, secret, stage === 'proof' ? { watchedWithAudio: true,
+ energyComparison: playback.energyComparison.trim(), timecodedNotes: playback.timecodedNotes.trim(),
+ excerptId: excerpt.id, filename: excerpt.filename } : undefined);
+ };
return <section id="mv-production-review" aria-label="Production review" className="rounded-lg border border-port-border bg-port-card p-3 space-y-3">
<h3 className="font-medium">Production review</h3>
@@ -43,7 +60,7 @@ export default function ProductionReviewPanel({ project, review, onOpenArtifact
{(ready?.[key].problems || []).map(problem => <p key={problem} className="mt-1 text-xs text-port-text-muted">{problem}</p>)}
<button type="button" className={`${buttonClass} mt-2`} onClick={() => approve(key)}
disabled={blocked || !password || ready?.[key].approved || !!ready?.[key].problems.length
- || (key === 'proof' && watched !== ready?.basis.proof)}>
+ || (key === 'proof' && (playbackBlocked || !playbackComplete))}>
Approve {label.toLowerCase()}
</button>
</li>)}
@@ -96,12 +113,18 @@ export default function ProductionReviewPanel({ project, review, onOpenArtifact
<button type="button" className={buttonClass} disabled={dirty || review.busy} onClick={review.prepare}>Prepare planning draft with autopilot</button>
<p className="text-xs text-port-text-muted">Uses the saved authoring provider and allowed tools. Builds Cast & Sets first, then pauses for art approval before planning shots. Existing edits are retained.</p>
<div className="grid gap-3 sm:grid-cols-2">
- {Object.entries({ cast: 'Cast guide', environments: 'Environment guide', visualLanguage: 'Visual language and mood board', motionLanguage: 'Motion language and choreography' }).map(([key, label]) =>
+ {Object.entries({ cast: 'Cast guide', environments: 'Environment guide', visualLanguage: 'Visual language and mood board' }).map(([key, label]) =>
<label key={key} htmlFor={fieldId(key)} className="text-sm">{label}<textarea id={fieldId(key)} rows={4} value={draft[key]} onChange={e => set(key, e.target.value)} className={fieldClass} /></label>)}
</div>
+ <label htmlFor={fieldId('motionLanguage')} className="block text-sm">Timed choreography and energy plan
+ <textarea id={fieldId('motionLanguage')} rows={7} value={draft.motionLanguage || ''} onChange={e => set('motionLanguage', e.target.value)} className={fieldClass}
+ aria-label="Timed choreography and energy plan" aria-describedby={fieldId('motion-help')}
+ placeholder={'Energy target: restrained, driving, explosive, or a described arc.\n0:00–0:08 / first downbeat: subject reaches, prop unfolds; camera pushes in; title lands on the vocal.\n0:08–0:16 / chorus hit: full-body turn and prop release; camera arcs; type expands then clears.\nRepeated chorus: preserve the motif, escalate pose range, travel, camera depth or transition scale.'} />
+ </label>
+ <p id={fieldId('motion-help')} className="text-xs text-port-text-muted">Choose the intended energy explicitly. For each time range and beat, word or section anchor, describe subject and prop actions, pose or travel changes, camera movement, typography and the transition. Name intentional holds and how each repeated chorus develops. The saved plan guides UI authoring and autopilot.</p>
<label htmlFor={fieldId('implementation')} className="block text-sm">Implementation and feasibility for {project.composition?.mode || 'composed'} rendering
<textarea id={fieldId('implementation')} rows={5} value={draft.implementationPlan || ''} onChange={e => set('implementationPlan', e.target.value)} className={fieldClass}
- placeholder="Scene graph and layers; vector/mesh construction; rig joints and pose limits; procedural materials; camera and transition mechanics; typography; frame rate, geometry and draw-call budgets." />
+ placeholder="Map each timed action to scene graph layers, vector/mesh construction, rig joints, pose limits and prop mechanics; specify camera paths and typography timing, transitions, frame rate, geometry and draw-call budgets." />
</label>
<p className="text-xs text-port-text-muted">Concept references establish intent. Document how this renderer can build and animate the look; a raster reference is not code-rendered evidence. Changing the plan invalidates prior art approval.</p>
<label htmlFor={fieldId('guide')} className="block text-sm">Visual cast and environment sheet
@@ -133,9 +156,9 @@ export default function ProductionReviewPanel({ project, review, onOpenArtifact
</select>
</label>
{!scene && <button type="button" className={buttonClass} disabled={dirty || review.busy || !shot.id} onClick={() => review.bindShot(shot.id)}>Create Board scene from this draft shot</button>}
- <p className="text-xs text-port-text-muted">Review exact start/end in Board. Imported timings remain provisional.</p>
+ <p className="text-xs text-port-text-muted">{scene && Number.isFinite(scene.startSec) && Number.isFinite(scene.endSec) ? `Shot window ${formatTimecode(scene.startSec)}–${formatTimecode(scene.endSec)}. ` : ''}Review exact start/end in Board. Imported timings remain provisional.</p>
{['action', 'staging', 'camera', 'transition'].map(key => <label key={key} htmlFor={fieldId(`${shotKey(shot)}-${key}`)} className="block text-sm capitalize">{key}
- <textarea id={fieldId(`${shotKey(shot)}-${key}`)} rows={2} value={shot[key]} onChange={e => setShot(shot, key, e.target.value)} className={fieldClass} />
+ <textarea id={fieldId(`${shotKey(shot)}-${key}`)} rows={2} value={shot[key]} placeholder={({ action: 'At a beat or word: subject and prop action; pose, travel and energy change.', staging: 'Depth, blocking, prop trajectory and typography placement through the shot.', camera: 'Timed camera path, framing changes and motivated holds.', transition: 'Exact entry/exit anchor, visual handoff and escalation into the next section.' })[key]} onChange={e => setShot(shot, key, e.target.value)} className={fieldClass} />
</label>)}
<fieldset><legend className="text-sm">Lyric anchors</legend>
{(project.lyricCues || []).filter(c => c.startSec < scene?.endSec && c.endSec > scene?.startSec).map(cue =>
@@ -150,7 +173,12 @@ export default function ProductionReviewPanel({ project, review, onOpenArtifact
</details>
<details open={ready?.storyboard.approved && !ready?.proof.approved}>
<summary className="cursor-pointer min-h-[44px] py-2 text-sm">Animated chorus proof</summary>
- <p className="text-sm">Author the approved storyboard in Compose, then render a 10–45 second chorus with its entry and exit. Watch with sound; check lyric timing, readable type, purposeful action, camera movement and transitions.</p>
+ <p className="text-sm">Author the approved storyboard in Compose, then render a 10–45 second chorus with its entry and exit. Watch with sound at normal speed and compare the chosen energy target and timed choreography below against the actual subject, props, camera, typography and transitions. Check accents against beat and lyric anchors, readable holds and repeated-chorus escalation. A strong static frame does not prove the motion works.</p>
+ <section aria-label="Saved choreography for proof comparison" className="rounded border border-port-border bg-port-bg p-3">
+ <h4 className="text-sm font-medium">Saved energy target and timed choreography</h4>
+ <p className="mt-1 whitespace-pre-wrap text-sm">{saved.motionLanguage || 'Save an energy target and timed choreography in the planning editor before judging the proof.'}</p>
+ <p className="mt-2 text-xs text-port-text-muted">Compare playback with this saved plan. If the chosen energy or actions are missing, record revision feedback with a time range before approving.</p>
+ </section>
<div className="flex flex-wrap items-end gap-2">
<label htmlFor={fieldId('proof-start')} className="text-sm">Proof start (seconds)<input id={fieldId('proof-start')} type="number" min="0" step="0.01" value={startSec} onChange={e => setStartSec(Number(e.target.value))} className={fieldClass} /></label>
<label htmlFor={fieldId('proof-end')} className="text-sm">Proof end (seconds)<input id={fieldId('proof-end')} type="number" min="0" step="0.01" value={endSec} onChange={e => setEndSec(Number(e.target.value))} className={fieldClass} /></label>
@@ -161,8 +189,22 @@ export default function ProductionReviewPanel({ project, review, onOpenArtifact
<p className="text-xs text-port-text-muted">A feasibility prototype uses the current authored composition and master audio without approving the look or authorizing production. It can be made before art approval; it never becomes approved proof automatically.</p>
{prototype?.status === 'complete' && prototype.filename && <figure><video controls className="mt-2 w-full rounded" aria-label="Unapproved feasibility prototype" src={`/data/videos/${encodeURIComponent(prototype.filename)}`} /><figcaption className="text-sm">Unapproved feasibility prototype — separate from production proof</figcaption></figure>}
{excerpt?.status === 'complete' && excerpt.filename && <video controls className="mt-2 w-full rounded" aria-label="Animated proof with master audio" src={`/data/videos/${encodeURIComponent(excerpt.filename)}`} />}
- <label htmlFor={fieldId('watched')} className="flex gap-2 py-2 text-sm"><input id={fieldId('watched')} type="checkbox" checked={!!ready && watched === ready.basis.proof}
- disabled={!ready || !!ready.proof.problems.length} onChange={e => setWatched(e.target.checked ? ready.basis.proof : null)} />I watched this revision with audio and checked the approved visual direction, motion and lyric timing.</label>
+ {matchingRecordedReview && <section aria-label="Recorded proof review" className="rounded border border-port-border p-3">
+ <h4 className="text-sm font-medium">Recorded proof review</h4>
+ <p className="mt-1 whitespace-pre-wrap text-sm">{matchingRecordedReview.energyComparison}</p>
+ <p className="mt-2 whitespace-pre-wrap text-sm">{matchingRecordedReview.timecodedNotes}</p>
+ </section>}
+ <label htmlFor={fieldId('energy-comparison')} className="block text-sm">Playback energy compared with the saved plan
+ <textarea id={fieldId('energy-comparison')} rows={3} maxLength={4000} disabled={playbackBlocked} value={playback.energyComparison} onChange={e => setPlayback({ energyComparison: e.target.value })} className={fieldClass}
+ placeholder="Chosen energy target; observed subject, prop and camera activity; where playback matches or misses the intended arc." />
+ </label>
+ <label htmlFor={fieldId('playback-notes')} className="block text-sm">Timecoded playback notes
+ <textarea id={fieldId('playback-notes')} rows={3} maxLength={4000} disabled={playbackBlocked} value={playback.timecodedNotes} onChange={e => setPlayback({ timecodedNotes: e.target.value })} className={fieldClass}
+ placeholder="0:04 — subject turns on the downbeat; prop opens through 0:06; camera and type clear the lyric. Name any mismatch to revise." />
+ </label>
+ <p className="text-xs text-port-text-muted">Include at least one playback timestamp such as 0:04 or 4.5s. These notes are saved with this exact proof. A replacement proof requires a new comparison and acknowledgement.</p>
+ <label htmlFor={fieldId('watched')} className="flex gap-2 py-2 text-sm"><input id={fieldId('watched')} type="checkbox" checked={playback.watched}
+ disabled={playbackBlocked} onChange={e => setPlayback({ watched: e.target.checked })} />I watched this revision with audio at normal speed and compared its energy, timed choreography and lyric timing with the saved plan.</label>
</details>
</section>;
}
diff --git a/client/src/components/musicVideo/ProductionReviewPanel.test.jsx b/client/src/components/musicVideo/ProductionReviewPanel.test.jsx
new file mode 100644
index 0000000000..caa11dbf07
--- /dev/null
+++ b/client/src/components/musicVideo/ProductionReviewPanel.test.jsx
@@ -0,0 +1,78 @@
+import { describe, expect, it, vi } from 'vitest';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import ProductionReviewPanel from './ProductionReviewPanel.jsx';
+
+const acknowledgement = 'I watched this revision with audio at normal speed and compared its energy, timed choreography and lyric timing with the saved plan.';
+const project = {
+ id: 'example-project', scenes: [], lyricCues: [], composition: { mode: 'document' },
+ productionReview: { proof: { excerptId: 'proof-a', basis: 'same-creative-basis' }, draft: {
+ cast: 'Example figure', environments: 'Example stage', visualLanguage: 'Copper and indigo',
+ motionLanguage: 'Energy target: driving chorus. 0:04 — figure turns and opens the prop on the downbeat.',
+ lyricsMode: 'instrumental', timingStatus: 'verified', timingNotes: 'Synthetic master', storyboard: [],
+ } },
+ excerpts: [{ id: 'proof-a', filename: 'proof-a.mp4', status: 'complete' }],
+};
+const reviewFixture = () => ({ readiness: {
+ basis: { art: 'art', storyboard: 'board', proof: 'same-creative-basis' },
+ art: { approved: true, problems: [] }, storyboard: { approved: true, problems: [] }, proof: { approved: false, problems: [] },
+}, busy: false, proof: { active: false }, approve: vi.fn(), save: vi.fn(async () => null) });
+function recordPlayback() {
+ fireEvent.change(screen.getByLabelText('Instance password for this approval'), { target: { value: 'synthetic-password' } });
+ fireEvent.change(screen.getByLabelText('Playback energy compared with the saved plan'), { target: { value: 'The driving turn matches the chosen energy.' } });
+ fireEvent.change(screen.getByLabelText('Timecoded playback notes'), { target: { value: '0:04 — figure turns on the downbeat; prop follows at 4.5s.' } });
+ fireEvent.click(screen.getByLabelText(acknowledgement));
+}
+
+describe('Production proof playback evidence', () => {
+ it('shows the recorded review for an approved artifact without treating it as fresh playback evidence', () => {
+ const review = reviewFixture();
+ review.readiness.proof.approved = true;
+ const approved = { ...project, productionReview: { ...project.productionReview, approvals: { proof: { proofReview: {
+ excerptId: 'proof-a', filename: 'proof-a.mp4', watchedWithAudio: true,
+ energyComparison: 'The driving turn matches the saved energy target.', timecodedNotes: '0:04 — the figure turns on the downbeat.',
+ } } } } };
+ const view = render(<ProductionReviewPanel project={approved} review={review} onOpenArtifact={vi.fn()} />);
+ expect(screen.getByLabelText('Recorded proof review').textContent).toContain('0:04 — the figure turns on the downbeat.');
+ expect(screen.getByLabelText(acknowledgement).checked).toBe(false);
+ expect(screen.getByLabelText('Timecoded playback notes').value).toBe('');
+ view.rerender(<ProductionReviewPanel project={{ ...approved, excerpts: [{ id: 'proof-a', filename: 'replacement.mp4', status: 'complete' }] }} review={review} onOpenArtifact={vi.fn()} />);
+ expect(screen.queryByLabelText('Recorded proof review')).toBeNull();
+ });
+
+ it.each([
+ { id: 'proof-b', filename: 'proof-b.mp4' },
+ { id: 'proof-a', filename: 'replacement.mp4' },
+ ])('requires new playback notes when the proof artifact changes to $filename without a creative-basis change', ({ id, filename }) => {
+ const review = reviewFixture();
+ const view = render(<ProductionReviewPanel project={project} review={review} onOpenArtifact={vi.fn()} />);
+ recordPlayback();
+ expect(screen.getByRole('button', { name: 'Approve animated proof' }).disabled).toBe(false);
+ const replacement = { ...project, productionReview: { ...project.productionReview, proof: { ...project.productionReview.proof, excerptId: id } },
+ excerpts: [{ id, filename, status: 'complete' }] };
+ view.rerender(<ProductionReviewPanel project={replacement} review={review} onOpenArtifact={vi.fn()} />);
+ expect(screen.getByLabelText(acknowledgement).checked).toBe(false);
+ expect(screen.getByLabelText('Playback energy compared with the saved plan').value).toBe('');
+ expect(screen.getByLabelText('Timecoded playback notes').value).toBe('');
+ expect(screen.getByRole('button', { name: 'Approve animated proof' }).disabled).toBe(true);
+ recordPlayback();
+ fireEvent.click(screen.getByRole('button', { name: 'Approve animated proof' }));
+ expect(review.approve).toHaveBeenCalledWith('proof', 'synthetic-password', expect.objectContaining({
+ excerptId: id, filename, watchedWithAudio: true, energyComparison: 'The driving turn matches the chosen energy.',
+ timecodedNotes: '0:04 — figure turns on the downbeat; prop follows at 4.5s.',
+ }));
+ });
+
+ it('keeps failed choreography saves dirty and blocks playback acknowledgement and approval', async () => {
+ const review = reviewFixture();
+ render(<ProductionReviewPanel project={project} review={review} onOpenArtifact={vi.fn()} />);
+ recordPlayback();
+ fireEvent.change(screen.getByLabelText('Timed choreography and energy plan'), { target: { value: 'Energy target: explosive. 0:04 — replace the turn with a leap.' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save planning edits', hidden: true }));
+ await waitFor(() => expect(review.save).toHaveBeenCalled());
+ expect(screen.getByText('Save edits before preparing, approving or rendering.')).toBeTruthy();
+ expect(screen.getByLabelText(acknowledgement).disabled).toBe(true);
+ expect(screen.getByLabelText('Timecoded playback notes').disabled).toBe(true);
+ expect(screen.getByRole('button', { name: 'Approve animated proof' }).disabled).toBe(true);
+ expect(review.approve).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/musicVideo/RenderStatusPanel.jsx b/client/src/components/musicVideo/RenderStatusPanel.jsx
index 1e9fdb6d34..4c4ba6df53 100644
--- a/client/src/components/musicVideo/RenderStatusPanel.jsx
+++ b/client/src/components/musicVideo/RenderStatusPanel.jsx
@@ -1,3 +1,4 @@
+import Banner from '../ui/Banner.jsx';
import { useRef } from 'react';
import { Film, Download, Maximize2 } from 'lucide-react';
@@ -84,3 +85,11 @@ export default function RenderStatusPanel({
</div>
);
}
+
+/** Persisted failures survive reload; kickoff/SSE failures stay bound to their project. */
+export function RenderFailure({ project, renderJob }) {
+ if (renderJob?.active && renderJob.context === project.id) return null;
+ const error = renderJob?.failure?.projectId === project.id ? renderJob.failure.message
+ : project.status === 'failed' ? project.renderError : null;
+ return error ? <Banner tone="error" title="Render failed" className="break-words">{error}</Banner> : null;
+}
diff --git a/client/src/components/musicVideo/RenderStatusPanel.test.jsx b/client/src/components/musicVideo/RenderStatusPanel.test.jsx
new file mode 100644
index 0000000000..895a334e9d
--- /dev/null
+++ b/client/src/components/musicVideo/RenderStatusPanel.test.jsx
@@ -0,0 +1,15 @@
+import { afterEach, expect, it } from 'vitest';
+import { cleanup, render, screen } from '@testing-library/react';
+import { RenderFailure } from './RenderStatusPanel.jsx';
+
+afterEach(cleanup);
+it('keeps a persisted render failure visible after reload and isolates another project’s SSE failure', () => {
+ const project = { id: 'mv-example', status: 'failed', renderError: 'Edit durationSec to a whole-frame duration and re-import.' };
+ const { rerender } = render(<RenderFailure project={project} renderJob={{ failure: { projectId: 'other', message: 'Other failure' } }} />);
+ expect(screen.getByRole('alert')).toHaveTextContent(project.renderError);
+ expect(screen.queryByText('Other failure')).not.toBeInTheDocument();
+ rerender(<RenderFailure project={project} renderJob={{ active: true, context: project.id }} />);
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ rerender(<RenderFailure project={{ ...project, status: 'complete', renderError: null }} renderJob={{}} />);
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+});
diff --git a/client/src/components/musicVideo/stages/ComposeStage.jsx b/client/src/components/musicVideo/stages/ComposeStage.jsx
index 9a1edbaedc..5a4acc3fad 100644
--- a/client/src/components/musicVideo/stages/ComposeStage.jsx
+++ b/client/src/components/musicVideo/stages/ComposeStage.jsx
@@ -1,3 +1,4 @@
+import { RenderFailure } from '../RenderStatusPanel.jsx';
import GradePanel from '../GradePanel.jsx';
import TypographyPanel from '../TypographyPanel.jsx';
import CodeVideoPanel from '../CodeVideoPanel.jsx';
@@ -14,6 +15,7 @@ export default function ComposeStage({ board }) {
const mode = project.composition?.mode;
return (
<fieldset disabled={locked} className="min-w-0">
+ <RenderFailure project={project} renderJob={board.renderJob} />
<div className="space-y-2 rounded-lg border border-port-border bg-port-card p-3">
<div className="flex flex-wrap items-center gap-2">
<span className="text-xs text-port-text-muted" aria-hidden="true">Render style</span>
diff --git a/client/src/components/musicVideo/stages/ReviewStage.jsx b/client/src/components/musicVideo/stages/ReviewStage.jsx
index 26b34b4505..3f21861fae 100644
--- a/client/src/components/musicVideo/stages/ReviewStage.jsx
+++ b/client/src/components/musicVideo/stages/ReviewStage.jsx
@@ -1,5 +1,5 @@
import DependencyImpactPanel from '../DependencyImpactPanel.jsx';
-import RenderStatusPanel from '../RenderStatusPanel.jsx';
+import RenderStatusPanel, { RenderFailure } from '../RenderStatusPanel.jsx';
import ExcerptPanel from '../ExcerptPanel.jsx';
import DevArtifactsPanel from '../DevArtifactsPanel.jsx';
import HandoffControls from '../HandoffControls.jsx';
@@ -17,6 +17,7 @@ export default function ReviewStage({ board }) {
} = board;
return (
<fieldset disabled={locked} className="min-w-0 space-y-3">
+ <RenderFailure project={project} renderJob={renderJob} />
<DependencyImpactPanel project={project} busy={revisions.busy} onRepair={revisions.repair} />
<section id="mv-final-video" aria-label="Final render" className="rounded-lg border border-port-border bg-port-card p-3">
<div className="flex flex-wrap items-center justify-between gap-2">
diff --git a/client/src/hooks/useMusicVideoProductionReview.js b/client/src/hooks/useMusicVideoProductionReview.js
index 33e9abde04..1eb01a3c99 100644
--- a/client/src/hooks/useMusicVideoProductionReview.js
+++ b/client/src/hooks/useMusicVideoProductionReview.js
@@ -56,8 +56,8 @@ export default function useMusicVideoProductionReview({ project, replaceProject
bindShot: shotId => call(() => bindMusicVideoProductionShot(project.id, shotId, { silent: true })),
save: draft => call(() => saveMusicVideoProductionDraft(project.id, draft, { silent: true })),
prepare: () => call(() => prepareMusicVideoProductionReview(project.id, {}, { silent: true })),
- approve: (stage, password) => call(() => approveMusicVideoProductionReview(project.id,
- { stage, password, basis: state?.readiness.basis[stage] }, { silent: true })),
+ approve: (stage, password, proofReview) => call(() => approveMusicVideoProductionReview(project.id,
+ { stage, password, basis: state?.readiness.basis[stage], ...(stage === 'proof' ? { proofReview } : {}) }, { silent: true })),
renderProof: window => proof.start({ id: project.id, window }, project.id),
};
}
diff --git a/client/src/hooks/useMusicVideoRenderJob.js b/client/src/hooks/useMusicVideoRenderJob.js
index f4fc20021c..e53f8eda1a 100644
--- a/client/src/hooks/useMusicVideoRenderJob.js
+++ b/client/src/hooks/useMusicVideoRenderJob.js
@@ -1,3 +1,4 @@
+import { useState } from 'react';
import {
renderMusicVideoProject,
musicVideoRenderEventsUrl,
@@ -21,13 +22,18 @@ const startRender = (projectId) => renderMusicVideoProject(projectId, { silent:
* callbacks. The job shape stays compatible with the existing cancel controls.
*/
export default function useMusicVideoRenderJob({ onRendered, onFailed } = {}) {
+ const [failure, setFailure] = useState(null);
const slot = useSseJobSlot({
startRequest: startRender,
eventsUrl: musicVideoRenderEventsUrl,
cancelRequest: cancelMusicVideoRender,
readPercent: readRenderPercent,
- onComplete: (frame, projectId) => onRendered?.(projectId, frame.result || {}),
- onErrorFrame: (_frame, projectId) => { onFailed?.(projectId); },
+ onComplete: (frame, projectId) => { setFailure(null); onRendered?.(projectId, frame.result || {}); },
+ onErrorFrame: (frame, projectId) => {
+ setFailure({ projectId, message: frame.error || 'Render failed' });
+ onFailed?.(projectId, frame.error || 'Render failed');
+ },
+ onKickoffError: (error, projectId) => { setFailure({ projectId, message: error?.message || 'Failed to start render' }); },
successToast: () => 'Music video rendered',
errorFallback: 'Render failed',
canceledMessage: 'Render cancelled',
@@ -36,6 +42,12 @@ export default function useMusicVideoRenderJob({ onRendered, onFailed } = {}) {
});
return {
...slot,
+ failure,
+ start: (projectId) => {
+ if (slot.active) return;
+ setFailure(null);
+ slot.start(projectId);
+ },
job: slot.jobId ? { jobId: slot.jobId, projectId: slot.context } : null,
progress: slot.active ? slot.percent : 0,
};
diff --git a/client/src/hooks/useMusicVideoRenderJob.test.jsx b/client/src/hooks/useMusicVideoRenderJob.test.jsx
new file mode 100644
index 0000000000..e27eaf0341
--- /dev/null
+++ b/client/src/hooks/useMusicVideoRenderJob.test.jsx
@@ -0,0 +1,26 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { act, renderHook } from '@testing-library/react';
+import useMusicVideoRenderJob from './useMusicVideoRenderJob.js';
+import { MockEventSource, lastEventSource } from '../test/mockEventSource';
+import { renderMusicVideoProject } from '../services/apiMusicVideo.js';
+
+vi.mock('../services/apiMusicVideo.js', () => ({
+ renderMusicVideoProject: vi.fn(), musicVideoRenderEventsUrl: id => `/events/${id}`, cancelMusicVideoRender: vi.fn(),
+}));
+vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), info: vi.fn(), success: vi.fn() } }));
+beforeEach(() => { vi.clearAllMocks(); MockEventSource.reset(); vi.stubGlobal('EventSource', MockEventSource); });
+afterEach(() => vi.unstubAllGlobals());
+
+it('retains kickoff and terminal failures after the shared SSE slot clears, then clears on retry', async () => {
+ renderMusicVideoProject.mockRejectedValueOnce(new Error('Invalid document duration')).mockResolvedValue({ jobId: 'job-example' });
+ const onFailed = vi.fn();
+ const { result } = renderHook(() => useMusicVideoRenderJob({ onFailed }));
+ await act(async () => result.current.start('mv-example'));
+ expect(result.current.failure).toEqual({ projectId: 'mv-example', message: 'Invalid document duration' });
+ await act(async () => result.current.start('mv-example'));
+ expect(result.current.failure).toBeNull();
+ act(() => lastEventSource().emit({ type: 'error', error: 'Document capture failed' }));
+ expect(result.current.active).toBe(false);
+ expect(result.current.failure).toEqual({ projectId: 'mv-example', message: 'Document capture failed' });
+ expect(onFailed).toHaveBeenCalledWith('mv-example', 'Document capture failed');
+});
diff --git a/client/src/lib/musicVideoAutonomous.js b/client/src/lib/musicVideoAutonomous.js
index ada1dd5984..032a9ee8ae 100644
--- a/client/src/lib/musicVideoAutonomous.js
+++ b/client/src/lib/musicVideoAutonomous.js
@@ -2,6 +2,8 @@
// vocabulary and brief normalizer (a dependency-light leaf) and owns the start
// form's draft ↔ wire mapping and the run's display helpers.
+import { musicVideoMediaMode } from '../../../server/lib/musicVideoMediaPolicy.js';
+
import {
AUTONOMOUS_DEFAULT_LIMITS, AUTONOMOUS_DEFAULT_TOOLS, AUTONOMOUS_LIVE_STATUSES, AUTONOMOUS_SONG_SOURCES, AUTONOMOUS_STAGES,
} from '../../../server/lib/musicVideoAutonomous.js';
@@ -25,6 +27,8 @@ export const AUTONOMOUS_STATUS_LABELS = Object.freeze({
export const emptyAutonomousDraft = () => ({
prompt: '',
+ mediaMode: 'code-images-video',
+ authoring: { providerId: '', model: '', effort: '' },
songSource: AUTONOMOUS_SONG_SOURCES[0],
localFallback: false,
instrumental: false,
@@ -51,6 +55,11 @@ export function autonomousRequestFromDraft(draft, { providerId, model, effort }
.map(([id, value]) => [id, value.trim()]));
return {
prompt: draft.prompt.trim(),
+ mediaMode: draft.mediaMode,
+ ...(draft.authoring?.providerId && draft.authoring?.model ? { authoring: {
+ providerId: draft.authoring.providerId, model: draft.authoring.model,
+ ...(draft.authoring.effort ? { effort: draft.authoring.effort } : {}),
+ } } : {}),
songSource: draft.songSource,
localFallback: draft.songSource === 'suno' && draft.localFallback === true,
instrumental: draft.instrumental === true,
@@ -125,6 +134,8 @@ export function autopilotDraftFromParams(params) {
const { prompt: _prompt, ...base } = emptyAutonomousDraft();
return {
...base,
+ mediaMode: musicVideoMediaMode(p),
+ authoring: { ...base.authoring, ...(p.authoring || {}) },
songSource: AUTONOMOUS_SONG_SOURCES.includes(p.songSource) ? p.songSource : base.songSource,
localFallback: p.localFallback === true,
instrumental: p.instrumental === true,
@@ -141,7 +152,7 @@ export function autopilotDraftFromParams(params) {
/**
* The `musicVideoAutopilot` params a draft saves. Starts from the saved params
- * so fields the form does not edit (review attempts, authoring provider) survive a save; the server re-normalizes it all on write.
+ * so fields the form does not edit (such as review attempts) survive a save; the server re-normalizes it all on write.
*/
export function autopilotParamsFromDraft(draft, saved, { providerId, model, effort } = {}) {
const { prompt: _prompt, ...request } = autonomousRequestFromDraft({ ...draft, prompt: '' }, {});
@@ -150,6 +161,7 @@ export function autopilotParamsFromDraft(draft, saved, { providerId, model, effo
...kept,
...request,
models: request.models || {},
+ authoring: request.authoring || null,
limits: { ...(kept.limits || {}), ...(request.limits || {}) },
moodBoardId: draft.moodBoardId || null,
ideaTags: String(draft.ideaTags || '').split(',').map((t) => t.trim()).filter(Boolean),
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index 63ba4564af..b090e2058e 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -189,9 +189,9 @@ export default function MusicVideo() {
const renderJob = useMusicVideoRenderJob({
onRendered: (projectId, result) => patchProject(projectId, (project) => ({
renderHistoryId: result.id || project.renderHistoryId,
- status: 'complete',
+ status: 'complete', renderError: null,
})),
- onFailed: (projectId) => patchProject(projectId, { status: 'failed' }),
+ onFailed: (projectId, renderError) => patchProject(projectId, { status: 'failed', renderError }),
});
// Draft excerpt render (#8986): a fast cue/cut preview of a chosen window,
// separate from the full-render job/mutex above so a director can preview a
@@ -298,6 +298,7 @@ export default function MusicVideo() {
// Only the ids go up: the server snapshots the universe/board style and track metadata into the concept.
createMusicVideoProject({
name: form.name.trim(),
+ mediaMode: form.mediaMode || 'code-images-video',
mode: form.mode,
trackId: form.trackId || null,
concept: { universeId: form.universeId || null },
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index 8639b94ad1..705e185265 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -451,6 +451,15 @@ describe('MusicVideo render control (#1760)', () => {
expect(toast.error).toHaveBeenCalledWith('Renderer stopped');
expect(screen.getByLabelText('Project').querySelector('option[value="mv-1"]')).toHaveTextContent('failed');
expect(screen.getByLabelText('Project').querySelector('option[value="mv-other"]')).toHaveTextContent('ready');
+ expect(screen.queryByText('Renderer stopped')).not.toBeInTheDocument();
+ await selectProject(PROJECT_WITH_CLIP.id);
+ await openStage('review');
+ expect(screen.getByText('Renderer stopped')).toBeInTheDocument();
+ await openStage('compose');
+ expect(screen.getByText('Renderer stopped')).toBeInTheDocument();
+ await selectProject(other.id);
+ await openStage('review');
+
sseState.latest = null;
fireEvent.click(screen.getByRole('button', { name: /^Render final$/ }));
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 0e05267a46..7e87114e66 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -60,7 +60,7 @@ is where each shared table is re-exported from its `server/lib` leaf.
| `providerHarnesses` | `harnessLabel(harnessId)` — the display name for an agent program PortOS drives (Claude Code, OpenCode, Codex, …), used wherever a harness is named (the preset-first pickers, the composition catalog hook), where `null` means Direct API and an unknown id renders verbatim rather than disappearing. Read through `harnessById` from the pure leaf `server/lib/providerHarnesses.js`, so a harness added to the registry is named here without a second edit. Also `providerHarnessId(provider)` (a derived preset's own `harnessId`, else the server's `harnessForProvider` classification) and `groupProvidersByHarness(providers)` — the `{ harnessId, label, providers }` buckets in registry order (Direct API after the agent harnesses, an `Other` bucket last) that the preset-first `ProviderModelSelector` renders as `<optgroup>`s (#7566) and the AI Providers page renders as its preset sections (#7567). `presetEditPath(presetId)` — the preset editor URL (`/ai/presets/:id`), falling back to the kept `/ai/edit/:id` alias for the one id (`new`) the static create route shadows. |
| `providerEndpoints` | WHERE a provider's endpoint points. `isLocalEndpoint` (loopback), `isPrivateNetworkEndpoint` (RFC1918 / tailnet address, or a `.local` / `.ts.net` / single-label host — somewhere an unauthenticated OpenAI-compatible server is a normal setup rather than a missing API key), `isLocalInstanceProvider` (talks to a daemon on THIS machine; mirror of `server/lib/localProviderRuntime.js#isLocalInstanceEndpoint` — gate anything that explains a provider by inspecting the host PortOS runs on), `isFleetProvider` / `isFleetHostConfigured` (another machine inside the private network), and `localBackendForProvider` (`'ollama'` / `'lmstudio'` / `null` by id, endpoint or name — it matches by NAME, so pair it with `isLocalInstanceProvider` before claiming this machine's install state). |
| `providerModels` | Which MODEL and EFFORT a run resolves to, and what a picker may list. The configured-default sentinels (`CODEX_CONFIGURED_DEFAULT` …, `isConfiguredDefaultModel`, `configuredDefaultIn` — so a picker can render an option matching a sentinel-valued tier instead of a blank select) and `filterSelectableModels`; the per-CLI effort ladders, `effortLevelsForProvider`, `resolveCliEffort` (what a stored effort actually runs as, so the picker can name a clamped level), `effortSurvivingModel` and `seedModelEffort`; the Antigravity base-model ↔ effort-suffix split (`splitAntigravityModel`, `antigravityBaseModels`, `antigravityModelEffortLevels`, `withStaleAntigravityPin`); the account-aware option list (`providerModelList`, `resolveProviderModelOptions`, `effortAwareModelOptions`, `MODEL_SOURCE` — the one place a Codex-subscription account catalog enters a picker); `effectiveModelFor`; `mergeModelLists` / `mergeProviderUpdate`; and `generationControlsFor` (which temperature / top-p / thinking controls a provider forwards at all). The sentinels, effort ladders and the Antigravity split are re-exported from the pure leaf `server/lib/providerModels.js`; `effortLevelsForProvider` / `resolveCliEffort` delegate to the server's and add the ladder a sanitized provider inventory publishes, clamped through the server's `clampEffortToLadder`. The generation-control tables still mirror `server/lib/opencodeConfig.js`. |
-| `providerSelection` | Which providers and models a picker may OFFER on this install: `isProviderHardwareCompatible` / `isProviderModelHardwareCompatible` / `filterHardwareCompatibleProviderModels` (server-annotated, fail-open), `selectableProviders` (the single rule `ProviderModelSelector` renders from), `filterRunnableProviders` (agent jobs need a CLI/TUI harness), the fail-closed tool-free local policy (`TOOL_FREE_LOCAL_PROVIDER_IDS`, `TOOL_FREE_LOCAL_TEXT_CAPABILITIES`, `isToolFreeLocalProvider`, `isToolFreeLocalModel`, `toolFreeLocalSelectionPolicy`) used by security-sensitive pickers, and the pr-reviewer postures (`PUBLIC_REVIEW_NO_TOOL_POSTURE` / `PUBLIC_REVIEW_ACTIONS_POSTURE`, `supportsPublicReviewPosture`, `enforcesPublicReviewPosture`, `publicReviewSelectionPolicy` — mirror of `server/lib/agentExecutionProfiles.js`: a pipeline stage names a POSTURE, the server publishes each provider's `publicReviewPostures` and `publicReviewEnforcedPostures` on `GET /api/providers`, and the picker offers exactly the providers this install can run the stage on, so no vendor is named on either side). Also the caller EXECUTION-MODE picker rule (`callerModeList`, `providerModeSelectionPolicy` — whose `modes` also bound the selector's compose flow) and `COMPOSE_OPTION_VALUE`, the "Custom combination…" action sentinel outside both provider-id grammars (#7566), over `server/lib/callerModePolicy.js` — the server enforces the policy on the pin, on `activeProvider` inheritance and on every fallback candidate; this only lets a picker SHOW the rule, keeping an ineligible saved value visible-but-disabled instead of hidden or silently replaced — read off `CALLER_MODE_POLICIES` in that pure leaf, so it cannot drift). |
+| `providerSelection` | Which providers and models a picker may OFFER on this install: `isProviderHardwareCompatible` / `isProviderModelHardwareCompatible` / `filterHardwareCompatibleProviderModels` (server-annotated, fail-open), `selectableProviders` (the single rule `ProviderModelSelector` renders from), `filterRunnableProviders` (agent jobs need a CLI/TUI harness), `supportsToolFreeOneShot` / `toolFreeOneShotSelectionPolicy` (API or server-verified tool-free CLI authoring; excludes TUI and unverified composite routes), the fail-closed tool-free local policy (`TOOL_FREE_LOCAL_PROVIDER_IDS`, `TOOL_FREE_LOCAL_TEXT_CAPABILITIES`, `isToolFreeLocalProvider`, `isToolFreeLocalModel`, `toolFreeLocalSelectionPolicy`) used by security-sensitive pickers, and the pr-reviewer postures (`PUBLIC_REVIEW_NO_TOOL_POSTURE` / `PUBLIC_REVIEW_ACTIONS_POSTURE`, `supportsPublicReviewPosture`, `enforcesPublicReviewPosture`, `publicReviewSelectionPolicy` — mirror of `server/lib/agentExecutionProfiles.js`: a pipeline stage names a POSTURE, the server publishes each provider's `publicReviewPostures` and `publicReviewEnforcedPostures` on `GET /api/providers`, and the picker offers exactly the providers this install can run the stage on, so no vendor is named on either side). Also the caller EXECUTION-MODE picker rule (`callerModeList`, `providerModeSelectionPolicy` — whose `modes` also bound the selector's compose flow) and `COMPOSE_OPTION_VALUE`, the "Custom combination…" action sentinel outside both provider-id grammars (#7566), over `server/lib/callerModePolicy.js` — the server enforces the policy on the pin, on `activeProvider` inheritance and on every fallback candidate; this only lets a picker SHOW the rule, keeping an ineligible saved value visible-but-disabled instead of hidden or silently replaced — read off `CALLER_MODE_POLICIES` in that pure leaf, so it cannot drift). |
| `localModelHeuristics` | What an untyped LOCAL model can do, judged from its id: `isEmbeddingModel` / `isVisionModel` / `isToolUseModel` (re-exported from the pure leaf `server/lib/localModelHeuristics.js` — one regex per family; a model card's explicit capability metadata outranks the id regex), `isVisionCapableCliProvider`, `filterGenerationModels` (sentinels and embedding-only models dropped), `visionLocalModelFilter` and `localToolUseHint` / `withToolUseOptionLabel` (unioned with the server's authoritative per-provider capability maps from `useVisionModelIds` / `useToolUseModelIds`; tool-use is an annotation plus warning, never a filter), and `modelCapabilityInfo` (capability badges for a selected model without over-sharing a local runtime's answer with another provider). |
| `providerContextWindows` | How large a context window a provider/model gets for planning and where the number came from: the vendor constants and the `KNOWN_MODEL_CONTEXT_WINDOWS` ladder (`knownModelContextWindow`, `knownProviderContextWindow`), `catalogModelContextWindow` (the window the provider's own `/models` catalog reported), `resolveModelContextWindow` → `{ tokens, source }` with `CONTEXT_WINDOW_SOURCE` (`override` / `reported` / `assumed` — the state a card has to label rather than print as fact), `effectiveModelContextWindow`, and `modelOptionLabel` ("id (32K ctx)"). The constants and the known-model / known-provider / catalog rungs are re-exported from the pure leaf `server/lib/providerContextWindows.js`, the same rungs the server's `effectiveContextWindow` budgets with — including `mergeObservedContextWindows`, which folds a local daemon's live window (off the readiness payload) onto the catalog rung so the card shows what the dispatch gate enforces, and holds every resolved window down to an Ollama daemon's launch `num_ctx` through `clampToRuntimeContextWindow` (applied internally, from `server/lib/aiToolkit/internal/ollamaBacked.js` — the same module the server's budgeter and pre-dispatch gate use), so the meter can't promise a budget a run would be refused for (#7466). `withRuntimeContextWindow(provider, ceiling)` stamps that ceiling's second rung — the ambient `OLLAMA_CONTEXT_LENGTH` the server launched the daemon with, which the browser cannot read and so takes off the readiness payload as `runtimeContextWindow` (#7472). |
| `providerModelAccess` | Which of a provider's advertised catalog this install is entitled to run (free tier, plan, hand-picked allowlist). Re-exports the policy rules the browser consumes from the pure leaf `server/lib/aiToolkit/internal/modelAccess.js` — `MODEL_ACCESS_MODES`, `MAX_MODEL_ACCESS_PATTERNS`, `CONFIGURED_MODEL_KEYS`, `normalizeModelAccess`, `modelMatchesAccessPatterns` — so the editor's live preview and the server's own scoping cannot disagree. Adds `providerModelCatalog(provider)` (the FULL list, off `modelCatalog` when the payload was scoped — seed a model editor from this or a Save persists the narrowed list), `previewModelAccess(catalog, policy, configuredModels)` → `{ total, visibleCount, hidden, inert }`, `configuredModelsOf`, `NO_MODEL_ACCESS` and `MODEL_ACCESS_MODE_LABELS`. `applyModelAccess` is deliberately NOT re-exported: a client payload is already scoped, and re-scoping would overwrite `modelCatalog` with the narrowed list. |
diff --git a/client/src/utils/providerSelection.js b/client/src/utils/providerSelection.js
index 41de594326..9232e2999c 100644
--- a/client/src/utils/providerSelection.js
+++ b/client/src/utils/providerSelection.js
@@ -84,6 +84,17 @@ export const toolFreeLocalSelectionPolicy = (
),
});
+/** One-shot authoring permits direct APIs or a server-verified tool-free CLI.
+ * Never infer CLI support from a command name, and never admit a TUI session.
+ */
+export const supportsToolFreeOneShot = (provider) => provider?.enabled !== false
+ && (provider?.type === 'api' || provider?.type === 'cli' && provider.toolFreeOneShot === true);
+
+// No compose modes: an unmaterialized CLI combination has no server capability
+// annotation yet. Existing pins still render through the selector's saved-value
+// path, with incompatible records visible but disabled.
+export const toolFreeOneShotSelectionPolicy = Object.freeze({ provider: supportsToolFreeOneShot });
+
// The two enforceable public-review postures. MIRROR of
// `server/lib/agentExecutionProfiles.js`; a pr-reviewer stage names a posture
// and the server publishes each provider's `publicReviewPostures` on
diff --git a/scripts/migrations/421-music-video-media-modes.js b/scripts/migrations/421-music-video-media-modes.js
new file mode 100644
index 0000000000..6e31b37969
--- /dev/null
+++ b/scripts/migrations/421-music-video-media-modes.js
@@ -0,0 +1,29 @@
+/** Pin legacy intent without deleting assets, changing tools or enabling providers. */
+import { readFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { musicVideoMediaMode } from '../../server/lib/musicVideoMediaPolicy.js';
+import { writeJsonAtomic } from './_lib.js';
+
+export const migrateMediaMode = (record) => Object.hasOwn(record, 'mediaMode') ? record : { ...record, mediaMode: musicVideoMediaMode(record) };
+
+export default {
+ async up({ rootDir }) {
+ const file = join(rootDir, 'data', 'music-video-projects.json');
+ const raw = await readFile(file, 'utf8').catch((error) => { if (error.code === 'ENOENT') return null; throw error; });
+ if (raw) {
+ const records = JSON.parse(raw);
+ if (!Array.isArray(records)) throw new Error('Music Video project file must contain an array');
+ await writeJsonAtomic(file, records.map(migrateMediaMode));
+ }
+ const { query } = await import('../../server/lib/db.js');
+ const table = await query("SELECT to_regclass('public.music_video_projects') AS name");
+ if (table.rows[0]?.name) {
+ await query(`UPDATE music_video_projects SET data = data || jsonb_build_object('mediaMode',
+ CASE WHEN data->'automation'->'tools' @> '["code:render"]'::jsonb
+ AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements_text(CASE WHEN jsonb_typeof(data->'automation'->'tools') = 'array' THEN data->'automation'->'tools' ELSE '[]'::jsonb END) AS tool WHERE tool LIKE 'image:%' OR tool LIKE 'video:%')
+ THEN 'code-only' ELSE 'code-images-video' END)
+ WHERE NOT data ? 'mediaMode'`);
+ }
+ return { success: true };
+ },
+};
diff --git a/scripts/vitestCiPool.js b/scripts/vitestCiPool.js
index 9494cc8247..65c50e2397 100644
--- a/scripts/vitestCiPool.js
+++ b/scripts/vitestCiPool.js
@@ -21,6 +21,7 @@ export const EXCLUSIVE_CAPTURE_TESTS = [
'services/htmlComposition/index.test.js',
'services/musicVideo/documentRender.browser.test.js',
'routes/musicVideoProductionReview.browser.test.js',
+ 'routes/musicVideoRichAuthoring.browser.test.js',
];
// Cutover's real subprocess proof has a four-second test budget. A retained
diff --git a/server/lib/README.md b/server/lib/README.md
index a53dc85374..45e2195582 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -830,3 +830,5 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `persistentMindContextEvents.js` | `selectPersistentMindContextEvents`, `renderPersistentMindContextEvent` — retain useful conversation evidence without diagnostic ledger noise. |
| `codeAnimationSound.js` | Versioned frame/sample timelines, deterministic impact/reveal WAV synthesis and decoded event measurements. |
+
+| `musicVideoMediaPolicy.js` | Whole-workflow media modes, legacy intent, selection admission and independent document renderer choice. |
diff --git a/server/lib/index.js b/server/lib/index.js
index e46c53ba8f..8c2b395cd0 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -814,3 +814,5 @@ export * from './persistentMindContextEvents.js';
export * from './scheduleExecutionFieldsValidation.js';
export * from './codeAnimationSound.js';
+
+export * from './musicVideoMediaPolicy.js';
diff --git a/server/lib/musicVideoAutonomous.js b/server/lib/musicVideoAutonomous.js
index ab9c2bdeba..4efb9d779b 100644
--- a/server/lib/musicVideoAutonomous.js
+++ b/server/lib/musicVideoAutonomous.js
@@ -1,3 +1,4 @@
+import { MUSIC_VIDEO_MEDIA_MODES, musicVideoMediaMode } from './musicVideoMediaPolicy.js';
/**
* Fully-autonomous Music Video — the pure vocabulary and transforms.
*
@@ -115,6 +116,7 @@ function normalizeAutonomousSettings(raw = {}) {
const authoringModel = clean(raw.authoring?.model, 200);
const authoringEffort = normalizeMusicVideoEffort(raw.authoring?.effort);
return {
+ mediaMode: MUSIC_VIDEO_MEDIA_MODES.includes(raw.mediaMode) ? raw.mediaMode : musicVideoMediaMode({ tools }),
songSource: AUTONOMOUS_SONG_SOURCES.includes(raw.songSource) ? raw.songSource : AUTONOMOUS_SONG_SOURCES[0],
// Suno only: when it cannot even take the request (signed out, no credits,
// page changed), render the song locally instead of parking the run.
diff --git a/server/lib/musicVideoDependencies.js b/server/lib/musicVideoDependencies.js
index ce7cc6eea4..afc2b81854 100644
--- a/server/lib/musicVideoDependencies.js
+++ b/server/lib/musicVideoDependencies.js
@@ -27,7 +27,7 @@ const compositionRef = (project, startSec, endSec) => {
const value = composition ? { ...composition,
cues: (composition.cues || []).filter((cue) => intersects(cue, startSec, endSec)),
} : null;
- return { role: 'composition', assetId: 'composition', revision: checksum(value), startSec, endSec };
+ return { role: 'composition', assetId: 'composition', revision: checksum({ mediaMode: project.mediaMode || null, composition: value }), startSec, endSec };
};
/** Evidence tracks its rendered window, selected layers and transitive take inputs. */
diff --git a/server/lib/musicVideoMediaPolicy.js b/server/lib/musicVideoMediaPolicy.js
new file mode 100644
index 0000000000..b97cd9def2
--- /dev/null
+++ b/server/lib/musicVideoMediaPolicy.js
@@ -0,0 +1,33 @@
+/** Media provenance policy is independent of the composition renderer. */
+export const MUSIC_VIDEO_MEDIA_MODES = ['code-only', 'code-images', 'code-images-video'];
+export const MUSIC_VIDEO_MEDIA_MODE_LABELS = {
+ 'code-only': 'Code only', 'code-images': 'Code + images', 'code-images-video': 'Code + images + video',
+};
+
+// Old explicit code-only tool choices remain restrictive. Missing policy never
+// adds tools or permits a provider the existing brief did not authorize.
+export function musicVideoMediaMode(project) {
+ if (MUSIC_VIDEO_MEDIA_MODES.includes(project?.mediaMode)) return project.mediaMode;
+ const tools = project?.automation?.tools || project?.tools || [];
+ return tools.includes('code:render') && !tools.some((id) => /^(image|video):/.test(id))
+ ? 'code-only' : 'code-images-video';
+}
+export function musicVideoAllowsMedia(project, kind) {
+ const mode = musicVideoMediaMode(project);
+ return kind === 'image' ? mode !== 'code-only' : kind === 'video' ? mode === 'code-images-video' : true;
+}
+export function assertMusicVideoMedia(project, kind, purpose = 'asset') {
+ if (musicVideoAllowsMedia(project, kind)) return;
+ const error = new Error(`${MUSIC_VIDEO_MEDIA_MODE_LABELS[musicVideoMediaMode(project)]} does not allow ${kind} ${purpose}, including planning guides. Change the media mode explicitly to use this asset.`);
+ Object.assign(error, { status: 422, code: 'MUSIC_VIDEO_MEDIA_POLICY' });
+ throw error;
+}
+export function assertMusicVideoMediaSelections(project) {
+ if (project?.visualSpec?.references?.length || project?.visualSpec?.moodBoardId || project?.styleReferences?.some((ref) => ref.imageId)) assertMusicVideoMedia(project, 'image', 'references');
+ for (const scene of project?.scenes || []) {
+ if (scene.referenceImageId) assertMusicVideoMedia(project, 'image', 'selection');
+ if (scene.videoHistoryId) assertMusicVideoMedia(project, 'video', 'selection');
+ }
+}
+export const musicVideoDocumentRenderer = (project) => project?.composition?.authoringRenderer
+ || (musicVideoMediaMode(project) === 'code-only' ? 'three' : 'canvas');
diff --git a/server/lib/musicVideoMediumPlan.js b/server/lib/musicVideoMediumPlan.js
index 81b98a9aff..cc6b892019 100644
--- a/server/lib/musicVideoMediumPlan.js
+++ b/server/lib/musicVideoMediumPlan.js
@@ -1,3 +1,4 @@
+import { musicVideoAllowsMedia } from './musicVideoMediaPolicy.js';
/**
* Planning-only medium policy. Final-edit seconds are an interval union, not
* provider clip lengths or a sum that double-counts overlapping footage.
@@ -28,6 +29,7 @@ export const musicVideoBriefTools = (project) => (Array.isArray(project?.automat
/** False when the brief names tools and none of them makes video. A brief naming no tools restricts nothing. */
export function musicVideoBriefAllowsVideo(project) {
+ if (!musicVideoAllowsMedia(project, 'video')) return false;
const tools = musicVideoBriefTools(project);
return tools.length === 0 || tools.some((t) => t.startsWith('video:'));
}
@@ -70,6 +72,7 @@ export function summarizeMusicVideoMediumPlan(project, directions = project?.tre
const codeFirst = policy.strategy === 'code-first';
for (const scene of project?.scenes || []) {
const d = byScene.get(scene.sceneId);
+ if (d?.medium === 'still' && !musicVideoAllowsMedia(project, 'image') || ['generated-footage', 'existing-footage'].includes(d?.medium) && !musicVideoAllowsMedia(project, 'video')) unresolved.push({ sceneId: scene.sceneId, blocking: true, message: 'This shot medium conflicts with the project media mode.' });
if (!d || !MUSIC_VIDEO_MEDIA.includes(d.medium)) {
if (codeFirst) unresolved.push({ sceneId: scene.sceneId, blocking: true, message: 'Compile a medium plan for this shot.' });
continue;
@@ -183,6 +186,9 @@ export function planMusicVideoMedia(project, directions) {
rationale = codeFirst ? 'Carry the section motif and transitions with code or available images.'
: 'Retain the legacy treatment route.';
}
+ if (!manualLayer && !scene?.referenceImageId && !scene?.videoHistoryId && (medium === 'still' && !musicVideoAllowsMedia(project, 'image') || ['existing-footage', 'generated-footage'].includes(medium) && !musicVideoAllowsMedia(project, 'video'))) {
+ medium = 'procedural'; rationale = 'Author the full scene in code within the selected media mode.';
+ }
return { ...d, medium, mediumRationale: rationale || d.rationale || 'Director-selected medium.', mediumPinned: manualLayer };
});
// Reserve pinned exceptions first. Automatic suggestions never displace a pin.
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 0a9466ac09..e8e502be45 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -1,3 +1,4 @@
+import { MUSIC_VIDEO_MEDIA_MODES } from './musicVideoMediaPolicy.js';
import { MUSIC_VIDEO_GRADE_PRESETS, MUSIC_VIDEO_GRADE_MAX_GRAIN } from './musicVideoGrade.js';
/**
* Music Video production mode — Zod schemas + shared enums (issue #1760, Phase 1).
@@ -401,6 +402,7 @@ export const musicVideoReactiveSectionSchema = z.object({
export const musicVideoCompositionSchema = z.object({
version: z.literal(1).optional(),
mode: z.enum(MUSIC_VIDEO_COMPOSITION_MODES).optional(),
+ authoringRenderer: z.enum(['canvas', 'three']).optional(),
cutting: z.enum(MUSIC_VIDEO_CUTTING_MODES).optional(),
grade: z.object({
preset: z.enum(MUSIC_VIDEO_GRADE_PRESETS).optional(),
@@ -746,6 +748,7 @@ export const musicVideoProductionResumeSchema = z.object({
export const musicVideoAutonomousStartSchema = z.object({
prompt: z.string().trim().min(1).max(AUTONOMOUS_PROMPT_MAX),
name: z.string().trim().min(1).max(AUTONOMOUS_NAME_MAX).optional(),
+ mediaMode: z.enum(MUSIC_VIDEO_MEDIA_MODES).optional(),
songSource: z.enum(AUTONOMOUS_SONG_SOURCES).optional(),
localFallback: z.boolean().optional(),
instrumental: z.boolean().optional(),
@@ -914,6 +917,7 @@ export const musicVideoCastAndSetsDirectionEditSchema = z.object({
}).strict();
export const musicVideoProjectCreateSchema = z.object({
+ mediaMode: z.enum(MUSIC_VIDEO_MEDIA_MODES).optional(),
productionPolicy: musicVideoProductionPolicySchema.optional(),
name: z.string().min(1).max(200),
mode: z.enum(MUSIC_VIDEO_MODES).optional(),
@@ -937,6 +941,7 @@ export const musicVideoProjectCreateSchema = z.object({
}).strict();
export const musicVideoProjectUpdateSchema = z.object({
+ mediaMode: z.enum(MUSIC_VIDEO_MEDIA_MODES).optional(),
productionPolicy: musicVideoProductionPolicySchema.optional(),
name: z.string().min(1).max(200).optional(),
mode: z.enum(MUSIC_VIDEO_MODES).optional(),
@@ -950,6 +955,7 @@ export const musicVideoProjectUpdateSchema = z.object({
videoSettings: musicVideoVideoSettingsSchema.optional(),
automation: musicVideoAutomationSchema.nullable().optional(),
renderHistoryId: z.string().max(64).nullable().optional(),
+ renderError: z.string().max(2000).nullable().optional(),
lyricCues: lyricCueList.optional(),
lyricMarkers: lyricMarkerList.optional(),
phrases: phraseList.optional(),
@@ -988,6 +994,13 @@ export const musicVideoProductionImportSchema = z.object({ source: z.string().mi
export const musicVideoProductionApprovalSchema = z.object({
stage: z.enum(['art', 'storyboard', 'proof']), basis: z.string().min(1).max(128),
password: z.string().min(1).max(1024),
+ proofReview: z.object({
+ watchedWithAudio: z.literal(true),
+ excerptId: z.string().min(1).max(200), filename: z.string().min(1).max(200),
+ energyComparison: z.string().trim().min(1).max(4000),
+ timecodedNotes: z.string().trim().min(1).max(4000)
+ .regex(/(?:\b\d{1,2}:\d{2}(?:\.\d+)?\b|\b\d+(?:\.\d+)?s\b)/, 'Include a playback time such as 0:04 or 4.5s.'),
+ }).strict().optional(),
}).strict();
export const musicVideoProductionProofSchema = z.object({
kind: z.enum(['proof', 'prototype']).optional(),
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index f5d569bc2e..7795a958a0 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -677,7 +677,8 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// v18 = named narrative event anchors and bounded section reactivity. Older
// composition normalizers drop these fields on edit. Absent remains legacy;
// no stored row rewrite is needed. Document manifests remain wire-local.
- musicVideoProjects: 18,
+ // v19 pins whole-workflow media policy; older peers cannot enforce it.
+ musicVideoProjects: 19,
// v1 = Creative Commission FEEDBACK federation (PostgreSQL `commission_feedback`)
// via the per-record peer-sync push pipeline (record kind `commissionFeedback`,
// sync category `commissionFeedback`, #2686 — split-record follow-up to #2657).
diff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.js
index 0a6295dc81..55b9d0a478 100644
--- a/server/lib/schemaVersions.test.js
+++ b/server/lib/schemaVersions.test.js
@@ -66,10 +66,10 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {
describe('buildPortosMeta', () => {
it('rejects repair, timing and narrative event metadata on older music-video peers', async () => {
const meta = await buildPortosMeta();
- expect(meta.schemaVersions.musicVideoProjects).toBe(18);
- for (const receiverV of [13, 14, 15, 16, 17]) {
+ expect(meta.schemaVersions.musicVideoProjects).toBe(19);
+ for (const receiverV of [13, 14, 15, 16, 17, 18]) {
expect(compareSchemaVersions(meta.schemaVersions, { ...meta.schemaVersions, musicVideoProjects: receiverV }).ahead)
- .toContainEqual({ category: 'musicVideoProjects', senderV: 18, receiverV });
+ .toContainEqual({ category: 'musicVideoProjects', senderV: 19, receiverV });
}
});
diff --git a/server/lib/syncWire.js b/server/lib/syncWire.js
index 20fd244ac0..7a507bfe70 100644
--- a/server/lib/syncWire.js
+++ b/server/lib/syncWire.js
@@ -58,6 +58,8 @@ export function stripMusicVideoLocalRenderPins(record, { stripVideoBackend = tru
// A fully-autonomous run names this install's providers, Suno songs and
// production run (services/musicVideo/autonomousService.js).
autonomousRun: _autonomousRun,
+ // Render diagnostics describe a job on this machine, never a peer job.
+ renderError: _renderError,
...shared
} = record;
// A composition document names a folder on this install only
diff --git a/server/lib/syncWire.test.js b/server/lib/syncWire.test.js
index f616755501..9cdcd3d7ed 100644
--- a/server/lib/syncWire.test.js
+++ b/server/lib/syncWire.test.js
@@ -340,6 +340,7 @@ describe('syncWire', () => {
name: 'Example Video',
imageMode: 'grok',
imageModelId: 'example-image-model',
+ renderError: 'Example local render diagnostic',
videoSettings: {
backend: 'grok',
modelId: 'example-video-model',
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index acd62da3fc..9ef88f32cc 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -500,7 +500,7 @@ router.post('/:id/production-review/prepare', asyncHandler(async (req, res) => {
router.post('/:id/production-review/approve', asyncHandler(async (req, res) => {
const input = validateRequest(musicVideoProductionApprovalSchema, req.body);
await requireProductionOperator(req);
- res.json(await approveProductionReview(req.params.id, { stage: input.stage, basis: input.basis }));
+ res.json(await approveProductionReview(req.params.id, { stage: input.stage, basis: input.basis, proofReview: input.proofReview }));
}));
router.post('/:id/production-review/proof', asyncHandler(async (req, res) => {
res.status(202).json(await renderProductionProof(req.params.id, validateRequest(musicVideoProductionProofSchema, req.body)));
diff --git a/server/routes/musicVideoProductionReview.browser.test.js b/server/routes/musicVideoProductionReview.browser.test.js
index 4605ffe7a4..3e595e47c6 100644
--- a/server/routes/musicVideoProductionReview.browser.test.js
+++ b/server/routes/musicVideoProductionReview.browser.test.js
@@ -116,11 +116,14 @@ describe.skipIf(!canRun)('production review in a real browser (Chrome, ffmpeg an
await page.locator('video').waitFor({ timeout: 120000 });
await page.locator('video').evaluate(async video => { await video.play(); await new Promise(r => setTimeout(r, 400)); video.pause(); });
expect(await page.locator('video').evaluate(v => v.videoWidth)).toBeGreaterThan(0);
- await page.getByLabel('I watched this revision with audio and checked the approved visual direction, motion and lyric timing.').check();
+ await page.getByLabel('Playback energy compared with the saved plan').fill('The synthetic fixture demonstrates a driving chorus: the modeled subject changes pose and travels while the camera moves through the scene.');
+ await page.getByLabel('Timecoded playback notes').fill('0:02 — subject enters the frame; 0:07 — pose and camera position differ and readable type remains clear. This is a synthetic workflow test, not artistic approval of a production video.');
+ await page.getByLabel('I watched this revision with audio at normal speed and compared its energy, timed choreography and lyric timing with the saved plan.').check();
await password.fill('synthetic-password'); await page.getByRole('button', { name: 'Approve animated proof' }).click();
await page.waitForFunction(() => [...document.querySelectorAll('[role=status]')].filter(el => el.textContent === 'Approved for this revision').length === 3);
const result = await store.getProject(p.id);
expect(result.productionReview.feedback[0].resolvedAt).toBeTruthy();
+ expect(result.productionReview.approvals.proof.proofReview).toMatchObject({ watchedWithAudio: true, excerptId: result.productionReview.proof.excerptId, timecodedNotes: expect.stringContaining('0:02') });
expect(errors).toEqual([]);
const proofFile = join(PATHS.videos, result.excerpts.find(e => e.id === result.productionReview.proof.excerptId).filename);
const frame = at => execFileSync(ffmpeg, ['-v', 'error', '-ss', String(at), '-i', proofFile, '-frames:v', '1', '-vf', 'scale=64:36', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-']);
diff --git a/server/routes/musicVideoProductionReview.test.js b/server/routes/musicVideoProductionReview.test.js
index 302a6a5dbb..1f9edbf073 100644
--- a/server/routes/musicVideoProductionReview.test.js
+++ b/server/routes/musicVideoProductionReview.test.js
@@ -4,6 +4,17 @@ import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';
+const author = vi.hoisted(() => ({ sections: [], calls: 0 }));
+vi.mock('../services/promptRunner.js', () => ({
+ assertProvider: () => {},
+ resolveProviderAndModel: async () => ({ provider: { id: 'fixture-author', type: 'api', enabled: true }, selectedModel: 'fixture-model' }),
+ runPromptThroughProvider: async ({ beforeExecute }) => {
+ await beforeExecute?.({ provider: { id: 'fixture-author', type: 'api' }, model: 'fixture-model' });
+ author.calls += 1;
+ return { text: JSON.stringify({ sections: author.sections }) };
+ },
+}));
+
const ROOT = () => lazyTempDataRoot('mv-production-review-');
vi.mock('../lib/paths.js', async original => makePathsProxy(await original(), { dataRoot: ROOT }));
vi.mock('../services/settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));
@@ -31,12 +42,17 @@ const read = () => request(app).get(`${base}/production-review`);
const save = body => request(app).put(`${base}/production-review`).send(body);
async function approve(stage, extra = {}) {
const status = await read();
- return request(app).post(`${base}/production-review/approve`).send({ stage,
+ const excerpt = status.body.project.excerpts?.find(e => e.id === status.body.project.productionReview?.proof?.excerptId);
+ const proofReview = stage === 'proof' && excerpt ? { watchedWithAudio: true, excerptId: excerpt.id, filename: excerpt.filename,
+ energyComparison: 'The playful energy target reads clearly in the subject and camera action.',
+ timecodedNotes: '0:04 doorway opens on the accent; 0:12 the second gesture grows in scale.' } : undefined;
+ return request(app).post(`${base}/production-review/approve`).send({ stage, proofReview,
basis: status.body.readiness.basis[stage], password: 'synthetic-operator-password', ...extra });
}
beforeEach(async () => {
auth.enabled = true;
+ author.calls = 0; author.sections = [];
project = await store.createProject({ name: 'Example animation', uploadedAudioFilename: 'synthetic-song.wav', composition: { mode: 'code' } });
base = `/api/music-video/${project.id}`;
await store.setProjectAnalysis(project.id, { durationSec: 20, bpm: 120, beats: [0, 1], downbeats: [0], sections: [{ startSec: 0, endSec: 20, label: 'Chorus' }] });
@@ -53,6 +69,38 @@ beforeEach(async () => {
afterAll(cleanupTempDataRoots);
describe('human-reviewed Music Video workflow', () => {
+ it('prepares an absent code-first medium plan before human storyboard approval and real authoring admission', async () => {
+ await store.updateProject(project.id, { mediaMode: 'code-only', composition: { mode: 'document', authoringRenderer: 'canvas' },
+ productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 } });
+ const originalDirection = { camera: 'Keep the authored slow push', medium: 'procedural', mediumPinned: true, mediumRationale: 'Exact code staging' };
+ await store.mutateProjectRecord(project.id, current => ({ project: { ...current,
+ scenes: current.scenes.map(scene => ({ ...scene, direction: originalDirection })) } }));
+ expect((await approve('art')).status).toBe(200);
+ const prepared = await request(app).post(`${base}/production-review/prepare`).send({});
+ expect(prepared.status).toBe(200);
+ expect(prepared.body.project.treatment).toMatchObject({ revision: 1, appliedRevision: 1,
+ compiledWith: { source: 'deterministic' }, shotDirections: [{ medium: 'procedural' }] });
+ expect(prepared.body.project.scenes[0]).toMatchObject({ direction: originalDirection, prompt: 'A paper figure opens a painted doorway.' });
+ expect(prepared.body.readiness.art.approved).toBe(true);
+ expect(prepared.body.readiness.storyboard.approved).toBe(false);
+ expect(author.calls).toBe(0);
+ const generate = () => request(app).post(`${base}/composition/document/generate`).send({ providerId: 'fixture-author', model: 'fixture-model' });
+ expect((await generate()).body.code).toBe('MUSIC_VIDEO_APPROVAL_REQUIRED');
+ expect((await approve('storyboard')).status).toBe(200);
+ const { buildCodeTimeline } = await import('../services/musicVideo/codeTimeline.js');
+ author.sections = buildCodeTimeline(await store.getProject(project.id)).sections.map(section => ({ id: section.id,
+ source: "function render(ctx, env) { ctx.fillStyle = '#203040'; ctx.fillRect(0, 0, env.width, env.height); }" }));
+ const generated = await generate();
+ expect(generated.status).toBe(201);
+ expect(generated.body.document.source.kind).toBe('generated');
+ expect(author.calls).toBe(1);
+ const beforeRepeat = await store.getProject(project.id);
+ await request(app).post(`${base}/production-review/prepare`).send({});
+ const repeated = await store.getProject(project.id);
+ expect(repeated.treatment).toEqual(beforeRepeat.treatment);
+ expect(repeated.scenes).toEqual(beforeRepeat.scenes);
+ });
+
it('refuses API credentials, password-free approval, stale revisions and final-render bypasses', async () => {
const status = await read();
const body = { stage: 'art', basis: status.body.readiness.basis.art, password: 'synthetic-operator-password' };
@@ -82,8 +130,17 @@ describe('human-reviewed Music Video workflow', () => {
expect((await approve('art')).status).toBe(200);
expect((await approve('storyboard')).status).toBe(200);
expect((await request(app).post(`${base}/production-review/proof`).send({ startSec: 0, endSec: 20 })).status).toBe(202);
+ expect((await approve('proof', { proofReview: undefined })).body.code).toBe('MUSIC_VIDEO_PROOF_REVIEW_REQUIRED');
+ const evidence = { watchedWithAudio: true, excerptId: 'older-proof', filename: 'synthetic-proof.mp4',
+ energyComparison: 'Matches the chosen playful target.', timecodedNotes: '0:04 the subject reaches the doorway.' };
+ expect((await approve('proof', { proofReview: evidence })).body.code).toBe('MUSIC_VIDEO_REVIEW_STALE');
+ expect((await approve('proof', { proofReview: { ...evidence, timecodedNotes: 'Looks good' } })).status).toBe(400);
expect((await approve('proof')).status).toBe(200);
const accepted = await store.getProject(project.id);
+ expect(accepted.productionReview.approvals.proof.proofReview).toMatchObject({
+ watchedWithAudio: true, excerptId: 'proof-fixture', filename: 'synthetic-proof.mp4',
+ timecodedNotes: '0:04 doorway opens on the accent; 0:12 the second gesture grows in scale.',
+ });
expect(() => assertProductionApproval(accepted)).not.toThrow();
const fork = await store.cloneProject(project.id, { variant: 'video-generation' });
expect(fork.productionReview.approvals).toEqual({});
@@ -112,6 +169,60 @@ describe('human-reviewed Music Video workflow', () => {
expect((await approve('storyboard')).status).toBe(200);
});
+ it('invalidates musical choreography evidence when analysis or the applied timing map changes, not receipt metadata', async () => {
+ const current = await store.getProject(project.id);
+ await store.setProjectAnalysis(project.id, { ...current.audioAnalysis, features: {
+ envelopes: { fps: 1, rms: [0.2, 0.8], low: [0.1, 0.7], mid: [0.2, 0.4], high: [0.1, 0.3] },
+ onsets: { low: [1], mid: [2], high: [3] },
+ } });
+ await store.mutateProjectRecord(project.id, p => ({ project: { ...p, audioTimingRevisions: [{
+ version: 1, basis: 'synthetic-timing-revision', appliedAt: '2026-01-01T00:00:00.000Z',
+ input: { targetTrackId: 'synthetic-track', intervals: [{ oldStartSec: 0, oldEndSec: 20, newStartSec: 0 }] },
+ }] } }));
+ // Explicitly reconfirm the alignment after the analysis change.
+ await save({ ...draft, timingStatus: 'provisional' });
+ await save(draft);
+ await approve('art'); await approve('storyboard');
+ await request(app).post(`${base}/production-review/proof`).send({ startSec: 0, endSec: 20 });
+ expect((await approve('proof', { proofReview: undefined })).body.code).toBe('MUSIC_VIDEO_PROOF_REVIEW_REQUIRED');
+ const evidence = { watchedWithAudio: true, excerptId: 'older-proof', filename: 'synthetic-proof.mp4',
+ energyComparison: 'Matches the chosen playful target.', timecodedNotes: '0:04 the subject reaches the doorway.' };
+ expect((await approve('proof', { proofReview: evidence })).body.code).toBe('MUSIC_VIDEO_REVIEW_STALE');
+ expect((await approve('proof', { proofReview: { ...evidence, timecodedNotes: 'Looks good' } })).status).toBe(400);
+ expect((await approve('proof')).status).toBe(200);
+ const accepted = await store.getProject(project.id);
+ const acceptedStatus = (await read()).body.readiness;
+ expect(acceptedStatus.readyForProduction).toBe(true);
+
+ const changes = {
+ onset: p => { p.audioAnalysis.features.onsets.low = [4]; },
+ envelope: p => { p.audioAnalysis.features.envelopes.rms = [0.8, 0.2]; },
+ downbeat: p => { p.audioAnalysis.downbeats = [1]; },
+ timingMap: p => { p.audioTimingRevisions[0].input.intervals[0].newStartSec = 1; },
+ };
+ for (const [label, change] of Object.entries(changes)) {
+ const revised = structuredClone(accepted);
+ change(revised);
+ await store.mutateProjectRecord(project.id, () => ({ project: revised }));
+ const readiness = (await read()).body.readiness;
+ expect(readiness.art.approved, label).toBe(true);
+ expect(readiness.storyboard.problems.join(' '), label).toContain('Lyric alignment is provisional or changed');
+ expect(readiness.basis.storyboard, label).not.toBe(acceptedStatus.basis.storyboard);
+ expect(readiness.basis.proof, label).not.toBe(acceptedStatus.basis.proof);
+ expect(readiness.readyForProduction, label).toBe(false);
+ expect((await approve('proof')).status, label).toBe(409);
+ }
+
+ const metadataOnly = structuredClone(accepted);
+ metadataOnly.name = 'Renamed example animation';
+ metadataOnly.audioTimingRevisions[0].appliedAt = '2026-01-02T00:00:00.000Z';
+ metadataOnly.audioAnalysis.waveform = [0.1, 0.3]; // Timeline display, not authored motion input.
+ await store.mutateProjectRecord(project.id, () => ({ project: metadataOnly }));
+ const retained = (await read()).body.readiness;
+ expect(retained.basis).toEqual(acceptedStatus.basis);
+ expect(retained.readyForProduction).toBe(true);
+ });
+
it('imports unbound planning without authorizing it, preserves source and binds only on explicit request', async () => {
const source = JSON.stringify({ cast: [{ id: 'paper-figure' }], environments: [{ id: 'doorway' }],
visualLanguage: { palette: ['indigo'] }, motionLanguage: { camera: 'dolly' }, productionAuthorized: true,
diff --git a/server/routes/musicVideoRichAuthoring.browser.test.js b/server/routes/musicVideoRichAuthoring.browser.test.js
new file mode 100644
index 0000000000..392c3ec09f
--- /dev/null
+++ b/server/routes/musicVideoRichAuthoring.browser.test.js
@@ -0,0 +1,164 @@
+/** Actual review controls + router/file store + Chrome/ffmpeg proof. No provider or live data. */
+import { afterAll, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { richSceneSource } from '../services/musicVideo/__richSceneFixture.js';
+const author = vi.hoisted(() => ({ sectionId: null, prompt: '' }));
+vi.mock('../services/promptRunner.js', () => ({
+ assertProvider: () => {},
+ resolveProviderAndModel: async () => ({ provider: { id: 'stub-provider', type: 'api', enabled: true }, selectedModel: 'fixture-model' }),
+ runPromptThroughProvider: async ({ prompt }) => { author.prompt = prompt; return { text: JSON.stringify({ sections: [{ id: author.sectionId, source: richSceneSource }] }) }; },
+}));
+import { existsSync } from 'node:fs';
+import { mkdir, writeFile, copyFile } from 'node:fs/promises';
+import { join, resolve } from 'node:path';
+import { execFileSync, spawn } from 'node:child_process';
+import { chromium } from 'playwright-core';
+import { createRequire } from 'node:module';
+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+vi.mock('../lib/paths.js', async original => makePathsProxy(await original(), { dataRoot: () => lazyTempDataRoot('mv-rich-ui-browser-') }));
+vi.mock('../services/instanceIdentity.js', () => ({ ensureInstanceId: async () => 'synthetic-instance' }));
+vi.mock('../services/settings.js', () => ({ getSettings: async () => ({}) }));
+vi.mock('../services/auth.js', () => ({ isAuthEnabled: async () => true, verifyPassword: async p => p === 'synthetic-password' }));
+let endpoint;
+vi.mock('../services/browserService.js', () => ({ cdpRequest: path => fetch(`${endpoint}${path}`) }));
+const { findFfmpeg } = await import('../lib/ffmpeg.js');
+const { _testChromeCaptureArgs, _waitForTestChrome, _cleanupTestBrowser } = await import('../services/htmlComposition/testBrowserCleanup.js');
+const chrome = [process.env.CHROME_PATH, chromium.executablePath(), '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/usr/bin/google-chrome'].find(p => p && existsSync(p));
+const ffmpeg = await findFfmpeg();
+// Server-only CI intentionally does not install the client workspace. This
+// cross-workspace visual test runs when all three local QA prerequisites exist.
+const client = resolve(import.meta.dirname, '../../client');
+const requireClient = createRequire(join(client, 'package.json'));
+let clientBundler;
+try {
+ clientBundler = ['vite', '@vitejs/plugin-react', '@tailwindcss/postcss'].map(name => requireClient.resolve(name));
+} catch (error) {
+ if (error.code !== 'MODULE_NOT_FOUND') throw error;
+}
+
+// Read-only dependency discovery can still initialize mocked path fixtures.
+// Vitest skips cleanup hooks when no browser test can run.
+const canRun = Boolean(chrome && ffmpeg && clientBundler);
+if (!canRun) cleanupTempDataRoots();
+
+let browser, proc, server;
+afterAll(async () => {
+ await _cleanupTestBrowser({ browser, proc, cleanup: () => {} });
+ if (server) await new Promise(resolve => server.close(resolve));
+ cleanupTempDataRoots();
+});
+
+describe.skipIf(!canRun)('rich document authoring in a real browser (Chrome, ffmpeg and client dependencies required)', () => {
+ it('selects code-only, authors and accepts a Three.js world through the real UI and renders its reviewed proof', async () => {
+ // Skipped suites do not run cleanup hooks: load data-owning services only here.
+ const { PATHS } = await import('../lib/paths.js');
+ const { default: router } = await import('./musicVideo.js');
+ const store = await import('../services/musicVideo/projects.js');
+ const { saveGeneratedDevArtifact } = await import('../services/musicVideo/devArtifactService.js');
+ await mkdir(PATHS.music, { recursive: true });
+ await mkdir(PATHS.videos, { recursive: true });
+ execFileSync(ffmpeg, ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'sine=frequency=220:duration=10', join(PATHS.music, 'synthetic-master.wav')]);
+ const p = await store.createProject({ name: 'Example paper doorway', uploadedAudioFilename: 'synthetic-master.wav', mediaMode: 'code-images', composition: { mode: 'document' } });
+ await store.setProjectAnalysis(p.id, { durationSec: 10, bpm: 120, beats: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], downbeats: [0, 4, 8], sections: [{ id: 'chorus', label: 'Chorus', startSec: 0, endSec: 10 }] });
+ await store.updateProject(p.id, { lyricCues: [{ id: 'line', text: 'Open the doorway', startSec: 1, endSec: 7, words: [{ conf: 'matched', w: 'Open', startSec: 1, endSec: 3 }, { conf: 'matched', w: 'the', startSec: 3, endSec: 4 }, { conf: 'matched', w: 'doorway', startSec: 4, endSec: 7 }] }] });
+ const scene = await store.addProjectScene(p.id, { label: 'Chorus', startSec: 0, endSec: 10, prompt: 'A paper doorway opens onto a copper sky.' });
+ const { buildCodeTimeline } = await import('../services/musicVideo/codeTimeline.js');
+ const sectionId = buildCodeTimeline(await store.getProject(p.id)).sections[0].id;
+ author.sectionId = sectionId;
+ const { artifact } = await saveGeneratedDevArtifact(p.id, { kind: 'cast-sets', title: 'Static concept reference — paper doorway', html: '<html><body><h1>Static concept reference</h1><svg viewBox="0 0 600 300"><rect width="600" height="300" fill="#151e35"/><rect x="200" y="30" width="160" height="220" fill="#d59655"/></svg></body></html>' });
+ const draft = { cast: 'Small paper operator in a copper vest.', environments: 'Indigo archive, layered door and warm sky.', visualLanguage: 'Cream paper, copper light, readable negative space.', motionLanguage: 'Operator reaches toward door; doorway opens through chorus.', guideArtifactId: artifact.id, lyricsMode: 'vocal', timingStatus: 'verified', timingNotes: 'Synthetic fixture word timings verified.', storyboard: [{ sceneId: scene.sceneId, lyricCueIds: ['line'], action: 'Open the door', staging: 'Operator left, door center', camera: 'Hold wide with layered depth', transition: 'Hold open doorway' }] };
+ const { saveProductionDraft } = await import('../services/musicVideo/productionReviewService.js');
+ await saveProductionDraft(p.id, draft);
+
+ const ui = join(PATHS.data, 'review-ui'); await mkdir(ui, { recursive: true });
+ const entry = `import React,{useEffect,useState} from 'react';import{createRoot}from'react-dom/client';import Panel from './src/components/musicVideo/ProductionReviewPanel.jsx';import DocumentPanel from './src/components/musicVideo/DocumentCompositionPanel.jsx';import useReview from './src/hooks/useMusicVideoProductionReview.js';function App(){const[p,setP]=useState(null);useEffect(()=>{fetch('/api/music-video/${p.id}/production-review').then(r=>r.json()).then(r=>setP(r.project))},[]);const review=useReview({project:p,replaceProject:setP});return p?<main style={{maxWidth:1100,margin:'auto',padding:24}}><h1>Music video production review</h1><DocumentPanel project={p} onProject={setP} onSave={async patch=>{const r=await fetch('/api/music-video/${p.id}',{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify(patch)});setP(await r.json())}}/><Panel project={p} review={review} onOpenArtifact={id=>window.open('/api/music-video/${p.id}/dev-artifacts/'+id+'/file')}/></main>:null}createRoot(document.getElementById('root')).render(<App/>);`;
+ const { build } = await import(clientBundler[0]);
+ const { default: react } = await import(clientBundler[1]);
+ const { default: tailwind } = await import(clientBundler[2]);
+ const { symlink } = await import('node:fs/promises');
+ await symlink(join(client, 'node_modules'), join(ui, 'node_modules'), 'dir');
+ await writeFile(join(ui, 'entry.jsx'), `import ${JSON.stringify(join(client, 'src/index.css'))};\n` + entry.replaceAll("'./src/", `'${client}/src/`));
+ await writeFile(join(ui, 'index.html'), '<html><head><meta name="viewport" content="width=device-width,initial-scale=1"></head><body><div id="root"></div><script type="module" src="/entry.jsx"></script></body></html>');
+ await build({ configFile: false, root: ui, plugins: [react()], css: { postcss: { plugins: [tailwind({ base: client })] } }, build: { outDir: join(ui, 'dist'), emptyOutDir: true }, logLevel: 'warn' });
+ const app = express(); app.use(express.json()); app.get('/api/providers', (req,res)=>res.json({activeProvider:'stub-provider',providers:[{id:'stub-provider',name:'Synthetic author',type:'api',enabled:true,models:['fixture-model'],defaultModel:'fixture-model',toolFreeOneShot:true}]})); app.use('/api/music-video', router); app.use('/data/videos', express.static(PATHS.videos)); app.use('/fonts', express.static(join(client, 'public/fonts'))); app.use(express.static(join(ui, 'dist'))); app.use(errorMiddleware);
+ server = await new Promise(resolve => { const listener = app.listen(0, '127.0.0.1', () => resolve(listener)); });
+ proc = spawn(chrome, _testChromeCaptureArgs(join(PATHS.data, 'test-chrome')), { stdio: ['ignore', 'ignore', 'pipe'] });
+ endpoint = new URL(await _waitForTestChrome(proc)).origin.replace('ws:', 'http:');
+ browser = await chromium.connectOverCDP(endpoint);
+ const page = await browser.newPage({ viewport: { width: 1280, height: 1000 } });
+ const errors = []; page.on('pageerror', e => errors.push(e.message));
+ await page.goto(`http://127.0.0.1:${server.address().port}`);
+ await page.getByLabel('Design and composition media').selectOption('code-only');
+ await page.getByLabel('Authoring renderer').selectOption('three');
+ expect((await store.getProject(p.id)).mediaMode).toBe('code-only');
+ const choreography = 'Energy target: driving chorus with an expansive exit.\n0:00–0:04 / opening downbeats: operator steps toward the door and raises the key; camera pushes in; title lands on the first vocal.\n0:04–0:10 / chorus accent: key turns, door swings outward, operator crosses the threshold; camera arcs around the prop; type clears before the exit.\nRepeat chorus: widen the doorway and increase the operator travel while retaining the copper motif.';
+ await page.getByText('Edit visual guide and storyboard', { exact: true }).click();
+ await page.getByLabel('Timed choreography and energy plan', { exact: true }).fill(choreography);
+ const [savedPlan] = await Promise.all([
+ page.waitForResponse(response => response.url().endsWith('/production-review') && response.request().method() === 'PUT'),
+ page.getByRole('button', { name: 'Save planning edits' }).click(),
+ ]);
+ expect(savedPlan.status()).toBe(200);
+ expect((await store.getProject(p.id)).productionReview.draft.motionLanguage).toBe(choreography);
+ const password = page.getByLabel('Instance password for this approval');
+ await password.fill('synthetic-password'); await page.getByRole('button', { name: 'Approve art direction', exact: true }).click();
+ const [planned] = await Promise.all([
+ page.waitForResponse(response => response.url().endsWith('/production-review/prepare') && response.request().method() === 'POST'),
+ page.getByRole('button', { name: 'Prepare planning draft with autopilot' }).click(),
+ ]);
+ expect(planned.status()).toBe(200);
+ expect((await store.getProject(p.id)).treatment.shotDirections[0].medium).toBe('procedural');
+ author.sectionId = buildCodeTimeline(await store.getProject(p.id)).sections[0].id;
+ await page.getByText('Review feedback and revision history', { exact: true }).click();
+ await page.getByLabel('Feedback stage').selectOption('storyboard');
+ await page.getByLabel('Feedback target').fill('shot: chorus / operator');
+ await page.getByLabel('Requested change').fill('Move the operator behind the threshold at the exit.');
+ await page.getByRole('button', { name: 'Save revision feedback' }).click();
+ await page.getByText('Move the operator behind the threshold at the exit.', { exact: true }).waitFor();
+ expect(await page.getByRole('button', { name: 'Approve lyric-timed storyboard' }).isDisabled()).toBe(true);
+ await page.getByLabel('Resolution for shot: chorus / operator').fill('Reviewed the updated staging in the storyboard.');
+ await password.fill('synthetic-password'); await page.getByRole('button', { name: 'Resolve feedback after review' }).click();
+ await page.getByText('Resolution: Reviewed the updated staging in the storyboard.', { exact: true }).waitFor();
+ const beforeBoard = await page.evaluate(async id => (await fetch('/api/music-video/' + id + '/production-review')).json(), p.id);
+ expect(beforeBoard.readiness.storyboard.problems).toEqual([]);
+ await password.fill('synthetic-password'); await page.getByRole('button', { name: 'Approve lyric-timed storyboard' }).click();
+ await page.getByRole('button', { name: 'Generate authored 3D composition' }).click();
+ await page.getByRole('button', { name: 'Accept reviewed version' }).waitFor();
+ expect(author.prompt).toContain(JSON.stringify(choreography));
+ await page.getByRole('button', { name: 'Accept reviewed version' }).click();
+ await page.waitForFunction(() => document.body.textContent.includes('generated ·'));
+ expect((await store.getProject(p.id)).composition.document.source.kind).toBe('generated');
+ await page.getByRole('button', { name: 'Render animated proof' }).click();
+ await page.locator('video').waitFor({ timeout: 120000 });
+ await page.locator('video').evaluate(async video => { await video.play(); await new Promise(r => setTimeout(r, 400)); video.pause(); });
+ expect(await page.locator('video').evaluate(v => v.videoWidth)).toBeGreaterThan(0);
+ expect(await page.getByRole('region', { name: 'Saved choreography for proof comparison' }).textContent()).toContain(choreography);
+ await password.fill('synthetic-password');
+ expect(await page.getByRole('button', { name: 'Approve animated proof' }).isDisabled()).toBe(true);
+ await page.getByLabel('Playback energy compared with the saved plan').fill('The synthetic fixture demonstrates a driving chorus: the modeled subject changes pose and travels while the camera moves through the scene.');
+ await page.getByLabel('Timecoded playback notes').fill('0:02 — subject enters the frame; 0:07 — pose and camera position differ and readable type remains clear. This is a synthetic workflow test, not artistic approval of a production video.');
+ await page.getByLabel('I watched this revision with audio at normal speed and compared its energy, timed choreography and lyric timing with the saved plan.').check();
+ await page.getByRole('button', { name: 'Approve animated proof' }).click();
+ await page.waitForFunction(() => [...document.querySelectorAll('[role=status]')].filter(el => el.textContent === 'Approved for this revision').length === 3);
+ const result = await store.getProject(p.id);
+ expect(result.productionReview.feedback[0].resolvedAt).toBeTruthy();
+ expect(result.productionReview.approvals.proof.proofReview).toMatchObject({ watchedWithAudio: true, excerptId: result.productionReview.proof.excerptId, timecodedNotes: expect.stringContaining('0:02') });
+ expect(errors).toEqual([]);
+ const proofFile = join(PATHS.videos, result.excerpts.find(e => e.id === result.productionReview.proof.excerptId).filename);
+ const frame = at => execFileSync(ffmpeg, ['-v', 'error', '-ss', String(at), '-i', proofFile, '-frames:v', '1', '-vf', 'scale=64:36', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-']);
+ const middle = frame(5);
+ expect([...middle].filter((_, i) => i % 3 === 0 && middle[i] > middle[i + 2] + 40).length).toBeGreaterThan(15); // authored warm character occupies the stage
+ expect(frame(2).equals(frame(7))).toBe(false); // actual authored motion changes the scene
+ if (process.env.MUSIC_VIDEO_RICH_UI_EVIDENCE_DIR) {
+ await mkdir(process.env.MUSIC_VIDEO_RICH_UI_EVIDENCE_DIR, { recursive: true });
+ await page.screenshot({ path: join(process.env.MUSIC_VIDEO_RICH_UI_EVIDENCE_DIR, 'review-desktop.png'), fullPage: true });
+ await page.setViewportSize({ width: 390, height: 844 });
+ await page.screenshot({ path: join(process.env.MUSIC_VIDEO_RICH_UI_EVIDENCE_DIR, 'review-mobile.png'), fullPage: true });
+ const excerpt = result.excerpts.find(e => e.id === result.productionReview.proof.excerptId);
+ await copyFile(join(PATHS.videos, excerpt.filename), join(process.env.MUSIC_VIDEO_RICH_UI_EVIDENCE_DIR, 'synthetic-chorus-proof.mp4'));
+ execFileSync(ffmpeg, ['-v', 'error', '-y', '-ss', '5', '-i', join(PATHS.videos, excerpt.filename), '-frames:v', '1', join(process.env.MUSIC_VIDEO_RICH_UI_EVIDENCE_DIR, 'proof-frame.png')]);
+ }
+ }, 180000);
+});
diff --git a/server/routes/providers.js b/server/routes/providers.js
index ff4dba8307..c90c8afc23 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -80,6 +80,7 @@ import {
import { runLocalRuntimeSetup, SETUP_ACTIONS } from '../services/localRuntimeSetup.js';
import { localEndpointPort, localRuntimeForProvider } from '../lib/localProviderRuntime.js';
import {
+ isToolFreeOneShotProvider,
enforcedPublicReviewPosturesForProvider,
publicReviewPosturesForProvider,
PUBLIC_REVIEW_NO_TOOL_POSTURE,
@@ -211,6 +212,7 @@ const presentProvider = (provider, capabilities = captureSystemCapabilities()) =
// decided in `POST /:id/refresh-models`, and the two must stay in step or
// a card offers a button the route refuses.
canRefreshModels: decorated.canRefreshModels || Boolean(harnessCatalogRuntime(provider)),
+ toolFreeOneShot: isToolFreeOneShotProvider(provider),
publicReviewPostures,
publicReviewEnforcedPostures: enforcedPublicReviewPosturesForProvider(provider),
publicReviewSupported: publicReviewPostures.includes(PUBLIC_REVIEW_NO_TOOL_POSTURE),
diff --git a/server/routes/providers.modelAccess.test.js b/server/routes/providers.modelAccess.test.js
index ec0bbc981a..19f81fe717 100644
--- a/server/routes/providers.modelAccess.test.js
+++ b/server/routes/providers.modelAccess.test.js
@@ -35,6 +35,16 @@ function appWith(providerService) {
}
describe('provider payloads carry the model-access-scoped catalog', () => {
+ it('offers an honest tool-free authoring capability, overriding stored claims', async () => {
+ const providers = [NVIDIA,
+ { id: 'headless', type: 'cli', command: 'claude', models: ['example-model'] },
+ { id: 'interactive', type: 'tui', command: 'claude', models: ['example-model'], toolFreeOneShot: true },
+ { id: 'agent', type: 'cli', command: 'codex', models: ['example-model'], toolFreeOneShot: true }];
+ const app = appWith({ getAllProviders: vi.fn().mockResolvedValue({ providers }) });
+ const res = await request(app).get('/api/providers');
+ expect(res.status).toBe(200);
+ expect(res.body.providers.map(p => [p.id, p.toolFreeOneShot])).toEqual([['nvidia-nim', true], ['headless', true], ['interactive', false], ['agent', false]]);
+ });
it('GET / narrows models, keeps the full catalog, and still strips the key', async () => {
const app = appWith({
getAllProviders: vi.fn().mockResolvedValue({ activeProvider: 'nvidia-nim', providers: [NVIDIA] }),
diff --git a/server/services/codeAnimation/prompt.js b/server/services/codeAnimation/prompt.js
index 934b75bd82..c46ca5deda 100644
--- a/server/services/codeAnimation/prompt.js
+++ b/server/services/codeAnimation/prompt.js
@@ -310,6 +310,36 @@ const CODE_VIDEO_RULES = `RUNTIME CONTRACT (the host already supplies this — w
- Determinism: no Math.random, Date.now, performance.now, getRandomValues, fetch, WebSocket, XMLHttpRequest, import, or require. Per-frame jitter must use env.frame (the integer frame index), never continuous env.t, so motion-blur sub-frames stay coherent.
- Canvas 2D only. No external assets, fonts, or network.`;
+// Share the studio craft bar with section authors without asking them to own
+// playback, redraw the lyric pass, or invent analyzed musical events.
+const MUSIC_VIDEO_DIRECTION = DIRECTION
+ .replace("where it gives none, time the beats yourself: establish → develop → climax → resolve", "use the supplied section, beat, downbeat and lyric-word times; choose authored action spans within them without inventing analyzed events")
+ .replace("- Endings: the player loops the film — when the brief ends by returning to its opening, match the final frame's framing, lighting, and motion to t=0 so the cut back feels intentional.", "- Endings: resolve the authored action at the supplied song ending; match the opening only when the approved brief requests a loop.");
+const MUSIC_VIDEO_SELF_REVIEW = SELF_REVIEW
+ .replace("step through renderFrame at every beat's key frame", 'step through render(ctx, env) on the host timeline at every supplied anchor and action key frame')
+ .replace('empty or static stretches', 'unmotivated empty or static stretches');
+const MUSIC_VIDEO_CHOREOGRAPHY = `MUSICAL CHOREOGRAPHY — author a timed performance, not a looping backdrop:
+- Follow the reviewed energy target and give each section a time-based action plan: what the subject does, how props respond, how the camera stages or reveals it, and how permitted non-lyric typography supports it. Use env.t/localT with explicit anticipation, action, follow-through and settling spans. Preserve the host's lyric pass as the authority: never redraw lyric words or event labels; stage the world around their readable space.
+- Ground meaningful actions and reveals in the supplied beats, downbeats and timed lyric words (startSec/endSec). Use supplied band onsets for actual accents; never invent a kick, snare, drop, word timing or missing event. If only a line timing exists, treat it as a line anchor, not separate invented word timings.
+- When song.features is present, envelopes.rms/low/mid/high are normalized 0..1 energy channels on envelopes.fps; runtime sample i is at i/fps seconds. Use those measured channels to shape bounded subject/prop amplitude, camera intensity and permitted typography emphasis. The prompt snapshot may evenly sample envelopes: sample k is at k*sampleStride/fps, while runtime env.song keeps the original grid. Listed onsets are measured times, not envelope peaks inferred by the author. Respect truncatedAtSec and do not extend missing measurements.
+- When song.features is null, audio feature data is unavailable: use only supplied beat/lyric/section anchors and explicitly authored motion, with no claimed spectral or instrumental reaction. Feature names alone are not measurements. Missing anchors stay missing; never fabricate analyzer results.
+- Repeated choruses keep a recognizable motif but escalate or deliberately change subject action, prop interaction, staging, camera reveal or scale. Vary the narrative consequence, not merely the particle color or animation seed.
+- The 3–5 second visual-payoff pacing rule does not require rapid cuts or constant motion. A change of expression, a prop consequence, a reveal or intentional stillness can carry the beat. Hold for tenderness, anticipation or silence when the music and approved direction call for it; make each hold purposeful, with a legible entry and release. Reactive accents must respect env.reactiveGain when supplied and never defeat a host silence hold.`;
+
+function promptFeatures(features) {
+ if (!features?.envelopes || !features?.onsets) return null;
+ const channels = ['rms', 'low', 'mid', 'high'];
+ const stride = Math.max(1, Math.ceil(Math.max(...channels.map(key => features.envelopes[key]?.length || 0)) / 240));
+ return {
+ envelopes: { fps: features.envelopes.fps, sampleStride: stride,
+ ...Object.fromEntries(channels.map(key => [key, (features.envelopes[key] || []).filter((_, index) => index % stride === 0).slice(0, 240)])),
+ },
+ onsets: Object.fromEntries(['low', 'mid', 'high'].map(key => [key, (features.onsets[key] || []).slice(0, 200)])),
+ onsetTimesTruncated: ['low', 'mid', 'high'].some(key => features.onsets[key]?.length > 200),
+ truncatedAtSec: features.truncatedAtSec ?? null,
+ };
+}
+
function promptSong(song) {
return {
durationSec: song.durationSec,
@@ -318,7 +348,8 @@ function promptSong(song) {
lyrics: (song.lyrics || []).slice(0, 400),
beats: (song.beats || []).slice(0, 400),
downbeats: (song.downbeats || []).slice(0, 200),
- featureNames: song.featureNames || [],
+ featureNames: (song.featureNames || []).slice(0, 40),
+ features: promptFeatures(song.features),
narrativeEvents: song.narrativeEvents || [],
reactiveSections: song.reactiveSections || [],
};
@@ -338,12 +369,15 @@ export function buildMusicVideoCodePrompt({ title = '', palette, song, styleLine
return [
`You write Canvas 2D section functions for a code-rendered music video${title ? ` titled "${trimTo(title, 200)}"` : ''}. The host seeks them against the song. No footage generation.`,
CODE_VIDEO_RULES,
+ MUSIC_VIDEO_DIRECTION,
+ MUSIC_VIDEO_CHOREOGRAPHY,
`PALETTE:\n${JSON.stringify(palette)}`,
styleLines.length ? `STYLE SOURCE:\n${styleLines.join('\n')}` : '',
directionContext ? `APPROVED CAST & SETS DEFINITIONS AND RULES:\n${directionContext}` : '',
`SONG (song.json):\n${JSON.stringify(promptSong(song))}`,
`SECTIONS:\n${brief}`,
scope,
+ MUSIC_VIDEO_SELF_REVIEW,
'OUTPUT: Return ONLY a ```json fence of the form {"sections":[{"id":"...","source":"function render(ctx, env) { ... }"}]}. No HTML document, no explanation.',
].filter(Boolean).join('\n\n');
}
@@ -367,12 +401,15 @@ export function extractCodeSections(text) {
}
/** Author only bounded drawing functions; the host owns the page and media. */
-export function buildMixedMediaDocumentPrompt({ title, song, palette, treatment, visualSpec, scenes, styleLines = [], onlySectionId = null, sharedStyle = null, directionContext = '' }) {
+export function buildMixedMediaDocumentPrompt({ title, song, palette, treatment, visualSpec, scenes, styleLines = [], onlySectionId = null, sharedStyle = null, directionContext = '', renderer = 'canvas', mediaMode = 'code-images-video' }) {
const sections = (song.sections || []).filter((section) => !onlySectionId || section.id === onlySectionId);
return [
- `Write original Canvas 2D section functions for a mixed-media music-video document titled ${JSON.stringify(trimTo(title, 200))}. The host owns the document, song clock, selected local media and lyric pass. Return code functions only; do not request or generate image/video assets.`,
- CODE_VIDEO_RULES.replace('- Canvas 2D only. No external assets, fonts, or network.', '- Canvas 2D only. No network, remote URLs, filesystem paths or font loading. The host binds only the listed selected project assets; draw over footage/stills without obscuring them, and draw the entire frame for card scenes.'),
- 'env additionally has mediaKind (video, image or null) and visualLayer (footage, still or card). The host has already drawn the selected media at its in/out time. Do not read DOM or load assets in a section function. Use seeded arithmetic from env.frame for visual motion. Keep repeated hooks related but deliberately vary their action.',
+ `MEDIA POLICY: ${mediaMode}. Code always authors composition, staging, characters, camera, text, motion and timing. Never generate guide images in code-only mode.`,
+ renderer === 'three' ? `Write complete authored Three.js worlds, one function render(ctx, env) per section. ctx = { THREE, scene, camera, text }; THREE is the installed locally packaged library; scene is a fresh Scene on EACH seek, camera a PerspectiveCamera, text a transparent Canvas2D overlay with local MV Mono font. Build modeled characters with articulated limbs and expressive poses, environments with depth/lighting/shadows, props, narrative action and camera choreography. Position every object analytically from env.t/localT; no simulation accumulation. Add geometry/lights to ctx.scene and set ctx.camera explicitly. Use ctx.text for designed typography. Render fills the whole frame; a particle field or text overlays alone are not a scene. Do not create a renderer, DOM elements, textures loaded from files, or another clock. env provides t, localT, frame, width, height, song, section, palette, safe, events and reactiveGain. No imports, require, fetch, Math.random, Date, performance, globalThis, window, document or external assets. The host draws aligned subtitles after your text; reserve lower title-safe space. Use reusable local functions within each section for anatomy and world construction.` : `Write original Canvas 2D section functions for a mixed-media music-video document titled ${JSON.stringify(trimTo(title, 200))}. The host owns the document, song clock, selected local media and lyric pass. Return code functions only; do not request or generate image/video assets.`,
+ renderer === 'three' ? '' : CODE_VIDEO_RULES.replace('- Canvas 2D only. No external assets, fonts, or network.', '- Canvas 2D only. No network, remote URLs, filesystem paths or font loading. The host binds only the listed selected project assets; draw over footage/stills without obscuring them, and draw the entire authored world for card scenes, including characters, environments, camera staging, lighting and narrative actions. Local packaged fonts MV Mono, MV Cond and MV Stencil are available; authored titles are allowed, but do not duplicate host subtitles.'),
+ MUSIC_VIDEO_DIRECTION,
+ MUSIC_VIDEO_CHOREOGRAPHY,
+ renderer === 'three' ? 'The authored Three.js world receives no selected-media handles; all visual staging uses geometry and the host text overlay.' : 'env additionally has mediaKind (video, image or null) and visualLayer (footage, still or card). The host has already drawn the selected media at its in/out time. Do not read DOM or load assets in a section function. Use seeded arithmetic from env.frame for visual motion. Keep repeated hooks related but deliberately vary their action.',
'NARRATIVE CLOCK: song.narrativeEvents are resolved absolute startFrame/endFrame bindings. env.events supplies active events with progress and counter value; env.reactiveGain is bounded by the section gain/maxGain and is zero during silence. The host freezes song time, media and graphics for silence, and draws exact event text/counters/motif labels after your function. Use the narrativeFunction, motif and mediumRationale to motivate your graphic actions; do not duplicate event text or infer new onsets. Prefer code/stills/selected media for exact text and graphics. Footage is for actions that need it and must already be selected.',
`SHARED STYLE CONTRACT:\n${JSON.stringify(sharedStyle || { palette, treatment: { brief: treatment?.brief || null, motifs: treatment?.arc?.motifs || [], styleLook: treatment?.styleLook || null }, visualSpec, styleLines })}`,
directionContext ? `APPROVED CAST & SETS DEFINITIONS AND RULES:\n${directionContext}` : '',
@@ -380,6 +417,7 @@ export function buildMixedMediaDocumentPrompt({ title, song, palette, treatment,
`APPROVED SCENE ASSIGNMENTS AND LOCAL ASSET IDS:\n${JSON.stringify(scenes)}`,
`SECTIONS TO AUTHOR:\n${JSON.stringify(sections)}`,
onlySectionId ? `Revise only section ${JSON.stringify(onlySectionId)}. Preserve the shared style contract and other sections.` : 'Return one function for each listed section id. Describe a specific visual action for each scene and a distinct entry/exit transition in its function.',
+ MUSIC_VIDEO_SELF_REVIEW,
'OUTPUT: Return ONLY a ```json fence of the form {"sections":[{"id":"...","source":"function render(ctx, env) { ... }"}]}. No HTML, no assets, no explanation.',
].filter(Boolean).join('\n\n');
}
diff --git a/server/services/codeAnimation/prompt.test.js b/server/services/codeAnimation/prompt.test.js
index 807392390c..e0ab78f0d0 100644
--- a/server/services/codeAnimation/prompt.test.js
+++ b/server/services/codeAnimation/prompt.test.js
@@ -1,11 +1,15 @@
import { describe, expect, it } from 'vitest';
import {
buildCodeAnimationPrompt,
+ buildMusicVideoCodePrompt,
+ buildMixedMediaDocumentPrompt,
+ PACING_RULE,
extractAnimationHtml,
resolveFrameSize,
CODE_ANIMATION_AUDIO_GLOBAL,
CODE_ANIMATION_MESSAGES,
} from './prompt.js';
+import { buildSongDocument } from '../musicVideo/codeTimeline.js';
const format = { durationSeconds: 20, aspectRatio: '16:9', resolution: '1080p', fps: 30 };
@@ -134,3 +138,61 @@ describe('extractAnimationHtml', () => {
expect(extractAnimationHtml(null)).toBeNull();
});
});
+
+// Exercise the production song adapter, not a prompt-only field nobody supplies.
+describe('music-video craft and measured choreography', () => {
+ const builders = [
+ ['native Canvas', buildMusicVideoCodePrompt],
+ ['document Canvas', input => buildMixedMediaDocumentPrompt({ ...input, renderer: 'canvas' })],
+ ['document Three.js', input => buildMixedMediaDocumentPrompt({ ...input, renderer: 'three' })],
+ ];
+ const samples = Array.from({ length: 600 }, (_, index) => index / 600);
+ const features = {
+ envelopes: { fps: 20, rms: samples, low: samples, mid: samples, high: samples },
+ onsets: { low: [0.75, 4.25], mid: [1.5], high: [2.75] }, truncatedAtSec: 30,
+ };
+ const project = {
+ audioAnalysis: { durationSec: 32, beats: [0, 0.5, 1, 1.5, 4], downbeats: [0, 4], features,
+ sections: [{ id: 'chorus', label: 'Chorus', startSec: 0, endSec: 32 }] },
+ lyricCues: [{ id: 'line', text: 'Open slowly', startSec: 1, endSec: 3,
+ words: [{ w: 'Open', startSec: 1.25, endSec: 2 }, { w: 'slowly', startSec: 2.25, endSec: 3 }] }],
+ };
+ const songSnapshot = prompt => JSON.parse(prompt.match(/^SONG[^\n]*\n([^\n]+)/m)[1]);
+
+ it.each(builders)('gives %s the shared craft bar and bounded real feature/word anchors', (_label, build) => {
+ const song = buildSongDocument(project);
+ const prompt = build({ title: 'Example measured choreography', song, palette: {}, scenes: [] });
+ expect(prompt).toContain('DIRECTION — make it feel like a studio short');
+ expect(prompt).toContain(PACING_RULE);
+ expect(prompt).toContain('SELF-REVIEW before you answer');
+ expect(prompt).toContain('step through render(ctx, env)');
+ expect(prompt).not.toContain('step through renderFrame');
+ expect(prompt.indexOf('SELF-REVIEW')).toBeLessThan(prompt.indexOf('OUTPUT:'));
+ expect(prompt).toContain('Follow the reviewed energy target and give each section a time-based action plan');
+ expect(prompt).toContain('Repeated choruses');
+ expect(prompt).toContain('does not require rapid cuts or constant motion');
+ expect(prompt).toContain("Preserve the host's lyric pass as the authority");
+ expect(prompt).toContain('never invent a kick, snare, drop, word timing or missing event');
+ const snapshot = songSnapshot(prompt);
+ expect(snapshot.beats).toEqual(project.audioAnalysis.beats);
+ expect(snapshot.downbeats).toEqual(project.audioAnalysis.downbeats);
+ expect(snapshot.lyrics[0].words[0]).toEqual({ text: 'Open', startSec: 1.25, endSec: 2 });
+ expect(snapshot.features.onsets).toEqual(features.onsets);
+ expect(snapshot.features.truncatedAtSec).toBe(30);
+ expect(snapshot.features.envelopes).toMatchObject({ fps: 20, sampleStride: 3 });
+ expect(snapshot.features.envelopes.low).toEqual(samples.filter((_, index) => index % 3 === 0));
+ expect(snapshot.features.envelopes.low.length).toBeLessThanOrEqual(240);
+ expect(song.features.envelopes.low).toEqual(samples); // runtime retains original sampling grid
+ });
+
+ it('does not manufacture features for a legacy or malformed analysis', () => {
+ for (const features of [null, { ...project.audioAnalysis.features, envelopes: { ...project.audioAnalysis.features.envelopes, low: [1.5] } }]) {
+ const song = buildSongDocument({ ...project, audioAnalysis: { ...project.audioAnalysis, features } });
+ for (const [, build] of builders) {
+ const prompt = build({ song, palette: {}, scenes: [] });
+ expect(songSnapshot(prompt).features).toBeNull();
+ expect(prompt).toContain('audio feature data is unavailable');
+ }
+ }
+ });
+});
diff --git a/server/services/htmlComposition/browser.js b/server/services/htmlComposition/browser.js
index 6b4ba95ee7..cc8a677d12 100644
--- a/server/services/htmlComposition/browser.js
+++ b/server/services/htmlComposition/browser.js
@@ -5,7 +5,7 @@ import { PATHS } from '../../lib/fileUtils.js';
import { cdpRequest } from '../browserService.js';
const ORIGIN = 'https://composition.invalid';
-const MIME = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.svg': 'image/svg+xml', '.webp': 'image/webp', '.woff': 'font/woff', '.woff2': 'font/woff2', '.mp4': 'video/mp4', '.mov': 'video/quicktime', '.webm': 'video/webm', '.mp3': 'audio/mpeg', '.wav': 'audio/wav' };
+const MIME = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.svg': 'image/svg+xml', '.webp': 'image/webp', '.woff': 'font/woff', '.woff2': 'font/woff2', '.mp4': 'video/mp4', '.mov': 'video/quicktime', '.webm': 'video/webm', '.mp3': 'audio/mpeg', '.wav': 'audio/wav' };
// Sandboxing removes alternate realms, popups, forms and workers. HTTP assets
// are fulfilled below, never continued to the browser's network stack.
const CSP = "sandbox allow-scripts; default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src http: https:; font-src 'self'; media-src 'self'; connect-src http: https:; frame-src 'none'; worker-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'";
@@ -90,7 +90,7 @@ async function readSlice(asset, start, end) {
} finally { await handle.close(); }
}
-export async function openComposition(directory, { signal, validateAssets, streamMedia = false } = {}) {
+export async function openComposition(directory, { signal, validateAssets, streamMedia = false, mediaMode = 'code-images-video' } = {}) {
const assets = await snapshotAssets(directory, { streamMedia });
validateAssets?.(assets);
signal?.throwIfAborted();
@@ -125,7 +125,9 @@ export async function openComposition(directory, { signal, validateAssets, strea
});
});
}
+ const policyCsp = CSP.replace('img-src http: https:', mediaMode === 'code-only' ? "img-src 'none'" : 'img-src http: https:').replace("media-src 'self'", mediaMode !== 'code-images-video' ? "media-src 'none'" : "media-src 'self'");
async function request(params) {
+ if (params.resourceType === 'Image' && mediaMode === 'code-only' || params.resourceType === 'Media' && mediaMode !== 'code-images-video') throw new Error('Composition media mode refused this asset');
const url = new URL(params.request.url);
const key = decodeURIComponent(url.pathname);
const asset = url.origin === ORIGIN && !url.username && !url.password && params.request.method === 'GET' && assets.get(key);
@@ -147,7 +149,7 @@ export async function openComposition(directory, { signal, validateAssets, strea
const range = rangeHeader ? parseByteRange(rangeHeader, size) : null;
if (rangeHeader && !range && size > 0) {
await send('Fetch.fulfillRequest', { requestId: params.requestId, responseCode: 416,
- responseHeaders: [{ name: 'Content-Range', value: `bytes */${size}` }, { name: 'Content-Security-Policy', value: CSP }], body: '' });
+ responseHeaders: [{ name: 'Content-Range', value: `bytes */${size}` }, { name: 'Content-Security-Policy', value: policyCsp }], body: '' });
return;
}
const start = range ? range.start : 0;
@@ -157,7 +159,7 @@ export async function openComposition(directory, { signal, validateAssets, strea
requestId: params.requestId, responseCode: range ? 206 : 200,
responseHeaders: [
{ name: 'Content-Type', value: MIME[extname(key).toLowerCase()] ?? 'application/octet-stream' },
- { name: 'Content-Security-Policy', value: CSP },
+ { name: 'Content-Security-Policy', value: policyCsp },
{ name: 'Access-Control-Allow-Origin', value: '*' },
{ name: 'X-DNS-Prefetch-Control', value: 'off' },
{ name: 'Accept-Ranges', value: 'bytes' },
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index ff3c137001..add5fbca8f 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -1256,6 +1256,11 @@ async function runJobLifecycle(job, markDispatched) {
watchdogTimer.unref?.();
try {
+ // A restored remote submission must reach its adapter to deliver an
+ // already-recorded cancellation, even after its project narrows or is deleted.
+ const recoveringRemoteCancellation = isRemoteMediaJob(job) && job.cancelRequested
+ && job.params?.remoteMedia?.reconcile === true && job.params.remoteMedia.cancelRequested === true;
+ if (!recoveringRemoteCancellation) await assertMusicVideoJobPolicy(job.kind, job.params);
const mod = await getGenModuleForJob(job);
if (job.params?.videoProduction) {
const { assertVideoAttemptDispatch } = await import('../creativeDirector/videoExecution.js');
@@ -1357,7 +1362,18 @@ export function assertMediaQueueRoom(count = 1) {
// refused (429 MEDIA_QUEUE_FULL) before ANY state changes — no id, no queue
// entry, no SSE entry, no snapshot write. The check and the push below run in
// one synchronous stretch, so concurrent submissions cannot overshoot it.
+async function assertMusicVideoJobPolicy(kind, params) {
+ if (params?.musicVideo?.projectId && ['image', 'video'].includes(kind)) {
+ const { getProject } = await import('../musicVideo/projects.js');
+ const { assertMusicVideoMedia } = await import('../../lib/musicVideoMediaPolicy.js');
+ const project = await getProject(params.musicVideo.projectId);
+ if (!project) throw new Error('Music Video project not found');
+ assertMusicVideoMedia(project, kind, 'generation');
+ }
+}
+
export async function enqueueJob({ kind, params, owner = null }) {
+ await assertMusicVideoJobPolicy(kind, params);
if (params?.musicVideo?.sceneId) {
const { assertMusicVideoSceneReview } = await import('../musicVideo/productionReviewService.js');
await assertMusicVideoSceneReview(params.musicVideo);
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index 663868cb9f..9b58a2296f 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -1,3 +1,4 @@
+vi.mock('../musicVideo/projects.js', () => ({ getProject: vi.fn(async () => ({ mediaMode: 'code-images-video' })) }));
vi.mock('../musicVideo/productionReviewService.js', () => ({ assertMusicVideoSceneReview: vi.fn(async () => {}) }));
import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync } from 'fs';
@@ -246,6 +247,19 @@ afterAll(async () => {
});
describe('mediaJobQueue', () => {
+ it('blocks guide generation and rechecks media policy before delayed provider dispatch', async () => {
+ const { getProject } = await import('../musicVideo/projects.js');
+ const request = { kind: 'image', params: { prompt: 'Synthetic guide', musicVideo: { projectId: 'mv-example', castAndSets: { key: 'guide' } } } };
+ getProject.mockResolvedValueOnce({ mediaMode: 'code-only' });
+ await expect(mediaJobQueue.enqueueJob(request)).rejects.toMatchObject({ code: 'MUSIC_VIDEO_MEDIA_POLICY' });
+ expect(stubs.generateImage).not.toHaveBeenCalled();
+ getProject.mockResolvedValueOnce({ mediaMode: 'code-images' }).mockResolvedValueOnce({ mediaMode: 'code-only' });
+ const { jobId } = await mediaJobQueue.enqueueJob(request);
+ await waitFor(() => mediaJobQueue.getJob(jobId).status === 'failed');
+ expect(mediaJobQueue.getJob(jobId).error).toContain('planning guides');
+ expect(stubs.generateImage).not.toHaveBeenCalled();
+ });
+
it('rejects an unreviewed music-video scene before queue admission and rechecks delayed dispatch', async () => {
const { assertMusicVideoSceneReview } = await import('../musicVideo/productionReviewService.js');
const request = { kind: 'video', params: { prompt: 'Synthetic scene', musicVideo: { projectId: 'mv-example', sceneId: 'scene-example' } } };
@@ -1533,6 +1547,31 @@ describe('Audio kind (#1928)', () => {
await waitFor(() => mediaJobQueue.getJob(id)?.status === 'completed');
});
+ it.each([{ mediaMode: 'code-only' }, null])('recovers an already-submitted remote cancellation after project policy changes: %j', async project => {
+ const { getProject } = await import('../musicVideo/projects.js');
+ getProject.mockResolvedValueOnce(project);
+ const id = '00000000-0000-4000-8000-000000000003';
+ writeFileSync(join(tempDataDir, 'media-jobs.json'), JSON.stringify({ jobs: [{
+ id, kind: 'video', status: 'running', queuedAt: new Date().toISOString(),
+ params: { musicVideo: { projectId: 'mv-example', sceneId: 'scene-example' },
+ remoteMedia: { ...remoteVideoMediaParams(), cancelRequested: true } },
+ }] }));
+ stubs.generateVideoRemote.mockImplementation(async params => {
+ videoGenEvents.emit('failed', { generationId: params.jobId, error: 'Canceled remotely' });
+ });
+ await mediaJobQueue.initMediaJobQueue();
+ await waitFor(() => mediaJobQueue.getJob(id)?.status === 'canceled');
+ expect(stubs.generateVideoRemote).toHaveBeenCalledWith(expect.objectContaining({
+ jobId: id, remoteMedia: expect.objectContaining({ reconcile: true, cancelRequested: true }),
+ }));
+ expect(stubs.generateVideo).not.toHaveBeenCalled();
+ // A newly submitted request still passes admission policy, even if it
+ // carries a forged cancellation/reconciliation marker.
+ await expect(mediaJobQueue.enqueueJob({ kind: 'video', params: {
+ musicVideo: { projectId: 'mv-example' }, remoteMedia: { ...remoteVideoMediaParams(), reconcile: true, cancelRequested: true },
+ } })).rejects.toThrow();
+ });
+
it('routes an image remote job to the remote adapter and the remote lane, not the GPU', async () => {
stubs.generateImage.mockImplementation(() => new Promise(() => {}));
diff --git a/server/services/musicVideo/__richSceneFixture.js b/server/services/musicVideo/__richSceneFixture.js
new file mode 100644
index 0000000000..0397eeb9b1
--- /dev/null
+++ b/server/services/musicVideo/__richSceneFixture.js
@@ -0,0 +1,23 @@
+// Synthetic author output used by browser and workflow contract tests only.
+export const richSceneSource = `function render(ctx, env) {
+ const { THREE, scene, camera, text } = ctx;
+ scene.background = new THREE.Color('#102030');
+ scene.add(new THREE.HemisphereLight(0xbbeeff, 0x223344, 2));
+ const key = new THREE.DirectionalLight(0xffffff, 3); key.position.set(2, 5, 4); key.castShadow=true; scene.add(key);
+ const floor = new THREE.Mesh(new THREE.PlaneGeometry(30,30), new THREE.MeshStandardMaterial({color:0x294358}));
+ floor.receiveShadow=true; floor.rotation.x = -Math.PI/2; scene.add(floor);
+ for (let i=0; i<9; i++) {
+ const tower = new THREE.Mesh(new THREE.BoxGeometry(0.7,2+i%3,0.8), new THREE.MeshStandardMaterial({color:0x456781}));
+ tower.position.set((i-4)*1.2,1,-4); scene.add(tower);
+ }
+ const character = new THREE.Group(); scene.add(character);
+ const body = new THREE.Mesh(new THREE.BoxGeometry(0.7,1.2,0.5), new THREE.MeshStandardMaterial({color:0xff9933})); body.castShadow=true; body.position.y=1.3; character.add(body);
+ const head = new THREE.Mesh(new THREE.SphereGeometry(0.35,16,12), new THREE.MeshStandardMaterial({color:0xffddaa})); head.position.y=2.2; character.add(head);
+ for (const side of [-1,1]) {
+ const arm = new THREE.Mesh(new THREE.BoxGeometry(0.18,0.9,0.18), body.material); arm.position.set(side*0.65,1.3,0); arm.rotation.z=side*(0.4+0.7*Math.sin(env.t*4)); character.add(arm);
+ const leg = new THREE.Mesh(new THREE.BoxGeometry(0.23,0.7,0.25), body.material); leg.position.set(side*0.22,0.35,0); character.add(leg);
+ }
+ character.position.x=Math.sin(env.t*2)*1.5;
+ camera.position.set(Math.sin(env.t)*2,3,8); camera.lookAt(0,1,0);
+ text.font='40px "MV Mono"'; text.fillStyle='#ffffff'; text.fillText('EXAMPLE WORLD',env.width*0.1,env.height*0.15);
+}`;
diff --git a/server/services/musicVideo/autonomousService.js b/server/services/musicVideo/autonomousService.js
index ccf48cdec2..2a019199ca 100644
--- a/server/services/musicVideo/autonomousService.js
+++ b/server/services/musicVideo/autonomousService.js
@@ -1,5 +1,7 @@
+import { musicVideoMediaMode, musicVideoAllowsMedia } from '../../lib/musicVideoMediaPolicy.js';
import { prepareProductionReview, renderProductionProof } from './productionReviewService.js';
import { assertProductionApproval, productionReadiness, productionProofNeedsRender, productionProofWindow } from './productionReview.js';
+
/**
* Fully-autonomous Music Video — the run orchestrator.
*
@@ -71,6 +73,8 @@ const defaults = {
probeDuration: (filename) => probeVideoDuration(join(PATHS.music, filename)).catch(() => null),
analyzeSong: async (projectId) => (await import('./projectAudio.js')).analyzeProjectSong(projectId),
startProduction: async (...args) => (await import('./productionService.js')).startProduction(...args),
+ generateDocument: async (...args) => (await import('./documentGeneration.js')).generateMixedMediaDocument(...args),
+ acceptDocument: async (...args) => (await import('./documentGeneration.js')).acceptMixedMediaDocument(...args),
generateCode: async (...args) => (await import('./codeGeneration.js')).generateMusicVideoCode(...args),
renderVideo: async (...args) => (await import('./render.js')).renderMusicVideo(...args),
};
@@ -196,6 +200,10 @@ const STAGES = {
},
async style({ project, run }) {
+ if (musicVideoMediaMode(project) === 'code-only') {
+ await deps.updateProject(project.id, { concept: { prompt: run.output.concept.prompt, style: run.output.concept.style || run.output.moodBoard?.stylePrompt || '' } });
+ return { output: { moodBoardId: null } };
+ }
const board = run.output.moodBoard;
const moodBoardId = run.brief.moodBoardId || run.output.moodBoardId || (await deps.createMoodBoard(board)).id;
// The board is also the project's linked mood board; the server derives the
@@ -258,18 +266,23 @@ const STAGES = {
},
async produce({ project, run }) {
- const medium = autonomousMedium(run.brief.tools);
+ const medium = musicVideoMediaMode(project) === 'code-only' ? 'code' : autonomousMedium(run.brief.tools);
if (medium === 'code' && !['code', 'document'].includes(project.composition?.mode)) {
- await deps.updateProject(project.id, { composition: { mode: 'code' } });
+ await deps.updateProject(project.id, { composition: { mode: 'document', authoringRenderer: 'three' } });
}
await prepareProductionReview(project.id);
project = await getProject(project.id);
assertProductionApproval(project, 'storyboard');
+ const authoring = run.brief.authoring || await llmOf(run);
+ const input = { providerId: authoring.providerId, model: authoring.model || undefined, ...(authoring.effort ? { effort: authoring.effort } : {}) };
if (medium === 'code') {
- const authoring = run.brief.authoring || (run.brief.llm ? { providerId: run.brief.llm.providerId, model: run.brief.llm.model, effort: run.brief.llm.effort } : {});
- if (project.composition?.mode === 'code' && !project.composition?.codeVideo?.sections?.length) await deps.generateCode(project.id, {
- providerId: authoring.providerId, model: authoring.model || undefined, ...(authoring.effort ? { effort: authoring.effort } : {}),
- });
+ if (project.composition?.mode === 'code') {
+ if (!project.composition?.codeVideo?.sections?.length) await deps.generateCode(project.id, input);
+ } else if (!project.composition?.document) {
+ const candidate = project.composition?.documentDraft ? { document: project.composition.documentDraft }
+ : await deps.generateDocument(project.id, input);
+ await deps.acceptDocument(project.id, candidate.document.directory);
+ }
project = await getProject(project.id);
const readiness = productionReadiness(project);
if (productionProofNeedsRender(project, readiness.basis.proof)) {
@@ -281,9 +294,10 @@ const STAGES = {
}
const started = await deps.startProduction(project.id, {
directive: trimTo([run.brief.prompt, run.brief.guidance].filter(Boolean).join('\n\n'), 4000),
- pool: autonomousPool(run.brief.tools, run.brief.models),
+ pool: autonomousPool(run.brief.tools, run.brief.models).filter((route) => musicVideoAllowsMedia(project, route.kind)),
limits: { ...run.brief.limits, ...(run.brief.budgetUsd != null ? { spendCapUsd: run.brief.budgetUsd } : {}) },
reviewer: { providerId: run.brief.llm?.providerId || null, model: run.brief.llm?.model || null },
+ authoring: input,
});
return { output: { productionRunId: started.run.id }, wait: true };
},
@@ -370,6 +384,8 @@ export async function startAutonomousVideo(input) {
const created = await deps.createProject({
name: brief.name || trimTo(brief.prompt.replace(/\s+/g, ' '), 60) || 'Autonomous music video',
mode: 'autonomous',
+ mediaMode: brief.mediaMode,
+ ...(brief.mediaMode !== 'code-images-video' ? { productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 } } : {}),
concept: { prompt: trimTo(brief.prompt, 8000) },
automation: {
tools: brief.tools,
diff --git a/server/services/musicVideo/autonomousService.test.js b/server/services/musicVideo/autonomousService.test.js
index 59d9c92342..9e76df056f 100644
--- a/server/services/musicVideo/autonomousService.test.js
+++ b/server/services/musicVideo/autonomousService.test.js
@@ -92,6 +92,8 @@ beforeEach(() => {
analyzeSong: stub('analyze', async () => ({})),
startProduction: stub('production', async () => ({ run: { id: 'mvpr-1' } })),
generateCode: stub('code', async () => ({})),
+ generateDocument: stub('document', async () => ({ document: { directory: 'music-video/mv-auto/composition/example' } })),
+ acceptDocument: stub('accept-document', async (id, directory) => { store.get(id).composition.document = { directory }; return {}; }),
renderVideo: stub('render', async () => ({ jobId: 'render-1' })),
};
service.__setAutonomousDepsForTests(doubles);
@@ -121,6 +123,51 @@ describe('startAutonomousVideo', () => {
expect(doubles.attachAudio).toHaveBeenCalledWith('track-1', 'music-song-a.mp3', expect.objectContaining({ source: 'suno', durationSec: 187 }));
});
+ it.each([
+ { mediaMode: 'code-images', explicit: true },
+ { mediaMode: 'code-images-video', explicit: false },
+ ])('passes the $mediaMode authoring pin through the real production preflight', async ({ mediaMode, explicit }) => {
+ const { buildProjectRecord } = await import('./projectsLogic.js');
+ const production = await import('./productionService.js');
+ const runner = await import('../promptRunner.js');
+ const authoring = { providerId: 'fixture-author', model: 'fixture-model', effort: 'high' };
+ const resolve = vi.spyOn(runner, 'resolveProviderAndModel').mockResolvedValue({
+ provider: { id: authoring.providerId, type: 'api', enabled: true }, selectedModel: authoring.model,
+ });
+ // Exercise actual authoring and pool validation against a synthetic image
+ // backend. The absent approved plan stops the run before any dispatch.
+ const isVideoModeUsable = vi.fn(() => false);
+ const loadEnv = vi.fn(async () => {
+ if (mediaMode === 'code-images') return { settings: { imageGen: { local: { pythonPath: '/opt/example/python' } } },
+ imageModels: [{ id: 'fixture-image' }], isVideoModeUsable };
+ throw Object.assign(new Error('Fixture stopped after authoring validation'), { code: 'FIXTURE_PREFLIGHT_COMPLETE' });
+ });
+ production.__setProductionDepsForTests({ loadEnv });
+ doubles.createProject.mockImplementation(async (input) => {
+ const project = buildProjectRecord(input, { id: 'mv-auto', now: '2026-01-01T00:00:00.000Z' });
+ store.set(project.id, clone(project));
+ return project;
+ });
+ doubles.startProduction.mockImplementation(production.startProduction);
+ doubles.resolveLlm.mockResolvedValue({ route: authoring });
+ try {
+ await service.startAutonomousVideo({ prompt: 'An authored world', mediaMode, models: { 'image:local': 'fixture-image' }, ...(explicit ? { authoring } : {}) });
+ await settled('failed');
+ expect(store.get('mv-auto')).toMatchObject({ composition: { mode: 'document' }, productionPolicy: { strategy: 'code-first' } });
+ expect(resolve).toHaveBeenCalledWith(authoring);
+ expect(loadEnv).toHaveBeenCalledOnce();
+ expect(runOf().errorCode).toBe(mediaMode === 'code-images' ? 'PRODUCTION_MEDIUM_CONFLICT' : 'FIXTURE_PREFLIGHT_COMPLETE');
+ if (mediaMode === 'code-images') {
+ expect(isVideoModeUsable).not.toHaveBeenCalled();
+ expect(doubles.startProduction.mock.calls[0][1].pool).toEqual([{ kind: 'image', mode: 'local', model: 'fixture-image' }]);
+ expect(runOf().brief.tools).toEqual(['image:local', 'video:local']);
+ }
+ } finally {
+ resolve.mockRestore();
+ production.__setProductionDepsForTests({});
+ }
+ });
+
it('finishes — and starts the final render — when the delegated production run completes', async () => {
await service.startAutonomousVideo({ prompt: 'p' });
await vi.waitFor(() => expect(runOf()?.output.productionRunId).toBe('mvpr-1'));
@@ -145,8 +192,10 @@ describe('startAutonomousVideo', () => {
await settled('running').catch(() => {});
await vi.waitFor(() => expect(calls).toContain('render'));
expect(calls).not.toContain('production');
- expect(doubles.generateCode).toHaveBeenCalledWith('mv-auto', { providerId: 'prov', model: 'm' });
- expect(store.get('mv-auto').composition).toEqual({ mode: 'code' });
+ expect(calls).not.toContain('board');
+ expect(doubles.acceptDocument).toHaveBeenCalledWith('mv-auto', 'music-video/mv-auto/composition/example');
+ expect(doubles.generateDocument).toHaveBeenCalledWith('mv-auto', { providerId: 'prov', model: 'm' });
+ expect(store.get('mv-auto').composition).toMatchObject({ mode: 'document', authoringRenderer: 'three' });
await settled('completed');
});
@@ -175,7 +224,7 @@ describe('startAutonomousVideo', () => {
it('threads the authoring effort into code generation for a code-only brief', async () => {
await service.startAutonomousVideo({ prompt: 'p', tools: ['code:render'], authoring: { providerId: 'prov', model: 'm', effort: 'medium' } });
await vi.waitFor(() => expect(calls).toContain('render'));
- expect(doubles.generateCode).toHaveBeenCalledWith('mv-auto', { providerId: 'prov', model: 'm', effort: 'medium' });
+ expect(doubles.generateDocument).toHaveBeenCalledWith('mv-auto', { providerId: 'prov', model: 'm', effort: 'medium' });
});
it('sends the Cast & Sets check-in to review only when the cast checkpoint is chosen', async () => {
@@ -458,10 +507,7 @@ it('parks standalone code at real human gates and replaces a stale proof before
} },
});
});
- doubles.generateCode.mockImplementation(async () => {
- const project = store.get('mv-auto');
- project.composition.codeVideo = { sections: [{ id: 'chorus', source: 'function render() {}' }] };
- });
+ doubles.generateDocument.mockResolvedValue({ document: { directory: 'music-video/mv-auto/composition/example' } });
renderProductionProof.mockImplementation(async (_id, window) => {
const project = store.get('mv-auto');
const id = `proof-${++proofNumber}`;
@@ -472,17 +518,20 @@ it('parks standalone code at real human gates and replaces a stale proof before
});
const approve = stage => {
const project = store.get('mv-auto');
- store.set(project.id, approveProductionStage(project, { stage, basis: productionReviewBasis(project)[stage] }));
+ const excerpt = project.excerpts?.find(e => e.id === project.productionReview?.proof?.excerptId);
+ store.set(project.id, approveProductionStage(project, { stage, basis: productionReviewBasis(project)[stage],
+ proofReview: stage === 'proof' ? { watchedWithAudio: true, excerptId: excerpt.id, filename: excerpt.filename,
+ energyComparison: 'Human fixture reviewed the intended energy.', timecodedNotes: '0:04 the chorus action lands.' } : undefined }));
};
await service.startAutonomousVideo({ prompt: 'Synthetic animation', tools: ['code:render'], authoring: { providerId: 'example', model: 'example-code' } });
await settled('needs-human');
- expect(doubles.generateCode).not.toHaveBeenCalled();
+ expect(doubles.generateDocument).not.toHaveBeenCalled();
expect(doubles.renderVideo).not.toHaveBeenCalled();
approve('art');
approve('storyboard');
await service.resumeAutonomousVideo('mv-auto');
await settled('needs-human');
- expect(doubles.generateCode).toHaveBeenCalledOnce();
+ expect(doubles.generateDocument).toHaveBeenCalledOnce();
expect(renderProductionProof).toHaveBeenCalledOnce();
expect(renderProductionProof).toHaveBeenLastCalledWith('mv-auto', { startSec: 0, endSec: 20 });
expect(doubles.renderVideo).not.toHaveBeenCalled();
@@ -500,7 +549,7 @@ it('parks standalone code at real human gates and replaces a stale proof before
expect(doubles.renderVideo).not.toHaveBeenCalled();
}
approve('proof');
- store.get('mv-auto').composition.codeVideo.sections[0].source = 'function render() { /* revision */ }';
+ store.get('mv-auto').composition.document.directory = 'music-video/mv-auto/composition/revised';
await service.resumeAutonomousVideo('mv-auto');
await settled('needs-human');
expect(renderProductionProof).toHaveBeenCalledTimes(4);
@@ -509,6 +558,6 @@ it('parks standalone code at real human gates and replaces a stale proof before
await service.resumeAutonomousVideo('mv-auto');
await settled('completed');
expect(doubles.renderVideo).toHaveBeenCalledOnce();
- expect(doubles.generateCode).toHaveBeenCalledOnce();
+ expect(doubles.generateDocument).toHaveBeenCalledOnce();
expect(doubles.startProduction).not.toHaveBeenCalled();
});
diff --git a/server/services/musicVideo/castAndSetsDirection.js b/server/services/musicVideo/castAndSetsDirection.js
index bc9f9dca59..814c09488d 100644
--- a/server/services/musicVideo/castAndSetsDirection.js
+++ b/server/services/musicVideo/castAndSetsDirection.js
@@ -1,3 +1,4 @@
+import { musicVideoAllowsMedia } from '../../lib/musicVideoMediaPolicy.js';
/**
* Music Video — Cast & Sets creative direction (pure): the LLM prompt, the
* response parser and the absent-vs-empty merge.
@@ -63,6 +64,7 @@ const MOOD_ITEM_TEXT = 280;
* read together because either can be saved without the other.
*/
export function castAndSetsMedium(project) {
+ if (!musicVideoAllowsMedia(project, 'image')) return 'procedural';
if (project?.productionPolicy?.strategy === 'code-first') return 'procedural';
const tools = briefTools(project);
return tools.some((t) => t.startsWith('code:')) && !tools.some((t) => t.startsWith('video:')) ? 'procedural' : 'photographic';
@@ -70,6 +72,7 @@ export function castAndSetsMedium(project) {
/** False when the brief names tools and none of them makes images (a code-only project). */
export function castAndSetsAllowsImages(project) {
+ if (!musicVideoAllowsMedia(project, 'image')) return false;
const tools = briefTools(project);
return tools.length === 0 || tools.some((t) => t.startsWith('image:'));
}
diff --git a/server/services/musicVideo/castAndSetsService.js b/server/services/musicVideo/castAndSetsService.js
index 820833801e..006e238bcf 100644
--- a/server/services/musicVideo/castAndSetsService.js
+++ b/server/services/musicVideo/castAndSetsService.js
@@ -1,3 +1,4 @@
+import { musicVideoAllowsMedia, assertMusicVideoMediaSelections } from '../../lib/musicVideoMediaPolicy.js';
import { productionFeedbackContext } from './productionReview.js';
import { withMusicVideoStyle } from './styleReferences.js';
/**
@@ -151,6 +152,7 @@ async function chooseCastAndSetsRoute(project, { preferred = null, settings } =
// ---- direction ------------------------------------------------------------------
async function loadContext(project) {
+ assertMusicVideoMediaSelections(project);
const boardId = project?.visualSpec?.moodBoardId;
const board = boardId ? await deps.loadBoard(boardId).catch(() => null) : null;
const resolveItem = board ? await deps.boardItemImage() : null;
@@ -208,7 +210,7 @@ async function writePlan(projectId, { direction = null, moodImages = null, force
const nextDirection = direction || stage.direction;
// A procedural project whose brief names no image tool is code-only: nothing
// is rendered, so no image backend is needed (or consulted).
- const codeOnly = nextDirection.medium === 'procedural' && !castAndSetsAllowsImages(project);
+ const codeOnly = !musicVideoAllowsMedia(project, 'image') || nextDirection.medium === 'procedural' && !castAndSetsAllowsImages(project);
const plan = codeOnly ? {} : buildCastAndSetsImagePlan(project, nextDirection, { revisionNotes: keyNotesText(stage.keyNotes) });
const renderKeys = affectedImageKeys(stage.plan || {}, plan, forceKeys);
const settings = await deps.getSettings();
@@ -527,6 +529,7 @@ function applyApproval(project, now) {
},
concept: { ...(project.concept || {}), subjects: castAndSetsSubjects(project, stage) },
};
+ assertMusicVideoMediaSelections(next);
if (stage.artifactId && (next.devArtifacts || []).some((a) => a.id === stage.artifactId && !a.deleted)) {
next = reviewDevArtifact(next, stage.artifactId, { status: 'approved' }, now).project;
}
diff --git a/server/services/musicVideo/castAndSetsService.test.js b/server/services/musicVideo/castAndSetsService.test.js
index cdb8a718c1..b148f2541a 100644
--- a/server/services/musicVideo/castAndSetsService.test.js
+++ b/server/services/musicVideo/castAndSetsService.test.js
@@ -475,6 +475,21 @@ it('ignores a previous revision completion while regeneration has reserved a key
expect((await current(project.id)).castAndSets.images.character.imageId).not.toBe(`${previous.id}.png`);
});
+it('preserves a retained image guide but refuses to activate its references after narrowing to code-only', async () => {
+ const project = await seed({ mediaMode: 'code-images', visualSpec: null, productionPolicy: { strategy: 'legacy' } });
+ await service.startCastAndSets(project.id);
+ await runTo(project.id, 'review');
+ const before = await current(project.id);
+ expect(before.castAndSets.images.character.imageId).toBeTruthy();
+ await projects.updateProject(project.id, { mediaMode: 'code-only' });
+ await expect(service.approveCastAndSets(project.id)).rejects.toMatchObject({ code: 'MUSIC_VIDEO_MEDIA_POLICY' });
+ const after = await current(project.id);
+ expect(after.visualSpec).toBeNull();
+ expect(after.castAndSets.status).toBe('review');
+ expect(after.castAndSets.images).toEqual(before.castAndSets.images);
+ expect(after.devArtifacts).toEqual(before.devArtifacts);
+});
+
describe('Cast & Sets procedural check-in', () => {
const PROCEDURAL = {
logline: 'A paper boat crosses a neon city.',
@@ -550,7 +565,7 @@ describe('Cast & Sets procedural check-in', () => {
runPrompt, getSettings: async () => ({}), enqueue, resolveRoute,
loadBoard: async () => null, loadTrack: async () => null,
});
- const project = await seedProcedural(['code:render']);
+ const project = await seed({ visualSpec: null, productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 }, automation: { tools: ['code:render'], checkins: { castAndSets: 'review' } } });
await service.startCastAndSets(project.id);
await until(async () => (await current(project.id)).castAndSets?.status === 'review', 'the code-only check-in');
const stage = (await current(project.id)).castAndSets;
diff --git a/server/services/musicVideo/codeGeneration.test.js b/server/services/musicVideo/codeGeneration.test.js
index ae46fd484a..3be1e54b72 100644
--- a/server/services/musicVideo/codeGeneration.test.js
+++ b/server/services/musicVideo/codeGeneration.test.js
@@ -116,12 +116,14 @@ describe('music video code generation (#9076)', () => {
const response = () => JSON.stringify({ sections: [{ id: 'a', source: fixtureSectionSource('#555555') }, { id: 'b', source: fixtureSectionSource('#666666') }] });
it('sends the approved definitions and motion/camera rules with both the full and the one-section request', async () => {
- h.project = { ...base(), castAndSets: { status: 'approved', direction: direction() } };
+ h.project = { ...base(), productionReview: { draft: { motionLanguage: 'Energy: playful. 0–1s unfold on the downbeat; 1–2s expand the chorus gesture.', implementationPlan: 'Hinge the paper limbs; arc the camera analytically.' } }, castAndSets: { status: 'approved', direction: direction() } };
h.response = response();
await generateMusicVideoCode('mv-code', { providerId: 'stub-provider' });
await regenerateMusicVideoCodeSection('mv-code', 'a', { providerId: 'stub-provider' });
expect(h.prompts).toHaveLength(2);
for (const prompt of h.prompts) {
+ expect(prompt).toContain(h.project.productionReview.draft.motionLanguage);
+ expect(prompt).toContain(h.project.productionReview.draft.implementationPlan);
expect(prompt).toContain('APPROVED CAST & SETS DEFINITIONS AND RULES');
expect(prompt).toContain('camera: slow dolly with a beat-synced push');
expect(prompt).toContain('movement: bobs on every beat');
diff --git a/server/services/musicVideo/codeTimeline.js b/server/services/musicVideo/codeTimeline.js
index 80b8a4cc0b..63b304fa89 100644
--- a/server/services/musicVideo/codeTimeline.js
+++ b/server/services/musicVideo/codeTimeline.js
@@ -11,6 +11,7 @@
*/
import { CODE_FPS } from './codeFrame.js';
+import { musicVideoSongFeaturesSchema } from '../../lib/musicVideoValidation.js';
const round3 = (n) => Math.round(n * 1000) / 1000;
@@ -222,6 +223,7 @@ export function buildCodeTimeline(project, { fps = CODE_FPS } = {}) {
/** The song.json document the composition seeks. Words fall back to the line. */
export function buildSongDocument(project, timeline = buildCodeTimeline(project)) {
const quantized = quantizeSongDuration(timeline.durationSec, timeline.fps);
+ const features = musicVideoSongFeaturesSchema.safeParse(project.audioAnalysis?.features);
const lines = lyricLines(project).map((line) => ({
id: typeof line.id === 'string' ? line.id : null,
text: line.text,
@@ -248,6 +250,7 @@ export function buildSongDocument(project, timeline = buildCodeTimeline(project)
fps: timeline.fps,
beats: timeline.beats,
downbeats: timeline.downbeats,
+ features: features.success ? features.data : null,
sections,
lyrics: lines,
};
diff --git a/server/services/musicVideo/composition.js b/server/services/musicVideo/composition.js
index 49dab4987b..da461d1e82 100644
--- a/server/services/musicVideo/composition.js
+++ b/server/services/musicVideo/composition.js
@@ -152,6 +152,7 @@ export function normalizeComposition(input) {
return {
version: COMPOSITION_VERSION,
mode: pick(input.mode, COMPOSITION_MODES, 'concat'),
+ ...(['canvas', 'three'].includes(input.authoringRenderer) ? { authoringRenderer: input.authoringRenderer } : {}),
textCues,
style: {
color: typeof style.color === 'string' && /^#[0-9a-f]{6}$/i.test(style.color) ? style.color.toLowerCase() : '#ffffff',
diff --git a/server/services/musicVideo/compositionDocument.js b/server/services/musicVideo/compositionDocument.js
index 10b2ab3e42..be7b189801 100644
--- a/server/services/musicVideo/compositionDocument.js
+++ b/server/services/musicVideo/compositionDocument.js
@@ -1,3 +1,6 @@
+import { createRequire } from 'node:module';
+import { createHash } from 'node:crypto';
+import { assertDocumentMediaPolicy } from './documentMediaPolicy.js';
/**
* Music Video — project composition documents (files on disk).
*
@@ -141,7 +144,9 @@ function storeVersion(projectId, files, source, options = {}) {
async function storeVersionNow(projectId, files, source, { draft = false, verifyCurrent = () => {} } = {}) {
assertDocumentShape(files.map((file) => file.rel));
- if (!(await getProject(projectId))) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ const initial = await getProject(projectId);
+ await assertDocumentMediaPolicy(initial, files);
+ if (!initial) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
const versionId = `doc-${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`;
const root = projectDocumentRoot(projectId);
const staging = join(root, `.${versionId}.partial`);
@@ -173,6 +178,7 @@ async function storeVersionNow(projectId, files, source, { draft = false, verify
try {
outcome = await mutateProjectRecord(projectId, (current) => {
verifyCurrent(current);
+ if (current.mediaMode !== initial.mediaMode) throw refuse('Media mode changed during import', 'COMPOSITION_DRAFT_STALE', 409);
const composition = normalizeComposition({ ...(current.composition || {}), ...(!draft ? { mode: 'document' } : {}) });
const project = { ...current, composition: { ...composition, [draft ? 'documentDraft' : 'document']: document }, updatedAt: document.updatedAt };
return { project };
@@ -282,7 +288,24 @@ export async function importDocumentTemplate(projectId, templateId = 'layered')
}
/** Stage a host-assembled generated document for review before selection. */
-export async function stageGeneratedDocument(projectId, generatedFiles, { verifyCurrent } = {}) {
+export async function stageGeneratedDocument(projectId, generatedFiles, { verifyCurrent, renderer = 'canvas' } = {}) {
+ if (renderer === 'three') {
+ const { files } = await collectTree(join(TEMPLATE_ROOT, 'spatial'));
+ const fonts = await collectTree(join(TEMPLATE_ROOT, 'layered', 'fonts'));
+ const require = createRequire(new URL('../../../client/package.json', import.meta.url));
+ const packageRoot = dirname(dirname(require.resolve('three')));
+ const pkg = JSON.parse(await readFile(join(packageRoot, 'package.json'), 'utf8'));
+ const dependencies = [];
+ for (const name of ['build/three.module.js', 'build/three.core.js', 'LICENSE']) {
+ const data = await readFile(join(packageRoot, name));
+ const rel = `vendor/${name.split('/').pop()}`;
+ files.push({ rel, data });
+ dependencies.push({ path: rel, sha256: createHash('sha256').update(data).digest('hex') });
+ }
+ files.push(...fonts.files.map((file) => ({ ...file, rel: `fonts/${file.rel}` })), ...generatedFiles,
+ { rel: 'dependencies.json', data: Buffer.from(JSON.stringify({ packages: [{ name: 'three', version: pkg.version, files: dependencies }], network: false })) });
+ return storeVersion(projectId, files, { kind: 'generated', name: 'Authored Three.js world' }, { draft: true, verifyCurrent });
+ }
const { files } = await collectTree(join(TEMPLATE_ROOT, 'layered'));
const index = await readFile(join(TEMPLATE_ROOT, 'layered', 'index.html'), 'utf8');
const marker = '<script src="engine.js"></script>';
@@ -387,6 +410,7 @@ export function detachDocument(projectId) {
/** The document folder a render stages; throws COMPOSITION_DOCUMENT_MISSING. */
export async function documentDirectoryForRender(project) {
+ await readDocumentFiles(project);
const dir = await requireDocument(project);
return relative(PATHS.data, dir).split(sep).join('/');
}
@@ -395,6 +419,7 @@ export async function documentDirectoryForRender(project) {
export async function readDocumentFiles(project) {
const dir = await requireDocument(project);
const { files } = await collectTree(dir);
+ await assertDocumentMediaPolicy(project, files);
const out = new Map();
for (const file of files) out.set(file.rel, { abs: file.abs, size: file.size });
return out;
diff --git a/server/services/musicVideo/devArtifactService.js b/server/services/musicVideo/devArtifactService.js
index 1ea4aa9e1a..db95dfbb1e 100644
--- a/server/services/musicVideo/devArtifactService.js
+++ b/server/services/musicVideo/devArtifactService.js
@@ -1,3 +1,5 @@
+import { assertDocumentMediaPolicy } from './documentMediaPolicy.js';
+import { musicVideoMediaMode } from '../../lib/musicVideoMediaPolicy.js';
/**
* Music Video — development artifact workflow: import/upload, generated saves,
* notes, review and soft delete over the pure transforms in devArtifacts.js
@@ -60,6 +62,7 @@ async function storeVersion(projectId, {
const mimeType = devArtifactTypeFor(ext);
if (!mimeType) throw new ServerError('Unsupported file type — accepted: HTML, Markdown, MP4, PNG, JPG', { status: 400, code: 'VALIDATION_ERROR' });
const project = await requireProject(projectId);
+ await assertDocumentMediaPolicy(project, [{ rel: `guide.${ext}`, data: buffer, abs: tempPath }]);
if (artifactId) findDevArtifact(project, artifactId);
const id = artifactId || newDevArtifactId();
const version = nextDevArtifactVersion(project, artifactId);
@@ -67,6 +70,9 @@ async function storeVersion(projectId, {
projectId, artifactId: id, version, ext: ext === 'jpeg' ? 'jpg' : ext, buffer, tempPath,
});
const out = await mutateProjectRecord(projectId, (current) => {
+ if (musicVideoMediaMode(current) !== musicVideoMediaMode(project)) {
+ throw new ServerError('Media mode changed during the artifact upload — try again', { status: 409, code: 'DEV_ARTIFACT_CONFLICT' });
+ }
// A concurrent write took this version number: refuse rather than point
// two versions at one file.
if (nextDevArtifactVersion(current, artifactId) !== version) {
diff --git a/server/services/musicVideo/documentGeneration.js b/server/services/musicVideo/documentGeneration.js
index f61d85ad02..09508dbad5 100644
--- a/server/services/musicVideo/documentGeneration.js
+++ b/server/services/musicVideo/documentGeneration.js
@@ -1,3 +1,4 @@
+import { musicVideoMediaMode, musicVideoDocumentRenderer, assertMusicVideoMediaSelections } from '../../lib/musicVideoMediaPolicy.js';
import { assertProductionApproval } from './productionReview.js';
/** User-triggered mixed-media document authoring. No provider runs on read or boot. */
import { createHash } from 'node:crypto';
@@ -29,6 +30,52 @@ function hasUnsafeReference(node) {
return Object.entries(node).some(([key, value]) => key !== 'loc' && key !== 'start' && key !== 'end' && hasUnsafeReference(value));
}
+// Three's convenience random functions hide Math.random or module-level RNG
+// state behind the namespace we supply. Track only that namespace and its
+// static aliases, so unrelated local methods with these names remain usable.
+function hasAmbientThreeRandom(fn) {
+ const random = new Set(['randInt', 'randFloat', 'randFloatSpread', 'seededRandom', 'generateUUID']);
+ const aliases = new Map([['ctx', new Set(['context'])]]);
+ const nodes = [];
+ const visit = (node) => {
+ if (!node || typeof node !== 'object') return;
+ if (Array.isArray(node)) { node.forEach(visit); return; }
+ if (node.type) nodes.push(node);
+ for (const [key, value] of Object.entries(node)) if (!['loc', 'start', 'end'].includes(key)) visit(value);
+ };
+ visit(fn.body);
+ const property = (node) => node.computed ? node.property?.value : node.property?.name;
+ const member = (kind, key) => kind === 'context' && key === 'THREE' ? 'three'
+ : kind === 'three' && key === 'MathUtils' ? 'math'
+ : kind === 'math' && random.has(key) ? 'random' : null;
+ const resolve = (node) => {
+ if (node?.type === 'Identifier') return aliases.get(node.name) || new Set();
+ if (['MemberExpression', 'OptionalMemberExpression'].includes(node?.type)) {
+ return new Set([...resolve(node.object)].map(kind => member(kind, property(node))).filter(Boolean));
+ }
+ return new Set();
+ };
+ const bind = (pattern, kinds) => {
+ if (pattern?.type === 'Identifier') {
+ const current = aliases.get(pattern.name) || new Set();
+ for (const kind of kinds) current.add(kind);
+ aliases.set(pattern.name, current);
+ } else if (pattern?.type === 'ObjectPattern') {
+ for (const field of pattern.properties) {
+ if (field.type !== 'ObjectProperty') continue;
+ const key = field.computed ? field.key.value : field.key.name || field.key.value;
+ bind(field.value, new Set([...kinds].map(kind => member(kind, key)).filter(Boolean)));
+ }
+ }
+ };
+ const bindings = nodes.filter(node => node.type === 'VariableDeclarator' || node.type === 'AssignmentExpression' && node.operator === '=');
+ // A bounded fixed point also covers aliases assigned after their declaration.
+ for (let pass = 0; pass <= bindings.length; pass++) {
+ for (const node of bindings) bind(node.id || node.left, resolve(node.init || node.right));
+ }
+ return nodes.some(node => resolve(node).has('random'));
+}
+
// Only an exact function declaration is embedded as a literal in generated.js.
// In particular, no model-supplied top-level statement ever runs in the page.
function checkedFunction(source) {
@@ -41,6 +88,7 @@ function checkedFunction(source) {
|| fn.params.length !== 2 || fn.params[0]?.name !== 'ctx' || fn.params[1]?.name !== 'env') {
throw fail('Return exactly function render(ctx, env) for each section', 'INVALID_SECTION_SOURCE');
}
+ if (hasAmbientThreeRandom(fn)) throw fail('Three.js MathUtils random helpers depend on ambient state. Use deterministic arithmetic from env.t or env.frame instead.', 'NONDETERMINISTIC_SECTION');
if (hasUnsafeReference(fn.body)) throw fail('A section must use only its drawing context and song-time inputs', 'NONDETERMINISTIC_SECTION');
return source;
}
@@ -49,6 +97,8 @@ function basisFor(project, includeEvents = true) {
// These are all inputs that can change which pixels or authoring directions
// a section means. A new candidate cannot publish across such an edit.
const input = {
+ mediaMode: musicVideoMediaMode(project),
+ authoringRenderer: musicVideoDocumentRenderer(project),
name: project.name || null,
productionDraft: project.productionReview?.draft || null,
treatment: project.treatment || null,
@@ -95,6 +145,8 @@ function affectedEventSections(before, after) {
}
async function authoringContext(project) {
+ assertMusicVideoMediaSelections(project);
+ if (musicVideoDocumentRenderer(project) === 'three' && (project.scenes || []).some((scene) => scene.referenceImageId || scene.videoHistoryId)) throw fail('Generated Three.js worlds currently use geometry only. Use Canvas or import a document to compose selected media.', 'COMPOSITION_RENDERER_MEDIA_UNSUPPORTED');
const plan = summarizeMusicVideoMediumPlan(project);
if (plan.strategy === 'code-first' && plan.blocked) {
throw fail(plan.unresolved.filter((item) => item.blocking).map((item) => item.message).join(' '), 'COMPOSITION_MEDIUM_PLAN_INCOMPLETE');
@@ -192,6 +244,7 @@ async function runAuthoring(projectId, { providerId, model, effort, sectionId =
styleLines: await styleLinesFor(project),
};
const prompt = buildMixedMediaDocumentPrompt({
+ renderer: musicVideoDocumentRenderer(project), mediaMode: musicVideoMediaMode(project),
title: project.name, song: { ...context.song, sections: context.song.sections.filter((section) => ids.includes(section.id)) }, palette: context.palette, treatment: project.treatment,
visualSpec: project.visualSpec, scenes: context.scenes, styleLines: sharedStyle.styleLines,
onlySectionId: sectionId, sharedStyle, directionContext: castAndSetsCodeContext(project),
@@ -208,7 +261,7 @@ async function runAuthoring(projectId, { providerId, model, effort, sectionId =
const merged = new Map((prior?.manifest.sections || []).map((section) => [section.id, section.source]));
for (const [id, source] of updated) merged.set(id, source);
const manifest = {
- version: 1, basis: context.basis, structuralBasis: context.structuralBasis, baseDocumentDirectory: project.composition?.document?.directory || null,
+ version: 1, renderer: musicVideoDocumentRenderer(project), mediaMode: musicVideoMediaMode(project), basis: context.basis, structuralBasis: context.structuralBasis, baseDocumentDirectory: project.composition?.document?.directory || null,
changedSectionIds: [...new Set([...((prior && project.composition?.documentDraft) ? prior.manifest.changedSectionIds || [] : []), ...ids])],
beforeSong: prior ? (project.composition?.documentDraft ? prior.manifest.beforeSong || prior.manifest.song : prior.manifest.song) : null,
sharedStyle, song: context.song, palette: context.palette,
@@ -219,6 +272,7 @@ async function runAuthoring(projectId, { providerId, model, effort, sectionId =
const active = project.composition?.document?.directory || null;
const draft = project.composition?.documentDraft?.directory || null;
const result = await stageGeneratedDocument(projectId, generatedFiles(manifest), {
+ renderer: manifest.renderer,
verifyCurrent: (current) => {
assertProductionApproval(current, 'storyboard');
verifyCurrent(current);
diff --git a/server/services/musicVideo/documentGeneration.test.js b/server/services/musicVideo/documentGeneration.test.js
index 801972666c..5b87617268 100644
--- a/server/services/musicVideo/documentGeneration.test.js
+++ b/server/services/musicVideo/documentGeneration.test.js
@@ -179,11 +179,16 @@ describe('treatment-driven mixed-media document authoring', () => {
it('revises one section, preserves the other functions, and refuses a stale acceptance', async () => {
const id = await fixture();
+ const motionLanguage = 'Energy: playful. 0–10s unfold on downbeats; 20–30s expand the chorus gesture.';
+ await projects.mutateProjectRecord(id, current => ({ project: { ...current, productionReview: { draft: { motionLanguage, implementationPlan: 'Hinged paper rig and analytic camera arc.' } } } }));
const first = (await generateMixedMediaDocument(id)).document;
+ expect(h.prompt).toContain(motionLanguage);
const before = await manifestAt(first);
h.response = response({ still: '#00ff00' });
const second = (await regenerateMixedMediaSection(id, 'still', { expectedDraft: first.directory })).document;
const after = await manifestAt(second);
+ expect(h.prompt).toContain(motionLanguage);
+ expect(h.prompt).toContain('Hinged paper rig and analytic camera arc.');
expect(after.sections.map((s) => s.source)).toEqual([before.sections[0].source, source('#00ff00'), before.sections[2].source]);
await expect(regenerateMixedMediaSection(id, 'still', { expectedDraft: first.directory })).rejects.toMatchObject({ code: 'COMPOSITION_DRAFT_STALE' });
await projects.mutateProjectRecord(id, (current) => ({ project: {
@@ -251,3 +256,35 @@ it('refuses a changed production draft after provider preparation and before pai
await expect(generateMixedMediaDocument(id)).rejects.toMatchObject({ code: 'COMPOSITION_DRAFT_STALE' });
expect(h.calls).toBe(0);
});
+
+it('refuses ambient Three.js random helpers and their aliases while allowing deterministic local helpers', async () => {
+ const created = await projects.createProject({ name: 'Example deterministic world', mediaMode: 'code-only' });
+ await projects.mutateProjectRecord(created.id, current => ({ project: { ...current,
+ audioAnalysis: { durationSec: 1, beats: [], downbeats: [], sections: [{ id: 'world', startSec: 0, endSec: 1 }] },
+ composition: { mode: 'document', authoringRenderer: 'three' },
+ } }));
+ // Library helpers hide the ambient RNG from the existing Math.random guard;
+ // namespace aliases and destructured calls must not bypass admission either.
+ const bodies = [
+ 'ctx.THREE.MathUtils.randFloat(0, 1)',
+ 'ctx.THREE.MathUtils.randInt(0, 10)',
+ 'ctx.THREE.MathUtils.randFloatSpread(10)',
+ 'ctx.THREE.MathUtils.seededRandom()',
+ 'ctx.THREE.MathUtils.generateUUID()',
+ 'const { THREE } = ctx; const utils = THREE.MathUtils; utils["randFloat"](0, 1)',
+ 'const { MathUtils: { seededRandom: sample } } = ctx.THREE; sample()',
+ 'let utils; utils = ctx.THREE.MathUtils; const { randInt: sample } = utils; sample(0, 10)',
+ ];
+ for (const body of bodies) {
+ h.response = JSON.stringify({ sections: [{ id: 'world', source: `function render(ctx, env) { ${body}; }` }] });
+ await expect(generateMixedMediaDocument(created.id), body).rejects.toMatchObject({ code: 'NONDETERMINISTIC_SECTION' });
+ expect((await projects.getProject(created.id)).composition.documentDraft).toBeUndefined();
+ }
+ h.response = JSON.stringify({ sections: [{ id: 'world', source: `function render(ctx, env) {
+ const local = { randFloat: (seed) => (Math.sin(seed * 123.45) + 1) / 2 };
+ const { THREE } = ctx;
+ ctx.scene.background = new THREE.Color(local.randFloat(env.frame), 0.5, 0.2);
+ }` }] });
+ const candidate = await generateMixedMediaDocument(created.id);
+ expect((await manifestAt(candidate.document)).renderer).toBe('three');
+});
diff --git a/server/services/musicVideo/documentMediaPolicy.js b/server/services/musicVideo/documentMediaPolicy.js
new file mode 100644
index 0000000000..337df97e0f
--- /dev/null
+++ b/server/services/musicVideo/documentMediaPolicy.js
@@ -0,0 +1,40 @@
+/** Import and render admission, before any imported code executes. */
+import { readFile } from 'node:fs/promises';
+import { extname } from 'node:path';
+import { parse } from '@babel/parser';
+import { assertMusicVideoMedia, musicVideoMediaMode } from '../../lib/musicVideoMediaPolicy.js';
+const IMAGES = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif', '.avif', '.bmp', '.svg', '.ico']);
+const VIDEO = new Set(['.mp4', '.mov', '.webm', '.mkv', '.avi']);
+const SOURCE = new Set(['.html', '.js', '.mjs', '.css', '.json', '.txt', '.md']);
+const FONTS = new Set(['.woff', '.woff2', '.ttf', '.otf']);
+export async function assertDocumentMediaPolicy(project, files) {
+ if (musicVideoMediaMode(project) === 'code-images-video') return;
+ for (const file of files) {
+ const ext = extname(file.rel).toLowerCase();
+ const bytes = file.data || await readFile(file.abs);
+ const signature = bytes.subarray(0, 16);
+ if (signature.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))
+ || signature.subarray(0, 3).equals(Buffer.from([255, 216, 255]))
+ || /^GIF8[79]a/.test(signature.toString('ascii'))
+ || signature.toString('ascii', 8, 12) === 'WEBP') assertMusicVideoMedia(project, 'image', 'document asset');
+ if (signature.toString('ascii', 4, 8) === 'ftyp') {
+ const kind = ['avif', 'avis'].includes(signature.toString('ascii', 8, 12)) ? 'image' : 'video';
+ assertMusicVideoMedia(project, kind, 'document asset');
+ }
+ if (signature.subarray(0, 4).equals(Buffer.from([26, 69, 223, 163]))) assertMusicVideoMedia(project, 'video', 'document asset');
+ if (IMAGES.has(ext)) assertMusicVideoMedia(project, 'image', 'document asset');
+ if (VIDEO.has(ext)) assertMusicVideoMedia(project, 'video', 'document asset');
+ // Unknown binary assets cannot hide renamed photos or clips in code-only packages.
+ if (!/^(?:.*\/)?LICENSE[^/]*$/i.test(file.rel) && !SOURCE.has(ext) && !FONTS.has(ext) && !IMAGES.has(ext)) assertMusicVideoMedia(project, 'video', 'binary document asset');
+ if (SOURCE.has(ext)) {
+ let source = bytes.toString('utf8');
+ if (ext === '.js' || ext === '.mjs') {
+ // Inspect executable text and string literals, not inert JSDoc such as Array<Image>.
+ const { comments } = parse(source, { sourceType: 'unambiguous' });
+ for (const comment of comments.slice().reverse()) source = source.slice(0, comment.start) + ' ' + source.slice(comment.end);
+ }
+ if (/data\s*:\s*image\/|<(?:img|image)\b|!\[[^\]]*\]\(/i.test(source)) assertMusicVideoMedia(project, 'image', 'embedded document asset');
+ if (/data\s*:\s*(?:video|audio)\/|<(?:video|audio)\b/i.test(source)) assertMusicVideoMedia(project, 'video', 'embedded document asset');
+ }
+ }
+}
diff --git a/server/services/musicVideo/documentModules.js b/server/services/musicVideo/documentModules.js
new file mode 100644
index 0000000000..831f306cde
--- /dev/null
+++ b/server/services/musicVideo/documentModules.js
@@ -0,0 +1,30 @@
+/** Resolve a document's local ES module graph for the opaque preview iframe. */
+import { readFile } from 'node:fs/promises';
+import { posix } from 'node:path';
+import { parse } from '@babel/parser';
+import { ServerError } from '../../lib/errorHandler.js';
+
+export async function inlineDocumentModule(entry, files, stack = new Set(), cache = new Map()) {
+ if (cache.has(entry)) return cache.get(entry);
+ const file = files.get(entry);
+ if (!file || stack.has(entry) || stack.size >= 32) throw new ServerError('Preview modules must form an acyclic local document graph', { status: 422, code: 'COMPOSITION_MODULE_INVALID' });
+ const source = file.data ? file.data.toString('utf8') : await readFile(file.abs, 'utf8');
+ const ast = parse(source, { sourceType: 'module' });
+ const nextStack = new Set([...stack, entry]);
+ const replacements = [];
+ for (const node of ast.program.body) {
+ if (!node.source || !['ImportDeclaration', 'ExportNamedDeclaration', 'ExportAllDeclaration'].includes(node.type)) continue;
+ const ref = node.source.value;
+ if (!ref.startsWith('./') && !ref.startsWith('../')) throw new ServerError('Package modules must use local relative imports', { status: 422, code: 'COMPOSITION_MODULE_INVALID' });
+ const key = posix.normalize(posix.join(posix.dirname(entry), ref));
+ const url = await inlineDocumentModule(key, files, nextStack, cache);
+ replacements.push({ start: node.source.start, end: node.source.end, value: JSON.stringify(url) });
+ }
+ const expandedSize = replacements.reduce((size, item) => size + item.value.length - (item.end - item.start), source.length);
+ if (expandedSize > 24 * 1024 * 1024) throw new ServerError('The expanded module graph exceeds the preview budget', { status: 413, code: 'COMPOSITION_MODULE_TOO_LARGE' });
+ let output = source;
+ for (const item of replacements.sort((a, b) => b.start - a.start)) output = output.slice(0, item.start) + item.value + output.slice(item.end);
+ const url = `data:text/javascript;base64,${Buffer.from(output).toString('base64')}`;
+ cache.set(entry, url);
+ return url;
+}
diff --git a/server/services/musicVideo/documentPreview.js b/server/services/musicVideo/documentPreview.js
index e953abc7ee..ea1af80144 100644
--- a/server/services/musicVideo/documentPreview.js
+++ b/server/services/musicVideo/documentPreview.js
@@ -1,3 +1,5 @@
+import { inlineDocumentModule } from './documentModules.js';
+import { musicVideoMediaMode } from '../../lib/musicVideoMediaPolicy.js';
/**
* Music Video — the in-app live preview of a composition document.
*
@@ -35,7 +37,7 @@ const INLINE_TOTAL_MAX = 24 * 1024 * 1024;
const BRIDGED = new Set(['.mp4', '.mov', '.webm', '.mp3', '.wav', '.png', '.jpg', '.jpeg', '.webp', '.gif']);
export const PREVIEW_CSP = [
- "default-src 'none'", "script-src 'unsafe-inline'", "style-src 'unsafe-inline'",
+ "default-src 'none'", "script-src 'unsafe-inline' data:", "style-src 'unsafe-inline'",
'img-src data: blob:', 'media-src data: blob:', 'font-src data: blob:',
"connect-src 'none'", "form-action 'none'", "base-uri 'none'", "object-src 'none'",
"frame-src 'none'", "worker-src 'none'", "manifest-src 'none'",
@@ -52,6 +54,11 @@ const cleanRef = (ref) => {
// Runs before any document script: asset bridge, relative-src mapping, seek/layout messages.
const BOOTSTRAP = `(() => {
+ // CSP does not block ICE/STUN. Match the render host before document code runs.
+ for (const key of ['RTCPeerConnection', 'webkitRTCPeerConnection', 'WebTransport', 'Worker', 'SharedWorker', 'WebSocket']) {
+ Object.defineProperty(globalThis, key, { configurable: false, writable: false,
+ value: function() { throw new Error(key + ' is disabled in compositions'); } });
+ }
const map = new Map();
let resolved = false;
let resolveAssets;
@@ -160,7 +167,18 @@ export async function buildDocumentPreview(project, { draft = false } = {}) {
if (rel === 'portos-mv.js') { html = html.split(match[0]).join(''); continue; }
const file = files.get(rel);
if (!file) continue;
- html = html.split(match[0]).join(`<script${match[1]}${match[3]}>${inlineScript(await readFile(file.abs, 'utf8'))}</script>`);
+ const isModule = /type\s*=\s*['"]module['"]/i.test(match[1] + match[3]);
+ html = html.split(match[0]).join(isModule
+ ? `<script type="module">import ${JSON.stringify(await inlineDocumentModule(rel, files))};</script>`
+ : `<script${match[1]}${match[3]}>${inlineScript(await readFile(file.abs, 'utf8'))}</script>`);
+ }
+ // Inline entry modules need the same local graph resolution as src modules.
+ for (const [index, match] of [...html.matchAll(/<script\b[^>]*type\s*=\s*['"]module['"][^>]*>([\s\S]*?)<\/script>/gi)].entries()) {
+ if (/^import "data:text\/javascript;base64,/.test(match[1])) continue;
+ const entry = `__inline-${index}.js`;
+ const graph = new Map(files); graph.set(entry, { data: Buffer.from(match[1]) });
+ const url = await inlineDocumentModule(entry, graph);
+ html = html.split(match[0]).join(`<script type="module">import ${JSON.stringify(url)};</script>`);
}
// Inline <style> blocks and style="" attributes, then <img src>.
for (const match of [...html.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)]) {
@@ -172,7 +190,9 @@ export async function buildDocumentPreview(project, { draft = false } = {}) {
const url = rel ? await dataUrl(rel) : null;
if (url) html = html.split(match[0]).join(match[0].replace(match[1], () => `"${url}"`));
}
- const head = `<meta http-equiv="Content-Security-Policy" content="${PREVIEW_CSP}"><script>${BOOTSTRAP}</script><script>window.PORTOS_MV = ${scriptJson(data)};window.PORTOS_MV_EVENT_STATE = ${narrativeFrameState.toString()};</script>`;
+ const mode = musicVideoMediaMode(project);
+ const csp = PREVIEW_CSP.replace('img-src data: blob:', mode === 'code-only' ? "img-src 'none'" : 'img-src data: blob:').replace('media-src data: blob:', mode !== 'code-images-video' ? "media-src 'none'" : 'media-src data: blob:');
+ const head = `<meta http-equiv="Content-Security-Policy" content="${csp}"><script>${BOOTSTRAP}</script><script>window.PORTOS_MV = ${scriptJson(data)};window.PORTOS_MV_EVENT_STATE = ${narrativeFrameState.toString()};</script>`;
const at = html.match(/<head[^>]*>/i);
html = at ? `${html.slice(0, at.index + at[0].length)}${head}${html.slice(at.index + at[0].length)}` : `${head}${html}`;
diff --git a/server/services/musicVideo/documentRender.browser.test.js b/server/services/musicVideo/documentRender.browser.test.js
index 71115dc50e..ac85c1f7c1 100644
--- a/server/services/musicVideo/documentRender.browser.test.js
+++ b/server/services/musicVideo/documentRender.browser.test.js
@@ -1,3 +1,4 @@
+import { richSceneSource } from './__richSceneFixture.js';
/**
* The shipped layered template with real Chrome and ffmpeg: an excerpt of a
* composition-document project seeks the selected take's <video> on SONG time
@@ -44,13 +45,7 @@ vi.mock('../../lib/paths.js', async (importOriginal) => makePathsProxy(await imp
dataRoot: () => lazyTempDataRoot('portos-mv-document-browser-'),
}));
-const { PATHS } = await import('../../lib/paths.js');
const { findFfmpeg } = await import('../../lib/ffmpeg.js');
-const { encodeDocumentComposition, prepareDocumentRender, documentRenderClock } = await import('./documentRender.js');
-const { importDocumentTemplate } = await import('./compositionDocument.js');
-const { generateMixedMediaDocument, regenerateMixedMediaSection, acceptMixedMediaDocument } = await import('./documentGeneration.js');
-const { buildDocumentPreview } = await import('./documentPreview.js');
-const projects = await import('./projects.js');
const { _cleanupTestBrowser, _waitForTestChrome, _testChromeCaptureArgs } = await import('../htmlComposition/testBrowserCleanup.js');
afterAll(() => cleanupTempDataRoots());
@@ -60,11 +55,23 @@ const chrome = [process.env.CHROME_PATH, chromium.executablePath(),
'/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser',
].find((path) => path && existsSync(path));
const ffmpeg = await findFfmpeg();
+// Imported discovery helpers can initialize mocked paths even on a skip.
+const canRun = Boolean(chrome && ffmpeg);
+if (!canRun) cleanupTempDataRoots();
-describe.skipIf(!chrome || !ffmpeg)('layered template with real Chrome and ffmpeg', () => {
+describe.skipIf(!canRun)('layered template with real Chrome and ffmpeg', () => {
let proc;
let browser;
+ let PATHS, encodeDocumentComposition, prepareDocumentRender, documentRenderClock, importDocumentTemplate;
+ let generateMixedMediaDocument, regenerateMixedMediaSection, acceptMixedMediaDocument, buildDocumentPreview, projects;
beforeAll(async () => {
+ // Keep collection read-only when Chrome/ffmpeg prerequisites skip the suite.
+ ({ PATHS } = await import('../../lib/paths.js'));
+ ({ encodeDocumentComposition, prepareDocumentRender, documentRenderClock } = await import('./documentRender.js'));
+ ({ importDocumentTemplate } = await import('./compositionDocument.js'));
+ ({ generateMixedMediaDocument, regenerateMixedMediaSection, acceptMixedMediaDocument } = await import('./documentGeneration.js'));
+ ({ buildDocumentPreview } = await import('./documentPreview.js'));
+ projects = await import('./projects.js');
const profile = join(PATHS.data, 'chrome-test-profile');
proc = spawn(chrome, _testChromeCaptureArgs(profile), { stdio: ['ignore', 'ignore', 'pipe'] });
const ws = await _waitForTestChrome(proc);
@@ -73,6 +80,66 @@ describe.skipIf(!chrome || !ffmpeg)('layered template with real Chrome and ffmpe
}, 30000);
afterAll(() => _cleanupTestBrowser({ browser, proc, cleanup: () => {} }));
+ // Server-only CI does not install client dependencies; the full local install
+ // exercises this cross-workspace package/render contract alongside the UI proof.
+ it.skipIf(!existsSync(new URL('../../../client/node_modules/three/package.json', import.meta.url)))('authors a local Three.js world and renders the same deterministic scene through module preview and export', async () => {
+ const created = await projects.createProject({ name: 'Synthetic authored world', mediaMode: 'code-only' });
+ await projects.mutateProjectRecord(created.id, (current) => ({ project: { ...current,
+ audioAnalysis: { durationSec: 1, beats: [0, 0.5], downbeats: [0], sections: [{ id: 'world', label: 'World', startSec: 0, endSec: 1 }] },
+ lyricCues: [{ id: 'line', text: 'EXAMPLE LYRIC', startSec: 0, endSec: 1, words: [{ w: 'EXAMPLE', startSec: 0 }, { w: 'LYRIC', startSec: 0.5 }] }],
+ composition: { mode: 'document', authoringRenderer: 'three' },
+ } }));
+ author.response = JSON.stringify({ sections: [{ id: 'world', source: richSceneSource }] });
+ const candidate = await generateMixedMediaDocument(created.id, { providerId: 'stub-provider' });
+ await acceptMixedMediaDocument(created.id, candidate.document.directory);
+ author.response = null;
+ const project = await projects.getProject(created.id);
+ const preview = await buildDocumentPreview(project);
+ expect(preview.assets).toEqual([]);
+ expect(preview.html).toContain("img-src 'none'");
+ const page = await browser.newPage({ viewport: { width: 1920, height: 1080 } });
+ const errors = []; page.on('pageerror', (error) => errors.push(error.message));
+ await page.evaluate(() => {
+ const live = new Set();
+ const create = WebGL2RenderingContext.prototype.createTexture;
+ const remove = WebGL2RenderingContext.prototype.deleteTexture;
+ WebGL2RenderingContext.prototype.createTexture = function (...args) { const value = create.apply(this, args); live.add(value); return value; };
+ WebGL2RenderingContext.prototype.deleteTexture = function (value) { live.delete(value); return remove.call(this, value); };
+ window.liveTextureCount = () => live.size;
+ });
+ await page.setContent(preview.html);
+ await page.waitForFunction(() => typeof window.portosComposition?.seek === 'function');
+ const transports = await page.evaluate(() => ['RTCPeerConnection', 'webkitRTCPeerConnection', 'WebTransport'].map(key => {
+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, key);
+ let message; try { new globalThis[key](); } catch (error) { message = error.message; }
+ return { key, configurable: descriptor.configurable, writable: descriptor.writable, message };
+ }));
+ expect(transports).toEqual(['RTCPeerConnection', 'webkitRTCPeerConnection', 'WebTransport'].map(key => ({ key, configurable: false, writable: false, message: `${key} is disabled in compositions` })));
+ const at = (t) => page.evaluate(async (t) => {
+ await window.portosComposition.seek(t);
+ return { world: document.getElementById('world').toDataURL(), type: document.getElementById('type').toDataURL() };
+ }, t);
+ const first = await at(0);
+ const textures = await page.evaluate(() => window.liveTextureCount());
+ const moved = await at(0.5);
+ expect(moved.world).not.toBe(first.world);
+ expect(await at(0)).toEqual(first);
+ expect(await page.evaluate(() => window.liveTextureCount())).toBe(textures);
+ const pixels = await sharp(Buffer.from(first.world.split(',')[1], 'base64')).resize(64,36).removeAlpha().raw().toBuffer();
+ const orange = [...Array(pixels.length / 3).keys()].filter((i) => pixels[i*3] > pixels[i*3+2] * 1.5 && pixels[i*3] > 100).length;
+ expect(orange).toBeGreaterThan(15); // authored character, not a blank backdrop/overlay-only fallback
+ expect(errors).toEqual([]);
+ await page.close();
+ await mkdir(PATHS.music, { recursive: true }); await mkdir(PATHS.videos, { recursive: true });
+ const master = join(PATHS.music, 'world.wav');
+ execFileSync(ffmpeg, ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'sine=frequency=220:duration=1', master]);
+ const outputPath = join(PATHS.videos, 'world.mp4');
+ const result = await encodeDocumentComposition({ project, plan: await prepareDocumentRender(project), jobId: 'world-proof', audioPath: master, outputPath, windowStart: 0, windowEnd: 2/24 });
+ expect(result).toMatchObject({ width: 1920, height: 1080, fps: 24 });
+ const rendered = execFileSync(ffmpeg, ['-v', 'error', '-i', outputPath, '-frames:v', '1', '-vf', 'scale=64:36', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-']);
+ expect(rendered.reduce((sum, v, i) => sum + Math.abs(v-pixels[i]), 0) / pixels.length).toBeLessThan(15);
+ }, 120000);
+
it('keeps event frames identical across shuffled seeks, an excerpt and a full render, and freezes silence', async () => {
const created = await projects.createProject({ name: 'Synthetic event proof' });
const base = { durationSec: 0.2, narrativeFunction: 'Mark the story turn', mediumRationale: 'Exact code graphics' };
diff --git a/server/services/musicVideo/documentRender.js b/server/services/musicVideo/documentRender.js
index 42cf4633a2..459a14ca16 100644
--- a/server/services/musicVideo/documentRender.js
+++ b/server/services/musicVideo/documentRender.js
@@ -1,3 +1,4 @@
+import { assertMusicVideoMediaSelections, musicVideoMediaMode } from '../../lib/musicVideoMediaPolicy.js';
import { musicVideoGradeFilter } from '../../lib/musicVideoGrade.js';
/**
* Music Video — render a project's composition document over the song.
@@ -102,6 +103,7 @@ export function documentRenderClock(songDurationSec, fps = DOCUMENT_RENDER_FPS)
* history did not (hosted renders record no geometry).
*/
export async function resolveSceneMedia(project, { history = [], probe = async () => null, strictLayers = false } = {}) {
+ assertMusicVideoMediaSelections(project);
const byId = new Map((Array.isArray(history) ? history : []).map((entry) => [entry.id, entry]));
const out = new Map();
const { safeUnder } = await import('../../lib/ffmpeg.js');
@@ -331,12 +333,20 @@ export async function encodeDocumentComposition({
prepare: (dir) => stageDocumentData(dir, data, media),
});
signal?.throwIfAborted();
- page = await openComposition(staged.directory, { signal, streamMedia: true });
+ page = await openComposition(staged.directory, { signal, streamMedia: true, mediaMode: musicVideoMediaMode(project) });
const metadata = await page.evaluate(`(() => {
const c = globalThis.portosComposition;
if (!c || typeof c.seek !== 'function') throw new Error('portosComposition.seek is required');
- return { durationSec: c.durationSec, fps: c.fps, width: c.width, height: c.height, formats: c.formats, layout: typeof c.layout === 'function' };
+ return { durationSec: c.durationSec, fps: c.fps, width: c.width, height: c.height, motionBlur: c.motionBlur, formats: c.formats, layout: typeof c.layout === 'function' };
})()`);
+ const frames = metadata.durationSec * metadata.fps;
+ if (Number.isFinite(frames) && metadata.fps > 0 && Math.abs(frames - Math.round(frames)) > 1e-8) {
+ const lowerFrames = Math.floor(frames);
+ throw new ServerError(`The composition document declares ${metadata.durationSec}s at ${metadata.fps} fps (${Number(frames.toFixed(8))} frames). Edit portosComposition.durationSec to a whole-frame duration, for example ${lowerFrames}/${metadata.fps} (${Number((lowerFrames / metadata.fps).toFixed(8))}s), and re-import the document. Review the song ending before choosing a shorter duration; PortOS has not rounded or trimmed the document.`, {
+ status: 422, code: 'COMPOSITION_DOCUMENT_FRAME_ALIGNMENT',
+ context: { durationSec: metadata.durationSec, fps: metadata.fps, frames },
+ });
+ }
// The managed browser is Google Chrome by default; a Chromium build without
// proprietary codecs cannot decode the H.264 takes. Say so up front instead
// of failing on the first scene's <video> error.
@@ -354,7 +364,7 @@ export async function encodeDocumentComposition({
status: 422, code: 'COMPOSITION_DOCUMENT_CONTRACT',
});
}
- const target = documentTargetFrame({ ...parsed.data, motionBlur: 1 }, project);
+ const target = documentTargetFrame(parsed.data, project);
const window = documentRenderWindow(target, { windowStart, windowEnd });
await encodeComposition(page, { ...target, durationSec: window.durationSec }, silent, {
videoFilter: musicVideoGradeFilter(project.composition?.grade, data.scenes, { fps: target.fps, offsetSec: window.startSec }),
diff --git a/server/services/musicVideo/documentRender.test.js b/server/services/musicVideo/documentRender.test.js
index a7c5eb1f6b..e18ed13d87 100644
--- a/server/services/musicVideo/documentRender.test.js
+++ b/server/services/musicVideo/documentRender.test.js
@@ -12,6 +12,9 @@ import { mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';
+vi.mock('../htmlComposition/encode.js', () => ({ encodeComposition: vi.fn(async () => { throw new Error('stop at encoder'); }) }));
+const { encodeComposition } = await import('../htmlComposition/encode.js');
+
const { browser } = vi.hoisted(() => ({ browser: { seen: null, contract: null } }));
vi.mock('../../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), {
dataRoot: () => lazyTempDataRoot('portos-mv-document-stage-'),
@@ -88,6 +91,12 @@ const encode = (project, plan, jobId) => encodeDocumentComposition({ project, pl
const scratchEntries = async () => (await readdir(join(PATHS.data, 'music-video-song-renders')).catch(() => []));
describe('composition document staging', () => {
+ it('preserves the document shutter sampling contract through the shared encoder', async () => {
+ const { project, plan } = await fixture();
+ browser.contract = { durationSec: 30, fps: 24, width: 1920, height: 1080, motionBlur: 4, layout: false };
+ await expect(encode(project, plan, 'job-shutter')).rejects.toThrow('stop at encoder');
+ expect(encodeComposition).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ motionBlur: 4 }), expect.any(String), expect.any(Object));
+ });
it('writes portos-mv.js with each scene\'s selected take (video first) and copies the files beside the page', async () => {
const { project, plan } = await fixture();
await expect(encode(project, plan, 'job-stage')).rejects.toThrow('stop after staging');
@@ -128,3 +137,16 @@ describe('composition document staging', () => {
expect(await scratchEntries()).toEqual([]);
});
});
+
+// Uniquely prevents an imported timeline from failing with only a generic schema message.
+it('explains fractional document frames before encoding without changing the imported duration', async () => {
+ const { project, plan } = await fixture();
+ browser.contract = { durationSec: 10.01, fps: 24, width: 1920, height: 1080 };
+ await expect(encode(project, plan, 'job-fractional')).rejects.toMatchObject({
+ code: 'COMPOSITION_DOCUMENT_FRAME_ALIGNMENT', status: 422,
+ message: expect.stringContaining('240/24 (10s)'),
+ context: { durationSec: 10.01, fps: 24, frames: 240.24 },
+ });
+ expect(browser.contract.durationSec).toBe(10.01);
+ expect(await scratchEntries()).toEqual([]);
+});
diff --git a/server/services/musicVideo/documentTemplates/spatial/engine.js b/server/services/musicVideo/documentTemplates/spatial/engine.js
new file mode 100644
index 0000000000..c21bd82389
--- /dev/null
+++ b/server/services/musicVideo/documentTemplates/spatial/engine.js
@@ -0,0 +1,89 @@
+export function mount(THREE) {
+
+const mv = window.PORTOS_MV;
+const authored = window.PORTOS_MV_GENERATED;
+const canvas = document.getElementById('world');
+const overlay = document.getElementById('type');
+const text = overlay.getContext('2d');
+const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, preserveDrawingBuffer: true });
+renderer.setPixelRatio(1);
+renderer.shadowMap.enabled = true;
+renderer.shadowMap.type = THREE.PCFSoftShadowMap;
+let width = mv.render.width;
+let height = mv.render.height;
+const ready = document.fonts.load('40px "MV Mono"');
+function layout(size) {
+ width = size.width; height = size.height;
+ renderer.setSize(width, height, false);
+ overlay.width = width; overlay.height = height;
+}
+layout({ width, height });
+function drawWords(t) {
+ const cue = (mv.lyrics || []).find((line) => t >= line.startSec && t < (line.endSec ?? line.startSec + 4));
+ if (!cue) return;
+ text.save();
+ text.font = `${Math.round(height * 0.04)}px "MV Mono"`;
+ text.textAlign = 'center'; text.textBaseline = 'middle';
+ const label = cue.text || (cue.words || []).map((word) => word.w).join(' ');
+ text.lineWidth = height * 0.007; text.strokeStyle = '#080b12'; text.fillStyle = '#ffffff';
+ text.strokeText(label, width / 2, height * 0.88, width * 0.8);
+ text.fillText(label, width / 2, height * 0.88, width * 0.8);
+ text.restore();
+}
+function drawEvents(state) {
+ for (const event of state.activeEvents) {
+ const label = event.kind === 'counter-change' ? `${event.text || event.name} ${Math.round(event.value)}`
+ : event.kind === 'motif-transformation' ? `${event.motif || event.name}: ${event.progress < 0.5 ? event.before || 'Before' : event.after || 'After'}`
+ : event.text || event.name;
+ text.save();
+ text.font = `${Math.round(height * 0.075)}px "MV Mono"`; text.textAlign = 'center';
+ text.fillStyle = '#ffffff'; text.strokeStyle = '#080b12'; text.lineWidth = height * 0.006;
+ text.globalAlpha = event.kind === 'reveal' ? Math.min(1, event.progress * 4) : 1;
+ text.strokeText(label, width / 2, height / 2, width * 0.8);
+ text.fillText(label, width / 2, height / 2, width * 0.8);
+ text.restore();
+ }
+}
+// Each seek owns a fresh world. The author receives no simulation clock or
+// mutable world from a prior frame, including out-of-order subframe captures.
+globalThis.portosComposition = {
+ durationSec: mv.render.durationSec, fps: mv.render.fps, width, height, motionBlur: 1,
+ formats: ['1920x1080', '1080x1920', '1080x1080'], layout,
+ async seek(requested) {
+ await ready;
+ const state = window.PORTOS_MV_EVENT_STATE({ ...mv.song, sections: mv.song.narrativeSections }, requested, mv.render.fps);
+ const t = state.hold ? state.t : requested;
+ const section = authored.song.sections.find((item) => t >= item.startSec && t < item.endSec) || authored.song.sections.at(-1);
+ const fn = authored.sections[section?.id];
+ if (!fn) throw new Error('No authored scene for this song time');
+ const scene = new THREE.Scene(); scene.background = new THREE.Color('#080b12');
+ const camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 200);
+ camera.position.set(0, 2, 9); camera.lookAt(0, 1, 0);
+ text.reset();
+ try {
+ text.save();
+ fn({ THREE, scene, camera, text }, { t, localT: t - section.startSec, frame: Math.floor(t * mv.render.fps),
+ width, height, song: authored.song, section, palette: authored.palette,
+ safe: { x: width * 0.1, y: height * 0.1, w: width * 0.8, h: height * 0.8 },
+ events: state.activeEvents || [], reactiveGain: state.reactiveGain ?? 1 });
+ text.restore();
+ renderer.render(scene, camera);
+ drawEvents(state);
+ drawWords(t);
+ } finally {
+ const resources = new Set();
+ scene.traverse((object) => {
+ if (object.shadow) resources.add(object.shadow);
+ if (object.geometry) resources.add(object.geometry);
+ for (const material of [object.material].flat().filter(Boolean)) {
+ resources.add(material);
+ for (const value of Object.values(material)) if (value?.isTexture) resources.add(value);
+ }
+ });
+ for (const value of [scene.background, scene.environment]) if (value?.isTexture) resources.add(value);
+ for (const resource of resources) resource.dispose();
+ }
+ },
+};
+
+}
diff --git a/server/services/musicVideo/documentTemplates/spatial/index.html b/server/services/musicVideo/documentTemplates/spatial/index.html
new file mode 100644
index 0000000000..91d2c3e3d7
--- /dev/null
+++ b/server/services/musicVideo/documentTemplates/spatial/index.html
@@ -0,0 +1,14 @@
+<!doctype html>
+<html lang="en"><head><meta charset="utf-8"><title>Authored music-video world</title>
+<style>
+@font-face{font-family:"MV Mono";src:url(fonts/ibm-plex-mono-400.woff2)}
+html,body{margin:0;overflow:hidden;background:#080b12}canvas{position:absolute;inset:0;width:100vw;height:100vh;object-fit:contain}
+</style></head><body><canvas id="world"></canvas><canvas id="type"></canvas>
+<script src="portos-mv.js"></script><!-- portos-allow-hidden-content: render-time song contract -->
+<script src="generated.js"></script><!-- portos-allow-hidden-content: validated authored scene functions -->
+<!-- portos-allow-hidden-content: local packaged Three.js and reviewed engine --><script type="module">
+import * as THREE from './vendor/three.module.js';
+import { mount } from './engine.js';
+mount(THREE);
+</script><!-- portos-allow-hidden-content: local deterministic renderer -->
+</body></html>
diff --git a/server/services/musicVideo/mediaModes.test.js b/server/services/musicVideo/mediaModes.test.js
new file mode 100644
index 0000000000..1cd5578049
--- /dev/null
+++ b/server/services/musicVideo/mediaModes.test.js
@@ -0,0 +1,132 @@
+import { afterAll, describe, expect, it, vi } from 'vitest';
+import { mkdir, writeFile, stat } from 'node:fs/promises';
+import { join } from 'node:path';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';
+vi.mock('../../lib/paths.js', async (original) => makePathsProxy(await original(), { dataRoot: () => lazyTempDataRoot('mv-media-policy-') }));
+vi.mock('./devArtifactStore.js', async (original) => {
+ const store = await original();
+ return { ...store, writeDevArtifactFile: vi.fn(store.writeDevArtifactFile) };
+});
+const projects = await import('./projects.js');
+const { importDocumentDirectory } = await import('./compositionDocument.js');
+const { PATHS } = await import('../../lib/paths.js');
+const { assertMusicVideoMedia, musicVideoMediaMode } = await import('../../lib/musicVideoMediaPolicy.js');
+const { castAndSetsAllowsImages, castAndSetsMedium } = await import('./castAndSetsDirection.js');
+const { migrateMediaMode } = await import('../../../scripts/migrations/421-music-video-media-modes.js');
+afterAll(() => cleanupTempDataRoots());
+
+describe('whole-workflow media modes', () => {
+ it('preserves legacy code-only intent and every historical asset without enabling a provider', () => {
+ const legacy = { automation: { tools: ['code:render'] }, scenes: [{ sceneId: 's', referenceImageId: 'historical.png' }] };
+ const migrated = migrateMediaMode(legacy);
+ expect(migrated).toEqual({ ...legacy, mediaMode: 'code-only' });
+ expect(migrateMediaMode(migrated)).toBe(migrated);
+ expect(musicVideoMediaMode(legacy)).toBe('code-only');
+ expect(() => assertMusicVideoMedia(migrated, 'image', 'guide generation')).toThrow(/planning guides/);
+ expect(castAndSetsMedium(migrated)).toBe('procedural');
+ expect(castAndSetsAllowsImages({ ...migrated, automation: { tools: ['image:local'] } })).toBe(false);
+ expect(migrateMediaMode({ scenes: legacy.scenes })).toEqual({ scenes: legacy.scenes, mediaMode: 'code-images-video' });
+ });
+
+ it('enforces project and take selection, handoff imports and narrowing without deleting selected data', async () => {
+ const project = await projects.createProject({ name: 'Example', mediaMode: 'code-images' });
+ const scene = await projects.addProjectScene(project.id, { label: 'Scene' });
+ await expect(projects.updateScene(project.id, scene.sceneId, { videoHistoryId: 'video-example' })).rejects.toMatchObject({ code: 'MUSIC_VIDEO_MEDIA_POLICY' });
+ await projects.updateScene(project.id, scene.sceneId, { referenceImageId: 'example.png' });
+ await expect(projects.updateProject(project.id, { mediaMode: 'code-only' })).rejects.toMatchObject({ code: 'MUSIC_VIDEO_MEDIA_POLICY' });
+ expect((await projects.getProject(project.id)).scenes[0].referenceImageId).toBe('example.png');
+ await projects.updateScene(project.id, scene.sceneId, { referenceImageId: null });
+ await projects.updateProject(project.id, { mediaMode: 'code-only' });
+ await expect(projects.selectSceneTake(project.id, scene.sceneId, (await projects.getProject(project.id)).scenes[0].takes[0].takeId)).rejects.toMatchObject({ code: 'MUSIC_VIDEO_MEDIA_POLICY' });
+ const fork = await projects.cloneProject(project.id);
+ expect(fork.mediaMode).toBe('code-only');
+ expect(fork.scenes[0].takes).toHaveLength(1); // retained history is never destroyed by narrowing/forking
+ await expect(projects.createProject({ name: 'Invalid', mediaMode: 'code-only', visualSpec: { references: [{ imageId: 'example.png' }] } })).rejects.toMatchObject({ code: 'MUSIC_VIDEO_MEDIA_POLICY' });
+ });
+
+ it('refuses raster and embedded image documents before activation, accepts code+local fonts', async () => {
+ const project = await projects.createProject({ name: 'Document', mediaMode: 'code-only' });
+ const dir = join(PATHS.data, 'candidate'); await mkdir(dir, { recursive: true });
+ await writeFile(join(dir, 'index.html'), '<img src="data:image/png;base64,AAAA">');
+ await expect(importDocumentDirectory(project.id, 'candidate')).rejects.toMatchObject({ code: 'MUSIC_VIDEO_MEDIA_POLICY' });
+ expect((await projects.getProject(project.id)).composition.document).toBeUndefined();
+ await writeFile(join(dir, 'index.html'), '<canvas></canvas>');
+ await writeFile(join(dir, 'example.woff2'), 'synthetic font');
+ await writeFile(join(dir, 'scene.js'), '/** @type {Array<Image>} */ const objects = [];');
+ const imported = await importDocumentDirectory(project.id, 'candidate');
+ expect(imported.project.composition.mode).toBe('document');
+ await writeFile(join(dir, 'scene.js'), 'const svg = `<image href="photo.png"/>`;');
+ await expect(importDocumentDirectory(project.id, 'candidate')).rejects.toMatchObject({ code: 'MUSIC_VIDEO_MEDIA_POLICY' });
+ await writeFile(join(dir, 'scene.js'), 'const objects = [];');
+ // Renaming a raster to an allowed local-font extension must not bypass admission.
+ await writeFile(join(dir, 'example.woff2'), Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
+ await expect(importDocumentDirectory(project.id, 'candidate')).rejects.toMatchObject({ code: 'MUSIC_VIDEO_MEDIA_POLICY' });
+ await writeFile(join(dir, 'example.woff2'), 'synthetic font');
+ await writeFile(join(dir, 'photo.png'), 'synthetic raster');
+ await expect(importDocumentDirectory(project.id, 'candidate')).rejects.toMatchObject({ code: 'MUSIC_VIDEO_MEDIA_POLICY' });
+ });
+});
+
+it('rejects embedded raster planning guides through the same policy as final documents', async () => {
+ const { saveGeneratedDevArtifact } = await import('./devArtifactService.js');
+ const project = await projects.createProject({ name: 'Guide example', mediaMode: 'code-only' });
+ await expect(saveGeneratedDevArtifact(project.id, { kind: 'cast-sets', title: 'Guide', html: '<img src="/api/images/example.png">' })).rejects.toMatchObject({ code: 'MUSIC_VIDEO_MEDIA_POLICY' });
+});
+
+it('allows AVIF document images only in a mode that permits images', async () => {
+ const project = await projects.createProject({ name: 'AVIF document', mediaMode: 'code-images' });
+ const dir = join(PATHS.data, 'avif-candidate');
+ await mkdir(dir, { recursive: true });
+ await writeFile(join(dir, 'index.html'), '<canvas></canvas>');
+ await writeFile(join(dir, 'photo.avif'), Buffer.from([0, 0, 0, 24, ...Buffer.from('ftypavif'), 0, 0, 0, 0]));
+ await expect(importDocumentDirectory(project.id, 'avif-candidate')).resolves.toHaveProperty('project.composition.mode', 'document');
+ await projects.updateProject(project.id, { mediaMode: 'code-only' });
+ await expect(importDocumentDirectory(project.id, 'avif-candidate')).rejects.toMatchObject({ code: 'MUSIC_VIDEO_MEDIA_POLICY' });
+});
+
+it('refuses a guide upload when the media mode narrows before its record commit and removes its file', async () => {
+ const { importDevArtifact } = await import('./devArtifactService.js');
+ const store = await import('./devArtifactStore.js');
+ const original = await vi.importActual('./devArtifactStore.js');
+ const project = await projects.createProject({ name: 'Concurrent guide', mediaMode: 'code-images' });
+ const tempPath = join(PATHS.data, 'uploaded-guide.png');
+ await writeFile(tempPath, Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
+ let storedFile;
+ store.writeDevArtifactFile.mockImplementationOnce(async (input) => {
+ const written = await original.writeDevArtifactFile(input);
+ storedFile = store.resolveDevArtifactFile(written.file);
+ await projects.updateProject(project.id, { mediaMode: 'code-only' });
+ return written;
+ });
+ await expect(importDevArtifact(project.id, { tempPath, originalName: 'guide.png', kind: 'cast-sets' }))
+ .rejects.toMatchObject({ code: 'DEV_ARTIFACT_CONFLICT' });
+ expect((await projects.getProject(project.id)).devArtifacts || []).toEqual([]);
+ await expect(stat(storedFile)).rejects.toMatchObject({ code: 'ENOENT' });
+ await expect(stat(tempPath)).rejects.toMatchObject({ code: 'ENOENT' });
+});
+
+it('blocks reselecting or approving retained raster guides, including embedded HTML, after narrowing', async () => {
+ const { importDevArtifact, saveGeneratedDevArtifact } = await import('./devArtifactService.js');
+ const { saveProductionDraft, approveProductionReview } = await import('./productionReviewService.js');
+ const { productionReadiness, productionReviewBasis } = await import('./productionReview.js');
+ const project = await projects.createProject({ name: 'Retained guide', mediaMode: 'code-images' });
+ const tempPath = join(PATHS.data, 'retained-guide.png');
+ await writeFile(tempPath, Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
+ const { artifact: raster } = await importDevArtifact(project.id, { tempPath, originalName: 'guide.png', kind: 'cast-sets' });
+ const { artifact: embedded } = await saveGeneratedDevArtifact(project.id, { kind: 'cast-sets', title: 'Embedded guide', html: '<img src="data:image/png;base64,AAAA">' });
+ const draft = { cast: 'Robot', environments: 'City', visualLanguage: 'Orange silhouettes', motionLanguage: 'Walk cycle', guideArtifactId: raster.id };
+ await saveProductionDraft(project.id, draft);
+ await projects.updateProject(project.id, { mediaMode: 'code-only' });
+ expect(productionReadiness(await projects.getProject(project.id)).art.problems).toContain('Code only requires a code-authored visual guide; select a compatible Development artifact.');
+ for (const guide of [raster, embedded]) {
+ await expect(saveProductionDraft(project.id, { ...draft, guideArtifactId: guide.id })).rejects.toMatchObject({ code: 'MUSIC_VIDEO_MEDIA_POLICY' });
+ // A legacy row may already select either guide before migration/narrowing.
+ await projects.mutateProjectRecord(project.id, current => ({ project: { ...current, productionReview: { ...current.productionReview, draft: { ...draft, guideArtifactId: guide.id } } } }));
+ await expect(approveProductionReview(project.id, { stage: 'art', basis: productionReviewBasis(await projects.getProject(project.id)).art })).rejects.toMatchObject({ code: 'MUSIC_VIDEO_MEDIA_POLICY' });
+ }
+ const { artifact: authored } = await saveGeneratedDevArtifact(project.id, { kind: 'cast-sets', title: 'Authored guide', html: '<svg><circle r="20" fill="orange"/></svg>' });
+ await saveProductionDraft(project.id, { ...draft, guideArtifactId: authored.id });
+ const approved = await approveProductionReview(project.id, { stage: 'art', basis: productionReviewBasis(await projects.getProject(project.id)).art });
+ expect(approved.readiness.art.approved).toBe(true);
+ expect(approved.project.devArtifacts.map(artifact => artifact.id)).toEqual(expect.arrayContaining([raster.id, embedded.id]));
+});
diff --git a/server/services/musicVideo/planner.js b/server/services/musicVideo/planner.js
index 35067f337a..5f16ea18e2 100644
--- a/server/services/musicVideo/planner.js
+++ b/server/services/musicVideo/planner.js
@@ -104,9 +104,9 @@ function directedPrompts(shot, generated = {}) {
shot.look && `Wardrobe: ${quote(`${shot.look.name}. ${shot.look.description}`, 350)}`,
generated.framePrompt || (shot.visualLayer === 'card' ? 'Graphic title card.' : 'Cinematic shot in the directed setting.'),
].filter(Boolean).join(' ');
- const motion = generated.prompt || (shot.visualLayer === 'card' ? 'Hold the graphic beat.'
+ const motion = generated.prompt || (shot.visualLayer === 'card' ? 'Choreograph the graphic scene around the supplied musical anchors; give subject, props and camera a readable action and payoff. Use a hold only when it serves the chosen energy target.'
: shot.shotMode === 'performance' ? `Perform to the source audio: ${shot.lyricText}`
- : `Slow camera push; interpret the emotion and action of ${shot.lyricText || shot.visualIntent || shot.sectionLabel || 'this instrumental passage'}.`);
+ : `Stage a readable subject action and camera response for ${shot.lyricText || shot.visualIntent || shot.sectionLabel || 'this instrumental passage'}, timed to the supplied musical anchors and chosen energy target.`);
return { framePrompt: frame.slice(0, SCENE_TEXT_MAX), prompt: motion.slice(0, SCENE_TEXT_MAX) };
}
@@ -139,6 +139,9 @@ export function buildScenePlanPrompt(project, shots) {
// Automation-first projects carry the director's standing guidance.
const guidance = project.automation?.guidance?.trim();
const guidanceLine = guidance ? `Director guidance: ${quote(guidance, PROMPT_GUIDANCE_MAX)}` : '';
+ const savedPlan = project.productionReview?.draft;
+ const motionPlan = savedPlan?.motionLanguage
+ ? `SAVED ENERGY AND CHOREOGRAPHY DRAFT (planning does not grant approval):\n${quote(savedPlan.motionLanguage, 12000)}\nImplementation: ${quote(savedPlan.implementationPlan || '', 16000)}` : '';
const hasLyrics = shots.some((s) => s.lyricText);
const hasDelivery = shots.some((s) => s.delivery?.length);
const shotLines = shots.map((s, i) => {
@@ -153,6 +156,12 @@ export function buildScenePlanPrompt(project, shots) {
if (s.visualLayer) parts.push(`layer: ${s.visualLayer}; mode: ${s.shotMode}`);
if (s.set) parts.push(`assigned set: ${quote(`${s.set.name}: ${s.set.description}; ${s.set.lighting || ''}`, 650)}`);
if (s.look) parts.push(`assigned look: ${quote(`${s.look.name}: ${s.look.description}`, 400)}`);
+ parts.push(`absolute time: ${s.startSec}–${s.endSec}s`);
+ const anchors = (values) => (values || []).filter(t => Number.isFinite(t) && t >= s.startSec && t < s.endSec).slice(0, 16).join(', ');
+ for (const kind of ['beats', 'downbeats']) {
+ const times = anchors(project.audioAnalysis?.[kind]);
+ if (times) parts.push(`${kind} (seconds): ${times}`);
+ }
if (s.shotMode === 'performance') parts.push(PERFORMANCE_FRAME);
return parts.join('; ');
}).join('\n');
@@ -164,15 +173,18 @@ ${musicVideoCreativeContext(concept)}
${musicVideoDirectionContext(direction)}
${briefLines}
${guidanceLine}
+${motionPlan}
The song has been cut into these shots (index; musical section and the shot's position inside it; duration; normalized 0..1 section energy — higher is louder/more intense; the lyric lines sung during the shot, or "instrumental"; optional director intent${hasDelivery ? '; optional delivery directions from the lyric sheet' : ''}):
${shotLines}
-For EACH shot above, propose the shot for a generative video model:
+For EACH shot above, propose a timed composition for its assigned medium (code-authored worlds, selected stills or footage):
- "framePrompt": the opening reference still — subject, setting, lighting, composition. Keep it concrete and visual.
- "prompt": the motion for that shot — camera move, subject motion, mood — building on the frame. Higher-energy sections read more kinetic; calmer sections more static/lingering.
- Shots in the same section are one edited sequence: keep subject and setting continuous, but vary framing (wide / medium / close), angle, or action from shot to shot so consecutive shots cut rather than repeat.
- The OPENING HOOK shot must grab attention immediately.
+- In each motion prompt, name absolute start/end times and the supplied musical anchors for subject action, prop transformation, camera framing/movement and any permitted graphic typography. Follow the saved energy target; this proposal still needs human review. Repeated choruses must develop the action, scale or staging instead of replaying the same pose. Include anticipation, payoff and recovery; motivated holds and long takes are valid. Do not replace choreography with continuous camera drift, geometry presence, subtitles alone or an arbitrary fast-cut quota.
+- If an energy target or required audio timing is absent, identify it as a director decision to review rather than inventing analysis or claiming the plan is approved.
${hasLyrics ? '- Let the lyric lines inform the imagery and emotion of their shot (interpret, do not illustrate word-for-word). Never render the lyrics as on-screen text in footage; assigned card layers use their explicit card text.\n' : ''}${hasDelivery ? '- Follow the delivery directions: spoken or whispered lines play as intimate close-ups; shouts land as hard-hitting cuts or impacts; a silence or stop is a held, frozen or cut-to-black beat.\n' : ''}- Keep the assigned layer and shot mode: performance uses source-audio lip-sync and a frontal medium close-up with the mouth visible; cutaways show narrative action without lip-sync; cards are graphic beats.\n- Honor any director intent given for a shot. Instrumental shots carry no singing or lip-sync.
Respond with ONLY a JSON array, one object per shot, in shot-index order (replace every <…> with real content; do NOT output the literal angle-bracket text), no other text:
diff --git a/server/services/musicVideo/planner.test.js b/server/services/musicVideo/planner.test.js
index ee30598cb0..70091b2574 100644
--- a/server/services/musicVideo/planner.test.js
+++ b/server/services/musicVideo/planner.test.js
@@ -211,6 +211,19 @@ describe('planShots', () => {
});
describe('buildScenePlanPrompt', () => {
+ it('carries the reviewed energy plan and actual musical anchors into autopilot shot choreography', () => {
+ const project = makeProject({ productionReview: { draft: { motionLanguage: 'Energy: playful. 0–4s: unfold on the downbeat; second chorus doubles the prop scale.', implementationPlan: 'Use a hinged prop and an analytic camera arc.' } } });
+ const { shots } = planShots(SECTIONS, { beats: BEATS, downbeats: DOWNBEATS });
+ const prompt = buildScenePlanPrompt(project, shots);
+ expect(prompt).toContain('SAVED ENERGY AND CHOREOGRAPHY DRAFT (planning does not grant approval)');
+ expect(prompt).toContain(project.productionReview.draft.motionLanguage);
+ expect(prompt).toContain(project.productionReview.draft.implementationPlan);
+ expect(prompt).toContain(`absolute time: ${shots[0].startSec}–${shots[0].endSec}s`);
+ expect(prompt).toContain('beats (seconds):');
+ expect(prompt).toContain('Repeated choruses must develop');
+ expect(prompt).toContain('motivated holds and long takes are valid');
+ });
+
it('carries the automation brief guidance into the plan prompt', () => {
const base = makeProject({ concept: {} });
expect(buildScenePlanPrompt(base, [])).not.toContain('Director guidance');
diff --git a/server/services/musicVideo/productionReview.js b/server/services/musicVideo/productionReview.js
index 58c7dc3f2b..98a7cac9ef 100644
--- a/server/services/musicVideo/productionReview.js
+++ b/server/services/musicVideo/productionReview.js
@@ -2,18 +2,26 @@
import { randomUUID } from 'node:crypto';
import { canonicalSnapshotChecksum as hash } from '../../lib/snapshotChecksum.js';
import { ServerError } from '../../lib/errorHandler.js';
+import { musicVideoAllowsMedia } from '../../lib/musicVideoMediaPolicy.js';
import { isNonBlankStr as text } from '../../lib/textUtils.js';
const artifact = (project, id) => (project.devArtifacts || []).find(a => a.id === id && !a.deleted);
const artifactBasis = a => a ? { id: a.id, version: a.version, file: a.file } : null;
-const source = p => ({ trackId: p.trackId, uploadedAudioFilename: p.uploadedAudioFilename,
- duration: p.audioAnalysis?.durationSec, beats: p.audioAnalysis?.beats, sections: p.audioAnalysis?.sections,
- lyrics: p.lyricCues, markers: p.lyricMarkers, phrases: p.phrases });
+const source = p => {
+ const timing = p.audioTimingRevisions?.at(-1);
+ return { trackId: p.trackId, uploadedAudioFilename: p.uploadedAudioFilename,
+ duration: p.audioAnalysis?.durationSec, beats: p.audioAnalysis?.beats, sections: p.audioAnalysis?.sections,
+ // These drive authored musical actions even when the beat grid and lyrics
+ // stay unchanged. Waveform display samples and receipt timestamps do not.
+ downbeats: p.audioAnalysis?.downbeats, features: p.audioAnalysis?.features,
+ audioTiming: timing ? { version: timing.version, basis: timing.basis, input: timing.input } : null,
+ lyrics: p.lyricCues, markers: p.lyricMarkers, phrases: p.phrases };
+};
export const productionAlignmentBasis = project => hash(source(project));
export function productionReviewBasis(project) {
const draft = project.productionReview?.draft || {};
- const art = hash({ projectId: project.id, mode: project.composition?.mode, policy: project.productionPolicy,
+ const art = hash({ projectId: project.id, mediaMode: project.mediaMode, authoringRenderer: project.composition?.authoringRenderer, mode: project.composition?.mode, policy: project.productionPolicy,
concept: project.concept, visualSpec: project.visualSpec, styleReferences: project.styleReferences,
direction: project.castAndSets?.direction,
cast: draft.cast, environments: draft.environments, visualLanguage: draft.visualLanguage,
@@ -43,6 +51,7 @@ export function productionReadiness(project) {
if (!text(draft[key])) artProblems.push(`${label} needs editable direction.`);
}
if (!['text/html', 'image/png', 'image/jpeg'].includes(artifact(project, draft.guideArtifactId)?.mimeType)) artProblems.push('Attach a visual cast/environment sheet from Development artifacts.');
+ if (artifact(project, draft.guideArtifactId)?.mimeType?.startsWith('image/') && !musicVideoAllowsMedia(project, 'image')) artProblems.push('Code only requires a code-authored visual guide; select a compatible Development artifact.');
const artApproved = !artProblems.length && review.approvals?.art?.basis === basis.art;
const boardProblems = unresolved('storyboard').map(f => `Resolve storyboard feedback for ${f.target}: ${f.text}`);
if (!artApproved) boardProblems.push('Review and approve the current art direction first.');
@@ -104,7 +113,7 @@ export function assertProductionApproval(project, stage = 'proof') {
{ status: 409, code: 'MUSIC_VIDEO_APPROVAL_REQUIRED', context: { stage, readiness } });
}
-export function approveProductionStage(project, { stage, basis }) {
+export function approveProductionStage(project, { stage, basis, proofReview }) {
const readiness = productionReadiness(project);
const expected = stage === 'proof'
? hash({ basis: readiness.basis.proof, excerptId: project.productionReview?.proof?.excerptId,
@@ -112,9 +121,19 @@ export function approveProductionStage(project, { stage, basis }) {
: readiness.basis[stage];
if (basis !== readiness.basis[stage]) throw new ServerError('This revision changed while you were reviewing it. Review it again.', { status: 409, code: 'MUSIC_VIDEO_REVIEW_STALE' });
if (readiness[stage].problems.length) throw new ServerError(readiness[stage].problems.join(' '), { status: 409, code: 'MUSIC_VIDEO_REVIEW_INCOMPLETE' });
+ if (stage === 'proof') {
+ const excerpt = project.excerpts?.find(e => e.id === project.productionReview?.proof?.excerptId);
+ if (proofReview?.watchedWithAudio !== true || !text(proofReview.energyComparison)
+ || !text(proofReview.timecodedNotes) || !/(?:\b\d{1,2}:\d{2}(?:\.\d+)?\b|\b\d+(?:\.\d+)?s\b)/.test(proofReview.timecodedNotes)) {
+ throw new ServerError('Play this proof with audio and record the energy comparison and timecoded choreography notes before approving.', { status: 409, code: 'MUSIC_VIDEO_PROOF_REVIEW_REQUIRED' });
+ }
+ if (proofReview.excerptId !== excerpt?.id || proofReview.filename !== excerpt?.filename) {
+ throw new ServerError('The rendered proof changed. Play and review the new excerpt before approving.', { status: 409, code: 'MUSIC_VIDEO_REVIEW_STALE' });
+ }
+ }
return { ...project, productionReview: { ...project.productionReview,
reviewedRevisions: { ...project.productionReview?.reviewedRevisions, [basis]: { draft: structuredClone(project.productionReview?.draft || {}), scenes: structuredClone(project.scenes || []), proof: structuredClone(project.productionReview?.proof || null), capturedAt: new Date().toISOString() } },
- approvals: { ...project.productionReview?.approvals, [stage]: { basis: expected, approvedAt: new Date().toISOString() } } } };
+ approvals: { ...project.productionReview?.approvals, [stage]: { basis: expected, approvedAt: new Date().toISOString(), ...(stage === 'proof' ? { proofReview: structuredClone(proofReview) } : {}) } } } };
}
/** Comments retain the exact reviewed draft, even after a replacement import. */
diff --git a/server/services/musicVideo/productionReviewService.js b/server/services/musicVideo/productionReviewService.js
index 06b56182e0..d14002c2f7 100644
--- a/server/services/musicVideo/productionReviewService.js
+++ b/server/services/musicVideo/productionReviewService.js
@@ -87,19 +87,52 @@ export async function requireProductionOperator(req) {
}
export async function saveProductionDraft(id, draft) {
- const { project } = await mutateProjectRecord(id, current => ({ project: { ...current,
+ const guard = await validateGuideSelection(await requireProject(id), () => draft.guideArtifactId);
+ const { project } = await mutateProjectRecord(id, current => {
+ guard(current);
+ return { project: { ...current,
productionReview: { ...current.productionReview, draft,
alignmentBasis: draft.timingStatus === 'verified'
? (current.productionReview?.draft?.timingStatus !== 'verified' ? productionAlignmentBasis(current) : current.productionReview?.alignmentBasis)
- : null } } }));
+ : null } } };
+ });
return changed(project);
}
export async function approveProductionReview(id, input) {
- const { project } = await mutateProjectRecord(id, current => ({ project: approveProductionStage(current, input) }));
+ const guard = await validateGuideSelection(await requireProject(id), current => current.productionReview?.draft?.guideArtifactId);
+ const { project } = await mutateProjectRecord(id, current => {
+ guard(current);
+ return { project: approveProductionStage(current, input) };
+ });
return changed(project);
}
+// Historical guides remain readable. Selecting or approving one validates its
+// immutable bytes under today's policy, including HTML saved before narrowing.
+async function validateGuideSelection(project, selectedId) {
+ const { musicVideoMediaMode } = await import('../../lib/musicVideoMediaPolicy.js');
+ const signature = current => {
+ const id = selectedId(current);
+ const artifact = current.devArtifacts?.find(entry => entry.id === id && !entry.deleted);
+ return JSON.stringify([musicVideoMediaMode(current), id || null, artifact?.file, artifact?.version]);
+ };
+ const initial = signature(project);
+ const id = selectedId(project);
+ if (id) {
+ const { findDevArtifact } = await import('./devArtifacts.js');
+ const { resolveDevArtifactFile } = await import('./devArtifactStore.js');
+ const { assertDocumentMediaPolicy } = await import('./documentMediaPolicy.js');
+ const artifact = findDevArtifact(project, id);
+ const abs = resolveDevArtifactFile(artifact.file);
+ if (!abs) throw new ServerError('Guide artifact file path is invalid', { status: 422, code: 'VALIDATION_ERROR' });
+ await assertDocumentMediaPolicy(project, [{ rel: artifact.file, abs }]);
+ }
+ return current => {
+ if (signature(current) !== initial) throw new ServerError('The guide or media mode changed while it was being checked — review it again.', { status: 409, code: 'MUSIC_VIDEO_REVIEW_STALE' });
+ };
+}
+
/** Prepare ordinary editable artifacts; never mark any stage approved. */
export async function prepareProductionReview(id, options = {}) {
let project = await requireProject(id);
@@ -139,6 +172,23 @@ export async function prepareProductionReview(id, options = {}) {
await planProject(id, { ...options, seedPrompts: true });
project = await requireProject(id);
}
+ // New code-first projects need an executable medium plan as well as scenes.
+ // Prepare supplies deterministic defaults before human storyboard approval;
+ // it never recompiles an existing treatment or replaces authored direction.
+ if (project.productionPolicy?.strategy === 'code-first' && !project.treatment) {
+ const { buildTreatmentDraft } = await import('./treatmentDraft.js');
+ const { treatmentBasis, writeCompiledTreatment, applyTreatmentToProject } = await import('./treatment.js');
+ ({ project } = await mutateProjectRecord(id, current => {
+ if (current.productionPolicy?.strategy !== 'code-first' || current.treatment
+ || !productionReadiness(current).art.approved) return { project: current };
+ const compiled = writeCompiledTreatment(current, { baseRevision: 0, basis: treatmentBasis(current),
+ draft: buildTreatmentDraft(current), compiledWith: { source: 'deterministic', providerId: null, model: null } });
+ const applied = applyTreatmentToProject(compiled, { revision: compiled.treatment.revision }).project;
+ const original = new Map(current.scenes.map(scene => [scene.sceneId, scene]));
+ return { project: { ...applied, scenes: applied.scenes.map(scene => ({ ...scene,
+ ...(original.get(scene.sceneId)?.direction ? { direction: original.get(scene.sceneId).direction } : {}) })) } };
+ }));
+ }
const { project: planned } = await mutateProjectRecord(id, current => {
const latest = current.productionReview.draft;
const storyboard = [...latest.storyboard, ...current.scenes.filter(scene => !latest.storyboard.some(shot => shot.sceneId === scene.sceneId)).map(scene => ({
diff --git a/server/services/musicVideo/projects.js b/server/services/musicVideo/projects.js
index 0f2a9f7373..684fe59578 100644
--- a/server/services/musicVideo/projects.js
+++ b/server/services/musicVideo/projects.js
@@ -1,3 +1,4 @@
+import { assertMusicVideoMediaSelections } from '../../lib/musicVideoMediaPolicy.js';
/**
* Music Video — project store backend dispatcher (#1760, Phase 1).
*
@@ -159,6 +160,7 @@ async function seedTrackMetadataOnUpdate(id, patch) {
}
export async function createProject(input) {
+ assertMusicVideoMediaSelections(input);
const seeded = await seedTrackMetadata(await seedVideoBackendDefault(input));
const snapshotted = await withStyleSnapshots(seeded);
const project = await (await selectBackend()).createProject(snapshotted);
diff --git a/server/services/musicVideo/projectsFile.test.js b/server/services/musicVideo/projectsFile.test.js
index 51d907a8dd..ebfaf01269 100644
--- a/server/services/musicVideo/projectsFile.test.js
+++ b/server/services/musicVideo/projectsFile.test.js
@@ -370,7 +370,7 @@ describe('editable code revisions and footage variants', () => {
it('forks a document into independent photographic production with song, storyboard and immutable assets', async () => {
const { castAndSetsMedium } = await import('./castAndSetsDirection.js');
const { startProductionOnProject, nextProductionStep } = await import('./production.js');
- const source = await file.createProject({ name: 'Example Film', trackId: 'example-track',
+ const source = await file.createProject({ name: 'Example Film', trackId: 'example-track', mediaMode: 'code-images-video',
concept: { prompt: 'A journey home', subjects: [{ kind: 'character', name: 'Paper protagonist' }], moodBoardStyle: 'Paper world' },
visualSpec: { moodBoardId: 'board-original', references: [{ imageId: 'original.png', role: 'character' }] },
composition: { mode: 'document' }, productionPolicy: { strategy: 'code-first' },
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index 10dfa1479b..5b3bf1c990 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -1,3 +1,4 @@
+import { musicVideoMediaMode, assertMusicVideoMediaSelections } from '../../lib/musicVideoMediaPolicy.js';
/**
* Music Video — pure record transforms (issue #1760, Phase 1).
*
@@ -154,15 +155,17 @@ export function buildProjectRecord(input, { id, now }) {
pacing: input.pacing ?? null,
// #8984 — composition manifest (null = plain concatenation render).
// The document pointer is set only by the import routes, never on create.
- composition: input.composition ? withStoredCompositionDocument(normalizeComposition(input.composition), null) : null,
+ composition: input.composition || input.mediaMode ? withStoredCompositionDocument(normalizeComposition(input.composition || { mode: 'document' }), null) : null,
// #8988 — optional sound-design bed mixed under the song.
soundBed: input.soundBed ? normalizeSoundBed(input.soundBed) : null,
// #8980 — optional pre-production treatment (brief, arc, shot direction,
// proof checklist); null until the director starts one. See treatment.js.
treatment: null,
- productionPolicy: normalizeMusicVideoProductionPolicy(input.productionPolicy),
+ mediaMode: musicVideoMediaMode(input),
+ productionPolicy: normalizeMusicVideoProductionPolicy(input.productionPolicy || (input.mediaMode ? { strategy: 'code-first', maxGeneratedVideoPercent: input.mediaMode === 'code-images-video' ? 100 : 0 } : null)),
scenes: [],
renderHistoryId: null,
+ renderError: null,
// Soft-delete tombstone trio — kept so peer-sync federation (a follow-up)
// is additive rather than a record-shape migration.
deleted: false,
@@ -275,6 +278,7 @@ export function cloneProjectRecord(source, {
}, approvals: {}, proof: null } : null,
...(source.castAndSets ? { castAndSets: { ...source.castAndSets, processId: null, productionRunId: null } } : {}),
renderHistoryId: null,
+ renderError: null,
renderDependencies: null,
// Publishing outputs and posted URLs belong to the source final render.
...(source.publishKit ? { publishKit: null } : {}),
@@ -291,6 +295,7 @@ export function cloneProjectRecord(source, {
medium: 'generated-footage', mediumPinned: false, mediumRationale: '' });
return {
...clone,
+ mediaMode: 'code-images-video',
composition: { ...clone.composition, mode: 'composed' },
productionPolicy: normalizeMusicVideoProductionPolicy({ strategy: 'legacy' }),
castAndSets: null,
@@ -385,6 +390,7 @@ export function applyProjectPatch(project, patch) {
// the flag set would render the old song's cut points against new audio.
const trackChanged = ('trackId' in patch && patch.trackId !== project.trackId)
|| ('uploadedAudioFilename' in patch && patch.uploadedAudioFilename !== project.uploadedAudioFilename);
+ if ('mediaMode' in patch || patch.visualSpec || patch.styleReferences) assertMusicVideoMediaSelections({ ...project, ...mergedPatch });
if (!trackChanged) return touch(project, mergedPatch);
// A planned section belongs to the old audio too; clear its provenance so
// the renderer does not preserve that plan's timing on the replacement song.
@@ -529,6 +535,7 @@ export function applySceneUpdate(project, sceneId, patch) {
if (updated.startSec != null && updated.endSec != null && updated.endSec < updated.startSec) {
throw new ServerError('endSec must be >= startSec', { status: 400, code: 'VALIDATION_ERROR' });
}
+ assertMusicVideoMediaSelections({ ...project, scenes: [updated], visualSpec: null });
const nextScenes = scenes.slice();
nextScenes[idx] = updated;
const next = touch(project, { scenes: nextScenes });
@@ -717,6 +724,7 @@ export function mergeProjectRecord(local, remoteRaw) {
if (Object.hasOwn(local, 'productionReview')) remote.productionReview = local.productionReview;
if (Object.hasOwn(local, 'castAndSets')) remote.castAndSets = local.castAndSets;
if (Object.hasOwn(local, 'autonomousRun')) remote.autonomousRun = local.autonomousRun;
+ if (Object.hasOwn(local, 'renderError')) remote.renderError = local.renderError;
// The composition document's files live only on this install as well
// (compositionDocument.js), so its pointer survives a newer remote body.
if (local.composition?.document || local.composition?.documentDraft) {
diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.js
index 55bf005823..dc43abba04 100644
--- a/server/services/musicVideo/projectsLogic.test.js
+++ b/server/services/musicVideo/projectsLogic.test.js
@@ -654,6 +654,7 @@ describe('mergeProjectRecord (#1770 LWW)', () => {
id: 'mv-1',
updatedAt: '2026-01-01T00:00:00Z',
name: 'local',
+ renderError: 'Example local document failure',
imageMode: 'codex',
imageModelId: 'example-image-model',
videoSettings: { backend: 'local', modelId: 'local-model', grokDuration: 5 },
@@ -662,6 +663,7 @@ describe('mergeProjectRecord (#1770 LWW)', () => {
id: 'mv-1',
updatedAt: '2026-01-05T00:00:00Z',
name: 'remote edit',
+ renderError: 'Peer failure must stay on peer',
videoSettings: { modelId: 'shared-model', grokDuration: 10 },
};
@@ -669,6 +671,7 @@ describe('mergeProjectRecord (#1770 LWW)', () => {
expect(r.remoteWins).toBe(true);
expect(r.next.name).toBe('remote edit');
+ expect(r.next.renderError).toBe('Example local document failure');
expect(r.next.imageMode).toBe('codex');
expect(r.next.imageModelId).toBe('example-image-model');
expect(r.next.videoSettings).toEqual({
diff --git a/server/services/musicVideo/render.document.test.js b/server/services/musicVideo/render.document.test.js
index 16ef060641..2a88bb4498 100644
--- a/server/services/musicVideo/render.document.test.js
+++ b/server/services/musicVideo/render.document.test.js
@@ -142,3 +142,17 @@ it('rejects a changed film between preparing its reviewed plan and starting the
await vi.waitFor(async () => expect((await projects.getProject(id)).status).toBe('failed'));
expect(encodeDocumentComposition).not.toHaveBeenCalled();
});
+
+// The API client can leave before the SSE failure: keep the reason on the record.
+it('persists a document failure for returning operators and clears it after a successful retry', async () => {
+ const id = await documentProject();
+ await importDocumentTemplate(id);
+ const message = 'Edit portosComposition.durationSec to a whole-frame duration and re-import the document.';
+ encodeDocumentComposition.mockRejectedValueOnce(new Error(message));
+ await renderMusicVideo(id);
+ await vi.waitFor(async () => expect(await projects.getProject(id)).toMatchObject({
+ status: 'failed', renderError: `Composition document render failed: ${message}`,
+ }));
+ await renderMusicVideo(id);
+ await vi.waitFor(async () => expect(await projects.getProject(id)).toMatchObject({ status: 'complete', renderError: null }));
+});
diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.js
index 75c43426a8..8c2681d38c 100644
--- a/server/services/musicVideo/render.js
+++ b/server/services/musicVideo/render.js
@@ -1,3 +1,4 @@
+import { assertMusicVideoMediaSelections } from '../../lib/musicVideoMediaPolicy.js';
import { assertProductionApproval, productionReviewBasis } from './productionReview.js';
import { musicVideoGradeFilter } from '../../lib/musicVideoGrade.js';
/**
@@ -583,6 +584,7 @@ export function assertCurrentClipDependencies(project) {
}
export async function planMusicVideoRender(project) {
+ assertMusicVideoMediaSelections(project);
assertCurrentClipDependencies(project);
const ffmpeg = await findFfmpeg();
if (!ffmpeg) throw new ServerError('ffmpeg not found on PATH', { status: 500, code: 'FFMPEG_MISSING' });
@@ -685,14 +687,14 @@ async function renderSeekedMode(projectId, project, handOff, renderer, options =
projectRenders.set(projectId, jobId);
handOff();
const priorStatus = project.status && project.status !== 'rendering' ? project.status : 'ready';
- await updateProject(projectId, { status: 'rendering', renderingOn, renderPartialFilename: filename }).catch((err) => {
+ await updateProject(projectId, { status: 'rendering', renderingOn, renderPartialFilename: filename, renderError: null }).catch((err) => {
console.error(`❌ Music-video ${renderer.label} render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→rendering write failed: ${err.message}`);
});
console.log(`🎬 Rendering ${renderer.label} music video [${jobId.slice(0, 8)}]: project=${projectId.slice(0, 8)} frames=${Math.round(plan.durationSec * plan.fps)} footage=off`);
const { signal } = job.overlayAbort;
const finish = async (patch) => {
projectRenders.delete(projectId);
- await updateProject(projectId, settledRender(patch.status, patch.extra || {})).catch((err) => {
+ await updateProject(projectId, settledRender(patch.status, { renderError: patch.status === 'failed' ? job.lastError?.slice(0, 2000) || 'Render failed' : null, ...patch.extra })).catch((err) => {
console.error(`❌ Music-video ${renderer.label} render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→${patch.status} write failed: ${err.message}`);
});
if (options.productionRunId) musicVideoEvents.emit('document-render', { projectId, runId: options.productionRunId, attemptId: options.productionRenderAttemptId, jobId, status: patch.status === 'complete' ? 'completed' : 'failed', error: job.lastError || null });
@@ -815,7 +817,7 @@ export async function renderMusicVideo(projectId, options = {}) {
// #9010: stamp this instance on the mark so a peer's boot recovery leaves
// it alone, and record the output file so OUR boot recovery can delete the
// partial a restart mid-encode leaves behind.
- await updateProject(projectId, { status: 'rendering', renderingOn, renderPartialFilename: filename }).catch((err) => {
+ await updateProject(projectId, { status: 'rendering', renderingOn, renderPartialFilename: filename, renderError: null }).catch((err) => {
console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→rendering write failed: ${err.message}`);
});
diff --git a/server/services/musicVideo/render.terminal.test.js b/server/services/musicVideo/render.terminal.test.js
index fe72523571..87cdfc9808 100644
--- a/server/services/musicVideo/render.terminal.test.js
+++ b/server/services/musicVideo/render.terminal.test.js
@@ -257,7 +257,7 @@ describe('recoverStuckMusicVideoRenders (#8430)', () => {
prime('stamp-1');
await renderMusicVideo('stamp-1');
expect(updateProject).toHaveBeenCalledWith('stamp-1', {
- status: 'rendering', renderingOn: 'inst-self', renderPartialFilename: expect.stringMatching(/^music-video-stamp-1-\d+\.mp4$/),
+ status: 'rendering', renderingOn: 'inst-self', renderError: null, renderPartialFilename: expect.stringMatching(/^music-video-stamp-1-\d+\.mp4$/),
});
});
diff --git a/server/services/musicVideo/takes.js b/server/services/musicVideo/takes.js
index f45ad2d25e..afeb85afe6 100644
--- a/server/services/musicVideo/takes.js
+++ b/server/services/musicVideo/takes.js
@@ -1,3 +1,4 @@
+import { assertMusicVideoMedia } from '../../lib/musicVideoMediaPolicy.js';
/**
* Music Video scene takes (#8965) — pure record transforms.
*
@@ -141,6 +142,7 @@ function appendToScene(scene, inputs, now) {
/** Append takes to one scene. Throws 404 for a deleted/unknown scene. */
export function appendSceneTakes(project, sceneId, inputs) {
+ for (const input of inputs) assertMusicVideoMedia(project, input.kind, 'take import');
const idx = findSceneIndex(project, sceneId);
const { scene, appended } = appendToScene(project.scenes[idx], inputs, new Date().toISOString());
return { project: replaceScene(project, idx, scene), scene, appended };
@@ -152,6 +154,7 @@ export function appendSceneTakes(project, sceneId, inputs) {
* is refused, so a partially applied import can't strand half a handoff.
*/
export function appendTakesAcrossScenes(project, items) {
+ for (const item of items) assertMusicVideoMedia(project, item.kind, 'handoff import');
const bySceneId = new Map();
items.forEach((item, index) => {
findSceneIndex(project, item.sceneId);
@@ -184,6 +187,7 @@ function locateTake(project, sceneId, takeId) {
/** Explicitly select a take for its slot. Selecting a rejected take restores it. */
export function selectSceneTake(project, sceneId, takeId) {
const { idx, scene, takes, take } = locateTake(project, sceneId, takeId);
+ assertMusicVideoMedia(project, take.kind, 'take selection');
const nextTakes = takes.map((t) => (t.takeId === takeId && t.status === 'rejected' ? { ...t, status: 'candidate' } : t));
const next = { ...scene, takes: nextTakes, [TAKE_SLOT[take.kind]]: take.assetId };
return { project: replaceScene(project, idx, next), scene: next };
diff --git a/server/services/musicVideo/treatmentDraft.js b/server/services/musicVideo/treatmentDraft.js
index ea9b65f67c..2f569148c0 100644
--- a/server/services/musicVideo/treatmentDraft.js
+++ b/server/services/musicVideo/treatmentDraft.js
@@ -1,3 +1,4 @@
+import { musicVideoMediaMode } from '../../lib/musicVideoMediaPolicy.js';
import { shotActionContractProblem } from '../../lib/musicVideoActionContract.js';
import { musicVideoStyleBasis, musicVideoStylePrompt } from '../../lib/musicVideoConditioning.js';
import { musicVideoCreativeContext } from '../../lib/musicVideoCreativeContext.js';
@@ -416,6 +417,7 @@ ${project.styleReferences?.length ? '- "styleLook": one short sentence summarizi
- "graphicLanguage": a concise visual note for the graphic cards and typography (HUD, pictograms, counters), honoring any graphic direction in the brief.
${hasLyrics ? '- "lyricInterpretation": what the lyrics mean and how the picture interprets them (not word-for-word illustration).\n' : '- The song is instrumental: set "lyricInterpretation" to null and invent no lyrics.\n'}- For EACH shot: "mode" (performance|cutaway|graphic), "route" (generated|supplied-asset|code-2d — code-2d becomes a code-rendered title card for a sung line or a moved still; prefer it where a video model cannot hold the requirement), "focalSubject", "framing", "negativeSpace" (none|upper|center|lower — the region kept clean for the separately composited text), "typographyRole" (none|subtitle|hero; must be none on instrumental shots), "emphasis", "transitionIn", "transitionOut", "rationale", and a "framePrompt" (the opening still) and "prompt" (the motion) for the image/video model.
- For EACH shot also supply "medium" (procedural|still|existing-footage|generated-footage) and "mediumRationale". Medium is independent of performance/cutaway intent. Retain director pins. Tie the medium to the shared motifs, their evolution across repeated sections, and entry/exit transitions.
+- MEDIA MODE: ${musicVideoMediaMode(project)}. Code authors scene composition, characters, environment, camera and timing in every mode. Code-only forbids images even for visual guides; code-images forbids generated or imported footage.
- For code-first, prefer procedural or still. Existing footage must be selected already; generated footage is an explicit exception within the allowance. At zero allowance never assign generated footage: report unmet performance intent rather than quietly generating it. This is planning, not a claim that procedural rendering is ready.
- Never ask the image or video model to render the lyrics or any text: typography is composited separately into the reserved region.
${lipSync ? `- Performance shots are lip-synced to the song on ${lipSync.label} (each shot a ${lipSync.minAudioSec}–${lipSync.maxAudioSec}s song window); use them for sung lines where a visible singer matters.` : '- This project\'s video backend cannot lip-sync: no shot can rely on a singer synced to the song.'}