Skip to content

Commit c0636d0

Browse files
feat(cli): snapshot --keep redoes one still and leaves the others (#5605)
* feat(cli): snapshot --keep redoes one board still and leaves the others * fix(skills): the board recipe waits for a released snapshot --keep * fix(cli): snapshot --keep refuses two times with one name and replaces linked stills
1 parent 71595dd commit c0636d0

4 files changed

Lines changed: 153 additions & 53 deletions

File tree

‎docs/packages/cli.mdx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -869,6 +869,7 @@ npx hyperframes snapshot my-project --at 1.5,4.3 --against ref.mp4
869869
| `--composition <id>` | Spread `--frames` across the visible interval of the element with this `data-composition-id`. Use one of `--at`, `--range` or `--composition`. |
870870
| `--output, -o` | Where the PNGs go (default: a new `<project>/.hyperframes/artifacts/snapshots/<id>` per run) |
871871
| `--end` / `--no-end` | Always add a readable end-of-timeline frame (default: on). `--no-end` captures only your `--at` times. |
872+
| `--keep` | Add to `--output` instead of clearing it, naming each still for its time: `at-0s.png`, `at-1.5s.png`, `at-12.25s.png` (no trailing zeros). Snapshotting one moment again replaces only that still. No contact sheet. |
872873
| `--zoom` | Crop to a CSS selector or an exact `x,y,w,h` region, using a raised device scale factor. Layout is untouched — never CSS zoom or a resized viewport. A selector that matches nothing is an error. |
873874
| `--against` | A reference video, such as footage you are rebuilding. For every captured time also saves its frame-exact frame (`ref-XX-…png`) and a labelled render / reference pair (`pair-XX-…jpg`). |
874875
| `--zoom-scale` | Pixel density for `--zoom` crops (default 3) |

‎packages/cli/src/commands/snapshot-contactSheet.test.ts‎

Lines changed: 99 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,23 @@
11
import { runCommand } from "citty";
2-
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2+
import {
3+
existsSync,
4+
linkSync,
5+
lstatSync,
6+
mkdirSync,
7+
mkdtempSync,
8+
readFileSync,
9+
readdirSync,
10+
rmSync,
11+
symlinkSync,
12+
writeFileSync,
13+
} from "node:fs";
314
import { tmpdir } from "node:os";
415
import { join } from "node:path";
516
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
617

718
const capture = vi.hoisted(() => ({
819
evaluate: vi.fn(),
9-
screenshot: vi.fn(async ({ path }: { path: string }) => {
10-
const bytes = Buffer.from("captured PNG");
11-
writeFileSync(path, bytes);
12-
return bytes;
13-
}),
20+
screenshot: vi.fn(async () => Buffer.from("captured PNG")),
1421
closeBrowser: vi.fn(async () => undefined),
1522
closeServer: vi.fn(async () => undefined),
1623
seek: vi.fn(async () => undefined),
@@ -43,26 +50,30 @@ import snapshotCommand from "./snapshot.js";
4350
import { historyDeps } from "../utils/historyOwner.js";
4451
import { openProjectHistory } from "@hyperframes/studio-server/history";
4552

53+
/** The page's answers for one run: asset check, duration, ready, then two per frame. */
54+
function primePage(frames: number) {
55+
capture.evaluate
56+
.mockReset()
57+
.mockResolvedValueOnce({ loaded: [], errored: [], unused: [] })
58+
.mockResolvedValueOnce(2)
59+
.mockResolvedValueOnce(true);
60+
for (let i = 0; i < frames; i++) {
61+
capture.evaluate.mockResolvedValueOnce([]).mockResolvedValueOnce(undefined);
62+
}
63+
}
64+
65+
const PROJECT_HTML =
66+
'<html><body><div id="root" data-composition-id="main" data-width="640" data-height="360" data-start="0" data-duration="2">Visible</div><script>window.__timelines = { main: { duration() { return 2; }, seek() {} } };</script></body></html>';
67+
4668
describe("snapshot contact sheet failures", () => {
4769
let project: string;
4870

4971
beforeEach(() => {
5072
vi.resetModules();
5173
vi.clearAllMocks();
5274
project = mkdtempSync(join(tmpdir(), "hf-snapshot-contact-sheet-"));
53-
writeFileSync(
54-
join(project, "index.html"),
55-
'<html><body><div id="root" data-composition-id="main" data-width="640" data-height="360" data-start="0" data-duration="2">Visible</div><script>window.__timelines = { main: { duration() { return 2; }, seek() {} } };</script></body></html>',
56-
);
57-
capture.evaluate
58-
.mockReset()
59-
.mockResolvedValueOnce({ loaded: [], errored: [], unused: [] })
60-
.mockResolvedValueOnce(2)
61-
.mockResolvedValueOnce(true)
62-
.mockResolvedValueOnce([])
63-
.mockResolvedValueOnce(undefined)
64-
.mockResolvedValueOnce([])
65-
.mockResolvedValueOnce(undefined);
75+
writeFileSync(join(project, "index.html"), PROJECT_HTML);
76+
primePage(2);
6677
vi.spyOn(console, "log").mockImplementation(() => undefined);
6778
vi.spyOn(console, "warn").mockImplementation(() => undefined);
6879
vi.spyOn(console, "error").mockImplementation(() => undefined);
@@ -161,20 +172,8 @@ describe("snapshot contact sheet failures", () => {
161172
historyRoot: historyDeps.historyRoot,
162173
ownerWaitMs: 0,
163174
});
164-
capture.screenshot.mockImplementation(async ({ path }: { path: string }) => {
165-
const bytes = Buffer.from("replaced PNG");
166-
writeFileSync(path, bytes);
167-
return bytes;
168-
});
169-
capture.evaluate
170-
.mockReset()
171-
.mockResolvedValueOnce({ loaded: [], errored: [], unused: [] })
172-
.mockResolvedValueOnce(2)
173-
.mockResolvedValueOnce(true)
174-
.mockResolvedValueOnce([])
175-
.mockResolvedValueOnce(undefined)
176-
.mockResolvedValueOnce([])
177-
.mockResolvedValueOnce(undefined);
175+
capture.screenshot.mockImplementation(async () => Buffer.from("replaced PNG"));
176+
primePage(2);
178177
try {
179178
await runCommand(snapshotCommand, args);
180179
for (const [index, time] of ["0.5", "1"].entries()) {
@@ -194,3 +193,70 @@ describe("snapshot contact sheet failures", () => {
194193
}
195194
});
196195
});
196+
197+
describe("snapshot --keep", () => {
198+
let project: string;
199+
let stills: string;
200+
201+
beforeEach(() => {
202+
project = mkdtempSync(join(tmpdir(), "hf-snapshot-keep-"));
203+
stills = join(project, "boards", "stills");
204+
writeFileSync(join(project, "index.html"), PROJECT_HTML);
205+
vi.spyOn(console, "log").mockImplementation(() => undefined);
206+
vi.spyOn(console, "warn").mockImplementation(() => undefined);
207+
});
208+
209+
afterEach(() => {
210+
vi.restoreAllMocks();
211+
rmSync(project, { recursive: true, force: true });
212+
});
213+
214+
async function snapshot(at: string, bytes: string) {
215+
capture.screenshot.mockImplementation(async () => Buffer.from(bytes));
216+
primePage(at.split(",").length);
217+
await runCommand(snapshotCommand, {
218+
rawArgs: [project, "--keep", "--at", at, "--no-end", "--describe", "false", "-o", stills],
219+
});
220+
}
221+
222+
it("redoes one moment and keeps every other still", async () => {
223+
await snapshot("0,0.5,1.5", "first PNG");
224+
await snapshot("0.5", "redo PNG");
225+
226+
expect(readdirSync(stills).sort()).toEqual(["at-0.5s.png", "at-0s.png", "at-1.5s.png"]);
227+
expect(readFileSync(join(stills, "at-0s.png"), "utf8")).toBe("first PNG");
228+
expect(readFileSync(join(stills, "at-0.5s.png"), "utf8")).toBe("redo PNG");
229+
expect(readFileSync(join(stills, "at-1.5s.png"), "utf8")).toBe("first PNG");
230+
expect(existsSync(join(stills, "contact-sheet.jpg"))).toBe(false);
231+
});
232+
233+
it("refuses two times that would share a still, before touching the folder", async () => {
234+
await snapshot("1.5", "first PNG");
235+
capture.screenshot.mockClear();
236+
237+
await expect(snapshot("1.5,1.5004", "second PNG")).rejects.toThrow(
238+
"--keep would name both 1.5 and 1.5004 at-1.5s.png",
239+
);
240+
expect(capture.screenshot).not.toHaveBeenCalled();
241+
expect(readFileSync(join(stills, "at-1.5s.png"), "utf8")).toBe("first PNG");
242+
});
243+
244+
it("replaces a linked still without writing through the link", async () => {
245+
mkdirSync(stills, { recursive: true });
246+
const hardVictim = join(project, "hard-victim.png");
247+
writeFileSync(hardVictim, "hard victim");
248+
linkSync(hardVictim, join(stills, "at-0.5s.png"));
249+
const softVictim = join(project, "soft-victim.png");
250+
writeFileSync(softVictim, "soft victim");
251+
if (process.platform !== "win32") symlinkSync(softVictim, join(stills, "at-1.5s.png"));
252+
253+
await snapshot("0.5,1.5", "new PNG");
254+
255+
expect(readFileSync(hardVictim, "utf8")).toBe("hard victim");
256+
expect(readFileSync(softVictim, "utf8")).toBe("soft victim");
257+
for (const still of ["at-0.5s.png", "at-1.5s.png"]) {
258+
expect(lstatSync(join(stills, still)).isFile()).toBe(true);
259+
expect(readFileSync(join(stills, still), "utf8")).toBe("new PNG");
260+
}
261+
});
262+
});

‎packages/cli/src/commands/snapshot.test.ts‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,10 @@ describe("formatSnapshotTimestamp", () => {
4848
it.each([
4949
[1.12, "1.12s"],
5050
[0.30000000000000004, "0.3s"],
51+
[0, "0s"],
52+
[1.5, "1.5s"],
53+
[12.25, "12.25s"],
54+
[1.5000001, "1.5s"],
5155
])("formats %s without discarding useful precision", (time, expected) => {
5256
expect(formatSnapshotTimestamp(time)).toBe(expected);
5357
});
@@ -76,9 +80,7 @@ describe("tailFrameTime", () => {
7680
describe("transparent snapshot capture", () => {
7781
it("asks Chrome to retain the alpha channel in review PNGs", () => {
7882
const source = readFileSync(new URL("./snapshot.ts", import.meta.url), "utf8");
79-
expect(source).toContain(
80-
'page.screenshot({ path: framePath, type: "png", omitBackground: true })',
81-
);
83+
expect(source).toContain('page.screenshot({ type: "png", omitBackground: true })');
8284
});
8385

8486
it("exposes --proxy/--no-proxy and forwards the override to the static server", () => {
@@ -931,10 +933,7 @@ describe("snapshot composite recapture", () => {
931933
const injection = source.indexOf("await injectVideoFramesBatch(page, updates)");
932934
const visibility = source.indexOf("await syncVideoFrameVisibility(", injection);
933935
const recapture = source.indexOf("await recaptureSnapshotComposite(page)", visibility);
934-
const finalCapture = source.indexOf(
935-
'page.screenshot({ path: framePath, type: "png"',
936-
recapture,
937-
);
936+
const finalCapture = source.indexOf('page.screenshot({ type: "png"', recapture);
938937
expect(injection).toBeGreaterThan(-1);
939938
expect(visibility).toBeGreaterThan(injection);
940939
expect(recapture).toBeGreaterThan(visibility);

‎packages/cli/src/commands/snapshot.ts‎

Lines changed: 47 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import { formatLintFindings } from "../utils/lintFormat.js";
4949
import { normalizeErrorMessage } from "../utils/errorMessage.js";
5050
import { serveStaticProjectHtml } from "../utils/staticProjectServer.js";
5151
import { c } from "../ui/colors.js";
52+
import { writeCaptureFileSync } from "../capture/captureFile.js";
5253
import { runCancellableProcess } from "../utils/cancellableProcess.js";
5354
import { findFFmpeg, findFFprobe, getFFmpegInstallHint } from "../browser/ffmpeg.js";
5455
import { parseAngle, type Camera } from "./motionShotLayout.js";
@@ -100,6 +101,21 @@ export function formatSnapshotTimestamp(time: number): string {
100101
return `${Number(time.toFixed(3))}s`;
101102
}
102103

104+
/** --keep names a still by its millisecond label, so two distinct times may not share one. */
105+
function assertDistinctKeepNames(times: number[]): void {
106+
const timeByLabel = new Map<string, number>();
107+
for (const time of times) {
108+
const label = formatSnapshotTimestamp(time);
109+
const other = timeByLabel.get(label);
110+
if (other !== undefined && other !== time) {
111+
throw new Error(
112+
`--keep would name both ${other} and ${time} at-${label}.png; pass times at least 1 ms apart`,
113+
);
114+
}
115+
timeByLabel.set(label, time);
116+
}
117+
}
118+
103119
/** Shows media by the runtime's visibility rule. A clip held at the composition end, or past the end of a source
104120
* shorter than its slot, samples one nominal 30fps frame inside the source; FFmpeg has no frame at or past its end. */
105121
export function resolveSnapshotVideoFrameTime(input: {
@@ -466,6 +482,8 @@ async function captureSnapshots(
466482
browserGpuMode?: BrowserGpuMode;
467483
/** Reference video: save its frame at each captured time plus a render|reference pair. */
468484
against?: string;
485+
/** Add to outputDir without clearing it; name each still by its time, not its place in the run. */
486+
keep?: boolean;
469487
},
470488
): Promise<string[]> {
471489
const { bundleWithLocalizedFonts } = await import("../utils/bundleWithLocalizedFonts.js");
@@ -604,7 +622,7 @@ async function captureSnapshots(
604622
mkdirSync(snapshotDir, { recursive: true });
605623
try {
606624
const { readdirSync } = await import("node:fs");
607-
for (const file of readdirSync(snapshotDir)) {
625+
for (const file of opts.keep ? [] : readdirSync(snapshotDir)) {
608626
if (/\.(png|jpg|jpeg)$/i.test(file)) {
609627
const path = resolve(snapshotDir, file);
610628
replaced.push(path);
@@ -819,8 +837,10 @@ async function captureSnapshots(
819837
await recaptureSnapshotComposite(page);
820838

821839
const timeLabel = formatSnapshotTimestamp(time);
822-
const index = String(i).padStart(2, "0");
823-
const filename = `frame-${index}-at-${timeLabel}.png`;
840+
const slot = opts.keep
841+
? `at-${timeLabel}`
842+
: `${String(i).padStart(2, "0")}-at-${timeLabel}`;
843+
const filename = opts.keep ? `${slot}.png` : `frame-${slot}.png`;
824844
const framePath = join(snapshotDir, filename);
825845

826846
let crop: { x: number; y: number; width: number; height: number } | undefined;
@@ -845,9 +865,12 @@ async function captureSnapshots(
845865
region,
846866
opts.zoomScale ?? DEFAULT_ZOOM_SCALE,
847867
);
848-
writeFileSync(framePath, buffer);
868+
writeCaptureFileSync(framePath, buffer);
849869
} else {
850-
await page.screenshot({ path: framePath, type: "png", omitBackground: true });
870+
writeCaptureFileSync(
871+
framePath,
872+
await page.screenshot({ type: "png", omitBackground: true }),
873+
);
851874
}
852875
artifacts.push({
853876
id: `${invocation}-${i}`,
@@ -871,9 +894,9 @@ async function captureSnapshots(
871894
` ${c.warn("⚠")} --against has no frame at ${timeLabel} — reference pair skipped`,
872895
);
873896
} else {
874-
const refPath = join(snapshotDir, `ref-${index}-at-${timeLabel}.png`);
875-
writeFileSync(refPath, refPng);
876-
const pairPath = join(snapshotDir, `pair-${index}-at-${timeLabel}.jpg`);
897+
const refPath = join(snapshotDir, `ref-${slot}.png`);
898+
writeCaptureFileSync(refPath, refPng);
899+
const pairPath = join(snapshotDir, `pair-${slot}.jpg`);
877900
const { createContactSheet } = await import("../capture/contactSheet.js");
878901
await createContactSheet([framePath, refPath], pairPath, {
879902
cols: 2,
@@ -998,6 +1021,12 @@ export default defineCommand({
9981021
"Always include a readable end-of-timeline frame (default: true). Pass --no-end to capture only your exact --at times.",
9991022
default: true,
10001023
},
1024+
keep: {
1025+
type: "boolean",
1026+
description:
1027+
"Add to --output instead of clearing it, naming each still at-<seconds>s.png (at-0s, at-1.5s, at-12.25s: no trailing zeros), so snapshotting one moment again replaces only that still. Times less than 1 ms apart share a name, so one run may not pass two of them. No contact sheet.",
1028+
default: false,
1029+
},
10011030
zoom: {
10021031
type: "string",
10031032
description:
@@ -1074,6 +1103,7 @@ export default defineCommand({
10741103
.map((s) => parseFloat(s.trim()))
10751104
.filter((n) => !isNaN(n))
10761105
: undefined;
1106+
if (args.keep === true && atTimestamps) assertDistinctKeepNames(atTimestamps);
10771107
// Gemini frame analysis runs by default (silently skipped if
10781108
// GEMINI_API_KEY is not set). `--describe "custom question"` overrides
10791109
// the default prompt with a targeted question. `--describe false` opts
@@ -1122,6 +1152,7 @@ export default defineCommand({
11221152
autoProxy: args.proxy as boolean | undefined,
11231153
browserGpuMode: resolveLocalBrowserGpuMode(args["browser-gpu"] as boolean | undefined),
11241154
against,
1155+
keep: args.keep === true,
11251156
});
11261157
reportArtifacts(
11271158
"snapshot",
@@ -1146,13 +1177,16 @@ export default defineCommand({
11461177
);
11471178
}
11481179

1149-
// Generate contact sheet for quick AI review
1180+
// Generate contact sheet for quick AI review; a --keep folder mixes runs, so it gets none.
11501181
try {
11511182
const { createSnapshotContactSheet } = await import("../capture/contactSheet.js");
1152-
const sheets = await createSnapshotContactSheet(
1153-
snapshotDir,
1154-
join(snapshotDir, "contact-sheet.jpg"),
1155-
);
1183+
const sheets =
1184+
args.keep === true
1185+
? []
1186+
: await createSnapshotContactSheet(
1187+
snapshotDir,
1188+
join(snapshotDir, "contact-sheet.jpg"),
1189+
);
11561190
reportArtifacts("snapshot", "contact-sheet", sheets);
11571191
for (const sheet of sheets) {
11581192
console.log(` ${resolve(sheet)} (grid view for AI review)`);

0 commit comments

Comments
 (0)