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: edit, compile and apply music-video treatments from the board (#8980)
[._.]/ Adam Eivy2a102230165c
diff --git a/client/src/components/musicVideo/TreatmentApplyReview.jsx b/client/src/components/musicVideo/TreatmentApplyReview.jsxnew file mode 100644index 0000000000..58239a76db--- /dev/null+++ b/client/src/components/musicVideo/TreatmentApplyReview.jsx@@ -0,0 +1,114 @@+import { useState } from 'react';+import { ClipboardCheck, AlertTriangle } from 'lucide-react';++const PROMPT_LABELS = {+ fill: 'prompts filled from the treatment',+ replace: 'treatment prompts updated',+ unchanged: 'prompts already match',+ manual: 'your edited prompts are kept',+ none: 'prompts untouched',+};++const snippet = (text) => (text && text.length > 90 ? `${text.slice(0, 89)}…` : text || '—');++/**+ * Apply review (#8980): shows exactly what applying the treatment would change+ * — per scene, whether its direction changes and what happens to its prompts —+ * before anything is written. Hand-edited prompts are kept unless the director+ * ticks "Use the treatment's prompts" for that scene; the server only honors+ * that tick for the exact prompts shown here. Selected takes are never touched.+ */+export default function TreatmentApplyReview({ project, api }) {+ const { preview, previewing, applying } = api;+ const [overwrite, setOverwrite] = useState({});+ const [addTextCues, setAddTextCues] = useState(false);+ const labels = new Map((project.scenes || []).map((s) => [s.sceneId, s.label || s.sectionLabel || 'Scene']));+ const idFor = (suffix) => `mv-apply-${project.id}-${suffix}`;++ const open = () => { setOverwrite({}); setAddTextCues(false); api.loadPreview(); };+ const changing = preview ? preview.scenes.filter((s) => s.directionChanged || ['fill', 'replace'].includes(s.prompt)).length : 0;+ const manual = preview ? preview.scenes.filter((s) => s.prompt === 'manual') : [];+ const hardStale = preview?.stale.filter((s) => s.blocking) || [];+ const audioStale = hardStale.some((s) => s.input === 'audio');++ const submit = () => api.apply({+ overwrite: manual.filter((s) => overwrite[s.sceneId]).map((s) => ({ sceneId: s.sceneId, promptFingerprint: s.promptFingerprint })),+ addTextCues,+ });++ return (+ <div className="space-y-2 border-t border-port-border pt-2">+ <div className="flex flex-wrap items-center gap-2">+ <button type="button" onClick={open} disabled={previewing || applying}+ className="flex items-center gap-1 bg-port-border hover:bg-port-border/70 disabled:opacity-50 rounded px-2 py-1 text-xs min-h-[44px] sm:min-h-0">+ <ClipboardCheck size={13} /> {previewing ? 'Reviewing…' : 'Review changes before applying'}+ </button>+ {preview && <span className="text-xs text-port-text-muted">{changing} of {preview.scenes.length} scenes would change</span>}+ </div>++ {preview && (+ <div className="space-y-2 rounded border border-port-border p-2 text-xs">+ {preview.stale.length > 0 && (+ <ul className="space-y-1">+ {preview.stale.map((s) => (+ <li key={s.input} className={`flex items-start gap-1.5 ${s.blocking ? 'text-port-error' : 'text-port-warning'}`}>+ <AlertTriangle size={12} className="mt-0.5 shrink-0" /> {s.message}+ </li>+ ))}+ </ul>+ )}+ {hardStale.length > 0 && (+ <div className="flex flex-wrap items-center gap-2">+ <span>Apply is blocked until the treatment matches the current project.</span>+ {!audioStale && (+ <button type="button" onClick={() => api.save({ rebase: true }).then(() => api.loadPreview())}+ className="bg-port-border hover:bg-port-border/70 rounded px-2 py-1 min-h-[44px] sm:min-h-0">+ Keep this treatment for the current inputs+ </button>+ )}+ {audioStale && <span className="text-port-text-muted">Recompile the treatment for the new song.</span>}+ </div>+ )}+ {hardStale.length === 0 && preview.unmappedSceneIds.length > 0 && (+ <p className="text-port-text-muted">{preview.unmappedSceneIds.length} newer scene{preview.unmappedSceneIds.length === 1 ? ' has' : 's have'} no direction — recompile to direct them.</p>+ )}+ <ul className="space-y-1 max-h-72 overflow-y-auto">+ {preview.scenes.map((s) => (+ <li key={s.sceneId} className="rounded border border-port-border/60 p-1.5">+ <div className="flex flex-wrap items-center gap-2">+ <span className="font-medium">{labels.get(s.sceneId) || s.label}</span>+ <span className="text-port-text-muted">{s.directionChanged ? 'direction updated' : 'direction unchanged'} · {PROMPT_LABELS[s.prompt]}</span>+ {s.keepsSelection && <span className="text-port-text-muted">· selected takes kept</span>}+ </div>+ {s.prompt === 'manual' && (+ <div className="mt-1 space-y-0.5">+ <p className="text-port-text-muted">Yours: {snippet(s.current.framePrompt || s.current.prompt)}</p>+ <p className="text-port-text-muted">Treatment: {snippet(s.suggested.framePrompt || s.suggested.prompt)}</p>+ <label className="flex items-center gap-1.5">+ <input type="checkbox" checked={!!overwrite[s.sceneId]}+ onChange={(e) => setOverwrite((prev) => ({ ...prev, [s.sceneId]: e.target.checked }))} />+ Use the treatment's prompts for this scene+ </label>+ </div>+ )}+ </li>+ ))}+ </ul>+ {preview.textCueCandidates > 0 && (+ <label htmlFor={idFor('cues')} className="flex items-center gap-1.5">+ <input id={idFor('cues')} type="checkbox" checked={addTextCues} onChange={(e) => setAddTextCues(e.target.checked)} />+ Add {preview.textCueCandidates} text cue{preview.textCueCandidates === 1 ? '' : 's'} from the timed lyrics, placed in each shot's reserved region+ </label>+ )}+ <div className="flex flex-wrap items-center gap-2">+ <button type="button" onClick={submit} disabled={preview.blocked || applying}+ className="bg-port-accent text-white disabled:opacity-50 rounded px-3 py-1.5 min-h-[44px] sm:min-h-0">+ {applying ? 'Applying…' : 'Apply treatment'}+ </button>+ <button type="button" onClick={api.clearPreview} className="text-port-text-muted underline">Cancel</button>+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/musicVideo/TreatmentPanel.jsx b/client/src/components/musicVideo/TreatmentPanel.jsxnew file mode 100644index 0000000000..1b0c0087b5--- /dev/null+++ b/client/src/components/musicVideo/TreatmentPanel.jsx@@ -0,0 +1,236 @@+import { useState } from 'react';+import { ScrollText, Sparkles, Wand2, AlertTriangle, Plus, Trash2 } from 'lucide-react';+import useFieldDraft from '../../hooks/useFieldDraft.js';+import useProviderModels from '../../hooks/useProviderModels.js';+import ProviderModelSelector from '../ProviderModelSelector.jsx';+import { formatTimecode } from '../../utils/formatters.js';+import TreatmentShotList from './TreatmentShotList.jsx';+import TreatmentProofs from './TreatmentProofs.jsx';+import TreatmentApplyReview from './TreatmentApplyReview.jsx';++const ASPECT_RATIOS = ['16:9', '9:16', '1:1', '4:5', '2.39:1'];+const ROLE_STYLES = {+ opening: 'bg-port-accent/30 text-port-accent',+ build: 'bg-port-border text-port-text',+ contrast: 'bg-port-warning/30 text-port-warning',+ payoff: 'bg-port-success/30 text-port-success',+ release: 'bg-port-border text-port-text-muted',+};+const inputCls = 'w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';++// One brief text field: buffered locally, committed on blur as a per-field patch.+function BriefField({ id, label, value, onCommit, multiline = false, maxLength, placeholder }) {+ const draft = useFieldDraft(value, onCommit);+ const Tag = multiline ? 'textarea' : 'input';+ return (+ <div>+ <label htmlFor={id} className="block text-xs text-port-text-muted mb-1">{label}</label>+ <Tag id={id} value={draft.value} onChange={draft.onChange} onBlur={draft.onBlur}+ maxLength={maxLength} placeholder={placeholder} rows={multiline ? 2 : undefined} className={inputCls} />+ </div>+ );+}++function BeatObjective({ beat, idFor, onSave }) {+ const draft = useFieldDraft(beat.objective, (objective) => onSave({ beats: [{ id: beat.id, objective }] }));+ return (+ <>+ <label htmlFor={idFor(`beat-${beat.id}`)} className="sr-only">Objective for {beat.label}</label>+ <textarea id={idFor(`beat-${beat.id}`)} rows={2} maxLength={1000} value={draft.value}+ onChange={draft.onChange} onBlur={draft.onBlur} className={inputCls} />+ </>+ );+}++/**+ * The pre-production treatment (#8980): a structured brief, the compiled+ * whole-song arc (beats by section, motifs, balance), per-shot direction, the+ * proof checklist and the Apply review. Compiling is always an explicit click —+ * "Draft without AI" makes no provider call at all. Keyed by project id at the+ * call site so a field draft never carries across projects.+ */+export default function TreatmentPanel({ project, treatment: api }) {+ const t = project.treatment || null;+ const brief = t?.brief || {};+ const arc = t?.arc || null;+ const idFor = (suffix) => `mv-treat-${project.id}-${suffix}`;+ const saveBrief = (patch) => api.save({ brief: patch });+ const [noteText, setNoteText] = useState('');+ const [noteUrl, setNoteUrl] = useState('');+ const notes = brief.referenceNotes || [];+ const urlValid = !noteUrl.trim() || /^https?:\/\/\S+$/i.test(noteUrl.trim());+ const {+ providers, selectedProviderId, selectedModel, availableModels, setSelectedProviderId, setSelectedModel,+ } = useProviderModels({ allowDefault: true, silent: true });+ const analyzed = !!project.audioAnalysis;+ const applied = t?.appliedRevision != null && t.appliedRevision === t.revision;++ const addNote = () => {+ if ((!noteText.trim() && !noteUrl.trim()) || !urlValid) return;+ saveBrief({ referenceNotes: [...notes, { note: noteText.trim(), url: noteUrl.trim() || null }] });+ setNoteText('');+ setNoteUrl('');+ };++ 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">+ <ScrollText size={13} />+ <span>Treatment</span>+ {t ? <span>· rev {t.revision}</span> : <span>· not started</span>}+ {arc && <span>· {t.shotDirections.length} directed shots</span>}+ {arc && <span className={applied ? 'text-port-success' : 'text-port-warning'}>· {applied ? 'applied' : 'not applied'}</span>}+ {t?.capabilityGaps?.length > 0 && <span className="text-port-warning">· {t.capabilityGaps.length} capability gap{t.capabilityGaps.length === 1 ? '' : 's'}</span>}+ </summary>++ <div className="mt-2 space-y-3">+ <div className="grid grid-cols-1 md:grid-cols-2 gap-2">+ <BriefField id={idFor('audience')} label="Audience" value={brief.audience} maxLength={500}+ placeholder="Who this is for — e.g. late-night city pop fans" onCommit={(v) => saveBrief({ audience: v })} />+ <div className="grid grid-cols-[minmax(0,1fr)_auto] gap-2">+ <BriefField id={idFor('destination')} label="Destination" value={brief.destination} maxLength={200}+ placeholder="Where it plays — e.g. vertical shorts feed" onCommit={(v) => saveBrief({ destination: v })} />+ <div>+ <label htmlFor={idFor('aspect')} className="block text-xs text-port-text-muted mb-1">Aspect</label>+ <select id={idFor('aspect')} value={brief.aspectRatio || ''} className={inputCls}+ onChange={(e) => saveBrief({ aspectRatio: e.target.value || null })}>+ <option value="">Any</option>+ {ASPECT_RATIOS.map((r) => <option key={r} value={r}>{r}</option>)}+ </select>+ </div>+ </div>+ <BriefField id={idFor('emotion')} label="Desired emotion" value={brief.emotion} maxLength={500}+ placeholder="What the viewer should feel" onCommit={(v) => saveBrief({ emotion: v })} />+ <BriefField id={idFor('hook')} label="Opening hook objective" value={brief.hookObjective} maxLength={1000}+ placeholder="What the first seconds must achieve" onCommit={(v) => saveBrief({ hookObjective: v })} />+ <BriefField id={idFor('premise')} label="Narrative premise" value={brief.premise} maxLength={2000} multiline+ placeholder="A story, or a visual arc without a literal plot" onCommit={(v) => saveBrief({ premise: v })} />+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">+ <BriefField id={idFor('must')} label="Must have" value={brief.mustHave} maxLength={2000} multiline+ placeholder="Comma-separated aesthetics or motifs" onCommit={(v) => saveBrief({ mustHave: v })} />+ <BriefField id={idFor('avoid')} label="Avoid" value={brief.avoid} maxLength={2000} multiline+ placeholder="What must not appear" onCommit={(v) => saveBrief({ avoid: v })} />+ </div>+ </div>++ <div className="space-y-1">+ <span className="text-xs text-port-text-muted">Reference notes (your own notes and links — never fetched)</span>+ {notes.length > 0 && (+ <ul className="space-y-1">+ {notes.map((n) => (+ <li key={n.id} className="flex items-start gap-2 text-xs">+ <span className="min-w-0 flex-1 break-words">{n.note}{n.url && <span className="text-port-text-muted"> — {n.url}</span>}</span>+ <button type="button" aria-label="Remove reference note" title="Remove reference note"+ onClick={() => saveBrief({ referenceNotes: notes.filter((x) => x.id !== n.id) })}+ className="min-h-[32px] min-w-[32px] inline-flex items-center justify-center text-port-error">+ <Trash2 size={12} />+ </button>+ </li>+ ))}+ </ul>+ )}+ <div className="flex flex-wrap items-end gap-2">+ <div className="min-w-0 flex-1 basis-48">+ <label htmlFor={idFor('note')} className="sr-only">Reference note</label>+ <input id={idFor('note')} value={noteText} maxLength={1000} onChange={(e) => setNoteText(e.target.value)}+ placeholder="Note — e.g. grainy 16mm, hand-drawn overlays" className={inputCls} />+ </div>+ <div className="min-w-0 flex-1 basis-48">+ <label htmlFor={idFor('url')} className="sr-only">Reference URL</label>+ <input id={idFor('url')} value={noteUrl} maxLength={2000} onChange={(e) => setNoteUrl(e.target.value)}+ placeholder="https://… (optional)" className={`${inputCls} ${urlValid ? '' : 'border-port-error'}`} />+ </div>+ <button type="button" onClick={addNote} disabled={(!noteText.trim() && !noteUrl.trim()) || !urlValid || notes.length >= 20}+ className="flex items-center gap-1 bg-port-border hover:bg-port-border/70 disabled:opacity-50 rounded px-2 py-1 text-xs min-h-[44px] sm:min-h-0">+ <Plus size={13} /> Add note+ </button>+ </div>+ </div>++ <div className="flex flex-wrap items-center gap-2 border-t border-port-border pt-2">+ {providers.length > 0 && (+ <ProviderModelSelector+ providers={providers}+ selectedProviderId={selectedProviderId}+ selectedModel={selectedModel}+ availableModels={availableModels}+ onProviderChange={setSelectedProviderId}+ onModelChange={setSelectedModel}+ label="AI provider"+ disabled={api.compiling}+ modelDisabled={availableModels.length === 0}+ compact+ alwaysShowModel+ emptyProviderOption="Active provider (default)"+ emptyModelOption="Default model"+ />+ )}+ <button type="button" disabled={!analyzed || api.compiling}+ onClick={() => api.compile({ useAi: true, providerId: selectedProviderId, model: selectedModel })}+ className="flex items-center gap-1 bg-port-accent text-white disabled:opacity-50 rounded px-2 py-1 text-xs min-h-[44px] sm:min-h-0">+ <Sparkles size={13} /> {api.compiling ? 'Compiling…' : (arc ? 'Recompile with AI' : 'Compile with AI')}+ </button>+ <button type="button" disabled={!analyzed || api.compiling} onClick={() => api.compile({ useAi: false })}+ className="flex items-center gap-1 bg-port-border hover:bg-port-border/70 disabled:opacity-50 rounded px-2 py-1 text-xs min-h-[44px] sm:min-h-0">+ <Wand2 size={13} /> Draft without AI+ </button>+ {!analyzed && <span className="text-xs text-port-text-muted">Analyze the song first — the arc is built on its sections.</span>}+ {t?.compiledAt && (+ <span className="text-[11px] text-port-text-muted">+ Compiled {t.compiledWith?.source === 'ai' ? `with ${t.compiledWith.providerId}${t.compiledWith.model ? ` / ${t.compiledWith.model}` : ''}` : 'deterministically'}+ </span>+ )}+ </div>++ {arc && (+ <div className="space-y-3">+ {t.capabilityGaps.length > 0 && (+ <ul className="space-y-1 rounded border border-port-warning/40 bg-port-warning/10 p-2">+ {t.capabilityGaps.map((g) => (+ <li key={g.id} className="flex items-start gap-1.5 text-xs">+ <AlertTriangle size={12} className="mt-0.5 shrink-0 text-port-warning" />+ <span><strong>{g.id}</strong>: {g.detail}</span>+ </li>+ ))}+ </ul>+ )}+ {arc.rationale && <p className="text-xs">{arc.rationale}</p>}+ {arc.lyricInterpretation && <p className="text-xs text-port-text-muted">Lyrics: {arc.lyricInterpretation}</p>}+ <ol className="grid grid-cols-1 lg:grid-cols-2 gap-2">+ {arc.beats.map((beat) => (+ <li key={beat.id} className="rounded border border-port-border p-2 space-y-1">+ <div className="flex flex-wrap items-center gap-2 text-xs">+ <span className={`px-1.5 py-0.5 rounded text-[10px] uppercase ${ROLE_STYLES[beat.role] || ''}`}>{beat.role}</span>+ <span className="font-medium">{beat.label}</span>+ {beat.startSec != null && <span className="text-port-text-muted">{formatTimecode(beat.startSec)}–{formatTimecode(beat.endSec)}</span>}+ </div>+ <BeatObjective beat={beat} idFor={idFor} onSave={api.save} />+ {beat.rationale && <p className="text-[11px] text-port-text-muted">{beat.rationale}</p>}+ </li>+ ))}+ </ol>+ <div className="grid grid-cols-1 md:grid-cols-2 gap-2 text-xs">+ <div>+ <span className="text-port-text-muted">Recurring motifs</span>+ <ul className="mt-1 space-y-1">+ {arc.motifs.map((m) => (+ <li key={m.id}><strong>{m.name}</strong>{m.description ? ` — ${m.description}` : ''}{m.evolution && <span className="block text-port-text-muted">{m.evolution}</span>}</li>+ ))}+ {arc.motifs.length === 0 && <li className="text-port-text-muted">None yet.</li>}+ </ul>+ </div>+ <div>+ <span className="text-port-text-muted">Balance</span>+ <p className="mt-1">Performance {arc.balance.performance}% · Cutaway {arc.balance.cutaway}% · Graphic {arc.balance.graphic}%</p>+ {arc.balance.rationale && <p className="text-port-text-muted">{arc.balance.rationale}</p>}+ </div>+ </div>+ <TreatmentShotList project={project} treatment={t} onSave={api.save} />+ <TreatmentProofs project={project} treatment={t} onReview={api.reviewProof} />+ <TreatmentApplyReview project={project} api={api} />+ </div>+ )}+ </div>+ </details>+ );+}diff --git a/client/src/components/musicVideo/TreatmentPanel.test.jsx b/client/src/components/musicVideo/TreatmentPanel.test.jsxnew file mode 100644index 0000000000..d55ba9d760--- /dev/null+++ b/client/src/components/musicVideo/TreatmentPanel.test.jsx@@ -0,0 +1,163 @@+/**+ * Treatment panel (#8980) rendered with the real useMusicVideoTreatment hook+ * over a mocked API: the Apply review keeps hand-edited prompts unless the+ * director ticks them (and then sends the reviewed fingerprint), a stale+ * treatment blocks Apply until it is rebased, compile is an explicit action,+ * and quick successive edits each carry the revision the previous one returned.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { useState } from 'react';+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';++vi.mock('../../services/apiMusicVideo.js', () => ({+ getMusicVideoProject: vi.fn(),+ updateMusicVideoTreatment: vi.fn(),+ compileMusicVideoTreatment: vi.fn(),+ previewMusicVideoTreatmentApply: vi.fn(),+ applyMusicVideoTreatment: vi.fn(),+ reviewMusicVideoTreatmentProof: vi.fn(),+}));+vi.mock('../../hooks/useProviderModels.js', () => ({+ default: () => ({+ providers: [], selectedProviderId: '', selectedModel: '', availableModels: [],+ setSelectedProviderId: vi.fn(), setSelectedModel: vi.fn(),+ }),+}));+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));++import * as api from '../../services/apiMusicVideo.js';+import useMusicVideoTreatment from '../../hooks/useMusicVideoTreatment.js';+import TreatmentPanel from './TreatmentPanel.jsx';++const TREATMENT = {+ version: 1,+ revision: 3,+ brief: { audience: '', destination: '', aspectRatio: null, emotion: '', premise: '', hookObjective: '', mustHave: '', avoid: '', referenceNotes: [] },+ arc: {+ rationale: 'Example arc',+ lyricInterpretation: null,+ beats: [{ id: 'beat-1', role: 'opening', sectionIndexes: [0], label: 'Intro', startSec: 0, endSec: 8, energy: 0.3, objective: 'Hook', rationale: '' }],+ motifs: [{ id: 'm1', name: 'Red umbrella', description: '', evolution: '', rationale: '' }],+ balance: { performance: 20, cutaway: 60, graphic: 20, rationale: '' },+ },+ shotDirections: [],+ proofs: [],+ capabilityGaps: [{ id: 'lip-sync', detail: 'No source-audio lip-sync is available.' }],+ basis: {},+ compiledAt: '2026-01-01T00:00:00.000Z',+ compiledWith: { source: 'deterministic', providerId: null, model: null },+ appliedRevision: null,+ appliedAt: null,+};+const PROJECT = {+ id: 'mv-1', name: 'Example', audioAnalysis: { sections: [] }, treatment: TREATMENT,+ scenes: [+ { sceneId: 's1', label: 'Intro · 1/2', prompt: 'my own motion', framePrompt: 'my own frame', referenceImageId: 'picked.png' },+ { sceneId: 's2', label: 'Intro · 2/2', prompt: '', framePrompt: null },+ ],+};+const PREVIEW = {+ revision: 3,+ stale: [],+ blocked: false,+ scenes: [+ { sceneId: 's1', label: 'Intro · 1/2', directionChanged: true, prompt: 'manual', promptFingerprint: 'fp-s1', current: { framePrompt: 'my own frame', prompt: 'my own motion' }, suggested: { framePrompt: 'train window', prompt: 'push in' }, keepsSelection: true },+ { sceneId: 's2', label: 'Intro · 2/2', directionChanged: true, prompt: 'fill', promptFingerprint: 'fp-s2', current: { framePrompt: '', prompt: '' }, suggested: { framePrompt: 'rain', prompt: 'drift' }, keepsSelection: false },+ ],+ missingSceneIds: [],+ unmappedSceneIds: [],+ textCueCandidates: 0,+};++function Harness({ initial = PROJECT }) {+ const [project, setProject] = useState(initial);+ const treatment = useMusicVideoTreatment({+ project,+ onProjectPatch: (_id, patch) => setProject((p) => ({ ...p, ...patch })),+ replaceProject: setProject,+ });+ return (+ <>+ <TreatmentPanel project={project} treatment={treatment} />+ <output data-testid="applied">{String(project.treatment?.appliedRevision ?? 'none')}</output>+ </>+ );+}++beforeEach(() => { vi.clearAllMocks(); });++describe('TreatmentPanel apply review', () => {+ it('keeps a hand-edited prompt by default and overwrites it only with the reviewed fingerprint', async () => {+ api.previewMusicVideoTreatmentApply.mockResolvedValue(PREVIEW);+ api.applyMusicVideoTreatment.mockImplementation(async () => ({+ project: { ...PROJECT, treatment: { ...TREATMENT, appliedRevision: 3 } },+ result: { directed: 2, promptsWritten: ['s1', 's2'], promptsKept: [], conflicted: [], textCuesAdded: 0 },+ }));+ render(<Harness />);+ fireEvent.click(screen.getByText('Review changes before applying'));+ expect(await screen.findByText(/2 of 2 scenes would change/)).toBeTruthy();+ expect(screen.getByText(/your edited prompts are kept/)).toBeTruthy();+ expect(screen.getByText(/selected takes kept/)).toBeTruthy();++ fireEvent.click(screen.getByLabelText(/Use the treatment's prompts for this scene/));+ fireEvent.click(screen.getByText('Apply treatment'));+ await waitFor(() => expect(api.applyMusicVideoTreatment).toHaveBeenCalledWith(+ 'mv-1',+ { revision: 3, overwrite: [{ sceneId: 's1', promptFingerprint: 'fp-s1' }], addTextCues: false },+ { silent: true },+ ));+ await waitFor(() => expect(screen.getByTestId('applied').textContent).toBe('3'));+ });++ it('blocks Apply on a stale input until the director keeps the treatment for the current inputs', async () => {+ api.previewMusicVideoTreatmentApply+ .mockResolvedValueOnce({ ...PREVIEW, blocked: true, stale: [{ input: 'visualSpec', blocking: true, message: 'The visual spec changed since this treatment was compiled.' }] })+ .mockResolvedValueOnce(PREVIEW);+ api.updateMusicVideoTreatment.mockResolvedValue({ treatment: { ...TREATMENT, revision: 4 } });+ render(<Harness />);+ fireEvent.click(screen.getByText('Review changes before applying'));+ expect(await screen.findByText(/visual spec changed/)).toBeTruthy();+ expect(screen.getByText('Apply treatment').closest('button').disabled).toBe(true);++ fireEvent.click(screen.getByText('Keep this treatment for the current inputs'));+ await waitFor(() => expect(api.updateMusicVideoTreatment).toHaveBeenCalledWith('mv-1', { rebase: true, baseRevision: 3 }, { silent: true }));+ await waitFor(() => expect(screen.getByText('Apply treatment').closest('button').disabled).toBe(false));+ expect(api.applyMusicVideoTreatment).not.toHaveBeenCalled();+ });+});++describe('TreatmentPanel edits and compile', () => {+ it('compiles only on an explicit click, and not before the song is analyzed', async () => {+ api.compileMusicVideoTreatment.mockResolvedValue({ treatment: { ...TREATMENT, revision: 4 }, aiUsed: false, aiSkippedReason: 'not-requested' });+ const { unmount } = render(<Harness initial={{ ...PROJECT, audioAnalysis: null }} />);+ expect(screen.getByText('Draft without AI').closest('button').disabled).toBe(true);+ unmount();++ render(<Harness />);+ expect(api.compileMusicVideoTreatment).not.toHaveBeenCalled();+ fireEvent.click(screen.getByText('Draft without AI'));+ await waitFor(() => expect(api.compileMusicVideoTreatment).toHaveBeenCalledWith('mv-1', { baseRevision: 3, useAi: false }, { silent: true }));+ });++ it('serializes quick brief edits so each carries the revision the previous save returned', async () => {+ let revision = 3;+ api.updateMusicVideoTreatment.mockImplementation(async (_id, body) => {+ revision += 1;+ return { treatment: { ...TREATMENT, revision, brief: { ...TREATMENT.brief, ...body.brief } } };+ });+ render(<Harness />);+ const audience = screen.getByLabelText('Audience');+ const emotion = screen.getByLabelText('Desired emotion');+ await act(async () => {+ fireEvent.change(audience, { target: { value: 'night owls' } });+ fireEvent.blur(audience);+ fireEvent.change(emotion, { target: { value: 'restless hope' } });+ fireEvent.blur(emotion);+ });+ await waitFor(() => expect(api.updateMusicVideoTreatment).toHaveBeenCalledTimes(2));+ expect(api.updateMusicVideoTreatment.mock.calls.map(([, body]) => [body.baseRevision, body.brief])).toEqual([+ [3, { audience: 'night owls' }],+ [4, { emotion: 'restless hope' }],+ ]);+ });+});diff --git a/client/src/components/musicVideo/TreatmentProofs.jsx b/client/src/components/musicVideo/TreatmentProofs.jsxnew file mode 100644index 0000000000..d8fd6a3043--- /dev/null+++ b/client/src/components/musicVideo/TreatmentProofs.jsx@@ -0,0 +1,110 @@+import { useState } from 'react';+import { CheckCircle2, XCircle, RotateCcw } from 'lucide-react';++const STATUS_STYLES = {+ proposed: 'bg-port-border text-port-text',+ passed: 'bg-port-success/30 text-port-success',+ failed: 'bg-port-error/30 text-port-error',+};+const KIND_LABELS = { 'risk-shot': 'Highest-risk shot', 'transition-text': 'Transition / text sequence' };++// The artifacts a review can cite: the final render, then each proof scene's+// clips and frames (the server re-checks every citation).+function evidenceOptions(project, proof) {+ const options = [];+ if (project.renderHistoryId) options.push({ value: `video:${project.renderHistoryId}`, label: 'Final render' });+ for (const scene of project.scenes || []) {+ if (!proof.sceneIds.includes(scene.sceneId)) continue;+ const name = scene.label || scene.sectionLabel || 'Scene';+ const takes = Array.isArray(scene.takes) ? scene.takes : [];+ takes.filter((t) => t.kind === 'video').forEach((t, i) => options.push({ value: `video:${t.assetId}`, label: `${name} — clip ${i + 1}` }));+ takes.filter((t) => t.kind === 'image').forEach((t, i) => options.push({ value: `image:${t.assetId}`, label: `${name} — frame ${i + 1}` }));+ }+ return [...new Map(options.map((o) => [o.value, o])).values()];+}++function ProofRow({ project, proof, onReview }) {+ const options = evidenceOptions(project, proof);+ const [evidence, setEvidence] = useState(options[0]?.value || '');+ const [note, setNote] = useState('');+ const idFor = (suffix) => `mv-proof-${project.id}-${proof.id}-${suffix}`;+ const scenes = new Map((project.scenes || []).map((s) => [s.sceneId, s]));+ const submit = (status) => {+ const [kind, id] = evidence ? [evidence.slice(0, evidence.indexOf(':')), evidence.slice(evidence.indexOf(':') + 1)] : [];+ onReview(proof.id, {+ status,+ ...(status === 'proposed' ? {} : {+ evidence: {+ ...(kind === 'video' ? { videoHistoryId: id } : {}),+ ...(kind === 'image' ? { imageId: id } : {}),+ note: note.trim(),+ },+ }),+ });+ };+ return (+ <li className="rounded border border-port-border/60 p-2 space-y-1 text-xs">+ <div className="flex flex-wrap items-center gap-2">+ <span className={`px-1.5 py-0.5 rounded text-[10px] uppercase ${STATUS_STYLES[proof.status] || ''}`}>{proof.status}</span>+ <span className="font-medium">{KIND_LABELS[proof.kind] || proof.kind}</span>+ <span className="text-port-text-muted">{proof.sceneIds.map((id) => scenes.get(id)?.label || 'deleted scene').join(' → ')}</span>+ </div>+ <p>{proof.artifact}</p>+ {proof.risk && <p className="text-port-text-muted">Risk: {proof.risk}</p>}+ {proof.route && <p className="text-port-text-muted">Route: {proof.route}</p>}+ <ul className="list-disc pl-4 space-y-0.5">+ {proof.checks.map((check, i) => <li key={check}><strong>{check}</strong>: {proof.passCriteria[i]}</li>)}+ </ul>+ {proof.evidence?.note && <p className="text-port-text-muted">Reviewed: {proof.evidence.note}</p>}+ <div className="flex flex-wrap items-end gap-2 pt-1">+ <div className="min-w-0 basis-48 flex-1">+ <label htmlFor={idFor('evidence')} className="block text-[10px] text-port-text-muted">Evidence</label>+ <select id={idFor('evidence')} value={evidence} onChange={(e) => setEvidence(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs">+ <option value="">No artifact yet</option>+ {options.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}+ </select>+ </div>+ <div className="min-w-0 basis-48 flex-[2]">+ <label htmlFor={idFor('note')} className="block text-[10px] text-port-text-muted">What you checked</label>+ <input id={idFor('note')} value={note} maxLength={2000} onChange={(e) => setNote(e.target.value)}+ placeholder="e.g. text readable at phone size, cut on the downbeat"+ className="w-full bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs" />+ </div>+ <button type="button" onClick={() => submit('passed')} disabled={!evidence || !note.trim()}+ className="flex items-center gap-1 bg-port-success/20 text-port-success disabled:opacity-50 rounded px-2 py-1 min-h-[44px] sm:min-h-0">+ <CheckCircle2 size={12} /> Passed+ </button>+ <button type="button" onClick={() => submit('failed')}+ className="flex items-center gap-1 bg-port-error/20 text-port-error rounded px-2 py-1 min-h-[44px] sm:min-h-0">+ <XCircle size={12} /> Failed+ </button>+ {proof.status !== 'proposed' && (+ <button type="button" onClick={() => submit('proposed')} aria-label="Reset proof to proposed" title="Reset to proposed"+ className="flex items-center gap-1 bg-port-border rounded px-2 py-1 min-h-[44px] sm:min-h-0">+ <RotateCcw size={12} />+ </button>+ )}+ </div>+ </li>+ );+}++/**+ * The proof checklist (#8980): the riskiest shot and one short transition/text+ * sequence to prove before full production. An entry stays `proposed` until a+ * review cites a real artifact; the server refuses a pass the artifact can't+ * show (a still for motion, anything but the final render for audio alignment+ * or composited text). Reviews are advisory — nothing else waits on them.+ */+export default function TreatmentProofs({ project, treatment, onReview }) {+ if (treatment.proofs.length === 0) return null;+ return (+ <div className="space-y-1">+ <span className="text-xs text-port-text-muted">Proof before full production</span>+ <ul className="space-y-2">+ {treatment.proofs.map((proof) => <ProofRow key={proof.id} project={project} proof={proof} onReview={onReview} />)}+ </ul>+ </div>+ );+}diff --git a/client/src/components/musicVideo/TreatmentShotList.jsx b/client/src/components/musicVideo/TreatmentShotList.jsxnew file mode 100644index 0000000000..4fb53a5716--- /dev/null+++ b/client/src/components/musicVideo/TreatmentShotList.jsx@@ -0,0 +1,89 @@+import useFieldDraft from '../../hooks/useFieldDraft.js';+import { formatTimecode } from '../../utils/formatters.js';++const MODES = ['performance', 'cutaway', 'graphic'];+const ROUTES = [['generated', 'Generated'], ['supplied-asset', 'Supplied asset'], ['code-2d', '2D / code motion']];+const REGIONS = [['none', 'No text region'], ['upper', 'Upper third'], ['center', 'Center'], ['lower', 'Lower third']];+const TYPE_ROLES = [['none', 'No text'], ['subtitle', 'Subtitle'], ['hero', 'Hero title']];+const cellCls = 'w-full bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs';++function DirectionText({ id, label, value, maxLength, onCommit }) {+ const draft = useFieldDraft(value, onCommit);+ return (+ <div className="min-w-0">+ <label htmlFor={id} className="block text-[10px] text-port-text-muted">{label}</label>+ <input id={id} value={draft.value} onChange={draft.onChange} onBlur={draft.onBlur} maxLength={maxLength} className={cellCls} />+ </div>+ );+}++function DirectionSelect({ id, label, value, options, onChange }) {+ return (+ <div className="min-w-0">+ <label htmlFor={id} className="block text-[10px] text-port-text-muted">{label}</label>+ <select id={id} value={value} onChange={(e) => onChange(e.target.value)} className={cellCls}>+ {options.map(([v, text]) => <option key={v} value={v}>{text}</option>)}+ </select>+ </div>+ );+}++/**+ * Per-shot direction (#8980), one row per board scene the treatment maps. Each+ * edit saves just that field for that scene; the scene's own timing stays+ * authoritative (a direction never moves a cut). Nothing reaches the scene's+ * prompts until the director applies the treatment.+ */+export default function TreatmentShotList({ project, treatment, onSave }) {+ const scenes = new Map((project.scenes || []).map((s) => [s.sceneId, s]));+ const beats = new Map((treatment.arc?.beats || []).map((b) => [b.id, b]));+ const save = (sceneId, patch) => onSave({ shotDirections: [{ sceneId, ...patch }] });+ const idFor = (sceneId, field) => `mv-dir-${project.id}-${sceneId}-${field}`;+ return (+ <details className="rounded border border-port-border p-2">+ <summary className="cursor-pointer text-xs text-port-text-muted select-none min-h-[32px] flex items-center">+ Shot direction ({treatment.shotDirections.length})+ </summary>+ <ul className="mt-2 space-y-2">+ {treatment.shotDirections.map((d) => {+ const scene = scenes.get(d.sceneId);+ const beat = beats.get(d.beatId);+ return (+ <li key={d.sceneId} className="rounded border border-port-border/60 p-2 space-y-1">+ <div className="flex flex-wrap items-center gap-2 text-xs">+ <span className="font-medium">{scene ? (scene.label || scene.sectionLabel || 'Scene') : 'Deleted scene'}</span>+ {scene?.startSec != null && <span className="text-port-text-muted">{formatTimecode(scene.startSec)}–{formatTimecode(scene.endSec)}</span>}+ {beat && <span className="text-port-text-muted">· {beat.role}</span>}+ {scene?.lyricText ? <span className="text-port-text-muted truncate max-w-[16rem]">· “{scene.lyricText}”</span> : <span className="text-port-text-muted">· instrumental</span>}+ </div>+ <div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-4 gap-1.5">+ <DirectionSelect id={idFor(d.sceneId, 'mode')} label="Mode" value={d.mode}+ options={MODES.map((m) => [m, m])} onChange={(mode) => save(d.sceneId, { mode })} />+ <DirectionSelect id={idFor(d.sceneId, 'route')} label="Route" value={d.route}+ options={ROUTES} onChange={(route) => save(d.sceneId, { route })} />+ <DirectionSelect id={idFor(d.sceneId, 'type')} label="Typography" value={d.typographyRole}+ options={TYPE_ROLES} onChange={(typographyRole) => save(d.sceneId, { typographyRole })} />+ <DirectionSelect id={idFor(d.sceneId, 'space')} label="Reserved region" value={d.negativeSpace}+ options={REGIONS} onChange={(negativeSpace) => save(d.sceneId, { negativeSpace })} />+ <DirectionText id={idFor(d.sceneId, 'focal')} label="Focal subject" value={d.focalSubject} maxLength={500}+ onCommit={(focalSubject) => save(d.sceneId, { focalSubject })} />+ <DirectionText id={idFor(d.sceneId, 'framing')} label="Framing" value={d.framing} maxLength={500}+ onCommit={(framing) => save(d.sceneId, { framing })} />+ <DirectionText id={idFor(d.sceneId, 'emphasis')} label="Emphasis" value={d.emphasis} maxLength={500}+ onCommit={(emphasis) => save(d.sceneId, { emphasis })} />+ <DirectionText id={idFor(d.sceneId, 'in')} label="Entry" value={d.transitionIn} maxLength={300}+ onCommit={(transitionIn) => save(d.sceneId, { transitionIn })} />+ <DirectionText id={idFor(d.sceneId, 'out')} label="Exit" value={d.transitionOut} maxLength={300}+ onCommit={(transitionOut) => save(d.sceneId, { transitionOut })} />+ </div>+ {d.rationale && <p className="text-[11px] text-port-text-muted">{d.rationale}</p>}+ {d.typographyRole !== 'none' && d.negativeSpace === 'none' && (+ <p className="text-[11px] text-port-warning">Text on this shot has no reserved region — it will sit over the subject.</p>+ )}+ </li>+ );+ })}+ </ul>+ </details>+ );+}diff --git a/client/src/components/musicVideo/VisualSpecPanel.jsx b/client/src/components/musicVideo/VisualSpecPanel.jsxindex b1cdff20c2..a8716d7c4a 100644--- a/client/src/components/musicVideo/VisualSpecPanel.jsx+++ b/client/src/components/musicVideo/VisualSpecPanel.jsx@@ -11,6 +11,9 @@ const ROLES = [['mood', 'Mood'], ['character', 'Character'], ['wardrobe', 'Wardrobe'],['set', 'Set'], ['prop', 'Prop'], ['style', 'Style'],];+// How the asset is meant to be used (#8980): a look reference, media that+// appears in the final video as-is, or motion-reference scaffolding only.+const USES = [['reference', 'Look reference'], ['final-visible', 'Final visible'], ['motion-reference', 'Motion reference only']];const MAX_PALETTE = 12;const MAX_REFERENCES = 24;@@ -122,6 +125,12 @@ export default function VisualSpecPanel({ project, onSave, onAddReference }) {<Trash2 size={12} /></button></div>+ <label htmlFor={idFor(`use-${ref.id}`)} className="sr-only">Reference use</label>+ <select id={idFor(`use-${ref.id}`)} value={ref.use || 'reference'}+ onChange={(e) => updateRef(ref.id, { use: e.target.value })}+ className="w-full bg-port-bg border border-port-border rounded px-1 py-0.5 text-[11px]">+ {USES.map(([value, label]) => <option key={value} value={value}>{label}</option>)}+ </select><label htmlFor={idFor(`label-${ref.id}`)} className="sr-only">Reference label</label><input id={idFor(`label-${ref.id}`)} defaultValue={ref.label || ''} maxLength={120}placeholder="Label (e.g. lead singer)"diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 5761e2d43b..ef4ec32c96 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -251,6 +251,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useMusicVideoModelSettings` | A project's saved render pins — video backend (local/Grok/fal.ai)/model/generation-mode/audio-reactive LoRA + the image-side frame pin — with the Video Gen catalog they read from. Optimistic-local + silent PATCH, rollback + toast on failure; `saving` gates the dependent generate buttons. Returns `{ models, modelsLoading, defaultModel, falEnabled, saving, settings, effectiveModelId, activeModel, audioReactiveModels, audioReactiveLoras, detectedAudioReactiveLora, audioReactiveReady, audioReactiveSelected, videoBlockedReason, change, changeFramePin }`. `videoBlockedReason` is the single "why can't I generate" string (an unavailable audio-reactive setup, or a fal.ai pin with no configured API key) shared by the disabled buttons, their tooltips, and the blocked-call toast. | The Music Video renderer selects and anything building a scene-clip job payload from them. || `useMusicVideoSceneMedia` | Both per-scene generation lanes (reference frame + scene clip) over `useSceneRenderLifecycle`, the frame/shot prompt builders (concept-style + visual-spec direction suffix), visual-spec reference-image conditioning with explicit unsupported-backend feedback (#8965), and the batch "generate the missing ones" actions. Returns `{ genScenes, genVideoScenes, conditioning, buildFramePrompt, buildShotPrompt, generateFrame, generateSceneVideo, continueSceneVideo, generateMissingFrames, generateMissingVideos }`. | The Music Video scene board — don't re-wire the two lanes or re-derive the i2v/a2v/extend payloads. || `useMusicVideoTakes` | Scene-take review + external-asset handoff for the Music Video board (#8965): serialized select / reject / note / gallery-import take mutations folded back as scene patches, the handoff manifest download, and the handoff import (gallery upload per file, then scene association by file tag with provider provenance). Returns `{ busy, selectTake, reviewTake, importTake, exportHandoff, importHandoffFiles }`. | The Music Video board's take strips, contact sheet and handoff row — don't re-sequence take mutations per call site. |+| `useMusicVideoTreatment` | The Music Video pre-production treatment (#8980): serialized brief/arc/shot-direction saves that each carry the latest known treatment revision (a 409 from a newer copy reloads the project), explicit compile (AI or deterministic) with skip-reason feedback, the Apply review (`loadPreview` → `apply({ overwrite, addTextCues })`) and proof verdicts. Returns `{ compiling, preview, previewing, applying, save, compile, loadPreview, apply, reviewProof, clearPreview }`. | The Music Video treatment panel — don't re-derive the revision bookkeeping per call site. || `useMusicVideoManualTempo` | The manual-tempo fallback for a project whose auto-detected BPM is null: BPM/offset drafts (reset on project switch), tap-tempo estimation, and the persisted `setMusicVideoManualTempo` call. Returns `{ bpm, setBpm, offset, setOffset, saving, tap, submit }`. | The Music Video "No tempo detected" row. || `useCanvasDprSize` | DevicePixelRatio-aware canvas sizing shared by the piano-roll renderers (`<PianoRoll>`, `<MidiPianoRoll>`): sizes the bitmap to container-width × height (or the container height when `height` is `undefined`) at the DPR, applies the transform, and redraws via a `drawRef` on mount + every `ResizeObserver` resize (observer created once per height, never churned by draw-closure changes). Returns a ref holding the current CSS width so draw code doesn't measure the DOM per frame. | Both piano-roll canvases. || `useCanvasRollPalette` | Resolves a canvas palette into a ref — `rollPalette` by default, or any resolver passed as the second argument (the Core Assembly avatar reads `--port-accent-2`), re-resolving on theme switch (`data-port-theme` MutationObserver) and repainting through a `drawRef`. Hands back a ref, not state, so a theme swap redraws the imperative canvas without a React re-render. | Both piano-roll canvases need theme-aware accent/bg colors that canvas `fillStyle` can't read from CSS vars. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 20a57a52b3..f1b3a45997 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -65,6 +65,7 @@ export { default as useMusicVideoModelSettings } from './useMusicVideoModelSettiexport { default as useMusicVideoRenderJob } from './useMusicVideoRenderJob.js';export { default as useMusicVideoSceneMedia } from './useMusicVideoSceneMedia.js';export { default as useMusicVideoTakes } from './useMusicVideoTakes.js';+export { default as useMusicVideoTreatment } from './useMusicVideoTreatment.js';export { default as useMusicVideoYoutubeImport } from './useMusicVideoYoutubeImport.js';export { default as useBeeperOutbox } from './useBeeperOutbox.js';export { default as useBeeperRealtime } from './useBeeperRealtime.js';diff --git a/client/src/hooks/useMusicVideoSceneMedia.js b/client/src/hooks/useMusicVideoSceneMedia.jsindex 65b63b01bb..1025c480f4 100644--- a/client/src/hooks/useMusicVideoSceneMedia.js+++ b/client/src/hooks/useMusicVideoSceneMedia.js@@ -104,13 +104,17 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS// The image prompt for a scene's reference frame: its frame prompt (or the// shot prompt as a fallback) suffixed with the project's global concept style// and the visual spec's palette/camera/typography direction.+ // An applied treatment (#8980) adds the scene's composition constraints last:+ // focal subject, framing, the region reserved for the composited typography,+ // and no lettering in the generated pixels. Same order as the server's+ // handoff manifest (handoff.js composePrompt).const buildFramePrompt = (scene) =>- [(scene.framePrompt?.trim() || scene.prompt?.trim() || ''), style, direction].filter(Boolean).join(', ');+ [(scene.framePrompt?.trim() || scene.prompt?.trim() || ''), style, direction, scene.direction?.frameClause?.trim()].filter(Boolean).join(', ');// The i2v prompt for a scene's clip: its shot prompt (or the frame prompt as a// fallback) suffixed the same way. The reference frame already fixes the// look; this prompt guides the motion.const buildShotPrompt = (scene) =>- [(scene.prompt?.trim() || scene.framePrompt?.trim() || ''), style, direction].filter(Boolean).join(', ');+ [(scene.prompt?.trim() || scene.framePrompt?.trim() || ''), style, direction, scene.direction?.motionClause?.trim()].filter(Boolean).join(', ');/*** Render a still reference frame for one scene from its frame prompt. Thediff --git a/client/src/hooks/useMusicVideoTreatment.js b/client/src/hooks/useMusicVideoTreatment.jsnew file mode 100644index 0000000000..89ad4fb825--- /dev/null+++ b/client/src/hooks/useMusicVideoTreatment.js@@ -0,0 +1,151 @@+import { useEffect, useRef, useState } from 'react';+import toast from '../components/ui/Toast';+import {+ getMusicVideoProject,+ updateMusicVideoTreatment,+ compileMusicVideoTreatment,+ previewMusicVideoTreatmentApply,+ applyMusicVideoTreatment,+ reviewMusicVideoTreatmentProof,+} from '../services/apiMusicVideo.js';++const AI_SKIP_LABELS = {+ 'no-provider': 'no AI provider is configured',+ 'provider-disabled': 'the AI provider is disabled',+ 'llm-failed': 'the AI call failed',+ 'unparsable-response': 'the AI answer was unusable',+ 'too-many-shots': 'too many shots for one AI pass',+};++/**+ * The Music Video pre-production treatment (#8980): brief/arc/shot-direction+ * edits, compile, the Apply review and proof verdicts.+ *+ * Every write names the treatment revision it was based on. Writes run one at+ * a time and each reads the revision the previous response returned, so quick+ * successive blurs never conflict with each other; a 409 from a genuinely+ * newer copy (another tab, a peer) reloads the project instead of retrying.+ *+ * `onProjectPatch(projectId, patch)` merges fields into the local record;+ * `replaceProject(project)` swaps it whole (Apply and a conflict reload touch+ * scenes and composition too).+ */+export default function useMusicVideoTreatment({ project, onProjectPatch, replaceProject } = {}) {+ const projectId = project?.id || null;+ const storedRevision = project?.treatment?.revision ?? 0;+ const revisionRef = useRef(storedRevision);+ const chainRef = useRef(Promise.resolve());+ const [compiling, setCompiling] = useState(false);+ const [preview, setPreview] = useState(null);+ const [previewing, setPreviewing] = useState(false);+ const [applying, setApplying] = useState(false);++ const projectRef = useRef(projectId);+ // A newer revision can arrive from outside this hook (a peer update, a+ // reload); within one project never move the ref backwards past a write this+ // hook already made. A project switch adopts that project's revision.+ useEffect(() => {+ if (projectRef.current !== projectId) {+ projectRef.current = projectId;+ revisionRef.current = storedRevision;+ } else {+ revisionRef.current = Math.max(revisionRef.current, storedRevision);+ }+ }, [projectId, storedRevision]);+ useEffect(() => { setPreview(null); }, [projectId]);++ const adopt = (id, treatment) => {+ revisionRef.current = treatment?.revision ?? revisionRef.current;+ onProjectPatch?.(id, { treatment });+ };++ const handleConflict = (id, err, fallback) => {+ if (err?.status === 409 && err?.code === 'TREATMENT_REVISION_CONFLICT') {+ toast.error('The treatment changed elsewhere — reloaded the latest version');+ return getMusicVideoProject(id, { silent: true }).then((fresh) => {+ revisionRef.current = fresh?.treatment?.revision ?? 0;+ replaceProject?.(fresh);+ }).catch(() => {});+ }+ toast.error(err?.message || fallback);+ return null;+ };++ // Serialize treatment writes; each reads the latest known revision when it runs.+ const enqueue = (work, fallback) => {+ const id = projectId;+ const run = chainRef.current.then(() => work(id, revisionRef.current));+ chainRef.current = run.catch((err) => handleConflict(id, err, fallback));+ return run.catch(() => null);+ };++ const save = (patch) => enqueue(+ (id, baseRevision) => updateMusicVideoTreatment(id, { ...patch, baseRevision }, { silent: true })+ .then(({ treatment }) => { adopt(id, treatment); setPreview(null); return treatment; }),+ 'Failed to save the treatment',+ );++ const compile = ({ useAi, providerId, model }) => {+ setCompiling(true);+ return enqueue(+ (id, baseRevision) => compileMusicVideoTreatment(id, {+ baseRevision,+ useAi,+ ...(providerId ? { providerId } : {}),+ ...(model ? { model } : {}),+ }, { silent: true }).then(({ treatment, aiUsed, aiSkippedReason }) => {+ adopt(id, treatment);+ setPreview(null);+ const shots = treatment.shotDirections.length;+ if (useAi && !aiUsed) toast.error(`Drafted without AI — ${AI_SKIP_LABELS[aiSkippedReason] || aiSkippedReason}`);+ else toast.success(`Treatment compiled for ${shots} shot${shots === 1 ? '' : 's'}${aiUsed ? ' with AI' : ''}`);+ return treatment;+ }),+ 'Treatment compile failed',+ ).finally(() => setCompiling(false));+ };++ const loadPreview = () => {+ const id = projectId;+ setPreviewing(true);+ return previewMusicVideoTreatmentApply(id, { silent: true })+ .then((data) => { if (id === projectRef.current) setPreview(data); })+ .catch((err) => toast.error(err?.message || 'Could not review the treatment'))+ .finally(() => setPreviewing(false));+ };++ const apply = ({ overwrite = [], addTextCues = false } = {}) => {+ if (!preview) return Promise.resolve(null);+ const id = projectId;+ const { revision } = preview;+ setApplying(true);+ return chainRef.current+ .then(() => applyMusicVideoTreatment(id, { revision, overwrite, addTextCues }, { silent: true }))+ .then(({ project: next, result }) => {+ replaceProject?.(next);+ setPreview(null);+ const kept = result.promptsKept.length + result.conflicted.length;+ toast.success(`Applied direction to ${result.directed} scene${result.directed === 1 ? '' : 's'}${kept ? ` — ${kept} hand-edited prompt${kept === 1 ? '' : 's'} kept` : ''}${result.textCuesAdded ? `, ${result.textCuesAdded} text cues added` : ''}`);+ return result;+ })+ .catch((err) => {+ // A stale review re-reads the preview so the director sees what changed.+ if (err?.status === 409) loadPreview();+ toast.error(err?.message || 'Apply failed');+ return null;+ })+ .finally(() => setApplying(false));+ };++ const reviewProof = (proofId, review) => enqueue(+ (id, baseRevision) => reviewMusicVideoTreatmentProof(id, proofId, { ...review, baseRevision }, { silent: true })+ .then(({ treatment }) => { adopt(id, treatment); return treatment; }),+ 'Failed to record the proof review',+ );++ return {+ compiling, preview, previewing, applying,+ save, compile, loadPreview, apply, reviewProof,+ clearPreview: () => setPreview(null),+ };+}diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex a34dbe083c..f97120c0c0 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -26,6 +26,7 @@ import useMusicVideoModelSettings from '../hooks/useMusicVideoModelSettings.js';import useMusicVideoManualTempo from '../hooks/useMusicVideoManualTempo.js';import useMusicVideoSceneMedia from '../hooks/useMusicVideoSceneMedia.js';import useMusicVideoTakes from '../hooks/useMusicVideoTakes.js';+import useMusicVideoTreatment from '../hooks/useMusicVideoTreatment.js';import useHydratedPreviewRoute from '../hooks/useHydratedPreviewRoute.js';import { normalizeImage, normalizeVideo } from '../components/media/normalize.js';import { useVideoFileSrc } from '../hooks/useVideoFileSrc.js';@@ -43,6 +44,7 @@ import SceneCard from '../components/musicVideo/SceneCard.jsx';import LyricsPanel from '../components/musicVideo/LyricsPanel.jsx';import TypographyPanel from '../components/musicVideo/TypographyPanel.jsx';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 GalleryImagePicker from '../components/imageGen/GalleryImagePicker.jsx';@@ -121,6 +123,9 @@ export default function MusicVideo() {applyScenePatch: patchScene,});const takes = useMusicVideoTakes({ project: selected, applyScenePatch: patchScene });+ // Pre-production treatment (#8980): brief, compiled arc, shot direction,+ // proof checklist and the non-destructive Apply review.+ const treatment = useMusicVideoTreatment({ project: selected, onProjectPatch: patchProject, replaceProject });// The one gallery picker on the page, aimed at either the visual spec's// references or one scene's frame takes. Cleared on a project switch so a// picker opened for one project can never write into another.@@ -650,6 +655,7 @@ export default function MusicVideo() {onSave={saveVisualSpec}onAddReference={() => setPickerTarget({ type: 'reference' })}/>+ <TreatmentPanel key={`treatment-${selected.id}`} project={selected} treatment={treatment} /><HandoffControlsprojectId={selected.id}busy={takes.busy}diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex 3d8119e926..322098eeb0 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -64,6 +64,12 @@ vi.mock('../services/apiMusicVideo.js', () => ({getMusicVideoHandoff: vi.fn(),getMusicVideoHandoffBundle: vi.fn(),importMusicVideoHandoff: vi.fn(),+ getMusicVideoProject: vi.fn(),+ updateMusicVideoTreatment: vi.fn(),+ compileMusicVideoTreatment: vi.fn(),+ previewMusicVideoTreatmentApply: vi.fn(),+ applyMusicVideoTreatment: vi.fn(),+ reviewMusicVideoTreatmentProof: vi.fn(),}));vi.mock('../services/apiUniverseBuilder.js', () => ({ getUniverse: vi.fn() }));vi.mock('../lib/downloadBlob.js', () => ({ downloadBlob: vi.fn() }));diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 0156aeb8aa..2b5f446c1b 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -126,3 +126,29 @@ export const musicVideoRenderEventsUrl = (jobId) =>export const cancelMusicVideoRender = (jobId, options = {}) =>request(`/music-video/render/${encodeURIComponent(jobId)}/cancel`, { method: 'POST', ...options });++// ---- Pre-production treatment (#8980) ----+// A structured brief, a compiled whole-song arc, per-shot direction keyed to the+// board's scene ids and a proof checklist. Every write names the treatment+// revision it was made against; a stale one is a 409 (`TREATMENT_REVISION_CONFLICT`).+export const getMusicVideoProject = (id, options = {}) => request(`/music-video/${encodeURIComponent(id)}`, options);+// Body: { baseRevision, brief?, beats?, motifs?, shotDirections?, rebase? } → { project, treatment }.+export const updateMusicVideoTreatment = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/treatment`, {+ method: 'PATCH', body: JSON.stringify(body), ...options,+});+// Explicit user action. Body: { baseRevision, useAi?, providerId?, model? }+// → { project, treatment, aiUsed, aiSkippedReason }.+export const compileMusicVideoTreatment = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/treatment/compile`, {+ method: 'POST', body: JSON.stringify(body), ...options,+});+// Read-only → { revision, stale, blocked, scenes, missingSceneIds, unmappedSceneIds, textCueCandidates }.+export const previewMusicVideoTreatmentApply = (id, options = {}) => request(`/music-video/${encodeURIComponent(id)}/treatment/apply-preview`, options);+// Body: { revision, overwrite?: [{ sceneId, promptFingerprint }], addTextCues? } → { project, result }.+export const applyMusicVideoTreatment = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/treatment/apply`, {+ method: 'POST', body: JSON.stringify(body), ...options,+});+// Body: { baseRevision, status, evidence?: { videoHistoryId?, imageId?, note } } → { project, treatment }.+export const reviewMusicVideoTreatmentProof = (id, proofId, body, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/treatment/proofs/${encodeURIComponent(proofId)}/review`, {+ method: 'POST', body: JSON.stringify(body), ...options,+ });diff --git a/docs/HTML_COMPOSITIONS.md b/docs/HTML_COMPOSITIONS.mdindex 31eaf2a1de..85f4a17fc9 100644--- a/docs/HTML_COMPOSITIONS.md+++ b/docs/HTML_COMPOSITIONS.md@@ -171,6 +171,18 @@ whole number of frames on the song's timebase, so the edit never drifts fromthe authored timeline. A plain concat render ignores the layer and playsfootage, exactly as before.+A project's pre-production **treatment** (#8980,+`server/services/musicVideo/treatment.js`) plans for this layer instead of+fighting it. Each directed shot names a typography role (none, subtitle,+hero) and a reserved region (upper third, center, lower third); applying the+treatment adds that region to the scene's frame and motion prompts as clean,+low-detail negative space and asks the image/video model for no lettering, so+the generated picture leaves room for the composited text rather than baking+text into pixels. Apply can also add text cues from the timed lyrics, placed+in each shot's reserved region; it never switches the render to `composed`.+The treatment's proof checklist treats readable text and audio alignment as+judgeable only in the final render.+## Launch-video admission (API foundation)`POST /api/html-composition/render` accepts `launchVideo: { targetDurationSec: 20 }`.diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.mdindex e5bed5348c..76928b07b2 100644--- a/docs/features/product-surfaces.md+++ b/docs/features/product-surfaces.md@@ -110,7 +110,7 @@ An end-to-end creative production suite for authors, worldbuilders, filmmakers,| **SongBook** | `/songbook` | Interactive chord charts, guitar tablature, lyric repertoire, and auto-scrolling practice sheet music. | — || **Creative Director** | `/creative-director` | Multi-scene episodic video production orchestrator: turn briefs into treatments, storyboards, render plans, and completed episodes. | — || **Creative Commissions** | `/creative-commission` | Standing briefs and scheduled/nightly autonomous media generation aligning with personal taste profiles and feedback. A universe and/or mood board can be picked as the style source: each run loads its style tags and reference images as the Creative Director's art-direction base, attaches those images to vision scene evaluation, and conditions local image renders on them. | — |-| **Music Video Studio** | `/music-video` | Audio-reactive video creation, beat-detection synchronization, scene choreography, and tempo alignment. Scenes are cutaways or lip-synced performance shots; a performance shot renders only on a verified source-audio provider (fal.ai MiniMax H3 lip-sync, 5–14.8s song slices placed at an exact edit in-point) — Grok video is cutaway-only. | — |+| **Music Video Studio** | `/music-video` | Audio-reactive video creation, beat-detection synchronization, scene choreography, tempo alignment, and audience-driven pre-production treatments that direct each shot. Scenes are cutaways or lip-synced performance shots; a performance shot renders only on a verified source-audio provider (fal.ai MiniMax H3 lip-sync, 5–14.8s song slices placed at an exact edit in-point) — Grok video is cutaway-only. | — || **Sharing & Conflict Resolution** | `/sharing`, `/sharing/duplicates`, `/sharing/conflicts` | Collaborative asset exchange via cloud storage buckets (Google Drive, Dropbox, iCloud, Syncthing) with duplicate reconciliation and conflict recovery journals. | — |---