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

prompt for HuggingFace access when MuScriptor MIDI weights are gated

[._.]/ Adam Eivy362a3f921f64
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 194e3f2395..b56e6056e2 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Fixes
+- **Audio → MIDI transcription now prompts for HuggingFace access instead of dead-ending on a gated-repo traceback.** MuScriptor's model weights turned out to live in a *gated* HuggingFace repo (`MuScriptor/muscriptor-*`), so the first transcription on a fresh install — even right after the runtime auto-installs — 403'd with a raw `GatedRepoError: Access to model … is restricted` traceback the user couldn't act on. The MuScriptor sidecar now runs under the shared `install_hf_error_handler` (the same cause-chain walker the image/video runners use), so a gated download emits a structured `USER_ERROR:gated_repo:<repo>` marker; the server classifies that into a typed `gated_repo` SSE frame (carrying the repo id), and the client opens the same license-accept + token-paste prompt the gated image models use (reusing `HfTokenBanner`): accept the model's license, paste a HuggingFace read token, and the transcription you originally asked for re-runs automatically. Gated-error detection is now shared via `isGatedRepoError`/`extractGatedRepo` in `server/lib/hfErrors.js` (also adopted by the image runner's prose fallback).
+
- **Layered Intelligence no longer silently wedges when pinned to an API-only provider.** After LI became an agent-backed scheduled task (#2322), its reasoning run needs a CLI/TUI coding provider (one with a file-writing harness to emit the `.agent-done` sentinel). Installs that carried an HTTP `api` provider (ollama / LM Studio) through migration 184 hit a dead end: every dispatch failed provider resolution *before* an agent registered, so nothing updated the task's status and it sat pending forever — silently blocking the app's whole improvement slot. Now the LI `buildTaskInput` hook detects an api-only provider up front and **skips** with an actionable reason (surfaced on the Intelligence tab: *"pick a CLI/TUI provider — e.g. the Claude Ollama sample"*), and, as a general safety net, any agent task that fails provider resolution with a **permanent** config error is **blocked** with a `provider-config` reason instead of re-failing on every dispatch.
## Features
diff --git a/client/src/components/install/MidiGatedModal.jsx b/client/src/components/install/MidiGatedModal.jsx
new file mode 100644
index 0000000000..da10273e4a
--- /dev/null
+++ b/client/src/components/install/MidiGatedModal.jsx
@@ -0,0 +1,43 @@
+/**
+ * Gated-repo gate for MuScriptor (audio → MIDI) transcription. MuScriptor's
+ * model weights live in a gated HuggingFace repo (MuScriptor/muscriptor-*), so
+ * a first transcribe with no accepted license / token 403s. useMidiTranscription
+ * opens this when the job streams an `HF_GATED` error frame — the user accepts
+ * the license and pastes a read token (reusing HfTokenBanner, the same
+ * paste-and-save flow the gated image models use), then `onSaved` re-runs the
+ * captured transcription.
+ */
+
+import { KeyRound } from 'lucide-react';
+import Modal from '../ui/Modal';
+import HfTokenBanner from '../imageGen/HfTokenBanner';
+
+export default function MidiGatedModal({ open, repo, onSaved, onClose }) {
+ const licenseUrl = repo ? `https://huggingface.co/${repo}` : 'https://huggingface.co';
+ return (
+ <Modal
+ open={open}
+ onClose={onClose}
+ size="md"
+ align="top"
+ zIndexClassName="z-[9999]"
+ ariaLabelledBy="midi-gated-title"
+ backdropClassName="bg-black/70 backdrop-blur-sm"
+ panelClassName="bg-port-card rounded-xl border border-port-border shadow-2xl overflow-hidden"
+ >
+ <div className="flex items-center gap-2.5 px-5 py-4 border-b border-port-border">
+ <KeyRound size={18} className="text-port-warning" />
+ <h2 id="midi-gated-title" className="text-sm font-semibold text-white">
+ HuggingFace access required
+ </h2>
+ </div>
+ <div className="px-5 py-4">
+ <HfTokenBanner
+ modelLabel={repo || 'MuScriptor'}
+ licenseUrl={licenseUrl}
+ onSaved={onSaved}
+ />
+ </div>
+ </Modal>
+ );
+}
diff --git a/client/src/components/songs/ReferenceAnalysis.jsx b/client/src/components/songs/ReferenceAnalysis.jsx
index 41fa541780..f576251525 100644
--- a/client/src/components/songs/ReferenceAnalysis.jsx
+++ b/client/src/components/songs/ReferenceAnalysis.jsx
@@ -37,6 +37,7 @@ import {
import useReferenceAudioImport from '../../hooks/useReferenceAudioImport.js';
import useMidiTranscription from '../../hooks/useMidiTranscription.js';
import MidiInstallModal from '../install/MidiInstallModal.jsx';
+import MidiGatedModal from '../install/MidiGatedModal.jsx';
import { startMemoRecording, arrayBufferToBase64 } from '../../lib/audioRecorder';
import { proposeSegmentScore, proposeStackedSegmentScore, diffScoreBars, PITCH_CLASS_NAMES } from '../../lib/referenceAnalysis';
import { scoreHasMusic, parseScore } from '../../lib/scoreNotation';
@@ -181,6 +182,7 @@ export function ReferenceAudioAttach({ reference, onUpdate }) {
return (
<div className="flex flex-wrap items-center gap-2">
<MidiInstallModal {...midiJob.installGate} />
+ <MidiGatedModal {...midiJob.gatedGate} />
<span className="flex items-center gap-1.5 text-xs text-port-success">
<AudioLines size={14} /> Audio attached
</span>
diff --git a/client/src/hooks/useMidiTranscription.js b/client/src/hooks/useMidiTranscription.js
index 4ae6130219..14f9e1b969 100644
--- a/client/src/hooks/useMidiTranscription.js
+++ b/client/src/hooks/useMidiTranscription.js
@@ -35,6 +35,13 @@ export default function useMidiTranscription({ startRequest, eventsUrl, cancelRe
// install reported success, fall back to the hint toast instead of looping
// the modal open.
const installAttemptedRef = useRef(false);
+ // Gated-repo gate (MuScriptor's weights live in a gated HuggingFace repo). A
+ // transcribe with no accepted license / token streams a `gated_repo` error
+ // frame; we open a license + token-entry modal (mirroring the image-model
+ // gated flow) instead of dead-ending on a raw-traceback toast, then re-run
+ // the captured transcription once a token is saved. Non-null = open for that
+ // target; `{ context, repo }`.
+ const [gatedContext, setGatedContext] = useState(null);
const sse = useSseProgress(job ? eventsUrl(job.jobId) : null);
const latest = sse.latest;
const stage = latest?.stage ?? null;
@@ -45,7 +52,13 @@ export default function useMidiTranscription({ startRequest, eventsUrl, cancelRe
onComplete?.(latest, job.context);
setJob(null);
} else if (latest.type === 'error') {
- toast.error(latest.error || 'MIDI transcription failed');
+ // Gated-repo download failure — open the license + token prompt instead
+ // of toasting a raw HuggingFace traceback the user can't act on.
+ if (latest.code === 'gated_repo') {
+ setGatedContext({ context: job.context, repo: latest.repo || null });
+ } else {
+ toast.error(latest.error || 'MIDI transcription failed');
+ }
setJob(null);
} else if (latest.type === 'canceled' || latest.type === 'cancelled') {
toast.info('MIDI transcription cancelled');
@@ -90,7 +103,7 @@ export default function useMidiTranscription({ startRequest, eventsUrl, cancelRe
};
const start = (context) => {
- if (job || pending || installContext !== null) return;
+ if (job || pending || installContext !== null || gatedContext !== null) return;
kickoff(context);
};
@@ -116,8 +129,31 @@ export default function useMidiTranscription({ startRequest, eventsUrl, cancelRe
},
};
+ // Gated-repo modal wiring — spread onto <MidiGatedModal>. Saving a token
+ // re-fires the captured transcription (the license may still be unaccepted,
+ // in which case it 403s and the modal reopens — each reopen needs a fresh
+ // Save click, so there's no runaway loop). Closing clears the target.
+ const gatedGate = {
+ open: gatedContext !== null,
+ repo: gatedContext?.repo ?? null,
+ onSaved: () => {
+ const ctx = gatedContext?.context ?? null;
+ setGatedContext(null);
+ if (ctx !== null) kickoff(ctx);
+ },
+ onClose: () => setGatedContext(null),
+ };
+
// `context` exposes the in-flight job's captured target so a caller can
// gate per-target UI ("is the active job for THIS record?") without
// mirroring the value in its own state.
- return { active: pending || !!job || installContext !== null, stage, context: job?.context ?? null, start, cancel, installGate };
+ return {
+ active: pending || !!job || installContext !== null || gatedContext !== null,
+ stage,
+ context: job?.context ?? null,
+ start,
+ cancel,
+ installGate,
+ gatedGate,
+ };
}
diff --git a/client/src/hooks/useMidiTranscription.test.jsx b/client/src/hooks/useMidiTranscription.test.jsx
index ee93a94b0f..1377bf5d35 100644
--- a/client/src/hooks/useMidiTranscription.test.jsx
+++ b/client/src/hooks/useMidiTranscription.test.jsx
@@ -5,8 +5,11 @@ import { renderHook, act } from '@testing-library/react';
// in jsdom and we can assert which toast (if any) fired.
const toast = vi.hoisted(() => ({ error: vi.fn(), info: vi.fn(), success: vi.fn() }));
vi.mock('../components/ui/Toast', () => ({ default: toast }));
+// Controllable SSE seam — tests mutate `sseState.latest` then rerender to feed
+// the hook a frame. Defaults to no frame so the install-gate tests are unaffected.
+const sseState = vi.hoisted(() => ({ latest: null, closed: false }));
vi.mock('./useSseProgress.js', () => ({
- useSseProgress: () => ({ latest: null, closed: false }),
+ useSseProgress: () => sseState,
isTerminalSseFrame: () => false,
}));
@@ -26,6 +29,8 @@ describe('useMidiTranscription — first-use install gate', () => {
beforeEach(() => {
toast.error.mockClear();
toast.info.mockClear();
+ sseState.latest = null;
+ sseState.closed = false;
startRequest = vi.fn();
});
@@ -86,3 +91,74 @@ describe('useMidiTranscription — first-use install gate', () => {
expect(toast.error).toHaveBeenCalledTimes(1);
});
});
+
+describe('useMidiTranscription — gated-repo gate', () => {
+ let startRequest;
+ const makeHook = () => renderHook(() => useMidiTranscription({
+ startRequest,
+ eventsUrl: (id) => `/e/${id}`,
+ cancelRequest: vi.fn().mockResolvedValue({}),
+ onComplete: vi.fn(),
+ }));
+
+ beforeEach(() => {
+ toast.error.mockClear();
+ sseState.latest = null;
+ sseState.closed = false;
+ startRequest = vi.fn().mockResolvedValue({ jobId: 'job-1' });
+ });
+
+ const gatedFrame = { type: 'error', code: 'gated_repo', repo: 'MuScriptor/muscriptor-medium', error: 'gated' };
+
+ it('opens the token prompt (no error toast) on a gated_repo error frame', async () => {
+ const { result, rerender } = makeHook();
+ await act(async () => { result.current.start('song.wav'); });
+
+ sseState.latest = gatedFrame;
+ await act(async () => { rerender(); });
+
+ expect(result.current.gatedGate.open).toBe(true);
+ expect(result.current.gatedGate.repo).toBe('MuScriptor/muscriptor-medium');
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+
+ it('re-runs the captured transcription once a token is saved', async () => {
+ const { result, rerender } = makeHook();
+ await act(async () => { result.current.start('song.wav'); });
+
+ sseState.latest = gatedFrame;
+ await act(async () => { rerender(); });
+ expect(result.current.gatedGate.open).toBe(true);
+
+ // A fresh kickoff must see no in-flight frame, else it would re-trip the gate.
+ sseState.latest = null;
+ await act(async () => { result.current.gatedGate.onSaved(); });
+ expect(result.current.gatedGate.open).toBe(false);
+ expect(startRequest).toHaveBeenNthCalledWith(2, 'song.wav');
+ expect(result.current.active).toBe(true);
+ });
+
+ it('closing the prompt clears the target without retrying', async () => {
+ const { result, rerender } = makeHook();
+ await act(async () => { result.current.start('song.wav'); });
+
+ sseState.latest = gatedFrame;
+ await act(async () => { rerender(); });
+ expect(result.current.gatedGate.open).toBe(true);
+
+ await act(async () => { result.current.gatedGate.onClose(); });
+ expect(result.current.gatedGate.open).toBe(false);
+ expect(startRequest).toHaveBeenCalledTimes(1);
+ });
+
+ it('a non-gated error frame still toasts', async () => {
+ const { result, rerender } = makeHook();
+ await act(async () => { result.current.start('song.wav'); });
+
+ sseState.latest = { type: 'error', error: 'boom' };
+ await act(async () => { rerender(); });
+
+ expect(result.current.gatedGate.open).toBe(false);
+ expect(toast.error).toHaveBeenCalledWith('boom');
+ });
+});
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index e14424fdaa..13b4755e9c 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -23,6 +23,7 @@ import {
} from '../services/apiMusicVideo.js';
import useMidiTranscription from '../hooks/useMidiTranscription.js';
import MidiInstallModal from '../components/install/MidiInstallModal.jsx';
+import MidiGatedModal from '../components/install/MidiGatedModal.jsx';
import { generateImage } from '../services/apiSystem.js';
import { generateVideo } from '../services/apiImageVideo.js';
import { listTracks, trackAudioUrl } from '../services/apiTracks.js';
@@ -563,6 +564,7 @@ export default function MusicVideo() {
return (
<div className="space-y-4">
<MidiInstallModal {...midiJob.installGate} />
+ <MidiGatedModal {...midiJob.gatedGate} />
<PageHeader icon={Film} title="Music Video" subtitle="Director-controlled, beat-aware music videos" />
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
diff --git a/scripts/transcribe_muscriptor.py b/scripts/transcribe_muscriptor.py
index 07dfca7256..6f8f32c3d6 100644
--- a/scripts/transcribe_muscriptor.py
+++ b/scripts/transcribe_muscriptor.py
@@ -25,6 +25,18 @@ import argparse
import json
import os
import sys
+from pathlib import Path
+
+# Share the canonical HuggingFace error → USER_ERROR: translation with the
+# image/video runners. MuScriptor's weights live in a *gated* HF repo, so a
+# first download without an accepted license raises GatedRepoError; the
+# decorator walks the cause chain and emits a structured
+# `USER_ERROR:gated_repo:<repo>` line (which the server classifies deep-linkably)
+# instead of a raw traceback the JS side has to prose-match. `_runner_common`
+# imports only stdlib at module load (torch/huggingface_hub are lazy), so this
+# is safe from the muscriptor venv.
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from _runner_common import install_hf_error_handler # noqa: E402
def log_stage(name, detail=""):
@@ -70,6 +82,7 @@ def _load_model(TranscriptionModel, size):
return TranscriptionModel.load_model()
+@install_hf_error_handler
def main():
parser = argparse.ArgumentParser(description="PortOS MuScriptor runner (audio → MIDI)")
parser.add_argument("--audio", required=True, help="Input audio path")
diff --git a/server/lib/hfErrors.js b/server/lib/hfErrors.js
index 5395bb99c1..9cf4419baf 100644
--- a/server/lib/hfErrors.js
+++ b/server/lib/hfErrors.js
@@ -22,3 +22,19 @@ export function extractGatedRepo(text = '') {
const match = String(text).match(GATED_REPO_RE);
return match ? match[1].replace(/\.git$/, '') : null;
}
+
+// Classifies a huggingface_hub failure as a *gated-access* error (a 403 on a
+// restricted repo the user hasn't been granted) — distinct from a benign
+// download hiccup. Shared by the image runner's prose fallback
+// (server/services/imageGen/local.js) and the MIDI transcription classifier
+// (server/services/audioMidiTranscription.js). Deliberately narrow (no bare
+// "403 Client Error", which also fires on unrelated auth failures) so
+// extractGatedRepo is only invoked once the error is genuinely gated. The LoRA
+// trainer (server/services/loraTraining/failure.js) keeps its own HF_AUTH_RE
+// because it also matches bare "401 Client Error", which this regex omits to
+// stay false-positive-free for the download paths.
+export const GATED_ERROR_RE = /GatedRepoError|Access to (?:model )?[\w.@/-]+ is restricted|Cannot access gated repo|Repo.*is gated/i;
+
+export function isGatedRepoError(text = '') {
+ return GATED_ERROR_RE.test(String(text));
+}
diff --git a/server/lib/hfErrors.test.js b/server/lib/hfErrors.test.js
index 9b337736e5..b209de5fd4 100644
--- a/server/lib/hfErrors.test.js
+++ b/server/lib/hfErrors.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { extractGatedRepo } from './hfErrors.js';
+import { extractGatedRepo, isGatedRepoError } from './hfErrors.js';
describe('extractGatedRepo', () => {
it('pulls the repo from the GatedRepoError prose', () => {
@@ -26,3 +26,19 @@ describe('extractGatedRepo', () => {
expect(extractGatedRepo(null)).toBeNull();
});
});
+
+describe('isGatedRepoError', () => {
+ it('matches the huggingface_hub gated-access shapes', () => {
+ expect(isGatedRepoError('huggingface_hub.errors.GatedRepoError: 403 Client Error.')).toBe(true);
+ expect(isGatedRepoError('Cannot access gated repo for url https://huggingface.co/MuScriptor/muscriptor-medium/resolve/main/model.safetensors')).toBe(true);
+ expect(isGatedRepoError('Access to model MuScriptor/muscriptor-medium is restricted and you are not in the authorized list.')).toBe(true);
+ expect(isGatedRepoError('Repo model foo/bar is gated. You must be authenticated to access it.')).toBe(true);
+ });
+
+ it('does not fire on unrelated failures or non-strings', () => {
+ expect(isGatedRepoError('ConnectionError: failed to reach huggingface.co')).toBe(false);
+ expect(isGatedRepoError('exit 1')).toBe(false);
+ expect(isGatedRepoError()).toBe(false);
+ expect(isGatedRepoError(null)).toBe(false);
+ });
+});
diff --git a/server/services/audioMidiTranscription.js b/server/services/audioMidiTranscription.js
index 10af809b38..c8c0fdf716 100644
--- a/server/services/audioMidiTranscription.js
+++ b/server/services/audioMidiTranscription.js
@@ -31,6 +31,7 @@ import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '
import { killWithEscalation } from '../lib/killWithEscalation.js';
import { safeChildProcessEnv } from '../lib/processEnv.js';
import { hfTokenEnv } from '../lib/hfToken.js';
+import { isGatedRepoError, extractGatedRepo } from '../lib/hfErrors.js';
import { resolveMuscriptorPython, isMuscriptorRuntimeReady, MUSCRIPTOR_VENV_DEFAULT } from '../lib/pythonSetup.js';
import { runSidecarProcess, parseSidecarResult } from '../lib/sidecarProcess.js';
import { ServerError } from '../lib/errorHandler.js';
@@ -49,6 +50,41 @@ export const DEFAULT_MUSCRIPTOR_MODEL = 'medium';
export const resolveMuscriptorModel = (model) =>
(MUSCRIPTOR_MODELS.includes(model) ? model : DEFAULT_MUSCRIPTOR_MODEL);
+// The sidecar's `@install_hf_error_handler` (scripts/_runner_common.py) emits a
+// structured `USER_ERROR:gated_repo:<repo>` line on a gated download — prefer it
+// over prose-matching a stderr tail that sidecarProcess has already truncated to
+// the last few lines. The repo group is optional (older/marker-less output).
+const GATED_MARKER_RE = /USER_ERROR:gated_repo(?::(\S+))?/;
+
+/**
+ * Map a failed sidecar reason onto the SSE error frame's typed fields. Pure —
+ * unit-tested without spawning Python.
+ *
+ * MuScriptor's weights live in a *gated* HuggingFace repo
+ * (`MuScriptor/muscriptor-*`), so the first download with no accepted license
+ * (or no token) 403s. Surface that as a typed `gated_repo` frame carrying the
+ * repo so the client can deep-link the license page + token entry (reusing the
+ * same `gated_repo` code the image runner emits) instead of dead-ending on a
+ * raw traceback toast. Detection prefers the sidecar's structured marker and
+ * falls back to the gated-error prose so a marker-less sidecar still classifies.
+ * Any other failure passes through as a plain error string.
+ */
+export function classifyMidiFailure(reason, model) {
+ const text = String(reason || '');
+ const marker = text.match(GATED_MARKER_RE);
+ if (marker || isGatedRepoError(text)) {
+ const repo = (marker && marker[1]) || extractGatedRepo(text) || `MuScriptor/muscriptor-${resolveMuscriptorModel(model)}`;
+ return {
+ code: 'gated_repo',
+ repo,
+ error:
+ `Access to ${repo} is gated on HuggingFace. Accept the license at `
+ + `https://huggingface.co/${repo} and add your HuggingFace token in Image Gen settings, then retry.`,
+ };
+ }
+ return { error: text || 'MIDI transcription failed' };
+}
+
const MUSCRIPTOR_INSTALL_HINT =
`MuScriptor runtime not found. Run \`INSTALL_MUSCRIPTOR=1 bash scripts/setup-image-video.sh\` `
+ `to bootstrap it (expected venv at ${MUSCRIPTOR_VENV_DEFAULT}).`;
@@ -130,8 +166,10 @@ export async function startMidiTranscription({ audioPath, outputName = 'transcri
try {
const { bin, args } = buildMuscriptorArgs({ pythonPath, audioPath, outputPath: tempOut, model: resolvedModel });
broadcastSse(job, { type: 'progress', stage: 'starting' });
- // Weights are ungated, but pass the HF token through when the user has
- // one so the first download doesn't hit anonymous rate limits.
+ // MuScriptor's weights live in a gated HF repo (MuScriptor/muscriptor-*),
+ // so pass the user's HF token through for the first download to
+ // authenticate. Without an accepted license the sidecar 403s and we
+ // classify that into a typed HF_GATED frame below.
const env = safeChildProcessEnv(await hfTokenEnv());
// A cancel can land while the env was resolving (no child to SIGTERM yet)
// — honor the flag before spawning anything.
@@ -165,7 +203,12 @@ export async function startMidiTranscription({ audioPath, outputName = 'transcri
const parsed = result.ok ? parseSidecarResult(result.stdout) : null;
const wroteFile = (statSync(tempOut, { throwIfNoEntry: false })?.size ?? 0) > 0;
if (!result.ok || !parsed || !wroteFile) {
- throw new Error(!result.ok ? result.reason : (!wroteFile ? 'sidecar wrote no MIDI' : 'sidecar returned no result'));
+ const reason = !result.ok ? result.reason : (!wroteFile ? 'sidecar wrote no MIDI' : 'sidecar returned no result');
+ const failure = classifyMidiFailure(reason, resolvedModel);
+ const err = new Error(failure.error);
+ if (failure.code) err.code = failure.code;
+ if (failure.repo) err.repo = failure.repo;
+ throw err;
}
broadcastSse(job, { type: 'progress', stage: 'importing' });
@@ -187,7 +230,12 @@ export async function startMidiTranscription({ audioPath, outputName = 'transcri
broadcastSse(job, { type: 'complete', filename, model: resolvedModel, ...extra });
} catch (err) {
console.error(`❌ MIDI transcription ${shortId(jobId)} failed: ${err?.message || err}`);
- broadcastSse(job, { type: 'error', error: err?.message || String(err) });
+ // Carry the typed gated-repo fields (code/repo) through to the client so
+ // it can open the license + token prompt; a plain failure ships as-is.
+ const frame = { type: 'error', error: err?.message || String(err) };
+ if (err?.code) frame.code = err.code;
+ if (err?.repo) frame.repo = err.repo;
+ broadcastSse(job, frame);
} finally {
job.settled = true;
await unlink(tempOut).catch(() => {});
diff --git a/server/services/audioMidiTranscription.test.js b/server/services/audioMidiTranscription.test.js
index 529175aa5c..7c712967ed 100644
--- a/server/services/audioMidiTranscription.test.js
+++ b/server/services/audioMidiTranscription.test.js
@@ -5,6 +5,7 @@ import {
resolveMuscriptorModel,
buildMuscriptorArgs,
cancelMidiTranscription,
+ classifyMidiFailure,
} from './audioMidiTranscription.js';
describe('resolveMuscriptorModel', () => {
@@ -51,3 +52,42 @@ describe('cancelMidiTranscription', () => {
expect(cancelMidiTranscription('nope')).toBe(false);
});
});
+
+describe('classifyMidiFailure', () => {
+ it('reads the sidecar structured USER_ERROR:gated_repo marker for the repo', () => {
+ const reason = 'STAGE:load-model:medium | USER_ERROR:gated_repo:MuScriptor/muscriptor-medium | '
+ + '❌ Access to MuScriptor/muscriptor-medium is restricted. Visit https://huggingface.co/... to request access';
+ const result = classifyMidiFailure(reason, 'medium');
+ expect(result.code).toBe('gated_repo');
+ expect(result.repo).toBe('MuScriptor/muscriptor-medium');
+ expect(result.error).toContain('https://huggingface.co/MuScriptor/muscriptor-medium');
+ });
+
+ it('flags a gated-repo 403 from raw prose (marker-less sidecar) with the repo pulled from the error', () => {
+ const reason = 'huggingface_hub.errors.GatedRepoError: 403 Client Error. '
+ + 'Cannot access gated repo for url https://huggingface.co/MuScriptor/muscriptor-medium/resolve/main/model.safetensors. '
+ + 'Access to model MuScriptor/muscriptor-medium is restricted and you are not in the authorized list.';
+ const result = classifyMidiFailure(reason, 'medium');
+ expect(result.code).toBe('gated_repo');
+ expect(result.repo).toBe('MuScriptor/muscriptor-medium');
+ expect(result.error).toContain('https://huggingface.co/MuScriptor/muscriptor-medium');
+ expect(result.error).toContain('HuggingFace token');
+ });
+
+ it('falls back to the model-derived repo when the error omits it', () => {
+ const result = classifyMidiFailure('Cannot access gated repo', 'large');
+ expect(result.code).toBe('gated_repo');
+ expect(result.repo).toBe('MuScriptor/muscriptor-large');
+ });
+
+ it('passes non-gated failures through as a plain error with no code', () => {
+ const result = classifyMidiFailure('sidecar wrote no MIDI', 'medium');
+ expect(result.code).toBeUndefined();
+ expect(result.repo).toBeUndefined();
+ expect(result.error).toBe('sidecar wrote no MIDI');
+ });
+
+ it('supplies a default message for an empty reason', () => {
+ expect(classifyMidiFailure('', 'medium').error).toBe('MIDI transcription failed');
+ });
+});
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 6bc7fb11bf..933f0e1f28 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -26,7 +26,7 @@ import { imageGenEvents } from '../imageGenEvents.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';
import { resolveFlux2Python, FLUX2_VENV_DEFAULT } from '../../lib/pythonSetup.js';
import { hfTokenEnv } from '../../lib/hfToken.js';
-import { extractGatedRepo } from '../../lib/hfErrors.js';
+import { extractGatedRepo, isGatedRepoError } from '../../lib/hfErrors.js';
import { safeChildProcessEnv } from '../../lib/processEnv.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { IMAGE_GEN_MODE } from './modes.js';
@@ -774,7 +774,7 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
// (404, network error) that merely prints a HF URL must NOT be turned
// into a misleading license-request flow. Extract the repo for the link
// only after the gated signal is confirmed.
- const hasGatedError = /GatedRepoError|Access to model .* is restricted|Cannot access gated repo/i.test(gatedText);
+ const hasGatedError = isGatedRepoError(gatedText);
if (hasGatedError) {
userKind = 'gated_repo';
userRepo = extractGatedRepo(gatedText);