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

feat(music-video): opt-in publishing platforms, per-platform accounts and post feedback

[._.]/ Adam Eivy1c18a2c1c272
diff --git a/client/src/components/musicVideo/PublishKitPanel.jsx b/client/src/components/musicVideo/PublishKitPanel.jsx
index 4ff53938d4..8a247a4009 100644
--- a/client/src/components/musicVideo/PublishKitPanel.jsx
+++ b/client/src/components/musicVideo/PublishKitPanel.jsx
@@ -62,8 +62,13 @@ function CopyField({ id, field, initial, onSave, disabled }) {
* platform's copy in one provider call from the director's own making-of
* notes, then edit and copy each field out.
*/
-export default function PublishKitPanel({ project, publishKit }) {
+export default function PublishKitPanel({ project, publishKit, enabledTargets }) {
const kit = project?.publishKit || {};
+ // Copy only for where the director posts (#9287); Suno's caption reuses the YouTube description.
+ const copyFields = enabledTargets
+ ? PUBLISH_FIELDS.filter(({ platform }) => enabledTargets.includes(platform) || (platform === 'youtube' && enabledTargets.includes('suno')))
+ : PUBLISH_FIELDS;
+ const noPlatforms = !!enabledTargets && copyFields.length === 0;
const idFor = (s) => `mv-publish-${project?.id}-${s}`;
const [notes, setNotes] = useState(kit.notes || '');
const [youtubeUrl, setYoutubeUrl] = useState(kit.links?.youtube || '');
@@ -176,14 +181,15 @@ export default function PublishKitPanel({ project, publishKit }) {
label="Writer" compact alwaysShowModel modelDisabled={availableModels.length === 0}
emptyProviderOption="Active provider (default)" emptyModelOption="Default model" disabled={publishKit.drafting} />
)}
- <button type="button" onClick={draft} disabled={publishKit.drafting}
+ <button type="button" onClick={draft} disabled={publishKit.drafting || noPlatforms}
className="flex items-center gap-1 bg-port-accent/20 text-port-accent disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0">
<Sparkles size={13} /> {publishKit.drafting ? 'Drafting…' : (kit.copy ? 'Redraft copy' : 'Draft copy')}
</button>
</div>
+ {noPlatforms && <p className="text-port-text-muted">Turn on a platform under Where you post to draft its copy.</p>}
{kit.copy && (
<div className="space-y-3" key={kit.copyDraftedAt || 'copy'}>
- {PUBLISH_FIELDS.map(({ platform, label, fields }) => (
+ {copyFields.map(({ platform, label, fields }) => (
<fieldset key={platform} className="space-y-1.5 rounded border border-port-border p-2">
<legend className="px-1 text-[11px] font-medium">{label}</legend>
{fields.map((field) => (
diff --git a/client/src/components/musicVideo/PublishPlatformsPanel.jsx b/client/src/components/musicVideo/PublishPlatformsPanel.jsx
new file mode 100644
index 0000000000..9b967d22a4
--- /dev/null
+++ b/client/src/components/musicVideo/PublishPlatformsPanel.jsx
@@ -0,0 +1,61 @@
+import { useState } from 'react';
+import { Globe } from 'lucide-react';
+import { PUBLISH_TARGETS } from './PublishPostingPanel.jsx';
+
+function historyLine(h) {
+ if (!h?.posts) return 'No posts yet';
+ const rated = ['good', 'mixed', 'poor'].filter((k) => h[k]).map((k) => `${h[k]} ${k}`);
+ return `${h.posts} post${h.posts === 1 ? '' : 's'}${rated.length ? ` · ${rated.join(' · ')}` : ''}`;
+}
+
+function AccountInput({ id, label, initial, onSave, disabled }) {
+ const [value, setValue] = useState(initial || '');
+ return (
+ <input id={id} value={value} disabled={disabled} aria-label={`${label} account`} placeholder="@handle (optional)"
+ onChange={(e) => setValue(e.target.value)}
+ onBlur={() => { if (value.trim() !== (initial || '')) onSave(value.trim() || null); }}
+ className="w-full sm:w-40 bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs min-h-[44px] sm:min-h-0 disabled:opacity-50" />
+ );
+}
+
+/**
+ * Where you post (#9287): every platform is opt-in. Turn on only the ones you
+ * use; name the account you post as (a dedicated account for this content,
+ * say) and a draft filled while signed in as someone else is refused where
+ * the platform shows who is signed in. Each row shows how your posts there
+ * were received, across every project, so you can learn what is worth it.
+ */
+export default function PublishPlatformsPanel({ publishing }) {
+ const { platforms, history, setPlatform } = publishing;
+ if (!platforms) return null;
+ const enabledCount = Object.values(platforms).filter((p) => p?.enabled).length;
+ return (
+ <section aria-label="Where you post" className="rounded-lg border border-port-border bg-port-card p-3 space-y-2 text-xs">
+ <h3 className="text-sm font-medium flex items-center gap-1.5"><Globe size={14} /> Where you post</h3>
+ <p className="text-port-text-muted">
+ {enabledCount ? 'Copy is drafted and posts are offered only for the platforms turned on here.' : 'No platforms yet. Turn on the ones you use; copy and posting cover only those.'}
+ </p>
+ <ul className="divide-y divide-port-border">
+ {PUBLISH_TARGETS.map(({ target, label }) => {
+ const p = platforms[target] || {};
+ const h = history?.[target];
+ const latest = h?.notes?.[0];
+ return (
+ <li key={target} className="py-1.5 flex flex-wrap items-center gap-2">
+ <label className="flex items-center gap-1.5 min-w-[9rem] min-h-[44px] sm:min-h-0">
+ <input type="checkbox" checked={!!p.enabled} onChange={(e) => setPlatform(target, { enabled: e.target.checked })} />
+ <span className="font-medium">{label}</span>
+ </label>
+ <AccountInput key={`${target}-${p.account || ''}`} id={`mv-platform-${target}-account`} label={label} initial={p.account}
+ disabled={!p.enabled} onSave={(account) => setPlatform(target, { account })} />
+ <div className="min-w-0 flex-1 text-[11px] text-port-text-muted">
+ <span>{historyLine(h)}</span>
+ {latest?.notes && <span className="block truncate" title={latest.notes}>Last note: {latest.notes}</span>}
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ </section>
+ );
+}
diff --git a/client/src/components/musicVideo/PublishPlatformsPanel.test.jsx b/client/src/components/musicVideo/PublishPlatformsPanel.test.jsx
new file mode 100644
index 0000000000..b82d52702a
--- /dev/null
+++ b/client/src/components/musicVideo/PublishPlatformsPanel.test.jsx
@@ -0,0 +1,66 @@
+/**
+ * Where you post (#9287): every platform is a toggle with an optional account,
+ * and each row shows how posts there were received across projects.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, fireEvent } from '@testing-library/react';
+import PublishPlatformsPanel from './PublishPlatformsPanel.jsx';
+import PublishKitPanel from './PublishKitPanel.jsx';
+
+vi.mock('../../hooks/useProviderModels.js', () => ({
+ default: () => ({ providers: [], selectedProviderId: '', selectedModel: '', availableModels: [], setSelectedProviderId: vi.fn(), setSelectedModel: vi.fn() }),
+}));
+
+const publishing = (over = {}) => ({
+ platforms: { x: { enabled: true, account: 'antic' }, reddit: { enabled: false, account: null } },
+ history: { reddit: { posts: 2, good: 0, mixed: 0, poor: 2, notes: [{ notes: 'poorly received', reception: 'poor' }] } },
+ setPlatform: vi.fn(async () => null),
+ ...over,
+});
+
+describe('PublishPlatformsPanel (#9287)', () => {
+ it('toggles platforms and saves an account on blur', () => {
+ const p = publishing();
+ render(<PublishPlatformsPanel publishing={p} />);
+ const reddit = screen.getByRole('checkbox', { name: 'Reddit' });
+ expect(reddit).not.toBeChecked();
+ expect(screen.getByRole('checkbox', { name: 'X thread' })).toBeChecked();
+ fireEvent.click(reddit);
+ expect(p.setPlatform).toHaveBeenCalledWith('reddit', { enabled: true });
+ const account = screen.getByLabelText('X thread account');
+ expect(account).toHaveValue('antic');
+ fireEvent.change(account, { target: { value: 'gof_music' } });
+ fireEvent.blur(account);
+ expect(p.setPlatform).toHaveBeenCalledWith('x', { account: 'gof_music' });
+ expect(screen.getByLabelText('Reddit account')).toBeDisabled();
+ });
+
+ it('shows what earlier posts taught', () => {
+ render(<PublishPlatformsPanel publishing={publishing()} />);
+ expect(screen.getByText('2 posts · 2 poor')).toBeInTheDocument();
+ expect(screen.getByText('Last note: poorly received')).toBeInTheDocument();
+ expect(screen.getAllByText('No posts yet').length).toBeGreaterThan(0);
+ });
+
+ it('renders nothing until the platforms load', () => {
+ const { container } = render(<PublishPlatformsPanel publishing={publishing({ platforms: null })} />);
+ expect(container).toBeEmptyDOMElement();
+ });
+});
+
+describe('PublishKitPanel copy per platform (#9287)', () => {
+ const kitHook = { building: false, progress: 0, build: vi.fn(), drafting: false, saving: false, draftCopy: vi.fn(), saveCopy: vi.fn(), selectThumbnail: vi.fn() };
+ const project = { id: 'mv-1', renderHistoryId: 'rh', publishKit: { copy: { youtube: { title: 'T' }, reddit: { title: 'R' } }, copyDraftedAt: 'x' } };
+
+ it('shows copy only for enabled platforms (YouTube too when Suno is on)', () => {
+ render(<PublishKitPanel project={project} publishKit={kitHook} enabledTargets={['suno', 'x']} />);
+ expect(screen.getByText('YouTube', { selector: 'legend' })).toBeInTheDocument();
+ expect(screen.getByText('X', { selector: 'legend' })).toBeInTheDocument();
+ expect(screen.queryByText('Reddit', { selector: 'legend' })).toBeNull();
+ });
+
+ it('holds the copy draft until a platform is on', () => {
+ render(<PublishKitPanel project={project} publishKit={kitHook} enabledTargets={[]} />);
+ expect(screen.getByRole('button', { name: /Redraft copy/ })).toBeDisabled();
+ });
+});
diff --git a/client/src/components/musicVideo/PublishPostingPanel.jsx b/client/src/components/musicVideo/PublishPostingPanel.jsx
index 5543bbb9c0..05c0c81b31 100644
--- a/client/src/components/musicVideo/PublishPostingPanel.jsx
+++ b/client/src/components/musicVideo/PublishPostingPanel.jsx
@@ -1,5 +1,5 @@
import { useState } from 'react';
-import { Send, ExternalLink, X as XIcon, LogIn } from 'lucide-react';
+import { Send, ExternalLink, X as XIcon, LogIn, Link as LinkIcon } from 'lucide-react';
// Where the release goes, in posting order: the full video first so every
// other post can link to it.
@@ -78,6 +78,48 @@ function TargetOptions({ target, kit, options, setOption, flairs, idFor }) {
return null;
}
+const RECEPTIONS = [['good', 'Good'], ['mixed', 'Mixed'], ['poor', 'Poor']];
+
+/** How a post landed: the director's rating and notes, which feed later copy drafts (#9287). */
+function PostFeedback({ idFor, label, post, onSave }) {
+ const [notes, setNotes] = useState(post.notes || '');
+ return (
+ <div className="space-y-1">
+ <div className="flex flex-wrap items-center gap-1.5" role="group" aria-label={`How the ${label} post was received`}>
+ <span className="text-[11px] text-port-text-muted">Reception</span>
+ {RECEPTIONS.map(([value, text]) => (
+ <button key={value} type="button" aria-pressed={post.reception === value}
+ onClick={() => onSave({ reception: post.reception === value ? null : value })}
+ className={`rounded border px-2 py-1 text-[11px] min-h-[44px] sm:min-h-0 ${post.reception === value ? 'border-port-accent text-port-accent bg-port-accent/10' : 'border-port-border'}`}>
+ {text}
+ </button>
+ ))}
+ </div>
+ <textarea id={idFor('notes')} aria-label={`Notes on the ${label} post`} value={notes} rows={2} maxLength={2000}
+ placeholder="What worked or didn't (feeds the next copy draft)"
+ onChange={(e) => setNotes(e.target.value)}
+ onBlur={() => { if (notes.trim() !== (post.notes || '')) onSave({ notes: notes.trim() || null }); }}
+ className={inputCls} />
+ </div>
+ );
+}
+
+/** Record a post made outside PortOS, so its reception can be tracked too. */
+function ManualLink({ idFor, label, onSave }) {
+ const [url, setUrl] = useState('');
+ 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="Posted by hand? Paste the link"
+ onChange={(e) => setUrl(e.target.value)} className={`${inputCls} 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
+ </button>
+ </div>
+ );
+}
+
function TargetRow({ project, kit, entry, publishing }) {
const { target, label, note } = entry;
const idFor = (key) => `mv-post-${project.id}-${target}-${key}`;
@@ -88,13 +130,14 @@ function TargetRow({ project, kit, entry, publishing }) {
const error = publishing.errors[target];
const posted = kit.posts?.[target];
const flairs = draft?.summary?.flairs;
+ const account = publishing.platforms?.[target]?.account;
const clean = Object.fromEntries(Object.entries(options).filter(([, v]) => v !== '' && v != null));
return (
<li className="rounded border border-port-border p-2 space-y-2">
<div className="flex flex-wrap items-start justify-between gap-2">
<div className="min-w-0">
- <div className="text-xs font-medium">{label}</div>
+ <div className="text-xs font-medium">{label}{account && <span className="font-normal text-port-text-muted"> as @{account}</span>}</div>
<div className="text-[11px] text-port-text-muted">{note}</div>
{posted?.url && (
<a href={posted.url} target="_blank" rel="noreferrer" className="text-[11px] text-port-accent flex items-center gap-1 break-all">
@@ -107,6 +150,9 @@ function TargetRow({ project, kit, entry, publishing }) {
{busy === 'prepare' ? 'Filling…' : (draft ? 'Fill again' : 'Fill draft')}
</button>
</div>
+ {posted
+ ? <PostFeedback key={posted.url || 'post'} idFor={idFor} label={label} post={posted} onSave={(body) => publishing.recordPost(target, body)} />
+ : <ManualLink idFor={idFor} label={label} onSave={(body) => publishing.recordPost(target, body)} />}
<TargetOptions target={target} kit={kit} options={options} setOption={setOption} flairs={flairs} idFor={idFor} />
{error && (
<div role="alert" className="text-[11px] text-port-error space-y-0.5">
@@ -147,12 +193,15 @@ function TargetRow({ project, kit, entry, publishing }) {
export default function PublishPostingPanel({ project, publishing }) {
const kit = project?.publishKit || {};
if (!kit.builtAt) return null;
+ // Only the platforms the director turned on (#9287), in posting order.
+ const targets = PUBLISH_TARGETS.filter((entry) => publishing.enabledTargets?.includes(entry.target));
return (
<section aria-label="Post the release" className="rounded-lg border border-port-border bg-port-card p-3 space-y-2 text-xs">
<h3 className="text-sm font-medium flex items-center gap-1.5"><Send size={14} /> Post the release</h3>
<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; nothing is posted until you review it and press Post.</p>
+ {!targets.length && <p className="text-port-text-muted">Turn on the platforms you use under Where you post to fill and post drafts here.</p>}
<ul className="space-y-2">
- {PUBLISH_TARGETS.map((entry) => <TargetRow key={entry.target} project={project} kit={kit} entry={entry} publishing={publishing} />)}
+ {targets.map((entry) => <TargetRow key={entry.target} project={project} kit={kit} entry={entry} publishing={publishing} />)}
</ul>
</section>
);
diff --git a/client/src/components/musicVideo/PublishPostingPanel.test.jsx b/client/src/components/musicVideo/PublishPostingPanel.test.jsx
index bd37ae10f2..2c83ba68b9 100644
--- a/client/src/components/musicVideo/PublishPostingPanel.test.jsx
+++ b/client/src/components/musicVideo/PublishPostingPanel.test.jsx
@@ -4,10 +4,11 @@
* explicit Post press, and keeps a sign-in refusal beside its platform.
*/
import { describe, it, expect, vi } from 'vitest';
-import { render, screen, fireEvent, within } from '@testing-library/react';
+import { render, screen, fireEvent, within, act } from '@testing-library/react';
import PublishPostingPanel, { PUBLISH_TARGETS } from './PublishPostingPanel.jsx';
-const hook = (over = {}) => ({ drafts: {}, busy: {}, errors: {}, prepare: vi.fn(), submit: vi.fn(), discard: vi.fn(), ...over });
+const ALL = ['youtube', 'suno', 'x', 'shorts', 'tiktok', 'instagram', 'reddit', 'stackerNews'];
+const hook = (over = {}) => ({ drafts: {}, busy: {}, errors: {}, prepare: vi.fn(), submit: vi.fn(), discard: vi.fn(), enabledTargets: ALL, platforms: {}, recordPost: vi.fn(async () => null), ...over });
const project = (kit = {}) => ({ id: 'mv-1', publishKit: { builtAt: '2026-01-01T00:00:00.000Z', thumbnails: ['t1.jpg'], ...kit } });
const row = (label) => screen.getByText(label, { selector: 'div' }).closest('li');
@@ -54,4 +55,38 @@ describe('PublishPostingPanel (#9282)', () => {
expect(alert).toHaveTextContent('Sign in to TikTok');
expect(alert).toHaveTextContent('https://www.tiktok.com/login');
});
+
+ it('offers only the platforms turned on, with the account posted as', () => {
+ render(<PublishPostingPanel project={project()} publishing={hook({ enabledTargets: ['x', 'youtube'], platforms: { x: { enabled: true, account: 'antic' } } })} />);
+ expect(screen.getAllByRole('listitem')).toHaveLength(2);
+ expect(screen.queryByText('Reddit', { selector: 'div' })).toBeNull();
+ expect(screen.getByText('as @antic')).toBeInTheDocument();
+ });
+
+ it('asks for platforms when none are on', () => {
+ render(<PublishPostingPanel project={project()} publishing={hook({ enabledTargets: [] })} />);
+ expect(screen.getByText(/Turn on the platforms you use/)).toBeInTheDocument();
+ expect(screen.queryAllByRole('listitem')).toHaveLength(0);
+ });
+
+ it('rates a posted post and records a post made by hand', async () => {
+ const publishing = hook({ enabledTargets: ['youtube', 'x'], recordPost: vi.fn(async () => ({ url: 'saved' })) });
+ render(<PublishPostingPanel project={project({ posts: { youtube: { url: 'https://youtu.be/abc', reception: 'good' } } })} publishing={publishing} />);
+ const yt = row('YouTube');
+ expect(within(yt).getByRole('button', { name: 'Good' })).toHaveAttribute('aria-pressed', 'true');
+ fireEvent.click(within(yt).getByRole('button', { name: 'Poor' }));
+ expect(publishing.recordPost).toHaveBeenCalledWith('youtube', { reception: 'poor' });
+ const notes = within(yt).getByLabelText('Notes on the YouTube post');
+ fireEvent.change(notes, { target: { value: 'slow start' } });
+ fireEvent.blur(notes);
+ expect(publishing.recordPost).toHaveBeenCalledWith('youtube', { notes: 'slow start' });
+
+ 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' } });
+ 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('');
+ });
});
diff --git a/client/src/components/musicVideo/stages/PublishStage.jsx b/client/src/components/musicVideo/stages/PublishStage.jsx
index 8268355e36..ea1433d794 100644
--- a/client/src/components/musicVideo/stages/PublishStage.jsx
+++ b/client/src/components/musicVideo/stages/PublishStage.jsx
@@ -1,16 +1,19 @@
import PublishKitPanel from '../PublishKitPanel.jsx';
import PublishPostingPanel from '../PublishPostingPanel.jsx';
+import PublishPlatformsPanel from '../PublishPlatformsPanel.jsx';
/**
* Publish: the release kit made from the final render (encodes, thumbnails,
* captions, chapters), the per-platform copy (#9281), and posting it through
- * the PortOS Browser with a review before every post (#9282).
+ * the PortOS Browser with a review before every post (#9282), only to the
+ * platforms the director turned on (#9287).
*/
export default function PublishStage({ board }) {
const { project, locked, publishKit, publishing } = board;
return (
<fieldset disabled={locked} className="min-w-0 space-y-3">
- <PublishKitPanel project={project} publishKit={publishKit} />
+ {publishing && <PublishPlatformsPanel publishing={publishing} />}
+ <PublishKitPanel project={project} publishKit={publishKit} enabledTargets={publishing?.enabledTargets} />
{publishing && <PublishPostingPanel project={project} publishing={publishing} />}
</fieldset>
);
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index bf940c100b..ee55081987 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -259,7 +259,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useMusicVideoAutoReview` | Opt-in automatic review/retries (#8988): start a run over a draft window with explicit review (`maxAttempts`) and paid-generation (`maxGenerations`) limits plus a vision reviewer; applies the project pushed on `music-video:auto-review` and submits the revised sections a run hands out through `submitSections` while the board is open. Returns `{ busy, action, start(startSec, endSec, limits, reviewer), resume(runId, limits?), stop(runId), cancel(runId) }`. | The Music Video excerpt panel. |
| `useMusicVideoExcerpts` | Draft excerpt render + timecoded review notes (#8986): a `useSseJobSlot` render job over a chosen `[startSec, endSec)` window (any terminal frame reloads the project, since the persisted excerpt shape lives server-side) plus add/edit/delete review-note calls that apply the fresh whole project from each response. Returns `{ rendering, progress, deletingId, noteBusyId, startExcerpt(startSec, endSec), cancelExcerpt(excerptId), attachRender(jobId, projectId), deleteExcerpt(excerptId), addNote(excerptId, {atSec, note, verdict?}), editNote(excerptId, noteId, patch), deleteNote(excerptId, noteId) }`. | The Music Video excerpt panel. |
| `useMusicVideoPublishKit` | Music Video publishing kit (#9281): a `useSseJobSlot` build job (encodes, thumbnails, captions, chapters) whose terminal frame reloads the project, plus the one-call copy draft, per-field copy edits and thumbnail choice, each applying the returned project. Returns `{ building, progress, build(), cancelBuild(), drafting, saving, draftCopy(body), saveCopy(patch), selectThumbnail(filename) }`. | The Music Video Publish stage. |
-| `useMusicVideoPublishing` | Music Video posting (#9282): per-platform drafts filled in the PortOS Browser. `prepare` returns the filled draft's summary and screenshot (a sign-in-required refusal is kept as the platform's error with its login URL), `submit` posts that reviewed draft and applies the returned project, `discard` closes it. Returns `{ drafts, busy, errors, prepare(target, options), submit(target), discard(target) }`. | The Music Video Publish stage's posting panel. |
+| `useMusicVideoPublishing` | Music Video posting (#9282): per-platform drafts filled in the PortOS Browser. `prepare` returns the filled draft's summary and screenshot (a sign-in-required refusal is kept as the platform's error with its login URL), `submit` posts that reviewed draft and applies the returned project, `discard` closes it. Platforms are opt-in (#9287): it loads the saved `platforms` (enabled + optional account each) and per-platform `history` (posts, reception tally, recent notes across projects); `setPlatform` toggles one optimistically and `recordPost` saves a hand-made post's link or a post's reception and notes. Returns `{ drafts, busy, errors, prepare(target, options), submit(target), discard(target), platforms, history, enabledTargets, setPlatform(target, change), recordPost(target, body) }`. | The Music Video Publish stage's posting panel. |
| `useMusicVideoModelSettings` | A project's saved render pins — video backend (local/Grok/fal.ai)/model/generation-mode/audio-reactive LoRA + the image-side frame pin — with the Video Gen catalog they read from. Optimistic-local + silent PATCH, rollback + toast on failure; `saving` gates the dependent generate buttons. Returns `{ models, modelsLoading, defaultModel, falEnabled, saving, settings, effectiveModelId, activeModel, audioReactiveModels, audioReactiveLoras, detectedAudioReactiveLora, audioReactiveReady, audioReactiveSelected, videoBlockedReason, change, changeFramePin }`. `videoBlockedReason` is the single "why can't I generate" string (an unavailable audio-reactive setup, or a fal.ai pin with no configured API key) shared by the disabled buttons, their tooltips, and the blocked-call toast. | The Music Video renderer selects and anything building a scene-clip job payload from them. |
| `useMusicVideoSceneMedia` | Both per-scene generation lanes (reference frame + scene clip) over `useSceneRenderLifecycle`, the frame/shot prompt builders (concept-style + visual-spec direction suffix), visual-spec reference-image conditioning with explicit unsupported-backend feedback (#8965), and the batch "generate the missing ones" actions. Returns `{ genScenes, genVideoScenes, conditioning, buildFramePrompt, buildShotPrompt, generateFrame, generateSceneVideo, continueSceneVideo, generateMissingFrames, generateMissingVideos }`. | The Music Video scene board — don't re-wire the two lanes or re-derive the i2v/a2v/extend payloads. |
| `useMusicVideoTakes` | Scene-take review + external-asset handoff for the Music Video board (#8965): serialized select / reject / note / gallery-import take mutations folded back as scene patches, the handoff manifest download, and the handoff import (gallery upload per file, then scene association by file tag with provider provenance). Returns `{ busy, selectTake, reviewTake, importTake, exportHandoff, importHandoffFiles }`. | The Music Video board's take strips, contact sheet and handoff row — don't re-sequence take mutations per call site. |
diff --git a/client/src/hooks/useMusicVideoPublishing.js b/client/src/hooks/useMusicVideoPublishing.js
index 970f6de228..5f16fbccc0 100644
--- a/client/src/hooks/useMusicVideoPublishing.js
+++ b/client/src/hooks/useMusicVideoPublishing.js
@@ -1,9 +1,12 @@
-import { useState } from 'react';
+import { useCallback, useEffect, useState } from 'react';
import toast from '../components/ui/Toast';
import {
prepareMusicVideoPublishDraft,
submitMusicVideoPublishDraft,
discardMusicVideoPublishDraft,
+ getMusicVideoPublishPlatforms,
+ updateMusicVideoPublishPlatforms,
+ recordMusicVideoPublishPost,
} from '../services/apiMusicVideo.js';
/**
@@ -12,12 +15,24 @@ import {
* and a screenshot) for the director to review; `submit` posts that same
* draft. Nothing posts without the second press. Errors are kept per platform
* so a sign-in prompt stays beside the platform that needs it.
+ *
+ * Platforms are opt-in (#9287): `platforms` is the director's saved choice of
+ * where they post (with an optional account each), `history` their posts and
+ * ratings per platform across projects. `recordPost` saves a post made by hand
+ * or rates one.
*/
export default function useMusicVideoPublishing({ project, replaceProject } = {}) {
const projectId = project?.id || null;
const [drafts, setDrafts] = useState({});
const [busy, setBusy] = useState({});
const [errors, setErrors] = useState({});
+ const [platforms, setPlatforms] = useState(null);
+ const [history, setHistory] = useState({});
+
+ const loadPlatforms = useCallback(() => getMusicVideoPublishPlatforms({ silent: true })
+ .then((res) => { setPlatforms(res?.platforms || {}); setHistory(res?.history || {}); })
+ .catch(() => setPlatforms((prev) => prev || {})), []);
+ useEffect(() => { loadPlatforms(); }, [loadPlatforms]);
const setFor = (setter, target, value) => setter((prev) => {
const next = { ...prev };
@@ -46,6 +61,7 @@ export default function useMusicVideoPublishing({ project, replaceProject } = {}
return submitMusicVideoPublishDraft(projectId, draft.draftId, { silent: true })
.then((res) => {
if (res?.project) replaceProject?.(res.project);
+ loadPlatforms();
setFor(setDrafts, target, null);
toast.success('Posted');
return res?.post || null;
@@ -65,5 +81,19 @@ export default function useMusicVideoPublishing({ project, replaceProject } = {}
if (draft) discardMusicVideoPublishDraft(projectId, draft.draftId, { silent: true }).catch(() => {});
};
- return { drafts, busy, errors, prepare, submit, discard };
+ const setPlatform = (target, change) => {
+ // Optimistic: the toggle flips at once and settles to the server's answer.
+ setPlatforms((prev) => ({ ...(prev || {}), [target]: { ...(prev?.[target] || {}), ...change } }));
+ return updateMusicVideoPublishPlatforms({ [target]: change })
+ .then((res) => { if (res?.platforms) setPlatforms(res.platforms); return res?.platforms || null; })
+ .catch(() => { loadPlatforms(); return null; });
+ };
+
+ const recordPost = (target, body) => recordMusicVideoPublishPost(projectId, target, body)
+ .then((res) => { if (res?.project) replaceProject?.(res.project); loadPlatforms(); return res?.post || null; })
+ .catch(() => null);
+
+ const enabledTargets = Object.entries(platforms || {}).filter(([, p]) => p?.enabled).map(([t]) => t);
+
+ return { drafts, busy, errors, prepare, submit, discard, platforms, history, enabledTargets, setPlatform, recordPost };
}
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index e469c7b6e7..58e2dfe6be 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -87,6 +87,9 @@ vi.mock('../services/apiMusicVideo.js', () => ({
prepareMusicVideoPublishDraft: vi.fn(),
submitMusicVideoPublishDraft: vi.fn(),
discardMusicVideoPublishDraft: vi.fn(),
+ getMusicVideoPublishPlatforms: vi.fn(async () => ({ platforms: {}, history: {} })),
+ updateMusicVideoPublishPlatforms: vi.fn(),
+ recordMusicVideoPublishPost: vi.fn(),
cancelMusicVideoExcerptRender: vi.fn(async () => ({ ok: true })),
deleteMusicVideoExcerpt: vi.fn(),
addMusicVideoExcerptNote: vi.fn(),
diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.js
index 4d1fb11af4..067540ce83 100644
--- a/client/src/services/apiMusicVideo.js
+++ b/client/src/services/apiMusicVideo.js
@@ -216,6 +216,13 @@ export const submitMusicVideoPublishDraft = (id, draftId, options = {}) =>
request(`/music-video/${encodeURIComponent(id)}/publish/drafts/${encodeURIComponent(draftId)}/submit`, { method: 'POST', ...options });
export const discardMusicVideoPublishDraft = (id, draftId, options = {}) =>
request(`/music-video/${encodeURIComponent(id)}/publish/drafts/${encodeURIComponent(draftId)}`, { method: 'DELETE', ...options });
+// Where the director posts (#9287): { platforms, history } and platform toggles;
+// a post's link, reception and notes → { project, post }.
+export const getMusicVideoPublishPlatforms = (options = {}) => request('/music-video/publish/platforms', options);
+export const updateMusicVideoPublishPlatforms = (patch, options = {}) =>
+ request('/music-video/publish/platforms', { method: 'PUT', body: JSON.stringify(patch || {}), ...options });
+export const recordMusicVideoPublishPost = (id, target, body, options = {}) =>
+ request(`/music-video/${encodeURIComponent(id)}/publish/posts/${encodeURIComponent(target)}`, { method: 'PUT', body: JSON.stringify(body || {}), ...options });
export const musicVideoExcerptRenderEventsUrl = (jobId) =>
`/api/music-video/excerpt/${encodeURIComponent(jobId)}/events`;
export const cancelMusicVideoExcerptRender = (jobId, options = {}) =>
diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.md
index eea86e1e8c..1d99115c02 100644
--- a/docs/features/product-surfaces.md
+++ b/docs/features/product-surfaces.md
@@ -110,7 +110,7 @@ An end-to-end creative production suite for authors, worldbuilders, filmmakers,
| **SongBook** | `/songbook` | Interactive chord charts, guitar tablature, lyric repertoire, and auto-scrolling practice sheet music. | — |
| **Creative Director** | `/creative-director` | Multi-scene episodic video production orchestrator: turn briefs into treatments, storyboards, render plans, and completed episodes. | — |
| **Creative Commissions** | `/creative-commission` | Standing briefs and scheduled/nightly autonomous media generation aligning with personal taste profiles and feedback. A universe and/or mood board can be picked as the style source: each run loads its style tags and reference images as the Creative Director's art-direction base, attaches those images to vision scene evaluation, and conditions local image renders on them. | — |
-| **Music Video Studio** | `/music-video` | A project opens on seven deep-linked stage tabs (`/music-video/:projectId/:stage` — `setup`, `cast-sets`, `board`, `produce`, `compose`, `review`, `publish`; a bottom tab bar on a phone) under a sticky header showing its progress, paid-generation spend against the cap, and the one next action for the stage it is in; the composition preview (or, without a composition document, the latest draft excerpt) is docked beside the Board, Compose and Review tabs, and scene cards seek it. Audio-reactive video creation, beat-detection synchronization, scene choreography, tempo alignment, and audience-driven pre-production treatments that direct each shot. Scenes are cutaways or lip-synced performance shots; a performance shot renders only on a verified source-audio provider (fal.ai MiniMax H3 lip-sync, 5–14.8s song slices placed at an exact edit in-point, cut from an optional full-length vocal stem when one is attached — uploaded, or separated from the song with a locally installed demucs) — Grok video is cutaway-only. The autopilot kickoff analyzes the song, imports the linked track's lyric sheet (its `[Verse]`/`[Chorus]` headers and stage directions kept as lyric markers that name the analysis sections and steer shot framing), separates the vocal, aligns every word with local whisper.cpp (large-v3-turbo, downloaded on first use), builds a Cast & Sets check-in (one creative-direction call that interprets the song, then a canonical character sheet, expression and looks sheets, one empty plate per set and in-set tests on the image queue, each later image conditioned on the character sheet; assembled into a self-contained sheet saved as a development artifact), stops for the director's review unless the brief auto-approves it, then plans against the approved references. Development artifacts (check-in sheets, animatics, treatments, storyboards; HTML/Markdown/MP4/PNG/JPG) are versioned per project, reviewed with notes and approve/request-changes, and viewed in a sandboxed viewer at `/music-video/:projectId/:stage/dev/:artifactId` (the stage-less `/music-video/:projectId/dev/:artifactId` still opens it). Draft excerpts are reviewed and selectively revised by hand, or by an opt-in auto-review run bounded by director-set review and paid-generation limits (a frame-only look never passes motion or audio sync). A server-owned production run (`/api/music-video/:id/production-runs`, #9066) plans an empty board, generates missing frames and clips only on a director-allowed image/video provider+model pool, hands the continuous draft to auto-review and dispatches its revisions — within explicit generation, review and (priced routes only) dollar limits, without the browser open, and never resuming on its own after a restart; the song is the sole audio unless a sound-design bed is explicitly chosen to mix under it. Draft excerpts can be re-framed as vertical or square social cuts with faded audio edges, from suggested hook windows (#9280). The Publish stage (#9281) builds a release kit from the final render: an X-sized 1080p, a 720p preview, a hook teaser, thumbnail candidates, lyric captions (SRT) and YouTube chapters. It also drafts every platform's copy in one director-triggered provider call from their own making-of notes, and every field stays editable. Posting (#9282) fills each platform's post (YouTube, Suno, an X thread, Shorts, TikTok, Instagram Reels, Reddit, Stacker News) in a new PortOS Browser tab with the director's signed-in sessions, shows a screenshot and summary of the filled draft, and posts only when the director presses Post for that draft; the posted links are kept on the project. | — |
+| **Music Video Studio** | `/music-video` | A project opens on seven deep-linked stage tabs (`/music-video/:projectId/:stage` — `setup`, `cast-sets`, `board`, `produce`, `compose`, `review`, `publish`; a bottom tab bar on a phone) under a sticky header showing its progress, paid-generation spend against the cap, and the one next action for the stage it is in; the composition preview (or, without a composition document, the latest draft excerpt) is docked beside the Board, Compose and Review tabs, and scene cards seek it. Audio-reactive video creation, beat-detection synchronization, scene choreography, tempo alignment, and audience-driven pre-production treatments that direct each shot. Scenes are cutaways or lip-synced performance shots; a performance shot renders only on a verified source-audio provider (fal.ai MiniMax H3 lip-sync, 5–14.8s song slices placed at an exact edit in-point, cut from an optional full-length vocal stem when one is attached — uploaded, or separated from the song with a locally installed demucs) — Grok video is cutaway-only. The autopilot kickoff analyzes the song, imports the linked track's lyric sheet (its `[Verse]`/`[Chorus]` headers and stage directions kept as lyric markers that name the analysis sections and steer shot framing), separates the vocal, aligns every word with local whisper.cpp (large-v3-turbo, downloaded on first use), builds a Cast & Sets check-in (one creative-direction call that interprets the song, then a canonical character sheet, expression and looks sheets, one empty plate per set and in-set tests on the image queue, each later image conditioned on the character sheet; assembled into a self-contained sheet saved as a development artifact), stops for the director's review unless the brief auto-approves it, then plans against the approved references. Development artifacts (check-in sheets, animatics, treatments, storyboards; HTML/Markdown/MP4/PNG/JPG) are versioned per project, reviewed with notes and approve/request-changes, and viewed in a sandboxed viewer at `/music-video/:projectId/:stage/dev/:artifactId` (the stage-less `/music-video/:projectId/dev/:artifactId` still opens it). Draft excerpts are reviewed and selectively revised by hand, or by an opt-in auto-review run bounded by director-set review and paid-generation limits (a frame-only look never passes motion or audio sync). A server-owned production run (`/api/music-video/:id/production-runs`, #9066) plans an empty board, generates missing frames and clips only on a director-allowed image/video provider+model pool, hands the continuous draft to auto-review and dispatches its revisions — within explicit generation, review and (priced routes only) dollar limits, without the browser open, and never resuming on its own after a restart; the song is the sole audio unless a sound-design bed is explicitly chosen to mix under it. Draft excerpts can be re-framed as vertical or square social cuts with faded audio edges, from suggested hook windows (#9280). The Publish stage (#9281) builds a release kit from the final render: an X-sized 1080p, a 720p preview, a hook teaser, thumbnail candidates, lyric captions (SRT) and YouTube chapters. It also drafts every platform's copy in one director-triggered provider call from their own making-of notes, and every field stays editable. Posting (#9282) fills each platform's post (YouTube, Suno, an X thread, Shorts, TikTok, Instagram Reels, Reddit, Stacker News) in a new PortOS Browser tab with the director's signed-in sessions, shows a screenshot and summary of the filled draft, and posts only when the director presses Post for that draft; the posted links are kept on the project. Platforms are opt-in (#9287): a "Where you post" list turns each one on (all start off) and optionally names the account posted as — X and Reddit drafts filled while signed in as someone else are refused. Copy is drafted and posts are offered only for enabled platforms. Each post (including one recorded by hand) can be rated good, mixed or poor with notes; ratings roll up per platform across projects and are passed to later copy drafts. | — |
| **Sharing & Conflict Resolution** | `/sharing`, `/sharing/duplicates`, `/sharing/conflicts` | Collaborative asset exchange via cloud storage buckets (Google Drive, Dropbox, iCloud, Syncthing) with duplicate reconciliation and conflict recovery journals. | — |
---
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index ee287770f6..d71deef783 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -549,6 +549,15 @@ export const musicVideoPublishThumbnailSchema = z.object({ filename: z.string().
export const MUSIC_VIDEO_PUBLISH_TARGETS = Object.freeze(['youtube', 'shorts', 'tiktok', 'instagram', 'x', 'reddit', 'stackerNews', 'suno']);
export const musicVideoPublishTargetSchema = z.enum(MUSIC_VIDEO_PUBLISH_TARGETS);
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();
+export const musicVideoPublishPostSchema = z.object({
+ url: publishUrl.nullable(),
+ reception: z.enum(['good', 'mixed', 'poor']).nullable(),
+ notes: z.string().max(2000).nullable(),
+}).partial().strict().refine((b) => Object.keys(b).length > 0, { message: 'url, reception or notes is required' });
export const musicVideoPublishPrepareSchema = z.object({
subreddit: z.string().max(40),
kind: z.enum(['self', 'link']),
diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.js
index 52ed7a143a..556979c105 100644
--- a/server/routes/musicVideo.js
+++ b/server/routes/musicVideo.js
@@ -41,6 +41,8 @@ import {
musicVideoPublishThumbnailSchema,
musicVideoPublishTargetSchema,
musicVideoPublishPrepareSchema,
+ musicVideoPublishPlatformsPatchSchema,
+ musicVideoPublishPostSchema,
musicVideoCodeGenerateSchema,
musicVideoExcerptNoteSchema,
musicVideoExcerptNoteUpdateSchema,
@@ -104,7 +106,8 @@ import { startExcerptRender, attachExcerptRenderSseClient, cancelExcerptRender }
import { deleteExcerpt, addReviewNote, editReviewNote, deleteReviewNote } from '../services/musicVideo/excerptService.js';
import { suggestSocialCuts } from '../services/musicVideo/socialCuts.js';
import { startPublishKitBuild, attachPublishKitSseClient, cancelPublishKitBuild, draftPublishKitCopy, updatePublishKitCopy, selectPublishKitThumbnail } from '../services/musicVideo/publishKit.js';
-import { preparePublishDraft, submitPublishDraft, discardPublishDraft } from '../services/musicVideo/publish/index.js';
+import { preparePublishDraft, submitPublishDraft, discardPublishDraft, recordPublishPost } from '../services/musicVideo/publish/index.js';
+import { getPublishPlatforms, updatePublishPlatforms, publishHistory } from '../services/musicVideo/publish/platforms.js';
import {
startRevision, resumeRevision, cancelRevision, releaseRevisionSection,
} from '../services/musicVideo/revisionService.js';
@@ -621,6 +624,25 @@ router.put('/:id/publish-kit/thumbnail', asyncHandler(async (req, res) => {
// --- Posting (#9282) ---
// Fill a platform's post in the PortOS Browser and return a screenshot; post
// only on a second, explicit request naming that live draft.
+// #9287: where the director posts (opt-in, optional account per platform),
+// with every platform's post history and ratings across projects.
+router.get('/publish/platforms', asyncHandler(async (req, res) => {
+ const [platforms, history] = await Promise.all([getPublishPlatforms(), publishHistory()]);
+ res.json({ platforms, history });
+}));
+
+router.put('/publish/platforms', asyncHandler(async (req, res) => {
+ const patch = validateRequest(musicVideoPublishPlatformsPatchSchema, req.body || {});
+ res.json({ platforms: await updatePublishPlatforms(patch) });
+}));
+
+// Record a post made by hand, or rate one: its link, reception and notes.
+router.put('/:id/publish/posts/:target', asyncHandler(async (req, res) => {
+ const target = validateRequest(musicVideoPublishTargetSchema, req.params.target);
+ const input = validateRequest(musicVideoPublishPostSchema, req.body || {});
+ res.json(await recordPublishPost(req.params.id, target, input));
+}));
+
router.post('/:id/publish/:target/prepare', asyncHandler(async (req, res) => {
const target = validateRequest(musicVideoPublishTargetSchema, req.params.target);
const options = validateRequest(musicVideoPublishPrepareSchema, req.body || {});
diff --git a/server/services/musicVideo/publish/index.js b/server/services/musicVideo/publish/index.js
index 4abda28a25..b10cb79576 100644
--- a/server/services/musicVideo/publish/index.js
+++ b/server/services/musicVideo/publish/index.js
@@ -10,7 +10,9 @@
* platform returns PUBLISH_LOGIN_REQUIRED; login, CAPTCHAs and 2FA are the
* director's to do in the PortOS Browser.
*
- * Posting results persist to `project.publishKit.posts[target] = { url, postedAt }`.
+ * Posting results persist to `project.publishKit.posts[target] = { url, postedAt }`;
+ * the director can add reception and notes, or record a post made by hand (#9287).
+ * Only platforms the director turned on can be prepared.
*/
import { randomUUID } from 'crypto';
import { existsSync } from 'fs';
@@ -21,6 +23,7 @@ import { safeUnder } from '../../../lib/ffmpeg.js';
import { getProject, mutateProjectRecord } from '../projects.js';
import { buildPublishPayload } from './payloads.js';
import { connectPortosBrowser } from './browser.js';
+import { assertAccount, assertPlatformEnabled, getPublishPlatforms, normalizePost } from './platforms.js';
import { youtubeAdapter, shortsAdapter } from './youtube.js';
import { tiktokAdapter } from './tiktok.js';
import { instagramAdapter } from './instagram.js';
@@ -91,6 +94,8 @@ async function withCovers(target, payload, deps) {
export async function preparePublishDraft(projectId, target, options = {}, deps = {}) {
const adapter = (deps.adapters || PUBLISH_ADAPTERS)[target];
if (!adapter) throw new ServerError(`Unknown publish target: ${target}`, { status: 400, code: 'VALIDATION_ERROR' });
+ const platforms = deps.platforms || await getPublishPlatforms();
+ assertPlatformEnabled(platforms, target);
const project = await getProject(projectId);
if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
let payload = resolveFiles(buildPublishPayload(target, project, options));
@@ -102,6 +107,8 @@ export async function preparePublishDraft(projectId, target, options = {}, deps
try {
await page.bringToFront();
const summary = await adapter.prepare(page, payload);
+ // A dedicated account for this content must be the one signed in (where the adapter can tell).
+ assertAccount(platforms, target, summary?.account);
const shot = await page.screenshot({ type: 'jpeg', quality: 70 }).catch(() => null);
const id = `mvpub-${randomUUID()}`;
const draft = { id, projectId, target, payload, page, browser, summary, createdAt: Date.now() };
@@ -145,3 +152,14 @@ export async function discardPublishDraft(projectId, draftId) {
await closeDraft(draft);
return true;
}
+
+/** Record or update one platform's post by hand: its link, reception (good/mixed/poor) and notes. */
+export async function recordPublishPost(projectId, target, input = {}) {
+ const { project } = await mutateProjectRecord(projectId, (current) => {
+ const kit = current.publishKit && typeof current.publishKit === 'object' ? current.publishKit : {};
+ const posts = { ...(kit.posts || {}) };
+ posts[target] = normalizePost(posts[target], input);
+ return { project: { ...current, publishKit: { ...kit, posts } } };
+ });
+ return { project, post: project.publishKit.posts[target] };
+}
diff --git a/server/services/musicVideo/publish/index.test.js b/server/services/musicVideo/publish/index.test.js
index 83f28c86e5..867c046d2d 100644
--- a/server/services/musicVideo/publish/index.test.js
+++ b/server/services/musicVideo/publish/index.test.js
@@ -14,7 +14,9 @@ vi.mock('../../../lib/paths.js', async (importOriginal) => makePathsProxy(await
const { PATHS } = await import('../../../lib/paths.js');
const projects = await import('../projects.js');
-const { preparePublishDraft, submitPublishDraft, discardPublishDraft } = await import('./index.js');
+const { preparePublishDraft, submitPublishDraft, discardPublishDraft, recordPublishPost } = await import('./index.js');
+
+const platforms = { stackerNews: { enabled: true, account: null }, youtube: { enabled: true, account: null }, x: { enabled: true, account: 'antic' } };
afterAll(() => cleanupTempDataRoots());
@@ -53,7 +55,7 @@ describe('publish drafts (#9282)', () => {
const id = await readyProject();
const { connect, pages } = fakeBrowser();
const adapters = { stackerNews: adapter() };
- const draft = await preparePublishDraft(id, 'stackerNews', { territory: 'art' }, { connect, adapters });
+ const draft = await preparePublishDraft(id, 'stackerNews', { territory: 'art' }, { connect, adapters, platforms });
expect(draft).toMatchObject({ target: 'stackerNews', summary: { title: 'Song' } });
expect(draft.screenshot).toMatch(/^data:image\/jpeg;base64,/);
expect(adapters.stackerNews.submit).not.toHaveBeenCalled();
@@ -69,8 +71,8 @@ describe('publish drafts (#9282)', () => {
const id = await readyProject();
const { connect, pages } = fakeBrowser();
const adapters = { stackerNews: adapter() };
- const first = await preparePublishDraft(id, 'stackerNews', {}, { connect, adapters });
- const second = await preparePublishDraft(id, 'stackerNews', {}, { connect, adapters });
+ const first = await preparePublishDraft(id, 'stackerNews', {}, { connect, adapters, platforms });
+ const second = await preparePublishDraft(id, 'stackerNews', {}, { connect, adapters, platforms });
expect(pages[0].closed).toBe(true);
await expect(submitPublishDraft(id, first.draftId, { adapters })).rejects.toMatchObject({ code: 'PUBLISH_DRAFT_MISSING' });
expect(await discardPublishDraft(id, second.draftId)).toBe(true);
@@ -82,7 +84,7 @@ describe('publish drafts (#9282)', () => {
const id = await readyProject();
const { connect, pages } = fakeBrowser();
const adapters = { stackerNews: adapter() };
- const draft = await preparePublishDraft(id, 'stackerNews', {}, { connect, adapters });
+ const draft = await preparePublishDraft(id, 'stackerNews', {}, { connect, adapters, platforms });
pages[0].closed = true;
await expect(submitPublishDraft(id, draft.draftId, { adapters })).rejects.toMatchObject({ code: 'PUBLISH_DRAFT_MISSING' });
expect(adapters.stackerNews.submit).not.toHaveBeenCalled();
@@ -93,21 +95,52 @@ describe('publish drafts (#9282)', () => {
const { connect, pages } = fakeBrowser();
const err = Object.assign(new Error('Sign in'), { status: 409, code: 'PUBLISH_LOGIN_REQUIRED' });
const adapters = { stackerNews: adapter({ prepare: vi.fn(async () => { throw err; }) }) };
- await expect(preparePublishDraft(id, 'stackerNews', {}, { connect, adapters })).rejects.toBe(err);
+ await expect(preparePublishDraft(id, 'stackerNews', {}, { connect, adapters, platforms })).rejects.toBe(err);
expect(pages[0].closed).toBe(true);
});
+ it('refuses a platform the director has not turned on, before opening a tab', async () => {
+ const id = await readyProject();
+ const { connect } = fakeBrowser();
+ await expect(preparePublishDraft(id, 'stackerNews', {}, { connect, adapters: { stackerNews: adapter() }, platforms: { stackerNews: { enabled: false } } }))
+ .rejects.toMatchObject({ status: 409, code: 'PUBLISH_PLATFORM_DISABLED' });
+ expect(connect).not.toHaveBeenCalled();
+ });
+
+ it('closes a draft filled while signed in to the wrong account', async () => {
+ const id = await readyProject();
+ await projects.mutateProjectRecord(id, (current) => ({ project: { ...current, publishKit: { ...current.publishKit, exports: [{ kind: 'x-1080p', filename: 'x.mp4' }], copy: { x: { hook: 'hi' } } } } }));
+ await mkdir(PATHS.videos, { recursive: true });
+ await writeFile(join(PATHS.videos, 'x.mp4'), 'x');
+ const { connect, pages } = fakeBrowser();
+ const adapters = { x: adapter({ label: 'X', prepare: vi.fn(async () => ({ account: 'someone_else' })) }) };
+ await expect(preparePublishDraft(id, 'x', {}, { connect, adapters, platforms })).rejects.toMatchObject({ status: 409, code: 'PUBLISH_WRONG_ACCOUNT' });
+ expect(pages[0].closed).toBe(true);
+ adapters.x.prepare = vi.fn(async () => ({ account: 'Antic' }));
+ await expect(preparePublishDraft(id, 'x', {}, { connect, adapters, platforms })).resolves.toMatchObject({ target: 'x' });
+ });
+
+ it('records a post made by hand, then its reception and notes', async () => {
+ const id = await readyProject();
+ const first = await recordPublishPost(id, 'reddit', { url: 'https://www.reddit.com/r/x/comments/1' });
+ expect(first.post).toMatchObject({ url: 'https://www.reddit.com/r/x/comments/1' });
+ expect(first.post.postedAt).toBeTruthy();
+ const rated = await recordPublishPost(id, 'reddit', { reception: 'poor', notes: 'poorly received' });
+ expect(rated.post).toMatchObject({ url: 'https://www.reddit.com/r/x/comments/1', reception: 'poor', notes: 'poorly received', postedAt: first.post.postedAt });
+ expect(rated.project.publishKit.posts.reddit.reception).toBe('poor');
+ });
+
it('resolves release files to paths, and 422s before opening a tab when one is missing', async () => {
const id = await readyProject();
await projects.mutateProjectRecord(id, (current) => ({ project: { ...current, publishKit: { ...current.publishKit, master: { filename: 'master.mp4' }, copy: { youtube: { title: 'Song' } } } } }));
const { connect } = fakeBrowser();
const adapters = { youtube: adapter({ label: 'YouTube' }) };
- await expect(preparePublishDraft(id, 'youtube', {}, { connect, adapters })).rejects.toMatchObject({ status: 422, code: 'PUBLISH_ASSET_MISSING' });
+ await expect(preparePublishDraft(id, 'youtube', {}, { connect, adapters, platforms })).rejects.toMatchObject({ status: 422, code: 'PUBLISH_ASSET_MISSING' });
expect(connect).not.toHaveBeenCalled();
await mkdir(PATHS.videos, { recursive: true });
await writeFile(join(PATHS.videos, 'master.mp4'), 'x');
- await preparePublishDraft(id, 'youtube', {}, { connect, adapters });
+ await preparePublishDraft(id, 'youtube', {}, { connect, adapters, platforms });
expect(adapters.youtube.prepare.mock.calls[0][1].video.path).toBe(join(PATHS.videos, 'master.mp4'));
});
});
diff --git a/server/services/musicVideo/publish/platforms.js b/server/services/musicVideo/publish/platforms.js
new file mode 100644
index 0000000000..cd9b03d2a2
--- /dev/null
+++ b/server/services/musicVideo/publish/platforms.js
@@ -0,0 +1,111 @@
+/**
+ * Music Video publishing (#9287): WHERE the director posts, and what they
+ * learned from posting there.
+ *
+ * Every platform is opt-in (`settings.musicVideoPublishing.platforms[target]
+ * = { enabled, account }`), off until the director turns it on, so the Publish
+ * stage never offers to post everywhere. `account` optionally names the
+ * handle they post as; adapters that can read the signed-in account refuse a
+ * mismatch. Each post they make (or record by hand) can carry a reception
+ * rating and notes; `publishHistory` rolls those up across every project so
+ * the director, and the copy prompt, can see what landed.
+ */
+import { MUSIC_VIDEO_PUBLISH_TARGETS } from '../../../lib/musicVideoValidation.js';
+import { ServerError } from '../../../lib/errorHandler.js';
+import { getSettings, updateSettingsWith } from '../../settings.js';
+import { listProjects } from '../projects.js';
+
+const SETTINGS_KEY = 'musicVideoPublishing';
+const RECEPTIONS = ['good', 'mixed', 'poor'];
+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. */
+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) }];
+ }));
+}
+
+export async function getPublishPlatforms() {
+ const settings = await getSettings().catch(() => ({}));
+ return normalizePlatforms(settings?.[SETTINGS_KEY]?.platforms);
+}
+
+/** Merge `{ [target]: { enabled?, account? } }` into the saved platforms; resolves the full set. */
+export async function updatePublishPlatforms(patch = {}) {
+ let next = null;
+ await updateSettingsWith((current) => {
+ const section = current?.[SETTINGS_KEY] && typeof current[SETTINGS_KEY] === 'object' ? current[SETTINGS_KEY] : {};
+ const platforms = normalizePlatforms(section.platforms);
+ for (const [target, change] of Object.entries(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);
+ }
+ next = platforms;
+ return { ...current, [SETTINGS_KEY]: { ...section, platforms } };
+ });
+ return next;
+}
+
+/** Refuse a platform the director has not turned on. */
+export function assertPlatformEnabled(platforms, target) {
+ if (!platforms?.[target]?.enabled) {
+ throw new ServerError(`${target} is not one of your publishing platforms — turn it on under "Where you post" first`, { status: 409, code: 'PUBLISH_PLATFORM_DISABLED', context: { target } });
+ }
+}
+
+/** Refuse a draft filled while signed in as someone other than the configured account. */
+export function assertAccount(platforms, target, detected) {
+ const want = platforms?.[target]?.account;
+ const have = cleanAccount(detected);
+ if (want && have && want.toLowerCase() !== have.toLowerCase()) {
+ throw new ServerError(`The PortOS Browser is signed in to ${target} as @${have}, not @${want} — switch accounts and fill again`, {
+ status: 409, code: 'PUBLISH_WRONG_ACCOUNT', context: { target, expected: want, signedInAs: have },
+ });
+ }
+}
+
+/** A post record with only the known fields, or null when `input` names nothing. */
+export function normalizePost(existing = {}, input = {}) {
+ const post = { ...(existing && typeof existing === 'object' ? existing : {}) };
+ if ('url' in input) post.url = typeof input.url === 'string' && input.url.trim() ? input.url.trim() : null;
+ if ('reception' in input) post.reception = RECEPTIONS.includes(input.reception) ? input.reception : null;
+ if ('notes' in input) post.notes = typeof input.notes === 'string' && input.notes.trim() ? input.notes.trim().slice(0, 2000) : null;
+ if (!post.postedAt && post.url) post.postedAt = new Date().toISOString();
+ if ('reception' in input || 'notes' in input) post.ratedAt = new Date().toISOString();
+ return post;
+}
+
+/**
+ * Per platform, across every project: how many posts, how they were received,
+ * and the most recent notes (newest first). Pure over `projects`.
+ */
+function summarizePublishHistory(projects = []) {
+ const history = Object.fromEntries(MUSIC_VIDEO_PUBLISH_TARGETS.map((t) => [t, { posts: 0, good: 0, mixed: 0, poor: 0, notes: [] }]));
+ for (const project of projects) {
+ const posts = project?.publishKit?.posts;
+ if (!posts || typeof posts !== 'object') continue;
+ for (const [target, post] of Object.entries(posts)) {
+ const h = history[target];
+ if (!h || !post || typeof post !== 'object') continue;
+ h.posts += 1;
+ if (RECEPTIONS.includes(post.reception)) h[post.reception] += 1;
+ if (post.notes || post.reception) h.notes.push({ project: project.name || 'Untitled', reception: post.reception || null, notes: post.notes || '', at: post.ratedAt || post.postedAt || null });
+ }
+ }
+ for (const h of Object.values(history)) {
+ h.notes.sort((a, b) => String(b.at || '').localeCompare(String(a.at || '')));
+ h.notes = h.notes.slice(0, RECENT_NOTES);
+ }
+ return history;
+}
+
+/** Post history per platform across every project (or across `projects` when given). */
+export async function publishHistory(projects = null) {
+ return summarizePublishHistory(projects || await listProjects().catch(() => []));
+}
diff --git a/server/services/musicVideo/publish/platforms.test.js b/server/services/musicVideo/publish/platforms.test.js
new file mode 100644
index 0000000000..638de670dd
--- /dev/null
+++ b/server/services/musicVideo/publish/platforms.test.js
@@ -0,0 +1,49 @@
+/**
+ * Where the director posts (#9287): platforms are opt-in, the account check
+ * only fires when both sides are known, and post ratings roll up per platform.
+ */
+import { afterAll, describe, expect, it } from 'vitest';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../../lib/mockPathsDataRoot.js';
+import { vi } from 'vitest';
+
+vi.mock('../../../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), {
+ dataRoot: () => lazyTempDataRoot('portos-mv-platforms-'),
+}));
+
+const { getPublishPlatforms, updatePublishPlatforms, assertAccount, assertPlatformEnabled, publishHistory } = await import('./platforms.js');
+
+afterAll(() => cleanupTempDataRoots());
+
+describe('publishing platforms (#9287)', () => {
+ it('starts with every platform off and saves toggles and accounts', async () => {
+ const initial = await getPublishPlatforms();
+ expect(Object.values(initial).every((p) => p.enabled === false && p.account === null)).toBe(true);
+ const saved = await updatePublishPlatforms({ x: { enabled: true, account: '@antic' }, reddit: { enabled: false }, myspace: { enabled: true } });
+ expect(saved.x).toEqual({ enabled: true, account: 'antic' });
+ expect(saved.myspace).toBeUndefined();
+ expect((await getPublishPlatforms()).x).toEqual({ enabled: true, account: 'antic' });
+ expect((await updatePublishPlatforms({ x: { account: '' } })).x).toEqual({ enabled: true, account: null });
+ });
+
+ 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();
+ const platforms = { x: { enabled: true, account: 'antic' }, tiktok: { enabled: true, account: null } };
+ expect(() => assertAccount(platforms, 'x', 'other')).toThrow(expect.objectContaining({ code: 'PUBLISH_WRONG_ACCOUNT' }));
+ expect(() => assertAccount(platforms, 'x', '@ANTIC')).not.toThrow();
+ expect(() => assertAccount(platforms, 'x', null)).not.toThrow(); // the adapter can't tell
+ expect(() => assertAccount(platforms, 'tiktok', 'anyone')).not.toThrow(); // no account configured
+ });
+
+ it('rolls post ratings up per platform, newest notes first', async () => {
+ const history = await publishHistory([
+ { name: 'Song A', publishKit: { posts: { reddit: { url: 'u', reception: 'poor', notes: 'downvoted', ratedAt: '2026-01-01' }, x: { url: 'u', reception: 'good', ratedAt: '2026-01-02' } } } },
+ { name: 'Song B', publishKit: { posts: { reddit: { url: 'u', reception: 'mixed', notes: 'a few comments', ratedAt: '2026-02-01' }, youtube: { url: 'u' } } } },
+ { name: 'No kit' },
+ ]);
+ expect(history.reddit).toMatchObject({ posts: 2, poor: 1, mixed: 1, good: 0 });
+ expect(history.reddit.notes.map((n) => n.notes)).toEqual(['a few comments', 'downvoted']);
+ expect(history.youtube).toMatchObject({ posts: 1, notes: [] });
+ expect(history.x.good).toBe(1);
+ });
+});
diff --git a/server/services/musicVideo/publish/reddit.js b/server/services/musicVideo/publish/reddit.js
index 7bbd668b96..601690b48a 100644
--- a/server/services/musicVideo/publish/reddit.js
+++ b/server/services/musicVideo/publish/reddit.js
@@ -28,7 +28,7 @@ export const redditAdapter = {
};
}, payload.subreddit));
if (!info.user) throw loginRequired(label, `${BASE}/login`);
- return { subreddit: payload.subreddit, kind: payload.kind, title: payload.title, flairText: payload.flairText, rules: info.rules, flairs: info.flairs };
+ return { account: info.user, subreddit: payload.subreddit, kind: payload.kind, title: payload.title, flairText: payload.flairText, rules: info.rules, flairs: info.flairs };
},
async submit(page, payload) {
const result = await step(label, 'post', () => page.evaluate(async (p) => {
diff --git a/server/services/musicVideo/publish/x.js b/server/services/musicVideo/publish/x.js
index 3da748e42b..609378b261 100644
--- a/server/services/musicVideo/publish/x.js
+++ b/server/services/musicVideo/publish/x.js
@@ -17,6 +17,7 @@ export const xAdapter = {
await step(label, 'open the composer', () => page.goto(COMPOSE_URL, { waitUntil: 'domcontentloaded', timeout: T }));
await page.waitForTimeout(4000);
if (/\/login|\/i\/flow/.test(page.url())) throw loginRequired(label, COMPOSE_URL);
+ const account = await page.evaluate(() => (document.querySelector('[data-testid=AppTabBar_Profile_Link]')?.getAttribute('href') || '').replace(/^\//, '') || null).catch(() => null);
for (const [i, post] of payload.posts.entries()) {
const editor = `[data-testid=tweetTextarea_${i}]`;
if (i > 0) await step(label, `add post ${i + 1}`, () => page.locator('[data-testid=addButton]').click({ timeout: T }));
@@ -37,7 +38,7 @@ export const xAdapter = {
return button && button.getAttribute('aria-disabled') !== 'true' && !uploading;
}, null, { timeout: 600_000 }));
const lengths = await page.evaluate((n) => Array.from({ length: n }, (_, i) => document.querySelector(`[data-testid=tweetTextarea_${i}]`)?.innerText.length ?? 0), payload.posts.length);
- return { posts: payload.posts.length, lengths };
+ return { account, posts: payload.posts.length, lengths };
},
async submit(page, payload) {
await step(label, 'post the thread', () => page.locator('[data-testid=tweetButton]').click({ timeout: T }));
diff --git a/server/services/musicVideo/publishKit.js b/server/services/musicVideo/publishKit.js
index c7a694f157..bf24320a16 100644
--- a/server/services/musicVideo/publishKit.js
+++ b/server/services/musicVideo/publishKit.js
@@ -211,20 +211,27 @@ function spentUsd(project) {
}
/**
- * Draft every platform's copy in ONE provider call the director asked for.
+ * Draft the copy for every platform the director posts to, in ONE provider call they asked for.
* `notes` (their making-of story) is saved with the kit so a redraft reuses it.
*/
export async function draftPublishKitCopy(projectId, { providerId = null, model = null, notes = '', links = {} } = {}, deps = {}) {
const project = await requireProject(projectId);
+ const { getPublishPlatforms, publishHistory } = await import('./publish/platforms.js');
+ const enabled = deps.platforms || await getPublishPlatforms();
+ // Only where the director posts (#9287); Suno's caption reuses the YouTube description.
+ const platforms = PUBLISH_PLATFORMS.filter((p) => enabled[p]?.enabled || (p === 'youtube' && enabled.suno?.enabled));
+ if (!platforms.length) throw kitError(409, 'PUBLISH_NO_PLATFORMS', 'Turn on at least one platform under "Where you post" before drafting copy');
+ const history = deps.history || await publishHistory().catch(() => ({}));
+ const lessons = Object.entries(history).flatMap(([platform, h]) => (h?.notes || []).map((n) => ({ platform, ...n })));
const { resolveProviderAndModel, runPromptThroughProvider } = deps.runner || await import('../promptRunner.js');
const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
if (!provider) throw kitError(503, 'NO_PROVIDER', 'No AI provider is available to draft the copy');
- const prompt = buildPublishCopyPrompt(project, { notes, spentUsd: spentUsd(project), links });
+ const prompt = buildPublishCopyPrompt(project, { notes, spentUsd: spentUsd(project), links, platforms, lessons });
const { text } = await runPromptThroughProvider({ provider, model: selectedModel, prompt, source: 'music-video-publish-copy' });
- const copy = parsePublishCopy(text);
+ const copy = parsePublishCopy(text, platforms);
if (!copy) throw kitError(502, 'PUBLISH_COPY_UNPARSEABLE', 'The copy draft came back without usable JSON — try again or another model');
return mutateProjectRecord(projectId, (current) => {
const kit = projectPublishKit(current);
- return { project: { ...current, publishKit: { ...kit, copy, notes, links: { ...(kit.links || {}), ...links }, copyDraftedAt: new Date().toISOString() } } };
+ return { project: { ...current, publishKit: { ...kit, copy: { ...(kit.copy || {}), ...copy }, notes, links: { ...(kit.links || {}), ...links }, copyDraftedAt: new Date().toISOString() } } };
});
}
diff --git a/server/services/musicVideo/publishKit.test.js b/server/services/musicVideo/publishKit.test.js
index 4bd2aa0d48..7aeb2d3aef 100644
--- a/server/services/musicVideo/publishKit.test.js
+++ b/server/services/musicVideo/publishKit.test.js
@@ -70,6 +70,8 @@ describe('publishing kit build (#9281)', () => {
});
});
+const ALL_ON = Object.fromEntries(['youtube', 'shorts', 'x', 'tiktok', 'instagram', 'reddit', 'stackerNews', 'suno'].map((t) => [t, { enabled: true }]));
+
describe('publishing kit copy (#9281)', () => {
const runner = (text) => ({
resolveProviderAndModel: vi.fn(async () => ({ provider: { id: 'p1' }, selectedModel: 'm1' })),
@@ -78,7 +80,7 @@ describe('publishing kit copy (#9281)', () => {
it('drafts every platform from one call and keeps each field editable', async () => {
const { id } = await projects.createProject({ name: 'Example Song' });
- const deps = { runner: runner(JSON.stringify({ youtube: { title: 'A title', description: 'desc', tags: ['music'] }, x: { hook: 'a hook', story: 'story' } })) };
+ const deps = { platforms: ALL_ON, history: {}, runner: runner(JSON.stringify({ youtube: { title: 'A title', description: 'desc', tags: ['music'] }, x: { hook: 'a hook', story: 'story' } })) };
const { project } = await kit.draftPublishKitCopy(id, { notes: 'made it on a Sunday', links: { youtube: 'https://example.com/v' } }, deps);
expect(deps.runner.runPromptThroughProvider).toHaveBeenCalledTimes(1);
expect(deps.runner.runPromptThroughProvider.mock.calls[0][0]).toMatchObject({ source: 'music-video-publish-copy' });
@@ -90,10 +92,34 @@ describe('publishing kit copy (#9281)', () => {
it('reports an unusable draft instead of saving it', async () => {
const { id } = await projects.createProject({ name: 'Example Song' });
- await expect(kit.draftPublishKitCopy(id, {}, { runner: runner('sorry, no JSON') })).rejects.toMatchObject({ status: 502, code: 'PUBLISH_COPY_UNPARSEABLE' });
+ await expect(kit.draftPublishKitCopy(id, {}, { platforms: ALL_ON, history: {}, runner: runner('sorry, no JSON') })).rejects.toMatchObject({ status: 502, code: 'PUBLISH_COPY_UNPARSEABLE' });
expect((await projects.getProject(id)).publishKit).toBeFalsy();
});
+ it('drafts only the platforms the director posts to, keeps other copy, and passes their ratings on', async () => {
+ const { id } = await projects.createProject({ name: 'Example Song' });
+ await projects.mutateProjectRecord(id, (current) => ({ project: { ...current, publishKit: { copy: { reddit: { title: 'kept', body: '' } } } } }));
+ const deps = {
+ platforms: { x: { enabled: true }, suno: { enabled: true }, reddit: { enabled: false } },
+ history: { x: { notes: [{ reception: 'good', notes: 'the cost hook worked' }] }, reddit: { notes: [{ reception: 'poor', notes: 'downvoted' }] } },
+ runner: runner(JSON.stringify({ youtube: { title: 'T' }, x: { hook: 'h' }, reddit: { title: 'ignored' } })),
+ };
+ const { project } = await kit.draftPublishKitCopy(id, {}, deps);
+ const prompt = deps.runner.runPromptThroughProvider.mock.calls[0][0].prompt;
+ expect(prompt).toContain('"x":{');
+ expect(prompt).toContain('"youtube":{'); // Suno's caption reuses it
+ expect(prompt).not.toContain('"reddit":{');
+ expect(prompt).toContain('x (good): the cost hook worked');
+ expect(prompt).not.toContain('downvoted');
+ expect(Object.keys(project.publishKit.copy).sort()).toEqual(['reddit', 'x', 'youtube']);
+ expect(project.publishKit.copy.reddit.title).toBe('kept');
+ });
+
+ it('refuses to draft before any platform is turned on', async () => {
+ const { id } = await projects.createProject({ name: 'Example Song' });
+ await expect(kit.draftPublishKitCopy(id, {}, { platforms: {}, history: {}, runner: runner('{}') })).rejects.toMatchObject({ status: 409, code: 'PUBLISH_NO_PLATFORMS' });
+ });
+
it('only selects a thumbnail the kit built', async () => {
const { id } = await projects.createProject({ name: 'Example Song' });
await projects.mutateProjectRecord(id, (current) => ({ project: { ...current, publishKit: { thumbnails: ['a.jpg', 'b.jpg'], thumbnail: 'a.jpg' } } }));
diff --git a/server/services/musicVideo/publishKitText.js b/server/services/musicVideo/publishKitText.js
index 1f7b7f667b..a2db4dbe70 100644
--- a/server/services/musicVideo/publishKitText.js
+++ b/server/services/musicVideo/publishKitText.js
@@ -117,12 +117,26 @@ const LIMITS = { youtubeTitle: 100, shortsTitle: 100, xHook: 280, redditTitle: 3
const str = (v, max) => (typeof v === 'string' && v.trim() ? v.trim().slice(0, max) : '');
+// The JSON shape each platform's copy takes in the prompt.
+const COPY_SPECS = {
+ youtube: '"youtube":{"title":"<=100 chars","description":"2 short paragraphs + the links given","tags":["8-15 lowercase tags"]}',
+ shorts: '"shorts":{"title":"<=100 chars, ends with #shorts","description":"1-2 sentences + the full video URL if given"}',
+ x: '"x":{"hook":"<=280 chars, one surprising claim, no links","story":"the making-of as a long post"}',
+ tiktok: '"tiktok":{"caption":"1-2 sentences + 4-6 hashtags"}',
+ instagram: '"instagram":{"caption":"1-2 sentences + 4-6 hashtags"}',
+ reddit: '"reddit":{"title":"<=300 chars","body":"markdown: what it is, what it cost, how it was made"}',
+ stackerNews: '"stackerNews":{"title":"<=80 chars","body":"markdown, personal tone"}',
+};
+
/**
* The copy prompt. `notes` is the director's own making-of story and
* `spentUsd` the generation spend; both are the facts the copy may claim —
- * nothing else about cost or process is invented.
+ * nothing else about cost or process is invented. `platforms` limits the
+ * draft to where the director posts (#9287); `lessons` are their own ratings
+ * of earlier posts (`{ platform, reception, notes }`), so the copy leans
+ * toward what landed and away from what didn't.
*/
-export function buildPublishCopyPrompt(project, { notes = '', spentUsd = null, links = {} } = {}) {
+export function buildPublishCopyPrompt(project, { notes = '', spentUsd = null, links = {}, platforms = PUBLISH_PLATFORMS, lessons = [] } = {}) {
const lyrics = timedLines(project).map((l) => l.text).join('\n');
const chapters = chaptersText(buildChapters(project));
const facts = [
@@ -131,6 +145,11 @@ export function buildPublishCopyPrompt(project, { notes = '', spentUsd = null, l
links.youtube ? `Full video URL: ${links.youtube}` : null,
links.song ? `Song URL: ${links.song}` : null,
].filter(Boolean).join('\n');
+ const wanted = PUBLISH_PLATFORMS.filter((p) => platforms.includes(p));
+ const lessonText = lessons
+ .filter((l) => wanted.includes(l.platform) && (l.reception || l.notes))
+ .map((l) => `- ${l.platform}${l.reception ? ` (${l.reception})` : ''}: ${l.notes || 'no notes'}`)
+ .join('\n');
return [
'You write release copy for a music video the user made. Write in the first person as the artist: plain, specific, no hype words, no emoji, no hashtags except where a field asks for them.',
'Use ONLY facts given below. Never invent costs, tools, durations or events.',
@@ -138,31 +157,27 @@ export function buildPublishCopyPrompt(project, { notes = '', spentUsd = null, l
fenceBlock('Making-of notes from the artist', notes || '(none)', 6000),
fenceBlock('Lyrics', lyrics || '(no timed lyrics)', 4000),
chapters ? fenceBlock('Chapters', chapters, 1200) : '',
+ lessonText ? fenceBlock('How the artist rated earlier posts (lean toward what landed, avoid what did not)', lessonText, 3000) : '',
'Return ONLY a JSON object with exactly these keys:',
- '{"youtube":{"title":"<=100 chars","description":"2 short paragraphs + the links given","tags":["8-15 lowercase tags"]},',
- ' "shorts":{"title":"<=100 chars, ends with #shorts","description":"1-2 sentences + the full video URL if given"},',
- ' "x":{"hook":"<=280 chars, one surprising claim, no links","story":"the making-of as a long post"},',
- ' "tiktok":{"caption":"1-2 sentences + 4-6 hashtags"},',
- ' "instagram":{"caption":"1-2 sentences + 4-6 hashtags"},',
- ' "reddit":{"title":"<=300 chars","body":"markdown: what it is, what it cost, how it was made"},',
- ' "stackerNews":{"title":"<=80 chars","body":"markdown, personal tone"}}',
+ `{${wanted.map((p) => COPY_SPECS[p]).join(',\n ')}}`,
].filter(Boolean).join('\n\n');
}
-/** The model's JSON reply as `{ platform: { field: text } }`, clipped to each platform's limits; null when unusable. */
-export function parsePublishCopy(text) {
+/** The model's JSON reply as `{ platform: { field: text } }` for `platforms`, clipped to each platform's limits; null when unusable. */
+export function parsePublishCopy(text, platforms = PUBLISH_PLATFORMS) {
const { value } = extractJson(text, { blockType: 'object' });
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
const v = (k) => (value[k] && typeof value[k] === 'object' ? value[k] : {});
- const copy = {
- youtube: { title: str(v('youtube').title, LIMITS.youtubeTitle), description: str(v('youtube').description, 5000), tags: (Array.isArray(v('youtube').tags) ? v('youtube').tags : []).map((t) => str(t, 60)).filter(Boolean).slice(0, 20) },
- shorts: { title: str(v('shorts').title, LIMITS.shortsTitle), description: str(v('shorts').description, 5000) },
- x: { hook: str(v('x').hook, LIMITS.xHook), story: str(v('x').story, 25000) },
- tiktok: { caption: str(v('tiktok').caption, LIMITS.caption) },
- instagram: { caption: str(v('instagram').caption, LIMITS.caption) },
- reddit: { title: str(v('reddit').title, LIMITS.redditTitle), body: str(v('reddit').body, 40000) },
- stackerNews: { title: str(v('stackerNews').title, LIMITS.stackerNewsTitle), body: str(v('stackerNews').body, 40000) },
+ const all = {
+ youtube: () => ({ title: str(v('youtube').title, LIMITS.youtubeTitle), description: str(v('youtube').description, 5000), tags: (Array.isArray(v('youtube').tags) ? v('youtube').tags : []).map((t) => str(t, 60)).filter(Boolean).slice(0, 20) }),
+ shorts: () => ({ title: str(v('shorts').title, LIMITS.shortsTitle), description: str(v('shorts').description, 5000) }),
+ x: () => ({ hook: str(v('x').hook, LIMITS.xHook), story: str(v('x').story, 25000) }),
+ tiktok: () => ({ caption: str(v('tiktok').caption, LIMITS.caption) }),
+ instagram: () => ({ caption: str(v('instagram').caption, LIMITS.caption) }),
+ reddit: () => ({ title: str(v('reddit').title, LIMITS.redditTitle), body: str(v('reddit').body, 40000) }),
+ stackerNews: () => ({ title: str(v('stackerNews').title, LIMITS.stackerNewsTitle), body: str(v('stackerNews').body, 40000) }),
};
+ const copy = Object.fromEntries(PUBLISH_PLATFORMS.filter((p) => platforms.includes(p)).map((p) => [p, all[p]()]));
const filled = Object.values(copy).some((fields) => Object.values(fields).some((f) => (Array.isArray(f) ? f.length : f)));
return filled ? copy : null;
}