Skip to content

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

feat(music-video): Suno form options and song retake for autonomous runs

Claude0553872f36f3
diff --git a/client/src/components/musicVideo/AutonomousRunPanel.jsx b/client/src/components/musicVideo/AutonomousRunPanel.jsx
index b5db712ea7..a9d68656cc 100644
--- a/client/src/components/musicVideo/AutonomousRunPanel.jsx
+++ b/client/src/components/musicVideo/AutonomousRunPanel.jsx
@@ -1,6 +1,6 @@
import { useState } from 'react';
import { Link } from 'react-router';
-import { AlertTriangle, CheckCircle2, Circle, CircleDot, ExternalLink, Loader2, Pause, Play, Wand2, X, XCircle } from 'lucide-react';
+import { AlertTriangle, CheckCircle2, Circle, CircleDot, ExternalLink, Loader2, Pause, Play, RotateCcw, Wand2, X, XCircle } from 'lucide-react';
import {
AUTONOMOUS_CHECKPOINT_LABELS, AUTONOMOUS_SONG_STEP_LABELS, AUTONOMOUS_STATUS_LABELS, AUTONOMOUS_VIEWABLE_STAGES,
autonomousStageOutput, autonomousStageRows, isAutonomousLive,
@@ -45,7 +45,8 @@ function StageOutput({ run, row, editableBelow }) {
/**
* 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,
+ * (optionally with edited lyrics or Suno style), retake the song at the song
+ * checkpoint, retry the stage that stopped,
* pause, or cancel. A finished stage's output (brief, lyrics, style, song) opens
* read-only from its checklist row; the open row is the caller's URL state
* (`selectedStage` / `onSelectStage`). Progress arrives over `music-video:autonomous` through
@@ -142,9 +143,17 @@ export default function AutonomousRunPanel({ project, auto, selectedStage = null
/>
</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 className="flex flex-wrap gap-2">
+ <button type="button" disabled={auto.busy} onClick={() => auto.resume(changed ? { [editable.key]: draft } : {})} className={`${buttonClass} bg-port-accent text-white border-port-accent`}>
+ <Play size={14} aria-hidden="true" /> {changed ? 'Save edit & approve' : 'Approve & continue'}
+ </button>
+ {awaiting === 'song' && (
+ // Discards this song and makes a new one (a new Suno generation spends credits), then pauses here again.
+ <button type="button" disabled={auto.busy} onClick={() => auto.resume({ retakeSong: true })} className={buttonClass}>
+ <RotateCcw size={14} aria-hidden="true" /> Retake song
+ </button>
+ )}
+ </div>
</div>
)}
diff --git a/client/src/components/musicVideo/AutonomousRunPanel.test.jsx b/client/src/components/musicVideo/AutonomousRunPanel.test.jsx
index 54c79393c7..cb7111165e 100644
--- a/client/src/components/musicVideo/AutonomousRunPanel.test.jsx
+++ b/client/src/components/musicVideo/AutonomousRunPanel.test.jsx
@@ -106,6 +106,17 @@ describe('AutonomousRunPanel', () => {
expect(screen.getByLabelText(/suno style \(edit before continuing\)/i).value).toBe('synthwave');
});
+ it('offers a song retake only at the song checkpoint', async () => {
+ api.resumeAutonomousMusicVideo.mockResolvedValue({ project: { id: 'mv-1', autonomousRun: baseRun() }, run: baseRun() });
+ const { unmount } = render(<Harness initial={baseRun({ status: 'awaiting-approval', awaiting: 'lyrics' })} />);
+ expect(screen.queryByRole('button', { name: /retake song/i })).toBeNull();
+ unmount();
+
+ render(<Harness initial={baseRun({ status: 'awaiting-approval', awaiting: 'song', stage: 'analyze' })} />);
+ fireEvent.click(screen.getByRole('button', { name: /retake song/i }));
+ await waitFor(() => expect(api.resumeAutonomousMusicVideo).toHaveBeenCalledWith('mv-1', { retakeSong: true }, { silent: true }));
+ });
+
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' })} />);
@@ -234,6 +245,22 @@ describe('AutonomousStartDrawer', () => {
});
});
+ it('sends the Suno form options only when set, and blocks an unrecognizable model version', async () => {
+ api.startAutonomousMusicVideo.mockResolvedValue({ project: { id: 'mv-new' }, run: baseRun() });
+ render(<AutonomousStartDrawer open onClose={() => {}} onStarted={() => {}} />);
+ fireEvent.change(screen.getByLabelText('Prompt'), { target: { value: 'p' } });
+ fireEvent.change(screen.getByLabelText('Code authoring provider'), { target: { value: 'fixture-api' } });
+ const submit = screen.getByRole('button', { name: /start autonomous video/i });
+ fireEvent.change(screen.getByLabelText('Suno model'), { target: { value: 'latest' } });
+ expect(submit.disabled).toBe(true);
+ fireEvent.change(screen.getByLabelText('Suno model'), { target: { value: 'v6' } });
+ fireEvent.change(screen.getByLabelText('Exclude styles'), { target: { value: ' metal ' } });
+ fireEvent.change(screen.getByLabelText('Vocal gender'), { target: { value: 'female' } });
+ fireEvent.click(submit);
+ await waitFor(() => expect(api.startAutonomousMusicVideo).toHaveBeenCalledTimes(1));
+ expect(api.startAutonomousMusicVideo.mock.calls[0][0].suno).toEqual({ excludeStyles: 'metal', vocalGender: 'female', model: 'v6' });
+ });
+
it('offers the local song source, and the Suno-only fallback opt-in only while Suno is the source', async () => {
api.startAutonomousMusicVideo.mockResolvedValue({ project: { id: 'mv-new' }, run: baseRun() });
render(<AutonomousStartDrawer open onClose={() => {}} onStarted={() => {}} />);
diff --git a/client/src/components/musicVideo/AutonomousStartDrawer.jsx b/client/src/components/musicVideo/AutonomousStartDrawer.jsx
index 7392db495f..5307e87e84 100644
--- a/client/src/components/musicVideo/AutonomousStartDrawer.jsx
+++ b/client/src/components/musicVideo/AutonomousStartDrawer.jsx
@@ -12,7 +12,8 @@ import toast from '../ui/Toast';
import useProviderModels from '../../hooks/useProviderModels.js';
import { startAutonomousMusicVideo } from '../../services/apiMusicVideo.js';
import {
- AUTONOMOUS_CHECKPOINT_IDS, AUTONOMOUS_CHECKPOINT_LABELS, autonomousRequestFromDraft, emptyAutonomousDraft,
+ AUTONOMOUS_CHECKPOINT_IDS, AUTONOMOUS_CHECKPOINT_LABELS, SUNO_LIMITS, SUNO_VOCAL_GENDERS, autonomousRequestFromDraft, emptyAutonomousDraft,
+ isSunoModelValid,
} from '../../lib/musicVideoAutonomous.js';
const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';
@@ -34,7 +35,9 @@ export default function AutonomousStartDrawer({ open, onClose, onStarted }) {
const toggleCheckpoint = (id) => patch({
checkpoints: AUTONOMOUS_CHECKPOINT_IDS.filter((c) => (c === id ? !draft.checkpoints.includes(c) : draft.checkpoints.includes(c))),
});
- const valid = draft.prompt.trim().length > 0 && authoringReady;
+ const patchSuno = (next) => setDraft((d) => ({ ...d, suno: { ...d.suno, ...next } }));
+ const sunoModelValid = draft.songSource !== 'suno' || isSunoModelValid(draft.suno.model);
+ const valid = draft.prompt.trim().length > 0 && authoringReady && sunoModelValid;
const handleSubmit = (e) => {
e.preventDefault();
@@ -82,6 +85,29 @@ export default function AutonomousStartDrawer({ open, onClose, onStarted }) {
<SongSourcePicker idPrefix="mv-auto" songSource={draft.songSource} localFallback={draft.localFallback} onChange={patch} />
+ {draft.songSource === 'suno' && (
+ <div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,10rem),16rem))] gap-3">
+ <div>
+ <label htmlFor="mv-auto-suno-exclude" className="block text-xs text-port-text-muted mb-1">Exclude styles</label>
+ <input id="mv-auto-suno-exclude" type="text" maxLength={SUNO_LIMITS.excludeStyles} value={draft.suno.excludeStyles} onChange={(e) => patchSuno({ excludeStyles: e.target.value })} placeholder="metal, screamo" className={inputClass} />
+ </div>
+ {!draft.instrumental && (
+ <div>
+ <label htmlFor="mv-auto-suno-vocal" className="block text-xs text-port-text-muted mb-1">Vocal gender</label>
+ <select id="mv-auto-suno-vocal" value={draft.suno.vocalGender} onChange={(e) => patchSuno({ vocalGender: e.target.value })} className={inputClass}>
+ <option value="">Suno decides</option>
+ {SUNO_VOCAL_GENDERS.map((gender) => <option key={gender} value={gender}>{gender === 'male' ? 'Male' : 'Female'}</option>)}
+ </select>
+ </div>
+ )}
+ <div>
+ <label htmlFor="mv-auto-suno-model" className="block text-xs text-port-text-muted mb-1">Suno model</label>
+ <input id="mv-auto-suno-model" type="text" maxLength={10} value={draft.suno.model} onChange={(e) => patchSuno({ model: e.target.value })} placeholder="Current (e.g. v6)" aria-invalid={!sunoModelValid} className={inputClass} />
+ {!sunoModelValid && <p className="text-[11px] text-port-error mt-1">Use a version such as v6 or v4.5.</p>}
+ </div>
+ </div>
+ )}
+
<ToggleChip id="mv-auto-instrumental" label="Instrumental (no vocals)" checked={draft.instrumental} onToggle={() => patch({ instrumental: !draft.instrumental })} />
<MediaModePicker id="mv-auto-media-mode" value={draft.mediaMode} onChange={(mediaMode) => patch({ mediaMode })} />
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 6767350711..d07c3891d5 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -67,7 +67,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `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`. |
| `musicVideoPreview.js` | Pick the representative produced asset for a Music Video project card (`selectMusicVideoPreview`: final video → latest excerpt → latest rendered scene clip → latest scene reference frame → visual spec reference) for the main project grid. Pure, computed off the project record, with image path and fallback helpers (`musicVideoImageSrc`, `musicVideoImageFallback`). |
| `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, and `autopilotDraftFromParams` / `autopilotParamsFromDraft` for the music-video-autopilot Schedule settings form. |
+| `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 (including the Suno form options and `isSunoModelValid`) plus `autonomousStageRows(run)` and `isAutonomousLive(run)` for the run panel, and `autopilotDraftFromParams` / `autopilotParamsFromDraft` for the music-video-autopilot Schedule settings form. |
| `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; the direction-LLM pin rides as `llm`, absent = Auto), plus `llmRouteLabel(route)` for the stage-route summary. 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/musicVideoAutonomous.js b/client/src/lib/musicVideoAutonomous.js
index 032a9ee8ae..1163361cf3 100644
--- a/client/src/lib/musicVideoAutonomous.js
+++ b/client/src/lib/musicVideoAutonomous.js
@@ -6,6 +6,7 @@ import { musicVideoMediaMode } from '../../../server/lib/musicVideoMediaPolicy.j
import {
AUTONOMOUS_DEFAULT_LIMITS, AUTONOMOUS_DEFAULT_TOOLS, AUTONOMOUS_LIVE_STATUSES, AUTONOMOUS_SONG_SOURCES, AUTONOMOUS_STAGES,
+ SUNO_MODEL_PATTERN,
} from '../../../server/lib/musicVideoAutonomous.js';
export const AUTONOMOUS_SONG_SOURCE_LABELS = Object.freeze({
@@ -13,7 +14,7 @@ export const AUTONOMOUS_SONG_SOURCE_LABELS = Object.freeze({
local: 'Local engine (Music Studio)',
});
-export { AUTONOMOUS_CHECKPOINT_IDS, AUTONOMOUS_SONG_SOURCES, autonomousMedium } from '../../../server/lib/musicVideoAutonomous.js';
+export { AUTONOMOUS_CHECKPOINT_IDS, AUTONOMOUS_SONG_SOURCES, SUNO_LIMITS, SUNO_VOCAL_GENDERS, autonomousMedium } from '../../../server/lib/musicVideoAutonomous.js';
export const AUTONOMOUS_CHECKPOINT_LABELS = Object.freeze({
...Object.fromEntries(AUTONOMOUS_STAGES.map((stage) => [stage.id, stage.label])),
@@ -39,8 +40,25 @@ export const emptyAutonomousDraft = () => ({
maxGenerations: String(AUTONOMOUS_DEFAULT_LIMITS.maxGenerations),
checkpoints: [],
moodBoardId: '',
+ // Suno's Advanced-form options; blank leaves that control as Suno has it.
+ suno: { excludeStyles: '', vocalGender: '', model: '' },
});
+/** A blank model is fine (Suno's current one); anything else must name a version such as v6. */
+export const isSunoModelValid = (model) => !String(model || '').trim() || SUNO_MODEL_PATTERN.test(String(model).trim());
+
+// The draft's Suno options as the request's `suno` object, or null when none is set.
+function sunoRequestFromDraft(suno = {}) {
+ const excludeStyles = String(suno.excludeStyles || '').trim();
+ const model = String(suno.model || '').trim();
+ const out = {
+ ...(excludeStyles ? { excludeStyles } : {}),
+ ...(suno.vocalGender ? { vocalGender: suno.vocalGender } : {}),
+ ...(model ? { model } : {}),
+ };
+ return Object.keys(out).length ? out : null;
+}
+
const optionalInt = (raw) => {
const n = Number.parseInt(raw, 10);
return Number.isInteger(n) ? n : undefined;
@@ -50,6 +68,7 @@ const optionalInt = (raw) => {
export function autonomousRequestFromDraft(draft, { providerId, model, effort } = {}) {
const budget = Number.parseFloat(draft.budget);
const maxGenerations = optionalInt(draft.maxGenerations);
+ const suno = draft.songSource === 'suno' ? sunoRequestFromDraft(draft.suno) : null;
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()]));
@@ -63,6 +82,7 @@ export function autonomousRequestFromDraft(draft, { providerId, model, effort }
songSource: draft.songSource,
localFallback: draft.songSource === 'suno' && draft.localFallback === true,
instrumental: draft.instrumental === true,
+ ...(suno ? { suno } : {}),
tools: draft.tools,
...(Object.keys(models).length ? { models } : {}),
...(draft.guidance.trim() ? { guidance: draft.guidance.trim() } : {}),
diff --git a/docs/features/music-video-autonomous.md b/docs/features/music-video-autonomous.md
index ba8a222f43..df1b83a323 100644
--- a/docs/features/music-video-autonomous.md
+++ b/docs/features/music-video-autonomous.md
@@ -29,7 +29,19 @@ State lives on the project as `autonomousRun` — install-local like `production
- `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 }`).
+Approving can carry edits (`POST /api/music-video/:id/autonomous/resume` with `{ lyrics }`, `{ style }` or a `{ suno }` options patch).
+
+**Retake song.** At the `song` checkpoint the run panel also offers **Retake song** (`{ retakeSong: true }` on resume, combinable with the lyrics, style and `suno` edits). It discards the song from the run — its track link, Suno song ids, source and any local render — resets the `song` stage, makes a new song (a new Suno generation spends credits again) and parks at the `song` checkpoint once more. The rejected track stays in the music library; only the project's link to it is cleared, which keeps the lyric cues' text and clears their timings until the new song re-seeds them. A retake anywhere else is refused with 409 `NOT_AT_SONG_CHECKPOINT`.
+
+## Suno form options
+
+A start request (and the scheduled task's settings) may carry an optional `suno` object for Suno's Advanced form, stored on the run's brief:
+
+- `excludeStyles` — Suno's **Exclude styles** field (up to 500 characters). An explicit empty string clears whatever Suno kept from its previous draft; omitting it leaves the field as Suno has it.
+- `vocalGender` — `male` or `female`; clicks Suno's matching button. Not sent for an instrumental.
+- `model` — a model version such as `v6`; the driver opens the version menu only when the current version differs.
+
+All three live under Suno's **More Options** section (expanded on demand) or its version menu. Each is a no-op when unset. When the page has no such control (an older Suno UI) or the version menu does not list the requested model, the driver logs a warning and continues with Suno's current setting rather than failing the song. The start drawer shows these fields when Suno is the song source; a resume may patch them key by key (`null` clears one).
## Production review
@@ -90,16 +102,16 @@ The Suno adapter fills the form through `placeholder` / role selectors and reads
| Method | Path | |
|---|---|---|
-| `POST` | `/api/music-video/autonomous` | Start (202 `{ project, run }`). Body: `prompt` plus optional `songSource` (`suno` default, or `local`), `localFallback`, `tools`, `models` (per-tool model pin), `budgetUsd`, `limits`, `checkpoints`, `instrumental`, `guidance`, `providerId`/`model` (brief + lyrics LLM), `authoring` (code-rendered video). |
+| `POST` | `/api/music-video/autonomous` | Start (202 `{ project, run }`). Body: `prompt` plus optional `songSource` (`suno` default, or `local`), `localFallback`, `suno` (Suno form options), `tools`, `models` (per-tool model pin), `budgetUsd`, `limits`, `checkpoints`, `instrumental`, `guidance`, `providerId`/`model` (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/resume` | Approve the checkpoint, retry the stage that stopped, or resume an interrupted run. Optional `lyrics`, `style`, `suno` edits; `retakeSong: true` at the song checkpoint. |
| `POST` | `/api/music-video/:id/autonomous/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`: `songSource`, `localFallback`, `tools`, `models`, `budgetUsd`, `limits`, `checkpoints`, `instrumental`, `guidance`, `providerId`/`model`, `authoring`, `ideaTags`). Set a cadence on its Schedule card; Run Now fires it once.
+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`: `songSource`, `localFallback`, `suno`, `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.
diff --git a/server/lib/README.md b/server/lib/README.md
index 7c43ea58db..3d4d9e5511 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -806,7 +806,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; `musicVideoCodeDirectionContext(direction)` renders the approved procedural direction (rules + reusable character definitions) for code-authoring requests; `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. |
+| `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, `normalizeSunoOptions` (the brief's optional `suno` form options: exclude styles, vocal gender, model version), 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, `llm: null` clears the direction-LLM pin, server-written `routes` survive but are never patch-settable). Also `normalizeMusicVideoLlm` / `normalizeMusicVideoEffort` / `musicVideoLlmRouteLabel` for that pin and the effective route a stage ran on (#9545). Dependency-light; 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/musicVideoAutonomous.js b/server/lib/musicVideoAutonomous.js
index 4efb9d779b..4740a24f39 100644
--- a/server/lib/musicVideoAutonomous.js
+++ b/server/lib/musicVideoAutonomous.js
@@ -66,7 +66,12 @@ export const AUTONOMOUS_LIMIT_BOUNDS = Object.freeze({
// 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 });
+export const SUNO_LIMITS = Object.freeze({ title: 80, style: 1000, lyrics: 5000, excludeStyles: 500 });
+
+// The Advanced form's optional controls a brief may set (`brief.suno`): the
+// "Exclude styles" field, the vocal gender buttons and the model version menu.
+export const SUNO_VOCAL_GENDERS = Object.freeze(['male', 'female']);
+export const SUNO_MODEL_PATTERN = /^v\d+(\.\d+)?$/i;
// 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.
@@ -76,6 +81,19 @@ export const AUTONOMOUS_DEFAULT_TOOLS = Object.freeze(['image:local', 'video:loc
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);
+/**
+ * The brief's Suno form options, or null when none is set. `excludeStyles` keeps
+ * an explicit '' (a director clearing the field Suno remembers from its last
+ * draft) apart from absent (null = leave the field alone).
+ */
+export function normalizeSunoOptions(raw) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const excludeStyles = isStr(raw.excludeStyles) ? clean(raw.excludeStyles, SUNO_LIMITS.excludeStyles) : null;
+ const vocalGender = SUNO_VOCAL_GENDERS.includes(raw.vocalGender) ? raw.vocalGender : null;
+ const model = isStr(raw.model) && SUNO_MODEL_PATTERN.test(raw.model.trim()) ? raw.model.trim() : null;
+ return excludeStyles === null && !vocalGender && !model ? null : { excludeStyles, vocalGender, model };
+}
+
/**
* How the video is produced, derived from the tool picks:
* `footage` — any image/video tool: the server-owned production run;
@@ -136,6 +154,7 @@ function normalizeAutonomousSettings(raw = {}) {
llm: llm ? { providerId: llm.providerId, model: llm.model, ...(llm.effort ? { effort: llm.effort } : {}) } : null,
authoring: authoringProvider && authoringModel
? { providerId: authoringProvider, model: authoringModel, ...(authoringEffort ? { effort: authoringEffort } : {}) } : null,
+ suno: normalizeSunoOptions(raw.suno),
};
}
@@ -175,14 +194,19 @@ export function nextAutonomousStage(stage) {
/**
* 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.
+ * instrumental song sends no lyrics at all, and no vocal gender. The brief's
+ * `suno` options ride along; null means "leave that control alone".
*/
-export function sunoSongFields({ title, style, lyrics, instrumental = false } = {}) {
+export function sunoSongFields({ title, style, lyrics, instrumental = false, suno = null } = {}) {
+ const options = normalizeSunoOptions(suno);
return {
title: clean(title, SUNO_LIMITS.title) || 'Untitled',
style: clean(style, SUNO_LIMITS.style),
lyrics: instrumental ? '' : clean(lyrics, SUNO_LIMITS.lyrics),
instrumental,
+ excludeStyles: options?.excludeStyles ?? null,
+ vocalGender: instrumental ? null : options?.vocalGender ?? null,
+ model: options?.model ?? null,
};
}
diff --git a/server/lib/musicVideoAutonomous.test.js b/server/lib/musicVideoAutonomous.test.js
index b2bcbdbd48..dcb04892ae 100644
--- a/server/lib/musicVideoAutonomous.test.js
+++ b/server/lib/musicVideoAutonomous.test.js
@@ -12,7 +12,7 @@ import {
sunoSongIdsFromHrefs,
} from './musicVideoAutonomous.js';
import { sanitizeTaskMetadata } from './cosValidation.js';
-import { musicVideoAutonomousStartSchema } from './musicVideoValidation.js';
+import { musicVideoAutonomousResumeSchema, musicVideoAutonomousStartSchema } from './musicVideoValidation.js';
describe('normalizeAutonomousBrief', () => {
it('defaults to the free local tools, no checkpoints, no budget — nothing metered unless opted in', () => {
@@ -57,6 +57,23 @@ describe('normalizeAutonomousBrief', () => {
expect(() => musicVideoAutonomousStartSchema.parse({ prompt: 'p', songSource: 'spotify' })).toThrow();
});
+ it('carries the Suno form options: absent or blank is null, an explicit empty exclusion is kept, junk is dropped', () => {
+ expect(normalizeAutonomousBrief({ prompt: 'p' }).suno).toBeNull();
+ expect(normalizeAutonomousBrief({ prompt: 'p', suno: {} }).suno).toBeNull();
+ const body = musicVideoAutonomousStartSchema.parse({ prompt: 'p', suno: { excludeStyles: ' metal, screamo ', vocalGender: 'female', model: 'v4.5' } });
+ expect(normalizeAutonomousBrief(body).suno).toEqual({ excludeStyles: 'metal, screamo', vocalGender: 'female', model: 'v4.5' });
+ // '' asks the driver to clear the exclusions Suno remembers; it is not "unset".
+ expect(normalizeAutonomousBrief({ prompt: 'p', suno: { excludeStyles: '' } }).suno).toEqual({ excludeStyles: '', vocalGender: null, model: null });
+ expect(normalizeAutonomousBrief({ prompt: 'p', suno: { vocalGender: 'robot', model: 'latest' } }).suno).toBeNull();
+ for (const suno of [{ model: 'latest' }, { vocalGender: 'robot' }, { excludeStyles: 'x'.repeat(501) }, { extra: 1 }]) {
+ expect(() => musicVideoAutonomousStartSchema.parse({ prompt: 'p', suno })).toThrow();
+ }
+ // A resume patches per key and may clear one with null; retakeSong rides the same request.
+ expect(musicVideoAutonomousResumeSchema.parse({ suno: { vocalGender: null }, retakeSong: true })).toEqual({ suno: { vocalGender: null }, retakeSong: true });
+ // The scheduled task stores the same options and they survive a re-normalize.
+ expect(normalizeAutopilotParams({ suno: { model: 'v6' } }).suno).toEqual({ excludeStyles: null, vocalGender: null, model: 'v6' });
+ });
+
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,
@@ -88,10 +105,18 @@ describe('Suno field shaping', () => {
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: 't', style: 's', lyrics: 'words', instrumental: true })).toEqual({
+ title: 't', style: 's', lyrics: '', instrumental: true, excludeStyles: null, vocalGender: null, model: null,
+ });
expect(sunoSongFields({}).title).toBe('Untitled');
});
+ it('passes the brief\'s Suno options to the form, with no vocal gender for an instrumental', () => {
+ const suno = { excludeStyles: 'metal', vocalGender: 'male', model: 'v6' };
+ expect(sunoSongFields({ title: 't', style: 's', lyrics: 'l', suno })).toMatchObject({ excludeStyles: 'metal', vocalGender: 'male', model: 'v6' });
+ expect(sunoSongFields({ title: 't', style: 's', instrumental: true, suno })).toMatchObject({ excludeStyles: 'metal', vocalGender: null, model: 'v6' });
+ });
+
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';
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 56a7592350..a49341ee91 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -37,6 +37,9 @@ import {
AUTONOMOUS_ORIGINS,
AUTONOMOUS_PROMPT_MAX,
AUTONOMOUS_SONG_SOURCES,
+ SUNO_LIMITS,
+ SUNO_MODEL_PATTERN,
+ SUNO_VOCAL_GENDERS,
} from './musicVideoAutonomous.js';
import { MUSCRIPTOR_MODELS } from './muscriptorModels.js';
import { IMAGE_GEN_MODES, VIDEO_GEN_MODES } from './generationModes.js';
@@ -759,6 +762,14 @@ export const musicVideoProductionResumeSchema = z.object({
}).strict();
// ---- Fully-autonomous run: one prompt → lyrics → Suno song → video --------------
+// Suno's Advanced-form options. `excludeStyles: ''` clears the field Suno keeps
+// from its last draft; null (resume only) clears a stored option.
+const musicVideoSunoOptionsSchema = z.object({
+ excludeStyles: z.string().trim().max(SUNO_LIMITS.excludeStyles).nullable().optional(),
+ vocalGender: z.enum(SUNO_VOCAL_GENDERS).nullable().optional(),
+ model: z.string().trim().regex(SUNO_MODEL_PATTERN, 'A Suno model version such as v6').nullable().optional(),
+}).strict();
+
// 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).
@@ -793,6 +804,7 @@ export const musicVideoAutonomousStartSchema = z.object({
ideaId: z.string().max(80).nullable().optional(),
ideaTitle: z.string().max(200).nullable().optional(),
}).strict().optional(),
+ suno: musicVideoSunoOptionsSchema.nullable().optional(),
}).strict();
// Resume a parked/failed run, or approve the checkpoint it is waiting on.
@@ -800,6 +812,10 @@ 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(),
+ // Patch the brief's Suno options, key by key (null clears one).
+ suno: musicVideoSunoOptionsSchema.optional(),
+ // At the song checkpoint: discard the song and generate a new one.
+ retakeSong: z.boolean().optional(),
}).strict();
// A generation kickoff that failed before reaching the queue (#9011) — names
diff --git a/server/routes/musicVideoAutonomous.test.js b/server/routes/musicVideoAutonomous.test.js
index 38210742ae..331ecd00db 100644
--- a/server/routes/musicVideoAutonomous.test.js
+++ b/server/routes/musicVideoAutonomous.test.js
@@ -171,6 +171,31 @@ describe('POST /api/music-video/autonomous', () => {
expect(startProduction).not.toHaveBeenCalled();
});
+ it('stores the Suno form options, and retakes the song over HTTP only at the song checkpoint', async () => {
+ expect((await request(app).post('/api/music-video/autonomous').send({ prompt: 'p', suno: { model: 'latest' } })).status).toBe(400);
+ const res = await begin({ prompt: 'p', checkpoints: ['lyrics', 'song'], suno: { excludeStyles: 'metal', vocalGender: 'female' } });
+ const id = res.body.project.id;
+ await settle();
+ expect(await get(id)).toMatchObject({ status: 'awaiting-approval', awaiting: 'lyrics', brief: { suno: { excludeStyles: 'metal', vocalGender: 'female', model: null } } });
+ const resume = (body) => request(app).post(`/api/music-video/${id}/autonomous/resume`).send(body);
+ const early = await resume({ retakeSong: true });
+ expect(early.status).toBe(409);
+ expect(early.body.code).toBe('NOT_AT_SONG_CHECKPOINT');
+ expect((await get(id)).awaiting).toBe('lyrics');
+
+ expect((await resume({ suno: { vocalGender: 'robot' } })).status).toBe(400);
+ expect((await resume({ suno: { model: 'v6' } })).status).toBe(200);
+ await settle();
+ expect(await get(id)).toMatchObject({ status: 'awaiting-approval', awaiting: 'song', output: { sunoSongIds: ['song-a'] } });
+
+ expect((await resume({ retakeSong: true, suno: { vocalGender: 'male' } })).status).toBe(200);
+ await settle();
+ expect(await get(id)).toMatchObject({
+ status: 'awaiting-approval', awaiting: 'song', stages: { song: { status: 'done' } },
+ brief: { suno: { excludeStyles: 'metal', vocalGender: 'male', model: 'v6' } },
+ });
+ });
+
it('cancels a live run, and refuses to cancel or resume one that is finished or absent', async () => {
const res = await begin({ prompt: 'p', checkpoints: ['lyrics'] });
const id = res.body.project.id;
diff --git a/server/services/musicVideo/autonomousService.js b/server/services/musicVideo/autonomousService.js
index 2a019199ca..44334a41f5 100644
--- a/server/services/musicVideo/autonomousService.js
+++ b/server/services/musicVideo/autonomousService.js
@@ -20,7 +20,9 @@ import { assertProductionApproval, productionReadiness, productionProofNeedsRend
* 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
+ * the run parks `awaiting-approval` and continues on approve; at the song
+ * checkpoint the director may instead retake the song (`retakeSong`), which
+ * discards it and generates a new one before parking there again. A signed-out
* Suno parks `needs-human`; any other failure parks `failed`. Both resume at the
* stage that stopped, reusing Suno songs already submitted. A brief may instead
* (or as a fallback, `localFallback`) make the song with the on-device Music
@@ -45,6 +47,7 @@ import {
autonomousPool,
nextAutonomousStage,
normalizeAutonomousBrief,
+ normalizeSunoOptions,
sunoSongFields,
} from '../../lib/musicVideoAutonomous.js';
import { getProject, mutateProjectRecord } from './projects.js';
@@ -220,7 +223,7 @@ const STAGES = {
// `output.songSource` records a fallback already taken, so a resume stays local.
if ((run.output.songSource || run.brief.songSource) === 'local') return localSong({ project, run, save });
const fields = sunoSongFields({
- title: run.output.title, style: run.output.sunoStyle, lyrics: run.output.lyrics, instrumental: run.brief.instrumental,
+ title: run.output.title, style: run.output.sunoStyle, lyrics: run.output.lyrics, instrumental: run.brief.instrumental, suno: run.brief.suno,
});
let submitted = run.output.sunoSongIds?.length > 0;
let song;
@@ -433,27 +436,61 @@ const assertResumable = (run) => {
if (run.status === 'running' && run.processId === PROCESS_ID) throw runError(409, 'ALREADY_RUNNING', 'This run is already running');
};
+// A retake is only meaningful while the run is parked on the song it would replace.
+const assertAtSongCheckpoint = (run) => {
+ if (run.status !== 'awaiting-approval' || run.awaiting !== 'song') {
+ throw runError(409, 'NOT_AT_SONG_CHECKPOINT', 'A song can only be retaken while the run is waiting for approval of its song');
+ }
+};
+
+// Every key the song stage (and `localSong`) writes; a retake nulls them all so
+// the stage runs from scratch — a new Suno request (the director's explicit,
+// credit-spending choice) or a new local render on a new track.
+const SONG_OUTPUT_KEYS = ['trackId', 'sunoSongIds', 'songSource', 'songFallbackReason', 'localTrackId', 'localSongJobId'];
+
export async function resumeAutonomousVideo(projectId, edits = {}) {
const { run } = await requireRun(projectId);
assertResumable(run);
+ const retake = edits.retakeSong === true;
+ if (retake) assertAtSongCheckpoint(run);
// Stop changes the record immediately, but its stage may still be settling.
// Let that attempt release ownership before marking a new attempt running.
await inflight.get(projectId);
- const out = await patchRun(projectId, (r) => {
+ let retakenTrackId = null;
+ const out = await patchRun(projectId, (r, current) => {
// Cancel or another Resume may have won while the old attempt settled.
assertResumable(r);
+ if (retake) {
+ assertAtSongCheckpoint(r);
+ // Unlink only the track this run linked, never one the director picked since.
+ if (r.output.trackId && current.trackId === r.output.trackId) retakenTrackId = r.output.trackId;
+ }
// 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;
+ const stage = retake ? 'song' : r.stage;
return {
status: 'running', awaiting: null, error: null, errorCode: null, processId: PROCESS_ID,
+ ...(edits.suno ? { brief: { ...r.brief, suno: normalizeSunoOptions({ ...r.brief.suno, ...edits.suno }) } } : {}),
output: {
+ ...(retake ? Object.fromEntries(SONG_OUTPUT_KEYS.map((key) => [key, null])) : {}),
...(typeof edits.lyrics === 'string' ? { lyrics: edits.lyrics } : {}),
...(typeof edits.style === 'string' && edits.style.trim() ? { sunoStyle: edits.style.trim() } : {}),
},
- ...stagePatch(r, stage, { error: null }),
+ ...(retake
+ ? { stage, ...stagePatch(r, stage, { status: 'pending', startedAt: null, finishedAt: null, error: null, step: null }) }
+ : stagePatch(r, stage, { error: null })),
};
});
+ if (retakenTrackId) {
+ // The rejected track stays in the music library (the director may still
+ // want it); only the project's link to it goes. Unlinking keeps the lyric
+ // cues' text and clears their timings (applyProjectPatch → invalidateTimedText),
+ // and the new song's link re-seeds them from its own lyrics. A failed unlink
+ // is not fatal: that same link replaces the old one.
+ await deps.updateProject(projectId, { trackId: null })
+ .catch((err) => console.warn(`⚠️ Autonomous music video ${short(out.run.id)} could not unlink the retaken track: ${err.message}`));
+ console.log(`🎬 Autonomous music video ${short(out.run.id)} retaking its song`);
+ }
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);
diff --git a/server/services/musicVideo/autonomousService.test.js b/server/services/musicVideo/autonomousService.test.js
index 9e76df056f..cc71b08f49 100644
--- a/server/services/musicVideo/autonomousService.test.js
+++ b/server/services/musicVideo/autonomousService.test.js
@@ -262,6 +262,65 @@ describe('checkpoints', () => {
});
});
+describe('retaking the song at the song checkpoint', () => {
+ it('discards the song, re-runs the stage with the edited lyrics, style and Suno options, and parks there again', async () => {
+ await service.startAutonomousVideo({ prompt: 'p', checkpoints: ['song'], suno: { excludeStyles: 'metal', vocalGender: 'female' } });
+ await settled('awaiting-approval');
+ expect(runOf()).toMatchObject({ awaiting: 'song', stage: 'analyze', output: { trackId: 'track-1', sunoSongIds: ['song-a', 'song-b'] } });
+ expect(doubles.generateSunoSong).toHaveBeenLastCalledWith(expect.objectContaining({ excludeStyles: 'metal', vocalGender: 'female', model: null }), expect.any(Object));
+ expect(store.get('mv-auto').trackId).toBe('track-1');
+
+ doubles.createTrack.mockResolvedValueOnce({ id: 'track-2' });
+ doubles.generateSunoSong.mockImplementationOnce(async (_fields, opts) => {
+ // A fresh request: the rejected take's ids are not offered for reuse.
+ expect(opts.songIds).toBeNull();
+ await opts.onSubmitted(['song-c', 'song-d']);
+ return { songId: 'song-d', songIds: ['song-c', 'song-d'], filename: 'music-song-d.m4a' };
+ });
+ const { run } = await service.resumeAutonomousVideo('mv-auto', {
+ retakeSong: true, lyrics: '[verse]\nnew words', style: 'darker synthwave', suno: { vocalGender: 'male', model: 'v6' },
+ });
+ expect(run).toMatchObject({ status: 'running', stage: 'song', awaiting: null, output: { trackId: null, sunoSongIds: null } });
+ await settled('awaiting-approval');
+ expect(runOf()).toMatchObject({
+ awaiting: 'song', stage: 'analyze',
+ brief: { suno: { excludeStyles: 'metal', vocalGender: 'male', model: 'v6' } },
+ output: { trackId: 'track-2', sunoSongIds: ['song-c', 'song-d'], lyrics: '[verse]\nnew words', sunoStyle: 'darker synthwave' },
+ });
+ expect(runOf().stages.song).toMatchObject({ status: 'done' });
+ expect(doubles.generateSunoSong).toHaveBeenCalledTimes(2);
+ expect(doubles.generateSunoSong).toHaveBeenLastCalledWith(expect.objectContaining({
+ lyrics: '[verse]\nnew words', style: 'darker synthwave', excludeStyles: 'metal', vocalGender: 'male', model: 'v6',
+ }), expect.any(Object));
+ // The project was unlinked from the rejected track, then linked to the new one; analysis has not run.
+ expect(doubles.updateProject).toHaveBeenCalledWith('mv-auto', { trackId: null });
+ expect(store.get('mv-auto').trackId).toBe('track-2');
+ expect(calls).not.toContain('analyze');
+
+ // Approving the new take continues the pipeline as before.
+ await service.resumeAutonomousVideo('mv-auto');
+ await vi.waitFor(() => expect(calls).toContain('production'));
+ });
+
+ it('refuses a retake anywhere but the song checkpoint, leaving the run untouched', async () => {
+ await service.startAutonomousVideo({ prompt: 'p', checkpoints: ['lyrics'] });
+ await settled('awaiting-approval');
+ const before = runOf();
+ await expect(service.resumeAutonomousVideo('mv-auto', { retakeSong: true })).rejects.toMatchObject({ status: 409, code: 'NOT_AT_SONG_CHECKPOINT' });
+ expect(runOf()).toEqual(before);
+ expect(calls).not.toContain('suno');
+ });
+
+ it('applies a Suno options patch on a plain approval too', async () => {
+ await service.startAutonomousVideo({ prompt: 'p', checkpoints: ['lyrics'], suno: { excludeStyles: 'metal', model: 'v5' } });
+ await settled('awaiting-approval');
+ await service.resumeAutonomousVideo('mv-auto', { suno: { model: null, vocalGender: 'female' } });
+ await vi.waitFor(() => expect(calls).toContain('production'));
+ expect(runOf().brief.suno).toEqual({ excludeStyles: 'metal', vocalGender: 'female', model: null });
+ expect(doubles.generateSunoSong).toHaveBeenCalledWith(expect.objectContaining({ excludeStyles: 'metal', vocalGender: 'female', model: null }), expect.any(Object));
+ });
+});
+
describe('song sub-step', () => {
it('records the Suno sub-step on the run, pushes it over the autonomous event, and clears it when the stage settles', async () => {
const pushed = [];
diff --git a/server/services/musicVideo/autonomousSuno.js b/server/services/musicVideo/autonomousSuno.js
index 553877e62d..4579937aec 100644
--- a/server/services/musicVideo/autonomousSuno.js
+++ b/server/services/musicVideo/autonomousSuno.js
@@ -11,12 +11,15 @@ import { execFile } from '../../lib/childProcess.js';
import { safeChildProcessOptions } from '../../lib/processEnv.js';
import { ServerError } from '../../lib/errorHandler.js';
import { sunoSongIdsFromHrefs, sunoSongUrl } from '../../lib/musicVideoAutonomous.js';
+import { escapeRegExp } from '../../lib/textUtils.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';
const SUNO_AUDIO_TIMEOUT_MS = 10 * 60 * 1000;
+// How long an opened version menu may take to list its items.
+const SUNO_MENU_WAIT_MS = 5000;
const songLinks = (page, title = null) => page.evaluate((wantedTitle) => [...document.querySelectorAll('a[href*="/song/"]')]
// Workspace rows may finish loading after Create. A newly seen href alone
@@ -82,6 +85,59 @@ async function sunoRefusalSignals(page) {
}).catch(() => ({ inspected: false }));
}
+// An older Suno UI may lack one of the Advanced options: skip it, but say so.
+const skipped = (control) => console.warn(`⚠️ ${LABEL}: ${control} not found — continuing without it`);
+
+/**
+ * The brief's optional Advanced-form controls (model version, exclude styles,
+ * vocal gender). Each is a no-op when unset and is skipped with a warning when
+ * the page has no such control; none of them blocks the song.
+ */
+async function setSunoOptions(page, fields) {
+ if (fields.model) {
+ await step(LABEL, 'choose the model version', async () => {
+ // The version picker is the menu button labelled with the current version ("v6").
+ const version = page.locator('button[aria-haspopup="menu"]').filter({ hasText: /^\s*v\d/i });
+ if (!await version.count()) return skipped('the model version menu');
+ const current = (await version.first().innerText({ timeout: T })).trim();
+ if (current.toLowerCase() === fields.model.toLowerCase()) return;
+ await version.first().click({ timeout: T });
+ const item = page.getByRole('menuitem', { name: new RegExp(`^${escapeRegExp(fields.model)}$`, 'i') });
+ await item.first().waitFor({ state: 'visible', timeout: SUNO_MENU_WAIT_MS }).catch(() => {});
+ if (!await item.count()) {
+ await page.keyboard.press('Escape');
+ return skipped(`model ${fields.model} in the version menu (keeping ${current})`);
+ }
+ await item.first().click({ timeout: T });
+ });
+ }
+ // Exclude styles and vocal gender sit in the collapsible "More Options" section.
+ if (fields.excludeStyles != null || fields.vocalGender) {
+ await step(LABEL, 'open More Options', async () => {
+ if (await page.locator('input[placeholder="Exclude styles"]:visible').count()) return;
+ const more = page.getByText(/^more options$/i);
+ if (!await more.count()) return skipped('the More Options section');
+ await more.first().click({ timeout: T });
+ });
+ }
+ // An explicit '' still fills: Suno keeps the previous draft's exclusions.
+ if (fields.excludeStyles != null) {
+ await step(LABEL, 'fill exclude styles', async () => {
+ const exclude = page.locator('input[placeholder="Exclude styles"]');
+ if (!await exclude.count()) return skipped('the Exclude styles field');
+ await exclude.first().fill(fields.excludeStyles, { timeout: T });
+ });
+ }
+ if (fields.vocalGender) {
+ await step(LABEL, 'choose the vocal gender', async () => {
+ // Plain Male / Female buttons; Suno exposes no pressed state to check.
+ const gender = page.getByRole('button', { name: fields.vocalGender === 'female' ? /^female$/i : /^male$/i });
+ if (!await gender.count()) return skipped('the vocal gender buttons');
+ await gender.first().click({ timeout: T });
+ });
+ }
+}
+
/**
* 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
@@ -130,6 +186,8 @@ async function submitSunoSong(page, fields, { sleep = defaultSleep, now = Date.n
});
}
+ await setSunoOptions(page, fields);
+
const before = new Set(sunoSongIdsFromHrefs(await songLinks(page)));
const observer = observeSunoPosts(page);
try {
diff --git a/server/services/musicVideo/autonomousSuno.test.js b/server/services/musicVideo/autonomousSuno.test.js
index ad1617f5ee..506fc59387 100644
--- a/server/services/musicVideo/autonomousSuno.test.js
+++ b/server/services/musicVideo/autonomousSuno.test.js
@@ -18,27 +18,53 @@ 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, modern = true, newTitleMatches = true, afterCreate = [NEW_A, NEW_B], onCreate, refusalSignals = { inspected: true, captcha: false, credits: false, signIn: false, contentPolicy: false } } = {}) {
+/**
+ * A just-enough Playwright page: tracks fills/clicks and exposes song links that appear after Create.
+ * `options` models the Advanced form's optional controls (version menu, More Options, vocal gender);
+ * null is an older UI that has none of them.
+ */
+function fakePage({ url = 'https://suno.com/create', hasForm = true, modern = true, newTitleMatches = true, afterCreate = [NEW_A, NEW_B], onCreate, refusalSignals = { inspected: true, captcha: false, credits: false, signIn: false, contentPolicy: false }, options = null } = {}) {
const fills = {};
+ const actions = [];
const events = new EventEmitter();
let created = false;
+ const count = (selector) => {
+ if (selector === 'textarea') return hasForm ? 1 : 0;
+ if (selector === '[role="textbox"][aria-label="Lyrics editor"]') return modern ? 1 : 0;
+ if (selector === 'input[placeholder="Exclude styles"]:visible') return options?.expanded ? 1 : 0;
+ if (selector === 'input[placeholder="Exclude styles"]' || selector === 'button[aria-haspopup="menu"]') return options ? 1 : 0;
+ return 1;
+ };
const locator = (selector) => {
const handle = {
- count: async () => selector === 'textarea' ? (hasForm ? 1 : 0) : selector === '[role="textbox"][aria-label="Lyrics editor"]' ? (modern ? 1 : 0) : 1,
+ count: async () => count(selector),
waitFor: async () => {},
fill: async (v) => { fills[selector] = v; },
- click: async () => {},
+ click: async () => { if (selector === 'button[aria-haspopup="menu"]') actions.push('open-version-menu'); },
+ innerText: async () => ` ${options?.version} `,
+ };
+ return { ...handle, first: () => handle, filter: () => ({ ...handle, first: () => handle }) };
+ };
+ const button = (role, options_) => {
+ if (role === 'menuitem') {
+ const match = () => (options?.menuItems || []).find((name) => options_.name.test(name));
+ const item = { waitFor: async () => { if (!match()) throw new Error('menu item timeout'); }, click: async () => { options.version = match(); actions.push(`model:${match()}`); } };
+ return { count: async () => (match() ? 1 : 0), first: () => item };
+ }
+ return {
+ count: async () => role === 'textbox' || role === 'tab' ? (modern ? 1 : 0) : /instrumental|custom/.test(String(options_.name)) ? (modern ? 0 : 1) : /male/.test(String(options_.name)) ? (options ? 1 : 0) : 1,
+ first: () => ({ click: async () => { if (/male/.test(String(options_.name))) actions.push(`gender:${options_.name}`); }, fill: async v => { fills[options_.name] = v; } }),
+ last: () => ({ click: async () => { created = true; actions.push('create'); onCreate?.(events); } }),
};
- return { ...handle, first: () => handle };
};
- const button = (role, options) => ({
- count: async () => role === 'textbox' || role === 'tab' ? (modern ? 1 : 0) : /instrumental|custom/.test(String(options.name)) ? (modern ? 0 : 1) : 1,
- first: () => ({ click: async () => {}, fill: async v => { fills[options.name] = v; } }),
- last: () => ({ click: async () => { created = true; onCreate?.(events); } }),
- });
return {
fills,
+ actions,
+ getByText: (text) => ({
+ count: async () => (options && text.test('More Options') ? 1 : 0),
+ first: () => ({ click: async () => { options.expanded = true; actions.push('more-options'); } }),
+ }),
+ keyboard: { press: async (key) => { actions.push(`key:${key}`); } },
on: events.on.bind(events),
once: events.once.bind(events),
emit: events.emit.bind(events),
@@ -124,6 +150,49 @@ describe('submitSunoSong', () => {
expect(page.fills['textarea[placeholder*="style" i]']).toBe(fields.style);
});
+ it('sets the model version, exclude styles and vocal gender, opening More Options for the hidden exclude field', async () => {
+ const options = { version: 'v5', menuItems: ['v4.5', 'v5', 'v6'], expanded: false };
+ const page = fakePage({ options });
+ const ids = await submitSunoSong(page, { ...fields, excludeStyles: 'metal, screamo', vocalGender: 'female', model: 'V6' }, { sleep: noSleep });
+ expect(ids).toEqual([NEW_A, NEW_B]);
+ expect(page.actions).toEqual(['open-version-menu', 'model:v6', 'more-options', 'gender:/^female$/i', 'create']);
+ expect(page.fills['input[placeholder="Exclude styles"]']).toBe('metal, screamo');
+ });
+
+ it('touches none of the options when the brief sets none, and clears exclusions only when asked', async () => {
+ const page = fakePage({ options: { version: 'v5', menuItems: ['v5', 'v6'], expanded: false } });
+ await submitSunoSong(page, { ...fields, excludeStyles: null, vocalGender: null, model: null }, { sleep: noSleep });
+ expect(page.actions).toEqual(['create']);
+ expect(page.fills).not.toHaveProperty('input[placeholder="Exclude styles"]');
+
+ // Already on the wanted version and already expanded: no menu, no toggle; '' clears Suno's remembered draft.
+ const cleared = fakePage({ options: { version: 'v6', menuItems: ['v6'], expanded: true } });
+ await submitSunoSong(cleared, { ...fields, excludeStyles: '', model: 'v6' }, { sleep: noSleep });
+ expect(cleared.actions).toEqual(['create']);
+ expect(cleared.fills['input[placeholder="Exclude styles"]']).toBe('');
+ });
+
+ it('warns and still creates the song when the version menu lacks the model or an older UI lacks the controls', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ const page = fakePage({ options: { version: 'v5', menuItems: ['v4.5', 'v5'], expanded: true } });
+ await submitSunoSong(page, { ...fields, model: 'v9', vocalGender: 'male' }, { sleep: noSleep });
+ expect(page.actions).toEqual(['open-version-menu', 'key:Escape', 'gender:/^male$/i', 'create']);
+ expect(warn).toHaveBeenCalledWith(expect.stringMatching(/model v9 in the version menu/));
+
+ warn.mockClear();
+ const older = fakePage();
+ await submitSunoSong(older, { ...fields, model: 'v6', excludeStyles: 'metal', vocalGender: 'female' }, { sleep: noSleep });
+ expect(older.actions).toEqual(['create']);
+ expect(warn.mock.calls.map(([line]) => line)).toEqual([
+ expect.stringMatching(/model version menu/), expect.stringMatching(/More Options/),
+ expect.stringMatching(/Exclude styles/), expect.stringMatching(/vocal gender/),
+ ]);
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
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' });