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
fix: make music-engine readiness mean "can actually run" (#4251)
[._.]/ Adam Eivy7b4336ee469e
diff --git a/.changelog/next/fixed-main.md b/.changelog/next/fixed-main.mdindex ca039b31a9..b6246ea258 100644--- a/.changelog/next/fixed-main.md+++ b/.changelog/next/fixed-main.md@@ -5,3 +5,6 @@- Single-file HuggingFace downloads no longer sit at 100% for the whole transfer — the badge now tracks bytes.- Enhance with AI and Prompt from media stay usable during a video render so the next clip can be queued.- Installing the MiniMax Music 3 engine no longer fails partway through — it now pulls a diffusers build that actually exists, and on Windows installs the CUDA build of PyTorch instead of the CPU-only one.+- Music engines whose install failed partway now report as not installed instead of ready — the Install button comes back, generation gives an actionable setup message instead of a Python traceback, and the installer stops refusing with 'already installed'+- Local music runtimes now build on a standalone Python instead of a conda base on Windows, where torch installs but cannot load (WinError 1114); an already-broken venv is rebuilt automatically+- MusicGen is now shown as unavailable on non-Apple-Silicon machines rather than offering an Install button whose installer skips and reports a confusing failurediff --git a/client/src/components/music/MusicGenPanel.jsx b/client/src/components/music/MusicGenPanel.jsxindex a42f6dcaa3..afb5341fca 100644--- a/client/src/components/music/MusicGenPanel.jsx+++ b/client/src/components/music/MusicGenPanel.jsx@@ -22,6 +22,9 @@ import {import RuntimeInstallModal from '../install/RuntimeInstallModal';function engineSetupMessage(engine) {+ // Host-incompatible comes first: it is the only reason that no amount of+ // installing will fix, so it must not be worded as a setup step.+ if (engine.platformSupported === false) return `${engine.name} requires ${engine.platformLabel || 'a different host'} and is unavailable on this machine.`;if (engine.cudaRequired && engine.cudaState === 'absent') return `${engine.name} requires an NVIDIA CUDA GPU and is unavailable on this host.`;if (engine.cudaRequired && engine.cudaState === 'unknown') return `${engine.name} is disabled because CUDA availability could not be determined.`;if (engine.runtimeReady === false && engine.fixedModelInstall && engine.modelReady === false) return `${engine.name} needs its runtime and model weights before generation.`;@@ -175,7 +178,9 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artistconst selectedUserModel = engine?.models?.find((m) => m.id === modelId && m.userAdded);const showRuntimeInstallHint = !!engine && !engine.ready && (!!prompt?.trim() || userSelectedEngine);- const canInstallRuntime = engine?.runtimeReady !== true && (!engine?.cudaRequired || engine?.cudaState === 'available');+ const canInstallRuntime = engine?.runtimeReady !== true+ && engine?.platformSupported !== false+ && (!engine?.cudaRequired || engine?.cudaState === 'available');return (<div className="space-y-2 border border-port-border rounded-lg p-3 bg-port-bg/40">@@ -195,7 +200,7 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artistclassName="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.cudaRequired && e.cudaState !== 'available' ? ' (CUDA unavailable)' : e.ready ? '' : ' (setup required)'}</option>+ <option key={e.id} value={e.id}>{e.name}{e.platformSupported === false ? ' (unavailable on this host)' : e.cudaRequired && e.cudaState !== 'available' ? ' (CUDA unavailable)' : e.ready ? '' : ' (setup required)'}</option>))}</select></label>@@ -243,7 +248,7 @@ export default function MusicGenPanel({ track, title = '', artistId = '', artist: null}</div>) : null}- {engine?.fixedModelInstall && !engine.modelReady && engine.cudaState === 'available' ? (+ {engine?.fixedModelInstall && !engine.modelReady && engine.platformSupported !== false && engine.cudaState === 'available' ? (<div className="rounded-lg border border-port-border px-3 py-2"><button type="button" onClick={handleFixedModelInstall} disabled={installing} className="inline-flex items-center gap-2 text-xs text-port-accent disabled:opacity-50">{installing ? <Loader2 size={13} className="animate-spin" /> : <Download size={13} />} Install modeldiff --git a/client/src/components/music/MusicGenPanel.test.jsx b/client/src/components/music/MusicGenPanel.test.jsxindex d03ccc0d00..1b1bddb8d2 100644--- a/client/src/components/music/MusicGenPanel.test.jsx+++ b/client/src/components/music/MusicGenPanel.test.jsx@@ -154,6 +154,27 @@ describe('MusicGenPanel', () => {expect(onGenerated).toHaveBeenCalledWith(expect.objectContaining({ id: 'generated-track' }));});+ it('names the host requirement and hides Install for a platform-gated engine', async () => {+ // MusicGen is MLX-only. Before this, a Windows/Linux user got an Install+ // button whose installer skipped and exited 0, surfaced as 'installer exited+ // 0 but MusicGen (MLX) is still not available'.+ api.listMusicEngines.mockResolvedValue({+ defaultEngine: 'musicgen',+ engines: [engine({+ ready: false,+ runtimeReady: false,+ platformSupported: false,+ platformLabel: 'macOS on Apple Silicon (MLX)',+ })],+ });++ render(<MusicGenPanel track={{ id: 'track-1' }} prompt="ambient bed" lyrics="" />);++ expect(await screen.findByText(/requires macOS on Apple Silicon/i)).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /install runtime/i })).not.toBeInTheDocument();+ expect(screen.getByRole('option', { name: /unavailable on this host/i })).toBeInTheDocument();+ });+it('offers the fixed-model install without suggesting a runtime reinstall', async () => {api.listMusicEngines.mockResolvedValue({defaultEngine: 'minimax-music3',diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.shindex 97c18ecf50..7b0849cba4 100755--- a/scripts/setup-image-video.sh+++ b/scripts/setup-image-video.sh@@ -712,6 +712,19 @@ fiINSTALL_MINIMAX_MUSIC3="${INSTALL_MINIMAX_MUSIC3:-0}"if [[ "$INSTALL_MINIMAX_MUSIC3" == "1" ]]; thenMINIMAX_MUSIC3_VENV="${HOME}/.portos/venv-minimax-music3"+ mkdir -p "${HOME}/.portos"+ # A venv built from a conda/anaconda base is the sticky Windows failure: pip+ # installs torch happily, then `import torch` dies with+ # "WinError 1114 ... c10.dll initialization routine failed" because conda's+ # MKL/OpenMP DLLs poison the search path. Re-running never helped, because the+ # venv already existed and got reused. Rebuild it when its recorded base is+ # conda and the interpreter we'd build from is not.+ if [[ -f "$MINIMAX_MUSIC3_VENV/pyvenv.cfg" ]] \+ && grep -qiE '^home *=.*(miniconda|anaconda)' "$MINIMAX_MUSIC3_VENV/pyvenv.cfg" \+ && [[ ! "$PYTHON_BIN" =~ [Mm]ini?conda|[Aa]naconda ]]; then+ echo "♻️ Existing MiniMax Music 3 venv was built from a conda base (torch can't load there) — rebuilding from ${PYTHON_BIN}."+ rm -rf "$MINIMAX_MUSIC3_VENV"+ fiMINIMAX_MUSIC3_PY="$MINIMAX_MUSIC3_VENV/bin/python3"[[ -x "$MINIMAX_MUSIC3_PY" || -x "$MINIMAX_MUSIC3_VENV/Scripts/python.exe" ]] || "$PYTHON_BIN" -m venv "$MINIMAX_MUSIC3_VENV"[[ -x "$MINIMAX_MUSIC3_PY" ]] || MINIMAX_MUSIC3_PY="$MINIMAX_MUSIC3_VENV/Scripts/python.exe"@@ -726,6 +739,20 @@ if [[ "$INSTALL_MINIMAX_MUSIC3" == "1" ]]; thenelse"$MINIMAX_MUSIC3_PY" -m pip install --upgrade torchfi+ # Fail here, with the cause named, rather than 400 MB of diffusers later. The+ # conda-base check above is a heuristic (a venv can inherit a poisoned DLL path+ # other ways); this is the ground truth.+ if ! "$MINIMAX_MUSIC3_PY" -c "import torch" 2>/dev/null; then+ echo "❌ torch installed into ${MINIMAX_MUSIC3_VENV} but cannot be imported." >&2+ "$MINIMAX_MUSIC3_PY" -c "import torch" 2>&1 | tail -5 >&2+ if is_windows; then+ echo " On Windows this is almost always a venv built from a conda/anaconda base:" >&2+ echo " conda's MKL/OpenMP DLLs break torch's c10.dll load (WinError 1114)." >&2+ echo " Install a standalone Python (\`uv python install 3.10\`, or python.org)," >&2+ echo " then re-run with PYTHON_BIN pointed at it." >&2+ fi+ exit 1+ fi# Pinned to the main commit that merged MiniMax Music 3 (diffusers PR #14456,# 2026-08-13) — the integration is in no tagged release yet. The pin must be a# commit reachable from main: pip clones the default branch, so a PR-branchdiff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.jsindex 48537b6a1f..afef58e035 100644--- a/server/lib/pythonSetup.js+++ b/server/lib/pythonSetup.js@@ -1,5 +1,5 @@import { execFile, spawn } from 'node:child_process';-import { existsSync } from 'node:fs';+import { existsSync, readdirSync } from 'node:fs';import { arch, homedir, platform } from 'node:os';import { dirname, join } from 'node:path';import { promisify } from 'node:util';@@ -56,6 +56,32 @@ export const pipNameFor = (importName) => PIP_NAMES[importName] || importName;const HOME = homedir();+// uv-managed CPython installs (`uv python install 3.10`). These are standalone+// python-build-standalone builds — no conda MKL/OpenMP in the DLL search path —+// which makes them the right base for a torch venv, so they rank with the+// python.org installs and ahead of conda. uv's install root is versioned and+// platform-tagged (`cpython-3.10.19-windows-x86_64-none`), so it has to be+// enumerated rather than listed. Newest version first; a bad read (uv absent,+// which is the common case) yields nothing rather than throwing.+const UV_PYTHON_ROOT = IS_WIN+ ? join(HOME, 'AppData', 'Roaming', 'uv', 'python')+ : join(HOME, '.local', 'share', 'uv', 'python');++function uvPythonCandidates() {+ let entries;+ try {+ entries = readdirSync(UV_PYTHON_ROOT);+ } catch {+ return [];+ }+ // Sort by the version triple descending, so 3.13 beats 3.10 and 3.10.19 beats+ // the bare 3.10 alias. localeCompare's numeric mode keeps 3.9 < 3.10.+ return entries+ .filter((name) => name.startsWith('cpython-'))+ .sort((a, b) => b.localeCompare(a, undefined, { numeric: true }))+ .map((name) => join(UV_PYTHON_ROOT, name, IS_WIN ? 'python.exe' : join('bin', 'python3')));+}+// Earlier = preferred. Non-externally-managed Pythons (venvs, conda) win// over Homebrew/system Pythons because PEP 668 blocks pip there.const PYTHON_CANDIDATES = IS_WIN@@ -136,6 +162,37 @@ export function detectPythonSync() {return found || null;}+// The interpreter to build a torch venv FROM — a different question than+// detectPythonSync's "which interpreter can we pip into".+//+// Those two answers conflict. `detectPythonSync` ranks conda highly precisely+// because conda is not PEP 668 externally-managed, so `installPackages` can pip+// straight into it. But a venv created from a conda base installs torch fine and+// then dies at `import torch` with "WinError 1114: c10.dll initialization routine+// failed" — conda's MKL/OpenMP DLLs poison the child venv's DLL search path.+// uv/python.org standalone builds are the reverse: externally-managed (so a bad+// pip target) but a perfect venv base.+//+// So this prefers standalone builds and only falls back to detectPythonSync's+// answer when there are none — a conda-based venv still beats no venv at all,+// and the setup script's own import check reports it when it can't work.+export function detectVenvBasePythonSync() {+ const standalone = [+ ...uvPythonCandidates(),+ ...(IS_WIN+ ? [+ join(HOME, 'AppData', 'Local', 'Programs', 'Python', 'Python313', 'python.exe'),+ join(HOME, 'AppData', 'Local', 'Programs', 'Python', 'Python312', 'python.exe'),+ join(HOME, 'AppData', 'Local', 'Programs', 'Python', 'Python311', 'python.exe'),+ 'C:\\Python313\\python.exe',+ 'C:\\Python312\\python.exe',+ 'C:\\Python311\\python.exe',+ ]+ : []),+ ];+ return standalone.find((p) => existsSync(p)) || detectPythonSync();+}+export async function detectPython() {// mlx ships arm64-only wheels; prefer an arm64 interpreter on Apple Silicon// so /opt/anaconda3 (often x86_64) doesn't beat /opt/homebrew/bin/python3.diff --git a/server/lib/pythonSetup.test.js b/server/lib/pythonSetup.test.jsindex a6e233476b..06121515da 100644--- a/server/lib/pythonSetup.test.js+++ b/server/lib/pythonSetup.test.js@@ -14,6 +14,8 @@ const mockState = {archByPath: new Map(),execShouldFail: false,pathPython: null,+ // Directory names under uv python root, as readdirSync would return them.+ uvPythonDirs: null,};vi.mock('node:os', async () => {@@ -32,7 +34,18 @@ vi.mock('node:fs', async () => {// Windows host they arrive backslash-separated while presentPaths is seeded// with the POSIX spellings the tests read. Normalize the probe, not the// fixtures — the module's own platform is pinned via mockState.platform.- return { ...actual, existsSync: (p) => mockState.presentPaths.has(String(p).split('\\').join('/')) };+ return {+ ...actual,+ existsSync: (p) => mockState.presentPaths.has(String(p).split('\\').join('/')),+ // uv's install root is enumerated rather than listed, so the candidate+ // builder readdirs it. `null` means "uv not installed" — the common case —+ // and must throw the way the real readdirSync does so the builder swallows+ // it instead of crashing module load.+ readdirSync: () => {+ if (!mockState.uvPythonDirs) throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' });+ return mockState.uvPythonDirs;+ },+ };});vi.mock('node:child_process', async () => {@@ -81,6 +94,7 @@ const resetState = () => {mockState.archByPath = new Map();mockState.execShouldFail = false;mockState.pathPython = null;+ mockState.uvPythonDirs = null;};describe('HOST_ARCH', () => {@@ -304,3 +318,73 @@ describe('resolveMfluxPython', () => {expect(resolveMfluxPython()).toBeNull();});});+describe('detectVenvBasePythonSync', () => {+ beforeEach(resetState);++ const WIN_UV = 'C:/Users/example/AppData/Roaming/uv/python';++ it('prefers a uv standalone build over conda — a conda-based venv cannot import torch', async () => {+ // Regression: on a box whose only listed Python was miniconda, every torch+ // venv the installer built died at `import torch` with+ // "WinError 1114 ... c10.dll initialization routine failed".+ mockState.platform = 'win32';+ mockState.homedir = 'C:/Users/example';+ mockState.uvPythonDirs = ['cpython-3.10-windows-x86_64-none'];+ mockState.presentPaths.add(`${WIN_UV}/cpython-3.10-windows-x86_64-none/python.exe`);+ mockState.presentPaths.add('C:/Users/example/miniconda3/python.exe');+ const { detectVenvBasePythonSync, detectPythonSync } = await loadModule();+ expect(posixPath(detectVenvBasePythonSync())).toBe(`${WIN_UV}/cpython-3.10-windows-x86_64-none/python.exe`);+ // ...and the pip-target picker is deliberately unchanged: uv Pythons are+ // PEP 668 externally-managed, so installPackages must not be sent there.+ expect(posixPath(detectPythonSync())).toBe('C:/Users/example/miniconda3/python.exe');+ });++ it('prefers the newest uv version, and 3.9 does not beat 3.10', async () => {+ mockState.platform = 'win32';+ mockState.homedir = 'C:/Users/example';+ mockState.uvPythonDirs = [+ 'cpython-3.9.21-windows-x86_64-none',+ 'cpython-3.13.12-windows-x86_64-none',+ 'cpython-3.10.19-windows-x86_64-none',+ ];+ for (const d of mockState.uvPythonDirs) mockState.presentPaths.add(`${WIN_UV}/${d}/python.exe`);+ const { detectVenvBasePythonSync } = await loadModule();+ expect(posixPath(detectVenvBasePythonSync())).toContain('cpython-3.13.12');+ });++ it('ignores non-cpython entries under the uv root and falls through to python.org', async () => {+ mockState.platform = 'win32';+ mockState.homedir = 'C:/Users/example';+ mockState.uvPythonDirs = ['.temp', 'pypy-3.10-windows-x86_64-none'];+ mockState.presentPaths.add('C:/Users/example/AppData/Local/Programs/Python/Python312/python.exe');+ mockState.presentPaths.add('C:/Users/example/miniconda3/python.exe');+ const { detectVenvBasePythonSync } = await loadModule();+ expect(posixPath(detectVenvBasePythonSync()))+ .toBe('C:/Users/example/AppData/Local/Programs/Python/Python312/python.exe');+ });++ it('falls back to the pip-target answer when no standalone build exists — a conda venv beats no venv', async () => {+ mockState.platform = 'win32';+ mockState.homedir = 'C:/Users/example';+ mockState.uvPythonDirs = null; // uv not installed: readdir throws+ mockState.presentPaths.add('C:/Users/example/miniconda3/python.exe');+ const { detectVenvBasePythonSync } = await loadModule();+ expect(posixPath(detectVenvBasePythonSync())).toBe('C:/Users/example/miniconda3/python.exe');+ });++ it('finds uv under its Linux install root too', async () => {+ mockState.platform = 'linux';+ mockState.homedir = '/home/example';+ mockState.uvPythonDirs = ['cpython-3.12.8-linux-x86_64-gnu'];+ mockState.presentPaths.add('/home/example/.local/share/uv/python/cpython-3.12.8-linux-x86_64-gnu/bin/python3');+ mockState.presentPaths.add('/opt/miniconda3/bin/python3');+ const { detectVenvBasePythonSync } = await loadModule();+ expect(posixPath(detectVenvBasePythonSync()))+ .toBe('/home/example/.local/share/uv/python/cpython-3.12.8-linux-x86_64-gnu/bin/python3');+ });++ it('returns null when there is no Python at all', async () => {+ const { detectVenvBasePythonSync } = await loadModule();+ expect(detectVenvBasePythonSync()).toBeNull();+ });+});diff --git a/server/lib/setupScriptRunner.js b/server/lib/setupScriptRunner.jsindex 35ad44d84e..cbba1f2df4 100644--- a/server/lib/setupScriptRunner.js+++ b/server/lib/setupScriptRunner.js@@ -18,7 +18,7 @@ import { join } from 'path';import { PATHS } from './fileUtils.js';import { resolveBashBinary, toBashPath } from './bashResolver.js';import { safeChildProcessEnv } from './processEnv.js';-import { detectPythonSync } from './pythonSetup.js';+import { detectVenvBasePythonSync } from './pythonSetup.js';import { killProcessTree } from './bufferedSpawn.js';const IS_WIN = process.platform === 'win32';@@ -38,7 +38,10 @@ export function spawnSetupScript(envVars = {}) {// An explicit PYTHON_BIN — from the caller or the environment — is the// documented override and wins over anything detected here.if (IS_WIN && !env.PYTHON_BIN && !process.env.PYTHON_BIN) {- const python = detectPythonSync();+ // Venv-base picker, not the pip-target picker: everything this script does+ // with PYTHON_BIN is `python -m venv`, and a conda base yields a venv whose+ // torch cannot load. See detectVenvBasePythonSync.+ const python = detectVenvBasePythonSync();if (python) env.PYTHON_BIN = toBashPath(python);}return spawn(resolveBashBinary(), [toBashPath(SETUP_IMAGE_VIDEO_SCRIPT)], {diff --git a/server/lib/setupScriptRunner.test.js b/server/lib/setupScriptRunner.test.jsindex 9a63901be1..053aa95e6d 100644--- a/server/lib/setupScriptRunner.test.js+++ b/server/lib/setupScriptRunner.test.js@@ -15,7 +15,7 @@ vi.mock('./bashResolver.js', async (importOriginal) => ({}));const detectPythonSyncMock = vi.fn();vi.mock('./pythonSetup.js', () => ({- detectPythonSync: (...a) => detectPythonSyncMock(...a),+ detectVenvBasePythonSync: (...a) => detectPythonSyncMock(...a),}));const killProcessTreeMock = vi.fn();vi.mock('./bufferedSpawn.js', () => ({diff --git a/server/routes/midiRuntime.test.js b/server/routes/midiRuntime.test.jsindex f2a590bfda..fa1e6b77d9 100644--- a/server/routes/midiRuntime.test.js+++ b/server/routes/midiRuntime.test.js@@ -14,7 +14,9 @@ vi.mock('../lib/pythonSetup.js', () => ({isMuscriptorRuntimeReady: async () => py.installed,invalidateMuscriptorPython: vi.fn(),MUSCRIPTOR_VENV_DEFAULT: '/home/x/.portos/venv-muscriptor/bin/python3',- detectPythonSync: () => null, // setupScriptRunner's Windows PYTHON_BIN preset+ detectPythonSync: () => null,+ // setupScriptRunner presets PYTHON_BIN from the venv-base picker on Windows.+ detectVenvBasePythonSync: () => null,}));// Real SSE frames so supertest can read them off the response body.diff --git a/server/routes/music.js b/server/routes/music.jsindex bc4d6002e1..49e350639e 100644--- a/server/routes/music.js+++ b/server/routes/music.js@@ -23,7 +23,10 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import { createLineReader } from '../lib/streamLines.js';import { SETUP_IMAGE_VIDEO_SCRIPT, spawnSetupScript, stopSetupScript } from '../lib/setupScriptRunner.js';-import { ENGINES, DEFAULT_ENGINE_ID, getEngine, isEngineReady, generateMusic } from '../services/pipeline/musicGen.js';+import {+ ENGINES, DEFAULT_ENGINE_ID, getEngine, isEngineHealthy, isEnginePlatformSupported,+ enginePlatformLabel, generateMusic,+} from '../services/pipeline/musicGen.js';import { listEngineModels, addAudioModel, removeAudioModel, isValidRepoId } from '../services/audioModels.js';import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';import { createInstallLogger } from '../lib/installLogger.js';@@ -42,7 +45,10 @@ router.get('/engines', asyncHandler(async (_req, res) => {const cuda = await getCudaCapability();const engines = await Promise.all(Object.values(ENGINES).map(async (engine) => {const modelCache = engine.fixedModelInstall ? await inspectModelCache(engine.models[0].repo).catch(() => ({ cached: false })) : null;- const runtimeReady = isEngineReady(engine.id);+ // 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.+ const runtimeReady = await isEngineHealthy(engine.id);return ({id: engine.id,name: engine.name,@@ -60,6 +66,11 @@ router.get('/engines', asyncHandler(async (_req, res) => {modelReady: modelCache ? modelCache.cached === true : true,runtimeReady,cudaRequired: engine.cudaRequired === true,+ // false when this host can never run the backend (e.g. MLX MusicGen off+ // Apple Silicon) — the UI shows "unavailable" instead of an Install button+ // whose installer would skip and exit 0.+ 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),installEnv: engine.installEnv,@@ -87,7 +98,7 @@ router.get('/setup/runtime-status', asyncHandler(async (req, res) => {res.json({runtime: engine.id,label: engine.name,- installed: isEngineReady(engine.id),+ installed: await isEngineHealthy(engine.id),venvPath: engine.resolvePython() || null,expectedVenvPath: engine.venvDefault,installEnvVar: engine.installEnv,@@ -109,6 +120,10 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {send({ type: 'error', message: `Another ${engine.name} install is already running. Wait for it to finish or restart PortOS.` });return safeEnd();}+ if (!isEnginePlatformSupported(engine.id)) {+ send({ type: 'error', message: `${engine.name} requires ${enginePlatformLabel(engine.id)} and cannot be installed on this host.` });+ return safeEnd();+ }if (engine.cudaRequired) {const cuda = await getCudaCapability();if (cuda.status !== 'available') {@@ -120,7 +135,9 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {}runtimeInstallInFlight.set(engine.id, null);- if (isEngineReady(engine.id)) {+ // Force a fresh probe: a cached `true` from before the venv broke would+ // short-circuit the very install meant to repair it.+ if (await isEngineHealthy(engine.id, { refresh: true })) {runtimeInstallInFlight.delete(engine.id);send({ type: 'log', message: `${engine.name} already installed at ${engine.resolvePython() || engine.venvDefault}` });send({ type: 'complete', message: 'Already installed - nothing to do.' });@@ -160,19 +177,31 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {emit({ type: 'error', message: `Installer failed to spawn: ${err.message}` });safeEnd();});- child.on('close', (code) => {- stdoutReader.flush();- stderrReader.flush();- finished = true;- runtimeInstallInFlight.delete(engine.id);- if (code === 0 && isEngineReady(engine.id)) {- emit({ type: 'complete', message: `${engine.name} ready: ${engine.resolvePython() || engine.venvDefault}` });- } else if (code === 0) {- emit({ type: 'error', message: `Installer exited 0 but ${engine.name} is still not available. Check the log above for setup errors.` });- } else {- emit({ type: 'error', message: `Installer exited with code ${code}.` });+ // Async because the completion verdict re-probes the venv. try/catch because+ // this runs outside the request lifecycle — an uncaught throw here would take+ // the process down instead of reaching the error middleware.+ child.on('close', async (code) => {+ try {+ stdoutReader.flush();+ stderrReader.flush();+ finished = true;+ runtimeInstallInFlight.delete(engine.id);+ // The venv just changed on disk, so the cached verdict is stale by+ // definition — re-probe rather than trusting it.+ const healthy = code === 0 && await isEngineHealthy(engine.id, { refresh: true });+ if (healthy) {+ emit({ type: 'complete', message: `${engine.name} ready: ${engine.resolvePython() || engine.venvDefault}` });+ } else if (code === 0) {+ emit({ type: 'error', message: `Installer exited 0 but ${engine.name} is still not available. Check the log above for setup errors.` });+ } else {+ emit({ type: 'error', message: `Installer exited with code ${code}.` });+ }+ safeEnd();+ } catch (err) {+ console.error(`❌ ${engine.name} install completion check failed: ${err.message}`);+ emit({ type: 'error', message: `Install completion check failed: ${err.message}` });+ safeEnd();}- safeEnd();});req.on('close', () => {diff --git a/server/routes/music.test.js b/server/routes/music.test.jsindex a3be3c6030..c3d2781050 100644--- a/server/routes/music.test.js+++ b/server/routes/music.test.js@@ -4,12 +4,15 @@ 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/+// tests drive per-case. The route only consumes ENGINES/getEngine/isEngineHealthy/// generateMusic + DEFAULT_ENGINE_ID.const gen = vi.hoisted(() => ({generateMusic: vi.fn(),ready: true,readyByEngine: null,+ healthy: null,+ healthyByEngine: null,+ unsupportedPlatform: null,}));const cuda = vi.hoisted(() => ({ status: 'available' }));vi.mock('../lib/cudaCapability.js', () => ({@@ -26,10 +29,42 @@ vi.mock('../services/pipeline/musicGen.js', () => {DEFAULT_ENGINE_ID: 'musicgen',getEngine: (id) => ENGINES[id] || ENGINES.musicgen,isEngineReady: (engineId) => (gen.readyByEngine ? gen.readyByEngine[engineId] === true : gen.ready),+ // The route reads readiness through isEngineHealthy (the import probe), so+ // `gen.healthyByEngine` / `gen.healthy` drive it; both default to the same+ // `ready` knobs so existing cases keep their meaning.+ isEnginePlatformSupported: (engineId) => (gen.unsupportedPlatform ? engineId !== gen.unsupportedPlatform : true),+ enginePlatformLabel: () => 'macOS on Apple Silicon (MLX)',+ isEngineHealthy: async (engineId) => {+ if (gen.healthyByEngine) return gen.healthyByEngine[engineId] === true;+ if (gen.healthy !== null) return gen.healthy;+ return gen.readyByEngine ? gen.readyByEngine[engineId] === true : gen.ready;+ },+ invalidateEngineHealth: vi.fn(),generateMusic: gen.generateMusic,};});+// The install route shells out to scripts/setup-image-video.sh. Stand in a child+// that closes immediately so the SSE stream terminates instead of running a real+// multi-GB bash install under the test.+const setup = vi.hoisted(() => ({ spawn: vi.fn(), exitCode: 0 }));+vi.mock('../lib/setupScriptRunner.js', async () => ({+ // Keep the real SETUP_IMAGE_VIDEO_SCRIPT — the route existsSync-checks it.+ ...(await vi.importActual('../lib/setupScriptRunner.js')),+ stopSetupScript: vi.fn(),+ spawnSetupScript: (env) => {+ setup.spawn(env);+ const listeners = {};+ const child = {+ stdout: { on: () => {} },+ stderr: { on: () => {} },+ on: (event, cb) => { listeners[event] = cb; },+ };+ Promise.resolve().then(() => listeners.close?.(setup.exitCode));+ return child;+ },+}));+vi.mock('../services/tracks/index.js', () => ({getTrack: vi.fn(),createTrack: vi.fn(async (input) => ({ id: 'track-new', ...input })),@@ -108,6 +143,11 @@ describe('music routes', () => {sse.run.mockReset().mockImplementation(async ({ res }) => { res.writeHead(200, { 'Content-Type': 'text/event-stream' }); res.end('data: {"type":"complete"}\n\n'); });gen.ready = true;gen.readyByEngine = null;+ gen.healthy = null;+ gen.healthyByEngine = null;+ gen.unsupportedPlatform = null;+ setup.spawn.mockReset();+ setup.exitCode = 0;cache.cached = true;cuda.status = 'available';models.list.mockResolvedValue([{ id: 'm', name: 'M', userAdded: false }]);@@ -185,6 +225,50 @@ describe('music routes', () => {expect(r.text).toContain('Already installed');});+ it('GET /setup/runtime-install proceeds when the interpreter exists but the venv is broken', async () => {+ // Regression: a failed install leaves the venv's interpreter behind, so the+ // old interpreter-exists check short-circuited with "already installed" and+ // the engine could never be repaired from the UI.+ gen.ready = true; // resolvePython() finds the leftover interpreter+ gen.healthy = false; // ...but the import probe fails+ const r = await request(app).get('/api/music/setup/runtime-install?runtime=acestep');+ expect(r.status).toBe(200);+ expect(r.text).not.toContain('Already installed');+ expect(r.text).toContain('Starting ACE-Step install.');+ expect(setup.spawn).toHaveBeenCalled();+ });++ it('GET /engines reports a broken venv as not ready so the install hint shows', async () => {+ gen.ready = true;+ gen.healthy = false;+ const r = await request(app).get('/api/music/engines');+ expect(r.status).toBe(200);+ const acestep = r.body.engines.find((e) => e.id === 'acestep');+ expect(acestep.runtimeReady).toBe(false);+ expect(acestep.ready).toBe(false);+ });++ it('GET /setup/runtime-install refuses on a host that can never run the engine', async () => {+ // Previously the route spawned the setup script, whose own platform guard+ // printed "Skipping." and exited 0 — surfaced to the user as "installer+ // exited 0 but the engine is still not available".+ gen.unsupportedPlatform = 'musicgen';+ gen.healthy = false;+ const r = await request(app).get('/api/music/setup/runtime-install?runtime=musicgen');+ expect(r.status).toBe(200);+ expect(r.text).toContain('cannot be installed on this host');+ expect(setup.spawn).not.toHaveBeenCalled();+ });++ it('GET /engines flags a host-incompatible engine so the UI can hide Install', async () => {+ gen.unsupportedPlatform = 'musicgen';+ const r = await request(app).get('/api/music/engines');+ const musicgen = r.body.engines.find((e) => e.id === 'musicgen');+ expect(musicgen.platformSupported).toBe(false);+ expect(musicgen.platformLabel).toContain('Apple Silicon');+ expect(r.body.engines.find((e) => e.id === 'acestep').platformSupported).toBe(true);+ });+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);diff --git a/server/routes/pipeline/audio.js b/server/routes/pipeline/audio.jsindex a0b9d13729..e5901f03fc 100644--- a/server/routes/pipeline/audio.js+++ b/server/routes/pipeline/audio.js@@ -28,7 +28,7 @@ import {generateMusic,ENGINES,DEFAULT_ENGINE_ID,- isEngineReady,+ isEngineHealthy,} from '../../services/pipeline/musicGen.js';import { deriveAudioCues, preserveRenderedCues } from '../../services/pipeline/audioCues.js';import { uploadSingle } from '../../lib/multipart.js';@@ -292,7 +292,7 @@ router.get('/audio/music-library', asyncHandler(async (_req, res) => {// id. The top-level `models`/`ready`/duration fields mirror the default engine// for backward compatibility with pre-multi-engine clients.router.get('/audio/music/generators', asyncHandler(async (_req, res) => {- const engines = Object.values(ENGINES).map((engine) => ({+ const engines = await Promise.all(Object.values(ENGINES).map(async (engine) => ({id: engine.id,name: engine.name,models: engine.models.map(({ id, name }) => ({ id, name })),@@ -303,8 +303,10 @@ router.get('/audio/music/generators', asyncHandler(async (_req, res) => {// The authoritative install-hint env var (e.g. INSTALL_AUDIOLDM2) so the UI// renders the exact command instead of re-deriving it from the engine id.installEnv: engine.installEnv,- ready: isEngineReady(engine.id),- }));+ // Health, not path-existence: a half-built venv would report ready here and+ // then fail inside the sidecar. Matches /api/music/engines.+ ready: await isEngineHealthy(engine.id),+ })));const fallback = engines.find((e) => e.id === DEFAULT_ENGINE_ID) ?? engines[0];res.json({engines,diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex b35ea75280..059a32d465 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -57,7 +57,9 @@ vi.mock('../services/tracks/index.js', () => ({vi.mock('../lib/pythonSetup.js', () => ({checkPackages: vi.fn(async () => ({ installed: ['mflux', 'mlx'], missing: [], missingPip: [] })),isAllowedPython: vi.fn(() => true),- detectPythonSync: vi.fn(() => null), // setupScriptRunner's Windows PYTHON_BIN preset+ detectPythonSync: vi.fn(() => null),+ // setupScriptRunner presets PYTHON_BIN from the venv-base picker on Windows.+ detectVenvBasePythonSync: vi.fn(() => null),}));vi.mock('../services/videoGen/local.js', () => ({diff --git a/server/services/creativeDirector/firstPassMusicGen.js b/server/services/creativeDirector/firstPassMusicGen.jsindex 5b50f59c72..aa3c8a4b64 100644--- a/server/services/creativeDirector/firstPassMusicGen.js+++ b/server/services/creativeDirector/firstPassMusicGen.js@@ -20,15 +20,21 @@*/import { enqueueJob } from '../mediaJobQueue/index.js';-import { ENGINES, DEFAULT_ENGINE_ID, isEngineReady } from '../pipeline/musicGen.js';+import { ENGINES, DEFAULT_ENGINE_ID, isEngineHealthy } from '../pipeline/musicGen.js';// First provisioned engine in ENGINES' declared order (musicgen, audioldm2,// acestep), so a project where only a non-default local backend is installed// (e.g. AudioLDM2 but not MusicGen) still gets a first-pass bed instead of// silently skipping on a hardcoded DEFAULT_ENGINE_ID check. Returns null when// nothing is provisioned.-function firstReadyEngineId() {- return Object.keys(ENGINES).find((id) => isEngineReady(id)) || null;+// Sequential on purpose: ENGINES' declared order IS the preference order, so+// the first healthy backend wins and the rest are never probed. isEngineHealthy+// caches its verdict, so the spawn cost is paid once per engine per process.+async function firstReadyEngineId() {+ for (const id of Object.keys(ENGINES)) {+ if (await isEngineHealthy(id)) return id;+ }+ return null;}// Keep the derived prompt bounded — a music-gen prompt is a short mood/style@@ -77,8 +83,10 @@ export async function enqueueFirstPassMusicBed(project, { engine } = {}) {// Resolve the engine once the project is known to need a render. An// explicit `engine` wins; otherwise prefer any provisioned local backend// over assuming the default (musicgen) is the one installed.- const resolvedEngine = engine || firstReadyEngineId() || DEFAULT_ENGINE_ID;- if (!isEngineReady(resolvedEngine)) {+ const resolvedEngine = engine || await firstReadyEngineId() || DEFAULT_ENGINE_ID;+ // Health, not mere presence: a half-built venv would otherwise pass this gate+ // and the enqueued job would die at render with a Python ImportError.+ if (!await isEngineHealthy(resolvedEngine)) {return { mode: resolvedEngine, enqueued: false, reason: 'engine-not-ready' };}const prompt = buildMusicBedPrompt(project);diff --git a/server/services/creativeDirector/firstPassMusicGen.test.js b/server/services/creativeDirector/firstPassMusicGen.test.jsindex a19cfe5930..a81022c8ed 100644--- a/server/services/creativeDirector/firstPassMusicGen.test.js+++ b/server/services/creativeDirector/firstPassMusicGen.test.js@@ -6,12 +6,12 @@ vi.mock('../mediaJobQueue/index.js', () => ({vi.mock('../pipeline/musicGen.js', () => ({ENGINES: { musicgen: {}, audioldm2: {}, acestep: {} },DEFAULT_ENGINE_ID: 'musicgen',- isEngineReady: vi.fn(),+ isEngineHealthy: vi.fn(),}));import { buildMusicBedPrompt, enqueueFirstPassMusicBed } from './firstPassMusicGen.js';import { enqueueJob } from '../mediaJobQueue/index.js';-import { isEngineReady } from '../pipeline/musicGen.js';+import { isEngineHealthy } from '../pipeline/musicGen.js';let jobSeq = 0;@@ -19,7 +19,7 @@ beforeEach(() => {vi.clearAllMocks();jobSeq = 0;enqueueJob.mockImplementation(() => ({ jobId: `job-${++jobSeq}`, position: 1, status: 'queued' }));- isEngineReady.mockReturnValue(true);+ isEngineHealthy.mockResolvedValue(true);});describe('buildMusicBedPrompt', () => {@@ -73,7 +73,7 @@ describe('enqueueFirstPassMusicBed', () => {});it('skips gracefully when no engine is ready', async () => {- isEngineReady.mockReturnValue(false);+ isEngineHealthy.mockResolvedValue(false);const project = { id: 'proj-1', name: 'Neon Drift' };const out = await enqueueFirstPassMusicBed(project);expect(out).toEqual({ mode: 'musicgen', enqueued: false, reason: 'engine-not-ready' });@@ -90,11 +90,11 @@ describe('enqueueFirstPassMusicBed', () => {it('reports no-project for a missing / id-less project (never reads engine readiness)', async () => {expect(await enqueueFirstPassMusicBed(null)).toEqual({ mode: 'musicgen', enqueued: false, reason: 'no-project' });expect(await enqueueFirstPassMusicBed({ name: 'no id' })).toEqual({ mode: 'musicgen', enqueued: false, reason: 'no-project' });- expect(isEngineReady).not.toHaveBeenCalled();+ expect(isEngineHealthy).not.toHaveBeenCalled();});it('prefers a ready non-default engine over the default when the default is not provisioned', async () => {- isEngineReady.mockImplementation((id) => id === 'audioldm2');+ isEngineHealthy.mockImplementation(async (id) => id === 'audioldm2');const project = { id: 'proj-1', name: 'Neon Drift', styleSpec: 'synthwave' };const out = await enqueueFirstPassMusicBed(project);expect(out).toEqual({ mode: 'audioldm2', enqueued: true, jobId: 'job-1' });@@ -106,6 +106,6 @@ describe('enqueueFirstPassMusicBed', () => {const out = await enqueueFirstPassMusicBed(project, { engine: 'acestep' });expect(out.mode).toBe('acestep');expect(enqueueJob.mock.calls[0][0].params.engine).toBe('acestep');- expect(isEngineReady).toHaveBeenCalledWith('acestep');+ expect(isEngineHealthy).toHaveBeenCalledWith('acestep');});});diff --git a/server/services/pipeline/musicGen.js b/server/services/pipeline/musicGen.jsindex e1ec6ee1ec..449ca3b516 100644--- a/server/services/pipeline/musicGen.js+++ b/server/services/pipeline/musicGen.js@@ -28,6 +28,9 @@*/import { existsSync, statSync } from 'fs';+import { execFile } from 'child_process';+import { platform as osPlatform, arch as osArch } from 'os';+import { promisify } from 'util';import { unlink } from 'fs/promises';import { join, dirname } from 'path';import { fileURLToPath } from 'url';@@ -44,6 +47,9 @@ import {import { getCudaCapability } from '../../lib/cudaCapability.js';import { inspectModelCache } from '../../lib/hfCache.js';import { ServerError } from '../../lib/errorHandler.js';+import { safeChildProcessEnv } from '../../lib/processEnv.js';++const execFileAsync = promisify(execFile);const __dirname = dirname(fileURLToPath(import.meta.url));// The sidecar scripts live at the repo root — resolve module-relative so the@@ -104,6 +110,15 @@ export const MINIMAX_MUSIC3_MODELS = Object.freeze([* - `scriptPath` — the Python sidecar* - `runtimeDir` — value for the sidecar's --runtime-dir flag* - `resolvePython` — () => venv interpreter path | null (readiness probe)+ * - `healthProbe` — python source proving the venv can actually run this+ * backend. `resolvePython` only confirms the interpreter exists, and a+ * failed/cancelled install leaves the interpreter with no packages — see+ * isEngineHealthy below. Mirrors each engine's assertion in+ * scripts/setup-image-video.sh; keep the two in sync.+ * - `requiresPlatform` — hosts this backend can run on at all, when it is not+ * portable. Absent means "anywhere". The installer already refuses on the+ * wrong host, but without this the UI offers an Install button that exits 0+ * having done nothing — see isEnginePlatformSupported below.* - `venvDefault`/`installEnv` — install-hint pieces for the 503 message*/export const ENGINES = Object.freeze({@@ -120,6 +135,14 @@ export const ENGINES = Object.freeze({resolvePython: resolveMusicgenPython,venvDefault: MUSICGEN_VENV_DEFAULT,installEnv: 'INSTALL_MUSICGEN',+ // MLX is Apple-Silicon only, and the implementation lives in the+ // ml-explore/mlx-examples clone rather than a pip package — there is no+ // Windows/Linux path at all. Mirrors the is_macos guard in+ // scripts/setup-image-video.sh's INSTALL_MUSICGEN block.+ requiresPlatform: { platform: 'darwin', arch: 'arm64', label: 'macOS on Apple Silicon (MLX)' },+ // Mirrors the setup script's MusicGen assertion — the class lives in the+ // mlx-examples clone, so the probe re-creates the sidecar's sys.path insert.+ healthProbe: 'import sys; sys.path.insert(0, r"' + MUSICGEN_RUNTIME_DIR + '"); import torch; from musicgen import MusicGen',// The sidecar passes `--model <repo>` straight to from_pretrained, so any// HuggingFace MusicGen checkpoint works — user-installed models are usable.customModels: true,@@ -137,6 +160,7 @@ export const ENGINES = Object.freeze({resolvePython: resolveAudioldm2Python,venvDefault: AUDIOLDM2_VENV_DEFAULT,installEnv: 'INSTALL_AUDIOLDM2',+ healthProbe: 'import torch; from diffusers import AudioLDM2Pipeline',// `--model <repo>` → AudioLDM2Pipeline.from_pretrained: any HF AudioLDM2// checkpoint works, so user-installed models are usable.customModels: true,@@ -154,6 +178,7 @@ export const ENGINES = Object.freeze({resolvePython: resolveAcestepPython,venvDefault: ACESTEP_VENV_DEFAULT,installEnv: 'INSTALL_ACESTEP',+ healthProbe: 'import torch; from acestep.pipeline_ace_step import ACEStepPipeline',// 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,@@ -177,6 +202,7 @@ export const ENGINES = Object.freeze({resolvePython: resolveMinimaxMusic3Python,venvDefault: MINIMAX_MUSIC3_VENV_DEFAULT,installEnv: 'INSTALL_MINIMAX_MUSIC3',+ healthProbe: 'import torch; from diffusers import ModularPipeline',lyrics: true,customModels: false,fixedModelInstall: true,@@ -205,14 +231,84 @@ export function getMusicgenModel(modelId) {return MUSICGEN_MODELS.find((m) => m.id === modelId) || null;}-// Whether a backend's opt-in venv is provisioned. The UI gates its "Generate"-// affordance on this so users see an install hint instead of a 503 after typing-// a prompt. Cheap (an existsSync probe behind the resolver's cache) — safe to-// call per request.+// Whether this host can run a backend at all. An engine with no+// `requiresPlatform` is portable and always supported. Distinct from every other+// readiness signal: the others describe something the user can fix by+// installing, this one never becomes true here. Without it the UI offers an+// Install button that runs the setup script, hits its own platform guard, prints+// "Skipping.", and exits 0 — reported back as "installer exited 0 but the engine+// is still not available", which reads like a broken install rather than an+// unsupported host.+export function isEnginePlatformSupported(engineId) {+ const { requiresPlatform } = getEngine(engineId);+ if (!requiresPlatform) return true;+ if (requiresPlatform.platform && osPlatform() !== requiresPlatform.platform) return false;+ if (requiresPlatform.arch && osArch() !== requiresPlatform.arch) return false;+ return true;+}++// Human-readable requirement for the UI's "unavailable on this host" copy, or+// null for a portable engine.+export function enginePlatformLabel(engineId) {+ return getEngine(engineId).requiresPlatform?.label || null;+}++// Whether a backend's venv interpreter exists. Cheap (an existsSync behind the+// resolver's cache) but NOT sufficient for a readiness verdict — a failed+// install leaves the interpreter with no packages, and this still says yes.+// Prefer `isEngineHealthy` for anything that gates install/generate UI; this+// stays as the synchronous "is there a venv at all" primitive.export function isEngineReady(engineId) {return getEngine(engineId).resolvePython() !== null;}+// Whether a backend's venv can actually RUN — not just whether its interpreter+// file exists. An install that dies partway (pip resolve failure, a killed+// child, a lost network) leaves `venv-<engine>/…/python` behind with none of the+// packages, and `isEngineReady` reports that corpse as provisioned forever: the+// install endpoint then short-circuits with "already installed", the UI hides+// the install affordance, and the engine can never be repaired from the app.+// Same failure `isFlux2VenvHealthy` exists to prevent for the FLUX.2 venv.+//+// Cached per engine because the probe spawns a Python process. `refresh: true`+// forces a re-probe — the install path passes it so a venv that broke after the+// last check is re-examined instead of trusting a stale `true`.+const engineHealthCache = new Map();++export async function isEngineHealthy(engineId, { refresh = false } = {}) {+ const engine = getEngine(engineId);+ // A host that can never run this backend is never healthy, and probing it+ // would spawn a python that cannot exist.+ if (!isEnginePlatformSupported(engine.id)) return false;+ if (refresh) engineHealthCache.delete(engine.id);+ else if (engineHealthCache.has(engine.id)) return engineHealthCache.get(engine.id);++ const python = engine.resolvePython();+ if (!python) {+ engineHealthCache.set(engine.id, false);+ return false;+ }+ // No declared probe → fall back to the interpreter-exists verdict rather than+ // guessing an import and reporting a working engine as broken.+ if (!engine.healthProbe) {+ engineHealthCache.set(engine.id, true);+ return true;+ }+ const healthy = await execFileAsync(python, ['-c', engine.healthProbe], {+ env: safeChildProcessEnv(),+ timeout: 60_000,+ }).then(() => true).catch(() => false);+ engineHealthCache.set(engine.id, healthy);+ return healthy;+}++// Drop a cached health verdict (or all of them). Called after an install so the+// next readiness check re-probes the freshly-built venv.+export function invalidateEngineHealth(engineId = null) {+ if (engineId) engineHealthCache.delete(engineId);+ else engineHealthCache.clear();+}+// Back-compat: MusicGen readiness probe.export function isMusicGenReady() {return resolveMusicgenPython() !== null;@@ -314,7 +410,13 @@ export async function generateMusic({ prompt, lyrics, engine: engineId = DEFAULT});}}- if (!pythonPath) {+ // Health, not just "the interpreter file is there". A venv left half-built by+ // a failed install passes the path check and then dies inside the sidecar with+ // a raw ImportError traceback; this turns that into the actionable 503 the+ // module contract promises. Subsumes the old `!pythonPath` guard — a missing+ // interpreter is unhealthy by definition, and is answered without a spawn. The+ // verdict is cached, so this costs one spawn per engine per process.+ if (!await isEngineHealthy(engine.id)) {throw new ServerError(`${engine.name} runtime not found. Run \`${engine.installEnv}=1 bash scripts/setup-image-video.sh\` to bootstrap it (expected venv at ${engine.venvDefault}).`,{ status: 503, code: 'PIPELINE_MUSIC_RUNTIME_MISSING' },diff --git a/server/services/pipeline/musicGen.test.js b/server/services/pipeline/musicGen.test.jsindex 8d89d449f8..c911f14fdd 100644--- a/server/services/pipeline/musicGen.test.js+++ b/server/services/pipeline/musicGen.test.js@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-import { tmpdir } from 'os';+import { tmpdir, platform as osPlatform, arch as osArch } from 'os';import { join } from 'path';import { rm, readdir } from 'fs/promises';import { writeFileSync, mkdtempSync } from 'fs';@@ -266,6 +266,14 @@ const h = vi.hoisted(() => ({mockWriteOutput: true,musicgenPython: '/fake/venv-musicgen/bin/python3',audioldm2Python: '/fake/venv-audioldm2/bin/python3',+ // isEngineHealthy's import probe: which interpreters it ran, and whether the+ // import succeeded (a half-built venv exits non-zero).+ probeCalls: [],+ probeOk: true,+ // Host identity, so platform-gated engines (MLX MusicGen) behave the same in+ // CI on Linux, on a Windows dev box, and on the Apple Silicon they target.+ osPlatform: 'darwin',+ osArch: 'arm64',}));// Set after the top-level imports resolve; the fileUtils mock reads it through// a getter so the (eagerly-built) PATHS object always reflects the final value.@@ -273,10 +281,27 @@ h.testDir = mkdtempSync(join(tmpdir(), 'musicgen-test-'));const TEST_DIR = h.testDir;const spawnCalls = h.spawnCalls;+// Partial: tmpdir() stays real (the suite writes fake WAVs under it); only the+// host identity is driven by the test.+vi.mock('os', async () => ({+ ...(await vi.importActual('os')),+ platform: () => h.osPlatform,+ arch: () => h.osArch,+}));+vi.mock('child_process', async () => {const actual = await vi.importActual('child_process');return {...actual,+ // isEngineHealthy probes the venv with `python -c <import>`; promisify()+ // wraps this callback form. h.probeOk drives success vs a broken venv.+ execFile: (file, args, opts, cb) => {+ h.probeCalls.push({ file, args });+ const done = typeof opts === 'function' ? opts : cb;+ setImmediate(() => (h.probeOk+ ? done(null, '', '')+ : done(Object.assign(new Error("ModuleNotFoundError: No module named 'torch'"), { code: 1 }))));+ },spawn: (bin, args, _opts) => {h.spawnCalls.push({ bin, args });const listeners = {};@@ -322,7 +347,9 @@ vi.mock('../../lib/pythonSetup.js', async () => {};});-const { generateMusic } = await import('./musicGen.js');+const {+ generateMusic, isEngineHealthy, invalidateEngineHealth, isEnginePlatformSupported, enginePlatformLabel,+} = await import('./musicGen.js');beforeEach(() => {h.spawnCalls.length = 0;@@ -331,6 +358,11 @@ beforeEach(() => {h.mockStdout = 'STAGE:done\nRESULT:{"output":"x","durationSec":12.5,"sampleRate":32000}\n';h.musicgenPython = '/fake/venv-musicgen/bin/python3';h.audioldm2Python = '/fake/venv-audioldm2/bin/python3';+ h.probeCalls.length = 0;+ h.probeOk = true;+ h.osPlatform = 'darwin';+ h.osArch = 'arm64';+ invalidateEngineHealth();});afterEach(async () => {@@ -419,3 +451,121 @@ describe('isEngineReady', () => {expect(isEngineReady('audioldm2')).toBe(false);});});++describe('isEngineHealthy', () => {+ it('reports a half-built venv as unhealthy even though the interpreter exists', async () => {+ // The exact state a killed/failed install leaves behind: `python` is there,+ // the packages are not. isEngineReady says yes; isEngineHealthy must not.+ h.probeOk = false;+ expect(isEngineReady('musicgen')).toBe(true);+ expect(await isEngineHealthy('musicgen')).toBe(false);+ });++ it('reports a fully-installed venv as healthy', async () => {+ expect(await isEngineHealthy('musicgen')).toBe(true);+ expect(h.probeCalls[0]).toMatchObject({ file: '/fake/venv-musicgen/bin/python3' });+ expect(h.probeCalls[0].args[0]).toBe('-c');+ });++ it('skips the probe entirely when no interpreter is resolved', async () => {+ h.audioldm2Python = null;+ expect(await isEngineHealthy('audioldm2')).toBe(false);+ expect(h.probeCalls).toHaveLength(0);+ });++ it('caches the verdict so repeat readiness checks do not respawn python', async () => {+ expect(await isEngineHealthy('musicgen')).toBe(true);+ expect(await isEngineHealthy('musicgen')).toBe(true);+ expect(h.probeCalls).toHaveLength(1);+ });++ it('re-probes with refresh so a repair install is not blocked by a stale verdict', async () => {+ h.probeOk = false;+ expect(await isEngineHealthy('musicgen')).toBe(false);+ // The install just rebuilt the venv — a cached `false` must not stick.+ h.probeOk = true;+ expect(await isEngineHealthy('musicgen', { refresh: true })).toBe(true);+ expect(h.probeCalls).toHaveLength(2);+ });++ it('tracks each engine independently', async () => {+ expect(await isEngineHealthy('musicgen')).toBe(true);+ h.probeOk = false;+ expect(await isEngineHealthy('audioldm2')).toBe(false);+ expect(await isEngineHealthy('musicgen')).toBe(true);+ });+});++describe('ENGINES healthProbe parity', () => {+ it('every engine declares an import probe', () => {+ // A new engine without one silently falls back to "the interpreter file+ // exists", which is the exact check isEngineHealthy was added to replace.+ for (const engine of Object.values(ENGINES)) {+ expect(typeof engine.healthProbe, `${engine.id} healthProbe`).toBe('string');+ expect(engine.healthProbe.length).toBeGreaterThan(0);+ }+ });+});++describe('generateMusic venv-health gate', () => {+ it('returns the install hint instead of spawning into a half-built venv', async () => {+ // The interpreter is present, the packages are not — without the health gate+ // the sidecar spawns and dies with a raw Python ImportError traceback.+ h.probeOk = false;+ await expect(generateMusic({ prompt: 'a calm piano bed', engine: 'musicgen' }))+ .rejects.toMatchObject({ status: 503, code: 'PIPELINE_MUSIC_RUNTIME_MISSING' });+ expect(spawnCalls).toHaveLength(0);+ });++ it('still generates when the venv is healthy', async () => {+ const res = await generateMusic({ prompt: 'a calm piano bed', engine: 'musicgen' });+ expect(res.filename).toMatch(/^music-gen-.*\.wav$/);+ expect(spawnCalls).toHaveLength(1);+ });+});+describe('isEnginePlatformSupported', () => {+ it('treats an engine with no requiresPlatform as portable', () => {+ expect(ENGINES.audioldm2.requiresPlatform).toBeUndefined();+ h.osPlatform = 'win32';+ h.osArch = 'x64';+ expect(isEnginePlatformSupported('audioldm2')).toBe(true);+ expect(enginePlatformLabel('audioldm2')).toBeNull();+ });++ it('allows MusicGen only on Apple Silicon', () => {+ // MLX has no Windows/Linux build, so the setup script skips and exits 0 —+ // which the install route used to report as "installer exited 0 but still+ // not available", indistinguishable from a broken install.+ expect(ENGINES.musicgen.requiresPlatform).toMatchObject({ platform: 'darwin', arch: 'arm64' });+ expect(isEnginePlatformSupported('musicgen')).toBe(true);++ h.osPlatform = 'win32';+ h.osArch = 'x64';+ expect(isEnginePlatformSupported('musicgen')).toBe(false);++ // Intel Mac: right OS, wrong silicon.+ h.osPlatform = 'darwin';+ h.osArch = 'x64';+ expect(isEnginePlatformSupported('musicgen')).toBe(false);+ });++ it('exposes a human-readable requirement for the UI', () => {+ expect(enginePlatformLabel('musicgen')).toContain('Apple Silicon');+ });++ it('never reports an unsupported host as healthy, and never spawns a probe there', async () => {+ h.osPlatform = 'win32';+ h.osArch = 'x64';+ h.probeOk = true;+ expect(await isEngineHealthy('musicgen')).toBe(false);+ expect(h.probeCalls).toHaveLength(0);+ });++ it('refuses to generate on an unsupported host instead of spawning the sidecar', async () => {+ h.osPlatform = 'win32';+ h.osArch = 'x64';+ await expect(generateMusic({ prompt: 'a calm piano bed', engine: 'musicgen' }))+ .rejects.toMatchObject({ status: 503, code: 'PIPELINE_MUSIC_RUNTIME_MISSING' });+ expect(spawnCalls).toHaveLength(0);+ });+});