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

DistroKid recipe uses the form's real field names, with a fixture test

Claudece6ae619d2f8
diff --git a/client/src/lib/distrokidForm.test.js b/client/src/lib/distrokidForm.test.js
new file mode 100644
index 0000000000..da38e3f935
--- /dev/null
+++ b/client/src/lib/distrokidForm.test.js
@@ -0,0 +1,94 @@
+// The DistroKid recipe's in-page steps (server/lib/distrokidForm.js) run in the
+// browser through page.evaluate, so they are tested here, against a fixture of
+// the upload form's fields (#10337), in the client's DOM environment.
+import { describe, it, expect, beforeEach } from 'vitest';
+import { discloseDistrokidAi, fillDistrokidFields, untickDistrokidExtras } from '../../../server/lib/distrokidForm.js';
+
+const radios = (name, values) => values.map((v) => `<label><input type="radio" name="${name}" value="${v}">${v}</label>`).join('');
+const options = (values) => values.map((v) => `<option value="${v}">${v}</option>`).join('');
+const range = (n) => Array.from({ length: n }, (_, i) => String(i));
+
+const FORM = `
+ <label><input type="checkbox" name="extras" value="socialmediapack" id="socialmediapack" checked>Social Media Pack</label>
+ ${radios('previouslyReleased_ab12', ['0', '1'])}
+ <input type="checkbox" id="checkboxPreserveNonStandardCaps">
+ <div hidden>${radios('spotifyArtistID', ['new'])}</div>
+ <div>${radios('spotifyArtistID', ['', 'new'])}</div>
+ <select name="appleArtistID"><option value="">Pick</option><option value="new">New profile</option></select>
+ ${radios('googleArtistID', ['new'])}${radios('instagramProfileArtistID', ['new'])}${radios('facebookProfileArtistID', ['new'])}
+ <select id="language">${options(['', 'English', 'Spanish'])}</select>
+ <select id="genrePrimary">${options(['', 'Alternative', 'Electronic', 'Pop'])}</select>
+ <select id="genreSecondary">${options(['', 'Alternative', 'Electronic', 'Pop'])}</select>
+ <input id="albumTitleInput" name="albumtitle">
+ ${radios('feat_cd34', ['0', '1'])}${radios('version_cd34', ['', 'Radio Edit'])}${radios('dolby_1', ['0', '1'])}
+ ${radios('coversong_cd34', ['0', '1'])}${radios('cleaned_cd34', ['0', '1'])}${radios('instrumental_cd34', ['0', '1'])}
+ <div class="songwriter">
+ <select><option>Music</option><option>Lyrics</option><option>Music and lyrics</option></select>
+ <input name="songwriter_real_name_first1"><input name="songwriter_real_name_last1">
+ </div>
+ <div class="preview">${radios('previewStart_1', ['no', 'yes'])}<select>${options(range(10))}</select><select>${options(range(60))}</select></div>
+ <select id="track-1-performer-1-role">${options(['', 'Vocals', 'Synthesizer'])}</select><input id="track-1-performer-1-name">
+ <select id="track-1-producer-1-role">${options(['', 'Producer', 'Mixing Engineer'])}</select><input id="track-1-producer-1-name">
+ ${radios('ai_gate_cd34', ['0', '1'])}
+ <label><input type="checkbox" name="ai_lyrics_cd34">Lyrics</label>
+ <label><input type="checkbox" name="ai_music_cd34">Music</label>
+ <label><input type="checkbox" name="ai_audio_cd34" value="full">All of the audio</label>
+ <label><input type="checkbox" name="ai_audio_cd34" value="partial">Part of the audio</label>
+ ${radios('ai_partial_audio_type_cd34', ['vocals', 'instruments'])}
+ <label><input type="checkbox" name="extras" value="legacy" checked>Leave a Legacy</label>
+ <label><input type="checkbox" name="extras" value="distrovid">DistroVid</label>
+`;
+
+const PLAN = {
+ albumTitle: 'Example Song', language: 'English', genre: 'Electronic', secondaryGenre: 'Pop', preserveCaps: true,
+ newArtistProfile: true, instrumental: false, songwriterRole: 'Music and lyrics', previewStart: { min: 1, sec: 5 },
+ credits: { performer: 'Alice Example', performerRole: 'Vocals', producer: 'Alice Example' },
+};
+const $ = (sel) => document.querySelector(sel);
+const checked = (name) => document.querySelector(`input[name^="${name}"]:checked`)?.value;
+
+describe('DistroKid form recipe', () => {
+ beforeEach(() => { document.body.innerHTML = FORM; });
+
+ it('answers every release and track question PortOS knows from the song', () => {
+ const { missed } = fillDistrokidFields(PLAN);
+ expect(missed).toEqual([]);
+ expect(checked('previouslyReleased_')).toBe('0');
+ expect($('#checkboxPreserveNonStandardCaps').checked).toBe(true);
+ // The shown variant of a profile question is the one answered.
+ expect([...document.querySelectorAll('input[name=spotifyArtistID][value=new]')].map((r) => r.checked)).toEqual([false, true]);
+ expect($('select[name=appleArtistID]').value).toBe('new');
+ expect([$('#language').value, $('#genrePrimary').value, $('#genreSecondary').value, $('#albumTitleInput').value]).toEqual(['English', 'Electronic', 'Pop', 'Example Song']);
+ expect(['feat_', 'version_', 'dolby_', 'coversong_', 'cleaned_', 'instrumental_'].map(checked)).toEqual(['0', '', '0', '0', '0', '0']);
+ expect($('.songwriter select').value).toBe('Music and lyrics');
+ expect(checked('previewStart_')).toBe('yes');
+ expect([...document.querySelectorAll('.preview select')].map((s) => s.value)).toEqual(['1', '5']);
+ expect([$('#track-1-performer-1-name').value, $('#track-1-performer-1-role').value, $('#track-1-producer-1-name').value, $('#track-1-producer-1-role').value])
+ .toEqual(['Alice Example', 'Vocals', 'Alice Example', 'Producer']);
+ });
+
+ it('reports a field the form no longer has instead of failing', () => {
+ $('#genrePrimary').remove();
+ $('#track-1-producer-1-name').remove();
+ const { missed } = fillDistrokidFields(PLAN);
+ expect(missed).toEqual(['genre (Electronic)', 'Apple Music credits (or untick Apple Music and iTunes)']);
+ });
+
+ it('discloses AI vocals as all of the audio, and AI music under a human voice as part of it', () => {
+ expect(discloseDistrokidAi({ step: 'gate', ai: { lyrics: false, music: true, vocals: true } })).toBe(true);
+ expect(checked('ai_gate_')).toBe('1');
+ expect(discloseDistrokidAi({ step: 'parts', ai: { lyrics: false, music: true, vocals: true } })).toBe(true);
+ const box = (sel) => $(sel).checked;
+ expect([box('[name^=ai_lyrics_]'), box('[name^=ai_music_]'), box('[value=full]'), box('[value=partial]')]).toEqual([false, true, true, false]);
+ expect(discloseDistrokidAi({ step: 'parts', ai: { lyrics: true, music: true, vocals: false } })).toBe(true);
+ expect([box('[name^=ai_lyrics_]'), box('[value=full]'), box('[value=partial]')]).toEqual([true, false, true]);
+ expect(checked('ai_partial_audio_type_')).toBe('instruments');
+ expect(discloseDistrokidAi({ step: 'gate', ai: { lyrics: false, music: false, vocals: false } })).toBe(true);
+ expect(checked('ai_gate_')).toBe('0');
+ });
+
+ it('leaves no paid extra ticked, and names the ones it unticked', () => {
+ expect(untickDistrokidExtras()).toEqual(['Social Media Pack', 'Leave a Legacy']);
+ expect(document.querySelectorAll('input[name=extras]:checked')).toHaveLength(0);
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 3d324aef14..2ee2a89ba9 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. |
+| `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. |
| `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`. |
diff --git a/server/lib/distrokidForm.js b/server/lib/distrokidForm.js
new file mode 100644
index 0000000000..efe80ff5b4
--- /dev/null
+++ b/server/lib/distrokidForm.js
@@ -0,0 +1,169 @@
+/**
+ * DistroKid upload form (distrokid.com/new/): the in-page steps of the
+ * release recipe (#10337). Each function runs INSIDE the page through
+ * Playwright's `page.evaluate(fn, arg)`, so it is self-contained: it reads
+ * only `document` and its argument, never this module's scope. The same
+ * functions run against a fixture document in the client's DOM tests.
+ *
+ * Per-track fields carry a random suffix per page load (`title_<uuid>`), so
+ * they are matched by name prefix. Several radios render one variant per
+ * situation (the store-profile questions), so the shown one wins.
+ */
+
+/**
+ * Answer the release and track questions PortOS knows from the song.
+ * `plan`: { albumTitle, language, genre, secondaryGenre, preserveCaps,
+ * newArtistProfile, instrumental, songwriterRole ('Music' | 'Lyrics' |
+ * 'Music and lyrics'), previewStart: { min, sec } | null,
+ * credits: { performer, performerRole, producer } }.
+ * Resolves `{ done, missed }`: the labels of the steps that took and of those
+ * that found no field (left for the director).
+ */
+export function fillDistrokidFields(plan) {
+ const done = [];
+ const missed = [];
+ const note = (label, ok) => (ok ? done : missed).push(label);
+ const shown = (el) => !el.closest('[hidden], [style*="display: none"], [style*="display:none"]')
+ && (typeof el.checkVisibility !== 'function' || el.checkVisibility());
+ const fire = (el) => {
+ el.dispatchEvent(new Event('input', { bubbles: true }));
+ el.dispatchEvent(new Event('change', { bubbles: true }));
+ };
+ const radio = (selector, value) => {
+ const all = [...document.querySelectorAll(selector)].filter((r) => r.value === value);
+ const pick = all.find(shown) || all[0];
+ if (!pick) return false;
+ if (!pick.checked) pick.click();
+ return true;
+ };
+ const choose = (el, want) => {
+ if (!el || el.tagName !== 'SELECT') return false;
+ const w = String(want).toLowerCase();
+ const opt = [...el.options].find((o) => o.value.toLowerCase() === w || o.textContent.trim().toLowerCase() === w);
+ if (!opt) return false;
+ el.value = opt.value;
+ fire(el);
+ return true;
+ };
+ const type = (el, value) => {
+ if (!el) return false;
+ el.value = value;
+ fire(el);
+ return true;
+ };
+ const tick = (el, on) => {
+ if (!el) return false;
+ if (el.checked !== on) el.click();
+ return true;
+ };
+ // The nearest ancestor of `el` holding at least `count` elements matching `selector`.
+ const around = (el, selector, count = 1) => {
+ for (let node = el?.parentElement; node; node = node.parentElement) {
+ if (node.querySelectorAll(selector).length >= count) return node;
+ }
+ return null;
+ };
+
+ note('previously released: no', radio('input[name^="previouslyReleased_"]', '0'));
+ if (plan.preserveCaps) note('keep the artist name\'s capitalization', tick(document.querySelector('#checkboxPreserveNonStandardCaps'), true));
+ if (plan.newArtistProfile) {
+ const names = ['spotifyArtistID', 'appleArtistID', 'googleArtistID', 'instagramProfileArtistID', 'facebookProfileArtistID'];
+ const answered = names.filter((n) => {
+ const select = [...document.querySelectorAll(`select[name="${n}"]`)].find((s) => [...s.options].some((o) => o.value === 'new'));
+ return select ? choose(select, 'new') : radio(`input[name="${n}"]`, 'new');
+ });
+ note('store profiles: new on all five', answered.length === names.length);
+ }
+ note(`language (${plan.language})`, choose(document.querySelector('#language'), plan.language));
+ if (plan.genre) note(`genre (${plan.genre})`, choose(document.querySelector('#genrePrimary'), plan.genre));
+ if (plan.secondaryGenre) note(`secondary genre (${plan.secondaryGenre})`, choose(document.querySelector('#genreSecondary'), plan.secondaryGenre));
+ if (plan.albumTitle) note('release title', type(document.querySelector('#albumTitleInput'), plan.albumTitle));
+ note('no featured artist', radio('input[name^="feat_"]', '0'));
+ note('normal version (not a radio edit)', radio('input[name^="version_"]', ''));
+ note('no Dolby Atmos', radio('input[name^="dolby_"]', '0'));
+ note('original song (not a cover)', radio('input[name^="coversong_"]', '0'));
+ note('not a clean version', radio('input[name^="cleaned_"]', '0'));
+ note(plan.instrumental ? 'instrumental' : 'has lyrics', radio('input[name^="instrumental_"]', plan.instrumental ? '1' : '0'));
+
+ const firstName = document.querySelector('[name^="songwriter_real_name_first"]');
+ const roleBox = around(firstName, 'select');
+ const roleSelect = roleBox && [...roleBox.querySelectorAll('select')].find((s) => [...s.options].some((o) => /music and lyrics/i.test(o.textContent)));
+ note(`songwriter role (${plan.songwriterRole})`, choose(roleSelect, plan.songwriterRole));
+
+ if (plan.previewStart) {
+ const yes = [...document.querySelectorAll('input[name="previewStart_1"]')].find((r) => r.value === 'yes');
+ let ok = !!yes && radio('input[name="previewStart_1"]', 'yes');
+ if (ok) {
+ const selects = [...(around(yes, 'select', 2)?.querySelectorAll('select') || [])];
+ const at = (el, n) => {
+ const opt = el && [...el.options].find((o) => Number(o.value || o.textContent) === n);
+ if (!opt) return false;
+ el.value = opt.value;
+ fire(el);
+ return true;
+ };
+ ok = selects.length >= 2 && at(selects[0], plan.previewStart.min) && at(selects[1], plan.previewStart.sec);
+ }
+ note(`preview start ${plan.previewStart.min}:${String(plan.previewStart.sec).padStart(2, '0')}`, ok);
+ }
+
+ const c = plan.credits || {};
+ const performer = type(document.querySelector('#track-1-performer-1-name'), c.performer)
+ && (!c.performerRole || choose(document.querySelector('#track-1-performer-1-role'), c.performerRole));
+ const producer = type(document.querySelector('#track-1-producer-1-name'), c.producer)
+ && choose(document.querySelector('#track-1-producer-1-role'), 'Producer');
+ note('Apple Music credits (or untick Apple Music and iTunes)', performer && producer);
+ return { done, missed };
+}
+
+/**
+ * The AI disclosure, in two steps because the parts appear once the gate says
+ * yes. `{ step: 'gate', ai }` answers the gate; `{ step: 'parts', ai }` ticks
+ * lyrics, music, and all of the audio (AI vocals) or part of it (AI
+ * instruments under a human voice). `ai`: { lyrics, music, vocals }.
+ * Resolves true when every field it needed was there.
+ */
+export function discloseDistrokidAi({ step, ai }) {
+ const any = !!(ai.lyrics || ai.music || ai.vocals);
+ const set = (el, on) => {
+ if (!el) return false;
+ if (el.checked !== on) el.click();
+ return true;
+ };
+ if (step === 'gate') {
+ const gate = document.querySelector(`input[type=radio][name^="ai_gate_"][value="${any ? 1 : 0}"]`);
+ if (!gate) return false;
+ gate.scrollIntoView?.({ block: 'center' });
+ return set(gate, true);
+ }
+ const full = document.querySelector('input[name^="ai_"][value="full"]');
+ const partial = document.querySelector('input[name^="ai_"][value="partial"]');
+ const partialAudio = !ai.vocals && ai.music;
+ let audio = set(full, !!ai.vocals) && set(partial, partialAudio);
+ if (audio && partialAudio) {
+ const kinds = [...document.querySelectorAll('[name^="ai_partial_audio_type_"]')];
+ const select = kinds.find((k) => k.tagName === 'SELECT');
+ if (select) {
+ audio = [...select.options].some((o) => o.value === 'instruments');
+ if (audio) {
+ select.value = 'instruments';
+ select.dispatchEvent(new Event('change', { bubbles: true }));
+ }
+ } else {
+ audio = set(kinds.find((k) => k.value === 'instruments'), true);
+ }
+ }
+ return set(document.querySelector('input[name^="ai_lyrics_"]'), !!ai.lyrics)
+ && set(document.querySelector('input[name^="ai_music_"]'), !!ai.music)
+ && audio;
+}
+
+/** Untick every paid extra (they share name=extras). Resolves the labels of the ones that were ticked. */
+export function untickDistrokidExtras() {
+ return [...document.querySelectorAll('input[name=extras]')]
+ .filter((b) => b.checked)
+ .map((b) => {
+ b.click();
+ return (b.closest('label')?.textContent || b.value || '').replace(/\s+/g, ' ').trim().slice(0, 60);
+ });
+}
diff --git a/server/lib/index.js b/server/lib/index.js
index deb47fa35a..aa29c0fb6a 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 './distrokidForm.js';
export * from './distrokidGenres.js';
export * from './domainAutonomy.js';
export * from './domainBudgets.js';
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 53e7c30f04..02ca894553 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -747,6 +747,7 @@ export const musicVideoPublishPrepareSchema = z.object({
language: z.string().trim().min(1).max(60),
songwriterRole: z.enum(['music', 'lyrics', 'both']),
newArtistProfile: z.boolean(),
+ preserveCaps: 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),
diff --git a/server/services/musicVideo/publish/distrokid.js b/server/services/musicVideo/publish/distrokid.js
index dae44e49b6..f86f9022ac 100644
--- a/server/services/musicVideo/publish/distrokid.js
+++ b/server/services/musicVideo/publish/distrokid.js
@@ -10,11 +10,13 @@
* 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
- * summary as left for the director rather than failing the whole draft.
+ * DistroKid restyles this form often, so every field is found by its id or
+ * name (the in-page steps live in lib/distrokidForm.js), and a field that is
+ * no longer there is reported in the summary as left for the director rather
+ * than failing the whole draft.
*/
import { PUBLISH_STEP_TIMEOUT_MS as T, loginRequired, step } from './browser.js';
+import { discloseDistrokidAi, fillDistrokidFields, untickDistrokidExtras } from '../../../lib/distrokidForm.js';
const label = 'DistroKid';
const UPLOAD_URL = 'https://distrokid.com/new/';
@@ -40,138 +42,7 @@ async function setValue(page, selector, value) {
}, [selector, value]);
}
-/** Check the first radio/checkbox whose label text matches `pattern` (a RegExp source). */
-async function checkByLabel(page, selector, pattern) {
- return page.evaluate(([sel, src]) => {
- const re = new RegExp(src, 'i');
- const box = [...document.querySelectorAll(sel)].find((b) => re.test((b.closest('label')?.innerText || b.parentElement?.innerText || '').replace(/\s+/g, ' ')));
- if (!box) return false;
- if (!box.checked) box.click();
- return true;
- }, [selector, pattern]);
-}
-
-/** 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) => {
- const radio = document.querySelector(`input[type=radio][name^="ai_gate_"][value="${yes ? 1 : 0}"]`);
- if (!radio) return false;
- radio.scrollIntoView({ block: 'center' });
- if (!radio.checked) radio.click();
- return true;
- }, any);
- 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) => 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 ROLE_TEXT = { music: 'Music', lyrics: 'Lyrics', both: 'Music and lyrics' };
const clock = (sec) => `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}`;
export const distrokidAdapter = {
@@ -201,24 +72,30 @@ export const distrokidAdapter = {
await page.locator(payload.explicit ? '#js-explicit-radio-button-1' : '#js-not-explicit-radio-button-1').first().check({ timeout: 5000 });
return true;
});
- 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))));
- }
+ const fields = await page.evaluate(fillDistrokidFields, {
+ albumTitle: payload.title,
+ language: payload.language,
+ genre: payload.genre,
+ secondaryGenre: payload.secondaryGenre,
+ preserveCaps: payload.preserveCaps,
+ newArtistProfile: payload.newArtistProfile,
+ instrumental: payload.instrumental,
+ songwriterRole: ROLE_TEXT[payload.songwriterRole] || ROLE_TEXT.both,
+ previewStart: payload.previewStartSec != null ? { min: Math.floor(payload.previewStartSec / 60), sec: payload.previewStartSec % 60 } : null,
+ credits: payload.credits,
+ }).catch(() => ({ done: [], missed: ['genre, language, credits and the other release answers'] }));
+ leftForYou.push(...fields.missed);
+ if (!payload.genre) leftForYou.push('genre');
+ if (!payload.newArtistProfile) leftForYou.push('your existing store profiles (Spotify, Apple, YouTube Music, Instagram, Facebook)');
+ await soft('AI disclosure', async () => {
+ if (!(await page.evaluate(discloseDistrokidAi, { step: 'gate', ai: payload.ai }))) return false;
+ if (!(payload.ai.lyrics || payload.ai.music || payload.ai.vocals)) return true;
+ await page.waitForTimeout(1000);
+ return page.evaluate(discloseDistrokidAi, { step: 'parts', ai: payload.ai });
+ });
// Paid extras are the director's call, every time: none stays ticked.
- const unticked = await untickPaidExtras(page).catch(() => null);
+ const unticked = await page.evaluate(untickDistrokidExtras).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(() => {});
@@ -234,7 +111,7 @@ export const distrokidAdapter = {
ai: aiParts.length ? aiParts.join(', ') : 'None',
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',
+ paidExtras: unticked === null ? null : (unticked.length ? `unticked: ${unticked.join(', ')}` : 'none ticked'),
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.js
index 7de67d4e33..1f627ccc61 100644
--- a/server/services/musicVideo/publish/payloads.js
+++ b/server/services/musicVideo/publish/payloads.js
@@ -16,6 +16,7 @@ const DEFAULT_SUBREDDIT = 'aivideo';
const missing = (message) => new ServerError(message, { status: 422, code: 'PUBLISH_ASSET_MISSING' });
const stale = () => new ServerError('The publishing kit was built from an earlier render — rebuild the kit before filling this draft', { status: 409, code: 'PUBLISH_KIT_STALE' });
const text = (v) => (typeof v === 'string' ? v.trim() : '');
+const titleCase = (name) => name.replace(/\S+/g, (w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase());
const kitOf = (project) => (project?.publishKit && typeof project.publishKit === 'object' ? project.publishKit : {});
/** Refuse a kit whose master came from a different render than the project's current one. */
@@ -203,6 +204,8 @@ const BUILDERS = {
genre: genre || null,
secondaryGenre: secondary && secondary !== genre ? secondary : null,
language: text(options.language) || 'English',
+ // DistroKid title-cases names unless told the capitalization is deliberate ("atomantic", "DJ Example").
+ preserveCaps: typeof options.preserveCaps === 'boolean' ? options.preserveCaps : artist !== titleCase(artist),
// 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).
diff --git a/server/services/musicVideo/publish/payloads.test.js b/server/services/musicVideo/publish/payloads.test.js
index ee2dd1bef5..7c12f2c256 100644
--- a/server/services/musicVideo/publish/payloads.test.js
+++ b/server/services/musicVideo/publish/payloads.test.js
@@ -133,7 +133,7 @@ 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,
+ songwriterRole: 'both', language: 'English', genre: null, secondaryGenre: null, newArtistProfile: false, preserveCaps: 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.
@@ -141,6 +141,8 @@ describe('buildPublishPayload (#9282)', () => {
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 });
+ // An all-lowercase artist name keeps its capitalization on the stores.
+ expect(buildPublishPayload('distrokid', song(), { ...who, artistName: 'example' }).preserveCaps).toBe(true);
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.