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] Fix beat-timeline drag-snap correctness gaps found in review
[._.]/ Adam Eivydec59b1ceb06
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 4f06431383..9d65803be6 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -9,7 +9,7 @@## 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)+- **[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 right edge to trim how long it plays, or drag its body to reposition it — both snap to the nearest beat, downbeat, or section boundary within a small tolerance; an unsnapped drop is left exactly where you placed it. A confirmed (snapped) length-trim is marked **beat-aligned** and now renders *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 — a reposition-only drag never marks a scene beat-aligned unless it already had a real, explicitly-set duration, so simply nudging a freshly-added scene can't silently crop its clip down to the timeline's placeholder length. Auto-arranging scenes across the song's sections by energy is filed as a follow-up (#1915). (Closes #1854)- **[issue-1915] Auto-arrange scenes across song sections by energy.** A one-click **Auto-arrange** button on the Music Video scene board distributes every scene across the analyzed song's sections weighted by each section's energy — louder sections get more (shorter) cuts, calmer sections get fewer (longer) ones — and writes the same persisted `startSec`/`endSec`/`beatAligned` fields the manual drag-snap arranger (#1854) writes, so the result is a director-tunable starting point honored exactly at render time. The offline audio analysis now records a normalized 0..1 `energy` per section (additive/optional — older cached analyses fall back to an even spread; re-run **Analyze** to populate it). The distribution is a pure, isolated helper — `autoArrangeScenes(scenes, audioAnalysis)` in `client/src/lib/beatGrid.js` (largest-remainder allocation by energy weight, interior cuts snapped to the beat grid) — unit-tested independently of the UI. (Closes #1915)diff --git a/client/src/components/musicVideo/BeatTimeline.jsx b/client/src/components/musicVideo/BeatTimeline.jsxindex 3ec97d3388..1f3f132533 100644--- a/client/src/components/musicVideo/BeatTimeline.jsx+++ b/client/src/components/musicVideo/BeatTimeline.jsx@@ -1,18 +1,20 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { buildBeatGridPoints, computeSceneSpans, snapTimeToGrid } from '../../lib/beatGrid.js';+import { buildBeatGridPoints, computeDragSpan, computeSceneSpans, shouldMarkBeatAligned } 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.+// whose right edge (out-point) and body (reposition) snap to the grid. There+// is intentionally no left-edge/in-point handle — `beatSnapClips`+// (server/services/musicVideo/render.js) always trims a clip from its own+// frame 0, so it has no way to honor a distinct in-point; offering that+// handle would promise behavior the render can't deliver.// 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.+// `beatSnapClips` 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 }) {@@ -39,33 +41,8 @@ export default function BeatTimeline({ audioAnalysis, scenes, onCommit }) {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,- });+ const result = computeDragSpan({ kind: drag.kind, startSpan: drag.startSpan, deltaSec, gridPoints, toleranceSec: SNAP_TOLERANCE_SEC });+ setLiveSpan({ sceneId: drag.sceneId, ...result });}, [gridPoints]);const onPointerUp = useCallback(() => {@@ -75,7 +52,8 @@ export default function BeatTimeline({ audioAnalysis, scenes, onCommit }) {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 });+ const beatAligned = shouldMarkBeatAligned({ kind: drag.kind, snapped: current.snapped, wasPersisted: drag.wasPersisted });+ onCommit?.(drag.sceneId, { startSec: current.startSec, endSec: current.endSec, beatAligned });}return null;});@@ -90,7 +68,11 @@ export default function BeatTimeline({ audioAnalysis, scenes, onCommit }) {const beginDrag = (e, sceneId, kind, span) => {e.preventDefault();- dragRef.current = { sceneId, kind, startClientX: e.clientX, startSpan: { startSec: span.startSec, endSec: span.endSec } };+ dragRef.current = {+ sceneId, kind, startClientX: e.clientX,+ startSpan: { startSec: span.startSec, endSec: span.endSec },+ wasPersisted: !!span.persisted,+ };setLiveSpan({ sceneId, startSec: span.startSec, endSec: span.endSec, snapped: false });window.addEventListener('pointermove', onPointerMove);window.addEventListener('pointerup', onPointerUp);@@ -101,7 +83,7 @@ export default function BeatTimeline({ audioAnalysis, scenes, onCommit }) {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>+ <span>Beat-quantized timeline — drag a scene's right edge to trim its length, 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">@@ -128,9 +110,6 @@ export default function BeatTimeline({ audioAnalysis, scenes, onCommit }) {<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)}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 91deda005c..98529a6573 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -35,7 +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; `autoArrangeScenes(scenes, audioAnalysis)` proposes a full `{ sceneId, startSec, endSec, beatAligned }[]` arrangement by distributing scenes across song sections weighted by each section's `energy` (#1915). Used by `components/musicVideo/BeatTimeline.jsx` and `pages/MusicVideo.jsx`. |+| `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; `computeDragSpan({kind, startSpan, deltaSec, gridPoints, ...})` resolves a timeline drag gesture (`'move'` or `'right'` — no `'left'`, since the render can only trim from a clip's own frame 0) into a new span; `shouldMarkBeatAligned({kind, snapped, wasPersisted})` gates the `beatAligned` flag so a reposition-only drag can't silently promote an unpersisted scene's placeholder fallback duration into a "saved exactly" render duration; `autoArrangeScenes(scenes, audioAnalysis)` proposes a full `{ sceneId, startSec, endSec, beatAligned }[]` arrangement by distributing scenes across song sections weighted by each section's `energy` (#1915). Used by `components/musicVideo/BeatTimeline.jsx` and `pages/MusicVideo.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.jsindex 61a10e8c55..89966cbfc1 100644--- a/client/src/lib/beatGrid.js+++ b/client/src/lib/beatGrid.js@@ -7,6 +7,7 @@const DEFAULT_TOLERANCE_SEC = 0.15;const DEFAULT_SCENE_DURATION_SEC = 3;+const MIN_SCENE_SEC = 0.3;const KIND_RANK = { beat: 0, downbeat: 1, section: 2 };// Merge an audioAnalysis record's beats, downbeats, and section start/end@@ -235,3 +236,45 @@ export function autoArrangeScenes(scenes, audioAnalysis, { minSceneSec = DEFAULT}return result;}++// Resolve a BeatTimeline drag gesture (pointer delta in seconds) into a new+// span, snapping to the grid when the result lands within tolerance. `kind`+// is `'move'` (reposition the whole block, duration unchanged) or `'right'`+// (drag the out-point — the render can only ever shorten/lengthen a clip+// from its own frame 0, so there is no `'left'`/in-point equivalent; see+// `server/services/musicVideo/render.js` `beatSnapClips`, which always trims+// from `inSec: 0`).+export function computeDragSpan({ kind, startSpan, deltaSec, gridPoints, toleranceSec = DEFAULT_TOLERANCE_SEC, minSceneSec = MIN_SCENE_SEC }) {+ let nextStart = startSpan.startSec;+ let nextEnd = startSpan.endSec;+ if (kind === 'move') {+ const duration = startSpan.endSec - startSpan.startSec;+ nextStart = Math.max(0, startSpan.startSec + deltaSec);+ nextEnd = nextStart + duration;+ } else {+ nextEnd = Math.max(startSpan.startSec + minSceneSec, startSpan.endSec + deltaSec);+ }+ let snapped = false;+ if (kind === 'move') {+ const snap = snapTimeToGrid(nextStart, gridPoints, toleranceSec);+ if (snap) { nextEnd = snap.t + (nextEnd - nextStart); nextStart = snap.t; snapped = true; }+ } else {+ const snap = snapTimeToGrid(nextEnd, gridPoints, toleranceSec);+ if (snap) { nextEnd = snap.t; snapped = true; }+ }+ return { startSec: Number(nextStart.toFixed(3)), endSec: Number(nextEnd.toFixed(3)), snapped };+}++// A snapped drag earns the `beatAligned` flag (render honors the saved+// duration exactly — see `beatSnapClips`) only when the resulting DURATION is+// trustworthy. A `'right'` resize is always an explicit, intentional+// duration-setting action, so it always qualifies. A `'move'` never touches+// duration — it only repositions the block — so confirming it must NOT+// silently promote an unpersisted scene's synthetic `computeSceneSpans`+// fallback span (3s, unrelated to the scene's real generated clip length)+// into a "saved exactly" render duration. Only a move on an already-persisted+// span (a real duration the user previously set) can mark beatAligned.+export function shouldMarkBeatAligned({ kind, snapped, wasPersisted }) {+ if (!snapped) return false;+ return kind !== 'move' || !!wasPersisted;+}diff --git a/client/src/lib/beatGrid.test.js b/client/src/lib/beatGrid.test.jsindex 57ae4606ab..46cfe0cfaa 100644--- a/client/src/lib/beatGrid.test.js+++ b/client/src/lib/beatGrid.test.js@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest';-import { buildBeatGridPoints, snapTimeToGrid, computeSceneSpans, autoArrangeScenes } from './beatGrid.js';+import { buildBeatGridPoints, snapTimeToGrid, computeSceneSpans, computeDragSpan, shouldMarkBeatAligned, autoArrangeScenes } from './beatGrid.js';describe('buildBeatGridPoints', () => {it('returns an empty list with no analysis', () => {@@ -249,3 +249,62 @@ describe('autoArrangeScenes', () => {expect(out.map((a) => a.sceneId)).toEqual(['s1', 's2']);});});++describe('computeDragSpan', () => {+ const grid = [{ t: 5, kind: 'beat' }, { t: 10, kind: 'downbeat' }];++ it('repositions both edges on a move, preserving duration', () => {+ const result = computeDragSpan({ kind: 'move', startSpan: { startSec: 2, endSec: 4 }, deltaSec: 1, gridPoints: [] });+ expect(result).toEqual({ startSec: 3, endSec: 5, snapped: false });+ });++ it('snaps a move to the nearest grid point and shifts the end by the same offset', () => {+ const result = computeDragSpan({ kind: 'move', startSpan: { startSec: 2, endSec: 4 }, deltaSec: 2.9, gridPoints: grid, toleranceSec: 0.2 });+ // raw start = 4.9, snaps to the beat at 5; duration (2) is preserved.+ expect(result).toEqual({ startSec: 5, endSec: 7, snapped: true });+ });++ it('never moves a move-drag start below 0', () => {+ const result = computeDragSpan({ kind: 'move', startSpan: { startSec: 1, endSec: 3 }, deltaSec: -5, gridPoints: [] });+ expect(result.startSec).toBe(0);+ expect(result.endSec).toBe(2); // duration preserved+ });++ it('only moves the end on a right-edge drag, start untouched', () => {+ const result = computeDragSpan({ kind: 'right', startSpan: { startSec: 2, endSec: 4 }, deltaSec: 1, gridPoints: [] });+ expect(result).toEqual({ startSec: 2, endSec: 5, snapped: false });+ });++ it('snaps a right-edge drag to the nearest grid point', () => {+ const result = computeDragSpan({ kind: 'right', startSpan: { startSec: 2, endSec: 4.9 }, deltaSec: 0, gridPoints: grid, toleranceSec: 0.2 });+ expect(result).toEqual({ startSec: 2, endSec: 5, snapped: true });+ });++ it('clamps a right-edge drag to minSceneSec', () => {+ const result = computeDragSpan({ kind: 'right', startSpan: { startSec: 2, endSec: 4 }, deltaSec: -10, gridPoints: [], minSceneSec: 0.5 });+ expect(result.endSec).toBeCloseTo(2.5, 5);+ });+});++describe('shouldMarkBeatAligned', () => {+ it('is false when the drag did not snap, regardless of kind', () => {+ expect(shouldMarkBeatAligned({ kind: 'right', snapped: false, wasPersisted: true })).toBe(false);+ expect(shouldMarkBeatAligned({ kind: 'move', snapped: false, wasPersisted: true })).toBe(false);+ });++ it('a snapped right-edge (explicit duration-setting) drag is always beat-aligned', () => {+ expect(shouldMarkBeatAligned({ kind: 'right', snapped: true, wasPersisted: false })).toBe(true);+ expect(shouldMarkBeatAligned({ kind: 'right', snapped: true, wasPersisted: true })).toBe(true);+ });++ it('a snapped move on an unpersisted (fallback) span is NOT beat-aligned', () => {+ // Reposition-only drags never set a duration — confirming one on a scene+ // whose span is still the computeSceneSpans placeholder must not bake+ // that synthetic duration in as the render's "saved exactly" length.+ expect(shouldMarkBeatAligned({ kind: 'move', snapped: true, wasPersisted: false })).toBe(false);+ });++ it('a snapped move on an already-persisted span IS beat-aligned', () => {+ expect(shouldMarkBeatAligned({ kind: 'move', snapped: true, wasPersisted: true })).toBe(true);+ });+});diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.jsindex 641fdb1a12..54fa1552f1 100644--- a/server/services/musicVideo/render.js+++ b/server/services/musicVideo/render.js@@ -179,6 +179,10 @@ export function beatSnapClips(clips, beats, { toleranceSec = 0.12, minClipSec =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) {+ // inSec stays 0 here deliberately: this only ever trims how much of the+ // clip plays, never which frames — there is no in-point/out-point+ // distinction. The BeatTimeline client intentionally exposes only a+ // right-edge (out-point) trim handle for the same reason (#1854).const outSec = Math.min(clip.duration, Math.max(minClipSec, scene.endSec - scene.startSec));running += outSec;return { ...clip, inSec: 0, outSec, duration: outSec };