Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(music-video): publishing kit — release encodes, captions, chapters, thumbnails and copy
[._.]/ Adam Eivy3145a88f27db
diff --git a/client/src/components/musicVideo/PublishKitPanel.jsx b/client/src/components/musicVideo/PublishKitPanel.jsxnew file mode 100644index 0000000000..f2d5e0d423--- /dev/null+++ b/client/src/components/musicVideo/PublishKitPanel.jsx@@ -0,0 +1,201 @@+import { useState } from 'react';+import { Package, Download, Copy, Sparkles, Image as ImageIcon, Captions, ListOrdered } from 'lucide-react';+import useProviderModels from '../../hooks/useProviderModels.js';+import ProviderModelSelector from '../ProviderModelSelector.jsx';+import { copyToClipboard } from '../../lib/clipboard.js';++const fmtTime = (sec) => {+ const s = Math.max(0, Math.floor(sec));+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;+};+const chaptersText = (chapters) => chapters.map((c) => `${fmtTime(c.startSec)} ${c.label}`).join('\n');++// What each platform's copy is made of; `max` shows a live count against the platform's own ceiling.+export const PUBLISH_FIELDS = [+ { platform: 'youtube', label: 'YouTube', fields: [+ { key: 'title', label: 'Title', max: 100 },+ { key: 'description', label: 'Description', multiline: true },+ { key: 'tags', label: 'Tags (comma-separated)', tags: true },+ ] },+ { platform: 'shorts', label: 'YouTube Shorts', fields: [{ key: 'title', label: 'Title', max: 100 }, { key: 'description', label: 'Description', multiline: true }] },+ { platform: 'x', label: 'X', fields: [{ key: 'hook', label: 'Hook post (no links)', max: 280, multiline: true }, { key: 'story', label: 'Story reply', multiline: true }] },+ { platform: 'tiktok', label: 'TikTok', fields: [{ key: 'caption', label: 'Caption', max: 2200, multiline: true }] },+ { platform: 'instagram', label: 'Instagram Reels', fields: [{ key: 'caption', label: 'Caption', max: 2200, multiline: true }] },+ { platform: 'reddit', label: 'Reddit', fields: [{ key: 'title', label: 'Title', max: 300 }, { key: 'body', label: 'Body (markdown)', multiline: true }] },+ { platform: 'stackerNews', label: 'Stacker News', fields: [{ key: 'title', label: 'Title', max: 80 }, { key: 'body', label: 'Body (markdown)', multiline: true }] },+];++const fieldValue = (copy, platform, field) => {+ const v = copy?.[platform]?.[field.key];+ if (field.tags) return Array.isArray(v) ? v.join(', ') : '';+ return typeof v === 'string' ? v : '';+};++function CopyField({ id, field, initial, onSave, disabled }) {+ const [value, setValue] = useState(initial);+ const over = field.max && value.length > field.max;+ const commit = () => {+ if (value === initial) return;+ onSave(field.tags ? value.split(',').map((t) => t.trim()).filter(Boolean) : value);+ };+ const Input = field.multiline ? 'textarea' : 'input';+ return (+ <div className="space-y-0.5">+ <div className="flex items-center justify-between gap-2">+ <label htmlFor={id} className="text-[11px] text-port-text-muted">{field.label}</label>+ <div className="flex items-center gap-2">+ {field.max && <span className={`text-[10px] font-mono ${over ? 'text-port-error' : 'text-port-text-muted'}`}>{value.length}/{field.max}</span>}+ <button type="button" onClick={() => copyToClipboard(value, `${field.label} copied`)} disabled={!value}+ aria-label={`Copy ${field.label}`} className="text-port-text-muted disabled:opacity-40 min-h-[44px] sm:min-h-0 px-1"><Copy size={12} /></button>+ </div>+ </div>+ <Input id={id} value={value} disabled={disabled} rows={field.multiline ? 4 : undefined}+ onChange={(e) => setValue(e.target.value)} onBlur={commit}+ className="w-full bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs min-h-[44px] sm:min-h-0" />+ </div>+ );+}++/**+ * Publishing kit (#9281): build the release assets from the final render+ * (platform encodes, thumbnails, SRT captions, YouTube chapters), draft every+ * platform's copy in one provider call from the director's own making-of+ * notes, then edit and copy each field out.+ */+export default function PublishKitPanel({ project, publishKit }) {+ const kit = project?.publishKit || {};+ const idFor = (s) => `mv-publish-${project?.id}-${s}`;+ const [notes, setNotes] = useState(kit.notes || '');+ const [youtubeUrl, setYoutubeUrl] = useState(kit.links?.youtube || '');+ const [songUrl, setSongUrl] = useState(kit.links?.song || '');+ const {+ providers, selectedProviderId, selectedModel, availableModels, setSelectedProviderId, setSelectedModel,+ } = useProviderModels({ allowDefault: true, silent: true });+ const canBuild = !!project?.renderHistoryId;+ const links = {+ ...(/^https?:\/\//.test(youtubeUrl.trim()) ? { youtube: youtubeUrl.trim() } : {}),+ ...(/^https?:\/\//.test(songUrl.trim()) ? { song: songUrl.trim() } : {}),+ };+ const draft = () => publishKit.draftCopy({+ ...(selectedProviderId ? { providerId: selectedProviderId } : {}),+ ...(selectedModel ? { model: selectedModel } : {}),+ notes, links,+ });++ return (+ <div className="space-y-3">+ <section aria-label="Release assets" className="rounded-lg border border-port-border bg-port-card p-3 space-y-2">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <h3 className="text-sm font-medium flex items-center gap-1.5"><Package size={14} /> Release assets</h3>+ <button type="button" disabled={!canBuild || publishKit.building} onClick={publishKit.build}+ className="flex items-center gap-1 bg-port-accent/20 text-port-accent disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0">+ <Package size={13} /> {kit.builtAt ? 'Rebuild kit' : 'Build publishing kit'}+ </button>+ </div>+ {!canBuild && <p className="text-xs text-port-text-muted">Render the final video first. The kit is made from it.</p>}+ {publishKit.building && (+ <div>+ <div className="h-1.5 bg-port-bg rounded overflow-hidden"><div className="h-full bg-port-accent transition-all" style={{ width: `${publishKit.progress}%` }} /></div>+ <p className="text-xs text-port-text-muted mt-1">Encoding — {Math.round(publishKit.progress)}%</p>+ </div>+ )}+ {kit.builtAt && (+ <div className="space-y-2 text-xs">+ <ul className="space-y-1">+ {kit.master?.filename && (+ <li className="flex flex-wrap items-center justify-between gap-2">+ <span>YouTube master (the final render)</span>+ <a href={`/data/videos/${kit.master.filename}`} download className="text-port-accent flex items-center gap-1 min-h-[44px] sm:min-h-0"><Download size={12} /> Download</a>+ </li>+ )}+ {(kit.exports || []).map((e) => (+ <li key={e.filename} className="flex flex-wrap items-center justify-between gap-2">+ <span>{e.label}{e.kind === 'teaser' && e.startSec != null && <span className="text-port-text-muted"> · {fmtTime(e.startSec)}–{fmtTime(e.endSec)}</span>}</span>+ <a href={`/data/videos/${e.filename}`} download className="text-port-accent flex items-center gap-1 min-h-[44px] sm:min-h-0"><Download size={12} /> Download</a>+ </li>+ ))}+ {kit.captionsFilename && (+ <li className="flex flex-wrap items-center justify-between gap-2">+ <span className="flex items-center gap-1"><Captions size={12} /> Lyric captions (SRT)</span>+ <a href={`/data/videos/${kit.captionsFilename}`} download className="text-port-accent flex items-center gap-1 min-h-[44px] sm:min-h-0"><Download size={12} /> Download</a>+ </li>+ )}+ </ul>+ {kit.chapters?.length > 0 && (+ <div className="space-y-1">+ <div className="flex items-center justify-between">+ <span className="text-port-text-muted flex items-center gap-1"><ListOrdered size={12} /> YouTube chapters (paste into the description)</span>+ <button type="button" onClick={() => copyToClipboard(chaptersText(kit.chapters), 'Chapters copied')} aria-label="Copy chapters"+ className="text-port-text-muted min-h-[44px] sm:min-h-0 px-1"><Copy size={12} /></button>+ </div>+ <pre className="bg-port-bg border border-port-border rounded p-2 whitespace-pre-wrap font-mono text-[11px]">{chaptersText(kit.chapters)}</pre>+ </div>+ )}+ {kit.thumbnails?.length > 0 && (+ <div className="space-y-1">+ <span className="text-port-text-muted flex items-center gap-1"><ImageIcon size={12} /> Thumbnail: pick one, or add title text before uploading</span>+ <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">+ {kit.thumbnails.map((name) => (+ <button key={name} type="button" onClick={() => publishKit.selectThumbnail(name)} aria-pressed={kit.thumbnail === name}+ aria-label={`Use thumbnail ${name}`}+ className={`rounded overflow-hidden border-2 ${kit.thumbnail === name ? 'border-port-accent' : 'border-transparent'}`}>+ <img src={`/data/video-thumbnails/${name}`} alt="" className="w-full aspect-video object-cover" />+ </button>+ ))}+ </div>+ </div>+ )}+ </div>+ )}+ </section>++ <section aria-label="Release copy" className="rounded-lg border border-port-border bg-port-card p-3 space-y-2 text-xs">+ <h3 className="text-sm font-medium flex items-center gap-1.5"><Sparkles size={14} /> Release copy</h3>+ <p className="text-port-text-muted">The draft only states what you give it here, plus the song, its lyrics and its generation spend. Nothing runs until you press Draft.</p>+ <div className="space-y-0.5">+ <label htmlFor={idFor('notes')} className="text-[11px] text-port-text-muted">Making-of notes (your story, in your words)</label>+ <textarea id={idFor('notes')} value={notes} maxLength={8000} rows={4} onChange={(e) => setNotes(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs" />+ </div>+ <div className="grid sm:grid-cols-2 gap-2">+ <div>+ <label htmlFor={idFor('youtube-url')} className="block text-[11px] text-port-text-muted">Full video URL (optional)</label>+ <input id={idFor('youtube-url')} value={youtubeUrl} onChange={(e) => setYoutubeUrl(e.target.value)} placeholder="https://…"+ className="w-full bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs min-h-[44px] sm:min-h-0" />+ </div>+ <div>+ <label htmlFor={idFor('song-url')} className="block text-[11px] text-port-text-muted">Song URL (optional)</label>+ <input id={idFor('song-url')} value={songUrl} onChange={(e) => setSongUrl(e.target.value)} placeholder="https://…"+ className="w-full bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs min-h-[44px] sm:min-h-0" />+ </div>+ </div>+ <div className="flex flex-wrap items-end gap-2">+ {providers.length > 0 && (+ <ProviderModelSelector providers={providers} selectedProviderId={selectedProviderId} selectedModel={selectedModel}+ availableModels={availableModels} onProviderChange={setSelectedProviderId} onModelChange={setSelectedModel}+ label="Writer" compact alwaysShowModel modelDisabled={availableModels.length === 0}+ emptyProviderOption="Active provider (default)" emptyModelOption="Default model" disabled={publishKit.drafting} />+ )}+ <button type="button" onClick={draft} disabled={publishKit.drafting}+ className="flex items-center gap-1 bg-port-accent/20 text-port-accent disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0">+ <Sparkles size={13} /> {publishKit.drafting ? 'Drafting…' : (kit.copy ? 'Redraft copy' : 'Draft copy')}+ </button>+ </div>+ {kit.copy && (+ <div className="space-y-3" key={kit.copyDraftedAt || 'copy'}>+ {PUBLISH_FIELDS.map(({ platform, label, fields }) => (+ <fieldset key={platform} className="space-y-1.5 rounded border border-port-border p-2">+ <legend className="px-1 text-[11px] font-medium">{label}</legend>+ {fields.map((field) => (+ <CopyField key={field.key} id={idFor(`${platform}-${field.key}`)} field={field}+ initial={fieldValue(kit.copy, platform, field)} disabled={publishKit.saving}+ onSave={(value) => publishKit.saveCopy({ [platform]: { [field.key]: value } })} />+ ))}+ </fieldset>+ ))}+ </div>+ )}+ </section>+ </div>+ );+}diff --git a/client/src/components/musicVideo/PublishKitPanel.test.jsx b/client/src/components/musicVideo/PublishKitPanel.test.jsxnew file mode 100644index 0000000000..7bd3bb69ec--- /dev/null+++ b/client/src/components/musicVideo/PublishKitPanel.test.jsx@@ -0,0 +1,60 @@+/**+ * Publish stage panel (#9281): the kit builds only from a final render, the+ * copy draft carries the director's notes and valid links, an edited field+ * saves on blur (tags as a list), and the thumbnail choice goes to the server.+ */+import { describe, it, expect, vi } from 'vitest';+import { render, screen, fireEvent } from '@testing-library/react';++vi.mock('../../hooks/useProviderModels.js', () => ({+ default: () => ({ providers: [], selectedProviderId: '', selectedModel: '', availableModels: [], setSelectedProviderId: vi.fn(), setSelectedModel: vi.fn() }),+}));+vi.mock('../../lib/clipboard.js', () => ({ copyToClipboard: vi.fn() }));++import PublishKitPanel from './PublishKitPanel.jsx';++const hook = (over = {}) => ({+ building: false, progress: 0, build: vi.fn(), drafting: false, saving: false,+ draftCopy: vi.fn(async () => null), saveCopy: vi.fn(async () => null), selectThumbnail: vi.fn(async () => null), ...over,+});+const built = {+ builtAt: '2026-01-01T00:00:00.000Z', master: { filename: 'master.mp4' },+ exports: [{ kind: 'x-1080p', label: 'X / social 1080p (12 Mbps)', filename: 'x.mp4' }],+ thumbnails: ['t1.jpg', 't2.jpg'], thumbnail: 't1.jpg', captionsFilename: 'c.srt',+ chapters: [{ startSec: 0, label: 'Opening line' }, { startSec: 30, label: 'Chorus' }, { startSec: 72, label: 'Outro' }],+ copy: { youtube: { title: 'A title', description: '', tags: ['music'] } }, copyDraftedAt: '2026-01-01T00:00:00.000Z',+};++describe('PublishKitPanel (#9281)', () => {+ it('builds only once there is a final render', () => {+ const k = hook();+ const { rerender } = render(<PublishKitPanel project={{ id: 'mv-1' }} publishKit={k} />);+ expect(screen.getByRole('button', { name: /Build publishing kit/ })).toBeDisabled();+ rerender(<PublishKitPanel project={{ id: 'mv-1', renderHistoryId: 'rh-1' }} publishKit={k} />);+ fireEvent.click(screen.getByRole('button', { name: /Build publishing kit/ }));+ expect(k.build).toHaveBeenCalled();+ });++ it('drafts copy from the notes and only well-formed links', () => {+ const k = hook();+ render(<PublishKitPanel project={{ id: 'mv-1', renderHistoryId: 'rh-1' }} publishKit={k} />);+ fireEvent.change(screen.getByLabelText(/Making-of notes/), { target: { value: 'hummed it in the car' } });+ fireEvent.change(screen.getByLabelText(/Full video URL/), { target: { value: 'https://example.com/v' } });+ fireEvent.change(screen.getByLabelText(/Song URL/), { target: { value: 'not a url' } });+ fireEvent.click(screen.getByRole('button', { name: /Draft copy/ }));+ expect(k.draftCopy).toHaveBeenCalledWith({ notes: 'hummed it in the car', links: { youtube: 'https://example.com/v' } });+ });++ it('shows the built kit, saves an edited field on blur and picks a thumbnail', () => {+ const k = hook();+ render(<PublishKitPanel project={{ id: 'mv-1', renderHistoryId: 'rh-1', publishKit: built }} publishKit={k} />);+ expect(screen.getByText('X / social 1080p (12 Mbps)')).toBeTruthy();+ expect(screen.getByText(/0:00 Opening line/)).toBeTruthy();+ const tags = screen.getByLabelText('Tags (comma-separated)');+ fireEvent.change(tags, { target: { value: 'music, ai video ,claude' } });+ fireEvent.blur(tags);+ expect(k.saveCopy).toHaveBeenCalledWith({ youtube: { tags: ['music', 'ai video', 'claude'] } });+ fireEvent.click(screen.getByRole('button', { name: 'Use thumbnail t2.jpg' }));+ expect(k.selectThumbnail).toHaveBeenCalledWith('t2.jpg');+ });+});diff --git a/client/src/components/musicVideo/stages/PublishStage.jsx b/client/src/components/musicVideo/stages/PublishStage.jsxnew file mode 100644index 0000000000..8c6eb80f2d--- /dev/null+++ b/client/src/components/musicVideo/stages/PublishStage.jsx@@ -0,0 +1,14 @@+import PublishKitPanel from '../PublishKitPanel.jsx';++/**+ * Publish: the release kit made from the final render (encodes, thumbnails,+ * captions, chapters) and the per-platform copy (#9281).+ */+export default function PublishStage({ board }) {+ const { project, locked, publishKit } = board;+ return (+ <fieldset disabled={locked} className="min-w-0">+ <PublishKitPanel project={project} publishKit={publishKit} />+ </fieldset>+ );+}diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 0b5e44d746..b4b7d0eeff 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -258,6 +258,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useMusicVideoRevisions` | Selective section revision (#8987): open a revision from a reviewed draft excerpt (its flagged sections' takes are rejected, the rest kept), resume it from the server checkpoint — generating ONLY the sections the server reports as `needsGeneration` through the board's scene lanes, or adopting the draft re-render via `attachRender` once every revised section has a take — and cancel it. Returns `{ busy, revise(excerptId, sceneIds?), resume(revisionId), cancel(revisionId), submitSections(project, refs, revisionId) }`. | The Music Video excerpt panel. || `useMusicVideoAutoReview` | Opt-in automatic review/retries (#8988): start a run over a draft window with explicit review (`maxAttempts`) and paid-generation (`maxGenerations`) limits plus a vision reviewer; applies the project pushed on `music-video:auto-review` and submits the revised sections a run hands out through `submitSections` while the board is open. Returns `{ busy, action, start(startSec, endSec, limits, reviewer), resume(runId, limits?), stop(runId), cancel(runId) }`. | The Music Video excerpt panel. || `useMusicVideoExcerpts` | Draft excerpt render + timecoded review notes (#8986): a `useSseJobSlot` render job over a chosen `[startSec, endSec)` window (any terminal frame reloads the project, since the persisted excerpt shape lives server-side) plus add/edit/delete review-note calls that apply the fresh whole project from each response. Returns `{ rendering, progress, deletingId, noteBusyId, startExcerpt(startSec, endSec), cancelExcerpt(excerptId), attachRender(jobId, projectId), deleteExcerpt(excerptId), addNote(excerptId, {atSec, note, verdict?}), editNote(excerptId, noteId, patch), deleteNote(excerptId, noteId) }`. | The Music Video excerpt panel. |+| `useMusicVideoPublishKit` | Music Video publishing kit (#9281): a `useSseJobSlot` build job (encodes, thumbnails, captions, chapters) whose terminal frame reloads the project, plus the one-call copy draft, per-field copy edits and thumbnail choice, each applying the returned project. Returns `{ building, progress, build(), cancelBuild(), drafting, saving, draftCopy(body), saveCopy(patch), selectThumbnail(filename) }`. | The Music Video Publish stage. || `useMusicVideoModelSettings` | A project's saved render pins — video backend (local/Grok/fal.ai)/model/generation-mode/audio-reactive LoRA + the image-side frame pin — with the Video Gen catalog they read from. Optimistic-local + silent PATCH, rollback + toast on failure; `saving` gates the dependent generate buttons. Returns `{ models, modelsLoading, defaultModel, falEnabled, saving, settings, effectiveModelId, activeModel, audioReactiveModels, audioReactiveLoras, detectedAudioReactiveLora, audioReactiveReady, audioReactiveSelected, videoBlockedReason, change, changeFramePin }`. `videoBlockedReason` is the single "why can't I generate" string (an unavailable audio-reactive setup, or a fal.ai pin with no configured API key) shared by the disabled buttons, their tooltips, and the blocked-call toast. | The Music Video renderer selects and anything building a scene-clip job payload from them. || `useMusicVideoSceneMedia` | Both per-scene generation lanes (reference frame + scene clip) over `useSceneRenderLifecycle`, the frame/shot prompt builders (concept-style + visual-spec direction suffix), visual-spec reference-image conditioning with explicit unsupported-backend feedback (#8965), and the batch "generate the missing ones" actions. Returns `{ genScenes, genVideoScenes, conditioning, buildFramePrompt, buildShotPrompt, generateFrame, generateSceneVideo, continueSceneVideo, generateMissingFrames, generateMissingVideos }`. | The Music Video scene board — don't re-wire the two lanes or re-derive the i2v/a2v/extend payloads. || `useMusicVideoTakes` | Scene-take review + external-asset handoff for the Music Video board (#8965): serialized select / reject / note / gallery-import take mutations folded back as scene patches, the handoff manifest download, and the handoff import (gallery upload per file, then scene association by file tag with provider provenance). Returns `{ busy, selectTake, reviewTake, importTake, exportHandoff, importHandoffFiles }`. | The Music Video board's take strips, contact sheet and handoff row — don't re-sequence take mutations per call site. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 216775ed18..2872aadc63 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -64,6 +64,7 @@ export { default as useMusicVideoAutoReview } from './useMusicVideoAutoReview.jsexport { default as useMusicVideoCastAndSets } from './useMusicVideoCastAndSets.js';export { default as useMusicVideoDevArtifacts } from './useMusicVideoDevArtifacts.js';export { default as useMusicVideoExcerpts } from './useMusicVideoExcerpts.js';+export { default as useMusicVideoPublishKit } from './useMusicVideoPublishKit.js';export { default as useMusicVideoKickoff } from './useMusicVideoKickoff.js';export { default as useMusicVideoManualTempo } from './useMusicVideoManualTempo.js';export { default as useMusicVideoMidiJob } from './useMusicVideoMidiJob.js';diff --git a/client/src/hooks/useMusicVideoPublishKit.js b/client/src/hooks/useMusicVideoPublishKit.jsnew file mode 100644index 0000000000..8421bdaeec--- /dev/null+++ b/client/src/hooks/useMusicVideoPublishKit.js@@ -0,0 +1,78 @@+import { useState } from 'react';+import toast from '../components/ui/Toast';+import {+ getMusicVideoProject,+ buildMusicVideoPublishKit,+ musicVideoPublishKitEventsUrl,+ cancelMusicVideoPublishKit,+ draftMusicVideoPublishCopy,+ updateMusicVideoPublishCopy,+ selectMusicVideoPublishThumbnail,+} from '../services/apiMusicVideo.js';+import useSseJobSlot from './useSseJobSlot.js';++const readPercent = (frame) => (Number.isFinite(frame.progress) ? frame.progress * 100 : undefined);++/**+ * Music Video publishing kit (#9281): the build is a `useSseJobSlot` job whose+ * terminal frame reloads the project it was started for (the kit lives on the+ * server record); the copy draft, copy edits and thumbnail choice each return+ * the whole project and apply it with `replaceProject`.+ */+export default function useMusicVideoPublishKit({ project, replaceProject } = {}) {+ const projectId = project?.id || null;+ const [drafting, setDrafting] = useState(false);+ const [saving, setSaving] = useState(false);++ const reload = (id) => {+ if (!id) return;+ getMusicVideoProject(id, { silent: true }).then(replaceProject).catch(() => {});+ };++ const job = useSseJobSlot({+ startRequest: () => buildMusicVideoPublishKit(projectId, { silent: true }),+ eventsUrl: musicVideoPublishKitEventsUrl,+ cancelRequest: cancelMusicVideoPublishKit,+ readPercent,+ onComplete: (_frame, id) => reload(id),+ onKickoffError: (err) => {+ if (err?.status === 409) { toast.error(err.message || 'The publishing kit cannot be built yet'); return true; }+ return false;+ },+ successToast: () => 'Publishing kit ready',+ errorFallback: 'Publishing kit build failed',+ canceledMessage: 'Publishing kit build cancelled',+ lostConnectionMessage: 'Lost connection to the publishing kit build',+ startErrorFallback: 'Failed to start the publishing kit build',+ });++ const apply = (res) => { if (res?.project) replaceProject(res.project); return res?.project || null; };++ const draftCopy = (body) => {+ setDrafting(true);+ return draftMusicVideoPublishCopy(projectId, body)+ .then(apply)+ .catch(() => null)+ .finally(() => setDrafting(false));+ };+ const saveCopy = (patch) => {+ setSaving(true);+ return updateMusicVideoPublishCopy(projectId, patch)+ .then(apply)+ .catch(() => null)+ .finally(() => setSaving(false));+ };+ const selectThumbnail = (filename) => selectMusicVideoPublishThumbnail(projectId, filename).then(apply).catch(() => null);++ return {+ building: job.active,+ progress: job.active ? job.percent : 0,+ build: () => job.start({}, projectId),+ cancelBuild: job.cancel,+ drafting,+ saving,+ draftCopy,+ saveCopy,+ selectThumbnail,+ };+}diff --git a/client/src/lib/musicVideoStages.js b/client/src/lib/musicVideoStages.jsindex 423b2107cb..03849d4dcf 100644--- a/client/src/lib/musicVideoStages.js+++ b/client/src/lib/musicVideoStages.js@@ -13,6 +13,7 @@ export const MUSIC_VIDEO_STAGES = [{ id: 'produce', label: 'Produce', title: 'Produce' },{ id: 'compose', label: 'Compose', title: 'Compose' },{ id: 'review', label: 'Review', title: 'Review & Export' },+ { id: 'publish', label: 'Publish', title: 'Publish' },];// Stages whose tab keeps the preview player docked beside the content.@@ -101,6 +102,8 @@ export function deriveStages(project) {produce: produceDone,compose: composeDone(project || {}, mode),review: !!project?.renderHistoryId,+ // #9281/#9282: a release is published once any platform post is recorded.+ publish: Object.keys(project?.publishKit?.posts || {}).length > 0,};const blocked = {'cast-sets': castStopped,@@ -108,7 +111,7 @@ export function deriveStages(project) {};const current = liveRun? 'produce'- : (MUSIC_VIDEO_STAGES.find((stage) => !done[stage.id])?.id || 'review');+ : (MUSIC_VIDEO_STAGES.find((stage) => !done[stage.id])?.id || 'publish');const stages = MUSIC_VIDEO_STAGES.map((stage) => {let state = 'todo';if (done[stage.id] && !(stage.id === current && liveRun)) state = 'done';@@ -175,6 +178,10 @@ export function deriveNextAction(project, {id: 'goto-compose', kind: 'goto', stage: 'compose',label: (project.composition?.mode === 'document') ? 'Attach a composition' : 'Add typography',};+ case 'publish':+ return project.publishKit?.builtAt+ ? { id: 'goto-publish', kind: 'goto', stage: 'publish', label: 'Publish the release' }+ : { id: 'goto-publish', kind: 'goto', stage: 'publish', label: 'Build the publishing kit' };default:if (project.renderHistoryId) return { id: 'goto-final', kind: 'goto', stage: 'review', anchor: 'mv-final-video', label: 'Watch final video' };return {diff --git a/client/src/lib/musicVideoStages.test.js b/client/src/lib/musicVideoStages.test.jsindex fdb82e6b5f..64d878d938 100644--- a/client/src/lib/musicVideoStages.test.js+++ b/client/src/lib/musicVideoStages.test.js@@ -70,8 +70,11 @@ describe('deriveStages / deriveNextAction', () => {expect(deriveNextAction(composed)).toMatchObject({ id: 'goto-compose', stage: 'compose' });const finished = { ...ready, renderHistoryId: 'rh-1' };- expect(stateOf(finished)).toMatchObject({ setup: 'done', board: 'done', produce: 'done', compose: 'done', review: 'done' });- expect(deriveNextAction(finished)).toMatchObject({ id: 'goto-final', kind: 'goto', stage: 'review' });+ expect(stateOf(finished)).toMatchObject({ setup: 'done', board: 'done', produce: 'done', compose: 'done', review: 'done', publish: 'active' });+ // #9281: a rendered project moves on to the release.+ expect(deriveNextAction(finished)).toMatchObject({ id: 'goto-publish', kind: 'goto', stage: 'publish', label: 'Build the publishing kit' });+ expect(deriveNextAction({ ...finished, publishKit: { builtAt: '2026-01-01T00:00:00.000Z' } })).toMatchObject({ label: 'Publish the release' });+ expect(stateOf({ ...finished, publishKit: { posts: { youtube: { url: 'https://example.com/v' } } } }).publish).toBe('done');});it('does not require scene footage for code-rendered or document projects', () => {diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex b08af1a291..88ef503950 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -29,6 +29,7 @@ import useMusicVideoDevArtifacts from '../hooks/useMusicVideoDevArtifacts.js';import useMusicVideoVocalSeparation from '../hooks/useMusicVideoVocalSeparation.js';import useMusicVideoRenderJob from '../hooks/useMusicVideoRenderJob.js';import useMusicVideoExcerpts from '../hooks/useMusicVideoExcerpts.js';+import useMusicVideoPublishKit from '../hooks/useMusicVideoPublishKit.js';import useMusicVideoRevisions from '../hooks/useMusicVideoRevisions.js';import useMusicVideoAutoReview from '../hooks/useMusicVideoAutoReview.js';import useMusicVideoProduction from '../hooks/useMusicVideoProduction.js';@@ -55,6 +56,7 @@ import BoardStage from '../components/musicVideo/stages/BoardStage.jsx';import ProduceStage from '../components/musicVideo/stages/ProduceStage.jsx';import ComposeStage from '../components/musicVideo/stages/ComposeStage.jsx';import ReviewStage from '../components/musicVideo/stages/ReviewStage.jsx';+import PublishStage from '../components/musicVideo/stages/PublishStage.jsx';import { compositionDraft } from '../components/musicVideo/compositionDraft.js';import ContactSheetDrawer from '../components/musicVideo/ContactSheetDrawer.jsx';import DevArtifactDrawer from '../components/musicVideo/DevArtifactDrawer.jsx';@@ -83,7 +85,7 @@ function autopilotBlocker(project) {// The panels each stage tab renders (see lib/musicVideoStages.js for the ids).const STAGE_VIEWS = {- setup: SetupStage, 'cast-sets': CastSetsStage, board: BoardStage, produce: ProduceStage, compose: ComposeStage, review: ReviewStage,+ setup: SetupStage, 'cast-sets': CastSetsStage, board: BoardStage, produce: ProduceStage, compose: ComposeStage, review: ReviewStage, publish: PublishStage,};const STATUS_COLORS = {@@ -179,6 +181,8 @@ export default function MusicVideo() {// separate from the full-render job/mutex above so a director can preview a// change without waiting on (or blocking) a full render.const excerpts = useMusicVideoExcerpts({ project: selected, replaceProject });+ // Publishing kit (#9281): release encodes, thumbnails, captions, chapters and copy.+ const publishKit = useMusicVideoPublishKit({ project: selected, replaceProject });const videoSettings = useMusicVideoModelSettings({ project: selected, onProjectPatch: patchProject });const tempo = useMusicVideoManualTempo({ project: selected, onUpdated: replaceProject });const sceneMedia = useMusicVideoSceneMedia({@@ -774,6 +778,7 @@ export default function MusicVideo() {takes,treatment,excerpts,+ publishKit,revisions,autoReview,finalVideo,diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex 60193a914f..b06b01ba84 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -78,6 +78,12 @@ vi.mock('../services/apiMusicVideo.js', () => ({reviewMusicVideoTreatmentProof: vi.fn(),renderMusicVideoExcerpt: vi.fn(async () => ({ jobId: 'mve-job-1', excerptId: 'mve-job-1' })),musicVideoExcerptRenderEventsUrl: (jobId) => `/api/music-video/excerpt/${jobId}/events`,+ buildMusicVideoPublishKit: vi.fn(async () => ({ jobId: 'mvpk-job-1' })),+ musicVideoPublishKitEventsUrl: (jobId) => `/api/music-video/publish-kit/${jobId}/events`,+ cancelMusicVideoPublishKit: vi.fn(async () => ({ ok: true })),+ draftMusicVideoPublishCopy: vi.fn(),+ updateMusicVideoPublishCopy: vi.fn(),+ selectMusicVideoPublishThumbnail: vi.fn(),cancelMusicVideoExcerptRender: vi.fn(async () => ({ ok: true })),deleteMusicVideoExcerpt: vi.fn(),addMusicVideoExcerptNote: vi.fn(),@@ -2094,11 +2100,12 @@ describe('MusicVideo stage tabs (#9243)', () => {await waitFor(() => expect(stopMusicVideoProduction).toHaveBeenCalledWith('mv-3', 'run-1', { silent: true }));});- it('takes a finished project to its final video', async () => {+ it('takes a finished project on to its release (#9281)', async () => {await openProject({ ...PROJECT_WITH_CLIP, audioAnalysis: PROJECT_ANALYZED.audioAnalysis, renderHistoryId: 'rh-9' }, 'board');- fireEvent.click(screen.getByRole('button', { name: 'Watch final video' }));- await waitFor(() => expect(selectedTab()).toHaveTextContent(/^Review/));- expect(document.getElementById('mv-final-video')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'Build the publishing kit' }));+ await waitFor(() => expect(selectedTab()).toHaveTextContent(/^Publish/));+ expect(screen.getByRole('region', { name: 'Release assets' })).toBeTruthy();+ expect(screen.getByRole('button', { name: /Build publishing kit/ })).not.toBeDisabled();});});diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex ff8aa3a65b..3a3810118d 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -192,6 +192,21 @@ export const getMusicVideoSocialCuts = (id, { count, minSec, maxSec } = {}, opticonst qs = params.toString();return request(`/music-video/${encodeURIComponent(id)}/social-cuts${qs ? `?${qs}` : ''}`, options);};+// ---- Publishing kit (#9281) ----+// Build: platform encodes, thumbnails, captions and chapters from the final+// render → { jobId } (progress over its own SSE URL). Copy: one provider draft,+// then per-field edits; both resolve to { project }.+export const buildMusicVideoPublishKit = (id, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/publish-kit/build`, { method: 'POST', ...options });+export const musicVideoPublishKitEventsUrl = (jobId) => `/api/music-video/publish-kit/${encodeURIComponent(jobId)}/events`;+export const cancelMusicVideoPublishKit = (jobId, options = {}) =>+ request(`/music-video/publish-kit/${encodeURIComponent(jobId)}/cancel`, { method: 'POST', ...options });+export const draftMusicVideoPublishCopy = (id, body, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/publish-kit/copy`, { method: 'POST', body: JSON.stringify(body || {}), ...options });+export const updateMusicVideoPublishCopy = (id, patch, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/publish-kit/copy`, { method: 'PATCH', body: JSON.stringify(patch || {}), ...options });+export const selectMusicVideoPublishThumbnail = (id, filename, options = {}) =>+ request(`/music-video/${encodeURIComponent(id)}/publish-kit/thumbnail`, { method: 'PUT', body: JSON.stringify({ filename }), ...options });export const musicVideoExcerptRenderEventsUrl = (jobId) =>`/api/music-video/excerpt/${encodeURIComponent(jobId)}/events`;export const cancelMusicVideoExcerptRender = (jobId, options = {}) =>diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.mdindex 29e03a1d56..48d931e377 100644--- a/docs/features/product-surfaces.md+++ b/docs/features/product-surfaces.md@@ -110,7 +110,7 @@ An end-to-end creative production suite for authors, worldbuilders, filmmakers,| **SongBook** | `/songbook` | Interactive chord charts, guitar tablature, lyric repertoire, and auto-scrolling practice sheet music. | — || **Creative Director** | `/creative-director` | Multi-scene episodic video production orchestrator: turn briefs into treatments, storyboards, render plans, and completed episodes. | — || **Creative Commissions** | `/creative-commission` | Standing briefs and scheduled/nightly autonomous media generation aligning with personal taste profiles and feedback. A universe and/or mood board can be picked as the style source: each run loads its style tags and reference images as the Creative Director's art-direction base, attaches those images to vision scene evaluation, and conditions local image renders on them. | — |-| **Music Video Studio** | `/music-video` | A project opens on six deep-linked stage tabs (`/music-video/:projectId/:stage` — `setup`, `cast-sets`, `board`, `produce`, `compose`, `review`; a bottom tab bar on a phone) under a sticky header showing its progress, paid-generation spend against the cap, and the one next action for the stage it is in; the composition preview (or, without a composition document, the latest draft excerpt) is docked beside the Board, Compose and Review tabs, and scene cards seek it. Audio-reactive video creation, beat-detection synchronization, scene choreography, tempo alignment, and audience-driven pre-production treatments that direct each shot. Scenes are cutaways or lip-synced performance shots; a performance shot renders only on a verified source-audio provider (fal.ai MiniMax H3 lip-sync, 5–14.8s song slices placed at an exact edit in-point, cut from an optional full-length vocal stem when one is attached — uploaded, or separated from the song with a locally installed demucs) — Grok video is cutaway-only. The autopilot kickoff analyzes the song, imports the linked track's lyric sheet (its `[Verse]`/`[Chorus]` headers and stage directions kept as lyric markers that name the analysis sections and steer shot framing), separates the vocal, aligns every word with local whisper.cpp (large-v3-turbo, downloaded on first use), builds a Cast & Sets check-in (one creative-direction call that interprets the song, then a canonical character sheet, expression and looks sheets, one empty plate per set and in-set tests on the image queue, each later image conditioned on the character sheet; assembled into a self-contained sheet saved as a development artifact), stops for the director's review unless the brief auto-approves it, then plans against the approved references. Development artifacts (check-in sheets, animatics, treatments, storyboards; HTML/Markdown/MP4/PNG/JPG) are versioned per project, reviewed with notes and approve/request-changes, and viewed in a sandboxed viewer at `/music-video/:projectId/:stage/dev/:artifactId` (the stage-less `/music-video/:projectId/dev/:artifactId` still opens it). Draft excerpts are reviewed and selectively revised by hand, or by an opt-in auto-review run bounded by director-set review and paid-generation limits (a frame-only look never passes motion or audio sync). A server-owned production run (`/api/music-video/:id/production-runs`, #9066) plans an empty board, generates missing frames and clips only on a director-allowed image/video provider+model pool, hands the continuous draft to auto-review and dispatches its revisions — within explicit generation, review and (priced routes only) dollar limits, without the browser open, and never resuming on its own after a restart; the song is the sole audio unless a sound-design bed is explicitly chosen to mix under it. | — |+| **Music Video Studio** | `/music-video` | A project opens on seven deep-linked stage tabs (`/music-video/:projectId/:stage` — `setup`, `cast-sets`, `board`, `produce`, `compose`, `review`, `publish`; a bottom tab bar on a phone) under a sticky header showing its progress, paid-generation spend against the cap, and the one next action for the stage it is in; the composition preview (or, without a composition document, the latest draft excerpt) is docked beside the Board, Compose and Review tabs, and scene cards seek it. Audio-reactive video creation, beat-detection synchronization, scene choreography, tempo alignment, and audience-driven pre-production treatments that direct each shot. Scenes are cutaways or lip-synced performance shots; a performance shot renders only on a verified source-audio provider (fal.ai MiniMax H3 lip-sync, 5–14.8s song slices placed at an exact edit in-point, cut from an optional full-length vocal stem when one is attached — uploaded, or separated from the song with a locally installed demucs) — Grok video is cutaway-only. The autopilot kickoff analyzes the song, imports the linked track's lyric sheet (its `[Verse]`/`[Chorus]` headers and stage directions kept as lyric markers that name the analysis sections and steer shot framing), separates the vocal, aligns every word with local whisper.cpp (large-v3-turbo, downloaded on first use), builds a Cast & Sets check-in (one creative-direction call that interprets the song, then a canonical character sheet, expression and looks sheets, one empty plate per set and in-set tests on the image queue, each later image conditioned on the character sheet; assembled into a self-contained sheet saved as a development artifact), stops for the director's review unless the brief auto-approves it, then plans against the approved references. Development artifacts (check-in sheets, animatics, treatments, storyboards; HTML/Markdown/MP4/PNG/JPG) are versioned per project, reviewed with notes and approve/request-changes, and viewed in a sandboxed viewer at `/music-video/:projectId/:stage/dev/:artifactId` (the stage-less `/music-video/:projectId/dev/:artifactId` still opens it). Draft excerpts are reviewed and selectively revised by hand, or by an opt-in auto-review run bounded by director-set review and paid-generation limits (a frame-only look never passes motion or audio sync). A server-owned production run (`/api/music-video/:id/production-runs`, #9066) plans an empty board, generates missing frames and clips only on a director-allowed image/video provider+model pool, hands the continuous draft to auto-review and dispatches its revisions — within explicit generation, review and (priced routes only) dollar limits, without the browser open, and never resuming on its own after a restart; the song is the sole audio unless a sound-design bed is explicitly chosen to mix under it. Draft excerpts can be re-framed as vertical or square social cuts with faded audio edges, from suggested hook windows (#9280). The Publish stage (#9281) builds a release kit from the final render: an X-sized 1080p, a 720p preview, a hook teaser, thumbnail candidates, lyric captions (SRT) and YouTube chapters. It also drafts every platform's copy in one director-triggered provider call from their own making-of notes, and every field stays editable. | — || **Sharing & Conflict Resolution** | `/sharing`, `/sharing/duplicates`, `/sharing/conflicts` | Collaborative asset exchange via cloud storage buckets (Google Drive, Dropbox, iCloud, Syncthing) with duplicate reconciliation and conflict recovery journals. | — |---diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex eb3dd4ae17..672a03b1de 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -524,6 +524,26 @@ export const musicVideoSocialCutsQuerySchema = z.object({maxSec: z.coerce.number().min(5).max(180).optional(),}).strict().refine((q) => q.minSec == null || q.maxSec == null || q.maxSec >= q.minSec, { message: 'maxSec must be at least minSec' });+// #9281: publishing kit — per-platform copy edits, the copy draft request, the chosen thumbnail.+const kitText = (max) => z.string().max(max);+export const musicVideoPublishCopyPatchSchema = z.object({+ youtube: z.object({ title: kitText(100), description: kitText(5000), tags: z.array(kitText(60)).max(30) }).partial().strict().optional(),+ shorts: z.object({ title: kitText(100), description: kitText(5000) }).partial().strict().optional(),+ x: z.object({ hook: kitText(280), story: kitText(25000) }).partial().strict().optional(),+ tiktok: z.object({ caption: kitText(2200) }).partial().strict().optional(),+ instagram: z.object({ caption: kitText(2200) }).partial().strict().optional(),+ reddit: z.object({ title: kitText(300), body: kitText(40000) }).partial().strict().optional(),+ stackerNews: z.object({ title: kitText(80), body: kitText(40000) }).partial().strict().optional(),+ notes: kitText(8000).optional(),+}).strict();+export const musicVideoPublishCopyDraftSchema = z.object({+ providerId: z.string().max(200).nullable().optional(),+ model: z.string().max(200).nullable().optional(),+ notes: kitText(8000).optional(),+ links: z.object({ youtube: z.string().url().max(500), song: z.string().url().max(500) }).partial().strict().optional(),+}).strict();+export const musicVideoPublishThumbnailSchema = z.object({ filename: z.string().min(1).max(300) }).strict();+export const musicVideoExcerptNoteSchema = z.object({atSec: z.number().min(0).max(36000),note: z.string().min(1).max(2000),diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 09908e7f1b..c7a4e41d64 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -36,6 +36,9 @@ import {musicVideoTreatmentProofReviewSchema,musicVideoExcerptRequestSchema,musicVideoSocialCutsQuerySchema,+ musicVideoPublishCopyPatchSchema,+ musicVideoPublishCopyDraftSchema,+ musicVideoPublishThumbnailSchema,musicVideoCodeGenerateSchema,musicVideoExcerptNoteSchema,musicVideoExcerptNoteUpdateSchema,@@ -98,6 +101,7 @@ import { generateMusicVideoCode, regenerateMusicVideoCodeSection } from '../servimport { startExcerptRender, attachExcerptRenderSseClient, cancelExcerptRender } from '../services/musicVideo/excerptRender.js';import { deleteExcerpt, addReviewNote, editReviewNote, deleteReviewNote } from '../services/musicVideo/excerptService.js';import { suggestSocialCuts } from '../services/musicVideo/socialCuts.js';+import { startPublishKitBuild, attachPublishKitSseClient, cancelPublishKitBuild, draftPublishKitCopy, updatePublishKitCopy, selectPublishKitThumbnail } from '../services/musicVideo/publishKit.js';import {startRevision, resumeRevision, cancelRevision, releaseRevisionSection,} from '../services/musicVideo/revisionService.js';@@ -577,6 +581,40 @@ router.post('/:id/excerpt', asyncHandler(async (req, res) => {res.json(await startExcerptRender(req.params.id, { startSec, endSec, aspect, fade }));}));+// --- Publishing kit (#9281) ---+// Platform encodes, thumbnails, captions and chapters from the final render+// (an SSE job), plus per-platform copy: one user-triggered draft, then edits.+router.post('/:id/publish-kit/build', asyncHandler(async (req, res) => {+ res.json(await startPublishKitBuild(req.params.id));+}));++router.get('/publish-kit/:jobId/events', (req, res) => {+ const ok = attachPublishKitSseClient(req.params.jobId, res);+ if (!ok) throw new ServerError('Publishing kit job not found or expired', { status: 404, code: 'NOT_FOUND' });+});++router.post('/publish-kit/:jobId/cancel', (req, res) => {+ res.json({ ok: cancelPublishKitBuild(req.params.jobId) });+});++router.post('/:id/publish-kit/copy', asyncHandler(async (req, res) => {+ const input = validateRequest(musicVideoPublishCopyDraftSchema, req.body || {});+ const { project } = await draftPublishKitCopy(req.params.id, input);+ res.json({ project });+}));++router.patch('/:id/publish-kit/copy', asyncHandler(async (req, res) => {+ const patch = validateRequest(musicVideoPublishCopyPatchSchema, req.body || {});+ const { project } = await updatePublishKitCopy(req.params.id, patch);+ res.json({ project });+}));++router.put('/:id/publish-kit/thumbnail', asyncHandler(async (req, res) => {+ const { filename } = validateRequest(musicVideoPublishThumbnailSchema, req.body || {});+ const { project } = await selectPublishKitThumbnail(req.params.id, filename);+ res.json({ project });+}));+// #9280: the song windows most likely to work as a vertical social cut.router.get('/:id/social-cuts', asyncHandler(async (req, res) => {const options = validateRequest(musicVideoSocialCutsQuerySchema, req.query);diff --git a/server/services/musicVideo/publishKit.js b/server/services/musicVideo/publishKit.jsnew file mode 100644index 0000000000..c7a694f157--- /dev/null+++ b/server/services/musicVideo/publishKit.js@@ -0,0 +1,230 @@+/**+ * Music Video — publishing kit (#9281).+ *+ * Everything a release needs that the project already knows: platform encodes+ * of the final render (an X-sized 1080p, a 720p preview, a hook teaser),+ * thumbnail candidates, an SRT of the timed lyrics, YouTube chapters, and+ * per-platform copy the director edits. `project.publishKit` is an additive+ * field on the whole-record LWW body (same posture as `excerpts`), so an older+ * peer carries it through untouched.+ *+ * The build runs ffmpeg only; the copy is ONE user-triggered LLM call (AI+ * Provider Usage Policy) and every field stays editable afterwards.+ */+import { randomUUID } from 'crypto';+import { existsSync } from 'fs';+import { unlink, writeFile } from 'fs/promises';+import { join } from 'path';+import { ServerError } from '../../lib/errorHandler.js';+import { ensureDir, PATHS } from '../../lib/fileUtils.js';+import { safeUnder, edgeFadeFilter } from '../../lib/ffmpeg.js';+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';+import { getProject, listProjects, mutateProjectRecord } from './projects.js';+import { suggestSocialCuts } from './socialCuts.js';+import { buildChapters, buildSrt, buildPublishCopyPrompt, parsePublishCopy, PUBLISH_PLATFORMS } from './publishKitText.js';++const jobs = new Map();+const projectBuilds = new Map();+const MAX_THUMBNAILS = 6;+// X caps a Premium upload's bitrate well under a 1080p master's; ~12 Mbps+// keeps the analog grain without the upload being re-crushed.+const X_VIDEO_ARGS = ['-c:v', 'libx264', '-profile:v', 'high', '-preset', 'medium', '-b:v', '10M', '-maxrate', '12M', '-bufsize', '24M', '-pix_fmt', 'yuv420p'];+const AUDIO_ARGS = ['-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart'];++export const attachPublishKitSseClient = (jobId, res) => attachSse(jobs, jobId, res);+export const projectPublishKit = (project) => (project?.publishKit && typeof project.publishKit === 'object' ? project.publishKit : {});++const kitError = (status, code, message) => new ServerError(message, { status, code });++async function requireProject(projectId) {+ const project = await getProject(projectId);+ if (!project) throw kitError(404, 'NOT_FOUND', 'Project not found');+ return project;+}++/** The final render's file (the YouTube master), or a 409 naming what's missing. */+async function finalRenderFile(project) {+ if (!project.renderHistoryId) throw kitError(409, 'NO_FINAL_RENDER', 'Render the final video before building the publishing kit');+ const { getHistoryItem } = await import('../videoGen/history.js');+ const entry = await getHistoryItem(project.renderHistoryId);+ const path = entry?.filename ? safeUnder(PATHS.videos, entry.filename) : null;+ if (!path || !existsSync(path)) throw kitError(409, 'NO_FINAL_RENDER', 'The final render file is missing — render the final video again');+ return { entry, path };+}++/** Frame times worth a thumbnail: performance-shot midpoints spread across the song, else even steps. */+function thumbnailTimes(project, durationSec, max = MAX_THUMBNAILS) {+ const perf = (project.scenes || [])+ .filter((s) => s?.shotMode === 'performance' && Number.isFinite(s.startSec) && Number.isFinite(s.endSec) && s.endSec > s.startSec && s.startSec < durationSec)+ .map((s) => (s.startSec + Math.min(s.endSec, durationSec)) / 2);+ const pool = perf.length ? perf : Array.from({ length: max }, (_, i) => ((i + 0.5) / max) * durationSec);+ if (pool.length <= max) return pool.map((t) => Math.round(t * 1000) / 1000);+ return Array.from({ length: max }, (_, i) => pool[Math.floor((i * pool.length) / max)]).map((t) => Math.round(t * 1000) / 1000);+}++/** A file an older build left behind, deleted only once no project's kit still names it (a clone shares the record). */+async function releaseKitFiles(filenames, keep) {+ if (!filenames.length) return;+ const others = await listProjects().catch(() => []);+ const referenced = new Set(keep);+ for (const p of others) {+ const kit = projectPublishKit(p);+ for (const f of [...(kit.exports || []).map((e) => e.filename), ...(kit.thumbnails || []), kit.captionsFilename]) if (f) referenced.add(f);+ }+ for (const name of filenames) {+ if (referenced.has(name)) continue;+ const root = name.endsWith('.jpg') ? PATHS.videoThumbnails : PATHS.videos;+ const path = safeUnder(root, name);+ if (path) await unlink(path).catch(() => {});+ }+}++/**+ * Start a kit build: encodes, thumbnails, captions and chapters from the+ * current final render. Returns `{ jobId }`; progress streams over SSE and the+ * record carries the result.+ */+export async function startPublishKitBuild(projectId) {+ const project = await requireProject(projectId);+ if (projectBuilds.has(projectId)) throw kitError(409, 'PUBLISH_KIT_BUILD_IN_PROGRESS', 'A publishing kit build is already running for this project');+ const { entry, path: masterPath } = await finalRenderFile(project);+ const { findFfmpeg, runFfmpegProcess, probeVideoDuration } = await import('../../lib/ffmpeg.js');+ const ffmpeg = await findFfmpeg();+ if (!ffmpeg) throw kitError(500, 'FFMPEG_MISSING', 'ffmpeg not found on PATH');+ const jobId = `mvpk-${randomUUID()}`;+ const job = { id: jobId, projectId, status: 'running', clients: [], abort: new AbortController() };+ jobs.set(jobId, job);+ projectBuilds.set(projectId, jobId);+ const tag = jobId.slice(5, 13);+ console.log(`📦 Building music-video publishing kit [${tag}]: project=${projectId.slice(0, 8)}`);++ const run = async () => {+ await ensureDir(PATHS.videos);+ await ensureDir(PATHS.videoThumbnails);+ const durationSec = Number(entry.durationSec) > 0 ? Number(entry.durationSec) : await probeVideoDuration(masterPath);+ const stem = `music-video-${projectId.slice(3, 11)}-${Date.now()}`;+ const [teaser] = suggestSocialCuts(project, { count: 1, minSec: 25, maxSec: 45 });+ const encodes = [+ { kind: 'x-1080p', label: 'X / social 1080p (12 Mbps)', filename: `${stem}-x-1080p.mp4`,+ args: ['-i', masterPath, '-vf', "scale=w='min(1920,iw)':h='min(1080,ih)':force_original_aspect_ratio=decrease", ...X_VIDEO_ARGS, ...AUDIO_ARGS] },+ { kind: 'preview-720p', label: '720p preview', filename: `${stem}-preview-720p.mp4`,+ args: ['-i', masterPath, '-vf', "scale=-2:'min(720,ih)'", '-c:v', 'libx264', '-preset', 'medium', '-crf', '23', '-pix_fmt', 'yuv420p', ...AUDIO_ARGS] },+ ...(teaser ? [{ kind: 'teaser', label: `Teaser ${Math.round(teaser.endSec - teaser.startSec)}s`, filename: `${stem}-teaser.mp4`, window: teaser,+ args: ['-ss', String(teaser.startSec), '-t', String(teaser.endSec - teaser.startSec), '-i', masterPath, ...X_VIDEO_ARGS,+ '-af', `asetpts=PTS-STARTPTS${edgeFadeFilter(teaser.endSec - teaser.startSec)}`, ...AUDIO_ARGS] }] : []),+ ];+ const times = thumbnailTimes(project, durationSec);+ const total = encodes.length + times.length;+ const written = [];+ let done = 0;+ const step = () => broadcastSse(job, { type: 'progress', progress: Math.min(0.99, ++done / total) });+ for (const encode of encodes) {+ const out = join(PATHS.videos, encode.filename);+ const result = await runFfmpegProcess({ bin: ffmpeg, signal: job.abort.signal, args: ['-hide_banner', '-loglevel', 'error', ...encode.args, '-y', out] });+ if (!result.ok) throw new Error(`${encode.label} encode failed: ${result.reason || 'ffmpeg error'}`);+ written.push(encode.filename);+ step();+ }+ const thumbnails = [];+ for (const [i, t] of times.entries()) {+ const name = `${stem}-thumb-${i + 1}.jpg`;+ const result = await runFfmpegProcess({ bin: ffmpeg, signal: job.abort.signal, args: ['-hide_banner', '-loglevel', 'error', '-ss', String(t), '-i', masterPath, '-frames:v', '1', '-vf', 'scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2', '-q:v', '2', '-y', join(PATHS.videoThumbnails, name)] });+ if (result.ok) { thumbnails.push(name); written.push(name); }+ step();+ }+ const srt = buildSrt(project);+ const captionsFilename = srt ? `${stem}-captions.srt` : null;+ if (srt) { await writeFile(join(PATHS.videos, captionsFilename), srt); written.push(captionsFilename); }+ const previous = projectPublishKit(project);+ const staleFiles = [...(previous.exports || []).map((e) => e.filename), ...(previous.thumbnails || []), previous.captionsFilename].filter(Boolean);+ await mutateProjectRecord(projectId, (current) => {+ const kit = projectPublishKit(current);+ return { project: { ...current, publishKit: {+ ...kit,+ builtAt: new Date().toISOString(),+ master: { filename: entry.filename, renderHistoryId: current.renderHistoryId },+ exports: encodes.map(({ kind, label, filename, window }) => ({ kind, label, filename, ...(window ? { startSec: window.startSec, endSec: window.endSec } : {}) })),+ thumbnails,+ thumbnail: thumbnails.includes(kit.thumbnail) ? kit.thumbnail : (thumbnails[0] || null),+ captionsFilename,+ chapters: buildChapters(current),+ } } };+ });+ await releaseKitFiles(staleFiles, written);+ return written;+ };++ Promise.resolve().then(run).then(() => {+ job.status = 'complete';+ projectBuilds.delete(projectId);+ console.log(`✅ Music-video publishing kit built [${tag}]`);+ broadcastSse(job, { type: 'complete', result: { projectId } });+ closeJobAfterDelay(jobs, jobId);+ }).catch((err) => {+ const canceled = job.abort.signal.aborted;+ job.status = canceled ? 'canceled' : 'error';+ projectBuilds.delete(projectId);+ const log = canceled ? console.log : console.error;+ log(`${canceled ? '🛑' : '❌'} Music-video publishing kit ${canceled ? 'cancelled' : 'failed'} [${tag}]: ${err.message}`);+ broadcastSse(job, { type: canceled ? 'canceled' : 'error', error: canceled ? 'Publishing kit build cancelled' : err.message });+ closeJobAfterDelay(jobs, jobId);+ });+ return { jobId };+}++export function cancelPublishKitBuild(jobId) {+ const job = jobs.get(jobId);+ if (!job || job.status !== 'running') return false;+ job.abort.abort();+ return true;+}++/** Choose the thumbnail the release uses (one the build cut). */+export async function selectPublishKitThumbnail(projectId, filename) {+ await requireProject(projectId);+ return mutateProjectRecord(projectId, (current) => {+ const kit = projectPublishKit(current);+ if (!(kit.thumbnails || []).includes(filename)) throw kitError(422, 'VALIDATION_ERROR', 'That thumbnail is not one this kit built');+ return { project: { ...current, publishKit: { ...kit, thumbnail: filename } } };+ });+}++/** Merge edited copy fields per platform (only known platforms and string/array fields). */+export async function updatePublishKitCopy(projectId, patch) {+ await requireProject(projectId);+ return mutateProjectRecord(projectId, (current) => {+ const kit = projectPublishKit(current);+ const copy = { ...(kit.copy || {}) };+ for (const platform of PUBLISH_PLATFORMS) {+ if (patch?.[platform] && typeof patch[platform] === 'object') copy[platform] = { ...(copy[platform] || {}), ...patch[platform] };+ }+ const next = { ...kit, copy, copyEditedAt: new Date().toISOString() };+ if (typeof patch?.notes === 'string') next.notes = patch.notes;+ return { project: { ...current, publishKit: next } };+ });+}++/** Generation spend across the project's production runs (what the copy may claim). */+function spentUsd(project) {+ const total = (project.productionRuns || []).reduce((sum, run) => sum + (Number.isFinite(Number(run?.usage?.spentUsd)) ? Number(run.usage.spentUsd) : 0), 0);+ return total > 0 ? total : null;+}++/**+ * Draft every platform's copy in ONE provider call the director asked for.+ * `notes` (their making-of story) is saved with the kit so a redraft reuses it.+ */+export async function draftPublishKitCopy(projectId, { providerId = null, model = null, notes = '', links = {} } = {}, deps = {}) {+ const project = await requireProject(projectId);+ const { resolveProviderAndModel, runPromptThroughProvider } = deps.runner || await import('../promptRunner.js');+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });+ if (!provider) throw kitError(503, 'NO_PROVIDER', 'No AI provider is available to draft the copy');+ const prompt = buildPublishCopyPrompt(project, { notes, spentUsd: spentUsd(project), links });+ const { text } = await runPromptThroughProvider({ provider, model: selectedModel, prompt, source: 'music-video-publish-copy' });+ const copy = parsePublishCopy(text);+ if (!copy) throw kitError(502, 'PUBLISH_COPY_UNPARSEABLE', 'The copy draft came back without usable JSON — try again or another model');+ return mutateProjectRecord(projectId, (current) => {+ const kit = projectPublishKit(current);+ return { project: { ...current, publishKit: { ...kit, copy, notes, links: { ...(kit.links || {}), ...links }, copyDraftedAt: new Date().toISOString() } } };+ });+}diff --git a/server/services/musicVideo/publishKit.test.js b/server/services/musicVideo/publishKit.test.jsnew file mode 100644index 0000000000..4bd2aa0d48--- /dev/null+++ b/server/services/musicVideo/publishKit.test.js@@ -0,0 +1,103 @@+/**+ * Publishing kit build + copy (#9281), through the real project store and a+ * real ffmpeg: the build refuses without a final render, turns a finished+ * render into the platform encodes, thumbnails, captions and chapters on the+ * record, and a rebuild frees the files the previous kit made. The copy is+ * one provider call (injected here) whose JSON lands editable on the kit.+ */+import { describe, expect, it, vi, afterAll } from 'vitest';+import { existsSync } from 'node:fs';+import { mkdir, readFile, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';++vi.mock('../../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), {+ dataRoot: () => lazyTempDataRoot('portos-mv-publish-kit-'),+}));++const { PATHS } = await import('../../lib/paths.js');+const { findFfmpeg, runFfmpegProcess } = await import('../../lib/ffmpeg.js');+const projects = await import('./projects.js');+const { saveHistory } = await import('../videoGen/history.js');+const kit = await import('./publishKit.js');+const ffmpeg = await findFfmpeg();++afterAll(() => cleanupTempDataRoots());++const cue = (text, startSec, endSec) => ({ id: `lc-${startSec}`, text, startSec, endSec });+const scene = (startSec, endSec, sectionLabel, shotMode = 'performance') => ({ sceneId: `mvs-${startSec}`, order: startSec, startSec, endSec, sectionLabel, shotMode, takes: [] });++async function renderedProject() {+ const created = await projects.createProject({ name: 'Example Song' });+ await mkdir(PATHS.videos, { recursive: true });+ const filename = `master-${created.id.slice(3, 11)}.mp4`;+ const made = await runFfmpegProcess({ bin: ffmpeg, args: ['-hide_banner', '-loglevel', 'error',+ '-f', 'lavfi', '-i', 'testsrc2=s=320x180:r=24:d=36', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=36',+ '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-shortest', '-y', join(PATHS.videos, filename)] });+ expect(made.ok).toBe(true);+ await saveHistory([{ id: 'render-1', filename, durationSec: 36 }]);+ await projects.mutateProjectRecord(created.id, (current) => ({ project: {+ ...current,+ renderHistoryId: 'render-1',+ audioAnalysis: { durationSec: 36 },+ scenes: [scene(0, 12, 'Verse 1'), scene(12, 24, 'Chorus 1'), scene(24, 36, 'Outro', 'cutaway')],+ lyricCues: [cue('first verse line', 1, 4), cue('the chorus line', 13, 16), cue('last words', 25, 28)],+ } }));+ return created.id;+}++describe('publishing kit build (#9281)', () => {+ it('refuses to build before there is a final render', async () => {+ const { id } = await projects.createProject({ name: 'Unrendered' });+ await expect(kit.startPublishKitBuild(id)).rejects.toMatchObject({ status: 409, code: 'NO_FINAL_RENDER' });+ });++ it.skipIf(!ffmpeg)('turns the final render into encodes, thumbnails, captions and chapters, and frees a rebuilt kit\'s old files', { timeout: 120000 }, async () => {+ const id = await renderedProject();+ await kit.startPublishKitBuild(id);+ await vi.waitFor(async () => expect((await projects.getProject(id)).publishKit?.builtAt).toBeTruthy(), { timeout: 90000, interval: 250 });+ const first = (await projects.getProject(id)).publishKit;+ expect(first.exports.map((e) => e.kind)).toEqual(['x-1080p', 'preview-720p', 'teaser']);+ for (const e of first.exports) expect(existsSync(join(PATHS.videos, e.filename))).toBe(true);+ expect(first.thumbnails).toHaveLength(2); // the two performance shots+ expect(first.thumbnail).toBe(first.thumbnails[0]);+ expect(await readFile(join(PATHS.videos, first.captionsFilename), 'utf8')).toContain('the chorus line');+ expect(first.chapters.map((c) => c.label)).toEqual(['first verse line', 'the chorus line', 'last words']);++ await expect(kit.startPublishKitBuild(id).then(() => kit.startPublishKitBuild(id))).rejects.toMatchObject({ code: 'PUBLISH_KIT_BUILD_IN_PROGRESS' });+ await vi.waitFor(async () => expect((await projects.getProject(id)).publishKit.builtAt).not.toBe(first.builtAt), { timeout: 90000, interval: 250 });+ await vi.waitFor(() => expect(existsSync(join(PATHS.videos, first.exports[0].filename))).toBe(false));+ });+});++describe('publishing kit copy (#9281)', () => {+ const runner = (text) => ({+ resolveProviderAndModel: vi.fn(async () => ({ provider: { id: 'p1' }, selectedModel: 'm1' })),+ runPromptThroughProvider: vi.fn(async () => ({ text })),+ });++ it('drafts every platform from one call and keeps each field editable', async () => {+ const { id } = await projects.createProject({ name: 'Example Song' });+ const deps = { runner: runner(JSON.stringify({ youtube: { title: 'A title', description: 'desc', tags: ['music'] }, x: { hook: 'a hook', story: 'story' } })) };+ const { project } = await kit.draftPublishKitCopy(id, { notes: 'made it on a Sunday', links: { youtube: 'https://example.com/v' } }, deps);+ expect(deps.runner.runPromptThroughProvider).toHaveBeenCalledTimes(1);+ expect(deps.runner.runPromptThroughProvider.mock.calls[0][0]).toMatchObject({ source: 'music-video-publish-copy' });+ expect(project.publishKit).toMatchObject({ notes: 'made it on a Sunday', links: { youtube: 'https://example.com/v' }, copy: { youtube: { title: 'A title' }, x: { hook: 'a hook' } } });+ const edited = await kit.updatePublishKitCopy(id, { x: { hook: 'my own hook' } });+ expect(edited.project.publishKit.copy.x).toEqual({ hook: 'my own hook', story: 'story' });+ expect(edited.project.publishKit.copy.youtube.title).toBe('A title');+ });++ it('reports an unusable draft instead of saving it', async () => {+ const { id } = await projects.createProject({ name: 'Example Song' });+ await expect(kit.draftPublishKitCopy(id, {}, { runner: runner('sorry, no JSON') })).rejects.toMatchObject({ status: 502, code: 'PUBLISH_COPY_UNPARSEABLE' });+ expect((await projects.getProject(id)).publishKit).toBeFalsy();+ });++ it('only selects a thumbnail the kit built', async () => {+ const { id } = await projects.createProject({ name: 'Example Song' });+ await projects.mutateProjectRecord(id, (current) => ({ project: { ...current, publishKit: { thumbnails: ['a.jpg', 'b.jpg'], thumbnail: 'a.jpg' } } }));+ expect((await kit.selectPublishKitThumbnail(id, 'b.jpg')).project.publishKit.thumbnail).toBe('b.jpg');+ await expect(kit.selectPublishKitThumbnail(id, 'elsewhere.jpg')).rejects.toMatchObject({ status: 422 });+ });+});diff --git a/server/services/musicVideo/publishKitText.js b/server/services/musicVideo/publishKitText.jsnew file mode 100644index 0000000000..1f7b7f667b--- /dev/null+++ b/server/services/musicVideo/publishKitText.js@@ -0,0 +1,168 @@+/**+ * Music Video — publishing kit text (#9281): YouTube chapters, an SRT of the+ * timed lyrics, and the per-platform copy prompt + parser. Pure: project in,+ * text out, so the kit build and the copy draft share one tested shape.+ */+import { extractJson } from '../../lib/jsonExtract.js';+import { fenceBlock } from '../../lib/promptFencing.js';++const finite = (n) => (typeof n === 'number' && Number.isFinite(n) ? n : null);+const round3 = (n) => Math.round(n * 1000) / 1000;++// YouTube only turns a description's timestamps into chapters when the first+// is 0:00, there are at least three, and each runs at least 10 seconds.+export const MIN_CHAPTER_SEC = 10;+const MIN_CHAPTERS = 3;+const MAX_LABEL = 45;++function timedLines(project) {+ return (project?.lyricCues || [])+ .filter((c) => c && typeof c.text === 'string' && c.text.trim() && finite(c.startSec) != null)+ .map((c) => ({ text: c.text.trim(), startSec: c.startSec, endSec: finite(c.endSec) }))+ .sort((a, b) => a.startSec - b.startSec);+}++/** A lyric line as a chapter title: no closing punctuation or quotes, cut at a word. */+function chapterLabel(text) {+ // Double quotes go; an apostrophe inside a word (I’m) stays, only wrapping single quotes are trimmed.+ let s = String(text || '').replace(/["“”]/g, '').replace(/\s+/g, ' ').trim().replace(/^['‘’]+|['‘’]+$/g, '').replace(/[.,!?;:]+$/, '');+ if (s.length > MAX_LABEL) s = `${s.slice(0, MAX_LABEL).replace(/\s+\S*$/, '')}…`;+ return s;+}++/** Song sections as the board names them (consecutive scenes sharing a section label), else the analysis sections. */+function sectionRuns(project) {+ const scenes = (project?.scenes || [])+ .filter((s) => finite(s?.startSec) != null && finite(s?.endSec) != null && s.endSec > s.startSec)+ .sort((a, b) => a.startSec - b.startSec);+ const runs = [];+ for (const scene of scenes) {+ const section = typeof scene.sectionLabel === 'string' && scene.sectionLabel.trim() ? scene.sectionLabel.trim() : null;+ const last = runs[runs.length - 1];+ if (last && last.section === section) last.endSec = Math.max(last.endSec, scene.endSec);+ else runs.push({ section, startSec: scene.startSec, endSec: scene.endSec });+ }+ if (runs.length) return runs;+ return (project?.audioAnalysis?.sections || [])+ .filter((s) => finite(s?.startSec) != null && finite(s?.endSec) != null && s.endSec > s.startSec)+ .map((s) => ({ section: typeof s.label === 'string' ? s.label : null, startSec: s.startSec, endSec: s.endSec }));+}++/**+ * `[{ startSec, label }]` YouTube chapters: each section titled by its first+ * sung line (else its section name), sections shorter than 10 s folded into+ * the one before (a short opener folds forward), the first forced to 0:00.+ * Empty when the song can't make the three chapters YouTube requires.+ */+export function buildChapters(project) {+ const lines = timedLines(project);+ const runs = sectionRuns(project).map((run, i) => {+ const line = lines.find((l) => l.startSec >= run.startSec - 1e-6 && l.startSec < run.endSec);+ return { ...run, label: chapterLabel(line?.text) || run.section || `Part ${i + 1}` };+ });+ const merged = [];+ for (const run of runs) {+ const last = merged[merged.length - 1];+ if (last && run.endSec - run.startSec < MIN_CHAPTER_SEC) last.endSec = run.endSec;+ else if (last && last.label === run.label) last.endSec = run.endSec;+ else merged.push({ ...run });+ }+ if (merged.length > 1 && merged[0].endSec - merged[0].startSec < MIN_CHAPTER_SEC) {+ merged[1].startSec = merged[0].startSec;+ merged.shift();+ }+ if (merged.length < MIN_CHAPTERS) return [];+ merged[0].startSec = 0;+ return merged.map(({ startSec, label }) => ({ startSec: round3(startSec), label }));+}++function formatChapterTime(sec) {+ const s = Math.max(0, Math.floor(sec));+ const h = Math.floor(s / 3600);+ const m = Math.floor((s % 3600) / 60);+ const r = String(s % 60).padStart(2, '0');+ return h ? `${h}:${String(m).padStart(2, '0')}:${r}` : `${m}:${r}`;+}++export const chaptersText = (chapters) => chapters.map((c) => `${formatChapterTime(c.startSec)} ${c.label}`).join('\n');++const srtTime = (sec) => {+ const ms = Math.max(0, Math.round(sec * 1000));+ const pad = (n, w = 2) => String(n).padStart(w, '0');+ return `${pad(Math.floor(ms / 3600000))}:${pad(Math.floor(ms / 60000) % 60)}:${pad(Math.floor(ms / 1000) % 60)},${pad(ms % 1000, 3)}`;+};++// A cue stays up long enough to read, but never over the next line.+const MIN_CUE_SEC = 0.9;+const CUE_GAP_SEC = 0.02;++/** The timed lyrics as SubRip captions, or null when nothing is timed. */+export function buildSrt(project) {+ const lines = timedLines(project);+ if (!lines.length) return null;+ const cues = lines.map((line, i) => {+ const next = lines[i + 1];+ let end = Math.max(line.endSec ?? line.startSec + 2, line.startSec + MIN_CUE_SEC);+ if (next && next.startSec > line.startSec + 0.3) end = Math.min(end, next.startSec - CUE_GAP_SEC);+ return { ...line, endSec: Math.max(end, line.startSec + 0.3) };+ });+ return `${cues.map((c, i) => `${i + 1}\n${srtTime(c.startSec)} --> ${srtTime(c.endSec)}\n${c.text}\n`).join('\n')}`;+}++// ---- per-platform copy (one user-triggered LLM call) ----++export const PUBLISH_PLATFORMS = Object.freeze(['youtube', 'shorts', 'x', 'tiktok', 'instagram', 'reddit', 'stackerNews']);+// 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 str = (v, max) => (typeof v === 'string' && v.trim() ? v.trim().slice(0, max) : '');++/**+ * The copy prompt. `notes` is the director's own making-of story and+ * `spentUsd` the generation spend; both are the facts the copy may claim —+ * nothing else about cost or process is invented.+ */+export function buildPublishCopyPrompt(project, { notes = '', spentUsd = null, links = {} } = {}) {+ const lyrics = timedLines(project).map((l) => l.text).join('\n');+ const chapters = chaptersText(buildChapters(project));+ const facts = [+ `Song title: ${project?.name || 'Untitled'}`,+ spentUsd != null ? `Video generation spend: $${Number(spentUsd).toFixed(2)}` : null,+ links.youtube ? `Full video URL: ${links.youtube}` : null,+ links.song ? `Song URL: ${links.song}` : null,+ ].filter(Boolean).join('\n');+ return [+ 'You write release copy for a music video the user made. Write in the first person as the artist: plain, specific, no hype words, no emoji, no hashtags except where a field asks for them.',+ 'Use ONLY facts given below. Never invent costs, tools, durations or events.',+ facts,+ fenceBlock('Making-of notes from the artist', notes || '(none)', 6000),+ fenceBlock('Lyrics', lyrics || '(no timed lyrics)', 4000),+ chapters ? fenceBlock('Chapters', chapters, 1200) : '',+ 'Return ONLY a JSON object with exactly these keys:',+ '{"youtube":{"title":"<=100 chars","description":"2 short paragraphs + the links given","tags":["8-15 lowercase tags"]},',+ ' "shorts":{"title":"<=100 chars, ends with #shorts","description":"1-2 sentences + the full video URL if given"},',+ ' "x":{"hook":"<=280 chars, one surprising claim, no links","story":"the making-of as a long post"},',+ ' "tiktok":{"caption":"1-2 sentences + 4-6 hashtags"},',+ ' "instagram":{"caption":"1-2 sentences + 4-6 hashtags"},',+ ' "reddit":{"title":"<=300 chars","body":"markdown: what it is, what it cost, how it was made"},',+ ' "stackerNews":{"title":"<=80 chars","body":"markdown, personal tone"}}',+ ].filter(Boolean).join('\n\n');+}++/** The model's JSON reply as `{ platform: { field: text } }`, clipped to each platform's limits; null when unusable. */+export function parsePublishCopy(text) {+ const { value } = extractJson(text, { blockType: 'object' });+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ const v = (k) => (value[k] && typeof value[k] === 'object' ? value[k] : {});+ const copy = {+ youtube: { title: str(v('youtube').title, LIMITS.youtubeTitle), description: str(v('youtube').description, 5000), tags: (Array.isArray(v('youtube').tags) ? v('youtube').tags : []).map((t) => str(t, 60)).filter(Boolean).slice(0, 20) },+ shorts: { title: str(v('shorts').title, LIMITS.shortsTitle), description: str(v('shorts').description, 5000) },+ x: { hook: str(v('x').hook, LIMITS.xHook), story: str(v('x').story, 25000) },+ tiktok: { caption: str(v('tiktok').caption, LIMITS.caption) },+ instagram: { caption: str(v('instagram').caption, LIMITS.caption) },+ reddit: { title: str(v('reddit').title, LIMITS.redditTitle), body: str(v('reddit').body, 40000) },+ stackerNews: { title: str(v('stackerNews').title, LIMITS.stackerNewsTitle), body: str(v('stackerNews').body, 40000) },+ };+ const filled = Object.values(copy).some((fields) => Object.values(fields).some((f) => (Array.isArray(f) ? f.length : f)));+ return filled ? copy : null;+}diff --git a/server/services/musicVideo/publishKitText.test.js b/server/services/musicVideo/publishKitText.test.jsnew file mode 100644index 0000000000..f7ceeaa3d7--- /dev/null+++ b/server/services/musicVideo/publishKitText.test.js@@ -0,0 +1,63 @@+/**+ * Publishing kit text (#9281): YouTube chapters obey YouTube's own rules+ * (0:00 first, >= 10 s each, >= 3 or none), captions never overlap and stay up+ * long enough to read, and the copy parser clips to each platform's limits.+ */+import { describe, expect, it } from 'vitest';+import { buildChapters, chaptersText, buildSrt, buildPublishCopyPrompt, parsePublishCopy } from './publishKitText.js';++const scene = (startSec, endSec, sectionLabel) => ({ sceneId: `s${startSec}`, startSec, endSec, sectionLabel });+const cue = (text, startSec, endSec) => ({ id: `c${startSec}`, text, startSec, endSec });++const project = {+ name: 'Example Song',+ scenes: [+ scene(0, 1.5, 'Intro'), scene(1.5, 20, 'Verse 1'), scene(20, 29, 'Verse 1'),+ scene(29, 40, 'Pre-Chorus'), scene(40, 43, 'Stop'), scene(43, 72, 'Chorus 1'), scene(72, 90, 'Outro'),+ ],+ lyricCues: [cue('I’m walking in the lab.', 1.9, 5), cue('One more layer', 32, 34), cue('"Hold the line!"', 44, 46)],+};++describe('buildChapters (#9281)', () => {+ it('titles sections by their first sung line, folds short ones, and starts at 0:00', () => {+ const chapters = buildChapters(project);+ expect(chapters.map((c) => c.startSec)).toEqual([0, 29, 43, 72]);+ expect(chapters.map((c) => c.label)).toEqual(['I’m walking in the lab', 'One more layer', 'Hold the line', 'Outro']);+ expect(chaptersText(chapters)).toBe('0:00 I’m walking in the lab\n0:29 One more layer\n0:43 Hold the line\n1:12 Outro');+ });++ it('offers no chapters when the song cannot make three of at least 10 s', () => {+ expect(buildChapters({ scenes: [scene(0, 12, 'A'), scene(12, 25, 'B')] })).toEqual([]);+ expect(buildChapters({})).toEqual([]);+ });+});++describe('buildSrt (#9281)', () => {+ it('keeps each cue on screen long enough to read without overlapping the next', () => {+ const srt = buildSrt({ lyricCues: [cue('one', 1, 1.2), cue('two', 1.5, 4), cue('three', 3.9, 5)] });+ expect(srt).toBe('1\n00:00:01,000 --> 00:00:01,480\none\n\n2\n00:00:01,500 --> 00:00:03,880\ntwo\n\n3\n00:00:03,900 --> 00:00:05,000\nthree\n');+ expect(buildSrt({})).toBeNull();+ });+});++describe('publish copy prompt + parser (#9281)', () => {+ it('states only the facts it was given', () => {+ const withSpend = buildPublishCopyPrompt(project, { notes: 'hummed it in the car', spentUsd: 37.876, links: { youtube: 'https://example.com/v' } });+ expect(withSpend).toContain('Video generation spend: $37.88');+ expect(withSpend).toContain('Full video URL: https://example.com/v');+ expect(withSpend).toContain('hummed it in the car');+ expect(buildPublishCopyPrompt(project, {})).not.toContain('spend:');+ });++ it('clips each field to its platform limit and rejects an empty or non-JSON reply', () => {+ const reply = `\`\`\`json\n${JSON.stringify({ youtube: { title: 'T'.repeat(150), tags: ['a', 'b'] }, x: { hook: 'H'.repeat(400), story: 'long' }, stackerNews: { title: 'S'.repeat(120) } })}\n\`\`\``;+ const copy = parsePublishCopy(reply);+ expect(copy.youtube.title).toHaveLength(100);+ expect(copy.youtube.tags).toEqual(['a', 'b']);+ expect(copy.x.hook).toHaveLength(280);+ expect(copy.stackerNews.title).toHaveLength(80);+ expect(copy.reddit).toEqual({ title: '', body: '' });+ expect(parsePublishCopy('no json here')).toBeNull();+ expect(parsePublishCopy('{"youtube":{}}')).toBeNull();+ });+});