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
add MuScriptor audio-to-MIDI transcription for rounds references and music video tracks
[._.]/ Adam Eivy293a03b38934
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex cdb20a38db..0b5125b75d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -62,3 +62,4 @@- **[issue-2350] Tier 2 (schema/type) now performs a real deterministic same-provider request/response correction instead of falling straight through.** Carved out of #2342: at the runner layer a schema/type failure never arrives as a provider *error* (the provider returns HTTP 200), so a malformed response can only be recognized against the caller's declared shape. `runPromptThroughProvider` gained an optional `responseSchema` (a Zod-style schema or a bare predicate) — and an optional `repair` normalizer callback — so a caller can now declare the response it expects. When the response fails that schema the runner attempts a **bounded deterministic JSON coercion in place** (strips markdown fences / prose and pulls the first schema-matching block, reusing `jsonExtract.extractJson`); if the shape still can't be recovered it **re-requests the same provider once with a schema-strengthened prompt** before falling through to the Tier-3 fallback provider and the Tier-4 investigation task. Every recovery is reconciled through the existing `noteFallbackStarted`/`noteFallbackHandled`/`noteFallbackFailed` lifecycle exactly like Tiers 1 and 3, so a Tier-2 recovery leaves **zero** investigation tasks; the recovering path is surfaced on the result (`fixTier: 2`/`fixStrategy: 'schema/type'`, plus `coercedResponse: true` for the pure in-place coercion) and in the single-line log (`🧩 Tier 2 (schema/type) retry …`). A schema/type failure never benches the healthy provider (it's response-specific, not an outage). The Messages triage caller declares its expected JSON-array shape as the first adopter.- **Layered Intelligence loop now supports every provider type.** The per-app AI-provider picker previously listed only `cli` providers, while the reasoning call went through the api-only `callProviderAISimple` — so a selected CLI provider failed at runtime with "requires an API-based provider," and API/TUI providers (Ollama, LM Studio, Claude/Codex/OpenCode TUI, etc.) never appeared at all. The reasoning call now routes through the unified `runPromptThroughProvider`, which dispatches on `provider.type`, and the picker lists all enabled `cli`/`api`/`tui` providers. CLI/TUI spawns run in the app's repo (`cwd`).- **A "Run now" of Layered Intelligence now tells you what actually happened.** Because the loop is handler-backed — it files one tracker issue rather than spawning a visible agent — a run that filed nothing gave no usable signal: the on-demand toast collapsed every non-filed outcome (reasoning model returned unparseable JSON, a duplicate/near-duplicate was suppressed, it parked on a blocking issue, no AI provider was configured, Jira wasn't set up, the tracker read failed) into a blanket "nothing to do right now," and on mobile that transient toast was easy to miss entirely. The handler now threads the real terminal reason through the on-demand feedback (so the toast reads e.g. "the reasoning model returned no usable JSON — try a non-reasoning model" or "paused on a blocking issue"), and every run persists its outcome (`lastRunAt` / action / reason / filed ref) so Edit App → Intelligence shows a durable **Last run** status line you can check any time. This is what made a reasoning-style local model (which often emits thinking text with no parseable JSON) look like a queued-but-not-running task with no explanation.+- **Rounds and Music Video can now turn a reference audio file into MIDI locally via MuScriptor.** MuScriptor (github.com/muscriptor/muscriptor) is a multi-instrument audio → MIDI transcription model that runs in an opt-in venv (`INSTALL_MUSCRIPTOR=1 bash scripts/setup-image-video.sh`, weights auto-download from HuggingFace on first use; small/medium/large tiers). A new shared service (`server/services/audioMidiTranscription.js` + the `scripts/transcribe_muscriptor.py` sidecar, same STAGE:/RESULT: wire protocol as the music-gen sidecars) exposes the kickoff/SSE/cancel job shape in both features: a Rounds reference with attached audio gains a **Transcribe MIDI** control (the resulting `.mid` lands as `references[].midiFilename` on Save, cleared with the audio like segments), and a Music Video project gains a **MIDI** toolbar button + download link (`project.midiTranscription` is persisted server-side on completion and invalidated when the audio source changes, exactly like `audioAnalysis`). When the venv isn't provisioned the kickoff 503s with the install hint instead of a bare spawn error.diff --git a/client/src/components/songs/ReferenceAnalysis.jsx b/client/src/components/songs/ReferenceAnalysis.jsxindex 477034db90..b1b13ee5da 100644--- a/client/src/components/songs/ReferenceAnalysis.jsx+++ b/client/src/components/songs/ReferenceAnalysis.jsx@@ -24,12 +24,18 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import {- ArrowLeft, AudioLines, Download, Flag, FlagOff, Layers, Loader2, Mic, Play, Plus, Square, Trash2, Upload, Wand2, X,+ ArrowLeft, AudioLines, Download, Flag, FlagOff, Layers, Loader2, Mic, Music, Play, Plus, Square, Trash2, Upload, Wand2, X,} from 'lucide-react';import toast from '../ui/Toast';import ScoreSheet from './ScoreSheet.jsx';import { uploadFile, getUploadUrl } from '../../services/api';+import {+ transcribeReferenceMidi,+ referenceMidiTranscriptionEventsUrl,+ cancelReferenceMidiTranscription,+} from '../../services/apiRounds.js';import useReferenceAudioImport from '../../hooks/useReferenceAudioImport.js';+import useMidiTranscription from '../../hooks/useMidiTranscription.js';import { startMemoRecording, arrayBufferToBase64 } from '../../lib/audioRecorder';import { proposeSegmentScore, proposeStackedSegmentScore, diffScoreBars, PITCH_CLASS_NAMES } from '../../lib/referenceAnalysis';import { scoreHasMusic, parseScore } from '../../lib/scoreNotation';@@ -43,6 +49,16 @@ const MAX_AUDIO_BYTES = 35 * 1024 * 1024;// disable adding more client-side; the server enforces the real bounds.const REF_SEGMENTS_MAX = 24;+// Human labels for the MuScriptor sidecar's STAGE names (SSE progress frames).+const MIDI_STAGE_LABELS = {+ starting: 'Starting…',+ 'import-runtime': 'Loading runtime…',+ 'load-model': 'Loading model…',+ transcribe: 'Transcribing…',+ 'write-midi': 'Writing MIDI…',+ importing: 'Saving…',+};+const msToSec = (ms) => (Math.max(0, ms) / 1000).toFixed(1);const secToMs = (raw) => {const n = Number(raw);@@ -92,6 +108,19 @@ export function ReferenceAudioAttach({ reference, onUpdate }) {onComplete: (filename) => { setUrl(''); onUpdate('audioFilename', filename); },});+ // Audio → MIDI transcription (MuScriptor) — turn the attached audio into a+ // .mid. Same explicit-save model as the other reference fields: the returned+ // uploads filename lands on the draft; the user Saves to keep it.+ const midiJob = useMidiTranscription({+ startRequest: (filename) => transcribeReferenceMidi(filename, undefined, { silent: true }),+ eventsUrl: referenceMidiTranscriptionEventsUrl,+ cancelRequest: cancelReferenceMidiTranscription,+ onComplete: ({ filename }) => {+ onUpdate('midiFilename', filename);+ toast.success('MIDI transcribed — Save the song to keep it');+ },+ });+// Never leave the mic open on unmount (deferred-work cleanup rule).useEffect(() => () => { handleRef.current?.cancel(); }, []);@@ -150,12 +179,50 @@ export function ReferenceAudioAttach({ reference, onUpdate }) {<AudioLines size={14} /> Audio attached</span><audio controls preload="none" src={getUploadUrl(reference.audioFilename)} className="h-8 max-w-[180px]" />+ {reference.midiFilename ? (+ <>+ <a+ href={getUploadUrl(reference.midiFilename)}+ download+ className="flex items-center gap-1 px-2 py-1 text-xs rounded-lg border border-port-border text-port-accent hover:bg-port-border/50"+ title="Download the transcribed MIDI file"+ >+ <Music size={13} /> MIDI+ </a>+ <button+ type="button"+ onClick={() => onUpdate('midiFilename', '')}+ title="Remove the MIDI transcription"+ className="flex items-center gap-1 px-1.5 py-1 text-xs rounded-lg border border-port-border text-gray-400 hover:text-port-error"+ >+ <X size={13} />+ </button>+ </>+ ) : midiJob.active ? (+ <span className="flex items-center gap-1.5 px-2 py-1 text-xs rounded-lg border border-port-border text-gray-300">+ <Loader2 size={13} className="animate-spin" /> {MIDI_STAGE_LABELS[midiJob.stage] || 'Transcribing…'}+ <button type="button" onClick={midiJob.cancel} title="Cancel MIDI transcription" className="ml-1 text-gray-400 hover:text-port-error">+ <X size={13} />+ </button>+ </span>+ ) : (+ <button+ type="button"+ onClick={() => midiJob.start(reference.audioFilename)}+ title="Transcribe this audio to MIDI with MuScriptor (local, needs INSTALL_MUSCRIPTOR=1)"+ className="flex items-center gap-1 px-2 py-1 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50"+ >+ <Music size={13} /> Transcribe MIDI+ </button>+ )}<buttontype="button"onClick={() => {- // Segments are offsets into THIS audio — clear them with it so- // stale ranges can't resurrect against a different recording.+ // Segments are offsets into THIS audio — and the MIDI was+ // transcribed from it — clear them with it so stale artifacts+ // can't resurrect against a different recording.onUpdate('segments', []);+ onUpdate('midiFilename', '');onUpdate('audioFilename', '');}}className="flex items-center gap-1 px-2 py-1 text-xs rounded-lg border border-port-border text-gray-400 hover:text-port-error"diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 257168e7e4..3d86c0a0a7 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -153,3 +153,4 @@ grep -i "what you want to do" client/src/hooks/README.md| `useYoutubeTrackImport` | One YouTube-audio-import job slot (#1945): start/cancel + SSE progress + terminal-frame handling via `POST /api/tracks/import/youtube`. Returns `{ active, percent, start(url, context), cancel }`; `onComplete(track, context)` fires with the finished Track. Call once per UI surface that can independently kick off an import — a shared slot would let one surface's kickoff orphan another's in-flight job. | Any picker that lets a user paste a YouTube URL to create a Track (Music Video's create form and track-change row). || `useVideoDownload` | One full-video-download job slot (#1946): start/cancel + SSE progress + terminal-frame handling via `POST /api/devtools/video-download`. Returns `{ active, percent, stage, start(url), cancel }`; `onComplete(video)` fires with the finished video-history entry. | The Dev Tools Video Downloader page. || `useReferenceAudioImport` | One round reference-audio-import job slot (#2120): start/cancel + SSE progress + terminal-frame handling via `POST /api/rounds/reference-audio/import`. Returns `{ active, percent, stage, start(url, context), cancel }`; `onComplete(filename, context)` fires with the uploads-dir filename to persist on the reference. Call once per surface that can independently kick off a download. | The reference-audio attach controls (`ReferenceAudioAttach`) — the "Download from URL" convenience. |+| `useMidiTranscription` | One audio → MIDI transcription job slot (MuScriptor): start/cancel + SSE stage progress + terminal-frame handling, generic over the Rounds and Music Video API surfaces (pass `startRequest`/`eventsUrl`/`cancelRequest`). Returns `{ active, stage, context, start(context), cancel }` (`context` is the in-flight job's captured target, for per-target UI gates); `onComplete(frame, context)` fires with the terminal frame (`filename`, `model`, any server-merged extras). | The Rounds reference "Transcribe MIDI" control and the Music Video MIDI button. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex b80ad37b60..0f1d3817a3 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -48,6 +48,7 @@ export { default as useUniverseAction } from './useUniverseAction.js';export { default as useVideoDownload } from './useVideoDownload.js';export { default as useYoutubeTrackImport } from './useYoutubeTrackImport.js';export { default as useReferenceAudioImport } from './useReferenceAudioImport.js';+export { default as useMidiTranscription } from './useMidiTranscription.js';// === Mixed (both default and named) — surface both ===export { default as useAsyncAction } from './useAsyncAction.js';diff --git a/client/src/hooks/useMidiTranscription.js b/client/src/hooks/useMidiTranscription.jsnew file mode 100644index 0000000000..ae2d60d7dd--- /dev/null+++ b/client/src/hooks/useMidiTranscription.js@@ -0,0 +1,72 @@+import { useEffect, useState } from 'react';+import toast from '../components/ui/Toast';+import { useSseProgress, isTerminalSseFrame } from './useSseProgress.js';++/**+ * One audio → MIDI transcription job slot (MuScriptor) — generic over the+ * Rounds and Music Video API surfaces, which share the same kickoff/SSE/cancel+ * job shape (mirroring useReferenceAudioImport). Call it once per UI surface+ * that can independently kick off a transcription so each owns its own job ++ * SSE subscription.+ *+ * `startRequest(context)` performs the feature's kickoff API call and resolves+ * `{ jobId }`; `eventsUrl(jobId)` / `cancelRequest(jobId)` are that feature's+ * SSE URL builder and cancel call. `onComplete(frame, context)` fires on the+ * terminal frame — `frame` carries `{ filename, model, ... }` plus whatever the+ * server merged in (the music video path includes the persisted+ * `midiTranscription`); `context` is whatever was passed to `start(context)`,+ * captured at kickoff so a slow-finishing job still attaches to the right+ * target even if the caller's own state changed while it was in flight.+ */+export default function useMidiTranscription({ startRequest, eventsUrl, cancelRequest, onComplete } = {}) {+ const [job, setJob] = useState(null); // { jobId, context }+ // Covers the gap between clicking Transcribe and the kickoff request+ // resolving, when `job` is still null — without it a fast double-click could+ // fire a second request whose response silently orphans the first job.+ const [pending, setPending] = useState(false);+ const sse = useSseProgress(job ? eventsUrl(job.jobId) : null);+ const latest = sse.latest;+ const stage = latest?.stage ?? null;++ useEffect(() => {+ if (!job || !latest) return;+ if (latest.type === 'complete') {+ onComplete?.(latest, job.context);+ setJob(null);+ } else if (latest.type === 'error') {+ toast.error(latest.error || 'MIDI transcription failed');+ setJob(null);+ } else if (latest.type === 'canceled' || latest.type === 'cancelled') {+ toast.info('MIDI transcription cancelled');+ setJob(null);+ }+ }, [latest]);++ // Stream closed without a terminal frame (server restart mid-transcription,+ // or the job was pruned before/after attach) — recover so the spinner can't hang.+ useEffect(() => {+ if (job && sse.closed && !isTerminalSseFrame(latest)) {+ setJob(null);+ toast.info('Lost connection to the MIDI transcription');+ }+ }, [sse.closed]);++ const start = (context) => {+ if (job || pending) return;+ setPending(true);+ startRequest(context)+ .then(({ jobId }) => setJob({ jobId, context }))+ .catch((err) => toast.error(err?.message || 'Failed to start MIDI transcription'))+ .finally(() => setPending(false));+ };++ const cancel = () => {+ if (!job) return;+ cancelRequest(job.jobId, { silent: true }).catch(() => {});+ };++ // `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, stage, context: job?.context ?? null, start, cancel };+}diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 12a36d3928..33fb611461 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -17,7 +17,12 @@ import {renderMusicVideoProject,musicVideoRenderEventsUrl,cancelMusicVideoRender,+ transcribeMusicVideoMidi,+ musicVideoMidiEventsUrl,+ cancelMusicVideoMidiTranscription,} from '../services/apiMusicVideo.js';+import { getUploadUrl } from '../services/apiMedia.js';+import useMidiTranscription from '../hooks/useMidiTranscription.js';import { generateImage } from '../services/apiSystem.js';import { generateVideo } from '../services/apiImageVideo.js';import { listTracks, trackAudioUrl } from '../services/apiTracks.js';@@ -254,6 +259,27 @@ export default function MusicVideo() {.catch((err) => toast.error(err?.message || 'Failed to delete project'));};+ // Audio → MIDI transcription (MuScriptor): turn the project's source audio+ // into a .mid. The server persists the pointer on the project at completion;+ // the terminal frame carries it, merged here keyed on the captured projectId+ // (the hook's `context`) so a project switch mid-transcription can't+ // misattribute the result. `midiTargetsSelected` gates the track-change+ // controls, since the .mid being produced is of the CURRENT audio (mirrors+ // renderTargetsSelected).+ const midiJob = useMidiTranscription({+ startRequest: (projectId) => transcribeMusicVideoMidi(projectId, {}, { silent: true }),+ eventsUrl: musicVideoMidiEventsUrl,+ cancelRequest: cancelMusicVideoMidiTranscription,+ onComplete: (frame, projectId) => {+ if (frame.midiTranscription) {+ setProjects((prev) => prev.map((p) => (p.id === projectId+ ? { ...p, midiTranscription: frame.midiTranscription } : p)));+ }+ toast.success('MIDI transcription ready');+ },+ });+ const midiTargetsSelected = !!(midiJob.active && selected && midiJob.context === selected.id);+const handleAnalyze = () => {if (!selected) return;setAnalyzing(true);@@ -609,6 +635,21 @@ export default function MusicVideo() {className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0 disabled:opacity-50"><Activity size={15} /> {analyzing ? 'Analyzing…' : 'Analyze'}</button>+ {midiTargetsSelected ? (+ <button onClick={midiJob.cancel} title="Cancel MIDI transcription"+ className="flex items-center gap-1 bg-port-warning/20 text-port-warning border border-port-border rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0">+ <Activity size={15} className="animate-spin" /> MIDI · Cancel+ </button>+ ) : (+ <button onClick={() => midiJob.start(selected.id)}+ disabled={midiJob.active || (!selected.trackId && !selected.uploadedAudioFilename)}+ title={!selected.trackId && !selected.uploadedAudioFilename+ ? 'Link a track first'+ : 'Transcribe the track to MIDI with MuScriptor (local, needs INSTALL_MUSCRIPTOR=1)'}+ className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0 disabled:opacity-50">+ <Music size={15} /> MIDI+ </button>+ )}<button onClick={handlePlan} disabled={planning || !selected.audioAnalysis}title={!selected.audioAnalysis ? 'Analyze the track first' : 'AI-propose a scene per song section'}className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0 disabled:opacity-50">@@ -648,20 +689,28 @@ export default function MusicVideo() {<span className="text-port-text-muted flex items-center gap-1"><Music size={12} /> {trackName(selected.trackId)}</span><select value={selected.trackId || ''} aria-label="Change track"onChange={(e) => e.target.value && handleChangeTrack(e.target.value)}- disabled={ytImportEdit.active || renderTargetsSelected}- title={renderTargetsSelected ? 'Wait for the current render to finish before changing the track' : undefined}+ disabled={ytImportEdit.active || renderTargetsSelected || midiTargetsSelected}+ title={renderTargetsSelected+ ? 'Wait for the current render to finish before changing the track'+ : midiTargetsSelected+ ? 'Wait for the MIDI transcription to finish before changing the track'+ : undefined}className="bg-port-bg border border-port-border rounded px-1.5 py-1 disabled:opacity-50"><option value="">Change track…</option>{tracks.map((t) => <option key={t.id} value={t.id}>{t.title || t.id}</option>)}</select><YoutubeImportControlsurl={ytUrlEdit} onUrlChange={(e) => setYtUrlEdit(e.target.value)}- job={ytImportEdit} disabled={renderTargetsSelected}+ job={ytImportEdit} disabled={renderTargetsSelected || midiTargetsSelected}onStart={() => {if (renderTargetsSelected) {toast.error('Wait for the current render to finish before changing the track');return;}+ if (midiTargetsSelected) {+ toast.error('Wait for the MIDI transcription to finish before changing the track');+ return;+ }setYtEditProjectId(selected.id);ytImportEdit.start(ytUrlEdit, selected.id);}}@@ -682,6 +731,13 @@ export default function MusicVideo() {className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1 text-xs hover:bg-port-border/40"><Download size={13} /> Download audio</a>+ {selected.midiTranscription?.filename && (+ <a href={getUploadUrl(selected.midiTranscription.filename)} download+ title={`Download the MIDI transcription (MuScriptor ${selected.midiTranscription.model || ''})`}+ className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-port-accent hover:bg-port-border/40">+ <Music size={13} /> Download MIDI+ </a>+ )}</div>);})()}diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex 338d042e90..5ec0622d7b 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -47,6 +47,9 @@ vi.mock('../services/apiMusicVideo.js', () => ({renderMusicVideoProject: vi.fn(async () => ({ jobId: 'job-1' })),musicVideoRenderEventsUrl: (jobId) => `/api/music-video/render/${jobId}/events`,cancelMusicVideoRender: vi.fn(async () => ({ ok: true })),+ transcribeMusicVideoMidi: vi.fn(async () => ({ jobId: 'midi-job-1', model: 'medium' })),+ musicVideoMidiEventsUrl: (jobId) => `/api/music-video/transcribe-midi/${jobId}/events`,+ cancelMusicVideoMidiTranscription: vi.fn(async () => ({ ok: true })),}));vi.mock('../services/apiSystem.js', () => ({ generateImage: vi.fn() }));vi.mock('../services/apiImageVideo.js', () => ({ generateVideo: vi.fn() }));@@ -74,7 +77,7 @@ vi.mock('../components/PageHeader', () => ({ default: ({ title }) => <div>{titleimport MusicVideo from './MusicVideo.jsx';import {listMusicVideoProjects, createMusicVideoProject, renderMusicVideoProject, planMusicVideoProject, updateMusicVideoProject,- deleteMusicVideoProject,+ deleteMusicVideoProject, transcribeMusicVideoMidi,} from '../services/apiMusicVideo.js';import { importTrackFromYoutube, trackImportEventsUrl, listTracks } from '../services/apiTracks.js';@@ -187,6 +190,29 @@ describe('MusicVideo audio preview + download', () => {});});+describe('MusicVideo audio → MIDI transcription (MuScriptor)', () => {+ it('disables the MIDI button when the project has no audio source', async () => {+ await openProject({ ...PROJECT_WITH_CLIP, trackId: null, uploadedAudioFilename: null });+ const btn = await screen.findByRole('button', { name: /^MIDI$/ });+ expect(btn).toHaveProperty('disabled', true);+ });++ it('kicks off a transcription for the selected project', async () => {+ await openProject(PROJECT_WITH_CLIP);+ const btn = await screen.findByRole('button', { name: /^MIDI$/ });+ expect(btn).toHaveProperty('disabled', false);+ fireEvent.click(btn);+ await waitFor(() => expect(transcribeMusicVideoMidi).toHaveBeenCalledWith('mv-1', {}, { silent: true }));+ });++ it('shows the MIDI download link once the project carries a transcription pointer', async () => {+ listTracks.mockResolvedValue([{ id: 't1', title: 'Neon Song', audioFilename: 'neon.mp3' }]);+ await openProject({ ...PROJECT_WITH_CLIP, midiTranscription: { filename: 'neon-midi.mid', model: 'medium' } });+ const dl = await screen.findByRole('link', { name: /Download MIDI/i });+ expect(dl.getAttribute('href')).toBe('/api/uploads/neon-midi.mid');+ });+});+describe('MusicVideo autonomous shot planner (#1855)', () => {it('disables AI Plan until the track is analyzed', async () => {await openProject(PROJECT_NO_CLIP);diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 771a4a4fc2..124147c772 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -47,6 +47,22 @@ export const reorderMusicVideoScenes = (id, sceneIds, options = {}) =>method: 'POST', body: JSON.stringify({ sceneIds }), ...options,});+// ---- Audio → MIDI transcription (MuScriptor) ----+// Transcribe the project's source audio into a .mid via the local MuScriptor+// sidecar. Kickoff resolves to { jobId, model } (503 with an install hint when+// the runtime isn't provisioned). Progress streams over SSE; the terminal+// `complete` frame carries the server-persisted `midiTranscription` pointer.+export const transcribeMusicVideoMidi = (id, body = {}, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/transcribe-midi`, {+ method: 'POST', body: JSON.stringify(body), ...options,+ });++export const musicVideoMidiEventsUrl = (jobId) =>+ `/api/music-video/transcribe-midi/${encodeURIComponent(jobId)}/events`;++export const cancelMusicVideoMidiTranscription = (jobId, options = {}) =>+ request(`/music-video/transcribe-midi/${encodeURIComponent(jobId)}/cancel`, { method: 'POST', ...options });+// ---- Render (#1760, Phase 2) ----// Kick off the master-bed render; resolves to { jobId }. Progress streams over// the SSE URL below (subscribe with useSseProgress). cancel stops an in-flight job.diff --git a/client/src/services/apiRounds.js b/client/src/services/apiRounds.jsindex d3495a665a..b51568ac02 100644--- a/client/src/services/apiRounds.js+++ b/client/src/services/apiRounds.js@@ -60,3 +60,20 @@ export const referenceAudioImportEventsUrl = (jobId) =>export const cancelReferenceAudioImport = (jobId, options = {}) =>request(`/rounds/reference-audio/import/${enc(jobId)}/cancel`, { method: 'POST', ...options });++// --- Reference-audio → MIDI transcription (MuScriptor) — transcribe an attached+// reference audio file (an uploads basename) into a .mid via the local+// MuScriptor sidecar. Kickoff returns { jobId, model } (503 with an install+// hint when the runtime isn't provisioned); progress streams over SSE; the+// terminal `complete` frame carries the { filename } the caller persists on the+// reference (via the normal PUT on Save, same as the audio import above).+export const transcribeReferenceMidi = (filename, model, options = {}) =>+ request('/rounds/reference-audio/transcribe-midi', {+ method: 'POST', body: JSON.stringify(model ? { filename, model } : { filename }), ...options,+ });++export const referenceMidiTranscriptionEventsUrl = (jobId) =>+ `/api/rounds/reference-audio/transcribe-midi/${enc(jobId)}/events`;++export const cancelReferenceMidiTranscription = (jobId, options = {}) =>+ request(`/rounds/reference-audio/transcribe-midi/${enc(jobId)}/cancel`, { method: 'POST', ...options });diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.shindex 8a8ea97a07..7c0e0d24a8 100755--- a/scripts/setup-image-video.sh+++ b/scripts/setup-image-video.sh@@ -15,6 +15,7 @@# 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).+# INSTALL_MUSCRIPTOR '1' to bootstrap a venv at ~/.portos/venv-muscriptor (the muscriptor pip package + its torch stack) for local audio → MIDI transcription (Rounds reference audio + Music Video parsing). Default: 0; opt in with INSTALL_MUSCRIPTOR=1 (runs on MPS / CUDA / CPU; model weights auto-download from HuggingFace on first transcription).set -euo pipefail@@ -61,8 +62,8 @@ mkdir -p "${PORTOS_DATA}/video-thumbnails"# install ever starts — which on Linux/CPU/CUDA blocks the advertised# `INSTALL_ACESTEP=1 bash …` path. A bare `bash setup-image-video.sh` still# installs mflux as before.-ANY_BYOV="${INSTALL_LTX2:-0}${INSTALL_WAN22:-0}${INSTALL_HUNYUAN:-0}${INSTALL_MUSICGEN:-0}${INSTALL_AUDIOLDM2:-0}${INSTALL_ACESTEP:-0}"-if [[ "$ANY_BYOV" == "000000" ]]; then+ANY_BYOV="${INSTALL_LTX2:-0}${INSTALL_WAN22:-0}${INSTALL_HUNYUAN:-0}${INSTALL_MUSICGEN:-0}${INSTALL_AUDIOLDM2:-0}${INSTALL_ACESTEP:-0}${INSTALL_MUSCRIPTOR:-0}"+if [[ "$ANY_BYOV" == "0000000" ]]; thenDEFAULT_INSTALL_MFLUX=1DEFAULT_INSTALL_VIDEO=$(is_macos && echo 1 || echo 0)DEFAULT_INSTALL_FLUX2=$(is_macos && echo 1 || echo 0)@@ -479,6 +480,45 @@ if [[ "$INSTALL_ACESTEP" == "1" ]]; thenecho "✅ ACE-Step venv ready: $ACESTEP_PY"fi+INSTALL_MUSCRIPTOR="${INSTALL_MUSCRIPTOR:-0}"+if [[ "$INSTALL_MUSCRIPTOR" == "1" ]]; then+ # Local audio → MIDI transcription for the Rounds workbench + Music Video+ # parsing system. MuScriptor is a multi-instrument music-transcription model+ # (https://github.com/muscriptor/muscriptor) that installs as the+ # `muscriptor` pip package — it declares its own torch stack, so this is a+ # sibling venv kept apart from the music-generation piles. The sidecar+ # `scripts/transcribe_muscriptor.py` imports `TranscriptionModel` from+ # muscriptor; server/lib/pythonSetup.js (resolveMuscriptorPython) looks for+ # python3 here. Runs on Apple-Silicon MPS, CUDA, or CPU. Model weights+ # (small/medium/large) auto-download from HuggingFace on first transcription,+ # so this only builds the venv — no weights are fetched here. Weights are+ # CC BY-NC 4.0 (non-commercial).+ MUSCRIPTOR_VENV="${HOME}/.portos/venv-muscriptor"+ MUSCRIPTOR_PY="$MUSCRIPTOR_VENV/bin/python3"+ mkdir -p "${HOME}/.portos"++ if [[ ! -x "$MUSCRIPTOR_PY" ]]; then+ echo "📦 Creating MuScriptor venv at ${MUSCRIPTOR_VENV}..."+ "$PYTHON_BIN" -m venv "$MUSCRIPTOR_VENV"+ fi+ echo "📦 Installing MuScriptor into ${MUSCRIPTOR_VENV} (pulls torch + audio deps)..."+ "$MUSCRIPTOR_PY" -m pip install --upgrade pip wheel setuptools >/dev/null+ # muscriptor declares its own deps (torch, soundfile, etc.), so installing the+ # package pulls the matching stack. The import probe below catches a broken+ # resolve before a transcription depends on it.+ "$MUSCRIPTOR_PY" -m pip install --upgrade \+ muscriptor \+ "huggingface_hub[hf_xet]"+ # Verify the model class imports — a clean import means transcription only+ # needs the one-time weight download, not a broken venv.+ if ! "$MUSCRIPTOR_PY" -c "from muscriptor import TranscriptionModel" 2>/dev/null; then+ echo "❌ MuScriptor venv built but 'from muscriptor import TranscriptionModel' failed." >&2+ echo " Check that the muscriptor package installed cleanly in ${MUSCRIPTOR_VENV}." >&2+ exit 1+ fi+ echo "✅ MuScriptor venv ready: $MUSCRIPTOR_PY"+fi+INSTALL_FLUX2="${INSTALL_FLUX2:-$DEFAULT_INSTALL_FLUX2}"if [[ "$INSTALL_FLUX2" == "1" ]]; then@@ -558,6 +598,9 @@ fiif [[ "$INSTALL_ACESTEP" == "1" ]]; thenecho " ACE-Step: ${HOME}/.portos/venv-acestep/bin/python3 (separate venv, acestep — full song + vocals)"fi+if [[ "$INSTALL_MUSCRIPTOR" == "1" ]]; then+ echo " MuScriptor: ${HOME}/.portos/venv-muscriptor/bin/python3 (separate venv, muscriptor — audio → MIDI)"+fiif [[ "$INSTALL_FLUX2" == "1" ]]; thenecho " 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/scripts/transcribe_muscriptor.py b/scripts/transcribe_muscriptor.pynew file mode 100644index 0000000000..07dfca7256--- /dev/null+++ b/scripts/transcribe_muscriptor.py@@ -0,0 +1,118 @@+#!/usr/bin/env python3+"""+PortOS MuScriptor runner — local audio → MIDI transcription.+Spawned by `server/services/audioMidiTranscription.js` for the Rounds+reference-audio workbench and the Music Video parsing system.++MuScriptor (https://github.com/muscriptor/muscriptor) is a multi-instrument+music-transcription model (small/medium/large variants, weights auto-download+from HuggingFace on first use). It installs as the `muscriptor` pip package+into an opt-in venv: `INSTALL_MUSCRIPTOR=1 bash scripts/setup-image-video.sh`+(see server/lib/pythonSetup.js resolveMuscriptorPython).++CLI contract (mirrors the generate_* audio sidecars):+ --audio <path> input audio (wav/mp3/flac/ogg/m4a — soundfile-supported)+ --output <path> output .mid path+ --model <size> small | medium | large (default medium)+ [--runtime-dir <dir>] optional sys.path prepend for a vendored checkout++Progress protocol (mirrors the image/video/musicgen sidecars): STAGE:<name>+[:detail] lines on stderr drive the JS-side progress display; a final+`RESULT:<json>` line on stdout reports the written path + byte count.+"""++import argparse+import json+import os+import sys+++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_model_class(runtime_dir):+ """Resolve muscriptor's TranscriptionModel class.++ MuScriptor ships as a pip package, so we normally import it straight from+ the venv. `runtime_dir` is honored for parity with the other audio+ sidecars — a vendored checkout can be prepended to sys.path. Raising a+ clear ImportError lets the JS side surface "run the installer" rather than+ 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 muscriptor import TranscriptionModel # type: ignore+ return TranscriptionModel+ except ImportError as exc:+ raise ImportError(+ "Could not import muscriptor. Run "+ "`INSTALL_MUSCRIPTOR=1 bash scripts/setup-image-video.sh` to build "+ f"the venv (looked in: {runtime_dir or 'venv site-packages'})."+ ) from exc+++def _load_model(TranscriptionModel, size):+ """Load the requested model size, tolerating signature drift.++ The documented API is `TranscriptionModel.load_model()` accepting a size+ keyword ("small" | "medium" | "large", default "medium"). If a future+ release changes the positional signature, fall back to the library default+ rather than failing the whole transcription.+ """+ try:+ return TranscriptionModel.load_model(size)+ except TypeError:+ log_stage("load-model", "size arg rejected — falling back to default model")+ return TranscriptionModel.load_model()+++def main():+ parser = argparse.ArgumentParser(description="PortOS MuScriptor runner (audio → MIDI)")+ parser.add_argument("--audio", required=True, help="Input audio path")+ parser.add_argument("--output", required=True, help="Output .mid path")+ parser.add_argument("--model", default="medium",+ choices=["small", "medium", "large"],+ help="MuScriptor model size (weights auto-download on first use)")+ parser.add_argument("--runtime-dir", default=os.environ.get("PORTOS_MUSCRIPTOR_RUNTIME_DIR", ""),+ help="Optional dir prepended to sys.path before importing muscriptor")+ args = parser.parse_args()++ if not os.path.isfile(args.audio):+ print(f"ERROR: audio file not found: {args.audio}", file=sys.stderr, flush=True)+ return 2++ log_stage("import-runtime")+ TranscriptionModel = _import_model_class(args.runtime_dir)++ log_stage("load-model", args.model)+ model = _load_model(TranscriptionModel, args.model)++ log_stage("transcribe", os.path.basename(args.audio))+ midi_bytes = model.transcribe_to_midi(args.audio)+ if not midi_bytes:+ print("ERROR: muscriptor returned no MIDI data", file=sys.stderr, flush=True)+ return 1++ log_stage("write-midi")+ out_dir = os.path.dirname(os.path.abspath(args.output))+ if out_dir:+ os.makedirs(out_dir, exist_ok=True)+ with open(args.output, "wb") as fh:+ fh.write(midi_bytes)++ result = {+ "output": args.output,+ "model": args.model,+ "bytes": len(midi_bytes),+ }+ print("RESULT:" + json.dumps(result), flush=True)+ log_stage("done")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/server/lib/README.md b/server/lib/README.mdindex d740cdd1d3..fff928ccfb 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -262,6 +262,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate). || `openapiSpec.js` | `buildOpenApiSpec(settings, { baseUrl, version })` — builds an OpenAPI 3.1 document for the currently-exposed public APIs from `apiRegistry`, reusing route Zod schemas via `z.toJSONSchema`. Exposed+`requireAuth` operations get a `security` requirement; passwordless ones don't. Served by `routes/apiDocs.js`. || `shellQuote.js` | `shellQuote(value)` — POSIX single-quote escaping for values interpolated into shell command strings (display command lines, copy-paste blocks in agent prompts). Bare-safe tokens pass through; everything else is single-quoted. Canonical escaper — don't hand-roll. |+| `sidecarProcess.js` | `runSidecarProcess({bin,args,env,signal,onStage,onProcess})` + `parseSidecarResult(stdout)` — the shared Python-sidecar STAGE:/RESULT: wire-protocol runner (spawn, tail-capped stdout/stderr, per-STAGE-line callback, abort/SIGTERM → `canceled`, non-zero exit → stderr-tail reason). Used by `pipeline/musicGen.js` (all music backends) and `audioMidiTranscription.js` (MuScriptor). || `singleFlight.js` | `createSingleFlight()` → `run(key, fn)` — keyed in-flight coalescer: concurrent calls for the same key share one `fn()` execution and result; the slot auto-clears on settle. Minimal by design (no TTL/result cache layered on top, doesn't reject concurrent callers). Used by `promptRunner.js`'s fallback mark-and-pick. || `sseUtils.js` | Per-job SSE stream helpers (imageGen + others) plus `createSseRunner` — the shared batch-runner lifecycle (runs map, terminal-frame replay, cancel, fire-and-forget coordinator) used by the pipeline completeness/analysis/checks runners. || `streamBackpressure.js` | `awaitWritableDrain(res)` — park a streaming-response producer on the socket's next `drain` (or `close`) when `res.write()` returned false, so SSE/NDJSON writes stay bounded for a slow reader. Shared by `routes/ask.js` (SSE) and `routes/localLlm.js` (NDJSON). |diff --git a/server/lib/index.js b/server/lib/index.jsindex 07f88aea7a..dc8731ade2 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -232,6 +232,7 @@ export * from './markedSection.js';export * from './objects.js';export * from './openapiSpec.js';export * from './shellQuote.js';+export * from './sidecarProcess.js';export * from './singleFlight.js';export * from './streamBackpressure.js';export * from './sseUtils.js';diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 0e5d210414..ff794c11e3 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -96,6 +96,23 @@ export const musicVideoPlanRequestSchema = z.object({model: z.string().max(200).optional(),}).strict();+// MuScriptor audio → MIDI transcription request (services/audioMidiTranscription.js).+// `model` picks the MuScriptor size tier; the service clamps unknown values to+// its default, this only types the field.+export const musicVideoTranscribeMidiRequestSchema = z.object({+ model: z.enum(['small', 'medium', 'large']).optional(),+}).strict();++// The persisted MIDI-transcription pointer (a .mid basename under /api/uploads,+// produced by the MuScriptor sidecar from the project's source audio). Cleared+// alongside audioAnalysis when the audio source changes — it was transcribed+// from the OLD track.+export const musicVideoMidiTranscriptionSchema = z.object({+ filename: z.string().min(1).max(256),+ model: z.string().max(32).optional(),+ createdAt: z.string().max(64).optional(),+}).strict();+// The cached beat/tempo/section map (audioAnalysis.js output). Validated when a// record round-trips so a hand-edited/legacy project can't carry a malformed// analysis; the analyzer itself produces this shape.diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.jsindex 8937cbad3a..b60b1f8bd3 100644--- a/server/lib/pythonSetup.js+++ b/server/lib/pythonSetup.js@@ -304,6 +304,38 @@ export function invalidateAcestepPython() {cachedAcestepPython = null;}+// MuScriptor (audio → MIDI transcription for the Rounds workbench + Music Video+// parsing, #reference-audio-to-midi) runs in its own venv at+// ~/.portos/venv-muscriptor — the `muscriptor` pip package pulls its own torch+// stack, kept apart from the music-generation venvs above. Model weights+// auto-download from HuggingFace on first transcription (small/medium/large).+// `INSTALL_MUSCRIPTOR=1 bash scripts/setup-image-video.sh` provisions the venv;+// the sidecar is `scripts/transcribe_muscriptor.py`.+const MUSCRIPTOR_VENV_CANDIDATES = IS_WIN+ ? [+ join(HOME, '.portos', 'venv-muscriptor', 'Scripts', 'python.exe'),+ join(PATHS.data, 'python', 'venv-muscriptor', 'Scripts', 'python.exe'),+ ]+ : [+ join(HOME, '.portos', 'venv-muscriptor', 'bin', 'python3'),+ join(PATHS.data, 'python', 'venv-muscriptor', 'bin', 'python3'),+ ];++export const MUSCRIPTOR_VENV_DEFAULT = MUSCRIPTOR_VENV_CANDIDATES[0];++let cachedMuscriptorPython = null;+export function resolveMuscriptorPython() {+ if (cachedMuscriptorPython && existsSync(cachedMuscriptorPython)) return cachedMuscriptorPython;+ for (const p of MUSCRIPTOR_VENV_CANDIDATES) {+ if (existsSync(p)) { cachedMuscriptorPython = p; return p; }+ }+ return null;+}++export function invalidateMuscriptorPython() {+ cachedMuscriptorPython = 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 actualdiff --git a/server/lib/sidecarProcess.js b/server/lib/sidecarProcess.jsnew file mode 100644index 0000000000..6d36b1a24f--- /dev/null+++ b/server/lib/sidecarProcess.js@@ -0,0 +1,112 @@+/**+ * Shared Python-sidecar process runner — the STAGE:/RESULT: wire protocol.+ *+ * Every media sidecar (scripts/generate_musicgen.py, generate_audioldm2.py,+ * generate_acestep.py, transcribe_muscriptor.py, …) speaks the same contract:+ * `STAGE:<name>[:detail]` lines on stderr drive the JS-side phase/progress+ * display, and a final `RESULT:<json>` line on stdout reports what was+ * produced. This module holds the one spawn/stream/close implementation so+ * consumers (pipeline/musicGen.js, audioMidiTranscription.js) can't drift on+ * the protocol.+ *+ * Not a route handler — the spawn-error / close branches run outside the+ * Express lifecycle and must not throw, so they resolve a structured result+ * instead.+ */++import { spawn } from 'child_process';++// Only the trailing RESULT: line is ever consumed, and sidecar runs are+// long-lived (first-run weight downloads, multi-minute inference) — so both+// streams are tail-capped rather than accumulated unbounded. stdout keeps+// enough for a generous RESULT payload; stderr keeps enough for a useful+// failure tail.+const STDOUT_TAIL = 16_000;+const STDERR_TAIL = 4000;++/**+ * Pull the sidecar's final `RESULT:<json>` line out of its stdout. Returns+ * null when no parseable result line is present so the caller can fail with a+ * useful message instead of a malformed success.+ */+export function parseSidecarResult(stdout) {+ const line = (stdout || '').split(/\r?\n/).reverse().find((l) => l.startsWith('RESULT:'));+ if (!line) return null;+ try {+ return JSON.parse(line.slice('RESULT:'.length));+ } catch {+ return null;+ }+}++/**+ * Spawn a sidecar and resolve `{ ok, stdout, canceled?, reason? }`.+ *+ * - `onStage(stage, detail, raw)` fires once per `STAGE:` line on stderr —+ * the caller decides what to do with it (log, SSE frame, idle-watchdog+ * reset). `raw` is the full text after the `STAGE:` prefix.+ * - `onProcess(proc | null)` hands the live child to the caller for external+ * cancel tracking (killWithEscalation); called with null once it exits.+ * - `signal` (optional AbortSignal) SIGTERMs the child; an already-aborted+ * signal resolves canceled without spawning (a cancel arriving between the+ * caller creating the controller and this executor running would otherwise+ * be silently missed).+ * - A SIGTERM/SIGKILL exit resolves `{ ok: false, canceled: true }`; a+ * non-zero exit carries the last few stderr lines as `reason`.+ */+export function runSidecarProcess({ bin, args, env, signal, onStage, onProcess }) {+ return new Promise((resolve) => {+ if (signal?.aborted) {+ resolve({ ok: false, canceled: true, reason: 'cancelled (aborted before spawn)', stdout: '' });+ return;+ }+ const proc = spawn(bin, args, { env, stdio: ['ignore', 'pipe', 'pipe'] });+ onProcess?.(proc);+ let stdoutTail = '';+ let stderrTail = '';+ let settled = false;+ const finish = (val) => {+ if (settled) return;+ settled = true;+ cleanup();+ onProcess?.(null);+ resolve(val);+ };++ let onAbort = null;+ const cleanup = () => { if (signal && onAbort) signal.removeEventListener('abort', onAbort); };+ if (signal) {+ onAbort = () => proc.kill('SIGTERM');+ signal.addEventListener('abort', onAbort, { once: true });+ }++ proc.stdout.on('data', (chunk) => {+ stdoutTail = (stdoutTail + chunk.toString()).slice(-STDOUT_TAIL);+ });+ proc.stderr.on('data', (chunk) => {+ const s = chunk.toString();+ stderrTail = (stderrTail + s).slice(-STDERR_TAIL);+ for (const line of s.split(/\r?\n/)) {+ const t = line.trim();+ if (t.startsWith('STAGE:')) {+ const raw = t.slice('STAGE:'.length);+ const [stage, detail] = raw.split(':');+ onStage?.(stage, detail || null, raw);+ }+ }+ });+ proc.on('error', (err) => finish({ ok: false, reason: `spawn failed: ${err.message}`, stdout: stdoutTail }));+ proc.on('close', (code, sig) => {+ if (sig === 'SIGTERM' || sig === 'SIGKILL') {+ finish({ ok: false, canceled: true, reason: `cancelled (${sig})`, stdout: stdoutTail });+ return;+ }+ if (code !== 0) {+ const tail = stderrTail.split(/\r?\n/).filter(Boolean).slice(-3).join(' | ');+ finish({ ok: false, reason: tail || `exit ${code}`, stdout: stdoutTail });+ return;+ }+ finish({ ok: true, stdout: stdoutTail });+ });+ });+}diff --git a/server/lib/sidecarProcess.test.js b/server/lib/sidecarProcess.test.jsnew file mode 100644index 0000000000..d1825614ed--- /dev/null+++ b/server/lib/sidecarProcess.test.js@@ -0,0 +1,77 @@+import { describe, it, expect, vi } from 'vitest';+import { runSidecarProcess, parseSidecarResult } from './sidecarProcess.js';++// Drive the real runner with the current node binary as a stand-in sidecar —+// cross-platform (node is what's running the tests) and exercises the actual+// spawn/stream/close paths rather than a mocked child.+const node = process.execPath;+const run = (script, opts = {}) => runSidecarProcess({ bin: node, args: ['-e', script], ...opts });++describe('parseSidecarResult', () => {+ it('parses the last RESULT: line from sidecar stdout', () => {+ const stdout = [+ 'some noise',+ 'RESULT:{"output":"/tmp/stale.mid","bytes":1}',+ 'RESULT:{"output":"/tmp/out.mid","model":"medium","bytes":2048}',+ '',+ ].join('\n');+ expect(parseSidecarResult(stdout)).toEqual({ output: '/tmp/out.mid', model: 'medium', bytes: 2048 });+ });++ it('returns null when no parseable RESULT line is present', () => {+ expect(parseSidecarResult('no result here')).toBeNull();+ expect(parseSidecarResult('RESULT:not-json')).toBeNull();+ expect(parseSidecarResult('')).toBeNull();+ expect(parseSidecarResult(undefined)).toBeNull();+ });+});++describe('runSidecarProcess', () => {+ it('resolves ok with stdout and fires onStage per STAGE: stderr line', async () => {+ const onStage = vi.fn();+ const result = await run(+ 'process.stderr.write("STAGE:load-model:medium\\nSTAGE:done\\n"); process.stdout.write("RESULT:{\\"x\\":1}\\n");',+ { onStage },+ );+ expect(result.ok).toBe(true);+ expect(parseSidecarResult(result.stdout)).toEqual({ x: 1 });+ expect(onStage).toHaveBeenCalledWith('load-model', 'medium', 'load-model:medium');+ expect(onStage).toHaveBeenCalledWith('done', null, 'done');+ });++ it('reports a non-zero exit with the stderr tail as the reason', async () => {+ const result = await run('process.stderr.write("boom: model exploded\\n"); process.exit(3);');+ expect(result.ok).toBe(false);+ expect(result.canceled).toBeUndefined();+ expect(result.reason).toContain('boom: model exploded');+ });++ it('resolves canceled when the child is SIGTERMed and hands the live child to onProcess', async () => {+ let child = null;+ const seen = [];+ const promise = run('setInterval(() => {}, 1000);', {+ onProcess: (p) => { seen.push(p); if (p) child = p; },+ });+ await vi.waitFor(() => { if (!child) throw new Error('not spawned yet'); });+ child.kill('SIGTERM');+ const result = await promise;+ expect(result.ok).toBe(false);+ expect(result.canceled).toBe(true);+ // onProcess got the live child, then null on exit.+ expect(seen[0]).not.toBeNull();+ expect(seen[seen.length - 1]).toBeNull();+ });++ it('resolves canceled without spawning when the signal is already aborted', async () => {+ const controller = new AbortController();+ controller.abort();+ const result = await run('process.stdout.write("should not run")', { signal: controller.signal });+ expect(result).toEqual({ ok: false, canceled: true, reason: 'cancelled (aborted before spawn)', stdout: '' });+ });++ it('resolves a spawn failure as a structured result instead of throwing', async () => {+ const result = await runSidecarProcess({ bin: '/nonexistent/python3', args: ['x.py'] });+ expect(result.ok).toBe(false);+ expect(result.reason).toMatch(/spawn failed/);+ });+});diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 7695599f8d..3b0c208f88 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -18,6 +18,7 @@ import {musicVideoSceneUpdateSchema,musicVideoSceneReorderSchema,musicVideoPlanRequestSchema,+ musicVideoTranscribeMidiRequestSchema,} from '../lib/validation.js';import { PATHS } from '../lib/fileUtils.js';import { safeUnder } from '../lib/ffmpeg.js';@@ -32,7 +33,13 @@ import {updateScene,deleteScene,reorderProjectScenes,+ setProjectMidiTranscription,} from '../services/musicVideo/projects.js';+import {+ startMidiTranscription,+ attachMidiTranscriptionSseClient,+ cancelMidiTranscription,+} from '../services/audioMidiTranscription.js';import { analyzeAudioFile } from '../services/musicVideo/audioAnalysis.js';import { renderMusicVideo, attachRenderSseClient, cancelRender } from '../services/musicVideo/render.js';import { planProject } from '../services/musicVideo/planner.js';@@ -116,6 +123,43 @@ router.post('/:id/plan', asyncHandler(async (req, res) => {res.json(result);}));+// --- Audio → MIDI transcription (MuScriptor) ---+// Transcribe the project's source audio into a .mid via the local MuScriptor+// sidecar. Kickoff returns 202 + a jobId (503 with the install hint when the+// venv isn't provisioned); progress streams over SSE. Unlike the rounds path+// (where the client persists on Save), the terminal `complete` frame here+// carries the server-persisted pointer — the project record isn't an editor+// draft, so the server lands `midiTranscription` on completion and the frame+// includes it for the client to merge.+router.post('/:id/transcribe-midi', asyncHandler(async (req, res) => {+ const { model } = validateRequest(musicVideoTranscribeMidiRequestSchema, req.body || {});+ const project = await getProject(req.params.id);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const audioPath = await resolveAudioPath(project);+ const projectId = project.id;+ res.status(202).json(await startMidiTranscription({+ audioPath,+ outputName: `${project.name || 'music-video'}-midi`,+ model,+ onComplete: async ({ filename, model: usedModel }) => {+ const midiTranscription = { filename, model: usedModel, createdAt: new Date().toISOString() };+ await setProjectMidiTranscription(projectId, midiTranscription);+ return { midiTranscription };+ },+ }));+}));++// Two-segment paths — distinct from the one-segment GET /:id project read.+router.get('/transcribe-midi/:jobId/events', (req, res) => {+ if (!attachMidiTranscriptionSseClient(req.params.jobId, res)) {+ throw new ServerError('Transcription job not found or expired', { status: 404, code: 'NOT_FOUND' });+ }+});++router.post('/transcribe-midi/:jobId/cancel', (req, res) => {+ res.json({ ok: cancelMidiTranscription(req.params.jobId) });+});+// --- Render (#1760, Phase 2) ---// Assemble the scenes' i2v clips into one MP4 over the track as the master audio// bed. Kickoff returns { jobId }; progress streams over SSE (mirrorsdiff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.jsindex 0c738a783c..925b622fb7 100644--- a/server/routes/musicVideo.test.js+++ b/server/routes/musicVideo.test.js@@ -14,6 +14,7 @@ vi.mock('../services/musicVideo/projects.js', () => ({updateScene: vi.fn(async (id, sceneId, p) => ({ sceneId, ...p })),deleteScene: vi.fn(async (id) => ({ id, scenes: [] })),reorderProjectScenes: vi.fn(async (id, ids) => ({ id, scenes: ids.map((sceneId, order) => ({ sceneId, order })) })),+ setProjectMidiTranscription: vi.fn(async (id, midi) => ({ id, midiTranscription: midi })),}));vi.mock('../services/musicVideo/audioAnalysis.js', () => ({@@ -32,6 +33,14 @@ vi.mock('../services/musicVideo/render.js', () => ({cancelRender: vi.fn(() => true),}));+// Mock the MuScriptor transcription service so the route test doesn't depend+// on a provisioned venv; the route's job is to validate + resolve + dispatch.+vi.mock('../services/audioMidiTranscription.js', () => ({+ startMidiTranscription: vi.fn(async () => ({ jobId: 'midi-job-1', model: 'medium' })),+ attachMidiTranscriptionSseClient: vi.fn(() => true),+ cancelMidiTranscription: vi.fn(() => true),+}));+vi.mock('../services/musicVideo/planner.js', () => ({planProject: vi.fn(async (id) => ({project: { id, scenes: [{ sceneId: 'mvs-1' }] },@@ -45,6 +54,7 @@ import * as svc from '../services/musicVideo/projects.js';import { analyzeAudioFile } from '../services/musicVideo/audioAnalysis.js';import { getTrack } from '../services/tracks/index.js';import * as renderSvc from '../services/musicVideo/render.js';+import * as midiSvc from '../services/audioMidiTranscription.js';import { planProject } from '../services/musicVideo/planner.js';import musicVideoRoutes from './musicVideo.js';@@ -142,6 +152,66 @@ describe('musicVideo routes', () => {});});+ describe('POST /:id/transcribe-midi', () => {+ it('202s with the jobId, resolving the project audio like analyze', async () => {+ svc.getProject.mockResolvedValue({ id: 'mv-1', name: 'Neon', trackId: 't1' });+ getTrack.mockResolvedValue({ id: 't1', audioFilename: 'song.wav' });+ const r = await request(app).post('/api/music-video/mv-1/transcribe-midi').send({ model: 'small' });+ expect(r.status).toBe(202);+ expect(r.body.jobId).toBe('midi-job-1');+ const call = midiSvc.startMidiTranscription.mock.calls[0][0];+ expect(call.audioPath).toMatch(/song\.wav$/);+ expect(call.model).toBe('small');+ expect(call.outputName).toBe('Neon-midi');+ expect(typeof call.onComplete).toBe('function');+ });++ it('onComplete persists the pointer on the project and returns it for the SSE frame', async () => {+ svc.getProject.mockResolvedValue({ id: 'mv-1', name: 'Neon', trackId: 't1' });+ getTrack.mockResolvedValue({ id: 't1', audioFilename: 'song.wav' });+ await request(app).post('/api/music-video/mv-1/transcribe-midi').send({});+ const { onComplete } = midiSvc.startMidiTranscription.mock.calls[0][0];+ const extra = await onComplete({ filename: 'neon-midi.mid', model: 'medium' });+ expect(svc.setProjectMidiTranscription).toHaveBeenCalledWith('mv-1', expect.objectContaining({+ filename: 'neon-midi.mid', model: 'medium',+ }));+ expect(extra.midiTranscription.filename).toBe('neon-midi.mid');+ });++ it('404s when the project is missing', async () => {+ svc.getProject.mockResolvedValue(null);+ const r = await request(app).post('/api/music-video/mv-x/transcribe-midi').send({});+ expect(r.status).toBe(404);+ expect(midiSvc.startMidiTranscription).not.toHaveBeenCalled();+ });++ it('400s when the project has no audio source', async () => {+ svc.getProject.mockResolvedValue({ id: 'mv-1', trackId: null, uploadedAudioFilename: null });+ const r = await request(app).post('/api/music-video/mv-1/transcribe-midi').send({});+ expect(r.status).toBe(400);+ expect(r.body.code).toBe('NO_AUDIO');+ });++ it('rejects an unknown model size', async () => {+ const r = await request(app).post('/api/music-video/mv-1/transcribe-midi').send({ model: 'xl' });+ expect(r.status).toBe(400);+ expect(midiSvc.startMidiTranscription).not.toHaveBeenCalled();+ });++ it('GET /transcribe-midi/:jobId/events 404s for an unknown job', async () => {+ midiSvc.attachMidiTranscriptionSseClient.mockReturnValueOnce(false);+ const r = await request(app).get('/api/music-video/transcribe-midi/nope/events');+ expect(r.status).toBe(404);+ });++ it('POST /transcribe-midi/:jobId/cancel forwards to the service', async () => {+ const r = await request(app).post('/api/music-video/transcribe-midi/midi-job-1/cancel');+ expect(r.status).toBe(200);+ expect(r.body).toEqual({ ok: true });+ expect(midiSvc.cancelMidiTranscription).toHaveBeenCalledWith('midi-job-1');+ });+ });+describe('POST /:id/plan', () => {it('plans with default options when no body is sent', async () => {const r = await request(app).post('/api/music-video/mv-1/plan');diff --git a/server/routes/rounds.js b/server/routes/rounds.jsindex 66c162ab7c..d3f2f759a5 100644--- a/server/routes/rounds.js+++ b/server/routes/rounds.js@@ -24,6 +24,14 @@ import {attachReferenceAudioSseClient,cancelReferenceAudioImport,} from '../services/roundReferenceAudioImport.js';+import {+ startMidiTranscription,+ attachMidiTranscriptionSseClient,+ cancelMidiTranscription,+ MUSCRIPTOR_MODELS,+} from '../services/audioMidiTranscription.js';+import { PATHS } from '../lib/fileUtils.js';+import { safeUnder } from '../lib/ffmpeg.js';const router = Router();@@ -138,6 +146,10 @@ const referenceSchema = z.object({note: str(svc.FIELD_MAX_LENGTH).optional().default(''),audioFilename: str(svc.URL_MAX_LENGTH).optional(),segments: z.array(refSegmentSchema).max(svc.REF_SEGMENTS_MAX).optional(),+ // MuScriptor audio → MIDI transcription of the attached audio (an+ // /api/uploads .mid pointer). The service persists it only alongside an+ // audioFilename — same structural invariant as segments.+ midiFilename: str(svc.URL_MAX_LENGTH).optional(),});// No `.default('')` on these fields: `.partial()` (used for PUT) materializes a@@ -246,6 +258,37 @@ router.post('/reference-audio/import/:jobId/cancel', (req, res) => {res.json({ ok: cancelReferenceAudioImport(req.params.jobId) });});+// --- Reference-audio → MIDI transcription (MuScriptor) ------------------------+// Transcribe an already-attached reference audio file (an /api/uploads basename)+// into a .mid via the local MuScriptor sidecar. Same job/SSE shape as the import+// above: kickoff returns 202 + a jobId (503 with the install hint when the venv+// isn't provisioned); progress streams over SSE; the client persists the+// returned midiFilename on the reference via the normal PUT on Save.+const transcribeMidiSchema = z.object({+ filename: str(svc.URL_MAX_LENGTH).min(1),+ model: z.enum(MUSCRIPTOR_MODELS).optional(),+});++router.post('/reference-audio/transcribe-midi', asyncHandler(async (req, res) => {+ const { filename, model } = validateRequest(transcribeMidiSchema, req.body || {});+ // The filename is a stored uploads basename — validate it can't escape the+ // uploads dir (same posture as musicVideo's resolveAudioPath).+ const audioPath = safeUnder(PATHS.uploads, filename);+ if (!audioPath) throw new ServerError('Invalid audio filename', { status: 400, code: 'VALIDATION_ERROR' });+ const outputName = filename.replace(/\.[^.]+$/, '') || 'reference';+ res.status(202).json(await startMidiTranscription({ audioPath, outputName, model }));+}));++router.get('/reference-audio/transcribe-midi/:jobId/events', (req, res) => {+ if (!attachMidiTranscriptionSseClient(req.params.jobId, res)) {+ throw new ServerError('Transcription job not found or expired', { status: 404, code: 'NOT_FOUND' });+ }+});++router.post('/reference-audio/transcribe-midi/:jobId/cancel', (req, res) => {+ res.json({ ok: cancelMidiTranscription(req.params.jobId) });+});+router.post('/', asyncHandler(async (req, res) => {const input = validateRequest(roundInputSchema, req.body || {});const round = await svc.createRound(input).catch(rethrowRoundError);diff --git a/server/routes/rounds.test.js b/server/routes/rounds.test.jsindex 9726e0c529..366706ee42 100644--- a/server/routes/rounds.test.js+++ b/server/routes/rounds.test.js@@ -36,6 +36,19 @@ const importMocks = vi.hoisted(() => ({}));vi.mock('../services/roundReferenceAudioImport.js', () => importMocks);+// Isolate the route contract from the real MuScriptor/venv transcription+// service — assert validation + dispatch, not the sidecar spawn. MUSCRIPTOR_+// MODELS stays real so the route's z.enum matches the service's actual set.+const midiMocks = vi.hoisted(() => ({+ startMidiTranscription: vi.fn(),+ attachMidiTranscriptionSseClient: vi.fn(),+ cancelMidiTranscription: vi.fn(),+}));+vi.mock('../services/audioMidiTranscription.js', async () => {+ const actual = await vi.importActual('../services/audioMidiTranscription.js');+ return { ...actual, ...midiMocks };+});+import roundsRoutes from './rounds.js';const makeApp = () => {@@ -51,6 +64,7 @@ describe('rounds route', () => {for (const fn of Object.values(mocks)) fn.mockReset();for (const fn of Object.values(aiMocks)) fn.mockReset();for (const fn of Object.values(importMocks)) fn.mockReset();+ for (const fn of Object.values(midiMocks)) fn.mockReset();});it('GET / returns the song list', async () => {@@ -366,4 +380,52 @@ describe('rounds route', () => {expect(res.body).toEqual({ ok: true });expect(importMocks.cancelReferenceAudioImport).toHaveBeenCalledWith('job-1');});++ // --- Reference-audio → MIDI transcription (MuScriptor) ----------------------+ it('POST /reference-audio/transcribe-midi 202s with the jobId, resolving the uploads path', async () => {+ midiMocks.startMidiTranscription.mockResolvedValue({ jobId: 'midi-1', model: 'medium' });+ const res = await request(makeApp())+ .post('/api/rounds/reference-audio/transcribe-midi')+ .send({ filename: 'abc123-ref.wav' });+ expect(res.status).toBe(202);+ expect(res.body).toEqual({ jobId: 'midi-1', model: 'medium' });+ const [arg] = midiMocks.startMidiTranscription.mock.calls[0];+ expect(arg.audioPath).toMatch(/uploads[\\/]abc123-ref\.wav$/);+ expect(arg.outputName).toBe('abc123-ref');+ expect(arg.model).toBeUndefined();+ });++ it('POST /reference-audio/transcribe-midi forwards a valid model and rejects an unknown one', async () => {+ midiMocks.startMidiTranscription.mockResolvedValue({ jobId: 'midi-1', model: 'large' });+ const ok = await request(makeApp())+ .post('/api/rounds/reference-audio/transcribe-midi')+ .send({ filename: 'ref.wav', model: 'large' });+ expect(ok.status).toBe(202);+ expect(midiMocks.startMidiTranscription.mock.calls[0][0].model).toBe('large');++ const bad = await request(makeApp())+ .post('/api/rounds/reference-audio/transcribe-midi')+ .send({ filename: 'ref.wav', model: 'xl' });+ expect(bad.status).toBe(400);+ });++ it('POST /reference-audio/transcribe-midi 400s on a traversal filename and a missing one', async () => {+ const traversal = await request(makeApp())+ .post('/api/rounds/reference-audio/transcribe-midi')+ .send({ filename: '../../etc/passwd' });+ expect(traversal.status).toBe(400);+ const missing = await request(makeApp())+ .post('/api/rounds/reference-audio/transcribe-midi')+ .send({});+ expect(missing.status).toBe(400);+ expect(midiMocks.startMidiTranscription).not.toHaveBeenCalled();+ });++ it('POST /reference-audio/transcribe-midi/:jobId/cancel reports the cancel result', async () => {+ midiMocks.cancelMidiTranscription.mockReturnValue(true);+ const res = await request(makeApp()).post('/api/rounds/reference-audio/transcribe-midi/midi-1/cancel');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ ok: true });+ expect(midiMocks.cancelMidiTranscription).toHaveBeenCalledWith('midi-1');+ });});diff --git a/server/services/audioMidiTranscription.js b/server/services/audioMidiTranscription.jsnew file mode 100644index 0000000000..cd4ee02281--- /dev/null+++ b/server/services/audioMidiTranscription.js@@ -0,0 +1,164 @@+/**+ * Audio → MIDI transcription via MuScriptor — shared by the Rounds workbench+ * (a reference's attached audio) and the Music Video parsing system (the+ * project's source track).+ *+ * MuScriptor (https://github.com/muscriptor/muscriptor) is a local+ * multi-instrument music-transcription model. It runs in an opt-in venv+ * (`INSTALL_MUSCRIPTOR=1 bash scripts/setup-image-video.sh`) through the+ * sidecar `scripts/transcribe_muscriptor.py`, which mirrors the generate_*+ * audio sidecars' STAGE:/RESULT: wire protocol. Model weights auto-download+ * from HuggingFace on first use, so the first transcription can sit in+ * `load-model` for a while — the STAGE lines keep that visible.+ *+ * Job shape mirrors roundReferenceAudioImport.js (the lightweight SSE-job+ * pattern): kickoff returns `{ jobId }` immediately, the transcription runs+ * detached and streams `{ type: 'progress' | 'complete' | 'error' |+ * 'canceled' }` frames, and the produced `.mid` lands in the uploads dir+ * (served at /api/uploads/<filename>) — a filename pointer, consistent with+ * every other audio field.+ */++import { randomUUID } from 'crypto';+import { existsSync, statSync } from 'fs';+import { unlink } from 'fs/promises';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { tmpdir } from 'os';+import { shortId, importFileToUploads } from '../lib/fileUtils.js';+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../lib/sseUtils.js';+import { killWithEscalation } from '../lib/killWithEscalation.js';+import { safeChildProcessEnv } from '../lib/processEnv.js';+import { hfTokenEnv } from '../lib/hfToken.js';+import { resolveMuscriptorPython, MUSCRIPTOR_VENV_DEFAULT } from '../lib/pythonSetup.js';+import { runSidecarProcess, parseSidecarResult } from '../lib/sidecarProcess.js';+import { ServerError } from '../lib/errorHandler.js';++const __dirname = dirname(fileURLToPath(import.meta.url));+// The sidecar lives at the repo root — resolve module-relative so the path is+// correct regardless of the server process's cwd (mirrors pipeline/musicGen.js).+const MUSCRIPTOR_SCRIPT = join(__dirname, '../../scripts/transcribe_muscriptor.py');++// MuScriptor model sizes (weights auto-download on first use). Medium is the+// library default — a quality/speed balance; small is the CPU-friendly tier.+export const MUSCRIPTOR_MODELS = Object.freeze(['small', 'medium', 'large']);+export const DEFAULT_MUSCRIPTOR_MODEL = 'medium';++/** Clamp a requested model size onto the known set (route validates shape; this guards the value). */+export const resolveMuscriptorModel = (model) =>+ (MUSCRIPTOR_MODELS.includes(model) ? model : DEFAULT_MUSCRIPTOR_MODEL);++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}).`;++/**+ * Build the sidecar `{ bin, args }`. Pure — unit-tested without spawning+ * Python (the buildSidecarArgs pattern from pipeline/musicGen.js).+ */+export function buildMuscriptorArgs({ pythonPath, scriptPath = MUSCRIPTOR_SCRIPT, audioPath, outputPath, model }) {+ return {+ bin: pythonPath,+ args: [+ scriptPath,+ '--audio', audioPath,+ '--output', outputPath,+ '--model', resolveMuscriptorModel(model),+ ],+ };+}++// jobId -> { clients, lastPayload, process }+const transcriptionJobs = new Map();++export const attachMidiTranscriptionSseClient = (jobId, res) => attachSse(transcriptionJobs, jobId, res);++/** Cancel an in-flight transcription. Returns false if the job is unknown or already finished. */+export function cancelMidiTranscription(jobId) {+ const job = transcriptionJobs.get(jobId);+ if (!job || !job.process) return false;+ const proc = job.process;+ killWithEscalation(proc, { label: 'muscriptor transcription', stillRunning: () => job.process === proc });+ return true;+}++/**+ * Kick off an audio → MIDI transcription. Returns `{ jobId, model }`+ * immediately; the sidecar runs detached and streams progress over SSE.+ * Terminal frames: `{ type: 'complete', filename, model, ...extra }` (where+ * `extra` is whatever the optional `onComplete` callback returns — the music+ * video route uses it to persist the pointer on the project and hand the+ * updated record to the client), `{ type: 'error', error }`, or+ * `{ type: 'canceled' }`. Throws (before returning a jobId) when the+ * MuScriptor venv isn't provisioned, so that surfaces as a real 503 with the+ * install hint.+ *+ * `audioPath` must already be resolved + validated by the caller (safeUnder+ * against the owning directory). `outputName` seeds the landed `.mid`+ * filename's human-readable prefix.+ */+export async function startMidiTranscription({ audioPath, outputName = 'transcription', model, onComplete }) {+ const pythonPath = resolveMuscriptorPython();+ if (!pythonPath) {+ throw new ServerError(MUSCRIPTOR_INSTALL_HINT, { status: 503, code: 'MIDI_RUNTIME_MISSING' });+ }+ if (!existsSync(audioPath)) {+ throw new ServerError('Audio file not found', { status: 404, code: 'NOT_FOUND' });+ }+ const resolvedModel = resolveMuscriptorModel(model);+ const jobId = randomUUID();+ const tempOut = join(tmpdir(), `portos-midi-${jobId}.mid`);+ const job = { id: jobId, status: 'running', clients: [], process: null };+ transcriptionJobs.set(jobId, job);+ console.log(`🎹 MIDI transcription ${shortId(jobId)} [${resolvedModel}] — ${audioPath}`);++ (async () => {+ 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.+ const env = safeChildProcessEnv(await hfTokenEnv());+ // STAGE: lines become SSE progress frames (and pm2 log lines, so a stuck+ // first-run weight download is visible); onProcess tracks the live child+ // for cancelMidiTranscription's killWithEscalation.+ const result = await runSidecarProcess({+ bin, args, env,+ onProcess: (proc) => { job.process = proc; },+ onStage: (stage, detail, raw) => {+ console.log(`🎹 muscriptor ${raw}`);+ broadcastSse(job, { type: 'progress', stage, detail });+ },+ });++ if (result.canceled) {+ console.log(`🛑 MIDI transcription ${shortId(jobId)} cancelled`);+ broadcastSse(job, { type: 'canceled' });+ return;+ }+ // A clean exit isn't enough — require a parsed RESULT line AND a+ // non-empty file on disk before landing the pointer, so a runtime-shape+ // drift can't attach a dangling/empty MIDI file.+ 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'));+ }++ broadcastSse(job, { type: 'progress', stage: 'importing' });+ const { filename } = await importFileToUploads(tempOut, `${outputName}.mid`);+ const extra = (await onComplete?.({ filename, model: resolvedModel })) || {};++ console.log(`🎹 MIDI transcription ${shortId(jobId)} complete — ${filename}`);+ 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) });+ } finally {+ await unlink(tempOut).catch(() => {});+ closeJobAfterDelay(transcriptionJobs, jobId);+ }+ })();++ return { jobId, model: resolvedModel };+}diff --git a/server/services/audioMidiTranscription.test.js b/server/services/audioMidiTranscription.test.jsnew file mode 100644index 0000000000..529175aa5c--- /dev/null+++ b/server/services/audioMidiTranscription.test.js@@ -0,0 +1,53 @@+import { describe, it, expect } from 'vitest';+import {+ MUSCRIPTOR_MODELS,+ DEFAULT_MUSCRIPTOR_MODEL,+ resolveMuscriptorModel,+ buildMuscriptorArgs,+ cancelMidiTranscription,+} from './audioMidiTranscription.js';++describe('resolveMuscriptorModel', () => {+ it('accepts every known model size', () => {+ for (const m of MUSCRIPTOR_MODELS) expect(resolveMuscriptorModel(m)).toBe(m);+ });++ it('clamps unknown/absent values to the default', () => {+ expect(resolveMuscriptorModel('xl')).toBe(DEFAULT_MUSCRIPTOR_MODEL);+ expect(resolveMuscriptorModel(undefined)).toBe(DEFAULT_MUSCRIPTOR_MODEL);+ expect(resolveMuscriptorModel(null)).toBe(DEFAULT_MUSCRIPTOR_MODEL);+ });+});++describe('buildMuscriptorArgs', () => {+ it('builds the sidecar argv with the resolved model', () => {+ const { bin, args } = buildMuscriptorArgs({+ pythonPath: '/venv/bin/python3',+ scriptPath: '/repo/scripts/transcribe_muscriptor.py',+ audioPath: '/data/uploads/song.wav',+ outputPath: '/tmp/out.mid',+ model: 'large',+ });+ expect(bin).toBe('/venv/bin/python3');+ expect(args).toEqual([+ '/repo/scripts/transcribe_muscriptor.py',+ '--audio', '/data/uploads/song.wav',+ '--output', '/tmp/out.mid',+ '--model', 'large',+ ]);+ });++ it('defaults the script path and clamps an unknown model', () => {+ const { args } = buildMuscriptorArgs({+ pythonPath: 'py', audioPath: 'a.wav', outputPath: 'o.mid', model: 'bogus',+ });+ expect(args[0]).toMatch(/transcribe_muscriptor\.py$/);+ expect(args[args.indexOf('--model') + 1]).toBe(DEFAULT_MUSCRIPTOR_MODEL);+ });+});++describe('cancelMidiTranscription', () => {+ it('returns false for an unknown job', () => {+ expect(cancelMidiTranscription('nope')).toBe(false);+ });+});diff --git a/server/services/musicVideo/projects.js b/server/services/musicVideo/projects.jsindex d9a0682996..94bc7c44b1 100644--- a/server/services/musicVideo/projects.js+++ b/server/services/musicVideo/projects.js@@ -105,6 +105,12 @@ export async function setProjectAnalysis(id, analysis) {return next;}+export async function setProjectMidiTranscription(id, midi) {+ const next = await (await selectBackend()).setProjectMidiTranscription(id, midi);+ emitRecordUpdated('musicVideoProject', id);+ return next;+}+export async function addProjectScene(id, sceneInput) {const scene = await (await selectBackend()).addProjectScene(id, sceneInput);emitRecordUpdated('musicVideoProject', id);diff --git a/server/services/musicVideo/projectsDB.js b/server/services/musicVideo/projectsDB.jsindex fc3e488710..af5a211a46 100644--- a/server/services/musicVideo/projectsDB.js+++ b/server/services/musicVideo/projectsDB.js@@ -18,6 +18,7 @@ import {buildProjectRecord,applyProjectPatch,setAudioAnalysis,+ setMidiTranscription,addScene,addScenes,applySceneUpdate,@@ -187,6 +188,11 @@ export async function setProjectAnalysis(id, analysis) {return project;}+export async function setProjectMidiTranscription(id, midi) {+ const { project } = await withLockedProject(id, (p) => ({ project: setMidiTranscription(p, midi) }));+ return project;+}+export async function addProjectScene(id, sceneInput) {const { result } = await withLockedProject(id, (p) => {const { project, scene } = addScene(p, sceneInput);diff --git a/server/services/musicVideo/projectsFile.js b/server/services/musicVideo/projectsFile.jsindex 8d9b8c5297..3d3436684c 100644--- a/server/services/musicVideo/projectsFile.js+++ b/server/services/musicVideo/projectsFile.js@@ -15,6 +15,7 @@ import {buildProjectRecord,applyProjectPatch,setAudioAnalysis,+ setMidiTranscription,addScene,addScenes,applySceneUpdate,@@ -150,6 +151,13 @@ export async function setProjectAnalysis(id, analysis) {return all[idx];}+export async function setProjectMidiTranscription(id, midi) {+ const { all, idx } = await loadAllAndIndex(id);+ all[idx] = setMidiTranscription(all[idx], midi);+ await saveAll(all);+ return all[idx];+}+export async function addProjectScene(id, sceneInput) {const { all, idx } = await loadAllAndIndex(id);const { project, scene } = addScene(all[idx], sceneInput);diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.jsindex 0280e0b18c..bb34e2e9b9 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -19,6 +19,7 @@ import { ServerError } from '../../lib/errorHandler.js';import {MUSIC_VIDEO_STATUSES,musicVideoAudioAnalysisSchema,+ musicVideoMidiTranscriptionSchema,musicVideoSceneCreateSchema,musicVideoSceneUpdateSchema,} from '../../lib/validation.js';@@ -71,6 +72,7 @@ export function buildProjectRecord(input, { id, now }) {uploadedAudioFilename,concept,audioAnalysis: null,+ midiTranscription: null,scenes: [],renderHistoryId: null,// Soft-delete tombstone trio — kept so peer-sync federation (a follow-up)@@ -108,7 +110,9 @@ export function applyProjectPatch(project, patch) {// analysis, so leave those untouched.const regressStatus = !patch.status && !['draft', 'failed'].includes(project.status);const statusPatch = regressStatus ? { status: 'draft' } : {};- return touch(project, { ...patch, ...statusPatch, audioAnalysis: null, scenes });+ // The MIDI transcription was produced from the OLD audio too — clear it with+ // the analysis so a stale .mid can't masquerade as the new track's score.+ return touch(project, { ...patch, ...statusPatch, audioAnalysis: null, midiTranscription: null, scenes });}/**@@ -123,6 +127,17 @@ export function setAudioAnalysis(project, analysis) {return touch(project, { audioAnalysis: validated, status });}+/**+ * Cache the MuScriptor audio → MIDI transcription pointer on the project (a+ * .mid basename under /api/uploads). Validated so a hand-edited/legacy record+ * can't store a malformed pointer; doesn't touch the lifecycle status — the+ * MIDI is a parsing artifact, not an arrangement step.+ */+export function setMidiTranscription(project, midi) {+ const validated = musicVideoMidiTranscriptionSchema.parse(midi);+ return touch(project, { midiTranscription: validated });+}+/** Default runtime fields for a scene the director (or planner) didn't supply. */function buildScene(input, { order }) {return {diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.jsindex c458c403ae..a4f39e5744 100644--- a/server/services/musicVideo/projectsLogic.test.js+++ b/server/services/musicVideo/projectsLogic.test.js@@ -3,6 +3,7 @@ import {buildProjectRecord,applyProjectPatch,setAudioAnalysis,+ setMidiTranscription,addScene,addScenes,applySceneUpdate,@@ -21,7 +22,7 @@ describe('buildProjectRecord', () => {expect(p).toMatchObject({id: 'mv-x', name: 'Neon Nights', status: 'draft', mode: 'director',trackId: 'track-9', uploadedAudioFilename: null, concept: null,- audioAnalysis: null, scenes: [], renderHistoryId: null,+ audioAnalysis: null, midiTranscription: null, scenes: [], renderHistoryId: null,deleted: false, deletedAt: null,});expect(p.createdAt).toBe(p.updatedAt);@@ -60,6 +61,17 @@ describe('applyProjectPatch', () => {expect(next.audioAnalysis).toBeNull();});+ it('clears the MIDI transcription when the audio source changes (it was transcribed from the OLD track)', () => {+ const withMidi = setMidiTranscription({ ...baseProject(), trackId: 't1' },+ { filename: 'song.mid', model: 'medium', createdAt: '2026-01-02T00:00:00.000Z' });+ expect(withMidi.midiTranscription).not.toBeNull();+ const next = applyProjectPatch(withMidi, { trackId: 't2' });+ expect(next.midiTranscription).toBeNull();+ // Non-audio patches leave it intact.+ const renamed = applyProjectPatch(withMidi, { name: 'Renamed' });+ expect(renamed.midiTranscription).toEqual(withMidi.midiTranscription);+ });+it('leaves audioAnalysis intact when trackId is patched to the SAME value', () => {const analyzed = setAudioAnalysis({ ...baseProject(), trackId: 't1' }, {bpm: 120, beats: [0], downbeats: [0], sections: [{ label: 'S', startSec: 0, endSec: 1 }], durationSec: 1,@@ -147,6 +159,21 @@ describe('setAudioAnalysis', () => {});});+describe('setMidiTranscription', () => {+ it('caches the validated pointer and leaves the lifecycle status alone', () => {+ const midi = { filename: 'song.mid', model: 'medium', createdAt: '2026-01-02T00:00:00.000Z' };+ const next = setMidiTranscription(baseProject(), midi);+ expect(next.midiTranscription).toEqual(midi);+ expect(next.status).toBe('draft');+ expect(next.updatedAt).not.toBe('2026-01-01T00:00:00.000Z');+ });++ it('rejects a malformed pointer', () => {+ expect(() => setMidiTranscription(baseProject(), { filename: '' })).toThrow();+ expect(() => setMidiTranscription(baseProject(), { filename: 'a.mid', extra: true })).toThrow();+ });+});+describe('scene board operations', () => {it('adds scenes with incrementing order and unique ids', () => {const { project: p1, scene: s1 } = addScene(baseProject(), { prompt: 'wide shot' });diff --git a/server/services/pipeline/musicGen.js b/server/services/pipeline/musicGen.jsindex 44e713085b..6aba46fb43 100644--- a/server/services/pipeline/musicGen.js+++ b/server/services/pipeline/musicGen.js@@ -27,7 +27,6 @@* identically to an uploaded one.*/-import { spawn } from 'child_process';import { existsSync, statSync } from 'fs';import { unlink } from 'fs/promises';import { join, dirname } from 'path';@@ -36,6 +35,7 @@ import { randomUUID } from 'crypto';import { PATHS, ensureDir } from '../../lib/fileUtils.js';import { safeChildProcessEnv } from '../../lib/processEnv.js';import { hfTokenEnv } from '../../lib/hfToken.js';+import { runSidecarProcess, parseSidecarResult } from '../../lib/sidecarProcess.js';import {resolveMusicgenPython, MUSICGEN_RUNTIME_DIR, MUSICGEN_VENV_DEFAULT,resolveAudioldm2Python, AUDIOLDM2_RUNTIME_DIR, AUDIOLDM2_VENV_DEFAULT,@@ -238,19 +238,6 @@ export function buildMusicGenArgs({ pythonPath, scriptPath = SIDECAR_SCRIPT, runreturn buildSidecarArgs({ engineId: 'musicgen', pythonPath, scriptPath, runtimeDir, repo, prompt, durationSec, outputPath });}-// Pull the saved path + actual duration out of the sidecar's `RESULT:<json>`-// line. Returns null when no parseable result line is present so the caller-// can fail with a useful message instead of a malformed success.-function parseResultLine(stdout) {- const line = (stdout || '').split(/\r?\n/).reverse().find((l) => l.startsWith('RESULT:'));- if (!line) return null;- try {- return JSON.parse(line.slice('RESULT:'.length));- } catch {- return null;- }-}-/*** Generate a background-music track and land it in the shared music library.* Returns `{ filename, durationSec, modelId, model, engine }`. Throws a@@ -303,13 +290,22 @@ export async function generateMusic({ prompt, lyrics, engine: engineId = DEFAULT// token isn't required — but pass it through when the user has one set so the// first download doesn't hit anonymous HF rate limits.const env = safeChildProcessEnv(await hfTokenEnv());- const result = await runSidecarProcess({ bin, args, env, signal, engineId: engine.id, onActivity });+ // STAGE: lines are echoed to pm2 logs so a stuck first-run model download is+ // visible, and fire onActivity so the media-job queue's idle watchdog resets+ // (see the doc block above).+ const result = await runSidecarProcess({+ bin, args, env, signal,+ onStage: (stage, detail, raw) => {+ console.log(`🎼 ${engine.id} ${raw}`);+ onActivity?.();+ },+ });// A clean exit isn't enough — the sidecar could exit 0 yet write nothing (or// a truncated file) if the runtime changes shape. Require both a parsed// RESULT line AND a non-empty file on disk before we persist the library// pointer; otherwise unlink the partial and fail, so the audio stage never// attaches a dangling/empty track.- const parsed = result.ok ? parseResultLine(result.stdout) : null;+ const parsed = result.ok ? parseSidecarResult(result.stdout) : null;const wroteFile = existsSync(outputPath) && statSync(outputPath).size > 0;if (!result.ok || !parsed || !wroteFile) {await unlink(outputPath).catch(() => {});@@ -327,60 +323,3 @@ export async function generateMusic({ prompt, lyrics, engine: engineId = DEFAULT};}-// Spawn a backend sidecar and resolve `{ ok, stdout, reason? }`. STAGE: lines-// on stderr are echoed to pm2 logs so a stuck first-run model download is-// visible (mirrors the image/video sidecars). Captures stdout for the RESULT-// line and a bounded stderr tail for the failure reason. Not a route handler —-// the spawn-error / close branches must not throw (they run outside the Express-// lifecycle), so they resolve a structured result instead.-function runSidecarProcess({ bin, args, env, signal, engineId = DEFAULT_ENGINE_ID, onActivity }) {- return new Promise((resolve) => {- // A cancel arriving between the caller awaiting up to here and this Promise- // executor running (e.g. the audio job-kind adapter's controller is aborted- // in the same tick it was created) would otherwise be silently missed —- // the 'abort' listener below is only attached AFTER spawn, so an- // already-aborted signal would let the sidecar spawn, run to completion,- // and report success despite the cancel. Check synchronously before- // spawning anything.- if (signal?.aborted) {- resolve({ ok: false, reason: 'cancelled (aborted before spawn)', stdout: '' });- return;- }- const proc = spawn(bin, args, { env, stdio: ['ignore', 'pipe', 'pipe'] });- let stdout = '';- let stderrTail = '';- const STDERR_TAIL = 4000;- let settled = false;- const finish = (val) => { if (!settled) { settled = true; cleanup(); resolve(val); } };-- let onAbort = null;- const cleanup = () => { if (signal && onAbort) signal.removeEventListener('abort', onAbort); };- if (signal) {- onAbort = () => proc.kill('SIGTERM');- signal.addEventListener('abort', onAbort, { once: true });- }-- proc.stdout.on('data', (chunk) => { stdout += chunk.toString(); });- proc.stderr.on('data', (chunk) => {- const s = chunk.toString();- stderrTail = (stderrTail + s).slice(-STDERR_TAIL);- for (const line of s.split(/\r?\n/)) {- const t = line.trim();- if (t.startsWith('STAGE:')) {- console.log(`🎼 ${engineId} ${t.slice('STAGE:'.length)}`);- onActivity?.();- }- }- });- proc.on('error', (err) => finish({ ok: false, reason: `spawn failed: ${err.message}`, stdout }));- proc.on('close', (code, sig) => {- if (sig === 'SIGTERM' || sig === 'SIGKILL') { finish({ ok: false, reason: `cancelled (${sig})`, stdout }); return; }- if (code !== 0) {- const tail = stderrTail.split(/\r?\n/).filter(Boolean).slice(-3).join(' | ');- finish({ ok: false, reason: tail || `exit ${code}`, stdout });- return;- }- finish({ ok: true, stdout });- });- });-}diff --git a/server/services/rounds.js b/server/services/rounds.jsindex d7b4c65bed..cac3e18f13 100644--- a/server/services/rounds.js+++ b/server/services/rounds.js@@ -322,6 +322,12 @@ const sanitizeReference = (r) => {// resurrect against a later, different recording.const segments = sanitizeList(r.segments, sanitizeRefSegment, REF_SEGMENTS_MAX);if (segments.length) ref.segments = segments;+ // A MuScriptor transcription OF the attached audio (an /api/uploads .mid+ // pointer) — same structural invariant as segments: derived from this+ // audio, so removing the audio drops it and a stale transcription can't+ // resurrect against a later, different recording.+ const midiFilename = trimField(r.midiFilename, URL_MAX_LENGTH);+ if (midiFilename) ref.midiFilename = midiFilename;}return ref;};diff --git a/server/services/rounds.test.js b/server/services/rounds.test.jsindex 78e13e13a4..ed77d67514 100644--- a/server/services/rounds.test.js+++ b/server/services/rounds.test.js@@ -451,6 +451,23 @@ describe('rounds service', () => {expect(many.references[0].segments).toHaveLength(svc.REF_SEGMENTS_MAX);});+ it('reference midiFilename persists only alongside an audioFilename', () => {+ const song = svc.sanitizeRound({+ id: 'x',+ references: [+ // Attached audio → the trimmed MIDI pointer round-trips.+ { url: 'https://example.com/a', audioFilename: 'ref.wav', midiFilename: ' ref-transcription.mid ' },+ // No audio → the MIDI was transcribed from a removed recording; drop it.+ { url: 'https://example.com/b', midiFilename: 'stale.mid' },+ // Attached audio, no MIDI → the key stays absent (no empty husk).+ { url: 'https://example.com/c', audioFilename: 'ref2.wav' },+ ],+ });+ expect(song.references[0].midiFilename).toBe('ref-transcription.mid');+ expect('midiFilename' in song.references[1]).toBe(false);+ expect('midiFilename' in song.references[2]).toBe(false);+ });+it('drops reference segments when no audio is attached (#2106)', () => {// Segments are offsets into the attached audio — without an audioFilename// they are stale ranges from a removed recording and must not persist