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
feat(issue-1945): import a track's audio from a YouTube URL via yt-dlp
[._.]/ Adam Eivy2676882fdd10
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 7623af577d..8af667c9a4 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -10,6 +10,8 @@## Music Video+- **[issue-1945] Import a track's audio straight from a YouTube URL.** Both the project-create form and an existing project's detail view now have a "paste a YouTube URL" field next to the track picker (the detail view also gained the ability to change a project's linked track after creation, which wasn't previously possible at all). PortOS downloads the video and extracts just its audio via `yt-dlp` (a new host dependency — install it the same way you installed `ffmpeg`), lands it in the shared music library as a new Track, and links it to the project automatically. Progress streams live (download % → extracting → importing) with a Cancel button, mirroring the render job's progress UI. `POST /api/tracks/import/youtube` is a library-level endpoint (`server/services/trackYoutubeImport.js`, `server/lib/ytdlp.js`), so any project's track picker can reuse an imported track without re-downloading.+- **[issue-1854] Beat-quantized timeline arranger: drag-snap scenes to the beat grid.** The director board's scene list now sits above an interactive **beat-grid timeline** (built from the project's cached audio analysis) showing section bands, beats, and downbeats. Drag a scene's right edge to trim how long it plays, or drag its body to reposition it — both snap to the nearest beat, downbeat, or section boundary within a small tolerance; an unsnapped drop is left exactly where you placed it. A confirmed (snapped) length-trim is marked **beat-aligned** and now renders *exactly* as arranged: the render's beat-snap step (`beatSnapClips`) honors a beat-aligned scene's saved `startSec`/`endSec` outright instead of re-deriving the cut from whichever beats happen to be nearby at render time — a reposition-only drag never marks a scene beat-aligned unless it already had a real, explicitly-set duration, so simply nudging a freshly-added scene can't silently crop its clip down to the timeline's placeholder length. Auto-arranging scenes across the song's sections by energy is filed as a follow-up (#1915). (Closes #1854)- **[issue-1915] Auto-arrange scenes across song sections by energy.** A one-click **Auto-arrange** button on the Music Video scene board distributes every scene across the analyzed song's sections weighted by each section's energy — louder sections get more (shorter) cuts, calmer sections get fewer (longer) ones — and writes the same persisted `startSec`/`endSec`/`beatAligned` fields the manual drag-snap arranger (#1854) writes, so the result is a director-tunable starting point honored exactly at render time. The offline audio analysis now records a normalized 0..1 `energy` per section (additive/optional — older cached analyses fall back to an even spread; re-run **Analyze** to populate it). The distribution is a pure, isolated helper — `autoArrangeScenes(scenes, audioAnalysis)` in `client/src/lib/beatGrid.js` (largest-remainder allocation by energy weight, interior cuts snapped to the beat grid) — unit-tested independently of the UI. (Closes #1915)diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 51d8675a51..67b9ca69ad 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -146,3 +146,4 @@ grep -i "what you want to do" client/src/hooks/README.md| `useUniverseNav` | `goToWorld(id)` → navigate to `/universes/:id`, preserve `location.search`. | Any Universe Builder caller that needs to switch worlds via URL. || `useVoiceUiSync` | Keeps voice server's UI index in sync with current page. | Wire once at root for voice agent support. || `useMoltworldWs` | Moltworld WebSocket feed. | Moltworld surfaces only. |+| `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). |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex d22e5c2607..7461fccd0d 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -44,6 +44,7 @@ export { default as useRowDraft } from './useRowDraft.js';export { default as useTheme } from './useTheme.js';export { default as useUniverse } from './useUniverse.js';export { default as useUniverseAction } from './useUniverseAction.js';+export { default as useYoutubeTrackImport } from './useYoutubeTrackImport.js';// === Mixed (both default and named) — surface both ===export { default as useAsyncAction } from './useAsyncAction.js';diff --git a/client/src/hooks/useYoutubeTrackImport.js b/client/src/hooks/useYoutubeTrackImport.jsnew file mode 100644index 0000000000..d99b987e22--- /dev/null+++ b/client/src/hooks/useYoutubeTrackImport.js@@ -0,0 +1,63 @@+import { useEffect, useState } from 'react';+import toast from '../components/ui/Toast';+import { importTrackFromYoutube, cancelTrackImport, trackImportEventsUrl } from '../services/apiTracks.js';+import { useSseProgress, isTerminalSseFrame } from './useSseProgress.js';++/**+ * One YouTube-audio-import job slot (#1945) — start/cancel + SSE progress ++ * terminal-frame handling. Call it once per UI surface that can independently+ * kick off an import (e.g. the create form and an existing project's track+ * picker) so two surfaces each own their own job and SSE subscription; a+ * single shared slot would let a second surface's kickoff silently orphan the+ * first surface's in-flight job (its SSE subscription would never re-attach).+ *+ * `onComplete(track, context)` fires once the import lands a Track — `context`+ * is whatever was passed to `start(url, context)`, captured at kickoff time so+ * a slow-finishing job still attaches to the right target even if the caller's+ * own state (e.g. which project is selected) changes while it's in flight.+ */+export default function useYoutubeTrackImport({ onComplete } = {}) {+ const [job, setJob] = useState(null); // { jobId, context }+ const sse = useSseProgress(job ? trackImportEventsUrl(job.jobId) : null);+ const percent = Math.round(sse.latest?.percent ?? 0);++ useEffect(() => {+ const frame = sse.latest;+ if (!job || !frame) return;+ if (frame.type === 'complete') {+ onComplete?.(frame.track, job.context);+ toast.success(`Imported "${frame.track.title}" from YouTube`);+ setJob(null);+ } else if (frame.type === 'error') {+ toast.error(frame.error || 'YouTube import failed');+ setJob(null);+ } else if (frame.type === 'canceled' || frame.type === 'cancelled') {+ toast.info('YouTube import cancelled');+ setJob(null);+ }+ }, [sse.latest]);++ // Stream closed without a terminal frame (server restart mid-import, or the+ // job was pruned before/after attach) — recover so the spinner can't hang.+ useEffect(() => {+ if (job && sse.closed && !isTerminalSseFrame(sse.latest)) {+ setJob(null);+ toast.info('Lost connection to the YouTube import — check the music library');+ }+ }, [sse.closed]);++ const start = (url, context) => {+ const trimmed = url.trim();+ if (!trimmed) return;+ importTrackFromYoutube(trimmed, { silent: true })+ .then(({ jobId }) => setJob({ jobId, context }))+ .catch((err) => toast.error(err?.message || 'Failed to start YouTube import'));+ };++ const cancel = () => {+ if (!job) return;+ cancelTrackImport(job.jobId, { silent: true }).catch(() => {});+ };++ return { active: !!job, percent, start, cancel };+}diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 97816e0794..73012eee21 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -1,10 +1,11 @@import { useEffect, useState, useCallback } from 'react';-import { Plus, Film, Trash2, Music, Activity, ArrowUp, ArrowDown, Image as ImageIcon, Video, Wand2 } from 'lucide-react';+import { Plus, Film, Trash2, Music, Activity, ArrowUp, ArrowDown, Image as ImageIcon, Video, Wand2, Download } from 'lucide-react';import toast from '../components/ui/Toast';import PageHeader from '../components/PageHeader';import {listMusicVideoProjects,createMusicVideoProject,+ updateMusicVideoProject,deleteMusicVideoProject,analyzeMusicVideoProject,planMusicVideoProject,@@ -22,6 +23,7 @@ import { listTracks } from '../services/apiTracks.js';import BeatTimeline from '../components/musicVideo/BeatTimeline.jsx';import { autoArrangeScenes } from '../lib/beatGrid.js';import useSceneRenderLifecycle from '../hooks/useSceneRenderLifecycle.js';+import useYoutubeTrackImport from '../hooks/useYoutubeTrackImport.js';import { useSseProgress, isTerminalSseFrame } from '../hooks/useSseProgress.js';import { formatDurationSec } from '../utils/formatters.js';@@ -39,6 +41,36 @@ const STATUS_COLORS = {failed: 'bg-port-error/30 text-port-error',};+// The URL input + Import/Cancel button pairing for a useYoutubeTrackImport+// slot — shared by the create form (full-size) and the detail view's+// track-change row (compact, inline in a flex-wrap toolbar). #1945+function YoutubeImportControls({ id, url, onUrlChange, job, onStart, compact = false }) {+ const size = compact ? 12 : 13;+ const py = compact ? 'py-1' : 'py-1.5';+ const btnExtra = compact ? '' : 'text-xs whitespace-nowrap min-h-[40px] sm:min-h-0';+ return (+ <>+ <input+ id={id} type="url" value={url} onChange={onUrlChange} disabled={job.active}+ placeholder="Import audio from a YouTube URL…" aria-label="Import audio from a YouTube URL"+ className={`${compact ? 'flex-1 min-w-[160px]' : 'flex-1 min-w-0'} bg-port-bg border border-port-border rounded px-2 ${py} text-sm disabled:opacity-50`}+ />+ {job.active ? (+ <button type="button" onClick={job.cancel}+ className={`flex items-center gap-1 bg-port-warning/20 text-port-warning border border-port-border rounded px-2 ${py} ${btnExtra}`}>+ <Activity size={size} className="animate-spin" /> {job.percent}%+ </button>+ ) : (+ <button type="button" onClick={onStart} disabled={!url.trim()}+ title="Download and extract this video's audio as a track"+ className={`flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 ${py} ${btnExtra} disabled:opacity-50`}>+ <Download size={size} /> Import+ </button>+ )}+ </>+ );+}+export default function MusicVideo() {const [projects, setProjects] = useState([]);const [tracks, setTracks] = useState([]);@@ -49,6 +81,30 @@ export default function MusicVideo() {const [planning, setPlanning] = useState(false);const [form, setForm] = useState({ name: '', mode: 'director', trackId: '' });const selected = projects.find((p) => p.id === selectedId) || null;++ // YouTube audio import (#1945): paste a URL, PortOS downloads + extracts the+ // track via yt-dlp and lands it in the shared library. Two independent job+ // slots — one per surface that can kick off an import — so starting one+ // doesn't orphan the other's in-flight job (see useYoutubeTrackImport).+ const [ytUrlCreate, setYtUrlCreate] = useState('');+ const [ytUrlEdit, setYtUrlEdit] = useState('');+ const attachImportedTrack = (track) => setTracks((prev) => [...prev, track]);+ const ytImportCreate = useYoutubeTrackImport({+ onComplete: (track) => {+ attachImportedTrack(track);+ setForm((f) => ({ ...f, trackId: track.id }));+ setYtUrlCreate('');+ },+ });+ const ytImportEdit = useYoutubeTrackImport({+ onComplete: (track, projectId) => {+ attachImportedTrack(track);+ updateMusicVideoProject(projectId, { trackId: track.id }, { silent: true })+ .then((proj) => replaceProject(proj))+ .catch((err) => toast.error(err?.message || 'Imported the track but failed to attach it to the project'));+ setYtUrlEdit('');+ },+ });const replaceProject = (next) => setProjects((prev) => prev.map((p) => (p.id === next.id ? next : p)));// 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@@ -251,6 +307,16 @@ export default function MusicVideo() {cancelMusicVideoRender(render.jobId, { silent: true }).catch(() => {});};+ // Re-point the selected project at a different library track (the detail+ // view's "Change track" picker — previously there was no way to relink a+ // project's audio after creation at all).+ const handleChangeTrack = (trackId) => {+ if (!selected) return;+ updateMusicVideoProject(selected.id, { trackId }, { silent: true })+ .then((proj) => replaceProject(proj))+ .catch((err) => toast.error(err?.message || 'Failed to change track'));+ };+const handleAddScene = () => {addMusicVideoScene(selected.id, { prompt: '' }).then((scene) => replaceProject({ ...selected, scenes: [...(selected.scenes || []), scene] }))@@ -395,6 +461,16 @@ export default function MusicVideo() {<option value="">— no track —</option>{tracks.map((t) => <option key={t.id} value={t.id}>{t.title || t.id}</option>)}</select>+ <label htmlFor="mv-yt-create" className="block text-xs text-port-text-muted">…or import audio from YouTube</label>+ <div className="flex gap-1">+ <YoutubeImportControls+ id="mv-yt-create" url={ytUrlCreate} onUrlChange={(e) => setYtUrlCreate(e.target.value)}+ job={ytImportCreate} onStart={() => ytImportCreate.start(ytUrlCreate)}+ />+ </div>+ {form.trackId && !ytImportCreate.active && (+ <p className="text-xs text-port-text-muted">Track set: {trackName(form.trackId)}</p>+ )}<button type="submit" className="w-full flex items-center justify-center gap-1 bg-port-accent text-white rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0"><Plus size={16} /> Create</button>@@ -465,6 +541,22 @@ export default function MusicVideo() {</button></div></div>+ {/* Track picker — pick an existing library track or import fresh audio+ from YouTube. Re-selecting either PATCHes the project's trackId. */}+ <div className="mt-2 flex flex-wrap items-center gap-2 text-xs">+ <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)}+ className="bg-port-bg border border-port-border rounded px-1.5 py-1">+ <option value="">Change track…</option>+ {tracks.map((t) => <option key={t.id} value={t.id}>{t.title || t.id}</option>)}+ </select>+ <YoutubeImportControls+ url={ytUrlEdit} onUrlChange={(e) => setYtUrlEdit(e.target.value)}+ job={ytImportEdit} onStart={() => ytImportEdit.start(ytUrlEdit, selected.id)}+ compact+ />+ </div>{render && (<div className="mt-2"><div className="h-1.5 bg-port-bg rounded overflow-hidden">diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex 5a0a2b0ac5..df8fc82917 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -3,7 +3,7 @@* gates on a scene having a generated clip, and clicking it kicks off the render.*/import { describe, it, expect, vi, beforeEach } from 'vitest';-import { render, screen, waitFor, fireEvent } from '@testing-library/react';+import { render, screen, waitFor, fireEvent, within } from '@testing-library/react';const PROJECT_WITH_CLIP = {id: 'mv-1', name: 'Neon Run', mode: 'director', status: 'ready',@@ -15,11 +15,26 @@ const PROJECT_NO_CLIP = {scenes: [{ sceneId: 's1', order: 0, prompt: 'a', referenceImageId: 'img1', videoHistoryId: null }],};-const { sseState } = vi.hoisted(() => ({ sseState: { latest: null, closed: false, frames: [], isOpen: false } }));+// The render job gets its own fixed state. The two independent YouTube-import+// job slots (create form + detail-view track picker, #1945) each get a state+// object keyed by their subscription URL (which encodes the jobId) — a single+// shared state would leak one slot's terminal frame into the other's.+const { sseState, ytSseStates, getYtSseState } = vi.hoisted(() => {+ const states = new Map();+ return {+ sseState: { latest: null, closed: false, frames: [], isOpen: false },+ ytSseStates: states,+ getYtSseState: (url) => {+ if (!states.has(url)) states.set(url, { latest: null, closed: false, frames: [], isOpen: false });+ return states.get(url);+ },+ };+});vi.mock('../services/apiMusicVideo.js', () => ({listMusicVideoProjects: vi.fn(async () => []),createMusicVideoProject: vi.fn(),+ updateMusicVideoProject: vi.fn(async (id, patch) => ({ id, ...patch })),deleteMusicVideoProject: vi.fn(),analyzeMusicVideoProject: vi.fn(),planMusicVideoProject: vi.fn(),@@ -33,16 +48,29 @@ vi.mock('../services/apiMusicVideo.js', () => ({}));vi.mock('../services/apiSystem.js', () => ({ generateImage: vi.fn() }));vi.mock('../services/apiImageVideo.js', () => ({ generateVideo: vi.fn() }));-vi.mock('../services/apiTracks.js', () => ({ listTracks: vi.fn(async () => []) }));+vi.mock('../services/apiTracks.js', () => ({+ listTracks: vi.fn(async () => []),+ importTrackFromYoutube: vi.fn(async () => ({ jobId: 'yt-job-1' })),+ trackImportEventsUrl: (jobId) => `/api/tracks/import/${jobId}/events`,+ cancelTrackImport: vi.fn(async () => ({ ok: true })),+}));vi.mock('../hooks/useSceneRenderLifecycle.js', () => ({default: () => ({ genScenes: {}, startScene: vi.fn(), clearScene: vi.fn(), trackJob: vi.fn() }),}));-vi.mock('../hooks/useSseProgress.js', () => ({ useSseProgress: () => sseState }));+const TERMINAL_TYPES = new Set(['complete', 'canceled', 'cancelled', 'error']);+vi.mock('../hooks/useSseProgress.js', () => ({+ useSseProgress: (url) => {+ if (!url) return { latest: null, closed: false, frames: [], isOpen: false };+ return url.includes('/tracks/import/') ? getYtSseState(url) : sseState;+ },+ isTerminalSseFrame: (frame) => TERMINAL_TYPES.has(frame?.type),+}));vi.mock('../components/ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), info: vi.fn() } }));vi.mock('../components/PageHeader', () => ({ default: ({ title }) => <div>{title}</div> }));import MusicVideo from './MusicVideo.jsx';-import { listMusicVideoProjects, renderMusicVideoProject, planMusicVideoProject } from '../services/apiMusicVideo.js';+import { listMusicVideoProjects, renderMusicVideoProject, planMusicVideoProject, updateMusicVideoProject } from '../services/apiMusicVideo.js';+import { importTrackFromYoutube, trackImportEventsUrl } from '../services/apiTracks.js';const PROJECT_ANALYZED = {...PROJECT_NO_CLIP,@@ -63,6 +91,7 @@ beforeEach(() => {vi.clearAllMocks();sseState.latest = null;sseState.closed = false;+ ytSseStates.clear();});describe('MusicVideo render control (#1760)', () => {@@ -108,3 +137,76 @@ describe('MusicVideo autonomous shot planner (#1855)', () => {await waitFor(() => expect(planMusicVideoProject).toHaveBeenCalledWith('mv-3', { seedPrompts: true }));});});++describe('MusicVideo YouTube audio import (#1945)', () => {+ it('starts an import from the detail view and attaches the finished track to the project', async () => {+ await openProject(PROJECT_NO_CLIP);+ // Two matches now (create form + detail-view row share the same+ // placeholder/aria-label) — the create form's carries the `mv-yt-create`+ // id, so the other one is the detail view's.+ const urlInput = screen.getAllByPlaceholderText(/Import audio from a YouTube URL/i)+ .find((el) => el.id !== 'mv-yt-create');+ fireEvent.change(urlInput, { target: { value: 'https://youtu.be/dQw4w9WgXcQ' } });+ const row = urlInput.closest('div');+ fireEvent.click(within(row).getByRole('button', { name: /Import/i }));+ await waitFor(() => expect(importTrackFromYoutube).toHaveBeenCalledWith('https://youtu.be/dQw4w9WgXcQ', { silent: true }));++ // Simulate the SSE terminal frame the job's kickoff subscribed to. The mock+ // hook returns a plain mutable object (not real React state), so mutating+ // it alone doesn't trigger a re-render — nudge one via an unrelated input+ // so the component re-reads the hook and its effect dependency changes.+ const url = trackImportEventsUrl('yt-job-1');+ getYtSseState(url).latest = {+ type: 'complete', trackId: 'track-yt-1', track: { id: 'track-yt-1', title: 'Imported Song' },+ };+ fireEvent.change(screen.getByPlaceholderText('Project name'), { target: { value: 'x' } });+ await waitFor(() => expect(updateMusicVideoProject).toHaveBeenCalledWith('mv-2', { trackId: 'track-yt-1' }, { silent: true }));+ });++ it('disables the Import button until a URL is entered', async () => {+ await openProject(PROJECT_NO_CLIP);+ const importBtns = screen.getAllByRole('button', { name: /Import/i });+ importBtns.forEach((btn) => expect(btn).toHaveProperty('disabled', true));+ });++ it('running the create-form and detail-view imports at once does not orphan either job', async () => {+ await openProject(PROJECT_NO_CLIP);+ importTrackFromYoutube+ .mockResolvedValueOnce({ jobId: 'yt-job-create' })+ .mockResolvedValueOnce({ jobId: 'yt-job-edit' });++ const inputs = screen.getAllByPlaceholderText(/Import audio from a YouTube URL/i);+ const createInput = inputs.find((el) => el.id === 'mv-yt-create');+ const editInput = inputs.find((el) => el.id !== 'mv-yt-create');++ fireEvent.change(createInput, { target: { value: 'https://youtu.be/create111' } });+ fireEvent.click(within(createInput.closest('div')).getByRole('button', { name: /Import/i }));+ await waitFor(() => expect(importTrackFromYoutube).toHaveBeenCalledWith('https://youtu.be/create111', { silent: true }));++ fireEvent.change(editInput, { target: { value: 'https://youtu.be/edit222' } });+ fireEvent.click(within(editInput.closest('div')).getByRole('button', { name: /Import/i }));+ await waitFor(() => expect(importTrackFromYoutube).toHaveBeenCalledWith('https://youtu.be/edit222', { silent: true }));++ // Both slots must independently show themselves as in-flight — a shared+ // slot would have the second kickoff silently take over the first's spot.+ const cancelBtns = screen.getAllByRole('button', { name: /%$/ });+ expect(cancelBtns).toHaveLength(2);++ // Completing the EDIT job must attach to the project without disturbing+ // the still-in-flight CREATE job.+ getYtSseState(trackImportEventsUrl('yt-job-edit')).latest = {+ type: 'complete', trackId: 'track-edit', track: { id: 'track-edit', title: 'Edit Track' },+ };+ fireEvent.change(screen.getByPlaceholderText('Project name'), { target: { value: 'x' } });+ await waitFor(() => expect(updateMusicVideoProject).toHaveBeenCalledWith('mv-2', { trackId: 'track-edit' }, { silent: true }));+ // The create-form job is still running — its Cancel/percent button remains.+ expect(screen.getAllByRole('button', { name: /%$/ })).toHaveLength(1);++ // Completing the CREATE job independently attaches to the form.+ getYtSseState(trackImportEventsUrl('yt-job-create')).latest = {+ type: 'complete', trackId: 'track-create', track: { id: 'track-create', title: 'Create Track' },+ };+ fireEvent.change(screen.getByPlaceholderText('Project name'), { target: { value: 'y' } });+ await waitFor(() => expect(screen.getByText(/Track set: Create Track/i)).toBeTruthy());+ });+});diff --git a/client/src/services/apiTracks.js b/client/src/services/apiTracks.jsindex 48cac03655..d87dd14bea 100644--- a/client/src/services/apiTracks.js+++ b/client/src/services/apiTracks.js@@ -30,6 +30,23 @@ export const deleteTrack = (id, requestOptions = {}) => request(`/tracks/${encod// attach an existing track without re-uploading.export const listMusicLibrary = (options = {}) => request('/tracks/library', options);+// --- YouTube import (#1945) — download + extract a track's audio via yt-dlp,+// land it in the shared library, and create a Track. Kickoff returns { jobId };+// progress streams over SSE (subscribe with useSseProgress).+export const importTrackFromYoutube = (url, options = {}) => request('/tracks/import/youtube', {+ method: 'POST',+ body: JSON.stringify({ url }),+ ...options,+});++export const trackImportEventsUrl = (jobId) =>+ `/api/tracks/import/${encodeURIComponent(jobId)}/events`;++export const cancelTrackImport = (jobId, options = {}) => request(`/tracks/import/${encodeURIComponent(jobId)}/cancel`, {+ method: 'POST',+ ...options,+});+// Attach an existing library track (by stored filename) to this track.export const attachTrackAudio = (id, filename, requestOptions = {}) => request(`/tracks/${encodeURIComponent(id)}/audio/attach`, {method: 'POST',diff --git a/server/lib/README.md b/server/lib/README.mdindex d2508e0fef..548f17f679 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -145,6 +145,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `gitRemote.js` | `getOriginInfo`, `parseGitRemoteUrl`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — classifies the local `origin` remote vs the upstream atomantic/PortOS repo. Used by the update flow to detect forks. || `processEnv.js` | `stripDebugMallocEnv(env)` — drop macOS `Malloc*` debug env vars before spawning a child. Pinokio-launched PortOS exports `MallocStackLogging`/`MallocScribble`/etc. that flood Python subprocess stderr with `can't turn off malloc stack logging` lines; route every Node→Python spawn through this. No-op on Linux/Windows. || `pythonSetup.js` | Python venv / runner setup helpers. |+| `ytdlp.js` | `findYtDlp()` — cached discovery of the `yt-dlp` binary on PATH, mirrors `findFfmpeg()` in `ffmpeg.js`. Used by the track YouTube-import job. |## Networkingdiff --git a/server/lib/index.js b/server/lib/index.jsindex 7475962fdf..1d0c0b011d 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -136,6 +136,7 @@ export * from './gitRemote.js';export * from './openFolder.js';export * from './processEnv.js';export * from './pythonSetup.js';+export * from './ytdlp.js';// === Networking ===export * from './abortTimeout.js';diff --git a/server/lib/ytdlp.js b/server/lib/ytdlp.jsnew file mode 100644index 0000000000..60d1005c7e--- /dev/null+++ b/server/lib/ytdlp.js@@ -0,0 +1,29 @@+/**+ * yt-dlp discovery — mirrors `findFfmpeg()` in `./ffmpeg.js`. yt-dlp is a+ * system binary (not an npm dependency), same "install it yourself" posture+ * as ffmpeg: a Python-based downloader isn't something PortOS should vendor+ * or auto-install.+ */++import { execFile } from 'child_process';+import { existsSync } from 'fs';+import { promisify } from 'util';+import { safeChildProcessEnv } from './processEnv.js';++const execFileAsync = promisify(execFile);+const IS_WIN = process.platform === 'win32';++let cachedYtDlpPath;+export const findYtDlp = async () => {+ if (cachedYtDlpPath !== undefined) return cachedYtDlpPath;+ const candidates = IS_WIN+ ? ['C:\\Program Files\\yt-dlp\\yt-dlp.exe']+ : ['/opt/homebrew/bin/yt-dlp', '/usr/local/bin/yt-dlp', '/usr/bin/yt-dlp'];+ for (const p of candidates) {+ if (existsSync(p)) { cachedYtDlpPath = p; return p; }+ }+ const cmd = IS_WIN ? 'where' : 'which';+ const { stdout } = await execFileAsync(cmd, ['yt-dlp'], { env: safeChildProcessEnv(), timeout: 5000 }).catch(() => ({ stdout: '' }));+ cachedYtDlpPath = stdout.trim().split(/\r?\n/)[0] || null;+ return cachedYtDlpPath;+};diff --git a/server/routes/tracks.js b/server/routes/tracks.jsindex fb8462f249..9536632056 100644--- a/server/routes/tracks.js+++ b/server/routes/tracks.js@@ -4,6 +4,9 @@* GET /api/tracks → Track[] (live, creation order)* POST /api/tracks → Track* GET /api/tracks/library → { tracks } (shared music library list)+ * POST /api/tracks/import/youtube → { jobId } (download + extract audio from a YouTube URL)+ * GET /api/tracks/import/:jobId/events → SSE progress for a YouTube import job+ * POST /api/tracks/import/:jobId/cancel → { ok }* GET /api/tracks/:id → Track* PATCH /api/tracks/:id → Track* DELETE /api/tracks/:id → { id } (soft delete)@@ -16,6 +19,10 @@* generated there. Bounds come from services/tracks/logic.js. Mirrors the* artists/albums routes plus the audio-attach surface from the pipeline audio* stage. Deleting a track does NOT delete its library audio (it may be shared).+ *+ * The YouTube import (#1945) is a library-level action (not per-track) — it+ * lands a new Track in the library, same as an upload, so any project's track+ * picker can attach it afterward without re-downloading.*/import { Router } from 'express';@@ -29,6 +36,9 @@ import {listMusicLibrary, importUploadedTrack, statMusicTrack,isSupportedMusicUpload, assertSafeMusicFilename, MUSIC_UPLOAD_MAX_BYTES,} from '../services/pipeline/musicLibrary.js';+import {+ startYoutubeImport, attachImportSseClient, cancelYoutubeImport, YOUTUBE_URL_RE,+} from '../services/trackYoutubeImport.js';const router = Router();@@ -85,6 +95,10 @@ const attachSchema = z.object({filename: z.string().trim().min(1).max(tracks.AUDIO_FILENAME_MAX),});+const youtubeImportSchema = z.object({+ url: z.string().trim().regex(YOUTUBE_URL_RE, 'Not a recognized YouTube URL (expected youtube.com/watch, youtu.be, or m.youtube.com)'),+});+// Reuse the pipeline audio stage's multipart upload contract (50MB, audio MIME).const musicUpload = uploadSingle('track', {limits: { fileSize: MUSIC_UPLOAD_MAX_BYTES },@@ -172,6 +186,24 @@ router.get('/library', asyncHandler(async (_req, res) => {res.json({ tracks: await listMusicLibrary() });}));+// YouTube audio import (#1945): download + extract a track's audio via yt-dlp,+// land it in the shared library, and create a Track pointing at it. Two-segment+// paths ('import/...') can't collide with the single-segment GET/:id below.+router.post('/import/youtube', asyncHandler(async (req, res) => {+ const { url } = validateRequest(youtubeImportSchema, req.body ?? {});+ res.status(202).json(await startYoutubeImport(url));+}));++router.get('/import/:jobId/events', (req, res) => {+ if (!attachImportSseClient(req.params.jobId, res)) {+ throw new ServerError('Import job not found or expired', { status: 404, code: 'NOT_FOUND' });+ }+});++router.post('/import/:jobId/cancel', (req, res) => {+ res.json({ ok: cancelYoutubeImport(req.params.jobId) });+});+router.post('/', asyncHandler(async (req, res) => {const body = validateRequest(createSchema, req.body ?? {});const track = await tracks.createTrack(body);diff --git a/server/routes/tracks.test.js b/server/routes/tracks.test.jsindex 2034f39023..4b04fb3fd5 100644--- a/server/routes/tracks.test.js+++ b/server/routes/tracks.test.js@@ -52,9 +52,16 @@ vi.mock('../services/albums/index.js', () => ({getAlbum: vi.fn(async () => null),updateAlbum: vi.fn(async (id, patch) => ({ id, ...patch })),}));+vi.mock('../services/trackYoutubeImport.js', () => ({+ YOUTUBE_URL_RE: /^https?:\/\/(www\.|m\.)?(youtube\.com\/watch\?[^\s#]*\bv=[\w-]{6,}|youtu\.be\/[\w-]{6,})/i,+ startYoutubeImport: vi.fn(async () => ({ jobId: 'job-1' })),+ attachImportSseClient: vi.fn(() => true),+ cancelYoutubeImport: vi.fn(() => true),+}));import * as musicLibrary from '../services/pipeline/musicLibrary.js';import * as albums from '../services/albums/index.js';+import * as ytImport from '../services/trackYoutubeImport.js';import { errorMiddleware } from '../lib/errorHandler.js';import tracksRoutes from './tracks.js';@@ -83,6 +90,39 @@ describe('tracks routes', () => {expect(tracks.getTrack).not.toHaveBeenCalled();});+ describe('YouTube import (#1945)', () => {+ it('POST /import/youtube starts a job for a valid URL', async () => {+ const r = await request(app).post('/api/tracks/import/youtube').send({ url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ' });+ expect(r.status).toBe(202);+ expect(r.body).toEqual({ jobId: 'job-1' });+ expect(ytImport.startYoutubeImport).toHaveBeenCalledWith('https://www.youtube.com/watch?v=dQw4w9WgXcQ');+ });++ it('POST /import/youtube accepts a youtu.be short link', async () => {+ const r = await request(app).post('/api/tracks/import/youtube').send({ url: 'https://youtu.be/dQw4w9WgXcQ' });+ expect(r.status).toBe(202);+ });++ it('POST /import/youtube rejects a non-YouTube URL (never reaches the service)', async () => {+ const r = await request(app).post('/api/tracks/import/youtube').send({ url: 'https://vimeo.com/12345' });+ expect(r.status).toBe(400);+ expect(ytImport.startYoutubeImport).not.toHaveBeenCalled();+ });++ it('GET /import/:jobId/events 404s when the job is unknown', async () => {+ ytImport.attachImportSseClient.mockReturnValueOnce(false);+ const r = await request(app).get('/api/tracks/import/missing/events');+ expect(r.status).toBe(404);+ });++ it('POST /import/:jobId/cancel proxies to the service', async () => {+ const r = await request(app).post('/api/tracks/import/job-1/cancel');+ expect(r.status).toBe(200);+ expect(r.body).toEqual({ ok: true });+ expect(ytImport.cancelYoutubeImport).toHaveBeenCalledWith('job-1');+ });+ });+it('POST / creates a track', async () => {const r = await request(app).post('/api/tracks').send({ title: 'Intro', engine: 'acestep' });expect(r.status).toBe(201);diff --git a/server/services/trackYoutubeImport.js b/server/services/trackYoutubeImport.jsnew file mode 100644index 0000000000..44ed07daa1--- /dev/null+++ b/server/services/trackYoutubeImport.js@@ -0,0 +1,184 @@+/**+ * Track YouTube import (#1945) — download + extract just the audio track from+ * a YouTube URL via yt-dlp, land it in the shared music library (data/music/),+ * and create a Track record pointing at it.+ *+ * Mirrors the render.js / loraDatasetCaption.js job pattern: kickoff returns a+ * jobId immediately, the download runs detached, progress streams over the+ * shared SSE helpers, and the client attaches with useSseProgress. A single+ * yt-dlp invocation does the whole job (`-x --audio-format mp3`, pointed at+ * our discovered ffmpeg via --ffmpeg-location) rather than a separate+ * download-then-ffmpeg-extract step — yt-dlp already shells out to ffmpeg+ * for the audio conversion internally, so a second pass would just re-decode.+ */++import { spawn } from 'child_process';+import { existsSync } from 'fs';+import { unlink } from 'fs/promises';+import { tmpdir } from 'os';+import { join, dirname } from 'path';+import { randomUUID } from 'crypto';+import { ServerError } from '../lib/errorHandler.js';+import { shortId, PATHS } from '../lib/fileUtils.js';+import { findFfmpeg, probeVideoDuration } from '../lib/ffmpeg.js';+import { findYtDlp } from '../lib/ytdlp.js';+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../lib/sseUtils.js';+import { safeChildProcessEnv } from '../lib/processEnv.js';+import { importUploadedTrack } from './pipeline/musicLibrary.js';+import { createTrack } from './tracks/index.js';++// youtube.com/watch, youtu.be, and m.youtube.com only (issue #1945 scope:+// "start narrow" — other video hosts are explicitly out of scope). This also+// constrains what a shelled-out yt-dlp will touch, even though args are+// passed as an array (no shell interpolation).+export const YOUTUBE_URL_RE = /^https?:\/\/(www\.|m\.)?(youtube\.com\/watch\?[^\s#]*\bv=[\w-]{6,}|youtu\.be\/[\w-]{6,})/i;++export function assertYoutubeUrl(url) {+ if (typeof url !== 'string' || !YOUTUBE_URL_RE.test(url)) {+ throw new ServerError(+ 'Not a recognized YouTube URL (expected youtube.com/watch, youtu.be, or m.youtube.com)',+ { status: 400, code: 'YOUTUBE_URL_INVALID' },+ );+ }+}++// jobId -> { clients, lastPayload, process }+const importJobs = new Map();++export const attachImportSseClient = (jobId, res) => attachSse(importJobs, jobId, res);++/** Cancel an in-flight import. Returns false if the job is unknown or already finished. */+export function cancelYoutubeImport(jobId) {+ const job = importJobs.get(jobId);+ if (!job || !job.process) return false;+ const proc = job.process;+ proc.kill('SIGTERM');+ setTimeout(() => {+ if (job.process === proc && proc.exitCode === null && proc.signalCode === null) {+ console.log(`⚠️ yt-dlp import didn't exit on SIGTERM — escalating to SIGKILL`);+ proc.kill('SIGKILL');+ }+ }, 8000);+ return true;+}++const TITLE_PREFIX = 'PORTOS_TITLE:';+// Custom progress markers via yt-dlp's `--progress-template`, rather than+// scraping the human-readable `[download] NN%` / `[ExtractAudio]` console+// lines — a stable machine interface (mirrors ffmpeg's `-progress pipe:2`+// key=value protocol used by render.js) that a yt-dlp text-format change+// can't silently break.+const PROGRESS_PREFIX = 'PORTOS_PROGRESS:';+const STAGE_PREFIX = 'PORTOS_STAGE:';++/**+ * Kick off a YouTube audio import. Returns `{ jobId }` immediately; the+ * download+extract runs detached and streams progress over SSE. Terminal+ * frames: `{ type: 'complete', trackId, track }`, `{ type: 'error', error }`,+ * or `{ type: 'canceled' }`.+ */+export async function startYoutubeImport(url) {+ assertYoutubeUrl(url);++ // Independent lookups (each its own existsSync probes + which/where fallback) —+ // run concurrently rather than in series.+ const [ytDlp, ffmpeg] = await Promise.all([findYtDlp(), findFfmpeg()]);+ if (!ytDlp) throw new ServerError('yt-dlp not found on PATH', { status: 500, code: 'YTDLP_MISSING' });+ if (!ffmpeg) throw new ServerError('ffmpeg not found on PATH', { status: 500, code: 'FFMPEG_MISSING' });++ const jobId = randomUUID();+ // -x --audio-format mp3 forces the final container to mp3 regardless of the+ // source's native audio codec, so the output path is known up front.+ const tempBase = join(tmpdir(), `portos-ytimport-${jobId}`);+ const outPath = `${tempBase}.mp3`;++ const job = { id: jobId, status: 'running', clients: [], process: null };+ importJobs.set(jobId, job);+ console.log(`📺 YouTube import ${shortId(jobId)} — ${url}`);++ (async () => {+ let title = '';+ try {+ const args = [+ '-f', 'bestaudio/best',+ '-x', '--audio-format', 'mp3', '--audio-quality', '0',+ '--no-playlist',+ '--ffmpeg-location', dirname(ffmpeg),+ '--newline',+ '--print', `${TITLE_PREFIX}%(title)s`,+ '--progress-template', `download:${PROGRESS_PREFIX}%(progress._percent_str)s`,+ '--progress-template', `postprocess:${STAGE_PREFIX}extracting`,+ // `--print` has two side effects that would otherwise break this job+ // (confirmed against a real download): it implies `--simulate` (skips+ // the actual download/postprocess entirely, so `--no-simulate` is+ // required to force the real run), AND it suppresses ALL of yt-dlp's+ // normal progress/postprocessor reporting — so `--progress` plus the+ // two `--progress-template`s above are required to get stable,+ // machine-readable progress/stage markers back alongside the printed+ // title in one invocation.+ '--no-simulate',+ '--progress',+ '-o', `${tempBase}.%(ext)s`,+ 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();+ return;+ }+ if (line.startsWith(PROGRESS_PREFIX)) {+ const percent = parseFloat(line.slice(PROGRESS_PREFIX.length));+ if (Number.isFinite(percent)) broadcastSse(job, { type: 'progress', percent });+ return;+ }+ if (line.startsWith(STAGE_PREFIX)) {+ 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);+ };+ proc.stdout.on('data', onData);+ proc.stderr.on('data', onData); // 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}` }));+ proc.on('close', (code, signal) => resolve({ code, signal }));+ });+ job.process = null;++ if (exit.signal === 'SIGTERM' || exit.signal === 'SIGKILL') {+ console.log(`🛑 YouTube import ${shortId(jobId)} cancelled`);+ broadcastSse(job, { type: 'canceled' });+ await unlink(outPath).catch(() => {});+ return;+ }+ if (exit.code !== 0 || !existsSync(outPath)) {+ throw new Error(exit.reason || `yt-dlp exited ${exit.code}`);+ }++ broadcastSse(job, { type: 'progress', percent: 100, stage: 'importing' });+ const { filename } = await importUploadedTrack(outPath, `${title || 'YouTube Import'}.mp3`);+ const durationSec = await probeVideoDuration(join(PATHS.music, filename)).catch(() => null);+ const track = await createTrack({ title: title || 'YouTube Import', audioFilename: filename, durationSec });++ console.log(`📺 YouTube import ${shortId(jobId)} complete — track=${shortId(track.id)} "${track.title}"`);+ broadcastSse(job, { type: 'complete', trackId: track.id, track });+ } 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(() => {});+ } finally {+ closeJobAfterDelay(importJobs, jobId);+ }+ })();++ return { jobId };+}diff --git a/server/services/trackYoutubeImport.test.js b/server/services/trackYoutubeImport.test.jsnew file mode 100644index 0000000000..f33261d0e9--- /dev/null+++ b/server/services/trackYoutubeImport.test.js@@ -0,0 +1,78 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../lib/ytdlp.js', () => ({ findYtDlp: vi.fn(async () => '/usr/local/bin/yt-dlp') }));+vi.mock('../lib/ffmpeg.js', () => ({+ findFfmpeg: vi.fn(async () => '/usr/local/bin/ffmpeg'),+ probeVideoDuration: vi.fn(async () => 120),+}));+vi.mock('./pipeline/musicLibrary.js', () => ({+ importUploadedTrack: vi.fn(async () => ({ filename: 'music-x.mp3', sizeBytes: 10 })),+}));+vi.mock('./tracks/index.js', () => ({+ createTrack: vi.fn(async (input) => ({ id: 'track-new', ...input })),+}));++const { findYtDlp } = await import('../lib/ytdlp.js');+const { findFfmpeg } = await import('../lib/ffmpeg.js');+const {+ YOUTUBE_URL_RE, assertYoutubeUrl, startYoutubeImport,+} = await import('./trackYoutubeImport.js');++beforeEach(() => {+ vi.clearAllMocks();+ findYtDlp.mockResolvedValue('/usr/local/bin/yt-dlp');+ findFfmpeg.mockResolvedValue('/usr/local/bin/ffmpeg');+});++describe('YOUTUBE_URL_RE / assertYoutubeUrl', () => {+ it('accepts a standard watch URL', () => {+ expect(YOUTUBE_URL_RE.test('https://www.youtube.com/watch?v=dQw4w9WgXcQ')).toBe(true);+ expect(() => assertYoutubeUrl('https://www.youtube.com/watch?v=dQw4w9WgXcQ')).not.toThrow();+ });++ it('accepts a youtu.be short link', () => {+ expect(YOUTUBE_URL_RE.test('https://youtu.be/dQw4w9WgXcQ')).toBe(true);+ });++ it('accepts an m.youtube.com link', () => {+ expect(YOUTUBE_URL_RE.test('https://m.youtube.com/watch?v=dQw4w9WgXcQ')).toBe(true);+ });++ it('accepts a watch URL with extra query params before v=', () => {+ expect(YOUTUBE_URL_RE.test('https://www.youtube.com/watch?list=PL123&v=dQw4w9WgXcQ')).toBe(true);+ });++ it('rejects a non-YouTube host', () => {+ expect(YOUTUBE_URL_RE.test('https://vimeo.com/12345')).toBe(false);+ expect(() => assertYoutubeUrl('https://vimeo.com/12345')).toThrow(/YouTube/);+ });++ it('rejects a youtube.com URL with no video id', () => {+ expect(YOUTUBE_URL_RE.test('https://www.youtube.com/watch?list=PL123')).toBe(false);+ });++ it('rejects a non-string input', () => {+ expect(() => assertYoutubeUrl(null)).toThrow();+ expect(() => assertYoutubeUrl(42)).toThrow();+ });+});++describe('startYoutubeImport — pre-spawn guards', () => {+ it('throws YTDLP_MISSING when yt-dlp is not found on PATH', async () => {+ findYtDlp.mockResolvedValue(null);+ await expect(startYoutubeImport('https://youtu.be/dQw4w9WgXcQ'))+ .rejects.toMatchObject({ status: 500, code: 'YTDLP_MISSING' });+ });++ it('throws FFMPEG_MISSING when ffmpeg is not found on PATH', async () => {+ findFfmpeg.mockResolvedValue(null);+ await expect(startYoutubeImport('https://youtu.be/dQw4w9WgXcQ'))+ .rejects.toMatchObject({ status: 500, code: 'FFMPEG_MISSING' });+ });++ it('rejects a non-YouTube URL before touching yt-dlp/ffmpeg discovery', async () => {+ await expect(startYoutubeImport('https://vimeo.com/12345'))+ .rejects.toMatchObject({ status: 400, code: 'YOUTUBE_URL_INVALID' });+ expect(findYtDlp).not.toHaveBeenCalled();+ });+});