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: import Suno song exports into the music library with provenance (#8967)
[._.]/ Adam Eivyc5594c8b992a
diff --git a/client/src/components/music/TrackRenderCard.jsx b/client/src/components/music/TrackRenderCard.jsxindex 0a84ac17bf..53dc1fad07 100644--- a/client/src/components/music/TrackRenderCard.jsx+++ b/client/src/components/music/TrackRenderCard.jsx@@ -14,6 +14,7 @@ import { Maximize2, Sparkles, Download, Trash2, CheckCircle2, Music2, Upload, Fiimport InlineConfirmRow from '../ui/InlineConfirmRow';import { formatTimecode, timeAgo } from '../../utils/formatters';import { trackAudioUrl } from '../../services/api';+import { renderSourceLabel } from '../../lib/trackProvenance';export default function TrackRenderCard({render,@@ -29,6 +30,8 @@ export default function TrackRenderCard({// An uploaded take has no engine (the studio cleared the gen metadata on// attach) — label it so a generated vs. imported take reads at a glance.const isUpload = !engine;+ // Where imported audio came from (e.g. a Suno export) — '' for a plain upload.+ const sourceLabel = renderSourceLabel(render.source);return (<div className={`bg-port-card border rounded-xl p-2.5 space-y-2 ${active ? 'border-port-accent' : 'border-port-border'}`}>@@ -55,10 +58,11 @@ export default function TrackRenderCard({{prompt ? (<p className="text-[11px] text-gray-300 line-clamp-2" title={prompt}>{prompt}</p>) : (- <p className="text-[11px] text-gray-600 italic">{isUpload ? 'Uploaded audio' : 'No prompt'}</p>+ <p className="text-[11px] text-gray-600 italic">{sourceLabel ? `Imported from ${sourceLabel}` : isUpload ? 'Uploaded audio' : 'No prompt'}</p>)}<div className="flex flex-wrap gap-1 text-[9px]">+ {sourceLabel ? <span className="px-1.5 py-0.5 bg-port-border text-gray-300 rounded">{sourceLabel}</span> : null}{engine ? <span className="px-1.5 py-0.5 bg-port-accent/20 text-port-accent rounded">{engine}</span> : null}{modelId ? <span className="px-1.5 py-0.5 bg-port-border text-gray-400 rounded truncate max-w-[140px]" title={modelId}>{modelId}</span> : null}{durationSec ? <span className="px-1.5 py-0.5 bg-port-border text-gray-400 rounded">{formatTimecode(durationSec)}</span> : null}diff --git a/client/src/components/music/TrackRenderModal.jsx b/client/src/components/music/TrackRenderModal.jsxindex d2fd897400..b6ae667f42 100644--- a/client/src/components/music/TrackRenderModal.jsx+++ b/client/src/components/music/TrackRenderModal.jsx@@ -12,6 +12,7 @@ import { Sparkles, CheckCircle2, Download, Trash2, X, Film } from 'lucide-react'import Modal from '../ui/Modal';import { formatTimecode, timeAgo } from '../../utils/formatters';import { trackAudioUrl } from '../../services/api';+import { renderSourceLabel } from '../../lib/trackProvenance';function MetaRow({ label, children }) {return (@@ -26,6 +27,7 @@ export default function TrackRenderModal({ render, active = false, onClose, onSeif (!render) return null;const { prompt, lyrics, engine, modelId, durationSec, audioFilename, createdAt } = render;const isUpload = !engine;+ const sourceLabel = renderSourceLabel(render.source);return (<Modal@@ -56,6 +58,7 @@ export default function TrackRenderModal({ render, active = false, onClose, onSe</audio><div className="space-y-1.5">+ {sourceLabel ? <MetaRow label="Source">{`Imported from ${sourceLabel}`}</MetaRow> : null}{engine ? <MetaRow label="Engine">{engine}</MetaRow> : null}{modelId ? <MetaRow label="Model">{modelId}</MetaRow> : null}{durationSec ? <MetaRow label="Duration">{formatTimecode(durationSec)} ({durationSec}s)</MetaRow> : null}diff --git a/client/src/components/music/TracksManager.jsx b/client/src/components/music/TracksManager.jsxindex 8b0d582348..8dc261aecb 100644--- a/client/src/components/music/TracksManager.jsx+++ b/client/src/components/music/TracksManager.jsx@@ -15,7 +15,7 @@import { useEffect, useMemo, useRef, useState } from 'react';import { Link, useNavigate, useParams } from 'react-router';-import { Plus, Loader2, Trash2, Save, Upload, Music2, Library, Sparkles } from 'lucide-react';+import { Plus, Loader2, Trash2, Save, Upload, Music2, Library, Sparkles, FileMusic } from 'lucide-react';import BrailleSpinner from '../BrailleSpinner';import toast from '../ui/Toast';import FilePickerButton from '../ui/FilePickerButton';@@ -269,13 +269,15 @@ export default function TracksManager() {return true;};- const handleAudioFile = async (e) => {- const file = e.target.files?.[0];+ // `fields` are the multipart provenance fields (#8967): a Suno export sends+ // `source: 'suno'` plus the style prompt and lyrics it was made from.+ const uploadAudio = async (file, fields = {}) => {if (!file || !requireSaved()) return;if (file.size > AUDIO_MAX_BYTES) { toast.error(`Audio exceeds ${formatBytes(AUDIO_MAX_BYTES, 0)}`); return; }const targetId = persisted.id; // server write targets THIS tracksetUploading(true);const fd = new FormData();+ Object.entries(fields).forEach(([k, v]) => fd.append(k, v));fd.append('track', file, file.name);const res = await uploadTrackAudio(targetId, fd, { silent: true }).catch((err) => { toast.error(err.message || 'Upload failed'); return null; });setUploading(false);@@ -284,10 +286,23 @@ export default function TracksManager() {// Only touch the open form if THIS track is still selected (the user may// have switched tracks during the upload round-trip).if (selectedIdRef.current === targetId) setForm((f) => ({ ...f, audioFilename: res.track.audioFilename }));- toast.success('Audio uploaded');+ toast.success(fields.source === 'suno' ? 'Suno export imported' : 'Audio uploaded');}};+ const handleAudioFile = (e) => uploadAudio(e.target.files?.[0]);++ // Import a song exported from Suno (a manual import — no Suno API is called).+ // Save the open form first so the style prompt + lyrics typed above persist on+ // the track AND ride onto the imported take as its provenance.+ const handleSunoExport = async (e) => {+ const file = e.target.files?.[0];+ if (!file || !requireSaved()) return;+ const saved = await persistForm();+ if (!saved) return;+ await uploadAudio(file, { source: 'suno', prompt: saved.prompt || '', lyrics: saved.lyrics || '' });+ };+const openLibrary = async () => {if (!requireSaved()) return;const targetId = persisted.id;@@ -643,6 +658,16 @@ export default function TracksManager() {>{uploading ? <Loader2 size={14} className="animate-spin" /> : <Upload size={14} />} Upload</FilePickerButton>+ <FilePickerButton+ accept="audio/*,.mp3,.wav,.m4a,.ogg,.flac"+ onChange={handleSunoExport}+ disabled={uploading || saving}+ ariaLabel="Import Suno export audio"+ title="Import audio you exported from Suno. The prompt (style) and lyrics above are saved with the take."+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent"+ >+ <FileMusic size={14} /> Suno export+ </FilePickerButton><buttontype="button"onClick={openLibrary}diff --git a/client/src/components/music/TracksManager.test.jsx b/client/src/components/music/TracksManager.test.jsxindex e3c043b6db..8d1bbef1fd 100644--- a/client/src/components/music/TracksManager.test.jsx+++ b/client/src/components/music/TracksManager.test.jsx@@ -50,7 +50,7 @@ vi.mock('../../services/api', () => ({vi.mock('../../services/apiMusicVideo.js', () => ({ listMusicVideoProjects: vi.fn() }));import TracksManager from './TracksManager.jsx';-import { listTracks, listAlbums, createTrack, deleteTrack, updateTrack } from '../../services/api';+import { listTracks, listAlbums, createTrack, deleteTrack, updateTrack, uploadTrackAudio } from '../../services/api';import { listMusicVideoProjects } from '../../services/apiMusicVideo.js';const TRACK = { id: 'track-1', title: 'Example Song', audioFilename: 'example.mp3', renders: [] };@@ -426,3 +426,38 @@ describe('<TracksManager> album picker', () => {expect(within(select).getAllByRole('option', { name: 'Debut LP' })).toHaveLength(1);});});++// #8967: a Suno export is a manual import through the ordinary track upload —+// the open form is saved first so its style prompt + lyrics persist AND ride+// onto the imported take as provenance.+describe('<TracksManager> Suno export import', () => {+ beforeEach(() => {+ listTracks.mockResolvedValue([TRACK]);+ listAlbums.mockResolvedValue([]);+ listMusicVideoProjects.mockResolvedValue([]);+ });+ afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ });++ it('saves the form, then uploads the file tagged as a Suno export with its prompt and lyrics', async () => {+ updateTrack.mockResolvedValue({ ...TRACK, prompt: 'dreamy synth-pop', lyrics: 'la la la' });+ uploadTrackAudio.mockResolvedValue({ track: { ...TRACK, audioFilename: 'music-suno.mp3' } });+ renderAt('track-1');+ await waitFor(() => expect(screen.getByLabelText('Title').value).toBe('Example Song'));+ fireEvent.change(screen.getByLabelText(/^Prompt/), { target: { value: 'dreamy synth-pop' } });++ const file = new File(['ID3'], 'suno-song.mp3', { type: 'audio/mpeg' });+ fireEvent.change(screen.getByLabelText('Import Suno export audio'), { target: { files: [file] } });++ await waitFor(() => expect(uploadTrackAudio).toHaveBeenCalledTimes(1));+ expect(updateTrack).toHaveBeenCalledWith('track-1', expect.objectContaining({ prompt: 'dreamy synth-pop' }), { silent: true });+ const [targetId, fd] = uploadTrackAudio.mock.calls[0];+ expect(targetId).toBe('track-1');+ expect(fd.get('source')).toBe('suno');+ expect(fd.get('prompt')).toBe('dreamy synth-pop');+ expect(fd.get('lyrics')).toBe('la la la');+ expect(fd.get('track').name).toBe('suno-song.mp3');+ });+});diff --git a/client/src/components/musicVideo/TrackPanel.jsx b/client/src/components/musicVideo/TrackPanel.jsxindex 67404a1e63..f7314f2048 100644--- a/client/src/components/musicVideo/TrackPanel.jsx+++ b/client/src/components/musicVideo/TrackPanel.jsx@@ -3,6 +3,7 @@ import toast from '../ui/Toast';import MidiVisualization from '../songs/MidiVisualization.jsx';import { trackAudioUrl } from '../../services/apiTracks.js';import YoutubeImportControls from './YoutubeImportControls.jsx';+import { trackSourceLabel } from '../../lib/trackProvenance.js';/*** The project's audio: pick an existing library track or import fresh audio from@@ -21,11 +22,18 @@ export default function TrackPanel({? 'Wait for the MIDI transcription to finish before changing the track': null;const audioUrl = audioFilename ? trackAudioUrl(audioFilename) : null;+ // Where the linked track's audio came from (e.g. a Suno export, #8967).+ const sourceLabel = trackSourceLabel(tracks.find((t) => t.id === project.trackId));const midiFile = project.midiTranscription?.filename;return (<><div className="mt-2 flex flex-wrap items-center gap-2 text-xs"><span className="text-port-text-muted flex items-center gap-1"><Music size={12} /> {trackName(project.trackId)}</span>+ {sourceLabel && (+ <span className="px-1.5 py-0.5 rounded bg-port-border text-port-text-muted text-[10px]" title={`Audio imported from ${sourceLabel}`}>+ {sourceLabel}+ </span>+ )}<select value={project.trackId || ''} aria-label="Change track"onChange={(e) => e.target.value && onChangeTrack(e.target.value)}disabled={youtube.editJob.active || renderBound || midiBound}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 020c6e065e..6eb5a64515 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -202,6 +202,7 @@ grep -i "what you want to do" client/src/lib/README.md| `wireframeCore.js` | The Kestrel Neon "core assembly": icosahedron geometry (`ICOSAHEDRON_VERTICES` / `ICOSAHEDRON_EDGES`, 12 vertices, 30 edges), `rotatePoint` / `projectIcosahedron` (Y-then-X rotation + perspective), and `drawWireframeCore(ctx, frame)` — one 2D-canvas frame of the depth-shaded wireframe with its orbit rings, vertex dots, and corner angle readout. Every color is an `[r, g, b]` triple so the caller sources them from `AGENT_STATES` and resolved theme tokens; no DOM reads. Consumed by `cos/CoreCoSAvatar.jsx`. || `chiptunePlayback.js` | Looping WebAudio preview for LLM-generated chiptune scores (#2911) — `buildChiptuneSchedule(score)` (pure pattern/order → absolute-time flatten, MIRRORS `server/lib/chiptuneScore.js` timing semantics), `parseChiptunePitch("C5")` → MIDI, and `createChiptunePlayer(getScore, { onLoop })` — a seamless-loop player over `createLookaheadTransport` (pulse-duty via PeriodicWave, triangle bass, noise-buffer/sine-sweep drums), exposing `position()` (monotonic across loop passes) + `loopSec()` for playhead UIs. No React — `ChiptunePanel` drives it. || `waveSketchPlayback.js` | One-shot WebAudio preview for the Music Designer's LLM-made wave sketches (#8376; stereo painted canvases #8464) — `createWaveSketchPlayer({ onEnded })` → `{ play(pcm | channels), stop(), position() }` over the shared `audioContext.js` context. Plays PCM from `synthesizeSketchChannels` (`server/lib/waveSketch.js`, the same deterministic synth the server renders the saved take with); a `stop()` during the resume makes `play` resolve false instead of sounding late. No React — `WaveformPanel` drives it in both the Music Designer and the Tracks editor. |+| `trackProvenance.js` | `renderSourceLabel(source)` / `trackSourceLabel(track)` — the display label (`Suno`, `YouTube`) for where a music take's audio came from, read off a render's `source` (#8967) or a track's ACTIVE render. Plain uploads and unrecorded (pre-provenance) takes return `''` — never guessed. Shared by the Tracks render cards and the Music Video track row. || `waveSketchSynth.js` | Off-main-thread synthesis for the drawn-waveform preview (#8470) — `createSketchSynthesizer({ createWorker? })` → `{ synthesize(sketch, columns), dispose() }`, resolving `{ channels, peaks }` from a module Web Worker with the channel buffers transferred. Latest request wins: a new render terminates the in-flight worker and resolves the superseded promise to `null`; no Worker (or a worker load failure) falls back to a deferred main-thread render. `WaveformPanel` drives it. || `waveSketchSynthWorker.js` | The Web Worker entry behind `waveSketchSynth.js` — `renderSketchPreview(sketch, columns)` → `{ channels, peaks }` runs the server's `synthesizeSketchChannels` unchanged (sample-identical to the saved take) plus the mono-mix peaks. Its `onmessage` handler installs only inside a worker scope, so importing it elsewhere is side-effect free. || `colorMatch.js` | Pure grading core for the song system's color-match training mode: `buildColorMatchTimeline(score, { bpm })` → `{ notes, totalMs, msPerQuarter, bpm }` (each note's target frequency + onset/offset window in ms, keyed by the same global note index the renderer flattens, timing mirroring `scorePlayback`); `gradeNote(hz, targetHz)` classifies a sung pitch against a target into `in-tune`/`close`/`off`/`missed` (octave-folded, thresholds `MATCH_IN_TUNE_CENTS`/`MATCH_CLOSE_CENTS`); `noteAtTime(timeline, tMs, fromIdx)` finds the active note for a rAF cursor; `summarizeAccuracy(grades)` → `{ graded, counts, percentInTune, perNote }` per-take summary (`perNote` is the ordered grade list a saved take persists, mirroring the server sanitizer); `gradesFromPerNote(timeline, perNote)` is its inverse — rebuilds the noteIndex→grade map to repaint a saved take's grading on open without re-grading audio; plus `centsBetween` and the `GRADE` enum. No React, no audio — the `useColorMatch` hook drives it. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 3bbe3894f0..42751950d5 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -247,3 +247,4 @@ export * from './layoutRoutes.js';export * from './navPresentation.js';export * from './squarifyTreemap.js';export * from './styleSourceChoice.js';+export * from './trackProvenance.js';diff --git a/client/src/lib/trackProvenance.js b/client/src/lib/trackProvenance.jsnew file mode 100644index 0000000000..fa3893554f--- /dev/null+++ b/client/src/lib/trackProvenance.js@@ -0,0 +1,15 @@+// Display labels for a music take's provenance — the `source` a render records+// when its audio did not come from a local engine (server/services/tracks/+// logic.js, #8967). A plain upload gets no label: the Upload icon already says+// it, and '' (unrecorded, pre-provenance) must not be guessed at.+const SOURCE_LABELS = Object.freeze({ suno: 'Suno', youtube: 'YouTube' });++/** Label for a render `source`, or '' when there is nothing worth naming. */+export const renderSourceLabel = (source) => SOURCE_LABELS[source] || '';++/** The provenance label of a track's ACTIVE take (the one its audio pointer plays). */+export const trackSourceLabel = (track) => {+ if (!track?.audioFilename) return '';+ const active = (track.renders || []).find((r) => r.audioFilename === track.audioFilename);+ return renderSourceLabel(active?.source);+};diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex 2161d6c359..4541f7c475 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -535,6 +535,15 @@ describe('MusicVideo audio preview + download', () => {expect(dl.getAttribute('download')).toBe('neon song.mp3');});+ it('labels a linked track whose active take was imported from a Suno export (#8967)', async () => {+ listTracks.mockResolvedValue([{+ id: 't1', title: 'Neon Song', audioFilename: 'neon.mp3',+ renders: [{ id: 'r-old', audioFilename: 'old.wav', source: '' }, { id: 'r-1', audioFilename: 'neon.mp3', source: 'suno' }],+ }]);+ await openProject(PROJECT_WITH_CLIP);+ expect(await screen.findByTitle('Audio imported from Suno')).toHaveTextContent('Suno');+ });+it('falls back to the project uploaded-audio file when there is no linked track', async () => {await openProject({ ...PROJECT_WITH_CLIP, trackId: null, uploadedAudioFilename: 'upload.wav' });const player = await screen.findByLabelText('Preview track audio');diff --git a/server/lib/paintedCanvas.test.js b/server/lib/paintedCanvas.test.jsindex fa7504c9ae..be3a898cef 100644--- a/server/lib/paintedCanvas.test.js+++ b/server/lib/paintedCanvas.test.js@@ -155,8 +155,8 @@ describe('sync compatibility', () => {// What a v7 peer's v1-only normalizer would do to it: strip it to null and// LWW the loss back — the reason for the bump.expect(normalizeWaveSketch({ ...painting, version: 1 })).toBeNull();- expect(PORTOS_SCHEMA_VERSIONS.tracks).toBe(8);+ expect(PORTOS_SCHEMA_VERSIONS.tracks).toBeGreaterThanOrEqual(8);const { ahead } = compareSchemaVersions(PORTOS_SCHEMA_VERSIONS, { ...PORTOS_SCHEMA_VERSIONS, tracks: 7 });- expect(ahead).toEqual([{ category: 'tracks', senderV: 8, receiverV: 7 }]);+ expect(ahead).toEqual([{ category: 'tracks', senderV: PORTOS_SCHEMA_VERSIONS.tracks, receiverV: 7 }]);});});diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex e6f0d2a746..985ce3b3ff 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -297,7 +297,12 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// its v1-only normalizeWaveSketch, which strips a painting to null, and would// LWW that loss back — so it must reject the record instead. Stored v1// sketches still normalize and render unchanged; nothing to migrate.- tracks: 8,+ // tracks v9 = render-history entries record their provenance `source`+ // (`'suno'` for a hand-imported Suno export, `'youtube'`, `'upload'`, #8967).+ // A <=v8 peer's sanitizer would strip it and LWW the unlabelled take back, so+ // an exported song would silently lose its attribution. Pre-v9 renders read+ // as `source: ''` (unrecorded); nothing to migrate.+ tracks: 9,// v1 = creative ingredients catalog (Postgres tables: catalog_scraps,// catalog_ingredients, catalog_ingredient_sources, catalog_ingredient_refs).// v2 = `catalog_ingredients.search_tsv` expanded to also index thediff --git a/server/routes/tracks.js b/server/routes/tracks.jsindex 83b0096a2f..e80d8e842d 100644--- a/server/routes/tracks.js+++ b/server/routes/tracks.js@@ -12,7 +12,8 @@* GET /api/tracks/:id → Track* PATCH /api/tracks/:id → Track* DELETE /api/tracks/:id → { id } (soft delete)- * POST /api/tracks/:id/audio/upload → Track (multipart 'track' file)+ * POST /api/tracks/:id/audio/upload → Track (multipart 'track' file + optional+ * source/prompt/lyrics provenance fields)* POST /api/tracks/:id/audio/attach → Track (attach a library filename)* DELETE /api/tracks/:id/audio → Track (clear the audio pointer)* POST /api/tracks/:id/waveform/draw → { sketch, llm, track } (LLM-drawn sketch, stored on the track)@@ -28,14 +29,23 @@* The YouTube import (#1945) is a library-level action (not per-track) — it* lands a new Track in the library, same as an upload, so any project's track* picker can attach it afterward without re-downloading.+ *+ * Suno (#8967) arrives through the per-track upload: `source=suno` marks audio+ * the user exported from Suno, and the style prompt + lyrics ride along onto+ * that take. It is a manual import — no Suno API is called and no credential is+ * involved — so it works regardless of hosted API access and never claims to be+ * a hosted integration.*/import { Router } from 'express';import { readFile, unlink } from 'fs/promises';+import { join } from 'path';import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest, isPaginationRequested, paginateArray } from '../lib/validation.js';import { uploadSingle } from '../lib/multipart.js';+import { PATHS } from '../lib/fileUtils.js';+import { probeVideoDuration } from '../lib/ffmpeg.js';import * as tracks from '../services/tracks/index.js';import { createTrackWithAlbum, updateTrackWithAlbum, removeTrackFromAlbum } from '../services/trackAlbumMembership.js';import {@@ -109,6 +119,15 @@ const attachSchema = z.object({filename: z.string().trim().min(1).max(tracks.AUDIO_FILENAME_MAX),});+// Text fields riding a per-track audio upload. `source` is the take's+// provenance: a plain file, or a song exported from Suno. prompt/lyrics describe+// that take on its render card (for Suno: the style prompt and lyrics used there).+const audioUploadSchema = z.object({+ source: z.enum([tracks.RENDER_SOURCES.UPLOAD, tracks.RENDER_SOURCES.SUNO]).optional().default(tracks.RENDER_SOURCES.UPLOAD),+ prompt: promptField.optional().default(''),+ lyrics: lyricsField.optional().default(''),+});+const youtubeImportSchema = z.object({url: z.string().trim().regex(YOUTUBE_VIDEO_URL_RE, YOUTUBE_URL_INVALID_MESSAGE),});@@ -128,6 +147,15 @@ const musicUpload = uploadSingle('track', {},});+// Run a multipart route's pre-import checks. A rejection deletes the temp+// upload first, so a refused request can't strand the file in os.tmpdir().+function checkBeforeImport(req, check) {+ return Promise.resolve().then(check).catch(async (err) => {+ if (req.file?.path) await unlink(req.file.path).catch(() => {});+ throw err;+ });+}+// Load a track or 404 — shared by the audio mutation routes.async function requireTrack(id) {const track = await tracks.getTrack(id);@@ -137,8 +165,9 @@ async function requireTrack(id) {// Make `filename` the active audio AND record it in the render history so an// uploaded/attached take shows up as a card alongside generated ones. An-// uploaded render has no engine/model/duration, so the active gen-metadata is-// cleared (keeps the read-only badges honest). Re-attaching a file already in+// uploaded render has no engine/model, so the active gen-metadata is cleared+// (keeps the read-only badges honest); `take` carries what IS known about it —+// provenance, the prompt/lyrics it was made from, its probed duration. Re-attaching a file already in// the history just re-selects it (no duplicate card).//// Re-reads the track by id (the caller validated existence earlier) so the@@ -148,7 +177,7 @@ async function requireTrack(id) {// by writing back a stale renders array. (The sub-millisecond getTrack→// updateTrack window is a single-user request race we don't lock against per the// trust model.)-async function attachAudioAsRender(trackId, filename) {+async function attachAudioAsRender(trackId, filename, take = {}) {const track = await tracks.getTrack(trackId);if (!track) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });const existing = (track.renders || []).find((r) => r.audioFilename === filename);@@ -156,12 +185,12 @@ async function attachAudioAsRender(trackId, filename) {const patch = tracks.selectRenderPatch(track, existing.id) || { audioFilename: filename };return tracks.updateTrack(trackId, patch);}- const { renders } = tracks.buildRenderAppend(track, { audioFilename: filename });+ const { renders } = tracks.buildRenderAppend(track, { ...take, audioFilename: filename });return tracks.updateTrack(trackId, {audioFilename: filename,engine: '',modelId: '',- durationSec: null,+ durationSec: take.durationSec ?? null,renders,});}@@ -227,11 +256,16 @@ router.delete('/:id', asyncHandler(async (req, res) => {}));// Upload an audio file into the shared library and attach it to this track.+// `source=suno` records the take as a Suno export (see the header note).router.post('/:id/audio/upload', musicUpload, asyncHandler(async (req, res) => {- const track = await requireTrack(req.params.id);+ const { track, take } = await checkBeforeImport(req, async () => ({+ take: validateRequest(audioUploadSchema, req.body ?? {}),+ track: await requireTrack(req.params.id),+ }));if (!req.file) throw new ServerError('No audio file uploaded', { status: 400, code: 'TRACK_AUDIO_MISSING_FILE' });const { filename, sizeBytes } = await importUploadedTrack(req.file.path, req.file.originalname);- const updated = await attachAudioAsRender(track.id, filename);+ const durationSec = await probeVideoDuration(join(PATHS.music, filename)).catch(() => null);+ const updated = await attachAudioAsRender(track.id, filename, { ...take, durationSec });res.json({ track: updated, filename, sizeBytes });}));diff --git a/server/routes/tracks.test.js b/server/routes/tracks.test.jsindex 8f199fbb7d..c0d7fc82ee 100644--- a/server/routes/tracks.test.js+++ b/server/routes/tracks.test.js@@ -24,6 +24,7 @@ vi.mock('../services/promptRunner.js', async () => ({vi.mock('../lib/ffmpeg.js', () => ({findFfmpeg: vi.fn().mockResolvedValue(null),runFfmpegProcess: vi.fn(),+ probeVideoDuration: vi.fn().mockResolvedValue(null),}));vi.mock('../services/tracks/index.js', () => ({@@ -40,6 +41,7 @@ vi.mock('../services/tracks/index.js', () => ({DURATION_MIN_SEC: 1,DURATION_MAX_SEC: 3600,TRACK_ID_RE: /^track-/,+ RENDER_SOURCES: { UPLOAD: 'upload', SUNO: 'suno', YOUTUBE: 'youtube' },listTracks: vi.fn(async () => [{ id: 'track-1', title: 'Intro' }]),getTrack: vi.fn(),createTrack: vi.fn(async (input) => ({ id: 'track-new', ...input })),@@ -92,6 +94,7 @@ import { TRACK_IDS_MAX } from '../services/albums/logic.js';import * as ytImport from '../services/trackYoutubeImport.js';import { errorMiddleware } from '../lib/errorHandler.js';import * as promptRunner from '../services/promptRunner.js';+import { probeVideoDuration } from '../lib/ffmpeg.js';import tracksRoutes from './tracks.js';function makeApp() {@@ -370,6 +373,47 @@ describe('tracks routes', () => {expect(r.body.code).toBe('TRACK_RENDER_NOT_FOUND');});+ describe('POST /:id/audio/upload (library upload + Suno export import, #8967)', () => {+ const boundary = '----portosupload';+ const upload = (fields = {}) => request(app).post('/api/tracks/track-1/audio/upload')+ .set('content-type', `multipart/form-data; boundary=${boundary}`)+ .send(Buffer.concat([+ ...Object.entries(fields).map(([k, v]) => Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${k}"\r\n\r\n${v}\r\n`)),+ Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="track"; filename="song.mp3"\r\nContent-Type: audio/mpeg\r\n\r\nID3fake\r\n--${boundary}--\r\n`),+ ]));++ it('lands a Suno export as the active take with its provenance, style prompt, lyrics and duration', async () => {+ tracks.getTrack.mockResolvedValue({ id: 'track-1', renders: [] });+ probeVideoDuration.mockResolvedValueOnce(187.4);+ const r = await upload({ source: 'suno', prompt: 'dreamy synth-pop', lyrics: 'la la la' });+ expect(r.status).toBe(200);+ expect(musicLibrary.importUploadedTrack).toHaveBeenCalledWith(expect.any(String), 'song.mp3');+ expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', expect.objectContaining({+ audioFilename: 'music-up.mp3', engine: '', modelId: '', durationSec: 187.4,+ renders: [expect.objectContaining({+ audioFilename: 'music-up.mp3', source: 'suno', prompt: 'dreamy synth-pop', lyrics: 'la la la', durationSec: 187.4,+ })],+ }));+ });++ it('records a plain upload as source "upload" when no provenance is sent', async () => {+ tracks.getTrack.mockResolvedValue({ id: 'track-1', renders: [] });+ const r = await upload();+ expect(r.status).toBe(200);+ const patch = tracks.updateTrack.mock.calls[0][1];+ expect(patch.renders[0]).toMatchObject({ source: 'upload', prompt: '', lyrics: '' });+ expect(patch.durationSec).toBeNull(); // ffprobe unavailable → unknown, not 0+ });++ it('refuses an unsupported source before importing anything', async () => {+ tracks.getTrack.mockResolvedValue({ id: 'track-1', renders: [] });+ const r = await upload({ source: 'suno-api' });+ expect(r.status).toBe(400);+ expect(musicLibrary.importUploadedTrack).not.toHaveBeenCalled();+ expect(tracks.updateTrack).not.toHaveBeenCalled();+ });+ });+describe('POST /:id/code/render (code-engine take, #8375)', () => {afterAll(async () => { await rm(musicDir, { recursive: true, force: true }); });diff --git a/server/services/trackYoutubeImport.js b/server/services/trackYoutubeImport.jsindex 6282e42b2c..e3fce3ee7f 100644--- a/server/services/trackYoutubeImport.js+++ b/server/services/trackYoutubeImport.js@@ -21,6 +21,7 @@ import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '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 { RENDER_SOURCES } from './tracks/logic.js';import { resolveYtDlpBinaries, downloadAudioToTempMp3, cleanupYtDlpTemp } from './ytdlpAudioImport.js';// YouTube-only by design (issue #1945 scope: "start narrow" — other video hosts@@ -118,7 +119,11 @@ export async function startYoutubeImport(url) {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 });+ // The take records its provenance (#8967) so the library can say where it came from.+ const track = await createTrack({+ title: title || 'YouTube Import', audioFilename: filename, durationSec,+ renders: [{ audioFilename: filename, durationSec, source: RENDER_SOURCES.YOUTUBE }],+ });console.log(`📺 YouTube import ${shortId(jobId)} complete — track=${shortId(track.id)} "${track.title}"`);broadcastSse(job, { type: 'complete', trackId: track.id, track });diff --git a/server/services/tracks/index.js b/server/services/tracks/index.jsindex 4783c70ac3..ea580e062e 100644--- a/server/services/tracks/index.js+++ b/server/services/tracks/index.js@@ -30,6 +30,7 @@ export {DURATION_MAX_SEC,RENDER_ID_MAX,RENDERS_MAX,+ RENDER_SOURCES,TRACK_ID_RE,trackAudioFilename,makeRender,diff --git a/server/services/tracks/logic.js b/server/services/tracks/logic.jsindex 0f547a1b74..61f3b1395b 100644--- a/server/services/tracks/logic.js+++ b/server/services/tracks/logic.js@@ -26,7 +26,12 @@* the studio can show each render as a card and re-select an* earlier one. Each entry is `{ id, audioFilename, prompt,* authoredPrompt, lyrics, instrumentalOnly, engine,- * modelId, executionProfile, durationSec, createdAt }`. The+ * modelId, executionProfile, source, durationSec,+ * createdAt }`. `source` is the take's provenance when it+ * did not come from a local engine — `'upload'` (a plain+ * file), `'suno'` (audio exported from Suno and imported by+ * hand), `'youtube'` (the YouTube audio import) — or '' when+ * unrecorded (generated takes and pre-provenance renders). The* top-level `audioFilename`/`engine`/`modelId`/`durationSec`* point at whichever render is currently ACTIVE (selected).* - chiptuneScore / chiptunePrompt — the LLM-composed looping 8-bit score@@ -63,6 +68,12 @@ export const MODEL_ID_MAX = 120;export const EXECUTION_PROFILE_MAX = 80;export const AUDIO_FILENAME_MAX = 256;export const RENDER_ID_MAX = 80;+// Render provenance slug (see `source` above). A lowercase slug rather than a+// closed enum so a later import source is a value, not a sanitizer change; the+// routes that WRITE a source validate it against the sources they support.+export const RENDER_SOURCE_MAX = 40;+const RENDER_SOURCE_RE = /^[a-z0-9-]{1,40}$/;+export const RENDER_SOURCES = Object.freeze({ UPLOAD: 'upload', SUNO: 'suno', YOUTUBE: 'youtube' });// Cap the render history per track so a runaway generate loop can't grow the// record unboundedly. Oldest renders fall off first (slice(-RENDERS_MAX)); the// audio bytes stay in the shared library (they may be referenced elsewhere).@@ -114,6 +125,7 @@ export function sanitizeRender(raw) {engine: trimTo(raw.engine, ENGINE_MAX),modelId: trimTo(raw.modelId, MODEL_ID_MAX),executionProfile: trimTo(raw.executionProfile, EXECUTION_PROFILE_MAX),+ source: isStr(raw.source) && RENDER_SOURCE_RE.test(raw.source) ? raw.source : '',durationSec: sanitizeDuration(raw.durationSec),createdAt: isStr(raw.createdAt) && raw.createdAt ? raw.createdAt : new Date().toISOString(),};@@ -171,6 +183,7 @@ export function sanitizeTrack(raw) {engine,modelId,executionProfile: '',+ source: '',durationSec,createdAt,}];diff --git a/server/services/tracks/logic.test.js b/server/services/tracks/logic.test.jsindex 833eddae00..b26258d0d3 100644--- a/server/services/tracks/logic.test.js+++ b/server/services/tracks/logic.test.js@@ -122,6 +122,13 @@ describe('tracks logic', () => {const legacy = sanitizeRender({ audioFilename: 'a.wav' });expect(legacy.id).toMatch(/^r-/); // deterministic fallback idexpect(legacy.instrumentalOnly).toBeNull();+ expect(legacy.source).toBe(''); // provenance unrecorded, not guessed+ });++ it('sanitizeRender keeps a provenance slug and blanks a malformed one', () => {+ expect(sanitizeRender({ audioFilename: 'a.mp3', source: 'suno' }).source).toBe('suno');+ expect(sanitizeRender({ audioFilename: 'a.mp3', source: 'Suno API!' }).source).toBe('');+ expect(sanitizeRender({ audioFilename: 'a.mp3', source: 42 }).source).toBe('');});it('makeRender stamps the caller-supplied id + now', () => {