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 instrumental music generation controls (#4475)

[._.]/ Adam Eivyb239886b03ac
diff --git a/.changelog/next/added-instrumental-music-generation.md b/.changelog/next/added-instrumental-music-generation.md
new file mode 100644
index 0000000000..69ab1c803d
--- /dev/null
+++ b/.changelog/next/added-instrumental-music-generation.md
@@ -0,0 +1,2 @@
+- Music generation now offers an instrumental-only option that leaves saved track lyrics intact.
+- Music Designer now creates MiniMax-ready structured captions with tempo, meter, vocal, production, and section-by-section arrangement guidance.
diff --git a/client/src/components/music/MusicDesigner.jsx b/client/src/components/music/MusicDesigner.jsx
index 7833c13b84..80210c9c6e 100644
--- a/client/src/components/music/MusicDesigner.jsx
+++ b/client/src/components/music/MusicDesigner.jsx
@@ -49,13 +49,11 @@ const FIRST_STEP = STEP_IDS[0];
const DRAFT_TITLE = 'Untitled music draft';
const ACTIVE_DRAFT_KEY = 'portos.musicDesigner.activeDraft';
-// Display-only mirrors of the shipped meta-prompts in
-// `server/services/musicDesigner.js`. They are rendered as placeholder text so
-// the user can see what they're overriding; the SERVER is the authority — an
-// empty override field sends no `template` at all and the server falls back to
-// its own constant, so drift here is cosmetic and can never change what runs.
-const DESCRIBE_PLACEHOLDER = 'Describe the given musical reference and description in richer detail in English, focusing primarily on the sound, instruments, feel, and the overall atmosphere. Also briefly describe the composition, instrumentation, beats, lyrical or instrumental style (maybe it doesn\'t have lyrics), and aesthetic. Keep it concise and genre-focused rather than overly technical.';
-const LYRICS_PLACEHOLDER = 'Write original song lyrics that fit the musical description below. Use the section syntax the audio engine expects: a bracketed section tag alone on its line ([verse], [chorus], [bridge], [outro]) with that section\'s lines beneath it. Match the mood, genre, energy, and vocal style implied by the description, and keep the phrasing singable. Keep the lyrics original (do not reproduce copyrighted lyrics verbatim).';
+// Display-only summaries of the shipped meta-prompts in
+// `server/services/musicDesigner.js`. The SERVER is the authority — an empty
+// override sends no `template` and uses the complete shipped instruction.
+const DESCRIBE_PLACEHOLDER = 'Rewrite the musical reference into a detailed, generation-oriented structured caption in English. Preserve explicit requirements and exclusions while developing genre and subgenres, emotional arc, imagery, sonics, production character, core instruments, and spatial feel. Describe approximate tempo, meter or time signature, rhythmic subdivision, and groove when they matter. Use exact BPM, key, scale, or time signature only when deliberately requested. State the vocal plan explicitly; for instrumental music, rule out vocals and name the lead melodic instrument. Treat the arrangement as a continuous section-by-section timeline with plausible entrances, exits, changes, and transitions. Keep lyric words out of the caption.';
+const LYRICS_PLACEHOLDER = 'Write original, singable song lyrics that fit the musical description. Put every bracketed section tag alone on its own line, using useful tags such as [intro], [verse], [pre-chorus], [chorus], [post-chorus], [bridge], [instrumental], [solo], and [outro], with words beginning on the following line. Build enough sections for the intended song length. Keep tempo, meter, key, arrangement, and production instructions in the separate musical description.';
const FIELD_CLASS = 'w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white';
const LABEL_CLASS = 'mb-1 block text-xs uppercase tracking-wider text-gray-500';
@@ -281,7 +279,7 @@ export default function MusicDesigner() {
<div>
<h2 className="text-lg font-semibold text-white">Design a tune</h2>
<p className="text-sm text-gray-400">
- Start from a reference or a vibe. AI drafts the musical description and the lyrics — you edit both before anything is rendered.
+ Start from a reference or a vibe. AI drafts a structured musical caption and optional lyrics — you edit both before anything is rendered.
</p>
</div>
@@ -319,7 +317,7 @@ export default function MusicDesigner() {
onChange={(event) => setConceptGuidance(event.target.value)}
disabled={draftLoading}
maxLength={4000}
- placeholder="Keep it under 100 BPM, no vocals in the intro…"
+ placeholder="90–96 BPM, 6/8 meter, D minor, instrumental only with a cello lead…"
className={FIELD_CLASS}
/>
</label>
@@ -342,7 +340,7 @@ export default function MusicDesigner() {
{advancedOpen && (
<div className="space-y-3 border-t border-port-border p-3">
<p className="text-xs text-gray-500">
- Leave a field blank to use the shipped instruction shown in it.
+ Leave a field blank to use the complete shipped instruction summarized by its placeholder.
</p>
<div>
<div className="flex items-center justify-between gap-2">
@@ -425,11 +423,19 @@ export default function MusicDesigner() {
disabled={draftLoading}
rows={8}
maxLength={8000}
- placeholder="Warm instrumental soul, relaxed pocket, Rhodes piano, 92 BPM…"
+ placeholder={'Global Metadata\nBasic Attributes: 92 BPM, 6/8 meter, warm instrumental soul…\n\nVocal Details\nInstrumental only; the Rhodes carries the lead melody…\n\nArrangement\nIntro: sparse keys enter first…'}
className={FIELD_CLASS}
/>
</label>
- <p className="text-xs text-gray-500">This is what conditions the render — edit it freely.</p>
+ <div className="rounded border border-port-border bg-port-bg/60 p-3 text-xs text-gray-400">
+ <p className="mb-2 font-medium text-gray-300">MiniMax structured caption</p>
+ <ul className="list-disc space-y-1 pl-4">
+ <li><span className="text-gray-300">Global Metadata</span> — genre, tempo/BPM, meter or time signature, groove, emotional arc, imagery, and mix profile.</li>
+ <li><span className="text-gray-300">Vocal Details</span> — explicit vocal performance, or “instrumental” plus the lead melodic instrument or texture.</li>
+ <li><span className="text-gray-300">Arrangement</span> — a section-by-section timeline of entrances, exits, transitions, texture, and energy.</li>
+ </ul>
+ <p className="mt-2 text-gray-500">Use exact BPM, key, scale, or meter only when you mean it. This entire caption conditions the render.</p>
+ </div>
<div className="flex flex-wrap gap-2">
<button
type="button"
@@ -491,11 +497,12 @@ export default function MusicDesigner() {
</div>
<div className="rounded border border-port-border bg-port-bg/60 p-3 text-xs text-gray-400">
<p className="mb-2 font-medium text-gray-300">Manual composition structure</p>
- <p className="mb-2">Put one section tag on its own line, then its singable lines. A useful arc is: intro → verse → pre-chorus → chorus → verse 2 → chorus → bridge → final chorus → outro.</p>
+ <p className="mb-2">Put one section tag on its own line, then begin its singable words on the next line. A useful arc is: intro → verse → pre-chorus → chorus → verse 2 → chorus → bridge → final chorus → outro.</p>
<ul className="mb-3 list-disc space-y-1 pl-4">
<li>Use 4–8 short lines for a verse and 2–4 lines for a pre-chorus or bridge.</li>
<li>Give the chorus a repeated hook; repeat the tag when the chorus returns.</li>
- <li>Leave a blank line between sections and keep tags lowercase, such as <code className="text-gray-300">[verse]</code> and <code className="text-gray-300">[chorus]</code>.</li>
+ <li>Use tags such as <code className="text-gray-300">[instrumental]</code> and <code className="text-gray-300">[solo]</code> for wordless sections; keep tempo, meter, and production direction in the description.</li>
+ <li>Include enough sections for the intended duration—MiniMax can end early when the lyric structure runs out.</li>
</ul>
<pre className="overflow-x-auto rounded bg-port-bg p-2 font-mono text-[11px] text-gray-300">{`[verse]\nShort image, short line\nA second line to sing\n\n[pre-chorus]\nBuild the thought\nTurn toward the hook\n\n[chorus]\nA repeatable hook\nA repeatable hook`}</pre>
</div>
@@ -514,8 +521,13 @@ export default function MusicDesigner() {
/>
</label>
<button type="button" onClick={() => { saveDraft({ prompt: description.trim(), lyrics: lyrics.trim() }); goTo('render'); }} disabled={busy || !draftReady} className={PRIMARY_BTN}>
- {lyrics.trim() ? 'Next: render' : 'Skip — make it instrumental'}
+ {lyrics.trim() ? 'Next: render' : 'Continue without lyrics'}
</button>
+ {!lyrics.trim() && (
+ <p className="text-xs text-gray-500">
+ On the render step, enable Instrumental only to prohibit wordless or background vocals too.
+ </p>
+ )}
</div>
)}
diff --git a/client/src/components/music/MusicDesigner.test.jsx b/client/src/components/music/MusicDesigner.test.jsx
index 0bc0bb44ed..14e9d29157 100644
--- a/client/src/components/music/MusicDesigner.test.jsx
+++ b/client/src/components/music/MusicDesigner.test.jsx
@@ -176,6 +176,8 @@ describe('<MusicDesigner>', () => {
const box = screen.getByLabelText(/music description/i);
expect(box).toHaveValue('Lush pads over a broken beat.');
+ expect(screen.getByText(/MiniMax structured caption/i)).toBeInTheDocument();
+ expect(screen.getByText(/meter or time signature/i)).toBeInTheDocument();
fireEvent.change(box, { target: { value: 'My own words.' } });
expect(box).toHaveValue('My own words.');
await waitFor(() => expect(api.updateTrack).toHaveBeenCalledWith(
@@ -234,7 +236,7 @@ describe('<MusicDesigner>', () => {
expect(screen.getByTestId('location')).toHaveTextContent('/music/generate/lyrics');
});
- it('is skippable — an instrumental reaches the generator with empty lyrics', async () => {
+ it('lets the user continue without lyrics while leaving vocal intent for the render step', async () => {
api.describeMusic.mockResolvedValue({ description: 'Lush pads over a broken beat.', llm: {} });
renderAt('/music/generate/concept');
@@ -243,7 +245,8 @@ describe('<MusicDesigner>', () => {
await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent('/music/generate/description'));
fireEvent.click(screen.getByRole('button', { name: /next: lyrics/i }));
- fireEvent.click(screen.getByRole('button', { name: /skip — make it instrumental/i }));
+ expect(screen.getByText(/enable instrumental only to prohibit wordless or background vocals/i)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: /continue without lyrics/i }));
const panel = await screen.findByTestId('gen-panel');
expect(panel).toHaveAttribute('data-prompt', 'Lush pads over a broken beat.');
diff --git a/client/src/components/music/MusicGenPanel.jsx b/client/src/components/music/MusicGenPanel.jsx
index b8d1a16969..e6eee80a88 100644
--- a/client/src/components/music/MusicGenPanel.jsx
+++ b/client/src/components/music/MusicGenPanel.jsx
@@ -4,8 +4,9 @@
* Lets the user pick a generation engine (MusicGen / AudioLDM2 / ACE-Step /
* MiniMax Music 3 and MiniMax Music 3 MLX), pick or install a model, and Generate
* audio from the track's prompt (+ lyrics for lyric-aware engines like ACE-Step
- * and MiniMax Music 3). On success the parent receives the updated track (the
- * server attaches the audio + gen metadata).
+ * and MiniMax Music 3), with an explicit instrumental-only override for every
+ * engine. On success the parent receives the updated track (the server attaches
+ * the audio + gen metadata).
*
* Engines that aren't provisioned (their opt-in venv is missing) are shown with
* an in-app install action and the Generate button is gated — mirroring the FLUX.2
@@ -93,6 +94,9 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
const [modelId, setModelId] = useState('');
const [durationSec, setDurationSec] = useState(null);
const [durationMode, setDurationMode] = useState('auto');
+ // Lyric text and vocal intent are independent: a lyricless prompt can still
+ // ask for wordless vocals, so instrumental mode is always an explicit choice.
+ const [instrumentalOnly, setInstrumentalOnly] = useState(false);
const [generating, setGenerating] = useState(false);
const [activeJob, setActiveJob] = useState(null);
const [activeJobId, setActiveJobId] = useState(null);
@@ -120,6 +124,9 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
if (found) {
setActiveJob(found);
setActiveJobId(found.id);
+ if (typeof found.params?.musicStudio?.instrumentalOnly === 'boolean') {
+ setInstrumentalOnly(found.params.musicStudio.instrumentalOnly);
+ }
setGenerating(true);
} else if (progress.status !== 'completed') {
setActiveJob(null);
@@ -199,12 +206,18 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
? engine.modelReadyById[selectedModelId] === true
: engine.modelReady === true;
const autoDurationAvailable = supportsAutoDuration(engine);
- const lyricDuration = useMemo(() => analyzeMusicLyrics(lyrics, {
+ const hasLyrics = typeof lyrics === 'string' && lyrics.trim().length > 0;
+ const conditioningLyrics = engine?.lyrics && !instrumentalOnly ? lyrics : '';
+ const lyricDuration = useMemo(() => analyzeMusicLyrics(conditioningLyrics, {
minDurationSec: Math.max(60, engine?.defaultDurationSec || 60),
maxDurationSec: engine?.maxDurationSec || 300,
- }), [lyrics, engine?.defaultDurationSec, engine?.maxDurationSec]);
+ }), [conditioningLyrics, engine?.defaultDurationSec, engine?.maxDurationSec]);
const usingAutoDuration = autoDurationAvailable && durationMode === 'auto';
+ // A render-level choice must not leak into another track in the master-detail
+ // editor. Each destination starts in the backward-compatible vocal-capable mode.
+ useEffect(() => { setInstrumentalOnly(false); }, [track?.id]);
+
// Remix: seed the engine / model / duration from a past render. Keyed on
// `remix.nonce` (bumped per Remix click) so re-clicking the SAME render
// re-applies even when its values are unchanged. An uploaded render carries no
@@ -216,6 +229,9 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
if (!remix) return;
if (remix.engineId) setEngineId(remix.engineId);
if (remix.modelId) setModelId(remix.modelId);
+ // Legacy/uploaded renders have no explicit mode. Do not infer vocal intent
+ // from an empty lyric snapshot; start those remixes vocal-capable.
+ setInstrumentalOnly(remix.instrumentalOnly === true);
if (remix.durationSec != null) {
setDurationSec(remix.durationSec);
// Remix means "recreate this take"; preserve its exact manual ceiling.
@@ -298,10 +314,15 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
setGenerating(true);
const body = {
prompt: prompt.trim(),
- lyrics: engine.lyrics ? (lyrics || '') : '',
engine: engine.id,
modelId: selectedModelId,
+ instrumentalOnly,
};
+ if (engine.lyrics) {
+ // Keep authored lyrics available to the track record even when the server
+ // deliberately excludes them from this render's engine conditioning.
+ body.lyrics = lyrics || '';
+ }
if (track?.id) body.trackId = track.id;
else {
body.title = title.trim();
@@ -320,7 +341,12 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
onGenerated?.(res.track);
toast.success('Track generated');
} else if (res?.jobId) {
- setActiveJob({ id: res.jobId, status: res.status, queuedAt: new Date().toISOString(), params: { musicStudio: { trackId: track?.id || null } } });
+ setActiveJob({
+ id: res.jobId,
+ status: res.status,
+ queuedAt: new Date().toISOString(),
+ params: { musicStudio: { trackId: track?.id || null, instrumentalOnly } },
+ });
setActiveJobId(res.jobId);
} else {
setGenerating(false);
@@ -495,9 +521,29 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
{setupProgress ? (
<p className="truncate text-[11px] text-gray-500">{setupProgress.message}</p>
) : null}
- {engine?.lyrics ? (
- <p className="text-[11px] text-gray-500">This engine uses the track’s lyrics as conditioning.</p>
- ) : null}
+ <div className="rounded-lg border border-port-border bg-port-bg px-3 py-2">
+ <div className="flex items-center gap-2">
+ <input
+ id="musicgen-instrumental-only"
+ type="checkbox"
+ checked={instrumentalOnly}
+ onChange={(event) => setInstrumentalOnly(event.target.checked)}
+ disabled={isGenerating}
+ aria-describedby="musicgen-instrumental-only-hint"
+ className="h-4 w-4 accent-port-accent"
+ />
+ <label htmlFor="musicgen-instrumental-only" className="text-sm font-medium text-gray-300">
+ Instrumental only
+ </label>
+ </div>
+ <p id="musicgen-instrumental-only-hint" className="mt-1 text-[11px] text-gray-500">
+ {instrumentalOnly
+ ? `An explicit no-vocals instruction will be added${hasLyrics ? '; saved lyrics will not condition this render' : ''}.`
+ : engine?.lyrics && hasLyrics
+ ? 'This engine will use the track’s lyrics as conditioning.'
+ : 'No lyric text will condition this render, but vocals may still follow the prompt unless instrumental mode is enabled.'}
+ </p>
+ </div>
<div className="flex items-center gap-2">
<button
diff --git a/client/src/components/music/MusicGenPanel.test.jsx b/client/src/components/music/MusicGenPanel.test.jsx
index 513413908f..b6973d0a4f 100644
--- a/client/src/components/music/MusicGenPanel.test.jsx
+++ b/client/src/components/music/MusicGenPanel.test.jsx
@@ -226,16 +226,98 @@ describe('MusicGenPanel', () => {
expect(onGenerated).toHaveBeenCalledWith(expect.objectContaining({ id: 'generated-track' }));
});
+ it('can render instrumentally without conditioning on or clearing the track lyrics', async () => {
+ api.listMusicEngines.mockResolvedValue({
+ defaultEngine: 'acestep',
+ engines: [engine({
+ id: 'acestep',
+ name: 'ACE-Step (full song + vocals)',
+ models: [{ id: 'ace-step-v1-3.5b', name: 'ACE-Step v1 3.5B', userAdded: false }],
+ defaultModelId: 'ace-step-v1-3.5b',
+ maxDurationSec: 240,
+ defaultDurationSec: 60,
+ lyrics: true,
+ customModels: false,
+ ready: true,
+ })],
+ });
+ api.generateMusic.mockResolvedValue({ track: { id: 'track-1' } });
+
+ render(<MusicGenPanel track={{ id: 'track-1' }} prompt="warm folk" lyrics={'[verse]\nKeep these words'} />);
+
+ const instrumental = await screen.findByRole('checkbox', { name: /instrumental only/i });
+ expect(instrumental).not.toBeChecked();
+ expect(instrumental).toBeEnabled();
+ fireEvent.click(instrumental);
+ expect(screen.getByText(/saved lyrics will not condition this render/i)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: /^generate$/i }));
+
+ await waitFor(() => expect(api.generateMusic).toHaveBeenCalled());
+ const requestBody = api.generateMusic.mock.calls[0][0];
+ expect(requestBody).toEqual(expect.objectContaining({
+ trackId: 'track-1',
+ instrumentalOnly: true,
+ lyrics: '[verse]\nKeep these words',
+ }));
+ });
+
+ it('keeps lyricless vocal textures possible until instrumental mode is explicitly selected', async () => {
+ api.listMusicEngines.mockResolvedValue({
+ defaultEngine: 'acestep',
+ engines: [engine({
+ id: 'acestep',
+ name: 'ACE-Step (full song + vocals)',
+ models: [{ id: 'ace-step-v1-3.5b', name: 'ACE-Step v1 3.5B', userAdded: false }],
+ defaultModelId: 'ace-step-v1-3.5b',
+ lyrics: true,
+ customModels: false,
+ ready: true,
+ })],
+ });
+ api.generateMusic.mockResolvedValue({ track: { id: 'track-1' } });
+
+ render(<MusicGenPanel track={{ id: 'track-1' }} prompt="distant wordless choir" lyrics="" />);
+
+ const instrumental = await screen.findByRole('checkbox', { name: /instrumental only/i });
+ expect(instrumental).not.toBeChecked();
+ expect(instrumental).toBeEnabled();
+ expect(screen.getByText(/vocals may still follow the prompt/i)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: /^generate$/i }));
+
+ await waitFor(() => expect(api.generateMusic).toHaveBeenCalledWith(expect.objectContaining({
+ instrumentalOnly: false,
+ lyrics: '',
+ }), { silent: true }));
+ });
+
+ it('offers instrumental-only conditioning for engines without a separate lyrics input', async () => {
+ api.listMusicEngines.mockResolvedValue({ defaultEngine: 'musicgen', engines: [engine({ ready: true })] });
+ api.generateMusic.mockResolvedValue({ track: { id: 'track-1' } });
+
+ render(<MusicGenPanel track={{ id: 'track-1' }} prompt="ambient choir textures" lyrics="" />);
+
+ const instrumental = await screen.findByRole('checkbox', { name: /instrumental only/i });
+ fireEvent.click(instrumental);
+ fireEvent.click(screen.getByRole('button', { name: /^generate$/i }));
+
+ await waitFor(() => expect(api.generateMusic).toHaveBeenCalled());
+ const requestBody = api.generateMusic.mock.calls[0][0];
+ expect(requestBody.instrumentalOnly).toBe(true);
+ expect(requestBody).not.toHaveProperty('lyrics');
+ });
+
it('rehydrates a running Music Studio job when the panel remounts', async () => {
api.listMusicEngines.mockResolvedValue({ defaultEngine: 'musicgen', engines: [engine({ ready: true })] });
api.getActiveProcessing.mockResolvedValue({ jobs: [{
id: 'job-remounted', kind: 'audio', status: 'running', startedAt: new Date(Date.now() - 5000).toISOString(),
- params: { musicStudio: { trackId: 'track-1' } },
+ params: { musicStudio: { trackId: 'track-1', instrumentalOnly: true } },
}] });
api.getMediaJob.mockResolvedValue({ status: 'running', startedAt: new Date(Date.now() - 5000).toISOString() });
render(<MusicGenPanel track={{ id: 'track-1' }} prompt="warm folk" lyrics="" />);
expect(await screen.findByText(/processing on the gpu|rendering audio/i)).toBeInTheDocument();
expect(screen.getByRole('status')).toHaveTextContent(/elapsed/);
+ expect(screen.getByRole('checkbox', { name: /instrumental only/i })).toBeChecked();
+ expect(screen.getByRole('checkbox', { name: /instrumental only/i })).toBeDisabled();
});
it('suggests a lyric-aware MiniMax ceiling and sends Auto mode', async () => {
diff --git a/client/src/components/music/TracksManager.jsx b/client/src/components/music/TracksManager.jsx
index f08a5aecd1..4434ffe27b 100644
--- a/client/src/components/music/TracksManager.jsx
+++ b/client/src/components/music/TracksManager.jsx
@@ -354,10 +354,18 @@ export default function TracksManager() {
setGenMode('audio');
setForm((f) => ({
...f,
- ...(render.prompt ? { prompt: render.prompt } : {}),
+ ...((render.authoredPrompt || render.prompt) ? { prompt: render.authoredPrompt || render.prompt } : {}),
...(render.lyrics ? { lyrics: render.lyrics } : {}),
}));
- setRemix({ engineId: render.engine, modelId: render.modelId, durationSec: render.durationSec, nonce: remixNonceRef.current });
+ setRemix({
+ engineId: render.engine,
+ modelId: render.modelId,
+ durationSec: render.durationSec,
+ // Only new renders carry an explicit vocal-mode decision. Legacy empty
+ // lyric snapshots are ambiguous and must not be reclassified as no-vocals.
+ ...(typeof render.instrumentalOnly === 'boolean' ? { instrumentalOnly: render.instrumentalOnly } : {}),
+ nonce: remixNonceRef.current,
+ });
};
return (
diff --git a/client/src/components/music/TracksManager.test.jsx b/client/src/components/music/TracksManager.test.jsx
index 2a9c01b7e1..5f31830b15 100644
--- a/client/src/components/music/TracksManager.test.jsx
+++ b/client/src/components/music/TracksManager.test.jsx
@@ -2,12 +2,19 @@ import { render, screen, cleanup, fireEvent, waitFor, within } from '@testing-li
import { MemoryRouter, Routes, Route, useLocation } from 'react-router';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+const musicGenProps = vi.hoisted(() => ({ current: null }));
+
// Stub the heavy children — this suite pins the MIDI read-through wiring
// (#2477 follow-up), not the editor/generation internals.
vi.mock('./ArtistPicker', () => ({ default: () => <div data-testid="artist-picker" /> }));
-vi.mock('./MusicGenPanel', () => ({ default: () => <div data-testid="gen-panel" /> }));
+vi.mock('./MusicGenPanel', () => ({ default: (props) => {
+ musicGenProps.current = props;
+ return <div data-testid="gen-panel" />;
+} }));
vi.mock('./ChiptunePanel', () => ({ default: () => <div data-testid="chiptune-panel" /> }));
-vi.mock('./TrackRenderCard', () => ({ default: () => <div data-testid="render-card" /> }));
+vi.mock('./TrackRenderCard', () => ({ default: ({ render: item, onRemix }) => (
+ <button type="button" data-testid="render-card" onClick={() => onRemix(item)}>Remix {item.id}</button>
+) }));
vi.mock('./TrackRenderModal', () => ({ default: () => null }));
vi.mock('../songs/MidiVisualization.jsx', () => ({
default: ({ url, model }) => <div data-testid="midi-viz" data-url={url} data-model={model} />,
@@ -197,6 +204,34 @@ describe('<TracksManager> generative workflow hand-off', () => {
));
expect(await screen.findByTestId('location')).toHaveTextContent('/music/generate/concept?trackId=track-1');
});
+
+ it('remixes only explicit instrumental modes and restores the authored prompt', async () => {
+ listTracks.mockResolvedValue([{
+ ...TRACK,
+ prompt: 'Current source',
+ lyrics: 'Current lyrics',
+ renders: [
+ {
+ id: 'render-explicit', audioFilename: 'explicit.wav', engine: 'acestep', prompt: 'Conditioned prompt',
+ authoredPrompt: 'Authored prompt', lyrics: '', instrumentalOnly: true, createdAt: '2026-01-02T00:00:00Z',
+ },
+ {
+ id: 'render-legacy', audioFilename: 'legacy.wav', engine: 'acestep', prompt: 'Legacy vocal texture',
+ lyrics: '', createdAt: '2026-01-01T00:00:00Z',
+ },
+ ],
+ }]);
+ musicGenProps.current = null;
+ renderAt('track-1');
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Remix render-explicit' }));
+ await waitFor(() => expect(musicGenProps.current?.remix).toEqual(expect.objectContaining({ instrumentalOnly: true })));
+ expect(musicGenProps.current.prompt).toBe('Authored prompt');
+
+ fireEvent.click(screen.getByRole('button', { name: 'Remix render-legacy' }));
+ await waitFor(() => expect(musicGenProps.current?.remix?.nonce).toBe(2));
+ expect(musicGenProps.current.remix).not.toHaveProperty('instrumentalOnly');
+ });
});
// ConfirmButtonPair delete wiring (via useConfirmDelete) and the field-edit
diff --git a/client/src/services/apiMusic.js b/client/src/services/apiMusic.js
index e355dfaaba..400d553368 100644
--- a/client/src/services/apiMusic.js
+++ b/client/src/services/apiMusic.js
@@ -9,11 +9,11 @@ import { request, maybeRedirectToLogin } from './apiCore.js';
// and a `ready` flag (the opt-in venv is provisioned) → { engines, defaultEngine }.
export const listMusicEngines = (options = {}) => request('/music/engines', options);
-// Generate a track. body: { prompt, lyrics?, engine?, modelId?, durationSec?,
+// Generate a track. body: { prompt, lyrics?, instrumentalOnly?, engine?, modelId?, durationSec?,
// durationMode?: 'auto'|'manual',
-// trackId? (update) | title?/artistId?/artist?/albumId? (create) }. Resolves to
-// { track, filename, durationSec, engine, modelId }. Long renders hold the
-// request open — callers should own their loading UI and pass `{ silent: true }`.
+// trackId? (update) | title?/artistId?/artist?/albumId? (create) }. New servers
+// acknowledge with HTTP 202 + { jobId, position, status }; an older rolling-
+// upgrade peer may still return { track }. Callers own their loading UI.
export const generateMusic = (body, requestOptions = {}) => request('/music/generate', {
method: 'POST',
body: JSON.stringify(body),
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index f2fb11a827..16daf16e7c 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -249,7 +249,10 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// tracks v4 = `track.concept` for resumable stepped music-designer drafts.
// Older peers must reject the record rather than round-trip it through a
// concept-unaware sanitizer and silently erase the saved creative brief.
- tracks: 4,
+ // tracks v5 = render-history entries gained `authoredPrompt` and the explicit
+ // nullable `instrumentalOnly` decision. A <=v4 peer would strip both, then LWW
+ // the ambiguous render back and make a later remix silently change vocal mode.
+ tracks: 5,
// v1 = creative ingredients catalog (Postgres tables: catalog_scraps,
// catalog_ingredients, catalog_ingredient_sources, catalog_ingredient_refs).
// v2 = `catalog_ingredients.search_tsv` expanded to also index the
diff --git a/server/routes/music.js b/server/routes/music.js
index 54a8b6501c..8a4a4ac12c 100644
--- a/server/routes/music.js
+++ b/server/routes/music.js
@@ -336,6 +336,9 @@ const generateSchema = z.object({
// No default: distinguish ABSENT (don't touch the track's lyrics) from a
// present '' (the user cleared them and generated without — persist the clear).
lyrics: z.string().trim().max(20000).optional(),
+ // A render-level override: ignore even supplied lyrics without clearing the
+ // track's saved lyric field when the completed audio is attached.
+ instrumentalOnly: z.boolean().optional().default(false),
engine: z.string().trim().max(60).optional(),
modelId: z.string().trim().max(120).optional(),
durationSec: z.number().positive().max(600).optional(),
@@ -349,6 +352,8 @@ const generateSchema = z.object({
albumId: z.string().trim().max(80).optional().default(''),
});
+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 ?? {});
// Reject an unknown engine explicitly rather than letting getEngine() fall
@@ -384,13 +389,21 @@ router.post('/generate', asyncHandler(async (req, res) => {
if (picked.userAdded) repo = picked.repo || picked.id;
}
+ // 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;
+
// 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").
- const usedLyrics = engine.lyrics ? (body.lyrics ?? '') : '';
+ const usedLyrics = engine.lyrics && !body.instrumentalOnly ? (body.lyrics ?? '') : '';
const liveJobs = listJobs({ kind: 'audio' }).filter((job) => job.status === 'queued' || job.status === 'running');
const duplicate = liveJobs.find((job) => {
@@ -408,7 +421,7 @@ router.post('/generate', asyncHandler(async (req, res) => {
const result = enqueueJob({
kind: 'audio',
params: {
- prompt: body.prompt,
+ prompt: usedPrompt,
lyrics: usedLyrics,
engine: engine.id,
modelId: body.modelId,
@@ -421,8 +434,13 @@ router.post('/generate', asyncHandler(async (req, res) => {
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: body.lyrics !== undefined,
+ lyricsProvided: engine.lyrics === true && body.lyrics !== undefined,
+ instrumentalOnly: body.instrumentalOnly,
},
},
});
diff --git a/server/routes/music.test.js b/server/routes/music.test.js
index 65d3d902a9..5fbecea453 100644
--- a/server/routes/music.test.js
+++ b/server/routes/music.test.js
@@ -3,11 +3,9 @@ import express from 'express';
import { request } from '../lib/testHelper.js';
import { ServerError } from '../lib/errorHandler.js';
-// Mock the music-gen service: a small engine registry + a generateMusic that the
-// tests drive per-case. The route only consumes ENGINES/getEngine/isEngineHealthy/
-// generateMusic + DEFAULT_ENGINE_ID.
+// Mock the music-gen service's engine registry and readiness probes. Generation
+// itself is queued through mediaJobQueue and never runs inside this route.
const gen = vi.hoisted(() => ({
- generateMusic: vi.fn(),
ready: true,
readyByEngine: null,
healthy: null,
@@ -71,7 +69,6 @@ vi.mock('../services/pipeline/musicGen.js', () => {
return gen.readyByEngine ? gen.readyByEngine[engineId] === true : gen.ready;
},
invalidateEngineHealth: vi.fn(),
- generateMusic: gen.generateMusic,
};
});
vi.mock('../services/mediaJobQueue/index.js', () => ({
@@ -174,10 +171,6 @@ describe('music routes', () => {
let app;
beforeEach(() => {
app = makeApp();
- // mockReset clears queued *Once implementations too (clearAllMocks only
- // clears call history) — otherwise an unconsumed mockResolvedValueOnce on
- // generateMusic leaks into the next test.
- gen.generateMusic.mockReset();
mediaQueue.enqueue.mockReset().mockImplementation(() => ({ jobId: 'job-1', position: 1, status: 'queued' }));
mediaQueue.jobs = [];
models.list.mockReset();
@@ -582,7 +575,6 @@ describe('music routes', () => {
it('POST /generate marks non-lyric jobs as not lyric-enabled', async () => {
tracks.getTrack.mockResolvedValueOnce({ id: 'track-1', title: 'Has Lyrics', lyrics: 'keep me' });
- gen.generateMusic.mockResolvedValueOnce({ filename: 'm.wav', durationSec: 12, engine: 'musicgen', modelId: 'm' });
// MusicGen is not lyric-aware; even if the client sends lyrics:'' the update must omit lyrics.
await request(app).post('/api/music/generate').send({ prompt: 'bed', lyrics: '', engine: 'musicgen', trackId: 'track-1' });
expect(mediaQueue.enqueue).toHaveBeenCalledWith(expect.objectContaining({ params: expect.objectContaining({ musicStudio: expect.objectContaining({ lyricsEnabled: false }) }) }));
@@ -590,11 +582,39 @@ describe('music routes', () => {
it('POST /generate records the empty conditioning snapshot when lyrics are absent', async () => {
tracks.getTrack.mockResolvedValueOnce({ id: 'track-1', title: 'Song', lyrics: 'old words' });
- gen.generateMusic.mockResolvedValueOnce({ filename: 'm.wav', durationSec: 60, engine: 'acestep', modelId: 'a' });
await request(app).post('/api/music/generate').send({ prompt: 'folk', engine: 'acestep', trackId: 'track-1' }); // no lyrics field
expect(mediaQueue.enqueue).toHaveBeenCalledWith(expect.objectContaining({ params: expect.objectContaining({ lyrics: '', musicStudio: expect.objectContaining({ lyricsEnabled: true }) }) }));
});
+ it('POST /generate separates authored text from instrumental engine conditioning', async () => {
+ tracks.getTrack.mockResolvedValueOnce({ id: 'track-1', title: 'Song', lyrics: 'keep these words' });
+ const r = await request(app).post('/api/music/generate').send({
+ prompt: 'warm folk',
+ lyrics: '[verse] do not condition with this',
+ instrumentalOnly: true,
+ engine: 'acestep',
+ trackId: 'track-1',
+ });
+
+ expect(r.status).toBe(202);
+ expect(mediaQueue.enqueue).toHaveBeenCalledWith(expect.objectContaining({
+ params: expect.objectContaining({
+ prompt: expect.stringContaining('Instrumental only.'),
+ lyrics: '',
+ musicStudio: expect.objectContaining({
+ authoredPrompt: 'warm folk',
+ authoredLyrics: '[verse] do not condition with this',
+ lyricsEnabled: true,
+ lyricsProvided: true,
+ instrumentalOnly: true,
+ }),
+ }),
+ }));
+ const queuedPrompt = mediaQueue.enqueue.mock.calls[0][0].params.prompt;
+ expect(queuedPrompt).toContain('Do not include sung, spoken, chanted, choir, or background vocals.');
+ expect(queuedPrompt).not.toBe('warm folk');
+ });
+
it('POST /generate keeps the track destination in the job snapshot', async () => {
tracks.getTrack.mockResolvedValueOnce({ id: 'track-1' });
await request(app).post('/api/music/generate').send({ prompt: 'beat', engine: 'musicgen', trackId: 'track-1' });
@@ -603,7 +623,6 @@ describe('music routes', () => {
it('POST /generate preserves an explicit lyric clear in the job snapshot', async () => {
tracks.getTrack.mockResolvedValueOnce({ id: 'track-1', title: 'Song', lyrics: 'old words' });
- gen.generateMusic.mockResolvedValueOnce({ filename: 'm.wav', durationSec: 60, engine: 'acestep', modelId: 'a' });
await request(app).post('/api/music/generate').send({ prompt: 'instrumental', lyrics: '', engine: 'acestep', trackId: 'track-1' });
expect(mediaQueue.enqueue).toHaveBeenCalledWith(expect.objectContaining({ params: expect.objectContaining({ lyrics: '', musicStudio: expect.objectContaining({ lyricsEnabled: true }) }) }));
});
@@ -612,7 +631,7 @@ describe('music routes', () => {
tracks.getTrack.mockResolvedValueOnce(null);
const r = await request(app).post('/api/music/generate').send({ prompt: 'x', trackId: 'gone' });
expect(r.status).toBe(404);
- expect(gen.generateMusic).not.toHaveBeenCalled(); // render never started
+ expect(mediaQueue.enqueue).not.toHaveBeenCalled();
});
it('POST /generate resolves a USER-INSTALLED model id to the queued job', async () => {
@@ -629,7 +648,7 @@ describe('music routes', () => {
const r = await request(app).post('/api/music/generate').send({ prompt: 'x', engine: 'musicgen', modelId: 'gone/removed' });
expect(r.status).toBe(400);
expect(r.body.code).toBe('PIPELINE_MUSIC_UNKNOWN_MODEL');
- expect(gen.generateMusic).not.toHaveBeenCalled();
+ expect(mediaQueue.enqueue).not.toHaveBeenCalled();
});
it('POST /generate carries album metadata to the queued job', async () => {
diff --git a/server/services/mediaJobQueue/sanitizeJob.js b/server/services/mediaJobQueue/sanitizeJob.js
index 4a495a3442..9e34dfb44d 100644
--- a/server/services/mediaJobQueue/sanitizeJob.js
+++ b/server/services/mediaJobQueue/sanitizeJob.js
@@ -10,7 +10,7 @@ const PARAM_ALLOWLIST = new Set([
]);
const MUSIC_STUDIO_KEYS = new Set([
- 'trackId', 'title', 'artistId', 'artist', 'albumId', 'lyricsEnabled', 'lyricsProvided',
+ 'trackId', 'title', 'artistId', 'artist', 'albumId', 'lyricsEnabled', 'lyricsProvided', 'instrumentalOnly',
]);
export function sanitizeJob(job) {
diff --git a/server/services/mediaJobQueue/sanitizeJob.test.js b/server/services/mediaJobQueue/sanitizeJob.test.js
new file mode 100644
index 0000000000..0fad4d7cd6
--- /dev/null
+++ b/server/services/mediaJobQueue/sanitizeJob.test.js
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest';
+import { sanitizeJob } from './sanitizeJob.js';
+
+describe('sanitizeJob', () => {
+ it('exposes instrumental mode without leaking authored Music Studio text', () => {
+ const job = sanitizeJob({
+ id: 'job-1',
+ kind: 'audio',
+ status: 'running',
+ params: {
+ prompt: 'safe conditioning prompt',
+ lyrics: 'private lyric draft',
+ musicStudio: {
+ trackId: 'track-1',
+ authoredPrompt: 'private source prompt',
+ authoredLyrics: 'private lyric draft',
+ instrumentalOnly: true,
+ },
+ },
+ });
+
+ expect(job.params.musicStudio).toEqual({ trackId: 'track-1', instrumentalOnly: true });
+ expect(job.params).not.toHaveProperty('lyrics');
+ });
+});
diff --git a/server/services/musicDesigner.js b/server/services/musicDesigner.js
index 36cb831d37..956f64ce9c 100644
--- a/server/services/musicDesigner.js
+++ b/server/services/musicDesigner.js
@@ -2,8 +2,8 @@
* Music designer — the two LLM steps behind the Music studio's stepped
* Generate tab (#4305).
*
- * describeMusic() short reference/vibe → a rich, genre-dense musical
- * description suitable as an ACE-Step conditioning prompt.
+ * describeMusic() short reference/vibe → a detailed structured caption
+ * suitable for MiniMax Music 3 and the other generators.
* writeLyrics() that description (+ the user's extra guidance) → original
* lyrics in the `[verse]` / `[chorus]` section syntax the
* lyric-aware engines expect.
@@ -33,9 +33,37 @@ const MAX_TEMPLATE = 8000;
const MAX_DESCRIPTION = 8000;
const MAX_LYRICS = 20000;
-export const DEFAULT_DESCRIBE_TEMPLATE = 'Describe the given musical reference and description in richer detail in English, focusing primarily on the sound, instruments, feel, and the overall atmosphere. Also briefly describe the composition, instrumentation, beats, lyrical or instrumental style (maybe it doesn\'t have lyrics), and aesthetic. Keep it concise and genre-focused rather than overly technical.';
-
-export const DEFAULT_LYRICS_TEMPLATE = 'Write original song lyrics that fit the musical description below. Use the section syntax the audio engine expects: a bracketed section tag alone on its line ([verse], [chorus], [bridge], [outro]) with that section\'s lines beneath it. Match the mood, genre, energy, and vocal style implied by the description, and keep the phrasing singable. Keep the lyrics original (do not reproduce copyrighted lyrics verbatim).';
+// Caption shape follows MiniMax Music 3's official music-caption-rewriter
+// contract. Keep it model-neutral enough to remain useful for ACE-Step and the
+// other text-conditioned engines in the same picker.
+export const DEFAULT_DESCRIBE_TEMPLATE = [
+ 'Rewrite the musical reference into a detailed, generation-oriented structured caption in English.',
+ 'Preserve every explicit requirement and exclusion while developing genre and subgenres, emotional arc, imagery, sonics, production character, core instruments, and spatial feel.',
+ 'Describe approximate tempo, meter or time signature, rhythmic subdivision, and groove when they matter. Use an exact BPM, key, scale, or time signature only when the user supplied it or clearly wants that precision; otherwise use a range or qualitative musical language.',
+ 'State the vocal plan explicitly. For instrumental music, say that it is instrumental, rule out vocals, and name the instrument or texture carrying the lead melodic role. For vocal music, describe lead configuration, timbre, register, delivery, harmonies, and restrained vocal effects.',
+ 'Treat the arrangement as a continuous section-by-section timeline: explain what enters, exits, changes, strips back, or intensifies, and keep transitions and instrument lifecycles musically plausible.',
+ 'Keep lyric words and lyrical subject matter out of the caption; the separate lyrics input owns them. Prefer concrete musical changes over decorative prose.',
+].join(' ');
+
+export const DEFAULT_LYRICS_TEMPLATE = [
+ 'Write original, singable song lyrics that fit the musical description below.',
+ 'Use only useful bracketed section tags such as [intro], [verse], [pre-chorus], [chorus], [post-chorus], [bridge], [instrumental], [solo], and [outro]. Every tag must sit alone on its own line, with any singable words beginning on the following line.',
+ 'Build a complete emotional and structural arc with enough sections for the intended song length; short lyrics can cause the music engine to end early.',
+ 'Keep tempo, meter, key, arrangement, and production instructions in the musical description rather than mixing them into lyric lines.',
+ 'Keep the lyrics original and do not reproduce copyrighted lyrics verbatim.',
+].join(' ');
+
+const DESCRIBE_OUTPUT_CONTRACT = [
+ 'Return ONLY the structured caption as plain text, normally 250–450 English words.',
+ 'Use exactly these three top-level headings in this order, each alone on its own line and without markdown markers:',
+ 'Global Metadata',
+ 'Cover basic attributes (genre, tempo, meter/groove, and only deliberate key/scale details), the global emotional progression, application imagery, and the sonic/production profile.',
+ 'Vocal Details',
+ 'Describe the vocal configuration and performance, or explicitly declare the piece instrumental and identify its lead melodic instrument or texture.',
+ 'Arrangement',
+ 'Describe primary and secondary instrument lifecycles, groove development, and a section-by-section energy timeline with concrete entrances, exits, transitions, textures, and spatial effects.',
+ 'No preamble, bullet list, song title, quoted lyrics, reasoning trace, or markdown fence.',
+].join('\n');
const clean = (value, max) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
@@ -54,7 +82,7 @@ export function buildDescribePrompt({ concept, guidance, template } = {}) {
pickTemplate(template, DEFAULT_DESCRIBE_TEMPLATE),
section('MUSICAL REFERENCE / VIBE', clean(concept, MAX_CONCEPT) || '(none given)'),
section('ADDITIONAL GUIDANCE FROM THE USER', clean(guidance, MAX_GUIDANCE)),
- '\n\nReturn ONLY the description as plain prose. No preamble, no headings, no bullet list, no markdown fence.',
+ `\n\n${DESCRIBE_OUTPUT_CONTRACT}`,
].join('');
}
diff --git a/server/services/musicDesigner.test.js b/server/services/musicDesigner.test.js
index 76e7ebeae8..b1966d3397 100644
--- a/server/services/musicDesigner.test.js
+++ b/server/services/musicDesigner.test.js
@@ -51,10 +51,33 @@ describe('prompt builders', () => {
expect(buildDescribePrompt({ concept: 'x' })).not.toContain('ADDITIONAL GUIDANCE');
});
+ it('requests the MiniMax structured-caption contract with deliberate timing detail', () => {
+ const prompt = buildDescribePrompt({ concept: 'an instrumental night drive in 6/8' });
+ const globalIndex = prompt.indexOf('Global Metadata');
+ const vocalIndex = prompt.indexOf('Vocal Details');
+ const arrangementIndex = prompt.indexOf('Arrangement');
+
+ expect(prompt).toMatch(/meter or time signature/i);
+ expect(prompt).toMatch(/250–450 English words/i);
+ expect(prompt).toMatch(/instrumental.*lead melodic/i);
+ expect(globalIndex).toBeGreaterThan(-1);
+ expect(vocalIndex).toBeGreaterThan(globalIndex);
+ expect(arrangementIndex).toBeGreaterThan(vocalIndex);
+ });
+
+ it('keeps music controls in the caption and requires standalone lyric tags', () => {
+ const prompt = buildLyricsPrompt({ description: 'slow compound-meter soul' });
+ expect(prompt).toMatch(/every tag must sit alone on its own line/i);
+ expect(prompt).toContain('[instrumental]');
+ expect(prompt).toContain('[solo]');
+ expect(prompt).toMatch(/tempo, meter, key, arrangement, and production instructions in the musical description/i);
+ });
+
it('keeps the output-format instruction outside the overridable template', () => {
// An override tunes the creative brief, not the wire format — a fenced or
// preambled response would land verbatim in the user's textarea.
expect(buildLyricsPrompt({ description: 'x', template: 'Whatever.' })).toContain('no markdown fence');
+ expect(buildDescribePrompt({ concept: 'x', template: 'Whatever.' })).toContain('Global Metadata');
});
});
diff --git a/server/services/musicStudioHook.js b/server/services/musicStudioHook.js
index 92405b0cb0..f51a3804ec 100644
--- a/server/services/musicStudioHook.js
+++ b/server/services/musicStudioHook.js
@@ -20,29 +20,36 @@ const hook = createMediaJobImageHook({
const filename = job.result?.filename;
if (typeof filename !== 'string' || !filename) return null;
const tag = job.params.musicStudio;
+ const authoredPrompt = typeof tag.authoredPrompt === 'string' ? tag.authoredPrompt : job.params.prompt;
+ const authoredLyrics = typeof tag.authoredLyrics === 'string' ? tag.authoredLyrics : job.params.lyrics;
return {
filename,
durationSec: Number.isFinite(job.result?.durationSec) ? Math.round(job.result.durationSec) : null,
engine: typeof job.result?.engine === 'string' ? job.result.engine : null,
modelId: typeof job.result?.modelId === 'string' ? job.result.modelId : null,
prompt: job.params.prompt,
+ authoredPrompt,
lyrics: job.params.lyrics,
+ authoredLyrics,
lyricsEnabled: tag.lyricsEnabled === true,
lyricsProvided: tag.lyricsProvided === true,
+ instrumentalOnly: typeof tag.instrumentalOnly === 'boolean' ? tag.instrumentalOnly : null,
title: tag.title,
artistId: tag.artistId,
artist: tag.artist,
albumId: tag.albumId,
};
},
- attach: async ({ job, trackId, filename, durationSec, engine, modelId, prompt, lyrics, lyricsEnabled, lyricsProvided, title, artistId, artist, albumId }) => {
+ attach: async ({ job, trackId, filename, durationSec, engine, modelId, prompt, authoredPrompt, lyrics, authoredLyrics, lyricsEnabled, lyricsProvided, instrumentalOnly, title, artistId, artist, albumId }) => {
const current = trackId ? await tracks.getTrack(trackId) : null;
// A deleted target is a successful render but no longer an attach target.
if (trackId && !current) return null;
const { renders } = tracks.buildRenderAppend(current, {
audioFilename: filename,
prompt,
+ authoredPrompt,
lyrics: lyricsEnabled ? lyrics : '',
+ instrumentalOnly,
engine,
modelId,
durationSec,
@@ -52,18 +59,21 @@ const hook = createMediaJobImageHook({
engine,
modelId,
durationSec,
- prompt,
+ prompt: authoredPrompt,
renders,
};
- if (lyricsEnabled && lyricsProvided) meta.lyrics = lyrics;
+ // Existing instrumental renders preserve the track's saved lyric draft;
+ // a standalone render has no prior record, so retain its authored lyrics.
+ const shouldPersistLyrics = lyricsEnabled && lyricsProvided && (instrumentalOnly !== true || !trackId);
+ if (shouldPersistLyrics) meta.lyrics = authoredLyrics;
const track = trackId
? await tracks.updateTrack(trackId, meta)
: await tracks.createTrack({
- title: title || prompt.slice(0, 60),
+ title: title || authoredPrompt.slice(0, 60),
artistId,
artist,
albumId,
- ...(lyricsEnabled && lyricsProvided ? { lyrics } : {}),
+ ...(shouldPersistLyrics ? { lyrics: authoredLyrics } : {}),
...meta,
});
if (!trackId && track?.albumId) {
diff --git a/server/services/musicStudioHook.test.js b/server/services/musicStudioHook.test.js
index 829b360c1f..377f43cac3 100644
--- a/server/services/musicStudioHook.test.js
+++ b/server/services/musicStudioHook.test.js
@@ -44,6 +44,68 @@ describe('music studio completion hook', () => {
expect(queue.updateJobResult).toHaveBeenCalledWith('job-1', { trackId: 'track-1' });
});
+ it('records an instrumental render without replacing saved track lyrics', async () => {
+ trackStore.getTrack.mockResolvedValue({ id: 'track-1', lyrics: 'keep these words', renders: [] });
+ queue.events.emit('completed', {
+ id: 'job-instrumental', kind: 'audio', queuedAt: new Date().toISOString(),
+ params: {
+ prompt: 'warm folk\n\nInstrumental only. Do not include vocals.',
+ lyrics: '',
+ musicStudio: {
+ trackId: 'track-1',
+ authoredPrompt: 'warm folk',
+ authoredLyrics: 'keep these words',
+ lyricsEnabled: true,
+ lyricsProvided: true,
+ instrumentalOnly: true,
+ },
+ },
+ result: { filename: 'instrumental.wav', durationSec: 60, engine: 'acestep', modelId: 'a' },
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+
+ expect(trackStore.buildRenderAppend).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'track-1' }),
+ expect.objectContaining({
+ prompt: expect.stringContaining('Instrumental only.'),
+ authoredPrompt: 'warm folk',
+ lyrics: '',
+ instrumentalOnly: true,
+ }),
+ );
+ const update = trackStore.updateTrack.mock.calls[0][1];
+ expect(update.prompt).toBe('warm folk');
+ expect(update).not.toHaveProperty('lyrics');
+ expect(queue.updateJobResult).toHaveBeenCalledWith('job-instrumental', { trackId: 'track-1' });
+ });
+
+ it('keeps authored lyrics when an instrumental render creates a standalone track', async () => {
+ queue.events.emit('completed', {
+ id: 'job-standalone-instrumental', kind: 'audio', queuedAt: new Date().toISOString(),
+ params: {
+ prompt: 'cinematic score\n\nInstrumental only. Do not include vocals.',
+ lyrics: '',
+ musicStudio: {
+ trackId: null,
+ title: 'Fake score',
+ authoredPrompt: 'cinematic score',
+ authoredLyrics: '[verse]\nSaved draft words',
+ lyricsEnabled: true,
+ lyricsProvided: true,
+ instrumentalOnly: true,
+ },
+ },
+ result: { filename: 'standalone.wav', durationSec: 60, engine: 'acestep', modelId: 'a' },
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+
+ expect(trackStore.createTrack).toHaveBeenCalledWith(expect.objectContaining({
+ title: 'Fake score',
+ prompt: 'cinematic score',
+ lyrics: '[verse]\nSaved draft words',
+ }));
+ });
+
it('creates a standalone track, appends its album, and does not crash when target is deleted', async () => {
trackStore.createTrack.mockResolvedValue({ id: 'track-new', albumId: 'album-1' });
queue.events.emit('completed', {
diff --git a/server/services/tracks/logic.js b/server/services/tracks/logic.js
index c107b710e3..18da5271c2 100644
--- a/server/services/tracks/logic.js
+++ b/server/services/tracks/logic.js
@@ -25,7 +25,8 @@
* - renders — the full render history (every generated/uploaded take), so
* the studio can show each render as a card and re-select an
* earlier one. Each entry is `{ id, audioFilename, prompt,
- * lyrics, engine, modelId, durationSec, createdAt }`. The
+ * authoredPrompt, lyrics, instrumentalOnly, engine,
+ * modelId, durationSec, createdAt }`. The
* top-level `audioFilename`/`engine`/`modelId`/`durationSec`
* point at whichever render is currently ACTIVE (selected).
*
@@ -99,7 +100,11 @@ export function sanitizeRender(raw) {
id,
audioFilename,
prompt: trimTo(raw.prompt, PROMPT_MAX),
+ authoredPrompt: trimTo(raw.authoredPrompt, PROMPT_MAX),
lyrics: trimTo(raw.lyrics, LYRICS_MAX),
+ // null means a legacy/uploaded render never recorded the choice. Preserve
+ // that sentinel so remixing cannot infer vocal intent from empty lyrics.
+ instrumentalOnly: typeof raw.instrumentalOnly === 'boolean' ? raw.instrumentalOnly : null,
engine: trimTo(raw.engine, ENGINE_MAX),
modelId: trimTo(raw.modelId, MODEL_ID_MAX),
durationSec: sanitizeDuration(raw.durationSec),
@@ -153,7 +158,9 @@ export function sanitizeTrack(raw) {
id: legacyRenderId(audioFilename),
audioFilename,
prompt,
+ authoredPrompt: prompt,
lyrics,
+ instrumentalOnly: null,
engine,
modelId,
durationSec,
diff --git a/server/services/tracks/logic.test.js b/server/services/tracks/logic.test.js
index 8c4d511d90..79d44dfdd6 100644
--- a/server/services/tracks/logic.test.js
+++ b/server/services/tracks/logic.test.js
@@ -83,6 +83,7 @@ describe('tracks logic', () => {
expect(t.renders).toHaveLength(1);
expect(t.renders[0]).toMatchObject({
audioFilename: 'music-abc.wav', engine: 'musicgen', modelId: 'musicgen-medium', durationSec: 12, prompt: 'warm folk',
+ authoredPrompt: 'warm folk', instrumentalOnly: null,
createdAt: '2026-01-02T00:00:00.000Z',
});
// Deterministic id derived from the filename — re-sanitizing (the DB read
@@ -111,12 +112,19 @@ describe('tracks logic', () => {
it('sanitizeRender drops entries without usable audio bytes', () => {
expect(sanitizeRender({ id: 'r1' })).toBeNull();
expect(sanitizeRender({ id: 'r1', audioFilename: '../x.wav' })).toBeNull();
- expect(sanitizeRender({ audioFilename: 'a.wav' }).id).toMatch(/^r-/); // deterministic fallback id
+ const legacy = sanitizeRender({ audioFilename: 'a.wav' });
+ expect(legacy.id).toMatch(/^r-/); // deterministic fallback id
+ expect(legacy.instrumentalOnly).toBeNull();
});
it('makeRender stamps the caller-supplied id + now', () => {
- const r = makeRender({ audioFilename: 'a.wav', engine: 'musicgen' }, { id: 'render-7', now: '2026-03-03T00:00:00.000Z' });
- expect(r).toMatchObject({ id: 'render-7', audioFilename: 'a.wav', engine: 'musicgen', createdAt: '2026-03-03T00:00:00.000Z' });
+ const r = makeRender({
+ audioFilename: 'a.wav', engine: 'musicgen', authoredPrompt: 'source prompt', instrumentalOnly: true,
+ }, { id: 'render-7', now: '2026-03-03T00:00:00.000Z' });
+ expect(r).toMatchObject({
+ id: 'render-7', audioFilename: 'a.wav', engine: 'musicgen', authoredPrompt: 'source prompt',
+ instrumentalOnly: true, createdAt: '2026-03-03T00:00:00.000Z',
+ });
});
it('selectRenderPatch points the active fields at the chosen render, not prompt/lyrics', () => {