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
Suno import: keep a song's excluded styles, and re-read them for older imports
Claudea3c46b8bb975
diff --git a/client/src/components/musicVideo/stages/CastSetsStage.jsx b/client/src/components/musicVideo/stages/CastSetsStage.jsxindex 620053b757..f41e69350c 100644--- a/client/src/components/musicVideo/stages/CastSetsStage.jsx+++ b/client/src/components/musicVideo/stages/CastSetsStage.jsx@@ -5,6 +5,7 @@ import CreativeSetupPanel from '../CreativeSetupPanel.jsx';import LookReferencesPanel from '../LookReferencesPanel.jsx';import VisualSpecPanel from '../VisualSpecPanel.jsx';import AutoSizeTextarea from '../../ui/AutoSizeTextarea';+import { useState } from 'react';import { formatCount } from '../../../utils/formatters.js';const directionSummary = (project) => {@@ -20,9 +21,37 @@ const directionSummary = (project) => {].join(' · ');};+/** Re-read the song style from its Suno link, for a song imported before excluded styles were kept. */+function SongStyleFromSuno({ onRead, disabled }) {+ const [open, setOpen] = useState(false);+ const [url, setUrl] = useState('');+ const [reading, setReading] = useState(false);+ if (!open) {+ return (+ <button type="button" disabled={disabled} onClick={() => setOpen(true)}+ className="text-xs text-port-accent hover:underline disabled:opacity-50">Read from Suno</button>+ );+ }+ const read = () => {+ setReading(true);+ onRead(url.trim()).then((ok) => { setReading(false); if (ok) { setOpen(false); setUrl(''); } });+ };+ return (+ <div className="flex min-w-0 basis-full flex-wrap items-center gap-2">+ <label htmlFor="mv-song-style-suno" className="sr-only">Suno song link</label>+ <input id="mv-song-style-suno" type="url" value={url} onChange={(e) => setUrl(e.target.value)}+ placeholder="https://suno.com/song/…"+ className="min-w-0 flex-1 rounded border border-port-border bg-port-bg px-2 py-1 text-sm" />+ <button type="button" disabled={disabled || reading || !url.trim()} onClick={read}+ className="rounded bg-port-accent px-3 py-1 text-xs text-white disabled:opacity-50">{reading ? 'Reading…' : 'Read'}</button>+ <button type="button" onClick={() => setOpen(false)} className="text-xs text-port-text-muted hover:underline">Cancel</button>+ </div>+ );+}+/** Concept, style, universe and look references: what the cast and sets are built from. */function CreativeDirection({ board }) {- const { project, locked, conceptDraft, styleDraft, songStyleDraft } = board;+ const { project, locked, conceptDraft, styleDraft, songStyleDraft, songStyleFromSuno } = board;return (<><CreativeSetupPanel@@ -64,7 +93,10 @@ function CreativeDirection({ board }) {</div>{songStyleDraft && (<div className="sm:col-span-2">- <label htmlFor="mv-song-style" className="mb-1 block text-xs text-port-text-muted">Song style</label>+ <div className="mb-1 flex flex-wrap items-center justify-between gap-2">+ <label htmlFor="mv-song-style" className="block text-xs text-port-text-muted">Song style</label>+ {songStyleFromSuno && <SongStyleFromSuno onRead={songStyleFromSuno} disabled={locked} />}+ </div><AutoSizeTextareaid="mv-song-style"value={songStyleDraft.value}diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex cca72a422f..1eeb60e72a 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -29,6 +29,7 @@ import {reorderMusicVideoScenes,importMusicVideoLyrics,importMusicVideoTrackLyrics,+ refreshMusicVideoSongStyleFromSuno,getMusicVideoActiveJobs,getMusicVideoProject,} from '../services/apiMusicVideo.js';@@ -863,6 +864,16 @@ export default function MusicVideo() {// onto the NEW project via commitConcept's captured `selected`. Discard// (never auto-commit) any pending edit the instant the selection changes.useEffect(() => { conceptDraft.reset(); styleDraft.reset(); songStyleDraft.reset(); }, [selectedId]);+ // Re-read the song style (with its excluded styles) from the song's Suno link.+ const songStyleFromSuno = (url) => refreshMusicVideoSongStyleFromSuno(selected.id, url, { silent: true })+ .then(({ project, excludedStylesKnown }) => {+ songStyleDraft.reset();+ replaceProject(project);+ if (excludedStylesKnown) toast.success('Song style read from Suno');+ else toast.warning('Read the style, but Suno only shows excluded styles when the PortOS Browser is signed in to Suno');+ return true;+ })+ .catch((err) => { toast.error(err?.message || 'Could not read the song style from Suno'); return false; });// BeatTimeline drag commit — same optimistic-local + silent-PATCH pattern as// the other scene field editors (#1854).const commitSceneTiming = (sceneId, patch) => {@@ -1168,6 +1179,7 @@ export default function MusicVideo() {conceptDraft,styleDraft,songStyleDraft,+ songStyleFromSuno,importingLyrics,aligningLyrics,alignStatus,diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 570224f5d2..1a226f5947 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -83,6 +83,12 @@ export const importMusicVideoTrackLyrics = (id, body = {}, options = {}) => requmethod: 'POST', body: JSON.stringify(body), ...options,});+// Re-read the song's Suno style (excluded styles included) from its song link.+// Resolves to { project, excludedStylesKnown }; also updates the linked track.+export const refreshMusicVideoSongStyleFromSuno = (id, url, options = {}) => request(`/music-video/${encodeURIComponent(id)}/song-style/suno`, {+ method: 'POST', body: JSON.stringify({ url }), ...options,+});+// Align director lyric lines to the vocal (#9074). Body `{}` aligns every line;// `{ cueId }` re-aligns one line. Kickoff resolves to { jobId, reused? } (#10155):// stages stream over SSE and the terminal `complete` frame carries the updateddiff --git a/server/lib/README.md b/server/lib/README.mdindex 91258b9d4c..5483406bea 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -681,7 +681,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`, `sunoCdnVideoUrl` (the public fallback when Suno withholds the audio file), and `parseSunoSongPage(html, songId)` → `{ title, lyrics, style, audioUrl (CDN media only), 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. |+| `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`, `sunoCdnVideoUrl` (the public fallback when Suno withholds the audio file), and `parseSunoSongPage(html, songId)` → `{ title, lyrics, style (excluded styles folded in as minus terms), excludedStylesKnown, audioUrl (CDN media only), 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, and `DISTROKID_REMEMBERED_OPTIONS` (the release answers kept in settings and refilled on every project). 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/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 4ce12ba7ce..c43979098d 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -85,6 +85,9 @@ export const MUSIC_VIDEO_MODES = ['director', 'autonomous'];// (or `failed`). `analyzed` marks "beat map cached but not yet arranged".export const MUSIC_VIDEO_STATUSES = ['draft', 'analyzed', 'ready', 'rendering', 'complete', 'failed'];+// Re-read a project's song style from its Suno song link.+export const musicVideoSongStyleSunoSchema = z.object({ url: z.string().trim().min(1).max(2000) });+// Optional global visual direction for the whole video.export const musicVideoConceptSchema = z.object({prompt: z.string().max(8000).optional(),diff --git a/server/lib/sunoSong.js b/server/lib/sunoSong.jsindex f0a8eeb15a..2f71cab7e3 100644--- a/server/lib/sunoSong.js+++ b/server/lib/sunoSong.js@@ -167,6 +167,9 @@ export function parseSunoSongPage(html, songId) {title,lyrics: text(song.metadata?.prompt),style: withExcludedStyles(text(song.metadata?.tags), text(song.metadata?.negative_tags)),+ // Whether the page said anything about excluded styles. An anonymous page+ // can leave the field out, which is not the same as a song excluding none.+ excludedStylesKnown: typeof song.metadata?.negative_tags === 'string',audioUrl,imageUrl,};diff --git a/server/lib/sunoSong.test.js b/server/lib/sunoSong.test.jsindex b5fc6d3424..b1b65178b6 100644--- a/server/lib/sunoSong.test.js+++ b/server/lib/sunoSong.test.js@@ -47,7 +47,7 @@ describe('parseSunoSongPage', () => {expect(parseSunoSongPage(html, ID)).toEqual({title: 'You Are the Room',lyrics,- style: 'industrial, glitch',+ style: 'industrial, glitch', excludedStylesKnown: false,audioUrl: `https://cdn1.suno.ai/${ID}.mp3`,imageUrl: `https://cdn2.suno.ai/image_large_${ID}.jpeg`,});@@ -56,7 +56,7 @@ describe('parseSunoSongPage', () => {it('folds Suno\'s excluded styles into the style as minus terms, once each', () => {const metadata = { prompt: 'words', tags: 'synth-pop, \u2011bubblegum pop', negative_tags: 'Bubblegum Pop, metal' };const html = page([`4:${JSON.stringify({ song: { id: ID, title: 'Full', metadata } })}\n`]);- expect(parseSunoSongPage(html, ID).style).toBe('synth-pop, \u2011bubblegum pop, -metal');+ expect(parseSunoSongPage(html, ID)).toMatchObject({ style: 'synth-pop, \u2011bubblegum pop, -metal', excludedStylesKnown: true });});it('prefers the full record over a slimmer listing of the same song', () => {@@ -73,11 +73,11 @@ describe('parseSunoSongPage', () => {const head = '<meta property="og:title" content="Rock & 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,+ title: 'Rock & Roll', lyrics: '', style: '', excludedStylesKnown: false, 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 });+ expect(parseSunoSongPage('<html>Just a moment…</html>', ID)).toEqual({ title: '', lyrics: '', style: '', excludedStylesKnown: false, audioUrl: null, imageUrl: null });});});diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex a098be1dc3..4f22dc22d9 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -12,7 +12,7 @@ import { existsSync } from 'fs';import { unlink } from 'fs/promises';import { pipeline } from 'stream/promises';import { Router } from 'express';-import { musicVideoProjectListQuerySchema, musicVideoFinishedOutsideSchema, musicVideoProductionDraftSchema, musicVideoProductionApprovalSchema, musicVideoProductionProofSchema, musicVideoProductionImportSchema, musicVideoProductionFeedbackSchema, musicVideoProductionFeedbackResolutionSchema, musicVideoProductionReviseSchema, musicVideoProductionRevertSchema } from '../lib/musicVideoValidation.js';+import { musicVideoSongStyleSunoSchema, musicVideoProjectListQuerySchema, musicVideoFinishedOutsideSchema, musicVideoProductionDraftSchema, musicVideoProductionApprovalSchema, musicVideoProductionProofSchema, musicVideoProductionImportSchema, musicVideoProductionFeedbackSchema, musicVideoProductionFeedbackResolutionSchema, musicVideoProductionReviseSchema, musicVideoProductionRevertSchema } from '../lib/musicVideoValidation.js';import { productionReadiness } from '../services/musicVideo/productionReview.js';import { finishedOutsideBlocker } from '../lib/musicVideoFinishedOutside.js';import { getProductionReview, saveProductionDraft, prepareProductionReview, approveProductionReview, renderProductionProof, requireProductionReviewer, importProductionPlanning, bindProductionShot, addProductionFeedback, closeProductionFeedback, reviseProductionFromFeedback, revertProductionInput } from '../services/musicVideo/productionReviewService.js';@@ -115,6 +115,7 @@ import {appendTakesAcrossScenes,selectSceneTake,reviewSceneTake,+ refreshSongStyleFromSuno,} from '../services/musicVideo/projects.js';import { buildHandoffManifest, buildHandoffBundle, matchSceneByFileTag } from '../services/musicVideo/handoff.js';import { getHistoryItem } from '../services/videoGen/history.js';@@ -540,6 +541,13 @@ router.post('/:id/lyrics/align', asyncHandler(async (req, res) => {res.status(202).json(await startLyricAlign(req.params.id, { cueId, separateVocals, retimeSong }));}));+// Re-read the song's Suno style (excluded styles included) from its song link,+// for a song imported before they were captured. Updates the linked track too.+router.post('/:id/song-style/suno', asyncHandler(async (req, res) => {+ const { url } = validateRequest(musicVideoSongStyleSunoSchema, req.body ?? {});+ res.json(await refreshSongStyleFromSuno(req.params.id, url));+}));+// After a track is attached or lyrics are imported (the director's own action),// analyze the song if it has no analysis and start word alignment when the// lines were never aligned. Returns the project and the alignment job to follow.diff --git a/server/services/musicVideo/autonomousSuno.js b/server/services/musicVideo/autonomousSuno.jsindex 1cef991c06..6f4190a34f 100644--- a/server/services/musicVideo/autonomousSuno.js+++ b/server/services/musicVideo/autonomousSuno.js@@ -459,4 +459,26 @@ export async function generateSunoSong(fields, deps = {}) {}}+/**+ * Read a song's page in the signed-in PortOS Browser, where Suno shows the+ * owner everything it records about the song (its excluded styles among them).+ * Resolves the page HTML; rejects when the browser is unavailable or signed out.+ */+export async function readSunoSongPage(songId, deps = {}) {+ const connect = deps.connect || connectPortosBrowser;+ return serialize(async () => {+ deps.signal?.throwIfAborted();+ const { browser, context } = await connect();+ let page;+ try {+ page = await context.newPage();+ await page.goto(sunoSongUrl(songId), { waitUntil: 'domcontentloaded', timeout: T });+ if (/sign-?in|login|accounts\./i.test(page.url())) throw loginRequired(LABEL, SUNO_CREATE_URL);+ return await page.content();+ } finally {+ await closeSunoBrowser(page, browser);+ }+ });+}+export const __testing = { submitSunoSong, downloadSunoAudio };diff --git a/server/services/musicVideo/projects.js b/server/services/musicVideo/projects.jsindex 8dc6f75cdc..84c020b054 100644--- a/server/services/musicVideo/projects.js+++ b/server/services/musicVideo/projects.js@@ -76,8 +76,9 @@ export async function listProjectIds(options = {}) {// clip render (an explicit `body.backend`), so a target/install video pin can// only take effect HERE, at record creation — the same explicit-body seeding// trap the universe batch form and sprites page picker hit on the image side.-import { getTrack } from '../tracks/index.js';+import { getTrack, updateTrack } from '../tracks/index.js';import { parseLyricCues } from './timedText.js';+import { ServerError } from '../../lib/errorHandler.js';// resolveVideoMode usability-gates the pin (a disabled grok pin seeds local);// an input that names a backend explicitly wins untouched.@@ -192,6 +193,21 @@ export async function updateProject(id, patch) {return next;}+/**+ * Re-read the song's style from its Suno link, excluded styles included, for a+ * song imported before they were captured. Sets the project's song style and+ * the linked track's style prompt, so later projects on the track get it too.+ */+export async function refreshSongStyleFromSuno(id, url) {+ const project = await getProject(id);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const { readSunoSongStyle } = await import('../trackSunoImport.js');+ const { style, excludedStylesKnown } = await readSunoSongStyle(url);+ if (project.trackId) await updateTrack(project.trackId, { prompt: style });+ const updated = await updateProject(id, { concept: { songStyle: style.slice(0, 2000) } });+ return { project: updated, excludedStylesKnown };+}+export async function deleteProject(id) {const result = await (await selectBackend()).deleteProject(id);// Soft-delete tombstone — push the deletion to subscribed peers immediately.diff --git a/server/services/musicVideo/projects.test.js b/server/services/musicVideo/projects.test.jsindex 4e75056068..20774b2fad 100644--- a/server/services/musicVideo/projects.test.js+++ b/server/services/musicVideo/projects.test.js@@ -33,7 +33,10 @@ const getSettings = vi.fn(async () => ({}));vi.mock('../settings.js', () => ({ getSettings: (...a) => getSettings(...a) }));const getTrack = vi.fn(async () => null);-vi.mock('../tracks/index.js', () => ({ getTrack: (...a) => getTrack(...a) }));+const updateTrack = vi.fn(async () => ({}));+vi.mock('../tracks/index.js', () => ({ getTrack: (...a) => getTrack(...a), updateTrack: (...a) => updateTrack(...a) }));+const readSunoSongStyle = vi.fn();+vi.mock('../trackSunoImport.js', () => ({ readSunoSongStyle: (...a) => readSunoSongStyle(...a) }));const projects = await import('./projects.js');@@ -223,3 +226,15 @@ describe('track metadata and lyrics auto-reading on create and update', () => {});});++describe('refreshSongStyleFromSuno', () => {+ it('sets the song style read from Suno on the project and its track, leaving the visual style alone', async () => {+ getTrack.mockResolvedValue({ id: 'track-1', title: 'Example', prompt: 'synth-pop' });+ const project = await projects.createProject({ trackId: 'track-1', concept: { style: 'soft analog glow' } });+ readSunoSongStyle.mockResolvedValue({ style: 'synth-pop, -metal', excludedStylesKnown: true });+ const { project: updated, excludedStylesKnown } = await projects.refreshSongStyleFromSuno(project.id, 'https://suno.com/song/x');+ expect(excludedStylesKnown).toBe(true);+ expect(updated.concept).toMatchObject({ style: 'soft analog glow', songStyle: 'synth-pop, -metal' });+ expect(updateTrack).toHaveBeenCalledWith('track-1', { prompt: 'synth-pop, -metal' });+ });+});diff --git a/server/services/trackSunoImport.js b/server/services/trackSunoImport.jsindex 185f0a2222..5be8dc2a7b 100644--- a/server/services/trackSunoImport.js+++ b/server/services/trackSunoImport.js@@ -74,7 +74,7 @@ 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 };+const limits = { browserWaitMs: 2 * 60 * 1000, styleReadMs: 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@@ -116,6 +116,59 @@ async function exportThroughBrowser(songId, outPath, signal) {return html;}+// Read the song's page the way an anonymous visitor sees it; null when Suno won't serve it.+const fetchSongPage = (songId) => fetchPublicText(`https://suno.com/song/${songId}`, {+ timeoutMs: PAGE_TIMEOUT_MS, headers: HEADERS, maxBytes: PAGE_MAX_BYTES, throwOnUnsafe: false,+}).catch(() => null);++// Prefer the signed-in page's style when it states the excluded styles.+const mergeStyle = (song, signedIn) => (signedIn.excludedStylesKnown+ ? signedIn.style || song.style : song.style || signedIn.style);++/**+ * Fill in what the anonymous page left out about a song's style. Suno keeps a+ * song's excluded styles out of the page it serves to anonymous visitors, so+ * when the page says nothing about them the signed-in PortOS Browser reads the+ * owner's view. Best effort: a signed-out or busy browser keeps the anonymous+ * style.+ */+async function withSignedInStyle(song, songId, signal) {+ if (song.excludedStylesKnown) return song;+ const abort = new AbortController();+ const stop = () => abort.abort();+ signal?.addEventListener('abort', stop, { once: true });+ const timer = setTimeout(stop, limits.styleReadMs);+ try {+ const { readSunoSongPage } = await import('./musicVideo/autonomousSuno.js');+ const read = readSunoSongPage(songId, { signal: abort.signal });+ read.catch(() => {});+ const html = await Promise.race([read, new Promise((_, reject) => {+ abort.signal.addEventListener('abort', () => reject(new Error('the PortOS Browser did not read the song page in time')), { once: true });+ })]);+ const signedIn = parseSunoSongPage(html, songId);+ return { ...song, style: mergeStyle(song, signedIn), excludedStylesKnown: signedIn.excludedStylesKnown };+ } catch (err) {+ console.warn(`⚠️ Suno style ${songId.slice(0, 8)}: kept the public style (${err?.message || err})`);+ return song;+ } finally {+ clearTimeout(timer);+ signal?.removeEventListener('abort', stop);+ }+}++/**+ * The full Suno style of a song link, excluded styles included, for refreshing+ * a song that was imported before they were captured. Throws 400 for a link+ * that isn't a Suno song and 404 when Suno shows no style for it.+ */+export async function readSunoSongStyle(url) {+ if (!isSunoSongUrl(url)) throw new ServerError(SUNO_URL_INVALID_MESSAGE, { status: 400, code: 'SUNO_URL_INVALID' });+ const songId = await resolveSunoSongId(url.trim());+ const song = await withSignedInStyle(parseSunoSongPage(await fetchSongPage(songId) || '', songId), songId);+ if (!song.style) throw new ServerError('Suno shows no style for that song', { status: 404, code: 'SUNO_STYLE_NOT_FOUND' });+ return { style: song.style, excludedStylesKnown: song.excludedStylesKnown };+}+// 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) {@@ -170,9 +223,7 @@ export async function startSunoImport(url) {broadcastSse(job, { type: 'progress', percent: 5, stage: 'reading' });const songId = await resolveSunoSongId(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 html = await fetchSongPage(songId);if (abortIfCanceled()) return;broadcastSse(job, { type: 'progress', percent: 20, stage: 'downloading' });@@ -201,7 +252,9 @@ export async function startSunoImport(url) {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 };+ // The signed-in page is the owner's full view: nothing more to read after it.+ song = { ...song, title: song.title || signedIn.title, lyrics: song.lyrics || signedIn.lyrics,+ style: mergeStyle(song, signedIn), excludedStylesKnown: song.excludedStylesKnown || Boolean(signedIn.title || signedIn.style) };};const routes = song.title ? [viaVideo, viaBrowser] : [viaBrowser, viaVideo];const failures = [];@@ -217,6 +270,9 @@ export async function startSunoImport(url) {}}+ // The audio came without the signed-in page: read it for the excluded styles.+ song = await withSignedInStyle(song, songId, job.abort.signal);+ if (abortIfCanceled()) return;broadcastSse(job, { type: 'progress', percent: 90, stage: 'importing' });const title = song.title || 'Suno song';const ext = tempPath.endsWith('.m4a') ? 'm4a' : 'mp3';diff --git a/server/services/trackSunoImport.test.js b/server/services/trackSunoImport.test.jsindex dc3b69b6d3..e76e1fe729 100644--- a/server/services/trackSunoImport.test.js+++ b/server/services/trackSunoImport.test.js@@ -11,16 +11,16 @@ vi.mock('./pipeline/musicLibrary.js', () => ({}));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('./musicVideo/autonomousSuno.js', () => ({ generateSunoSong: vi.fn() }));+vi.mock('./musicVideo/autonomousSuno.js', () => ({ generateSunoSong: vi.fn(), readSunoSongPage: vi.fn() }));vi.mock('../lib/safeUrlFetch.js', () => ({ fetchPublicText: vi.fn(), fetchPublicBinary: vi.fn(), resolvePublicUrl: vi.fn() }));const { broadcastSse } = await import('../lib/sseUtils.js');const { probeVideoDuration, runFfmpegProcess } = await import('../lib/ffmpeg.js');const { fetchPublicText, fetchPublicBinary, resolvePublicUrl } = await import('../lib/safeUrlFetch.js');const { importUploadedTrack } = await import('./pipeline/musicLibrary.js');-const { generateSunoSong } = await import('./musicVideo/autonomousSuno.js');+const { generateSunoSong, readSunoSongPage } = await import('./musicVideo/autonomousSuno.js');const { createTrack } = await import('./tracks/index.js');-const { startSunoImport, cancelSunoImport, __testing } = await import('./trackSunoImport.js');+const { startSunoImport, cancelSunoImport, readSunoSongStyle, __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>`;@@ -47,6 +47,7 @@ beforeEach(() => {probeVideoDuration.mockResolvedValue(200);runFfmpegProcess.mockResolvedValue({ ok: true });generateSunoSong.mockRejectedValue(new Error('Sign in to Suno in the PortOS Browser'));+ readSunoSongPage.mockRejectedValue(new Error('Sign in to Suno in the PortOS Browser'));fetchPublicBinary.mockResolvedValue({ buffer: Buffer.from('ID3audio'), contentType: 'audio/mpeg' });});@@ -66,6 +67,27 @@ describe('startSunoImport', () => {}));});+ it('reads the excluded styles from the signed-in page when the public page leaves them out', async () => {+ fetchPublicText.mockResolvedValue(songPage({+ id: ID, title: 'Cutting', audio_url: `https://cdn1.suno.ai/${ID}.mp3`, metadata: { prompt: 'words', tags: 'synth-pop' },+ }));+ readSunoSongPage.mockResolvedValue(songPage({ id: ID, title: 'Cutting', metadata: { prompt: 'words', tags: 'synth-pop', negative_tags: 'metal, cutesy' } }));+ await startSunoImport(`https://suno.com/song/${ID}`);+ expect(await terminal()).toMatchObject({ type: 'complete' });+ expect(readSunoSongPage).toHaveBeenCalledWith(ID, expect.objectContaining({ signal: expect.any(AbortSignal) }));+ expect(createTrack).toHaveBeenCalledWith(expect.objectContaining({ prompt: 'synth-pop, -metal, -cutesy' }));+ });++ it('skips the signed-in read when the public page states the excluded styles', async () => {+ fetchPublicText.mockResolvedValue(songPage({+ id: ID, title: 'Cutting', audio_url: `https://cdn1.suno.ai/${ID}.mp3`, metadata: { tags: 'synth-pop', negative_tags: '' },+ }));+ await startSunoImport(`https://suno.com/song/${ID}`);+ expect(await terminal()).toMatchObject({ type: 'complete' });+ expect(readSunoSongPage).not.toHaveBeenCalled();+ expect(createTrack).toHaveBeenCalledWith(expect.objectContaining({ prompt: 'synth-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}`);@@ -235,3 +257,18 @@ describe('startSunoImport', () => {await expect(startSunoImport('https://example.com/song/x')).rejects.toMatchObject({ status: 400, code: 'SUNO_URL_INVALID' });});});++describe('readSunoSongStyle', () => {+ it('returns the full style of an earlier import, and keeps the public one when the browser is signed out', async () => {+ fetchPublicText.mockResolvedValue(songPage({ id: ID, title: 'Cutting', metadata: { tags: 'synth-pop' } }));+ readSunoSongPage.mockResolvedValueOnce(songPage({ id: ID, metadata: { tags: 'synth-pop', negative_tags: 'metal' } }));+ await expect(readSunoSongStyle(`https://suno.com/song/${ID}`)).resolves.toEqual({ style: 'synth-pop, -metal', excludedStylesKnown: true });+ await expect(readSunoSongStyle(`https://suno.com/song/${ID}`)).resolves.toEqual({ style: 'synth-pop', excludedStylesKnown: false });+ });++ it('refuses a link that is not a Suno song, or a song with no style', async () => {+ await expect(readSunoSongStyle('https://example.com/song/x')).rejects.toMatchObject({ status: 400 });+ fetchPublicText.mockResolvedValue(null);+ await expect(readSunoSongStyle(`https://suno.com/song/${ID}`)).rejects.toMatchObject({ status: 404 });+ });+});