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 (claude): fix cross-project import orphaning, stream buffer collision, temp file leak

[._.]/ Adam Eivy6f4471094235
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index 73012eee21..ebdb6747c0 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -106,6 +106,20 @@ export default function MusicVideo() {
},
});
const replaceProject = (next) => setProjects((prev) => prev.map((p) => (p.id === next.id ? next : p)));
+ // `ytImportEdit` is one shared job slot for the whole detail view (not
+ // per-project) — switching the selected project while it has an import in
+ // flight would silently orphan that job's SSE subscription (the finished
+ // track would land in the library but never get attached, since the
+ // completion handler's onComplete never fires for a target nobody is
+ // listening for anymore) and misattribute its progress UI to whichever
+ // project is now selected. Block switching until that import settles.
+ const selectProject = (id) => {
+ if (ytImportEdit.active && id !== selectedId) {
+ toast.error('Finish or cancel the in-progress YouTube import before switching projects');
+ return;
+ }
+ setSelectedId(id);
+ };
// Merge ONLY a scene's referenceImageId via a functional update so a render
// that resolves after the user edited the board can't clobber those edits with
// a stale project snapshot. Shared by the socket handler and the synchronous
@@ -162,7 +176,7 @@ export default function MusicVideo() {
createMusicVideoProject({ name: form.name.trim(), mode: form.mode, trackId: form.trackId || null })
.then((proj) => {
setProjects((prev) => [...prev, proj]);
- setSelectedId(proj.id);
+ selectProject(proj.id);
setForm({ name: '', mode: 'director', trackId: '' });
toast.success('Project created');
})
@@ -480,7 +494,7 @@ export default function MusicVideo() {
{loading && <p className="text-sm text-port-text-muted">Loading…</p>}
{!loading && projects.length === 0 && <p className="text-sm text-port-text-muted">No projects yet.</p>}
{projects.map((p) => (
- <button key={p.id} onClick={() => setSelectedId(p.id)}
+ <button key={p.id} onClick={() => selectProject(p.id)}
className={`w-full text-left px-3 py-2 rounded border ${selectedId === p.id ? 'border-port-accent bg-port-accent/10' : 'border-port-border bg-port-card'}`}>
<div className="flex items-center justify-between gap-2">
<span className="text-sm truncate">{p.name}</span>
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index df8fc82917..6d46b3e705 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -4,6 +4,7 @@
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor, fireEvent, within } from '@testing-library/react';
+import toast from '../components/ui/Toast';
const PROJECT_WITH_CLIP = {
id: 'mv-1', name: 'Neon Run', mode: 'director', status: 'ready',
@@ -209,4 +210,25 @@ describe('MusicVideo YouTube audio import (#1945)', () => {
fireEvent.change(screen.getByPlaceholderText('Project name'), { target: { value: 'y' } });
await waitFor(() => expect(screen.getByText(/Track set: Create Track/i)).toBeTruthy());
});
+
+ it('blocks switching projects while the detail-view import is in flight (single shared job slot)', async () => {
+ const projectB = { ...PROJECT_NO_CLIP, id: 'mv-3', name: 'Other Project' };
+ listMusicVideoProjects.mockResolvedValue([PROJECT_NO_CLIP, projectB]);
+ render(<MusicVideo />);
+ const listBtnA = await screen.findByRole('button', { name: new RegExp(PROJECT_NO_CLIP.name) });
+ fireEvent.click(listBtnA);
+
+ const editInput = screen.getAllByPlaceholderText(/Import audio from a YouTube URL/i)
+ .find((el) => el.id !== 'mv-yt-create');
+ fireEvent.change(editInput, { target: { value: 'https://youtu.be/xyz' } });
+ fireEvent.click(within(editInput.closest('div')).getByRole('button', { name: /Import/i }));
+ await waitFor(() => expect(importTrackFromYoutube).toHaveBeenCalled());
+
+ // Switching to the OTHER project while this one's import is in flight
+ // must be blocked — it would silently orphan the in-flight job's SSE
+ // subscription and misattribute its progress UI to the new selection.
+ fireEvent.click(screen.getByRole('button', { name: new RegExp(projectB.name) }));
+ expect(toast.error).toHaveBeenCalledWith(expect.stringMatching(/before switching projects/i));
+ expect(listBtnA).toHaveClass('border-port-accent');
+ });
});
diff --git a/server/services/trackYoutubeImport.js b/server/services/trackYoutubeImport.js
index 44ed07daa1..2680f92eec 100644
--- a/server/services/trackYoutubeImport.js
+++ b/server/services/trackYoutubeImport.js
@@ -14,7 +14,7 @@
import { spawn } from 'child_process';
import { existsSync } from 'fs';
-import { unlink } from 'fs/promises';
+import { readdir, unlink } from 'fs/promises';
import { tmpdir } from 'os';
import { join, dirname } from 'path';
import { randomUUID } from 'crypto';
@@ -71,6 +71,19 @@ const TITLE_PREFIX = 'PORTOS_TITLE:';
const PROGRESS_PREFIX = 'PORTOS_PROGRESS:';
const STAGE_PREFIX = 'PORTOS_STAGE:';
+// A cancelled/failed run may leave behind yt-dlp's PRE-extraction download
+// (native extension — .webm/.m4a/etc., only renamed to our known `.mp3`
+// AFTER a successful postprocess step), so cleanup can't just unlink one
+// known path — glob every temp file this job's prefix touched.
+async function cleanupTempFiles(jobId) {
+ const prefix = `portos-ytimport-${jobId}`;
+ const dir = tmpdir();
+ const entries = await readdir(dir).catch(() => []);
+ await Promise.all(
+ entries.filter((name) => name.startsWith(prefix)).map((name) => unlink(join(dir, name)).catch(() => {})),
+ );
+}
+
/**
* Kick off a YouTube audio import. Returns `{ jobId }` immediately; the
* download+extract runs detached and streams progress over SSE. Terminal
@@ -124,7 +137,6 @@ export async function startYoutubeImport(url) {
const proc = spawn(ytDlp, args, { env: safeChildProcessEnv(), stdio: ['ignore', 'pipe', 'pipe'] });
job.process = proc;
- let buf = '';
const onLine = (line) => {
if (line.startsWith(TITLE_PREFIX)) {
title = line.slice(TITLE_PREFIX.length).trim();
@@ -139,14 +151,20 @@ export async function startYoutubeImport(url) {
broadcastSse(job, { type: 'progress', percent: 100, stage: line.slice(STAGE_PREFIX.length) });
}
};
- const onData = (chunk) => {
- buf += chunk.toString();
- const lines = buf.split(/\r?\n/);
- buf = lines.pop();
- lines.forEach(onLine);
+ // Separate buffers per stream — stdout and stderr chunks arrive
+ // independently, so a shared buffer can complete a partial line from
+ // one stream with a chunk from the other, corrupting a marker line.
+ const makeLineReader = () => {
+ let buf = '';
+ return (chunk) => {
+ buf += chunk.toString();
+ const lines = buf.split(/\r?\n/);
+ buf = lines.pop();
+ lines.forEach(onLine);
+ };
};
- proc.stdout.on('data', onData);
- proc.stderr.on('data', onData); // yt-dlp writes some progress/info lines to stderr too
+ proc.stdout.on('data', makeLineReader());
+ proc.stderr.on('data', makeLineReader()); // yt-dlp writes some progress/info lines to stderr too
const exit = await new Promise((resolve) => {
proc.on('error', (err) => resolve({ code: null, reason: `spawn failed: ${err.message}` }));
@@ -157,7 +175,7 @@ export async function startYoutubeImport(url) {
if (exit.signal === 'SIGTERM' || exit.signal === 'SIGKILL') {
console.log(`🛑 YouTube import ${shortId(jobId)} cancelled`);
broadcastSse(job, { type: 'canceled' });
- await unlink(outPath).catch(() => {});
+ await cleanupTempFiles(jobId);
return;
}
if (exit.code !== 0 || !existsSync(outPath)) {
@@ -174,7 +192,7 @@ export async function startYoutubeImport(url) {
} catch (err) {
console.error(`❌ YouTube import ${shortId(jobId)} failed: ${err?.message || err}`);
broadcastSse(job, { type: 'error', error: err?.message || String(err) });
- await unlink(outPath).catch(() => {});
+ await cleanupTempFiles(jobId);
} finally {
closeJobAfterDelay(importJobs, jobId);
}