Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(music-video): post the release through the PortOS Browser with a review before every post
[._.]/ Adam Eivya91f9efa887a
diff --git a/client/src/components/musicVideo/PublishPostingPanel.jsx b/client/src/components/musicVideo/PublishPostingPanel.jsxnew file mode 100644index 0000000000..e390a607cb--- /dev/null+++ b/client/src/components/musicVideo/PublishPostingPanel.jsx@@ -0,0 +1,159 @@+import { useState } from 'react';+import { Send, ExternalLink, X as XIcon, LogIn } from 'lucide-react';++// Where the release goes, in posting order: the full video first so every+// other post can link to it.+export const PUBLISH_TARGETS = [+ { target: 'youtube', label: 'YouTube', note: 'The final render, with chapters, thumbnail and captions' },+ { target: 'suno', label: 'Suno', note: 'Publishes the song with the cover and a link to the video' },+ { target: 'x', label: 'X thread', note: 'Hook with the 1080p video, then the story, prompt and links' },+ { target: 'shorts', label: 'YouTube Shorts', note: 'The newest 9:16 social cut' },+ { target: 'tiktok', label: 'TikTok', note: 'The newest 9:16 social cut, labelled AI-generated' },+ { target: 'instagram', label: 'Instagram Reels', note: 'The newest 9:16 social cut, with the AI label' },+ { target: 'reddit', label: 'Reddit', note: 'A text or link post to one subreddit' },+ { target: 'stackerNews', label: 'Stacker News', note: 'A link post to the full video' },+];++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';++const summaryRows = (summary) => Object.entries(summary || {})+ .filter(([, v]) => v != null && v !== '' && (typeof v !== 'object' || (Array.isArray(v) && v.every((x) => typeof x === 'string'))))+ .map(([k, v]) => [k, Array.isArray(v) ? v.join(' · ') : String(v)]);++function TargetOptions({ target, kit, options, setOption, flairs, idFor }) {+ 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>+ {input}+ </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} />);+ 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} />);++ if (target === 'reddit') {+ return (+ <div className="grid sm:grid-cols-2 gap-2">+ {text('subreddit', 'Subreddit', 'SunoAI')}+ {field('kind', 'Post type',+ <select id={idFor('kind')} value={options.kind || 'self'} onChange={(e) => setOption('kind', e.target.value)} className={inputCls}>+ <option value="self">Text post</option>+ <option value="link">Link to the full video</option>+ </select>)}+ {flairs?.length > 0 && field('flairId', 'Flair',+ <select id={idFor('flairId')} value={options.flairId || ''} onChange={(e) => setOption('flairId', e.target.value)} className={inputCls}>+ <option value="">No flair</option>+ {flairs.map((f) => <option key={f.id} value={f.id}>{f.text}</option>)}+ </select>)}+ <div className="sm:col-span-2">{area('firstComment', 'First comment (optional)')}</div>+ </div>+ );+ }+ if (target === 'stackerNews') {+ return <div className="grid sm:grid-cols-2 gap-2">{text('territory', 'Territory', 'art')}<div className="sm:col-span-2">{area('firstComment', 'First comment (optional)')}</div></div>;+ }+ if (target === 'suno') {+ return (+ <div className="grid sm:grid-cols-2 gap-2 items-end">+ {text('songUrl', 'Song URL (the take to publish)', kit.links?.song || 'https://suno.com/song/…')}+ <label className="flex items-center gap-1.5 text-xs min-h-[44px] sm:min-h-0">+ <input type="checkbox" checked={options.pin !== false} onChange={(e) => setOption('pin', e.target.checked)} /> Pin to profile+ </label>+ </div>+ );+ }+ if (target === 'x') {+ return (+ <div className="space-y-2">+ {area('prompt', 'Prompt reply (optional, e.g. the prompt that started it)')}+ {kit.thumbnails?.length > 0 && field('storyImage', 'Image on the story reply (optional)',+ <select id={idFor('storyImage')} value={options.storyImage || ''} onChange={(e) => setOption('storyImage', e.target.value)} className={inputCls}>+ <option value="">None</option>+ {kit.thumbnails.map((name) => <option key={name} value={name}>{name}</option>)}+ </select>)}+ </div>+ );+ }+ return null;+}++function TargetRow({ project, kit, entry, publishing }) {+ const { target, label, note } = entry;+ const idFor = (key) => `mv-post-${project.id}-${target}-${key}`;+ const [options, setOptions] = useState({});+ const setOption = (key, value) => setOptions((prev) => ({ ...prev, [key]: value }));+ const draft = publishing.drafts[target];+ const busy = publishing.busy[target];+ const error = publishing.errors[target];+ const posted = kit.posts?.[target];+ const flairs = draft?.summary?.flairs;+ 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-[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">+ <ExternalLink size={11} /> Posted {posted.postedAt ? new Date(posted.postedAt).toLocaleDateString() : ''}: {posted.url}+ </a>+ )}+ </div>+ <button type="button" onClick={() => publishing.prepare(target, clean)} disabled={!!busy}+ className="flex items-center gap-1 bg-port-accent/20 text-port-accent disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0">+ {busy === 'prepare' ? 'Filling…' : (draft ? 'Fill again' : 'Fill draft')}+ </button>+ </div>+ <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">+ <div className="flex items-center gap-1">{error.code === 'PUBLISH_LOGIN_REQUIRED' && <LogIn size={11} />}{error.message}</div>+ {error.url && <div className="text-port-text-muted break-all">Sign-in page: {error.url}</div>}+ </div>+ )}+ {draft && (+ <div className="space-y-2">+ {draft.screenshot && <img src={draft.screenshot} alt={`${label} draft as filled`} className="w-full rounded border border-port-border" />}+ <dl className="grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-[11px]">+ {summaryRows(draft.summary).map(([k, v]) => (+ <div key={k} className="contents"><dt className="text-port-text-muted">{k}</dt><dd className="min-w-0 break-words whitespace-pre-wrap">{v}</dd></div>+ ))}+ </dl>+ <div className="flex flex-wrap gap-2">+ <button type="button" onClick={() => publishing.submit(target)} disabled={!!busy}+ className="flex items-center gap-1 bg-port-accent text-white disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0">+ <Send size={13} /> {busy === 'submit' ? 'Posting…' : `Post to ${label}`}+ </button>+ <button type="button" onClick={() => publishing.discard(target)} disabled={!!busy}+ 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">+ <XIcon size={13} /> Discard+ </button>+ </div>+ </div>+ )}+ </li>+ );+}++/**+ * Posting (#9282): each platform's post is filled in the PortOS Browser (in+ * a new tab, with the director's signed-in sessions) and shown back here as+ * a screenshot and summary. Nothing is posted until the director presses+ * Post for that draft.+ */+export default function PublishPostingPanel({ project, publishing }) {+ const kit = project?.publishKit || {};+ if (!kit.builtAt) return null;+ 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>+ <ul className="space-y-2">+ {PUBLISH_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.jsxnew file mode 100644index 0000000000..bd37ae10f2--- /dev/null+++ b/client/src/components/musicVideo/PublishPostingPanel.test.jsx@@ -0,0 +1,57 @@+/**+ * Posting panel (#9282): hidden until the kit is built, fills a draft with the+ * platform's options, shows the filled draft for review, posts only on the+ * 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 PublishPostingPanel, { PUBLISH_TARGETS } from './PublishPostingPanel.jsx';++const hook = (over = {}) => ({ drafts: {}, busy: {}, errors: {}, prepare: vi.fn(), submit: vi.fn(), discard: vi.fn(), ...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');++describe('PublishPostingPanel (#9282)', () => {+ it('stays hidden until the publishing kit is built', () => {+ const { container } = render(<PublishPostingPanel project={{ id: 'mv-1', publishKit: {} }} publishing={hook()} />);+ expect(container).toBeEmptyDOMElement();+ });++ it('lists every platform, full video first, with recorded posts linked', () => {+ render(<PublishPostingPanel project={project({ posts: { youtube: { url: 'https://youtu.be/abc', postedAt: '2026-01-02T00:00:00.000Z' } } })} publishing={hook()} />);+ expect(screen.getAllByRole('listitem')).toHaveLength(PUBLISH_TARGETS.length);+ expect(PUBLISH_TARGETS[0].target).toBe('youtube');+ expect(within(row('YouTube')).getByRole('link')).toHaveAttribute('href', 'https://youtu.be/abc');+ });++ it('fills a Reddit draft with the subreddit and post type, dropping blanks', () => {+ const publishing = hook();+ render(<PublishPostingPanel project={project()} publishing={publishing} />);+ const reddit = row('Reddit');+ fireEvent.change(within(reddit).getByLabelText('Subreddit'), { target: { value: 'SunoAI' } });+ fireEvent.change(within(reddit).getByLabelText('Post type'), { target: { value: 'link' } });+ fireEvent.click(within(reddit).getByRole('button', { name: 'Fill draft' }));+ expect(publishing.prepare).toHaveBeenCalledWith('reddit', { subreddit: 'SunoAI', kind: 'link' });+ });++ it('shows the filled draft and posts only when Post is pressed', () => {+ const publishing = hook({ drafts: { stackerNews: { draftId: 'd1', summary: { title: 'Song', territory: 'art' }, screenshot: 'data:image/jpeg;base64,AA' } } });+ render(<PublishPostingPanel project={project()} publishing={publishing} />);+ const sn = row('Stacker News');+ expect(within(sn).getByAltText('Stacker News draft as filled')).toBeInTheDocument();+ expect(within(sn).getByText('Song')).toBeInTheDocument();+ expect(publishing.submit).not.toHaveBeenCalled();+ fireEvent.click(within(sn).getByRole('button', { name: /Post to Stacker News/ }));+ expect(publishing.submit).toHaveBeenCalledWith('stackerNews');+ fireEvent.click(within(sn).getByRole('button', { name: /Discard/ }));+ expect(publishing.discard).toHaveBeenCalledWith('stackerNews');+ });++ it('keeps a sign-in refusal beside its platform', () => {+ const publishing = hook({ errors: { tiktok: { message: 'Sign in to TikTok in the PortOS Browser', code: 'PUBLISH_LOGIN_REQUIRED', url: 'https://www.tiktok.com/login' } } });+ render(<PublishPostingPanel project={project()} publishing={publishing} />);+ const alert = within(row('TikTok')).getByRole('alert');+ expect(alert).toHaveTextContent('Sign in to TikTok');+ expect(alert).toHaveTextContent('https://www.tiktok.com/login');+ });+});diff --git a/client/src/components/musicVideo/stages/PublishStage.jsx b/client/src/components/musicVideo/stages/PublishStage.jsxindex 8c6eb80f2d..8268355e36 100644--- a/client/src/components/musicVideo/stages/PublishStage.jsx+++ b/client/src/components/musicVideo/stages/PublishStage.jsx@@ -1,14 +1,17 @@import PublishKitPanel from '../PublishKitPanel.jsx';+import PublishPostingPanel from '../PublishPostingPanel.jsx';/*** Publish: the release kit made from the final render (encodes, thumbnails,- * captions, chapters) and the per-platform copy (#9281).+ * captions, chapters), the per-platform copy (#9281), and posting it through+ * the PortOS Browser with a review before every post (#9282).*/export default function PublishStage({ board }) {- const { project, locked, publishKit } = board;+ const { project, locked, publishKit, publishing } = board;return (- <fieldset disabled={locked} className="min-w-0">+ <fieldset disabled={locked} className="min-w-0 space-y-3"><PublishKitPanel project={project} publishKit={publishKit} />+ {publishing && <PublishPostingPanel project={project} publishing={publishing} />}</fieldset>);}diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex b4b7d0eeff..bf940c100b 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -259,6 +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. || `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/index.js b/client/src/hooks/index.jsindex 2872aadc63..327be1abcf 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -65,6 +65,7 @@ export { default as useMusicVideoCastAndSets } from './useMusicVideoCastAndSets.export { default as useMusicVideoDevArtifacts } from './useMusicVideoDevArtifacts.js';export { default as useMusicVideoExcerpts } from './useMusicVideoExcerpts.js';export { default as useMusicVideoPublishKit } from './useMusicVideoPublishKit.js';+export { default as useMusicVideoPublishing } from './useMusicVideoPublishing.js';export { default as useMusicVideoKickoff } from './useMusicVideoKickoff.js';export { default as useMusicVideoManualTempo } from './useMusicVideoManualTempo.js';export { default as useMusicVideoMidiJob } from './useMusicVideoMidiJob.js';diff --git a/client/src/hooks/useMusicVideoPublishing.js b/client/src/hooks/useMusicVideoPublishing.jsnew file mode 100644index 0000000000..970f6de228--- /dev/null+++ b/client/src/hooks/useMusicVideoPublishing.js@@ -0,0 +1,69 @@+import { useState } from 'react';+import toast from '../components/ui/Toast';+import {+ prepareMusicVideoPublishDraft,+ submitMusicVideoPublishDraft,+ discardMusicVideoPublishDraft,+} from '../services/apiMusicVideo.js';++/**+ * Music Video posting (#9282). Each platform is two explicit steps: `prepare`+ * fills the post in the PortOS Browser and returns what it filled (a summary+ * 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.+ */+export default function useMusicVideoPublishing({ project, replaceProject } = {}) {+ const projectId = project?.id || null;+ const [drafts, setDrafts] = useState({});+ const [busy, setBusy] = useState({});+ const [errors, setErrors] = useState({});++ const setFor = (setter, target, value) => setter((prev) => {+ const next = { ...prev };+ if (value == null) delete next[target];+ else next[target] = value;+ return next;+ });+ const fail = (target, err) => {+ setFor(setErrors, target, { message: err?.message || 'Failed', code: err?.code || null, url: err?.context?.url || null });+ };++ const prepare = (target, options = {}) => {+ setFor(setBusy, target, 'prepare');+ setFor(setErrors, target, null);+ return prepareMusicVideoPublishDraft(projectId, target, options, { silent: true })+ .then((draft) => { setFor(setDrafts, target, draft); return draft; })+ .catch((err) => { setFor(setDrafts, target, null); fail(target, err); return null; })+ .finally(() => setFor(setBusy, target, null));+ };++ const submit = (target) => {+ const draft = drafts[target];+ if (!draft) return Promise.resolve(null);+ setFor(setBusy, target, 'submit');+ setFor(setErrors, target, null);+ return submitMusicVideoPublishDraft(projectId, draft.draftId, { silent: true })+ .then((res) => {+ if (res?.project) replaceProject?.(res.project);+ setFor(setDrafts, target, null);+ toast.success('Posted');+ return res?.post || null;+ })+ .catch((err) => {+ // A gone draft can't be posted again; the director fills it afresh.+ if (err?.code === 'PUBLISH_DRAFT_MISSING') setFor(setDrafts, target, null);+ fail(target, err);+ return null;+ })+ .finally(() => setFor(setBusy, target, null));+ };++ const discard = (target) => {+ const draft = drafts[target];+ setFor(setDrafts, target, null);+ if (draft) discardMusicVideoPublishDraft(projectId, draft.draftId, { silent: true }).catch(() => {});+ };++ return { drafts, busy, errors, prepare, submit, discard };+}diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 88ef503950..3305139ca5 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -30,6 +30,7 @@ import useMusicVideoVocalSeparation from '../hooks/useMusicVideoVocalSeparation.import useMusicVideoRenderJob from '../hooks/useMusicVideoRenderJob.js';import useMusicVideoExcerpts from '../hooks/useMusicVideoExcerpts.js';import useMusicVideoPublishKit from '../hooks/useMusicVideoPublishKit.js';+import useMusicVideoPublishing from '../hooks/useMusicVideoPublishing.js';import useMusicVideoRevisions from '../hooks/useMusicVideoRevisions.js';import useMusicVideoAutoReview from '../hooks/useMusicVideoAutoReview.js';import useMusicVideoProduction from '../hooks/useMusicVideoProduction.js';@@ -183,6 +184,8 @@ export default function MusicVideo() {const excerpts = useMusicVideoExcerpts({ project: selected, replaceProject });// Publishing kit (#9281): release encodes, thumbnails, captions, chapters and copy.const publishKit = useMusicVideoPublishKit({ project: selected, replaceProject });+ // Posting (#9282): fill each platform's post in the PortOS Browser, post on a second press.+ const publishing = useMusicVideoPublishing({ project: selected, replaceProject });const videoSettings = useMusicVideoModelSettings({ project: selected, onProjectPatch: patchProject });const tempo = useMusicVideoManualTempo({ project: selected, onUpdated: replaceProject });const sceneMedia = useMusicVideoSceneMedia({@@ -779,6 +782,7 @@ export default function MusicVideo() {treatment,excerpts,publishKit,+ publishing,revisions,autoReview,finalVideo,diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex b06b01ba84..e469c7b6e7 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -84,6 +84,9 @@ vi.mock('../services/apiMusicVideo.js', () => ({draftMusicVideoPublishCopy: vi.fn(),updateMusicVideoPublishCopy: vi.fn(),selectMusicVideoPublishThumbnail: vi.fn(),+ prepareMusicVideoPublishDraft: vi.fn(),+ submitMusicVideoPublishDraft: vi.fn(),+ discardMusicVideoPublishDraft: 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.jsindex 3a3810118d..4d1fb11af4 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -207,6 +207,15 @@ export const updateMusicVideoPublishCopy = (id, patch, options = {}) =>request(`/music-video/${encodeURIComponent(id)}/publish-kit/copy`, { method: 'PATCH', body: JSON.stringify(patch || {}), ...options });export const selectMusicVideoPublishThumbnail = (id, filename, options = {}) =>request(`/music-video/${encodeURIComponent(id)}/publish-kit/thumbnail`, { method: 'PUT', body: JSON.stringify({ filename }), ...options });+// ---- Posting (#9282) ----+// Prepare fills the platform's post in the PortOS Browser → { draftId, target,+// summary, screenshot }; submit posts that live draft → { project, post }.+export const prepareMusicVideoPublishDraft = (id, target, options = {}, reqOptions = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/publish/${encodeURIComponent(target)}/prepare`, { method: 'POST', body: JSON.stringify(options || {}), ...reqOptions });+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 });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.mdindex 48d931e377..eea86e1e8c 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. | — |+| **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. | — || **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.jsindex 672a03b1de..ee287770f6 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -544,6 +544,25 @@ export const musicVideoPublishCopyDraftSchema = z.object({}).strict();export const musicVideoPublishThumbnailSchema = z.object({ filename: z.string().min(1).max(300) }).strict();+// #9282: posting to a platform through the PortOS Browser. One strict options+// object covers every target; each target's payload builder reads only its own.+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);+export const musicVideoPublishPrepareSchema = z.object({+ subreddit: z.string().max(40),+ kind: z.enum(['self', 'link']),+ url: publishUrl,+ flairId: z.string().max(100),+ flairText: z.string().max(64),+ firstComment: kitText(10000),+ territory: z.string().max(40),+ songUrl: publishUrl,+ pin: z.boolean(),+ prompt: kitText(25000),+ storyImage: z.string().min(1).max(300),+}).partial().strict();+export const musicVideoExcerptNoteSchema = z.object({atSec: z.number().min(0).max(36000),note: z.string().min(1).max(2000),diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex c7a4e41d64..52ed7a143a 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -39,6 +39,8 @@ import {musicVideoPublishCopyPatchSchema,musicVideoPublishCopyDraftSchema,musicVideoPublishThumbnailSchema,+ musicVideoPublishTargetSchema,+ musicVideoPublishPrepareSchema,musicVideoCodeGenerateSchema,musicVideoExcerptNoteSchema,musicVideoExcerptNoteUpdateSchema,@@ -102,6 +104,7 @@ 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 {startRevision, resumeRevision, cancelRevision, releaseRevisionSection,} from '../services/musicVideo/revisionService.js';@@ -615,6 +618,23 @@ router.put('/:id/publish-kit/thumbnail', asyncHandler(async (req, res) => {res.json({ project });}));+// --- 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.+router.post('/:id/publish/:target/prepare', asyncHandler(async (req, res) => {+ const target = validateRequest(musicVideoPublishTargetSchema, req.params.target);+ const options = validateRequest(musicVideoPublishPrepareSchema, req.body || {});+ res.json(await preparePublishDraft(req.params.id, target, options));+}));++router.post('/:id/publish/drafts/:draftId/submit', asyncHandler(async (req, res) => {+ res.json(await submitPublishDraft(req.params.id, req.params.draftId));+}));++router.delete('/:id/publish/drafts/:draftId', asyncHandler(async (req, res) => {+ res.json({ ok: await discardPublishDraft(req.params.id, req.params.draftId) });+}));+// #9280: the song windows most likely to work as a vertical social cut.router.get('/:id/social-cuts', asyncHandler(async (req, res) => {const options = validateRequest(musicVideoSocialCutsQuerySchema, req.query);diff --git a/server/services/musicVideo/publish/browser.js b/server/services/musicVideo/publish/browser.jsnew file mode 100644index 0000000000..c76e5fb2dd--- /dev/null+++ b/server/services/musicVideo/publish/browser.js@@ -0,0 +1,109 @@+/**+ * Music Video publishing (#9282) — the PortOS Browser session every platform+ * adapter drives, plus the editor/file helpers the platforms need. Lessons+ * from driving these UIs by hand are encoded here once:+ *+ * - Connect with `isLocal: true`: Playwright otherwise refuses to hand a file+ * over 50 MB to a browser it thinks is remote, and every video upload is.+ * - Draft.js / Lexical editors (X, TikTok, Stacker News) ignore `fill()` and+ * drop newlines from typed text; a synthetic `paste` event lands the text+ * the way a user's paste does.+ * - Each draft gets its OWN new tab, so a fill can never land in another tab+ * that happens to match the same URL (a YouTube Studio edit page of an+ * already-published video matched `studio.youtube.com` once and was edited).+ */+import { ServerError } from '../../../lib/errorHandler.js';++export const PUBLISH_STEP_TIMEOUT_MS = 60_000;++/** Connect to the running PortOS Browser (launching it when it is stopped). */+export async function connectPortosBrowser() {+ const { getHealthStatus, launchBrowser } = await import('../../browserService.js');+ let health = await getHealthStatus();+ if (!health.connected) health = await launchBrowser();+ if (!health.connected) {+ throw new ServerError('PortOS Browser is unavailable. Start it in Settings › Browser, then retry.', { status: 503, code: 'PORTOS_BROWSER_UNAVAILABLE' });+ }+ const host = health.cdpHost === '0.0.0.0' || health.cdpHost === '::' ? '127.0.0.1' : health.cdpHost;+ const { chromium } = await import('playwright-core');+ const browser = await chromium.connectOverCDP(`http://${host}:${health.cdpPort}`, { isLocal: true, noDefaults: true, timeout: 30_000 });+ const context = browser.contexts()[0];+ if (!context) {+ await browser.close().catch(() => {});+ throw new ServerError('PortOS Browser has no usable profile context.', { status: 503, code: 'PORTOS_BROWSER_UNAVAILABLE' });+ }+ return { browser, context };+}++/** A platform needs the user to sign in, in the PortOS Browser, before a draft can be filled. */+export const loginRequired = (label, url) => new ServerError(`Sign in to ${label} in the PortOS Browser, then fill the draft again`, {+ status: 409, code: 'PUBLISH_LOGIN_REQUIRED', context: { platform: label, url },+});++/** A step the page never reached: say which, so a UI change is diagnosable. */+export const stepFailed = (label, step, err) => new ServerError(`${label}: ${step} (${err?.message?.split('\n')[0] || 'timed out'})`, {+ status: 502, code: 'PUBLISH_STEP_FAILED', context: { platform: label, step },+});++/** Run one named step, turning a Playwright timeout into a `stepFailed` naming it. */+export async function step(label, name, fn) {+ try {+ return await fn();+ } catch (err) {+ if (err instanceof ServerError) throw err;+ throw stepFailed(label, name, err);+ }+}++/** Paste `text` into the first element matching `selector`, as a user's paste would. */+export async function pasteText(page, selector, text) {+ const ok = await page.evaluate(([sel, txt]) => {+ const el = document.querySelector(sel);+ if (!el) return false;+ el.focus();+ const data = new DataTransfer();+ data.setData('text/plain', txt);+ el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));+ return true;+ }, [selector, text]);+ if (!ok) throw new Error(`no editor matched ${selector}`);+}++/** Replace a contenteditable's text: focus, select all, delete, then paste. */+export async function replaceEditorText(page, selector, text) {+ await page.locator(selector).first().click();+ await page.keyboard.press('ControlOrMeta+A');+ await page.keyboard.press('Backspace');+ await pasteText(page, selector, text);+}++/** Click the last VISIBLE element whose trimmed text is exactly `text` (dialogs stack their buttons last). */+export async function clickVisibleText(page, text, { selector = 'button,[role=button]' } = {}) {+ const clicked = await page.evaluate(([sel, want]) => {+ const found = [...document.querySelectorAll(sel)].filter((e) => e.offsetParent && (e.innerText || '').trim() === want);+ const target = found[found.length - 1];+ if (!target) return false;+ target.click();+ return true;+ }, [selector, text]);+ if (!clicked) throw new Error(`no visible "${text}" control`);+}++/** Turn on the switch/checkbox that sits beside a label, when it is off. Returns its final state. */+export async function ensureToggleBeside(page, labelText) {+ return page.evaluate((want) => {+ const label = [...document.querySelectorAll('span,div,label')].find((e) => e.children.length === 0 && e.textContent.trim() === want);+ if (!label) return null;+ let node = label;+ for (let i = 0; i < 8 && node; i += 1) {+ node = node.parentElement;+ const sw = node?.querySelector('[role=switch],input[type=checkbox]');+ if (sw) {+ const on = sw.getAttribute('aria-checked') === 'true' || sw.checked === true;+ if (!on) sw.click();+ return true;+ }+ }+ return null;+ }, labelText);+}diff --git a/server/services/musicVideo/publish/index.js b/server/services/musicVideo/publish/index.jsnew file mode 100644index 0000000000..4abda28a25--- /dev/null+++ b/server/services/musicVideo/publish/index.js@@ -0,0 +1,147 @@+/**+ * Music Video publishing (#9282): fill a platform's post in the PortOS Browser,+ * show the director what it will post, and post only when they press Post.+ *+ * `prepare` opens a NEW tab, runs the platform adapter's fill (never its+ * submit), screenshots the filled draft and parks it under a draft id.+ * `submit` requires that same live draft: a missing, expired or closed draft+ * is a 409 and nothing is posted. One browser operation runs at a time,+ * because keyboard input goes to whichever tab has focus. A logged-out+ * 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 }`.+ */+import { randomUUID } from 'crypto';+import { existsSync } from 'fs';+import { join } from 'path';+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 { connectPortosBrowser } from './browser.js';+import { youtubeAdapter, shortsAdapter } from './youtube.js';+import { tiktokAdapter } from './tiktok.js';+import { instagramAdapter } from './instagram.js';+import { xAdapter } from './x.js';+import { redditAdapter } from './reddit.js';+import { stackerNewsAdapter } from './stackerNews.js';+import { sunoAdapter } from './suno.js';++export const PUBLISH_ADAPTERS = Object.freeze({+ youtube: youtubeAdapter, shorts: shortsAdapter, tiktok: tiktokAdapter, instagram: instagramAdapter,+ x: xAdapter, reddit: redditAdapter, stackerNews: stackerNewsAdapter, suno: sunoAdapter,+});+const DRAFT_TTL_MS = 30 * 60 * 1000;+const drafts = new Map();+let browserTail = Promise.resolve();++/** Run `fn` after every earlier browser operation settles (typing needs the focused tab). */+function serialize(fn) {+ const run = browserTail.then(fn, fn);+ browserTail = run.catch(() => {});+ return run;+}++const draftError = (message) => new ServerError(message, { status: 409, code: 'PUBLISH_DRAFT_MISSING' });++async function closeDraft(draft) {+ drafts.delete(draft.id);+ clearTimeout(draft.timer);+ await draft.page?.close().catch(() => {});+ await draft.browser?.close().catch(() => {}); // disconnects; the PortOS Browser keeps running+}++const DIRS = { videos: () => PATHS.videos, videoThumbnails: () => PATHS.videoThumbnails };++/** Resolve every `{ dir, name }` file ref in a payload to an existing absolute `path`. */+function resolveFiles(value) {+ if (Array.isArray(value)) return value.map(resolveFiles);+ if (!value || typeof value !== 'object') return value;+ if (typeof value.dir === 'string' && typeof value.name === 'string') {+ const path = DIRS[value.dir] ? safeUnder(DIRS[value.dir](), value.name) : null;+ if (!path || !existsSync(path)) throw new ServerError(`A release file is missing on disk (${value.name}) — rebuild the publishing kit`, { status: 422, code: 'PUBLISH_ASSET_MISSING' });+ return { ...value, path };+ }+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, resolveFiles(v)]));+}++/** Cut the frame a platform shows before play: TikTok's cover (9:16 frame) and Suno's (square). */+async function withCovers(target, payload, deps) {+ if (target !== 'tiktok' && target !== 'suno') return payload;+ const source = target === 'tiktok' ? payload.video?.path : payload.cover?.path;+ if (!source) return payload;+ const { findFfmpeg, runFfmpegProcess } = await import('../../../lib/ffmpeg.js');+ const ffmpeg = await (deps.findFfmpeg || findFfmpeg)();+ if (!ffmpeg) return payload;+ await ensureDir(PATHS.videoThumbnails);+ const out = join(PATHS.videoThumbnails, `publish-cover-${target}-${Date.now()}.jpg`);+ const args = target === 'tiktok'+ ? ['-hide_banner', '-loglevel', 'error', '-ss', String(payload.coverAtSec || 0), '-i', source, '-frames:v', '1', '-q:v', '2', '-y', out]+ : ['-hide_banner', '-loglevel', 'error', '-i', source, '-vf', "crop='min(iw,ih)':'min(iw,ih)',scale=1500:1500", '-frames:v', '1', '-q:v', '2', '-y', out];+ const result = await (deps.runFfmpegProcess || runFfmpegProcess)({ bin: ffmpeg, args });+ return result.ok ? { ...payload, cover: { dir: 'videoThumbnails', name: out.split(/[\\/]/).pop(), path: out } } : payload;+}++/**+ * Fill `target`'s post for this project and park it for the director's review.+ * Resolves `{ draftId, target, summary, screenshot }` (a data: URL).+ */+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 project = await getProject(projectId);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ let payload = resolveFiles(buildPublishPayload(target, project, options));+ payload = await withCovers(target, payload, deps);+ for (const draft of [...drafts.values()]) if (draft.projectId === projectId && draft.target === target) await closeDraft(draft);+ return serialize(async () => {+ const { browser, context } = await (deps.connect || connectPortosBrowser)();+ const page = await context.newPage();+ try {+ await page.bringToFront();+ const summary = await adapter.prepare(page, payload);+ 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() };+ draft.timer = setTimeout(() => { closeDraft(draft).catch(() => {}); }, DRAFT_TTL_MS);+ draft.timer.unref?.();+ drafts.set(id, draft);+ console.log(`📝 ${adapter.label} draft filled for music-video ${projectId.slice(0, 8)} [${id.slice(6, 14)}]`);+ return { draftId: id, target, summary, screenshot: shot ? `data:image/jpeg;base64,${shot.toString('base64')}` : null };+ } catch (err) {+ await page.close().catch(() => {});+ await browser.close().catch(() => {});+ throw err;+ }+ });+}++/** Post a draft the director reviewed. Resolves `{ project, post }`. */+export async function submitPublishDraft(projectId, draftId, deps = {}) {+ const draft = drafts.get(draftId);+ if (!draft || draft.projectId !== projectId) throw draftError('That draft is gone (posted, discarded or expired) — fill it again');+ if (draft.page.isClosed?.()) { await closeDraft(draft); throw draftError('The draft tab was closed — fill it again'); }+ const adapter = (deps.adapters || PUBLISH_ADAPTERS)[draft.target];+ return serialize(async () => {+ await draft.page.bringToFront();+ const { url = null } = await adapter.submit(draft.page, draft.payload) || {};+ await closeDraft(draft);+ const post = { url, postedAt: new Date().toISOString() };+ console.log(`🚀 Posted music-video ${projectId.slice(0, 8)} to ${adapter.label}${url ? `: ${url}` : ''}`);+ const { project } = await mutateProjectRecord(projectId, (current) => {+ const kit = current.publishKit && typeof current.publishKit === 'object' ? current.publishKit : {};+ return { project: { ...current, publishKit: { ...kit, posts: { ...(kit.posts || {}), [draft.target]: post } } } };+ });+ return { project, post };+ });+}++/** Close a draft without posting it. */+export async function discardPublishDraft(projectId, draftId) {+ const draft = drafts.get(draftId);+ if (!draft || draft.projectId !== projectId) return false;+ await closeDraft(draft);+ return true;+}diff --git a/server/services/musicVideo/publish/index.test.js b/server/services/musicVideo/publish/index.test.jsnew file mode 100644index 0000000000..83f28c86e5--- /dev/null+++ b/server/services/musicVideo/publish/index.test.js@@ -0,0 +1,113 @@+/**+ * Posting state machine (#9282) with a fake browser and adapters: prepare+ * fills a draft in a new tab and returns its screenshot, submit posts only a+ * live draft and records the link, discard and re-prepare close the old tab.+ */+import { afterAll, describe, expect, it, vi } from 'vitest';+import { mkdir, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../../lib/mockPathsDataRoot.js';++vi.mock('../../../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), {+ dataRoot: () => lazyTempDataRoot('portos-mv-publish-'),+}));++const { PATHS } = await import('../../../lib/paths.js');+const projects = await import('../projects.js');+const { preparePublishDraft, submitPublishDraft, discardPublishDraft } = await import('./index.js');++afterAll(() => cleanupTempDataRoots());++function fakeBrowser() {+ const pages = [];+ const connect = vi.fn(async () => ({+ browser: { close: vi.fn(async () => {}) },+ context: {+ newPage: async () => {+ const page = { closed: false, bringToFront: vi.fn(async () => {}), screenshot: vi.fn(async () => Buffer.from('jpg')), isClosed() { return this.closed; }, close: vi.fn(async function close() { page.closed = true; }) };+ pages.push(page);+ return page;+ },+ },+ }));+ return { connect, pages };+}++const adapter = (over = {}) => ({+ label: 'Stacker News',+ prepare: vi.fn(async (page, payload) => ({ title: payload.title })),+ submit: vi.fn(async () => ({ url: 'https://stacker.news/items/1' })),+ ...over,+});++async function readyProject() {+ const { id } = await projects.createProject({ name: 'Release' });+ await projects.mutateProjectRecord(id, (current) => ({ project: { ...current, publishKit: {+ links: { youtube: 'https://youtu.be/abc' }, copy: { stackerNews: { title: 'Song', body: 'b' } },+ } } }));+ return id;+}++describe('publish drafts (#9282)', () => {+ it('fills a draft, then posts it only on submit and records the link', async () => {+ const id = await readyProject();+ const { connect, pages } = fakeBrowser();+ const adapters = { stackerNews: adapter() };+ const draft = await preparePublishDraft(id, 'stackerNews', { territory: 'art' }, { connect, adapters });+ expect(draft).toMatchObject({ target: 'stackerNews', summary: { title: 'Song' } });+ expect(draft.screenshot).toMatch(/^data:image\/jpeg;base64,/);+ expect(adapters.stackerNews.submit).not.toHaveBeenCalled();++ const { project, post } = await submitPublishDraft(id, draft.draftId, { adapters });+ expect(post.url).toBe('https://stacker.news/items/1');+ expect(project.publishKit.posts.stackerNews.url).toBe('https://stacker.news/items/1');+ expect(pages[0].closed).toBe(true);+ await expect(submitPublishDraft(id, draft.draftId, { adapters })).rejects.toMatchObject({ status: 409, code: 'PUBLISH_DRAFT_MISSING' });+ });++ it('closes the earlier draft when the same target is filled again, and discards on request', async () => {+ 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 });+ 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);+ expect(pages[1].closed).toBe(true);+ expect(await discardPublishDraft(id, second.draftId)).toBe(false);+ });++ it('refuses a draft whose tab the director closed', async () => {+ const id = await readyProject();+ const { connect, pages } = fakeBrowser();+ const adapters = { stackerNews: adapter() };+ const draft = await preparePublishDraft(id, 'stackerNews', {}, { connect, adapters });+ pages[0].closed = true;+ await expect(submitPublishDraft(id, draft.draftId, { adapters })).rejects.toMatchObject({ code: 'PUBLISH_DRAFT_MISSING' });+ expect(adapters.stackerNews.submit).not.toHaveBeenCalled();+ });++ it('closes the tab and surfaces the adapter\'s error when a fill fails', async () => {+ const id = await readyProject();+ 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);+ expect(pages[0].closed).toBe(true);+ });++ 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' });+ expect(connect).not.toHaveBeenCalled();++ await mkdir(PATHS.videos, { recursive: true });+ await writeFile(join(PATHS.videos, 'master.mp4'), 'x');+ await preparePublishDraft(id, 'youtube', {}, { connect, adapters });+ expect(adapters.youtube.prepare.mock.calls[0][1].video.path).toBe(join(PATHS.videos, 'master.mp4'));+ });+});diff --git a/server/services/musicVideo/publish/instagram.js b/server/services/musicVideo/publish/instagram.jsnew file mode 100644index 0000000000..3d605baffb--- /dev/null+++ b/server/services/musicVideo/publish/instagram.js@@ -0,0 +1,69 @@+/**+ * Instagram Reels adapter (#9282), driving instagram.com's create flow (a+ * video post is shared as a reel). Hard-won rules: keep the Original crop (the+ * default square crop cuts a 9:16 cut in half), type the caption into the+ * focused box (it ignores synthetic paste) with no "@" (the mention picker+ * swallows the next word — payloads strip it), turn on "Add AI label" under+ * Advanced settings, and NEVER press Escape: it opens "Discard post?".+ */+import { PUBLISH_STEP_TIMEOUT_MS as T, clickVisibleText, ensureToggleBeside, loginRequired, step } from './browser.js';++const HOME_URL = 'https://www.instagram.com/';+const label = 'Instagram';++export const instagramAdapter = {+ label,+ async prepare(page, payload) {+ await step(label, 'open Instagram', () => page.goto(HOME_URL, { waitUntil: 'domcontentloaded', timeout: T }));+ await page.waitForTimeout(5000);+ if (/accounts\/login/.test(page.url()) || await page.locator('input[name=password]').count()) throw loginRequired(label, HOME_URL);+ await step(label, 'start a new post', async () => {+ await page.evaluate(() => {+ const icon = [...document.querySelectorAll('svg[aria-label="New post"]')].find((s) => s.getBoundingClientRect().width > 0);+ (icon?.closest('a,[role=link],[role=button]') || icon?.parentElement)?.click();+ });+ await page.waitForTimeout(1500);+ await page.evaluate(() => [...document.querySelectorAll('a,[role=link],[role=button]')].find((e) => e.offsetParent && e.innerText.trim() === 'Post')?.click());+ });+ await step(label, 'upload the video', () => page.locator('input[type=file][accept*=video]').first().setInputFiles(payload.video.path, { timeout: T }));+ await page.waitForTimeout(6000);+ await clickVisibleText(page, 'OK').catch(() => {}); // "Video posts are now shared as reels"+ await step(label, 'keep the original 9:16 crop', async () => {+ await page.evaluate(() => [...document.querySelectorAll('svg[aria-label="Select crop"]')][0]?.closest('button,[role=button],div')?.click());+ await page.waitForTimeout(1000);+ await page.evaluate(() => {+ const opts = [...document.querySelectorAll('span,div')].filter((e) => e.offsetParent && e.children.length <= 1 && e.innerText.trim() === 'Original');+ opts[opts.length - 1]?.click();+ });+ });+ for (const where of ['go to Edit', 'go to the caption']) {+ await step(label, where, async () => {+ await clickVisibleText(page, 'Next', { selector: '[role=dialog] [role=button],[role=dialog] button' });+ await page.waitForTimeout(2500);+ });+ }+ if (payload.caption) {+ await step(label, 'write the caption', async () => {+ await page.evaluate(() => {+ const box = document.querySelector('[aria-label="Add a caption..."]');+ box.focus();+ const sel = window.getSelection();+ sel.selectAllChildren(box);+ sel.collapseToEnd();+ });+ await page.keyboard.type(payload.caption, { delay: 5 });+ });+ }+ const aiLabel = await step(label, 'turn on the AI label', async () => {+ await page.evaluate(() => [...document.querySelectorAll('[role=dialog] [role=button],[role=dialog] div')].find((e) => e.offsetParent && e.innerText.trim() === 'Advanced settings')?.click());+ await page.waitForTimeout(1200);+ return ensureToggleBeside(page, 'Add AI label');+ });+ return { caption: payload.caption, aiLabel: aiLabel === true };+ },+ async submit(page) {+ await step(label, 'share', () => clickVisibleText(page, 'Share'));+ await step(label, 'wait for the reel to be shared', () => page.waitForFunction(() => /Your reel has been shared|Reel shared/i.test(document.body.innerText), null, { timeout: 180_000 }));+ return { url: null };+ },+};diff --git a/server/services/musicVideo/publish/payloads.js b/server/services/musicVideo/publish/payloads.jsnew file mode 100644index 0000000000..a82b756b63--- /dev/null+++ b/server/services/musicVideo/publish/payloads.js@@ -0,0 +1,125 @@+/**+ * Music Video publishing (#9282) — what each platform posts, built from the+ * project's publishing kit (#9281). Pure: project + kit + the director's+ * per-platform options in, a payload of text and file NAMES out (the service+ * resolves names to paths), or a 422 naming what is missing.+ */+import { ServerError } from '../../../lib/errorHandler.js';+import { chaptersText } from '../publishKitText.js';++const TITLE_LIMITS = { youtube: 100, shorts: 100, reddit: 300, stackerNews: 80 };++const missing = (message) => new ServerError(message, { status: 422, code: 'PUBLISH_ASSET_MISSING' });+const text = (v) => (typeof v === 'string' ? v.trim() : '');+const kitOf = (project) => (project?.publishKit && typeof project.publishKit === 'object' ? project.publishKit : {});++/** The newest finished 9:16 social cut (#9280): what Shorts, TikTok and Reels upload. */+function latestVerticalCut(project) {+ const cuts = (project?.excerpts || []).filter((e) => e?.status === 'complete' && e.aspect === '9:16' && e.filename);+ return cuts.length ? cuts[cuts.length - 1] : null;+}++/** The full video's public link: the recorded YouTube post, else the one the director gave the kit. */+const fullVideoUrl = (kit) => text(kit.posts?.youtube?.url) || text(kit.links?.youtube) || '';+const songUrl = (kit, options) => text(options?.songUrl) || text(kit.posts?.suno?.url) || text(kit.links?.song) || '';++function requireTitle(platform, title) {+ if (!title) throw missing(`Write the ${platform} title in the release copy first`);+ const max = TITLE_LIMITS[platform];+ if (max && title.length > max) throw missing(`The ${platform} title is ${title.length} characters; the limit is ${max}`);+ return title;+}++function youtubeDescription(kit) {+ const body = text(kit.copy?.youtube?.description);+ // YouTube makes chapters from the description's timestamps; add them unless the copy already has them.+ const chapters = Array.isArray(kit.chapters) && kit.chapters.length && !/(^|\n)0:00\s/.test(body) ? `\n\nChapters\n${chaptersText(kit.chapters)}` : '';+ return `${body}${chapters}`.trim();+}++// A typed "@" on Instagram opens the mention picker, which swallows the next word.+const instagramSafe = (caption) => caption.replace(/@(\w)/g, '$1');++const BUILDERS = {+ youtube: (project, kit) => {+ if (!kit.master?.filename) throw missing('Build the publishing kit first — it names the final render to upload');+ return {+ video: { dir: 'videos', name: kit.master.filename },+ title: requireTitle('youtube', text(kit.copy?.youtube?.title)),+ description: youtubeDescription(kit),+ tags: (kit.copy?.youtube?.tags || []).map(text).filter(Boolean),+ thumbnail: kit.thumbnail ? { dir: 'videoThumbnails', name: kit.thumbnail } : null,+ captions: kit.captionsFilename ? { dir: 'videos', name: kit.captionsFilename } : null,+ };+ },+ shorts: (project, kit) => {+ const cut = latestVerticalCut(project);+ if (!cut) throw missing('Render a 9:16 social cut on the Review stage first');+ const url = fullVideoUrl(kit);+ const description = [text(kit.copy?.shorts?.description), url && !text(kit.copy?.shorts?.description).includes(url) ? `Full video: ${url}` : ''].filter(Boolean).join('\n\n');+ return { video: { dir: 'videos', name: cut.filename }, title: requireTitle('shorts', text(kit.copy?.shorts?.title)), description, tags: [], thumbnail: null, captions: null };+ },+ tiktok: (project, kit) => {+ const cut = latestVerticalCut(project);+ if (!cut) throw missing('Render a 9:16 social cut on the Review stage first');+ return { video: { dir: 'videos', name: cut.filename }, caption: text(kit.copy?.tiktok?.caption), coverAtSec: Math.max(0, (cut.endSec - cut.startSec) / 2) };+ },+ instagram: (project, kit) => {+ const cut = latestVerticalCut(project);+ if (!cut) throw missing('Render a 9:16 social cut on the Review stage first');+ return { video: { dir: 'videos', name: cut.filename }, caption: instagramSafe(text(kit.copy?.instagram?.caption)) };+ },+ x: (project, kit, options = {}) => {+ const hook = text(kit.copy?.x?.hook);+ if (!hook) throw missing('Write the X hook post in the release copy first');+ const clip = (kit.exports || []).find((e) => e.kind === 'x-1080p')?.filename;+ if (!clip) throw missing('Build the publishing kit first — the X post carries its 1080p encode');+ const links = [+ songUrl(kit, options) ? `The song: ${songUrl(kit, options)}` : '',+ // X builds a post's link card from its LAST link, so the full video goes last.+ fullVideoUrl(kit) ? `Full video: ${fullVideoUrl(kit)}` : '',+ ].filter(Boolean).join('\n');+ const posts = [+ { text: hook, media: { dir: 'videos', name: clip } },+ text(kit.copy?.x?.story) ? { text: text(kit.copy.x.story), media: options.storyImage ? { dir: 'videoThumbnails', name: options.storyImage } : null } : null,+ text(options.prompt) ? { text: text(options.prompt), media: null } : null,+ links ? { text: links, media: null } : null,+ ].filter(Boolean);+ return { posts };+ },+ reddit: (project, kit, options = {}) => {+ const subreddit = text(options.subreddit).replace(/^\/?r\//i, '');+ if (!/^[A-Za-z0-9_]{2,21}$/.test(subreddit)) throw missing('Name the subreddit to post in');+ const title = requireTitle('reddit', text(kit.copy?.reddit?.title));+ // r/SunoAI removes song posts whose title doesn't open with the genre in brackets.+ if (subreddit.toLowerCase() === 'sunoai' && !/^\[[^\]]+\]/.test(title)) throw missing('r/SunoAI titles must start with the genre in brackets, e.g. [Electropop] Song Name');+ const url = options.kind === 'link' ? (text(options.url) || fullVideoUrl(kit)) : '';+ if (options.kind === 'link' && !url) throw missing('A Reddit link post needs the full video URL');+ return {+ subreddit, kind: options.kind === 'link' ? 'link' : 'self', title, body: text(kit.copy?.reddit?.body), url,+ flairId: text(options.flairId) || null, flairText: text(options.flairText) || null, firstComment: text(options.firstComment) || null,+ };+ },+ stackerNews: (project, kit, options = {}) => {+ const url = fullVideoUrl(kit);+ if (!url) throw missing('Stacker News posts link to the full video: publish to YouTube first, or add its URL to the kit');+ const territory = text(options.territory || 'art').replace(/^~/, '');+ if (!/^[A-Za-z0-9_]{1,32}$/.test(territory)) throw missing('Name the Stacker News territory');+ return { territory, title: requireTitle('stackerNews', text(kit.copy?.stackerNews?.title)), url, body: text(kit.copy?.stackerNews?.body), firstComment: text(options.firstComment) || null };+ },+ suno: (project, kit, options = {}) => {+ const song = songUrl(kit, options);+ if (!/^https:\/\/(www\.)?suno\.com\/song\/[\w-]+/.test(song)) throw missing('Give the Suno song URL to publish (suno.com/song/…)');+ const video = fullVideoUrl(kit);+ const lead = text(kit.copy?.youtube?.description).split(/\n\s*\n/)[0] || '';+ const caption = [lead, video ? `Music video: ${video}` : ''].filter(Boolean).join(' ').slice(0, 500);+ return { songUrl: song, caption, cover: kit.thumbnail ? { dir: 'videoThumbnails', name: kit.thumbnail } : null, pin: options.pin !== false };+ },+};++/** The payload one platform posts, or a 422 naming the first missing piece. */+export function buildPublishPayload(platform, project, options = {}) {+ const build = BUILDERS[platform];+ if (!build) throw new ServerError(`Unknown publish target: ${platform}`, { status: 400, code: 'VALIDATION_ERROR' });+ return build(project, kitOf(project), options || {});+}diff --git a/server/services/musicVideo/publish/payloads.test.js b/server/services/musicVideo/publish/payloads.test.jsnew file mode 100644index 0000000000..65b29a15f3--- /dev/null+++ b/server/services/musicVideo/publish/payloads.test.js@@ -0,0 +1,94 @@+/**+ * What each platform posts (#9282): built from the publishing kit and the+ * director's per-platform options, or a 422 naming the missing piece.+ */+import { describe, expect, it } from 'vitest';+import { buildPublishPayload } from './payloads.js';++const kit = (over = {}) => ({+ master: { filename: 'master.mp4' },+ exports: [{ kind: 'x-1080p', filename: 'x.mp4' }, { kind: 'teaser', filename: 'teaser.mp4' }],+ thumbnail: 'thumb-1.jpg',+ captionsFilename: 'captions.srt',+ chapters: [{ startSec: 0, label: 'Intro' }, { startSec: 30, label: 'Chorus' }, { startSec: 75, label: 'Outro' }],+ links: { youtube: 'https://youtu.be/abc', song: 'https://suno.com/song/1234-abcd' },+ copy: {+ youtube: { title: 'Song — Music Video', description: 'The story.\n\nMore.', tags: ['ai music', ' '] },+ shorts: { title: 'Song #Shorts', description: 'Hook' },+ x: { hook: 'Watch this', story: 'How it was made' },+ tiktok: { caption: 'tt caption' },+ instagram: { caption: 'made with @portos and @suno' },+ reddit: { title: '[Electropop] Song', body: 'Body' },+ stackerNews: { title: 'Song', body: 'SN body' },+ },+ ...over,+});+const project = (over = {}, excerpts = [{ status: 'complete', aspect: '9:16', filename: 'cut-a.mp4', startSec: 10, endSec: 30 }]) => ({ publishKit: kit(over), excerpts });++describe('buildPublishPayload (#9282)', () => {+ it('uploads the master to YouTube with chapters appended, thumbnail and captions', () => {+ const p = buildPublishPayload('youtube', project());+ expect(p.video).toEqual({ dir: 'videos', name: 'master.mp4' });+ expect(p.description).toContain('0:00 Intro');+ expect(p.tags).toEqual(['ai music']);+ expect(p.thumbnail).toEqual({ dir: 'videoThumbnails', name: 'thumb-1.jpg' });+ expect(p.captions).toEqual({ dir: 'videos', name: 'captions.srt' });+ });++ it('does not repeat chapters the description already has', () => {+ const p = buildPublishPayload('youtube', project({ copy: { youtube: { title: 't', description: 'x\n0:00 Start\n0:30 Next' } } }));+ expect(p.description).not.toContain('Chapters');+ });++ it('refuses YouTube without a built kit or a title, and a title over the limit', () => {+ expect(() => buildPublishPayload('youtube', { publishKit: {} })).toThrow(expect.objectContaining({ status: 422, code: 'PUBLISH_ASSET_MISSING' }));+ expect(() => buildPublishPayload('youtube', project({ copy: {} }))).toThrow(/title/);+ expect(() => buildPublishPayload('youtube', project({ copy: { youtube: { title: 'x'.repeat(101) } } }))).toThrow(/limit is 100/);+ });++ it('sends the newest 9:16 cut to Shorts, TikTok and Reels, linking the full video from Shorts', () => {+ const excerpts = [+ { status: 'complete', aspect: '9:16', filename: 'old.mp4', startSec: 0, endSec: 20 },+ { status: 'complete', aspect: '16:9', filename: 'wide.mp4', startSec: 0, endSec: 20 },+ { status: 'complete', aspect: '9:16', filename: 'new.mp4', startSec: 40, endSec: 60 },+ { status: 'running', aspect: '9:16', filename: 'partial.mp4' },+ ];+ const shorts = buildPublishPayload('shorts', project({}, excerpts));+ expect(shorts.video.name).toBe('new.mp4');+ expect(shorts.description).toBe('Hook\n\nFull video: https://youtu.be/abc');+ expect(buildPublishPayload('tiktok', project({}, excerpts))).toMatchObject({ video: { name: 'new.mp4' }, coverAtSec: 10 });+ expect(buildPublishPayload('instagram', project({}, excerpts)).caption).toBe('made with portos and suno');+ expect(() => buildPublishPayload('tiktok', project({}, []))).toThrow(/9:16 social cut/);+ });++ it('threads X: hook with the 1080p encode, story, prompt, then links with the full video last', () => {+ const { posts } = buildPublishPayload('x', project(), { prompt: 'the prompt', storyImage: 'still.png' });+ expect(posts.map((p) => p.text)).toEqual(['Watch this', 'How it was made', 'the prompt', 'The song: https://suno.com/song/1234-abcd\nFull video: https://youtu.be/abc']);+ expect(posts[0].media).toEqual({ dir: 'videos', name: 'x.mp4' });+ expect(posts[1].media).toEqual({ dir: 'videoThumbnails', name: 'still.png' });+ expect(() => buildPublishPayload('x', project({ exports: [] }))).toThrow(/1080p/);+ });++ it('prefers the recorded YouTube post over the kit link', () => {+ const p = buildPublishPayload('stackerNews', project({ posts: { youtube: { url: 'https://www.youtube.com/watch?v=posted' } } }));+ expect(p).toMatchObject({ url: 'https://www.youtube.com/watch?v=posted', territory: 'art', title: 'Song' });+ });++ it('validates Reddit subreddits and r/SunoAI\'s genre-bracket title rule', () => {+ expect(buildPublishPayload('reddit', project(), { subreddit: 'r/SunoAI', kind: 'link' })).toMatchObject({ subreddit: 'SunoAI', kind: 'link', url: 'https://youtu.be/abc' });+ expect(buildPublishPayload('reddit', project(), { subreddit: 'aivideo' })).toMatchObject({ kind: 'self', url: '' });+ expect(() => buildPublishPayload('reddit', project(), {})).toThrow(/subreddit/);+ expect(() => buildPublishPayload('reddit', project({ copy: { reddit: { title: 'Song' } } }), { subreddit: 'SunoAI' })).toThrow(/brackets/);+ });++ it('needs a suno.com song URL and captions it with the full video', () => {+ const p = buildPublishPayload('suno', project());+ expect(p).toMatchObject({ songUrl: 'https://suno.com/song/1234-abcd', pin: true, cover: { name: 'thumb-1.jpg' } });+ expect(p.caption).toBe('The story. Music video: https://youtu.be/abc');+ expect(() => buildPublishPayload('suno', project({ links: {} }))).toThrow(/Suno song URL/);+ });++ it('rejects an unknown target', () => {+ expect(() => buildPublishPayload('myspace', project())).toThrow(expect.objectContaining({ status: 400 }));+ });+});diff --git a/server/services/musicVideo/publish/reddit.js b/server/services/musicVideo/publish/reddit.jsnew file mode 100644index 0000000000..7bbd668b96--- /dev/null+++ b/server/services/musicVideo/publish/reddit.js@@ -0,0 +1,52 @@+/**+ * Reddit adapter (#9282). The new composer's video tool ignores files set by+ * automation, so this posts a text or link post through old.reddit's own+ * `/api/submit` with the signed-in session's modhash. prepare() checks the+ * session and reads the subreddit's rules and post flairs (so the director+ * sees what the sub requires before posting); submit() posts, then adds the+ * optional first comment.+ */+import { ServerError } from '../../../lib/errorHandler.js';+import { PUBLISH_STEP_TIMEOUT_MS as T, loginRequired, step } from './browser.js';++const BASE = 'https://old.reddit.com';+const label = 'Reddit';++export const redditAdapter = {+ label,+ async prepare(page, payload) {+ await step(label, 'open Reddit', () => page.goto(`${BASE}/r/${payload.subreddit}/`, { waitUntil: 'domcontentloaded', timeout: T }));+ const info = await step(label, 'read the subreddit', () => page.evaluate(async (sub) => {+ const me = await (await fetch('/api/me.json', { credentials: 'include' })).json().catch(() => ({}));+ if (!me?.data?.name) return { user: null };+ const rules = await (await fetch(`/r/${sub}/about/rules.json`)).json().catch(() => ({}));+ const flairs = await (await fetch(`/r/${sub}/api/link_flair_v2.json?uh=${me.data.modhash}`, { credentials: 'include' })).json().catch(() => []);+ return {+ user: me.data.name,+ rules: (rules.rules || []).map((r) => r.short_name).slice(0, 15),+ flairs: Array.isArray(flairs) ? flairs.filter((f) => !f.mod_only).map((f) => ({ id: f.id, text: f.text })).slice(0, 60) : [],+ };+ }, 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 };+ },+ async submit(page, payload) {+ const result = await step(label, 'post', () => page.evaluate(async (p) => {+ const me = await (await fetch('/api/me.json', { credentials: 'include' })).json();+ const form = new URLSearchParams({+ sr: p.subreddit, kind: p.kind, title: p.title, api_type: 'json', uh: me.data.modhash, sendreplies: 'true', resubmit: 'true',+ ...(p.kind === 'link' ? { url: p.url, ...(p.body ? { text: p.body } : {}) } : { text: p.body || '' }),+ ...(p.flairId ? { flair_id: p.flairId } : {}), ...(p.flairText ? { flair_text: p.flairText } : {}),+ });+ const res = await (await fetch('/api/submit', { method: 'POST', body: form, credentials: 'include' })).json();+ if (res?.json?.errors?.length) return { error: res.json.errors.map((e) => e.join(': ')).join('; ') };+ const post = res?.json?.data;+ if (post?.name && p.firstComment) {+ await fetch('/api/comment', { method: 'POST', credentials: 'include', body: new URLSearchParams({ thing_id: post.name, text: p.firstComment, api_type: 'json', uh: me.data.modhash }) });+ }+ return { url: post?.url || null };+ }, payload));+ if (result.error) throw new ServerError(`Reddit refused the post: ${result.error}`, { status: 422, code: 'PUBLISH_REJECTED' });+ return { url: result.url ? result.url.replace('://old.reddit.com', '://www.reddit.com') : null };+ },+};diff --git a/server/services/musicVideo/publish/stackerNews.js b/server/services/musicVideo/publish/stackerNews.jsnew file mode 100644index 0000000000..a3fc286db2--- /dev/null+++ b/server/services/musicVideo/publish/stackerNews.js@@ -0,0 +1,57 @@+/**+ * Stacker News adapter (#9282): a link post in a territory (10 sats in ~art),+ * the body in the post's "context" editor, and the optional first comment+ * (for example the starter prompt) posted as a reply. The url field is read+ * back after the body is written, because a stray keystroke once landed in it.+ */+import { PUBLISH_STEP_TIMEOUT_MS as T, loginRequired, pasteText, step } from './browser.js';++const label = 'Stacker News';++export const stackerNewsAdapter = {+ label,+ async prepare(page, payload) {+ const url = `https://stacker.news/~${payload.territory}/post?type=link`;+ await step(label, 'open the link-post form', () => page.goto(url, { waitUntil: 'domcontentloaded', timeout: T }));+ await page.waitForTimeout(4000);+ if (!(await page.locator('input[name=title]').count())) throw loginRequired(label, 'https://stacker.news/login');+ await step(label, 'write the title and link', async () => {+ await page.locator('input[name=title]').fill(payload.title);+ await page.locator('input[name=url]').fill(payload.url);+ });+ if (payload.body) {+ await step(label, 'write the body', async () => {+ await page.locator('text=options').first().click({ timeout: T });+ await page.locator('div[contenteditable=true]').first().click();+ await pasteText(page, 'div[contenteditable=true]', payload.body);+ });+ }+ await step(label, 'check the link', async () => {+ if ((await page.locator('input[name=url]').inputValue()) !== payload.url) await page.locator('input[name=url]').fill(payload.url);+ });+ const cost = await page.evaluate(() => [...document.querySelectorAll('button[type=submit]')].map((b) => b.innerText.trim()).find((t) => /post/i.test(t)) || null);+ return { territory: payload.territory, title: payload.title, url: payload.url, cost };+ },+ async submit(page, payload) {+ await step(label, 'post', () => page.locator('button[type=submit]').filter({ hasText: 'post' }).first().click({ timeout: T }));+ const url = await step(label, 'find the new post', async () => {+ await page.waitForURL((u) => !/\/post\?/.test(u.toString()), { timeout: 60_000 });+ await page.waitForTimeout(2500);+ return page.evaluate((title) => {+ const link = [...document.querySelectorAll('a[href^="/items/"]')].find((a) => a.innerText.trim().startsWith(title.slice(0, 40)));+ return link ? `https://stacker.news${link.getAttribute('href').replace(/\/$/, '')}` : null;+ }, payload.title);+ });+ if (url && payload.firstComment) {+ await step(label, 'add the first comment', async () => {+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: T });+ await page.waitForTimeout(3000);+ await page.locator('div[contenteditable=true]').first().click();+ await pasteText(page, 'div[contenteditable=true]', payload.firstComment);+ await page.locator('button[type=submit]').filter({ hasText: 'reply' }).first().click({ timeout: T });+ await page.waitForTimeout(3000);+ });+ }+ return { url };+ },+};diff --git a/server/services/musicVideo/publish/suno.js b/server/services/musicVideo/publish/suno.jsnew file mode 100644index 0000000000..9ff59aeadd--- /dev/null+++ b/server/services/musicVideo/publish/suno.js@@ -0,0 +1,51 @@+/**+ * Suno adapter (#9282): publish one of the director's songs with the release+ * cover and a caption linking the video, pinned to their profile. prepare()+ * opens the song's own Publish dialog and fills it; submit() presses Publish.+ * Lyrics and styles are left exactly as the director made them.+ */+import { PUBLISH_STEP_TIMEOUT_MS as T, clickVisibleText, ensureToggleBeside, loginRequired, step } from './browser.js';++const label = 'Suno';++export const sunoAdapter = {+ label,+ async prepare(page, payload) {+ await step(label, 'open the song', () => page.goto(payload.songUrl, { waitUntil: 'domcontentloaded', timeout: T }));+ await page.waitForTimeout(5000);+ if (!(await page.locator("button[aria-label='More options']").count())) throw loginRequired(label, payload.songUrl);+ await step(label, 'open the Publish dialog', async () => {+ await page.locator("button[aria-label='More options']").first().click({ timeout: T });+ await page.locator('[role=menuitem]').filter({ hasText: /^Publish$/ }).first().click({ timeout: T });+ await page.locator('[role=dialog]').first().waitFor({ timeout: T });+ });+ let cover = false;+ if (payload.cover) {+ await step(label, 'upload the cover', async () => {+ const [chooser] = await Promise.all([+ page.waitForEvent('filechooser', { timeout: T }),+ page.locator('[role=dialog] button').filter({ hasText: 'Upload' }).first().click(),+ ]);+ await chooser.setFiles(payload.cover.path);+ await page.waitForTimeout(3000);+ });+ cover = true;+ }+ if (payload.caption) {+ await step(label, 'write the caption', async () => {+ await page.locator('[role=dialog]').getByText('Edit caption, lyrics and styles').first().click({ timeout: T });+ await page.locator("[role=dialog] textarea[placeholder='Add a caption']").fill(payload.caption);+ await page.waitForTimeout(500);+ await clickVisibleText(page, 'Save'); // the details dialog's Save, stacked above the Publish dialog's+ await page.waitForTimeout(2500);+ });+ }+ const pinned = payload.pin ? await step(label, 'pin it to the profile', () => ensureToggleBeside(page, 'Pin song to profile')) : false;+ return { songUrl: payload.songUrl, cover, caption: payload.caption, pinned: pinned === true };+ },+ async submit(page, payload) {+ await step(label, 'publish', () => clickVisibleText(page, 'Publish'));+ await step(label, 'confirm it published', () => page.waitForFunction(() => /Published/.test(document.body.innerText), null, { timeout: 60_000 }));+ return { url: payload.songUrl };+ },+};diff --git a/server/services/musicVideo/publish/tiktok.js b/server/services/musicVideo/publish/tiktok.jsnew file mode 100644index 0000000000..60ddd35185--- /dev/null+++ b/server/services/musicVideo/publish/tiktok.js@@ -0,0 +1,70 @@+/**+ * TikTok adapter (#9282), driving TikTok Studio's web upload. prepare()+ * uploads the vertical cut, writes the caption, sets a chosen cover (the+ * default is frame 0, often a title card) and turns on the AI-generated label+ * (a switch with its own confirm dialog). submit() presses Post.+ */+import { PUBLISH_STEP_TIMEOUT_MS as T, clickVisibleText, loginRequired, replaceEditorText, step } from './browser.js';++const UPLOAD_URL = 'https://www.tiktok.com/tiktokstudio/upload';+const label = 'TikTok';++export const tiktokAdapter = {+ label,+ async prepare(page, payload) {+ await step(label, 'open TikTok Studio', () => page.goto(UPLOAD_URL, { waitUntil: 'domcontentloaded', timeout: T }));+ await page.waitForTimeout(5000);+ if (/\/login/.test(page.url())) throw loginRequired(label, UPLOAD_URL);+ await step(label, 'upload the video', () => page.locator('input[type=file][accept*=video]').first().setInputFiles(payload.video.path, { timeout: T }));+ await step(label, 'wait for the caption editor', () => page.locator('[contenteditable=true]').first().waitFor({ timeout: T }));+ if (payload.caption) {+ await step(label, 'write the caption', () => replaceEditorText(page, '[contenteditable=true]', payload.caption));+ await page.keyboard.press('Escape'); // closes the hashtag suggestion popup, nothing else+ }+ let cover = false;+ if (payload.cover) {+ await step(label, 'set the cover frame', async () => {+ await page.locator('text=Edit cover').first().click({ timeout: T });+ await page.locator('input[type=file][accept*=image]').first().setInputFiles(payload.cover.path, { timeout: T });+ await page.waitForTimeout(2500);+ await clickVisibleText(page, 'Save');+ await page.waitForTimeout(1500);+ });+ cover = true;+ }+ await step(label, 'open the post settings', () => page.locator('text=Show more').first().click({ timeout: T }));+ const aiLabel = await step(label, 'turn on the AI-generated label', async () => {+ const was = await page.evaluate(() => {+ const text = [...document.querySelectorAll('*')].find((e) => e.children.length === 0 && e.textContent.trim() === 'AI-generated content');+ let node = text;+ for (let i = 0; i < 8 && node; i += 1) {+ node = node.parentElement;+ const sw = node?.querySelector('[role=switch]');+ if (sw) {+ const on = sw.getAttribute('aria-checked') === 'true' || /checked|on/i.test(sw.className);+ if (!on) sw.click();+ return on;+ }+ }+ return null;+ });+ if (was === null) throw new Error('no AI-generated content switch');+ if (was === false) {+ await page.waitForTimeout(800);+ await clickVisibleText(page, 'Turn on').catch(() => {}); // the confirm dialog, when TikTok shows one+ }+ return true;+ });+ const checks = await page.evaluate(() => (document.body.innerText.match(/Content check lite[^\n]*\n?[^\n]{0,120}/) || [])[0] || null);+ return { caption: payload.caption, cover, aiLabel, checks };+ },+ async submit(page) {+ await step(label, 'post', () => clickVisibleText(page, 'Post'));+ const url = await step(label, 'find the new post', async () => {+ await page.waitForURL(/tiktokstudio\/content/, { timeout: 120_000 });+ await page.waitForTimeout(3000);+ return page.evaluate(() => [...document.querySelectorAll('a[href*="/video/"]')].map((a) => a.href)[0] || null);+ });+ return { url };+ },+};diff --git a/server/services/musicVideo/publish/x.js b/server/services/musicVideo/publish/x.jsnew file mode 100644index 0000000000..3da748e42b--- /dev/null+++ b/server/services/musicVideo/publish/x.js@@ -0,0 +1,58 @@+/**+ * X thread adapter (#9282). prepare() composes the whole thread in one+ * composer: each post's text goes in by paste (the Draft.js editor keeps its+ * line breaks that way), media attaches through the focused post's file input,+ * and the thread waits until every upload reports Ready. X builds a post's+ * link card from its LAST link; the payload already orders links for that.+ * submit() presses "Post all" and finds the new thread on the profile.+ */+import { PUBLISH_STEP_TIMEOUT_MS as T, loginRequired, pasteText, step } from './browser.js';++const COMPOSE_URL = 'https://x.com/compose/post';+const label = 'X';++export const xAdapter = {+ label,+ async prepare(page, payload) {+ 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);+ 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 }));+ await step(label, `write post ${i + 1}`, async () => {+ await page.locator(editor).waitFor({ timeout: T });+ await pasteText(page, editor, post.text);+ });+ if (post.media) {+ await step(label, `attach media to post ${i + 1}`, async () => {+ await page.locator(editor).click();+ await page.locator('input[data-testid=fileInput]').first().setInputFiles(post.media.path, { timeout: T });+ });+ }+ }+ await step(label, 'wait for the uploads', () => page.waitForFunction(() => {+ const button = document.querySelector('[data-testid=tweetButton]');+ const uploading = [...document.querySelectorAll('[data-testid=attachments]')].some((a) => /Uploading|Processing/i.test(a.innerText));+ 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 };+ },+ async submit(page, payload) {+ await step(label, 'post the thread', () => page.locator('[data-testid=tweetButton]').click({ timeout: T }));+ await step(label, 'wait for it to send', () => page.waitForURL((url) => !/compose/.test(url.toString()), { timeout: 180_000 }));+ const url = await step(label, 'find the new thread', async () => {+ const profile = await page.locator('[data-testid=AppTabBar_Profile_Link]').getAttribute('href', { timeout: T });+ await page.goto(`https://x.com${profile}`, { waitUntil: 'domcontentloaded', timeout: T });+ await page.waitForTimeout(5000);+ const opening = payload.posts[0].text.slice(0, 40);+ return page.evaluate((start) => {+ const article = [...document.querySelectorAll('article')].find((a) => (a.querySelector('[data-testid=tweetText]')?.innerText || '').startsWith(start));+ const href = article && [...article.querySelectorAll('a[href*="/status/"]')].map((a) => a.getAttribute('href')).find((h) => /\/status\/\d+$/.test(h));+ return href ? `https://x.com${href}` : null;+ }, opening);+ });+ return { url };+ },+};diff --git a/server/services/musicVideo/publish/youtube.js b/server/services/musicVideo/publish/youtube.jsnew file mode 100644index 0000000000..bdefef133e--- /dev/null+++ b/server/services/musicVideo/publish/youtube.js@@ -0,0 +1,109 @@+/**+ * YouTube + YouTube Shorts adapter (#9282), driving YouTube Studio's upload+ * dialog. A Short is the same upload of a vertical cut under 3 minutes.+ * prepare() uploads and fills everything up to the Visibility step with+ * Public selected; submit() presses Publish. Studio saves an upload as a+ * private draft as soon as the file lands, so a discarded draft stays in the+ * channel's Content list as Private.+ */+import { PUBLISH_STEP_TIMEOUT_MS as T, loginRequired, step } from './browser.js';++const UPLOAD_URL = 'https://www.youtube.com/upload';+// The dialog shows the watch link with or without its scheme (Shorts omit it).+const LINK_RE = /(https?:\/\/)?(youtu\.be|(www\.)?youtube\.com\/shorts)\/[\w-]+/;+const normalizeLink = (link) => (link ? (link.startsWith('http') ? link : `https://${link}`) : null);++async function selectDropdownItem(page, triggerSelector, itemText) {+ await page.evaluate((sel) => {+ const t = document.querySelector(sel);+ t.scrollIntoView({ block: 'center' });+ t.click();+ }, triggerSelector);+ await page.waitForTimeout(800);+ const picked = await page.evaluate((want) => {+ const item = [...document.querySelectorAll('tp-yt-paper-item')].find((e) => e.offsetParent && e.innerText.trim() === want);+ if (!item) return false;+ item.scrollIntoView({ block: 'center' });+ item.click();+ return true;+ }, itemText);+ if (!picked) throw new Error(`no "${itemText}" option`);+}++function adapter(label) {+ return {+ label,+ async prepare(page, payload) {+ await step(label, 'open the upload dialog', () => page.goto(UPLOAD_URL, { waitUntil: 'domcontentloaded', timeout: T }));+ await page.waitForTimeout(4000);+ if (/accounts\.google\.com/.test(page.url())) throw loginRequired(label, UPLOAD_URL);+ await step(label, 'upload the video', () => page.locator('input[type=file][name=Filedata]').first().setInputFiles(payload.video.path, { timeout: T }));+ const title = page.locator('#title-textarea #textbox');+ await step(label, 'wait for the details form', () => title.waitFor({ timeout: T }));+ await step(label, 'set the title', async () => {+ await title.click();+ await page.keyboard.press('ControlOrMeta+A');+ await page.keyboard.press('Backspace');+ await page.keyboard.insertText(payload.title);+ });+ if (payload.description) {+ await step(label, 'set the description', async () => {+ await page.locator('#description-textarea #textbox').click();+ await page.keyboard.insertText(payload.description);+ });+ }+ let thumbnail = false;+ if (payload.thumbnail) {+ // Custom thumbnails need a verified channel; without one the input is absent.+ const input = page.locator('input#file-loader[accept*=image]');+ if (await input.count()) {+ await step(label, 'upload the thumbnail', () => input.first().setInputFiles(payload.thumbnail.path, { timeout: T }));+ thumbnail = true;+ }+ }+ await step(label, 'mark it not made for kids', () => page.locator('tp-yt-paper-radio-button[name=VIDEO_MADE_FOR_KIDS_NOT_MFK]').click({ timeout: T }));+ await step(label, 'open the advanced details', () => page.locator('#toggle-button').filter({ hasText: 'Show more' }).first().click({ timeout: T }));+ await step(label, 'declare no paid promotion', () => page.locator('tp-yt-paper-radio-button[name=VIDEO_PAID_PRODUCT_PLACEMENT_NO]').click({ timeout: T }));+ // The singer is a realistic AI-generated person: YouTube requires the disclosure.+ await step(label, 'disclose altered or synthetic content', () => page.locator('tp-yt-paper-radio-button[name=VIDEO_HAS_ALTERED_CONTENT_YES]').click({ timeout: T }));+ if (payload.tags?.length) {+ await step(label, 'add the tags', async () => {+ await page.locator("input[aria-label='Tags']").click();+ await page.keyboard.insertText(`${payload.tags.join(', ')},`);+ });+ }+ await step(label, 'set the Music category', () => selectDropdownItem(page, 'ytcp-form-select#category ytcp-dropdown-trigger', 'Music'));+ await step(label, 'go to Video elements', () => page.locator('#next-button').click({ timeout: T }));+ let captions = false;+ if (payload.captions) {+ await step(label, 'upload the lyric captions', async () => {+ await page.locator('ytcp-button').filter({ hasText: /^Add$/ }).first().click({ timeout: T });+ await page.locator('button').filter({ hasText: 'Upload file' }).first().click({ timeout: T });+ await page.locator('#captions-file-loader').setInputFiles(payload.captions.path, { timeout: T });+ await page.waitForTimeout(3000);+ await page.locator('button').filter({ hasText: /^Done$/ }).last().click({ timeout: T });+ });+ captions = true;+ }+ await step(label, 'go to Visibility', async () => {+ await page.locator('#next-button').click({ timeout: T });+ await page.waitForTimeout(1500);+ await page.locator('#next-button').click({ timeout: T });+ });+ await step(label, 'choose Public', () => page.locator('tp-yt-paper-radio-button[name=PUBLIC]').click({ timeout: T }));+ const link = normalizeLink(await page.evaluate((re) => (document.querySelector('ytcp-uploads-dialog')?.innerText.match(new RegExp(re)) || [])[0] || null, LINK_RE.source));+ return { title: payload.title, link, thumbnail, captions };+ },+ async submit(page) {+ await step(label, 'publish', () => page.locator('#done-button').click({ timeout: T }));+ const url = await step(label, 'confirm it published', async () => {+ await page.waitForFunction(() => /Video published|published/i.test(document.body.innerText), null, { timeout: 120_000 });+ return normalizeLink(await page.evaluate((re) => (document.body.innerText.match(new RegExp(re)) || [])[0] || null, LINK_RE.source));+ });+ return { url };+ },+ };+}++export const youtubeAdapter = adapter('YouTube');+export const shortsAdapter = adapter('YouTube Shorts');