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: time out stalled ffmpeg on thumbnail, frame-extraction and collage paths (#12965)
[._.]/ Adam Eivy262097a8599d
diff --git a/server/lib/README.md b/server/lib/README.mdindex e6207375b6..cb18486afb 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -468,7 +468,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `upgradeFallback.js` | `installUpgradeFallback(server, options)` bounds the lifetime of unclaimed HTTP upgrade requests (ending and destroying them after `timeoutMs`, default 1000ms) to replace engine.io's `destroyUpgrade` timer so reverse proxies with slow upstreams (e.g. Eidoverse `/ws`) can complete handshakes without being cut short (#12069). Exempts claimed upgrades (`socket.portosUpgradeClaimed = true` via `markUpgradeClaimed(socket)`) and requests matching Engine.IO's listener on the server. || `httpCompression.js` | `httpCompression` negotiates Brotli/gzip for API and static responses while preserving streaming, ranges, existing encodings, and `no-transform`. || `execGit.js` | `execGit(args, cwd, options)` and `execGitSafe(args, cwd, options)` shared process boundary for Git operations, worktrees, and `services/forgeAuth.js` credential resolution. The safe variant converts rejections into `{ exitCode: 1, stdout: '', stderr }`; `services/git.js` re-exports both for compatibility. `cwd` is REQUIRED — it rejects on a missing/blank one rather than letting `spawn` fall back to `process.cwd()` and run git against PortOS's own checkout (#4554). |-| `ffmpeg.js` | `probeMediaTags` reads container/stream tags, returning null when inspection fails. Shared ffmpeg helpers (videoGen + videoTimeline). `vfrSyncArgs(bin)` probes/caches supported VFR output flags per binary (fps_mode on current builds, vsync on older builds); inconclusive probes stay uncached. `probeVideoGeometry(videoPath)` measures a finished clip's `{ width, height, fps, numFrames, durationSec }` (null when any axis is unreadable) for hosted renders that record no frame count. `generateThumbnail(videoPath, jobId, { atSec } = {})` accepts a clamped poster seek while preserving the single-clip default. Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `buildExtendSpliceArgs({sourcePath, generatedPath, outPath, keepFrames, newStartFrame, width, height, fps, audio, sourceAudioPath, masterOutPath})` is the plain-Extend counterpart: source frames `[0, keep)` + render frames from `newStartFrame`, one encode, audio crossfaded (~40 ms linear) at the seam; `sourceAudioPath` swaps the source span's audio for a lossless master and `masterOutPath` also writes the mix as a 24-bit FLAC master, so the delivered AAC is encoded once from PCM. Its stream-copy sibling is `buildExtendNewSpanArgs` (encode only the render's new span) + `buildExtendConcatList` + `buildExtendCopyArgs` (join it to the untouched source with `-c:v copy`); `probeVideoCodecSignature` gates it and `videoFrameHashes` (per-frame MD5) proves the join before anything is replaced; `audioFingerprint` / `sealAudioMaster` / `readAudioMasterFingerprint` bind a master to the exact decoded soundtrack it was mixed for so a replaced soundtrack invalidates it — driven by `services/videoGen/extendSplice.js`. `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. `installEncodedVideo(tmpPath, targetPath, label)` is the shared in-place install: move the original aside to a `.bak` on Windows (where `fs.rename` refuses an existing destination), rename the new file over it, and restore the backup — plus unlink the temp — on any failure, returning `{ok:true,outPath}` / `{ok:false,reason}` so the worst case is "skipped", never "the video is gone". Use it for EVERY replace-a-video-with-its-re-encode path; `pipeline/audioMux.js` is the out-of-module caller. `edgeFadeFilter(durationSec)` is the `-af` fade-in/fade-out fragment a mid-song clip (a social cut) appends to its trim. Loudness mastering (#10249): `MASTER_LOUDNESS` (-14 LUFS / -1.5 dBTP / LRA 11), `planLoudnessMaster` (measure then build the linear apply filter; throws on a silent source), `reportMasteredLoudness` (post-encode before/after numbers). |+| `ffmpeg.js` | `runFfmpegProcess({ bin, args, signal, timeoutMs })` — `timeoutMs` (opt-in; `FFMPEG_FRAME_TIMEOUT_MS` for one frame, `FFMPEG_SCAN_TIMEOUT_MS` for a full-file pass) SIGTERMs then SIGKILLs a stalled child and resolves `{ ok:false, reason:'timed out after <n>s' }`; the `signal` abort path escalates the same way. Long encodes pass no ceiling. `probeMediaTags` reads container/stream tags, returning null when inspection fails. Shared ffmpeg helpers (videoGen + videoTimeline). `vfrSyncArgs(bin)` probes/caches supported VFR output flags per binary (fps_mode on current builds, vsync on older builds); inconclusive probes stay uncached. `probeVideoGeometry(videoPath)` measures a finished clip's `{ width, height, fps, numFrames, durationSec }` (null when any axis is unreadable) for hosted renders that record no frame count. `generateThumbnail(videoPath, jobId, { atSec } = {})` accepts a clamped poster seek while preserving the single-clip default. Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `buildExtendSpliceArgs({sourcePath, generatedPath, outPath, keepFrames, newStartFrame, width, height, fps, audio, sourceAudioPath, masterOutPath})` is the plain-Extend counterpart: source frames `[0, keep)` + render frames from `newStartFrame`, one encode, audio crossfaded (~40 ms linear) at the seam; `sourceAudioPath` swaps the source span's audio for a lossless master and `masterOutPath` also writes the mix as a 24-bit FLAC master, so the delivered AAC is encoded once from PCM. Its stream-copy sibling is `buildExtendNewSpanArgs` (encode only the render's new span) + `buildExtendConcatList` + `buildExtendCopyArgs` (join it to the untouched source with `-c:v copy`); `probeVideoCodecSignature` gates it and `videoFrameHashes` (per-frame MD5) proves the join before anything is replaced; `audioFingerprint` / `sealAudioMaster` / `readAudioMasterFingerprint` bind a master to the exact decoded soundtrack it was mixed for so a replaced soundtrack invalidates it — driven by `services/videoGen/extendSplice.js`. `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. `installEncodedVideo(tmpPath, targetPath, label)` is the shared in-place install: move the original aside to a `.bak` on Windows (where `fs.rename` refuses an existing destination), rename the new file over it, and restore the backup — plus unlink the temp — on any failure, returning `{ok:true,outPath}` / `{ok:false,reason}` so the worst case is "skipped", never "the video is gone". Use it for EVERY replace-a-video-with-its-re-encode path; `pipeline/audioMux.js` is the out-of-module caller. `edgeFadeFilter(durationSec)` is the `-af` fade-in/fade-out fragment a mid-song clip (a social cut) appends to its trim. Loudness mastering (#10249): `MASTER_LOUDNESS` (-14 LUFS / -1.5 dBTP / LRA 11), `planLoudnessMaster` (measure then build the linear apply filter; throws on a silent source), `reportMasteredLoudness` (post-encode before/after numbers). || `ffmpegFilterGraph.js` | `filterGraphViaFile(bin, args, path)` moves a `-filter_complex` graph over `FILTER_GRAPH_ARG_LIMIT` into a file (`-/filter_complex`, or `-filter_complex_script` before ffmpeg 7), since Linux and Windows cap argument length. Used by the music video render and excerpt encodes. || `forgeAccessErrors.js` | `isForgeNoAccessError(err)` / `isForgeNoAccessMessage(text)` / `logForgeNoAccessOnce(scope, repoSpec, detail)` / `forgeNoAccessRemedy(repoSpec)` — tells a PERMANENT `gh` no-access 404 (`Could not resolve to a Repository`, `HTTP 404`) apart from a transient blip. `execGh` stamps `ghNoAccess` on the rejection and keeps it OUT of the consecutive-failure backoff (which caps at 15 min and then re-fires forever), and the polling jobs (`branchReconcile`, `prWatcher`) narrate it exactly once per scope+repo per process with a remedy line instead of once per tick. `__resetForgeNoAccessLog()` is the test seam. || `forkHead.js` | `normalizeForkHead(value)` / `forkRemoteName(ownerLogin)` / `resolveTaskForkHead(metadata)` — the validated `{remoteUrl, ownerLogin}` address of a cross-repository PR's head branch, which has no `origin/<branch>` to attach to. Fail-closed: anything that isn't a usable pair (or that starts with `-`, which git would read as an option) is `null`, so every caller falls back to origin-only behavior instead of guessing. `forkRemoteName` is the deterministic `fork-<owner>` remote name that makes a re-attach reuse the remote it already added. Shared by `appPullRequests.js` (produces), `agentWorktreeCleanup.js`/`prRemediationFollowUp.js` (persist in task metadata), `agentWorkspacePrep.js` (threads), and `worktreeManager.js` (consumes — it has no forge client of its own). `resolveTaskForkHead` is the single reader of the generic `forkHead` task-metadata key, the fork-side counterpart to `taskTargetBranch.js`. |diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.jsindex d234c902e3..417205f072 100644--- a/server/lib/ffmpeg.js+++ b/server/lib/ffmpeg.js@@ -94,12 +94,24 @@ export const vfrSyncArgs = async (bin) => {* - `returnStderr`: when true a successful result also carries the captured* stderr tail as `stderr` (loudness measurement reads its JSON from there).*+ * - `timeoutMs`: optional wall-clock ceiling for a stalled ffmpeg (unreadable+ * input, evicted cloud file, dead network mount). On expiry the child gets+ * SIGTERM, then SIGKILL after `FFMPEG_KILL_GRACE_MS`, and the result is+ * `{ ok: false, reason: 'timed out after <n>s' }`. No default: long encodes+ * rely on their caller `signal` instead. The `signal` abort path escalates+ * to SIGKILL the same way.+ ** Returns `{ ok: true }` on exit code 0, otherwise `{ ok: false, reason }`* where `reason` is a short human-readable string suitable for logging or* surfacing in a UI error. Spawn errors are translated into `reason: 'spawn* failed: …'` so callers don't need a separate `.on('error', …)` handler.*/-export function runFfmpegProcess({ bin, args, signal, stderrTailBytes = 2000, returnStderr = false } = {}) {+export const FFMPEG_KILL_GRACE_MS = 5000;+// Ceilings for bounded work: one frame/poster, and a single full-file pass.+export const FFMPEG_FRAME_TIMEOUT_MS = 2 * 60 * 1000;+export const FFMPEG_SCAN_TIMEOUT_MS = 15 * 60 * 1000;++export function runFfmpegProcess({ bin, args, signal, timeoutMs, stderrTailBytes = 2000, returnStderr = false } = {}) {if (!bin || typeof bin !== 'string') {return Promise.resolve({ ok: false, reason: 'invalid ffmpeg binary' });}@@ -122,20 +134,47 @@ export function runFfmpegProcess({ bin, args, signal, stderrTailBytes = 2000, re// removeEventListener on normal completion so a signal reused across many// ffmpeg calls (one per render queue) doesn't accumulate dozens of unfired// listeners — the leak the audioMux audit flagged.+ let closed = false;+ let timedOut = false;+ let timeoutTimer = null;+ let killTimer = null;+ // SIGTERM first; a child wedged in uninterruptible IO may ignore it, so+ // follow with SIGKILL unless it has closed by then.+ const terminate = () => {+ proc.kill('SIGTERM');+ if (killTimer) return;+ killTimer = setTimeout(() => { if (!closed) proc.kill('SIGKILL'); }, FFMPEG_KILL_GRACE_MS);+ killTimer.unref?.();+ };+ const clearTimers = () => {+ closed = true;+ clearTimeout(timeoutTimer);+ clearTimeout(killTimer);+ };+ if (Number.isFinite(timeoutMs) && timeoutMs > 0) {+ timeoutTimer = setTimeout(() => { timedOut = true; terminate(); }, timeoutMs);+ timeoutTimer.unref?.();+ }let onAbort = null;if (signal) {- onAbort = () => proc.kill('SIGTERM');+ onAbort = terminate;signal.addEventListener('abort', onAbort, { once: true });}const cleanupSignal = () => {if (signal && onAbort) signal.removeEventListener('abort', onAbort);};proc.on('error', (err) => {+ clearTimers();cleanupSignal();resolve({ ok: false, reason: `spawn failed: ${err.message}` });});proc.on('close', (code, sig) => {+ clearTimers();cleanupSignal();+ if (timedOut) {+ resolve({ ok: false, reason: `timed out after ${Math.round(timeoutMs / 1000)}s` });+ return;+ }if (sig === 'SIGTERM' || sig === 'SIGKILL') {resolve({ ok: false, reason: `cancelled (${sig})` });return;@@ -251,6 +290,7 @@ export const generateThumbnail = async (videoPath, jobId, { atSec } = {}) => {bin: ffmpeg,args: ['-ss', seekSec.toFixed(Number.isFinite(atSec) ? 6 : 2), '-i', videoPath, '-vframes', '1', '-q:v', '5', '-y', thumbPath],stderrTailBytes: 0,+ timeoutMs: FFMPEG_FRAME_TIMEOUT_MS,});if (!result.ok && result.reason?.startsWith('spawn failed: ')) {console.log(`⚠️ ffmpeg thumbnail failed to spawn: ${result.reason.slice('spawn failed: '.length)}`);@@ -361,6 +401,7 @@ export const videoFrameHashes = async (videoPath) => {const run = await runFfmpegProcess({bin: ffmpeg,args: ['-v', 'error', '-xerror', '-i', videoPath, '-map', '0:v:0', '-f', 'framemd5', '-y', hashPath],+ timeoutMs: FFMPEG_SCAN_TIMEOUT_MS,});if (!run.ok) return null;const rows = (await readFile(hashPath, 'utf8')).split(/\r?\n/).filter((line) => line && !line.startsWith('#'));@@ -509,6 +550,7 @@ export const extractEvaluationFrames = async (videoPath, jobId, count = 5) => {bin: ffmpeg,args: ['-i', videoPath, '-vf', `select='${selectExpr}'`, ...await vfrSyncArgs(ffmpeg), '-q:v', '5', '-y', outPattern],stderrTailBytes: 0,+ timeoutMs: FFMPEG_SCAN_TIMEOUT_MS,});if (!result.ok && result.reason?.startsWith('spawn failed: ')) {console.log(`⚠️ ffmpeg multi-frame extract failed to spawn: ${result.reason.slice('spawn failed: '.length)}`);diff --git a/server/lib/ffmpeg.timeout.test.js b/server/lib/ffmpeg.timeout.test.jsnew file mode 100644index 0000000000..3a6bbbbf27--- /dev/null+++ b/server/lib/ffmpeg.timeout.test.js@@ -0,0 +1,70 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { EventEmitter } from 'events';++const spawnMock = vi.hoisted(() => vi.fn());+vi.mock('./childProcess.js', async (orig) => ({ ...(await orig()), spawn: spawnMock }));++import { runFfmpegProcess, FFMPEG_KILL_GRACE_MS } from './ffmpeg.js';++// A child that records kills and only closes when told (a wedged ffmpeg).+function stuckChild({ honorsSigterm = false } = {}) {+ const child = new EventEmitter();+ child.stderr = new EventEmitter();+ child.signals = [];+ child.kill = vi.fn((sig) => {+ child.signals.push(sig);+ if (sig === 'SIGKILL' || (sig === 'SIGTERM' && honorsSigterm)) {+ queueMicrotask(() => child.emit('close', null, sig));+ }+ return true;+ });+ return child;+}++describe('runFfmpegProcess stall handling', () => {+ beforeEach(() => { vi.useFakeTimers(); spawnMock.mockReset(); });+ afterEach(() => { vi.useRealTimers(); });++ it('times out a child that ignores SIGTERM and escalates to SIGKILL', async () => {+ const child = stuckChild();+ spawnMock.mockReturnValue(child);+ const p = runFfmpegProcess({ bin: 'ffmpeg', args: [], timeoutMs: 30000 });+ await vi.advanceTimersByTimeAsync(30000);+ expect(child.signals).toEqual(['SIGTERM']);+ await vi.advanceTimersByTimeAsync(FFMPEG_KILL_GRACE_MS);+ expect(child.signals).toEqual(['SIGTERM', 'SIGKILL']);+ expect(await p).toEqual({ ok: false, reason: 'timed out after 30s' });+ });++ it('skips SIGKILL when the child exits on SIGTERM', async () => {+ const child = stuckChild({ honorsSigterm: true });+ spawnMock.mockReturnValue(child);+ const p = runFfmpegProcess({ bin: 'ffmpeg', args: [], timeoutMs: 1000 });+ await vi.advanceTimersByTimeAsync(1000);+ expect(await p).toEqual({ ok: false, reason: 'timed out after 1s' });+ await vi.advanceTimersByTimeAsync(FFMPEG_KILL_GRACE_MS * 2);+ expect(child.signals).toEqual(['SIGTERM']);+ });++ it('does not time out a child that finishes in time', async () => {+ const child = stuckChild();+ spawnMock.mockReturnValue(child);+ const p = runFfmpegProcess({ bin: 'ffmpeg', args: [], timeoutMs: 1000 });+ child.emit('close', 0, null);+ expect(await p).toEqual({ ok: true });+ await vi.advanceTimersByTimeAsync(10000);+ expect(child.signals).toEqual([]);+ });++ it('escalates the abort-signal path to SIGKILL', async () => {+ const child = stuckChild();+ spawnMock.mockReturnValue(child);+ const ac = new AbortController();+ const p = runFfmpegProcess({ bin: 'ffmpeg', args: [], signal: ac.signal });+ ac.abort();+ expect(child.signals).toEqual(['SIGTERM']);+ await vi.advanceTimersByTimeAsync(FFMPEG_KILL_GRACE_MS);+ expect(child.signals).toEqual(['SIGTERM', 'SIGKILL']);+ expect(await p).toEqual({ ok: false, reason: 'cancelled (SIGKILL)' });+ });+});diff --git a/server/services/codeAnimation/referenceVideo.js b/server/services/codeAnimation/referenceVideo.jsindex 8695802158..cda27cce40 100644--- a/server/services/codeAnimation/referenceVideo.js+++ b/server/services/codeAnimation/referenceVideo.js@@ -10,7 +10,7 @@ import { readFile, stat, writeFile } from 'fs/promises';import { join } from 'path';import { ServerError } from '../../lib/errorHandler.js';import { ensureDir } from '../../lib/fileCore.js';-import { findFfmpeg, probeVideoDuration, runFfmpegProcess } from '../../lib/ffmpeg.js';+import { FFMPEG_FRAME_TIMEOUT_MS, FFMPEG_SCAN_TIMEOUT_MS, findFfmpeg, probeVideoDuration, runFfmpegProcess } from '../../lib/ffmpeg.js';import { PATHS } from '../../lib/paths.js';import { makePathResolver } from '../../lib/pathSafety.js';import { trimTo } from '../../lib/textUtils.js';@@ -41,6 +41,7 @@ async function detectCuts(ffmpeg, videoPath) {args: ['-hide_banner', '-nostats', '-loglevel', 'info', '-i', videoPath, '-an', '-vf', `scale=320:-2,select='gt(scene,${CUT_THRESHOLD})',showinfo`, '-f', 'null', '-'],returnStderr: true,stderrTailBytes: 400000,+ timeoutMs: FFMPEG_SCAN_TIMEOUT_MS,});// null, not [], so a failed pass never reads as "no cuts".return result.ok ? parseCutTimes(result.stderr) : null;@@ -50,6 +51,7 @@ async function extractKeyframe(ffmpeg, videoPath, atSec, outputPath) {const result = await runFfmpegProcess({bin: ffmpeg,args: ['-hide_banner', '-loglevel', 'error', '-ss', atSec.toFixed(2), '-i', videoPath, '-frames:v', '1', '-vf', 'scale=1280:-2', '-q:v', '3', '-y', outputPath],+ timeoutMs: FFMPEG_FRAME_TIMEOUT_MS,});if (!result.ok) throw new Error(`Reference keyframe failed: ${result.reason}`);}diff --git a/server/services/moodBoard/collage.js b/server/services/moodBoard/collage.jsindex 7c1a0c74f0..c58fe36223 100644--- a/server/services/moodBoard/collage.js+++ b/server/services/moodBoard/collage.js@@ -20,7 +20,7 @@ import { join } from 'path';import sharp from 'sharp';import { ServerError } from '../../lib/errorHandler.js';import { PATHS, ensureDir, atomicWrite } from '../../lib/fileUtils.js';-import { findFfmpeg, runFfmpegProcess, probeVideoDuration, safeUnder } from '../../lib/ffmpeg.js';+import { FFMPEG_FRAME_TIMEOUT_MS, findFfmpeg, runFfmpegProcess, probeVideoDuration, safeUnder } from '../../lib/ffmpeg.js';import { assetBasename } from '../../lib/localImageFilename.js';import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { emitRecordUpdated } from '../sharing/recordEvents.js';@@ -70,6 +70,7 @@ async function sampleVideoFrames(videoFile, count, outDir, prefix, picked = nullbin: ffmpeg,args: ['-ss', times[i].toFixed(3), '-i', videoPath, '-frames:v', '1', '-q:v', '1', '-qmin', '1', '-y', out],stderrTailBytes: 0,+ timeoutMs: FFMPEG_FRAME_TIMEOUT_MS,});if (result.ok) paths.push({ path: out, time: times[i] });}diff --git a/server/services/sprites/walkTrims.js b/server/services/sprites/walkTrims.jsindex 31044cbfb2..2511ddb134 100644--- a/server/services/sprites/walkTrims.js+++ b/server/services/sprites/walkTrims.js@@ -20,7 +20,7 @@ import { tmpdir } from 'os';import {ensureDir, atomicWrite, pathExists, sha256File, readJSONFile, rmGuarded, writeFileGuarded,} from '../../lib/fileUtils.js';-import { findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';+import { FFMPEG_SCAN_TIMEOUT_MS, findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';import { ServerError } from '../../lib/errorHandler.js';import { decodeRgbaFrame, encodePng } from '../../lib/imageRgba.js';import { resolveSpriteAssetPath, spriteDir, toRecordRelativeAssetPath } from './paths.js';@@ -63,6 +63,7 @@ async function encodeTrimGif(frames, fps, destAbs) {'-loop', '0',destAbs,],+ timeoutMs: FFMPEG_SCAN_TIMEOUT_MS,});await rmGuarded(scratch, { recursive: true, force: true }).catch(() => {});if (!result.ok) throw new ServerError(`GIF encode failed: ${result.reason}`, { status: 500, code: 'GIF_ENCODE_FAILED' });diff --git a/server/services/sprites/walkTrims.test.js b/server/services/sprites/walkTrims.test.jsindex f9668e4b56..4922b3e873 100644--- a/server/services/sprites/walkTrims.test.js+++ b/server/services/sprites/walkTrims.test.js@@ -37,6 +37,7 @@ const runFfmpegProcess = vi.fn(async ({ args }) => {return { ok: true };});vi.mock('../../lib/ffmpeg.js', () => ({+ FFMPEG_SCAN_TIMEOUT_MS: 900000,findFfmpeg: async () => '/fake/ffmpeg',runFfmpegProcess: (...args) => runFfmpegProcess(...args),}));diff --git a/server/services/videoGen/frameExtraction.js b/server/services/videoGen/frameExtraction.jsindex 5b0c36c698..34e16a401d 100644--- a/server/services/videoGen/frameExtraction.js+++ b/server/services/videoGen/frameExtraction.js@@ -8,7 +8,7 @@ import { spawn } from '../../lib/childProcess.js';import { ensureDir, PATHS, UUID_RE, tryReadFile, copyFileGuarded, writeFileGuarded, unlinkGuarded, rmGuarded } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import {- findFfmpeg, safeUnder, extractEvaluationFrames, runFfmpegProcess, vfrSyncArgs,+ FFMPEG_SCAN_TIMEOUT_MS, findFfmpeg, safeUnder, extractEvaluationFrames, runFfmpegProcess, vfrSyncArgs,} from '../../lib/ffmpeg.js';import {TAIL_WINDOW_SECONDS, CANDIDATE_FPS, MAX_CANDIDATES, pickBestFrame,@@ -46,6 +46,7 @@ async function decodeTailCandidates(ffmpeg, videoPath, candidateDir) {'-frames:v', String(MAX_CANDIDATES), '-y', outPattern,],stderrTailBytes: 0,+ timeoutMs: FFMPEG_SCAN_TIMEOUT_MS,});if (!scan.ok && scan.reason?.startsWith('spawn failed: ')) {console.log(`⚠️ Anchor candidate scan failed to spawn: ${scan.reason.slice('spawn failed: '.length)}`);