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
[issue-1854] Add beat-quantized timeline arranger with drag-snap and persisted render
[._.]/ Adam Eivy1056422c3eaf
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0c7918f310..96e950eb97 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,10 @@- **[issue-1835] Brain & CoS list endpoints now support opt-in `limit`/`offset` pagination** — `GET /api/brain/people|projects|ideas|admin|memories` and `GET /api/cos/tasks` previously returned their entire backing store with no bound, while sibling endpoints (`GET /api/brain/links`, `GET /api/memory`) already exposed pagination envelopes. Each of these endpoints now accepts `limit`/`offset` query params: when neither is present they return the exact same shape as before (raw array for the brain collections; the `{ user, cos }` grouped structure for tasks), so every existing client keeps working; when a pagination param is passed they return a bounded `{ <collection>, total, limit, offset }` envelope — and for `/api/cos/tasks` the paginated branch windows each source's `tasks` array, adds a `pagination` block, and drops the full-set derived collections (`grouped`, `autoApproved`, `awaitingApproval`) so the response is genuinely bounded rather than re-leaking the whole queue. `limit` defaults to 50 and is clamped to 500. Shared `isPaginationRequested` / `paginateArray` helpers were added to `server/lib/validation.js` alongside the existing `parsePagination`. (#1835)+## Music Video++- **[issue-1854] Beat-quantized timeline arranger: drag-snap scenes to the beat grid.** The director board's scene list now sits above an interactive **beat-grid timeline** (built from the project's cached audio analysis) showing section bands, beats, and downbeats. Drag a scene's left/right edge to trim its in/out point — or drag its body to reposition it — and it snaps to the nearest beat, downbeat, or section boundary within a small tolerance; an unsnapped drop is left exactly where you placed it. Confirmed (snapped) scenes are marked **beat-aligned** and now render *exactly* as arranged: the render's beat-snap step (`beatSnapClips`) honors a beat-aligned scene's saved `startSec`/`endSec` outright instead of re-deriving the cut from whichever beats happen to be nearby at render time. Auto-arranging scenes across the song's sections by energy is filed as a follow-up (#1915). (Closes #1854)+## Security- **`safeUrlFetch` SSRF guard now pins the vetted IP at connect time, closing a DNS-rebinding TOCTOU** — `isPublicHttpUrlSafe` resolved a hostname's DNS to validate it was public, but the subsequent `fetch` re-resolved the same hostname at connect time, so a rebinding host could answer a public address for the check and a loopback/link-local/cloud-metadata address for the actual connection, slipping past the guard. The guard now resolves once and the connection is pinned to that exact validated address via a per-request undici `Agent` whose `connect.lookup` always returns the vetted IP — while Host header and TLS SNI stay the original hostname, so cert validation is unaffected. Every redirect hop is still independently re-validated and re-pinned. (Low real-world exploitability — PortOS is single-user on a private network and URL sources are user-pasted Pinterest boards / stored feeds — but the connect-time re-resolution is now eliminated.) (#1859)diff --git a/client/src/components/musicVideo/BeatTimeline.jsx b/client/src/components/musicVideo/BeatTimeline.jsxnew file mode 100644index 0000000000..3ec97d3388--- /dev/null+++ b/client/src/components/musicVideo/BeatTimeline.jsx@@ -0,0 +1,151 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { buildBeatGridPoints, computeSceneSpans, snapTimeToGrid } from '../../lib/beatGrid.js';++// Beat-quantized timeline arranger for a music-video project's scene board+// (#1854). Renders a beat-grid overlay (section bands, beat/downbeat ticks)+// from the project's cached `audioAnalysis`, plus draggable scene blocks+// whose left/right edges (in/out) and body (reposition) snap to the grid.+// On drag release, `onCommit(sceneId, { startSec, endSec, beatAligned })`+// persists the result via the existing scene PATCH endpoint — the server's+// `beatSnapClips` (server/services/musicVideo/render.js) honors a+// `beatAligned` scene's saved boundaries exactly at render time instead of+// re-deriving them from the live beat grid.++const PX_PER_SEC = 80;+const MIN_SCENE_SEC = 0.3;+const SNAP_TOLERANCE_SEC = 0.15;++export default function BeatTimeline({ audioAnalysis, scenes, onCommit }) {+ const gridPoints = useMemo(() => buildBeatGridPoints(audioAnalysis), [audioAnalysis]);+ const baseSpans = useMemo(+ () => computeSceneSpans(scenes, audioAnalysis?.durationSec),+ [scenes, audioAnalysis?.durationSec],+ );++ // In-flight drag preview, keyed by sceneId — overrides the matching base+ // span while dragging so the block tracks the pointer without round-+ // tripping through the parent's `scenes` prop on every pixel of movement.+ const [liveSpan, setLiveSpan] = useState(null);+ const dragRef = useRef(null);++ const spans = baseSpans.map((span) => (+ liveSpan && liveSpan.sceneId === span.sceneId ? { ...span, ...liveSpan } : span+ ));++ const totalDurationSec = Math.max(audioAnalysis?.durationSec || 0, ...spans.map((s) => s.endSec), 1);+ const widthPx = Math.ceil(totalDurationSec * PX_PER_SEC) + 40;++ const onPointerMove = useCallback((e) => {+ const drag = dragRef.current;+ if (!drag) return;+ const deltaSec = (e.clientX - drag.startClientX) / PX_PER_SEC;+ let nextStart = drag.startSpan.startSec;+ let nextEnd = drag.startSpan.endSec;+ if (drag.kind === 'move') {+ const duration = drag.startSpan.endSec - drag.startSpan.startSec;+ nextStart = Math.max(0, drag.startSpan.startSec + deltaSec);+ nextEnd = nextStart + duration;+ } else if (drag.kind === 'left') {+ nextStart = Math.max(0, Math.min(drag.startSpan.endSec - MIN_SCENE_SEC, drag.startSpan.startSec + deltaSec));+ } else if (drag.kind === 'right') {+ nextEnd = Math.max(drag.startSpan.startSec + MIN_SCENE_SEC, drag.startSpan.endSec + deltaSec);+ }+ let snapped = false;+ if (drag.kind === 'move') {+ const snap = snapTimeToGrid(nextStart, gridPoints, SNAP_TOLERANCE_SEC);+ if (snap) { nextEnd = snap.t + (nextEnd - nextStart); nextStart = snap.t; snapped = true; }+ } else {+ const snapStart = drag.kind === 'left' ? snapTimeToGrid(nextStart, gridPoints, SNAP_TOLERANCE_SEC) : null;+ const snapEnd = drag.kind === 'right' ? snapTimeToGrid(nextEnd, gridPoints, SNAP_TOLERANCE_SEC) : null;+ if (snapStart) { nextStart = snapStart.t; snapped = true; }+ if (snapEnd) { nextEnd = snapEnd.t; snapped = true; }+ }+ setLiveSpan({+ sceneId: drag.sceneId,+ startSec: Number(nextStart.toFixed(3)),+ endSec: Number(nextEnd.toFixed(3)),+ snapped,+ });+ }, [gridPoints]);++ const onPointerUp = useCallback(() => {+ const drag = dragRef.current;+ dragRef.current = null;+ window.removeEventListener('pointermove', onPointerMove);+ window.removeEventListener('pointerup', onPointerUp);+ setLiveSpan((current) => {+ if (drag && current && current.sceneId === drag.sceneId) {+ onCommit?.(drag.sceneId, { startSec: current.startSec, endSec: current.endSec, beatAligned: current.snapped });+ }+ return null;+ });+ }, [onCommit, onPointerMove]);++ // Drop any window listeners left from an in-flight drag if the timeline+ // unmounts mid-gesture (e.g. switching projects while dragging).+ useEffect(() => () => {+ window.removeEventListener('pointermove', onPointerMove);+ window.removeEventListener('pointerup', onPointerUp);+ }, [onPointerMove, onPointerUp]);++ const beginDrag = (e, sceneId, kind, span) => {+ e.preventDefault();+ dragRef.current = { sceneId, kind, startClientX: e.clientX, startSpan: { startSec: span.startSec, endSec: span.endSec } };+ setLiveSpan({ sceneId, startSec: span.startSec, endSec: span.endSec, snapped: false });+ window.addEventListener('pointermove', onPointerMove);+ window.addEventListener('pointerup', onPointerUp);+ };++ if (!audioAnalysis || !scenes || scenes.length === 0) return null;++ return (+ <div className="space-y-1">+ <div className="flex items-center justify-between text-xs text-port-text-muted">+ <span>Beat-quantized timeline — drag a scene's edges to snap to beats, or its body to reposition</span>+ {audioAnalysis.bpm && <span>{audioAnalysis.bpm} BPM</span>}+ </div>+ <div className="overflow-x-auto border border-port-border rounded-lg bg-port-bg">+ <div className="relative h-28" style={{ width: `${widthPx}px`, touchAction: 'none' }}>+ {(audioAnalysis.sections || []).map((section, i) => (+ <div key={`sec-${i}`}+ className="absolute top-0 h-6 border-r border-port-border/60 overflow-hidden"+ style={{ left: section.startSec * PX_PER_SEC, width: Math.max(2, (section.endSec - section.startSec) * PX_PER_SEC) }}+ title={section.label}>+ <span className="absolute top-0.5 left-1 text-[10px] text-port-text-muted truncate max-w-full">{section.label}</span>+ </div>+ ))}+ {(audioAnalysis.beats || []).map((t, i) => (+ <div key={`b-${i}`} className="absolute top-7 bottom-0 w-px bg-port-border" style={{ left: t * PX_PER_SEC }} />+ ))}+ {(audioAnalysis.downbeats || []).map((t, i) => (+ <div key={`db-${i}`} className="absolute top-6 bottom-0 w-px bg-port-accent/60" style={{ left: t * PX_PER_SEC }} />+ ))}+ {spans.map((span, i) => {+ const scene = scenes.find((s) => s.sceneId === span.sceneId);+ const dragging = liveSpan?.sceneId === span.sceneId;+ const snappedNow = dragging && liveSpan.snapped;+ return (+ <div key={span.sceneId}+ className={`absolute top-14 h-12 rounded border bg-port-card/90 select-none ${snappedNow ? 'border-port-success' : 'border-port-accent'}`}+ style={{ left: span.startSec * PX_PER_SEC, width: Math.max(6, (span.endSec - span.startSec) * PX_PER_SEC) }}>+ <div role="presentation"+ className="absolute inset-y-0 left-0 w-2 cursor-ew-resize hover:bg-port-accent/40"+ onPointerDown={(e) => beginDrag(e, span.sceneId, 'left', span)} />+ <div role="presentation"+ className="absolute inset-0 flex items-center justify-center text-[10px] px-2 cursor-grab truncate"+ onPointerDown={(e) => beginDrag(e, span.sceneId, 'move', span)}+ title={scene?.prompt || `Scene #${(scene?.order ?? i) + 1}`}>+ #{(scene?.order ?? i) + 1}+ {scene?.beatAligned && !dragging && <span className="ml-1 text-port-success">●</span>}+ </div>+ <div role="presentation"+ className="absolute inset-y-0 right-0 w-2 cursor-ew-resize hover:bg-port-accent/40"+ onPointerDown={(e) => beginDrag(e, span.sceneId, 'right', span)} />+ </div>+ );+ })}+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex d59dc9ee11..7bf0b4b3bb 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -35,6 +35,7 @@ grep -i "what you want to do" client/src/lib/README.md| `universeStylePreset.js` | Build the client-side style preset that `composeStyledPrompt` layers on top. || `universeRunTag.js` | `buildUniverseSectionRenderTag(universe, kindKey, entry)` — the durable `universeRun` job tag the canon-render call sites (UniverseCanonSection, NounsStage, Story Builder characters step) pass to `generateImage` so the server auto-files the render into the universe collection AND appends it to the entry's `imageRefs[]` (no client follow-up PATCH). || `beatColors.js` | `BEAT_KIND_COLORS` + `getBeatKindColor(kind)` — per-kind display colors for reader-map emotional beats (kinds defined server-side in `storyArc.js`). Keeps every beat visualization consistent. |+| `beatGrid.js` | Music-video beat-quantized timeline arranger (#1854). `buildBeatGridPoints(audioAnalysis)` merges beats/downbeats/section edges into one ranked snap-point list; `snapTimeToGrid(timeSec, gridPoints, toleranceSec)` finds the nearest point within tolerance; `computeSceneSpans(scenes, durationSec)` lays out scenes without a persisted `startSec`/`endSec` contiguously as a display-only fallback. Used by `components/musicVideo/BeatTimeline.jsx`. || `bibleLimits.js` | Mirror of `server/lib/storyBible.js` `BIBLE_LIMITS`. || `catalogTypes.js` | Client mirror of `server/lib/catalogTypes.js` — catalog ingredient type registry (label, badge color, primary-content key/label, snippet fallback chain, per-type editor field list) for the Catalog list/picker/editor. || `editorialRoadmap.js` | `projectAnalyzedPoints` (aggregate roadmap → analyzed chart points with arc-position `frac`) + `dominant` (most-frequent string). Shared by EditorialRoadmapPanel and the Reader Map page. |diff --git a/client/src/lib/beatGrid.js b/client/src/lib/beatGrid.jsnew file mode 100644index 0000000000..730503dcb2--- /dev/null+++ b/client/src/lib/beatGrid.js@@ -0,0 +1,79 @@+// Pure helpers for the music-video beat-quantized timeline arranger (#1854).+// Consumed by client/src/components/musicVideo/BeatTimeline.jsx. Mirrors the+// spirit of the server's shorten-only `beatSnapClips` (server/services/+// musicVideo/render.js) but for INTERACTIVE drag, where a dragged edge can+// move either direction — only the server's at-render safety net is+// shorten-only.++const DEFAULT_TOLERANCE_SEC = 0.15;+const DEFAULT_SCENE_DURATION_SEC = 3;+const KIND_RANK = { beat: 0, downbeat: 1, section: 2 };++// Merge an audioAnalysis record's beats, downbeats, and section start/end+// times into one sorted list of snap points. Section boundaries and+// downbeats are stronger landmarks than plain beats, so near-coincident+// points (within 10ms — e.g. a downbeat landing on a section edge) collapse+// to the single strongest kind rather than offering two near-identical targets.+export function buildBeatGridPoints(audioAnalysis) {+ if (!audioAnalysis) return [];+ const points = [];+ for (const t of audioAnalysis.beats || []) {+ if (typeof t === 'number') points.push({ t, kind: 'beat' });+ }+ for (const t of audioAnalysis.downbeats || []) {+ if (typeof t === 'number') points.push({ t, kind: 'downbeat' });+ }+ for (const s of audioAnalysis.sections || []) {+ if (typeof s?.startSec === 'number') points.push({ t: s.startSec, kind: 'section' });+ if (typeof s?.endSec === 'number') points.push({ t: s.endSec, kind: 'section' });+ }+ const sorted = points.slice().sort((a, b) => a.t - b.t || KIND_RANK[b.kind] - KIND_RANK[a.kind]);+ const merged = [];+ for (const p of sorted) {+ const prev = merged[merged.length - 1];+ if (prev && Math.abs(prev.t - p.t) < 0.01) {+ if (KIND_RANK[p.kind] > KIND_RANK[prev.kind]) merged[merged.length - 1] = p;+ continue;+ }+ merged.push(p);+ }+ return merged;+}++// Snap `timeSec` to the nearest grid point within toleranceSec. Returns the+// snapped { t, kind } point, or null when nothing is close enough (free+// placement — the caller keeps the raw dragged value and beatAligned=false).+export function snapTimeToGrid(timeSec, gridPoints, toleranceSec = DEFAULT_TOLERANCE_SEC) {+ if (!Array.isArray(gridPoints) || gridPoints.length === 0) return null;+ let nearest = null;+ let nearestDist = Infinity;+ for (const p of gridPoints) {+ const dist = Math.abs(p.t - timeSec);+ if (dist < nearestDist) { nearest = p; nearestDist = dist; }+ }+ return nearest && nearestDist <= toleranceSec ? nearest : null;+}++// Scenes without a persisted startSec/endSec need SOME position to render at+// before the user has ever dragged them. Lay those out contiguously after+// the last persisted/placed scene, each defaulting to a few seconds (clamped+// to the analyzed track length when known). Scenes that already carry an+// explicit, valid startSec/endSec keep them untouched. This is a display-only+// fallback — nothing here is persisted until the user actually drags an edge.+export function computeSceneSpans(scenes, durationSec) {+ const ordered = (Array.isArray(scenes) ? scenes : []).slice().sort((a, b) => (a.order ?? 0) - (b.order ?? 0));+ let cursor = 0;+ return ordered.map((scene) => {+ if (typeof scene.startSec === 'number' && typeof scene.endSec === 'number' && scene.endSec > scene.startSec) {+ cursor = Math.max(cursor, scene.endSec);+ return { sceneId: scene.sceneId, startSec: scene.startSec, endSec: scene.endSec, persisted: true };+ }+ const startSec = cursor;+ const naturalEnd = startSec + DEFAULT_SCENE_DURATION_SEC;+ const endSec = typeof durationSec === 'number' && durationSec > startSec+ ? Math.min(naturalEnd, durationSec)+ : naturalEnd;+ cursor = endSec;+ return { sceneId: scene.sceneId, startSec, endSec, persisted: false };+ });+}diff --git a/client/src/lib/beatGrid.test.js b/client/src/lib/beatGrid.test.jsnew file mode 100644index 0000000000..6fdcef5a98--- /dev/null+++ b/client/src/lib/beatGrid.test.js@@ -0,0 +1,96 @@+import { describe, it, expect } from 'vitest';+import { buildBeatGridPoints, snapTimeToGrid, computeSceneSpans } from './beatGrid.js';++describe('buildBeatGridPoints', () => {+ it('returns an empty list with no analysis', () => {+ expect(buildBeatGridPoints(null)).toEqual([]);+ });++ it('merges beats, downbeats, and section edges, sorted by time', () => {+ const points = buildBeatGridPoints({+ beats: [0, 0.5, 1],+ downbeats: [0],+ sections: [{ label: 'Section 1', startSec: 0, endSec: 1 }],+ });+ expect(points.map((p) => p.t)).toEqual([0, 0.5, 1]);+ });++ it('collapses near-identical timestamps to the strongest kind', () => {+ // A downbeat at 1.0 and a section edge at 1.005 are the "same" landmark.+ const points = buildBeatGridPoints({+ beats: [1.0],+ downbeats: [1.0],+ sections: [{ label: 'Section 1', startSec: 0, endSec: 1.005 }],+ });+ expect(points).toHaveLength(2); // 0 and the merged ~1.0 point+ const merged = points.find((p) => Math.abs(p.t - 1.0) < 0.02);+ expect(merged.kind).toBe('section'); // section outranks downbeat outranks beat+ });++ it('ignores malformed entries', () => {+ const points = buildBeatGridPoints({ beats: [null, undefined, 'x', 1], downbeats: [], sections: [] });+ expect(points).toEqual([{ t: 1, kind: 'beat' }]);+ });+});++describe('snapTimeToGrid', () => {+ const grid = [{ t: 1, kind: 'beat' }, { t: 2, kind: 'downbeat' }, { t: 4, kind: 'section' }];++ it('returns null with no grid points', () => {+ expect(snapTimeToGrid(1, [])).toBeNull();+ expect(snapTimeToGrid(1, null)).toBeNull();+ });++ it('snaps to the nearest point within tolerance', () => {+ expect(snapTimeToGrid(1.05, grid, 0.15)).toEqual({ t: 1, kind: 'beat' });+ });++ it('returns null when nothing is within tolerance', () => {+ expect(snapTimeToGrid(2.6, grid, 0.15)).toBeNull();+ });++ it('picks the closer of two candidates', () => {+ expect(snapTimeToGrid(1.6, grid, 1)).toEqual({ t: 2, kind: 'downbeat' });+ });+});++describe('computeSceneSpans', () => {+ it('returns an empty array with no scenes', () => {+ expect(computeSceneSpans(null)).toEqual([]);+ expect(computeSceneSpans([])).toEqual([]);+ });++ it('keeps an explicit, valid startSec/endSec untouched', () => {+ const spans = computeSceneSpans([{ sceneId: 's1', order: 0, startSec: 2, endSec: 5 }]);+ expect(spans).toEqual([{ sceneId: 's1', startSec: 2, endSec: 5, persisted: true }]);+ });++ it('lays out scenes without a position contiguously in order', () => {+ const spans = computeSceneSpans([+ { sceneId: 's2', order: 1 },+ { sceneId: 's1', order: 0 },+ ]);+ expect(spans).toEqual([+ { sceneId: 's1', startSec: 0, endSec: 3, persisted: false },+ { sceneId: 's2', startSec: 3, endSec: 6, persisted: false },+ ]);+ });++ it('resumes the fallback cursor after a persisted scene', () => {+ const spans = computeSceneSpans([+ { sceneId: 's1', order: 0, startSec: 0, endSec: 10 },+ { sceneId: 's2', order: 1 },+ ]);+ expect(spans[1]).toEqual({ sceneId: 's2', startSec: 10, endSec: 13, persisted: false });+ });++ it('clamps a fallback span to the track duration when known', () => {+ const spans = computeSceneSpans([{ sceneId: 's1', order: 0 }], 1.5);+ expect(spans[0]).toEqual({ sceneId: 's1', startSec: 0, endSec: 1.5, persisted: false });+ });++ it('treats a non-positive endSec<=startSec pair as not persisted', () => {+ const spans = computeSceneSpans([{ sceneId: 's1', order: 0, startSec: 5, endSec: 5 }]);+ expect(spans[0]).toEqual({ sceneId: 's1', startSec: 0, endSec: 3, persisted: false });+ });+});diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 5f1785cf44..c4c8c777e7 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -17,6 +17,7 @@ export * from './universeStylePreset.js';// === Pipeline / image-gen defaults ===export * from './beatColors.js';+export * from './beatGrid.js';export * from './bibleLimits.js';export * from './catalogTypes.js';export * from './editorialRoadmap.js';diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex ec737fe9d1..ccc0ff74fe 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -18,6 +18,7 @@ import {import { generateImage } from '../services/apiSystem.js';import { generateVideo } from '../services/apiImageVideo.js';import { listTracks } from '../services/apiTracks.js';+import BeatTimeline from '../components/musicVideo/BeatTimeline.jsx';import useSceneRenderLifecycle from '../hooks/useSceneRenderLifecycle.js';import { useSseProgress, isTerminalSseFrame } from '../hooks/useSseProgress.js';import { formatDurationSec } from '../utils/formatters.js';@@ -201,6 +202,12 @@ export default function MusicVideo() {updateMusicVideoScene(selected.id, sceneId, patch, { silent: true }).catch((err) => toast.error(err?.message || 'Failed to save scene'));};+ // BeatTimeline drag commit — same optimistic-local + silent-PATCH pattern as+ // the other scene field editors (#1854).+ const commitSceneTiming = (sceneId, patch) => {+ editSceneLocal(sceneId, patch);+ saveScene(sceneId, patch);+ };const handleDeleteScene = (sceneId) => {deleteMusicVideoScene(selected.id, sceneId)@@ -405,6 +412,10 @@ export default function MusicVideo() {)}</div>+ {selected.audioAnalysis && (selected.scenes || []).length > 0 && (+ <BeatTimeline audioAnalysis={selected.audioAnalysis} scenes={selected.scenes} onCommit={commitSceneTiming} />+ )}+<div className="flex items-center justify-between"><h3 className="text-sm font-medium">Scene board</h3><button onClick={handleAddScene} className="flex items-center gap-1 bg-port-accent text-white rounded px-2 py-1.5 text-sm min-h-[40px] sm:min-h-0">diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.jsindex 8ab1947af3..641fdb1a12 100644--- a/server/services/musicVideo/render.js+++ b/server/services/musicVideo/render.js@@ -10,10 +10,14 @@* one external audio input as the sole output audio, ended on `-shortest` so the* render runs only as long as the shorter of (video, track).*- * Lightweight beat-snap: when the project carries a cached beat analysis, each- * cut is trimmed back to the nearest beat (never extended — a clip can't grow),- * so cuts land on the music. With no analysis the clips render at their natural- * length. The full beat-quantized arranger is a follow-up.+ * Beat-snap: when the project carries a cached beat analysis, each cut is+ * trimmed back to the nearest beat (never extended — a clip can't grow), so+ * cuts land on the music. With no analysis the clips render at their natural+ * length. A scene the director has explicitly arranged on the beat-quantized+ * timeline (#1854 — `startSec`/`endSec`/`beatAligned` saved via drag-snap in+ * the client) skips this live re-derivation entirely: its saved boundaries+ * are honored exactly, so the render matches what was shown on the timeline+ * rather than whatever the current beat grid would produce.*/import { spawn } from 'child_process';@@ -154,12 +158,35 @@ export async function resolveSceneClips(project) {// at least `minClipSec` long. Snapping only ever SHORTENS a clip (a clip can't// be extended past its rendered length), so a cut can move earlier onto a beat// but never later. Returns a NEW clips array with adjusted `outSec`/`duration`.-// With no beats (no analysis) the clips are returned unchanged.-export function beatSnapClips(clips, beats, { toleranceSec = 0.12, minClipSec = 0.4 } = {}) {+// With no beats (no analysis) and no persisted scene arrangement, clips are+// returned unchanged.+//+// `scenes` (optional) is the project's scene list — when a clip's matching+// scene has `beatAligned: true` and a valid `startSec`/`endSec` (persisted by+// the BeatTimeline drag-snap arranger, #1854), that scene's saved duration is+// honored EXACTLY instead of being re-derived from the live beat grid: the+// director already snapped and saved it, so the render shouldn't silently+// recompute a different cut from whatever the grid says today. Clamped to the+// clip's own rendered length (a saved duration can't make a clip longer than+// what was actually generated) and to `minClipSec`. The running cursor still+// advances by the honored duration so any later, non-aligned clips keep+// snapping against the correct cumulative position.+export function beatSnapClips(clips, beats, { toleranceSec = 0.12, minClipSec = 0.4, scenes = null } = {}) {const grid = Array.isArray(beats) ? beats.filter((b) => typeof b === 'number' && b >= 0).sort((a, b) => a - b) : [];- if (grid.length === 0) return clips.map((c) => ({ ...c }));+ const scenesById = Array.isArray(scenes) ? new Map(scenes.map((s) => [s.sceneId, s])) : null;+ if (grid.length === 0 && !scenesById) return clips.map((c) => ({ ...c }));let running = 0;return clips.map((clip) => {+ const scene = scenesById?.get(clip.sceneId);+ if (scene?.beatAligned && typeof scene.startSec === 'number' && typeof scene.endSec === 'number' && scene.endSec > scene.startSec) {+ const outSec = Math.min(clip.duration, Math.max(minClipSec, scene.endSec - scene.startSec));+ running += outSec;+ return { ...clip, inSec: 0, outSec, duration: outSec };+ }+ if (grid.length === 0) {+ running += clip.duration;+ return { ...clip };+ }const naturalEnd = running + clip.duration;// Nearest beat at or before the natural end (snap trims, never extends).let best = null;@@ -255,7 +282,7 @@ export async function renderMusicVideo(projectId) {const rawClips = await resolveSceneClips(project);const audioDurationSec = await probeVideoDuration(audioPath).catch(() => null);const beats = project.audioAnalysis?.beats;- const clips = beatSnapClips(rawClips, beats);+ const clips = beatSnapClips(rawClips, beats, { scenes: project.scenes });await ensureDir(PATHS.videos);await ensureDir(PATHS.videoThumbnails);diff --git a/server/services/musicVideo/render.test.js b/server/services/musicVideo/render.test.jsindex bccc95f403..a0acb71435 100644--- a/server/services/musicVideo/render.test.js+++ b/server/services/musicVideo/render.test.js@@ -101,6 +101,59 @@ describe('beatSnapClips', () => {expect(out[0].outSec).toBeCloseTo(1.95, 5);expect(out[1].outSec).toBeCloseTo(1.95, 5); // 3.9 - 1.95});++ // #1854 — a director-arranged scene's saved startSec/endSec is honored+ // exactly, bypassing live re-derivation from the beat grid.+ describe('with a persisted scene arrangement', () => {+ it('honors a beatAligned scene\'s saved duration instead of the live grid', () => {+ const scenes = [{ sceneId: 's1', startSec: 10, endSec: 11.2, beatAligned: true }];+ // Without the override, the nearest beat (1.95) would trim the clip to 1.95s.+ const out = beatSnapClips([clip({ sceneId: 's1', duration: 2, outSec: 2 })], [1.95], { toleranceSec: 0.12, scenes });+ expect(out[0].outSec).toBeCloseTo(1.2, 5); // 11.2 - 10+ expect(out[0].duration).toBeCloseTo(1.2, 5);+ });++ it('clamps a persisted duration to the clip\'s own rendered length', () => {+ const scenes = [{ sceneId: 's1', startSec: 0, endSec: 100, beatAligned: true }];+ const out = beatSnapClips([clip({ sceneId: 's1', duration: 2, outSec: 2 })], null, { scenes });+ expect(out[0].outSec).toBe(2);+ });++ it('clamps a persisted duration to minClipSec', () => {+ const scenes = [{ sceneId: 's1', startSec: 0, endSec: 0.05, beatAligned: true }];+ const out = beatSnapClips([clip({ sceneId: 's1', duration: 2, outSec: 2 })], null, { scenes, minClipSec: 0.4 });+ expect(out[0].outSec).toBeCloseTo(0.4, 5);+ });++ it('falls back to live beat-snapping for a scene without beatAligned set', () => {+ const scenes = [{ sceneId: 's1', startSec: 10, endSec: 11.2, beatAligned: false }];+ const out = beatSnapClips([clip({ sceneId: 's1', duration: 2, outSec: 2 })], [1.95], { toleranceSec: 0.12, scenes });+ expect(out[0].outSec).toBeCloseTo(1.95, 5);+ });++ it('falls back to live beat-snapping when startSec/endSec are missing', () => {+ const scenes = [{ sceneId: 's1', beatAligned: true, startSec: null, endSec: null }];+ const out = beatSnapClips([clip({ sceneId: 's1', duration: 2, outSec: 2 })], [1.95], { toleranceSec: 0.12, scenes });+ expect(out[0].outSec).toBeCloseTo(1.95, 5);+ });++ it('advances the running cursor by the honored duration for later clips', () => {+ const scenes = [{ sceneId: 's1', startSec: 0, endSec: 1, beatAligned: true }];+ // clip0 honored at 1.0s exactly; clip1 (no scene match) natural end = 1+2=3, beat at 2.95 → 2.95-1=1.95.+ const out = beatSnapClips(+ [clip({ sceneId: 's1', duration: 2, outSec: 2 }), clip({ sceneId: 's2', duration: 2, outSec: 2 })],+ [2.95],+ { toleranceSec: 0.12, scenes },+ );+ expect(out[0].outSec).toBeCloseTo(1, 5);+ expect(out[1].outSec).toBeCloseTo(1.95, 5);+ });++ it('returns clips unchanged with no beat grid and no matching scenes', () => {+ const out = beatSnapClips([clip({ sceneId: 's1', duration: 2, outSec: 2 })], null, { scenes: [] });+ expect(out[0].outSec).toBe(2);+ });+ });});describe('resolveSceneClips', () => {