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

Publish page: show what each post will say, and keep DistroKid answers for every release

Claude848b9557dc56
diff --git a/client/src/components/musicVideo/PublishKitPanel.jsx b/client/src/components/musicVideo/PublishKitPanel.jsx
index 7380e5aaed..7d3c0c28da 100644
--- a/client/src/components/musicVideo/PublishKitPanel.jsx
+++ b/client/src/components/musicVideo/PublishKitPanel.jsx
@@ -101,6 +101,7 @@ export default function PublishKitPanel({ project, publishKit, enabledTargets })
// Only the newest save reports, so an earlier one landing late can't claim "saved" over it.
return publishKit.saveCopy(patch).then((saved) => { if (seq === saveSeq.current) setSaveState(saved ? 'saved' : 'failed'); });
};
+ const badLink = (value) => !!value.trim() && !/^https?:\/\//.test(value.trim());
const saveLink = (key, value) => {
const url = value.trim();
if (url === (kit.links?.[key] || '') || (url && !/^https?:\/\//.test(url))) return;
@@ -231,11 +232,13 @@ export default function PublishKitPanel({ project, publishKit, enabledTargets })
<label htmlFor={idFor('youtube-url')} className="block text-[11px] text-port-text-muted">Full video URL (optional)</label>
<input id={idFor('youtube-url')} value={youtubeUrl} onChange={(e) => setYoutubeUrl(e.target.value)} onBlur={() => saveLink('youtube', youtubeUrl)} placeholder="https://…"
className="w-full bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs min-h-[44px] sm:min-h-0" />
+ {badLink(youtubeUrl) && <p className="text-[11px] text-port-warning">Not saved: a link starts with https://</p>}
</div>
<div>
<label htmlFor={idFor('song-url')} className="block text-[11px] text-port-text-muted">Song URL (optional)</label>
<input id={idFor('song-url')} value={songUrl} onChange={(e) => setSongUrl(e.target.value)} onBlur={() => saveLink('song', songUrl)} placeholder="https://…"
className="w-full bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs min-h-[44px] sm:min-h-0" />
+ {badLink(songUrl) && <p className="text-[11px] text-port-warning">Not saved: a link starts with https://</p>}
</div>
</div>
<fieldset className="space-y-1 rounded border border-port-border p-2">
diff --git a/client/src/components/musicVideo/PublishPostingPanel.jsx b/client/src/components/musicVideo/PublishPostingPanel.jsx
index 1d094c21c2..75fb52cd0b 100644
--- a/client/src/components/musicVideo/PublishPostingPanel.jsx
+++ b/client/src/components/musicVideo/PublishPostingPanel.jsx
@@ -1,9 +1,9 @@
-import { useState } from 'react';
+import { useEffect, useState } from 'react';
import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';
-import { safeReadJsonStorage, safeWriteJsonStorage } from '../../lib/safeStorage.js';
+import { safeReadJsonStorage, safeRemoveStorage } from '../../lib/safeStorage.js';
import { ExternalLink, X as XIcon, LogIn, Link as LinkIcon, Check, ChevronDown, ChevronRight, Undo2 } from 'lucide-react';
import PublishCard from './PublishCard.jsx';
-import { DISTROKID_GENRES, suggestDistrokidGenres } from '../../../../server/lib/distrokidGenres.js';
+import { DISTROKID_GENRES, DISTROKID_REMEMBERED_OPTIONS, suggestDistrokidGenres } from '../../../../server/lib/distrokidGenres.js';
import { publishRowAnchor } from '../../lib/musicVideoStages.js';
// Where the release goes, in posting order: the full video first so every
@@ -26,15 +26,20 @@ export const PUBLISH_TARGETS = [
// `accountPlaceholder` marks an account that is a name, not an @handle.
target: 'distrokid', label: 'DistroKid', accountPlaceholder: 'Artist name',
note: 'The song as a single to Spotify, Apple Music, YouTube Music and the other stores, with a square cover and the AI disclosure. You tick the agreements and press Upload',
- linkPlaceholder: 'Release or store link (optional): Mark done works without one',
+ linkPlaceholder: 'Store link, if you have one',
},
];
// The DistroKid answers the director gives once (songwriter legal name and
-// role, language, Apple performer role), remembered on this device only. The
-// store-profile answer is never remembered: new profiles are per first release.
+// role, language, Apple credits) are kept in settings with the platform, so
+// every project on every device refills them. The store-profile answer is
+// never kept: new profiles are per first release. Older installs kept a few
+// on this device only (SONGWRITER_KEY); those seed the settings once.
const SONGWRITER_KEY = 'portos.musicVideo.distrokidSongwriter';
-const DISTROKID_REMEMBERED = { songwriterFirst: 'first', songwriterLast: 'last', songwriterRole: 'role', language: 'language', performerRole: 'performerRole' };
+const LEGACY_REMEMBERED = { songwriterFirst: 'first', songwriterLast: 'last', songwriterRole: 'role', language: 'language', performerRole: 'performerRole' };
+// Options that ARE the account named under Where you post: editing one here updates it there.
+const ACCOUNT_OPTION = { distrokid: 'artistName', substack: 'publication' };
+const REMEMBERED_OPTIONS = { distrokid: DISTROKID_REMEMBERED_OPTIONS };
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';
@@ -58,7 +63,7 @@ function verticalCutChoices(project) {
return cuts;
}
-function TargetOptions({ target, kit, project, options, setOption, flairs, idFor, account }) {
+function TargetOptions({ target, kit, project, options, setOption, commitOption, flairs, idFor, account }) {
const field = (key, label, input) => (
<div key={key} className="space-y-0.5 min-w-0">
<label htmlFor={idFor(key)} className="block text-[11px] text-port-text-muted">{label}</label>
@@ -66,7 +71,8 @@ function TargetOptions({ target, kit, project, options, setOption, flairs, idFor
</div>
);
const text = (key, label, placeholder) => field(key, label,
- <input id={idFor(key)} value={options[key] || ''} placeholder={placeholder} onChange={(e) => setOption(key, e.target.value)} className={inputCls} />);
+ <input id={idFor(key)} value={options[key] || ''} placeholder={placeholder} onChange={(e) => setOption(key, e.target.value)}
+ onBlur={(e) => commitOption(key, e.target.value)} className={inputCls} />);
const area = (key, label) => field(key, label,
<textarea id={idFor(key)} value={options[key] || ''} rows={3} onChange={(e) => setOption(key, e.target.value)} className={inputCls} />);
@@ -145,6 +151,7 @@ function TargetOptions({ target, kit, project, options, setOption, flairs, idFor
</select>);
return (
<div className="space-y-2">
+ <p className="text-[11px] text-port-text-muted">Your name, role, language and credits are kept for the next release, on any device.</p>
<div className="grid sm:grid-cols-2 gap-2">
{text('artistName', 'Artist name', account || 'Your artist name')}
{field('releaseDate', 'Release date (blank = as soon as possible)',
@@ -152,7 +159,7 @@ function TargetOptions({ target, kit, project, options, setOption, flairs, idFor
{text('songwriterFirst', 'Songwriter legal first name', 'First')}
{text('songwriterLast', 'Songwriter legal last name', 'Last')}
{field('songwriterRole', 'Songwriter wrote',
- <select id={idFor('songwriterRole')} aria-label="Songwriter wrote" value={options.songwriterRole || (instrumental ? 'music' : 'both')} onChange={(e) => setOption('songwriterRole', e.target.value)} className={inputCls}>
+ <select id={idFor('songwriterRole')} aria-label="Songwriter wrote" value={options.songwriterRole || (instrumental ? 'music' : 'both')} onChange={(e) => { setOption('songwriterRole', e.target.value); commitOption('songwriterRole', e.target.value); }} className={inputCls}>
<option value="both">Music and lyrics</option>
<option value="music">Music</option>
<option value="lyrics">Lyrics</option>
@@ -167,9 +174,9 @@ function TargetOptions({ target, kit, project, options, setOption, flairs, idFor
{check('newArtistProfile', 'First release as this artist (new store profiles)', false)}
</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('performerName', 'Apple performer (real name)', fullName === 'Songwriter legal name' ? 'Same as the songwriter' : fullName)}
{text('performerRole', 'Performer role (optional)', 'e.g. Vocals')}
- {text('producerName', 'Apple producer (real name)', fullName)}
+ {text('producerName', 'Apple producer (real name)', fullName === 'Songwriter legal name' ? 'Same as the songwriter' : 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>
@@ -231,8 +238,8 @@ function ManualLink({ idFor, label, placeholder, onSave, hideMarkDone = false })
const valid = /^https?:\/\/\S+$/.test(url.trim());
return (
<div className="flex flex-wrap items-center gap-2">
- <input id={idFor('manual-url')} aria-label={`Link to a ${label} post made by hand`} value={url} placeholder={placeholder || 'Posted by hand? Paste the link'}
- onChange={(e) => setUrl(e.target.value)} className={`${inputCls} flex-1 min-w-0`} />
+ <input id={idFor('manual-url')} aria-label={`Link to the ${label} post`} value={url} placeholder={placeholder || 'Posted it? Paste the link to the post'}
+ onChange={(e) => setUrl(e.target.value)} className={`${inputCls} basis-full sm:basis-auto sm:flex-1 min-w-0`} />
<button type="button" disabled={!valid} onClick={() => onSave({ url: url.trim() }).then((post) => { if (post) setUrl(''); })}
className="flex items-center gap-1 border border-port-border disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0">
<LinkIcon size={12} /> Record
@@ -268,6 +275,61 @@ function UndoDone({ label, onUndo }) {
);
}
+/** The DistroKid answers kept in settings, else (older installs) the ones this device remembered. */
+function rememberedDistrokid(platform) {
+ const kept = platform?.defaults || {};
+ return Object.keys(kept).length ? { ...kept } : legacyDistrokid();
+}
+function legacyDistrokid() {
+ const saved = safeReadJsonStorage(SONGWRITER_KEY, {}) || {};
+ return Object.fromEntries(Object.entries(LEGACY_REMEMBERED).filter(([, k]) => typeof saved[k] === 'string' && saved[k].trim()).map(([opt, k]) => [opt, saved[k].trim()]));
+}
+
+// The kit fields a post is built from: a change to any of them refreshes the preview.
+const kitStamp = (project) => {
+ const kit = project?.publishKit || {};
+ return JSON.stringify([project?.name, project?.renderHistoryId, kit.copy, kit.links, kit.posts, kit.thumbnail, kit.coverArt?.filename, kit.master, kit.exports, kit.chapters, project?.excerpts?.length]);
+};
+
+/** What Fill draft would post for this row, re-read (briefly debounced) when its options or the kit change. */
+function usePostPreview({ open, target, options, project, publishing }) {
+ const [preview, setPreview] = useState(null);
+ const optionsKey = JSON.stringify(options);
+ const stamp = kitStamp(project);
+ useEffect(() => {
+ if (!open || !publishing.preview) return undefined;
+ let active = true;
+ const timer = setTimeout(() => {
+ publishing.preview(target, options).then((res) => { if (active) setPreview(res); });
+ }, 400);
+ return () => { active = false; clearTimeout(timer); };
+ // `options` is keyed by its JSON; the hook's functions are stable enough per project.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open, target, optionsKey, stamp, project?.id]);
+ return preview;
+}
+
+/** "What gets posted": every word and file Fill draft will put in the post, or what is still missing. */
+function PostPreview({ label, preview }) {
+ if (!preview) return null;
+ if (!preview.ready) {
+ return <p role="status" className="text-[11px] text-port-warning">Not ready to fill: {preview.problem}</p>;
+ }
+ return (
+ <details className="rounded border border-port-border bg-port-bg/50 p-2 text-[11px]" open>
+ <summary className="cursor-pointer font-medium min-h-[44px] sm:min-h-0 flex items-center">What gets posted to {label}</summary>
+ <dl className="mt-1 space-y-1">
+ {(preview.parts || []).map(({ label: rowLabel, text }, i) => (
+ <div key={`${rowLabel}-${i}`}>
+ <dt className="text-port-text-muted">{rowLabel}</dt>
+ <dd className="min-w-0 break-words whitespace-pre-wrap">{text}</dd>
+ </div>
+ ))}
+ </dl>
+ </details>
+ );
+}
+
const STATUS = { posted: ['Done', 'text-port-success border-port-success/40'], draft: ['Draft open', 'text-port-warning border-port-warning/40'], none: ['To do', 'text-port-text-muted border-port-border'] };
function TargetRow({ project, kit, entry, publishing }) {
@@ -280,14 +342,34 @@ function TargetRow({ project, kit, entry, publishing }) {
return { songUrl: `https://suno.com/song/${encodeURIComponent(songId)}` };
}
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: '', songwriterLast: '', ...remembered, aiLyrics: !!project?.autonomousRun?.output?.lyrics };
+ return { songwriterFirst: '', songwriterLast: '', ...rememberedDistrokid(publishing.platforms?.distrokid), aiLyrics: !!project?.autonomousRun?.output?.lyrics };
}
return {};
});
const setOption = (key, value) => setOptions((prev) => ({ ...prev, [key]: value }));
+ // Keep an answer that repeats across releases (or the account it names) in settings when the director leaves the field.
+ const commitOption = (key, raw) => {
+ const value = typeof raw === 'string' ? raw.trim() : raw;
+ const platform = publishing.platforms?.[target] || {};
+ if (ACCOUNT_OPTION[target] === key) {
+ if (value && value !== (platform.account || '')) publishing.setPlatform(target, { account: value });
+ return;
+ }
+ if (!REMEMBERED_OPTIONS[target]?.includes(key) || value === (platform.defaults?.[key] || '')) return;
+ publishing.setPlatform(target, { defaults: { [key]: value || null } });
+ };
+ // A device that remembered answers before settings kept them hands them over once.
+ useEffect(() => {
+ if (target !== 'distrokid' || !publishing.platforms?.distrokid) return;
+ const kept = publishing.platforms.distrokid.defaults || {};
+ if (Object.keys(kept).length) return;
+ const legacy = legacyDistrokid();
+ if (!Object.keys(legacy).length) return;
+ publishing.setPlatform('distrokid', { defaults: legacy }).then((saved) => { if (saved) safeRemoveStorage(SONGWRITER_KEY); });
+ // Once per mount: the settings answer above wins from then on.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [target]);
const [confirmDiscard, setConfirmDiscard] = useState(false);
const [confirmAgain, setConfirmAgain] = useState(false);
const draft = publishing.drafts[target];
@@ -301,12 +383,8 @@ function TargetRow({ project, kit, entry, publishing }) {
const status = posted ? 'posted' : draft ? 'draft' : 'none';
const Chevron = open ? ChevronDown : ChevronRight;
const clean = Object.fromEntries(Object.entries(options).filter(([, v]) => v !== '' && v != null));
- const fill = (extra) => {
- 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, { ...clean, ...extra });
- };
+ const fill = (extra) => publishing.prepare(target, { ...clean, ...extra });
+ const preview = usePostPreview({ open, target, options: clean, project, publishing });
return (
<li id={publishRowAnchor(target)} data-fold className="rounded border border-port-border p-2 space-y-2 scroll-mt-4">
@@ -357,16 +435,16 @@ function TargetRow({ project, kit, entry, publishing }) {
)}
</div>
{open && <div id={idFor('body')} className="space-y-2">
- {posted
- ? (
- <>
- <PostFeedback key={posted.url || 'post'} idFor={idFor} label={label} post={posted} onSave={(body) => publishing.recordPost(target, body)} />
- {!posted.url && <ManualLink idFor={idFor} label={label} placeholder={linkPlaceholder} onSave={(body) => publishing.recordPost(target, body)} hideMarkDone />}
- <UndoDone label={label} onUndo={() => publishing.removePost?.(target)} />
- </>
- )
- : <ManualLink idFor={idFor} label={label} placeholder={linkPlaceholder} onSave={(body) => publishing.recordPost(target, body)} />}
- <TargetOptions target={target} kit={kit} project={project} options={options} setOption={setOption} flairs={flairs} idFor={idFor} account={account} />
+ {posted && (
+ <>
+ <PostFeedback key={posted.url || 'post'} idFor={idFor} label={label} post={posted} onSave={(body) => publishing.recordPost(target, body)} />
+ {!posted.url && <ManualLink idFor={idFor} label={label} placeholder={linkPlaceholder} onSave={(body) => publishing.recordPost(target, body)} hideMarkDone />}
+ <UndoDone label={label} onUndo={() => publishing.removePost?.(target)} />
+ </>
+ )}
+ <TargetOptions target={target} kit={kit} project={project} options={options} setOption={setOption} commitOption={commitOption} flairs={flairs} idFor={idFor} account={account} />
+ <PostPreview label={label} preview={preview} />
+ {!posted && <ManualLink idFor={idFor} label={label} placeholder={linkPlaceholder} onSave={(body) => publishing.recordPost(target, body)} />}
{error && (
<div role="alert" className="text-[11px] text-port-error space-y-0.5">
<div className="flex items-center gap-1">{error.code === 'PUBLISH_LOGIN_REQUIRED' && <LogIn size={11} />}{error.message}</div>
@@ -420,7 +498,7 @@ export default function PublishPostingPanel({ project, publishing }) {
return (
<PublishCard projectId={project.id} cardId="posting" label="Publish manually" icon={ExternalLink}
summary={targets.length ? `${done} of ${targets.length} done` : ''} defaultOpen={!targets.length || done < targets.length}>
- <p className="text-port-text-muted">Sign in to each platform in the PortOS Browser first. Fill draft opens a new tab there and fills the post from the kit and copy above; review and publish yourself on the platform. PortOS cannot submit posts.</p>
+ <p className="text-port-text-muted">Each platform shows what gets posted. Fill draft opens a tab in the PortOS Browser on the computer running PortOS (sign in there first), fills the post and shows a screenshot here. You press Post there. Then paste the post&apos;s link and press Record, or press Mark done when there is no link yet.</p>
{!targets.length && <p className="text-port-text-muted">Turn on the platforms you use under Where you post to prepare drafts. Final publication happens on each platform.</p>}
<ul className="space-y-2">
{targets.map((entry) => <TargetRow key={`${project.id}-${entry.target}`} project={project} kit={kit} entry={entry} publishing={publishing} />)}
diff --git a/client/src/components/musicVideo/PublishPostingPanel.test.jsx b/client/src/components/musicVideo/PublishPostingPanel.test.jsx
index 052db1cd42..4dc149c317 100644
--- a/client/src/components/musicVideo/PublishPostingPanel.test.jsx
+++ b/client/src/components/musicVideo/PublishPostingPanel.test.jsx
@@ -68,53 +68,111 @@ describe('PublishPostingPanel (#9282)', () => {
expect(publishing.prepare).toHaveBeenCalledWith('shorts', { cutId: 'kit-vertical' });
});
- it('fills a DistroKid release with the songwriter and AI parts, and remembers the songwriter on this device', () => {
- const publishing = hook({ platforms: { distrokid: { enabled: true, account: 'Example Artist' } } });
+ // A settings store like the server's: setPlatform merges a platform's change, as PUT /publish/platforms does.
+ const settingsStore = (platforms) => {
+ const store = { platforms };
+ store.setPlatform = vi.fn(async (target, change) => {
+ const current = store.platforms[target] || {};
+ store.platforms = { ...store.platforms, [target]: { ...current, ...change, ...(change.defaults ? { defaults: { ...current.defaults, ...change.defaults } } : {}) } };
+ return store.platforms;
+ });
+ return store;
+ };
+
+ it('fills a DistroKid release with the songwriter and AI parts, and keeps the songwriter in settings for every device', () => {
+ const store = settingsStore({ distrokid: { enabled: true, account: 'Example Artist', defaults: {} } });
const p = { ...project(), autonomousRun: { output: { lyrics: 'la la' } } };
- const { unmount } = render(<PublishPostingPanel project={p} publishing={publishing} />);
+ const { unmount } = render(<PublishPostingPanel project={p} publishing={hook({ platforms: store.platforms, setPlatform: store.setPlatform })} />);
expandAll();
const dk = row('DistroKid');
expect(within(dk).getByLabelText('Artist name')).toHaveAttribute('placeholder', 'Example Artist');
expect(dk).toHaveTextContent('as Example Artist');
expect(dk).not.toHaveTextContent('@Example Artist');
expect(within(dk).getByLabelText('Instrumental')).toBeChecked(); // no lyric cues
- fireEvent.change(within(dk).getByLabelText('Songwriter legal first name'), { target: { value: 'Alice' } });
- fireEvent.change(within(dk).getByLabelText('Songwriter legal last name'), { target: { value: 'Example' } });
+ const first = within(dk).getByLabelText('Songwriter legal first name');
+ fireEvent.change(first, { target: { value: 'Alice' } });
+ fireEvent.blur(first);
+ expect(store.setPlatform).toHaveBeenLastCalledWith('distrokid', { defaults: { songwriterFirst: 'Alice' } });
+ const last = within(dk).getByLabelText('Songwriter legal last name');
+ fireEvent.change(last, { target: { value: 'Example' } });
+ fireEvent.blur(last);
fireEvent.click(within(dk).getByLabelText('Explicit lyrics'));
+ const publishing = hook({ platforms: store.platforms });
fireEvent.click(within(dk).getByRole('button', { name: 'Fill draft' }));
- expect(publishing.prepare).toHaveBeenCalledWith('distrokid', { songwriterFirst: 'Alice', songwriterLast: 'Example', aiLyrics: true, explicit: true });
unmount();
- render(<PublishPostingPanel project={project()} publishing={hook()} />);
+ // Another project (or device) reads the same settings and starts filled in.
+ render(<PublishPostingPanel project={project()} publishing={hook({ platforms: store.platforms, setPlatform: store.setPlatform })} />);
expandAll();
expect(within(row('DistroKid')).getByLabelText('Songwriter legal first name')).toHaveValue('Alice');
+ expect(within(row('DistroKid')).getByLabelText('Songwriter legal last name')).toHaveValue('Example');
+ expect(publishing.prepare).not.toHaveBeenCalled();
+ });
+
+ it('sends the typed songwriter with the AI parts, and editing the artist name renames the DistroKid account', () => {
+ const store = settingsStore({ distrokid: { enabled: true, account: 'Example Artist', defaults: { songwriterFirst: 'Alice', songwriterLast: 'Example' } } });
+ const publishing = hook({ platforms: store.platforms, setPlatform: store.setPlatform });
+ render(<PublishPostingPanel project={{ ...project(), autonomousRun: { output: { lyrics: 'la la' } } }} publishing={publishing} />);
+ expandAll();
+ const dk = row('DistroKid');
+ 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 });
+ const artist = within(dk).getByLabelText('Artist name');
+ fireEvent.change(artist, { target: { value: 'New Name' } });
+ fireEvent.blur(artist);
+ expect(store.setPlatform).toHaveBeenLastCalledWith('distrokid', { account: 'New Name' });
});
- it('suggests a genre from the song and remembers the once-only DistroKid answers', () => {
- const publishing = hook({ platforms: { distrokid: { enabled: true, account: 'Example Artist' } } });
+ it('hands songwriter answers this device remembered before settings kept them over once', async () => {
+ localStorage.setItem('portos.musicVideo.distrokidSongwriter', JSON.stringify({ first: 'Alice', last: 'Example', language: 'Spanish' }));
+ const store = settingsStore({ distrokid: { enabled: true, account: null, defaults: {} } });
+ render(<PublishPostingPanel project={project()} publishing={hook({ platforms: store.platforms, setPlatform: store.setPlatform })} />);
+ expandAll();
+ expect(within(row('DistroKid')).getByLabelText('Songwriter legal first name')).toHaveValue('Alice');
+ expect(store.setPlatform).toHaveBeenCalledWith('distrokid', { defaults: { songwriterFirst: 'Alice', songwriterLast: 'Example', language: 'Spanish' } });
+ await act(async () => {});
+ expect(localStorage.getItem('portos.musicVideo.distrokidSongwriter')).toBeNull();
+ });
+
+ it('suggests a genre from the song and keeps only the answers that repeat across releases', () => {
+ const store = settingsStore({ distrokid: { enabled: true, account: 'Example Artist', defaults: {} } });
const p = { ...project(), autonomousRun: { output: { sunoStyle: 'dark synthwave, pop hooks' } } };
- const { unmount } = render(<PublishPostingPanel project={p} publishing={publishing} />);
+ const { unmount } = render(<PublishPostingPanel project={p} publishing={hook({ platforms: store.platforms, setPlatform: store.setPlatform })} />);
expandAll();
const dk = row('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' } });
+ const language = within(dk).getByLabelText('Language');
+ fireEvent.change(language, { target: { value: 'Spanish' } });
+ fireEvent.blur(language);
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: true }));
unmount();
- const later = hook({ platforms: { distrokid: { enabled: true, account: 'Example Artist' } } });
+ const later = hook({ platforms: store.platforms, setPlatform: store.setPlatform });
render(<PublishPostingPanel project={project()} publishing={later} />);
expandAll();
const again = row('DistroKid');
expect(within(again).getByLabelText('Language')).toHaveValue('Spanish');
- // New store profiles are asked per release, never carried to the next one.
+ // New store profiles and the genre are asked per release, never carried to the next one.
expect(within(again).getByLabelText('First release as this artist (new store profiles)')).not.toBeChecked();
+ expect(within(again).getByLabelText('Genre')).toHaveValue('');
fireEvent.click(within(again).getByRole('button', { name: 'Fill draft' }));
expect(later.prepare.mock.calls[0][1]).not.toHaveProperty('newArtistProfile');
- expect(within(again).getByLabelText('Genre')).toHaveValue('');
+ });
+
+ it('shows what each platform will post, or what is missing, before Fill draft', async () => {
+ vi.useFakeTimers();
+ const preview = vi.fn(async (target) => (target === 'x'
+ ? { ready: true, parts: [{ label: 'Post · with the 1080p video', text: 'The hook' }, { label: 'Reply 1', text: 'Full video: https://youtu.be/example' }] }
+ : { ready: false, problem: 'Write the TikTok caption first' }));
+ render(<PublishPostingPanel project={project()} publishing={hook({ enabledTargets: ['x', 'tiktok'], preview })} />);
+ expandAll();
+ await act(async () => { await vi.advanceTimersByTimeAsync(500); });
+ vi.useRealTimers();
+ expect(preview).toHaveBeenCalledWith('x', {});
+ expect(within(row('X thread')).getByText('What gets posted to X thread')).toBeInTheDocument();
+ expect(within(row('X thread')).getByText('Full video: https://youtu.be/example')).toBeInTheDocument();
+ expect(within(row('TikTok')).getByRole('status')).toHaveTextContent('Not ready to fill: Write the TikTok caption first');
});
it('asks before filling a second draft for a platform already posted to', () => {
@@ -194,10 +252,10 @@ describe('PublishPostingPanel (#9282)', () => {
const x = row('X thread');
const record = within(x).getByRole('button', { name: /Record/ });
expect(record).toBeDisabled();
- fireEvent.change(within(x).getByLabelText('Link to a X thread post made by hand'), { target: { value: 'https://x.com/antic/status/1' } });
+ fireEvent.change(within(x).getByLabelText('Link to the X thread post'), { target: { value: 'https://x.com/antic/status/1' } });
await act(async () => { fireEvent.click(record); });
expect(publishing.recordPost).toHaveBeenCalledWith('x', { url: 'https://x.com/antic/status/1' });
- expect(within(x).getByLabelText('Link to a X thread post made by hand')).toHaveValue('');
+ expect(within(x).getByLabelText('Link to the X thread post')).toHaveValue('');
});
it('folds a done platform with its status, marks one done without a link, and undoes a mark', async () => {
@@ -220,7 +278,7 @@ describe('PublishPostingPanel (#9282)', () => {
expect(within(done).getByText(/Marked done/)).toBeInTheDocument();
fireEvent.click(within(done).getByRole('button', { name: /DistroKid.*Done/ }));
// a link can still be added later, and the mark undone behind a confirm
- expect(within(done).getByLabelText('Link to a DistroKid post made by hand')).toBeInTheDocument();
+ expect(within(done).getByLabelText('Link to the DistroKid post')).toBeInTheDocument();
expect(within(done).queryByRole('button', { name: 'Mark DistroKid done' })).not.toBeInTheDocument();
fireEvent.click(within(done).getByRole('button', { name: 'Not done…' }));
fireEvent.click(within(done).getByRole('button', { name: 'Confirm marking DistroKid not done' }));
diff --git a/client/src/hooks/useMusicVideoPublishing.js b/client/src/hooks/useMusicVideoPublishing.js
index bc2f5588f0..7eaa5a53a6 100644
--- a/client/src/hooks/useMusicVideoPublishing.js
+++ b/client/src/hooks/useMusicVideoPublishing.js
@@ -3,6 +3,7 @@ import socket from '../services/socket';
import {
getMusicVideoPublishDrafts,
prepareMusicVideoPublishDraft,
+ previewMusicVideoPublishPost,
discardMusicVideoPublishDraft,
getMusicVideoPublishPlatforms,
updateMusicVideoPublishPlatforms,
@@ -22,7 +23,8 @@ const EMPTY_POSTING = { drafts: {}, busy: {}, errors: {} };
* where they post (with an optional account each), `history` their posts and
* ratings per platform across projects. `recordPost` saves a post made by hand
* (a link, or `{ posted: true }` to mark it done without one) or rates one;
- * `removePost` undoes the done mark.
+ * `removePost` undoes the done mark. `preview` reads what Fill draft would
+ * post, without opening anything.
*/
export default function useMusicVideoPublishing({ project, replaceProject } = {}) {
const projectId = project?.id || null;
@@ -92,6 +94,9 @@ export default function useMusicVideoPublishing({ project, replaceProject } = {}
.finally(() => setFor('busy', target, null));
};
+ // What Fill draft would post with these options; null when the preview itself failed.
+ const preview = (target, options = {}) => previewMusicVideoPublishPost(projectId, target, options, { silent: true }).catch(() => null);
+
const discard = (target) => {
const draft = drafts[target];
setFor('drafts', target, null);
@@ -100,7 +105,16 @@ export default function useMusicVideoPublishing({ project, replaceProject } = {}
const setPlatform = (target, change) => {
// Optimistic: the toggle flips at once and settles to the server's answer.
- setPlatforms((prev) => ({ ...(prev || {}), [target]: { ...(prev?.[target] || {}), ...change } }));
+ // `defaults` merges per answer (null forgets one), as the server does.
+ setPlatforms((prev) => {
+ const current = prev?.[target] || {};
+ const next = { ...current, ...change };
+ if (change.defaults) {
+ next.defaults = { ...(current.defaults || {}) };
+ for (const [k, v] of Object.entries(change.defaults)) { if (v == null || v === '') delete next.defaults[k]; else next.defaults[k] = v; }
+ }
+ return { ...(prev || {}), [target]: next };
+ });
return updateMusicVideoPublishPlatforms({ [target]: change })
.then((res) => { if (res?.platforms) setPlatforms(res.platforms); return res?.platforms || null; })
.catch(() => { loadPlatforms(); return null; });
@@ -116,5 +130,5 @@ export default function useMusicVideoPublishing({ project, replaceProject } = {}
const enabledTargets = Object.entries(platforms || {}).filter(([, p]) => p?.enabled).map(([t]) => t);
- return { drafts, busy, errors, prepare, discard, platforms, history, enabledTargets, setPlatform, recordPost, removePost };
+ return { drafts, busy, errors, prepare, preview, discard, platforms, history, enabledTargets, setPlatform, recordPost, removePost };
}
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index 614366124c..2659070bdb 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -294,6 +294,9 @@ export const musicVideoCoverFontUrl = (id) => `/api/music-video/publish/cover-fo
// summary, screenshot }. Manual posting is handled outside this wrapper.
export const prepareMusicVideoPublishDraft = (id, target, options = {}, reqOptions = {}) =>
request(`/music-video/${encodeURIComponent(id)}/publish/${encodeURIComponent(target)}/prepare`, { method: 'POST', body: JSON.stringify(options || {}), ...reqOptions });
+// What Fill draft would post, read-only → { ready, parts: [{ label, text }] } or { ready: false, problem }.
+export const previewMusicVideoPublishPost = (id, target, options = {}, reqOptions = {}) =>
+ request(`/music-video/${encodeURIComponent(id)}/publish/${encodeURIComponent(target)}/preview`, { method: 'POST', body: JSON.stringify(options || {}), ...reqOptions });
// A project's live drafts (state 'open' | 'closed') so a reloaded card rehydrates → { drafts }.
export const getMusicVideoPublishDrafts = (id, options = {}) =>
request(`/music-video/${encodeURIComponent(id)}/publish/drafts`, options);
diff --git a/docs/API.md b/docs/API.md
index 26c1763002..f2a24ae888 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -576,6 +576,7 @@ leaves finished ones alone. Agents outside PortOS call these with `node scripts/
| POST | `/human-actions/plans` | Schedule `{ planKey, title, steps: [{ title, dueAt, instructions[], content[{label,text}], links[{label,url}], priority }] }` (`dueAt` needs a UTC offset) |
| GET | `/music-video/:id/publish/promotion-plan` | A music video's open promotion steps |
| POST | `/music-video/:id/publish/promotion-plan` | Plan its promotion with one provider call `{ goal?, audience?, days?, providerId?, model? }` and schedule the steps |
+| POST | `/music-video/:id/publish/:target/preview` | What Fill draft would post for one platform (same body as prepare) → `{ ready, parts }` or `{ ready: false, problem }` |
### Notifications
diff --git a/server/lib/README.md b/server/lib/README.md
index f302a3ce6f..048c403a8b 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -682,7 +682,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `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. |
| `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. Shared by the DistroKid publish payload and the publish panel's genre pickers. |
+| `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. |
| `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.js
index e1a00067cd..6637a3c06e 100644
--- a/server/lib/distrokidGenres.js
+++ b/server/lib/distrokidGenres.js
@@ -5,6 +5,16 @@
* always pick another; the adapter matches DistroKid's option by its text.
*/
+/**
+ * The DistroKid answers that stay the same from release to release (the
+ * songwriter's legal name and role, language, Apple credits). PortOS keeps
+ * them in settings under Where you post, so every new project, on any device,
+ * starts with them filled in. The artist name is the DistroKid account itself.
+ */
+export const DISTROKID_REMEMBERED_OPTIONS = Object.freeze([
+ 'songwriterFirst', 'songwriterLast', 'songwriterRole', 'language', 'performerName', 'performerRole', 'producerName',
+]);
+
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',
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index f139395fad..2a0be87d1d 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -1,6 +1,7 @@
import { MUSIC_VIDEO_MEDIA_MODES } from './musicVideoMediaPolicy.js';
import { MUSIC_VIDEO_GRADE_PRESETS, MUSIC_VIDEO_GRADE_MAX_GRAIN } from './musicVideoGrade.js';
import { COVER_DESIGN_OPTIONS } from './musicVideoCoverOverlay.js';
+import { DISTROKID_REMEMBERED_OPTIONS } from './distrokidGenres.js';
/**
* Music Video production mode — Zod schemas + shared enums (issue #1760, Phase 1).
*
@@ -789,7 +790,13 @@ const publishUrl = z.string().url().max(500);
// #9287: which platforms the director posts to (opt-in), the account for each,
// and a post's link, reception and notes.
const publishPlatformEntry = z.object({ enabled: z.boolean(), account: z.string().max(100).nullable() }).partial().strict();
-export const musicVideoPublishPlatformsPatchSchema = z.object(Object.fromEntries(MUSIC_VIDEO_PUBLISH_TARGETS.map((t) => [t, publishPlatformEntry.optional()]))).strict();
+// DistroKid also keeps the release answers that repeat on every project ('' or null forgets one).
+const rememberedAnswer = z.string().max(100).nullable();
+const distrokidPlatformEntry = publishPlatformEntry.extend({
+ defaults: z.object(Object.fromEntries(DISTROKID_REMEMBERED_OPTIONS.map((k) => [k, rememberedAnswer]))).partial().strict(),
+}).partial().strict();
+export const musicVideoPublishPlatformsPatchSchema = z.object(Object.fromEntries(MUSIC_VIDEO_PUBLISH_TARGETS
+ .map((t) => [t, (t === 'distrokid' ? distrokidPlatformEntry : publishPlatformEntry).optional()]))).strict();
export const musicVideoPublishPostSchema = z.object({
url: publishUrl.nullable(),
// Marks the platform done without a link (a DistroKid upload has none until the stores go live).
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index 3e23f1a023..e161989717 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -132,7 +132,7 @@ import { startExcerptRender, attachExcerptRenderSseClient, cancelExcerptRender }
import { deleteExcerpt, addReviewNote, editReviewNote, deleteReviewNote } from '../services/musicVideo/excerptService.js';
import { suggestSocialCuts } from '../services/musicVideo/socialCuts.js';
import { getActivePublishKitBuild, startPublishKitBuild, attachPublishKitSseClient, cancelPublishKitBuild, draftPublishKitCopy, updatePublishKitCopy, selectPublishKitThumbnail } from '../services/musicVideo/publishKit.js';
-import { preparePublishDraft, discardPublishDraft, listPublishDrafts, recordPublishPost, removePublishPost } from '../services/musicVideo/publish/index.js';
+import { preparePublishDraft, previewPublishPost, discardPublishDraft, listPublishDrafts, recordPublishPost, removePublishPost } from '../services/musicVideo/publish/index.js';
import { getPublishPlatforms, updatePublishPlatforms, publishHistory } from '../services/musicVideo/publish/platforms.js';
import { listArtistStyles, saveArtistStyle, removeArtistStyle } from '../services/musicVideo/publish/artistStyles.js';
import { addCoverFont, coverFontPath, listCoverFonts, MAX_COVER_FONT_BYTES, removeCoverFont } from '../services/musicVideo/coverFonts.js';
@@ -1087,6 +1087,13 @@ router.delete('/:id/publish/posts/:target', asyncHandler(async (req, res) => {
res.json(await removePublishPost(req.params.id, target));
}));
+// What Fill draft would post, read-only: the rows of text and files, or what is still missing.
+router.post('/:id/publish/:target/preview', asyncHandler(async (req, res) => {
+ const target = validateRequest(musicVideoPublishTargetSchema, req.params.target);
+ const options = validateRequest(musicVideoPublishPrepareSchema, req.body || {});
+ res.json(await previewPublishPost(req.params.id, target, options));
+}));
+
router.post('/:id/publish/:target/prepare', asyncHandler(async (req, res) => {
const target = validateRequest(musicVideoPublishTargetSchema, req.params.target);
await requireProductionReviewer(req);
diff --git a/server/services/musicVideo/publish/index.js b/server/services/musicVideo/publish/index.js
index f78cd3a2cf..cda7ad6830 100644
--- a/server/services/musicVideo/publish/index.js
+++ b/server/services/musicVideo/publish/index.js
@@ -12,7 +12,7 @@ import { ServerError } from '../../../lib/errorHandler.js';
import { PATHS, ensureDir } from '../../../lib/fileUtils.js';
import { safeUnder } from '../../../lib/ffmpeg.js';
import { getProject, mutateProjectRecord } from '../projects.js';
-import { buildPublishPayload } from './payloads.js';
+import { buildPublishPayload, publishPreviewParts } from './payloads.js';
import { connectPortosBrowser, serializeBrowserOperation as serialize } from './browser.js';
import { assertAccount, assertPlatformEnabled, getPublishPlatforms, normalizePost } from './platforms.js';
import { youtubeAdapter, shortsAdapter } from './youtube.js';
@@ -197,6 +197,25 @@ export async function preparePublishDraft(projectId, target, options = {}, deps
});
}
+/**
+ * What Fill draft would post for `target` with these options, without opening
+ * anything: `{ ready: true, parts }` (the rows the director reads), or
+ * `{ ready: false, problem }` naming what is missing, in the words Fill draft
+ * would refuse with.
+ */
+export async function previewPublishPost(projectId, target, options = {}, deps = {}) {
+ if (!(deps.adapters || PUBLISH_ADAPTERS)[target]) throw new ServerError(`Unknown publish target: ${target}`, { status: 400, code: 'VALIDATION_ERROR' });
+ const project = await getProject(projectId);
+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ const platforms = deps.platforms || await getPublishPlatforms();
+ return Promise.resolve()
+ .then(() => buildPublishPayload(target, project, withPlatformDefaults(target, options, platforms)))
+ .then((payload) => ({ ready: true, parts: publishPreviewParts(target, project, payload) }), (err) => {
+ if (err?.status === 422 || err?.status === 409) return { ready: false, problem: err.message };
+ throw err;
+ });
+}
+
/** Close a draft without posting it. */
export async function discardPublishDraft(projectId, draftId, deps = {}) {
const draft = drafts.get(draftId);
diff --git a/server/services/musicVideo/publish/payloads.js b/server/services/musicVideo/publish/payloads.js
index f913e3449a..8df74487d7 100644
--- a/server/services/musicVideo/publish/payloads.js
+++ b/server/services/musicVideo/publish/payloads.js
@@ -274,3 +274,88 @@ export function buildPublishPayload(platform, project, options = {}) {
if (!build) throw new ServerError(`Unknown publish target: ${platform}`, { status: 400, code: 'VALIDATION_ERROR' });
return build(project, kitOf(project), options || {});
}
+
+const clock = (sec) => {
+ const s = Math.max(0, Math.floor(Number(sec) || 0));
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
+};
+const yesNo = (v) => (v ? 'Yes' : 'No');
+
+/** The 9:16 cut a payload posts, in words ("9:16 cut 0:40–1:10"). */
+function cutLabel(project, video) {
+ const cut = verticalCuts(project).find((c) => c.filename === video?.name);
+ return cut ? `${cut.id === 'kit-vertical' ? 'Kit vertical (fit)' : '9:16 cut'} ${clock(cut.startSec)}–${clock(cut.endSec)}` : '9:16 cut';
+}
+
+/**
+ * What one platform's post will say, as `[{ label, text }]` rows the director
+ * reads before Fill draft: every word PortOS types (titles, captions, the
+ * links it adds, the chapters it appends) and which file goes with it. Built
+ * from the same payload Fill draft posts, so the two cannot disagree.
+ */
+export function publishPreviewParts(platform, project, payload) {
+ const rows = [];
+ const add = (label, value) => { if (value != null && value !== '') rows.push({ label, text: String(value) }); };
+ const p = payload || {};
+ switch (platform) {
+ case 'youtube':
+ add('Video', 'The final render');
+ add('Title', p.title); add('Description', p.description);
+ add('Tags', p.tags?.length ? p.tags.join(', ') : 'None');
+ add('Thumbnail', p.thumbnail ? 'The one picked under Release assets' : 'None');
+ add('Captions', p.captions ? 'Lyric captions (SRT)' : 'None');
+ break;
+ case 'shorts':
+ add('Video', cutLabel(project, p.video)); add('Title', p.title); add('Description', p.description);
+ break;
+ case 'tiktok':
+ case 'instagram':
+ add('Video', cutLabel(project, p.video)); add('Caption', p.caption || '(empty)');
+ break;
+ case 'x':
+ (p.posts || []).forEach((post, i) => {
+ const media = post.media ? (post.media.dir === 'videos' ? ' · with the 1080p video' : ' · with an image') : '';
+ add(i === 0 ? `Post${media}` : `Reply ${i}${media}`, post.text);
+ });
+ break;
+ case 'reddit':
+ add('Where', `r/${p.subreddit}`);
+ add('Type', { video: 'Video upload (the final render)', self: 'Text post', link: 'Link post' }[p.kind]);
+ add('Title', p.title); add('Body', p.body); add('Link', p.url); add('First comment', p.firstComment);
+ break;
+ case 'stackerNews':
+ add('Where', `~${p.territory}`); add('Title', p.title); add('Link', p.url); add('Body', p.body); add('First comment', p.firstComment);
+ break;
+ case 'substack':
+ add('Publication', p.publication); add('Video at the top', p.videoUrl); add('Title', p.title); add('Subtitle', p.subtitle); add('Body', p.body);
+ add('Saved as', 'A draft in Substack (you choose who gets it)');
+ break;
+ case 'suno':
+ add('Song', p.songUrl); add('Caption', p.caption || '(empty)');
+ add('Cover', p.cover ? (p.cover.square ? 'The cover art' : 'The thumbnail, cut square') : 'None');
+ add('Pin to profile', yesNo(p.pin));
+ break;
+ case 'sunoHook':
+ add('Song', p.songUrl); add('Video', cutLabel(project, p.video));
+ add('Song window', `From ${clock(p.startSec)}`);
+ add('Caption', p.caption || '(empty)'); add("Suno's lyrics", p.showLyrics ? 'Shown' : 'Hidden');
+ break;
+ case 'distrokid': {
+ const ai = [p.ai?.music && 'music', p.ai?.vocals && 'all of the audio', p.ai?.lyrics && 'lyrics'].filter(Boolean);
+ add('Song title', p.title); add('Artist', p.artist);
+ add('Songwriter', `${p.songwriter?.first} ${p.songwriter?.last} (${{ both: 'music and lyrics', music: 'music', lyrics: 'lyrics' }[p.songwriterRole] || p.songwriterRole})`);
+ add('Release date', p.releaseDate || 'As soon as possible');
+ add('Genre', [p.genre || 'Not picked', p.secondaryGenre].filter(Boolean).join(' · '));
+ add('Language', p.language);
+ add('Explicit', yesNo(p.explicit)); add('Instrumental', yesNo(p.instrumental));
+ add('Made with AI', ai.length ? ai.join(', ') : 'Nothing');
+ add('Apple credits', `Performer ${p.credits?.performer}${p.credits?.performerRole ? ` (${p.credits.performerRole})` : ''} · Producer ${p.credits?.producer}`);
+ add('Cover', p.cover?.square ? 'The cover art' : 'The thumbnail, cut square');
+ if (p.previewStartSec != null) add('Store preview from', clock(p.previewStartSec));
+ break;
+ }
+ default:
+ break;
+ }
+ return rows;
+}
diff --git a/server/services/musicVideo/publish/payloads.test.js b/server/services/musicVideo/publish/payloads.test.js
index f3832b6626..bdc0250c3e 100644
--- a/server/services/musicVideo/publish/payloads.test.js
+++ b/server/services/musicVideo/publish/payloads.test.js
@@ -3,7 +3,7 @@
* director's per-platform options, or a 422 naming the missing piece.
*/
import { describe, expect, it } from 'vitest';
-import { buildPublishPayload } from './payloads.js';
+import { buildPublishPayload, publishPreviewParts } from './payloads.js';
import { captureMusicVideoEvidence } from '../../../lib/musicVideoDependencies.js';
const kit = (over = {}) => ({
@@ -168,4 +168,15 @@ describe('buildPublishPayload (#9282)', () => {
expect(buildPublishPayload('distrokid', { ...withCover, publishKit: kit({ thumbnail: null, coverArt: { filename: 'cover-1.jpg' } }) }, who).cover.name).toBe('cover-1.jpg');
expect(buildPublishPayload('suno', withCover, { songUrl: 'https://suno.com/song/87654321-dcba-4cba-8cba-cba987654321' }).cover.name).toBe('cover-1.jpg');
});
+
+ it('previews every word a post carries, including what PortOS adds (chapters, links, the Suno caption)', () => {
+ const rows = (target, p = project(), options = {}) => Object.fromEntries(publishPreviewParts(target, p, buildPublishPayload(target, p, options)).map((r) => [r.label, r.text]));
+ expect(rows('youtube').Description).toContain('Chapters\n0:00 Intro');
+ const x = rows('x');
+ expect(x['Post · with the 1080p video']).toBe('Watch this');
+ expect(x['Reply 1']).toBe('How it was made');
+ expect(x['Reply 2']).toBe('The song: https://suno.com/song/12345678-abcd-4abc-8abc-123456789abc\nFull video: https://youtu.be/abc');
+ expect(rows('suno').Caption).toBe('The story. Music video: https://youtu.be/abc');
+ expect(rows('tiktok')).toMatchObject({ Video: '9:16 cut 0:10–0:30', Caption: 'tt caption' });
+ });
});
diff --git a/server/services/musicVideo/publish/platforms.js b/server/services/musicVideo/publish/platforms.js
index 96aa13ddcc..ad9748c283 100644
--- a/server/services/musicVideo/publish/platforms.js
+++ b/server/services/musicVideo/publish/platforms.js
@@ -14,6 +14,7 @@ import { MUSIC_VIDEO_PUBLISH_TARGETS } from '../../../lib/musicVideoValidation.j
import { ServerError } from '../../../lib/errorHandler.js';
import { getSettings, updateSettingsWith } from '../../settings.js';
import { listProjects } from '../projects.js';
+import { DISTROKID_REMEMBERED_OPTIONS } from '../../../lib/distrokidGenres.js';
const SETTINGS_KEY = 'musicVideoPublishing';
const RECEPTIONS = ['good', 'mixed', 'poor'];
@@ -21,12 +22,29 @@ const RECENT_NOTES = 5;
const cleanAccount = (v) => (typeof v === 'string' ? v.trim().replace(/^@/, '').slice(0, 100) : '') || null;
-/** Every target's `{ enabled, account }`, defaulting to off. */
+// Release answers that repeat on every project, kept with the platform so any device refills them.
+const REMEMBERED = { distrokid: DISTROKID_REMEMBERED_OPTIONS };
+const SONGWRITER_ROLES = ['music', 'lyrics', 'both'];
+function cleanDefaults(target, stored) {
+ const keys = REMEMBERED[target] || [];
+ const source = stored && typeof stored === 'object' ? stored : {};
+ const out = {};
+ for (const key of keys) {
+ const v = typeof source[key] === 'string' ? source[key].trim().slice(0, 100) : '';
+ if (!v || (key === 'songwriterRole' && !SONGWRITER_ROLES.includes(v))) continue;
+ out[key] = v;
+ }
+ return out;
+}
+
+/** Every target's `{ enabled, account }` (plus `defaults` where answers repeat), defaulting to off. */
function normalizePlatforms(stored) {
const source = stored && typeof stored === 'object' ? stored : {};
return Object.fromEntries(MUSIC_VIDEO_PUBLISH_TARGETS.map((target) => {
const entry = source[target] && typeof source[target] === 'object' ? source[target] : {};
- return [target, { enabled: entry.enabled === true, account: cleanAccount(entry.account) }];
+ const platform = { enabled: entry.enabled === true, account: cleanAccount(entry.account) };
+ if (REMEMBERED[target]) platform.defaults = cleanDefaults(target, entry.defaults);
+ return [target, platform];
}));
}
@@ -35,7 +53,7 @@ export async function getPublishPlatforms() {
return normalizePlatforms(settings?.[SETTINGS_KEY]?.platforms);
}
-/** Merge `{ [target]: { enabled?, account? } }` into the saved platforms; resolves the full set. */
+/** Merge `{ [target]: { enabled?, account?, defaults? } }` into the saved platforms; resolves the full set. */
export async function updatePublishPlatforms(patch = {}) {
let next = null;
await updateSettingsWith((current) => {
@@ -45,6 +63,16 @@ export async function updatePublishPlatforms(patch = {}) {
if (!platforms[target] || !change || typeof change !== 'object') continue;
if (typeof change.enabled === 'boolean') platforms[target].enabled = change.enabled;
if ('account' in change) platforms[target].account = cleanAccount(change.account);
+ // Per key: a value saves it, an empty one forgets it.
+ if (REMEMBERED[target] && change.defaults && typeof change.defaults === 'object') {
+ const merged = { ...platforms[target].defaults };
+ for (const [key, value] of Object.entries(change.defaults)) {
+ if (!REMEMBERED[target].includes(key)) continue;
+ if (value == null || value === '') delete merged[key];
+ else merged[key] = value;
+ }
+ platforms[target].defaults = cleanDefaults(target, merged);
+ }
}
next = platforms;
return { ...current, [SETTINGS_KEY]: { ...section, platforms } };
diff --git a/server/services/musicVideo/publish/platforms.test.js b/server/services/musicVideo/publish/platforms.test.js
index 638de670dd..ea1874b9e5 100644
--- a/server/services/musicVideo/publish/platforms.test.js
+++ b/server/services/musicVideo/publish/platforms.test.js
@@ -25,6 +25,15 @@ describe('publishing platforms (#9287)', () => {
expect((await updatePublishPlatforms({ x: { account: '' } })).x).toEqual({ enabled: true, account: null });
});
+ it('keeps the DistroKid answers that repeat across releases, one at a time, and forgets a cleared one', async () => {
+ expect((await getPublishPlatforms()).distrokid.defaults).toEqual({});
+ await updatePublishPlatforms({ distrokid: { defaults: { songwriterFirst: ' Alice ', language: 'Spanish' } } });
+ const saved = await updatePublishPlatforms({ distrokid: { defaults: { songwriterLast: 'Example', language: null, newArtistProfile: true } } });
+ expect(saved.distrokid.defaults).toEqual({ songwriterFirst: 'Alice', songwriterLast: 'Example' });
+ expect((await getPublishPlatforms()).distrokid.defaults).toEqual({ songwriterFirst: 'Alice', songwriterLast: 'Example' });
+ expect(saved.x).not.toHaveProperty('defaults');
+ });
+
it('refuses disabled platforms and a known-wrong account only', () => {
expect(() => assertPlatformEnabled({ x: { enabled: false } }, 'x')).toThrow(expect.objectContaining({ code: 'PUBLISH_PLATFORM_DISABLED' }));
expect(() => assertPlatformEnabled({ x: { enabled: true } }, 'x')).not.toThrow();