Skip to content

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

address review round 2: correct the anchor offset, stop pinning an unscanned fallback (#4666)

[._.]/ Adam Eivy8d4294572aac
diff --git a/server/lib/README.md b/server/lib/README.md
index 789f469e7b..d74d833bb0 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -213,7 +213,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `hostShutdown.js` | Tells "PortOS was restarted out from under a running agent" apart from "the agent failed" (#3202). `markHostShuttingDown()` / `isHostShuttingDown()` are the in-process latch the SIGTERM/SIGINT handler sets first thing; `shouldAbandonForHostShutdown({sentinelPresent,terminatedByUser,paused})` keeps every spawn path on the same preserve-vs-finalize policy. `writeHostShutdownMarker({agentIds,signal})` / `readHostShutdownMarker()` / `clearHostShutdownMarker()` persist that verdict to `data/cos/host-shutdown.json` so the NEXT boot's orphan sweep can requeue those agents as *interrupted* — no orphan-retry charge, no 30-minute cooldown. All non-throwing: a missing marker degrades to the ordinary orphan path. |
| `execGit.js` | `execGit(args, cwd, options)` utility imported by `git.js` + worktree manager. `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` | Shared ffmpeg helpers (videoGen + videoTimeline). 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`). `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. |
-| `frameQuality.js` | Scores decoded video frames so a chained render can CHOOSE its continuation anchor instead of taking whatever an end-seek lands on. `scoreFrame({width,height,data},{recency})` combines three terms over a raw single-channel buffer: log-compressed `gradientVariance` (focus), distance of `meanLuma` from mid-grey (exposure penalty, which rejects a fade-to-black or a blown highlight), and a small linear recency bonus that keeps the anchor near the cut when candidates are comparably clean. Usability and ranking are deliberately separate: `usable` gates on raw gradient variance against `MIN_SIGNAL_VARIANCE` alone, so only a mathematically degenerate frame is rejected and a legitimately dark low-key tail still qualifies — the same contract `imageFrameStats.js` keeps. Gating on the composite score instead would reject every night scene on the exposure term. `TAIL_WINDOW_SECONDS` is capped at the reach of the single `-sseof -1.0` seek this replaces: focus is systematically highest at the OLDEST candidate, so a wider window would widen the backward jump at each chain seam rather than tightening it. `pickBestFrame(paths)` decodes each candidate through `sharp` and returns the winner (or `null` when nothing decodes or nothing clears the floor, so the caller degrades rather than failing a render). `TAIL_WINDOW_SECONDS` / `CANDIDATE_FPS` / `MAX_CANDIDATES` define the window the caller decodes from. Consumer: `services/videoGen/local.js#extractLastFrame`. |
+| `frameQuality.js` | Scores decoded video frames so a chained render can CHOOSE its continuation anchor instead of taking whatever an end-seek lands on. `scoreFrame({width,height,data},{recency})` combines three terms over a raw single-channel buffer: log-compressed `gradientVariance` (focus), distance of `meanLuma` from mid-grey (exposure penalty, which rejects a fade-to-black or a blown highlight), and a small linear recency bonus that keeps the anchor near the cut when candidates are comparably clean. Usability and ranking are deliberately separate: `usable` gates on raw gradient variance against `MIN_SIGNAL_VARIANCE` alone, so only a mathematically degenerate frame is rejected and a legitimately dark low-key tail still qualifies — the same contract `imageFrameStats.js` keeps. Gating on the composite score instead would reject every night scene on the exposure term. `TAIL_WINDOW_SECONDS` is capped at the reach of the single `-sseof -1.0` seek this replaces: focus is systematically highest at the OLDEST candidate, so a wider window would widen the backward jump at each chain seam rather than tightening it. `pickBestFrame(paths)` decodes each candidate through `sharp` and returns the winner (or `null` when nothing decodes or every candidate is degenerate, so the caller degrades rather than failing a render); its `index` is the position in the array AS PASSED, because the caller turns that into the anchor's time offset. `MAX_CANDIDATES` is derived from the window, never set independently — the ffmpeg-side `-frames:v` cap truncates from the NEWEST end, exactly the frames recency prefers. `TAIL_WINDOW_SECONDS` / `CANDIDATE_FPS` / `MAX_CANDIDATES` define the window the caller decodes from. Consumer: `services/videoGen/local.js#extractLastFrame`. |
| `ffmpegRenderGuard.js` | `attachFfmpegRenderGuard(proc, {label, onSpawnError, onProcessError, onClose})` — shared spawn-state tracking + exactly-once `terminal` guard + pre-vs-post-spawn dispatch for the SSE ffmpeg render runners (musicVideo/render + videoTimeline/local). Owns the 'spawn'/'error'/'close' wiring (only the pre-spawn 'error' or 'close' finalizes; a post-spawn 'error' records only) and takes the service-specific finalize bodies as callbacks so each renderer keeps its own project-status/history behavior. |
| `gitArgs.js` | `PROTECTED_BRANCHES`, `validateFilePaths(files)` — pure command-arg builders/validators for `git.js` (reject injection/traversal in staged paths). |
| `gitCommitProbe.js` | `commitsSince(workspacePath, sinceMs)` / `committedDuringRun(workspacePath, sinceMs)` — the run-window commit probe: how many commits landed with a COMMITTER date inside a run's window (so a rebase/commit by the agent counts, a merely-pulled remote commit does not). The single machine-checkable "did this run commit anything?" primitive shared by finalize's success-criteria evaluation, run completion, runner completion, and orphan recovery — it replaced the unsatisfiable task-id commit-marker grep (#3637). Non-throwing: a non-repo, empty repo, or git timeout is 0. |
diff --git a/server/lib/frameQuality.js b/server/lib/frameQuality.js
index 83b483a0dc..8bfbf455c8 100644
--- a/server/lib/frameQuality.js
+++ b/server/lib/frameQuality.js
@@ -41,7 +41,10 @@ import sharp from 'sharp';
// recency bonus biases toward the cut but cannot bound the window on its own.
export const TAIL_WINDOW_SECONDS = 1.0;
export const CANDIDATE_FPS = 12;
-export const MAX_CANDIDATES = 12;
+// Derived, never an independent number: the ffmpeg-side cap (`-frames:v`)
+// truncates from the NEWEST end, which is exactly the frames the recency term
+// prefers. If the two ever disagreed, the cap would silently discard the pick.
+export const MAX_CANDIDATES = Math.round(TAIL_WINDOW_SECONDS * CANDIDATE_FPS);
// Gradient variance that maps to a focus of 1.0. Real sharp frames land in the
// low thousands, so this leaves headroom without clamping ordinary content.
@@ -145,19 +148,21 @@ export function scoreFrame(frame, { recency = 1 } = {}) {
* candidate, and must never abort a render the user already paid GPU time for.
*/
export async function decodeGreyscaleFrame(path, { sharpImpl = sharp } = {}) {
- // `removeAlpha()` before `greyscale()` matters: greyscale PRESERVES alpha, so
- // an RGBA source decodes to 2 interleaved channels. The buffer would still be
- // ≥ width×height bytes, so the shape check below would pass while
- // gradientVariance read alpha samples as neighbouring pixels and meanLuma
- // averaged only the first half of the image.
+ // On sharp 0.35.3 `.greyscale().raw()` already lands ONE channel even for an
+ // RGBA source (verified: byte-identical with and without removeAlpha). The
+ // explicit `removeAlpha()` makes that a stated requirement rather than an
+ // incidental property, and the channel check below is the backstop if it ever
+ // stops holding: an interleaved buffer is still ≥ width×height bytes, so the
+ // shape check alone would pass while gradientVariance read alpha samples as
+ // neighbouring pixels and meanLuma averaged half the image.
const decoded = await sharpImpl(path).removeAlpha().greyscale().raw()
.toBuffer({ resolveWithObject: true })
.catch(() => null);
if (!decoded?.info) return null;
const { width, height, channels } = decoded.info;
- // Belt and braces for a sharp stand-in (or a future format) that lands more
- // than one channel here anyway — interleaved data must never reach the
- // scorer, and a null simply drops this candidate.
+ // Interleaved data must never reach the scorer; a null simply drops this
+ // candidate. `channels == null` means the decoder didn't report it, which is
+ // not evidence of a problem — sentinel discipline, not `!channels`.
if (channels != null && channels !== 1) return null;
const frame = { width, height, data: decoded.data };
return isFrame(frame) ? frame : null;
@@ -165,19 +170,26 @@ export async function decodeGreyscaleFrame(path, { sharpImpl = sharp } = {}) {
/**
* Score every candidate path (given in timeline order, oldest first) and
- * return the best one, or null when nothing decoded or nothing clears the
- * usability floor. The returned `index` is the candidate's position in the
- * input array, which is what lets the caller name the offset it picked.
+ * return the best one, or null when nothing decoded or every candidate is
+ * degenerate. The returned `index` is the candidate's position in the input
+ * array AS PASSED — non-string entries are skipped, not renumbered — because
+ * the caller derives the anchor's time offset from it.
*/
export async function pickBestFrame(paths, { sharpImpl = sharp } = {}) {
- const list = Array.isArray(paths) ? paths.filter((p) => typeof p === 'string' && p) : [];
+ const list = Array.isArray(paths) ? paths : [];
if (!list.length) return null;
let best = null;
+ // Indices are positions in the CALLER's array, never in a filtered copy —
+ // the caller derives the anchor's time offset from `index` against that same
+ // array, so a renumbering here would silently mis-report the offset. Skipped
+ // entries are holes in the timeline, not a reason to shift the rest.
+ //
// Decoded sequentially on purpose: only the SCORE outlives each frame, so
// one raw buffer is live at a time. Decoding the whole window at once would
// hold width × height bytes per candidate simultaneously, which scales with
// the render resolution for no wall-clock that matters next to a GPU render.
for (let i = 0; i < list.length; i++) {
+ if (typeof list[i] !== 'string' || !list[i]) continue;
// eslint-disable-next-line no-await-in-loop
const frame = await decodeGreyscaleFrame(list[i], { sharpImpl });
if (!frame) continue;
diff --git a/server/lib/frameQuality.test.js b/server/lib/frameQuality.test.js
index 9e26629fdc..499ae72af7 100644
--- a/server/lib/frameQuality.test.js
+++ b/server/lib/frameQuality.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi } from 'vitest';
+import sharp from 'sharp';
import {
gradientVariance, meanLuma, scoreFrame, pickBestFrame, decodeGreyscaleFrame,
RECENCY_WEIGHT, MIN_SIGNAL_VARIANCE,
@@ -166,6 +167,36 @@ describe('decodeGreyscaleFrame', () => {
});
});
+describe('decodeGreyscaleFrame — against the real sharp', () => {
+ const rgbaPng = async (width, height) => {
+ const raw = Buffer.alloc(width * height * 4);
+ for (let i = 0; i < width * height; i++) {
+ raw[i * 4] = (i * 7) % 256;
+ raw[i * 4 + 1] = (i * 13) % 256;
+ raw[i * 4 + 2] = (i * 29) % 256;
+ raw[i * 4 + 3] = i % 2 ? 255 : 40; // varying alpha
+ }
+ return sharp(raw, { raw: { width, height, channels: 4 } }).png().toBuffer();
+ };
+
+ it('decodes an RGBA source to exactly one byte per pixel', async () => {
+ // The `channels !== 1` guard would silently drop EVERY candidate and revert
+ // the whole feature to the end seek if a real decode ever landed
+ // interleaved data. Every other test in this repo runs the scorer against a
+ // stand-in, so this is the only place that claim is actually checked.
+ const width = 12;
+ const height = 9;
+ const frame = await decodeGreyscaleFrame(await rgbaPng(width, height));
+ expect(frame).toMatchObject({ width, height });
+ expect(frame.data.length).toBe(width * height);
+ expect(scoreFrame(frame, { recency: 1 }).usable).toBe(true);
+ });
+
+ it('returns null for bytes that are not an image', async () => {
+ await expect(decodeGreyscaleFrame(Buffer.from('not an image'))).resolves.toBeNull();
+ });
+});
+
describe('pickBestFrame', () => {
it('picks the sharpest candidate, not the last one', async () => {
const paths = ['/t/a.png', '/t/b.png', '/t/c.png'];
@@ -213,4 +244,12 @@ describe('pickBestFrame', () => {
await pickBestFrame(['/t/a.png', null, '', undefined], { sharpImpl: impl });
expect(impl).toHaveBeenCalledTimes(1);
});
+
+ it('reports the index in the array as passed, not in a filtered copy', async () => {
+ // The caller turns `index` into the anchor's time offset against this same
+ // array, so renumbering around skipped entries would mis-report the offset.
+ const sharpImpl = fakeSharp({ '/t/c.png': SHARP });
+ const best = await pickBestFrame([null, '', '/t/c.png'], { sharpImpl });
+ expect(best).toMatchObject({ path: '/t/c.png', index: 2 });
+ });
});
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 7671237ddc..75950cdb33 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -17,7 +17,7 @@ import { join, basename } from 'path';
import { tmpdir, totalmem } from 'os';
import { randomUUID } from 'crypto';
import { promisify } from 'util';
-import { ensureDir, PATHS, UUID_RE } from '../../lib/fileUtils.js';
+import { ensureDir, PATHS, UUID_RE, tryReadFile } from '../../lib/fileUtils.js';
import { spawnDetached } from '../../lib/detachedSpawn.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { createLineReader } from '../../lib/streamLines.js';
@@ -31,7 +31,7 @@ import { getVideoModels, getDefaultVideoModelId, getTextEncoderRepo } from '../.
import {
findFfmpeg, safeUnder, generateThumbnail, optimizeForStreaming, upscaleVideo2x,
extractEvaluationFrames, probeFrameCount, trimVideoFromFrame,
- hasAudioStream, buildTrimConcatArgs, bt709TagFilter,
+ hasAudioStream, buildTrimConcatArgs, bt709TagFilter, runFfmpegProcess,
} from '../../lib/ffmpeg.js';
import {
TAIL_WINDOW_SECONDS, CANDIDATE_FPS, MAX_CANDIDATES, pickBestFrame,
@@ -2594,6 +2594,12 @@ async function setHistoryItemsHidden(ids, hidden) {
}).catch(() => {});
}
+// Sidecar `extractedAt` marking an anchor produced by the end-seek fallback
+// because the candidate scan could not run — as opposed to a scan that ran and
+// found the tail genuinely degenerate, which is a stable property of the clip.
+// The former is provisional and re-scanned on the next call; the latter is not.
+const UNSCANNED_ANCHOR = 'last-frame-unscanned';
+
// Decode the tail-window candidates for `extractLastFrame` into a temp dir and
// return their paths in timeline order (oldest first).
//
@@ -2609,18 +2615,21 @@ async function decodeTailCandidates(ffmpeg, videoPath, candidateDir) {
await rm(candidateDir, { recursive: true, force: true }).catch(() => {});
await ensureDir(candidateDir);
const outPattern = join(candidateDir, 'cand-%03d.png');
- await new Promise((resolve) => {
- const proc = spawn(ffmpeg, [
+ // Through the catalog helper rather than a hand-rolled spawn: it already
+ // translates spawn errors into a reason string instead of an unhandled
+ // 'error' event, matching every other extraction path in this file.
+ const scan = await runFfmpegProcess({
+ bin: ffmpeg,
+ args: [
'-sseof', `-${TAIL_WINDOW_SECONDS.toFixed(2)}`, '-i', videoPath,
'-vf', `fps=${CANDIDATE_FPS}`, '-vsync', 'vfr',
'-frames:v', String(MAX_CANDIDATES), '-y', outPattern,
- ], safeChildProcessOptions({ stdio: 'ignore' }));
- proc.on('close', () => resolve());
- proc.on('error', (err) => {
- console.log(`⚠️ Anchor candidate scan failed to spawn: ${err.message}`);
- resolve();
- });
+ ],
+ stderrTailBytes: 0,
});
+ if (!scan.ok && scan.reason?.startsWith('spawn failed: ')) {
+ console.log(`⚠️ Anchor candidate scan failed to spawn: ${scan.reason.slice('spawn failed: '.length)}`);
+ }
// The muxer numbers sequentially from 1, so the first gap is the end of the
// run — enumerate by name rather than reading the directory back. The exit
// code is deliberately not consulted: a partial run still wrote usable
@@ -2727,8 +2736,21 @@ export async function extractLastFrame(historyId) {
await writeFile(sidecarPath, JSON.stringify(meta, null, 2), { flag: 'wx' }).catch(() => {});
};
+ // A cached anchor the fallback produced WITHOUT a scan is provisional: serving
+ // it from the size>0 hit would pin a one-off ffmpeg or tmpdir failure to this
+ // clip permanently, with no retry short of deleting the file by hand. An
+ // absent or unparseable sidecar is NOT evidence of that — legacy files have
+ // none — so only the explicit marker triggers a re-scan.
+ const cachedIsProvisional = async () => {
+ const raw = await tryReadFile(sidecarPath);
+ if (!raw) return false;
+ const parsed = JSON.parse(raw.toString());
+ return parsed?.extractedAt === UNSCANNED_ANCHOR;
+ };
+
const cachedSize = safeStatSize(framePath);
- if (cachedSize != null && cachedSize > 0) {
+ if (cachedSize != null && cachedSize > 0
+ && !await cachedIsProvisional().catch(() => false)) {
await writeSidecar();
return { filename: frameFilename, path: `/data/images/${frameFilename}` };
}
@@ -2768,18 +2790,25 @@ export async function extractLastFrame(historyId) {
// UUID/`upload-<uuid8>` above, so the recursive remove can't escape tmpdir.
await rm(candidateDir, { recursive: true, force: true }).catch(() => {});
+ // 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(() => {});
+
if (installed) {
- // Offset back from the NEWEST candidate, not from a nominal window start:
- // `-sseof` clamps to the file start on a clip shorter than the window, so
- // deriving this from TAIL_WINDOW_SECONDS would state an offset the frame
- // does not have. Measured against the candidates actually decoded, this is
- // exact in both cases.
- const offset = (candidates.length - 1 - best.index) / CANDIDATE_FPS;
+ // Offset derived from the candidates actually decoded, not from a nominal
+ // window start: `-sseof` clamps to the file start on a clip shorter than
+ // the window, so TAIL_WINDOW_SECONDS would name an offset the frame does
+ // not have. The fps grid stops one interval short of EOF, so the newest
+ // 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.
+ 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}`);
return { filename: frameFilename, path: `/data/images/${frameFilename}` };
}
- if (candidates.length) {
+ if (candidates.length && !best) {
console.log(`⚠️ No usable anchor among ${candidates.length} tail candidates for ${item.id.slice(0, 8)} — falling back to the end seek`);
}
@@ -2807,7 +2836,11 @@ export async function extractLastFrame(historyId) {
if (writtenSize === 0) await unlink(framePath).catch(() => {});
return reject(new ServerError('Failed to extract last frame', { status: 500, code: 'FFMPEG_FAILED' }));
}
- await writeSidecar();
+ // 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);
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.js
index 23ca51380b..fc977763f3 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -197,6 +197,10 @@ vi.mock('../../lib/ffmpeg.js', async () => ({
// The real builder is pure and covered by ffmpeg.test.js; keep it real here
// so the chain tests assert on the argv that actually reaches ffmpeg.
buildTrimConcatArgs: (await vi.importActual('../../lib/ffmpeg.js')).buildTrimConcatArgs,
+ // Also real: it spawns through the mocked lib/childProcess.js, so the anchor
+ // tests still read the argv off the shared spawn mock. Stubbing it would hide
+ // the very args they assert on.
+ runFfmpegProcess: (await vi.importActual('../../lib/ffmpeg.js')).runFfmpegProcess,
// Report the setparams filter as available so the chain tests assert on the
// fully-tagged argv (the degraded, container-flags-only shape is covered in
// ffmpeg.test.js).
@@ -424,12 +428,13 @@ describe('extractLastFrame — anchor selection', () => {
join(tmpdir(), `anchorcand-${ID}`),
{ recursive: true, force: true },
);
- // Sidecar names the offset the anchor actually came from, measured back
- // from the NEWEST candidate rather than a nominal window start: 9 of the 12
- // decoded frames follow index 2, so at 12fps the pick sits 0.75s from the
- // end of the tail that was actually scanned.
+ // Sidecar names the offset the anchor actually came from, derived from the
+ // candidates actually decoded rather than a nominal window start. The fps
+ // grid stops one interval short of EOF, so index 2 of 12 at 12fps sits
+ // (12−2)/12 = 0.83s from the end — not 0.75s, which would be the distance
+ // to the newest CANDIDATE rather than to the cut.
const sidecar = JSON.parse(vi.mocked(writeFile).mock.calls.at(-1)[1]);
- expect(sidecar).toMatchObject({ filename: ANCHOR, extractedAt: '-0.75s' });
+ expect(sidecar).toMatchObject({ filename: ANCHOR, extractedAt: '-0.83s' });
});
it('reads back exactly the candidate files it told ffmpeg to write', async () => {
@@ -453,6 +458,73 @@ describe('extractLastFrame — anchor selection', () => {
expect(scanned).toHaveLength(3);
});
+ it('reports the offset against the candidates it got, not a nominal window', async () => {
+ // The short-clip case the offset arithmetic exists for: `-sseof` clamps to
+ // the file start, so a sub-window clip yields fewer candidates and a
+ // TAIL_WINDOW_SECONDS-derived offset would name a time the frame does not
+ // have. (3 − 1) / 12fps = 0.17s from the cut.
+ await seedHistory();
+ fsState.missOnce = [ANCHOR];
+ fsState.candidateCount = 3;
+ 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: '-0.17s' });
+ });
+
+ it.each([
+ ['re-scans', 'last-frame-unscanned', true],
+ ['serves', '-0.42s', false],
+ ['serves', 'last-frame', false],
+ ])('%s a cached anchor whose sidecar says %s', async (_verb, extractedAt, rescans) => {
+ // A one-off ffmpeg or tmpdir failure used to pin the degraded end-seek frame
+ // to this clip forever behind the size>0 cache hit. The sidecar marker is
+ // what makes THAT attempt provisional — and the other two rows are the
+ // bypass probe: without the marker the cache must still short-circuit, or
+ // every click re-spawns ffmpeg and the cache stops existing.
+ const { tryReadFile } = await import('../../lib/fileUtils.js');
+ await seedHistory();
+ vi.mocked(tryReadFile).mockResolvedValueOnce(
+ JSON.stringify({ filename: ANCHOR, extractedAt }),
+ );
+ anchorPick.best = null;
+ fsState.candidateCount = 0; // the scan still can't produce anything
+
+ await extractLastFrame(ID);
+
+ // statSync reports a healthy non-zero file in every row; only the marker
+ // decides whether the scan runs anyway.
+ expect((await ffmpegSpawns()).length > 0).toBe(rescans);
+ });
+
+ it.each([
+ ['a scan that ran and found nothing usable', 12, 'last-frame'],
+ ['a scan that could not run at all', 0, 'last-frame-unscanned'],
+ ])('marks the fallback anchor from %s as %s', async (_label, count, expected) => {
+ // Only the second is provisional: a degenerate tail is a property of the
+ // clip and must stay cached, or every click re-spawns ffmpeg for nothing.
+ await seedHistory();
+ fsState.missOnce = [ANCHOR];
+ fsState.candidateCount = count;
+ anchorPick.best = null;
+ 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: expected });
+ });
+
it('falls back to the end seek when no candidate is usable', async () => {
await seedHistory();
fsState.missOnce = [ANCHOR];