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

add ACE-Step on-device music generation + HuggingFace audio-model installer

[._.]/ Adam Eivy3149909538dc
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 73304e489b..ddae4ed300 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -14,10 +14,13 @@
- **Music studio (Create → Music).** A new home for generating and organizing music with local OSS tools, with three tabs:
- **Artists** — reusable musical personas (the audio analogue of Authors): name, genre, bio, musical style, plus a physical description + portrait style used to **generate an artist portrait** with your existing image-gen options, **upload** one, or pick from the gallery.
- **Albums** — ordered track collections under an artist, with **cover art** you generate (1024×1024 via your image-gen options), upload, or pick from the gallery; add tracks and reorder them.
- - **Tracks** — singles or album members with lyrics + a generation prompt and an audio file you **upload** or **attach** from the shared music library, played back inline. The generation prompt/lyrics and engine/model/duration metadata are captured now; the on-device **Generate** button (Ace-Step and friends) wires in next update.
+ - **Tracks** — singles or album members with lyrics + a generation prompt and an audio file you **upload**, **attach** from the shared music library, or **generate on-device** (see below), played back inline.
Artists, Albums, and Tracks are db-primary PostgreSQL entities (federation-ready, mirroring Authors). Cross-peer sync for them is tracked separately (#1502); for now they're local-only.
+- **On-device music generation in the Track editor.** Generate a track's audio locally from its prompt (+ lyrics) — no API key, no network at inference. Three OSS engines behind one picker: **MusicGen** (MLX) and **AudioLDM2** (diffusers) for instrumental/ambient beds, and **ACE-Step** (`INSTALL_ACESTEP=1 bash scripts/setup-image-video.sh`) for full songs *with vocals*, which uses the track's lyrics as conditioning. Engines whose opt-in venv isn't installed show their install hint and gate the Generate button (same posture as the FLUX.2 image venv). The generated WAV lands in the shared music library and attaches to the track with its engine/model/duration metadata.
+- **Install additional audio models from HuggingFace.** The Track editor's generator panel can pull extra checkpoints (e.g. a larger MusicGen, an AudioLDM2 variant) straight from HuggingFace into the local cache — same streamed-download path as the image/video model installer — and they become selectable for generation immediately. User-installed models persist in `data/audio-models.json` and can be removed from the same panel.
+
- **Autopilot convergence rounds are now configurable.** The series autopilot re-verifies the arc (and re-reviews the manuscript) in bounded auto-resolve loops, and previously hard-stopped after 3 arc rounds / 2 editorial rounds with "did not converge after 3 rounds" — leaving no way to give a stubborn arc more attempts. You can now set **Arc verify rounds** and **Editorial rounds** (0–20, where 0 skips that gate) in Autonomous mode → **Options**; the values persist as a per-install default and are reused on **Resume**. A per-run override still wins over the saved default, which wins over the built-in floor (3 / 2). When a gate still can't auto-resolve within the limit, the pause message now says how many blocking findings remain and points you to edit the arc/manuscript or raise the limit and resume.
- Editorial Checks page now has an AI provider + model selector that configures the editorial pass. Leave it on "Default provider" to use the active/stage provider, or pick a specific provider/model to override the LLM-backed checks for that run.
- App **Automation** tabs now show a banner when scheduled automation is globally paused, with a one-click **Resume**. Manually clicking **Run** on a task now bypasses the global pause — the pause only stops scheduled/autonomous spawning, not explicit user triggers.
diff --git a/client/src/components/music/MusicGenPanel.jsx b/client/src/components/music/MusicGenPanel.jsx
new file mode 100644
index 0000000000..ce901cf9d2
--- /dev/null
+++ b/client/src/components/music/MusicGenPanel.jsx
@@ -0,0 +1,221 @@
+/**
+ * MusicGenPanel — on-device music generation for the Track editor.
+ *
+ * Lets the user pick a generation engine (MusicGen / AudioLDM2 / ACE-Step),
+ * pick or install a model, and Generate audio from the track's prompt (+ lyrics
+ * for lyric-aware engines like ACE-Step). 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
+ * their install hint 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.
+ */
+
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { Loader2, Wand2, Download, X } from 'lucide-react';
+import toast from '../ui/Toast';
+import {
+ listMusicEngines, generateMusic, installAudioModel, removeAudioModel,
+} from '../../services/api';
+
+export default function MusicGenPanel({ track, prompt, lyrics, onGenerated }) {
+ const [engines, setEngines] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [engineId, setEngineId] = useState('');
+ const [modelId, setModelId] = useState('');
+ const [durationSec, setDurationSec] = useState(null);
+ const [generating, setGenerating] = useState(false);
+ // Inline HF model install.
+ const [installRepo, setInstallRepo] = useState('');
+ const [installing, setInstalling] = useState(false);
+ const [installProgress, setInstallProgress] = useState(null);
+ const mountedRef = useRef(true);
+ useEffect(() => () => { mountedRef.current = false; }, []);
+
+ const loadEngines = async () => {
+ const data = await listMusicEngines({ silent: true }).catch(() => null);
+ if (!mountedRef.current) return;
+ const list = Array.isArray(data?.engines) ? data.engines : [];
+ setEngines(list);
+ setLoading(false);
+ // Default to the first READY engine, else the server default, else the first.
+ if (!engineId && list.length) {
+ const ready = list.find((e) => e.ready);
+ const pick = ready || list.find((e) => e.id === data.defaultEngine) || list[0];
+ setEngineId(pick.id);
+ }
+ };
+
+ useEffect(() => { loadEngines(); }, []);
+
+ const engine = useMemo(() => engines.find((e) => e.id === engineId) || null, [engines, engineId]);
+
+ // Reset model + duration to the engine's defaults whenever the engine changes.
+ useEffect(() => {
+ if (!engine) return;
+ setModelId(engine.defaultModelId || engine.models?.[0]?.id || '');
+ setDurationSec((d) => (d == null ? engine.defaultDurationSec : d));
+ }, [engine]);
+
+ const canGenerate = !!engine?.ready && !!prompt?.trim() && !generating && !!track?.id;
+
+ const handleGenerate = async () => {
+ if (!engine) return;
+ if (!track?.id) { toast.error('Save the track first, then generate'); return; }
+ if (!prompt?.trim()) { toast.error('Add a generation prompt first'); return; }
+ setGenerating(true);
+ const body = {
+ prompt: prompt.trim(),
+ lyrics: engine.lyrics ? (lyrics || '') : '',
+ engine: engine.id,
+ modelId,
+ trackId: track.id,
+ };
+ 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);
+ if (res?.track) {
+ onGenerated?.(res.track);
+ toast.success('Track generated');
+ }
+ };
+
+ const handleInstall = async () => {
+ const repo = installRepo.trim();
+ if (!repo || !engine) return;
+ setInstalling(true);
+ setInstallProgress({ message: `Starting ${repo}…` });
+ await installAudioModel({ engine: engine.id, repo }, (ev) => {
+ if (!mountedRef.current) return;
+ if (ev.type === 'progress') setInstallProgress({ message: `${ev.file || 'downloading'} — ${Math.round((ev.progress || 0) * 100)}%`, progress: ev.progress });
+ else if (ev.type === 'stage') setInstallProgress({ message: ev.stage });
+ else if (ev.type === 'error') { toast.error(ev.message || 'Download failed'); }
+ }).catch((err) => { if (mountedRef.current) toast.error(err.message || 'Install failed'); });
+ if (!mountedRef.current) return;
+ setInstalling(false);
+ setInstallProgress(null);
+ setInstallRepo('');
+ await loadEngines(); // refresh model list (the new repo is now registered)
+ setModelId(repo);
+ toast.success(`Installed ${repo}`);
+ };
+
+ const handleRemoveModel = async (id) => {
+ if (!engine) return;
+ await removeAudioModel(engine.id, id, { silent: true }).catch((err) => { toast.error(err.message || 'Remove failed'); return null; });
+ await loadEngines();
+ if (modelId === id) setModelId(engine.defaultModelId || '');
+ };
+
+ if (loading) return <div className="text-xs text-gray-500">Loading generators…</div>;
+ if (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);
+
+ return (
+ <div className="space-y-2 border border-port-border rounded-lg p-3 bg-port-bg/40">
+ <div className="flex items-center gap-2 text-sm text-gray-300">
+ <Wand2 size={14} className="text-port-accent" /> Generate audio on-device
+ </div>
+
+ <div className="grid grid-cols-2 gap-2">
+ <label className="block">
+ <span className="block text-[11px] uppercase tracking-wider text-gray-500 mb-1">Engine</span>
+ <select
+ value={engineId}
+ onChange={(e) => setEngineId(e.target.value)}
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
+ >
+ {engines.map((e) => (
+ <option key={e.id} value={e.id}>{e.name}{e.ready ? '' : ' (not installed)'}</option>
+ ))}
+ </select>
+ </label>
+ <label className="block">
+ <span className="block text-[11px] uppercase tracking-wider text-gray-500 mb-1">Model</span>
+ <select
+ value={modelId}
+ onChange={(e) => setModelId(e.target.value)}
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
+ >
+ {(engine?.models || []).map((m) => (
+ <option key={m.id} value={m.id}>{m.name}{m.userAdded ? ' (installed)' : ''}</option>
+ ))}
+ </select>
+ </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>
+
+ {engine && !engine.ready ? (
+ <p className="text-[11px] text-port-warning">
+ {engine.name} isn’t installed. Run <code className="text-gray-300">{engine.installEnv}=1 bash scripts/setup-image-video.sh</code> to provision it.
+ </p>
+ ) : null}
+ {engine?.lyrics ? (
+ <p className="text-[11px] text-gray-500">This engine uses the track’s lyrics as conditioning.</p>
+ ) : null}
+
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={handleGenerate}
+ disabled={!canGenerate}
+ title={!track?.id ? 'Save the track first' : !prompt?.trim() ? 'Add a generation prompt' : !engine?.ready ? 'Engine not installed' : 'Generate audio'}
+ 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} />}
+ {generating ? 'Generating…' : 'Generate'}
+ </button>
+ {selectedUserModel ? (
+ <button
+ type="button"
+ onClick={() => handleRemoveModel(selectedUserModel.id)}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-gray-400 hover:text-port-error text-xs"
+ title="Remove this installed model"
+ >
+ <X size={12} /> Remove model
+ </button>
+ ) : null}
+ </div>
+
+ {/* Install an additional model from HuggingFace. */}
+ <div className="pt-2 border-t border-port-border/60">
+ <span className="block text-[11px] uppercase tracking-wider text-gray-500 mb-1">Install a model from HuggingFace</span>
+ <div className="flex items-center gap-2">
+ <input
+ value={installRepo}
+ onChange={(e) => setInstallRepo(e.target.value)}
+ placeholder="org/model-repo"
+ disabled={installing}
+ className="flex-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm disabled:opacity-50"
+ />
+ <button
+ type="button"
+ onClick={handleInstall}
+ disabled={installing || !installRepo.trim()}
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50"
+ >
+ {installing ? <Loader2 size={14} className="animate-spin" /> : <Download size={14} />}
+ Install
+ </button>
+ </div>
+ {installProgress ? <p className="text-[11px] text-gray-500 mt-1 truncate">{installProgress.message}</p> : null}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/music/TracksManager.jsx b/client/src/components/music/TracksManager.jsx
index fc688bf9ee..187275b863 100644
--- a/client/src/components/music/TracksManager.jsx
+++ b/client/src/components/music/TracksManager.jsx
@@ -17,6 +17,7 @@ import { Plus, Loader2, Trash2, Save, Upload, Music2, X, Library } from 'lucide-
import toast from '../ui/Toast';
import { formatTimecode } from '../../utils/formatters';
import ArtistPicker from './ArtistPicker';
+import MusicGenPanel from './MusicGenPanel';
import {
listTracks, createTrack, updateTrack, deleteTrack,
uploadTrackAudio, attachTrackAudio, clearTrackAudio, listMusicLibrary, listAlbums,
@@ -323,6 +324,21 @@ export default function TracksManager() {
</div>
) : null}
+ {/* On-device generation — available once the track is saved (the
+ server attaches the audio + metadata to the persisted track).
+ Uses the CURRENT prompt/lyrics in the form. */}
+ {persisted ? (
+ <MusicGenPanel
+ track={persisted}
+ prompt={form.prompt}
+ lyrics={form.lyrics}
+ onGenerated={(updated) => {
+ upsertLocal(updated);
+ if (selectedIdRef.current === updated.id) setForm(formFromTrack(updated));
+ }}
+ />
+ ) : null}
+
<Field label="Audio" hint="Upload an audio file or attach one from the shared music library. Save the track first.">
{form.audioFilename ? (
<div className="space-y-2">
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 1ae1441625..5f1f295440 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -93,6 +93,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiArtists.js` | Music artist personas (name, genre, bio, musical style, portrait description/style). |
| `apiAlbums.js` | Music albums (title, artist FK + name, description, genre, release year, cover art, ordered track ids). |
| `apiTracks.js` | Music tracks (title, album/artist FKs, lyrics, prompt, gen metadata, audio-library pointer) + shared music-library list + audio upload/attach/clear. |
+| `apiMusic.js` | On-device music generation (MusicGen / AudioLDM2 / ACE-Step): list engines (+ readiness) and generate a track from a prompt/lyrics. |
| `apiWritersRoom.js` | Writers Room (folders + works + drafts, live continuation + render-preview reservation, scene-image attach). |
| `apiSharing.js` | Share buckets + federation sync. |
| `apiRounds.js` | Rounds workbench CRUD (a cappella round writing + arranging voice layers + learning tracking). |
diff --git a/client/src/services/api.js b/client/src/services/api.js
index a5d5f5dc3e..4e2c27376f 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -51,6 +51,7 @@ export * from './apiAuthors.js';
export * from './apiArtists.js';
export * from './apiAlbums.js';
export * from './apiTracks.js';
+export * from './apiMusic.js';
export * from './apiPipeline.js';
export * from './apiSharing.js';
export * from './apiRounds.js';
diff --git a/client/src/services/apiMusic.js b/client/src/services/apiMusic.js
new file mode 100644
index 0000000000..b64a3580dd
--- /dev/null
+++ b/client/src/services/apiMusic.js
@@ -0,0 +1,62 @@
+import { request } from './apiCore.js';
+
+// ---- Music generation (on-device) ----
+// The Music studio's generator surface over server/services/pipeline/musicGen.js
+// (MusicGen / AudioLDM2 / ACE-Step behind one contract). `options` lets a caller
+// suppress request()'s auto-toast with `{ silent: true }`.
+
+// List selectable engines with their models, duration window, lyric capability,
+// and a `ready` flag (the opt-in venv is provisioned) → { engines, defaultEngine }.
+export const listMusicEngines = (options = {}) => request('/music/engines', options);
+
+// Generate a track. body: { prompt, lyrics?, engine?, modelId?, durationSec?,
+// 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 }`.
+export const generateMusic = (body, requestOptions = {}) => request('/music/generate', {
+ method: 'POST',
+ body: JSON.stringify(body),
+ ...requestOptions,
+});
+
+// The merged shipped+user model list for one engine → { models }.
+export const listEngineModels = (engine, options = {}) => request(`/music/models/${encodeURIComponent(engine)}`, options);
+
+// De-register a user-installed model (id is the HF repo id) → { removed }.
+export const removeAudioModel = (engine, id, requestOptions = {}) =>
+ request(`/music/models/${encodeURIComponent(engine)}/${id.split('/').map(encodeURIComponent).join('/')}`, {
+ method: 'DELETE',
+ ...requestOptions,
+ });
+
+// Install an additional audio model from HuggingFace into an engine. The server
+// streams the download as Server-Sent Events; this helper drives an EventSource
+// and invokes `onEvent({ type, progress, message, ... })` per frame, resolving
+// when the stream ends. (POST-with-SSE: we use fetch + a manual reader since
+// EventSource is GET-only.) Returns a Promise<void>.
+export async function installAudioModel({ engine, repo, name }, onEvent) {
+ const res = await fetch('/api/music/models', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ engine, repo, name }),
+ });
+ if (!res.ok || !res.body) {
+ const msg = await res.text().catch(() => '');
+ throw new Error(msg || `Install failed (${res.status})`);
+ }
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder();
+ let buf = '';
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buf += decoder.decode(value, { stream: true });
+ const frames = buf.split('\n\n');
+ buf = frames.pop() || '';
+ for (const frame of frames) {
+ const line = frame.split('\n').find((l) => l.startsWith('data:'));
+ if (!line) continue;
+ try { onEvent?.(JSON.parse(line.slice('data:'.length).trim())); } catch { /* ignore malformed frame */ }
+ }
+ }
+}
diff --git a/scripts/generate_acestep.py b/scripts/generate_acestep.py
new file mode 100644
index 0000000000..d6d653a8a8
--- /dev/null
+++ b/scripts/generate_acestep.py
@@ -0,0 +1,182 @@
+#!/usr/bin/env python3
+"""
+PortOS ACE-Step runner — local OSS full-song generation (prompt + lyrics).
+Spawned by `server/services/pipeline/musicGen.js` as a third backend alongside
+`scripts/generate_musicgen.py` and `scripts/generate_audioldm2.py`.
+
+ACE-Step (https://github.com/ace-step/ACE-Step, Apache-2.0) is a music
+*foundation* model: unlike MusicGen/AudioLDM2 (text→ambient audio), it takes a
+style/tags **prompt** AND **lyrics** and renders a full, structured song with
+vocals. It runs on Apple-Silicon MPS, CUDA, or CPU.
+
+This script MIRRORS the musicgen/audioldm2 sidecar CLI/contract so the JS side
+can spawn any of the three behind the same `generateMusic` path, plus a
+backend-specific `--lyrics`:
+ --model <hf-repo> --text <prompt/tags> --output <wav> --duration <sec>
+ [--lyrics <text>] [--runtime-dir <dir>] [--seed <int>] [--steps <int>]
+ [--guidance <float>]
+
+`--model` is accepted for argv parity but ACE-Step resolves its own checkpoints
+(auto-downloaded to ~/.cache/ace-step/checkpoints, or PORTOS_ACESTEP_CHECKPOINT_DIR
+/ --runtime-dir when set); the repo id isn't a from_pretrained arg here.
+
+Progress protocol (mirrors the other sidecars): STAGE:<name>[:detail] lines on
+stderr drive the JS-side phase tracker; a final `RESULT:<json>` line on stdout
+reports the saved path + actual duration.
+
+Output: ACE-Step writes a 48 kHz stereo WAV. We ask the pipeline to render into a
+temp dir (its save_path appends its own timestamped filename) and then move the
+single produced file to --output, so the JS side's deterministic
+`music-gen-<uuid>.wav` basename in PATHS.music is preserved.
+"""
+
+import argparse
+import contextlib
+import glob
+import json
+import os
+import shutil
+import sys
+import tempfile
+import wave
+
+
+def log_stage(name, detail=""):
+ """Emit a STAGE: line the JS sidecar tails for phase/progress display."""
+ line = f"STAGE:{name}" + (f":{detail}" if detail else "")
+ print(line, file=sys.stderr, flush=True)
+
+
+def _import_pipeline(runtime_dir):
+ """Resolve the ACEStepPipeline class.
+
+ ACE-Step installs as the `acestep` pip package
+ (`pip install git+https://github.com/ace-step/ACE-Step.git`). `runtime_dir`
+ is honored for parity with the other sidecars — if a caller vendored a
+ checkout, prepend it to sys.path first. A clear ImportError lets the JS side
+ surface "run the installer" instead of a bare traceback.
+ """
+ if runtime_dir and os.path.isdir(runtime_dir) and runtime_dir not in sys.path:
+ sys.path.insert(0, runtime_dir)
+ try:
+ from acestep.pipeline_ace_step import ACEStepPipeline # type: ignore
+ return ACEStepPipeline
+ except ImportError as exc:
+ raise ImportError(
+ "Could not import ACEStepPipeline from the acestep package. Run "
+ "`INSTALL_ACESTEP=1 bash scripts/setup-image-video.sh` to build the "
+ f"venv (acestep + torch). (runtime-dir: {runtime_dir})"
+ ) from exc
+
+
+def _pick_device_id():
+ """Return (device_id, is_cpu). ACE-Step takes a numeric CUDA device id; MPS
+ and CPU both pass through device_id=0 and the pipeline picks the backend.
+ We only need to know whether we're on CPU to widen the dtype to float32."""
+ import torch
+
+ if torch.backends.mps.is_available():
+ return 0, False
+ if torch.cuda.is_available():
+ return 0, False
+ return 0, True
+
+
+def _wav_duration_seconds(path):
+ """Read a WAV's duration via the stdlib so we report the TRUE rendered
+ length (the model quantizes duration to its latent frame rate)."""
+ with contextlib.closing(wave.open(path, "rb")) as wav:
+ frames = wav.getnframes()
+ rate = wav.getframerate() or 1
+ return frames / float(rate)
+
+
+def main():
+ parser = argparse.ArgumentParser(description="PortOS ACE-Step runner")
+ parser.add_argument("--model", default="ACE-Step/ACE-Step-v1-3.5B",
+ help="HF repo id (parity only; ACE-Step resolves its own checkpoints)")
+ parser.add_argument("--text", required=True, help="Style/tags prompt")
+ parser.add_argument("--lyrics", default="", help="Song lyrics (may include [verse]/[chorus] tags)")
+ parser.add_argument("--output", required=True, help="Output WAV path")
+ parser.add_argument("--duration", type=float, default=60.0, help="Target song length in seconds")
+ parser.add_argument("--runtime-dir", default=os.environ.get("PORTOS_ACESTEP_RUNTIME_DIR", ""),
+ help="Optional dir prepended to sys.path before importing acestep")
+ parser.add_argument("--seed", type=int, default=0, help="RNG seed (0 → pipeline default/random)")
+ parser.add_argument("--steps", type=int, default=60, help="Diffusion inference steps")
+ parser.add_argument("--guidance", type=float, default=15.0, help="Classifier-free guidance scale")
+ args = parser.parse_args()
+
+ text = (args.text or "").strip()
+ if not text:
+ print("ERROR: --text is required", file=sys.stderr, flush=True)
+ return 2
+
+ # Floor keeps the model from a zero-length latent; the JS side already clamps
+ # to the engine's MAX_DURATION_SEC before spawn, so the ceiling here is just a
+ # defensive sanity guard.
+ duration = max(1.0, min(float(args.duration or 60.0), 600.0))
+ steps = max(1, int(args.steps or 60))
+
+ log_stage("import-runtime")
+ ACEStepPipeline = _import_pipeline(args.runtime_dir)
+
+ device_id, is_cpu = _pick_device_id()
+ # bf16 on accelerators; CPU widens to float32 (bf16 matmul is slow/unsupported
+ # on CPU). The pipeline itself further adjusts dtype for MPS internally.
+ dtype = "float32" if is_cpu else "bfloat16"
+
+ # Checkpoint dir: explicit env/runtime-dir wins, else let ACE-Step auto-
+ # download to its default cache (~/.cache/ace-step/checkpoints).
+ checkpoint_dir = os.environ.get("PORTOS_ACESTEP_CHECKPOINT_DIR", "") or None
+
+ log_stage("load-model", args.model)
+ pipe = ACEStepPipeline(
+ checkpoint_dir=checkpoint_dir,
+ device_id=device_id,
+ dtype=dtype,
+ cpu_offload=is_cpu,
+ )
+
+ # ACE-Step's __call__ appends its OWN timestamped filename when save_path is a
+ # directory, so we render into a temp dir and then move the single produced
+ # audio file to --output (preserving the JS side's deterministic basename).
+ out_dir = os.path.dirname(os.path.abspath(args.output))
+ if out_dir:
+ os.makedirs(out_dir, exist_ok=True)
+
+ with tempfile.TemporaryDirectory(prefix="acestep-") as tmp:
+ log_stage("generate", f"{duration:.1f}s/{steps}steps")
+ manual_seeds = [int(args.seed)] if args.seed else None
+ pipe(
+ format="wav",
+ audio_duration=duration,
+ prompt=text,
+ lyrics=(args.lyrics or ""),
+ infer_step=steps,
+ guidance_scale=float(args.guidance or 15.0),
+ manual_seeds=manual_seeds,
+ save_path=tmp,
+ )
+
+ log_stage("encode-wav")
+ produced = sorted(glob.glob(os.path.join(tmp, "*.wav")))
+ if not produced:
+ print("ERROR: ACE-Step produced no .wav output", file=sys.stderr, flush=True)
+ return 1
+ # On the off chance batch>1 ever lands here, take the first; we request
+ # batch_size default (1).
+ shutil.move(produced[0], args.output)
+
+ actual_seconds = _wav_duration_seconds(args.output)
+ result = {
+ "output": args.output,
+ "model": args.model,
+ "durationSec": round(actual_seconds, 3),
+ }
+ print("RESULT:" + json.dumps(result), flush=True)
+ log_stage("done")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.sh
index 3a27d20559..3a59ced129 100755
--- a/scripts/setup-image-video.sh
+++ b/scripts/setup-image-video.sh
@@ -14,6 +14,7 @@
# 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_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).
set -euo pipefail
@@ -419,6 +420,46 @@ if [[ "$INSTALL_AUDIOLDM2" == "1" ]]; then
echo "✅ AudioLDM2 venv ready: $AUDIOLDM2_PY"
fi
+INSTALL_ACESTEP="${INSTALL_ACESTEP:-0}"
+if [[ "$INSTALL_ACESTEP" == "1" ]]; then
+ # Local full-song generation for the Music studio (Phase 4 — third backend
+ # alongside MusicGen + AudioLDM2). ACE-Step is a music FOUNDATION model that
+ # takes a style/tags prompt AND lyrics and renders a structured song with
+ # vocals. It installs as the `acestep` pip package (from git — no clone to
+ # import from), so this is a sibling torch venv. The sidecar
+ # `scripts/generate_acestep.py` imports `ACEStepPipeline` from acestep;
+ # server/lib/pythonSetup.js (resolveAcestepPython) looks for python3 here.
+ # Runs on Apple-Silicon MPS, CUDA, or CPU. The Windows Scripts/python.exe path
+ # is resolved on the JS side by pythonSetup's ACESTEP_VENV_CANDIDATES.
+ # ACE-Step auto-downloads its 3.5B checkpoints to ~/.cache/ace-step on first
+ # run, so this only builds the venv — no weights are fetched here.
+ ACESTEP_VENV="${HOME}/.portos/venv-acestep"
+ ACESTEP_PY="$ACESTEP_VENV/bin/python3"
+ mkdir -p "${HOME}/.portos"
+
+ if [[ ! -x "$ACESTEP_PY" ]]; then
+ echo "📦 Creating ACE-Step venv at ${ACESTEP_VENV}..."
+ "$PYTHON_BIN" -m venv "$ACESTEP_VENV"
+ fi
+ echo "📦 Installing ACE-Step into ${ACESTEP_VENV} (this pulls torch + the acestep package)..."
+ "$ACESTEP_PY" -m pip install --upgrade pip wheel setuptools >/dev/null
+ # The acestep package declares its own deps (torch, diffusers, transformers,
+ # audio I/O, etc.), so installing it from git pulls the matching stack. Pinning
+ # nothing here keeps us on the upstream-tested set; the import probe below
+ # catches a broken resolve before generation depends on it.
+ "$ACESTEP_PY" -m pip install --upgrade \
+ "git+https://github.com/ace-step/ACE-Step.git" \
+ "huggingface_hub[hf_xet]"
+ # Verify the pipeline class imports — a clean import means generation only
+ # needs the one-time checkpoint download, not a broken venv.
+ if ! "$ACESTEP_PY" -c "import torch; from acestep.pipeline_ace_step import ACEStepPipeline" 2>/dev/null; then
+ echo "❌ ACE-Step venv built but 'import torch; from acestep.pipeline_ace_step import ACEStepPipeline' failed." >&2
+ echo " Check that torch + the acestep package installed cleanly in ${ACESTEP_VENV}." >&2
+ exit 1
+ fi
+ echo "✅ ACE-Step venv ready: $ACESTEP_PY"
+fi
+
INSTALL_FLUX2="${INSTALL_FLUX2:-$DEFAULT_INSTALL_FLUX2}"
if [[ "$INSTALL_FLUX2" == "1" ]]; then
@@ -495,6 +536,9 @@ fi
if [[ "$INSTALL_AUDIOLDM2" == "1" ]]; then
echo " AudioLDM2: ${HOME}/.portos/venv-audioldm2/bin/python3 (separate venv, diffusers — long-form audio)"
fi
+if [[ "$INSTALL_ACESTEP" == "1" ]]; then
+ echo " ACE-Step: ${HOME}/.portos/venv-acestep/bin/python3 (separate venv, acestep — full song + vocals)"
+fi
if [[ "$INSTALL_FLUX2" == "1" ]]; then
echo " FLUX.2: ${HOME}/.portos/venv-flux2/bin/python3 (separate venv)"
echo " Z-Image: reuses the FLUX.2 venv (Apache 2.0, no HF login needed)"
diff --git a/server/index.js b/server/index.js
index b86c80ac41..05f59fe8eb 100644
--- a/server/index.js
+++ b/server/index.js
@@ -113,6 +113,7 @@ import authorsRoutes from './routes/authors.js';
import artistsRoutes from './routes/artists.js';
import albumsRoutes from './routes/albums.js';
import tracksRoutes from './routes/tracks.js';
+import musicRoutes from './routes/music.js';
import conflictJournalRoutes from './routes/conflictJournal.js';
import { initUniverseBuilderCollectionHook } from './services/universeBuilderCollectionHook.js';
import { initCatalogImageAttachHook } from './services/catalogImageAttachHook.js';
@@ -537,6 +538,7 @@ app.use('/api/authors', authorsRoutes);
app.use('/api/artists', artistsRoutes);
app.use('/api/albums', albumsRoutes);
app.use('/api/tracks', tracksRoutes);
+app.use('/api/music', musicRoutes);
app.use('/api/pipeline', pipelineRoutes);
app.use('/api/conflict-journal', conflictJournalRoutes);
app.use('/api/importer', importerRoutes);
diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.js
index 4121d4232a..8937cbad3a 100644
--- a/server/lib/pythonSetup.js
+++ b/server/lib/pythonSetup.js
@@ -265,6 +265,45 @@ export function invalidateAudioldm2Python() {
cachedAudioldm2Python = null;
}
+// ACE-Step (third music backend — full-song generation with vocals) runs in its
+// own venv at ~/.portos/venv-acestep — the `acestep` pip package + torch, kept
+// apart from the MusicGen MLX pile and the AudioLDM2 diffusers pile. ACE-Step
+// installs as a pip package (no clone to import from), so the sidecar normally
+// imports it straight from the venv; the optional --runtime-dir points at a
+// vendored checkout if ever needed. `INSTALL_ACESTEP=1 bash
+// scripts/setup-image-video.sh` provisions the venv. ACE-Step resolves its own
+// model checkpoints (auto-download to ~/.cache/ace-step/checkpoints).
+const ACESTEP_VENV_CANDIDATES = IS_WIN
+ ? [
+ join(HOME, '.portos', 'venv-acestep', 'Scripts', 'python.exe'),
+ join(PATHS.data, 'python', 'venv-acestep', 'Scripts', 'python.exe'),
+ ]
+ : [
+ join(HOME, '.portos', 'venv-acestep', 'bin', 'python3'),
+ join(PATHS.data, 'python', 'venv-acestep', 'bin', 'python3'),
+ ];
+
+export const ACESTEP_VENV_DEFAULT = ACESTEP_VENV_CANDIDATES[0];
+
+// Optional dir prepended to the sidecar's sys.path before importing acestep.
+// Empty sentinel (the sidecar's --runtime-dir is a no-op when blank) — ACE-Step
+// imports from the venv's installed package; kept for argv parity with the other
+// music sidecars and so a vendored checkout can be pointed at later.
+export const ACESTEP_RUNTIME_DIR = '';
+
+let cachedAcestepPython = null;
+export function resolveAcestepPython() {
+ if (cachedAcestepPython && existsSync(cachedAcestepPython)) return cachedAcestepPython;
+ for (const p of ACESTEP_VENV_CANDIDATES) {
+ if (existsSync(p)) { cachedAcestepPython = p; return p; }
+ }
+ return null;
+}
+
+export function invalidateAcestepPython() {
+ cachedAcestepPython = null;
+}
+
// Used by /api/image-gen/setup/* routes to validate user-supplied pythonPath
// before exec. Single-user / Tailnet model means we trust the operator, but
// "you can shell out to anything" is still too sharp — restrict to actual
diff --git a/server/routes/music.js b/server/routes/music.js
new file mode 100644
index 0000000000..99d869240e
--- /dev/null
+++ b/server/routes/music.js
@@ -0,0 +1,161 @@
+/**
+ * Music generation routes (the Music studio's on-device generator surface).
+ *
+ * GET /api/music/engines → { engines, defaultEngine }
+ * POST /api/music/generate → { track, filename, durationSec, engine, modelId }
+ *
+ * Generation runs the engine-agnostic `generateMusic` (server/services/pipeline/
+ * musicGen.js) — MusicGen / AudioLDM2 / ACE-Step 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
+ * own generator routes; this is the studio's standalone path.
+ *
+ * Generation is synchronous here (one render at a time, like the pipeline audio
+ * stage's generate route) — a long ACE-Step render holds the request open. An
+ * async mediaJobQueue lane can be added later behind the same response shape.
+ */
+
+import { Router } from 'express';
+import { z } from 'zod';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import { ENGINES, DEFAULT_ENGINE_ID, getEngine, isEngineReady, generateMusic } from '../services/pipeline/musicGen.js';
+import { listEngineModels, addAudioModel, removeAudioModel, isValidRepoId } from '../services/audioModels.js';
+import { startHfDownloadStream } from '../lib/sseDownload.js';
+import * as tracks from '../services/tracks/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.
+router.get('/engines', asyncHandler(async (_req, res) => {
+ const engines = await Promise.all(Object.values(ENGINES).map(async (engine) => ({
+ id: engine.id,
+ name: engine.name,
+ models: await listEngineModels(engine.id),
+ defaultModelId: engine.defaultModelId,
+ minDurationSec: engine.minDurationSec,
+ maxDurationSec: engine.maxDurationSec,
+ defaultDurationSec: engine.defaultDurationSec,
+ lyrics: engine.lyrics === true,
+ ready: isEngineReady(engine.id),
+ installEnv: engine.installEnv,
+ venvDefault: engine.venvDefault,
+ })));
+ res.json({ engines, defaultEngine: DEFAULT_ENGINE_ID });
+}));
+
+// --- Install additional audio models from HuggingFace -----------------------
+// The shipped per-engine model lists (musicGen.js) cover the common checkpoints;
+// these endpoints let a user add more HF repos (e.g. a larger MusicGen, an
+// AudioLDM2 variant) using the SAME HF-download path as the image/video model
+// installer. A registered model's id is its repo id, which the sidecar passes
+// to --model, so it's selectable for generation immediately.
+
+const installSchema = z.object({
+ engine: z.string().trim().min(1).max(60),
+ repo: z.string().trim().min(1).max(200),
+ name: z.string().trim().max(200).optional(),
+});
+
+// GET /api/music/models/:engine → the merged shipped+user model list for one
+// engine (also exposed via /engines, but handy for a focused refresh).
+router.get('/models/:engine', asyncHandler(async (req, res) => {
+ if (!ENGINES[req.params.engine]) throw new ServerError('Unknown audio engine', { status: 404, code: 'AUDIO_MODEL_UNKNOWN_ENGINE' });
+ res.json({ models: await listEngineModels(req.params.engine) });
+}));
+
+// POST /api/music/models — register an HF repo for an engine, then STREAM its
+// download as SSE (text/event-stream). Registering first (before the bytes land)
+// is intentional: the generation sidecars auto-download a missing checkpoint on
+// first use, so even a cancelled pre-download leaves a usable (lazily-fetched)
+// model — same posture as the shipped models.
+router.post('/models', asyncHandler(async (req, res) => {
+ const body = validateRequest(installSchema, req.body ?? {});
+ if (!ENGINES[body.engine]) throw new ServerError('Unknown audio engine', { status: 400, code: 'AUDIO_MODEL_UNKNOWN_ENGINE' });
+ if (!isValidRepoId(body.repo)) throw new ServerError('Invalid HuggingFace repo id', { status: 400, code: 'AUDIO_MODEL_INVALID_REPO' });
+ await addAudioModel({ engine: body.engine, repo: body.repo, name: body.name });
+ // Hand the response to the shared SSE driver — it owns writeHead/end + the
+ // in-flight dedupe + client-disconnect kill. The cache pre-warm is best-effort.
+ await startHfDownloadStream({ req, res, repo: body.repo });
+}));
+
+// DELETE /api/music/models/:engine/*id — de-register a user-added model. The id
+// is an HF repo id (contains a slash), so it's captured as a named trailing
+// wildcard (`*id`, path-to-regexp v8) rather than a single `:id` segment.
+// path-to-regexp returns the splat as an array of path segments; rejoin with
+// `/` to reconstruct the repo id. Cached weights are left to the HF cache;
+// shipped defaults can't be removed here (no-op → 200 {removed:false}).
+router.delete('/models/:engine/*id', asyncHandler(async (req, res) => {
+ const splat = req.params.id;
+ const id = Array.isArray(splat) ? splat.join('/') : String(splat || '');
+ const removed = await removeAudioModel({ engine: req.params.engine, id });
+ res.json({ removed });
+}));
+
+const generateSchema = z.object({
+ prompt: z.string().trim().min(1, 'prompt is required').max(8000),
+ lyrics: z.string().trim().max(20000).optional().default(''),
+ engine: z.string().trim().max(60).optional(),
+ modelId: z.string().trim().max(120).optional(),
+ durationSec: z.number().positive().max(600).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(),
+ title: z.string().trim().max(200).optional(),
+ artistId: z.string().trim().max(80).optional().default(''),
+ artist: z.string().trim().max(120).optional().default(''),
+ albumId: z.string().trim().max(80).optional().default(''),
+});
+
+router.post('/generate', asyncHandler(async (req, res) => {
+ const body = validateRequest(generateSchema, req.body ?? {});
+ const engine = getEngine(body.engine);
+
+ // generateMusic throws a typed ServerError (503 venv-missing / 500 sidecar
+ // failure) that asyncHandler maps verbatim — no need to re-wrap here.
+ const result = await generateMusic({
+ prompt: body.prompt,
+ lyrics: body.lyrics,
+ engine: engine.id,
+ modelId: body.modelId,
+ durationSec: body.durationSec,
+ });
+
+ // Persist the audio onto a track: update the named one, or create a new one.
+ const meta = {
+ audioFilename: result.filename,
+ engine: result.engine,
+ modelId: result.modelId,
+ durationSec: Math.round(result.durationSec),
+ prompt: body.prompt,
+ lyrics: body.lyrics,
+ };
+ let track;
+ if (body.trackId) {
+ track = await tracks.getTrack(body.trackId);
+ if (!track) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });
+ track = await tracks.updateTrack(body.trackId, meta);
+ } else {
+ track = await tracks.createTrack({
+ title: body.title?.trim() || body.prompt.slice(0, 60),
+ artistId: body.artistId,
+ artist: body.artist,
+ albumId: body.albumId,
+ ...meta,
+ });
+ }
+
+ res.status(body.trackId ? 200 : 201).json({
+ track,
+ filename: result.filename,
+ durationSec: result.durationSec,
+ engine: result.engine,
+ modelId: result.modelId,
+ });
+}));
+
+export default router;
diff --git a/server/routes/music.test.js b/server/routes/music.test.js
new file mode 100644
index 0000000000..a88287ea2c
--- /dev/null
+++ b/server/routes/music.test.js
@@ -0,0 +1,150 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { ServerError } from '../lib/errorHandler.js';
+
+// Mock the music-gen service: a small engine registry + a generateMusic that the
+// tests drive per-case. The route only consumes ENGINES/getEngine/isEngineReady/
+// generateMusic + DEFAULT_ENGINE_ID.
+const gen = vi.hoisted(() => ({ generateMusic: vi.fn(), ready: true }));
+vi.mock('../services/pipeline/musicGen.js', () => {
+ const ENGINES = {
+ musicgen: { id: 'musicgen', name: 'MusicGen', models: [{ id: 'm', name: 'M' }], defaultModelId: 'm', minDurationSec: 1, maxDurationSec: 30, defaultDurationSec: 12, installEnv: 'INSTALL_MUSICGEN', venvDefault: '/v/mg' },
+ 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', lyrics: true },
+ };
+ return {
+ ENGINES,
+ DEFAULT_ENGINE_ID: 'musicgen',
+ getEngine: (id) => ENGINES[id] || ENGINES.musicgen,
+ isEngineReady: () => gen.ready,
+ generateMusic: gen.generateMusic,
+ };
+});
+
+vi.mock('../services/tracks/index.js', () => ({
+ getTrack: vi.fn(),
+ createTrack: vi.fn(async (input) => ({ id: 'track-new', ...input })),
+ updateTrack: vi.fn(async (id, patch) => ({ id, ...patch })),
+}));
+
+const models = vi.hoisted(() => ({ list: vi.fn(), add: vi.fn(), remove: vi.fn() }));
+vi.mock('../services/audioModels.js', () => ({
+ listEngineModels: (engineId) => models.list(engineId),
+ addAudioModel: (args) => models.add(args),
+ removeAudioModel: (args) => models.remove(args),
+ isValidRepoId: (r) => typeof r === 'string' && /^[\w.-]+\/[\w./-]+$/.test(r) && !r.includes('..'),
+}));
+
+// The SSE download driver writes to the response + ends it; stub it to a quick
+// 200 so the route test doesn't spawn Python.
+const sse = vi.hoisted(() => ({ run: vi.fn(async ({ res }) => { res.writeHead(200, { 'Content-Type': 'text/event-stream' }); res.end('data: {"type":"complete"}\n\n'); }) }));
+vi.mock('../lib/sseDownload.js', () => ({ startHfDownloadStream: (args) => sse.run(args) }));
+
+import * as tracks from '../services/tracks/index.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import musicRoutes from './music.js';
+
+function makeApp() {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/music', musicRoutes);
+ app.use(errorMiddleware);
+ return app;
+}
+
+describe('music routes', () => {
+ let app;
+ beforeEach(() => {
+ app = makeApp();
+ vi.clearAllMocks();
+ gen.ready = true;
+ models.list.mockResolvedValue([{ id: 'm', name: 'M', userAdded: false }]);
+ });
+
+ it('GET /engines lists engines with readiness + lyric capability + merged models', async () => {
+ const r = await request(app).get('/api/music/engines');
+ expect(r.status).toBe(200);
+ expect(r.body.defaultEngine).toBe('musicgen');
+ const ace = r.body.engines.find((e) => e.id === 'acestep');
+ expect(ace.lyrics).toBe(true);
+ expect(ace.ready).toBe(true);
+ expect(ace.models).toEqual([{ id: 'm', name: 'M', userAdded: false }]);
+ expect(r.body.engines.find((e) => e.id === 'musicgen').lyrics).toBe(false);
+ });
+
+ it('GET /models/:engine returns the merged model list; 404s for an unknown engine', async () => {
+ const r = await request(app).get('/api/music/models/acestep');
+ expect(r.status).toBe(200);
+ expect(r.body.models).toEqual([{ id: 'm', name: 'M', userAdded: false }]);
+ expect((await request(app).get('/api/music/models/nope')).status).toBe(404);
+ });
+
+ it('POST /models registers the model then streams the download (SSE)', async () => {
+ models.add.mockResolvedValueOnce({ id: 'facebook/musicgen-large', repo: 'facebook/musicgen-large', name: 'musicgen-large' });
+ const r = await request(app).post('/api/music/models').send({ engine: 'musicgen', repo: 'facebook/musicgen-large' });
+ expect(r.status).toBe(200);
+ expect(models.add).toHaveBeenCalledWith({ engine: 'musicgen', repo: 'facebook/musicgen-large', name: undefined });
+ expect(sse.run).toHaveBeenCalledWith(expect.objectContaining({ repo: 'facebook/musicgen-large' }));
+ });
+
+ it('POST /models rejects an unknown engine / invalid repo before downloading', async () => {
+ expect((await request(app).post('/api/music/models').send({ engine: 'nope', repo: 'a/b' })).status).toBe(400);
+ expect((await request(app).post('/api/music/models').send({ engine: 'musicgen', repo: 'bad' })).status).toBe(400);
+ expect(models.add).not.toHaveBeenCalled();
+ expect(sse.run).not.toHaveBeenCalled();
+ });
+
+ it('DELETE /models/:engine/* de-registers a slash-containing repo id', async () => {
+ models.remove.mockResolvedValueOnce(true);
+ const r = await request(app).delete('/api/music/models/musicgen/facebook/musicgen-large');
+ expect(r.status).toBe(200);
+ expect(r.body.removed).toBe(true);
+ expect(models.remove).toHaveBeenCalledWith({ engine: 'musicgen', id: 'facebook/musicgen-large' });
+ });
+
+ it('POST /generate creates a new track from the result', async () => {
+ gen.generateMusic.mockResolvedValueOnce({ filename: 'music-gen-x.wav', durationSec: 61.4, engine: 'acestep', modelId: 'a' });
+ const r = await request(app).post('/api/music/generate').send({
+ prompt: 'warm folk', lyrics: '[verse] hi', engine: 'acestep', title: 'My Song',
+ });
+ expect(r.status).toBe(201);
+ expect(gen.generateMusic).toHaveBeenCalledWith(expect.objectContaining({ prompt: 'warm folk', lyrics: '[verse] hi', engine: 'acestep' }));
+ expect(tracks.createTrack).toHaveBeenCalledWith(expect.objectContaining({
+ title: 'My Song', audioFilename: 'music-gen-x.wav', engine: 'acestep', modelId: 'a', durationSec: 61, lyrics: '[verse] hi',
+ }));
+ expect(r.body.track.id).toBe('track-new');
+ expect(r.body.filename).toBe('music-gen-x.wav');
+ });
+
+ 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' });
+ const r = await request(app).post('/api/music/generate').send({ prompt: 'beat', trackId: 'track-1' });
+ expect(r.status).toBe(200);
+ expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', expect.objectContaining({ audioFilename: 'music-gen-y.wav' }));
+ expect(tracks.createTrack).not.toHaveBeenCalled();
+ });
+
+ it('POST /generate with an unknown trackId 404s and does not create', async () => {
+ tracks.getTrack.mockResolvedValueOnce(null);
+ gen.generateMusic.mockResolvedValueOnce({ filename: 'm.wav', durationSec: 10, engine: 'musicgen', modelId: 'm' });
+ const r = await request(app).post('/api/music/generate').send({ prompt: 'x', trackId: 'track-missing' });
+ expect(r.status).toBe(404);
+ expect(tracks.updateTrack).not.toHaveBeenCalled();
+ expect(tracks.createTrack).not.toHaveBeenCalled();
+ });
+
+ it('POST /generate rejects a missing prompt', async () => {
+ const r = await request(app).post('/api/music/generate').send({ engine: 'acestep' });
+ expect(r.status).toBe(400);
+ expect(gen.generateMusic).not.toHaveBeenCalled();
+ });
+
+ it('POST /generate surfaces a 503 when the engine venv is missing', async () => {
+ gen.generateMusic.mockRejectedValueOnce(new ServerError('ACE-Step runtime not found. Run `INSTALL_ACESTEP=1 …`', { status: 503, code: 'PIPELINE_MUSIC_RUNTIME_MISSING' }));
+ const r = await request(app).post('/api/music/generate').send({ prompt: 'x', engine: 'acestep' });
+ expect(r.status).toBe(503);
+ expect(r.body.code).toBe('PIPELINE_MUSIC_RUNTIME_MISSING');
+ expect(tracks.createTrack).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/audioModels.js b/server/services/audioModels.js
new file mode 100644
index 0000000000..e152cce4de
--- /dev/null
+++ b/server/services/audioModels.js
@@ -0,0 +1,130 @@
+/**
+ * User-installed audio model registry — augments the shipped music-gen engine
+ * model lists (server/services/pipeline/musicGen.js `ENGINES[id].models`) with
+ * extra HuggingFace checkpoints the user downloads via the Music studio.
+ *
+ * The SHIPPED models live in code (musicGen.js); this registry holds only the
+ * user's ADDITIONS, persisted to `data/audio-models.json` keyed by engine id:
+ *
+ * { "musicgen": [ { "id": "facebook/musicgen-large", "repo": "facebook/musicgen-large", "name": "MusicGen Large" } ],
+ * "audioldm2": [], "acestep": [] }
+ *
+ * `listEngineModels(engineId)` merges shipped + user models (shipped first,
+ * deduped by id) so the route/UI present one combined list. A user model's `id`
+ * IS its HF repo id, which the sidecar passes straight to `--model`, so a
+ * downloaded checkpoint is selectable for generation immediately (no restart —
+ * the JSON is read on each list call, unlike the code-level defaults).
+ *
+ * Install flow: the route downloads the HF repo via `downloadHfRepo` (shared
+ * with the image/video model installer) into the local HF cache, then calls
+ * `addAudioModel` here to register it. Removing a model only de-registers it
+ * (the cached weights are managed by the HF cache, not deleted here).
+ */
+
+import { join } from 'path';
+import { readJSONFile, atomicWrite, ensureDir } from '../lib/fileUtils.js';
+import { PATHS } from '../lib/fileUtils.js';
+import { getEngine, ENGINES } from './pipeline/musicGen.js';
+
+const REGISTRY_FILE = join(PATHS.data, 'audio-models.json');
+
+const isStr = (v) => typeof v === 'string' && v.trim().length > 0;
+// HF repo ids look like `org/name` (optionally with extra path segments). Keep
+// the guard permissive but reject path-traversal / whitespace / control chars.
+const REPO_RE = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._\/-]+$/;
+
+export function isValidRepoId(repo) {
+ return isStr(repo) && REPO_RE.test(repo.trim()) && !repo.includes('..');
+}
+
+// One sanitized user-model entry, or null to drop. `id` defaults to the repo id
+// (what the sidecar's --model wants); `name` defaults to the repo's basename.
+function sanitizeUserModel(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ const repo = isStr(raw.repo) ? raw.repo.trim() : '';
+ if (!isValidRepoId(repo)) return null;
+ const id = isStr(raw.id) ? raw.id.trim() : repo;
+ const name = isStr(raw.name) ? raw.name.trim().slice(0, 200) : repo.split('/').pop();
+ return { id, repo, name };
+}
+
+async function loadRegistry() {
+ const raw = await readJSONFile(REGISTRY_FILE, {});
+ const out = {};
+ if (raw && typeof raw === 'object') {
+ for (const engineId of Object.keys(ENGINES)) {
+ const list = Array.isArray(raw[engineId]) ? raw[engineId] : [];
+ out[engineId] = list.map(sanitizeUserModel).filter(Boolean);
+ }
+ } else {
+ for (const engineId of Object.keys(ENGINES)) out[engineId] = [];
+ }
+ return out;
+}
+
+async function saveRegistry(registry) {
+ await ensureDir(PATHS.data);
+ await atomicWrite(REGISTRY_FILE, registry);
+}
+
+/** User-added models for one engine (sanitized). */
+export async function listUserModels(engineId) {
+ const reg = await loadRegistry();
+ return reg[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? }`
+ * 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 seen = new Set(shipped.map((m) => m.id));
+ const user = (await listUserModels(engine.id))
+ .filter((m) => !seen.has(m.id))
+ .map((m) => ({ id: m.id, name: m.name, repo: m.repo, userAdded: true }));
+ return [...shipped, ...user];
+}
+
+/**
+ * Register a downloaded HF checkpoint for an engine. Idempotent: re-adding the
+ * same repo updates its display name rather than duplicating. Rejects an unknown
+ * engine or an invalid repo id. Returns the sanitized entry.
+ */
+export async function addAudioModel({ engine: engineId, repo, name }) {
+ if (!ENGINES[engineId]) {
+ throw Object.assign(new Error(`Unknown audio engine: ${engineId}`), { status: 400, code: 'AUDIO_MODEL_UNKNOWN_ENGINE' });
+ }
+ const entry = sanitizeUserModel({ repo, name, id: repo });
+ if (!entry) {
+ throw Object.assign(new Error('Invalid HuggingFace repo id'), { status: 400, code: 'AUDIO_MODEL_INVALID_REPO' });
+ }
+ const reg = await loadRegistry();
+ const list = reg[engineId] || [];
+ const idx = list.findIndex((m) => m.id === entry.id);
+ if (idx >= 0) list[idx] = entry;
+ else list.push(entry);
+ reg[engineId] = list;
+ await saveRegistry(reg);
+ console.log(`🎚️ Registered audio model for ${engineId}: ${entry.repo}`);
+ return entry;
+}
+
+/**
+ * De-register a user-added model (does NOT touch the cached weights — the HF
+ * cache owns those). Returns true if an entry was removed. A shipped default id
+ * is a no-op (not in the user registry) — shipped models can't be removed here.
+ */
+export async function removeAudioModel({ engine: engineId, id }) {
+ const reg = await loadRegistry();
+ const list = reg[engineId] || [];
+ const next = list.filter((m) => m.id !== id);
+ if (next.length === list.length) return false;
+ reg[engineId] = next;
+ await saveRegistry(reg);
+ console.log(`🎚️ De-registered audio model for ${engineId}: ${id}`);
+ return true;
+}
diff --git a/server/services/audioModels.test.js b/server/services/audioModels.test.js
new file mode 100644
index 0000000000..2794d20502
--- /dev/null
+++ b/server/services/audioModels.test.js
@@ -0,0 +1,87 @@
+/**
+ * User-installed audio model registry — augments the shipped musicGen engine
+ * model lists. tmpdir-backed so it never touches real data/audio-models.json.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'audio-models-test-'));
+
+vi.mock('../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };
+});
+
+const svc = await import('./audioModels.js');
+const { ENGINES } = await import('./pipeline/musicGen.js');
+
+function reset() {
+ rmSync(join(TEST_DATA_ROOT, 'audio-models.json'), { force: true });
+}
+
+beforeEach(reset);
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+describe('audioModels — isValidRepoId', () => {
+ it('accepts org/name shapes and rejects junk / traversal', () => {
+ expect(svc.isValidRepoId('facebook/musicgen-large')).toBe(true);
+ expect(svc.isValidRepoId('ACE-Step/ACE-Step-v1-3.5B')).toBe(true);
+ expect(svc.isValidRepoId('no-slash')).toBe(false);
+ expect(svc.isValidRepoId('../evil/x')).toBe(false);
+ expect(svc.isValidRepoId('a b/c')).toBe(false);
+ expect(svc.isValidRepoId('')).toBe(false);
+ expect(svc.isValidRepoId(null)).toBe(false);
+ });
+});
+
+describe('audioModels — add / list / merge / remove', () => {
+ it('listEngineModels returns the shipped defaults when no user models exist', async () => {
+ const shipped = ENGINES.musicgen.models.map((m) => m.id);
+ const listed = (await svc.listEngineModels('musicgen')).map((m) => m.id);
+ expect(listed).toEqual(shipped);
+ expect((await svc.listEngineModels('musicgen')).every((m) => m.userAdded === false)).toBe(true);
+ });
+
+ it('adds a user model and merges it after the shipped ones (marked userAdded)', async () => {
+ const entry = await svc.addAudioModel({ engine: 'musicgen', repo: 'facebook/musicgen-large' });
+ expect(entry).toEqual({ id: 'facebook/musicgen-large', repo: 'facebook/musicgen-large', name: 'musicgen-large' });
+ const listed = await svc.listEngineModels('musicgen');
+ const added = listed.find((m) => m.id === 'facebook/musicgen-large');
+ expect(added).toBeTruthy();
+ expect(added.userAdded).toBe(true);
+ // Shipped models stay first + not flagged userAdded.
+ expect(listed[0].userAdded).toBe(false);
+ });
+
+ it('uses a provided display name and is idempotent on re-add (updates name)', async () => {
+ await svc.addAudioModel({ engine: 'acestep', repo: 'someorg/ace-lora', name: 'My LoRA' });
+ await svc.addAudioModel({ engine: 'acestep', repo: 'someorg/ace-lora', name: 'My LoRA v2' });
+ const user = await svc.listUserModels('acestep');
+ expect(user).toHaveLength(1);
+ expect(user[0].name).toBe('My LoRA v2');
+ });
+
+ it('rejects an unknown engine and an invalid repo', async () => {
+ await expect(svc.addAudioModel({ engine: 'nope', repo: 'a/b' })).rejects.toMatchObject({ code: 'AUDIO_MODEL_UNKNOWN_ENGINE' });
+ await expect(svc.addAudioModel({ engine: 'musicgen', repo: 'bad' })).rejects.toMatchObject({ code: 'AUDIO_MODEL_INVALID_REPO' });
+ });
+
+ it('does not duplicate a shipped model id if a user re-adds it', async () => {
+ const shippedId = ENGINES.audioldm2.models[0].id;
+ // shipped ids are short slugs (e.g. "audioldm2"), not repo ids, so a user
+ // adding the repo id is a DISTINCT entry; verify the shipped one stays single.
+ await svc.addAudioModel({ engine: 'audioldm2', repo: 'cvssp/audioldm2-large' });
+ const ids = (await svc.listEngineModels('audioldm2')).map((m) => m.id);
+ expect(ids.filter((id) => id === shippedId)).toHaveLength(1);
+ });
+
+ it('removes a user model (returns true), and is a no-op for an unknown id', async () => {
+ await svc.addAudioModel({ engine: 'musicgen', repo: 'facebook/musicgen-large' });
+ expect(await svc.removeAudioModel({ engine: 'musicgen', id: 'facebook/musicgen-large' })).toBe(true);
+ expect((await svc.listUserModels('musicgen'))).toHaveLength(0);
+ expect(await svc.removeAudioModel({ engine: 'musicgen', id: 'not/there' })).toBe(false);
+ });
+});
diff --git a/server/services/pipeline/musicGen.js b/server/services/pipeline/musicGen.js
index 69688013a8..6f0a15295a 100644
--- a/server/services/pipeline/musicGen.js
+++ b/server/services/pipeline/musicGen.js
@@ -39,6 +39,7 @@ import { hfTokenEnv } from '../../lib/hfToken.js';
import {
resolveMusicgenPython, MUSICGEN_RUNTIME_DIR, MUSICGEN_VENV_DEFAULT,
resolveAudioldm2Python, AUDIOLDM2_RUNTIME_DIR, AUDIOLDM2_VENV_DEFAULT,
+ resolveAcestepPython, ACESTEP_RUNTIME_DIR, ACESTEP_VENV_DEFAULT,
} from '../../lib/pythonSetup.js';
import { ServerError } from '../../lib/errorHandler.js';
@@ -47,6 +48,7 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
// paths are correct regardless of the server process's cwd.
const MUSICGEN_SCRIPT = join(__dirname, '../../../scripts/generate_musicgen.py');
const AUDIOLDM2_SCRIPT = join(__dirname, '../../../scripts/generate_audioldm2.py');
+const ACESTEP_SCRIPT = join(__dirname, '../../../scripts/generate_acestep.py');
// Back-compat alias for the pre-multi-engine `buildMusicGenArgs` default.
const SIDECAR_SCRIPT = MUSICGEN_SCRIPT;
@@ -79,6 +81,14 @@ export const AUDIOLDM2_MODELS = Object.freeze([
]);
export const DEFAULT_AUDIOLDM2_MODEL_ID = 'audioldm2';
+// ACE-Step weights. The 3.5B foundation model is the only public checkpoint;
+// `repo` is informational (the sidecar lets ACE-Step resolve + auto-download its
+// own checkpoints, unlike the from_pretrained backends above).
+export const ACESTEP_MODELS = Object.freeze([
+ { id: 'ace-step-v1-3.5b', repo: 'ACE-Step/ACE-Step-v1-3.5B', name: 'ACE-Step v1 3.5B (full song + vocals)' },
+]);
+export const DEFAULT_ACESTEP_MODEL_ID = 'ace-step-v1-3.5b';
+
/**
* Backend registry. Each engine is fully described here so the route, UI and
* `generateMusic` stay generator-agnostic. Fields:
@@ -119,6 +129,23 @@ export const ENGINES = Object.freeze({
venvDefault: AUDIOLDM2_VENV_DEFAULT,
installEnv: 'INSTALL_AUDIOLDM2',
},
+ acestep: {
+ id: 'acestep',
+ name: 'ACE-Step (full song + vocals)',
+ models: ACESTEP_MODELS,
+ defaultModelId: DEFAULT_ACESTEP_MODEL_ID,
+ minDurationSec: 1,
+ maxDurationSec: 240,
+ defaultDurationSec: 60,
+ scriptPath: ACESTEP_SCRIPT,
+ runtimeDir: ACESTEP_RUNTIME_DIR,
+ resolvePython: resolveAcestepPython,
+ venvDefault: ACESTEP_VENV_DEFAULT,
+ installEnv: 'INSTALL_ACESTEP',
+ // ACE-Step is lyric-aware: the route/UI may send `lyrics`, threaded into the
+ // sidecar as --lyrics. The other engines ignore lyrics (the flag gates UI).
+ lyrics: true,
+ },
});
export const DEFAULT_ENGINE_ID = 'musicgen';
@@ -169,23 +196,25 @@ export function clampDuration(durationSec, engineId = DEFAULT_ENGINE_ID) {
/**
* Build the `{ bin, args }` for a backend's sidecar. Pure — unit-tested without
- * spawning Python. Both sidecars share the same flag contract
+ * 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.
+ * 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, durationSec, outputPath }) {
+export function buildSidecarArgs({ engineId = DEFAULT_ENGINE_ID, pythonPath, scriptPath, runtimeDir, repo, prompt, lyrics, durationSec, outputPath }) {
const engine = getEngine(engineId);
- return {
- bin: pythonPath,
- args: [
- scriptPath ?? engine.scriptPath,
- '--model', repo,
- '--text', prompt,
- '--duration', String(clampDuration(durationSec, engine.id)),
- '--output', outputPath,
- '--runtime-dir', runtimeDir ?? engine.runtimeDir,
- ],
- };
+ const args = [
+ scriptPath ?? engine.scriptPath,
+ '--model', repo,
+ '--text', prompt,
+ '--duration', String(clampDuration(durationSec, engine.id)),
+ '--output', outputPath,
+ '--runtime-dir', runtimeDir ?? engine.runtimeDir,
+ ];
+ if (engine.lyrics) args.push('--lyrics', typeof lyrics === 'string' ? lyrics : '');
+ return { bin: pythonPath, args };
}
/**
@@ -216,12 +245,13 @@ function parseResultLine(stdout) {
* ServerError (503) when the selected backend's venv isn't provisioned, or
* (500) when the sidecar exits non-zero / produces no result.
*
- * `engine` selects the backend (`musicgen` | `audioldm2`); unknown ids fall
- * back to the default. `modelId` is resolved within that engine's registry.
- * `signal` (optional AbortSignal) SIGTERMs the child — wired through so a
- * future cancel button can abort a long render.
+ * `engine` selects the backend (`musicgen` | `audioldm2` | `acestep`); 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
+ * through so a cancel button can abort a long render.
*/
-export async function generateMusic({ prompt, engine: engineId = DEFAULT_ENGINE_ID, durationSec, modelId, signal } = {}) {
+export async function generateMusic({ prompt, lyrics, engine: engineId = DEFAULT_ENGINE_ID, durationSec, modelId, signal } = {}) {
const text = (prompt || '').trim();
if (!text) {
throw new ServerError('prompt is required', { status: 400, code: 'PIPELINE_MUSIC_EMPTY_PROMPT' });
@@ -240,7 +270,7 @@ export async function generateMusic({ prompt, engine: engineId = DEFAULT_ENGINE_
await 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, durationSec: resolvedDuration, outputPath });
+ const { bin, args } = buildSidecarArgs({ engineId: engine.id, pythonPath, repo: model.repo, 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 a
diff --git a/server/services/pipeline/musicGen.test.js b/server/services/pipeline/musicGen.test.js
index 9ddf630ad5..a1cab55f84 100644
--- a/server/services/pipeline/musicGen.test.js
+++ b/server/services/pipeline/musicGen.test.js
@@ -62,8 +62,8 @@ describe('AUDIOLDM2_MODELS registry', () => {
});
describe('ENGINES backend registry', () => {
- it('exposes both backends with the fields the route + UI consume', () => {
- expect(Object.keys(ENGINES).sort()).toEqual(['audioldm2', 'musicgen']);
+ it('exposes all backends with the fields the route + UI consume', () => {
+ expect(Object.keys(ENGINES).sort()).toEqual(['acestep', 'audioldm2', 'musicgen']);
for (const engine of Object.values(ENGINES)) {
expect(typeof engine.id).toBe('string');
expect(typeof engine.name).toBe('string');
@@ -172,6 +172,37 @@ describe('buildSidecarArgs', () => {
const { args } = buildSidecarArgs({ ...base, engineId: 'audioldm2' });
expect(args).toContain('--runtime-dir');
});
+
+ it('threads --lyrics ONLY for lyric-aware engines (acestep)', () => {
+ const ace = buildSidecarArgs({ ...base, engineId: 'acestep', repo: 'ACE-Step/ACE-Step-v1-3.5B', lyrics: '[verse]\nhello' });
+ expect(ace.args[0]).toMatch(/generate_acestep\.py$/);
+ expect(ace.args).toContain('--lyrics');
+ expect(ace.args[ace.args.indexOf('--lyrics') + 1]).toBe('[verse]\nhello');
+ // Non-lyric engines never get the flag, even when lyrics are passed.
+ const mg = buildSidecarArgs({ ...base, engineId: 'musicgen', lyrics: 'ignored' });
+ expect(mg.args).not.toContain('--lyrics');
+ const ald = buildSidecarArgs({ ...base, engineId: 'audioldm2', lyrics: 'ignored' });
+ expect(ald.args).not.toContain('--lyrics');
+ });
+
+ it('sends an empty --lyrics for acestep when none provided (never undefined)', () => {
+ const { args } = buildSidecarArgs({ ...base, engineId: 'acestep' });
+ expect(args).toContain('--lyrics');
+ expect(args[args.indexOf('--lyrics') + 1]).toBe('');
+ });
+});
+
+describe('acestep engine entry', () => {
+ it('is lyric-aware and uses the acestep sidecar', () => {
+ expect(ENGINES.acestep.lyrics).toBe(true);
+ expect(ENGINES.acestep.scriptPath).toMatch(/generate_acestep\.py$/);
+ expect(ENGINES.acestep.installEnv).toBe('INSTALL_ACESTEP');
+ });
+
+ it('the other engines are NOT lyric-aware', () => {
+ expect(ENGINES.musicgen.lyrics).toBeUndefined();
+ expect(ENGINES.audioldm2.lyrics).toBeUndefined();
+ });
});
describe('buildMusicGenArgs (back-compat wrapper)', () => {