From a2f926708901f1fc52c18888db103cd768537824 Mon Sep 17 00:00:00 2001 From: Michael Wang Date: Sun, 15 Nov 2026 17:10:12 +0000 Subject: [PATCH] fix: snapshot escapes composition text in its output; stills sweep the transcode cache (#7832) * fix(cli): snapshot shows control characters in composition text as escapes * fix(studio-server): making or serving a still sweeps the transcode cache --- packages/cli/src/commands/snapshot.test.ts | 18 +++++++++++++ packages/cli/src/commands/snapshot.ts | 25 +++++++++-------- .../src/helpers/proxyTranscoder.test.ts | 27 +++++++++++++++++++ .../src/helpers/proxyTranscoder.ts | 13 ++++++--- scripts/package-size-budgets.json | 4 +-- 5 files changed, 71 insertions(+), 16 deletions(-) diff --git a/packages/cli/src/commands/snapshot.test.ts b/packages/cli/src/commands/snapshot.test.ts index 306436bd6d..185e944aa4 100644 --- a/packages/cli/src/commands/snapshot.test.ts +++ b/packages/cli/src/commands/snapshot.test.ts @@ -988,6 +988,24 @@ describe("extractVideoFrameToBuffer", () => { }, ); + it.skipIf(noProbe)( + "prints a video's name in its warning with control characters shown as escapes", + async () => { + const dir = mkdtempSync(join(tmpdir(), "hf-snapshot-escape-")); + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + try { + const named = join(dir, "clip\u001b]0;x\u0007.mp4"); + expect(await extractVideoFrameOrWarn([], named, 1)).toBeNull(); + const out = warn.mock.calls.map((call) => String(call[0])).join("\n"); + expect(out).toContain("clip\\x1b]0;x\\x07.mp4"); + expect(out).not.toContain("\u0007"); + } finally { + warn.mockRestore(); + rmSync(dir, { recursive: true, force: true }); + } + }, + ); + it.skipIf(noProbe)( "selects exact frame times in a fragmented MP4 whose start rounds down", async () => { diff --git a/packages/cli/src/commands/snapshot.ts b/packages/cli/src/commands/snapshot.ts index 7926767637..fdcd2db983 100644 --- a/packages/cli/src/commands/snapshot.ts +++ b/packages/cli/src/commands/snapshot.ts @@ -101,6 +101,7 @@ import { normalizeErrorMessage, atStep } from "../utils/errorMessage.js"; import { describeSharpLoadFailure } from "../utils/sharpLoadFailure.js"; import { serveStaticProjectHtml } from "../utils/staticProjectServer.js"; import { c } from "../ui/colors.js"; +import { terminalText } from "../utils/terminalText.js"; import { writeCaptureFileSync } from "../capture/captureFile.js"; import { runCancellableProcess } from "../utils/cancellableProcess.js"; import { findFFmpeg, findFFprobe, getFFmpegInstallHint } from "../browser/ffmpeg.js"; @@ -829,7 +830,7 @@ export async function frameOrWarn( } catch (error) { if (!(error instanceof FrameExtractError)) throw error; warnings.push(error.message); - console.warn(` ${c.warn("⚠")} ${error.message}`); + console.warn(` ${c.warn("⚠")} ${terminalText(error.message)}`); return null; } } @@ -1010,7 +1011,7 @@ export async function captureSnapshots( : null; if (swallowed) { warnings.push(swallowed); - console.warn(` ${c.warn("⚠")} ${swallowed}`); + console.warn(` ${c.warn("⚠")} ${terminalText(swallowed)}`); } const server = await serveCapturePage(projectDir, html, opts.autoProxy); const fps = compositionFps(html); @@ -1074,7 +1075,7 @@ export async function captureSnapshots( if (fontReport.unused.length > 0) parts.push(`${fontReport.unused.length} unused`); log(`\n ${c.dim("Fonts:")} ${parts.join(", ")}`); if (fontReport.errored.length > 0) { - log(` ${c.error("Fonts FAILED:")} ${fontReport.errored.join(", ")}`); + log(` ${c.error("Fonts FAILED:")} ${terminalText(fontReport.errored.join(", "))}`); } } @@ -1226,7 +1227,7 @@ export async function captureSnapshots( if (project?.refused) { const message = `${relative(projectDir, project.file)} is not media: a document, a pipe or device, or a playlist naming files outside its folder`; warnings.push(message); - console.warn(` ${c.warn("⚠")} ${message}`); + console.warn(` ${c.warn("⚠")} ${terminalText(message)}`); } return project; }); @@ -1630,7 +1631,7 @@ function warnUnsettledImages(images: UnsettledImages, time: number, warnings: st if (sources.length === 0) continue; const message = `${sources.length} image(s) ${what} at ${time}s, so the frame may be missing them: ${sources.join(", ")}`; warnings.push(message); - console.warn(` ${c.warn("⚠")} ${message}`); + console.warn(` ${c.warn("⚠")} ${terminalText(message)}`); } } @@ -1747,19 +1748,19 @@ function printReview( log: (message: string) => void, ): void { const beats = review.plan.beats.map( - (beat) => `${formatSnapshotTimestamp(beat.time)} ${beat.label}`, + (beat) => `${formatSnapshotTimestamp(beat.time)} ${terminalText(beat.label)}`, ); log(` Beat sheet (settled frame per scene): ${sheets.beats.join(", ") || "none"}`); log(` ${c.dim(beats.join(" · "))}`); review.plan.seams.forEach((seam, index) => { - const sides = `${seam.from ?? "start"} -> ${seam.to ?? "end"}`; + const sides = terminalText(`${seam.from ?? "start"} -> ${seam.to ?? "end"}`); const strip = sheets.seams[index] ?? "not written"; log(` Seam ${index + 1} at ${formatSnapshotTimestamp(seam.time)} (${sides}): ${strip}`); }); log( ` Phone sheet (beats at ${REVIEW_PHONE_WIDTH} px wide): ${sheets.phone.join(", ") || "none"}`, ); - for (const note of review.plan.notes) log(` ${c.dim(note)}`); + for (const note of review.plan.notes) log(` ${c.dim(terminalText(note))}`); } export default defineCommand({ @@ -1941,7 +1942,9 @@ export default defineCommand({ camera && (camera.yaw !== 0 || camera.pitch !== 0) ? ` ${c.dim(`(angle yaw ${camera.yaw}° pitch ${camera.pitch}°)`)}` : ""; - log(`${c.accent("◆")} Capturing ${label} from ${c.accent(project.name)}${angleLabel}`); + log( + `${c.accent("◆")} Capturing ${label} from ${c.accent(terminalText(project.name))}${angleLabel}`, + ); let managedSnapshotDir: string | undefined; let exitCode = 0; @@ -2133,7 +2136,7 @@ export default defineCommand({ } } catch (descErr) { const msg = normalizeErrorMessage(descErr); - log(` ${c.dim(`--describe failed: ${msg}`)}`); + log(` ${c.dim(`--describe failed: ${terminalText(msg)}`)}`); } } if (asJson) { @@ -2151,7 +2154,7 @@ export default defineCommand({ if (err instanceof CliRuntimeError && err.result.presented) throw err; const msg = failureMessage(err); if (asJson) console.log(JSON.stringify(withMeta(jsonFailure("runtime_error", msg)), null, 2)); - else console.error(`\n${c.error("✗")} Snapshot failed: ${msg}`); + else console.error(`\n${c.error("✗")} Snapshot failed: ${terminalText(msg)}`); failCommand(); } finally { if (managedSnapshotDir) diff --git a/packages/studio-server/src/helpers/proxyTranscoder.test.ts b/packages/studio-server/src/helpers/proxyTranscoder.test.ts index fc85e68126..283372371d 100644 --- a/packages/studio-server/src/helpers/proxyTranscoder.test.ts +++ b/packages/studio-server/src/helpers/proxyTranscoder.test.ts @@ -2034,6 +2034,33 @@ describe("resolveStill", () => { 60_000, ); + it.skipIf(!canStill)( + "sweeps the cache when it makes a still, so stills alone cannot grow it without bound", + async () => { + vi.resetModules(); + vi.doUnmock("./mediaMetadata.js"); + const { resolveStill, CACHE_DIR_NAME } = await import("./proxyTranscoder.js"); + const projectDir = tmpProject(); + const clip = join(projectDir, "clip.mp4"); + execFileSync(realFfmpeg!, [ + ...["-v", "error", "-f", "lavfi", "-i", "testsrc2=s=320x180:r=25:d=2"], + ...["-c:v", "libx264", "-pix_fmt", "yuv420p", clip], + ]); + const cacheDir = join(projectDir, CACHE_DIR_NAME); + mkdirSync(cacheDir, { recursive: true }); + const idle = join(cacheDir, `${"a".repeat(64)}.jpg`); + writeFileSync(idle, "old still"); + const longAgo = new Date(Date.now() - 31 * 24 * 60 * 60 * 1000); + utimesSync(idle, longAgo, longAgo); + + const made = await resolveStill(projectDir, clip, 1); + + expect(existsSync(made)).toBe(true); + expect(existsSync(idle)).toBe(false); + }, + 60_000, + ); + async function stillSetup() { const spy = createSpawnSpy(); const { resolveStill } = await loadModule(spy.spawn, FFMPEG_PATH); diff --git a/packages/studio-server/src/helpers/proxyTranscoder.ts b/packages/studio-server/src/helpers/proxyTranscoder.ts index c39d75c680..9fb0749ddb 100644 --- a/packages/studio-server/src/helpers/proxyTranscoder.ts +++ b/packages/studio-server/src/helpers/proxyTranscoder.ts @@ -349,9 +349,11 @@ function forget(job: ProxyJob): void { if (inFlight.get(job.cachePath)?.job === job) inFlight.delete(job.cachePath); } -function maintainProxyCache(cacheDir: string, staleTempMs?: number): void { +function maintainProxyCache(cacheDir: string, staleTempMs?: number, justServed?: string): void { + const protectedPaths = new Set([...inFlight.keys(), ...stillsInFlight.keys()]); + if (justServed) protectedPaths.add(justServed); try { - cleanupProxyCache(cacheDir, { protectedPaths: new Set(inFlight.keys()), staleTempMs }); + cleanupProxyCache(cacheDir, { protectedPaths, staleTempMs }); } catch (error) { // Cache maintenance must never turn a playable preview into an error. console.warn( @@ -1169,7 +1171,11 @@ export function resolveStill( const at = Math.max(0, Math.round(atSeconds * 10) / 10); const key = fastCopyKey(source.sourcePath, PROXY_PARAMS_VERSION, `still@${at}`, box); const cachePath = join(source.projectDir, CACHE_DIR_NAME, `${key}${PROXY_STILL_EXTENSION}`); - if (existsSync(cachePath)) return Promise.resolve(cachePath); + if (existsSync(cachePath)) { + markCacheEntryUsed(cachePath); + maintainProxyCache(dirname(cachePath), undefined, cachePath); + return Promise.resolve(cachePath); + } let job = stillsInFlight.get(cachePath); if (!job) { const abandoned = new AbortController(); @@ -1235,6 +1241,7 @@ async function makeStill( } finally { rmSync(tempPath, { force: true }); } + maintainProxyCache(dirname(cachePath), undefined, cachePath); return cachePath; } diff --git a/scripts/package-size-budgets.json b/scripts/package-size-budgets.json index e20616d69f..693b2b3cbb 100644 --- a/scripts/package-size-budgets.json +++ b/scripts/package-size-budgets.json @@ -56,7 +56,7 @@ "unpacked": 26703858 }, "@hyperframes/studio-server": { - "packed": 172000, - "unpacked": 672000 + "packed": 173500, + "unpacked": 676000 } }