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 editor panel to start, monitor, stop and resume a production run (#9066)
[._.]/ Adam Eivy0e8ee5a17048
diff --git a/client/src/components/musicVideo/ProductionPanel.jsx b/client/src/components/musicVideo/ProductionPanel.jsxnew file mode 100644index 0000000000..caf47a2710--- /dev/null+++ b/client/src/components/musicVideo/ProductionPanel.jsx@@ -0,0 +1,217 @@+import { useState } from 'react';+import { Clapperboard, Play, Pause, X } from 'lucide-react';+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 { formatUsd } from '../../utils/formatters.js';++const POOL_TOOLS = MUSIC_VIDEO_AUTOMATION_TOOLS.filter((t) => t.group === 'image' || t.group === 'video');+const POOL_TOOL_IDS = new Set(POOL_TOOLS.map((t) => t.id));++const STATUS_LABELS = {+ running: 'Running', stopped: 'Paused', 'limit-reached': 'Stopped at a limit', blocked: 'Blocked',+ 'needs-replan': 'Setup changed', completed: 'Finished', 'needs-human': 'Needs you', failed: 'Failed', canceled: 'Cancelled',+};+const STATUS_TONES = {+ running: 'text-port-accent', stopped: 'text-port-warning', 'limit-reached': 'text-port-warning', blocked: 'text-port-warning',+ 'needs-replan': 'text-port-warning', completed: 'text-port-success', 'needs-human': 'text-port-warning',+ 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';+const SHOWN_STEPS = 8;++const toolLabel = new Map(POOL_TOOLS.map((t) => [t.id, t.label]));+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));+};++function StepRow({ step }) {+ return (+ <li className="flex flex-wrap gap-x-2 min-w-0">+ <span className="font-mono">{step.kind}</span>+ <span className="text-port-text-muted">{routeLabel(step.route)}</span>+ <span className={STEP_TONES[step.status] || 'text-port-accent'}>{step.status}</span>+ {step.rationale && <span className="text-port-text-muted min-w-0 break-words">{step.rationale}</span>}+ {step.error && <span className="text-port-error min-w-0 break-words">{step.error}</span>}+ </li>+ );+}++function RunView({ run, production }) {+ const live = RESUMABLE.has(run.status);+ const steps = run.steps || [];+ const failures = steps.filter((s) => s.error);+ const cap = run.limits.spendCapUsd;+ const needsReplan = run.status === 'needs-replan';+ const hint = run.interrupted+ ? 'The server restarted — nothing is running. Resume to continue.'+ : run.stopReason;+ return (+ <div className="space-y-2">+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">+ <span className={`font-medium ${STATUS_TONES[run.status] || ''}`}>{run.interrupted ? 'Interrupted' : STATUS_LABELS[run.status] || run.status}</span>+ <span className="text-port-text-muted">+ {run.usage.generations}/{run.limits.maxGenerations} generations · {formatUsd(run.usage.spentUsd)}{cap != null ? ` of ${formatUsd(cap)}` : ' spent (no cap)'}+ </span>+ </div>+ {run.directive && <p className="text-port-text-muted break-words">Directive: {run.directive}</p>}+ <p className="text-port-text-muted">Allowed: {(run.pool || []).map(routeLabel).join(', ')}</p>+ {hint && <p className="text-port-warning break-words">{hint}</p>}+ {run.error && <p className="text-port-error break-words">{run.error}</p>}+ {failures.length > 0 && <p className="text-port-error">{failures.length} step{failures.length === 1 ? '' : 's'} failed — see the list below.</p>}+ {steps.length > 0 && (+ <ul className="space-y-0.5" aria-label="Production steps">+ {steps.slice(-SHOWN_STEPS).reverse().map((step) => <StepRow key={step.key} step={step} />)}+ </ul>+ )}+ <div className="flex flex-wrap gap-2">+ {run.status === 'running' && !run.interrupted && (+ <button type="button" disabled={production.busy} onClick={() => production.stop(run.id)}+ className="flex items-center gap-1 border border-port-border rounded px-3 py-2 min-h-[44px] sm:min-h-0 sm:px-2 sm:py-1 disabled:opacity-50">+ <Pause size={12} /> Stop+ </button>+ )}+ {live && (run.status !== 'running' || run.interrupted) && (+ <button type="button" disabled={production.busy}+ onClick={() => production.resume(run.id, needsReplan ? { acceptBasis: true } : {})}+ 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} /> {needsReplan ? 'Resume with the new setup' : 'Resume'}+ </button>+ )}+ {live && (+ <button type="button" disabled={production.busy} onClick={() => production.cancel(run.id)}+ className="flex items-center gap-1 border border-port-border rounded px-3 py-2 min-h-[44px] sm:min-h-0 sm:px-2 sm:py-1 disabled:opacity-50">+ <X size={12} /> Cancel+ </button>+ )}+ </div>+ </div>+ );+}++function StartForm({ project, production }) {+ const [pool, setPool] = useState(() => initialPool(project));+ const [directive, setDirective] = useState('');+ const [maxGenerations, setMaxGenerations] = useState(12);+ const [maxReviewAttempts, setMaxReviewAttempts] = useState(3);+ const [spendCap, setSpendCap] = useState('');+ const {+ providers, selectedProviderId, selectedModel, availableModels, setSelectedProviderId, setSelectedModel,+ } = useProviderModels({ allowDefault: true, silent: true });+ const idFor = (s) => `mv-production-${project?.id}-${s}`;+ const picked = new Set(pool);+ const capValue = spendCap === '' ? null : Number(spendCap);+ const hasImage = pool.some((id) => id.startsWith('image:'));+ const hasVideo = pool.some((id) => id.startsWith('video:'));+ const valid = hasImage && hasVideo+ && Number.isInteger(maxGenerations) && maxGenerations >= 1 && maxGenerations <= 500+ && Number.isInteger(maxReviewAttempts) && maxReviewAttempts >= 1 && maxReviewAttempts <= 10+ && (capValue == null || (Number.isFinite(capValue) && capValue >= 0));++ const toggle = (id) => setPool((cur) => (cur.includes(id) ? cur.filter((t) => t !== id) : [...cur, id]));+ const start = () => production.start({+ ...(directive.trim() ? { directive: directive.trim() } : {}),+ pool: POOL_TOOLS.filter((t) => picked.has(t.id)).map((t) => {+ const [kind, mode] = t.id.split(':');+ return { kind, mode };+ }),+ limits: { maxGenerations, maxReviewAttempts, ...(capValue != null ? { spendCapUsd: capValue } : {}) },+ ...(selectedProviderId ? { providerId: selectedProviderId } : {}),+ ...(selectedModel ? { model: selectedModel } : {}),+ });++ return (+ <div className="space-y-2">+ <p className="text-port-text-muted">+ Plans the board, generates the missing frames and clips, renders and reviews the draft, and revises failed sections — on the server, so you can close this tab.+ Only the routes you allow are ever used, and it never exceeds the limits below. Metered routes have no known price, so a dollar cap refuses them.+ </p>+ <fieldset className="min-w-0" aria-labelledby={idFor('pool-label')}>+ <span id={idFor('pool-label')} className="block text-[11px] text-port-text-muted mb-1">Allowed image and video routes</span>+ <div className="flex flex-wrap gap-1.5">+ {POOL_TOOLS.map((tool) => (+ <ToggleChip+ key={tool.id}+ id={idFor(`tool-${tool.id}`)}+ label={tool.metered ? `${tool.label} $` : tool.label}+ hint={tool.metered ? 'Spends money or remote quota' : undefined}+ checked={picked.has(tool.id)}+ onToggle={() => toggle(tool.id)}+ />+ ))}+ </div>+ {!(hasImage && hasVideo) && <p className="text-port-warning mt-1">Allow at least one image and one video route.</p>}+ </fieldset>+ <div>+ <label htmlFor={idFor('directive')} className="block text-[10px] text-port-text-muted">Production directive</label>+ <textarea id={idFor('directive')} rows={2} maxLength={4000} value={directive} onChange={(e) => setDirective(e.target.value)}+ placeholder="What to make and what to avoid — steers the plan when the board is empty."+ className="w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-xs" />+ </div>+ <div className="flex flex-wrap items-end gap-2">+ <div>+ <label htmlFor={idFor('generations')} className="block text-[10px] text-port-text-muted">Max generations</label>+ <input id={idFor('generations')} type="number" min={1} max={500} step={1} value={maxGenerations} disabled={production.busy}+ onChange={(e) => setMaxGenerations(Number(e.target.value))} className={inputCls} />+ </div>+ <div>+ <label htmlFor={idFor('attempts')} className="block text-[10px] text-port-text-muted">Max reviews</label>+ <input id={idFor('attempts')} type="number" min={1} max={10} step={1} value={maxReviewAttempts} disabled={production.busy}+ onChange={(e) => setMaxReviewAttempts(Number(e.target.value))} className={inputCls} />+ </div>+ <div>+ <label htmlFor={idFor('cap')} className="block text-[10px] text-port-text-muted">Spend cap (USD)</label>+ <input id={idFor('cap')} type="number" min={0} step={1} inputMode="decimal" value={spendCap} disabled={production.busy}+ placeholder="No cap" onChange={(e) => setSpendCap(e.target.value)} className={inputCls} />+ </div>+ {providers.length > 0 && (+ <ProviderModelSelector+ providers={providers}+ selectedProviderId={selectedProviderId}+ selectedModel={selectedModel}+ availableModels={availableModels}+ onProviderChange={setSelectedProviderId}+ onModelChange={setSelectedModel}+ label="Reviewer (vision)"+ disabled={production.busy}+ modelDisabled={availableModels.length === 0}+ compact+ />+ )}+ <button type="button" 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>+ </div>+ </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 }) {+ const run = currentProductionRun(project);+ const active = run && RESUMABLE.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>+ {run && <RunView run={run} production={production} />}+ {!active && <StartForm key={run?.id || 'new'} project={project} production={production} />}+ </div>+ );+}diff --git a/client/src/components/musicVideo/ProductionPanel.test.jsx b/client/src/components/musicVideo/ProductionPanel.test.jsxnew file mode 100644index 0000000000..be99bb030a--- /dev/null+++ b/client/src/components/musicVideo/ProductionPanel.test.jsx@@ -0,0 +1,80 @@+/**+ * 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/hooks/README.md b/client/src/hooks/README.mdindex 173542381e..6f8574b59d 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -247,6 +247,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useMidiTranscription` | One audio → MIDI transcription job slot (MuScriptor): start/cancel + SSE stage progress + terminal-frame handling, generic over the Rounds and Music Video API surfaces (pass `startRequest`/`eventsUrl`/`cancelRequest`). Returns `{ active, stage, stageLabel, context, start(context), cancel }` (`stageLabel` is the ready-to-render human label for the current STAGE — including a distinct "Downloading model…" for the first-use weight download, which also fires a one-time toast; `context` is the in-flight job's captured target, for per-target UI gates); `onComplete(frame, context)` fires with the terminal frame (`filename`, `model`, any server-merged extras). | The Rounds reference "Transcribe MIDI" control and the Music Video MIDI button. || `useMusicVideoYoutubeImport` | The Music Video page's two independent `useYoutubeTrackImport` slots (create form + detail-view track row) plus their URL drafts, the detail slot's captured target project, and the URL-nav backstop that bounces a deep link / Back / ⌘K jump away from an in-flight import back to its project. Returns `{ createUrl, setCreateUrl, editUrl, setEditUrl, createJob, editJob, startCreate, startEdit, switchBlockedMessage }`. | The Music Video page. Reuse `switchBlockedMessage` for any additional guard (delete, list picker) so every surface says the same thing. || `useMusicVideoMidiJob` | `useMidiTranscription` bound to the music-video API surface, plus the MuScriptor model-size picker state (read fresh at each kickoff). Returns the slot (`active`/`stage`/`stageLabel`/`context`/`start(projectId)`/`cancel`/`installGate`/`gatedGate`) plus `{ model, setModel }`; `onTranscribed(projectId, midiTranscription)` fires on a non-discarded terminal frame. | The Music Video MIDI button + model select. |+| `useMusicVideoProduction` | Server-owned production run (#9066): start a browserless plan → frames → clips → reviewed-draft run with an allowed provider/model pool and explicit limits, and Stop / Resume / Cancel it; applies the project pushed on `music-video:production` and toasts terminal outcomes. Returns `{ busy, start(body), resume(runId, body?), stop(runId), cancel(runId) }`. | The Music Video production panel. || `useMusicVideoRenderJob` | The final-render job (#1760 Phase 2): kickoff (409 → attach to the existing job), SSE progress, terminal-frame handling and non-terminal stream-close recovery. Thin `useSseJobSlot` adapter with 0–1 progress conversion; returns `{ active, pending, context, job, progress, start(projectId), cancel }`; `onRendered(projectId, result)` / `onFailed(projectId)` key on the projectId captured at kickoff. | The Music Video "Render final" control. || `useMusicVideoRevisions` | Selective section revision (#8987): open a revision from a reviewed draft excerpt (its flagged sections' takes are rejected, the rest kept), resume it from the server checkpoint — generating ONLY the sections the server reports as `needsGeneration` through the board's scene lanes, or adopting the draft re-render via `attachRender` once every revised section has a take — and cancel it. Returns `{ busy, revise(excerptId, sceneIds?), resume(revisionId), cancel(revisionId), submitSections(project, refs, revisionId) }`. | The Music Video excerpt panel. || `useMusicVideoAutoReview` | Opt-in automatic review/retries (#8988): start a run over a draft window with explicit review (`maxAttempts`) and paid-generation (`maxGenerations`) limits plus a vision reviewer; applies the project pushed on `music-video:auto-review` and submits the revised sections a run hands out through `submitSections` while the board is open. Returns `{ busy, action, start(startSec, endSec, limits, reviewer), resume(runId, limits?), stop(runId), cancel(runId) }`. | The Music Video excerpt panel. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 7c796d7540..04efb8e097 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -64,6 +64,7 @@ export { default as useMusicVideoExcerpts } from './useMusicVideoExcerpts.js';export { default as useMusicVideoManualTempo } from './useMusicVideoManualTempo.js';export { default as useMusicVideoMidiJob } from './useMusicVideoMidiJob.js';export { default as useMusicVideoModelSettings } from './useMusicVideoModelSettings.js';+export { default as useMusicVideoProduction } from './useMusicVideoProduction.js';export { default as useMusicVideoRenderJob } from './useMusicVideoRenderJob.js';export { default as useMusicVideoRevisions } from './useMusicVideoRevisions.js';export { default as useMusicVideoSceneMedia } from './useMusicVideoSceneMedia.js';diff --git a/client/src/hooks/useMusicVideoProduction.js b/client/src/hooks/useMusicVideoProduction.jsnew file mode 100644index 0000000000..ef8077a8f3--- /dev/null+++ b/client/src/hooks/useMusicVideoProduction.js@@ -0,0 +1,71 @@+import { useEffect, useRef, useState } from 'react';+import toast from '../components/ui/Toast';+import socket from '../services/socket';+import {+ startMusicVideoProduction,+ resumeMusicVideoProduction,+ stopMusicVideoProduction,+ cancelMusicVideoProduction,+} from '../services/apiMusicVideo.js';++const OUTCOME_TOASTS = {+ completed: () => toast.success('Production run finished — review the draft'),+ 'needs-human': (run) => toast.info(`Production needs you: ${run.stopReason || 'check the latest draft'}`),+ 'limit-reached': (run) => toast.info(`Production stopped at its limit: ${run.stopReason || ''}`),+ blocked: (run) => toast.info(`Production is blocked: ${run.stopReason || 'no allowed route can continue'}`),+ 'needs-replan': () => toast.info('The creative setup changed — resume to continue against the new setup'),+ failed: (run) => toast.error(`Production failed: ${run.stopReason || run.error || 'unknown error'}`),+};++/**+ * Server-owned production run (#9066). Only an explicit `start`/`resume` runs+ * anything; the server dispatches every frame, clip and revision itself, so+ * this hook only applies the project it pushes over `music-video:production`+ * (no polling) and reports terminal outcomes.+ *+ * Returns `{ busy, start(body), resume(runId, body?), stop(runId), cancel(runId) }`.+ */+export default function useMusicVideoProduction({ project, replaceProject } = {}) {+ const projectId = project?.id || null;+ const [busy, setBusy] = useState(false);+ const replaceRef = useRef(replaceProject);+ const lastStatus = useRef(new Map());+ useEffect(() => {+ replaceRef.current = replaceProject;+ });++ useEffect(() => {+ if (!projectId) return undefined;+ const onProduction = (data) => {+ if (data?.projectId !== projectId) return;+ if (data.project) replaceRef.current?.(data.project);+ const run = data.run;+ if (run?.id && lastStatus.current.get(run.id) !== run.status) {+ const seen = lastStatus.current.has(run.id);+ lastStatus.current.set(run.id, run.status);+ if (seen || run.status !== 'running') OUTCOME_TOASTS[run.status]?.(run);+ }+ };+ socket.on('music-video:production', onProduction);+ return () => socket.off('music-video:production', onProduction);+ }, [projectId]);++ const call = (request) => {+ setBusy(true);+ return request()+ .then((res) => {+ if (res?.project) replaceRef.current?.(res.project);+ if (res?.run) lastStatus.current.set(res.run.id, res.run.status);+ return res;+ })+ .catch((err) => { toast.error(err?.message || 'Production request failed'); return null; })+ .finally(() => setBusy(false));+ };++ const start = (body) => call(() => startMusicVideoProduction(projectId, body, { silent: true }));+ const resume = (runId, body = {}) => call(() => resumeMusicVideoProduction(projectId, runId, body, { silent: true }));+ const stop = (runId) => call(() => stopMusicVideoProduction(projectId, runId, { silent: true }));+ const cancel = (runId) => call(() => cancelMusicVideoProduction(projectId, runId, { silent: true }));++ return { busy, start, resume, stop, cancel };+}diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 4c843c6a20..bae26975de 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -28,6 +28,7 @@ import useMusicVideoRenderJob from '../hooks/useMusicVideoRenderJob.js';import useMusicVideoExcerpts from '../hooks/useMusicVideoExcerpts.js';import useMusicVideoRevisions from '../hooks/useMusicVideoRevisions.js';import useMusicVideoAutoReview from '../hooks/useMusicVideoAutoReview.js';+import useMusicVideoProduction from '../hooks/useMusicVideoProduction.js';import useMusicVideoModelSettings from '../hooks/useMusicVideoModelSettings.js';import useMusicVideoManualTempo from '../hooks/useMusicVideoManualTempo.js';import useMusicVideoSceneMedia from '../hooks/useMusicVideoSceneMedia.js';@@ -50,6 +51,7 @@ import { universeStyleSnapshot, moodBoardStyleSnapshot } from '../lib/musicVideoimport 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';@@ -162,6 +164,7 @@ export default function MusicVideo() {// sections, resumable from the server's checkpoint.const revisions = useMusicVideoRevisions({ project: selected, replaceProject, sceneMedia, attachRender: excerpts.attachRender });const autoReview = useMusicVideoAutoReview({ project: selected, replaceProject, submitSections: revisions.submitSections });+ const production = useMusicVideoProduction({ project: selected, replaceProject });// 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 });@@ -814,6 +817,7 @@ export default function MusicVideo() {finalVideo={finalVideo}onOpenPreview={openPreview}/>+ <ProductionPanel project={selected} production={production} /><ExcerptPanelproject={selected}rendering={excerpts.rendering}diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 5c07472169..ed2fff25d3 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -220,6 +220,20 @@ export const stopMusicVideoAutoReview = (id, runId, options = {}) =>export const cancelMusicVideoAutoReview = (id, runId, options = {}) =>request(`/music-video/${encodeURIComponent(id)}/auto-reviews/${encodeURIComponent(runId)}/cancel`, { method: 'POST', ...options });+// ---- Server-owned production run (#9066) ----+// Start body: { directive?, pool: [{ kind: 'image'|'video', mode, model? }], limits: { maxGenerations,+// maxReviewAttempts, spendCapUsd? }, providerId?, model? } → { project, run }. The run advances+// server-side and reports over the `music-video:production` socket event.+export const startMusicVideoProduction = (id, body, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/production-runs`, { method: 'POST', body: JSON.stringify(body), ...options });+// Body: { limits?: partial limits (may only RAISE), acceptBasis?: true } — acceptBasis continues a run halted `needs-replan`.+export const resumeMusicVideoProduction = (id, runId, body = {}, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/production-runs/${encodeURIComponent(runId)}/resume`, { method: 'POST', body: JSON.stringify(body), ...options });+export const stopMusicVideoProduction = (id, runId, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/production-runs/${encodeURIComponent(runId)}/stop`, { method: 'POST', ...options });+export const cancelMusicVideoProduction = (id, runId, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/production-runs/${encodeURIComponent(runId)}/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