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
DistroKid draft fills genre, language, store profiles and Apple credits
Claude10ae10553cbc
diff --git a/client/src/components/musicVideo/PublishPostingPanel.jsx b/client/src/components/musicVideo/PublishPostingPanel.jsxindex 7b9fd40bc5..f9baf9c53a 100644--- a/client/src/components/musicVideo/PublishPostingPanel.jsx+++ b/client/src/components/musicVideo/PublishPostingPanel.jsx@@ -2,6 +2,7 @@ import { useState } from 'react';import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';import { safeReadJsonStorage, safeWriteJsonStorage } from '../../lib/safeStorage.js';import { ExternalLink, X as XIcon, LogIn, Link as LinkIcon } from 'lucide-react';+import { DISTROKID_GENRES, suggestDistrokidGenres } from '../../../../server/lib/distrokidGenres.js';// Where the release goes, in posting order: the full video first so every// other post can link to it.@@ -22,8 +23,10 @@ export const PUBLISH_TARGETS = [},];-// The songwriter's legal name DistroKid asks for, remembered on this device only.+// The DistroKid answers the director gives once (songwriter legal name and+// role, language, store profiles, Apple performer role), remembered on this device only.const SONGWRITER_KEY = 'portos.musicVideo.distrokidSongwriter';+const DISTROKID_REMEMBERED = { songwriterFirst: 'first', songwriterLast: 'last', songwriterRole: 'role', language: 'language', newArtistProfile: 'newArtistProfile', performerRole: 'performerRole' };const inputCls = 'w-full bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs min-h-[44px] sm:min-h-0';@@ -109,6 +112,14 @@ function TargetOptions({ target, kit, project, options, setOption, flairs, idFor</label>);const hasLyrics = (project?.lyricCues || []).some((cue) => cue?.text?.trim());+ const instrumental = options.instrumental ?? !hasLyrics;+ const suggested = suggestDistrokidGenres(project);+ const fullName = [options.songwriterFirst, options.songwriterLast].map((v) => v?.trim()).filter(Boolean).join(' ') || 'Songwriter legal name';+ const genreSelect = (key, label, suggestion, noneLabel) => field(key, label,+ <select id={idFor(key)} value={options[key] || ''} onChange={(e) => setOption(key, e.target.value)} className={inputCls}>+ <option value="">{suggestion ? `${suggestion} (from the song's style)` : noneLabel}</option>+ {DISTROKID_GENRES.map((g) => <option key={g} value={g}>{g}</option>)}+ </select>);return (<div className="space-y-2"><div className="grid sm:grid-cols-2 gap-2">@@ -117,10 +128,25 @@ function TargetOptions({ target, kit, project, options, setOption, flairs, idFor<input id={idFor('releaseDate')} type="date" aria-label="Release date" value={options.releaseDate || ''} onChange={(e) => setOption('releaseDate', e.target.value)} className={inputCls} />)}{text('songwriterFirst', 'Songwriter legal first name', 'First')}{text('songwriterLast', 'Songwriter legal last name', 'Last')}+ {field('songwriterRole', 'Songwriter wrote',+ <select id={idFor('songwriterRole')} value={options.songwriterRole || (instrumental ? 'music' : 'both')} onChange={(e) => setOption('songwriterRole', e.target.value)} className={inputCls}>+ <option value="both">Music and lyrics</option>+ <option value="music">Music</option>+ <option value="lyrics">Lyrics</option>+ </select>)}+ {text('language', 'Language', 'English')}+ {genreSelect('genre', 'Genre', suggested.primary, 'Pick a genre')}+ {genreSelect('secondaryGenre', 'Secondary genre (optional)', suggested.secondary, 'None')}</div><div className="flex flex-wrap gap-x-4">{check('explicit', 'Explicit lyrics', false)}{check('instrumental', 'Instrumental', !hasLyrics)}+ {check('newArtistProfile', 'First release as this artist (new store profiles)', true)}+ </div>+ <div role="group" aria-label="Apple Music credits" className="grid sm:grid-cols-3 gap-2">+ {text('performerName', 'Apple performer (real name)', fullName)}+ {text('performerRole', 'Performer role (optional)', 'e.g. Vocals')}+ {text('producerName', 'Apple producer (real name)', fullName)}</div><div role="group" aria-label="Parts made with AI" className="flex flex-wrap gap-x-4"><span className="text-[11px] text-port-text-muted self-center">Made with AI:</span>@@ -199,8 +225,9 @@ function TargetRow({ project, kit, entry, publishing }) {}if (target === 'distrokid') {const saved = safeReadJsonStorage(SONGWRITER_KEY, {}) || {};+ const remembered = Object.fromEntries(Object.entries(DISTROKID_REMEMBERED).filter(([, k]) => saved[k] != null && saved[k] !== '').map(([opt, k]) => [opt, saved[k]]));// A song whose lyrics an LLM wrote in the autonomous run discloses AI lyrics by default.- return { songwriterFirst: saved.first || '', songwriterLast: saved.last || '', aiLyrics: !!project?.autonomousRun?.output?.lyrics };+ return { songwriterFirst: '', songwriterLast: '', ...remembered, aiLyrics: !!project?.autonomousRun?.output?.lyrics };}return {};});@@ -227,8 +254,10 @@ function TargetRow({ project, kit, entry, publishing }) {)}</div><button type="button" onClick={() => {- if (target === 'distrokid' && clean.songwriterFirst && clean.songwriterLast) safeWriteJsonStorage(SONGWRITER_KEY, { first: clean.songwriterFirst, last: clean.songwriterLast });- publishing.prepare(target, clean);+ if (target === 'distrokid' && clean.songwriterFirst && clean.songwriterLast) {+ safeWriteJsonStorage(SONGWRITER_KEY, Object.fromEntries(Object.entries(DISTROKID_REMEMBERED).filter(([opt]) => clean[opt] != null).map(([opt, k]) => [k, clean[opt]])));+ }+ publishing.prepare(target, target === 'distrokid' ? { newArtistProfile: true, ...clean } : clean);}} disabled={!!busy}className="flex items-center gap-1 bg-port-accent/20 text-port-accent disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0">{busy === 'prepare' ? 'Filling…' : (draft ? 'Fill again' : 'Fill draft')}diff --git a/client/src/components/musicVideo/PublishPostingPanel.test.jsx b/client/src/components/musicVideo/PublishPostingPanel.test.jsxindex e09411bdb4..0673d103fa 100644--- a/client/src/components/musicVideo/PublishPostingPanel.test.jsx+++ b/client/src/components/musicVideo/PublishPostingPanel.test.jsx@@ -61,12 +61,34 @@ describe('PublishPostingPanel (#9282)', () => {fireEvent.change(within(dk).getByLabelText('Songwriter legal last name'), { target: { value: 'Example' } });fireEvent.click(within(dk).getByLabelText('Explicit lyrics'));fireEvent.click(within(dk).getByRole('button', { name: 'Fill draft' }));- expect(publishing.prepare).toHaveBeenCalledWith('distrokid', { songwriterFirst: 'Alice', songwriterLast: 'Example', aiLyrics: true, explicit: true });+ expect(publishing.prepare).toHaveBeenCalledWith('distrokid', { songwriterFirst: 'Alice', songwriterLast: 'Example', aiLyrics: true, explicit: true, newArtistProfile: true });unmount();render(<PublishPostingPanel project={project()} publishing={hook()} />);expect(within(row('Spotify (via DistroKid)')).getByLabelText('Songwriter legal first name')).toHaveValue('Alice');});+ it('suggests a genre from the song and remembers the once-only DistroKid answers', () => {+ const publishing = hook({ platforms: { distrokid: { enabled: true, account: 'Example Artist' } } });+ const p = { ...project(), autonomousRun: { output: { sunoStyle: 'dark synthwave, pop hooks' } } };+ const { unmount } = render(<PublishPostingPanel project={p} publishing={publishing} />);+ const dk = row('Spotify (via DistroKid)');+ expect(within(dk).getByLabelText('Genre')).toHaveDisplayValue('Electronic (from the song\'s style)');+ expect(within(dk).getByLabelText('Secondary genre (optional)')).toHaveDisplayValue('Pop (from the song\'s style)');+ fireEvent.change(within(dk).getByLabelText('Songwriter legal first name'), { target: { value: 'Alice' } });+ fireEvent.change(within(dk).getByLabelText('Songwriter legal last name'), { target: { value: 'Example' } });+ fireEvent.change(within(dk).getByLabelText('Genre'), { target: { value: 'Rock' } });+ fireEvent.change(within(dk).getByLabelText('Language'), { target: { value: 'Spanish' } });+ fireEvent.click(within(dk).getByLabelText('First release as this artist (new store profiles)'));+ fireEvent.click(within(dk).getByRole('button', { name: 'Fill draft' }));+ expect(publishing.prepare).toHaveBeenCalledWith('distrokid', expect.objectContaining({ genre: 'Rock', language: 'Spanish', newArtistProfile: false }));+ unmount();+ render(<PublishPostingPanel project={project()} publishing={hook()} />);+ const again = row('Spotify (via DistroKid)');+ expect(within(again).getByLabelText('Language')).toHaveValue('Spanish');+ expect(within(again).getByLabelText('First release as this artist (new store profiles)')).not.toBeChecked();+ expect(within(again).getByLabelText('Genre')).toHaveValue('');+ });+it('shows no cut picker when there is only one 9:16 cut', () => {render(<PublishPostingPanel project={project()} publishing={hook()} />);expect(within(row('TikTok')).queryByLabelText('Vertical cut to post')).toBeNull();diff --git a/server/lib/README.md b/server/lib/README.mdindex fd50f6e4ba..3d324aef14 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -668,6 +668,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `asyncMutex.js` | Promise-based async mutex. || `concurrencyGate.js` | `createConcurrencyGate(limit)` → `run(fn)` — cap on simultaneous async work for ONE module-scoped budget, released FIFO. Sibling to `mapWithConcurrency.js`, which caps in-flight work *within one array map*; a gate is shared state, so several call sites fanning out at the same remote respect one budget instead of each respecting its own while the host sees the sum. `createMutex` (`asyncMutex.js`) is this with `limit` fixed at 1 — prefer it for mutual exclusion. Note the budget is per-MODULE, not per-host: two modules calling one host each get their own gate. Used by `huggingFaceMetadata.js` (4) and `ollamaRegistryCatalog.js` (16), whose cold catalog-enrichment bursts otherwise arrive at a free public API as a thundering herd — which the Hub answers with an HTTP/2 GOAWAY that surfaces as a bare `fetch failed`. || `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. |+| `distrokidGenres.js` | DistroKid's store genre list (`DISTROKID_GENRES`) and `suggestDistrokidGenres(project)`, a first primary/secondary genre guess from the song's own style words. Shared by the DistroKid publish payload and the publish panel's genre pickers. || `domainAutonomy.js` | Per-domain autonomy guardrails (pure). `AUTONOMY_DOMAINS`/`DOMAIN_IDS`/`DOMAIN_MODES` (`off`/`dry-run`/`execute`), `getDomainMode(config, id)`, and `normalizeDomainAutonomy(raw)` to coerce a hand-edited/partial map. Default per domain is `execute` (reproduces pre-#711 behavior, so no migration needed). Also `CREATIVE_DOMAIN`/`getCreativeAutonomyMode(config)` (#2183) — the Creative Director orchestrator domain, kept out of `DOMAIN_IDS` and defaulting to mirror the `cos` mode. || `domainBudgets.js` | Per-domain daily autonomy budgets (pure). `BUDGET_LIMIT_FIELDS` (`maxActionsPerDay`/`maxMinutesPerDay`), `getDomainBudget(config, id)`, `normalizeDomainBudgets(raw)`, `hasBudget(budget)`, and `evaluateBudget(budget, usage)` → `{ withinBudget, exceeded }`. A `null`/non-positive cap means unlimited (default per domain, so no migration needed). Token/$ caps are intentionally absent — CLI subscription providers expose no per-run metering. Usage ledger + gate wiring live in `services/domainUsage.js`. || `federationSafety.js` | "Does this JSON-shaped payload carry anything that must not leave the install?" — the structured, REFUSAL-side counterpart to the scrubbers (`secretText.js`, `homePath.js`) that rewrite text for a log. `federationSafetyFindings(value, { limit })` walks every string AND every object key, returning `{ code, path, detail }` for a home/Windows path, IPv4 or IPv6 literal, `.ts.net`/`.local` host, MAC, email, phone number, labelled GPS coordinate (the shared table is `piiRedactionPatterns.js`), credential-shaped value (`scrubSecretTokens`) or credential-NAMED key (`secretKeys.js#isSecretKey` — the half no value-shape scan can see). Deliberately over-refuses rather than under-detects: a payload leaving the machine should fail on "looks like an address", and the finding names the exact JSON path to fix. `walkJsonText` / `describeJsonPath` are the reusable path-reporting walk. Pure; reads no environment. |diff --git a/server/lib/distrokidGenres.js b/server/lib/distrokidGenres.jsnew file mode 100644index 0000000000..7f380e6767--- /dev/null+++ b/server/lib/distrokidGenres.js@@ -0,0 +1,63 @@+/**+ * DistroKid's store genres, and a first guess at a song's from its own style+ * words (the Suno style prompt and the musical description the autonomous run+ * wrote). Pure: project in, `{ primary, secondary }` out. The director can+ * always pick another; the adapter matches DistroKid's option by its text.+ */++export const DISTROKID_GENRES = Object.freeze([+ 'Alternative', 'Blues', "Children's Music", 'Classical', 'Comedy', 'Country', 'Dance', 'Electronic',+ 'Folk', 'Hip Hop/Rap', 'Holiday', 'Industrial', 'Instrumental', 'J-Pop', 'Jazz', 'K-Pop', 'Latin',+ 'Metal', 'New Age', 'Pop', 'Punk', 'R&B/Soul', 'Reggae', 'Rock', 'Singer/Songwriter', 'Soundtrack',+ 'Spoken Word', 'World',+]);++// Style words to a store genre. The earliest word in the song's style picks the+// primary genre, the next different genre the secondary.+const STYLE_WORDS = [+ [/\b(hip[\s-]?hop|rap|trap|boom[\s-]?bap|drill)\b/gi, 'Hip Hop/Rap'],+ [/\b(r&b|rnb|soul|neo[\s-]?soul|funk)\b/gi, 'R&B/Soul'],+ [/\b(industrial|ebm)\b/gi, 'Industrial'],+ [/\b(edm|house|techno|trance|dubstep|drum (?:and|&|n) bass|dnb|synthwave|electronic|electronica|electro|idm|glitch|downtempo|trip[\s-]?hop|ambient)\b/gi, 'Electronic'],+ [/\b(dance|disco)\b/gi, 'Dance'],+ [/\b(metal|metalcore|djent)\b/gi, 'Metal'],+ [/\b(punk|post[\s-]?punk|hardcore)\b/gi, 'Punk'],+ [/\b(indie|alternative|alt)\b/gi, 'Alternative'],+ [/\b(rock|grunge|shoegaze)\b/gi, 'Rock'],+ [/\b(folk|acoustic|americana)\b/gi, 'Folk'],+ [/\b(country|bluegrass)\b/gi, 'Country'],+ [/\b(jazz|swing|bebop)\b/gi, 'Jazz'],+ [/\b(blues)\b/gi, 'Blues'],+ [/\b(classical|orchestral|chamber|baroque)\b/gi, 'Classical'],+ [/\b(soundtrack|cinematic|film score|score)\b/gi, 'Soundtrack'],+ [/\b(reggae|dub|dancehall)\b/gi, 'Reggae'],+ [/\b(latin|reggaeton|salsa|bossa nova|cumbia)\b/gi, 'Latin'],+ [/\b(k[\s-]?pop)\b/gi, 'K-Pop'],+ [/\b(j[\s-]?pop)\b/gi, 'J-Pop'],+ [/\b(new age|meditation)\b/gi, 'New Age'],+ [/\b(spoken word|poetry)\b/gi, 'Spoken Word'],+ [/\b(singer[\s-]?songwriter)\b/gi, 'Singer/Songwriter'],+ [/\b(pop|synth[\s-]?pop|hyperpop)\b/gi, 'Pop'],+];++const styleText = (project) => {+ const out = project?.autonomousRun?.output || {};+ return [out.sunoStyle, out.musicalDescription, project?.concept?.genre].filter((s) => typeof s === 'string' && s.trim()).join(' \n ');+};++/** `{ primary, secondary }` store genres for the song, either null when its style names none. */+export function suggestDistrokidGenres(project) {+ const text = styleText(project);+ const hits = [];+ for (const [re, genre] of STYLE_WORDS) {+ // A "k-pop" or "j-pop" mention is not also a "pop" one.+ for (const m of text.matchAll(re)) {+ if (genre === 'Pop' && /[kj][\s-]?$/i.test(text.slice(Math.max(0, m.index - 2), m.index))) continue;+ hits.push({ at: m.index, genre });+ break;+ }+ }+ hits.sort((a, b) => a.at - b.at);+ const genres = [...new Set(hits.map((h) => h.genre))];+ return { primary: genres[0] || null, secondary: genres[1] || null };+}diff --git a/server/lib/distrokidGenres.test.js b/server/lib/distrokidGenres.test.jsnew file mode 100644index 0000000000..d9d012dd7e--- /dev/null+++ b/server/lib/distrokidGenres.test.js@@ -0,0 +1,19 @@+import { describe, it, expect } from 'vitest';+import { DISTROKID_GENRES, suggestDistrokidGenres } from './distrokidGenres.js';++const song = (sunoStyle, musicalDescription) => ({ autonomousRun: { output: { sunoStyle, musicalDescription } } });++describe('suggestDistrokidGenres', () => {+ it('orders genres by where the style names them, and only suggests store genres', () => {+ expect(suggestDistrokidGenres(song('indie rock, shoegaze guitars, dreamy'))).toEqual({ primary: 'Alternative', secondary: 'Rock' });+ expect(suggestDistrokidGenres(song('trap beat', 'A hip hop track with soul samples'))).toEqual({ primary: 'Hip Hop/Rap', secondary: 'R&B/Soul' });+ const { primary, secondary } = suggestDistrokidGenres(song('cinematic orchestral score'));+ expect([primary, secondary].every((g) => DISTROKID_GENRES.includes(g))).toBe(true);+ });++ it('does not read k-pop as pop, and suggests nothing for a song with no style words', () => {+ expect(suggestDistrokidGenres(song('k-pop anthem'))).toEqual({ primary: 'K-Pop', secondary: null });+ expect(suggestDistrokidGenres({})).toEqual({ primary: null, secondary: null });+ expect(suggestDistrokidGenres(song('slow, sad, whispered'))).toEqual({ primary: null, secondary: null });+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex e61936f7d4..deb47fa35a 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -643,6 +643,7 @@ export * from './assetRoutePrefixes.js';export * from './asyncMutex.js';export * from './concurrencyGate.js';export * from './dispatchLabels.js';+export * from './distrokidGenres.js';export * from './domainAutonomy.js';export * from './domainBudgets.js';export * from './eidoverseCreativeToolkit.js';diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 0033607ef8..53e7c30f04 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -742,6 +742,15 @@ export const musicVideoPublishPrepareSchema = z.object({aiLyrics: z.boolean(),aiMusic: z.boolean(),aiVocals: z.boolean(),+ genre: z.string().trim().min(1).max(60),+ secondaryGenre: z.string().trim().min(1).max(60),+ language: z.string().trim().min(1).max(60),+ songwriterRole: z.enum(['music', 'lyrics', 'both']),+ newArtistProfile: z.boolean(),+ performerName: z.string().trim().min(1).max(100),+ performerRole: z.string().trim().min(1).max(60),+ producerName: z.string().trim().min(1).max(100),+ previewStartSec: z.number().min(0).max(3600),}).partial().strict();export const musicVideoExcerptNoteSchema = z.object({diff --git a/server/services/musicVideo/publish/distrokid.js b/server/services/musicVideo/publish/distrokid.jsindex 14ed31e259..dae44e49b6 100644--- a/server/services/musicVideo/publish/distrokid.js+++ b/server/services/musicVideo/publish/distrokid.js@@ -2,10 +2,13 @@* DistroKid adapter: the song goes to Spotify (and the other stores DistroKid* delivers to) as a single. Spotify has no upload for independent artists, so* a distributor is the only route. prepare() fills DistroKid's upload form- * with the song's audio, a square cover, title, artist, songwriter, explicit- * and instrumental flags, the AI disclosure, and the release date. It never- * ticks the agreement boxes or presses Upload: those attest the director owns- * the rights, so they stay with the director.+ * with the song's audio, a square cover, title, artist, songwriter and role,+ * explicit and instrumental flags, the AI disclosure, genre, language, store+ * profiles, Apple Music credits, the preview start and the release date, and+ * unticks every paid extra. It never ticks the agreement boxes or presses+ * Upload: those attest the director owns the rights, so they stay with the+ * director. Per-track fields carry a random suffix per page load, so they are+ * matched by name prefix.** DistroKid restyles this form often, so every field is found by its name or* its label text, and a field that is no longer there is reported in the@@ -48,7 +51,90 @@ async function checkByLabel(page, selector, pattern) {}, [selector, pattern]);}-/** Answer DistroKid's AI question and tick the parts the director says AI made. */+/** Set every checkbox matching `selector` to `on`; false when there is none. */+async function setChecked(page, selector, on) {+ return page.evaluate(([sel, want]) => {+ const boxes = [...document.querySelectorAll(sel)].filter((b) => b.type !== 'hidden');+ for (const b of boxes) if (b.checked !== want) b.click();+ return boxes.length > 0;+ }, [selector, on]);+}++/**+ * Answer a radio question: inside the smallest block whose text matches+ * `question` and that holds radios, click the radio labelled `answer`.+ */+async function answerQuestion(page, question, answer) {+ return page.evaluate(([qSrc, aSrc]) => {+ const q = new RegExp(qSrc, 'i');+ const a = new RegExp(aSrc, 'i');+ const labelOf = (r) => (r.closest('label')?.innerText || r.parentElement?.innerText || r.value || '').replace(/\s+/g, ' ').trim();+ const blocks = [...document.querySelectorAll('div, fieldset, section, tr, li')]+ .filter((el) => q.test(el.innerText || '') && el.querySelector('input[type=radio]'))+ .sort((x, y) => (x.innerText || '').length - (y.innerText || '').length);+ for (const block of blocks) {+ const radio = [...block.querySelectorAll('input[type=radio]')].find((r) => a.test(labelOf(r)));+ if (radio) { if (!radio.checked) radio.click(); return true; }+ }+ return false;+ }, [question, answer]);+}++/** Pick "new profile" on every store-profile question (Spotify, Apple, YouTube Music, Instagram, Facebook). */+async function newStoreProfiles(page) {+ return page.evaluate(() => {+ const names = ['spotifyArtistID', 'appleArtistID', 'googleArtistID', 'instagramProfileArtistID', 'facebookProfileArtistID'];+ let answered = 0;+ for (const name of names) {+ const els = [...document.querySelectorAll(`[name="${name}"]`)];+ const select = els.find((e) => e.tagName === 'SELECT' && [...e.options].some((o) => o.value === 'new'));+ const radio = els.find((e) => e.type === 'radio' && e.value === 'new');+ if (select) {+ select.value = 'new';+ select.dispatchEvent(new Event('change', { bubbles: true }));+ } else if (radio) {+ if (!radio.checked) radio.click();+ } else continue;+ answered += 1;+ }+ return answered === names.length;+ });+}++/** Apple Music's required credits: the performer and producer names (and the performer's role, when given). */+async function appleCredits(page, credits) {+ return page.evaluate((c) => {+ const fill = (prefix, name, role) => {+ const fields = [...document.querySelectorAll(`[id^="${prefix}"]`)];+ const text = fields.find((f) => f.tagName === 'INPUT' && f.type === 'text');+ if (!text) return false;+ text.value = name;+ text.dispatchEvent(new Event('input', { bubbles: true }));+ text.dispatchEvent(new Event('change', { bubbles: true }));+ if (!role) return true;+ const select = fields.find((f) => f.tagName === 'SELECT');+ const opt = select && [...select.options].find((o) => o.textContent.trim().toLowerCase() === role.toLowerCase());+ if (!opt) return false;+ select.value = opt.value;+ select.dispatchEvent(new Event('change', { bubbles: true }));+ return true;+ };+ return fill('track-1-performer-1-', c.performer, c.performerRole) && fill('track-1-producer-1-', c.producer, 'Producer');+ }, credits);+}++/** Untick every paid extra (they all share name=extras); the labels of any that were ticked. */+async function untickPaidExtras(page) {+ return page.evaluate(() => [...document.querySelectorAll('input[name=extras]')]+ .filter((b) => b.checked)+ .map((b) => { b.click(); return (b.closest('label')?.innerText || b.value || '').replace(/\s+/g, ' ').trim().slice(0, 60); }));+}++/**+ * Answer DistroKid's AI question and tick the parts the director says AI made.+ * The parts are checkboxes in the form (ai_lyrics_…, ai_music_…, and "all" or+ * "part of the audio"); older forms asked in a pop-up, still handled.+ */async function discloseAi(page, ai) {const any = ai.lyrics || ai.music || ai.vocals;const answered = await page.evaluate((yes) => {@@ -61,24 +147,33 @@ async function discloseAi(page, ai) {if (!answered || !any) return answered;await page.waitForTimeout(1000);return page.evaluate((want) => {+ const labelOf = (b) => (b.closest('label')?.innerText || b.parentElement?.innerText || '').replace(/\s+/g, ' ');+ const set = (box, on) => { if (box && box.checked !== on) box.click(); return !!box; };+ const lyrics = document.querySelector('input[name^="ai_lyrics_"]');+ const music = document.querySelector('input[name^="ai_music_"]');+ if (lyrics || music) {+ const audio = [...document.querySelectorAll('input[name^="ai_"]')].filter((b) => /of the audio/i.test(labelOf(b)));+ const all = audio.find((b) => /all of the audio/i.test(labelOf(b)));+ const part = audio.find((b) => /part of the audio/i.test(labelOf(b)));+ // All of the audio (AI vocals) or, for AI music under a human voice, part of it.+ const audioOk = want.vocals+ ? set(all, true) && (!part || part.type === 'radio' || set(part, false))+ : (!all || all.type === 'radio' || set(all, false)) && (!want.music || !part || set(part, true));+ return set(lyrics, want.lyrics) && set(music, want.music) && audioOk;+ }const popup = [...document.querySelectorAll('.swal2-popup')].find((p) => /which parts|ai-generated/i.test(p.innerText || ''));if (!popup) return false;- const tick = (re, on) => {- const box = [...popup.querySelectorAll('input[type=checkbox]')].find((b) => re.test(b.closest('label')?.innerText || b.parentElement?.innerText || ''));- if (box && box.checked !== on) box.click();- return !!box;- };- const found = [- tick(/lyrics/i, want.lyrics),- tick(/music\s*\(composed/i, want.music),- tick(/all of the audio/i, want.vocals),- ];+ const tick = (re, on) => set([...popup.querySelectorAll('input[type=checkbox]')].find((b) => re.test(labelOf(b))), on);+ const found = [tick(/lyrics/i, want.lyrics), tick(/music\s*\(composed/i, want.music), tick(/all of the audio/i, want.vocals)];const save = [...popup.querySelectorAll('button')].find((b) => /^save$/i.test((b.innerText || '').trim()));save?.click();return found.every(Boolean) && !!save;}, ai);}+const ROLE_ANSWER = { music: 'music', lyrics: 'lyrics', both: 'both|music and lyrics|lyrics and music' };+const clock = (sec) => `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}`;+export const distrokidAdapter = {label,async prepare(page, payload) {@@ -108,18 +203,39 @@ export const distrokidAdapter = {});await soft(payload.instrumental ? 'instrumental' : 'contains lyrics', () => checkByLabel(page, 'input[type=radio]', payload.instrumental ? 'instrumental|no lyrics' : 'contains lyrics'));if (payload.releaseDate) await soft(`release date ${payload.releaseDate}`, () => setValue(page, '#release-date-dp, input[name=releaseDate]', payload.releaseDate));+ await soft(`songwriter role (${payload.songwriterRole})`, () => answerQuestion(page, 'songwriter|wrote', ROLE_ANSWER[payload.songwriterRole] || ROLE_ANSWER.both));await soft('AI disclosure', () => discloseAi(page, payload.ai));+ await soft('previously released: no', () => answerQuestion(page, 'previously released|released before', '^no'));+ await soft(`language (${payload.language})`, () => setValue(page, '#language', payload.language));+ if (payload.genre) await soft(`genre (${payload.genre})`, () => setValue(page, '#genrePrimary', payload.genre));+ else leftForYou.push('genre');+ if (payload.secondaryGenre) await soft(`secondary genre (${payload.secondaryGenre})`, () => setValue(page, '#genreSecondary', payload.secondaryGenre));+ if (payload.newArtistProfile) await soft('store profiles: new on all five', () => newStoreProfiles(page));+ else leftForYou.push('your existing store profiles (Spotify, Apple, YouTube Music, Instagram, Facebook)');+ await soft('Apple Music credits (or untick Apple Music and iTunes)', () => appleCredits(page, payload.credits));+ if (payload.previewStartSec != null) {+ await soft(`preview start ${clock(payload.previewStartSec)}`, () => answerQuestion(page, 'preview|clip', clock(payload.previewStartSec))+ .then((ok) => ok || setValue(page, 'select[name*=preview i], select[id*=preview i], input[name*=preview i]', String(payload.previewStartSec))));+ }+ // Paid extras are the director's call, every time: none stays ticked.+ const unticked = await untickPaidExtras(page).catch(() => null);+ if (unticked === null) leftForYou.push('check that no paid extras are ticked');await page.evaluate(() => document.querySelector('#js-track-upload-1')?.scrollIntoView({ block: 'center' })).catch(() => {});const aiParts = [payload.ai.lyrics && 'lyrics', payload.ai.music && 'music', payload.ai.vocals && 'all of the audio'].filter(Boolean);return {artist: payload.artist,title: payload.title,- songwriter: `${payload.songwriter.first} ${payload.songwriter.last}`,+ songwriter: `${payload.songwriter.first} ${payload.songwriter.last} (${payload.songwriterRole === 'both' ? 'music and lyrics' : payload.songwriterRole})`,releaseDate: payload.releaseDate || 'As soon as possible',+ genre: [payload.genre, payload.secondaryGenre].filter(Boolean).join(' / ') || null,+ language: payload.language,explicit: payload.explicit ? 'Yes' : 'No',ai: aiParts.length ? aiParts.join(', ') : 'None',- leftForYou: [...leftForYou, 'the agreement checkboxes', 'Upload'],+ appleCredits: `${payload.credits.performer} (performer), ${payload.credits.producer} (producer)`,+ preview: payload.previewStartSec != null ? `from ${clock(payload.previewStartSec)}` : null,+ paidExtras: unticked?.length ? `unticked: ${unticked.join(', ')}` : 'none',+ leftForYou: [...leftForYou, 'which stores (DistroKid picks all by default)', 'the agreement checkboxes', 'Upload'],};},};diff --git a/server/services/musicVideo/publish/payloads.js b/server/services/musicVideo/publish/payloads.jsindex 0cb7468512..7de67d4e33 100644--- a/server/services/musicVideo/publish/payloads.js+++ b/server/services/musicVideo/publish/payloads.js@@ -7,6 +7,8 @@import { ServerError } from '../../../lib/errorHandler.js';import { chaptersText } from '../publishKitText.js';import { musicVideoDependencyChanges } from '../../../lib/musicVideoDependencies.js';+import { suggestDistrokidGenres } from '../../../lib/distrokidGenres.js';+import { suggestSocialCuts } from '../socialCuts.js';const TITLE_LIMITS = { youtube: 100, shorts: 100, reddit: 300, stackerNews: 80 };const DEFAULT_SUBREDDIT = 'aivideo';@@ -185,11 +187,31 @@ const BUILDERS = {const releaseDate = text(options.releaseDate);if (releaseDate && !/^\d{4}-\d{2}-\d{2}$/.test(releaseDate)) throw missing('Give the release date as YYYY-MM-DD');const hasLyrics = (project?.lyricCues || []).some((cue) => text(cue?.text));+ const instrumental = typeof options.instrumental === 'boolean' ? options.instrumental : !hasLyrics;+ const suggested = suggestDistrokidGenres(project);+ const genre = text(options.genre) || suggested.primary;+ const secondary = text(options.secondaryGenre) || suggested.secondary;+ const fullName = `${songwriter.first} ${songwriter.last}`;+ // The store preview (and TikTok clip) opens on the song's strongest hook.+ const previewStartSec = Number.isFinite(options.previewStartSec) ? options.previewStartSec : (suggestSocialCuts(project, { count: 1 })[0]?.startSec ?? null);return {title, artist, songwriter, releaseDate: releaseDate || null,+ songwriterRole: options.songwriterRole || (instrumental ? 'music' : 'both'),explicit: options.explicit === true,- instrumental: typeof options.instrumental === 'boolean' ? options.instrumental : !hasLyrics,+ instrumental,ai: { lyrics: options.aiLyrics === true, music: options.aiMusic !== false, vocals: options.aiVocals !== false },+ genre: genre || null,+ secondaryGenre: secondary && secondary !== genre ? secondary : null,+ language: text(options.language) || 'English',+ // Store profiles: a first release asks for new ones; otherwise the director links the existing ones.+ newArtistProfile: options.newArtistProfile === true,+ // Apple Music requires a performer and a producer credit (real names).+ credits: {+ performer: text(options.performerName) || fullName,+ performerRole: text(options.performerRole) || null,+ producer: text(options.producerName) || fullName,+ },+ previewStartSec: previewStartSec != null ? Math.max(0, Math.floor(previewStartSec)) : null,cover,};},diff --git a/server/services/musicVideo/publish/payloads.test.js b/server/services/musicVideo/publish/payloads.test.jsindex 36eb8def6c..ee2dd1bef5 100644--- a/server/services/musicVideo/publish/payloads.test.js+++ b/server/services/musicVideo/publish/payloads.test.js@@ -133,7 +133,14 @@ describe('buildPublishPayload (#9282)', () => {expect(buildPublishPayload('distrokid', song(), who)).toMatchObject({title: 'Song', artist: 'Example Artist', explicit: false, instrumental: false, releaseDate: null,ai: { lyrics: false, music: true, vocals: true }, cover: { name: 'thumb-1.jpg' },+ songwriterRole: 'both', language: 'English', genre: null, secondaryGenre: null, newArtistProfile: false,+ credits: { performer: 'Alice Example', producer: 'Alice Example', performerRole: null }, previewStartSec: 0,});+ // Genre comes from the song's own style words; the director's picks win, and the preview opens on the hook.+ const styled = song({ autonomousRun: { output: { sunoStyle: 'dark synthwave, pop hooks, female vocal' } } });+ expect(buildPublishPayload('distrokid', styled, who)).toMatchObject({ genre: 'Electronic', secondaryGenre: 'Pop' });+ expect(buildPublishPayload('distrokid', styled, { ...who, genre: 'Pop', secondaryGenre: 'Pop', newArtistProfile: true, performerName: 'Bob Example', performerRole: 'Vocals', previewStartSec: 42.7 }))+ .toMatchObject({ genre: 'Pop', secondaryGenre: null, newArtistProfile: true, credits: { performer: 'Bob Example', performerRole: 'Vocals', producer: 'Alice Example' }, previewStartSec: 42 });expect(buildPublishPayload('distrokid', song({ lyricCues: [] }), { ...who, aiLyrics: true, releaseDate: '2026-11-06' })).toMatchObject({ instrumental: true, releaseDate: '2026-11-06', ai: { lyrics: true } });// The composed cover art wins over the thumbnail, for DistroKid and Suno alike.