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

Import a Suno song link as a music video's track

Claude0fb47eb1c450
diff --git a/client/src/components/musicVideo/CreateProjectDrawer.jsx b/client/src/components/musicVideo/CreateProjectDrawer.jsx
index 6bb9d8041f..461b5832f5 100644
--- a/client/src/components/musicVideo/CreateProjectDrawer.jsx
+++ b/client/src/components/musicVideo/CreateProjectDrawer.jsx
@@ -16,7 +16,7 @@ const MODES = [
/**
* "New music video" drawer — track-first workflow:
- * 1. Select the music track (or import from YouTube) — audio source for the video.
+ * 1. Select the music track (or import a Suno song or YouTube audio) — audio source for the video.
* 2. Lyrics, concept, and style info are automatically read from the chosen track.
* 3. Name, mode, universe/moodboard, and brief settings.
*/
@@ -73,7 +73,7 @@ export default function CreateProjectDrawer({ open, onClose, form, onFormChange,
</select>
<div>
- <span className="block text-xs text-port-text-muted mb-1">…or import audio from YouTube</span>
+ <span className="block text-xs text-port-text-muted mb-1">…or import a Suno song or YouTube audio</span>
<div className="flex gap-1">
<YoutubeImportControls
id="mv-yt-create"
diff --git a/client/src/components/musicVideo/TrackPanel.jsx b/client/src/components/musicVideo/TrackPanel.jsx
index 43b6340190..ec34026b41 100644
--- a/client/src/components/musicVideo/TrackPanel.jsx
+++ b/client/src/components/musicVideo/TrackPanel.jsx
@@ -27,8 +27,8 @@ function timedDataLabels(project) {
}
/**
- * The project's audio: pick an existing library track or import fresh audio from
- * YouTube (re-selecting either PATCHes the project's trackId), then preview and
+ * The project's audio: pick an existing library track or import a Suno song or
+ * YouTube audio (re-selecting either PATCHes the project's trackId), then preview and
* download the resolved master file. Relinking is blocked while a render or a
* MIDI transcription is bound to this project — both already resolved the
* project's audio at kickoff. An optional vocal stem (#8977) conditions
diff --git a/client/src/components/musicVideo/YoutubeImportControls.jsx b/client/src/components/musicVideo/YoutubeImportControls.jsx
index 42127b168e..25486268ea 100644
--- a/client/src/components/musicVideo/YoutubeImportControls.jsx
+++ b/client/src/components/musicVideo/YoutubeImportControls.jsx
@@ -1,7 +1,7 @@
import { Activity, Download } from 'lucide-react';
// The URL input + Import/Cancel button pairing for a useMusicVideoYoutubeImport
-// slot — shared by the create form (full-size) and the detail view's
+// slot (a YouTube video or a Suno song link) — shared by the create form (full-size) and the detail view's
// track-change row (compact, inline in a flex-wrap toolbar). #1945
export default function YoutubeImportControls({ id, url, onUrlChange, job, onStart, compact = false, disabled = false }) {
const size = compact ? 12 : 13;
@@ -17,7 +17,7 @@ export default function YoutubeImportControls({ id, url, onUrlChange, job, onSta
// starting the import. Harmless on the detail view's usage, which
// isn't inside a <form>.
onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); if (url.trim()) onStart(); } }}
- placeholder="Import audio from a YouTube URL…" aria-label="Import audio from a YouTube URL"
+ placeholder="Paste a YouTube or Suno link…" aria-label="Import audio from a YouTube or Suno link"
className={`${compact ? 'flex-1 min-w-[160px]' : 'flex-1 min-w-0'} bg-port-bg border border-port-border rounded px-2 ${py} text-sm disabled:opacity-50 min-h-[44px] sm:min-h-0`}
/>
{job.active ? (
@@ -27,7 +27,7 @@ export default function YoutubeImportControls({ id, url, onUrlChange, job, onSta
</button>
) : (
<button type="button" onClick={onStart} disabled={!url.trim() || disabled}
- title="Download and extract this video's audio as a track"
+ title="Import this song's audio as a track"
className={`flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 ${py} ${btnExtra} disabled:opacity-50`}>
<Download size={size} /> Import
</button>
diff --git a/client/src/hooks/useMusicVideoYoutubeImport.js b/client/src/hooks/useMusicVideoYoutubeImport.js
index 0d010e545c..1315514f41 100644
--- a/client/src/hooks/useMusicVideoYoutubeImport.js
+++ b/client/src/hooks/useMusicVideoYoutubeImport.js
@@ -5,12 +5,12 @@ import useYoutubeTrackImport from './useYoutubeTrackImport.js';
// Every surface that blocks a project switch during an in-flight import says the
// same thing — the page reuses this for its own list-picker/delete guards.
-const SWITCH_BLOCKED_MESSAGE = 'Finish or cancel the in-progress YouTube import before switching projects';
+const SWITCH_BLOCKED_MESSAGE = 'Finish or cancel the in-progress audio import before switching projects';
/**
- * The music-video page's two YouTube audio-import slots (#1945): paste a URL,
- * PortOS downloads + extracts the track via yt-dlp and lands it in the shared
- * library. Two INDEPENDENT job slots — one per surface that can kick off an
+ * The music-video page's two audio-import slots (#1945): paste a YouTube or
+ * Suno song link, PortOS downloads the audio (yt-dlp for YouTube) and lands it
+ * in the shared library. Two INDEPENDENT job slots — one per surface that can kick off an
* import (the create form and the detail view's track-change row) — so starting
* one doesn't orphan the other's in-flight job (see useYoutubeTrackImport).
*
diff --git a/client/src/hooks/useYoutubeTrackImport.js b/client/src/hooks/useYoutubeTrackImport.js
index 8539e3a56f..e6d879279d 100644
--- a/client/src/hooks/useYoutubeTrackImport.js
+++ b/client/src/hooks/useYoutubeTrackImport.js
@@ -1,8 +1,10 @@
-import { importTrackFromYoutube, cancelTrackImport, trackImportEventsUrl } from '../services/apiTracks.js';
+import { importTrackFromYoutube, importTrackFromSuno, cancelTrackImport, trackImportEventsUrl } from '../services/apiTracks.js';
+import { isSunoSongUrl } from '../../../server/lib/sunoSong.js';
import useSseJobSlot from './useSseJobSlot.js';
/**
- * One YouTube-audio-import job slot (#1945) — start/cancel + SSE progress +
+ * One audio-import job slot (#1945) for a pasted YouTube or Suno song link —
+ * a Suno link imports the song with its title, lyrics and style — start/cancel + SSE progress +
* terminal-frame handling. A thin wrapper over the generic `useSseJobSlot`
* (#2368); call it once per UI surface that can independently kick off an import
* (e.g. the create form and an existing project's track picker) so two surfaces
@@ -17,16 +19,16 @@ import useSseJobSlot from './useSseJobSlot.js';
*/
export default function useYoutubeTrackImport({ onComplete } = {}) {
const { active, percent, start, cancel } = useSseJobSlot({
- startRequest: (url) => importTrackFromYoutube(url, { silent: true }),
+ startRequest: (url) => (isSunoSongUrl(url) ? importTrackFromSuno : importTrackFromYoutube)(url, { silent: true }),
eventsUrl: trackImportEventsUrl,
cancelRequest: cancelTrackImport,
trimStartArg: true,
onComplete: (frame, context) => onComplete?.(frame.track, context),
- successToast: (frame) => `Imported "${frame.track.title}" from YouTube`,
- errorFallback: 'YouTube import failed',
- canceledMessage: 'YouTube import cancelled',
- lostConnectionMessage: 'Lost connection to the YouTube import — check the music library',
- startErrorFallback: 'Failed to start YouTube import',
+ successToast: (frame) => `Imported "${frame.track.title}" from ${frame.source === 'suno' ? 'Suno' : 'YouTube'}`,
+ errorFallback: 'Audio import failed',
+ canceledMessage: 'Audio import cancelled',
+ lostConnectionMessage: 'Lost connection to the audio import — check the music library',
+ startErrorFallback: 'Failed to start the audio import',
});
return { active, percent, start, cancel };
}
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index e6f83ab185..389f5181df 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -470,12 +470,12 @@ export default function MusicVideo() {
const handleCreate = (e) => {
e.preventDefault();
if (!form.name.trim()) return;
- // A YouTube import in flight hasn't set form.trackId yet — creating now
+ // An audio import in flight hasn't set form.trackId yet — creating now
// would make a track-less project, and the import's later completion
// would only fill in the (already-reset) form's trackId instead of
// attaching to the project the user just created.
if (youtube.createJob.active) {
- toast.error('Finish or cancel the in-progress YouTube import before creating the project');
+ toast.error('Finish or cancel the in-progress audio import before creating the project');
return;
}
if (creating) return;
@@ -505,7 +505,7 @@ export default function MusicVideo() {
const handleDeleteRequest = (id) => {
if (youtube.editJob.active && id === selectedId) {
- toast.error('Finish or cancel the in-progress YouTube import before deleting this project');
+ toast.error('Finish or cancel the in-progress audio import before deleting this project');
return;
}
requestDelete(id);
@@ -516,7 +516,7 @@ export default function MusicVideo() {
// in-flight edit-surface import targets would still finish server-side
// and try to PATCH a now-deleted project.
if (youtube.editJob.active && id === selectedId) {
- toast.error('Finish or cancel the in-progress YouTube import before deleting this project');
+ toast.error('Finish or cancel the in-progress audio import before deleting this project');
return;
}
deleteMusicVideoProject(id, { silent: true })
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index 1a584957f9..d4b800dfa7 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -241,6 +241,7 @@ vi.mock('../services/apiTracks.js', () => ({
listTracks: vi.fn(async () => []),
trackAudioUrl: (filename) => `/data/music/${encodeURIComponent(filename)}`,
importTrackFromYoutube: vi.fn(async () => ({ jobId: 'yt-job-1' })),
+ importTrackFromSuno: vi.fn(async () => ({ jobId: 'suno-job-1' })),
trackImportEventsUrl: (jobId) => `/api/tracks/import/${jobId}/events`,
cancelTrackImport: vi.fn(async () => ({ ok: true })),
}));
@@ -272,7 +273,7 @@ import {
getMusicVideoPublishPlatforms, draftMusicVideoPublishCopy,
} from '../services/apiMusicVideo.js';
import { generateImage, uploadGalleryImage } from '../services/apiSystem.js';
-import { importTrackFromYoutube, trackImportEventsUrl, listTracks } from '../services/apiTracks.js';
+import { importTrackFromYoutube, importTrackFromSuno, trackImportEventsUrl, listTracks } from '../services/apiTracks.js';
import { generateVideo, getVideoGenStatus, getVideoHistoryItem } from '../services/apiImageVideo.js';
import { getUniverse } from '../services/apiUniverseBuilder.js';
import { downloadBlob } from '../lib/downloadBlob.js';
@@ -1828,7 +1829,7 @@ describe('MusicVideo concept & style editor (#3168)', () => {
describe('MusicVideo YouTube audio import (#1945)', () => {
it('starts an import from the detail view and attaches the finished track to the project', async () => {
await openProject(PROJECT_NO_CLIP, 'setup');
- const urlInput = screen.getByPlaceholderText(/Import audio from a YouTube URL/i);
+ const urlInput = screen.getByPlaceholderText(/Paste a YouTube or Suno link/i);
fireEvent.change(urlInput, { target: { value: 'https://youtu.be/dQw4w9WgXcQ' } });
const row = urlInput.closest('div');
fireEvent.click(within(row).getByRole('button', { name: /Import/i }));
@@ -1846,6 +1847,16 @@ describe('MusicVideo YouTube audio import (#1945)', () => {
await waitFor(() => expect(updateMusicVideoProject).toHaveBeenCalledWith('mv-2', { trackId: 'track-yt-1' }, { silent: true }));
});
+ it('imports a pasted Suno song link through the Suno import', async () => {
+ await openProject(PROJECT_NO_CLIP, 'setup');
+ const urlInput = screen.getByPlaceholderText(/Paste a YouTube or Suno link/i);
+ const songUrl = 'https://suno.com/song/11111111-2222-4333-8444-555555555555';
+ fireEvent.change(urlInput, { target: { value: songUrl } });
+ fireEvent.click(within(urlInput.closest('div')).getByRole('button', { name: /Import/i }));
+ await waitFor(() => expect(importTrackFromSuno).toHaveBeenCalledWith(songUrl, { silent: true }));
+ expect(importTrackFromYoutube).not.toHaveBeenCalled();
+ });
+
it('disables the Import button until a URL is entered', async () => {
await openProject(PROJECT_NO_CLIP, 'setup');
// Exact name: other stages also carry "Import take" / handoff import controls.
@@ -1861,7 +1872,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {
.mockResolvedValueOnce({ jobId: 'yt-job-create' })
.mockResolvedValueOnce({ jobId: 'yt-job-edit' });
- const inputs = screen.getAllByPlaceholderText(/Import audio from a YouTube URL/i);
+ const inputs = screen.getAllByPlaceholderText(/Paste a YouTube or Suno link/i);
const createInput = inputs.find((el) => el.id === 'mv-yt-create');
const editInput = inputs.find((el) => el.id !== 'mv-yt-create');
@@ -1902,7 +1913,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {
renderMV();
const picker = await selectProject(PROJECT_NO_CLIP.id);
- const editInput = screen.getAllByPlaceholderText(/Import audio from a YouTube URL/i)
+ const editInput = screen.getAllByPlaceholderText(/Paste a YouTube or Suno link/i)
.find((el) => el.id !== 'mv-yt-create');
fireEvent.change(editInput, { target: { value: 'https://youtu.be/xyz' } });
fireEvent.click(within(editInput.closest('div')).getByRole('button', { name: /Import/i }));
@@ -1922,7 +1933,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {
// Open mv-2 and start its detail-view import.
await selectProject(PROJECT_NO_CLIP.id);
await waitFor(() => expect(screen.getByTestId('loc').textContent).toBe('/music-video/mv-2'));
- const editInput = screen.getAllByPlaceholderText(/Import audio from a YouTube URL/i)
+ const editInput = screen.getAllByPlaceholderText(/Paste a YouTube or Suno link/i)
.find((el) => el.id !== 'mv-yt-create');
fireEvent.change(editInput, { target: { value: 'https://youtu.be/xyz' } });
fireEvent.click(within(editInput.closest('div')).getByRole('button', { name: /Import/i }));
@@ -1938,7 +1949,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {
it('blocks deleting the selected project while its import is in flight', async () => {
await openProject(PROJECT_NO_CLIP, 'setup');
- const editInput = screen.getAllByPlaceholderText(/Import audio from a YouTube URL/i)
+ const editInput = screen.getAllByPlaceholderText(/Paste a YouTube or Suno link/i)
.find((el) => el.id !== 'mv-yt-create');
fireEvent.change(editInput, { target: { value: 'https://youtu.be/xyz' } });
fireEvent.click(within(editInput.closest('div')).getByRole('button', { name: /Import/i }));
@@ -1972,7 +1983,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {
listMusicVideoProjects.mockResolvedValue([]);
renderMV();
await openCreateForm();
- const createInput = await screen.findByPlaceholderText(/Import audio from a YouTube URL/i);
+ const createInput = await screen.findByPlaceholderText(/Paste a YouTube or Suno link/i);
fireEvent.change(createInput, { target: { value: 'https://youtu.be/enterkey' } });
fireEvent.keyDown(createInput, { key: 'Enter' });
await waitFor(() => expect(importTrackFromYoutube).toHaveBeenCalledWith('https://youtu.be/enterkey', { silent: true }));
@@ -1985,7 +1996,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {
importTrackFromYoutube.mockImplementation(() => new Promise((resolve) => { resolveKickoff = resolve; }));
renderMV();
await openCreateForm();
- const createInput = await screen.findByPlaceholderText(/Import audio from a YouTube URL/i);
+ const createInput = await screen.findByPlaceholderText(/Paste a YouTube or Suno link/i);
fireEvent.change(createInput, { target: { value: 'https://youtu.be/doubleclick' } });
const importBtn = within(createInput.closest('div')).getByRole('button', { name: /Import/i });
fireEvent.click(importBtn);
@@ -2002,7 +2013,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {
renderMV();
const picker = await selectProject(PROJECT_NO_CLIP.id);
- const editInput = screen.getAllByPlaceholderText(/Import audio from a YouTube URL/i)
+ const editInput = screen.getAllByPlaceholderText(/Paste a YouTube or Suno link/i)
.find((el) => el.id !== 'mv-yt-create');
fireEvent.change(editInput, { target: { value: 'https://youtu.be/pending' } });
fireEvent.click(within(editInput.closest('div')).getByRole('button', { name: /Import/i }));
@@ -2027,7 +2038,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {
await openCreateForm();
const nameInput = await screen.findByPlaceholderText('Project name');
fireEvent.change(nameInput, { target: { value: 'New MV' } });
- const createInput = screen.getAllByPlaceholderText(/Import audio from a YouTube URL/i)
+ const createInput = screen.getAllByPlaceholderText(/Paste a YouTube or Suno link/i)
.find((el) => el.id === 'mv-yt-create');
fireEvent.change(createInput, { target: { value: 'https://youtu.be/xyz' } });
fireEvent.click(within(createInput.closest('div')).getByRole('button', { name: /Import/i }));
@@ -2228,7 +2239,7 @@ describe('MusicVideo YouTube audio import (#1945)', () => {
fireEvent.change(trackSelect, { target: { value: 'other-track' } });
expect(updateMusicVideoProject).not.toHaveBeenCalled();
- const editInput = screen.getAllByPlaceholderText(/Import audio from a YouTube URL/i)
+ const editInput = screen.getAllByPlaceholderText(/Paste a YouTube or Suno link/i)
.find((el) => el.id !== 'mv-yt-create');
expect(editInput).toHaveProperty('disabled', true);
});
diff --git a/client/src/services/apiTracks.js b/client/src/services/apiTracks.js
index cd795b67a9..8f6877a9c4 100644
--- a/client/src/services/apiTracks.js
+++ b/client/src/services/apiTracks.js
@@ -38,6 +38,12 @@ export const importTrackFromYoutube = (url, options = {}) => request('/tracks/im
body: JSON.stringify({ url }),
...options,
});
+// A Suno song link: the song's audio plus the title, lyrics and style its page carries.
+export const importTrackFromSuno = (url, options = {}) => request('/tracks/import/suno', {
+ method: 'POST',
+ body: JSON.stringify({ url }),
+ ...options,
+});
export const trackImportEventsUrl = (jobId) =>
`/api/tracks/import/${encodeURIComponent(jobId)}/events`;
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 2bdea717bd..904c6d6b9e 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -84,7 +84,7 @@ Admission inventory (`withBackupAssetPublication`):
| Music-library upload copy and deletion (`pipeline/musicLibrary.js`) | Covered (#9982): the copy and the unlink each hold one lease; the delete route intentionally leaves existing issue/project references to the removed file |
| Voice benchmark audio and row (`voice/profileBenchmarks.js`), cloned-candidate recording and row (`voice/profiles.js`), and the fine-tune job record that names each sealed checkpoint (`voice/fineTuning.js`) | Covered (#9982); promoting a checkpoint writes only a row naming bytes the job record already named |
| Pipeline audio stage rows: generated music, cue render and voice-over line render (`routes/pipeline/audio.js`) | Covered (#9982): the row that first names the WAV takes the lease; the sidecar or synthesizer writes the WAV before it |
-| Music-library upload attach: Music Designer upload, pipeline music upload and YouTube import (`routes/tracks.js`, `routes/pipeline/audio.js`, `trackYoutubeImport.js`) | Reference-only: the admitted library import copies the file first and the track or issue row commits after it |
+| Music-library upload attach: Music Designer upload, pipeline music upload, YouTube import and Suno import (`routes/tracks.js`, `routes/pipeline/audio.js`, `trackYoutubeImport.js`, `trackSunoImport.js`) | Reference-only: the admitted library import copies the file first and the track or issue row commits after it |
| LoRA training and deployed LoRAs: trained-adapter registration, checkpoint promotion over the deployed adapter, the promoted-checkpoint preview copy, the progress row naming trainer-written samples and checkpoints, run deletion, and LoRA deletion from the LoRA manager or Media Models (`loraTraining/index.js`, `loras.js`) | Covered (#9982): registration and promotion hold one lease from the adapter write through the run row and dataset flag; Civitai and Hugging Face installs admit the sidecar that first names the already-linked weights |
| Music Video final and excerpt renders, publishing-kit builds and composition document versions (`musicVideo/render.js`, `musicVideo/excerptRender.js`, `musicVideo/publishKit.js`, `musicVideo/compositionDocument.js`) | Covered (#9982): the encoder or import writes the files in place; the history entry and project row that first name them commit under one lease |
| Music Video excerpt deletion (`musicVideo/excerptService.js`) | Reference-only: the project row drops the excerpt before its unreferenced video and contact sheet are unlinked |
diff --git a/server/lib/README.md b/server/lib/README.md
index 8361ad37fe..50e439eaee 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -679,6 +679,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `dispatchLabels.js` | slashdo dispatch-hint contract: the `model:` capability and `effort:` reasoning-budget label vocabulary (the tiers themselves live in this module and are deliberately not re-enumerated here — a catalog copy of them is what drifted a tier behind), prescribed forge colors, validation (`normalizeDispatchModel` / `normalizeDispatchEffort`), the read-side inverse (`dispatchHintFromLabels` — recovers `{model, effort}` from a raw label-name list, used by branch-reconcile's per-branch routing hint), the per-forge label separator (`labelSeparator` / `forgeLabelName` — GitLab spells every prefixed label with its native scoped `::`, GitHub keeps `:`, and the read side accepts both; applied once at the `forgeIssueLabels` / `dispatchLabelSpec` boundary so the axis builders stay canonical; Jira keeps the hyphen form), optional contributor labels (`good first issue` / `help wanted`, never implied by `model:light`, and released at claim time by `formatContributorLabelReleaseCommands` — one best-effort command per label, since a forge fails the whole edit when a named label is absent), the one shared volunteer-claim policy (`volunteerClaimLabels` / `formatVolunteerClaimCommands` — a human comment claiming an unassigned issue is resolved by BOTH issueWatcher.js's deterministic pass and the claim prompt's Phase 1 handoff, so both stamp `in-progress` and retire the invitations rather than writing opposite state), the open-ended planner-attribution axis (`planner:<model>`, `normalizePlannerId` / `resolvePlannerId` / `formatPlannerLabelGuidance` — records WHICH model wrote the plan, prefix-matched by `dispatchLabelSpec` so it lazily creates like the fixed labels; a filing agent takes the value from its prompt, never from self-identification), the workflow-state markers (`EPIC_LABEL`/`EPIC_DECOMPOSED_LABEL` and `IN_PROGRESS_LABEL` — state, not hints: shared with perpetualWork.js#isActionableIssue, issueReconcile.js's zombie scan, issueWatcher.js's volunteer assignment, and the claim prompts), lazy-create command text, the optional `--label` slots a rendered `issue create` example offers (`OPTIONAL_ISSUE_LABEL_FLAG_SLOTS` / `formatOptionalIssueLabelFlags` — one list so a new axis reaches every prompt template's copy-pasteable command, not just its prose), and shared dispatch plus issue-quality guidance (`ISSUE_QUALITY_GUIDANCE`, `DISPATCH_HINT_GUIDANCE`, `MANDATORY_DISPATCH_HINT_GUIDANCE`, `JIRA_DISPATCH_HINT_GUIDANCE`, `MANDATORY_JIRA_DISPATCH_HINT_GUIDANCE`, `REFERENCE_WATCH_LABEL_CONTRACT`, plus the consumer-side pair `DISPATCH_HINT_READING_GUIDANCE` / `DISPATCH_HINT_FANOUT_GUIDANCE` — what the labels mean to an agent that RECEIVES them (the preloaded `open-issues` task data input) and, for an orchestrator only, how to route each sub-agent by its own issue (the swarm block); the fan-out form is the reading form plus one line, never a second copy of the vocabulary). All forge filing callers require both dispatch axes and verify labels after creation; help wanted requires specific hardware validation or valuable input from real users; never invent `medium`; reject future-only/speculative work while keeping useful current refactors claimable. Consumed by work-tracker instructions, quota-burn audits, Layered Intelligence filing, and claim follow-up prompts. |
| `distrokidForm.js` | The in-page steps of the DistroKid upload recipe (#10337): `fillDistrokidFields` (genre, language, store profiles, credits, preview start, the track's normal answers), `discloseDistrokidAi` (inline AI checkboxes, gate then parts) and `untickDistrokidExtras` (paid extras). Self-contained so `page.evaluate` can ship them, and tested against a fixture form in the client's DOM tests. |
| `sunoPage.js` | The in-page step of the Suno publish recipe: `markSunoSongMenu(songId)` tags the song page's OWN "More options" button with `data-portos-song-menu` (false when there is none), skipping the menus of other songs the page shows: the "Cover of" card of the song a cover was made from, the Similar / By-artist lists, the playbar. Runs inside the page via `page.evaluate`, so it reads only `document`; fixture tests live in `client/src/lib/sunoPage.test.js`. |
+| `sunoSong.js` | Suno song links and pages for the track import: `SUNO_SONG_URL_RE` / `isSunoSongUrl` (a `suno.com/song/<uuid>` page or `suno.com/s/<code>` share link), `sunoSongIdFromUrl`, `isSunoHost`, `sunoCdnAudioUrl`, and `parseSunoSongPage(html, songId)` → `{ title, lyrics, style, audioUrl, imageUrl }` read from the page's Next.js flight payload (long-text rows resolved) with og: tags as fallback. Pure leaf the client also imports. |
| `sunoSongPicker.js` | `pickSongRow(rows, { songId, durationSec, title })`: which Suno Hook picker row is the project song: by id when a row carries it, else the one row with the song's length, else the only row; -1 when rows cannot be told apart. |
| `distrokidGenres.js` | DistroKid's store genre list (`DISTROKID_GENRES`) and `suggestDistrokidGenres(project)`, a first primary/secondary genre guess from the song's own style words. Shared by the DistroKid publish payload and the publish panel's genre pickers. |
| `domainAutonomy.js` | Per-domain autonomy guardrails (pure). `AUTONOMY_DOMAINS`/`DOMAIN_IDS`/`DOMAIN_MODES` (`off`/`dry-run`/`execute`), `getDomainMode(config, id)`, and `normalizeDomainAutonomy(raw)` to coerce a hand-edited/partial map. Default per domain is `execute` (reproduces pre-#711 behavior, so no migration needed). Also `CREATIVE_DOMAIN`/`getCreativeAutonomyMode(config)` (#2183) — the Creative Director orchestrator domain, kept out of `DOMAIN_IDS` and defaulting to mirror the `cos` mode. |
diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.js
index c817ca254b..aa07bb4a35 100644
--- a/server/lib/backupAssetOwners.js
+++ b/server/lib/backupAssetOwners.js
@@ -135,7 +135,7 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
// follow the same import-then-row order.
id: 'music-library-attach-after-import',
status: 'reference-only',
- modules: ['services/trackYoutubeImport.js'],
+ modules: ['services/trackYoutubeImport.js', 'services/trackSunoImport.js'],
},
{
// Final and excerpt renders, publishing-kit builds and composition document
diff --git a/server/lib/index.js b/server/lib/index.js
index baf317b9eb..67157f865d 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -653,6 +653,7 @@ export * from './dispatchLabels.js';
export * from './distrokidForm.js';
export * from './distrokidGenres.js';
export * from './sunoPage.js';
+export * from './sunoSong.js';
export * from './sunoSongPicker.js';
export * from './domainAutonomy.js';
export * from './domainBudgets.js';
diff --git a/server/lib/sunoSong.js b/server/lib/sunoSong.js
new file mode 100644
index 0000000000..25f94bd155
--- /dev/null
+++ b/server/lib/sunoSong.js
@@ -0,0 +1,150 @@
+/**
+ * Suno song links and song pages — the pure half of the track import from a
+ * Suno URL. Accepts a song page (`suno.com/song/<uuid>`) or a share link
+ * (`suno.com/s/<code>`, which redirects to one), and reads the song's title,
+ * lyrics, style and audio/cover URLs out of the page HTML.
+ *
+ * A pure leaf: the client imports `isSunoSongUrl` to route a pasted URL to the
+ * right import endpoint, so this module imports no Node built-in.
+ */
+
+const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
+
+/** A Suno song page or share link on suno.com / suno.ai (www. and app. too). */
+export const SUNO_SONG_URL_RE = new RegExp(
+ `^https?:\\/\\/(?:www\\.|app\\.)?suno\\.(?:com|ai)\\/(?:song\\/${UUID}|s\\/[A-Za-z0-9_-]{4,64})\\/?(?:[?#]\\S*)?$`,
+ 'i',
+);
+
+export const SUNO_URL_INVALID_MESSAGE = 'Paste a Suno song link (suno.com/song/… or suno.com/s/…)';
+
+const SONG_ID_RE = new RegExp(`\\/song\\/(${UUID})`, 'i');
+
+export const isSunoSongUrl = (url) => typeof url === 'string' && SUNO_SONG_URL_RE.test(url.trim());
+
+/** The song id in a `/song/<uuid>` URL (lower-cased), or null — a share link carries none until resolved. */
+export function sunoSongIdFromUrl(url) {
+ return typeof url === 'string' ? SONG_ID_RE.exec(url)?.[1]?.toLowerCase() ?? null : null;
+}
+
+/** Suno's own hosts — the only places the import follows a share link or downloads from. */
+export function isSunoHost(hostname) {
+ const host = String(hostname || '').toLowerCase();
+ return ['suno.com', 'suno.ai'].some((domain) => host === domain || host.endsWith(`.${domain}`));
+}
+
+/** Suno's CDN copy of a song's audio, used when the page names none. */
+export const sunoCdnAudioUrl = (songId) => `https://cdn1.suno.ai/${encodeURIComponent(songId)}.mp3`;
+
+const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", '#39': "'", '#x27': "'" };
+const decodeEntities = (s) => s.replace(/&(amp|lt|gt|quot|apos|#39|#x27);/gi, (m, name) => ENTITIES[name.toLowerCase()] ?? m);
+
+function metaContent(html, property) {
+ for (const tag of html.match(/<meta\b[^>]*>/gi) || []) {
+ const name = /\b(?:property|name)\s*=\s*["']([^"']+)["']/i.exec(tag)?.[1];
+ if (name?.toLowerCase() !== property) continue;
+ const content = /\bcontent\s*=\s*"([^"]*)"|\bcontent\s*=\s*'([^']*)'/i.exec(tag);
+ const value = content?.[1] ?? content?.[2];
+ if (value) return decodeEntities(value).trim();
+ }
+ return '';
+}
+
+// The page is a Next.js app: the song record rides in `self.__next_f.push([1,"…"])`
+// script chunks, each a JSON string literal. Decoded and joined they make
+// React's flight stream, whose rows hold the song's JSON.
+function flightPayload(html) {
+ const parts = [];
+ for (const m of html.matchAll(/self\.__next_f\.push\(\[1,("(?:[^"\\]|\\.)*")\]\)/g)) {
+ try { parts.push(JSON.parse(m[1])); } catch { /* a chunk that isn't a plain string literal */ }
+ }
+ return parts.join('');
+}
+
+// The flight stream moves a long string (lyrics, often) into its own raw
+// `<id>:T<hex byte length>,<text>` row and leaves `"$<id>"` in its place. Cut
+// those rows out — their unescaped quotes and braces would derail the JSON
+// scan — and keep their text by id.
+function splitTextRows(payload) {
+ const texts = new Map();
+ const row = /(?:^|\n)([0-9a-f]+):T([0-9a-f]+),/gi;
+ let json = '';
+ let pos = 0;
+ for (let m = row.exec(payload); m; m = row.exec(payload)) {
+ const start = m.index + m[0].length;
+ const byteLength = parseInt(m[2], 16);
+ // A character is at least one byte, so the text fits in byteLength chars.
+ const bytes = new TextEncoder().encode(payload.slice(start, start + byteLength)).slice(0, byteLength);
+ const text = new TextDecoder().decode(bytes);
+ texts.set(m[1].toLowerCase(), text);
+ json += `${payload.slice(pos, m.index)}\n`;
+ pos = start + text.length;
+ row.lastIndex = pos;
+ }
+ return { json: json + payload.slice(pos), texts };
+}
+
+// Every object in the stream that has `"id":"<songId>"` as one of its own
+// keys, parsed. One forward pass tracks string state and an open-brace stack,
+// so the song's record parses whole however Suno orders its keys, and a parent
+// song nested in its `history` can't cut it short.
+function objectsWithId(json, songId) {
+ const needle = `"id":"${songId}"`;
+ const starts = [];
+ const wanted = new Set();
+ const found = [];
+ let inString = false;
+ for (let i = 0; i < json.length; i++) {
+ const c = json[i];
+ if (inString) {
+ if (c === '\\') i++;
+ else if (c === '"') inString = false;
+ } else if (c === '"') {
+ if (starts.length && json.slice(i, i + needle.length).toLowerCase() === needle) wanted.add(starts[starts.length - 1]);
+ inString = true;
+ } else if (c === '{') {
+ starts.push(i);
+ } else if (c === '}' && starts.length) {
+ const from = starts.pop();
+ if (!wanted.has(from)) continue;
+ try { found.push(JSON.parse(json.slice(from, i + 1))); } catch { /* not plain JSON */ }
+ }
+ }
+ return found;
+}
+
+const isSunoUrl = (value) => {
+ if (typeof value !== 'string' || !URL.canParse(value)) return false;
+ const url = new URL(value);
+ return url.protocol === 'https:' && isSunoHost(url.hostname);
+};
+
+/**
+ * Read what a Suno song page says about `songId`. Every field is best effort:
+ * '' (or null for a URL) when the page doesn't carry it, so a page Suno
+ * restyles still imports the audio. URLs are kept only when they point at Suno.
+ */
+export function parseSunoSongPage(html, songId) {
+ const page = typeof html === 'string' ? html : '';
+ const id = String(songId || '').toLowerCase();
+ const { json, texts } = splitTextRows(id ? flightPayload(page) : '');
+ // The song can be listed more than once (its record, the playbar); the full
+ // record is the one carrying `metadata`.
+ const records = json ? objectsWithId(json, id) : [];
+ const song = records.find((r) => r?.metadata && typeof r.metadata === 'object') || records[0] || {};
+ const text = (value) => {
+ if (typeof value !== 'string') return '';
+ const ref = /^\$([0-9a-f]+)$/i.exec(value)?.[1];
+ return (ref ? texts.get(ref.toLowerCase()) ?? '' : value).trim();
+ };
+ const title = text(song.title) || metaContent(page, 'og:title').replace(/\s*\|\s*Suno\s*$/i, '').trim();
+ const audioUrl = [song.audio_url, metaContent(page, 'og:audio')].find(isSunoUrl) || null;
+ const imageUrl = [song.image_large_url, song.image_url, metaContent(page, 'og:image')].find(isSunoUrl) || null;
+ return {
+ title,
+ lyrics: text(song.metadata?.prompt),
+ style: text(song.metadata?.tags),
+ audioUrl,
+ imageUrl,
+ };
+}
diff --git a/server/lib/sunoSong.test.js b/server/lib/sunoSong.test.js
new file mode 100644
index 0000000000..76eabad0d0
--- /dev/null
+++ b/server/lib/sunoSong.test.js
@@ -0,0 +1,72 @@
+import { describe, it, expect } from 'vitest';
+import { isSunoSongUrl, sunoSongIdFromUrl, parseSunoSongPage } from './sunoSong.js';
+
+const ID = '11111111-2222-4333-8444-555555555555';
+const PARENT = '99999999-8888-4777-8666-555555555555';
+const OTHER = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee';
+
+// Wrap flight-stream text the way a Next.js page ships it: one JSON string literal per push.
+const page = (chunks, head = '') => `<html><head>${head}</head><body>${chunks
+ .map((c) => `<script>self.__next_f.push([1,${JSON.stringify(c)}])</script>`).join('')}</body></html>`;
+const textRow = (ref, text) => `${ref}:T${new TextEncoder().encode(text).length.toString(16)},${text}`;
+
+describe('Suno song URLs', () => {
+ it.each([
+ [`https://suno.com/song/${ID}`, ID],
+ [`https://www.suno.com/song/${ID.toUpperCase()}?sh=abc`, ID],
+ [`https://app.suno.ai/song/${ID}/`, ID],
+ ['https://suno.com/s/AbCdEf123456', null],
+ ])('accepts %s', (url, id) => {
+ expect(isSunoSongUrl(url)).toBe(true);
+ expect(sunoSongIdFromUrl(url)).toBe(id);
+ });
+
+ it.each([
+ 'https://suno.com/create',
+ `https://suno.com/playlist/${ID}`,
+ `https://evilsuno.com/song/${ID}`,
+ `https://suno.com.example.com/song/${ID}`,
+ `https://suno.com/song/${ID} extra`,
+ ])('rejects %s', (url) => {
+ expect(isSunoSongUrl(url)).toBe(false);
+ });
+});
+
+describe('parseSunoSongPage', () => {
+ it('reads the song record, resolving long lyrics from a text row, whatever its key order', () => {
+ const lyrics = '[Verse]\nThe "room" is {you} — ünïcödé\n[Chorus]\nYou are the room';
+ const record = {
+ title: 'You Are the Room',
+ metadata: { tags: 'industrial, glitch', prompt: '$2a', history: [{ id: PARENT, title: 'Parent take' }] },
+ id: ID,
+ audio_url: `https://cdn1.suno.ai/${ID}.mp3`,
+ image_large_url: `https://cdn2.suno.ai/image_large_${ID}.jpeg`,
+ };
+ const related = { id: OTHER, title: 'Someone else', metadata: { prompt: 'not these lyrics', tags: 'pop' } };
+ const html = page([`1:${JSON.stringify(['$', 'div', null, { related }])}\n`, textRow('2a', lyrics), `3:${JSON.stringify({ clip: record })}\n`]);
+ expect(parseSunoSongPage(html, ID)).toEqual({
+ title: 'You Are the Room',
+ lyrics,
+ style: 'industrial, glitch',
+ audioUrl: `https://cdn1.suno.ai/${ID}.mp3`,
+ imageUrl: `https://cdn2.suno.ai/image_large_${ID}.jpeg`,
+ });
+ });
+
+ it('prefers the full record over a slimmer listing of the same song', () => {
+ const html = page([`4:${JSON.stringify({ playbar: { id: ID, title: 'Short' }, song: { id: ID, title: 'Full', metadata: { prompt: 'words', tags: 'rock' } } })}\n`]);
+ expect(parseSunoSongPage(html, ID)).toMatchObject({ title: 'Full', lyrics: 'words', style: 'rock' });
+ });
+
+ it('falls back to og: tags and refuses media URLs off Suno', () => {
+ const head = '<meta property="og:title" content="Rock &amp; Roll | Suno"><meta property="og:image" content="https://evil.example/x.jpg">'
+ + `<meta property="og:audio" content="https://cdn1.suno.ai/${ID}.mp3">`;
+ expect(parseSunoSongPage(page([], head), ID)).toEqual({
+ title: 'Rock & Roll', lyrics: '', style: '', audioUrl: `https://cdn1.suno.ai/${ID}.mp3`, imageUrl: null,
+ });
+ });
+
+ it('returns empty fields for a page that carries nothing (a challenge page)', () => {
+ expect(parseSunoSongPage('<html>Just a moment…</html>', ID)).toEqual({ title: '', lyrics: '', style: '', audioUrl: null, imageUrl: null });
+ });
+});
diff --git a/server/routes/tracks.js b/server/routes/tracks.js
index 28c222cc87..b51046f571 100644
--- a/server/routes/tracks.js
+++ b/server/routes/tracks.js
@@ -7,7 +7,8 @@
* POST /api/tracks → Track
* GET /api/tracks/library → { tracks } (shared music library list)
* POST /api/tracks/import/youtube → { jobId } (download + extract audio from a YouTube URL)
- * GET /api/tracks/import/:jobId/events → SSE progress for a YouTube import job
+ * POST /api/tracks/import/suno → { jobId } (a Suno song's audio, title, lyrics and style)
+ * GET /api/tracks/import/:jobId/events → SSE progress for a YouTube or Suno import job
* POST /api/tracks/import/:jobId/cancel → { ok }
* GET /api/tracks/:id → Track
* PATCH /api/tracks/:id → Track
@@ -58,6 +59,8 @@ import {
startYoutubeImport, attachImportSseClient, cancelYoutubeImport,
} from '../services/trackYoutubeImport.js';
import { YOUTUBE_VIDEO_URL_RE, YOUTUBE_URL_INVALID_MESSAGE } from '../lib/youtubeUrl.js';
+import { startSunoImport, attachSunoImportSseClient, cancelSunoImport } from '../services/trackSunoImport.js';
+import { SUNO_SONG_URL_RE, SUNO_URL_INVALID_MESSAGE } from '../lib/sunoSong.js';
import { generateChiptuneScore, renderChiptuneTrack, publishChiptuneTrack } from '../services/chiptune.js';
import { drawWaveSketchForTrack, renderWaveSketchToTrack } from '../services/musicWaveform.js';
import { PAINTED_CANVAS_LIMITS } from '../lib/paintedCanvas.js';
@@ -134,6 +137,10 @@ const youtubeImportSchema = z.object({
url: z.string().trim().regex(YOUTUBE_VIDEO_URL_RE, YOUTUBE_URL_INVALID_MESSAGE),
});
+const sunoImportSchema = z.object({
+ url: z.string().trim().regex(SUNO_SONG_URL_RE, SUNO_URL_INVALID_MESSAGE),
+});
+
// Reuse the pipeline audio stage's multipart upload contract (50MB, audio MIME).
const musicUpload = uploadSingle('track', {
limits: { fileSize: MUSIC_UPLOAD_MAX_BYTES },
@@ -189,14 +196,21 @@ router.post('/import/youtube', asyncHandler(async (req, res) => {
res.status(202).json(await startYoutubeImport(url));
}));
+// Suno song import: the song's audio plus the title, lyrics and style its page
+// carries, as a Track. Its jobs share the events/cancel routes below.
+router.post('/import/suno', asyncHandler(async (req, res) => {
+ const { url } = validateRequest(sunoImportSchema, req.body ?? {});
+ res.status(202).json(await startSunoImport(url));
+}));
+
router.get('/import/:jobId/events', (req, res) => {
- if (!attachImportSseClient(req.params.jobId, res)) {
+ if (!attachImportSseClient(req.params.jobId, res) && !attachSunoImportSseClient(req.params.jobId, res)) {
throw new ServerError('Import job not found or expired', { status: 404, code: 'NOT_FOUND' });
}
});
router.post('/import/:jobId/cancel', (req, res) => {
- res.json({ ok: cancelYoutubeImport(req.params.jobId) });
+ res.json({ ok: cancelYoutubeImport(req.params.jobId) || cancelSunoImport(req.params.jobId) });
});
router.post('/', asyncHandler(async (req, res) => {
diff --git a/server/routes/tracks.test.js b/server/routes/tracks.test.js
index f64a28f04d..ca477a0f44 100644
--- a/server/routes/tracks.test.js
+++ b/server/routes/tracks.test.js
@@ -99,6 +99,12 @@ vi.mock('../services/trackYoutubeImport.js', () => ({
attachImportSseClient: vi.fn(() => true),
cancelYoutubeImport: vi.fn(() => true),
}));
+vi.mock('../services/trackSunoImport.js', () => ({
+ startSunoImport: vi.fn(async () => ({ jobId: 'suno-job' })),
+ attachSunoImportSseClient: vi.fn(() => false),
+ cancelSunoImport: vi.fn(() => false),
+}));
+import * as sunoImport from '../services/trackSunoImport.js';
import * as musicLibrary from '../services/pipeline/musicLibrary.js';
import * as albums from '../services/albums/index.js';
@@ -204,6 +210,35 @@ describe('tracks routes', () => {
});
});
+ describe('Suno import', () => {
+ it.each([
+ 'https://suno.com/song/62cd2904-a9ad-41fc-8097-c85cebe08586',
+ 'https://suno.com/s/AbCdEf123456',
+ ])('POST /import/suno starts a job for %s', async (url) => {
+ const r = await request(app).post('/api/tracks/import/suno').send({ url });
+ expect(r.status).toBe(202);
+ expect(r.body).toEqual({ jobId: 'suno-job' });
+ expect(sunoImport.startSunoImport).toHaveBeenCalledWith(url);
+ });
+
+ it('POST /import/suno rejects a non-Suno URL (never reaches the service)', async () => {
+ const r = await request(app).post('/api/tracks/import/suno').send({ url: 'https://example.com/song/62cd2904-a9ad-41fc-8097-c85cebe08586' });
+ expect(r.status).toBe(400);
+ expect(sunoImport.startSunoImport).not.toHaveBeenCalled();
+ });
+
+ it('a Suno job streams and cancels through the shared import routes', async () => {
+ ytImport.attachImportSseClient.mockReturnValueOnce(false);
+ sunoImport.attachSunoImportSseClient.mockImplementationOnce((_id, res) => { res.status(200).end(); return true; });
+ expect((await request(app).get('/api/tracks/import/suno-job/events')).status).toBe(200);
+ ytImport.cancelYoutubeImport.mockReturnValueOnce(false);
+ sunoImport.cancelSunoImport.mockReturnValueOnce(true);
+ const r = await request(app).post('/api/tracks/import/suno-job/cancel');
+ expect(r.body).toEqual({ ok: true });
+ expect(sunoImport.cancelSunoImport).toHaveBeenCalledWith('suno-job');
+ });
+ });
+
it('POST / creates a track', async () => {
const r = await request(app).post('/api/tracks').send({ title: 'Intro', engine: 'acestep' });
expect(r.status).toBe(201);
diff --git a/server/services/trackSunoImport.js b/server/services/trackSunoImport.js
new file mode 100644
index 0000000000..d86c867103
--- /dev/null
+++ b/server/services/trackSunoImport.js
@@ -0,0 +1,130 @@
+/**
+ * Track import from a Suno song link — the Suno sibling of the YouTube import
+ * (trackYoutubeImport.js). Reads the song page for its title, lyrics and style,
+ * downloads the song's audio from Suno, lands it in the shared music library
+ * (data/music/), and creates a Track carrying that metadata.
+ *
+ * Same job contract as the YouTube import so the client drives both through one
+ * slot: kickoff returns a jobId at once, the work runs detached, and progress
+ * streams over SSE. Terminal frames: `{ type: 'complete', trackId, track, source }`,
+ * `{ type: 'error', error }`, or `{ type: 'canceled' }`.
+ */
+
+import { randomUUID } from 'crypto';
+import { mkdtemp, rm, writeFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { ServerError } from '../lib/errorHandler.js';
+import { shortId, PATHS } from '../lib/fileUtils.js';
+import { probeVideoDuration } from '../lib/ffmpeg.js';
+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../lib/sseUtils.js';
+import { fetchPublicBinary, fetchPublicText, resolvePublicUrl } from '../lib/safeUrlFetch.js';
+import {
+ isSunoSongUrl, isSunoHost, sunoSongIdFromUrl, sunoCdnAudioUrl, parseSunoSongPage, SUNO_URL_INVALID_MESSAGE,
+} from '../lib/sunoSong.js';
+import { importUploadedTrack, MUSIC_UPLOAD_MAX_BYTES } from './pipeline/musicLibrary.js';
+import { createTrack } from './tracks/index.js';
+import { RENDER_SOURCES } from './tracks/logic.js';
+
+const PAGE_TIMEOUT_MS = 20_000;
+const PAGE_MAX_BYTES = 5 * 1024 * 1024;
+const AUDIO_TIMEOUT_MS = 5 * 60 * 1000;
+// Suno serves its pages to browsers; a bare fetch user agent can get a challenge page instead.
+const HEADERS = { 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0 Safari/537.36' };
+
+// jobId -> { clients, lastPayload, status, canceled }
+const importJobs = new Map();
+
+export const attachSunoImportSseClient = (jobId, res) => attachSse(importJobs, jobId, res);
+
+export const __testing = { importJobs };
+
+/** Cancel an in-flight import; false when the job is unknown or already over. */
+export function cancelSunoImport(jobId) {
+ const job = importJobs.get(jobId);
+ if (!job || job.canceled || job.status !== 'running') return false;
+ job.canceled = true;
+ return true;
+}
+
+// A share link (suno.com/s/…) redirects to the song page; follow it on Suno's own hosts only.
+async function resolveSongId(url) {
+ const direct = sunoSongIdFromUrl(url);
+ if (direct) return direct;
+ const finalUrl = await resolvePublicUrl(url, {
+ timeoutMs: PAGE_TIMEOUT_MS, headers: HEADERS, allowUrl: (u) => u.protocol === 'https:' && isSunoHost(u.hostname),
+ });
+ const songId = sunoSongIdFromUrl(finalUrl);
+ if (!songId) throw new Error('That Suno link did not lead to a song page');
+ return songId;
+}
+
+/**
+ * Kick off a Suno song import. Throws 400 for a URL that isn't a Suno song
+ * link; everything after that runs detached and reports over SSE.
+ */
+export async function startSunoImport(url) {
+ if (!isSunoSongUrl(url)) throw new ServerError(SUNO_URL_INVALID_MESSAGE, { status: 400, code: 'SUNO_URL_INVALID' });
+
+ const jobId = randomUUID();
+ const job = { id: jobId, status: 'running', clients: [], canceled: false };
+ importJobs.set(jobId, job);
+ console.log(`🎶 Suno import ${shortId(jobId)} — ${url}`);
+
+ (async () => {
+ let dir = null;
+ const abortIfCanceled = () => {
+ if (!job.canceled) return false;
+ console.log(`🛑 Suno import ${shortId(jobId)} cancelled`);
+ broadcastSse(job, { type: 'canceled' });
+ return true;
+ };
+ try {
+ broadcastSse(job, { type: 'progress', percent: 5, stage: 'reading' });
+ const songId = await resolveSongId(url.trim());
+ // The page only adds metadata; a page Suno won't serve still imports the audio.
+ const html = await fetchPublicText(`https://suno.com/song/${songId}`, {
+ timeoutMs: PAGE_TIMEOUT_MS, headers: HEADERS, maxBytes: PAGE_MAX_BYTES, throwOnUnsafe: false,
+ }).catch(() => null);
+ const song = parseSunoSongPage(html || '', songId);
+ if (abortIfCanceled()) return;
+
+ broadcastSse(job, { type: 'progress', percent: 20, stage: 'downloading' });
+ const audio = await fetchPublicBinary(song.audioUrl || sunoCdnAudioUrl(songId), {
+ timeoutMs: AUDIO_TIMEOUT_MS, headers: HEADERS, maxBytes: MUSIC_UPLOAD_MAX_BYTES, throwOnUnsafe: false,
+ });
+ if (abortIfCanceled()) return;
+ if (!audio?.buffer?.byteLength) {
+ throw new Error('Could not download the song audio from Suno (is the song public or unlisted?)');
+ }
+
+ broadcastSse(job, { type: 'progress', percent: 90, stage: 'importing' });
+ const title = song.title || 'Suno song';
+ const ext = /mp4|m4a|aac/i.test(audio.contentType) ? 'm4a' : 'mp3';
+ dir = await mkdtemp(join(tmpdir(), 'portos-sunoimport-'));
+ const tempPath = join(dir, `song.${ext}`);
+ await writeFile(tempPath, audio.buffer);
+ const { filename } = await importUploadedTrack(tempPath, `${title}.${ext}`);
+ const durationSec = await probeVideoDuration(join(PATHS.music, filename)).catch(() => null);
+ const track = await createTrack({
+ title, lyrics: song.lyrics, prompt: song.style, audioFilename: filename, durationSec,
+ renders: [{
+ audioFilename: filename, durationSec, source: RENDER_SOURCES.SUNO,
+ prompt: song.style, authoredPrompt: song.style, lyrics: song.lyrics,
+ }],
+ });
+
+ console.log(`🎶 Suno import ${shortId(jobId)} complete — track=${shortId(track.id)} "${track.title}"`);
+ broadcastSse(job, { type: 'complete', trackId: track.id, track, source: 'suno' });
+ } catch (err) {
+ console.error(`❌ Suno import ${shortId(jobId)} failed: ${err?.message || err}`);
+ broadcastSse(job, { type: 'error', error: err?.message || String(err) });
+ } finally {
+ if (dir) await rm(dir, { recursive: true, force: true }).catch(() => {});
+ job.status = 'done';
+ closeJobAfterDelay(importJobs, jobId);
+ }
+ })();
+
+ return { jobId };
+}
diff --git a/server/services/trackSunoImport.test.js b/server/services/trackSunoImport.test.js
new file mode 100644
index 0000000000..21b20628cb
--- /dev/null
+++ b/server/services/trackSunoImport.test.js
@@ -0,0 +1,92 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('../lib/ffmpeg.js', () => ({ probeVideoDuration: vi.fn(async () => 200) }));
+vi.mock('./pipeline/musicLibrary.js', () => ({
+ importUploadedTrack: vi.fn(async () => ({ filename: 'music-suno.mp3', sizeBytes: 10 })),
+ MUSIC_UPLOAD_MAX_BYTES: 50 * 1024 * 1024,
+}));
+vi.mock('./tracks/index.js', () => ({ createTrack: vi.fn(async (input) => ({ id: 'track-new', ...input })) }));
+vi.mock('../lib/sseUtils.js', () => ({ broadcastSse: vi.fn(), attachSseClient: vi.fn(() => true), closeJobAfterDelay: vi.fn() }));
+vi.mock('../lib/safeUrlFetch.js', () => ({ fetchPublicText: vi.fn(), fetchPublicBinary: vi.fn(), resolvePublicUrl: vi.fn() }));
+
+const { broadcastSse } = await import('../lib/sseUtils.js');
+const { fetchPublicText, fetchPublicBinary, resolvePublicUrl } = await import('../lib/safeUrlFetch.js');
+const { importUploadedTrack } = await import('./pipeline/musicLibrary.js');
+const { createTrack } = await import('./tracks/index.js');
+const { startSunoImport, cancelSunoImport } = await import('./trackSunoImport.js');
+
+const ID = '11111111-2222-4333-8444-555555555555';
+const songPage = (record) => `<script>self.__next_f.push([1,${JSON.stringify(`5:${JSON.stringify(record)}\n`)}])</script>`;
+
+// The terminal frame the detached job broadcast, once it lands.
+const terminal = () => vi.waitFor(() => {
+ const frame = broadcastSse.mock.calls.map(([, f]) => f).find((f) => ['complete', 'error', 'canceled'].includes(f.type));
+ expect(frame).toBeTruthy();
+ return frame;
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ fetchPublicBinary.mockResolvedValue({ buffer: Buffer.from('ID3audio'), contentType: 'audio/mpeg' });
+});
+
+describe('startSunoImport', () => {
+ it('imports the audio as a Suno take with the title, lyrics and style from the song page', async () => {
+ fetchPublicText.mockResolvedValue(songPage({
+ id: ID, title: 'Airplane Mode', audio_url: `https://cdn1.suno.ai/${ID}.mp3`,
+ metadata: { prompt: '[Verse]\nno signal', tags: 'dream pop' },
+ }));
+ await startSunoImport(`https://suno.com/song/${ID}`);
+ expect(await terminal()).toMatchObject({ type: 'complete', trackId: 'track-new', source: 'suno' });
+ expect(fetchPublicBinary).toHaveBeenCalledWith(`https://cdn1.suno.ai/${ID}.mp3`, expect.any(Object));
+ expect(importUploadedTrack).toHaveBeenCalledWith(expect.stringMatching(/song\.mp3$/), 'Airplane Mode.mp3');
+ expect(createTrack).toHaveBeenCalledWith(expect.objectContaining({
+ title: 'Airplane Mode', lyrics: '[Verse]\nno signal', prompt: 'dream pop', durationSec: 200,
+ renders: [expect.objectContaining({ source: 'suno', lyrics: '[Verse]\nno signal', prompt: 'dream pop' })],
+ }));
+ });
+
+ it('still imports the audio from Suno\'s CDN when the page cannot be read', async () => {
+ fetchPublicText.mockResolvedValue(null);
+ await startSunoImport(`https://suno.com/song/${ID}`);
+ expect(await terminal()).toMatchObject({ type: 'complete' });
+ expect(fetchPublicBinary).toHaveBeenCalledWith(`https://cdn1.suno.ai/${ID}.mp3`, expect.any(Object));
+ expect(createTrack).toHaveBeenCalledWith(expect.objectContaining({ title: 'Suno song', lyrics: '' }));
+ });
+
+ it('follows a share link only on Suno\'s own hosts', async () => {
+ resolvePublicUrl.mockResolvedValue(`https://suno.com/song/${ID}`);
+ fetchPublicText.mockResolvedValue(null);
+ await startSunoImport('https://suno.com/s/AbCdEf123456');
+ expect(await terminal()).toMatchObject({ type: 'complete' });
+ const { allowUrl } = resolvePublicUrl.mock.calls[0][1];
+ expect(allowUrl(new URL('https://suno.com/song/x'))).toBe(true);
+ expect(allowUrl(new URL('https://example.com/song/x'))).toBe(false);
+ expect(fetchPublicText).toHaveBeenCalledWith(`https://suno.com/song/${ID}`, expect.any(Object));
+ });
+
+ it('reports an error when the audio cannot be downloaded, creating no track', async () => {
+ fetchPublicText.mockResolvedValue(null);
+ fetchPublicBinary.mockResolvedValue(null);
+ await startSunoImport(`https://suno.com/song/${ID}`);
+ expect(await terminal()).toMatchObject({ type: 'error', error: expect.stringMatching(/Could not download/) });
+ expect(createTrack).not.toHaveBeenCalled();
+ });
+
+ it('ends as cancelled, creating no track, when cancelled mid-download', async () => {
+ fetchPublicText.mockResolvedValue(null);
+ let release;
+ fetchPublicBinary.mockReturnValue(new Promise((resolve) => { release = resolve; }));
+ const { jobId } = await startSunoImport(`https://suno.com/song/${ID}`);
+ await vi.waitFor(() => expect(fetchPublicBinary).toHaveBeenCalled());
+ expect(cancelSunoImport(jobId)).toBe(true);
+ expect(cancelSunoImport(jobId)).toBe(false);
+ release({ buffer: Buffer.from('x'), contentType: 'audio/mpeg' });
+ expect(await terminal()).toEqual({ type: 'canceled' });
+ expect(importUploadedTrack).not.toHaveBeenCalled();
+ });
+
+ it('refuses a link that is not a Suno song', async () => {
+ await expect(startSunoImport('https://example.com/song/x')).rejects.toMatchObject({ status: 400, code: 'SUNO_URL_INVALID' });
+ });
+});
diff --git a/server/services/trackYoutubeImport.js b/server/services/trackYoutubeImport.js
index e3fce3ee7f..2d72d99e76 100644
--- a/server/services/trackYoutubeImport.js
+++ b/server/services/trackYoutubeImport.js
@@ -126,7 +126,7 @@ export async function startYoutubeImport(url) {
});
console.log(`📺 YouTube import ${shortId(jobId)} complete — track=${shortId(track.id)} "${track.title}"`);
- broadcastSse(job, { type: 'complete', trackId: track.id, track });
+ broadcastSse(job, { type: 'complete', trackId: track.id, track, source: 'youtube' });
} catch (err) {
console.error(`❌ YouTube import ${shortId(jobId)} failed: ${err?.message || err}`);
broadcastSse(job, { type: 'error', error: err?.message || String(err) });