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

fix: pace MiniMax instrumental renders

[._.]/ Adam Eivy00f4a2fcb2d8
diff --git a/.changelog/next/fixed-codex-fix-minimax-music-duration.md b/.changelog/next/fixed-codex-fix-minimax-music-duration.md
new file mode 100644
index 0000000000..ae840a1b9d
--- /dev/null
+++ b/.changelog/next/fixed-codex-fix-minimax-music-duration.md
@@ -0,0 +1 @@
+- MiniMax Music 3 instrumental renders now pace their generated section sheet to the requested duration, and local music prompts reach text encoders without Markdown emphasis markers.
diff --git a/server/lib/README.md b/server/lib/README.md
index e66cc568b2..9f498f61a9 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -306,6 +306,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `postStreak.js` | Pure DST-safe POST practice-streak math — the single `computePostStreaks` implementation shared by scored sessions and the training log, plus `computeUnifiedStreak` (a day is active with EITHER a session or a practice entry), `normalizeYmd` (day-key prefix for a date that may be a full ISO timestamp), and `recordDayKey` / `withDerivedDayKeys` (re-derive a record's day key from its `startedAt`/`completedAt`/`timestamp` instant, so readers ignore a `date` frozen in a previously-configured timezone). |
| `activeDays.js` | Cross-domain "days active" set math (#4120) — `unionActiveDayKeys(sources, timezone)` unions several domains' stored date values into one sorted array of user-local `YYYY-MM-DD` keys (`.length` is the honest day count; summing per-domain counts would double-count any day logged in two domains), and `toUserDayKey(value, timezone)` is its per-value normalizer. Owns the day-boundary reconciliation between POST (stamps `userLocalToday()`) and the health logs (stamp the server-local `getDateString()`): a value carrying an INSTANT (the pre-#2681 full-ISO shape some legacy training entries still store) is re-keyed into the user's timezone rather than `split('T')[0]`'d to the UTC day, while a value that is already a bare day LABEL is taken as authored — there is no instant left to re-derive from, so retro-normalizing stored health keys is out of scope by construction, not by omission. Non-day values are dropped rather than coerced. Pure. |
| `planIds.js` | Utilities for PLAN.md `[slug]` IDs. |
+| `markdownText.js` | `stripMarkdownEmphasis(text)` — unwrap `**bold**` / `~~struck~~` / `` `code` `` / `[text](url)` and drop HTML comments, keeping the words. For strings handed to something that can't read markdown (a model's text encoder, a slug builder, TTS); leftover lone `*_~` become spaces so an unbalanced marker can't fuse two words. Does not collapse whitespace — callers that need that normalize themselves. |
| `renderSlot.js` | Render-slot helpers for `(proof\|final)Image` per stage. |
| `renderTargets.js` | Render-target alphabet (#3231): `RENDER_TARGET`/`RENDER_TARGETS` name every creative surface that enqueues renders (universe-bible, sprite-reference, music-video, …) — the keys into `settings.renderDefaults` — plus the `RENDER_TARGET_BACKEND_AUTO` fall-through sentinel. Dependency-free leaf; resolved per surface by `services/imageGen/cloudProviderConfig.js#resolveRenderTargetConfig`. |
| `telegramClient.js` | Telegram bot client. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 0b7f3f6c44..d9bf60229b 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -287,6 +287,7 @@ export * from './postTopics.js';
export * from './spacedRepetition.js';
export * from './songPractice.js';
export * from './planIds.js';
+export * from './markdownText.js';
export * from './renderSlot.js';
export * from './renderTargets.js';
export * from './telegramClient.js';
diff --git a/server/lib/markdownText.js b/server/lib/markdownText.js
new file mode 100644
index 0000000000..9ebd5af57c
--- /dev/null
+++ b/server/lib/markdownText.js
@@ -0,0 +1,33 @@
+/**
+ * Markdown → plain-text normalization for strings that are about to be handed
+ * to something that has no idea what markdown is (a model's text encoder, a
+ * slug builder, a TTS engine).
+ *
+ * The motivating case: prompts authored in a markdown-ish textarea reach a
+ * text-to-audio sidecar with their `**emphasis**` intact, and the encoder
+ * tokenizes the asterisks as literal content — conditioning noise the author
+ * never intended to write.
+ */
+
+/**
+ * Strip common markdown wrappers, keeping the words inside them.
+ * - `**bold**` → `bold`
+ * - `~~struck~~` → `struck`
+ * - `` `code` `` → `code`
+ * - `[text](url)` → `text`
+ * - HTML comments → removed
+ *
+ * Leftover lone `*`/`_`/`~` become spaces rather than being deleted, so an
+ * unbalanced marker can't fuse two words together. Whitespace is NOT collapsed
+ * here — callers that care (slug builders) normalize it themselves, and
+ * callers that don't (prompt text) keep their line structure intact.
+ */
+export function stripMarkdownEmphasis(text) {
+ return String(text ?? '')
+ .replace(/<!--[\s\S]*?-->/g, ' ')
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
+ .replace(/`([^`]*)`/g, '$1')
+ .replace(/\*\*([^*]+)\*\*/g, '$1')
+ .replace(/~~([^~]+)~~/g, '$1')
+ .replace(/[*_~]/g, ' ');
+}
diff --git a/server/lib/markdownText.test.js b/server/lib/markdownText.test.js
new file mode 100644
index 0000000000..16c959a62f
--- /dev/null
+++ b/server/lib/markdownText.test.js
@@ -0,0 +1,35 @@
+import { describe, it, expect } from 'vitest';
+import { stripMarkdownEmphasis } from './markdownText.js';
+
+describe('stripMarkdownEmphasis', () => {
+ it('unwraps the common inline markers, keeping the words', () => {
+ expect(stripMarkdownEmphasis('a **bold** claim')).toBe('a bold claim');
+ expect(stripMarkdownEmphasis('a ~~struck~~ claim')).toBe('a struck claim');
+ expect(stripMarkdownEmphasis('a `code` claim')).toBe('a code claim');
+ expect(stripMarkdownEmphasis('see [the docs](https://example.com)')).toBe('see the docs');
+ });
+
+ it('drops HTML comments entirely', () => {
+ expect(stripMarkdownEmphasis('keep<!-- drop me -->this').trim()).toBe('keep this');
+ });
+
+ it('turns an unbalanced marker into a space so words cannot fuse', () => {
+ // `a*b` must not become `ab` — that invents a word the author never wrote.
+ expect(stripMarkdownEmphasis('a*b')).toBe('a b');
+ expect(stripMarkdownEmphasis('snake_case_name')).toBe('snake case name');
+ });
+
+ it('leaves plain text and its whitespace untouched', () => {
+ const prose = 'Genre: acoustic pop.\nBPM: 96.\n Warm and intimate.';
+ expect(stripMarkdownEmphasis(prose)).toBe(prose);
+ });
+
+ it('coerces non-strings instead of throwing', () => {
+ for (const input of [undefined, null, 0, false]) {
+ expect(() => stripMarkdownEmphasis(input)).not.toThrow();
+ }
+ expect(stripMarkdownEmphasis(undefined)).toBe('');
+ expect(stripMarkdownEmphasis(null)).toBe('');
+ expect(stripMarkdownEmphasis(42)).toBe('42');
+ });
+});
diff --git a/server/lib/planIds.js b/server/lib/planIds.js
index 07b7e27bf6..c78bd18e5a 100644
--- a/server/lib/planIds.js
+++ b/server/lib/planIds.js
@@ -23,6 +23,7 @@
*/
import { execGit } from './execGit.js';
+import { stripMarkdownEmphasis } from './markdownText.js';
import { spawn } from 'child_process';
const SLUG_MAX_LEN = 50;
@@ -30,24 +31,6 @@ const CHECKBOX_RE = /^(?<indent>\s*)-\s+\[(?<box>[ xX])\]\s+(?:\[(?<id>[a-z0-9][
const NEEDS_INPUT_RE = /<!--\s*NEEDS_INPUT\s*-->/;
const DRIFT_LINE_RE = /^\s*>\s*⚠️\s*DRIFT:/;
-/**
- * Strip common markdown wrappers from a title fragment.
- * - `**bold**` → `bold`
- * - `~~struck~~` → `struck`
- * - `` `code` `` → `code`
- * - `[text](url)` → `text`
- * - HTML comments → removed
- */
-function stripMarkdown(text) {
- return text
- .replace(/<!--[\s\S]*?-->/g, ' ')
- .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
- .replace(/`([^`]*)`/g, '$1')
- .replace(/\*\*([^*]+)\*\*/g, '$1')
- .replace(/~~([^~]+)~~/g, '$1')
- .replace(/[*_~]/g, ' ');
-}
-
/**
* Lowercase + kebab-case a string, ASCII-only, collapse repeats.
*/
@@ -77,7 +60,7 @@ function truncateOnBoundary(slug, max) {
*/
export function slugify(title, takenIds = new Set()) {
const taken = takenIds instanceof Set ? takenIds : new Set(takenIds);
- const base = truncateOnBoundary(kebab(stripMarkdown(String(title || ''))), SLUG_MAX_LEN) || 'item';
+ const base = truncateOnBoundary(kebab(stripMarkdownEmphasis(title)), SLUG_MAX_LEN) || 'item';
if (!taken.has(base)) return base;
// Collision: append -2, -3, ... — keep the suffix inside SLUG_MAX_LEN.
for (let n = 2; n < 10000; n++) {
diff --git a/server/services/pipeline/musicGen.js b/server/services/pipeline/musicGen.js
index d724640d7b..4a019d95c1 100644
--- a/server/services/pipeline/musicGen.js
+++ b/server/services/pipeline/musicGen.js
@@ -48,6 +48,7 @@ import {
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 { safeChildProcessEnv } from '../../lib/processEnv.js';
const execFileAsync = promisify(execFile);
@@ -245,7 +246,10 @@ export const ENGINES = Object.freeze({
// a structure-tag-only lyric sheet, and `[Instrumental]` is one of its
// documented section tags. Engines without this field (ACE-Step) accept an
// empty string and render an instrumental themselves.
- instrumentalLyrics: '[instrumental]',
+ //
+ // The sheet is built per-render rather than fixed, because `audio_duration`
+ // is only a CEILING for this engine — see buildMinimaxInstrumentalLyrics.
+ instrumentalLyrics: buildMinimaxInstrumentalLyrics,
customModels: false,
fixedModelInstall: true,
cudaRequired: true,
@@ -368,6 +372,45 @@ export function clampDuration(durationSec, engineId = DEFAULT_ENGINE_ID) {
return Math.max(engine.minDurationSec, Math.min(engine.maxDurationSec, n));
}
+// Section tags for a MiniMax Music 3 instrumental body, cycled to pad the sheet
+// out. Restricted to the tags the model card documents, and to the ones that
+// don't imply a vocal line ([verse]/[chorus] would) — an instrumental render
+// should not coax the model into singing.
+const MINIMAX_INSTRUMENTAL_BODY = Object.freeze(['instrumental', 'bridge', 'instrumental', 'solo']);
+// Roughly how much audio one body section buys. Deliberately pessimistic:
+// `audio_duration` still truncates hard at the requested length, so an
+// over-provisioned sheet costs nothing while an under-provisioned one is the
+// bug this exists to fix.
+const MINIMAX_SEC_PER_SECTION = 20;
+const MINIMAX_MAX_BODY_SECTIONS = 12;
+
+/**
+ * Build MiniMax Music 3's structure-tag lyric sheet for an instrumental render,
+ * sized to the requested duration.
+ *
+ * MiniMax Music 3 treats `audio_duration` as an UPPER BOUND, not a target: its
+ * global LLM emits `<|audio_end|>` whenever it decides the piece is finished
+ * and the autoregressive loop breaks there (see the diffusers
+ * `MiniMaxMusic3AutoregressiveStep` — "The language model may stop earlier").
+ * What actually paces the song is the lyric sheet's section tags. A one-tag
+ * sheet is one section long, so a 60s request came back at 25s. Giving
+ * the model a section count proportionate to the ask is the only lever the
+ * architecture exposes — and per the model card, tags are "generative control
+ * rather than strict symbolic guarantees", so this raises the expected length
+ * without promising it.
+ */
+export function buildMinimaxInstrumentalLyrics(durationSec) {
+ const seconds = clampDuration(durationSec, 'minimax-music3');
+ // The intro and outro carry their own runtime, so only the remainder needs
+ // body sections. At least one body section always survives the floor.
+ const bodyCount = Math.min(
+ MINIMAX_MAX_BODY_SECTIONS,
+ Math.max(1, Math.ceil((seconds - MINIMAX_SEC_PER_SECTION) / MINIMAX_SEC_PER_SECTION)),
+ );
+ const body = Array.from({ length: bodyCount }, (_, i) => MINIMAX_INSTRUMENTAL_BODY[i % MINIMAX_INSTRUMENTAL_BODY.length]);
+ return ['intro', ...body, 'outro'].map((tag) => `[${tag}]`).join('\n');
+}
+
/**
* Build the `{ bin, args }` for a backend's sidecar. Pure — unit-tested without
* spawning Python. All sidecars share the same base flag contract
@@ -379,20 +422,29 @@ export function clampDuration(durationSec, engineId = DEFAULT_ENGINE_ID) {
*/
export function buildSidecarArgs({ engineId = DEFAULT_ENGINE_ID, pythonPath, scriptPath, runtimeDir, repo, prompt, lyrics, durationSec, outputPath }) {
const engine = getEngine(engineId);
+ const seconds = clampDuration(durationSec, engine.id);
const args = [
scriptPath ?? engine.scriptPath,
'--model', repo,
- '--text', prompt,
- '--duration', String(clampDuration(durationSec, engine.id)),
+ // Prompts are authored in a plain textarea that many users type markdown
+ // into out of habit. Every backend's text encoder tokenizes `**` and `_`
+ // as literal content, so the emphasis markers become conditioning noise —
+ // strip them and keep the words.
+ '--text', stripMarkdownEmphasis(prompt).trim(),
+ '--duration', String(seconds),
'--output', outputPath,
'--runtime-dir', runtimeDir ?? engine.runtimeDir,
];
if (engine.lyrics) {
// Preserve the caller's string verbatim when they supplied one; substitute
// only when it is absent or whitespace, and only for an engine that cannot
- // accept empty lyrics (see instrumentalLyrics).
+ // accept empty lyrics (see instrumentalLyrics). The substitute may be a
+ // builder that sizes the sheet to the render length.
const provided = typeof lyrics === 'string' ? lyrics : '';
- args.push('--lyrics', provided.trim() ? provided : (engine.instrumentalLyrics || ''));
+ const fallback = typeof engine.instrumentalLyrics === 'function'
+ ? engine.instrumentalLyrics(seconds)
+ : (engine.instrumentalLyrics || '');
+ args.push('--lyrics', provided.trim() ? provided : fallback);
}
return { bin: pythonPath, args };
}
diff --git a/server/services/pipeline/musicGen.test.js b/server/services/pipeline/musicGen.test.js
index 3f158c2e28..f6de951c08 100644
--- a/server/services/pipeline/musicGen.test.js
+++ b/server/services/pipeline/musicGen.test.js
@@ -8,6 +8,7 @@ import { writeFileSync, mkdtempSync } from 'fs';
import {
buildMusicGenArgs,
buildSidecarArgs,
+ buildMinimaxInstrumentalLyrics,
clampDuration,
getMusicgenModel,
getEngine,
@@ -174,6 +175,19 @@ describe('buildSidecarArgs', () => {
outputPath: '/data/music/music-gen-abc.wav',
};
+ it('strips markdown emphasis out of the prompt for every engine', () => {
+ // The prompt box is a plain textarea; users type markdown into it out of
+ // habit and the text encoders tokenize `**`/`_` as literal content.
+ const textArg = (args) => args[args.indexOf('--text') + 1];
+ for (const engineId of Object.keys(ENGINES)) {
+ const { args } = buildSidecarArgs({
+ ...base, engineId, repo: 'some/repo',
+ prompt: 'slow-burning, cinematic instrumental with a **dark** `analog` pulse',
+ });
+ expect(textArg(args), engineId).toBe('slow-burning, cinematic instrumental with a dark analog pulse');
+ }
+ });
+
it('routes to the musicgen sidecar script for the musicgen engine', () => {
const { bin, args } = buildSidecarArgs({ ...base, engineId: 'musicgen' });
expect(bin).toBe('/venv/bin/python3');
@@ -595,16 +609,28 @@ describe('instrumental lyrics fallback', () => {
const base = { pythonPath: '/venv/bin/python3', prompt: 'cinematic electronic instrumental', durationSec: 60, outputPath: '/tmp/out.wav' };
const lyricsArg = (args) => args[args.indexOf('--lyrics') + 1];
- it('substitutes the documented [instrumental] tag when MiniMax Music 3 gets no lyrics', () => {
+ it('substitutes a documented structure-tag sheet when MiniMax Music 3 gets no lyrics', () => {
// The checkpoint's tokenize step raises on an empty string, so an
// instrumental prompt used to die with "`lyrics` must be a non-empty
// string" after the model had already loaded.
for (const lyrics of [undefined, '', ' ', '\n\t ']) {
const { args } = buildSidecarArgs({ ...base, engineId: 'minimax-music3', repo: 'MiniMaxAI/MiniMax-Music3', lyrics });
- expect(lyricsArg(args), `lyrics=${JSON.stringify(lyrics)}`).toBe('[instrumental]');
+ expect(lyricsArg(args), `lyrics=${JSON.stringify(lyrics)}`).toBe(buildMinimaxInstrumentalLyrics(60));
}
});
+ it('sizes the substituted sheet to the render duration, not a fixed one-tag stub', () => {
+ // `audio_duration` is only a ceiling for this engine — the global LLM ends
+ // the piece on its own, paced by the sheet's section count. A single
+ // [instrumental] tag is one section, which is why a 60s ask returned 25s.
+ const lyricsFor = (durationSec) => lyricsArg(
+ buildSidecarArgs({ ...base, engineId: 'minimax-music3', repo: 'MiniMaxAI/MiniMax-Music3', durationSec, lyrics: '' }).args,
+ );
+ const sections = (sheet) => sheet.split('\n').length;
+ expect(sections(lyricsFor(20))).toBeLessThan(sections(lyricsFor(60)));
+ expect(sections(lyricsFor(60))).toBeLessThan(sections(lyricsFor(240)));
+ });
+
it('never touches lyrics the caller actually supplied', () => {
const words = '[verse]\nExample words here';
const { args } = buildSidecarArgs({ ...base, engineId: 'minimax-music3', repo: 'MiniMaxAI/MiniMax-Music3', lyrics: words });
@@ -617,3 +643,49 @@ describe('instrumental lyrics fallback', () => {
expect(lyricsArg(args)).toBe('');
});
});
+
+describe('buildMinimaxInstrumentalLyrics', () => {
+ const tags = (sheet) => sheet.split('\n');
+
+ it('brackets every line and opens on [intro] / closes on [outro]', () => {
+ const lines = tags(buildMinimaxInstrumentalLyrics(60));
+ for (const line of lines) expect(line).toMatch(/^\[[a-z]+\]$/);
+ expect(lines[0]).toBe('[intro]');
+ expect(lines.at(-1)).toBe('[outro]');
+ });
+
+ it('uses only tags the model card documents, and none that imply a vocal', () => {
+ // Section tags are a fixed vocabulary; [verse]/[chorus] would coax the
+ // model into singing over what the user asked to be an instrumental.
+ const documented = new Set(['intro', 'instrumental', 'bridge', 'solo', 'outro']);
+ for (const seconds of [1, 30, 60, 120, 300]) {
+ for (const line of tags(buildMinimaxInstrumentalLyrics(seconds))) {
+ expect(documented, `${seconds}s → ${line}`).toContain(line.slice(1, -1));
+ }
+ }
+ });
+
+ it('grows monotonically with duration and always keeps a body section', () => {
+ let previous = 0;
+ for (const seconds of [1, 20, 60, 120, 240, 300]) {
+ const count = tags(buildMinimaxInstrumentalLyrics(seconds)).length;
+ expect(count, `${seconds}s`).toBeGreaterThanOrEqual(previous);
+ // intro + at least one body + outro
+ expect(count, `${seconds}s`).toBeGreaterThanOrEqual(3);
+ previous = count;
+ }
+ });
+
+ it('clamps into the engine window instead of throwing on junk input', () => {
+ // Mirrors clampDuration's contract — the route validates shape, this
+ // guards the math, so a non-finite duration falls back to the default.
+ for (const bad of [undefined, null, NaN, 'sixty', -5, 1e9]) {
+ expect(() => buildMinimaxInstrumentalLyrics(bad)).not.toThrow();
+ expect(tags(buildMinimaxInstrumentalLyrics(bad)).length).toBeGreaterThanOrEqual(3);
+ }
+ });
+
+ it('caps the sheet so a 5-minute render does not emit an unbounded tag wall', () => {
+ expect(tags(buildMinimaxInstrumentalLyrics(300)).length).toBeLessThanOrEqual(14);
+ });
+});