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 round 3: classify the fallback anchor by what happened, not by candidate count (#4666)
[._.]/ Adam Eivye7285de247ae
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex 75950cdb33..ea0537291e 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -12,7 +12,7 @@import { execFile, spawn } from '../../lib/childProcess.js';import { existsSync, statSync } from 'fs';-import { unlink, writeFile, copyFile, rm, rename } from 'fs/promises';+import { unlink, writeFile, copyFile, rm } from 'fs/promises';import { join, basename } from 'path';import { tmpdir, totalmem } from 'os';import { randomUUID } from 'crypto';@@ -2640,7 +2640,12 @@ async function decodeTailCandidates(ffmpeg, videoPath, candidateDir) {if (!existsSync(p)) break;paths.push(p);}- return paths;+ // `complete` = the run reached EOF, which is what lets the caller read the+ // newest candidate as "one grid interval before the cut". A truncated run+ // numbers from the OLDEST frame just the same, so without this the caller+ // cannot tell "short clip" (candidates end at EOF) from "ffmpeg died partway"+ // (candidates end wherever it stopped) and would name the wrong offset.+ return { paths, complete: scan.ok };}// Extract a continuation anchor frame from the tail of a video as a PNG into@@ -2760,10 +2765,10 @@ export async function extractLastFrame(historyId) {// Everything here degrades to the single-seek fallback below rather than// throwing: this runs mid-chain, and a scan failure must not lose a render.const candidateDir = join(tmpdir(), `anchorcand-${item.id}`);- const candidates = await decodeTailCandidates(ffmpeg, videoPath, candidateDir)+ const { paths: candidates, complete: scanComplete } = await decodeTailCandidates(ffmpeg, videoPath, candidateDir).catch((err) => {console.log(`⚠️ Anchor candidate scan failed: ${err.message}`);- return [];+ return { paths: [], complete: false };});const best = candidates.length? await pickBestFrame(candidates).catch((err) => {@@ -2771,20 +2776,26 @@ export async function extractLastFrame(historyId) {return null;}): null;- // Copy through a temp name and rename into place. `copyFile` is not atomic,- // and a truncated non-zero PNG at framePath would be served forever by the- // size>0 cache hit above — the fallback's own guard only unlinks at exactly- // zero bytes.+ // Copy straight to framePath and verify the result, rather than staging a+ // `.tmp` alongside it: PATHS.images is enumerated by the peer media-library+ // manifest, which skips only `.json`, so a staging file there would federate+ // as an image asset. A short copy is caught by the size check and unlinked,+ // so a truncated PNG can't be served forever by the size>0 cache hit above.+ // (A hard crash mid-copy can still leave one — the same exposure the fallback+ // ffmpeg write below has always had, not a new class.)+ const expectedSize = best ? safeStatSize(best.path) : null;const installed = best- ? await copyFile(best.path, `${framePath}.tmp`)- .then(() => rename(`${framePath}.tmp`, framePath))- .then(() => true)- .catch(async (err) => {+ ? await copyFile(best.path, framePath).then(() => {+ const written = safeStatSize(framePath);+ if (written && (expectedSize == null || written === expectedSize)) return true;+ console.log(`⚠️ Anchor install wrote ${written ?? 'nothing'} of ${expectedSize ?? '?'} bytes — discarding`);+ return false;+ }).catch((err) => {console.log(`⚠️ Anchor install failed: ${err.message}`);- await unlink(`${framePath}.tmp`).catch(() => {});return false;}): false;+ if (best && !installed) await unlink(framePath).catch(() => {});// Drop the whole candidate dir either way — they're temp decodes and the// winner is already copied into data/images/ by now. `item.id` is validated// UUID/`upload-<uuid8>` above, so the recursive remove can't escape tmpdir.@@ -2792,8 +2803,10 @@ export async function extractLastFrame(historyId) {// Both extraction paths below know the truth about this anchor, so they must// be able to REPLACE a sidecar written by an earlier attempt — `wx` alone- // would leave a stale provisional marker in place and re-scan forever.- if (best || !candidates.length) await unlink(sidecarPath).catch(() => {});+ // would leave a stale provisional marker in place and re-scan forever. This+ // is the extraction path (the cache hit already returned), so an unconditional+ // drop is right: whatever is written next is authoritative.+ await unlink(sidecarPath).catch(() => {});if (installed) {// Offset derived from the candidates actually decoded, not from a nominal@@ -2803,9 +2816,15 @@ export async function extractLastFrame(historyId) {// candidate is ~1/CANDIDATE_FPS from the end, not at it — hence// `length - index` rather than `length - 1 - index`. Accurate to within// one sampling interval, which is what the sidecar claims.+ // Only meaningful when the run reached EOF. A truncated scan's candidates+ // end wherever ffmpeg stopped, so the distance to the cut is unknown —+ // name the candidate instead of inventing a time.const offset = (candidates.length - best.index) / CANDIDATE_FPS;- await writeSidecar(`-${offset.toFixed(2)}s`);- console.log(`🎞️ Anchor frame ${best.index + 1}/${candidates.length} at -${offset.toFixed(2)}s (focus ${best.focus.toFixed(2)}): ${frameFilename}`);+ const where = scanComplete+ ? `-${offset.toFixed(2)}s`+ : `tail-candidate ${best.index + 1}/${candidates.length}`;+ await writeSidecar(where);+ console.log(`🎞️ Anchor frame ${best.index + 1}/${candidates.length} at ${where} (focus ${best.focus.toFixed(2)}): ${frameFilename}`);return { filename: frameFilename, path: `/data/images/${frameFilename}` };}if (candidates.length && !best) {@@ -2837,10 +2856,11 @@ export async function extractLastFrame(historyId) {return reject(new ServerError('Failed to extract last frame', { status: 500, code: 'FFMPEG_FAILED' }));}// A scan that RAN and found nothing usable is a property of the clip —- // cache it. A scan that could not run at all (no candidates decoded) is- // transient, and the old code would have pinned this degraded frame- // forever behind the size>0 cache hit. Mark it so the next call retries.- await writeSidecar(candidates.length ? 'last-frame' : UNSCANNED_ANCHOR);+ // cache it. Everything else reaching here is transient (the scan could+ // not run, or a winner was found and the install failed), and caching it+ // would pin this degraded frame forever behind the size>0 cache hit.+ // Key on what actually happened, not merely on candidate count.+ await writeSidecar(candidates.length && !best ? 'last-frame' : UNSCANNED_ANCHOR);console.log(`🎞️ Anchor frame via end-seek fallback: ${frameFilename}`);resolve({ filename: frameFilename, path: `/data/images/${frameFilename}` });} catch (err) {diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex fc977763f3..9841c0eaa3 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -308,6 +308,11 @@ vi.mock('fs/promises', () => ({// Shared shape for both the child_process spawn mock (ffmpeg/probe) and the// detachedSpawn mock (the render child). Hoisted so the vi.mock factories// (themselves hoisted above normal declarations) can reference it.+// When non-null, the NEXT spawn closes with this exit code — the only way to+// drive a partial ffmpeg run (candidates written, non-zero exit) through the+// shared proc mock.+const spawnState = vi.hoisted(() => ({ nextExitCode: null }));+const { makeProc } = vi.hoisted(() => ({makeProc: () => {const listeners = {};@@ -324,8 +329,10 @@ const { makeProc } = vi.hoisted(() => ({};// fire close(0) async so the caller's .on('close') handler can register firstsetImmediate(() => {- proc.exitCode = 0;- listeners.close?.(0, null);+ const code = spawnState.nextExitCode ?? 0;+ spawnState.nextExitCode = null;+ proc.exitCode = code;+ listeners.close?.(code, null);});return proc;},@@ -361,6 +368,7 @@ afterEach(() => {settingsState.acceptedModelTerms = [];fsState.missOnce = [];fsState.candidateCount = null;+ spawnState.nextExitCode = null;anchorPick.best = null;vi.clearAllMocks();});@@ -404,19 +412,19 @@ describe('extractLastFrame — anchor selection', () => {score: 0.82,usable: true,};- const { copyFile, rename, writeFile, rm } = await import('fs/promises');+ const { copyFile, writeFile, rm } = await import('fs/promises');await expect(extractLastFrame(ID)).resolves.toEqual({filename: ANCHOR,path: `/data/images/${ANCHOR}`,});- // The winner is installed under the NEW cache name, not the legacy one —- // and through a temp file, so a truncated copy can never be cached as a- // non-zero PNG that the size>0 hit would then serve forever.+ // The winner is installed under the NEW cache name, not the legacy one, and+ // straight to it — no `.tmp` alongside, which the peer media-library+ // manifest would federate as an image asset (it skips only `.json`).const dest = join(MOCK_PATHS.images, ANCHOR);- expect(vi.mocked(copyFile)).toHaveBeenCalledWith(anchorPick.best.path, `${dest}.tmp`);- expect(vi.mocked(rename)).toHaveBeenCalledWith(`${dest}.tmp`, dest);+ expect(vi.mocked(copyFile)).toHaveBeenCalledWith(anchorPick.best.path, dest);+ expect(vi.mocked(copyFile).mock.calls.some(([, d]) => String(d).endsWith('.tmp'))).toBe(false);// One decode pass over the tail window; the single-seek fallback must NOT// have run — that would mean the scored pick was thrown away.const spawns = await ffmpegSpawns();@@ -525,6 +533,67 @@ describe('extractLastFrame — anchor selection', () => {expect(sidecar).toMatchObject({ extractedAt: expected });});+ it('names the candidate rather than a time when the scan was truncated', async () => {+ // A partial run's candidates end wherever ffmpeg stopped, not at EOF, so+ // the grid gives no distance to the cut. Inventing one would put a silent+ // lie in the gallery record.+ await seedHistory();+ fsState.missOnce = [ANCHOR];+ fsState.candidateCount = 3;+ spawnState.nextExitCode = 1; // ffmpeg wrote 3 frames, then died+ anchorPick.best = {+ path: join(tmpdir(), `anchorcand-${ID}`, 'cand-002.png'),+ index: 1, focus: 0.6, quality: 0.6, score: 0.65, usable: true,+ };+ const { writeFile } = await import('fs/promises');++ await extractLastFrame(ID);++ const sidecar = JSON.parse(vi.mocked(writeFile).mock.calls.at(-1)[1]);+ expect(sidecar).toMatchObject({ extractedAt: 'tail-candidate 2/3' });+ });++ it('treats a failed install as provisional, not as a degenerate tail', async () => {+ // A winner WAS found; only the copy failed (ENOSPC/EIO/EACCES — all+ // transient). Stamping that 'last-frame' would classify it as a property of+ // the clip and pin the degraded end-seek anchor behind the cache forever.+ await seedHistory();+ fsState.missOnce = [ANCHOR];+ anchorPick.best = {+ path: join(tmpdir(), `anchorcand-${ID}`, 'cand-006.png'),+ index: 5, focus: 0.7, quality: 0.7, score: 0.8, usable: true,+ };+ const { copyFile, writeFile } = await import('fs/promises');+ vi.mocked(copyFile).mockRejectedValueOnce(new Error('ENOSPC'));++ await extractLastFrame(ID);++ const sidecar = JSON.parse(vi.mocked(writeFile).mock.calls.at(-1)[1]);+ expect(sidecar).toMatchObject({ extractedAt: 'last-frame-unscanned' });+ });++ it('clears a stale provisional marker once a scan finally runs', async () => {+ // call 1 could not scan → 'last-frame-unscanned'; call 2 scans and finds the+ // tail genuinely degenerate. The `wx` sidecar write is a no-op against the+ // surviving file, so without an unconditional unlink the marker outlives the+ // scan and the clip re-scans on every click forever.+ const { tryReadFile } = await import('../../lib/fileUtils.js');+ await seedHistory();+ vi.mocked(tryReadFile).mockResolvedValueOnce(+ JSON.stringify({ filename: ANCHOR, extractedAt: 'last-frame-unscanned' }),+ );+ fsState.candidateCount = 12; // this time the scan runs...+ anchorPick.best = null; // ...and the tail really is degenerate+ const { unlink, writeFile } = await import('fs/promises');++ await extractLastFrame(ID);++ const sidecarPath = join(MOCK_PATHS.images, ANCHOR.replace('.png', '.metadata.json'));+ expect(vi.mocked(unlink)).toHaveBeenCalledWith(sidecarPath);+ const sidecar = JSON.parse(vi.mocked(writeFile).mock.calls.at(-1)[1]);+ expect(sidecar).toMatchObject({ extractedAt: 'last-frame' });+ });+it('falls back to the end seek when no candidate is usable', async () => {await seedHistory();fsState.missOnce = [ANCHOR];@@ -1005,8 +1074,8 @@ describe('generateChainedVideo — continuation strategy (context window vs lastanchorPick.best = best;// One hop → one anchor cache check; miss it so extraction actually runs.fsState.missOnce = ['anchor-'];- const { rename } = await import('fs/promises');- vi.mocked(rename).mockClear();+ const { copyFile } = await import('fs/promises');+ vi.mocked(copyFile).mockClear();const { renders, innerJobIds } = await runChain({modelId: 'ltx23_unified',@@ -1015,9 +1084,9 @@ describe('generateChainedVideo — continuation strategy (context window vs last}, 2);expect(flagValue(renders[1], '--image')).toBeTruthy();- // A scored winner is renamed into place under the new cache name; the+ // A scored winner is copied into place under the new cache name; the// fallback lets ffmpeg write that path directly, so there is no install.- const installedAnchor = vi.mocked(rename).mock.calls+ const installedAnchor = vi.mocked(copyFile).mock.calls.some(([, dest]) => dest === join(MOCK_PATHS.images, `anchor-${innerJobIds[0]}.png`));expect(installedAnchor).toBe(!!best);});