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): vertical and square social cuts with hook suggestions
[._.]/ Adam Eivyf6d5ea112b9b
diff --git a/client/src/components/musicVideo/ExcerptPanel.jsx b/client/src/components/musicVideo/ExcerptPanel.jsxindex 5afb661761..a298afdc35 100644--- a/client/src/components/musicVideo/ExcerptPanel.jsx+++ b/client/src/components/musicVideo/ExcerptPanel.jsx@@ -1,5 +1,7 @@import { useRef, useState } from 'react';-import { Film, Flag, CheckCircle2, Trash2, X, Clapperboard, RotateCcw } from 'lucide-react';+import { Film, Flag, CheckCircle2, Trash2, X, Clapperboard, RotateCcw, Smartphone, Sparkles } from 'lucide-react';+import { musicVideoAspect, MUSIC_VIDEO_ASPECTS } from '../../lib/musicVideoAspect.js';+import { getMusicVideoSocialCuts } from '../../services/apiMusicVideo.js';import RevisionPanel, { currentRevision } from './RevisionPanel.jsx';import AutoReviewPanel from './AutoReviewPanel.jsx';@@ -9,6 +11,14 @@ const VERDICT_STYLES = {};const STATUS_LABELS = { rendering: 'Rendering…', complete: 'Ready', error: 'Failed', canceled: 'Cancelled' };+// The player frame for an excerpt's own aspect (#9280): a vertical social cut+// plays tall and narrow instead of pillarboxed in a 16:9 box.+const PLAYER_FRAME = {+ '9:16': 'aspect-[9/16] max-h-[60vh] mx-auto',+ '1:1': 'aspect-square max-h-[50vh] mx-auto',+};+const ASPECT_LABELS = { '16:9': '16:9 (YouTube)', '9:16': '9:16 (Shorts, TikTok, Reels)', '1:1': '1:1 (square)' };+const fmt = (sec) => {const s = Math.max(0, Math.round(sec * 10) / 10);const m = Math.floor(s / 60);@@ -77,7 +87,8 @@ function ExcerptCard({ excerpt, deleting, noteBusy, onDelete, onCancel, onAddNotreturn (<li className="rounded border border-port-border p-2 space-y-2"><div className="flex flex-wrap items-center justify-between gap-2 text-xs">- <span className="font-medium">{fmt(excerpt.startSec)} – {fmt(excerpt.endSec)} <span className="text-port-text-muted">({STATUS_LABELS[excerpt.status] || excerpt.status})</span></span>+ <span className="font-medium">{fmt(excerpt.startSec)} – {fmt(excerpt.endSec)} <span className="text-port-text-muted">({STATUS_LABELS[excerpt.status] || excerpt.status})</span>+ {excerpt.aspect && excerpt.aspect !== '16:9' && <span className="ml-1.5 px-1.5 py-0.5 rounded bg-port-accent/20 text-port-accent text-[10px]">{excerpt.aspect}</span>}</span><div className="flex items-center gap-2">{/* #8987: regenerate ONLY the sections holding a flagged note; the rest stay as approved. */}{excerpt.status === 'complete' && excerpt.sections?.length > 0 && excerpt.notes?.some((n) => n.verdict === 'flagged') && (@@ -94,7 +105,7 @@ function ExcerptCard({ excerpt, deleting, noteBusy, onDelete, onCancel, onAddNot{excerpt.status === 'complete' && excerpt.filename && (<div className="space-y-2"><video ref={videoRef} src={`/data/videos/${excerpt.filename}`} controls playsInline preload="metadata"- className="w-full aspect-video max-h-[45vh] object-contain rounded bg-black border border-port-border"+ className={`w-full ${PLAYER_FRAME[excerpt.aspect] || 'aspect-video max-h-[45vh]'} object-contain rounded bg-black border border-port-border`}aria-label={`Play excerpt ${fmt(excerpt.startSec)} to ${fmt(excerpt.endSec)}`} />{excerpt.contactSheetFilename && (<details className="text-xs">@@ -141,8 +152,24 @@ export default function ExcerptPanel({ project, rendering, progress, excerpts, rconst durationSec = project?.audioAnalysis?.durationSec ?? null;const [startSec, setStartSec] = useState(0);const [endSec, setEndSec] = useState(durationSec ? Math.min(15, durationSec) : 15);+ const projectAspect = musicVideoAspect(project);+ const [aspect, setAspect] = useState(projectAspect);+ const [fade, setFade] = useState(false);+ const [suggestions, setSuggestions] = useState(null);+ const [suggesting, setSuggesting] = useState(false);const idFor = (s) => `mv-excerpt-${project?.id}-${s}`;const valid = Number.isFinite(startSec) && Number.isFinite(endSec) && endSec > startSec;+ // A social cut (another frame, faded edges) needs a composition that lays+ // itself out per frame; a footage render only cuts at its own aspect.+ const canReframe = ['document', 'code'].includes(project?.composition?.mode);+ const render = (s, e, opts) => actions.startExcerpt(s, e, opts);+ const suggestHooks = () => {+ setSuggesting(true);+ getMusicVideoSocialCuts(project.id, { count: 3 }, { silent: true })+ .then((res) => setSuggestions(res?.suggestions || []))+ .catch(() => setSuggestions([]))+ .finally(() => setSuggesting(false));+ };return (<div className="space-y-2">@@ -160,12 +187,54 @@ export default function ExcerptPanel({ project, rendering, progress, excerpts, ronChange={(e) => setEndSec(Number(e.target.value))}className="w-24 bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs min-h-[44px] sm:min-h-0" /></div>+ {canReframe && (+ <div>+ <label htmlFor={idFor('aspect')} className="block text-[10px] text-port-text-muted">Frame</label>+ <select id={idFor('aspect')} value={aspect} onChange={(e) => setAspect(e.target.value)}+ className="bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs min-h-[44px] sm:min-h-0">+ {MUSIC_VIDEO_ASPECTS.map((a) => <option key={a} value={a}>{ASPECT_LABELS[a] || a}</option>)}+ </select>+ </div>+ )}+ {canReframe && (+ <label htmlFor={idFor('fade')} className="flex items-center gap-1 text-xs text-port-text-muted min-h-[44px] sm:min-h-0">+ <input id={idFor('fade')} type="checkbox" checked={fade} onChange={(e) => setFade(e.target.checked)} />+ Fade audio edges+ </label>+ )}<button type="button" disabled={rendering || !valid}- onClick={() => actions.startExcerpt(startSec, endSec)}+ onClick={() => render(startSec, endSec, canReframe ? { aspect: aspect === projectAspect ? null : aspect, fade } : undefined)}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"><Film size={13} /> Render excerpt</button></div>+ {canReframe && (+ <div className="rounded border border-port-border p-2 space-y-1.5">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <span className="text-xs text-port-text-muted flex items-center gap-1"><Smartphone size={12} /> Social cuts: vertical hooks for Shorts, TikTok and Reels</span>+ <button type="button" onClick={suggestHooks} disabled={suggesting}+ className="flex items-center gap-1 text-port-accent disabled:opacity-50 text-xs min-h-[44px] sm:min-h-0">+ <Sparkles size={12} /> {suggesting ? 'Finding hooks…' : 'Suggest hooks'}+ </button>+ </div>+ {suggestions && suggestions.length === 0 && <p className="text-xs text-port-text-muted">No hook windows found. Time the lyrics first.</p>}+ {suggestions && suggestions.length > 0 && (+ <ul className="space-y-1">+ {suggestions.map((s) => (+ <li key={`${s.startSec}-${s.endSec}`} className="flex flex-wrap items-center gap-2 text-xs">+ <span className="font-mono shrink-0">{fmt(s.startSec)} – {fmt(s.endSec)}</span>+ <span className="min-w-0 flex-1 break-words">{s.label ? `“${s.label}”` : ''} <span className="text-port-text-muted">{s.reasons.join(' · ')}</span></span>+ <button type="button" onClick={() => { setStartSec(s.startSec); setEndSec(s.endSec); }}+ className="text-port-text-muted min-h-[44px] sm:min-h-0 px-1">Use range</button>+ <button type="button" disabled={rendering}+ onClick={() => { setStartSec(s.startSec); setEndSec(s.endSec); render(s.startSec, s.endSec, { aspect: projectAspect === '9:16' ? null : '9:16', fade: true }); }}+ className="text-port-accent disabled:opacity-50 min-h-[44px] sm:min-h-0 px-1">Render 9:16</button>+ </li>+ ))}+ </ul>+ )}+ </div>+ )}{rendering && (<div><div className="h-1.5 bg-port-bg rounded overflow-hidden">diff --git a/client/src/components/musicVideo/ExcerptPanel.test.jsx b/client/src/components/musicVideo/ExcerptPanel.test.jsxnew file mode 100644index 0000000000..1325dbf8ba--- /dev/null+++ b/client/src/components/musicVideo/ExcerptPanel.test.jsx@@ -0,0 +1,49 @@+/**+ * Social cuts in the excerpt panel (#9280): a composition-document project can+ * render an excerpt at another frame with faded edges, and a suggested hook+ * renders as a vertical cut in one click. A footage project keeps the plain+ * range-only control (it has no frame of its own to re-lay-out).+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';++vi.mock('../../services/apiMusicVideo.js', () => ({ getMusicVideoSocialCuts: vi.fn() }));++import { getMusicVideoSocialCuts } from '../../services/apiMusicVideo.js';+import ExcerptPanel from './ExcerptPanel.jsx';++const documentProject = { id: 'mv-1', name: 'Example Song', composition: { mode: 'document' }, audioAnalysis: { durationSec: 90 } };++function renderPanel(project, startExcerpt = vi.fn()) {+ render(<ExcerptPanel project={project} rendering={false} progress={0} excerpts={[]} startExcerpt={startExcerpt} />);+ return startExcerpt;+}++beforeEach(() => vi.clearAllMocks());++describe('ExcerptPanel social cuts (#9280)', () => {+ it('renders the chosen range at another frame with faded audio edges', () => {+ const start = renderPanel(documentProject);+ fireEvent.change(screen.getByLabelText('Frame'), { target: { value: '9:16' } });+ fireEvent.click(screen.getByLabelText('Fade audio edges'));+ fireEvent.click(screen.getByRole('button', { name: /Render excerpt/ }));+ expect(start).toHaveBeenCalledWith(0, 15, { aspect: '9:16', fade: true });+ });++ it('renders a suggested hook as a vertical faded cut', async () => {+ getMusicVideoSocialCuts.mockResolvedValue({ suggestions: [{ startSec: 43.5, endSec: 62.4, score: 0.8, label: 'the chorus line', reasons: ['chorus', 'sings the title'] }] });+ const start = renderPanel(documentProject);+ fireEvent.click(screen.getByRole('button', { name: /Suggest hooks/ }));+ await waitFor(() => expect(screen.getByText(/the chorus line/)).toBeTruthy());+ fireEvent.click(screen.getByRole('button', { name: 'Render 9:16' }));+ expect(start).toHaveBeenCalledWith(43.5, 62.4, { aspect: '9:16', fade: true });+ });++ it('keeps a footage project to its own frame', () => {+ const start = renderPanel({ ...documentProject, composition: { mode: 'concat' } });+ expect(screen.queryByLabelText('Frame')).toBeNull();+ expect(screen.queryByRole('button', { name: /Suggest hooks/ })).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: /Render excerpt/ }));+ expect(start).toHaveBeenCalledWith(0, 15, undefined);+ });+});diff --git a/client/src/hooks/useMusicVideoExcerpts.js b/client/src/hooks/useMusicVideoExcerpts.jsindex fed4392b50..45c80358ac 100644--- a/client/src/hooks/useMusicVideoExcerpts.js+++ b/client/src/hooks/useMusicVideoExcerpts.js@@ -44,7 +44,7 @@ export default function useMusicVideoExcerpts({ project, replaceProject } = {})};const job = useSseJobSlot({- startRequest: ({ startSec, endSec }) => renderMusicVideoExcerpt(projectId, { startSec, endSec }, { silent: true }),+ startRequest: (body) => renderMusicVideoExcerpt(projectId, body, { silent: true }),eventsUrl: musicVideoExcerptRenderEventsUrl,cancelRequest: cancelMusicVideoExcerptRender,readPercent,@@ -61,7 +61,10 @@ export default function useMusicVideoExcerpts({ project, replaceProject } = {})startErrorFallback: 'Failed to start the excerpt render',});- const startExcerpt = (startSec, endSec) => job.start({ startSec, endSec }, projectId);+ // #9280: a social cut passes its own frame (`aspect`) and faded audio edges.+ const startExcerpt = (startSec, endSec, { aspect = null, fade = false } = {}) => job.start({+ startSec, endSec, ...(aspect ? { aspect } : {}), ...(fade ? { fade: true } : {}),+ }, projectId);// #8987: a selective revision's resume starts its draft re-render server-side;// adopt that job so it shows the same progress and reloads on its finish.const attachRender = (jobId, id = projectId) => job.attach(jobId, id);diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 0b37589c1b..ff8aa3a65b 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -182,6 +182,16 @@ export const cancelMusicVideoRender = (jobId, options = {}) =>export const renderMusicVideoExcerpt = (id, body, options = {}) => request(`/music-video/${encodeURIComponent(id)}/excerpt`, {method: 'POST', body: JSON.stringify(body), ...options,});+// #9280: the song windows most likely to work as a vertical social cut —+// { suggestions: [{ startSec, endSec, score, label, reasons }] }.+export const getMusicVideoSocialCuts = (id, { count, minSec, maxSec } = {}, options = {}) => {+ const params = new URLSearchParams();+ if (count != null) params.set('count', String(count));+ if (minSec != null) params.set('minSec', String(minSec));+ if (maxSec != null) params.set('maxSec', String(maxSec));+ const qs = params.toString();+ return request(`/music-video/${encodeURIComponent(id)}/social-cuts${qs ? `?${qs}` : ''}`, options);+};export const musicVideoExcerptRenderEventsUrl = (jobId) =>`/api/music-video/excerpt/${encodeURIComponent(jobId)}/events`;export const cancelMusicVideoExcerptRender = (jobId, options = {}) =>diff --git a/docs/HTML_COMPOSITIONS.md b/docs/HTML_COMPOSITIONS.mdindex 09050c6968..fc1f8ac96f 100644--- a/docs/HTML_COMPOSITIONS.md+++ b/docs/HTML_COMPOSITIONS.md@@ -266,7 +266,24 @@ snapped to the frame grid). The picture is captured silent and the master song(plus the optional sound-design bed) is muxed under it. The project's aspectratio picks the frame; a page authored at another aspect must list that sizein `portosComposition.formats` (its `layout({ width, height })` hook-reframes). A `seek(t)` that rejects — for example a `<video>` that failed to+reframes).++**Social cuts (#9280).** A draft excerpt can render at another frame than the+project's: `POST /api/music-video/:id/excerpt` takes `aspect` (`16:9`, `9:16`,+`1:1`) and `fade` (fade-in 0.08 s and fade-out 0.6 s on the excerpt's audio).+The render re-frames the project for that one job, so `PORTOS_MV.render` and+`PORTOS_MV.project.aspect` report the cut's frame, and the page must declare+that size in `formats` (or read its size from `PORTOS_MV.render`). The stored+project keeps its own aspect, and the excerpt records `aspect`, `fade`, `width`+and `height`. Footage (ffmpeg) projects refuse a re-framed cut+(`EXCERPT_ASPECT_UNSUPPORTED`), because cropping their 16:9 frame slices+through the type layers. `GET /api/music-video/:id/social-cuts?count=&minSec=&maxSec=`+suggests hook windows: sung lines, lip-sync coverage, chorus sections,+loudness and the title lyric, returned as non-overlapping `{ startSec, endSec,+score, label, reasons }`. The Review stage lists them with a one-click+"Render 9:16".++A `seek(t)` that rejects — for example a `<video>` that failed toseek — fails the render and names the frame. A page that draws `<video>`frames must await `seeked` before painting; the template seeks to the middleof the source frame so a frame boundary can never round to the previous one.diff --git a/server/lib/README.md b/server/lib/README.mdindex 795e2fc62a..b5501dca1b 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -406,7 +406,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `httpDrain.js` | `createHttpDrain(servers)` tracks every ordinary request the HTTP listeners accept; `begin(windowMs)` is the synchronous shutdown step that stops intake on all of them (`server.close()` plus a 503 `Connection: close` gate for requests arriving on still-open keep-alive sockets), turns off keep-alive on in-flight responses, drops open SSE streams, and resolves `{ remaining }` once accepted requests finish or the window ends (#8323). || `httpCompression.js` | `httpCompression` negotiates Brotli/gzip for API and static responses while preserving streaming, ranges, existing encodings, and `no-transform`. || `execGit.js` | `execGit(args, cwd, options)` and `execGitSafe(args, cwd, options)` shared process boundary for Git operations, worktrees, and `services/forgeAuth.js` credential resolution. The safe variant converts rejections into `{ exitCode: 1, stdout: '', stderr }`; `services/git.js` re-exports both for compatibility. `cwd` is REQUIRED — it rejects on a missing/blank one rather than letting `spawn` fall back to `process.cwd()` and run git against PortOS's own checkout (#4554). |-| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). `probeVideoGeometry(videoPath)` measures a finished clip's `{ width, height, fps, numFrames, durationSec }` (null when any axis is unreadable) for hosted renders that record no frame count. `generateThumbnail(videoPath, jobId, { atSec } = {})` accepts a clamped poster seek while preserving the single-clip default. Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. `installEncodedVideo(tmpPath, targetPath, label)` is the shared in-place install: move the original aside to a `.bak` on Windows (where `fs.rename` refuses an existing destination), rename the new file over it, and restore the backup — plus unlink the temp — on any failure, returning `{ok:true,outPath}` / `{ok:false,reason}` so the worst case is "skipped", never "the video is gone". Use it for EVERY replace-a-video-with-its-re-encode path; `pipeline/audioMux.js` is the out-of-module caller. |+| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). `probeVideoGeometry(videoPath)` measures a finished clip's `{ width, height, fps, numFrames, durationSec }` (null when any axis is unreadable) for hosted renders that record no frame count. `generateThumbnail(videoPath, jobId, { atSec } = {})` accepts a clamped poster seek while preserving the single-clip default. Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. `installEncodedVideo(tmpPath, targetPath, label)` is the shared in-place install: move the original aside to a `.bak` on Windows (where `fs.rename` refuses an existing destination), rename the new file over it, and restore the backup — plus unlink the temp — on any failure, returning `{ok:true,outPath}` / `{ok:false,reason}` so the worst case is "skipped", never "the video is gone". Use it for EVERY replace-a-video-with-its-re-encode path; `pipeline/audioMux.js` is the out-of-module caller. `edgeFadeFilter(durationSec)` is the `-af` fade-in/fade-out fragment a mid-song clip (a social cut) appends to its trim. || `forgeAccessErrors.js` | `isForgeNoAccessError(err)` / `isForgeNoAccessMessage(text)` / `logForgeNoAccessOnce(scope, repoSpec, detail)` / `forgeNoAccessRemedy(repoSpec)` — tells a PERMANENT `gh` no-access 404 (`Could not resolve to a Repository`, `HTTP 404`) apart from a transient blip. `execGh` stamps `ghNoAccess` on the rejection and keeps it OUT of the consecutive-failure backoff (which caps at 15 min and then re-fires forever), and the polling jobs (`branchReconcile`, `prWatcher`) narrate it exactly once per scope+repo per process with a remedy line instead of once per tick. `__resetForgeNoAccessLog()` is the test seam. || `forkHead.js` | `normalizeForkHead(value)` / `forkRemoteName(ownerLogin)` / `resolveTaskForkHead(metadata)` — the validated `{remoteUrl, ownerLogin}` address of a cross-repository PR's head branch, which has no `origin/<branch>` to attach to. Fail-closed: anything that isn't a usable pair (or that starts with `-`, which git would read as an option) is `null`, so every caller falls back to origin-only behavior instead of guessing. `forkRemoteName` is the deterministic `fork-<owner>` remote name that makes a re-attach reuse the remote it already added. Shared by `appPullRequests.js` (produces), `agentWorktreeCleanup.js`/`prRemediationFollowUp.js` (persist in task metadata), `agentWorkspacePrep.js` (threads), and `worktreeManager.js` (consumes — it has no forge client of its own). `resolveTaskForkHead` is the single reader of the generic `forkHead` task-metadata key, the fork-side counterpart to `taskTargetBranch.js`. || `frameQuality.js` | Scores decoded video frames so a chained render can CHOOSE its continuation anchor instead of taking whatever an end-seek lands on. `scoreFrame({width,height,data},{recency})` combines three terms over a raw single-channel buffer: log-compressed `gradientVariance` (focus), distance of `meanLuma` from mid-grey (exposure penalty, which rejects a fade-to-black or a blown highlight), and a small linear recency bonus that keeps the anchor near the cut when candidates are comparably clean. Usability and ranking are deliberately separate: `usable` gates on raw gradient variance against `MIN_SIGNAL_VARIANCE` alone, so only a mathematically degenerate frame is rejected and a legitimately dark low-key tail still qualifies — the same contract `imageFrameStats.js` keeps. Gating on the composite score instead would reject every night scene on the exposure term. `TAIL_WINDOW_SECONDS` is capped at the reach of the single `-sseof -1.0` seek this replaces: focus is systematically highest at the OLDEST candidate, so a wider window would widen the backward jump at each chain seam rather than tightening it. `pickBestFrame(paths)` decodes each candidate through `sharp` and returns the winner (or `null` when nothing decodes or every candidate is degenerate, so the caller degrades rather than failing a render); its `index` is the position in the array AS PASSED, because the caller turns that into the anchor's time offset. `MAX_CANDIDATES` is derived from the window, never set independently — the ffmpeg-side `-frames:v` cap truncates from the NEWEST end, exactly the frames recency prefers. `TAIL_WINDOW_SECONDS` / `CANDIDATE_FPS` / `MAX_CANDIDATES` define the window the caller decodes from. Consumer: `services/videoGen/local.js#extractLastFrame`. |@@ -798,6 +798,6 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `muscriptorModels.js` | `MUSCRIPTOR_MODELS` (`small`/`medium`/`large`) — MuScriptor size tiers shared by route schemas and `audioMidiTranscription.js`; pinned to the Python runner's argparse choices. || `loopInterval.js` | Loop interval grammar (`MIN_INTERVAL_MS`, `parseInterval`, `isValidLoopInterval`) shared by `services/loops.js` and `createLoopSchema` so the route rejects what the service would. |-| `musicVideoAspect.js` | `musicVideoAspect(project)` (treatment brief aspect, default 16:9), `MUSIC_VIDEO_FRAME_GEN_SIZES` and `musicVideoFrameGenSize(project)`: the size every Music Video reference frame is requested at, so a backend never picks portrait for a 16:9 video. Shared by `productionDispatch.js`, `documentRender.js` and the client board. |+| `musicVideoAspect.js` | `musicVideoAspect(project)` (treatment brief aspect, default 16:9), `MUSIC_VIDEO_FRAME_GEN_SIZES` and `musicVideoFrameGenSize(project)`: the size every Music Video reference frame is requested at, so a backend never picks portrait for a 16:9 video. `musicVideoAtAspect(project, aspect)` re-frames the project for one render (a vertical social cut) without touching the record. Shared by `productionDispatch.js`, `documentRender.js` and the client board. || `musicVideoMotion.js` | `MOTION_CONTINUITY_CLAUSE`: the clause every Music Video motion (i2v) prompt ends with, pinning the reference frame's lighting, time of day and palette. Shared by `handoff.js` and the client board. || `musicVideoConditioning.js` | `musicVideoConditioningReferences(project, scene)` selects the approved character sheet and scene's mapped set plate, with capped project-wide fallback; shared by board and production. |diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.jsindex 9677a1b468..09394734d1 100644--- a/server/lib/ffmpeg.js+++ b/server/lib/ffmpeg.js@@ -425,6 +425,15 @@ export const H264_ENCODE_ARGS = Object.freeze([]);export const AAC_ENCODE_ARGS = Object.freeze(['-c:a', 'aac', '-b:a', '192k']);+// A clip cut from mid-song (a social cut) starts and stops on a hard edge; a+// short fade in and a longer fade out keep it from clicking. Returned as an+// `-af` chain fragment (leading comma) so callers append it to their trim.+export const edgeFadeFilter = (durationSec, { inSec = 0.08, outSec = 0.6 } = {}) => {+ const out = Math.min(outSec, Math.max(0, durationSec / 2));+ const fadeIn = Math.min(inSec, Math.max(0, durationSec / 2));+ return `,afade=t=in:st=0:d=${fadeIn},afade=t=out:st=${Math.max(0, durationSec - out).toFixed(3)}:d=${out}`;+};+// BT.709 color tagging for every re-encode this module writes.//// Untagged H.264 makes each player guess a color space, and the common guessdiff --git a/server/lib/musicVideoAspect.js b/server/lib/musicVideoAspect.jsindex 39a255ab73..20f4643e64 100644--- a/server/lib/musicVideoAspect.js+++ b/server/lib/musicVideoAspect.js@@ -22,5 +22,16 @@ export const MUSIC_VIDEO_FRAME_GEN_SIZES = Object.freeze({'1:1': Object.freeze({ width: 1024, height: 1024 }),});+/**+ * The project framed at another aspect for ONE render (a 9:16 social cut of a+ * 16:9 video), leaving the stored record untouched. Every renderer reads the+ * aspect through `musicVideoAspect`, so re-framing the brief is enough.+ */+export function musicVideoAtAspect(project, aspect) {+ if (!MUSIC_VIDEO_ASPECTS.includes(aspect) || aspect === musicVideoAspect(project)) return project;+ const treatment = project?.treatment || {};+ return { ...project, treatment: { ...treatment, brief: { ...(treatment.brief || {}), aspectRatio: aspect } } };+}+/** `{ width, height }` to request a project's reference frames at. */export const musicVideoFrameGenSize = (project) => ({ ...MUSIC_VIDEO_FRAME_GEN_SIZES[musicVideoAspect(project)] });diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 96faa35e99..eb3dd4ae17 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -512,8 +512,18 @@ export const MUSIC_VIDEO_EXCERPT_NOTE_VERDICTS = ['flagged', 'approved'];export const musicVideoExcerptRequestSchema = z.object({startSec: z.number().min(0).max(36000),endSec: z.number().min(0).max(36000),+ // #9280: a social cut renders at another frame and fades its audio edges.+ aspect: z.enum(['16:9', '9:16', '1:1']).optional(),+ fade: z.boolean().optional(),}).strict().refine((r) => r.endSec > r.startSec, { message: 'endSec must be greater than startSec' });+// #9280: hook-window suggestions for social cuts.+export const musicVideoSocialCutsQuerySchema = z.object({+ count: z.coerce.number().int().min(1).max(10).optional(),+ minSec: z.coerce.number().min(3).max(120).optional(),+ 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' });+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 254bb35b72..09908e7f1b 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -35,6 +35,7 @@ import {musicVideoTreatmentApplySchema,musicVideoTreatmentProofReviewSchema,musicVideoExcerptRequestSchema,+ musicVideoSocialCutsQuerySchema,musicVideoCodeGenerateSchema,musicVideoExcerptNoteSchema,musicVideoExcerptNoteUpdateSchema,@@ -96,6 +97,7 @@ import { prepareCodeRender } from '../services/musicVideo/codeRender.js';import { generateMusicVideoCode, regenerateMusicVideoCodeSection } from '../services/musicVideo/codeGeneration.js';import { 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 {startRevision, resumeRevision, cancelRevision, releaseRevisionSection,} from '../services/musicVideo/revisionService.js';@@ -571,8 +573,14 @@ router.delete('/:id/composition/document', asyncHandler(async (req, res) => {// full render above) on its OWN job map, so an excerpt draft and a full render// can run at once without contending for the same mutex.router.post('/:id/excerpt', asyncHandler(async (req, res) => {- const { startSec, endSec } = validateRequest(musicVideoExcerptRequestSchema, req.body);- res.json(await startExcerptRender(req.params.id, { startSec, endSec }));+ const { startSec, endSec, aspect, fade } = validateRequest(musicVideoExcerptRequestSchema, req.body);+ res.json(await startExcerptRender(req.params.id, { startSec, endSec, aspect, fade }));+}));++// #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);+ res.json({ suggestions: suggestSocialCuts(await requireProject(req.params.id), options) });}));router.get('/excerpt/:jobId/events', (req, res) => {diff --git a/server/routes/musicVideoExcerpt.test.js b/server/routes/musicVideoExcerpt.test.jsindex 776a85c503..0c25a0d9ea 100644--- a/server/routes/musicVideoExcerpt.test.js+++ b/server/routes/musicVideoExcerpt.test.js@@ -28,6 +28,7 @@ vi.mock('../services/musicVideo/excerptRender.js', () => ({}));const { default: musicVideoRoutes } = await import('./musicVideo.js');+const { startExcerptRender } = await import('../services/musicVideo/excerptRender.js');const projects = await import('../services/musicVideo/projects.js');const app = express();@@ -141,3 +142,27 @@ describe('excerpts survive a clone (#8986 acceptance)', () => {expect(existsSync(sheetPath)).toBe(false);});});++describe('social cuts (#9280)', () => {+ it('forwards a vertical, faded excerpt request and rejects an unknown aspect', async () => {+ const project = await projects.createProject({ name: 'Example Video' });+ startExcerptRender.mockResolvedValue({ jobId: 'mve-2', excerptId: 'mve-2' });+ const ok = await request(app).post(`${base(project.id)}/excerpt`).send({ startSec: 10, endSec: 25, aspect: '9:16', fade: true });+ expect(ok.status).toBe(200);+ expect(startExcerptRender).toHaveBeenCalledWith(project.id, { startSec: 10, endSec: 25, aspect: '9:16', fade: true });+ const bad = await request(app).post(`${base(project.id)}/excerpt`).send({ startSec: 10, endSec: 25, aspect: '4:3' });+ expect(bad.status).toBe(400);+ });++ it('suggests hook windows from the project\'s lyric timing', async () => {+ const created = await projects.createProject({ name: 'Example Video' });+ await projects.updateProject(created.id, {+ audioAnalysis: { durationSec: 60 },+ lyricCues: Array.from({ length: 10 }, (_, i) => ({ id: `lc-${i}`, text: `line ${i}`, startSec: i * 6, endSec: i * 6 + 5 })),+ });+ const r = await request(app).get(`${base(created.id)}/social-cuts?count=2&minSec=10&maxSec=20`);+ expect(r.status).toBe(200);+ expect(r.body.suggestions).toHaveLength(2);+ expect(r.body.suggestions[0]).toMatchObject({ startSec: expect.any(Number), endSec: expect.any(Number), reasons: expect.any(Array) });+ });+});diff --git a/server/services/musicVideo/codeRender.js b/server/services/musicVideo/codeRender.jsindex 068baa644b..4541f8bdc3 100644--- a/server/services/musicVideo/codeRender.js+++ b/server/services/musicVideo/codeRender.js@@ -18,7 +18,7 @@ import { buildCodeTimeline, buildSongDocument, codeFrameSize, paletteFromProject// so unit tests of the footage renderer can keep a partial ffmpeg mock.const AAC_MUX_ARGS = Object.freeze(['-c:a', 'aac', '-b:a', '192k']);-export function _muxExactArgs(videoPath, audioPath, outputPath, durationSec, audioStartSec = 0) {+export function _muxExactArgs(videoPath, audioPath, outputPath, durationSec, audioStartSec = 0, fade = '') {const args = ['-hide_banner', '-loglevel', 'error', '-i', videoPath];if (audioStartSec > 0) args.push('-ss', String(audioStartSec));args.push(@@ -26,7 +26,7 @@ export function _muxExactArgs(videoPath, audioPath, outputPath, durationSec, aud'-map', '0:v:0', '-map', '1:a:0','-t', String(durationSec),'-c:v', 'copy',- '-af', `atrim=duration=${durationSec},apad=whole_dur=${durationSec},asetpts=PTS-STARTPTS`,+ '-af', `atrim=duration=${durationSec},apad=whole_dur=${durationSec},asetpts=PTS-STARTPTS${fade}`,...AAC_MUX_ARGS,'-movflags', '+faststart','-y', outputPath,@@ -72,9 +72,9 @@ export function prepareCodeRender(project, { windowStart = null, windowEnd = nul}export async function encodeCodeComposition({- html, song, width, height, fps, durationSec, audioPath, outputPath, directory, signal, onProgress, audioStartSec = 0,+ html, song, width, height, fps, durationSec, audioPath, outputPath, directory, signal, onProgress, audioStartSec = 0, fade = false,}) {- const { findFfmpeg, runFfmpegProcess } = await import('../../lib/ffmpeg.js');+ const { findFfmpeg, runFfmpegProcess, edgeFadeFilter } = await import('../../lib/ffmpeg.js');const { openComposition } = await import('../htmlComposition/browser.js');const { encodeComposition } = await import('../htmlComposition/encode.js');const ffmpeg = await findFfmpeg();@@ -92,7 +92,7 @@ export async function encodeCodeComposition({});signal?.throwIfAborted();const mux = await runFfmpegProcess({- bin: ffmpeg, signal, args: _muxExactArgs(silent, audioPath, outputPath, durationSec, audioStartSec),+ bin: ffmpeg, signal, args: _muxExactArgs(silent, audioPath, outputPath, durationSec, audioStartSec, fade ? edgeFadeFilter(durationSec) : ''),});if (!mux.ok) {if (signal?.aborted || /cancelled/.test(mux.reason || '')) {diff --git a/server/services/musicVideo/codeRender.test.js b/server/services/musicVideo/codeRender.test.jsindex 343dd79266..631072c63c 100644--- a/server/services/musicVideo/codeRender.test.js+++ b/server/services/musicVideo/codeRender.test.js@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest';import { mkdtemp, readFile, rm, writeFile } from 'fs/promises';import { tmpdir } from 'os';import { join } from 'path';-import { findFfmpeg, probeVideoDuration, runFfmpegProcess } from '../../lib/ffmpeg.js';+import { findFfmpeg, probeVideoDuration, runFfmpegProcess, edgeFadeFilter } from '../../lib/ffmpeg.js';import { pcmToWavBuffer } from '../../lib/chiptuneRender.js';import { prepareCodeRender, _muxExactArgs } from './codeRender.js';@@ -59,6 +59,15 @@ describe.skipIf(!ffmpeg)('code render mux (#9076)', () => {const args = _muxExactArgs(silent, wav, out, plan.durationSec, 0).join(' ');expect(args).not.toContain('afade');expect(await readFile(out)).toBeInstanceOf(Buffer);+ // A social cut (#9280) fades its edges without changing the length: ffmpeg+ // accepts the fade chain and the file still covers the song.+ const faded = join(dir, 'faded.mp4');+ const fadedMux = await runFfmpegProcess({+ bin: ffmpeg,+ args: _muxExactArgs(silent, wav, faded, plan.durationSec, 0, edgeFadeFilter(plan.durationSec)),+ });+ expect(fadedMux.ok).toBe(true);+ expect(Math.abs((await probeVideoDuration(faded)) - plan.durationSec)).toBeLessThan(1 / 24 + 0.02);} finally {await rm(dir, { recursive: true, force: true });}diff --git a/server/services/musicVideo/documentRender.js b/server/services/musicVideo/documentRender.jsindex 3916bb7778..7d87f63d44 100644--- a/server/services/musicVideo/documentRender.js+++ b/server/services/musicVideo/documentRender.js@@ -270,12 +270,12 @@ function documentBoundaryTimes(data, window) {// Mux the silent picture with the master song (and the optional bed), both// cut to the window on SONG time.-function documentMuxArgs(videoPath, audioPath, outputPath, { startSec, durationSec, songDurationSec, soundBed = null, buildBed, audioNorm }) {+function documentMuxArgs(videoPath, audioPath, outputPath, { startSec, durationSec, songDurationSec, soundBed = null, buildBed, audioNorm, fade = '' }) {if (!soundBed?.path) {const args = ['-hide_banner', '-loglevel', 'error', '-i', videoPath];if (startSec > 0) args.push('-ss', String(startSec));args.push('-i', audioPath, '-map', '0:v:0', '-map', '1:a:0', '-t', String(durationSec), '-c:v', 'copy',- '-af', `atrim=duration=${durationSec},apad=whole_dur=${durationSec},asetpts=PTS-STARTPTS`,+ '-af', `atrim=duration=${durationSec},apad=whole_dur=${durationSec},asetpts=PTS-STARTPTS${fade}`,'-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart', '-y', outputPath);return args;}@@ -284,7 +284,7 @@ function documentMuxArgs(videoPath, audioPath, outputPath, { startSec, durationSfirstInputIdx: 2, mainLabel: '[master]', outLabel: '[mixa]',});const filters = [`[1:a]${audioNorm}[master]`, ...bed.filters,- `[mixa]atrim=start=${startSec}:end=${startSec + durationSec},asetpts=PTS-STARTPTS,apad=whole_dur=${durationSec}[outa]`];+ `[mixa]atrim=start=${startSec}:end=${startSec + durationSec},asetpts=PTS-STARTPTS,apad=whole_dur=${durationSec}${fade}[outa]`];return ['-hide_banner', '-loglevel', 'error', '-i', videoPath, '-i', audioPath, ...bed.inputs,'-filter_complex', filters.join(';'), '-map', '0:v:0', '-map', '[outa]', '-t', String(durationSec), '-c:v', 'copy','-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart', '-y', outputPath];@@ -295,9 +295,9 @@ function documentMuxArgs(videoPath, audioPath, outputPath, { startSec, durationS* Resolves `{ width, height, fps, durationSec, startSec, boundaryTimes }`.*/export async function encodeDocumentComposition({- project, plan, jobId, audioPath, soundBed = null, outputPath, signal, onProgress, windowStart = null, windowEnd = null,+ project, plan, jobId, audioPath, soundBed = null, outputPath, signal, onProgress, windowStart = null, windowEnd = null, fade = false,}) {- const { findFfmpeg, runFfmpegProcess, probeVideoGeometry } = await import('../../lib/ffmpeg.js');+ const { findFfmpeg, runFfmpegProcess, probeVideoGeometry, edgeFadeFilter } = await import('../../lib/ffmpeg.js');const { stageMusicVideoComposition } = await import('../htmlComposition/index.js');const { openComposition } = await import('../htmlComposition/browser.js');const { encodeComposition } = await import('../htmlComposition/encode.js');@@ -352,7 +352,7 @@ export async function encodeDocumentComposition({bin: ffmpeg, signal,args: documentMuxArgs(silent, audioPath, outputPath, {startSec: window.startSec, durationSec: window.durationSec, songDurationSec: plan.songDurationSec,- soundBed, buildBed: buildAudioBedMix, audioNorm: AUDIO_NORM,+ soundBed, buildBed: buildAudioBedMix, audioNorm: AUDIO_NORM, fade: fade ? edgeFadeFilter(window.durationSec) : '',}),});if (!mux.ok) {diff --git a/server/services/musicVideo/excerpt.js b/server/services/musicVideo/excerpt.jsindex e0cc937112..23b0e4b0cb 100644--- a/server/services/musicVideo/excerpt.js+++ b/server/services/musicVideo/excerpt.js@@ -53,7 +53,7 @@ function findExcerpt(project, excerptId) {* project; the render job fills in `filename`/`contactSheetFilename` (or* `error`) once the encode finishes.*/-export function startExcerptOnProject(project, { startSec, endSec, sections = null, partialFilename = null, renderingOn = null }, now = new Date().toISOString()) {+export function startExcerptOnProject(project, { startSec, endSec, sections = null, partialFilename = null, renderingOn = null, aspect = null, fade = false }, now = new Date().toISOString()) {if (!(startSec >= 0) || !(endSec > startSec) || endSec > MAX_EXCERPT_SEC) {throw excerptError(422, 'INVALID_EXCERPT_RANGE', 'endSec must be greater than startSec, and both within range');}@@ -76,6 +76,10 @@ export function startExcerptOnProject(project, { startSec, endSec, sections = nu// #8987: the sections the draft cuts, in ABSOLUTE song time — what a// flagged note maps onto when the director asks for a selective revision.sections: Array.isArray(sections) ? sections : null,+ // #9280: a social cut's frame (the project's own unless re-framed) and+ // whether its audio edges fade; `width`/`height` land with the finished file.+ aspect: aspect || null,+ fade: fade === true,error: null,notes: [],createdAt: now,diff --git a/server/services/musicVideo/excerptRender.js b/server/services/musicVideo/excerptRender.jsindex a0f39241a5..c4e25f198e 100644--- a/server/services/musicVideo/excerptRender.js+++ b/server/services/musicVideo/excerptRender.js@@ -38,6 +38,7 @@ import { renderTypographyOverlays, removeCompositionScratch } from './compositioimport { startExcerptOnProject, applyExcerptPatch } from './excerpt.js';import { markRevisionRendering, settleRevisionRender } from './revision.js';import { ensureInstanceId } from '../instanceIdentity.js';+import { musicVideoAspect, musicVideoAtAspect } from '../../lib/musicVideoAspect.js';import { musicVideoEvents } from './events.js';const jobs = new Map();@@ -87,10 +88,10 @@ const SEEKED_EXCERPTS = Object.freeze({const full = prepareCodeRender(project);return { full, totalSec: full.durationSec, songSections: full.song.sections.map((s) => ({ sceneId: s.sceneId || s.id, startSec: s.startSec, endSec: s.endSec })) };},- encode: async ({ project, projectId, jobId, audioPath, outputPath, signal, onProgress, startSec, endSec }) => {+ encode: async ({ project, projectId, jobId, audioPath, outputPath, signal, onProgress, startSec, endSec, fade }) => {const plan = prepareCodeRender(project, { windowStart: startSec, windowEnd: endSec });await encodeCodeComposition({- ...plan, audioPath, audioStartSec: startSec, outputPath, directory: `compositions/music-video/${projectId}/${jobId}`, signal, onProgress,+ ...plan, audioPath, audioStartSec: startSec, outputPath, directory: `compositions/music-video/${projectId}/${jobId}`, signal, onProgress, fade,});return { width: plan.width, height: plan.height, fps: plan.fps, boundaryTimes: plan.sectionTimes };},@@ -106,13 +107,16 @@ const SEEKED_EXCERPTS = Object.freeze({.map((s) => ({ sceneId: s.sceneId, startSec: s.startSec, endSec: s.endSec }));return { plan, totalSec: plan.durationSec, songSections };},- encode: ({ prepared, project, jobId, audioPath, soundBed, outputPath, signal, onProgress, startSec, endSec }) => encodeDocumentComposition({- project, plan: prepared.plan, jobId, audioPath, soundBed, outputPath, signal, onProgress, windowStart: startSec, windowEnd: endSec,+ encode: ({ prepared, project, jobId, audioPath, soundBed, outputPath, signal, onProgress, startSec, endSec, fade }) => encodeDocumentComposition({+ project, plan: prepared.plan, jobId, audioPath, soundBed, outputPath, signal, onProgress, windowStart: startSec, windowEnd: endSec, fade,}),},});-async function launchSeekedExcerpt({ projectId, project, startSec, endSec, revisionId, handOff, renderer }) {+async function launchSeekedExcerpt({ projectId, project: stored, startSec, endSec, revisionId, handOff, renderer, aspect = null, fade = false }) {+ // A social cut renders the same composition at another frame (#9280): the+ // re-framed view drives planning, staging and capture; the record keeps its own aspect.+ const project = musicVideoAtAspect(stored, aspect);const prepared = await renderer.prepare(project);// Same order as a full render: a missing master throws before the// excerpt is marked rendering.@@ -139,7 +143,7 @@ async function launchSeekedExcerpt({ projectId, project, startSec, endSec, revis}));const renderingOn = await ensureInstanceId();const { excerpt } = await mutateProjectRecord(projectId, (current) => {- const started = startExcerptOnProject(current, { startSec, endSec: endClamped, sections, partialFilename: filename, renderingOn });+ const started = startExcerptOnProject(current, { startSec, endSec: endClamped, sections, partialFilename: filename, renderingOn, aspect: musicVideoAspect(project), fade });return revisionId ? { ...started, project: markRevisionRendering(started.project, revisionId, started.excerpt.id) } : started;});const excerptId = excerpt.id;@@ -165,7 +169,7 @@ async function launchSeekedExcerpt({ projectId, project, startSec, endSec, revisreturn persisted;};Promise.resolve().then(() => renderer.encode({- prepared, project, projectId, jobId, audioPath, soundBed, outputPath, signal, startSec, endSec: endClamped,+ prepared, project, projectId, jobId, audioPath, soundBed, outputPath, signal, startSec, endSec: endClamped, fade,onProgress: (fraction) => broadcastSse(job, { type: 'progress', progress: fraction }),})).then(async (encoded) => {job.overlayAbort = null;@@ -180,7 +184,7 @@ async function launchSeekedExcerpt({ projectId, project, startSec, endSec, revisconsole.warn(`⚠️ Music-video ${renderer.label} excerpt contact sheet failed [${jobId.slice(4, 12)}]: ${err.message}`);contactSheetFilename = null;}- const persisted = await finalize({ status: 'complete', filename, contactSheetFilename, error: null, jobId: null });+ const persisted = await finalize({ status: 'complete', filename, contactSheetFilename, error: null, jobId: null, width: encoded.width ?? null, height: encoded.height ?? null });if (!persisted) {await unlink(outputPath).catch(() => {});broadcastSse(job, { type: 'error', error: 'The excerpt rendered, but saving the result failed — reload the project and try again' });@@ -202,7 +206,7 @@ async function launchSeekedExcerpt({ projectId, project, startSec, endSec, revisreturn { jobId, excerptId };}-export async function startExcerptRender(projectId, { startSec, endSec }, { revisionId = null } = {}) {+export async function startExcerptRender(projectId, { startSec, endSec, aspect = null, fade = false }, { revisionId = null } = {}) {const project = await getProject(projectId);if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });@@ -219,7 +223,14 @@ export async function startExcerptRender(projectId, { startSec, endSec }, { reviconst seeked = SEEKED_EXCERPTS[project.composition?.mode];if (seeked) {return await launchSeekedExcerpt({- projectId, project, startSec, endSec, revisionId, handOff: () => { handedOff = true; }, renderer: seeked,+ projectId, project, startSec, endSec, revisionId, handOff: () => { handedOff = true; }, renderer: seeked, aspect, fade,+ });+ }+ // A footage (ffmpeg) render has no frame of its own to re-lay-out: cropping+ // the 16:9 cut would slice through its type and cards (#9280).+ if ((aspect && aspect !== musicVideoAspect(project)) || fade) {+ throw new ServerError('Social cuts (another aspect, faded edges) need a composition-document or code-rendered project', {+ status: 422, code: 'EXCERPT_ASPECT_UNSUPPORTED',});}const { ffmpeg, audioPath, composed, clips, audioDurationSec, soundBed } = await planMusicVideoRender(project);diff --git a/server/services/musicVideo/render.document.test.js b/server/services/musicVideo/render.document.test.jsindex 94b60e40b9..b3cc09740a 100644--- a/server/services/musicVideo/render.document.test.js+++ b/server/services/musicVideo/render.document.test.js@@ -19,7 +19,7 @@ vi.mock('../videoGen/local.js', () => ({ loadHistory: vi.fn(async () => []), mutvi.mock('./codeRender.js', async (importOriginal) => ({ ...(await importOriginal()), writeCodeProofSheet: vi.fn(async () => null) }));vi.mock('./documentRender.js', async (importOriginal) => ({...(await importOriginal()),- encodeDocumentComposition: vi.fn(async ({ plan }) => ({ width: 1920, height: 1080, fps: 24, durationSec: plan.durationSec, startSec: 0, boundaryTimes: [0] })),+ encodeDocumentComposition: vi.fn(async ({ plan }) => ({ width: plan.width, height: plan.height, fps: 24, durationSec: plan.durationSec, startSec: 0, boundaryTimes: [0] })),}));const { PATHS } = await import('../../lib/paths.js');@@ -66,6 +66,29 @@ describe('composition-document render plan', () => {await vi.waitFor(async () => expect((await projects.getProject(id)).renderHistoryId).toBe(jobId));});+ it('renders a faded 9:16 social cut of a 16:9 document project without re-framing the project (#9280)', async () => {+ const id = await documentProject();+ await importDocumentTemplate(id);+ encodeDocumentComposition.mockClear();+ const { excerptId } = await startExcerptRender(id, { startSec: 1, endSec: 4, aspect: '9:16', fade: true });+ await vi.waitFor(async () => expect((await projects.getProject(id)).excerpts.find((e) => e.id === excerptId).status).toBe('complete'));+ const call = encodeDocumentComposition.mock.calls.at(-1)[0];+ expect(call).toMatchObject({ fade: true, windowStart: 1, windowEnd: 4, plan: { width: 1080, height: 1920 } });+ expect(call.project.treatment.brief.aspectRatio).toBe('9:16');+ const stored = await projects.getProject(id);+ expect(stored.treatment?.brief?.aspectRatio ?? '16:9').toBe('16:9');+ expect(stored.excerpts.find((e) => e.id === excerptId)).toMatchObject({ aspect: '9:16', fade: true, width: 1080, height: 1920 });+ });++ it('refuses a social cut of a footage project, which has no frame of its own to re-lay-out (#9280)', async () => {+ await mkdir(PATHS.music, { recursive: true });+ await writeFile(join(PATHS.music, 'song.wav'), Buffer.alloc(64));+ const { id } = await projects.createProject({ name: 'Footage', uploadedAudioFilename: 'song.wav' });+ for (const body of [{ aspect: '9:16' }, { fade: true }]) {+ await expect(startExcerptRender(id, { startSec: 1, endSec: 3, ...body })).rejects.toMatchObject({ status: 422, code: 'EXCERPT_ASPECT_UNSUPPORTED' });+ }+ });+it('refuses a full render and an excerpt over a stale performance take, like a footage render (#9266)', async () => {const id = await documentProject();await importDocumentTemplate(id);diff --git a/server/services/musicVideo/socialCuts.js b/server/services/musicVideo/socialCuts.jsnew file mode 100644index 0000000000..51236cd60f--- /dev/null+++ b/server/services/musicVideo/socialCuts.js@@ -0,0 +1,125 @@+/**+ * Music Video — hook windows for vertical social cuts (#9280).+ *+ * A Short / TikTok / Reel lives or dies in its first seconds, so a cut should+ * open on a sung line, hold a face that is singing it, sit in the song's+ * loudest stretch, and ideally say the title. This scores every lyric-line+ * aligned window of `minSec`–`maxSec` on those signals and returns the best+ * non-overlapping few. Pure: project in, suggestions out.+ */++const round3 = (n) => Math.round(n * 1000) / 1000;+const finite = (n) => (typeof n === 'number' && Number.isFinite(n) ? n : null);+const HOOK_SECTION = /\b(chorus|hook|refrain|drop)\b/i;+const LIFT_SECTION = /\b(bridge|breakdown|pre-?chorus)\b/i;+const LEAD_IN_SEC = 0.25;+const TAIL_SEC = 0.35;+const WEIGHTS = Object.freeze({ performance: 0.35, lyric: 0.2, energy: 0.2, hook: 0.15, title: 0.1 });++function songLength(project) {+ const ends = [finite(project?.audioAnalysis?.durationSec)];+ for (const s of project?.scenes || []) ends.push(finite(s?.endSec));+ for (const c of project?.lyricCues || []) ends.push(finite(c?.endSec));+ return ends.reduce((max, v) => (v != null && v > max ? v : max), 0);+}++function lyricLines(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) != null && c.endSec > c.startSec ? c.endSec : c.startSec + 1.5 }))+ .sort((a, b) => a.startSec - b.startSec);+}++const overlap = (a0, a1, b0, b1) => Math.max(0, Math.min(a1, b1) - Math.max(a0, b0));+const covered = (spans, s, e) => spans.reduce((sum, span) => sum + overlap(s, e, span.startSec, span.endSec), 0) / (e - s);++const normalize = (text) => text.toLowerCase().normalize('NFKD').replace(/[^\p{L}\p{N}\s]/gu, ' ').replace(/\s+/g, ' ').trim();++function titlePhrase(project) {+ const name = typeof project?.name === 'string' ? normalize(project.name.replace(/\(.*?\)|\[.*?\]/g, '')) : '';+ return name.length >= 3 ? name : null;+}++/** Mean waveform level over [s, e), relative to the song's loudest stretch of the same length. */+function energyScorer(project, duration) {+ const wave = Array.isArray(project?.audioAnalysis?.waveform) ? project.audioAnalysis.waveform.filter((v) => finite(v) != null) : [];+ if (wave.length < 8 || !(duration > 0)) return () => 0.5;+ const at = (s, e) => {+ const i0 = Math.max(0, Math.floor((s / duration) * wave.length));+ const i1 = Math.min(wave.length, Math.max(i0 + 1, Math.ceil((e / duration) * wave.length)));+ let sum = 0;+ for (let i = i0; i < i1; i++) sum += wave[i];+ return sum / (i1 - i0);+ };+ const peak = Math.max(...wave);+ return (s, e) => (peak > 0 ? Math.min(1, at(s, e) / peak) : 0.5);+}++function scoreWindow(ctx, startSec, endSec) {+ const { performance, lines, hookSpans, liftSpans, title, energy } = ctx;+ const perf = covered(performance, startSec, endSec);+ const lyric = Math.min(1, covered(lines, startSec, endSec));+ const loud = energy(startSec, endSec);+ const hook = covered(hookSpans, startSec, endSec) > 0.5 ? 1 : covered(liftSpans, startSec, endSec) > 0.5 ? 0.5 : 0;+ const inside = lines.filter((l) => l.startSec >= startSec - 1e-6 && l.startSec < endSec);+ const saysTitle = title && inside.some((l) => normalize(l.text).includes(title)) ? 1 : 0;+ const score = WEIGHTS.performance * perf + WEIGHTS.lyric * lyric + WEIGHTS.energy * loud + WEIGHTS.hook * hook + WEIGHTS.title * saysTitle;+ const reasons = [];+ if (perf >= 0.5) reasons.push(`lip-sync ${Math.round(perf * 100)}%`);+ if (hook === 1) reasons.push('chorus');+ else if (hook === 0.5) reasons.push('bridge');+ if (saysTitle) reasons.push('sings the title');+ if (loud >= 0.75) reasons.push('high energy');+ return { score, reasons, label: inside[0]?.text?.slice(0, 80) || null };+}++/**+ * Up to `count` non-overlapping `{ startSec, endSec, score, label, reasons }`+ * windows, best first. Windows open just before a sung line and close just after+ * one; a song without lyric timing falls back to evenly spaced windows.+ */+export function suggestSocialCuts(project, { count = 3, minSec = 15, maxSec = 30 } = {}) {+ const duration = songLength(project);+ if (!(duration > 0)) return [];+ const lo = Math.min(minSec, maxSec);+ const hi = Math.max(minSec, maxSec);+ if (duration <= lo) return [{ startSec: 0, endSec: round3(duration), score: 1, label: null, reasons: ['whole song'] }];+ const scenes = (project?.scenes || []).filter((s) => finite(s?.startSec) != null && finite(s?.endSec) != null && s.endSec > s.startSec);+ const ctx = {+ lines: lyricLines(project),+ performance: scenes.filter((s) => s.shotMode === 'performance'),+ hookSpans: scenes.filter((s) => HOOK_SECTION.test(s.sectionLabel || '')),+ liftSpans: scenes.filter((s) => LIFT_SECTION.test(s.sectionLabel || '')),+ title: titlePhrase(project),+ energy: energyScorer(project, duration),+ };+ const candidates = [];+ if (ctx.lines.length) {+ for (const first of ctx.lines) {+ const startSec = Math.max(0, first.startSec - LEAD_IN_SEC);+ let best = null;+ for (const last of ctx.lines) {+ const endSec = Math.min(duration, last.endSec + TAIL_SEC);+ const span = endSec - startSec;+ if (last.startSec < first.startSec || span < lo || span > hi) continue;+ const scored = scoreWindow(ctx, startSec, endSec);+ if (!best || scored.score > best.score + 1e-9) best = { startSec, endSec, ...scored };+ }+ if (best) candidates.push(best);+ }+ }+ if (!candidates.length) {+ const span = Math.min(hi, duration);+ for (let startSec = 0; startSec + span <= duration + 1e-6; startSec += Math.max(1, span / 2)) {+ candidates.push({ startSec, endSec: startSec + span, ...scoreWindow(ctx, startSec, startSec + span) });+ }+ }+ candidates.sort((a, b) => b.score - a.score || a.startSec - b.startSec);+ const picked = [];+ for (const c of candidates) {+ if (picked.length >= count) break;+ if (picked.some((p) => overlap(p.startSec, p.endSec, c.startSec, c.endSec) > 0)) continue;+ picked.push(c);+ }+ return picked.map((c) => ({ startSec: round3(c.startSec), endSec: round3(c.endSec), score: round3(c.score), label: c.label, reasons: c.reasons }));+}diff --git a/server/services/musicVideo/socialCuts.test.js b/server/services/musicVideo/socialCuts.test.jsnew file mode 100644index 0000000000..59d5aef9dc--- /dev/null+++ b/server/services/musicVideo/socialCuts.test.js@@ -0,0 +1,58 @@+/**+ * Hook windows for vertical social cuts (#9280): the scoring prefers a sung,+ * lip-synced chorus that says the title, windows never overlap, and a song+ * with no lyric timing (or shorter than a cut) still gets a usable window.+ */+import { describe, expect, it } from 'vitest';+import { suggestSocialCuts } from './socialCuts.js';++const line = (text, startSec, endSec) => ({ id: `lc-${startSec}`, text, startSec, endSec });+const scene = (startSec, endSec, shotMode, sectionLabel) => ({ sceneId: `mvs-${startSec}`, startSec, endSec, shotMode, sectionLabel });++// 90 s song: a quiet cutaway verse (0–30), a lip-synced chorus that sings the+// title (30–60), then a loud instrumental-ish outro with sparse lyrics (60–90).+const project = {+ name: 'Example Song',+ audioAnalysis: { durationSec: 90, waveform: Array.from({ length: 90 }, (_, i) => (i < 30 ? 0.2 : i < 60 ? 0.6 : 0.8)) },+ scenes: [scene(0, 30, 'cutaway', 'Verse 1'), scene(30, 60, 'performance', 'Chorus 1'), scene(60, 90, 'cutaway', 'Outro')],+ lyricCues: [+ ...Array.from({ length: 6 }, (_, i) => line(`verse line ${i}`, i * 5, i * 5 + 4)),+ ...Array.from({ length: 6 }, (_, i) => line(i === 1 ? 'this is my example song' : `chorus line ${i}`, 30 + i * 5, 30 + i * 5 + 4)),+ line('outro line', 70, 74),+ ],+};++describe('suggestSocialCuts (#9280)', () => {+ it('ranks the lip-synced chorus that sings the title first, with its reasons', () => {+ const [best] = suggestSocialCuts(project);+ expect(best.startSec).toBeGreaterThanOrEqual(29);+ expect(best.endSec).toBeLessThanOrEqual(60.5);+ expect(best.endSec - best.startSec).toBeGreaterThanOrEqual(15);+ expect(best.reasons).toEqual(expect.arrayContaining(['chorus', 'sings the title']));+ expect(best.label).toMatch(/chorus line|example song/);+ });++ it('returns non-overlapping windows inside the song and within the length bounds', () => {+ const cuts = suggestSocialCuts(project, { count: 5, minSec: 8, maxSec: 12 });+ expect(cuts.length).toBeGreaterThan(1);+ for (const c of cuts) {+ expect(c.startSec).toBeGreaterThanOrEqual(0);+ expect(c.endSec).toBeLessThanOrEqual(90);+ expect(c.endSec - c.startSec).toBeGreaterThanOrEqual(8 - 1e-9);+ expect(c.endSec - c.startSec).toBeLessThanOrEqual(12 + 1e-9);+ }+ const sorted = [...cuts].sort((a, b) => a.startSec - b.startSec);+ for (let i = 1; i < sorted.length; i++) expect(sorted[i].startSec).toBeGreaterThanOrEqual(sorted[i - 1].endSec);+ });++ it('falls back to evenly spaced windows when the song has no lyric timing', () => {+ const cuts = suggestSocialCuts({ ...project, lyricCues: [] }, { count: 2, minSec: 15, maxSec: 20 });+ expect(cuts).toHaveLength(2);+ expect(cuts.every((c) => Math.abs(c.endSec - c.startSec - 20) < 1e-6)).toBe(true);+ });++ it('offers the whole song when it is shorter than a cut, and nothing without a duration', () => {+ expect(suggestSocialCuts({ audioAnalysis: { durationSec: 9 } })).toEqual([{ startSec: 0, endSec: 9, score: 1, label: null, reasons: ['whole song'] }]);+ expect(suggestSocialCuts({})).toEqual([]);+ });+});