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: generate treatment-driven mixed-media documents (#9300)

[._.]/ Adam Eivy9f196f6148dc
diff --git a/.claude/skills/portos-music-video-code/SKILL.md b/.claude/skills/portos-music-video-code/SKILL.md
new file mode 100644
index 0000000000..bc2e66f7fb
--- /dev/null
+++ b/.claude/skills/portos-music-video-code/SKILL.md
@@ -0,0 +1,16 @@
+---
+name: portos-music-video-code
+description: Author and review a treatment-driven mixed-media music-video composition in PortOS.
+---
+
+# Mixed-media composition authoring
+
+Use the Music Video **Compose → Document → Generate mixed-media composition** action after the song is analyzed, the treatment is approved, and each footage or still scene has a timed, selected local asset. The provider and model shown beside the button write only section drawing functions. No footage or still provider runs during this step. Missing selected media is a preflight error to resolve on the scene board.
+
+PortOS assembles the functions into an immutable candidate version of its layered document. The active document remains selected while the candidate is previewed. Scrub the candidate through each section boundary, selected clip in-point and out-point, repeated hooks and lyric onsets; play it with the master song to judge movement and audio alignment. Accept the reviewed version to render it, or discard it. **Regenerate section** writes a new candidate with the same shared style contract and every other section unchanged. If the treatment, song, scene timing or selected media changed, generate a fresh candidate.
+
+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.
+
+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.
diff --git a/client/src/components/musicVideo/CompositionPreviewPlayer.jsx b/client/src/components/musicVideo/CompositionPreviewPlayer.jsx
index 48249263ce..815650c2f7 100644
--- a/client/src/components/musicVideo/CompositionPreviewPlayer.jsx
+++ b/client/src/components/musicVideo/CompositionPreviewPlayer.jsx
@@ -23,8 +23,9 @@ const lyricAt = (cues, t) => {
* while the transport stays usable; the iframe stays mounted so the loaded
* media and playhead survive.
*/
-export default function CompositionPreviewPlayer({ project, audioUrl, seekRequest = null, collapsed = false }) {
- const doc = project.composition?.document || null;
+export default function CompositionPreviewPlayer({ project, audioUrl, seekRequest = null, collapsed = false, draft = false }) {
+ const doc = (draft ? project.composition?.documentDraft : project.composition?.document) || null;
+ const scrubId = draft ? 'mv-doc-draft-scrub' : 'mv-doc-scrub';
const [preview, setPreview] = useState(null);
const [previewError, setPreviewError] = useState('');
const [status, setStatus] = useState('');
@@ -43,11 +44,11 @@ export default function CompositionPreviewPlayer({ project, audioUrl, seekReques
setPreviewError('');
seekState.current = { inFlight: false, pending: null, ready: false };
if (!refresh) return () => { active = false; };
- getMusicVideoCompositionPreview(project.id, { silent: true })
+ getMusicVideoCompositionPreview(project.id, { silent: true, draft })
.then((next) => { if (active) setPreview(next); })
.catch((err) => { if (active) setPreviewError(err?.message || 'Could not build the preview'); });
return () => { active = false; };
- }, [project.id, refresh]);
+ }, [project.id, refresh, draft]);
const postSeek = useCallback((time) => {
const frame = iframeRef.current?.contentWindow;
@@ -145,7 +146,7 @@ export default function CompositionPreviewPlayer({ project, audioUrl, seekReques
<div className={`overflow-hidden rounded border border-port-border bg-black mx-auto ${collapsed ? 'max-lg:hidden' : ''}`}
style={{ aspectRatio: aspect, maxHeight: '70vh', maxWidth: '100%' }}>
{preview?.html ? (
- <iframe ref={iframeRef} title="Composition document preview" sandbox="allow-scripts" srcDoc={preview.html} className="h-full w-full" />
+ <iframe ref={iframeRef} title={draft ? 'Composition candidate preview' : 'Composition document preview'} sandbox="allow-scripts" srcDoc={preview.html} className="h-full w-full" />
) : (
<p className="p-3 text-xs text-port-text-muted">{previewError ? '' : 'Building the preview…'}</p>
)}
@@ -154,8 +155,8 @@ export default function CompositionPreviewPlayer({ project, audioUrl, seekReques
<button type="button" className={buttonCls} onClick={togglePlay} disabled={!preview || !audioUrl}>
{playing ? <Pause size={14} /> : <Play size={14} />} {playing ? 'Pause' : 'Play'}
</button>
- <label htmlFor="mv-doc-scrub" className="sr-only">Scrub the composition preview</label>
- <input id="mv-doc-scrub" type="range" min={0} max={duration || 0} step={1 / fps} value={Math.min(t, duration || 0)}
+ <label htmlFor={scrubId} className="sr-only">{draft ? 'Scrub the composition candidate' : 'Scrub the composition preview'}</label>
+ <input id={scrubId} type="range" min={0} max={duration || 0} step={1 / fps} value={Math.min(t, duration || 0)}
onChange={(e) => { audioRef.current?.pause(); setPlaying(false); seek(Number(e.target.value)); }}
className="min-w-0 flex-1" />
<span className="text-xs text-port-text-muted tabular-nums">{t.toFixed(2)}s / {duration.toFixed(1)}s</span>
diff --git a/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx b/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx
index f70ed66f22..edc31366b0 100644
--- a/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx
+++ b/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx
@@ -46,4 +46,13 @@ describe('CompositionPreviewPlayer', () => {
rerender(<CompositionPreviewPlayer project={project} audioUrl="/data/music/song.mp3" seekRequest={{ t: 99, n: 3 }} />);
await waitFor(() => expect(screen.getByText(/^9\.9\ds \/ 10\.0s$/)).toBeTruthy());
});
+
+ it('gives simultaneous active and candidate previews distinct scrubbers', async () => {
+ const both = { ...project, composition: { ...project.composition,
+ documentDraft: { ...DOCUMENT, directory: 'music-video/mv-1/composition/doc-candidate' } } };
+ render(<><CompositionPreviewPlayer project={both} audioUrl={null} /><CompositionPreviewPlayer project={both} audioUrl={null} draft /></>);
+ await screen.findByTitle('Composition candidate preview');
+ expect(screen.getByLabelText('Scrub the composition preview').id).toBe('mv-doc-scrub');
+ expect(screen.getByLabelText('Scrub the composition candidate').id).toBe('mv-doc-draft-scrub');
+ });
});
diff --git a/client/src/components/musicVideo/DocumentCompositionPanel.jsx b/client/src/components/musicVideo/DocumentCompositionPanel.jsx
index a30843cc3d..82e9e97616 100644
--- a/client/src/components/musicVideo/DocumentCompositionPanel.jsx
+++ b/client/src/components/musicVideo/DocumentCompositionPanel.jsx
@@ -1,18 +1,23 @@
-import { useState } from 'react';
+import { useEffect, useState } from 'react';
import FilePickerButton from '../ui/FilePickerButton.jsx';
-import { Download, FileArchive, FolderInput, LayoutTemplate, Unlink } from 'lucide-react';
+import { Download, FileArchive, FolderInput, LayoutTemplate, Unlink, Film, RotateCcw } from 'lucide-react';
import toast from '../ui/Toast';
+import useProviderModels from '../../hooks/useProviderModels.js';
+import ProviderModelSelector from '../ProviderModelSelector.jsx';
+import CompositionPreviewPlayer from './CompositionPreviewPlayer.jsx';
import { downloadBlob } from '../../lib/downloadBlob';
import { formatBytes, timeAgo } from '../../utils/formatters.js';
import { compositionDraft } from './compositionDraft.js';
import {
detachMusicVideoCompositionDocument, getMusicVideoCompositionDocument, getMusicVideoCompositionExport,
importMusicVideoCompositionDirectory, importMusicVideoCompositionZip, startMusicVideoCompositionTemplate,
+ generateMusicVideoMixedMediaDocument, regenerateMusicVideoMixedMediaSection,
+ getMusicVideoMixedMediaCandidate, acceptMusicVideoMixedMediaDocument, discardMusicVideoMixedMediaDocument,
} from '../../services/apiMusicVideo.js';
const buttonCls = 'flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50';
const inputCls = 'bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs min-h-[44px] sm:min-h-0';
-const SOURCE_LABELS = { template: 'template', zip: 'zip', directory: 'folder' };
+const SOURCE_LABELS = { template: 'template', zip: 'zip', directory: 'folder', generated: 'generated' };
const linesOf = (value) => String(value || '').split('\n').map((line) => line.trim()).filter(Boolean);
// "12.5 = 80" per line → [[12.5, 80], …]; unparseable lines are dropped.
@@ -116,13 +121,30 @@ function DocumentFiles({ projectId, directory }) {
* beside the stage tabs so it stays visible while scenes and typography are
* edited.
*/
-export default function DocumentCompositionPanel({ project, onProject, onSave }) {
+export default function DocumentCompositionPanel({ project, audioUrl, onProject, onSave }) {
const doc = project.composition?.document || null;
const [busy, setBusy] = useState(null);
// Replacing or detaching drops the current version folder once nothing
// points at it, so both ask for a second click (no window.confirm).
const [confirming, setConfirming] = useState(null);
const [folder, setFolder] = useState('');
+ const [candidate, setCandidate] = useState(null);
+ const [selectedSection, setSelectedSection] = useState('');
+ const {
+ providers, selectedProviderId, selectedModel, availableModels, selectedProvider,
+ setSelectedProviderId, setSelectedModel,
+ } = useProviderModels({ preselectDefaults: true, silent: true });
+
+ useEffect(() => {
+ let active = true;
+ if (!project.composition?.documentDraft && project.composition?.document?.source?.kind !== 'generated') {
+ setCandidate(null); return () => { active = false; };
+ }
+ getMusicVideoMixedMediaCandidate(project.id, { silent: true })
+ .then((next) => { if (active) setCandidate(next); })
+ .catch((err) => { if (active) toast.error(err?.message || 'Could not load the candidate'); });
+ return () => { active = false; };
+ }, [project.id, project.updatedAt, project.composition?.documentDraft?.directory, project.composition?.document?.directory, project.composition?.document?.source?.kind]);
const run = async (label, task, success) => {
setBusy(label);
@@ -146,6 +168,14 @@ export default function DocumentCompositionPanel({ project, onProject, onSave })
return {};
});
const detach = confirmFirst('detach', () => run('detach', () => detachMusicVideoCompositionDocument(project.id, { silent: true }), 'Composition document detached'));
+ const effectiveModel = selectedModel || selectedProvider?.defaultModel || '';
+ 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');
+ const regenerate = () => selectedSectionValid && run('regenerate', () => regenerateMusicVideoMixedMediaSection(project.id, selectedSection,
+ { ...provider, expectedDraft: candidate?.source?.directory }, { silent: true }), 'New candidate ready to review');
+ const accept = () => run('accept', () => acceptMusicVideoMixedMediaDocument(project.id, candidate?.candidate?.directory, { silent: true }), 'Candidate selected for rendering');
+ const discard = () => run('discard', () => discardMusicVideoMixedMediaDocument(project.id, candidate?.candidate?.directory, { silent: true }), 'Candidate discarded');
return (
<section className="mt-3 space-y-2 rounded-lg border border-port-border bg-port-bg p-2" aria-label="Composition document">
@@ -186,6 +216,42 @@ export default function DocumentCompositionPanel({ project, onProject, onSave })
<Unlink size={14} /> {confirming === 'detach' ? 'Click again to detach' : 'Detach'}
</button>
</div>
+ <div className="space-y-2 rounded border border-port-border p-2">
+ <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}
+ 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>
+ <div className="flex flex-wrap items-end gap-2">
+ <button type="button" className={`${buttonCls} bg-port-accent text-white`} disabled={!!busy || !selectedProviderId || !effectiveModel} onClick={generate}>
+ <Film size={14} /> {busy === 'generate' ? 'Generating…' : 'Generate mixed-media composition'}
+ </button>
+ {candidate?.source && <>
+ <div>
+ <label htmlFor="mv-doc-section" className="block text-xs text-port-text-muted mb-0.5">Section to revise</label>
+ <select id="mv-doc-section" className={inputCls} value={selectedSectionValid ? selectedSection : ''} onChange={(e) => setSelectedSection(e.target.value)}>
+ <option value="">Choose section</option>
+ {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 || !selectedSectionValid || candidate.stale || !selectedProviderId || !effectiveModel} onClick={regenerate}>
+ <RotateCcw size={14} /> {busy === 'regenerate' ? 'Regenerating…' : 'Regenerate section'}
+ </button>
+ </>}
+ {candidate?.candidate && <>
+ <button type="button" className={buttonCls} disabled={!!busy || candidate.stale} onClick={accept}>Accept reviewed version</button>
+ <button type="button" className={buttonCls} disabled={!!busy} onClick={discard}>Discard candidate</button>
+ </>}
+ </div>
+ {candidate?.stale && <p className="text-xs text-port-warning" role="status">The treatment, song or selected assets changed. Generate a fresh candidate.</p>}
+ {candidate?.candidate && <div className="rounded border border-port-border p-2">
+ <p className="mb-2 text-xs text-port-text-muted">Candidate preview · {candidate.providerId || 'provider'} / {candidate.model || 'default model'} · active document stays selected until accepted</p>
+ <CompositionPreviewPlayer project={project} audioUrl={audioUrl} draft />
+ </div>}
+ </div>
<OverlayEditor key={`${project.id}-${project.composition?.overlay ? 'hud' : 'none'}`} project={project} onSave={onSave} />
{doc && <DocumentFiles key={doc.directory} projectId={project.id} directory={doc.directory} />}
</section>
diff --git a/client/src/components/musicVideo/DocumentCompositionPanel.test.jsx b/client/src/components/musicVideo/DocumentCompositionPanel.test.jsx
index b7ececc69f..d37af8a291 100644
--- a/client/src/components/musicVideo/DocumentCompositionPanel.test.jsx
+++ b/client/src/components/musicVideo/DocumentCompositionPanel.test.jsx
@@ -8,8 +8,20 @@ const api = vi.hoisted(() => ({
importMusicVideoCompositionDirectory: vi.fn(),
getMusicVideoCompositionExport: vi.fn(),
detachMusicVideoCompositionDocument: vi.fn(),
+ getMusicVideoMixedMediaCandidate: vi.fn(),
+ generateMusicVideoMixedMediaDocument: vi.fn(),
+ regenerateMusicVideoMixedMediaSection: vi.fn(),
+ acceptMusicVideoMixedMediaDocument: vi.fn(),
+ discardMusicVideoMixedMediaDocument: vi.fn(),
}));
vi.mock('../../services/apiMusicVideo.js', () => api);
+vi.mock('../../hooks/useProviderModels.js', () => ({ default: () => ({
+ providers: [{ id: 'stub-provider', name: 'Stub Provider', models: ['fixture-model'] }],
+ selectedProviderId: 'stub-provider', selectedModel: 'fixture-model', availableModels: ['fixture-model'],
+ selectedProvider: { id: 'stub-provider', name: 'Stub Provider' },
+ setSelectedProviderId: vi.fn(), setSelectedModel: vi.fn(),
+}) }));
+vi.mock('./CompositionPreviewPlayer.jsx', () => ({ default: () => <div>Candidate preview</div> }));
vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
import DocumentCompositionPanel from './DocumentCompositionPanel.jsx';
@@ -17,6 +29,8 @@ import DocumentCompositionPanel from './DocumentCompositionPanel.jsx';
const DOCUMENT = { directory: 'music-video/mv-1/composition/doc-a', entry: 'index.html', updatedAt: '2026-01-01T00:00:00.000Z', source: { kind: 'template', name: 'layered' }, files: 9, bytes: 90000 };
const bare = { id: 'mv-1', name: 'Example', updatedAt: '2026-01-01T00:00:00.000Z', composition: { mode: 'document' } };
const attached = { ...bare, composition: { mode: 'document', document: DOCUMENT } };
+const generated = { ...DOCUMENT, directory: 'music-video/mv-1/composition/doc-generated', source: { kind: 'generated', name: 'Mixed-media composition' } };
+const withCandidate = { ...bare, composition: { mode: 'document', document: DOCUMENT, documentDraft: generated } };
beforeEach(() => {
for (const fn of Object.values(api)) fn.mockReset();
@@ -48,4 +62,37 @@ describe('DocumentCompositionPanel', () => {
fireEvent.click(screen.getByRole('button', { name: /Click again to detach/ }));
await waitFor(() => expect(onProject).toHaveBeenLastCalledWith(bare));
});
+
+ it('keeps the active document while a generated candidate is reviewed and explicitly accepted', async () => {
+ api.getMusicVideoMixedMediaCandidate.mockResolvedValue({
+ candidate: generated, source: generated, stale: false, providerId: 'stub-provider', model: 'fixture-model',
+ sections: [{ id: 'verse', label: 'Verse', startSec: 0, endSec: 10 }],
+ });
+ api.acceptMusicVideoMixedMediaDocument.mockResolvedValue({ project: { ...bare, composition: { mode: 'document', document: generated } } });
+ const onProject = vi.fn();
+ render(<DocumentCompositionPanel project={withCandidate} onProject={onProject} onSave={vi.fn()} />);
+ expect(await screen.findByText('Candidate preview')).toBeTruthy();
+ expect(api.acceptMusicVideoMixedMediaDocument).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'Accept reviewed version' }));
+ await waitFor(() => expect(api.acceptMusicVideoMixedMediaDocument).toHaveBeenCalledWith('mv-1', generated.directory, { silent: true }));
+ expect(onProject).toHaveBeenCalled();
+ });
+
+ it('does not regenerate a section removed by a refreshed candidate timeline', async () => {
+ const next = { ...generated, directory: 'music-video/mv-1/composition/doc-next' };
+ api.getMusicVideoMixedMediaCandidate
+ .mockResolvedValueOnce({ candidate: generated, source: generated, stale: false,
+ sections: [{ id: 'verse', label: 'Verse', startSec: 0, endSec: 10 }] })
+ .mockResolvedValueOnce({ candidate: next, source: next, stale: false,
+ sections: [{ id: 'chorus', label: 'Chorus', startSec: 0, endSec: 10 }] });
+ const { rerender } = render(<DocumentCompositionPanel project={withCandidate} onProject={vi.fn()} onSave={vi.fn()} />);
+ fireEvent.change(await screen.findByLabelText('Section to revise'), { target: { value: 'verse' } });
+ expect(screen.getByRole('button', { name: 'Regenerate section' }).disabled).toBe(false);
+ rerender(<DocumentCompositionPanel project={{ ...withCandidate, updatedAt: '2026-01-02T00:00:00.000Z',
+ composition: { ...withCandidate.composition, documentDraft: next } }} onProject={vi.fn()} onSave={vi.fn()} />);
+ await waitFor(() => expect(api.getMusicVideoMixedMediaCandidate).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Regenerate section' }).disabled).toBe(true));
+ expect(screen.getByLabelText('Section to revise').value).toBe('');
+ expect(api.regenerateMusicVideoMixedMediaSection).not.toHaveBeenCalled();
+ });
});
diff --git a/client/src/components/musicVideo/stages/ComposeStage.jsx b/client/src/components/musicVideo/stages/ComposeStage.jsx
index 852796b628..7ea6e9f01e 100644
--- a/client/src/components/musicVideo/stages/ComposeStage.jsx
+++ b/client/src/components/musicVideo/stages/ComposeStage.jsx
@@ -26,6 +26,7 @@ export default function ComposeStage({ board }) {
<DocumentCompositionPanel
key={`document-${project.id}`}
project={project}
+ audioUrl={audioUrl}
onProject={board.replaceProject}
onSave={board.saveProjectFields}
/>
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index 067540ce83..7306672350 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -376,7 +376,16 @@ export const startMusicVideoCompositionTemplate = (id, template = 'layered', opt
request(`${compositionDocumentPath(id)}/template`, { method: 'POST', body: JSON.stringify({ template }), ...options });
export const getMusicVideoCompositionExport = (id, options = {}) =>
request(`${compositionDocumentPath(id)}/export`, { responseType: 'arraybuffer', ...options });
-export const getMusicVideoCompositionPreview = (id, options = {}) => request(`${compositionDocumentPath(id)}/preview`, options);
+export const getMusicVideoCompositionPreview = (id, { draft = false, ...options } = {}) => request(`${compositionDocumentPath(id)}/preview${draft ? '?draft=1' : ''}`, options);
+export const generateMusicVideoMixedMediaDocument = (id, body, options = {}) =>
+ request(`${compositionDocumentPath(id)}/generate`, { method: 'POST', body: JSON.stringify(body || {}), ...options });
+export const getMusicVideoMixedMediaCandidate = (id, options = {}) => request(`${compositionDocumentPath(id)}/candidate`, options);
+export const regenerateMusicVideoMixedMediaSection = (id, sectionId, body, options = {}) =>
+ request(`${compositionDocumentPath(id)}/sections/${encodeURIComponent(sectionId)}/regenerate`, { method: 'POST', body: JSON.stringify(body), ...options });
+export const acceptMusicVideoMixedMediaDocument = (id, directory, options = {}) =>
+ request(`${compositionDocumentPath(id)}/accept`, { method: 'POST', body: JSON.stringify({ directory }), ...options });
+export const discardMusicVideoMixedMediaDocument = (id, directory, options = {}) =>
+ request(`${compositionDocumentPath(id)}/candidate`, { method: 'DELETE', body: JSON.stringify({ directory }), ...options });
export const detachMusicVideoCompositionDocument = (id, options = {}) =>
request(compositionDocumentPath(id), { method: 'DELETE', ...options });
// One preview asset (a scene take under /data, or a document file) as a Blob the
diff --git a/server/lib/musicVideoLayers.js b/server/lib/musicVideoLayers.js
index 6d3c6209f0..a0cd4b4dd8 100644
--- a/server/lib/musicVideoLayers.js
+++ b/server/lib/musicVideoLayers.js
@@ -29,6 +29,17 @@ export function sceneVisualLayer(scene, { layered = false } = {}) {
return layered && (layer === 'still' || layer === 'card') ? layer : 'footage';
}
+/** A generated document executes the explicit code-first medium plan. */
+export function documentSceneVisualLayer(project, scene, { generated = false } = {}) {
+ if (!generated || project?.productionPolicy?.strategy !== 'code-first') return sceneVisualLayer(scene, { layered: true });
+ const direction = (project?.treatment?.shotDirections || []).find((entry) => entry.sceneId === scene.sceneId)
+ || scene?.direction;
+ if (direction?.medium === 'procedural') return 'card';
+ if (direction?.medium === 'still') return 'still';
+ if (direction?.medium === 'existing-footage' || direction?.medium === 'generated-footage') return 'footage';
+ return sceneVisualLayer(scene, { layered: true });
+}
+
/** A still/card section has no clip to measure, so it needs an authored span. */
export function sceneHasAuthoredSpan(scene) {
return typeof scene?.startSec === 'number' && typeof scene?.endSec === 'number' && scene.endSec > scene.startSec;
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index ade7864f92..81ca75807b 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -281,7 +281,7 @@ export const MUSIC_VIDEO_COMPOSITION_MODES = ['concat', 'composed', 'code', 'doc
export const MUSIC_VIDEO_CUTTING_MODES = ['scene', 'intercut'];
// Shipped starting points a project can copy into its document folder.
export const MUSIC_VIDEO_DOCUMENT_TEMPLATES = ['layered'];
-export const MUSIC_VIDEO_DOCUMENT_SOURCES = ['zip', 'directory', 'template'];
+export const MUSIC_VIDEO_DOCUMENT_SOURCES = ['zip', 'directory', 'template', 'generated'];
// One immutable document version: data/music-video/<projectId>/composition/<versionId>.
export const MUSIC_VIDEO_DOCUMENT_DIRECTORY = /^music-video\/[A-Za-z0-9_-]{1,100}\/composition\/[A-Za-z0-9_-]{1,100}$/;
// One section function. Reject the calls that would make a frame depend on
@@ -371,6 +371,7 @@ export const musicVideoCompositionSchema = z.object({
posterSec: timedSec,
codeVideo: musicVideoCodeVideoSchema.nullable().optional(),
document: musicVideoCompositionDocumentSchema.nullable().optional(),
+ documentDraft: musicVideoCompositionDocumentSchema.nullable().optional(),
overlay: musicVideoCompositionOverlaySchema.nullable().optional(),
}).strict();
@@ -382,6 +383,15 @@ export const musicVideoDocumentDirectoryImportSchema = z.object({
export const musicVideoDocumentFileQuerySchema = z.object({
path: z.string().min(1).max(512),
+ draft: z.literal('1').optional(),
+}).strict();
+
+export const musicVideoDocumentDraftQuerySchema = z.object({ draft: z.literal('1').optional() }).strict();
+export const musicVideoDocumentCandidateSchema = z.object({
+ directory: z.string().regex(MUSIC_VIDEO_DOCUMENT_DIRECTORY),
+}).strict();
+export const musicVideoMixedMediaRegenerateSchema = musicVideoCodeGenerateSchema.extend({
+ expectedDraft: z.string().regex(MUSIC_VIDEO_DOCUMENT_DIRECTORY),
}).strict();
export const musicVideoDocumentTemplateSchema = z.object({
diff --git a/server/lib/syncWire.js b/server/lib/syncWire.js
index 970b8862d5..56bb995eb1 100644
--- a/server/lib/syncWire.js
+++ b/server/lib/syncWire.js
@@ -61,8 +61,8 @@ export function stripMusicVideoLocalRenderPins(record, { stripVideoBackend = tru
// (services/musicVideo/compositionDocument.js); the render mode and HUD
// settings still sync, and a peer without the files refuses to render.
if (shared.composition && typeof shared.composition === 'object' && !Array.isArray(shared.composition)
- && Object.hasOwn(shared.composition, 'document')) {
- const { document: _document, ...composition } = shared.composition;
+ && (Object.hasOwn(shared.composition, 'document') || Object.hasOwn(shared.composition, 'documentDraft'))) {
+ const { document: _document, documentDraft: _documentDraft, ...composition } = shared.composition;
shared.composition = composition;
}
if (stripVideoBackend && shared.videoSettings
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index 556979c105..4ea65bd88e 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -62,6 +62,9 @@ import {
musicVideoDocumentDirectoryImportSchema,
musicVideoDocumentFileQuerySchema,
musicVideoDocumentTemplateSchema,
+ musicVideoDocumentDraftQuerySchema,
+ musicVideoDocumentCandidateSchema,
+ musicVideoMixedMediaRegenerateSchema,
isPaginationRequested,
paginateArray,
} from '../lib/validation.js';
@@ -121,6 +124,7 @@ import { planProject } from '../services/musicVideo/planner.js';
import {
DOCUMENT_ZIP_MAX_BYTES,
detachDocument,
+ discardGeneratedDocument,
documentMimeType,
exportDocumentZip,
importDocumentDirectory,
@@ -130,6 +134,7 @@ import {
resolveDocumentFile,
} from '../services/musicVideo/compositionDocument.js';
import { buildDocumentPreview } from '../services/musicVideo/documentPreview.js';
+import { acceptMixedMediaDocument, generateMixedMediaDocument, readMixedMediaCandidate, regenerateMixedMediaSection } from '../services/musicVideo/documentGeneration.js';
import { isZipUpload } from '../lib/zipStream.js';
import { parseLyricCues } from '../services/musicVideo/timedText.js';
import { alignProjectLyrics } from '../services/musicVideo/lyricAlign.js';
@@ -546,6 +551,30 @@ router.post('/:id/composition/document/template', asyncHandler(async (req, res)
res.status(201).json(await importDocumentTemplate(req.params.id, template));
}));
+router.post('/:id/composition/document/generate', asyncHandler(async (req, res) => {
+ const body = validateRequest(musicVideoCodeGenerateSchema, req.body || {});
+ res.status(201).json(await generateMixedMediaDocument(req.params.id, body));
+}));
+
+router.get('/:id/composition/document/candidate', asyncHandler(async (req, res) => {
+ res.json(await readMixedMediaCandidate(req.params.id));
+}));
+
+router.post('/:id/composition/document/sections/:sectionId/regenerate', asyncHandler(async (req, res) => {
+ const body = validateRequest(musicVideoMixedMediaRegenerateSchema, req.body || {});
+ res.status(201).json(await regenerateMixedMediaSection(req.params.id, req.params.sectionId, body));
+}));
+
+router.post('/:id/composition/document/accept', asyncHandler(async (req, res) => {
+ const { directory } = validateRequest(musicVideoDocumentCandidateSchema, req.body || {});
+ res.json(await acceptMixedMediaDocument(req.params.id, directory));
+}));
+
+router.delete('/:id/composition/document/candidate', asyncHandler(async (req, res) => {
+ const { directory } = validateRequest(musicVideoDocumentCandidateSchema, req.body || {});
+ res.json(await discardGeneratedDocument(req.params.id, directory));
+}));
+
router.get('/:id/composition/document/export', asyncHandler(async (req, res) => {
const { zip, filename } = await exportDocumentZip(await requireProject(req.params.id));
res.set('Content-Type', 'application/zip');
@@ -554,15 +583,22 @@ router.get('/:id/composition/document/export', asyncHandler(async (req, res) =>
}));
router.get('/:id/composition/document/preview', asyncHandler(async (req, res) => {
- res.json(await buildDocumentPreview(await requireProject(req.params.id)));
+ const { draft } = validateRequest(musicVideoDocumentDraftQuerySchema, req.query || {});
+ const project = await requireProject(req.params.id);
+ const pointer = draft ? project.composition?.documentDraft : project.composition?.document;
+ if (draft && !pointer) throw new ServerError('No composition candidate to preview', { status: 404, code: 'NOT_FOUND' });
+ res.json(await buildDocumentPreview(draft ? { ...project, composition: { ...project.composition, document: pointer } } : project, { draft: Boolean(draft) }));
}));
// One document file, for the preview's asset bridge (fetched by the PortOS
// page, never loaded by the sandboxed preview itself). Served inert: a
// sandbox CSP, no sniffing, same-origin only.
router.get('/:id/composition/document/file', asyncHandler(async (req, res) => {
- const { path } = validateRequest(musicVideoDocumentFileQuerySchema, req.query || {});
- const abs = await resolveDocumentFile(await requireProject(req.params.id), path);
+ const { path, draft } = validateRequest(musicVideoDocumentFileQuerySchema, req.query || {});
+ const project = await requireProject(req.params.id);
+ const pointer = draft ? project.composition?.documentDraft : project.composition?.document;
+ if (draft && !pointer) throw new ServerError('No composition candidate to preview', { status: 404, code: 'NOT_FOUND' });
+ const abs = await resolveDocumentFile(draft ? { ...project, composition: { ...project.composition, document: pointer } } : project, path);
res.setHeader('Content-Security-Policy', "sandbox; default-src 'none'");
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Cross-Origin-Resource-Policy', 'same-origin');
diff --git a/server/services/codeAnimation/prompt.js b/server/services/codeAnimation/prompt.js
index 76526f7227..71c9e5ea0a 100644
--- a/server/services/codeAnimation/prompt.js
+++ b/server/services/codeAnimation/prompt.js
@@ -318,6 +318,7 @@ function promptSong(song) {
lyrics: (song.lyrics || []).slice(0, 400),
beats: (song.beats || []).slice(0, 400),
downbeats: (song.downbeats || []).slice(0, 200),
+ featureNames: song.featureNames || [],
};
}
@@ -361,3 +362,19 @@ export function extractCodeSections(text) {
}
return [];
}
+
+/** 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 }) {
+ 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.',
+ `SHARED STYLE CONTRACT:\n${JSON.stringify(sharedStyle || { palette, treatment: { brief: treatment?.brief || null, motifs: treatment?.arc?.motifs || [], styleLook: treatment?.styleLook || null }, visualSpec, styleLines })}`,
+ `SONG AND LYRIC TIMING:\n${JSON.stringify(promptSong(song))}`,
+ `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.',
+ '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/musicVideo/codeGeneration.js b/server/services/musicVideo/codeGeneration.js
index eb92b88477..17cdbc08c4 100644
--- a/server/services/musicVideo/codeGeneration.js
+++ b/server/services/musicVideo/codeGeneration.js
@@ -16,7 +16,7 @@ import { normalizeComposition } from './composition.js';
import { getProject, mutateProjectRecord } from './projects.js';
import { buildCodeTimeline, buildSongDocument, paletteFromProject } from './codeTimeline.js';
-async function styleLinesFor(project) {
+export async function styleLinesFor(project) {
const universeId = project.concept?.universeId;
if (!universeId) return [];
try {
@@ -42,7 +42,7 @@ function acceptSources(parsed, ids) {
return accepted;
}
-async function runModel({ providerId, model, prompt }) {
+export async function runModel({ providerId, model, prompt, source = 'music-video-code' }) {
const { assertProvider, resolveProviderAndModel, runPromptThroughProvider } = await import('../promptRunner.js');
const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
assertProvider(provider, { message: 'No AI provider available to write the code video', code: 'PROVIDER_UNAVAILABLE', status: 400 });
@@ -51,7 +51,7 @@ async function runModel({ providerId, model, prompt }) {
provider,
model: selectedModel || undefined,
prompt,
- source: 'music-video-code',
+ source,
cwd: PATHS.data,
});
return { text, providerId: provider.id, model: selectedModel || null };
diff --git a/server/services/musicVideo/codeTimeline.js b/server/services/musicVideo/codeTimeline.js
index ef5f0f035b..80b8a4cc0b 100644
--- a/server/services/musicVideo/codeTimeline.js
+++ b/server/services/musicVideo/codeTimeline.js
@@ -182,7 +182,13 @@ export function buildCodeTimeline(project, { fps = CODE_FPS } = {}) {
if (lyric) {
const anchor = anchorOf(lyric);
const beat = beatAtOrBefore(beats, anchor);
- return { ...window, snap: beat ?? anchor, snapKind: beat == null ? 'lyric' : 'beat', lyricId: lyric.id || null };
+ // A late word can quantize onto the next section's boundary. Keep this
+ // window instead of collapsing it into the following one.
+ const snapped = beat ?? anchor;
+ if (snapped >= window.endSec - 1 / fps) {
+ return { ...window, snap: window.startSec, snapKind: 'nominal', lyricId: lyric.id || null };
+ }
+ return { ...window, snap: snapped, snapKind: beat == null ? 'lyric' : 'beat', lyricId: lyric.id || null };
}
const down = nearest(downbeats, window.startSec);
if (down != null) return { ...window, snap: down, snapKind: 'downbeat', lyricId: null };
diff --git a/server/services/musicVideo/codeTimeline.test.js b/server/services/musicVideo/codeTimeline.test.js
index dd061af4b9..81358a3072 100644
--- a/server/services/musicVideo/codeTimeline.test.js
+++ b/server/services/musicVideo/codeTimeline.test.js
@@ -86,6 +86,22 @@ describe('buildCodeTimeline (#9076)', () => {
expect(timeline.sections[1].snapKind).toBe('downbeat');
});
+ it('keeps a section when its last lyric snaps onto the following boundary', () => {
+ const lateLyric = {
+ ...project,
+ audioAnalysis: { durationSec: 30, beats: [0, 10, 20], downbeats: [0, 10, 20], sections: [
+ { id: 'intro', startSec: 0, endSec: 10 },
+ { id: 'verse', startSec: 10, endSec: 20 },
+ { id: 'hook', startSec: 20, endSec: 30 },
+ ] },
+ lyricCues: [{ id: 'last-line', text: 'on the cut', startSec: 19.8, endSec: 20.1,
+ words: [{ w: 'on', startSec: 20 }] }],
+ };
+ expect(buildCodeTimeline(lateLyric).sections.map((section) => [section.id, section.startSec])).toEqual([
+ ['intro', 0], ['verse', 10], ['hook', 20],
+ ]);
+ });
+
it('prefers treatment windows over analyzed sections', () => {
const directed = {
...project,
diff --git a/server/services/musicVideo/composition.js b/server/services/musicVideo/composition.js
index 65af9408e4..1cfd5a366e 100644
--- a/server/services/musicVideo/composition.js
+++ b/server/services/musicVideo/composition.js
@@ -143,6 +143,7 @@ export function normalizeComposition(input) {
const style = input.style && typeof input.style === 'object' ? input.style : {};
const codeVideo = normalizeCodeVideo(input.codeVideo);
const documentRef = normalizeCompositionDocument(input.document);
+ const documentDraft = normalizeCompositionDocument(input.documentDraft);
const overlay = normalizeCompositionOverlay(input.overlay);
return {
version: COMPOSITION_VERSION,
@@ -161,6 +162,7 @@ export function normalizeComposition(input) {
...(codeVideo ? { codeVideo } : {}),
// Same posture: present only once a document was imported / a HUD set.
...(documentRef ? { document: documentRef } : {}),
+ ...(documentDraft ? { documentDraft } : {}),
...(overlay ? { overlay } : {}),
};
}
@@ -180,8 +182,12 @@ export function withAutopilotCutting(project) {
*/
export function withStoredCompositionDocument(next, stored) {
if (!next) return next;
- const { document: _ignored, ...rest } = next;
- return stored?.document ? { ...rest, document: stored.document } : rest;
+ const { document: _ignored, documentDraft: _ignoredDraft, ...rest } = next;
+ return {
+ ...rest,
+ ...(stored?.document ? { document: stored.document } : {}),
+ ...(stored?.documentDraft ? { documentDraft: stored.documentDraft } : {}),
+ };
}
/** Clear the audio-derived timings (cue times, poster) when the song changes, keeping the text. */
diff --git a/server/services/musicVideo/compositionDocument.js b/server/services/musicVideo/compositionDocument.js
index b75b3f7abd..10b2ab3e42 100644
--- a/server/services/musicVideo/compositionDocument.js
+++ b/server/services/musicVideo/compositionDocument.js
@@ -134,12 +134,12 @@ function serializeProject(projectId, task) {
* and point the project at it. The folder is assembled under a hidden name and
* renamed into place, so a failed import never leaves a half-written version.
*/
-function storeVersion(projectId, files, source) {
+function storeVersion(projectId, files, source, options = {}) {
assertProjectId(projectId);
- return serializeProject(projectId, () => storeVersionNow(projectId, files, source));
+ return serializeProject(projectId, () => storeVersionNow(projectId, files, source, options));
}
-async function storeVersionNow(projectId, files, source) {
+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 versionId = `doc-${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`;
@@ -172,8 +172,9 @@ async function storeVersionNow(projectId, files, source) {
let outcome;
try {
outcome = await mutateProjectRecord(projectId, (current) => {
- const composition = normalizeComposition({ ...(current.composition || {}), mode: 'document' });
- const project = { ...current, composition: { ...composition, document }, updatedAt: document.updatedAt };
+ verifyCurrent(current);
+ const composition = normalizeComposition({ ...(current.composition || {}), ...(!draft ? { mode: 'document' } : {}) });
+ const project = { ...current, composition: { ...composition, [draft ? 'documentDraft' : 'document']: document }, updatedAt: document.updatedAt };
return { project };
});
} catch (error) {
@@ -197,7 +198,7 @@ async function pruneDocumentVersions(projectId) {
const entries = await readdir(root, { withFileTypes: true }).catch(() => []);
if (!entries.length) return 0;
const referenced = new Set((await listProjects({ includeDeleted: true }))
- .map((project) => project?.composition?.document?.directory).filter(Boolean));
+ .flatMap((project) => [project?.composition?.document?.directory, project?.composition?.documentDraft?.directory]).filter(Boolean));
let removed = 0;
const staleBefore = Date.now() - 60 * 60 * 1000;
for (const entry of entries) {
@@ -280,6 +281,50 @@ export async function importDocumentTemplate(projectId, templateId = 'layered')
return storeVersion(projectId, files, { kind: 'template', name: templateId });
}
+/** Stage a host-assembled generated document for review before selection. */
+export async function stageGeneratedDocument(projectId, generatedFiles, { 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>';
+ if (!index.includes(marker)) throw new Error('Layered template has no engine script');
+ const staged = files.filter((file) => file.rel !== 'index.html');
+ staged.push({ rel: 'index.html', data: Buffer.from(index.replace(marker, '<script src="generated.js"></script>\n' + marker)) });
+ staged.push(...generatedFiles);
+ return storeVersion(projectId, staged, { kind: 'generated', name: 'Mixed-media composition' }, { draft: true, verifyCurrent });
+}
+
+/** Select exactly the candidate the director reviewed. */
+export function acceptGeneratedDocument(projectId, directory, { verifyCurrent = () => {} } = {}) {
+ return serializeProject(projectId, async () => {
+ const outcome = await mutateProjectRecord(projectId, (current) => {
+ const draft = current.composition?.documentDraft;
+ if (!draft || draft.directory !== directory || draft.source?.kind !== 'generated') {
+ throw refuse('The composition candidate changed — review the latest version', 'COMPOSITION_DRAFT_STALE', 409);
+ }
+ verifyCurrent(current);
+ const { documentDraft: _ignored, ...composition } = current.composition;
+ return { project: { ...current, composition: { ...composition, mode: 'document', document: draft }, updatedAt: new Date().toISOString() } };
+ });
+ await pruneDocumentVersions(projectId);
+ return { project: outcome.project, document: outcome.project.composition.document };
+ });
+}
+
+/** Discard a candidate without replacing the active document. */
+export function discardGeneratedDocument(projectId, directory) {
+ return serializeProject(projectId, async () => {
+ const outcome = await mutateProjectRecord(projectId, (current) => {
+ if (current.composition?.documentDraft?.directory !== directory) {
+ throw refuse('The composition candidate changed', 'COMPOSITION_DRAFT_STALE', 409);
+ }
+ const { documentDraft: _ignored, ...composition } = current.composition;
+ return { project: { ...current, composition, updatedAt: new Date().toISOString() } };
+ });
+ await pruneDocumentVersions(projectId);
+ return { project: outcome.project };
+ });
+}
+
async function requireDocument(project) {
const dir = resolveDocumentDirectory(project?.composition?.document);
if (!dir || !(await documentAvailable(project))) {
diff --git a/server/services/musicVideo/documentGeneration.js b/server/services/musicVideo/documentGeneration.js
new file mode 100644
index 0000000000..fbcf54282b
--- /dev/null
+++ b/server/services/musicVideo/documentGeneration.js
@@ -0,0 +1,220 @@
+/** User-triggered mixed-media document authoring. No provider runs on read or boot. */
+import { createHash } from 'node:crypto';
+import { readFile } from 'node:fs/promises';
+import { parse } from '@babel/parser';
+import { ServerError } from '../../lib/errorHandler.js';
+import { isDeterministicCodeSource } from '../../lib/musicVideoValidation.js';
+import { summarizeMusicVideoMediumPlan } from '../../lib/musicVideoMediumPlan.js';
+import { buildMixedMediaDocumentPrompt, extractCodeSections } from '../codeAnimation/prompt.js';
+import { buildCodeTimeline, buildSongDocument, paletteFromProject } from './codeTimeline.js';
+import { runModel, styleLinesFor } from './codeGeneration.js';
+import { getProject } from './projects.js';
+import { buildDocumentData, documentAspect, documentRenderClock, documentSongDuration, DOCUMENT_FRAME_SIZES, resolveSceneMedia } from './documentRender.js';
+import { acceptGeneratedDocument, readDocumentFiles, stageGeneratedDocument } from './compositionDocument.js';
+
+const fail = (message, code = 'COMPOSITION_AUTHORING_INVALID', status = 422) => new ServerError(message, { code, status });
+const jsonForScript = (value) => JSON.stringify(value).replace(/</g, '\\u003c');
+const FORBIDDEN_GLOBALS = new Set(['window', 'document', 'globalThis', 'self', 'fetch', 'XMLHttpRequest', 'WebSocket',
+ 'Date', 'performance', 'crypto', 'Function', 'eval', 'setTimeout', 'setInterval', 'requestAnimationFrame']);
+
+function hasUnsafeReference(node) {
+ if (!node || typeof node !== 'object') return false;
+ if (Array.isArray(node)) return node.some(hasUnsafeReference);
+ if (node.type === 'Identifier' && FORBIDDEN_GLOBALS.has(node.name)) return true;
+ if (node.type === 'MemberExpression' && node.object?.name === 'Math'
+ && (node.property?.name === 'random' || node.property?.value === 'random')) return true;
+ if (node.type === 'MemberExpression' && (node.property?.name === 'constructor' || node.property?.value === 'constructor')) return true;
+ return Object.entries(node).some(([key, value]) => key !== 'loc' && key !== 'start' && key !== 'end' && hasUnsafeReference(value));
+}
+
+// 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) {
+ if (!isDeterministicCodeSource(source)) throw fail('A section contains a networked or non-deterministic call', 'NONDETERMINISTIC_SECTION');
+ let body;
+ try { body = parse(source, { sourceType: 'script' }).program.body; }
+ catch { throw fail('A section function has invalid JavaScript', 'INVALID_SECTION_SOURCE'); }
+ const fn = body[0];
+ if (body.length !== 1 || fn?.type !== 'FunctionDeclaration' || fn.id?.name !== 'render' || fn.async || fn.generator
+ || 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 (hasUnsafeReference(fn.body)) throw fail('A section must use only its drawing context and song-time inputs', 'NONDETERMINISTIC_SECTION');
+ return source;
+}
+
+function basisFor(project) {
+ // 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 = {
+ name: project.name || null,
+ treatment: project.treatment || null,
+ productionPolicy: project.productionPolicy || null,
+ visualSpec: project.visualSpec || null,
+ concept: project.concept || null,
+ trackId: project.trackId || null,
+ uploadedAudioFilename: project.uploadedAudioFilename || null,
+ audioAnalysis: project.audioAnalysis || null,
+ lyricCues: project.lyricCues || null,
+ lyricMarkers: project.lyricMarkers || null,
+ scenes: project.scenes || [],
+ compositionStyle: project.composition?.style || { color: '#ffffff', font: 'sans' },
+ };
+ return createHash('sha256').update(JSON.stringify(input)).digest('hex');
+}
+
+async function authoringContext(project) {
+ 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');
+ }
+ const duration = documentSongDuration(project);
+ const timeline = buildCodeTimeline(project);
+ if (!duration || !timeline.sections.length || timeline.durationSec > duration + 1 / 24) {
+ throw fail('Analyze a song of at most 15 minutes and time its sections before generating a composition', 'NO_TIMELINE');
+ }
+ const song = {
+ ...buildSongDocument(project, timeline),
+ featureNames: Object.keys(project.audioAnalysis?.features || {}).slice(0, 40),
+ };
+ const { loadHistory } = await import('../videoGen/history.js');
+ const history = (project.scenes || []).some((scene) => scene.videoHistoryId) ? await loadHistory() : [];
+ const media = await resolveSceneMedia(project, { history, strictLayers: true });
+ const frame = DOCUMENT_FRAME_SIZES[documentAspect(project)];
+ const data = buildDocumentData(project, { media, frame, clock: documentRenderClock(duration), songDurationSec: duration, generated: true });
+ const scenes = data.scenes.map((scene) => {
+ const original = project.scenes.find((entry) => entry.sceneId === scene.sceneId);
+ const wanted = scene.visualLayer === 'still' ? 'image' : scene.visualLayer === 'footage' ? 'video' : null;
+ if (wanted && (scene.startSec == null || scene.endSec == null || scene.media?.kind !== wanted)) {
+ throw fail(`Scene ${scene.sceneId} needs a timed, selected ${wanted === 'video' ? 'clip' : 'still'} already available on this machine`, 'COMPOSITION_MEDIA_MISSING');
+ }
+ return {
+ sceneId: scene.sceneId, label: scene.label, startSec: scene.startSec, endSec: scene.endSec,
+ visualLayer: scene.visualLayer, visualIntent: scene.visualIntent,
+ direction: (project.treatment?.shotDirections || []).find((direction) => direction.sceneId === scene.sceneId) || scene.direction,
+ assetId: scene.media?.kind === 'video' ? original.videoHistoryId : scene.media?.kind === 'image' ? original.referenceImageId : null,
+ mediaKind: scene.media?.kind || null,
+ inSec: scene.media?.inSec ?? null, outSec: scene.media?.outSec ?? null,
+ };
+ });
+ return { song, scenes, basis: basisFor(project), palette: paletteFromProject(project) };
+}
+
+function acceptedSections(text, ids) {
+ const parsed = extractCodeSections(text);
+ const wanted = new Set(ids);
+ const accepted = new Map();
+ for (const entry of parsed) {
+ if (!wanted.has(entry.id) || accepted.has(entry.id)) continue;
+ accepted.set(entry.id, checkedFunction(entry.source));
+ }
+ if (accepted.size !== wanted.size) {
+ throw fail(`The authoring model returned ${accepted.size} of ${wanted.size} required section functions`, 'MISSING_SECTION_SOURCE');
+ }
+ return accepted;
+}
+
+function generatedFiles(manifest) {
+ const functions = manifest.sections.map(({ id, source }) => `${jsonForScript(id)}: (${source}\n)`).join(',\n');
+ const script = `window.PORTOS_MV_GENERATED = { song: ${jsonForScript(manifest.song)}, palette: ${jsonForScript(manifest.palette)}, sections: {\n${functions}\n} };\n`;
+ return [
+ { rel: 'generated.js', data: Buffer.from(script) },
+ { rel: 'manifest.json', data: Buffer.from(JSON.stringify(manifest)) },
+ ];
+}
+
+async function priorManifest(project) {
+ const pointer = project.composition?.documentDraft || project.composition?.document;
+ if (pointer?.source?.kind !== 'generated') throw fail('Generate a mixed-media document before revising a section', 'NO_GENERATED_DOCUMENT', 409);
+ const files = await readDocumentFiles({ ...project, composition: { ...project.composition, document: pointer } });
+ const file = files.get('manifest.json');
+ if (!file) throw fail('The generated document manifest is missing', 'COMPOSITION_DOCUMENT_MISSING', 409);
+ const manifest = JSON.parse(await readFile(file.abs, 'utf8'));
+ if (manifest.version !== 1 || !Array.isArray(manifest.sections) || !manifest.basis) throw fail('The generated document manifest is invalid');
+ return { pointer, manifest };
+}
+
+async function runAuthoring(projectId, { providerId, model, sectionId = null, expectedDraft = null } = {}) {
+ const project = await getProject(projectId);
+ if (!project) throw fail('Project not found', 'NOT_FOUND', 404);
+ const context = await authoringContext(project);
+ let prior = null;
+ if (sectionId) {
+ prior = await priorManifest(project);
+ if (prior.manifest.basis !== context.basis) throw fail('The treatment or selected media changed — generate a fresh document', 'COMPOSITION_DRAFT_STALE', 409);
+ if (project.composition?.documentDraft
+ && (project.composition?.document?.directory || null) !== (prior.manifest.baseDocumentDirectory || null)) {
+ throw fail('The selected document changed — generate a fresh candidate', 'COMPOSITION_DRAFT_STALE', 409);
+ }
+ if (!prior.manifest.sections.some((section) => section.id === sectionId)) throw fail('Section not found in the generated document', 'SECTION_NOT_FOUND', 404);
+ if (expectedDraft !== prior.pointer.directory) throw fail('The candidate changed — review it again', 'COMPOSITION_DRAFT_STALE', 409);
+ }
+ const sharedStyle = prior?.manifest.sharedStyle || {
+ palette: context.palette,
+ treatment: { brief: project.treatment?.brief || null, motifs: project.treatment?.arc?.motifs || [], arc: project.treatment?.arc?.beats || [], styleLook: project.treatment?.styleLook || null },
+ visualSpec: project.visualSpec || null,
+ styleLines: await styleLinesFor(project),
+ };
+ const prompt = buildMixedMediaDocumentPrompt({
+ title: project.name, song: context.song, palette: context.palette, treatment: project.treatment,
+ visualSpec: project.visualSpec, scenes: context.scenes, styleLines: sharedStyle.styleLines,
+ onlySectionId: sectionId, sharedStyle,
+ });
+ const run = await runModel({ providerId, model, prompt, source: 'music-video-document' });
+ const ids = sectionId ? [sectionId] : context.song.sections.map((section) => section.id);
+ const updated = acceptedSections(run.text, ids);
+ 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, baseDocumentDirectory: project.composition?.document?.directory || null,
+ sharedStyle, song: context.song, palette: context.palette,
+ scenes: context.scenes,
+ sections: context.song.sections.map(({ id }) => ({ id, source: merged.get(id) })),
+ providerId: run.providerId, model: run.model,
+ };
+ const active = project.composition?.document?.directory || null;
+ const draft = project.composition?.documentDraft?.directory || null;
+ const result = await stageGeneratedDocument(projectId, generatedFiles(manifest), {
+ verifyCurrent: (current) => {
+ if (basisFor(current) !== context.basis || (current.composition?.document?.directory || null) !== active
+ || (current.composition?.documentDraft?.directory || null) !== draft) {
+ throw fail('The project or candidate changed during generation — review the current state and retry', 'COMPOSITION_DRAFT_STALE', 409);
+ }
+ },
+ });
+ return { ...result, providerId: run.providerId, model: run.model };
+}
+
+export const generateMixedMediaDocument = (projectId, input = {}) => runAuthoring(projectId, input);
+export const regenerateMixedMediaSection = (projectId, sectionId, input = {}) => runAuthoring(projectId, { ...input, sectionId });
+
+export async function acceptMixedMediaDocument(projectId, directory) {
+ const project = await getProject(projectId);
+ if (!project?.composition?.documentDraft || project.composition.documentDraft.directory !== directory) {
+ throw fail('The composition candidate changed', 'COMPOSITION_DRAFT_STALE', 409);
+ }
+ const { manifest } = await priorManifest(project);
+ return acceptGeneratedDocument(projectId, directory, {
+ verifyCurrent: (current) => {
+ if (basisFor(current) !== manifest.basis || (current.composition?.document?.directory || null) !== (manifest.baseDocumentDirectory || null)) {
+ throw fail('The treatment or selected media changed — generate a fresh document', 'COMPOSITION_DRAFT_STALE', 409);
+ }
+ },
+ });
+}
+
+export async function readMixedMediaCandidate(projectId) {
+ const project = await getProject(projectId);
+ if (!project) throw fail('Project not found', 'NOT_FOUND', 404);
+ if (!project.composition?.documentDraft && project.composition?.document?.source?.kind !== 'generated') return { candidate: null, source: null, sections: [] };
+ const { pointer, manifest } = await priorManifest(project);
+ return {
+ candidate: project.composition?.documentDraft || null,
+ source: pointer,
+ sections: (manifest.song?.sections || []).map(({ id, label, startSec, endSec }) => ({ id, label, startSec, endSec })),
+ providerId: manifest.providerId, model: manifest.model,
+ stale: manifest.basis !== basisFor(project)
+ || (Boolean(project.composition?.documentDraft)
+ && (project.composition?.document?.directory || null) !== (manifest.baseDocumentDirectory || null)),
+ };
+}
diff --git a/server/services/musicVideo/documentGeneration.test.js b/server/services/musicVideo/documentGeneration.test.js
new file mode 100644
index 0000000000..32881df73c
--- /dev/null
+++ b/server/services/musicVideo/documentGeneration.test.js
@@ -0,0 +1,118 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';
+
+const h = vi.hoisted(() => ({ calls: 0, prompt: '', response: '' }));
+vi.mock('../../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), {
+ dataRoot: () => lazyTempDataRoot('portos-mv-document-author-'),
+}));
+vi.mock('../promptRunner.js', () => ({
+ assertProvider: () => {},
+ resolveProviderAndModel: async () => ({ provider: { id: 'stub-provider' }, selectedModel: 'fixture-model' }),
+ runPromptThroughProvider: async ({ prompt }) => {
+ h.calls += 1; h.prompt = prompt;
+ return { text: h.response };
+ },
+}));
+
+const { PATHS } = await import('../../lib/paths.js');
+const projects = await import('./projects.js');
+const { importDocumentTemplate } = await import('./compositionDocument.js');
+const { generateMixedMediaDocument, regenerateMixedMediaSection, acceptMixedMediaDocument } = await import('./documentGeneration.js');
+
+const source = (color) => `function render(ctx, env) { ctx.fillStyle = '${color}'; ctx.fillRect(0, 0, env.width, env.height); }`;
+const response = (colors) => JSON.stringify({ sections: Object.entries(colors).map(([id, color]) => ({ id, source: source(color) })) });
+const manifestAt = async (document) => JSON.parse(await readFile(join(PATHS.data, document.directory, 'manifest.json'), 'utf8'));
+
+afterAll(() => cleanupTempDataRoots());
+beforeEach(() => { h.calls = 0; h.prompt = ''; h.response = response({ intro: '#112233', still: '#445566', clip: '#778899' }); });
+
+async function fixture() {
+ await mkdir(PATHS.images, { recursive: true });
+ await mkdir(PATHS.videos, { recursive: true });
+ await writeFile(join(PATHS.images, 'still.png'), 'selected still');
+ await writeFile(join(PATHS.videos, 'clip.webm'), 'selected clip');
+ await writeFile(join(PATHS.data, 'video-history.json'), JSON.stringify([{ id: 'vh-clip', filename: 'clip.webm', numFrames: 240, fps: 24, width: 640, height: 360 }]));
+ const created = await projects.createProject({ name: 'Example Song' });
+ await projects.mutateProjectRecord(created.id, (current) => ({ project: {
+ ...current,
+ audioAnalysis: { durationSec: 30, beats: [0, 10, 20], downbeats: [0, 10, 20], features: { brightness: [0.2] }, sections: [
+ { id: 'intro', label: 'Intro', startSec: 0, endSec: 10 },
+ { id: 'still', label: 'Verse', startSec: 10, endSec: 20 },
+ { id: 'clip', label: 'Hook', startSec: 20, endSec: 30 },
+ ] },
+ lyricCues: [{ id: 'l1', text: 'Example words', startSec: 19.8, endSec: 21, words: [{ w: 'Example', startSec: 20 }] }],
+ visualSpec: { palette: ['#112233', '#ffffff', '#ff7700'], cameraRules: 'Low angle' },
+ productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 },
+ treatment: { revision: 1, brief: { premise: 'A paper kite crosses the city', graphicLanguage: 'Ink and cut paper' }, arc: { motifs: [{ name: 'Kite', evolution: 'Fold to flight' }] }, shotDirections: [
+ { sceneId: 's-intro', medium: 'procedural', mediumRationale: 'Open with graphics' },
+ { sceneId: 's-still', medium: 'still', mediumRationale: 'Hold the selected image' },
+ { sceneId: 's-clip', medium: 'existing-footage', mediumRationale: 'Use the selected take', framing: 'Tight', transitionIn: 'Hard cut' },
+ ] },
+ scenes: [
+ { sceneId: 's-intro', order: 0, startSec: 0, endSec: 10 },
+ { sceneId: 's-still', order: 1, startSec: 10, endSec: 20, referenceImageId: 'still.png' },
+ { sceneId: 's-clip', order: 2, startSec: 20, endSec: 30, shotMode: 'performance', videoHistoryId: 'vh-clip', takes: [
+ { kind: 'video', assetId: 'vh-clip', shotInstruction: { shotMode: 'performance', edit: { inSec: 1, outSec: 8 } } },
+ ] },
+ ],
+ } }));
+ return created.id;
+}
+
+describe('treatment-driven mixed-media document authoring', () => {
+ it('preflights selected media before a provider call and stages a reviewable 30-second document', async () => {
+ const id = await fixture();
+ const original = await projects.getProject(id);
+ await projects.mutateProjectRecord(id, (current) => ({ project: { ...current, scenes: current.scenes.map((s) => s.sceneId === 's-still' ? { ...s, referenceImageId: 'missing.png' } : s) } }));
+ await expect(generateMixedMediaDocument(id)).rejects.toMatchObject({ code: 'COMPOSITION_MEDIA_MISSING' });
+ expect(h.calls).toBe(0);
+ await projects.mutateProjectRecord(id, (current) => ({ project: { ...current, scenes: original.scenes } }));
+ const active = (await importDocumentTemplate(id)).document;
+ const { document: candidate } = await generateMixedMediaDocument(id, { providerId: 'stub-provider', model: 'fixture-model' });
+ const project = await projects.getProject(id);
+ expect(project.composition.document.directory).toBe(active.directory);
+ expect(project.composition.documentDraft.directory).toBe(candidate.directory);
+ const manifest = await manifestAt(candidate);
+ expect(manifest.song.durationSec).toBe(30);
+ expect(manifest.scenes.map((s) => [s.visualLayer, s.assetId])).toEqual([
+ ['card', null], ['still', 'still.png'], ['footage', 'vh-clip'],
+ ]);
+ expect(manifest.scenes[2].inSec).toBe(1);
+ expect(h.prompt).toContain('A paper kite crosses the city');
+ expect(h.prompt).toContain('Fold to flight');
+ expect(h.prompt).toContain('brightness');
+ expect(h.prompt).toContain('still.png');
+ expect(h.prompt).toContain('vh-clip');
+ expect(h.calls).toBe(1); // no image or video provider
+ expect(await readFile(join(PATHS.data, candidate.directory, 'generated.js'), 'utf8')).toContain('function render(ctx, env)');
+ });
+
+ it('revises one section, preserves the other functions, and refuses a stale acceptance', async () => {
+ const id = await fixture();
+ const first = (await generateMixedMediaDocument(id)).document;
+ 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(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: {
+ ...current, scenes: current.scenes.map((scene) => scene.sceneId === 's-clip'
+ ? { ...scene, takes: [{ ...scene.takes[0], shotInstruction: { shotMode: 'performance', edit: { inSec: 2, outSec: 8 } } }] }
+ : scene),
+ } }));
+ await expect(acceptMixedMediaDocument(id, second.directory)).rejects.toMatchObject({ code: 'COMPOSITION_DRAFT_STALE' });
+ expect((await projects.getProject(id)).composition.documentDraft.directory).toBe(second.directory);
+ });
+
+ it('refuses a candidate after the uploaded master song changes without changing its analysis shape', async () => {
+ const id = await fixture();
+ const candidate = (await generateMixedMediaDocument(id)).document;
+ await projects.mutateProjectRecord(id, (current) => ({ project: {
+ ...current, uploadedAudioFilename: 'replacement-master.wav',
+ } }));
+ await expect(acceptMixedMediaDocument(id, candidate.directory)).rejects.toMatchObject({ code: 'COMPOSITION_DRAFT_STALE' });
+ });
+});
diff --git a/server/services/musicVideo/documentPreview.js b/server/services/musicVideo/documentPreview.js
index 512807360b..92910f52bc 100644
--- a/server/services/musicVideo/documentPreview.js
+++ b/server/services/musicVideo/documentPreview.js
@@ -112,14 +112,15 @@ const BOOTSTRAP = `(() => {
* The preview page and the assets to post into it:
* `{ html, assets: [{ key, url, bytes }], width, height, fps, durationSec }`.
*/
-export async function buildDocumentPreview(project) {
+export async function buildDocumentPreview(project, { draft = false } = {}) {
const files = await readDocumentFiles(project);
const songDurationSec = documentSongDuration(project) || 0;
const clock = documentRenderClock(songDurationSec);
const frame = DOCUMENT_FRAME_SIZES[documentAspect(project)];
const history = (project.scenes || []).some((s) => s?.videoHistoryId) ? await loadHistory() : [];
- const media = await resolveSceneMedia(project, { history });
- const data = buildDocumentData(project, { media, frame, clock, songDurationSec });
+ const media = await resolveSceneMedia(project, { history, strictLayers: project.composition?.document?.source?.kind === 'generated' });
+ const data = buildDocumentData(project, { media, frame, clock, songDurationSec,
+ generated: project.composition?.document?.source?.kind === 'generated' });
let inlined = 0;
const inlinedKeys = new Set();
@@ -183,7 +184,7 @@ export async function buildDocumentPreview(project) {
}
for (const [rel, file] of files) {
if (inlinedKeys.has(rel) || !BRIDGED.has(extname(rel).toLowerCase())) continue;
- assets.push({ key: rel, url: `/api/music-video/${encodeURIComponent(project.id)}/composition/document/file?path=${encodeURIComponent(rel)}`, bytes: file.size });
+ assets.push({ key: rel, url: `/api/music-video/${encodeURIComponent(project.id)}/composition/document/file?path=${encodeURIComponent(rel)}${draft ? '&draft=1' : ''}`, bytes: file.size });
}
return { html, assets, width: frame.width, height: frame.height, fps: clock.fps, durationSec: clock.durationSec };
}
diff --git a/server/services/musicVideo/documentRender.browser.test.js b/server/services/musicVideo/documentRender.browser.test.js
index de118b7d19..d553e29fbe 100644
--- a/server/services/musicVideo/documentRender.browser.test.js
+++ b/server/services/musicVideo/documentRender.browser.test.js
@@ -7,12 +7,24 @@
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { existsSync } from 'node:fs';
-import { mkdir, rm, writeFile } from 'node:fs/promises';
+import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { execFileSync, spawn } from 'node:child_process';
import { chromium } from 'playwright-core';
import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';
+const author = vi.hoisted(() => ({ calls: 0, response: null }));
+vi.mock('../promptRunner.js', () => ({
+ assertProvider: () => {},
+ resolveProviderAndModel: async () => ({ provider: { id: 'stub-provider' }, selectedModel: 'fixture-model' }),
+ runPromptThroughProvider: async () => {
+ author.calls += 1;
+ return { text: author.response || JSON.stringify({ sections: ['intro', 'still', 'clip'].map((id) => ({
+ id, source: "function render(ctx, env) { if (env.visualLayer === 'card') { ctx.fillStyle = '#123456'; ctx.fillRect(0, 0, env.width, env.height); } }",
+ })) }) };
+ },
+}));
+
let endpoint;
vi.mock('../browserService.js', () => ({ cdpRequest: (path) => fetch(`${endpoint}${path}`) }));
vi.mock('../../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), {
@@ -23,6 +35,8 @@ const { PATHS } = await import('../../lib/paths.js');
const { findFfmpeg } = await import('../../lib/ffmpeg.js');
const { encodeDocumentComposition, prepareDocumentRender } = 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 } = await import('../htmlComposition/testBrowserCleanup.js');
@@ -103,4 +117,109 @@ describe.skipIf(!chrome || !ffmpeg)('layered template with real Chrome and ffmpe
await rm(first.outputPath, { force: true });
await rm(second.outputPath, { force: true });
}, 120000);
+
+ it('renders a generated 30-second card/still/clip document with the selected performance in-point', async () => {
+ await mkdir(PATHS.videos, { recursive: true });
+ await mkdir(PATHS.images, { recursive: true });
+ await mkdir(PATHS.music, { recursive: true });
+ const clip = join(PATHS.videos, 'generated-rgb.webm');
+ execFileSync(ffmpeg, ['-v', 'error', '-y',
+ '-f', 'lavfi', '-i', 'color=c=red:s=640x360:r=24:d=1', '-f', 'lavfi', '-i', 'color=c=lime:s=640x360:r=24:d=1', '-f', 'lavfi', '-i', 'color=c=blue:s=640x360:r=24:d=1',
+ '-filter_complex', '[0:v][1:v][2:v]concat=n=3:v=1:a=0', '-c:v', 'libvpx', '-b:v', '1M', '-g', '24', clip]);
+ execFileSync(ffmpeg, ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'color=c=yellow:s=640x360:d=1', '-frames:v', '1', join(PATHS.images, 'generated-still.png')]);
+ const master = join(PATHS.music, 'generated-master.wav');
+ execFileSync(ffmpeg, ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'sine=frequency=220:duration=30', master]);
+ const created = await projects.createProject({ name: 'Generated Example' });
+ await projects.mutateProjectRecord(created.id, (current) => ({ project: {
+ ...current,
+ audioAnalysis: { durationSec: 30, beats: [0, 10, 20], downbeats: [0, 10, 20], sections: [
+ { id: 'intro', startSec: 0, endSec: 10 }, { id: 'still', startSec: 10, endSec: 20 }, { id: 'clip', startSec: 20, endSec: 30 },
+ ] },
+ productionPolicy: { strategy: 'code-first', maxGeneratedVideoPercent: 0 },
+ treatment: { shotDirections: [
+ { sceneId: 'card', medium: 'procedural', mediumRationale: 'Graphic opening' },
+ { sceneId: 'image', medium: 'still', mediumRationale: 'Use selected image' },
+ { sceneId: 'video', medium: 'existing-footage', mediumRationale: 'Use selected clip' },
+ ] },
+ scenes: [
+ { sceneId: 'card', order: 0, startSec: 0, endSec: 10 },
+ { sceneId: 'image', order: 1, startSec: 10, endSec: 20, referenceImageId: 'generated-still.png' },
+ { sceneId: 'video', order: 2, startSec: 20, endSec: 30, shotMode: 'performance', videoHistoryId: 'vh-generated', takes: [
+ { kind: 'video', assetId: 'vh-generated', shotInstruction: { shotMode: 'performance', edit: { inSec: 1, outSec: 3 } } },
+ ] },
+ ],
+ } }));
+ await writeFile(join(PATHS.data, 'video-history.json'), JSON.stringify([{ id: 'vh-generated', filename: 'generated-rgb.webm', numFrames: 72, fps: 24, width: 640, height: 360 }]));
+ author.calls = 0;
+ const staged = await generateMixedMediaDocument(created.id);
+ expect(author.calls).toBe(1);
+ expect((await projects.getProject(created.id)).composition.document).toBeUndefined();
+ await acceptMixedMediaDocument(created.id, staged.document.directory);
+ const project = await projects.getProject(created.id);
+ const preview = await buildDocumentPreview(project);
+ expect(preview.html).toContain('PORTOS_MV_GENERATED');
+ expect(preview.html).toContain('"inSec":1');
+ const previewFrames = async (current, times) => {
+ const page = await browser.newPage();
+ const prepared = await buildDocumentPreview(current);
+ await page.setContent(prepared.html);
+ const files = Object.fromEntries(await Promise.all(prepared.assets.map(async (asset) => [asset.key,
+ (await readFile(asset.key.endsWith('.webm') ? clip : join(PATHS.images, 'generated-still.png'))).toString('base64')])));
+ await page.evaluate(async (encoded) => {
+ const blobs = Object.fromEntries(Object.entries(encoded).map(([key, value]) => [key,
+ new Blob([Uint8Array.from(atob(value), (c) => c.charCodeAt(0))], { type: key.endsWith('.webm') ? 'video/webm' : 'image/png' })]));
+ window.postMessage({ type: 'portos-mv:assets', files: blobs }, '*');
+ await window.PORTOS_MV_ASSETS;
+ }, files);
+ const pixels = [];
+ for (const time of times) pixels.push(await page.evaluate(async (t) => {
+ await window.portosComposition.seek(t);
+ const canvas = document.getElementById('stage');
+ return [...canvas.getContext('2d').getImageData(Math.floor(canvas.width / 2), Math.floor(canvas.height / 2), 1, 1).data].slice(0, 3);
+ }, time));
+ await page.close();
+ return pixels;
+ };
+ const beforeProof = await previewFrames(project, [0, 10, 20]);
+ const plan = { ...(await prepareDocumentRender(project)), frame: { width: 1280, height: 720 } };
+ const renderAt = async (time, name) => {
+ const outputPath = join(PATHS.videos, name);
+ await encodeDocumentComposition({ project, plan, jobId: name.replace(/\W/g, ''), audioPath: master, outputPath, windowStart: time, windowEnd: time + 1 / 24 });
+ const frame = execFileSync(ffmpeg, ['-v', 'error', '-i', outputPath, '-frames:v', '1', '-vf', 'scale=64:36', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-']);
+ await rm(outputPath, { force: true });
+ return [...frame.subarray((18 * 64 + 32) * 3, (18 * 64 + 32) * 3 + 3)];
+ };
+ const card = await renderAt(0, 'generated-card.mp4');
+ const still = await renderAt(10, 'generated-still.mp4');
+ const firstClip = await renderAt(20, 'generated-clip.mp4');
+ const repeated = await renderAt(20, 'generated-clip-again.mp4');
+ const fullPath = join(PATHS.videos, 'generated-full.mp4');
+ await encodeDocumentComposition({ project, plan, jobId: 'generated-full', audioPath: master, outputPath: fullPath });
+ const fullPixel = (time) => {
+ const frame = execFileSync(ffmpeg, ['-v', 'error', '-ss', String(time), '-i', fullPath, '-frames:v', '1', '-vf', 'scale=64:36', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-']);
+ return [...frame.subarray((18 * 64 + 32) * 3, (18 * 64 + 32) * 3 + 3)];
+ };
+ for (const [index, time] of [0, 10, 20].entries()) {
+ const excerpt = [card, still, firstClip][index];
+ const final = fullPixel(time);
+ for (let channel = 0; channel < 3; channel++) {
+ expect(Math.abs(beforeProof[index][channel] - excerpt[channel]), `preview/excerpt ${time}s channel ${channel}`).toBeLessThan(35);
+ expect(Math.abs(final[channel] - excerpt[channel]), `final/excerpt ${time}s channel ${channel}`).toBeLessThan(25);
+ }
+ }
+ await rm(fullPath, { force: true });
+ expect(card[2]).toBeGreaterThan(50);
+ expect(still[0]).toBeGreaterThan(140);
+ expect(still[1]).toBeGreaterThan(140);
+ expect(firstClip[1]).toBeGreaterThan(firstClip[0] + 60); // clip time 1s is green, not red
+ expect(firstClip).toEqual(repeated);
+ author.response = JSON.stringify({ sections: [{ id: 'still', source: "function render(ctx, env) { ctx.fillStyle = '#ff00ff'; ctx.fillRect(0, 0, env.width, env.height); }" }] });
+ const revision = await regenerateMixedMediaSection(created.id, 'still', { expectedDraft: project.composition.document.directory });
+ await acceptMixedMediaDocument(created.id, revision.document.directory);
+ const afterProof = await previewFrames(await projects.getProject(created.id), [0, 10, 20]);
+ expect(afterProof[0]).toEqual(beforeProof[0]);
+ expect(afterProof[1]).not.toEqual(beforeProof[1]);
+ expect(afterProof[2]).toEqual(beforeProof[2]);
+ author.response = null;
+ }, 180000);
});
diff --git a/server/services/musicVideo/documentRender.js b/server/services/musicVideo/documentRender.js
index 7d87f63d44..6cdf852ec5 100644
--- a/server/services/musicVideo/documentRender.js
+++ b/server/services/musicVideo/documentRender.js
@@ -31,7 +31,7 @@ import { ServerError } from '../../lib/errorHandler.js';
import { PATHS } from '../../lib/fileUtils.js';
import { htmlCompositionContractSchemaFor } from '../../lib/validation.js';
import { selectedPerformanceInstruction } from '../../lib/musicVideoShotTiming.js';
-import { sceneVisualLayer } from '../../lib/musicVideoLayers.js';
+import { documentSceneVisualLayer } from '../../lib/musicVideoLayers.js';
import { musicVideoAspect } from '../../lib/musicVideoAspect.js';
import { documentDirectoryForRender } from './compositionDocument.js';
import { musicVideoSongDocument } from './compositionRender.js';
@@ -99,15 +99,17 @@ export function documentRenderClock(songDurationSec, fps = DOCUMENT_RENDER_FPS)
* `history` is the video history list; `probe(path)` measures a clip the
* history did not (hosted renders record no geometry).
*/
-export async function resolveSceneMedia(project, { history = [], probe = async () => null } = {}) {
+export async function resolveSceneMedia(project, { history = [], probe = async () => null, strictLayers = false } = {}) {
const byId = new Map((Array.isArray(history) ? history : []).map((entry) => [entry.id, entry]));
const out = new Map();
const { safeUnder } = await import('../../lib/ffmpeg.js');
for (const scene of Array.isArray(project?.scenes) ? project.scenes : []) {
if (!scene?.sceneId) continue;
+ const layer = documentSceneVisualLayer(project, scene, { generated: strictLayers });
+ if (strictLayers && layer === 'card') continue;
const entry = scene.videoHistoryId ? byId.get(scene.videoHistoryId) : null;
const videoPath = entry?.filename ? safeUnder(PATHS.videos, entry.filename) : null;
- if (videoPath && existsSync(videoPath)) {
+ if ((!strictLayers || layer === 'footage') && videoPath && existsSync(videoPath)) {
const measured = entry.numFrames && entry.fps && entry.width && entry.height ? entry : { ...entry, ...((await probe(videoPath)) || {}) };
const duration = measured.numFrames && measured.fps ? measured.numFrames / measured.fps : null;
const edit = selectedPerformanceInstruction(scene)?.edit ?? null;
@@ -124,7 +126,7 @@ export async function resolveSceneMedia(project, { history = [], probe = async (
});
continue;
}
- const imagePath = scene.referenceImageId ? safeUnder(PATHS.images, scene.referenceImageId) : null;
+ const imagePath = (!strictLayers || layer === 'still') && scene.referenceImageId ? safeUnder(PATHS.images, scene.referenceImageId) : null;
if (imagePath && existsSync(imagePath)) {
const ext = (/\.([a-z0-9]{2,5})$/i.exec(scene.referenceImageId)?.[1] || 'png').toLowerCase();
out.set(scene.sceneId, { kind: 'image', path: imagePath, ext: ext === 'jpeg' ? 'jpg' : ext, inSec: null, outSec: null, fps: null, width: null, height: null });
@@ -146,7 +148,7 @@ function sceneDirection(project, sceneId) {
* The `window.PORTOS_MV` payload (pure). `media` is resolveSceneMedia's map;
* `frame` is `{ width, height }`; `clock` is documentRenderClock's result.
*/
-export function buildDocumentData(project, { media = new Map(), frame, clock, songDurationSec }) {
+export function buildDocumentData(project, { media = new Map(), frame, clock, songDurationSec, generated = false }) {
const song = musicVideoSongDocument(project);
const analysis = project?.audioAnalysis || {};
const scenes = (Array.isArray(project?.scenes) ? project.scenes : [])
@@ -164,7 +166,7 @@ export function buildDocumentData(project, { media = new Map(), frame, clock, so
startSec: start,
endSec: start != null && end != null && end > start ? end : null,
shotMode: scene.shotMode === 'performance' ? 'performance' : 'cutaway',
- visualLayer: sceneVisualLayer(scene, { layered: true }),
+ visualLayer: documentSceneVisualLayer(project, scene, { generated }),
stillMove: typeof scene.stillMove === 'string' ? scene.stillMove : null,
cardText: typeof scene.cardText === 'string' ? scene.cardText : null,
cardColor: typeof scene.cardColor === 'string' ? scene.cardColor : null,
@@ -306,8 +308,9 @@ export async function encodeDocumentComposition({
const ffmpeg = await findFfmpeg();
if (!ffmpeg) throw new ServerError('ffmpeg not found on PATH', { status: 500, code: 'FFMPEG_MISSING' });
const history = (project.scenes || []).some((s) => s?.videoHistoryId) ? await loadHistory() : [];
- const media = await resolveSceneMedia(project, { history, probe: probeVideoGeometry });
- const data = buildDocumentData(project, { media, frame: plan.frame, clock: plan.clock, songDurationSec: plan.songDurationSec });
+ const media = await resolveSceneMedia(project, { history, probe: probeVideoGeometry, strictLayers: project.composition?.document?.source?.kind === 'generated' });
+ const data = buildDocumentData(project, { media, frame: plan.frame, clock: plan.clock, songDurationSec: plan.songDurationSec,
+ generated: project.composition?.document?.source?.kind === 'generated' });
const silent = `${outputPath}.silent.mp4`;
let staged;
let page;
diff --git a/server/services/musicVideo/documentTemplates/layered/engine.js b/server/services/musicVideo/documentTemplates/layered/engine.js
index 4737c8b3df..f6312afff4 100644
--- a/server/services/musicVideo/documentTemplates/layered/engine.js
+++ b/server/services/musicVideo/documentTemplates/layered/engine.js
@@ -16,6 +16,7 @@
(() => {
'use strict';
const MV = window.PORTOS_MV;
+ const GENERATED = window.PORTOS_MV_GENERATED || null;
if (!MV || !MV.render) throw new Error('PORTOS_MV is missing — PortOS writes portos-mv.js next to index.html when it renders');
// ---------- frame ----------
@@ -383,12 +384,18 @@
};
const cardFor = (scene) => (scene?.visualLayer === 'card' ? CARDS.title : null);
+ function sectionFunction(t) {
+ const section = GENERATED?.song?.sections?.find((item) => t >= item.startSec && t < item.endSec);
+ return section ? { section, fn: GENERATED.sections?.[section.id] } : null;
+ }
+
// ---------- frame ----------
function render(t, scene, source) {
ctx.fillStyle = C.ink; ctx.fillRect(0, 0, W, H);
+ const authored = sectionFunction(t);
if (scene) {
const lt = t - scene.startSec; const d = scene.endSec - scene.startSec;
- const card = cardFor(scene);
+ const card = authored?.fn ? null : cardFor(scene);
if (card) card(t, lt, d, scene, source);
else if (source) {
const energetic = isHighEnergy(t) || scene.shotMode === 'performance';
@@ -397,6 +404,18 @@
}
if (isHighEnergy(t)) glitch(t, pulse(t, downs, 8) * 0.5);
}
+ if (authored?.fn) {
+ const inset = 0.1;
+ ctx.save();
+ try {
+ authored.fn(ctx, {
+ t, localT: t - authored.section.startSec, frame: frameOf(t), width: W, height: H,
+ song: GENERATED.song, palette: GENERATED.palette, section: authored.section,
+ safe: { x: W * inset, y: H * inset, w: W * (1 - 2 * inset), h: H * (1 - 2 * inset) },
+ karaoke: [], mediaKind: scene?.media?.kind || null, visualLayer: scene?.visualLayer || null,
+ });
+ } finally { ctx.restore(); }
+ }
vignette(0.5);
grain(t, 0.09);
drawHud(t);
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index a366dc8d09..2eeddddb4c 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -660,8 +660,14 @@ export function mergeProjectRecord(local, remoteRaw) {
if (Object.hasOwn(local, 'castAndSets')) remote.castAndSets = local.castAndSets;
// 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 && remote.composition && typeof remote.composition === 'object' && !Array.isArray(remote.composition)) {
- remote.composition = { ...remote.composition, document: local.composition.document };
+ if (local.composition?.document || local.composition?.documentDraft) {
+ const sharedComposition = remote.composition && typeof remote.composition === 'object' && !Array.isArray(remote.composition)
+ ? remote.composition : {};
+ remote.composition = {
+ ...sharedComposition,
+ ...(local.composition.document ? { document: local.composition.document } : {}),
+ ...(local.composition.documentDraft ? { documentDraft: local.composition.documentDraft } : {}),
+ };
}
if (local.videoSettings && typeof local.videoSettings === 'object'
&& !Array.isArray(local.videoSettings) && Object.hasOwn(local.videoSettings, 'backend')) {
diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.js
index eb9bd60431..a7442ffb58 100644
--- a/server/services/musicVideo/projectsLogic.test.js
+++ b/server/services/musicVideo/projectsLogic.test.js
@@ -741,6 +741,16 @@ describe('composition document (render style `document`)', () => {
expect(next.name).toBe('remote edit');
expect(next.composition.document).toEqual(pointer);
});
+
+ it('keeps local document pointers when a newer peer has no composition', () => {
+ const draft = { ...pointer, directory: 'music-video/mv-1/composition/doc-draft', source: { kind: 'generated', name: 'Mixed-media composition' } };
+ const local = { ...withDocument(), composition: { ...withDocument().composition, documentDraft: draft } };
+ const remote = { ...local, updatedAt: '2026-01-05T00:00:00Z', composition: null };
+ const { next } = mergeProjectRecord(local, remote);
+ expect(next.composition.document).toEqual(pointer);
+ expect(next.composition.documentDraft).toEqual(draft);
+ expect(next.composition.mode).toBeUndefined();
+ });
});
it('preserves optional project moodboard uploads through create, patch and clone', () => {