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: scale music-video auto-review sampling to cover every shot (#9272)
Adam Eivy9154b6ba58c7
diff --git a/server/routes/musicVideoAutoReview.test.js b/server/routes/musicVideoAutoReview.test.jsindex 41d3ec1227..59e852e8f8 100644--- a/server/routes/musicVideoAutoReview.test.js+++ b/server/routes/musicVideoAutoReview.test.js@@ -61,21 +61,18 @@ vi.mock('../lib/ffmpeg.js', async (importOriginal) => {...real,findFfmpeg: vi.fn(async () => (h.analysisAvailable ? 'ffmpeg' : null)),findFfprobe: vi.fn(async () => (h.analysisAvailable ? 'ffprobe' : null)),- // Real frame files, so the reviewer sees a non-empty continuous strip.- extractEvaluationFrames: vi.fn(async (_path, id, count) => {- mkdir(PATHS.videoThumbnails, { recursive: true });- return Array.from({ length: count }, (_, i) => {- const name = `${id}-f${i + 1}.jpg`;- write(joinPath(PATHS.videoThumbnails, name), 'jpg');- return name;- });- }),+ probeVideoStreamInfo: vi.fn(async () => ({ width: 640, height: 360, fps: 24, frameCount: null })),};});vi.mock('../lib/sseUtils.js', () => ({ broadcastSse: vi.fn(), attachSseClient: vi.fn(() => true), closeJobAfterDelay: vi.fn() }));vi.mock('../services/instanceIdentity.js', () => ({ ensureInstanceId: vi.fn(async () => 'inst-test') }));vi.mock('../lib/killWithEscalation.js', () => ({ killWithEscalation: vi.fn((proc) => proc.emit('close', null, 'SIGTERM')) }));-vi.mock('../services/htmlComposition/encode.js', () => ({ encodeFileContactSheetAtTimes: vi.fn(async () => {}) }));+// Real sheet files, so the reviewer sees a non-empty continuous strip.+vi.mock('../services/htmlComposition/encode.js', async () => {+ const { writeFileSync: write, mkdirSync: mkdir } = await import('fs');+ const { dirname } = await import('path');+ return { encodeFileContactSheetAtTimes: vi.fn(async (_video, out) => { mkdir(dirname(out), { recursive: true }); write(out, 'jpg'); }) };+});vi.mock('../services/mediaJobQueue/index.js', async () => ({mediaJobEvents: new (await import('events')).EventEmitter(),listJobs: vi.fn(({ kind } = {}) => h.jobs.filter((j) => !kind || j.kind === kind)),diff --git a/server/services/htmlComposition/encode.js b/server/services/htmlComposition/encode.jsindex e9d26533ce..5d2de43213 100644--- a/server/services/htmlComposition/encode.js+++ b/server/services/htmlComposition/encode.js@@ -252,13 +252,13 @@ export async function encodeReferenceContactSheet(videoPath, outputPath, { every// selection — rather than a `between(t,…)` time window: at 30/60fps a time// window can match several consecutive frames, overfilling the tile before// later boundary times are ever reached.-export async function encodeFileContactSheetAtTimes(videoPath, outputPath, times, { width, height, fps } = {}) {+export async function encodeFileContactSheetAtTimes(videoPath, outputPath, times, { width, height, fps, columns: requestedColumns } = {}) {const ffmpeg = await findFfmpeg();if (!ffmpeg) throw new Error('ffmpeg not found on PATH');if (!Array.isArray(times) || times.length === 0) throw new Error('encodeFileContactSheetAtTimes: no sample times');if (!(fps > 0)) throw new Error('encodeFileContactSheetAtTimes: fps is required');const tileWidth = width && height && width < height ? 240 : 360;- const columns = Math.min(PROOF_COLUMNS, times.length);+ const columns = Math.min(requestedColumns || PROOF_COLUMNS, times.length);const rows = Math.ceil(times.length / columns);// Two very close boundary times can round to the same frame index — the// dedup means the tile gets one fewer real frame than requested (a paddeddiff --git a/server/services/musicVideo/autoReviewJudge.js b/server/services/musicVideo/autoReviewJudge.jsindex 7a4ca4176b..63df294a1b 100644--- a/server/services/musicVideo/autoReviewJudge.js+++ b/server/services/musicVideo/autoReviewJudge.js@@ -88,12 +88,53 @@ export function unplannedFreezes(freezes, sections) {* The reviewer prompt. `sections` and `frameTimes` are on the excerpt's own* timeline (0 = its start), which is also the timeline findings must use.*/-export function buildAutoReviewPrompt({ spanSec, sections = [], frameTimes = [], hasContactSheet = false, concept = null, fps = 24 }) {+// The strip is tiled into 4x3 contact sheets (#9272) so a long edit can be+// sampled densely without exceeding the reviewer's image cap.+export const SHEET_COLUMNS = 4;+export const SHEET_TILES = 12;+export const MAX_REVIEW_IMAGES = 8;+const STRIP_MIN_FRAMES = 12;+const STRIP_MAX_FRAMES = 96;+const SECONDS_PER_FRAME = 4;++/**+ * Song-relative times (on the excerpt's own timeline) to sample: at least one+ * frame per 4s (12–96), and every section's midpoint. The remaining budget is+ * spread evenly. Capped so the tiled sheets plus the boundary sheet stay+ * within MAX_REVIEW_IMAGES.+ */+export function planStripTimes(spanSec, sections = [], { hasContactSheet = false } = {}) {+ if (!(spanSec > 0)) return [];+ const cap = Math.min(STRIP_MAX_FRAMES, SHEET_TILES * (MAX_REVIEW_IMAGES - (hasContactSheet ? 1 : 0)));+ let mids = sections+ .map((s) => (s.startSec + s.endSec) / 2)+ .filter((t) => Number.isFinite(t) && t >= 0 && t <= spanSec);+ // Every section keeps its frame even when that exceeds the 4s-per-frame+ // budget; only the image cap trims sections.+ const budget = Math.min(cap, Math.max(STRIP_MIN_FRAMES, Math.ceil(spanSec / SECONDS_PER_FRAME), mids.length));+ if (mids.length > budget) mids = Array.from({ length: budget }, (_, i) => mids[Math.floor(((i + 0.5) * mids.length) / budget)]);+ // Spend the rest of the budget where the existing samples are sparsest+ // (greedy farthest-point), so fill frames never collide with a midpoint.+ const times = [...mids];+ const grid = Array.from({ length: budget * 4 }, (_, i) => ((i + 0.5) * spanSec) / (budget * 4));+ while (times.length < budget) {+ let best = grid[0];+ let bestGap = -1;+ for (const g of grid) {+ const gap = times.length ? Math.min(...times.map((t) => Math.abs(t - g))) : Infinity;+ if (gap > bestGap) { best = g; bestGap = gap; }+ }+ times.push(best);+ }+ return times.sort((a, b) => a - b).map((t) => Math.round(t * 1000) / 1000);+}++export function buildAutoReviewPrompt({ spanSec, sections = [], frameTimes = [], hasContactSheet = false, tiled = false, concept = null, fps = 24 }) {const sectionLines = sections.map((s, i) => ` ${i + 1}. ${s.startSec.toFixed(2)}s–${s.endSec.toFixed(2)}s — ${s.layer || 'footage'}`).join('\n') || ' (unknown)';const images = [hasContactSheet ? '- Image 1 is a contact sheet: one frame at every cut and title-cue boundary, in time order.' : null,frameTimes.length- ? `- ${hasContactSheet ? 'The remaining images' : 'The images'} are ${frameTimes.length} frames sampled evenly across the continuous excerpt, in order, at ${frameTimes.map((t) => `${t.toFixed(2)}s`).join(', ')}.`+ ? `- ${hasContactSheet ? 'The remaining images' : 'The images'} are ${frameTimes.length} frames sampled across the continuous excerpt (at least one inside every section), in time order, at ${frameTimes.map((t) => `${t.toFixed(2)}s`).join(', ')}.${tiled ? ` They are tiled into contact sheets of up to ${SHEET_TILES} frames (${SHEET_COLUMNS} across, read left to right, top to bottom); each tile is the next time in that list.` : ''}`: null,].filter(Boolean).join('\n');const brief = concept && (isNonBlankStr(concept.prompt) || isNonBlankStr(concept.style))diff --git a/server/services/musicVideo/autoReviewJudge.test.js b/server/services/musicVideo/autoReviewJudge.test.jsnew file mode 100644index 0000000000..bc4b054b65--- /dev/null+++ b/server/services/musicVideo/autoReviewJudge.test.js@@ -0,0 +1,32 @@+import { describe, it, expect } from 'vitest';+import { MAX_REVIEW_IMAGES, SHEET_TILES, buildAutoReviewPrompt, planStripTimes } from './autoReviewJudge.js';++const sections = (n, span) => Array.from({ length: n }, (_, i) => ({ startSec: (i * span) / n, endSec: ((i + 1) * span) / n }));++describe('planStripTimes (#9272)', () => {+ it('samples at least one frame inside every section of a long, many-shot edit', () => {+ const secs = sections(65, 204);+ const times = planStripTimes(204, secs);+ expect(times.length).toBeGreaterThanOrEqual(65);+ for (const s of secs) expect(times.some((t) => t >= s.startSec && t <= s.endSec)).toBe(true);+ expect([...times].sort((a, b) => a - b)).toEqual(times);+ });++ it('keeps a short excerpt at 12 frames', () => {+ expect(planStripTimes(20, sections(5, 20))).toHaveLength(12);+ });++ it('never needs more than the reviewer image cap once tiled', () => {+ for (const hasContactSheet of [false, true]) {+ const times = planStripTimes(900, sections(200, 900), { hasContactSheet });+ expect(Math.ceil(times.length / SHEET_TILES) + (hasContactSheet ? 1 : 0)).toBeLessThanOrEqual(MAX_REVIEW_IMAGES);+ expect(times.every((t) => t >= 0 && t <= 900)).toBe(true);+ }+ });++ it('lists every tile time in the prompt so findings stay timecoded', () => {+ const prompt = buildAutoReviewPrompt({ spanSec: 20, sections: sections(2, 20), frameTimes: [1.5, 12], tiled: true });+ expect(prompt).toContain('1.50s, 12.00s');+ expect(prompt).toContain('contact sheets');+ });+});diff --git a/server/services/musicVideo/autoReviewService.js b/server/services/musicVideo/autoReviewService.jsindex 056e268080..df2c7a8b57 100644--- a/server/services/musicVideo/autoReviewService.js+++ b/server/services/musicVideo/autoReviewService.js@@ -27,10 +27,10 @@ import { existsSync } from 'fs';import { join } from 'path';import { promisify } from 'util';import { ServerError } from '../../lib/errorHandler.js';-import { PATHS } from '../../lib/fileUtils.js';+import { PATHS, ensureDir } from '../../lib/fileUtils.js';import { execFile } from '../../lib/childProcess.js';import { safeChildProcessOptions } from '../../lib/processEnv.js';-import { extractEvaluationFrames, findFfmpeg, findFfprobe, safeUnder } from '../../lib/ffmpeg.js';+import { findFfmpeg, findFfprobe, probeVideoStreamInfo, safeUnder } from '../../lib/ffmpeg.js';import { isVisionCapableCliProvider } from '../../lib/localModelHeuristics.js';import { getProject, mutateProjectRecord } from './projects.js';import { musicVideoEvents } from './events.js';@@ -56,7 +56,10 @@ import {stopAutoReviewOnProject,} from './autoReview.js';import {+ SHEET_COLUMNS,+ SHEET_TILES,buildAutoReviewPrompt,+ planStripTimes,gateAutoReview,parseAutoReviewResponse,parseFreezeIntervals,@@ -66,8 +69,6 @@ import {} from './autoReviewJudge.js';const execFileAsync = promisify(execFile);-// Frames sampled evenly across the continuous excerpt for the reviewer.-const STRIP_FRAMES = 12;// A run takes at most this many steps per advance before yielding — a guard// against a step that fails to change the record looping forever.const MAX_STEPS_PER_ADVANCE = 16;@@ -139,6 +140,26 @@ async function callReviewer(run, prompt, screenshots) {return { text: result.text, used: { ...used, model: result.model || used.model } };}+// Tile the sampled times into 4x3 contact sheets. Returns the sheet files and+// the times actually captured (a failed sheet drops its own times, keeping+// tiles and the prompt's frameTimes aligned).+async function extractStripSheets(excerptPath, jobId, times) {+ const { encodeFileContactSheetAtTimes } = await import('../htmlComposition/encode.js');+ const info = await probeVideoStreamInfo(excerptPath).catch(() => ({}));+ const fps = info.fps > 0 ? info.fps : 24;+ await ensureDir(PATHS.videoThumbnails);+ const sheets = [];+ const captured = [];+ for (let i = 0; i * SHEET_TILES < times.length; i += 1) {+ const chunk = times.slice(i * SHEET_TILES, (i + 1) * SHEET_TILES);+ const out = join(PATHS.videoThumbnails, `${jobId}-s${i + 1}.jpg`);+ const ok = await encodeFileContactSheetAtTimes(excerptPath, out, chunk, { width: info.width, height: info.height, fps, columns: SHEET_COLUMNS })+ .then(() => true, () => false);+ if (ok && existsSync(out)) { sheets.push(out); captured.push(...chunk); }+ }+ return { sheets, captured };+}+/** Review one rendered draft. Never throws — a failed look is an inconclusive review. */async function reviewDraft(project, run, excerpt) {const excerptPath = safeUnder(PATHS.videos, excerpt.filename || '');@@ -151,19 +172,18 @@ async function reviewDraft(project, run, excerpt) {}const analysis = await analyzeContinuousExcerpt(excerptPath, spanSec, sections).catch((err) => ({ ok: false, error: err.message }));const attemptN = run.attempts.length;- const stripNames = await extractEvaluationFrames(excerptPath, `mvar-${short(run.id)}-a${attemptN}`, STRIP_FRAMES).catch(() => []);- const strip = stripNames.map((name) => join(PATHS.videoThumbnails, name)).filter((p) => existsSync(p));const sheet = excerpt.contactSheetFilename ? safeUnder(PATHS.videoThumbnails, excerpt.contactSheetFilename) : null;const hasSheet = !!sheet && existsSync(sheet);+ const planned = planStripTimes(spanSec, sections, { hasContactSheet: hasSheet });+ const { sheets: strip, captured: frameTimes } = await extractStripSheets(excerptPath, `mvar-${short(run.id)}-a${attemptN}`, planned).catch(() => ({ sheets: [], captured: [] }));const screenshots = [...(hasSheet ? [sheet] : []), ...strip];- const frameTimes = strip.map((_, i) => (strip.length > 1 ? (i * spanSec) / (strip.length - 1) : 0));- const evidence = { boundaryFrames: hasSheet ? 1 : 0, continuousFrames: strip.length };+ const evidence = { boundaryFrames: hasSheet ? 1 : 0, continuousFrames: frameTimes.length };let parsed = null;let reviewerError = null;let used = { providerId: run.reviewer.providerId, model: run.reviewer.model };if (screenshots.length) {- const prompt = buildAutoReviewPrompt({ spanSec, sections, frameTimes, hasContactSheet: hasSheet, concept: project.concept });+ const prompt = buildAutoReviewPrompt({ spanSec, sections, frameTimes, hasContactSheet: hasSheet, tiled: true, concept: project.concept });try {const reply = await callReviewer(run, prompt, screenshots);used = reply.used;