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
Add LinkedIn as a music video publish destination
Claudedeb1557ce31e
diff --git a/client/src/components/musicVideo/PublishKitPanel.jsx b/client/src/components/musicVideo/PublishKitPanel.jsxindex e6ffc9faae..525a666c83 100644--- a/client/src/components/musicVideo/PublishKitPanel.jsx+++ b/client/src/components/musicVideo/PublishKitPanel.jsx@@ -22,6 +22,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: '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.jsxindex 59652857e2..657fd055e3 100644--- a/client/src/components/musicVideo/PublishPostingPanel.jsx+++ b/client/src/components/musicVideo/PublishPostingPanel.jsx@@ -13,6 +13,10 @@ export const PUBLISH_TARGETS = [{ target: 'suno', label: 'Suno', note: 'Publishes the song with the cover and a link to the video' },{ target: 'sunoHook', label: 'Suno Hook', note: 'A 9:16 cut (the newest by default) set to its window of the song. You press Post' },{ target: 'x', label: 'X thread', note: 'Hook with the 1080p video, then the story, prompt and links' },+ {+ 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: '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' },@@ -141,6 +145,13 @@ function TargetOptions({ target, kit, project, options, setOption, commitOption,</div>);}+ if (target === 'linkedin') {+ 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+ </label>+ );+ }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>;}diff --git a/client/src/components/musicVideo/PublishPostingPanel.test.jsx b/client/src/components/musicVideo/PublishPostingPanel.test.jsxindex fc5454e63b..122b258483 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', 'shorts', 'tiktok', 'instagram', 'reddit', 'stackerNews', 'substack', 'distrokid'];+const ALL = ['youtube', 'suno', 'sunoHook', 'x', 'linkedin', '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,6 +64,20 @@ 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', () => {+ 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');+ expect(links).toBeChecked();+ fireEvent.click(within(linkedin).getByRole('button', { name: 'Fill draft' }));+ expect(publishing.prepare).toHaveBeenCalledWith('linkedin', {});+ fireEvent.click(links);+ fireEvent.click(within(linkedin).getByRole('button', { name: 'Fill draft' }));+ expect(publishing.prepare).toHaveBeenLastCalledWith('linkedin', { linksComment: false });+ });+it('picks the X story image from thumbnails, with No image as the default', () => {const publishing = hook();render(<PublishPostingPanel project={project({ thumbnails: ['t1.jpg', 't2.jpg'] })} publishing={publishing} />);diff --git a/docs/features/music-video-autonomous.md b/docs/features/music-video-autonomous.mdindex 68e5ca4b8e..19fa6a1920 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), PortOS records that link itself while the tab's session is attached; 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, 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.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.mdindex 796692cc6e..0607d5e0d8 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, 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, 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/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 2a0be87d1d..5b23c0c75e 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -706,6 +706,7 @@ export const musicVideoPublishCopyPatchSchema = z.object({youtube: z.object({ title: kitText(100), description: kitText(5000), tags: z.array(kitText(60)).max(30) }).partial().strict().optional(),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(),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(),@@ -784,7 +785,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', 'reddit', 'stackerNews', 'substack', 'suno', 'sunoHook', 'distrokid']);+export const MUSIC_VIDEO_PUBLISH_TARGETS = Object.freeze(['youtube', 'shorts', 'tiktok', 'instagram', 'x', 'linkedin', '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,@@ -811,6 +812,8 @@ 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).+ 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.publication: z.string().trim().min(1).max(200),diff --git a/server/services/musicVideo/publish/index.js b/server/services/musicVideo/publish/index.jsindex add3cb375d..2fe32e99ff 100644--- a/server/services/musicVideo/publish/index.js+++ b/server/services/musicVideo/publish/index.js@@ -22,6 +22,7 @@ import { youtubeAdapter, shortsAdapter } from './youtube.js';import { tiktokAdapter } from './tiktok.js';import { instagramAdapter } from './instagram.js';import { xAdapter } from './x.js';+import { linkedinAdapter } from './linkedin.js';import { redditAdapter } from './reddit.js';import { stackerNewsAdapter } from './stackerNews.js';import { substackAdapter } from './substack.js';@@ -32,7 +33,7 @@ import { musicVideoEvents } from '../events.js';export const PUBLISH_ADAPTERS = Object.freeze({youtube: youtubeAdapter, shorts: shortsAdapter, tiktok: tiktokAdapter, instagram: instagramAdapter,- x: xAdapter, reddit: redditAdapter, stackerNews: stackerNewsAdapter, substack: substackAdapter, suno: sunoAdapter, sunoHook: sunoHookAdapter, distrokid: distrokidAdapter,+ x: xAdapter, linkedin: linkedinAdapter, 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.@@ -112,7 +113,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). Reads only; PortOS still presses nothing.+ * (by URL and title). PortOS presses nothing: at most it types a first comment for the director to send (LinkedIn).*/function watchForPost(draft, adapter) {const { page } = draft;diff --git a/server/services/musicVideo/publish/linkedin.js b/server/services/musicVideo/publish/linkedin.jsnew file mode 100644index 0000000000..97be27bacb--- /dev/null+++ b/server/services/musicVideo/publish/linkedin.js@@ -0,0 +1,93 @@+/**+ * LinkedIn adapter: a native video post (LinkedIn shows uploaded video to far+ * more people than a post with an outside link), with short text and the+ * links, when the director wants them, saved for the first comment instead.+ *+ * prepare() opens the feed's share box, uploads the 1080p encode through the+ * Add media chooser, steps through the media editor's Next (that only returns+ * to the composer), pastes the text, and waits for the upload. PortOS never+ * presses Post.+ *+ * LinkedIn stays on the feed after Post and offers "View post" in a toast.+ * Once the director opens it, findPost records the post's link and, when there+ * is a first comment, types it into the post's comment box: the director+ * presses Comment.+ */+import { PUBLISH_STEP_TIMEOUT_MS as T, clickVisibleText, landedOnPost, loginRequired, pasteText, step } from './browser.js';++const label = 'LinkedIn';+const SHARE_URL = 'https://www.linkedin.com/feed/?shareActive=true';+const SIGN_IN = /linkedin\.com\/(?:login|authwall|checkpoint|uas\/login|signup)/;+const DIALOG = '[role=dialog]';+const EDITOR = `${DIALOG} .ql-editor[contenteditable=true]`;+const COMMENT_EDITOR = '.comments-comment-box .ql-editor[contenteditable=true], .comments-comment-texteditor .ql-editor[contenteditable=true]';+const POST_URL = /^https:\/\/www\.linkedin\.com\/feed\/update\/urn:li:(?:activity|share|ugcPost):\d+/;++/** The post's opening words, as the post page shows them (its first line; LinkedIn folds the rest under "see more"). */+const opening = (text) => String(text || '').split('\n').map((line) => line.trim()).find(Boolean) || '';++async function openComposer(page) {+ await step(label, 'open the share box', () => page.goto(SHARE_URL, { waitUntil: 'domcontentloaded', timeout: T }));+ await page.waitForTimeout(4000);+ if (SIGN_IN.test(page.url())) throw loginRequired(label, 'https://www.linkedin.com/login');+ // ?shareActive opens the share box itself; when it doesn't, press "Start a post".+ const open = await page.locator(EDITOR).first().waitFor({ timeout: 8000 }).then(() => true, () => false);+ if (!open) {+ await step(label, 'start a post', async () => {+ await clickVisibleText(page, 'Start a post');+ await page.locator(EDITOR).first().waitFor({ timeout: T });+ });+ }+}++async function attachVideo(page, video) {+ await step(label, 'attach the video', async () => {+ const button = page.locator(`${DIALOG} button[aria-label="Add media"], ${DIALOG} button[aria-label="Add a video"]`).first();+ const [chooser] = await Promise.all([page.waitForEvent('filechooser', { timeout: T }), button.click({ timeout: T })]);+ await chooser.setFiles(video.path);+ });+ // The media editor opens over the composer with the clip; Next returns to the composer.+ await step(label, 'return to the post', async () => {+ await page.locator(`${DIALOG} video`).first().waitFor({ timeout: 120_000 }).catch(() => {});+ await page.waitForTimeout(1500);+ for (const name of ['Next', 'Done']) {+ if (await page.locator(EDITOR).first().isVisible().catch(() => false)) break;+ await clickVisibleText(page, name).catch(() => {});+ await page.waitForTimeout(1500);+ }+ await page.locator(EDITOR).first().waitFor({ timeout: T });+ });+}++export const linkedinAdapter = {+ label,+ async prepare(page, payload) {+ await openComposer(page);+ await attachVideo(page, payload.video);+ await step(label, 'write the post', async () => {+ await page.locator(EDITOR).first().click({ timeout: T });+ await pasteText(page, EDITOR, payload.text);+ });+ await step(label, 'wait for the upload', () => page.waitForFunction((dialog) => {+ const box = document.querySelector(dialog);+ const post = [...(box?.querySelectorAll('button') || [])].find((b) => (b.innerText || '').trim() === 'Post');+ const uploading = box?.querySelector('[role=progressbar], progress') || /Uploading|Processing/i.test(box?.innerText || '');+ return post && !post.disabled && post.getAttribute('aria-disabled') !== 'true' && !uploading;+ }, DIALOG, { timeout: 600_000 }));+ const length = await page.evaluate((sel) => document.querySelector(sel)?.innerText.trim().length ?? 0, EDITOR).catch(() => null);+ return {+ characters: length,+ firstComment: payload.firstComment ? 'Typed into the comment box once you press Post, then View post' : null,+ };+ },+ async findPost(page, payload) {+ const url = await landedOnPost(page, POST_URL, opening(payload.text), ([match]) => `${match}/`);+ if (url && payload.firstComment) {+ // Typed, never sent: the director presses Comment. A miss still records the post.+ await page.locator(COMMENT_EDITOR).first().click({ timeout: 10_000 })+ .then(() => pasteText(page, COMMENT_EDITOR, 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/linkedin.test.js b/server/services/musicVideo/publish/linkedin.test.jsnew file mode 100644index 0000000000..498542c939--- /dev/null+++ b/server/services/musicVideo/publish/linkedin.test.js@@ -0,0 +1,75 @@+/**+ * LinkedIn adapter: the share box gets the video and the post text 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 { linkedinAdapter } from './linkedin.js';++function fakePage({ url = 'https://www.linkedin.com/feed/?shareActive=true', shows = '' } = {}) {+ const log = [];+ const page = {+ log,+ goto: async (to) => { log.push(['goto', to]); },+ url: () => url,+ waitForTimeout: async () => {},+ waitForEvent: async () => ({ setFiles: async (path) => { log.push(['setFiles', path]); } }),+ waitForFunction: async (_fn, arg) => { if (typeof arg === 'string' && arg !== '[role=dialog]' && !shows.includes(arg)) throw new Error('timed out'); },+ locator: (sel) => {+ const el = {+ first: () => el,+ waitFor: async () => {},+ isVisible: async () => true,+ click: async () => { log.push(['click', sel]); },+ };+ return el;+ },+ // pasteText passes [selector, text]; clickVisibleText passes [selector, label]; the length read passes the selector.+ evaluate: async (_fn, arg) => {+ if (Array.isArray(arg)) { log.push(['paste', arg[0], arg[1]]); return true; }+ return 21;+ },+ };+ return page;+}++const payload = { video: { path: '/videos/x.mp4' }, text: 'I made a music video.\n\nMore.', firstComment: 'Full video: https://youtu.be/abc' };++describe('LinkedIn adapter', () => {+ it('uploads the video and pastes the post into the share box, pressing nothing', async () => {+ const page = fakePage();+ const summary = await linkedinAdapter.prepare(page, payload);+ expect(page.log[0]).toEqual(['goto', 'https://www.linkedin.com/feed/?shareActive=true']);+ expect(page.log).toContainEqual(['setFiles', '/videos/x.mp4']);+ expect(page.log).toContainEqual(['paste', '[role=dialog] .ql-editor[contenteditable=true]', payload.text]);+ expect(page.log.some(([kind, sel]) => kind === 'click' && /Post/.test(sel))).toBe(false);+ expect(summary).toMatchObject({ characters: 21, firstComment: expect.stringMatching(/View post/) });+ });++ it('asks for sign-in when LinkedIn redirects to its login wall', async () => {+ await expect(linkedinAdapter.prepare(fakePage({ url: 'https://www.linkedin.com/authwall?trk=x' }), payload)).rejects.toMatchObject({ code: 'PUBLISH_LOGIN_REQUIRED' });+ });++ it('records the opened post and types the first comment without sending it', async () => {+ const page = fakePage({ url: 'https://www.linkedin.com/feed/update/urn:li:activity:7123456789/?trk=x', shows: 'I made a music video.' });+ await expect(linkedinAdapter.findPost(page, payload)).resolves.toBe('https://www.linkedin.com/feed/update/urn:li:activity:7123456789/');+ expect(page.log.filter(([kind]) => kind === 'paste').map(([, , text]) => text)).toEqual([payload.firstComment]);+ expect(page.log.filter(([kind]) => kind === 'click').every(([, sel]) => /comment/.test(sel))).toBe(true);+ });++ it('ignores the feed and other posts', async () => {+ await expect(linkedinAdapter.findPost(fakePage({ url: 'https://www.linkedin.com/feed/' }), payload)).resolves.toBeNull();+ const other = fakePage({ url: 'https://www.linkedin.com/feed/update/urn:li:activity:1/', shows: 'Someone else' });+ await expect(linkedinAdapter.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.linkedin.com/feed/update/urn:li:activity:7/', shows: 'I made a music video.' });+ page.locator = () => ({ first() { return this; }, click: async () => { throw new Error('no comment box'); } });+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ await expect(linkedinAdapter.findPost(page, payload)).resolves.toBe('https://www.linkedin.com/feed/update/urn:li:activity:7/');+ expect(warn).toHaveBeenCalled();+ warn.mockRestore();+ });+});diff --git a/server/services/musicVideo/publish/payloads.js b/server/services/musicVideo/publish/payloads.jsindex 8d7b4a9869..6815813260 100644--- a/server/services/musicVideo/publish/payloads.js+++ b/server/services/musicVideo/publish/payloads.js@@ -12,6 +12,9 @@ import { suggestSocialCuts } from '../socialCuts.js';const TITLE_LIMITS = { youtube: 100, shorts: 100, reddit: 300, stackerNews: 80, substack: 100 };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;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' });@@ -155,6 +158,23 @@ const BUILDERS = {].filter(Boolean);return { posts };},+ // A native upload (LinkedIn shows those to more people than outside links);+ // the links go in the first comment, never in the post.+ linkedin: (project, kit, options = {}) => {+ 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 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 };+ },reddit: (project, kit, options = {}) => {// r/aivideo is the default (#9307): a native video post, title + flair, no// body. Showcase posts to tool-support subs (r/ClaudeAI, r/SunoAI) landed poorly.@@ -323,6 +343,11 @@ export function publishPreviewParts(platform, project, payload) {add(i === 0 ? `Post${media}` : `Reply ${i}${media}`, post.text);});break;+ case 'linkedin':+ add('Video', 'The 1080p encode of the final render');+ add('Post', p.text);+ add('First comment (you press Comment)', p.firstComment);+ break;case 'reddit':add('Where', `r/${p.subreddit}`);add('Type', { video: 'Video upload (the final render)', self: 'Text post', link: 'Link post' }[p.kind]);diff --git a/server/services/musicVideo/publish/payloads.test.js b/server/services/musicVideo/publish/payloads.test.jsindex bdc0250c3e..60ff23beab 100644--- a/server/services/musicVideo/publish/payloads.test.js+++ b/server/services/musicVideo/publish/payloads.test.js@@ -17,6 +17,7 @@ const kit = (over = {}) => ({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' },+ linkedin: { post: 'I made a music video.' },tiktok: { caption: 'tt caption' },instagram: { caption: 'made with @portos and @suno' },reddit: { title: '[Electropop] Song', body: 'Body' },@@ -46,6 +47,19 @@ describe('buildPublishPayload (#9282)', () => {expect(buildPublishPayload('youtube', fresh).video.name).toBe('master.mp4');});+ it('uploads the 1080p encode to LinkedIn with the links in the first comment, never in the post', () => {+ const p = buildPublishPayload('linkedin', project());+ 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',+ });+ 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();+ expect(() => buildPublishPayload('linkedin', project({ copy: {} }))).toThrow(/LinkedIn post/);+ expect(() => buildPublishPayload('linkedin', project({ copy: { linkedin: { post: 'x'.repeat(3001) } } }))).toThrow(/limit is 3000/);+ expect(() => buildPublishPayload('linkedin', { ...project(), audioAnalysis: { durationSec: 16 * 60 } })).toThrow(/up to 15 minutes/);+ });+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.jsindex b83eb10377..2a998e6bc4 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', 'tiktok', 'instagram', 'reddit', 'stackerNews', 'substack']);+export const PUBLISH_PLATFORMS = Object.freeze(['youtube', 'shorts', 'x', 'linkedin', '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, redditTitle: 300, stackerNewsTitle: 80, substackTitle: 100, substackSubtitle: 250, caption: 2200 };+const LIMITS = { youtubeTitle: 100, shortsTitle: 100, xHook: 280, linkedinPost: 3000, redditTitle: 300, stackerNewsTitle: 80, substackTitle: 100, substackSubtitle: 250, caption: 2200 };const str = (v, max) => (typeof v === 'string' && v.trim() ? v.trim().slice(0, max) : '');@@ -141,6 +141,7 @@ function copySpecs({ include, length }) {youtube: `"youtube":{"title":"<=100 chars","description":"${body('2 short paragraphs')} + the links given"${tags ? ',"tags":["8-15 lowercase tags"]' : ''}}`,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' : ''}"}`,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')}"}`,@@ -243,6 +244,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) }),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) }),