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-2120]): download reference audio from a URL via yt-dlp
Adam Eivye8af4b9cafaa
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex cde5fb350c..460e54f971 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -9,6 +9,7 @@- **[issue-2104] Fixed: 500 Miles' reference TikTok videos now show up on older installs.** The built-in "500 Miles" round shipped with three TikTok reference performances, but any install that already had its data saved from before those were added never picked them up — the Reference material section stayed empty. A one-time backfill now restores the three references for those installs, without touching anything you may have added of your own.- **[issue-2105] Fixed: "Hey Ho Nobody Home" now sings in D minor and stacks cleanly with its partner rounds.** The built-in round shipped with a mis-transcribed melody — centered on G with a major third — that contradicted its own key label and sounded a harsh clash when stacked with Ah Poor Bird and Rose Rose Rose Red in the Round Stack view. The melody is now the correct D-centered, all-natural minor tune (same shape, just the right key), so the three-round quodlibet is consonant. Older installs get the corrected melody automatically; a score you customized yourself is left untouched (use "Refresh from template" to pull the fix).- **[issue-2106] Learn the real parts from a reference recording.** A round reference (like a layered TikTok performance) can now carry attached audio — upload a file or capture through the mic while the video plays — and open in a new analysis view: see the waveform, mark the time ranges where each voice sings alone, and extract each range into a proposed part snapped to the round's tempo and key. Review the proposal side by side with the part you already have, with each bar flagged where the notes disagree, then apply it with one click (nothing changes until you Save). All analysis runs locally on your machine — no AI calls.+- **[issue-2120] Attach a reference's audio straight from a URL.** Following #2106's upload + mic-capture attach paths, a reference now also offers "Download from URL": paste a link (a TikTok performance, a YouTube clip, …) and PortOS downloads + extracts just the audio via `yt-dlp` into your uploads dir, ready to analyze like any other attached recording — with a live download-progress readout you can cancel. It's a best-effort convenience (scraping is brittle; upload and mic capture stay the primary paths) and requires `yt-dlp` installed on the host (detected at runtime, no new npm dependency — the same discovery the YouTube track import uses). The URL is SSRF-guarded (http(s) only; loopback/link-local/private-LAN hosts refused) and the download is bounded to a short-clip size/duration. Under the hood, the yt-dlp download+extract+SSE-progress core is now shared between this and the YouTube track import (#1945) rather than duplicated. (`server/services/ytdlpAudioImport.js`, `server/services/roundReferenceAudioImport.js`, `server/services/trackYoutubeImport.js`, `server/lib/fileUtils.js`, `server/routes/rounds.js`, `client/src/hooks/useReferenceAudioImport.js`, `client/src/components/songs/ReferenceAnalysis.jsx`)## Mediadiff --git a/client/src/components/songs/ReferenceAnalysis.jsx b/client/src/components/songs/ReferenceAnalysis.jsxindex 25d6081c47..82a2e8a419 100644--- a/client/src/components/songs/ReferenceAnalysis.jsx+++ b/client/src/components/songs/ReferenceAnalysis.jsx@@ -24,11 +24,12 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import {- ArrowLeft, AudioLines, Flag, FlagOff, Layers, Loader2, Mic, Play, Plus, Square, Trash2, Upload, Wand2, X,+ ArrowLeft, AudioLines, Download, Flag, FlagOff, Layers, Loader2, Mic, 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 useReferenceAudioImport from '../../hooks/useReferenceAudioImport.js';import { startMemoRecording, arrayBufferToBase64 } from '../../lib/audioRecorder';import { proposeSegmentScore, proposeStackedSegmentScore, diffScoreBars, PITCH_CLASS_NAMES } from '../../lib/referenceAnalysis';import { scoreHasMusic, parseScore } from '../../lib/scoreNotation';@@ -79,9 +80,18 @@ function SecondsInput({ valueMs, onCommit, ariaLabel }) {export function ReferenceAudioAttach({ reference, onUpdate }) {const [busy, setBusy] = useState(false);const [recording, setRecording] = useState(false);+ const [url, setUrl] = useState('');const fileRef = useRef(null);const handleRef = useRef(null);+ // "Download audio from URL" (#2120) — best-effort yt-dlp fetch straight onto+ // the reference. On completion the returned uploads-dir filename is set on the+ // draft (flipping to the attached state); the user Saves to keep it, same as+ // upload/mic capture.+ const audioImport = useReferenceAudioImport({+ onComplete: (filename) => { setUrl(''); onUpdate('audioFilename', filename); },+ });+// Never leave the mic open on unmount (deferred-work cleanup rule).useEffect(() => () => { handleRef.current?.cancel(); }, []);@@ -156,33 +166,72 @@ export function ReferenceAudioAttach({ reference, onUpdate }) {);}+ const downloading = audioImport.active;+ const downloadLabel = audioImport.stage === 'extracting'+ ? 'Extracting…'+ : audioImport.stage === 'importing'+ ? 'Saving…'+ : `Downloading ${audioImport.percent}%`;+return (- <div className="flex flex-wrap items-center gap-2">- <input ref={fileRef} type="file" accept="audio/*" onChange={onFile} className="hidden" aria-label="Upload reference audio file" />- <button- type="button"- onClick={() => fileRef.current?.click()}- disabled={busy || recording}- className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50 disabled:opacity-50"- >- {busy ? <Loader2 size={14} className="animate-spin" /> : <Upload size={14} />} Upload audio- </button>- {recording ? (- <button type="button" onClick={stopRecord} className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg bg-port-error text-white hover:bg-port-error/90 animate-pulse">- <Square size={14} /> Stop capture- </button>- ) : (+ <div className="flex flex-col gap-1.5">+ <div className="flex flex-wrap items-center gap-2">+ <input ref={fileRef} type="file" accept="audio/*" onChange={onFile} className="hidden" aria-label="Upload reference audio file" /><buttontype="button"- onClick={startRecord}- disabled={busy}- title="Record through the mic while the reference video plays"+ onClick={() => fileRef.current?.click()}+ disabled={busy || recording || downloading}className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50 disabled:opacity-50">- <Mic size={14} /> Capture from mic+ {busy ? <Loader2 size={14} className="animate-spin" /> : <Upload size={14} />} Upload audio</button>- )}- <span className="text-xs text-gray-600">Upload a screen-recording’s audio, or capture the mic while the video plays.</span>+ {recording ? (+ <button type="button" onClick={stopRecord} className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg bg-port-error text-white hover:bg-port-error/90 animate-pulse">+ <Square size={14} /> Stop capture+ </button>+ ) : (+ <button+ type="button"+ onClick={startRecord}+ disabled={busy || downloading}+ title="Record through the mic while the reference video plays"+ className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50 disabled:opacity-50"+ >+ <Mic size={14} /> Capture from mic+ </button>+ )}+ {downloading ? (+ <span className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg border border-port-border text-gray-300">+ <Loader2 size={14} className="animate-spin" /> {downloadLabel}+ <button type="button" onClick={audioImport.cancel} title="Cancel download" className="ml-1 text-gray-400 hover:text-port-error">+ <X size={13} />+ </button>+ </span>+ ) : (+ <div className="flex items-center gap-1">+ <input+ type="url"+ value={url}+ onChange={(e) => setUrl(e.target.value)}+ onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); audioImport.start(url); } }}+ placeholder="Paste a video URL…"+ disabled={busy || recording}+ aria-label="Reference audio URL to download"+ className="px-2 py-1.5 text-xs rounded-lg border border-port-border bg-port-bg text-gray-200 w-44 disabled:opacity-50"+ />+ <button+ type="button"+ onClick={() => audioImport.start(url)}+ disabled={busy || recording || !url.trim()}+ title="Download audio from a URL via yt-dlp"+ className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50 disabled:opacity-50"+ >+ <Download size={14} /> Download+ </button>+ </div>+ )}+ </div>+ <span className="text-xs text-gray-600">Upload a screen-recording’s audio, capture the mic while the video plays, or download audio from a URL (needs yt-dlp installed).</span></div>);}diff --git a/client/src/components/songs/ReferenceAnalysis.test.jsx b/client/src/components/songs/ReferenceAnalysis.test.jsxindex c89cb6f799..378b7b560b 100644--- a/client/src/components/songs/ReferenceAnalysis.test.jsx+++ b/client/src/components/songs/ReferenceAnalysis.test.jsx@@ -25,6 +25,23 @@ vi.mock('../../lib/audioRecorder', () => ({arrayBufferToBase64: vi.fn(() => 'b64'),}));+// Control the reference-audio-import hook (#2120) so the "Download from URL"+// control is exercised without a real yt-dlp/SSE round-trip. `state` is mutated+// per-test to simulate the active (downloading) vs idle render.+const refImport = vi.hoisted(() => ({+ start: vi.fn(),+ cancel: vi.fn(),+ onComplete: null,+ state: { active: false, percent: 0, stage: null },+}));+vi.mock('../../hooks/useReferenceAudioImport.js', () => ({+ default: (opts = {}) => {+ refImport.onComplete = opts.onComplete;+ return { ...refImport.state, start: refImport.start, cancel: refImport.cancel };+ },+}));++import { act } from '@testing-library/react';import ReferenceAnalysis, { ReferenceAudioAttach } from './ReferenceAnalysis.jsx';const SR = 16000;@@ -395,4 +412,28 @@ describe('ReferenceAudioAttach', () => {// ranges can't resurrect against a later, different recording.expect(onUpdate).toHaveBeenCalledWith('segments', []);});++ it('starts a URL download and wires the finished filename onto the reference draft (#2120)', () => {+ refImport.start.mockClear();+ refImport.state = { active: false, percent: 0, stage: null };+ const onUpdate = vi.fn();+ render(<ReferenceAudioAttach reference={{ id: 'r', url: 'https://x.com' }} onUpdate={onUpdate} />);++ const input = screen.getByLabelText(/reference audio url/i);+ fireEvent.change(input, { target: { value: 'https://tiktok.com/@a/video/1' } });+ fireEvent.click(screen.getByRole('button', { name: /download/i }));+ expect(refImport.start).toHaveBeenCalledWith('https://tiktok.com/@a/video/1');++ // Simulate the SSE 'complete' frame landing an uploads-dir filename.+ act(() => refImport.onComplete('dl.mp3'));+ expect(onUpdate).toHaveBeenCalledWith('audioFilename', 'dl.mp3');+ });++ it('shows live progress and disables upload while a download is active (#2120)', () => {+ refImport.state = { active: true, percent: 42, stage: null };+ render(<ReferenceAudioAttach reference={{ id: 'r', url: 'https://x.com' }} onUpdate={vi.fn()} />);+ expect(screen.getByText(/downloading 42%/i)).toBeTruthy();+ expect(screen.getByRole('button', { name: /upload audio/i }).disabled).toBe(true);+ refImport.state = { active: false, percent: 0, stage: null }; // reset for other tests+ });});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 1ce02bd075..17a6243c7b 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -149,3 +149,4 @@ grep -i "what you want to do" client/src/hooks/README.md| `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). || `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. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex aa3e857e10..29c61da0be 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -46,6 +46,7 @@ export { default as useUniverse } from './useUniverse.js';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';// === Mixed (both default and named) — surface both ===export { default as useAsyncAction } from './useAsyncAction.js';diff --git a/client/src/hooks/useReferenceAudioImport.js b/client/src/hooks/useReferenceAudioImport.jsnew file mode 100644index 0000000000..233875ad70--- /dev/null+++ b/client/src/hooks/useReferenceAudioImport.js@@ -0,0 +1,76 @@+import { useEffect, useState } from 'react';+import toast from '../components/ui/Toast';+import {+ importReferenceAudio,+ cancelReferenceAudioImport,+ referenceAudioImportEventsUrl,+} from '../services/apiRounds.js';+import { useSseProgress, isTerminalSseFrame } from './useSseProgress.js';++/**+ * One round reference-audio-import job slot (#2120) — download + extract a+ * reference's audio from a URL via yt-dlp into the uploads dir, streaming SSE+ * progress. The deferred convenience path from the reference-audio analysis+ * feature (#2106); upload/mic capture remain the primary attach paths.+ *+ * Mirrors `useYoutubeTrackImport`: call it once per UI surface that can+ * independently kick off an import so each owns its own job + SSE subscription+ * (a shared slot would let a second kickoff orphan the first's in-flight job).+ *+ * `onComplete(filename, context)` fires once the download lands a file in the+ * uploads dir — `context` is whatever was passed to `start(url, 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 useReferenceAudioImport({ onComplete } = {}) {+ const [job, setJob] = useState(null); // { jobId, context }+ // `pending` covers the gap between clicking Download 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 ? referenceAudioImportEventsUrl(job.jobId) : null);+ const latest = sse.latest;+ const percent = Math.round(latest?.percent ?? 0);+ const stage = latest?.stage ?? null;++ useEffect(() => {+ if (!job || !latest) return;+ if (latest.type === 'complete') {+ onComplete?.(latest.filename, job.context);+ toast.success('Reference audio downloaded — Save the song to keep it');+ setJob(null);+ } else if (latest.type === 'error') {+ toast.error(latest.error || 'Reference audio download failed');+ setJob(null);+ } else if (latest.type === 'canceled' || latest.type === 'cancelled') {+ toast.info('Reference audio download cancelled');+ setJob(null);+ }+ }, [latest]);++ // Stream closed without a terminal frame (server restart mid-download, 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 reference-audio download');+ }+ }, [sse.closed]);++ const start = (url, context) => {+ const trimmed = (url || '').trim();+ if (!trimmed || job || pending) return;+ setPending(true);+ importReferenceAudio(trimmed, { silent: true })+ .then(({ jobId }) => setJob({ jobId, context }))+ .catch((err) => toast.error(err?.message || 'Failed to start reference-audio download'))+ .finally(() => setPending(false));+ };++ const cancel = () => {+ if (!job) return;+ cancelReferenceAudioImport(job.jobId, { silent: true }).catch(() => {});+ };++ return { active: pending || !!job, percent, stage, start, cancel };+}diff --git a/client/src/services/apiRounds.js b/client/src/services/apiRounds.jsindex 2253d40574..d3495a665a 100644--- a/client/src/services/apiRounds.js+++ b/client/src/services/apiRounds.js@@ -46,3 +46,17 @@ export const evaluateRound = (id, body = {}, options) =>// providerId?, model? } — partIds optionally restricts which harmony parts.export const deriveRoundParts = (id, body = {}, options) =>request(`/rounds/${enc(id)}/derive-parts`, { method: 'POST', body: JSON.stringify(body), ...options });++// --- Reference-audio import (#2120) — download + extract a reference's audio+// from a URL via yt-dlp into the uploads dir. Kickoff returns { jobId }; progress+// streams over SSE (subscribe with useSseProgress); the terminal `complete` frame+// carries the { filename } the caller persists on the reference. Upload/mic+// capture remain the primary attach paths.+export const importReferenceAudio = (url, options = {}) =>+ request('/rounds/reference-audio/import', { method: 'POST', body: JSON.stringify({ url }), ...options });++export const referenceAudioImportEventsUrl = (jobId) =>+ `/api/rounds/reference-audio/import/${enc(jobId)}/events`;++export const cancelReferenceAudioImport = (jobId, options = {}) =>+ request(`/rounds/reference-audio/import/${enc(jobId)}/cancel`, { method: 'POST', ...options });diff --git a/docs/plans/2026-07-04-rounds-ytdlp-reference-audio.md b/docs/plans/2026-07-04-rounds-ytdlp-reference-audio.mdnew file mode 100644index 0000000000..f16f765b58--- /dev/null+++ b/docs/plans/2026-07-04-rounds-ytdlp-reference-audio.md@@ -0,0 +1,72 @@+# Rounds: yt-dlp "Download audio from URL" for references (#2120)++**Approved:** 2026-07-04++## Goal++Add the deferred convenience path from #2106: on a round *reference* (e.g. a+layered TikTok performance), let the user paste a URL and have PortOS download ++extract its audio via `yt-dlp`, landing the file in the uploads dir so it can be+attached and analyzed like an uploaded/mic-captured recording. Upload and mic+capture remain the primary paths; this is best-effort.++## Key discovery — reuse, don't rebuild++The yt-dlp + audio-extraction + SSE-progress machinery already exists for the+YouTube **track** import (#1945): `server/lib/ytdlp.js` (`findYtDlp`),+`server/services/trackYoutubeImport.js`, `server/lib/sseUtils.js`,+`server/lib/killWithEscalation.js`. #2120's operation is nearly identical,+differing only in:++1. **URL scope** — any public http(s) URL + SSRF guard (not YouTube-only).+2. **Output** — land in `PATHS.uploads` and return a `filename` (not the music+ library + a Track record).++## Design (approved decisions)++- **Progress UX:** SSE streaming progress (mirrors the LoRA/track import), not a+ blocking spinner.+- **URL scope:** any public http(s) URL; `assertPublicHttpUrl(url, { blockPrivate: true })`+ from `safeUrlFetch.js` rejects private/loopback/metadata hosts. yt-dlp decides+ what it can actually extract; a failure degrades to a clear error.+- **Reuse strategy:** extract the shared yt-dlp download core and refactor the+ track import to use it (DRY; the track path has test coverage so the refactor+ is verifiable).++### Components++1. **`server/services/ytdlpAudioImport.js`** (new, shared core) — binary+ discovery/assert, arg construction, `--progress-template` parsing, spawn,+ cancel-aware exit classification, temp cleanup. Returns+ `{ outcome, outPath, title, reason }`; SSE + post-processing stay with the+ caller. `trackYoutubeImport.js` refactored to call it.+2. **`server/lib/fileUtils.js`** — new `importFileToUploads(tempPath, originalName)`+ (copyFile+unlink cross-device-safe, `uuid8-sanitizedName`, mirrors the+ `/api/uploads` naming). Registered in the lib barrel + README.+3. **`server/services/roundReferenceAudioImport.js`** (new) — SSRF-guarded+ `startReferenceAudioImport(url)` job that runs the core, lands the mp3 via+ `importFileToUploads`, and streams `{ type:'complete', filename }`. Plus+ attach/cancel SSE helpers.+4. **`server/routes/rounds.js`** — `POST /reference-audio/import`,+ `GET /reference-audio/import/:jobId/events`,+ `POST /reference-audio/import/:jobId/cancel` (placed before `/:id`).+5. **Client** — `apiRounds.js` wrappers, a `useReferenceAudioImport` hook+ (mirrors `useYoutubeTrackImport`), and a "Download from URL" control in+ `ReferenceAudioAttach` (`ReferenceAnalysis.jsx`) that sets `audioFilename`+ via the existing `onUpdate` path on completion.++### Bounds / safety++- `execFile`/`spawn` with a fixed arg array (no shell) — the yt-dlp binary is the+ only command, args never interpolate through a shell.+- `--max-filesize` / `--match-filters duration<=…` cap resource use (its own+ uploads-appropriate bounds).+- Binary-missing → `409`/`500` with an actionable "install yt-dlp/ffmpeg" message.++## Tests++- Shared core: URL/arg invariants; happy path + failure with mocked `spawn`.+- `roundReferenceAudioImport`: SSRF rejection; happy path lands a filename.+- Rounds route: kickoff + SSE attach + cancel.+- Re-run `trackYoutubeImport.test.js` (no regression) and `lib/index.test.js`+ (barrel).diff --git a/server/lib/README.md b/server/lib/README.mdindex c2ea16489d..067774464a 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -114,7 +114,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record push loop (peer:online convergence) collapses N `sync_base_hashes.json` rewrites into one terminal write (re-entrant; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from every `pruneTombstoned*` path — universe/series/issue/collection) so the side store doesn't grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. || `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. || `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. |-| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `pathExists` (async `existsSync` replacement for request/hot paths), `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |+| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `pathExists` (async `existsSync` replacement for request/hot paths), `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, `sanitizeFilename`, `importFileToUploads(tempPath, name)` (land a server-produced temp file in `PATHS.uploads` with `/api/uploads` naming), JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. || `createKeyCachedQueue.js` | Per-KEY serialized async work queue (sibling to `fileWriteQueue.js`'s single tail). `createKeyCachedQueue()` returns `queue(key, work)` that chains each `work` thunk onto the prior in-flight promise for that `key` — same-key work runs one-after-another (later sees earlier's committed result), different keys run concurrently. Self-pruning tail Map; `work` runs on both fulfil and reject so one failure can't stall the chain; carries `.clear()` for test reset. Used by the media-job completion hooks (writers-room / catalog / music-video scene-image attach) to serialize per-record. || `createNewestWinsGuard.js` | Newest-render-wins ordering guard for out-of-order async completions. `createNewestWinsGuard()` returns `{ isStale(key, at), mark(key, at), clear() }` — tracks the newest applied `queuedAt` per slot `key` so an older render completing after a newer one is dropped (`isStale` true) instead of clobbering the newer frame. ISO timestamps compare as strings; absent `at` is never stale. Used by `createMediaJobImageHook`'s opt-in guard and the catalog hook's portrait slot. || `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. |diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex f394a9f6a2..33f2c46cec 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -4,7 +4,7 @@* Shared utilities for file operations used across services.*/-import { access, appendFile, chmod, mkdir, readFile, readdir, stat, writeFile, rename, unlink } from 'fs/promises';+import { access, appendFile, chmod, mkdir, readFile, readdir, stat, writeFile, rename, unlink, copyFile } from 'fs/promises';import { existsSync, statSync, createReadStream } from 'fs';import { execFile } from 'child_process';import { promisify } from 'util';@@ -891,6 +891,27 @@ export function sanitizeFilename(filename) {return sanitized;}+/**+ * 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.+ *+ * 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);+ const filename = `${randomUUID().slice(0, 8)}-${sanitizeFilename(originalName)}`;+ const dest = join(PATHS.uploads, filename);+ await copyFile(tempPath, dest);+ await unlink(tempPath).catch(() => {});+ const s = await stat(dest).catch(() => null);+ return { filename, sizeBytes: s?.size ?? 0 };+}+/*** Validate a user-supplied filename is a safe basename with one of the* allowed extensions — refuses path-traversal, null bytes, separators, anddiff --git a/server/routes/rounds.js b/server/routes/rounds.jsindex ea08398f9f..66c162ab7c 100644--- a/server/routes/rounds.js+++ b/server/routes/rounds.js@@ -19,6 +19,11 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import * as svc from '../services/rounds.js';import { generateRound, evaluateRound, deriveRoundParts } from '../services/roundsAI.js';+import {+ startReferenceAudioImport,+ attachReferenceAudioSseClient,+ cancelReferenceAudioImport,+} from '../services/roundReferenceAudioImport.js';const router = Router();@@ -216,6 +221,31 @@ router.get('/:id', asyncHandler(async (req, res) => {res.json({ round });}));+// --- Reference-audio import (#2120) -----------------------------------------+// Download + extract audio from a URL via yt-dlp into the uploads dir, so it can+// be attached to a round reference and analyzed exactly like an upload/mic+// capture (the deferred convenience path from #2106; upload/mic stay primary).+// Two-segment `reference-audio/...` paths are registered before `/:id` so the+// literal segment can't be read as a round id. The kickoff returns 202 + a+// jobId; progress streams over SSE; the client persists the returned filename+// on the reference via the normal PUT on Save.+const referenceAudioImportSchema = z.object({ url: str(2048).min(1) });++router.post('/reference-audio/import', asyncHandler(async (req, res) => {+ const { url } = validateRequest(referenceAudioImportSchema, req.body || {});+ res.status(202).json(await startReferenceAudioImport(url));+}));++router.get('/reference-audio/import/:jobId/events', (req, res) => {+ if (!attachReferenceAudioSseClient(req.params.jobId, res)) {+ throw new ServerError('Import job not found or expired', { status: 404, code: 'NOT_FOUND' });+ }+});++router.post('/reference-audio/import/:jobId/cancel', (req, res) => {+ res.json({ ok: cancelReferenceAudioImport(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 ea6bbd0baa..9726e0c529 100644--- a/server/routes/rounds.test.js+++ b/server/routes/rounds.test.js@@ -28,6 +28,14 @@ const aiMocks = vi.hoisted(() => ({}));vi.mock('../services/roundsAI.js', () => aiMocks);+// Isolate the route contract from the real yt-dlp/SSE import service (#2120).+const importMocks = vi.hoisted(() => ({+ startReferenceAudioImport: vi.fn(),+ attachReferenceAudioSseClient: vi.fn(),+ cancelReferenceAudioImport: vi.fn(),+}));+vi.mock('../services/roundReferenceAudioImport.js', () => importMocks);+import roundsRoutes from './rounds.js';const makeApp = () => {@@ -42,6 +50,7 @@ describe('rounds route', () => {beforeEach(() => {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();});it('GET / returns the song list', async () => {@@ -332,4 +341,29 @@ describe('rounds route', () => {const [arg] = aiMocks.deriveRoundParts.mock.calls[0];expect(arg.partIds).toEqual(['bass', 'high-harmony-1']);});++ // --- Reference-audio import (#2120) ---------------------------------------+ it('POST /reference-audio/import 202s with the jobId from the service', async () => {+ importMocks.startReferenceAudioImport.mockResolvedValue({ jobId: 'job-1' });+ const res = await request(makeApp())+ .post('/api/rounds/reference-audio/import')+ .send({ url: 'https://tiktok.com/@a/video/1' });+ expect(res.status).toBe(202);+ expect(res.body).toEqual({ jobId: 'job-1' });+ expect(importMocks.startReferenceAudioImport).toHaveBeenCalledWith('https://tiktok.com/@a/video/1');+ });++ it('POST /reference-audio/import 400s on a missing url (not read as a round id)', async () => {+ const res = await request(makeApp()).post('/api/rounds/reference-audio/import').send({});+ expect(res.status).toBe(400);+ expect(importMocks.startReferenceAudioImport).not.toHaveBeenCalled();+ });++ it('POST /reference-audio/import/:jobId/cancel reports the cancel result', async () => {+ importMocks.cancelReferenceAudioImport.mockReturnValue(true);+ const res = await request(makeApp()).post('/api/rounds/reference-audio/import/job-1/cancel');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ ok: true });+ expect(importMocks.cancelReferenceAudioImport).toHaveBeenCalledWith('job-1');+ });});diff --git a/server/services/roundReferenceAudioImport.js b/server/services/roundReferenceAudioImport.jsnew file mode 100644index 0000000000..b86a6b015d--- /dev/null+++ b/server/services/roundReferenceAudioImport.js@@ -0,0 +1,101 @@+/**+ * Round reference-audio import (#2120) — the deferred convenience path from the+ * reference-audio analysis feature (#2106). Download + extract the audio from a+ * reference URL (a layered TikTok performance, a YouTube clip, …) via yt-dlp and+ * land it in the uploads dir, so it can be attached to a round reference and+ * analyzed exactly like an uploaded file or a mic capture.+ *+ * Reuses the shared yt-dlp download core (`ytdlpAudioImport.js`) — same job/SSE+ * shape as the YouTube track import (#1945). The two differences from that path:+ * 1. URL scope — ANY public http(s) URL (SSRF-guarded), not YouTube-only. yt-dlp+ * decides what it can actually extract; a scrape failure degrades to a clear+ * error (upload/mic capture remain the primary attach paths).+ * 2. Output — lands in PATHS.uploads and returns a `filename` for the+ * reference's `audioFilename`, rather than the music library + a Track.+ */++import { randomUUID } from 'crypto';+import { shortId, importFileToUploads } from '../lib/fileUtils.js';+import { assertPublicHttpUrl } from '../lib/safeUrlFetch.js';+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../lib/sseUtils.js';+import { killWithEscalation } from '../lib/killWithEscalation.js';+import { resolveYtDlpBinaries, downloadAudioToTempMp3, cleanupYtDlpTemp } from './ytdlpAudioImport.js';++// Reference performances are short clips — bound resource use so a mistyped+// link to a long archive/livestream can't download + transcode unbounded.+export const REFERENCE_AUDIO_MAX_BYTES = 60 * 1024 * 1024; // 60MB+export const REFERENCE_AUDIO_MAX_DURATION_SEC = 20 * 60; // 20 minutes++// jobId -> { clients, lastPayload, process }+const importJobs = new Map();++export const attachReferenceAudioSseClient = (jobId, res) => attachSse(importJobs, jobId, res);++/** Cancel an in-flight import. Returns false if the job is unknown or already finished. */+export function cancelReferenceAudioImport(jobId) {+ const job = importJobs.get(jobId);+ if (!job || !job.process) return false;+ const proc = job.process;+ killWithEscalation(proc, { label: 'yt-dlp reference audio', stillRunning: () => job.process === proc });+ return true;+}++/**+ * Kick off a reference-audio download. Returns `{ jobId }` immediately; the+ * download+extract runs detached and streams progress over SSE. Terminal+ * frames: `{ type: 'complete', filename }`, `{ type: 'error', error }`, or+ * `{ type: 'canceled' }`. Throws (before returning a jobId) on an unsafe URL or+ * a missing yt-dlp/ffmpeg binary, so those surface as real HTTP errors.+ */+export async function startReferenceAudioImport(url) {+ // SSRF guard: http(s) only, reject loopback/link-local/metadata AND private+ // LAN hosts (blockPrivate) — yt-dlp fetches the URL itself, so it never+ // reaches our SSRF-guarded fetcher; validate before handing it the URL.+ await assertPublicHttpUrl(url, { blockPrivate: true });+ const { ytDlp, ffmpeg } = await resolveYtDlpBinaries();++ const jobId = randomUUID();+ const tempPrefix = `portos-refaudio-${jobId}`;+ const job = { id: jobId, status: 'running', clients: [], process: null };+ importJobs.set(jobId, job);+ console.log(`🎧 Reference-audio import ${shortId(jobId)} — ${url}`);++ (async () => {+ try {+ const result = await downloadAudioToTempMp3({+ url, ytDlp, ffmpeg, tempPrefix,+ maxBytes: REFERENCE_AUDIO_MAX_BYTES,+ maxDurationSec: REFERENCE_AUDIO_MAX_DURATION_SEC,+ onProgress: (p) => broadcastSse(job, { type: 'progress', ...p }),+ registerProcess: (proc) => { job.process = proc; },+ });++ if (result.outcome === 'canceled') {+ console.log(`🛑 Reference-audio import ${shortId(jobId)} cancelled`);+ broadcastSse(job, { type: 'canceled' });+ return;+ }+ if (result.outcome === 'failed') {+ throw new Error(result.reason);+ }++ broadcastSse(job, { type: 'progress', percent: 100, stage: 'importing' });+ const { title, outPath } = result;+ const { filename } = await importFileToUploads(outPath, `${title || 'Reference Audio'}.mp3`);++ console.log(`🎧 Reference-audio import ${shortId(jobId)} complete — ${filename}`);+ broadcastSse(job, { type: 'complete', filename, title: title || null });+ } catch (err) {+ console.error(`❌ Reference-audio import ${shortId(jobId)} failed: ${err?.message || err}`);+ broadcastSse(job, { type: 'error', error: err?.message || String(err) });+ // The core cleans temp on canceled/failed; this catch covers a throw from+ // the post-complete landing (importFileToUploads), whose produced outPath+ // the core handed off and no longer owns.+ await cleanupYtDlpTemp(tempPrefix);+ } finally {+ closeJobAfterDelay(importJobs, jobId);+ }+ })();++ return { jobId };+}diff --git a/server/services/roundReferenceAudioImport.test.js b/server/services/roundReferenceAudioImport.test.jsnew file mode 100644index 0000000000..b8bf58a6b0--- /dev/null+++ b/server/services/roundReferenceAudioImport.test.js@@ -0,0 +1,91 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { ServerError } from '../lib/errorHandler.js';++vi.mock('../lib/safeUrlFetch.js', () => ({ assertPublicHttpUrl: vi.fn(async () => {}) }));+vi.mock('../lib/sseUtils.js', () => ({+ broadcastSse: vi.fn(),+ attachSseClient: vi.fn(() => true),+ closeJobAfterDelay: vi.fn(),+}));+vi.mock('../lib/killWithEscalation.js', () => ({ killWithEscalation: vi.fn() }));+vi.mock('./ytdlpAudioImport.js', () => ({+ resolveYtDlpBinaries: vi.fn(async () => ({ ytDlp: '/yt', ffmpeg: '/ff' })),+ downloadAudioToTempMp3: vi.fn(),+ cleanupYtDlpTemp: vi.fn(async () => {}),+}));+vi.mock('../lib/fileUtils.js', async (importOriginal) => ({+ ...(await importOriginal()),+ importFileToUploads: vi.fn(async () => ({ filename: 'ab12cd34-Reference_Audio.mp3', sizeBytes: 100 })),+}));++const { assertPublicHttpUrl } = await import('../lib/safeUrlFetch.js');+const { broadcastSse } = await import('../lib/sseUtils.js');+const { resolveYtDlpBinaries, downloadAudioToTempMp3, cleanupYtDlpTemp } = await import('./ytdlpAudioImport.js');+const { importFileToUploads } = await import('../lib/fileUtils.js');+const { startReferenceAudioImport } = await import('./roundReferenceAudioImport.js');++// Let the detached kickoff IIFE run to its terminal broadcast.+const flush = async () => {+ for (let i = 0; i < 4; i += 1) await new Promise((r) => setImmediate(r));+};++beforeEach(() => {+ vi.clearAllMocks();+ assertPublicHttpUrl.mockResolvedValue(undefined);+ resolveYtDlpBinaries.mockResolvedValue({ ytDlp: '/yt', ffmpeg: '/ff' });+});++describe('startReferenceAudioImport — pre-kickoff guards', () => {+ it('rejects an unsafe URL before touching yt-dlp discovery', async () => {+ assertPublicHttpUrl.mockRejectedValue(new ServerError('unsafe', { status: 400, code: 'UNSAFE_URL' }));+ await expect(startReferenceAudioImport('http://127.0.0.1/x'))+ .rejects.toMatchObject({ status: 400, code: 'UNSAFE_URL' });+ expect(resolveYtDlpBinaries).not.toHaveBeenCalled();+ });++ it('applies the strict SSRF posture (blockPrivate) so LAN hosts are rejected', async () => {+ downloadAudioToTempMp3.mockResolvedValue({ outcome: 'canceled' });+ await startReferenceAudioImport('https://example.com/clip');+ await flush();+ expect(assertPublicHttpUrl).toHaveBeenCalledWith('https://example.com/clip', { blockPrivate: true });+ });+});++describe('startReferenceAudioImport — outcomes', () => {+ it('lands the mp3 in uploads and broadcasts complete with the filename', async () => {+ downloadAudioToTempMp3.mockResolvedValue({ outcome: 'complete', outPath: '/tmp/x.mp3', title: 'My Clip' });+ const { jobId } = await startReferenceAudioImport('https://example.com/clip');+ expect(jobId).toBeTruthy();+ await flush();++ expect(importFileToUploads).toHaveBeenCalledWith('/tmp/x.mp3', 'My Clip.mp3');+ expect(broadcastSse).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ type: 'complete', filename: 'ab12cd34-Reference_Audio.mp3' }),+ );+ });++ it('falls back to a default title when yt-dlp reported none', async () => {+ downloadAudioToTempMp3.mockResolvedValue({ outcome: 'complete', outPath: '/tmp/x.mp3', title: '' });+ await startReferenceAudioImport('https://example.com/clip');+ await flush();+ expect(importFileToUploads).toHaveBeenCalledWith('/tmp/x.mp3', 'Reference Audio.mp3');+ });++ it('broadcasts error and cleans temp on a failed download', async () => {+ downloadAudioToTempMp3.mockResolvedValue({ outcome: 'failed', reason: 'no audio was produced' });+ await startReferenceAudioImport('https://example.com/clip');+ await flush();+ expect(broadcastSse).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ type: 'error', error: 'no audio was produced' }));+ expect(cleanupYtDlpTemp).toHaveBeenCalled();+ expect(importFileToUploads).not.toHaveBeenCalled();+ });++ it('broadcasts canceled when the download was cancelled', async () => {+ downloadAudioToTempMp3.mockResolvedValue({ outcome: 'canceled' });+ await startReferenceAudioImport('https://example.com/clip');+ await flush();+ expect(broadcastSse).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ type: 'canceled' }));+ expect(importFileToUploads).not.toHaveBeenCalled();+ });+});diff --git a/server/services/trackYoutubeImport.js b/server/services/trackYoutubeImport.jsindex c4dac6217a..eca9ed32d9 100644--- a/server/services/trackYoutubeImport.js+++ b/server/services/trackYoutubeImport.js@@ -5,28 +5,22 @@** 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.+ * shared SSE helpers, and the client attaches with useSseProgress. The yt-dlp+ * download+extract itself is the shared core in `ytdlpAudioImport.js` (reused+ * by the round reference-audio import #2120); this module owns the YouTube-only+ * URL scope, the music-library landing, and the Track creation.*/-import { spawn } from 'child_process';-import { existsSync } from 'fs';-import { readdir, unlink } from 'fs/promises';-import { tmpdir } from 'os';-import { join, dirname } from 'path';import { randomUUID } from 'crypto';+import { join } from 'path';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 { probeVideoDuration } from '../lib/ffmpeg.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../lib/sseUtils.js';-import { safeChildProcessEnv } from '../lib/processEnv.js';import { killWithEscalation } from '../lib/killWithEscalation.js';import { importUploadedTrack, MUSIC_UPLOAD_MAX_BYTES } from './pipeline/musicLibrary.js';import { createTrack, DURATION_MAX_SEC } from './tracks/index.js';+import { resolveYtDlpBinaries, downloadAudioToTempMp3, cleanupYtDlpTemp } from './ytdlpAudioImport.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@@ -57,28 +51,6 @@ export function cancelYoutubeImport(jobId) {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:';--// 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@@ -87,111 +59,35 @@ async function cleanupTempFiles(jobId) {*/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 { ytDlp, ffmpeg } = await resolveYtDlpBinaries();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 tempPrefix = `portos-ytimport-${jobId}`;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',- // Bound resource use to the same limits the manual upload path already- // enforces (MUSIC_UPLOAD_MAX_BYTES, DURATION_MAX_SEC) — without these,- // a long video or a livestream/archive URL downloads and transcodes- // unbounded, eating disk in tmpdir()/data/music and CPU with no cap.- '--max-filesize', String(MUSIC_UPLOAD_MAX_BYTES),- '--match-filters', `duration <= ${DURATION_MAX_SEC}`,- '-o', `${tempBase}.%(ext)s`,- url,- ];- const proc = spawn(ytDlp, args, { env: safeChildProcessEnv(), stdio: ['ignore', 'pipe', 'pipe'] });- job.process = proc;-- 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) });- }- };- // 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', 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}` }));- proc.on('close', (code, signal) => resolve({ code, signal }));+ const result = await downloadAudioToTempMp3({+ url, ytDlp, ffmpeg, tempPrefix,+ maxBytes: MUSIC_UPLOAD_MAX_BYTES,+ maxDurationSec: DURATION_MAX_SEC,+ onProgress: (p) => broadcastSse(job, { type: 'progress', ...p }),+ registerProcess: (proc) => { job.process = proc; },});- job.process = null;- if (exit.signal === 'SIGTERM' || exit.signal === 'SIGKILL') {+ if (result.outcome === 'canceled') {console.log(`🛑 YouTube import ${shortId(jobId)} cancelled`);broadcastSse(job, { type: 'canceled' });- await cleanupTempFiles(jobId);return;}- if (exit.code !== 0 || !existsSync(outPath)) {- // A --match-filters/--max-filesize rejection exits 0 with no output- // file (yt-dlp treats a filtered-out video as "nothing to do", not an- // error) — `--print`'s suppression of normal reporting (see above)- // means the specific reason never reaches our stdout/stderr parsing,- // so name the two known bounds explicitly rather than a bare exit code.- const reason = exit.code === 0- ? `no audio was produced — the video may be longer than ${DURATION_MAX_SEC / 60} minutes or its audio larger than ${Math.round(MUSIC_UPLOAD_MAX_BYTES / 1024 / 1024)}MB, or it may be otherwise unavailable`- : (exit.reason || `yt-dlp exited ${exit.code}`);- throw new Error(reason);+ if (result.outcome === 'failed') {+ throw new Error(result.reason);}broadcastSse(job, { type: 'progress', percent: 100, stage: 'importing' });+ const { title, outPath } = result;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 });@@ -201,7 +97,10 @@ 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 cleanupTempFiles(jobId);+ // The core cleans temp on canceled/failed; this catch covers a throw from+ // the post-complete landing (importUploadedTrack/createTrack), whose+ // produced outPath the core handed off and no longer owns.+ await cleanupYtDlpTemp(tempPrefix);} finally {closeJobAfterDelay(importJobs, jobId);}diff --git a/server/services/ytdlpAudioImport.js b/server/services/ytdlpAudioImport.jsnew file mode 100644index 0000000000..24ab087756--- /dev/null+++ b/server/services/ytdlpAudioImport.js@@ -0,0 +1,179 @@+/**+ * Shared yt-dlp audio-download core.+ *+ * Extracted from the YouTube track import (#1945) so a second consumer — the+ * round reference-audio "Download from URL" convenience (#2120) — can reuse the+ * hard part (yt-dlp arg construction, `--progress-template` machine-readable+ * progress parsing, cancel-aware exit classification, temp-file cleanup) rather+ * than duplicating ~120 lines of subtle yt-dlp knowledge.+ *+ * A single yt-dlp invocation does the whole job (`-x --audio-format mp3`,+ * pointed at our discovered ffmpeg via --ffmpeg-location) — yt-dlp already+ * shells out to ffmpeg for the audio conversion internally, so a second pass+ * would just re-decode.+ *+ * The core is deliberately SSE-agnostic: it takes an `onProgress` callback and+ * a `registerProcess` hook, and RETURNS an outcome. The caller owns the job+ * map, SSE broadcasting, terminal frames, and post-processing (where the+ * produced file lands). URL validation is the caller's job too — the track+ * import allows only YouTube URLs, the reference import allows any public+ * http(s) URL (SSRF-guarded) — so the core never sees an unvetted URL.+ */++import { spawn } from 'child_process';+import { existsSync } from 'fs';+import { readdir, unlink } from 'fs/promises';+import { tmpdir } from 'os';+import { join, dirname } from 'path';+import { ServerError } from '../lib/errorHandler.js';+import { findFfmpeg } from '../lib/ffmpeg.js';+import { findYtDlp } from '../lib/ytdlp.js';+import { safeChildProcessEnv } from '../lib/processEnv.js';++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:';++/**+ * Locate yt-dlp + ffmpeg, throwing an actionable ServerError if either is+ * missing. Call this at kickoff (before returning a jobId) so a missing binary+ * surfaces as a real HTTP error instead of an SSE frame nobody's attached to+ * yet. Independent lookups run concurrently.+ */+export async function resolveYtDlpBinaries() {+ 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' });+ return { ytDlp, ffmpeg };+}++/**+ * 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.+ */+export async function cleanupYtDlpTemp(tempPrefix) {+ const dir = tmpdir();+ const entries = await readdir(dir).catch(() => []);+ await Promise.all(+ entries.filter((name) => name.startsWith(tempPrefix)).map((name) => unlink(join(dir, name)).catch(() => {})),+ );+}++/**+ * Download + extract audio to a temp mp3 via one yt-dlp invocation.+ *+ * @param {object} opts+ * @param {string} opts.url Already-validated source URL.+ * @param {string} opts.ytDlp yt-dlp binary path (from resolveYtDlpBinaries).+ * @param {string} opts.ffmpeg ffmpeg binary path (from resolveYtDlpBinaries).+ * @param {string} opts.tempPrefix Unique per-job temp filename prefix (no dir).+ * @param {number} opts.maxBytes `--max-filesize` cap.+ * @param {number} opts.maxDurationSec `--match-filters duration<=` cap.+ * @param {function} opts.onProgress ({ percent, stage }) => void — SSE-agnostic.+ * @param {function} opts.registerProcess (proc|null) => void — lets the caller wire cancel.+ * @returns {Promise<{ outcome:'complete'|'canceled'|'failed', outPath?:string, title?:string, reason?:string }>}+ *+ * Never throws for a yt-dlp runtime failure (returns `failed` + `reason`); the+ * caller decides how to surface it. Cleans temp files on `canceled`/`failed`;+ * on `complete` the caller owns `outPath` (moves it, then it's gone).+ */+export async function downloadAudioToTempMp3({+ url, ytDlp, ffmpeg, tempPrefix, maxBytes, maxDurationSec, onProgress, registerProcess,+}) {+ // -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(), tempPrefix);+ const outPath = `${tempBase}.mp3`;++ let title = '';+ 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',+ // Bound resource use — without these, a long video or a livestream/archive+ // URL downloads and transcodes unbounded, eating disk in tmpdir() and CPU+ // with no cap.+ '--max-filesize', String(maxBytes),+ '--match-filters', `duration <= ${maxDurationSec}`,+ '-o', `${tempBase}.%(ext)s`,+ url,+ ];++ const proc = spawn(ytDlp, args, { env: safeChildProcessEnv(), stdio: ['ignore', 'pipe', 'pipe'] });+ registerProcess(proc);++ 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)) onProgress({ percent });+ return;+ }+ if (line.startsWith(STAGE_PREFIX)) {+ onProgress({ percent: 100, stage: line.slice(STAGE_PREFIX.length) });+ }+ };+ // 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', 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}` }));+ proc.on('close', (code, signal) => resolve({ code, signal }));+ });+ registerProcess(null);++ if (exit.signal === 'SIGTERM' || exit.signal === 'SIGKILL') {+ await cleanupYtDlpTemp(tempPrefix);+ return { outcome: 'canceled' };+ }+ if (exit.code !== 0 || !existsSync(outPath)) {+ // A --match-filters/--max-filesize rejection exits 0 with no output file+ // (yt-dlp treats a filtered-out video as "nothing to do", not an error) —+ // `--print`'s suppression of normal reporting (see above) means the+ // specific reason never reaches our stdout/stderr parsing, so name the two+ // known bounds explicitly rather than a bare exit code.+ const reason = exit.code === 0+ ? `no audio was produced — the source may be longer than ${Math.round(maxDurationSec / 60)} minutes or its audio larger than ${Math.round(maxBytes / 1024 / 1024)}MB, or it may be otherwise unavailable`+ : (exit.reason || `yt-dlp exited ${exit.code}`);+ await cleanupYtDlpTemp(tempPrefix);+ return { outcome: 'failed', reason };+ }++ return { outcome: 'complete', outPath, title };+}diff --git a/server/services/ytdlpAudioImport.test.js b/server/services/ytdlpAudioImport.test.jsnew file mode 100644index 0000000000..f805bde09d--- /dev/null+++ b/server/services/ytdlpAudioImport.test.js@@ -0,0 +1,115 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { EventEmitter } from 'events';++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') }));+vi.mock('child_process', async (importOriginal) => ({ ...(await importOriginal()), spawn: vi.fn() }));++const { findYtDlp } = await import('../lib/ytdlp.js');+const { findFfmpeg } = await import('../lib/ffmpeg.js');+const { spawn } = await import('child_process');+const { resolveYtDlpBinaries, downloadAudioToTempMp3 } = await import('./ytdlpAudioImport.js');++// A fake yt-dlp child. `emit` optionally pushes stdout/stderr lines before the+// close, letting a test exercise the progress/title marker parsing.+function fakeChild({ code = 0, signal = null, stdout = [] } = {}) {+ const proc = new EventEmitter();+ proc.stdout = new EventEmitter();+ proc.stderr = new EventEmitter();+ setImmediate(() => {+ stdout.forEach((line) => proc.stdout.emit('data', Buffer.from(`${line}\n`)));+ proc.emit('close', code, signal);+ });+ return proc;+}++const baseArgs = {+ url: 'https://example.com/clip',+ ytDlp: '/usr/local/bin/yt-dlp',+ ffmpeg: '/usr/local/bin/ffmpeg',+ tempPrefix: 'portos-test-abc',+ maxBytes: 60 * 1024 * 1024,+ maxDurationSec: 1200,+ onProgress: () => {},+ registerProcess: () => {},+};++beforeEach(() => {+ vi.clearAllMocks();+ findYtDlp.mockResolvedValue('/usr/local/bin/yt-dlp');+ findFfmpeg.mockResolvedValue('/usr/local/bin/ffmpeg');+});++describe('resolveYtDlpBinaries', () => {+ it('returns both binary paths when present', async () => {+ await expect(resolveYtDlpBinaries()).resolves.toEqual({+ ytDlp: '/usr/local/bin/yt-dlp',+ ffmpeg: '/usr/local/bin/ffmpeg',+ });+ });++ it('throws YTDLP_MISSING when yt-dlp is absent', async () => {+ findYtDlp.mockResolvedValue(null);+ await expect(resolveYtDlpBinaries()).rejects.toMatchObject({ status: 500, code: 'YTDLP_MISSING' });+ });++ it('throws FFMPEG_MISSING when ffmpeg is absent', async () => {+ findFfmpeg.mockResolvedValue(null);+ await expect(resolveYtDlpBinaries()).rejects.toMatchObject({ status: 500, code: 'FFMPEG_MISSING' });+ });+});++describe('downloadAudioToTempMp3 — argv', () => {+ it('extracts audio to mp3 and bounds the download with the passed caps', async () => {+ spawn.mockReturnValue(fakeChild({ code: 0 }));+ await downloadAudioToTempMp3(baseArgs);++ expect(spawn).toHaveBeenCalledOnce();+ const [bin, args] = spawn.mock.calls[0];+ expect(bin).toBe('/usr/local/bin/yt-dlp');+ expect(args).toEqual(expect.arrayContaining(['-x', '--audio-format', 'mp3']));+ expect(args).toEqual(expect.arrayContaining(['--max-filesize', String(60 * 1024 * 1024)]));+ expect(args).toEqual(expect.arrayContaining(['--match-filters', 'duration <= 1200']));+ expect(args[args.length - 1]).toBe('https://example.com/clip'); // url is last+ });+});++describe('downloadAudioToTempMp3 — outcomes', () => {+ it('reports canceled on SIGTERM', async () => {+ spawn.mockReturnValue(fakeChild({ code: null, signal: 'SIGTERM' }));+ const result = await downloadAudioToTempMp3(baseArgs);+ expect(result.outcome).toBe('canceled');+ });++ it('reports failed (no output file) with a bounds-aware reason on a clean exit that produced nothing', async () => {+ spawn.mockReturnValue(fakeChild({ code: 0 })); // exit 0 but no temp mp3 exists+ const result = await downloadAudioToTempMp3(baseArgs);+ expect(result.outcome).toBe('failed');+ expect(result.reason).toMatch(/no audio was produced/);+ });++ it('reports failed with the exit code when yt-dlp errors', async () => {+ spawn.mockReturnValue(fakeChild({ code: 1 }));+ const result = await downloadAudioToTempMp3(baseArgs);+ expect(result.outcome).toBe('failed');+ expect(result.reason).toMatch(/yt-dlp exited 1/);+ });++ it('parses PORTOS_PROGRESS markers into onProgress percents', async () => {+ const seen = [];+ spawn.mockReturnValue(fakeChild({ code: 1, stdout: ['PORTOS_PROGRESS: 42.0%', 'PORTOS_PROGRESS:not-a-number'] }));+ await downloadAudioToTempMp3({ ...baseArgs, onProgress: (p) => seen.push(p) });+ expect(seen).toContainEqual({ percent: 42 });+ // A non-numeric percent is ignored, not forwarded as NaN.+ expect(seen.some((p) => Number.isNaN(p.percent))).toBe(false);+ });++ it('registers the process then clears it on exit', async () => {+ const registered = [];+ spawn.mockReturnValue(fakeChild({ code: 1 }));+ await downloadAudioToTempMp3({ ...baseArgs, registerProcess: (p) => registered.push(p) });+ expect(registered).toHaveLength(2);+ expect(registered[0]).not.toBeNull(); // the child+ expect(registered[1]).toBeNull(); // cleared after close+ });+});