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): fully autonomous music videos from one prompt
[._.]/ Adam Eivy70c5ee40c065
diff --git a/client/src/components/musicVideo/AutonomousRunPanel.jsx b/client/src/components/musicVideo/AutonomousRunPanel.jsxnew file mode 100644index 0000000000..ee262228f8--- /dev/null+++ b/client/src/components/musicVideo/AutonomousRunPanel.jsx@@ -0,0 +1,110 @@+import { useState } from 'react';+import { AlertTriangle, CheckCircle2, Circle, CircleDot, Loader2, Pause, Play, Wand2, X, XCircle } from 'lucide-react';+import {+ AUTONOMOUS_CHECKPOINT_LABELS, AUTONOMOUS_STATUS_LABELS, autonomousStageRows, isAutonomousLive,+} from '../../lib/musicVideoAutonomous.js';++const STATUS_TONES = {+ running: 'text-port-accent', 'awaiting-approval': 'text-port-warning', 'needs-human': 'text-port-warning', stopped: 'text-port-warning',+ completed: 'text-port-success', failed: 'text-port-error', canceled: 'text-port-text-muted',+};+const STAGE_MARKS = {+ done: { Icon: CheckCircle2, cls: 'text-port-success', label: 'done' },+ running: { Icon: Loader2, cls: 'text-port-accent animate-spin', label: 'running' },+ failed: { Icon: XCircle, cls: 'text-port-error', label: 'failed' },+ pending: { Icon: Circle, cls: 'text-port-text-muted', label: 'not started' },+};+const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';+const buttonClass = 'flex items-center gap-1 rounded border border-port-border bg-port-bg px-3 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50';++/**+ * The fully-autonomous run on a project: where it is in the pipeline, what it is+ * waiting for, and the few things the director can do — approve a checkpoint+ * (optionally with edited lyrics or Suno style), retry the stage that stopped,+ * pause, or cancel. Progress arrives over `music-video:autonomous` through+ * `useAutonomousMusicVideo`; this panel only renders the run it is given.+ */+export default function AutonomousRunPanel({ project, auto }) {+ const run = project?.autonomousRun;+ const [edit, setEdit] = useState(null); // { for: stage, value } — the director's edit at a checkpoint+ if (!run) return null;+ const rows = autonomousStageRows(run);+ const live = isAutonomousLive(run);+ const awaiting = run.status === 'awaiting-approval' ? run.awaiting : null;+ // The one editable output each checkpoint offers: lyrics before the style+ // stage, the Suno style line before the song is made.+ const editable = awaiting === 'lyrics' ? { key: 'lyrics', label: 'Lyrics', value: run.output?.lyrics || '' }+ : awaiting === 'style' ? { key: 'style', label: 'Suno style', value: run.output?.sunoStyle || '' } : null;+ const draft = edit && edit.for === awaiting ? edit.value : editable?.value;+ const changed = editable && draft !== editable.value;+ const canRetry = ['needs-human', 'failed', 'stopped'].includes(run.status) || run.interrupted;+ const tone = STATUS_TONES[run.status] || '';++ return (+ <section className="bg-port-card border border-port-border rounded-lg p-3 space-y-3 min-w-0" aria-label="Autonomous run">+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">+ <span className="flex items-center gap-1 text-sm font-medium"><Wand2 size={15} className="text-port-accent" aria-hidden="true" /> Autonomous run</span>+ <span className={`text-sm ${tone}`}>{run.interrupted ? 'Interrupted — resume to continue' : AUTONOMOUS_STATUS_LABELS[run.status] || run.status}</span>+ {run.brief?.origin?.kind === 'schedule' && (+ <span className="text-xs text-port-text-muted">Scheduled{run.brief.origin.ideaTitle ? ` · from “${run.brief.origin.ideaTitle}”` : ''}</span>+ )}+ </div>++ <ol aria-label="Autonomous stages" className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,11rem),1fr))] gap-x-3 gap-y-1 text-xs">+ {rows.map((row) => {+ const { Icon, cls, label } = STAGE_MARKS[row.status] || STAGE_MARKS.pending;+ return (+ <li key={row.id} aria-current={row.current ? 'step' : undefined} className={`flex min-w-0 items-center gap-1 ${row.current ? 'font-medium text-port-text' : 'text-port-text-muted'}`}>+ {row.current && row.status === 'pending' ? <CircleDot size={13} className="shrink-0 text-port-accent" aria-hidden="true" /> : <Icon size={13} className={`shrink-0 ${cls}`} aria-hidden="true" />}+ <span className="truncate">{row.label}</span>+ <span className="sr-only">({label})</span>+ </li>+ );+ })}+ </ol>++ {run.error && (+ <p role="status" className="flex items-start gap-1 text-xs text-port-warning break-words min-w-0">+ <AlertTriangle size={13} className="mt-0.5 shrink-0" aria-hidden="true" /> <span className="min-w-0">{run.error}</span>+ </p>+ )}++ {awaiting && (+ <div className="rounded border border-port-border p-2 space-y-2">+ <p className="text-xs text-port-text-muted">+ Paused after <strong className="text-port-text">{AUTONOMOUS_CHECKPOINT_LABELS[awaiting] || awaiting}</strong> — nothing further runs until you approve.+ </p>+ {editable && (+ <div>+ <label htmlFor="mv-auto-edit" className="block text-xs text-port-text-muted mb-1">{editable.label} (edit before continuing)</label>+ <textarea+ id="mv-auto-edit"+ rows={editable.key === 'lyrics' ? 10 : 3}+ value={draft}+ onChange={(e) => setEdit({ for: awaiting, value: e.target.value })}+ className={`${inputClass} font-mono text-xs`}+ />+ </div>+ )}+ <button type="button" disabled={auto.busy} onClick={() => auto.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>+ </div>+ )}++ {live || run.status === 'failed' ? (+ <div className="flex flex-wrap gap-2">+ {canRetry && !awaiting && (+ <button type="button" disabled={auto.busy} onClick={() => auto.resume()} className={buttonClass}>+ <Play size={14} aria-hidden="true" /> {run.status === 'failed' ? 'Retry' : 'Resume'}+ </button>+ )}+ {run.status === 'running' && !run.interrupted && (+ <button type="button" disabled={auto.busy} onClick={() => auto.stop()} className={buttonClass}><Pause size={14} aria-hidden="true" /> Pause</button>+ )}+ <button type="button" disabled={auto.busy} onClick={() => auto.cancel()} className={`${buttonClass} text-port-error`}><X size={14} aria-hidden="true" /> Cancel</button>+ </div>+ ) : null}+ </section>+ );+}diff --git a/client/src/components/musicVideo/AutonomousRunPanel.test.jsx b/client/src/components/musicVideo/AutonomousRunPanel.test.jsxnew file mode 100644index 0000000000..a9d6ebcd19--- /dev/null+++ b/client/src/components/musicVideo/AutonomousRunPanel.test.jsx@@ -0,0 +1,140 @@+/**+ * The autonomous run panel + start drawer over the real useAutonomousMusicVideo+ * hook, with a mocked API and socket: the drawer sends only what the director+ * chose (unmetered tools by default, no checkpoints, blank optionals omitted),+ * a checkpoint offers the one output worth editing and approves with the edit,+ * a failed/needs-you run offers a retry, and a pushed project updates the+ * visible run without polling.+ */+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', () => ({+ startAutonomousMusicVideo: vi.fn(),+ resumeAutonomousMusicVideo: vi.fn(),+ stopAutonomousMusicVideo: vi.fn(),+ cancelAutonomousMusicVideo: 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 AutonomousRunPanel from './AutonomousRunPanel.jsx';+import AutonomousStartDrawer from './AutonomousStartDrawer.jsx';+import useAutonomousMusicVideo from '../../hooks/useAutonomousMusicVideo.js';+import * as api from '../../services/apiMusicVideo.js';++const stages = (overrides = {}) => ({+ brief: { status: 'done' }, lyrics: { status: 'done' }, style: { status: 'pending' }, song: { status: 'pending' },+ analyze: { status: 'pending' }, produce: { status: 'pending' }, ...overrides,+});+const baseRun = (over = {}) => ({+ id: 'mvar-1', status: 'running', stage: 'style', awaiting: null, interrupted: false, error: null,+ brief: { origin: { kind: 'manual' } }, stages: stages(), output: { lyrics: '[verse]\nrain', sunoStyle: 'synthwave' }, ...over,+});++function Harness({ initial }) {+ const [project, setProject] = useState({ id: 'mv-1', autonomousRun: initial });+ const auto = useAutonomousMusicVideo({ project, replaceProject: setProject });+ return <AutonomousRunPanel project={project} auto={auto} />;+}++beforeEach(() => {+ vi.clearAllMocks();+ listeners.clear();+});++describe('AutonomousRunPanel', () => {+ it('shows the stage progress and updates from a pushed project, with no polling', async () => {+ render(<Harness initial={baseRun()} />);+ expect(screen.getByText('Running')).toBeTruthy();+ expect(screen.getByRole('list', { name: 'Autonomous stages' }).querySelectorAll('li')).toHaveLength(6);++ await act(async () => {+ listeners.get('music-video:autonomous')({ projectId: 'mv-1', run: baseRun({ status: 'completed', stage: 'produce' }), project: { id: 'mv-1', autonomousRun: baseRun({ status: 'completed', stage: 'produce' }) } });+ });+ expect(screen.getByText('Finished')).toBeTruthy();+ // A finished run offers nothing to press.+ expect(screen.queryByRole('button', { name: /cancel/i })).toBeNull();+ });++ it('approves a lyrics checkpoint, sending the director’s edit only when they changed it', async () => {+ api.resumeAutonomousMusicVideo.mockResolvedValue({ project: { id: 'mv-1', autonomousRun: baseRun() }, run: baseRun() });+ render(<Harness initial={baseRun({ status: 'awaiting-approval', awaiting: 'lyrics' })} />);++ fireEvent.click(screen.getByRole('button', { name: /approve & continue/i }));+ await waitFor(() => expect(api.resumeAutonomousMusicVideo).toHaveBeenCalledWith('mv-1', {}, { silent: true }));+ });++ it('sends the edited lyrics when approving after an edit', async () => {+ api.resumeAutonomousMusicVideo.mockResolvedValue({ project: { id: 'mv-1', autonomousRun: baseRun() }, run: baseRun() });+ render(<Harness initial={baseRun({ status: 'awaiting-approval', awaiting: 'lyrics' })} />);+ fireEvent.change(screen.getByLabelText(/lyrics \(edit before continuing\)/i), { target: { value: '[verse]\nedited' } });+ fireEvent.click(screen.getByRole('button', { name: /save edit & approve/i }));+ await waitFor(() => expect(api.resumeAutonomousMusicVideo).toHaveBeenCalledWith('mv-1', { lyrics: '[verse]\nedited' }, { silent: true }));+ });++ it('offers the Suno style line to edit at the style checkpoint (the last stop before Suno is used)', async () => {+ render(<Harness initial={baseRun({ status: 'awaiting-approval', awaiting: 'style' })} />);+ expect(screen.getByLabelText(/suno style \(edit before continuing\)/i).value).toBe('synthwave');+ });++ it('offers a retry for a run that needs the director, and shows why', async () => {+ api.resumeAutonomousMusicVideo.mockResolvedValue({ project: { id: 'mv-1', autonomousRun: baseRun() }, run: baseRun() });+ render(<Harness initial={baseRun({ status: 'needs-human', stage: 'song', error: 'Sign in to Suno in the PortOS Browser' })} />);+ expect(screen.getByRole('status').textContent).toContain('Sign in to Suno');+ fireEvent.click(screen.getByRole('button', { name: /resume/i }));+ await waitFor(() => expect(api.resumeAutonomousMusicVideo).toHaveBeenCalledWith('mv-1', {}, { silent: true }));+ });++ it('flags a run left over from before a server restart and offers to resume it', () => {+ render(<Harness initial={baseRun({ interrupted: true })} />);+ expect(screen.getByText(/interrupted — resume to continue/i)).toBeTruthy();+ expect(screen.getByRole('button', { name: /resume/i })).toBeTruthy();+ expect(screen.queryByRole('button', { name: /pause/i })).toBeNull();+ });+});++describe('AutonomousStartDrawer', () => {+ it('starts a run from the prompt alone, sending the free tools, no checkpoints and no blank optionals', async () => {+ api.startAutonomousMusicVideo.mockResolvedValue({ project: { id: 'mv-new', name: 'New' }, run: baseRun() });+ const onStarted = vi.fn();+ render(<AutonomousStartDrawer open onClose={() => {}} onStarted={onStarted} />);++ const submit = screen.getByRole('button', { name: /start autonomous video/i });+ expect(submit.disabled).toBe(true);+ fireEvent.change(screen.getByLabelText('Prompt'), { target: { value: ' a courier crosses a rainy city ' } });+ fireEvent.click(submit);++ await waitFor(() => expect(onStarted).toHaveBeenCalledWith({ id: 'mv-new', name: 'New' }));+ const [body, options] = api.startAutonomousMusicVideo.mock.calls[0];+ expect(options).toEqual({ silent: true });+ expect(body).toEqual({+ prompt: 'a courier crosses a rainy city', instrumental: false, tools: ['image:local', 'video:local'],+ budgetUsd: null, limits: { maxGenerations: 40 }, checkpoints: [],+ });+ });++ it('sends the director’s picks: checkpoints, a per-tool model pin, a budget and code-only rendering', async () => {+ api.startAutonomousMusicVideo.mockResolvedValue({ project: { id: 'mv-new' }, run: baseRun() });+ render(<AutonomousStartDrawer open onClose={() => {}} onStarted={() => {}} />);+ fireEvent.change(screen.getByLabelText('Prompt'), { target: { value: 'p' } });+ fireEvent.click(screen.getByLabelText('Lyrics', { selector: '#mv-auto-checkpoint-lyrics' }));+ fireEvent.change(screen.getByLabelText(/local image gen model/i), { target: { value: 'flux2-dev' } });+ fireEvent.change(screen.getByLabelText(/budget cap/i), { target: { value: '12' } });+ fireEvent.click(screen.getByRole('button', { name: /start autonomous video/i }));+ await waitFor(() => expect(api.startAutonomousMusicVideo).toHaveBeenCalled());+ expect(api.startAutonomousMusicVideo.mock.calls[0][0]).toMatchObject({+ checkpoints: ['lyrics'], models: { 'image:local': 'flux2-dev' }, budgetUsd: 12,+ });+ });+});diff --git a/client/src/components/musicVideo/AutonomousStartDrawer.jsx b/client/src/components/musicVideo/AutonomousStartDrawer.jsxnew file mode 100644index 0000000000..a069aecfe8--- /dev/null+++ b/client/src/components/musicVideo/AutonomousStartDrawer.jsx@@ -0,0 +1,196 @@+import { useState } from 'react';+import { Wand2 } from 'lucide-react';+import Drawer from '../Drawer.jsx';+import ToggleChip from '../ui/ToggleChip.jsx';+import ProviderModelSelector from '../ProviderModelSelector.jsx';+import toast from '../ui/Toast';+import useProviderModels from '../../hooks/useProviderModels.js';+import { startAutonomousMusicVideo } from '../../services/apiMusicVideo.js';+import { MUSIC_VIDEO_AUTOMATION_TOOLS, MUSIC_VIDEO_AUTOMATION_TOOL_IDS } from '../../lib/musicVideoAutomation.js';+import {+ AUTONOMOUS_CHECKPOINT_IDS, AUTONOMOUS_CHECKPOINT_LABELS, autonomousMedium, autonomousRequestFromDraft, emptyAutonomousDraft,+} from '../../lib/musicVideoAutonomous.js';++const GROUPS = [['image', 'Image'], ['video', 'Video'], ['code', 'Code']];+const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';++/**+ * "Autonomous music video" — the alternate entry point: one prompt, no track,+ * style or board picked up front. The server writes a creative brief, lyrics and+ * a mood board, makes the song in Suno (PortOS Browser), then produces the video+ * with the chosen tools. Checkpoints are optional approval stops.+ */+export default function AutonomousStartDrawer({ open, onClose, onStarted }) {+ const [draft, setDraft] = useState(emptyAutonomousDraft);+ const [submitting, setSubmitting] = useState(false);+ const llm = useProviderModels({ allowDefault: true, silent: true });+ const patch = (next) => setDraft((d) => ({ ...d, ...next }));+ const picked = new Set(draft.tools);+ const medium = autonomousMedium(draft.tools);+ const toggleTool = (id) => patch({+ tools: MUSIC_VIDEO_AUTOMATION_TOOL_IDS.filter((t) => (t === id ? !picked.has(t) : picked.has(t))),+ });+ const toggleCheckpoint = (id) => patch({+ checkpoints: AUTONOMOUS_CHECKPOINT_IDS.filter((c) => (c === id ? !draft.checkpoints.includes(c) : draft.checkpoints.includes(c))),+ });+ const modelTools = MUSIC_VIDEO_AUTOMATION_TOOLS.filter((t) => t.group !== 'code' && picked.has(t.id));+ const valid = draft.prompt.trim().length > 0;++ const handleSubmit = (e) => {+ e.preventDefault();+ if (!valid || submitting) return;+ setSubmitting(true);+ startAutonomousMusicVideo(+ autonomousRequestFromDraft(draft, { providerId: llm.selectedProviderId || undefined, model: llm.selectedModel || undefined }),+ { silent: true },+ )+ .then(({ project }) => {+ setDraft(emptyAutonomousDraft());+ toast.success('Autonomous music video started');+ onStarted(project);+ })+ .catch((err) => toast.error(err?.message || 'Failed to start the autonomous music video'))+ .finally(() => setSubmitting(false));+ };++ return (+ <Drawer+ open={open}+ onClose={onClose}+ size="md"+ title="Autonomous music video"+ subtitle="One prompt in — lyrics, a Suno song, a mood board and the video out"+ closeOnEsc={false}+ closeOnBackdrop={false}+ >+ <form onSubmit={handleSubmit} className="space-y-4">+ <div>+ <label htmlFor="mv-auto-prompt" className="block text-xs text-port-text-muted mb-1">Prompt</label>+ <textarea+ id="mv-auto-prompt"+ rows={4}+ maxLength={4000}+ value={draft.prompt}+ onChange={(e) => patch({ prompt: e.target.value })}+ placeholder="A courier crosses a rainy neon city at night — melancholic synthwave, a hopeful chorus."+ className={inputClass}+ />+ <p className="text-[11px] text-port-text-muted mt-1">+ The song is made in Suno through the PortOS Browser — sign in to Suno there first. The agent also builds its own mood board and visual style from this prompt.+ </p>+ </div>++ <ToggleChip id="mv-auto-instrumental" label="Instrumental (no vocals)" checked={draft.instrumental} onToggle={() => patch({ instrumental: !draft.instrumental })} />++ <fieldset className="min-w-0" aria-labelledby="mv-auto-tools-label">+ <span id="mv-auto-tools-label" className="block text-xs text-port-text-muted mb-1">How the video is made</span>+ <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">+ {GROUPS.map(([group, label]) => (+ <div key={group} className="border border-port-border rounded p-2 min-w-0">+ <div className="text-[11px] uppercase tracking-wide text-port-text-muted mb-1">{label}</div>+ <div className="flex flex-wrap gap-1.5">+ {MUSIC_VIDEO_AUTOMATION_TOOLS.filter((t) => t.group === group).map((tool) => (+ <ToggleChip+ key={tool.id}+ id={`mv-auto-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={() => toggleTool(tool.id)}+ />+ ))}+ </div>+ </div>+ ))}+ </div>+ <p className="text-[11px] text-port-text-muted mt-1">+ {medium === 'code'+ ? 'Only “Render with code” is picked: the video is drawn by code — no images or footage are generated.'+ : 'Image and video tools drive the production run; it stops at the generation limit and the budget.'}+ </p>+ </fieldset>++ {modelTools.length > 0 && (+ <div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,14rem),1fr))] gap-3">+ {modelTools.map((tool) => (+ <div key={tool.id} className="min-w-0">+ <label htmlFor={`mv-auto-model-${tool.id}`} className="block text-xs text-port-text-muted mb-1">{tool.label} model (optional)</label>+ <input+ id={`mv-auto-model-${tool.id}`}+ value={draft.models[tool.id] || ''}+ onChange={(e) => patch({ models: { ...draft.models, [tool.id]: e.target.value } })}+ placeholder="Install default"+ maxLength={200}+ className={inputClass}+ />+ </div>+ ))}+ </div>+ )}++ <div>+ <label htmlFor="mv-auto-guidance" className="block text-xs text-port-text-muted mb-1">Guidance (optional)</label>+ <textarea+ id="mv-auto-guidance"+ rows={2}+ maxLength={4000}+ value={draft.guidance}+ onChange={(e) => patch({ guidance: e.target.value })}+ placeholder="Tone, pacing, what to avoid — the agent writes and plans against this."+ className={inputClass}+ />+ </div>++ <div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,12rem),16rem))] gap-3">+ <div>+ <label htmlFor="mv-auto-budget" className="block text-xs text-port-text-muted mb-1">Budget cap (USD)</label>+ <input id="mv-auto-budget" type="number" min="0" step="1" value={draft.budget} onChange={(e) => patch({ budget: e.target.value })} placeholder="No cap" className={inputClass} />+ </div>+ <div>+ <label htmlFor="mv-auto-generations" className="block text-xs text-port-text-muted mb-1">Max generations</label>+ <input id="mv-auto-generations" type="number" min="1" max="500" step="1" value={draft.maxGenerations} onChange={(e) => patch({ maxGenerations: e.target.value })} className={inputClass} />+ </div>+ </div>++ <fieldset className="min-w-0" aria-labelledby="mv-auto-checkpoints-label">+ <span id="mv-auto-checkpoints-label" className="block text-xs text-port-text-muted mb-1">Pause for my approval after (optional)</span>+ <div className="flex flex-wrap gap-1.5">+ {AUTONOMOUS_CHECKPOINT_IDS.map((id) => (+ <ToggleChip+ key={id}+ id={`mv-auto-checkpoint-${id}`}+ label={AUTONOMOUS_CHECKPOINT_LABELS[id]}+ checked={draft.checkpoints.includes(id)}+ onToggle={() => toggleCheckpoint(id)}+ />+ ))}+ </div>+ <p className="text-[11px] text-port-text-muted mt-1">With none picked the run is fully unattended.</p>+ </fieldset>++ {llm.providers.length > 0 && (+ <ProviderModelSelector+ providers={llm.providers}+ selectedProviderId={llm.selectedProviderId}+ selectedModel={llm.selectedModel}+ availableModels={llm.availableModels}+ onProviderChange={llm.setSelectedProviderId}+ onModelChange={llm.setSelectedModel}+ label="Writes the brief and lyrics"+ disabled={submitting}+ modelDisabled={llm.availableModels.length === 0}+ compact+ />+ )}++ <button+ type="submit"+ disabled={!valid || submitting}+ className="w-full flex items-center justify-center gap-1 bg-port-accent text-white rounded px-2 py-1.5 text-sm min-h-[44px] sm:min-h-0 disabled:opacity-50"+ >+ <Wand2 size={16} /> {submitting ? 'Starting…' : 'Start autonomous video'}+ </button>+ </form>+ </Drawer>+ );+}diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 0eaa3cb1f3..cf1f73af7c 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -252,6 +252,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. || `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/index.js b/client/src/hooks/index.jsindex 5e1757a476..50dfc9e7fb 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -71,6 +71,7 @@ export { default as useMusicVideoManualTempo } from './useMusicVideoManualTempo.export { default as useMusicVideoMidiJob } from './useMusicVideoMidiJob.js';export { default as useMusicVideoModelSettings } from './useMusicVideoModelSettings.js';export { default as useMusicVideoProduction } from './useMusicVideoProduction.js';+export { default as useAutonomousMusicVideo } from './useAutonomousMusicVideo.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/useAutonomousMusicVideo.js b/client/src/hooks/useAutonomousMusicVideo.jsnew file mode 100644index 0000000000..e9c312ed8c--- /dev/null+++ b/client/src/hooks/useAutonomousMusicVideo.js@@ -0,0 +1,67 @@+import { useEffect, useRef, useState } from 'react';+import toast from '../components/ui/Toast';+import socket from '../services/socket';+import {+ cancelAutonomousMusicVideo,+ resumeAutonomousMusicVideo,+ stopAutonomousMusicVideo,+} from '../services/apiMusicVideo.js';++const OUTCOME_TOASTS = {+ 'awaiting-approval': (run) => toast.info(`Autonomous music video is waiting for your approval of the ${run.awaiting || 'last'} step`),+ 'needs-human': (run) => toast.info(`Autonomous music video needs you: ${run.error || 'check the run'}`),+ completed: () => toast.success('Autonomous music video finished — review it'),+ failed: (run) => toast.error(`Autonomous music video failed: ${run.error || 'unknown error'}`),+};++/**+ * Fully-autonomous run (prompt → lyrics → Suno song → video). Starting one is+ * the Music Video page's create flow; this hook owns what happens afterwards:+ * 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() }`.+ */+export default function useAutonomousMusicVideo({ project, replaceProject } = {}) {+ const projectId = project?.id || null;+ const [busy, setBusy] = useState(false);+ const replaceRef = useRef(replaceProject);+ const lastStatus = useRef({ id: null, status: null }); // a project has one run+ useEffect(() => {+ replaceRef.current = replaceProject;+ });++ useEffect(() => {+ if (!projectId) return undefined;+ const onAutonomous = (data) => {+ if (data?.projectId !== projectId) return;+ if (data.project) replaceRef.current?.(data.project);+ const run = data.run;+ if (run?.id && lastStatus.current.status !== run.status) {+ const seen = lastStatus.current.id === run.id;+ lastStatus.current = { id: run.id, status: run.status };+ if (seen || run.status !== 'running') OUTCOME_TOASTS[run.status]?.(run);+ }+ };+ socket.on('music-video:autonomous', onAutonomous);+ return () => socket.off('music-video:autonomous', onAutonomous);+ }, [projectId]);++ const call = (request) => {+ setBusy(true);+ return request()+ .then((res) => {+ if (res?.project) replaceRef.current?.(res.project);+ 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; })+ .finally(() => setBusy(false));+ };++ const resume = (edits = {}) => call(() => resumeAutonomousMusicVideo(projectId, edits, { silent: true }));+ const stop = () => call(() => stopAutonomousMusicVideo(projectId, { silent: true }));+ const cancel = () => call(() => cancelAutonomousMusicVideo(projectId, { silent: true }));++ return { busy, resume, stop, cancel };+}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex c7f6aec4f7..ef3a0181cf 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -66,6 +66,7 @@ grep -i "what you want to do" client/src/lib/README.md| `musicVideoShotTiming.js` | Re-export of `server/lib/musicVideoShotTiming.js` (#8977) — shot modes, the verified source-audio lip-sync capability table, `performanceBlockedReason`, `planPerformanceRepair` (measured accepted-prefix boundary, suffix interval and next spend), `planPerformanceWindow`, `grokCoverage`, `approximateMotionCues`, `shotSplitLimit` (when a scene offers a lyric-boundary split), `falSceneTake` (a fal take's model, length, resolution and estimated cost). Used by `hooks/useMusicVideoSceneMedia.js` and `components/musicVideo/SceneCard.jsx`. || `musicVideoStages.js` | Music Video page stage model: `MUSIC_VIDEO_STAGES` (setup → cast-sets → board → produce → compose → review), `resolveStageParam(value)` for the `:stage` route param, `deriveStages(project)` (per-stage `done`/`active`/`blocked`/`todo` + `current`, the first incomplete stage; a live production run pins Produce), `deriveNextAction(project, ctx)` (the one primary action the sticky header offers — approve Cast & Sets, stop/resume production, render final, …), `projectSpend(project)` (paid generation used vs. cap) and `currentProductionRun`. Used by `components/musicVideo/MusicVideoLayout.jsx` and `pages/MusicVideo.jsx`. || `musicVideoUniverseRefs.js` | `pullUniverseCanonReferences(universe, existingReferences)` (#8978) maps a linked universe's characters/places/objects to visual-spec references (character/set/prop roles), skipping images already present and capping at `MUSIC_VIDEO_MAX_REFERENCES` (24, mirrors the server schema). Returns `{ next, added, skipped }`; the caller persists `next` via the ordinary visualSpec PATCH. Used by `components/musicVideo/VisualSpecPanel.jsx`. (The style snapshots are derived server-side, #9105.) |+| `musicVideoAutonomous.js` | Fully-autonomous Music Video, client half: re-exports the server stage vocabulary (`AUTONOMOUS_STAGES`, checkpoint ids, default tools/limits, `autonomousMedium`), the status/checkpoint labels, and owns the start form's `emptyAutonomousDraft` / `autonomousRequestFromDraft` mapping plus `autonomousStageRows(run)` and `isAutonomousLive(run)` for the run panel. || `musicVideoAutomation.js` | Music Video automation brief, client half: re-exports the server tool catalog (`MUSIC_VIDEO_AUTOMATION_TOOLS` / `_TOOL_IDS`), `DEFAULT_AUTOMATION_TOOLS` (the unmetered tools), and the form mapping `automationDraftFrom(automation)` / `automationFromDraft(draft)` (empty budget = no cap). Used by the create drawer and `AutopilotPanel`. || `bibleLimits.js` | `BIBLE_LIMITS` re-exported from the pure leaf `server/lib/bibleLimits.js`, plus the client-only `capImageRefs` / `appendImageRefById` for the optimistic imageRefs-append paths. || `characterEvolution.js` | The five-stage character evolution lens as the editors consume it. Re-exports `EVOLUTION_STAGES` / `EVOLUTION_OUTCOMES` / `EVOLUTION_STAGE_LABELS` / `EVOLUTION_STAGE_TEXT_FIELDS` / `EVOLUTION_EVIDENCE_FIELDS` / `EVOLUTION_EVIDENCE_STATUSES` / `CHARACTER_EVOLUTION_LIMITS` / `evolutionEvidenceStatus` / `isDeclaredEvolution` from the pure leaf `server/lib/characterEvolution.js` (a guard in `server/lib/characterEvolution.test.js` fails if this file ever restates a vocabulary instead of re-exporting it), adds the editor descriptors `EVOLUTION_STAGE_EDITOR_FIELDS` / `EVOLUTION_OUTCOME_HINTS` (#6440), and the draft-mutation helpers `evolutionStage` / `patchEvolution` / `patchEvolutionStage` / `patchEvolutionEvidence` that keep an editor's draft collapsing to the same shape the server sanitizer produces — so a present-but-empty field is a real clear (#6441). |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 4d9b752eaa..cb9f596a71 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -76,6 +76,7 @@ export * from './musicVideoShotTiming.js';export * from './musicVideoStages.js';export * from './musicVideoUniverseRefs.js';export * from './musicVideoAutomation.js';+export * from './musicVideoAutonomous.js';export * from './pipelineImageDefaults.js';export * from './reverseOutlineGrid.js';export * from './reviewerModels.js';diff --git a/client/src/lib/musicVideoAutonomous.js b/client/src/lib/musicVideoAutonomous.jsnew file mode 100644index 0000000000..9bef829a61--- /dev/null+++ b/client/src/lib/musicVideoAutonomous.js@@ -0,0 +1,68 @@+// Fully-autonomous Music Video — client half. Re-exports the server's stage+// vocabulary and brief normalizer (a dependency-light leaf) and owns the start+// form's draft ↔ wire mapping and the run's display helpers.++import {+ AUTONOMOUS_DEFAULT_LIMITS, AUTONOMOUS_DEFAULT_TOOLS, AUTONOMOUS_LIVE_STATUSES, AUTONOMOUS_STAGES,+} from '../../../server/lib/musicVideoAutonomous.js';++export { AUTONOMOUS_CHECKPOINT_IDS, 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',+});++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',+});++export const emptyAutonomousDraft = () => ({+ prompt: '',+ instrumental: false,+ tools: [...AUTONOMOUS_DEFAULT_TOOLS],+ models: {},+ guidance: '',+ budget: '',+ maxGenerations: String(AUTONOMOUS_DEFAULT_LIMITS.maxGenerations),+ checkpoints: [],+});++const optionalInt = (raw) => {+ const n = Number.parseInt(raw, 10);+ return Number.isInteger(n) ? n : undefined;+};++/** The start request for a draft: blank optional fields are omitted so the server defaults apply. */+export function autonomousRequestFromDraft(draft, { providerId, model } = {}) {+ const budget = Number.parseFloat(draft.budget);+ const maxGenerations = optionalInt(draft.maxGenerations);+ const models = Object.fromEntries(Object.entries(draft.models || {})+ .filter(([id, value]) => draft.tools.includes(id) && typeof value === 'string' && value.trim())+ .map(([id, value]) => [id, value.trim()]));+ return {+ prompt: draft.prompt.trim(),+ instrumental: draft.instrumental === true,+ tools: draft.tools,+ ...(Object.keys(models).length ? { models } : {}),+ ...(draft.guidance.trim() ? { guidance: draft.guidance.trim() } : {}),+ budgetUsd: Number.isFinite(budget) && budget >= 0 ? budget : null,+ ...(maxGenerations ? { limits: { maxGenerations } } : {}),+ checkpoints: draft.checkpoints,+ ...(providerId ? { providerId, ...(model ? { model } : {}) } : {}),+ };+}++/** One display row per stage of a run: its label, state and (when failed) the error. */+export function autonomousStageRows(run) {+ if (!run) return [];+ return AUTONOMOUS_STAGES.map((stage) => {+ const state = run.stages?.[stage.id] || {};+ const current = run.stage === stage.id;+ return { id: stage.id, label: stage.label, status: state.status || 'pending', current, error: state.error || null };+ });+}++/** True while the run can still move (or be nudged): the project page keeps its panel prominent. */+export const isAutonomousLive = (run) => !!run && AUTONOMOUS_LIVE_STATUSES.includes(run.status);diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex a27431b1a1..0433fd7e35 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -1,6 +1,6 @@import { useEffect, useState, useCallback, useMemo, useRef } from 'react';import { useParams, useNavigate, useSearchParams } from 'react-router';-import { Plus, Film, Copy, Trash2 } from 'lucide-react';+import { Plus, Film, Copy, Trash2, Wand2 } from 'lucide-react';import toast from '../components/ui/Toast';import PageHeader from '../components/PageHeader';import {@@ -34,6 +34,7 @@ import useMusicVideoPublishing from '../hooks/useMusicVideoPublishing.js';import useMusicVideoRevisions from '../hooks/useMusicVideoRevisions.js';import useMusicVideoAutoReview from '../hooks/useMusicVideoAutoReview.js';import useMusicVideoProduction from '../hooks/useMusicVideoProduction.js';+import useAutonomousMusicVideo from '../hooks/useAutonomousMusicVideo.js';import useMusicVideoModelSettings from '../hooks/useMusicVideoModelSettings.js';import useMusicVideoManualTempo from '../hooks/useMusicVideoManualTempo.js';import useMusicVideoSceneMedia from '../hooks/useMusicVideoSceneMedia.js';@@ -47,6 +48,8 @@ import MidiInstallModal from '../components/install/MidiInstallModal.jsx';import MidiGatedModal from '../components/install/MidiGatedModal.jsx';import { listTracks, trackAudioUrl } from '../services/apiTracks.js';import CreateProjectDrawer from '../components/musicVideo/CreateProjectDrawer.jsx';+import AutonomousStartDrawer from '../components/musicVideo/AutonomousStartDrawer.jsx';+import AutonomousRunPanel from '../components/musicVideo/AutonomousRunPanel.jsx';import { automationDraftFrom, automationFromDraft } from '../lib/musicVideoAutomation.js';import { listUniverseNames } from '../services/apiUniverseBuilder.js';import MusicVideoLayout from '../components/musicVideo/MusicVideoLayout.jsx';@@ -127,6 +130,7 @@ export default function MusicVideo() {const [importingLyrics, setImportingLyrics] = useState(false);const [aligningLyrics, setAligningLyrics] = useState(false);const [createOpen, setCreateOpen] = useState(false);+ const [autonomousOpen, setAutonomousOpen] = useState(false);const [creating, setCreating] = useState(false);const [form, setForm] = useState(emptyCreateForm);const selected = projects.find((p) => p.id === selectedId) || null;@@ -202,6 +206,7 @@ export default function MusicVideo() {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 });+ const autonomous = useAutonomousMusicVideo({ project: selected, replaceProject });// Cast & Sets check-in (before the plan) and the development files it saves.const castSets = useMusicVideoCastAndSets({ project: selected, replaceProject });const devArtifacts = useMusicVideoDevArtifacts({ project: selected, replaceProject });@@ -949,6 +954,14 @@ export default function MusicVideo() {</button></span>)}+ <button+ type="button"+ onClick={() => setAutonomousOpen(true)}+ title="One prompt in — lyrics, a Suno song, a mood board and the video out"+ className="flex items-center gap-1 rounded border border-port-accent text-port-accent px-3 py-1.5 text-sm min-h-[44px] sm:min-h-0"+ >+ <Wand2 size={15} /> Autonomous+ </button><buttontype="button"onClick={() => setCreateOpen(true)}@@ -973,6 +986,16 @@ export default function MusicVideo() {submitting={creating}/>+ <AutonomousStartDrawer+ open={autonomousOpen}+ onClose={() => setAutonomousOpen(false)}+ onStarted={(proj) => {+ setProjects((prev) => [...prev, proj]);+ selectProject(proj.id);+ setAutonomousOpen(false);+ }}+ />+<div>{!selected && !loading && routeProjectId && (<p className="text-sm text-port-text-muted">@@ -982,14 +1005,23 @@ export default function MusicVideo() {)}{!selected && (loading || !routeProjectId) && (<div className="bg-port-card border border-port-border rounded-lg p-6 text-center">- <p className="text-sm text-port-text-muted mb-3">Pick a project in the header, or start a new one — seed a name, universe and board, choose the tools and a budget, and let autopilot churn.</p>- <button- type="button"- onClick={() => setCreateOpen(true)}- className="inline-flex items-center gap-1 bg-port-accent text-white rounded px-3 py-1.5 text-sm min-h-[44px] sm:min-h-0"- >- <Plus size={15} /> New music video- </button>+ <p className="text-sm text-port-text-muted mb-3">Pick a project in the header, start a new one — seed a name, universe and board, choose the tools and a budget, and let autopilot churn — or go fully autonomous from a single prompt.</p>+ <div className="flex flex-wrap justify-center gap-2">+ <button+ type="button"+ onClick={() => setCreateOpen(true)}+ className="inline-flex items-center gap-1 bg-port-accent text-white rounded px-3 py-1.5 text-sm min-h-[44px] sm:min-h-0"+ >+ <Plus size={15} /> New music video+ </button>+ <button+ type="button"+ onClick={() => setAutonomousOpen(true)}+ className="inline-flex items-center gap-1 rounded border border-port-accent text-port-accent px-3 py-1.5 text-sm min-h-[44px] sm:min-h-0"+ >+ <Wand2 size={15} /> Autonomous+ </button>+ </div></div>)}{selected && (@@ -1012,7 +1044,10 @@ export default function MusicVideo() {/>) : null}>- <StageView key={selected.id} board={board} />+ <div className="space-y-3 min-w-0">+ <AutonomousRunPanel key={`autonomous-${selected.id}`} project={selected} auto={autonomous} />+ <StageView key={selected.id} board={board} />+ </div></MusicVideoLayout>)}</div>diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 06eb489f15..e04b4f75e9 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -292,6 +292,20 @@ export const stopMusicVideoProduction = (id, runId, options = {}) =>export const cancelMusicVideoProduction = (id, runId, options = {}) =>request(`/music-video/${encodeURIComponent(id)}/production-runs/${encodeURIComponent(runId)}/cancel`, { method: 'POST', ...options });+// ---- Fully-autonomous run: one prompt → lyrics → Suno song → video ----+// Start body: { prompt, tools?, models?, budgetUsd?, limits?, checkpoints?, instrumental?, guidance?,+// providerId?, model?, authoring? } → 202 { project, run }. The run advances server-side and reports+// over the `music-video:autonomous` socket event. Resume approves the checkpoint it waits on (optionally+// with edited { lyrics, style }) or retries the stage that stopped.+export const startAutonomousMusicVideo = (body, options = {}) =>+ request('/music-video/autonomous', { method: 'POST', body: JSON.stringify(body), ...options });+export const resumeAutonomousMusicVideo = (id, body = {}, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/autonomous/resume`, { method: 'POST', body: JSON.stringify(body), ...options });+export const stopAutonomousMusicVideo = (id, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/autonomous/stop`, { method: 'POST', ...options });+export const cancelAutonomousMusicVideo = (id, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/autonomous/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 treatmentdiff --git a/docs/API.md b/docs/API.mdindex b429f6b96e..af562ff911 100644--- a/docs/API.md+++ b/docs/API.md@@ -748,7 +748,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom| `/api/media-jobs` | Async media job queue || `/api/creative-director` | Creative Director projects || `/api/fableloom` | FableLoom interactive story generation |-| `/api/music-video` | Music video projects |+| `/api/music-video` | Music video projects; [one-prompt autonomous runs](./features/music-video-autonomous.md) at `/api/music-video/autonomous` || `/api/mood-boards` | Mood boards || `/api/decks` | Decks (playing-card / tarot designer) || `/api/writers-room` | Writers Room |diff --git a/docs/README.md b/docs/README.mdindex c106bf7d46..1d705cc2a2 100644--- a/docs/README.md+++ b/docs/README.md@@ -31,6 +31,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo| [MODEL_ACCESS.md](./MODEL_ACCESS.md) | Scoping a provider to the models your plan entitles you to — free tiers, allow/deny globs, gateway inheritance || [MODEL-COMPARISON.md](./MODEL-COMPARISON.md) | Sourced provider/model/effort comparisons, cost estimates and CoS research refresh || [THREEJS_MODELS.md](./THREEJS_MODELS.md) | Three.js procedural 3D model generation and trust boundary |+| [features/music-video-autonomous.md](./features/music-video-autonomous.md) | One-prompt autonomous music videos: brief → lyrics → mood board → Suno song → production, optional checkpoints, and the `music-video-autopilot` scheduled task that turns Brain ideas into videos || [features/music-video-temporal-evidence.md](./features/music-video-temporal-evidence.md) | Performance source provenance, synchronized playback and optional local temporal analyzer protocol || [features/music-renderer-benchmarks.md](./features/music-renderer-benchmarks.md) | Technical and full-length listening evidence for local music renderer profiles || [CONTRIBUTING.md](./CONTRIBUTING.md) | Dev setup (PostgreSQL required), code conventions |diff --git a/docs/features/music-video-autonomous.md b/docs/features/music-video-autonomous.mdnew file mode 100644index 0000000000..754a91fb66--- /dev/null+++ b/docs/features/music-video-autonomous.md@@ -0,0 +1,63 @@+# Autonomous Music Video++One prompt in, a finished music video out. The Music Video page's **Autonomous** entry point (and the `music-video-autopilot` scheduled task) starts a server-owned run that does everything the hand-driven flow asks you to set up first: it writes the creative brief, the lyrics and a mood board, makes the song in Suno, and produces the video with the tools you allowed. Approval checkpoints are optional; with none chosen the run is fully unattended.++## Pipeline++```+brief → lyrics → style → song → analyze → produce+```++| Stage | What happens | Costs |+|---|---|---|+| `brief` | One LLM call turns the prompt into a title, a musical description, a compact Suno style line, a visual concept and a mood-board spec. The project is renamed to the title. | one provider call |+| `lyrics` | Original lyrics written against the musical description (skipped for an instrumental). | one provider call |+| `style` | A **Mood Board** (text notes + a composite look prompt and an avoid list) is created and linked as the project's mood board; the concept is set from the brief. No images are generated. | free |+| `song` | The PortOS Browser drives the Suno web UI (custom mode: lyrics, style, title), the song is downloaded from Suno's CDN into the music library, a Track is created, the take is recorded with `source: 'suno'`, and the project is linked to it. | Suno credits |+| `analyze` | The usual offline beat / tempo / section analysis. | free |+| `produce` | **Footage** (any image/video tool picked): the existing server-owned production run (`/production-runs`) with a pool built from the picks, then the final render once it completes. **Code** (only `code:render`): a code-rendered video is authored and rendered directly. | per tool |++State lives on the project as `autonomousRun` — install-local like `productionRuns` (stripped from the peer wire, not carried into a clone). Each stage settles in one serialized project write, so a crash resumes at the stage that did not settle. After a server restart a run is shown **interrupted** and nothing advances until you resume it (no cold-bootstrap provider calls).++## Checkpoints++`checkpoints` names the stages that park the run in `awaiting-approval` until you approve:++- `lyrics` — review/edit the lyrics before anything else is spent.+- `style` — review the mood board and edit the Suno style line; the last stop before Suno credits are used.+- `song` — listen to the Suno song before the image/video quota is spent.+- `cast` — flips the existing Cast & Sets check-in to *review* (the production run owns it).++Approving can carry edits (`POST /api/music-video/:id/autonomous/resume` with `{ lyrics }` or `{ style }`).++## Failure handling++- A signed-out Suno parks the run **`needs-human`** (`PUBLISH_LOGIN_REQUIRED`): sign in to Suno in the PortOS Browser, then Resume.+- Any other stage failure parks **`failed`** with the error; Retry re-runs that stage only. Songs already submitted to Suno are stored the moment Suno accepts the request, so a failed download retries the same songs and never spends credits on a second generation.+- A parked or failed delegated production run parks this run `needs-human`; Resume resumes the production run.++The Suno adapter fills the form through `placeholder` / role selectors and reads the new `/song/<id>` links; everything after Create is plain HTTP against the CDN. If Suno redesigns the page, the failing step is named in the error (`Suno: fill the lyrics (…)`).++## API++| Method | Path | |+|---|---|---|+| `POST` | `/api/music-video/autonomous` | Start (202 `{ project, run }`). Body: `prompt` plus optional `tools`, `models` (per-tool model pin), `budgetUsd`, `limits`, `checkpoints`, `instrumental`, `guidance`, `providerId`/`model` (brief + lyrics LLM), `authoring` (code-rendered video). |+| `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. |+| `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 }`).++## Scheduled task: `music-video-autopilot`++A programmatic scheduled task (no agent). Each run picks the **oldest active Brain idea no earlier run used** (optionally only ideas carrying one of `ideaTags`), turns it into the prompt and starts an autonomous run with the task's saved settings (`taskMetadata.musicVideoAutopilot`: `tools`, `models`, `budgetUsd`, `limits`, `checkpoints`, `instrumental`, `guidance`, `providerId`/`model`, `authoring`, `ideaTags`). Set a cadence on its Schedule card; Run Now fires it once.++- It declines while a previous scheduled run is still live, so videos never pile up behind a slow Suno login or a long production.+- An idea counts as used once its run is live or finished; a failed or canceled run leaves the idea available for the next fire.+- The shipped default is the free local tool set with no checkpoints and no budget cap — nothing metered is spent until you opt in.+- Like every scheduled automation it is gated on Config → Improve being enabled.++## Where it lives++`server/lib/musicVideoAutonomous.js` (vocabulary, brief normalizer, Suno limits, idea picker) · `server/services/musicVideo/autonomous{Service,Brief,Board,Suno}.js` · `server/services/scheduledHandlers/musicVideoAutopilot.js` · `client/src/components/musicVideo/Autonomous{StartDrawer,RunPanel}.jsx`.diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.mdindex 77f56d9a78..d4972c749d 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` | A project opens on seven deep-linked stage tabs (`/music-video/:projectId/:stage` — `setup`, `cast-sets`, `board`, `produce`, `compose`, `review`, `publish`; a bottom tab bar on a phone) under a sticky header showing its progress, paid-generation spend against the cap, and the one next action for the stage it is in; the composition preview (or, without a composition document, the latest draft excerpt) is docked beside the Board, Compose and Review tabs, and scene cards seek it. 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, cut from an optional full-length vocal stem when one is attached — uploaded, or separated from the song with a locally installed demucs) — Grok video is cutaway-only. The autopilot kickoff analyzes the song, imports the linked track's lyric sheet (its `[Verse]`/`[Chorus]` headers and stage directions kept as lyric markers that name the analysis sections and steer shot framing), separates the vocal, aligns every word with local whisper.cpp (large-v3-turbo, downloaded on first use), builds a Cast & Sets check-in (one creative-direction call that interprets the song, then a canonical character sheet, expression and looks sheets, one empty plate per set and in-set tests on the image queue, each later image conditioned on the character sheet; assembled into a self-contained sheet saved as a development artifact), stops for the director's review unless the brief auto-approves it, then plans against the approved references. Development artifacts (check-in sheets, animatics, treatments, storyboards; HTML/Markdown/MP4/PNG/JPG) are versioned per project, reviewed with notes and approve/request-changes, and viewed in a sandboxed viewer at `/music-video/:projectId/:stage/dev/:artifactId` (the stage-less `/music-video/:projectId/dev/:artifactId` still opens it). Draft excerpts are reviewed and selectively revised by hand, or by an opt-in auto-review run bounded by director-set review and paid-generation limits (a frame-only look never passes motion or audio sync). A server-owned production run (`/api/music-video/:id/production-runs`, #9066) plans an empty board, generates missing frames and clips only on a director-allowed image/video provider+model pool, hands the continuous draft to auto-review and dispatches its revisions — within explicit generation, review and (priced routes only) dollar limits, without the browser open, and never resuming on its own after a restart; the song is the sole audio unless a sound-design bed is explicitly chosen to mix under it. A footage or composed render can intercut (#9290): shots are re-cut on the song's section energy (every 2 beats in the loudest quarter, up to every 8 in the quietest) and on sung word onsets, alternating the host shot — a lip-synced take stays in sync — with unshown footage from a cutaway in the same section, so the edit gets faster without generating more clips; an autopilot production run defaults to it unless the director chose one cut per shot. Lyric lines sung two or more times are hooks: the treatment's text cues give them a word-by-word build (#9291) — each word lands on its sung onset in heavy caps, the newest in the accent color. Draft excerpts can be re-framed as vertical or square social cuts with faded audio edges, from suggested hook windows (#9280). The Publish stage (#9281) builds a release kit from the final render: an X-sized 1080p, a 720p preview, a hook teaser, thumbnail candidates, lyric captions (SRT) and YouTube chapters. It also drafts every platform's copy in one director-triggered provider call from their own making-of notes, and every field stays editable. Posting (#9282) fills each platform's post (YouTube, Suno, an X thread, Shorts, TikTok, Instagram Reels, Reddit, Stacker News) in a new PortOS Browser tab with the director's signed-in sessions, shows a screenshot and summary of the filled draft, and posts only when the director presses Post for that draft; the posted links are kept on the project. Reddit defaults to a native video post in r/aivideo — title and flair, no body — through the new composer's own Video button (#9307). Platforms are opt-in (#9287): a "Where you post" list turns each one on (all start off) and optionally names the account posted as — X and Reddit drafts filled while signed in as someone else are refused. Copy is drafted and posts are offered only for enabled platforms. Each post (including one recorded by hand) can be rated good, mixed or poor with notes; ratings roll up per platform across projects and are passed to later copy drafts. | — |+| **Music Video Studio** | `/music-video` | A project opens on seven deep-linked stage tabs (`/music-video/:projectId/:stage` — `setup`, `cast-sets`, `board`, `produce`, `compose`, `review`, `publish`; a bottom tab bar on a phone) under a sticky header showing its progress, paid-generation spend against the cap, and the one next action for the stage it is in; the composition preview (or, without a composition document, the latest draft excerpt) is docked beside the Board, Compose and Review tabs, and scene cards seek it. 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, cut from an optional full-length vocal stem when one is attached — uploaded, or separated from the song with a locally installed demucs) — Grok video is cutaway-only. The autopilot kickoff analyzes the song, imports the linked track's lyric sheet (its `[Verse]`/`[Chorus]` headers and stage directions kept as lyric markers that name the analysis sections and steer shot framing), separates the vocal, aligns every word with local whisper.cpp (large-v3-turbo, downloaded on first use), builds a Cast & Sets check-in (one creative-direction call that interprets the song, then a canonical character sheet, expression and looks sheets, one empty plate per set and in-set tests on the image queue, each later image conditioned on the character sheet; assembled into a self-contained sheet saved as a development artifact), stops for the director's review unless the brief auto-approves it, then plans against the approved references. Development artifacts (check-in sheets, animatics, treatments, storyboards; HTML/Markdown/MP4/PNG/JPG) are versioned per project, reviewed with notes and approve/request-changes, and viewed in a sandboxed viewer at `/music-video/:projectId/:stage/dev/:artifactId` (the stage-less `/music-video/:projectId/dev/:artifactId` still opens it). Draft excerpts are reviewed and selectively revised by hand, or by an opt-in auto-review run bounded by director-set review and paid-generation limits (a frame-only look never passes motion or audio sync). A server-owned production run (`/api/music-video/:id/production-runs`, #9066) plans an empty board, generates missing frames and clips only on a director-allowed image/video provider+model pool, hands the continuous draft to auto-review and dispatches its revisions — within explicit generation, review and (priced routes only) dollar limits, without the browser open, and never resuming on its own after a restart; the song is the sole audio unless a sound-design bed is explicitly chosen to mix under it. A footage or composed render can intercut (#9290): shots are re-cut on the song's section energy (every 2 beats in the loudest quarter, up to every 8 in the quietest) and on sung word onsets, alternating the host shot — a lip-synced take stays in sync — with unshown footage from a cutaway in the same section, so the edit gets faster without generating more clips; an autopilot production run defaults to it unless the director chose one cut per shot. Lyric lines sung two or more times are hooks: the treatment's text cues give them a word-by-word build (#9291) — each word lands on its sung onset in heavy caps, the newest in the accent color. Draft excerpts can be re-framed as vertical or square social cuts with faded audio edges, from suggested hook windows (#9280). The **Autonomous** entry point (`docs/features/music-video-autonomous.md`) starts from one prompt instead of a chosen track: it writes the brief, lyrics and a mood board, makes the song in Suno through the PortOS Browser, and runs the production — with optional approval checkpoints, and a `music-video-autopilot` scheduled task that turns unused Brain ideas into videos. The Publish stage (#9281) builds a release kit from the final render: an X-sized 1080p, a 720p preview, a hook teaser, thumbnail candidates, lyric captions (SRT) and YouTube chapters. It also drafts every platform's copy in one director-triggered provider call from their own making-of notes, and every field stays editable. Posting (#9282) fills each platform's post (YouTube, Suno, an X thread, Shorts, TikTok, Instagram Reels, Reddit, Stacker News) in a new PortOS Browser tab with the director's signed-in sessions, shows a screenshot and summary of the filled draft, and posts only when the director presses Post for that draft; the posted links are kept on the project. Reddit defaults to a native video post in r/aivideo — title and flair, no body — through the new composer's own Video button (#9307). Platforms are opt-in (#9287): a "Where you post" list turns each one on (all start off) and optionally names the account posted as — X and Reddit drafts filled while signed in as someone else are refused. Copy is drafted and posts are offered only for enabled platforms. Each post (including one recorded by hand) can be rated good, mixed or poor with notes; ratings roll up per platform across projects and are passed to later copy drafts. | — || **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. | — |---diff --git a/server/lib/README.md b/server/lib/README.mdindex 17c7e8de88..1266f93a58 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -797,6 +797,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `musicVideoCreativeContext.js` | `musicVideoDirectionContext(direction)` bounds the authoritative Cast & Sets bible; `musicVideoCreativeContext(concept)` composes the selected universe style and authored cast/place/object bible for planning and generation. || `moodBoardStyleContext.js` | `collectBoardStyleContext(board)` bounds a board's notes, captions, analyzed prompts, and composite style for creative prompts. `moodBoardImageCandidates(board, resolveItem)` lists the poster first, then pinned local images. |+| `musicVideoAutonomous.js` | Fully-autonomous Music Video vocabulary: `AUTONOMOUS_STAGES` (brief → lyrics → style → song → analyze → produce), optional `AUTONOMOUS_CHECKPOINT_IDS`, `normalizeAutonomousSettings` / `normalizeAutonomousBrief` / `normalizeAutopilotParams` (the shared run settings, a run's stored brief, and the scheduled task's params), `autonomousMedium` / `autonomousPool` (tool picks → footage vs code, production route pool), `sunoSongFields` + Suno limits/URL helpers, and `pickBrainIdea` / `ideaToPrompt` for the scheduled task. Pure; the client drawer and the run service import it. || `musicVideoAutomation.js` | Music Video automation brief: `MUSIC_VIDEO_AUTOMATION_TOOLS` (image/video backends derived from `generationModes.js` plus `code:render`, each flagged `metered`), `MUSIC_VIDEO_AUTOMATION_TOOL_IDS`, and `normalizeMusicVideoAutomation(patch, current)` (per-sub-field merge, catalog-ordered tools, `budgetUsd: null` = no cap). Dependency-free; the client create drawer imports it. || `albumLimits.js` | Album record length/count caps shared by the albums sanitizer and client editors. || `artistLimits.js` | Artist record length caps shared by the artists sanitizer and client editors. |diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.jsindex 0ee897e6a4..f1e573f9c6 100644--- a/server/lib/cosValidation.js+++ b/server/lib/cosValidation.js@@ -16,6 +16,7 @@ import { EFFORT_LEVELS } from './providerModels.js';import { isValidSlashdoCommand } from './slashdoInvocation.js';import { PR_COMPLETION_VALUES, PR_REVIEW_MODE_VALUES } from './prDisposition.js';import { QUEUEABLE_IMAGE_MODES } from './generationModes.js';+import { normalizeAutopilotParams } from './musicVideoAutonomous.js';import { PUBLIC_REVIEW_EXECUTION_PROFILES } from './agentExecutionProfiles.js';import { ORCHESTRATION_MODES, ORCHESTRATION_ROLES } from './orchestrationProfile.js';import { AGENT_RUN_EVENT_KINDS, RUN_EVENT_READ_LIMITS } from './agentRunEvents.js';@@ -1328,7 +1329,17 @@ export function sanitizeTaskMetadata(raw) {clean.mode = raw.mode;hasKeys = true;}- // Pipeline configuration is the one nested task-metadata shape. Keep only+ // The music-video-autopilot handler's params bag (lib/musicVideoAutonomous.js+ // owns the shape): tools, per-tool models, budget, limits, checkpoints, LLM,+ // and the Brain idea tags it may draw from. Re-normalized on every save.+ if (Object.prototype.hasOwnProperty.call(raw, 'musicVideoAutopilot')) {+ const params = normalizeAutopilotParams(raw.musicVideoAutopilot);+ if (params) {+ clean.musicVideoAutopilot = params;+ hasKeys = true;+ }+ }+ // Pipeline configuration is the other nested task-metadata shape. Keep only// known stage fields and fail the whole update when a known field is malformed// so a bad custom pipeline cannot silently lose its safety posture.if (Object.prototype.hasOwnProperty.call(raw, 'pipeline')) {diff --git a/server/lib/index.js b/server/lib/index.jsindex 716cf2489b..7721fd29a7 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -778,6 +778,7 @@ export * from './databaseWriterRegistry.js';export * from './musicVideoCreativeContext.js';export * from './moodBoardStyleContext.js';export * from './musicVideoAutomation.js';+export * from './musicVideoAutonomous.js';export * as albumLimits from './albumLimits.js';export * as artistLimits from './artistLimits.js';export * as authorLimits from './authorLimits.js';diff --git a/server/lib/musicVideoAutonomous.js b/server/lib/musicVideoAutonomous.jsnew file mode 100644index 0000000000..708242a862--- /dev/null+++ b/server/lib/musicVideoAutonomous.js@@ -0,0 +1,211 @@+/**+ * Fully-autonomous Music Video — the pure vocabulary and transforms.+ *+ * A dependency-light leaf (the client's start drawer and the server's run+ * service import it directly, like musicVideoAutomation.js) so the stage list,+ * the brief shape and the Suno field limits cannot drift between the form, the+ * Zod schema and the orchestrator.+ *+ * One prompt drives the whole pipeline:+ *+ * brief → lyrics → style → song → analyze → produce+ *+ * brief one LLM call turns the prompt into a title, a musical description,+ * a Suno style line, a visual concept and a mood-board spec+ * lyrics original lyrics written against that description+ * style the mood board + visual concept are created from the prompt+ * song the PortOS Browser drives the Suno web UI, the song is downloaded+ * into the music library and imported as a track+ * analyze beat / section analysis of the downloaded audio+ * produce the existing server-owned production run (footage tools) or the+ * code-rendered video (code-only tools)+ *+ * Any of `lyrics` / `style` / `song` may be a CHECKPOINT: the run parks in+ * `awaiting-approval` until the director approves it. By default none are, so+ * the run is fully unattended.+ */++import { MUSIC_VIDEO_AUTOMATION_TOOL_IDS } from './musicVideoAutomation.js';+import { isStr, trimTo } from './textUtils.js';++export const AUTONOMOUS_STAGES = Object.freeze([+ Object.freeze({ id: 'brief', label: 'Creative brief' }),+ Object.freeze({ id: 'lyrics', label: 'Lyrics' }),+ Object.freeze({ id: 'style', label: 'Mood board & style' }),+ Object.freeze({ id: 'song', label: 'Song (Suno)' }),+ Object.freeze({ id: 'analyze', label: 'Analyze song' }),+ Object.freeze({ id: 'produce', label: 'Produce video' }),+]);+export const AUTONOMOUS_STAGE_IDS = Object.freeze(AUTONOMOUS_STAGES.map((s) => s.id));++// The stages whose output the director may want to approve before the run+// spends anything further (Suno credits follow `lyrics`; image/video quota+// follows `song`). `cast` is the existing Cast & Sets check-in inside+// production — it is not a stage of this run, it flips that gate to review.+const AUTONOMOUS_STAGE_CHECKPOINT_IDS = Object.freeze(['lyrics', 'style', 'song']);+export const AUTONOMOUS_CHECKPOINT_IDS = Object.freeze([...AUTONOMOUS_STAGE_CHECKPOINT_IDS, 'cast']);++export const AUTONOMOUS_SONG_SOURCES = Object.freeze(['suno']);++// A run in one of these states can still be resumed / approved.+export const AUTONOMOUS_LIVE_STATUSES = Object.freeze(['running', 'awaiting-approval', 'needs-human', 'stopped']);++export const AUTONOMOUS_PROMPT_MAX = 4000;+export const AUTONOMOUS_NAME_MAX = 200;+export const AUTONOMOUS_ORIGINS = Object.freeze(['manual', 'schedule']);++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 }),+ maxReviewAttempts: Object.freeze({ min: 1, max: 10 }),+});++// Suno's custom-song form fields (v4.5+). Shaping text to these keeps a long+// LLM caption from being silently truncated — or rejected — by the page.+export const SUNO_LIMITS = Object.freeze({ title: 80, style: 1000, lyrics: 5000 });++// Free (local, un-metered) tools only, the same default a hand-made autopilot+// brief starts from — nothing paid is spent unless the operator opts in.+export const AUTONOMOUS_DEFAULT_TOOLS = Object.freeze(['image:local', 'video:local']);++// Normalize line endings, then trim and cap (non-strings become '').+const clean = (v, max) => trimTo(isStr(v) ? v.replace(/\r\n?/g, '\n') : v, max);+const int = (v, { min, max }, fallback) => (Number.isInteger(v) && v >= min && v <= max ? v : fallback);++/**+ * How the video is produced, derived from the tool picks:+ * `footage` — any image/video tool: the server-owned production run;+ * `code` — only `code:render`: a code-rendered video, no media generation.+ */+export const autonomousMedium = (tools) => (autonomousPool(tools).length ? 'footage' : 'code');++/** The production-run route pool for a tool list (+ optional per-tool model pins). */+export function autonomousPool(tools, models = {}) {+ return (Array.isArray(tools) ? tools : [])+ .filter((id) => isStr(id) && (id.startsWith('image:') || id.startsWith('video:')))+ .map((id) => {+ const [kind, mode] = id.split(':');+ const model = models?.[id]; // already trimmed by normalizeAutonomousSettings+ return { kind, mode, ...(model ? { model } : {}) };+ });+}++/**+ * The run settings a start request and the scheduled task share: everything+ * except the prompt itself. Unknown tool ids and checkpoint ids are dropped;+ * blank optional strings collapse to absent. Throws nothing — the route's Zod+ * schema owns rejection, this owns shape.+ */+function normalizeAutonomousSettings(raw = {}) {+ const picked = new Set(Array.isArray(raw.tools) ? raw.tools : AUTONOMOUS_DEFAULT_TOOLS);+ const tools = MUSIC_VIDEO_AUTOMATION_TOOL_IDS.filter((id) => picked.has(id));+ const models = {};+ for (const [id, model] of Object.entries(raw.models && typeof raw.models === 'object' ? raw.models : {})) {+ if (tools.includes(id) && isStr(model) && model.trim()) models[id] = model.trim().slice(0, 200);+ }+ const checkpoints = AUTONOMOUS_CHECKPOINT_IDS.filter((id) => Array.isArray(raw.checkpoints) && raw.checkpoints.includes(id));+ const budget = Number(raw.budgetUsd);+ const llmProvider = clean(raw.providerId, 200);+ const llmModel = clean(raw.model, 200);+ const authoringProvider = clean(raw.authoring?.providerId, 200);+ const authoringModel = clean(raw.authoring?.model, 200);+ return {+ songSource: AUTONOMOUS_SONG_SOURCES.includes(raw.songSource) ? raw.songSource : AUTONOMOUS_SONG_SOURCES[0],+ instrumental: raw.instrumental === true,+ guidance: clean(raw.guidance, 4000),+ tools,+ models,+ budgetUsd: raw.budgetUsd != null && Number.isFinite(budget) && budget >= 0 ? Math.min(budget, 100000) : null,+ limits: {+ maxGenerations: int(raw.limits?.maxGenerations, AUTONOMOUS_LIMIT_BOUNDS.maxGenerations, AUTONOMOUS_DEFAULT_LIMITS.maxGenerations),+ maxReviewAttempts: int(raw.limits?.maxReviewAttempts, AUTONOMOUS_LIMIT_BOUNDS.maxReviewAttempts, AUTONOMOUS_DEFAULT_LIMITS.maxReviewAttempts),+ },+ checkpoints,+ llm: llmProvider ? { providerId: llmProvider, model: llmModel || null } : null,+ authoring: authoringProvider && authoringModel ? { providerId: authoringProvider, model: authoringModel } : null,+ };+}++/** Normalize a start request into the brief a run stores: the settings plus prompt, name and origin. */+export function normalizeAutonomousBrief(raw = {}) {+ const origin = raw.origin && typeof raw.origin === 'object' ? raw.origin : {};+ return {+ prompt: clean(raw.prompt, AUTONOMOUS_PROMPT_MAX),+ name: clean(raw.name, AUTONOMOUS_NAME_MAX) || null,+ ...normalizeAutonomousSettings(raw),+ origin: {+ kind: AUTONOMOUS_ORIGINS.includes(origin.kind) ? origin.kind : 'manual',+ ideaId: clean(origin.ideaId, 80) || null,+ ideaTitle: clean(origin.ideaTitle, 200) || null,+ },+ };+}++/**+ * The scheduled task's saved configuration (`taskMetadata.musicVideoAutopilot`):+ * the run settings plus which brain ideas it may draw from. Returns null for a+ * non-object so the task-metadata sanitizer can drop it.+ */+export function normalizeAutopilotParams(raw) {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;+ const tags = (Array.isArray(raw.ideaTags) ? raw.ideaTags : [])+ .map((t) => clean(t, 50)).filter(Boolean).slice(0, 20);+ return { ...normalizeAutonomousSettings(raw), ideaTags: [...new Set(tags)] };+}++/** The stage a run goes to after `stage`, or null after the last. */+export function nextAutonomousStage(stage) {+ const i = AUTONOMOUS_STAGE_IDS.indexOf(stage);+ return i >= 0 && i < AUTONOMOUS_STAGE_IDS.length - 1 ? AUTONOMOUS_STAGE_IDS[i + 1] : null;+}++/**+ * Shape the generated text into what the Suno form accepts. Section tags in+ * the lyrics pass through unchanged (Suno reads `[Verse]` style tags); an+ * instrumental song sends no lyrics at all.+ */+export function sunoSongFields({ title, style, lyrics, instrumental = false } = {}) {+ return {+ title: clean(title, SUNO_LIMITS.title) || 'Untitled',+ style: clean(style, SUNO_LIMITS.style),+ lyrics: instrumental ? '' : clean(lyrics, SUNO_LIMITS.lyrics),+ instrumental,+ };+}++/** Suno song ids carried by `/song/<uuid>` links, de-duplicated in page order. */+const SUNO_SONG_ID = /\/song\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i;+export function sunoSongIdsFromHrefs(hrefs) {+ const ids = [];+ for (const href of Array.isArray(hrefs) ? hrefs : []) {+ const m = isStr(href) ? SUNO_SONG_ID.exec(href) : null;+ if (m && !ids.includes(m[1].toLowerCase())) ids.push(m[1].toLowerCase());+ }+ return ids;+}++/** The public CDN URL Suno serves a finished song's audio from. */+export const sunoAudioUrl = (songId) => `https://cdn1.suno.ai/${encodeURIComponent(songId)}.mp3`;+export const sunoSongUrl = (songId) => `https://suno.com/song/${encodeURIComponent(songId)}`;++/**+ * Choose the next brain idea to turn into a video: the OLDEST active idea no+ * earlier run used (a stable, drain-the-backlog order), optionally limited to+ * ideas carrying one of `tags`. Returns null when nothing is eligible.+ */+export function pickBrainIdea(ideas, { usedIdeaIds = [], tags = [] } = {}) {+ const used = new Set(usedIdeaIds);+ const wanted = new Set((Array.isArray(tags) ? tags : []).map((t) => String(t).trim().toLowerCase()).filter(Boolean));+ const eligible = (Array.isArray(ideas) ? ideas : []).filter((idea) => {+ if (!idea?.id || used.has(idea.id) || idea.status === 'done') return false;+ if (!wanted.size) return true;+ return (idea.tags || []).some((t) => wanted.has(String(t).trim().toLowerCase()));+ });+ eligible.sort((a, b) => String(a.createdAt || '').localeCompare(String(b.createdAt || '')) || String(a.id).localeCompare(String(b.id)));+ return eligible[0] || null;+}++/** A brain idea as the free-text prompt a run starts from. */+export function ideaToPrompt(idea) {+ return [idea?.title, idea?.oneLiner, idea?.notes].map((v) => clean(v, 2000)).filter(Boolean).join('\n\n').slice(0, AUTONOMOUS_PROMPT_MAX);+}diff --git a/server/lib/musicVideoAutonomous.test.js b/server/lib/musicVideoAutonomous.test.jsnew file mode 100644index 0000000000..1ad5d8ca5b--- /dev/null+++ b/server/lib/musicVideoAutonomous.test.js@@ -0,0 +1,116 @@+import { describe, it, expect } from 'vitest';+import {+ AUTONOMOUS_DEFAULT_TOOLS,+ SUNO_LIMITS,+ autonomousMedium,+ autonomousPool,+ ideaToPrompt,+ normalizeAutonomousBrief,+ normalizeAutopilotParams,+ pickBrainIdea,+ sunoAudioUrl,+ sunoSongFields,+ sunoSongIdsFromHrefs,+} from './musicVideoAutonomous.js';+import { sanitizeTaskMetadata } from './cosValidation.js';+import { musicVideoAutonomousStartSchema } from './musicVideoValidation.js';++describe('normalizeAutonomousBrief', () => {+ it('defaults to the free local tools, no checkpoints, no budget — nothing metered unless opted in', () => {+ const brief = normalizeAutonomousBrief({ prompt: ' a song about rain ' });+ expect(brief).toMatchObject({+ prompt: 'a song about rain', tools: AUTONOMOUS_DEFAULT_TOOLS, checkpoints: [], budgetUsd: null,+ llm: null, authoring: null, origin: { kind: 'manual', ideaId: null },+ });+ expect(brief.limits).toEqual({ maxGenerations: 40, maxReviewAttempts: 3 });+ });++ it('drops unknown tools/checkpoints, models for unpicked tools, and out-of-range limits', () => {+ const brief = normalizeAutonomousBrief({+ prompt: 'p', tools: ['image:local', 'bogus', 'code:render'], checkpoints: ['song', 'nope', 'cast'],+ models: { 'image:local': 'flux2-dev', 'video:local': 'unpicked', 'image:nope': 'x' },+ limits: { maxGenerations: 9999, maxReviewAttempts: 2 }, budgetUsd: -5, providerId: ' prov ', model: ' m ',+ });+ expect(brief.tools).toEqual(['image:local', 'code:render']);+ expect(brief.checkpoints).toEqual(['song', 'cast']);+ expect(brief.models).toEqual({ 'image:local': 'flux2-dev' });+ expect(brief.limits).toEqual({ maxGenerations: 40, maxReviewAttempts: 2 });+ expect(brief.budgetUsd).toBeNull();+ expect(brief.llm).toEqual({ providerId: 'prov', model: 'm' });+ });++ it('agrees with the start schema: whatever the schema accepts normalizes to a brief the run can use', () => {+ const body = musicVideoAutonomousStartSchema.parse({+ prompt: 'p', tools: ['video:local'], checkpoints: ['lyrics'], models: { 'video:local': 'ltx' }, budgetUsd: 5,+ authoring: { providerId: 'a', model: 'b' }, origin: { kind: 'schedule', ideaId: 'idea-1' },+ });+ expect(normalizeAutonomousBrief(body)).toMatchObject({ budgetUsd: 5, authoring: { providerId: 'a', model: 'b' }, origin: { kind: 'schedule', ideaId: 'idea-1' } });+ expect(() => musicVideoAutonomousStartSchema.parse({ prompt: 'p', tools: ['nope'] })).toThrow();+ expect(() => musicVideoAutonomousStartSchema.parse({ prompt: '' })).toThrow();+ });+});++describe('tool picks → how the video is made', () => {+ it('any image/video tool means footage production; code alone means a code-rendered video', () => {+ expect(autonomousMedium(['code:render'])).toBe('code');+ expect(autonomousMedium(['code:render', 'image:local'])).toBe('footage');+ expect(autonomousMedium([])).toBe('code');+ });++ it('builds the production route pool from the picks, pinning models where given', () => {+ expect(autonomousPool(['image:local', 'video:grok', 'code:render'], { 'image:local': 'flux2-dev' }))+ .toEqual([{ kind: 'image', mode: 'local', model: 'flux2-dev' }, { kind: 'video', mode: 'grok' }]);+ });+});++describe('Suno field shaping', () => {+ it('bounds every field to what the form accepts and sends no lyrics for an instrumental', () => {+ const long = 'x'.repeat(9000);+ const fields = sunoSongFields({ title: long, style: long, lyrics: long });+ expect(fields.title.length).toBe(SUNO_LIMITS.title);+ expect(fields.style.length).toBe(SUNO_LIMITS.style);+ expect(fields.lyrics.length).toBe(SUNO_LIMITS.lyrics);+ expect(sunoSongFields({ title: 't', style: 's', lyrics: 'words', instrumental: true })).toEqual({ title: 't', style: 's', lyrics: '', instrumental: true });+ expect(sunoSongFields({}).title).toBe('Untitled');+ });++ it('reads song ids out of workspace links, ignoring everything else and repeats', () => {+ const a = '0a1b2c3d-1111-2222-3333-444455556666';+ const b = '9f8e7d6c-aaaa-bbbb-cccc-ddddeeeeffff';+ expect(sunoSongIdsFromHrefs([`/song/${a}`, '/create', `https://suno.com/song/${b.toUpperCase()}?x=1`, `/song/${a}`, null, '/song/not-a-uuid']))+ .toEqual([a, b]);+ expect(sunoAudioUrl(a)).toBe(`https://cdn1.suno.ai/${a}.mp3`);+ });+});++describe('Brain idea selection', () => {+ const ideas = [+ { id: 'c', title: 'C', status: 'active', createdAt: '2026-03-01T00:00:00.000Z', tags: ['song'] },+ { id: 'a', title: 'A', status: 'active', createdAt: '2026-01-01T00:00:00.000Z', tags: [] },+ { id: 'b', title: 'B', status: 'done', createdAt: '2025-12-01T00:00:00.000Z', tags: ['song'] },+ ];++ it('takes the oldest active idea no earlier run used', () => {+ expect(pickBrainIdea(ideas).id).toBe('a');+ expect(pickBrainIdea(ideas, { usedIdeaIds: ['a'] }).id).toBe('c');+ expect(pickBrainIdea(ideas, { usedIdeaIds: ['a', 'c'] })).toBeNull();+ });++ it('limits to tagged ideas case-insensitively when tags are set', () => {+ expect(pickBrainIdea(ideas, { tags: ['SONG'] }).id).toBe('c');+ expect(pickBrainIdea(ideas, { tags: ['missing'] })).toBeNull();+ });++ it('turns an idea into the run prompt', () => {+ expect(ideaToPrompt({ title: 'T', oneLiner: 'one', notes: 'more' })).toBe('T\n\none\n\nmore');+ });+});++describe('scheduled-task params', () => {+ it('survive task-metadata sanitization, re-normalized, and a non-object is dropped', () => {+ const saved = sanitizeTaskMetadata({ musicVideoAutopilot: { tools: ['image:local', 'junk'], ideaTags: ['Song', 'song', ' '], budgetUsd: 3 } });+ expect(saved.musicVideoAutopilot).toMatchObject({ tools: ['image:local'], ideaTags: ['Song', 'song'], budgetUsd: 3 });+ expect(saved.musicVideoAutopilot).toEqual(normalizeAutopilotParams(saved.musicVideoAutopilot));+ expect(sanitizeTaskMetadata({ musicVideoAutopilot: 'nope' })).toBeNull();+ });+});diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 8b98220bca..29d29f887b 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -21,6 +21,14 @@ import {MUSIC_VIDEO_AUTOMATION_TOOL_IDS,MUSIC_VIDEO_CHECKIN_MODES,} from './musicVideoAutomation.js';+import {+ AUTONOMOUS_CHECKPOINT_IDS,+ AUTONOMOUS_LIMIT_BOUNDS,+ AUTONOMOUS_NAME_MAX,+ AUTONOMOUS_ORIGINS,+ AUTONOMOUS_PROMPT_MAX,+ AUTONOMOUS_SONG_SOURCES,+} from './musicVideoAutonomous.js';import { MUSCRIPTOR_MODELS } from './muscriptorModels.js';import { IMAGE_GEN_MODES, VIDEO_GEN_MODES } from './generationModes.js';@@ -722,6 +730,44 @@ export const musicVideoProductionResumeSchema = z.object({acceptBasis: z.boolean().optional(),}).strict();+// ---- Fully-autonomous run: one prompt → lyrics → Suno song → video --------------+// 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).+export const musicVideoAutonomousStartSchema = z.object({+ prompt: z.string().trim().min(1).max(AUTONOMOUS_PROMPT_MAX),+ name: z.string().trim().min(1).max(AUTONOMOUS_NAME_MAX).optional(),+ songSource: z.enum(AUTONOMOUS_SONG_SOURCES).optional(),+ instrumental: z.boolean().optional(),+ guidance: z.string().max(4000).optional(),+ tools: z.array(z.enum(MUSIC_VIDEO_AUTOMATION_TOOL_IDS)).max(MUSIC_VIDEO_AUTOMATION_TOOL_IDS.length).optional(),+ // Per-tool model pin, e.g. { 'image:local': 'flux-dev' }; absent = the install default.+ models: z.partialRecord(z.enum(MUSIC_VIDEO_AUTOMATION_TOOL_IDS), z.string().trim().min(1).max(200)).optional(),+ budgetUsd: z.number().min(0).max(MUSIC_VIDEO_AUTOMATION_BUDGET_MAX_USD).nullable().optional(),+ limits: z.object({+ maxGenerations: z.number().int().min(AUTONOMOUS_LIMIT_BOUNDS.maxGenerations.min).max(AUTONOMOUS_LIMIT_BOUNDS.maxGenerations.max).optional(),+ maxReviewAttempts: z.number().int().min(AUTONOMOUS_LIMIT_BOUNDS.maxReviewAttempts.min).max(AUTONOMOUS_LIMIT_BOUNDS.maxReviewAttempts.max).optional(),+ }).strict().optional(),+ checkpoints: z.array(z.enum(AUTONOMOUS_CHECKPOINT_IDS)).max(AUTONOMOUS_CHECKPOINT_IDS.length).optional(),+ // The LLM that writes the brief and lyrics (blank = the install's active provider).+ providerId: z.string().trim().min(1).max(200).nullable().optional(),+ model: z.string().trim().min(1).max(200).nullable().optional(),+ // The separate code-authoring provider a code-rendered video needs.+ authoring: z.object({ providerId: z.string().min(1).max(200), model: z.string().min(1).max(200) }).strict().optional(),+ origin: z.object({+ kind: z.enum(AUTONOMOUS_ORIGINS).optional(),+ ideaId: z.string().max(80).nullable().optional(),+ ideaTitle: z.string().max(200).nullable().optional(),+ }).strict().optional(),+}).strict();++// Resume a parked/failed run, or approve the checkpoint it is waiting on.+export const musicVideoAutonomousResumeSchema = z.object({+ // Replace the stage output the director edited at a checkpoint.+ lyrics: z.string().max(20000).optional(),+ style: z.string().max(AUTONOMOUS_PROMPT_MAX).optional(),+}).strict();+// A generation kickoff that failed before reaching the queue (#9011) — names// the rejected section whose claim should clear so the next resume can hand// it out again immediately instead of waiting out GENERATION_CLAIM_LEASE_MS.diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 15febcde93..4a85eb1bc7 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -60,7 +60,7 @@ const RAW_NAV_COMMANDS = [{ id: 'nav.create.creative-commission', path: '/creative-commission', label: 'Creative Commissions', section: 'Create', aliases: ['creative-commission', 'commissions', 'commission', 'creation-engine', 'autonomous-creation', 'standing-brief', 'recurring-brief'], keywords: ['schedule', 'recurring', 'nightly', 'brief', 'autonomous', 'creation engine', 'cron', 'feedback', 'taste', 'standing commission', 'auto-generate'] },{ id: 'nav.create.fableloom', path: '/fableloom', label: 'FableLoom', section: 'Create', aliases: ['fableloom', 'fable-loom', 'loom', 'branching-narrative', 'interactive-story', 'branching-story'], keywords: ['branching', 'interactive', 'narrative', 'intent', 'endings', 'reader', 'scene', 'node', 'graph', 'nonlinear', 'play', 'story graph'] },{ id: 'nav.create.game', path: '/game', label: 'Game', section: 'Create', aliases: ['game', 'games', 'game-studio'], keywords: ['managed app', 'sprite', 'atlas', 'music', 'asset bundle', 'manifest', 'feedback'] },- { id: 'nav.create.music-video', path: '/music-video', label: 'Music Video', section: 'Create', previousPaths: ['/media/music-video', '/media/music-video/:projectId'], aliases: ['music-video', 'musicvideo', 'music video', 'mv', 'sync-to-beat'], keywords: ['music', 'beat', 'sync', 'audio-reactive', 'director', 'scene board', 'tempo', 'choreography'] },+ { id: 'nav.create.music-video', path: '/music-video', label: 'Music Video', section: 'Create', previousPaths: ['/media/music-video', '/media/music-video/:projectId'], aliases: ['music-video', 'musicvideo', 'music video', 'mv', 'sync-to-beat'], keywords: ['music', 'beat', 'sync', 'audio-reactive', 'director', 'scene board', 'tempo', 'choreography', 'autonomous', 'suno', 'one prompt', 'lyrics'] },{ id: 'nav.create.decks', path: '/decks', label: 'Decks', section: 'Create', aliases: ['decks', 'deck', 'card-deck', 'playing-cards', 'tarot', 'tarot-deck', 'cards'], keywords: ['playing cards', 'tarot', 'card deck', 'card design', 'suits', 'arcana', 'style guide', 'batch render', 'card art'] },{ id: 'nav.create.mood-boards', path: '/mood-boards', label: 'Mood Boards', section: 'Create', aliases: ['mood-boards', 'mood-board', 'moodboard', 'mood', 'inspiration', 'references'], keywords: ['inspiration', 'reference', 'pin', 'visual', 'canvas', 'collect', 'pinboard', 'palette', 'ideas'] },// Promoted out of the Media Gen tabs to a top-level Create page (#2930).diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex f61fc8802f..f5d569bc2e 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -643,6 +643,9 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// live under this install's data/music-video/ and are not in the project's// asset manifest, so they are never sent. What an approved check-in writes// into ordinary fields (visual-spec references, concept subjects) syncs.+ // The fully-autonomous run (`autonomousRun`, services/musicVideo/autonomousService.js)+ // is wire-local like `productionRuns`: it names this install's providers, Suno+ // songs and production run, and a peer must never execute it — no bump.// v10 = composition mode `document` (a project-owned HTML composition// document) and `composition.overlay` (its HUD settings). A v9 peer's// normalizeComposition collapses the unknown mode to `concat` and drops thediff --git a/server/lib/syncWire.js b/server/lib/syncWire.jsindex 56bb995eb1..8bdbf0c2f2 100644--- a/server/lib/syncWire.js+++ b/server/lib/syncWire.js@@ -55,6 +55,9 @@ export function stripMusicVideoLocalRenderPins(record, { stripVideoBackend = tru// Development artifacts and the Cast & Sets checkpoint name files and jobs// on this install only (services/musicVideo/devArtifacts.js, castAndSets.js).devArtifacts: _devArtifacts, castAndSets: _castAndSets,+ // A fully-autonomous run names this install's providers, Suno songs and+ // production run (services/musicVideo/autonomousService.js).+ autonomousRun: _autonomousRun,...shared} = record;// A composition document names a folder on this install onlydiff --git a/server/lib/taskTargetScope.js b/server/lib/taskTargetScope.jsindex 6867055371..24eed98c38 100644--- a/server/lib/taskTargetScope.js+++ b/server/lib/taskTargetScope.js@@ -48,6 +48,7 @@ export function requiresManagedAppTarget(taskType) {*/export const PROGRAMMATIC_SCHEDULED_TASK_TYPES = Object.freeze(['development-watchdog',+ 'music-video-autopilot','universe-bible-describe','universe-bible-images',]);diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex b5302f1f92..fe9fe98a3f 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -56,6 +56,8 @@ import {musicVideoAutoReviewResumeSchema,musicVideoProductionStartSchema,musicVideoProductionResumeSchema,+ musicVideoAutonomousStartSchema,+ musicVideoAutonomousResumeSchema,musicVideoDevArtifactImportSchema,musicVideoDevArtifactNoteSchema,musicVideoDevArtifactNoteUpdateSchema,@@ -74,7 +76,6 @@ import {} from '../lib/validation.js';import { recordRenderPinFields } from '../lib/sharedSchemas.js';import { PATHS } from '../lib/fileUtils.js';-import { safeUnder } from '../lib/ffmpeg.js';import { resolveGalleryImage } from '../lib/pathSafety.js';import { uploadSingle } from '../lib/multipart.js';import { isSupportedMusicUpload, MUSIC_UPLOAD_MAX_BYTES } from '../services/pipeline/musicLibrary.js';@@ -105,7 +106,8 @@ import {attachMidiTranscriptionSseClient,cancelMidiTranscription,} from '../services/audioMidiTranscription.js';-import { analyzeAudioFile, analyzeAudioFileManual, buildManualAnalysisFromCached } from '../services/musicVideo/audioAnalysis.js';+import { analyzeAudioFileManual, buildManualAnalysisFromCached } from '../services/musicVideo/audioAnalysis.js';+import { analyzeProjectSong, resolveProjectAudioPath } from '../services/musicVideo/projectAudio.js';import { renderMusicVideo, attachRenderSseClient, cancelRender } from '../services/musicVideo/render.js';import { prepareCodeRender } from '../services/musicVideo/codeRender.js';import { generateMusicVideoCode, regenerateMusicVideoCodeSection } from '../services/musicVideo/codeGeneration.js';@@ -126,6 +128,9 @@ import {import {startProduction, resumeProduction, stopProduction, cancelProduction, getProduction,} from '../services/musicVideo/productionService.js';+import {+ startAutonomousVideo, getAutonomousRun, resumeAutonomousVideo, stopAutonomousVideo, cancelAutonomousVideo,+} from '../services/musicVideo/autonomousService.js';import { planProject } from '../services/musicVideo/planner.js';import {DOCUMENT_ZIP_MAX_BYTES,@@ -145,7 +150,7 @@ import { isZipUpload } from '../lib/zipStream.js';import { parseLyricCues } from '../services/musicVideo/timedText.js';import { alignProjectLyrics } from '../services/musicVideo/lyricAlign.js';import { importTrackLyrics, MAX_LYRIC_CUES } from '../services/musicVideo/trackLyrics.js';-import { offsetLyricMarkers, relabelAnalysisSections } from '../services/musicVideo/lyricMarkers.js';+import { offsetLyricMarkers } from '../services/musicVideo/lyricMarkers.js';import {updateTreatment,compileTreatment,@@ -153,7 +158,6 @@ import {applyTreatment,reviewProof,} from '../services/musicVideo/treatmentService.js';-import { getTrack } from '../services/tracks/index.js';import {listDevArtifacts,getDevArtifact,@@ -282,41 +286,11 @@ router.post('/vocal-stem/separate/:jobId/cancel', asyncHandler(async (req, res)res.json({ ok: cancelVocalSeparation(req.params.jobId) });}));-// Resolve a project's source audio to an absolute path under data/music/. The-// filename comes from the linked track or the uploaded-audio field; both are-// validated as safe basenames so a tampered record can't escape the directory.-async function resolveAudioPath(project) {- let filename = null;- if (project.trackId) {- const track = await getTrack(project.trackId);- if (!track) throw new ServerError('Linked track not found', { status: 404, code: 'NOT_FOUND' });- filename = track.audioFilename;- } else if (project.uploadedAudioFilename) {- filename = project.uploadedAudioFilename;- }- if (!filename) {- throw new ServerError('Project has no audio to analyze — set a track or upload audio first', { status: 400, code: 'NO_AUDIO' });- }- const safe = safeUnder(PATHS.music, filename);- if (!safe) throw new ServerError('Invalid audio filename', { status: 400, code: 'VALIDATION_ERROR' });- return safe;-}-// Run the offline beat/tempo/section analysis and cache it on the project.// Synchronous: the DSP pass over a song-length track is a couple of seconds, so// it returns the updated project directly (the SSE-streamed render lands later).router.post('/:id/analyze', asyncHandler(async (req, res) => {- const project = await getProject(req.params.id);- if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- const audioPath = await resolveAudioPath(project);- const analysis = await analyzeAudioFile(audioPath);- if (!analysis) {- throw new ServerError('Could not analyze audio (decode failed or ffmpeg unavailable)', { status: 422, code: 'ANALYZE_FAILED' });- }- // Timed lyrics with sheet headers name the fresh sections too (a no-op- // until the lines are aligned).- const updated = await setProjectAnalysis(project.id, relabelAnalysisSections(analysis, project.lyricCues, project.lyricMarkers));- res.json(updated);+ res.json(await analyzeProjectSong(req.params.id));}));// Manual-tempo fallback: lets a director supply a known BPM + first-downbeat@@ -333,7 +307,7 @@ router.post('/:id/analyze/manual', asyncHandler(async (req, res) => {const cached = project.audioAnalysis;const analysis = cached && Array.isArray(cached.sections) && typeof cached.durationSec === 'number'? buildManualAnalysisFromCached(cached, { bpm, offsetSec })- : await analyzeAudioFileManual(await resolveAudioPath(project), { bpm, offsetSec });+ : await analyzeAudioFileManual(await resolveProjectAudioPath(project), { bpm, offsetSec });if (!analysis) {throw new ServerError('Could not analyze audio (decode failed or ffmpeg unavailable)', { status: 422, code: 'ANALYZE_FAILED' });}@@ -443,7 +417,7 @@ router.post('/:id/transcribe-midi', asyncHandler(async (req, res) => {const { model } = validateRequest(musicVideoTranscribeMidiRequestSchema, req.body || {});const project = await getProject(req.params.id);if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- const audioPath = await resolveAudioPath(project);+ const audioPath = await resolveProjectAudioPath(project);const projectId = project.id;// Audio-source identity at kickoff — the completion callback re-checks it so// a transcription of the OLD track can't land on a project whose audio was@@ -845,6 +819,35 @@ router.post('/:id/production-runs/:runId/cancel', asyncHandler(async (req, res)res.json(await cancelProduction(req.params.id, req.params.runId));}));+// --- Fully-autonomous run (one prompt → lyrics → Suno song → video) ---+// The alternate entry point: no track, style or board is picked up front. Start+// creates the project and returns at once; the run advances in the background+// (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.+router.post('/autonomous', asyncHandler(async (req, res) => {+ const input = validateRequest(musicVideoAutonomousStartSchema, req.body || {});+ res.status(202).json(await startAutonomousVideo(input));+}));++router.get('/:id/autonomous', asyncHandler(async (req, res) => {+ res.json(await getAutonomousRun(req.params.id));+}));++// 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));+}));++router.post('/:id/autonomous/stop', asyncHandler(async (req, res) => {+ res.json(await stopAutonomousVideo(req.params.id));+}));++router.post('/:id/autonomous/cancel', asyncHandler(async (req, res) => {+ res.json(await cancelAutonomousVideo(req.params.id));+}));+// --- Development artifacts ("ingredients") ---// Reviewable development files attached to the project: list, import/upload// (HTML, Markdown, MP4, PNG, JPG — a new artifact, or a new version of one),diff --git a/server/routes/musicVideoAutonomous.test.js b/server/routes/musicVideoAutonomous.test.jsnew file mode 100644index 0000000000..184e1ac698--- /dev/null+++ b/server/routes/musicVideoAutonomous.test.js@@ -0,0 +1,122 @@+/**+ * Fully-autonomous Music Video (one prompt → lyrics → Suno song → video),+ * through the real router and the real file-backed project store. Only the+ * stage providers (LLM, mood board, Suno, track store, analysis, production)+ * are doubles. Pins what no unit test above can: request validation at the+ * door, that the run checkpoint survives the real store's read/write path, the+ * checkpoint → approve round trip over HTTP, and that the run never leaves+ * this install (peer-sync wire and clone).+ */++import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots, sweepStrayTempRoots } from '../lib/mockPathsDataRoot.js';++const ROOT = () => lazyTempDataRoot('mv-autonomous-route-test-');+vi.mock('../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), { dataRoot: ROOT }));+vi.mock('../services/settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));++const { default: musicVideoRoutes } = await import('./musicVideo.js');+const projects = await import('../services/musicVideo/projects.js');+const service = await import('../services/musicVideo/autonomousService.js');+const { stripMusicVideoLocalRenderPins } = await import('../lib/syncWire.js');++const app = express();+app.use(express.json());+app.use('/api/music-video', musicVideoRoutes);+app.use(errorMiddleware);++const BRIEF = {+ title: 'Neon Rain', musicalDescription: 'synthwave', sunoStyle: 'synthwave',+ concept: { prompt: 'a courier crosses a rainy city', style: 'neon noir' },+ moodBoard: { name: 'Neon Rain', description: 'wet streets', notes: ['teal'], stylePrompt: 'neon noir', negativePrompt: '' },+};+const startProduction = vi.fn(async () => ({ run: { id: 'mvpr-1' } }));++beforeAll(() => sweepStrayTempRoots('mv-autonomous-route-test-'));+afterAll(() => cleanupTempDataRoots());+beforeEach(() => {+ startProduction.mockClear();+ service.__setAutonomousDepsForTests({+ draftCreativeBrief: async () => ({ brief: BRIEF }),+ writeLyrics: async () => ({ lyrics: '[verse]\nrain on glass' }),+ createMoodBoard: async () => ({ id: 'board-1' }),+ generateSunoSong: async (_fields, opts) => {+ await opts.onSubmitted(['song-a']);+ return { songId: 'song-a', songIds: ['song-a'], filename: 'music-song-a.mp3' };+ },+ createTrack: async () => ({ id: 'track-1' }),+ attachAudio: async () => ({}),+ probeDuration: async () => 120,+ // The real updateProject would validate the track link against the track store.+ updateProject: async (id, patch) => (patch.trackId ? projects.getProject(id) : projects.updateProject(id, patch)),+ analyzeSong: async () => ({}),+ startProduction,+ });+});++const get = async (id) => (await request(app).get(`/api/music-video/${id}/autonomous`)).body.run;++describe('POST /api/music-video/autonomous', () => {+ it('validates at the door: a blank prompt, an unknown tool and an unknown field are 400s', async () => {+ for (const body of [{ prompt: ' ' }, { prompt: 'p', tools: ['image:nope'] }, { prompt: 'p', surprise: true }, {}]) {+ const res = await request(app).post('/api/music-video/autonomous').send(body);+ expect(res.status, JSON.stringify(body)).toBe(400);+ }+ });++ it('accepts a prompt, persists the run on the real project record and runs through to production', async () => {+ const res = await request(app).post('/api/music-video/autonomous').send({ prompt: 'a courier crosses a rainy city', tools: ['image:local'] });+ expect(res.status).toBe(202);+ const id = res.body.project.id;+ expect(res.body.project).toMatchObject({ mode: 'autonomous', automation: { tools: ['image:local'] } });++ await vi.waitFor(async () => expect((await get(id)).output.productionRunId).toBe('mvpr-1'));+ const run = await get(id);+ expect(run).toMatchObject({ status: 'running', stage: 'produce', interrupted: false });+ expect(Object.values(run.stages).map((s) => s.status)).toEqual(['done', 'done', 'done', 'done', 'done', 'running']);+ const stored = await projects.getProject(id);+ expect(stored.autonomousRun.output).toMatchObject({ moodBoardId: 'board-1', trackId: 'track-1' });+ expect(stored.name).toBe('Neon Rain');+ });++ it('parks at a checkpoint and continues over HTTP, applying the director’s lyric edit', async () => {+ const res = await request(app).post('/api/music-video/autonomous').send({ prompt: 'p', checkpoints: ['lyrics'] });+ const id = res.body.project.id;+ await vi.waitFor(async () => expect((await get(id)).status).toBe('awaiting-approval'));+ expect(startProduction).not.toHaveBeenCalled();++ const bad = await request(app).post(`/api/music-video/${id}/autonomous/resume`).send({ lyrics: 5 });+ expect(bad.status).toBe(400);+ const ok = await request(app).post(`/api/music-video/${id}/autonomous/resume`).send({ lyrics: '[verse]\nedited' });+ expect(ok.status).toBe(200);+ await vi.waitFor(async () => expect((await get(id)).output.lyrics).toBe('[verse]\nedited'));+ await vi.waitFor(() => expect(startProduction).toHaveBeenCalled());+ });++ it('cancels a live run, and refuses to cancel or resume one that is finished or absent', async () => {+ const res = await request(app).post('/api/music-video/autonomous').send({ prompt: 'p', checkpoints: ['lyrics'] });+ const id = res.body.project.id;+ await vi.waitFor(async () => expect((await get(id)).status).toBe('awaiting-approval'));+ expect((await request(app).post(`/api/music-video/${id}/autonomous/cancel`)).body.run.status).toBe('canceled');+ expect((await request(app).post(`/api/music-video/${id}/autonomous/cancel`)).status).toBe(409);+ expect((await request(app).post(`/api/music-video/${id}/autonomous/resume`)).status).toBe(409);++ const plain = await projects.createProject({ name: 'Hand made' });+ expect((await request(app).get(`/api/music-video/${plain.id}/autonomous`)).status).toBe(404);+ });+});++describe('the run stays on this install', () => {+ it('is stripped from the peer-sync wire and not carried into a clone', async () => {+ const res = await request(app).post('/api/music-video/autonomous').send({ prompt: 'p', checkpoints: ['lyrics'] });+ const id = res.body.project.id;+ await vi.waitFor(async () => expect((await get(id)).status).toBe('awaiting-approval'));+ const stored = await projects.getProject(id);+ expect(stripMusicVideoLocalRenderPins(stored)).not.toHaveProperty('autonomousRun');+ const clone = await projects.cloneProject(id, {});+ expect(clone.autonomousRun ?? null).toBeNull();+ });+});diff --git a/server/routes/tracks.js b/server/routes/tracks.jsindex 36647033d3..28c222cc87 100644--- a/server/routes/tracks.js+++ b/server/routes/tracks.js@@ -48,6 +48,7 @@ import { uploadSingle } from '../lib/multipart.js';import { PATHS } from '../lib/fileUtils.js';import { probeVideoDuration } from '../lib/ffmpeg.js';import * as tracks from '../services/tracks/index.js';+import { attachAudioAsRender } from '../services/trackAudioAttach.js';import { createTrackWithAlbum, updateTrackWithAlbum, removeTrackFromAlbum } from '../services/trackAlbumMembership.js';import {listMusicLibrary, importUploadedTrack, statMusicTrack,@@ -164,38 +165,6 @@ async function requireTrack(id) {return track;}-// Make `filename` the active audio AND record it in the render history so an-// uploaded/attached take shows up as a card alongside generated ones. An-// uploaded render has no engine/model, so the active gen-metadata is cleared-// (keeps the read-only badges honest); `take` carries what IS known about it —-// provenance, the prompt/lyrics it was made from, its probed duration. Re-attaching a file already in-// the history just re-selects it (no duplicate card).-//-// Re-reads the track by id (the caller validated existence earlier) so the-// append builds on the FRESHEST persisted history: a render added to this track-// between the route's initial load and now — a long generation finishing, or a-// parallel upload, both of which can span the file-import window — isn't dropped-// by writing back a stale renders array. (The sub-millisecond getTrack→-// updateTrack window is a single-user request race we don't lock against per the-// trust model.)-async function attachAudioAsRender(trackId, filename, take = {}) {- const track = await tracks.getTrack(trackId);- if (!track) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });- const existing = (track.renders || []).find((r) => r.audioFilename === filename);- if (existing) {- const patch = tracks.selectRenderPatch(track, existing.id) || { audioFilename: filename };- return tracks.updateTrack(trackId, patch);- }- const { renders } = tracks.buildRenderAppend(track, { ...take, audioFilename: filename });- return tracks.updateTrack(trackId, {- audioFilename: filename,- engine: '',- modelId: '',- durationSec: take.durationSec ?? null,- renders,- });-}-// Backward-compatible by default: returns the full tracks array. When a client// passes `limit`/`offset`, the response becomes the bounded// `{ items, total, limit, offset }` envelope every paginated PortOS list shares.diff --git a/server/services/musicVideo/autonomousBoard.js b/server/services/musicVideo/autonomousBoard.jsnew file mode 100644index 0000000000..359d783c7f--- /dev/null+++ b/server/services/musicVideo/autonomousBoard.js@@ -0,0 +1,33 @@+/**+ * Autonomous Music Video — build a mood board from the creative brief.+ *+ * A board of text notes plus a composite style (the same `style.prompt` /+ * `negativePrompt` shape the board's own "compose style" action writes), so+ * the project's authored style snapshot (styleSnapshots.js) reads the look+ * description first. Only text items are created: nothing here renders or+ * downloads an image, so the stage costs no media quota.+ */+import { addBoardItem, createBoard, updateBoard } from '../moodBoard/index.js';++/**+ * @param {{ name: string, description: string, notes: string[], stylePrompt: string, negativePrompt: string }} spec+ * @returns the created board (with its items and style)+ */+export async function createAutonomousMoodBoard(spec) {+ const board = await createBoard({ name: spec.name, description: spec.description });+ for (const text of spec.notes || []) {+ await addBoardItem(board.id, { type: 'text', text, source: 'autonomous music video' });+ }+ if (spec.stylePrompt) {+ await updateBoard(board.id, {+ style: {+ prompt: spec.stylePrompt,+ ...(spec.negativePrompt ? { negativePrompt: spec.negativePrompt } : {}),+ analyzedItemCount: 0,+ composedAt: new Date().toISOString(),+ },+ });+ }+ console.log(`🖼️ Autonomous music video mood board "${spec.name}" created (${(spec.notes || []).length} notes)`);+ return board;+}diff --git a/server/services/musicVideo/autonomousBrief.js b/server/services/musicVideo/autonomousBrief.jsnew file mode 100644index 0000000000..b63b734406--- /dev/null+++ b/server/services/musicVideo/autonomousBrief.js@@ -0,0 +1,99 @@+/**+ * Autonomous Music Video — the creative-brief LLM step.+ *+ * One call turns the operator's free-text prompt into everything the later+ * stages need that is not the lyrics: the song title, a musical description+ * (the lyric writer's input), a compact Suno style line, the visual concept,+ * and a mood-board spec (name, notes, a composite look prompt and what to+ * avoid). Sanitizing is strict — every field is length-bounded and a missing or+ * wrong-typed field falls back to something derived from the prompt, so a thin+ * model answer degrades the board rather than failing the run.+ *+ * Runs only inside an explicit autonomous run (AI Provider Usage Policy): the+ * run is a user-started or scheduled automation, never boot-time work.+ */++import { ServerError } from '../../lib/errorHandler.js';+import { trimTo } from '../../lib/textUtils.js';+import { SUNO_LIMITS } from '../../lib/musicVideoAutonomous.js';+import { parseLLMJSON } from '../aiProvider.js';+import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from '../promptRunner.js';++const NOTE_MAX = 600;+const NOTES_MAX = 10;++function buildBriefPrompt({ prompt, guidance, instrumental }) {+ return `You are the creative director for a fully autonomous music video. From the operator's idea below, design the song AND the look of its video.++Idea:+${prompt}+${guidance ? `\nOperator guidance:\n${guidance}\n` : ''}+${instrumental ? 'The song is INSTRUMENTAL: no vocals.\n' : ''}+Return JSON only, with exactly these keys:+{+ "title": "a short, evocative song title (max 6 words)",+ "musicalDescription": "2-4 sentences: genre and subgenres, mood and emotional arc, tempo feel, instrumentation, vocal character${instrumental ? ' (instrumental)' : ''}, production. No lyrics.",+ "sunoStyle": "a comma-separated Suno style prompt, at most ${Math.floor(SUNO_LIMITS.style * 0.9)} characters: genres, mood, tempo, instruments, vocal type, production words. No artist names.",+ "concept": {+ "prompt": "2-4 sentences: the visual story or world of the video, who/what we see, how it evolves with the song",+ "style": "one line: the overall visual style"+ },+ "moodBoard": {+ "name": "a short board name",+ "description": "1-2 sentences describing the board's through-line",+ "notes": ["5-8 short, concrete visual reference notes: palette, lighting, texture, camera, era, setting, motifs"],+ "stylePrompt": "one ready-to-render paragraph describing the consistent look (medium, palette, lighting, composition, finish)",+ "negativePrompt": "comma-separated things the look must avoid"+ }+}+Keep every value original and concrete; do not copy existing song lyrics.`;+}++/** Sanitize a parsed brief; absent/invalid fields fall back to prompt-derived text. */+function sanitizeBrief(parsed, { prompt }) {+ const root = parsed && typeof parsed === 'object' ? parsed : {};+ const seed = trimTo(prompt.replace(/\s+/g, ' ').trim(), 4000);+ const title = trimTo(root.title, SUNO_LIMITS.title) || trimTo(seed, 48) || 'Untitled';+ const board = root.moodBoard && typeof root.moodBoard === 'object' ? root.moodBoard : {};+ const concept = root.concept && typeof root.concept === 'object' ? root.concept : {};+ const notes = (Array.isArray(board.notes) ? board.notes : [])+ .map((n) => trimTo(n, NOTE_MAX)).filter(Boolean).slice(0, NOTES_MAX);+ return {+ title,+ musicalDescription: trimTo(root.musicalDescription, 4000) || seed,+ sunoStyle: trimTo(root.sunoStyle, SUNO_LIMITS.style) || trimTo(seed, 200),+ concept: {+ prompt: trimTo(concept.prompt, 4000) || seed,+ style: trimTo(concept.style, 2000),+ },+ moodBoard: {+ name: trimTo(board.name, 200) || title,+ description: trimTo(board.description, 2000) || seed.slice(0, 500),+ notes,+ stylePrompt: trimTo(board.stylePrompt, 4000),+ negativePrompt: trimTo(board.negativePrompt, 2000),+ },+ };+}++export async function draftCreativeBrief({ prompt, guidance = '', instrumental = false, providerId, model } = {}) {+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });+ assertProvider(provider, { message: 'No AI provider available to draft the music video brief', code: 'NO_PROVIDER' });+ const result = await runPromptThroughProvider({+ provider,+ model: selectedModel,+ prompt: buildBriefPrompt({ prompt, guidance, instrumental }),+ source: 'music-video-autonomous-brief',+ });+ let parsed;+ try {+ parsed = parseLLMJSON(result.text || '');+ } catch (err) {+ throw new ServerError(`The model returned an invalid creative brief: ${err.message}`, { status: 502, code: 'BRIEF_BAD_JSON' });+ }+ const brief = sanitizeBrief(parsed, { prompt });+ console.log(`🎬 Autonomous music video brief drafted via ${provider.id}/${result.model || 'default'}: "${brief.title}"`);+ return { brief, llm: { provider: provider.id, model: result.model || null } };+}++export const __testing = { buildBriefPrompt, sanitizeBrief };diff --git a/server/services/musicVideo/autonomousBrief.test.js b/server/services/musicVideo/autonomousBrief.test.jsnew file mode 100644index 0000000000..5a10ad7d8a--- /dev/null+++ b/server/services/musicVideo/autonomousBrief.test.js@@ -0,0 +1,39 @@+import { describe, it, expect } from 'vitest';+import { __testing } from './autonomousBrief.js';+import { SUNO_LIMITS } from '../../lib/musicVideoAutonomous.js';++const { sanitizeBrief, buildBriefPrompt } = __testing;++describe('sanitizeBrief', () => {+ it('bounds a verbose model answer to what the later stages accept', () => {+ const brief = sanitizeBrief({+ title: 'T'.repeat(500), sunoStyle: 's'.repeat(5000), musicalDescription: 'd',+ concept: { prompt: 'story', style: 'noir' },+ moodBoard: { name: 'Board', description: 'desc', notes: ['a', '', 42, ...Array(20).fill('n')], stylePrompt: 'look', negativePrompt: 'avoid' },+ }, { prompt: 'a courier in the rain' });+ expect(brief.title.length).toBe(SUNO_LIMITS.title);+ expect(brief.sunoStyle.length).toBe(SUNO_LIMITS.style);+ expect(brief.moodBoard.notes).toHaveLength(10);+ expect(brief.moodBoard.notes.every((n) => typeof n === 'string' && n)).toBe(true);+ });++ it('falls back to the operator’s prompt for every missing or wrong-typed field, so a thin answer degrades rather than fails', () => {+ const brief = sanitizeBrief({ title: 7, concept: 'nope', moodBoard: null }, { prompt: 'a courier in the rain' });+ expect(brief).toMatchObject({+ title: 'a courier in the rain', musicalDescription: 'a courier in the rain', sunoStyle: 'a courier in the rain',+ concept: { prompt: 'a courier in the rain', style: '' },+ moodBoard: { name: 'a courier in the rain', notes: [], stylePrompt: '' },+ });+ expect(sanitizeBrief(null, { prompt: 'p' }).title).toBe('p');+ });+});++describe('buildBriefPrompt', () => {+ it('carries the prompt and guidance, and says so when the song is instrumental', () => {+ const prompt = buildBriefPrompt({ prompt: 'rain city', guidance: 'no neon', instrumental: true });+ expect(prompt).toContain('rain city');+ expect(prompt).toContain('no neon');+ expect(prompt).toContain('INSTRUMENTAL');+ expect(buildBriefPrompt({ prompt: 'x', guidance: '', instrumental: false })).not.toContain('INSTRUMENTAL');+ });+});diff --git a/server/services/musicVideo/autonomousService.js b/server/services/musicVideo/autonomousService.jsnew file mode 100644index 0000000000..6e1b8cc158--- /dev/null+++ b/server/services/musicVideo/autonomousService.js@@ -0,0 +1,404 @@+/**+ * Fully-autonomous Music Video — the run orchestrator.+ *+ * One prompt drives a whole video: creative brief → lyrics → mood board & style+ * → Suno song (PortOS Browser) → beat analysis → the existing production run+ * (image/video tools) or a code-rendered video. The vocabulary, brief shape and+ * Suno field limits live in `lib/musicVideoAutonomous.js`.+ *+ * The run is an install-local checkpoint on the project (`project.autonomousRun`,+ * wire-local like `productionRuns`: it names this install's providers and the+ * peer must never execute it). Each stage settles in one serialized project+ * write, so a crash resumes at the stage that did not settle; a stage's output+ * is stored before the next one reads it. `processId` pins a running run to the+ * server process that started it — after a restart nothing advances until the+ * operator (or the scheduled task) explicitly resumes (AI Provider Usage+ * Policy: no cold-bootstrap work).+ *+ * Checkpoints are optional approval gates after `lyrics` / `style` / `song`:+ * the run parks `awaiting-approval` and continues on approve. A signed-out+ * Suno parks `needs-human`; any other failure parks `failed`. Both resume at the+ * stage that stopped, reusing Suno songs already submitted.+ *+ * 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.+ */++import { randomUUID } from 'crypto';+import { join } from 'path';+import { PATHS } from '../../lib/fileUtils.js';+import { probeVideoDuration } from '../../lib/ffmpeg.js';+import { ServerError } from '../../lib/errorHandler.js';+import { trimTo } from '../../lib/textUtils.js';+import {+ AUTONOMOUS_LIVE_STATUSES,+ AUTONOMOUS_STAGE_IDS,+ autonomousMedium,+ autonomousPool,+ nextAutonomousStage,+ normalizeAutonomousBrief,+ sunoSongFields,+} from '../../lib/musicVideoAutonomous.js';+import { getProject, mutateProjectRecord } from './projects.js';+import { musicVideoEvents } from './events.js';++const PROCESS_ID = `proc-${randomUUID()}`;+const inflight = new Set();+const short = (id) => String(id).slice(0, 8);++// Lazy imports keep this module's static closure small: it is reached by the+// route table and the scheduled handler, and each dependency below pulls a+// whole subtree (LLM runner, mood board store, browser driver, production).+const defaults = {+ createProject: async (input) => (await import('./projects.js')).createProject(input),+ updateProject: async (id, patch) => (await import('./projects.js')).updateProject(id, patch),+ draftCreativeBrief: async (args) => (await import('./autonomousBrief.js')).draftCreativeBrief(args),+ writeLyrics: async (args) => (await import('../musicDesigner.js')).writeLyrics(args),+ createMoodBoard: async (spec) => (await import('./autonomousBoard.js')).createAutonomousMoodBoard(spec),+ generateSunoSong: async (fields, opts) => (await import('./autonomousSuno.js')).generateSunoSong(fields, opts),+ createTrack: async (input) => (await import('../trackAlbumMembership.js')).createTrackWithAlbum(input).then((r) => r.track),+ attachAudio: async (trackId, filename, take) => (await import('../trackAudioAttach.js')).attachAudioAsRender(trackId, filename, take),+ probeDuration: (filename) => probeVideoDuration(join(PATHS.music, filename)).catch(() => null),+ analyzeSong: async (projectId) => (await import('./projectAudio.js')).analyzeProjectSong(projectId),+ startProduction: async (...args) => (await import('./productionService.js')).startProduction(...args),+ generateCode: async (...args) => (await import('./codeGeneration.js')).generateMusicVideoCode(...args),+ renderVideo: async (...args) => (await import('./render.js')).renderMusicVideo(...args),+};+let deps = { ...defaults };+export function __setAutonomousDepsForTests(overrides) { deps = { ...defaults, ...overrides }; }++const runError = (status, code, message, context) =>+ new ServerError(message, { status, code, ...(context ? { context } : {}) });++const projectAutonomousRun = (project) => project?.autonomousRun || null;++async function requireRun(projectId) {+ const project = await getProject(projectId);+ if (!project) throw runError(404, 'NOT_FOUND', 'Project not found');+ const run = projectAutonomousRun(project);+ if (!run) throw runError(404, 'NO_AUTONOMOUS_RUN', 'This project has no autonomous run');+ return { project, run };+}++/** The run as the client sees it: `interrupted` when it was pinned to a previous server process. */+export const presentAutonomousRun = (run) => (run+ ? { ...run, interrupted: run.status === 'running' && run.processId !== PROCESS_ID }+ : null);++function publish(project, run) {+ musicVideoEvents.emit('autonomous', { projectId: project.id, runId: run.id, run: presentAutonomousRun(run), project: { ...project, autonomousRun: presentAutonomousRun(run) } });+}++/** One serialized write of the run record; `fn` returns the patch to merge. */+async function patchRun(projectId, fn) {+ const now = new Date().toISOString();+ const out = await mutateProjectRecord(projectId, (current) => {+ const run = projectAutonomousRun(current);+ if (!run) throw runError(404, 'NO_AUTONOMOUS_RUN', 'This project has no autonomous run');+ const patch = fn(run, current) || {};+ const next = {+ ...run,+ ...patch,+ stages: { ...run.stages, ...(patch.stages || {}) },+ output: { ...run.output, ...(patch.output || {}) },+ updatedAt: now,+ };+ return { project: { ...current, autonomousRun: next }, run: next };+ });+ publish(out.project, out.run);+ return out;+}++const stagePatch = (run, stage, patch) => ({ stages: { [stage]: { ...run.stages[stage], ...patch } } });++// ---- stage executors -------------------------------------------------------------+// Each returns `{ output }` (merged into run.output) or `{ output, wait: true }`+// when the stage's completion arrives later (production).++const llmOf = (run) => ({ providerId: run.brief.llm?.providerId, model: run.brief.llm?.model || undefined });++const STAGES = {+ async brief({ project, run }) {+ const { brief } = await deps.draftCreativeBrief({+ prompt: run.brief.prompt, guidance: run.brief.guidance, instrumental: run.brief.instrumental, ...llmOf(run),+ });+ // A blank project name from the prompt gives way to the song title.+ if (!run.brief.name) await deps.updateProject(project.id, { name: trimTo(brief.title, 200) });+ return { output: brief };+ },++ async lyrics({ run }) {+ if (run.brief.instrumental) return { output: { lyrics: '' } };+ const { lyrics } = await deps.writeLyrics({+ description: run.output.musicalDescription, guidance: run.brief.guidance || undefined, ...llmOf(run),+ });+ return { output: { lyrics } };+ },++ async style({ project, run }) {+ const board = run.output.moodBoard;+ const moodBoardId = run.output.moodBoardId || (await deps.createMoodBoard(board)).id;+ // The board is also the project's linked mood board; the server derives the+ // authored style snapshot from it (styleSnapshots.js).+ await deps.updateProject(project.id, {+ concept: { prompt: run.output.concept.prompt, ...(run.output.concept.style ? { style: run.output.concept.style } : {}) },+ visualSpec: { moodBoardId },+ });+ return { output: { moodBoardId } };+ },++ async song({ project, run, save }) {+ if (run.output.trackId) return { output: {} };+ const fields = sunoSongFields({+ title: run.output.title, style: run.output.sunoStyle, lyrics: run.output.lyrics, instrumental: run.brief.instrumental,+ });+ const song = await deps.generateSunoSong(fields, {+ songIds: run.output.sunoSongIds,+ // Stored the moment Suno accepts the request, so a failed download retries+ // the same songs instead of spending credits on another generation.+ onSubmitted: (ids) => save({ output: { sunoSongIds: ids } }),+ });+ const track = await deps.createTrack({+ title: fields.title, concept: run.brief.prompt, lyrics: fields.lyrics, prompt: fields.style,+ });+ const durationSec = await deps.probeDuration(song.filename);+ await deps.attachAudio(track.id, song.filename, { source: 'suno', prompt: fields.style, lyrics: fields.lyrics, durationSec });+ // Linking the track seeds the project's timed lyric cues from the track lyrics.+ await deps.updateProject(project.id, { trackId: track.id });+ return { output: { trackId: track.id, sunoSongIds: song.songIds } };+ },++ async analyze({ project }) {+ await deps.analyzeSong(project.id);+ return { output: {} };+ },++ async produce({ project, run }) {+ const medium = autonomousMedium(run.brief.tools);+ if (medium === 'code') {+ await deps.updateProject(project.id, { composition: { mode: 'code' } });+ const authoring = run.brief.authoring || (run.brief.llm ? { providerId: run.brief.llm.providerId, model: run.brief.llm.model } : {});+ await deps.generateCode(project.id, { providerId: authoring.providerId, model: authoring.model || undefined });+ const render = await deps.renderVideo(project.id);+ return { output: { renderJobId: render?.jobId || null } };+ }+ const started = await deps.startProduction(project.id, {+ directive: trimTo([run.brief.prompt, run.brief.guidance].filter(Boolean).join('\n\n'), 4000),+ pool: autonomousPool(run.brief.tools, run.brief.models),+ limits: { ...run.brief.limits, ...(run.brief.budgetUsd != null ? { spendCapUsd: run.brief.budgetUsd } : {}) },+ reviewer: { providerId: run.brief.llm?.providerId || null, model: run.brief.llm?.model || null },+ });+ return { output: { productionRunId: started.run.id }, wait: true };+ },+};++// ---- the advance loop ------------------------------------------------------------++const isLoginRequired = (err) => err?.code === 'PUBLISH_LOGIN_REQUIRED';++async function park(projectId, status, patch) {+ const out = await patchRun(projectId, () => ({ status, ...patch }));+ const log = status === 'failed' ? console.error : status === 'completed' ? console.log : console.warn;+ log(`${status === 'completed' ? '✅' : status === 'failed' ? '❌' : '⏸️'} Autonomous music video ${short(out.run.id)} ${status}${patch.error ? `: ${patch.error}` : ''}`);+ return out;+}++async function advance(projectId) {+ if (inflight.has(projectId)) return;+ inflight.add(projectId);+ try {+ for (;;) {+ const project = await getProject(projectId);+ const run = projectAutonomousRun(project);+ if (!run || run.status !== 'running' || run.processId !== PROCESS_ID) return;+ const stage = run.stage;+ const executor = STAGES[stage];+ if (!executor) {+ await park(projectId, 'failed', { error: `Unknown stage "${stage}"`, errorCode: 'UNKNOWN_STAGE' });+ return;+ }+ await patchRun(projectId, (r) => stagePatch(r, stage, { status: 'running', startedAt: new Date().toISOString(), error: null }));+ let result;+ try {+ result = await executor({ project, run, save: (patch) => patchRun(projectId, () => patch) });+ } catch (err) {+ await patchRun(projectId, (r) => stagePatch(r, stage, { status: 'failed', error: trimTo(err.message, 500) }));+ await park(projectId, isLoginRequired(err) ? 'needs-human' : 'failed', { error: trimTo(err.message, 500), errorCode: err.code || null });+ return;+ }+ const finishedAt = new Date().toISOString();+ if (result.wait) {+ await patchRun(projectId, (r) => ({ output: result.output, ...stagePatch(r, stage, { status: 'running' }) }));+ console.log(`🎬 Autonomous music video ${short(run.id)} handed ${stage} to production`);+ return;+ }+ const next = nextAutonomousStage(stage);+ const checkpoint = run.brief.checkpoints.includes(stage);+ await patchRun(projectId, (r) => ({+ output: result.output,+ ...stagePatch(r, stage, { status: 'done', finishedAt }),+ ...(checkpoint ? { status: 'awaiting-approval', awaiting: stage, stage: next } : next ? { stage: next } : { status: 'completed', stage }),+ }));+ console.log(`🎬 Autonomous music video ${short(run.id)} finished ${stage}${checkpoint ? ' — waiting for approval' : ''}`);+ if (checkpoint || !next) return;+ }+ } catch (err) {+ console.error(`❌ Autonomous music video advance failed for ${short(projectId)}: ${err.message}`);+ } finally {+ inflight.delete(projectId);+ }+}++function advanceInBackground(projectId) {+ advance(projectId).catch((err) => console.error(`❌ Autonomous music video advance failed for ${short(projectId)}: ${err.message}`));+}++// ---- director actions ------------------------------------------------------------++const emptyStages = () => Object.fromEntries(AUTONOMOUS_STAGE_IDS.map((id) => [id, { status: 'pending', startedAt: null, finishedAt: null, error: null }]));++/**+ * 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);+ if (!brief.prompt) throw runError(400, 'VALIDATION_ERROR', 'A prompt is required');+ const now = new Date().toISOString();+ const created = await deps.createProject({+ name: brief.name || trimTo(brief.prompt.replace(/\s+/g, ' '), 60) || 'Autonomous music video',+ mode: 'autonomous',+ concept: { prompt: trimTo(brief.prompt, 8000) },+ automation: {+ tools: brief.tools,+ guidance: brief.guidance,+ budgetUsd: brief.budgetUsd,+ checkins: { castAndSets: brief.checkpoints.includes('cast') ? 'review' : 'auto' },+ },+ });+ const run = {+ id: `mvar-${randomUUID()}`,+ status: 'running',+ stage: AUTONOMOUS_STAGE_IDS[0],+ awaiting: null,+ brief,+ stages: emptyStages(),+ output: {},+ error: null,+ errorCode: null,+ processId: PROCESS_ID,+ createdAt: now,+ 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' : ''})`);+ publish(out.project, out.run);+ advanceInBackground(created.id);+ return { project: out.project, run: presentAutonomousRun(out.run) };+}++export async function getAutonomousRun(projectId) {+ const { run } = await requireRun(projectId);+ return { run: presentAutonomousRun(run) };+}++/**+ * Resume a parked, failed or interrupted run at the stage that stopped — or+ * approve the checkpoint it is waiting on (optionally replacing the stage+ * output the director edited). Returns `{ project, run }`.+ */+export async function resumeAutonomousVideo(projectId, edits = {}) {+ const { run } = await requireRun(projectId);+ const resumable = AUTONOMOUS_LIVE_STATUSES.includes(run.status) || run.status === 'failed';+ if (!resumable) throw runError(409, 'NOT_RESUMABLE', `A ${run.status} run cannot be resumed`);+ if (run.status === 'running' && run.processId === PROCESS_ID) throw runError(409, 'ALREADY_RUNNING', 'This run is already running');+ const out = await patchRun(projectId, (r) => {+ // A run waiting on production resumes by resuming that run, not by redoing+ // the stage — the stage re-runs only when production never started.+ const stage = r.stage;+ return {+ status: 'running', awaiting: null, error: null, errorCode: null, processId: PROCESS_ID,+ output: {+ ...(typeof edits.lyrics === 'string' ? { lyrics: edits.lyrics } : {}),+ ...(typeof edits.style === 'string' && edits.style.trim() ? { sunoStyle: edits.style.trim() } : {}),+ },+ ...stagePatch(r, stage, { error: null }),+ };+ });+ if (out.run.stage === 'produce' && out.run.output.productionRunId) {+ const { resumeProduction } = await import('./productionService.js');+ const failure = await resumeProduction(projectId, out.run.output.productionRunId, { acceptBasis: true }).then(() => null, (err) => err);+ if (failure) {+ // A failed or canceled production run cannot be resumed; say so rather than leave the run looking live.+ const parked = await park(projectId, 'needs-human', { error: trimTo(`Production could not resume: ${failure.message}`, 500), errorCode: failure.code || null });+ return { project: parked.project, run: presentAutonomousRun(parked.run) };+ }+ return { project: out.project, run: presentAutonomousRun(out.run) };+ }+ advanceInBackground(projectId);+ return { project: out.project, run: presentAutonomousRun(out.run) };+}++export async function stopAutonomousVideo(projectId) {+ const { run } = await requireRun(projectId);+ if (!['running', 'awaiting-approval', 'needs-human'].includes(run.status)) throw runError(409, 'NOT_RUNNING', `A ${run.status} run cannot be stopped`);+ const out = await patchRun(projectId, () => ({ status: 'stopped' }));+ if (run.output.productionRunId) {+ const { stopProduction } = await import('./productionService.js');+ await stopProduction(projectId, run.output.productionRunId).catch(() => {});+ }+ return { project: out.project, run: presentAutonomousRun(out.run) };+}++export async function cancelAutonomousVideo(projectId) {+ const { run } = await requireRun(projectId);+ if (!(AUTONOMOUS_LIVE_STATUSES.includes(run.status) || run.status === 'failed')) throw runError(409, 'NOT_CANCELABLE', `A ${run.status} run cannot be canceled`);+ const out = await patchRun(projectId, () => ({ status: 'canceled', awaiting: null }));+ if (run.output.productionRunId) {+ const { cancelProduction } = await import('./productionService.js');+ await cancelProduction(projectId, run.output.productionRunId).catch(() => {});+ }+ return { project: out.project, run: presentAutonomousRun(out.run) };+}++// ---- production completion -------------------------------------------------------++const PRODUCTION_PARKED = new Set(['limit-reached', 'blocked', 'needs-replan', 'needs-human', 'stopped']);++/**+ * A production run this autonomous run delegated to advanced. Mirrors its+ * terminal state onto the run: completed → kick off the final render and+ * finish; failed → failed; any parked state → needs-human (resume continues it).+ */+async function onProductionEvent({ projectId, runId, run: production }) {+ // Production emits on every step; only a terminal or parked state concerns us, and+ // the project is read only once one arrives.+ if (!projectId || !(['completed', 'failed', 'canceled'].includes(production?.status) || PRODUCTION_PARKED.has(production?.status))) return;+ const project = await getProject(projectId).catch(() => null);+ const run = projectAutonomousRun(project);+ if (!run || run.stage !== 'produce' || run.output.productionRunId !== runId) return;+ if (!['running', 'needs-human'].includes(run.status)) return;+ const reason = trimTo(production.stopReason || production.error || '', 500);+ if (production.status === 'completed') {+ const render = await deps.renderVideo(projectId).catch((err) => ({ error: err }));+ await patchRun(projectId, (r) => ({+ status: 'completed',+ ...stagePatch(r, 'produce', { status: render.error ? 'failed' : 'done', finishedAt: new Date().toISOString(), error: render.error ? trimTo(render.error.message, 500) : null }),+ ...(render.error ? { error: `The draft is ready, but the final render did not start: ${trimTo(render.error.message, 400)}` } : { output: { renderJobId: render.jobId || null } }),+ }));+ console.log(`✅ Autonomous music video ${short(run.id)} finished${render.error ? ' (final render did not start)' : ' — final render started'}`);+ } else if (production.status === 'failed') {+ await park(projectId, 'failed', { error: reason || 'Production failed', errorCode: 'PRODUCTION_FAILED' });+ } else if (production.status === 'canceled') {+ await park(projectId, 'canceled', { error: reason || null });+ } else if (PRODUCTION_PARKED.has(production.status) && run.status === 'running') {+ await park(projectId, 'needs-human', { error: reason || `Production is ${production.status}`, errorCode: 'PRODUCTION_PARKED' });+ }+}++musicVideoEvents.on('production', (event) => {+ onProductionEvent(event).catch((err) => console.error(`❌ Autonomous music video could not settle on production: ${err.message}`));+});++export const __testing = { onProductionEvent, advance };diff --git a/server/services/musicVideo/autonomousService.test.js b/server/services/musicVideo/autonomousService.test.jsnew file mode 100644index 0000000000..210d0877ae--- /dev/null+++ b/server/services/musicVideo/autonomousService.test.js@@ -0,0 +1,218 @@+/**+ * Fully-autonomous Music Video run — orchestration contract. The project store+ * is an in-memory double with the real store's serialized read-modify-write;+ * every stage's provider (LLM, mood board, Suno, track store, production) is a+ * double, so these tests pin what the run owns: stage order and persistence,+ * checkpoints, failure parking and retry, and the hand-off to production.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const store = new Map();+let writeTail = Promise.resolve();+const clone = (v) => JSON.parse(JSON.stringify(v));+vi.mock('./projects.js', () => ({+ getProject: async (id) => (store.has(id) ? clone(store.get(id)) : null),+ mutateProjectRecord: (id, transform) => {+ const run = writeTail.then(() => {+ if (!store.has(id)) throw Object.assign(new Error('Project not found'), { status: 404 });+ const out = transform(clone(store.get(id)));+ store.set(id, clone(out.project));+ return { ...out, project: clone(out.project) };+ });+ writeTail = run.catch(() => {});+ return run;+ },+}));++const { musicVideoEvents } = await import('./events.js');+const service = await import('./autonomousService.js');++const BRIEF = {+ title: 'Neon Rain',+ musicalDescription: 'Synthwave with a melancholic arc',+ sunoStyle: 'synthwave, dreamy, 100 bpm',+ concept: { prompt: 'A courier crosses a rainy city at night', style: 'neon noir' },+ moodBoard: { name: 'Neon Rain', description: 'wet streets', notes: ['teal and magenta'], stylePrompt: 'neon noir', negativePrompt: 'daylight' },+};++let calls;+let doubles;+const stub = (name, impl) => vi.fn(async (...args) => { calls.push(name); return impl(...args); });++beforeEach(() => {+ store.clear();+ calls = [];+ doubles = {+ createProject: stub('createProject', async (input) => {+ const project = { id: 'mv-auto', ...input };+ store.set(project.id, clone(project));+ return project;+ }),+ updateProject: stub('updateProject', async (id, patch) => {+ const next = { ...store.get(id), ...patch };+ store.set(id, clone(next));+ return next;+ }),+ draftCreativeBrief: stub('brief', async () => ({ brief: BRIEF })),+ writeLyrics: stub('lyrics', async () => ({ lyrics: '[verse]\nrain on glass' })),+ createMoodBoard: stub('board', async () => ({ id: 'board-1' })),+ generateSunoSong: stub('suno', async (_fields, opts) => {+ await opts.onSubmitted(['song-a', 'song-b']);+ return { songId: 'song-a', songIds: ['song-a', 'song-b'], filename: 'music-song-a.mp3' };+ }),+ createTrack: stub('track', async () => ({ id: 'track-1' })),+ attachAudio: stub('attach', async () => ({})),+ probeDuration: stub('probe', async () => 187),+ analyzeSong: stub('analyze', async () => ({})),+ startProduction: stub('production', async () => ({ run: { id: 'mvpr-1' } })),+ generateCode: stub('code', async () => ({})),+ renderVideo: stub('render', async () => ({ jobId: 'render-1' })),+ };+ service.__setAutonomousDepsForTests(doubles);+});++const runOf = (id = 'mv-auto') => store.get(id)?.autonomousRun;+const settled = (status) => vi.waitFor(() => expect(runOf()?.status).toBe(status));++describe('startAutonomousVideo', () => {+ it('creates an autonomous-mode project from the prompt alone and runs to the production hand-off', async () => {+ const { project, run } = await service.startAutonomousVideo({ prompt: 'a courier crosses a rainy city', tools: ['image:local', 'video:local'], models: { 'image:local': 'flux2-dev' } });+ expect(project.mode).toBe('autonomous');+ expect(project.automation).toMatchObject({ tools: ['image:local', 'video:local'], checkins: { castAndSets: 'auto' } });+ expect(run).toMatchObject({ status: 'running', stage: 'brief' });++ // Production is delegated, so the run stays "running" at the produce stage.+ await vi.waitFor(() => expect(calls).toContain('production'));+ expect(calls).toEqual(['createProject', 'brief', 'updateProject', 'lyrics', 'board', 'updateProject', 'suno', 'track', 'probe', 'attach', 'updateProject', 'analyze', 'production']);+ expect(runOf()).toMatchObject({ status: 'running', stage: 'produce' });+ expect(runOf().output).toMatchObject({ trackId: 'track-1', moodBoardId: 'board-1', productionRunId: 'mvpr-1', sunoSongIds: ['song-a', 'song-b'] });+ expect(doubles.startProduction).toHaveBeenCalledWith('mv-auto', expect.objectContaining({+ pool: [{ kind: 'image', mode: 'local', model: 'flux2-dev' }, { kind: 'video', mode: 'local' }],+ limits: { maxGenerations: 40, maxReviewAttempts: 3 },+ }));+ // The song title renames the project; the track carries the prompt/lyrics Suno was given.+ expect(store.get('mv-auto').name).toBe('Neon Rain');+ expect(doubles.attachAudio).toHaveBeenCalledWith('track-1', 'music-song-a.mp3', expect.objectContaining({ source: 'suno', durationSec: 187 }));+ });++ it('finishes — and starts the final render — when the delegated production run completes', async () => {+ await service.startAutonomousVideo({ prompt: 'p' });+ await vi.waitFor(() => expect(runOf()?.output.productionRunId).toBe('mvpr-1'));+ // An unrelated production run and a non-terminal event change nothing.+ await service.__testing.onProductionEvent({ projectId: 'mv-auto', runId: 'someone-else', run: { status: 'completed' } });+ await service.__testing.onProductionEvent({ projectId: 'mv-auto', runId: 'mvpr-1', run: { status: 'running' } });+ expect(runOf().status).toBe('running');++ await service.__testing.onProductionEvent({ projectId: 'mv-auto', runId: 'mvpr-1', run: { status: 'completed' } });+ expect(runOf()).toMatchObject({ status: 'completed', output: expect.objectContaining({ renderJobId: 'render-1' }) });+ });++ it('parks needs-human when production parks, and failed when it fails', async () => {+ await service.startAutonomousVideo({ prompt: 'p' });+ await vi.waitFor(() => expect(runOf()?.output.productionRunId).toBe('mvpr-1'));+ await service.__testing.onProductionEvent({ projectId: 'mv-auto', runId: 'mvpr-1', run: { status: 'limit-reached', stopReason: 'generation limit' } });+ expect(runOf()).toMatchObject({ status: 'needs-human', error: 'generation limit' });+ });++ it('renders a code-only brief directly: generate the code, render, no production run', async () => {+ await service.startAutonomousVideo({ prompt: 'p', tools: ['code:render'], authoring: { providerId: 'prov', model: 'm' } });+ await settled('running').catch(() => {});+ await vi.waitFor(() => expect(calls).toContain('render'));+ expect(calls).not.toContain('production');+ expect(doubles.generateCode).toHaveBeenCalledWith('mv-auto', { providerId: 'prov', model: 'm' });+ expect(store.get('mv-auto').composition).toEqual({ mode: 'code' });+ await settled('completed');+ });++ it('sends the Cast & Sets check-in to review only when the cast checkpoint is chosen', async () => {+ const { project } = await service.startAutonomousVideo({ prompt: 'p', checkpoints: ['cast'] });+ expect(project.automation.checkins.castAndSets).toBe('review');+ await vi.waitFor(() => expect(calls).toContain('production')); // let the background run finish before the next test resets the doubles+ });++ it('rejects a blank prompt', async () => {+ await expect(service.startAutonomousVideo({ prompt: ' ' })).rejects.toMatchObject({ status: 400 });+ expect(calls).toEqual([]);+ });+});++describe('checkpoints', () => {+ it('parks after a checkpointed stage, then approves with the director’s edited lyrics', async () => {+ await service.startAutonomousVideo({ prompt: 'p', checkpoints: ['lyrics'] });+ await settled('awaiting-approval');+ expect(runOf()).toMatchObject({ awaiting: 'lyrics', stage: 'style' });+ // Nothing spends past the checkpoint (no board, no Suno) until approval.+ expect(calls).not.toContain('board');+ expect(calls).not.toContain('suno');++ await service.resumeAutonomousVideo('mv-auto', { lyrics: '[verse]\nedited line' });+ await vi.waitFor(() => expect(calls).toContain('production'));+ expect(doubles.generateSunoSong).toHaveBeenCalledWith(expect.objectContaining({ lyrics: '[verse]\nedited line' }), expect.any(Object));+ });+});++describe('failure and retry', () => {+ it('parks needs-human on a signed-out Suno, then retries that stage with the same inputs', async () => {+ doubles.generateSunoSong.mockImplementationOnce(async () => {+ throw Object.assign(new Error('Sign in to Suno'), { code: 'PUBLISH_LOGIN_REQUIRED' });+ });+ await service.startAutonomousVideo({ prompt: 'p' });+ await settled('needs-human');+ expect(runOf()).toMatchObject({ stage: 'song', errorCode: 'PUBLISH_LOGIN_REQUIRED' });+ expect(runOf().stages.song.status).toBe('failed');+ // The earlier stages' output survived: nothing is re-drafted on retry.+ const briefCalls = calls.filter((c) => c === 'brief').length;++ await service.resumeAutonomousVideo('mv-auto');+ await vi.waitFor(() => expect(calls).toContain('production'));+ expect(calls.filter((c) => c === 'brief').length).toBe(briefCalls);+ expect(runOf().stages.song.status).toBe('done');+ });++ it('keeps the submitted Suno songs when the download fails, so a retry reuses them', async () => {+ doubles.generateSunoSong.mockImplementationOnce(async (_f, opts) => {+ await opts.onSubmitted(['song-a', 'song-b']);+ throw new Error('did not finish rendering');+ });+ await service.startAutonomousVideo({ prompt: 'p' });+ await settled('failed');+ expect(runOf().output.sunoSongIds).toEqual(['song-a', 'song-b']);++ await service.resumeAutonomousVideo('mv-auto');+ await vi.waitFor(() => expect(calls).toContain('production'));+ expect(doubles.generateSunoSong).toHaveBeenLastCalledWith(expect.any(Object), expect.objectContaining({ songIds: ['song-a', 'song-b'] }));+ });++ it('refuses to resume a finished run and to start a second advance of a live one', async () => {+ await service.startAutonomousVideo({ prompt: 'p' });+ await vi.waitFor(() => expect(runOf()?.output.productionRunId).toBe('mvpr-1'));+ await expect(service.resumeAutonomousVideo('mv-auto')).rejects.toMatchObject({ code: 'ALREADY_RUNNING' });+ await service.__testing.onProductionEvent({ projectId: 'mv-auto', runId: 'mvpr-1', run: { status: 'completed' } });+ await expect(service.resumeAutonomousVideo('mv-auto')).rejects.toMatchObject({ code: 'NOT_RESUMABLE' });+ });+});++describe('events and process pinning', () => {+ it('publishes every change over the autonomous event', async () => {+ const seen = [];+ const listener = (e) => seen.push(e.run.status);+ musicVideoEvents.on('autonomous', listener);+ await service.startAutonomousVideo({ prompt: 'p', checkpoints: ['song'] });+ await settled('awaiting-approval');+ musicVideoEvents.off('autonomous', listener);+ expect(seen[0]).toBe('running');+ expect(seen.at(-1)).toBe('awaiting-approval');+ });++ it('shows a run pinned to another server process as interrupted and does not advance it', async () => {+ await service.startAutonomousVideo({ prompt: 'p', checkpoints: ['lyrics'] });+ await settled('awaiting-approval');+ const stale = { ...runOf(), status: 'running', processId: 'proc-from-before-restart' };+ store.set('mv-auto', { ...store.get('mv-auto'), autonomousRun: stale });+ expect(service.presentAutonomousRun(stale).interrupted).toBe(true);+ const before = calls.length;+ await service.__testing.advance('mv-auto');+ expect(calls.length).toBe(before);+ });+});diff --git a/server/services/musicVideo/autonomousSuno.js b/server/services/musicVideo/autonomousSuno.jsnew file mode 100644index 0000000000..70a6c89b31--- /dev/null+++ b/server/services/musicVideo/autonomousSuno.js@@ -0,0 +1,159 @@+/**+ * Autonomous Music Video — the Suno step.+ *+ * Drives the Suno web UI in the PortOS Browser (the same signed-in profile the+ * publish adapters use; no Suno API or credential is involved) to make one song+ * from generated lyrics + a style line, then downloads the finished audio from+ * Suno's public CDN into the music library and imports it as a Track.+ *+ * Two deliberate choices keep this robust to Suno's UI churn:+ * - The page is only used to FILL the custom-song form, press Create, and+ * read back the new `/song/<id>` links. Everything after that — waiting for+ * the song and fetching the audio — happens over HTTP against the CDN, so a+ * redesigned player or download menu cannot break it.+ * - Every page interaction goes through `step()`, so a failure names the+ * control that was missing ("Suno: fill the lyrics (...)") and a signed-out+ * page is reported as PUBLISH_LOGIN_REQUIRED, which the run surfaces as a+ * parked "needs you" state rather than a generic failure.+ *+ * `page`, `fetch`, `sleep` and the storage calls are injectable so the whole+ * flow is unit-testable without a browser or the network.+ */++import { mkdtemp, rm, writeFile } from 'fs/promises';+import { join } from 'path';+import { tmpdir } from 'os';+import { ServerError } from '../../lib/errorHandler.js';+import { sunoAudioUrl, sunoSongIdsFromHrefs, sunoSongUrl } from '../../lib/musicVideoAutonomous.js';+import { sleep as defaultSleep } from '../../lib/fileCore.js';+import { PUBLISH_STEP_TIMEOUT_MS as T, connectPortosBrowser, loginRequired, serializeBrowserOperation as serialize, step } from './publish/browser.js';++const LABEL = 'Suno';+const SUNO_CREATE_URL = 'https://suno.com/create';+// How long a generation may take before the run gives up on it, and how often+// the CDN is polled while waiting. Suno finishes a song in roughly a minute or+// two; the cap covers a busy queue.+const SUNO_AUDIO_TIMEOUT_MS = 10 * 60 * 1000;+const SUNO_POLL_INTERVAL_MS = 10 * 1000;+// A real song is megabytes; anything under this is a stub or error body.+const MIN_AUDIO_BYTES = 100 * 1024;++const songLinks = (page) => page.evaluate(() => [...document.querySelectorAll('a[href*="/song/"]')].map((a) => a.getAttribute('href')));++/**+ * Fill Suno's custom-song form and press Create. Returns the ids of the songs+ * that appeared (Suno makes two takes per request) — the links present before+ * the click are excluded, so an older song in the workspace is never mistaken+ * for ours.+ */+async function submitSunoSong(page, fields, { sleep = defaultSleep } = {}) {+ await step(LABEL, 'open the create page', () => page.goto(SUNO_CREATE_URL, { waitUntil: 'domcontentloaded', timeout: T }));+ await sleep(4000);+ // A signed-out visitor is bounced to a sign-in page or sees no create form.+ const url = typeof page.url === 'function' ? page.url() : '';+ const hasForm = await page.locator('textarea').count();+ if (/sign-?in|login|accounts\./i.test(url) || !hasForm) throw loginRequired(LABEL, SUNO_CREATE_URL);++ await step(LABEL, 'switch to custom mode', async () => {+ const custom = page.getByRole('button', { name: /^custom$/i });+ if (await custom.count()) await custom.first().click({ timeout: T });+ });+ await step(LABEL, 'fill the lyrics', async () => {+ const box = page.locator('textarea[placeholder*="lyrics" i]').first();+ if (fields.instrumental || !fields.lyrics) return;+ await box.fill(fields.lyrics, { timeout: T });+ });+ await step(LABEL, 'fill the style', async () => {+ await page.locator('textarea[placeholder*="style" i]').first().fill(fields.style, { timeout: T });+ });+ await step(LABEL, 'fill the title', async () => {+ const title = page.locator('input[placeholder*="title" i]').first();+ if (await title.count()) await title.fill(fields.title, { timeout: T });+ });+ if (fields.instrumental) {+ await step(LABEL, 'turn instrumental on', async () => {+ await page.getByRole('button', { name: /^instrumental$/i }).first().click({ timeout: T });+ });+ }++ const before = new Set(sunoSongIdsFromHrefs(await songLinks(page)));+ await step(LABEL, 'press Create', async () => {+ await page.getByRole('button', { name: /^create( song)?$/i }).last().click({ timeout: T });+ });++ // New rows land at the top of the workspace list once Suno accepts the request.+ const deadline = Date.now() + 90_000;+ while (Date.now() < deadline) {+ await sleep(3000);+ const fresh = sunoSongIdsFromHrefs(await songLinks(page)).filter((id) => !before.has(id));+ if (fresh.length) return fresh;+ }+ throw new ServerError('Suno: no new song appeared after pressing Create — check the PortOS Browser for a credits, captcha or content-policy prompt', {+ status: 502, code: 'SUNO_NO_SONG', context: { platform: LABEL },+ });+}++/**+ * Wait for a song's audio to be fetchable and fully written, then return its+ * bytes. "Fully written" = a 200 whose size is at least MIN_AUDIO_BYTES and+ * unchanged across two polls (Suno streams a partial file while it renders).+ */+async function downloadSunoAudio(songId, {+ fetchImpl = fetch, sleep = defaultSleep, timeoutMs = SUNO_AUDIO_TIMEOUT_MS, intervalMs = SUNO_POLL_INTERVAL_MS, now = Date.now,+} = {}) {+ const deadline = now() + timeoutMs;+ let lastSize = -1;+ for (;;) {+ const res = await fetchImpl(sunoAudioUrl(songId)).catch(() => null);+ if (res?.ok) {+ const bytes = Buffer.from(await res.arrayBuffer());+ if (bytes.length >= MIN_AUDIO_BYTES && bytes.length === lastSize) return bytes;+ lastSize = bytes.length;+ }+ if (now() + intervalMs > deadline) {+ throw new ServerError(`Suno: the song ${songId} did not finish rendering in time`, {+ status: 504, code: 'SUNO_AUDIO_TIMEOUT', context: { platform: LABEL, songId, url: sunoSongUrl(songId) },+ });+ }+ await sleep(intervalMs);+ }+}++/**+ * Make one Suno song and import it into the music library.+ *+ * `fields` is the output of `sunoSongFields`. Resolves to+ * `{ songId, songIds, filename, sizeBytes }` — the first take is imported; its+ * sibling take ids are returned so the run can record them.+ */+export async function generateSunoSong(fields, deps = {}) {+ const connect = deps.connect || connectPortosBrowser;+ const importAudio = deps.importAudio || (async (bytes) => {+ const { importUploadedTrack } = await import('../pipeline/musicLibrary.js');+ const dir = await mkdtemp(join(tmpdir(), 'portos-suno-'));+ const tmp = join(dir, 'song.mp3');+ await writeFile(tmp, bytes);+ return importUploadedTrack(tmp, 'song.mp3').finally(() => rm(dir, { recursive: true, force: true }).catch(() => {}));+ });+ // A retry after a failed download reuses the songs already submitted rather+ // than spending more Suno credits on a second generation.+ const songIds = deps.songIds?.length ? deps.songIds : await serialize(async () => {+ const { browser, context } = await connect();+ const page = await context.newPage();+ try {+ const submitted = await submitSunoSong(page, fields, deps);+ await deps.onSubmitted?.(submitted);+ return submitted;+ } finally {+ await page.close().catch(() => {});+ await browser.close().catch(() => {}); // disconnects; the PortOS Browser keeps running+ }+ });+ const [songId] = songIds;+ const bytes = await downloadSunoAudio(songId, deps);+ const { filename, sizeBytes } = await importAudio(bytes);+ console.log(`🎵 Suno song ${songId.slice(0, 8)} imported as ${filename} (${Math.round(sizeBytes / 1024)} KB)`);+ return { songId, songIds, filename, sizeBytes };+}++export const __testing = { submitSunoSong, downloadSunoAudio };diff --git a/server/services/musicVideo/autonomousSuno.test.js b/server/services/musicVideo/autonomousSuno.test.jsnew file mode 100644index 0000000000..ff4061b595--- /dev/null+++ b/server/services/musicVideo/autonomousSuno.test.js@@ -0,0 +1,116 @@+/**+ * The Suno step with a fake browser page and a fake CDN. Pins what only this+ * layer knows: a signed-out page is a login-required park (not a generic+ * failure), songs already in the workspace are never mistaken for ours, audio+ * is accepted only once it stops growing, and a retry reuses submitted songs.+ */++import { describe, it, expect, vi } from 'vitest';+import { __testing, generateSunoSong } from './autonomousSuno.js';++const { downloadSunoAudio, submitSunoSong } = __testing;++const OLD = '11111111-1111-1111-1111-111111111111';+const NEW_A = '22222222-2222-2222-2222-222222222222';+const NEW_B = '33333333-3333-3333-3333-333333333333';+const noSleep = async () => {};++/** A just-enough Playwright page: tracks fills/clicks and exposes song links that appear after Create. */+function fakePage({ url = 'https://suno.com/create', hasForm = true, afterCreate = [NEW_A, NEW_B] } = {}) {+ const fills = {};+ let created = false;+ const locator = (selector) => {+ const handle = {+ count: async () => (selector === 'textarea' ? (hasForm ? 1 : 0) : 1),+ fill: async (v) => { fills[selector] = v; },+ click: async () => {},+ };+ return { ...handle, first: () => handle };+ };+ const button = () => ({+ count: async () => 1,+ first: () => ({ click: async () => {} }),+ last: () => ({ click: async () => { created = true; } }),+ });+ return {+ fills,+ goto: vi.fn(async () => {}),+ url: () => url,+ locator,+ getByRole: button,+ evaluate: async () => [`/song/${OLD}`, ...(created ? afterCreate.map((id) => `/song/${id}`) : [])],+ close: async () => {},+ };+}++describe('submitSunoSong', () => {+ const fields = { title: 'Neon Rain', style: 'synthwave', lyrics: '[verse]\nrain', instrumental: false };++ it('fills the custom form and returns only the songs that appeared after Create', async () => {+ const page = fakePage();+ const ids = await submitSunoSong(page, fields, { sleep: noSleep });+ expect(ids).toEqual([NEW_A, NEW_B]);+ expect(page.fills['textarea[placeholder*="lyrics" i]']).toBe('[verse]\nrain');+ expect(page.fills['textarea[placeholder*="style" i]']).toBe('synthwave');+ expect(page.fills['input[placeholder*="title" i]']).toBe('Neon Rain');+ });++ it('leaves the lyrics empty for an instrumental song', async () => {+ const page = fakePage();+ await submitSunoSong(page, { ...fields, instrumental: true, lyrics: '' }, { sleep: noSleep });+ expect(page.fills['textarea[placeholder*="lyrics" i]']).toBeUndefined();+ });++ it('reports a signed-out page as login-required so the run parks for the operator', async () => {+ await expect(submitSunoSong(fakePage({ hasForm: false }), fields, { sleep: noSleep })).rejects.toMatchObject({ code: 'PUBLISH_LOGIN_REQUIRED' });+ await expect(submitSunoSong(fakePage({ url: 'https://accounts.suno.com/sign-in' }), fields, { sleep: noSleep })).rejects.toMatchObject({ code: 'PUBLISH_LOGIN_REQUIRED' });+ });+});++describe('downloadSunoAudio', () => {+ const body = (size) => ({ ok: true, arrayBuffer: async () => new ArrayBuffer(size) });++ it('waits out a partial file: returns only once the size is stable and real', async () => {+ const fetchImpl = vi.fn()+ .mockResolvedValueOnce({ ok: false })+ .mockResolvedValueOnce(body(1000)) // too small — a stub+ .mockResolvedValueOnce(body(300 * 1024)) // growing+ .mockResolvedValueOnce(body(400 * 1024))+ .mockResolvedValueOnce(body(400 * 1024)); // stable+ const bytes = await downloadSunoAudio(NEW_A, { fetchImpl, sleep: noSleep, now: () => 0 });+ expect(bytes.length).toBe(400 * 1024);+ expect(fetchImpl).toHaveBeenCalledTimes(5);+ expect(fetchImpl).toHaveBeenCalledWith(`https://cdn1.suno.ai/${NEW_A}.mp3`);+ });++ it('gives up with a clear timeout naming the song when it never finishes', async () => {+ let t = 0;+ await expect(downloadSunoAudio(NEW_A, {+ fetchImpl: async () => ({ ok: false }), sleep: noSleep, intervalMs: 10, timeoutMs: 25, now: () => (t += 10),+ })).rejects.toMatchObject({ code: 'SUNO_AUDIO_TIMEOUT', context: expect.objectContaining({ songId: NEW_A }) });+ });+});++describe('generateSunoSong', () => {+ const fields = { title: 't', style: 's', lyrics: 'l', instrumental: false };+ const audio = { ok: true, arrayBuffer: async () => new ArrayBuffer(200 * 1024) };+ const connect = async () => ({ browser: { close: async () => {} }, context: { newPage: async () => fakePage() } });++ it('submits once, downloads the first take and imports it', async () => {+ const importAudio = vi.fn(async () => ({ filename: 'music-x.mp3', sizeBytes: 204800 }));+ const onSubmitted = vi.fn();+ const out = await generateSunoSong(fields, { connect, importAudio, onSubmitted, fetchImpl: async () => audio, sleep: noSleep, intervalMs: 0 });+ expect(out).toMatchObject({ songId: NEW_A, songIds: [NEW_A, NEW_B], filename: 'music-x.mp3' });+ expect(onSubmitted).toHaveBeenCalledWith([NEW_A, NEW_B]);+ });++ it('with songs already submitted, never opens the browser — a retry spends no new credits', async () => {+ const connectSpy = vi.fn(connect);+ const out = await generateSunoSong(fields, {+ connect: connectSpy, importAudio: async () => ({ filename: 'm.mp3', sizeBytes: 1 }), songIds: [NEW_B],+ fetchImpl: async () => audio, sleep: noSleep, intervalMs: 0,+ });+ expect(connectSpy).not.toHaveBeenCalled();+ expect(out.songId).toBe(NEW_B);+ });+});diff --git a/server/services/musicVideo/events.js b/server/services/musicVideo/events.jsindex 75dbed5c89..3c342c018f 100644--- a/server/services/musicVideo/events.js+++ b/server/services/musicVideo/events.js@@ -32,6 +32,11 @@ import { EventEmitter } from 'events';// production run advanced (steps, route choices, spend, halts); socket.js// bridges it to `music-video:production`.//+// A fully-autonomous run (autonomousService.js) adds:+// 'autonomous' → { projectId, runId, run } — the run changed stage or status+// (a stage settled, a checkpoint is waiting, it needs the director, it+// finished); bridged to `music-video:autonomous`.+//// The Cast & Sets check-in adds:// 'cast-and-sets' → { projectId, stage, project } — the check-in stage// advanced (direction, an image landed, the sheet is ready, approved);diff --git a/server/services/musicVideo/projectAudio.js b/server/services/musicVideo/projectAudio.jsnew file mode 100644index 0000000000..450033fb91--- /dev/null+++ b/server/services/musicVideo/projectAudio.js@@ -0,0 +1,50 @@+/**+ * A Music Video project's source audio: resolve it to an absolute path under+ * data/music/ and run the offline beat/tempo/section analysis on it. Shared by+ * the `/analyze` routes and the autonomous run so both read the same file the+ * same way.+ */+import { ServerError } from '../../lib/errorHandler.js';+import { PATHS } from '../../lib/fileUtils.js';+import { safeUnder } from '../../lib/ffmpeg.js';+import { getTrack } from '../tracks/index.js';+import { getProject, setProjectAnalysis } from './projects.js';+import { analyzeAudioFile } from './audioAnalysis.js';+import { relabelAnalysisSections } from './lyricMarkers.js';++/**+ * Resolve a project's source audio to an absolute path under data/music/. The+ * filename comes from the linked track or the uploaded-audio field; both are+ * validated as safe basenames so a tampered record can't escape the directory.+ */+export async function resolveProjectAudioPath(project) {+ let filename = null;+ if (project.trackId) {+ const track = await getTrack(project.trackId);+ if (!track) throw new ServerError('Linked track not found', { status: 404, code: 'NOT_FOUND' });+ filename = track.audioFilename;+ } else if (project.uploadedAudioFilename) {+ filename = project.uploadedAudioFilename;+ }+ if (!filename) {+ throw new ServerError('Project has no audio to analyze — set a track or upload audio first', { status: 400, code: 'NO_AUDIO' });+ }+ const safe = safeUnder(PATHS.music, filename);+ if (!safe) throw new ServerError('Invalid audio filename', { status: 400, code: 'VALIDATION_ERROR' });+ return safe;+}++/**+ * Analyze the project's audio and cache the result on it. Timed lyrics with+ * sheet headers name the fresh sections too (a no-op until the lines are+ * aligned). Resolves to the updated project.+ */+export async function analyzeProjectSong(projectId) {+ const project = await getProject(projectId);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const analysis = await analyzeAudioFile(await resolveProjectAudioPath(project));+ if (!analysis) {+ throw new ServerError('Could not analyze audio (decode failed or ffmpeg unavailable)', { status: 422, code: 'ANALYZE_FAILED' });+ }+ return setProjectAnalysis(project.id, relabelAnalysisSections(analysis, project.lyricCues, project.lyricMarkers));+}diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.jsindex 0b27f00bf9..18e553c4a1 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -252,6 +252,8 @@ export function cloneProjectRecord(source, {...(Array.isArray(source.autoReviews) ? { autoReviews: [] } : {}),// #9066: a production run executes against the SOURCE's scenes and jobs....(Array.isArray(source.productionRuns) ? { productionRuns: [] } : {}),+ // An autonomous run executes against the SOURCE's audio, board and production.+ ...(source.autonomousRun ? { autonomousRun: null } : {}),// Development artifacts ride along as-is: every version is an immutable// file, so the clone points at the same bytes (devArtifacts.js). The Cast// & Sets check-in keeps its direction and images, but its dispatch pin and@@ -674,6 +676,7 @@ export function mergeProjectRecord(local, remoteRaw) {// their files and jobs exist only on this install.if (Object.hasOwn(local, 'devArtifacts')) remote.devArtifacts = local.devArtifacts;if (Object.hasOwn(local, 'castAndSets')) remote.castAndSets = local.castAndSets;+ if (Object.hasOwn(local, 'autonomousRun')) remote.autonomousRun = local.autonomousRun;// The composition document's files live only on this install as well// (compositionDocument.js), so its pointer survives a newer remote body.if (local.composition?.document || local.composition?.documentDraft) {diff --git a/server/services/musicVideo/publish/browser.js b/server/services/musicVideo/publish/browser.jsindex c76e5fb2dd..5e9f11baa2 100644--- a/server/services/musicVideo/publish/browser.js+++ b/server/services/musicVideo/publish/browser.js@@ -16,6 +16,19 @@ import { ServerError } from '../../../lib/errorHandler.js';export const PUBLISH_STEP_TIMEOUT_MS = 60_000;+let browserTail = Promise.resolve();++/**+ * Run `fn` after every earlier PortOS Browser operation settles. Typing goes to+ * whichever tab has focus, so every driver of the shared browser — a publish+ * draft or an autonomous Suno song — queues here, not on a private tail.+ */+export function serializeBrowserOperation(fn) {+ const run = browserTail.then(fn, fn);+ browserTail = run.catch(() => {});+ return run;+}+/** Connect to the running PortOS Browser (launching it when it is stopped). */export async function connectPortosBrowser() {const { getHealthStatus, launchBrowser } = await import('../../browserService.js');diff --git a/server/services/musicVideo/publish/index.js b/server/services/musicVideo/publish/index.jsindex b10cb79576..8d2d0499d8 100644--- a/server/services/musicVideo/publish/index.js+++ b/server/services/musicVideo/publish/index.js@@ -22,7 +22,7 @@ import { PATHS, ensureDir } from '../../../lib/fileUtils.js';import { safeUnder } from '../../../lib/ffmpeg.js';import { getProject, mutateProjectRecord } from '../projects.js';import { buildPublishPayload } from './payloads.js';-import { connectPortosBrowser } from './browser.js';+import { connectPortosBrowser, serializeBrowserOperation as serialize } from './browser.js';import { assertAccount, assertPlatformEnabled, getPublishPlatforms, normalizePost } from './platforms.js';import { youtubeAdapter, shortsAdapter } from './youtube.js';import { tiktokAdapter } from './tiktok.js';@@ -38,14 +38,6 @@ export const PUBLISH_ADAPTERS = Object.freeze({});const DRAFT_TTL_MS = 30 * 60 * 1000;const drafts = new Map();-let browserTail = Promise.resolve();--/** Run `fn` after every earlier browser operation settles (typing needs the focused tab). */-function serialize(fn) {- const run = browserTail.then(fn, fn);- browserTail = run.catch(() => {});- return run;-}const draftError = (message) => new ServerError(message, { status: 409, code: 'PUBLISH_DRAFT_MISSING' });diff --git a/server/services/scheduledHandlers/index.js b/server/services/scheduledHandlers/index.jsindex 5ef530da83..f577afbe97 100644--- a/server/services/scheduledHandlers/index.js+++ b/server/services/scheduledHandlers/index.js@@ -52,6 +52,7 @@*/export const SCHEDULED_HANDLER_MODULES = {'development-watchdog': () => import('./developmentWatchdog.js'),+ 'music-video-autopilot': () => import('./musicVideoAutopilot.js'),'universe-bible-describe': () => import('./universeBibleDescribe.js'),'universe-bible-images': () => import('./universeBibleImages.js'),};diff --git a/server/services/scheduledHandlers/musicVideoAutopilot.js b/server/services/scheduledHandlers/musicVideoAutopilot.jsnew file mode 100644index 0000000000..dab33a7e3f--- /dev/null+++ b/server/services/scheduledHandlers/musicVideoAutopilot.js@@ -0,0 +1,70 @@+/**+ * Scheduled handler `music-video-autopilot` — turn one Brain idea into a fully+ * autonomous music video per run.+ *+ * PROGRAMMATIC: no agent is spawned. Each run picks the OLDEST active Brain idea+ * no earlier autonomous run used (optionally limited to ideas carrying one of+ * `ideaTags`), then starts the same autonomous run the Music Video page's+ * "Autonomous" entry point starts: creative brief → lyrics → mood board → Suno+ * song → analysis → production. The task's `taskMetadata.musicVideoAutopilot`+ * carries the run settings (tools, per-tool models, budget, limits, checkpoints,+ * LLM) — see `normalizeAutopilotParams` in `lib/musicVideoAutonomous.js`.+ *+ * It declines (never queues a second one) while a previous autonomous run is+ * still live, so a slow Suno login or a long production cannot pile up videos.+ * An idea only counts as used once its run is live or finished; a failed or+ * canceled run leaves the idea available for the next fire.+ *+ * `countPending` is side-effect free and makes no provider call.+ */++import { getIdeas } from '../brainStorage.js';+import { listProjects } from '../musicVideo/projects.js';+import { AUTONOMOUS_LIVE_STATUSES, ideaToPrompt, normalizeAutopilotParams, pickBrainIdea } from '../../lib/musicVideoAutonomous.js';++const USED_STATUSES = new Set([...AUTONOMOUS_LIVE_STATUSES, 'completed']);++/** Brain ideas an earlier run already turned into a video, and whether a run is still live. */+function priorRuns(projects) {+ const usedIdeaIds = [];+ let live = null;+ for (const project of projects || []) {+ const run = project?.autonomousRun;+ if (!run || project.deleted) continue;+ if (run.brief?.origin?.ideaId && USED_STATUSES.has(run.status)) usedIdeaIds.push(run.brief.origin.ideaId);+ if (run.brief?.origin?.kind === 'schedule' && AUTONOMOUS_LIVE_STATUSES.includes(run.status)) live = project;+ }+ return { usedIdeaIds, live };+}++async function inspect(params) {+ const settings = normalizeAutopilotParams(params?.musicVideoAutopilot) || normalizeAutopilotParams({});+ const [ideas, projects] = await Promise.all([getIdeas(), listProjects()]);+ const { usedIdeaIds, live } = priorRuns(projects);+ const idea = pickBrainIdea(ideas, { usedIdeaIds, tags: settings.ideaTags });+ return { settings, idea, live };+}++export async function countPending({ params } = {}) {+ const { idea, live } = await inspect(params);+ if (live) return { count: 0, detail: `"${live.name}" is still in progress` };+ return { count: idea ? 1 : 0, detail: idea ? `Next idea: ${idea.title}` : 'No unused active Brain ideas' };+}++export async function run({ params } = {}) {+ const { settings, idea, live } = await inspect(params);+ if (live) return { dispatched: false, reason: `a previous autonomous music video ("${live.name}") is still in progress` };+ if (!idea) return { dispatched: false, reason: 'no unused active Brain ideas to turn into a music video' };+ const { ideaTags: _ideaTags, ...runSettings } = settings;+ const { startAutonomousVideo } = await import('../musicVideo/autonomousService.js');+ const { project } = await startAutonomousVideo({+ ...runSettings,+ // The LLM pin is stored as `llm` on the normalized settings; the start+ // request takes it as providerId/model.+ providerId: settings.llm?.providerId,+ model: settings.llm?.model || undefined,+ prompt: ideaToPrompt(idea),+ origin: { kind: 'schedule', ideaId: idea.id, ideaTitle: idea.title },+ });+ return { dispatched: true, summary: `Started music video "${project.name}" from Brain idea "${idea.title}"` };+}diff --git a/server/services/scheduledHandlers/musicVideoAutopilot.test.js b/server/services/scheduledHandlers/musicVideoAutopilot.test.jsnew file mode 100644index 0000000000..17f6faa5f5--- /dev/null+++ b/server/services/scheduledHandlers/musicVideoAutopilot.test.js@@ -0,0 +1,55 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++const ideas = [];+const projects = [];+const startAutonomousVideo = vi.fn();+vi.mock('../brainStorage.js', () => ({ getIdeas: async () => ideas }));+vi.mock('../musicVideo/projects.js', () => ({ listProjects: async () => projects }));+vi.mock('../musicVideo/autonomousService.js', () => ({ startAutonomousVideo }));++const { countPending, run } = await import('./musicVideoAutopilot.js');++const idea = (id, createdAt, extra = {}) => ({ id, title: `Idea ${id}`, oneLiner: `about ${id}`, status: 'active', createdAt, tags: [], ...extra });+const project = (name, status, ideaId, kind = 'schedule') => ({ name, autonomousRun: { status, brief: { origin: { kind, ideaId } } } });++beforeEach(() => {+ ideas.length = 0;+ projects.length = 0;+ startAutonomousVideo.mockReset();+ startAutonomousVideo.mockImplementation(async () => ({ project: { name: 'Made' } }));+});++describe('music-video-autopilot scheduled handler', () => {+ it('starts one run from the oldest unused idea, carrying the task settings and the idea as origin', async () => {+ ideas.push(idea('new', '2026-02-01T00:00:00.000Z'), idea('old', '2026-01-01T00:00:00.000Z'));+ const out = await run({ params: { musicVideoAutopilot: { tools: ['code:render'], checkpoints: ['lyrics'], providerId: 'prov', model: 'm' } } });+ expect(out).toMatchObject({ dispatched: true });+ expect(startAutonomousVideo).toHaveBeenCalledTimes(1);+ expect(startAutonomousVideo.mock.calls[0][0]).toMatchObject({+ tools: ['code:render'], checkpoints: ['lyrics'], providerId: 'prov', model: 'm',+ prompt: expect.stringContaining('Idea old'), origin: { kind: 'schedule', ideaId: 'old', ideaTitle: 'Idea old' },+ });+ });++ it('skips ideas an earlier run is using or finished, but not ones whose run failed or was canceled', async () => {+ ideas.push(idea('a', '2026-01-01T00:00:00.000Z'), idea('b', '2026-01-02T00:00:00.000Z'), idea('c', '2026-01-03T00:00:00.000Z'));+ projects.push(project('A', 'completed', 'a'), project('B', 'failed', 'b'));+ await run({ params: {} });+ expect(startAutonomousVideo.mock.calls[0][0].origin.ideaId).toBe('b');+ });++ it('declines while a scheduled run is still live, so videos never pile up', async () => {+ ideas.push(idea('a', '2026-01-01T00:00:00.000Z'));+ projects.push(project('In flight', 'needs-human', 'zzz'));+ expect(await run({ params: {} })).toMatchObject({ dispatched: false, reason: expect.stringContaining('In flight') });+ expect(await countPending({ params: {} })).toMatchObject({ count: 0 });+ expect(startAutonomousVideo).not.toHaveBeenCalled();+ });++ it('declines with a reason when no idea is eligible, honoring the tag filter', async () => {+ ideas.push(idea('a', '2026-01-01T00:00:00.000Z', { tags: ['poem'] }));+ expect(await run({ params: { musicVideoAutopilot: { ideaTags: ['song'] } } })).toMatchObject({ dispatched: false });+ expect(await countPending({ params: { musicVideoAutopilot: { ideaTags: ['poem'] } } })).toMatchObject({ count: 1 });+ expect(startAutonomousVideo).not.toHaveBeenCalled();+ });+});diff --git a/server/services/socket.js b/server/services/socket.jsindex 89ae40566b..e9652423c6 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -313,6 +313,8 @@ const SIMPLE_BRIDGES = [{ emitter: musicVideoEvents, event: 'scene-video', channel: 'music-video:scene-video' },{ emitter: musicVideoEvents, event: 'auto-review', channel: 'music-video:auto-review' },{ emitter: musicVideoEvents, event: 'production', channel: 'music-video:production' },+ // A fully-autonomous run (prompt → lyrics → Suno song → video) advancing.+ { emitter: musicVideoEvents, event: 'autonomous', channel: 'music-video:autonomous' },// The Cast & Sets check-in advancing, and a development artifact changing.{ emitter: musicVideoEvents, event: 'cast-and-sets', channel: 'music-video:cast-and-sets' },{ emitter: musicVideoEvents, event: 'dev-artifact', channel: 'music-video:dev-artifact' },diff --git a/server/services/taskScheduleRegistry.js b/server/services/taskScheduleRegistry.jsindex 683dccc3a6..9cfb0016bb 100644--- a/server/services/taskScheduleRegistry.js+++ b/server/services/taskScheduleRegistry.js@@ -13,6 +13,7 @@ import {PUBLIC_REVIEW_GATE_EXECUTION_PROFILE,} from '../lib/agentExecutionProfiles.js';import { INTERVAL_TYPES } from './taskScheduleConstants.js';+import { normalizeAutopilotParams } from '../lib/musicVideoAutonomous.js';// Programmatic handler types + target-scope vocabulary live in// `lib/taskTargetScope.js` (see that file for why); re-exported here because@@ -430,6 +431,14 @@ const TASK_INTERVAL_DEFAULTS = {// ON_DEMAND with NO interval and NO cron: enabled so the user can press Run// Now, never clock-due, so a fresh install spends nothing until they do.'development-watchdog': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, taskMetadata: null },+ // music-video-autopilot turns one unused Brain idea into a fully autonomous+ // music video per run (lyrics → Suno song → mood board → production). Like+ // the bible handlers it is on-demand until the operator sets a cadence on the+ // card. Its params bag is `musicVideoAutopilot` (tools, per-tool models,+ // budget, checkpoints, idea tags); the shipped default is the free/local tool+ // set so nothing metered is spent until the operator opts in. It has no Quota+ // Burn form: image/video spend is bounded by its own budget and limits.+ 'music-video-autopilot': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, taskMetadata: { musicVideoAutopilot: normalizeAutopilotParams({}) } },'universe-bible-describe': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, taskMetadata: { universeId: 'all', scope: 'all', depth: 'full', maxEntries: 10 } },'universe-bible-images': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, taskMetadata: { universeId: 'all', scope: 'all', maxEntries: 10, requireDescribed: false } }};@@ -608,6 +617,7 @@ export const TASK_TYPE_DESCRIPTIONS = {'user-action-review': 'Review the operator-action log for repeated manual work and propose automations — file issues (default) or queue CoS tasks','layered-intelligence': "Use app goals + performance metrics to file at most one deduplicated improvement issue; inspect read-only context and file a visibility gap when evidence is insufficient — no code",'development-watchdog': 'Inspect maintainer repository ownership and queue eligible work without an inference call',+ 'music-video-autopilot': 'Turn the next unused Brain idea into a fully autonomous music video — lyrics, Suno song, mood board and video. No agent','universe-bible-describe': 'Fill in blank universe bible sheets — one expand prompt per entry, emptiest first. No agent','universe-bible-images': 'Render images for universe bible entries that have none yet. No agent — PortOS enqueues the renders itself'};@@ -643,6 +653,10 @@ export const TASK_TYPE_PROMPT_INFO = Object.freeze({// `programmatic` is NOT `runtime-generated`: there is no prompt at all for the// user to read or a hook to render. PortOS performs the work itself, so the// UI shows the settings that bound it instead of a prompt editor.+ 'music-video-autopilot': Object.freeze({+ mode: 'programmatic',+ description: 'PortOS picks the oldest unused active Brain idea and runs the autonomous music-video pipeline itself — no agent and no prompt template. Tools, per-tool models, budget, checkpoints and idea tags are the settings that bound it.'+ }),'universe-bible-describe': Object.freeze({mode: 'programmatic',description: 'PortOS sends one bible-expand prompt per entry itself — no agent and no prompt template. Scope, depth, and the per-run entry cap are the settings that bound it.'diff --git a/server/services/taskScheduleRegistry.programmatic.test.js b/server/services/taskScheduleRegistry.programmatic.test.jsindex 403d62cd29..7a7a527bdc 100644--- a/server/services/taskScheduleRegistry.programmatic.test.js+++ b/server/services/taskScheduleRegistry.programmatic.test.js@@ -76,6 +76,14 @@ describe('programmatic scheduled handlers — shipped params', () => {expect(DEFAULT_TASK_INTERVALS[taskType].taskMetadata).toBeNull();continue;}+ // The music-video autopilot is configured on its own Schedule card (its+ // paid image/video spend is bounded by its budget and limits), so it has+ // no Quota Burn form to mirror.+ if (taskType === 'music-video-autopilot') {+ expect(params).toEqual({});+ expect(Object.keys(DEFAULT_TASK_INTERVALS[taskType].taskMetadata)).toEqual(['musicVideoAutopilot']);+ continue;+ }expect(Object.keys(params).length, taskType).toBeGreaterThan(0);const expected = Object.fromEntries(Object.entries(params)diff --git a/server/services/trackAudioAttach.js b/server/services/trackAudioAttach.jsnew file mode 100644index 0000000000..41d0d64e1b--- /dev/null+++ b/server/services/trackAudioAttach.js@@ -0,0 +1,42 @@+/**+ * Attach a library audio file to a track as its active render. Shared by the+ * per-track upload/attach routes and the autonomous Music Video run, so every+ * path that lands audio on a track records the same render card.+ */+import { ServerError } from '../lib/errorHandler.js';+import * as tracks from './tracks/index.js';++/**+ * Make `filename` the active audio AND record it in the render history so an+ * uploaded/attached take shows up as a card alongside generated ones. An+ * uploaded render has no engine/model, so the active gen-metadata is cleared+ * (keeps the read-only badges honest); `take` carries what IS known about it —+ * provenance, the prompt/lyrics it was made from, its probed duration.+ * Re-attaching a file already in the history just re-selects it (no duplicate+ * card).+ *+ * Re-reads the track by id (the caller validated existence earlier) so the+ * append builds on the FRESHEST persisted history: a render added to this track+ * between the caller's initial load and now — a long generation finishing, or a+ * parallel upload, both of which can span the file-import window — isn't dropped+ * by writing back a stale renders array. (The sub-millisecond getTrack→+ * updateTrack window is a single-user request race we don't lock against per the+ * trust model.)+ */+export async function attachAudioAsRender(trackId, filename, take = {}) {+ const track = await tracks.getTrack(trackId);+ if (!track) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });+ const existing = (track.renders || []).find((r) => r.audioFilename === filename);+ if (existing) {+ const patch = tracks.selectRenderPatch(track, existing.id) || { audioFilename: filename };+ return tracks.updateTrack(trackId, patch);+ }+ const { renders } = tracks.buildRenderAppend(track, { ...take, audioFilename: filename });+ return tracks.updateTrack(trackId, {+ audioFilename: filename,+ engine: '',+ modelId: '',+ durationSec: take.durationSec ?? null,+ renders,+ });+}