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
Keep the Suno link import fast when the browser can't export (#10566)
[._.]/94f685afadc3
diff --git a/server/services/trackSunoImport.js b/server/services/trackSunoImport.jsindex 03a775b8a7..8034092dc6 100644--- a/server/services/trackSunoImport.js+++ b/server/services/trackSunoImport.js@@ -68,27 +68,75 @@ async function extractAudio(videoPath, outPath, signal) {throw new Error('Could not take the audio out of the video Suno offers for this song');}+// The browser export's budget here. The autopilot allows 10 minutes, but a+// signed-out browser shows no usable Download menu (no sign-in redirect), so+// only a timeout ends that wait; an import should fall back long before then.+const BROWSER_EXPORT_TIMEOUT_MS = 90_000;+// The whole browser leg, including its wait in the shared browser queue+// (behind an autopilot song or a publish draft), which the export's own+// budget doesn't count. Mutable for tests.+const limits = { browserWaitMs: 2 * 60 * 1000 };+// Export the song through the signed-in PortOS Browser, the same export the// autopilot uses, so a private or unpublished song in the user's own Suno// library imports too. Resolves the page HTML it saw (for title and lyrics).async function exportThroughBrowser(songId, outPath, signal) {const { generateSunoSong } = await import('./musicVideo/autonomousSuno.js');+ // Its own signal: a cancel or the wait budget running out stops it, and a+ // queued export sees the aborted signal when its turn comes and exits.+ const exportAbort = new AbortController();+ const stop = () => exportAbort.abort();+ if (signal.aborted) stop();+ signal.addEventListener('abort', stop, { once: true });+ let timer;let html = '';- await generateSunoSong({}, {- songIds: [songId], signal,+ const exported = generateSunoSong({}, {+ songIds: [songId], signal: exportAbort.signal, timeoutMs: BROWSER_EXPORT_TIMEOUT_MS,onSongPage: (pageHtml) => { html = pageHtml; },- // Keep the export out of the library until it passes this import's checks.- importAudio: async (path) => { await copyFile(path, outPath); return { filename: null, sizeBytes: 0 }; },+ // Keep the export out of the library until it passes this import's checks,+ // and never let an export that finishes after its leg gave up overwrite+ // what the next route wrote.+ importAudio: async (path) => {+ if (!exportAbort.signal.aborted) await copyFile(path, outPath);+ return { filename: null, sizeBytes: 0 };+ },});+ exported.catch(() => {});+ try {+ await Promise.race([exported, new Promise((_, reject) => {+ exportAbort.signal.addEventListener('abort', () => reject(new Error(signal.aborted+ ? 'cancelled'+ : `the PortOS Browser did not finish the export within ${Math.round(limits.browserWaitMs / 1000)}s`)), { once: true });+ if (exportAbort.signal.aborted) reject(new Error('cancelled'));+ timer = setTimeout(stop, limits.browserWaitMs);+ })]);+ } finally {+ clearTimeout(timer);+ signal.removeEventListener('abort', stop);+ }return html;}+// Take the audio from the song's public video, which stays downloadable+// without signing in even when Suno withholds the audio file.+async function audioFromPublicVideo(songId, dir, outPath, signal, onExtracting) {+ const video = await fetchPublicBinary(sunoCdnVideoUrl(songId), {+ timeoutMs: AUDIO_TIMEOUT_MS, headers: HEADERS, maxBytes: VIDEO_MAX_BYTES, throwOnUnsafe: false,+ });+ if (signal.aborted) return;+ if (!video?.buffer?.byteLength || !isVideoResponse(video.contentType)) throw new Error('its public video was refused too');+ onExtracting();+ const videoPath = join(dir, 'song.mp4');+ await writeFile(videoPath, video.buffer);+ await extractAudio(videoPath, outPath, signal);+}+// jobId -> { clients, lastPayload, status, canceled }const importJobs = new Map();export const attachSunoImportSseClient = (jobId, res) => attachSse(importJobs, jobId, res);-export const __testing = { importJobs };+export const __testing = { importJobs, limits };/** Cancel an in-flight import; false when the job is unknown or already over. */export function cancelSunoImport(jobId) {@@ -150,32 +198,35 @@ export async function startSunoImport(url) {tempPath = join(dir, `song.${/mp4|m4a|aac/i.test(audio.contentType) ? 'm4a' : 'mp3'}`);await writeFile(tempPath, audio.buffer);} else {- // Suno withholds the audio file from anonymous requests (always for a- // private or unpublished song). The signed-in browser can export it.- broadcastSse(job, { type: 'progress', percent: 30, stage: 'exporting' });+ // Suno withholds the audio file from anonymous requests. A public song+ // (its anonymous page names it) takes the fast public-video route first;+ // a private or unpublished one shows nothing anonymously, so the+ // signed-in browser export comes first.tempPath = join(dir, 'song.m4a');- const browserError = await exportThroughBrowser(songId, tempPath, job.abort.signal).then((pageHtml) => {- // Fill only what the anonymous page lacked: a private song shows nothing there.- const signedIn = parseSunoSongPage(pageHtml, songId);+ // Progress only moves forward, even when the browser leg follows a failed extraction.+ let percent = 20;+ const viaVideo = () => audioFromPublicVideo(songId, dir, tempPath, job.abort.signal, () => {+ percent = 70;+ broadcastSse(job, { type: 'progress', percent, stage: 'extracting' });+ });+ const viaBrowser = async () => {+ percent = Math.max(percent, 30);+ broadcastSse(job, { type: 'progress', percent, stage: 'exporting' });+ const signedIn = parseSunoSongPage(await exportThroughBrowser(songId, tempPath, job.abort.signal), songId);+ // Fill only what the anonymous page lacked.song = { ...song, title: song.title || signedIn.title, lyrics: song.lyrics || signedIn.lyrics, style: song.style || signedIn.style };- return null;- }, (err) => err);- if (abortIfCanceled()) return;- if (browserError) {- console.warn(`⚠️ Suno import ${shortId(jobId)}: browser export failed (${browserError.message}); trying the public video`);- // A public song's video stays downloadable without signing in, and carries the same audio.- const video = await fetchPublicBinary(sunoCdnVideoUrl(songId), {- timeoutMs: AUDIO_TIMEOUT_MS, headers: HEADERS, maxBytes: VIDEO_MAX_BYTES, throwOnUnsafe: false,- });- if (abortIfCanceled()) return;- if (!video?.buffer?.byteLength || !isVideoResponse(video.contentType)) {- throw new Error(`Suno would not hand over this song's audio. For a private or unpublished song, sign in to Suno in the PortOS Browser and try again (${browserError.message})`);- }- broadcastSse(job, { type: 'progress', percent: 70, stage: 'extracting' });- const videoPath = join(dir, 'song.mp4');- await writeFile(videoPath, video.buffer);- await extractAudio(videoPath, tempPath, job.abort.signal);+ };+ const routes = song.title ? [viaVideo, viaBrowser] : [viaBrowser, viaVideo];+ const failures = [];+ for (const route of routes) {+ const failure = await route().then(() => null, (err) => err);if (abortIfCanceled()) return;+ if (!failure) break;+ console.warn(`⚠️ Suno import ${shortId(jobId)}: ${failure.message}`);+ failures.push(failure.message);+ }+ if (failures.length === routes.length) {+ throw new Error(`Suno would not hand over this song's audio. For a private or unpublished song, sign in to Suno in the PortOS Browser and try again (${failures.join('; ')})`);}}diff --git a/server/services/trackSunoImport.test.js b/server/services/trackSunoImport.test.jsindex 5e885f2eb9..dc3b69b6d3 100644--- a/server/services/trackSunoImport.test.js+++ b/server/services/trackSunoImport.test.js@@ -20,11 +20,21 @@ const { fetchPublicText, fetchPublicBinary, resolvePublicUrl } = await import('.const { importUploadedTrack } = await import('./pipeline/musicLibrary.js');const { generateSunoSong } = await import('./musicVideo/autonomousSuno.js');const { createTrack } = await import('./tracks/index.js');-const { startSunoImport, cancelSunoImport } = await import('./trackSunoImport.js');+const { startSunoImport, cancelSunoImport, __testing } = 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>`;+// A browser export that lands a file through the import's importAudio.+const exportsFile = (page) => async (_fields, deps) => {+ if (page) deps.onSongPage(page);+ const { mkdtemp, writeFile, rm } = await import('fs/promises');+ const srcDir = await mkdtemp(`${(await import('os')).tmpdir()}/suno-test-`);+ await writeFile(`${srcDir}/song.m4a`, 'm4a');+ await deps.importAudio(`${srcDir}/song.m4a`, 'song.m4a').finally(() => rm(srcDir, { recursive: true, force: true }));+ return { songId: ID };+};+// 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));@@ -98,17 +108,10 @@ describe('startSunoImport', () => {it('exports a private song through the signed-in browser, taking its title and lyrics from that page', async () => {fetchPublicText.mockResolvedValue(null); // the anonymous page shows nothing for a private songfetchPublicBinary.mockResolvedValue(null);- generateSunoSong.mockImplementation(async (_fields, deps) => {- deps.onSongPage(songPage({ id: ID, title: 'Unreleased', metadata: { prompt: 'draft words', tags: 'lo-fi' } }));- const { mkdtemp, writeFile, rm } = await import('fs/promises');- const srcDir = await mkdtemp(`${(await import('os')).tmpdir()}/suno-test-`);- await writeFile(`${srcDir}/song.m4a`, 'm4a');- await deps.importAudio(`${srcDir}/song.m4a`, 'song.m4a').finally(() => rm(srcDir, { recursive: true, force: true }));- return { songId: ID };- });+ generateSunoSong.mockImplementation(exportsFile(songPage({ id: ID, title: 'Unreleased', metadata: { prompt: 'draft words', tags: 'lo-fi' } })));await startSunoImport(`https://suno.com/song/${ID}`);expect(await terminal()).toMatchObject({ type: 'complete' });- expect(generateSunoSong).toHaveBeenCalledWith({}, expect.objectContaining({ songIds: [ID], signal: expect.any(AbortSignal) }));+ expect(generateSunoSong).toHaveBeenCalledWith({}, expect.objectContaining({ songIds: [ID], signal: expect.any(AbortSignal), timeoutMs: 90_000 }));expect(fetchPublicBinary.mock.calls.map(([url]) => url)).not.toContain(`https://cdn1.suno.ai/${ID}.mp4`);expect(importUploadedTrack).toHaveBeenCalledWith(expect.stringMatching(/song\.m4a$/), 'Unreleased.m4a');expect(createTrack).toHaveBeenCalledWith(expect.objectContaining({ title: 'Unreleased', lyrics: 'draft words', prompt: 'lo-fi' }));@@ -131,6 +134,58 @@ describe('startSunoImport', () => {expect(runFfmpegProcess).toHaveBeenCalledWith({ bin: '/usr/local/bin/ffmpeg', signal: expect.any(AbortSignal), args: expect.arrayContaining(['-vn', '-c:a', 'copy']) });expect(importUploadedTrack).toHaveBeenCalledWith(expect.stringMatching(/song\.m4a$/), 'Airplane Mode.m4a');expect(createTrack).toHaveBeenCalledWith(expect.objectContaining({ title: 'Airplane Mode', lyrics: '[Verse]\nno signal' }));+ // A public song takes the fast public-video route, never the browser queue.+ expect(generateSunoSong).not.toHaveBeenCalled();+ });++ it('exports a public song through the browser when its public video is refused', async () => {+ fetchPublicText.mockResolvedValue(songPage({ id: ID, title: 'Airplane Mode', metadata: { prompt: 'words', tags: 'pop' } }));+ fetchPublicBinary.mockResolvedValue(null); // mp3 and mp4 both refused+ generateSunoSong.mockImplementation(exportsFile(null));+ await startSunoImport(`https://suno.com/song/${ID}`);+ expect(await terminal()).toMatchObject({ type: 'complete' });+ expect(generateSunoSong).toHaveBeenCalled();+ expect(createTrack).toHaveBeenCalledWith(expect.objectContaining({ title: 'Airplane Mode', lyrics: 'words' }));+ });++ it('keeps progress moving forward when the browser export follows a failed extraction', async () => {+ fetchPublicText.mockResolvedValue(songPage({ id: ID, title: 'Airplane Mode' }));+ fetchPublicBinary.mockImplementation(async (url) => (url.endsWith('.mp4') ? { buffer: Buffer.from('v'), contentType: 'video/mp4' } : null));+ runFfmpegProcess.mockResolvedValue({ ok: false, reason: 'no audio stream' });+ generateSunoSong.mockImplementation(exportsFile(null));+ await startSunoImport(`https://suno.com/song/${ID}`);+ expect(await terminal()).toMatchObject({ type: 'complete' });+ const percents = broadcastSse.mock.calls.map(([, f]) => f).filter((f) => f.type === 'progress').map((f) => f.percent);+ expect(percents).toEqual([...percents].sort((a, b) => a - b));+ });++ it('falls back to the public video when the browser export waits past its budget', async () => {+ const { browserWaitMs } = __testing.limits;+ __testing.limits.browserWaitMs = 20;+ try {+ fetchPublicText.mockResolvedValue(null); // private-looking page: the browser goes first+ fetchPublicBinary.mockImplementation(async (url) => (url.endsWith('.mp4') ? { buffer: Buffer.from('v'), contentType: 'video/mp4' } : null));+ let exportSignal;+ generateSunoSong.mockImplementation((_fields, deps) => { exportSignal = deps.signal; return new Promise(() => {}); });+ await startSunoImport(`https://suno.com/song/${ID}`);+ expect(await terminal()).toMatchObject({ type: 'complete' });+ expect(fetchPublicBinary.mock.calls.map(([url]) => url)).toContain(`https://cdn1.suno.ai/${ID}.mp4`);+ // The still-queued export is told to stand down.+ expect(exportSignal.aborted).toBe(true);+ } finally {+ __testing.limits.browserWaitMs = browserWaitMs;+ }+ });++ it('cancels at once while the browser export waits its turn in the shared browser queue', async () => {+ fetchPublicText.mockResolvedValue(null); // private song: the browser export goes first+ fetchPublicBinary.mockResolvedValue(null);+ generateSunoSong.mockImplementation(() => new Promise(() => {})); // queued behind another browser job+ const { jobId } = await startSunoImport(`https://suno.com/song/${ID}`);+ await vi.waitFor(() => expect(generateSunoSong).toHaveBeenCalled());+ expect(cancelSunoImport(jobId)).toBe(true);+ expect(await terminal()).toEqual({ type: 'canceled' });+ expect(fetchPublicBinary.mock.calls.map(([url]) => url)).not.toContain(`https://cdn1.suno.ai/${ID}.mp4`);});it('transcodes when the video\'s audio track will not copy, and fails when nothing will', async () => {