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: add local music studio options to autonomous music video

[._.]/ Adam Eivyf4d1b2ce267c
diff --git a/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.jsx b/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.jsx
index 1ae8773439..3ea78852c7 100644
--- a/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.jsx
+++ b/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.jsx
@@ -70,7 +70,7 @@ export default function MusicVideoAutopilotSettings({ taskType, config, onUpdate
<input id="mv-ap-idea-tags" value={draft.ideaTags} onChange={(e) => patch({ ideaTags: e.target.value })} placeholder="song, music — comma separated; blank = any active idea" className={inputClass} />
</div>
- <SongSourcePicker idPrefix="mv-ap" songSource={draft.songSource} localFallback={draft.localFallback} onChange={patch} />
+ <SongSourcePicker idPrefix="mv-ap" songSource={draft.songSource} localFallback={draft.localFallback} localMusic={draft.localMusic} onChange={patch} />
<ToggleChip id="mv-ap-instrumental" label="Instrumental (no vocals)" checked={draft.instrumental} onToggle={() => patch({ instrumental: !draft.instrumental })} />
diff --git a/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.test.jsx b/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.test.jsx
index 9af47bdbd1..e573fd4ebb 100644
--- a/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.test.jsx
+++ b/client/src/components/cos/tabs/schedule/MusicVideoAutopilotSettings.test.jsx
@@ -4,6 +4,9 @@ import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/re
vi.mock('../../../../services/apiMoodBoard.js', () => ({
listMoodBoardNames: vi.fn(async () => [{ id: 'mb-1', name: 'Neon Rain' }]),
}));
+vi.mock('../../../../services/apiMusic.js', () => ({
+ listMusicEngines: vi.fn(async () => ({ engines: [{ id: 'acestep', name: 'ACE-Step', ready: true, lyrics: true }] })),
+}));
vi.mock('../../../../services/apiImageVideo.js', () => ({
getVideoGenModelContext: vi.fn(async () => ({
models: [
diff --git a/client/src/components/musicVideo/AutonomousRunPanel.test.jsx b/client/src/components/musicVideo/AutonomousRunPanel.test.jsx
index c25ca9b09d..75caa3a93c 100644
--- a/client/src/components/musicVideo/AutonomousRunPanel.test.jsx
+++ b/client/src/components/musicVideo/AutonomousRunPanel.test.jsx
@@ -22,6 +22,9 @@ vi.mock('../../services/apiMusicVideo.js', () => ({
cancelAutonomousMusicVideo: vi.fn(),
}));
vi.mock('../../services/apiMoodBoard.js', () => ({ listMoodBoardNames: vi.fn(async () => [{ id: 'mb-1', name: 'Neon Rain' }]) }));
+vi.mock('../../services/apiMusic.js', () => ({
+ listMusicEngines: vi.fn(async () => ({ engines: [{ id: 'acestep', name: 'ACE-Step', ready: true, lyrics: true }] })),
+}));
vi.mock('../../services/apiImageVideo.js', () => ({
getVideoGenModelContext: vi.fn(async () => ({
models: [
diff --git a/client/src/components/musicVideo/AutonomousStartDrawer.jsx b/client/src/components/musicVideo/AutonomousStartDrawer.jsx
index 2c957472cd..cc78fc2964 100644
--- a/client/src/components/musicVideo/AutonomousStartDrawer.jsx
+++ b/client/src/components/musicVideo/AutonomousStartDrawer.jsx
@@ -96,7 +96,7 @@ export default function AutonomousStartDrawer({ open, onClose, onStarted }) {
</p>
</div>
- <SongSourcePicker idPrefix="mv-auto" songSource={draft.songSource} localFallback={draft.localFallback} onChange={patch} />
+ <SongSourcePicker idPrefix="mv-auto" songSource={draft.songSource} localFallback={draft.localFallback} localMusic={draft.localMusic} onChange={patch} />
{draft.songSource === 'suno' && (
<div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,10rem),16rem))] gap-3">
diff --git a/client/src/components/musicVideo/SongSourcePicker.jsx b/client/src/components/musicVideo/SongSourcePicker.jsx
index ee0b1b6893..f949f4277b 100644
--- a/client/src/components/musicVideo/SongSourcePicker.jsx
+++ b/client/src/components/musicVideo/SongSourcePicker.jsx
@@ -1,15 +1,47 @@
+import { useEffect, useState } from 'react';
import ToggleChip from '../ui/ToggleChip.jsx';
-import { AUTONOMOUS_SONG_SOURCES, AUTONOMOUS_SONG_SOURCE_LABELS } from '../../lib/musicVideoAutonomous.js';
+import {
+ AUTONOMOUS_SONG_SOURCES,
+ AUTONOMOUS_SONG_SOURCE_LABELS,
+ LOCAL_MUSIC_CODE_LANGUAGES,
+ LOCAL_MUSIC_CODE_LANGUAGE_LABELS,
+ LOCAL_MUSIC_TYPES,
+ LOCAL_MUSIC_TYPE_LABELS,
+} from '../../lib/musicVideoAutonomous.js';
+import { listMusicEngines } from '../../services/apiMusic.js';
const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';
/**
* Where an autonomous run's song comes from — Suno through the PortOS Browser or
* a local Music Studio engine — plus the Suno-only opt-in to render locally when
- * Suno cannot take the request. Shared by the start drawer and the autopilot
- * Schedule form; `onChange` receives a partial draft patch.
+ * Suno cannot take the request, and local Music Studio options (audio model or code).
+ * Shared by the start drawer and the autopilot Schedule form; `onChange` receives
+ * a partial draft patch.
*/
-export default function SongSourcePicker({ idPrefix, songSource, localFallback, onChange }) {
+export default function SongSourcePicker({ idPrefix, songSource, localFallback, localMusic, engines: propEngines, onChange }) {
+ const [engines, setEngines] = useState(propEngines || []);
+ const showLocalOptions = songSource === 'local' || localFallback === true;
+
+ useEffect(() => {
+ if (propEngines || !showLocalOptions) return;
+ let active = true;
+ listMusicEngines({ silent: true })
+ .then((data) => {
+ if (!active) return;
+ const list = Array.isArray(data?.engines) ? data.engines : (Array.isArray(data) ? data : []);
+ setEngines(list);
+ })
+ .catch(() => {});
+ return () => { active = false; };
+ }, [propEngines, showLocalOptions]);
+
+ const type = localMusic?.type === 'code' ? 'code' : 'model';
+ const engine = localMusic?.engine || '';
+ const language = localMusic?.language || 'strudel';
+
+ const patchLocal = (patch) => onChange({ localMusic: { ...(localMusic || {}), ...patch } });
+
return (
<div>
<label htmlFor={`${idPrefix}-song-source`} className="block text-xs text-port-text-muted mb-1">Song source</label>
@@ -38,6 +70,69 @@ export default function SongSourcePicker({ idPrefix, songSource, localFallback,
/>
</div>
)}
+
+ {showLocalOptions && (
+ <div className="mt-3 p-3 bg-port-card/40 border border-port-border/60 rounded space-y-3">
+ <div className="text-xs font-medium text-port-text">
+ {songSource === 'local' ? 'Local Music Studio options' : 'Local fallback options'}
+ </div>
+ <div className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,10rem),16rem))] gap-3">
+ <div>
+ <label htmlFor={`${idPrefix}-local-music-type`} className="block text-xs text-port-text-muted mb-1">Type</label>
+ <select
+ id={`${idPrefix}-local-music-type`}
+ value={type}
+ onChange={(e) => patchLocal({ type: e.target.value })}
+ className={inputClass}
+ >
+ {LOCAL_MUSIC_TYPES.map((t) => (
+ <option key={t} value={t}>{LOCAL_MUSIC_TYPE_LABELS[t] || t}</option>
+ ))}
+ </select>
+ </div>
+ {type === 'model' ? (
+ <div>
+ <label htmlFor={`${idPrefix}-local-music-engine`} className="block text-xs text-port-text-muted mb-1">Audio engine</label>
+ <select
+ id={`${idPrefix}-local-music-engine`}
+ value={engine}
+ onChange={(e) => patchLocal({ engine: e.target.value || null })}
+ className={inputClass}
+ >
+ <option value="">Auto (best ready engine)</option>
+ {engines.map((e) => (
+ <option key={e.id} value={e.id}>
+ {e.name || e.id}{e.lyrics ? ' (lyrics)' : ' (instrumental)'}{e.ready === false ? ' (not ready)' : ''}
+ </option>
+ ))}
+ {engine && !engines.some((e) => e.id === engine) && (
+ <option value={engine}>{engine} (configured)</option>
+ )}
+ </select>
+ </div>
+ ) : (
+ <div>
+ <label htmlFor={`${idPrefix}-local-music-language`} className="block text-xs text-port-text-muted mb-1">Code language</label>
+ <select
+ id={`${idPrefix}-local-music-language`}
+ value={language}
+ onChange={(e) => patchLocal({ language: e.target.value })}
+ className={inputClass}
+ >
+ {LOCAL_MUSIC_CODE_LANGUAGES.map((lang) => (
+ <option key={lang} value={lang}>{LOCAL_MUSIC_CODE_LANGUAGE_LABELS[lang] || lang}</option>
+ ))}
+ </select>
+ </div>
+ )}
+ </div>
+ <p className="text-[11px] text-port-text-muted">
+ {type === 'model'
+ ? 'Rendered on this machine by an audio model (e.g. ACE-Step or MiniMax for vocals, MusicGen for instrumental).'
+ : 'The music is written as code. SuperCollider renders offline in a container; Strudel and Tone.js are live-coding Web Audio environments.'}
+ </p>
+ </div>
+ )}
</div>
);
}
diff --git a/client/src/components/musicVideo/SongSourcePicker.test.jsx b/client/src/components/musicVideo/SongSourcePicker.test.jsx
new file mode 100644
index 0000000000..b61e5f3130
--- /dev/null
+++ b/client/src/components/musicVideo/SongSourcePicker.test.jsx
@@ -0,0 +1,96 @@
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { render, screen, fireEvent, cleanup, waitFor, act } from '@testing-library/react';
+
+const mockEngines = [
+ { id: 'acestep', name: 'ACE-Step', ready: true, lyrics: true },
+ { id: 'musicgen', name: 'MusicGen', ready: true, lyrics: false },
+];
+
+vi.mock('../../services/apiMusic.js', () => ({
+ listMusicEngines: vi.fn(async () => ({ engines: mockEngines })),
+}));
+
+import SongSourcePicker from './SongSourcePicker.jsx';
+
+afterEach(cleanup);
+
+describe('SongSourcePicker', () => {
+ it('renders Suno source without local options when fallback is off', () => {
+ const onChange = vi.fn();
+ render(
+ <SongSourcePicker
+ idPrefix="test"
+ songSource="suno"
+ localFallback={false}
+ localMusic={null}
+ onChange={onChange}
+ />
+ );
+
+ expect(screen.getByLabelText('Song source').value).toBe('suno');
+ expect(screen.getByLabelText('Render locally if Suno is unavailable')).toBeInTheDocument();
+ expect(screen.queryByLabelText('Type')).not.toBeInTheDocument();
+ });
+
+ it('renders local music options when songSource is local', async () => {
+ const onChange = vi.fn();
+ render(
+ <SongSourcePicker
+ idPrefix="test"
+ songSource="local"
+ localFallback={false}
+ localMusic={{ type: 'model', engine: '' }}
+ onChange={onChange}
+ />
+ );
+ await act(async () => {});
+
+ expect(screen.getByText('Local Music Studio options')).toBeInTheDocument();
+ expect(screen.getByLabelText('Type').value).toBe('model');
+ await waitFor(() => expect(screen.getByLabelText('Audio engine')).toBeInTheDocument());
+
+ fireEvent.change(screen.getByLabelText('Audio engine'), { target: { value: 'acestep' } });
+ expect(onChange).toHaveBeenCalledWith({
+ localMusic: { type: 'model', engine: 'acestep' },
+ });
+ });
+
+ it('switches to code language options when Type is code', async () => {
+ const onChange = vi.fn();
+ render(
+ <SongSourcePicker
+ idPrefix="test"
+ songSource="local"
+ localFallback={false}
+ localMusic={{ type: 'code', language: 'strudel' }}
+ onChange={onChange}
+ />
+ );
+ await act(async () => {});
+
+ expect(screen.getByLabelText('Type').value).toBe('code');
+ expect(screen.getByLabelText('Code language').value).toBe('strudel');
+
+ fireEvent.change(screen.getByLabelText('Code language'), { target: { value: 'supercollider' } });
+ expect(onChange).toHaveBeenCalledWith({
+ localMusic: { type: 'code', language: 'supercollider' },
+ });
+ });
+
+ it('shows fallback options when Suno has localFallback enabled', async () => {
+ const onChange = vi.fn();
+ render(
+ <SongSourcePicker
+ idPrefix="test"
+ songSource="suno"
+ localFallback={true}
+ localMusic={{ type: 'model', engine: '' }}
+ onChange={onChange}
+ />
+ );
+ await act(async () => {});
+
+ expect(screen.getByText('Local fallback options')).toBeInTheDocument();
+ expect(screen.getByLabelText('Type')).toBeInTheDocument();
+ });
+});
diff --git a/client/src/lib/musicVideoAutonomous.js b/client/src/lib/musicVideoAutonomous.js
index 7f440b7487..cef02714b2 100644
--- a/client/src/lib/musicVideoAutonomous.js
+++ b/client/src/lib/musicVideoAutonomous.js
@@ -8,6 +8,7 @@ import { llmStagesDraftFrom, llmStagesFromDraft } from './musicVideoAutomation.j
import {
AUTONOMOUS_DEFAULT_LIMITS, AUTONOMOUS_DEFAULT_TOOLS, AUTONOMOUS_LIVE_STATUSES, AUTONOMOUS_SONG_SOURCES, AUTONOMOUS_STAGES,
SUNO_MODEL_PATTERN,
+ normalizeLocalMusicOptions,
} from '../../../server/lib/musicVideoAutonomous.js';
export const AUTONOMOUS_SONG_SOURCE_LABELS = Object.freeze({
@@ -15,7 +16,19 @@ export const AUTONOMOUS_SONG_SOURCE_LABELS = Object.freeze({
local: 'Local engine (Music Studio)',
});
-export { AUTONOMOUS_AUTO_APPROVE_STAGES, AUTONOMOUS_CHECKPOINT_IDS, AUTONOMOUS_SONG_SOURCES, SUNO_LIMITS, SUNO_VOCAL_GENDERS, autonomousMedium } from '../../../server/lib/musicVideoAutonomous.js';
+export {
+ AUTONOMOUS_AUTO_APPROVE_STAGES,
+ AUTONOMOUS_CHECKPOINT_IDS,
+ AUTONOMOUS_SONG_SOURCES,
+ LOCAL_MUSIC_CODE_LANGUAGES,
+ LOCAL_MUSIC_CODE_LANGUAGE_LABELS,
+ LOCAL_MUSIC_TYPES,
+ LOCAL_MUSIC_TYPE_LABELS,
+ SUNO_LIMITS,
+ SUNO_VOCAL_GENDERS,
+ autonomousMedium,
+ normalizeLocalMusicOptions,
+} from '../../../server/lib/musicVideoAutonomous.js';
export const AUTONOMOUS_CHECKPOINT_LABELS = Object.freeze({
...Object.fromEntries(AUTONOMOUS_STAGES.map((stage) => [stage.id, stage.label])),
@@ -36,6 +49,11 @@ export const emptyAutonomousDraft = () => ({
authoring: { providerId: '', model: '', effort: '' },
songSource: AUTONOMOUS_SONG_SOURCES[0],
localFallback: false,
+ localMusic: {
+ type: 'model',
+ engine: '',
+ language: 'strudel',
+ },
instrumental: false,
tools: [...AUTONOMOUS_DEFAULT_TOOLS],
models: {},
@@ -78,6 +96,7 @@ 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 localMusic = (draft.songSource === 'local' || draft.localFallback) ? normalizeLocalMusicOptions(draft.localMusic) : null;
const llmStages = llmStagesFromDraft(draft.llmStages);
const models = Object.fromEntries(Object.entries(draft.models || {})
.filter(([id, value]) => draft.tools.includes(id) && typeof value === 'string' && value.trim())
@@ -91,6 +110,7 @@ export function autonomousRequestFromDraft(draft, { providerId, model, effort }
} } : {}),
songSource: draft.songSource,
localFallback: draft.songSource === 'suno' && draft.localFallback === true,
+ ...(localMusic ? { localMusic } : {}),
instrumental: draft.instrumental === true,
...(suno ? { suno } : {}),
tools: draft.tools,
@@ -178,6 +198,11 @@ export function autopilotDraftFromParams(params) {
authoring: { ...base.authoring, ...(p.authoring || {}) },
songSource: AUTONOMOUS_SONG_SOURCES.includes(p.songSource) ? p.songSource : base.songSource,
localFallback: p.localFallback === true,
+ localMusic: {
+ type: p.localMusic?.type || 'model',
+ engine: p.localMusic?.engine || '',
+ language: p.localMusic?.language || 'strudel',
+ },
instrumental: p.instrumental === true,
tools: Array.isArray(p.tools) ? [...p.tools] : base.tools,
models: { ...(p.models || {}) },
@@ -202,6 +227,7 @@ export function autopilotParamsFromDraft(draft, saved, { providerId, model, effo
return {
...kept,
...request,
+ localMusic: request.localMusic || null,
models: request.models || {},
authoring: request.authoring || null,
// The params are replaced whole on save, so an unpinned map and an off toggle are explicit.
diff --git a/server/lib/musicVideoAutonomous.js b/server/lib/musicVideoAutonomous.js
index 2304bdc8ce..da1bc9ee52 100644
--- a/server/lib/musicVideoAutonomous.js
+++ b/server/lib/musicVideoAutonomous.js
@@ -51,6 +51,37 @@ export const AUTONOMOUS_CHECKPOINT_IDS = Object.freeze([...AUTONOMOUS_STAGE_CHEC
// and credits) or the on-device Music Designer engines (free, no browser).
export const AUTONOMOUS_SONG_SOURCES = Object.freeze(['suno', 'local']);
+// Local Music Studio options: audio models or generative code.
+export const LOCAL_MUSIC_TYPES = Object.freeze(['model', 'code']);
+export const LOCAL_MUSIC_TYPE_LABELS = Object.freeze({
+ model: 'Audio model',
+ code: 'Code',
+});
+export const LOCAL_MUSIC_CODE_LANGUAGES = Object.freeze(['strudel', 'tonejs', 'supercollider']);
+export const LOCAL_MUSIC_CODE_LANGUAGE_LABELS = Object.freeze({
+ strudel: 'Strudel',
+ tonejs: 'Tone.js',
+ supercollider: 'SuperCollider',
+});
+
+/**
+ * The brief's local Music Studio options: model (with optional engine pin) or
+ * code (with chosen language). Returns null when no option is configured.
+ */
+export function normalizeLocalMusicOptions(raw) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const hasType = LOCAL_MUSIC_TYPES.includes(raw.type);
+ const type = hasType ? raw.type : (raw.language ? 'code' : 'model');
+ const engine = isStr(raw.engine) ? clean(raw.engine, 64) || null : null;
+ const language = isStr(raw.language) && LOCAL_MUSIC_CODE_LANGUAGES.includes(raw.language) ? raw.language : null;
+ if (!hasType && !engine && !language) return null;
+ return {
+ type,
+ ...(engine ? { engine } : {}),
+ ...(type === 'code' ? { language: language || 'strudel' } : {}),
+ };
+}
+
// 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']);
@@ -150,6 +181,7 @@ function normalizeAutonomousSettings(raw = {}) {
// 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,
+ localMusic: normalizeLocalMusicOptions(raw.localMusic),
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 27068bd18c..c896461414 100644
--- a/server/lib/musicVideoAutonomous.test.js
+++ b/server/lib/musicVideoAutonomous.test.js
@@ -7,6 +7,7 @@ import {
ideaToPrompt,
normalizeAutonomousBrief,
normalizeAutopilotParams,
+ normalizeLocalMusicOptions,
pickBrainIdea,
sunoSongFields,
sunoSongIdsFromHrefs,
@@ -185,3 +186,38 @@ describe('scheduled-task params', () => {
expect(sanitizeTaskMetadata({ musicVideoAutopilot: { moodBoardId: ' ' } }).musicVideoAutopilot.moodBoardId).toBeNull();
});
});
+
+describe('normalizeLocalMusicOptions', () => {
+ it('normalizes local music options for audio models and code', () => {
+ expect(normalizeLocalMusicOptions(null)).toBeNull();
+ expect(normalizeLocalMusicOptions(undefined)).toBeNull();
+ expect(normalizeLocalMusicOptions('invalid')).toBeNull();
+ expect(normalizeLocalMusicOptions({})).toBeNull();
+ expect(normalizeLocalMusicOptions({ type: 'model' })).toEqual({ type: 'model' });
+ expect(normalizeLocalMusicOptions({ type: 'model', engine: 'acestep' })).toEqual({ type: 'model', engine: 'acestep' });
+ expect(normalizeLocalMusicOptions({ type: 'model', engine: ' ' })).toEqual({ type: 'model' });
+ expect(normalizeLocalMusicOptions({ type: 'code' })).toEqual({ type: 'code', language: 'strudel' });
+ expect(normalizeLocalMusicOptions({ type: 'code', language: 'supercollider' })).toEqual({ type: 'code', language: 'supercollider' });
+ expect(normalizeLocalMusicOptions({ type: 'code', language: 'unknown' })).toEqual({ type: 'code', language: 'strudel' });
+ expect(normalizeLocalMusicOptions({ language: 'tonejs' })).toEqual({ type: 'code', language: 'tonejs' });
+ });
+
+ it('validates localMusic in autonomous start and resume schemas', () => {
+ const startValid = musicVideoAutonomousStartSchema.parse({
+ prompt: 'test prompt',
+ songSource: 'local',
+ localMusic: { type: 'model', engine: 'acestep' },
+ });
+ expect(startValid.localMusic).toEqual({ type: 'model', engine: 'acestep' });
+
+ const resumeValid = musicVideoAutonomousResumeSchema.parse({
+ localMusic: { type: 'code', language: 'supercollider' },
+ });
+ expect(resumeValid.localMusic).toEqual({ type: 'code', language: 'supercollider' });
+
+ expect(() => musicVideoAutonomousStartSchema.parse({
+ prompt: 'test prompt',
+ localMusic: { type: 'invalid-type' },
+ })).toThrow();
+ });
+});
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 447819cf9f..02c6dd90f7 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -39,6 +39,8 @@ import {
AUTONOMOUS_ORIGINS,
AUTONOMOUS_PROMPT_MAX,
AUTONOMOUS_SONG_SOURCES,
+ LOCAL_MUSIC_CODE_LANGUAGES,
+ LOCAL_MUSIC_TYPES,
SUNO_LIMITS,
SUNO_MODEL_PATTERN,
SUNO_VOCAL_GENDERS,
@@ -774,6 +776,13 @@ const musicVideoSunoOptionsSchema = z.object({
maxMode: z.boolean().nullable().optional(),
}).strict();
+// Local Music Studio options: model (with optional engine) or code (with chosen language).
+export const musicVideoLocalMusicOptionsSchema = z.object({
+ type: z.enum(LOCAL_MUSIC_TYPES).optional(),
+ engine: z.string().trim().max(64).nullable().optional(),
+ language: z.enum(LOCAL_MUSIC_CODE_LANGUAGES).nullable().optional(),
+}).strict();
+
// A provider/model/effort pin for a Music Video text stage. Effort is the union
// of every accepted level; the runner clamps it to the chosen provider's ladder.
export const musicVideoLlmSchema = z.object({
@@ -807,6 +816,7 @@ export const musicVideoAutonomousStartSchema = z.object({
mediaMode: z.enum(MUSIC_VIDEO_MEDIA_MODES).optional(),
songSource: z.enum(AUTONOMOUS_SONG_SOURCES).optional(),
localFallback: z.boolean().optional(),
+ localMusic: musicVideoLocalMusicOptionsSchema.nullable().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(),
@@ -848,6 +858,8 @@ export const musicVideoAutonomousResumeSchema = z.object({
style: z.string().max(AUTONOMOUS_PROMPT_MAX).optional(),
// Patch the brief's Suno options, key by key (null clears one).
suno: musicVideoSunoOptionsSchema.optional(),
+ // Patch the brief's local Music Studio options.
+ localMusic: musicVideoLocalMusicOptionsSchema.nullable().optional(),
// At the song checkpoint: discard the song and generate a new one.
retakeSong: z.boolean().optional(),
// Replace the brief's auto-approve grant ("auto-approve the rest").
diff --git a/server/services/musicVideo/autonomousLocalSong.js b/server/services/musicVideo/autonomousLocalSong.js
index 16431cbdf7..4cb1e61e16 100644
--- a/server/services/musicVideo/autonomousLocalSong.js
+++ b/server/services/musicVideo/autonomousLocalSong.js
@@ -17,6 +17,7 @@
* the flow is unit-testable without a GPU.
*/
+import { randomUUID } from 'crypto';
import { ServerError } from '../../lib/errorHandler.js';
import { sleep as defaultSleep } from '../../lib/fileCore.js';
import { trimTo } from '../../lib/textUtils.js';
@@ -37,6 +38,10 @@ 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),
+ writeMusicCode: async (args) => (await import('../musicCode.js')).writeMusicCode(args),
+ renderSuperColliderSource: async (args) => (await import('../superColliderRender.js')).renderSuperColliderSource(args),
+ saveSuperColliderTakeToTrack: async (args) => (await import('../musicCode.js')).saveSuperColliderTakeToTrack(args),
+ getSuperColliderStatus: async () => (await import('../superColliderRuntime.js')).getSuperColliderStatus(),
getJob: async (id) => (await import('../mediaJobQueue/index.js')).getJob(id),
getTrack: async (id) => (await import('../tracks/index.js')).getTrack(id),
cancelJob: async (id) => (await import('../mediaJobQueue/index.js')).cancelJob(id),
@@ -69,10 +74,28 @@ const defaults = {
/**
* 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.
+ * When `engineId` is specified, verifies it exists, is healthy, and can sing lyrics.
*/
-async function pickLocalSongEngine({ instrumental }, deps = {}) {
+async function pickLocalSongEngine({ instrumental, engineId = null }, deps = {}) {
const { listEngines, isEngineHealthy } = { ...defaults, ...deps };
- const engines = Object.values(await listEngines());
+ const rawEngines = await listEngines();
+ const engines = Array.isArray(rawEngines) ? rawEngines : Object.values(rawEngines || {});
+
+ if (engineId) {
+ const specified = engines.find((e) => e.id === engineId);
+ if (!specified) {
+ throw fail(400, 'LOCAL_SONG_UNKNOWN_ENGINE', `Local music engine '${engineId}' is not installed or recognized`);
+ }
+ const healthy = await isEngineHealthy(specified.id);
+ if (!healthy) {
+ throw fail(409, 'LOCAL_SONG_ENGINE_UNHEALTHY', `Selected local music engine '${specified.name || specified.id}' is not ready — check its install in Music Studio`);
+ }
+ if (!instrumental && specified.lyrics !== true) {
+ throw fail(409, 'LOCAL_SONG_ENGINE_NO_LYRICS', `Selected local music engine '${specified.name || specified.id}' cannot sing lyrics — make the song instrumental or select a lyric-capable engine (e.g. ACE-Step)`);
+ }
+ return specified;
+ }
+
const healthy = [];
for (const engine of engines) {
if (await isEngineHealthy(engine.id)) healthy.push(engine);
@@ -96,7 +119,9 @@ const durationFor = (engine) => (engine.autoDuration
* 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 = {}) {
+export async function generateLocalSong({
+ trackId, title, prompt, lyrics = '', instrumental = false, jobId = null, localMusic = null, onSubmitted,
+}, overrides = {}) {
const deps = { ...defaults, ...overrides };
const { timeoutMs = LOCAL_SONG_TIMEOUT_MS } = overrides;
@@ -104,9 +129,40 @@ export async function generateLocalSong({ trackId, title, prompt, lyrics = '', i
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 };
+ if (localMusic?.type === 'code') {
+ if (localMusic.language === 'supercollider') {
+ const status = await deps.getSuperColliderStatus().catch(() => ({ ready: false, message: 'Status check failed' }));
+ if (!status?.ready) {
+ throw fail(409, 'LOCAL_SONG_SUPERCOLLIDER_UNAVAILABLE', `SuperCollider is not ready: ${status?.message || 'runtime unavailable'} — check its install in Music Studio`);
+ }
+ const codeJobId = jobId || `sc-${randomUUID()}`;
+ await onSubmitted?.(codeJobId);
+ const codeResult = await deps.writeMusicCode({
+ description: prompt,
+ lyrics: instrumental ? '' : lyrics,
+ language: 'supercollider',
+ });
+ const preview = await deps.renderSuperColliderSource({
+ jobId: codeJobId,
+ source: codeResult.code,
+ durationSec: Math.min(LOCAL_SONG_TARGET_SEC, 120),
+ seed: Math.floor(Math.random() * 100000),
+ });
+ const saved = await deps.saveSuperColliderTakeToTrack({
+ trackId,
+ jobId: preview.jobId,
+ prompt,
+ title,
+ });
+ return { trackId, filename: saved.filename, jobId: codeJobId };
+ }
+ throw fail(400, 'LOCAL_SONG_BROWSER_CODE_ENGINE',
+ `${localMusic.language === 'tonejs' ? 'Tone.js' : 'Strudel'} music code requires an interactive browser session to synthesize audio — select SuperCollider or an Audio Model for autonomous runs`);
+ }
+
let job = jobId ? await deps.getJob(jobId) : null;
if (!job || job.status === 'failed' || job.status === 'canceled') {
- const engine = await pickLocalSongEngine({ instrumental }, deps);
+ const engine = await pickLocalSongEngine({ instrumental, engineId: localMusic?.engine || null }, deps);
const queued = await deps.queueGeneration({
prompt: trimTo(prompt, 8000),
...(instrumental || !lyrics ? {} : { lyrics: trimTo(lyrics, 20000) }),
diff --git a/server/services/musicVideo/autonomousLocalSong.test.js b/server/services/musicVideo/autonomousLocalSong.test.js
index 282fb9a321..142f66b3df 100644
--- a/server/services/musicVideo/autonomousLocalSong.test.js
+++ b/server/services/musicVideo/autonomousLocalSong.test.js
@@ -28,6 +28,10 @@ function harness({ healthy = ['musicgen', 'acestep'], tracks = {}, jobs = {}, wa
listEngines: async () => ENGINES,
isEngineHealthy: async (id) => healthy.includes(id),
queueGeneration: vi.fn(async () => ({ jobId: 'job-1', status: 'queued' })),
+ writeMusicCode: vi.fn(async () => ({ code: 'SynthDef(\\pad, {}).add;', language: 'supercollider' })),
+ renderSuperColliderSource: vi.fn(async ({ jobId }) => ({ jobId, wavPath: 'sc.wav' })),
+ saveSuperColliderTakeToTrack: vi.fn(async ({ trackId }) => ({ track: { id: trackId }, filename: 'sc.wav', durationSec: 30 })),
+ getSuperColliderStatus: vi.fn(async () => ({ ready: true })),
getJob: async (id) => state.jobs[id] || null,
getTrack: async (id) => state.tracks[id] || null,
cancelJob: vi.fn(async () => true),
@@ -50,6 +54,43 @@ describe('engine choice', () => {
expect(instrumental.deps.queueGeneration.mock.calls[0][0].engine).toBe('musicgen');
});
+ it('uses a pinned engine when valid and healthy', async () => {
+ const pinned = harness({ healthy: ['musicgen', 'acestep', 'minimax'] });
+ await generateLocalSong({ ...song, localMusic: { type: 'model', engine: 'minimax' } }, pinned.deps);
+ expect(pinned.deps.queueGeneration.mock.calls[0][0].engine).toBe('minimax');
+ });
+
+ it('rejects an unknown, unhealthy, or lyric-incompatible pinned engine', async () => {
+ const { deps } = harness({ healthy: ['musicgen', 'acestep'] });
+ await expect(generateLocalSong({ ...song, localMusic: { type: 'model', engine: 'nonexistent' } }, deps))
+ .rejects.toMatchObject({ code: 'LOCAL_SONG_UNKNOWN_ENGINE' });
+ await expect(generateLocalSong({ ...song, localMusic: { type: 'model', engine: 'minimax' } }, deps))
+ .rejects.toMatchObject({ code: 'LOCAL_SONG_ENGINE_UNHEALTHY' });
+ await expect(generateLocalSong({ ...song, localMusic: { type: 'model', engine: 'musicgen' } }, deps))
+ .rejects.toMatchObject({ code: 'LOCAL_SONG_ENGINE_NO_LYRICS' });
+ });
+
+ it('renders music via SuperCollider code and saves the take', async () => {
+ const { deps } = harness();
+ const onSubmitted = vi.fn();
+ const out = await generateLocalSong({ ...song, localMusic: { type: 'code', language: 'supercollider' }, onSubmitted }, deps);
+ expect(deps.writeMusicCode).toHaveBeenCalledWith({
+ description: 'synthwave', lyrics: '[verse]\nrain', language: 'supercollider',
+ });
+ expect(deps.renderSuperColliderSource).toHaveBeenCalled();
+ expect(deps.saveSuperColliderTakeToTrack).toHaveBeenCalled();
+ expect(out.filename).toBe('sc.wav');
+ expect(onSubmitted).toHaveBeenCalledWith(expect.stringMatching(/^sc-/));
+ });
+
+ it('rejects browser-only code languages in unattended run', async () => {
+ const { deps } = harness();
+ await expect(generateLocalSong({ ...song, localMusic: { type: 'code', language: 'strudel' } }, deps))
+ .rejects.toMatchObject({ code: 'LOCAL_SONG_BROWSER_CODE_ENGINE' });
+ await expect(generateLocalSong({ ...song, localMusic: { type: 'code', language: 'tonejs' } }, deps))
+ .rejects.toMatchObject({ code: 'LOCAL_SONG_BROWSER_CODE_ENGINE' });
+ });
+
it('names what is missing instead of rendering the wrong thing', async () => {
const instrumentalOnly = harness({ healthy: ['musicgen'] });
await expect(generateLocalSong(song, instrumentalOnly.deps)).rejects.toMatchObject({ code: 'LOCAL_SONG_NO_ENGINE', message: expect.stringContaining('sing lyrics') });
diff --git a/server/services/musicVideo/autonomousService.js b/server/services/musicVideo/autonomousService.js
index 1fddef1205..6a8df1013c 100644
--- a/server/services/musicVideo/autonomousService.js
+++ b/server/services/musicVideo/autonomousService.js
@@ -55,6 +55,7 @@ import {
nextAutonomousStage,
normalizeAutoApprove,
normalizeAutonomousBrief,
+ normalizeLocalMusicOptions,
normalizeSunoOptions,
sunoSongFields,
} from '../../lib/musicVideoAutonomous.js';
@@ -245,6 +246,7 @@ async function localSong({ project, run, save }) {
}
await deps.generateLocalSong({
trackId, title, prompt, lyrics, instrumental: run.brief.instrumental, jobId: run.output.localSongJobId,
+ localMusic: run.brief.localMusic,
onSubmitted: async (jobId) => {
await save({ output: { localSongJobId: jobId } });
// Stop/cancel cancel the job they find on the record; one that landed
@@ -595,9 +597,10 @@ export async function resumeAutonomousVideo(projectId, edits = {}, { autoApprove
const stage = retake ? 'song' : r.stage;
return {
status: 'running', awaiting: null, error: null, errorCode: null, processId: PROCESS_ID,
- ...(edits.suno || grant ? { brief: {
+ ...(edits.suno || edits.localMusic !== undefined || grant ? { brief: {
...r.brief,
...(edits.suno ? { suno: normalizeSunoOptions({ ...r.brief.suno, ...edits.suno }) } : {}),
+ ...(edits.localMusic !== undefined ? { localMusic: normalizeLocalMusicOptions(edits.localMusic ? { ...r.brief.localMusic, ...edits.localMusic } : null) } : {}),
...(grant || {}),
} } : {}),
output: {