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): let an autonomous run auto-approve production review stages
Claude3e9ddb454951
diff --git a/client/src/components/musicVideo/AutoApproveFields.jsx b/client/src/components/musicVideo/AutoApproveFields.jsxnew file mode 100644index 0000000000..caece2c661--- /dev/null+++ b/client/src/components/musicVideo/AutoApproveFields.jsx@@ -0,0 +1,50 @@+import ToggleChip from '../ui/ToggleChip.jsx';+import { AUTONOMOUS_AUTO_APPROVE_LABELS, AUTONOMOUS_AUTO_APPROVE_STAGES } from '../../lib/musicVideoAutonomous.js';++const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';++/**+ * "Auto-approve" — the Production review stages the autonomous run may approve+ * itself (art, storyboard, animated proof). Granting that is the operator's+ * authority, so picking any stage asks for the instance password once, on this+ * request; it is sent with it and never stored. `error` is the API's refusal.+ */+export default function AutoApproveFields({ idPrefix, value, onChange, password, onPasswordChange, error = null, granted = [] }) {+ const toggle = (stage) => onChange(AUTONOMOUS_AUTO_APPROVE_STAGES.filter((s) => (s === stage ? !value.includes(s) : value.includes(s))));+ return (+ <fieldset className="min-w-0 space-y-1" aria-labelledby={`${idPrefix}-auto-approve-label`}>+ <span id={`${idPrefix}-auto-approve-label`} className="block text-xs text-port-text-muted">Auto-approve (optional)</span>+ <div className="flex flex-wrap gap-1.5">+ {AUTONOMOUS_AUTO_APPROVE_STAGES.map((stage) => (+ <ToggleChip+ key={stage}+ id={`${idPrefix}-auto-approve-${stage}`}+ label={AUTONOMOUS_AUTO_APPROVE_LABELS[stage]}+ checked={value.includes(stage)}+ onToggle={() => toggle(stage)}+ />+ ))}+ </div>+ <p className="text-[11px] text-port-text-muted">+ The run approves these Production review stages itself once each has no open problems; the proof after its render finishes.+ {granted.length > 0 && ` Currently granted: ${granted.map((s) => AUTONOMOUS_AUTO_APPROVE_LABELS[s] || s).join(', ')}.`}+ </p>+ {value.length > 0 && (+ <div>+ <label htmlFor={`${idPrefix}-auto-approve-password`} className="block text-xs text-port-text-muted mb-1">Instance password to grant this</label>+ <input+ id={`${idPrefix}-auto-approve-password`}+ type="password"+ autoComplete="current-password"+ value={password}+ onChange={(e) => onPasswordChange(e.target.value)}+ aria-invalid={!!error}+ className={inputClass}+ />+ <p className="text-[11px] text-port-text-muted mt-1">Enter it yourself, once. API tokens cannot grant approval.</p>+ </div>+ )}+ {error && <p role="alert" className="text-[11px] text-port-error break-words">{error}</p>}+ </fieldset>+ );+}diff --git a/client/src/components/musicVideo/AutonomousRunPanel.jsx b/client/src/components/musicVideo/AutonomousRunPanel.jsxindex 323a73bd03..ed0b5d772f 100644--- a/client/src/components/musicVideo/AutonomousRunPanel.jsx+++ b/client/src/components/musicVideo/AutonomousRunPanel.jsx@@ -5,6 +5,7 @@ import {AUTONOMOUS_CHECKPOINT_LABELS, AUTONOMOUS_LYRICS_STEP_LABELS, AUTONOMOUS_SONG_STEP_LABELS, AUTONOMOUS_STATUS_LABELS, AUTONOMOUS_VIEWABLE_STAGES,autonomousStageOutput, autonomousStageRows, isAutonomousLive,} from '../../lib/musicVideoAutonomous.js';+import AutoApproveFields from './AutoApproveFields.jsx';// The stages that report a sub-step while they run (the server's `stages[id].step`).const STEP_LABELS = { lyrics: AUTONOMOUS_LYRICS_STEP_LABELS, song: AUTONOMOUS_SONG_STEP_LABELS };@@ -58,6 +59,10 @@ function StageOutput({ run, row, editableBelow }) {export default function AutonomousRunPanel({ project, auto, selectedStage = null, onSelectStage }) {const run = project?.autonomousRun;const [edit, setEdit] = useState(null); // { for: stage, value } — the director's edit at a checkpoint+ // "Auto-approve the rest": a grant sent with the next resume (password entered once, never kept).+ const [autoApprove, setAutoApprove] = useState([]);+ const [password, setPassword] = useState('');+ const [grantError, setGrantError] = useState(null);if (!run) return null;const rows = autonomousStageRows(run);const live = isAutonomousLive(run);@@ -73,6 +78,17 @@ export default function AutonomousRunPanel({ project, auto, selectedStage = null// A stale or hand-edited `?run-stage=` that names no finished, viewable stage opens nothing.const selectedRow = rows.find((row) => row.id === selectedStage && row.status === 'done' && AUTONOMOUS_VIEWABLE_STAGES.includes(row.id)) || null;const selected = selectedRow?.id || null;+ const grantBlocked = autoApprove.length > 0 && !password;+ // Every resume path carries the grant when one is picked; a refused password shows inline.+ const resume = (edits = {}) => {+ if (!autoApprove.length) return auto.resume(edits);+ const secret = password;+ setPassword('');+ setGrantError(null);+ return auto.resume({ ...edits, autoApprove, password: secret }, { inline: true })+ .then((res) => { setAutoApprove([]); return res; })+ .catch((err) => { setGrantError(err?.message || 'Could not grant auto-approval'); });+ };return (<section className="bg-port-card border border-port-border rounded-lg p-3 space-y-3 min-w-0" aria-label="Autonomous run">@@ -147,12 +163,12 @@ export default function AutonomousRunPanel({ project, auto, selectedStage = null</div>)}<div className="flex flex-wrap gap-2">- <button type="button" disabled={auto.busy} onClick={() => auto.resume(changed ? { [editable.key]: draft } : {})} className={`${buttonClass} bg-port-accent text-white border-port-accent`}>+ <button type="button" disabled={auto.busy || grantBlocked} onClick={() => resume(changed ? { [editable.key]: draft } : {})} className={`${buttonClass} bg-port-accent text-white border-port-accent`}><Play size={14} aria-hidden="true" /> {changed ? 'Save edit & approve' : 'Approve & continue'}</button>{awaiting === 'song' && (// Discards this song and makes a new one (a new Suno generation spends credits), then pauses here again.- <button type="button" disabled={auto.busy} onClick={() => auto.resume({ retakeSong: true })} className={buttonClass}>+ <button type="button" disabled={auto.busy || grantBlocked} onClick={() => resume({ retakeSong: true })} className={buttonClass}><RotateCcw size={14} aria-hidden="true" /> Retake song</button>)}@@ -160,10 +176,22 @@ export default function AutonomousRunPanel({ project, auto, selectedStage = null</div>)}+ {(awaiting || canRetry) && (live || run.status === 'failed') && (+ <AutoApproveFields+ idPrefix="mv-run"+ value={autoApprove}+ onChange={(next) => { setAutoApprove(next); setGrantError(null); }}+ password={password}+ onPasswordChange={setPassword}+ error={grantError}+ granted={run.brief?.autoApprove || []}+ />+ )}+{live || run.status === 'failed' ? (<div className="flex flex-wrap gap-2">{canRetry && !awaiting && (- <button type="button" disabled={auto.busy} onClick={() => auto.resume()} className={buttonClass}>+ <button type="button" disabled={auto.busy || grantBlocked} onClick={() => resume()} className={buttonClass}><Play size={14} aria-hidden="true" /> {run.status === 'failed' ? 'Retry' : 'Resume'}</button>)}diff --git a/client/src/components/musicVideo/AutonomousRunPanel.test.jsx b/client/src/components/musicVideo/AutonomousRunPanel.test.jsxindex cb7111165e..6d4f1b0225 100644--- a/client/src/components/musicVideo/AutonomousRunPanel.test.jsx+++ b/client/src/components/musicVideo/AutonomousRunPanel.test.jsx@@ -281,3 +281,44 @@ describe('AutonomousStartDrawer', () => {expect(api.startAutonomousMusicVideo.mock.calls[1][0]).toMatchObject({ songSource: 'local', localFallback: false });});});++describe('auto-approve the rest', () => {+ const refusal = () => Object.assign(new Error('Enter the instance password yourself to let the run approve production review stages.'), { status: 403, code: 'OPERATOR_REAUTH_REQUIRED' });++ it('starts with the picked stages and the password, asking for the password only once a stage is picked, and shows a refusal inline', async () => {+ api.startAutonomousMusicVideo.mockRejectedValueOnce(refusal()).mockResolvedValue({ project: { id: 'mv-new' }, run: baseRun() });+ render(<AutonomousStartDrawer open onClose={() => {}} onStarted={() => {}} />);+ fireEvent.change(screen.getByLabelText('Prompt'), { target: { value: 'p' } });+ fireEvent.change(screen.getByLabelText('Code authoring provider'), { target: { value: 'fixture-api' } });+ expect(screen.queryByLabelText('Instance password to grant this')).toBeNull();+ fireEvent.click(screen.getByLabelText('Proof', { selector: '#mv-auto-auto-approve-proof' }));+ fireEvent.click(screen.getByLabelText('Art', { selector: '#mv-auto-auto-approve-art' }));+ const submit = screen.getByRole('button', { name: /start autonomous video/i });+ expect(submit.disabled).toBe(true);+ fireEvent.change(screen.getByLabelText('Instance password to grant this'), { target: { value: 'wrong-password' } });+ fireEvent.click(submit);+ await waitFor(() => expect(screen.getByRole('alert').textContent).toContain('Enter the instance password yourself'));+ expect(api.startAutonomousMusicVideo.mock.calls[0][0]).toMatchObject({ autoApprove: ['art', 'proof'], password: 'wrong-password' });+ // The password is never kept for a retry.+ expect(screen.getByLabelText('Instance password to grant this').value).toBe('');+ fireEvent.change(screen.getByLabelText('Instance password to grant this'), { target: { value: 'synthetic-password' } });+ fireEvent.click(submit);+ await waitFor(() => expect(api.startAutonomousMusicVideo).toHaveBeenCalledTimes(2));+ expect(api.startAutonomousMusicVideo.mock.calls[1][0]).toMatchObject({ autoApprove: ['art', 'proof'], password: 'synthetic-password' });+ });++ it('resumes a parked run with "auto-approve the rest", showing a refused password next to the control', async () => {+ api.resumeAutonomousMusicVideo.mockRejectedValueOnce(refusal()).mockResolvedValue({ project: { id: 'mv-1', autonomousRun: baseRun() }, run: baseRun() });+ render(<Harness initial={baseRun({ status: 'needs-human', stage: 'produce', error: 'Review and approve the current art direction first.', brief: { origin: { kind: 'manual' }, autoApprove: [] } })} />);+ for (const stage of ['storyboard', 'art', 'proof']) fireEvent.click(screen.getByLabelText(stage[0].toUpperCase() + stage.slice(1), { selector: `#mv-run-auto-approve-${stage}` }));+ const resume = screen.getByRole('button', { name: /resume/i });+ expect(resume.disabled).toBe(true);+ fireEvent.change(screen.getByLabelText('Instance password to grant this'), { target: { value: 'wrong-password' } });+ fireEvent.click(resume);+ await waitFor(() => expect(screen.getByRole('alert').textContent).toContain('Enter the instance password yourself'));+ expect(api.resumeAutonomousMusicVideo).toHaveBeenLastCalledWith('mv-1', { autoApprove: ['art', 'storyboard', 'proof'], password: 'wrong-password' }, { silent: true });+ fireEvent.change(screen.getByLabelText('Instance password to grant this'), { target: { value: 'synthetic-password' } });+ fireEvent.click(resume);+ await waitFor(() => expect(api.resumeAutonomousMusicVideo).toHaveBeenLastCalledWith('mv-1', { autoApprove: ['art', 'storyboard', 'proof'], password: 'synthetic-password' }, { silent: true }));+ });+});diff --git a/client/src/components/musicVideo/AutonomousStartDrawer.jsx b/client/src/components/musicVideo/AutonomousStartDrawer.jsxindex 61471c52c1..dfb93399a2 100644--- a/client/src/components/musicVideo/AutonomousStartDrawer.jsx+++ b/client/src/components/musicVideo/AutonomousStartDrawer.jsx@@ -1,5 +1,6 @@import CodeAuthoringPicker from './CodeAuthoringPicker.jsx';import MediaModePicker from './MediaModePicker.jsx';+import AutoApproveFields from './AutoApproveFields.jsx';import { useState } from 'react';import { Wand2 } from 'lucide-react';import Drawer from '../Drawer.jsx';@@ -32,28 +33,42 @@ export default function AutonomousStartDrawer({ open, onClose, onStarted }) {const [authoringReady, setAuthoringReady] = useState(false);const llm = useProviderModels({ allowDefault: true, silent: true, withEffort: true });const [effort, setEffort] = useState('');+ // Kept out of the draft: the password rides one request and is cleared after it.+ const [autoApprove, setAutoApprove] = useState([]);+ const [password, setPassword] = useState('');+ const [grantError, setGrantError] = useState(null);const patch = (next) => setDraft((d) => ({ ...d, ...next }));const toggleCheckpoint = (id) => patch({checkpoints: AUTONOMOUS_CHECKPOINT_IDS.filter((c) => (c === id ? !draft.checkpoints.includes(c) : draft.checkpoints.includes(c))),});const patchSuno = (next) => setDraft((d) => ({ ...d, suno: { ...d.suno, ...next } }));const sunoModelValid = draft.songSource !== 'suno' || isSunoModelValid(draft.suno.model);- const valid = draft.prompt.trim().length > 0 && authoringReady && sunoModelValid;+ const valid = draft.prompt.trim().length > 0 && authoringReady && sunoModelValid && (!autoApprove.length || !!password);const handleSubmit = (e) => {e.preventDefault();if (!valid || submitting) return;setSubmitting(true);+ setGrantError(null);+ const secret = password;+ setPassword('');startAutonomousMusicVideo(- autonomousRequestFromDraft(draft, { providerId: llm.selectedProviderId || undefined, model: llm.selectedModel || undefined, effort: effort || undefined }),+ {+ ...autonomousRequestFromDraft(draft, { providerId: llm.selectedProviderId || undefined, model: llm.selectedModel || undefined, effort: effort || undefined }),+ ...(autoApprove.length ? { autoApprove, password: secret } : {}),+ },{ silent: true },).then(({ project }) => {setDraft(emptyAutonomousDraft());+ setAutoApprove([]);toast.success('Autonomous music video started');onStarted(project);})- .catch((err) => toast.error(err?.message || 'Failed to start the autonomous music video'))+ .catch((err) => {+ if (String(err?.code || '').startsWith('OPERATOR_')) setGrantError(err.message);+ else toast.error(err?.message || 'Failed to start the autonomous music video');+ }).finally(() => setSubmitting(false));};@@ -162,9 +177,18 @@ export default function AutonomousStartDrawer({ open, onClose, onStarted }) {/>))}</div>- <p className="text-[11px] text-port-text-muted mt-1">Production still pauses for your art, storyboard and animated proof approvals.</p>+ <p className="text-[11px] text-port-text-muted mt-1">Production still pauses for your art, storyboard and animated proof approvals unless you auto-approve them below.</p></fieldset>+ <AutoApproveFields+ idPrefix="mv-auto"+ value={autoApprove}+ onChange={(next) => { setAutoApprove(next); setGrantError(null); }}+ password={password}+ onPasswordChange={setPassword}+ error={grantError}+ />+{llm.providers.length > 0 && (<ProviderModelSelectorproviders={llm.providers}diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 59dea3ffcf..5a2d459eec 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -253,7 +253,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useMusicVideoDevArtifacts` | A project's development files ("ingredients"): import a file or a new version, add/resolve notes, approve / request changes, remove; applies the returned project. Returns `{ busy, upload, addNote, resolveNote, review, remove }`. | The Music Video Development section and viewer drawer. || `useMusicVideoVocalSeparation` | "Separate vocals" (demucs) as a `useSseJobSlot`: `start(projectId)` for the button, `run(projectId)` as a promise resolving with the project carrying its new stem (or null on failure/cancel), `stageLabel` for install/separation progress, `onSeparated(projectId, project)` on success. | The Music Video vocal-stem control and the autopilot kickoff. || `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. |-| `useAutonomousMusicVideo` | Fully-autonomous run (prompt → lyrics → Suno song → video): applies the project pushed on `music-video:autonomous` and toasts the outcomes that need the director (checkpoint waiting, needs you, finished, failed). Returns `{ busy, resume(edits?), stop(), cancel() }`. | The Music Video autonomous run panel. |+| `useAutonomousMusicVideo` | Fully-autonomous run (prompt → lyrics → Suno song → video): applies the project pushed on `music-video:autonomous` and toasts the outcomes that need the director (checkpoint waiting, needs you, finished, failed). Returns `{ busy, resume(edits?, { inline }?), stop(), cancel() }` (an `inline` resume rejects instead of toasting, for errors shown next to the control). | The Music Video autonomous run panel. || `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. |diff --git a/client/src/hooks/useAutonomousMusicVideo.js b/client/src/hooks/useAutonomousMusicVideo.jsindex e9c312ed8c..2d246ad5d7 100644--- a/client/src/hooks/useAutonomousMusicVideo.js+++ b/client/src/hooks/useAutonomousMusicVideo.js@@ -20,7 +20,7 @@ const OUTCOME_TOASTS = {* it applies the project the server pushes over `music-video:autonomous` (no* polling) and toasts the outcomes that need the director.*- * Returns `{ busy, resume(edits?), stop(), cancel() }`.+ * Returns `{ busy, resume(edits?, { inline }?), stop(), cancel() }`; an `inline` resume rejects instead of toasting.*/export default function useAutonomousMusicVideo({ project, replaceProject } = {}) {const projectId = project?.id || null;@@ -47,7 +47,8 @@ export default function useAutonomousMusicVideo({ project, replaceProject } = {}return () => socket.off('music-video:autonomous', onAutonomous);}, [projectId]);- const call = (request) => {+ // `inline: true` leaves the error to the caller (shown next to the control) instead of toasting it.+ const call = (request, { inline = false } = {}) => {setBusy(true);return request().then((res) => {@@ -55,11 +56,15 @@ export default function useAutonomousMusicVideo({ project, replaceProject } = {}if (res?.run) lastStatus.current = { id: res.run.id, status: res.run.status };return res;})- .catch((err) => { toast.error(err?.message || 'Autonomous run request failed'); return null; })+ .catch((err) => {+ if (inline) throw err;+ toast.error(err?.message || 'Autonomous run request failed');+ return null;+ }).finally(() => setBusy(false));};- const resume = (edits = {}) => call(() => resumeAutonomousMusicVideo(projectId, edits, { silent: true }));+ const resume = (edits = {}, options = {}) => call(() => resumeAutonomousMusicVideo(projectId, edits, { silent: true }), options);const stop = () => call(() => stopAutonomousMusicVideo(projectId, { silent: true }));const cancel = () => call(() => cancelAutonomousMusicVideo(projectId, { silent: true }));diff --git a/client/src/lib/musicVideoAutonomous.js b/client/src/lib/musicVideoAutonomous.jsindex 1042a074cb..0c6fd1badf 100644--- a/client/src/lib/musicVideoAutonomous.js+++ b/client/src/lib/musicVideoAutonomous.js@@ -15,13 +15,16 @@ export const AUTONOMOUS_SONG_SOURCE_LABELS = Object.freeze({local: 'Local engine (Music Studio)',});-export { AUTONOMOUS_CHECKPOINT_IDS, AUTONOMOUS_SONG_SOURCES, SUNO_LIMITS, SUNO_VOCAL_GENDERS, autonomousMedium } from '../../../server/lib/musicVideoAutonomous.js';+export { AUTONOMOUS_AUTO_APPROVE_STAGES, AUTONOMOUS_CHECKPOINT_IDS, AUTONOMOUS_SONG_SOURCES, SUNO_LIMITS, SUNO_VOCAL_GENDERS, autonomousMedium } from '../../../server/lib/musicVideoAutonomous.js';export const AUTONOMOUS_CHECKPOINT_LABELS = Object.freeze({...Object.fromEntries(AUTONOMOUS_STAGES.map((stage) => [stage.id, stage.label])),cast: 'Cast & Sets',});+// Production review stages the run may approve itself (`brief.autoApprove`).+export const AUTONOMOUS_AUTO_APPROVE_LABELS = Object.freeze({ art: 'Art', storyboard: 'Storyboard', proof: 'Proof' });+export const AUTONOMOUS_STATUS_LABELS = Object.freeze({running: 'Running', 'awaiting-approval': 'Waiting for your approval', 'needs-human': 'Needs you', stopped: 'Paused',completed: 'Finished', failed: 'Failed', canceled: 'Cancelled',diff --git a/docs/features/music-video-autonomous.md b/docs/features/music-video-autonomous.mdindex 7573f36d3d..f6091c9fbf 100644--- a/docs/features/music-video-autonomous.md+++ b/docs/features/music-video-autonomous.md@@ -82,6 +82,8 @@ Use **Render feasibility prototype — unapproved** to test a current authored cApproval and feedback resolution require the operator to re-enter the existing instance password. Agent bearer credentials cannot authorize those operations. Password-free installs can draft and prototype; setting a password is required before production approval. This separates delegated agent credentials from operator authority; it does not defend against someone who controls the host or knows the password.+**Auto-approve the rest.** A run can be told once which of these stages it may approve itself: `autoApprove: ['art', 'storyboard', 'proof']` (any subset) on the start request or on `POST /api/music-video/:id/autonomous/resume`, together with `password` — the instance password, entered by the operator once on that request with the same checks as an approval (no `Authorization` header; a missing or wrong password is 403 `OPERATOR_REAUTH_REQUIRED`). The password is never stored; the run records the grant as `brief.autoApprove` and `brief.autoApproveAuthorizedAt`. A resume's list replaces the stored grant (`[]` clears it, no password needed). In **Produce** the run then approves art and the storyboard (`approvedBy: 'autopilot'`) only when that stage's readiness report has no problems — anything a human must fix, such as provisional lyric timings, still parks the run `needs-human` — and, for a code-rendered video, waits for the proof excerpt to finish rendering (up to 90 minutes; a failed render fails the run) and approves that exact excerpt with an `autoApproved` proof review instead of a watched-with-audio record. The approval HTTP route never accepts an `autoApproved` review. Footage runs still approve their proof in production review. Start drawer and run panel offer the same choice as **Auto-approve** chips with a password field.+External draft preparation also requires operator reauthentication. PortOS never submits a final post: review and publish on the destination platform, then record the resulting link. Existing projects and assets remain intact, but an older project's final render now requires the same production review.The local browser acceptance test (`server/routes/musicVideoProductionReview.browser.test.js`) exercises the real React controls, approval routes, native code renderer, ffmpeg output and video playback with synthetic data. It requires Chrome, ffmpeg and installed client dependencies; server-only CI skips this cross-workspace check. API and orchestration tests run independently of those visual-test prerequisites.@@ -129,9 +131,9 @@ The Suno adapter fills the form through `placeholder` / role selectors and reads| Method | Path | ||---|---|---|-| `POST` | `/api/music-video/autonomous` | Start (202 `{ project, run }`). Body: `prompt` plus optional `songSource` (`suno` default, or `local`), `localFallback`, `suno` (Suno form options), `tools`, `models` (per-tool model pin), `budgetUsd`, `limits`, `checkpoints`, `instrumental`, `guidance`, `providerId`/`model`/`effort` (the direction LLM), `llmStages` (per-stage LLM pins), `lyricsReview`, `authoring` (code-rendered video). |+| `POST` | `/api/music-video/autonomous` | Start (202 `{ project, run }`). Body: `prompt` plus optional `songSource` (`suno` default, or `local`), `localFallback`, `suno` (Suno form options), `tools`, `models` (per-tool model pin), `budgetUsd`, `limits`, `checkpoints`, `instrumental`, `guidance`, `providerId`/`model`/`effort` (the direction LLM), `llmStages` (per-stage LLM pins), `lyricsReview`, `authoring` (code-rendered video), `autoApprove` (+ `password`, see Production review). || `GET` | `/api/music-video/:id/autonomous` | The run. |-| `POST` | `/api/music-video/:id/autonomous/resume` | Approve the checkpoint, retry the stage that stopped, or resume an interrupted run. Optional `lyrics`, `style`, `suno` edits; `retakeSong: true` at the song checkpoint. |+| `POST` | `/api/music-video/:id/autonomous/resume` | Approve the checkpoint, retry the stage that stopped, or resume an interrupted run. Optional `lyrics`, `style`, `suno` edits; `retakeSong: true` at the song checkpoint; `autoApprove` (+ `password`) to grant auto-approval of production review stages. || `POST` | `/api/music-video/:id/autonomous/stop` / `cancel` | Pause / cancel (also stops/cancels its production run). |Progress is pushed over the `music-video:autonomous` socket event (`{ projectId, runId, run, project }`).diff --git a/server/lib/musicVideoAutonomous.js b/server/lib/musicVideoAutonomous.jsindex 3667d33eb9..2304bdc8ce 100644--- a/server/lib/musicVideoAutonomous.js+++ b/server/lib/musicVideoAutonomous.js@@ -58,6 +58,15 @@ export const AUTONOMOUS_PROMPT_MAX = 4000;export const AUTONOMOUS_NAME_MAX = 200;export const AUTONOMOUS_ORIGINS = Object.freeze(['manual', 'schedule']);+// The Production review stages a run may approve by itself once the operator+// grants it (`brief.autoApprove`, set with the instance password on start or+// resume). In review order; readiness checks still gate every one.+export const AUTONOMOUS_AUTO_APPROVE_STAGES = Object.freeze(['art', 'storyboard', 'proof']);++/** Known auto-approve stages, de-duplicated, in review order. */+export const normalizeAutoApprove = (list) => AUTONOMOUS_AUTO_APPROVE_STAGES+ .filter((stage) => Array.isArray(list) && list.includes(stage));+export const AUTONOMOUS_DEFAULT_LIMITS = Object.freeze({ maxGenerations: 40, maxReviewAttempts: 3 });export const AUTONOMOUS_LIMIT_BOUNDS = Object.freeze({maxGenerations: Object.freeze({ min: 1, max: 500 }),diff --git a/server/lib/musicVideoAutonomous.test.js b/server/lib/musicVideoAutonomous.test.jsindex 18342b0a9a..27068bd18c 100644--- a/server/lib/musicVideoAutonomous.test.js+++ b/server/lib/musicVideoAutonomous.test.js@@ -96,6 +96,19 @@ describe('normalizeAutonomousBrief', () => {expect(() => musicVideoAutonomousStartSchema.parse({ prompt: 'p', tools: ['nope'] })).toThrow();expect(() => musicVideoAutonomousStartSchema.parse({ prompt: '' })).toThrow();});++ it('accepts an auto-approve grant on start and resume: known stages only, de-duplicated in review order, never in the scheduled params', () => {+ expect(musicVideoAutonomousStartSchema.parse({ prompt: 'p', autoApprove: ['proof', 'art', 'proof', 'art'], password: 'example-password' }))+ .toMatchObject({ autoApprove: ['art', 'proof'], password: 'example-password' });+ expect(musicVideoAutonomousResumeSchema.parse({ autoApprove: ['storyboard', 'storyboard'] })).toEqual({ autoApprove: ['storyboard'] });+ expect(musicVideoAutonomousResumeSchema.parse({ autoApprove: [] })).toEqual({ autoApprove: [] });+ for (const autoApprove of [['render'], 'art', [1]]) {+ expect(() => musicVideoAutonomousResumeSchema.parse({ autoApprove }), JSON.stringify(autoApprove)).toThrow();+ }+ expect(() => musicVideoAutonomousStartSchema.parse({ prompt: 'p', password: '' })).toThrow();+ // A grant needs the operator's password on that request, so a saved schedule cannot carry one.+ expect(normalizeAutopilotParams({ autoApprove: ['art'] })).not.toHaveProperty('autoApprove');+ });});describe('tool picks → how the video is made', () => {diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 5eb29c9d5b..c8fc2cc09d 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -32,6 +32,7 @@ import {MUSIC_VIDEO_CHECKIN_MODES,} from './musicVideoAutomation.js';import {+ AUTONOMOUS_AUTO_APPROVE_STAGES,AUTONOMOUS_CHECKPOINT_IDS,AUTONOMOUS_LIMIT_BOUNDS,AUTONOMOUS_NAME_MAX,@@ -41,6 +42,7 @@ import {SUNO_LIMITS,SUNO_MODEL_PATTERN,SUNO_VOCAL_GENDERS,+ normalizeAutoApprove,} from './musicVideoAutonomous.js';import { MUSCRIPTOR_MODELS } from './muscriptorModels.js';import { IMAGE_GEN_MODES, VIDEO_GEN_MODES } from './generationModes.js';@@ -786,6 +788,16 @@ export const musicVideoLlmStagesSchema = z.object(Object.fromEntries(MUSIC_VIDEO_LLM_STAGES.map((stage) => [stage, musicVideoLlmSchema.nullable().optional()]),)).strict();+// Production review stages the run may approve by itself (de-duplicated, in+// review order). A non-empty list is approval authority, so the request must+// carry the instance password once (checked by the route, never stored); an+// empty list on resume clears the grant.+const musicVideoAutoApproveFields = {+ autoApprove: z.array(z.enum(AUTONOMOUS_AUTO_APPROVE_STAGES)).max(AUTONOMOUS_AUTO_APPROVE_STAGES.length * 4)+ .transform(normalizeAutoApprove).optional(),+ password: z.string().min(1).max(1024).optional(),+};+// The alternate entry point: no track, style or board is picked up front. Tool// ids are the same catalog the autopilot brief uses; `checkpoints` names the// stages that park for approval (none = fully unattended).@@ -826,6 +838,7 @@ export const musicVideoAutonomousStartSchema = z.object({ideaTitle: z.string().max(200).nullable().optional(),}).strict().optional(),suno: musicVideoSunoOptionsSchema.nullable().optional(),+ ...musicVideoAutoApproveFields,}).strict();// Resume a parked/failed run, or approve the checkpoint it is waiting on.@@ -837,6 +850,8 @@ export const musicVideoAutonomousResumeSchema = z.object({suno: musicVideoSunoOptionsSchema.optional(),// At the song checkpoint: discard the song and generate a new one.retakeSong: z.boolean().optional(),+ // Replace the brief's auto-approve grant ("auto-approve the rest").+ ...musicVideoAutoApproveFields,}).strict();// A generation kickoff that failed before reaching the queue (#9011) — namesdiff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 447a20c639..6b36961542 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -897,9 +897,18 @@ router.post('/:id/production-runs/:runId/cancel', asyncHandler(async (req, res)// (brief → lyrics → mood board → Suno → analysis → production) and reports over// `music-video:autonomous`. Optional checkpoints park it for approval. Only these// explicit requests (or the scheduled task) begin work — nothing at boot does.+// A non-empty `autoApprove` lets the run approve those Production review stages+// itself. That is the operator's authority, so the request re-enters the+// instance password once (same check as an approval; never stored).+const authorizeAutoApprove = async (req, autoApprove) => {+ if (!autoApprove?.length) return false;+ await requireProductionOperator(req);+ return true;+};router.post('/autonomous', asyncHandler(async (req, res) => {- const input = validateRequest(musicVideoAutonomousStartSchema, req.body || {});- res.status(202).json(await startAutonomousVideo(input));+ const { password: _password, ...input } = validateRequest(musicVideoAutonomousStartSchema, req.body || {});+ const autoApproveAuthorized = await authorizeAutoApprove(req, input.autoApprove);+ res.status(202).json(await startAutonomousVideo(input, { autoApproveAuthorized }));}));router.get('/:id/autonomous', asyncHandler(async (req, res) => {@@ -908,8 +917,9 @@ router.get('/:id/autonomous', asyncHandler(async (req, res) => {// Resume a parked/failed/interrupted run, or approve the checkpoint it waits on.router.post('/:id/autonomous/resume', asyncHandler(async (req, res) => {- const edits = validateRequest(musicVideoAutonomousResumeSchema, req.body || {});- res.json(await resumeAutonomousVideo(req.params.id, edits));+ const { password: _password, ...edits } = validateRequest(musicVideoAutonomousResumeSchema, req.body || {});+ const autoApproveAuthorized = await authorizeAutoApprove(req, edits.autoApprove);+ res.json(await resumeAutonomousVideo(req.params.id, edits, { autoApproveAuthorized }));}));router.post('/:id/autonomous/stop', asyncHandler(async (req, res) => {diff --git a/server/routes/musicVideoAutonomous.test.js b/server/routes/musicVideoAutonomous.test.jsindex 1feb18e734..984e33dc67 100644--- a/server/routes/musicVideoAutonomous.test.js+++ b/server/routes/musicVideoAutonomous.test.js@@ -218,6 +218,30 @@ describe('POST /api/music-video/autonomous', () => {});});+ it('grants auto-approve only with the operator password: none, a wrong one or an agent credential is 403 and changes nothing', async () => {+ const res = await begin({ prompt: 'p', checkpoints: ['lyrics'] });+ const id = res.body.project.id;+ await settle();+ const resume = (body) => request(app).post(`/api/music-video/${id}/autonomous/resume`).send(body);+ for (const body of [{ autoApprove: ['art', 'storyboard'] }, { autoApprove: ['proof'], password: 'wrong' }]) {+ const refused = await resume(body);+ expect(refused.status, JSON.stringify(body)).toBe(403);+ expect(refused.body.code).toBe('OPERATOR_REAUTH_REQUIRED');+ }+ const agent = await request(app).post(`/api/music-video/${id}/autonomous/resume`).set('authorization', 'Bearer synthetic-agent')+ .send({ autoApprove: ['art'], password: 'synthetic-operator-password' });+ expect(agent.status).toBe(403);+ expect((await begin({ prompt: 'p', autoApprove: ['art'] })).status).toBe(403);+ expect((await get(id))).toMatchObject({ status: 'awaiting-approval', brief: { autoApprove: [] } });++ const granted = await resume({ autoApprove: ['storyboard', 'art', 'art'], password: 'synthetic-operator-password' });+ expect(granted.status).toBe(200);+ await settle();+ const stored = await projects.getProject(id);+ expect(stored.autonomousRun.brief).toMatchObject({ autoApprove: ['art', 'storyboard'], autoApproveAuthorizedAt: expect.any(String) });+ expect(JSON.stringify(stored)).not.toContain('synthetic-operator-password');+ });+it('cancels a live run, and refuses to cancel or resume one that is finished or absent', async () => {const res = await begin({ prompt: 'p', checkpoints: ['lyrics'] });const id = res.body.project.id;diff --git a/server/routes/musicVideoProductionReview.test.js b/server/routes/musicVideoProductionReview.test.jsindex 7c3413b83e..ae9dfa7994 100644--- a/server/routes/musicVideoProductionReview.test.js+++ b/server/routes/musicVideoProductionReview.test.js@@ -36,7 +36,7 @@ vi.mock('../services/musicVideo/excerptRender.js', async original => ({ ...awaitconst { default: router } = await import('./musicVideo.js');const store = await import('../services/musicVideo/projects.js');const { saveGeneratedDevArtifact } = await import('../services/musicVideo/devArtifactService.js');-const { assertProductionApproval } = await import('../services/musicVideo/productionReview.js');+const { assertProductionApproval, approveProductionStage, productionReviewBasis } = await import('../services/musicVideo/productionReview.js');const app = express();app.use(express.json()); app.use('/api/music-video', router); app.use(errorMiddleware);let project, base, draft;@@ -155,6 +155,25 @@ describe('human-reviewed Music Video workflow', () => {expect((await request(app).post(`${base}/render`).send({})).status).toBe(409);});+ it('accepts an autonomous run\'s auto-approved proof for the current excerpt only, and never over HTTP', async () => {+ expect((await approve('art')).status).toBe(200);+ expect((await approve('storyboard')).status).toBe(200);+ expect((await request(app).post(`${base}/production-review/proof`).send({ startSec: 0, endSec: 20 })).status).toBe(202);+ const autoReview = { autoApproved: true, watchedWithAudio: false, excerptId: 'proof-fixture', filename: 'synthetic-proof.mp4',+ energyComparison: 'Auto-approved by the autonomous run (brief.autoApprove).', timecodedNotes: '0:00 auto-approved' };+ // The operator route cannot claim the waiver, even with the password.+ expect((await approve('proof', { proofReview: autoReview })).status).toBe(400);+ const current = await store.getProject(project.id);+ const input = { stage: 'proof', basis: productionReviewBasis(current).proof, approvedBy: 'autopilot' };+ expect(() => approveProductionStage(current, { ...input, proofReview: { ...autoReview, excerptId: 'older-proof' } }))+ .toThrow(expect.objectContaining({ code: 'MUSIC_VIDEO_REVIEW_STALE' }));+ expect(() => approveProductionStage(current, { ...input, proofReview: { ...autoReview, autoApproved: 'yes' } }))+ .toThrow(expect.objectContaining({ code: 'MUSIC_VIDEO_PROOF_REVIEW_REQUIRED' }));+ const approved = approveProductionStage(current, { ...input, proofReview: autoReview });+ expect(approved.productionReview.approvals.proof).toMatchObject({ approvedBy: 'autopilot', proofReview: { autoApproved: true } });+ expect(() => assertProductionApproval(approved)).not.toThrow();+ });+it('distinguishes provisional/zero-length/missing lyrics from an explicit instrumental', async () => {await approve('art');await save({ ...draft, timingStatus: 'provisional' });diff --git a/server/services/musicVideo/autonomousService.js b/server/services/musicVideo/autonomousService.jsindex 9a3692643c..166ee2ecf9 100644--- a/server/services/musicVideo/autonomousService.js+++ b/server/services/musicVideo/autonomousService.js@@ -32,6 +32,14 @@ import { assertProductionApproval, productionReadiness, productionProofNeedsRend* Production is delegated: `produce` starts the server-owned production run (or* the code render) and finishes when that reports back over the `production`* event. Only explicit start/resume requests begin work.+ *+ * Production review (art → storyboard → proof) is a human gate: `produce` parks+ * `needs-human` until it is approved. `brief.autoApprove` lets the operator hand+ * the listed stages to the run instead — granted once, with the instance+ * password, on the start or resume request (the route checks it; the service+ * only accepts a grant the route authorized). An auto-approval still needs a+ * clean readiness report for that stage, and the proof is approved only once+ * its excerpt has actually rendered.*/import { randomUUID } from 'crypto';@@ -47,6 +55,7 @@ import {autonomousMedium,autonomousPool,nextAutonomousStage,+ normalizeAutoApprove,normalizeAutonomousBrief,normalizeSunoOptions,sunoSongFields,@@ -83,6 +92,9 @@ const defaults = {acceptDocument: async (...args) => (await import('./documentGeneration.js')).acceptMixedMediaDocument(...args),generateCode: async (...args) => (await import('./codeGeneration.js')).generateMusicVideoCode(...args),renderVideo: async (...args) => (await import('./render.js')).renderMusicVideo(...args),+ // The operator route's persistence path, minus its password check (the grant was checked on start/resume).+ approveProductionReview: async (...args) => (await import('./productionReviewService.js')).approveProductionReview(...args),+ wait: (ms) => new Promise((resolve) => { setTimeout(resolve, ms); }),};let deps = { ...defaults };export function __setAutonomousDepsForTests(overrides) { deps = { ...defaults, ...overrides }; }@@ -131,6 +143,75 @@ async function patchRun(projectId, fn) {const stagePatch = (run, stage, patch) => ({ stages: { [stage]: { ...run.stages[stage], ...patch } } });+// ---- production review auto-approval (brief.autoApprove) --------------------------++const PROOF_POLL_MS = 5_000;+const PROOF_WAIT_MAX_MS = 90 * 60_000;+const autoApproves = (run, stage) => normalizeAutoApprove(run.brief.autoApprove).includes(stage);++/**+ * The brief fields for an auto-approve request: none when it lists no stage,+ * else the stages plus when the operator granted them. A non-empty list the+ * route did not authorize (operator password) is refused.+ */+function autoApproveGrant(list, authorized) {+ const autoApprove = normalizeAutoApprove(list);+ if (!autoApprove.length) return { autoApprove: [], autoApproveAuthorizedAt: null };+ if (!authorized) throw runError(403, 'OPERATOR_REAUTH_REQUIRED', 'Enter the instance password yourself to let the run approve production review stages. Agent/API credentials cannot grant it.');+ return { autoApprove, autoApproveAuthorizedAt: new Date().toISOString() };+}++/** Approve `stage` for the run when the brief allows it and its readiness is clean; returns the fresh project. */+async function autoApproveStage(project, run, stage) {+ if (!autoApproves(run, stage)) return project;+ const readiness = productionReadiness(project);+ if (readiness[stage].approved || readiness[stage].problems.length) return project;+ await deps.approveProductionReview(project.id, { stage, basis: readiness.basis[stage], approvedBy: 'autopilot' });+ console.log(`🤖 Autonomous music video ${short(run.id)} auto-approved ${stage} (brief.autoApprove)`);+ return getProject(project.id);+}++/**+ * Wait for the current proof excerpt to finish rendering (polls the record; the+ * excerpt job runs on its own). Stops when the run is stopped or canceled; a+ * failed render or a render past the cap fails the stage.+ */+async function awaitProofExcerpt(projectId, run) {+ const polls = Math.ceil(PROOF_WAIT_MAX_MS / PROOF_POLL_MS);+ for (let i = 0; ; i++) {+ const project = await getProject(projectId);+ const latest = projectAutonomousRun(project);+ if (latest?.id !== run.id || latest.status !== 'running' || latest.processId !== PROCESS_ID) {+ throw runError(409, 'NOT_RUNNING', 'The run was stopped while its proof rendered');+ }+ const excerptId = project.productionReview?.proof?.excerptId;+ const excerpt = excerptId ? (project.excerpts || []).find((e) => e.id === excerptId) : null;+ if (excerpt?.status === 'complete') return project;+ if (excerpt && excerpt.status !== 'rendering') {+ throw runError(500, 'PROOF_RENDER_FAILED', `The proof render failed: ${trimTo(excerpt.error || excerpt.status, 400)}`);+ }+ if (i >= polls) throw runError(504, 'PROOF_RENDER_TIMEOUT', 'The proof render did not finish within 90 minutes');+ await deps.wait(PROOF_POLL_MS);+ }+}++/** Approve the rendered proof for the run (brief lists `proof`); readiness problems are left for the assert to park on. */+async function autoApproveProof(projectId, run) {+ const project = await awaitProofExcerpt(projectId, run);+ const readiness = productionReadiness(project);+ if (readiness.proof.approved || readiness.proof.problems.length) return;+ const excerptId = project.productionReview.proof.excerptId;+ const excerpt = project.excerpts.find((e) => e.id === excerptId);+ await deps.approveProductionReview(projectId, {+ stage: 'proof', basis: readiness.basis.proof, approvedBy: 'autopilot',+ proofReview: {+ autoApproved: true, watchedWithAudio: false, excerptId, filename: excerpt.filename,+ energyComparison: 'Auto-approved by the autonomous run (brief.autoApprove).', timecodedNotes: '0:00 auto-approved',+ },+ });+ console.log(`🤖 Autonomous music video ${short(run.id)} auto-approved proof ${short(excerptId)} (brief.autoApprove)`);+}+// ---- stage executors -------------------------------------------------------------// Each returns `{ output }` (merged into run.output) or `{ output, wait: true }`// when the stage's completion arrives later (production).@@ -316,6 +397,14 @@ const STAGES = {}await prepareProductionReview(project.id);project = await getProject(project.id);+ const artWasApproved = productionReadiness(project).art.approved;+ project = await autoApproveStage(project, run, 'art');+ if (!artWasApproved && productionReadiness(project).art.approved) {+ // Preparing stops at the art gate; with art approved it drafts the storyboard.+ await prepareProductionReview(project.id);+ project = await getProject(project.id);+ }+ project = await autoApproveStage(project, run, 'storyboard');assertProductionApproval(project, 'storyboard');// The authoring stage's pin, else the run's code-authoring pin taken as// given (production checks it exactly), else the direction LLM.@@ -334,6 +423,7 @@ const STAGES = {if (productionProofNeedsRender(project, readiness.basis.proof)) {await renderProductionProof(project.id, productionProofWindow(project));}+ if (autoApproves(run, 'proof')) await autoApproveProof(project.id, run);assertProductionApproval(await getProject(project.id));const render = await deps.renderVideo(project.id);return { output: { renderJobId: render?.jobId || null } };@@ -423,8 +513,8 @@ const emptyStages = () => Object.fromEntries(AUTONOMOUS_STAGE_IDS.map((id) => [i* Start a run from one prompt: creates the project (autonomous mode, no track* yet) and begins the pipeline in the background. Returns `{ project, run }`.*/-export async function startAutonomousVideo(input) {- const brief = normalizeAutonomousBrief(input);+export async function startAutonomousVideo(input, { autoApproveAuthorized = false } = {}) {+ const brief = { ...normalizeAutonomousBrief(input), ...autoApproveGrant(input?.autoApprove, autoApproveAuthorized) };if (!brief.prompt) throw runError(400, 'VALIDATION_ERROR', 'A prompt is required');const now = new Date().toISOString();const created = await deps.createProject({@@ -458,7 +548,7 @@ export async function startAutonomousVideo(input) {updatedAt: now,};const out = await mutateProjectRecord(created.id, (current) => ({ project: { ...current, autonomousRun: run }, run }));- console.log(`🎬 Autonomous music video ${short(run.id)} started (${brief.tools.length} tool(s), ${brief.checkpoints.length} checkpoint(s)${brief.origin.kind === 'schedule' ? ', scheduled' : ''})`);+ console.log(`🎬 Autonomous music video ${short(run.id)} started (${brief.tools.length} tool(s), ${brief.checkpoints.length} checkpoint(s)${brief.autoApprove.length ? `, auto-approve ${brief.autoApprove.join('/')}` : ''}${brief.origin.kind === 'schedule' ? ', scheduled' : ''})`);publish(out.project, out.run);advanceInBackground(created.id);return { project: out.project, run: presentAutonomousRun(out.run) };@@ -496,9 +586,11 @@ const assertAtSongCheckpoint = (run) => {// credit-spending choice) or a new local render on a new track.const SONG_OUTPUT_KEYS = ['trackId', 'sunoSongIds', 'songSource', 'songFallbackReason', 'localTrackId', 'localSongJobId'];-export async function resumeAutonomousVideo(projectId, edits = {}) {+export async function resumeAutonomousVideo(projectId, edits = {}, { autoApproveAuthorized = false } = {}) {const { run } = await requireRun(projectId);assertResumable(run);+ // "Auto-approve the rest": replaces the brief's grant (an empty list clears it).+ const grant = edits.autoApprove !== undefined ? autoApproveGrant(edits.autoApprove, autoApproveAuthorized) : null;const retake = edits.retakeSong === true;if (retake) assertAtSongCheckpoint(run);// Stop changes the record immediately, but its stage may still be settling.@@ -518,7 +610,11 @@ export async function resumeAutonomousVideo(projectId, edits = {}) {const stage = retake ? 'song' : r.stage;return {status: 'running', awaiting: null, error: null, errorCode: null, processId: PROCESS_ID,- ...(edits.suno ? { brief: { ...r.brief, suno: normalizeSunoOptions({ ...r.brief.suno, ...edits.suno }) } } : {}),+ ...(edits.suno || grant ? { brief: {+ ...r.brief,+ ...(edits.suno ? { suno: normalizeSunoOptions({ ...r.brief.suno, ...edits.suno }) } : {}),+ ...(grant || {}),+ } } : {}),output: {...(retake ? Object.fromEntries(SONG_OUTPUT_KEYS.map((key) => [key, null])) : {}),...(typeof edits.lyrics === 'string' ? { lyrics: edits.lyrics } : {}),diff --git a/server/services/musicVideo/autonomousService.test.js b/server/services/musicVideo/autonomousService.test.jsindex de27ee898d..18ea4cdf30 100644--- a/server/services/musicVideo/autonomousService.test.js+++ b/server/services/musicVideo/autonomousService.test.js@@ -723,3 +723,104 @@ it('parks standalone code at real human gates and replaces a stale proof beforeexpect(doubles.generateDocument).toHaveBeenCalledOnce();expect(doubles.startProduction).not.toHaveBeenCalled();});++describe('auto-approve the rest (brief.autoApprove)', () => {+ const PROOF_NOTE = 'Auto-approved by the autonomous run (brief.autoApprove).';+ let actual;+ beforeEach(async () => {+ creativeReview.real = true;+ actual = await vi.importActual('./productionReview.js');+ // The service's persistence path, minus the operator check the route owns.+ doubles.approveProductionReview = stub('approve', async (id, input) => {+ store.set(id, clone(actual.approveProductionStage(clone(store.get(id)), input)));+ });+ doubles.wait = vi.fn(async () => {});+ service.__setAutonomousDepsForTests(doubles);+ });+ const reviewFixture = (draft = {}) => doubles.analyzeSong.mockImplementation(async () => {+ Object.assign(store.get('mv-auto'), {+ audioAnalysis: { durationSec: 20, sections: [{ id: 'chorus', label: 'Chorus', startSec: 0, endSec: 20 }] },+ scenes: [{ sceneId: 'shot', startSec: 0, endSec: 20, label: 'Chorus' }],+ devArtifacts: [{ id: 'guide', version: 1, file: 'guide.html', mimeType: 'text/html' }],+ productionReview: { draft: {+ cast: 'Paper dancer', environments: 'Theatre', visualLanguage: 'Ink silhouettes', motionLanguage: 'Slow orbit',+ guideArtifactId: 'guide', lyricsMode: 'instrumental', timingNotes: 'Synthetic instrumental master checked.',+ storyboard: [{ sceneId: 'shot', lyricCueIds: [], action: 'Dancer unfolds', staging: 'Wide theatre', camera: 'Orbit', transition: 'Fade' }],+ ...draft,+ } },+ });+ });+ const approvals = () => store.get('mv-auto').productionReview.approvals || {};++ it('is granted only with operator authority, on start or on a resume of a parked run, and then approves clean art and storyboard itself', async () => {+ reviewFixture();+ await expect(service.startAutonomousVideo({ prompt: 'p', tools: ['image:local'], autoApprove: ['art'] }))+ .rejects.toMatchObject({ status: 403, code: 'OPERATOR_REAUTH_REQUIRED' });+ expect(store.size).toBe(0);++ await service.startAutonomousVideo({ prompt: 'p', tools: ['image:local'] });+ await settled('needs-human');+ expect(runOf()).toMatchObject({ errorCode: 'MUSIC_VIDEO_APPROVAL_REQUIRED', brief: { autoApprove: [], autoApproveAuthorizedAt: null } });+ await expect(service.resumeAutonomousVideo('mv-auto', { autoApprove: ['art', 'storyboard'] }))+ .rejects.toMatchObject({ status: 403, code: 'OPERATOR_REAUTH_REQUIRED' });+ expect(runOf()).toMatchObject({ status: 'needs-human', brief: { autoApprove: [] } });+ expect(doubles.approveProductionReview).not.toHaveBeenCalled();++ await service.resumeAutonomousVideo('mv-auto', { autoApprove: ['art', 'storyboard'] }, { autoApproveAuthorized: true });+ await vi.waitFor(() => expect(doubles.startProduction).toHaveBeenCalledOnce());+ expect(runOf().brief).toMatchObject({ autoApprove: ['art', 'storyboard'], autoApproveAuthorizedAt: expect.any(String) });+ expect(doubles.approveProductionReview.mock.calls.map(([, input]) => input.stage)).toEqual(['art', 'storyboard']);+ expect(approvals()).toMatchObject({ art: { approvedBy: 'autopilot' }, storyboard: { approvedBy: 'autopilot' } });+ expect(approvals().proof).toBeUndefined();+ expect(actual.productionReadiness(store.get('mv-auto')).storyboard.approved).toBe(true);+ });++ it('never approves past a readiness problem: the run parks for a human at that stage', async () => {+ reviewFixture({ timingNotes: '' });+ await service.startAutonomousVideo({ prompt: 'p', tools: ['image:local'], autoApprove: ['art', 'storyboard'] }, { autoApproveAuthorized: true });+ await settled('needs-human');+ expect(runOf()).toMatchObject({ errorCode: 'MUSIC_VIDEO_APPROVAL_REQUIRED', error: 'Explain and confirm the instrumental exception.' });+ expect(approvals().art).toMatchObject({ approvedBy: 'autopilot' });+ expect(approvals().storyboard).toBeUndefined();+ expect(doubles.startProduction).not.toHaveBeenCalled();+ });++ const proofRenders = async (outcome) => {+ const { renderProductionProof } = await import('./productionReviewService.js');+ renderProductionProof.mockImplementation(async (_id, window) => {+ const project = store.get('mv-auto');+ project.excerpts = [{ id: 'proof-1', status: 'rendering', filename: null }];+ project.productionReview.proof = { ...window, excerptId: 'proof-1' };+ project.productionReview.proof.basis = actual.productionReviewBasis(project).proof;+ return { jobId: 'proof-1' };+ });+ // The excerpt job settles while the run waits between polls.+ doubles.wait.mockImplementation(async () => { Object.assign(store.get('mv-auto').excerpts[0], outcome); });+ return renderProductionProof;+ };++ it('waits for the proof render to finish, then approves that excerpt and starts the final render', async () => {+ reviewFixture();+ await proofRenders({ status: 'complete', filename: 'proof-1.mp4' });+ await service.startAutonomousVideo({ prompt: 'p', tools: ['code:render'], authoring: { providerId: 'example', model: 'example-code' },+ autoApprove: ['art', 'storyboard', 'proof'] }, { autoApproveAuthorized: true });+ await settled('completed');+ expect(doubles.wait).toHaveBeenCalledOnce();+ expect(doubles.wait).toHaveBeenCalledWith(5000);+ expect(approvals().proof).toMatchObject({ approvedBy: 'autopilot', proofReview: {+ autoApproved: true, watchedWithAudio: false, excerptId: 'proof-1', filename: 'proof-1.mp4', energyComparison: PROOF_NOTE } });+ expect(actual.productionReadiness(store.get('mv-auto')).readyForProduction).toBe(true);+ expect(doubles.renderVideo).toHaveBeenCalledOnce();+ });++ it('fails the run with the excerpt error when the proof render fails', async () => {+ reviewFixture();+ await proofRenders({ status: 'error', error: 'Synthetic encoder failure' });+ await service.startAutonomousVideo({ prompt: 'p', tools: ['code:render'], authoring: { providerId: 'example', model: 'example-code' },+ autoApprove: ['art', 'storyboard', 'proof'] }, { autoApproveAuthorized: true });+ await settled('failed');+ expect(runOf()).toMatchObject({ errorCode: 'PROOF_RENDER_FAILED', error: 'The proof render failed: Synthetic encoder failure' });+ expect(approvals().proof).toBeUndefined();+ expect(doubles.renderVideo).not.toHaveBeenCalled();+ });+});diff --git a/server/services/musicVideo/productionReview.js b/server/services/musicVideo/productionReview.jsindex 78f765d207..90004236ba 100644--- a/server/services/musicVideo/productionReview.js+++ b/server/services/musicVideo/productionReview.js@@ -130,7 +130,14 @@ export function assertProductionApproval(project, stage = 'proof') {{ status: 409, code: 'MUSIC_VIDEO_APPROVAL_REQUIRED', context: { stage, readiness } });}-export function approveProductionStage(project, { stage, basis, proofReview }) {+/**+ * `approvedBy: 'autopilot'` marks an approval the autonomous run made under the+ * operator's `brief.autoApprove` grant. Its proof review is `autoApproved: true`:+ * nobody watched it, so the watched/notes record is waived, but it must still+ * name the current excerpt. The HTTP approval schema rejects both fields, so+ * only the run (in-process) can set them.+ */+export function approveProductionStage(project, { stage, basis, proofReview, approvedBy }) {const readiness = productionReadiness(project);const expected = stage === 'proof'? hash({ basis: readiness.basis.proof, excerptId: project.productionReview?.proof?.excerptId,@@ -140,17 +147,17 @@ export function approveProductionStage(project, { stage, basis, proofReview }) {if (readiness[stage].problems.length) throw new ServerError(readiness[stage].problems.join(' '), { status: 409, code: 'MUSIC_VIDEO_REVIEW_INCOMPLETE' });if (stage === 'proof') {const excerpt = project.excerpts?.find(e => e.id === project.productionReview?.proof?.excerptId);- if (proofReview?.watchedWithAudio !== true || !text(proofReview.energyComparison)- || !text(proofReview.timecodedNotes) || !/(?:\b\d{1,2}:\d{2}(?:\.\d+)?\b|\b\d+(?:\.\d+)?s\b)/.test(proofReview.timecodedNotes)) {+ if (proofReview?.autoApproved !== true && (proofReview?.watchedWithAudio !== true || !text(proofReview.energyComparison)+ || !text(proofReview.timecodedNotes) || !/(?:\b\d{1,2}:\d{2}(?:\.\d+)?\b|\b\d+(?:\.\d+)?s\b)/.test(proofReview.timecodedNotes))) {throw new ServerError('Play this proof with audio and record the energy comparison and timecoded choreography notes before approving.', { status: 409, code: 'MUSIC_VIDEO_PROOF_REVIEW_REQUIRED' });}- if (proofReview.excerptId !== excerpt?.id || proofReview.filename !== excerpt?.filename) {+ if (proofReview.excerptId !== excerpt?.id || proofReview.filename !== excerpt?.filename || !excerpt?.filename) {throw new ServerError('The rendered proof changed. Play and review the new excerpt before approving.', { status: 409, code: 'MUSIC_VIDEO_REVIEW_STALE' });}}return { ...project, productionReview: { ...project.productionReview,reviewedRevisions: { ...project.productionReview?.reviewedRevisions, [basis]: { draft: structuredClone(project.productionReview?.draft || {}), scenes: structuredClone(project.scenes || []), proof: structuredClone(project.productionReview?.proof || null), capturedAt: new Date().toISOString() } },- approvals: { ...project.productionReview?.approvals, [stage]: { basis: expected, approvedAt: new Date().toISOString(), ...(stage === 'proof' ? { proofReview: structuredClone(proofReview) } : {}) } } } };+ approvals: { ...project.productionReview?.approvals, [stage]: { basis: expected, approvedAt: new Date().toISOString(), ...(approvedBy ? { approvedBy } : {}), ...(stage === 'proof' ? { proofReview: structuredClone(proofReview) } : {}) } } } };}/** Comments retain the exact reviewed draft, even after a replacement import. */