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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([4224]): enable MiniMax-Music3 MLX on Apple Silicon (#4418)
[._.]/ Adam Eivyfb13cd6941c7
diff --git a/.changelog/next/changed-issue-4224.md b/.changelog/next/changed-issue-4224.mdnew file mode 100644index 0000000000..0d26f43444--- /dev/null+++ b/.changelog/next/changed-issue-4224.md@@ -0,0 +1 @@+- [4224] Add Apple Silicon MiniMax Music 3 MLX generation with selectable 8-bit and BF16 checkpoints.diff --git a/client/src/components/music/MusicGenPanel.jsx b/client/src/components/music/MusicGenPanel.jsxindex 2c7c1c53b2..6c9ef98849 100644--- a/client/src/components/music/MusicGenPanel.jsx+++ b/client/src/components/music/MusicGenPanel.jsx@@ -2,17 +2,17 @@* MusicGenPanel — on-device music generation for the Track editor.** Lets the user pick a generation engine (MusicGen / AudioLDM2 / ACE-Step /- * MiniMax Music 3), 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).+ * 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).** 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* venv gate in image gen. Additional HuggingFace checkpoints can be installed* inline (streamed download), then selected immediately.*- * A fixed-model engine (MiniMax Music 3) needs BOTH a runtime venv and a fixed+ * A fixed-model engine (MiniMax-Music3) needs BOTH a runtime venv and a fixed* weights download, and neither is useful alone. The setup banner therefore* carries ONE action that installs whatever is still missing: it opens the* runtime installer first when that's absent, then — once the refreshed engine@@ -42,10 +42,11 @@ import RuntimeInstallModal from '../install/RuntimeInstallModal';* or it's CUDA-only on a host with no usable NVIDIA GPU, where an install button* would just be a slower way to fail.*/-function engineSetupState(engine) {+function engineSetupState(engine, selectedModelReady = null, selectedModelSizeGb = null) {if (!engine) return null;const needsRuntime = engine.runtimeReady !== true;- const needsWeights = engine.fixedModelInstall === true && engine.modelReady === false;+ const needsWeights = engine.fixedModelInstall === true+ && (selectedModelReady === null ? engine.modelReady === false : selectedModelReady === false);const blocked = engine.platformSupported === false|| (engine.cudaRequired === true && engine.cudaState !== 'available');@@ -55,10 +56,10 @@ function engineSetupState(engine) {else if (engine.cudaRequired === true && engine.cudaState !== 'available') message = `${engine.name} requires an NVIDIA CUDA GPU and is unavailable on this host.`;else if (engine.runtimeReady === false && needsWeights) message = `${engine.name} needs its runtime and model weights before generation.`;else if (engine.runtimeReady === false) message = `${engine.name} needs its runtime before generation.`;- else if (needsWeights) message = `${engine.name} model weights are not installed yet.`;+ else if (needsWeights) message = `${engine.name} ${engine.modelReadyById && selectedModelReady === false ? 'selected model weights' : 'model weights'} are not installed yet.`;else message = `${engine.name} is not installed yet. Install the runtime to enable generation.`;- const size = formatDownloadGb(engine.modelSizeGb);+ const size = formatDownloadGb(selectedModelSizeGb ?? engine.modelSizeGb);const suffix = size ? ` (${size})` : '';let label = null;if (!blocked && needsRuntime && needsWeights) label = `Install runtime + weights${suffix}`;@@ -127,6 +128,19 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist}, [generating]);const engine = useMemo(() => engines.find((e) => e.id === engineId) || null, [engines, engineId]);+ const selectedModel = engine?.models?.find((item) => item.id === modelId)+ || engine?.models?.find((item) => item.id === engine.defaultModelId)+ || engine?.models?.[0]+ || null;+ // A native <select> displays its first option while React is applying the+ // engine's default id. Use that effective option for readiness and generation+ // too, so the first paint cannot briefly disable an otherwise ready engine.+ const selectedModelId = selectedModel?.id || modelId;+ const selectedModelReady = !engine?.fixedModelInstall+ ? true+ : engine?.modelReadyById+ ? engine.modelReadyById[selectedModelId] === true+ : engine.modelReady === true;const autoDurationAvailable = supportsAutoDuration(engine);const lyricDuration = useMemo(() => analyzeMusicLyrics(lyrics, {minDurationSec: Math.max(60, engine?.defaultDurationSec || 60),@@ -166,14 +180,18 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artistsetDurationSec((d) => (d == null ? engine.defaultDurationSec : d));}, [engine?.id, engine?.models]);- const canGenerate = !!engine?.ready && !!prompt?.trim() && !generating;- const setup = engineSetupState(engine);+ const canGenerate = !!engine?.ready && selectedModelReady && !!prompt?.trim() && !generating;+ const selectedModelSizeGb = engine?.modelSizeGbById?.[selectedModelId] ?? null;+ const setup = engineSetupState(engine, selectedModelReady, selectedModelSizeGb);// `target` is the engine record to install for — passed explicitly by the// post-runtime chain, which holds a fresher record than component state does.const installFixedModel = async (target) => {const eng = target || engine;- const model = eng?.models?.find((item) => item.id === eng.defaultModelId) || eng?.models?.[0];+ const selectedId = eng?.id === engine?.id ? selectedModelId : '';+ const model = eng?.models?.find((item) => item.id === selectedId)+ || eng?.models?.find((item) => item.id === eng.defaultModelId)+ || eng?.models?.[0];if (!eng || !model?.repo) return;setInstalling(true);setSetupProgress({ message: `Starting ${model.name}…` });@@ -206,7 +224,12 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artistconst list = await loadEngines();if (!mountedRef.current) return;const fresh = list.find((e) => e.id === engineId);- const freshSetup = engineSetupState(fresh);+ const freshSelectedModelReady = !fresh?.fixedModelInstall+ ? true+ : fresh?.modelReadyById+ ? fresh.modelReadyById[selectedModelId] === true+ : fresh.modelReady === true;+ const freshSetup = engineSetupState(fresh, freshSelectedModelReady, fresh?.modelSizeGbById?.[selectedModelId] ?? null);if (freshSetup && !freshSetup.blocked && !freshSetup.needsRuntime && freshSetup.needsWeights) {await installFixedModel(fresh);}@@ -220,7 +243,7 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artistprompt: prompt.trim(),lyrics: engine.lyrics ? (lyrics || '') : '',engine: engine.id,- modelId,+ modelId: selectedModelId,};if (track?.id) body.trackId = track.id;else {@@ -276,7 +299,7 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artistif (engines.length === 0) return <div className="text-xs text-gray-500">No music generators available.</div>;const selectedUserModel = engine?.models?.find((m) => m.id === modelId && m.userAdded);- const showRuntimeInstallHint = !!engine && !engine.ready && (!!prompt?.trim() || userSelectedEngine);+ const showRuntimeInstallHint = !!engine && (!engine.ready || !selectedModelReady) && (!!prompt?.trim() || userSelectedEngine);return (<div className="space-y-2 border border-port-border rounded-lg p-3 bg-port-bg/40">@@ -406,7 +429,7 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artisttype="button"onClick={handleGenerate}disabled={!canGenerate}- title={!prompt?.trim() ? 'Add a generation prompt' : !engine?.ready ? 'Complete engine setup first' : track?.id ? 'Generate audio' : 'Generate and create a standalone track'}+ title={!prompt?.trim() ? 'Add a generation prompt' : !engine?.ready ? 'Complete engine setup first' : !selectedModelReady ? 'Install the selected model first' : track?.id ? 'Generate audio' : 'Generate and create a standalone track'}className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50">{generating ? <Loader2 size={14} className="animate-spin" /> : <Wand2 size={14} />}@@ -439,7 +462,9 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist<p className="mt-1.5 text-[11px] text-gray-500">{engine?.id === 'minimax-music3'? 'MiniMax Music 3 does not report an exact percentage yet; a 60-second track can take tens of minutes on a 24 GB GPU.'- : 'Generation is still active. Longer requested durations take more time.'}+ : engine?.id === 'minimax-music3-mlx'+ ? 'MiniMax Music 3 MLX does not report an exact percentage yet; the first render includes model loading.'+ : 'Generation is still active. Longer requested durations take more time.'}</p></div>) : null}diff --git a/client/src/components/music/MusicGenPanel.test.jsx b/client/src/components/music/MusicGenPanel.test.jsxindex 855ee8fa75..597b1210e2 100644--- a/client/src/components/music/MusicGenPanel.test.jsx+++ b/client/src/components/music/MusicGenPanel.test.jsx@@ -356,6 +356,45 @@ describe('MusicGenPanel', () => {expect(api.installAudioModel).not.toHaveBeenCalled();});+ it('gates the selected MLX snapshot independently and defaults to 8-bit', async () => {+ api.listMusicEngines.mockResolvedValue({+ defaultEngine: 'minimax-music3-mlx',+ engines: [engine({+ id: 'minimax-music3-mlx', name: 'MiniMax Music 3 (MLX)', ready: true,+ runtimeReady: true, modelReady: true, modelReadyById: {+ 'minimax-music3-mlx-8bit': true,+ 'minimax-music3-mlx-bf16': false,+ }, fixedModelInstall: true, customModels: false, lyrics: true,+ cudaState: 'available', platformSupported: true, maxDurationSec: 300, defaultDurationSec: 60,+ modelSizeGbById: { 'minimax-music3-mlx-8bit': 14, 'minimax-music3-mlx-bf16': 29 },+ models: [+ { id: 'minimax-music3-mlx-8bit', repo: 'mlx-community/MiniMax-Music3-8bit', name: 'MiniMax Music 3 MLX 8-bit' },+ { id: 'minimax-music3-mlx-bf16', repo: 'mlx-community/MiniMax-Music3-bf16', name: 'MiniMax Music 3 MLX BF16' },+ ],+ defaultModelId: 'minimax-music3-mlx-8bit',+ })],+ });++ render(<MusicGenPanel prompt="cinematic score" lyrics="[verse] Example" />);++ const modelSelect = await screen.findByRole('combobox', { name: /model/i });+ expect(modelSelect).toHaveValue('minimax-music3-mlx-8bit');+ expect(screen.queryByRole('button', { name: /download model weights/i })).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: /generate track/i })).toBeEnabled();++ fireEvent.change(modelSelect, { target: { value: 'minimax-music3-mlx-bf16' } });+ expect(await screen.findByText(/selected model weights are not installed yet/i)).toBeInTheDocument();+ const install = screen.getByRole('button', { name: /download model weights \(~29 GB\)/i });+ expect(install).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /generate track/i })).toBeDisabled();++ fireEvent.click(install);+ await waitFor(() => expect(api.installAudioModel).toHaveBeenCalledWith(+ { engine: 'minimax-music3-mlx', repo: 'mlx-community/MiniMax-Music3-bf16' },+ expect.any(Function),+ ));+ });+it('shows honest elapsed GPU feedback while MiniMax generation is running', async () => {api.listMusicEngines.mockResolvedValue({defaultEngine: 'minimax-music3',diff --git a/scripts/generate_minimax_music3_mlx.py b/scripts/generate_minimax_music3_mlx.pynew file mode 100644index 0000000000..1f240663ca--- /dev/null+++ b/scripts/generate_minimax_music3_mlx.py@@ -0,0 +1,101 @@+#!/usr/bin/env python3+"""MiniMax Music 3 MLX sidecar using PortOS' STAGE/RESULT protocol."""++import argparse+import json+import os+import sys+import wave+++TARGET_SAMPLE_RATE = 32000+++def to_stereo(audio, np):+ """Orient an MLX/NumPy waveform to (2, samples) float32."""+ audio = np.squeeze(np.asarray(audio)).astype(np.float32)+ if audio.size == 0:+ raise RuntimeError("MiniMax Music 3 MLX returned empty audio")+ if audio.ndim == 1:+ return np.stack([audio, audio])+ if audio.ndim != 2:+ raise RuntimeError(f"unexpected audio shape {audio.shape}")+ if audio.shape[0] == 2:+ return audio+ if audio.shape[0] == 1:+ return np.repeat(audio, 2, axis=0)+ if audio.shape[1] == 2:+ return audio.T+ if audio.shape[1] == 1:+ return np.repeat(audio.T, 2, axis=0)+ raise RuntimeError(f"could not orient audio shape {audio.shape} to stereo")+++def resample_to_target(audio, source_rate, np, target_rate=TARGET_SAMPLE_RATE):+ """Resample (2, samples) audio to the library's existing 32 kHz rate."""+ if source_rate == target_rate:+ return audio+ if source_rate <= 0:+ raise RuntimeError(f"invalid MiniMax Music 3 MLX sample rate {source_rate}")+ target_length = max(1, round(audio.shape[1] * target_rate / source_rate))+ source_x = np.arange(audio.shape[1], dtype=np.float64)+ target_x = np.linspace(0, audio.shape[1] - 1, target_length)+ return np.stack([np.interp(target_x, source_x, channel) for channel in audio])+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument("--model", required=True)+ parser.add_argument("--revision", default="")+ parser.add_argument("--text", required=True)+ parser.add_argument("--lyrics", default="")+ parser.add_argument("--duration", type=float, required=True)+ parser.add_argument("--output", required=True)+ parser.add_argument("--runtime-dir", default="")+ parser.add_argument("--steps", type=int, default=30)+ parser.add_argument("--seed", type=int, default=0)+ args = parser.parse_args()++ if args.runtime_dir:+ sys.path.insert(0, args.runtime_dir)++ import numpy as np+ from mlx_audio.music import load++ print("STAGE:load-model", file=sys.stderr, flush=True)+ model = load(args.model, revision=args.revision) if args.revision else load(args.model)+ print("STAGE:generate", file=sys.stderr, flush=True)+ requested_duration = float(max(1, min(300, args.duration)))+ chunks = []+ sample_rate = None+ for result in model.generate(+ text=args.text,+ lyrics=args.lyrics,+ duration=requested_duration,+ steps=args.steps,+ seed=args.seed,+ ):+ result_rate = int(result.sample_rate)+ if sample_rate is None:+ sample_rate = result_rate+ elif result_rate != sample_rate:+ raise RuntimeError("MiniMax Music 3 MLX returned inconsistent sample rates")+ chunks.append(to_stereo(result.audio, np))++ if not chunks or sample_rate is None:+ raise RuntimeError("MiniMax Music 3 MLX produced no audio")++ audio = np.concatenate(chunks, axis=1)+ audio = resample_to_target(audio, sample_rate, np)+ pcm = (np.clip(audio, -1, 1).T * 32767).astype(np.int16)+ os.makedirs(os.path.dirname(args.output) or ".", exist_ok=True)+ with wave.open(args.output, "wb") as wav:+ wav.setnchannels(2)+ wav.setsampwidth(2)+ wav.setframerate(TARGET_SAMPLE_RATE)+ wav.writeframes(pcm.tobytes())+ print("RESULT:" + json.dumps({"durationSec": len(pcm) / TARGET_SAMPLE_RATE, "sampleRate": TARGET_SAMPLE_RATE}), flush=True)+++if __name__ == "__main__":+ main()diff --git a/scripts/generate_minimax_music3_mlx.test.js b/scripts/generate_minimax_music3_mlx.test.jsnew file mode 100644index 0000000000..32160d9575--- /dev/null+++ b/scripts/generate_minimax_music3_mlx.test.js@@ -0,0 +1,51 @@+import { execFileSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import { describe, expect, it } from 'vitest';+import { resolveTestPython } from '../server/lib/testHelper.js';++const script = join(dirname(fileURLToPath(import.meta.url)), 'generate_minimax_music3_mlx.py');+const pyBin = resolveTestPython();+const hasNumpy = (() => {+ if (!pyBin) return false;+ try {+ execFileSync(pyBin, ['-c', 'import numpy'], { stdio: 'ignore' });+ return true;+ } catch {+ return false;+ }+})();++const runPython = (body) => execFileSync(pyBin, ['-c', [+ 'import importlib.util, json, sys',+ 'import numpy as np',+ 'spec = importlib.util.spec_from_file_location("mm3mlx", sys.argv[1])',+ 'mod = importlib.util.module_from_spec(spec)',+ 'spec.loader.exec_module(mod)',+ body,+].join('\n'), script], { encoding: 'utf8' }).trim();++describe.skipIf(!hasNumpy)('generate_minimax_music3_mlx sidecar helpers', () => {+ it('orients channels-first, channels-last, and mono audio to stereo', () => {+ const output = runPython([+ 'values = {}',+ 'for label, shape in (("first", (2, 8)), ("last", (8, 2)), ("mono", (8,))):',+ ' values[label] = list(mod.to_stereo(np.arange(int(np.prod(shape)), dtype=np.float64).reshape(shape), np).shape)',+ 'print(json.dumps(values))',+ ].join('\n'));+ expect(JSON.parse(output)).toEqual({ first: [2, 8], last: [2, 8], mono: [2, 8] });+ });++ it('resamples the MLX 44.1 kHz output to the shared 32 kHz library rate', () => {+ const output = runPython([+ 'audio = np.zeros((2, 441), dtype=np.float32)',+ 'resampled = mod.resample_to_target(audio, 44100, np)',+ 'print(json.dumps(list(resampled.shape)))',+ ].join('\n'));+ expect(JSON.parse(output)).toEqual([2, 320]);+ });++ it('rejects an audio shape that cannot be made stereo', () => {+ expect(() => runPython('mod.to_stereo(np.zeros((3, 4), dtype=np.float32), np)')).toThrow();+ });+});diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.shindex bada4f3368..92631f2291 100755--- a/scripts/setup-image-video.sh+++ b/scripts/setup-image-video.sh@@ -16,6 +16,8 @@# INSTALL_FLUX2 '1' to also bootstrap a separate venv at ~/.portos/venv-flux2 for FLUX.2-klein (default: 1 on macOS, 0 elsewhere)# INSTALL_MUSICGEN '1' to bootstrap a venv at ~/.portos/venv-musicgen + clone ml-explore/mlx-examples to ~/.portos/mlx-examples for local MusicGen (MLX) background-music generation (pipeline audio stage). Default: 0; opt in with INSTALL_MUSICGEN=1 (macOS / Apple Silicon only).# MLX_EXAMPLES_PIN commit SHA of ml-explore/mlx-examples to check out for MusicGen (default: main).+# INSTALL_MINIMAX_MUSIC3_MLX '1' to bootstrap a separate venv at ~/.portos/venv-minimax-music3-mlx for native MiniMax Music 3 MLX generation (Music studio). Default: 0; opt in with INSTALL_MINIMAX_MUSIC3_MLX=1 (macOS / Apple Silicon only).+# MLX_AUDIO_PIN commit SHA of Blaizzy/mlx-audio containing MiniMax Music 3 support (default: 784b29e2691a93ca7483147d86f61859dfaa6296).# INSTALL_AUDIOLDM2 '1' to bootstrap a venv at ~/.portos/venv-audioldm2 (torch + diffusers) for local AudioLDM2 long-form background-music generation (pipeline audio stage, second backend alongside MusicGen). Default: 0; opt in with INSTALL_AUDIOLDM2=1 (runs on MPS / CUDA / CPU).# INSTALL_ACESTEP '1' to bootstrap a venv at ~/.portos/venv-acestep (torch + the acestep package) for local ACE-Step full-song generation with vocals (Music studio, third backend). Default: 0; opt in with INSTALL_ACESTEP=1 (runs on MPS / CUDA / CPU; checkpoints auto-download to ~/.cache/ace-step on first run).# INSTALL_ACESTEP15 '1' to bootstrap a venv at ~/.portos/venv-acestep15 (the ACE-Step 1.5 package + torch) for local ACE-Step 1.5 full-song generation (Music studio). Default: 0; opt in with INSTALL_ACESTEP15=1 (runs on MPS / CUDA / CPU; model weights are installed separately from Music).@@ -81,7 +83,7 @@ mkdir -p "${PORTOS_DATA}/video-thumbnails"# When the user only wants a specific BYOV runtime (set via INSTALL_LTX2 /# INSTALL_WAN22 / INSTALL_HUNYUAN / INSTALL_MINIMAX_H3 / INSTALL_MINIMAX_H3_CUDA — or one of the self-contained MUSIC venvs-# INSTALL_MUSICGEN / INSTALL_AUDIOLDM2 / INSTALL_ACESTEP / INSTALL_ACESTEP15 — typically from the+# INSTALL_MUSICGEN / INSTALL_AUDIOLDM2 / INSTALL_ACESTEP / INSTALL_ACESTEP15 / INSTALL_MINIMAX_MUSIC3_MLX — typically from the# in-app installer), skip the mflux + legacy mlx_video preamble. Those# bring-your-own-venv runtimes are self-contained and don't depend on mflux;# running the preamble unprompted hits PEP 668 ("externally-managed-environment")@@ -89,7 +91,7 @@ mkdir -p "${PORTOS_DATA}/video-thumbnails"# install ever starts — which on Linux/CPU/CUDA blocks the advertised# `INSTALL_ACESTEP=1 bash …` path. A bare `bash setup-image-video.sh` still# installs mflux as before.-ANY_BYOV="${INSTALL_LTX2:-0}${INSTALL_LTX25:-0}${INSTALL_WAN22:-0}${INSTALL_HUNYUAN:-0}${INSTALL_MINIMAX_H3:-0}${INSTALL_MINIMAX_H3_CUDA:-0}${INSTALL_MUSICGEN:-0}${INSTALL_AUDIOLDM2:-0}${INSTALL_ACESTEP:-0}${INSTALL_ACESTEP15:-0}${INSTALL_MINIMAX_MUSIC3:-0}${INSTALL_MUSCRIPTOR:-0}"+ANY_BYOV="${INSTALL_LTX2:-0}${INSTALL_LTX25:-0}${INSTALL_WAN22:-0}${INSTALL_HUNYUAN:-0}${INSTALL_MINIMAX_H3:-0}${INSTALL_MINIMAX_H3_CUDA:-0}${INSTALL_MUSICGEN:-0}${INSTALL_AUDIOLDM2:-0}${INSTALL_ACESTEP:-0}${INSTALL_ACESTEP15:-0}${INSTALL_MINIMAX_MUSIC3:-0}${INSTALL_MINIMAX_MUSIC3_MLX:-0}${INSTALL_MUSCRIPTOR:-0}"# "no BYOV runtime was requested" = the concatenation contains no non-zero# character. Matching a literal string of zeros instead made this a counting# exercise that the string and the variable list had to agree on — and they had@@ -819,6 +821,41 @@ if [[ "$INSTALL_MINIMAX_MUSIC3" == "1" ]]; thenecho " Model weights (~29 GB) install separately from Music → Generate."fi+INSTALL_MINIMAX_MUSIC3_MLX="${INSTALL_MINIMAX_MUSIC3_MLX:-0}"+if [[ "$INSTALL_MINIMAX_MUSIC3_MLX" == "1" ]]; then+ # Native MLX MiniMax Music 3 is intentionally a sibling of the CUDA+ # Diffusers runtime above: the packages have different dependency stacks and+ # the MLX model loader is Apple-Silicon-only. Model weights stay a separate,+ # explicit Music-studio download so installing a runtime never spends tens of+ # gigabytes without the user's consent.+ if ! is_macos || [[ "$(uname -m)" != "arm64" ]]; then+ echo "⚠️ INSTALL_MINIMAX_MUSIC3_MLX=1 is macOS / Apple-Silicon only. Skipping." >&2+ else+ MINIMAX_MUSIC3_MLX_VENV="${HOME}/.portos/venv-minimax-music3-mlx"+ mkdir -p "${HOME}/.portos"+ if ! venv_exists "$MINIMAX_MUSIC3_MLX_VENV"; then+ echo "📦 Creating MiniMax Music 3 MLX venv at ${MINIMAX_MUSIC3_MLX_VENV}..."+ "$PYTHON_BIN" -m venv "$MINIMAX_MUSIC3_MLX_VENV"+ fi+ MINIMAX_MUSIC3_MLX_PY="$(venv_python "$MINIMAX_MUSIC3_MLX_VENV")"+ MLX_AUDIO_PIN="${MLX_AUDIO_PIN:-784b29e2691a93ca7483147d86f61859dfaa6296}"+ echo "📦 Installing MiniMax Music 3 MLX packages into ${MINIMAX_MUSIC3_MLX_VENV}..."+ "$MINIMAX_MUSIC3_MLX_PY" -m pip install --upgrade pip wheel setuptools >/dev/null+ # MiniMax Music 3 support merged into mlx-audio after its latest release;+ # pin the merge commit until a release containing it is published. The model+ # cards themselves document this same upstream commit as the required API.+ "$MINIMAX_MUSIC3_MLX_PY" -m pip install --upgrade \+ "mlx-audio @ git+https://github.com/Blaizzy/mlx-audio.git@${MLX_AUDIO_PIN}" \+ "huggingface_hub[hf_xet]"+ if ! "$MINIMAX_MUSIC3_MLX_PY" -c "import mlx; from mlx_audio.music import load" 2>/dev/null; then+ echo "❌ MiniMax Music 3 MLX venv built but 'import mlx; from mlx_audio.music import load' failed." >&2+ echo " Check that mlx-audio installed cleanly in ${MINIMAX_MUSIC3_MLX_VENV}." >&2+ exit 1+ fi+ echo "✅ MiniMax Music 3 MLX venv ready: $MINIMAX_MUSIC3_MLX_PY (mlx-audio @ ${MLX_AUDIO_PIN:0:12})"+ fi+fi+INSTALL_MUSCRIPTOR="${INSTALL_MUSCRIPTOR:-0}"if [[ "$INSTALL_MUSCRIPTOR" == "1" ]]; then# Local audio → MIDI transcription for the Rounds workbench + Music Video@@ -942,6 +979,9 @@ fiif [[ "$INSTALL_MUSICGEN" == "1" ]] && is_macos; thenecho " MusicGen: ${HOME}/.portos/venv-musicgen/bin/python3 (separate venv, MLX runtime @ ${HOME}/.portos/mlx-examples/musicgen)"fi+if [[ "$INSTALL_MINIMAX_MUSIC3_MLX" == "1" ]] && is_macos && [[ "$(uname -m)" == "arm64" ]]; then+ echo " MiniMax Music 3 MLX: ${MINIMAX_MUSIC3_MLX_PY} (separate venv, mlx-audio; weights install separately in Music)"+fiif [[ "$INSTALL_AUDIOLDM2" == "1" ]]; thenecho " AudioLDM2: ${AUDIOLDM2_PY} (separate venv, diffusers — long-form audio)"fidiff --git a/scripts/setup-image-video.test.js b/scripts/setup-image-video.test.jsindex 8bb16dd291..629cbca726 100644--- a/scripts/setup-image-video.test.js+++ b/scripts/setup-image-video.test.js@@ -79,6 +79,7 @@ describe('setup-image-video venv layout handling (issue #4200)', () => {['AudioLDM2', 'AUDIOLDM2_VENV', 'AUDIOLDM2_PY'],['ACE-Step', 'ACESTEP_VENV', 'ACESTEP_PY'],['MiniMax Music 3', 'MINIMAX_MUSIC3_VENV', 'MINIMAX_MUSIC3_PY'],+ ['MiniMax Music 3 MLX', 'MINIMAX_MUSIC3_MLX_VENV', 'MINIMAX_MUSIC3_MLX_PY'],['MuScriptor', 'MUSCRIPTOR_VENV', 'MUSCRIPTOR_PY'],['FLUX.2', 'FLUX2_VENV', 'FLUX2_PY'],])('%s reuses an existing Windows venv and resolves it with the helper', (_name, venv, python) => {diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.jsindex 1e5a8723c3..d7a4c5dba2 100644--- a/server/lib/pythonSetup.js+++ b/server/lib/pythonSetup.js@@ -483,6 +483,30 @@ export function invalidateMinimaxMusic3Python() {cachedMinimaxMusic3Python = null;}+// MiniMax Music 3's native MLX port runs in a separate venv from the CUDA+// Diffusers runtime above. Keeping the stacks isolated prevents a torch/+// diffusers upgrade from changing the MLX install (and vice versa).+const MINIMAX_MUSIC3_MLX_VENV_CANDIDATES = [+ join(HOME, '.portos', 'venv-minimax-music3-mlx', 'bin', 'python3'),+ join(PATHS.data, 'python', 'venv-minimax-music3-mlx', 'bin', 'python3'),+];++export const MINIMAX_MUSIC3_MLX_VENV_DEFAULT = MINIMAX_MUSIC3_MLX_VENV_CANDIDATES[0];+export const MINIMAX_MUSIC3_MLX_RUNTIME_DIR = '';++let cachedMinimaxMusic3MlxPython = null;+export function resolveMinimaxMusic3MlxPython() {+ if (cachedMinimaxMusic3MlxPython && existsSync(cachedMinimaxMusic3MlxPython)) return cachedMinimaxMusic3MlxPython;+ for (const p of MINIMAX_MUSIC3_MLX_VENV_CANDIDATES) {+ if (existsSync(p)) { cachedMinimaxMusic3MlxPython = p; return p; }+ }+ return null;+}++export function invalidateMinimaxMusic3MlxPython() {+ cachedMinimaxMusic3MlxPython = null;+}+// Every venv PortOS provisions with `huggingface_hub` installed, in preference// order. hfDownload.js falls back through these to find an interpreter that can// run scripts/hf_download_repo.py when no image-gen runtime is configured — a@@ -497,6 +521,7 @@ export const HF_HUB_PYTHON_RESOLVERS = Object.freeze([resolveAudioldm2Python,resolveMusicgenPython,resolveMinimaxMusic3Python,+ resolveMinimaxMusic3MlxPython,]);// MuScriptor (audio → MIDI transcription for the Rounds workbench + Music Videodiff --git a/server/lib/sseDownload.js b/server/lib/sseDownload.jsindex 76f4a6d8c0..4d40f50e1d 100644--- a/server/lib/sseDownload.js+++ b/server/lib/sseDownload.js@@ -57,7 +57,7 @@ export function onClientDisconnect(_req, res, onDisconnect) {});}-export async function startHfDownloadStream({ req, res, repo, repos, fallbacks, cachedFile = null, alreadyDownloadedMessage, force = false, pythonPath = null }) {+export async function startHfDownloadStream({ req, res, repo, revision = null, repos, fallbacks, cachedFile = null, alreadyDownloadedMessage, force = false, pythonPath = null }) {// Three input shapes, two semantics:// - `repo` (single string) / `repos` (ordered array) — ALL must succeed. Used// when a model has auxiliary repos that must be present alongside the main@@ -95,7 +95,10 @@ export async function startHfDownloadStream({ req, res, repo, repos, fallbacks,};};const firstSuccessWins = Array.isArray(fallbacks);- const targets = (firstSuccessWins ? fallbacks : (Array.isArray(repos) ? repos : [repo]))+ const targetInputs = firstSuccessWins+ ? fallbacks+ : (Array.isArray(repos) ? repos : [revision ? { repo, revision } : repo]);+ const targets = targetInputs.map(normalizeTarget).filter(Boolean);const { send, safeEnd } = openSseStream(res);diff --git a/server/routes/music.js b/server/routes/music.jsindex f2ff5a4a38..f2d35eee8f 100644--- a/server/routes/music.js+++ b/server/routes/music.js@@ -12,7 +12,7 @@* fires them on its own (AI Provider Usage Policy).** Generation runs the engine-agnostic `generateMusic` (server/services/pipeline/- * musicGen.js) — MusicGen / AudioLDM2 / ACE-Step behind one contract — lands the+ * musicGen.js) — MusicGen / AudioLDM2 / ACE-Step / MiniMax-Music3 behind one contract — lands the* WAV in the shared music library (data/music/), then creates a new Track (or* updates an existing one via `trackId`) with the audio pointer + the prompt /* lyrics / engine / model / duration metadata. The pipeline audio stage has its@@ -52,11 +52,24 @@ const router = Router();router.get('/engines', asyncHandler(async (_req, res) => {const cuda = await getCudaCapability();const engines = await Promise.all(Object.values(ENGINES).map(async (engine) => {+ const fixedModels = engine.fixedModelInstall ? engine.models : [];+ const modelReadyById = engine.fixedModelInstall+ ? Object.fromEntries(await Promise.all(fixedModels.map(async (model) => [+ model.id,+ (await inspectModelCache(model.repo, { revision: model.revision }).catch(() => ({ cached: false }))).cached === true,+ ])))+ : null;+ // `modelReady` remains an aggregate for older clients. Newer clients gate+ // generation against the selected model in `modelReadyById`, so having the+ // smaller MLX checkpoint cached does not falsely green-light its BF16 peer.+ const modelReady = modelReadyById ? Object.values(modelReadyById).some(Boolean) : true;// The one checkpoint a fixed-model engine installs. Resolved by// defaultModelId, not position, so readiness + size stay attached to the// model the client actually downloads and renders with.const fixedModel = engine.fixedModelInstall ? getEngineModel(engine.id, engine.defaultModelId) : null;- const modelCache = fixedModel ? await inspectModelCache(fixedModel.repo).catch(() => ({ cached: false })) : null;+ const modelSizeGbById = engine.fixedModelInstall+ ? Object.fromEntries(fixedModels.map((model) => [model.id, model.downloadSizeGb ?? null]))+ : null;// isEngineHealthy, not isEngineReady: a half-built venv (install died// mid-pip) still has its interpreter, and reporting that as runtimeReady// hides the install affordance on a backend that cannot generate.@@ -76,10 +89,12 @@ router.get('/engines', asyncHandler(async (_req, res) => {// checkpoint via checkpoint_dir, so custom repos don't apply to it.customModels: engine.customModels === true,fixedModelInstall: engine.fixedModelInstall === true,- modelReady: modelCache ? modelCache.cached === true : true,+ modelReady,+ ...(modelReadyById ? { modelReadyById } : {}),// Rough download footprint for the fixed weights, so the install button can// say how big the pull is before the user commits to it.modelSizeGb: fixedModel?.downloadSizeGb ?? null,+ ...(modelSizeGbById ? { modelSizeGbById } : {}),runtimeReady,cudaRequired: engine.cudaRequired === true,// false when this host can never run the backend (e.g. MLX MusicGen off@@ -88,7 +103,7 @@ router.get('/engines', asyncHandler(async (_req, res) => {platformSupported: isEnginePlatformSupported(engine.id),platformLabel: enginePlatformLabel(engine.id),cudaState: engine.cudaRequired ? cuda.status : 'available',- ready: runtimeReady && (!engine.cudaRequired || cuda.status === 'available') && (!modelCache || modelCache.cached === true),+ ready: runtimeReady && (!engine.cudaRequired || cuda.status === 'available') && modelReady,installEnv: engine.installEnv,venvDefault: engine.venvDefault,});@@ -275,15 +290,18 @@ router.post('/models', asyncHandler(async (req, res) => {// A shipped fixed model may declare `downloadIgnore` to skip repo paths its// runtime never loads (see MINIMAX_MUSIC3_MODELS) — a user-added repo has no// such contract, so it always gets the full snapshot.+ const downloadTarget = { repo: body.repo, ignore: fixedModel?.downloadIgnore ?? [] };+ if (fixedModel?.revision) downloadTarget.revision = fixedModel.revision;await startHfDownloadStream({req,res,- repos: [{ repo: body.repo, ignore: fixedModel?.downloadIgnore ?? [] }],+ repos: [downloadTarget],});// Roll back if the weights aren't actually present now (failed/cancelled// download) so a bogus repo doesn't persist. Best-effort: a rollback failure// is logged by the service, not surfaced (the response already closed).- const cached = await inspectModelCache(body.repo).catch(() => ({ cached: false }));+ const cacheOptions = fixedModel?.revision ? { revision: fixedModel.revision } : {};+ const cached = await inspectModelCache(body.repo, cacheOptions).catch(() => ({ cached: false }));if (!cached.cached) {if (!fixedModel) await removeAudioModel({ engine: body.engine, id: body.repo }).catch(() => {});}diff --git a/server/routes/music.test.js b/server/routes/music.test.jsindex f9d511fef7..f4af5fa291 100644--- a/server/routes/music.test.js+++ b/server/routes/music.test.js@@ -24,6 +24,10 @@ vi.mock('../services/pipeline/musicGen.js', () => {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', downloadIgnore: ['qwen_7B/*', 'flowmatching_vae.pth', 'dav.pth', 'figures/*'], downloadSizeGb: 29 }], 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 },+ 'minimax-music3-mlx': { id: 'minimax-music3-mlx', name: 'MiniMax Music 3 (MLX)', models: [+ { id: 'minimax-music3-mlx-8bit', repo: 'mlx-community/MiniMax-Music3-8bit', revision: '10aa4ca578d04c6f5256c1bc22fc8405a09602b5', downloadSizeGb: 14, name: 'MiniMax Music 3 MLX 8-bit' },+ { id: 'minimax-music3-mlx-bf16', repo: 'mlx-community/MiniMax-Music3-bf16', revision: '83a5f2d365673689df5c8f36e21e108751fd92ea', downloadSizeGb: 29, name: 'MiniMax Music 3 MLX BF16' },+ ], defaultModelId: 'minimax-music3-mlx-8bit', minDurationSec: 1, maxDurationSec: 300, defaultDurationSec: 60, installEnv: 'INSTALL_MINIMAX_MUSIC3_MLX', venvDefault: '/v/minimax-mlx', resolvePython: () => (gen.ready ? '/v/minimax-mlx/bin/python3' : null), lyrics: true, customModels: false, fixedModelInstall: true, autoDuration: true },};return {ENGINES,@@ -103,8 +107,11 @@ vi.mock('../lib/sseDownload.js', () => ({}));// Register-after-download gates on whether the repo landed in the cache.-const cache = vi.hoisted(() => ({ cached: true }));-vi.mock('../lib/hfCache.js', () => ({ inspectModelCache: vi.fn(async () => ({ cached: cache.cached })) }));+const cache = vi.hoisted(() => ({ cached: true, byRevision: null, calls: [] }));+vi.mock('../lib/hfCache.js', () => ({ inspectModelCache: vi.fn(async (repo, options = {}) => {+ cache.calls.push({ repo, ...options });+ return { cached: cache.byRevision?.[options.revision] ?? cache.cached };+}) }));vi.mock('../services/albums/index.js', () => ({getAlbum: vi.fn(async () => null),@@ -159,6 +166,8 @@ describe('music routes', () => {setup.spawn.mockReset();setup.exitCode = 0;cache.cached = true;+ cache.byRevision = null;+ cache.calls.length = 0;cuda.status = 'available';models.list.mockResolvedValue([{ id: 'm', name: 'M', userAdded: false }]);designer.describeMusic.mockReset().mockResolvedValue({ description: 'Lush pads over a broken beat.', llm: { provider: 'fake-provider', model: 'fake-model' } });@@ -300,6 +309,29 @@ describe('music routes', () => {});});+ it('GET /engines reports MLX readiness separately for the 8-bit and BF16 snapshots', async () => {+ cache.byRevision = {+ '10aa4ca578d04c6f5256c1bc22fc8405a09602b5': true,+ '83a5f2d365673689df5c8f36e21e108751fd92ea': false,+ };+ const r = await request(app).get('/api/music/engines');+ expect(r.status).toBe(200);+ expect(r.body.engines.find((e) => e.id === 'minimax-music3-mlx')).toMatchObject({+ modelReady: true,+ modelReadyById: {+ 'minimax-music3-mlx-8bit': true,+ 'minimax-music3-mlx-bf16': false,+ },+ ready: true,+ platformSupported: true,+ installEnv: 'INSTALL_MINIMAX_MUSIC3_MLX',+ });+ expect(cache.calls).toEqual(expect.arrayContaining([+ { repo: 'mlx-community/MiniMax-Music3-8bit', revision: '10aa4ca578d04c6f5256c1bc22fc8405a09602b5' },+ { repo: 'mlx-community/MiniMax-Music3-bf16', revision: '83a5f2d365673689df5c8f36e21e108751fd92ea' },+ ]));+ });+it('GET /engines exposes ACE-Step 1.5 as a fixed model install distinct from v1', async () => {cache.cached = false;const r = await request(app).get('/api/music/engines');@@ -411,6 +443,25 @@ describe('music routes', () => {expect(models.add).toHaveBeenCalledWith({ engine: 'musicgen', repo: 'facebook/musicgen-large', name: undefined });});+ it('POST /models pins a fixed MLX download to the shipped revision', async () => {+ const r = await request(app).post('/api/music/models').send({+ engine: 'minimax-music3-mlx', repo: 'mlx-community/MiniMax-Music3-8bit',+ });+ expect(r.status).toBe(200);+ expect(models.add).not.toHaveBeenCalled();+ expect(sse.run).toHaveBeenCalledWith(expect.objectContaining({+ repos: [{+ repo: 'mlx-community/MiniMax-Music3-8bit',+ ignore: [],+ revision: '10aa4ca578d04c6f5256c1bc22fc8405a09602b5',+ }],+ }));+ expect(cache.calls).toContainEqual({+ repo: 'mlx-community/MiniMax-Music3-8bit',+ revision: '10aa4ca578d04c6f5256c1bc22fc8405a09602b5',+ });+ });+it('POST /models forwards a shipped fixed model\'s downloadIgnore to the download stream', async () => {const r = await request(app).post('/api/music/models').send({ engine: 'minimax-music3', repo: 'MiniMaxAI/MiniMax-Music3' });expect(r.status).toBe(200);diff --git a/server/services/audioModels.js b/server/services/audioModels.jsindex e152cce4de..0b6a5f755b 100644--- a/server/services/audioModels.js+++ b/server/services/audioModels.js@@ -75,13 +75,19 @@ export async function listUserModels(engineId) {/*** The combined model list for an engine: shipped defaults (from musicGen.js)- * first, then user-added, deduped by id. Returned shape is `{ id, name, repo? }`+ * first, then user-added, deduped by id. Returned shape is `{ id, name, repo?, revision? }`* matching the shipped models so the route/UI treat them uniformly. `userAdded`* marks the entries this registry contributed (so the UI can offer "remove").*/export async function listEngineModels(engineId) {const engine = getEngine(engineId);- const shipped = engine.models.map((m) => ({ id: m.id, name: m.name, repo: m.repo, userAdded: false }));+ const shipped = engine.models.map((m) => ({+ id: m.id,+ name: m.name,+ repo: m.repo,+ ...(m.revision ? { revision: m.revision } : {}),+ userAdded: false,+ }));const seen = new Set(shipped.map((m) => m.id));const user = (await listUserModels(engine.id)).filter((m) => !seen.has(m.id))diff --git a/server/services/pipeline/musicGen.js b/server/services/pipeline/musicGen.jsindex ebee69002d..e97f1a21f7 100644--- a/server/services/pipeline/musicGen.js+++ b/server/services/pipeline/musicGen.js@@ -11,6 +11,9 @@* (≤30s; trained on 30s windows, degrades past that). First backend.* - `audioldm2` — AudioLDM2 latent diffusion via HuggingFace `diffusers`.* Long-form (well past 30s), torch on MPS/CUDA/CPU. Second backend.+ * - `minimax-music3` — MiniMax Music 3 via CUDA Diffusers, up to five minutes.+ * - `minimax-music3-mlx` — native MiniMax Music 3 on Apple Silicon via MLX,+ * with selectable 8-bit and BF16 checkpoints.** An ENGINES registry holds each backend's models, duration window, sidecar* script, venv resolver and install hint, so the route, UI and `generateMusic`@@ -22,8 +25,8 @@* `generateMusic` throws a 503 with that backend's install hint rather than a* bare spawn error — exactly like the FLUX.2 venv gate.*- * Output: a mono WAV written into the shared music library (PATHS.music) under- * a `music-gen-<uuid>.wav` basename, so the picker treats a generated track+ * Output: a WAV written into the shared music library (PATHS.music) under a+ * `music-gen-<uuid>.wav` basename, so the picker treats a generated track* identically to an uploaded one.*/@@ -44,6 +47,7 @@ import {resolveAcestepPython, ACESTEP_RUNTIME_DIR, ACESTEP_VENV_DEFAULT,resolveAcestep15Python, ACESTEP15_RUNTIME_DIR, ACESTEP15_VENV_DEFAULT,resolveMinimaxMusic3Python, MINIMAX_MUSIC3_RUNTIME_DIR, MINIMAX_MUSIC3_VENV_DEFAULT,+ resolveMinimaxMusic3MlxPython, MINIMAX_MUSIC3_MLX_RUNTIME_DIR, MINIMAX_MUSIC3_MLX_VENV_DEFAULT,} from '../../lib/pythonSetup.js';import { getCudaCapability } from '../../lib/cudaCapability.js';import { inspectModelCache } from '../../lib/hfCache.js';@@ -62,6 +66,7 @@ const AUDIOLDM2_SCRIPT = join(__dirname, '../../../scripts/generate_audioldm2.pyconst ACESTEP_SCRIPT = join(__dirname, '../../../scripts/generate_acestep.py');const ACESTEP15_SCRIPT = join(__dirname, '../../../scripts/generate_acestep15.py');const MINIMAX_MUSIC3_SCRIPT = join(__dirname, '../../../scripts/generate_minimax_music3.py');+const MINIMAX_MUSIC3_MLX_SCRIPT = join(__dirname, '../../../scripts/generate_minimax_music3_mlx.py');// Back-compat alias for the pre-multi-engine `buildMusicGenArgs` default.const SIDECAR_SCRIPT = MUSICGEN_SCRIPT;@@ -120,12 +125,33 @@ export const MINIMAX_MUSIC3_MODELS = Object.freeze([{id: 'minimax-music3',repo: 'MiniMaxAI/MiniMax-Music3',- name: 'MiniMax Music 3 (CUDA, up to 5 minutes)',+ name: 'MiniMax-Music3 (CUDA, up to 5 minutes)',downloadIgnore: Object.freeze(['qwen_7B/*', 'flowmatching_vae.pth', 'dav.pth', 'figures/*']),downloadSizeGb: 29,},]);+// These are immutable HF revisions because a shipped model must not silently+// change underneath an existing install. The 8-bit conversion is the practical+// default for general Apple-Silicon installs (~14 GB); BF16 remains selectable+// as the larger unquantized reference (~29 GB) for high-memory systems.+export const MINIMAX_MUSIC3_MLX_MODELS = Object.freeze([+ {+ id: 'minimax-music3-mlx-8bit',+ repo: 'mlx-community/MiniMax-Music3-8bit',+ revision: '10aa4ca578d04c6f5256c1bc22fc8405a09602b5',+ downloadSizeGb: 14,+ name: 'MiniMax-Music3 MLX 8-bit (~14 GB, lower-memory default)',+ },+ {+ id: 'minimax-music3-mlx-bf16',+ repo: 'mlx-community/MiniMax-Music3-bf16',+ revision: '83a5f2d365673689df5c8f36e21e108751fd92ea',+ downloadSizeGb: 29,+ name: 'MiniMax-Music3 MLX BF16 (~29 GB, unquantized reference)',+ },+]);+/*** Backend registry. Each engine is fully described here so the route, UI and* `generateMusic` stay generator-agnostic. Fields:@@ -242,7 +268,7 @@ export const ENGINES = Object.freeze({},'minimax-music3': {id: 'minimax-music3',- name: 'MiniMax Music 3 (CUDA only)',+ name: 'MiniMax-Music3 (CUDA only)',models: MINIMAX_MUSIC3_MODELS,defaultModelId: 'minimax-music3',minDurationSec: 1,@@ -272,6 +298,32 @@ export const ENGINES = Object.freeze({fixedModelInstall: true,cudaRequired: true,},+ 'minimax-music3-mlx': {+ id: 'minimax-music3-mlx',+ name: 'MiniMax-Music3 (MLX, Apple Silicon)',+ models: MINIMAX_MUSIC3_MLX_MODELS,+ defaultModelId: 'minimax-music3-mlx-8bit',+ minDurationSec: 1,+ maxDurationSec: 300,+ defaultDurationSec: 60,+ scriptPath: MINIMAX_MUSIC3_MLX_SCRIPT,+ runtimeDir: MINIMAX_MUSIC3_MLX_RUNTIME_DIR,+ resolvePython: resolveMinimaxMusic3MlxPython,+ venvDefault: MINIMAX_MUSIC3_MLX_VENV_DEFAULT,+ installEnv: 'INSTALL_MINIMAX_MUSIC3_MLX',+ healthProbe: 'import mlx; from mlx_audio.music import load',+ lyrics: true,+ instrumentalLyrics: buildMinimaxInstrumentalLyrics,+ autoDuration: true,+ customModels: false,+ fixedModelInstall: true,+ supportsModelRevision: true,+ requiresPlatform: {+ platform: 'darwin',+ arch: 'arm64',+ label: 'macOS on Apple Silicon (MLX)',+ },+ },});export const DEFAULT_ENGINE_ID = 'musicgen';@@ -433,16 +485,19 @@ export function buildMinimaxInstrumentalLyrics(durationSec) {* spawning Python. All sidecars share the same base flag contract* (`--model/--text/--duration/--output/--runtime-dir`), so one builder serves* every engine; `engineId` selects the duration window + script + runtime dir.+ * Engines with immutable shipped snapshots can opt into `--revision` so the+ * Python loader and the local cache inspect the same HF commit.* Lyric-aware engines (`engine.lyrics`, e.g. ACE-Step) additionally get* `--lyrics`; non-lyric engines never receive the flag (their sidecars don't* define it), so a stray lyrics arg can't break a MusicGen/AudioLDM2 spawn.*/-export function buildSidecarArgs({ engineId = DEFAULT_ENGINE_ID, pythonPath, scriptPath, runtimeDir, repo, prompt, lyrics, durationSec, outputPath }) {+export function buildSidecarArgs({ engineId = DEFAULT_ENGINE_ID, pythonPath, scriptPath, runtimeDir, repo, revision, prompt, lyrics, durationSec, outputPath }) {const engine = getEngine(engineId);const seconds = clampDuration(durationSec, engine.id);const args = [scriptPath ?? engine.scriptPath,'--model', repo,+ ...(engine.supportsModelRevision && revision ? ['--revision', revision] : []),// 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 —@@ -482,10 +537,10 @@ export function buildMusicGenArgs({ pythonPath, scriptPath = SIDECAR_SCRIPT, run* (500) when the sidecar exits non-zero / produces no result.** `engine` selects the backend (`musicgen` | `audioldm2` | `acestep` |- * `acestep15`); unknown+ * `acestep15` | `minimax-music3` | `minimax-music3-mlx`); unknown* ids fall back to the default. `modelId` is resolved within that engine's- * registry. `lyrics` is forwarded only to lyric-aware engines (ACE-Step); other- * engines ignore it. `signal` (optional AbortSignal) SIGTERMs the child — wired+ * registry. `lyrics` is forwarded only to lyric-aware engines; other engines+ * ignore it. `signal` (optional AbortSignal) SIGTERMs the child — wired* through so a cancel button can abort a long render. `onActivity` (optional)* fires once per `STAGE:` line the sidecar emits — the media-job queue's* generic idle watchdog resets its timer off it via the audio job-kind@@ -526,7 +581,7 @@ export async function generateMusic({ prompt, lyrics, engine: engineId = DEFAULT}}if (engine.fixedModelInstall) {- const cache = await inspectModelCache(model.repo).catch(() => ({ cached: false }));+ const cache = await inspectModelCache(model.repo, { revision: model.revision }).catch(() => ({ cached: false }));if (!cache.cached) {throw new ServerError(`${engine.name} model weights are not installed. Install them from Music before generating.`, {status: 503, code: 'PIPELINE_MUSIC_MODEL_MISSING',@@ -549,7 +604,7 @@ export async function generateMusic({ prompt, lyrics, engine: engineId = DEFAULTawait ensureDir(PATHS.music);const filename = `music-gen-${randomUUID()}.wav`;const outputPath = join(PATHS.music, filename);- const { bin, args } = buildSidecarArgs({ engineId: engine.id, pythonPath, repo: model.repo, prompt: text, lyrics, durationSec: resolvedDuration, outputPath });+ const { bin, args } = buildSidecarArgs({ engineId: engine.id, pythonPath, repo: model.repo, revision: model.revision, prompt: text, lyrics, durationSec: resolvedDuration, outputPath });console.log(`🎼 Generating music [${engine.id}/${model.id}] ${clampDuration(resolvedDuration, engine.id)}s: "${text.slice(0, 60)}"`);// The default backends use ungated HF weights (facebook/* and cvssp/*), so adiff --git a/server/services/pipeline/musicGen.test.js b/server/services/pipeline/musicGen.test.jsindex 562f6539a3..67c54d1270 100644--- a/server/services/pipeline/musicGen.test.js+++ b/server/services/pipeline/musicGen.test.js@@ -26,6 +26,7 @@ import {DEFAULT_ENGINE_ID,MUSICGEN_MODELS,AUDIOLDM2_MODELS,+ MINIMAX_MUSIC3_MLX_MODELS,DEFAULT_MUSICGEN_MODEL_ID,DEFAULT_AUDIOLDM2_MODEL_ID,MIN_DURATION_SEC,@@ -72,7 +73,7 @@ describe('AUDIOLDM2_MODELS registry', () => {describe('ENGINES backend registry', () => {it('exposes all backends with the fields the route + UI consume', () => {- expect(Object.keys(ENGINES).sort()).toEqual(['acestep', 'acestep15', 'audioldm2', 'minimax-music3', 'musicgen']);+ expect(Object.keys(ENGINES).sort()).toEqual(['acestep', 'acestep15', 'audioldm2', 'minimax-music3', 'minimax-music3-mlx', 'musicgen']);for (const engine of Object.values(ENGINES)) {expect(typeof engine.id).toBe('string');expect(typeof engine.name).toBe('string');@@ -108,6 +109,24 @@ describe('ENGINES backend registry', () => {expect(ENGINES.acestep.models[0].repo).toBe('ACE-Step/ACE-Step-v1-3.5B');});+ it('offers both pinned MLX MiniMax variants with 8-bit as the default', () => {+ expect(ENGINES['minimax-music3-mlx']).toMatchObject({+ id: 'minimax-music3-mlx',+ name: expect.stringContaining('MiniMax-Music3'),+ defaultModelId: 'minimax-music3-mlx-8bit',+ installEnv: 'INSTALL_MINIMAX_MUSIC3_MLX',+ lyrics: true,+ customModels: false,+ fixedModelInstall: true,+ supportsModelRevision: true,+ requiresPlatform: { platform: 'darwin', arch: 'arm64' },+ });+ expect(MINIMAX_MUSIC3_MLX_MODELS).toEqual([+ expect.objectContaining({ id: 'minimax-music3-mlx-8bit', repo: 'mlx-community/MiniMax-Music3-8bit', revision: expect.stringMatching(/^[0-9a-f]{40}$/) }),+ expect.objectContaining({ id: 'minimax-music3-mlx-bf16', repo: 'mlx-community/MiniMax-Music3-bf16', revision: expect.stringMatching(/^[0-9a-f]{40}$/) }),+ ]);+ });+it('musicgen window mirrors the legacy module-level constants', () => {expect(ENGINES.musicgen.minDurationSec).toBe(MIN_DURATION_SEC);expect(ENGINES.musicgen.maxDurationSec).toBe(MAX_DURATION_SEC);@@ -175,6 +194,19 @@ describe('buildSidecarArgs', () => {expect(args.slice(args.indexOf('--duration'), args.indexOf('--duration') + 2)).toEqual(['--duration', '300']);expect(args.slice(args.indexOf('--lyrics'), args.indexOf('--lyrics') + 2)).toEqual(['--lyrics', 'Example lyrics']);});++ it('pins the selected MLX checkpoint revision in the sidecar args', () => {+ const { args } = buildSidecarArgs({+ engineId: 'minimax-music3-mlx', pythonPath: '/venv/python', repo: 'mlx-community/MiniMax-Music3-8bit',+ revision: '10aa4ca578d04c6f5256c1bc22fc8405a09602b5', prompt: 'bright pop', lyrics: '[verse] Example',+ durationSec: 30, outputPath: '/tmp/out.wav',+ });+ expect(args.slice(args.indexOf('--revision'), args.indexOf('--revision') + 2)).toEqual([+ '--revision', '10aa4ca578d04c6f5256c1bc22fc8405a09602b5',+ ]);+ expect(args[0]).toMatch(/generate_minimax_music3_mlx\.py$/);+ expect(args).toContain('--lyrics');+ });const base = {pythonPath: '/venv/bin/python3',repo: 'facebook/musicgen-medium',@@ -310,6 +342,7 @@ const h = vi.hoisted(() => ({musicgenPython: '/fake/venv-musicgen/bin/python3',audioldm2Python: '/fake/venv-audioldm2/bin/python3',minimaxMusic3Python: '/fake/venv-minimax-music3/bin/python3',+ minimaxMusic3MlxPython: '/fake/venv-minimax-music3-mlx/bin/python3',// isEngineHealthy's import probe: which interpreters it ran, and whether the// import succeeded (a half-built venv exits non-zero).probeCalls: [],@@ -389,6 +422,7 @@ vi.mock('../../lib/pythonSetup.js', async () => {resolveMusicgenPython: () => h.musicgenPython,resolveAudioldm2Python: () => h.audioldm2Python,resolveMinimaxMusic3Python: () => h.minimaxMusic3Python,+ resolveMinimaxMusic3MlxPython: () => h.minimaxMusic3MlxPython,};});@@ -404,6 +438,7 @@ beforeEach(() => {h.musicgenPython = '/fake/venv-musicgen/bin/python3';h.audioldm2Python = '/fake/venv-audioldm2/bin/python3';h.minimaxMusic3Python = '/fake/venv-minimax-music3/bin/python3';+ h.minimaxMusic3MlxPython = '/fake/venv-minimax-music3-mlx/bin/python3';h.probeCalls.length = 0;h.probeOk = true;h.osPlatform = 'darwin';@@ -440,6 +475,25 @@ describe('generateMusic backend selection', () => {expect(duration).toBe('120');});+ it('routes MiniMax Music 3 MLX to its sibling venv and pins the selected checkpoint', async () => {+ await generateMusic({+ prompt: 'warm cinematic pop',+ lyrics: '[verse]\nExample words',+ engine: 'minimax-music3-mlx',+ modelId: 'minimax-music3-mlx-bf16',+ durationSec: 30,+ });+ expect(spawnCalls).toHaveLength(1);+ expect(spawnCalls[0].bin).toBe('/fake/venv-minimax-music3-mlx/bin/python3');+ expect(spawnCalls[0].args[0]).toMatch(/generate_minimax_music3_mlx\.py$/);+ expect(spawnCalls[0].args.slice(spawnCalls[0].args.indexOf('--model'), spawnCalls[0].args.indexOf('--model') + 2)).toEqual([+ '--model', 'mlx-community/MiniMax-Music3-bf16',+ ]);+ expect(spawnCalls[0].args.slice(spawnCalls[0].args.indexOf('--revision'), spawnCalls[0].args.indexOf('--revision') + 2)).toEqual([+ '--revision', '83a5f2d365673689df5c8f36e21e108751fd92ea',+ ]);+ });+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);