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]): export completed Suno M4A through the browser (#9560)

[._.]/bcdfeae8c180
diff --git a/docs/features/music-video-autonomous.md b/docs/features/music-video-autonomous.md
index 5dcfd20923..3c47c62117 100644
--- a/docs/features/music-video-autonomous.md
+++ b/docs/features/music-video-autonomous.md
@@ -13,7 +13,7 @@ brief → lyrics → style → song → analyze → produce
| `brief` | One LLM call turns the prompt into a title, a musical description, a compact Suno style line, a visual concept and a mood-board spec. The project is renamed to the title. | one provider call |
| `lyrics` | Original lyrics written against the musical description (skipped for an instrumental). | one provider call |
| `style` | A **Mood Board** (text notes + a composite look prompt and an avoid list) is created and linked as the project's mood board; the concept is set from the brief. No images are generated. | free |
-| `song` | The PortOS Browser submits a Suno song (custom mode: lyrics, style, title). CDN downloads are bounded and decoded before import, but the current adapter cannot verify generation completion and stops before importing (see [Suno completion evidence](#suno-completion-evidence)). | Suno credits |
+| `song` | The PortOS Browser drives the Suno web UI (custom mode: lyrics, style, title), only M4A is selected in Suno's Download UI and the completed audio is validated and imported directly into the music library, a Track is created, the take is recorded with `source: 'suno'`, and the project is linked to it. | Suno credits |
| `song` (local) | `songSource: 'local'` renders the song with the on-device Music Designer engines instead (see [Local song source](#local-song-source)). | free (GPU time) |
| `analyze` | The usual offline beat / tempo / section analysis. | free |
| `produce` | **Footage** (any image/video tool picked): the existing server-owned production run (`/production-runs`) with a pool built from the picks, then the final render once it completes. **Code** (only `code:render`): a code-rendered video is authored and rendered directly. | per tool |
@@ -44,37 +44,31 @@ Approving can carry edits (`POST /api/music-video/:id/autonomous/resume` with `{
## Suno completion evidence
-The CDN exposes playable partial files. Two equal byte counts, an audio MIME
-header, a duration, or successful decoding cannot prove that generation ended.
-As required by [#9525](https://github.com/atomantic/PortOS/issues/9525), the adapter
-preserves that uncertainty explicitly until a reliable completion signal is
-available. **Automatic Suno import is currently unavailable**: a stable,
-decodable candidate returns `SUNO_AUDIO_COMPLETION_UNVERIFIED` instead of
-silently importing potentially partial audio. Choosing the local song source
-remains the complete unattended path.
-
-The downloader aborts stalled headers and body reads within the overall budget
-(`SUNO_AUDIO_TIMEOUT`). It rejects known non-audio content and uses ffmpeg to
-decode candidate audio in a temporary directory, removed on success or failure.
-Diagnostics carry fixed reasons and bounded HTTP status, never response bodies
-or song URLs.
-
-A future integration must verify the exact song's completion before returning
-`complete` from the internal completion adapter; `pending` keeps polling, and
-missing/unrecognized evidence remains unknown. The injected completed fixture
-tests this admission contract; it is not evidence of live Suno support.
-[#9474](https://github.com/atomantic/PortOS/issues/9474) owns live Suno acceptance.
-Retry retains already-submitted IDs and does not press Create or spend more
-credits. Repeating Retry cannot resolve unknown completion until the integration
-provides that evidence.
+The CDN exposes playable partial files. Equal byte counts, an audio MIME header,
+a duration, or successful decoding cannot prove that generation ended. The
+adapter uses Suno's Download UI and waits for the browser to finish saving the
+M4A export before validating and importing it. It never downloads a CDN preview.
+
+Validation checks the container signature and uses ffmpeg to decode every audio
+frame with file-only access, the MOV/M4A demuxer, a bounded process deadline, and
+positive decoded-frame evidence. Original AAC or Opus audio and optional
+subtitles remain unchanged. Invalid content, missing ffmpeg, timeout, or
+cancellation prevents import. Temporary files are removed on success or failure;
+diagnostics contain fixed reasons rather than decoder output or private paths.
+
+[#9474](https://github.com/atomantic/PortOS/issues/9474) owns live acceptance of
+the new browser export driver. Deterministic browser fixtures and real synthetic
+decoder tests do not establish that live acceptance. Retry retains submitted IDs
+and does not press Create or spend credits on a second generation.
## Failure handling
- A signed-out Suno parks the run **`needs-human`** (`PUBLISH_LOGIN_REQUIRED`): sign in to Suno in the PortOS Browser, then Resume.
- Any other stage failure parks **`failed`** with the error; Retry re-runs that stage only. Songs already submitted to Suno are stored the moment Suno accepts the request, so a failed download retries the same songs and never spends credits on a second generation.
+- Resume after Stop waits for the prior stage attempt to settle before restarting. A Cancel while Resume waits remains canceled.
- A parked or failed delegated production run parks this run `needs-human`; Resume resumes the production run.
-The Suno adapter fills the form through `placeholder` / role selectors and reads the new `/song/<id>` links; everything after Create is plain HTTP against the CDN. If Suno redesigns the page, the failing step is named in the error (`Suno: fill the lyrics (…)`).
+The Suno adapter fills the form through `placeholder` / role selectors and reads the new `/song/<id>` links. It opens the first take in the same signed-in PortOS Browser, selects only M4A, and presses Download (or Unlock & Download) once. It waits for the browser download to finish saving, checks the container and decodes the complete audio to reject damaged files, and imports the original M4A without conversion. The export has a ten-minute deadline; timeout, cancellation, or invalid audio removes staging files and never imports a partial/error response. Failures identify the export stage using bounded reason metadata. A retry reopens the existing song rather than pressing Create again.
## API
diff --git a/server/lib/musicVideoAutonomous.js b/server/lib/musicVideoAutonomous.js
index 9c712249dc..52d625e81f 100644
--- a/server/lib/musicVideoAutonomous.js
+++ b/server/lib/musicVideoAutonomous.js
@@ -192,8 +192,6 @@ export function sunoSongIdsFromHrefs(hrefs) {
return ids;
}
-/** The public CDN URL Suno serves a finished song's audio from. */
-export const sunoAudioUrl = (songId) => `https://cdn1.suno.ai/${encodeURIComponent(songId)}.mp3`;
export const sunoSongUrl = (songId) => `https://suno.com/song/${encodeURIComponent(songId)}`;
/**
diff --git a/server/lib/musicVideoAutonomous.test.js b/server/lib/musicVideoAutonomous.test.js
index 2200df59f0..a1bb449477 100644
--- a/server/lib/musicVideoAutonomous.test.js
+++ b/server/lib/musicVideoAutonomous.test.js
@@ -8,7 +8,6 @@ import {
normalizeAutonomousBrief,
normalizeAutopilotParams,
pickBrainIdea,
- sunoAudioUrl,
sunoSongFields,
sunoSongIdsFromHrefs,
} from './musicVideoAutonomous.js';
@@ -87,7 +86,6 @@ describe('Suno field shaping', () => {
const b = '9f8e7d6c-aaaa-bbbb-cccc-ddddeeeeffff';
expect(sunoSongIdsFromHrefs([`/song/${a}`, '/create', `https://suno.com/song/${b.toUpperCase()}?x=1`, `/song/${a}`, null, '/song/not-a-uuid']))
.toEqual([a, b]);
- expect(sunoAudioUrl(a)).toBe(`https://cdn1.suno.ai/${a}.mp3`);
});
});
diff --git a/server/services/musicVideo/autonomousService.js b/server/services/musicVideo/autonomousService.js
index 8fcf1351b1..4ae1571117 100644
--- a/server/services/musicVideo/autonomousService.js
+++ b/server/services/musicVideo/autonomousService.js
@@ -47,7 +47,8 @@ import { getProject, mutateProjectRecord } from './projects.js';
import { musicVideoEvents } from './events.js';
const PROCESS_ID = `proc-${randomUUID()}`;
-const inflight = new Set();
+const inflight = new Map();
+const sunoControllers = new Map();
const short = (id) => String(id).slice(0, 8);
// Lazy imports keep this module's static closure small: it is reached by the
@@ -195,9 +196,15 @@ const STAGES = {
});
let submitted = run.output.sunoSongIds?.length > 0;
let song;
+ const controller = new AbortController();
+ sunoControllers.set(run.id, controller);
try {
+ const latest = projectAutonomousRun(await getProject(project.id));
+ if (latest?.id !== run.id || latest.status !== 'running') controller.abort();
+ controller.signal.throwIfAborted();
song = await deps.generateSunoSong(fields, {
songIds: run.output.sunoSongIds,
+ signal: controller.signal,
// Stored the moment Suno accepts the request, so a failed download retries
// the same songs instead of spending credits on another generation.
onSubmitted: (ids) => { submitted = true; return save({ output: { sunoSongIds: ids } }); },
@@ -205,11 +212,14 @@ const STAGES = {
} catch (err) {
// Only before Suno accepted a request: after that, credits are spent and a
// retry reuses those songs rather than paying for a second render.
- if (!run.brief.localFallback || submitted) throw err;
+ if (controller.signal.aborted || !run.brief.localFallback || submitted) throw err;
console.warn(`⚠️ Autonomous music video ${short(run.id)} could not use Suno (${trimTo(err.message, 200)}) — rendering the song locally`);
await save({ output: { songSource: 'local', songFallbackReason: trimTo(err.message, 500) } });
return localSong({ project, run, save });
+ } finally {
+ sunoControllers.delete(run.id);
}
+ controller.signal.throwIfAborted();
const track = await deps.createTrack({
title: fields.title, concept: run.brief.prompt, lyrics: fields.lyrics, prompt: fields.style,
});
@@ -257,7 +267,8 @@ async function park(projectId, status, patch) {
async function advance(projectId) {
if (inflight.has(projectId)) return;
- inflight.add(projectId);
+ const settlement = Promise.withResolvers();
+ inflight.set(projectId, settlement.promise);
try {
for (;;) {
const project = await getProject(projectId);
@@ -274,7 +285,7 @@ async function advance(projectId) {
try {
result = await executor({ project, run, save: (patch) => patchRun(projectId, () => patch) });
} catch (err) {
- // A stop/cancel mid-stage (it cancels the local render) must not become a failure.
+ // A stop/cancel mid-stage (it cancels the song operation) must not become a failure.
const latest = projectAutonomousRun(await getProject(projectId));
if (latest?.status !== 'running' || latest.processId !== PROCESS_ID) return;
await patchRun(projectId, (r) => stagePatch(r, stage, { status: 'failed', error: trimTo(err.message, 500) }));
@@ -301,6 +312,7 @@ async function advance(projectId) {
console.error(`❌ Autonomous music video advance failed for ${short(projectId)}: ${err.message}`);
} finally {
inflight.delete(projectId);
+ settlement.resolve();
}
}
@@ -362,12 +374,21 @@ export async function getAutonomousRun(projectId) {
* approve the checkpoint it is waiting on (optionally replacing the stage
* output the director edited). Returns `{ project, run }`.
*/
-export async function resumeAutonomousVideo(projectId, edits = {}) {
- const { run } = await requireRun(projectId);
+const assertResumable = (run) => {
const resumable = AUTONOMOUS_LIVE_STATUSES.includes(run.status) || run.status === 'failed';
if (!resumable) throw runError(409, 'NOT_RESUMABLE', `A ${run.status} run cannot be resumed`);
if (run.status === 'running' && run.processId === PROCESS_ID) throw runError(409, 'ALREADY_RUNNING', 'This run is already running');
+};
+
+export async function resumeAutonomousVideo(projectId, edits = {}) {
+ const { run } = await requireRun(projectId);
+ assertResumable(run);
+ // Stop changes the record immediately, but its stage may still be settling.
+ // Let that attempt release ownership before marking a new attempt running.
+ await inflight.get(projectId);
const out = await patchRun(projectId, (r) => {
+ // Cancel or another Resume may have won while the old attempt settled.
+ assertResumable(r);
// A run waiting on production resumes by resuming that run, not by redoing
// the stage — the stage re-runs only when production never started.
const stage = r.stage;
@@ -407,6 +428,7 @@ export async function stopAutonomousVideo(projectId) {
const { stopProduction } = await import('./productionService.js');
await stopProduction(projectId, run.output.productionRunId).catch(() => {});
}
+ sunoControllers.get(run.id)?.abort();
await cancelLocalSongJob(out.run);
return { project: out.project, run: presentAutonomousRun(out.run) };
}
@@ -419,6 +441,7 @@ export async function cancelAutonomousVideo(projectId) {
const { cancelProduction } = await import('./productionService.js');
await cancelProduction(projectId, run.output.productionRunId).catch(() => {});
}
+ sunoControllers.get(run.id)?.abort();
await cancelLocalSongJob(out.run);
return { project: out.project, run: presentAutonomousRun(out.run) };
}
diff --git a/server/services/musicVideo/autonomousService.test.js b/server/services/musicVideo/autonomousService.test.js
index e0c5f04af9..cf316e018a 100644
--- a/server/services/musicVideo/autonomousService.test.js
+++ b/server/services/musicVideo/autonomousService.test.js
@@ -263,6 +263,54 @@ describe('local song source (#9473)', () => {
expect(runOf().output.sunoSongIds).toEqual(['song-a']);
});
+ it.each(['stopAutonomousVideo', 'cancelAutonomousVideo'])('aborts a Suno export through %s and preserves its submitted ids without attaching audio', async (action) => {
+ let signal;
+ let ended = false;
+ doubles.generateSunoSong.mockImplementationOnce(async (_fields, opts) => {
+ signal = opts.signal;
+ await opts.onSubmitted(['song-a', 'song-b']);
+ try {
+ await new Promise((_, reject) => signal.addEventListener('abort', () => reject(new Error('cancelled')), { once: true }));
+ } finally { ended = true; }
+ });
+ await service.startAutonomousVideo({ prompt: 'p', localFallback: true });
+ await vi.waitFor(() => expect(runOf()?.output.sunoSongIds).toEqual(['song-a', 'song-b']));
+ await service[action]('mv-auto');
+ await vi.waitFor(() => expect(ended).toBe(true));
+ expect(signal.aborted).toBe(true);
+ expect(runOf()).toMatchObject({ status: action === 'stopAutonomousVideo' ? 'stopped' : 'canceled', output: { sunoSongIds: ['song-a', 'song-b'] } });
+ expect(doubles.createTrack).not.toHaveBeenCalled();
+ expect(doubles.generateLocalSong).not.toHaveBeenCalled();
+ });
+
+ it.each([false, true])('settles a stopped Suno attempt before resuming, honoring a later Cancel (%s)', async (cancelWhileWaiting) => {
+ let rejectPending;
+ doubles.generateSunoSong.mockImplementationOnce(async (_fields, opts) => {
+ await opts.onSubmitted(['song-a', 'song-b']);
+ return new Promise((_, reject) => { rejectPending = reject; });
+ });
+ await service.startAutonomousVideo({ prompt: 'example' });
+ await vi.waitFor(() => expect(rejectPending).toBeTypeOf('function'));
+ await service.stopAutonomousVideo('mv-auto');
+ const resumed = service.resumeAutonomousVideo('mv-auto');
+ const result = cancelWhileWaiting
+ ? expect(resumed).rejects.toMatchObject({ code: 'NOT_RESUMABLE' })
+ : expect(resumed).resolves.toMatchObject({ run: { status: 'running' } });
+ if (cancelWhileWaiting) await service.cancelAutonomousVideo('mv-auto');
+ expect(doubles.generateSunoSong).toHaveBeenCalledTimes(1);
+ rejectPending(new Error('Export cancelled by earlier Stop'));
+ await result;
+ if (cancelWhileWaiting) {
+ expect(runOf().status).toBe('canceled');
+ expect(doubles.generateSunoSong).toHaveBeenCalledTimes(1);
+ } else {
+ await vi.waitFor(() => expect(calls).toContain('production'));
+ expect(doubles.generateSunoSong).toHaveBeenCalledTimes(2);
+ expect(doubles.generateSunoSong).toHaveBeenLastCalledWith(expect.any(Object), expect.objectContaining({ songIds: ['song-a', 'song-b'] }));
+ expect(runOf()).toMatchObject({ status: 'running', error: null });
+ }
+ });
+
it('cancels the queued render on stop and leaves the run stopped, not failed', async () => {
let release;
doubles.generateLocalSong.mockImplementationOnce(async ({ onSubmitted }) => {
diff --git a/server/services/musicVideo/autonomousSuno.audio.test.js b/server/services/musicVideo/autonomousSuno.audio.test.js
new file mode 100644
index 0000000000..8bc1dead51
--- /dev/null
+++ b/server/services/musicVideo/autonomousSuno.audio.test.js
@@ -0,0 +1,77 @@
+import { EventEmitter } from 'node:events';
+import { mkdtemp, readFile, writeFile, rm, stat } from 'node:fs/promises';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { promisify } from 'node:util';
+import { describe, it, expect, vi } from 'vitest';
+import { execFile } from '../../lib/childProcess.js';
+import { findFfmpeg } from '../../lib/ffmpeg.js';
+import { generateSunoSong } from './autonomousSuno.js';
+
+const ffmpeg = await findFfmpeg();
+const execFileAsync = promisify(execFile);
+const SONG = '22222222-2222-2222-2222-222222222222';
+
+// Exercise the default decoder through the import boundary, with synthetic
+// bytes delivered by a completed browser export. No live Suno or provider calls.
+function completedExport(bytes) {
+ const page = new EventEmitter();
+ let path;
+ page.goto = async () => {};
+ page.url = () => `https://suno.com/song/${SONG}`;
+ page.close = async () => {};
+ const download = {
+ saveAs: async (target) => { path = target; await writeFile(target, bytes); },
+ failure: async () => null, cancel: async () => {}, delete: async () => {},
+ };
+ page.getByRole = (_role, { name }) => {
+ const button = {
+ evaluate: async () => name === 'M4A',
+ click: async () => { if (name instanceof RegExp) page.emit('download', download); },
+ };
+ return { ...button, first: () => button };
+ };
+ return {
+ songIds: [SONG],
+ connect: async () => ({ browser: { close: async () => {} }, context: { newPage: async () => page } }),
+ importAudio: vi.fn(async (target, name) => {
+ expect(await readFile(target)).toEqual(bytes);
+ expect(name).toBe('song.m4a');
+ return { filename: 'example.m4a', sizeBytes: bytes.length };
+ }),
+ savedPath: () => path,
+ };
+}
+
+describe.skipIf(!ffmpeg)('Suno real M4A decoder', () => {
+ it.each(['aac', 'libopus'])('imports completed %s M4A unchanged and rejects a truncated faststart body', async (codec) => {
+ const dir = await mkdtemp(join(tmpdir(), 'portos-suno-fixture-'));
+ try {
+ const fixture = join(dir, 'example.m4a');
+ await execFileAsync(ffmpeg, ['-nostdin', '-v', 'error', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=2', '-c:a', codec, '-movflags', '+faststart', '-f', 'mp4', fixture], { timeout: 15_000 });
+ const bytes = await readFile(fixture);
+ const good = completedExport(bytes);
+ await expect(generateSunoSong({}, good)).resolves.toMatchObject({ filename: 'example.m4a' });
+ expect(good.importAudio).toHaveBeenCalledOnce();
+ await expect(stat(good.savedPath())).rejects.toMatchObject({ code: 'ENOENT' });
+
+ const bad = completedExport(bytes.subarray(0, Math.floor(bytes.length * 0.6)));
+ const error = await generateSunoSong({}, bad).catch(err => err);
+ expect(error).toMatchObject({ code: 'SUNO_AUDIO_INVALID', context: { reason: 'decode_failed' } });
+ expect(JSON.stringify({ message: error.message, context: error.context })).not.toMatch(/example\.m4a|portos-suno|Invalid|Error/);
+ expect(bad.importAudio).not.toHaveBeenCalled();
+ await expect(stat(bad.savedPath())).rejects.toMatchObject({ code: 'ENOENT' });
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+ });
+
+ it.each(['html', 'malformed-container'])('rejects %s without importing and removes the staged download', async (kind) => {
+ const bytes = Buffer.alloc(200 * 1024, kind === 'html' ? '<html>private-body' : 0);
+ if (kind !== 'html') bytes.write('ftyp', 4);
+ const w = completedExport(bytes);
+ await expect(generateSunoSong({}, w)).rejects.toMatchObject({ code: 'SUNO_AUDIO_INVALID' });
+ expect(w.importAudio).not.toHaveBeenCalled();
+ await expect(stat(w.savedPath())).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+});
diff --git a/server/services/musicVideo/autonomousSuno.js b/server/services/musicVideo/autonomousSuno.js
index abb9137d93..3afec2ab07 100644
--- a/server/services/musicVideo/autonomousSuno.js
+++ b/server/services/musicVideo/autonomousSuno.js
@@ -1,46 +1,22 @@
/**
- * Autonomous Music Video — the Suno step.
- *
- * Drives the Suno web UI in the PortOS Browser (the same signed-in profile the
- * publish adapters use; no Suno API or credential is involved) to make one song
- * from generated lyrics + a style line, then downloads the finished audio from
- * Suno's public CDN into the music library and imports it as a Track.
- *
- * Two deliberate choices keep this robust to Suno's UI churn:
- * - The page is only used to FILL the custom-song form, press Create, and
- * read back the new `/song/<id>` links. Everything after that — waiting for
- * audio — happens over HTTP against the CDN. This transport does not yet
- * provide a verified generation-completion signal; import fails closed.
- * - Every page interaction goes through `step()`, so a failure names the
- * control that was missing ("Suno: fill the lyrics (...)") and a signed-out
- * page is reported as PUBLISH_LOGIN_REQUIRED, which the run surfaces as a
- * parked "needs you" state rather than a generic failure.
- *
- * `page`, `fetch`, `sleep` and the storage calls are injectable so the whole
- * flow is unit-testable without a browser or the network.
+ * Generate a Suno song in the signed-in PortOS Browser, export only M4A
+ * 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, rm, writeFile } from 'fs/promises';
+import { mkdtemp, open, rm } from 'fs/promises';
import { join } from 'path';
import { tmpdir } from 'os';
import { promisify } from 'util';
import { execFile } from '../../lib/childProcess.js';
import { safeChildProcessOptions } from '../../lib/processEnv.js';
-import { withAbortTimeout } from '../../lib/abortTimeout.js';
import { ServerError } from '../../lib/errorHandler.js';
-import { sunoAudioUrl, sunoSongIdsFromHrefs } from '../../lib/musicVideoAutonomous.js';
+import { sunoSongIdsFromHrefs, sunoSongUrl } from '../../lib/musicVideoAutonomous.js';
import { sleep as defaultSleep } from '../../lib/fileCore.js';
import { PUBLISH_STEP_TIMEOUT_MS as T, connectPortosBrowser, loginRequired, serializeBrowserOperation as serialize, step } from './publish/browser.js';
const LABEL = 'Suno';
const SUNO_CREATE_URL = 'https://suno.com/create';
-// How long a generation may take before the run gives up on it, and how often
-// the CDN is polled while waiting. Suno finishes a song in roughly a minute or
-// two; the cap covers a busy queue.
const SUNO_AUDIO_TIMEOUT_MS = 10 * 60 * 1000;
-const SUNO_POLL_INTERVAL_MS = 10 * 1000;
-// A real song is megabytes; anything under this is a stub or error body.
-const MIN_AUDIO_BYTES = 100 * 1024;
const songLinks = (page, title = null) => page.evaluate((wantedTitle) => [...document.querySelectorAll('a[href*="/song/"]')]
// Workspace rows may finish loading after Create. A newly seen href alone
@@ -112,7 +88,8 @@ async function sunoRefusalSignals(page) {
* the click are excluded, so an older song in the workspace is never mistaken
* for ours.
*/
-async function submitSunoSong(page, fields, { sleep = defaultSleep, now = Date.now } = {}) {
+async function submitSunoSong(page, fields, { sleep = defaultSleep, now = Date.now, signal } = {}) {
+ signal?.throwIfAborted();
await step(LABEL, 'open the create page', () => page.goto(SUNO_CREATE_URL, { waitUntil: 'domcontentloaded', timeout: T }));
await page.locator('textarea').first().waitFor({ state: 'visible', timeout: T }).catch(() => {});
// A signed-out visitor is bounced to a sign-in page or sees no create form.
@@ -157,6 +134,7 @@ async function submitSunoSong(page, fields, { sleep = defaultSleep, now = Date.n
const observer = observeSunoPosts(page);
try {
await step(LABEL, 'press Create', async () => {
+ signal?.throwIfAborted();
await page.getByRole('button', { name: /^create( song)?$/i }).last().click({ timeout: T });
});
@@ -182,150 +160,165 @@ async function submitSunoSong(page, fields, { sleep = defaultSleep, now = Date.n
}
}
-// Decoding is a separate boundary from generation completion: a partial MP3
-// can decode perfectly. Never expose ffmpeg stderr (it contains local paths).
-async function validateSunoAudio(bytes, { signal, timeoutMs }) {
+// Container metadata cannot prove audio frames are complete and decodable.
+// Preserve the strict decoder boundary from the former CDN adapter, now using
+// the completed browser download and accepting Suno's AAC or Opus M4A output.
+async function validateSunoAudio(path, { signal, timeoutMs }) {
+ const file = await open(path, 'r');
+ const header = Buffer.alloc(12);
+ const { bytesRead } = await file.read(header, 0, header.length, 0).finally(() => file.close());
+ if (bytesRead !== 12 || header.toString('ascii', 4, 8) !== 'ftyp') return false;
const { findFfmpeg } = await import('../../lib/ffmpeg.js');
const bin = await findFfmpeg();
if (!bin) throw new ServerError('Suno: audio validation requires ffmpeg', {
status: 503, code: 'SUNO_AUDIO_VALIDATION_UNAVAILABLE', context: { platform: LABEL },
});
signal.throwIfAborted();
- const dir = await mkdtemp(join(tmpdir(), 'portos-suno-validation-'));
try {
- const file = join(dir, 'candidate.mp3');
- await writeFile(file, bytes, { signal });
- // Force an audio stream and decode the entire candidate; neither MIME nor
- // a readable container header proves that its audio frames are decodable.
+ // Decode every frame without transcoding the source. Restrict both the
+ // protocol and demuxer: a downloaded playlist cannot initiate network I/O.
const { stdout } = await promisify(execFile)(bin, [
'-nostdin', '-v', 'error', '-xerror', '-err_detect', 'explode',
- '-protocol_whitelist', 'file', '-format_whitelist', 'mp3,wav', '-i', file,
+ '-protocol_whitelist', 'file', '-format_whitelist', 'mov', '-i', path,
'-map', '0:a:0', '-progress', 'pipe:1', '-stats_period', '600', '-f', 'null', '-',
], safeChildProcessOptions({ signal, timeout: Math.min(timeoutMs, 15_000), killSignal: 'SIGKILL', maxBuffer: 64 * 1024 }));
if (![...stdout.matchAll(/^out_time_us=(\d+)$/gm)].some((match) => Number(match[1]) > 0)) {
throw new Error('No decoded audio frames');
}
return true;
- } catch (error) {
+ } catch {
if (signal.aborted) throw signal.reason;
+ // Raw decoder output contains local paths and must not enter diagnostics.
throw new ServerError('Suno: downloaded content is not decodable audio', {
status: 502, code: 'SUNO_AUDIO_INVALID', context: { platform: LABEL, reason: 'decode_failed' },
});
- } finally {
- await rm(dir, { recursive: true, force: true });
}
}
-/**
- * Stable sizes are only a polling heuristic. The CDN integration currently
- * has no verified completion signal, so its default remains explicitly
- * unknown. A future verified adapter must check this exact song and return
- * 'complete'; playable audio, a duration, or a 200 response are not evidence.
- */
-async function downloadSunoAudio(songId, {
- fetchImpl = fetch, sleep = defaultSleep, timeoutMs = SUNO_AUDIO_TIMEOUT_MS, intervalMs = SUNO_POLL_INTERVAL_MS, now = Date.now,
- checkCompletion = async () => 'unknown', validateAudio = validateSunoAudio,
+/** 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,
} = {}) {
- const deadline = now() + timeoutMs;
- let lastSize = -1;
- let reason = 'not_available';
- let httpStatus = null;
- const timeout = () => new ServerError('Suno: audio download did not complete within its time budget', {
- status: 504, code: 'SUNO_AUDIO_TIMEOUT', context: { platform: LABEL, reason, httpStatus },
+ const controller = new AbortController();
+ const deadline = Date.now() + timeoutMs;
+ const remaining = () => Math.max(1, deadline - Date.now());
+ let download;
+ let stage = 'open-song';
+ let stopped;
+ let rejectStop;
+ const stopPromise = new Promise((_, reject) => { rejectStop = reject; });
+ // The operation may already be cancelled before its first await.
+ stopPromise.catch(() => {});
+ const error = (code, reason, status = 502) => new ServerError(`Suno: M4A export ${reason}`, {
+ status, code, context: { platform: LABEL, stage, reason },
});
- for (;;) {
- const remaining = deadline - now();
- if (remaining <= 0) throw timeout();
- const candidate = await withAbortTimeout(remaining, async (signal) => {
- let res;
- try {
- // Fetch only after observing completion, so a status transition cannot
- // certify bytes downloaded while the song was still rendering.
- const completion = await checkCompletion(songId, { signal });
- signal.throwIfAborted();
- res = await fetchImpl(sunoAudioUrl(songId), { signal });
- signal.throwIfAborted();
- httpStatus = Number.isInteger(res.status) && res.status >= 100 && res.status <= 599 ? res.status : null;
- if (!res.ok) { reason = 'http_status'; return null; }
- const mime = res.headers?.get('content-type')?.split(';')[0].trim().toLowerCase();
- if (mime?.startsWith('text/') || /(?:json|xml|html)/.test(mime || '')) {
- throw new ServerError('Suno: downloaded content is not audio', {
- status: 502, code: 'SUNO_AUDIO_INVALID', context: { platform: LABEL, reason: 'non_audio_content', httpStatus },
- });
- }
- const bytes = Buffer.from(await res.arrayBuffer());
- signal.throwIfAborted();
- const stable = bytes.length >= MIN_AUDIO_BYTES && bytes.length === lastSize;
- lastSize = bytes.length;
- if (!stable) { reason = 'size_unstable'; return null; }
- const valid = await validateAudio(bytes, { signal, timeoutMs: Math.max(1, deadline - now()) });
- signal.throwIfAborted();
- if (valid !== true) throw new ServerError('Suno: downloaded content is not decodable audio', {
- status: 502, code: 'SUNO_AUDIO_INVALID', context: { platform: LABEL, reason: 'decode_failed' },
- });
- if (completion === 'complete') return bytes;
- if (completion === 'pending') { reason = 'generation_pending'; return null; }
- throw new ServerError('Suno: audio is decodable, but generation completion is unverified; existing song IDs are retained for retry', {
- status: 502, code: 'SUNO_AUDIO_COMPLETION_UNVERIFIED', context: { platform: LABEL, reason: 'completion_unknown' },
- });
- } catch (error) {
- if (signal.aborted) { reason = 'deadline_exceeded'; throw timeout(); }
- if (error instanceof ServerError) throw error;
- reason = 'transport_failed';
- return null;
- } finally {
- // Cancel unconsumed error bodies too. A locked body is owned by the
- // fetch consumer, which receives the same abort signal. Cancellation
- // starts immediately; its acknowledgment cannot extend our deadline.
- if (res?.body && !res.bodyUsed) void res.body.cancel().catch(() => {});
- }
+ const stop = (err) => {
+ if (stopped) return;
+ stopped = err;
+ controller.abort();
+ rejectStop(err);
+ // Don't await an unresponsive browser during cancellation.
+ download?.cancel().catch(() => {});
+ };
+ const abort = () => stop(error('SUNO_AUDIO_CANCELLED', 'cancelled', 499));
+ const timer = setTimeout(() => stop(error('SUNO_AUDIO_TIMEOUT', 'deadline-exceeded', 504)), timeoutMs);
+ signal?.addEventListener('abort', abort, { once: true });
+ if (signal?.aborted) abort();
+ const bounded = async (name, fn) => {
+ stage = name;
+ if (stopped) throw stopped;
+ return Promise.race([Promise.resolve().then(fn), stopPromise]);
+ };
+ let onDownload;
+ 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);
+ await bounded('open-options', () => page.getByRole('button', { name: 'More options', exact: true }).first().click({ timeout: remaining() }));
+ await bounded('open-download', () => page.getByRole('menuitem', { name: 'Download', exact: true }).click({ timeout: remaining() }));
+ for (const name of ['M4A', 'MP3', 'WAV', 'MP4 video asset']) {
+ const button = page.getByRole('button', { name, exact: true });
+ const selected = await bounded('select-m4a', () => button.evaluate((el) => el.classList.contains('bg-foreground-primary') && el.classList.contains('text-background-primary')));
+ if (selected !== (name === 'M4A')) await bounded('select-m4a', () => button.click({ timeout: remaining() }));
+ }
+ // Fail closed if Suno changes selection behavior: never unlock an export
+ // while another format remains selected or M4A failed to become selected.
+ for (const name of ['M4A', 'MP3', 'WAV', 'MP4 video asset']) {
+ const selected = await bounded('verify-m4a', () => page.getByRole('button', { name, exact: true }).evaluate((el) => el.classList.contains('bg-foreground-primary') && el.classList.contains('text-background-primary')));
+ if (selected !== (name === 'M4A')) throw error('SUNO_AUDIO_DOWNLOAD_FAILED', 'format-selection-failed');
+ }
+ // Register before clicking; a completed export can emit immediately. Own
+ // the listener so timeout/cancellation can remove it without waiting for a
+ // second Playwright timeout. Never repeat an Unlock & Download click.
+ const started = new Promise((resolve) => {
+ onDownload = (value) => { download = value; resolve(value); };
+ page.once('download', onDownload);
});
- if (now() >= deadline) throw timeout();
- if (candidate) return candidate;
- if (now() + intervalMs >= deadline) throw timeout();
- await sleep(intervalMs);
+ 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');
+ 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;
+ // Playwright and ffprobe errors may contain user paths, URLs or page text.
+ throw error('SUNO_AUDIO_DOWNLOAD_FAILED', 'export-failed');
+ } finally {
+ clearTimeout(timer);
+ signal?.removeEventListener('abort', abort);
+ if (onDownload) page.off('download', onDownload);
+ // The page owner closes it before removing the staging directory. Cancel
+ // also stops pending saveAs work; browser artifact deletion is best effort.
+ if (download) {
+ download.cancel().catch(() => {});
+ download.delete().catch(() => {});
+ }
}
}
-/**
- * Make one Suno song and import it into the music library.
- *
- * `fields` is the output of `sunoSongFields`. Resolves to
- * `{ songId, songIds, filename, sizeBytes }` — the first take is imported; its
- * sibling take ids are returned so the run can record them.
- */
+// A dead CDP connection must not turn an already timed-out export into an
+// unbounded cleanup wait. Close the tab before disconnecting. Cancellation of
+// an already dispatched browser action is best effort if CDP is unresponsive;
+// we never retry that click, and an aborted operation can never import audio.
+async function closeSunoBrowser(page, browser) {
+ for (const close of [() => page?.close(), () => browser.close()]) {
+ let timer;
+ await Promise.race([
+ Promise.resolve().then(close).catch(() => {}),
+ new Promise(resolve => { timer = setTimeout(resolve, 500); }),
+ ]).finally(() => clearTimeout(timer));
+ }
+}
+
+/** Generate (or resume) a song and import its completed, validated M4A. */
export async function generateSunoSong(fields, deps = {}) {
const connect = deps.connect || connectPortosBrowser;
- const importAudio = deps.importAudio || (async (bytes) => {
+ const importAudio = deps.importAudio || (async (path, name) => {
const { importUploadedTrack } = await import('../pipeline/musicLibrary.js');
- const dir = await mkdtemp(join(tmpdir(), 'portos-suno-'));
- const tmp = join(dir, 'song.mp3');
- try {
- await writeFile(tmp, bytes);
- return await importUploadedTrack(tmp, 'song.mp3');
- } finally {
- await rm(dir, { recursive: true, force: true });
- }
- });
- // A retry after a failed download reuses the songs already submitted rather
- // than spending more Suno credits on a second generation.
- const songIds = deps.songIds?.length ? deps.songIds : await serialize(async () => {
- const { browser, context } = await connect();
- const page = await context.newPage();
- try {
- const submitted = await submitSunoSong(page, fields, deps);
- await deps.onSubmitted?.(submitted);
- return submitted;
- } finally {
- await page.close().catch(() => {});
- await browser.close().catch(() => {}); // disconnects; the PortOS Browser keeps running
- }
+ return importUploadedTrack(path, name);
});
- const [songId] = songIds;
- const bytes = await downloadSunoAudio(songId, deps);
- const { filename, sizeBytes } = await importAudio(bytes);
- console.log(`🎵 Suno audio imported (${Math.round(sizeBytes / 1024)} KB)`);
- return { songId, songIds, filename, sizeBytes };
+ const dir = await mkdtemp(join(tmpdir(), 'portos-suno-'));
+ const path = join(dir, 'song.m4a');
+ try {
+ const songIds = await serialize(async () => {
+ deps.signal?.throwIfAborted();
+ const { browser, context } = await connect();
+ let page;
+ try {
+ page = await context.newPage();
+ const ids = deps.songIds?.length ? deps.songIds : await submitSunoSong(page, fields, deps);
+ if (!deps.songIds?.length) await deps.onSubmitted?.(ids);
+ await downloadSunoAudio(page, ids[0], path, deps);
+ return ids;
+ } finally {
+ await closeSunoBrowser(page, browser); // disconnect; keep the shared browser running
+ }
+ });
+ deps.signal?.throwIfAborted();
+ const { filename, sizeBytes } = await importAudio(path, 'song.m4a');
+ return { songId: songIds[0], songIds, filename, sizeBytes };
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
}
export const __testing = { submitSunoSong, downloadSunoAudio };
diff --git a/server/services/musicVideo/autonomousSuno.test.js b/server/services/musicVideo/autonomousSuno.test.js
index 35dd9a5a62..d61e58416d 100644
--- a/server/services/musicVideo/autonomousSuno.test.js
+++ b/server/services/musicVideo/autonomousSuno.test.js
@@ -1,24 +1,15 @@
-/**
- * The Suno step with a fake browser page and a fake CDN. Pins what only this
- * layer knows: a signed-out page is a login-required park (not a generic
- * failure), songs already in the workspace are never mistaken for ours, audio
- * requires decoding and verified completion, and a retry reuses submitted songs.
- */
-
import { EventEmitter } from 'node:events';
-import { mkdtemp, access } from 'fs/promises';
-import { findFfmpeg } from '../../lib/ffmpeg.js';
+import { readFile, writeFile, stat } from 'node:fs/promises';
import { describe, it, expect, vi, afterEach } from 'vitest';
-import { __testing, generateSunoSong } from './autonomousSuno.js';
+import { findFfmpeg } from '../../lib/ffmpeg.js';
-vi.mock('fs/promises', async (importOriginal) => {
- const actual = await importOriginal();
- return { ...actual, mkdtemp: vi.fn(actual.mkdtemp) };
-});
-const ffmpegAvailable = Boolean(await findFfmpeg());
-const completed = { checkCompletion: async () => 'complete', validateAudio: async () => true };
+const { decode } = vi.hoisted(() => ({ decode: vi.fn(async () => ({ stdout: 'out_time_us=12000000\n' })) }));
+vi.mock('../../lib/childProcess.js', () => ({ execFile: Object.assign(() => {}, { [Symbol.for('nodejs.util.promisify.custom')]: decode }) }));
-const { downloadSunoAudio, submitSunoSong } = __testing;
+vi.mock('../../lib/ffmpeg.js', () => ({ findFfmpeg: vi.fn(async () => 'ffmpeg') }));
+import { __testing, generateSunoSong } from './autonomousSuno.js';
+
+const { submitSunoSong } = __testing;
const OLD = '11111111-1111-1111-1111-111111111111';
const NEW_A = '22222222-2222-2222-2222-222222222222';
@@ -47,6 +38,8 @@ function fakePage({ url = 'https://suno.com/create', hasForm = true, modern = tr
return {
fills,
on: events.on.bind(events),
+ once: events.once.bind(events),
+ emit: events.emit.bind(events),
off: events.off.bind(events),
listenerCount: events.listenerCount.bind(events),
goto: vi.fn(async () => {}),
@@ -135,174 +128,199 @@ describe('submitSunoSong', () => {
});
});
-describe('downloadSunoAudio', () => {
- afterEach(() => vi.useRealTimers());
- const body = (size) => ({ ok: true, arrayBuffer: async () => new ArrayBuffer(size) });
+// 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 } = {}) {
+ const page = fakePage();
+ const baseRole = page.getByRole;
+ const selected = new Set(['MP3', 'WAV', 'MP4 video asset']);
+ const actions = [];
+ let savedPath;
+ const download = {
+ saveAs: vi.fn(async (path) => {
+ savedPath = path;
+ await writeFile(path, bytes);
+ if (stalled === 'save') return new Promise(() => {});
+ }),
+ failure: vi.fn(async () => failure),
+ cancel: vi.fn(async () => {}),
+ delete: vi.fn(async () => {}),
+ };
+ page.getByRole = (role, options) => {
+ const name = options.name;
+ if (typeof name === 'string' && ['M4A', 'MP3', 'WAV', 'MP4 video asset'].includes(name)) return {
+ evaluate: async (fn) => fn({ classList: { contains: () => selected.has(name) } }),
+ click: async () => { actions.push(name); if (ignoreSelection) return; selected.has(name) ? selected.delete(name) : selected.add(name); },
+ };
+ 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 (role === 'menuitem') return { click: async ({ timeout }) => {
+ actions.push(name);
+ if (readyAfterMs) {
+ expect(timeout).toBeGreaterThan(readyAfterMs);
+ await new Promise(resolve => setTimeout(resolve, readyAfterMs));
+ }
+ } };
+ return baseRole(role, options);
+ };
+ page.close = vi.fn(async () => {});
+ const browser = { close: vi.fn(async () => {}) };
+ const connect = vi.fn(async () => ({ browser, context: { newPage: async () => page } }));
+ const importAudio = vi.fn(async (path, name) => {
+ expect(name).toBe('song.m4a');
+ expect(await readFile(path)).toEqual(m4a);
+ return { filename: 'music-example.m4a', sizeBytes: m4a.length };
+ });
+ return { page, selected, actions, download, savedPath: () => savedPath, browser, connect, importAudio };
+}
+
+describe('generateSunoSong M4A export', () => {
+ const fields = { title: 'Example Song', style: 'synthwave', lyrics: 'example', instrumental: false };
+ afterEach(() => { vi.useRealTimers(); vi.clearAllMocks(); });
+
+ it('submits once, selects only M4A, saves the completed download, and imports the original file', async () => {
+ const w = workflow();
+ const onSubmitted = vi.fn();
+ const out = await generateSunoSong(fields, { ...w, onSubmitted, sleep: noSleep });
+ expect(out).toEqual({ songId: NEW_A, songIds: [NEW_A, NEW_B], filename: 'music-example.m4a', sizeBytes: m4a.length });
+ expect(onSubmitted).toHaveBeenCalledWith([NEW_A, NEW_B]);
+ expect(w.selected).toEqual(new Set(['M4A']));
+ expect(w.actions.filter(x => x === 'export')).toHaveLength(1);
+ expect(w.importAudio).toHaveBeenCalledTimes(1);
+ expect(decode).toHaveBeenCalledWith('ffmpeg', expect.arrayContaining(['-protocol_whitelist', 'file', '-format_whitelist', 'mov', '-err_detect', 'explode']), expect.objectContaining({ timeout: 15_000, killSignal: 'SIGKILL', maxBuffer: 64 * 1024, signal: expect.any(AbortSignal) }));
+ expect(w.page.listenerCount('download')).toBe(0);
+ expect(w.page.close).toHaveBeenCalled();
+ expect(w.browser.close).toHaveBeenCalled();
+ await expect(stat(w.savedPath())).rejects.toMatchObject({ code: 'ENOENT' });
+ });
- it('selects stable candidates for decoding and verified completion', async () => {
- const fetchImpl = vi.fn()
- .mockResolvedValueOnce({ ok: false })
- .mockResolvedValueOnce(body(1000)) // too small — a stub
- .mockResolvedValueOnce(body(300 * 1024)) // growing
- .mockResolvedValueOnce(body(400 * 1024))
- .mockResolvedValueOnce(body(400 * 1024)); // stable
- const bytes = await downloadSunoAudio(NEW_A, { ...completed, fetchImpl, sleep: noSleep, now: () => 0 });
- expect(bytes.length).toBe(400 * 1024);
- expect(fetchImpl).toHaveBeenCalledTimes(5);
- expect(fetchImpl).toHaveBeenCalledWith(`https://cdn1.suno.ai/${NEW_A}.mp3`, { signal: expect.any(AbortSignal) });
+ it('never presses Create or imports when stopped while the form is opening', async () => {
+ const w = workflow();
+ const controller = new AbortController();
+ w.page.goto.mockImplementationOnce(async () => controller.abort());
+ const onSubmitted = vi.fn();
+ await expect(generateSunoSong(fields, { ...w, signal: controller.signal, onSubmitted })).rejects.toThrow();
+ expect(onSubmitted).not.toHaveBeenCalled();
+ expect(w.page.listenerCount('request')).toBe(0);
+ expect(w.actions).not.toContain('export');
+ expect(w.importAudio).not.toHaveBeenCalled();
});
- it('times out with bounded diagnostics when it never finishes', async () => {
- let t = 0;
- await expect(downloadSunoAudio(NEW_A, {
- fetchImpl: async () => ({ ok: false }), sleep: noSleep, intervalMs: 10, timeoutMs: 25, now: () => (t += 10),
- })).rejects.toMatchObject({ code: 'SUNO_AUDIO_TIMEOUT', context: expect.objectContaining({ platform: 'Suno' }) });
+ it('reopens an existing song for export without ever pressing Create', async () => {
+ const w = workflow();
+ const onSubmitted = vi.fn();
+ const out = await generateSunoSong(fields, { ...w, songIds: [NEW_B], onSubmitted });
+ expect(w.page.goto).toHaveBeenCalledExactlyOnceWith(`https://suno.com/song/${NEW_B}`, expect.any(Object));
+ expect(w.page.fills).toEqual({});
+ expect(onSubmitted).not.toHaveBeenCalled();
+ expect(out.songId).toBe(NEW_B);
});
- it.each(['headers', 'body'])('aborts stalled %s at the overall deadline without leaking timers', async (phase) => {
+
+ it.each(['event', 'save'])('bounds a stalled download %s and cleans up without importing or retrying the click', async (stalled) => {
vi.useFakeTimers();
- let requestSignal;
- let bodyAborted = false;
- const fetchImpl = async (_url, { signal }) => {
- requestSignal = signal;
- const hang = () => new Promise((_resolve, reject) => signal.addEventListener('abort', () => {
- bodyAborted = phase === 'body';
- reject(signal.reason);
- }, { once: true }));
- if (phase === 'headers') return hang();
- return { ok: true, status: 200, bodyUsed: true, arrayBuffer: hang };
- };
- const assertion = expect(downloadSunoAudio(NEW_A, { fetchImpl, timeoutMs: 100 })).rejects.toMatchObject({
- code: 'SUNO_AUDIO_TIMEOUT', context: { reason: 'deadline_exceeded' },
- });
- await vi.advanceTimersByTimeAsync(100);
+ const w = workflow({ stalled });
+ const result = generateSunoSong(fields, { ...w, songIds: [NEW_A], timeoutMs: 1000 });
+ const assertion = expect(result).rejects.toMatchObject({ code: 'SUNO_AUDIO_TIMEOUT', context: { reason: 'deadline-exceeded' } });
+ await vi.waitFor(() => expect(w.actions).toContain('export'));
+ await vi.advanceTimersByTimeAsync(1000);
await assertion;
- expect(requestSignal.aborted).toBe(true);
- expect(bodyAborted).toBe(phase === 'body');
+ expect(w.importAudio).not.toHaveBeenCalled();
+ expect(w.page.listenerCount('download')).toBe(0);
+ expect(w.actions.filter(x => x === 'export')).toHaveLength(1);
+ expect(w.page.close).toHaveBeenCalled();
+ if (stalled === 'save') {
+ expect(w.download.cancel).toHaveBeenCalled();
+ await expect(stat(w.savedPath())).rejects.toMatchObject({ code: 'ENOENT' });
+ }
expect(vi.getTimerCount()).toBe(0);
});
- it('cancels unread HTTP error bodies before retrying', async () => {
- let time = 0;
- const cancel = vi.fn(async () => {});
- await expect(downloadSunoAudio(NEW_A, {
- fetchImpl: async () => ({ ok: false, status: 503, body: { cancel } }),
- now: () => time, sleep: async (ms) => { time += ms; }, timeoutMs: 25, intervalMs: 10,
- })).rejects.toMatchObject({ code: 'SUNO_AUDIO_TIMEOUT', context: { httpStatus: 503 } });
- expect(cancel).toHaveBeenCalledTimes(3);
+ it('allows generation readiness to take longer than the ordinary browser step timeout', async () => {
+ vi.useFakeTimers();
+ const w = workflow({ readyAfterMs: 90_000 });
+ const result = generateSunoSong(fields, { ...w, songIds: [NEW_A] });
+ await vi.waitFor(() => expect(w.actions).toContain('Download'));
+ await vi.advanceTimersByTimeAsync(90_000);
+ await expect(result).resolves.toMatchObject({ filename: 'music-example.m4a' });
+ expect(w.actions.filter(x => x === 'export')).toHaveLength(1);
+ expect(vi.getTimerCount()).toBe(0);
});
- it('never imports stable, decodable audio while generation is pending', async () => {
- let time = 0;
- const importAudio = vi.fn();
- await expect(generateSunoSong({}, {
- ...completed, checkCompletion: async () => 'pending', songIds: [NEW_A], importAudio,
- fetchImpl: async () => body(200 * 1024), now: () => time,
- sleep: async (ms) => { time += ms; }, timeoutMs: 25, intervalMs: 10,
- })).rejects.toMatchObject({ code: 'SUNO_AUDIO_TIMEOUT', context: { reason: 'generation_pending' } });
- expect(importAudio).not.toHaveBeenCalled();
+ it('rejects a completed HTML response even when its body is song-sized', async () => {
+ const w = workflow({ bytes: Buffer.from('<html>' + 'error'.repeat(30000)) });
+ await expect(generateSunoSong(fields, { ...w, songIds: [NEW_A] })).rejects.toMatchObject({ code: 'SUNO_AUDIO_INVALID' });
+ expect(w.importAudio).not.toHaveBeenCalled();
+ expect(decode).not.toHaveBeenCalled();
+ await expect(stat(w.savedPath())).rejects.toMatchObject({ code: 'ENOENT' });
});
- it('imports bytes fetched after completion rather than certifying an earlier partial body', async () => {
- let checks = 0;
- let complete = false;
- const partial = Buffer.alloc(200 * 1024, 1);
- const finished = Buffer.alloc(200 * 1024, 2);
- const importAudio = vi.fn(async () => ({ filename: 'finished.mp3', sizeBytes: finished.length }));
- await generateSunoSong({}, {
- songIds: [NEW_A], importAudio, validateAudio: completed.validateAudio, sleep: noSleep,
- checkCompletion: async () => { complete = ++checks >= 2; return complete ? 'complete' : 'pending'; },
- fetchImpl: async () => new Response(complete ? finished : partial),
- });
- expect(importAudio).toHaveBeenCalledWith(finished);
+ it('rejects a successful decoder without positive audio frame evidence', async () => {
+ const w = workflow();
+ decode.mockResolvedValueOnce({ stdout: 'out_time_us=0\nprogress=end\n' });
+ await expect(generateSunoSong(fields, { ...w, songIds: [NEW_A] })).rejects.toMatchObject({ code: 'SUNO_AUDIO_INVALID' });
+ expect(w.importAudio).not.toHaveBeenCalled();
});
- it('preserves unknown completion explicitly and never resubmits on retry', async () => {
- const connect = vi.fn();
- const importAudio = vi.fn();
- for (let attempt = 0; attempt < 2; attempt += 1) {
- await expect(generateSunoSong({}, {
- songIds: [NEW_A], connect, importAudio, validateAudio: completed.validateAudio,
- fetchImpl: async () => body(200 * 1024), sleep: noSleep,
- })).rejects.toMatchObject({ code: 'SUNO_AUDIO_COMPLETION_UNVERIFIED' });
- }
- expect(connect).not.toHaveBeenCalled();
- expect(importAudio).not.toHaveBeenCalled();
+ it('reports unavailable validation without importing when ffmpeg is absent', async () => {
+ const w = workflow();
+ findFfmpeg.mockResolvedValueOnce(null);
+ await expect(generateSunoSong(fields, { ...w, songIds: [NEW_A] })).rejects.toMatchObject({ status: 503, code: 'SUNO_AUDIO_VALIDATION_UNAVAILABLE' });
+ expect(w.importAudio).not.toHaveBeenCalled();
+ expect(decode).not.toHaveBeenCalled();
});
- it('rejects large HTML responses and cancels unread content without importing', async () => {
- const importAudio = vi.fn();
- const cancel = vi.fn(async () => {});
- const arrayBuffer = vi.fn(async () => Buffer.alloc(200 * 1024, '<'));
- const error = await generateSunoSong({}, {
- ...completed, songIds: [NEW_A], importAudio,
- fetchImpl: async () => ({ ok: true, status: 200, headers: new Headers({ 'content-type': 'text/html' }), arrayBuffer, body: { cancel } }),
- }).catch(error => error);
- expect(error).toMatchObject({ code: 'SUNO_AUDIO_INVALID', context: { reason: 'non_audio_content' } });
- expect(importAudio).not.toHaveBeenCalled();
- expect(arrayBuffer).not.toHaveBeenCalled();
- expect(cancel).toHaveBeenCalledOnce();
- expect(JSON.stringify({ message: error.message, context: error.context })).not.toContain(NEW_A);
+ it('cancels a pending save, removes listeners and staging files, and never imports', async () => {
+ const w = workflow({ stalled: 'save' });
+ const controller = new AbortController();
+ const result = generateSunoSong(fields, { ...w, songIds: [NEW_A], signal: controller.signal });
+ const assertion = expect(result).rejects.toMatchObject({ code: 'SUNO_AUDIO_CANCELLED' });
+ await vi.waitFor(() => expect(w.download.saveAs).toHaveBeenCalled());
+ controller.abort();
+ await assertion;
+ expect(w.download.cancel).toHaveBeenCalled();
+ expect(w.importAudio).not.toHaveBeenCalled();
+ expect(w.page.listenerCount('download')).toBe(0);
+ await expect(stat(w.savedPath())).rejects.toMatchObject({ code: 'ENOENT' });
});
-});
-
-describe('generateSunoSong', () => {
- const fields = { title: 't', style: 's', lyrics: 'l', instrumental: false };
- const audio = { ok: true, arrayBuffer: async () => new ArrayBuffer(200 * 1024) };
- const connect = async () => ({ browser: { close: async () => {} }, context: { newPage: async () => fakePage() } });
-
- it('submits once, downloads the first take and imports it', async () => {
- const importAudio = vi.fn(async () => ({ filename: 'music-x.mp3', sizeBytes: 204800 }));
- const onSubmitted = vi.fn();
- const out = await generateSunoSong(fields, { ...completed, connect, importAudio, onSubmitted, fetchImpl: async () => audio, sleep: noSleep, intervalMs: 0 });
- expect(out).toMatchObject({ songId: NEW_A, songIds: [NEW_A, NEW_B], filename: 'music-x.mp3' });
- expect(onSubmitted).toHaveBeenCalledWith([NEW_A, NEW_B]);
+ it('fails closed before unlock when the format selection no longer works', async () => {
+ const w = workflow({ ignoreSelection: true });
+ await expect(generateSunoSong(fields, { ...w, songIds: [NEW_A] })).rejects.toMatchObject({ context: { reason: 'format-selection-failed' } });
+ expect(w.actions).not.toContain('export');
+ expect(w.importAudio).not.toHaveBeenCalled();
});
- it('with songs already submitted, never opens the browser — a retry spends no new credits', async () => {
- const connectSpy = vi.fn(connect);
- const out = await generateSunoSong(fields, {
- ...completed, connect: connectSpy, importAudio: async () => ({ filename: 'm.mp3', sizeBytes: 1 }), songIds: [NEW_B],
- fetchImpl: async () => audio, sleep: noSleep, intervalMs: 0,
- });
- expect(connectSpy).not.toHaveBeenCalled();
- expect(out.songId).toBe(NEW_B);
+ it('rejects truncated audio even when its container metadata remains readable', async () => {
+ const w = workflow();
+ decode.mockRejectedValueOnce(new Error('private decoder output <user-home>/example.m4a'));
+ await expect(generateSunoSong(fields, { ...w, songIds: [NEW_A] })).rejects.toMatchObject({ code: 'SUNO_AUDIO_INVALID' });
+ expect(w.importAudio).not.toHaveBeenCalled();
});
-});
-// Real decoder contract: synthetic PCM WAV avoids network calls and credits.
-describe.skipIf(!ffmpegAvailable)('Suno audio decoding', () => {
- function wav() {
- const frames = 96_000;
- const bytes = Buffer.alloc(44 + frames * 2);
- bytes.write('RIFF'); bytes.writeUInt32LE(bytes.length - 8, 4); bytes.write('WAVEfmt ', 8);
- bytes.writeUInt32LE(16, 16); bytes.writeUInt16LE(1, 20); bytes.writeUInt16LE(1, 22);
- bytes.writeUInt32LE(48_000, 24); bytes.writeUInt32LE(96_000, 28);
- bytes.writeUInt16LE(2, 32); bytes.writeUInt16LE(16, 34);
- bytes.write('data', 36); bytes.writeUInt32LE(frames * 2, 40);
- for (let i = 0; i < frames; i++) bytes.writeInt16LE(Math.round(8000 * Math.sin(i * Math.PI / 60)), 44 + i * 2);
- return bytes;
- }
+ it('finishes a timed-out export even when both browser close calls stall', async () => {
+ vi.useFakeTimers();
+ const w = workflow({ stalled: 'event' });
+ w.page.close.mockImplementation(() => new Promise(() => {}));
+ w.browser.close.mockImplementation(() => new Promise(() => {}));
+ const result = generateSunoSong(fields, { ...w, songIds: [NEW_A], timeoutMs: 1000 });
+ const assertion = expect(result).rejects.toMatchObject({ code: 'SUNO_AUDIO_TIMEOUT' });
+ await vi.waitFor(() => expect(w.actions).toContain('export'));
+ await vi.advanceTimersByTimeAsync(2000);
+ await assertion;
+ expect(w.page.listenerCount('download')).toBe(0);
+ expect(w.importAudio).not.toHaveBeenCalled();
+ expect(w.actions.filter(x => x === 'export')).toHaveLength(1);
+ expect(vi.getTimerCount()).toBe(0);
+ });
- it.each(['valid', 'malformed', 'disguised-html'])('validates %s bytes before import and removes temporary artifacts', async (kind) => {
- const bytes = kind === 'valid' ? wav() : Buffer.alloc(200 * 1024, kind === 'malformed' ? 0 : '<html>private-body');
- const importAudio = vi.fn(async () => ({ filename: 'test.mp3', sizeBytes: bytes.length }));
- const firstTemp = mkdtemp.mock.results.length;
- const result = generateSunoSong({}, {
- songIds: [NEW_A], importAudio, checkCompletion: async () => 'complete',
- fetchImpl: async () => new Response(bytes, { headers: { 'content-type': 'audio/mpeg' } }), sleep: noSleep,
- });
- if (kind === 'valid') {
- await expect(result).resolves.toMatchObject({ filename: 'test.mp3' });
- expect(importAudio).toHaveBeenCalledWith(bytes);
- } else {
- const error = await result.catch(error => error);
- expect(error).toMatchObject({ code: 'SUNO_AUDIO_INVALID', context: { reason: 'decode_failed' } });
- expect(JSON.stringify({ message: error.message, context: error.context })).not.toMatch(/private-body|candidate|portos-suno-validation/);
- expect(importAudio).not.toHaveBeenCalled();
- }
- const temps = mkdtemp.mock.results.slice(firstTemp);
- expect(temps).toHaveLength(1);
- for (const temp of temps) await expect(access(await temp.value)).rejects.toMatchObject({ code: 'ENOENT' });
+ it('reports fixed browser failure metadata without private download details', async () => {
+ const w = workflow({ failure: 'failed https://example.com/?token=example-secret <user-home>/downloads' });
+ const error = await generateSunoSong(fields, { ...w, songIds: [NEW_A] }).catch(err => err);
+ expect(error).toMatchObject({ code: 'SUNO_AUDIO_DOWNLOAD_FAILED', context: { stage: 'check-download', reason: 'browser-download-failed' } });
+ expect(JSON.stringify({ message: error.message, context: error.context })).not.toMatch(/example-secret|https:|user-home/);
+ expect(w.importAudio).not.toHaveBeenCalled();
});
});