Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Add Facebook as a music video publish destination

Claude2f1f20398c2d
diff --git a/client/src/components/musicVideo/PublishCrossLinksPanel.jsx b/client/src/components/musicVideo/PublishCrossLinksPanel.jsx
index f281be7839..a678279be1 100644
--- a/client/src/components/musicVideo/PublishCrossLinksPanel.jsx
+++ b/client/src/components/musicVideo/PublishCrossLinksPanel.jsx
@@ -3,8 +3,8 @@ import { Check, Link2, LogIn } from 'lucide-react';
import PublishCard from './PublishCard.jsx';
import { crossLinkBackfill, crossLinksEnabled } from '../../../../server/lib/musicVideoCrossLinks.js';
-const LABELS = { youtube: 'YouTube description', suno: 'Suno caption', x: 'X reply', stackerNews: 'Stacker News comment' };
-const ACTION = { youtube: 'Fill edit', suno: 'Fill edit', x: 'Fill reply', stackerNews: 'Fill comment' };
+const LABELS = { youtube: 'YouTube description', suno: 'Suno caption', x: 'X reply', stackerNews: 'Stacker News comment', facebook: 'Facebook comment' };
+const ACTION = { youtube: 'Fill edit', suno: 'Fill edit', x: 'Fill reply', stackerNews: 'Fill comment', facebook: 'Fill comment' };
const btn = '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';
/** One posted platform: the links it lacks, a Fill that opens its edit in the PortOS Browser, and Saved. */
diff --git a/client/src/components/musicVideo/PublishKitPanel.jsx b/client/src/components/musicVideo/PublishKitPanel.jsx
index 525a666c83..c53a2e19e7 100644
--- a/client/src/components/musicVideo/PublishKitPanel.jsx
+++ b/client/src/components/musicVideo/PublishKitPanel.jsx
@@ -23,6 +23,7 @@ export const PUBLISH_FIELDS = [
{ platform: 'shorts', label: 'YouTube Shorts', fields: [{ key: 'title', label: 'Title', max: 100 }, { key: 'description', label: 'Description', multiline: true }] },
{ platform: 'x', label: 'X', fields: [{ key: 'hook', label: 'Hook post (no links)', max: 280, multiline: true }, { key: 'story', label: 'Story reply', multiline: true }] },
{ platform: 'linkedin', label: 'LinkedIn', fields: [{ key: 'post', label: 'Post (no links: they go in the first comment)', max: 3000, multiline: true }] },
+ { platform: 'facebook', label: 'Facebook', fields: [{ key: 'post', label: 'Post (no links: they go in the first comment)', max: 63206, multiline: true }] },
{ platform: 'tiktok', label: 'TikTok', fields: [{ key: 'caption', label: 'Caption', max: 2200, multiline: true }] },
{ platform: 'instagram', label: 'Instagram Reels', fields: [{ key: 'caption', label: 'Caption', max: 2200, multiline: true }] },
{ platform: 'reddit', label: 'Reddit', fields: [{ key: 'title', label: 'Title', max: 300 }, { key: 'body', label: 'Body (markdown)', multiline: true }] },
diff --git a/client/src/components/musicVideo/PublishPostingPanel.jsx b/client/src/components/musicVideo/PublishPostingPanel.jsx
index 2493613cb3..58e40845b7 100644
--- a/client/src/components/musicVideo/PublishPostingPanel.jsx
+++ b/client/src/components/musicVideo/PublishPostingPanel.jsx
@@ -17,6 +17,10 @@ export const PUBLISH_TARGETS = [
target: 'linkedin', label: 'LinkedIn', accountPlaceholder: 'Your name',
note: 'Your short post with the 1080p video uploaded, and the links in a first comment. You press Post, then View post: PortOS records the link and types the comment for you to send',
},
+ {
+ target: 'facebook', label: 'Facebook', accountPlaceholder: 'Your name or Page',
+ note: 'Your short post with the 1080p video uploaded (Facebook shares it as a reel), and the links in a first comment. Posts as the profile or Page active in the PortOS Browser. You press Post, then open the post: PortOS records the link and types the comment for you to send',
+ },
{ target: 'shorts', label: 'YouTube Shorts', note: 'A 9:16 cut (the newest by default)' },
{ target: 'tiktok', label: 'TikTok', note: 'A 9:16 cut (the newest by default), labelled AI-generated' },
{ target: 'instagram', label: 'Instagram Reels', note: 'A 9:16 cut (the newest by default), with the AI label' },
@@ -194,10 +198,10 @@ function TargetOptions({ target, kit, project, options, setOption, commitOption,
</div>
);
}
- if (target === 'linkedin') {
+ if (target === 'linkedin' || target === 'facebook') {
return (
<label className="flex items-center gap-1.5 text-xs min-h-[44px] sm:min-h-0">
- <input type="checkbox" checked={options.linksComment !== false} onChange={(e) => setOption('linksComment', e.target.checked)} /> Put the full video and song links in a first comment
+ <input type="checkbox" checked={options.linksComment !== false} onChange={(e) => setOption('linksComment', e.target.checked)} /> Put the links (full video, song, other posts) in a first comment
</label>
);
}
diff --git a/client/src/components/musicVideo/PublishPostingPanel.test.jsx b/client/src/components/musicVideo/PublishPostingPanel.test.jsx
index 8f4bfe1d1e..3734583b5b 100644
--- a/client/src/components/musicVideo/PublishPostingPanel.test.jsx
+++ b/client/src/components/musicVideo/PublishPostingPanel.test.jsx
@@ -10,7 +10,7 @@ import PublishPostingPanel, { PUBLISH_TARGETS } from './PublishPostingPanel.jsx'
// Publish cards and platform rows fold when done; open everything so a test sees the whole page.
const expandAll = () => { for (let b = screen.queryAllByRole('button', { expanded: false }); b.length; b = screen.queryAllByRole('button', { expanded: false })) b.forEach((x) => fireEvent.click(x)); };
-const ALL = ['youtube', 'suno', 'sunoHook', 'x', 'linkedin', 'shorts', 'tiktok', 'instagram', 'reddit', 'stackerNews', 'substack', 'distrokid'];
+const ALL = ['youtube', 'suno', 'sunoHook', 'x', 'linkedin', 'facebook', 'shorts', 'tiktok', 'instagram', 'reddit', 'stackerNews', 'substack', 'distrokid'];
const hook = (over = {}) => ({ drafts: {}, busy: {}, errors: {}, prepare: vi.fn(), submit: vi.fn(), discard: vi.fn(), enabledTargets: ALL, platforms: {}, recordPost: vi.fn(async () => null), ...over });
const project = (kit = {}) => ({ id: 'mv-1', publishKit: { builtAt: '2026-01-01T00:00:00.000Z', thumbnails: ['t1.jpg'], ...kit } });
const row = (label) => screen.getAllByRole('listitem').find((li) => li.querySelector('h4 button > span')?.firstChild?.textContent === label);
@@ -64,18 +64,18 @@ describe('PublishPostingPanel (#9282)', () => {
expect(publishing.prepare).toHaveBeenLastCalledWith('substack', { publication: 'other' });
});
- it('fills a LinkedIn draft with the links comment on, unless the director turns it off', () => {
+ it.each([['LinkedIn', 'linkedin'], ['Facebook', 'facebook']])('fills a %s draft with the links comment on, unless the director turns it off', (label, target) => {
const publishing = hook();
render(<PublishPostingPanel project={project()} publishing={publishing} />);
expandAll();
- const linkedin = row('LinkedIn');
- const links = within(linkedin).getByLabelText('Put the full video and song links in a first comment');
+ const card = row(label);
+ const links = within(card).getByLabelText('Put the links (full video, song, other posts) in a first comment');
expect(links).toBeChecked();
- fireEvent.click(within(linkedin).getByRole('button', { name: 'Fill draft' }));
- expect(publishing.prepare).toHaveBeenCalledWith('linkedin', {});
+ fireEvent.click(within(card).getByRole('button', { name: 'Fill draft' }));
+ expect(publishing.prepare).toHaveBeenCalledWith(target, {});
fireEvent.click(links);
- fireEvent.click(within(linkedin).getByRole('button', { name: 'Fill draft' }));
- expect(publishing.prepare).toHaveBeenLastCalledWith('linkedin', { linksComment: false });
+ fireEvent.click(within(card).getByRole('button', { name: 'Fill draft' }));
+ expect(publishing.prepare).toHaveBeenLastCalledWith(target, { linksComment: false });
});
it('picks the X story image from thumbnails, with No image as the default', () => {
diff --git a/docs/features/music-video-autonomous.md b/docs/features/music-video-autonomous.md
index 19fa6a1920..17a5f0886f 100644
--- a/docs/features/music-video-autonomous.md
+++ b/docs/features/music-video-autonomous.md
@@ -88,7 +88,7 @@ A proof approval is bound to its exact excerpt ID and filename; `energyCompariso
**Automatic planning approvals.** An authenticated start or `POST /api/music-video/:id/autonomous/resume` can grant `autoApprove: ['art', 'storyboard']` (any subset). The run records `brief.autoApprove`, `brief.autoApproveAuthorizedAt`, and `brief.autoApproveAuthorizedBy`; automatic decisions also record the run ID. A resume list replaces the grant; explicit `[]` revokes it and also requires authentication. Omitting the list preserves the existing policy. In **Produce**, the run first waits for Cast & Sets to draft the art guide (`stages.produce.step: 'cast-and-sets'`; its settle event carries the run on, and a failed Cast & Sets fails the run with `CAST_SETS_FAILED`), so the art gate is never judged empty. A `storyboard` grant also makes the run do the lyric-timing chores a director would: after analysis it aligns the vocal to the lyric sheet and times lines alignment skipped, then before the storyboard gate it verifies the timing (reviewer `{ kind: 'autopilot', runId }`), marks an instrumental song as one, and anchors each shot to the lyric lines it overlaps. It verifies only timings it can trust: when alignment failed or the recognizer heard less than half of the words, the timings are mostly guesses, so it leaves them provisional and parks the run with that reason. Automatic planning approval still requires a clean readiness report; a line it cannot time, or any other open problem, still parks the run. Proof is never auto-approved; a legacy brief listing `proof` is ignored for it, since the final render no longer waits on a proof. Start drawer and run panel expose the planning choices without a password field, and the run panel shows existing grants so they can be revoked.
-External draft preparation uses the existing authenticated session without password re-entry; agents may prepare drafts. PortOS never submits a final post: review and publish on the destination platform. When the filled tab lands on the new post's own page (Stacker News, Reddit, Substack, DistroKid, and LinkedIn once you press View post), PortOS records that link itself while the tab's session is attached, and for LinkedIn types the links comment for you to send; otherwise paste the link on the platform's card. Existing projects and assets remain intact, but an older project's final render now requires the same production review.
+External draft preparation uses the existing authenticated session without password re-entry; agents may prepare drafts. PortOS never submits a final post: review and publish on the destination platform. When the filled tab lands on the new post's own page (Stacker News, Reddit, Substack, DistroKid, LinkedIn once you press View post, and Facebook once you open the new post), PortOS records that link itself while the tab's session is attached, and for LinkedIn and Facebook types the links comment for you to send; otherwise paste the link on the platform's card. Existing projects and assets remain intact, but an older project's final render now requires the same production review.
The local browser acceptance test (`server/routes/musicVideoProductionReview.browser.test.js`) exercises the real React controls, approval routes, native code renderer, ffmpeg output and video playback with synthetic data. It requires Chrome, ffmpeg and installed client dependencies; server-only CI skips this cross-workspace check. API and orchestration tests run independently of those visual-test prerequisites.
diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.md
index 0607d5e0d8..89fdc8eb44 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 is six deep-linked steps (`/music-video/:projectId/:stage` — Song `setup`, Look `cast-sets`, Storyboard `board`, Make `produce`, Final render `review`, Publish `publish`; an old `compose` link opens Make), listed down the left with a state word and one fact each (a bottom icon bar on a phone). Each step opens with what "done" means and an always-visible checklist, and ends with its own approval (art on Look, the timed storyboard on Storyboard; an animated proof on Make is optional and never holds the final render). Approvals never require typed notes. A sticky header gives one status line ("Step 3 of 6: Storyboard needs you"), the one next action, an Autopilot button, paid-generation spend against the cap and **Project settings** — a drawer holding the render style and services, advanced audio tools, the autopilot brief and runs, and every development file, the external handoff and the making-of export; a **Needs attention** banner under that status line lists any state a half-finished workflow left on the server — an open revision, an interrupted Cast & Sets stage, an auto-review waiting for its revised sections, a final render nobody is watching — with its Resume / Continue / Cancel / Reattach inline, derived from the saved record so it survives a reload; a preview player is docked beside every step — the final render, the live composition document, each finished draft excerpt and, before anything is rendered, a storyboard animatic (the song under each shot's frame or card), picked from the dock (`?play=`) — 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 the known lyrics to the vocal stem with local MMS_FA CTC (downloaded on first use, a garbage token between lines absorbs instrumental gaps; standalone alignment asks for Demucs htdemucs_ft consent before creating a missing stem), 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 run started from the board generates its revised sections on the server too (#10014), routed from the project's saved image and video pins, so it completes with no tab open; a section that cannot be generated unattended (a synchronous image backend, a clip lane only the board can submit) parks the run as needing the director, with the reason named. 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. A footage or composed render can intercut (#9290): shots are re-cut on the song's section energy (every 2 beats in the loudest quarter, up to every 8 in the quietest) and on sung word onsets, alternating the host shot — a lip-synced take stays in sync — with unshown footage from a cutaway in the same section, so the edit gets faster without generating more clips; an autopilot production run defaults to it unless the director chose one cut per shot. Lyric lines sung two or more times are hooks: the treatment's text cues give them a word-by-word build (#9291) — each word lands on its sung onset in heavy caps, the newest in the accent color. Draft excerpts can be re-framed as vertical or square social cuts with faded audio edges, from suggested hook windows (#9280). The **Autonomous** entry point (`docs/features/music-video-autonomous.md`) starts from one prompt instead of a chosen track: it writes the brief, lyrics and a mood board, makes the song in Suno through the PortOS Browser, and runs the production — with optional approval checkpoints, and a `music-video-autopilot` scheduled task that turns unused Brain ideas into videos. 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, LinkedIn, Shorts, TikTok, Instagram Reels, Reddit, Stacker News, Substack, DistroKid) 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. Reddit defaults to a native video post in r/aivideo — title and flair, no body — through the new composer's own Video button (#9307). Platforms are opt-in (#9287): a "Where you post" list turns each one on (all start off) and optionally names the account posted as — X and Reddit drafts filled while signed in as someone else are refused. Copy is drafted and posts are offered only for enabled platforms. Each post (including one recorded by hand) can be rated good, mixed or poor with notes; ratings roll up per platform across projects and are passed to later copy drafts. | — |
+| **Music Video Studio** | `/music-video` | A project is six deep-linked steps (`/music-video/:projectId/:stage` — Song `setup`, Look `cast-sets`, Storyboard `board`, Make `produce`, Final render `review`, Publish `publish`; an old `compose` link opens Make), listed down the left with a state word and one fact each (a bottom icon bar on a phone). Each step opens with what "done" means and an always-visible checklist, and ends with its own approval (art on Look, the timed storyboard on Storyboard; an animated proof on Make is optional and never holds the final render). Approvals never require typed notes. A sticky header gives one status line ("Step 3 of 6: Storyboard needs you"), the one next action, an Autopilot button, paid-generation spend against the cap and **Project settings** — a drawer holding the render style and services, advanced audio tools, the autopilot brief and runs, and every development file, the external handoff and the making-of export; a **Needs attention** banner under that status line lists any state a half-finished workflow left on the server — an open revision, an interrupted Cast & Sets stage, an auto-review waiting for its revised sections, a final render nobody is watching — with its Resume / Continue / Cancel / Reattach inline, derived from the saved record so it survives a reload; a preview player is docked beside every step — the final render, the live composition document, each finished draft excerpt and, before anything is rendered, a storyboard animatic (the song under each shot's frame or card), picked from the dock (`?play=`) — 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 the known lyrics to the vocal stem with local MMS_FA CTC (downloaded on first use, a garbage token between lines absorbs instrumental gaps; standalone alignment asks for Demucs htdemucs_ft consent before creating a missing stem), 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 run started from the board generates its revised sections on the server too (#10014), routed from the project's saved image and video pins, so it completes with no tab open; a section that cannot be generated unattended (a synchronous image backend, a clip lane only the board can submit) parks the run as needing the director, with the reason named. 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. A footage or composed render can intercut (#9290): shots are re-cut on the song's section energy (every 2 beats in the loudest quarter, up to every 8 in the quietest) and on sung word onsets, alternating the host shot — a lip-synced take stays in sync — with unshown footage from a cutaway in the same section, so the edit gets faster without generating more clips; an autopilot production run defaults to it unless the director chose one cut per shot. Lyric lines sung two or more times are hooks: the treatment's text cues give them a word-by-word build (#9291) — each word lands on its sung onset in heavy caps, the newest in the accent color. Draft excerpts can be re-framed as vertical or square social cuts with faded audio edges, from suggested hook windows (#9280). The **Autonomous** entry point (`docs/features/music-video-autonomous.md`) starts from one prompt instead of a chosen track: it writes the brief, lyrics and a mood board, makes the song in Suno through the PortOS Browser, and runs the production — with optional approval checkpoints, and a `music-video-autopilot` scheduled task that turns unused Brain ideas into videos. 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, LinkedIn, Facebook, Shorts, TikTok, Instagram Reels, Reddit, Stacker News, Substack, DistroKid) 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. Reddit defaults to a native video post in r/aivideo — title and flair, no body — through the new composer's own Video button (#9307). Platforms are opt-in (#9287): a "Where you post" list turns each one on (all start off) and optionally names the account posted as — X and Reddit drafts filled while signed in as someone else are refused. Copy is drafted and posts are offered only for enabled platforms. Each post (including one recorded by hand) can be rated good, mixed or poor with notes; ratings roll up per platform across projects and are passed to later copy drafts. | — |
| **Sharing & Conflict Resolution** | `/sharing`, `/sharing/duplicates`, `/sharing/conflicts` | Collaborative asset exchange via cloud storage buckets (Google Drive, Dropbox, iCloud, Syncthing) with duplicate reconciliation and conflict recovery journals. | — |
---
diff --git a/server/lib/musicVideoCrossLinks.js b/server/lib/musicVideoCrossLinks.js
index 027da9dbf5..85114b45ff 100644
--- a/server/lib/musicVideoCrossLinks.js
+++ b/server/lib/musicVideoCrossLinks.js
@@ -11,12 +11,12 @@
/** Every post another post can link to, in the order a link list shows them. */
export const CROSS_LINK_LABELS = Object.freeze({
- suno: 'Song', youtube: 'Music video', x: 'X', tiktok: 'TikTok', instagram: 'Instagram',
+ suno: 'Song', youtube: 'Music video', x: 'X', linkedin: 'LinkedIn', facebook: 'Facebook', tiktok: 'TikTok', instagram: 'Instagram',
reddit: 'Reddit', stackerNews: 'Stacker News', substack: 'Substack', distrokid: 'Streaming',
});
/** Posts whose text can still take links after posting: an edit, or a reply/comment under it. */
-export const CROSS_LINK_EDIT_TARGETS = Object.freeze(['youtube', 'suno', 'x', 'stackerNews']);
+export const CROSS_LINK_EDIT_TARGETS = Object.freeze(['youtube', 'suno', 'x', 'stackerNews', 'facebook']);
// What each draft linked before posts recorded their links.
const LEGACY_LINKS = { youtube: [], suno: ['youtube'], x: ['suno', 'youtube'], stackerNews: ['youtube'] };
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 8c2348e86f..3e3bb86918 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -708,6 +708,7 @@ export const musicVideoPublishCopyPatchSchema = z.object({
shorts: z.object({ title: kitText(100), description: kitText(5000) }).partial().strict().optional(),
x: z.object({ hook: kitText(280), story: kitText(25000) }).partial().strict().optional(),
linkedin: z.object({ post: kitText(3000) }).partial().strict().optional(),
+ facebook: z.object({ post: kitText(63206) }).partial().strict().optional(),
tiktok: z.object({ caption: kitText(2200) }).partial().strict().optional(),
instagram: z.object({ caption: kitText(2200) }).partial().strict().optional(),
reddit: z.object({ title: kitText(300), body: kitText(40000) }).partial().strict().optional(),
@@ -786,7 +787,7 @@ export const musicVideoCoverArtGenerateSchema = z.object({
// #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', 'linkedin', 'reddit', 'stackerNews', 'substack', 'suno', 'sunoHook', 'distrokid']);
+export const MUSIC_VIDEO_PUBLISH_TARGETS = Object.freeze(['youtube', 'shorts', 'tiktok', 'instagram', 'x', 'linkedin', 'facebook', 'reddit', 'stackerNews', 'substack', 'suno', 'sunoHook', 'distrokid']);
export const musicVideoPublishTargetSchema = z.enum(MUSIC_VIDEO_PUBLISH_TARGETS);
const publishUrl = z.string().url().max(500);
// #9287: which platforms the director posts to (opt-in), the account for each,
@@ -819,7 +820,7 @@ export const musicVideoPublishPrepareSchema = z.object({
flairId: z.string().max(100),
flairText: z.string().max(64),
firstComment: kitText(10000),
- // LinkedIn: put the full video and song links in a first comment (default on).
+ // LinkedIn, Facebook: put the full video and song links in a first comment (default on).
linksComment: z.boolean(),
territory: z.string().max(40),
// Substack: the publication (name.substack.com or a custom domain); defaults to the account under Where you post.
diff --git a/server/services/musicVideo/publish/crossLinkEdits.js b/server/services/musicVideo/publish/crossLinkEdits.js
index fe1f50e6a9..7e56f4e9a7 100644
--- a/server/services/musicVideo/publish/crossLinkEdits.js
+++ b/server/services/musicVideo/publish/crossLinkEdits.js
@@ -2,13 +2,15 @@
* Backfill cross-links: open a post that is already up and add the links to
* the release's posts made after it. Each prepare() fills a form in its own
* tab and stops there: the director reviews it and presses Save (YouTube,
- * Suno) or Reply (X, Stacker News). PortOS never saves, posts or deletes.
+ * Suno), Reply (X, Stacker News) or Enter (a Facebook comment). PortOS never
+ * saves, posts or deletes.
*
* `row` is one `crossLinkBackfill()` entry: `{ target, url, missing, text }`,
* `text` being the `Label: url` lines to add.
*/
import { PUBLISH_STEP_TIMEOUT_MS as T, loginRequired, pasteText, step } from './browser.js';
import { markSunoSongMenu } from '../../../lib/sunoPage.js';
+import { facebookSignedOut, typeFacebookComment } from './facebook.js';
// Suno's caption limit; the new-draft builder enforces the same one.
const SUNO_CAPTION_MAX = 500;
@@ -120,4 +122,15 @@ const stackerNews = {
},
};
-export const CROSS_LINK_ADAPTERS = Object.freeze({ youtube, suno, x, stackerNews });
+const facebook = {
+ label: 'Facebook',
+ async prepare(page, row) {
+ await step(this.label, 'open the post', () => page.goto(row.url, { waitUntil: 'domcontentloaded', timeout: T }));
+ await page.waitForTimeout(4000);
+ if (await facebookSignedOut(page)) throw loginRequired(this.label, 'https://www.facebook.com/login');
+ await step(this.label, 'write the comment', () => typeFacebookComment(page, row.text));
+ return { added: row.text.split('\n'), leftForYou: ['Enter (sends the comment)'] };
+ },
+};
+
+export const CROSS_LINK_ADAPTERS = Object.freeze({ youtube, suno, x, stackerNews, facebook });
diff --git a/server/services/musicVideo/publish/crossLinkEdits.test.js b/server/services/musicVideo/publish/crossLinkEdits.test.js
index d1cf8cb0c3..43811acf94 100644
--- a/server/services/musicVideo/publish/crossLinkEdits.test.js
+++ b/server/services/musicVideo/publish/crossLinkEdits.test.js
@@ -55,4 +55,15 @@ describe('cross-link edits', () => {
expect(filled.every((t) => t.length <= 500)).toBe(true);
expect(summary.leftForYou[0]).toContain('https://stacker.news/items/7');
});
+
+ it('types the missing links as a comment on the Facebook post and leaves sending it to the director', async () => {
+ const pasted = [];
+ const box = { click: async () => {}, evaluate: async (_fn, t) => pasted.push(t), innerText: async () => pasted.join('') };
+ const page = fakePage({ count: 0 });
+ page.locator = (sel) => (String(sel).includes('comment') ? { first: () => box } : { count: async () => 0 });
+ const summary = await CROSS_LINK_ADAPTERS.facebook.prepare(page, row('facebook', 'https://www.facebook.com/reel/1'));
+ expect(page.goto.mock.calls[0][0]).toBe('https://www.facebook.com/reel/1');
+ expect(pasted).toEqual([row('facebook').text]);
+ expect(summary.leftForYou).toEqual(['Enter (sends the comment)']);
+ });
});
diff --git a/server/services/musicVideo/publish/facebook.js b/server/services/musicVideo/publish/facebook.js
new file mode 100644
index 0000000000..f2c7fee9b0
--- /dev/null
+++ b/server/services/musicVideo/publish/facebook.js
@@ -0,0 +1,141 @@
+/**
+ * Facebook adapter: a native video post (Facebook shows uploaded video to far
+ * more people than a post with an outside link, and since 2025 every uploaded
+ * video is shared as a reel), with short text and the links, when the
+ * director wants them, saved for the first comment instead.
+ *
+ * prepare() opens the feed's "What's on your mind" composer, pastes the text,
+ * attaches the 1080p encode through Photo/video and waits for the upload.
+ * PortOS never presses Next or Post. The composer posts as whichever profile
+ * is active in the PortOS Browser, so a Page posts the same way once the
+ * director switches to it.
+ *
+ * Facebook stays on the feed after Post. Once the director opens the new post
+ * (its timestamp), findPost records the post's link and, when there is a
+ * first comment, types it into the comment box: the director presses Enter.
+ *
+ * Like LinkedIn's share box, everything goes through Playwright locators
+ * (they pierce open shadow roots), never `document` queries.
+ */
+import { PUBLISH_STEP_TIMEOUT_MS as T, loginRequired, step } from './browser.js';
+
+const label = 'Facebook';
+const HOME_URL = 'https://www.facebook.com/';
+const SIGN_IN = /facebook\.com\/(?:login|checkpoint|recover|r\.php)/;
+const TEXTBOX = '[role=textbox][contenteditable=true]';
+// The composer is the dialog holding the post's text box (a notification can be another dialog).
+const COMPOSER = `[role=dialog]:has(${TEXTBOX})`;
+const COMMENT_BOX = `${TEXTBOX}[aria-label*="comment" i]`;
+// Drafts whose first comment was already typed: a reload of the post page must not type it twice.
+const commented = new WeakSet();
+const UPLOAD_WAIT_MS = 600_000;
+// A post's own page: a reel (every uploaded video), a video, a post, or a permalink.
+const POST_URL = /^https:\/\/(?:www|web|m)\.facebook\.com\/(?:reel\/\d+|[\w.-]+\/(?:posts|videos)\/[\w.-]+|permalink\.php\?[^#]*story_fbid=[\w-]+[^#]*|watch\/?\?v=\d+)/;
+
+/** The post's opening words, as the post page shows them (Facebook folds the rest under "See more"). */
+const opening = (text) => String(text || '').split('\n').map((line) => line.trim()).find(Boolean) || '';
+
+/** The last visible button named exactly `name` (its text or aria-label: Photo/video is an icon) inside `scope`. */
+const button = (scope, name) => scope.getByRole('button', { name, exact: true }).filter({ visible: true }).last();
+
+/**
+ * Write `text` into the Lexical editor `locator` matches. A synthetic paste
+ * keeps the line breaks (and opens no @mention picker); when Lexical ignores
+ * it, the lines are typed with Enter between.
+ */
+async function pasteInto(page, locator, text) {
+ await locator.click({ timeout: T });
+ await locator.evaluate((el, txt) => {
+ el.focus();
+ const data = new DataTransfer();
+ data.setData('text/plain', txt);
+ el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
+ }, text);
+ await page.waitForTimeout(500);
+ if ((await locator.innerText()).trim()) return;
+ for (const [i, line] of String(text).split('\n').entries()) {
+ if (i > 0) await page.keyboard.press('Enter');
+ if (line) await page.keyboard.insertText(line);
+ }
+}
+
+/** Whether the composer is done uploading: no progress bar or Uploading/Processing note. */
+async function uploadSettled(page) {
+ const composer = page.locator(COMPOSER).last();
+ if (!(await composer.locator('video, img').count())) return false;
+ if (await composer.locator('[role=progressbar], progress').count()) return false;
+ return !(await page.locator(COMPOSER).filter({ hasText: /Uploading|Processing/i }).count());
+}
+
+async function openComposer(page) {
+ await step(label, 'open Facebook', () => page.goto(HOME_URL, { waitUntil: 'domcontentloaded', timeout: T }));
+ await page.waitForTimeout(4000);
+ if (await facebookSignedOut(page)) throw loginRequired(label, 'https://www.facebook.com/login');
+ await step(label, 'open the post composer', async () => {
+ await page.locator('[role=button]:visible', { hasText: /on your mind/i }).first().click({ timeout: T });
+ await page.locator(`${COMPOSER} ${TEXTBOX}`).first().waitFor({ timeout: T });
+ });
+}
+
+async function attachVideo(page, video) {
+ await step(label, 'attach the video', async () => {
+ const composer = page.locator(COMPOSER).last();
+ // Photo/video opens the composer's media area, which holds the file input.
+ await button(composer, 'Photo/video').click({ timeout: T });
+ const input = composer.locator('input[type=file]').first();
+ if (await input.waitFor({ state: 'attached', timeout: 10_000 }).then(() => true, () => false)) {
+ await input.setInputFiles(video.path);
+ return;
+ }
+ const [chooser] = await Promise.all([
+ page.waitForEvent('filechooser', { timeout: T }),
+ composer.locator('[role=button]', { hasText: /Add photos\/videos/i }).first().click({ timeout: T }),
+ ]);
+ await chooser.setFiles(video.path);
+ });
+}
+
+/** Type `text` into the open post's comment box (never sent: the director presses Enter). */
+export const typeFacebookComment = (page, text) => pasteInto(page, page.locator(COMMENT_BOX).first(), text);
+
+/** Whether a page shows Facebook's sign-in form instead of the signed-in site. */
+export const facebookSignedOut = async (page) => SIGN_IN.test(page.url()) || (await page.locator('input[name=pass]').count()) > 0;
+
+export const facebookAdapter = {
+ label,
+ async prepare(page, payload) {
+ await openComposer(page);
+ await step(label, 'write the post', () => pasteInto(page, page.locator(`${COMPOSER} ${TEXTBOX}`).first(), payload.text));
+ await attachVideo(page, payload.video);
+ await step(label, 'wait for the upload', async () => {
+ const deadline = Date.now() + UPLOAD_WAIT_MS;
+ while (!(await uploadSettled(page))) {
+ if (Date.now() > deadline) throw new Error('the upload did not finish');
+ await page.waitForTimeout(2000);
+ }
+ });
+ const composer = page.locator(COMPOSER).last();
+ const length = await composer.locator(TEXTBOX).first().innerText().then((t) => t.trim().length, () => null);
+ const next = await button(composer, 'Next').count().catch(() => 0);
+ return {
+ characters: length,
+ // A video post may ask for Next (post settings) before Post; neither is pressed here.
+ youPress: next ? 'Next, then Post' : 'Post',
+ firstComment: payload.firstComment ? 'Typed into the comment box once you press Post and open the post' : null,
+ };
+ },
+ async findPost(page, payload) {
+ const match = page.url().match(POST_URL);
+ const want = opening(payload.text).slice(0, 30);
+ if (!match || !want) return null;
+ const shown = await page.getByText(want).first().waitFor({ timeout: 15_000 }).then(() => true, () => false);
+ const url = shown ? match[0] : null;
+ if (url && payload.firstComment && !commented.has(payload)) {
+ commented.add(payload);
+ // Typed, never sent: the director presses Enter. A miss still records the post.
+ await typeFacebookComment(page, payload.firstComment)
+ .catch((err) => console.warn(`⚠️ ${label}: could not type the first comment (${err?.message?.split('\n')[0]})`));
+ }
+ return url;
+ },
+};
diff --git a/server/services/musicVideo/publish/facebook.test.js b/server/services/musicVideo/publish/facebook.test.js
new file mode 100644
index 0000000000..994fbc779e
--- /dev/null
+++ b/server/services/musicVideo/publish/facebook.test.js
@@ -0,0 +1,92 @@
+/**
+ * Facebook adapter: the composer gets the post text and the video and is left
+ * for the director's Post; once they open the new post, its link is recorded
+ * and the first comment is typed (never sent).
+ */
+import { describe, expect, it, vi } from 'vitest';
+import { facebookAdapter } from './facebook.js';
+
+// A page whose elements exist only for locators, logging every click, paste and file.
+function fakePage({ url = 'https://www.facebook.com/', shows = '', signedOut = false, nextButton = false } = {}) {
+ const log = [];
+ const typed = {};
+ let uploaded = false;
+ const element = (sel, name) => {
+ const el = {
+ first: () => el,
+ last: () => el,
+ filter: (opts) => element(sel, opts?.hasText?.source || name),
+ locator: (child, opts) => element(`${sel} ${child}`, opts?.hasText?.source || name),
+ getByRole: (_role, opts) => element(`${sel} button`, opts.name),
+ count: async () => {
+ if (/input\[name=pass\]/.test(sel)) return signedOut ? 1 : 0;
+ if (/progressbar/.test(sel)) return 0;
+ if (/video, img/.test(sel)) return uploaded ? 1 : 0;
+ if (name === 'Next') return nextButton ? 1 : 0;
+ return /Uploading/.test(String(name)) ? 0 : 1;
+ },
+ waitFor: async () => {},
+ click: async () => { log.push(['click', name || sel]); },
+ setInputFiles: async (path) => { log.push(['setFiles', path]); uploaded = true; },
+ evaluate: async (_fn, text) => { typed[sel] = text; log.push(['paste', sel, text]); },
+ innerText: async () => typed[sel] || '',
+ };
+ return el;
+ };
+ return {
+ log,
+ goto: async (to) => { log.push(['goto', to]); },
+ url: () => url,
+ waitForTimeout: async () => {},
+ keyboard: { press: async () => {}, insertText: async () => {} },
+ getByText: (want) => ({ first: () => ({ waitFor: async () => { if (!shows.includes(want)) throw new Error('timeout'); } }) }),
+ locator: (sel, opts) => element(sel, opts?.hasText?.source),
+ };
+}
+
+const payload = { video: { path: '/videos/x.mp4' }, text: 'I made a music video.\n\nMore.', firstComment: 'Full video: https://youtu.be/abc' };
+
+describe('Facebook adapter', () => {
+ it('writes the post and uploads the video, never pressing Next or Post', async () => {
+ const page = fakePage({ nextButton: true });
+ const summary = await facebookAdapter.prepare(page, payload);
+ expect(page.log[0]).toEqual(['goto', 'https://www.facebook.com/']);
+ expect(page.log).toContainEqual(['click', 'on your mind']);
+ expect(page.log).toContainEqual(['click', 'Photo/video']);
+ expect(page.log).toContainEqual(['setFiles', '/videos/x.mp4']);
+ expect(page.log.find(([kind]) => kind === 'paste')[2]).toBe(payload.text);
+ expect(page.log.some(([kind, what]) => kind === 'click' && /^(Post|Next)$/.test(what))).toBe(false);
+ expect(summary).toMatchObject({ characters: payload.text.length, youPress: 'Next, then Post', firstComment: expect.stringMatching(/open the post/) });
+ });
+
+ it('asks for sign-in when Facebook shows its login form', async () => {
+ await expect(facebookAdapter.prepare(fakePage({ signedOut: true }), payload)).rejects.toMatchObject({ code: 'PUBLISH_LOGIN_REQUIRED' });
+ });
+
+ it('records the opened reel and types the first comment once, without sending it', async () => {
+ const page = fakePage({ url: 'https://www.facebook.com/reel/1234567890?s=x', shows: 'I made a music video.' });
+ const draft = { ...payload };
+ await expect(facebookAdapter.findPost(page, draft)).resolves.toBe('https://www.facebook.com/reel/1234567890');
+ expect(page.log.filter(([kind]) => kind === 'paste').map(([, sel, text]) => [/comment/.test(sel), text])).toEqual([[true, payload.firstComment]]);
+ // A reload of the post page records it again but never types the comment twice.
+ await facebookAdapter.findPost(page, draft);
+ expect(page.log.filter(([kind]) => kind === 'paste')).toHaveLength(1);
+ });
+
+ it('ignores the feed and other people\'s posts', async () => {
+ await expect(facebookAdapter.findPost(fakePage({ url: 'https://www.facebook.com/' }), payload)).resolves.toBeNull();
+ const other = fakePage({ url: 'https://www.facebook.com/someone/posts/pfbid0abc', shows: 'Someone else' });
+ await expect(facebookAdapter.findPost(other, payload)).resolves.toBeNull();
+ expect(other.log).toEqual([]);
+ });
+
+ it('still records the post when the comment box cannot be found', async () => {
+ const page = fakePage({ url: 'https://www.facebook.com/example/videos/42', shows: 'I made a music video.' });
+ const base = page.locator;
+ page.locator = (sel, opts) => (/comment/.test(sel) ? { first() { return this; }, click: async () => { throw new Error('no comment box'); } } : base(sel, opts));
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ await expect(facebookAdapter.findPost(page, { ...payload })).resolves.toBe('https://www.facebook.com/example/videos/42');
+ expect(warn).toHaveBeenCalled();
+ warn.mockRestore();
+ });
+});
diff --git a/server/services/musicVideo/publish/index.js b/server/services/musicVideo/publish/index.js
index 8c2fbd1e6f..7d24102c55 100644
--- a/server/services/musicVideo/publish/index.js
+++ b/server/services/musicVideo/publish/index.js
@@ -23,6 +23,7 @@ import { tiktokAdapter } from './tiktok.js';
import { instagramAdapter } from './instagram.js';
import { xAdapter } from './x.js';
import { linkedinAdapter } from './linkedin.js';
+import { facebookAdapter } from './facebook.js';
import { redditAdapter } from './reddit.js';
import { stackerNewsAdapter } from './stackerNews.js';
import { substackAdapter } from './substack.js';
@@ -35,7 +36,7 @@ import { carriedLinks, crossLinkBackfill, dropCarriedLink, mergeCarriedLinks } f
export const PUBLISH_ADAPTERS = Object.freeze({
youtube: youtubeAdapter, shorts: shortsAdapter, tiktok: tiktokAdapter, instagram: instagramAdapter,
- x: xAdapter, linkedin: linkedinAdapter, reddit: redditAdapter, stackerNews: stackerNewsAdapter, substack: substackAdapter, suno: sunoAdapter, sunoHook: sunoHookAdapter, distrokid: distrokidAdapter,
+ x: xAdapter, linkedin: linkedinAdapter, facebook: facebookAdapter, reddit: redditAdapter, stackerNews: stackerNewsAdapter, substack: substackAdapter, suno: sunoAdapter, sunoHook: sunoHookAdapter, distrokid: distrokidAdapter,
});
// The tab stays open past this: the human publishes from it. After the TTL only
// the CDP session is dropped; the tab closes on Discard, Fill again, or by hand.
@@ -115,7 +116,7 @@ async function recordDetectedPost(draft, url) {
/**
* Follow a filled tab while its session is attached: each time it navigates,
* the adapter's `findPost` says whether it now shows the director's new post
- * (by URL and title). PortOS presses nothing: at most it types a first comment for the director to send (LinkedIn).
+ * (by URL and title). PortOS presses nothing: at most it types a first comment for the director to send (LinkedIn, Facebook).
*/
function watchForPost(draft, adapter) {
const { page } = draft;
diff --git a/server/services/musicVideo/publish/payloads.js b/server/services/musicVideo/publish/payloads.js
index 58930e9697..aa027f66a6 100644
--- a/server/services/musicVideo/publish/payloads.js
+++ b/server/services/musicVideo/publish/payloads.js
@@ -16,6 +16,8 @@ const DEFAULT_SUBREDDIT = 'aivideo';
// LinkedIn's limits for a video post made from a computer: 3,000 characters of text, 15 minutes of video.
const LINKEDIN_POST_MAX = 3000;
const LINKEDIN_VIDEO_MAX_SEC = 15 * 60;
+// Facebook's post text limit; uploaded video has no practical length limit (every upload is a reel since 2025).
+const FACEBOOK_POST_MAX = 63206;
const missing = (message) => new ServerError(message, { status: 422, code: 'PUBLISH_ASSET_MISSING' });
const stale = () => new ServerError('The publishing kit was built from an earlier render — rebuild the kit before filling this draft', { status: 409, code: 'PUBLISH_KIT_STALE' });
@@ -144,6 +146,29 @@ const releaseCover = (kit) => {
return kit.thumbnail ? { dir: 'videoThumbnails', name: kit.thumbnail } : null;
};
+/** The 1080p encode a native video post (LinkedIn, Facebook) uploads. */
+function nativeVideo(project, kit, platform) {
+ const clip = (kit.exports || []).find((e) => e.kind === 'x-1080p')?.filename;
+ if (!clip) throw missing(`Build the publishing kit first — the ${platform} post uploads its 1080p encode`);
+ requireFreshKit(project, kit);
+ return { dir: 'videos', name: clip };
+}
+
+/**
+ * A native video post's first comment (unless the director turned it off):
+ * the full video and the song, then the release's other posts.
+ */
+function linksComment(kit, options, self) {
+ if (options.linksComment === false) return { firstComment: null, crossLinks: [] };
+ const lead = [
+ fullVideoUrl(kit) ? { target: 'youtube', line: `Full video: ${fullVideoUrl(kit)}` } : null,
+ songUrl(kit, options) ? { target: 'suno', line: `The song: ${songUrl(kit, options)}` } : null,
+ ].filter(Boolean);
+ const others = otherPosts(kit, options, '', { exclude: ['youtube', 'suno', self] });
+ const lines = [...lead.map((l) => l.line), ...others.lines];
+ return { firstComment: lines.join('\n') || null, crossLinks: [...lead.map((l) => l.target), ...others.carried] };
+}
+
const BUILDERS = {
youtube: (project, kit, options = {}) => {
if (!kit.master?.filename) throw missing('Build the publishing kit first — it names the final render to upload');
@@ -200,16 +225,17 @@ const BUILDERS = {
const post = text(kit.copy?.linkedin?.post);
if (!post) throw missing('Write the LinkedIn post in the release copy first');
if (post.length > LINKEDIN_POST_MAX) throw missing(`The LinkedIn post is ${post.length} characters; the limit is ${LINKEDIN_POST_MAX}`);
- const clip = (kit.exports || []).find((e) => e.kind === 'x-1080p')?.filename;
- if (!clip) throw missing('Build the publishing kit first — the LinkedIn post uploads its 1080p encode');
- requireFreshKit(project, kit);
+ const video = nativeVideo(project, kit, 'LinkedIn');
const duration = Number(project?.audioAnalysis?.durationSec);
if (duration > LINKEDIN_VIDEO_MAX_SEC) throw missing(`LinkedIn takes videos up to 15 minutes; this one is ${Math.ceil(duration / 60)}`);
- const links = options.linksComment === false ? '' : [
- fullVideoUrl(kit) ? `Full video: ${fullVideoUrl(kit)}` : '',
- songUrl(kit, options) ? `The song: ${songUrl(kit, options)}` : '',
- ].filter(Boolean).join('\n');
- return { video: { dir: 'videos', name: clip }, text: post, firstComment: links || null };
+ return { video, text: post, ...linksComment(kit, options, 'linkedin') };
+ },
+ // The same shape as LinkedIn: Facebook favors uploaded video over outside links.
+ facebook: (project, kit, options = {}) => {
+ const post = text(kit.copy?.facebook?.post);
+ if (!post) throw missing('Write the Facebook post in the release copy first');
+ if (post.length > FACEBOOK_POST_MAX) throw missing(`The Facebook post is ${post.length} characters; the limit is ${FACEBOOK_POST_MAX}`);
+ return { video: nativeVideo(project, kit, 'Facebook'), text: post, ...linksComment(kit, options, 'facebook') };
},
reddit: (project, kit, options = {}) => {
// r/aivideo is the default (#9307): a native video post, title + flair, no
@@ -385,9 +411,10 @@ export function publishPreviewParts(platform, project, payload) {
});
break;
case 'linkedin':
+ case 'facebook':
add('Video', 'The 1080p encode of the final render');
add('Post', p.text);
- add('First comment (you press Comment)', p.firstComment);
+ add(platform === 'facebook' ? 'First comment (you press Enter)' : 'First comment (you press Comment)', p.firstComment);
break;
case 'reddit':
add('Where', `r/${p.subreddit}`);
diff --git a/server/services/musicVideo/publish/payloads.test.js b/server/services/musicVideo/publish/payloads.test.js
index 56604a1b93..d255211a90 100644
--- a/server/services/musicVideo/publish/payloads.test.js
+++ b/server/services/musicVideo/publish/payloads.test.js
@@ -52,6 +52,7 @@ describe('buildPublishPayload (#9282)', () => {
expect(p).toEqual({
video: { dir: 'videos', name: 'x.mp4' }, text: 'I made a music video.',
firstComment: 'Full video: https://youtu.be/abc\nThe song: https://suno.com/song/12345678-abcd-4abc-8abc-123456789abc',
+ crossLinks: ['youtube', 'suno'],
});
expect(publishPreviewParts('linkedin', project(), p).map((r) => r.label)).toEqual(['Video', 'Post', 'First comment (you press Comment)']);
expect(buildPublishPayload('linkedin', project(), { linksComment: false }).firstComment).toBeNull();
@@ -60,6 +61,19 @@ describe('buildPublishPayload (#9282)', () => {
expect(() => buildPublishPayload('linkedin', { ...project(), audioAnalysis: { durationSec: 16 * 60 } })).toThrow(/up to 15 minutes/);
});
+ it('uploads the 1080p encode to Facebook with the full video, song and other posts in the first comment', () => {
+ const posted = project({ copy: { facebook: { post: 'I made a music video.' } }, posts: { x: { url: 'https://x.com/example/status/42' }, facebook: { url: 'https://www.facebook.com/reel/1' } } });
+ const p = buildPublishPayload('facebook', posted);
+ expect(p).toEqual({
+ video: { dir: 'videos', name: 'x.mp4' }, text: 'I made a music video.',
+ firstComment: 'Full video: https://youtu.be/abc\nThe song: https://suno.com/song/12345678-abcd-4abc-8abc-123456789abc\nX: https://x.com/example/status/42',
+ crossLinks: ['youtube', 'suno', 'x'],
+ });
+ expect(publishPreviewParts('facebook', posted, p).map((r) => r.label)).toEqual(['Video', 'Post', 'First comment (you press Enter)']);
+ expect(buildPublishPayload('facebook', posted, { linksComment: false })).toMatchObject({ firstComment: null, crossLinks: [] });
+ expect(() => buildPublishPayload('facebook', project())).toThrow(/Facebook post/);
+ });
+
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');
diff --git a/server/services/musicVideo/publishKitText.js b/server/services/musicVideo/publishKitText.js
index 2a998e6bc4..f8e0e5203c 100644
--- a/server/services/musicVideo/publishKitText.js
+++ b/server/services/musicVideo/publishKitText.js
@@ -111,9 +111,9 @@ export function buildSrt(project) {
// ---- per-platform copy (one user-triggered LLM call) ----
-export const PUBLISH_PLATFORMS = Object.freeze(['youtube', 'shorts', 'x', 'linkedin', 'tiktok', 'instagram', 'reddit', 'stackerNews', 'substack']);
+export const PUBLISH_PLATFORMS = Object.freeze(['youtube', 'shorts', 'x', 'linkedin', 'facebook', 'tiktok', 'instagram', 'reddit', 'stackerNews', 'substack']);
// Each platform's own title ceiling; the parser clips rather than rejecting.
-const LIMITS = { youtubeTitle: 100, shortsTitle: 100, xHook: 280, linkedinPost: 3000, redditTitle: 300, stackerNewsTitle: 80, substackTitle: 100, substackSubtitle: 250, caption: 2200 };
+const LIMITS = { youtubeTitle: 100, shortsTitle: 100, xHook: 280, linkedinPost: 3000, facebookPost: 63206, redditTitle: 300, stackerNewsTitle: 80, substackTitle: 100, substackSubtitle: 250, caption: 2200 };
const str = (v, max) => (typeof v === 'string' && v.trim() ? v.trim().slice(0, max) : '');
@@ -142,6 +142,7 @@ function copySpecs({ include, length }) {
shorts: `"shorts":{"title":"<=100 chars${tags ? ', ends with #shorts' : ''}","description":"1-2 sentences + the full video URL if given"}`,
x: `"x":{"hook":"<=280 chars, ${short ? 'one or two sentences' : 'one surprising claim'}, no links","story":"${short ? 'empty string' : 'the making-of as a long post'}"}`,
linkedin: `"linkedin":{"post":"${short ? '1-2 sentences' : '2-4 short sentences'}, no links${tags ? ', may end with 2-3 hashtags' : ''}"}`,
+ facebook: `"facebook":{"post":"${short ? '1-2 sentences' : '2-4 short sentences'}, no links"}`,
tiktok: `"tiktok":{"caption":"1-2 sentences${tags ? ' + 4-6 hashtags' : ''}"}`,
instagram: `"instagram":{"caption":"1-2 sentences${tags ? ' + 4-6 hashtags' : ''}"}`,
reddit: `"reddit":{"title":"<=300 chars","body":"${body('markdown: what it is and how it was made')}"}`,
@@ -245,6 +246,7 @@ export function parsePublishCopy(text, platforms = PUBLISH_PLATFORMS, { hashtags
shorts: () => ({ title: str(v('shorts').title, LIMITS.shortsTitle), description: str(v('shorts').description, 5000) }),
x: () => ({ hook: str(v('x').hook, LIMITS.xHook), story: str(v('x').story, 25000) }),
linkedin: () => ({ post: str(v('linkedin').post, LIMITS.linkedinPost) }),
+ facebook: () => ({ post: str(v('facebook').post, LIMITS.facebookPost) }),
tiktok: () => ({ caption: str(v('tiktok').caption, LIMITS.caption) }),
instagram: () => ({ caption: str(v('instagram').caption, LIMITS.caption) }),
reddit: () => ({ title: str(v('reddit').title, LIMITS.redditTitle), body: str(v('reddit').body, 40000) }),