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

reconcile a v1-edited clips mirror, and stop the editor reporting live sources as missing

[._.]/ Adam Eivy055da061d388
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index d3d8608fdf..963dd4e87a 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -200,6 +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`/`findSegmentAt` (project-time ↔ segment mapping), `fadeMultiplier` (linear, matching ffmpeg's default `tri` curve), `overlayOpacityAt`, `audioTrackStateAt`, `segmentVolumeAt` (clipVolume × segment volume × fade — the product the export writes into each segment audio chain, so the preview auditions the mix that renders), `assetUrl(assetKind, assetFile)`, the edit clamps `clampTrim` (keeps ≥ 1 frame, matching the server's CLIP_TOO_SHORT floor) and `fitFadePatch` (shrinks an over-long fade pair proportionally instead of letting the PATCH 400), and the save helpers `stripKey`/`withKeys`/`timelinePatch`. Change a rule here and in the server module in the same commit. |
+| `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`/`findSegmentAt` (project-time ↔ segment mapping), `fadeMultiplier` (linear, matching ffmpeg's default `tri` curve), `overlayOpacityAt`, `audioTrackStateAt`, `segmentVolumeAt` (clipVolume × segment volume × fade — the product the export writes into each segment audio chain, so the preview auditions the mix that renders), `assetUrl(assetKind, assetFile)`, the edit clamps `clampTrim` (keeps ≥ 1 frame, matching the server's CLIP_TOO_SHORT floor) and `fitFadePatch` (shrinks an over-long fade pair proportionally instead of letting the PATCH 400), the index summary `projectSummary(project, thumbnailFor)` (block count / duration / card thumbnail — reads the `segments` lane, NEVER the derived `clips` mirror, which omits stills), 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/videoTimelineModel.js b/client/src/lib/videoTimelineModel.js
index 7209e28a98..bc8ec271e9 100644
--- a/client/src/lib/videoTimelineModel.js
+++ b/client/src/lib/videoTimelineModel.js
@@ -180,3 +180,27 @@ export const segmentVolumeAt = (segment, clipVolume, within) => {
const base = (clipVolume == null ? 1 : clipVolume) * (segment.volume == null ? 1 : segment.volume);
return clamp(base * fadeMultiplier(segment.fadeInSec || 0, segment.fadeOutSec || 0, duration, within), 0, 1);
};
+
+/**
+ * Summary a project index needs: how many blocks the timeline holds, how long
+ * it runs, and a thumbnail for the card.
+ *
+ * Reads the `segments` lane, NEVER the derived `clips` mirror — the mirror
+ * carries only clip segments, so a project built from stills would report zero
+ * blocks and zero seconds while playing back perfectly in the editor. A v1
+ * project that predates the lane falls back to `clips`, which for it IS the
+ * lane. `thumbnailFor(clipId)` resolves a video clip's thumbnail filename.
+ */
+export const projectSummary = (project, thumbnailFor) => {
+ const segments = Array.isArray(project?.segments) ? project.segments : (project?.clips || []);
+ let totalSec = 0;
+ let firstThumb = null;
+ for (const segment of segments) {
+ totalSec += segmentDuration(segment);
+ if (firstThumb) continue;
+ firstThumb = segment.type === 'still'
+ ? assetUrl(segment.assetKind, segment.assetFile)
+ : assetUrl('video-thumbnails', thumbnailFor(segment.clipId));
+ }
+ return { totalSec, blockCount: segments.length, firstThumb };
+};
diff --git a/client/src/lib/videoTimelineModel.test.js b/client/src/lib/videoTimelineModel.test.js
index e92f904d8f..873121e925 100644
--- a/client/src/lib/videoTimelineModel.test.js
+++ b/client/src/lib/videoTimelineModel.test.js
@@ -13,6 +13,7 @@ import {
clampTrim,
fitFadePatch,
segmentVolumeAt,
+ projectSummary,
} from './videoTimelineModel';
const clip = (inSec, outSec) => ({ type: 'clip', clipId: 'c', inSec, outSec });
@@ -223,3 +224,48 @@ describe('segmentVolumeAt — preview must audition what the export mixes', () =
expect(segmentVolumeAt({ type: 'still', durationSec: 3 }, 1, 1)).toBe(0);
});
});
+
+describe('projectSummary — the index must count the lane, not the mirror', () => {
+ const thumbFor = (id) => (id === 'c1' ? 'c1.jpg' : null);
+
+ it('counts stills, which the derived clips mirror deliberately omits', () => {
+ const summary = projectSummary({
+ segments: [
+ { type: 'clip', clipId: 'c1', inSec: 0, outSec: 2 },
+ { type: 'still', assetKind: 'images', assetFile: 'plate.png', durationSec: 3 },
+ ],
+ // A layered project's mirror carries only its clip segments; reading it
+ // here would under-report the timeline the editor actually plays.
+ clips: [{ clipId: 'c1', inSec: 0, outSec: 2 }],
+ }, thumbFor);
+
+ expect(summary).toMatchObject({ blockCount: 2, totalSec: 5 });
+ });
+
+ it('does not report a stills-only project as empty', () => {
+ const summary = projectSummary({
+ segments: [{ type: 'still', assetKind: 'images', assetFile: 'plate.png', durationSec: 4 }],
+ clips: [],
+ }, thumbFor);
+
+ expect(summary).toMatchObject({ blockCount: 1, totalSec: 4, firstThumb: '/data/images/plate.png' });
+ });
+
+ it('falls back to clips for a v1 project, where the mirror IS the lane', () => {
+ expect(projectSummary({ clips: [{ clipId: 'c1', inSec: 1, outSec: 4 }] }, thumbFor))
+ .toMatchObject({ blockCount: 1, totalSec: 3, firstThumb: '/data/video-thumbnails/c1.jpg' });
+ });
+
+ it('takes the first block\'s thumbnail, still or clip', () => {
+ expect(projectSummary({
+ segments: [
+ { type: 'still', assetKind: 'images', assetFile: 'first.png', durationSec: 1 },
+ { type: 'clip', clipId: 'c1', inSec: 0, outSec: 1 },
+ ],
+ }, thumbFor).firstThumb).toBe('/data/images/first.png');
+ });
+
+ it('reports an empty project as empty rather than throwing', () => {
+ expect(projectSummary({}, thumbFor)).toEqual({ totalSec: 0, blockCount: 0, firstThumb: null });
+ });
+});
diff --git a/client/src/pages/VideoTimeline.jsx b/client/src/pages/VideoTimeline.jsx
index db27c56e83..396125ff65 100644
--- a/client/src/pages/VideoTimeline.jsx
+++ b/client/src/pages/VideoTimeline.jsx
@@ -5,6 +5,7 @@ import PageSkeleton from '../components/ui/PageSkeleton';
import toast from '../components/ui/Toast';
import * as api from '../services/api';
import { formatDurationSec } from '../utils/formatters';
+import { projectSummary } from '../lib/videoTimelineModel';
export default function VideoTimeline() {
const navigate = useNavigate();
@@ -52,19 +53,8 @@ export default function VideoTimeline() {
const projectStats = useMemo(() => {
const historyMap = new Map(history.map((h) => [h.id, h]));
- const stats = new Map();
- for (const project of projects) {
- let totalSec = 0;
- let firstThumb = null;
- for (const ref of project.clips || []) {
- const clip = historyMap.get(ref.clipId);
- if (!clip) continue;
- totalSec += Math.max(0, ref.outSec - ref.inSec);
- if (!firstThumb && clip.thumbnail) firstThumb = `/data/video-thumbnails/${clip.thumbnail}`;
- }
- stats.set(project.id, { totalSec, firstThumb });
- }
- return stats;
+ const thumbnailFor = (clipId) => historyMap.get(clipId)?.thumbnail;
+ return new Map(projects.map((p) => [p.id, projectSummary(p, thumbnailFor)]));
}, [projects, history]);
return (
@@ -100,7 +90,7 @@ export default function VideoTimeline() {
{!loading && projects.length > 0 && (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
{projects.map((project) => {
- const { totalSec, firstThumb } = projectStats.get(project.id) || { totalSec: 0, firstThumb: null };
+ const { totalSec, blockCount, firstThumb } = projectStats.get(project.id) || { totalSec: 0, blockCount: 0, firstThumb: null };
return (
<div key={project.id} className="bg-port-card border border-port-border rounded-xl overflow-hidden hover:border-port-accent/50 transition-colors">
<button
@@ -135,7 +125,7 @@ export default function VideoTimeline() {
</button>
</div>
<div className="flex items-center gap-3 text-xs text-gray-400">
- <span className="flex items-center gap-1"><Film className="w-3 h-3" />{(project.clips || []).length} clips</span>
+ <span className="flex items-center gap-1"><Film className="w-3 h-3" />{blockCount} blocks</span>
<span className="flex items-center gap-1"><Clock className="w-3 h-3" />{formatDurationSec(totalSec)}</span>
</div>
</div>
diff --git a/client/src/pages/VideoTimelineEditor.jsx b/client/src/pages/VideoTimelineEditor.jsx
index c226dcbfdc..7a48483d27 100644
--- a/client/src/pages/VideoTimelineEditor.jsx
+++ b/client/src/pages/VideoTimelineEditor.jsx
@@ -81,6 +81,8 @@ export default function VideoTimelineEditor() {
const [history, setHistory] = useState([]);
const [images, setImages] = useState([]);
const [musicTracks, setMusicTracks] = useState([]);
+ // Which catalogues have actually been fetched — see knownAbsent below.
+ const [loaded, setLoaded] = useState({ clips: false, images: false, music: false });
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
// The three lanes live in ONE state object so a save always ships a
@@ -128,11 +130,15 @@ export default function VideoTimelineEditor() {
const refresh = useCallback(async () => {
setLoading(true);
setError(null);
+ // `null` = the request FAILED; `[]` = a genuinely empty library. Collapsing
+ // the two would wipe a populated list on a transient error and then mark
+ // every segment, overlay and bed drawing on it as "missing" — sources the
+ // server can still render perfectly well.
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),
+ api.listVideoHistory({ silent: true }).catch(() => null),
+ api.listImageGallery({ silent: true }).catch(() => null),
+ api.listMusicLibrary({ silent: true }).catch(() => null),
]);
if (proj) {
const nextLanes = {
@@ -153,11 +159,16 @@ export default function VideoTimelineEditor() {
const entries = laneEntries(nextLanes, lane);
setSelection(entries?.[index] ? { lane, key: entries[index]._key } : null);
}
- 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 (Array.isArray(hist)) setHistory(hist);
+ if (Array.isArray(gallery)) setImages(gallery);
if (library) setMusicTracks(Array.isArray(library.tracks) ? library.tracks : []);
+ // Whether each library actually loaded, so the "missing source" badges can
+ // stay silent about a lane whose catalogue we never received.
+ setLoaded((prev) => ({
+ clips: prev.clips || Array.isArray(hist),
+ images: prev.images || Array.isArray(gallery),
+ music: prev.music || !!library,
+ }));
setLoading(false);
}, [projectId]);
@@ -187,13 +198,24 @@ export default function VideoTimelineEditor() {
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.
+ // A lane entry is "missing" when its source is gone from the catalogue it
+ // came from — the render would 404, so the editor flags it up front.
+ //
+ // Only `images`, `music` and the video history have a client-side catalogue.
+ // For an asset kind we cannot enumerate — or a catalogue whose fetch failed —
+ // "absent from the list" is NOT evidence of absence on disk, so say nothing
+ // and let the render's MISSING_CLIPS report be the authority.
+ const knownAbsent = useCallback((kind, file) => {
+ if (kind === 'images') return loaded.images && !imageNames.has(file);
+ if (kind === 'music') return loaded.music && !musicNames.has(file);
+ return false; // 'video-thumbnails' / 'audio' — no catalogue to check against
+ }, [loaded.images, loaded.music, imageNames, musicNames]);
+
const isSegmentMissing = useCallback((seg) => (seg.type === 'still'
- ? !imageNames.has(seg.assetFile)
- : !historyMap.has(seg.clipId)), [imageNames, historyMap]);
- const isOverlayMissing = useCallback((ov) => !imageNames.has(ov.assetFile), [imageNames]);
- const isBedMissing = useCallback((tr) => tr.assetKind === 'music' && !musicNames.has(tr.assetFile), [musicNames]);
+ ? knownAbsent(seg.assetKind, seg.assetFile)
+ : loaded.clips && !historyMap.has(seg.clipId)), [knownAbsent, loaded.clips, historyMap]);
+ const isOverlayMissing = useCallback((ov) => knownAbsent(ov.assetKind, ov.assetFile), [knownAbsent]);
+ const isBedMissing = useCallback((tr) => knownAbsent(tr.assetKind, tr.assetFile), [knownAbsent]);
const total = useMemo(() => timelineDuration(segments), [segments]);
@@ -851,31 +873,39 @@ export default function VideoTimelineEditor() {
</div>
<div className="bg-port-card/30 border border-port-border rounded-lg p-2 overflow-x-auto space-y-1">
- {segments.length === 0 ? (
+ {segments.length === 0 && overlays.length === 0 && audio.tracks.length === 0 ? (
<div className="text-xs text-gray-500 py-6 text-center">
Drag-drop reorder once you've added clips. Add clips, stills, overlays and audio from the library on the left.
</div>
) : (
+ /* Every lane renders whenever ANY lane has content. Gating the
+ free lanes on the video lane would strand an overlay or bed
+ added to an empty project — unselectable and unremovable until
+ a video segment happened to be added. */
<>
<div className="text-[9px] uppercase tracking-wide text-gray-600 px-0.5">Video</div>
- <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd}>
- <SortableContext items={segmentKeys} 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={selectSegment}
- onRemove={removeSegment}
- />
- ))}
- </div>
- </SortableContext>
- </DndContext>
+ {segments.length === 0 ? (
+ <div className="text-[10px] text-gray-600 pl-2 py-2">Add a clip or a still from the library</div>
+ ) : (
+ <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd}>
+ <SortableContext items={segmentKeys} 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={selectSegment}
+ onRemove={removeSegment}
+ />
+ ))}
+ </div>
+ </SortableContext>
+ </DndContext>
+ )}
<FloatingLane
title="Overlays"
diff --git a/server/services/videoTimeline/local.crud.test.js b/server/services/videoTimeline/local.crud.test.js
index d1fcfb672f..16a810aff4 100644
--- a/server/services/videoTimeline/local.crud.test.js
+++ b/server/services/videoTimeline/local.crud.test.js
@@ -209,3 +209,40 @@ describe('updateProject — the v1 clips payload cannot silently destroy the new
expect(updated.segments[0].durationSec).toBe(4);
});
});
+
+describe('updateProject — a legacy save cannot silently reset clip effects', () => {
+ it('refuses a clips-only save against a lane carrying fades', async () => {
+ seed([{
+ id: 'p1', updatedAt: 'u1', schemaVersion: 2, clips: [{ clipId: CLIP_A, inSec: 0, outSec: 4 }],
+ segments: [{ type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 4, fadeInSec: 1, fadeOutSec: 0, volume: 1 }],
+ overlays: [], audio: { clipVolume: 1, tracks: [] },
+ }]);
+
+ // The v1 payload has no fade field, so rebuilding from it would reset the
+ // fade to zero without telling anyone.
+ await expect(updateProject('p1', { clips: [{ clipId: CLIP_A, inSec: 0, outSec: 4 }] }))
+ .rejects.toMatchObject({ code: 'SCHEMA_TOO_NEW' });
+ });
+
+ it('refuses a clips-only save against a lane carrying a non-default volume', async () => {
+ seed([{
+ id: 'p1', updatedAt: 'u1', schemaVersion: 2, clips: [{ clipId: CLIP_A, inSec: 0, outSec: 4 }],
+ segments: [{ type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 4, fadeInSec: 0, fadeOutSec: 0, volume: 0.4 }],
+ overlays: [], audio: { clipVolume: 1, tracks: [] },
+ }]);
+
+ await expect(updateProject('p1', { clips: [{ clipId: CLIP_A, inSec: 0, outSec: 4 }] }))
+ .rejects.toMatchObject({ code: 'SCHEMA_TOO_NEW' });
+ });
+
+ it('accepts it when every clip is at its neutral defaults — nothing can be lost', async () => {
+ seed([{
+ id: 'p1', updatedAt: 'u1', schemaVersion: 2, clips: [{ clipId: CLIP_A, inSec: 0, outSec: 4 }],
+ segments: [{ type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 4, fadeInSec: 0, fadeOutSec: 0, volume: 1 }],
+ overlays: [], audio: { clipVolume: 1, tracks: [] },
+ }]);
+
+ const updated = await updateProject('p1', { clips: [{ clipId: CLIP_B, inSec: 1, outSec: 6 }] });
+ expect(updated.segments[0]).toMatchObject({ clipId: CLIP_B, inSec: 1, outSec: 6 });
+ });
+});
diff --git a/server/services/videoTimeline/local.js b/server/services/videoTimeline/local.js
index 5f22bf311b..95989199cc 100644
--- a/server/services/videoTimeline/local.js
+++ b/server/services/videoTimeline/local.js
@@ -23,7 +23,7 @@ import { randomUUID } from 'crypto';
import { ensureDir, PATHS, readJSONFile, atomicWrite } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
-import { findFfmpeg, findFfprobe, safeUnder, generateThumbnail, probeVideoDuration, BT709_CONTAINER_ARGS } from '../../lib/ffmpeg.js';
+import { findFfmpeg, findFfprobe, safeUnder, generateThumbnail, probeVideoDuration, BT709_CONTAINER_ARGS, bt709TagFilter } from '../../lib/ffmpeg.js';
import { safeChildProcessOptions } from '../../lib/processEnv.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { attachFfmpegRenderGuard } from '../../lib/ffmpegRenderGuard.js';
@@ -177,12 +177,16 @@ export async function updateProject(id, patch, expectedUpdatedAt) {
if (!Array.isArray(patch.clips)) {
throw new ServerError('clips must be an array', { status: 400, code: 'VALIDATION_ERROR' });
}
- const nonClip = (project.segments || []).filter((s) => s.type !== 'clip');
- if (nonClip.length > 0) {
- throw new ServerError('Project uses the layered timeline — a clips-only save would drop its non-clip segments', {
+ // A `clips` entry carries only { clipId, inSec, outSec }, so rebuilding the
+ // lane from one erases every layered field it cannot express — a still
+ // outright, and a clip's fades and volume back to their neutral defaults.
+ const wouldDrop = (project.segments || []).filter((s) => s.type !== 'clip'
+ || s.fadeInSec > 0 || s.fadeOutSec > 0 || (s.volume != null && s.volume !== 1));
+ if (wouldDrop.length > 0) {
+ throw new ServerError('Project uses the layered timeline — a clips-only save would drop its stills, fades or volume', {
status: 409,
code: 'SCHEMA_TOO_NEW',
- context: { schemaVersion: TIMELINE_SCHEMA_VERSION, droppedSegmentCount: nonClip.length },
+ context: { schemaVersion: TIMELINE_SCHEMA_VERSION, droppedSegmentCount: wouldDrop.length },
});
}
project.segments = validateSegments(patch.clips.map((c) => ({ type: 'clip', ...(c && typeof c === 'object' ? c : {}) })));
@@ -423,7 +427,7 @@ const fadeChain = (prefix, { fadeInSec = 0, fadeOutSec = 0 }, duration, lead = [
// carries its on-disk path, its project-time `duration`, and (for a clip) its
// probed `hasAudio`. Geometry comes off the timeline rather than being
// re-derived here, so exactly one place decides the canvas.
-export function buildFfmpegArgs(timeline, outputPath) {
+export function buildFfmpegArgs(timeline, outputPath, { colorTagFilter = null } = {}) {
const t = timeline || {};
const segments = t.segments || [];
if (segments.length === 0) throw new Error('buildFfmpegArgs: empty clips');
@@ -490,7 +494,13 @@ export function buildFfmpegArgs(timeline, outputPath) {
// 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]';
+ // From ffmpeg 8 the encoder reads colour properties off the FRAMES, silently
+ // overriding the container flags — so a flags-only output still decodes
+ // washed-out. `setparams` stamps the frames; the caller probes for it once
+ // (`bt709TagFilter()`) and passes the string in, keeping this builder pure.
+ const tag = typeof colorTagFilter === 'string' && colorTagFilter ? colorTagFilter : null;
+ const videoOut = tag ? '[vpre]' : '[outv]';
+ const vConcatOut = overlays.length > 0 ? '[cv]' : videoOut;
const aConcatOut = audioTracks.length > 0 ? '[ca]' : '[outa]';
filters.push(`${concatStreams.join('')}concat=n=${segments.length}:v=1:a=1${vConcatOut}${aConcatOut}`);
@@ -516,7 +526,7 @@ export function buildFfmpegArgs(timeline, outputPath) {
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}]`;
+ const out = j === overlays.length - 1 ? videoOut : `[ovc${j}]`;
filters.push(
`${overlayIn}[ov${j}]overlay=x=${x}:y=${y}:eof_action=pass:enable='between(t,${fmt(ov.startSec)},${fmt(end)})'${out}`
);
@@ -555,6 +565,8 @@ export function buildFfmpegArgs(timeline, outputPath) {
);
}
+ if (tag) filters.push(`[vpre]${tag}[outv]`);
+
const args = [
...inputs,
'-filter_complex', filters.join(';'),
@@ -614,7 +626,7 @@ export async function renderProject(projectId) {
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(timeline, outputPath);
+ const { args, totalDuration, canonW, canonH, fps } = buildFfmpegArgs(timeline, outputPath, { colorTagFilter: await bt709TagFilter() });
const job = {
id: jobId,
diff --git a/server/services/videoTimeline/local.terminal.test.js b/server/services/videoTimeline/local.terminal.test.js
index 9fa173eeb5..4be5b568ef 100644
--- a/server/services/videoTimeline/local.terminal.test.js
+++ b/server/services/videoTimeline/local.terminal.test.js
@@ -50,6 +50,7 @@ vi.mock('../../lib/ffmpeg.js', () => ({
safeUnder: (root, name) => (name ? `${root}/${name}` : null),
generateThumbnail: vi.fn(async () => 'thumb.jpg'),
probeVideoDuration: vi.fn(async () => null), // no bed probing in these render-lifecycle cases
+ bt709TagFilter: vi.fn(async () => null), // no setparams on this stub build
BT709_CONTAINER_ARGS: ['-color_primaries', 'bt709', '-color_trc', 'bt709', '-colorspace', 'bt709'],
}));
vi.mock('../../lib/processEnv.js', () => ({
diff --git a/server/services/videoTimeline/local.test.js b/server/services/videoTimeline/local.test.js
index 893f6a63fa..47d5adae71 100644
--- a/server/services/videoTimeline/local.test.js
+++ b/server/services/videoTimeline/local.test.js
@@ -379,3 +379,35 @@ describe('buildFfmpegArgs — combined lanes and input indexing', () => {
expect(filter).not.toContain('0.19999');
});
});
+
+describe('buildFfmpegArgs — BT.709 frame tagging', () => {
+ const TAG = 'setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709';
+
+ it('stamps the frames as well as the container when the build supports setparams', () => {
+ // From ffmpeg 8 the encoder reads colour off the FRAMES and overrides the
+ // container flags, so the flags alone still decode washed-out.
+ const filter = filterOf(buildFfmpegArgs(lane([baseClip()]), '/out.mp4', { colorTagFilter: TAG }).args);
+ expect(filter).toContain('concat=n=1:v=1:a=1[vpre][outa]');
+ expect(filter).toContain(`[vpre]${TAG}[outv]`);
+ });
+
+ it('tags after the overlay composite, not before it', () => {
+ const filter = filterOf(buildFfmpegArgs(lane([baseClip()], {
+ 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,
+ }],
+ }), '/out.mp4', { colorTagFilter: TAG }).args);
+ expect(filter).toContain('[cv][ov0]overlay=');
+ expect(filter).toContain('[vpre]');
+ expect(filter.indexOf('overlay=')).toBeLessThan(filter.indexOf(`[vpre]${TAG}`));
+ });
+
+ it('emits the minimal graph unchanged on a build without the filter', () => {
+ const { args } = buildFfmpegArgs(lane([baseClip()]), '/out.mp4', { colorTagFilter: null });
+ expect(filterOf(args)).toContain('concat=n=1:v=1:a=1[outv][outa]');
+ expect(filterOf(args)).not.toContain('setparams');
+ // The container flags need no probe and are always emitted.
+ expect(args).toContain('-color_primaries');
+ });
+});
diff --git a/server/services/videoTimeline/segments.js b/server/services/videoTimeline/segments.js
index b6cfe4b9e7..8435a3a8cb 100644
--- a/server/services/videoTimeline/segments.js
+++ b/server/services/videoTimeline/segments.js
@@ -224,6 +224,44 @@ export const deriveLegacyClips = (segments) => segments
.filter((s) => s.type === 'clip')
.map((s) => ({ clipId: s.clipId, inSec: s.inSec, outSec: s.outSec }));
+const sameMirror = (a, b) => a.length === b.length
+ && a.every((c, i) => c.clipId === b[i].clipId && c.inSec === b[i].inSec && c.outSec === b[i].outSec);
+
+/**
+ * Reconcile a stored `clips` mirror that no longer matches its lane.
+ *
+ * v2 rebuilds the mirror on every write, so a divergence can only come from a
+ * v1 build editing the project after a rollback: that build knows only `clips`
+ * and leaves `segments` untouched, so trusting `segments` would silently
+ * discard the user's legacy edits. Take the mirror as the authority for order
+ * and trims, carrying each clip's fades and volume across from the segment
+ * that still matches it by id (matched in order, so a clip used twice keeps
+ * both of its treatments).
+ *
+ * A lane holding STILLS is the one unreconcilable case — a v1 mirror cannot
+ * represent them, so honouring it would delete work the old build never saw.
+ * The lane wins there and the mirror is rebuilt.
+ */
+const reconcileLegacyMirror = (segments, storedClips) => {
+ if (!Array.isArray(storedClips)) return segments;
+ if (segments.some((s) => s.type !== 'clip')) return segments;
+ const mirror = storedClips
+ .filter((c) => c && typeof c === 'object')
+ .map((c) => ({ clipId: String(c.clipId || ''), inSec: Math.max(0, num(c.inSec, 0)), outSec: num(c.outSec, NaN) }))
+ .filter((c) => c.clipId && Number.isFinite(c.outSec) && c.outSec > c.inSec);
+ if (sameMirror(deriveLegacyClips(segments), mirror)) return segments;
+
+ const effectsById = new Map();
+ for (const s of segments) {
+ if (!effectsById.has(s.clipId)) effectsById.set(s.clipId, []);
+ effectsById.get(s.clipId).push({ fadeInSec: s.fadeInSec, fadeOutSec: s.fadeOutSec, volume: s.volume });
+ }
+ return mirror.map((c) => {
+ const effects = effectsById.get(c.clipId)?.shift();
+ return { type: 'clip', ...c, fadeInSec: 0, fadeOutSec: 0, volume: 1, ...effects };
+ });
+};
+
/**
* 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`
@@ -241,7 +279,7 @@ export function normalizeProject(project) {
? project.segments
: legacyClips.map((c) => ({ type: 'clip', ...c }));
- const segments = rawSegments.flatMap((entry) => {
+ const coerced = rawSegments.flatMap((entry) => {
if (!entry || typeof entry !== 'object') return [];
const type = entry.type || (entry.clipId ? 'clip' : null);
if (type === 'clip') {
@@ -273,6 +311,12 @@ export function normalizeProject(project) {
return [];
});
+ // A stored mirror that diverges from the lane means a rolled-back v1 build
+ // edited this project; that edit is newer than the lane it never touched.
+ const segments = Array.isArray(project.segments)
+ ? reconcileLegacyMirror(coerced, project.clips)
+ : coerced;
+
const overlays = Array.isArray(project.overlays)
? project.overlays.filter((o) => o && typeof o === 'object').map((o) => ({
type: 'image',
diff --git a/server/services/videoTimeline/segments.test.js b/server/services/videoTimeline/segments.test.js
index bb88d32ebc..fb9bf3f72a 100644
--- a/server/services/videoTimeline/segments.test.js
+++ b/server/services/videoTimeline/segments.test.js
@@ -40,16 +40,49 @@ describe('normalizeProject — v1 → v2 upgrade', () => {
expect(normalizeProject(once)).toEqual(once);
});
- it('rebuilds the clips mirror from segments, so a stale mirror cannot resurrect a removed segment', () => {
- const project = {
+ it('takes a diverged clips mirror as a rolled-back v1 build\'s edit, not a stale copy', () => {
+ // v2 rebuilds the mirror on every write, so a mirror that disagrees with
+ // the lane can only have been written by a v1 build after a rollback —
+ // and that edit is newer than the lane it had no way to touch.
+ const v2 = normalizeProject({
id: 'p1',
schemaVersion: 2,
- segments: [{ type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 2 }],
- // An older build wrote this before the segment was deleted.
+ segments: [{ type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 2, fadeInSec: 0.5, volume: 0.3 }],
clips: [{ clipId: CLIP_A, inSec: 0, outSec: 2 }, { clipId: CLIP_B, inSec: 0, outSec: 9 }],
- };
+ });
+
+ expect(v2.segments.map((s) => s.clipId)).toEqual([CLIP_A, CLIP_B]);
+ // Effects the v1 build couldn't see ride across from the matching segment.
+ expect(v2.segments[0]).toMatchObject({ fadeInSec: 0.5, volume: 0.3 });
+ // A clip the v1 build added carries neutral defaults.
+ expect(v2.segments[1]).toMatchObject({ clipId: CLIP_B, fadeInSec: 0, fadeOutSec: 0, volume: 1 });
+ });
+
+ it('keeps the lane when it holds stills — a v1 mirror cannot represent them', () => {
+ const v2 = normalizeProject({
+ id: 'p1',
+ schemaVersion: 2,
+ segments: [
+ { type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 2 },
+ { type: 'still', assetKind: 'images', assetFile: 'plate.png', durationSec: 3 },
+ ],
+ // Honouring this would delete a still the old build never saw.
+ clips: [{ clipId: CLIP_B, inSec: 0, outSec: 9 }],
+ });
+
+ expect(v2.segments).toHaveLength(2);
+ expect(v2.segments[1]).toMatchObject({ type: 'still', assetFile: 'plate.png' });
+ expect(v2.clips).toEqual([{ clipId: CLIP_A, inSec: 0, outSec: 2 }]);
+ });
- expect(normalizeProject(project).clips).toEqual([{ clipId: CLIP_A, inSec: 0, outSec: 2 }]);
+ it('leaves a matching mirror alone — no divergence, no reconciliation', () => {
+ const v2 = normalizeProject({
+ id: 'p1',
+ schemaVersion: 2,
+ segments: [{ type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 2, fadeInSec: 0.5, fadeOutSec: 0, volume: 0.3 }],
+ clips: [{ clipId: CLIP_A, inSec: 0, outSec: 2 }],
+ });
+ expect(v2.segments[0]).toMatchObject({ fadeInSec: 0.5, volume: 0.3 });
});
it('drops corrupt entries instead of throwing — this runs on every read', () => {