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): local song source for autonomous runs when Suno is unavailable (#9473)

Adam Eivy625d9fea751d
diff --git a/client/src/components/musicVideo/AutonomousRunPanel.test.jsx b/client/src/components/musicVideo/AutonomousRunPanel.test.jsx
index 138dd85310..7976e7605c 100644
--- a/client/src/components/musicVideo/AutonomousRunPanel.test.jsx
+++ b/client/src/components/musicVideo/AutonomousRunPanel.test.jsx
@@ -120,7 +120,7 @@ describe('AutonomousStartDrawer', () => {
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'],
+ prompt: 'a courier crosses a rainy city', songSource: 'suno', localFallback: false, instrumental: false, tools: ['image:local', 'video:local'],
budgetUsd: null, limits: { maxGenerations: 40 }, checkpoints: [],
});
});
@@ -140,4 +140,22 @@ describe('AutonomousStartDrawer', () => {
checkpoints: ['lyrics'], models: { 'image:local': 'flux2-dev' }, budgetUsd: 12, moodBoardId: 'mb-1',
});
});
+
+ 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={() => {}} />);
+ fireEvent.change(screen.getByLabelText('Prompt'), { target: { value: 'p' } });
+ fireEvent.click(screen.getByLabelText(/render locally if suno is unavailable/i));
+ fireEvent.click(screen.getByRole('button', { name: /start autonomous video/i }));
+ await waitFor(() => expect(api.startAutonomousMusicVideo).toHaveBeenCalledTimes(1));
+ expect(api.startAutonomousMusicVideo.mock.calls[0][0]).toMatchObject({ songSource: 'suno', localFallback: true });
+
+ fireEvent.change(screen.getByLabelText('Song source'), { target: { value: 'local' } });
+ expect(screen.queryByLabelText(/render locally if suno is unavailable/i)).toBeNull();
+ fireEvent.change(screen.getByLabelText('Prompt'), { target: { value: 'p' } });
+ fireEvent.click(screen.getByRole('button', { name: /start autonomous video/i }));
+ await waitFor(() => expect(api.startAutonomousMusicVideo).toHaveBeenCalledTimes(2));
+ // The stale fallback tick must not ride along once Suno is no longer the source.
+ expect(api.startAutonomousMusicVideo.mock.calls[1][0]).toMatchObject({ songSource: 'local', localFallback: false });
+ });
});
diff --git a/client/src/components/musicVideo/AutonomousStartDrawer.jsx b/client/src/components/musicVideo/AutonomousStartDrawer.jsx
index 82cfa98696..a58330b4cf 100644
--- a/client/src/components/musicVideo/AutonomousStartDrawer.jsx
+++ b/client/src/components/musicVideo/AutonomousStartDrawer.jsx
@@ -9,7 +9,7 @@ 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, AUTONOMOUS_SONG_SOURCES, AUTONOMOUS_SONG_SOURCE_LABELS, autonomousRequestFromDraft, emptyAutonomousDraft,
} 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';
@@ -17,7 +17,8 @@ const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded
/**
* "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
+ * a mood board, makes the song (Suno in the PortOS Browser, or a local Music
+ * Studio engine), then produces the video
* with the chosen tools. Checkpoints are optional approval stops.
*/
export default function AutonomousStartDrawer({ open, onClose, onStarted }) {
@@ -53,7 +54,7 @@ export default function AutonomousStartDrawer({ open, onClose, onStarted }) {
onClose={onClose}
size="md"
title="Autonomous music video"
- subtitle="One prompt in — lyrics, a Suno song, a mood board and the video out"
+ subtitle="One prompt in — lyrics, a song, a mood board and the video out"
closeOnEsc={false}
closeOnBackdrop={false}
>
@@ -70,10 +71,39 @@ export default function AutonomousStartDrawer({ open, onClose, onStarted }) {
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.
+ The agent also builds its own mood board and visual style from this prompt.
</p>
</div>
+ <div>
+ <label htmlFor="mv-auto-song-source" className="block text-xs text-port-text-muted mb-1">Song source</label>
+ <select
+ id="mv-auto-song-source"
+ value={draft.songSource}
+ onChange={(e) => patch({ songSource: e.target.value })}
+ className={inputClass}
+ >
+ {AUTONOMOUS_SONG_SOURCES.map((source) => (
+ <option key={source} value={source}>{AUTONOMOUS_SONG_SOURCE_LABELS[source]}</option>
+ ))}
+ </select>
+ <p className="text-[11px] text-port-text-muted mt-1">
+ {draft.songSource === 'suno'
+ ? 'Suno is driven through the PortOS Browser — sign in to Suno there first. It spends Suno credits.'
+ : 'Rendered on this machine by a ready Music Studio engine (a lyric-capable one such as ACE-Step for vocals). Free, but it queues behind other GPU work.'}
+ </p>
+ {draft.songSource === 'suno' && (
+ <div className="mt-2">
+ <ToggleChip
+ id="mv-auto-local-fallback"
+ label="Render locally if Suno is unavailable"
+ checked={draft.localFallback}
+ onToggle={() => patch({ localFallback: !draft.localFallback })}
+ />
+ </div>
+ )}
+ </div>
+
<ToggleChip id="mv-auto-instrumental" label="Instrumental (no vocals)" checked={draft.instrumental} onToggle={() => patch({ instrumental: !draft.instrumental })} />
<ToolPicker tools={draft.tools} models={draft.models} onChange={patch} />
diff --git a/client/src/lib/musicVideoAutonomous.js b/client/src/lib/musicVideoAutonomous.js
index 179db42dca..a0c3d20d28 100644
--- a/client/src/lib/musicVideoAutonomous.js
+++ b/client/src/lib/musicVideoAutonomous.js
@@ -3,10 +3,15 @@
// form's draft ↔ wire mapping and the run's display helpers.
import {
- AUTONOMOUS_DEFAULT_LIMITS, AUTONOMOUS_DEFAULT_TOOLS, AUTONOMOUS_LIVE_STATUSES, AUTONOMOUS_STAGES,
+ AUTONOMOUS_DEFAULT_LIMITS, AUTONOMOUS_DEFAULT_TOOLS, AUTONOMOUS_LIVE_STATUSES, AUTONOMOUS_SONG_SOURCES, AUTONOMOUS_STAGES,
} from '../../../server/lib/musicVideoAutonomous.js';
-export { AUTONOMOUS_CHECKPOINT_IDS, autonomousMedium } from '../../../server/lib/musicVideoAutonomous.js';
+export const AUTONOMOUS_SONG_SOURCE_LABELS = Object.freeze({
+ suno: 'Suno (PortOS Browser)',
+ local: 'Local engine (Music Studio)',
+});
+
+export { AUTONOMOUS_CHECKPOINT_IDS, AUTONOMOUS_SONG_SOURCES, autonomousMedium } from '../../../server/lib/musicVideoAutonomous.js';
export const AUTONOMOUS_CHECKPOINT_LABELS = Object.freeze({
...Object.fromEntries(AUTONOMOUS_STAGES.map((stage) => [stage.id, stage.label])),
@@ -20,6 +25,8 @@ export const AUTONOMOUS_STATUS_LABELS = Object.freeze({
export const emptyAutonomousDraft = () => ({
prompt: '',
+ songSource: AUTONOMOUS_SONG_SOURCES[0],
+ localFallback: false,
instrumental: false,
tools: [...AUTONOMOUS_DEFAULT_TOOLS],
models: {},
@@ -44,6 +51,8 @@ export function autonomousRequestFromDraft(draft, { providerId, model } = {}) {
.map(([id, value]) => [id, value.trim()]));
return {
prompt: draft.prompt.trim(),
+ songSource: draft.songSource,
+ localFallback: draft.songSource === 'suno' && draft.localFallback === true,
instrumental: draft.instrumental === true,
tools: draft.tools,
...(Object.keys(models).length ? { models } : {}),
diff --git a/docs/features/music-video-autonomous.md b/docs/features/music-video-autonomous.md
index 754a91fb66..db3691d6fb 100644
--- a/docs/features/music-video-autonomous.md
+++ b/docs/features/music-video-autonomous.md
@@ -1,6 +1,6 @@
# 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.
+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, or on this machine), and produces the video with the tools you allowed. Approval checkpoints are optional; with none chosen the run is fully unattended.
## Pipeline
@@ -14,6 +14,7 @@ brief → lyrics → style → song → analyze → produce
| `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 |
+| `song` (local) | `songSource: 'local'` renders the song with the on-device Music Designer engines instead (see [Local song source](#local-song-source)). | free (GPU time) |
| `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 |
@@ -30,6 +31,17 @@ State lives on the project as `autonomousRun` — install-local like `production
Approving can carry edits (`POST /api/music-video/:id/autonomous/resume` with `{ lyrics }` or `{ style }`).
+## Local song source
+
+`songSource: 'local'` makes the song with the Music Designer engines (ACE-Step, MiniMax, …) through the same audio media-job lane the Music studio uses — no browser, no Suno account. The request goes through `queueMusicGeneration` (`server/services/musicGeneration.js`, the pipeline behind `POST /api/music/generate`), called in-process.
+
+1. The Track is created first (title, lyrics, prompt) and its id stored as `output.localTrackId`.
+2. A ready engine is picked: a lyric-capable one for a vocal song, any ready one for an instrumental (`LOCAL_SONG_NO_ENGINE` when none can run — install one in Music Studio). The prompt is the musical description plus the (editable) style line; the duration is a full song clamped to the engine's window, or the engine's automatic duration.
+3. The render is queued onto that Track and the job id stored as `output.localSongJobId`; the Music Studio completion hook lands the audio on the Track, and the stage settles once it is there. A retry rejoins the stored job (or starts a new one if it failed/was canceled) and never renders a track that already has audio.
+4. Stop / Cancel on a run waiting in this stage cancels the queued render.
+
+**Fallback.** With `localFallback: true` (Suno source only), a Suno failure *before Suno accepted the request* — signed out, no credits, page changed, browser down — switches the run to the local source instead of parking it (`output.songSource: 'local'`, `output.songFallbackReason`). Once Suno has accepted a request the credits are spent, so a later failure parks as usual and a retry reuses those songs. A fully unattended scheduled run therefore still finishes when Suno is unavailable.
+
## Failure handling
- A signed-out Suno parks the run **`needs-human`** (`PUBLISH_LOGIN_REQUIRED`): sign in to Suno in the PortOS Browser, then Resume.
@@ -42,7 +54,7 @@ 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 `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`, `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). |
@@ -51,7 +63,7 @@ Progress is pushed over the `music-video:autonomous` socket event (`{ projectId,
## 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.
+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.
- 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.
@@ -60,4 +72,4 @@ A programmatic scheduled task (no agent). Each run picks the **oldest active Bra
## 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`.
+`server/lib/musicVideoAutonomous.js` (vocabulary, brief normalizer, Suno limits, idea picker) · `server/services/musicVideo/autonomous{Service,Brief,Board,Suno,LocalSong}.js` · `server/services/musicGeneration.js` · `server/services/scheduledHandlers/musicVideoAutopilot.js` · `client/src/components/musicVideo/Autonomous{StartDrawer,RunPanel}.jsx`.
diff --git a/server/lib/musicVideoAutonomous.js b/server/lib/musicVideoAutonomous.js
index 9695cafb98..9c712249dc 100644
--- a/server/lib/musicVideoAutonomous.js
+++ b/server/lib/musicVideoAutonomous.js
@@ -15,7 +15,8 @@
* 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
+ * into the music library and imported as a track — or, with
+ * `songSource: 'local'`, the on-device Music Designer engines render it
* 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)
@@ -32,7 +33,7 @@ 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: 'song', label: 'Song' }),
Object.freeze({ id: 'analyze', label: 'Analyze song' }),
Object.freeze({ id: 'produce', label: 'Produce video' }),
]);
@@ -45,7 +46,9 @@ export const AUTONOMOUS_STAGE_IDS = Object.freeze(AUTONOMOUS_STAGES.map((s) => s
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']);
+// Where the song comes from: the Suno web UI (needs a signed-in PortOS Browser
+// and credits) or the on-device Music Designer engines (free, no browser).
+export const AUTONOMOUS_SONG_SOURCES = Object.freeze(['suno', 'local']);
// 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']);
@@ -111,6 +114,9 @@ function normalizeAutonomousSettings(raw = {}) {
const authoringModel = clean(raw.authoring?.model, 200);
return {
songSource: AUTONOMOUS_SONG_SOURCES.includes(raw.songSource) ? raw.songSource : AUTONOMOUS_SONG_SOURCES[0],
+ // Suno only: when it cannot even take the request (signed out, no credits,
+ // page changed), render the song locally instead of parking the run.
+ localFallback: raw.localFallback === true,
instrumental: raw.instrumental === true,
guidance: clean(raw.guidance, 4000),
tools,
diff --git a/server/lib/musicVideoAutonomous.test.js b/server/lib/musicVideoAutonomous.test.js
index 240987690c..2200df59f0 100644
--- a/server/lib/musicVideoAutonomous.test.js
+++ b/server/lib/musicVideoAutonomous.test.js
@@ -39,6 +39,14 @@ describe('normalizeAutonomousBrief', () => {
expect(brief.llm).toEqual({ providerId: 'prov', model: 'm' });
});
+ it('keeps Suno the default song source, accepts local, and only honors the fallback opt-in as a boolean', () => {
+ expect(normalizeAutonomousBrief({ prompt: 'p' })).toMatchObject({ songSource: 'suno', localFallback: false });
+ expect(normalizeAutonomousBrief({ prompt: 'p', songSource: 'local', localFallback: true })).toMatchObject({ songSource: 'local', localFallback: true });
+ expect(normalizeAutonomousBrief({ prompt: 'p', songSource: 'spotify', localFallback: 'yes' })).toMatchObject({ songSource: 'suno', localFallback: false });
+ expect(musicVideoAutonomousStartSchema.parse({ prompt: 'p', songSource: 'local', localFallback: true })).toMatchObject({ songSource: 'local' });
+ expect(() => musicVideoAutonomousStartSchema.parse({ prompt: 'p', songSource: 'spotify' })).toThrow();
+ });
+
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,
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 6136a4668f..921beca719 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -738,6 +738,7 @@ 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(),
+ localFallback: z.boolean().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(),
diff --git a/server/routes/music.js b/server/routes/music.js
index 389d36ffdf..4e0e1c72c6 100644
--- a/server/routes/music.js
+++ b/server/routes/music.js
@@ -17,7 +17,8 @@
* `code` is its "Code" engine: the LLM writes the piece as Strudel code, which
* only ever runs in the browser's sandboxed player frame, never on the server.
*
- * Generation runs the engine-agnostic `generateMusic` (server/services/pipeline/
+ * Generation (`queueMusicGeneration`, services/musicGeneration.js — shared with the
+ * autonomous Music Video run) runs the engine-agnostic `generateMusic` (server/services/pipeline/
* musicGen.js) through the unified audio media-job lane. The completion hook
* lands the WAV in the shared music library and creates or updates the Track,
* independently of whether the requesting browser remains mounted. The pipeline
@@ -35,7 +36,7 @@ import { validateRequest } from '../lib/validation.js';
import { createLineReader } from '../lib/streamLines.js';
import { SETUP_IMAGE_VIDEO_SCRIPT, spawnSetupScript, stopSetupScript } from '../lib/setupScriptRunner.js';
import {
- ENGINES, getEngine, isEngineHealthy, isEnginePlatformSupported,
+ ENGINES, isEngineHealthy, isEnginePlatformSupported,
enginePlatformLabel, resolveEngineVramReadiness, MUSIC_VRAM_READINESS,
formatEngineVramReadinessMessage,
} from '../services/pipeline/musicGen.js';
@@ -50,16 +51,8 @@ import { onClientDisconnect, openSseStream } from '../lib/sseDownload.js';
import { createInstallLogger } from '../lib/installLogger.js';
import { inspectModelCache } from '../lib/hfCache.js';
import { getCudaCapability } from '../lib/cudaCapability.js';
-import {
- FEDERATED_MEDIA_WIRE_VERSION,
- federatedMediaAudioProfileSchema,
- federatedMediaDeniesFeature,
- federatedMediaSupports,
-} from '../lib/federatedMediaWire.js';
-import { enqueueJob, listJobs } from '../services/mediaJobQueue/index.js';
-import { resolveFederatedMediaProvider } from '../services/federatedMediaConsumer.js';
-import { getPeers } from '../services/instances.js';
-import * as tracks from '../services/tracks/index.js';
+import { federatedMediaAudioProfileSchema } from '../lib/federatedMediaWire.js';
+import { queueMusicGeneration } from '../services/musicGeneration.js';
const router = Router();
@@ -448,194 +441,9 @@ const generateSchema = z.object({
// The check moved into the handler, below the capability resolve.
});
-const INSTRUMENTAL_ONLY_GUIDANCE = 'Instrumental only. Do not include sung, spoken, chanted, choir, or background vocals. Carry the lead melody with the described instruments or textures.';
-
router.post('/generate', asyncHandler(async (req, res) => {
const body = validateRequest(generateSchema, req.body ?? {});
-
- // Validate local destination and duplicate state before any peer probe. A
- // stale track or duplicate request should not generate needless federation
- // traffic, even though the probe itself does not start provider work.
- if (body.trackId) {
- const existing = await tracks.getTrack(body.trackId);
- if (!existing) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });
- }
- const liveJobs = listJobs({ kind: 'audio' }).filter((job) => job.status === 'queued' || job.status === 'running');
- const duplicate = liveJobs.find((job) => {
- const tag = job.params?.musicStudio;
- return body.trackId ? tag?.trackId === body.trackId : tag && !tag.trackId;
- });
- if (duplicate) {
- throw new ServerError('Music generation is already in progress', {
- status: 409,
- code: 'PIPELINE_MUSIC_BUSY',
- context: { jobId: duplicate.id },
- });
- }
-
- let engine;
- let repo;
- let remoteMedia;
-
- if (body.mediaProviderPeerId) {
- const peers = await getPeers();
- const peer = peers.find((candidate) => candidate.id === body.mediaProviderPeerId);
- if (!peer) {
- throw new ServerError('Selected media provider peer was not found', {
- status: 404,
- code: 'MEDIA_PROVIDER_PEER_NOT_FOUND',
- });
- }
- const resolved = await resolveFederatedMediaProvider(peer, {
- kind: 'audio',
- engine: body.engine,
- modelId: body.modelId,
- });
- const capability = resolved.capability;
- if (body.durationMode === 'auto' && !capability.autoDuration) {
- throw new ServerError('Selected remote engine does not support automatic duration', {
- status: 400,
- code: 'MEDIA_PROVIDER_AUTO_DURATION_UNSUPPORTED',
- });
- }
- if (body.durationSec !== undefined
- && ((Number.isFinite(capability.minDurationSec) && body.durationSec < capability.minDurationSec)
- || (Number.isFinite(capability.maxDurationSec) && body.durationSec > capability.maxDurationSec))) {
- throw new ServerError('Requested duration is outside the remote engine limits', {
- status: 400,
- code: 'MEDIA_PROVIDER_DURATION_UNSUPPORTED',
- context: {
- minDurationSec: capability.minDurationSec,
- maxDurationSec: capability.maxDurationSec,
- },
- });
- }
- // Two independent facts, and conflating them is how a lyrical render
- // silently comes back instrumental: `capability.lyrics` says the MODEL
- // sings — the same check the provider's own admission gate makes — while
- // the `lyrics` FEATURE says this PEER'S BUILD carries the words at all.
- // Each failure gets its own message, so a caller who actually sent words is
- // told which half is missing rather than getting a plausible render of the
- // wrong thing. Why absent fails closed lives in federatedMediaSupports.
- if (body.lyrics && !body.instrumentalOnly) {
- if (!capability.lyrics) {
- throw new ServerError(
- 'The selected remote model renders instrumental audio only. Pick a lyric-capable model, or render this track locally.',
- { status: 400, code: 'MEDIA_PROVIDER_LYRICS_UNSUPPORTED' },
- );
- }
- if (!federatedMediaSupports(resolved.status, 'lyrics', capability)) {
- // `federatedMediaDeniesFeature` keeps message selection separate from
- // the shared fail-closed gate: a present pre-vocabulary status is also
- // a build-level denial for lyrics, while a missing status is unknown.
- throw new ServerError(
- federatedMediaDeniesFeature(resolved.status, 'lyrics', capability)
- ? 'The selected peer runs a PortOS build that cannot carry lyrics to its provider. Update the peer, or render this track locally.'
- : 'The selected peer is not reporting that it can carry lyrics to its provider. Render this track locally, or pick a lyric-capable peer.',
- { status: 400, code: 'MEDIA_PROVIDER_LYRICS_UNSUPPORTED' },
- );
- }
- }
- engine = {
- id: capability.engine,
- name: capability.engineName,
- // The model's own capability, not the wire's: this drives the render
- // snapshot (`lyricsEnabled`), which records what the engine is, and the
- // guard above already refused the one combination where the two disagree
- // in a way that would change the audio.
- lyrics: capability.lyrics,
- };
- remoteMedia = {
- wireVersion: FEDERATED_MEDIA_WIRE_VERSION,
- peerId: peer.id,
- reconcile: false,
- cancelRequested: false,
- profile: body.remoteMusicProfile,
- };
- } else {
- // Reject an unknown engine explicitly rather than letting getEngine() fall
- // back to the default — a typo/stale client would otherwise render with the
- // wrong local backend. An absent engine still selects the local default.
- if (body.engine !== undefined && !ENGINES[body.engine]) {
- throw new ServerError(`Unknown audio engine: ${body.engine}`, { status: 400, code: 'PIPELINE_MUSIC_UNKNOWN_ENGINE' });
- }
- engine = getEngine(body.engine);
-
- // Resolve a local user-installed model to its HF repo. Remote models are
- // validated against the peer's exact allowlist and never interpreted as a
- // path or local repository on this machine.
- if (body.modelId) {
- const merged = await listEngineModels(engine.id);
- const picked = merged.find((m) => m.id === body.modelId);
- if (!picked) {
- throw new ServerError(`Unknown model for ${engine.name}: ${body.modelId}`, { status: 400, code: 'PIPELINE_MUSIC_UNKNOWN_MODEL' });
- }
- if (picked.userAdded) repo = picked.repo || picked.id;
- }
- }
-
- // The lyrics that actually CONDITION this render: what the caller sent for a
- // lyric-aware engine ('' = render without lyrics), nothing for a non-lyric
- // engine. The same value drives the generation call AND the render snapshot,
- // so a render card can never claim conditioning text the audio wasn't built
- // from (an absent-lyrics lyric render is genuinely un-conditioned, not "the
- // track's old words").
- // Make the render-level override explicit in BOTH conditioning inputs. Merely
- // dropping lyrics is not enough when the authored caption itself mentions a
- // vocalist. Keep it idempotent so remixing an instrumental take does not append
- // the same directive repeatedly.
- const usedPrompt = body.instrumentalOnly && !body.prompt.includes(INSTRUMENTAL_ONLY_GUIDANCE)
- ? `${body.prompt}\n\n${INSTRUMENTAL_ONLY_GUIDANCE}`
- : body.prompt;
- const usedLyrics = engine.lyrics && !body.instrumentalOnly ? (body.lyrics ?? '') : '';
- if (remoteMedia) {
- // Lyrics ride the marker, not the top-level params, for the same reason the
- // profile does: `params.lyrics` stays blank so a build rolled back past
- // `remoteMedia` fails closed instead of re-rendering locally (#4683).
- // Omitted when empty so an instrumental remote render submits — and
- // idempotency-hashes — exactly the body a pre-lyrics build did.
- if (usedLyrics) remoteMedia.lyrics = usedLyrics;
- remoteMedia.request = {
- engine: engine.id,
- modelId: body.modelId,
- ...(body.durationSec !== undefined ? { durationSec: body.durationSec } : {}),
- ...(body.durationMode !== undefined ? { durationMode: body.durationMode } : {}),
- };
- }
-
- const result = await enqueueJob({
- kind: 'audio',
- params: {
- // Keep only the fixed-vocabulary profile and routing request under the
- // versioned remote marker. An older PortOS that does not understand
- // remoteMedia will route this audio job to the local adapter; the empty
- // prompt makes that rollback fail closed before a duplicate local render.
- // New consumers derive the safe provider prompt from the profile.
- prompt: remoteMedia ? '' : usedPrompt,
- lyrics: remoteMedia ? '' : usedLyrics,
- engine: engine.id,
- modelId: body.modelId,
- repo,
- durationSec: body.durationSec,
- durationMode: body.durationMode,
- ...(remoteMedia ? { remoteMedia } : {}),
- musicStudio: {
- trackId: body.trackId || null,
- title: body.title || body.prompt.slice(0, 60),
- artistId: body.artistId,
- artist: body.artist,
- albumId: body.albumId,
- // Keep editable source text distinct from the augmented prompt and
- // empty lyric payload that actually condition an instrumental render.
- authoredPrompt: body.prompt,
- authoredLyrics: engine.lyrics === true ? body.lyrics : undefined,
- lyricsEnabled: engine.lyrics === true,
- lyricsProvided: engine.lyrics === true && body.lyrics !== undefined,
- instrumentalOnly: body.instrumentalOnly,
- },
- },
- });
- res.status(202).json(result);
+ res.status(202).json(await queueMusicGeneration(body));
}));
export default router;
diff --git a/server/services/musicGeneration.js b/server/services/musicGeneration.js
new file mode 100644
index 0000000000..5f940c37d5
--- /dev/null
+++ b/server/services/musicGeneration.js
@@ -0,0 +1,216 @@
+/**
+ * Music generation pipeline — the engine-agnostic "make a song" request shared by
+ * the Music studio's `POST /api/music/generate` route and the autonomous Music
+ * Video run's local song source (#9473), so the run queues a render in-process
+ * instead of calling its own HTTP API.
+ *
+ * `queueMusicGeneration` takes an already-validated request body (the route's
+ * `generateSchema` owns validation), resolves the local engine/model or the
+ * federated media provider, and enqueues one audio media job. It returns the
+ * enqueue ack immediately; the audio lane renders it and the Music Studio
+ * completion hook (`musicStudioHook.js`) lands the WAV on the track.
+ */
+
+import { ServerError } from '../lib/errorHandler.js';
+import { ENGINES, getEngine } from './pipeline/musicGen.js';
+import { listEngineModels } from './audioModels.js';
+import {
+ FEDERATED_MEDIA_WIRE_VERSION,
+ federatedMediaDeniesFeature,
+ federatedMediaSupports,
+} from '../lib/federatedMediaWire.js';
+import { enqueueJob, listJobs } from './mediaJobQueue/index.js';
+import { resolveFederatedMediaProvider } from './federatedMediaConsumer.js';
+import { getPeers } from './instances.js';
+import * as tracks from './tracks/index.js';
+
+const INSTRUMENTAL_ONLY_GUIDANCE = 'Instrumental only. Do not include sung, spoken, chanted, choir, or background vocals. Carry the lead melody with the described instruments or textures.';
+
+/** Queue one audio render. Resolves to `{ jobId, position, status }`. */
+export async function queueMusicGeneration(input) {
+ // The route's schema applies these defaults; an in-process caller gets them here.
+ const body = { instrumentalOnly: false, artistId: '', artist: '', albumId: '', ...input };
+ // Validate local destination and duplicate state before any peer probe. A
+ // stale track or duplicate request should not generate needless federation
+ // traffic, even though the probe itself does not start provider work.
+ if (body.trackId) {
+ const existing = await tracks.getTrack(body.trackId);
+ if (!existing) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ const liveJobs = listJobs({ kind: 'audio' }).filter((job) => job.status === 'queued' || job.status === 'running');
+ const duplicate = liveJobs.find((job) => {
+ const tag = job.params?.musicStudio;
+ return body.trackId ? tag?.trackId === body.trackId : tag && !tag.trackId;
+ });
+ if (duplicate) {
+ throw new ServerError('Music generation is already in progress', {
+ status: 409,
+ code: 'PIPELINE_MUSIC_BUSY',
+ context: { jobId: duplicate.id },
+ });
+ }
+
+ let engine;
+ let repo;
+ let remoteMedia;
+
+ if (body.mediaProviderPeerId) {
+ const peers = await getPeers();
+ const peer = peers.find((candidate) => candidate.id === body.mediaProviderPeerId);
+ if (!peer) {
+ throw new ServerError('Selected media provider peer was not found', {
+ status: 404,
+ code: 'MEDIA_PROVIDER_PEER_NOT_FOUND',
+ });
+ }
+ const resolved = await resolveFederatedMediaProvider(peer, {
+ kind: 'audio',
+ engine: body.engine,
+ modelId: body.modelId,
+ });
+ const capability = resolved.capability;
+ if (body.durationMode === 'auto' && !capability.autoDuration) {
+ throw new ServerError('Selected remote engine does not support automatic duration', {
+ status: 400,
+ code: 'MEDIA_PROVIDER_AUTO_DURATION_UNSUPPORTED',
+ });
+ }
+ if (body.durationSec !== undefined
+ && ((Number.isFinite(capability.minDurationSec) && body.durationSec < capability.minDurationSec)
+ || (Number.isFinite(capability.maxDurationSec) && body.durationSec > capability.maxDurationSec))) {
+ throw new ServerError('Requested duration is outside the remote engine limits', {
+ status: 400,
+ code: 'MEDIA_PROVIDER_DURATION_UNSUPPORTED',
+ context: {
+ minDurationSec: capability.minDurationSec,
+ maxDurationSec: capability.maxDurationSec,
+ },
+ });
+ }
+ // Two independent facts, and conflating them is how a lyrical render
+ // silently comes back instrumental: `capability.lyrics` says the MODEL
+ // sings — the same check the provider's own admission gate makes — while
+ // the `lyrics` FEATURE says this PEER'S BUILD carries the words at all.
+ // Each failure gets its own message, so a caller who actually sent words is
+ // told which half is missing rather than getting a plausible render of the
+ // wrong thing. Why absent fails closed lives in federatedMediaSupports.
+ if (body.lyrics && !body.instrumentalOnly) {
+ if (!capability.lyrics) {
+ throw new ServerError(
+ 'The selected remote model renders instrumental audio only. Pick a lyric-capable model, or render this track locally.',
+ { status: 400, code: 'MEDIA_PROVIDER_LYRICS_UNSUPPORTED' },
+ );
+ }
+ if (!federatedMediaSupports(resolved.status, 'lyrics', capability)) {
+ // `federatedMediaDeniesFeature` keeps message selection separate from
+ // the shared fail-closed gate: a present pre-vocabulary status is also
+ // a build-level denial for lyrics, while a missing status is unknown.
+ throw new ServerError(
+ federatedMediaDeniesFeature(resolved.status, 'lyrics', capability)
+ ? 'The selected peer runs a PortOS build that cannot carry lyrics to its provider. Update the peer, or render this track locally.'
+ : 'The selected peer is not reporting that it can carry lyrics to its provider. Render this track locally, or pick a lyric-capable peer.',
+ { status: 400, code: 'MEDIA_PROVIDER_LYRICS_UNSUPPORTED' },
+ );
+ }
+ }
+ engine = {
+ id: capability.engine,
+ name: capability.engineName,
+ // The model's own capability, not the wire's: this drives the render
+ // snapshot (`lyricsEnabled`), which records what the engine is, and the
+ // guard above already refused the one combination where the two disagree
+ // in a way that would change the audio.
+ lyrics: capability.lyrics,
+ };
+ remoteMedia = {
+ wireVersion: FEDERATED_MEDIA_WIRE_VERSION,
+ peerId: peer.id,
+ reconcile: false,
+ cancelRequested: false,
+ profile: body.remoteMusicProfile,
+ };
+ } else {
+ // Reject an unknown engine explicitly rather than letting getEngine() fall
+ // back to the default — a typo/stale client would otherwise render with the
+ // wrong local backend. An absent engine still selects the local default.
+ if (body.engine !== undefined && !ENGINES[body.engine]) {
+ throw new ServerError(`Unknown audio engine: ${body.engine}`, { status: 400, code: 'PIPELINE_MUSIC_UNKNOWN_ENGINE' });
+ }
+ engine = getEngine(body.engine);
+
+ // Resolve a local user-installed model to its HF repo. Remote models are
+ // validated against the peer's exact allowlist and never interpreted as a
+ // path or local repository on this machine.
+ if (body.modelId) {
+ const merged = await listEngineModels(engine.id);
+ const picked = merged.find((m) => m.id === body.modelId);
+ if (!picked) {
+ throw new ServerError(`Unknown model for ${engine.name}: ${body.modelId}`, { status: 400, code: 'PIPELINE_MUSIC_UNKNOWN_MODEL' });
+ }
+ if (picked.userAdded) repo = picked.repo || picked.id;
+ }
+ }
+
+ // The lyrics that actually CONDITION this render: what the caller sent for a
+ // lyric-aware engine ('' = render without lyrics), nothing for a non-lyric
+ // engine. The same value drives the generation call AND the render snapshot,
+ // so a render card can never claim conditioning text the audio wasn't built
+ // from (an absent-lyrics lyric render is genuinely un-conditioned, not "the
+ // track's old words").
+ // Make the render-level override explicit in BOTH conditioning inputs. Merely
+ // dropping lyrics is not enough when the authored caption itself mentions a
+ // vocalist. Keep it idempotent so remixing an instrumental take does not append
+ // the same directive repeatedly.
+ const usedPrompt = body.instrumentalOnly && !body.prompt.includes(INSTRUMENTAL_ONLY_GUIDANCE)
+ ? `${body.prompt}\n\n${INSTRUMENTAL_ONLY_GUIDANCE}`
+ : body.prompt;
+ const usedLyrics = engine.lyrics && !body.instrumentalOnly ? (body.lyrics ?? '') : '';
+ if (remoteMedia) {
+ // Lyrics ride the marker, not the top-level params, for the same reason the
+ // profile does: `params.lyrics` stays blank so a build rolled back past
+ // `remoteMedia` fails closed instead of re-rendering locally (#4683).
+ // Omitted when empty so an instrumental remote render submits — and
+ // idempotency-hashes — exactly the body a pre-lyrics build did.
+ if (usedLyrics) remoteMedia.lyrics = usedLyrics;
+ remoteMedia.request = {
+ engine: engine.id,
+ modelId: body.modelId,
+ ...(body.durationSec !== undefined ? { durationSec: body.durationSec } : {}),
+ ...(body.durationMode !== undefined ? { durationMode: body.durationMode } : {}),
+ };
+ }
+
+ const result = await enqueueJob({
+ kind: 'audio',
+ params: {
+ // Keep only the fixed-vocabulary profile and routing request under the
+ // versioned remote marker. An older PortOS that does not understand
+ // remoteMedia will route this audio job to the local adapter; the empty
+ // prompt makes that rollback fail closed before a duplicate local render.
+ // New consumers derive the safe provider prompt from the profile.
+ prompt: remoteMedia ? '' : usedPrompt,
+ lyrics: remoteMedia ? '' : usedLyrics,
+ engine: engine.id,
+ modelId: body.modelId,
+ repo,
+ durationSec: body.durationSec,
+ durationMode: body.durationMode,
+ ...(remoteMedia ? { remoteMedia } : {}),
+ musicStudio: {
+ trackId: body.trackId || null,
+ title: body.title || body.prompt.slice(0, 60),
+ artistId: body.artistId,
+ artist: body.artist,
+ albumId: body.albumId,
+ // Keep editable source text distinct from the augmented prompt and
+ // empty lyric payload that actually condition an instrumental render.
+ authoredPrompt: body.prompt,
+ authoredLyrics: engine.lyrics === true ? body.lyrics : undefined,
+ lyricsEnabled: engine.lyrics === true,
+ lyricsProvided: engine.lyrics === true && body.lyrics !== undefined,
+ instrumentalOnly: body.instrumentalOnly,
+ },
+ },
+ });
+ return result;
+}
diff --git a/server/services/musicVideo/autonomousLocalSong.js b/server/services/musicVideo/autonomousLocalSong.js
new file mode 100644
index 0000000000..7e2cf449bf
--- /dev/null
+++ b/server/services/musicVideo/autonomousLocalSong.js
@@ -0,0 +1,136 @@
+/**
+ * Autonomous Music Video — the local song source (#9473).
+ *
+ * The alternative to the Suno step: renders the song with the on-device Music
+ * Designer engines (ACE-Step, MiniMax, …) through the same audio media-job lane
+ * the Music studio uses, so an unattended run still finishes when Suno is
+ * signed out, out of credits or redesigned.
+ *
+ * The song's Track is created up front and handed to the generation request, so
+ * the Music Studio completion hook (`musicStudioHook.js`) lands the rendered
+ * audio on it. This module then only waits for the job to finish and for that
+ * attach to be visible on the track. The job id is stored the moment it is
+ * queued (`onSubmitted`), so a retry rejoins a render still in flight instead of
+ * starting a second one, and a track that already has audio is never re-rendered.
+ *
+ * Every provider (engine registry, media queue, track store) is injectable so
+ * the flow is unit-testable without a GPU.
+ */
+
+import { ServerError } from '../../lib/errorHandler.js';
+import { sleep as defaultSleep } from '../../lib/fileCore.js';
+import { trimTo } from '../../lib/textUtils.js';
+
+// A full song, not the engines' short default clip. Clamped to each engine's own window.
+const LOCAL_SONG_TARGET_SEC = 180;
+// A render waits behind the GPU lane, so the cap is generous; the run's stop
+// button cancels the job, which settles the wait.
+const LOCAL_SONG_TIMEOUT_MS = 90 * 60 * 1000;
+// The completion hook attaches the audio a moment after the job reports done.
+const ATTACH_POLL_MS = 500;
+const ATTACH_POLLS = 40;
+const TERMINAL = ['completed', 'failed', 'canceled'];
+
+const fail = (status, code, message, context) => new ServerError(message, { status, code, ...(context ? { context } : {}) });
+
+const defaults = {
+ listEngines: async () => (await import('../pipeline/musicGen.js')).ENGINES,
+ isEngineHealthy: async (id) => (await import('../pipeline/musicGen.js')).isEngineHealthy(id),
+ queueGeneration: async (body) => (await import('../musicGeneration.js')).queueMusicGeneration(body),
+ getJob: async (id) => (await import('../mediaJobQueue/index.js')).getJob(id),
+ getTrack: async (id) => (await import('../tracks/index.js')).getTrack(id),
+ // Resolves with the job once it reaches a terminal state (the queue's own
+ // events; an already-finished job resolves at once).
+ waitForJob: async (jobId, { timeoutMs }) => {
+ const { getJob, mediaJobEvents } = await import('../mediaJobQueue/index.js');
+ return new Promise((resolve, reject) => {
+ const settle = (job) => {
+ cleanup();
+ resolve(job);
+ };
+ const onEvent = (job) => { if (job?.id === jobId) settle(job); };
+ const timer = setTimeout(() => {
+ cleanup();
+ reject(fail(504, 'LOCAL_SONG_TIMEOUT', 'The local song did not finish rendering in time', { jobId }));
+ }, timeoutMs);
+ const cleanup = () => {
+ clearTimeout(timer);
+ for (const status of TERMINAL) mediaJobEvents.off(status, onEvent);
+ };
+ for (const status of TERMINAL) mediaJobEvents.on(status, onEvent);
+ const current = getJob(jobId);
+ if (current && TERMINAL.includes(current.status)) settle(current);
+ });
+ },
+ sleep: defaultSleep,
+};
+
+/**
+ * Pick the local engine for a song: a lyric-capable one when the song has
+ * vocals, otherwise any — among the engines this host can actually run now.
+ */
+export async function pickLocalSongEngine({ instrumental }, deps = {}) {
+ const { listEngines, isEngineHealthy } = { ...defaults, ...deps };
+ const engines = Object.values(await listEngines());
+ const healthy = [];
+ for (const engine of engines) {
+ if (await isEngineHealthy(engine.id)) healthy.push(engine);
+ }
+ const picked = (instrumental ? healthy : healthy.filter((e) => e.lyrics === true))[0];
+ if (picked) return picked;
+ throw fail(409, 'LOCAL_SONG_NO_ENGINE', instrumental || !healthy.length
+ ? 'No local music engine is ready — install one in Music Studio, or use the Suno source'
+ : 'No ready local music engine can sing lyrics — install a lyric-capable one (e.g. ACE-Step) in Music Studio, make the song instrumental, or use the Suno source');
+}
+
+/** The render window for an engine: automatic when it supports that, else a full song clamped to its limits. */
+const durationFor = (engine) => (engine.autoDuration
+ ? { durationMode: 'auto' }
+ : { durationSec: Math.max(engine.minDurationSec ?? 1, Math.min(LOCAL_SONG_TARGET_SEC, engine.maxDurationSec ?? LOCAL_SONG_TARGET_SEC)) });
+
+/**
+ * Render one song and wait for its audio to land on `trackId`.
+ *
+ * `prompt` is the musical description; `lyrics` is ignored for an instrumental.
+ * Resolves to `{ trackId, filename, jobId }`. `jobId` (a previous attempt's
+ * queued render) is rejoined while it is still live or finished.
+ */
+export async function generateLocalSong({ trackId, title, prompt, lyrics = '', instrumental = false, jobId = null, onSubmitted }, overrides = {}) {
+ const deps = { ...defaults, ...overrides };
+ const { timeoutMs = LOCAL_SONG_TIMEOUT_MS } = overrides;
+
+ const existing = await deps.getTrack(trackId);
+ if (!existing) throw fail(404, 'NOT_FOUND', 'The song track was removed before its audio rendered');
+ if (existing.audioFilename) return { trackId, filename: existing.audioFilename, jobId };
+
+ let job = jobId ? await deps.getJob(jobId) : null;
+ if (!job || job.status === 'failed' || job.status === 'canceled') {
+ const engine = await pickLocalSongEngine({ instrumental }, deps);
+ const queued = await deps.queueGeneration({
+ prompt: trimTo(prompt, 8000),
+ ...(instrumental || !lyrics ? {} : { lyrics: trimTo(lyrics, 20000) }),
+ instrumentalOnly: instrumental,
+ engine: engine.id,
+ ...durationFor(engine),
+ trackId,
+ title: trimTo(title, 200) || undefined,
+ });
+ jobId = queued.jobId;
+ await onSubmitted?.(jobId);
+ console.log(`🎵 Autonomous music video queued a local song on ${engine.id} (job ${String(jobId).slice(0, 8)})`);
+ }
+
+ job = await deps.waitForJob(jobId, { timeoutMs });
+ if (job.status !== 'completed') {
+ throw fail(502, 'LOCAL_SONG_FAILED', `The local song ${job.status === 'canceled' ? 'was canceled' : 'failed to render'}${job.error ? `: ${trimTo(job.error, 300)}` : ''}`, { jobId });
+ }
+ const filename = job.result?.filename;
+ for (let i = 0; i < ATTACH_POLLS; i += 1) {
+ const track = await deps.getTrack(trackId);
+ if (track?.audioFilename && (!filename || track.audioFilename === filename)) return { trackId, filename: track.audioFilename, jobId };
+ await deps.sleep(ATTACH_POLL_MS);
+ }
+ throw fail(504, 'LOCAL_SONG_ATTACH_TIMEOUT', 'The local song rendered but did not reach its track', { jobId, filename });
+}
+
+export const __testing = { durationFor };
diff --git a/server/services/musicVideo/autonomousLocalSong.test.js b/server/services/musicVideo/autonomousLocalSong.test.js
new file mode 100644
index 0000000000..17d51514f0
--- /dev/null
+++ b/server/services/musicVideo/autonomousLocalSong.test.js
@@ -0,0 +1,136 @@
+/**
+ * Autonomous Music Video — local song source. The engine registry, media queue
+ * and track store are doubles; these tests pin what this module owns: choosing
+ * an engine the host can run, queuing onto the pre-created track, rejoining a
+ * render a previous attempt queued, and settling only once the audio has landed.
+ */
+
+import { describe, it, expect, vi } from 'vitest';
+// The media queue is only reached by the default job waiter (every other test injects its own).
+const queue = vi.hoisted(() => ({ events: null, jobs: {} }));
+vi.mock('../mediaJobQueue/index.js', async () => {
+ const { EventEmitter: Emitter } = await import('events');
+ queue.events = new Emitter();
+ return { mediaJobEvents: queue.events, getJob: (id) => queue.jobs[id] || null };
+});
+
+import { generateLocalSong, pickLocalSongEngine } from './autonomousLocalSong.js';
+
+const ENGINES = {
+ musicgen: { id: 'musicgen', minDurationSec: 1, maxDurationSec: 30 },
+ acestep: { id: 'acestep', lyrics: true, minDurationSec: 1, maxDurationSec: 240 },
+ minimax: { id: 'minimax', lyrics: true, autoDuration: true },
+};
+
+function harness({ healthy = ['musicgen', 'acestep'], tracks = {}, jobs = {}, waited } = {}) {
+ const state = { tracks: { 't-1': { id: 't-1' }, ...tracks }, jobs: { ...jobs } };
+ const deps = {
+ listEngines: async () => ENGINES,
+ isEngineHealthy: async (id) => healthy.includes(id),
+ queueGeneration: vi.fn(async () => ({ jobId: 'job-1', status: 'queued' })),
+ getJob: async (id) => state.jobs[id] || null,
+ getTrack: async (id) => state.tracks[id] || null,
+ // The completion hook attaches the audio a beat after the job reports done.
+ waitForJob: vi.fn(async (id) => waited?.(state, id) ?? { id, status: 'completed', result: { filename: 'song.wav' } }),
+ sleep: vi.fn(async () => { state.tracks['t-1'] = { id: 't-1', audioFilename: 'song.wav' }; }),
+ };
+ return { state, deps };
+}
+
+const song = { trackId: 't-1', title: 'Neon Rain', prompt: 'synthwave', lyrics: '[verse]\nrain' };
+
+describe('pickLocalSongEngine', () => {
+ it('takes a ready lyric-capable engine for a vocal song, any ready engine for an instrumental', async () => {
+ const { deps } = harness();
+ expect((await pickLocalSongEngine({ instrumental: false }, deps)).id).toBe('acestep');
+ expect((await pickLocalSongEngine({ instrumental: true }, deps)).id).toBe('musicgen');
+ });
+
+ it('names what is missing instead of rendering the wrong thing', async () => {
+ const { deps } = harness({ healthy: ['musicgen'] });
+ await expect(pickLocalSongEngine({ instrumental: false }, deps)).rejects.toMatchObject({ code: 'LOCAL_SONG_NO_ENGINE', message: expect.stringContaining('sing lyrics') });
+ const none = harness({ healthy: [] });
+ await expect(pickLocalSongEngine({ instrumental: true }, none.deps)).rejects.toMatchObject({ code: 'LOCAL_SONG_NO_ENGINE' });
+ });
+});
+
+describe('generateLocalSong', () => {
+ it('queues the render onto the track, stores the job id, and settles when the audio has landed', async () => {
+ const { deps } = harness();
+ const onSubmitted = vi.fn();
+ const out = await generateLocalSong({ ...song, onSubmitted }, deps);
+ expect(deps.queueGeneration).toHaveBeenCalledWith({
+ prompt: 'synthwave', lyrics: '[verse]\nrain', instrumentalOnly: false, engine: 'acestep', durationSec: 180, trackId: 't-1', title: 'Neon Rain',
+ });
+ expect(onSubmitted).toHaveBeenCalledWith('job-1');
+ expect(out).toEqual({ trackId: 't-1', filename: 'song.wav', jobId: 'job-1' });
+ expect(deps.sleep).toHaveBeenCalled(); // waited out the hook's attach
+ });
+
+ it('sends no lyrics for an instrumental and lets an auto-duration engine choose the length', async () => {
+ const { deps } = harness({ healthy: ['minimax'] });
+ await generateLocalSong({ ...song, instrumental: true }, deps);
+ const body = deps.queueGeneration.mock.calls[0][0];
+ expect(body).toMatchObject({ engine: 'minimax', instrumentalOnly: true, durationMode: 'auto' });
+ expect(body).not.toHaveProperty('lyrics');
+ expect(body).not.toHaveProperty('durationSec');
+ });
+
+ it('does not render again when the track already has audio, and rejoins a live job from a previous attempt', async () => {
+ const done = harness({ tracks: { 't-1': { id: 't-1', audioFilename: 'song.wav' } } });
+ await generateLocalSong(song, done.deps);
+ expect(done.deps.queueGeneration).not.toHaveBeenCalled();
+
+ const live = harness({ jobs: { 'job-0': { id: 'job-0', status: 'running' } } });
+ await generateLocalSong({ ...song, jobId: 'job-0' }, live.deps);
+ expect(live.deps.queueGeneration).not.toHaveBeenCalled();
+ expect(live.deps.waitForJob).toHaveBeenCalledWith('job-0', expect.any(Object));
+ });
+
+ it('starts a new render when the previous job failed or was canceled', async () => {
+ const { deps } = harness({ jobs: { 'job-0': { id: 'job-0', status: 'canceled' } } });
+ const out = await generateLocalSong({ ...song, jobId: 'job-0' }, deps);
+ expect(deps.queueGeneration).toHaveBeenCalledTimes(1);
+ expect(out.jobId).toBe('job-1');
+ });
+
+ it('fails the stage when the render fails or the audio never reaches the track', async () => {
+ const failed = harness({ waited: async (_s, id) => ({ id, status: 'failed', error: 'out of memory' }) });
+ await expect(generateLocalSong(song, failed.deps)).rejects.toMatchObject({ code: 'LOCAL_SONG_FAILED', message: expect.stringContaining('out of memory') });
+
+ const lost = harness();
+ lost.deps.sleep = vi.fn(async () => {});
+ await expect(generateLocalSong(song, lost.deps)).rejects.toMatchObject({ code: 'LOCAL_SONG_ATTACH_TIMEOUT' });
+ });
+
+ it('fails clearly when the track was deleted while the run waited', async () => {
+ const { deps } = harness();
+ await expect(generateLocalSong({ ...song, trackId: 'gone' }, deps)).rejects.toMatchObject({ status: 404 });
+ });
+});
+
+describe('the default job waiter', () => {
+ const waitWith = (jobId, opts = {}) => {
+ const { deps } = harness();
+ const { waitForJob: _injected, ...rest } = deps; // fall back to the module's own waiter
+ return generateLocalSong({ ...song, jobId }, { ...rest, ...opts, getJob: async (id) => queue.jobs[id] || { id, status: 'running' } });
+ };
+
+ it('settles on the queue event for its own job only, then detaches its listeners', async () => {
+ const pending = waitWith('job-9');
+ await vi.waitFor(() => expect(queue.events.listenerCount('completed')).toBe(1));
+ queue.events.emit('completed', { id: 'someone-else', status: 'completed' });
+ queue.events.emit('completed', { id: 'job-9', status: 'completed', result: { filename: 'song.wav' } });
+ await expect(pending).resolves.toMatchObject({ jobId: 'job-9', filename: 'song.wav' });
+ expect(queue.events.listenerCount('completed') + queue.events.listenerCount('failed') + queue.events.listenerCount('canceled')).toBe(0);
+ });
+
+ it('turns a cancel (the run was stopped) into a failed stage, and a stuck queue into a timeout', async () => {
+ const canceled = waitWith('job-8');
+ await vi.waitFor(() => expect(queue.events.listenerCount('canceled')).toBe(1));
+ queue.events.emit('canceled', { id: 'job-8', status: 'canceled' });
+ await expect(canceled).rejects.toMatchObject({ code: 'LOCAL_SONG_FAILED' });
+
+ await expect(waitWith('job-7', { timeoutMs: 5 })).rejects.toMatchObject({ code: 'LOCAL_SONG_TIMEOUT' });
+ });
+});
diff --git a/server/services/musicVideo/autonomousService.js b/server/services/musicVideo/autonomousService.js
index 4cfbba3c5b..3dd73199f5 100644
--- a/server/services/musicVideo/autonomousService.js
+++ b/server/services/musicVideo/autonomousService.js
@@ -18,7 +18,10 @@
* 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.
+ * 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
+ * Designer engines (`autonomousLocalSong.js`), so a run finishes with Suno
+ * unavailable.
*
* Production is delegated: `produce` starts the server-owned production run (or
* the code render) and finishes when that reports back over the `production`
@@ -57,6 +60,8 @@ const defaults = {
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),
+ generateLocalSong: async (args) => (await import('./autonomousLocalSong.js')).generateLocalSong(args),
+ cancelLocalSong: async (jobId) => (await import('../mediaJobQueue/index.js')).cancelJob(jobId),
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),
@@ -118,6 +123,31 @@ const stagePatch = (run, stage, patch) => ({ stages: { [stage]: { ...run.stages[
const llmOf = (run) => ({ providerId: run.brief.llm?.providerId, model: run.brief.llm?.model || undefined });
+/**
+ * The local song source: the track is created first (its id is stored at once),
+ * the render is queued onto it, and the stage settles once the audio has landed.
+ * A retry rejoins the stored render instead of queuing a second one.
+ */
+async function localSong({ project, run, save }) {
+ const title = trimTo(run.output.title, 200) || 'Untitled';
+ const lyrics = run.brief.instrumental ? '' : run.output.lyrics || '';
+ // The style line is editable at the style checkpoint, so it conditions the render alongside the description.
+ const prompt = [run.output.musicalDescription, run.output.sunoStyle].filter(Boolean).join('\n\n') || run.brief.prompt;
+ let trackId = run.output.localTrackId;
+ if (!trackId) {
+ const track = await deps.createTrack({ title, concept: run.brief.prompt, lyrics, prompt });
+ trackId = track.id;
+ await save({ output: { localTrackId: trackId } });
+ }
+ await deps.generateLocalSong({
+ trackId, title, prompt, lyrics, instrumental: run.brief.instrumental, jobId: run.output.localSongJobId,
+ onSubmitted: (jobId) => save({ output: { localSongJobId: jobId } }),
+ });
+ // Linking the track seeds the project's timed lyric cues from the track lyrics.
+ await deps.updateProject(project.id, { trackId });
+ return { output: { trackId, songSource: 'local' } };
+}
+
const STAGES = {
async brief({ project, run }) {
const { brief } = await deps.draftCreativeBrief({
@@ -150,15 +180,28 @@ const STAGES = {
async song({ project, run, save }) {
if (run.output.trackId) return { output: {} };
+ // `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,
});
- 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 } }),
- });
+ let submitted = run.output.sunoSongIds?.length > 0;
+ let song;
+ try {
+ 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) => { submitted = true; return save({ output: { sunoSongIds: ids } }); },
+ });
+ } catch (err) {
+ // Only before Suno accepted a request: after that, credits are spent and a
+ // retry reuses those songs rather than paying for a second render.
+ if (!run.brief.localFallback || submitted) throw err;
+ console.warn(`⚠️ Autonomous music video ${short(run.id)} could not use Suno (${trimTo(err.message, 200)}) — rendering the song locally`);
+ await save({ output: { songSource: 'local', songFallbackReason: trimTo(err.message, 500) } });
+ return localSong({ project, run, save });
+ }
const track = await deps.createTrack({
title: fields.title, concept: run.brief.prompt, lyrics: fields.lyrics, prompt: fields.style,
});
@@ -223,6 +266,9 @@ async function advance(projectId) {
try {
result = await executor({ project, run, save: (patch) => patchRun(projectId, () => patch) });
} catch (err) {
+ // A stop/cancel mid-stage (it cancels the local render) must not become a failure.
+ const latest = projectAutonomousRun(await getProject(projectId));
+ if (latest?.status !== 'running' || latest.processId !== PROCESS_ID) return;
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;
@@ -348,6 +394,7 @@ export async function stopAutonomousVideo(projectId) {
const { stopProduction } = await import('./productionService.js');
await stopProduction(projectId, run.output.productionRunId).catch(() => {});
}
+ if (run.stage === 'song' && run.output.localSongJobId) await deps.cancelLocalSong(run.output.localSongJobId).catch(() => {});
return { project: out.project, run: presentAutonomousRun(out.run) };
}
@@ -359,6 +406,7 @@ export async function cancelAutonomousVideo(projectId) {
const { cancelProduction } = await import('./productionService.js');
await cancelProduction(projectId, run.output.productionRunId).catch(() => {});
}
+ if (run.stage === 'song' && run.output.localSongJobId) await deps.cancelLocalSong(run.output.localSongJobId).catch(() => {});
return { project: out.project, run: presentAutonomousRun(out.run) };
}
diff --git a/server/services/musicVideo/autonomousService.test.js b/server/services/musicVideo/autonomousService.test.js
index c10c0c6b95..b3fb891989 100644
--- a/server/services/musicVideo/autonomousService.test.js
+++ b/server/services/musicVideo/autonomousService.test.js
@@ -61,6 +61,11 @@ beforeEach(() => {
await opts.onSubmitted(['song-a', 'song-b']);
return { songId: 'song-a', songIds: ['song-a', 'song-b'], filename: 'music-song-a.mp3' };
}),
+ generateLocalSong: stub('local', async ({ trackId, onSubmitted }) => {
+ await onSubmitted('job-local');
+ return { trackId, filename: 'song.wav', jobId: 'job-local' };
+ }),
+ cancelLocalSong: stub('cancel-local', async () => true),
createTrack: stub('track', async () => ({ id: 'track-1' })),
attachAudio: stub('attach', async () => ({})),
probeDuration: stub('probe', async () => 187),
@@ -201,6 +206,81 @@ describe('failure and retry', () => {
});
});
+describe('local song source (#9473)', () => {
+ it('runs end to end with Suno never touched: the track exists first, the render lands on it, then analysis', async () => {
+ doubles.generateSunoSong.mockRejectedValue(new Error('Suno must not be used'));
+ await service.startAutonomousVideo({ prompt: 'p', songSource: 'local', instrumental: false });
+ await vi.waitFor(() => expect(calls).toContain('production'));
+ expect(calls).toEqual(['createProject', 'brief', 'updateProject', 'lyrics', 'board', 'updateProject', 'track', 'local', 'updateProject', 'analyze', 'production']);
+ expect(doubles.generateLocalSong).toHaveBeenCalledWith(expect.objectContaining({
+ trackId: 'track-1', title: 'Neon Rain', lyrics: '[verse]\nrain on glass', instrumental: false,
+ prompt: 'Synthwave with a melancholic arc\n\nsynthwave, dreamy, 100 bpm',
+ }));
+ expect(runOf().output).toMatchObject({ trackId: 'track-1', localTrackId: 'track-1', localSongJobId: 'job-local', songSource: 'local' });
+ expect(store.get('mv-auto').trackId).toBe('track-1');
+ });
+
+ it('retries a failed render on the same track and job instead of creating a second track', async () => {
+ doubles.generateLocalSong.mockImplementationOnce(async ({ onSubmitted }) => {
+ await onSubmitted('job-local');
+ throw new Error('out of memory');
+ });
+ await service.startAutonomousVideo({ prompt: 'p', songSource: 'local' });
+ await settled('failed');
+ await service.resumeAutonomousVideo('mv-auto');
+ await vi.waitFor(() => expect(calls).toContain('production'));
+ expect(calls.filter((c) => c === 'track')).toHaveLength(1);
+ expect(doubles.generateLocalSong).toHaveBeenLastCalledWith(expect.objectContaining({ trackId: 'track-1', jobId: 'job-local' }));
+ });
+
+ it('falls back to the local engine when the brief opts in and Suno cannot take the request', async () => {
+ doubles.generateSunoSong.mockImplementationOnce(async () => {
+ throw Object.assign(new Error('Sign in to Suno'), { code: 'PUBLISH_LOGIN_REQUIRED' });
+ });
+ await service.startAutonomousVideo({ prompt: 'p', localFallback: true });
+ await vi.waitFor(() => expect(calls).toContain('production'));
+ expect(calls).toContain('local');
+ expect(runOf().output).toMatchObject({ songSource: 'local', songFallbackReason: 'Sign in to Suno', trackId: 'track-1' });
+ });
+
+ it('does not fall back without the opt-in, nor after Suno already took credits for the request', 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(calls).not.toContain('local');
+ });
+
+ it('keeps the Suno songs when the download fails even with the fallback on', async () => {
+ doubles.generateSunoSong.mockImplementationOnce(async (_f, opts) => {
+ await opts.onSubmitted(['song-a']);
+ throw new Error('did not finish rendering');
+ });
+ await service.startAutonomousVideo({ prompt: 'p', localFallback: true });
+ await settled('failed');
+ expect(calls).not.toContain('local');
+ expect(runOf().output.sunoSongIds).toEqual(['song-a']);
+ });
+
+ it('cancels the queued render on stop and leaves the run stopped, not failed', async () => {
+ let release;
+ doubles.generateLocalSong.mockImplementationOnce(async ({ onSubmitted }) => {
+ await onSubmitted('job-local');
+ await new Promise((resolve) => { release = resolve; });
+ throw new Error('The local song was canceled');
+ });
+ await service.startAutonomousVideo({ prompt: 'p', songSource: 'local' });
+ await vi.waitFor(() => expect(runOf()?.output.localSongJobId).toBe('job-local'));
+ await service.stopAutonomousVideo('mv-auto');
+ expect(doubles.cancelLocalSong).toHaveBeenCalledWith('job-local');
+ release();
+ await new Promise((resolve) => setTimeout(resolve, 20)); // the aborted stage settles in the background
+ expect(runOf()).toMatchObject({ status: 'stopped', stage: 'song' });
+ expect(runOf().stages.song.status).toBe('running');
+ });
+});
+
describe('events and process pinning', () => {
it('publishes every change over the autonomous event', async () => {
const seen = [];