Skip to content

Commit 237a984

Browse files
fix(studio): undoing a freeze frame removes the still it made (#4971)
* fix(studio): undoing a freeze frame removes the still it made * fix(studio-server): a failed frame extraction leaves no partial still * fix(studio-server): a freeze claims its still's name before extracting * fix(studio-server): a freeze past the media's end fails instead of saving an empty still * refactor(studio-server): freeze route names say what its comments said
1 parent 8e457d4 commit 237a984

9 files changed

Lines changed: 173 additions & 40 deletions

File tree

‎packages/studio-server/src/helpers/freezeFrame.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,9 @@ describe("freezeFrameMediaTime", () => {
6161
});
6262

6363
describe("freezeExtractArgs", () => {
64-
it("seeks before the input and writes one frame, never over an existing file", () => {
64+
it("seeks before the input and writes one frame into the file the route claimed", () => {
6565
expect(freezeExtractArgs("/p/a.mp4", 7.2004, "/p/assets/freeze/a-3200.png")).toEqual([
66-
"-n",
66+
"-y",
6767
"-ss",
6868
"7.2",
6969
"-i",

‎packages/studio-server/src/helpers/freezeFrame.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ export function freezeFrameMediaTime(input: {
4040
}
4141

4242
export function freezeExtractArgs(src: string, mediaTime: number, output: string): string[] {
43-
return ["-n", "-ss", String(round3(mediaTime)), "-i", src, "-frames:v", "1", output];
43+
return ["-y", "-ss", String(round3(mediaTime)), "-i", src, "-frames:v", "1", output];
4444
}
4545

4646
export const randomStillToken = (): string => randomBytes(4).toString("hex");

‎packages/studio-server/src/routes/freezeFrame.test.ts‎

Lines changed: 70 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ describe("freeze-frame route", () => {
4141
const calls: string[][] = [];
4242
const { dir, post } = setup(async (args) => {
4343
calls.push(args);
44+
writeFileSync(args.at(-1) ?? "", "png");
4445
return { ok: true };
4546
});
4647
const res = await post({
@@ -49,11 +50,12 @@ describe("freeze-frame route", () => {
4950
target: { id: "talk" },
5051
playhead: 2.5,
5152
});
52-
const body: { before?: string; after?: string; imageSrc?: string } = await res.json();
53+
const body: { before?: string; after?: string; imageSrc?: string; stillPath?: string } =
54+
await res.json();
5355
expect(res.status).toBe(200);
5456
const output = calls[0]?.at(-1) ?? "";
5557
expect(calls[0]).toEqual([
56-
"-n",
58+
"-y",
5759
"-ss",
5860
"2.5",
5961
"-i",
@@ -65,6 +67,7 @@ describe("freeze-frame route", () => {
6567
expect(dirname(output)).toBe(join(dir, "assets/freeze"));
6668
expect(basename(output)).toMatch(/^talk-[0-9a-f]{10}-2500-[0-9a-f]{8}\.png$/);
6769
expect(body.imageSrc).toBe(`assets/freeze/${basename(output)}`);
70+
expect(body.stillPath).toBe(`assets/freeze/${basename(output)}`);
6871
expect(body.before).toBe(html);
6972
expect(readFileSync(join(dir, "index.html"), "utf-8")).toBe(body.after);
7073
expect(body.after).toContain('id="talk-freeze"');
@@ -86,8 +89,13 @@ describe("freeze-frame route", () => {
8689
expect(calls).toEqual([]);
8790
});
8891

89-
it("leaves the file untouched when extraction fails", async () => {
90-
const { dir, post } = setup(async () => ({ ok: false, error: "boom" }));
92+
it("leaves the file untouched, and no partial still, when extraction fails", async () => {
93+
let still = "";
94+
const { dir, post } = setup(async (args) => {
95+
still = args.at(-1) ?? "";
96+
writeFileSync(still, "partial");
97+
return { ok: false, error: "boom" };
98+
});
9199
const res = await post({
92100
path: "index.html",
93101
expectedVersion: fileContentVersion(html),
@@ -96,6 +104,45 @@ describe("freeze-frame route", () => {
96104
});
97105
expect(res.status).toBe(500);
98106
expect(readFileSync(join(dir, "index.html"), "utf-8")).toBe(html);
107+
expect(still).not.toBe("");
108+
expect(existsSync(still)).toBe(false);
109+
});
110+
111+
it("refuses, leaving nothing behind, when ffmpeg succeeds without writing a frame", async () => {
112+
let still = "";
113+
const { dir, post } = setup(async (args) => {
114+
still = args.at(-1) ?? "";
115+
return { ok: true };
116+
});
117+
const res = await post({
118+
path: "index.html",
119+
expectedVersion: fileContentVersion(html),
120+
target: { id: "talk" },
121+
playhead: 2.5,
122+
});
123+
expect(res.status).toBe(500);
124+
expect(readFileSync(join(dir, "index.html"), "utf-8")).toBe(html);
125+
expect(still).not.toBe("");
126+
expect(existsSync(still)).toBe(false);
127+
});
128+
129+
it("removes the still it extracted when the page changed before the write", async () => {
130+
let still = "";
131+
const { dir, post } = setup(async (args) => {
132+
still = args.at(-1) ?? "";
133+
writeFileSync(still, "png");
134+
writeFileSync(join(dir, "index.html"), `${html}\n<!-- edited meanwhile -->`);
135+
return { ok: true };
136+
});
137+
const res = await post({
138+
path: "index.html",
139+
expectedVersion: fileContentVersion(html),
140+
target: { id: "talk" },
141+
playhead: 2.5,
142+
});
143+
expect(res.status).toBe(409);
144+
expect(still).not.toBe("");
145+
expect(existsSync(still)).toBe(false);
99146
});
100147

101148
it("keeps a traversal clip id inside assets/freeze, for the ffmpeg output and the still's src", async () => {
@@ -104,6 +151,7 @@ describe("freeze-frame route", () => {
104151
const { dir, post } = setup(
105152
async (args) => {
106153
calls.push(args);
154+
writeFileSync(args.at(-1) ?? "", "png");
107155
return { ok: true };
108156
},
109157
{ path: "scenes/a.html", html: evil.replace('src="media/', 'src="../media/') },
@@ -114,9 +162,11 @@ describe("freeze-frame route", () => {
114162
target: { id: "../../../../outside/frame" },
115163
playhead: 2.5,
116164
});
117-
const body: { imageSrc?: string; after?: string } = await res.json();
165+
const body: { imageSrc?: string; after?: string; stillPath?: string } = await res.json();
118166
expect(res.status).toBe(200);
119167
const output = calls[0]?.at(-1) ?? "";
168+
// The history names project files from the project root, not from the page that shows the still.
169+
expect(body.stillPath).toBe(`assets/freeze/${basename(output)}`);
120170
expect(basename(output)).toMatch(/^____________outside_frame-[0-9a-f]{10}-2500-/);
121171
expect(dirname(output)).toBe(join(dir, "assets/freeze"));
122172
expect(body.imageSrc).toBe(`../assets/freeze/${basename(output)}`);
@@ -190,16 +240,26 @@ describe("freeze-frame route", () => {
190240
expect(readFileSync(outputs[0] ?? "", "utf-8")).toBe(first);
191241
});
192242

193-
it("gives concurrent requests distinct stills", async () => {
243+
it("gives concurrent requests distinct stills and keeps only the one the page uses", async () => {
194244
const outputs: string[] = [];
195245
const { dir, post } = setup(writingExtractor(outputs));
196246
const results = await Promise.all([freeze(post, dir, "talk"), freeze(post, dir, "talk")]);
197247
expect(results.map((res) => res.status).sort()).toEqual([200, 409]);
198248
expect(new Set(outputs).size).toBe(2);
199-
expect(outputs.map((output) => readFileSync(output, "utf-8"))).toEqual([
200-
expect.stringContaining("#"),
201-
expect.stringContaining("#"),
202-
]);
249+
const kept = outputs.filter((output) => existsSync(output));
250+
expect(kept).toHaveLength(1);
251+
expect(readFileSync(kept[0] ?? "", "utf-8")).toContain("#");
252+
expect(readFileSync(join(dir, "index.html"), "utf-8")).toContain(basename(kept[0] ?? ""));
253+
});
254+
255+
it("keeps the winner's still when two requests race for the same name", async () => {
256+
const outputs: string[] = [];
257+
const { dir, post } = setup(writingExtractor(outputs), undefined, () => "fixed");
258+
const results = await Promise.all([freeze(post, dir, "talk"), freeze(post, dir, "talk")]);
259+
expect(results.map((res) => res.status).sort()).toEqual([200, 409]);
260+
expect(outputs).toHaveLength(1);
261+
expect(existsSync(outputs[0] ?? "")).toBe(true);
262+
expect(readFileSync(join(dir, "index.html"), "utf-8")).toContain(basename(outputs[0] ?? ""));
203263
});
204264

205265
it("refuses, without extracting, when the still's name is already taken", async () => {

‎packages/studio-server/src/routes/freezeFrame.ts‎

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { execFile } from "node:child_process";
2-
import { existsSync, readFileSync, statSync } from "node:fs";
2+
import { closeSync, openSync, readFileSync, rmSync, statSync } from "node:fs";
33
import { dirname, join, relative, sep } from "node:path";
44
import type { Hono } from "hono";
55
import { findFfBinary } from "@hyperframes/parsers/ff-binaries";
@@ -80,13 +80,23 @@ function readExpected(absPath: string, expectedVersion: string): { content: stri
8080
: { error: "file conflict", status: 409 };
8181
}
8282

83+
function claimStillNameBeforeExtracting(path: string): boolean {
84+
try {
85+
closeSync(openSync(path, "wx"));
86+
return true;
87+
} catch (error) {
88+
if ((error as NodeJS.ErrnoException).code === "EEXIST") return false;
89+
throw error;
90+
}
91+
}
92+
8393
async function extractStill(
8494
projectDir: string,
8595
absPath: string,
8696
source: FreezeSource,
8797
playhead: number,
8898
tools: { extract: FrameExtractor; stillToken: () => string },
89-
): Promise<{ imageSrc: string } | Failure> {
99+
): Promise<{ imageSrc: string; stillPath: string; imagePath: string } | Failure> {
90100
const fileDir = dirname(absPath);
91101
const mediaPath = pinWithinProject(projectDir, relative(projectDir, join(fileDir, source.src)));
92102
if (!mediaPath) return { error: `forbidden media path: ${source.src}`, status: 403 };
@@ -97,17 +107,18 @@ async function extractStill(
97107
if (!imagePath || dirname(imagePath) !== freezeDir) {
98108
return { error: `forbidden freeze path: ${fileName}`, status: 403 };
99109
}
100-
if (existsSync(imagePath))
110+
if (!claimStillNameBeforeExtracting(imagePath))
101111
return { error: `freeze still already exists: ${fileName}`, status: 409 };
102112
const extracted = await tools.extract(freezeExtractArgs(mediaPath, source.mediaTime, imagePath));
103-
if (!extracted.ok) {
104-
return {
105-
error: `Could not extract the frame: ${extracted.error ?? "ffmpeg failed"}`,
106-
status: 500,
107-
};
113+
const partialOrNoFrame = !extracted.ok || statSync(imagePath).size === 0;
114+
if (partialOrNoFrame) {
115+
rmSync(imagePath, { force: true });
116+
const reason = extracted.ok ? "no frame at this time" : (extracted.error ?? "ffmpeg failed");
117+
return { error: `Could not extract the frame: ${reason}`, status: 500 };
108118
}
109119
const depth = relative(projectDir, fileDir).split(sep).filter(Boolean).length;
110-
return { imageSrc: `${"../".repeat(depth)}${FREEZE_DIR.join("/")}/${fileName}` };
120+
const stillPath = `${FREEZE_DIR.join("/")}/${fileName}`;
121+
return { imageSrc: `${"../".repeat(depth)}${stillPath}`, stillPath, imagePath };
111122
}
112123

113124
function writeFolded(
@@ -160,17 +171,21 @@ export function registerFreezeFrameRoutes(
160171
stillToken,
161172
});
162173
if ("error" in still) return c.json({ error: still.error }, still.status);
163-
const { imageSrc } = still;
174+
const { imageSrc, stillPath, imagePath } = still;
164175
const folded = applyFreezeFrameToHtml(before, {
165176
target: body.target,
166177
playhead: body.playhead,
167178
imageSrc,
168179
});
169-
if (!folded) return c.json({ error: "Freeze target was not found in the file" }, 400);
180+
const failAndRemoveStill = (error: string, status: 400 | Failure["status"]) => {
181+
rmSync(imagePath, { force: true });
182+
return c.json({ error }, status);
183+
};
184+
if (!folded) return failAndRemoveStill("Freeze target was not found in the file", 400);
170185
const written = writeFolded(project.dir, absPath, body.path, before, folded.html, {
171186
token: body.transactionToken ?? c.req.header("X-Hyperframes-Write-Token"),
172187
});
173-
if ("error" in written) return c.json({ error: written.error }, written.status);
188+
if ("error" in written) return failAndRemoveStill(written.error, written.status);
174189
const { version, writeToken, backupPath } = written;
175190
return c.json({
176191
ok: true,
@@ -182,6 +197,7 @@ export function registerFreezeFrameRoutes(
182197
backupPath,
183198
freezeId: folded.freezeId,
184199
imageSrc,
200+
stillPath,
185201
});
186202
});
187203
}

‎packages/studio/src/hooks/useFreezeFrame.test.ts‎

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1+
// @vitest-environment happy-dom
2+
import { act, createElement } from "react";
3+
import { createRoot } from "react-dom/client";
14
import { afterEach, describe, expect, it, vi } from "vitest";
25
import type { TimelineElement } from "../player";
3-
import { requestFreezeFrame } from "./useFreezeFrame";
6+
import { requestFreezeFrame, useFreezeFrame } from "./useFreezeFrame";
47

58
afterEach(() => vi.unstubAllGlobals());
69

@@ -29,14 +32,15 @@ function stubFetch(freezeResponse: { status: number; body: unknown }) {
2932

3033
describe("requestFreezeFrame", () => {
3134
it("posts the clip target, file version and an authored-time playhead", async () => {
32-
const calls = stubFetch({ status: 200, body: { before: "a", after: "b", version: "v2" } });
35+
const frozen = { before: "a", after: "b", version: "v2", stillPath: "assets/freeze/t.png" };
36+
const calls = stubFetch({ status: 200, body: frozen });
3337
const result = await requestFreezeFrame({
3438
projectId: "p",
3539
path: "scene.html",
3640
element,
3741
playhead: 7.5,
3842
});
39-
expect(result).toEqual({ before: "a", after: "b", version: "v2" });
43+
expect(result).toEqual(frozen);
4044
const post = calls[1];
4145
expect(post?.url).toContain("/file-mutations/freeze-frame");
4246
expect(post?.body).toMatchObject({
@@ -54,3 +58,35 @@ describe("requestFreezeFrame", () => {
5458
).rejects.toThrow("Move the playhead inside a video clip to freeze");
5559
});
5660
});
61+
62+
describe("useFreezeFrame", () => {
63+
it("records the still it made with the edit, so Undo removes it", async () => {
64+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
65+
stubFetch({
66+
status: 200,
67+
body: { before: "a", after: "b", version: "v2", stillPath: "assets/freeze/talk.png" },
68+
});
69+
const recordEdit = vi.fn(async () => {});
70+
let freeze!: ReturnType<typeof useFreezeFrame>;
71+
function Harness() {
72+
freeze = useFreezeFrame({
73+
projectId: "p",
74+
activeCompPath: "index.html",
75+
showToast: () => {},
76+
writeProjectFile: async () => {},
77+
recordEdit,
78+
reloadPreview: () => {},
79+
});
80+
return null;
81+
}
82+
const root = createRoot(document.createElement("div"));
83+
await act(async () => root.render(createElement(Harness)));
84+
await act(() => freeze({ ...element, sourceFile: "index.html" }, 7.5));
85+
expect(recordEdit).toHaveBeenCalledWith({
86+
label: "Freeze frame",
87+
files: { "index.html": { before: "a", after: "b" } },
88+
created: ["assets/freeze/talk.png"],
89+
});
90+
act(() => root.unmount());
91+
});
92+
});

‎packages/studio/src/hooks/useFreezeFrame.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ interface FreezeFrameResponse {
1414
before: string;
1515
after: string;
1616
version: string;
17+
stillPath: string;
1718
}
1819

1920
function isFreezeFrameResponse(value: unknown): value is FreezeFrameResponse {
@@ -22,7 +23,8 @@ function isFreezeFrameResponse(value: unknown): value is FreezeFrameResponse {
2223
return (
2324
typeof body.before === "string" &&
2425
typeof body.after === "string" &&
25-
typeof body.version === "string"
26+
typeof body.version === "string" &&
27+
typeof body.stillPath === "string"
2628
);
2729
}
2830

@@ -109,6 +111,7 @@ export function useFreezeFrame(options: UseFreezeFrameOptions) {
109111
await opts.recordEdit({
110112
label: "Freeze frame",
111113
files: { [path]: { before: result.before, after: result.after } },
114+
created: [result.stillPath],
112115
});
113116
opts.observeProjectFileVersion?.(path, result.version);
114117
});

‎packages/studio/src/hooks/usePersistentEditHistory.test.ts‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22
// fallow-ignore-file code-duplication
33
import { act, createElement } from "react";
44
import { createRoot } from "react-dom/client";
5-
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
66
import { tmpdir } from "node:os";
7-
import { join } from "node:path";
7+
import { dirname, join } from "node:path";
88
import { afterEach, expect, it, vi } from "vitest";
99
import {
1010
createStudioApi,
@@ -316,6 +316,29 @@ it("refuses a second press whose edit is undone once an edit was made after the
316316
expect(file()).toBe("B");
317317
});
318318

319+
it("a file the edit made (a freeze's still) is deleted by its Undo and put back by its Redo", async () => {
320+
const { dir, hook, save, readFile } = await studio();
321+
const still = join(dir, "assets", "freeze", "talk.png");
322+
mkdirSync(dirname(still), { recursive: true });
323+
writeFileSync(still, "png");
324+
save("B");
325+
await act(() =>
326+
hook().recordEdit({
327+
label: "Freeze frame",
328+
files: { "index.html": { before: "A", after: "B" } },
329+
created: ["assets/freeze/talk.png"],
330+
}),
331+
);
332+
await vi.waitFor(() => expect(hook().undoLabel).toBe("Freeze frame"));
333+
334+
await act(() => hook().undo({ readFile }));
335+
expect(existsSync(still)).toBe(false);
336+
337+
await vi.waitFor(() => expect(hook().canRedo).toBe(true));
338+
await act(() => hook().redo({ readFile }));
339+
expect(readFileSync(still, "utf8")).toBe("png");
340+
});
341+
319342
it("a drag's edits under one key undo as one step, even before the drag goes idle", async () => {
320343
const { hook, file, save, readFile } = await studio();
321344
const writes: Array<[before: string, after: string]> = [

0 commit comments

Comments
 (0)