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 lyric-aware MiniMax music duration

[._.]/ Adam Eivy49971f64ce49
diff --git a/.changelog/next/changed-music-auto-duration.md b/.changelog/next/changed-music-auto-duration.md
new file mode 100644
index 0000000000..79c6879d00
--- /dev/null
+++ b/.changelog/next/changed-music-auto-duration.md
@@ -0,0 +1 @@
+- MiniMax Music 3 now offers a lyric-aware Auto duration mode that leaves room for intro/outro sections, warns when a manual ceiling is too short, and recomputes the recommendation server-side.
diff --git a/client/src/components/music/MusicGenPanel.jsx b/client/src/components/music/MusicGenPanel.jsx
index 1818dbcb53..3c3b566aad 100644
--- a/client/src/components/music/MusicGenPanel.jsx
+++ b/client/src/components/music/MusicGenPanel.jsx
@@ -16,6 +16,8 @@ import { useEffect, useMemo, useState } from 'react';
import useMounted from '../../hooks/useMounted';
import { Loader2, Wand2, Download, X } from 'lucide-react';
import toast from '../ui/Toast';
+import { analyzeMusicLyrics } from '../../lib/musicDuration.js';
+import { formatDurationSec } from '../../utils/formatters.js';
import {
listMusicEngines, generateMusic, installAudioModel, removeAudioModel,
} from '../../services/api';
@@ -33,12 +35,20 @@ function engineSetupMessage(engine) {
return `${engine.name} is not installed yet. Install the runtime to enable generation.`;
}
+function supportsAutoDuration(engine) {
+ // The server capability is authoritative: an older server may know the
+ // MiniMax engine but will silently fall back to its fixed default when it
+ // receives no lyric-aware duration implementation.
+ return engine?.autoDuration === true;
+}
+
export default function MusicGenPanel({ track, title = '', artistId = '', artist = '', albumId = '', prompt, lyrics, onGenerated, remix }) {
const [engines, setEngines] = useState([]);
const [loading, setLoading] = useState(true);
const [engineId, setEngineId] = useState('');
const [modelId, setModelId] = useState('');
const [durationSec, setDurationSec] = useState(null);
+ const [durationMode, setDurationMode] = useState('auto');
const [generating, setGenerating] = useState(false);
const [generationElapsedSec, setGenerationElapsedSec] = useState(0);
// Inline HF model install.
@@ -76,6 +86,12 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
}, [generating]);
const engine = useMemo(() => engines.find((e) => e.id === engineId) || null, [engines, engineId]);
+ const autoDurationAvailable = supportsAutoDuration(engine);
+ const lyricDuration = useMemo(() => analyzeMusicLyrics(lyrics, {
+ minDurationSec: Math.max(60, engine?.defaultDurationSec || 60),
+ maxDurationSec: engine?.maxDurationSec || 300,
+ }), [lyrics, engine?.defaultDurationSec, engine?.maxDurationSec]);
+ const usingAutoDuration = autoDurationAvailable && durationMode === 'auto';
// Remix: seed the engine / model / duration from a past render. Keyed on
// `remix.nonce` (bumped per Remix click) so re-clicking the SAME render
@@ -88,7 +104,11 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
if (!remix) return;
if (remix.engineId) setEngineId(remix.engineId);
if (remix.modelId) setModelId(remix.modelId);
- if (remix.durationSec != null) setDurationSec(remix.durationSec);
+ if (remix.durationSec != null) {
+ setDurationSec(remix.durationSec);
+ // Remix means "recreate this take"; preserve its exact manual ceiling.
+ setDurationMode('manual');
+ }
}, [remix?.nonce]);
// Keep the model selection valid for the current engine: reset to the engine
@@ -142,7 +162,8 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
body.artist = artist;
body.albumId = albumId;
}
- if (Number.isFinite(durationSec)) body.durationSec = durationSec;
+ if (usingAutoDuration) body.durationMode = 'auto';
+ else if (Number.isFinite(durationSec)) body.durationSec = durationSec;
const res = await generateMusic(body, { silent: true }).catch((err) => { toast.error(err.message || 'Generation failed'); return null; });
if (!mountedRef.current) return;
setGenerating(false);
@@ -229,19 +250,68 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist
</label>
</div>
- <label className="block">
- <span className="block text-[11px] uppercase tracking-wider text-gray-500 mb-1">
- Duration (s){engine ? ` — ${engine.minDurationSec}–${engine.maxDurationSec}` : ''}
- </span>
- <input
- type="number"
- value={durationSec ?? ''}
- min={engine?.minDurationSec}
- max={engine?.maxDurationSec}
- onChange={(e) => setDurationSec(e.target.value === '' ? null : Number(e.target.value))}
- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
- />
- </label>
+ <div className={autoDurationAvailable ? 'grid grid-cols-2 gap-2' : undefined}>
+ {autoDurationAvailable ? (
+ <label className="block">
+ <span className="block text-[11px] uppercase tracking-wider text-gray-500 mb-1">Duration mode</span>
+ <select
+ id="musicgen-duration-mode"
+ value={durationMode}
+ onChange={(e) => setDurationMode(e.target.value)}
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
+ >
+ <option value="auto">Auto — let MiniMax choose</option>
+ <option value="manual">Manual</option>
+ </select>
+ </label>
+ ) : null}
+ <label className="block">
+ <span className="block text-[11px] uppercase tracking-wider text-gray-500 mb-1">
+ Duration (s){engine ? ` — ${engine.minDurationSec}–${engine.maxDurationSec}` : ''}
+ </span>
+ <input
+ id="musicgen-duration"
+ type="number"
+ value={usingAutoDuration ? lyricDuration.suggestedDurationSec : (durationSec ?? '')}
+ min={engine?.minDurationSec}
+ max={engine?.maxDurationSec}
+ disabled={usingAutoDuration}
+ onChange={(e) => {
+ setDurationMode('manual');
+ setDurationSec(e.target.value === '' ? null : Number(e.target.value));
+ }}
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm disabled:opacity-70"
+ />
+ </label>
+ </div>
+
+ {autoDurationAvailable ? (
+ <div className="rounded-lg border border-port-accent/20 bg-port-accent/5 px-3 py-2 text-[11px]">
+ {lyricDuration.hasLyrics ? (
+ <p className="text-gray-300">
+ Auto sets a <span className="font-medium text-port-accent">{formatDurationSec(lyricDuration.suggestedDurationSec)}</span> ceiling from {lyricDuration.wordCount} lyric words {lyricDuration.sectionCount > 0 ? <>across {lyricDuration.sectionCount} tagged section{lyricDuration.sectionCount === 1 ? '' : 's'}</> : 'with no tagged sections detected'}, with room for the ending. MiniMax may finish earlier when the composition resolves.
+ </p>
+ ) : (
+ <p className="text-gray-300">
+ Auto uses a {formatDurationSec(lyricDuration.suggestedDurationSec)} ceiling because there is no lyric text to measure; MiniMax may finish earlier.
+ </p>
+ )}
+ {lyricDuration.sectionCount === 0 && lyricDuration.hasLyrics ? (
+ <p className="mt-1 text-gray-500">No structured lyric sections detected. Add tags such as [intro], [verse], [chorus], and [outro] so MiniMax can pace the composition more reliably.</p>
+ ) : null}
+ {lyricDuration.sectionCount > 0 && !lyricDuration.hasOutro && lyricDuration.hasLyrics ? (
+ <p className="mt-1 text-gray-500">No [outro] section detected. Auto leaves extra room, but an explicit [outro] marker gives the ending clearer structure.</p>
+ ) : null}
+ {lyricDuration.isCapped ? (
+ <p className="mt-1 text-port-warning">These lyrics estimate beyond MiniMax’s five-minute limit, so the final lines may still need to be shortened or split into another render.</p>
+ ) : null}
+ </div>
+ ) : null}
+ {autoDurationAvailable && !usingAutoDuration && lyricDuration.hasLyrics && Number.isFinite(durationSec) && durationSec < lyricDuration.suggestedDurationSec ? (
+ <p className="text-[11px] text-port-warning">
+ This manual ceiling is shorter than the lyric estimate ({formatDurationSec(lyricDuration.suggestedDurationSec)}); the last section or outro may be cut off.
+ </p>
+ ) : null}
{showRuntimeInstallHint ? (
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 rounded-lg border border-port-warning/30 bg-port-warning/10 px-3 py-2">
diff --git a/client/src/components/music/MusicGenPanel.test.jsx b/client/src/components/music/MusicGenPanel.test.jsx
index dc779352d0..e4ea9a8f5a 100644
--- a/client/src/components/music/MusicGenPanel.test.jsx
+++ b/client/src/components/music/MusicGenPanel.test.jsx
@@ -154,6 +154,100 @@ describe('MusicGenPanel', () => {
expect(onGenerated).toHaveBeenCalledWith(expect.objectContaining({ id: 'generated-track' }));
});
+ it('suggests a lyric-aware MiniMax ceiling and sends Auto mode', async () => {
+ api.listMusicEngines.mockResolvedValue({
+ defaultEngine: 'minimax-music3',
+ engines: [engine({
+ id: 'minimax-music3',
+ name: 'MiniMax Music 3 (CUDA only)',
+ autoDuration: true,
+ lyrics: true,
+ maxDurationSec: 300,
+ defaultDurationSec: 60,
+ models: [{ id: 'minimax-music3', repo: 'MiniMaxAI/MiniMax-Music3', name: 'MiniMax Music 3' }],
+ defaultModelId: 'minimax-music3',
+ })],
+ });
+ api.generateMusic.mockResolvedValue({ track: { id: 'track-auto' } });
+
+ const lyrics = `[verse]\n${'word '.repeat(150)}\n[outro]`;
+ render(<MusicGenPanel track={{ id: 'track-1' }} prompt="warm cinematic pop" lyrics={lyrics} />);
+
+ expect(await screen.findByRole('combobox', { name: /duration mode/i })).toHaveValue('auto');
+ expect(screen.getByLabelText(/duration \(s\)/i)).toHaveValue(120);
+ expect(screen.getByText(/ceiling from 150 lyric words/i)).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: /^generate$/i }));
+ await waitFor(() => expect(api.generateMusic).toHaveBeenCalledWith(expect.objectContaining({
+ durationMode: 'auto',
+ }), { silent: true }));
+ expect(api.generateMusic.mock.calls[0][0]).not.toHaveProperty('durationSec');
+ });
+
+ it('does not advertise Auto mode when the server omits the capability', async () => {
+ api.listMusicEngines.mockResolvedValue({
+ defaultEngine: 'minimax-music3',
+ engines: [engine({
+ id: 'minimax-music3',
+ name: 'MiniMax Music 3 (CUDA only)',
+ lyrics: true,
+ maxDurationSec: 300,
+ defaultDurationSec: 60,
+ models: [{ id: 'minimax-music3', repo: 'MiniMaxAI/MiniMax-Music3', name: 'MiniMax Music 3' }],
+ defaultModelId: 'minimax-music3',
+ })],
+ });
+
+ render(<MusicGenPanel track={{ id: 'track-1' }} prompt="warm cinematic pop" lyrics="Long lyric text" />);
+
+ await screen.findByRole('combobox', { name: /engine/i });
+ expect(screen.queryByRole('combobox', { name: /duration mode/i })).not.toBeInTheDocument();
+ expect(screen.getByLabelText(/duration \(s\)/i)).not.toBeDisabled();
+ });
+
+ it('warns when lyric text has no structure tags for MiniMax to pace', async () => {
+ api.listMusicEngines.mockResolvedValue({
+ defaultEngine: 'minimax-music3',
+ engines: [engine({
+ id: 'minimax-music3',
+ name: 'MiniMax Music 3 (CUDA only)',
+ autoDuration: true,
+ lyrics: true,
+ maxDurationSec: 300,
+ defaultDurationSec: 60,
+ models: [{ id: 'minimax-music3', repo: 'MiniMaxAI/MiniMax-Music3', name: 'MiniMax Music 3' }],
+ defaultModelId: 'minimax-music3',
+ })],
+ });
+
+ render(<MusicGenPanel track={{ id: 'track-1' }} prompt="warm cinematic pop" lyrics="plain lyric text without sections" />);
+
+ expect(await screen.findByText(/no structured lyric sections detected/i)).toBeInTheDocument();
+ });
+
+ it('warns when a manual MiniMax duration is shorter than the lyric recommendation', async () => {
+ api.listMusicEngines.mockResolvedValue({
+ defaultEngine: 'minimax-music3',
+ engines: [engine({
+ id: 'minimax-music3',
+ name: 'MiniMax Music 3 (CUDA only)',
+ autoDuration: true,
+ lyrics: true,
+ maxDurationSec: 300,
+ defaultDurationSec: 60,
+ models: [{ id: 'minimax-music3', repo: 'MiniMaxAI/MiniMax-Music3', name: 'MiniMax Music 3' }],
+ defaultModelId: 'minimax-music3',
+ })],
+ });
+
+ const lyrics = `[verse]\n${'word '.repeat(150)}\n[outro]`;
+ render(<MusicGenPanel track={{ id: 'track-1' }} prompt="warm cinematic pop" lyrics={lyrics} />);
+
+ fireEvent.change(await screen.findByRole('combobox', { name: /duration mode/i }), { target: { value: 'manual' } });
+ fireEvent.change(screen.getByLabelText(/duration \(s\)/i), { target: { value: '60' } });
+ expect(screen.getByText(/shorter than the lyric estimate/i)).toBeInTheDocument();
+ });
+
it('names the host requirement and hides Install for a platform-gated engine', async () => {
// MusicGen is MLX-only. Before this, a Windows/Linux user got an Install
// button whose installer skipped and exited 0, surfaced as 'installer exited
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 0aa32a61fb..9af74cc654 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -49,6 +49,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `runnerFamilies.js` | Mirror of `server/lib/runners.js`. |
| `slashdoCatalog.js` | Mirror of `server/lib/slashdoCatalog.js` — the launchable slashdo workflows (`SLASHDO_WORKFLOWS`, `slashdoWorkflowsForApp(isSwiftApp)`, `SLASHDO_APP_TYPES`) driving the app-overview Agent Operations buttons. Adds only the per-button Tailwind classes; pinned by `server/lib/slashdoCatalog.test.js`. |
| `issueLength.js` | Mirror of `server/lib/issueLength.js`. |
+| `musicDuration.js` | Lyric-aware MiniMax Music 3 duration analysis: section/word detection, ending-cushioned auto-duration recommendations, and cap warnings. Mirrors `server/lib/musicDuration.js`. |
## Pipeline / image-gen defaults
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index b2aef058a6..17d01705c9 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -38,6 +38,7 @@ export * from './imageTo3dReasons.js';
export * from './importerDeepLink.js';
export * from './letteringDensity.js';
export * from './issueLength.js';
+export * from './musicDuration.js';
export * from './muscriptorModels.js';
export * from './pipelineImageDefaults.js';
export * from './reverseOutlineGrid.js';
diff --git a/client/src/lib/musicDuration.js b/client/src/lib/musicDuration.js
new file mode 100644
index 0000000000..c11598cc39
--- /dev/null
+++ b/client/src/lib/musicDuration.js
@@ -0,0 +1,87 @@
+// Client-side mirror of `server/lib/musicDuration.js`. MiniMax Music 3 treats
+// audio_duration as a ceiling, so the recommendation deliberately includes
+// phrase/section space and an ending cushion instead of equating word count to
+// the final audio length.
+
+import { countWords } from '../utils/formatters.js';
+
+export const MINIMAX_AUTO_MIN_DURATION_SEC = 60;
+export const MINIMAX_AUTO_MAX_DURATION_SEC = 300;
+export const MINIMAX_AUTO_DURATION_STEP_SEC = 10;
+
+const SECONDS_PER_WORD = 0.5;
+const SECONDS_PER_LINE_BREAK = 0.25;
+const SECONDS_PER_SECTION_BREAK = 3;
+const ENDING_CUSHION_SEC = 20;
+const SAFETY_MULTIPLIER = 1.2;
+
+function boundedNumber(value, fallback) {
+ return Number.isFinite(Number(value)) && Number(value) > 0 ? Number(value) : fallback;
+}
+
+function roundUp(value, step) {
+ return Math.ceil(value / step) * step;
+}
+
+/**
+ * Analyze structured song lyrics without changing the user's text.
+ *
+ * Tags are recognized when they start a line (`[verse]`, `[outro]`, etc.). A
+ * tag with text after it still contributes that text to the word count. The
+ * returned `estimatedDurationSec` is intentionally allowed to exceed the
+ * engine maximum so the UI can explain when the model's hard ceiling may still
+ * be too short.
+ */
+export function analyzeMusicLyrics(lyrics, options = {}) {
+ const minDurationSec = boundedNumber(options.minDurationSec, MINIMAX_AUTO_MIN_DURATION_SEC);
+ const maxDurationSec = Math.max(minDurationSec, boundedNumber(options.maxDurationSec, MINIMAX_AUTO_MAX_DURATION_SEC));
+ const lines = typeof lyrics === 'string' ? lyrics.split(/\r?\n/) : [];
+ const contentLines = [];
+ let sectionCount = 0;
+ let hasOutro = false;
+
+ for (const rawLine of lines) {
+ const line = rawLine.trim();
+ if (!line) continue;
+ const tagged = line.match(/^\[([^\]\r\n]+)\]\s*(.*)$/);
+ if (tagged) {
+ sectionCount += 1;
+ if (/^outro\b/i.test(tagged[1].trim())) hasOutro = true;
+ if (tagged[2].trim()) contentLines.push(tagged[2].trim());
+ continue;
+ }
+ contentLines.push(line);
+ }
+
+ const wordCount = countWords(contentLines.join('\n'));
+ const contentLineCount = contentLines.length;
+ const effectiveSectionCount = Math.max(1, sectionCount);
+ const hasLyrics = wordCount > 0;
+ const estimatedDurationSec = hasLyrics
+ ? Math.ceil((
+ wordCount * SECONDS_PER_WORD
+ + Math.max(0, contentLineCount - 1) * SECONDS_PER_LINE_BREAK
+ + Math.max(0, effectiveSectionCount - 1) * SECONDS_PER_SECTION_BREAK
+ + ENDING_CUSHION_SEC
+ ) * SAFETY_MULTIPLIER)
+ : minDurationSec;
+ const suggestedDurationSec = Math.max(
+ minDurationSec,
+ Math.min(maxDurationSec, roundUp(estimatedDurationSec, MINIMAX_AUTO_DURATION_STEP_SEC)),
+ );
+
+ return {
+ hasLyrics,
+ wordCount,
+ contentLineCount,
+ sectionCount,
+ hasOutro,
+ estimatedDurationSec,
+ suggestedDurationSec,
+ isCapped: hasLyrics && estimatedDurationSec > maxDurationSec,
+ };
+}
+
+export function recommendMinimaxDurationSec(lyrics, options = {}) {
+ return analyzeMusicLyrics(lyrics, options).suggestedDurationSec;
+}
diff --git a/client/src/lib/musicDuration.test.js b/client/src/lib/musicDuration.test.js
new file mode 100644
index 0000000000..7ad5907a77
--- /dev/null
+++ b/client/src/lib/musicDuration.test.js
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest';
+import {
+ analyzeMusicLyrics,
+ recommendMinimaxDurationSec,
+ MINIMAX_AUTO_MAX_DURATION_SEC,
+ MINIMAX_AUTO_MIN_DURATION_SEC,
+} from './musicDuration.js';
+
+describe('music duration recommendations', () => {
+ it('uses lyrics and section structure to leave room for an ending', () => {
+ const short = analyzeMusicLyrics('[verse]\nrain on the window');
+ const long = analyzeMusicLyrics('[verse]\n' + 'word '.repeat(180) + '\n[chorus]\n' + 'sing '.repeat(80) + '\n[outro]');
+
+ expect(short.hasLyrics).toBe(true);
+ expect(short.sectionCount).toBe(1);
+ expect(short.hasOutro).toBe(false);
+ expect(long.sectionCount).toBe(3);
+ expect(long.hasOutro).toBe(true);
+ expect(long.suggestedDurationSec).toBeGreaterThan(short.suggestedDurationSec);
+ });
+
+ it('recognizes inline tag text as lyrics rather than dropping it', () => {
+ const result = analyzeMusicLyrics('[verse] keep this line\nplain words\n[outro] last line');
+
+ expect(result.wordCount).toBe(7);
+ expect(result.sectionCount).toBe(2);
+ expect(result.hasOutro).toBe(true);
+ });
+
+ it('falls back to the engine default when there is no lyric text', () => {
+ expect(recommendMinimaxDurationSec('[intro]\n[outro]')).toBe(MINIMAX_AUTO_MIN_DURATION_SEC);
+ expect(recommendMinimaxDurationSec(' ')).toBe(MINIMAX_AUTO_MIN_DURATION_SEC);
+ });
+
+ it('caps the recommendation while exposing that the lyrics exceed the cap', () => {
+ const result = analyzeMusicLyrics('word '.repeat(2000));
+
+ expect(result.suggestedDurationSec).toBe(MINIMAX_AUTO_MAX_DURATION_SEC);
+ expect(result.isCapped).toBe(true);
+ expect(result.estimatedDurationSec).toBeGreaterThan(MINIMAX_AUTO_MAX_DURATION_SEC);
+ });
+
+ it('accepts custom engine bounds for mirrored server behavior', () => {
+ const result = analyzeMusicLyrics('one two three', { minDurationSec: 12, maxDurationSec: 30 });
+
+ expect(result.suggestedDurationSec).toBe(30);
+ });
+});
diff --git a/client/src/services/apiMusic.js b/client/src/services/apiMusic.js
index 986dc503cd..e355dfaaba 100644
--- a/client/src/services/apiMusic.js
+++ b/client/src/services/apiMusic.js
@@ -10,6 +10,7 @@ import { request, maybeRedirectToLogin } from './apiCore.js';
export const listMusicEngines = (options = {}) => request('/music/engines', options);
// Generate a track. body: { prompt, lyrics?, 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 }`.
diff --git a/server/lib/README.md b/server/lib/README.md
index 1b731c2114..a249ed5299 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -290,6 +290,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `isVisionModel(model)` (string id or model card — prefers explicit `type:'vlm'`/`capabilities:['vision']` metadata, falls back to id regex; used by the LoRA captioner); `recommendEditorialModel(models)` ranks installed models for editorial review/editing. Pure. Mirror `isEmbeddingModel`/`isVisionModel` in `client/src/utils/providers.js`. |
| `loraDataset.js` | Pure helpers for character LoRA training datasets (`data/lora-datasets/`): `sanitizeLoraDataset` (collectionStore sanitizer), `deriveTriggerWord` (name → single-token slug with collision suffix), `prefixCaption` (idempotent trigger-word prefixing), `buildVariationMatrix` (deterministic view/pose/expression/outfit tuples for batch generation), `computeDatasetReadiness` (trainable gate: ≥`MIN_TRAINING_IMAGES` ready+captioned images, plus an advisory `recommended`/`quality` tier via `datasetQualityTier` nudging toward `RECOMMENDED_TRAINING_IMAGES`), `analyzeCaptionInvariants` (flags identity fragments repeated across ≥`INVARIANT_SHARE_THRESHOLD` of captions — those bind to the caption phrases instead of the trigger token, issue #1320) + `stripSharedFragments` (rewrite one caption with those fragments removed, trigger preserved). Prompt building + I/O live in `services/loraDatasetGenerate.js` / `services/loraDatasets.js`. |
| `issueLength.js` | Per-issue size targets fed into text stages. |
+| `musicDuration.js` | Lyric-aware MiniMax Music 3 duration analysis and ending-cushioned auto-duration recommendation; mirrors `client/src/lib/musicDuration.js`. |
| `learningVerdict.js` | The three-way success-criteria verdict a completed agent run carries on `result.validationPassed` (#4107). `true`/`false` = a declared criterion was met/missed; `null` = none declared (record the run, fall back to the exit code); `SKIP_LEARNING_VERDICT` = nothing ever evaluated the run, so task-learning must not record it at all (a programmatic-I/O output hook that bailed on `no-app`/`app-not-found`). `isSkipLearningVerdict(v)` gates the skip; `toValidationVerdict(v)` narrows anything non-boolean — including the sentinel — back to `null` for downstream telemetry. JSON-safe string (not a Symbol) because the verdict is persisted and read back by the learning backfill, and older readers already narrow on `typeof v === 'boolean'`. Pure. |
| `investigationTasks.js` | Investigation-task identity, the approval policy, and the auto-retry decision — shared by the producers (`services/investigationTaskProducer.js`), the reaper (`cosTaskStore.js`, which used to hand-copy the predicate to dodge an import cycle) and the retry (`services/investigationRetry.js`). `isInvestigationTask(task)` (durable `isInvestigation` marker, falling back to the `INVESTIGATION_HEADLINE_PREFIX` headline for pre-#2615 / peer-synced tasks); `buildInvestigationFingerprint(task, analysis)` / `investigationFingerprint({category, kind, scope})` → the `category:kind:scope` dedup key; `resolveInvestigationApproval({fingerprint, tasks, recentCreations})` → unattended by default (#3714), held only on a `repeat-fingerprint` or `failure-storm` loop, with `approvalReason` + `loopProse` for the queue UI; `couldReleaseBlockedTasks(investigation)` is the pure pre-read gate for `resolveInvestigationRetryTargets({investigation, tasksById})`, which returns the failure-blocked tasks a just-completed investigation releases plus every skip and its `RETRY_SKIP_REASONS` reason (an `auto-expired` completion, a non-`blocked` task, a `NON_AUTO_RETRY_BLOCK_CATEGORIES` block, or a task past `MAX_AUTO_RETRIES_PER_TASK`); `autoRetryMetadata(task, investigationId, now)` stamps the budget that survives the revive's own `failureCount` reset. Pure. |
| `mediaItemKey.js` | `<kind>:<ref>` key vocabulary for media items. |
diff --git a/server/lib/index.js b/server/lib/index.js
index eefb4a66ab..92bf49d989 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -269,6 +269,7 @@ export * from './localModelHeuristics.js';
export * from './ollamaContext.js';
export * from './loraDataset.js';
export * from './issueLength.js';
+export * from './musicDuration.js';
export * from './investigationTasks.js';
export * from './learningVerdict.js';
export * from './mediaItemKey.js';
diff --git a/server/lib/musicDuration.js b/server/lib/musicDuration.js
new file mode 100644
index 0000000000..b9a428bd1e
--- /dev/null
+++ b/server/lib/musicDuration.js
@@ -0,0 +1,82 @@
+// Server-side mirror of `client/src/lib/musicDuration.js`. MiniMax Music 3
+// treats audio_duration as a ceiling, so auto mode sizes that ceiling from the
+// lyric structure and leaves room for the composition to resolve.
+
+import { countWords } from './textUtils.js';
+
+export const MINIMAX_AUTO_MIN_DURATION_SEC = 60;
+export const MINIMAX_AUTO_MAX_DURATION_SEC = 300;
+export const MINIMAX_AUTO_DURATION_STEP_SEC = 10;
+
+const SECONDS_PER_WORD = 0.5;
+const SECONDS_PER_LINE_BREAK = 0.25;
+const SECONDS_PER_SECTION_BREAK = 3;
+const ENDING_CUSHION_SEC = 20;
+const SAFETY_MULTIPLIER = 1.2;
+
+function boundedNumber(value, fallback) {
+ return Number.isFinite(Number(value)) && Number(value) > 0 ? Number(value) : fallback;
+}
+
+function roundUp(value, step) {
+ return Math.ceil(value / step) * step;
+}
+
+/**
+ * Analyze structured song lyrics without changing the user's text. The
+ * returned estimate may exceed the engine maximum so callers can surface a
+ * truthful "lyrics may still be too long" warning.
+ */
+export function analyzeMusicLyrics(lyrics, options = {}) {
+ const minDurationSec = boundedNumber(options.minDurationSec, MINIMAX_AUTO_MIN_DURATION_SEC);
+ const maxDurationSec = Math.max(minDurationSec, boundedNumber(options.maxDurationSec, MINIMAX_AUTO_MAX_DURATION_SEC));
+ const lines = typeof lyrics === 'string' ? lyrics.split(/\r?\n/) : [];
+ const contentLines = [];
+ let sectionCount = 0;
+ let hasOutro = false;
+
+ for (const rawLine of lines) {
+ const line = rawLine.trim();
+ if (!line) continue;
+ const tagged = line.match(/^\[([^\]\r\n]+)\]\s*(.*)$/);
+ if (tagged) {
+ sectionCount += 1;
+ if (/^outro\b/i.test(tagged[1].trim())) hasOutro = true;
+ if (tagged[2].trim()) contentLines.push(tagged[2].trim());
+ continue;
+ }
+ contentLines.push(line);
+ }
+
+ const wordCount = countWords(contentLines.join('\n'));
+ const contentLineCount = contentLines.length;
+ const effectiveSectionCount = Math.max(1, sectionCount);
+ const hasLyrics = wordCount > 0;
+ const estimatedDurationSec = hasLyrics
+ ? Math.ceil((
+ wordCount * SECONDS_PER_WORD
+ + Math.max(0, contentLineCount - 1) * SECONDS_PER_LINE_BREAK
+ + Math.max(0, effectiveSectionCount - 1) * SECONDS_PER_SECTION_BREAK
+ + ENDING_CUSHION_SEC
+ ) * SAFETY_MULTIPLIER)
+ : minDurationSec;
+ const suggestedDurationSec = Math.max(
+ minDurationSec,
+ Math.min(maxDurationSec, roundUp(estimatedDurationSec, MINIMAX_AUTO_DURATION_STEP_SEC)),
+ );
+
+ return {
+ hasLyrics,
+ wordCount,
+ contentLineCount,
+ sectionCount,
+ hasOutro,
+ estimatedDurationSec,
+ suggestedDurationSec,
+ isCapped: hasLyrics && estimatedDurationSec > maxDurationSec,
+ };
+}
+
+export function recommendMinimaxDurationSec(lyrics, options = {}) {
+ return analyzeMusicLyrics(lyrics, options).suggestedDurationSec;
+}
diff --git a/server/lib/musicDuration.test.js b/server/lib/musicDuration.test.js
new file mode 100644
index 0000000000..7ad5907a77
--- /dev/null
+++ b/server/lib/musicDuration.test.js
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest';
+import {
+ analyzeMusicLyrics,
+ recommendMinimaxDurationSec,
+ MINIMAX_AUTO_MAX_DURATION_SEC,
+ MINIMAX_AUTO_MIN_DURATION_SEC,
+} from './musicDuration.js';
+
+describe('music duration recommendations', () => {
+ it('uses lyrics and section structure to leave room for an ending', () => {
+ const short = analyzeMusicLyrics('[verse]\nrain on the window');
+ const long = analyzeMusicLyrics('[verse]\n' + 'word '.repeat(180) + '\n[chorus]\n' + 'sing '.repeat(80) + '\n[outro]');
+
+ expect(short.hasLyrics).toBe(true);
+ expect(short.sectionCount).toBe(1);
+ expect(short.hasOutro).toBe(false);
+ expect(long.sectionCount).toBe(3);
+ expect(long.hasOutro).toBe(true);
+ expect(long.suggestedDurationSec).toBeGreaterThan(short.suggestedDurationSec);
+ });
+
+ it('recognizes inline tag text as lyrics rather than dropping it', () => {
+ const result = analyzeMusicLyrics('[verse] keep this line\nplain words\n[outro] last line');
+
+ expect(result.wordCount).toBe(7);
+ expect(result.sectionCount).toBe(2);
+ expect(result.hasOutro).toBe(true);
+ });
+
+ it('falls back to the engine default when there is no lyric text', () => {
+ expect(recommendMinimaxDurationSec('[intro]\n[outro]')).toBe(MINIMAX_AUTO_MIN_DURATION_SEC);
+ expect(recommendMinimaxDurationSec(' ')).toBe(MINIMAX_AUTO_MIN_DURATION_SEC);
+ });
+
+ it('caps the recommendation while exposing that the lyrics exceed the cap', () => {
+ const result = analyzeMusicLyrics('word '.repeat(2000));
+
+ expect(result.suggestedDurationSec).toBe(MINIMAX_AUTO_MAX_DURATION_SEC);
+ expect(result.isCapped).toBe(true);
+ expect(result.estimatedDurationSec).toBeGreaterThan(MINIMAX_AUTO_MAX_DURATION_SEC);
+ });
+
+ it('accepts custom engine bounds for mirrored server behavior', () => {
+ const result = analyzeMusicLyrics('one two three', { minDurationSec: 12, maxDurationSec: 30 });
+
+ expect(result.suggestedDurationSec).toBe(30);
+ });
+});
diff --git a/server/routes/music.js b/server/routes/music.js
index 82548fe322..37cef3d298 100644
--- a/server/routes/music.js
+++ b/server/routes/music.js
@@ -46,9 +46,9 @@ import * as albums from '../services/albums/index.js';
const router = Router();
// GET /api/music/engines — every selectable backend with its models (shipped +
-// user-installed, merged), duration window, lyric capability, and a `ready` flag
-// (the opt-in venv is provisioned). The UI gates its Generate affordance + shows
-// the install hint from this.
+// user-installed, merged), duration window, lyric capability, auto-duration
+// support, and a `ready` flag (the opt-in venv is provisioned). The UI gates its
+// Generate affordance + shows the install hint from this.
router.get('/engines', asyncHandler(async (_req, res) => {
const cuda = await getCudaCapability();
const engines = await Promise.all(Object.values(ENGINES).map(async (engine) => {
@@ -66,6 +66,7 @@ router.get('/engines', asyncHandler(async (_req, res) => {
maxDurationSec: engine.maxDurationSec,
defaultDurationSec: engine.defaultDurationSec,
lyrics: engine.lyrics === true,
+ autoDuration: engine.autoDuration === true,
// Whether this engine can render an arbitrary HuggingFace checkpoint (gates
// the "install/select model" UI). ACE-Step resolves a single foundation
// checkpoint via checkpoint_dir, so custom repos don't apply to it.
@@ -359,6 +360,7 @@ const generateSchema = z.object({
engine: z.string().trim().max(60).optional(),
modelId: z.string().trim().max(120).optional(),
durationSec: z.number().positive().max(600).optional(),
+ durationMode: z.enum(['auto', 'manual']).optional(),
// Attach the result to an existing track (else a new one is created). The
// title seeds a freshly-created track; ignored when trackId is given.
trackId: z.string().trim().max(80).optional(),
@@ -420,6 +422,7 @@ router.post('/generate', asyncHandler(async (req, res) => {
modelId: body.modelId,
repo,
durationSec: body.durationSec,
+ durationMode: body.durationMode,
});
// Persist the audio + gen metadata. Lyrics follow the audio that was actually
diff --git a/server/routes/music.test.js b/server/routes/music.test.js
index 68ff6f3ce6..ac2f386677 100644
--- a/server/routes/music.test.js
+++ b/server/routes/music.test.js
@@ -23,7 +23,7 @@ vi.mock('../services/pipeline/musicGen.js', () => {
musicgen: { id: 'musicgen', name: 'MusicGen', models: [{ id: 'm', name: 'M' }], defaultModelId: 'm', minDurationSec: 1, maxDurationSec: 30, defaultDurationSec: 12, installEnv: 'INSTALL_MUSICGEN', venvDefault: '/v/mg', resolvePython: () => (gen.ready ? '/v/mg/bin/python3' : null), customModels: true },
acestep: { id: 'acestep', name: 'ACE-Step', models: [{ id: 'a', name: 'A' }], defaultModelId: 'a', minDurationSec: 1, maxDurationSec: 240, defaultDurationSec: 60, installEnv: 'INSTALL_ACESTEP', venvDefault: '/v/ace', resolvePython: () => (gen.ready ? '/v/ace/bin/python3' : null), lyrics: true, customModels: false },
acestep15: { id: 'acestep15', name: 'ACE-Step 1.5', models: [{ id: 'ace-step-v1.5', repo: 'ACE-Step/Ace-Step1.5', name: 'ACE-Step 1.5' }], defaultModelId: 'ace-step-v1.5', minDurationSec: 1, maxDurationSec: 240, defaultDurationSec: 60, installEnv: 'INSTALL_ACESTEP15', venvDefault: '/v/ace15', resolvePython: () => (gen.ready ? '/v/ace15/bin/python3' : null), lyrics: true, customModels: false, fixedModelInstall: true },
- 'minimax-music3': { id: 'minimax-music3', name: 'MiniMax Music 3', models: [{ id: 'minimax-music3', repo: 'MiniMaxAI/MiniMax-Music3', name: 'MiniMax Music 3' }], defaultModelId: 'minimax-music3', minDurationSec: 1, maxDurationSec: 300, defaultDurationSec: 60, installEnv: 'INSTALL_MINIMAX_MUSIC3', venvDefault: '/v/minimax', resolvePython: () => (gen.ready ? '/v/minimax/bin/python3' : null), lyrics: true, customModels: false, fixedModelInstall: true, cudaRequired: true },
+ 'minimax-music3': { id: 'minimax-music3', name: 'MiniMax Music 3', models: [{ id: 'minimax-music3', repo: 'MiniMaxAI/MiniMax-Music3', name: 'MiniMax Music 3' }], defaultModelId: 'minimax-music3', minDurationSec: 1, maxDurationSec: 300, defaultDurationSec: 60, installEnv: 'INSTALL_MINIMAX_MUSIC3', venvDefault: '/v/minimax', resolvePython: () => (gen.ready ? '/v/minimax/bin/python3' : null), lyrics: true, customModels: false, fixedModelInstall: true, cudaRequired: true, autoDuration: true },
};
return {
ENGINES,
@@ -271,6 +271,7 @@ describe('music routes', () => {
const mg = r.body.engines.find((e) => e.id === 'musicgen');
expect(mg.lyrics).toBe(false);
expect(mg.customModels).toBe(true);
+ expect(r.body.engines.find((e) => e.id === 'minimax-music3').autoDuration).toBe(true);
});
it('GET /engines reports readiness per engine', async () => {
@@ -442,6 +443,23 @@ describe('music routes', () => {
expect(r.body.filename).toBe('music-gen-x.wav');
});
+ it('POST /generate forwards MiniMax auto duration mode to the generator', async () => {
+ gen.generateMusic.mockResolvedValueOnce({ filename: 'music-gen-auto.wav', durationSec: 148, engine: 'minimax-music3', modelId: 'minimax-music3' });
+ const r = await request(app).post('/api/music/generate').send({
+ prompt: 'warm folk',
+ lyrics: `[verse]\n${'word '.repeat(180)}\n[outro]`,
+ engine: 'minimax-music3',
+ durationMode: 'auto',
+ });
+
+ expect(r.status).toBe(201);
+ expect(gen.generateMusic).toHaveBeenCalledWith(expect.objectContaining({
+ engine: 'minimax-music3',
+ lyrics: expect.stringContaining('[verse]'),
+ durationMode: 'auto',
+ }));
+ });
+
it('POST /generate with trackId updates the existing track (200)', async () => {
tracks.getTrack.mockResolvedValueOnce({ id: 'track-1', title: 'Existing' });
gen.generateMusic.mockResolvedValueOnce({ filename: 'music-gen-y.wav', durationSec: 30, engine: 'musicgen', modelId: 'm' });
diff --git a/server/services/pipeline/musicGen.js b/server/services/pipeline/musicGen.js
index 2dd864380f..02e9dfb6c9 100644
--- a/server/services/pipeline/musicGen.js
+++ b/server/services/pipeline/musicGen.js
@@ -49,6 +49,7 @@ import { getCudaCapability } from '../../lib/cudaCapability.js';
import { inspectModelCache } from '../../lib/hfCache.js';
import { ServerError } from '../../lib/errorHandler.js';
import { stripMarkdownEmphasis } from '../../lib/markdownText.js';
+import { recommendMinimaxDurationSec } from '../../lib/musicDuration.js';
import { safeChildProcessOptions } from '../../lib/processEnv.js';
const execFileAsync = promisify(execFile);
@@ -250,6 +251,9 @@ export const ENGINES = Object.freeze({
// The sheet is built per-render rather than fixed, because `audio_duration`
// is only a CEILING for this engine — see buildMinimaxInstrumentalLyrics.
instrumentalLyrics: buildMinimaxInstrumentalLyrics,
+ // Auto mode sizes that ceiling from lyric words/sections and leaves room
+ // for an ending. MiniMax may still stop earlier by design.
+ autoDuration: true,
customModels: false,
fixedModelInstall: true,
cudaRequired: true,
@@ -476,7 +480,7 @@ export function buildMusicGenArgs({ pythonPath, scriptPath = SIDECAR_SCRIPT, run
* flat timeout. Callers outside the queue (the Pipeline Audio routes) omit it
* and behave exactly as before.
*/
-export async function generateMusic({ prompt, lyrics, engine: engineId = DEFAULT_ENGINE_ID, durationSec, modelId, repo, signal, onActivity } = {}) {
+export async function generateMusic({ prompt, lyrics, engine: engineId = DEFAULT_ENGINE_ID, durationSec, durationMode, modelId, repo, signal, onActivity } = {}) {
const text = (prompt || '').trim();
if (!text) {
throw new ServerError('prompt is required', { status: 400, code: 'PIPELINE_MUSIC_EMPTY_PROMPT' });
@@ -491,7 +495,12 @@ export async function generateMusic({ prompt, lyrics, engine: engineId = DEFAULT
const model = repo
? { id: modelId || repo, repo, name: modelId || repo }
: shippedModel;
- const resolvedDuration = durationSec ?? engine.defaultDurationSec;
+ const resolvedDuration = durationMode === 'auto' && engine.autoDuration
+ ? recommendMinimaxDurationSec(lyrics, {
+ minDurationSec: engine.defaultDurationSec,
+ maxDurationSec: engine.maxDurationSec,
+ })
+ : durationSec ?? engine.defaultDurationSec;
const pythonPath = engine.resolvePython();
if (engine.cudaRequired) {
const cuda = await getCudaCapability();
diff --git a/server/services/pipeline/musicGen.test.js b/server/services/pipeline/musicGen.test.js
index e5b57da5ba..562f6539a3 100644
--- a/server/services/pipeline/musicGen.test.js
+++ b/server/services/pipeline/musicGen.test.js
@@ -4,6 +4,14 @@ import { join } from 'path';
import { rm, readdir } from 'fs/promises';
import { writeFileSync, mkdtempSync } from 'fs';
+vi.mock('../../lib/cudaCapability.js', () => ({
+ getCudaCapability: vi.fn(async () => ({ status: 'available', gpus: [], maxVramGb: null, error: null })),
+}));
+
+vi.mock('../../lib/hfCache.js', () => ({
+ inspectModelCache: vi.fn(async () => ({ cached: true })),
+}));
+
// ---- Pure-helper tests (no mocks needed) ---------------------------------
import {
buildMusicGenArgs,
@@ -301,6 +309,7 @@ const h = vi.hoisted(() => ({
mockWriteOutput: true,
musicgenPython: '/fake/venv-musicgen/bin/python3',
audioldm2Python: '/fake/venv-audioldm2/bin/python3',
+ minimaxMusic3Python: '/fake/venv-minimax-music3/bin/python3',
// isEngineHealthy's import probe: which interpreters it ran, and whether the
// import succeeded (a half-built venv exits non-zero).
probeCalls: [],
@@ -379,6 +388,7 @@ vi.mock('../../lib/pythonSetup.js', async () => {
...actual,
resolveMusicgenPython: () => h.musicgenPython,
resolveAudioldm2Python: () => h.audioldm2Python,
+ resolveMinimaxMusic3Python: () => h.minimaxMusic3Python,
};
});
@@ -393,6 +403,7 @@ beforeEach(() => {
h.mockStdout = 'STAGE:done\nRESULT:{"output":"x","durationSec":12.5,"sampleRate":32000}\n';
h.musicgenPython = '/fake/venv-musicgen/bin/python3';
h.audioldm2Python = '/fake/venv-audioldm2/bin/python3';
+ h.minimaxMusic3Python = '/fake/venv-minimax-music3/bin/python3';
h.probeCalls.length = 0;
h.probeOk = true;
h.osPlatform = 'darwin';
@@ -417,6 +428,18 @@ describe('generateMusic backend selection', () => {
expect(res.filename).toMatch(/^music-gen-.*\.wav$/);
});
+ it('sizes MiniMax auto mode from lyric length instead of using the 60-second default', async () => {
+ await generateMusic({
+ prompt: 'warm cinematic pop',
+ lyrics: `[verse]\n${'word '.repeat(150)}\n[outro]`,
+ engine: 'minimax-music3',
+ durationMode: 'auto',
+ });
+
+ const duration = spawnCalls[0].args[spawnCalls[0].args.indexOf('--duration') + 1];
+ expect(duration).toBe('120');
+ });
+
it('routes to the audioldm2 sidecar + venv when engine=audioldm2', async () => {
const res = await generateMusic({ prompt: 'ambient drone', engine: 'audioldm2', durationSec: 60 });
expect(spawnCalls).toHaveLength(1);