Skip to content

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

align the timeline preview with the export canvas, and stop rejecting valid gallery filenames

[._.]/ Adam Eivyfccd90a253eb
diff --git a/client/src/components/media/VideoTimelineInspector.jsx b/client/src/components/media/VideoTimelineInspector.jsx
index 862a3fa924..6870f9dc33 100644
--- a/client/src/components/media/VideoTimelineInspector.jsx
+++ b/client/src/components/media/VideoTimelineInspector.jsx
@@ -10,6 +10,7 @@ import { memo } from 'react';
import { Trash2 } from 'lucide-react';
import useFieldDraft from '../../hooks/useFieldDraft';
import { clamp } from '../../utils/formatters';
+import { MAX_FADE_SEC } from '../../lib/videoTimelineModel';
/**
* Commit-on-blur numeric input. The draft buffer is what lets the user type
@@ -42,9 +43,14 @@ export const NumberField = memo(function NumberField({ id, label, value, step =
);
});
-/** The fade pair every lane entry carries, bounded by its own duration. */
+/**
+ * The fade pair every lane entry carries, bounded by its own duration AND by
+ * the server's absolute fade cap — an entry longer than 30s would otherwise
+ * let the user type a fade the save rejects with a 400, leaving the editor
+ * unsavable until they guessed the real limit.
+ */
export const FadeFields = memo(function FadeFields({ idPrefix, entry, duration, onCommit }) {
- const max = Math.max(0, duration);
+ const max = Math.min(Math.max(0, duration), MAX_FADE_SEC);
return (
<div className="grid grid-cols-2 gap-2">
<NumberField
diff --git a/client/src/lib/videoTimelineModel.js b/client/src/lib/videoTimelineModel.js
index bc8ec271e9..55a663c79c 100644
--- a/client/src/lib/videoTimelineModel.js
+++ b/client/src/lib/videoTimelineModel.js
@@ -78,16 +78,45 @@ export const fadeMultiplier = (fadeInSec, fadeOutSec, duration, within) => {
/**
* Effective opacity of an overlay at project-time `t` — 0 outside its window,
* its configured opacity inside, scaled by whichever alpha fade is active.
+ *
+ * `limitSec` is the timeline's own length. The export clamps an overlay that
+ * runs past the end of the video lane to that length, which pulls its fade-out
+ * earlier; pass the same value here or the preview stays opaque through
+ * seconds the render fades.
*/
-export const overlayOpacityAt = (overlay, t) => {
+export const overlayOpacityAt = (overlay, t, limitSec = Infinity) => {
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 end = Math.min(start + Math.max(0, overlay.durationSec || 0), limitSec);
+ const dur = end - start;
+ if (dur <= 0 || t < start || t > end) return 0;
const base = overlay.opacity == null ? 1 : overlay.opacity;
return base * fadeMultiplier(overlay.fadeInSec || 0, overlay.fadeOutSec || 0, dur, t - start);
};
+/**
+ * Aspect ratio of the canonical render canvas — the first CLIP segment's
+ * dimensions, mirroring resolveTimeline. The editor's preview must adopt it or
+ * an overlay placed against a 16:9 box lands somewhere else in a portrait or
+ * square export. `dimsFor(clipId)` resolves a clip's `{ width, height }`.
+ */
+export const canvasAspectRatio = (segments, dimsFor) => {
+ for (const segment of segments || []) {
+ if (segment.type === 'still') continue;
+ const dims = dimsFor(segment.clipId);
+ if (dims?.width > 0 && dims?.height > 0) return dims.width / dims.height;
+ }
+ // A stills-only project has no intrinsic geometry — the server falls back to
+ // 1280×720, so the preview must too.
+ return DEFAULT_CANVAS_ASPECT;
+};
+
+/** Mirrors DEFAULT_CANVAS in server/services/videoTimeline/local.js. */
+export const DEFAULT_CANVAS_ASPECT = 1280 / 720;
+
+/** Mirrors MAX_FADE_SEC in server/services/videoTimeline/segments.js. */
+export const MAX_FADE_SEC = 30;
+
/**
* Where an audio track sits relative to project-time `t`.
* `active` is false outside its window; `within` is seconds into the track's
diff --git a/client/src/lib/videoTimelineModel.test.js b/client/src/lib/videoTimelineModel.test.js
index 873121e925..6b346f99f1 100644
--- a/client/src/lib/videoTimelineModel.test.js
+++ b/client/src/lib/videoTimelineModel.test.js
@@ -14,6 +14,7 @@ import {
fitFadePatch,
segmentVolumeAt,
projectSummary,
+ canvasAspectRatio,
} from './videoTimelineModel';
const clip = (inSec, outSec) => ({ type: 'clip', clipId: 'c', inSec, outSec });
@@ -269,3 +270,46 @@ describe('projectSummary — the index must count the lane, not the mirror', ()
expect(projectSummary({}, thumbFor)).toEqual({ totalSec: 0, blockCount: 0, firstThumb: null });
});
});
+
+describe('overlayOpacityAt — clamped to the timeline length like the export', () => {
+ const overlay = { startSec: 4, durationSec: 6, opacity: 1, fadeInSec: 0, fadeOutSec: 2 };
+
+ it('pulls the fade-out earlier when the overlay outruns the video lane', () => {
+ // The export clamps the overlay's end to the timeline length, so its
+ // 2s fade-out lands at 6s–8s, not 8s–10s.
+ expect(overlayOpacityAt(overlay, 7, 8)).toBeCloseTo(0.5);
+ expect(overlayOpacityAt(overlay, 8, 8)).toBe(0);
+ });
+
+ it('uses the configured window when the overlay fits', () => {
+ expect(overlayOpacityAt(overlay, 7, 30)).toBe(1);
+ expect(overlayOpacityAt(overlay, 9, 30)).toBeCloseTo(0.5);
+ });
+
+ it('is fully transparent once the limit cuts the window to nothing', () => {
+ expect(overlayOpacityAt(overlay, 4, 4)).toBe(0);
+ });
+});
+
+describe('canvasAspectRatio — the preview must match the export canvas', () => {
+ const dims = { c1: { width: 1080, height: 1920 }, c2: { width: 1920, height: 1080 } };
+ const dimsFor = (id) => dims[id];
+
+ it('takes the FIRST clip segment, mirroring resolveTimeline', () => {
+ expect(canvasAspectRatio([
+ { type: 'still', assetKind: 'images', assetFile: 'a.png', durationSec: 2 },
+ { type: 'clip', clipId: 'c1' },
+ { type: 'clip', clipId: 'c2' },
+ ], dimsFor)).toBeCloseTo(1080 / 1920);
+ });
+
+ it('falls back to the server default for a stills-only project', () => {
+ expect(canvasAspectRatio([{ type: 'still', assetKind: 'images', assetFile: 'a.png', durationSec: 2 }], dimsFor))
+ .toBeCloseTo(1280 / 720);
+ });
+
+ it('skips a clip whose dimensions are unknown rather than dividing by zero', () => {
+ expect(canvasAspectRatio([{ type: 'clip', clipId: 'gone' }, { type: 'clip', clipId: 'c2' }], dimsFor))
+ .toBeCloseTo(1920 / 1080);
+ });
+});
diff --git a/client/src/pages/VideoTimelineEditor.jsx b/client/src/pages/VideoTimelineEditor.jsx
index 81193f5964..bf2174378c 100644
--- a/client/src/pages/VideoTimelineEditor.jsx
+++ b/client/src/pages/VideoTimelineEditor.jsx
@@ -28,6 +28,7 @@ import {
assetUrl,
segmentDuration,
timelineDuration,
+ canvasAspectRatio,
findSegmentAt,
fadeMultiplier,
overlayOpacityAt,
@@ -218,6 +219,10 @@ export default function VideoTimelineEditor() {
const isBedMissing = useCallback((tr) => knownAbsent(tr.assetKind, tr.assetFile), [knownAbsent]);
const total = useMemo(() => timelineDuration(segments), [segments]);
+ const canvasAspect = useMemo(
+ () => canvasAspectRatio(segments, (clipId) => historyMap.get(clipId)),
+ [segments, historyMap],
+ );
// Clamp the playhead into [0, total] when the timeline duration shrinks
// (segment removal, tighter trim, etc.). Without this, t can exceed total
@@ -767,7 +772,11 @@ export default function VideoTimelineEditor() {
{/* Center — preview + tracks */}
<div className="space-y-3 min-w-0">
- <div className="bg-black rounded-lg overflow-hidden aspect-video relative">
+ {/* The preview adopts the CANONICAL render canvas, not a fixed 16:9
+ box — overlay x/y/width are normalized against that canvas, so a
+ portrait or square project would otherwise place them somewhere
+ the export does not. */}
+ <div className="bg-black rounded-lg overflow-hidden relative" style={{ aspectRatio: canvasAspect }}>
<video
ref={videoRef}
className={`w-full h-full ${activeStillSrc ? 'invisible' : ''}`}
@@ -800,7 +809,7 @@ export default function VideoTimelineEditor() {
src={src}
alt=""
data-testid="overlay-preview"
- style={{ left, top, width, opacity: overlayOpacityAt(overlay, t) }}
+ style={{ left, top, width, opacity: overlayOpacityAt(overlay, t, total) }}
className="absolute pointer-events-none"
/>
) : null))}
diff --git a/server/services/videoTimeline/local.js b/server/services/videoTimeline/local.js
index 0e75cfa5f9..808137b6f4 100644
--- a/server/services/videoTimeline/local.js
+++ b/server/services/videoTimeline/local.js
@@ -41,6 +41,7 @@ import {
defaultAudio,
deriveLegacyClips,
resolveAsset,
+ fitFades,
} from './segments.js';
const PROJECTS_FILE = join(PATHS.data, 'video-projects.json');
@@ -410,22 +411,6 @@ export async function resolveTimeline(rawProject) {
// 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 };
-}
-
-// Fade filters for one segment, in the segment's own post-setpts clock.
-// `prefix` is 'fade' (video) or 'afade' (audio) — the two must agree on the
-// fade-out start, so they share one expression. `lead` carries filters that
-// belong ahead of the ramp (an audio volume trim).
const fadeChain = (prefix, { fadeInSec = 0, fadeOutSec = 0 }, duration, lead = []) => {
const parts = [...lead];
if (fadeInSec > 0) parts.push(`${prefix}=t=in:st=0:d=${fmt(fadeInSec)}`);
diff --git a/server/services/videoTimeline/segments.js b/server/services/videoTimeline/segments.js
index 8435a3a8cb..70ac5473e7 100644
--- a/server/services/videoTimeline/segments.js
+++ b/server/services/videoTimeline/segments.js
@@ -19,7 +19,8 @@
* 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.
+ * shared top-level-entry predicate plus a resolved-prefix check rather than
+ * 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`
@@ -28,8 +29,8 @@
*/
import { existsSync } from 'fs';
-import { PATHS } from '../../lib/fileUtils.js';
-import { safeUnder } from '../../lib/ffmpeg.js';
+import { join, resolve as resolvePath, sep } from 'path';
+import { PATHS, isTopLevelEntryName } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
export const TIMELINE_SCHEMA_VERSION = 2;
@@ -49,6 +50,23 @@ export const AUDIO_ASSET_KINDS = ['audio', 'music'];
export const MAX_SEGMENTS = 200;
export const MAX_OVERLAYS = 50;
export const MAX_AUDIO_TRACKS = 20;
+/**
+ * Shrink a fade pair that no longer fits `duration`, scaling both
+ * proportionally so the author's balance survives. Non-throwing twin of
+ * `clampFades`: that one rejects an over-long pair at persist time, this one
+ * repairs a pair that a LATER change made too long (a probe-shortened bed, a
+ * legacy trim). ffmpeg's `fade` renders the whole segment black when its start
+ * time goes negative, so an unfitted pair is not a cosmetic problem.
+ */
+export 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 };
+}
+
export const MAX_FADE_SEC = 30;
export const MAX_STILL_SEC = 600;
export const MAX_VOLUME = 4;
@@ -60,11 +78,30 @@ const bad = (message, context) => new ServerError(message, { status: 400, code:
* 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.
*/
+/**
+ * Resolve `{ assetKind, assetFile }` under its allowlisted root.
+ *
+ * `isTopLevelEntryName` rather than `safeUnder`: both refuse separators, but
+ * `safeUnder` rejects any `..` SUBSTRING, which would turn a perfectly valid
+ * gallery file like `my..render.png` into an unusable timeline asset. Naming a
+ * single entry is what makes the `join` safe in the filesystem sense — with no
+ * separator there is no intermediate component for a symlink to redirect — and
+ * the resolved-prefix check below is the lexical backstop.
+ */
+export function assetPathFor(assetKind, assetFile) {
+ const root = ASSET_ROOTS[assetKind];
+ if (!root || !isTopLevelEntryName(assetFile)) return null;
+ const full = resolvePath(join(root, assetFile));
+ return full.startsWith(resolvePath(root) + sep) ? full : null;
+}
+
+/**
+ * `assetPathFor` plus the caller's kind allowlist and an on-disk existence
+ * check. Returns null — never 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);
+ const full = assetPathFor(assetKind, assetFile);
if (!full) return null;
if (requireExists && !existsSync(full)) return null;
return full;
@@ -98,7 +135,7 @@ const assetFields = (raw, allowedKinds, label) => {
// 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)) {
+ if (!assetPathFor(assetKind, assetFile)) {
throw bad(`${label}: assetFile must be a plain filename inside data/${assetKind}`);
}
return { assetKind, assetFile };
@@ -258,7 +295,12 @@ const reconcileLegacyMirror = (segments, storedClips) => {
}
return mirror.map((c) => {
const effects = effectsById.get(c.clipId)?.shift();
- return { type: 'clip', ...c, fadeInSec: 0, fadeOutSec: 0, volume: 1, ...effects };
+ // The v1 build may have SHORTENED this clip; a fade pair sized against the
+ // old trim would then be longer than the segment, which validateSegments
+ // refuses — leaving the layered editor unable to save until the user
+ // repaired it by hand.
+ const fades = fitFades(effects?.fadeInSec, effects?.fadeOutSec, c.outSec - c.inSec);
+ return { type: 'clip', ...c, volume: effects?.volume ?? 1, ...fades };
});
};
diff --git a/server/services/videoTimeline/segments.test.js b/server/services/videoTimeline/segments.test.js
index fb9bf3f72a..e836dfffe3 100644
--- a/server/services/videoTimeline/segments.test.js
+++ b/server/services/videoTimeline/segments.test.js
@@ -7,6 +7,8 @@ import {
validateAudio,
deriveLegacyClips,
resolveAsset,
+ assetPathFor,
+ fitFades,
segmentDuration,
laneDuration,
} from './segments.js';
@@ -218,3 +220,59 @@ describe('deriveLegacyClips', () => {
]);
});
});
+
+describe('assetPathFor — a valid gallery basename must stay usable', () => {
+ it('accepts a filename containing a `..` substring, which the gallery permits', () => {
+ // `safeUnder` rejects any `..` substring, which would make this real
+ // gallery file unselectable in the timeline.
+ expect(assetPathFor('images', 'my..render.png')).toMatch(/data[/\\]images[/\\]my\.\.render\.png$/);
+ expect(() => validateSegments([{ type: 'still', assetKind: 'images', assetFile: 'my..render.png', durationSec: 2 }]))
+ .not.toThrow();
+ });
+
+ it('still refuses a traversal segment, a separator and the bare dots', () => {
+ expect(assetPathFor('images', '../secrets.png')).toBeNull();
+ expect(assetPathFor('images', 'nested/logo.png')).toBeNull();
+ expect(assetPathFor('images', '..')).toBeNull();
+ expect(assetPathFor('images', '.')).toBeNull();
+ expect(assetPathFor('images', 'a\\b.png')).toBeNull();
+ });
+
+ it('refuses an unknown kind', () => {
+ expect(assetPathFor('videos', 'clip.mp4')).toBeNull();
+ });
+});
+
+describe('fitFades', () => {
+ it('leaves a fitting pair alone', () => {
+ expect(fitFades(1, 1, 4)).toEqual({ fadeInSec: 1, fadeOutSec: 1 });
+ });
+
+ it('scales an over-long pair proportionally rather than dropping one', () => {
+ expect(fitFades(1, 3, 2)).toEqual({ fadeInSec: 0.5, fadeOutSec: 1.5 });
+ });
+
+ it('collapses to zero when the duration does', () => {
+ expect(fitFades(1, 1, 0)).toEqual({ fadeInSec: 0, fadeOutSec: 0 });
+ });
+});
+
+describe('reconcileLegacyMirror — a legacy trim must not strand an over-long fade', () => {
+ it('refits fades carried onto a clip the v1 build shortened', () => {
+ const v2 = normalizeProject({
+ id: 'p1',
+ schemaVersion: 2,
+ segments: [{ type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 10, fadeInSec: 5, fadeOutSec: 5, volume: 0.5 }],
+ // The v1 editor cut this to 2s; the old 5s+5s fade pair no longer fits.
+ clips: [{ clipId: CLIP_A, inSec: 0, outSec: 2 }],
+ });
+
+ const [seg] = v2.segments;
+ expect(seg.outSec - seg.inSec).toBe(2);
+ expect(seg.fadeInSec + seg.fadeOutSec).toBeLessThanOrEqual(2);
+ expect(seg.volume).toBe(0.5);
+ // The refitted result must survive the persist-time validator, or the
+ // layered editor could never save this project again.
+ expect(() => validateSegments(v2.segments)).not.toThrow();
+ });
+});