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
feat(creative-director): sanity-check rendered video before auto-accept
Adam Eivy0de9416e8987
diff --git a/PLAN.md b/PLAN.mdindex 737763dfde..a73d83143e 100644--- a/PLAN.md+++ b/PLAN.md@@ -21,7 +21,7 @@ The PR landed with full pipeline mechanics + auto-recovery + smoke-test fixture,- [ ] **Audio continuity across scenes.** mlx-video-with-audio generates audio per-clip; concatenated scenes have audible cuts at scene boundaries. Either render scenes silently and add a single backing audio pass at stitch time, or apply a short crossfade in `videoTimeline/local.js#buildFfmpegArgs` (already does video crossfades — extend to audio with `acrossfade`).- [ ] **Duplicate evaluator spawn dedup.** During the long E2E run, server logs showed `Task already being spawned, skipping duplicate` followed seconds later by a *second* agent spawning for the exact same task id. The CoS task lane logic ends up double-acquiring. Reproduce in a unit test against `taskSchedule` / `agentLifecycle` and fix the de-dup window.- [ ] **Render slowness on long sessions.** Per-scene render time degraded from ~3.5 min (early) to 10–30 min (late) within one project — likely accumulated listeners + queue races. Profile after sustained use; the round-22 dedup work probably already helps; verify.-- [ ] **Auto-accept watchdog.** `autoAcceptScenes: true` skips the Claude evaluator entirely. Add a server-side sanity check (file exists, file size > 0, ffprobe can read at least 1 frame) before writing the synthetic accepted evaluation — without it a black/zero-frame render would still be marked accepted.+- [x] ~~**Auto-accept watchdog.**~~ Done — `verifyVideoPlayable()` in `server/lib/ffmpeg.js` checks file-exists / size > 0 / ffprobe-can-read-at-least-1-frame. `sceneRunner.handleRenderCompleted` runs it before marking the auto-accept synthetic evaluation; on failure it routes to `handleRenderFailed` (which respects `MAX_SCENE_RETRIES`) instead of polluting the collection with a broken video. Falls back to file-exists/size checks only on hosts without ffprobe installed.- [x] ~~**Smoke-test cost reduction.**~~ Done — dropped `durationSeconds` 3s→2s, added a hidden `1:1-small` (384×384) aspect preset for the smoke fixture only (kept out of `ASPECT_RATIOS` so the user-facing dropdown is unchanged). Smoke run now ~63% cheaper in pixel-frame terms. Lets pipeline health checks complete in render time only.### Other backlogdiff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.jsindex dfb0de83be..7122a0d766 100644--- a/server/lib/ffmpeg.js+++ b/server/lib/ffmpeg.js@@ -7,7 +7,7 @@*/import { execFile, spawn } from 'child_process';-import { existsSync } from 'fs';+import { existsSync, statSync } from 'fs';import { unlink, rename } from 'fs/promises';import { join, resolve as resolvePath, sep as PATH_SEP, dirname } from 'path';import { randomUUID } from 'crypto';@@ -108,6 +108,36 @@ const probeFrameCount = async (videoPath) => {return (await run(false)) ?? (await run(true));};+// Sanity-check that a rendered video file is actually playable: the file+// exists on disk, has non-zero bytes, and ffprobe can decode at least one+// video frame from it. Returns `{ ok: true }` on success and+// `{ ok: false, reason }` with a short human-readable cause on failure.+//+// Used by the `autoAcceptScenes` path in the Creative Director scene+// runner to avoid marking a black/zero-frame render as accepted just+// because the renderer process exited 0. Falls back to "ok" when ffprobe+// is unavailable so machines without ffmpeg installed still complete the+// auto-accept flow (the file-exists/size>0 checks still run).+export const verifyVideoPlayable = async (videoPath) => {+ if (typeof videoPath !== 'string' || !videoPath) {+ return { ok: false, reason: 'invalid video path' };+ }+ if (!existsSync(videoPath)) {+ return { ok: false, reason: `video file missing: ${videoPath}` };+ }+ const size = statSync(videoPath).size;+ if (!size || size <= 0) {+ return { ok: false, reason: 'video file is empty (0 bytes)' };+ }+ const ffprobe = await findFfprobe();+ if (!ffprobe) return { ok: true };+ const frames = await probeFrameCount(videoPath);+ if (!frames || frames < 1) {+ return { ok: false, reason: 'ffprobe could not read any video frames' };+ }+ return { ok: true };+};+// Extract `count` evenly-spaced frames across the video for the cognitive// evaluator. Saved as `<jobId>-f1.jpg ... -f<count>.jpg` in// `data/video-thumbnails/`. Returns the array of basenames in timeline orderdiff --git a/server/lib/ffmpeg.test.js b/server/lib/ffmpeg.test.jsnew file mode 100644index 0000000000..906358e17a--- /dev/null+++ b/server/lib/ffmpeg.test.js@@ -0,0 +1,71 @@+import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import { writeFileSync, mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import { verifyVideoPlayable, safeUnder } from './ffmpeg.js';++describe('verifyVideoPlayable', () => {+ let tmpDir;+ beforeAll(() => {+ tmpDir = mkdtempSync(join(tmpdir(), 'portos-ffmpeg-test-'));+ });+ afterAll(() => {+ rmSync(tmpDir, { recursive: true, force: true });+ });++ it('rejects an empty/invalid path', async () => {+ expect(await verifyVideoPlayable('')).toEqual({ ok: false, reason: 'invalid video path' });+ expect(await verifyVideoPlayable(null)).toEqual({ ok: false, reason: 'invalid video path' });+ expect(await verifyVideoPlayable(undefined)).toEqual({ ok: false, reason: 'invalid video path' });+ });++ it('rejects a missing file', async () => {+ const missing = join(tmpDir, 'does-not-exist.mp4');+ const res = await verifyVideoPlayable(missing);+ expect(res.ok).toBe(false);+ expect(res.reason).toMatch(/missing/);+ });++ it('rejects a zero-byte file', async () => {+ const empty = join(tmpDir, 'empty.mp4');+ writeFileSync(empty, '');+ const res = await verifyVideoPlayable(empty);+ expect(res.ok).toBe(false);+ expect(res.reason).toMatch(/empty/);+ });++ it('rejects a non-empty but non-decodable file when ffprobe is available', async () => {+ // Garbage bytes that look like a non-empty file but cannot be decoded as+ // video — ffprobe will report no frames. When ffprobe is NOT installed+ // on the test host, the helper short-circuits to ok:true (documented+ // behavior), so we accept either outcome here rather than skipping.+ const junk = join(tmpDir, 'junk.mp4');+ writeFileSync(junk, Buffer.alloc(64, 0));+ const res = await verifyVideoPlayable(junk);+ if (!res.ok) {+ expect(res.reason).toMatch(/ffprobe|frame/);+ } else {+ expect(res.ok).toBe(true);+ }+ });+});++describe('safeUnder', () => {+ it('accepts a plain basename under a root', () => {+ const root = '/tmp/portos-root';+ expect(safeUnder(root, 'foo.mp4')).toBe('/tmp/portos-root/foo.mp4');+ });++ it('rejects path-traversal segments', () => {+ expect(safeUnder('/tmp/portos-root', '../escape.mp4')).toBeNull();+ expect(safeUnder('/tmp/portos-root', 'sub/foo.mp4')).toBeNull();+ expect(safeUnder('/tmp/portos-root', '..')).toBeNull();+ });++ it('rejects non-string input', () => {+ expect(safeUnder('/tmp/portos-root', null)).toBeNull();+ expect(safeUnder('/tmp/portos-root', undefined)).toBeNull();+ expect(safeUnder('/tmp/portos-root', 42)).toBeNull();+ });+});diff --git a/server/services/creativeDirector/sceneRunner.js b/server/services/creativeDirector/sceneRunner.jsindex 17b3e11a2e..d402cf9f90 100644--- a/server/services/creativeDirector/sceneRunner.js+++ b/server/services/creativeDirector/sceneRunner.js@@ -32,7 +32,7 @@ import { join, basename, resolve as resolvePath, sep as PATH_SEP } from 'path';import { existsSync } from 'fs';import { PATHS } from '../../lib/fileUtils.js';import { presetToRenderParams } from '../../lib/creativeDirectorPresets.js';-import { extractEvaluationFrames, safeUnder } from '../../lib/ffmpeg.js';+import { extractEvaluationFrames, safeUnder, verifyVideoPlayable } from '../../lib/ffmpeg.js';import { extractLastFrame } from '../videoGen/local.js';import { enqueueJob, mediaJobEvents } from '../mediaJobQueue/index.js';import { getSettings } from '../settings.js';@@ -206,6 +206,19 @@ async function handleRenderCompleted(projectId, sceneId, jobId) {// video into the project's collection, and let the orchestrator advance.// No Claude task spawned, so a smoke run completes in render time only.if (fresh.autoAcceptScenes === true) {+ // Sanity-check the rendered file BEFORE marking accepted: a black /+ // zero-byte / unreadable render exits the queue with code 0 in some+ // ffmpeg+mlx_video failure modes, which would otherwise sail through+ // auto-accept and pollute the collection with broken videos.+ const videoPath = safeUnder(PATHS.videos, `${jobId}.mp4`);+ const sanity = videoPath+ ? await verifyVideoPlayable(videoPath)+ : { ok: false, reason: `unsafe video path for jobId ${jobId}` };+ if (!sanity.ok) {+ console.log(`⚠️ CD auto-accept sanity check failed for ${sceneId} (${jobId.slice(0, 8)}): ${sanity.reason}`);+ await handleRenderFailed(projectId, sceneId, `auto-accept sanity check failed: ${sanity.reason}`);+ return;+ }await updateScene(projectId, sceneId, {status: 'accepted',renderedJobId: jobId,