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

fix([issue-9474]): import the Suno M4A the PortOS Browser saves to its download folder

[._.]/ Adam Eivy38c58ad0389a
diff --git a/server/services/musicVideo/autonomousSuno.js b/server/services/musicVideo/autonomousSuno.js
index bea9dd6b6a..a3b1a6d32e 100644
--- a/server/services/musicVideo/autonomousSuno.js
+++ b/server/services/musicVideo/autonomousSuno.js
@@ -3,7 +3,7 @@
* through its Download UI, validate the completed file, and import it directly.
* Retries reuse submitted song ids so a failed export never repeats Create.
*/
-import { mkdtemp, open, rm } from 'fs/promises';
+import { copyFile, mkdtemp, open, rm } from 'fs/promises';
import { join } from 'path';
import { tmpdir } from 'os';
import { promisify } from 'util';
@@ -195,9 +195,40 @@ async function validateSunoAudio(path, { signal, timeoutMs }) {
}
}
+const DOWNLOAD_POLL_MS = 1000;
+const downloadKey = (file) => `${file.name}\0${file.modified}`;
+
+async function defaultListDownloads() {
+ const { getDownloads } = await import('../browserService.js');
+ return getDownloads();
+}
+
+// The PortOS Browser keeps Chrome's native download manager (see
+// browser/server.js), so a CDP-attached Playwright never sees a `download`
+// event: the M4A just lands in the profile's download directory. Detect it
+// there instead — a new .m4a (Chrome lists a file only after its .crdownload
+// rename) whose size held steady across two polls.
+async function watchDownloadsDir(listDownloads, baseline, signal, pollMs) {
+ let lastSize = null;
+ let lastName = null;
+ while (!signal.aborted) {
+ const { downloadDir, files } = await listDownloads().catch(() => ({ files: [] }));
+ const fresh = files.find((f) => /\.m4a$/i.test(f.name) && !baseline.has(downloadKey(f)));
+ if (fresh && fresh.name === lastName && fresh.size === lastSize && fresh.size > 0) return join(downloadDir, fresh.name);
+ lastName = fresh?.name ?? null;
+ lastSize = fresh?.size ?? null;
+ await new Promise((resolve) => {
+ const timer = setTimeout(resolve, pollMs);
+ signal.addEventListener('abort', () => { clearTimeout(timer); resolve(); }, { once: true });
+ });
+ }
+ return null;
+}
+
/** One bounded export, including waiting for the browser to finish saving. */
async function downloadSunoAudio(page, songId, path, {
timeoutMs = SUNO_AUDIO_TIMEOUT_MS, signal, validateAudio = validateSunoAudio,
+ listDownloads = defaultListDownloads, downloadPollMs = DOWNLOAD_POLL_MS,
} = {}) {
const controller = new AbortController();
const deadline = Date.now() + timeoutMs;
@@ -230,6 +261,7 @@ async function downloadSunoAudio(page, songId, path, {
return Promise.race([Promise.resolve().then(fn), stopPromise]);
};
let onDownload;
+ const watch = new AbortController();
try {
await bounded('open-song', () => page.goto(sunoSongUrl(songId), { waitUntil: 'domcontentloaded', timeout: remaining() }));
if (/sign-?in|login|accounts\./i.test(page.url())) throw loginRequired(LABEL, SUNO_CREATE_URL);
@@ -253,10 +285,18 @@ async function downloadSunoAudio(page, songId, path, {
onDownload = (value) => { download = value; resolve(value); };
page.once('download', onDownload);
});
+ const baseline = new Set((await bounded('snapshot-downloads', () => listDownloads().catch(() => ({ files: [] })))).files.map(downloadKey));
await bounded('start-download', () => page.getByRole('button', { name: /^(Unlock & Download|Download)$/ }).click({ timeout: remaining() }));
- await bounded('wait-download', () => started);
- await bounded('save-download', () => download.saveAs(path));
- if (await bounded('check-download', () => download.failure())) throw error('SUNO_AUDIO_DOWNLOAD_FAILED', 'browser-download-failed');
+ const landed = await bounded('wait-download', () => Promise.race([
+ started.then(() => null),
+ watchDownloadsDir(listDownloads, baseline, watch.signal, downloadPollMs),
+ ]));
+ if (landed) {
+ await bounded('save-download', () => copyFile(landed, path));
+ } else {
+ await bounded('save-download', () => download.saveAs(path));
+ if (await bounded('check-download', () => download.failure())) throw error('SUNO_AUDIO_DOWNLOAD_FAILED', 'browser-download-failed');
+ }
if (!await bounded('validate-audio', () => validateAudio(path, { signal: controller.signal, timeoutMs: remaining() }))) throw error('SUNO_AUDIO_INVALID', 'invalid-audio');
} catch (err) {
if (err instanceof ServerError) throw err;
@@ -264,6 +304,7 @@ async function downloadSunoAudio(page, songId, path, {
throw error('SUNO_AUDIO_DOWNLOAD_FAILED', 'export-failed');
} finally {
clearTimeout(timer);
+ watch.abort();
signal?.removeEventListener('abort', abort);
if (onDownload) page.off('download', onDownload);
// The page owner closes it before removing the staging directory. Cancel
diff --git a/server/services/musicVideo/autonomousSuno.test.js b/server/services/musicVideo/autonomousSuno.test.js
index 4ff9b6786f..a0fe6f1b47 100644
--- a/server/services/musicVideo/autonomousSuno.test.js
+++ b/server/services/musicVideo/autonomousSuno.test.js
@@ -1,5 +1,7 @@
import { EventEmitter } from 'node:events';
-import { readFile, writeFile, stat } from 'node:fs/promises';
+import { mkdtemp, readFile, rm, writeFile, stat } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import { describe, it, expect, vi, afterEach } from 'vitest';
import { findFfmpeg } from '../../lib/ffmpeg.js';
@@ -130,12 +132,14 @@ describe('submitSunoSong', () => {
// Synthetic container signature; ffmpeg is mocked at its process boundary.
const m4a = Buffer.from([0, 0, 0, 24, 102, 116, 121, 112, 77, 52, 65, 32]);
-function workflow({ bytes = m4a, stalled, failure = null, ignoreSelection = false, readyAfterMs = 0 } = {}) {
+function workflow({ bytes = m4a, stalled, failure = null, ignoreSelection = false, readyAfterMs = 0, landsInDir = null } = {}) {
const page = fakePage();
const baseRole = page.getByRole;
const selected = new Set(['MP3', 'WAV', 'MP4 video asset']);
const actions = [];
let savedPath;
+ const dirFiles = [];
+ const listDownloads = vi.fn(async () => ({ downloadDir: landsInDir, files: [...dirFiles] }));
const download = {
saveAs: vi.fn(async (path) => {
savedPath = path;
@@ -155,7 +159,10 @@ function workflow({ bytes = m4a, stalled, failure = null, ignoreSelection = fals
if (role === 'button' && String(name) === '/^(Unlock & Download|Download)$/') return { click: async () => {
actions.push('export');
expect(page.listenerCount('download')).toBe(1);
- if (stalled !== 'event') page.emit('download', download);
+ if (landsInDir) {
+ await writeFile(join(landsInDir, 'Example Song.m4a'), bytes);
+ dirFiles.push({ name: 'Example Song.m4a', size: bytes.length, modified: '2026-01-01T00:00:00.000Z' });
+ } else if (stalled !== 'event') page.emit('download', download);
} };
if (role === 'menuitem') return { click: async ({ timeout }) => {
actions.push(name);
@@ -174,7 +181,7 @@ function workflow({ bytes = m4a, stalled, failure = null, ignoreSelection = fals
expect(await readFile(path)).toEqual(m4a);
return { filename: 'music-example.m4a', sizeBytes: m4a.length };
});
- return { page, selected, actions, download, savedPath: () => savedPath, browser, connect, importAudio };
+ return { page, selected, actions, download, savedPath: () => savedPath, browser, connect, importAudio, listDownloads, downloadPollMs: 5 };
}
describe('generateSunoSong M4A export', () => {
@@ -197,6 +204,20 @@ describe('generateSunoSong M4A export', () => {
await expect(stat(w.savedPath())).rejects.toMatchObject({ code: 'ENOENT' });
});
+ it('imports an M4A the PortOS Browser saved to its download directory when Playwright emits no download event', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'portos-suno-test-'));
+ try {
+ const w = workflow({ landsInDir: dir });
+ const out = await generateSunoSong(fields, { ...w, songIds: [NEW_A] });
+ expect(out).toMatchObject({ filename: 'music-example.m4a' });
+ expect(w.download.saveAs).not.toHaveBeenCalled();
+ expect(w.actions.filter(x => x === 'export')).toHaveLength(1);
+ expect(w.page.listenerCount('download')).toBe(0);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+ });
+
it('never presses Create or imports when stopped while the form is opening', async () => {
const w = workflow();
const controller = new AbortController();