Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(publish): cross-links between a release's posts
Claude714a358416e8
diff --git a/client/src/components/musicVideo/PublishCrossLinksPanel.jsx b/client/src/components/musicVideo/PublishCrossLinksPanel.jsxnew file mode 100644index 0000000000..f281be7839--- /dev/null+++ b/client/src/components/musicVideo/PublishCrossLinksPanel.jsx@@ -0,0 +1,93 @@+import { useState } from 'react';+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 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. */+function BackfillRow({ row, publishing }) {+ const [busy, setBusy] = useState(null);+ const [filled, setFilled] = useState(null);+ const [error, setError] = useState(null);+ const label = LABELS[row.target];+ const fill = () => {+ setBusy('fill');+ setError(null);+ publishing.prepareCrossLinks(row.target)+ .then((res) => setFilled(res))+ .catch((err) => setError({ message: err?.message || 'Failed', login: err?.code === 'PUBLISH_LOGIN_REQUIRED' }))+ .finally(() => setBusy(null));+ };+ // Saved records the links this edit added (the ones listed when it was filled).+ const saved = () => {+ setBusy('saved');+ publishing.recordPost(row.target, { links: filled?.links || row.missing.map((l) => l.target) })+ .then((post) => { if (post) setFilled(null); })+ .finally(() => setBusy(null));+ };+ const done = !row.missing.length;+ return (+ <li className="rounded border border-port-border p-2 space-y-1.5 min-w-0">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="min-w-0 flex-1">+ <div className="font-medium">{label}</div>+ <div className="text-[11px] text-port-text-muted break-words">+ {done ? 'Links every other post' : `Add ${row.missing.map((l) => l.label).join(', ')}`}+ </div>+ </div>+ {!done && (+ <div className="flex flex-wrap gap-1.5">+ <button type="button" onClick={fill} disabled={!!busy} className={`${btn} bg-port-accent/20 text-port-accent border-transparent`}>+ {busy === 'fill' ? 'Filling…' : (filled ? 'Fill again' : ACTION[row.target])}+ </button>+ <button type="button" onClick={saved} disabled={!!busy} aria-label={`Mark the ${label} links saved`} className={btn}>+ <Check size={12} /> {busy === 'saved' ? 'Saving…' : 'Saved'}+ </button>+ </div>+ )}+ </div>+ {!done && <pre className="whitespace-pre-wrap break-all text-[11px] bg-port-bg rounded p-1.5">{row.text}</pre>}+ {error && <div role="alert" className="text-[11px] text-port-error flex items-center gap-1">{error.login && <LogIn size={11} />}{error.message}</div>}+ {filled && (+ <div className="space-y-1">+ {filled.screenshot && <img src={filled.screenshot} alt={`${label} with the links filled in`} className="w-full rounded border border-port-border" />}+ {filled.summary?.leftForYou?.length > 0 && (+ <p className="text-[11px] text-port-text-muted whitespace-pre-wrap">Left for you in the PortOS Browser: {filled.summary.leftForYou.join(' · ')}. Then press Saved here.</p>+ )}+ </div>+ )}+ </li>+ );+}++/**+ * Cross-links between the release's posts: new drafts list the posts already+ * made (a switch), and a post that went up before the others can take their+ * links afterwards. Fill opens its edit form, or a reply/comment under it, in+ * the PortOS Browser with the links added; the director saves it there and+ * presses Saved here. PortOS never saves, posts or deletes on a platform.+ */+export default function PublishCrossLinksPanel({ project, publishing }) {+ const kit = project?.publishKit || {};+ if (!kit.builtAt || !publishing?.prepareCrossLinks) return null;+ const rows = crossLinkBackfill(kit);+ const enabled = crossLinksEnabled(kit);+ const pending = rows.filter((r) => r.missing.length).length;+ return (+ <PublishCard projectId={project.id} cardId="cross-links" label="Cross-links" icon={Link2}+ summary={pending ? `${pending} post${pending === 1 ? '' : 's'} missing links` : ''} defaultOpen={pending > 0}>+ <label htmlFor={`mv-cross-links-${project.id}`} className="flex items-center gap-1.5 min-h-[44px] sm:min-h-0">+ <input id={`mv-cross-links-${project.id}`} type="checkbox" checked={enabled} onChange={(e) => publishing.setCrossLinks(e.target.checked)} />+ New drafts link the posts already made (YouTube, Suno, X, Stacker News, Substack)+ </label>+ {rows.length ? (+ <ul className="space-y-2">{rows.map((row) => <BackfillRow key={row.target} row={row} publishing={publishing} />)}</ul>+ ) : (+ <p className="text-port-text-muted">Once YouTube, Suno, X or Stacker News is posted, this lists the links each one still lacks.</p>+ )}+ </PublishCard>+ );+}diff --git a/client/src/components/musicVideo/PublishCrossLinksPanel.test.jsx b/client/src/components/musicVideo/PublishCrossLinksPanel.test.jsxnew file mode 100644index 0000000000..10f6771edb--- /dev/null+++ b/client/src/components/musicVideo/PublishCrossLinksPanel.test.jsx@@ -0,0 +1,40 @@+/**+ * Cross-links card: lists the links each post already up still lacks, fills+ * its edit in the PortOS Browser on request, and counts the links only when+ * the director says they saved it.+ */+import { describe, it, expect, vi } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import PublishCrossLinksPanel from './PublishCrossLinksPanel.jsx';++const project = (kit = {}) => ({ id: 'mv-1', publishKit: { builtAt: '2026-01-01T00:00:00.000Z', ...kit } });+const posts = {+ x: { url: 'https://x.com/example/status/1', postedAt: '2026-01-01T00:00:00Z', links: [] },+ youtube: { url: 'https://youtu.be/abc', postedAt: '2026-01-01T01:00:00Z', links: ['x'] },+};+const hook = (over = {}) => ({ prepareCrossLinks: vi.fn(), recordPost: vi.fn(async () => ({})), setCrossLinks: vi.fn(async () => true), ...over });++describe('PublishCrossLinksPanel', () => {+ it('fills the X reply with the video link, then records it as linked on Saved', async () => {+ const publishing = hook({ prepareCrossLinks: vi.fn(async () => ({ target: 'x', links: ['youtube'], screenshot: 'data:image/jpeg;base64,AA', summary: { leftForYou: ['Reply'] } })) });+ render(<PublishCrossLinksPanel project={project({ posts })} publishing={publishing} />);+ expect(screen.getByText('Links every other post')).toBeInTheDocument(); // YouTube already links X+ expect(screen.getByText('Music video: https://youtu.be/abc')).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Fill reply' }));+ expect(await screen.findByAltText('X reply with the links filled in')).toBeInTheDocument();+ expect(publishing.prepareCrossLinks).toHaveBeenCalledWith('x');+ expect(publishing.recordPost).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Mark the X reply links saved' }));+ expect(publishing.recordPost).toHaveBeenCalledWith('x', { links: ['youtube'] });+ await waitFor(() => expect(screen.queryByAltText('X reply with the links filled in')).not.toBeInTheDocument());+ });++ it('keeps a sign-in refusal beside its row and toggles links in new drafts', async () => {+ const publishing = hook({ prepareCrossLinks: vi.fn(async () => { throw Object.assign(new Error('Sign in to X in the PortOS Browser'), { code: 'PUBLISH_LOGIN_REQUIRED' }); }) });+ render(<PublishCrossLinksPanel project={project({ posts })} publishing={publishing} />);+ fireEvent.click(screen.getByRole('button', { name: 'Fill reply' }));+ expect(await screen.findByRole('alert')).toHaveTextContent('Sign in to X');+ fireEvent.click(screen.getByLabelText(/New drafts link the posts already made/));+ expect(publishing.setCrossLinks).toHaveBeenCalledWith(false);+ });+});diff --git a/client/src/components/musicVideo/stages/PublishStage.jsx b/client/src/components/musicVideo/stages/PublishStage.jsxindex 026d8df159..85fde22ad9 100644--- a/client/src/components/musicVideo/stages/PublishStage.jsx+++ b/client/src/components/musicVideo/stages/PublishStage.jsx@@ -1,14 +1,15 @@import PublishKitPanel from '../PublishKitPanel.jsx';import PublishPostingPanel from '../PublishPostingPanel.jsx';import PublishPlatformsPanel from '../PublishPlatformsPanel.jsx';+import PublishCrossLinksPanel from '../PublishCrossLinksPanel.jsx';import PromotionPlanPanel from '../PromotionPlanPanel.jsx';/*** Publish: the release kit made from the final render (encodes, thumbnails,* captions, chapters), the per-platform copy (#9281), and posting it through* the PortOS Browser with a review before every post (#9282), only to the- * platforms the director turned on (#9287), then a promotion plan of dated- * steps for the director with reminders.+ * platforms the director turned on (#9287), cross-links between those posts,+ * then a promotion plan of dated steps for the director with reminders.*/export default function PublishStage({ board }) {const { project, locked, publishKit, publishing, excerpts } = board;@@ -17,6 +18,7 @@ export default function PublishStage({ board }) {{publishing && <PublishPlatformsPanel projectId={project?.id} publishing={publishing} />}<PublishKitPanel project={project} publishKit={publishKit} enabledTargets={publishing?.enabledTargets} />{publishing && <PublishPostingPanel project={project} publishing={publishing} excerpts={excerpts} />}+ {publishing && <PublishCrossLinksPanel project={project} publishing={publishing} />}<PromotionPlanPanel project={project} /></fieldset>);diff --git a/client/src/hooks/useMusicVideoPublishing.js b/client/src/hooks/useMusicVideoPublishing.jsindex cb5dad10bf..6275029b3a 100644--- a/client/src/hooks/useMusicVideoPublishing.js+++ b/client/src/hooks/useMusicVideoPublishing.js@@ -9,6 +9,8 @@ import {updateMusicVideoPublishPlatforms,recordMusicVideoPublishPost,removeMusicVideoPublishPost,+ setMusicVideoPublishCrossLinks,+ prepareMusicVideoCrossLinkEdit,} from '../services/apiMusicVideo.js';const EMPTY_POSTING = { drafts: {}, busy: {}, errors: {} };@@ -136,7 +138,14 @@ export default function useMusicVideoPublishing({ project, replaceProject } = {}.then((res) => { if (res?.project) replaceProject?.(res.project); loadPlatforms(); return true; }).catch(() => false);+ // Cross-links: whether new drafts list the release's other posts.+ const setCrossLinks = (enabled) => setMusicVideoPublishCrossLinks(projectId, enabled)+ .then((res) => { if (res?.project) replaceProject?.(res.project); return true; })+ .catch(() => false);+ // Fill a posted platform's edit (or a reply under it) with the links it lacks; errors stay with the caller.+ const prepareCrossLinks = (target) => prepareMusicVideoCrossLinkEdit(projectId, target, { silent: true });+const enabledTargets = Object.entries(platforms || {}).filter(([, p]) => p?.enabled).map(([t]) => t);- return { drafts, busy, errors, prepare, preview, discard, platforms, history, enabledTargets, setPlatform, recordPost, removePost };+ return { drafts, busy, errors, prepare, preview, discard, platforms, history, enabledTargets, setPlatform, recordPost, removePost, setCrossLinks, prepareCrossLinks };}diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 2659070bdb..3265154397 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -312,6 +312,13 @@ export const recordMusicVideoPublishPost = (id, target, body, options = {}) =>// Undo a platform's "done" (PortOS's record only) → { project }.export const removeMusicVideoPublishPost = (id, target, options = {}) =>request(`/music-video/${encodeURIComponent(id)}/publish/posts/${encodeURIComponent(target)}`, { method: 'DELETE', ...options });+// Cross-links between the release's posts: whether new drafts list the others+// → { project }, and filling a posted platform's edit with the links it lacks+// → { target, links, summary, screenshot } (the director saves it there).+export const setMusicVideoPublishCrossLinks = (id, enabled, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/publish/cross-links`, { method: 'PUT', body: JSON.stringify({ enabled }), ...options });+export const prepareMusicVideoCrossLinkEdit = (id, target, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/publish/${encodeURIComponent(target)}/cross-links`, { method: 'POST', body: '{}', ...options });export const musicVideoExcerptRenderEventsUrl = (jobId) =>`/api/music-video/excerpt/${encodeURIComponent(jobId)}/events`;export const cancelMusicVideoExcerptRender = (jobId, options = {}) =>diff --git a/server/lib/README.md b/server/lib/README.mdindex 048c403a8b..f8d09ea38b 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -854,6 +854,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `sheetPointers.js` | Browser-safe persisted character-sheet layout: `LEGACY_SHEET_VARIANT_ID`, `readSheetPointer`, `listSheetPointers`, identity-preserving `applySheetPointerToCharacter`, and default-variant browser adapter `applySheetPointer`. || `musicVideoGrade.js` | Opt-in Music Video grade presets, bounded normalization, and shared song-timed RGB curves with deterministic grain for composed and document encodes. || `musicVideoDependencies.js` | Versioned take/evidence provenance, dependency comparisons and bounded selective-repair previews. |+| `musicVideoCrossLinks.js` | Cross-links between a release's posts: each post's public link, the `Label: url` lines a new draft adds, which links a posted record carries (`links`, or what its draft always linked), and `crossLinkBackfill(kit)` listing the links each editable post (YouTube, Suno, X, Stacker News) still lacks. Shared by the publish payloads and the Publish stage. || `musicVideoExcerptRange.js` | `excerptRangeFits(startSec, endSec, totalSec, fps)`: whether a code/document excerpt window fits a frame-quantized render, allowing the end up to one frame past it (scene ends follow the analysed song length; the caller clamps). The start must fall inside the render; an unknown fps allows no slack. || `musicVideoPlateEvidence.js` | Asset-bound authored-shot plate requirements, current evidence and selected-image admission. |diff --git a/server/lib/index.js b/server/lib/index.jsindex a8fb4ecf78..d366bc35de 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -832,6 +832,7 @@ export * from './imageLimits.js';export * from './musicVideoActionContract.js';export * from './musicVideoGrade.js';export * from './musicVideoDependencies.js';+export * from './musicVideoCrossLinks.js';export * from './musicVideoExcerptRange.js';export * from './musicVideoPlateEvidence.js';diff --git a/server/lib/musicVideoCrossLinks.js b/server/lib/musicVideoCrossLinks.jsnew file mode 100644index 0000000000..bcd499482b--- /dev/null+++ b/server/lib/musicVideoCrossLinks.js@@ -0,0 +1,88 @@+/**+ * Cross-links between a music video's release posts. Pure, shared by the+ * publish payloads (a new draft lists the posts already made) and the+ * Publish stage's "Backfill cross-links" card (which posts already up are+ * missing links to the ones made after them).+ *+ * A post record may carry `links`: the targets whose links it already shows.+ * Posts recorded before that field existed are read with what their draft+ * always linked (`LEGACY_LINKS`), counted only when that link existed first.+ */++/** 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',+ 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']);++// What each draft linked before posts recorded their links.+const LEGACY_LINKS = { youtube: [], suno: ['youtube'], x: ['suno', 'youtube'], stackerNews: ['youtube'] };++const str = (v) => (typeof v === 'string' ? v.trim() : '');+const kitOf = (kit) => (kit && typeof kit === 'object' ? kit : {});++/** The public link for `target`: its recorded post, else (song, full video) the link given the kit. */+export function releaseLinkUrl(kit, target, { songUrl } = {}) {+ const k = kitOf(kit);+ if (target === 'suno') return str(songUrl) || str(k.posts?.suno?.url) || str(k.links?.song);+ if (target === 'youtube') return str(k.posts?.youtube?.url) || str(k.links?.youtube);+ return str(k.posts?.[target]?.url);+}++/** Whether new drafts list the release's other posts (on unless the director turned it off). */+export const crossLinksEnabled = (kit) => kitOf(kit).crossLinks !== false;++/** `[{ target, label, url }]` for every linkable post except `exclude`. */+export function releaseLinks(kit, { exclude = [], songUrl } = {}) {+ return Object.keys(CROSS_LINK_LABELS)+ .filter((target) => !exclude.includes(target))+ .map((target) => ({ target, label: CROSS_LINK_LABELS[target], url: releaseLinkUrl(kit, target, { songUrl }) }))+ .filter((link) => link.url);+}++/**+ * Split `links` into the ones `text` already shows (`carried`) and the+ * `Label: url` lines still to add (`lines`, with their `targets`).+ */+export function crossLinkLines(links, text = '') {+ const carried = [];+ const added = [];+ for (const link of links) (String(text).includes(link.url) ? carried : added).push(link);+ return { carried: carried.map((l) => l.target), targets: added.map((l) => l.target), lines: added.map((l) => `${l.label}: ${l.url}`) };+}++/** The targets a posted record already links to. */+export function carriedLinks(kit, target) {+ const posts = kitOf(kit).posts || {};+ const post = posts[target];+ if (Array.isArray(post?.links)) return post.links;+ const at = post?.postedAt || '';+ return (LEGACY_LINKS[target] || []).filter((other) => {+ const earlier = posts[other];+ if (earlier) return !!earlier.postedAt && earlier.postedAt <= at;+ // A link given the kit by hand (song, full video) was there from the start.+ return !!releaseLinkUrl(kit, other);+ });+}++/**+ * Per posted, still-editable platform: the links it lacks and the text that+ * adds them (`Label: url` lines). `[{ target, url, missing, text }]`.+ */+export function crossLinkBackfill(kit) {+ const posts = kitOf(kit).posts || {};+ return CROSS_LINK_EDIT_TARGETS.filter((target) => str(posts[target]?.url)).map((target) => {+ const exclude = [target, ...carriedLinks(kit, target), ...(target === 'stackerNews' ? ['youtube'] : [])];+ const missing = releaseLinks(kit, { exclude });+ return { target, url: str(posts[target].url), missing, text: missing.map((l) => `${l.label}: ${l.url}`).join('\n') };+ });+}++/** `existing` links plus `added`, known targets only, without repeats. */+export function mergeCarriedLinks(existing, added) {+ const all = [...(Array.isArray(existing) ? existing : []), ...(Array.isArray(added) ? added : [])];+ return [...new Set(all.filter((t) => Object.hasOwn(CROSS_LINK_LABELS, t)))];+}diff --git a/server/lib/musicVideoCrossLinks.test.js b/server/lib/musicVideoCrossLinks.test.jsnew file mode 100644index 0000000000..efa1bd59a1--- /dev/null+++ b/server/lib/musicVideoCrossLinks.test.js@@ -0,0 +1,28 @@+/**+ * Which links a posted record already carries: its recorded `links`, else+ * what its draft always linked, counted only when that link existed first.+ */+import { describe, expect, it } from 'vitest';+import { carriedLinks, crossLinkBackfill } from './musicVideoCrossLinks.js';++const song = 'https://suno.com/song/12345678-abcd-4abc-8abc-123456789abc';++describe('cross-links between release posts', () => {+ it('reads a post recorded before links were kept by what its draft linked at the time', () => {+ const kit = { links: { song }, posts: {+ x: { url: 'https://x.com/example/status/1', postedAt: '2026-01-01T01:00:00Z' },+ youtube: { url: 'https://youtu.be/abc', postedAt: '2026-01-01T02:00:00Z' },+ suno: { url: song, postedAt: '2026-01-01T00:00:00Z' },+ } };+ // The song was up before the X thread; the video came after it.+ expect(carriedLinks(kit, 'x')).toEqual(['suno']);+ expect(carriedLinks({ ...kit, posts: { ...kit.posts, x: { ...kit.posts.x, links: ['youtube'] } } }, 'x')).toEqual(['youtube']);+ // A song link given the kit by hand counts as there from the start.+ expect(carriedLinks({ links: { song }, posts: { x: kit.posts.x } }, 'x')).toEqual(['suno']);+ const rows = Object.fromEntries(crossLinkBackfill(kit).map((r) => [r.target, r]));+ expect(rows.x.text).toBe('Music video: https://youtu.be/abc');+ expect(rows.suno.missing.map((l) => l.target)).toEqual(['youtube', 'x']);+ expect(rows.youtube.missing.map((l) => l.target)).toEqual(['suno', 'x']);+ expect(rows.stackerNews).toBeUndefined();+ });+});diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 5b23c0c75e..8c2348e86f 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -2,6 +2,7 @@ import { MUSIC_VIDEO_MEDIA_MODES } from './musicVideoMediaPolicy.js';import { MUSIC_VIDEO_GRADE_PRESETS, MUSIC_VIDEO_GRADE_MAX_GRAIN } from './musicVideoGrade.js';import { COVER_DESIGN_OPTIONS } from './musicVideoCoverOverlay.js';import { DISTROKID_REMEMBERED_OPTIONS } from './distrokidGenres.js';+import { CROSS_LINK_EDIT_TARGETS } from './musicVideoCrossLinks.js';/*** Music Video production mode — Zod schemas + shared enums (issue #1760, Phase 1).*@@ -804,7 +805,13 @@ export const musicVideoPublishPostSchema = z.object({posted: z.literal(true),reception: z.enum(['good', 'mixed', 'poor']).nullable(),notes: z.string().max(2000).nullable(),-}).partial().strict().refine((b) => Object.keys(b).length > 0, { message: 'url, posted, reception or notes is required' });+ // The release's other posts this one now links to (cross-links), added to what it linked already.+ links: z.array(musicVideoPublishTargetSchema).max(MUSIC_VIDEO_PUBLISH_TARGETS.length),+}).partial().strict().refine((b) => Object.keys(b).length > 0, { message: 'url, posted, reception, notes or links is required' });+// Whether new drafts list the release's other posts, and which posted platform gets its missing links.+export const musicVideoPublishCrossLinksSchema = z.object({ enabled: z.boolean() }).strict();+export const musicVideoCrossLinkTargetSchema = z.enum(CROSS_LINK_EDIT_TARGETS);+export const musicVideoCrossLinkEditSchema = z.object({}).strict();export const musicVideoPublishPrepareSchema = z.object({subreddit: z.string().max(40),kind: z.enum(['self', 'link', 'video']),diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex e161989717..58134de9c2 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -57,6 +57,9 @@ import {musicVideoPublishPrepareSchema,musicVideoPublishPlatformsPatchSchema,musicVideoPublishPostSchema,+ musicVideoPublishCrossLinksSchema,+ musicVideoCrossLinkTargetSchema,+ musicVideoCrossLinkEditSchema,musicVideoCodeGenerateSchema,musicVideoExcerptNoteSchema,musicVideoExcerptNoteUpdateSchema,@@ -132,7 +135,7 @@ import { startExcerptRender, attachExcerptRenderSseClient, cancelExcerptRender }import { deleteExcerpt, addReviewNote, editReviewNote, deleteReviewNote } from '../services/musicVideo/excerptService.js';import { suggestSocialCuts } from '../services/musicVideo/socialCuts.js';import { getActivePublishKitBuild, startPublishKitBuild, attachPublishKitSseClient, cancelPublishKitBuild, draftPublishKitCopy, updatePublishKitCopy, selectPublishKitThumbnail } from '../services/musicVideo/publishKit.js';-import { preparePublishDraft, previewPublishPost, discardPublishDraft, listPublishDrafts, recordPublishPost, removePublishPost } from '../services/musicVideo/publish/index.js';+import { preparePublishDraft, previewPublishPost, discardPublishDraft, listPublishDrafts, recordPublishPost, removePublishPost, prepareCrossLinkEdit, setPublishCrossLinks } from '../services/musicVideo/publish/index.js';import { getPublishPlatforms, updatePublishPlatforms, publishHistory } from '../services/musicVideo/publish/platforms.js';import { listArtistStyles, saveArtistStyle, removeArtistStyle } from '../services/musicVideo/publish/artistStyles.js';import { addCoverFont, coverFontPath, listCoverFonts, MAX_COVER_FONT_BYTES, removeCoverFont } from '../services/musicVideo/coverFonts.js';@@ -1094,6 +1097,21 @@ router.post('/:id/publish/:target/preview', asyncHandler(async (req, res) => {res.json(await previewPublishPost(req.params.id, target, options));}));+// Whether new drafts list the release's other posts (cross-links).+router.put('/:id/publish/cross-links', asyncHandler(async (req, res) => {+ const { enabled } = validateRequest(musicVideoPublishCrossLinksSchema, req.body || {});+ res.json(await setPublishCrossLinks(req.params.id, enabled));+}));++// Fill a posted platform's edit form (or a reply under it) with the links it lacks; the director saves it.+router.post('/:id/publish/:target/cross-links', asyncHandler(async (req, res) => {+ const target = validateRequest(musicVideoCrossLinkTargetSchema, req.params.target);+ await requireProductionReviewer(req);+ const { password: _password, ...body } = req.body || {};+ validateRequest(musicVideoCrossLinkEditSchema, body);+ res.json(await prepareCrossLinkEdit(req.params.id, target));+}));+router.post('/:id/publish/:target/prepare', asyncHandler(async (req, res) => {const target = validateRequest(musicVideoPublishTargetSchema, req.params.target);await requireProductionReviewer(req);diff --git a/server/services/musicVideo/publish/crossLinkEdits.js b/server/services/musicVideo/publish/crossLinkEdits.jsnew file mode 100644index 0000000000..97ba093191--- /dev/null+++ b/server/services/musicVideo/publish/crossLinkEdits.js@@ -0,0 +1,108 @@+/**+ * 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.+ *+ * `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';++const youtubeIdOf = (url) => String(url).match(/(?:youtu\.be\/|[?&]v=|\/shorts\/)([\w-]{6,})/)?.[1] || null;+const tweetIdOf = (url) => String(url).match(/\/status\/(\d+)/)?.[1] || null;+const sunoSongIdOf = (url) => String(url).match(/\/song\/([0-9a-f-]{36})/i)?.[1] || null;++/** The lines of `text` whose link `existing` does not already show. */+const linesNotIn = (text, existing) => text.split('\n').filter((line) => line && !existing.includes(line.slice(line.indexOf(': ') + 2)));++const youtube = {+ label: 'YouTube',+ async prepare(page, row) {+ const id = youtubeIdOf(row.url);+ if (!id) throw new Error(`no video id in ${row.url}`);+ const url = `https://studio.youtube.com/video/${id}/edit`;+ await step(this.label, 'open the video details', () => page.goto(url, { waitUntil: 'domcontentloaded', timeout: T }));+ await page.waitForTimeout(4000);+ if (/accounts\.google\.com/.test(page.url())) throw loginRequired(this.label, url);+ const box = page.locator('#description-textarea #textbox').first();+ await step(this.label, 'wait for the description', () => box.waitFor({ timeout: T }));+ const lines = linesNotIn(row.text, await box.innerText());+ if (lines.length) {+ await step(this.label, 'add the links to the description', async () => {+ await box.click();+ await page.keyboard.press('ControlOrMeta+End');+ await page.keyboard.insertText(`\n\n${lines.join('\n')}`);+ });+ }+ return { added: lines.length ? lines : ['Nothing: the description already has every link'], leftForYou: ['Save (top right)'] };+ },+};++const suno = {+ label: 'Suno',+ async prepare(page, row) {+ await step(this.label, 'open the song', () => page.goto(row.url, { waitUntil: 'domcontentloaded', timeout: T }));+ await page.waitForTimeout(5000);+ if (!(await page.locator("button[aria-label='More options']").count())) throw loginRequired(this.label, row.url);+ // Suno moves its menus around: a miss leaves the lines for the director to paste, never fails the card.+ const caption = await (async () => {+ const songId = sunoSongIdOf(page.url()) || sunoSongIdOf(row.url);+ if (!songId || !(await page.evaluate(markSunoSongMenu, songId))) return null;+ await page.locator('[data-portos-song-menu]').click({ timeout: 15_000 });+ await page.waitForTimeout(600);+ const item = (re) => page.locator('[role=menuitem]').filter({ hasText: re }).first();+ if (await item(/^Edit$/).isVisible().catch(() => false)) {+ await item(/^Edit$/).hover();+ await page.waitForTimeout(600);+ }+ const details = item(/Song Details|Edit Details|Details/);+ if (!(await details.isVisible().catch(() => false))) return null;+ await details.click({ timeout: 15_000 });+ const field = page.locator("[role=dialog] textarea[placeholder='Add a caption'], [role=dialog] textarea[aria-label*='caption' i]").first();+ await field.waitFor({ timeout: 15_000 });+ return field;+ })().catch(() => null);+ if (!caption) return { added: [], leftForYou: [`Open the song's details and add to its caption:\n${row.text}`, 'Save'] };+ const current = await caption.inputValue();+ const lines = linesNotIn(row.text, current);+ if (lines.length) await step(this.label, 'add the links to the caption', () => caption.fill([current.trimEnd(), lines.join('\n')].filter(Boolean).join('\n')));+ return { added: lines.length ? lines : ['Nothing: the caption already has every link'], leftForYou: ['Save'] };+ },+};++const x = {+ label: 'X',+ async prepare(page, row) {+ const id = tweetIdOf(row.url);+ if (!id) throw new Error(`no post id in ${row.url}`);+ const url = `https://x.com/intent/post?in_reply_to=${id}&text=${encodeURIComponent(row.text)}`;+ await step(this.label, 'open a reply to the post', () => page.goto(url, { waitUntil: 'domcontentloaded', timeout: T }));+ await page.waitForTimeout(4000);+ if (/\/login|\/i\/flow/.test(page.url())) throw loginRequired(this.label, url);+ const editor = '[data-testid=tweetTextarea_0]';+ await step(this.label, 'wait for the reply composer', () => page.locator(editor).first().waitFor({ timeout: T }));+ // The intent link normally prefills the text; paste it when it did not.+ const shown = await page.locator(editor).first().innerText().catch(() => '');+ if (!shown.includes(row.missing[0]?.url || row.text)) await step(this.label, 'write the reply', () => pasteText(page, editor, row.text));+ return { added: row.text.split('\n'), leftForYou: ['Reply'] };+ },+};++const stackerNews = {+ label: 'Stacker News',+ async prepare(page, row) {+ await step(this.label, 'open the post', () => page.goto(row.url, { waitUntil: 'domcontentloaded', timeout: T }));+ await page.waitForTimeout(3000);+ const editor = 'div[contenteditable=true]';+ if (!(await page.locator(editor).count())) throw loginRequired(this.label, 'https://stacker.news/login');+ await step(this.label, 'write the comment', async () => {+ await page.locator(editor).first().click();+ await pasteText(page, editor, row.text);+ });+ return { added: row.text.split('\n'), leftForYou: ['reply'] };+ },+};++export const CROSS_LINK_ADAPTERS = Object.freeze({ youtube, suno, x, stackerNews });diff --git a/server/services/musicVideo/publish/index.js b/server/services/musicVideo/publish/index.jsindex 2fe32e99ff..eabbaa7be0 100644--- a/server/services/musicVideo/publish/index.js+++ b/server/services/musicVideo/publish/index.js@@ -30,6 +30,8 @@ import { sunoAdapter } from './suno.js';import { sunoHookAdapter } from './sunoHook.js';import { distrokidAdapter } from './distrokid.js';import { musicVideoEvents } from '../events.js';+import { CROSS_LINK_ADAPTERS } from './crossLinkEdits.js';+import { carriedLinks, crossLinkBackfill, mergeCarriedLinks } from '../../../lib/musicVideoCrossLinks.js';export const PUBLISH_ADAPTERS = Object.freeze({youtube: youtubeAdapter, shorts: shortsAdapter, tiktok: tiktokAdapter, instagram: instagramAdapter,@@ -100,7 +102,7 @@ async function recordDetectedPost(draft, url) {drafts.delete(draft.id);draft.state = 'posted';// A record that fails to save leaves the draft as it was: the card keeps it, and the link can still be pasted.- const { project } = await recordPublishPost(draft.projectId, draft.target, { url }).catch((err) => {+ const { project } = await recordPublishPost(draft.projectId, draft.target, { url, links: draft.payload?.crossLinks }).catch((err) => {draft.state = 'open';drafts.set(draft.id, draft);throw err;@@ -295,19 +297,70 @@ export async function listPublishDrafts(projectId, deps = {}) {return mine.map(draftPresentation);}-/** Record or update one platform's post by hand: its link, reception (good/mixed/poor) and notes. */+/**+ * Record or update one platform's post by hand: its link, reception+ * (good/mixed/poor) and notes, and `links`, the release's other posts it now+ * links to (added to what it linked already). A link pasted for a post filled+ * here takes the links that draft carried.+ */export async function recordPublishPost(projectId, target, input = {}, deps = {}) {// The Suno post's link is the song the Hook plays: keep its song page, not a share link.if (target === 'suno' && isSunoShareLink(input.url)) input = { ...input, url: await canonicalizeSunoUrl(input.url, deps).catch(() => input.url) };+ if (input.url && !input.links) {+ const filled = [...drafts.values()].filter((d) => d.projectId === projectId && d.target === target).at(-1);+ if (filled?.payload?.crossLinks) input = { ...input, links: filled.payload.crossLinks };+ }const { project } = await mutateProjectRecord(projectId, (current) => {const kit = current.publishKit && typeof current.publishKit === 'object' ? current.publishKit : {};const posts = { ...(kit.posts || {}) };+ if (Array.isArray(input.links) && posts[target]) input = { ...input, links: mergeCarriedLinks(carriedLinks(kit, target), input.links) };posts[target] = normalizePost(posts[target], input);return { project: { ...current, publishKit: { ...kit, posts } } };});return { project, post: project.publishKit.posts[target] };}+/** Turn on or off whether new drafts list the release's other posts. */+export async function setPublishCrossLinks(projectId, enabled) {+ const { project } = await mutateProjectRecord(projectId, (current) => {+ const kit = current.publishKit && typeof current.publishKit === 'object' ? current.publishKit : {};+ return { project: { ...current, publishKit: { ...kit, crossLinks: enabled === true } } };+ });+ return { project };+}++/**+ * Open a posted platform's edit form (or a reply under it) in the PortOS+ * Browser and add the links to the release's posts it lacks. Nothing is+ * saved or posted: the director reviews the tab and saves it, then marks it+ * linked here. Resolves `{ target, links, summary, screenshot }`.+ */+export async function prepareCrossLinkEdit(projectId, target, deps = {}) {+ const adapter = (deps.crossLinkAdapters || CROSS_LINK_ADAPTERS)[target];+ if (!adapter) throw new ServerError(`No cross-link edit for ${target}`, { status: 400, code: 'VALIDATION_ERROR' });+ const project = await getProject(projectId);+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ const row = crossLinkBackfill(project.publishKit).find((r) => r.target === target);+ if (!row) throw new ServerError(`Record the ${adapter.label} post's link first`, { status: 422, code: 'PUBLISH_ASSET_MISSING' });+ if (!row.missing.length) throw new ServerError(`The ${adapter.label} post already links every other post`, { status: 409, code: 'PUBLISH_CROSS_LINKS_CURRENT' });+ return serialize(async () => {+ const { browser, context } = await (deps.connect || connectPortosBrowser)();+ const page = await context.newPage();+ try {+ await page.bringToFront();+ const summary = await adapter.prepare(page, row);+ const shot = await page.screenshot({ type: 'jpeg', quality: 70 }).catch(() => null);+ console.log(`🔗 ${adapter.label} cross-link edit filled for music-video ${projectId.slice(0, 8)}`);+ return { target, links: row.missing.map((l) => l.target), summary, screenshot: shot ? `data:image/jpeg;base64,${shot.toString('base64')}` : null };+ } catch (err) {+ await page.close().catch(() => {});+ throw err;+ } finally {+ await browser.close().catch(() => {}); // disconnects; the tab stays open for the director+ }+ });+}+/** Undo a platform's "done": drop its post record (a mistaken mark, or a post taken down). */export async function removePublishPost(projectId, target) {const { project } = await mutateProjectRecord(projectId, (current) => {diff --git a/server/services/musicVideo/publish/index.test.js b/server/services/musicVideo/publish/index.test.jsindex 87044c8785..af07b722f7 100644--- a/server/services/musicVideo/publish/index.test.js+++ b/server/services/musicVideo/publish/index.test.js@@ -14,7 +14,7 @@ vi.mock('../../../lib/paths.js', async (importOriginal) => makePathsProxy(awaitconst { PATHS } = await import('../../../lib/paths.js');const projects = await import('../projects.js');-const { preparePublishDraft, discardPublishDraft, listPublishDrafts, recordPublishPost, removePublishPost } = await import('./index.js');+const { preparePublishDraft, discardPublishDraft, listPublishDrafts, recordPublishPost, removePublishPost, prepareCrossLinkEdit, setPublishCrossLinks } = await import('./index.js');const { musicVideoEvents } = await import('../events.js');const { stackerNewsAdapter } = await import('./stackerNews.js');@@ -82,7 +82,7 @@ describe('publish drafts (#9282)', () => {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' });+ expect(substack.prepare).toHaveBeenCalledWith(expect.anything(), { publication: 'example.substack.com', videoUrl: 'https://youtu.be/abc', title: 'Song', subtitle: 'Sub', body: 'b', crossLinks: ['youtube'] });await expect(preparePublishDraft(id, 'substack', { again: true }, { connect, adapters: { substack }, platforms: { substack: { enabled: true, account: null } } })).rejects.toMatchObject({ status: 422, message: expect.stringMatching(/publication/) });});@@ -322,4 +322,40 @@ describe('publish drafts (#9282)', () => {await expect(preparePublishDraft(id, 'distrokid', options, deps)).rejects.toMatchObject({ status: 422, code: 'PUBLISH_ASSET_MISSING', message: expect.stringMatching(/missing on disk/) });expect(connect).not.toHaveBeenCalled();});++ it('records the links a filled draft carried when its link is pasted', async () => {+ const id = await readyProject();+ const { connect } = fakeBrowser();+ await preparePublishDraft(id, 'stackerNews', { territory: 'art' }, { connect, adapters: { stackerNews: adapter() }, platforms });+ const { post } = await recordPublishPost(id, 'stackerNews', { url: 'https://stacker.news/items/5' });+ expect(post.links).toEqual(['youtube']);+ });++ it('backfills a post made before the others: fills the missing links, leaves the tab for the director, then counts them once Saved', async () => {+ const id = await readyProject();+ await projects.mutateProjectRecord(id, (current) => ({ project: { ...current, publishKit: { ...current.publishKit, posts: {+ // Posted before YouTube existed, and before posts recorded their links.+ x: { url: 'https://x.com/example/status/42', postedAt: '2026-01-01T00:00:00Z' },+ youtube: { url: 'https://youtu.be/abc', postedAt: '2026-01-01T01:00:00Z', links: [] },+ stackerNews: { url: 'https://stacker.news/items/7', postedAt: '2026-01-01T02:00:00Z', links: ['youtube'] },+ } } } }));+ const { connect, pages, browsers } = fakeBrowser();+ const x = { label: 'X', prepare: vi.fn(async () => ({ leftForYou: ['Reply'] })) };+ const filled = await prepareCrossLinkEdit(id, 'x', { connect, crossLinkAdapters: { x } });+ expect(x.prepare.mock.calls[0][1]).toMatchObject({ target: 'x', url: 'https://x.com/example/status/42', text: 'Music video: https://youtu.be/abc\nStacker News: https://stacker.news/items/7' });+ expect(filled).toMatchObject({ target: 'x', links: ['youtube', 'stackerNews'], summary: { leftForYou: ['Reply'] }, screenshot: expect.stringMatching(/^data:image\/jpeg/) });+ expect(pages[0].closed).toBe(false);+ expect(browsers[0].close).toHaveBeenCalled();++ const { post } = await recordPublishPost(id, 'x', { links: filled.links });+ expect(post.links).toEqual(['youtube', 'stackerNews']);+ await expect(prepareCrossLinkEdit(id, 'x', { connect, crossLinkAdapters: { x } })).rejects.toMatchObject({ status: 409, code: 'PUBLISH_CROSS_LINKS_CURRENT' });+ await expect(prepareCrossLinkEdit(id, 'suno', { connect, crossLinkAdapters: { suno: x } })).rejects.toMatchObject({ status: 422 });+ });++ it('turns cross-links in new drafts off and on', async () => {+ const id = await readyProject();+ expect((await setPublishCrossLinks(id, false)).project.publishKit).toMatchObject({ crossLinks: false, copy: { stackerNews: { title: 'Song' } } });+ expect((await setPublishCrossLinks(id, true)).project.publishKit.crossLinks).toBe(true);+ });});diff --git a/server/services/musicVideo/publish/payloads.js b/server/services/musicVideo/publish/payloads.jsindex c74f805c3d..0dcdce3e9b 100644--- a/server/services/musicVideo/publish/payloads.js+++ b/server/services/musicVideo/publish/payloads.js@@ -9,6 +9,7 @@ import { chaptersText } from '../publishKitText.js';import { musicVideoDependencyChanges } from '../../../lib/musicVideoDependencies.js';import { suggestDistrokidGenres } from '../../../lib/distrokidGenres.js';import { suggestSocialCuts } from '../socialCuts.js';+import { crossLinkLines, crossLinksEnabled, releaseLinkUrl, releaseLinks } from '../../../lib/musicVideoCrossLinks.js';const TITLE_LIMITS = { youtube: 100, shorts: 100, reddit: 300, stackerNews: 80, substack: 100 };const DEFAULT_SUBREDDIT = 'aivideo';@@ -66,11 +67,11 @@ function pickVerticalCut(project, options) {}/** The full video's public link: the recorded YouTube post, else the one the director gave the kit. */-const fullVideoUrl = (kit) => text(kit.posts?.youtube?.url) || text(kit.links?.youtube) || '';+const fullVideoUrl = (kit) => releaseLinkUrl(kit, 'youtube');/** The Suno song a post links or plays: the director's pick, else the recorded Suno post, else the kit's song link. */export const publishSongUrl = (project, options) => {const kit = kitOf(project);- return text(options?.songUrl) || text(kit.posts?.suno?.url) || text(kit.links?.song) || '';+ return releaseLinkUrl(kitOf(project), 'suno', { songUrl: text(options?.songUrl) });};const songUrl = (kit, options) => publishSongUrl({ publishKit: kit }, options);@@ -81,11 +82,42 @@ function requireTitle(platform, title) {return title;}-function youtubeDescription(kit) {- const body = text(kit.copy?.youtube?.description);+/**+ * The release's other posts this one lists (unless the director turned+ * cross-links off), as `Label: url` lines missing from `base`, and every+ * target the finished post links (`carried`), which its record keeps.+ */+function otherPosts(kit, options, base, { exclude, always = [] }) {+ const links = crossLinksEnabled(kit) ? releaseLinks(kit, { exclude, songUrl: text(options?.songUrl) }) : [];+ const found = crossLinkLines(links, base);+ return { ...found, carried: [...always, ...found.carried, ...found.targets] };+}+const withLines = (body, lines) => [body, lines.join('\n')].filter(Boolean).join('\n\n');++function youtubeDescription(kit, options) {+ const copy = text(kit.copy?.youtube?.description);+ const links = otherPosts(kit, options, copy, { exclude: ['youtube'] });+ const body = withLines(copy, links.lines);// YouTube makes chapters from the description's timestamps; add them unless the copy already has them.const chapters = Array.isArray(kit.chapters) && kit.chapters.length && !/(^|\n)0:00\s/.test(body) ? `\n\nChapters\n${chaptersText(kit.chapters)}` : '';- return `${body}${chapters}`.trim();+ return { description: `${body}${chapters}`.trim(), crossLinks: links.carried };+}++const SUNO_CAPTION_MAX = 500;+/** The Suno caption: the story's lead, the video, then the other posts while they fit (a link is never cut). */+function sunoCaption(kit, options) {+ const video = fullVideoUrl(kit);+ const tail = video ? `Music video: ${video}` : '';+ const lead = text(kit.copy?.youtube?.description).split(/\n\s*\n/)[0] || '';+ let caption = [lead.slice(0, Math.max(0, SUNO_CAPTION_MAX - tail.length - 1)), tail].filter(Boolean).join(' ');+ const links = otherPosts(kit, options, caption, { exclude: ['suno', 'youtube'], always: video ? ['youtube'] : [] });+ const carried = links.carried.filter((t) => !links.targets.includes(t));+ links.lines.forEach((line, i) => {+ if (caption.length + line.length + 1 > SUNO_CAPTION_MAX) return;+ caption = `${caption}\n${line}`;+ carried.push(links.targets[i]);+ });+ return { caption, crossLinks: carried };}// A typed "@" on Instagram opens the mention picker, which swallows the next word.@@ -115,13 +147,13 @@ const releaseCover = (kit) => {};const BUILDERS = {- youtube: (project, kit) => {+ youtube: (project, kit, options = {}) => {if (!kit.master?.filename) throw missing('Build the publishing kit first — it names the final render to upload');requireFreshKit(project, kit);return {video: { dir: 'videos', name: kit.master.filename },title: requireTitle('youtube', text(kit.copy?.youtube?.title)),- description: youtubeDescription(kit),+ ...youtubeDescription(kit, options),tags: (kit.copy?.youtube?.tags || []).map(text).filter(Boolean),thumbnail: kit.thumbnail ? { dir: 'videoThumbnails', name: kit.thumbnail } : null,captions: kit.captionsFilename ? { dir: 'videos', name: kit.captionsFilename } : null,@@ -147,18 +179,22 @@ const BUILDERS = {const clip = (kit.exports || []).find((e) => e.kind === 'x-1080p')?.filename;if (!clip) throw missing('Build the publishing kit first — the X post carries its 1080p encode');requireFreshKit(project, kit);+ const writing = [hook, text(kit.copy?.x?.story), text(options.prompt)].join('\n');+ const others = otherPosts(kit, options, writing, { exclude: ['suno', 'youtube', 'x'] });const links = [songUrl(kit, options) ? `The song: ${songUrl(kit, options)}` : '',+ ...others.lines,// X builds a post's link card from its LAST link, so the full video goes last.fullVideoUrl(kit) ? `Full video: ${fullVideoUrl(kit)}` : '',].filter(Boolean).join('\n');+ const crossLinks = [...(songUrl(kit, options) ? ['suno'] : []), ...others.carried, ...(fullVideoUrl(kit) ? ['youtube'] : [])];const posts = [{ text: hook, media: { dir: 'videos', name: clip } },text(kit.copy?.x?.story) ? { text: text(kit.copy.x.story), media: options.storyImage ? { dir: 'videoThumbnails', name: options.storyImage } : null } : null,text(options.prompt) ? { text: text(options.prompt), media: null } : null,links ? { text: links, media: null } : null,].filter(Boolean);- return { posts };+ return { posts, crossLinks };},// A native upload (LinkedIn shows those to more people than outside links);// the links go in the first comment, never in the post.@@ -208,27 +244,31 @@ const BUILDERS = {if (!url) throw missing('Stacker News posts link to the full video: publish to YouTube first, or add its URL to the kit');const territory = text(options.territory || 'art').replace(/^~/, '');if (!/^[A-Za-z0-9_]{1,32}$/.test(territory)) throw missing('Name the Stacker News territory');- return { territory, title: requireTitle('stackerNews', text(kit.copy?.stackerNews?.title)), url, body: text(kit.copy?.stackerNews?.body), firstComment: text(options.firstComment) || null };+ const copy = text(kit.copy?.stackerNews?.body);+ const links = otherPosts(kit, options, copy, { exclude: ['youtube', 'stackerNews'], always: ['youtube'] });+ return {+ territory, title: requireTitle('stackerNews', text(kit.copy?.stackerNews?.title)), url, body: withLines(copy, links.lines),+ firstComment: text(options.firstComment) || null, crossLinks: links.carried,+ };},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');+ const copy = text(kit.copy?.substack?.body);+ const body = { text: copy, ...otherPosts(kit, options, copy, { exclude: ['youtube', 'substack'], always: ['youtube'] }) };return {publication, videoUrl,title: requireTitle('substack', text(kit.copy?.substack?.title)),- subtitle: text(kit.copy?.substack?.subtitle), body: text(kit.copy?.substack?.body),+ subtitle: text(kit.copy?.substack?.subtitle), body: withLines(body.text, body.lines), crossLinks: body.carried,};},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.if (!/^https:\/\/(www\.)?suno\.com\/song\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i.test(song)) throw missing('Give the Suno song URL to publish (suno.com/song/… or a suno.com/s/… share link)');- const video = fullVideoUrl(kit);- const lead = text(kit.copy?.youtube?.description).split(/\n\s*\n/)[0] || '';- const caption = [lead, video ? `Music video: ${video}` : ''].filter(Boolean).join(' ').slice(0, 500);- return { songUrl: song, caption, cover: releaseCover(kit), pin: options.pin !== false };+ return { songUrl: song, ...sunoCaption(kit, options), cover: releaseCover(kit), pin: options.pin !== false };},// A Suno Hook (#10375): the vertical cut set to a window of the project's song.sunoHook: (project, kit, options = {}) => {diff --git a/server/services/musicVideo/publish/payloads.test.js b/server/services/musicVideo/publish/payloads.test.jsindex 60ff23beab..56604a1b93 100644--- a/server/services/musicVideo/publish/payloads.test.js+++ b/server/services/musicVideo/publish/payloads.test.js@@ -126,7 +126,7 @@ describe('buildPublishPayload (#9282)', () => {expect(() => host('https://substack.com/@example')).toThrow(/Substack publication/);expect(() => host('www.substack.com')).toThrow(/Substack publication/);expect(buildPublishPayload('substack', project({ copy }), { publication: 'example' }))- .toEqual({ publication: 'example.substack.com', videoUrl: 'https://youtu.be/abc', title: 'Song', subtitle: '', body: 'Body' });+ .toEqual({ publication: 'example.substack.com', videoUrl: 'https://youtu.be/abc', title: 'Song', subtitle: '', body: 'Body\n\nSong: https://suno.com/song/12345678-abcd-4abc-8abc-123456789abc', crossLinks: ['youtube', 'suno'] });expect(() => buildPublishPayload('substack', project({ copy, links: {} }), { publication: 'example' })).toThrow(/publish to YouTube first/);expect(() => buildPublishPayload('substack', project(), { publication: 'example' })).toThrow(/substack title/);});@@ -151,6 +151,37 @@ describe('buildPublishPayload (#9282)', () => {expect(() => buildPublishPayload('suno', project({ links: {} }), { songUrl: 'https://suno.com/song/example' })).toThrow(/Suno song URL/);});+ it('lists the release posts already made in later drafts, never cutting a link, and none when turned off', () => {+ const posts = {+ suno: { url: 'https://suno.com/song/12345678-abcd-4abc-8abc-123456789abc', postedAt: '2026-01-01T00:00:00Z' },+ x: { url: 'https://x.com/example/status/1', postedAt: '2026-01-01T00:01:00Z' },+ stackerNews: { url: 'https://stacker.news/items/1', postedAt: '2026-01-01T00:02:00Z' },+ };+ const yt = buildPublishPayload('youtube', project({ posts }));+ expect(yt.description).toContain('The story.\n\nMore.\n\nSong: https://suno.com/song/12345678-abcd-4abc-8abc-123456789abc\nX: https://x.com/example/status/1\nStacker News: https://stacker.news/items/1\n\nChapters');+ expect(yt.crossLinks).toEqual(['suno', 'x', 'stackerNews']);+ // X keeps the full video last (its link card) with the others between.+ const x = buildPublishPayload('x', project({ posts }));+ expect(x.posts.at(-1).text).toBe('The song: https://suno.com/song/12345678-abcd-4abc-8abc-123456789abc\nStacker News: https://stacker.news/items/1\nFull video: https://youtu.be/abc');+ expect(x.crossLinks).toEqual(['suno', 'stackerNews', 'youtube']);+ const suno = buildPublishPayload('suno', project({ posts }));+ expect(suno.caption).toBe('The story. Music video: https://youtu.be/abc\nX: https://x.com/example/status/1\nStacker News: https://stacker.news/items/1');+ expect(suno.crossLinks).toEqual(['youtube', 'x', 'stackerNews']);+ const sn = buildPublishPayload('stackerNews', project({ posts }));+ expect(sn.body).toBe('SN body\n\nSong: https://suno.com/song/12345678-abcd-4abc-8abc-123456789abc\nX: https://x.com/example/status/1');+ // A link the copy already shows is not repeated.+ const typed = buildPublishPayload('stackerNews', project({ posts, copy: { ...kit().copy, stackerNews: { title: 'Song', body: 'On X: https://x.com/example/status/1' } } }));+ expect(typed.body).toBe('On X: https://x.com/example/status/1\n\nSong: https://suno.com/song/12345678-abcd-4abc-8abc-123456789abc');+ expect(typed.crossLinks).toEqual(['youtube', 'x', 'suno']);+ // A long caption keeps whole links: the video always, the rest while they fit.+ const long = buildPublishPayload('suno', project({ posts, copy: { youtube: { description: 'w'.repeat(600) } } }));+ expect(long.caption.length).toBeLessThanOrEqual(500);+ expect(long.caption.endsWith('Music video: https://youtu.be/abc')).toBe(true);+ expect(long.crossLinks).toEqual(['youtube']);+ const off = buildPublishPayload('youtube', project({ posts, crossLinks: false }));+ expect(off.description).not.toContain('x.com');+ });+it('rejects an unknown target', () => {expect(() => buildPublishPayload('myspace', project())).toThrow(expect.objectContaining({ status: 400 }));});diff --git a/server/services/musicVideo/publish/platforms.js b/server/services/musicVideo/publish/platforms.jsindex ad9748c283..b13c5b547c 100644--- a/server/services/musicVideo/publish/platforms.js+++ b/server/services/musicVideo/publish/platforms.js@@ -15,6 +15,7 @@ import { ServerError } from '../../../lib/errorHandler.js';import { getSettings, updateSettingsWith } from '../../settings.js';import { listProjects } from '../projects.js';import { DISTROKID_REMEMBERED_OPTIONS } from '../../../lib/distrokidGenres.js';+import { mergeCarriedLinks } from '../../../lib/musicVideoCrossLinks.js';const SETTINGS_KEY = 'musicVideoPublishing';const RECEPTIONS = ['good', 'mixed', 'poor'];@@ -103,6 +104,8 @@ export function normalizePost(existing = {}, input = {}) {const post = { ...(existing && typeof existing === 'object' ? existing : {}) };if ('url' in input) post.url = typeof input.url === 'string' && input.url.trim() ? input.url.trim() : null;if ('reception' in input) post.reception = RECEPTIONS.includes(input.reception) ? input.reception : null;+ // The release's other posts this one links to (cross-links).+ if (Array.isArray(input.links)) post.links = mergeCarriedLinks([], input.links);if ('notes' in input) post.notes = typeof input.notes === 'string' && input.notes.trim() ? input.notes.trim().slice(0, 2000) : null;if (!post.postedAt && (post.url || input.posted === true)) post.postedAt = new Date().toISOString();if ('reception' in input || 'notes' in input) post.ratedAt = new Date().toISOString();