Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Music video: revise lyrics and Suno audio in preserved versions (#9642)
[._.]/1ddcca85e284
diff --git a/client/src/components/musicVideo/ProductionReviewPanel.jsx b/client/src/components/musicVideo/ProductionReviewPanel.jsxindex 2cfe7643b5..c0b1d6b400 100644--- a/client/src/components/musicVideo/ProductionReviewPanel.jsx+++ b/client/src/components/musicVideo/ProductionReviewPanel.jsx@@ -23,7 +23,8 @@ export default function ProductionReviewPanel({ project, review, onOpenArtifactconst [endSec, setEndSec] = useState(project.productionReview?.proof?.endSec || Math.min(20, project.audioAnalysis?.durationSec || 20));const ready = review.readiness;const set = (key, value) => setLocal({ ...draft, [key]: value });- const shots = [...draft.storyboard, ...(project.scenes || []).filter(scene => !draft.storyboard.some(s => s.sceneId === scene.sceneId)).map(scene => ({+ const documentShots = draft.storyboardSource === 'document';+ const shots = documentShots ? draft.storyboard : [...draft.storyboard, ...(project.scenes || []).filter(scene => !draft.storyboard.some(s => s.sceneId === scene.sceneId)).map(scene => ({id: scene.sceneId, sceneId: scene.sceneId, lyricCueIds: [], action: '', staging: '', camera: '', transition: '',}))];const shotKey = shot => shot.id || shot.sceneId;@@ -108,9 +109,26 @@ export default function ProductionReviewPanel({ project, review, onOpenArtifactcatch (error) { setImportError(error.message); }}} /></label>+ {project.composition?.mode === 'document' && <div className="space-y-2 rounded border border-port-border p-2">+ <p className="text-sm">Document shot manifest</p>+ <p className="text-xs text-port-text-muted">Export the composition in Compose. Have its author extract the actual shot IDs, timings and choreography from the source (for example timeline.js) into the JSON format below, keeping its documentDirectory and audioBasis from when that source was authored. A generic document section or Board row is not a shot list. Reauthor and reimport the composition after changing lyrics or timing, then import its matching manifest here.</p>+ <label htmlFor={fieldId('document-shots')} className="block text-sm">Import document shot manifest+ <input id={fieldId('document-shots')} type="file" accept=".json,application/json" disabled={dirty || review.busy || !project.productionReview?.draft || !project.composition.document} className={fieldClass}+ onChange={async e => {+ const file = e.target.files?.[0]; e.target.value = ''; setImportError(null);+ if (!file) return;+ try {+ const input = JSON.parse(await file.text());+ if (await review.importDocumentShots(input)) setLocal(null);+ } catch (error) { setImportError(error.message); }+ }} />+ </label>+ <details><summary className="cursor-pointer py-2 text-sm">Shot manifest format</summary><pre className="overflow-auto whitespace-pre-wrap break-all text-xs">{JSON.stringify({ ...ready?.documentShotImport, sourceFile: 'timeline.js', shots: [{ id: 'source-shot-id', sceneId: null, startSec: 0, endSec: 10, lyricCueIds: [], action: 'Source action', staging: 'Source staging', camera: 'Source camera', transition: 'Source transition' }] }, null, 2)}</pre></details>+ <p className="text-xs">{project.productionReview?.documentStoryboard ? `Bound source: ${project.productionReview.documentStoryboard.sourceFile}. Reimporting a document, changing audio or editing these shots requires a new matching manifest.` : 'No document shot manifest bound. Board scenes do not stand in for source shots.'}</p>+ </div>}{importError && <p role="alert">{importError}</p>}{draft.sourceArtifactId && <button type="button" className={buttonClass} onClick={() => onOpenArtifact(draft.sourceArtifactId)}>Read preserved original planning draft</button>}- <button type="button" className={buttonClass} disabled={dirty || review.busy} onClick={review.prepare}>Prepare planning draft with autopilot</button>+ <button type="button" className={buttonClass} disabled={dirty || review.busy || documentShots} 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' }).map(([key, label]) =>@@ -145,18 +163,26 @@ export default function ProductionReviewPanel({ project, review, onOpenArtifact</select></label><label htmlFor={fieldId('alignment-notes')} className="block text-sm">Alignment notes / instrumental rationale<textarea id={fieldId('alignment-notes')} rows={2} value={draft.timingNotes} onChange={e => set('timingNotes', e.target.value)} className={fieldClass} /></label>+ <label htmlFor={fieldId('storyboard-source')} className="block text-sm">Storyboard source+ <select id={fieldId('storyboard-source')} value={draft.storyboardSource || 'board'} onChange={e => set('storyboardSource', e.target.value)} className={fieldClass}>+ <option value="board">Board scenes</option><option value="document">Authored document shot manifest</option>+ </select>+ </label>{shots.map(shot => {- const scene = project.scenes?.find(s => s.sceneId === shot.sceneId);+ const scene = documentShots ? shot : project.scenes?.find(s => s.sceneId === shot.sceneId);return <details key={shotKey(shot)} className="rounded border border-port-border p-2">- <summary className="cursor-pointer min-h-[44px] text-sm">{scene?.label || shot.id || 'Unbound shot'} — {scene ? 'edit choreography' : 'bind to a Board scene'}</summary>- <label htmlFor={fieldId(`scene-${shotKey(shot)}`)} className="block text-sm">Board scene+ <summary className="cursor-pointer min-h-[44px] text-sm">{scene?.label || shot.id || 'Unbound shot'} — {documentShots ? 'document source shot' : scene ? 'edit choreography' : 'bind to a Board scene'}</summary>+ {!documentShots && <label htmlFor={fieldId(`scene-${shotKey(shot)}`)} className="block text-sm">Board scene<select id={fieldId(`scene-${shotKey(shot)}`)} value={shot.sceneId || ''} onChange={e => setShot(shot, 'sceneId', e.target.value || null)} className={fieldClass}><option value="">Unbound draft — no scene selected</option>{(project.scenes || []).map(s => <option key={s.sceneId} value={s.sceneId}>{s.label || s.sceneId}</option>)}</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">{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>+ </label>}+ {!documentShots && !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>}+ {documentShots ? <div className="flex flex-wrap gap-2">+ {['startSec', 'endSec'].map(key => <label key={key} htmlFor={fieldId(`${shotKey(shot)}-${key}`)} className="text-sm">{key === 'startSec' ? 'Shot start (seconds)' : 'Shot end (seconds)'}<input id={fieldId(`${shotKey(shot)}-${key}`)} type="number" min="0" step="0.01" value={shot[key] ?? ''} onChange={e => setShot(shot, key, e.target.value === '' ? null : Number(e.target.value))} className={fieldClass} /></label>)}+ <p className="text-xs text-port-text-muted">Planning edits do not rewrite source code. Reauthor or reimport in Compose, then import its matching shot manifest before approval.</p>+ </div> : <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]} 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>)}diff --git a/client/src/components/musicVideo/SongRevisionPanel.jsx b/client/src/components/musicVideo/SongRevisionPanel.jsxnew file mode 100644index 0000000000..3c5536b05b--- /dev/null+++ b/client/src/components/musicVideo/SongRevisionPanel.jsx@@ -0,0 +1,108 @@+import { useEffect, useRef, useState } from 'react';+import { Link } from 'react-router';+import { saveMusicVideoSongRevision, actOnMusicVideoSongRevision, getMusicVideoProject } from '../../services/apiMusicVideo.js';+import { trackAudioUrl } from '../../services/apiTracks.js';+import socket from '../../services/socket';+import { formatCount } from '../../utils/formatters.js';++/** A saved draft never changes the current master. Only a listened-to candidate may replace it. */+export default function SongRevisionPanel({ project, tracks = [], onUpdated, onFork, disabled }) {+ const track = tracks.find((t) => t.id === project.trackId);+ const seed = project.songRevision?.fields || project.songRevisionHistory?.at(-1)?.fields;+ const [fields, setFields] = useState(() => seed || {+ title: (track?.title || project.name || '').slice(0, 80), style: track?.prompt || '',+ lyrics: track?.lyrics || (project.lyricCues || []).map((cue) => cue.text).join('\n'), instrumental: false,+ });+ const localEdited = useRef(false);+ const editFields = (next) => { localEdited.current = true; setFields(next); };+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState('');+ const [heard, setHeard] = useState({});+ const updateRef = useRef(onUpdated);+ const latestSequence = useRef(project.songRevision?.sequence || 0);+ latestSequence.current = Math.max(latestSequence.current, project.songRevision?.sequence || 0);+ updateRef.current = (next) => {+ if ((next.songRevision?.sequence || 0) < latestSequence.current) return;+ latestSequence.current = next.songRevision?.sequence || 0;+ if (!localEdited.current && next.songRevision?.fields) {+ setFields(next.songRevision.fields);+ }+ onUpdated(next);+ return next;+ };+ useEffect(() => {+ let active = true;+ let generation = 0;+ const receive = (event) => { if (active && event.projectId === project.id) { generation++; updateRef.current(event.project); } };+ const refresh = () => {+ const requested = ++generation;+ return getMusicVideoProject(project.id, { silent: true }).then((next) => {+ if (active && requested === generation && (next.songRevision?.sequence || 0) > latestSequence.current) updateRef.current(next);+ }).catch((err) => { if (active && requested === generation) setError(err.message); });+ };+ socket.on('music-video:song-revision', receive);+ socket.on('connect', refresh);+ refresh();+ return () => { active = false; socket.off('music-video:song-revision', receive); socket.off('connect', refresh); };+ }, [project.id]);+ const revision = project.songRevision;+ const dirty = JSON.stringify(fields) !== JSON.stringify(revision?.fields);+ const run = (request) => {+ setBusy(true); setError('');+ return request().then(({ project: next }) => updateRef.current(next))+ .catch((err) => setError(err.message)).finally(() => setBusy(false));+ };+ const action = (name, extra = {}) => run(() => actOnMusicVideoSongRevision(project.id, name, { revisionId: revision.id, ...extra }, { silent: true }));+ const settled = ['review', 'failed'].includes(revision?.status);+ const canDraft = !revision || ['draft', 'canceled', 'failed'].includes(revision.status);+ return <section aria-label="Song revision" className="min-w-0 space-y-3 rounded-lg border border-port-border bg-port-card p-3">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <h3 className="font-medium">Revise lyrics & song</h3>+ <button type="button" disabled={busy || disabled} onClick={onFork} className="min-h-[44px] text-sm text-port-accent">Fork & revise song</button>+ </div>+ <p className="text-xs text-port-text-muted">Fork preserves this version and its video. Edit the fork’s song, generate Suno candidates, then listen and select new audio. Saving a draft uses no credits.</p>+ {project.parentProjectId && <p className="text-xs">Version {formatCount(project.version || 2)} · <Link className="text-port-accent" to={`/music-video/${project.parentProjectId}`}>Previous version</Link> · {formatCount(project.songRevisionHistory?.length || 0)} prior song revisions</p>}+ {project.parentProjectId && <>+ <fieldset disabled={busy || disabled || !canDraft} className="grid min-w-0 grid-cols-1 gap-2 sm:grid-cols-2">+ <div><label htmlFor="song-revision-title" className="block text-xs">Song title</label><input id="song-revision-title" value={fields.title} maxLength={80} onChange={(e) => editFields({ ...fields, title: e.target.value })} className="w-full rounded border border-port-border bg-port-bg p-2" /></div>+ <div><label htmlFor="song-revision-style" className="block text-xs">Suno musical style</label><textarea id="song-revision-style" value={fields.style} maxLength={1000} onChange={(e) => editFields({ ...fields, style: e.target.value })} className="w-full rounded border border-port-border bg-port-bg p-2" /></div>+ <div className="sm:col-span-2"><label htmlFor="song-revision-lyrics" className="block text-xs">Revision lyrics</label><textarea id="song-revision-lyrics" rows={6} value={fields.lyrics} maxLength={5000} onChange={(e) => editFields({ ...fields, lyrics: e.target.value })} className="w-full rounded border border-port-border bg-port-bg p-2" /></div>+ <label className="flex items-center gap-2 text-xs" htmlFor="song-revision-instrumental"><input id="song-revision-instrumental" type="checkbox" checked={fields.instrumental} onChange={(e) => editFields({ ...fields, instrumental: e.target.checked })} />Instrumental</label>+ <button type="button" disabled={!dirty || !fields.title.trim() || !fields.style.trim() || (!fields.instrumental && !fields.lyrics.trim())} onClick={() => run(() => saveMusicVideoSongRevision(project.id, fields, { silent: true })).then(next => { if (next) { localEdited.current = false; setFields(next.songRevision.fields); } })} className="min-h-[44px] text-sm text-port-accent">Save song draft</button>+ </fieldset>+ {revision && <>+ <p role="status" className="text-sm">Song revision: {revision.status}</p>+ {revision.error && <p role="alert" className="text-sm text-port-warning">{revision.error}. Downloads can resume using the same submitted songs. If no song IDs were returned, check Suno before creating another draft.</p>}+ <div className="flex flex-wrap gap-3">+ {['draft', 'failed', 'generating'].includes(revision.status) && <button type="button" disabled={busy || disabled || dirty} onClick={() => action('generate')} className="min-h-[44px] text-sm text-port-accent">{revision.submitted ? 'Resume candidate downloads' : 'Generate with Suno — uses credits'}</button>}+ {revision.status !== 'selected' && revision.status !== 'canceled' && <button type="button" disabled={busy} onClick={() => action('cancel')} className="min-h-[44px] text-sm">Cancel song revision</button>}+ </div>+ <div className="grid min-w-0 grid-cols-1 gap-3 sm:grid-cols-2">+ {(revision.candidates || []).map((candidate, index) => <div key={`${revision.id}:${candidate.songId}`} className="min-w-0 space-y-2 rounded border border-port-border p-2">+ <a href={`https://suno.com/song/${encodeURIComponent(candidate.songId)}`} target="_blank" rel="noreferrer" className="text-sm text-port-accent">Suno candidate {formatCount(index + 1)}</a>+ <audio controls preload="none" src={trackAudioUrl(candidate.filename)} aria-label={`Listen to candidate ${index + 1}`} onPlay={() => setHeard((old) => ({ ...old, [`${revision.id}:${candidate.songId}`]: true }))} className="w-full" />+ <button type="button" disabled={busy || disabled || !settled || !heard[`${revision.id}:${candidate.songId}`]} onClick={() => action('select', { songId: candidate.songId })} className="min-h-[44px] text-sm text-port-accent">Use candidate {formatCount(index + 1)}</button>+ </div>)}+ </div>+ {revision.status === 'selected' && <div className="space-y-2 text-sm" role="status">+ <p>New master selected. Art and editable composition source are retained. Beat analysis, lyric alignment, shot timing, proofs and renders need fresh review.</p>+ <ol className="list-inside list-decimal space-y-1">+ <li>Analyze the new song and align its lyrics below; verify by listening.</li>+ <li><Link className="text-port-accent" to={`/music-video/${project.id}/board`}>Review shot timing and retained or revised art on the Board.</Link></li>+ <li><Link className="text-port-accent" to={`/music-video/${project.id}/compose`}>Regenerate or reimport the composition against the new audio.</Link> Imported source can contain a fuller timeline than the Board; revise that source too.</li>+ <li><Link className="text-port-accent" to={`/music-video/${project.id}/review`}>Rebuild and review proofs before the full video.</Link></li>+ </ol>+ </div>}+ </>}+ </>}+ {!!project.songRevisionHistory?.length && <details>+ <summary className="cursor-pointer py-2 text-sm">Previous song revision provenance</summary>+ <ul className="space-y-2 text-xs">{project.songRevisionHistory.map(previous => <li key={previous.id} className="rounded border border-port-border p-2">+ <p>{previous.fields?.title} · {previous.status}</p>+ <p className="whitespace-pre-wrap">{previous.fields?.style}</p>+ {previous.selectedSongId && <a className="text-port-accent" href={`https://suno.com/song/${encodeURIComponent(previous.selectedSongId)}`} target="_blank" rel="noreferrer">Selected Suno source</a>}+ </li>)}</ul>+ </details>}+ {error && <p role="alert" className="text-sm text-port-error">{error}</p>}+ </section>;+}diff --git a/client/src/components/musicVideo/SongRevisionPanel.test.jsx b/client/src/components/musicVideo/SongRevisionPanel.test.jsxnew file mode 100644index 0000000000..acfcd01221--- /dev/null+++ b/client/src/components/musicVideo/SongRevisionPanel.test.jsx@@ -0,0 +1,70 @@+import { useState } from 'react';+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';+import { MemoryRouter } from 'react-router';+import SongRevisionPanel from './SongRevisionPanel.jsx';+const socket = vi.hoisted(() => ({ on: vi.fn(), off: vi.fn() }));+const api = vi.hoisted(() => ({ save: vi.fn(), act: vi.fn(), get: vi.fn() }));+vi.mock('../../services/apiMusicVideo.js', () => ({ saveMusicVideoSongRevision: api.save, actOnMusicVideoSongRevision: api.act, getMusicVideoProject: api.get }));+vi.mock('../../services/socket', () => ({ default: socket }));+const fields = { title: 'Example song', style: 'Pop', lyrics: 'New morning', instrumental: false };+const base = { id: 'fork', parentProjectId: 'original', version: 2, songRevision: { id: 'rev', fields, status: 'draft', candidates: [] } };+function Harness({ initial = base }) {+ const [project, setProject] = useState(initial);+ return <MemoryRouter><SongRevisionPanel project={project} onUpdated={setProject} onFork={() => {}} /></MemoryRouter>;+}+beforeEach(() => { vi.clearAllMocks(); api.get.mockResolvedValue(base); });+describe('song revision UI', () => {+ it('gates generation on saving and selection on listening, then exposes the rebuild path', async () => {+ api.save.mockImplementation(async (_id, next) => ({ project: { ...base, songRevision: { ...base.songRevision, fields: { ...next, style: next.style.trim() } } } }));+ api.act.mockImplementation(async (_id, action) => ({ project: { ...base, songRevision: {+ ...base.songRevision, fields: { ...fields, lyrics: 'Edited morning' }, status: action === 'select' ? 'selected' : 'review',+ candidates: [{ songId: 'song-a', filename: 'example.m4a' }],+ } } }));+ render(<Harness />);+ expect(api.act).not.toHaveBeenCalled();+ fireEvent.change(screen.getByLabelText('Revision lyrics'), { target: { value: 'Edited morning' } });+ fireEvent.change(screen.getByLabelText('Suno musical style'), { target: { value: ' Pop ' } });+ expect(screen.getByRole('button', { name: /Generate with Suno/ })).toBeDisabled();+ fireEvent.click(screen.getByRole('button', { name: 'Save song draft' }));+ await waitFor(() => expect(screen.getByRole('button', { name: /Generate with Suno/ })).toBeEnabled());+ fireEvent.click(screen.getByRole('button', { name: /Generate with Suno/ }));+ const select = await screen.findByRole('button', { name: 'Use candidate 1' });+ expect(select).toBeDisabled(); fireEvent.play(screen.getByLabelText('Listen to candidate 1')); fireEvent.click(select);+ expect(await screen.findByText(/New master selected/)).toBeInTheDocument();+ expect(screen.getByRole('link', { name: /Regenerate or reimport/ })).toHaveAttribute('href', '/music-video/fork/compose');+ expect(api.act.mock.calls.map((call) => call[1])).toEqual(['generate', 'select']);+ });+ it('recovers a revision completed while Setup was closed and adopts its saved fields', async () => {+ api.get.mockResolvedValue({ ...base, songRevision: { ...base.songRevision, id: 'recovered', sequence: 5,+ fields: { ...fields, lyrics: 'Recovered lyrics' }, status: 'failed', submitted: true, songIds: ['take-a'] } });+ render(<Harness initial={{ ...base, songRevision: null }} />);+ await waitFor(() => expect(screen.getByLabelText('Revision lyrics')).toHaveValue('Recovered lyrics'));+ expect(screen.getByRole('button', { name: 'Resume candidate downloads' })).toBeEnabled();+ expect(api.act).not.toHaveBeenCalled();+ });+ it('does not adopt stale save fields after a newer revision arrives', async () => {+ const pending = Promise.withResolvers();+ api.save.mockReturnValue(pending.promise);+ render(<Harness />);+ fireEvent.change(screen.getByLabelText('Suno musical style'), { target: { value: ' Pop edited ' } });+ fireEvent.click(screen.getByRole('button', { name: 'Save song draft' }));+ const receive = socket.on.mock.calls.find(([event]) => event === 'music-video:song-revision')[1];+ act(() => receive({ projectId: base.id, project: { ...base, songRevision: { ...base.songRevision, sequence: 3, status: 'canceled' } } }));+ await act(async () => pending.resolve({ project: { ...base, songRevision: { ...base.songRevision, sequence: 2, fields: { ...fields, style: 'Pop edited' } } } }));+ expect(screen.getByLabelText('Suno musical style')).toHaveValue(' Pop edited ');+ expect(screen.getByText('Song revision: canceled')).toBeInTheDocument();+ });+ it('keeps a failed save dirty and cancels without selecting audio', async () => {+ api.save.mockRejectedValue(new Error('Save unavailable'));+ render(<Harness />);+ fireEvent.change(screen.getByLabelText('Suno musical style'), { target: { value: 'New style' } });+ fireEvent.click(screen.getByRole('button', { name: 'Save song draft' }));+ expect(await screen.findByRole('alert')).toHaveTextContent('Save unavailable');+ expect(screen.getByRole('button', { name: /Generate with Suno/ })).toBeDisabled();+ api.act.mockResolvedValue({ project: { ...base, songRevision: { ...base.songRevision, status: 'canceled' } } });+ fireEvent.click(screen.getByRole('button', { name: 'Cancel song revision' }));+ await screen.findByText('Song revision: canceled');+ expect(api.act).toHaveBeenCalledWith('fork', 'cancel', { revisionId: 'rev' }, { silent: true });+ });+});diff --git a/client/src/components/musicVideo/stages/SetupStage.jsx b/client/src/components/musicVideo/stages/SetupStage.jsxindex 2b72d3656c..d6f708a25b 100644--- a/client/src/components/musicVideo/stages/SetupStage.jsx+++ b/client/src/components/musicVideo/stages/SetupStage.jsx@@ -1,3 +1,4 @@+import SongRevisionPanel from '../SongRevisionPanel.jsx';import StyleReferencesPanel from '../StyleReferencesPanel.jsx';import AutoSizeTextarea from '../../ui/AutoSizeTextarea';import CreativeSetupPanel from '../CreativeSetupPanel.jsx';@@ -20,6 +21,7 @@ export default function SetupStage({ board }) {} = board;return (<>+ <SongRevisionPanel key={`song-${project.id}`} project={project} tracks={tracks} onUpdated={board.replaceProject} onFork={board.onForkSong} disabled={locked || renderBound || midiBound} /><CreativeSetupPanelkey={`creative-${project.id}`}project={project}diff --git a/client/src/hooks/useMusicVideoProductionReview.js b/client/src/hooks/useMusicVideoProductionReview.jsindex 1eb01a3c99..d1785e559c 100644--- a/client/src/hooks/useMusicVideoProductionReview.js+++ b/client/src/hooks/useMusicVideoProductionReview.js@@ -1,5 +1,5 @@import { useEffect, useRef, useState } from 'react';-import { getMusicVideoProductionReview, saveMusicVideoProductionDraft, prepareMusicVideoProductionReview,+import { importMusicVideoDocumentShots, getMusicVideoProductionReview, saveMusicVideoProductionDraft, prepareMusicVideoProductionReview,approveMusicVideoProductionReview, renderMusicVideoProductionProof, musicVideoExcerptRenderEventsUrl,cancelMusicVideoExcerptRender, importMusicVideoProductionPlanning, bindMusicVideoProductionShot, addMusicVideoProductionFeedback, resolveMusicVideoProductionFeedback } from '../services/apiMusicVideo.js';import useSseJobSlot from './useSseJobSlot.js';@@ -52,6 +52,7 @@ export default function useMusicVideoProductionReview({ project, replaceProjectreturn { readiness: state?.owner === project ? state.readiness : null, busy, error, proof,feedback: body => call(() => addMusicVideoProductionFeedback(project.id, { ...body, basis: state?.readiness.basis[body.stage] }, { silent: true })),resolveFeedback: (feedbackId, resolution, password) => call(() => resolveMusicVideoProductionFeedback(project.id, { feedbackId, resolution, password }, { silent: true })),+ importDocumentShots: body => call(() => importMusicVideoDocumentShots(project.id, body, { silent: true })),importPlanning: source => call(() => importMusicVideoProductionPlanning(project.id, source, { silent: true })),bindShot: shotId => call(() => bindMusicVideoProductionShot(project.id, shotId, { silent: true })),save: draft => call(() => saveMusicVideoProductionDraft(project.id, draft, { silent: true })),diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex cc7392ffa8..c274cc4a90 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -344,7 +344,7 @@ export default function MusicVideo() {.catch((err) => toast.error(err?.message || 'Failed to delete project'));};- const handleClone = (optionsOrTarget = {}, maybeOptions = {}) => {+ const handleClone = (optionsOrTarget = {}, maybeOptions = {}, songRevision = false) => {const isTarget = optionsOrTarget && typeof optionsOrTarget.id === 'string';const target = isTarget ? optionsOrTarget : selected;const options = isTarget ? maybeOptions : (optionsOrTarget || {});@@ -354,7 +354,7 @@ export default function MusicVideo() {cloneMusicVideoProject(target.id, options, { silent: true }).then((project) => {setProjects((prev) => [...prev, project]);- navigate(`/music-video/${project.id}`);+ navigate(`/music-video/${project.id}${songRevision === true ? "/setup" : ""}`);toast.success(`Created ${project.name}`);}).catch((err) => toast.error(err?.message || 'Failed to clone project'))@@ -807,6 +807,7 @@ export default function MusicVideo() {locked: creativeSetupPending || styleReferencesPending || compositionSavePending > 0,busy: { analyzing, planning, arranging, cloning },tracks,+ onForkSong: () => handleClone({}, {}, true),trackName,audioFilename,audioUrl,diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex 05b3e3eb3d..e03c8a71d4 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -347,6 +347,7 @@ beforeEach(() => {// Keep the real artifact iframe and src assertions without navigating to its API URL.window.happyDOM.settings.navigation.disableChildFrameNavigation = true;vi.clearAllMocks();+ getMusicVideoProject.mockImplementation(async id => (await listMusicVideoProjects()).find(project => project.id === id));sseState.latest = null;sseState.closed = false;ytSseStates.clear();diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 7ecebe0726..d718ffeaf3 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -444,3 +444,14 @@ export const bindMusicVideoProductionShot = (id, shotId, options = {}) => requesexport const addMusicVideoProductionFeedback = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/production-review/feedback`, { method: 'POST', body: JSON.stringify(body), ...options });export const resolveMusicVideoProductionFeedback = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/production-review/feedback/resolve`, { method: 'POST', body: JSON.stringify(body), ...options });+// Drafting is free; generation and candidate selection are separate explicit actions.+export const saveMusicVideoSongRevision = (id, fields, options = {}) => request(`/music-video/${encodeURIComponent(id)}/song-revision`, { method: 'POST', body: JSON.stringify(fields), ...options });+export const actOnMusicVideoSongRevision = (id, action, data, options = {}) => {+ const config = { method: 'POST', body: JSON.stringify(data), ...options };+ if (action === 'generate') return request(`/music-video/${encodeURIComponent(id)}/song-revision/generate`, config);+ if (action === 'cancel') return request(`/music-video/${encodeURIComponent(id)}/song-revision/cancel`, config);+ if (action === 'select') return request(`/music-video/${encodeURIComponent(id)}/song-revision/select`, config);+ return Promise.reject(new Error('Unknown song revision action'));+};++export const importMusicVideoDocumentShots = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/production-review/document-shots`, { method: 'POST', body: JSON.stringify(body), ...options });diff --git a/server/lib/musicVideoDependencies.js b/server/lib/musicVideoDependencies.jsindex afc2b81854..550f01660e 100644--- a/server/lib/musicVideoDependencies.js+++ b/server/lib/musicVideoDependencies.js@@ -30,9 +30,15 @@ const compositionRef = (project, startSec, endSec) => {return { role: 'composition', assetId: 'composition', revision: checksum({ mediaMode: project.mediaMode || null, composition: value }), startSec, endSec };};+const songRef = (project) => ({ role: 'song', assetId: 'master', revision: checksum({+ trackId: project.trackId ?? null, uploadedAudioFilename: project.uploadedAudioFilename ?? null,+ audioAnalysis: project.audioAnalysis ?? null, lyricCues: project.lyricCues || [],+ lyricMarkers: project.lyricMarkers || [], phrases: project.phrases || [],+}) });+/** Evidence tracks its rendered window, selected layers and transitive take inputs. */export function captureMusicVideoEvidence(project, { sceneIds = null, startSec = 0, endSec = 36000, composition = true } = {}) {- const references = [];+ const references = [songRef(project)];for (const scene of project.scenes || []) {if (sceneIds ? !sceneIds.includes(scene.sceneId) : !intersects(scene, startSec, endSec)) continue;references.push(layerRef(scene));@@ -56,17 +62,19 @@ export function musicVideoDependencyChanges(project, dependencies) {if (!dependencies || dependencies.version !== MUSIC_VIDEO_DEPENDENCY_VERSION || !Array.isArray(dependencies.references)) {return [{ role: 'unknown', reason: 'Dependency evidence was not recorded; review again' }];}- const changes = [];+ const changes = dependencies.references.some((ref) => ref.role === 'window') && !dependencies.references.some((ref) => ref.role === 'song')+ ? [{ role: 'song', reason: 'Song dependency evidence was not recorded; review again' }] : [];for (const ref of dependencies.references) {let current;const scene = (project.scenes || []).find((entry) => entry.sceneId === ref.sceneId);- if (ref.role === 'window') current = { assetId: 'scene-set', revision: checksum((project.scenes || []).filter((scene) => intersects(scene, ref.startSec, ref.endSec)).map((scene) => scene.sceneId).sort()) };+ if (ref.role === 'song') current = songRef(project);+ else if (ref.role === 'window') current = { assetId: 'scene-set', revision: checksum((project.scenes || []).filter((scene) => intersects(scene, ref.startSec, ref.endSec)).map((scene) => scene.sceneId).sort()) };else if (ref.role === 'composition') current = compositionRef(project, ref.startSec, ref.endSec);else if (!scene) current = null;else if (slots[ref.role]) current = assetRef(scene, ref.role);else if (ref.role === 'layer') current = layerRef(scene);if (!current || current.assetId !== ref.assetId || current.revision !== ref.revision) {- changes.push({ ...ref, reason: `${ref.role === 'plate' ? 'Selected plate or its crop/mask inputs' : ref.role === 'clip' ? 'Selected clip' : ref.role === 'layer' ? 'Shot timing or composition layer' : 'Composition'} changed` });+ changes.push({ ...ref, reason: `${ref.role === 'song' ? 'Master audio, lyrics or alignment' : ref.role === 'plate' ? 'Selected plate or its crop/mask inputs' : ref.role === 'clip' ? 'Selected clip' : ref.role === 'layer' ? 'Shot timing or composition layer' : 'Composition'} changed` });}}return changes;diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex e8e502be45..0cb769e896 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -11,6 +11,13 @@ import { MUSIC_VIDEO_GRADE_PRESETS, MUSIC_VIDEO_GRADE_MAX_GRAIN } from './musicV*/import { z } from 'zod';++export const musicVideoSongDraftSchema = z.object({+ title: z.string().trim().min(1).max(80), style: z.string().trim().min(1).max(1000),+ lyrics: z.string().max(5000), instrumental: z.boolean().default(false),+}).strict().refine((v) => v.instrumental || v.lyrics.trim().length > 0, 'Lyrics are required for a vocal song');+export const musicVideoSongActionSchema = z.object({ revisionId: z.string().min(1) }).strict();+export const musicVideoSongSelectSchema = z.object({ revisionId: z.string().min(1), songId: z.string().min(1) }).strict();import { EFFORT_LEVELS } from './providerModels.js';import { shotActionContractProblem } from './musicVideoActionContract.js';import { NARRATIVE_EVENT_KINDS } from './musicVideoNarrativeEvents.js';@@ -976,6 +983,7 @@ export const musicVideoProjectCloneSchema = z.object({// Review content is editable; approval records are server-owned and never PATCHable.export const musicVideoProductionDraftSchema = z.object({+ storyboardSource: z.enum(['board', 'document']).optional(),cast: z.string().max(12000), environments: z.string().max(12000),visualLanguage: z.string().max(12000), motionLanguage: z.string().max(12000),implementationPlan: z.string().max(16000).optional(),@@ -990,6 +998,20 @@ export const musicVideoProductionDraftSchema = z.object({camera: z.string().max(4000), transition: z.string().max(4000),}).strict()).max(2000),}).strict();+export const musicVideoDocumentShotsSchema = z.object({+ documentDirectory: z.string().min(1).max(500), audioBasis: z.string().min(1).max(128),+ sourceFile: z.string().min(1).max(200),+ shots: musicVideoProductionDraftSchema.shape.storyboard.min(1),+}).strict().superRefine((value, ctx) => {+ const ids = new Set();+ for (const shot of value.shots) {+ if (!shot.id?.trim() || ids.has(shot.id) || shot.sceneId != null+ || !Number.isFinite(shot.startSec) || !(shot.endSec > shot.startSec)) {+ ctx.addIssue({ code: 'custom', message: 'Document shots need unique source IDs, positive timing and no Board scene binding' });+ }+ ids.add(shot.id);+ }+});export const musicVideoProductionImportSchema = z.object({ source: z.string().min(2).max(250000) }).strict();export const musicVideoProductionApprovalSchema = z.object({stage: z.enum(['art', 'storyboard', 'proof']), basis: z.string().min(1).max(128),diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.jsindex 8ccf16adf3..9283253c46 100644--- a/server/lib/socketEventContracts.js+++ b/server/lib/socketEventContracts.js@@ -44,6 +44,10 @@ const loomRunSnapshot = (production) => Object.freeze({});export const SOCKET_EVENT_CONTRACTS = Object.freeze({+ 'music-video:song-revision': {+ direction: 'server-to-client', summary: 'A song revision changed; apply the persisted project snapshot.',+ payloadSchema: { type: 'object', required: ['projectId', 'project'], properties: { projectId: { type: 'string' }, project: { type: 'object' } } },+ },'voice-studio:changed': {direction: 'server-to-client', summary: 'Voice library or runtime setup changed; refetch authenticated state.',payloadSchema: { type: 'object', properties: {}, additionalProperties: false },diff --git a/server/lib/syncWire.js b/server/lib/syncWire.jsindex 7a507bfe70..981d225f89 100644--- a/server/lib/syncWire.js+++ b/server/lib/syncWire.js@@ -60,6 +60,7 @@ export function stripMusicVideoLocalRenderPins(record, { stripVideoBackend = truautonomousRun: _autonomousRun,// Render diagnostics describe a job on this machine, never a peer job.renderError: _renderError,+ songRevision: _songRevision, songRevisionHistory: _songRevisionHistory,...shared} = record;// A composition document names a folder on this install onlydiff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 9ef88f32cc..447a20c639 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -219,6 +219,31 @@ router.post('/', asyncHandler(async (req, res) => {res.status(201).json(project);}));+router.post('/:id/song-revision', asyncHandler(async (req, res) => {+ const { musicVideoSongDraftSchema } = await import('../lib/musicVideoValidation.js');+ const fields = validateRequest(musicVideoSongDraftSchema, req.body);+ const { saveSongRevision } = await import('../services/musicVideo/songRevision.js');+ res.json(await saveSongRevision(req.params.id, fields));+}));+router.post('/:id/song-revision/generate', asyncHandler(async (req, res) => {+ const { musicVideoSongActionSchema } = await import('../lib/musicVideoValidation.js');+ const { revisionId } = validateRequest(musicVideoSongActionSchema, req.body);+ const { generateSongRevision } = await import('../services/musicVideo/songRevision.js');+ res.status(202).json(await generateSongRevision(req.params.id, revisionId));+}));+router.post('/:id/song-revision/cancel', asyncHandler(async (req, res) => {+ const { musicVideoSongActionSchema } = await import('../lib/musicVideoValidation.js');+ const { revisionId } = validateRequest(musicVideoSongActionSchema, req.body);+ const { cancelSongRevision } = await import('../services/musicVideo/songRevision.js');+ res.json(await cancelSongRevision(req.params.id, revisionId));+}));+router.post('/:id/song-revision/select', asyncHandler(async (req, res) => {+ const { musicVideoSongSelectSchema } = await import('../lib/musicVideoValidation.js');+ const { revisionId, songId } = validateRequest(musicVideoSongSelectSchema, req.body);+ const { selectSongRevision } = await import('../services/musicVideo/songRevision.js');+ res.json(await selectSongRevision(req.params.id, revisionId, songId));+}));+router.post('/:id/clone', asyncHandler(async (req, res) => {const options = validateRequest(musicVideoProjectCloneSchema, req.body || {});res.status(201).json(await cloneProject(req.params.id, options));@@ -315,7 +340,7 @@ router.post('/:id/analyze/manual', asyncHandler(async (req, res) => {if (!analysis) {throw new ServerError('Could not analyze audio (decode failed or ffmpeg unavailable)', { status: 422, code: 'ANALYZE_FAILED' });}- const updated = await setProjectAnalysis(project.id, analysis);+ const updated = await setProjectAnalysis(project.id, analysis, project);res.json(updated);}));@@ -483,6 +508,13 @@ router.post('/:id/production-review/feedback/resolve', asyncHandler(async (req,router.get('/:id/production-review', asyncHandler(async (req, res) => {res.json(await getProductionReview(req.params.id));}));+router.post('/:id/production-review/document-shots', asyncHandler(async (req, res) => {+ const { musicVideoDocumentShotsSchema } = await import('../lib/musicVideoValidation.js');+ const input = validateRequest(musicVideoDocumentShotsSchema, req.body);+ const { importDocumentShots } = await import('../services/musicVideo/productionReviewService.js');+ res.json(await importDocumentShots(req.params.id, input));+}));+router.post('/:id/production-review/import', asyncHandler(async (req, res) => {const { source } = validateRequest(musicVideoProductionImportSchema, req.body);res.json(await importProductionPlanning(req.params.id, source));diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.jsindex 27760e9026..93f9dc5418 100644--- a/server/routes/musicVideo.test.js+++ b/server/routes/musicVideo.test.js@@ -444,7 +444,7 @@ describe('musicVideo routes', () => {const r = await request(app).post('/api/music-video/mv-1/analyze');expect(r.status).toBe(200);expect(r.body.audioAnalysis).toEqual(analysis);- expect(svc.setProjectAnalysis).toHaveBeenCalledWith('mv-1', analysis);+ expect(svc.setProjectAnalysis).toHaveBeenCalledWith('mv-1', analysis, { id: 'mv-1', trackId: 't1' });});});@@ -480,7 +480,7 @@ describe('musicVideo routes', () => {expect(r.status).toBe(200);expect(r.body.audioAnalysis).toEqual(analysis);expect(analyzeAudioFileManual).toHaveBeenCalledWith(expect.stringContaining('song.wav'), { bpm: 128, offsetSec: 0.25 });- expect(svc.setProjectAnalysis).toHaveBeenCalledWith('mv-1', analysis);+ expect(svc.setProjectAnalysis).toHaveBeenCalledWith('mv-1', analysis, { id: 'mv-1', trackId: 't1' });});it('skips the ffmpeg decode and reuses cached sections/durationSec when a prior analysis exists', async () => {diff --git a/server/routes/musicVideoProductionReview.test.js b/server/routes/musicVideoProductionReview.test.jsindex 1f9edbf073..7c3413b83e 100644--- a/server/routes/musicVideoProductionReview.test.js+++ b/server/routes/musicVideoProductionReview.test.js@@ -18,6 +18,8 @@ vi.mock('../services/promptRunner.js', () => ({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 () => ({})) }));+const planner = vi.hoisted(() => vi.fn());+vi.mock('../services/musicVideo/planner.js', () => ({ planProject: planner }));const auth = vi.hoisted(() => ({ enabled: true }));vi.mock('../services/auth.js', () => ({ isAuthEnabled: async () => auth.enabled, verifyPassword: async password => password === 'synthetic-operator-password' }));vi.mock('../services/musicVideo/excerptRender.js', async original => ({ ...await original(),@@ -279,3 +281,68 @@ describe('human-reviewed Music Video workflow', () => {expect((await request(app).post(`${base}/publish/youtube/prepare`).send({ approved: true })).status).toBe(403);});});++describe('document-bound storyboard revision', () => {+ it('preserves a document manifest imported while Board preparation is in flight', async () => {+ const { importDocumentTemplate } = await import('../services/musicVideo/compositionDocument.js');+ const imported = await importDocumentTemplate(project.id, 'layered');+ await store.mutateProjectRecord(project.id, current => ({ project: { ...current, scenes: [] } }));+ await approve('art');+ const entered = Promise.withResolvers();+ const held = Promise.withResolvers();+ planner.mockImplementationOnce(async () => {+ await store.addProjectScene(project.id, { label: 'Board row', startSec: 0, endSec: 20 });+ entered.resolve(); await held.promise;+ });+ const preparing = Promise.resolve(request(app).post(`${base}/production-review/prepare`).send({}));+ await entered.promise;+ const shots = [{ id: 'authored-shot', sceneId: null, startSec: 0, endSec: 20, lyricCueIds: ['line-a'],+ action: 'Open door', staging: 'Left', camera: 'Track', transition: 'Cut' }];+ const audioBasis = (await read()).body.readiness.documentShotImport.audioBasis;+ expect((await request(app).post(`${base}/production-review/document-shots`).send({+ documentDirectory: imported.document.directory, audioBasis, sourceFile: 'engine.js', shots,+ })).status).toBe(200);+ held.resolve();+ expect((await preparing).body.project.productionReview.draft.storyboard).toEqual(shots);+ });+ it('requires real source shots, preserves Board rows, and invalidates document, shot and master changes', async () => {+ const { importDocumentTemplate } = await import('../services/musicVideo/compositionDocument.js');+ const imported = await importDocumentTemplate(project.id, 'layered');+ const documentDirectory = imported.document.directory;+ const shots = [+ { id: 'authored-intro', sceneId: null, startSec: 0, endSec: 10, lyricCueIds: ['line-a'], action: 'Open doorway', staging: 'Figure left', camera: 'Dolly', transition: 'Cut' },+ { id: 'authored-outro', sceneId: null, startSec: 10, endSec: 20, lyricCueIds: [], action: 'Cross doorway', staging: 'Figure center', camera: 'Track', transition: 'Fade' },+ ];+ const audioBasis = (await read()).body.readiness.documentShotImport.audioBasis;+ const bind = body => request(app).post(`${base}/production-review/document-shots`).send({ audioBasis, ...body });+ await save({ ...draft, storyboardSource: 'document', storyboard: [] });+ await approve('art');+ expect((await approve('storyboard')).status).toBe(409);+ expect((await bind({ documentDirectory, sourceFile: 'missing.js', shots })).status).toBe(404);+ expect((await bind({ documentDirectory, sourceFile: 'engine.js', shots: [shots[0], shots[0]] })).status).toBe(400);+ const bound = await bind({ documentDirectory, sourceFile: 'engine.js', shots });+ expect(bound.status).toBe(200);+ expect(bound.body.project.scenes).toHaveLength(1);+ expect(bound.body.project.productionReview.draft.storyboard).toHaveLength(2);+ const prepared = await request(app).post(`${base}/production-review/prepare`).send({});+ expect(prepared.body.project.productionReview.draft.storyboard).toEqual(shots);+ expect((await request(app).post(`${base}/production-review/shots/authored-intro/bind`).send({})).status).toBe(409);+ expect((await approve('storyboard')).status).toBe(200);+ const accepted = await read();+ const oldBasis = accepted.body.readiness.basis.storyboard;+ await save({ ...bound.body.project.productionReview.draft, storyboard: shots.map((s, i) => i ? s : { ...s, camera: 'New track' }) });+ expect((await approve('storyboard')).status).toBe(409);+ await bind({ documentDirectory, sourceFile: 'engine.js', shots });+ expect((await approve('storyboard')).status).toBe(200);+ await importDocumentTemplate(project.id, 'layered');+ expect((await approve('storyboard')).status).toBe(409);+ expect((await bind({ documentDirectory, sourceFile: 'engine.js', shots })).status).toBe(409);+ const latest = await store.getProject(project.id);+ await bind({ documentDirectory: latest.composition.document.directory, sourceFile: 'engine.js', shots });+ await store.updateProject(project.id, { uploadedAudioFilename: 'new-master.wav' });+ expect((await approve('storyboard', { basis: oldBasis })).status).toBe(409);+ expect((await bind({ documentDirectory: latest.composition.document.directory, sourceFile: 'engine.js', shots })).status).toBe(409);+ expect((await read()).body.readiness.storyboard.problems.join(' ')).toContain('current authored document');+ expect((await request(app).post(`${base}/render`).send({})).status).toBe(409);+ });+});diff --git a/server/routes/musicVideoSongRevision.browser.test.js b/server/routes/musicVideoSongRevision.browser.test.jsnew file mode 100644index 0000000000..12d9a59abb--- /dev/null+++ b/server/routes/musicVideoSongRevision.browser.test.js@@ -0,0 +1,149 @@+/** Real UI, HTTP persistence and sockets; Suno only is a test double. */+import { afterAll, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { Server } from 'socket.io';+import { existsSync } from 'node:fs';+import { mkdir, writeFile, symlink } from 'node:fs/promises';+import { join, resolve } from 'node:path';+import { spawn } from 'node:child_process';+import { createRequire } from 'node:module';+import { chromium } from 'playwright-core';+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-song-browser-') }));+vi.mock('../services/settings.js', () => ({ getSettings: async () => ({}) }));+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 client = resolve(import.meta.dirname, '../../client');+const requireClient = createRequire(join(client, 'package.json'));+let bundler;+try { bundler = ['vite', '@vitejs/plugin-react', '@tailwindcss/postcss'].map(name => requireClient.resolve(name)); }+catch (err) { if (err.code !== 'MODULE_NOT_FOUND') throw err; }+const canRun = Boolean(chrome && bundler);+// Prerequisite discovery may initialize mocked paths; skipped suites have no cleanup hooks.+if (!canRun) cleanupTempDataRoots();+let browser, proc, server, io, songs, musicVideoEvents;+const broadcast = event => io.emit('music-video:song-revision', event);+afterAll(async () => {+ musicVideoEvents?.off('song-revision', broadcast);+ await songs?.__testing.settle(); songs?.__setSongRevisionDepsForTests();+ await _cleanupTestBrowser({ browser, proc, cleanup: () => {} });+ if (io) await new Promise(resolve => io.close(resolve));+ else if (server) await new Promise(resolve => server.close(resolve));+ cleanupTempDataRoots();+});++describe.skipIf(!canRun)('song revision in Chrome (client dependencies required)', () => {+ it('forks, edits, generates, listens and selects without altering the previous version', async () => {+ // Load data-owning modules only when this browser workflow will actually run.+ const { PATHS } = await import('../lib/paths.js');+ const { default: router } = await import('./musicVideo.js');+ const store = await import('../services/musicVideo/projects.js');+ songs = await import('../services/musicVideo/songRevision.js');+ ({ musicVideoEvents } = await import('../services/musicVideo/events.js'));+ await mkdir(PATHS.music, { recursive: true });+ const wav = Buffer.alloc(44 + 32000);+ wav.write('RIFF'); wav.writeUInt32LE(wav.length - 8, 4); wav.write('WAVEfmt ', 8); wav.writeUInt32LE(16, 16);+ wav.writeUInt16LE(1, 20); wav.writeUInt16LE(1, 22); wav.writeUInt32LE(16000, 24); wav.writeUInt32LE(32000, 28);+ wav.writeUInt16LE(2, 32); wav.writeUInt16LE(16, 34); wav.write('data', 36); wav.writeUInt32LE(32000, 40);+ for (let i = 0; i < 16000; i++) wav.writeInt16LE(Math.round(Math.sin(i * Math.PI * 440 / 16000) * 1000), 44 + i * 2);+ await writeFile(join(PATHS.music, 'synthetic.wav'), wav);+ const original = await store.createProject({ name: 'Example film', uploadedAudioFilename: 'original.wav', composition: { mode: 'code' } });+ await store.updateProject(original.id, { lyricCues: [{ id: 'line', text: 'Old lyric' }] });+ await store.mutateProjectRecord(original.id, p => ({ project: { ...p, productionReview: { draft: {+ cast: 'Figure', environments: 'Room', visualLanguage: 'Paper', motionLanguage: 'Walk', guideArtifactId: null,+ lyricsMode: 'vocal', timingStatus: 'provisional', timingNotes: '', storyboard: [],+ } } } }));+ const before = await store.getProject(original.id);+ let creates = 0;+ let generationMode = 'success';+ songs.__setSongRevisionDepsForTests({ generate: async (_fields, opts) => {+ if (!opts.songIds) { creates++; await opts.onSubmitted(['candidate-a', 'candidate-b']); }+ if (generationMode === 'failed') throw new Error('Synthetic download failure');+ if (generationMode === 'held') await new Promise((_, reject) => opts.signal.addEventListener('abort', () => reject(new Error('Canceled')), { once: true }));+ return { songId: opts.songIds?.[0] || 'candidate-b', filename: 'synthetic.wav' };+ } });+ const ui = join(PATHS.data, 'ui'); await mkdir(ui, { recursive: true });+ await symlink(join(client, 'node_modules'), join(ui, 'node_modules'), 'dir');+ const entry = `import React,{useState} from 'react';import{createRoot}from'react-dom/client';import{BrowserRouter,useNavigate}from'react-router';import Panel from '${client}/src/components/musicVideo/SongRevisionPanel.jsx';import ReviewPanel from '${client}/src/components/musicVideo/ProductionReviewPanel.jsx';import useReview from '${client}/src/hooks/useMusicVideoProductionReview.js';import{cloneMusicVideoProject}from'${client}/src/services/apiMusicVideo.js';function App(){const[p,setP]=useState(${JSON.stringify(before)});const nav=useNavigate();const review=useReview({project:p,replaceProject:setP});return <main style={{maxWidth:1000,margin:'auto',padding:20}}><Panel key={p.id} project={p} onUpdated={setP} onFork={()=>cloneMusicVideoProject(p.id).then(next=>{setP(next);nav('/music-video/'+next.id+'/setup')})}/><ReviewPanel key={'review-'+p.id} project={p} review={review} onOpenArtifact={()=>{}}/></main>}createRoot(document.getElementById('root')).render(<BrowserRouter><App/></BrowserRouter>);`;+ await writeFile(join(ui, 'entry.jsx'), `import ${JSON.stringify(join(client, 'src/index.css'))};\n` + entry);+ 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>');+ const { build } = await import(bundler[0]); const { default: react } = await import(bundler[1]); const { default: tailwind } = await import(bundler[2]);+ await build({ configFile: false, root: ui, plugins: [react()], css: { postcss: { plugins: [tailwind({ base: client })] } }, build: { outDir: join(ui, 'dist') }, logLevel: 'warn' });+ const app = express(); app.use(express.json()); app.use('/api/music-video', router); app.use('/data/music', express.static(PATHS.music)); 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)); });+ io = new Server(server); musicVideoEvents.on('song-revision', broadcast);+ proc = spawn(chrome, _testChromeCaptureArgs(join(PATHS.data, 'chrome')), { stdio: ['ignore', 'ignore', 'pipe'] });+ browser = await chromium.connectOverCDP(await _waitForTestChrome(proc));+ const page = await browser.newPage({ viewport: { width: 1000, height: 900 } });+ const errors = []; page.on('pageerror', e => errors.push(e.message));+ await page.goto(`http://127.0.0.1:${server.address().port}`);+ await page.getByRole('button', { name: 'Fork & revise song' }).click();+ await page.getByLabel('Suno musical style').fill('Bright synth pop');+ await page.getByLabel('Revision lyrics').fill('[Verse]\nNew lyric');+ await page.getByRole('button', { name: 'Save song draft' }).click();+ await page.getByText('Song revision: draft', { exact: true }).waitFor(); expect(creates).toBe(0);+ await page.getByRole('button', { name: 'Generate with Suno — uses credits' }).click();+ await page.getByText('Song revision: review', { exact: true }).waitFor();+ expect(await page.getByRole('button', { name: 'Use candidate 1' }).isDisabled()).toBe(true);+ await page.getByLabel('Listen to candidate 1').evaluate(audio => audio.play());+ await page.getByRole('button', { name: 'Use candidate 1' }).click();+ await page.getByText('Song revision: selected', { exact: true }).waitFor(); expect(creates).toBe(1);+ const selected = await store.getProject(new URL(page.url()).pathname.split('/')[2]);+ expect(selected).toMatchObject({ uploadedAudioFilename: 'synthetic.wav', audioAnalysis: null, trackId: null });+ expect(selected.lyricCues[0].text).toBe('New lyric'); expect(await store.getProject(original.id)).toEqual(before);+ const { importDocumentTemplate } = await import('../services/musicVideo/compositionDocument.js');+ const { productionAlignmentBasis } = await import('../services/musicVideo/productionReview.js');+ const doc = await importDocumentTemplate(selected.id, 'layered');+ musicVideoEvents.emit('song-revision', { projectId: selected.id, project: doc.project });+ await page.getByText('Edit visual guide and storyboard', { exact: true }).click();+ const manifest = { documentDirectory: doc.document.directory, audioBasis: productionAlignmentBasis(doc.project), sourceFile: 'engine.js',+ shots: [{ id: 'authored-shot', sceneId: null, startSec: 0, endSec: 1, lyricCueIds: [], action: 'Open door', staging: 'Figure left', camera: 'Track', transition: 'Cut' }] };+ const upload = () => page.getByLabel('Import document shot manifest', { exact: true }).setInputFiles({ name: 'shots.json', mimeType: 'application/json', buffer: Buffer.from(JSON.stringify(manifest)) });+ await upload();+ await page.getByText('authored-shot — document source shot', { exact: true }).waitFor();+ expect(await page.getByRole('button', { name: 'Prepare planning draft with autopilot' }).isDisabled()).toBe(true);+ const replacement = await importDocumentTemplate(selected.id, 'layered');+ musicVideoEvents.emit('song-revision', { projectId: selected.id, project: replacement.project });+ await page.waitForFunction(directory => document.body.textContent.includes(directory), replacement.document.directory);+ await upload();+ await page.getByRole('alert').filter({ hasText: 'composition version changed' }).waitFor();+ expect((await store.getProject(selected.id)).productionReview.documentStoryboard.directory).toBe(doc.document.directory);++ const priorVersion = await store.getProject(selected.id);+ await page.getByRole('button', { name: 'Fork & revise song' }).click();+ await page.getByLabel('Revision lyrics').fill('Another revision');+ await page.getByRole('button', { name: 'Save song draft' }).click();+ await page.getByText('Song revision: draft', { exact: true }).waitFor();+ generationMode = 'failed';+ await page.getByRole('button', { name: 'Generate with Suno — uses credits' }).click();+ await page.getByText('Song revision: failed', { exact: true }).waitFor();+ expect(creates).toBe(2);+ generationMode = 'success';+ await page.getByRole('button', { name: 'Resume candidate downloads' }).click();+ await page.getByText('Song revision: review', { exact: true }).waitFor();+ expect(creates).toBe(2);+ await page.getByRole('button', { name: 'Cancel song revision' }).click();+ await page.getByText('Song revision: canceled', { exact: true }).waitFor();+ await page.getByLabel('Revision lyrics').fill('Cancel this pending generation');+ await page.getByRole('button', { name: 'Save song draft' }).click();+ await page.getByText('Song revision: draft', { exact: true }).waitFor();+ generationMode = 'held';+ await page.getByRole('button', { name: 'Generate with Suno — uses credits' }).click();+ await page.getByText('Song revision: generating', { exact: true }).waitFor();+ await page.getByRole('button', { name: 'Cancel song revision' }).click();+ await page.getByText('Song revision: canceled', { exact: true }).waitFor();+ await songs.__testing.settle();+ const lastVersion = await store.getProject(new URL(page.url()).pathname.split('/')[2]);+ expect(lastVersion.uploadedAudioFilename).toBe('synthetic.wav');+ expect(lastVersion.songRevisionHistory.at(-1).status).toBe('canceled');+ expect(await store.getProject(selected.id)).toEqual(priorVersion);+ expect(await store.getProject(original.id)).toEqual(before);++ for (const width of [1000, 360]) {+ await page.setViewportSize({ width, height: 900 });+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);+ }+ expect(errors).toEqual([]);+ }, 60000);+});diff --git a/server/routes/musicVideoSongRevision.test.js b/server/routes/musicVideoSongRevision.test.jsnew file mode 100644index 0000000000..850885b104--- /dev/null+++ b/server/routes/musicVideoSongRevision.test.js@@ -0,0 +1,134 @@+import { describe, it, expect, vi, afterAll, afterEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';++vi.mock('../lib/paths.js', async (original) => makePathsProxy(await original(), { dataRoot: () => lazyTempDataRoot('mv-song-revision-test-') }));+vi.mock('../services/settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));+const analyzers = vi.hoisted(() => ({ auto: vi.fn(), manual: vi.fn() }));+vi.mock('../services/musicVideo/audioAnalysis.js', async (original) => ({ ...(await original()), analyzeAudioFile: analyzers.auto, analyzeAudioFileManual: analyzers.manual }));+const { default: routes } = await import('./musicVideo.js');+const store = await import('../services/musicVideo/projects.js');+const service = await import('../services/musicVideo/songRevision.js');+const { captureMusicVideoEvidence } = await import('../lib/musicVideoDependencies.js');+const { stripMusicVideoLocalRenderPins } = await import('../lib/syncWire.js');+const app = express();+app.use(express.json()); app.use('/api/music-video', routes); app.use(errorMiddleware);+const fields = { title: 'Example song', style: 'Bright synth pop', lyrics: '[Verse]\nA new morning', instrumental: false };+const post = (id, action = '', body = {}) => request(app).post(`/api/music-video/${id}/song-revision${action ? `/${action}` : ''}`).send(body);+async function fixture() {+ const source = await store.createProject({ name: 'Example video', uploadedAudioFilename: 'original.m4a', composition: { mode: 'code' } });+ await store.mutateProjectRecord(source.id, (p) => {+ const project = { ...p, status: 'complete', lyricCues: [{ id: 'cue-a', text: 'Old morning', startSec: 1, endSec: 2 }],+ scenes: [{ sceneId: 'scene-a', referenceImageId: 'art.png', visualLayer: 'still', startSec: 0, endSec: 20, beatAligned: true }],+ renderHistoryId: 'old-render', audioAnalysis: { durationSec: 20 },+ };+ project.excerpts = [{ id: 'proof-a', status: 'complete', startSec: 0, endSec: 10, dependencies: captureMusicVideoEvidence(project) }];+ return { project };+ });+ const before = await store.getProject(source.id);+ const fork = await store.cloneProject(source.id);+ const draft = await post(fork.id, '', fields);+ expect(draft.status).toBe(200);+ return { before, fork, revisionId: draft.body.project.songRevision.id };+}+afterEach(async () => { await service.__testing.settle(); service.__setSongRevisionDepsForTests(); });+afterAll(cleanupTempDataRoots);++describe('fork song revision through HTTP', () => {+ it('keeps source and shared art intact, selects only explicit candidates and marks old proof evidence stale', async () => {+ const { before, fork, revisionId } = await fixture();+ const generate = vi.fn(async (_fields, opts) => {+ if (!opts.songIds) await opts.onSubmitted(['take-a', 'take-b']);+ const songId = opts.songIds?.[0] || 'take-b';+ return { songId, filename: `${songId}.m4a` };+ });+ service.__setSongRevisionDepsForTests({ generate });+ expect((await post(before.id, '', fields)).status).toBe(409);+ expect((await post(fork.id, '', { ...fields, unknown: true })).status).toBe(400);+ expect(generate).not.toHaveBeenCalled();+ expect((await post(fork.id, 'generate', { revisionId })).status).toBe(202);+ await service.__testing.settle();+ const pending = await store.getProject(fork.id);+ expect(pending.uploadedAudioFilename).toBe('original.m4a');+ expect(pending.songRevision.status).toBe('review');+ expect(pending.songRevision.candidates).toHaveLength(2);+ expect((await post(fork.id, 'select', { revisionId, songId: 'unknown' })).status).toBe(409);+ const selected = await post(fork.id, 'select', { revisionId, songId: 'take-a' });+ expect(selected.status).toBe(200);+ expect(selected.body.project).toMatchObject({ uploadedAudioFilename: 'take-a.m4a', trackId: null, audioAnalysis: null, status: 'draft' });+ expect(selected.body.project.lyricCues[0]).toMatchObject({ text: 'A new morning', startSec: null });+ expect(selected.body.project.scenes[0]).toMatchObject({ referenceImageId: 'art.png', beatAligned: false });+ expect(selected.body.project.excerpts[0].dependencyState.status).toBe('stale');+ expect(await store.getProject(before.id)).toEqual(before);+ expect((await post(fork.id, 'select', { revisionId, songId: 'take-b' })).status).toBe(409);+ const next = await store.cloneProject(fork.id);+ expect(next.songRevision).toBeNull();+ expect(next.songRevisionHistory.at(-1).selectedSongId).toBe('take-a');+ expect(stripMusicVideoLocalRenderPins(pending)).not.toHaveProperty('songRevision');+ });++ it.each(['auto', 'manual'])('rejects %s analysis completing after a new candidate is selected', async (kind) => {+ const { fork, revisionId } = await fixture();+ await store.mutateProjectRecord(fork.id, (p) => ({ project: { ...p, audioAnalysis: null } }));+ service.__setSongRevisionDepsForTests({ generate: async (_fields, opts) => {+ await opts.onSubmitted(['take-new']);+ return { songId: 'take-new', filename: 'take-new.m4a' };+ } });+ await post(fork.id, 'generate', { revisionId }); await service.__testing.settle();+ const entered = Promise.withResolvers();+ const held = Promise.withResolvers();+ analyzers[kind].mockImplementationOnce(async () => { entered.resolve(); return held.promise; });+ const analysisRequest = Promise.resolve(request(app).post(`/api/music-video/${fork.id}/analyze${kind === 'manual' ? '/manual' : ''}`).send({ bpm: 120 }));+ await entered.promise;+ expect((await post(fork.id, 'select', { revisionId, songId: 'take-new' })).status).toBe(200);+ held.resolve({ bpm: 120, beats: [0], downbeats: [0], sections: [], durationSec: 20 });+ const stale = await analysisRequest;+ expect(stale.status).toBe(409);+ expect(stale.body.code).toBe('MUSIC_VIDEO_AUDIO_CHANGED');+ expect((await store.getProject(fork.id)).audioAnalysis).toBeNull();+ });++ it('retries downloads without repeating Create and cancels without changing master', async () => {+ const { fork, revisionId } = await fixture();+ let fail = true;+ let submissions = 0;+ service.__setSongRevisionDepsForTests({ generate: async (_fields, opts) => {+ if (!opts.songIds) { submissions++; await opts.onSubmitted(['take-a', 'take-b']); }+ if (fail) throw new Error('download failed');+ return { songId: opts.songIds[0], filename: `${opts.songIds[0]}.m4a` };+ } });+ await post(fork.id, 'generate', { revisionId }); await service.__testing.settle();+ expect((await store.getProject(fork.id)).songRevision.status).toBe('failed');+ fail = false;+ await post(fork.id, 'generate', { revisionId }); await service.__testing.settle();+ expect(submissions).toBe(1);+ expect((await post(fork.id, 'cancel', { revisionId })).status).toBe(200);+ expect((await store.getProject(fork.id)).uploadedAudioFilename).toBe('original.m4a');+ const next = await post(fork.id, '', { ...fields, lyrics: 'Another morning' });+ expect(next.status).toBe(200);+ expect(next.body.project.songRevisionHistory.at(-1).status).toBe('canceled');+ expect((await post(fork.id, 'generate', { revisionId })).status).toBe(409);+ });++ it('refuses concurrent generation, stops a late completion after cancel and refuses ambiguous resubmission', async () => {+ const { fork, revisionId } = await fixture();+ const held = Promise.withResolvers();+ const entered = Promise.withResolvers();+ service.__setSongRevisionDepsForTests({ generate: async (_fields, opts) => {+ await opts.onSubmitted(['take-a']); entered.resolve(); await held.promise;+ return { songId: 'take-a', filename: 'take-a.m4a' };+ } });+ await post(fork.id, 'generate', { revisionId }); await entered.promise;+ expect((await post(fork.id, 'generate', { revisionId })).status).toBe(409);+ await post(fork.id, 'cancel', { revisionId }); held.resolve(); await service.__testing.settle();+ expect((await store.getProject(fork.id)).songRevision).toMatchObject({ status: 'canceled', candidates: [] });+ const next = await post(fork.id, '', fields);+ const newId = next.body.project.songRevision.id;+ service.__setSongRevisionDepsForTests({ generate: async () => { throw new Error('unknown submission'); } });+ await post(fork.id, 'generate', { revisionId: newId }); await service.__testing.settle();+ const refused = await post(fork.id, 'generate', { revisionId: newId });+ expect(refused.status).toBe(409); expect(refused.body.code || refused.body.error?.code).toBe('SONG_SUBMISSION_UNKNOWN');+ });+});diff --git a/server/services/musicVideo/productionReview.js b/server/services/musicVideo/productionReview.jsindex 98a7cac9ef..78f765d207 100644--- a/server/services/musicVideo/productionReview.js+++ b/server/services/musicVideo/productionReview.js@@ -19,6 +19,12 @@ const source = p => {};export const productionAlignmentBasis = project => hash(source(project));+/** A shot manifest belongs to one immutable authored document and one master timeline. */+export const documentStoryboardBasis = project => hash({+ document: project.composition?.document?.directory, source: source(project),+ shots: project.productionReview?.draft?.storyboard,+});+export function productionReviewBasis(project) {const draft = project.productionReview?.draft || {};const art = hash({ projectId: project.id, mediaMode: project.mediaMode, authoringRenderer: project.composition?.authoringRenderer, mode: project.composition?.mode, policy: project.productionPolicy,@@ -28,6 +34,8 @@ export function productionReviewBasis(project) {motionLanguage: draft.motionLanguage, implementationPlan: draft.implementationPlan, guide: artifactBasis(artifact(project, draft.guideArtifactId)) });const storyboard = hash({ art, source: source(project), lyricsMode: draft.lyricsMode,timingStatus: draft.timingStatus, timingNotes: draft.timingNotes, storyboard: draft.storyboard,+ storyboardSource: draft.storyboardSource || 'board', documentStoryboard: project.productionReview?.documentStoryboard,+ document: draft.storyboardSource === 'document' ? project.composition?.document : null,scenes: (project.scenes || []).map(({ sceneId, startSec, endSec, lyricText, visualIntent, prompt, framePrompt }) =>({ sceneId, startSec, endSec, lyricText, visualIntent, prompt, framePrompt })), treatment: project.treatment });const window = project.productionReview?.proof;@@ -71,9 +79,18 @@ export function productionReadiness(project) {boardProblems.push('Every lyric line needs bounded, positive-duration word timings; repair zero-length or missing words.');}}- const scenes = project.scenes || [];- if (draft.storyboard?.some(shot => !shot.sceneId || !scenes.some(s => s.sceneId === shot.sceneId))) boardProblems.push('Bind every draft shot to a real Board scene.');- if (new Set((draft.storyboard || []).map(s => s.sceneId)).size !== draft.storyboard?.length) boardProblems.push('Each storyboard shot must bind to its own Board scene.');+ const documentShots = draft.storyboardSource === 'document';+ const scenes = documentShots ? (draft.storyboard || []).map(shot => ({ ...shot, sceneId: shot.id, label: shot.id })) : project.scenes || [];+ if (documentShots) {+ if (project.composition?.mode !== 'document' || !project.composition.document?.directory+ || review.documentStoryboard?.basis !== documentStoryboardBasis(project)) {+ boardProblems.push('Import a shot manifest from the current authored document and master audio. Reauthor or reimport after source, timing or shot changes.');+ }+ if (new Set(scenes.map(s => s.id)).size !== scenes.length || scenes.some(s => !text(s.id))) boardProblems.push('Document shots need unique source IDs.');+ } else {+ if (draft.storyboard?.some(shot => !shot.sceneId || !scenes.some(s => s.sceneId === shot.sceneId))) boardProblems.push('Bind every draft shot to a real Board scene.');+ if (new Set((draft.storyboard || []).map(s => s.sceneId)).size !== draft.storyboard?.length) boardProblems.push('Each storyboard shot must bind to its own Board scene.');+ }if (!scenes.length) boardProblems.push('Create a timed shot storyboard.');const timedScenes = scenes.filter(s => Number.isFinite(s.startSec) && s.endSec > s.startSec).sort((a, b) => a.startSec - b.startSec);if (timedScenes.length && (timedScenes[0].startSec > 1 / 24@@ -82,7 +99,7 @@ export function productionReadiness(project) {boardProblems.push('Storyboard shots must cover the master without unintended gaps or overlaps.');}for (const scene of scenes) {- const shot = draft.storyboard?.find(s => s.sceneId === scene.sceneId);+ const shot = documentShots ? scene : draft.storyboard?.find(s => s.sceneId === scene.sceneId);if (!(Number.isFinite(scene.startSec) && scene.endSec > scene.startSec && scene.endSec <= duration)|| !shot || ['action', 'staging', 'camera', 'transition'].some(key => !text(shot[key]))) {boardProblems.push(`Complete timing, action, staging, camera and transition for ${scene.label || 'each shot'}.`);@@ -100,7 +117,7 @@ export function productionReadiness(project) {proofProblems.push('Render and watch a current animated chorus proof with the master song.');}const proofApproved = !proofProblems.length && review.approvals?.proof?.basis === hash({ basis: basis.proof, excerptId: excerpt.id, filename: excerpt.filename });- return { basis, art: { approved: artApproved, problems: [...new Set(artProblems)] },+ return { basis, documentShotImport: { documentDirectory: project.composition?.document?.directory || null, audioBasis: productionAlignmentBasis(project) }, art: { approved: artApproved, problems: [...new Set(artProblems)] },storyboard: { approved: storyboardApproved, problems: [...new Set(boardProblems)] },proof: { approved: proofApproved, problems: proofProblems, excerptId: excerpt?.id || null },readyForProduction: proofApproved };diff --git a/server/services/musicVideo/productionReviewService.js b/server/services/musicVideo/productionReviewService.jsindex d14002c2f7..389a2b7ec6 100644--- a/server/services/musicVideo/productionReviewService.js+++ b/server/services/musicVideo/productionReviewService.js@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';import { ServerError } from '../../lib/errorHandler.js';import { getProject, mutateProjectRecord } from './projects.js';import { musicVideoEvents } from './events.js';-import { productionReadiness, productionReviewBasis, productionAlignmentBasis, approveProductionStage, assertProductionApproval, recordProductionFeedback, resolveProductionFeedback } from './productionReview.js';+import { productionReadiness, productionReviewBasis, productionAlignmentBasis, documentStoryboardBasis, approveProductionStage, assertProductionApproval, recordProductionFeedback, resolveProductionFeedback } from './productionReview.js';const reviewProcessId = randomUUID();@@ -57,11 +57,35 @@ export async function importProductionPlanning(id, source) {return changed(project);}+/** A director supplies source-authored shot IDs/times; never infer shots from a generic Board row. */+export async function importDocumentShots(id, input) {+ const before = await requireProject(id);+ if (!before.productionReview?.draft) throw new ServerError('Save a planning draft before importing document shots.', { status: 409, code: 'PLANNING_DRAFT_REQUIRED' });+ if (before.composition?.mode !== 'document' || before.composition.document?.directory !== input.documentDirectory || productionAlignmentBasis(before) !== input.audioBasis) {+ throw new ServerError('The composition version changed. Export its source and import a matching shot manifest.', { status: 409, code: 'DOCUMENT_STORYBOARD_STALE' });+ }+ const { resolveDocumentFile } = await import('./compositionDocument.js');+ await resolveDocumentFile(before, input.sourceFile);+ const alignment = productionAlignmentBasis(before);+ const { project } = await mutateProjectRecord(id, current => {+ if (current.composition?.document?.directory !== input.documentDirectory || productionAlignmentBasis(current) !== alignment) {+ throw new ServerError('Document or audio changed during import.', { status: 409, code: 'DOCUMENT_STORYBOARD_STALE' });+ }+ const next = { ...current, productionReview: { ...current.productionReview,+ draft: { ...current.productionReview?.draft, storyboardSource: 'document', storyboard: input.shots } } };+ next.productionReview.documentStoryboard = { directory: input.documentDirectory, sourceFile: input.sourceFile,+ basis: documentStoryboardBasis(next), importedAt: new Date().toISOString() };+ return { project: next };+ });+ return changed(project);+}+/** Explicitly create and bind an unbound draft shot, under the project write lock. */export async function bindProductionShot(id, shotId) {const { addScene } = await import('./projectsLogic.js');const { project } = await mutateProjectRecord(id, current => {const draft = current.productionReview?.draft;+ if (draft?.storyboardSource === 'document') throw new ServerError('Document shots are edited in their authored source, not bound to Board scenes.', { status: 409, code: 'DOCUMENT_STORYBOARD' });const shot = draft?.storyboard.find(s => s.id === shotId);if (!shot) throw new ServerError('Draft shot not found', { status: 404, code: 'NOT_FOUND' });if (shot.sceneId) throw new ServerError('This draft shot is already bound. Edit its existing Board scene.', { status: 409, code: 'SHOT_ALREADY_BOUND' });@@ -136,6 +160,7 @@ async function validateGuideSelection(project, selectedId) {/** Prepare ordinary editable artifacts; never mark any stage approved. */export async function prepareProductionReview(id, options = {}) {let project = await requireProject(id);+ if (project.productionReview?.draft?.storyboardSource === 'document') return present(project);const stage = project.castAndSets;const hasManualGuide = !productionReadiness(project).art.problems.length;if (!hasManualGuide && (!stage?.direction || !stage.artifactId)) {@@ -157,6 +182,7 @@ export async function prepareProductionReview(id, options = {}) {// Merge against the latest draft while holding the write lock: a guide job// may finish while the operator is editing its text.await mutateProjectRecord(id, current => {+ if (current.productionReview?.draft?.storyboardSource === 'document') return { project: current };const prior = current.productionReview?.draft || {};const draft = { lyricsMode: 'vocal', timingStatus: 'provisional', timingNotes: '', storyboard: [], ...prior,cast: prior.cast || describe(d.protagonist), environments: prior.environments || describe(d.sets),@@ -166,7 +192,7 @@ export async function prepareProductionReview(id, options = {}) {return { project: { ...current, productionReview: { ...current.productionReview, draft } } };});project = await requireProject(id);- if (!productionReadiness(project).art.approved) return present(project);+ if (project.productionReview?.draft?.storyboardSource === 'document' || !productionReadiness(project).art.approved) return present(project);if (!project.scenes?.length) {const { planProject } = await import('./planner.js');await planProject(id, { ...options, seedPrompts: true });@@ -191,6 +217,7 @@ export async function prepareProductionReview(id, options = {}) {}const { project: planned } = await mutateProjectRecord(id, current => {const latest = current.productionReview.draft;+ if (latest.storyboardSource === 'document') return { project: current };const storyboard = [...latest.storyboard, ...current.scenes.filter(scene => !latest.storyboard.some(shot => shot.sceneId === scene.sceneId)).map(scene => ({sceneId: scene.sceneId,lyricCueIds: (current.lyricCues || []).filter(c => c.startSec < scene.endSec && c.endSec > scene.startSec).map(c => c.id),diff --git a/server/services/musicVideo/projectAudio.js b/server/services/musicVideo/projectAudio.jsindex 450033fb91..14f01c0155 100644--- a/server/services/musicVideo/projectAudio.js+++ b/server/services/musicVideo/projectAudio.js@@ -46,5 +46,5 @@ export async function analyzeProjectSong(projectId) {if (!analysis) {throw new ServerError('Could not analyze audio (decode failed or ffmpeg unavailable)', { status: 422, code: 'ANALYZE_FAILED' });}- return setProjectAnalysis(project.id, relabelAnalysisSections(analysis, project.lyricCues, project.lyricMarkers));+ return setProjectAnalysis(project.id, relabelAnalysisSections(analysis, project.lyricCues, project.lyricMarkers), project);}diff --git a/server/services/musicVideo/projects.js b/server/services/musicVideo/projects.jsindex 684fe59578..809d2663ac 100644--- a/server/services/musicVideo/projects.js+++ b/server/services/musicVideo/projects.js@@ -191,8 +191,8 @@ export async function deleteProject(id) {return result;}-export async function setProjectAnalysis(id, analysis) {- const next = await (await selectBackend()).setProjectAnalysis(id, analysis);+export async function setProjectAnalysis(id, analysis, sourceProject) {+ const next = await (await selectBackend()).setProjectAnalysis(id, analysis, sourceProject);emitRecordUpdated('musicVideoProject', id);return next;}diff --git a/server/services/musicVideo/projectsDB.js b/server/services/musicVideo/projectsDB.jsindex c13ae3085e..cddfb1b330 100644--- a/server/services/musicVideo/projectsDB.js+++ b/server/services/musicVideo/projectsDB.js@@ -43,8 +43,8 @@ export async function cloneProject(id, options = {}) {});}-export async function setProjectAnalysis(id, analysis) {- const { project } = await withLockedProject(id, (current) => ({ project: logic.setAudioAnalysis(current, analysis) }));+export async function setProjectAnalysis(id, analysis, sourceProject) {+ const { project } = await withLockedProject(id, (current) => ({ project: logic.setAudioAnalysis(current, analysis, sourceProject) }));return project;}diff --git a/server/services/musicVideo/projectsFile.js b/server/services/musicVideo/projectsFile.jsindex 56f6706c7d..65bb25d5d8 100644--- a/server/services/musicVideo/projectsFile.js+++ b/server/services/musicVideo/projectsFile.js@@ -50,9 +50,9 @@ async function cloneProjectUnqueued(id, options = {}) {return clone;}-async function setProjectAnalysisUnqueued(id, analysis) {+async function setProjectAnalysisUnqueued(id, analysis, sourceProject) {const { all, idx } = await loadAllAndIndex(id);- all[idx] = logic.setAudioAnalysis(all[idx], analysis);+ all[idx] = logic.setAudioAnalysis(all[idx], analysis, sourceProject);await saveAll(all);return all[idx];}diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.jsindex 5b3bf1c990..ca9829f738 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -259,6 +259,8 @@ export function cloneProjectRecord(source, {// A revision is in-progress work against the SOURCE's takes; the clone// starts with none (its carried-over notes can open a fresh one).revisions: [],+ songRevision: null,+ songRevisionHistory: [...(source.songRevisionHistory || []), ...(source.songRevision ? [source.songRevision] : [])],audioTimingRevisions: [],// #9102: an auto-review run is tied to the SOURCE's revisions/excerpts, so a// clone starts with none (terminal runs too — their links are source-scoped).@@ -432,7 +434,10 @@ export function applyProjectPatch(project, patch) {* ready/rendering project shouldn't regress its lifecycle). The analysis shape* is validated so a hand-edited/legacy record can't store a malformed map.*/-export function setAudioAnalysis(project, analysis) {+export function setAudioAnalysis(project, analysis, sourceProject) {+ if (sourceProject && (project.trackId !== sourceProject.trackId || project.uploadedAudioFilename !== sourceProject.uploadedAudioFilename)) {+ throw new ServerError('The audio changed during analysis. Analyze the selected master again.', { status: 409, code: 'MUSIC_VIDEO_AUDIO_CHANGED' });+ }const validated = musicVideoAudioAnalysisSchema.parse(analysis);const status = project.status === 'draft' ? 'analyzed' : project.status;return touch(project, { audioAnalysis: validated, status });diff --git a/server/services/musicVideo/songRevision.js b/server/services/musicVideo/songRevision.jsnew file mode 100644index 0000000000..49cf870454--- /dev/null+++ b/server/services/musicVideo/songRevision.js@@ -0,0 +1,126 @@+/** Explicit, fork-scoped song revision. Never advances on boot or selects audio automatically. */+import { randomUUID } from 'crypto';+import { ServerError } from '../../lib/errorHandler.js';+import { getProject, mutateProjectRecord } from './projects.js';+import { applyProjectPatch } from './projectsLogic.js';+import { parseLyricCues } from './timedText.js';+import { musicVideoEvents } from './events.js';++const inflight = new Map();+const fail = (message, code = 'SONG_REVISION_CONFLICT') => { throw new ServerError(message, { status: 409, code }); };+const defaults = { generate: async (...args) => (await import('./autonomousSuno.js')).generateSunoSong(...args) };+let deps = defaults;+export const __setSongRevisionDepsForTests = (overrides = {}) => { deps = { ...defaults, ...overrides }; };++function requireRevision(project, id) {+ if (!project.parentProjectId) fail('Fork a version before revising its song');+ if (!project.songRevision || project.songRevision.id !== id) fail('This song revision is no longer current');+ return project.songRevision;+}+async function mutate(id, fn) {+ const out = await mutateProjectRecord(id, (current) => {+ const next = fn(current);+ return { ...next, project: { ...next.project, updatedAt: new Date().toISOString(),+ songRevision: { ...next.project.songRevision, sequence: (current.songRevision?.sequence || 0) + 1 } } };+ });+ musicVideoEvents.emit('song-revision', { projectId: id, project: out.project });+ return out;+}+const patch = (id, revisionId, fn) => mutate(id, (project) => {+ const revision = requireRevision(project, revisionId);+ return { project: { ...project, songRevision: { ...revision, ...fn(revision), updatedAt: new Date().toISOString() } } };+});++export async function saveSongRevision(projectId, fields) {+ return mutate(projectId, (project) => {+ if (!project.parentProjectId) fail('Fork a version before revising its song');+ if (inflight.has(projectId) || ['generating', 'review', 'selected'].includes(project.songRevision?.status)) fail('Select or cancel the current candidates; fork again after selecting a song');+ const previous = project.songRevision;+ const revision = { id: `mvsr-${randomUUID()}`, fields, status: 'draft', songIds: [], candidates: [], createdAt: new Date().toISOString() };+ return { project: { ...project, songRevision: revision,+ songRevisionHistory: previous ? [...(project.songRevisionHistory || []), previous] : (project.songRevisionHistory || []),+ } };+ });+}++async function generate(projectId, revisionId, controller) {+ try {+ controller.signal.throwIfAborted();+ let revision = (await getProject(projectId)).songRevision;+ const persist = async (update) => {+ const out = await patch(projectId, revisionId, (r) => update(r));+ revision = out.project.songRevision;+ };+ const accept = async (song) => {+ controller.signal.throwIfAborted();+ await persist((r) => ({ candidates: [...r.candidates.filter((c) => c.songId !== song.songId), { songId: song.songId, filename: song.filename } ] }));+ };+ if (!revision.songIds.length) {+ // Reserve before dispatch. A crash without returned ids must NEVER repeat Create.+ await persist(() => ({ submitted: true }));+ const song = await deps.generate(revision.fields, {+ signal: controller.signal,+ onSubmitted: (songIds) => persist(() => ({ songIds })),+ });+ await accept(song);+ }+ for (const songId of revision.songIds) {+ controller.signal.throwIfAborted();+ if (revision.candidates.some((c) => c.songId === songId)) continue;+ const song = await deps.generate(revision.fields, { songIds: [songId], signal: controller.signal });+ await accept(song);+ }+ controller.signal.throwIfAborted();+ await patch(projectId, revisionId, (r) => r.status === 'canceled' ? {} : { status: 'review', error: null });+ } catch (err) {+ // Background work owns its failures; cancellation leaves the source/master intact.+ await patch(projectId, revisionId, (r) => r.status === 'canceled' ? {} : {+ status: 'failed', error: err.code || 'SONG_GENERATION_FAILED',+ }).catch((writeError) => console.error(`❌ Song revision could not store failure: ${writeError.code || 'STORE_FAILED'}`));+ } finally {+ inflight.delete(projectId);+ }+}++export async function generateSongRevision(projectId, revisionId) {+ if (inflight.has(projectId)) fail('Song generation is already in progress');+ const controller = new AbortController();+ // Install the reservation before any await; cancellation can always find it.+ const pending = { controller, promise: null };+ inflight.set(projectId, pending);+ const out = await patch(projectId, revisionId, (r) => {+ if (!['draft', 'failed', 'generating'].includes(r.status)) fail('Save a new draft to generate another song');+ if (r.submitted && !r.songIds.length) fail('The previous submission has an unknown outcome. Check Suno before saving a new draft.', 'SONG_SUBMISSION_UNKNOWN');+ return { status: 'generating', error: null };+ }).catch((err) => { inflight.delete(projectId); throw err; });+ pending.promise = generate(projectId, revisionId, controller);+ return out;+}++export async function cancelSongRevision(projectId, revisionId) {+ const out = await patch(projectId, revisionId, (r) => {+ if (r.status === 'selected') fail('The selected song is already applied; fork another version to revise it');+ return { status: 'canceled' };+ });+ inflight.get(projectId)?.controller.abort();+ return out;+}++export async function selectSongRevision(projectId, revisionId, songId) {+ return mutate(projectId, (project) => {+ const revision = requireRevision(project, revisionId);+ if (inflight.has(projectId) || !['review', 'failed'].includes(revision.status)) fail('Wait for candidate generation to settle before selecting audio');+ if (project.status === 'rendering' || project.autonomousRun?.status === 'running' || project.productionRuns?.some((r) => r.status === 'running')) fail('Stop active production before replacing the master audio');+ const candidate = revision.candidates.find((c) => c.songId === songId);+ if (!candidate) fail('Import and listen to a candidate before selecting it');+ const { cues, markers } = parseLyricCues(revision.fields.instrumental ? '' : revision.fields.lyrics);+ const next = applyProjectPatch(project, { trackId: null, uploadedAudioFilename: candidate.filename, lyricCues: cues, lyricMarkers: markers, phrases: [] });+ if (next.productionReview) next.productionReview = { ...next.productionReview,+ draft: { ...next.productionReview.draft, timingStatus: 'provisional' }, alignmentBasis: null,+ approvals: next.productionReview.approvals?.art ? { art: next.productionReview.approvals.art } : {}, proof: null,+ };+ return { project: { ...next, songRevision: { ...revision, status: 'selected', selectedSongId: songId, selectedAt: new Date().toISOString() } } };+ });+}++export const __testing = { settle: async () => { await Promise.all([...inflight.values()].map((entry) => entry.promise)); } };diff --git a/server/services/socket.js b/server/services/socket.jsindex e9652423c6..2c015182cb 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -315,6 +315,7 @@ const SIMPLE_BRIDGES = [{ emitter: musicVideoEvents, event: 'production', channel: 'music-video:production' },// A fully-autonomous run (prompt → lyrics → Suno song → video) advancing.{ emitter: musicVideoEvents, event: 'autonomous', channel: 'music-video:autonomous' },+ { emitter: musicVideoEvents, event: 'song-revision', channel: 'music-video:song-revision' },// The Cast & Sets check-in advancing, and a development artifact changing.{ emitter: musicVideoEvents, event: 'cast-and-sets', channel: 'music-video:cast-and-sets' },{ emitter: musicVideoEvents, event: 'dev-artifact', channel: 'music-video:dev-artifact' },