Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(pipeline): audio stage music — upload, shared library, picker

[._.]/ Adam Eivy3bcd84cf9f2b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 79ef96b3bd..faf9b04a18 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,31 @@
## Added
+- **Pipeline audio stage: background-music upload + shared library + picker
+ (Phase 4c).** The audio stage now carries an optional music track alongside
+ the VO lines, with three new routes: `POST
+ /pipeline/issues/:id/stages/audio/music/upload` (multipart upload + attach
+ in one round trip; MP3/WAV/M4A/OGG/FLAC, 50 MB max), `POST
+ …/music/attach` (re-bind an existing library track to the issue), `DELETE
+ …/music` (detach from the issue), plus library-level `GET
+ /pipeline/audio/music-library` and `DELETE /pipeline/audio/music-library/:filename`.
+ Tracks live under a new shared `data/music/` directory served via
+ `/data/music` static; deleting a library file intentionally leaves
+ pointers stale on issue records so the broken playback surfaces to the
+ user (auto-purge would scan every issue on every delete). The AudioStage
+ UI gains a "Background Music" section below the lines list with Upload /
+ Pick from library buttons, an inline confirm row for destructive library
+ deletes (matching the user's preference for `[Cancel] [Delete]` over the
+ two-click-arm pattern), and inline `<audio>` playback for the attached
+ track. The `MUSIC_SOURCE` const (`upload | library | gen`) replaces bare
+ strings in the routes so the upcoming local-OSS MusicGen sub-phase
+ (4c.2) plugs in as a sibling `'gen'` source without a contract change.
+ Touches: new `server/services/pipeline/musicLibrary.js` + tests, new
+ `server/services/pipeline/musicLibrary.test.js`, `server/routes/pipeline.js`,
+ `server/lib/fileUtils.js` (`PATHS.music`), `server/index.js` (static
+ mount), `client/src/services/apiPipeline.js`,
+ `client/src/components/pipeline/stages/AudioStage.jsx`.
+
- **`plan-task` scheduled task — strict PLAN.md executor.** New task type in
`server/services/taskSchedule.js` that picks the next unchecked PLAN.md
item, implements it (worktree + `/simplify` + PR by default), and **moves**
diff --git a/PLAN.md b/PLAN.md
index d2695f46f6..eb584b1935 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -239,5 +239,10 @@ Skeleton landed in `server/services/pipeline/` + `client/src/pages/Pipeline*.jsx
- [ ] **Extract migration scaffolding into `data/migrations/_lib.js`.** Migrations 003 and 006 both implement the same hash-driven prompt-replace pattern (~75 lines of boilerplate each). Lift `replaceUnmodifiedStagePrompts({ rootDir, oldHashes, newHashes, featureName, customizedHint })` into a shared helper so the next prompt-replace migration is ~15 lines. While at it, have `scripts/setup-data.js` import the same hash maps from each migration so the drift table stops duplicating them. Skipped during the 006 commit to keep diff focused.
- [ ] **Shots-aware scene-output-contract partial.** `data.sample/prompts/stages/pipeline-extract-scenes.md` now inlines the JSON output contract (with `shots[]`) instead of using `{{> scene-output-contract }}`. If a third shots-using stage ever appears (or a top-level scene field gets added), the partial and the inlined copy in extract-scenes will drift. Split into composable partials (`_partials/scene-fields-core.md` + `_partials/scene-fields-shots.md`) when that third caller materializes — until then the inline copy is the smaller risk.
- [ ] **Voice picker on character cards (Pipeline Audio 4b follow-up).** AudioStage renders fine without it (per-line render falls through to the project default voice), but binding `character.voiceId` today requires hand-editing JSON or PATCHing the universe canon. The picker should live on `CanonCard` (`client/src/components/pipeline/CanonCard.jsx`) when `kind === 'character'`: chip with current voice id, dropdown reading `/api/pipeline/tts/voices`, audition button that fetches `/api/pipeline/tts/preview` and plays inline, and a Save handler that PATCHes the universe canon entry (`updateUniverseCharacter` — needs to exist in `apiUniverseBuilder.js`). Same picker re-usable on a per-line override in `AudioStage.jsx`. Local OSS (Kokoro/Piper) always included; 3rd-party engines surface through the same merged list.
-- [ ] **Pipeline Audio — music + mux (Phase 4c/d).** Per the AnyFilm comparison plan (`~/.claude/plans/i-want-to-examine-polished-meteor.md` cluster C). 4c: local OSS music generation (MusicGen via Python sidecar mirroring image-gen wiring) + user-upload + library + 3rd-party stub. Music picker on AudioStage. 4d: mux VO + music into the episode-video CD stitch — extend the CD treatment to carry audio-file refs and let the final ffmpeg stitch overlay them.
+- [ ] **Pipeline Audio — music generation + mux (Phase 4c.2 / 4d).** Per the AnyFilm comparison plan (`~/.claude/plans/i-want-to-examine-polished-meteor.md` cluster C). 4c (user-upload + library + picker) **shipped 2026-05-16**. Remaining:
+ - **4c.2: Local OSS music generation.** MusicGen via a Python sidecar mirroring the image-gen wiring; new `'gen'` source on `stages.audio.music`. Plug into the same `listMusicLibrary` so generated tracks appear alongside uploads. Investigation needed first: pick a generator. MusicGen-MLX is local but bounded ~30s without sliding-window stitching; AudioLDM2 is older; Suno is the cleanest UX but commercial. ~150 LOC for the AudioStage button + queue routing once the generator is picked.
+ - **4c.3: 3rd-party music engine stubs.** Same UI affordance as the VO engines — once 4c.2 lands the abstraction, 3rd-party engines plug in as sibling sources.
+ - **4d: Mux VO + music into the episode-video CD stitch.** Extend `server/services/creativeDirector/stitchRunner.js` to read `stages.audio.lines[].audioFilename` + `stages.audio.music.trackFilename` from the source issue and emit a second ffmpeg pass that overlays them onto the per-clip video. Timing: VO tied to scene/dialogue order; music as a full-episode bed at configurable gain. New project-level `audioMode: 'per-clip' | 'silent' | 'pipeline'` ('pipeline' reads from the audio stage); 'per-clip' stays default for back-compat.
+- [ ] **Extract `listDirectoryByExtension(dir, { extensions, mapEntry })` helper in `server/lib/fileUtils.js`.** Three call sites today follow the same readdir + filter-by-extension + stat-per-entry shape: `server/services/loras.js#listLoras` (sidecar reads), `server/services/imageGen/local.js#listGallery` (civitai-aware fields), `server/services/pipeline/musicLibrary.js#listMusicLibrary`. Each carries domain-specific per-entry mapping, so the shared helper takes a `mapEntry(dirent, statResult) → entry|null` callback. Saves ~15 LOC at each site plus a single fix-point for future "use `readdir(withFileTypes:true)` to skip the stat when only `.isFile()` is needed" optimization. Surfaced from the /simplify pass on Phase 4c.
+- [ ] **Teach `request()` in `client/src/services/apiCore.js` about FormData.** Two helpers today bypass `request()` because it hard-codes `Content-Type: application/json`: `apiHealth.js#uploadAppleHealthXml` and `apiPipeline.js#uploadPipelineMusicTrack`. Each re-implements the error-shape extraction (`{ error, code, status }`) inline. Fix: in `request()`, when `body instanceof FormData`, omit the `Content-Type` header so the browser sets `multipart/form-data; boundary=...` automatically. Both call sites then collapse to a single `request()` call. Surfaced from the /simplify pass on Phase 4c.
- [ ] **Per-panel/scene image progress in the Pipeline UI.** Right now ComicPages and Storyboards record `jobId` but don't subscribe to the media-job SSE for live preview. Tie into the existing per-job progress hook so each panel shows live render thumbnails.
diff --git a/client/src/components/pipeline/stages/AudioStage.jsx b/client/src/components/pipeline/stages/AudioStage.jsx
index e7835006e4..0f8ec89897 100644
--- a/client/src/components/pipeline/stages/AudioStage.jsx
+++ b/client/src/components/pipeline/stages/AudioStage.jsx
@@ -12,20 +12,26 @@
*/
import { useEffect, useRef, useState } from 'react';
-import { Loader2, Sparkles, Wand2, Mic } from 'lucide-react';
+import { Loader2, Sparkles, Wand2, Mic, Music, Upload, Trash2 } from 'lucide-react';
import toast from '../../ui/Toast';
import {
extractPipelineAudioLines,
renderPipelineAudioLine,
patchPipelineAudioLine,
+ listPipelineMusicLibrary,
+ uploadPipelineMusicTrack,
+ attachPipelineMusicTrack,
+ detachPipelineMusicTrack,
+ deletePipelineMusicTrack,
PIPELINE_STAGE_LABELS,
PIPELINE_STAGE_STATUS_LABEL as STATUS_LABEL,
PIPELINE_STAGE_STATUS_COLOR as STATUS_COLOR,
} from '../../../services/api';
export default function AudioStage({ issue, onStageUpdate }) {
- const stage = issue.stages?.audio || { status: 'empty', lines: [] };
+ const stage = issue.stages?.audio || { status: 'empty', lines: [], music: null };
const lines = Array.isArray(stage.lines) ? stage.lines : [];
+ const music = stage.music || null;
const [extracting, setExtracting] = useState(false);
// Per-line render busy state keyed by line index — multiple lines can
// render concurrently with independent spinners.
@@ -48,6 +54,81 @@ export default function AudioStage({ issue, onStageUpdate }) {
if (armTimerRef.current) clearTimeout(armTimerRef.current);
}, []);
+ const [musicLibrary, setMusicLibrary] = useState(null);
+ const [musicLibraryLoading, setMusicLibraryLoading] = useState(false);
+ const [musicPickerOpen, setMusicPickerOpen] = useState(false);
+ const [musicUploading, setMusicUploading] = useState(false);
+ const [musicAttaching, setMusicAttaching] = useState(null);
+ // Inline confirm-row pattern per the user's preference: clicking trash
+ // reveals [Cancel] [Delete] for that row only. Stored as the filename so
+ // only one row shows the confirm at a time.
+ const [pendingLibraryDelete, setPendingLibraryDelete] = useState(null);
+ const fileInputRef = useRef(null);
+
+ const loadMusicLibrary = async () => {
+ setMusicLibraryLoading(true);
+ const result = await listPipelineMusicLibrary().catch((err) => {
+ toast.error(err.message || 'Failed to load music library');
+ return null;
+ });
+ setMusicLibraryLoading(false);
+ if (result) setMusicLibrary(result.tracks || []);
+ };
+
+ const openMusicPicker = async () => {
+ setMusicPickerOpen(true);
+ if (musicLibrary === null) await loadMusicLibrary();
+ };
+
+ const handleMusicUpload = async (file) => {
+ if (!file) return;
+ setMusicUploading(true);
+ const result = await uploadPipelineMusicTrack(issue.id, file).catch((err) => {
+ toast.error(err.message || 'Upload failed');
+ return null;
+ });
+ setMusicUploading(false);
+ if (!result) return;
+ onStageUpdate?.('audio', result.stage, result.issue);
+ setMusicLibrary(null);
+ setMusicPickerOpen(false);
+ toast.success(`Uploaded ${file.name}`);
+ };
+
+ const handleAttach = async (track) => {
+ setMusicAttaching(track.filename);
+ const result = await attachPipelineMusicTrack(issue.id, { trackFilename: track.filename, label: track.label }).catch((err) => {
+ toast.error(err.message || 'Attach failed');
+ return null;
+ });
+ setMusicAttaching(null);
+ if (!result) return;
+ onStageUpdate?.('audio', result.stage, result.issue);
+ setMusicPickerOpen(false);
+ toast.success(`Attached ${track.label || track.filename}`);
+ };
+
+ const handleDetach = async () => {
+ const result = await detachPipelineMusicTrack(issue.id).catch((err) => {
+ toast.error(err.message || 'Detach failed');
+ return null;
+ });
+ if (!result) return;
+ onStageUpdate?.('audio', result.stage, result.issue);
+ toast.success('Removed music from this issue');
+ };
+
+ const handleLibraryDelete = async (filename) => {
+ setPendingLibraryDelete(null);
+ const result = await deletePipelineMusicTrack(filename).catch((err) => {
+ toast.error(err.message || 'Delete failed');
+ return null;
+ });
+ if (!result) return;
+ setMusicLibrary((prev) => (prev || []).filter((t) => t.filename !== filename));
+ toast.success(`Removed ${filename} from library`);
+ };
+
const storyboardSceneCount = (issue.stages?.storyboards?.scenes || []).length;
const canExtract = storyboardSceneCount > 0;
@@ -249,6 +330,163 @@ export default function AudioStage({ issue, onStageUpdate }) {
})}
</ul>
)}
+
+ <section className="pt-4 border-t border-port-border">
+ <div className="flex items-start justify-between flex-wrap gap-3 mb-3">
+ <div className="flex items-center gap-3">
+ <Music className="w-5 h-5 text-port-accent" />
+ <div>
+ <h3 className="text-base font-semibold text-white">Background Music</h3>
+ <p className="text-xs text-gray-500 mt-0.5">
+ Optional track played under the rendered episode. Upload from disk now;
+ {' '}<span className="text-gray-600">local OSS generation (MusicGen) coming next.</span>
+ </p>
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept="audio/mpeg,audio/mp3,audio/wav,audio/x-wav,audio/mp4,audio/m4a,audio/ogg,audio/flac,.mp3,.wav,.m4a,.ogg,.flac"
+ onChange={(e) => {
+ const file = e.target.files?.[0];
+ e.target.value = '';
+ if (file) void handleMusicUpload(file);
+ }}
+ className="hidden"
+ />
+ <button
+ type="button"
+ onClick={() => fileInputRef.current?.click()}
+ disabled={musicUploading}
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-card border border-port-border text-white text-sm hover:border-port-accent/50 disabled:opacity-40"
+ >
+ {musicUploading ? <Loader2 size={14} className="animate-spin" /> : <Upload size={14} />}
+ Upload track
+ </button>
+ <button
+ type="button"
+ onClick={() => (musicPickerOpen ? setMusicPickerOpen(false) : openMusicPicker())}
+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-card border border-port-border text-white text-sm hover:border-port-accent/50"
+ >
+ <Music size={14} />
+ {musicPickerOpen ? 'Close library' : 'Pick from library'}
+ </button>
+ </div>
+ </div>
+
+ {music ? (
+ <div className="p-3 bg-port-card border border-port-border rounded-lg">
+ <div className="flex items-start justify-between gap-3 flex-wrap">
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2 mb-1">
+ <span className="text-sm font-medium text-white truncate">
+ {music.label || music.trackFilename}
+ </span>
+ <span className="text-[10px] uppercase tracking-wider text-gray-500">
+ {music.source || 'unknown'}
+ </span>
+ </div>
+ {music.trackFilename ? (
+ <audio
+ controls
+ src={`/data/music/${encodeURIComponent(music.trackFilename)}`}
+ className="w-full max-w-md"
+ >
+ <track kind="captions" />
+ </audio>
+ ) : null}
+ </div>
+ <button
+ type="button"
+ onClick={handleDetach}
+ title="Remove music from this issue (track stays in the library)"
+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:text-port-error border border-port-border hover:border-port-error/50"
+ >
+ <Trash2 size={12} /> Remove
+ </button>
+ </div>
+ </div>
+ ) : (
+ <p className="text-sm text-gray-400 italic">
+ No background music attached. Upload a track or pick one from the library.
+ </p>
+ )}
+
+ {musicPickerOpen ? (
+ <div className="mt-3 p-3 bg-port-bg border border-port-border rounded-lg">
+ <div className="flex items-center justify-between mb-2">
+ <span className="text-xs uppercase tracking-wider text-gray-500">Library</span>
+ {musicLibraryLoading ? (
+ <Loader2 size={12} className="animate-spin text-gray-500" />
+ ) : null}
+ </div>
+ {musicLibrary === null || musicLibraryLoading ? (
+ <p className="text-xs text-gray-500">Loading…</p>
+ ) : musicLibrary.length === 0 ? (
+ <p className="text-xs text-gray-500 italic">
+ Library is empty. Click <strong>Upload track</strong> above to add your first one.
+ </p>
+ ) : (
+ <ul className="space-y-1.5 max-h-80 overflow-y-auto">
+ {musicLibrary.map((track) => {
+ const isCurrent = music?.trackFilename === track.filename;
+ const isAttaching = musicAttaching === track.filename;
+ const confirming = pendingLibraryDelete === track.filename;
+ return (
+ <li key={track.filename} className="flex items-center gap-2 p-2 bg-port-card border border-port-border rounded">
+ <div className="min-w-0 flex-1">
+ <div className="text-sm text-white truncate">{track.label || track.filename}</div>
+ <div className="text-[10px] text-gray-500 font-mono">{track.filename}</div>
+ </div>
+ {confirming ? (
+ <>
+ <span className="text-xs text-gray-400 italic">Delete from library?</span>
+ <button
+ type="button"
+ onClick={() => setPendingLibraryDelete(null)}
+ className="px-2 py-1 rounded border border-port-border text-gray-300 text-xs hover:border-gray-500"
+ >
+ Cancel
+ </button>
+ <button
+ type="button"
+ onClick={() => handleLibraryDelete(track.filename)}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded bg-port-error text-white text-xs"
+ >
+ <Trash2 size={12} /> Delete
+ </button>
+ </>
+ ) : (
+ <>
+ <button
+ type="button"
+ onClick={() => handleAttach(track)}
+ disabled={isCurrent || isAttaching}
+ title={isCurrent ? 'Already attached to this issue' : 'Attach to this issue'}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded bg-port-accent text-white text-xs disabled:opacity-50"
+ >
+ {isAttaching ? <Loader2 size={12} className="animate-spin" /> : null}
+ {isCurrent ? 'Attached' : 'Attach'}
+ </button>
+ <button
+ type="button"
+ onClick={() => setPendingLibraryDelete(track.filename)}
+ title="Delete from library (issues that point at this file will fail playback)"
+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs border border-port-border text-gray-400 hover:text-port-error hover:border-port-error/50"
+ >
+ <Trash2 size={12} />
+ </button>
+ </>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </div>
+ ) : null}
+ </section>
</div>
);
}
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index 835e712aba..46d32129eb 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -1,4 +1,5 @@
-import { request } from './apiCore.js';
+import { request, API_BASE } from './apiCore.js';
+import { buildFormData } from './apiImageVideo.js';
// Stage IDs mirror server/services/pipeline/issues.js — keep these in sync.
// `nouns` is a UI-only pseudo-stage: it has no server stage record + no LLM
@@ -365,3 +366,44 @@ export const patchPipelineAudioLine = (issueId, lineIdx, patch) =>
method: 'PATCH',
body: JSON.stringify(patch),
});
+
+// ---- Music library (Phase 4c) ----
+export const listPipelineMusicLibrary = () =>
+ request('/pipeline/audio/music-library');
+
+// Bypasses `request()` because that helper hard-codes
+// `Content-Type: application/json`, which conflicts with FormData's
+// auto-generated multipart boundary.
+export const uploadPipelineMusicTrack = async (issueId, file, { label } = {}) => {
+ const res = await fetch(
+ `${API_BASE}/pipeline/issues/${encodeURIComponent(issueId)}/stages/audio/music/upload`,
+ { method: 'POST', body: buildFormData({ track: file, label }) },
+ );
+ if (!res.ok) {
+ const err = await res.json().catch(() => ({ error: res.statusText }));
+ const e = new Error(err.error || res.statusText);
+ e.code = err.code;
+ e.status = res.status;
+ throw e;
+ }
+ return res.json();
+};
+
+export const attachPipelineMusicTrack = (issueId, { trackFilename, label } = {}) =>
+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/audio/music/attach`, {
+ method: 'POST',
+ body: JSON.stringify({ trackFilename, label }),
+ });
+
+export const detachPipelineMusicTrack = (issueId) =>
+ request(`/pipeline/issues/${encodeURIComponent(issueId)}/stages/audio/music`, {
+ method: 'DELETE',
+ });
+
+// Library deletes do NOT auto-purge issue references — by design, so the
+// user sees the broken playback and re-picks rather than the library
+// silently rewriting issue state.
+export const deletePipelineMusicTrack = (filename) =>
+ request(`/pipeline/audio/music-library/${encodeURIComponent(filename)}`, {
+ method: 'DELETE',
+ });
diff --git a/server/index.js b/server/index.js
index 530194516b..44abc1e60c 100644
--- a/server/index.js
+++ b/server/index.js
@@ -477,6 +477,9 @@ app.use('/data/video-thumbnails', express.static(PATHS.videoThumbnails));
// Voice-over WAVs rendered by the pipeline audio stage — the AudioStage UI
// pulls them inline via <audio src="/data/audio/<filename>">.
app.use('/data/audio', express.static(PATHS.audio));
+// Background-music tracks (uploaded today, generated locally tomorrow). The
+// AudioStage music picker plays them inline via <audio src="/data/music/...">.
+app.use('/data/music', express.static(PATHS.music));
// Serve built client UI (production mode — no Vite dev server needed)
const CLIENT_DIST = join(__dirname, '..', 'client', 'dist');
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index 51425ba1b6..dcb9c103e3 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -66,10 +66,14 @@ export const PATHS = {
loras: join(__lib_dirname, '../../data/loras'),
videos: join(__lib_dirname, '../../data/videos'),
videoThumbnails: join(__lib_dirname, '../../data/video-thumbnails'),
- // Persisted audio renders (voice-over lines, music). Kept distinct from
+ // Persisted audio renders (voice-over lines). Kept distinct from
// the in-memory voice-agent synthesis path in services/voice/ — that path
// streams WAV over Socket.IO without ever touching disk.
audio: join(__lib_dirname, '../../data/audio'),
+ // Uploaded + (eventually) generated background music tracks. Separate from
+ // `audio/` so the user can browse + reuse a track across issues without
+ // walking through the VO-line filenames.
+ music: join(__lib_dirname, '../../data/music'),
slashdo: join(__lib_dirname, '../../lib/slashdo')
};
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index 2514f16534..df0c999518 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -60,6 +60,16 @@ import { listVisualStyles } from '../lib/visualStyles.js';
import { buildComicPdf, PAGE_SIZES, DEFAULT_PAGE_SIZE, ERR_NO_RENDERED_PAGES } from '../services/pipeline/comicPdf.js';
import { listAllVoices, synthesizeToFile, parseVoiceId, extractDialogueLines, resolveVoiceForLine } from '../services/pipeline/audio.js';
import { synthesize as synthesizeVoice } from '../services/voice/tts.js';
+import {
+ listMusicLibrary,
+ importUploadedTrack,
+ deleteMusicTrack,
+ statMusicTrack,
+ isSupportedMusicUpload,
+ MUSIC_SOURCE,
+ MUSIC_UPLOAD_MAX_BYTES,
+} from '../services/pipeline/musicLibrary.js';
+import { uploadSingle } from '../lib/multipart.js';
import { parseComicScript } from '../lib/comicScriptParser.js';
import {
LENGTH_PROFILE_NAMES,
@@ -652,6 +662,98 @@ router.post('/issues/:id/stages/audio/lines/:lineIdx/render', asyncHandler(async
});
}));
+// Music library — shared across every issue; the audio stage stores only a
+// pointer (`music.trackFilename`). Local OSS generation (4c.2) and 3rd-party
+// engines (4c.3) plug in as sibling sources behind the same library list.
+
+const musicUpload = uploadSingle('track', {
+ limits: { fileSize: MUSIC_UPLOAD_MAX_BYTES },
+ fileFilter: (_req, file, cb) => {
+ if (isSupportedMusicUpload(file)) {
+ cb(null, true);
+ } else {
+ cb(new ServerError(
+ 'Unsupported audio format — accepted: MP3, WAV, M4A, OGG, FLAC',
+ { status: 400, code: 'PIPELINE_MUSIC_UNSUPPORTED_FORMAT' },
+ ));
+ }
+ },
+});
+
+// The audio stage status reflects whether the *VO line list* is ready, since
+// music alone doesn't make an episode renderable. So music-only mutations
+// leave status at 'empty' when no lines exist and bump to 'edited' otherwise.
+const audioStatusAfterMusicChange = (issue) =>
+ ((issue.stages?.audio?.lines || []).length ? 'edited' : 'empty');
+
+router.get('/audio/music-library', asyncHandler(async (_req, res) => {
+ res.json({ tracks: await listMusicLibrary() });
+}));
+
+router.post('/issues/:id/stages/audio/music/upload', musicUpload, asyncHandler(async (req, res) => {
+ if (!req.file) {
+ throw new ServerError('No audio file uploaded', {
+ status: 400, code: 'PIPELINE_MUSIC_NO_FILE',
+ });
+ }
+ const issue = await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const { filename, sizeBytes } = await importUploadedTrack(req.file.path, req.file.originalname);
+ const label = typeof req.body?.label === 'string' && req.body.label.trim()
+ ? req.body.label.trim()
+ : null;
+ const { issue: updatedIssue, stage } = await issuesSvc.updateStage(req.params.id, 'audio', {
+ status: audioStatusAfterMusicChange(issue),
+ music: { source: MUSIC_SOURCE.UPLOAD, trackFilename: filename, label },
+ errorMessage: '',
+ });
+ res.json({ issue: updatedIssue, stage, music: stage.music, sizeBytes });
+}));
+
+const musicAttachSchema = z.object({
+ trackFilename: z.string().trim().min(1).max(500),
+ label: z.string().trim().max(200).nullable().optional(),
+});
+router.post('/issues/:id/stages/audio/music/attach', asyncHandler(async (req, res) => {
+ const body = validateRequest(musicAttachSchema, req.body ?? {});
+ // Single-file stat instead of full library listing — one syscall vs. N+1.
+ const found = await statMusicTrack(body.trackFilename);
+ if (!found) {
+ throw new ServerError('Music track not found in library', {
+ status: 404, code: 'PIPELINE_MUSIC_NOT_FOUND',
+ });
+ }
+ const issue = await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const { issue: updatedIssue, stage } = await issuesSvc.updateStage(req.params.id, 'audio', {
+ status: audioStatusAfterMusicChange(issue),
+ music: {
+ source: MUSIC_SOURCE.LIBRARY,
+ trackFilename: body.trackFilename,
+ label: body.label?.trim() || found.label,
+ },
+ errorMessage: '',
+ });
+ res.json({ issue: updatedIssue, stage, music: stage.music });
+}));
+
+router.delete('/issues/:id/stages/audio/music', asyncHandler(async (req, res) => {
+ const issue = await issuesSvc.getIssue(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const { issue: updatedIssue, stage } = await issuesSvc.updateStage(req.params.id, 'audio', {
+ status: audioStatusAfterMusicChange(issue),
+ music: null,
+ errorMessage: '',
+ });
+ res.json({ issue: updatedIssue, stage });
+}));
+
+// Deleting from the library leaves stale `music.trackFilename` pointers on
+// issues so the user sees the broken playback and re-picks. Auto-purging
+// would scan every issue on every delete; deferred until needed.
+router.delete('/audio/music-library/:filename', asyncHandler(async (req, res) => {
+ const { filename } = req.params;
+ const existed = await deleteMusicTrack(filename);
+ res.json({ filename, deleted: existed });
+}));
+
// =====================
// Series routes
// =====================
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index 78102f7c83..847c4a5c4e 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -191,6 +191,48 @@ vi.mock('../services/voice/tts.js', () => ({
VALID_ENGINES: new Set(['kokoro', 'piper']),
}));
+const musicLibraryStore = new Map();
+let lastImportedName = null;
+const assertSafe = (name) => {
+ if (typeof name !== 'string' || name.includes('..') || name.includes('/')) {
+ const e = new Error('Invalid music filename');
+ e.status = 400; e.code = 'VALIDATION_ERROR';
+ throw e;
+ }
+};
+vi.mock('../services/pipeline/musicLibrary.js', () => ({
+ MUSIC_UPLOAD_MAX_BYTES: 50 * 1024 * 1024,
+ MUSIC_SOURCE: { UPLOAD: 'upload', LIBRARY: 'library', GEN: 'gen' },
+ isSupportedMusicUpload: vi.fn(() => true),
+ listMusicLibrary: vi.fn(async () => Array.from(musicLibraryStore.values())),
+ importUploadedTrack: vi.fn(async (_tmpPath, originalName) => {
+ lastImportedName = originalName;
+ const filename = `music-uuid-${++uuidCounter}.mp3`;
+ musicLibraryStore.set(filename, { filename, label: originalName.replace(/\.[^.]+$/, ''), sizeBytes: 11, updatedAt: new Date().toISOString() });
+ return { filename, sizeBytes: 11 };
+ }),
+ statMusicTrack: vi.fn(async (filename) => {
+ assertSafe(filename);
+ return musicLibraryStore.get(filename) || null;
+ }),
+ deleteMusicTrack: vi.fn(async (filename) => {
+ assertSafe(filename);
+ const existed = musicLibraryStore.has(filename);
+ musicLibraryStore.delete(filename);
+ return existed;
+ }),
+}));
+
+vi.mock('../lib/multipart.js', () => ({
+ uploadSingle: () => (req, _res, next) => {
+ req.file = req.body?._mockFile || null;
+ delete req.body?._mockFile;
+ next();
+ },
+ optionalUpload: () => (_req, _res, next) => next(),
+ uploadFields: () => (_req, _res, next) => next(),
+}));
+
const pipelineRouter = (await import('./pipeline.js')).default;
function makeApp() {
@@ -1310,4 +1352,120 @@ describe('pipeline routes', () => {
expect(r.status).toBe(400);
});
});
+
+ describe('music library routes', () => {
+ beforeEach(() => {
+ musicLibraryStore.clear();
+ lastImportedName = null;
+ });
+
+ async function seedIssue(app) {
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S' });
+ const iss = await request(app).post(`/api/pipeline/series/${ser.body.id}/issues`).send({ title: 'I' });
+ return iss.body;
+ }
+
+ it('GET /audio/music-library returns the current track list', async () => {
+ const app = makeApp();
+ musicLibraryStore.set('music-1.mp3', { filename: 'music-1.mp3', label: 'theme', sizeBytes: 100, updatedAt: '2026-05-15T00:00:00.000Z' });
+ const r = await request(app).get('/api/pipeline/audio/music-library');
+ expect(r.status).toBe(200);
+ expect(r.body.tracks).toHaveLength(1);
+ expect(r.body.tracks[0].filename).toBe('music-1.mp3');
+ });
+
+ it('POST /audio/music/upload imports the file and attaches it to the issue', async () => {
+ const app = makeApp();
+ const iss = await seedIssue(app);
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.id}/stages/audio/music/upload`)
+ // The mock multipart parser pulls req.file out of req.body._mockFile so
+ // this test can sidestep the real streaming parser without losing the
+ // route's req.file contract.
+ .send({ _mockFile: { path: '/tmp/uploaded.mp3', originalname: 'My Theme.mp3', mimetype: 'audio/mpeg', size: 11 } });
+ expect(r.status).toBe(200);
+ expect(r.body.music.source).toBe('upload');
+ expect(r.body.music.trackFilename).toMatch(/^music-uuid-/);
+ // Persisted on the issue
+ const after = await request(app).get(`/api/pipeline/issues/${iss.id}`);
+ expect(after.body.stages.audio.music.trackFilename).toBe(r.body.music.trackFilename);
+ expect(lastImportedName).toBe('My Theme.mp3');
+ });
+
+ it('POST /audio/music/upload 400s when no file is uploaded', async () => {
+ const app = makeApp();
+ const iss = await seedIssue(app);
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.id}/stages/audio/music/upload`)
+ .send({});
+ expect(r.status).toBe(400);
+ });
+
+ it('POST /audio/music/attach attaches an existing library track', async () => {
+ const app = makeApp();
+ const iss = await seedIssue(app);
+ musicLibraryStore.set('shared.mp3', { filename: 'shared.mp3', label: 'shared', sizeBytes: 100, updatedAt: '2026-05-15T00:00:00.000Z' });
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.id}/stages/audio/music/attach`)
+ .send({ trackFilename: 'shared.mp3', label: 'Library pick' });
+ expect(r.status).toBe(200);
+ expect(r.body.music.source).toBe('library');
+ expect(r.body.music.trackFilename).toBe('shared.mp3');
+ expect(r.body.music.label).toBe('Library pick');
+ });
+
+ it('POST /audio/music/attach 404s when the track is not in the library', async () => {
+ const app = makeApp();
+ const iss = await seedIssue(app);
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.id}/stages/audio/music/attach`)
+ .send({ trackFilename: 'ghost.mp3' });
+ expect(r.status).toBe(404);
+ });
+
+ it('POST /audio/music/attach 400s on path-traversal filenames', async () => {
+ const app = makeApp();
+ const iss = await seedIssue(app);
+ const r = await request(app)
+ .post(`/api/pipeline/issues/${iss.id}/stages/audio/music/attach`)
+ .send({ trackFilename: '../etc/passwd' });
+ expect(r.status).toBe(400);
+ });
+
+ it('DELETE /audio/music clears music from the issue without deleting the library entry', async () => {
+ const app = makeApp();
+ const iss = await seedIssue(app);
+ musicLibraryStore.set('shared.mp3', { filename: 'shared.mp3', label: 'shared', sizeBytes: 100, updatedAt: '2026-05-15T00:00:00.000Z' });
+ await request(app)
+ .post(`/api/pipeline/issues/${iss.id}/stages/audio/music/attach`)
+ .send({ trackFilename: 'shared.mp3' });
+ const r = await request(app)
+ .delete(`/api/pipeline/issues/${iss.id}/stages/audio/music`)
+ .send();
+ expect(r.status).toBe(200);
+ expect(r.body.stage.music).toBeNull();
+ // Library entry survives the issue detach
+ expect(musicLibraryStore.has('shared.mp3')).toBe(true);
+ });
+
+ it('DELETE /audio/music-library/:filename removes the file from the library', async () => {
+ const app = makeApp();
+ musicLibraryStore.set('doomed.mp3', { filename: 'doomed.mp3', label: 'doomed', sizeBytes: 1, updatedAt: '2026-05-15T00:00:00.000Z' });
+ const r = await request(app)
+ .delete('/api/pipeline/audio/music-library/doomed.mp3')
+ .send();
+ expect(r.status).toBe(200);
+ expect(r.body.deleted).toBe(true);
+ expect(musicLibraryStore.has('doomed.mp3')).toBe(false);
+ });
+
+ it('DELETE /audio/music-library/:filename returns deleted:false when the file is already gone', async () => {
+ const app = makeApp();
+ const r = await request(app)
+ .delete('/api/pipeline/audio/music-library/ghost.mp3')
+ .send();
+ expect(r.status).toBe(200);
+ expect(r.body.deleted).toBe(false);
+ });
+ });
});
diff --git a/server/services/pipeline/musicLibrary.js b/server/services/pipeline/musicLibrary.js
new file mode 100644
index 0000000000..18890be1b9
--- /dev/null
+++ b/server/services/pipeline/musicLibrary.js
@@ -0,0 +1,177 @@
+/**
+ * Background-music library for the pipeline audio stage.
+ *
+ * Storage model: a single shared directory at `PATHS.music`. Every track —
+ * uploaded today, locally generated tomorrow — lives here under a deterministic
+ * basename. The library list is just `readdir + stat` filtered to known audio
+ * extensions. No JSON index — the filesystem is the source of truth, which
+ * keeps the library robust across server restarts and direct file drops.
+ *
+ * Provider strategy mirrors `audio.js`: **local-first**. User-upload is the
+ * always-available path (zero infra). Local MusicGen via a Python sidecar
+ * (4c.2 follow-up) and a 3rd-party Suno stub (4c.3) plug in as sibling
+ * sources behind the same library list — the AudioStage picker doesn't
+ * care which one wrote the bytes.
+ */
+
+import { readdir, stat, copyFile, unlink } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join, extname, basename } from 'path';
+import { randomUUID } from 'crypto';
+import { PATHS, ensureDir, assertSafeFilename } from '../../lib/fileUtils.js';
+
+// Mirror of the sanitizer's MUSIC_SOURCES set in `services/pipeline/issues.js`.
+// Exported so routes don't sprinkle bare strings; `'gen'` is reserved for the
+// next sub-phase (local MusicGen sidecar / 3rd-party Suno stub).
+export const MUSIC_SOURCE = Object.freeze({
+ UPLOAD: 'upload',
+ LIBRARY: 'library',
+ GEN: 'gen',
+});
+
+export const SUPPORTED_AUDIO_EXTENSIONS = Object.freeze(['.mp3', '.wav', '.m4a', '.ogg', '.flac']);
+
+export const SUPPORTED_AUDIO_MIME = Object.freeze({
+ '.mp3': 'audio/mpeg',
+ '.wav': 'audio/wav',
+ '.m4a': 'audio/mp4',
+ '.ogg': 'audio/ogg',
+ '.flac': 'audio/flac',
+});
+
+export const MUSIC_UPLOAD_MAX_BYTES = 50 * 1024 * 1024;
+
+// Returns true if the MIME or filename extension marks this as one of our
+// supported audio formats. Used by the multipart fileFilter — matching either
+// signal handles browsers that report `application/octet-stream` for drag-
+// drop uploads while still requiring a known extension.
+export function isSupportedMusicUpload(file) {
+ if (!file) return false;
+ const ext = (extname(file.originalname || '') || '').toLowerCase();
+ if (!SUPPORTED_AUDIO_EXTENSIONS.includes(ext)) return false;
+ const mime = (file.mimetype || '').toLowerCase();
+ if (mime.startsWith('audio/')) return true;
+ if (mime === 'application/octet-stream') return true;
+ if (mime === 'video/mp4' && ext === '.m4a') return true; // some browsers
+ return false;
+}
+
+/**
+ * Validate a stored music filename — same pattern as the rest of the codebase.
+ * Rejects path traversal, separators, and disallowed extensions.
+ */
+export function assertSafeMusicFilename(filename) {
+ assertSafeFilename(filename, {
+ extensions: [...SUPPORTED_AUDIO_EXTENSIONS],
+ subject: 'music filename',
+ });
+}
+
+/**
+ * Generate a fresh deterministic basename for a newly-uploaded track. Keeps
+ * the original extension so the static handler picks the right Content-Type.
+ */
+export function buildStoredFilename(originalName) {
+ const ext = (extname(originalName || '') || '.mp3').toLowerCase();
+ const safeExt = SUPPORTED_AUDIO_EXTENSIONS.includes(ext) ? ext : '.mp3';
+ return `music-${randomUUID()}${safeExt}`;
+}
+
+/**
+ * Strip the extension off a stored filename to produce a default label for
+ * the library picker when the caller didn't pass one explicitly.
+ */
+export function deriveDefaultLabel(originalName) {
+ const name = basename(originalName || '');
+ const ext = extname(name);
+ return ext ? name.slice(0, -ext.length) : name;
+}
+
+/**
+ * List every track currently sitting in the library. Each entry carries the
+ * stored filename (what the audio stage persists on `music.trackFilename`),
+ * file size, and last-modified timestamp so the picker can show "added X
+ * minutes ago" without a separate metadata store.
+ *
+ * Missing directory → empty list (no surprise 500 on a fresh install).
+ */
+export async function listMusicLibrary() {
+ await ensureDir(PATHS.music);
+ let names = [];
+ try {
+ names = await readdir(PATHS.music);
+ } catch (err) {
+ if (err.code === 'ENOENT') return [];
+ throw err;
+ }
+ const entries = await Promise.all(
+ names
+ .filter((name) => SUPPORTED_AUDIO_EXTENSIONS.includes((extname(name) || '').toLowerCase()))
+ .map(async (name) => {
+ const full = join(PATHS.music, name);
+ const s = await stat(full).catch(() => null);
+ if (!s || !s.isFile()) return null;
+ return {
+ filename: name,
+ label: deriveDefaultLabel(name),
+ sizeBytes: s.size,
+ updatedAt: s.mtime.toISOString(),
+ };
+ }),
+ );
+ return entries.filter(Boolean).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
+}
+
+/**
+ * Move an uploaded temp file into the library and return the persisted
+ * filename. Caller (the route) reads `req.file.path` from the multipart
+ * helper. Returns `{ filename, sizeBytes }`.
+ */
+export async function importUploadedTrack(tempPath, originalName) {
+ await ensureDir(PATHS.music);
+ const filename = buildStoredFilename(originalName);
+ const dest = join(PATHS.music, filename);
+ // copyFile + unlink instead of rename — the multipart helper writes to
+ // os.tmpdir(), which may sit on a different filesystem (rename across
+ // devices throws EXDEV on Linux). Copy works regardless; the temp file
+ // unlink is best-effort cleanup.
+ await copyFile(tempPath, dest);
+ await unlink(tempPath).catch(() => {});
+ const s = await stat(dest).catch(() => null);
+ return { filename, sizeBytes: s?.size ?? 0 };
+}
+
+/**
+ * Confirm a track exists in the library. Returns the same shape as a list
+ * entry (`{ filename, label, sizeBytes }`) or `null` if missing. Validates
+ * the filename to prevent path-traversal.
+ */
+export async function statMusicTrack(filename) {
+ assertSafeMusicFilename(filename);
+ const full = join(PATHS.music, filename);
+ if (!existsSync(full)) return null;
+ const s = await stat(full).catch(() => null);
+ if (!s || !s.isFile()) return null;
+ return {
+ filename,
+ label: deriveDefaultLabel(filename),
+ sizeBytes: s.size,
+ };
+}
+
+/**
+ * Delete a track from the library by stored filename. Returns true if the
+ * file existed and was removed; false if it was already gone. Validates the
+ * filename so a path-traversal attempt can't escape `PATHS.music`.
+ */
+export async function deleteMusicTrack(filename) {
+ assertSafeMusicFilename(filename);
+ const full = join(PATHS.music, filename);
+ try {
+ await unlink(full);
+ return true;
+ } catch (err) {
+ if (err.code === 'ENOENT') return false;
+ throw err;
+ }
+}
diff --git a/server/services/pipeline/musicLibrary.test.js b/server/services/pipeline/musicLibrary.test.js
new file mode 100644
index 0000000000..fd30bf7a8c
--- /dev/null
+++ b/server/services/pipeline/musicLibrary.test.js
@@ -0,0 +1,219 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { mkdir, rm, writeFile, readFile, readdir, stat } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+
+const TEST_HOME = join(tmpdir(), `portos-music-test-${process.pid}-${Date.now()}`);
+const FAKE_MUSIC_DIR = join(TEST_HOME, 'music');
+
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ return {
+ ...actual,
+ PATHS: { ...actual.PATHS, music: FAKE_MUSIC_DIR },
+ ensureDir: vi.fn(async (dir) => mkdir(dir, { recursive: true })),
+ };
+});
+
+const {
+ listMusicLibrary,
+ importUploadedTrack,
+ deleteMusicTrack,
+ statMusicTrack,
+ isSupportedMusicUpload,
+ buildStoredFilename,
+ deriveDefaultLabel,
+ assertSafeMusicFilename,
+ MUSIC_SOURCE,
+ SUPPORTED_AUDIO_EXTENSIONS,
+} = await import('./musicLibrary.js');
+
+beforeEach(async () => {
+ await rm(TEST_HOME, { recursive: true, force: true }).catch(() => {});
+ await mkdir(FAKE_MUSIC_DIR, { recursive: true });
+});
+
+afterEach(async () => {
+ await rm(TEST_HOME, { recursive: true, force: true }).catch(() => {});
+});
+
+describe('isSupportedMusicUpload', () => {
+ it('accepts MP3/WAV/M4A/OGG/FLAC by extension when MIME is audio/*', () => {
+ for (const ext of SUPPORTED_AUDIO_EXTENSIONS) {
+ expect(isSupportedMusicUpload({ originalname: `track${ext}`, mimetype: 'audio/mpeg' })).toBe(true);
+ }
+ });
+
+ it('accepts application/octet-stream when extension is known (drag-drop browsers)', () => {
+ expect(isSupportedMusicUpload({ originalname: 'track.mp3', mimetype: 'application/octet-stream' })).toBe(true);
+ });
+
+ it('accepts video/mp4 only when extension is .m4a (Safari quirk)', () => {
+ expect(isSupportedMusicUpload({ originalname: 'audio.m4a', mimetype: 'video/mp4' })).toBe(true);
+ expect(isSupportedMusicUpload({ originalname: 'movie.mp4', mimetype: 'video/mp4' })).toBe(false);
+ });
+
+ it('rejects unknown extensions even with audio/* MIME', () => {
+ expect(isSupportedMusicUpload({ originalname: 'track.aiff', mimetype: 'audio/aiff' })).toBe(false);
+ });
+
+ it('rejects null/empty input', () => {
+ expect(isSupportedMusicUpload(null)).toBe(false);
+ expect(isSupportedMusicUpload({})).toBe(false);
+ });
+});
+
+describe('buildStoredFilename', () => {
+ it('preserves a known extension', () => {
+ expect(buildStoredFilename('My Song.wav')).toMatch(/^music-[0-9a-f-]+\.wav$/);
+ });
+
+ it('falls back to .mp3 for unknown/missing extension', () => {
+ expect(buildStoredFilename('untitled')).toMatch(/^music-[0-9a-f-]+\.mp3$/);
+ expect(buildStoredFilename('audio.xyz')).toMatch(/^music-[0-9a-f-]+\.mp3$/);
+ });
+
+ it('generates distinct filenames per call', () => {
+ const a = buildStoredFilename('track.mp3');
+ const b = buildStoredFilename('track.mp3');
+ expect(a).not.toBe(b);
+ });
+});
+
+describe('deriveDefaultLabel', () => {
+ it('strips the extension', () => {
+ expect(deriveDefaultLabel('My Song.wav')).toBe('My Song');
+ });
+
+ it('leaves names without extension untouched', () => {
+ expect(deriveDefaultLabel('untitled')).toBe('untitled');
+ });
+});
+
+describe('assertSafeMusicFilename', () => {
+ it('accepts well-formed library filenames', () => {
+ expect(() => assertSafeMusicFilename('music-abc.mp3')).not.toThrow();
+ expect(() => assertSafeMusicFilename('music-abc.wav')).not.toThrow();
+ });
+
+ it('rejects path traversal', () => {
+ expect(() => assertSafeMusicFilename('../etc/passwd')).toThrow();
+ expect(() => assertSafeMusicFilename('foo/bar.mp3')).toThrow();
+ expect(() => assertSafeMusicFilename('..')).toThrow();
+ });
+
+ it('rejects unsupported extensions', () => {
+ expect(() => assertSafeMusicFilename('foo.aiff')).toThrow();
+ });
+});
+
+describe('listMusicLibrary', () => {
+ it('returns an empty list on a fresh install (no dir yet)', async () => {
+ await rm(FAKE_MUSIC_DIR, { recursive: true, force: true });
+ const tracks = await listMusicLibrary();
+ expect(tracks).toEqual([]);
+ // ensureDir should have created the directory by the time we return
+ expect(existsSync(FAKE_MUSIC_DIR)).toBe(true);
+ });
+
+ it('lists only known audio extensions and skips other files', async () => {
+ await writeFile(join(FAKE_MUSIC_DIR, 'a.mp3'), Buffer.from('a'));
+ await writeFile(join(FAKE_MUSIC_DIR, 'b.wav'), Buffer.from('bb'));
+ await writeFile(join(FAKE_MUSIC_DIR, 'cover.png'), Buffer.from('ccc'));
+ await writeFile(join(FAKE_MUSIC_DIR, 'notes.txt'), Buffer.from('dddd'));
+ const tracks = await listMusicLibrary();
+ const names = tracks.map((t) => t.filename).sort();
+ expect(names).toEqual(['a.mp3', 'b.wav']);
+ });
+
+ it('sorts newest-first', async () => {
+ // Stagger mtimes by writing then touching forward in time
+ await writeFile(join(FAKE_MUSIC_DIR, 'older.mp3'), Buffer.from('o'));
+ await new Promise((r) => setTimeout(r, 10));
+ await writeFile(join(FAKE_MUSIC_DIR, 'newer.mp3'), Buffer.from('n'));
+ const tracks = await listMusicLibrary();
+ expect(tracks[0].filename).toBe('newer.mp3');
+ expect(tracks[1].filename).toBe('older.mp3');
+ });
+
+ it('exposes label + sizeBytes + updatedAt on each entry', async () => {
+ await writeFile(join(FAKE_MUSIC_DIR, 'theme.mp3'), Buffer.from('hello'));
+ const [track] = await listMusicLibrary();
+ expect(track).toMatchObject({
+ filename: 'theme.mp3',
+ label: 'theme',
+ sizeBytes: 5,
+ });
+ expect(typeof track.updatedAt).toBe('string');
+ expect(track.updatedAt.endsWith('Z')).toBe(true);
+ });
+});
+
+describe('importUploadedTrack', () => {
+ it('copies the temp upload into PATHS.music and returns a uuid filename', async () => {
+ const tmp = join(TEST_HOME, 'upload-tmp.mp3');
+ await writeFile(tmp, Buffer.from('audio bytes'));
+ const { filename, sizeBytes } = await importUploadedTrack(tmp, 'My Theme.mp3');
+ expect(filename).toMatch(/^music-[0-9a-f-]+\.mp3$/);
+ expect(sizeBytes).toBe(11);
+ // Destination written
+ const written = await readFile(join(FAKE_MUSIC_DIR, filename));
+ expect(written.toString()).toBe('audio bytes');
+ // Temp source cleaned up
+ expect(existsSync(tmp)).toBe(false);
+ });
+
+ it('is robust when the temp file lives on a different fs (copy not rename)', async () => {
+ // We can't easily simulate EXDEV here, but verify the copy-then-unlink
+ // order succeeds when both paths are local.
+ const tmp = join(TEST_HOME, 'upload-tmp.wav');
+ await writeFile(tmp, Buffer.from('wav'));
+ const { filename } = await importUploadedTrack(tmp, 'a.wav');
+ expect(existsSync(join(FAKE_MUSIC_DIR, filename))).toBe(true);
+ });
+});
+
+describe('statMusicTrack', () => {
+ it('returns shape when the file exists', async () => {
+ await writeFile(join(FAKE_MUSIC_DIR, 'theme.mp3'), Buffer.from('hi'));
+ const result = await statMusicTrack('theme.mp3');
+ expect(result).toMatchObject({ filename: 'theme.mp3', label: 'theme', sizeBytes: 2 });
+ });
+
+ it('returns null when missing — one syscall, not a list-and-find', async () => {
+ expect(await statMusicTrack('ghost.mp3')).toBeNull();
+ });
+
+ it('throws on path-traversal attempts', async () => {
+ await expect(statMusicTrack('../etc/passwd')).rejects.toThrow();
+ });
+});
+
+describe('MUSIC_SOURCE', () => {
+ it('matches the sanitizer source allowlist in issues.js', () => {
+ expect(MUSIC_SOURCE).toMatchObject({
+ UPLOAD: 'upload',
+ LIBRARY: 'library',
+ GEN: 'gen',
+ });
+ });
+});
+
+describe('deleteMusicTrack', () => {
+ it('removes the file and returns true when it existed', async () => {
+ await writeFile(join(FAKE_MUSIC_DIR, 'doomed.mp3'), Buffer.from('x'));
+ const result = await deleteMusicTrack('doomed.mp3');
+ expect(result).toBe(true);
+ expect(existsSync(join(FAKE_MUSIC_DIR, 'doomed.mp3'))).toBe(false);
+ });
+
+ it('returns false when the file was already gone', async () => {
+ const result = await deleteMusicTrack('missing.mp3');
+ expect(result).toBe(false);
+ });
+
+ it('throws on path-traversal attempts (never touches the FS)', async () => {
+ await expect(deleteMusicTrack('../../etc/passwd')).rejects.toThrow();
+ });
+});