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
address review (claude,codex): serialize video-history writes, robust download output detection
[._.]/ Adam Eivy0f6f9c071b9e
diff --git a/server/services/videoDownload.js b/server/services/videoDownload.jsindex 95d5f82865..4582e5591e 100644--- a/server/services/videoDownload.js+++ b/server/services/videoDownload.js@@ -17,7 +17,6 @@*/import { spawn } from 'child_process';-import { existsSync } from 'fs';import { readdir, unlink } from 'fs/promises';import { join, dirname } from 'path';import { randomUUID } from 'crypto';@@ -27,7 +26,7 @@ import { findFfmpeg, generateThumbnail, probeVideoDuration } from '../lib/ffmpegimport { findYtDlp } from '../lib/ytdlp.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../lib/sseUtils.js';import { safeChildProcessEnv } from '../lib/processEnv.js';-import { loadHistory, saveHistory } from './videoGen/history.js';+import { loadHistory, mutateVideoHistory } from './videoGen/history.js';import { deleteHistoryItem } from './videoGen/local.js';import { videoGenEvents } from './videoGen/events.js';@@ -114,6 +113,45 @@ async function cleanupDownloadFiles(jobId) {);}+// Locate the final produced file for a job. yt-dlp writes intermediate streams+// as `downloaded-<id>.f<code>.<ext>` and a `.part`/`.ytdl` in progress, then+// merges/remuxes to a single `downloaded-<id>.<ext>` and deletes the rest. We do+// NOT hardcode `.mp4`: the format fallback chain can land a single-file webm/mkv+// (VP9/AV1) that `--merge-output-format`/`--remux-video mp4` only converts on a+// best-effort basis, so assuming `.mp4` would miss a perfectly-good download and+// then delete it as a "failure". Prefer an exact `.mp4`, else the lone remaining+// non-intermediate file. Returns the basename or null when nothing was produced.+export async function findDownloadedFile(jobId, dir = PATHS.videos) {+ const prefix = `${FILENAME_PREFIX}${jobId}.`;+ const entries = await readdir(dir).catch(() => []);+ const candidates = entries.filter((n) =>+ n.startsWith(prefix)+ && !n.endsWith('.part')+ && !n.endsWith('.ytdl')+ && !/\.f\d+\.[^.]+$/.test(n), // format-fragment intermediates (.f137.mp4)+ );+ return candidates.find((n) => n === `${prefix}mp4`) || candidates[0] || null;+}++// Build the `source: 'download'` video-history entry. Pure + exported so the+// load-bearing shape (the fields normalizeVideo, mediaAssetIndex videoToRow, and+// deleteHistoryItem all depend on) is pinned by a unit test rather than only+// implicitly exercised by the spawn path. `id === jobId` so the live media-index+// `completed` hook loads it by generationId AND deleteHistoryItem's `${id}.jpg`+// thumbnail + `${filename}` cleanup both resolve.+export function buildDownloadHistoryEntry({ jobId, filename, thumbnail, durationSec, title, sourceUrl }) {+ return {+ id: jobId,+ filename,+ thumbnail,+ createdAt: new Date().toISOString(),+ source: 'download',+ sourceUrl,+ title: title || 'Downloaded video',+ ...(durationSec != null ? { durationSec } : {}),+ };+}+/*** Kick off a full-video download. Returns `{ jobId }` immediately; the download* runs detached and streams progress over SSE. Terminal frames:@@ -128,10 +166,9 @@ export async function startVideoDownload(url) {if (!ffmpeg) throw new ServerError('ffmpeg not found on PATH', { status: 500, code: 'FFMPEG_MISSING' });const jobId = randomUUID();- const filename = `${FILENAME_PREFIX}${jobId}.mp4`;- const outPath = join(PATHS.videos, filename);- // yt-dlp writes intermediate streams as `downloaded-<uuid>.<ext>` then merges- // to .mp4; --merge-output-format mp4 makes the final container known up front.+ // The final filename/extension isn't known until the download resolves (the+ // format fallback can produce a non-mp4 single file), so it's detected from+ // disk on success via findDownloadedFile rather than assumed here.const outTemplate = join(PATHS.videos, `${FILENAME_PREFIX}${jobId}.%(ext)s`);const job = { id: jobId, status: 'running', clients: [], process: null };@@ -146,6 +183,10 @@ export async function startVideoDownload(url) {// broad browser playback; fall back to best single-file mp4, then best.'-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best','--merge-output-format', 'mp4',+ // Best-effort remux a single-file/non-mp4 result into an mp4 container so+ // browser playback is broad; when the codec can't be remuxed losslessly+ // yt-dlp leaves the native container, which findDownloadedFile handles.+ '--remux-video', 'mp4','--no-playlist','--ffmpeg-location', dirname(ffmpeg),'--newline',@@ -158,7 +199,13 @@ export async function startVideoDownload(url) {'--no-simulate','--progress','--max-filesize', String(VIDEO_DOWNLOAD_MAX_BYTES),+ // Two --match-filters are OR'd by yt-dlp: bound KNOWN-duration videos to+ // the cap, but let a post whose duration can't be resolved pre-download+ // (common on x.com/Twitter) through rather than silently rejecting it —+ // the byte cap above still bounds it. A known video longer than the cap+ // matches neither filter and is skipped.'--match-filters', `duration <= ${VIDEO_DOWNLOAD_MAX_DURATION_SEC}`,+ '--match-filters', '!duration','-o', outTemplate,url,];@@ -205,18 +252,21 @@ export async function startVideoDownload(url) {await cleanupDownloadFiles(jobId);return;}- if (exit.code !== 0 || !existsSync(outPath)) {+ const produced = await findDownloadedFile(jobId);+ if (exit.code !== 0 || !produced) {// A --match-filters/--max-filesize rejection exits 0 with no output// file (yt-dlp treats a filtered-out video as "nothing to do") — and- // --print suppresses the specific reason, so name the two known bounds.+ // --print suppresses the specific reason, so name the known bounds.// x.com/Twitter downloads also fail here on login-walled/rate-limited// content; surface a clear message rather than a bare exit code.const reason = exit.code === 0- ? `no video was produced — it may be longer than ${VIDEO_DOWNLOAD_MAX_DURATION_SEC / 60} minutes or larger than ${Math.round(VIDEO_DOWNLOAD_MAX_BYTES / 1024 / 1024 / 1024)}GB, or (for x.com) login-walled or rate-limited`+ ? `no video was produced — it may be longer than ${VIDEO_DOWNLOAD_MAX_DURATION_SEC / 60} minutes or larger than ${Math.round(VIDEO_DOWNLOAD_MAX_BYTES / 1024 / 1024 / 1024)}GB, or (for x.com) login-walled, rate-limited, or otherwise unavailable`: (exit.reason || `yt-dlp exited ${exit.code}`);throw new Error(reason);}+ const filename = produced;+ const outPath = join(PATHS.videos, filename);broadcastSse(job, { type: 'progress', percent: 100, stage: 'finalizing' });const [thumbnail, durationSec] = await Promise.all([generateThumbnail(outPath, jobId),@@ -225,22 +275,10 @@ export async function startVideoDownload(url) {// Derived, not a generation: a `source: 'download'` video-history entry so// the existing videoToRow / onVideoCompleted media-index path and the- // gallery pick it up unmodified. `id === jobId` so the shared- // deleteHistoryItem cleans the file + `${jobId}.jpg` thumbnail.- const entry = {- id: jobId,- filename,- thumbnail,- createdAt: new Date().toISOString(),- mode: 'download',- source: 'download',- sourceUrl: url,- title: title || 'Downloaded video',- ...(durationSec != null ? { durationSec } : {}),- };- const history = await loadHistory().catch(() => []);- history.unshift(entry);- await saveHistory(history);+ // gallery pick it up unmodified. Serialized read-modify-write so two+ // near-simultaneous downloads can't clobber each other's entry.+ const entry = buildDownloadHistoryEntry({ jobId, filename, thumbnail, durationSec, title, sourceUrl: url });+ await mutateVideoHistory((history) => { history.unshift(entry); return history; });// Let the live media-asset index hook index this immediately (it loads// history by generationId and upserts one row). Reconcile is the backstop.diff --git a/server/services/videoDownload.test.js b/server/services/videoDownload.test.jsindex c8194b5209..ce38444346 100644--- a/server/services/videoDownload.test.js+++ b/server/services/videoDownload.test.js@@ -1,4 +1,4 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';// Mock the history store so listDownloads/deleteDownload can be exercised// without touching disk, and mock deleteHistoryItem so deleteDownload's@@ -14,11 +14,16 @@ vi.mock('./videoGen/history.js', () => ({vi.mock('./videoGen/local.js', () => ({ deleteHistoryItem }));vi.mock('./videoGen/events.js', () => ({ videoGenEvents: { emit: vi.fn() } }));+import { mkdtemp, writeFile, rm } from 'fs/promises';+import { join } from 'path';+import { tmpdir } from 'os';import {SUPPORTED_VIDEO_URL_RE,assertSupportedVideoUrl,listDownloads,deleteDownload,+ buildDownloadHistoryEntry,+ findDownloadedFile,} from './videoDownload.js';describe('videoDownload URL allowlist', () => {@@ -83,3 +88,66 @@ describe('listDownloads / deleteDownload', () => {await expect(deleteDownload('nope')).rejects.toMatchObject({ status: 404 });});});++describe('buildDownloadHistoryEntry (contract shape)', () => {+ it('pins the fields normalizeVideo / videoToRow / deleteHistoryItem depend on', () => {+ const entry = buildDownloadHistoryEntry({+ jobId: 'job-1',+ filename: 'downloaded-job-1.mp4',+ thumbnail: 'job-1.jpg',+ durationSec: 42,+ title: 'A Clip',+ sourceUrl: 'https://youtu.be/abc123XYZ',+ });+ // id === jobId so the media-index completed hook + deleteHistoryItem resolve;+ // thumbnail/filename are what deleteHistoryItem unlinks.+ expect(entry.id).toBe('job-1');+ expect(entry.filename).toBe('downloaded-job-1.mp4');+ expect(entry.thumbnail).toBe('job-1.jpg');+ expect(entry.source).toBe('download');+ expect(entry.sourceUrl).toBe('https://youtu.be/abc123XYZ');+ expect(entry.title).toBe('A Clip');+ expect(entry.durationSec).toBe(42);+ expect(typeof entry.createdAt).toBe('string');+ // No `mode` field — `source` is the marker; a bogus mode would confuse the+ // gallery Remix path.+ expect(entry).not.toHaveProperty('mode');+ });++ it('defaults a missing title and omits durationSec when unknown', () => {+ const entry = buildDownloadHistoryEntry({+ jobId: 'j', filename: 'downloaded-j.mp4', thumbnail: null, durationSec: null, title: '', sourceUrl: 'u',+ });+ expect(entry.title).toBe('Downloaded video');+ expect(entry).not.toHaveProperty('durationSec');+ });+});++describe('findDownloadedFile (robust output detection)', () => {+ let dir;+ beforeEach(async () => { dir = await mkdtemp(join(tmpdir(), 'viddl-')); });+ afterEach(async () => { await rm(dir, { recursive: true, force: true }); });++ it('prefers an exact .mp4 over other candidates', async () => {+ await writeFile(join(dir, 'downloaded-x.mp4'), 'v');+ await writeFile(join(dir, 'downloaded-x.webm'), 'v');+ expect(await findDownloadedFile('x', dir)).toBe('downloaded-x.mp4');+ });++ it('finds a non-mp4 single-file result (the .mp4-assumption bug)', async () => {+ await writeFile(join(dir, 'downloaded-y.webm'), 'v');+ expect(await findDownloadedFile('y', dir)).toBe('downloaded-y.webm');+ });++ it('ignores in-progress and format-fragment intermediates', async () => {+ await writeFile(join(dir, 'downloaded-z.f137.mp4'), 'v'); // fragment+ await writeFile(join(dir, 'downloaded-z.mp4.part'), 'v'); // partial+ await writeFile(join(dir, 'downloaded-z.webm.ytdl'), 'v'); // sidecar+ expect(await findDownloadedFile('z', dir)).toBeNull();+ });++ it('does not match a different job id', async () => {+ await writeFile(join(dir, 'downloaded-other.mp4'), 'v');+ expect(await findDownloadedFile('mine', dir)).toBeNull();+ });+});diff --git a/server/services/videoGen/history.js b/server/services/videoGen/history.jsindex cf4302252e..5a4d8f9003 100644--- a/server/services/videoGen/history.js+++ b/server/services/videoGen/history.js@@ -13,3 +13,29 @@ const HISTORY_FILE = join(PATHS.data, 'video-history.json');export const loadHistory = () => readJSONFile(HISTORY_FILE, []);export const saveHistory = (h) => atomicWrite(HISTORY_FILE, h);++// Serialized read-modify-write for the shared history file. `loadHistory` ++// mutate + `saveHistory` is not atomic on its own, so two write paths that+// finish near-simultaneously (e.g. two out-of-queue video downloads completing+// from two browser tabs — see server/services/videoDownload.js) both read the+// same stale array and the later save clobbers the earlier's new entry, leaving+// an orphaned file that's absent from the list/media-index and undeletable. A+// module-level promise tail collapses concurrent mutations to a single writer+// per file (the `issueWriteTail` pattern in CLAUDE.md). `mutator(list)` receives+// the freshest persisted array and returns the array to persist (return the+// same reference after mutating it in place, or a new array). Any writer that+// can race another on this file should route through here.+let historyWriteTail = Promise.resolve();+export function mutateVideoHistory(mutator) {+ const run = historyWriteTail.then(async () => {+ const history = await loadHistory();+ const next = await mutator(Array.isArray(history) ? history : []);+ const toSave = Array.isArray(next) ? next : history;+ await saveHistory(toSave);+ return toSave;+ });+ // Keep the tail alive even if this mutation rejects, so one failure doesn't+ // wedge every subsequent write behind a permanently-rejected promise.+ historyWriteTail = run.then(() => {}, () => {});+ return run;+}diff --git a/server/services/videoGen/history.test.js b/server/services/videoGen/history.test.jsnew file mode 100644index 0000000000..1ff876c878--- /dev/null+++ b/server/services/videoGen/history.test.js@@ -0,0 +1,43 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// In-memory store standing in for data/video-history.json so the serialization+// test never touches disk. readJSONFile returns a COPY (a real read wouldn't+// hand back the live array) after a microtask delay to widen the race window;+// atomicWrite replaces the store.+const store = { data: [] };+vi.mock('../../lib/fileUtils.js', () => ({+ PATHS: { data: '/tmp/videohistory-test' },+ readJSONFile: vi.fn(async () => {+ await new Promise((r) => setTimeout(r, 5));+ return store.data.slice();+ }),+ atomicWrite: vi.fn(async (_file, value) => { store.data = value; }),+}));++import { mutateVideoHistory } from './history.js';++describe('mutateVideoHistory serialization', () => {+ beforeEach(() => { store.data = []; });++ it('does not lose an entry when two mutations run concurrently', async () => {+ // Without the write tail, both reads see the empty array and the later save+ // clobbers the earlier entry — the store would end with one item, not two.+ await Promise.all([+ mutateVideoHistory((h) => { h.unshift({ id: 'a' }); return h; }),+ mutateVideoHistory((h) => { h.unshift({ id: 'b' }); return h; }),+ ]);+ expect(store.data.map((x) => x.id).sort()).toEqual(['a', 'b']);+ });++ it('applies mutations in call order (later mutation sees earlier writes)', async () => {+ await mutateVideoHistory((h) => { h.unshift({ id: '1' }); return h; });+ const result = await mutateVideoHistory((h) => { h.unshift({ id: '2' }); return h; });+ expect(result.map((x) => x.id)).toEqual(['2', '1']);+ });++ it('a rejecting mutation does not wedge subsequent writes', async () => {+ await expect(mutateVideoHistory(() => { throw new Error('boom'); })).rejects.toThrow('boom');+ await mutateVideoHistory((h) => { h.unshift({ id: 'after' }); return h; });+ expect(store.data.map((x) => x.id)).toEqual(['after']);+ });+});