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
pick the video continuation anchor by scoring tail frames instead of trusting the end seek (#4666)
[._.]/ Adam Eivy92dcb3f3daa6
diff --git a/server/lib/README.md b/server/lib/README.mdindex 563201ec8f..cc66a34eb2 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -213,6 +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. `quality` (focus − exposure) is what `USABLE_QUALITY_FLOOR` tests — NOT `score`, or the free recency bonus on the last candidate could lift a black frame over the floor. `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`. || `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.jsnew file mode 100644index 0000000000..1c0c344bcd--- /dev/null+++ b/server/lib/frameQuality.js@@ -0,0 +1,162 @@+/**+ * Frame-quality scoring — picks the video continuation anchor by measuring+ * candidate frames instead of trusting wherever an end-seek happens to land.+ *+ * A chained render conditions chunk N+1 on ONE frame taken from the tail of+ * chunk N. Local video output is motion-heavy by construction (the prompt+ * guidance explicitly asks for a camera move and a visible action), so that+ * frame is frequently motion-blurred, mid-blink, or inside a fade — and the+ * next chunk inherits the blur as the scene's actual content, compounding+ * through every subsequent hop.+ *+ * The scoring is deliberately cheap and dependency-free beyond `sharp` (already+ * a server dependency): decode each candidate to a raw single-channel buffer,+ * then combine three terms.+ *+ * focus — log-compressed variance of the first-difference gradient.+ * Log compression is what keeps one exceptionally sharp frame+ * from swamping the exposure term.+ * exposure — penalty on the distance of mean luma from mid-grey, which is+ * what rejects a frame inside a fade-to-black or a blown highlight.+ * recency — a small linear preference for later frames, so among+ * comparably clean candidates the anchor stays as close to the+ * cut as possible. Without it the scorer drifts toward the calm+ * middle of the window and continuity loosens.+ *+ * `quality` (focus − exposure) is what the usability floor tests, NOT `score`+ * — otherwise the free recency bonus on the last candidate could lift a black+ * frame over the floor.+ */++import sharp from 'sharp';++// Tail window the candidates are decoded from, and how densely. ~12 frames+// across the final 1.75s: dense enough that a blur burst doesn't cover every+// candidate, sparse enough that the decode stays well under a second.+export const TAIL_WINDOW_SECONDS = 1.75;+export const CANDIDATE_FPS = 7;+export const MAX_CANDIDATES = 12;++// 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.+export const FOCUS_SCALE = 20000;+export const EXPOSURE_WEIGHT = 0.6;+export const RECENCY_WEIGHT = 0.15;+// Below this, the whole tail is unusable (black, or uniformly featureless) and+// the caller should degrade rather than anchor on it.+export const USABLE_QUALITY_FLOOR = 0.05;++const clamp01 = (n) => (n < 0 ? 0 : (n > 1 ? 1 : n));++const isFrame = (frame) => !!frame+ && Number.isInteger(frame.width) && Number.isInteger(frame.height)+ && frame.width > 0 && frame.height > 0+ && frame.data?.length >= frame.width * frame.height;++/**+ * Variance of the horizontal + vertical first differences over a raw+ * single-channel buffer. Higher = sharper. Both difference sets are pooled+ * into one sample population so a frame blurred along only one axis (the+ * common camera-pan case) still scores low.+ */+export function gradientVariance(frame) {+ if (!isFrame(frame)) return 0;+ const { width, height, data } = frame;+ let sum = 0;+ let sumSq = 0;+ let n = 0;+ for (let y = 0; y < height; y++) {+ const row = y * width;+ for (let x = 0; x < width; x++) {+ const i = row + x;+ if (x + 1 < width) {+ const dx = data[i + 1] - data[i];+ sum += dx; sumSq += dx * dx; n++;+ }+ if (y + 1 < height) {+ const dy = data[i + width] - data[i];+ sum += dy; sumSq += dy * dy; n++;+ }+ }+ }+ if (!n) return 0;+ const mean = sum / n;+ return Math.max(0, sumSq / n - mean * mean);+}++/** Mean luma of a raw single-channel buffer, normalized to 0..1. */+export function meanLuma(frame) {+ if (!isFrame(frame)) return 0;+ const { width, height, data } = frame;+ const count = width * height;+ let sum = 0;+ for (let i = 0; i < count; i++) sum += data[i];+ return sum / count / 255;+}++/**+ * Score one decoded frame. `recency` is 0 for the oldest candidate in the+ * window and 1 for the newest; a single candidate is treated as newest.+ *+ * Returns every component, not just the total, so a caller can log WHY a tail+ * was rejected instead of just that it was.+ */+export function scoreFrame(frame, { recency = 1 } = {}) {+ const variance = gradientVariance(frame);+ const focus = clamp01(Math.log1p(variance) / Math.log1p(FOCUS_SCALE));+ const luma = meanLuma(frame);+ // Distance from mid-grey, normalized so pure black and pure white both hit 1.+ const exposurePenalty = clamp01(Math.abs(luma - 0.5) / 0.5);+ const r = clamp01(Number.isFinite(recency) ? recency : 0);+ const quality = focus - EXPOSURE_WEIGHT * exposurePenalty;+ return {+ focus,+ luma,+ exposurePenalty,+ recency: r,+ quality,+ score: quality + RECENCY_WEIGHT * r,+ usable: quality >= USABLE_QUALITY_FLOOR,+ };+}++/**+ * Decode an image file to a raw greyscale frame. Returns null on ANY decode+ * failure — a candidate ffmpeg wrote partially (or not at all) is simply not a+ * candidate, and must never abort a render the user already paid GPU time for.+ */+export async function decodeGreyscaleFrame(path, { sharpImpl = sharp } = {}) {+ const decoded = await sharpImpl(path).greyscale().raw()+ .toBuffer({ resolveWithObject: true })+ .catch(() => null);+ if (!decoded?.info) return null;+ const { width, height } = decoded.info;+ const frame = { width, height, data: decoded.data };+ return isFrame(frame) ? frame : null;+}++/**+ * 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.+ */+export async function pickBestFrame(paths, { sharpImpl = sharp } = {}) {+ const list = Array.isArray(paths) ? paths.filter((p) => typeof p === 'string' && p) : [];+ if (!list.length) return null;+ let best = null;+ // 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++) {+ // eslint-disable-next-line no-await-in-loop+ const frame = await decodeGreyscaleFrame(list[i], { sharpImpl });+ if (!frame) continue;+ const recency = list.length === 1 ? 1 : i / (list.length - 1);+ const scored = scoreFrame(frame, { recency });+ if (!scored.usable) continue;+ if (!best || scored.score > best.score) best = { path: list[i], index: i, ...scored };+ }+ return best;+}diff --git a/server/lib/frameQuality.test.js b/server/lib/frameQuality.test.jsnew file mode 100644index 0000000000..60999a8017--- /dev/null+++ b/server/lib/frameQuality.test.js@@ -0,0 +1,182 @@+import { describe, it, expect, vi } from 'vitest';+import {+ gradientVariance, meanLuma, scoreFrame, pickBestFrame, decodeGreyscaleFrame,+ RECENCY_WEIGHT, USABLE_QUALITY_FLOOR,+} from './frameQuality.js';++// Deterministic synthetic frames — a real clip's tail can't be checked into+// the repo, and the scorer only ever sees a raw single-channel buffer anyway.+const makeFrame = (width, height, fn) => ({+ width,+ height,+ data: Uint8Array.from({ length: width * height }, (_, i) => fn(i % width, Math.floor(i / width))),+});++// Seeded LCG so "noise" is byte-identical on every run and in CI.+const seededNoise = (width, height, seed = 1) => {+ let s = seed;+ return makeFrame(width, height, () => {+ s = (s * 1103515245 + 12345) & 0x7fffffff;+ return Math.floor((s / 0x7fffffff) * 256);+ });+};++// Box-blur the same pattern: identical exposure, strictly less high-frequency+// detail — which is exactly the motion-blur case the anchor picker exists for.+const boxBlur = (frame, radius = 2) => makeFrame(frame.width, frame.height, (x, y) => {+ let total = 0;+ let count = 0;+ for (let dy = -radius; dy <= radius; dy++) {+ for (let dx = -radius; dx <= radius; dx++) {+ const nx = x + dx;+ const ny = y + dy;+ if (nx >= 0 && nx < frame.width && ny >= 0 && ny < frame.height) {+ total += frame.data[ny * frame.width + nx];+ count++;+ }+ }+ }+ return Math.round(total / count);+});++const SHARP = seededNoise(48, 48);+const BLURRED = boxBlur(SHARP);+const BLACK = makeFrame(48, 48, () => 0);+const WHITE = makeFrame(48, 48, () => 255);+const FLAT_GREY = makeFrame(48, 48, () => 128);++describe('gradientVariance', () => {+ it('ranks a sharp frame above its blurred twin', () => {+ expect(gradientVariance(SHARP)).toBeGreaterThan(gradientVariance(BLURRED));+ });++ it('is zero for a flat frame and for degenerate input', () => {+ expect(gradientVariance(FLAT_GREY)).toBe(0);+ expect(gradientVariance(null)).toBe(0);+ // Buffer shorter than width*height — a truncated decode, not a frame.+ expect(gradientVariance({ width: 8, height: 8, data: new Uint8Array(4) })).toBe(0);+ });+});++describe('meanLuma', () => {+ it('normalizes to 0..1', () => {+ expect(meanLuma(BLACK)).toBe(0);+ expect(meanLuma(WHITE)).toBe(1);+ expect(meanLuma(FLAT_GREY)).toBeCloseTo(128 / 255, 5);+ });+});++describe('scoreFrame', () => {+ it('scores a sharp frame well above a blurred one at equal recency', () => {+ const sharp = scoreFrame(SHARP, { recency: 0 });+ const blurred = scoreFrame(BLURRED, { recency: 0 });+ expect(sharp.focus).toBeGreaterThan(blurred.focus);+ expect(sharp.score).toBeGreaterThan(blurred.score);+ // The sharp/blur gap must exceed the whole recency budget, or a blurred+ // frame at the cut would outrank a clean one earlier in the window.+ expect(sharp.score - blurred.score).toBeGreaterThan(RECENCY_WEIGHT);+ expect(sharp.usable).toBe(true);+ });++ it('rejects a fade-to-black frame even with the full recency bonus', () => {+ const black = scoreFrame(BLACK, { recency: 1 });+ expect(black.exposurePenalty).toBe(1);+ expect(black.quality).toBeLessThan(USABLE_QUALITY_FLOOR);+ expect(black.usable).toBe(false);+ });++ it('rejects a blown highlight the same way it rejects black', () => {+ expect(scoreFrame(WHITE, { recency: 1 }).usable).toBe(false);+ });++ it('rejects a well-exposed but featureless frame', () => {+ // Perfect exposure alone must not qualify — a flat grey carries nothing+ // for the next chunk to condition on.+ const flat = scoreFrame(FLAT_GREY, { recency: 1 });+ expect(flat.exposurePenalty).toBeLessThan(0.01);+ expect(flat.usable).toBe(false);+ });++ it('breaks a tie between identical frames in favour of the later one', () => {+ const early = scoreFrame(SHARP, { recency: 0 });+ const late = scoreFrame(SHARP, { recency: 1 });+ expect(late.score).toBeGreaterThan(early.score);+ expect(late.score - early.score).toBeCloseTo(RECENCY_WEIGHT, 10);+ });++ it('clamps an out-of-range or non-finite recency instead of skewing the score', () => {+ expect(scoreFrame(SHARP, { recency: 5 }).recency).toBe(1);+ expect(scoreFrame(SHARP, { recency: -1 }).recency).toBe(0);+ expect(scoreFrame(SHARP, { recency: NaN }).recency).toBe(0);+ });+});++// ─── candidate selection ─────────────────────────────────────────────────────++// Minimal sharp stand-in: maps a path to a canned raw greyscale decode, or+// throws for paths meant to model a partial/absent file.+const fakeSharp = (byPath) => (path) => ({+ greyscale() { return this; },+ raw() { return this; },+ async toBuffer() {+ const frame = byPath[path];+ if (!frame) throw new Error(`ENOENT: ${path}`);+ return { data: Buffer.from(frame.data), info: { width: frame.width, height: frame.height } };+ },+});++describe('decodeGreyscaleFrame', () => {+ it('returns null on a decode failure rather than throwing', async () => {+ const sharpImpl = fakeSharp({});+ await expect(decodeGreyscaleFrame('/tmp/missing.png', { sharpImpl })).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'];+ const sharpImpl = fakeSharp({ '/t/a.png': BLURRED, '/t/b.png': SHARP, '/t/c.png': BLURRED });+ const best = await pickBestFrame(paths, { sharpImpl });+ expect(best).toMatchObject({ path: '/t/b.png', index: 1 });+ });++ it('prefers the later of two comparably clean candidates', async () => {+ const paths = ['/t/a.png', '/t/b.png'];+ const sharpImpl = fakeSharp({ '/t/a.png': SHARP, '/t/b.png': SHARP });+ const best = await pickBestFrame(paths, { sharpImpl });+ expect(best.index).toBe(1);+ expect(best.recency).toBe(1);+ });++ it('returns null when every candidate is unusable', async () => {+ const paths = ['/t/a.png', '/t/b.png'];+ const sharpImpl = fakeSharp({ '/t/a.png': BLACK, '/t/b.png': BLACK });+ await expect(pickBestFrame(paths, { sharpImpl })).resolves.toBeNull();+ });++ it('returns null when nothing decodes, and never throws', async () => {+ const sharpImpl = fakeSharp({});+ await expect(pickBestFrame(['/t/a.png'], { sharpImpl })).resolves.toBeNull();+ await expect(pickBestFrame([], { sharpImpl })).resolves.toBeNull();+ await expect(pickBestFrame(null, { sharpImpl })).resolves.toBeNull();+ });++ it('skips undecodable candidates but still picks from the rest', async () => {+ const paths = ['/t/a.png', '/t/gone.png', '/t/c.png'];+ const sharpImpl = fakeSharp({ '/t/a.png': SHARP, '/t/c.png': BLURRED });+ const best = await pickBestFrame(paths, { sharpImpl });+ expect(best.path).toBe('/t/a.png');+ });++ it('treats a lone candidate as the newest frame', async () => {+ const sharpImpl = fakeSharp({ '/t/only.png': SHARP });+ const best = await pickBestFrame(['/t/only.png'], { sharpImpl });+ expect(best).toMatchObject({ index: 0, recency: 1 });+ });++ it('does not call sharp for non-string entries', async () => {+ const impl = vi.fn(fakeSharp({ '/t/a.png': SHARP }));+ await pickBestFrame(['/t/a.png', null, '', undefined], { sharpImpl: impl });+ expect(impl).toHaveBeenCalledTimes(1);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex eaf8c74734..d844153b00 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -207,6 +207,7 @@ export * from './hostShutdown.js';export * from './execGit.js';export * from './ffmpeg.js';export * from './ffmpegRenderGuard.js';+export * from './frameQuality.js';export * from './gitArgs.js';export * from './gitCommitProbe.js';export * from './gitForge.js';diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex fea97d9a0f..75944b6a53 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 } 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';@@ -33,6 +33,9 @@ import {extractEvaluationFrames, probeFrameCount, trimVideoFromFrame,hasAudioStream, buildTrimConcatArgs, bt709TagFilter,} from '../../lib/ffmpeg.js';+import {+ TAIL_WINDOW_SECONDS, CANDIDATE_FPS, MAX_CANDIDATES, pickBestFrame,+} from '../../lib/frameQuality.js';import {resolveContextFrames, resolveContinuityStrategy, extendLatentFrames,contextPrefixFrames, tailWindowStartFrame,@@ -2591,8 +2594,61 @@ async function setHistoryItemsHidden(ids, hidden) {}).catch(() => {});}-// Extract the last frame of a video as a PNG into data/images/ — used to-// chain a clip into Imagine for "continue from last frame" remixing.+// Decode the tail-window candidates for `extractLastFrame` into a temp dir and+// return their paths in timeline order (oldest first).+//+// One ffmpeg pass: seek to TAIL_WINDOW_SECONDS before EOF, decimate to+// CANDIDATE_FPS, and let the image2 muxer write numbered PNGs. A clip shorter+// than the window simply yields fewer files — the caller degrades to whatever+// exists. Returns [] on any failure; a scan that can't run must never abort a+// render the user already paid GPU time for.+async function decodeTailCandidates(ffmpeg, videoPath, candidateDir) {+ // Clear first: a crashed prior run can leave a longer numbered run behind,+ // and the by-name enumeration below would read those stale frames as this+ // clip's candidates.+ 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, [+ '-sseof', `-${TAIL_WINDOW_SECONDS}`, '-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();+ });+ });+ // 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+ // frames, and the scorer rejects whatever didn't decode.+ const paths = [];+ for (let i = 1; i <= MAX_CANDIDATES; i++) {+ const p = join(candidateDir, `cand-${String(i).padStart(3, '0')}.png`);+ if (!existsSync(p)) break;+ paths.push(p);+ }+ return paths;+}++// Extract a continuation anchor frame from the tail of a video as a PNG into+// data/images/ — used to chain a clip into the next render, and to feed the+// "continue from last frame" remix UX.+//+// The anchor is CHOSEN, not seeked to: several frames from the final+// TAIL_WINDOW_SECONDS are decoded and scored on focus, exposure, and recency+// (see lib/frameQuality.js), and the winner is installed. A single `-sseof`+// seek returns whichever frame lands first after the seek, which on+// motion-heavy local output is routinely a motion-blurred or mid-fade frame —+// and in a multi-chunk chain the next chunk inherits that blur as the scene's+// actual content, compounding through every subsequent hop.+//+// When no candidate clears the usability floor (a genuinely black or+// featureless tail), this falls back to the original single-seek behavior and+// says so: a degraded anchor still beats failing the chain.export async function extractLastFrame(historyId) {// Keep this service safe for callers outside the route layer too. Shared// gallery uploads deliberately use `upload-<uuid8>` ids, while generated@@ -2620,7 +2676,12 @@ export async function extractLastFrame(historyId) {if (typeof item.id !== 'string' || (!UUID_RE.test(item.id) && !UPLOADED_HISTORY_ID_RE.test(item.id))) {throw new ServerError('Invalid history id', { status: 400, code: 'VALIDATION_ERROR' });}- const frameFilename = `lastframe-${item.id}.png`;+ // `anchor-` rather than the historical `lastframe-`: the file's contents are+ // now policy-dependent (a scored pick, not a fixed seek), so reusing the old+ // name would serve every pre-change file forever from the cache hit below+ // and make the improvement invisible on any clip a user already continued.+ // No migration needed — the new name simply misses once per clip.+ const frameFilename = `anchor-${item.id}.png`;const framePath = join(PATHS.images, frameFilename);// Cache hit: ffmpeg-extracted frames are deterministic for a given video,// so a file already on disk is reusable. UI clicks "Continue" repeatedly@@ -2643,7 +2704,12 @@ export async function extractLastFrame(historyId) {// calls this too so frames extracted before this change get backfilled.// `wx` flag makes the create-if-missing race-free — EEXIST is the no-op.const sidecarPath = join(PATHS.images, frameFilename.replace('.png', '.metadata.json'));- const writeSidecar = async () => {+ // `extractedAt` names the offset the anchor actually came from, so the+ // gallery record says what it is instead of the fixed string 'last-frame'+ // (which was never true — the old seek landed somewhere in the final second).+ // The cache-hit and fallback paths genuinely don't know the offset, so they+ // keep the legacy value.+ const writeSidecar = async (extractedAt = 'last-frame') => {const meta = {filename: frameFilename,prompt: item.prompt,@@ -2654,7 +2720,7 @@ export async function extractLastFrame(historyId) {seed: item.seed,extractedFromVideoId: item.id,extractedFromVideoFilename: item.filename,- extractedAt: 'last-frame',+ extractedAt,kind: 'extracted-frame',createdAt: new Date().toISOString(),};@@ -2668,6 +2734,44 @@ export async function extractLastFrame(historyId) {}if (cachedSize === 0) await unlink(framePath).catch(() => {});+ // ── Scored pick over the tail window ──────────────────────────────────────+ // 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)+ .catch((err) => {+ console.log(`⚠️ Anchor candidate scan failed: ${err.message}`);+ return [];+ });+ const best = candidates.length+ ? await pickBestFrame(candidates).catch((err) => {+ console.log(`⚠️ Anchor scoring failed: ${err.message}`);+ return null;+ })+ : null;+ const installed = best+ ? await copyFile(best.path, framePath).then(() => true).catch((err) => {+ console.log(`⚠️ Anchor install failed: ${err.message}`);+ return false;+ })+ : false;+ // 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.+ await rm(candidateDir, { recursive: true, force: true }).catch(() => {});++ if (installed) {+ // Candidate i sits i/CANDIDATE_FPS into a window that starts+ // TAIL_WINDOW_SECONDS before EOF, so this is its offset from the end.+ const offset = TAIL_WINDOW_SECONDS - 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) {+ console.log(`⚠️ No usable anchor among ${candidates.length} tail candidates for ${item.id.slice(0, 8)} — falling back to the end seek`);+ }+return new Promise((resolve, reject) => {// -sseof -1.0 seeks 1s before end. The previous -0.1 was too tight on// videos with audio (B-frames + AV mux push the last keyframe earlier@@ -2693,7 +2797,7 @@ export async function extractLastFrame(historyId) {return reject(new ServerError('Failed to extract last frame', { status: 500, code: 'FFMPEG_FAILED' }));}await writeSidecar();- console.log(`🎞️ Extracted last frame: ${frameFilename}`);+ console.log(`🎞️ Anchor frame via end-seek fallback: ${frameFilename}`);resolve({ filename: frameFilename, path: `/data/images/${frameFilename}` });} catch (err) {reject(err instanceof ServerError ? err : new ServerError(`Failed to extract last frame: ${err.message}`, { status: 500, code: 'FFMPEG_FAILED' }));diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex c382dd3ac4..0e1a07b8f7 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -236,9 +236,27 @@ vi.mock('../../lib/hfCache.js', () => ({},}));+// Default: every path exists at 1000 bytes. `missOnce` lets one test drive a+// cache MISS on a path that then exists after ffmpeg writes it — which is the+// only way to reach extractLastFrame's extraction path at all, since a+// stat-everything mock otherwise short-circuits on the cache hit.+const fsState = vi.hoisted(() => ({ missOnce: [] }));vi.mock('fs', () => ({existsSync: vi.fn(() => true),- statSync: vi.fn(() => ({ size: 1000 })),+ statSync: vi.fn((p) => {+ const i = fsState.missOnce.findIndex((frag) => String(p).includes(frag));+ if (i >= 0) { fsState.missOnce.splice(i, 1); return undefined; }+ return { size: 1000 };+ }),+}));++// Anchor scoring. The scorer itself is unit-tested in lib/frameQuality.test.js;+// stub the pick here so these tests drive the two outcomes extractLastFrame+// branches on — a scored winner, and a tail with nothing usable in it.+const anchorPick = vi.hoisted(() => ({ best: null }));+vi.mock('../../lib/frameQuality.js', async (importOriginal) => ({+ ...await importOriginal(),+ pickBestFrame: vi.fn(async () => anchorPick.best),}));// Whether the installed MiniMax H3 checkout can apply LoRAs to its quantized@@ -269,6 +287,7 @@ vi.mock('fs/promises', () => ({unlink: vi.fn(async () => {}),writeFile: vi.fn(async () => {}),copyFile: vi.fn(async () => {}),+ rm: vi.fn(async () => {}),// Unused by the code under test, but lib/ffmpeg.js imports it and the ffmpeg// mock above pulls the real module in for buildTrimConcatArgs.rename: vi.fn(async () => {}),@@ -329,22 +348,98 @@ beforeEach(async () => {afterEach(() => {settingsState.acceptedModelTerms = [];+ fsState.missOnce = [];+ anchorPick.best = null;vi.clearAllMocks();});-describe('extractLastFrame — shared-gallery uploads', () => {- it('accepts an uploaded gallery history id', async () => {+describe('extractLastFrame — anchor selection', () => {+ const ID = 'upload-ab12cd34';+ const ANCHOR = 'anchor-upload-ab12cd34.png';++ const seedHistory = async () => {const { readJSONFile } = await import('../../lib/fileUtils.js');- vi.mocked(readJSONFile).mockResolvedValueOnce([{- id: 'upload-ab12cd34',- filename: 'upload-ab12cd34.mp4',+ vi.mocked(readJSONFile).mockResolvedValue([{+ id: ID,+ filename: `${ID}.mp4`,prompt: 'example',}]);+ };- await expect(extractLastFrame('upload-ab12cd34')).resolves.toMatchObject({- filename: 'lastframe-upload-ab12cd34.png',- path: '/data/images/lastframe-upload-ab12cd34.png',+ const ffmpegSpawns = async () => {+ const { spawn } = await import('../../lib/childProcess.js');+ return vi.mocked(spawn).mock.calls.map(([, args]) => (Array.isArray(args) ? args : []));+ };++ it('accepts an uploaded gallery history id and serves the cached anchor', async () => {+ await seedHistory();+ // Cache hit (statSync reports a non-empty file) — no ffmpeg at all.+ await expect(extractLastFrame(ID)).resolves.toEqual({+ filename: ANCHOR,+ path: `/data/images/${ANCHOR}`,+ });+ expect(await ffmpegSpawns()).toHaveLength(0);+ });++ it('scores the tail window and installs the winning candidate', async () => {+ await seedHistory();+ fsState.missOnce = [ANCHOR];+ anchorPick.best = {+ path: join(tmpdir(), `anchorcand-${ID}`, 'cand-003.png'),+ index: 2,+ focus: 0.81,+ quality: 0.79,+ score: 0.82,+ usable: true,+ };+ 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.+ expect(vi.mocked(copyFile)).toHaveBeenCalledWith(+ anchorPick.best.path,+ join(MOCK_PATHS.images, ANCHOR),+ );+ // 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();+ expect(spawns).toHaveLength(1);+ expect(spawns[0]).toEqual(expect.arrayContaining(['-sseof', '-1.75', '-vf', 'fps=7']));+ expect(spawns[0]).not.toContain('-vframes');+ // Temp candidates are cleaned up rather than left in tmpdir.+ expect(vi.mocked(rm)).toHaveBeenCalledWith(+ join(tmpdir(), `anchorcand-${ID}`),+ { recursive: true, force: true },+ );+ // Sidecar names the offset the anchor actually came from — candidate 3 of+ // a 7fps window that starts 1.75s before EOF sits 1.46s from the end.+ const sidecar = JSON.parse(vi.mocked(writeFile).mock.calls.at(-1)[1]);+ expect(sidecar).toMatchObject({ filename: ANCHOR, extractedAt: '-1.46s' });+ });++ it('falls back to the end seek when no candidate is usable', async () => {+ await seedHistory();+ fsState.missOnce = [ANCHOR];+ anchorPick.best = null;+ const { copyFile, writeFile } = await import('fs/promises');++ await expect(extractLastFrame(ID)).resolves.toEqual({+ filename: ANCHOR,+ path: `/data/images/${ANCHOR}`,+ });++ expect(vi.mocked(copyFile)).not.toHaveBeenCalled();+ const spawns = await ffmpegSpawns();+ expect(spawns).toHaveLength(2);+ expect(spawns[1]).toEqual(expect.arrayContaining(['-sseof', '-1.0', '-vframes', '1']));+ // The fallback genuinely doesn't know which frame it got, so the sidecar+ // keeps the legacy value rather than inventing an offset.+ const sidecar = JSON.parse(vi.mocked(writeFile).mock.calls.at(-1)[1]);+ expect(sidecar).toMatchObject({ extractedAt: 'last-frame' });});});@@ -796,6 +891,33 @@ describe('generateChainedVideo — continuation strategy (context window vs lastexpect(flagValue(renders[1], '--image')).toBeTruthy();});+ it.each([+ ['a scored anchor', { path: join(tmpdir(), 'cand-006.png'), index: 5, focus: 0.7, quality: 0.7, score: 0.8, usable: true }],+ ['the end-seek fallback', null],+ ])('stages a continuation still for the next frame-hop chunk via %s', async (_label, best) => {+ // The hop must survive BOTH anchor outcomes. A scoring failure degrades to+ // the old single-seek behavior — it must never leave chunk 1 with no image,+ // which would render it from the prompt alone and break the chain.+ anchorPick.best = best;+ // One hop → one anchor cache check; miss it so extraction actually runs.+ fsState.missOnce = ['anchor-'];+ const { copyFile } = await import('fs/promises');+ vi.mocked(copyFile).mockClear();++ const { renders, innerJobIds } = await runChain({+ modelId: 'ltx23_unified',+ mode: 'extend',+ extendFromVideoPath: join(MOCK_PATHS.videos, 'original-video.mp4'),+ }, 2);++ expect(flagValue(renders[1], '--image')).toBeTruthy();+ // A scored winner is installed under the new cache name; the fallback lets+ // ffmpeg write that path directly, so there is no copy.+ const installedAnchor = vi.mocked(copyFile).mock.calls+ .some(([, dest]) => dest === join(MOCK_PATHS.images, `anchor-${innerJobIds[0]}.png`));+ expect(installedAnchor).toBe(!!best);+ });+it('keeps the first chunk of an extend chain whole, conditioned on the user source clip', async () => {// In an extend chain chunk 0's output is `user clip + extension`, and the// user clip belongs in the result exactly once — here. Trimming it would