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
add layered timeline editing: stills, overlays, fades and an audio bed (#4873)
[._.]/ Adam Eivy760fc0d7a449
diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 1574fd4fa9..7ada22d180 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -200,5 +200,6 @@ grep -i "what you want to do" client/src/lib/README.md| `threejsSculpt.js` | Three.js construction helpers for the validated procedural sculpt spec (`server/lib/threejsModel.js`) used by the Three.js Models preview. `createSculptBufferGeometry(definition)` builds the schema forms r3f has no direct element for — `custom` (indexed BufferGeometry), `extrude` (closed 2D outline + holes swept to `depth`, optional bevel) and `tube` (CatmullRom path swept at `radius`) — returning null for primitives, which stay declarative; callers own disposal. `needsSculptBufferGeometry(definition)` is the matching predicate. `sculptMaterialProps(definition, envMapIntensity)` maps a material definition to its Three.js props, forwarding the physical-only channels (`clearcoat`, `ior`, `transmission`, `thickness`, `sheen`, `iridescence`, `anisotropy`) only for `type: physical`, and the spec-level `environment.intensity` as `envMapIntensity` on every lit material (`basic` is unlit and takes none). Mirrors the `createGeometry`/`createMaterial` bodies `buildThreejsFactorySource()` emits, so the preview and the exported standalone factory render the same scene. || `universeBuilderShared.js` | Shared constants + pure category/trunk/composite helpers for the Universe Builder page and its extracted tab/editor components (#2374): `TRUNK_TABS`/`TRUNK_BY_ID`/`TRUNK_BY_KIND`, `TAB_*` + `BUCKET_CANON`, `CATEGORY_LABELS`, `DEFAULT_RENDER_OPTS`, `COMPOSITE_BOARD_KINDS`; and helpers `groupBucketsByKind`, `normalizeCategoryKey`, `humanizeCategory`, `ensureDraftCategories`, `getCategoryKeys`, `compositeKindLabel`. No React state — safe to import from the page or any tab component without a cycle. || `universeBuilderCounts.js` | Pure prompt-count helpers for the Universe Builder render buttons (#2374), mirroring the server's compile/skip rules so inline counts match what `/render` will enqueue: `totalVariationCount`, `canonEntryHasContent`, `countCanonWithContent`, `renderPromptCount`, `scopedPromptCount`. The server `compilePrompts`/`synthesizeCanonPrompt` copy is authoritative — keep in sync. |+| `videoTimelineModel.js` | Pure model helpers for the layered video timeline, mirroring `server/services/videoTimeline/segments.js` so the browser preview and the ffmpeg export make the same cut/geometry/mix decisions: `segmentDuration`/`timelineDuration`/`segmentStarts`/`findSegmentAt` (project-time ↔ segment mapping), `fadeMultiplier` (linear, matching ffmpeg's default `tri` curve), `overlayOpacityAt`, `audioTrackStateAt`, `assetUrl(assetKind, assetFile)`, and the save helpers `stripKey`/`withKeys`/`timelinePatch`. Change a rule here and in the server module in the same commit. || `wrSceneCursor.js` | Resolve which script scene the editor caret sits in (`sceneAtCursor`, `sceneAnchorIndex`) — inverse of WorkEditor's jump-to-scene text search; drives the live render preview's "scene at cursor" target. || `writingGuide.js` | Canonical Writers Room reference data + craft principles rendered by the Guide page (`/writers-room/guide`): `WRITING_LENGTH_TARGETS` (microfiction→novel word/char bands), `BOOK_LENGTH_ESTIMATES` (page-based), `WRITING_PRINCIPLES`, `PLANNED_ANALYSES` (e.g. the emotional-roadmap evaluator), and `classifyByWordCount(n)` for labelling a draft's length. Future word-count gauges / length checks read from here so targets don't drift from the docs. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex ed47b0b8f0..5afed2b04a 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -167,6 +167,7 @@ export * from './tribe.js';export * from './quotaBurnPatch.js';export * from './tribeCadence.js';export * from './universeBuilderExpand.js';+export * from './videoTimelineModel.js';export * from './uuid.js';export * from './webglSupport.js';export * from './wrSceneCursor.js';diff --git a/client/src/lib/videoTimelineModel.js b/client/src/lib/videoTimelineModel.jsnew file mode 100644index 0000000000..63d83e8447--- /dev/null+++ b/client/src/lib/videoTimelineModel.js@@ -0,0 +1,133 @@+/**+ * Pure model helpers for the layered video timeline (schemaVersion 2).+ *+ * Mirrors server/services/videoTimeline/segments.js so the browser preview and+ * the ffmpeg export make the SAME cut, geometry, and mix decisions — the whole+ * point of the lane model is that what the editor shows is what renders. When+ * a rule changes on one side (fade curve, overlay placement, asset kinds),+ * change it on the other in the same commit.+ *+ * No React, no I/O — safe to import from the page, its child components, and+ * tests alike.+ */++export const TIMELINE_SCHEMA_VERSION = 2;++export const IMAGE_ASSET_KINDS = ['images', 'video-thumbnails'];+export const AUDIO_ASSET_KINDS = ['audio', 'music'];++// data/ subdirectory → the URL prefix the server exposes it under.+const ASSET_URL_PREFIX = {+ images: '/data/images',+ 'video-thumbnails': '/data/video-thumbnails',+ audio: '/data/audio',+ music: '/data/music',+};++/** Browser URL for an `{ assetKind, assetFile }` pair, or null when unknown. */+export const assetUrl = (assetKind, assetFile) => {+ const prefix = ASSET_URL_PREFIX[assetKind];+ if (!prefix || !assetFile) return null;+ return `${prefix}/${encodeURIComponent(assetFile)}`;+};++/** Project-time length a video-lane segment occupies. */+export const segmentDuration = (segment) => {+ if (!segment) return 0;+ if (segment.type === 'still') return Math.max(0, segment.durationSec || 0);+ return Math.max(0, (segment.outSec || 0) - (segment.inSec || 0));+};++export const timelineDuration = (segments) => (segments || []).reduce((sum, s) => sum + segmentDuration(s), 0);++/**+ * Map project-time `t` to the (segmentIndex, withinSegmentSec) pair the+ * preview needs. The strict `t < acc + dur` comparison falls through on exact+ * boundaries so a playhead landing on a seam shows the NEXT segment, not the+ * last frame of the prior one.+ */+export const findSegmentAt = (segments, t) => {+ let acc = 0;+ for (let i = 0; i < segments.length; i++) {+ const dur = segmentDuration(segments[i]);+ if (t < acc + dur || i === segments.length - 1) {+ return { index: i, within: Math.max(0, t - acc), startAtProj: acc };+ }+ acc += dur;+ }+ return { index: -1, within: 0, startAtProj: 0 };+};++/**+ * Fade multiplier at `within` seconds into something `duration` long.+ *+ * Linear, matching ffmpeg's default `fade`/`afade` curve (`tri`). A zero-length+ * fade returns 1 rather than dividing by zero, and the two fades multiply where+ * they overlap — the server refuses to persist an overlapping pair, but a+ * probe-clamped duration can create one at render time.+ */+export const fadeMultiplier = (fadeInSec, fadeOutSec, duration, within) => {+ if (!(duration > 0)) return 1;+ const clamped = Math.min(Math.max(within, 0), duration);+ let m = 1;+ if (fadeInSec > 0) m *= Math.min(1, clamped / fadeInSec);+ if (fadeOutSec > 0) m *= Math.min(1, (duration - clamped) / fadeOutSec);+ return Math.min(1, Math.max(0, m));+};++/**+ * Effective opacity of an overlay at project-time `t` — 0 outside its window,+ * its configured opacity inside, scaled by whichever alpha fade is active.+ */+export const overlayOpacityAt = (overlay, t) => {+ if (!overlay) return 0;+ const start = overlay.startSec || 0;+ const dur = Math.max(0, overlay.durationSec || 0);+ if (dur <= 0 || t < start || t > start + dur) return 0;+ const base = overlay.opacity == null ? 1 : overlay.opacity;+ return base * fadeMultiplier(overlay.fadeInSec || 0, overlay.fadeOutSec || 0, dur, t - start);+};++/**+ * Where an audio track sits relative to project-time `t`.+ * `active` is false outside its window; `within` is seconds into the track's+ * own (already offset) timeline, which is what the preview element seeks to.+ */+export const audioTrackStateAt = (track, t) => {+ const start = track?.startSec || 0;+ const dur = Math.max(0, track?.durationSec || 0);+ const active = dur > 0 && t >= start && t < start + dur;+ const within = Math.min(Math.max(t - start, 0), dur);+ const volume = active+ ? (track.volume == null ? 1 : track.volume)+ * fadeMultiplier(track.fadeInSec || 0, track.fadeOutSec || 0, dur, within)+ : 0;+ return { active, within, sourceTime: (track?.offsetSec || 0) + within, volume };+};++/** Drop the client-only `_key` identity dnd-kit needs before PATCHing. */+export const stripKey = (entry) => {+ if (!entry || typeof entry !== 'object') return entry;+ const { _key, ...rest } = entry;+ return rest;+};++/**+ * The PATCH body for a timeline save. Lanes are sent whole — the server+ * replaces each lane it receives — and `_key`s are stripped so they never+ * reach the persisted project.+ */+export const timelinePatch = ({ segments, overlays, audio }) => ({+ segments: (segments || []).map(stripKey),+ overlays: (overlays || []).map(stripKey),+ audio: {+ clipVolume: audio?.clipVolume == null ? 1 : audio.clipVolume,+ tracks: (audio?.tracks || []).map(stripKey),+ },+});++/** Stable dnd/React identity for a lane entry. Never persisted. */+export const laneKey = (prefix, idx) => `${prefix}-${idx}-${Math.random().toString(36).slice(2, 8)}`;++/** Attach `_key` to every entry of a lane loaded from the server. */+export const withKeys = (entries, prefix) => (entries || []).map((e, idx) => ({ ...e, _key: laneKey(prefix, idx) }));diff --git a/client/src/lib/videoTimelineModel.test.js b/client/src/lib/videoTimelineModel.test.jsnew file mode 100644index 0000000000..435e323621--- /dev/null+++ b/client/src/lib/videoTimelineModel.test.js@@ -0,0 +1,160 @@+import { describe, it, expect } from 'vitest';+import {+ assetUrl,+ segmentDuration,+ timelineDuration,+ findSegmentAt,+ fadeMultiplier,+ overlayOpacityAt,+ audioTrackStateAt,+ stripKey,+ withKeys,+ timelinePatch,+} from './videoTimelineModel';++const clip = (inSec, outSec) => ({ type: 'clip', clipId: 'c', inSec, outSec });+const still = (durationSec) => ({ type: 'still', assetKind: 'images', assetFile: 'a.png', durationSec });++describe('assetUrl', () => {+ it('maps each allowlisted kind to its served directory', () => {+ expect(assetUrl('images', 'plate.png')).toBe('/data/images/plate.png');+ expect(assetUrl('music', 'bed.mp3')).toBe('/data/music/bed.mp3');+ expect(assetUrl('video-thumbnails', 'thumb.jpg')).toBe('/data/video-thumbnails/thumb.jpg');+ });++ it('encodes the filename so a space or hash cannot break the URL', () => {+ expect(assetUrl('images', 'my plate #2.png')).toBe('/data/images/my%20plate%20%232.png');+ });++ it('returns null for an unknown kind or an empty filename', () => {+ expect(assetUrl('videos', 'x.mp4')).toBeNull();+ expect(assetUrl('images', '')).toBeNull();+ });+});++describe('segmentDuration / timelineDuration', () => {+ it('measures a still by its hold and a clip by its trim', () => {+ expect(segmentDuration(still(3))).toBe(3);+ expect(segmentDuration(clip(1, 4))).toBe(3);+ });++ it('never goes negative on an inverted trim', () => {+ expect(segmentDuration(clip(4, 1))).toBe(0);+ });++ it('sums a heterogeneous lane', () => {+ expect(timelineDuration([clip(0, 2), still(3), clip(1, 2)])).toBe(6);+ });+});++describe('findSegmentAt', () => {+ const lane = [clip(0, 2), still(3), clip(5, 6)];++ it('maps project time into the right segment', () => {+ expect(findSegmentAt(lane, 0.5)).toEqual({ index: 0, within: 0.5, startAtProj: 0 });+ expect(findSegmentAt(lane, 3)).toEqual({ index: 1, within: 1, startAtProj: 2 });+ expect(findSegmentAt(lane, 5.5)).toEqual({ index: 2, within: 0.5, startAtProj: 5 });+ });++ it('falls through an exact seam to the NEXT segment', () => {+ expect(findSegmentAt(lane, 2).index).toBe(1);+ expect(findSegmentAt(lane, 5).index).toBe(2);+ });++ it('clamps past the end to the last segment', () => {+ expect(findSegmentAt(lane, 99).index).toBe(2);+ });+});++describe('fadeMultiplier', () => {+ it('is 1 with no fades', () => {+ expect(fadeMultiplier(0, 0, 4, 2)).toBe(1);+ });++ it('ramps linearly in and out, matching ffmpeg\'s default tri curve', () => {+ expect(fadeMultiplier(1, 0, 4, 0)).toBe(0);+ expect(fadeMultiplier(1, 0, 4, 0.5)).toBeCloseTo(0.5);+ expect(fadeMultiplier(1, 0, 4, 1)).toBe(1);+ expect(fadeMultiplier(0, 2, 4, 3)).toBeCloseTo(0.5);+ expect(fadeMultiplier(0, 2, 4, 4)).toBe(0);+ });++ it('multiplies where an overlapping pair leaves no full-opacity window', () => {+ // 3s of fade across a 2s segment — the probe-clamped case.+ expect(fadeMultiplier(1.5, 1.5, 2, 1)).toBeCloseTo(1 / 1.5 * (1 / 1.5));+ });++ it('returns 1 rather than dividing by a zero duration', () => {+ expect(fadeMultiplier(1, 1, 0, 0)).toBe(1);+ });+});++describe('overlayOpacityAt', () => {+ const overlay = { startSec: 2, durationSec: 4, opacity: 0.5, fadeInSec: 1, fadeOutSec: 1 };++ it('is fully transparent outside its window', () => {+ expect(overlayOpacityAt(overlay, 1.9)).toBe(0);+ expect(overlayOpacityAt(overlay, 6.1)).toBe(0);+ });++ it('scales its configured opacity by the alpha ramp', () => {+ expect(overlayOpacityAt(overlay, 2)).toBe(0);+ expect(overlayOpacityAt(overlay, 2.5)).toBeCloseTo(0.25);+ expect(overlayOpacityAt(overlay, 4)).toBeCloseTo(0.5);+ expect(overlayOpacityAt(overlay, 5.5)).toBeCloseTo(0.25);+ });++ it('defaults a missing opacity to fully opaque', () => {+ expect(overlayOpacityAt({ startSec: 0, durationSec: 2 }, 1)).toBe(1);+ });+});++describe('audioTrackStateAt', () => {+ const track = { startSec: 2, offsetSec: 30, durationSec: 4, volume: 0.8, fadeInSec: 1, fadeOutSec: 0 };++ it('is silent and inactive before its start', () => {+ expect(audioTrackStateAt(track, 0)).toMatchObject({ active: false, volume: 0 });+ });++ it('seeks the source at offset + elapsed, not at project time', () => {+ expect(audioTrackStateAt(track, 3).sourceTime).toBe(31);+ });++ it('applies the fade ramp to the configured volume', () => {+ expect(audioTrackStateAt(track, 2.5).volume).toBeCloseTo(0.4);+ expect(audioTrackStateAt(track, 4).volume).toBeCloseTo(0.8);+ });++ it('goes inactive at the exact end so it cannot double up with the next placement', () => {+ expect(audioTrackStateAt(track, 6).active).toBe(false);+ });+});++describe('save helpers', () => {+ it('strips the client-only _key', () => {+ expect(stripKey({ _key: 'k', clipId: 'c', inSec: 0 })).toEqual({ clipId: 'c', inSec: 0 });+ });++ it('gives every loaded lane entry a distinct key', () => {+ const keyed = withKeys([still(1), still(1)], 'seg');+ expect(keyed[0]._key).not.toBe(keyed[1]._key);+ expect(keyed[0]).toMatchObject({ type: 'still', durationSec: 1 });+ });++ it('builds a PATCH body with every lane present and no keys', () => {+ const patch = timelinePatch({+ segments: [{ ...clip(0, 2), _key: 'a' }],+ overlays: [{ assetKind: 'images', assetFile: 'l.png', startSec: 0, durationSec: 1, _key: 'b' }],+ audio: { clipVolume: 0.5, tracks: [{ assetKind: 'music', assetFile: 'b.mp3', startSec: 0, durationSec: 2, _key: 'c' }] },+ });++ expect(JSON.stringify(patch)).not.toContain('_key');+ expect(patch.segments).toHaveLength(1);+ expect(patch.overlays).toHaveLength(1);+ expect(patch.audio).toMatchObject({ clipVolume: 0.5 });+ });++ it('sends every lane even when empty, so clearing one actually persists', () => {+ expect(timelinePatch({})).toEqual({ segments: [], overlays: [], audio: { clipVolume: 1, tracks: [] } });+ });+});diff --git a/client/src/pages/VideoTimelineEditor.jsx b/client/src/pages/VideoTimelineEditor.jsxindex 3f4c149733..362268ee20 100644--- a/client/src/pages/VideoTimelineEditor.jsx+++ b/client/src/pages/VideoTimelineEditor.jsx@@ -16,38 +16,56 @@ import {import { dndTransformToCss } from '../lib/dndTransform';import {Play, Pause, Plus, Trash2, X, Save, Film, Loader2, ArrowLeft, Volume2, VolumeX,+ Image as ImageIcon, Music,} from 'lucide-react';import toast from '../components/ui/Toast';import * as api from '../services/api';import { formatTimecode } from '../utils/formatters';import { useSseProgress, isTerminalSseFrame } from '../hooks/useSseProgress';import { clickableProps } from '../lib/a11yKeyboard.js';+import {+ assetUrl,+ segmentDuration,+ timelineDuration,+ findSegmentAt,+ fadeMultiplier,+ overlayOpacityAt,+ audioTrackStateAt,+ timelinePatch,+ withKeys,+ laneKey,+} from '../lib/videoTimelineModel';-// Map project-time t (every clip contributes its trimmed duration) to the-// (clipIndex, withinClipSec) pair the preview <video> element needs. The-// strict t < acc+dur comparison falls through on exact boundaries so a-// playhead landing on a seam plays the next clip, not the end of the prior.-const findClipAt = (clips, t) => {- let acc = 0;- for (let i = 0; i < clips.length; i++) {- const dur = Math.max(0, clips[i].outSec - clips[i].inSec);- if (t < acc + dur || i === clips.length - 1) {- return { index: i, within: Math.max(0, t - acc), startAtProj: acc };- }- acc += dur;- }- return { index: -1, within: 0, startAtProj: 0 };-};+const EMPTY_LANES = { segments: [], overlays: [], audio: { clipVolume: 1, tracks: [] } };++// Default lengths for a newly-added still/overlay/bed. The bed length is a+// guess — the client can't probe the file — so the server clamps it down to+// the real duration at render time.+const DEFAULT_STILL_SEC = 3;+const DEFAULT_OVERLAY_SEC = 3;+const DEFAULT_BED_SEC = 10;++const num2 = (n) => (Number.isFinite(n) ? Number(n).toFixed(2) : '');-const totalDuration = (clips) => clips.reduce((s, c) => s + Math.max(0, c.outSec - c.inSec), 0);+const segmentLabel = (segment, meta) => {+ if (!segment) return 'clip';+ if (segment.type === 'still') return segment.assetFile || 'still';+ return meta?.prompt?.trim().slice(0, 40) || 'clip';+};-// Draggable+sortable timeline block. Snaps the trimmed duration to a width-// derived from `pxPerSec` so longer clips visibly take more horizontal space.+// Draggable+sortable video-lane block. Snaps the segment's project-time length+// to a width derived from `pxPerSec` so longer segments visibly take more+// horizontal space, and marks its fades so a cut reads at a glance.export function TimelineBlock({ clip, clipMeta, isSelected, isMissing, pxPerSec, onSelect, onRemove }) {const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: clip._key });- const dur = Math.max(0.05, clip.outSec - clip.inSec);- const removeLabel = isMissing ? 'missing clip' : clipMeta?.prompt?.trim().slice(0, 40) || 'clip';+ const isStill = clip.type === 'still';+ const dur = Math.max(0.05, segmentDuration(clip));+ const label = segmentLabel(clip, clipMeta);+ const removeLabel = isMissing ? 'missing clip' : label;const width = Math.max(60, dur * pxPerSec);+ const thumbSrc = isStill+ ? assetUrl(clip.assetKind, clip.assetFile)+ : (clipMeta?.thumbnail ? `/data/video-thumbnails/${clipMeta.thumbnail}` : null);const style = {transform: dndTransformToCss(transform),transition,@@ -70,20 +88,37 @@ export function TimelineBlock({ clip, clipMeta, isSelected, isMissing, pxPerSec,{...listeners}{...clickableProps(() => onSelect(clip._key))}>- {clipMeta?.thumbnail && (+ {thumbSrc && (<img- src={`/data/video-thumbnails/${clipMeta.thumbnail}`}+ src={thumbSrc}alt=""draggable={false}className="w-full h-full object-cover rounded-md opacity-80"/>)}<div className="absolute inset-0 rounded-md bg-gradient-to-t from-black/70 via-transparent to-transparent pointer-events-none" />+ {/* Fade ramps read as wedges of black over the head/tail of the block. */}+ {clip.fadeInSec > 0 && (+ <div+ data-testid="fade-in-ramp"+ aria-hidden="true"+ style={{ width: `${Math.min(100, (clip.fadeInSec / dur) * 100)}%` }}+ className="absolute inset-y-0 left-0 rounded-l-md bg-gradient-to-r from-black/80 to-transparent pointer-events-none"+ />+ )}+ {clip.fadeOutSec > 0 && (+ <div+ data-testid="fade-out-ramp"+ aria-hidden="true"+ style={{ width: `${Math.min(100, (clip.fadeOutSec / dur) * 100)}%` }}+ className="absolute inset-y-0 right-0 rounded-r-md bg-gradient-to-l from-black/80 to-transparent pointer-events-none"+ />+ )}<div className="absolute bottom-1 left-1.5 right-1.5 text-[10px] text-white truncate font-medium">- {isMissing ? '(missing)' : clipMeta?.prompt?.slice(0, 40) || 'clip'}+ {isMissing ? '(missing)' : label}</div><div className="absolute top-1 left-1.5 text-[9px] text-white bg-black/60 px-1 rounded">- {dur.toFixed(2)}s+ {isStill ? `still · ${dur.toFixed(2)}s` : `${dur.toFixed(2)}s`}</div><buttontype="button"@@ -101,9 +136,48 @@ export function TimelineBlock({ clip, clipMeta, isSelected, isMissing, pxPerSec,);}+// A free-floating lane block (overlay or audio bed). Unlike the video lane+// these are positioned by absolute project time, so they carry no sort order —+// the inspector's start field is what moves them.+export function LaneBlock({ entry, label, tone, isSelected, isMissing, pxPerSec, onSelect, onRemove }) {+ const dur = Math.max(0.05, entry.durationSec || 0);+ const style = {+ left: `${(entry.startSec || 0) * pxPerSec}px`,+ width: `${Math.max(28, dur * pxPerSec)}px`,+ };+ return (+ <div+ style={style}+ className={`absolute top-1 bottom-1 rounded border cursor-pointer overflow-hidden ${+ isMissing+ ? 'bg-port-error/20 border-port-error'+ : isSelected+ ? 'border-port-accent bg-port-accent/20'+ : `${tone} hover:border-port-accent/50`+ }`}+ onClick={() => onSelect(entry._key)}+ {...clickableProps(() => onSelect(entry._key))}+ >+ <span className="absolute inset-x-1 top-0.5 text-[9px] text-white truncate pointer-events-none">+ {isMissing ? '(missing)' : label}+ </span>+ <button+ type="button"+ onClick={(e) => { e.stopPropagation(); onRemove(entry._key); }}+ onPointerDown={(e) => e.stopPropagation()}+ className="absolute bottom-0 right-0 p-0.5 text-white/70 hover:text-port-error"+ title="Remove"+ aria-label={`Remove ${label} from timeline`}+ >+ <X className="w-3 h-3" aria-hidden="true" />+ </button>+ </div>+ );+}+// Library tile — renders a clip from history with an "Add to timeline" button.-// Does not use DnD here; click-to-add at end is simpler and equally functional-// for v1. Reordering on the timeline itself uses sortable.+// Does not use DnD here; click-to-add at end is simpler and equally functional.+// Reordering on the timeline itself uses sortable.function LibraryTile({ clip, onAdd }) {const dur = clip.numFrames && clip.fps ? clip.numFrames / clip.fps : 0;return (@@ -134,21 +208,104 @@ function LibraryTile({ clip, onAdd }) {);}+// Gallery tile — one image, two destinations. A still joins the video lane as+// its own held segment; an overlay floats above whatever is playing at the+// current playhead.+function StillTile({ image, onAddStill, onAddOverlay }) {+ const src = assetUrl('images', image.filename);+ return (+ <div className="bg-port-card border border-port-border rounded-md overflow-hidden hover:border-port-accent/50 transition-colors">+ <div className="aspect-video bg-port-bg">+ {src && <img src={src} alt={image.filename} className="w-full h-full object-cover" loading="lazy" />}+ </div>+ <div className="p-1.5 space-y-1">+ <p className="text-[10px] text-gray-300 truncate" title={image.filename}>{image.filename}</p>+ <div className="flex gap-1">+ <button+ type="button"+ onClick={() => onAddStill(image)}+ className="flex-1 px-1 py-1 bg-port-accent/20 hover:bg-port-accent/40 text-port-accent text-[10px] rounded"+ >+ Still+ </button>+ <button+ type="button"+ onClick={() => onAddOverlay(image)}+ className="flex-1 px-1 py-1 bg-port-card border border-port-border hover:border-port-accent text-gray-300 text-[10px] rounded"+ >+ Overlay+ </button>+ </div>+ </div>+ </div>+ );+}++function AudioRow({ track, onAdd }) {+ return (+ <div className="flex items-center gap-2 bg-port-card border border-port-border rounded-md px-2 py-1.5 hover:border-port-accent/50 transition-colors">+ <Music className="w-3 h-3 text-gray-500 shrink-0" aria-hidden="true" />+ <span className="text-[10px] text-gray-300 truncate flex-1" title={track.filename}>{track.label || track.filename}</span>+ <button+ type="button"+ onClick={() => onAdd(track)}+ className="px-1.5 py-1 bg-port-accent/20 hover:bg-port-accent/40 text-port-accent text-[10px] rounded shrink-0"+ >+ Add+ </button>+ </div>+ );+}++// Inspector number input with its own draft state. Editing the canonical value+// on every keystroke forces each stroke through toFixed(), which prevents+// typing "0." at all; committing on blur avoids that and batches the PATCH.+function NumberField({ id, label, value, step = 0.05, min, max, hint, onCommit }) {+ const [draft, setDraft] = useState(num2(value));+ useEffect(() => { setDraft(num2(value)); }, [value]);+ return (+ <label htmlFor={id} className="block text-xs text-gray-400">+ {label}+ <input+ id={id}+ type="number"+ step={step}+ min={min}+ max={max}+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ onBlur={(e) => {+ const n = Number(e.target.value);+ if (Number.isFinite(n)) onCommit(n);+ else setDraft(num2(value));+ }}+ className="w-full mt-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-none focus:border-port-accent"+ />+ {hint && <span className="block mt-0.5 text-[10px] text-gray-500">{hint}</span>}+ </label>+ );+}+export default function VideoTimelineEditor() {const { projectId } = useParams();const navigate = useNavigate();const [project, setProject] = useState(null);const [history, setHistory] = useState([]);+ const [images, setImages] = useState([]);+ const [musicTracks, setMusicTracks] = useState([]);const [loading, setLoading] = useState(true);const [error, setError] = useState(null);- // Local timeline (each clip gets a stable _key for dnd-kit identity)- const [clips, setClips] = useState([]);- const [selectedKey, setSelectedKey] = useState(null);- // Track the current selection by its STABLE identity (clipId + position) so a- // refresh — which regenerates every clip's random _key — can re-derive selectedKey- // instead of collapsing the inspector to "Select a clip". Read from a ref so refresh- // needn't depend on clips/selectedKey (which would re-trigger the load-on-mount loop).- const selectionRef = useRef({ clipId: null, index: -1 });+ // The three lanes live in ONE state object so a save always ships a+ // consistent snapshot — three separate useStates would let a debounced PATCH+ // read a half-updated timeline.+ const [lanes, setLanes] = useState(EMPTY_LANES);+ // { lane: 'segment' | 'overlay' | 'audio', key } — null when nothing is selected.+ const [selection, setSelection] = useState(null);+ // Track the current selection by its STABLE position so a refresh — which+ // regenerates every entry's random _key — can re-derive it instead of+ // collapsing the inspector to "Select a clip". Read from a ref so refresh+ // needn't depend on lanes/selection (which would re-trigger the load-on-mount loop).+ const selectionRef = useRef({ lane: null, index: -1 });const [pxPerSec, setPxPerSec] = useState(60);const [t, setT] = useState(0); // project-time in secondsconst [playing, setPlaying] = useState(false);@@ -156,11 +313,10 @@ export default function VideoTimelineEditor() {const [renderJobId, setRenderJobId] = useState(null);const [renderProgress, setRenderProgress] = useState(0);const [showLibrary, setShowLibrary] = useState(true);- // Local input drafts. Editing the canonical state on every keystroke makes- // the rename onBlur-vs-canonical comparison always-equal, and forces the- // trim inputs through toFixed() per stroke (which prevents typing "0.").+ const [libraryTab, setLibraryTab] = useState('clips');+ // Local input draft. Editing the canonical state on every keystroke makes the+ // rename onBlur-vs-canonical comparison always-equal.const [nameDraft, setNameDraft] = useState('');- const [trimDraft, setTrimDraft] = useState({ inSec: '', outSec: '' });const videoRef = useRef(null);const lastSrcRef = useRef('');@@ -170,45 +326,60 @@ export default function VideoTimelineEditor() {// ref we update synchronously gives the handler the live value.const playingRef = useRef(false);useEffect(() => { playingRef.current = playing; }, [playing]);- const playClipIndexRef = useRef(-1);+ const playSegmentIndexRef = useRef(-1);+ // One <audio> element per bed track, keyed by its client-side _key.+ const bedRefs = useRef(new Map());const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));+ const { segments, overlays, audio } = lanes;+const refresh = useCallback(async () => {setLoading(true);setError(null);- const [proj, hist] = await Promise.all([+ const [proj, hist, gallery, library] = await Promise.all([api.getTimelineProject(projectId).catch((err) => { setError(err.message); return null; }),api.listVideoHistory().catch(() => []),+ api.listImageGallery().catch(() => []),+ api.listMusicLibrary().catch(() => null),]);if (proj) {- const newClips = (proj.clips || []).map((c, idx) => ({ ...c, _key: `${c.clipId}-${idx}-${Math.random().toString(36).slice(2, 8)}` }));+ const nextLanes = {+ segments: withKeys(proj.segments, 'seg'),+ overlays: withKeys(proj.overlays, 'ov'),+ audio: {+ clipVolume: proj.audio?.clipVolume == null ? 1 : proj.audio.clipVolume,+ tracks: withKeys(proj.audio?.tracks, 'bed'),+ },+ };setProject(proj);- setClips(newClips);- // Re-derive selection from the stable clipId (+ prior position) so a refresh —- // e.g. a CONFLICT reload mid-edit — doesn't leave selectedKey pointing at a- // now-regenerated _key and collapse the inspector. Prefer the same index; fall- // back to the first clip with the same clipId; clear if the clip is gone.- const { clipId: selId, index: selIdx } = selectionRef.current;- if (selId != null) {- const match = newClips[selIdx]?.clipId === selId- ? newClips[selIdx]- : newClips.find((c) => c.clipId === selId);- setSelectedKey(match ? match._key : null);- }+ setLanes(nextLanes);+ // Re-derive selection from its lane + prior position so a refresh — e.g. a+ // CONFLICT reload mid-edit — doesn't leave `selection` pointing at a+ // now-regenerated _key and collapse the inspector.+ const { lane, index } = selectionRef.current;+ const laneEntries = lane === 'overlay' ? nextLanes.overlays+ : lane === 'audio' ? nextLanes.audio.tracks+ : lane === 'segment' ? nextLanes.segments : null;+ setSelection(laneEntries?.[index] ? { lane, key: laneEntries[index]._key } : null);}- setHistory(hist);+ setHistory(Array.isArray(hist) ? hist : []);+ setImages(Array.isArray(gallery) ? gallery : []);+ // `null` = the request failed; `[]` = a genuinely empty library. Only the+ // former should leave the previous list alone.+ if (library) setMusicTracks(Array.isArray(library.tracks) ? library.tracks : []);setLoading(false);}, [projectId]);- // Keep the stable-identity mirror of the current selection current so refresh() can- // reattach selectedKey after it regenerates clip _keys.+ // Keep the stable-position mirror of the current selection current so refresh()+ // can reattach it after it regenerates lane _keys.useEffect(() => {- const idx = clips.findIndex((c) => c._key === selectedKey);- selectionRef.current = idx >= 0- ? { clipId: clips[idx].clipId, index: idx }- : { clipId: null, index: -1 };- }, [selectedKey, clips]);+ if (!selection) { selectionRef.current = { lane: null, index: -1 }; return; }+ const entries = selection.lane === 'overlay' ? overlays+ : selection.lane === 'audio' ? audio.tracks : segments;+ const idx = entries.findIndex((e) => e._key === selection.key);+ selectionRef.current = idx >= 0 ? { lane: selection.lane, index: idx } : { lane: null, index: -1 };+ }, [selection, segments, overlays, audio.tracks]);useEffect(() => { refresh(); }, [refresh]);@@ -219,21 +390,8 @@ export default function VideoTimelineEditor() {if (project?.name) setNameDraft(project.name);}, [project?.id, project?.name]);- // Sync trim drafts when the user picks a different clip. While editing the- // selected clip, the draft is the source of truth — committing on blur- // drives the canonical update.- useEffect(() => {- setTrimDraft((prev) => {- const sel = clips.find((c) => c._key === selectedKey);- if (!sel) return { inSec: '', outSec: '' };- const next = { inSec: sel.inSec.toFixed(2), outSec: sel.outSec.toFixed(2) };- if (prev.inSec === next.inSec && prev.outSec === next.outSec) return prev;- return next;- });- }, [selectedKey, clips]);-// O(1) clip metadata lookup. The video-sync effect runs on every rAF tick- // during playback; a linear find() per frame multiplied by clip count is+ // during playback; a linear find() per frame multiplied by segment count is// measurable on long timelines.const historyMap = useMemo(() => {const m = new Map();@@ -242,24 +400,34 @@ export default function VideoTimelineEditor() {}, [history]);const metaFor = useCallback((clipId) => historyMap.get(clipId), [historyMap]);- const total = useMemo(() => totalDuration(clips), [clips]);+ const imageNames = useMemo(() => new Set(images.map((i) => i.filename)), [images]);+ const musicNames = useMemo(() => new Set(musicTracks.map((m) => m.filename)), [musicTracks]);++ // A lane entry is "missing" when its source is gone from the library it came+ // from — the render would 404, so the editor flags it up front.+ const isSegmentMissing = useCallback((seg) => (seg.type === 'still'+ ? !imageNames.has(seg.assetFile)+ : !metaFor(seg.clipId)), [imageNames, metaFor]);+ const isOverlayMissing = useCallback((ov) => !imageNames.has(ov.assetFile), [imageNames]);+ const isBedMissing = useCallback((tr) => tr.assetKind === 'music' && !musicNames.has(tr.assetFile), [musicNames]);++ const total = useMemo(() => timelineDuration(segments), [segments]);// Clamp the playhead into [0, total] when the timeline duration shrinks- // (clip removal, tighter trim, etc.). Without this, t can exceed total- // and findClipAt returns a `within` past the last clip's outSec — the+ // (segment removal, tighter trim, etc.). Without this, t can exceed total+ // and findSegmentAt returns a `within` past the last segment's end — the// preview seeks to black frames.useEffect(() => {if (t > total) { setT(total); setPlaying(false); }}, [total, t]);- // Save current timeline (debounced via the caller). Server validates and- // returns the canonical project; we only update updatedAt and preserve+ // Save the whole timeline (debounced via the caller). The server validates+ // and returns the canonical project; we only update updatedAt and preserve// local _keys to avoid blowing away the dnd identity.const saveTimeline = useCallback(async (next) => {if (!project) return false;- const cleanClips = next.map((c) => ({ clipId: c.clipId, inSec: c.inSec, outSec: c.outSec }));const updated = await api.updateTimelineProject(projectId, {- clips: cleanClips,+ ...timelinePatch(next),expectedUpdatedAt: project.updatedAt,}, { silent: true }).catch((err) => {if (err.code === 'CONFLICT') {@@ -275,7 +443,7 @@ export default function VideoTimelineEditor() {return true;}, [project, projectId, refresh]);- // Debounced save: trim-input edits fire many PATCHes per drag if we don't+ // Debounced save: trim/fade edits fire many PATCHes per drag if we don't// batch them. 400ms gives the user time to stop fiddling before we hit the// server.const saveTimerRef = useRef(null);@@ -288,63 +456,128 @@ export default function VideoTimelineEditor() {// timeout doesn't fire after navigation.useEffect(() => () => clearTimeout(saveTimerRef.current), []);- const updateClips = useCallback((updater) => {- setClips((prev) => {+ const updateLanes = useCallback((updater) => {+ setLanes((prev) => {const next = typeof updater === 'function' ? updater(prev) : updater;queueSave(next);return next;});}, [queueSave]);- // Add a clip to the end of the timeline at its full natural duration+ const patchSegment = useCallback((key, patch) => {+ updateLanes((prev) => ({+ ...prev,+ segments: prev.segments.map((s) => (s._key === key ? { ...s, ...patch(s) } : s)),+ }));+ }, [updateLanes]);++ const patchOverlay = useCallback((key, patch) => {+ updateLanes((prev) => ({+ ...prev,+ overlays: prev.overlays.map((o) => (o._key === key ? { ...o, ...patch(o) } : o)),+ }));+ }, [updateLanes]);++ const patchBed = useCallback((key, patch) => {+ updateLanes((prev) => ({+ ...prev,+ audio: { ...prev.audio, tracks: prev.audio.tracks.map((tr) => (tr._key === key ? { ...tr, ...patch(tr) } : tr)) },+ }));+ }, [updateLanes]);++ // --- Add / remove -----------------------------------------------------+const addClip = (clip) => {const fullDur = clip.numFrames && clip.fps ? clip.numFrames / clip.fps : 4;const next = {- _key: `${clip.id}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,+ _key: laneKey(clip.id, segments.length),+ type: 'clip',clipId: clip.id,inSec: 0,outSec: fullDur,+ fadeInSec: 0,+ fadeOutSec: 0,+ volume: 1,+ };+ updateLanes((prev) => ({ ...prev, segments: [...prev.segments, next] }));+ setSelection({ lane: 'segment', key: next._key });+ };++ const addStill = (image) => {+ const next = {+ _key: laneKey('still', segments.length),+ type: 'still',+ assetKind: 'images',+ assetFile: image.filename,+ durationSec: DEFAULT_STILL_SEC,+ fadeInSec: 0,+ fadeOutSec: 0,};- updateClips((prev) => [...prev, next]);- setSelectedKey(next._key);+ updateLanes((prev) => ({ ...prev, segments: [...prev.segments, next] }));+ setSelection({ lane: 'segment', key: next._key });};- const removeClip = (key) => {- updateClips((prev) => prev.filter((c) => c._key !== key));- if (selectedKey === key) setSelectedKey(null);+ const addOverlay = (image) => {+ const next = {+ _key: laneKey('ov', overlays.length),+ type: 'image',+ assetKind: 'images',+ assetFile: image.filename,+ startSec: Math.min(t, Math.max(0, total - 0.1)),+ durationSec: DEFAULT_OVERLAY_SEC,+ x: 0.05,+ y: 0.05,+ width: 0.25,+ opacity: 1,+ fadeInSec: 0,+ fadeOutSec: 0,+ };+ updateLanes((prev) => ({ ...prev, overlays: [...prev.overlays, next] }));+ setSelection({ lane: 'overlay', key: next._key });};- // Update the inSec/outSec of the selected clip; clamp to 0..sourceDuration.- const editSelected = (patch) => {- updateClips((prev) => prev.map((c) => {- if (c._key !== selectedKey) return c;- const meta = metaFor(c.clipId);- const sourceDur = meta?.numFrames && meta?.fps ? meta.numFrames / meta.fps : Infinity;- // Match the server's CLIP_TOO_SHORT guard (1/fps). Hardcoded 0.04 was- // too lenient at 24fps and would let the UI build a project that the- // render rejected with 400 CLIP_TOO_SHORT.- const minDur = meta?.fps && meta.fps > 0 ? 1 / meta.fps : 0.04;- let inSec = patch.inSec != null ? patch.inSec : c.inSec;- let outSec = patch.outSec != null ? patch.outSec : c.outSec;- inSec = Math.max(0, Math.min(inSec, sourceDur - minDur));- outSec = Math.max(inSec + minDur, Math.min(outSec, sourceDur));- return { ...c, inSec, outSec };- }));+ const addBed = (track) => {+ const next = {+ _key: laneKey('bed', audio.tracks.length),+ assetKind: 'music',+ assetFile: track.filename,+ startSec: Math.min(t, Math.max(0, total - 0.1)),+ offsetSec: 0,+ // The client can't probe the file; the server clamps this down to the+ // real duration when it renders.+ durationSec: Math.max(1, Math.min(DEFAULT_BED_SEC, total || DEFAULT_BED_SEC)),+ volume: 0.6,+ fadeInSec: 0,+ fadeOutSec: 0,+ };+ updateLanes((prev) => ({ ...prev, audio: { ...prev.audio, tracks: [...prev.audio.tracks, next] } }));+ setSelection({ lane: 'audio', key: next._key });+ };++ const removeFromLane = (lane, key) => {+ updateLanes((prev) => {+ if (lane === 'overlay') return { ...prev, overlays: prev.overlays.filter((o) => o._key !== key) };+ if (lane === 'audio') return { ...prev, audio: { ...prev.audio, tracks: prev.audio.tracks.filter((tr) => tr._key !== key) } };+ return { ...prev, segments: prev.segments.filter((s) => s._key !== key) };+ });+ setSelection((sel) => (sel && sel.key === key ? null : sel));};const onDragEnd = ({ active, over }) => {if (!over || active.id === over.id) return;- updateClips((prev) => {- const oldIdx = prev.findIndex((c) => c._key === active.id);- const newIdx = prev.findIndex((c) => c._key === over.id);+ updateLanes((prev) => {+ const oldIdx = prev.segments.findIndex((s) => s._key === active.id);+ const newIdx = prev.segments.findIndex((s) => s._key === over.id);if (oldIdx === -1 || newIdx === -1) return prev;- return arrayMove(prev, oldIdx, newIdx);+ return { ...prev, segments: arrayMove(prev.segments, oldIdx, newIdx) };});};- // Preview playback: keep a single <video> element that follows project-time.- // On every rAF tick, advance `t` by elapsed wall-time, find which clip we're- // in, and swap the <video>.src + currentTime when crossing a boundary.+ // --- Preview ----------------------------------------------------------++ // Playback: keep a single <video> element that follows project-time. On every+ // rAF tick, advance `t` by elapsed wall-time; the sync effects below drive+ // the media elements from it.const rafRef = useRef(null);const lastTickRef = useRef(0);useEffect(() => {@@ -367,58 +600,103 @@ export default function VideoTimelineEditor() {return () => cancelAnimationFrame(rafRef.current);}, [playing, total]);- // Sync the <video> element to project-time `t` whenever it changes.+ const active = useMemo(() => {+ if (segments.length === 0) return null;+ const { index, within } = findSegmentAt(segments, t);+ if (index < 0) return null;+ const segment = segments[index];+ return { index, within, segment, duration: segmentDuration(segment) };+ }, [segments, t]);++ // Sync the <video> element to project-time `t` whenever it changes. A still+ // segment has no video source — the effect parks the element so the <img>+ // below can take over the frame.useEffect(() => {- if (clips.length === 0) return;- const { index, within } = findClipAt(clips, t);- if (index < 0) return;- const clip = clips[index];- const meta = metaFor(clip.clipId);- if (!meta) return;- const src = `/data/videos/${meta.filename}`;+ if (!active) return;const video = videoRef.current;if (!video) return;- const wantTime = clip.inSec + within;+ if (active.segment.type === 'still') {+ lastSrcRef.current = '';+ playSegmentIndexRef.current = active.index;+ video.pause();+ return;+ }+ const meta = metaFor(active.segment.clipId);+ if (!meta) return;+ const src = `/data/videos/${meta.filename}`;+ const wantTime = active.segment.inSec + active.within;if (lastSrcRef.current !== src) {lastSrcRef.current = src;video.src = src;// Wait for metadata before seeking — seek-before-load silently no-ops// and the user sees frame 0 of the clip instead of `inSec + within`.video.onloadedmetadata = () => {- // Rapid scrubbing across clip boundaries reassigns src (and this+ // Rapid scrubbing across segment boundaries reassigns src (and this// handler) before the prior metadata load fires; bail if this src is// no longer the one we want so a stale load can't seek the new clip.if (lastSrcRef.current !== src) return;video.currentTime = wantTime;if (playingRef.current) video.play().catch(() => {});};- } else if (index !== playClipIndexRef.current) {+ } else if (active.index !== playSegmentIndexRef.current) {video.currentTime = wantTime;} else if (!playing && Math.abs(video.currentTime - wantTime) > 0.05) {- // Scrubbing while paused or moving the playhead within the same clip:- // the rAF loop only fires while playing, so we need to drive the- // element manually. During playback the video element advances on its- // own — re-seeking on every rAF tick would cause buffering stutter.+ // Scrubbing while paused or moving the playhead within the same segment:+ // the rAF loop only fires while playing, so we need to drive the element+ // manually. During playback the video element advances on its own —+ // re-seeking on every rAF tick would cause buffering stutter.video.currentTime = wantTime;}- playClipIndexRef.current = index;- }, [clips, t, metaFor, playing]);+ playSegmentIndexRef.current = active.index;+ }, [active, metaFor, playing]);- // Pause/play the underlying element in lockstep with `playing`.+ // Pause/play the underlying element in lockstep with `playing`. A still+ // segment holds no video, so there is nothing to start.useEffect(() => {const video = videoRef.current;if (!video) return;- if (playing) video.play().catch(() => {});+ if (playing && active?.segment.type !== 'still') video.play().catch(() => {});else video.pause();- }, [playing]);+ }, [playing, active?.segment.type]);useEffect(() => {const video = videoRef.current;if (video) video.muted = muted;}, [muted]);+ // Drive the bed <audio> elements from the same playhead the export mixes+ // against, so what the user hears while scrubbing is what amix will produce.+ useEffect(() => {+ for (const track of audio.tracks) {+ const el = bedRefs.current.get(track._key);+ if (!el) continue;+ const state = audioTrackStateAt(track, t);+ el.muted = muted;+ // clipVolume scales the video lane's OWN audio, not the bed — the export+ // applies it inside each segment's chain, before amix.+ el.volume = Math.min(1, Math.max(0, state.volume));+ if (!state.active) {+ if (!el.paused) el.pause();+ continue;+ }+ // Re-seeking every tick causes audible stutter; only correct real drift.+ if (Math.abs(el.currentTime - state.sourceTime) > 0.25) el.currentTime = state.sourceTime;+ if (playing && el.paused) el.play().catch(() => {});+ if (!playing && !el.paused) el.pause();+ }+ }, [audio.tracks, t, playing, muted]);++ // Stop every bed when the editor unmounts — a detached <audio> that was+ // playing keeps producing sound in some browsers.+ useEffect(() => {+ const els = bedRefs.current;+ return () => { for (const el of els.values()) el?.pause(); };+ }, []);++ // --- Render -----------------------------------------------------------+const handleRender = async () => {- if (clips.length === 0) {+ if (segments.length === 0) {toast.error('Add at least one clip before rendering');return;}@@ -426,13 +704,18 @@ export default function VideoTimelineEditor() {// layout. If the save fails (conflict, network), abort — otherwise we'd// render a stale server-side timeline while the UI shows fresh edits.clearTimeout(saveTimerRef.current);- const saved = await saveTimeline(clips);+ const saved = await saveTimeline(lanes);if (!saved) return;const result = await api.renderTimelineProject(projectId, { silent: true }).catch((err) => {if (err.code === 'RENDER_IN_PROGRESS') {const jobId = err.context?.jobId;if (jobId) { setRenderJobId(jobId); toast('Re-attaching to in-flight render'); return null; }}+ if (err.code === 'MISSING_CLIPS') {+ const gone = [...(err.context?.missingClipIds || []), ...(err.context?.missingAssets || [])];+ toast.error(`Render failed — ${gone.length} missing source${gone.length === 1 ? '' : 's'}`);+ return null;+ }toast.error(`Render failed: ${err.message}`);return null;});@@ -504,16 +787,27 @@ export default function VideoTimelineEditor() {);}- const selectedClip = clips.find((c) => c._key === selectedKey);- const selectedMeta = selectedClip ? metaFor(selectedClip.clipId) : null;+ const selectedSegment = selection?.lane === 'segment' ? segments.find((s) => s._key === selection.key) : null;+ const selectedOverlay = selection?.lane === 'overlay' ? overlays.find((o) => o._key === selection.key) : null;+ const selectedBed = selection?.lane === 'audio' ? audio.tracks.find((tr) => tr._key === selection.key) : null;+ const selectedMeta = selectedSegment?.type === 'clip' ? metaFor(selectedSegment.clipId) : null;const selectedSourceDur = selectedMeta?.numFrames && selectedMeta?.fps ? selectedMeta.numFrames / selectedMeta.fps : null;// Filter the library: hide outputs of any timeline render so the rail// doesn't grow unbounded with the user's own renders.const libraryClips = history.filter((h) => !h.timelineProjectId && !h.hidden);+ const usedClipIds = new Set(segments.filter((s) => s.type === 'clip').map((s) => s.clipId));++ const activeStillSrc = active?.segment.type === 'still'+ ? assetUrl(active.segment.assetKind, active.segment.assetFile)+ : null;+ // The same linear ramp ffmpeg's `fade` applies, rendered as a black scrim so+ // the preview shows the cut the export will make.+ const activeFadeScrim = active+ ? 1 - fadeMultiplier(active.segment.fadeInSec || 0, active.segment.fadeOutSec || 0, active.duration, active.within)+ : 0;- const usedClipIds = new Set(clips.map((c) => c.clipId));- const missingKeys = new Set(clips.filter((c) => !metaFor(c.clipId)).map((c) => c._key));+ const laneWidth = Math.max(240, total * pxPerSec);return (<div className="space-y-3">@@ -550,7 +844,9 @@ export default function VideoTimelineEditor() {}}className="bg-transparent text-white font-medium text-lg focus:outline-none focus:bg-port-card focus:px-2 rounded transition-all"/>- <span className="text-xs text-gray-500">{clips.length} clips · {formatTimecode(total)}</span>+ <span className="text-xs text-gray-500">+ {segments.length} segments · {overlays.length} overlays · {audio.tracks.length} beds · {formatTimecode(total)}+ </span></div><div className="flex items-center gap-2"><button@@ -563,7 +859,7 @@ export default function VideoTimelineEditor() {<buttontype="button"onClick={handleRender}- disabled={clips.length === 0 || !!renderJobId}+ disabled={segments.length === 0 || !!renderJobId}className="flex items-center gap-2 px-3 py-1.5 bg-port-success hover:bg-port-success/80 disabled:opacity-40 disabled:cursor-not-allowed text-white text-sm rounded-md">{renderJobId ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}@@ -576,8 +872,30 @@ export default function VideoTimelineEditor() {{/* Left rail — library */}{showLibrary && (<div className="bg-port-card/50 border border-port-border rounded-lg p-2 max-h-[600px] overflow-y-auto">- <div className="text-xs uppercase text-gray-500 tracking-wide mb-2 px-1">Clip library</div>- {libraryClips.length === 0 ? (+ <div className="flex gap-1 mb-2" role="tablist" aria-label="Clip library">+ {[+ { id: 'clips', label: 'Clips', Icon: Film },+ { id: 'stills', label: 'Stills', Icon: ImageIcon },+ { id: 'audio', label: 'Audio', Icon: Music },+ ].map(({ id, label, Icon }) => (+ <button+ key={id}+ type="button"+ role="tab"+ aria-selected={libraryTab === id}+ onClick={() => setLibraryTab(id)}+ className={`flex-1 flex items-center justify-center gap-1 px-1.5 py-1 text-[10px] rounded ${+ libraryTab === id+ ? 'bg-port-accent/20 text-port-accent'+ : 'text-gray-400 hover:text-white border border-port-border'+ }`}+ >+ <Icon className="w-3 h-3" aria-hidden="true" /> {label}+ </button>+ ))}+ </div>++ {libraryTab === 'clips' && (libraryClips.length === 0 ? (<div className="text-xs text-gray-500 px-1 py-4">No clips. Generate some on the Video page.</div>) : (<div className="grid grid-cols-1 gap-2">@@ -587,31 +905,103 @@ export default function VideoTimelineEditor() {</div>))}</div>- )}+ ))}++ {libraryTab === 'stills' && (images.length === 0 ? (+ <div className="text-xs text-gray-500 px-1 py-4">No images. Generate some on the Image page.</div>+ ) : (+ <div className="grid grid-cols-1 gap-2">+ {images.map((image) => (+ <StillTile key={image.filename} image={image} onAddStill={addStill} onAddOverlay={addOverlay} />+ ))}+ </div>+ ))}++ {libraryTab === 'audio' && (musicTracks.length === 0 ? (+ <div className="text-xs text-gray-500 px-1 py-4">No audio in the shared music library.</div>+ ) : (+ <div className="grid grid-cols-1 gap-1.5">+ {musicTracks.map((track) => (+ <AudioRow key={track.filename} track={track} onAdd={addBed} />+ ))}+ </div>+ ))}</div>)}- {/* Center — preview + track */}+ {/* Center — preview + tracks */}<div className="space-y-3 min-w-0"><div className="bg-black rounded-lg overflow-hidden aspect-video relative"><videoref={videoRef}- className="w-full h-full"+ className={`w-full h-full ${activeStillSrc ? 'invisible' : ''}`}playsInlinepreload="auto"/>- {clips.length === 0 && (+ {activeStillSrc && (+ <img src={activeStillSrc} alt="" className="absolute inset-0 w-full h-full object-contain" />+ )}+ {/* Overlay lane, composited exactly as ffmpeg will: normalized+ position/width against the canvas, alpha from the same ramp. */}+ {overlays.map((ov) => {+ const opacity = overlayOpacityAt(ov, t);+ if (opacity <= 0) return null;+ const src = assetUrl(ov.assetKind, ov.assetFile);+ if (!src) return null;+ return (+ <img+ key={ov._key}+ src={src}+ alt=""+ data-testid="overlay-preview"+ style={{+ left: `${(ov.x || 0) * 100}%`,+ top: `${(ov.y || 0) * 100}%`,+ width: `${(ov.width || 0.25) * 100}%`,+ opacity,+ }}+ className="absolute pointer-events-none"+ />+ );+ })}+ {activeFadeScrim > 0 && (+ <div+ data-testid="fade-scrim"+ aria-hidden="true"+ style={{ opacity: activeFadeScrim }}+ className="absolute inset-0 bg-black pointer-events-none"+ />+ )}+ {segments.length === 0 && (<div className="absolute inset-0 flex items-center justify-center text-gray-500 text-sm">Add clips to start</div>)}</div>+ {/* Bed playback elements. Hidden — the timeline lane is the UI. */}+ {audio.tracks.map((track) => {+ const src = assetUrl(track.assetKind, track.assetFile);+ if (!src) return null;+ return (+ <audio+ key={track._key}+ ref={(el) => {+ if (el) bedRefs.current.set(track._key, el);+ else bedRefs.current.delete(track._key);+ }}+ src={src}+ preload="auto"+ className="hidden"+ />+ );+ })}+<div className="flex items-center gap-2 text-xs text-gray-400"><buttontype="button"onClick={() => setPlaying((p) => !p)}- disabled={clips.length === 0}+ disabled={segments.length === 0}className="p-2 bg-port-card border border-port-border rounded-md hover:border-port-accent disabled:opacity-40"title={playing ? 'Pause' : 'Play'} aria-label={playing ? 'Pause' : 'Play'}>@@ -634,14 +1024,15 @@ export default function VideoTimelineEditor() {value={Math.min(t, total)}onChange={(e) => { setPlaying(false); setT(Number(e.target.value)); }}className="flex-1"- disabled={clips.length === 0}+ disabled={segments.length === 0}/><span className="font-mono text-[11px] tabular-nums">{formatTimecode(t)} / {formatTimecode(total)}</span>- <label className="flex items-center gap-1 ml-2">+ <label htmlFor="timeline-zoom" className="flex items-center gap-1 ml-2"><span>zoom</span><input+ id="timeline-zoom"type="range"min={20}max={200}@@ -652,30 +1043,90 @@ export default function VideoTimelineEditor() {</label></div>- <div className="bg-port-card/30 border border-port-border rounded-lg p-2 overflow-x-auto">- {clips.length === 0 ? (+ <div className="bg-port-card/30 border border-port-border rounded-lg p-2 overflow-x-auto space-y-1">+ {segments.length === 0 ? (<div className="text-xs text-gray-500 py-6 text-center">- Drag-drop reorder once you've added clips. Add from the library on the left.+ Drag-drop reorder once you've added clips. Add clips, stills, overlays and audio from the library on the left.</div>) : (- <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd}>- <SortableContext items={clips.map((c) => c._key)} strategy={horizontalListSortingStrategy}>- <div className="flex gap-1 items-stretch min-w-min py-1">- {clips.map((clip) => (- <TimelineBlock- key={clip._key}- clip={clip}- clipMeta={metaFor(clip.clipId)}- isSelected={clip._key === selectedKey}- isMissing={missingKeys.has(clip._key)}- pxPerSec={pxPerSec}- onSelect={setSelectedKey}- onRemove={removeClip}- />- ))}- </div>- </SortableContext>- </DndContext>+ <>+ <div className="text-[9px] uppercase tracking-wide text-gray-600 px-0.5">Video</div>+ <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd}>+ <SortableContext items={segments.map((s) => s._key)} strategy={horizontalListSortingStrategy}>+ <div className="flex gap-1 items-stretch min-w-min py-1">+ {segments.map((segment) => (+ <TimelineBlock+ key={segment._key}+ clip={segment}+ clipMeta={segment.type === 'clip' ? metaFor(segment.clipId) : null}+ isSelected={selection?.lane === 'segment' && segment._key === selection.key}+ isMissing={isSegmentMissing(segment)}+ pxPerSec={pxPerSec}+ onSelect={(key) => setSelection({ lane: 'segment', key })}+ onRemove={(key) => removeFromLane('segment', key)}+ />+ ))}+ </div>+ </SortableContext>+ </DndContext>++ <div className="text-[9px] uppercase tracking-wide text-gray-600 px-0.5 pt-1">Overlays</div>+ <div className="relative h-8 bg-port-bg/40 rounded" style={{ width: `${laneWidth}px` }}>+ {overlays.length === 0 && (+ <span className="absolute inset-0 flex items-center pl-2 text-[10px] text-gray-600">+ Add an overlay from the Stills tab+ </span>+ )}+ {overlays.map((ov) => (+ <LaneBlock+ key={ov._key}+ entry={ov}+ label={ov.assetFile}+ tone="bg-port-accent/15 border-port-accent/40"+ isSelected={selection?.lane === 'overlay' && ov._key === selection.key}+ isMissing={isOverlayMissing(ov)}+ pxPerSec={pxPerSec}+ onSelect={(key) => setSelection({ lane: 'overlay', key })}+ onRemove={(key) => removeFromLane('overlay', key)}+ />+ ))}+ <div+ data-testid="lane-playhead"+ aria-hidden="true"+ style={{ left: `${Math.min(t, total) * pxPerSec}px` }}+ className="absolute inset-y-0 w-px bg-port-accent pointer-events-none"+ />+ </div>++ <div className="text-[9px] uppercase tracking-wide text-gray-600 px-0.5 pt-1">Audio</div>+ <div className="relative h-8 bg-port-bg/40 rounded" style={{ width: `${laneWidth}px` }}>+ {audio.tracks.length === 0 && (+ <span className="absolute inset-0 flex items-center pl-2 text-[10px] text-gray-600">+ Add a bed from the Audio tab+ </span>+ )}+ {audio.tracks.map((track) => (+ <LaneBlock+ key={track._key}+ entry={track}+ label={track.assetFile}+ tone="bg-port-success/15 border-port-success/40"+ isSelected={selection?.lane === 'audio' && track._key === selection.key}+ isMissing={isBedMissing(track)}+ pxPerSec={pxPerSec}+ onSelect={(key) => setSelection({ lane: 'audio', key })}+ onRemove={(key) => removeFromLane('audio', key)}+ />+ ))}+ <div+ data-testid="lane-playhead"+ aria-hidden="true"+ style={{ left: `${Math.min(t, total) * pxPerSec}px` }}+ className="absolute inset-y-0 w-px bg-port-accent pointer-events-none"+ />+ </div>++ </>)}</div></div>@@ -683,80 +1134,199 @@ export default function VideoTimelineEditor() {{/* Right rail — inspector */}<div className="bg-port-card/50 border border-port-border rounded-lg p-3 space-y-3"><div className="text-xs uppercase text-gray-500 tracking-wide">Inspector</div>- {!selectedClip ? (- <div className="text-xs text-gray-500">Select a clip on the timeline to trim it.</div>- ) : missingKeys.has(selectedClip._key) ? (++ {!selection && (+ <div className="text-xs text-gray-500">Select a block on the timeline to edit it.</div>+ )}++ {selectedSegment && isSegmentMissing(selectedSegment) && (<div className="text-xs text-port-error space-y-2">- <p>Source clip missing — it may have been deleted from the gallery. Remove this block from the timeline.</p>+ <p>Source missing — it may have been deleted from the gallery. Remove this block from the timeline.</p><buttontype="button"- onClick={() => removeClip(selectedClip._key)}+ onClick={() => removeFromLane('segment', selectedSegment._key)}className="w-full px-2 py-1.5 bg-port-error/20 hover:bg-port-error/40 text-port-error text-xs rounded flex items-center justify-center gap-1"><Trash2 className="w-3 h-3" /> Remove</button></div>- ) : (+ )}++ {selectedSegment && !isSegmentMissing(selectedSegment) && selectedSegment.type === 'clip' && (<>{selectedMeta?.thumbnail && (- <img- src={`/data/video-thumbnails/${selectedMeta.thumbnail}`}- alt=""- className="w-full aspect-video object-cover rounded"- />+ <img src={`/data/video-thumbnails/${selectedMeta.thumbnail}`} alt="" className="w-full aspect-video object-cover rounded" />)}- <div className="text-[11px] text-gray-300 line-clamp-3" title={selectedMeta?.prompt}>- {selectedMeta?.prompt}- </div>+ <div className="text-[11px] text-gray-300 line-clamp-3" title={selectedMeta?.prompt}>{selectedMeta?.prompt}</div><div className="text-[10px] text-gray-500">source: {selectedSourceDur?.toFixed(2) ?? '?'}s · {selectedMeta?.width}×{selectedMeta?.height} · {selectedMeta?.fps}fps</div>- <label className="block text-xs text-gray-400">- In (s)- <input- type="number"- step="0.05"- min={0}- max={selectedSourceDur || undefined}- value={trimDraft.inSec}- onChange={(e) => setTrimDraft((d) => ({ ...d, inSec: e.target.value }))}- onBlur={(e) => {- const n = Number(e.target.value);- if (Number.isFinite(n)) editSelected({ inSec: n });- }}- className="w-full mt-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-none focus:border-port-accent"- />- </label>- <label className="block text-xs text-gray-400">- Out (s)- <input- type="number"- step="0.05"- min={selectedClip.inSec + 0.05}- max={selectedSourceDur || undefined}- value={trimDraft.outSec}- onChange={(e) => setTrimDraft((d) => ({ ...d, outSec: e.target.value }))}- onBlur={(e) => {- const n = Number(e.target.value);- if (Number.isFinite(n)) editSelected({ outSec: n });- }}- className="w-full mt-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-none focus:border-port-accent"- />- </label>+ <NumberField+ id="segment-in" label="In (s)" value={selectedSegment.inSec} min={0} max={selectedSourceDur || undefined}+ onCommit={(n) => patchSegment(selectedSegment._key, (s) => clampTrim(s, { inSec: n }, selectedSourceDur, selectedMeta?.fps))}+ />+ <NumberField+ id="segment-out" label="Out (s)" value={selectedSegment.outSec} min={0} max={selectedSourceDur || undefined}+ onCommit={(n) => patchSegment(selectedSegment._key, (s) => clampTrim(s, { outSec: n }, selectedSourceDur, selectedMeta?.fps))}+ /><div className="text-[10px] text-gray-500">- trimmed: {(selectedClip.outSec - selectedClip.inSec).toFixed(2)}s+ trimmed: {segmentDuration(selectedSegment).toFixed(2)}s</div>- <button- type="button"- onClick={() => removeClip(selectedClip._key)}- className="w-full px-2 py-1.5 bg-port-error/20 hover:bg-port-error/40 text-port-error text-xs rounded flex items-center justify-center gap-1"- >- <Trash2 className="w-3 h-3" /> Remove from timeline- </button>+ <FadeFields+ idPrefix="segment"+ entry={selectedSegment}+ duration={segmentDuration(selectedSegment)}+ onCommit={(patch) => patchSegment(selectedSegment._key, (s) => fitFadePatch(s, patch, segmentDuration(s)))}+ />+ <NumberField+ id="segment-volume" label="Volume (×)" value={selectedSegment.volume ?? 1} step={0.05} min={0} max={4}+ onCommit={(n) => patchSegment(selectedSegment._key, () => ({ volume: clamp(n, 0, 4) }))}+ />+ <RemoveButton label="Remove from timeline" onClick={() => removeFromLane('segment', selectedSegment._key)} />+ </>+ )}++ {selectedSegment && !isSegmentMissing(selectedSegment) && selectedSegment.type === 'still' && (+ <>+ <img src={assetUrl(selectedSegment.assetKind, selectedSegment.assetFile)} alt="" className="w-full aspect-video object-cover rounded" />+ <div className="text-[11px] text-gray-300 truncate" title={selectedSegment.assetFile}>{selectedSegment.assetFile}</div>+ <NumberField+ id="still-duration" label="Hold (s)" value={selectedSegment.durationSec} min={0.05} max={600}+ onCommit={(n) => patchSegment(selectedSegment._key, (s) => fitFadePatch(s, { durationSec: clamp(n, 0.05, 600) }, clamp(n, 0.05, 600)))}+ />+ <FadeFields+ idPrefix="still"+ entry={selectedSegment}+ duration={segmentDuration(selectedSegment)}+ onCommit={(patch) => patchSegment(selectedSegment._key, (s) => fitFadePatch(s, patch, segmentDuration(s)))}+ />+ <RemoveButton label="Remove from timeline" onClick={() => removeFromLane('segment', selectedSegment._key)} />+ </>+ )}++ {selectedOverlay && (+ <>+ <img src={assetUrl(selectedOverlay.assetKind, selectedOverlay.assetFile)} alt="" className="w-full aspect-video object-contain rounded bg-port-bg" />+ <div className="text-[11px] text-gray-300 truncate" title={selectedOverlay.assetFile}>{selectedOverlay.assetFile}</div>+ <NumberField id="overlay-start" label="Start (s)" value={selectedOverlay.startSec} min={0}+ onCommit={(n) => patchOverlay(selectedOverlay._key, () => ({ startSec: Math.max(0, n) }))} />+ <NumberField id="overlay-duration" label="Duration (s)" value={selectedOverlay.durationSec} min={0.05} max={600}+ onCommit={(n) => patchOverlay(selectedOverlay._key, (o) => fitFadePatch(o, { durationSec: clamp(n, 0.05, 600) }, clamp(n, 0.05, 600)))} />+ <div className="grid grid-cols-2 gap-2">+ <NumberField id="overlay-x" label="X (0–1)" value={selectedOverlay.x ?? 0} step={0.01} min={-1} max={2}+ onCommit={(n) => patchOverlay(selectedOverlay._key, () => ({ x: clamp(n, -1, 2) }))} />+ <NumberField id="overlay-y" label="Y (0–1)" value={selectedOverlay.y ?? 0} step={0.01} min={-1} max={2}+ onCommit={(n) => patchOverlay(selectedOverlay._key, () => ({ y: clamp(n, -1, 2) }))} />+ </div>+ <NumberField id="overlay-width" label="Width (× canvas)" value={selectedOverlay.width ?? 0.25} step={0.01} min={0.01} max={4}+ onCommit={(n) => patchOverlay(selectedOverlay._key, () => ({ width: clamp(n, 0.01, 4) }))} />+ <NumberField id="overlay-opacity" label="Opacity (0–1)" value={selectedOverlay.opacity ?? 1} step={0.05} min={0} max={1}+ onCommit={(n) => patchOverlay(selectedOverlay._key, () => ({ opacity: clamp(n, 0, 1) }))} />+ <FadeFields+ idPrefix="overlay"+ entry={selectedOverlay}+ duration={selectedOverlay.durationSec}+ onCommit={(patch) => patchOverlay(selectedOverlay._key, (o) => fitFadePatch(o, patch, o.durationSec))}+ />+ <RemoveButton label="Remove overlay" onClick={() => removeFromLane('overlay', selectedOverlay._key)} />+ </>+ )}++ {selectedBed && (+ <>+ <div className="flex items-center gap-2 text-[11px] text-gray-300">+ <Music className="w-3 h-3 text-gray-500" aria-hidden="true" />+ <span className="truncate" title={selectedBed.assetFile}>{selectedBed.assetFile}</span>+ </div>+ <NumberField id="bed-start" label="Start (s)" value={selectedBed.startSec} min={0}+ onCommit={(n) => patchBed(selectedBed._key, () => ({ startSec: Math.max(0, n) }))} />+ <NumberField id="bed-offset" label="Source offset (s)" value={selectedBed.offsetSec ?? 0} min={0}+ hint="Where playback starts inside the file"+ onCommit={(n) => patchBed(selectedBed._key, () => ({ offsetSec: Math.max(0, n) }))} />+ <NumberField id="bed-duration" label="Duration (s)" value={selectedBed.durationSec} min={0.05} max={600}+ hint="Clamped to the file's real length at render"+ onCommit={(n) => patchBed(selectedBed._key, (tr) => fitFadePatch(tr, { durationSec: clamp(n, 0.05, 600) }, clamp(n, 0.05, 600)))} />+ <NumberField id="bed-volume" label="Volume (×)" value={selectedBed.volume ?? 1} step={0.05} min={0} max={4}+ onCommit={(n) => patchBed(selectedBed._key, () => ({ volume: clamp(n, 0, 4) }))} />+ <FadeFields+ idPrefix="bed"+ entry={selectedBed}+ duration={selectedBed.durationSec}+ onCommit={(patch) => patchBed(selectedBed._key, (tr) => fitFadePatch(tr, patch, tr.durationSec))}+ />+ <RemoveButton label="Remove bed" onClick={() => removeFromLane('audio', selectedBed._key)} /></>)}++ <div className="pt-2 border-t border-port-border">+ <NumberField+ id="mix-clip-volume"+ label="Clip audio (×)"+ value={audio.clipVolume ?? 1}+ step={0.05}+ min={0}+ max={4}+ hint="Scales every video segment's own audio"+ onCommit={(n) => updateLanes((prev) => ({ ...prev, audio: { ...prev.audio, clipVolume: clamp(n, 0, 4) } }))}+ />+ </div></div></div></div>);}++// --- Small shared pieces ------------------------------------------------++export const clamp = (n, min, max) => Math.min(max, Math.max(min, n));++// Clamp a trim edit to 0..sourceDuration, matching the server's CLIP_TOO_SHORT+// guard (1/fps). A hardcoded floor was too lenient at 24fps and let the UI+// build a project the render then rejected with 400.+export function clampTrim(segment, patch, sourceDur, fps) {+ const limit = sourceDur || Infinity;+ const minDur = fps && fps > 0 ? 1 / fps : 0.04;+ let inSec = patch.inSec != null ? patch.inSec : segment.inSec;+ let outSec = patch.outSec != null ? patch.outSec : segment.outSec;+ inSec = Math.max(0, Math.min(inSec, limit - minDur));+ outSec = Math.max(inSec + minDur, Math.min(outSec, limit));+ return fitFadePatch(segment, { inSec, outSec }, outSec - inSec);+}++// The server refuses a fade pair that outlasts its own duration, so shrink the+// OTHER fade rather than letting the PATCH 400 mid-edit.+export function fitFadePatch(entry, patch, duration) {+ const merged = { ...entry, ...patch };+ const fin = Math.max(0, merged.fadeInSec || 0);+ const fout = Math.max(0, merged.fadeOutSec || 0);+ if (fin + fout <= duration) return patch;+ const scale = fin + fout > 0 ? Math.max(0, duration) / (fin + fout) : 0;+ return { ...patch, fadeInSec: fin * scale, fadeOutSec: fout * scale };+}++function FadeFields({ idPrefix, entry, duration, onCommit }) {+ return (+ <div className="grid grid-cols-2 gap-2">+ <NumberField+ id={`${idPrefix}-fade-in`} label="Fade in (s)" value={entry.fadeInSec ?? 0} step={0.05} min={0} max={duration}+ onCommit={(n) => onCommit({ fadeInSec: clamp(n, 0, Math.max(0, duration)) })}+ />+ <NumberField+ id={`${idPrefix}-fade-out`} label="Fade out (s)" value={entry.fadeOutSec ?? 0} step={0.05} min={0} max={duration}+ onCommit={(n) => onCommit({ fadeOutSec: clamp(n, 0, Math.max(0, duration)) })}+ />+ </div>+ );+}++function RemoveButton({ label, onClick }) {+ return (+ <button+ type="button"+ onClick={onClick}+ className="w-full px-2 py-1.5 bg-port-error/20 hover:bg-port-error/40 text-port-error text-xs rounded flex items-center justify-center gap-1"+ >+ <Trash2 className="w-3 h-3" /> {label}+ </button>+ );+}diff --git a/client/src/pages/VideoTimelineEditor.test.jsx b/client/src/pages/VideoTimelineEditor.test.jsxindex 91b77d126f..8795909fb8 100644--- a/client/src/pages/VideoTimelineEditor.test.jsx+++ b/client/src/pages/VideoTimelineEditor.test.jsx@@ -18,7 +18,7 @@ vi.mock('@dnd-kit/sortable', async () => {};});-import { TimelineBlock } from './VideoTimelineEditor';+import { TimelineBlock, LaneBlock, clampTrim, fitFadePatch } from './VideoTimelineEditor';const clip = { _key: 'clip-key', clipId: 'clip-1', inSec: 0, outSec: 2 };const clipMeta = { prompt: 'A dramatic sunrise' };@@ -71,3 +71,143 @@ describe('TimelineBlock — remove control', () => {expect(onRemove).toHaveBeenCalledWith('clip-key');});});++describe('TimelineBlock — heterogeneous segments', () => {+ it('renders a still by its asset filename, thumbnailed from the gallery', () => {+ render(+ <TimelineBlock+ clip={{ _key: 'still-key', type: 'still', assetKind: 'images', assetFile: 'plate.png', durationSec: 3 }}+ clipMeta={null}+ isSelected={false}+ isMissing={false}+ pxPerSec={60}+ onSelect={vi.fn()}+ onRemove={vi.fn()}+ />,+ );++ expect(screen.getByText('still · 3.00s')).toBeInTheDocument();+ expect(screen.getByText('plate.png')).toBeInTheDocument();+ expect(document.querySelector('img')).toHaveAttribute('src', '/data/images/plate.png');+ expect(screen.getByRole('button', { name: 'Remove plate.png from timeline' })).toBeInTheDocument();+ });++ it('sizes a clip block from its TRIMMED length, not the source length', () => {+ render(+ <TimelineBlock+ clip={{ _key: 'k', type: 'clip', clipId: 'c', inSec: 1, outSec: 3 }}+ clipMeta={{ prompt: 'A dramatic sunrise' }}+ isSelected={false}+ isMissing={false}+ pxPerSec={50}+ onSelect={vi.fn()}+ onRemove={vi.fn()}+ />,+ );++ expect(screen.getByText('2.00s')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /Remove A dramatic sunrise/ }).closest('div')).toHaveStyle({ width: '100px' });+ });++ it('draws fade ramps proportional to the segment, and none when a fade is zero', () => {+ const { unmount } = render(+ <TimelineBlock+ clip={{ _key: 'k', type: 'clip', clipId: 'c', inSec: 0, outSec: 4, fadeInSec: 1, fadeOutSec: 0 }}+ clipMeta={{ prompt: 'p' }}+ isSelected={false}+ isMissing={false}+ pxPerSec={60}+ onSelect={vi.fn()}+ onRemove={vi.fn()}+ />,+ );++ expect(screen.getByTestId('fade-in-ramp')).toHaveStyle({ width: '25%' });+ expect(screen.queryByTestId('fade-out-ramp')).not.toBeInTheDocument();+ unmount();++ render(+ <TimelineBlock+ clip={{ _key: 'k', type: 'clip', clipId: 'c', inSec: 0, outSec: 4, fadeInSec: 0, fadeOutSec: 2 }}+ clipMeta={{ prompt: 'p' }}+ isSelected={false}+ isMissing={false}+ pxPerSec={60}+ onSelect={vi.fn()}+ onRemove={vi.fn()}+ />,+ );+ expect(screen.getByTestId('fade-out-ramp')).toHaveStyle({ width: '50%' });+ });+});++describe('LaneBlock — free-floating overlay/bed placement', () => {+ const entry = { _key: 'ov-1', startSec: 2, durationSec: 3 };++ it('positions and sizes itself in project time at the current zoom', () => {+ render(+ <LaneBlock entry={entry} label="logo.png" tone="" isSelected={false} isMissing={false} pxPerSec={40} onSelect={vi.fn()} onRemove={vi.fn()} />,+ );++ const block = screen.getByText('logo.png').closest('div');+ expect(block).toHaveStyle({ left: '80px', width: '120px' });+ });++ it('flags a missing source instead of showing a label that resolves to nothing', () => {+ render(+ <LaneBlock entry={entry} label="gone.png" tone="" isSelected={false} isMissing onSelect={vi.fn()} pxPerSec={40} onRemove={vi.fn()} />,+ );+ expect(screen.getByText('(missing)')).toBeInTheDocument();+ expect(screen.queryByText('gone.png')).not.toBeInTheDocument();+ });++ it('removes without also selecting the block', () => {+ const onSelect = vi.fn();+ const onRemove = vi.fn();+ render(+ <LaneBlock entry={entry} label="logo.png" tone="" isSelected={false} isMissing={false} pxPerSec={40} onSelect={onSelect} onRemove={onRemove} />,+ );++ fireEvent.click(screen.getByRole('button', { name: 'Remove logo.png from timeline' }));++ expect(onSelect).not.toHaveBeenCalled();+ expect(onRemove).toHaveBeenCalledWith('ov-1');+ });+});++describe('clampTrim', () => {+ const segment = { inSec: 0, outSec: 4, fadeInSec: 0, fadeOutSec: 0 };++ it('clamps out to the source duration', () => {+ expect(clampTrim(segment, { outSec: 99 }, 5, 24)).toMatchObject({ outSec: 5 });+ });++ it('keeps at least one frame between in and out, matching the server guard', () => {+ // 24fps → 1/24s minimum, not the old hardcoded 0.04.+ expect(clampTrim(segment, { inSec: 4 }, 4, 24).outSec - clampTrim(segment, { inSec: 4 }, 4, 24).inSec)+ .toBeCloseTo(1 / 24);+ });++ it('shrinks fades that no longer fit the tightened trim', () => {+ const faded = { inSec: 0, outSec: 4, fadeInSec: 1, fadeOutSec: 1 };+ const patched = clampTrim(faded, { outSec: 1 }, 4, 24);+ expect(patched.fadeInSec + patched.fadeOutSec).toBeCloseTo(1);+ });+});++describe('fitFadePatch', () => {+ it('leaves a fitting fade pair untouched', () => {+ expect(fitFadePatch({ fadeInSec: 0.5, fadeOutSec: 0.5 }, { fadeInSec: 1 }, 4)).toEqual({ fadeInSec: 1 });+ });++ it('scales an over-long pair down proportionally rather than dropping one', () => {+ const patched = fitFadePatch({ fadeInSec: 1, fadeOutSec: 3 }, { fadeInSec: 1 }, 2);+ expect(patched.fadeInSec).toBeCloseTo(0.5);+ expect(patched.fadeOutSec).toBeCloseTo(1.5);+ });++ it('zeroes both fades when the duration collapses', () => {+ const patched = fitFadePatch({ fadeInSec: 1, fadeOutSec: 1 }, { durationSec: 0 }, 0);+ expect(patched).toMatchObject({ fadeInSec: 0, fadeOutSec: 0 });+ });+});diff --git a/scripts/migrations/295-video-timeline-segments.js b/scripts/migrations/295-video-timeline-segments.jsnew file mode 100644index 0000000000..681e70d7cc--- /dev/null+++ b/scripts/migrations/295-video-timeline-segments.js@@ -0,0 +1,101 @@+/**+ * Upgrade data/video-projects.json to the v2 layered timeline shape.+ *+ * v1 projects persisted a single ordered `clips` array of+ * `{ clipId, inSec, outSec }`. v2 replaces that with three lanes — `segments`+ * (the ordered video lane, which now also holds stills), `overlays`, and+ * `audio` — plus a per-project `schemaVersion`.+ *+ * The service normalizes on every read too, so this migration is not strictly+ * required for correctness. It exists so the on-disk file matches what the app+ * writes: without it, a project the user never re-saves keeps its v1 shape+ * forever, and a backup/restore or a peer-copied file carries the old layout+ * around indefinitely.+ *+ * `clips` is deliberately RETAINED as a derived mirror of the clip segments —+ * an install rolled back to a v1 build still renders its video lane instead of+ * opening an empty project. Idempotent: a project already at schemaVersion 2+ * with a matching mirror is left untouched.+ */++import { existsSync } from 'fs';+import { readFile } from 'fs/promises';+import { join } from 'path';+import { writeJsonAtomic } from './_lib.js';++const SCHEMA_VERSION = 2;++const num = (value, fallback = 0) => {+ const n = Number(value);+ return Number.isFinite(n) ? n : fallback;+};++const deriveClips = (segments) => segments+ .filter((s) => s.type === 'clip')+ .map((s) => ({ clipId: s.clipId, inSec: s.inSec, outSec: s.outSec }));++// A v1 clip entry only carries clipId/inSec/outSec; everything the lane model+// adds gets its neutral default so the upgraded project renders identically.+const upgradeClip = (raw) => {+ const inSec = Math.max(0, num(raw.inSec, 0));+ const outSec = num(raw.outSec, NaN);+ if (!Number.isFinite(outSec) || outSec <= inSec) return null;+ return {+ type: 'clip',+ clipId: String(raw.clipId || ''),+ inSec,+ outSec,+ fadeInSec: 0,+ fadeOutSec: 0,+ volume: 1,+ };+};++export default {+ async up({ rootDir }) {+ const path = join(rootDir, 'data', 'video-projects.json');+ if (!existsSync(path)) return { ok: true, reason: 'no-projects-file', updated: 0 };++ const raw = await readFile(path, 'utf8').catch(() => null);+ if (raw == null) return { ok: false, reason: 'unreadable', updated: 0 };++ let projects;+ try {+ projects = JSON.parse(raw);+ } catch (err) {+ // A corrupt state file must not crash the migration runner — that would+ // turn a cosmetic upgrade into a boot blocker.+ console.warn(`⚠️ migration 295: ${path} is not valid JSON (${err.message}); skipping`);+ return { ok: false, reason: 'invalid-json', updated: 0 };+ }+ if (!Array.isArray(projects)) return { ok: false, reason: 'not-an-array', updated: 0 };++ let updated = 0;+ const next = projects.map((project) => {+ if (!project || typeof project !== 'object') return project;+ if (project.schemaVersion === SCHEMA_VERSION && Array.isArray(project.segments)) return project;++ const legacyClips = Array.isArray(project.clips) ? project.clips : [];+ const segments = Array.isArray(project.segments)+ ? project.segments+ : legacyClips.map(upgradeClip).filter(Boolean);++ updated += 1;+ return {+ ...project,+ schemaVersion: SCHEMA_VERSION,+ segments,+ overlays: Array.isArray(project.overlays) ? project.overlays : [],+ audio: project.audio && typeof project.audio === 'object' && !Array.isArray(project.audio)+ ? { clipVolume: num(project.audio.clipVolume, 1), tracks: Array.isArray(project.audio.tracks) ? project.audio.tracks : [] }+ : { clipVolume: 1, tracks: [] },+ clips: deriveClips(segments),+ };+ });++ if (!updated) return { ok: true, reason: 'already-current', updated: 0 };+ await writeJsonAtomic(path, next);+ console.log(`📝 ${path}: upgraded ${updated} timeline project${updated === 1 ? '' : 's'} to the layered segment model`);+ return { ok: true, reason: 'updated', updated };+ },+};diff --git a/scripts/migrations/295-video-timeline-segments.test.js b/scripts/migrations/295-video-timeline-segments.test.jsnew file mode 100644index 0000000000..abb3e06acc--- /dev/null+++ b/scripts/migrations/295-video-timeline-segments.test.js@@ -0,0 +1,102 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './295-video-timeline-segments.js';++const CLIP_A = '11111111-1111-4111-8111-111111111111';+const CLIP_B = '22222222-2222-4222-8222-222222222222';++const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);+const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));++describe('migration 295 — layered video timeline', () => {+ let rootDir;+ let projectsPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-295-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ projectsPath = join(rootDir, 'data/video-projects.json');+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('is a no-op on an install that has never used the timeline editor', async () => {+ const result = await migration.up({ rootDir });+ expect(result).toEqual({ ok: true, reason: 'no-projects-file', updated: 0 });+ });++ it('upgrades a v1 project to lanes while keeping the clips mirror', async () => {+ writeJson(projectsPath, [{+ id: 'p1',+ name: 'Example Project',+ createdAt: '2020-01-01T00:00:00.000Z',+ updatedAt: '2020-01-02T00:00:00.000Z',+ clips: [{ clipId: CLIP_A, inSec: 0, outSec: 4 }, { clipId: CLIP_B, inSec: 1, outSec: 2.5 }],+ }]);++ const result = await migration.up({ rootDir });+ const [project] = readJson(projectsPath);++ expect(result).toMatchObject({ ok: true, reason: 'updated', updated: 1 });+ expect(project.schemaVersion).toBe(2);+ expect(project.segments).toEqual([+ { type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 4, fadeInSec: 0, fadeOutSec: 0, volume: 1 },+ { type: 'clip', clipId: CLIP_B, inSec: 1, outSec: 2.5, fadeInSec: 0, fadeOutSec: 0, volume: 1 },+ ]);+ expect(project.overlays).toEqual([]);+ expect(project.audio).toEqual({ clipVolume: 1, tracks: [] });+ // Retained so a rolled-back v1 build still renders the video lane.+ expect(project.clips).toEqual([{ clipId: CLIP_A, inSec: 0, outSec: 4 }, { clipId: CLIP_B, inSec: 1, outSec: 2.5 }]);+ // Untouched metadata survives.+ expect(project.name).toBe('Example Project');+ expect(project.createdAt).toBe('2020-01-01T00:00:00.000Z');+ expect(project.updatedAt).toBe('2020-01-02T00:00:00.000Z');+ });++ it('drops a v1 clip with an inverted trim rather than carrying it into the lane', async () => {+ writeJson(projectsPath, [{ id: 'p1', clips: [{ clipId: CLIP_A, inSec: 5, outSec: 2 }, { clipId: CLIP_B, inSec: 0, outSec: 1 }] }]);++ await migration.up({ rootDir });+ const [project] = readJson(projectsPath);++ expect(project.segments).toHaveLength(1);+ expect(project.segments[0].clipId).toBe(CLIP_B);+ expect(project.clips).toEqual([{ clipId: CLIP_B, inSec: 0, outSec: 1 }]);+ });++ it('is idempotent — a second run reports already-current and rewrites nothing', async () => {+ writeJson(projectsPath, [{ id: 'p1', clips: [{ clipId: CLIP_A, inSec: 0, outSec: 2 }] }]);++ await migration.up({ rootDir });+ const afterFirst = readFileSync(projectsPath, 'utf8');+ const second = await migration.up({ rootDir });++ expect(second).toEqual({ ok: true, reason: 'already-current', updated: 0 });+ expect(readFileSync(projectsPath, 'utf8')).toBe(afterFirst);+ });++ it('upgrades only the projects that need it, in one pass', async () => {+ writeJson(projectsPath, [+ { id: 'v2', schemaVersion: 2, segments: [{ type: 'still', assetKind: 'images', assetFile: 'a.png', durationSec: 2 }], overlays: [], audio: { clipVolume: 1, tracks: [] }, clips: [] },+ { id: 'v1', clips: [{ clipId: CLIP_A, inSec: 0, outSec: 3 }] },+ ]);++ const result = await migration.up({ rootDir });+ const [alreadyV2, upgraded] = readJson(projectsPath);++ expect(result.updated).toBe(1);+ expect(alreadyV2.segments[0]).toMatchObject({ type: 'still', assetFile: 'a.png' });+ expect(upgraded.schemaVersion).toBe(2);+ });++ it('reports corrupt state instead of crashing the migration runner', async () => {+ writeFileSync(projectsPath, '{ not json');+ expect(await migration.up({ rootDir })).toMatchObject({ ok: false, reason: 'invalid-json' });++ writeJson(projectsPath, { projects: [] });+ expect(await migration.up({ rootDir })).toMatchObject({ ok: false, reason: 'not-an-array' });+ });+});diff --git a/server/routes/videoTimeline.js b/server/routes/videoTimeline.jsindex 44cb3a7151..ba159eac90 100644--- a/server/routes/videoTimeline.js+++ b/server/routes/videoTimeline.js@@ -23,22 +23,96 @@ import {const router = Router();+// Lane schemas mirror server/services/videoTimeline/segments.js. Zod is the+// coarse shape/bounds gate at the edge; the service validators re-check the+// cross-field rules (fades fitting inside their own duration, asset+// containment under an allowlisted data/ subdirectory) that a schema can't+// express against the filesystem.+const IMAGE_ASSET_KINDS = ['images', 'video-thumbnails'];+const AUDIO_ASSET_KINDS = ['audio', 'music'];++const fadeFields = {+ fadeInSec: z.number().min(0).max(30).optional(),+ fadeOutSec: z.number().min(0).max(30).optional(),+};++const assetFields = (kinds) => ({+ assetKind: z.enum(kinds),+ // Basename only — the service resolves it under the kind's data/ root and+ // refuses anything that escapes.+ assetFile: z.string().min(1).max(255),+});+const clipSchema = z.object({clipId: z.string().guid(),inSec: z.number().min(0),outSec: z.number().min(0),}).refine((c) => c.outSec > c.inSec, { message: 'outSec must be > inSec', path: ['outSec'] });+const clipSegmentSchema = z.object({+ type: z.literal('clip'),+ clipId: z.string().guid(),+ inSec: z.number().min(0),+ outSec: z.number().min(0),+ volume: z.number().min(0).max(4).optional(),+ ...fadeFields,+}).refine((c) => c.outSec > c.inSec, { message: 'outSec must be > inSec', path: ['outSec'] });++const stillSegmentSchema = z.object({+ type: z.literal('still'),+ ...assetFields(IMAGE_ASSET_KINDS),+ durationSec: z.number().gt(0).max(600),+ ...fadeFields,+});++const segmentSchema = z.discriminatedUnion('type', [clipSegmentSchema, stillSegmentSchema]);++const overlaySchema = z.object({+ type: z.literal('image').optional(),+ ...assetFields(IMAGE_ASSET_KINDS),+ startSec: z.number().min(0),+ durationSec: z.number().gt(0).max(600),+ // Normalized to the canonical canvas so placement survives a change of+ // canonical dimensions. Slight overscan lets a graphic bleed off-frame.+ x: z.number().min(-1).max(2).optional(),+ y: z.number().min(-1).max(2).optional(),+ width: z.number().gt(0).max(4).optional(),+ opacity: z.number().min(0).max(1).optional(),+ ...fadeFields,+});++const audioTrackSchema = z.object({+ ...assetFields(AUDIO_ASSET_KINDS),+ startSec: z.number().min(0),+ offsetSec: z.number().min(0).optional(),+ durationSec: z.number().gt(0).max(600),+ volume: z.number().min(0).max(4).optional(),+ ...fadeFields,+});++const audioSchema = z.object({+ clipVolume: z.number().min(0).max(4).optional(),+ tracks: z.array(audioTrackSchema).max(20).optional(),+});+const createBodySchema = z.object({name: z.string().min(1).max(200),});+const LANE_KEYS = ['name', 'clips', 'segments', 'overlays', 'audio'];+const updateBodySchema = z.object({name: z.string().min(1).max(200).optional(),+ // `clips` is the v1 video lane. Still accepted so an older client (or an+ // older peer-authored payload) keeps working; the service upgrades it to+ // clip segments, and `segments` wins when both are present.clips: z.array(clipSchema).max(200).optional(),+ segments: z.array(segmentSchema).max(200).optional(),+ overlays: z.array(overlaySchema).max(50).optional(),+ audio: audioSchema.optional(),expectedUpdatedAt: z.string().optional(),-}).refine((b) => b.name !== undefined || b.clips !== undefined, {- message: 'PATCH body must include at least name or clips',+}).refine((b) => LANE_KEYS.some((k) => b[k] !== undefined), {+ message: `PATCH body must include at least one of: ${LANE_KEYS.join(', ')}`,});// Backward-compatible by default: returns the full projects array. When a clientdiff --git a/server/services/videoTimeline/local.crud.test.js b/server/services/videoTimeline/local.crud.test.jsnew file mode 100644index 0000000000..11eda88927--- /dev/null+++ b/server/services/videoTimeline/local.crud.test.js@@ -0,0 +1,166 @@+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { writeFileSync, readFileSync, mkdirSync } from 'fs';+import { join } from 'path';+import { mockPathsDataRoot } from '../../lib/mockPathsDataRoot.js';++// CRUD round-trip for the layered timeline: a v1 project loads as lanes, both+// PATCH shapes converge on `segments`, and the derived `clips` mirror is+// rebuilt on every write.+const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'timeline-crud-' });++vi.mock('../../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../../lib/fileUtils.js');+ return makeProxy(actual);+});++const { createProject, getProject, listProjects, updateProject, deleteProject } = await import('./local.js');++const PROJECTS_FILE = join(tempRoot, 'video-projects.json');+const CLIP_A = '11111111-1111-4111-8111-111111111111';+const CLIP_B = '22222222-2222-4222-8222-222222222222';++const seed = (projects) => {+ mkdirSync(tempRoot, { recursive: true });+ writeFileSync(PROJECTS_FILE, JSON.stringify(projects, null, 2));+};+const onDisk = () => JSON.parse(readFileSync(PROJECTS_FILE, 'utf8'));++beforeEach(() => seed([]));+afterAll(() => cleanup());++describe('createProject', () => {+ it('starts a new project at the current schema version with three empty lanes', async () => {+ const project = await createProject('Example Project');+ expect(project).toMatchObject({+ name: 'Example Project',+ schemaVersion: 2,+ segments: [],+ overlays: [],+ audio: { clipVolume: 1, tracks: [] },+ clips: [],+ });+ });+});++describe('loading a v1 project', () => {+ it('presents a legacy clips-only project as lanes without needing the migration to have run', async () => {+ seed([{ id: 'p1', name: 'Legacy', updatedAt: 'u1', clips: [{ clipId: CLIP_A, inSec: 0, outSec: 4 }] }]);++ const project = await getProject('p1');++ expect(project.schemaVersion).toBe(2);+ expect(project.segments).toEqual([+ { type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 4, fadeInSec: 0, fadeOutSec: 0, volume: 1 },+ ]);+ expect(project.overlays).toEqual([]);+ // Read-only: the file itself is untouched until something writes.+ expect(onDisk()[0].segments).toBeUndefined();+ });++ it('lists a corrupt file as empty rather than crashing', async () => {+ writeFileSync(PROJECTS_FILE, JSON.stringify({ projects: [] }));+ expect(await listProjects()).toEqual([]);+ });+});++describe('updateProject — lane writes', () => {+ it('accepts the v1 clips payload and upgrades it into the video lane', async () => {+ seed([{ id: 'p1', name: 'Legacy', updatedAt: 'u1', clips: [] }]);++ const updated = await updateProject('p1', { clips: [{ clipId: CLIP_A, inSec: 0, outSec: 2 }] });++ expect(updated.segments).toEqual([+ { type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 2, fadeInSec: 0, fadeOutSec: 0, volume: 1 },+ ]);+ expect(onDisk()[0].schemaVersion).toBe(2);+ });++ it('lets segments win when a client sends both shapes', async () => {+ seed([{ id: 'p1', updatedAt: 'u1', clips: [] }]);++ const updated = await updateProject('p1', {+ clips: [{ clipId: CLIP_A, inSec: 0, outSec: 2 }],+ segments: [{ type: 'clip', clipId: CLIP_B, inSec: 0, outSec: 3 }],+ });++ expect(updated.segments).toHaveLength(1);+ expect(updated.segments[0].clipId).toBe(CLIP_B);+ });++ it('rebuilds the clips mirror from the written lane on every save', async () => {+ seed([{ id: 'p1', updatedAt: 'u1', clips: [{ clipId: CLIP_A, inSec: 0, outSec: 9 }] }]);++ const updated = await updateProject('p1', {+ segments: [+ { type: 'clip', clipId: CLIP_B, inSec: 1, outSec: 3 },+ { type: 'still', assetKind: 'images', assetFile: 'plate.png', durationSec: 2 },+ ],+ });++ // The stale mirror entry is gone; the still contributes nothing to it.+ expect(updated.clips).toEqual([{ clipId: CLIP_B, inSec: 1, outSec: 3 }]);+ expect(onDisk()[0].clips).toEqual([{ clipId: CLIP_B, inSec: 1, outSec: 3 }]);+ });++ it('persists overlays and the audio mix', async () => {+ seed([{ id: 'p1', updatedAt: 'u1', clips: [] }]);++ const updated = await updateProject('p1', {+ segments: [{ type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 5 }],+ overlays: [{ assetKind: 'images', assetFile: 'logo.png', startSec: 1, durationSec: 2, opacity: 0.5 }],+ audio: { clipVolume: 0.3, tracks: [{ assetKind: 'music', assetFile: 'bed.mp3', startSec: 0, durationSec: 4, volume: 0.7 }] },+ });++ expect(updated.overlays[0]).toMatchObject({ type: 'image', assetFile: 'logo.png', opacity: 0.5 });+ expect(updated.audio).toMatchObject({ clipVolume: 0.3 });+ expect(updated.audio.tracks[0]).toMatchObject({ assetFile: 'bed.mp3', volume: 0.7 });+ });++ it('clears a lane when the client sends it empty', async () => {+ seed([{+ id: 'p1', updatedAt: 'u1', schemaVersion: 2, clips: [],+ segments: [], overlays: [{ assetKind: 'images', assetFile: 'logo.png', startSec: 0, durationSec: 1 }],+ audio: { clipVolume: 1, tracks: [] },+ }]);++ expect((await updateProject('p1', { overlays: [] })).overlays).toEqual([]);+ });++ it('leaves an unmentioned lane alone', async () => {+ seed([{+ id: 'p1', updatedAt: 'u1', schemaVersion: 2, clips: [],+ segments: [], overlays: [{ assetKind: 'images', assetFile: 'logo.png', startSec: 0, durationSec: 1 }],+ audio: { clipVolume: 0.4, tracks: [] },+ }]);++ const updated = await updateProject('p1', { name: 'Renamed' });++ expect(updated.name).toBe('Renamed');+ expect(updated.overlays).toHaveLength(1);+ expect(updated.audio.clipVolume).toBe(0.4);+ });++ it('rejects an invalid lane without writing anything', async () => {+ seed([{ id: 'p1', updatedAt: 'u1', schemaVersion: 2, segments: [], overlays: [], audio: { clipVolume: 1, tracks: [] }, clips: [] }]);++ await expect(updateProject('p1', {+ overlays: [{ assetKind: 'images', assetFile: '../../etc/passwd', startSec: 0, durationSec: 1 }],+ })).rejects.toThrow(/plain filename/);++ expect(onDisk()[0].updatedAt).toBe('u1');+ });++ it('still refuses a stale expectedUpdatedAt across the new lanes', async () => {+ seed([{ id: 'p1', updatedAt: 'u2', schemaVersion: 2, segments: [], overlays: [], audio: { clipVolume: 1, tracks: [] }, clips: [] }]);++ await expect(updateProject('p1', { overlays: [] }, 'u1')).rejects.toMatchObject({ code: 'CONFLICT' });+ });+});++describe('deleteProject', () => {+ it('removes the project and 404s on a second attempt', async () => {+ seed([{ id: 'p1', updatedAt: 'u1', clips: [] }]);+ expect(await deleteProject('p1')).toEqual({ ok: true });+ await expect(deleteProject('p1')).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });+});diff --git a/server/services/videoTimeline/local.js b/server/services/videoTimeline/local.jsindex f8b146e4a8..b858b8fc3c 100644--- a/server/services/videoTimeline/local.js+++ b/server/services/videoTimeline/local.js@@ -27,10 +27,33 @@ import { findFfmpeg, findFfprobe, safeUnder, generateThumbnail } from '../../libimport { safeChildProcessOptions } from '../../lib/processEnv.js';import { killWithEscalation } from '../../lib/killWithEscalation.js';import { attachFfmpegRenderGuard } from '../../lib/ffmpegRenderGuard.js';+import { mapWithConcurrency } from '../../lib/mapWithConcurrency.js';import { loadHistory, mutateVideoHistory } from '../videoGen/local.js';+import {+ TIMELINE_SCHEMA_VERSION,+ IMAGE_ASSET_KINDS,+ AUDIO_ASSET_KINDS,+ normalizeProject,+ validateSegments,+ validateOverlays,+ validateAudio,+ defaultAudio,+ deriveLegacyClips,+ resolveAsset,+ segmentDuration,+} from './segments.js';const PROJECTS_FILE = join(PATHS.data, 'video-projects.json');+// ffprobe spawns one child per source, so cap the fan-out: a 200-segment+// project would otherwise fork-bomb on render startup.+const PROBE_CONCURRENCY = 8;+// A stills-only project has no clip to take geometry from.+const DEFAULT_CANVAS = { width: 1280, height: 720, fps: 24 };+// Floor for a probe-clamped audio slice — atrim with start === end produces+// an empty stream that amix rejects.+const MIN_MEDIA_SEC = 0.05;+// Per-project render mutex map. Keyed by projectId so two different projects// can render in parallel; same project re-render returns 409 with the// existing jobId so the UI can attach SSE instead of getting a stale failure.@@ -61,7 +84,11 @@ export const loadProjects = async () => {// a non-array root would crash every CRUD path with "x.findIndex is not a// function" instead of degrading gracefully to an empty list.const raw = await readJSONFile(PROJECTS_FILE, []);- return Array.isArray(raw) ? raw : [];+ // Every read upgrades v1 (`clips`-only) projects to the v2 lane shape in+ // memory, so the rest of the service only ever sees `segments`/`overlays`/+ // `audio`. The on-disk upgrade is migration 295; this keeps a project the+ // migration missed (restored backup, peer-copied file) working anyway.+ return Array.isArray(raw) ? raw.map(normalizeProject) : [];};const saveProjects = async (projects) => {// First write on a fresh install lands before PATHS.data is created by any@@ -90,6 +117,10 @@ export async function createProject(name) {name: trimmed,createdAt: now,updatedAt: now,+ schemaVersion: TIMELINE_SCHEMA_VERSION,+ segments: [],+ overlays: [],+ audio: defaultAudio(),clips: [],};projects.unshift(project);@@ -98,24 +129,11 @@ export async function createProject(name) {return project;}-// Validate a single clip patch entry. Returns the cleaned object or throws.-// We don't trust client-supplied numFrames/fps — those come from the history-// entry at render time. Only clipId + inSec/outSec are persisted.-const validateClip = (raw, idx) => {- if (!raw || typeof raw !== 'object') {- throw new ServerError(`Clip ${idx}: must be an object`, { status: 400, code: 'VALIDATION_ERROR' });- }- const clipId = String(raw.clipId || '').trim();- if (!/^[a-f0-9-]{36}$/i.test(clipId)) {- throw new ServerError(`Clip ${idx}: invalid clipId`, { status: 400, code: 'VALIDATION_ERROR' });- }- const inSec = Number(raw.inSec);- const outSec = Number(raw.outSec);- if (!Number.isFinite(inSec) || !Number.isFinite(outSec) || inSec < 0 || outSec <= inSec) {- throw new ServerError(`Clip ${idx}: inSec/outSec invalid (need 0 ≤ inSec < outSec)`, { status: 400, code: 'VALIDATION_ERROR' });- }- return { clipId, inSec, outSec };-};+// The video lane replaces v1's flat `clips` array. `validateSegments` owns+// every per-entry rule (clip trim bounds, still duration, asset containment,+// fades that fit inside their own duration) for both shapes — we don't trust+// client-supplied numFrames/fps here either; those come from the history+// entry at render time.export async function updateProject(id, patch, expectedUpdatedAt) {const projects = await loadProjects();@@ -138,12 +156,23 @@ export async function updateProject(id, patch, expectedUpdatedAt) {if (!trimmed) throw new ServerError('Project name cannot be empty', { status: 400, code: 'VALIDATION_ERROR' });project.name = trimmed;}- if (patch.clips != null) {+ if (patch.segments != null) {+ project.segments = validateSegments(patch.segments);+ } else if (patch.clips != null) {+ // Legacy v1 client (or an older peer-authored payload): a flat clip array+ // replaces the whole video lane. Upgraded in place so the persisted model+ // stays single-shaped regardless of which client wrote it.if (!Array.isArray(patch.clips)) {throw new ServerError('clips must be an array', { status: 400, code: 'VALIDATION_ERROR' });}- project.clips = patch.clips.map(validateClip);+ project.segments = validateSegments(patch.clips.map((c) => ({ type: 'clip', ...(c && typeof c === 'object' ? c : {}) })));}+ if (patch.overlays != null) project.overlays = validateOverlays(patch.overlays);+ if (patch.audio != null) project.audio = validateAudio(patch.audio);+ // `clips` is a derived mirror, never an input to the render — rebuild it from+ // the authoritative lane on every write so it can't drift.+ project.schemaVersion = TIMELINE_SCHEMA_VERSION;+ project.clips = deriveLegacyClips(project.segments || []);project.updatedAt = new Date().toISOString();projects[idx] = project;await saveProjects(projects);@@ -187,12 +216,38 @@ const probeAudio = async (videoPath) => {});};-// Resolve every clip in a project to a verified on-disk path + duration +-// audio-presence. Throws ServerError(404) listing every missing/invalid clip-// so the editor can highlight them. Returns the array of resolved entries-// in project order.-export async function resolveClips(project) {- if (!Array.isArray(project.clips) || project.clips.length === 0) {+// ffprobe a media file's duration in seconds, or null when ffprobe is missing+// or the container reports no duration. Used to clamp an audio track's+// requested slice to what the file actually holds — an atrim past EOF yields a+// shorter-than-declared bed, which amix then pads with silence.+const probeDuration = async (mediaPath) => {+ const ffprobe = await findFfprobe();+ if (!ffprobe) return null;+ return new Promise((resolve) => {+ const proc = spawn(ffprobe, [+ '-v', 'error',+ '-show_entries', 'format=duration',+ '-of', 'default=nw=1:nk=1',+ mediaPath,+ ], safeChildProcessOptions({ stdio: ['ignore', 'pipe', 'ignore'] }));+ let out = '';+ proc.stdout.on('data', (c) => { out += c.toString(); });+ proc.on('close', () => {+ const n = Number(out.trim());+ resolve(Number.isFinite(n) && n > 0 ? n : null);+ });+ proc.on('error', () => resolve(null));+ });+};++// Resolve a project's three lanes to verified on-disk paths + durations ++// audio-presence. Throws ServerError(404) listing every missing clip AND every+// missing asset so the editor can highlight them all in one pass instead of+// surfacing one broken reference per failed render.+export async function resolveTimeline(rawProject) {+ const project = normalizeProject(rawProject);+ const segments = project.segments || [];+ if (segments.length === 0) {throw new ServerError('Project has no clips', { status: 400, code: 'EMPTY_PROJECT' });}const history = await loadHistory();@@ -201,97 +256,235 @@ export async function resolveClips(project) {const historyList = Array.isArray(history) ? history : [];const historyMap = new Map(historyList.map((h) => [h.id, h]));const missing = [];+ const missingAssets = [];const prepared = [];- for (let i = 0; i < project.clips.length; i++) {- const ref = project.clips[i];- const entry = historyMap.get(ref.clipId);- if (!entry) { missing.push(ref.clipId); continue; }++ for (let i = 0; i < segments.length; i++) {+ const seg = segments[i];+ if (seg.type === 'still') {+ const assetPath = resolveAsset(seg.assetKind, seg.assetFile, { allowedKinds: IMAGE_ASSET_KINDS });+ if (!assetPath) { missingAssets.push(`${seg.assetKind}/${seg.assetFile}`); continue; }+ prepared.push({ kind: 'still', i, seg, assetPath, duration: seg.durationSec });+ continue;+ }+ const entry = historyMap.get(seg.clipId);+ if (!entry) { missing.push(seg.clipId); continue; }const videoPath = safeUnder(PATHS.videos, entry.filename);- if (!videoPath || !existsSync(videoPath)) { missing.push(ref.clipId); continue; }+ if (!videoPath || !existsSync(videoPath)) { missing.push(seg.clipId); continue; }const sourceDuration = entry.numFrames && entry.fps ? entry.numFrames / entry.fps : null;- const inSec = Math.max(0, ref.inSec);- const outSec = sourceDuration != null ? Math.min(ref.outSec, sourceDuration) : ref.outSec;+ const inSec = Math.max(0, seg.inSec);+ const outSec = sourceDuration != null ? Math.min(seg.outSec, sourceDuration) : seg.outSec;if (outSec - inSec < 1 / Math.max(1, entry.fps || 24)) {throw new ServerError(`Clip ${i} trim too short — must be ≥ 1 frame`, {- status: 400, code: 'CLIP_TOO_SHORT', context: { index: i, clipId: ref.clipId },+ status: 400, code: 'CLIP_TOO_SHORT', context: { index: i, clipId: seg.clipId },});}- prepared.push({ i, ref, entry, videoPath, inSec, outSec });+ // A fade authored against the stored trim can outlast a clip that the+ // history entry has since shortened; rescale rather than emitting a+ // negative fade start (which renders as an all-black segment).+ const duration = outSec - inSec;+ const fades = fitFades(seg.fadeInSec, seg.fadeOutSec, duration);+ prepared.push({ kind: 'clip', i, seg, entry, videoPath, inSec, outSec, duration, fades });}- if (missing.length > 0) {- throw new ServerError(`Missing source clips: ${missing.length}`, {- status: 404, code: 'MISSING_CLIPS', context: { missingClipIds: missing },- });++ const overlays = [];+ for (const ov of project.overlays || []) {+ const assetPath = resolveAsset(ov.assetKind, ov.assetFile, { allowedKinds: IMAGE_ASSET_KINDS });+ if (!assetPath) { missingAssets.push(`${ov.assetKind}/${ov.assetFile}`); continue; }+ overlays.push({ ...ov, assetPath });}- // ffprobe spawns one child per clip. Parallelize, but cap concurrency so a- // 200-clip project doesn't fork-bomb on render startup.- const PROBE_CONCURRENCY = 8;- const audioFlags = new Array(prepared.length);- for (let start = 0; start < prepared.length; start += PROBE_CONCURRENCY) {- const batch = prepared.slice(start, start + PROBE_CONCURRENCY);- const results = await Promise.all(batch.map((p) => probeAudio(p.videoPath)));- for (let j = 0; j < results.length; j++) audioFlags[start + j] = results[j];++ const audioTracks = [];+ for (const tr of project.audio?.tracks || []) {+ const assetPath = resolveAsset(tr.assetKind, tr.assetFile, { allowedKinds: AUDIO_ASSET_KINDS });+ if (!assetPath) { missingAssets.push(`${tr.assetKind}/${tr.assetFile}`); continue; }+ audioTracks.push({ ...tr, assetPath });+ }++ if (missing.length > 0 || missingAssets.length > 0) {+ throw new ServerError(`Missing timeline sources: ${missing.length + missingAssets.length}`, {+ status: 404, code: 'MISSING_CLIPS', context: { missingClipIds: missing, missingAssets },+ });}- return prepared.map((p, idx) => ({- index: p.i,- clipId: p.ref.clipId,- videoPath: p.videoPath,- inSec: p.inSec,- outSec: p.outSec,- duration: p.outSec - p.inSec,- width: p.entry.width,- height: p.entry.height,- fps: p.entry.fps,- hasAudio: audioFlags[idx],- }));++ const clipEntries = prepared.filter((p) => p.kind === 'clip');+ const audioFlags = new Map();+ const clipAudio = await mapWithConcurrency(clipEntries, PROBE_CONCURRENCY, (p) => probeAudio(p.videoPath));+ clipEntries.forEach((p, j) => audioFlags.set(p.i, clipAudio[j]));++ const bedDurations = await mapWithConcurrency(audioTracks, PROBE_CONCURRENCY, (tr) => probeDuration(tr.assetPath));+ audioTracks.forEach((tr, j) => {+ const probed = bedDurations[j];+ // A probe reporting LESS than the requested slice is authoritative.+ // `null` (no ffprobe on PATH, unreadable container) must NOT collapse into+ // "0 seconds available" — leave the stored slice alone in that case.+ if (probed == null) return;+ tr.offsetSec = Math.min(tr.offsetSec, Math.max(0, probed - MIN_MEDIA_SEC));+ tr.durationSec = Math.min(tr.durationSec, Math.max(MIN_MEDIA_SEC, probed - tr.offsetSec));+ const fitted = fitFades(tr.fadeInSec, tr.fadeOutSec, tr.durationSec);+ tr.fadeInSec = fitted.fadeInSec;+ tr.fadeOutSec = fitted.fadeOutSec;+ });++ const resolvedSegments = prepared.map((p) => (p.kind === 'still'+ ? {+ type: 'still',+ index: p.i,+ assetKind: p.seg.assetKind,+ assetFile: p.seg.assetFile,+ assetPath: p.assetPath,+ duration: p.duration,+ fadeInSec: p.seg.fadeInSec,+ fadeOutSec: p.seg.fadeOutSec,+ }+ : {+ type: 'clip',+ index: p.i,+ clipId: p.seg.clipId,+ videoPath: p.videoPath,+ inSec: p.inSec,+ outSec: p.outSec,+ duration: p.duration,+ width: p.entry.width,+ height: p.entry.height,+ fps: p.entry.fps,+ hasAudio: audioFlags.get(p.i) === true,+ fadeInSec: p.fades.fadeInSec,+ fadeOutSec: p.fades.fadeOutSec,+ volume: p.seg.volume,+ }));++ const firstClip = resolvedSegments.find((seg) => seg.type === 'clip');+ return {+ segments: resolvedSegments,+ overlays,+ audioTracks,+ clipVolume: project.audio?.clipVolume ?? 1,+ // A stills-only project has no intrinsic geometry — fall back to 720p/24+ // rather than letting scale/pad inherit `undefined` and fail the graph.+ canonW: firstClip?.width || DEFAULT_CANVAS.width,+ canonH: firstClip?.height || DEFAULT_CANVAS.height,+ fps: firstClip?.fps || DEFAULT_CANVAS.fps,+ };+}++/**+ * Back-compat wrapper: the v1 entry point returned only the video lane.+ * Retained so any caller still asking for "the resolved clips" keeps working.+ */+export async function resolveClips(project) {+ return (await resolveTimeline(project)).segments;}-// scale+pad, aresample, and aformat are unconditional belt-and-suspenders.-// Without them, mixed LTX-2 versions error with "Input link parameters do-// not match" mid-render.-export function buildFfmpegArgs(clips, outputPath) {- if (clips.length === 0) throw new Error('buildFfmpegArgs: empty clips');- const canonW = clips[0].width;- const canonH = clips[0].height;+// Filter-graph number formatting. Raw interpolation of a subtraction result+// leaks float noise (`2.9000000000000004`) into the graph string, while+// toFixed would pad clean integers to `4.000`. Round to microseconds, then+// stringify.+const fmt = (n) => String(Math.round(Number(n) * 1e6) / 1e6);++// `fade` renders black (and `afade` silence) for the whole segment when its+// start time goes negative, so fades that no longer fit are scaled down+// proportionally rather than dropped — the author's intended balance survives.+function fitFades(fadeInSec, fadeOutSec, duration) {+ const fin = Math.max(0, Number(fadeInSec) || 0);+ const fout = Math.max(0, Number(fadeOutSec) || 0);+ const span = fin + fout;+ if (span <= duration || span === 0) return { fadeInSec: fin, fadeOutSec: fout };+ const scale = Math.max(0, duration) / span;+ return { fadeInSec: fin * scale, fadeOutSec: fout * scale };+}++const videoFades = (seg, duration) => {+ const parts = [];+ if (seg.fadeInSec > 0) parts.push(`fade=t=in:st=0:d=${fmt(seg.fadeInSec)}`);+ if (seg.fadeOutSec > 0) {+ parts.push(`fade=t=out:st=${fmt(Math.max(0, duration - seg.fadeOutSec))}:d=${fmt(seg.fadeOutSec)}`);+ }+ return parts.length > 0 ? `,${parts.join(',')}` : '';+};++const audioShaping = (seg, duration, volume) => {+ const parts = [];+ if (volume !== 1) parts.push(`volume=${fmt(volume)}`);+ if (seg.fadeInSec > 0) parts.push(`afade=t=in:st=0:d=${fmt(seg.fadeInSec)}`);+ if (seg.fadeOutSec > 0) {+ parts.push(`afade=t=out:st=${fmt(Math.max(0, duration - seg.fadeOutSec))}:d=${fmt(seg.fadeOutSec)}`);+ }+ return parts.length > 0 ? `,${parts.join(',')}` : '';+};++// scale+pad, format, aresample and aformat are unconditional+// belt-and-suspenders. Without them, mixed LTX-2 versions error with "Input+// link parameters do not match" mid-render — and an RGBA still concatenated+// after a yuv420p clip fails exactly the same way.+//+// Accepts either a resolved timeline object from resolveTimeline() or a bare+// segment array (the v1 signature — video lane only, no overlays or bed).+export function buildFfmpegArgs(timeline, outputPath) {+ const t = Array.isArray(timeline) ? { segments: timeline } : (timeline || {});+ const segments = t.segments || [];+ if (segments.length === 0) throw new Error('buildFfmpegArgs: empty clips');+ const overlays = t.overlays || [];+ const audioTracks = t.audioTracks || [];+ const clipVolume = t.clipVolume == null ? 1 : t.clipVolume;++ const firstClip = segments.find((seg) => (seg.type || 'clip') === 'clip');+ const canonW = t.canonW || firstClip?.width || DEFAULT_CANVAS.width;+ const canonH = t.canonH || firstClip?.height || DEFAULT_CANVAS.height;+ const fps = t.fps || firstClip?.fps || DEFAULT_CANVAS.fps;const inputs = [];const filters = [];const concatStreams = [];-let inputIdx = 0;- const indices = clips.map((c) => {++ const totalDuration = segments.reduce((sum, seg) => sum + (seg.duration ?? segmentDuration(seg)), 0);++ for (let i = 0; i < segments.length; i++) {+ const seg = segments[i];+ const isStill = (seg.type || 'clip') === 'still';+ const duration = seg.duration ?? segmentDuration(seg);+const vIdx = inputIdx++;- inputs.push('-i', c.videoPath);+ if (isStill) {+ // -loop 1 turns a single image into an endless stream; -t bounds it to+ // the segment's held duration so concat receives a finite input.+ inputs.push('-loop', '1', '-t', fmt(duration), '-i', seg.assetPath);+ } else {+ inputs.push('-i', seg.videoPath);+ }++ // fps=<canon> resamples each source to the timeline's canonical frame rate;+ // without it, concat fails with "Input link parameters do not match" when a+ // project mixes clips of different fps (e.g. a 24fps generation next to a+ // 30fps one) or holds a still alongside them.+ const trim = isStill+ ? `trim=start=0:end=${fmt(duration)}`+ : `trim=start=${fmt(seg.inSec)}:end=${fmt(seg.outSec)}`;+ filters.push(+ `[${vIdx}:v]scale=${canonW}:${canonH}:force_original_aspect_ratio=decrease,pad=${canonW}:${canonH}:(ow-iw)/2:(oh-ih)/2,setsar=1,format=yuv420p,fps=${fps},${trim},setpts=PTS-STARTPTS${videoFades(seg, duration)}[v${i}]`+ );++ const hasAudio = !isStill && seg.hasAudio;let aIdx;- if (c.hasAudio) {+ if (hasAudio) {aIdx = vIdx;} else {- // -t bounds the otherwise-infinite anullsrc to match the trimmed clip+ // -t bounds the otherwise-infinite anullsrc to match the segment's// duration so concat=v=1:a=1 gets a length-matched silent track.aIdx = inputIdx++;- inputs.push('-f', 'lavfi', '-t', String(c.duration), '-i', `anullsrc=channel_layout=stereo:sample_rate=48000`);+ inputs.push('-f', 'lavfi', '-t', fmt(duration), '-i', `anullsrc=channel_layout=stereo:sample_rate=48000`);}- return { vIdx, aIdx };- });-- for (let i = 0; i < clips.length; i++) {- const c = clips[i];- const { vIdx, aIdx } = indices[i];- // fps=<canon> resamples each clip to the timeline's canonical frame rate;- // without it, concat fails with "Input link parameters do not match" when- // a project mixes clips of different fps (e.g. a 24fps generation and a- // 30fps one).- filters.push(- `[${vIdx}:v]scale=${canonW}:${canonH}:force_original_aspect_ratio=decrease,pad=${canonW}:${canonH}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=${clips[0].fps || 24},trim=start=${c.inSec}:end=${c.outSec},setpts=PTS-STARTPTS[v${i}]`- );- if (c.hasAudio) {+ if (hasAudio) {+ const vol = clipVolume * (seg.volume == null ? 1 : seg.volume);filters.push(- `[${aIdx}:a]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,atrim=start=${c.inSec}:end=${c.outSec},asetpts=PTS-STARTPTS[a${i}]`+ `[${aIdx}:a]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,atrim=start=${fmt(seg.inSec)}:end=${fmt(seg.outSec)},asetpts=PTS-STARTPTS${audioShaping(seg, duration, vol)}[a${i}]`);} else {// The silent input must match the same sample-format/layout as the// real-audio branches; concat=v=1:a=1 fails fast with "Input link- // parameters do not match" if they diverge.+ // parameters do not match" if they diverge. No volume or fade here — the+ // stream is already silence.filters.push(`[${aIdx}:a]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,asetpts=PTS-STARTPTS[a${i}]`);@@ -299,9 +492,73 @@ export function buildFfmpegArgs(clips, outputPath) {concatStreams.push(`[v${i}][a${i}]`);}- filters.push(`${concatStreams.join('')}concat=n=${clips.length}:v=1:a=1[outv][outa]`);+ // Label the concat outputs as the FINAL outputs whenever no later lane+ // post-processes them, so a plain clip-only project still produces the exact+ // minimal graph it always has.+ const vConcatOut = overlays.length > 0 ? '[cv]' : '[outv]';+ const aConcatOut = audioTracks.length > 0 ? '[ca]' : '[outa]';+ filters.push(`${concatStreams.join('')}concat=n=${segments.length}:v=1:a=1${vConcatOut}${aConcatOut}`);++ // Overlay lane. Each overlay input is looped for the WHOLE timeline rather+ // than just its own window: overlay() blocks waiting on a secondary frame+ // when the secondary stream starts late, so we keep it always-available and+ // gate visibility with enable=between(). The alpha fades therefore run on+ // the shared timeline clock, not an overlay-local one.+ let overlayIn = '[cv]';+ overlays.forEach((ov, j) => {+ const oIdx = inputIdx++;+ inputs.push('-loop', '1', '-t', fmt(totalDuration), '-i', ov.assetPath);+ // -2 keeps the auto-derived height even — libx264 rejects odd dimensions+ // once the overlay is composited back into yuv420p.+ const w = Math.max(2, Math.round((ov.width * canonW) / 2) * 2);+ const x = Math.round(ov.x * canonW);+ const y = Math.round(ov.y * canonH);+ const end = Math.min(totalDuration, ov.startSec + ov.durationSec);+ const chain = [`scale=${w}:-2`, `fps=${fps}`, 'format=rgba'];+ if (ov.opacity < 1) chain.push(`colorchannelmixer=aa=${fmt(ov.opacity)}`);+ if (ov.fadeInSec > 0) chain.push(`fade=t=in:st=${fmt(ov.startSec)}:d=${fmt(ov.fadeInSec)}:alpha=1`);+ if (ov.fadeOutSec > 0) {+ chain.push(`fade=t=out:st=${fmt(Math.max(ov.startSec, end - ov.fadeOutSec))}:d=${fmt(ov.fadeOutSec)}:alpha=1`);+ }+ filters.push(`[${oIdx}:v]${chain.join(',')}[ov${j}]`);+ const out = j === overlays.length - 1 ? '[outv]' : `[ovc${j}]`;+ filters.push(+ `${overlayIn}[ov${j}]overlay=x=${x}:y=${y}:eof_action=pass:enable='between(t,${fmt(ov.startSec)},${fmt(end)})'${out}`+ );+ overlayIn = out;+ });- const totalDuration = clips.reduce((s, c) => s + c.duration, 0);+ // Audio bed. Each track is trimmed from its own offset, faded on its own+ // clock, then delayed to its project-time start before mixing under the+ // concatenated lane audio. normalize=0 keeps adding a second bed from+ // silently attenuating everything already in the mix.+ if (audioTracks.length > 0) {+ const bedLabels = [];+ audioTracks.forEach((tr, j) => {+ const aIdx = inputIdx++;+ inputs.push('-i', tr.assetPath);+ const parts = [+ 'aresample=48000',+ 'aformat=sample_fmts=fltp:channel_layouts=stereo',+ `atrim=start=${fmt(tr.offsetSec)}:end=${fmt(tr.offsetSec + tr.durationSec)}`,+ 'asetpts=PTS-STARTPTS',+ ];+ if (tr.volume !== 1) parts.push(`volume=${fmt(tr.volume)}`);+ if (tr.fadeInSec > 0) parts.push(`afade=t=in:st=0:d=${fmt(tr.fadeInSec)}`);+ if (tr.fadeOutSec > 0) {+ parts.push(`afade=t=out:st=${fmt(Math.max(0, tr.durationSec - tr.fadeOutSec))}:d=${fmt(tr.fadeOutSec)}`);+ }+ if (tr.startSec > 0) {+ const ms = Math.round(tr.startSec * 1000);+ parts.push(`adelay=${ms}|${ms}`);+ }+ filters.push(`[${aIdx}:a]${parts.join(',')}[bed${j}]`);+ bedLabels.push(`[bed${j}]`);+ });+ filters.push(+ `[ca]${bedLabels.join('')}amix=inputs=${bedLabels.length + 1}:duration=first:dropout_transition=0:normalize=0[outa]`+ );+ }const args = [...inputs,@@ -320,7 +577,7 @@ export function buildFfmpegArgs(clips, outputPath) {outputPath,];- return { args, totalDuration, canonW, canonH, fps: clips[0].fps };+ return { args, totalDuration, canonW, canonH, fps };}export function cancelRender(jobId) {@@ -348,17 +605,17 @@ export async function renderProject(projectId) {const ffmpeg = await findFfmpeg();if (!ffmpeg) throw new ServerError('ffmpeg not found on PATH', { status: 500, code: 'FFMPEG_MISSING' });- // Resolve clips and build args BEFORE claiming the mutex — if either step- // throws (missing clips, validation), a stale projectRenders entry would- // permanently block future renders of this project.- const clips = await resolveClips(project);+ // Resolve every lane and build args BEFORE claiming the mutex — if either+ // step throws (missing clips or assets, validation), a stale projectRenders+ // entry would permanently block future renders of this project.+ const timeline = await resolveTimeline(project);await ensureDir(PATHS.videos);await ensureDir(PATHS.videoThumbnails);const jobId = randomUUID();const filename = `timeline-${projectId.slice(0, 8)}-${Date.now()}.mp4`;const outputPath = join(PATHS.videos, filename);- const { args, totalDuration, canonW, canonH, fps } = buildFfmpegArgs(clips, outputPath);+ const { args, totalDuration, canonW, canonH, fps } = buildFfmpegArgs(timeline, outputPath);const job = {id: jobId,@@ -371,7 +628,7 @@ export async function renderProject(projectId) {jobs.set(jobId, job);projectRenders.set(projectId, jobId);- console.log(`🎞️ Rendering timeline [${jobId.slice(0, 8)}]: project=${projectId.slice(0, 8)} clips=${clips.length} duration=${totalDuration.toFixed(2)}s`);+ console.log(`🎞️ Rendering timeline [${jobId.slice(0, 8)}]: project=${projectId.slice(0, 8)} segments=${timeline.segments.length} overlays=${timeline.overlays.length} beds=${timeline.audioTracks.length} duration=${totalDuration.toFixed(2)}s`);const proc = spawn(ffmpeg, args, safeChildProcessOptions({ stdio: ['ignore', 'ignore', 'pipe'] }));job.process = proc;diff --git a/server/services/videoTimeline/local.test.js b/server/services/videoTimeline/local.test.jsindex ae6d4d0d57..d24095d2ea 100644--- a/server/services/videoTimeline/local.test.js+++ b/server/services/videoTimeline/local.test.js@@ -113,3 +113,244 @@ describe('buildFfmpegArgs', () => {expect(args[args.length - 1]).toBe('/out.mp4');});});++// --- Layered lanes (schemaVersion 2) -----------------------------------++const stillSegment = (overrides = {}) => ({+ type: 'still',+ index: 0,+ assetKind: 'images',+ assetFile: 'plate.png',+ assetPath: '/data/images/plate.png',+ duration: 3,+ fadeInSec: 0,+ fadeOutSec: 0,+ ...overrides,+});++const filterOf = (args) => args[args.indexOf('-filter_complex') + 1];++describe('buildFfmpegArgs — stills in the video lane', () => {+ it('loops a still for exactly its hold and normalizes it to the canonical geometry', () => {+ const { args, totalDuration, canonW, canonH } = buildFfmpegArgs({+ segments: [baseClip({ width: 1024, height: 576, fps: 30 }), stillSegment()],+ canonW: 1024, canonH: 576, fps: 30,+ }, '/out.mp4');++ expect(totalDuration).toBe(7);+ expect(canonW).toBe(1024);+ expect(canonH).toBe(576);++ const inputs = args.slice(0, args.indexOf('-filter_complex'));+ // clip (0) + its real audio, then the still (1) + an anullsrc stub (2).+ expect(inputs).toContain('-loop');+ expect(inputs).toContain('/data/images/plate.png');++ const filter = filterOf(args);+ // The still is scaled/padded to the SAME canvas as the clip, and forced to+ // yuv420p so concat's link parameters match.+ expect(filter).toContain('[1:v]scale=1024:576');+ expect(filter).toContain('format=yuv420p');+ expect(filter).toContain('trim=start=0:end=3');+ // A still has no audio of its own — it gets the silent stub.+ expect(filter).toContain('[2:a]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,asetpts=PTS-STARTPTS[a1]');+ expect(filter).toContain('[v0][a0][v1][a1]concat=n=2:v=1:a=1[outv][outa]');+ });++ it('falls back to 720p24 for a stills-only project rather than inheriting undefined geometry', () => {+ const { args, canonW, canonH, fps } = buildFfmpegArgs({ segments: [stillSegment()] }, '/out.mp4');+ expect(canonW).toBe(1280);+ expect(canonH).toBe(720);+ expect(fps).toBe(24);+ expect(filterOf(args)).toContain('scale=1280:720');+ });+});++describe('buildFfmpegArgs — fades', () => {+ it('emits video and audio fades anchored to the segment, not the source', () => {+ const filter = filterOf(buildFfmpegArgs({+ segments: [baseClip({ inSec: 2, outSec: 6, duration: 4, fadeInSec: 0.5, fadeOutSec: 1 })],+ }, '/out.mp4').args);++ // setpts rebases the segment to t=0, so the fades are relative to that.+ expect(filter).toContain('setpts=PTS-STARTPTS,fade=t=in:st=0:d=0.5,fade=t=out:st=3:d=1[v0]');+ expect(filter).toContain('asetpts=PTS-STARTPTS,afade=t=in:st=0:d=0.5,afade=t=out:st=3:d=1[a0]');+ });++ it('omits fade filters entirely when both fades are zero', () => {+ const filter = filterOf(buildFfmpegArgs({ segments: [baseClip()] }, '/out.mp4').args);+ expect(filter).not.toContain('fade=');+ });++ it('applies the clip volume multiplier to the segment audio', () => {+ const filter = filterOf(buildFfmpegArgs({+ segments: [baseClip({ volume: 0.5 })], clipVolume: 0.5,+ }, '/out.mp4').args);+ expect(filter).toContain('volume=0.25');+ });++ it('leaves a silent stub un-shaped — there is nothing to fade or attenuate', () => {+ const filter = filterOf(buildFfmpegArgs({+ segments: [baseClip({ hasAudio: false, fadeInSec: 1, fadeOutSec: 1, volume: 0.2 })], clipVolume: 0.5,+ }, '/out.mp4').args);+ expect(filter).toContain('[1:a]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,asetpts=PTS-STARTPTS[a0]');+ expect(filter).not.toContain('afade=');+ });+});++describe('buildFfmpegArgs — overlay lane', () => {+ const overlay = (overrides = {}) => ({+ type: 'image',+ assetKind: 'images',+ assetFile: 'logo.png',+ assetPath: '/data/images/logo.png',+ startSec: 1,+ durationSec: 2,+ x: 0.5,+ y: 0.25,+ width: 0.25,+ opacity: 1,+ fadeInSec: 0,+ fadeOutSec: 0,+ ...overrides,+ });++ it('composites over the concat output, gated to its window and sized against the canvas', () => {+ const { args } = buildFfmpegArgs({+ segments: [baseClip({ width: 800, height: 400, duration: 4 })],+ overlays: [overlay()],+ canonW: 800, canonH: 400, fps: 24,+ }, '/out.mp4');+ const filter = filterOf(args);++ // The concat now feeds an intermediate label, not [outv].+ expect(filter).toContain('concat=n=1:v=1:a=1[cv][outa]');+ // 0.25 × 800 = 200 wide, -2 keeps the derived height even.+ expect(filter).toContain('[1:v]scale=200:-2,fps=24,format=rgba[ov0]');+ expect(filter).toContain("[cv][ov0]overlay=x=400:y=100:eof_action=pass:enable='between(t,1,3)'[outv]");++ // The overlay input is looped for the WHOLE timeline so overlay() never+ // stalls waiting on a late-starting secondary stream.+ const inputs = args.slice(0, args.indexOf('-filter_complex'));+ const loopIdx = inputs.lastIndexOf('-loop');+ expect(inputs.slice(loopIdx, loopIdx + 6)).toEqual(['-loop', '1', '-t', '4', '-i', '/data/images/logo.png']);+ });++ it('drives partial opacity and alpha fades on the shared timeline clock', () => {+ const filter = filterOf(buildFfmpegArgs({+ segments: [baseClip({ duration: 6, outSec: 6 })],+ overlays: [overlay({ startSec: 2, durationSec: 3, opacity: 0.5, fadeInSec: 0.5, fadeOutSec: 1 })],+ }, '/out.mp4').args);++ expect(filter).toContain('colorchannelmixer=aa=0.5');+ // Fade-in starts at the overlay's PROJECT start, not 0 — the input runs+ // for the whole timeline.+ expect(filter).toContain('fade=t=in:st=2:d=0.5:alpha=1');+ expect(filter).toContain('fade=t=out:st=4:d=1:alpha=1');+ });++ it('chains multiple overlays so each composites onto the previous result', () => {+ const filter = filterOf(buildFfmpegArgs({+ segments: [baseClip()],+ overlays: [overlay(), overlay({ assetFile: 'badge.png', assetPath: '/data/images/badge.png', startSec: 0 })],+ }, '/out.mp4').args);++ expect(filter).toContain('[cv][ov0]overlay=');+ expect(filter).toContain('[ovc0]');+ expect(filter).toContain('[ovc0][ov1]overlay=');+ expect(filter.match(/\[outv\]/g)).toHaveLength(1);+ });+});++describe('buildFfmpegArgs — audio bed', () => {+ const bed = (overrides = {}) => ({+ assetKind: 'music',+ assetFile: 'bed.mp3',+ assetPath: '/data/music/bed.mp3',+ startSec: 0,+ offsetSec: 0,+ durationSec: 4,+ volume: 1,+ fadeInSec: 0,+ fadeOutSec: 0,+ ...overrides,+ });++ it('mixes a bed under the lane audio without normalizing the levels down', () => {+ const filter = filterOf(buildFfmpegArgs({+ segments: [baseClip()], audioTracks: [bed()],+ }, '/out.mp4').args);++ expect(filter).toContain('concat=n=1:v=1:a=1[outv][ca]');+ expect(filter).toContain('[1:a]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,atrim=start=0:end=4,asetpts=PTS-STARTPTS[bed0]');+ expect(filter).toContain('[ca][bed0]amix=inputs=2:duration=first:dropout_transition=0:normalize=0[outa]');+ });++ it('trims from the source offset, shapes, then delays to the project start', () => {+ const filter = filterOf(buildFfmpegArgs({+ segments: [baseClip({ duration: 10, outSec: 10 })],+ audioTracks: [bed({ startSec: 2.5, offsetSec: 30, durationSec: 5, volume: 0.4, fadeInSec: 1, fadeOutSec: 2 })],+ }, '/out.mp4').args);++ // Fades are on the track's own clock (post-atrim), so they come BEFORE adelay.+ expect(filter).toContain('atrim=start=30:end=35,asetpts=PTS-STARTPTS,volume=0.4,afade=t=in:st=0:d=1,afade=t=out:st=3:d=2,adelay=2500|2500[bed0]');+ });++ it('mixes several beds in one amix pass', () => {+ const filter = filterOf(buildFfmpegArgs({+ segments: [baseClip()],+ audioTracks: [bed(), bed({ assetFile: 'sfx.wav', assetPath: '/data/audio/sfx.wav', assetKind: 'audio' })],+ }, '/out.mp4').args);+ expect(filter).toContain('[ca][bed0][bed1]amix=inputs=3:');+ });+});++describe('buildFfmpegArgs — combined lanes and input indexing', () => {+ it('keeps input indices consistent across silent stubs, overlays and beds', () => {+ const { args } = buildFfmpegArgs({+ segments: [+ baseClip({ hasAudio: false, duration: 2, outSec: 2 }), // input 0 (video) + 1 (anullsrc)+ stillSegment({ duration: 1 }), // input 2 (still) + 3 (anullsrc)+ baseClip({ hasAudio: true, duration: 3, outSec: 3 }), // input 4 (video + audio)+ ],+ overlays: [{+ type: 'image', assetKind: 'images', assetFile: 'logo.png', assetPath: '/logo.png',+ startSec: 0, durationSec: 1, x: 0, y: 0, width: 0.5, opacity: 1, fadeInSec: 0, fadeOutSec: 0,+ }], // input 5+ audioTracks: [{+ assetKind: 'music', assetFile: 'bed.mp3', assetPath: '/bed.mp3',+ startSec: 0, offsetSec: 0, durationSec: 2, volume: 1, fadeInSec: 0, fadeOutSec: 0,+ }], // input 6+ canonW: 768, canonH: 512, fps: 24,+ }, '/out.mp4');++ const filter = filterOf(args);+ expect(filter).toContain('[0:v]scale=768:512');+ expect(filter).toContain('[1:a]aresample=48000');+ expect(filter).toContain('[2:v]scale=768:512');+ expect(filter).toContain('[3:a]aresample=48000');+ expect(filter).toContain('[4:v]scale=768:512');+ expect(filter).toContain('[4:a]aresample=48000');+ expect(filter).toContain('[5:v]scale=384:-2');+ expect(filter).toContain('[6:a]aresample=48000');+ // Both post-lanes are present, so concat feeds intermediate labels.+ expect(filter).toContain('concat=n=3:v=1:a=1[cv][ca]');+ expect(args).toContain('[outv]');+ expect(args).toContain('[outa]');+ });++ it('accepts the v1 bare-array signature and produces the same minimal graph', () => {+ const fromArray = buildFfmpegArgs([baseClip()], '/out.mp4');+ const fromObject = buildFfmpegArgs({ segments: [baseClip()] }, '/out.mp4');+ expect(fromArray.args).toEqual(fromObject.args);+ });++ it('rounds float noise out of the graph instead of leaking it', () => {+ const filter = filterOf(buildFfmpegArgs({+ segments: [baseClip({ inSec: 0.1, outSec: 0.3, duration: 0.2, fadeOutSec: 0.1 })],+ }, '/out.mp4').args);+ // 0.3 - 0.1 === 0.19999999999999998 in IEEE 754.+ expect(filter).toContain('fade=t=out:st=0.1:d=0.1');+ expect(filter).not.toContain('0.19999');+ });+});diff --git a/server/services/videoTimeline/segments.js b/server/services/videoTimeline/segments.jsnew file mode 100644index 0000000000..283eeb46c6--- /dev/null+++ b/server/services/videoTimeline/segments.js@@ -0,0 +1,326 @@+/**+ * Video Timeline — layered segment/lane model (schemaVersion 2).+ *+ * v1 projects persisted a single ordered `clips` array of `{ clipId, inSec,+ * outSec }`, so anything that wasn't a trimmed generated video clip (a held+ * still, a logo overlay, a music bed, a deliberate cross-fade) needed a+ * separate tool or a manual re-render. v2 replaces that with three lanes that+ * the browser preview and the ffmpeg export both read:+ *+ * segments — the ordered video lane. Heterogeneous: `clip` (a trimmed+ * entry from video history) or `still` (an image held for a+ * duration). Each carries its own fade in/out and volume.+ * overlays — free-floating image overlays positioned in project time and+ * in normalized canvas space, with their own alpha fades.+ * audio — `{ clipVolume, tracks[] }`. `clipVolume` scales the video+ * lane's own audio; each track places a library file at an+ * absolute project time with offset/trim/fades.+ *+ * Assets are addressed as `{ assetKind, assetFile }` rather than a free path:+ * `assetKind` selects one of a fixed allowlist of `data/` subdirectories and+ * `assetFile` must be a plain basename, so `resolveAsset` can reuse the+ * existing `safeUnder` containment check instead of trusting a stored path.+ *+ * `clips` stays on every persisted project as a DERIVED mirror of the video+ * lane's clip segments. It is never the source of truth once `segments`+ * exists — it is there so an install rolled back to a v1 build still renders+ * the video lane instead of seeing an empty project.+ */++import { existsSync } from 'fs';+import { PATHS } from '../../lib/fileUtils.js';+import { safeUnder } from '../../lib/ffmpeg.js';+import { ServerError } from '../../lib/errorHandler.js';++export const TIMELINE_SCHEMA_VERSION = 2;++// Allowlisted `data/` subdirectories a timeline asset may come from. Anything+// not in this map is rejected before it can reach ffmpeg.+export const ASSET_ROOTS = {+ images: PATHS.images,+ 'video-thumbnails': PATHS.videoThumbnails,+ audio: PATHS.audio,+ music: PATHS.music,+};++export const IMAGE_ASSET_KINDS = ['images', 'video-thumbnails'];+export const AUDIO_ASSET_KINDS = ['audio', 'music'];++export const MAX_SEGMENTS = 200;+export const MAX_OVERLAYS = 50;+export const MAX_AUDIO_TRACKS = 20;+const MAX_FADE_SEC = 30;+const MAX_STILL_SEC = 600;+const MAX_VOLUME = 4;++const bad = (message, context) => new ServerError(message, { status: 400, code: 'VALIDATION_ERROR', context });++/**+ * Resolve an `{ assetKind, assetFile }` pair to an absolute on-disk path, or+ * null when the kind is not allowlisted, the filename is not a safe basename,+ * or the file does not exist. Never returns a path outside the asset root.+ */+export function resolveAsset(assetKind, assetFile, { allowedKinds = null, requireExists = true } = {}) {+ if (allowedKinds && !allowedKinds.includes(assetKind)) return null;+ const root = ASSET_ROOTS[assetKind];+ if (!root) return null;+ const full = safeUnder(root, assetFile);+ if (!full) return null;+ if (requireExists && !existsSync(full)) return null;+ return full;+}++const num = (value, fallback = 0) => {+ const n = Number(value);+ return Number.isFinite(n) ? n : fallback;+};++const clamp = (value, min, max) => Math.min(max, Math.max(min, value));++// Fades are stored per segment/overlay/track and always land inside their+// own duration — a fade longer than the thing it fades produces an ffmpeg+// `fade` with a negative start time, which silently renders black.+const clampFades = (fadeInSec, fadeOutSec, duration, label) => {+ const fin = clamp(num(fadeInSec, 0), 0, MAX_FADE_SEC);+ const fout = clamp(num(fadeOutSec, 0), 0, MAX_FADE_SEC);+ if (fin + fout > duration) {+ throw bad(`${label}: fadeInSec + fadeOutSec (${(fin + fout).toFixed(2)}s) exceeds its duration (${duration.toFixed(2)}s)`);+ }+ return { fadeInSec: fin, fadeOutSec: fout };+};++const assetFields = (raw, allowedKinds, label) => {+ const assetKind = String(raw.assetKind || '').trim();+ if (!allowedKinds.includes(assetKind)) {+ throw bad(`${label}: assetKind must be one of ${allowedKinds.join(', ')}`);+ }+ const assetFile = String(raw.assetFile || '').trim();+ // Containment is re-checked at render time against the live filesystem;+ // this is the persist-time shape guard so a traversal string never lands+ // in the project file at all.+ if (!assetFile || !safeUnder(ASSET_ROOTS[assetKind], assetFile)) {+ throw bad(`${label}: assetFile must be a plain filename inside data/${assetKind}`);+ }+ return { assetKind, assetFile };+};++const validateClipSegment = (raw, label) => {+ const clipId = String(raw.clipId || '').trim();+ if (!/^[a-f0-9-]{36}$/i.test(clipId)) throw bad(`${label}: invalid clipId`);+ const inSec = num(raw.inSec, NaN);+ const outSec = num(raw.outSec, NaN);+ if (!Number.isFinite(inSec) || !Number.isFinite(outSec) || inSec < 0 || outSec <= inSec) {+ throw bad(`${label}: inSec/outSec invalid (need 0 ≤ inSec < outSec)`);+ }+ const { fadeInSec, fadeOutSec } = clampFades(raw.fadeInSec, raw.fadeOutSec, outSec - inSec, label);+ return {+ type: 'clip',+ clipId,+ inSec,+ outSec,+ fadeInSec,+ fadeOutSec,+ volume: clamp(num(raw.volume, 1), 0, MAX_VOLUME),+ };+};++const validateStillSegment = (raw, label) => {+ const { assetKind, assetFile } = assetFields(raw, IMAGE_ASSET_KINDS, label);+ const durationSec = num(raw.durationSec, NaN);+ if (!Number.isFinite(durationSec) || durationSec <= 0 || durationSec > MAX_STILL_SEC) {+ throw bad(`${label}: durationSec must be in (0, ${MAX_STILL_SEC}]`);+ }+ const { fadeInSec, fadeOutSec } = clampFades(raw.fadeInSec, raw.fadeOutSec, durationSec, label);+ return { type: 'still', assetKind, assetFile, durationSec, fadeInSec, fadeOutSec };+};++/**+ * Validate the ordered video lane. Accepts the v1 shape too — an entry with+ * no `type` but a `clipId` is a legacy clip — so a client that hasn't been+ * updated (or a project loaded from a v1 file) round-trips unchanged.+ */+export function validateSegments(raw) {+ if (!Array.isArray(raw)) throw bad('segments must be an array');+ if (raw.length > MAX_SEGMENTS) throw bad(`segments: at most ${MAX_SEGMENTS} entries`);+ return raw.map((entry, idx) => {+ const label = `Segment ${idx}`;+ if (!entry || typeof entry !== 'object') throw bad(`${label}: must be an object`);+ const type = entry.type || (entry.clipId ? 'clip' : null);+ if (type === 'clip') return validateClipSegment(entry, label);+ if (type === 'still') return validateStillSegment(entry, label);+ throw bad(`${label}: unknown segment type "${entry.type}" (expected clip or still)`);+ });+}++export function validateOverlays(raw) {+ if (!Array.isArray(raw)) throw bad('overlays must be an array');+ if (raw.length > MAX_OVERLAYS) throw bad(`overlays: at most ${MAX_OVERLAYS} entries`);+ return raw.map((entry, idx) => {+ const label = `Overlay ${idx}`;+ if (!entry || typeof entry !== 'object') throw bad(`${label}: must be an object`);+ const { assetKind, assetFile } = assetFields(entry, IMAGE_ASSET_KINDS, label);+ const startSec = Math.max(0, num(entry.startSec, 0));+ const durationSec = num(entry.durationSec, NaN);+ if (!Number.isFinite(durationSec) || durationSec <= 0 || durationSec > MAX_STILL_SEC) {+ throw bad(`${label}: durationSec must be in (0, ${MAX_STILL_SEC}]`);+ }+ const { fadeInSec, fadeOutSec } = clampFades(entry.fadeInSec, entry.fadeOutSec, durationSec, label);+ return {+ type: 'image',+ assetKind,+ assetFile,+ startSec,+ durationSec,+ // Normalized to the canonical canvas so an overlay keeps its placement+ // when the project's canonical dimensions change (a different first+ // clip). Slight overscan is allowed so a graphic can bleed off-frame.+ x: clamp(num(entry.x, 0), -1, 2),+ y: clamp(num(entry.y, 0), -1, 2),+ width: clamp(num(entry.width, 0.25), 0.01, 4),+ opacity: clamp(num(entry.opacity, 1), 0, 1),+ fadeInSec,+ fadeOutSec,+ };+ });+}++export function validateAudio(raw) {+ if (raw == null) return defaultAudio();+ if (typeof raw !== 'object' || Array.isArray(raw)) throw bad('audio must be an object');+ const rawTracks = raw.tracks == null ? [] : raw.tracks;+ if (!Array.isArray(rawTracks)) throw bad('audio.tracks must be an array');+ if (rawTracks.length > MAX_AUDIO_TRACKS) throw bad(`audio.tracks: at most ${MAX_AUDIO_TRACKS} entries`);+ const tracks = rawTracks.map((entry, idx) => {+ const label = `Audio track ${idx}`;+ if (!entry || typeof entry !== 'object') throw bad(`${label}: must be an object`);+ const { assetKind, assetFile } = assetFields(entry, AUDIO_ASSET_KINDS, label);+ const durationSec = num(entry.durationSec, NaN);+ if (!Number.isFinite(durationSec) || durationSec <= 0 || durationSec > MAX_STILL_SEC) {+ throw bad(`${label}: durationSec must be in (0, ${MAX_STILL_SEC}]`);+ }+ const { fadeInSec, fadeOutSec } = clampFades(entry.fadeInSec, entry.fadeOutSec, durationSec, label);+ return {+ assetKind,+ assetFile,+ startSec: Math.max(0, num(entry.startSec, 0)),+ offsetSec: Math.max(0, num(entry.offsetSec, 0)),+ durationSec,+ volume: clamp(num(entry.volume, 1), 0, MAX_VOLUME),+ fadeInSec,+ fadeOutSec,+ };+ });+ return { clipVolume: clamp(num(raw.clipVolume, 1), 0, MAX_VOLUME), tracks };+}++export const defaultAudio = () => ({ clipVolume: 1, tracks: [] });++/**+ * The `clips` mirror written alongside `segments`. Only clip segments survive+ * — a v1 build has no way to render a still, and emitting a placeholder entry+ * would make it render the wrong source.+ */+export const deriveLegacyClips = (segments) => segments+ .filter((s) => s.type === 'clip')+ .map((s) => ({ clipId: s.clipId, inSec: s.inSec, outSec: s.outSec }));++/**+ * Upgrade a persisted project to the v2 lane shape in memory. Idempotent, and+ * tolerant of a hand-edited file: a non-array `clips`/`segments`/`overlays`+ * degrades to empty rather than throwing, because this runs on every read.+ *+ * A v1 project (no `segments`) has its `clips` promoted to clip segments. A+ * v2 project keeps `segments` as the source of truth and REBUILDS the `clips`+ * mirror, so a stale mirror written by an older build can never resurrect a+ * removed segment.+ */+export function normalizeProject(project) {+ if (!project || typeof project !== 'object') return project;+ const legacyClips = Array.isArray(project.clips) ? project.clips : [];+ const rawSegments = Array.isArray(project.segments)+ ? project.segments+ : legacyClips.map((c) => ({ type: 'clip', ...c }));++ const segments = rawSegments.flatMap((entry) => {+ if (!entry || typeof entry !== 'object') return [];+ const type = entry.type || (entry.clipId ? 'clip' : null);+ if (type === 'clip') {+ const inSec = Math.max(0, num(entry.inSec, 0));+ const outSec = num(entry.outSec, NaN);+ if (!Number.isFinite(outSec) || outSec <= inSec) return [];+ return [{+ type: 'clip',+ clipId: String(entry.clipId || ''),+ inSec,+ outSec,+ fadeInSec: clamp(num(entry.fadeInSec, 0), 0, MAX_FADE_SEC),+ fadeOutSec: clamp(num(entry.fadeOutSec, 0), 0, MAX_FADE_SEC),+ volume: clamp(num(entry.volume, 1), 0, MAX_VOLUME),+ }];+ }+ if (type === 'still') {+ const durationSec = num(entry.durationSec, NaN);+ if (!Number.isFinite(durationSec) || durationSec <= 0) return [];+ return [{+ type: 'still',+ assetKind: String(entry.assetKind || ''),+ assetFile: String(entry.assetFile || ''),+ durationSec,+ fadeInSec: clamp(num(entry.fadeInSec, 0), 0, MAX_FADE_SEC),+ fadeOutSec: clamp(num(entry.fadeOutSec, 0), 0, MAX_FADE_SEC),+ }];+ }+ return [];+ });++ const overlays = Array.isArray(project.overlays)+ ? project.overlays.filter((o) => o && typeof o === 'object').map((o) => ({+ type: 'image',+ assetKind: String(o.assetKind || ''),+ assetFile: String(o.assetFile || ''),+ startSec: Math.max(0, num(o.startSec, 0)),+ durationSec: Math.max(0, num(o.durationSec, 0)),+ x: clamp(num(o.x, 0), -1, 2),+ y: clamp(num(o.y, 0), -1, 2),+ width: clamp(num(o.width, 0.25), 0.01, 4),+ opacity: clamp(num(o.opacity, 1), 0, 1),+ fadeInSec: clamp(num(o.fadeInSec, 0), 0, MAX_FADE_SEC),+ fadeOutSec: clamp(num(o.fadeOutSec, 0), 0, MAX_FADE_SEC),+ })).filter((o) => o.durationSec > 0)+ : [];++ const rawAudio = project.audio && typeof project.audio === 'object' && !Array.isArray(project.audio)+ ? project.audio+ : {};+ const audio = {+ clipVolume: clamp(num(rawAudio.clipVolume, 1), 0, MAX_VOLUME),+ tracks: Array.isArray(rawAudio.tracks)+ ? rawAudio.tracks.filter((t) => t && typeof t === 'object').map((t) => ({+ assetKind: String(t.assetKind || ''),+ assetFile: String(t.assetFile || ''),+ startSec: Math.max(0, num(t.startSec, 0)),+ offsetSec: Math.max(0, num(t.offsetSec, 0)),+ durationSec: Math.max(0, num(t.durationSec, 0)),+ volume: clamp(num(t.volume, 1), 0, MAX_VOLUME),+ fadeInSec: clamp(num(t.fadeInSec, 0), 0, MAX_FADE_SEC),+ fadeOutSec: clamp(num(t.fadeOutSec, 0), 0, MAX_FADE_SEC),+ })).filter((t) => t.durationSec > 0)+ : [],+ };++ return {+ ...project,+ schemaVersion: TIMELINE_SCHEMA_VERSION,+ segments,+ overlays,+ audio,+ clips: deriveLegacyClips(segments),+ };+}++/** Project-time duration of the video lane. */+export const segmentDuration = (segment) => (segment.type === 'still'+ ? segment.durationSec+ : Math.max(0, segment.outSec - segment.inSec));++export const laneDuration = (segments) => segments.reduce((sum, s) => sum + segmentDuration(s), 0);diff --git a/server/services/videoTimeline/segments.test.js b/server/services/videoTimeline/segments.test.jsnew file mode 100644index 0000000000..bb88d32ebc--- /dev/null+++ b/server/services/videoTimeline/segments.test.js@@ -0,0 +1,187 @@+import { describe, it, expect } from 'vitest';+import {+ TIMELINE_SCHEMA_VERSION,+ normalizeProject,+ validateSegments,+ validateOverlays,+ validateAudio,+ deriveLegacyClips,+ resolveAsset,+ segmentDuration,+ laneDuration,+} from './segments.js';++const CLIP_A = '11111111-1111-4111-8111-111111111111';+const CLIP_B = '22222222-2222-4222-8222-222222222222';++describe('normalizeProject — v1 → v2 upgrade', () => {+ it('promotes a legacy clips array to clip segments and stamps the schema version', () => {+ const v1 = {+ id: 'p1',+ name: 'Example Project',+ clips: [{ clipId: CLIP_A, inSec: 0, outSec: 4 }, { clipId: CLIP_B, inSec: 1, outSec: 2.5 }],+ };++ const v2 = normalizeProject(v1);++ expect(v2.schemaVersion).toBe(TIMELINE_SCHEMA_VERSION);+ expect(v2.segments).toEqual([+ { type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 4, fadeInSec: 0, fadeOutSec: 0, volume: 1 },+ { type: 'clip', clipId: CLIP_B, inSec: 1, outSec: 2.5, fadeInSec: 0, fadeOutSec: 0, volume: 1 },+ ]);+ expect(v2.overlays).toEqual([]);+ expect(v2.audio).toEqual({ clipVolume: 1, tracks: [] });+ // The mirror stays so a rolled-back v1 build still renders the video lane.+ expect(v2.clips).toEqual(v1.clips);+ });++ it('is idempotent — normalizing a v2 project changes nothing', () => {+ const once = normalizeProject({ id: 'p1', clips: [{ clipId: CLIP_A, inSec: 0, outSec: 2 }] });+ expect(normalizeProject(once)).toEqual(once);+ });++ it('rebuilds the clips mirror from segments, so a stale mirror cannot resurrect a removed segment', () => {+ const project = {+ id: 'p1',+ schemaVersion: 2,+ segments: [{ type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 2 }],+ // An older build wrote this before the segment was deleted.+ clips: [{ clipId: CLIP_A, inSec: 0, outSec: 2 }, { clipId: CLIP_B, inSec: 0, outSec: 9 }],+ };++ expect(normalizeProject(project).clips).toEqual([{ clipId: CLIP_A, inSec: 0, outSec: 2 }]);+ });++ it('drops corrupt entries instead of throwing — this runs on every read', () => {+ const project = normalizeProject({+ id: 'p1',+ clips: 'not-an-array',+ segments: [+ null,+ { type: 'clip', clipId: CLIP_A, inSec: 3, outSec: 1 }, // inverted trim+ { type: 'still', assetKind: 'images', assetFile: 'a.png', durationSec: 0 }, // zero hold+ { type: 'clip', clipId: CLIP_B, inSec: 0, outSec: 2 },+ ],+ overlays: 'nope',+ audio: [],+ });++ expect(project.segments).toHaveLength(1);+ expect(project.segments[0].clipId).toBe(CLIP_B);+ expect(project.overlays).toEqual([]);+ expect(project.audio).toEqual({ clipVolume: 1, tracks: [] });+ });++ it('carries stills, overlays and audio through unchanged', () => {+ const v2 = normalizeProject({+ id: 'p1',+ segments: [{ type: 'still', assetKind: 'images', assetFile: 'plate.png', durationSec: 3, fadeInSec: 0.5, fadeOutSec: 0.5 }],+ overlays: [{ assetKind: 'images', assetFile: 'logo.png', startSec: 1, durationSec: 2, x: 0.1, y: 0.2, width: 0.3, opacity: 0.8 }],+ audio: { clipVolume: 0.5, tracks: [{ assetKind: 'music', assetFile: 'bed.mp3', startSec: 0, durationSec: 5, volume: 0.4 }] },+ });++ expect(v2.segments[0]).toMatchObject({ type: 'still', assetFile: 'plate.png', durationSec: 3 });+ expect(v2.overlays[0]).toMatchObject({ type: 'image', assetFile: 'logo.png', opacity: 0.8 });+ expect(v2.audio.tracks[0]).toMatchObject({ assetFile: 'bed.mp3', volume: 0.4 });+ // Stills contribute no clip mirror — a v1 build has no way to render one.+ expect(v2.clips).toEqual([]);+ });+});++describe('validateSegments', () => {+ it('accepts a v1-shaped entry with no type and treats it as a clip', () => {+ expect(validateSegments([{ clipId: CLIP_A, inSec: 0, outSec: 2 }])[0]).toMatchObject({ type: 'clip', clipId: CLIP_A });+ });++ it('rejects an inverted trim', () => {+ expect(() => validateSegments([{ type: 'clip', clipId: CLIP_A, inSec: 2, outSec: 1 }]))+ .toThrow(/inSec\/outSec invalid/);+ });++ it('rejects an unknown segment type', () => {+ expect(() => validateSegments([{ type: 'caption', text: 'hi' }])).toThrow(/unknown segment type/);+ });++ it('rejects a fade pair that outlasts its own segment', () => {+ expect(() => validateSegments([{ type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 2, fadeInSec: 1.5, fadeOutSec: 1.5 }]))+ .toThrow(/exceeds its duration/);+ });++ it('rejects a still whose assetFile escapes its asset root', () => {+ expect(() => validateSegments([{ type: 'still', assetKind: 'images', assetFile: '../../etc/passwd', durationSec: 2 }]))+ .toThrow(/plain filename/);+ });++ it('rejects an assetKind outside the allowlist', () => {+ expect(() => validateSegments([{ type: 'still', assetKind: 'videos', assetFile: 'a.png', durationSec: 2 }]))+ .toThrow(/assetKind must be one of/);+ });++ it('clamps volume into range', () => {+ expect(validateSegments([{ type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 2, volume: 99 }])[0].volume).toBe(4);+ expect(validateSegments([{ type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 2, volume: -1 }])[0].volume).toBe(0);+ });+});++describe('validateOverlays / validateAudio', () => {+ it('fills geometry defaults and clamps opacity', () => {+ const [ov] = validateOverlays([{ assetKind: 'images', assetFile: 'logo.png', startSec: 1, durationSec: 2, opacity: 5 }]);+ expect(ov).toMatchObject({ type: 'image', x: 0, y: 0, width: 0.25, opacity: 1 });+ });++ it('rejects an audio track pointing at the image gallery', () => {+ expect(() => validateAudio({ tracks: [{ assetKind: 'images', assetFile: 'a.png', startSec: 0, durationSec: 2 }] }))+ .toThrow(/assetKind must be one of/);+ });++ it('treats a null audio lane as the neutral default rather than an error', () => {+ expect(validateAudio(null)).toEqual({ clipVolume: 1, tracks: [] });+ });++ it('rejects a non-array tracks value', () => {+ expect(() => validateAudio({ tracks: 'bed.mp3' })).toThrow(/must be an array/);+ });+});++describe('resolveAsset', () => {+ it('refuses a traversal filename', () => {+ expect(resolveAsset('images', '../secrets.png', { requireExists: false })).toBeNull();+ expect(resolveAsset('images', 'nested/logo.png', { requireExists: false })).toBeNull();+ });++ it('refuses a kind outside the caller allowlist even when it is a known root', () => {+ expect(resolveAsset('music', 'bed.mp3', { allowedKinds: ['images'], requireExists: false })).toBeNull();+ });++ it('resolves a plain basename under its asset root', () => {+ const resolved = resolveAsset('images', 'logo.png', { requireExists: false });+ expect(resolved).toMatch(/data[/\\]images[/\\]logo\.png$/);+ });+});++describe('duration helpers', () => {+ it('measures a still by its hold and a clip by its trim', () => {+ expect(segmentDuration({ type: 'still', durationSec: 3 })).toBe(3);+ expect(segmentDuration({ type: 'clip', inSec: 1, outSec: 4 })).toBe(3);+ });++ it('sums the lane', () => {+ expect(laneDuration([+ { type: 'clip', inSec: 0, outSec: 2 },+ { type: 'still', durationSec: 3 },+ ])).toBe(5);+ });+});++describe('deriveLegacyClips', () => {+ it('keeps only clip segments, in lane order', () => {+ expect(deriveLegacyClips([+ { type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 2 },+ { type: 'still', assetKind: 'images', assetFile: 'a.png', durationSec: 1 },+ { type: 'clip', clipId: CLIP_B, inSec: 1, outSec: 3 },+ ])).toEqual([+ { clipId: CLIP_A, inSec: 0, outSec: 2 },+ { clipId: CLIP_B, inSec: 1, outSec: 3 },+ ]);+ });+});