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
fix a spurious lane-cap refusal, serialize editor writes, and cover resolveTimeline
[._.]/ Adam Eivy8afa32f48f39
diff --git a/client/src/components/media/VideoTimelineInspector.jsx b/client/src/components/media/VideoTimelineInspector.jsxindex 6870f9dc33..d1ae84afc6 100644--- a/client/src/components/media/VideoTimelineInspector.jsx+++ b/client/src/components/media/VideoTimelineInspector.jsx@@ -19,14 +19,17 @@ import { MAX_FADE_SEC } from '../../lib/videoTimelineModel';*/export const NumberField = memo(function NumberField({ id, label, value, step = 0.05, min = 0, max, hint, onCommit }) {const draft = useFieldDraft(Number.isFinite(value) ? Number(value).toFixed(2) : '', (next) => {+ // An emptied or non-numeric field is a discard, not a commit of zero:+ // useFieldDraft clears its buffer either way, so the input snaps back to+ // the persisted value instead of silently writing the clamped minimum.+ if (String(next).trim() === '') return;const n = Number(next);- // A non-numeric draft is discarded — useFieldDraft falls back to the- // persisted value, so the input snaps back rather than committing NaN.if (Number.isFinite(n)) onCommit(clamp(n, min, max ?? Infinity));});+ const hintId = hint ? `${id}-hint` : undefined;return (- <label htmlFor={id} className="block text-xs text-gray-400">- {label}+ <div className="block text-xs text-gray-400">+ <label htmlFor={id}>{label}</label><inputid={id}type="number"@@ -36,10 +39,13 @@ export const NumberField = memo(function NumberField({ id, label, value, step =value={draft.value}onChange={draft.onChange}onBlur={draft.onBlur}+ // The hint is described-by rather than nested in the label, or it+ // would be read as part of the field's name on every focus.+ aria-describedby={hintId}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>+ {hint && <span id={hintId} className="block mt-0.5 text-[10px] text-gray-500">{hint}</span>}+ </div>);});diff --git a/client/src/components/media/VideoTimelineInspector.test.jsx b/client/src/components/media/VideoTimelineInspector.test.jsxnew file mode 100644index 0000000000..f016ae06f1--- /dev/null+++ b/client/src/components/media/VideoTimelineInspector.test.jsx@@ -0,0 +1,99 @@+import { describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen } from '@testing-library/react';++import { NumberField, FadeFields, RemoveButton } from './VideoTimelineInspector';++describe('NumberField — bounds are declared once and enforced on commit', () => {+ const renderField = (props = {}) => {+ const onCommit = vi.fn();+ render(<NumberField id="f" label="Hold (s)" value={3} min={0.05} max={600} onCommit={onCommit} {...props} />);+ return { onCommit, input: screen.getByLabelText('Hold (s)') };+ };++ it('puts the same bounds on the input that it clamps with', () => {+ const { input } = renderField();+ expect(input).toHaveAttribute('min', '0.05');+ expect(input).toHaveAttribute('max', '600');+ });++ it('commits on blur, not per keystroke — editing must not round-trip each stroke', () => {+ const { onCommit, input } = renderField();+ fireEvent.change(input, { target: { value: '12' } });+ expect(onCommit).not.toHaveBeenCalled();+ fireEvent.blur(input);+ expect(onCommit).toHaveBeenCalledWith(12);+ });++ it('clamps a committed value into range rather than sending it to a 400', () => {+ const { onCommit, input } = renderField();+ fireEvent.change(input, { target: { value: '9999' } });+ fireEvent.blur(input);+ expect(onCommit).toHaveBeenCalledWith(600);+ });++ it('clamps below the minimum too', () => {+ const { onCommit, input } = renderField();+ fireEvent.change(input, { target: { value: '-5' } });+ fireEvent.blur(input);+ expect(onCommit).toHaveBeenCalledWith(0.05);+ });++ it('treats an emptied field as a discard, not a commit of the minimum', () => {+ // A number input yields '' for anything unparseable, so this covers the+ // non-numeric case too. Committing here would silently write 0.05.+ const { onCommit, input } = renderField();+ fireEvent.change(input, { target: { value: '' } });+ fireEvent.blur(input);+ expect(onCommit).not.toHaveBeenCalled();+ expect(input).toHaveValue(3);+ });++ it('does not fire a save when the field is focused and blurred untouched', () => {+ const { onCommit, input } = renderField();+ fireEvent.blur(input);+ expect(onCommit).not.toHaveBeenCalled();+ });++ it('describes the field with its hint without folding it into the label', () => {+ const hint = "Clamped to the file's real length at render";+ const { input } = renderField({ hint });+ // getByLabelText resolving means the hint did not become part of the name.+ expect(screen.getByText(hint)).toBeInTheDocument();+ expect(input).toHaveAttribute('aria-describedby', 'f-hint');+ });+});++describe('FadeFields — bounded by the entry AND by the server cap', () => {+ const renderFades = (duration) => {+ const onCommit = vi.fn();+ render(<FadeFields idPrefix="seg" entry={{ fadeInSec: 0, fadeOutSec: 0 }} duration={duration} onCommit={onCommit} />);+ return { onCommit, fadeIn: screen.getByLabelText('Fade in (s)') };+ };++ it('bounds a short entry by its own duration', () => {+ expect(renderFades(4).fadeIn).toHaveAttribute('max', '4');+ });++ it('bounds a long entry by the server 30s fade cap, not its duration', () => {+ // A 120s still would otherwise accept a 90s fade that the save 400s,+ // leaving the project unsavable until the user guessed the real limit.+ const { onCommit, fadeIn } = renderFades(120);+ expect(fadeIn).toHaveAttribute('max', '30');+ fireEvent.change(fadeIn, { target: { value: '90' } });+ fireEvent.blur(fadeIn);+ expect(onCommit).toHaveBeenCalledWith({ fadeInSec: 30 });+ });++ it('collapses to zero for a zero-length entry rather than going negative', () => {+ expect(renderFades(0).fadeIn).toHaveAttribute('max', '0');+ });+});++describe('RemoveButton', () => {+ it('is a labelled button that calls its handler', () => {+ const onClick = vi.fn();+ render(<RemoveButton label="Remove overlay" onClick={onClick} />);+ fireEvent.click(screen.getByRole('button', { name: /Remove overlay/ }));+ expect(onClick).toHaveBeenCalledOnce();+ });+});diff --git a/client/src/pages/VideoTimelineEditor.jsx b/client/src/pages/VideoTimelineEditor.jsxindex d849af99e9..64e92622de 100644--- a/client/src/pages/VideoTimelineEditor.jsx+++ b/client/src/pages/VideoTimelineEditor.jsx@@ -242,7 +242,20 @@ export default function VideoTimelineEditor() {// 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) => {+ // Every PATCH from this editor — a lane save, a rename — chains onto one+ // tail. All of them assert `expectedUpdatedAt`, so two in flight together+ // means the second is guaranteed a 409 even though nothing outside the+ // editor changed; if the loser is a lane save, its reload discards the edit+ // the user just made. Serializing here mirrors the server's own single-tail+ // write queue and leaves 409 meaning what it should: someone ELSE wrote.+ const writeTailRef = useRef(Promise.resolve());+ const queueWrite = useCallback((fn) => {+ const next = writeTailRef.current.then(fn, fn);+ writeTailRef.current = next.catch(() => {});+ return next;+ }, []);++ const saveTimeline = useCallback((next) => queueWrite(async () => {if (updatedAtRef.current == null) return false;const updated = await api.updateTimelineProject(projectId, {...timelinePatch(next),@@ -260,7 +273,7 @@ export default function VideoTimelineEditor() {updatedAtRef.current = updated.updatedAt;setProject((p) => ({ ...p, updatedAt: updated.updatedAt }));return true;- }, [projectId, refresh]);+ }), [projectId, refresh, queueWrite]);// 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@@ -296,20 +309,20 @@ export default function VideoTimelineEditor() {// gate 400s the whole PATCH, so one entry over the limit makes EVERY// subsequent debounced save fail with a message that names no lane, and the// user has to guess which one to trim.+ //+ // The decision reads `lanes` directly, NOT a flag set inside the setState+ // updater — React only runs an updater eagerly when the fiber has no pending+ // work, and the rAF playhead loop keeps work pending throughout playback, so+ // such a flag would still be false when read and report a spurious "limit+ // reached" on a perfectly good add.const addToLane = useCallback((lane, entry) => {- let added = false;- updateLanes((prev) => {- const entries = laneEntries(prev, lane);- if (entries.length >= LANE_CAPS[lane].max) return prev;- added = true;- return withLaneEntries(prev, lane, [...entries, entry]);- });- if (!added) {+ if (laneEntries(lanes, lane).length >= LANE_CAPS[lane].max) {toast.error(`${LANE_CAPS[lane].label} limit reached (${LANE_CAPS[lane].max}) — remove one first`);return;}+ updateLanes((prev) => withLaneEntries(prev, lane, [...laneEntries(prev, lane), entry]));setSelection({ lane, key: entry._key });- }, [updateLanes]);+ }, [lanes, updateLanes]);const removeFromLane = useCallback((lane, key) => {updateLanes((prev) => withLaneEntries(prev, lane, laneEntries(prev, lane).filter((e) => e._key !== key)));@@ -691,22 +704,27 @@ export default function VideoTimelineEditor() {aria-label="Project name"value={nameDraft}onChange={(e) => setNameDraft(e.target.value)}- onBlur={async (e) => {+ onBlur={(e) => {const trimmed = e.target.value.trim();if (!trimmed) { setNameDraft(project.name); return; }if (trimmed === project.name) return;- const updated = await api.updateTimelineProject(projectId, {- name: trimmed, expectedUpdatedAt: updatedAtRef.current,- }, { silent: true }).catch((err) => {- toast.error(`Rename failed: ${err.message}`);- setNameDraft(project.name);- return null;+ // Through the same tail as the lane saves — see queueWrite. The+ // expectedUpdatedAt read has to happen INSIDE the queued fn, or+ // it captures a value the preceding write has already replaced.+ queueWrite(async () => {+ const updated = await api.updateTimelineProject(projectId, {+ name: trimmed, expectedUpdatedAt: updatedAtRef.current,+ }, { silent: true }).catch((err) => {+ toast.error(`Rename failed: ${err.message}`);+ setNameDraft(project.name);+ return null;+ });+ if (updated) {+ updatedAtRef.current = updated.updatedAt;+ setProject((p) => ({ ...p, name: updated.name, updatedAt: updated.updatedAt }));+ setNameDraft(updated.name);+ }});- if (updated) {- updatedAtRef.current = updated.updatedAt;- setProject((p) => ({ ...p, name: updated.name, updatedAt: updated.updatedAt }));- setNameDraft(updated.name);- }}}className="bg-transparent text-white font-medium text-lg focus:outline-none focus:bg-port-card focus:px-2 rounded transition-all"/>diff --git a/client/src/pages/VideoTimelineEditor.test.jsx b/client/src/pages/VideoTimelineEditor.test.jsxnew file mode 100644index 0000000000..f46484003e--- /dev/null+++ b/client/src/pages/VideoTimelineEditor.test.jsx@@ -0,0 +1,158 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { render, screen, waitFor, fireEvent } from '@testing-library/react';++// The editor's pure rules live in lib/videoTimelineModel.js and its blocks in+// components/media/VideoTimelineLanes.jsx, both tested there. What only exists+// here is the page's own wiring: which lanes render, what counts as a missing+// source, and the lane caps.++vi.mock('@dnd-kit/sortable', async () => {+ const actual = await vi.importActual('@dnd-kit/sortable');+ return {+ ...actual,+ useSortable: () => ({+ attributes: {}, listeners: {}, setNodeRef: () => {}, transform: null, transition: null, isDragging: false,+ }),+ };+});++const toastError = vi.hoisted(() => vi.fn());+vi.mock('../components/ui/Toast', () => ({+ default: Object.assign(vi.fn(), { error: toastError, success: vi.fn() }),+}));++vi.mock('react-router', () => ({+ useParams: () => ({ projectId: 'p1' }),+ useNavigate: () => vi.fn(),+}));++vi.mock('../hooks/useSseProgress', () => ({+ useSseProgress: () => ({ latest: null, closed: false }),+ isTerminalSseFrame: () => false,+}));++const api = vi.hoisted(() => ({+ project: null,+ history: [],+ gallery: [],+ music: { tracks: [] },+ galleryThrows: false,+}));++vi.mock('../services/api', () => ({+ getTimelineProject: async () => api.project,+ listVideoHistory: async () => api.history,+ listImageGallery: async () => {+ if (api.galleryThrows) throw new Error('network');+ return api.gallery;+ },+ listMusicLibrary: async () => api.music,+ updateTimelineProject: async () => ({ updatedAt: 'u2' }),+ renderTimelineProject: async () => ({ jobId: 'j1' }),+}));++const VideoTimelineEditor = (await import('./VideoTimelineEditor')).default;++const CLIP_A = '11111111-1111-4111-8111-111111111111';++const project = (over = {}) => ({+ id: 'p1', name: 'Example Project', updatedAt: 'u1', schemaVersion: 2,+ segments: [], overlays: [], audio: { clipVolume: 1, tracks: [] }, clips: [], ...over,+});++const clipSegment = { type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 4, fadeInSec: 0, fadeOutSec: 0, volume: 1 };+const stillSegment = { type: 'still', assetKind: 'images', assetFile: 'plate.png', durationSec: 3, fadeInSec: 0, fadeOutSec: 0 };+const overlayEntry = { type: 'image', assetKind: 'images', assetFile: 'logo.png', startSec: 0, durationSec: 2, x: 0, y: 0, width: 0.25, opacity: 1, fadeInSec: 0, fadeOutSec: 0 };+const bedEntry = { assetKind: 'music', assetFile: 'bed.mp3', startSec: 0, offsetSec: 0, durationSec: 4, volume: 1, fadeInSec: 0, fadeOutSec: 0 };++beforeEach(() => {+ toastError.mockClear();+ api.project = project();+ api.history = [{ id: CLIP_A, prompt: 'A dramatic sunrise', filename: 'a.mp4', thumbnail: 'a.jpg', width: 1920, height: 1080, fps: 24, numFrames: 96 }];+ api.gallery = [{ filename: 'plate.png' }, { filename: 'logo.png' }];+ api.music = { tracks: [{ filename: 'bed.mp3', label: 'Bed' }] };+ api.galleryThrows = false;+});++const renderEditor = async () => {+ render(<VideoTimelineEditor />);+ await waitFor(() => expect(screen.queryByText('Loading project…')).not.toBeInTheDocument());+};++describe('lane visibility', () => {+ it('shows the empty-timeline hint only when EVERY lane is empty', async () => {+ await renderEditor();+ expect(screen.getByText(/Add clips, stills, overlays and audio/)).toBeInTheDocument();+ });++ it('renders the free lanes for a project whose video lane is empty', async () => {+ // Overlays and beds added to an empty project would otherwise be+ // unselectable and unremovable on reload.+ api.project = project({ overlays: [overlayEntry], audio: { clipVolume: 1, tracks: [bedEntry] } });+ await renderEditor();++ expect(screen.queryByText(/Add clips, stills, overlays and audio/)).not.toBeInTheDocument();+ expect(screen.getByText('Add a clip or a still from the library')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Remove logo.png from timeline' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Remove bed.mp3 from timeline' })).toBeInTheDocument();+ });++ it('summarises every lane in the header, not just the video lane', async () => {+ api.project = project({ segments: [clipSegment, stillSegment], overlays: [overlayEntry], audio: { clipVolume: 1, tracks: [bedEntry] } });+ await renderEditor();+ expect(screen.getByText(/2 segments · 1 overlays · 1 beds/)).toBeInTheDocument();+ });+});++describe('missing-source detection', () => {+ it('flags a still whose gallery file is gone', async () => {+ api.gallery = [{ filename: 'logo.png' }];+ api.project = project({ segments: [stillSegment] });+ await renderEditor();+ expect(screen.getByText('(missing)')).toBeInTheDocument();+ });++ it('says nothing when the gallery fetch FAILED — an unloaded catalogue is not evidence of absence', async () => {+ // Collapsing a failed fetch into "empty" would mark every still and+ // overlay missing even though the server can still render them.+ api.galleryThrows = true;+ api.project = project({ segments: [stillSegment], overlays: [overlayEntry] });+ await renderEditor();+ expect(screen.queryByText('(missing)')).not.toBeInTheDocument();+ });++ it('does not flag an asset kind it has no catalogue for', async () => {+ api.project = project({ audio: { clipVolume: 1, tracks: [{ ...bedEntry, assetKind: 'audio', assetFile: 'vo.wav' }] } });+ await renderEditor();+ expect(screen.queryByText('(missing)')).not.toBeInTheDocument();+ });+});++describe('lane caps', () => {+ it('refuses an add past the overlay cap with a message naming the lane', async () => {+ // One entry over the cap 400s every later debounced save, with nothing+ // telling the user which lane to trim.+ api.project = project({+ segments: [clipSegment],+ overlays: Array.from({ length: 50 }, (_, i) => ({ ...overlayEntry, assetFile: `logo${i}.png` })),+ });+ api.gallery = [{ filename: 'plate.png' }, ...Array.from({ length: 50 }, (_, i) => ({ filename: `logo${i}.png` }))];+ await renderEditor();++ fireEvent.click(screen.getByRole('tab', { name: /Stills/ }));+ fireEvent.click(screen.getAllByRole('button', { name: 'Overlay' })[0]);++ expect(toastError).toHaveBeenCalledWith(expect.stringContaining('Overlay lane limit reached (50)'));+ });++ it('allows the add when the lane is under the cap', async () => {+ api.project = project({ segments: [clipSegment] });+ await renderEditor();++ fireEvent.click(screen.getByRole('tab', { name: /Stills/ }));+ fireEvent.click(screen.getAllByRole('button', { name: 'Overlay' })[0]);++ expect(toastError).not.toHaveBeenCalled();+ await waitFor(() => expect(screen.getByRole('button', { name: 'Remove plate.png from timeline' })).toBeInTheDocument());+ });+});diff --git a/server/services/videoTimeline/local.resolve.test.js b/server/services/videoTimeline/local.resolve.test.jsnew file mode 100644index 0000000000..8983f67f6a--- /dev/null+++ b/server/services/videoTimeline/local.resolve.test.js@@ -0,0 +1,226 @@+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { mkdirSync, writeFileSync, rmSync } from 'fs';+import { join } from 'path';+import { mockPathsDataRoot } from '../../lib/mockPathsDataRoot.js';++// resolveTimeline is where the lane model meets the filesystem: it verifies+// every source, picks the canonical canvas, probes audio presence and bed+// durations, and refits fades that a later change made too long. buildFfmpegArgs+// tests all START from a resolved timeline, so none of that is covered there.+const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'timeline-resolve-' });++vi.mock('../../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../../lib/fileUtils.js');+ return makeProxy(actual);+});++const h = vi.hoisted(() => ({+ history: [],+ // `null` from a duration probe means "could not probe", never "zero seconds".+ probedDuration: null,+ hasAudio: true,+}));++vi.mock('../videoGen/local.js', () => ({+ loadHistory: async () => h.history,+ mutateVideoHistory: async (fn) => fn([]),+}));++vi.mock('../../lib/ffmpeg.js', async () => {+ const actual = await vi.importActual('../../lib/ffmpeg.js');+ return {+ ...actual,+ findFfprobe: async () => '/usr/bin/ffprobe',+ probeVideoDuration: async () => h.probedDuration,+ };+});++// probeAudio spawns ffprobe itself; stub the child so the flag is ours to set.+vi.mock('../../lib/childProcess.js', async () => {+ const actual = await vi.importActual('../../lib/childProcess.js');+ return { ...actual, spawn: () => {+ const listeners = {};+ const proc = {+ stdout: { on: (ev, fn) => { if (ev === 'data') fn(Buffer.from(h.hasAudio ? 'audio\n' : '\n')); } },+ on: (ev, fn) => { listeners[ev] = fn; if (ev === 'close') setImmediate(() => fn(0)); return proc; },+ };+ return proc;+ } };+});++const { resolveTimeline } = await import('./local.js');++const VIDEOS = join(tempRoot, 'videos');+const IMAGES = join(tempRoot, 'images');+const MUSIC = join(tempRoot, 'music');++const CLIP_A = '11111111-1111-4111-8111-111111111111';+const CLIP_B = '22222222-2222-4222-8222-222222222222';++const historyEntry = (id, over = {}) => ({+ id, filename: `${id}.mp4`, width: 1920, height: 1080, fps: 24, numFrames: 240, ...over,+});++beforeEach(() => {+ for (const dir of [VIDEOS, IMAGES, MUSIC]) mkdirSync(dir, { recursive: true });+ writeFileSync(join(VIDEOS, `${CLIP_A}.mp4`), 'x');+ writeFileSync(join(VIDEOS, `${CLIP_B}.mp4`), 'x');+ writeFileSync(join(IMAGES, 'plate.png'), 'x');+ writeFileSync(join(MUSIC, 'bed.mp3'), 'x');+ h.history = [historyEntry(CLIP_A), historyEntry(CLIP_B)];+ h.probedDuration = null;+ h.hasAudio = true;+});++afterAll(() => cleanup());++const project = (over = {}) => ({+ id: 'p1', schemaVersion: 2, overlays: [], audio: { clipVolume: 1, tracks: [] }, clips: [], ...over,+});++describe('resolveTimeline — sources', () => {+ it('refuses an empty lane', async () => {+ await expect(resolveTimeline(project({ segments: [] }))).rejects.toMatchObject({ code: 'EMPTY_PROJECT' });+ });++ it('reports every missing clip AND asset in one 404, so the editor can flag them all at once', async () => {+ const err = await resolveTimeline(project({+ segments: [+ { type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 4 },+ { type: 'clip', clipId: '33333333-3333-4333-8333-333333333333', inSec: 0, outSec: 2 },+ { type: 'still', assetKind: 'images', assetFile: 'gone.png', durationSec: 2 },+ ],+ overlays: [{ type: 'image', assetKind: 'images', assetFile: 'nologo.png', startSec: 0, durationSec: 1, x: 0, y: 0, width: 0.5, opacity: 1, fadeInSec: 0, fadeOutSec: 0 }],+ audio: { clipVolume: 1, tracks: [{ assetKind: 'music', assetFile: 'nobed.mp3', startSec: 0, offsetSec: 0, durationSec: 2, volume: 1, fadeInSec: 0, fadeOutSec: 0 }] },+ })).catch((e) => e);++ expect(err.context.missingClipIds).toHaveLength(1);+ expect(err.context.missingAssets).toEqual(['images/gone.png', 'images/nologo.png', 'music/nobed.mp3']);+ });++ it('rejects a clip trimmed shorter than one frame', async () => {+ await expect(resolveTimeline(project({+ segments: [{ type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 0.001 }],+ }))).rejects.toMatchObject({ code: 'CLIP_TOO_SHORT' });+ });++ it('clamps an out point past the source duration', async () => {+ // 240 frames at 24fps = 10s of source.+ const { segments } = await resolveTimeline(project({+ segments: [{ type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 99 }],+ }));+ expect(segments[0].outSec).toBe(10);+ expect(segments[0].duration).toBe(10);+ });+});++describe('resolveTimeline — canonical canvas', () => {+ it('skips a clip carrying no dimensions rather than letterboxing the project into the fallback', async () => {+ // An uploaded or downloaded clip has no width/height in history+ // (videoUpload.js / videoDownload.js write none). Taking the first clip+ // unconditionally would force the whole render to 720p — and disagree+ // with the editor's preview, which skips those too.+ h.history = [historyEntry(CLIP_A, { width: undefined, height: undefined, fps: undefined }), historyEntry(CLIP_B, { width: 1080, height: 1920, fps: 30 })];++ const resolved = await resolveTimeline(project({+ segments: [+ { type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 4 },+ { type: 'clip', clipId: CLIP_B, inSec: 0, outSec: 4 },+ ],+ }));++ expect([resolved.canonW, resolved.canonH, resolved.fps]).toEqual([1080, 1920, 30]);+ });++ it('falls back to 720p24 when NO clip has dimensions', async () => {+ h.history = [historyEntry(CLIP_A, { width: undefined, height: undefined, fps: undefined })];+ const resolved = await resolveTimeline(project({+ segments: [{ type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 4 }],+ }));+ expect([resolved.canonW, resolved.canonH, resolved.fps]).toEqual([1280, 720, 24]);+ });++ it('falls back to 720p24 for a stills-only project', async () => {+ const resolved = await resolveTimeline(project({+ segments: [{ type: 'still', assetKind: 'images', assetFile: 'plate.png', durationSec: 3, fadeInSec: 0, fadeOutSec: 0 }],+ }));+ expect([resolved.canonW, resolved.canonH, resolved.fps]).toEqual([1280, 720, 24]);+ expect(resolved.segments[0]).toMatchObject({ type: 'still', duration: 3 });+ });+});++describe('resolveTimeline — fades that a later change made too long', () => {+ it('refits a clip fade against a trim the history entry has since shortened', async () => {+ // Stored trim says 0–8s with 3s+3s of fade; the source is only 1s long+ // now, so the pair must shrink or ffmpeg renders the segment all black.+ h.history = [historyEntry(CLIP_A, { numFrames: 24, fps: 24 })];+ const { segments } = await resolveTimeline(project({+ segments: [{ type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 8, fadeInSec: 3, fadeOutSec: 3, volume: 1 }],+ }));++ expect(segments[0].duration).toBe(1);+ expect(segments[0].fadeInSec + segments[0].fadeOutSec).toBeCloseTo(1);+ });++ it('refits a still fade against its own hold', async () => {+ const { segments } = await resolveTimeline(project({+ segments: [{ type: 'still', assetKind: 'images', assetFile: 'plate.png', durationSec: 1, fadeInSec: 3, fadeOutSec: 3 }],+ }));+ expect(segments[0].fadeInSec + segments[0].fadeOutSec).toBeCloseTo(1);+ });+});++describe('resolveTimeline — bed probing', () => {+ const bedProject = (over = {}) => project({+ segments: [{ type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 4 }],+ audio: {+ clipVolume: 1,+ tracks: [{ assetKind: 'music', assetFile: 'bed.mp3', startSec: 0, offsetSec: 0, durationSec: 30, volume: 1, fadeInSec: 0, fadeOutSec: 0, ...over }],+ },+ });++ it('clamps a requested slice to what the file actually holds', async () => {+ h.probedDuration = 5;+ const { audioTracks } = await resolveTimeline(bedProject());+ expect(audioTracks[0].durationSec).toBe(5);+ });++ it('leaves the slice alone when the probe could not run — null is not zero seconds', async () => {+ // With no ffprobe (or an unreadable container) the requested slice stands;+ // collapsing null into 0 would silently drop the bed from every render.+ h.probedDuration = null;+ const { audioTracks } = await resolveTimeline(bedProject());+ expect(audioTracks[0].durationSec).toBe(30);+ });++ it('pulls an offset back inside the file and shrinks the slice to match', async () => {+ h.probedDuration = 4;+ const { audioTracks } = await resolveTimeline(bedProject({ offsetSec: 100, durationSec: 10 }));+ expect(audioTracks[0].offsetSec).toBeLessThanOrEqual(4);+ expect(audioTracks[0].offsetSec + audioTracks[0].durationSec).toBeLessThanOrEqual(4);+ });++ it('refits the bed fades after the probe shortens it', async () => {+ h.probedDuration = 2;+ const { audioTracks } = await resolveTimeline(bedProject({ fadeInSec: 5, fadeOutSec: 5 }));+ expect(audioTracks[0].fadeInSec + audioTracks[0].fadeOutSec).toBeCloseTo(2);+ });+});++describe('resolveTimeline — audio presence', () => {+ it('records the probed flag per clip', async () => {+ h.hasAudio = false;+ const { segments } = await resolveTimeline(project({+ segments: [{ type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 4 }],+ }));+ expect(segments[0].hasAudio).toBe(false);+ });++ it('carries the project clip volume through for the mix', async () => {+ const resolved = await resolveTimeline(project({+ segments: [{ type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 4 }],+ audio: { clipVolume: 0.25, tracks: [] },+ }));+ expect(resolved.clipVolume).toBe(0.25);+ });+});diff --git a/server/services/videoTimeline/local.test.js b/server/services/videoTimeline/local.test.jsindex c71bb7fd45..3ef626c168 100644--- a/server/services/videoTimeline/local.test.js+++ b/server/services/videoTimeline/local.test.js@@ -437,16 +437,3 @@ describe('buildFfmpegArgs — an overlay clamped by the timeline end', () => {expect(filter).toContain('fade=t=out:st=5.5:d=2:alpha=1');});});--describe('buildFfmpegArgs — canonical geometry', () => {- it('is taken from the timeline, which skips a clip carrying no dimensions', () => {- // An uploaded or downloaded clip has no width/height in history; letting- // it decide the canvas would letterbox the whole project into 720p and- // disagree with the editor's preview, which skips those too.- const { canonW, canonH } = buildFfmpegArgs({- segments: [baseClip({ width: undefined, height: undefined }), baseClip({ width: 1080, height: 1920 })],- canonW: 1080, canonH: 1920, fps: 24,- }, '/out.mp4');- expect([canonW, canonH]).toEqual([1080, 1920]);- });-});diff --git a/server/services/videoTimeline/segments.js b/server/services/videoTimeline/segments.jsindex ace8ca213e..888f712bdc 100644--- a/server/services/videoTimeline/segments.js+++ b/server/services/videoTimeline/segments.js@@ -132,7 +132,12 @@ const clampFades = (fadeInSec, fadeOutSec, duration, label) => {// `ffmpeg exit 1`; refusing them here turns that into a 400 naming the field.const IMAGE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp'];const AUDIO_EXTENSIONS = ['.mp3', '.wav', '.m4a', '.aac', '.flac', '.ogg', '.opus'];-const extensionsFor = (kinds) => (kinds === AUDIO_ASSET_KINDS ? AUDIO_EXTENSIONS : IMAGE_EXTENSIONS);+const EXTENSIONS_BY_KIND = {+ images: IMAGE_EXTENSIONS,+ 'video-thumbnails': IMAGE_EXTENSIONS,+ audio: AUDIO_EXTENSIONS,+ music: AUDIO_EXTENSIONS,+};const assetFields = (raw, allowedKinds, label) => {const assetKind = String(raw.assetKind || '').trim();@@ -146,7 +151,7 @@ const assetFields = (raw, allowedKinds, label) => {if (!assetPathFor(assetKind, assetFile)) {throw bad(`${label}: assetFile must be a plain filename inside data/${assetKind}`);}- const extensions = extensionsFor(allowedKinds);+ const extensions = EXTENSIONS_BY_KIND[assetKind];if (!extensions.some((ext) => assetFile.toLowerCase().endsWith(ext))) {throw bad(`${label}: assetFile must be one of ${extensions.join(', ')}`);}