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

address review (codex): federate the music-video MIDI, guard stale attach, fix Windows venv layout

[._.]/ Adam Eivy572d2a7bdd04
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index 33fb611461..7b1a019c5b 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -21,7 +21,6 @@ import {
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';
@@ -732,7 +731,7 @@ export default function MusicVideo() {
<Download size={13} /> Download audio
</a>
{selected.midiTranscription?.filename && (
- <a href={getUploadUrl(selected.midiTranscription.filename)} download
+ <a href={trackAudioUrl(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
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index 5ec0622d7b..ec1c362925 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -209,7 +209,9 @@ describe('MusicVideo audio → MIDI transcription (MuScriptor)', () => {
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');
+ // Served from the music dir (same static route as the master audio) so the
+ // federated .mid resolves on peers too.
+ expect(dl.getAttribute('href')).toBe('/data/music/neon-midi.mid');
});
});
diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.sh
index 7c0e0d24a8..a177838484 100755
--- a/scripts/setup-image-video.sh
+++ b/scripts/setup-image-video.sh
@@ -497,10 +497,17 @@ if [[ "$INSTALL_MUSCRIPTOR" == "1" ]]; then
MUSCRIPTOR_PY="$MUSCRIPTOR_VENV/bin/python3"
mkdir -p "${HOME}/.portos"
- if [[ ! -x "$MUSCRIPTOR_PY" ]]; then
+ if [[ ! -x "$MUSCRIPTOR_PY" && ! -x "$MUSCRIPTOR_VENV/Scripts/python.exe" ]]; then
echo "📦 Creating MuScriptor venv at ${MUSCRIPTOR_VENV}..."
"$PYTHON_BIN" -m venv "$MUSCRIPTOR_VENV"
fi
+ # A venv created by Windows Python (this script run under git-bash) places the
+ # interpreter at Scripts/python.exe instead of bin/python3 — pick whichever
+ # layout the venv actually has so the pip steps below work on both. The JS
+ # side (pythonSetup's MUSCRIPTOR_VENV_CANDIDATES) already probes both.
+ if [[ ! -x "$MUSCRIPTOR_PY" ]]; then
+ MUSCRIPTOR_PY="$MUSCRIPTOR_VENV/Scripts/python.exe"
+ 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
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index 5873a50412..6fa2546955 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -899,26 +899,33 @@ export function sanitizeFilename(filename) {
}
/**
- * Move a temp file into the uploads dir (`PATHS.uploads`) and return the
- * persisted filename, mirroring the `/api/uploads` route's naming
- * (`<uuid8>-<sanitized-name>`) so a server-produced file (e.g. a yt-dlp audio
- * extraction, #2120) is served and referenced exactly like a user upload.
+ * Move a temp file into `destDir` and return the persisted filename, using the
+ * `/api/uploads` route's naming (`<uuid8>-<sanitized-name>`) so a
+ * server-produced file is served and referenced exactly like a user upload.
*
* copyFile + unlink instead of rename — the source usually lives in
* `os.tmpdir()`, which may sit on a different filesystem (rename across devices
* throws EXDEV on Linux); copy works regardless. The temp unlink is best-effort
* cleanup. Returns `{ filename, sizeBytes }`.
*/
-export async function importFileToUploads(tempPath, originalName) {
- await ensureDir(PATHS.uploads);
+export async function importFileToDir(tempPath, originalName, destDir) {
+ await ensureDir(destDir);
const filename = `${randomUUID().slice(0, 8)}-${sanitizeFilename(originalName)}`;
- const dest = join(PATHS.uploads, filename);
+ const dest = join(destDir, filename);
await copyFile(tempPath, dest);
await unlink(tempPath).catch(() => {});
const s = await stat(dest).catch(() => null);
return { filename, sizeBytes: s?.size ?? 0 };
}
+/**
+ * `importFileToDir` pinned to the uploads dir (`PATHS.uploads`) — the common
+ * case (e.g. a yt-dlp audio extraction, #2120).
+ */
+export async function importFileToUploads(tempPath, originalName) {
+ return importFileToDir(tempPath, originalName, PATHS.uploads);
+}
+
/**
* Validate a user-supplied filename is a safe basename with one of the
* allowed extensions — refuses path-traversal, null bytes, separators, and
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index ff794c11e3..aec8b4ce2c 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -103,8 +103,9 @@ 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
+// The persisted MIDI-transcription pointer (a .mid basename under data/music/,
+// produced by the MuScriptor sidecar from the project's source audio; it lives
+// with the master audio so the peer-sync asset manifest federates it). Cleared
// alongside audioAnalysis when the audio source changes — it was transcribed
// from the OLD track.
export const musicVideoMidiTranscriptionSchema = z.object({
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index 3b0c208f88..c621a616c2 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -137,11 +137,28 @@ router.post('/:id/transcribe-midi', asyncHandler(async (req, res) => {
if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
const audioPath = await resolveAudioPath(project);
const projectId = project.id;
+ // Audio-source identity at kickoff — the completion callback re-checks it so
+ // a transcription of the OLD track can't land on a project whose audio was
+ // swapped mid-run (another client / peer sync). applyProjectPatch clears
+ // midiTranscription on the swap; without this guard the in-flight job would
+ // reintroduce the stale pointer right after.
+ const sourceTrackId = project.trackId ?? null;
+ const sourceUpload = project.uploadedAudioFilename ?? null;
res.status(202).json(await startMidiTranscription({
audioPath,
outputName: `${project.name || 'music-video'}-midi`,
model,
+ // Land the .mid in the music dir (not uploads) so the peer-sync asset
+ // manifest federates it with the project's other audio — the manifest
+ // only ships known asset kinds/directories, and `music` is one.
+ destDir: PATHS.music,
onComplete: async ({ filename, model: usedModel }) => {
+ const current = await getProject(projectId);
+ if (!current) throw new Error('Project was deleted during transcription');
+ if ((current.trackId ?? null) !== sourceTrackId || (current.uploadedAudioFilename ?? null) !== sourceUpload) {
+ console.log(`🎹 Audio source of ${projectId} changed mid-transcription — dropping the stale MIDI result`);
+ return {};
+ }
const midiTranscription = { filename, model: usedModel, createdAt: new Date().toISOString() };
await setProjectMidiTranscription(projectId, midiTranscription);
return { midiTranscription };
diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.js
index 925b622fb7..d1d104f44f 100644
--- a/server/routes/musicVideo.test.js
+++ b/server/routes/musicVideo.test.js
@@ -163,6 +163,9 @@ describe('musicVideo routes', () => {
expect(call.audioPath).toMatch(/song\.wav$/);
expect(call.model).toBe('small');
expect(call.outputName).toBe('Neon-midi');
+ // Lands in the music dir (not uploads) so the peer-sync asset manifest
+ // federates the .mid with the project's other audio.
+ expect(call.destDir).toMatch(/music$/);
expect(typeof call.onComplete).toBe('function');
});
@@ -178,6 +181,19 @@ describe('musicVideo routes', () => {
expect(extra.midiTranscription.filename).toBe('neon-midi.mid');
});
+ it('onComplete drops a stale result when the audio source changed mid-transcription', async () => {
+ svc.getProject.mockResolvedValueOnce({ id: 'mv-1', name: 'Neon', trackId: 't1' }); // kickoff read
+ 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];
+ // By completion time the project points at a different track — the old
+ // audio's MIDI must not be re-attached (applyProjectPatch cleared it).
+ svc.getProject.mockResolvedValueOnce({ id: 'mv-1', name: 'Neon', trackId: 't2' });
+ const extra = await onComplete({ filename: 'stale.mid', model: 'medium' });
+ expect(extra).toEqual({});
+ expect(svc.setProjectMidiTranscription).not.toHaveBeenCalled();
+ });
+
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({});
diff --git a/server/services/audioMidiTranscription.js b/server/services/audioMidiTranscription.js
index cd4ee02281..e4108cdca2 100644
--- a/server/services/audioMidiTranscription.js
+++ b/server/services/audioMidiTranscription.js
@@ -14,9 +14,10 @@
* 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.
+ * 'canceled' }` frames, and the produced `.mid` lands in the caller's
+ * `destDir` — uploads for rounds (served at /api/uploads/<filename>), the
+ * music dir for music video (so the file federates with the project's other
+ * audio) — a filename pointer, consistent with every other audio field.
*/
import { randomUUID } from 'crypto';
@@ -25,7 +26,7 @@ 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 { PATHS, shortId, importFileToDir } 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';
@@ -95,9 +96,12 @@ export function cancelMidiTranscription(jobId) {
*
* `audioPath` must already be resolved + validated by the caller (safeUnder
* against the owning directory). `outputName` seeds the landed `.mid`
- * filename's human-readable prefix.
+ * filename's human-readable prefix. `destDir` picks where the `.mid` lands —
+ * uploads by default (the rounds path); the music video route passes
+ * `PATHS.music` so the file federates to peers alongside the project's other
+ * audio (the peer-sync asset manifest only ships known directories).
*/
-export async function startMidiTranscription({ audioPath, outputName = 'transcription', model, onComplete }) {
+export async function startMidiTranscription({ audioPath, outputName = 'transcription', model, onComplete, destDir = PATHS.uploads }) {
const pythonPath = resolveMuscriptorPython();
if (!pythonPath) {
throw new ServerError(MUSCRIPTOR_INSTALL_HINT, { status: 503, code: 'MIDI_RUNTIME_MISSING' });
@@ -146,7 +150,7 @@ export async function startMidiTranscription({ audioPath, outputName = 'transcri
}
broadcastSse(job, { type: 'progress', stage: 'importing' });
- const { filename } = await importFileToUploads(tempOut, `${outputName}.mid`);
+ const { filename } = await importFileToDir(tempOut, `${outputName}.mid`, destDir);
const extra = (await onComplete?.({ filename, model: resolvedModel })) || {};
console.log(`🎹 MIDI transcription ${shortId(jobId)} complete — ${filename}`);
diff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.js
index 5c1786c7da..18e0cc4531 100644
--- a/server/services/sharing/peerSyncAssets.js
+++ b/server/services/sharing/peerSyncAssets.js
@@ -415,6 +415,8 @@ async function videoHistoryFilenamesById() {
* `music:<filename>` ships it exactly once. The track is dynamic-resolved via
* `getTrack`; a deleted/missing track or a track with no `audioFilename` simply
* contributes nothing (a missing file is skipped, same as every other ref).
+ * The project's MuScriptor MIDI transcription (`midiTranscription.filename`)
+ * also lives under PATHS.music and ships through the same `music` entries.
* - per-scene rendered clips (`scene.videoHistoryId` → a video-history row →
* `<filename>` under PATHS.videos). The row METADATA union-merges via the
* `videoHistory` dataSync category; this adds the bytes. Falls back to the
@@ -441,6 +443,10 @@ export async function buildMusicVideoAssetManifest(project) {
const track = await getTrack(project.trackId).catch(() => null);
if (isStr(track?.audioFilename)) audioNames.push(track.audioFilename);
}
+ // MuScriptor MIDI transcription of the master audio — lands under PATHS.music
+ // precisely so it rides this manifest; without it a subscribed peer receives
+ // a `midiTranscription.filename` pointer whose bytes never arrive.
+ if (isStr(project?.midiTranscription?.filename)) audioNames.push(project.midiTranscription.filename);
for (const name of [...new Set(audioNames)]) {
const audio = await hashSimpleAsset(name, 'music', PATHS.music);
if (audio) dedup.set(`${audio.kind}:${audio.filename}`, audio);
diff --git a/server/services/sharing/peerSyncAssets.test.js b/server/services/sharing/peerSyncAssets.test.js
index f907a2dd31..824e405744 100644
--- a/server/services/sharing/peerSyncAssets.test.js
+++ b/server/services/sharing/peerSyncAssets.test.js
@@ -89,6 +89,19 @@ describe('buildMusicVideoAssetManifest — master audio', () => {
expect(manifest).toEqual([]);
});
+ it('bundles the MuScriptor MIDI transcription alongside the master audio', async () => {
+ const audioBytes = Buffer.from('uploaded-audio');
+ const midiBytes = Buffer.from('MThd-midi-bytes');
+ writeMusic('upload.mp3', audioBytes);
+ writeMusic('neon-midi.mid', midiBytes);
+ const manifest = await buildMusicVideoAssetManifest({
+ trackId: null, uploadedAudioFilename: 'upload.mp3', scenes: [],
+ midiTranscription: { filename: 'neon-midi.mid', model: 'medium' },
+ });
+ expect(manifest).toContainEqual({ filename: 'upload.mp3', kind: 'music', sha256: sha(audioBytes) });
+ expect(manifest).toContainEqual({ filename: 'neon-midi.mid', kind: 'music', sha256: sha(midiBytes) });
+ });
+
it('dedups when the upload basename and the linked track point at the same file', async () => {
const bytes = Buffer.from('shared');
writeMusic('shared.mp3', bytes);