Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(music-video): stage tabs, sticky next-action header and docked preview (#9243)
Adam Eivy4a9891bb39d2
diff --git a/client/src/App.jsx b/client/src/App.jsxindex ae99c7d911..233f86df79 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -563,7 +563,10 @@ export default function App() {convention. */}<Route path="music-video" element={<MusicVideo />} /><Route path="music-video/:projectId" element={<MusicVideo />} />+ {/* Stage tab (setup | cast-sets | board | produce | compose | review); an unknown stage opens the project's default. */}+ <Route path="music-video/:projectId/:stage" element={<MusicVideo />} /><Route path="music-video/:projectId/dev/:artifactId" element={<MusicVideo />} />+ <Route path="music-video/:projectId/:stage/dev/:artifactId" element={<MusicVideo />} />{/* 3D — a top-level Create page (moved out of the Media Gen tabs). Therecord id is the URL, per the ID-based deep-linking convention. */}<Route path="3d" element={<Media3D />} />diff --git a/client/src/components/musicVideo/AnalysisPanel.jsx b/client/src/components/musicVideo/AnalysisPanel.jsxindex d3812ab1d3..fc0be77b90 100644--- a/client/src/components/musicVideo/AnalysisPanel.jsx+++ b/client/src/components/musicVideo/AnalysisPanel.jsx@@ -42,7 +42,7 @@ export default function AnalysisPanel({ audioAnalysis, scenes, tempo, onReanalyz{onReanalyze && (<button type="button" onClick={onReanalyze} disabled={analyzing}title="Re-runs the offline analysis, including tempo detection (replaces a manually set tempo)"- className="bg-port-card border border-port-border rounded px-2 py-1 min-h-[32px] hover:bg-port-border/40 disabled:opacity-50">+ className="bg-port-card border border-port-border rounded px-2 py-1 min-h-[44px] sm:min-h-[32px] hover:bg-port-border/40 disabled:opacity-50">{analyzing ? 'Analyzing…' : 'Re-analyze'}</button>)}diff --git a/client/src/components/musicVideo/AutomationPanel.jsx b/client/src/components/musicVideo/AutomationPanel.jsxdeleted file mode 100644index 55aaf26cf1..0000000000--- a/client/src/components/musicVideo/AutomationPanel.jsx+++ /dev/null@@ -1,103 +0,0 @@-import { useState } from 'react';-import { Bot, Play } from 'lucide-react';-import AutomationBriefFields from './AutomationBriefFields.jsx';-import Pill from '../ui/Pill.jsx';-import { MUSIC_VIDEO_AUTOMATION_TOOLS, automationDraftFrom, automationFromDraft } from '../../lib/musicVideoAutomation.js';-import { formatUsd } from '../../utils/formatters.js';--const toolLabel = new Map(MUSIC_VIDEO_AUTOMATION_TOOLS.map((t) => [t.id, t.label]));-const actionClass = 'text-sm text-port-accent min-h-[44px] sm:min-h-0 px-1';--/**- * The project's automation brief — tools, guidance, budget — shown first on- * the board, with a one-click kickoff (analyze the song, import the track's- * lyrics, separate vocals, align words, build the Cast & Sets check-in, then- * plan every shot against the brief). `kickoffStep` names the step running- * now; `checkin` is the check-in card shown under the brief. Edits PATCH- * through `onSave`, which owns the error toast.- */-export default function AutomationPanel({ project, onSave, onKickoff, kickoffBusy, kickoffStep = null, kickoffBlockedReason, checkin = null }) {- const [draft, setDraft] = useState(null);- const [saving, setSaving] = useState(false);- const automation = project.automation || null;-- const save = () => {- setSaving(true);- onSave(automationFromDraft(draft))- .then(() => setDraft(null))- // A failed save keeps the brief open for another try.- .catch(() => {})- .finally(() => setSaving(false));- };-- let header = null;- let body;- if (draft) {- body = (- <fieldset disabled={saving} className="space-y-3 min-w-0">- <AutomationBriefFields idPrefix={`mv-auto-${project.id}`} draft={draft} onChange={(patch) => setDraft((d) => ({ ...d, ...patch }))} />- <div className="flex flex-wrap gap-3">- <button type="button" onClick={save} className="bg-port-accent text-white rounded px-3 py-2 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50">- {saving ? 'Saving…' : 'Save brief'}- </button>- <button type="button" onClick={() => setDraft(null)} className="text-sm min-h-[44px] sm:min-h-0">Cancel</button>- </div>- </fieldset>- );- } else if (automation) {- header = (- <>- <span className="text-xs text-port-text-muted">- {automation.tools.length} tool{automation.tools.length === 1 ? '' : 's'}- {' · '}- {automation.budgetUsd != null ? `${formatUsd(automation.budgetUsd)} cap` : 'no budget cap'}- {' · '}- {automation.checkins?.castAndSets === 'auto' ? 'check-ins auto-approved' : 'stops for check-ins'}- </span>- <div className="ml-auto flex flex-wrap items-center gap-2">- <button type="button" onClick={() => setDraft(automationDraftFrom(automation))} className={actionClass}>Edit brief</button>- <button- type="button"- onClick={onKickoff}- disabled={kickoffBusy || !!kickoffBlockedReason}- title={kickoffBlockedReason || 'Analyze the song, import its lyrics, separate and align the vocal, build the Cast & Sets check-in, then plan every shot against the brief'}- className="flex items-center gap-1 bg-port-accent text-white rounded px-3 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50"- >- <Play size={14} /> {kickoffBusy ? 'Working…' : 'Analyze & plan'}- </button>- </div>- </>- );- body = (- <>- {automation.tools.length > 0 && (- <div className="flex flex-wrap gap-1">- {automation.tools.map((id) => <Pill key={id} size="xs" bordered={false}>{toolLabel.get(id) || id}</Pill>)}- </div>- )}- <p className="text-xs text-port-text-muted break-words line-clamp-3">- {automation.guidance || 'No guidance yet — the agent plans from the song, universe and board alone.'}- </p>- {kickoffStep && <p className="text-xs text-port-accent" role="status">{kickoffStep}</p>}- {kickoffBlockedReason && <p className="text-xs text-port-warning">{kickoffBlockedReason}</p>}- {checkin}- </>- );- } else {- header = (- <button type="button" onClick={() => setDraft(automationDraftFrom(null))} className={`ml-auto ${actionClass}`}>Set up autopilot</button>- );- body = <p className="text-xs text-port-text-muted">Hand this video to the agent: pick the tools it may use, give it guidance and a budget.</p>;- }-- return (- <section className="bg-port-card border border-port-border rounded-lg p-3 space-y-2 min-w-0" aria-label="Autopilot">- <div className="flex flex-wrap items-center gap-2">- <Bot size={16} className="text-port-accent shrink-0" aria-hidden="true" />- <h3 className="text-sm font-medium">Autopilot</h3>- {header}- </div>- {body}- </section>- );-}diff --git a/client/src/components/musicVideo/AutomationPanel.test.jsx b/client/src/components/musicVideo/AutomationPanel.test.jsxdeleted file mode 100644index 27a4af993b..0000000000--- a/client/src/components/musicVideo/AutomationPanel.test.jsx+++ /dev/null@@ -1,109 +0,0 @@-/**- * Autopilot kickoff ("Analyze & plan"): the steps run in order on the- * freshest project, the panel names the step that is running, a step whose- * result already exists is skipped, and a failed lyric step still plans while- * a failed analysis stops the run.- */-import { describe, it, expect, vi } from 'vitest';-import { render, screen, fireEvent, waitFor } from '@testing-library/react';-import AutomationPanel from './AutomationPanel.jsx';-import useMusicVideoKickoff from '../../hooks/useMusicVideoKickoff.js';--const automation = { tools: ['local-image'], guidance: 'Moody neon', budgetUsd: null };--function deferred() {- let resolve;- const promise = new Promise((r) => { resolve = r; });- return { promise, resolve };-}--function Harness({ project, steps }) {- const kickoff = useMusicVideoKickoff(steps);- return (- <AutomationPanel- project={project}- onSave={vi.fn()}- onKickoff={() => kickoff.run(project)}- kickoffBusy={kickoff.running}- kickoffStep={kickoff.stepLabel}- />- );-}--const cue = (id, text, words) => ({ id, text, startSec: null, endSec: null, ...(words ? { words } : {}) });--describe('AutomationPanel autopilot kickoff', () => {- it('analyzes, imports track lyrics, separates vocals, aligns and plans — showing each step', async () => {- const order = [];- const base = { id: 'mv-1', trackId: 't1', automation, lyricCues: [] };- const analyzed = { ...base, audioAnalysis: { sections: [] } };- const withLyrics = { ...analyzed, lyricCues: [cue('lc-1', 'hold on')] };- const withStem = { ...withLyrics, vocalStemFilename: 'stem.wav' };- const aligned = { ...withStem, lyricCues: [cue('lc-1', 'hold on', [{ w: 'hold' }, { w: 'on' }])] };- const separating = deferred();- const steps = {- analyze: vi.fn(async () => { order.push('analyze'); return analyzed; }),- importLyrics: vi.fn(async (p) => { order.push(['lyrics', p]); return withLyrics; }),- separateVocals: vi.fn((p) => { order.push(['vocals', p]); return separating.promise; }),- alignLyrics: vi.fn(async (p) => { order.push(['align', p]); return aligned; }),- plan: vi.fn(async (p) => { order.push(['plan', p]); }),- };- render(<Harness project={base} steps={steps} />);- fireEvent.click(screen.getByRole('button', { name: /Analyze & plan/ }));-- expect(await screen.findByRole('status')).toHaveTextContent('Separating vocals…');- expect(screen.getByRole('button', { name: /Working/ }).disabled).toBe(true);- separating.resolve(withStem);-- await waitFor(() => expect(steps.plan).toHaveBeenCalled());- expect(order).toEqual([- 'analyze',- ['lyrics', analyzed],- ['vocals', withLyrics],- ['align', withStem],- ['plan', aligned],- ]);- await waitFor(() => expect(screen.queryByRole('status')).toBeNull());- });-- it('skips what already exists, and still plans when the lyric import fails', async () => {- const project = {- id: 'mv-2', trackId: 't1', automation, audioAnalysis: { sections: [] }, vocalStemFilename: 'stem.wav', lyricCues: [],- };- const steps = {- analyze: vi.fn(),- importLyrics: vi.fn(async () => null),- separateVocals: vi.fn(),- alignLyrics: vi.fn(),- plan: vi.fn(async () => {}),- };- render(<Harness project={project} steps={steps} />);- fireEvent.click(screen.getByRole('button', { name: /Analyze & plan/ }));- await waitFor(() => expect(steps.plan).toHaveBeenCalledWith(project));- expect(steps.analyze).not.toHaveBeenCalled();- expect(steps.importLyrics).toHaveBeenCalledOnce();- // No lyric lines means nothing to separate or align.- expect(steps.separateVocals).not.toHaveBeenCalled();- expect(steps.alignLyrics).not.toHaveBeenCalled();- });-- it('stops when the analysis fails', async () => {- const analyzing = deferred();- const steps = {- analyze: vi.fn(() => analyzing.promise),- importLyrics: vi.fn(),- separateVocals: vi.fn(),- alignLyrics: vi.fn(),- plan: vi.fn(),- };- render(<Harness project={{ id: 'mv-3', trackId: 't1', automation, lyricCues: [] }} steps={steps} />);- const button = screen.getByRole('button', { name: /Analyze & plan/ });- fireEvent.click(button);- expect(await screen.findByRole('status')).toHaveTextContent('Analyzing the song…');- analyzing.resolve(null);- await waitFor(() => expect(screen.queryByRole('status')).toBeNull());- expect(steps.analyze).toHaveBeenCalledOnce();- expect(steps.importLyrics).not.toHaveBeenCalled();- expect(steps.plan).not.toHaveBeenCalled();- });-});diff --git a/client/src/components/musicVideo/ProductionPanel.jsx b/client/src/components/musicVideo/AutopilotPanel.jsxsimilarity index 67%rename from client/src/components/musicVideo/ProductionPanel.jsxrename to client/src/components/musicVideo/AutopilotPanel.jsxindex 01c41d4464..2226d962d3 100644--- a/client/src/components/musicVideo/ProductionPanel.jsx+++ b/client/src/components/musicVideo/AutopilotPanel.jsx@@ -1,9 +1,14 @@import { useState } from 'react';-import { Clapperboard, Play, Pause, X } from 'lucide-react';+import { Bot, Clapperboard, Pause, Play, X } from 'lucide-react';+import AutomationBriefFields from './AutomationBriefFields.jsx';+import Pill from '../ui/Pill.jsx';import useProviderModels from '../../hooks/useProviderModels.js';import ProviderModelSelector from '../ProviderModelSelector.jsx';import ToggleChip from '../ui/ToggleChip.jsx';-import { DEFAULT_AUTOMATION_TOOLS, MUSIC_VIDEO_AUTOMATION_TOOLS } from '../../lib/musicVideoAutomation.js';+import {+ DEFAULT_AUTOMATION_TOOLS, MUSIC_VIDEO_AUTOMATION_TOOLS, automationDraftFrom, automationFromDraft,+} from '../../lib/musicVideoAutomation.js';+import { RESUMABLE_RUN_STATUSES, currentProductionRun } from '../../lib/musicVideoStages.js';import { formatUsd } from '../../utils/formatters.js';const POOL_TOOLS = MUSIC_VIDEO_AUTOMATION_TOOLS.filter((t) => t.group === 'image' || t.group === 'video');@@ -19,19 +24,14 @@ const STATUS_TONES = {failed: 'text-port-error', canceled: 'text-port-text-muted',};const STEP_TONES = { completed: 'text-port-success', failed: 'text-port-error', canceled: 'text-port-text-muted', refused: 'text-port-text-muted' };-const RESUMABLE = new Set(['running', 'stopped', 'limit-reached', 'blocked', 'needs-replan']);const inputCls = 'w-24 bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs min-h-[44px] sm:min-h-0';const SHOWN_STEPS = 8;const toolLabel = new Map(POOL_TOOLS.map((t) => [t.id, t.label]));+const briefToolLabel = new Map(MUSIC_VIDEO_AUTOMATION_TOOLS.map((t) => [t.id, t.label]));+const actionClass = 'text-sm text-port-accent min-h-[44px] sm:min-h-0 px-1';const routeLabel = (route) => `${toolLabel.get(`${route.kind}:${route.mode}`) || `${route.kind} ${route.mode}`}${route.model ? ` · ${route.model}` : ''}`;-/** The run worth showing: the live one, else the most recent. */-export const currentProductionRun = (project) => {- const runs = Array.isArray(project?.productionRuns) ? project.productionRuns : [];- return runs.find((r) => RESUMABLE.has(r.status)) || runs[runs.length - 1] || null;-};-const initialPool = (project) => {const fromBrief = (project?.automation?.tools || []).filter((id) => POOL_TOOL_IDS.has(id));return fromBrief.length ? fromBrief : DEFAULT_AUTOMATION_TOOLS.filter((id) => POOL_TOOL_IDS.has(id));@@ -50,7 +50,7 @@ function StepRow({ step }) {}function RunView({ run, production }) {- const live = RESUMABLE.has(run.status);+ const live = RESUMABLE_RUN_STATUSES.has(run.status);const steps = run.steps || [];const failures = steps.filter((s) => s.error);const cap = run.limits.spendCapUsd;@@ -190,7 +190,7 @@ function StartForm({ project, production }) {compact/>)}- <button type="button" disabled={production.busy || !valid} onClick={start}+ <button type="button" id="mv-production-start" disabled={production.busy || !valid} onClick={start}className="flex items-center gap-1 bg-port-accent text-white rounded px-3 py-2 min-h-[44px] sm:min-h-0 sm:px-2 sm:py-1 disabled:opacity-50"><Play size={12} /> {production.busy ? 'Starting…' : 'Start production'}</button>@@ -199,14 +199,100 @@ function StartForm({ project, production }) {);}+/** The brief: tools, guidance and budget, with the one-click kickoff. */+function BriefSection({ project, onSave, onKickoff, kickoffBusy, kickoffStep, kickoffBlockedReason }) {+ const [draft, setDraft] = useState(null);+ const [saving, setSaving] = useState(false);+ const automation = project.automation || null;++ const save = () => {+ setSaving(true);+ onSave(automationFromDraft(draft))+ .then(() => setDraft(null))+ // A failed save keeps the brief open for another try.+ .catch(() => {})+ .finally(() => setSaving(false));+ };++ let header = null;+ let body;+ if (draft) {+ body = (+ <fieldset disabled={saving} className="space-y-3 min-w-0">+ <AutomationBriefFields idPrefix={`mv-auto-${project.id}`} draft={draft} onChange={(patch) => setDraft((d) => ({ ...d, ...patch }))} />+ <div className="flex flex-wrap gap-3">+ <button type="button" onClick={save} className="bg-port-accent text-white rounded px-3 py-2 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50">+ {saving ? 'Saving…' : 'Save brief'}+ </button>+ <button type="button" onClick={() => setDraft(null)} className="text-sm min-h-[44px] sm:min-h-0">Cancel</button>+ </div>+ </fieldset>+ );+ } else if (automation) {+ header = (+ <>+ <span className="text-xs text-port-text-muted">+ {automation.tools.length} tool{automation.tools.length === 1 ? '' : 's'}+ {' · '}+ {automation.budgetUsd != null ? `${formatUsd(automation.budgetUsd)} cap` : 'no budget cap'}+ {' · '}+ {automation.checkins?.castAndSets === 'auto' ? 'check-ins auto-approved' : 'stops for check-ins'}+ </span>+ <div className="ml-auto flex flex-wrap items-center gap-2">+ <button type="button" onClick={() => setDraft(automationDraftFrom(automation))} className={actionClass}>Edit brief</button>+ <button+ type="button"+ onClick={onKickoff}+ disabled={kickoffBusy || !!kickoffBlockedReason}+ title={kickoffBlockedReason || 'Analyze the song, import its lyrics, separate and align the vocal, build the Cast & Sets check-in, then plan every shot against the brief'}+ className="flex items-center gap-1 bg-port-accent text-white rounded px-3 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50"+ >+ <Play size={14} /> {kickoffBusy ? 'Working…' : 'Analyze & plan'}+ </button>+ </div>+ </>+ );+ body = (+ <>+ {automation.tools.length > 0 && (+ <div className="flex flex-wrap gap-1">+ {automation.tools.map((id) => <Pill key={id} size="xs" bordered={false}>{briefToolLabel.get(id) || id}</Pill>)}+ </div>+ )}+ <p className="text-xs text-port-text-muted break-words line-clamp-3">+ {automation.guidance || 'No guidance yet — the agent plans from the song, universe and board alone.'}+ </p>+ {kickoffStep && <p className="text-xs text-port-accent" role="status">{kickoffStep}</p>}+ {kickoffBlockedReason && <p className="text-xs text-port-warning">{kickoffBlockedReason}</p>}+ </>+ );+ } else {+ header = (+ <button type="button" onClick={() => setDraft(automationDraftFrom(null))} className={`ml-auto ${actionClass}`}>Set up autopilot</button>+ );+ body = <p className="text-xs text-port-text-muted">Hand this video to the agent: pick the tools it may use, give it guidance and a budget.</p>;+ }++ return (+ <div className="space-y-2">+ <div className="flex flex-wrap items-center gap-2">+ <Bot size={16} className="text-port-accent shrink-0" aria-hidden="true" />+ <h3 className="text-sm font-medium">Autopilot</h3>+ {header}+ </div>+ {body}+ </div>+ );+}+/*** Server-owned production run (#9066): nothing runs until the director starts* it with an allowed provider/model pool and explicit limits. Progress arrives* over the `music-video:production` socket event via `useMusicVideoProduction`.*/-export default function ProductionPanel({ project, production }) {+function ProductionSection({ project, production }) {const run = currentProductionRun(project);- const active = run && RESUMABLE.has(run.status);+ const active = run && RESUMABLE_RUN_STATUSES.has(run.status);return (<div className="rounded border border-port-border p-2 space-y-2 text-xs" aria-label="Production run"><span className="font-medium flex items-center gap-1"><Clapperboard size={12} /> Autonomous production (opt-in)</span>@@ -215,3 +301,28 @@ export default function ProductionPanel({ project, production }) {</div>);}++/**+ * Autopilot: one card holding the project's automation brief (tools, guidance,+ * budget, kickoff) and its server-side production run (allowed routes,+ * generation and spend caps, the run log). Edits PATCH through `onSave`, which+ * owns the error toast; `production` is the `useMusicVideoProduction` slot.+ * `kickoffStep` names the kickoff step running now.+ */+export default function AutopilotPanel({+ project, production, onSave, onKickoff, kickoffBusy, kickoffStep = null, kickoffBlockedReason,+}) {+ return (+ <section className="bg-port-card border border-port-border rounded-lg p-3 space-y-3 min-w-0" aria-label="Autopilot">+ <BriefSection+ project={project}+ onSave={onSave}+ onKickoff={onKickoff}+ kickoffBusy={kickoffBusy}+ kickoffStep={kickoffStep}+ kickoffBlockedReason={kickoffBlockedReason}+ />+ <ProductionSection project={project} production={production} />+ </section>+ );+}diff --git a/client/src/components/musicVideo/AutopilotPanel.test.jsx b/client/src/components/musicVideo/AutopilotPanel.test.jsxnew file mode 100644index 0000000000..92c6afe5d0--- /dev/null+++ b/client/src/components/musicVideo/AutopilotPanel.test.jsx@@ -0,0 +1,186 @@+/**+ * Autopilot panel: the brief's kickoff ("Analyze & plan" — steps run in order+ * on the freshest project, the panel names the step running, a step whose+ * result already exists is skipped, and a failed lyric step still plans while+ * a failed analysis stops the run) and the server-owned production run (#9066)+ * over the real useMusicVideoProduction hook with a mocked API and socket: a+ * run starts only with the director's explicit pool and limits, a+ * restart-interrupted run is resumed explicitly, and a pushed project updates+ * the visible run.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { useState } from 'react';+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';++const listeners = vi.hoisted(() => new Map());+vi.mock('../../services/socket', () => ({+ default: { on: (ev, fn) => listeners.set(ev, fn), off: (ev) => listeners.delete(ev) },+}));+vi.mock('../../services/apiMusicVideo.js', () => ({+ startMusicVideoProduction: vi.fn(),+ resumeMusicVideoProduction: vi.fn(),+ stopMusicVideoProduction: vi.fn(),+ cancelMusicVideoProduction: vi.fn(),+}));+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), info: vi.fn(), error: vi.fn() } }));+vi.mock('../../hooks/useProviderModels.js', () => ({+ default: () => ({+ providers: [], selectedProviderId: '', selectedModel: '', availableModels: [],+ setSelectedProviderId: () => {}, setSelectedModel: () => {},+ }),+}));++import AutopilotPanel from './AutopilotPanel.jsx';+import useMusicVideoKickoff from '../../hooks/useMusicVideoKickoff.js';+import useMusicVideoProduction from '../../hooks/useMusicVideoProduction.js';+import * as api from '../../services/apiMusicVideo.js';++const IDLE_PRODUCTION = { busy: false, start: vi.fn(), resume: vi.fn(), stop: vi.fn(), cancel: vi.fn() };+const automation = { tools: ['local-image'], guidance: 'Moody neon', budgetUsd: null };++function deferred() {+ let resolve;+ const promise = new Promise((r) => { resolve = r; });+ return { promise, resolve };+}++function KickoffHarness({ project, steps }) {+ const kickoff = useMusicVideoKickoff(steps);+ return (+ <AutopilotPanel+ project={project}+ production={IDLE_PRODUCTION}+ onSave={vi.fn()}+ onKickoff={() => kickoff.run(project)}+ kickoffBusy={kickoff.running}+ kickoffStep={kickoff.stepLabel}+ />+ );+}++const cue = (id, text, words) => ({ id, text, startSec: null, endSec: null, ...(words ? { words } : {}) });++describe('AutopilotPanel kickoff', () => {+ it('analyzes, imports track lyrics, separates vocals, aligns and plans — showing each step', async () => {+ const order = [];+ const base = { id: 'mv-1', trackId: 't1', automation, lyricCues: [] };+ const analyzed = { ...base, audioAnalysis: { sections: [] } };+ const withLyrics = { ...analyzed, lyricCues: [cue('lc-1', 'hold on')] };+ const withStem = { ...withLyrics, vocalStemFilename: 'stem.wav' };+ const aligned = { ...withStem, lyricCues: [cue('lc-1', 'hold on', [{ w: 'hold' }, { w: 'on' }])] };+ const separating = deferred();+ const steps = {+ analyze: vi.fn(async () => { order.push('analyze'); return analyzed; }),+ importLyrics: vi.fn(async (p) => { order.push(['lyrics', p]); return withLyrics; }),+ separateVocals: vi.fn((p) => { order.push(['vocals', p]); return separating.promise; }),+ alignLyrics: vi.fn(async (p) => { order.push(['align', p]); return aligned; }),+ plan: vi.fn(async (p) => { order.push(['plan', p]); }),+ };+ render(<KickoffHarness project={base} steps={steps} />);+ fireEvent.click(screen.getByRole('button', { name: /Analyze & plan/ }));++ expect(await screen.findByRole('status')).toHaveTextContent('Separating vocals…');+ expect(screen.getByRole('button', { name: /Working/ }).disabled).toBe(true);+ separating.resolve(withStem);++ await waitFor(() => expect(steps.plan).toHaveBeenCalled());+ expect(order).toEqual([+ 'analyze',+ ['lyrics', analyzed],+ ['vocals', withLyrics],+ ['align', withStem],+ ['plan', aligned],+ ]);+ await waitFor(() => expect(screen.queryByRole('status')).toBeNull());+ });++ it('skips what already exists, and still plans when the lyric import fails', async () => {+ const project = {+ id: 'mv-2', trackId: 't1', automation, audioAnalysis: { sections: [] }, vocalStemFilename: 'stem.wav', lyricCues: [],+ };+ const steps = {+ analyze: vi.fn(),+ importLyrics: vi.fn(async () => null),+ separateVocals: vi.fn(),+ alignLyrics: vi.fn(),+ plan: vi.fn(async () => {}),+ };+ render(<KickoffHarness project={project} steps={steps} />);+ fireEvent.click(screen.getByRole('button', { name: /Analyze & plan/ }));+ await waitFor(() => expect(steps.plan).toHaveBeenCalledWith(project));+ expect(steps.analyze).not.toHaveBeenCalled();+ expect(steps.importLyrics).toHaveBeenCalledOnce();+ // No lyric lines means nothing to separate or align.+ expect(steps.separateVocals).not.toHaveBeenCalled();+ expect(steps.alignLyrics).not.toHaveBeenCalled();+ });++ it('stops when the analysis fails', async () => {+ const analyzing = deferred();+ const steps = {+ analyze: vi.fn(() => analyzing.promise),+ importLyrics: vi.fn(),+ separateVocals: vi.fn(),+ alignLyrics: vi.fn(),+ plan: vi.fn(),+ };+ render(<KickoffHarness project={{ id: 'mv-3', trackId: 't1', automation, lyricCues: [] }} steps={steps} />);+ const button = screen.getByRole('button', { name: /Analyze & plan/ });+ fireEvent.click(button);+ expect(await screen.findByRole('status')).toHaveTextContent('Analyzing the song…');+ analyzing.resolve(null);+ await waitFor(() => expect(screen.queryByRole('status')).toBeNull());+ expect(steps.analyze).toHaveBeenCalledOnce();+ expect(steps.importLyrics).not.toHaveBeenCalled();+ expect(steps.plan).not.toHaveBeenCalled();+ });+});++const run = (over = {}) => ({+ id: 'run-1', status: 'running', interrupted: false, directive: '', stopReason: null, error: null,+ pool: [{ kind: 'image', mode: 'local', model: null }, { kind: 'video', mode: 'local', model: null }],+ limits: { maxGenerations: 12, maxReviewAttempts: 3, spendCapUsd: null },+ usage: { generations: 2, spentUsd: 0 },+ steps: [{ key: 'frame:s1:base:1', kind: 'frame', sceneId: 's1', route: { kind: 'image', mode: 'local', model: null }, rationale: 'first eligible', status: 'queued', error: null }],+ ...over,+});++function ProductionHarness({ initial }) {+ const [project, setProject] = useState(initial);+ const production = useMusicVideoProduction({ project, replaceProject: setProject });+ return <AutopilotPanel project={project} production={production} onSave={vi.fn()} onKickoff={vi.fn()} kickoffBusy={false} />;+}++describe('AutopilotPanel production run', () => {+ beforeEach(() => { vi.clearAllMocks(); listeners.clear(); });++ it('starts only when the director presses Start, with the allowed pool and limits', async () => {+ api.startMusicVideoProduction.mockResolvedValue({ project: { id: 'p1', productionRuns: [run()] }, run: run() });+ render(<ProductionHarness initial={{ id: 'p1', productionRuns: [] }} />);+ expect(api.startMusicVideoProduction).not.toHaveBeenCalled();+ fireEvent.change(screen.getByLabelText('Max generations'), { target: { value: '5' } });+ fireEvent.click(screen.getByRole('button', { name: /Start production/ }));+ await waitFor(() => expect(api.startMusicVideoProduction).toHaveBeenCalled());+ const [id, body] = api.startMusicVideoProduction.mock.calls[0];+ expect(id).toBe('p1');+ expect(body.limits).toEqual({ maxGenerations: 5, maxReviewAttempts: 3 });+ expect(body.pool.length).toBeGreaterThan(1);+ expect(body.pool.every((r) => ['image', 'video'].includes(r.kind) && r.mode)).toBe(true);+ expect(await screen.findByText('Running')).toBeTruthy();+ });++ it('shows an interrupted run and resumes it only on request; pushed projects update it', async () => {+ api.resumeMusicVideoProduction.mockResolvedValue({ project: { id: 'p1', productionRuns: [run()] }, run: run() });+ render(<ProductionHarness initial={{ id: 'p1', productionRuns: [run({ interrupted: true })] }} />);+ expect(screen.getByText(/server restarted/)).toBeTruthy();+ expect(api.resumeMusicVideoProduction).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: /Resume/ }));+ await waitFor(() => expect(api.resumeMusicVideoProduction).toHaveBeenCalledWith('p1', 'run-1', {}, { silent: true }));++ act(() => listeners.get('music-video:production')({+ projectId: 'p1', run: run({ status: 'blocked' }),+ project: { id: 'p1', productionRuns: [run({ status: 'blocked', stopReason: 'No allowed route can generate the frame' })] },+ }));+ expect(await screen.findByText(/No allowed route can generate the frame/)).toBeTruthy();+ });+});diff --git a/client/src/components/musicVideo/CompositionPreviewPlayer.jsx b/client/src/components/musicVideo/CompositionPreviewPlayer.jsxnew file mode 100644index 0000000000..48249263ce--- /dev/null+++ b/client/src/components/musicVideo/CompositionPreviewPlayer.jsx@@ -0,0 +1,167 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { Pause, Play } from 'lucide-react';+import { fetchMusicVideoPreviewAsset, getMusicVideoCompositionPreview } from '../../services/apiMusicVideo.js';++const buttonCls = 'flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50';++/** The lyric line sung at song time `t`, from the project's timed cues. */+const lyricAt = (cues, t) => {+ const line = (cues || []).find((cue) => typeof cue.startSec === 'number' && typeof cue.endSec === 'number' && t >= cue.startSec && t < cue.endSec);+ return line?.text || '';+};++/**+ * Live preview of the project's composition document: the sandboxed iframe,+ * the song, play/scrub and the lyric line being sung. The iframe runs in an+ * opaque-origin sandbox that cannot fetch, so this component fetches the scene+ * takes and document media and posts them in as Blobs over the+ * `portos-mv:*` message bridge, then drives the document with seek messages.+ *+ * `seekRequest` (`{ t, n }`) moves the player from outside — the board seeks it+ * to a scene's start; `n` changes on every request so seeking twice to the same+ * time still applies. `collapsed` hides the picture (mini-player) below `lg`+ * while the transport stays usable; the iframe stays mounted so the loaded+ * media and playhead survive.+ */+export default function CompositionPreviewPlayer({ project, audioUrl, seekRequest = null, collapsed = false }) {+ const doc = project.composition?.document || null;+ const [preview, setPreview] = useState(null);+ const [previewError, setPreviewError] = useState('');+ const [status, setStatus] = useState('');+ const [t, setT] = useState(0);+ const [playing, setPlaying] = useState(false);+ const iframeRef = useRef(null);+ const audioRef = useRef(null);+ const blobCache = useRef(new Map());+ const seekState = useRef({ inFlight: false, pending: null, ready: false });+ const appliedSeek = useRef(null);++ const refresh = doc ? `${doc.directory}|${project.updatedAt}` : null;+ useEffect(() => {+ let active = true;+ setPreview(null);+ setPreviewError('');+ seekState.current = { inFlight: false, pending: null, ready: false };+ if (!refresh) return () => { active = false; };+ getMusicVideoCompositionPreview(project.id, { silent: true })+ .then((next) => { if (active) setPreview(next); })+ .catch((err) => { if (active) setPreviewError(err?.message || 'Could not build the preview'); });+ return () => { active = false; };+ }, [project.id, refresh]);++ const postSeek = useCallback((time) => {+ const frame = iframeRef.current?.contentWindow;+ const state = seekState.current;+ if (!frame || !state.ready) return;+ if (state.inFlight) { state.pending = time; return; }+ state.inFlight = true;+ frame.postMessage({ type: 'portos-mv:seek', t: time }, '*');+ }, []);++ useEffect(() => {+ if (!preview) return undefined;+ let active = true;+ const onMessage = async (event) => {+ if (event.source !== iframeRef.current?.contentWindow) return;+ const message = event.data || {};+ const state = seekState.current;+ if (message.type === 'portos-mv:loaded') {+ const files = {};+ let loaded = 0;+ for (const asset of preview.assets || []) {+ if (!active) return;+ setStatus(`Loading preview media ${loaded + 1}/${preview.assets.length}…`);+ const blob = blobCache.current.get(asset.url) || await fetchMusicVideoPreviewAsset(asset.url).catch(() => null);+ if (blob) { blobCache.current.set(asset.url, blob); files[asset.key] = blob; }+ loaded += 1;+ }+ if (!active) return;+ setStatus(loaded === (preview.assets || []).length ? '' : 'Some preview media could not be loaded');+ iframeRef.current?.contentWindow?.postMessage({ type: 'portos-mv:assets', files }, '*');+ state.ready = true;+ postSeek(t);+ } else if (message.type === 'portos-mv:seeked') {+ state.inFlight = false;+ if (state.pending != null) { const next = state.pending; state.pending = null; postSeek(next); }+ } else if (message.type === 'portos-mv:error') {+ state.inFlight = false;+ setPreviewError(String(message.message || 'The composition document failed in the preview'));+ }+ };+ window.addEventListener('message', onMessage);+ return () => { active = false; window.removeEventListener('message', onMessage); };+ // `t` is read once when the page loads; later seeks go through postSeek.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [preview, postSeek]);++ const duration = preview?.durationSec || 0;+ const fps = preview?.fps || 24;+ const seek = useCallback((time) => {+ const next = Math.min(Math.max(0, time), Math.max(0, duration - 1 / fps));+ setT(next);+ postSeek(next);+ if (audioRef.current && Math.abs((audioRef.current.currentTime || 0) - next) > 0.05) audioRef.current.currentTime = next;+ }, [duration, fps, postSeek]);++ // An outside seek (a scene card) waits for the preview to know its duration,+ // then applies exactly once per request.+ useEffect(() => {+ if (!seekRequest || duration <= 0 || appliedSeek.current === seekRequest.n) return;+ appliedSeek.current = seekRequest.n;+ audioRef.current?.pause?.();+ setPlaying(false);+ seek(seekRequest.t);+ }, [seekRequest, duration, seek]);++ useEffect(() => {+ if (!playing) return undefined;+ let handle = 0;+ let posted = -1;+ const tick = () => {+ const time = audioRef.current?.currentTime || 0;+ const frameIndex = Math.floor(time * fps + 1e-9);+ if (frameIndex !== posted) { posted = frameIndex; setT(time); postSeek(time); }+ handle = requestAnimationFrame(tick);+ };+ handle = requestAnimationFrame(tick);+ return () => cancelAnimationFrame(handle);+ }, [playing, fps, postSeek]);++ const togglePlay = () => {+ const audio = audioRef.current;+ if (!audio) return;+ if (playing) { audio.pause(); setPlaying(false); return; }+ audio.play?.()?.catch?.(() => {});+ setPlaying(true);+ };++ if (!doc) return null;+ const aspect = preview?.width && preview?.height ? `${preview.width} / ${preview.height}` : '16 / 9';+ const lyric = lyricAt(project.lyricCues, t);+ return (+ <div className="space-y-2" aria-label="Composition preview">+ {previewError && <p className="text-xs text-port-error" role="alert">{previewError}</p>}+ {status && <p className="text-xs text-port-text-muted">{status}</p>}+ <div className={`overflow-hidden rounded border border-port-border bg-black mx-auto ${collapsed ? 'max-lg:hidden' : ''}`}+ style={{ aspectRatio: aspect, maxHeight: '70vh', maxWidth: '100%' }}>+ {preview?.html ? (+ <iframe ref={iframeRef} title="Composition document preview" sandbox="allow-scripts" srcDoc={preview.html} className="h-full w-full" />+ ) : (+ <p className="p-3 text-xs text-port-text-muted">{previewError ? '' : 'Building the preview…'}</p>+ )}+ </div>+ <div className="flex flex-wrap items-center gap-2">+ <button type="button" className={buttonCls} onClick={togglePlay} disabled={!preview || !audioUrl}>+ {playing ? <Pause size={14} /> : <Play size={14} />} {playing ? 'Pause' : 'Play'}+ </button>+ <label htmlFor="mv-doc-scrub" className="sr-only">Scrub the composition preview</label>+ <input id="mv-doc-scrub" type="range" min={0} max={duration || 0} step={1 / fps} value={Math.min(t, duration || 0)}+ onChange={(e) => { audioRef.current?.pause(); setPlaying(false); seek(Number(e.target.value)); }}+ className="min-w-0 flex-1" />+ <span className="text-xs text-port-text-muted tabular-nums">{t.toFixed(2)}s / {duration.toFixed(1)}s</span>+ </div>+ {lyric && <p className="text-xs italic break-words" aria-live="off" data-testid="preview-lyric">♪ {lyric}</p>}+ {audioUrl && <audio ref={audioRef} src={audioUrl} preload="none" className="hidden" onEnded={() => setPlaying(false)} />}+ </div>+ );+}diff --git a/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx b/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsxnew file mode 100644index 0000000000..f70ed66f22--- /dev/null+++ b/client/src/components/musicVideo/CompositionPreviewPlayer.test.jsx@@ -0,0 +1,49 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';++const api = vi.hoisted(() => ({+ getMusicVideoCompositionPreview: vi.fn(),+ fetchMusicVideoPreviewAsset: vi.fn(),+}));+vi.mock('../../services/apiMusicVideo.js', () => api);++import CompositionPreviewPlayer from './CompositionPreviewPlayer.jsx';++const DOCUMENT = { directory: 'music-video/mv-1/composition/doc-a', entry: 'index.html' };+const project = {+ id: 'mv-1', name: 'Example', updatedAt: '2026-01-01T00:00:00.000Z', composition: { mode: 'document', document: DOCUMENT },+ lyricCues: [{ id: 'l1', text: 'first line', startSec: 1, endSec: 3 }, { id: 'l2', text: 'second line', startSec: 3, endSec: 6 }],+};++beforeEach(() => {+ for (const fn of Object.values(api)) fn.mockReset();+ api.getMusicVideoCompositionPreview.mockResolvedValue({ html: '<!doctype html><p>preview</p>', assets: [], width: 1920, height: 1080, fps: 24, durationSec: 10 });+});++describe('CompositionPreviewPlayer', () => {+ it('runs the document in an opaque-origin sandbox and renders nothing without one', async () => {+ const { container, rerender } = render(<CompositionPreviewPlayer project={{ ...project, composition: { mode: 'document' } }} audioUrl={null} />);+ expect(container).toBeEmptyDOMElement();+ expect(api.getMusicVideoCompositionPreview).not.toHaveBeenCalled();++ rerender(<CompositionPreviewPlayer project={project} audioUrl={null} />);+ const frame = await screen.findByTitle('Composition document preview');+ expect(frame.getAttribute('sandbox')).toBe('allow-scripts');+ });++ it('seeks to each outside request once the preview knows its length, and follows the lyric line', async () => {+ const { rerender } = render(<CompositionPreviewPlayer project={project} audioUrl="/data/music/song.mp3" seekRequest={{ t: 2, n: 1 }} />);+ // The request arrived before the preview loaded; it applies when the duration is known.+ await waitFor(() => expect(screen.getByText('2.00s / 10.0s')).toBeTruthy());+ expect(screen.getByTestId('preview-lyric')).toHaveTextContent('first line');++ // Seeking again to the same time is a new request (a new n), not a no-op.+ rerender(<CompositionPreviewPlayer project={project} audioUrl="/data/music/song.mp3" seekRequest={{ t: 4.5, n: 2 }} />);+ await waitFor(() => expect(screen.getByText('4.50s / 10.0s')).toBeTruthy());+ expect(screen.getByTestId('preview-lyric')).toHaveTextContent('second line');++ // Past the end clamps to the last frame instead of leaving the timeline.+ rerender(<CompositionPreviewPlayer project={project} audioUrl="/data/music/song.mp3" seekRequest={{ t: 99, n: 3 }} />);+ await waitFor(() => expect(screen.getByText(/^9\.9\ds \/ 10\.0s$/)).toBeTruthy());+ });+});diff --git a/client/src/components/musicVideo/DevArtifactDrawer.jsx b/client/src/components/musicVideo/DevArtifactDrawer.jsxindex 4ceda895fd..17687f4c27 100644--- a/client/src/components/musicVideo/DevArtifactDrawer.jsx+++ b/client/src/components/musicVideo/DevArtifactDrawer.jsx@@ -47,7 +47,7 @@ function Viewer({ projectId, artifact, version }) {* history, notes and review actions. For the sheet the Cast & Sets check-in is* waiting on, the review actions are the stage's own: "Regenerate with notes"* and "Approve & continue". Open state and the viewed version live in the URL- * (`/music-video/:projectId/dev/:artifactId?v=N`).+ * (`/music-video/:projectId/:stage/dev/:artifactId?v=N`; the older `/music-video/:projectId/dev/:artifactId` still opens it).*/export default function DevArtifactDrawer({open, onClose, project, artifact, version, onVersionChange, ops, busy, castAndSets,diff --git a/client/src/components/musicVideo/DevArtifactsPanel.jsx b/client/src/components/musicVideo/DevArtifactsPanel.jsxindex 06123d1a8c..26dcf6efc1 100644--- a/client/src/components/musicVideo/DevArtifactsPanel.jsx+++ b/client/src/components/musicVideo/DevArtifactsPanel.jsx@@ -22,12 +22,18 @@ const ACCEPT = '.html,.htm,.md,.mp4,.png,.jpg,.jpeg';/*** The project's development files ("ingredients") — the Cast & Sets sheet,* animatics, treatments, storyboards — with their review status. Opening one- * navigates to its deep link (`/music-video/:projectId/dev/:artifactId`),+ * navigates to its deep link (`/music-video/:projectId/:stage/dev/:artifactId`),* which shows it in the viewer drawer.+ *+ * `kinds` narrows the list to those artifact kinds (the Cast & Sets tab shows+ * only its own sheets); without `onUpload` the import control is left out.*/-export default function DevArtifactsPanel({ project, busy, onOpen, onUpload }) {+export default function DevArtifactsPanel({+ project, busy, onOpen, onUpload = null, kinds = null, title = 'Development',+ emptyText = 'Check-in sheets, animatics and other working files',+}) {const artifacts = (project.devArtifacts || [])- .filter((a) => !a.deleted)+ .filter((a) => !a.deleted && (!kinds || kinds.includes(a.kind))).sort((a, b) => String(b.updatedAt || '').localeCompare(String(a.updatedAt || '')));const [kind, setKind] = useState('other');const idPrefix = `mv-dev-${project.id}`;@@ -42,19 +48,21 @@ export default function DevArtifactsPanel({ project, busy, onOpen, onUpload }) {<section className="bg-port-card border border-port-border rounded-lg p-3 space-y-2 min-w-0" aria-labelledby={`${idPrefix}-title`}><div className="flex flex-wrap items-center gap-2"><FolderOpen size={16} className="text-port-accent shrink-0" aria-hidden="true" />- <h3 id={`${idPrefix}-title`} className="text-sm font-medium">Development</h3>- <span className="text-xs text-port-text-muted">{artifacts.length ? `${artifacts.length} file${artifacts.length === 1 ? '' : 's'}` : 'Check-in sheets, animatics and other working files'}</span>- <div className="ml-auto flex flex-wrap items-center gap-2">- <label htmlFor={`${idPrefix}-kind`} className="sr-only">Kind of file to import</label>- <select id={`${idPrefix}-kind`} value={kind} onChange={(e) => setKind(e.target.value)} disabled={busy}- className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs min-h-[44px] sm:min-h-0">- {Object.entries(DEV_ARTIFACT_KIND_LABELS).map(([id, label]) => <option key={id} value={id}>{label}</option>)}- </select>- <FilePickerButton accept={ACCEPT} onChange={upload} disabled={busy} ariaLabel="Import development file"- className="flex items-center gap-1 text-sm text-port-accent min-h-[44px] sm:min-h-0 px-1 cursor-pointer">- <Upload size={14} aria-hidden="true" /> Import- </FilePickerButton>- </div>+ <h3 id={`${idPrefix}-title`} className="text-sm font-medium">{title}</h3>+ <span className="text-xs text-port-text-muted">{artifacts.length ? `${artifacts.length} file${artifacts.length === 1 ? '' : 's'}` : emptyText}</span>+ {onUpload && (+ <div className="ml-auto flex flex-wrap items-center gap-2">+ <label htmlFor={`${idPrefix}-kind`} className="sr-only">Kind of file to import</label>+ <select id={`${idPrefix}-kind`} value={kind} onChange={(e) => setKind(e.target.value)} disabled={busy}+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs min-h-[44px] sm:min-h-0">+ {Object.entries(DEV_ARTIFACT_KIND_LABELS).map(([id, label]) => <option key={id} value={id}>{label}</option>)}+ </select>+ <FilePickerButton accept={ACCEPT} onChange={upload} disabled={busy} ariaLabel="Import development file"+ className="flex items-center gap-1 text-sm text-port-accent min-h-[44px] sm:min-h-0 px-1 cursor-pointer">+ <Upload size={14} aria-hidden="true" /> Import+ </FilePickerButton>+ </div>+ )}</div>{artifacts.length > 0 && (<ul className="divide-y divide-port-border">diff --git a/client/src/components/musicVideo/DocumentCompositionPanel.jsx b/client/src/components/musicVideo/DocumentCompositionPanel.jsxindex 79050513e3..a30843cc3d 100644--- a/client/src/components/musicVideo/DocumentCompositionPanel.jsx+++ b/client/src/components/musicVideo/DocumentCompositionPanel.jsx@@ -1,14 +1,13 @@-import { useCallback, useEffect, useRef, useState } from 'react';+import { useState } from 'react';import FilePickerButton from '../ui/FilePickerButton.jsx';-import { Download, FileArchive, FolderInput, LayoutTemplate, Pause, Play, Unlink } from 'lucide-react';+import { Download, FileArchive, FolderInput, LayoutTemplate, Unlink } from 'lucide-react';import toast from '../ui/Toast';import { downloadBlob } from '../../lib/downloadBlob';import { formatBytes, timeAgo } from '../../utils/formatters.js';import { compositionDraft } from './compositionDraft.js';import {- detachMusicVideoCompositionDocument, fetchMusicVideoPreviewAsset, getMusicVideoCompositionDocument, getMusicVideoCompositionExport,- getMusicVideoCompositionPreview, importMusicVideoCompositionDirectory, importMusicVideoCompositionZip,- startMusicVideoCompositionTemplate,+ detachMusicVideoCompositionDocument, getMusicVideoCompositionDocument, getMusicVideoCompositionExport,+ importMusicVideoCompositionDirectory, importMusicVideoCompositionZip, startMusicVideoCompositionTemplate,} from '../../services/apiMusicVideo.js';const buttonCls = 'flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50';@@ -50,7 +49,7 @@ function OverlayEditor({ project, onSave }) {const field = (key) => ({ value: draft[key], onChange: (e) => setDraft((d) => ({ ...d, [key]: e.target.value })), onBlur: () => save() });return (<details className="rounded border border-port-border p-2 text-xs">- <summary className="cursor-pointer select-none text-port-text-muted">HUD overlay — {overlay?.enabled === false || !overlay ? 'off' : 'on'} (drawn by the layered template)</summary>+ <summary className="cursor-pointer select-none text-port-text-muted min-h-[44px] sm:min-h-0 flex items-center">HUD overlay — {overlay?.enabled === false || !overlay ? 'off' : 'on'} (drawn by the layered template)</summary><div className="mt-2 flex flex-wrap items-center gap-3"><label htmlFor="mv-doc-hud-on" className="flex items-center gap-1 min-h-[44px] sm:min-h-0"><input id="mv-doc-hud-on" type="checkbox" checked={Boolean(overlay) && overlay.enabled !== false} onChange={(e) => save({ enabled: e.target.checked })} /> Show HUD@@ -98,7 +97,7 @@ function DocumentFiles({ projectId, directory }) {};return (<details key={directory} className="rounded border border-port-border p-2 text-xs" onToggle={(e) => load(e.currentTarget.open)}>- <summary className="cursor-pointer select-none text-port-text-muted">Files</summary>+ <summary className="cursor-pointer select-none text-port-text-muted min-h-[44px] sm:min-h-0 flex items-center">Files</summary>{error && <p role="status" className="mt-1 text-port-error">{error}</p>}{manifest && !manifest.available && <p className="mt-1 text-port-warning">The document folder is missing on this machine — import it again.</p>}{manifest?.available && (@@ -112,115 +111,18 @@ function DocumentFiles({ projectId, directory }) {/*** The project's composition document (render style `document`): what is- * attached, import (template / zip / data folder), export, and a live preview.- * The preview runs in an opaque-origin sandbox that cannot fetch; this panel- * fetches the scene takes and document media and posts them in as Blobs.+ * attached, import (template / zip / data folder), export, the HUD overlay and+ * the document's files. The live preview is `CompositionPreviewPlayer`, docked+ * beside the stage tabs so it stays visible while scenes and typography are+ * edited.*/-export default function DocumentCompositionPanel({ project, audioUrl, onProject, onSave }) {+export default function DocumentCompositionPanel({ project, onProject, onSave }) {const doc = project.composition?.document || null;const [busy, setBusy] = useState(null);// Replacing or detaching drops the current version folder once nothing// points at it, so both ask for a second click (no window.confirm).const [confirming, setConfirming] = useState(null);const [folder, setFolder] = useState('');- const [preview, setPreview] = useState(null);- const [previewError, setPreviewError] = useState('');- const [status, setStatus] = useState('');- const [t, setT] = useState(0);- const [playing, setPlaying] = useState(false);- const iframeRef = useRef(null);- const audioRef = useRef(null);- const blobCache = useRef(new Map());- const seekState = useRef({ inFlight: false, pending: null, ready: false });-- const refresh = doc ? `${doc.directory}|${project.updatedAt}` : null;- useEffect(() => {- let active = true;- setPreview(null);- setPreviewError('');- seekState.current = { inFlight: false, pending: null, ready: false };- if (!refresh) return () => { active = false; };- getMusicVideoCompositionPreview(project.id, { silent: true })- .then((next) => { if (active) setPreview(next); })- .catch((err) => { if (active) setPreviewError(err?.message || 'Could not build the preview'); });- return () => { active = false; };- }, [project.id, refresh]);-- const postSeek = useCallback((time) => {- const frame = iframeRef.current?.contentWindow;- const state = seekState.current;- if (!frame || !state.ready) return;- if (state.inFlight) { state.pending = time; return; }- state.inFlight = true;- frame.postMessage({ type: 'portos-mv:seek', t: time }, '*');- }, []);-- useEffect(() => {- if (!preview) return undefined;- let active = true;- const onMessage = async (event) => {- if (event.source !== iframeRef.current?.contentWindow) return;- const message = event.data || {};- const state = seekState.current;- if (message.type === 'portos-mv:loaded') {- const files = {};- let loaded = 0;- for (const asset of preview.assets || []) {- if (!active) return;- setStatus(`Loading preview media ${loaded + 1}/${preview.assets.length}…`);- const blob = blobCache.current.get(asset.url) || await fetchMusicVideoPreviewAsset(asset.url).catch(() => null);- if (blob) { blobCache.current.set(asset.url, blob); files[asset.key] = blob; }- loaded += 1;- }- if (!active) return;- setStatus(loaded === (preview.assets || []).length ? '' : 'Some preview media could not be loaded');- iframeRef.current?.contentWindow?.postMessage({ type: 'portos-mv:assets', files }, '*');- state.ready = true;- postSeek(t);- } else if (message.type === 'portos-mv:seeked') {- state.inFlight = false;- if (state.pending != null) { const next = state.pending; state.pending = null; postSeek(next); }- } else if (message.type === 'portos-mv:error') {- state.inFlight = false;- setPreviewError(String(message.message || 'The composition document failed in the preview'));- }- };- window.addEventListener('message', onMessage);- return () => { active = false; window.removeEventListener('message', onMessage); };- // `t` is read once when the page loads; later seeks go through postSeek.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [preview, postSeek]);-- const duration = preview?.durationSec || 0;- const fps = preview?.fps || 24;- const seek = useCallback((time) => {- const next = Math.min(Math.max(0, time), Math.max(0, duration - 1 / fps));- setT(next);- postSeek(next);- if (audioRef.current && Math.abs((audioRef.current.currentTime || 0) - next) > 0.05) audioRef.current.currentTime = next;- }, [duration, fps, postSeek]);-- useEffect(() => {- if (!playing) return undefined;- let handle = 0;- let posted = -1;- const tick = () => {- const time = audioRef.current?.currentTime || 0;- const frameIndex = Math.floor(time * fps + 1e-9);- if (frameIndex !== posted) { posted = frameIndex; setT(time); postSeek(time); }- handle = requestAnimationFrame(tick);- };- handle = requestAnimationFrame(tick);- return () => cancelAnimationFrame(handle);- }, [playing, fps, postSeek]);-- const togglePlay = () => {- const audio = audioRef.current;- if (!audio) return;- if (playing) { audio.pause(); setPlaying(false); return; }- audio.play?.()?.catch?.(() => {});- setPlaying(true);- };const run = async (label, task, success) => {setBusy(label);@@ -245,7 +147,6 @@ export default function DocumentCompositionPanel({ project, audioUrl, onProject,});const detach = confirmFirst('detach', () => run('detach', () => detachMusicVideoCompositionDocument(project.id, { silent: true }), 'Composition document detached'));- const aspect = preview?.width && preview?.height ? `${preview.width} / ${preview.height}` : '16 / 9';return (<section className="mt-3 space-y-2 rounded-lg border border-port-border bg-port-bg p-2" aria-label="Composition document"><div className="flex flex-wrap items-center gap-2 text-xs text-port-text-muted">@@ -286,35 +187,7 @@ export default function DocumentCompositionPanel({ project, audioUrl, onProject,</button></div><OverlayEditor key={`${project.id}-${project.composition?.overlay ? 'hud' : 'none'}`} project={project} onSave={onSave} />- {doc && (- <>- <DocumentFiles key={doc.directory} projectId={project.id} directory={doc.directory} />- {previewError && <p className="text-xs text-port-error" role="alert">{previewError}</p>}- {status && <p className="text-xs text-port-text-muted">{status}</p>}- <div className="overflow-hidden rounded border border-port-border bg-black mx-auto" style={{ aspectRatio: aspect, maxHeight: '70vh', maxWidth: '100%' }}>- {preview?.html ? (- <iframe ref={iframeRef} title="Composition document preview" sandbox="allow-scripts" srcDoc={preview.html} className="h-full w-full" />- ) : (- <p className="p-3 text-xs text-port-text-muted">{previewError ? '' : 'Building the preview…'}</p>- )}- </div>- <div className="flex flex-wrap items-center gap-2">- <button type="button" className={buttonCls} onClick={togglePlay} disabled={!preview || !audioUrl}>- {playing ? <Pause size={14} /> : <Play size={14} />} {playing ? 'Pause' : 'Play'}- </button>- <label htmlFor="mv-doc-scrub" className="sr-only">Scrub the composition preview</label>- <input id="mv-doc-scrub" type="range" min={0} max={duration || 0} step={1 / fps} value={Math.min(t, duration || 0)}- onChange={(e) => { audioRef.current?.pause(); setPlaying(false); seek(Number(e.target.value)); }}- className="min-w-0 flex-1" />- <span className="text-xs text-port-text-muted tabular-nums">{t.toFixed(2)}s / {duration.toFixed(1)}s</span>- </div>- <p className="text-[11px] text-port-text-muted">- Renders, draft excerpts, proofs and auto-review all seek this document on song time with the song as the only audio (plus the sound bed, when set).- It reads <code>window.PORTOS_MV</code> from <code>portos-mv.js</code>; each scene's selected take is copied into <code>media/</code>.- </p>- {audioUrl && <audio ref={audioRef} src={audioUrl} preload="none" className="hidden" onEnded={() => setPlaying(false)} />}- </>- )}+ {doc && <DocumentFiles key={doc.directory} projectId={project.id} directory={doc.directory} />}</section>);}diff --git a/client/src/components/musicVideo/DocumentCompositionPanel.test.jsx b/client/src/components/musicVideo/DocumentCompositionPanel.test.jsxindex 1c5dc941e8..b7ececc69f 100644--- a/client/src/components/musicVideo/DocumentCompositionPanel.test.jsx+++ b/client/src/components/musicVideo/DocumentCompositionPanel.test.jsx@@ -2,14 +2,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { fireEvent, render, screen, waitFor } from '@testing-library/react';const api = vi.hoisted(() => ({- getMusicVideoCompositionPreview: vi.fn(),getMusicVideoCompositionDocument: vi.fn(),startMusicVideoCompositionTemplate: vi.fn(),importMusicVideoCompositionZip: vi.fn(),importMusicVideoCompositionDirectory: vi.fn(),getMusicVideoCompositionExport: vi.fn(),detachMusicVideoCompositionDocument: vi.fn(),- fetchMusicVideoPreviewAsset: vi.fn(),}));vi.mock('../../services/apiMusicVideo.js', () => api);vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));@@ -22,27 +20,23 @@ const attached = { ...bare, composition: { mode: 'document', document: DOCUMENTbeforeEach(() => {for (const fn of Object.values(api)) fn.mockReset();- api.getMusicVideoCompositionPreview.mockResolvedValue({ html: '<!doctype html><p>preview</p>', assets: [], width: 1920, height: 1080, fps: 24, durationSec: 10 });api.startMusicVideoCompositionTemplate.mockResolvedValue({ project: attached, document: DOCUMENT });api.detachMusicVideoCompositionDocument.mockResolvedValue({ project: bare });});describe('DocumentCompositionPanel', () => {- it('starts from the template in one click when nothing is attached, and builds no preview', async () => {+ it('starts from the template in one click when nothing is attached', async () => {const onProject = vi.fn();- render(<DocumentCompositionPanel project={bare} audioUrl={null} onProject={onProject} onSave={vi.fn()} />);+ render(<DocumentCompositionPanel project={bare} onProject={onProject} onSave={vi.fn()} />);fireEvent.click(screen.getByRole('button', { name: /Start from template/ }));await waitFor(() => expect(onProject).toHaveBeenCalledWith(attached));expect(api.startMusicVideoCompositionTemplate).toHaveBeenCalledWith('mv-1', 'layered', { silent: true });- expect(api.getMusicVideoCompositionPreview).not.toHaveBeenCalled();});- it('shows the attached document in a sandboxed preview and asks twice before replacing or detaching it', async () => {+ it('shows the attached document and asks twice before replacing or detaching it', async () => {const onProject = vi.fn();- render(<DocumentCompositionPanel project={attached} audioUrl={null} onProject={onProject} onSave={vi.fn()} />);+ render(<DocumentCompositionPanel project={attached} onProject={onProject} onSave={vi.fn()} />);expect(screen.getByText(/template · layered · 9 files/)).toBeTruthy();- const frame = await screen.findByTitle('Composition document preview');- expect(frame.getAttribute('sandbox')).toBe('allow-scripts');fireEvent.click(screen.getByRole('button', { name: /Replace with template/ }));expect(api.startMusicVideoCompositionTemplate).not.toHaveBeenCalled();diff --git a/client/src/components/musicVideo/LyricsPanel.jsx b/client/src/components/musicVideo/LyricsPanel.jsxindex 0faf013017..9395cc7b59 100644--- a/client/src/components/musicVideo/LyricsPanel.jsx+++ b/client/src/components/musicVideo/LyricsPanel.jsx@@ -171,7 +171,7 @@ export default function LyricsPanel({ project, onEditLocal, onSave, onImport, imreturn (<details className="mt-2 bg-port-bg border border-port-border rounded-lg p-2 text-xs">- <summary className="cursor-pointer select-none text-port-text-muted">+ <summary className="cursor-pointer select-none text-port-text-muted min-h-[44px] sm:min-h-0 flex flex-wrap items-center gap-x-1">Lyrics, phrases & pacing — {cues.length} line{cues.length === 1 ? '' : 's'} ({timedCount} timed)· {phrases.length} phrase{phrases.length === 1 ? '' : 's'}<span className="block sm:inline sm:ml-1">— AI Plan cuts on timed lines and phrase edges; no lyrics = an instrumental plan.</span>diff --git a/client/src/components/musicVideo/MusicVideoLayout.jsx b/client/src/components/musicVideo/MusicVideoLayout.jsxnew file mode 100644index 0000000000..dd758f2972--- /dev/null+++ b/client/src/components/musicVideo/MusicVideoLayout.jsx@@ -0,0 +1,170 @@+import { useEffect, useRef, useState } from 'react';+import {+ AlertTriangle, ArrowRight, CheckCircle2, Circle, CircleDot, Clapperboard, Film, Layers, LayoutGrid, Music, Play,+ SlidersHorizontal, Users,+} from 'lucide-react';+import TabPills from '../ui/TabPills.jsx';+import Pill from '../ui/Pill.jsx';+import { PREVIEW_STAGES } from '../../lib/musicVideoStages.js';+import { formatUsd } from '../../utils/formatters.js';++// One icon per stage: the bottom tab bar collapses to icons on a phone, and a+// repeated glyph would be a repeated destination.+const STAGE_ICONS = {+ setup: SlidersHorizontal, 'cast-sets': Users, board: LayoutGrid, produce: Clapperboard, compose: Layers, review: Film,+};+const STATE_MARKS = {+ done: { Icon: CheckCircle2, cls: 'text-port-success', label: 'done' },+ active: { Icon: CircleDot, cls: 'text-port-accent', label: 'in progress' },+ blocked: { Icon: AlertTriangle, cls: 'text-port-warning', label: 'needs you' },+ todo: { Icon: Circle, cls: 'text-port-text-muted', label: 'not started' },+};++// Below `lg` the preview is a mini-player pinned above the bottom tab bar (or+// the viewport edge once the tab bar is in the header); from `lg` it is a+// sticky right column that clears the header (the -0.75rem cancels the+// scroll container's md:p-6, which sticky offsets are measured inside of).+const DOCK_CLASSES = 'max-lg:fixed max-lg:inset-x-0 max-lg:bottom-0 max-lg:z-30 max-lg:max-h-[70vh] max-lg:overflow-y-auto max-md:bottom-[calc(env(safe-area-inset-bottom)+3rem)] lg:sticky lg:top-[calc(var(--mv-header-h,9rem)-0.75rem)] lg:max-h-[calc(100vh-var(--mv-header-h,9rem)-2rem)] lg:overflow-y-auto';++/** Progress through the pipeline. Status only — the tabs below are the navigation. */+function ProgressStrip({ stages, current }) {+ return (+ <ol aria-label="Progress" className="flex min-w-0 items-center gap-x-3 gap-y-1 overflow-hidden text-xs">+ {stages.map((stage) => {+ const { Icon, cls, label } = STATE_MARKS[stage.state];+ const isCurrent = stage.id === current;+ return (+ <li+ key={stage.id}+ aria-current={isCurrent ? 'step' : undefined}+ data-state={stage.state}+ className={`flex shrink-0 items-center gap-1 ${isCurrent ? 'font-medium text-port-text' : 'text-port-text-muted'}`}+ >+ <Icon size={13} className={`shrink-0 ${cls}`} aria-hidden="true" />+ <span className={isCurrent ? '' : 'max-sm:sr-only'}>{stage.title}</span>+ <span className="sr-only">({label})</span>+ </li>+ );+ })}+ </ol>+ );+}++/**+ * The Music Video project frame: a sticky header (name, track, spend, the+ * progress strip and the one next action for the project's stage), the stage+ * tabs — on top from `md` up, a bottom tab bar on a phone — the active stage's+ * content, and the docked preview player beside it on the Board, Compose and+ * Review tabs.+ *+ * `progress` is `deriveStages(project)`; `nextAction` is `deriveNextAction(…)`.+ * `dock` is the `PreviewDock` element (or null when there is nothing to preview).+ */+export default function MusicVideoLayout({+ project, trackLabel, stage, onStageChange, progress, nextAction, onNextAction, spend,+ dock, children,+}) {+ const headerRef = useRef(null);+ const rootRef = useRef(null);+ const dockVisible = !!dock && PREVIEW_STAGES.has(stage);+ // The preview loads media, so it mounts the first time a stage shows it and+ // then stays mounted — hidden on the other tabs — to keep its playhead.+ const [dockMounted, setDockMounted] = useState(false);+ useEffect(() => { if (dockVisible) setDockMounted(true); }, [dockVisible]);++ // The dock sticks just under the header, whose height depends on wrapping.+ useEffect(() => {+ const header = headerRef.current;+ const root = rootRef.current;+ if (!header || !root || typeof ResizeObserver === 'undefined') return undefined;+ const apply = () => root.style.setProperty('--mv-header-h', `${Math.round(header.getBoundingClientRect().height)}px`);+ apply();+ const observer = new ResizeObserver(apply);+ observer.observe(header);+ return () => observer.disconnect();+ }, []);++ // A new tab starts at its top, not wherever the last one was scrolled to.+ const firstStage = useRef(true);+ useEffect(() => {+ if (firstStage.current) { firstStage.current = false; return; }+ document.getElementById('main-content')?.scrollTo?.({ top: 0 });+ }, [stage]);++ const tabs = progress.stages.map((entry) => ({+ id: entry.id,+ label: entry.label,+ icon: STAGE_ICONS[entry.id],+ trailing: entry.state === 'blocked'+ ? <AlertTriangle size={12} className="shrink-0 text-port-warning" aria-label="needs you" />+ : entry.state === 'done' ? <CheckCircle2 size={12} className="shrink-0 text-port-success max-lg:hidden" aria-label="done" /> : null,+ }));+ const showSpend = spend.spentUsd > 0 || spend.capUsd != null;+ const ActionIcon = nextAction?.kind === 'goto' ? ArrowRight : Play;++ return (+ <div ref={rootRef} className={`space-y-3 ${dockVisible ? 'max-lg:pb-40' : 'max-md:pb-20'}`}>+ <header+ ref={headerRef}+ className="sticky top-[calc(env(safe-area-inset-top)-1rem)] z-30 -mx-4 space-y-2 border-b border-port-border bg-port-bg px-4 pt-2 md:top-[calc(env(safe-area-inset-top)-1.5rem)] md:-mx-6 md:px-6"+ >+ <div className="flex min-w-0 items-center gap-3">+ <h2 className="min-w-0 flex-1 truncate text-lg font-semibold">{project.name}</h2>+ {nextAction && (+ <button+ type="button"+ onClick={onNextAction}+ disabled={nextAction.disabled}+ title={nextAction.reason}+ className="flex min-h-[44px] shrink-0 items-center gap-1 rounded bg-port-accent px-3 py-1.5 text-sm text-white disabled:opacity-50 sm:min-h-0"+ >+ <ActionIcon size={14} aria-hidden="true" /> {nextAction.label}+ </button>+ )}+ </div>+ <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1">+ <ProgressStrip stages={progress.stages} current={progress.current} />+ <span className="flex min-w-0 items-center gap-1 text-xs text-port-text-muted max-sm:hidden">+ <Music size={12} className="shrink-0" aria-hidden="true" />+ <span className="truncate">{trackLabel}</span>+ </span>+ {showSpend && (+ <Pill size="xs" tone={spend.capUsd != null && spend.spentUsd >= spend.capUsd ? 'warning' : 'muted'}>+ <span title="Paid generation used across this project's production runs, against the cap">+ {formatUsd(spend.spentUsd)}{spend.capUsd != null ? ` / ${formatUsd(spend.capUsd)}` : ' · no cap'}+ </span>+ </Pill>+ )}+ </div>+ <nav+ aria-label="Stages"+ className="max-md:fixed max-md:inset-x-0 max-md:bottom-0 max-md:z-40 max-md:border-t max-md:border-port-border max-md:bg-port-bg max-md:pb-[env(safe-area-inset-bottom)]"+ >+ <TabPills+ tabs={tabs}+ activeTab={stage}+ onChange={onStageChange}+ variant="underline"+ size="sm"+ stretch+ mobileCompact+ ariaLabel="Music video stages"+ controlsIdPrefix="mv-stage"+ />+ </nav>+ </header>++ <div className={`grid items-start gap-4 ${dockVisible ? 'lg:grid-cols-[minmax(0,1fr)_minmax(20rem,26rem)]' : ''}`}>+ <div+ role="tabpanel"+ id={`mv-stage-${stage}`}+ aria-labelledby={`tab-${stage}`}+ className="min-w-0 space-y-3"+ >+ {children}+ </div>+ {dockMounted && dock ? <div className={dockVisible ? DOCK_CLASSES : 'hidden'}>{dock}</div> : null}+ </div>+ </div>+ );+}diff --git a/client/src/components/musicVideo/PreviewDock.jsx b/client/src/components/musicVideo/PreviewDock.jsxnew file mode 100644index 0000000000..509709b64f--- /dev/null+++ b/client/src/components/musicVideo/PreviewDock.jsx@@ -0,0 +1,75 @@+import { useEffect, useRef } from 'react';+import { ChevronDown, ChevronUp, MonitorPlay } from 'lucide-react';+import CompositionPreviewPlayer from './CompositionPreviewPlayer.jsx';+import { resolvePreviewSource } from '../../lib/musicVideoStages.js';+import { formatTimecode } from '../../utils/formatters.js';++// The fallback when the project has no composition document: the newest+// finished draft excerpt. Its clock starts at the excerpt's own start, so a+// seek to song time `t` lands at `t - startSec` and is ignored outside it.+function ExcerptPreview({ excerpt, seekRequest, collapsed }) {+ const videoRef = useRef(null);+ const pending = useRef(null);+ const applied = useRef(null);+ const seekTo = (t) => {+ const video = videoRef.current;+ if (!video) return;+ if (video.readyState >= 1) video.currentTime = Math.min(t, video.duration || t);+ else pending.current = t;+ };+ useEffect(() => {+ if (!seekRequest || applied.current === seekRequest.n) return;+ applied.current = seekRequest.n;+ const t = seekRequest.t - excerpt.startSec;+ if (t >= 0 && t <= excerpt.endSec - excerpt.startSec) seekTo(t);+ }, [seekRequest, excerpt.startSec, excerpt.endSec]);+ return (+ <video+ ref={videoRef}+ src={`/data/videos/${excerpt.filename}`}+ controls+ playsInline+ preload="metadata"+ onLoadedMetadata={() => { if (pending.current != null) { seekTo(pending.current); pending.current = null; } }}+ aria-label="Latest draft excerpt preview"+ className={`aspect-video max-h-[50vh] w-full rounded border border-port-border bg-black object-contain ${collapsed ? 'max-lg:hidden' : ''}`}+ />+ );+}++/**+ * The docked preview card. `MusicVideoLayout` places it: a right-hand column+ * beside the Board, Compose and Review tabs from `lg` up, a collapsible+ * mini-player pinned above the bottom tab bar below it. Plays the composition+ * document when there is one, else the latest draft excerpt; renders nothing+ * when there is neither. `seekRequest` (`{ t, n }`) is the scene-card seek.+ */+export default function PreviewDock({ project, audioUrl, seekRequest, collapsed, onToggleCollapsed }) {+ const source = resolvePreviewSource(project);+ if (!source) return null;+ const subtitle = source.kind === 'document'+ ? 'Composition document'+ : `Draft ${formatTimecode(source.excerpt.startSec)}–${formatTimecode(source.excerpt.endSec)}`;+ const Chevron = collapsed ? ChevronUp : ChevronDown;+ return (+ <aside aria-label="Preview" className="space-y-2 rounded-lg border border-port-border bg-port-card p-2 max-lg:rounded-b-none">+ <div className="flex items-center gap-2 text-xs text-port-text-muted">+ <MonitorPlay size={14} className="shrink-0 text-port-accent" aria-hidden="true" />+ <span className="text-sm font-medium text-port-text">Preview</span>+ <span className="min-w-0 truncate">{subtitle}</span>+ <button+ type="button"+ onClick={onToggleCollapsed}+ aria-expanded={!collapsed}+ aria-label={collapsed ? 'Expand preview' : 'Collapse preview'}+ className="ml-auto flex min-h-[44px] min-w-[44px] items-center justify-center rounded lg:hidden"+ >+ <Chevron size={16} aria-hidden="true" />+ </button>+ </div>+ {source.kind === 'document'+ ? <CompositionPreviewPlayer project={project} audioUrl={audioUrl} seekRequest={seekRequest} collapsed={collapsed} />+ : <ExcerptPreview excerpt={source.excerpt} seekRequest={seekRequest} collapsed={collapsed} />}+ </aside>+ );+}diff --git a/client/src/components/musicVideo/ProductionPanel.test.jsx b/client/src/components/musicVideo/ProductionPanel.test.jsxdeleted file mode 100644index be99bb030a..0000000000--- a/client/src/components/musicVideo/ProductionPanel.test.jsx+++ /dev/null@@ -1,80 +0,0 @@-/**- * Production panel (#9066) over the real useMusicVideoProduction hook with a- * mocked API and socket: a run starts only with the director's explicit pool- * and limits, a restart-interrupted run is resumed explicitly, and a pushed- * project updates the visible run.- */-import { describe, it, expect, vi, beforeEach } from 'vitest';-import { useState } from 'react';-import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';--const listeners = vi.hoisted(() => new Map());-vi.mock('../../services/socket', () => ({- default: { on: (ev, fn) => listeners.set(ev, fn), off: (ev) => listeners.delete(ev) },-}));-vi.mock('../../services/apiMusicVideo.js', () => ({- startMusicVideoProduction: vi.fn(),- resumeMusicVideoProduction: vi.fn(),- stopMusicVideoProduction: vi.fn(),- cancelMusicVideoProduction: vi.fn(),-}));-vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), info: vi.fn(), error: vi.fn() } }));-vi.mock('../../hooks/useProviderModels.js', () => ({- default: () => ({- providers: [], selectedProviderId: '', selectedModel: '', availableModels: [],- setSelectedProviderId: () => {}, setSelectedModel: () => {},- }),-}));--import ProductionPanel from './ProductionPanel.jsx';-import useMusicVideoProduction from '../../hooks/useMusicVideoProduction.js';-import * as api from '../../services/apiMusicVideo.js';--const run = (over = {}) => ({- id: 'run-1', status: 'running', interrupted: false, directive: '', stopReason: null, error: null,- pool: [{ kind: 'image', mode: 'local', model: null }, { kind: 'video', mode: 'local', model: null }],- limits: { maxGenerations: 12, maxReviewAttempts: 3, spendCapUsd: null },- usage: { generations: 2, spentUsd: 0 },- steps: [{ key: 'frame:s1:base:1', kind: 'frame', sceneId: 's1', route: { kind: 'image', mode: 'local', model: null }, rationale: 'first eligible', status: 'queued', error: null }],- ...over,-});--function Harness({ initial }) {- const [project, setProject] = useState(initial);- const production = useMusicVideoProduction({ project, replaceProject: setProject });- return <ProductionPanel project={project} production={production} />;-}--describe('ProductionPanel', () => {- beforeEach(() => { vi.clearAllMocks(); listeners.clear(); });-- it('starts only when the director presses Start, with the allowed pool and limits', async () => {- api.startMusicVideoProduction.mockResolvedValue({ project: { id: 'p1', productionRuns: [run()] }, run: run() });- render(<Harness initial={{ id: 'p1', productionRuns: [] }} />);- expect(api.startMusicVideoProduction).not.toHaveBeenCalled();- fireEvent.change(screen.getByLabelText('Max generations'), { target: { value: '5' } });- fireEvent.click(screen.getByRole('button', { name: /Start production/ }));- await waitFor(() => expect(api.startMusicVideoProduction).toHaveBeenCalled());- const [id, body] = api.startMusicVideoProduction.mock.calls[0];- expect(id).toBe('p1');- expect(body.limits).toEqual({ maxGenerations: 5, maxReviewAttempts: 3 });- expect(body.pool.length).toBeGreaterThan(1);- expect(body.pool.every((r) => ['image', 'video'].includes(r.kind) && r.mode)).toBe(true);- expect(await screen.findByText('Running')).toBeTruthy();- });-- it('shows an interrupted run and resumes it only on request; pushed projects update it', async () => {- api.resumeMusicVideoProduction.mockResolvedValue({ project: { id: 'p1', productionRuns: [run()] }, run: run() });- render(<Harness initial={{ id: 'p1', productionRuns: [run({ interrupted: true })] }} />);- expect(screen.getByText(/server restarted/)).toBeTruthy();- expect(api.resumeMusicVideoProduction).not.toHaveBeenCalled();- fireEvent.click(screen.getByRole('button', { name: /Resume/ }));- await waitFor(() => expect(api.resumeMusicVideoProduction).toHaveBeenCalledWith('p1', 'run-1', {}, { silent: true }));-- act(() => listeners.get('music-video:production')({- projectId: 'p1', run: run({ status: 'blocked' }),- project: { id: 'p1', productionRuns: [run({ status: 'blocked', stopReason: 'No allowed route can generate the frame' })] },- }));- expect(await screen.findByText(/No allowed route can generate the frame/)).toBeTruthy();- });-});diff --git a/client/src/components/musicVideo/ProjectActionGroups.jsx b/client/src/components/musicVideo/ProjectActionGroups.jsxnew file mode 100644index 0000000000..1179993f95--- /dev/null+++ b/client/src/components/musicVideo/ProjectActionGroups.jsx@@ -0,0 +1,212 @@+import { Film, Music, Activity, Image as ImageIcon, Video, Wand2 } from 'lucide-react';+import RecordRenderPinRow from '../imageGen/RecordRenderPinRow.jsx';+import { MUSCRIPTOR_MODELS } from '../../lib/muscriptorModels.js';+import VideoRenderSettings from './VideoRenderSettings.jsx';+import { sceneRenderReady, sceneVisualLayer } from '../../lib/musicVideoLayers.js';+import { compositionDraft, RENDER_STYLES } from './compositionDraft.js';++/**+ * The board-level actions the old single toolbar carried, split by the stage+ * that owns them: analyze + MIDI (Setup), AI plan + auto-arrange (Board), the+ * frame/clip generators and their render pins (Produce), the render style+ * (Compose) and the final render (Review). Each group takes the page's hook+ * slots (`midi`, `videoSettings`, `sceneMedia`, `renderJob`) and the+ * page-owned in-flight flags in `busy`.+ */++const buttonCls = 'flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50';+const groupCls = 'flex min-w-0 flex-wrap items-center gap-2';++const uniqueCount = (scenes, key) => new Set(scenes.map((scene) => scene[key]).filter(Boolean)).size;+const noAudioOf = (project) => !project.trackId && !project.uploadedAudioFilename;++/** Analyze the beat grid and transcribe the track to MIDI. */+export function AudioActions({ project, midi, midiBound, busy, onAnalyze }) {+ const noAudio = noAudioOf(project);+ return (+ <div className={groupCls}>+ <button onClick={onAnalyze} disabled={busy.analyzing || noAudio}+ title={noAudio ? 'Link a track first' : 'Analyze beat grid'}+ className={buttonCls}>+ <Activity size={15} /> {busy.analyzing ? 'Analyzing…' : 'Analyze'}+ </button>+ {midiBound ? (+ <button onClick={midi.cancel} title="Cancel MIDI transcription"+ className="flex items-center gap-1 bg-port-warning/20 text-port-warning border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0">+ <Activity size={15} className="animate-spin" /> {midi.stageLabel} · Cancel+ </button>+ ) : (+ <>+ <select value={midi.model} onChange={(e) => midi.setModel(e.target.value)}+ disabled={midi.active}+ aria-label="MuScriptor model size"+ title="MuScriptor model size — larger is higher quality but slower and a bigger first-use download"+ className="bg-port-bg border border-port-border rounded px-1.5 py-1.5 text-sm capitalize min-h-[44px] sm:min-h-0 disabled:opacity-50">+ {MUSCRIPTOR_MODELS.map((m) => <option key={m} value={m}>{m}</option>)}+ </select>+ <button onClick={() => midi.start(project.id)}+ disabled={midi.active || noAudio}+ title={noAudio+ ? 'Link a track first'+ : `Transcribe the track to MIDI with MuScriptor (${midi.model} model, local — installs automatically on first use)`}+ className={buttonCls}>+ <Music size={15} /> MIDI+ </button>+ </>+ )}+ </div>+ );+}++/** Plan the shots against the analyzed song and spread them by energy. */+export function PlanActions({ project, busy, onPlan, onAutoArrange }) {+ const sceneCount = (project.scenes || []).length;+ return (+ <div className={groupCls}>+ <button onClick={onPlan} disabled={busy.planning || !project.audioAnalysis}+ title={!project.audioAnalysis ? 'Analyze the track first' : 'AI-plan bounded shots per song section, cut on timed lyrics, phrases and beats'}+ className={buttonCls}>+ <Wand2 size={15} /> {busy.planning ? 'Planning…' : 'AI Plan'}+ </button>+ <button onClick={onAutoArrange}+ disabled={busy.arranging || !project.audioAnalysis || sceneCount === 0}+ title={!project.audioAnalysis+ ? 'Analyze the track first'+ : sceneCount === 0+ ? 'Add scenes first'+ : 'Distribute scenes across song sections by energy'}+ className={buttonCls}>+ <Wand2 size={15} /> {busy.arranging ? 'Arranging…' : 'Auto-arrange'}+ </button>+ </div>+ );+}++/** The frame renderer pin, the scene-video renderer, and the batch generators. */+export function GenerationActions({ project, videoSettings, sceneMedia }) {+ const scenes = project.scenes || [];+ const sceneCount = scenes.length;+ // #8985: in a composed render a still needs only its frame and a title card+ // needs neither frame nor clip, so the counts cover the scenes that use them.+ const mode = project.composition?.mode || 'concat';+ const layered = mode === 'composed';+ const codeMode = mode === 'code';+ const frameScenes = scenes.filter((scene) => sceneVisualLayer(scene, { layered }) !== 'card');+ const footageScenes = scenes.filter((scene) => sceneVisualLayer(scene, { layered }) === 'footage');+ const referenceFrameCount = frameScenes.filter((scene) => scene.referenceImageId).length;+ const renderableSceneCount = footageScenes.filter((scene) => scene.videoHistoryId).length;+ const uniqueReferenceFrameCount = uniqueCount(frameScenes, 'referenceImageId');+ const uniqueVideoCount = uniqueCount(footageScenes, 'videoHistoryId');+ const missingFrameCount = frameScenes.length - referenceFrameCount;+ const missingVideoCount = footageScenes.length - renderableSceneCount;+ const footageFramesReady = footageScenes.every((scene) => scene.referenceImageId);+ const generatingFrames = Object.keys(sceneMedia.genScenes).length > 0;+ const generatingVideos = Object.keys(sceneMedia.genVideoScenes).length > 0;+ const footageBlocked = codeMode ? 'Code-rendered style draws the picture in code and does not generate footage' : '';+ return (+ <div className={groupCls}>+ <RecordRenderPinRow+ idPrefix="mv-frame-pin"+ label="Frames"+ imageMode={project.imageMode ?? null}+ imageModelId={project.imageModelId ?? null}+ onChange={videoSettings.changeFramePin}+ />+ <VideoRenderSettings videoSettings={videoSettings} generating={generatingVideos} />+ <button+ onClick={sceneMedia.generateMissingFrames}+ disabled={codeMode || videoSettings.framePinSaving || sceneCount === 0 || missingFrameCount === 0 || generatingFrames}+ title={footageBlocked || (videoSettings.framePinSaving+ ? 'Saving the frame renderer…'+ : (missingFrameCount > 0 ? `Generate ${missingFrameCount} missing reference frame${missingFrameCount === 1 ? '' : 's'}` : 'Every scene has a reference frame'))}+ className={buttonCls}+ >+ <ImageIcon size={15} /> Frames {referenceFrameCount}/{frameScenes.length}+ </button>+ <button+ onClick={sceneMedia.generateMissingVideos}+ disabled={codeMode || videoSettings.saving || footageScenes.length === 0 || missingVideoCount === 0 || !footageFramesReady || generatingVideos || !!videoSettings.videoBlockedReason}+ title={footageBlocked || videoSettings.videoBlockedReason+ || (!footageFramesReady+ ? 'Generate every reference frame first'+ : (missingVideoCount > 0 ? `Generate ${missingVideoCount} missing scene video${missingVideoCount === 1 ? '' : 's'}` : 'Every scene has a video'))}+ className={buttonCls}+ >+ <Video size={15} /> Videos {renderableSceneCount}/{footageScenes.length}+ </button>+ {(uniqueReferenceFrameCount < referenceFrameCount || uniqueVideoCount < renderableSceneCount) && (+ <span+ className="text-[10px] px-2 py-1.5 rounded border border-port-warning/40 bg-port-warning/10 text-port-warning"+ title={`${referenceFrameCount - uniqueReferenceFrameCount} scene${referenceFrameCount - uniqueReferenceFrameCount === 1 ? '' : 's'} reuse a reference frame; ${renderableSceneCount - uniqueVideoCount} reuse a video clip`}+ >+ Repetition: {uniqueReferenceFrameCount} unique frames · {uniqueVideoCount} unique clips+ </span>+ )}+ </div>+ );+}++/** Footage / composed / code-rendered / composition document. */+export function RenderStyleSelect({ project, onRenderStyle }) {+ return (+ <div>+ <label htmlFor="mv-toolbar-render-style" className="sr-only">Render style</label>+ <select id="mv-toolbar-render-style" value={compositionDraft(project).mode}+ onChange={(e) => onRenderStyle?.(e.target.value)}+ className="bg-port-bg border border-port-border rounded px-1.5 py-1.5 text-sm min-h-[44px] sm:min-h-0">+ {RENDER_STYLES.map(([value, label]) => <option key={value} value={value}>{label}</option>)}+ </select>+ </div>+ );+}++/** Render the complete video, or cancel the render in flight for this project. */+export function RenderFinalButton({ project, renderJob }) {+ const scenes = project.scenes || [];+ const sceneCount = scenes.length;+ const mode = project.composition?.mode || 'concat';+ const layered = mode === 'composed';+ const codeMode = mode === 'code';+ const documentMode = mode === 'document';+ const readySceneCount = scenes.filter((scene) => sceneRenderReady(scene, { layered })).length;+ const noAudio = noAudioOf(project);+ const codeDuration = Math.max(+ project.audioAnalysis?.durationSec || 0,+ ...scenes.map((scene) => scene.endSec || 0),+ ...(project.lyricCues || []).map((cue) => cue.endSec || cue.startSec || 0),+ );+ const codeReady = codeMode && !noAudio && codeDuration > 0;+ // A composition document seeks the song: it needs the analysis's duration+ // and an attached document; scene media is optional (the document decides).+ const documentBlocked = !documentMode ? '' : noAudio ? 'Link a track first'+ : !(project.audioAnalysis?.durationSec > 0) ? 'Analyze the track first — the document is timed against the song'+ : !project.composition?.document ? 'Start from the template or import a composition document first' : '';+ if (renderJob.active && renderJob.context === project.id) {+ return (+ <button onClick={renderJob.cancel} disabled={renderJob.pending}+ title={renderJob.pending ? 'Preparing render' : 'Cancel render'}+ className="flex items-center gap-1 bg-port-warning/20 text-port-warning border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0">+ <Activity size={15} className="animate-spin" /> {renderJob.pending ? 'Preparing render…' : `${renderJob.progress}% · Cancel`}+ </button>+ );+ }+ return (+ <button onClick={() => renderJob.start(project.id)} disabled={renderJob.active || (documentMode ? !!documentBlocked : codeMode ? !codeReady : (sceneCount === 0 || readySceneCount !== sceneCount))}+ title={renderJob.active+ ? 'Wait for the other project render to finish, or return to it to cancel'+ : documentMode+ ? (documentBlocked || 'Render the composition document over the song')+ : codeMode+ ? (codeReady ? 'Render the code-rendered video over the song. This does not generate footage.' : 'Analyze the song or time a scene before rendering code')+ : sceneCount === 0+ ? 'Add scenes first'+ : readySceneCount !== sceneCount+ ? (layered+ ? `${sceneCount - readySceneCount} scene${sceneCount - readySceneCount === 1 ? ' is' : 's are'} not ready — footage needs a video, a still needs a frame and a span, a card needs a span`+ : `Generate videos for all ${sceneCount} scenes first`)+ : 'Render the complete music video over the track'}+ className="flex items-center gap-1 bg-port-accent text-white rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50">+ <Film size={15} /> {renderJob.active ? 'Rendering another project…' : 'Render final'}+ </button>+ );+}diff --git a/client/src/components/musicVideo/ProjectToolbar.jsx b/client/src/components/musicVideo/ProjectToolbar.jsxdeleted file mode 100644index 3187f5bf9b..0000000000--- a/client/src/components/musicVideo/ProjectToolbar.jsx+++ /dev/null@@ -1,190 +0,0 @@-import { Film, Trash2, Music, Activity, Image as ImageIcon, Video, Wand2, Copy } from 'lucide-react';-import RecordRenderPinRow from '../imageGen/RecordRenderPinRow.jsx';-import { MUSCRIPTOR_MODELS } from '../../lib/muscriptorModels.js';-import VideoRenderSettings from './VideoRenderSettings.jsx';-import { sceneRenderReady, sceneVisualLayer } from '../../lib/musicVideoLayers.js';-import { compositionDraft, RENDER_STYLES } from './compositionDraft.js';--const uniqueCount = (scenes, key) => new Set(scenes.map((scene) => scene[key]).filter(Boolean)).size;--/**- * The open project's title row + every board-level action: analyze, transcribe- * MIDI, AI-plan, auto-arrange, the frame/video render pins, the batch- * frame/clip generators, fork, final render, delete.- *- * `midi` / `videoSettings` / `sceneMedia` / `renderJob` are the page's hook- * slots; `busy` carries the page-owned in-flight flags for the project-level- * actions it still owns.- */-export default function ProjectToolbar({- project, midi, midiBound, videoSettings, sceneMedia, renderJob, busy,- onAnalyze, onPlan, onAutoArrange, onClone, onDelete, onRenderStyle,-}) {- const scenes = project.scenes || [];- const sceneCount = scenes.length;- // #8985: in a composed render a still needs only its frame and a title card- // needs neither frame nor clip, so the counts cover the scenes that use them.- const mode = project.composition?.mode || 'concat';- const layered = mode === 'composed';- const codeMode = mode === 'code';- const frameScenes = scenes.filter((scene) => sceneVisualLayer(scene, { layered }) !== 'card');- const footageScenes = scenes.filter((scene) => sceneVisualLayer(scene, { layered }) === 'footage');- const referenceFrameCount = frameScenes.filter((scene) => scene.referenceImageId).length;- const renderableSceneCount = footageScenes.filter((scene) => scene.videoHistoryId).length;- const readySceneCount = scenes.filter((scene) => sceneRenderReady(scene, { layered })).length;- const uniqueReferenceFrameCount = uniqueCount(frameScenes, 'referenceImageId');- const uniqueVideoCount = uniqueCount(footageScenes, 'videoHistoryId');- const missingFrameCount = frameScenes.length - referenceFrameCount;- const missingVideoCount = footageScenes.length - renderableSceneCount;- const footageFramesReady = footageScenes.every((scene) => scene.referenceImageId);- const generatingFrames = Object.keys(sceneMedia.genScenes).length > 0;- const generatingVideos = Object.keys(sceneMedia.genVideoScenes).length > 0;- const noAudio = !project.trackId && !project.uploadedAudioFilename;- const codeDuration = Math.max(- project.audioAnalysis?.durationSec || 0,- ...(project.scenes || []).map((scene) => scene.endSec || 0),- ...(project.lyricCues || []).map((cue) => cue.endSec || cue.startSec || 0),- );- const codeReady = codeMode && !noAudio && codeDuration > 0;- // A composition document seeks the song: it needs the analysis's duration- // and an attached document; scene media is optional (the document decides).- const documentMode = mode === 'document';- const documentBlocked = !documentMode ? '' : noAudio ? 'Link a track first'- : !(project.audioAnalysis?.durationSec > 0) ? 'Analyze the track first — the document is timed against the song'- : !project.composition?.document ? 'Start from the template or import a composition document first' : '';- const footageBlocked = codeMode ? 'Code-rendered style draws the picture in code and does not generate footage' : '';- const nextVersion = (project.version || 1) + 1;- return (- <div className="flex min-w-0 flex-wrap items-start gap-2">- <h2 className="w-full text-lg font-semibold sm:w-auto sm:shrink-0">{project.name}</h2>- <div className="flex min-w-0 w-full flex-1 flex-wrap items-center justify-start gap-2 sm:w-auto sm:justify-end">- <div>- <label htmlFor="mv-toolbar-render-style" className="sr-only">Render style</label>- <select id="mv-toolbar-render-style" value={compositionDraft(project).mode}- onChange={(e) => onRenderStyle?.(e.target.value)}- className="bg-port-bg border border-port-border rounded px-1.5 py-1.5 text-sm min-h-[44px] sm:min-h-0">- {RENDER_STYLES.map(([value, label]) => <option key={value} value={value}>{label}</option>)}- </select>- </div>- <button onClick={onAnalyze} disabled={busy.analyzing || noAudio}- title={noAudio ? 'Link a track first' : 'Analyze beat grid'}- className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50">- <Activity size={15} /> {busy.analyzing ? 'Analyzing…' : 'Analyze'}- </button>- {midiBound ? (- <button onClick={midi.cancel} title="Cancel MIDI transcription"- className="flex items-center gap-1 bg-port-warning/20 text-port-warning border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0">- <Activity size={15} className="animate-spin" /> {midi.stageLabel} · Cancel- </button>- ) : (- <>- <select value={midi.model} onChange={(e) => midi.setModel(e.target.value)}- disabled={midi.active}- aria-label="MuScriptor model size"- title="MuScriptor model size — larger is higher quality but slower and a bigger first-use download"- className="bg-port-bg border border-port-border rounded px-1.5 py-1.5 text-sm capitalize disabled:opacity-50">- {MUSCRIPTOR_MODELS.map((m) => <option key={m} value={m}>{m}</option>)}- </select>- <button onClick={() => midi.start(project.id)}- disabled={midi.active || noAudio}- title={noAudio- ? 'Link a track first'- : `Transcribe the track to MIDI with MuScriptor (${midi.model} model, local — installs automatically on first use)`}- className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50">- <Music size={15} /> MIDI- </button>- </>- )}- <button onClick={onPlan} disabled={busy.planning || !project.audioAnalysis}- title={!project.audioAnalysis ? 'Analyze the track first' : 'AI-plan bounded shots per song section, cut on timed lyrics, phrases and beats'}- className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50">- <Wand2 size={15} /> {busy.planning ? 'Planning…' : 'AI Plan'}- </button>- <button onClick={onAutoArrange}- disabled={busy.arranging || !project.audioAnalysis || sceneCount === 0}- title={!project.audioAnalysis- ? 'Analyze the track first'- : sceneCount === 0- ? 'Add scenes first'- : 'Distribute scenes across song sections by energy'}- className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50">- <Wand2 size={15} /> {busy.arranging ? 'Arranging…' : 'Auto-arrange'}- </button>- <RecordRenderPinRow- idPrefix="mv-frame-pin"- label="Frames"- imageMode={project.imageMode ?? null}- imageModelId={project.imageModelId ?? null}- onChange={videoSettings.changeFramePin}- />- <VideoRenderSettings videoSettings={videoSettings} generating={generatingVideos} />- <button- onClick={sceneMedia.generateMissingFrames}- disabled={codeMode || videoSettings.framePinSaving || sceneCount === 0 || missingFrameCount === 0 || generatingFrames}- title={footageBlocked || (videoSettings.framePinSaving- ? 'Saving the frame renderer…'- : (missingFrameCount > 0 ? `Generate ${missingFrameCount} missing reference frame${missingFrameCount === 1 ? '' : 's'}` : 'Every scene has a reference frame'))}- className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50"- >- <ImageIcon size={15} /> Frames {referenceFrameCount}/{frameScenes.length}- </button>- <button- onClick={sceneMedia.generateMissingVideos}- disabled={codeMode || videoSettings.saving || footageScenes.length === 0 || missingVideoCount === 0 || !footageFramesReady || generatingVideos || !!videoSettings.videoBlockedReason}- title={footageBlocked || videoSettings.videoBlockedReason- || (!footageFramesReady- ? 'Generate every reference frame first'- : (missingVideoCount > 0 ? `Generate ${missingVideoCount} missing scene video${missingVideoCount === 1 ? '' : 's'}` : 'Every scene has a video'))}- className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50"- >- <Video size={15} /> Videos {renderableSceneCount}/{footageScenes.length}- </button>- {(uniqueReferenceFrameCount < referenceFrameCount || uniqueVideoCount < renderableSceneCount) && (- <span- className="text-[10px] px-2 py-1.5 rounded border border-port-warning/40 bg-port-warning/10 text-port-warning"- title={`${referenceFrameCount - uniqueReferenceFrameCount} scene${referenceFrameCount - uniqueReferenceFrameCount === 1 ? '' : 's'} reuse a reference frame; ${renderableSceneCount - uniqueVideoCount} reuse a video clip`}- >- Repetition: {uniqueReferenceFrameCount} unique frames · {uniqueVideoCount} unique clips- </span>- )}- <button- onClick={onClone}- disabled={busy.cloning}- title={`Create an editable v${nextVersion}; keep scene media attached and clear the final render`}- className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50"- >- <Copy size={15} /> {busy.cloning ? 'Forking…' : `Fork v${nextVersion}`}- </button>- {renderJob.active && renderJob.context === project.id ? (- <button onClick={renderJob.cancel} disabled={renderJob.pending}- title={renderJob.pending ? 'Preparing render' : 'Cancel render'}- className="flex items-center gap-1 bg-port-warning/20 text-port-warning border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0">- <Activity size={15} className="animate-spin" /> {renderJob.pending ? 'Preparing render…' : `${renderJob.progress}% · Cancel`}- </button>- ) : (- <button onClick={() => renderJob.start(project.id)} disabled={renderJob.active || (documentMode ? !!documentBlocked : codeMode ? !codeReady : (sceneCount === 0 || readySceneCount !== sceneCount))}- title={renderJob.active- ? 'Wait for the other project render to finish, or return to it to cancel'- : documentMode- ? (documentBlocked || 'Render the composition document over the song')- : codeMode- ? (codeReady ? 'Render the code-rendered video over the song. This does not generate footage.' : 'Analyze the song or time a scene before rendering code')- : sceneCount === 0- ? 'Add scenes first'- : readySceneCount !== sceneCount- ? (layered- ? `${sceneCount - readySceneCount} scene${sceneCount - readySceneCount === 1 ? ' is' : 's are'} not ready — footage needs a video, a still needs a frame and a span, a card needs a span`- : `Generate videos for all ${sceneCount} scenes first`)- : 'Render the complete music video over the track'}- className="flex items-center gap-1 bg-port-accent text-white rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50">- <Film size={15} /> {renderJob.active ? 'Rendering another project…' : 'Render final'}- </button>- )}- <button onClick={onDelete} title="Delete project" aria-label="Delete project"- className="flex items-center gap-1 text-port-error border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0">- <Trash2 size={15} />- </button>- </div>- </div>- );-}diff --git a/client/src/components/musicVideo/SceneCard.jsx b/client/src/components/musicVideo/SceneCard.jsxindex 062bc64b17..15c5e39e91 100644--- a/client/src/components/musicVideo/SceneCard.jsx+++ b/client/src/components/musicVideo/SceneCard.jsx@@ -1,5 +1,5 @@import { useRef, useState } from 'react';-import { Trash2, Activity, ArrowUp, ArrowDown, Image as ImageIcon, Video, Maximize2, AlertTriangle, ImagePlus, Clapperboard, Scissors } from 'lucide-react';+import { Trash2, Activity, ArrowUp, ArrowDown, ChevronRight, Image as ImageIcon, Video, Maximize2, AlertTriangle, ImagePlus, Clapperboard, Scissors } from 'lucide-react';import { formatDurationSec, formatUsd } from '../../utils/formatters.js';import { useVideoFileSrc } from '../../hooks/useVideoFileSrc.js';import SceneTakeStrip from './SceneTakeStrip.jsx';@@ -54,6 +54,11 @@ const COVERAGE_TOLERANCE_SEC = 0.25;* A shot longer than that lane renders in one take (the lip-sync audio window,* or Grok's longest clip) offers `onSplit(sceneId, backend)`, which cuts it* into contiguous scenes at lyric pauses / phrase boundaries server-side.+ *+ * The card is a disclosure: collapsed it is one row — frame thumbnail, title,+ * timing, lyric line and status — and it opens on tap to the full editor.+ * Opening or closing it also calls `onSeek(scene)`, so the docked preview+ * jumps to the scene's start.*/export default function SceneCard({scene, index, isLast, generatingFrame, generatingVideo,@@ -61,7 +66,7 @@ export default function SceneCard({onMove, onDelete, onEditLocal, onSave,onGenerateFrame, onGenerateVideo, onContinueVideo,onOpenPreview, onSelectTake, onReviewTake, onImportTake, onImportClipTake, takeBusy = false, layered = false,- lipSyncBackend = '', songDurationSec = null, onSplit, falVideoSettings = null,+ lipSyncBackend = '', songDurationSec = null, onSplit, falVideoSettings = null, onSeek,}) {// Pause the inline clip before opening the lightbox so the user can't hear// two desynced copies — MediaLightbox autoplays unmuted, and the thumb's@@ -111,13 +116,24 @@ export default function SceneCard({const canSplit = splitLimit != null && timedSpan != null && timedSpan > splitLimit + 1e-6;const shotModeId = `mv-shot-mode-${scene.sceneId}`;return (- <div className="bg-port-card border border-port-border rounded-lg p-3 space-y-2">- <div className="flex items-center justify-between gap-2">- <div className="min-w-0">- <div className="text-sm font-medium truncate">+ <details className="group min-w-0 rounded-lg border border-port-border bg-port-card">+ <summary+ onClick={() => onSeek?.(scene)}+ className="flex min-h-[44px] cursor-pointer select-none items-center gap-3 p-2 marker:content-none [&::-webkit-details-marker]:hidden"+ >+ <ChevronRight size={14} aria-hidden="true" className="shrink-0 text-port-text-muted transition-transform group-open:rotate-90" />+ {scene.referenceImageId ? (+ <img src={`/data/images/${scene.referenceImageId}`} alt="" loading="lazy" className="aspect-video w-16 shrink-0 rounded border border-port-border object-cover sm:w-20" />+ ) : (+ <span className="flex aspect-video w-16 shrink-0 items-center justify-center rounded border border-dashed border-port-border text-port-text-muted sm:w-20" aria-hidden="true">+ <ImageIcon size={14} />+ </span>+ )}+ <div className="min-w-0 flex-1">+ <div className="truncate text-sm font-medium">{scene.sectionLabel || scene.label || `Scene ${scene.order + 1}`}</div>- <div className="text-[11px] text-port-text-muted">+ <div className="truncate text-[11px] text-port-text-muted">#{scene.order + 1}{typeof scene.startSec === 'number' && typeof scene.endSec === 'number'? ` · ${formatDurationSec(scene.endSec - scene.startSec)} · ${formatDurationSec(scene.startSec)}–${formatDurationSec(scene.endSec)}`@@ -126,269 +142,275 @@ export default function SceneCard({{scene.videoHistoryId ? ' · video ready' : ''}{clipSec != null ? ` · clip ${clipSec.toFixed(1)}s` : ''}</div>+ {scene.lyricText && <div className="truncate text-[11px] italic text-port-text-muted">♪ {scene.lyricText}</div>}</div>- <div className="flex items-center gap-2">+ {(generatingFrame || generatingVideo) && (+ <Activity size={14} className="shrink-0 animate-spin text-port-accent" aria-label="Generating" />+ )}+ </summary>+ <div className="space-y-2 p-3 pt-0">+ <div className="flex items-center justify-end gap-2"><button onClick={() => onMove(index, -1)} disabled={index === 0} aria-label="Move up" className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 disabled:opacity-30" title="Move up"><ArrowUp size={14} /></button><button onClick={() => onMove(index, 1)} disabled={isLast} aria-label="Move down" className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 disabled:opacity-30" title="Move down"><ArrowDown size={14} /></button><button onClick={() => onDelete(scene.sceneId)} aria-label="Delete scene" className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 text-port-error" title="Delete scene"><Trash2 size={14} /></button></div>- </div>- <textarea- aria-label="Shot prompt"- value={scene.prompt || ''} rows={2}- onChange={(e) => onEditLocal(scene.sceneId, { prompt: e.target.value })}- onBlur={(e) => onSave(scene.sceneId, { prompt: e.target.value })}- placeholder="Shot prompt — what this scene's video should show"- className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm"- />- {(scene.lyricText || scene.visualIntent || scene.direction) && (- <div className="text-[11px] text-port-text-muted space-y-0.5">- {scene.lyricText && <p className="italic break-words">♪ {scene.lyricText}</p>}- {scene.visualIntent && <p className="break-words">Intent: {scene.visualIntent}</p>}- {/* Applied treatment direction (#8980) — appended to both generated prompts. */}- {scene.direction && (- <p className="break-words" title={scene.direction.frameClause}>- Direction: {scene.direction.mode}{scene.direction.focalSubject ? ` · ${scene.direction.focalSubject}` : ''}- {scene.direction.typographyRole !== 'none' ? ` · ${scene.direction.typographyRole} text, ${scene.direction.negativeSpace} region kept clear` : ' · no text'}- </p>+ <textarea+ aria-label="Shot prompt"+ value={scene.prompt || ''} rows={2}+ onChange={(e) => onEditLocal(scene.sceneId, { prompt: e.target.value })}+ onBlur={(e) => onSave(scene.sceneId, { prompt: e.target.value })}+ placeholder="Shot prompt — what this scene's video should show"+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm"+ />+ {(scene.lyricText || scene.visualIntent || scene.direction) && (+ <div className="text-[11px] text-port-text-muted space-y-0.5">+ {scene.lyricText && <p className="italic break-words">♪ {scene.lyricText}</p>}+ {scene.visualIntent && <p className="break-words">Intent: {scene.visualIntent}</p>}+ {/* Applied treatment direction (#8980) — appended to both generated prompts. */}+ {scene.direction && (+ <p className="break-words" title={scene.direction.frameClause}>+ Direction: {scene.direction.mode}{scene.direction.focalSubject ? ` · ${scene.direction.focalSubject}` : ''}+ {scene.direction.typographyRole !== 'none' ? ` · ${scene.direction.typographyRole} text, ${scene.direction.negativeSpace} region kept clear` : ' · no text'}+ </p>+ )}+ </div>+ )}+ <div className="flex flex-wrap gap-2 items-center text-xs">+ {SCENE_TIME_FIELDS.map(([labelText, key]) => {+ const toValue = (v) => (v === '' ? null : Number(v));+ return (+ <label key={key} className="flex items-center gap-1">{labelText}+ <input type="number" min="0" step="0.1" value={scene[key] ?? ''} className="w-16 bg-port-bg border border-port-border rounded px-1 py-1 min-h-[44px] sm:min-h-0"+ onChange={(e) => onEditLocal(scene.sceneId, { [key]: toValue(e.target.value) })}+ onBlur={(e) => onSave(scene.sceneId, { [key]: toValue(e.target.value) })} />+ </label>+ );+ })}+ <label className="flex items-center gap-1 min-h-[44px] sm:min-h-0">+ <input type="checkbox" checked={!!scene.beatAligned}+ onChange={(e) => { onEditLocal(scene.sceneId, { beatAligned: e.target.checked }); onSave(scene.sceneId, { beatAligned: e.target.checked }); }} />+ Beat-aligned+ </label>+ <label className="flex items-center gap-1 min-h-[44px] sm:min-h-0" title="Repeat the generated clip to fill a span longer than the clip. Off: the shot must be covered by its clip (trim, continue, or replace it).">+ <input type="checkbox" checked={loops} disabled={performance} onChange={(e) => applyPatch({ loop: e.target.checked })} />+ Loop clip+ </label>+ {/* A performance is sung footage — only the footage layer offers it. */}+ {layer === 'footage' && (+ <>+ <label htmlFor={shotModeId} className="flex items-center gap-1">Shot</label>+ <select id={shotModeId} value={performance ? 'performance' : 'cutaway'}+ onChange={(e) => applyPatch({ shotMode: e.target.value })}+ className="bg-port-bg border border-port-border rounded px-1 py-1 min-h-[44px] sm:min-h-0"+ title="Cutaway: any video lane animates the frame under the song. Performance: a singer lip-synced to the song itself (needs a source-audio provider).">+ <option value="cutaway">Cutaway</option>+ <option value="performance">Performance (lip-sync)</option>+ </select>+ </>+ )}+ </div>+ <div className="flex flex-wrap gap-2 items-center text-xs">+ <label htmlFor={fieldId('layer')}>Layer</label>+ <select id={fieldId('layer')} value={layer} onChange={(e) => applyPatch({ visualLayer: e.target.value })}+ className="bg-port-bg border border-port-border rounded px-1 py-1 min-h-[44px] sm:min-h-0">+ {MUSIC_VIDEO_VISUAL_LAYERS.map((value) => <option key={value} value={value}>{LAYER_LABELS[value]}</option>)}+ </select>+ {layer === 'still' && (+ <>+ <label htmlFor={fieldId('move')}>Move</label>+ <select id={fieldId('move')} value={scene.stillMove || 'hold'} onChange={(e) => applyPatch({ stillMove: e.target.value })}+ className="bg-port-bg border border-port-border rounded px-1 py-1 min-h-[44px] sm:min-h-0">+ {STILL_MOVE_LABELS.map(([value, text]) => <option key={value} value={value}>{text}</option>)}+ </select>+ </>+ )}+ {layer === 'card' && (+ <>+ <label htmlFor={fieldId('card-text')}>Card text</label>+ <input id={fieldId('card-text')} type="text" maxLength={500} value={scene.cardText || ''}+ placeholder="Title shown on the card"+ onChange={(e) => onEditLocal(scene.sceneId, { cardText: e.target.value })}+ onBlur={(e) => onSave(scene.sceneId, { cardText: e.target.value.trim() || null })}+ className="min-w-0 flex-1 basis-40 bg-port-bg border border-port-border rounded px-1 py-1 min-h-[44px] sm:min-h-0" />+ <label htmlFor={fieldId('card-color')}>Background</label>+ <input id={fieldId('card-color')} type="color" value={scene.cardColor || '#000000'}+ onChange={(e) => onEditLocal(scene.sceneId, { cardColor: e.target.value })}+ onBlur={(e) => onSave(scene.sceneId, { cardColor: e.target.value })}+ className="h-8 w-10 min-h-[44px] sm:min-h-0 bg-port-bg border border-port-border rounded" />+ </>)}</div>- )}- <div className="flex flex-wrap gap-2 items-center text-xs">- {SCENE_TIME_FIELDS.map(([labelText, key]) => {- const toValue = (v) => (v === '' ? null : Number(v));- return (- <label key={key} className="flex items-center gap-1">{labelText}- <input type="number" min="0" step="0.1" value={scene[key] ?? ''} className="w-16 bg-port-bg border border-port-border rounded px-1 py-1 min-h-[44px] sm:min-h-0"- onChange={(e) => onEditLocal(scene.sceneId, { [key]: toValue(e.target.value) })}- onBlur={(e) => onSave(scene.sceneId, { [key]: toValue(e.target.value) })} />- </label>- );- })}- <label className="flex items-center gap-1 min-h-[44px] sm:min-h-0">- <input type="checkbox" checked={!!scene.beatAligned}- onChange={(e) => { onEditLocal(scene.sceneId, { beatAligned: e.target.checked }); onSave(scene.sceneId, { beatAligned: e.target.checked }); }} />- Beat-aligned- </label>- <label className="flex items-center gap-1 min-h-[44px] sm:min-h-0" title="Repeat the generated clip to fill a span longer than the clip. Off: the shot must be covered by its clip (trim, continue, or replace it).">- <input type="checkbox" checked={loops} disabled={performance} onChange={(e) => applyPatch({ loop: e.target.checked })} />- Loop clip- </label>- {/* A performance is sung footage — only the footage layer offers it. */}- {layer === 'footage' && (- <>- <label htmlFor={shotModeId} className="flex items-center gap-1">Shot</label>- <select id={shotModeId} value={performance ? 'performance' : 'cutaway'}- onChange={(e) => applyPatch({ shotMode: e.target.value })}- className="bg-port-bg border border-port-border rounded px-1 py-1 min-h-[44px] sm:min-h-0"- title="Cutaway: any video lane animates the frame under the song. Performance: a singer lip-synced to the song itself (needs a source-audio provider).">- <option value="cutaway">Cutaway</option>- <option value="performance">Performance (lip-sync)</option>- </select>- </>+ {layer !== 'footage' && !layered && (+ <p className="text-[11px] text-port-text-muted">+ {LAYER_LABELS[layer]} sections render in composed mode — a plain render plays this scene's footage.+ </p>)}- </div>- <div className="flex flex-wrap gap-2 items-center text-xs">- <label htmlFor={fieldId('layer')}>Layer</label>- <select id={fieldId('layer')} value={layer} onChange={(e) => applyPatch({ visualLayer: e.target.value })}- className="bg-port-bg border border-port-border rounded px-1 py-1 min-h-[44px] sm:min-h-0">- {MUSIC_VIDEO_VISUAL_LAYERS.map((value) => <option key={value} value={value}>{LAYER_LABELS[value]}</option>)}- </select>- {layer === 'still' && (- <>- <label htmlFor={fieldId('move')}>Move</label>- <select id={fieldId('move')} value={scene.stillMove || 'hold'} onChange={(e) => applyPatch({ stillMove: e.target.value })}- className="bg-port-bg border border-port-border rounded px-1 py-1 min-h-[44px] sm:min-h-0">- {STILL_MOVE_LABELS.map(([value, text]) => <option key={value} value={value}>{text}</option>)}- </select>- </>+ {layer !== 'footage' && layered && !sceneHasAuthoredSpan(scene) && (+ <p role="alert" className="text-[11px] text-port-warning">+ Set a start and end — a {layer === 'card' ? 'title card' : 'still'} runs for exactly its span.+ </p>)}- {layer === 'card' && (- <>- <label htmlFor={fieldId('card-text')}>Card text</label>- <input id={fieldId('card-text')} type="text" maxLength={500} value={scene.cardText || ''}- placeholder="Title shown on the card"- onChange={(e) => onEditLocal(scene.sceneId, { cardText: e.target.value })}- onBlur={(e) => onSave(scene.sceneId, { cardText: e.target.value.trim() || null })}- className="min-w-0 flex-1 basis-40 bg-port-bg border border-port-border rounded px-1 py-1 min-h-[44px] sm:min-h-0" />- <label htmlFor={fieldId('card-color')}>Background</label>- <input id={fieldId('card-color')} type="color" value={scene.cardColor || '#000000'}- onChange={(e) => onEditLocal(scene.sceneId, { cardColor: e.target.value })}- onBlur={(e) => onSave(scene.sceneId, { cardColor: e.target.value })}- className="h-8 w-10 min-h-[44px] sm:min-h-0 bg-port-bg border border-port-border rounded" />- </>+ {performance && performanceBlocked && (+ <div role="alert" className="flex items-start gap-2 rounded border border-port-warning/40 bg-port-warning/10 px-2 py-1.5 text-xs text-port-warning">+ <AlertTriangle size={13} className="shrink-0 mt-0.5" />+ <span className="min-w-0 break-words">{performanceBlocked}</span>+ </div>)}- </div>- {layer !== 'footage' && !layered && (- <p className="text-[11px] text-port-text-muted">- {LAYER_LABELS[layer]} sections render in composed mode — a plain render plays this scene's footage.- </p>- )}- {layer !== 'footage' && layered && !sceneHasAuthoredSpan(scene) && (- <p role="alert" className="text-[11px] text-port-warning">- Set a start and end — a {layer === 'card' ? 'title card' : 'still'} runs for exactly its span.- </p>- )}- {performance && performanceBlocked && (- <div role="alert" className="flex items-start gap-2 rounded border border-port-warning/40 bg-port-warning/10 px-2 py-1.5 text-xs text-port-warning">- <AlertTriangle size={13} className="shrink-0 mt-0.5" />- <span className="min-w-0 break-words">{performanceBlocked}</span>- </div>- )}- {performance && !performanceBlocked && (- <p className="text-[11px] text-port-text-muted break-words" data-testid="performance-plan">- Lip-sync via {capability.label} ({capability.modelId}) · song {formatDurationSec(plan.windowStartSec)}–{formatDurationSec(plan.windowEndSec)}- {plan.editInSec > 0 ? ` · shot starts ${plan.editInSec.toFixed(2)}s into the take` : ''} · {performanceCost}- </p>- )}- {falTake && !falTake.performance && (- <p className="text-[11px] text-port-text-muted break-words" data-testid="fal-cutaway-plan">- fal.ai renders {falTake.seconds != null ? `a ${falTake.seconds}s ` : 'a '}clip on {getFalVideoModel(falTake.modelId)?.label || falTake.modelId}- {' · '}{falCost || 'cost unknown — billed to your fal.ai account'}- </p>- )}- {grokPlan && (- <p className={`text-[11px] break-words ${grokPlan.needsSplit ? 'text-port-warning' : 'text-port-text-muted'}`}>- Grok renders a {grokPlan.requestSec}s clip for this {timedSpan.toFixed(1)}s cutaway- {grokPlan.needsSplit ? ` — ${grokPlan.uncoveredSec.toFixed(1)}s uncovered; split the scene rather than loop it` : ''}. Motion timing in the prompt is approximate.- </p>- )}- {canSplit && onSplit && (- <button type="button" onClick={() => onSplit(scene.sceneId, lipSyncBackend || null)}- className="inline-flex items-center gap-1 rounded bg-port-bg border border-port-border hover:bg-port-border/40 px-2 py-1 text-xs min-h-[44px] sm:min-h-0"- title={`Cut this ${timedSpan.toFixed(1)}s shot into scenes of at most ${splitLimit.toFixed(2)}s at lyric pauses or phrase boundaries — nothing is looped or stretched`}>- <Scissors size={13} /> Split on lyric boundaries- </button>- )}- {underCovered && (- <div role="alert" className="flex flex-wrap items-center gap-2 rounded border border-port-warning/40 bg-port-warning/10 px-2 py-1.5 text-xs text-port-warning">- <AlertTriangle size={13} className="shrink-0" />- <span className="min-w-0 flex-1 basis-48">- Shot runs {spanSec.toFixed(1)}s but its clip is {clipSec.toFixed(1)}s — the render won't repeat it.- Trim the shot, continue or regenerate a longer clip, or loop it on purpose.- </span>- <button type="button" onClick={() => applyPatch({ endSec: Math.round((scene.startSec + clipSec) * 1000) / 1000 })}- className="rounded bg-port-bg border border-port-border px-2 py-1 min-h-[44px] sm:min-h-0 text-port-text">Trim to clip</button>- <button type="button" onClick={() => applyPatch({ loop: true })}- className="rounded bg-port-bg border border-port-border px-2 py-1 min-h-[44px] sm:min-h-0 text-port-text">Loop clip</button>- </div>- )}- {/* Reference frame — the still image that seeds this shot (Phase 1b) */}- <div className="flex flex-col gap-2 sm:flex-row sm:items-start">- <textarea- aria-label="Reference frame prompt"- value={scene.framePrompt || ''} rows={2}- onChange={(e) => onEditLocal(scene.sceneId, { framePrompt: e.target.value })}- onBlur={(e) => onSave(scene.sceneId, { framePrompt: e.target.value || null })}- placeholder="Reference frame prompt — the still that seeds this shot (defaults to the shot prompt)"- className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm"- />- <div className="flex items-center gap-2">- {scene.referenceImageId && (- <button- type="button"- onClick={() => onOpenPreview?.(`image:${scene.referenceImageId}`)}- aria-label={`View scene ${index + 1} reference frame full size`}- title={`View scene ${index + 1} reference frame full size`}- className="shrink-0 rounded border border-port-border overflow-hidden focus:outline-none focus:ring-2 focus:ring-port-accent"- >- <img- src={`/data/images/${scene.referenceImageId}`}- alt=""- className="w-32 aspect-video object-cover block"- />- </button>- )}- <div className="flex flex-col gap-1">- <button onClick={() => onGenerateFrame(scene)} disabled={!!generatingFrame}- className="flex items-center gap-1 bg-port-border hover:bg-port-border/70 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0 whitespace-nowrap"- title={scene.referenceImageId- ? 'Render another candidate frame — your selected frame stays until you pick a new one'- : 'Generate a still reference frame for this scene'}>- {generatingFrame ? <Activity size={14} className="animate-spin" /> : <ImageIcon size={14} />}- {generatingFrame ? 'Generating frame…' : (scene.referenceImageId ? 'New frame take' : 'Generate frame')}- </button>- {onImportTake && (- <button type="button" onClick={() => onImportTake(scene)} disabled={takeBusy}- className="flex items-center gap-1 bg-port-bg border border-port-border hover:bg-port-border/40 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0 whitespace-nowrap"- title="Add a frame from the gallery or an upload (e.g. made in an external tool) as a take">- <ImagePlus size={14} /> Import take+ {performance && !performanceBlocked && (+ <p className="text-[11px] text-port-text-muted break-words" data-testid="performance-plan">+ Lip-sync via {capability.label} ({capability.modelId}) · song {formatDurationSec(plan.windowStartSec)}–{formatDurationSec(plan.windowEndSec)}+ {plan.editInSec > 0 ? ` · shot starts ${plan.editInSec.toFixed(2)}s into the take` : ''} · {performanceCost}+ </p>+ )}+ {falTake && !falTake.performance && (+ <p className="text-[11px] text-port-text-muted break-words" data-testid="fal-cutaway-plan">+ fal.ai renders {falTake.seconds != null ? `a ${falTake.seconds}s ` : 'a '}clip on {getFalVideoModel(falTake.modelId)?.label || falTake.modelId}+ {' · '}{falCost || 'cost unknown — billed to your fal.ai account'}+ </p>+ )}+ {grokPlan && (+ <p className={`text-[11px] break-words ${grokPlan.needsSplit ? 'text-port-warning' : 'text-port-text-muted'}`}>+ Grok renders a {grokPlan.requestSec}s clip for this {timedSpan.toFixed(1)}s cutaway+ {grokPlan.needsSplit ? ` — ${grokPlan.uncoveredSec.toFixed(1)}s uncovered; split the scene rather than loop it` : ''}. Motion timing in the prompt is approximate.+ </p>+ )}+ {canSplit && onSplit && (+ <button type="button" onClick={() => onSplit(scene.sceneId, lipSyncBackend || null)}+ className="inline-flex items-center gap-1 rounded bg-port-bg border border-port-border hover:bg-port-border/40 px-2 py-1 text-xs min-h-[44px] sm:min-h-0"+ title={`Cut this ${timedSpan.toFixed(1)}s shot into scenes of at most ${splitLimit.toFixed(2)}s at lyric pauses or phrase boundaries — nothing is looped or stretched`}>+ <Scissors size={13} /> Split on lyric boundaries+ </button>+ )}+ {underCovered && (+ <div role="alert" className="flex flex-wrap items-center gap-2 rounded border border-port-warning/40 bg-port-warning/10 px-2 py-1.5 text-xs text-port-warning">+ <AlertTriangle size={13} className="shrink-0" />+ <span className="min-w-0 flex-1 basis-48">+ Shot runs {spanSec.toFixed(1)}s but its clip is {clipSec.toFixed(1)}s — the render won't repeat it.+ Trim the shot, continue or regenerate a longer clip, or loop it on purpose.+ </span>+ <button type="button" onClick={() => applyPatch({ endSec: Math.round((scene.startSec + clipSec) * 1000) / 1000 })}+ className="rounded bg-port-bg border border-port-border px-2 py-1 min-h-[44px] sm:min-h-0 text-port-text">Trim to clip</button>+ <button type="button" onClick={() => applyPatch({ loop: true })}+ className="rounded bg-port-bg border border-port-border px-2 py-1 min-h-[44px] sm:min-h-0 text-port-text">Loop clip</button>+ </div>+ )}+ {/* Reference frame — the still image that seeds this shot (Phase 1b) */}+ <div className="flex flex-col gap-2 sm:flex-row sm:items-start">+ <textarea+ aria-label="Reference frame prompt"+ value={scene.framePrompt || ''} rows={2}+ onChange={(e) => onEditLocal(scene.sceneId, { framePrompt: e.target.value })}+ onBlur={(e) => onSave(scene.sceneId, { framePrompt: e.target.value || null })}+ placeholder="Reference frame prompt — the still that seeds this shot (defaults to the shot prompt)"+ className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm"+ />+ <div className="flex items-center gap-2">+ {scene.referenceImageId && (+ <button+ type="button"+ onClick={() => onOpenPreview?.(`image:${scene.referenceImageId}`)}+ aria-label={`View scene ${index + 1} reference frame full size`}+ title={`View scene ${index + 1} reference frame full size`}+ className="shrink-0 rounded border border-port-border overflow-hidden focus:outline-none focus:ring-2 focus:ring-port-accent"+ >+ <img+ src={`/data/images/${scene.referenceImageId}`}+ alt=""+ className="w-32 aspect-video object-cover block"+ /></button>)}+ <div className="flex flex-col gap-1">+ <button onClick={() => onGenerateFrame(scene)} disabled={!!generatingFrame}+ className="flex items-center gap-1 bg-port-border hover:bg-port-border/70 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0 whitespace-nowrap"+ title={scene.referenceImageId+ ? 'Render another candidate frame — your selected frame stays until you pick a new one'+ : 'Generate a still reference frame for this scene'}>+ {generatingFrame ? <Activity size={14} className="animate-spin" /> : <ImageIcon size={14} />}+ {generatingFrame ? 'Generating frame…' : (scene.referenceImageId ? 'New frame take' : 'Generate frame')}+ </button>+ {onImportTake && (+ <button type="button" onClick={() => onImportTake(scene)} disabled={takeBusy}+ className="flex items-center gap-1 bg-port-bg border border-port-border hover:bg-port-border/40 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0 whitespace-nowrap"+ title="Add a frame from the gallery or an upload (e.g. made in an external tool) as a take">+ <ImagePlus size={14} /> Import take+ </button>+ )}+ </div></div></div>- </div>- <SceneTakeStrip scene={scene} kind="image" busy={takeBusy}- onSelect={(take) => onSelectTake?.(scene, take)}- onReview={(take, review) => onReviewTake?.(scene, take, review)}- onOpenPreview={onOpenPreview} />- {/* Scene clip — i2v video generated from the reference frame (Phase 1) */}- <div className="flex items-center gap-2 flex-wrap">- {scene.videoHistoryId && (- <div className="relative w-40 shrink-0">- <video- ref={clipPlayerRef}- src={clipSrc}- className="w-full aspect-video object-cover rounded border border-port-border bg-black"- muted- playsInline- preload="metadata"- controls- onLoadedMetadata={(e) => {- const sec = e.currentTarget.duration;- if (Number.isFinite(sec) && sec > 0) setClipMeta({ id: scene.videoHistoryId, sec });- }}- />- {/* Corner expand — do not put the open handler on <video> itself;- that would fight native play/pause controls. Shape matches- ScenePreview's open-in-new-tab overlay. Pause first so the- lightbox's unmuted autoplay doesn't double-play the audio. */}+ <SceneTakeStrip scene={scene} kind="image" busy={takeBusy}+ onSelect={(take) => onSelectTake?.(scene, take)}+ onReview={(take, review) => onReviewTake?.(scene, take, review)}+ onOpenPreview={onOpenPreview} />+ {/* Scene clip — i2v video generated from the reference frame (Phase 1) */}+ <div className="flex items-center gap-2 flex-wrap">+ {scene.videoHistoryId && (+ <div className="relative w-40 shrink-0">+ <video+ ref={clipPlayerRef}+ src={clipSrc}+ className="w-full aspect-video object-cover rounded border border-port-border bg-black"+ muted+ playsInline+ preload="metadata"+ controls+ onLoadedMetadata={(e) => {+ const sec = e.currentTarget.duration;+ if (Number.isFinite(sec) && sec > 0) setClipMeta({ id: scene.videoHistoryId, sec });+ }}+ />+ {/* Corner expand — do not put the open handler on <video> itself;+ that would fight native play/pause controls. Shape matches+ ScenePreview's open-in-new-tab overlay. Pause first so the+ lightbox's unmuted autoplay doesn't double-play the audio. */}+ <button+ type="button"+ onClick={() => {+ clipPlayerRef.current?.pause();+ onOpenPreview?.(`video:${scene.videoHistoryId}`);+ }}+ aria-label={`View scene ${index + 1} clip full size`}+ title={`View scene ${index + 1} clip full size`}+ className="always-dark absolute top-1 right-1 min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 p-1 flex items-center justify-center rounded bg-black/50 text-white hover:bg-black/80 focus:outline-none focus:ring-2 focus:ring-port-accent"+ >+ <Maximize2 className="w-3 h-3" />+ </button>+ </div>+ )}+ <button onClick={() => onGenerateVideo(scene)}+ disabled={settingsSaving || !scene.referenceImageId || !!generatingVideo || !!videoBlockedReason || !!performanceBlocked}+ className="flex items-center gap-1 bg-port-border hover:bg-port-border/70 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0 whitespace-nowrap"+ title={videoBlockedReason || performanceBlocked+ || (!scene.referenceImageId ? 'Generate a reference frame first'+ : performance ? `Lip-sync this scene's frame to the song via ${capability.label} — ${performanceCost}`+ : "Generate this scene's video from its reference frame (i2v)")}>+ {generatingVideo ? <Activity size={14} className="animate-spin" /> : <Video size={14} />}+ {generatingVideo ? 'Generating video…' : (scene.videoHistoryId ? 'New video take' : 'Generate video')}+ </button>+ {scene.videoHistoryId && canContinueShot && (<button- type="button"- onClick={() => {- clipPlayerRef.current?.pause();- onOpenPreview?.(`video:${scene.videoHistoryId}`);- }}- aria-label={`View scene ${index + 1} clip full size`}- title={`View scene ${index + 1} clip full size`}- className="always-dark absolute top-1 right-1 min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 p-1 flex items-center justify-center rounded bg-black/50 text-white hover:bg-black/80 focus:outline-none focus:ring-2 focus:ring-port-accent"+ onClick={() => onContinueVideo(scene)}+ disabled={settingsSaving || !!generatingVideo}+ className="flex items-center gap-1 bg-port-bg border border-port-border hover:bg-port-border/40 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0 whitespace-nowrap"+ title="Native-extend this clip from its final latent frames and attach the longer result to this scene">- <Maximize2 className="w-3 h-3" />+ <Video size={14} /> Continue shot</button>- </div>- )}- <button onClick={() => onGenerateVideo(scene)}- disabled={settingsSaving || !scene.referenceImageId || !!generatingVideo || !!videoBlockedReason || !!performanceBlocked}- className="flex items-center gap-1 bg-port-border hover:bg-port-border/70 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0 whitespace-nowrap"- title={videoBlockedReason || performanceBlocked- || (!scene.referenceImageId ? 'Generate a reference frame first'- : performance ? `Lip-sync this scene's frame to the song via ${capability.label} — ${performanceCost}`- : "Generate this scene's video from its reference frame (i2v)")}>- {generatingVideo ? <Activity size={14} className="animate-spin" /> : <Video size={14} />}- {generatingVideo ? 'Generating video…' : (scene.videoHistoryId ? 'New video take' : 'Generate video')}- </button>- {scene.videoHistoryId && canContinueShot && (- <button- onClick={() => onContinueVideo(scene)}- disabled={settingsSaving || !!generatingVideo}- className="flex items-center gap-1 bg-port-bg border border-port-border hover:bg-port-border/40 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0 whitespace-nowrap"- title="Native-extend this clip from its final latent frames and attach the longer result to this scene"- >- <Video size={14} /> Continue shot- </button>- )}- {onImportClipTake && (- <button type="button" onClick={() => onImportClipTake(scene)} disabled={takeBusy}- className="flex items-center gap-1 bg-port-bg border border-port-border hover:bg-port-border/40 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0 whitespace-nowrap"- title="Pick an existing clip from the gallery (e.g. made in an external tool) as a take">- <Clapperboard size={14} /> Import clip take- </button>- )}+ )}+ {onImportClipTake && (+ <button type="button" onClick={() => onImportClipTake(scene)} disabled={takeBusy}+ className="flex items-center gap-1 bg-port-bg border border-port-border hover:bg-port-border/40 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0 whitespace-nowrap"+ title="Pick an existing clip from the gallery (e.g. made in an external tool) as a take">+ <Clapperboard size={14} /> Import clip take+ </button>+ )}+ </div>+ <SceneTakeStrip scene={scene} kind="video" busy={takeBusy}+ onSelect={(take) => onSelectTake?.(scene, take)}+ onReview={(take, review) => onReviewTake?.(scene, take, review)}+ onOpenPreview={onOpenPreview} /></div>- <SceneTakeStrip scene={scene} kind="video" busy={takeBusy}- onSelect={(take) => onSelectTake?.(scene, take)}- onReview={(take, review) => onReviewTake?.(scene, take, review)}- onOpenPreview={onOpenPreview} />- </div>+ </details>);}diff --git a/client/src/components/musicVideo/StageSection.jsx b/client/src/components/musicVideo/StageSection.jsxnew file mode 100644index 0000000000..a5316b525b--- /dev/null+++ b/client/src/components/musicVideo/StageSection.jsx@@ -0,0 +1,20 @@+import { ChevronRight } from 'lucide-react';++/**+ * A stage panel group that folds away: a native `<details>` (so it works+ * without script and reads as a disclosure to assistive tech) with a one-line+ * summary beside the title, collapsed unless `defaultOpen`. The summary row is+ * the 44px tap target on a phone.+ */+export default function StageSection({ id, title, summary = null, defaultOpen = false, children, className = '' }) {+ return (+ <details id={id} open={defaultOpen || undefined} className={`group min-w-0 rounded-lg border border-port-border bg-port-card ${className}`}>+ <summary className="flex min-h-[44px] cursor-pointer select-none items-center gap-2 px-3 py-2 marker:content-none [&::-webkit-details-marker]:hidden">+ <ChevronRight size={14} aria-hidden="true" className="shrink-0 text-port-text-muted transition-transform group-open:rotate-90" />+ <span className="shrink-0 text-sm font-medium">{title}</span>+ {summary && <span className="min-w-0 truncate text-xs text-port-text-muted">{summary}</span>}+ </summary>+ <div className="min-w-0 space-y-2 px-3 pb-3">{children}</div>+ </details>+ );+}diff --git a/client/src/components/musicVideo/TrackPanel.jsx b/client/src/components/musicVideo/TrackPanel.jsxindex 4bf4dac381..621902ecc2 100644--- a/client/src/components/musicVideo/TrackPanel.jsx+++ b/client/src/components/musicVideo/TrackPanel.jsx@@ -75,7 +75,7 @@ export default function TrackPanel({<audio src={audioUrl} controls preload="metadata" className="h-8 max-w-full" aria-label="Preview track audio" /><a href={audioUrl} download={audioFilename}title="Download the audio track"- className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1 text-xs hover:bg-port-border/40">+ className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1 text-xs min-h-[44px] sm:min-h-0 hover:bg-port-border/40"><Download size={13} /> Download audio</a></div>diff --git a/client/src/components/musicVideo/TreatmentPanel.jsx b/client/src/components/musicVideo/TreatmentPanel.jsxindex 7ee028eeb8..0d12dcbe43 100644--- a/client/src/components/musicVideo/TreatmentPanel.jsx+++ b/client/src/components/musicVideo/TreatmentPanel.jsx@@ -86,7 +86,7 @@ export default function TreatmentPanel({ project, treatment: api }) {return (<details className="mt-2 rounded border border-port-border bg-port-bg/40 p-2">- <summary className="cursor-pointer text-xs text-port-text-muted select-none min-h-[32px] flex flex-wrap items-center gap-2">+ <summary className="cursor-pointer text-xs text-port-text-muted select-none min-h-[44px] sm:min-h-[32px] flex flex-wrap items-center gap-2"><ScrollText size={13} /><span>Treatment</span>{t ? <span>· rev {t.revision}</span> : <span>· not started</span>}diff --git a/client/src/components/musicVideo/TypographyPanel.jsx b/client/src/components/musicVideo/TypographyPanel.jsxindex 999bbd7ab3..52587778b2 100644--- a/client/src/components/musicVideo/TypographyPanel.jsx+++ b/client/src/components/musicVideo/TypographyPanel.jsx@@ -40,7 +40,7 @@ export default function TypographyPanel({ project, onEditLocal, onSave }) {return (<details className="mt-2 bg-port-bg border border-port-border rounded-lg p-2 text-xs">- <summary className="cursor-pointer select-none text-port-text-muted">+ <summary className="cursor-pointer select-none text-port-text-muted min-h-[44px] sm:min-h-0 flex flex-wrap items-center gap-x-1">Typography — {renderStyleLabel(composition.mode)} · {cues.length} text cue{cues.length === 1 ? '' : 's'}<span className="block sm:inline sm:ml-1">— timed text laid over the footage, kept inside the title-safe area.</span></summary>diff --git a/client/src/components/musicVideo/VisualSpecPanel.jsx b/client/src/components/musicVideo/VisualSpecPanel.jsxindex 7e83820e91..b1ca9e9a98 100644--- a/client/src/components/musicVideo/VisualSpecPanel.jsx+++ b/client/src/components/musicVideo/VisualSpecPanel.jsx@@ -72,7 +72,7 @@ export default function VisualSpecPanel({ project, onSave, onAddReference }) {return (<details className="mt-2 rounded border border-port-border bg-port-bg/40 p-2 group">- <summary className="cursor-pointer text-xs text-port-text-muted select-none min-h-[32px] flex items-center gap-2">+ <summary className="cursor-pointer text-xs text-port-text-muted select-none min-h-[44px] sm:min-h-[32px] flex items-center gap-2"><Palette size={13} /><span>Visual spec</span><span>· {references.length} reference{references.length === 1 ? '' : 's'}</span>diff --git a/client/src/components/musicVideo/YoutubeImportControls.jsx b/client/src/components/musicVideo/YoutubeImportControls.jsxindex 047d47cf87..42127b168e 100644--- a/client/src/components/musicVideo/YoutubeImportControls.jsx+++ b/client/src/components/musicVideo/YoutubeImportControls.jsx@@ -6,7 +6,7 @@ import { Activity, Download } from 'lucide-react';export default function YoutubeImportControls({ id, url, onUrlChange, job, onStart, compact = false, disabled = false }) {const size = compact ? 12 : 13;const py = compact ? 'py-1' : 'py-1.5';- const btnExtra = compact ? '' : 'text-xs whitespace-nowrap min-h-[44px] sm:min-h-0';+ const btnExtra = compact ? 'min-h-[44px] sm:min-h-0' : 'text-xs whitespace-nowrap min-h-[44px] sm:min-h-0';return (<><inputdiff --git a/client/src/components/musicVideo/stages/BoardStage.jsx b/client/src/components/musicVideo/stages/BoardStage.jsxnew file mode 100644index 0000000000..bd5093a5db--- /dev/null+++ b/client/src/components/musicVideo/stages/BoardStage.jsx@@ -0,0 +1,71 @@+import { Plus } from 'lucide-react';+import BeatTimeline from '../BeatTimeline.jsx';+import SceneCard from '../SceneCard.jsx';+import { PlanActions } from '../ProjectActionGroups.jsx';++/**+ * Board: plan and arrange the shots, the beat timeline, and the scene cards —+ * one column on a phone, two and three as the column widens (a container+ * query, so the docked preview narrowing the column is accounted for). Cards+ * are collapsed to a thumbnail, lyric and status until tapped.+ */+export default function BoardStage({ board }) {+ const { project, locked, busy, sceneMedia, videoSettings, takes } = board;+ const scenes = project.scenes || [];+ return (+ <fieldset disabled={locked} className="min-w-0 space-y-3">+ <div className="rounded-lg border border-port-border bg-port-card p-3">+ <PlanActions project={project} busy={busy} onPlan={board.onPlan} onAutoArrange={board.onAutoArrange} />+ </div>++ {project.audioAnalysis && scenes.length > 0 && (+ <BeatTimeline audioAnalysis={project.audioAnalysis} scenes={scenes} lyricCues={project.lyricCues} onCommit={board.commitSceneTiming} />+ )}++ <div className="flex items-center justify-between">+ <h3 className="text-sm font-medium">Scene board</h3>+ <button onClick={board.onAddScene} className="flex min-h-[44px] items-center gap-1 rounded bg-port-accent px-2 py-1.5 text-sm text-white sm:min-h-0">+ <Plus size={15} /> Add scene+ </button>+ </div>++ {scenes.length === 0 && <p className="text-sm text-port-text-muted">No scenes yet — add one to start the board.</p>}+ <div className="@container">+ <div className="grid grid-cols-1 items-start gap-3 @2xl:grid-cols-2 @5xl:grid-cols-3">+ {scenes.map((scene, idx) => (+ <SceneCard+ key={scene.sceneId}+ scene={scene}+ index={idx}+ isLast={idx === scenes.length - 1}+ generatingFrame={sceneMedia.genScenes[scene.sceneId]}+ generatingVideo={sceneMedia.genVideoScenes[scene.sceneId]}+ settingsSaving={videoSettings.saving}+ videoBlockedReason={videoSettings.videoBlockedReason}+ lipSyncBackend={videoSettings.audioReactiveSelected ? 'local' : videoSettings.settings.backend}+ songDurationSec={project.audioAnalysis?.durationSec ?? null}+ falVideoSettings={videoSettings.settings}+ canContinueShot={board.canContinueShot}+ onMove={board.moveScene}+ onDelete={board.onDeleteScene}+ onSplit={board.onSplitScene}+ onEditLocal={board.editSceneLocal}+ onSave={board.saveScene}+ onGenerateFrame={sceneMedia.generateFrame}+ onGenerateVideo={sceneMedia.generateSceneVideo}+ onContinueVideo={sceneMedia.continueSceneVideo}+ onOpenPreview={board.openPreview}+ onSeek={board.seekToScene}+ takeBusy={takes.busy}+ onSelectTake={takes.selectTake}+ onReviewTake={takes.reviewTake}+ onImportTake={(target) => board.setPickerTarget({ type: 'take', sceneId: target.sceneId })}+ onImportClipTake={(target) => board.setPickerTarget({ type: 'clip', sceneId: target.sceneId })}+ layered={project.composition?.mode === 'composed'}+ />+ ))}+ </div>+ </div>+ </fieldset>+ );+}diff --git a/client/src/components/musicVideo/stages/CastSetsStage.jsx b/client/src/components/musicVideo/stages/CastSetsStage.jsxnew file mode 100644index 0000000000..656957a30b--- /dev/null+++ b/client/src/components/musicVideo/stages/CastSetsStage.jsx@@ -0,0 +1,40 @@+import CastAndSetsCheckin from '../CastAndSetsCheckin.jsx';+import DevArtifactsPanel from '../DevArtifactsPanel.jsx';++/**+ * Cast & Sets: the check-in the autopilot stops at before planning — approve,+ * regenerate with notes, resume or skip — and the sheets it saved.+ */+export default function CastSetsStage({ board }) {+ const { project, locked, castSets, kickoff } = board;+ return (+ <fieldset disabled={locked} className="min-w-0 space-y-3">+ {project.castAndSets ? (+ <div className="rounded-lg border border-port-border bg-port-card p-3">+ <CastAndSetsCheckin+ project={project}+ busy={castSets.busy || kickoff.running}+ onOpenSheet={board.openArtifact}+ onApprove={board.approveCastAndSets}+ onRegenerate={() => castSets.regenerate()}+ onResume={() => castSets.resume()}+ onSkip={board.skipCastAndSets}+ />+ </div>+ ) : (+ <p className="rounded-lg border border-port-border bg-port-card p-3 text-sm text-port-text-muted">+ The autopilot builds the cast and sets — and stops for your check-in — before it plans the shots.+ Run it from the header or the Produce tab; a hands-on project can skip this stage.+ </p>+ )}+ <DevArtifactsPanel+ project={project}+ busy={board.devArtifacts.busy}+ onOpen={board.openArtifact}+ kinds={['cast-sets']}+ title="Cast & Sets sheets"+ emptyText="The check-in sheet appears here once the cast and sets are built"+ />+ </fieldset>+ );+}diff --git a/client/src/components/musicVideo/stages/ComposeStage.jsx b/client/src/components/musicVideo/stages/ComposeStage.jsxnew file mode 100644index 0000000000..852796b628--- /dev/null+++ b/client/src/components/musicVideo/stages/ComposeStage.jsx@@ -0,0 +1,36 @@+import TypographyPanel from '../TypographyPanel.jsx';+import CodeVideoPanel from '../CodeVideoPanel.jsx';+import DocumentCompositionPanel from '../DocumentCompositionPanel.jsx';+import { RenderStyleSelect } from '../ProjectActionGroups.jsx';++/**+ * Compose: how the final render is put together — the render style, the timed+ * typography, and (per style) the code-rendered or composition-document+ * panel. The preview of what this produces is docked beside these panels.+ */+export default function ComposeStage({ board }) {+ const { project, locked, audioUrl } = board;+ const mode = project.composition?.mode;+ return (+ <fieldset disabled={locked} className="min-w-0">+ <div className="space-y-2 rounded-lg border border-port-border bg-port-card p-3">+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-xs text-port-text-muted" aria-hidden="true">Render style</span>+ <RenderStyleSelect project={project} onRenderStyle={board.onRenderStyle} />+ </div>+ <TypographyPanel project={project} onEditLocal={board.editProjectLocal} onSave={board.saveProjectFields} />+ {mode === 'code' && (+ <CodeVideoPanel project={project} audioUrl={audioUrl} onProject={board.replaceProject} />+ )}+ {mode === 'document' && (+ <DocumentCompositionPanel+ key={`document-${project.id}`}+ project={project}+ onProject={board.replaceProject}+ onSave={board.saveProjectFields}+ />+ )}+ </div>+ </fieldset>+ );+}diff --git a/client/src/components/musicVideo/stages/ProduceStage.jsx b/client/src/components/musicVideo/stages/ProduceStage.jsxnew file mode 100644index 0000000000..5395335476--- /dev/null+++ b/client/src/components/musicVideo/stages/ProduceStage.jsx@@ -0,0 +1,29 @@+import AutopilotPanel from '../AutopilotPanel.jsx';+import StageSection from '../StageSection.jsx';+import { GenerationActions } from '../ProjectActionGroups.jsx';++/**+ * Produce: the autopilot (brief, allowed routes, generation and spend caps,+ * the run log) and the manual generators — frame and clip renderers, and the+ * batch "generate what's missing" buttons.+ */+export default function ProduceStage({ board }) {+ const { project, locked, production, videoSettings, sceneMedia, kickoff } = board;+ return (+ <fieldset disabled={locked} className="min-w-0 space-y-3">+ <AutopilotPanel+ key={`autopilot-${project.id}`}+ project={project}+ production={production}+ onSave={board.saveAutomation}+ onKickoff={board.onKickoff}+ kickoffBusy={board.busy.analyzing || board.busy.planning || kickoff.running}+ kickoffStep={kickoff.stepLabel}+ kickoffBlockedReason={board.autopilotBlockedReason}+ />+ <StageSection title="Generation" defaultOpen summary="Frame and clip renderers, and generate what is missing">+ <GenerationActions project={project} videoSettings={videoSettings} sceneMedia={sceneMedia} />+ </StageSection>+ </fieldset>+ );+}diff --git a/client/src/components/musicVideo/stages/ReviewStage.jsx b/client/src/components/musicVideo/stages/ReviewStage.jsxnew file mode 100644index 0000000000..04e8a9aa5a--- /dev/null+++ b/client/src/components/musicVideo/stages/ReviewStage.jsx@@ -0,0 +1,71 @@+import RenderStatusPanel from '../RenderStatusPanel.jsx';+import ExcerptPanel from '../ExcerptPanel.jsx';+import DevArtifactsPanel from '../DevArtifactsPanel.jsx';+import HandoffControls from '../HandoffControls.jsx';+import StageSection from '../StageSection.jsx';+import { RenderFinalButton } from '../ProjectActionGroups.jsx';++/**+ * Review & Export: the final render and its player, draft excerpts with review+ * notes, section revision and auto-review (they act on the excerpt window, so+ * they live beside it), every development file, and the external-tool handoff.+ */+export default function ReviewStage({ board }) {+ const {+ project, locked, renderJob, renderBound, finalVideo, excerpts, revisions, autoReview, sceneMedia, devArtifacts, takes,+ } = board;+ return (+ <fieldset disabled={locked} className="min-w-0 space-y-3">+ <section id="mv-final-video" aria-label="Final render" className="rounded-lg border border-port-border bg-port-card p-3">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <h3 className="text-sm font-medium">Final render</h3>+ <RenderFinalButton project={project} renderJob={renderJob} />+ </div>+ <RenderStatusPanel+ rendering={renderBound}+ progress={renderJob.progress}+ renderHistoryId={project.renderHistoryId}+ finalVideo={finalVideo}+ onOpenPreview={board.openPreview}+ />+ </section>++ <div className="rounded-lg border border-port-border bg-port-card p-3">+ <ExcerptPanel+ project={project}+ rendering={excerpts.rendering}+ progress={excerpts.progress}+ excerpts={project.excerpts || []}+ deletingId={excerpts.deletingId}+ noteBusyId={excerpts.noteBusyId}+ startExcerpt={excerpts.startExcerpt}+ cancelExcerpt={excerpts.cancelExcerpt}+ deleteExcerpt={excerpts.deleteExcerpt}+ addNote={excerpts.addNote}+ editNote={excerpts.editNote}+ deleteNote={excerpts.deleteNote}+ revision={{ ...revisions, genScenes: sceneMedia.genScenes, genVideoScenes: sceneMedia.genVideoScenes }}+ autoReview={autoReview}+ />+ </div>++ <DevArtifactsPanel+ project={project}+ busy={devArtifacts.busy}+ onOpen={board.openArtifact}+ onUpload={board.onUploadArtifact}+ />++ <StageSection title="External handoff" summary="Export prompts, import files made in other tools">+ <HandoffControls+ projectId={project.id}+ busy={takes.busy}+ onExport={takes.exportHandoff}+ onExportBundle={takes.exportHandoffBundle}+ onImport={takes.importHandoffFiles}+ onOpenContactSheet={board.openContactSheet}+ />+ </StageSection>+ </fieldset>+ );+}diff --git a/client/src/components/musicVideo/stages/SetupStage.jsx b/client/src/components/musicVideo/stages/SetupStage.jsxnew file mode 100644index 0000000000..c180861c0f--- /dev/null+++ b/client/src/components/musicVideo/stages/SetupStage.jsx@@ -0,0 +1,101 @@+import AutoSizeTextarea from '../../ui/AutoSizeTextarea';+import CreativeSetupPanel from '../CreativeSetupPanel.jsx';+import TrackPanel from '../TrackPanel.jsx';+import AnalysisPanel from '../AnalysisPanel.jsx';+import LyricsPanel from '../LyricsPanel.jsx';+import VisualSpecPanel from '../VisualSpecPanel.jsx';+import TreatmentPanel from '../TreatmentPanel.jsx';+import { AudioActions } from '../ProjectActionGroups.jsx';++/**+ * Setup: where the song, its analysis and the creative direction come from —+ * creative setup (universe, cast, places), the track and its analysis/MIDI,+ * lyrics, concept & style, the visual spec and the treatment.+ */+export default function SetupStage({ board }) {+ const {+ project, tracks, trackName, audioFilename, locked, youtube, separation, midi, midiBound, renderBound, tempo, busy,+ conceptDraft, styleDraft, importingLyrics, aligningLyrics, treatment,+ } = board;+ return (+ <>+ <CreativeSetupPanel+ key={`creative-${project.id}`}+ project={project}+ onPendingChange={board.setCreativeSetupPending}+ onSave={board.saveCreativeSetup}+ />+ <fieldset disabled={locked} className="min-w-0">+ <div id="mv-track" className="space-y-2 rounded-lg border border-port-border bg-port-card p-3">+ <TrackPanel+ project={project}+ tracks={tracks}+ trackName={trackName}+ audioFilename={audioFilename}+ youtube={youtube}+ renderBound={renderBound}+ midiBound={midiBound}+ onChangeTrack={board.onChangeTrack}+ onProjectUpdated={board.replaceProject}+ separation={separation}+ />+ <AudioActions project={project} midi={midi} midiBound={midiBound} busy={busy} onAnalyze={board.onAnalyze} />+ <AnalysisPanel+ audioAnalysis={project.audioAnalysis}+ scenes={project.scenes || []}+ tempo={tempo}+ onReanalyze={board.onAnalyze}+ analyzing={busy.analyzing}+ />+ <LyricsPanel+ project={project}+ onEditLocal={board.editProjectLocal}+ onSave={board.saveProjectFields}+ onImport={board.onImportLyrics}+ onImportTrack={board.onImportTrackLyrics}+ importing={importingLyrics}+ onAlign={board.onAlignLyrics}+ aligning={aligningLyrics}+ />++ {/* Concept & style — global direction for the video */}+ <div className="mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2">+ <div>+ <label htmlFor="mv-concept" className="mb-1 block text-xs text-port-text-muted">Concept</label>+ <AutoSizeTextarea+ id="mv-concept"+ value={conceptDraft.value}+ rows={2}+ maxLength={8000}+ onChange={conceptDraft.onChange}+ onBlur={conceptDraft.onBlur}+ placeholder="What is this video about — story, theme, or narrative thread for the AI plan to build on."+ className="min-h-[44px] w-full rounded border border-port-border bg-port-bg px-2 py-1.5 text-sm"+ />+ </div>+ <div>+ <label htmlFor="mv-style" className="mb-1 block text-xs text-port-text-muted">Visual style</label>+ <AutoSizeTextarea+ id="mv-style"+ value={styleDraft.value}+ rows={2}+ maxLength={2000}+ onChange={styleDraft.onChange}+ onBlur={styleDraft.onBlur}+ placeholder="Art style, references, palette, mood — appended to every generated frame and shot prompt."+ className="min-h-[44px] w-full rounded border border-port-border bg-port-bg px-2 py-1.5 text-sm"+ />+ </div>+ </div>+ <VisualSpecPanel+ key={project.id}+ project={project}+ onSave={board.saveVisualSpec}+ onAddReference={board.onAddReference}+ />+ <TreatmentPanel key={`treatment-${project.id}`} project={project} treatment={treatment} />+ </div>+ </fieldset>+ </>+ );+}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 35890c30f3..17bc6e0f52 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -59,11 +59,12 @@ grep -i "what you want to do" client/src/lib/README.md| `backupExcludes.js` | CLIENT MIRROR of the backup-exclude block in `server/lib/sharedSchemas.js` (#7241) — `anchorUserExclude` / `anchorUserExcludes` / `isSafeExcludePattern` / `EXCLUDE_PATTERN_MAX_LENGTH`. The Backup settings tab anchors a newly added exclude and renders the effective list with these, so the chip the user sees is the rsync filter the server will actually run instead of an unanchored pattern that matches at any depth. || `beatColors.js` | `BEAT_KIND_COLORS` + `getBeatKindColor(kind)` — per-kind display colors for reader-map emotional beats (kinds defined server-side in `storyArc.js`). Keeps every beat visualization consistent. || `beatGrid.js` | Music-video beat-quantized timeline arranger (#1854). `buildBeatGridPoints(audioAnalysis)` merges beats/downbeats/section edges into one ranked snap-point list; `snapTimeToGrid(timeSec, gridPoints, toleranceSec)` finds the nearest point within tolerance; `computeSceneSpans(scenes, durationSec)` lays out scenes without a persisted `startSec`/`endSec` contiguously as a display-only fallback; `computeDragSpan({kind, startSpan, deltaSec, gridPoints, ...})` resolves a timeline drag gesture (`'move'` or `'right'` — no `'left'`, since the render can only trim from a clip's own frame 0) into a new span; `shouldMarkBeatAligned({kind, snapped, wasPersisted})` gates the `beatAligned` flag so a reposition-only drag can't silently promote an unpersisted scene's placeholder fallback duration into a "saved exactly" render duration; `autoArrangeScenes(scenes, audioAnalysis)` proposes a full `{ sceneId, startSec, endSec, beatAligned }[]` arrangement by distributing scenes across song sections weighted by each section's `energy` (#1915). Used by `components/musicVideo/BeatTimeline.jsx` and `pages/MusicVideo.jsx`. |-| `musicVideoLayers.js` | Music-video per-scene visual layers (#8985), re-exported from `server/lib/musicVideoLayers.js`: `MUSIC_VIDEO_VISUAL_LAYERS`, `MUSIC_VIDEO_STILL_MOVES`, `sceneVisualLayer(scene, { layered })`, `sceneHasAuthoredSpan`, `sceneRenderReady(scene, { layered })`. Used by `components/musicVideo/SceneCard.jsx`, `ProjectToolbar.jsx` and `hooks/useMusicVideoSceneMedia.js`. |+| `musicVideoLayers.js` | Music-video per-scene visual layers (#8985), re-exported from `server/lib/musicVideoLayers.js`: `MUSIC_VIDEO_VISUAL_LAYERS`, `MUSIC_VIDEO_STILL_MOVES`, `sceneVisualLayer(scene, { layered })`, `sceneHasAuthoredSpan`, `sceneRenderReady(scene, { layered })`. Used by `components/musicVideo/SceneCard.jsx`, `ProjectActionGroups.jsx` and `hooks/useMusicVideoSceneMedia.js`. || `musicVideoTakes.js` | Music-video scene takes view helpers (#8965): `sceneTakeList(scene, kind)` lists a scene's image/video takes with an un-materialized pre-takes selection appended as a read-only `legacy` take; `takePreviewKey`, `takeThumbUrl`, `takeProvenance`; `TAKE_SLOT` maps a take kind to its selection field. Used by `components/musicVideo/SceneTakeStrip.jsx` and `pages/MusicVideo.jsx`. || `musicVideoShotTiming.js` | Re-export of `server/lib/musicVideoShotTiming.js` (#8977) — shot modes, the verified source-audio lip-sync capability table, `performanceBlockedReason`, `planPerformanceWindow`, `grokCoverage`, `approximateMotionCues`, `shotSplitLimit` (when a scene offers a lyric-boundary split), `falSceneTake` (a fal take's model, length, resolution and estimated cost). Used by `hooks/useMusicVideoSceneMedia.js` and `components/musicVideo/SceneCard.jsx`. |+| `musicVideoStages.js` | Music Video page stage model: `MUSIC_VIDEO_STAGES` (setup → cast-sets → board → produce → compose → review), `resolveStageParam(value)` for the `:stage` route param, `deriveStages(project)` (per-stage `done`/`active`/`blocked`/`todo` + `current`, the first incomplete stage; a live production run pins Produce), `deriveNextAction(project, ctx)` (the one primary action the sticky header offers — approve Cast & Sets, stop/resume production, render final, …), `projectSpend(project)` (paid generation used vs. cap) and `currentProductionRun`. Used by `components/musicVideo/MusicVideoLayout.jsx` and `pages/MusicVideo.jsx`. || `musicVideoUniverseRefs.js` | `pullUniverseCanonReferences(universe, existingReferences)` (#8978) maps a linked universe's characters/places/objects to visual-spec references (character/set/prop roles), skipping images already present and capping at `MUSIC_VIDEO_MAX_REFERENCES` (24, mirrors the server schema). Returns `{ next, added, skipped }`; the caller persists `next` via the ordinary visualSpec PATCH. Used by `components/musicVideo/VisualSpecPanel.jsx`. (The style snapshots are derived server-side, #9105.) |-| `musicVideoAutomation.js` | Music Video automation brief, client half: re-exports the server tool catalog (`MUSIC_VIDEO_AUTOMATION_TOOLS` / `_TOOL_IDS`), `DEFAULT_AUTOMATION_TOOLS` (the unmetered tools), and the form mapping `automationDraftFrom(automation)` / `automationFromDraft(draft)` (empty budget = no cap). Used by the create drawer and `AutomationPanel`. |+| `musicVideoAutomation.js` | Music Video automation brief, client half: re-exports the server tool catalog (`MUSIC_VIDEO_AUTOMATION_TOOLS` / `_TOOL_IDS`), `DEFAULT_AUTOMATION_TOOLS` (the unmetered tools), and the form mapping `automationDraftFrom(automation)` / `automationFromDraft(draft)` (empty budget = no cap). Used by the create drawer and `AutopilotPanel`. || `bibleLimits.js` | `BIBLE_LIMITS` re-exported from the pure leaf `server/lib/bibleLimits.js`, plus the client-only `capImageRefs` / `appendImageRefById` for the optimistic imageRefs-append paths. || `characterEvolution.js` | The five-stage character evolution lens as the editors consume it. Re-exports `EVOLUTION_STAGES` / `EVOLUTION_OUTCOMES` / `EVOLUTION_STAGE_LABELS` / `EVOLUTION_STAGE_TEXT_FIELDS` / `EVOLUTION_EVIDENCE_FIELDS` / `EVOLUTION_EVIDENCE_STATUSES` / `CHARACTER_EVOLUTION_LIMITS` / `evolutionEvidenceStatus` / `isDeclaredEvolution` from the pure leaf `server/lib/characterEvolution.js` (a guard in `server/lib/characterEvolution.test.js` fails if this file ever restates a vocabulary instead of re-exporting it), adds the editor descriptors `EVOLUTION_STAGE_EDITOR_FIELDS` / `EVOLUTION_OUTCOME_HINTS` (#6440), and the draft-mutation helpers `evolutionStage` / `patchEvolution` / `patchEvolutionStage` / `patchEvolutionEvidence` that keep an editor's draft collapsing to the same shape the server sanitizer produces — so a present-but-empty field is a real clear (#6441). || `characterFramework.js` | The narrative-character framework as the editors consume it. Re-exports `CHARACTER_ARC_TYPES` / `CHARACTER_FRAMEWORK_FIELDS` / `CHARACTER_FRAMEWORK_TEXT_FIELDS` / `CHARACTER_FRAMEWORK_LIMITS` / `CHARACTER_PSYCHOLOGY_LIMITS` / `CHARACTER_SLIDER_AXES` / `PSYCHOLOGY_ASSESSMENTS` / `PSYCHOLOGY_DRIVE_AXES` / `RELATIONSHIP_LINK_TYPES` from the pure leaf `server/lib/characterFramework.js`, and adds the editor descriptors `CHARACTER_FRAMEWORK_EDITOR_FIELDS` (Ghost → Wound → Lie → Need → Want, with labels/placeholders/caps), `CHARACTER_MOTIVATIONS_FIELD`, `CHARACTER_SECRETS_FIELD`, `CHARACTER_PSYCHOLOGY_EDITOR_FIELDS` / `CHARACTER_PSYCHOLOGY_NOTE_FIELD` / `CHARACTER_PSYCHOLOGY_DRIVE_HINTS` (#6414), and `CHARACTER_SLIDER_MIN` / `CHARACTER_SLIDER_MAX`. Shared by the Universe cast editor and the Writers Room bible so the two never restate the same field copy (#6417). |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 533ba6f69c..97ae4202e7 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -71,6 +71,7 @@ export * from './muscriptorModels.js';export * from './musicVideoLayers.js';export * from './musicVideoTakes.js';export * from './musicVideoShotTiming.js';+export * from './musicVideoStages.js';export * from './musicVideoUniverseRefs.js';export * from './musicVideoAutomation.js';export * from './pipelineImageDefaults.js';diff --git a/client/src/lib/musicVideoStages.js b/client/src/lib/musicVideoStages.jsnew file mode 100644index 0000000000..0296cae517--- /dev/null+++ b/client/src/lib/musicVideoStages.js@@ -0,0 +1,185 @@+/**+ * Music Video page stages: the tab set, which stage a project is in, the one+ * "next action" the sticky header offers for it, and the project's generation+ * spend. Pure functions over the project record so the header, the progress+ * strip and the tests all read the same answer.+ */+import { sceneRenderReady } from './musicVideoLayers.js';++export const MUSIC_VIDEO_STAGES = [+ { id: 'setup', label: 'Setup', title: 'Setup' },+ { id: 'cast-sets', label: 'Cast & Sets', title: 'Cast & Sets' },+ { id: 'board', label: 'Board', title: 'Board' },+ { id: 'produce', label: 'Produce', title: 'Produce' },+ { id: 'compose', label: 'Compose', title: 'Compose' },+ { id: 'review', label: 'Review', title: 'Review & Export' },+];++// Stages whose tab keeps the preview player docked beside the content.+export const PREVIEW_STAGES = new Set(['board', 'compose', 'review']);++export const isStageId = (value) => MUSIC_VIDEO_STAGES.some((stage) => stage.id === value);++/** A production run in one of these states can still be resumed (or is live). */+export const RESUMABLE_RUN_STATUSES = new Set(['running', 'stopped', 'limit-reached', 'blocked', 'needs-replan']);+// A stopped run that needs the director's attention rather than a click on Resume.+const RUN_BLOCKED_STATUSES = new Set(['limit-reached', 'blocked', 'needs-replan', 'needs-human', 'failed']);+const CAST_WORKING = new Set(['directing', 'imaging', 'assembling']);++/** The run worth showing: the live one, else the most recent. */+export const currentProductionRun = (project) => {+ const runs = Array.isArray(project?.productionRuns) ? project.productionRuns : [];+ return runs.find((r) => RESUMABLE_RUN_STATUSES.has(r.status)) || runs[runs.length - 1] || null;+};++export const projectHasAudio = (project) => !!(project?.trackId || project?.uploadedAudioFilename);++/**+ * What the project has spent on paid generation across its production runs,+ * against the cap that applies now: the live/latest run's, else the autopilot+ * brief's budget. `capUsd` is null when nothing caps it.+ */+export function projectSpend(project) {+ const runs = Array.isArray(project?.productionRuns) ? project.productionRuns : [];+ const spentUsd = runs.reduce((sum, run) => {+ const spent = Number(run?.usage?.spentUsd);+ return sum + (Number.isFinite(spent) ? spent : 0);+ }, 0);+ const run = currentProductionRun(project);+ const runCap = run?.limits?.spendCapUsd;+ const briefCap = project?.automation?.budgetUsd;+ const capUsd = runCap != null ? runCap : (briefCap != null ? briefCap : null);+ return { spentUsd, capUsd };+}++/**+ * What the docked preview plays: the composition document when the project+ * renders as one, otherwise the newest finished draft excerpt, otherwise+ * nothing (the dock stays out of the way).+ */+export function resolvePreviewSource(project) {+ if (project?.composition?.mode === 'document' && project.composition.document) return { kind: 'document' };+ const excerpt = [...(project?.excerpts || [])].reverse().find((e) => e.status === 'complete' && e.filename);+ return excerpt ? { kind: 'excerpt', excerpt } : null;+}++/** Resolve the `:stage` route param; an unknown or missing value is null. */+export const resolveStageParam = (value) => (isStageId(value) ? value : null);++const composeDone = (project, mode) => {+ if (mode === 'composed') return (project.composition?.textCues || []).length > 0;+ if (mode === 'document') return !!project.composition?.document;+ // Footage has nothing to compose; a code-rendered video is composed by its own panel on demand.+ return true;+};++/**+ * Each stage's state derived from the project record — `done`, `blocked`+ * (stopped and needs the director), `active` (the stage the project is in), or+ * `todo` — plus `current`, the first stage that is not done. A live production+ * run owns the project, so it pins `current` to Produce.+ */+export function deriveStages(project) {+ const scenes = project?.scenes || [];+ const mode = project?.composition?.mode || 'concat';+ const cast = project?.castAndSets || null;+ const run = currentProductionRun(project);+ const liveRun = !!run && RESUMABLE_RUN_STATUSES.has(run.status);+ const layered = mode === 'composed';+ // Code and document renders draw the picture themselves; scene footage is optional there.+ const footageOptional = mode === 'code' || mode === 'document';+ const planned = scenes.length > 0;+ const castApplies = !!cast || !!project?.automation;+ const castStopped = !!cast && (cast.interrupted || cast.status === 'failed');+ const castDone = !castApplies || cast?.status === 'approved' || cast?.status === 'skipped' || (!cast && planned);+ const produceDone = planned && (footageOptional || scenes.every((scene) => sceneRenderReady(scene, { layered })));++ const done = {+ setup: projectHasAudio(project) && !!project?.audioAnalysis,+ 'cast-sets': castDone,+ board: planned,+ produce: produceDone,+ compose: composeDone(project || {}, mode),+ review: !!project?.renderHistoryId,+ };+ const blocked = {+ 'cast-sets': castStopped,+ produce: !!run && RUN_BLOCKED_STATUSES.has(run.status),+ };+ const current = liveRun+ ? 'produce'+ : (MUSIC_VIDEO_STAGES.find((stage) => !done[stage.id])?.id || 'review');+ const stages = MUSIC_VIDEO_STAGES.map((stage) => {+ let state = 'todo';+ if (done[stage.id] && !(stage.id === current && liveRun)) state = 'done';+ else if (stage.id === current) state = blocked[stage.id] ? 'blocked' : 'active';+ return { ...stage, state };+ });+ return { stages, current };+}++/**+ * The single primary action the sticky header offers. `kind: 'run'` calls a+ * handler the page owns (keyed by `id`); `kind: 'goto'` opens a stage (and+ * optionally scrolls to `anchor`). `disabled` carries the reason it can't run+ * yet. A live production run, a render in flight and a running kickoff win+ * over the stage: they own the project until they settle.+ */+export function deriveNextAction(project, {+ renderActive = false, renderProgress = 0, renderPending = false, renderBlockedByOther = false,+ kickoffRunning = false, kickoffStep = '', kickoffBlockedReason = null,+ planning = false, analyzing = false,+} = {}) {+ if (!project) return null;+ const { current } = deriveStages(project);+ const run = currentProductionRun(project);+ const cast = project.castAndSets || null;+ const scenes = project.scenes || [];++ if (run && RESUMABLE_RUN_STATUSES.has(run.status)) {+ if (run.status === 'running' && !run.interrupted) return { id: 'stop-production', kind: 'run', label: 'Stop production', runId: run.id };+ return {+ id: 'resume-production', kind: 'run', runId: run.id, acceptBasis: run.status === 'needs-replan',+ label: run.status === 'needs-replan' ? 'Resume with new setup' : 'Resume production',+ };+ }+ if (renderActive) {+ return {+ id: 'render-progress', kind: 'run', label: renderPending ? 'Preparing…' : `Rendering… ${Math.round(renderProgress)}%`,+ disabled: true,+ };+ }+ if (kickoffRunning || analyzing || planning) {+ return { id: 'busy', kind: 'run', label: kickoffStep || (planning ? 'Planning…' : 'Working…'), disabled: true };+ }++ switch (current) {+ case 'setup':+ if (!projectHasAudio(project)) return { id: 'goto-setup', kind: 'goto', stage: 'setup', anchor: 'mv-track', label: 'Attach a track' };+ if (project.automation && scenes.length === 0) {+ return { id: 'kickoff', kind: 'run', label: 'Run autopilot', disabled: !!kickoffBlockedReason, reason: kickoffBlockedReason || undefined };+ }+ return { id: 'analyze', kind: 'run', label: 'Analyze song' };+ case 'cast-sets':+ if (cast?.status === 'review') return { id: 'approve-cast-sets', kind: 'run', label: 'Approve cast & sets' };+ if (cast && (cast.interrupted || cast.status === 'failed')) return { id: 'resume-cast-sets', kind: 'run', label: 'Resume cast & sets' };+ if (cast && CAST_WORKING.has(cast.status)) return { id: 'busy', kind: 'run', label: 'Building cast & sets…', disabled: true };+ return { id: 'kickoff', kind: 'run', label: 'Run autopilot', disabled: !!kickoffBlockedReason, reason: kickoffBlockedReason || undefined };+ case 'board':+ return { id: 'plan', kind: 'run', label: 'Plan the shots', disabled: !project.audioAnalysis, reason: project.audioAnalysis ? undefined : 'Analyze the track first' };+ case 'produce':+ if (run?.status === 'needs-human') return { id: 'goto-review', kind: 'goto', stage: 'review', label: 'Review the draft' };+ return { id: 'goto-produce', kind: 'goto', stage: 'produce', anchor: 'mv-production-start', label: 'Set up production' };+ case 'compose':+ return {+ id: 'goto-compose', kind: 'goto', stage: 'compose',+ label: (project.composition?.mode === 'document') ? 'Attach a composition' : 'Add typography',+ };+ default:+ if (project.renderHistoryId) return { id: 'goto-final', kind: 'goto', stage: 'review', anchor: 'mv-final-video', label: 'Watch final video' };+ return {+ id: 'render-final', kind: 'run', label: 'Render final video',+ disabled: renderBlockedByOther, reason: renderBlockedByOther ? 'Wait for the other project render to finish' : undefined,+ };+ }+}diff --git a/client/src/lib/musicVideoStages.test.js b/client/src/lib/musicVideoStages.test.jsnew file mode 100644index 0000000000..fdb82e6b5f--- /dev/null+++ b/client/src/lib/musicVideoStages.test.js@@ -0,0 +1,128 @@+import { describe, it, expect } from 'vitest';+import {+ MUSIC_VIDEO_STAGES, currentProductionRun, deriveNextAction, deriveStages, projectSpend, resolvePreviewSource, resolveStageParam,+} from './musicVideoStages.js';++const ANALYSIS = { bpm: 120, durationSec: 30, sections: [] };+const scene = (over = {}) => ({ sceneId: 's1', order: 0, prompt: 'a', referenceImageId: 'img', videoHistoryId: 'vid', ...over });+const run = (over = {}) => ({+ id: 'run-1', status: 'running', interrupted: false, limits: { maxGenerations: 12, spendCapUsd: 20 }, usage: { generations: 3, spentUsd: 4.5 }, ...over,+});+const stateOf = (project) => Object.fromEntries(deriveStages(project).stages.map((s) => [s.id, s.state]));++describe('deriveStages / deriveNextAction', () => {+ it('a fresh autopilot project starts at Setup and offers to run autopilot once a track is attached', () => {+ const fresh = { id: 'p', trackId: 't1', automation: { tools: [] }, scenes: [] };+ expect(deriveStages(fresh).current).toBe('setup');+ expect(deriveNextAction(fresh)).toMatchObject({ id: 'kickoff', kind: 'run', disabled: false });+ // With the autopilot blocked (e.g. unsaved creative setup) the action stays visible but disabled, with the reason.+ expect(deriveNextAction(fresh, { kickoffBlockedReason: 'Save the creative setup first.' }))+ .toMatchObject({ id: 'kickoff', disabled: true, reason: 'Save the creative setup first.' });+ // No track: the only useful step is attaching one.+ expect(deriveNextAction({ ...fresh, trackId: null })).toMatchObject({ id: 'goto-setup', kind: 'goto', stage: 'setup' });+ // A hands-on project (no brief) analyzes the song.+ expect(deriveNextAction({ id: 'p', trackId: 't1', scenes: [] })).toMatchObject({ id: 'analyze' });+ });++ it('a project waiting on Cast & Sets approval offers the approval, and a stopped check-in offers to resume', () => {+ const waiting = { id: 'p', trackId: 't1', audioAnalysis: ANALYSIS, automation: {}, castAndSets: { status: 'review' }, scenes: [] };+ expect(deriveStages(waiting).current).toBe('cast-sets');+ expect(stateOf(waiting)).toMatchObject({ setup: 'done', 'cast-sets': 'active', board: 'todo' });+ expect(deriveNextAction(waiting)).toMatchObject({ id: 'approve-cast-sets', kind: 'run' });++ const interrupted = { ...waiting, castAndSets: { status: 'imaging', interrupted: true } };+ expect(stateOf(interrupted)['cast-sets']).toBe('blocked');+ expect(deriveNextAction(interrupted)).toMatchObject({ id: 'resume-cast-sets' });++ const working = { ...waiting, castAndSets: { status: 'imaging' } };+ expect(deriveNextAction(working)).toMatchObject({ id: 'busy', disabled: true });+ });++ it('a live production run owns the project: stop while it runs, resume once it is paused or needs a new basis', () => {+ // Nothing else is done yet — the run still pins the header to Produce.+ const running = { id: 'p', trackId: 't1', scenes: [], productionRuns: [run()] };+ expect(deriveStages(running).current).toBe('produce');+ expect(stateOf(running).produce).toBe('active');+ expect(deriveNextAction(running)).toMatchObject({ id: 'stop-production', runId: 'run-1' });++ const paused = { ...running, productionRuns: [run({ status: 'stopped' })] };+ expect(deriveNextAction(paused)).toMatchObject({ id: 'resume-production', acceptBasis: false });+ const replan = { ...running, productionRuns: [run({ status: 'needs-replan' })] };+ expect(deriveNextAction(replan)).toMatchObject({ id: 'resume-production', acceptBasis: true });+ const interrupted = { ...running, productionRuns: [run({ interrupted: true })] };+ expect(deriveNextAction(interrupted)).toMatchObject({ id: 'resume-production' });+ });++ it('walks Board → Produce → Compose → Review, then reports a finished project', () => {+ const planned = { id: 'p', trackId: 't1', audioAnalysis: ANALYSIS, scenes: [scene({ referenceImageId: null, videoHistoryId: null })] };+ expect(deriveStages(planned).current).toBe('produce');+ expect(deriveNextAction(planned)).toMatchObject({ id: 'goto-produce', kind: 'goto', stage: 'produce' });++ const ready = { ...planned, scenes: [scene()] };+ expect(deriveStages(ready).current).toBe('review');+ expect(deriveNextAction(ready)).toMatchObject({ id: 'render-final', kind: 'run', disabled: false });+ expect(deriveNextAction(ready, { renderBlockedByOther: true })).toMatchObject({ id: 'render-final', disabled: true });+ expect(deriveNextAction(ready, { renderActive: true, renderProgress: 41.6 })).toMatchObject({ id: 'render-progress', disabled: true, label: 'Rendering… 42%' });++ // A composed render needs its text cues before it is ready to render.+ const composed = { ...ready, composition: { mode: 'composed', textCues: [] } };+ expect(deriveStages(composed).current).toBe('compose');+ expect(deriveNextAction(composed)).toMatchObject({ id: 'goto-compose', stage: 'compose' });++ const finished = { ...ready, renderHistoryId: 'rh-1' };+ expect(stateOf(finished)).toMatchObject({ setup: 'done', board: 'done', produce: 'done', compose: 'done', review: 'done' });+ expect(deriveNextAction(finished)).toMatchObject({ id: 'goto-final', kind: 'goto', stage: 'review' });+ });++ it('does not require scene footage for code-rendered or document projects', () => {+ const bare = { id: 'p', trackId: 't1', audioAnalysis: ANALYSIS, scenes: [scene({ referenceImageId: null, videoHistoryId: null })] };+ expect(stateOf({ ...bare, composition: { mode: 'code' } }).produce).toBe('done');+ const doc = { ...bare, composition: { mode: 'document' } };+ expect(deriveStages(doc).current).toBe('compose');+ expect(deriveNextAction(doc).label).toBe('Attach a composition');+ expect(deriveStages({ ...doc, composition: { mode: 'document', document: { directory: 'd' } } }).current).toBe('review');+ });++ it('treats the check-in as not applicable to a hands-on project', () => {+ expect(stateOf({ id: 'p', trackId: 't1', audioAnalysis: ANALYSIS, scenes: [] })['cast-sets']).toBe('done');+ });+});++describe('projectSpend', () => {+ it('sums every run and takes the live run\'s cap, falling back to the brief budget', () => {+ const project = {+ automation: { budgetUsd: 50 },+ productionRuns: [run({ id: 'a', status: 'completed', usage: { spentUsd: 1.25 } }), run({ id: 'b', status: 'running', usage: { spentUsd: 2 }, limits: { spendCapUsd: 10 } })],+ };+ expect(projectSpend(project)).toEqual({ spentUsd: 3.25, capUsd: 10 });+ expect(projectSpend({ automation: { budgetUsd: 50 }, productionRuns: [] })).toEqual({ spentUsd: 0, capUsd: 50 });+ expect(projectSpend({})).toEqual({ spentUsd: 0, capUsd: null });+ });+});++describe('stage route param', () => {+ it('accepts a known stage and rejects anything else so the page can fall back to the default', () => {+ for (const stage of MUSIC_VIDEO_STAGES) expect(resolveStageParam(stage.id)).toBe(stage.id);+ expect(resolveStageParam('dev')).toBeNull();+ expect(resolveStageParam(undefined)).toBeNull();+ });++ it('picks the live run over an older completed one', () => {+ expect(currentProductionRun({ productionRuns: [run({ id: 'live' }), run({ id: 'done', status: 'completed' })] }).id).toBe('live');+ expect(currentProductionRun({})).toBeNull();+ });+});++describe('resolvePreviewSource', () => {+ it('prefers the composition document, then the newest finished excerpt, then nothing', () => {+ const excerpts = [+ { id: 'a', status: 'complete', filename: 'a.mp4', startSec: 0, endSec: 10 },+ { id: 'b', status: 'complete', filename: 'b.mp4', startSec: 10, endSec: 20 },+ { id: 'c', status: 'rendering', filename: null },+ ];+ expect(resolvePreviewSource({ composition: { mode: 'document', document: { directory: 'd' } }, excerpts })).toEqual({ kind: 'document' });+ expect(resolvePreviewSource({ composition: { mode: 'document' }, excerpts }).excerpt.id).toBe('b');+ expect(resolvePreviewSource({ composition: { mode: 'concat', document: { directory: 'd' } }, excerpts }).kind).toBe('excerpt');+ expect(resolvePreviewSource({ excerpts: [{ id: 'c', status: 'error' }] })).toBeNull();+ });+});diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 5cf35c206f..6e3cc536f4 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -1,9 +1,7 @@-import CreativeSetupPanel from '../components/musicVideo/CreativeSetupPanel.jsx';import { useEffect, useState, useCallback, useMemo, useRef } from 'react';import { useParams, useNavigate, useSearchParams } from 'react-router';-import { Plus, Film } from 'lucide-react';+import { Plus, Film, Copy, Trash2 } from 'lucide-react';import toast from '../components/ui/Toast';-import AutoSizeTextarea from '../components/ui/AutoSizeTextarea';import PageHeader from '../components/PageHeader';import {listMusicVideoProjects,@@ -46,36 +44,29 @@ import MediaPreview from '../components/media/MediaPreview.jsx';import MidiInstallModal from '../components/install/MidiInstallModal.jsx';import MidiGatedModal from '../components/install/MidiGatedModal.jsx';import { listTracks, trackAudioUrl } from '../services/apiTracks.js';-import BeatTimeline from '../components/musicVideo/BeatTimeline.jsx';import CreateProjectDrawer from '../components/musicVideo/CreateProjectDrawer.jsx';-import AutomationPanel from '../components/musicVideo/AutomationPanel.jsx';import { automationDraftFrom, automationFromDraft } from '../lib/musicVideoAutomation.js';import { listUniverseNames } from '../services/apiUniverseBuilder.js';-import ProjectToolbar from '../components/musicVideo/ProjectToolbar.jsx';-import TrackPanel from '../components/musicVideo/TrackPanel.jsx';-import RenderStatusPanel from '../components/musicVideo/RenderStatusPanel.jsx';-import ProductionPanel from '../components/musicVideo/ProductionPanel.jsx';-import ExcerptPanel from '../components/musicVideo/ExcerptPanel.jsx';-import AnalysisPanel from '../components/musicVideo/AnalysisPanel.jsx';-import SceneCard from '../components/musicVideo/SceneCard.jsx';-import LyricsPanel from '../components/musicVideo/LyricsPanel.jsx';-import TypographyPanel from '../components/musicVideo/TypographyPanel.jsx';-import CodeVideoPanel from '../components/musicVideo/CodeVideoPanel.jsx';-import DocumentCompositionPanel from '../components/musicVideo/DocumentCompositionPanel.jsx';+import MusicVideoLayout from '../components/musicVideo/MusicVideoLayout.jsx';+import PreviewDock from '../components/musicVideo/PreviewDock.jsx';+import SetupStage from '../components/musicVideo/stages/SetupStage.jsx';+import CastSetsStage from '../components/musicVideo/stages/CastSetsStage.jsx';+import BoardStage from '../components/musicVideo/stages/BoardStage.jsx';+import ProduceStage from '../components/musicVideo/stages/ProduceStage.jsx';+import ComposeStage from '../components/musicVideo/stages/ComposeStage.jsx';+import ReviewStage from '../components/musicVideo/stages/ReviewStage.jsx';import { compositionDraft } from '../components/musicVideo/compositionDraft.js';-import VisualSpecPanel from '../components/musicVideo/VisualSpecPanel.jsx';-import TreatmentPanel from '../components/musicVideo/TreatmentPanel.jsx';-import HandoffControls from '../components/musicVideo/HandoffControls.jsx';import ContactSheetDrawer from '../components/musicVideo/ContactSheetDrawer.jsx';-import DevArtifactsPanel from '../components/musicVideo/DevArtifactsPanel.jsx';import DevArtifactDrawer from '../components/musicVideo/DevArtifactDrawer.jsx';-import CastAndSetsCheckin from '../components/musicVideo/CastAndSetsCheckin.jsx';import GalleryImagePicker from '../components/imageGen/GalleryImagePicker.jsx';import GalleryVideoPicker from '../components/videoGen/GalleryVideoPicker.jsx';import { autoArrangeScenes } from '../lib/beatGrid.js';import { isLtx2FamilyRuntime } from '../lib/runnerFamilies';import { videoPosterForJob } from '../lib/creativeDirectorPreview.js';import { sceneTakeList } from '../lib/musicVideoTakes.js';+import {+ deriveNextAction, deriveStages, projectSpend, resolvePreviewSource, resolveStageParam,+} from '../lib/musicVideoStages.js';// Automation first: a new project defaults to autopilot with the free tools.const emptyCreateForm = () => ({@@ -105,9 +96,12 @@ export default function MusicVideo() {// scene board is directly shareable/bookmarkable and reachable from the// media job-completion hooks. selectProject() navigates; the browser URL is// the single source of truth for "which project is open".- // A development artifact opens from its own deep link- // (/music-video/:projectId/dev/:artifactId), the version from `?v=`.- const { projectId: routeProjectId, artifactId: routeArtifactId } = useParams();+ // The open stage is `/music-video/:projectId/:stage` (Setup, Cast & Sets,+ // Board, Produce, Compose, Review); a missing or unknown stage opens the+ // stage the project was in. A development artifact opens from its own deep+ // link (/music-video/:projectId/:stage/dev/:artifactId, or the older+ // /music-video/:projectId/dev/:artifactId), the version from `?v=`.+ const { projectId: routeProjectId, artifactId: routeArtifactId, stage: routeStage } = useParams();const navigate = useNavigate();const [projects, setProjects] = useState([]);const [tracks, setTracks] = useState([]);@@ -126,6 +120,16 @@ export default function MusicVideo() {const [form, setForm] = useState(emptyCreateForm);const selected = projects.find((p) => p.id === selectedId) || null;+ // Which stage tab is open. The URL is the source of truth; with none (or an+ // unknown one) the tab is the stage the project was in when it was opened,+ // pinned so a stage completing mid-session doesn't move the user off the tab+ // they are working in — the header's next action tracks the project instead.+ const progress = useMemo(() => deriveStages(selected), [selected]);+ const [openedStage, setOpenedStage] = useState({ id: null, stage: null });+ if (selected && openedStage.id !== selected.id) setOpenedStage({ id: selected.id, stage: progress.current });+ const pinnedStage = openedStage.id === selected?.id ? openedStage.stage : null;+ const activeStage = resolveStageParam(routeStage) || pinnedStage || progress.current;+const replaceProject = (next) => setProjects((prev) => prev.map((p) => (p.id === next.id ? next : p)));// Functional merges keyed on the captured projectId/sceneId so an async result// that resolves after the user edited the board can't clobber those edits with@@ -379,8 +383,8 @@ export default function MusicVideo() {};const approveCastAndSets = () => castSets.approve().then(continueAfterCheckin);const skipCastAndSets = () => castSets.skip().then(continueAfterCheckin);- const openArtifact = (artifactId) => navigate(`/music-video/${encodeURIComponent(selected.id)}/dev/${encodeURIComponent(artifactId)}`);- const closeArtifact = () => navigate(`/music-video/${encodeURIComponent(selected?.id || routeProjectId)}`);+ const openArtifact = (artifactId) => navigate(`/music-video/${encodeURIComponent(selected.id)}/${activeStage}/dev/${encodeURIComponent(artifactId)}`);+ const closeArtifact = () => navigate(`/music-video/${encodeURIComponent(selected?.id || routeProjectId)}/${activeStage}`);const openArtifactRecord = routeArtifactId? (selected?.devArtifacts || []).find((a) => a.id === routeArtifactId && !a.deleted) || null: null;@@ -671,7 +675,7 @@ export default function MusicVideo() {items.push(videoItem(take.assetId, `${take.assetId}.mp4`, take.prompt || scene.prompt || ''));}}- // Scenes can reuse the same frame/clip (ProjectToolbar surfaces a+ // Scenes can reuse the same frame/clip (the Produce tab's generation controls surface a// "Repetition: N unique frames" badge). Dedupe by key so prev/next and// openPreview's .find() land on a single item rather than the first of// several identical keys with different prompts.@@ -684,6 +688,143 @@ export default function MusicVideo() {if (match) setPreview(match);}, [previewItems, setPreview]);+ // ---- stage plumbing -------------------------------------------------------+ // A header action that lands on a control (Attach a track, Set up production)+ // scrolls to and focuses it once its stage has rendered.+ const [pendingAnchor, setPendingAnchor] = useState(null);+ useEffect(() => {+ if (!pendingAnchor || pendingAnchor.stage !== activeStage) return;+ const el = document.getElementById(pendingAnchor.id);+ el?.scrollIntoView?.({ block: 'center', behavior: 'smooth' });+ const focusable = el?.matches?.('button, input, select, textarea, a') ? el : el?.querySelector?.('button, input, select, textarea, a');+ focusable?.focus?.({ preventScroll: true });+ setPendingAnchor(null);+ }, [pendingAnchor, activeStage]);+ const goToStage = (stage, anchor = null) => {+ setPendingAnchor(anchor ? { stage, id: anchor } : null);+ navigate(`/music-video/${encodeURIComponent(selected.id)}/${stage}`);+ };++ // The docked preview: scene cards seek it; on a phone it is a mini-player+ // that starts collapsed. Both reset with the project.+ const [seekRequest, setSeekRequest] = useState(null);+ const [dockCollapsed, setDockCollapsed] = useState(true);+ useEffect(() => { setSeekRequest(null); setDockCollapsed(true); }, [selectedId]);+ const seekToScene = (scene) => {+ if (typeof scene?.startSec !== 'number') return;+ setSeekRequest((prev) => ({ t: scene.startSec, n: (prev?.n || 0) + 1 }));+ };++ const audioFilename = projectAudioFilename(selected);+ const audioUrl = audioFilename ? trackAudioUrl(audioFilename) : null;+ const nextAction = selected ? deriveNextAction(selected, {+ renderActive: renderTargetsSelected,+ renderProgress: renderJob.progress,+ renderPending: renderJob.pending,+ renderBlockedByOther: !!renderJob.active && !renderTargetsSelected,+ kickoffRunning: kickoff.running,+ kickoffStep: kickoff.stepLabel,+ kickoffBlockedReason: autopilotBlockedReason,+ planning,+ analyzing,+ }) : null;+ const runNextAction = () => {+ if (!selected || !nextAction || nextAction.disabled) return;+ if (nextAction.kind === 'goto') { goToStage(nextAction.stage, nextAction.anchor); return; }+ switch (nextAction.id) {+ case 'kickoff': handleKickoff(); break;+ case 'analyze': handleAnalyze(); break;+ case 'plan': handlePlan(); break;+ case 'approve-cast-sets': approveCastAndSets(); break;+ case 'resume-cast-sets': castSets.resume(); break;+ case 'stop-production': production.stop(nextAction.runId); break;+ case 'resume-production': production.resume(nextAction.runId, nextAction.acceptBasis ? { acceptBasis: true } : {}); break;+ case 'render-final': renderJob.start(selected.id); break;+ default: break;+ }+ };++ // Everything the stage panels need, in one place: stages read what they+ // use, so a panel moving between tabs never changes a signature here.+ const board = selected ? {+ project: selected,+ locked: creativeSetupPending,+ busy: { analyzing, planning, arranging, cloning },+ tracks,+ trackName,+ audioFilename,+ audioUrl,+ youtube,+ separation,+ midi,+ midiBound: midiTargetsSelected,+ renderBound: renderTargetsSelected,+ tempo,+ videoSettings,+ sceneMedia,+ renderJob,+ production,+ castSets,+ devArtifacts,+ takes,+ treatment,+ excerpts,+ revisions,+ autoReview,+ finalVideo,+ kickoff,+ conceptDraft,+ styleDraft,+ importingLyrics,+ aligningLyrics,+ autopilotBlockedReason,+ canContinueShot,+ replaceProject,+ editProjectLocal,+ saveProjectFields,+ saveVisualSpec,+ saveAutomation,+ saveCreativeSetup: (patch) => updateMusicVideoProject(selected.id, patch, { silent: true }).then((project) => {+ patchProject(project.id, { concept: project.concept, visualSpec: project.visualSpec });+ }),+ setCreativeSetupPending,+ setPickerTarget,+ onAddReference: () => setPickerTarget({ type: 'reference' }),+ onAnalyze: () => handleAnalyze(),+ onPlan: () => handlePlan(),+ onAutoArrange: handleAutoArrange,+ onKickoff: handleKickoff,+ onChangeTrack: handleChangeTrack,+ onImportLyrics: handleImportLyrics,+ onImportTrackLyrics: handleImportTrackLyrics,+ onAlignLyrics: handleAlignLyrics,+ onAddScene: handleAddScene,+ onDeleteScene: handleDeleteScene,+ onSplitScene: handleSplitScene,+ onRenderStyle: (mode) => {+ const composition = compositionDraft(selected, { mode });+ editProjectLocal({ composition });+ saveProjectFields({ composition });+ },+ onUploadArtifact: (file, fields) => devArtifacts.upload(file, fields).then((res) => {+ if (res?.artifact) openArtifact(res.artifact.id);+ }),+ editSceneLocal,+ saveScene,+ moveScene,+ commitSceneTiming,+ approveCastAndSets,+ skipCastAndSets,+ openArtifact,+ openPreview,+ openContactSheet: () => setContactSheetOpen(true),+ seekToScene,+ } : null;+ const STAGES = {+ setup: SetupStage, 'cast-sets': CastSetsStage, board: BoardStage, produce: ProduceStage, compose: ComposeStage, review: ReviewStage,+ };+ const StageView = STAGES[activeStage];+return (<div className="space-y-4"><MidiInstallModal {...midi.installGate} />@@ -758,6 +899,28 @@ export default function MusicVideo() {</span></span>)}+ {selected && (+ <span className="flex items-center gap-1">+ <button+ type="button"+ onClick={handleClone}+ disabled={cloning}+ title={`Create an editable v${(selected.version || 1) + 1}; keep scene media attached and clear the final render`}+ className="flex min-h-[44px] min-w-[44px] items-center justify-center gap-1 rounded border border-port-border bg-port-bg px-2 py-1.5 text-sm disabled:opacity-50 sm:min-h-0 sm:min-w-0"+ >+ <Copy size={15} aria-hidden="true" /> <span className="max-sm:sr-only">{cloning ? 'Forking…' : `Fork v${(selected.version || 1) + 1}`}</span>+ </button>+ <button+ type="button"+ onClick={() => handleDelete(selected.id)}+ title="Delete project"+ aria-label="Delete project"+ className="flex min-h-[44px] min-w-[44px] items-center justify-center rounded border border-port-border px-2 py-1.5 text-sm text-port-error sm:min-h-0 sm:min-w-0"+ >+ <Trash2 size={15} />+ </button>+ </span>+ )}<buttontype="button"onClick={() => setCreateOpen(true)}@@ -782,7 +945,6 @@ export default function MusicVideo() {submitting={creating}/>-<div>{!selected && !loading && routeProjectId && (<p className="text-sm text-port-text-muted">@@ -803,234 +965,27 @@ export default function MusicVideo() {</div>)}{selected && (- <div className="space-y-3">- <AutomationPanel- key={`automation-${selected.id}`}- project={selected}- onSave={saveAutomation}- onKickoff={handleKickoff}- kickoffBusy={analyzing || planning || kickoff.running}- kickoffStep={kickoff.stepLabel}- kickoffBlockedReason={autopilotBlockedReason}- checkin={(- <CastAndSetsCheckin- project={selected}- busy={castSets.busy || kickoff.running}- onOpenSheet={openArtifact}- onApprove={approveCastAndSets}- onRegenerate={() => castSets.regenerate()}- onResume={() => castSets.resume()}- onSkip={skipCastAndSets}- />- )}- />- <CreativeSetupPanel key={`creative-${selected.id}`} project={selected} onPendingChange={setCreativeSetupPending}- onSave={(patch) => updateMusicVideoProject(selected.id, patch, { silent: true }).then((project) => {- patchProject(project.id, { concept: project.concept, visualSpec: project.visualSpec });- })} />- <DevArtifactsPanel- project={selected}- busy={devArtifacts.busy}- onOpen={openArtifact}- onUpload={(file, fields) => devArtifacts.upload(file, fields).then((res) => {- if (res?.artifact) openArtifact(res.artifact.id);- })}- />- <fieldset disabled={creativeSetupPending} className="space-y-3 min-w-0">- <div className="bg-port-card border border-port-border rounded-lg p-3">- <ProjectToolbar- project={selected}- onRenderStyle={(mode) => {- const composition = compositionDraft(selected, { mode });- editProjectLocal({ composition });- saveProjectFields({ composition });- }}- midi={midi}- midiBound={midiTargetsSelected}- videoSettings={videoSettings}- sceneMedia={sceneMedia}- renderJob={renderJob}- busy={{ analyzing, planning, arranging, cloning }}- onAnalyze={handleAnalyze}- onPlan={() => handlePlan()}- onAutoArrange={handleAutoArrange}- onClone={handleClone}- onDelete={() => handleDelete(selected.id)}- />- {/* Restricted-model license gate for the saved scene-video- renderer. Only mounts while that exact license is still- unaccepted — after download-time acknowledgement it stays- off the board. */}-- {/* Track audio source is first in the edit workspace */}- <TrackPanel- project={selected}- tracks={tracks}- trackName={trackName}- audioFilename={projectAudioFilename(selected)}- youtube={youtube}- renderBound={renderTargetsSelected}- midiBound={midiTargetsSelected}- onChangeTrack={handleChangeTrack}- onProjectUpdated={replaceProject}- separation={separation}- />- <AnalysisPanel- audioAnalysis={selected.audioAnalysis}- scenes={selected.scenes || []}- tempo={tempo}- onReanalyze={handleAnalyze}- analyzing={analyzing}- />- <LyricsPanel- project={selected}- onEditLocal={editProjectLocal}- onSave={saveProjectFields}- onImport={handleImportLyrics}- onImportTrack={handleImportTrackLyrics}- importing={importingLyrics}- onAlign={handleAlignLyrics}- aligning={aligningLyrics}- />-- {/* Concept & style — global direction for the video */}- <div className="mt-2 grid grid-cols-1 sm:grid-cols-2 gap-2">- <div>- <label htmlFor="mv-concept" className="block text-xs text-port-text-muted mb-1">Concept</label>- <AutoSizeTextarea- id="mv-concept"- value={conceptDraft.value}- rows={2}- maxLength={8000}- onChange={conceptDraft.onChange}- onBlur={conceptDraft.onBlur}- placeholder="What is this video about — story, theme, or narrative thread for the AI plan to build on."- className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px]"- />- </div>- <div>- <label htmlFor="mv-style" className="block text-xs text-port-text-muted mb-1">Visual style</label>- <AutoSizeTextarea- id="mv-style"- value={styleDraft.value}- rows={2}- maxLength={2000}- onChange={styleDraft.onChange}- onBlur={styleDraft.onBlur}- placeholder="Art style, references, palette, mood — appended to every generated frame and shot prompt."- className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[44px]"- />- </div>- </div>- <VisualSpecPanel- key={selected.id}- project={selected}- onSave={saveVisualSpec}- onAddReference={() => setPickerTarget({ type: 'reference' })}- />- <TypographyPanel+ <MusicVideoLayout+ project={selected}+ trackLabel={trackName(selected.trackId)}+ stage={activeStage}+ onStageChange={(stage) => goToStage(stage)}+ progress={progress}+ nextAction={nextAction}+ onNextAction={runNextAction}+ spend={projectSpend(selected)}+ dock={resolvePreviewSource(selected) ? (+ <PreviewDockproject={selected}- onEditLocal={editProjectLocal}- onSave={saveProjectFields}+ audioUrl={audioUrl}+ seekRequest={seekRequest}+ collapsed={dockCollapsed}+ onToggleCollapsed={() => setDockCollapsed((c) => !c)}/>- <TreatmentPanel key={`treatment-${selected.id}`} project={selected} treatment={treatment} />- {selected.composition?.mode === 'code' && (- <CodeVideoPanel- project={selected}- audioUrl={projectAudioFilename(selected) ? trackAudioUrl(projectAudioFilename(selected)) : null}- onProject={replaceProject}- />- )}- {selected.composition?.mode === 'document' && (- <DocumentCompositionPanel- key={`document-${selected.id}`}- project={selected}- audioUrl={projectAudioFilename(selected) ? trackAudioUrl(projectAudioFilename(selected)) : null}- onProject={replaceProject}- onSave={saveProjectFields}- />- )}- <RenderStatusPanel- rendering={renderTargetsSelected}- progress={renderJob.progress}- renderHistoryId={selected.renderHistoryId}- finalVideo={finalVideo}- onOpenPreview={openPreview}- />- <ProductionPanel project={selected} production={production} />- <ExcerptPanel- project={selected}- rendering={excerpts.rendering}- progress={excerpts.progress}- excerpts={selected.excerpts || []}- deletingId={excerpts.deletingId}- noteBusyId={excerpts.noteBusyId}- startExcerpt={excerpts.startExcerpt}- cancelExcerpt={excerpts.cancelExcerpt}- deleteExcerpt={excerpts.deleteExcerpt}- addNote={excerpts.addNote}- editNote={excerpts.editNote}- deleteNote={excerpts.deleteNote}- revision={{ ...revisions, genScenes: sceneMedia.genScenes, genVideoScenes: sceneMedia.genVideoScenes }}- autoReview={autoReview}- />- <HandoffControls- projectId={selected.id}- busy={takes.busy}- onExport={takes.exportHandoff}- onExportBundle={takes.exportHandoffBundle}- onImport={takes.importHandoffFiles}- onOpenContactSheet={() => setContactSheetOpen(true)}- />- </div>-- {selected.audioAnalysis && (selected.scenes || []).length > 0 && (- <BeatTimeline audioAnalysis={selected.audioAnalysis} scenes={selected.scenes} lyricCues={selected.lyricCues} onCommit={commitSceneTiming} />- )}-- <div className="flex items-center justify-between">- <h3 className="text-sm font-medium">Scene board</h3>- <button onClick={handleAddScene} className="flex items-center gap-1 bg-port-accent text-white rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0">- <Plus size={15} /> Add scene- </button>- </div>-- {(selected.scenes || []).length === 0 && <p className="text-sm text-port-text-muted">No scenes yet — add one to start the board.</p>}- <div className="grid grid-cols-1 xl:grid-cols-2 gap-3">- {(selected.scenes || []).map((scene, idx) => (- <SceneCard- key={scene.sceneId}- scene={scene}- index={idx}- isLast={idx === selected.scenes.length - 1}- generatingFrame={sceneMedia.genScenes[scene.sceneId]}- generatingVideo={sceneMedia.genVideoScenes[scene.sceneId]}- settingsSaving={videoSettings.saving}- videoBlockedReason={videoSettings.videoBlockedReason}- lipSyncBackend={videoSettings.audioReactiveSelected ? 'local' : videoSettings.settings.backend}- songDurationSec={selected.audioAnalysis?.durationSec ?? null}- falVideoSettings={videoSettings.settings}- canContinueShot={canContinueShot}- onMove={moveScene}- onDelete={handleDeleteScene}- onSplit={handleSplitScene}- onEditLocal={editSceneLocal}- onSave={saveScene}- onGenerateFrame={sceneMedia.generateFrame}- onGenerateVideo={sceneMedia.generateSceneVideo}- onContinueVideo={sceneMedia.continueSceneVideo}- onOpenPreview={openPreview}- takeBusy={takes.busy}- onSelectTake={takes.selectTake}- onReviewTake={takes.reviewTake}- onImportTake={(target) => setPickerTarget({ type: 'take', sceneId: target.sceneId })}- onImportClipTake={(target) => setPickerTarget({ type: 'clip', sceneId: target.sceneId })}- layered={selected.composition?.mode === 'composed'}- />- ))}- </div>- </fieldset>- </div>+ ) : null}+ >+ <StageView board={board} />+ </MusicVideoLayout>)}</div></div>diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex 7f28e3228a..20f3d497b2 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -100,6 +100,18 @@ vi.mock('../services/apiMusicVideo.js', () => ({resolveMusicVideoDevArtifactNote: vi.fn(),reviewMusicVideoDevArtifact: vi.fn(),deleteMusicVideoDevArtifact: vi.fn(),+ getMusicVideoCompositionPreview: vi.fn(async () => ({ html: '<!doctype html><p>preview</p>', assets: [], width: 1920, height: 1080, fps: 24, durationSec: 60 })),+ getMusicVideoCompositionDocument: vi.fn(),+ fetchMusicVideoPreviewAsset: vi.fn(),+ startMusicVideoCompositionTemplate: vi.fn(),+ importMusicVideoCompositionZip: vi.fn(),+ importMusicVideoCompositionDirectory: vi.fn(),+ getMusicVideoCompositionExport: vi.fn(),+ detachMusicVideoCompositionDocument: vi.fn(),+ startMusicVideoProduction: vi.fn(),+ resumeMusicVideoProduction: vi.fn(),+ stopMusicVideoProduction: vi.fn(),+ cancelMusicVideoProduction: vi.fn(),}));// Server pushes (production runs, the Cast & Sets check-in) arrive over the// socket; tests deliver them through this registry.@@ -201,7 +213,7 @@ import {renderMusicVideoExcerpt, deleteMusicVideoExcerpt, addMusicVideoExcerptNote,updateMusicVideoExcerptNote, deleteMusicVideoExcerptNote, getMusicVideoProject,startMusicVideoRevision, resumeMusicVideoRevision, cancelMusicVideoRevision,- startMusicVideoCastAndSets, approveMusicVideoCastAndSets,+ startMusicVideoCastAndSets, approveMusicVideoCastAndSets, stopMusicVideoProduction,} from '../services/apiMusicVideo.js';import { generateImage, uploadGalleryImage } from '../services/apiSystem.js';import { importTrackFromYoutube, trackImportEventsUrl, listTracks } from '../services/apiTracks.js';@@ -232,13 +244,17 @@ const PROJECT_ANALYZED = {// clicking a project navigates to its id'd URL, and the component re-reads// useParams() to open its board (no remount: both routes render the same// component type, so React preserves the instance across the param change).+const MV_ROUTES = (+ <Routes>+ <Route path="/music-video" element={<MusicVideo />} />+ <Route path="/music-video/:projectId" element={<MusicVideo />} />+ <Route path="/music-video/:projectId/:stage" element={<MusicVideo />} />+ <Route path="/music-video/:projectId/dev/:artifactId" element={<MusicVideo />} />+ <Route path="/music-video/:projectId/:stage/dev/:artifactId" element={<MusicVideo />} />+ </Routes>+);const renderMV = () => render(- <MemoryRouter initialEntries={['/music-video']}>- <Routes>- <Route path="/music-video" element={<MusicVideo />} />- <Route path="/music-video/:projectId" element={<MusicVideo />} />- </Routes>- </MemoryRouter>,+ <MemoryRouter initialEntries={['/music-video']}>{MV_ROUTES}</MemoryRouter>,);// Flush pending pre-resolved mock promises inside act so their .then setState@@ -263,11 +279,23 @@ const selectProject = async (projectId) => {return picker;};-const openProject = async (project) => {+// The page is a set of stage tabs (deep-linked as /music-video/:id/:stage); a+// control is only on screen while its stage is open, so tests say which one.+const STAGE_TABS = {+ setup: /^Setup/, 'cast-sets': /^Cast & Sets/, board: /^Board/, produce: /^Produce/, compose: /^Compose/, review: /^Review/,+};+const openStage = async (stage) => {+ const tab = await screen.findByRole('tab', { name: STAGE_TABS[stage] });+ fireEvent.click(tab);+ await waitFor(() => expect(screen.getByRole('tab', { name: STAGE_TABS[stage] })).toHaveAttribute('aria-selected', 'true'));+};++const openProject = async (project, stage = null) => {listMusicVideoProjects.mockResolvedValue([project]);renderMV();await selectProject(project.id);await screen.findByRole('heading', { level: 2, name: project.name });+ if (stage) await openStage(stage);};const openCreateForm = async () => {@@ -289,10 +317,7 @@ const renderMVWithNav = (to) => render(<MemoryRouter initialEntries={['/music-video']}><LocationProbe /><NavTo to={to} />- <Routes>- <Route path="/music-video" element={<MusicVideo />} />- <Route path="/music-video/:projectId" element={<MusicVideo />} />- </Routes>+ {MV_ROUTES}</MemoryRouter>,);@@ -308,7 +333,7 @@ beforeEach(() => {describe('MusicVideo render control (#1760)', () => {it('enables Render and kicks off the job when a scene has a clip', async () => {- await openProject(PROJECT_WITH_CLIP);+ await openProject(PROJECT_WITH_CLIP, 'review');const renderBtn = await screen.findByRole('button', { name: /^Render final$/ });expect(renderBtn).toHaveProperty('disabled', false);@@ -323,37 +348,48 @@ describe('MusicVideo render control (#1760)', () => {renderMusicVideoProject.mockImplementationOnce(() => new Promise((resolve) => { resolveKickoff = resolve; }));renderMV();await selectProject(PROJECT_WITH_CLIP.id);+ await openStage('review');fireEvent.click(screen.getByRole('button', { name: /^Render final$/ }));expect(screen.getByRole('button', { name: 'Preparing render…' })).toBeDisabled();+ await openStage('setup');expect(screen.getByLabelText('Change track')).toBeDisabled();fireEvent.change(screen.getByLabelText('Change track'), { target: { value: 'other-track' } });expect(updateMusicVideoProject).not.toHaveBeenCalled();await selectProject(other.id);+ await openStage('review');const otherRender = screen.getByRole('button', { name: 'Rendering another project…' });expect(otherRender).toBeDisabled();fireEvent.click(otherRender);expect(renderMusicVideoProject).toHaveBeenCalledTimes(1);- expect(screen.getByLabelText('Change track')).not.toBeDisabled();expect(screen.queryByTitle('Cancel render')).not.toBeInTheDocument();+ await openStage('setup');+ expect(screen.getByLabelText('Change track')).not.toBeDisabled();await act(async () => { resolveKickoff({ jobId: 'render-first' }); });sseState.latest = { type: 'progress', progress: 0.375 };await selectProject(PROJECT_WITH_CLIP.id);+ await openStage('review');expect(screen.getByTitle('Cancel render')).toHaveTextContent('38%');+ // The header offers no second render while this one is in flight — it shows the progress.+ expect(screen.getByRole('button', { name: 'Rendering… 38%' })).toBeDisabled();+ await openStage('setup');expect(screen.getByLabelText('Change track')).toBeDisabled();// A metadata frame omits progress; the final-render adapter keeps 38%.sseState.latest = { type: 'status', message: 'Finishing output' };fireEvent.click(screen.getByRole('button', { name: /New project/i }));+ await openStage('review');expect(screen.getByTitle('Cancel render')).toHaveTextContent('38%');await selectProject(other.id);sseState.latest = { type: 'complete', result: { id: 'rh-9' } };fireEvent.change(screen.getByPlaceholderText('Project name'), { target: { value: 'Unrelated draft' } });await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Music video rendered'));+ await openStage('review');expect(screen.queryByText(/Open in Media History/i)).not.toBeInTheDocument();await selectProject(PROJECT_WITH_CLIP.id);+ await openStage('review');expect(screen.getByText(/Open in Media History/i).closest('a')).toHaveAttribute('href', expect.stringContaining('preview=video%3Arh-9'));});@@ -361,11 +397,13 @@ describe('MusicVideo render control (#1760)', () => {renderMusicVideoProject.mockRejectedValueOnce(Object.assign(new Error('Render is still preparing'), { status: 409, context: { jobId: null } })).mockRejectedValueOnce(Object.assign(new Error('Render already exists'), { status: 409, context: { jobId: 'existing-render' } }));- await openProject(PROJECT_WITH_CLIP);+ await openProject(PROJECT_WITH_CLIP, 'review');fireEvent.click(screen.getByRole('button', { name: /^Render final$/ }));await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Render is still preparing'));expect(screen.getByRole('button', { name: /^Render final$/ })).toBeEnabled();+ await openStage('setup');expect(screen.getByLabelText('Change track')).toBeEnabled();+ await openStage('review');fireEvent.click(screen.getByRole('button', { name: /^Render final$/ }));fireEvent.click(await screen.findByTitle('Cancel render'));@@ -382,9 +420,11 @@ describe('MusicVideo render control (#1760)', () => {listMusicVideoProjects.mockResolvedValue([PROJECT_WITH_CLIP, other]);renderMV();await selectProject(PROJECT_WITH_CLIP.id);+ await openStage('review');fireEvent.click(screen.getByRole('button', { name: /^Render final$/ }));await screen.findByTitle('Cancel render');await selectProject(other.id);+ await openStage('review');sseState.latest = { type: 'error', error: 'Renderer stopped' };fireEvent.click(screen.getByRole('button', { name: /New project/i }));expect(toast.error).toHaveBeenCalledWith('Renderer stopped');@@ -403,13 +443,13 @@ describe('MusicVideo render control (#1760)', () => {});it('disables Render when no scene has a generated clip', async () => {- await openProject(PROJECT_NO_CLIP);+ await openProject(PROJECT_NO_CLIP, 'review');const renderBtn = await screen.findByRole('button', { name: /^Render final$/ });expect(renderBtn).toHaveProperty('disabled', true);});it('shows the rendered-video link once a project carries a renderHistoryId', async () => {- await openProject({ ...PROJECT_WITH_CLIP, renderHistoryId: 'rh-9' });+ await openProject({ ...PROJECT_WITH_CLIP, renderHistoryId: 'rh-9' }, 'review');await screen.findByText(/Download MP4/i);const link = await screen.findByText(/Open in Media History/i);// Media History matches video items by their `video:<id>` key via ?preview=.@@ -419,7 +459,7 @@ describe('MusicVideo render control (#1760)', () => {describe('MusicVideo draft excerpt render (#8986)', () => {it('kicks off an excerpt render with the typed range and shows progress', async () => {- await openProject(PROJECT_WITH_CLIP);+ await openProject(PROJECT_WITH_CLIP, 'review');fireEvent.change(screen.getByLabelText('Start (sec)'), { target: { value: '10' } });fireEvent.change(screen.getByLabelText('End (sec)'), { target: { value: '20' } });fireEvent.click(screen.getByRole('button', { name: /Render excerpt/i }));@@ -444,7 +484,7 @@ describe('MusicVideo draft excerpt render (#8986)', () => {notes: [{ id: 'mvn-1', atSec: 3, note: 'lip-sync drifts here', verdict: null }],}],});- await openProject(PROJECT_WITH_CLIP);+ await openProject(PROJECT_WITH_CLIP, 'review');fireEvent.click(screen.getByRole('button', { name: /Render excerpt/i }));await waitFor(() => expect(renderMusicVideoExcerpt).toHaveBeenCalled());await settle();@@ -469,7 +509,7 @@ describe('MusicVideo draft excerpt render (#8986)', () => {project: { ...project, excerpts: [{ ...project.excerpts[0], notes: [{ id: 'mvn-1', atSec: 0, note: 'looks great', verdict: null }] }] },note: { id: 'mvn-1', atSec: 0, note: 'looks great', verdict: null },});- await openProject(project);+ await openProject(project, 'review');fireEvent.change(screen.getByLabelText('New review note'), { target: { value: 'looks great' } });fireEvent.click(screen.getByRole('button', { name: 'Add' }));@@ -495,7 +535,7 @@ describe('MusicVideo draft excerpt render (#8986)', () => {excerpts: [{ id: 'mve-1', startSec: 10, endSec: 20, status: 'complete', filename: 'excerpt-1.mp4', contactSheetFilename: null, error: null, notes: [] }],};deleteMusicVideoExcerpt.mockResolvedValue({ ...project, excerpts: [] });- await openProject(project);+ await openProject(project, 'review');fireEvent.click(screen.getByRole('button', { name: /^Delete$/ }));await waitFor(() => expect(deleteMusicVideoExcerpt).toHaveBeenCalledWith('mv-1', 'mve-1', { silent: true }));await waitFor(() => expect(screen.queryByLabelText(/Play excerpt/i)).not.toBeInTheDocument());@@ -534,7 +574,7 @@ describe('MusicVideo selective section revision (#8987)', () => {startMusicVideoRevision.mockResolvedValue({ project: opened, revision: opened.revisions[0], skippedSceneIds: [] });resumeMusicVideoRevision.mockResolvedValue({ project: opened, revision: opened.revisions[0], needsGeneration: [{ sceneId: 's2', kind: 'video' }], generating: [], render: null });generateVideo.mockResolvedValue({ jobId: 'video-job-s2' });- await openProject(REVIEWED);+ await openProject(REVIEWED, 'review');fireEvent.click(await findEnabledByRole('button', { name: /Revise flagged/i }));await waitFor(() => expect(resumeMusicVideoRevision).toHaveBeenCalledWith('mv-1', 'mvr-1', { silent: true }));@@ -551,7 +591,7 @@ describe('MusicVideo selective section revision (#8987)', () => {project: { ...ready, revisions: [{ ...ready.revisions[0], status: 'rendering', renderExcerptId: 'mve-2' }] },revision: { ...ready.revisions[0], status: 'rendering' }, needsGeneration: [], generating: [], render: { jobId: 'mve-2', excerptId: 'mve-2' },});- await openProject(ready);+ await openProject(ready, 'review');fireEvent.click(await findEnabledByRole('button', { name: /Render revised draft/i }));await waitFor(() => expect(resumeMusicVideoRevision).toHaveBeenCalledWith('mv-1', 'mvr-1', { silent: true }));@@ -563,7 +603,7 @@ describe('MusicVideo selective section revision (#8987)', () => {it('cancels an open revision', async () => {const open = withRevision(null);cancelMusicVideoRevision.mockResolvedValue({ project: { ...open, revisions: [{ ...open.revisions[0], status: 'canceled' }] }, revision: { ...open.revisions[0], status: 'canceled' } });- await openProject(open);+ await openProject(open, 'review');fireEvent.click(await findEnabledByRole('button', { name: /Cancel revision/i }));await waitFor(() => expect(cancelMusicVideoRevision).toHaveBeenCalledWith('mv-1', 'mvr-1', { silent: true }));await screen.findByText(/Revision — Cancelled/);@@ -577,9 +617,10 @@ describe('MusicVideo project video renderer', () => {await openProject({...PROJECT_NO_CLIP,videoSettings: { modelId: 'ltx23_distilled_q4' },- });+ }, 'produce');expect(await screen.findByLabelText('Scene video renderer')).toHaveProperty('value', '');+ await openStage('board');fireEvent.click(screen.getByRole('button', { name: /^Generate video$/ }));await waitFor(() => expect(generateVideo).toHaveBeenCalled());expect(generateVideo.mock.calls.at(-1)[0]).not.toHaveProperty('backend');@@ -587,7 +628,7 @@ describe('MusicVideo project video renderer', () => {});it('clears an existing backend pin with the Install default option', async () => {- await openProject(PROJECT_NO_CLIP);+ await openProject(PROJECT_NO_CLIP, 'produce');fireEvent.change(await screen.findByLabelText('Scene video renderer'), {target: { value: '' },@@ -602,7 +643,7 @@ describe('MusicVideo project video renderer', () => {it('persists the local model and uses it for scene generation', async () => {generateVideo.mockResolvedValue({ jobId: 'video-job-1' });- await openProject(PROJECT_NO_CLIP);+ await openProject(PROJECT_NO_CLIP, 'produce');const model = await screen.findByLabelText('Local video model');fireEvent.change(model, { target: { value: 'ltx23_distilled_q4' } });@@ -612,6 +653,7 @@ describe('MusicVideo project video renderer', () => {{ silent: true },));+ await openStage('board');fireEvent.click(screen.getByRole('button', { name: /^Generate video$/ }));await waitFor(() => expect(generateVideo).toHaveBeenCalledWith(expect.objectContaining({backend: 'local',@@ -623,7 +665,7 @@ describe('MusicVideo project video renderer', () => {it('continues an existing scene through the local model native extend mode', async () => {generateVideo.mockResolvedValue({ jobId: 'video-job-2' });- await openProject(PROJECT_WITH_CLIP);+ await openProject(PROJECT_WITH_CLIP, 'board');fireEvent.click(await screen.findByRole('button', { name: /^Continue shot$/ }));@@ -639,7 +681,7 @@ describe('MusicVideo project video renderer', () => {it('uses project audio as no-vocals conditioning at the scene song offset', async () => {generateVideo.mockResolvedValue({ jobId: 'audio-reactive-job' });- await openProject(PROJECT_NO_CLIP);+ await openProject(PROJECT_NO_CLIP, 'produce');fireEvent.change(await screen.findByLabelText('Scene generation mode'), {target: { value: 'audioReactive' },@@ -656,6 +698,7 @@ describe('MusicVideo project video renderer', () => {{ silent: true },));+ await openStage('board');fireEvent.click(screen.getByRole('button', { name: /^Generate video$/ }));await waitFor(() => expect(generateVideo).toHaveBeenCalledWith(expect.objectContaining({backend: 'local',@@ -680,7 +723,7 @@ describe('MusicVideo project video renderer', () => {audioReactiveLora: 'audio-reactive-v2.safetensors',audioReactiveScale: 1.2,},- });+ }, 'produce');const lora = await screen.findByLabelText('Audio reactive LoRA');expect(lora.value).toBe('audio-reactive-v2.safetensors');@@ -700,7 +743,7 @@ describe('MusicVideo project video renderer', () => {falEnabled: true,models: [{ id: 'ltx23_distilled_q4', name: 'LTX-2.3 Distilled Q4', runtime: 'ltx2' }],});- await openProject(PROJECT_NO_CLIP);+ await openProject(PROJECT_NO_CLIP, 'produce');fireEvent.change(await screen.findByLabelText('Scene video renderer'), {target: { value: 'fal' },@@ -724,9 +767,10 @@ describe('MusicVideo project video renderer', () => {await openProject({...PROJECT_NO_CLIP,videoSettings: { backend: 'fal', falDuration: 6 },- });+ }, 'produce');expect(await screen.findByLabelText('fal.ai scene clip duration')).toHaveProperty('value', '6');+ await openStage('board');// No model pin: the default Hailuo-02 image-to-video take, priced before it is paid for.expect((await screen.findByTestId('fal-cutaway-plan')).textContent).toContain('est. $0.27 (6s at 768P)');fireEvent.click(await findEnabledByRole('button', { name: /^Generate video$/ }));@@ -749,7 +793,7 @@ describe('MusicVideo project video renderer', () => {...PROJECT_NO_CLIP,videoSettings: { backend: 'fal', falModelId: 'minimax/h3-max/image-to-video', falResolution: '1080P' },scenes: [{ ...PROJECT_NO_CLIP.scenes[0], startSec: 0, endSec: 7.2 }],- });+ }, 'board');// A 7.2s shot on H3 Max (5–15s whole seconds) renders 8s at $0.16/s.expect((await screen.findByTestId('fal-cutaway-plan')).textContent).toContain('est. $1.28 (8s at 1080P)');@@ -759,6 +803,7 @@ describe('MusicVideo project video renderer', () => {})));// Switching model clears the resolution pin — its alphabet is per model.+ await openStage('produce');fireEvent.change(await screen.findByLabelText('fal.ai cutaway model'), {target: { value: 'fal-ai/kling-video/v3/pro/image-to-video' },});@@ -772,7 +817,7 @@ describe('MusicVideo project video renderer', () => {it('blocks fal.ai scene generation with a clear preflight reason when no API key is configured', async () => {// getVideoGenStatus's default mock omits falEnabled, so it resolves false —// exactly the "no fal.ai API key configured" install this covers.- await openProject({ ...PROJECT_NO_CLIP, videoSettings: { backend: 'fal' } });+ await openProject({ ...PROJECT_NO_CLIP, videoSettings: { backend: 'fal' } }, 'board');const generate = await screen.findByRole('button', { name: /^Generate video$/ });expect(generate).toBeDisabled();@@ -794,9 +839,10 @@ describe('MusicVideo project video renderer', () => {});it('labels Grok cutaway-only and blocks a performance shot on it without calling the provider', async () => {- await openProject(performanceProject({ backend: 'grok', grokDuration: 6 }));+ await openProject(performanceProject({ backend: 'grok', grokDuration: 6 }), 'produce');expect(await screen.findByRole('option', { name: 'Grok video (cutaway only)' })).toBeTruthy();+ await openStage('board');expect(await screen.findByText(/Grok video is cutaway-only/)).toBeTruthy();const generate = await screen.findByRole('button', { name: /^Generate video$/ });expect(generate).toBeDisabled();@@ -810,7 +856,7 @@ describe('MusicVideo project video renderer', () => {models: [{ id: 'ltx23_distilled_q4', name: 'LTX-2.3 Distilled Q4', runtime: 'ltx2' }],});generateVideo.mockResolvedValue({ jobId: 'fal-lipsync-job' });- await openProject(performanceProject({ backend: 'fal', falDuration: 6 }));+ await openProject(performanceProject({ backend: 'fal', falDuration: 6 }), 'board');const plan = await screen.findByTestId('performance-plan');expect(plan.textContent).toContain('minimax/h3-max/lip-sync/image-to-video');@@ -827,7 +873,7 @@ describe('MusicVideo project video renderer', () => {it('persists a scene switched to a performance shot', async () => {updateMusicVideoScene.mockResolvedValue({ ...PROJECT_NO_CLIP.scenes[0], shotMode: 'performance' });- await openProject(PROJECT_NO_CLIP);+ await openProject(PROJECT_NO_CLIP, 'board');fireEvent.change(await screen.findByLabelText('Shot'), { target: { value: 'performance' } });await waitFor(() => expect(updateMusicVideoScene).toHaveBeenCalledWith(@@ -845,7 +891,7 @@ describe('MusicVideo project video renderer', () => {{ ...longShot, sceneId: 's1b', order: 1, label: 'Verse · 2/2', startSec: 21, videoHistoryId: null },];splitMusicVideoScene.mockResolvedValue({ project: { ...project, scenes: pieces }, scenes: pieces });- await openProject(project);+ await openProject(project, 'board');// The too-long refusal stays, now with a way out that never loops or stretches.expect(await screen.findByText(/Split the scene on a lyric or phrase boundary/)).toBeTruthy();@@ -862,7 +908,7 @@ describe('MusicVideo project video renderer', () => {videoSettings: { backend: 'grok', grokDuration: 6 },phrases: [{ id: 'p1', startSec: 12, endSec: 15, intent: 'camera pushes in' }],scenes: [{ ...PROJECT_NO_CLIP.scenes[0], startSec: 10, endSec: 17.2 }],- });+ }, 'board');expect(await screen.findByText(/Grok renders a 10s clip for this 7\.2s cutaway/)).toBeTruthy();fireEvent.click(await findEnabledByRole('button', { name: /^Generate video$/ }));@@ -880,7 +926,7 @@ describe('MusicVideo project video renderer', () => {PROJECT_WITH_CLIP.scenes[0],{ ...PROJECT_WITH_CLIP.scenes[0], sceneId: 's2', order: 1 },],- });+ }, 'produce');expect(await screen.findByText('Repetition: 1 unique frames · 1 unique clips')).toBeTruthy();});@@ -905,7 +951,7 @@ describe('MusicVideo restricted-model license gate', () => {models: [{ id: 'gated_model', name: 'Gated Model', runtime: 'ltx2', termsGate: GATE }],});generateVideo.mockResolvedValue({ jobId: 'gated-job' });- await openProject(PROJECT_NO_CLIP);+ await openProject(PROJECT_NO_CLIP, 'board');const generate = await findEnabledByRole('button', { name: /^Generate video$/ });expect(screen.queryByRole('checkbox', { name: /I am eligible/ })).toBeNull();@@ -937,7 +983,7 @@ describe('MusicVideo project versions', () => {describe('MusicVideo audio preview + download', () => {it('shows preview player + download link for a linked track', async () => {listTracks.mockResolvedValue([{ id: 't1', title: 'Neon Song', audioFilename: 'neon song.mp3' }]);- await openProject(PROJECT_WITH_CLIP);+ await openProject(PROJECT_WITH_CLIP, 'setup');const player = await screen.findByLabelText('Preview track audio');expect(player.getAttribute('src')).toBe('/data/music/neon%20song.mp3');const dl = screen.getByRole('link', { name: /Download audio/i });@@ -950,20 +996,20 @@ describe('MusicVideo audio preview + download', () => {id: 't1', title: 'Neon Song', audioFilename: 'neon.mp3',renders: [{ id: 'r-old', audioFilename: 'old.wav', source: '' }, { id: 'r-1', audioFilename: 'neon.mp3', source: 'suno' }],}]);- await openProject(PROJECT_WITH_CLIP);+ await openProject(PROJECT_WITH_CLIP, 'setup');expect(await screen.findByTitle('Audio imported from Suno')).toHaveTextContent('Suno');});it('falls back to the project uploaded-audio file when there is no linked track', async () => {- await openProject({ ...PROJECT_WITH_CLIP, trackId: null, uploadedAudioFilename: 'upload.wav' });+ await openProject({ ...PROJECT_WITH_CLIP, trackId: null, uploadedAudioFilename: 'upload.wav' }, 'setup');const player = await screen.findByLabelText('Preview track audio');expect(player.getAttribute('src')).toBe('/data/music/upload.wav');});it('renders no audio controls when the project has no audio', async () => {- await openProject({ ...PROJECT_WITH_CLIP, trackId: null, uploadedAudioFilename: null });- // Board opened (Render button present) but no audio surface.- await screen.findByRole('button', { name: /^Render final$/ });+ await openProject({ ...PROJECT_WITH_CLIP, trackId: null, uploadedAudioFilename: null }, 'setup');+ // Setup opened (the track picker is present) but no audio surface.+ await screen.findByLabelText('Change track');expect(screen.queryByLabelText('Preview track audio')).toBeNull();expect(screen.queryByRole('link', { name: /Download audio/i })).toBeNull();});@@ -971,7 +1017,7 @@ describe('MusicVideo audio preview + download', () => {describe('MusicVideo musical timeline', () => {it('renders waveform, beat evidence, legend, and the detected rhythmic window', async () => {- await openProject(PROJECT_ANALYZED);+ await openProject(PROJECT_ANALYZED, 'board');expect(screen.getByRole('img', { name: /audio waveform overview with 4 beats and 1 downbeats/i })).toBeTruthy();expect(screen.getByText(/waveform, sections, and 4\/4 beat-grid assumption/i)).toBeTruthy();expect(screen.getByText(/detected near 0:40\.00–1:10\.00/i)).toBeTruthy();@@ -981,13 +1027,13 @@ describe('MusicVideo musical timeline', () => {describe('MusicVideo audio → MIDI transcription (MuScriptor)', () => {it('disables the MIDI button when the project has no audio source', async () => {- await openProject({ ...PROJECT_WITH_CLIP, trackId: null, uploadedAudioFilename: null });+ await openProject({ ...PROJECT_WITH_CLIP, trackId: null, uploadedAudioFilename: null }, 'setup');const btn = await screen.findByRole('button', { name: /^MIDI$/ });expect(btn).toHaveProperty('disabled', true);});it('kicks off a transcription for the selected project with the default model', async () => {- await openProject(PROJECT_WITH_CLIP);+ await openProject(PROJECT_WITH_CLIP, 'setup');const btn = await screen.findByRole('button', { name: /^MIDI$/ });expect(btn).toHaveProperty('disabled', false);fireEvent.click(btn);@@ -995,7 +1041,7 @@ describe('MusicVideo audio → MIDI transcription (MuScriptor)', () => {});it('kicks off a transcription with the chosen model size', async () => {- await openProject(PROJECT_WITH_CLIP);+ await openProject(PROJECT_WITH_CLIP, 'setup');fireEvent.change(await screen.findByLabelText('MuScriptor model size'), { target: { value: 'large' } });fireEvent.click(await screen.findByRole('button', { name: /^MIDI$/ }));await waitFor(() => expect(transcribeMusicVideoMidi).toHaveBeenCalledWith('mv-1', { model: 'large' }, { silent: true }));@@ -1003,7 +1049,7 @@ describe('MusicVideo audio → MIDI transcription (MuScriptor)', () => {it('shows the MIDI download link once the project carries a transcription pointer', async () => {listTracks.mockResolvedValue([{ id: 't1', title: 'Neon Song', audioFilename: 'neon.mp3' }]);- await openProject({ ...PROJECT_WITH_CLIP, midiTranscription: { filename: 'neon-midi.mid', model: 'medium' } });+ await openProject({ ...PROJECT_WITH_CLIP, midiTranscription: { filename: 'neon-midi.mid', model: 'medium' } }, 'setup');// Two links now: the download button and the MidiVisualization panel's// download icon (#2477) — both serve from the music dir (same static route// as the master audio) so the federated .mid resolves on peers too.@@ -1015,7 +1061,7 @@ describe('MusicVideo audio → MIDI transcription (MuScriptor)', () => {describe('MusicVideo autonomous shot planner (#1855)', () => {it('disables AI Plan until the track is analyzed', async () => {- await openProject(PROJECT_NO_CLIP);+ await openProject(PROJECT_NO_CLIP, 'board');const planBtn = await screen.findByRole('button', { name: /AI Plan/i });expect(planBtn).toHaveProperty('disabled', true);});@@ -1024,7 +1070,7 @@ describe('MusicVideo autonomous shot planner (#1855)', () => {const plannedProject = { ...PROJECT_ANALYZED, scenes: [{ sceneId: 's1', order: 0, prompt: 'p' }] };planMusicVideoProject.mockResolvedValue({ project: plannedProject, scenesAdded: 1, promptsSeeded: false, promptsSkippedReason: 'no-provider' });- await openProject(PROJECT_ANALYZED);+ await openProject(PROJECT_ANALYZED, 'board');const planBtn = await screen.findByRole('button', { name: /AI Plan/i });expect(planBtn).toHaveProperty('disabled', false);@@ -1040,7 +1086,7 @@ describe('MusicVideo lyrics and shot coverage (#8964)', () => {{ id: 'lc-2', text: 'second line', startSec: 3, endSec: null },];importMusicVideoLyrics.mockResolvedValue({ project: { ...PROJECT_ANALYZED, lyricCues: cues }, imported: 2, format: 'lrc' });- await openProject(PROJECT_ANALYZED);+ await openProject(PROJECT_ANALYZED, 'setup');fireEvent.change(screen.getByLabelText('Lyrics to import'), { target: { value: '[00:01.00]first line\n[00:03.00]second line' } });fireEvent.click(screen.getByRole('button', { name: /^Import lyrics$/ }));@@ -1071,7 +1117,7 @@ describe('MusicVideo lyrics and shot coverage (#8964)', () => {{ w: 'home', startSec: 1, endSec: 1.5, conf: 'interpolated' },],}];- await openProject({ ...PROJECT_ANALYZED, lyricCues: [{ id: 'lc-1', text: 'walking home', startSec: null, endSec: null }] });+ await openProject({ ...PROJECT_ANALYZED, lyricCues: [{ id: 'lc-1', text: 'walking home', startSec: null, endSec: null }] }, 'setup');expect(alignMusicVideoLyrics).not.toHaveBeenCalled();alignMusicVideoLyrics.mockResolvedValue({ id: 'mv-3', lyricCues: cues, updatedAt: 't' });fireEvent.click(screen.getByRole('button', { name: 'Align words' }));@@ -1091,8 +1137,9 @@ describe('MusicVideo lyrics and shot coverage (#8964)', () => {],};updateMusicVideoScene.mockResolvedValue({});- await openProject(project);- expect(screen.getByText(/first line/)).toBeTruthy();+ await openProject(project, 'board');+ // The card's summary row and its editor both quote the lyric.+ expect(screen.getAllByText(/first line/).length).toBeGreaterThan(0);const players = document.body.querySelectorAll('video[src^="/data/videos/h"]');expect(players).toHaveLength(2);@@ -1117,7 +1164,7 @@ describe('MusicVideo typography composition (#8984)', () => {{ id: 'lc-2', text: 'untimed line', startSec: null, endSec: null },];updateMusicVideoProject.mockResolvedValue({});- await openProject({ ...PROJECT_ANALYZED, lyricCues });+ await openProject({ ...PROJECT_ANALYZED, lyricCues }, 'compose');fireEvent.click(screen.getByRole('button', { name: /Copy timed lyrics \(1\)/ }));const text = await screen.findByLabelText('Text cue 1 text');@@ -1149,10 +1196,11 @@ describe('MusicVideo section layers (#8985)', () => {it('makes a footage-less scene a title card so a composed project can render', async () => {updateMusicVideoScene.mockResolvedValue({});- await openProject({ ...PROJECT_WITH_CLIP, scenes, composition: composition('composed') });+ await openProject({ ...PROJECT_WITH_CLIP, scenes, composition: composition('composed') }, 'review');const renderBtn = await screen.findByRole('button', { name: /^Render final$/ });expect(renderBtn).toBeDisabled();+ await openStage('board');const layer = document.getElementById('mv-scene-s2-layer');fireEvent.change(layer, { target: { value: 'card' } });await waitFor(() => expect(updateMusicVideoScene).toHaveBeenCalledWith('mv-1', 's2', { visualLayer: 'card' }, { silent: true }));@@ -1161,13 +1209,16 @@ describe('MusicVideo section layers (#8985)', () => {fireEvent.blur(cardText);await waitFor(() => expect(updateMusicVideoScene).toHaveBeenCalledWith('mv-1', 's2', { cardText: 'Chapter two' }, { silent: true }));// A card needs no frame or clip, so the board is ready; only the footage scene counts toward Videos.- await waitFor(() => expect(screen.getByRole('button', { name: /^Render final$/ })).toBeEnabled());+ await openStage('produce');expect(screen.getByRole('button', { name: /Videos 1\/1/ })).toBeTruthy();+ await openStage('review');+ await waitFor(() => expect(screen.getByRole('button', { name: /^Render final$/ })).toBeEnabled());});it('keeps a plain render on footage and says the layer only applies to composed renders', async () => {- await openProject({ ...PROJECT_WITH_CLIP, scenes: [scenes[0], { ...scenes[1], visualLayer: 'card' }], composition: composition('concat') });+ await openProject({ ...PROJECT_WITH_CLIP, scenes: [scenes[0], { ...scenes[1], visualLayer: 'card' }], composition: composition('concat') }, 'board');expect(await screen.findByText(/Title card sections render in composed mode/)).toBeTruthy();+ await openStage('review');expect(screen.getByRole('button', { name: /^Render final$/ })).toBeDisabled();});});@@ -1175,7 +1226,7 @@ describe('MusicVideo section layers (#8985)', () => {describe('MusicVideo concept & style editor (#3168)', () => {it('seeds the fields from the project and persists each on blur', async () => {const withConcept = { ...PROJECT_NO_CLIP, concept: { prompt: 'A road trip through neon ruins', style: 'Cyberpunk anime' } };- await openProject(withConcept);+ await openProject(withConcept, 'setup');const conceptField = await screen.findByLabelText('Concept');const styleField = screen.getByLabelText('Visual style');@@ -1201,7 +1252,7 @@ describe('MusicVideo concept & style editor (#3168)', () => {it('does not re-PATCH when a field is focused and blurred without an edit', async () => {const withConcept = { ...PROJECT_NO_CLIP, concept: { prompt: 'Unchanged', style: 'Unchanged' } };- await openProject(withConcept);+ await openProject(withConcept, 'setup');const conceptField = await screen.findByLabelText('Concept');fireEvent.focus(conceptField);fireEvent.blur(conceptField);@@ -1235,7 +1286,7 @@ describe('MusicVideo concept & style editor (#3168)', () => {});it('starts empty and enables AI Plan to use them once set', async () => {- await openProject(PROJECT_ANALYZED);+ await openProject(PROJECT_ANALYZED, 'setup');const conceptField = await screen.findByLabelText('Concept');expect(conceptField).toHaveValue('');@@ -1251,7 +1302,7 @@ describe('MusicVideo concept & style editor (#3168)', () => {describe('MusicVideo YouTube audio import (#1945)', () => {it('starts an import from the detail view and attaches the finished track to the project', async () => {- await openProject(PROJECT_NO_CLIP);+ await openProject(PROJECT_NO_CLIP, 'setup');const urlInput = screen.getByPlaceholderText(/Import audio from a YouTube URL/i);fireEvent.change(urlInput, { target: { value: 'https://youtu.be/dQw4w9WgXcQ' } });const row = urlInput.closest('div');@@ -1271,15 +1322,15 @@ describe('MusicVideo YouTube audio import (#1945)', () => {});it('disables the Import button until a URL is entered', async () => {- await openProject(PROJECT_NO_CLIP);- // Exact name: the board also carries "Import take" / handoff import controls.+ await openProject(PROJECT_NO_CLIP, 'setup');+ // Exact name: other stages also carry "Import take" / handoff import controls.const importBtns = screen.getAllByRole('button', { name: /^Import$/i });expect(importBtns.length).toBeGreaterThan(0);importBtns.forEach((btn) => expect(btn).toHaveProperty('disabled', true));});it('running the create-form and detail-view imports at once does not orphan either job', async () => {- await openProject(PROJECT_NO_CLIP);+ await openProject(PROJECT_NO_CLIP, 'setup');await openCreateForm();importTrackFromYoutube.mockResolvedValueOnce({ jobId: 'yt-job-create' })@@ -1361,7 +1412,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {});it('blocks deleting the selected project while its import is in flight', async () => {- await openProject(PROJECT_NO_CLIP);+ await openProject(PROJECT_NO_CLIP, 'setup');const editInput = screen.getAllByPlaceholderText(/Import audio from a YouTube URL/i).find((el) => el.id !== 'mv-yt-create');fireEvent.change(editInput, { target: { value: 'https://youtu.be/xyz' } });@@ -1509,7 +1560,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {prompt: 'Cosmic sci-fi',}]);updateMusicVideoProject.mockResolvedValue({ ...project, trackId: 'track-new', concept: { prompt: 'Space journey', style: 'Cosmic sci-fi' } });- await openProject(project);+ await openProject(project, 'setup');const changeTrackSelect = screen.getByLabelText('Change track');fireEvent.change(changeTrackSelect, { target: { value: 'track-new' } });@@ -1532,7 +1583,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {// An instrumental track: nothing to import, so nothing to separate or align.importMusicVideoTrackLyrics.mockResolvedValue({ project: analyzed, imported: 0, markers: 0, skipped: 'no-track-lyrics' });planMusicVideoProject.mockResolvedValue({ project: analyzed, scenesAdded: 3, promptsSeeded: true });- await openProject(project);+ await openProject(project, 'produce');fireEvent.click(screen.getByRole('button', { name: /Analyze & plan/ }));await waitFor(() => expect(planMusicVideoProject).toHaveBeenCalledWith(project.id, { seedPrompts: true }, { silent: true }));expect(analyzeMusicVideoProject).toHaveBeenCalledWith(project.id, { silent: true });@@ -1550,11 +1601,14 @@ describe('MusicVideo YouTube audio import (#1945)', () => {const approved = { ...reviewing, castAndSets: { ...reviewing.castAndSets, status: 'approved' }, devArtifacts: [{ ...sheet, status: 'approved' }] };approveMusicVideoCastAndSets.mockResolvedValue({ project: approved, stage: approved.castAndSets });planMusicVideoProject.mockResolvedValue({ project: approved, scenesAdded: 2, promptsSeeded: true });- await openProject(project);+ await openProject(project, 'produce');fireEvent.click(screen.getByRole('button', { name: /Analyze & plan/ }));await waitFor(() => expect(startMusicVideoCastAndSets).toHaveBeenCalledWith(project.id, {}, { silent: true }));await pushSocket('music-video:cast-and-sets', { projectId: project.id, project: reviewing, stage: reviewing.castAndSets });+ // The check-in lives on the Cast & Sets tab; the header offers its approval.+ expect(screen.getByRole('button', { name: 'Approve cast & sets' })).toBeEnabled();+ await openStage('cast-sets');expect(await screen.findByText('Waiting for your check-in.')).toBeTruthy();await settle();expect(planMusicVideoProject).not.toHaveBeenCalled();@@ -1570,7 +1624,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {startMusicVideoCastAndSets.mockResolvedValue({ project: directing, stage: directing.castAndSets });const approved = { ...project, castAndSets: { status: 'approved', revision: 1, plan: {}, images: {} } };planMusicVideoProject.mockResolvedValue({ project: approved, scenesAdded: 2, promptsSeeded: true });- await openProject(project);+ await openProject(project, 'produce');fireEvent.click(screen.getByRole('button', { name: /Analyze & plan/ }));await waitFor(() => expect(startMusicVideoCastAndSets).toHaveBeenCalled());@@ -1591,12 +1645,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {const project = { ...PROJECT_NO_CLIP, devArtifacts: [sheet] };listMusicVideoProjects.mockResolvedValue([project]);render(- <MemoryRouter initialEntries={[`/music-video/${project.id}/dev/mvd-1?v=1`]}>- <Routes>- <Route path="/music-video/:projectId" element={<MusicVideo />} />- <Route path="/music-video/:projectId/dev/:artifactId" element={<MusicVideo />} />- </Routes>- </MemoryRouter>,+ <MemoryRouter initialEntries={[`/music-video/${project.id}/cast-sets/dev/mvd-1?v=1`]}>{MV_ROUTES}</MemoryRouter>,);const frame = await screen.findByTitle('Cast & Sets — Nova v1');expect(frame.getAttribute('sandbox')).toBe('allow-scripts');@@ -1607,10 +1656,11 @@ describe('MusicVideo YouTube audio import (#1945)', () => {});it('blocks relinking the track while a render is in progress for the selected project', async () => {- await openProject(PROJECT_WITH_CLIP);+ await openProject(PROJECT_WITH_CLIP, 'review');fireEvent.click(await screen.findByRole('button', { name: /^Render final$/ }));await waitFor(() => expect(renderMusicVideoProject).toHaveBeenCalled());+ await openStage('setup');const trackSelect = screen.getByLabelText('Change track');expect(trackSelect).toHaveProperty('disabled', true);fireEvent.change(trackSelect, { target: { value: 'other-track' } });@@ -1626,16 +1676,11 @@ describe('MusicVideo YouTube audio import (#1945)', () => {// View-only — no remix/clean action handlers. Keys are deep-linkable via ?preview=.describe('MusicVideo media lightbox (#3718)', () => {const renderMVAt = (path) => render(- <MemoryRouter initialEntries={[path]}>- <Routes>- <Route path="/music-video" element={<MusicVideo />} />- <Route path="/music-video/:projectId" element={<MusicVideo />} />- </Routes>- </MemoryRouter>,+ <MemoryRouter initialEntries={[path]}>{MV_ROUTES}</MemoryRouter>,);it('opens the lightbox from a reference-frame thumbnail click', async () => {- await openProject(PROJECT_WITH_CLIP);+ await openProject(PROJECT_WITH_CLIP, 'board');fireEvent.click(await screen.findByRole('button', { name: 'View scene 1 reference frame full size' }));const dialog = await screen.findByRole('dialog', { name: /Media viewer/i });expect(dialog).toBeTruthy();@@ -1645,7 +1690,7 @@ describe('MusicVideo media lightbox (#3718)', () => {});it('opens the lightbox from a scene-clip expand control without hijacking play/pause', async () => {- await openProject(PROJECT_WITH_CLIP);+ await openProject(PROJECT_WITH_CLIP, 'board');// Inline thumb keeps its own controls attribute for native play/pause.const inlineVideo = document.querySelector('video[src="/data/videos/h1.mp4"]');expect(inlineVideo).toBeTruthy();@@ -1660,7 +1705,7 @@ describe('MusicVideo media lightbox (#3718)', () => {it('opens the final render from the resolved filename, not the history-id reconstruction', async () => {// getVideoHistoryItem is mocked → { id: 'rh-9', filename: 'final.mp4' }; the// final-render id is NOT its filename stem, so /data/videos/rh-9.mp4 404s.- await openProject({ ...PROJECT_WITH_CLIP, renderHistoryId: 'rh-9' });+ await openProject({ ...PROJECT_WITH_CLIP, renderHistoryId: 'rh-9' }, 'review');const expand = await screen.findByRole('button', { name: 'View final video full size' });fireEvent.click(expand);const dialog = await screen.findByRole('dialog', { name: /Media viewer/i });@@ -1675,7 +1720,7 @@ describe('MusicVideo media lightbox (#3718)', () => {// the image model never saw. The sidecar is the only record of the real// one — and it also carries the `cleanedFrom` lineage the hand-rolled item// shape used to drop.- await openProject(PROJECT_WITH_CLIP);+ await openProject(PROJECT_WITH_CLIP, 'board');fireEvent.click(await screen.findByRole('button', { name: 'View scene 1 reference frame full size' }));const dialog = await screen.findByRole('dialog', { name: /Media viewer/i });await waitFor(() => {@@ -1717,7 +1762,7 @@ describe('MusicVideo visual spec, takes and handoff (#8965)', () => {universeStyle: 'Ink silhouettes', moodBoardStyle: 'Watercolor', subjects: [{ id: 'lead', kind: 'character', role: 'protagonist', name: 'Example singer', description: 'Silver coat' },],- } });+ } }, 'board');fireEvent.click(screen.getByRole('button', { name: /^Generate frame$/ }));await waitFor(() => expect(generateImage).toHaveBeenCalledWith(expect.objectContaining({prompt: expect.stringContaining('character (protagonist): Example singer — Silver coat'),@@ -1731,7 +1776,7 @@ describe('MusicVideo visual spec, takes and handoff (#8965)', () => {new Error('Reference images are only supported for FLUX.2 and Qwen Image 2.1 models on the local backend'),{ code: 'REFERENCE_IMAGES_FLUX2_ONLY', status: 400 },));- await openProject(SPEC_PROJECT);+ await openProject(SPEC_PROJECT, 'board');fireEvent.click(screen.getByRole('button', { name: /^Generate frame$/ }));await waitFor(() => expect(generateImage).toHaveBeenCalledWith({prompt: 'harbor at dawn, grainy 16mm, color palette #112233; camera: locked-off wides',@@ -1775,7 +1820,7 @@ describe('MusicVideo visual spec, takes and handoff (#8965)', () => {referenceImageId: 'take-b.png',takes: [{ ...scene.takes[0], status: 'rejected' }, scene.takes[1]],});- await openProject({ ...PROJECT_NO_CLIP, id: 'mv-takes', name: 'Takes Project', scenes: [scene] });+ await openProject({ ...PROJECT_NO_CLIP, id: 'mv-takes', name: 'Takes Project', scenes: [scene] }, 'board');const strip = screen.getByRole('list', { name: /Frame takes/ });expect(within(strip).getByText(/imported · midjourney/)).toBeTruthy();@@ -1799,7 +1844,7 @@ describe('MusicVideo visual spec, takes and handoff (#8965)', () => {imported: [{ sceneId: 's1', takeId: 't-mj', kind: 'image', assetId: 'upload-0001.png', originalName: 'S01-s1-harbor.png' }],skipped: [],});- await openProject(SPEC_PROJECT);+ await openProject(SPEC_PROJECT, 'review');const file = new File(['png-bytes'], 'S01-s1-harbor.png', { type: 'image/png' });fireEvent.change(screen.getByLabelText('Import generated files'), { target: { files: [file] } });@@ -1810,12 +1855,13 @@ describe('MusicVideo visual spec, takes and handoff (#8965)', () => {expect(uploadGalleryImage).toHaveBeenCalledTimes(1);await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Imported 1 take from midjourney'));// The imported take filled the empty slot on the board.+ await openStage('board');expect(await screen.findByRole('button', { name: 'View scene 1 reference frame full size' })).toBeTruthy();});it('downloads the ZIP handoff bundle from Export bundle (#8978)', async () => {getMusicVideoHandoffBundle.mockResolvedValueOnce(new ArrayBuffer(8));- await openProject(SPEC_PROJECT);+ await openProject(SPEC_PROJECT, 'review');fireEvent.click(await screen.findByRole('button', { name: /^Export bundle$/ }));await waitFor(() => expect(getMusicVideoHandoffBundle).toHaveBeenCalledWith('mv-spec', { silent: true }));await waitFor(() => expect(downloadBlob).toHaveBeenCalledWith(@@ -1839,7 +1885,7 @@ describe('MusicVideo pull references from universe (#8978)', () => {places: [{ id: 'p1', name: 'Harbor', imageRefs: ['harbor.png'] }], // already a referenceobjects: [],});- await openProject(UNIVERSE_PROJECT);+ await openProject(UNIVERSE_PROJECT, 'setup');fireEvent.click(await screen.findByRole('button', { name: /^Pull from universe$/ }));await waitFor(() => expect(getUniverse).toHaveBeenCalledWith('u1', { silent: true }));@@ -1860,7 +1906,7 @@ describe('MusicVideo pull references from universe (#8978)', () => {getUniverse.mockResolvedValue({characters: [], places: [{ id: 'p1', name: 'Harbor', imageRefs: ['harbor.png'] }], objects: [],});- await openProject(UNIVERSE_PROJECT);+ await openProject(UNIVERSE_PROJECT, 'setup');fireEvent.click(await screen.findByRole('button', { name: /^Pull from universe$/ }));await waitFor(() => expect(getUniverse).toHaveBeenCalledTimes(1));expect(updateMusicVideoProject).not.toHaveBeenCalled();@@ -1870,7 +1916,7 @@ describe('MusicVideo pull references from universe (#8978)', () => {it('applies the pull against the latest references, not a stale click-time snapshot (race guard)', async () => {let resolveUniverse;getUniverse.mockReturnValueOnce(new Promise((resolve) => { resolveUniverse = resolve; }));- await openProject(UNIVERSE_PROJECT);+ await openProject(UNIVERSE_PROJECT, 'setup');fireEvent.click(await screen.findByRole('button', { name: /^Pull from universe$/ }));await waitFor(() => expect(getUniverse).toHaveBeenCalledTimes(1));@@ -1896,7 +1942,7 @@ describe('MusicVideo pull references from universe (#8978)', () => {});it('does not offer Pull from universe when the project has no linked universe', async () => {- await openProject(PROJECT_NO_CLIP);+ await openProject(PROJECT_NO_CLIP, 'setup');expect(screen.queryByRole('button', { name: /Pull from universe/i })).toBeNull();});});@@ -1906,7 +1952,7 @@ describe('MusicVideo per-scene clip import (#8978)', () => {addMusicVideoSceneTake.mockResolvedValueOnce({scene: { ...PROJECT_NO_CLIP.scenes[0], videoHistoryId: 'rh-9', takes: [{ takeId: 't1', kind: 'video', assetId: 'rh-9', status: 'candidate' }] },});- await openProject(PROJECT_NO_CLIP);+ await openProject(PROJECT_NO_CLIP, 'board');fireEvent.click(await screen.findByRole('button', { name: /^Import clip take$/ }));const dialog = await screen.findByRole('dialog', { name: /Pick a video from your gallery/i });@@ -1931,9 +1977,173 @@ describe('MusicVideo scene clip non-MP4 playback (#8978)', () => {getVideoHistoryItem.mockImplementation((id) => (id === 'h1'? Promise.resolve({ id: 'h1', filename: 'h1.mov' }): Promise.reject(Object.assign(new Error('Not found'), { status: 404 }))));- await openProject(PROJECT_WITH_CLIP);+ await openProject(PROJECT_WITH_CLIP, 'board');await waitFor(() => expect(document.querySelector('video[src="/data/videos/h1.mov"]')).toBeTruthy());expect(document.querySelector('video[src="/data/videos/h1.mp4"]')).toBeNull();});});++describe('MusicVideo stage tabs (#9243)', () => {+ const renderAt = (path) => render(+ <MemoryRouter initialEntries={[path]}>+ <LocationProbe />+ {MV_ROUTES}+ </MemoryRouter>,+ );+ const selectedTab = () => screen.getByRole('tab', { selected: true });++ it('opens the stage named in the URL, falls back to the project\'s own stage for an unknown one, and the tabs navigate', async () => {+ listMusicVideoProjects.mockResolvedValue([PROJECT_WITH_CLIP]);+ renderAt('/music-video/mv-1/produce');+ await screen.findByRole('heading', { level: 2, name: PROJECT_WITH_CLIP.name });+ expect(selectedTab()).toHaveTextContent(/^Produce/);+ expect(screen.getByRole('button', { name: 'Set up autopilot' })).toBeTruthy();++ fireEvent.click(screen.getByRole('tab', { name: STAGE_TABS.board }));+ await waitFor(() => expect(screen.getByTestId('loc').textContent).toBe('/music-video/mv-1/board'));+ expect(selectedTab()).toHaveTextContent(/^Board/);+ expect(screen.getByRole('button', { name: /Add scene/ })).toBeTruthy();+ });++ it('falls back to the stage the project is in when the URL names no stage or an unknown one', async () => {+ // Track linked but not analyzed: Setup.+ listMusicVideoProjects.mockResolvedValue([PROJECT_WITH_CLIP]);+ renderAt('/music-video/mv-1/not-a-stage');+ await screen.findByRole('heading', { level: 2, name: PROJECT_WITH_CLIP.name });+ expect(selectedTab()).toHaveTextContent(/^Setup/);+ });++ it('keeps the open tab when a stage completes, while the header moves on to the next action', async () => {+ const analyzed = { ...PROJECT_NO_CLIP, audioAnalysis: PROJECT_ANALYZED.audioAnalysis };+ analyzeMusicVideoProject.mockResolvedValue(analyzed);+ await openProject(PROJECT_NO_CLIP);+ expect(selectedTab()).toHaveTextContent(/^Setup/);++ fireEvent.click(screen.getByRole('button', { name: 'Analyze song' }));+ await waitFor(() => expect(analyzeMusicVideoProject).toHaveBeenCalledWith('mv-2', { silent: true }));+ // Analysis is done and the shot has no frame or clip: the header now points at production…+ expect(await screen.findByRole('button', { name: 'Set up production' })).toBeTruthy();+ // …but the tab the director is working in is not pulled out from under them.+ expect(selectedTab()).toHaveTextContent(/^Setup/);+ });++ it('every control has exactly one home tab', async () => {+ const project = { ...PROJECT_WITH_CLIP, castAndSets: { status: 'review', revision: 1, plan: {}, images: {} }, audioAnalysis: PROJECT_ANALYZED.audioAnalysis };+ const landmarks = {+ setup: { 'Change track': () => screen.queryByLabelText('Change track'), 'Concept': () => screen.queryByLabelText('Concept'), MIDI: () => screen.queryByRole('button', { name: /^MIDI$/ }) },+ 'cast-sets': { 'Cast & Sets check-in': () => screen.queryByLabelText('Cast & Sets check-in') },+ board: { 'AI Plan': () => screen.queryByRole('button', { name: /AI Plan/ }), 'Add scene': () => screen.queryByRole('button', { name: /Add scene/ }), 'Shot prompt': () => screen.queryByLabelText('Shot prompt') },+ produce: { 'Autopilot': () => screen.queryByLabelText('Autopilot'), 'Scene video renderer': () => screen.queryByLabelText('Scene video renderer'), 'Start production': () => screen.queryByRole('button', { name: /Start production/ }) },+ compose: { 'Render style': () => document.getElementById('mv-toolbar-render-style'), Typography: () => screen.queryByText(/^Typography —/) },+ review: { 'Render final': () => screen.queryByRole('button', { name: /^Render final$/ }), 'Render excerpt': () => screen.queryByRole('button', { name: /Render excerpt/ }), 'Import development file': () => screen.queryByLabelText('Import development file') },+ };+ await openProject(project);+ for (const [stage, own] of Object.entries(landmarks)) {+ await openStage(stage);+ for (const [name, find] of Object.entries(own)) expect(find(), `${name} on ${stage}`).toBeTruthy();+ for (const [other, theirs] of Object.entries(landmarks)) {+ if (other === stage) continue;+ for (const [name, find] of Object.entries(theirs)) expect(find(), `${name} must not be on ${stage}`).toBeFalsy();+ }+ }+ });++ describe('the sticky header\'s next action', () => {+ it('runs the autopilot for a fresh autopilot project', async () => {+ // The check-in is already skipped, so the run goes straight from analysis to the plan.+ const project = { ...PROJECT_NO_CLIP, scenes: [], lyricCues: [], castAndSets: { status: 'skipped' }, automation: { tools: ['image:local'], guidance: '', budgetUsd: null } };+ const analyzed = { ...project, audioAnalysis: PROJECT_ANALYZED.audioAnalysis };+ analyzeMusicVideoProject.mockResolvedValue(analyzed);+ importMusicVideoTrackLyrics.mockResolvedValue({ project: analyzed, imported: 0, markers: 0 });+ planMusicVideoProject.mockResolvedValue({ project: analyzed, scenesAdded: 1, promptsSeeded: false });+ await openProject(project);+ fireEvent.click(screen.getByRole('button', { name: 'Run autopilot' }));+ await waitFor(() => expect(analyzeMusicVideoProject).toHaveBeenCalledWith(project.id, { silent: true }));+ await waitFor(() => expect(planMusicVideoProject).toHaveBeenCalledWith(project.id, { seedPrompts: true }, { silent: true }));+ });++ it('approves the Cast & Sets check-in it is waiting on, from any tab', async () => {+ const waiting = {+ ...PROJECT_ANALYZED, scenes: [], lyricCues: [], automation: { tools: ['image:local'], guidance: '', budgetUsd: null },+ castAndSets: { status: 'review', revision: 1, plan: {}, images: {} },+ };+ const approved = { ...waiting, castAndSets: { ...waiting.castAndSets, status: 'approved' } };+ approveMusicVideoCastAndSets.mockResolvedValue({ project: approved, stage: approved.castAndSets });+ importMusicVideoTrackLyrics.mockResolvedValue({ project: approved, imported: 0, markers: 0 });+ planMusicVideoProject.mockResolvedValue({ project: approved, scenesAdded: 1, promptsSeeded: false });+ await openProject(waiting, 'setup');+ fireEvent.click(screen.getByRole('button', { name: 'Approve cast & sets' }));+ await waitFor(() => expect(approveMusicVideoCastAndSets).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(planMusicVideoProject).toHaveBeenCalled());+ });++ it('stops a running production run and shows what it has spent against its cap', async () => {+ const run = {+ id: 'run-1', status: 'running', interrupted: false, directive: '', stopReason: null, error: null, pool: [],+ limits: { maxGenerations: 12, maxReviewAttempts: 3, spendCapUsd: 20 }, usage: { generations: 3, spentUsd: 4.5 }, steps: [],+ };+ const project = { ...PROJECT_ANALYZED, productionRuns: [run] };+ stopMusicVideoProduction.mockResolvedValue({ project, run });+ await openProject(project, 'board');+ expect(screen.getByText('$4.50 / $20.00')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'Stop production' }));+ await waitFor(() => expect(stopMusicVideoProduction).toHaveBeenCalledWith('mv-3', 'run-1', { silent: true }));+ });++ it('takes a finished project to its final video', async () => {+ await openProject({ ...PROJECT_WITH_CLIP, audioAnalysis: PROJECT_ANALYZED.audioAnalysis, renderHistoryId: 'rh-9' }, 'board');+ fireEvent.click(screen.getByRole('button', { name: 'Watch final video' }));+ await waitFor(() => expect(selectedTab()).toHaveTextContent(/^Review/));+ expect(document.getElementById('mv-final-video')).toBeTruthy();+ });+ });++ describe('docked preview', () => {+ const DOCUMENT = { directory: 'music-video/mv-doc/composition/doc-a', entry: 'index.html', updatedAt: '2026-01-01T00:00:00.000Z', source: { kind: 'template', name: 'layered' }, files: 9, bytes: 90000 };+ const docProject = {+ ...PROJECT_WITH_CLIP,+ id: 'mv-doc',+ name: 'Document Project',+ audioAnalysis: null,+ composition: { version: 1, mode: 'document', textCues: [], style: { color: '#ffffff', font: 'sans' }, posterSec: null, document: DOCUMENT },+ scenes: [+ { sceneId: 's1', order: 0, prompt: 'a', referenceImageId: 'img1', videoHistoryId: 'h1', startSec: 0, endSec: 4 },+ { sceneId: 's2', order: 1, prompt: 'b', referenceImageId: 'img1', videoHistoryId: 'h1', startSec: 4, endSec: 8 },+ ],+ };++ it('seeks the player to a scene\'s start when its card is opened, and mounts only once a preview stage is visited', async () => {+ listTracks.mockResolvedValue([{ id: 't1', title: 'Neon Song', audioFilename: 'neon.mp3' }]);+ await openProject(docProject, 'setup');+ expect(screen.queryByTitle('Composition document preview')).toBeNull();++ await openStage('board');+ expect(await screen.findByTitle('Composition document preview')).toBeTruthy();+ await waitFor(() => expect(screen.getByText('0.00s / 60.0s')).toBeTruthy());+ fireEvent.click(screen.getByText('Scene 2'));+ await waitFor(() => expect(screen.getByText('4.00s / 60.0s')).toBeTruthy());+ fireEvent.click(screen.getByText('Scene 1'));+ await waitFor(() => expect(screen.getByText('0.00s / 60.0s')).toBeTruthy());+ });++ it('falls back to the latest finished draft excerpt when there is no composition document', async () => {+ const project = {+ ...PROJECT_WITH_CLIP,+ excerpts: [+ { id: 'mve-1', startSec: 0, endSec: 10, status: 'complete', filename: 'excerpt-old.mp4', notes: [] },+ { id: 'mve-2', startSec: 10, endSec: 20, status: 'complete', filename: 'excerpt-new.mp4', notes: [] },+ ],+ };+ await openProject(project, 'board');+ const player = await screen.findByLabelText('Latest draft excerpt preview');+ expect(player.getAttribute('src')).toBe('/data/videos/excerpt-new.mp4');+ expect(screen.queryByTitle('Composition document preview')).toBeNull();+ });++ it('offers no preview when the project has neither a document nor a finished excerpt', async () => {+ await openProject(PROJECT_WITH_CLIP, 'board');+ expect(screen.queryByLabelText('Preview')).toBeNull();+ });+ });+});