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

fix: close three excerpt-render review findings (#8986)

[._.]/ Adam Eivye4b097bc4541
diff --git a/server/routes/musicVideoExcerpt.test.js b/server/routes/musicVideoExcerpt.test.js
index e7f3f7ac08..776a85c503 100644
--- a/server/routes/musicVideoExcerpt.test.js
+++ b/server/routes/musicVideoExcerpt.test.js
@@ -9,7 +9,7 @@
import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
import express from 'express';
-import { rmSync } from 'fs';
+import { existsSync, mkdirSync, rmSync, writeFileSync } from 'fs';
import { join } from 'path';
import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
@@ -116,4 +116,28 @@ describe('excerpts survive a clone (#8986 acceptance)', () => {
const cloned = await projects.cloneProject(project.id, {});
expect(cloned.excerpts).toEqual(project.excerpts);
});
+
+ // A clone never duplicates the rendered bytes — it carries over the SAME
+ // filename pointers as the source (see the previous test). Deleting one
+ // project's excerpt must not unlink a file the other still references.
+ it('does not delete the shared excerpt file while a clone still references it, and does once neither does', async () => {
+ const { project } = await projectWithExcerpt();
+ const cloned = await projects.cloneProject(project.id, {});
+ const videoPath = join(ROOT(), 'videos', 'music-video-excerpt-1.mp4');
+ const sheetPath = join(ROOT(), 'video-thumbnails', 'music-video-excerpt-1-sheet.png');
+ mkdirSync(join(ROOT(), 'videos'), { recursive: true });
+ mkdirSync(join(ROOT(), 'video-thumbnails'), { recursive: true });
+ writeFileSync(videoPath, 'mp4-bytes');
+ writeFileSync(sheetPath, 'png-bytes');
+
+ const first = await request(app).delete(`${base(project.id)}/excerpt/mve-1`);
+ expect(first.status).toBe(200);
+ expect(existsSync(videoPath)).toBe(true); // the clone still references it
+ expect(existsSync(sheetPath)).toBe(true);
+
+ const second = await request(app).delete(`${base(cloned.id)}/excerpt/mve-1`);
+ expect(second.status).toBe(200);
+ expect(existsSync(videoPath)).toBe(false); // no project references it anymore
+ expect(existsSync(sheetPath)).toBe(false);
+ });
});
diff --git a/server/services/musicVideo/excerpt.js b/server/services/musicVideo/excerpt.js
index 4f04119e46..c40b514576 100644
--- a/server/services/musicVideo/excerpt.js
+++ b/server/services/musicVideo/excerpt.js
@@ -27,7 +27,10 @@ import { ServerError } from '../../lib/errorHandler.js';
import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';
const MAX_NOTE_LEN = 2000;
-const MAX_EXCERPT_SEC = 3600;
+// Matches the route's musicVideoExcerptRequestSchema bound exactly — the same
+// generic "song time" ceiling every other music-video timedSec field uses —
+// so a range the public schema accepts can never fail this deeper check.
+const MAX_EXCERPT_SEC = 36000;
function excerptError(status, code, message, context) {
return new ServerError(message, { status, code, ...(context ? { context } : {}) });
diff --git a/server/services/musicVideo/excerptRender.js b/server/services/musicVideo/excerptRender.js
index d1352c7730..9431441e42 100644
--- a/server/services/musicVideo/excerptRender.js
+++ b/server/services/musicVideo/excerptRender.js
@@ -109,22 +109,32 @@ export async function startExcerptRender(projectId, { startSec, endSec }) {
console.log(`🎬 Rendering music-video excerpt [${jobId.slice(4, 12)}]: project=${projectId.slice(0, 8)} range=[${startSec.toFixed(2)},${endClamped.toFixed(2)}]s clips=${clips.length} cues=${cues.length}`);
+ // Returns whether the persistence write succeeded — the success path below
+ // gates its 'complete' broadcast on it, so a director is never told an
+ // excerpt is ready when the record never actually recorded it (the project
+ // would otherwise stay stuck 'rendering' while the client believes it's
+ // done). The error/cancel paths already broadcast their OWN terminal type
+ // before calling this, so their write failing only delays the record
+ // catching up (boot recovery clears a truly stuck one).
const finalize = async (patch) => {
projectExcerptRenders.delete(projectId);
- await mutateProjectRecord(projectId, (current) => ({ project: applyExcerptPatch(current, excerptId, patch) })).catch((err) => {
- console.error(`❌ Music-video excerpt render [${jobId.slice(4, 12)}] project ${projectId.slice(0, 8)} status→${patch.status} write failed: ${err.message}`);
- });
+ const persisted = await mutateProjectRecord(projectId, (current) => ({ project: applyExcerptPatch(current, excerptId, patch) }))
+ .then(() => true, (err) => {
+ console.error(`❌ Music-video excerpt render [${jobId.slice(4, 12)}] project ${projectId.slice(0, 8)} status→${patch.status} write failed: ${err.message}`);
+ return false;
+ });
if (composition) await removeCompositionScratch(jobId).catch((err) => {
console.warn(`⚠️ Music-video excerpt render [${jobId.slice(4, 12)}] could not remove its overlay scratch: ${err.message}`);
});
closeJobAfterDelay(jobs, jobId);
+ return persisted;
};
// A cut/cue contact sheet is a best-effort companion artifact — its
// failure never fails an excerpt whose video encoded successfully.
const buildContactSheet = async () => {
try {
- const times = excerptBoundaryTimes(probe.sections, cues, startSec, endClamped);
+ const times = excerptBoundaryTimes(probe.sections, cues, startSec, endClamped, { fps: probe.fps });
const sheetFilename = `${filename.replace(/\.mp4$/, '')}-sheet.png`;
await encodeFileContactSheetAtTimes(outputPath, join(PATHS.videoThumbnails, sheetFilename), times, { width: probe.canonW, height: probe.canonH });
return sheetFilename;
@@ -194,7 +204,11 @@ export async function startExcerptRender(projectId, { startSec, endSec }) {
try {
job.status = 'complete';
const contactSheetFilename = await buildContactSheet();
- await finalize({ status: 'complete', filename, contactSheetFilename, error: null, jobId: null });
+ const persisted = await finalize({ status: 'complete', filename, contactSheetFilename, error: null, jobId: null });
+ if (!persisted) {
+ broadcastSse(job, { type: 'error', error: 'The excerpt rendered, but saving the result failed — reload the project and try again' });
+ return;
+ }
console.log(`✅ Music-video excerpt rendered [${jobId.slice(4, 12)}]: ${filename}`);
broadcastSse(job, { type: 'complete', result: { excerptId, filename, path: `/data/videos/${filename}`, contactSheetFilename, contactSheetPath: contactSheetFilename ? `/data/video-thumbnails/${contactSheetFilename}` : null } });
} catch (err) {
diff --git a/server/services/musicVideo/excerptService.js b/server/services/musicVideo/excerptService.js
index c99169ede4..5bab9fbae3 100644
--- a/server/services/musicVideo/excerptService.js
+++ b/server/services/musicVideo/excerptService.js
@@ -12,7 +12,7 @@
import { unlink } from 'fs/promises';
import { PATHS } from '../../lib/fileUtils.js';
import { safeUnder } from '../../lib/ffmpeg.js';
-import { mutateProjectRecord } from './projects.js';
+import { listProjects, mutateProjectRecord } from './projects.js';
import {
addExcerptNote,
removeExcerptFromProject,
@@ -20,12 +20,28 @@ import {
updateExcerptNote,
} from './excerpt.js';
-/** Remove an excerpt and its rendered files. Refuses while its render is in flight. */
+// A clone carries its source project's `excerpts` over verbatim (the review
+// notes survive the clone, #8986 acceptance) — including the ORIGINAL's
+// filename/contactSheetFilename, since a clone never duplicates the actual
+// rendered bytes. Two projects can therefore point at the same on-disk file;
+// deleting one project's excerpt must not unlink it out from under the other.
+async function stillReferenced(filename) {
+ if (!filename) return false;
+ const projects = await listProjects();
+ return projects.some((p) => (p.excerpts || []).some((e) => e.filename === filename || e.contactSheetFilename === filename));
+}
+
+async function unlinkIfUnreferenced(root, filename) {
+ if (!filename || await stillReferenced(filename)) return;
+ await unlink(safeUnder(root, filename) || '').catch(() => {});
+}
+
+/** Remove an excerpt and its rendered files (only once no other project still references them). Refuses while its render is in flight. */
export async function deleteExcerpt(id, excerptId) {
const { project, excerpt } = await mutateProjectRecord(id, (current) => removeExcerptFromProject(current, excerptId));
await Promise.all([
- excerpt.filename ? unlink(safeUnder(PATHS.videos, excerpt.filename) || '').catch(() => {}) : null,
- excerpt.contactSheetFilename ? unlink(safeUnder(PATHS.videoThumbnails, excerpt.contactSheetFilename) || '').catch(() => {}) : null,
+ unlinkIfUnreferenced(PATHS.videos, excerpt.filename),
+ unlinkIfUnreferenced(PATHS.videoThumbnails, excerpt.contactSheetFilename),
]);
return project;
}
diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.js
index a4e6982b06..71f36ab5e5 100644
--- a/server/services/musicVideo/render.js
+++ b/server/services/musicVideo/render.js
@@ -480,12 +480,22 @@ export function buildMusicVideoFfmpegArgs(clips, audioPath, outputPath, { audioD
// returns them pre-excerpt, or as `renderableCues`/`sectionCardCues` compute
// them). Always includes both ends of the window so the sheet covers the first
// and last frame even when no cut/cue lands exactly on them.
-export function excerptBoundaryTimes(sections, cues, startSec, endSec) {
+//
+// No encoded video has a frame timestamped at its own total duration (the last
+// frame's presentation time is always `duration - 1/fps` or earlier), so any
+// boundary that lands exactly at the excerpt's end (its own `span`, including
+// one shifted there from a cut/cue at or past `endSec`) is guarded back to
+// `span - 1/fps` — the last frame a real capture can land on — rather than
+// asking `encodeFileContactSheetAtTimes` for an instant that doesn't exist.
+export function excerptBoundaryTimes(sections, cues, startSec, endSec, { fps = 24 } = {}) {
const span = endSec - startSec;
- const times = new Set([0, span]);
+ const lastFrame = fps > 0 ? Math.max(0, round3(span - 1 / fps)) : span;
+ const times = new Set([0, lastFrame]);
const add = (t) => {
if (typeof t !== 'number' || !Number.isFinite(t)) return;
- if (t >= startSec - 1e-9 && t <= endSec + 1e-9) times.add(round3(Math.min(span, Math.max(0, t - startSec))));
+ if (t < startSec - 1e-9 || t > endSec + 1e-9) return;
+ const rel = Math.min(span, Math.max(0, t - startSec));
+ times.add(rel >= span - 1e-9 ? lastFrame : round3(rel));
};
for (const s of Array.isArray(sections) ? sections : []) { add(s.startSec); add(s.endSec); }
for (const c of Array.isArray(cues) ? cues : []) { add(c.startSec); add(c.endSec); }
diff --git a/server/services/musicVideo/render.test.js b/server/services/musicVideo/render.test.js
index 6688acb54f..a1375e5fe4 100644
--- a/server/services/musicVideo/render.test.js
+++ b/server/services/musicVideo/render.test.js
@@ -95,6 +95,9 @@ describe('buildMusicVideoFfmpegArgs', () => {
});
describe('excerptBoundaryTimes (#8986)', () => {
+ // No encoded file has a frame timestamped at its own total duration, so the
+ // trailing boundary is always guarded back to `span - 1/fps` (default 24fps)
+ // — the last frame a real capture can land on.
it('re-bases cut and cue boundaries inside the window to the excerpt timeline and dedupes', () => {
const sections = [
{ sceneId: 'a', startSec: 0, endSec: 2 },
@@ -102,17 +105,30 @@ describe('excerptBoundaryTimes (#8986)', () => {
{ sceneId: 'c', startSec: 4, endSec: 6 },
];
const cues = [{ startSec: 2, endSec: 3 }]; // lands exactly on a cut — deduped
- expect(excerptBoundaryTimes(sections, cues, 1, 5)).toEqual([0, 1, 2, 3, 4]);
+ expect(excerptBoundaryTimes(sections, cues, 1, 5)).toEqual([0, 1, 2, 3, 3.958]);
});
it('always includes both ends of the window even with no cut/cue on them', () => {
const sections = [{ sceneId: 'a', startSec: 0, endSec: 10 }];
- expect(excerptBoundaryTimes(sections, [], 2, 7)).toEqual([0, 5]);
+ expect(excerptBoundaryTimes(sections, [], 2, 7)).toEqual([0, 4.958]);
});
it('drops boundaries outside the window', () => {
const sections = [{ sceneId: 'a', startSec: 0, endSec: 1 }, { sceneId: 'b', startSec: 1, endSec: 20 }];
- expect(excerptBoundaryTimes(sections, [], 5, 8)).toEqual([0, 3]);
+ expect(excerptBoundaryTimes(sections, [], 5, 8)).toEqual([0, 2.958]);
+ });
+
+ it('guards a cut/cue boundary that lands exactly at the window end the same as the trailing bookend', () => {
+ // Section b's end (6) lands exactly on the window's own end (endSec=6) —
+ // its re-based time (span=4) must collapse onto the SAME guarded last-frame
+ // time as the bookend, not sit at an impossible frame just past it.
+ const sections = [{ sceneId: 'a', startSec: 0, endSec: 2 }, { sceneId: 'b', startSec: 2, endSec: 6 }];
+ expect(excerptBoundaryTimes(sections, [], 2, 6)).toEqual([0, 3.958]);
+ });
+
+ it('scales the last-frame guard to the given fps', () => {
+ const sections = [{ sceneId: 'a', startSec: 0, endSec: 10 }];
+ expect(excerptBoundaryTimes(sections, [], 0, 10, { fps: 30 })).toEqual([0, 9.967]); // 10 - 1/30
});
});