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 Substack as a music video publish destination

Claudecf5be1912f48
diff --git a/client/src/components/musicVideo/PublishKitPanel.jsx b/client/src/components/musicVideo/PublishKitPanel.jsx
index 082ccb656c..aa697ce812 100644
--- a/client/src/components/musicVideo/PublishKitPanel.jsx
+++ b/client/src/components/musicVideo/PublishKitPanel.jsx
@@ -25,6 +25,7 @@ export const PUBLISH_FIELDS = [
{ 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 }] },
{ platform: 'stackerNews', label: 'Stacker News', fields: [{ key: 'title', label: 'Title', max: 80 }, { key: 'body', label: 'Body (markdown)', multiline: true }] },
+ { platform: 'substack', label: 'Substack', fields: [{ key: 'title', label: 'Title', max: 100 }, { key: 'subtitle', label: 'Subtitle', max: 250 }, { key: 'body', label: 'Body (under the video)', multiline: true }] },
];
// What the writer may use beyond the notes and links; mirrors the server's
diff --git a/client/src/components/musicVideo/PublishPostingPanel.jsx b/client/src/components/musicVideo/PublishPostingPanel.jsx
index e53273fa3e..3f212eb8bf 100644
--- a/client/src/components/musicVideo/PublishPostingPanel.jsx
+++ b/client/src/components/musicVideo/PublishPostingPanel.jsx
@@ -17,6 +17,10 @@ export const PUBLISH_TARGETS = [
{ target: 'instagram', label: 'Instagram Reels', note: 'A 9:16 cut (the newest by default), with the AI label' },
{ target: 'reddit', label: 'Reddit', note: 'A native video post to r/aivideo (title and flair, no body)' },
{ target: 'stackerNews', label: 'Stacker News', note: 'A link post to the full video' },
+ {
+ target: 'substack', label: 'Substack', accountPlaceholder: 'name.substack.com',
+ note: 'A post with the full video at the top, then your title, subtitle and body. Substack keeps it in Drafts; you choose who gets it and press Publish',
+ },
{
// `accountPlaceholder` marks an account that is a name, not an @handle.
target: 'distrokid', label: 'Spotify (via DistroKid)', accountPlaceholder: 'Artist name',
@@ -108,6 +112,9 @@ function TargetOptions({ target, kit, project, options, setOption, flairs, idFor
if (target === 'stackerNews') {
return <div className="grid sm:grid-cols-2 gap-2">{text('territory', 'Territory', 'art')}<div className="sm:col-span-2">{area('firstComment', 'First comment (optional)')}</div></div>;
}
+ if (target === 'substack') {
+ return text('publication', 'Publication', account || 'name.substack.com');
+ }
if (target === 'suno') {
// Prefill from kit links or run output if available
const defaultSongUrl = kit.links?.song || (options.songUrl ? null : 'https://suno.com/song/…');
diff --git a/client/src/components/musicVideo/PublishPostingPanel.test.jsx b/client/src/components/musicVideo/PublishPostingPanel.test.jsx
index 4946635763..11ae72502b 100644
--- a/client/src/components/musicVideo/PublishPostingPanel.test.jsx
+++ b/client/src/components/musicVideo/PublishPostingPanel.test.jsx
@@ -7,7 +7,7 @@ import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent, within, act } from '@testing-library/react';
import PublishPostingPanel, { PUBLISH_TARGETS } from './PublishPostingPanel.jsx';
-const ALL = ['youtube', 'suno', 'sunoHook', 'x', 'shorts', 'tiktok', 'instagram', 'reddit', 'stackerNews', 'distrokid'];
+const ALL = ['youtube', 'suno', 'sunoHook', 'x', '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.getByText(label, { selector: 'div' }).closest('li');
@@ -35,6 +35,18 @@ describe('PublishPostingPanel (#9282)', () => {
expect(publishing.prepare).toHaveBeenCalledWith('reddit', { subreddit: 'SunoAI', kind: 'link' });
});
+ it('fills a Substack draft on the publication typed, else the one under Where you post', () => {
+ const publishing = hook({ platforms: { substack: { enabled: true, account: 'example' } } });
+ render(<PublishPostingPanel project={project()} publishing={publishing} />);
+ const substack = row('Substack');
+ expect(within(substack).getByLabelText('Publication')).toHaveAttribute('placeholder', 'example');
+ fireEvent.click(within(substack).getByRole('button', { name: 'Fill draft' }));
+ expect(publishing.prepare).toHaveBeenCalledWith('substack', {});
+ fireEvent.change(within(substack).getByLabelText('Publication'), { target: { value: 'other' } });
+ fireEvent.click(within(substack).getByRole('button', { name: 'Fill draft' }));
+ expect(publishing.prepare).toHaveBeenLastCalledWith('substack', { publication: 'other' });
+ });
+
it('lets the director pick which 9:16 cut a Shorts draft posts (#10150)', () => {
const publishing = hook();
const p = { ...project({ master: { renderHistoryId: 'r1' }, exports: [{ kind: 'vertical-9x16', filename: 'v.mp4', startSec: 10, endSec: 40 }] }),
diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.md
index f3c85cfb3e..8d4c2832f7 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 every word with local whisper.cpp (large-v3-turbo, downloaded on first use), builds a Cast & Sets check-in (one creative-direction call that interprets the song, then a canonical character sheet, expression and looks sheets, one empty plate per set and in-set tests on the image queue, each later image conditioned on the character sheet; assembled into a self-contained sheet saved as a development artifact), stops for the director's review unless the brief auto-approves it, then plans against the approved references. Development artifacts (check-in sheets, animatics, treatments, storyboards; HTML/Markdown/MP4/PNG/JPG) are versioned per project, reviewed with notes and approve/request-changes, and viewed in a sandboxed viewer at `/music-video/:projectId/:stage/dev/:artifactId` (the stage-less `/music-video/:projectId/dev/:artifactId` still opens it). Draft excerpts are reviewed and selectively revised by hand, or by an opt-in auto-review run bounded by director-set review and paid-generation limits (a frame-only look never passes motion or audio sync). A 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) 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 every word with local whisper.cpp (large-v3-turbo, downloaded on first use), builds a Cast & Sets check-in (one creative-direction call that interprets the song, then a canonical character sheet, expression and looks sheets, one empty plate per set and in-set tests on the image queue, each later image conditioned on the character sheet; assembled into a self-contained sheet saved as a development artifact), stops for the director's review unless the brief auto-approves it, then plans against the approved references. Development artifacts (check-in sheets, animatics, treatments, storyboards; HTML/Markdown/MP4/PNG/JPG) are versioned per project, reviewed with notes and approve/request-changes, and viewed in a sandboxed viewer at `/music-video/:projectId/:stage/dev/:artifactId` (the stage-less `/music-video/:projectId/dev/:artifactId` still opens it). Draft excerpts are reviewed and selectively revised by hand, or by an opt-in auto-review run bounded by director-set review and paid-generation limits (a frame-only look never passes motion or audio sync). A 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. | — |
| **Sharing & Conflict Resolution** | `/sharing`, `/sharing/duplicates`, `/sharing/conflicts` | Collaborative asset exchange via cloud storage buckets (Google Drive, Dropbox, iCloud, Syncthing) with duplicate reconciliation and conflict recovery journals. | — |
---
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index 4652c31e0c..9d5b64d27f 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -677,6 +677,7 @@ export const musicVideoPublishCopyPatchSchema = z.object({
instagram: z.object({ caption: kitText(2200) }).partial().strict().optional(),
reddit: z.object({ title: kitText(300), body: kitText(40000) }).partial().strict().optional(),
stackerNews: z.object({ title: kitText(80), body: kitText(40000) }).partial().strict().optional(),
+ substack: z.object({ title: kitText(100), subtitle: kitText(250), body: kitText(40000) }).partial().strict().optional(),
notes: kitText(8000).optional(),
}).strict();
export const musicVideoPublishCopyDraftSchema = z.object({
@@ -744,7 +745,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', 'suno', 'sunoHook', 'distrokid']);
+export const MUSIC_VIDEO_PUBLISH_TARGETS = Object.freeze(['youtube', 'shorts', 'tiktok', 'instagram', 'x', '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,
@@ -764,6 +765,8 @@ export const musicVideoPublishPrepareSchema = z.object({
flairText: z.string().max(64),
firstComment: kitText(10000),
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),
songUrl: publishUrl,
pin: z.boolean(),
// Suno Hook: keep the page's lyric overlay (default off: the cut carries its own).
diff --git a/server/services/musicVideo/publish/index.js b/server/services/musicVideo/publish/index.js
index 1585682aa0..f8d4dab7d3 100644
--- a/server/services/musicVideo/publish/index.js
+++ b/server/services/musicVideo/publish/index.js
@@ -21,6 +21,7 @@ import { instagramAdapter } from './instagram.js';
import { xAdapter } from './x.js';
import { redditAdapter } from './reddit.js';
import { stackerNewsAdapter } from './stackerNews.js';
+import { substackAdapter } from './substack.js';
import { sunoAdapter } from './suno.js';
import { sunoHookAdapter } from './sunoHook.js';
import { distrokidAdapter } from './distrokid.js';
@@ -28,7 +29,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, suno: sunoAdapter, sunoHook: sunoHookAdapter, distrokid: distrokidAdapter,
+ x: xAdapter, 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.
@@ -125,10 +126,12 @@ async function withCovers(target, payload, deps) {
return result.ok ? { ...payload, cover: { dir: 'videoThumbnails', name: out.split(/[\\/]/).pop(), path: out } } : uncut();
}
-/** DistroKid's options default the artist to the account named under Where you post. */
+/** Options named once under Where you post: DistroKid's artist, Substack's publication. */
+const ACCOUNT_OPTION = { distrokid: 'artistName', substack: 'publication' };
function withPlatformDefaults(target, options, platforms) {
- if (target !== 'distrokid' || options?.artistName) return options;
- return { ...options, artistName: platforms?.distrokid?.account || '' };
+ const key = ACCOUNT_OPTION[target];
+ if (!key || options?.[key]) return options;
+ return { ...options, [key]: platforms?.[target]?.account || '' };
}
/** The release audio a distributor uploads: the project's own source song. */
diff --git a/server/services/musicVideo/publish/index.test.js b/server/services/musicVideo/publish/index.test.js
index ee2c581912..b02610c831 100644
--- a/server/services/musicVideo/publish/index.test.js
+++ b/server/services/musicVideo/publish/index.test.js
@@ -65,6 +65,19 @@ async function readyProject() {
}
describe('publish drafts (#9282)', () => {
+ it('fills a Substack post on the publication named under Where you post', async () => {
+ const { id } = await projects.createProject({ name: 'Release' });
+ await projects.mutateProjectRecord(id, (current) => ({ project: { ...current, publishKit: {
+ links: { youtube: 'https://youtu.be/abc' }, copy: { substack: { title: 'Song', subtitle: 'Sub', body: 'b' } },
+ } } }));
+ const { connect } = fakeBrowser();
+ const substack = adapter({ label: 'Substack' });
+ await preparePublishDraft(id, 'substack', {}, { connect, adapters: { substack }, platforms: { substack: { enabled: true, account: 'example' } } });
+ expect(substack.prepare).toHaveBeenCalledWith(expect.anything(), { publication: 'example.substack.com', videoUrl: 'https://youtu.be/abc', title: 'Song', subtitle: 'Sub', body: 'b' });
+ await expect(preparePublishDraft(id, 'substack', { again: true }, { connect, adapters: { substack }, platforms: { substack: { enabled: true, account: null } } }))
+ .rejects.toMatchObject({ status: 422, message: expect.stringMatching(/publication/) });
+ });
+
it('fills a reviewable draft but never submits it; records a manually published link', async () => {
const id = await readyProject();
const { connect, pages } = fakeBrowser();
diff --git a/server/services/musicVideo/publish/payloads.js b/server/services/musicVideo/publish/payloads.js
index bbf1d4b584..f43a84ee8f 100644
--- a/server/services/musicVideo/publish/payloads.js
+++ b/server/services/musicVideo/publish/payloads.js
@@ -10,7 +10,7 @@ import { musicVideoDependencyChanges } from '../../../lib/musicVideoDependencies
import { suggestDistrokidGenres } from '../../../lib/distrokidGenres.js';
import { suggestSocialCuts } from '../socialCuts.js';
-const TITLE_LIMITS = { youtube: 100, shorts: 100, reddit: 300, stackerNews: 80 };
+const TITLE_LIMITS = { youtube: 100, shorts: 100, reddit: 300, stackerNews: 80, substack: 100 };
const DEFAULT_SUBREDDIT = 'aivideo';
const missing = (message) => new ServerError(message, { status: 422, code: 'PUBLISH_ASSET_MISSING' });
@@ -81,6 +81,16 @@ function youtubeDescription(kit) {
// A typed "@" on Instagram opens the mention picker, which swallows the next word.
const instagramSafe = (caption) => caption.replace(/@(\w)/g, '$1');
+/**
+ * The publication's host from what the director typed: a bare name means
+ * name.substack.com; a custom domain or a pasted URL keeps only its host.
+ */
+export function substackPublication(value) {
+ const host = text(value).toLowerCase().replace(/^https?:\/\//, '').replace(/^@/, '').split(/[/?#]/)[0];
+ if (/^[a-z0-9-]{1,63}$/.test(host)) return `${host}.substack.com`;
+ return /^(?:[a-z0-9-]{1,63}\.)+[a-z]{2,}$/.test(host) ? host : null;
+}
+
// The release cover: the composed cover art when there is one (already square,
// with the title set), else the kit's thumbnail (cut square at post time).
const releaseCover = (kit) => {
@@ -167,6 +177,17 @@ const BUILDERS = {
if (!/^[A-Za-z0-9_]{1,32}$/.test(territory)) throw missing('Name the Stacker News territory');
return { territory, title: requireTitle('stackerNews', text(kit.copy?.stackerNews?.title)), url, body: text(kit.copy?.stackerNews?.body), firstComment: text(options.firstComment) || null };
},
+ substack: (project, kit, options = {}) => {
+ const publication = substackPublication(options.publication);
+ if (!publication) throw missing('Name your Substack publication (name.substack.com) under Where you post');
+ const videoUrl = fullVideoUrl(kit);
+ if (!videoUrl) throw missing('Substack posts embed the full video: publish to YouTube first, or add its URL to the kit');
+ return {
+ publication, videoUrl,
+ title: requireTitle('substack', text(kit.copy?.substack?.title)),
+ subtitle: text(kit.copy?.substack?.subtitle), body: text(kit.copy?.substack?.body),
+ };
+ },
suno: (project, kit, options = {}) => {
const song = songUrl(kit, options);
// The adapter finds the song's own menu by its id, so the URL must carry it.
diff --git a/server/services/musicVideo/publish/payloads.test.js b/server/services/musicVideo/publish/payloads.test.js
index d98a6ce257..52873c7732 100644
--- a/server/services/musicVideo/publish/payloads.test.js
+++ b/server/services/musicVideo/publish/payloads.test.js
@@ -3,7 +3,7 @@
* director's per-platform options, or a 422 naming the missing piece.
*/
import { describe, expect, it } from 'vitest';
-import { buildPublishPayload } from './payloads.js';
+import { buildPublishPayload, substackPublication } from './payloads.js';
import { captureMusicVideoEvidence } from '../../../lib/musicVideoDependencies.js';
const kit = (over = {}) => ({
@@ -102,6 +102,18 @@ describe('buildPublishPayload (#9282)', () => {
expect(p).toMatchObject({ url: 'https://www.youtube.com/watch?v=posted', territory: 'art', title: 'Song' });
});
+ it('reads the Substack publication from a name, a pasted URL or a custom domain', () => {
+ expect(substackPublication('example')).toBe('example.substack.com');
+ expect(substackPublication('https://Example.substack.com/p/old-post')).toBe('example.substack.com');
+ expect(substackPublication('news.example.com')).toBe('news.example.com');
+ expect(substackPublication('not a host')).toBeNull();
+ const copy = { substack: { title: 'Song', subtitle: '', body: 'Body' } };
+ expect(buildPublishPayload('substack', project({ copy }), { publication: 'example' }))
+ .toEqual({ publication: 'example.substack.com', videoUrl: 'https://youtu.be/abc', title: 'Song', subtitle: '', body: 'Body' });
+ expect(() => buildPublishPayload('substack', project({ copy, links: {} }), { publication: 'example' })).toThrow(/publish to YouTube first/);
+ expect(() => buildPublishPayload('substack', project(), { publication: 'example' })).toThrow(/substack title/);
+ });
+
it('posts a native video to r/aivideo by default, and validates other subreddits\' rules', () => {
const named = (over = {}) => ({ ...project({ copy: { reddit: { title: 'Song Name — a music video', body: 'Body' } }, ...over }), name: 'Song Name' });
expect(buildPublishPayload('reddit', named(), {})).toMatchObject({ subreddit: 'aivideo', kind: 'video', video: { dir: 'videos', name: 'master.mp4' }, body: '' });
diff --git a/server/services/musicVideo/publish/substack.js b/server/services/musicVideo/publish/substack.js
new file mode 100644
index 0000000000..7e35f7918d
--- /dev/null
+++ b/server/services/musicVideo/publish/substack.js
@@ -0,0 +1,51 @@
+/**
+ * Substack adapter: a newsletter post on the director's publication with the
+ * full video embedded at the top, then the title, subtitle and body. Substack
+ * turns a YouTube link pasted on its own line into a video embed; when it does
+ * not, the link stays in the post as plain text, and the summary says which.
+ *
+ * Substack saves a post as a draft in the publication the moment it is typed
+ * into, so a filled draft also appears under the publication's Drafts. PortOS
+ * never presses Continue or Publish: sending to subscribers stays with the director.
+ */
+import { PUBLISH_STEP_TIMEOUT_MS as T, loginRequired, pasteText, step } from './browser.js';
+
+const label = 'Substack';
+const TITLE = '[data-testid="post-title"], textarea#post-title, textarea.post-title, textarea[placeholder="Title"]';
+const SUBTITLE = '[data-testid="post-subtitle"], textarea#post-subtitle, textarea.subtitle, textarea[placeholder^="Add a subtitle"]';
+const BODY = '.ProseMirror[contenteditable="true"]';
+
+export const substackAdapter = {
+ label,
+ async prepare(page, payload) {
+ const editorUrl = `https://${payload.publication}/publish/post?type=newsletter`;
+ await step(label, 'open a new post', () => page.goto(editorUrl, { waitUntil: 'domcontentloaded', timeout: T }));
+ await page.waitForTimeout(4000);
+ if (/\/sign-?in|\/account\/login/.test(page.url())) throw loginRequired(label, editorUrl);
+ await step(label, 'write the title', async () => {
+ await page.locator(TITLE).first().waitFor({ timeout: T });
+ await page.locator(TITLE).first().fill(payload.title);
+ });
+ if (payload.subtitle) {
+ await step(label, 'write the subtitle', () => page.locator(SUBTITLE).first().fill(payload.subtitle, { timeout: T }));
+ }
+ await step(label, 'embed the video', async () => {
+ await page.locator(BODY).first().click({ timeout: T });
+ await pasteText(page, BODY, payload.videoUrl);
+ await page.waitForTimeout(3000);
+ });
+ if (payload.body) {
+ await step(label, 'write the body', async () => {
+ await page.locator(BODY).first().click();
+ await page.keyboard.press('ControlOrMeta+End');
+ await page.keyboard.press('Enter');
+ await pasteText(page, BODY, payload.body);
+ });
+ }
+ const embedded = await page.evaluate((sel) => !!document.querySelector(sel)?.querySelector('iframe[src*="youtube"], [class*="youtube"]'), BODY).catch(() => false);
+ return {
+ publication: payload.publication, title: payload.title, subtitle: payload.subtitle || null,
+ video: embedded ? `Embedded: ${payload.videoUrl}` : `Link (not embedded): ${payload.videoUrl}`,
+ };
+ },
+};
diff --git a/server/services/musicVideo/publishKitText.js b/server/services/musicVideo/publishKitText.js
index 4946fb2518..b83eb10377 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']);
+export const PUBLISH_PLATFORMS = Object.freeze(['youtube', 'shorts', 'x', '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, caption: 2200 };
+const LIMITS = { youtubeTitle: 100, shortsTitle: 100, xHook: 280, redditTitle: 300, stackerNewsTitle: 80, substackTitle: 100, substackSubtitle: 250, caption: 2200 };
const str = (v, max) => (typeof v === 'string' && v.trim() ? v.trim().slice(0, max) : '');
@@ -145,6 +145,7 @@ function copySpecs({ include, length }) {
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')}"}`,
stackerNews: `"stackerNews":{"title":"<=80 chars","body":"${body('markdown, personal tone')}"}`,
+ substack: `"substack":{"title":"<=100 chars","subtitle":"one line","body":"${body('3-5 short paragraphs of plain text, no markdown')}"}`,
};
}
@@ -246,6 +247,7 @@ export function parsePublishCopy(text, platforms = PUBLISH_PLATFORMS, { hashtags
instagram: () => ({ caption: str(v('instagram').caption, LIMITS.caption) }),
reddit: () => ({ title: str(v('reddit').title, LIMITS.redditTitle), body: str(v('reddit').body, 40000) }),
stackerNews: () => ({ title: str(v('stackerNews').title, LIMITS.stackerNewsTitle), body: str(v('stackerNews').body, 40000) }),
+ substack: () => ({ title: str(v('substack').title, LIMITS.substackTitle), subtitle: str(v('substack').subtitle, LIMITS.substackSubtitle), body: str(v('substack').body, 40000) }),
};
const copy = Object.fromEntries(PUBLISH_PLATFORMS.filter((p) => platforms.includes(p)).map((p) => [p, all[p]()]));
const filled = Object.values(copy).some((fields) => Object.values(fields).some((f) => (Array.isArray(f) ? f.length : f)));