Skip to content

Commit 36f8bd0

Browse files
feat(studio): undo and redo step through the project history, whoever made the change (#4456)
* feat(studio-server): an undo taken from Studio is not mistaken for an outside edit * feat(studio): undo and redo step through the project history, whoever made the change * feat(studio): the dev server keeps each project history, in the same folder as preview * fix(studio-server): an undo that deletes a file reads as Studio's, and dev histories close * fix(studio-server): a claim keeps an agent's earlier write the agent's and takes back Studio's own * chore: allow the removal of Studio's browser edit history files * test(studio): mock the project history in the runtime smoke * fix(studio): step past a jammed undo and say why a step fails * fix(studio-server): an agent turn cut by a claim commits its part before the claim * fix(studio-server): a claim's cut ends a held drag and takes only the cut files out of a turn * fix(studio-server): a held drag ends when someone else changed a file it already holds
1 parent 4064b18 commit 36f8bd0

29 files changed

Lines changed: 1368 additions & 1954 deletions

‎packages/cli/src/server/studioServer.test.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { EventEmitter } from "node:events";
22
import { afterEach, describe, expect, it, vi } from "vitest";
3-
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
44
import { tmpdir } from "node:os";
55
import { basename, join } from "node:path";
66
import { createProjectSignature, fileContentVersion } from "@hyperframes/studio-server";
@@ -665,6 +665,30 @@ describe("Studio file-change SSE", () => {
665665
}
666666
});
667667

668+
it("labels the deletion an undo from Studio makes with Studio's write token", async () => {
669+
const projectDir = tmpProject();
670+
writeFileSync(join(projectDir, "index.html"), "<html>before</html>");
671+
server = createStudioServer({ projectDir, historyRoot: tmpProject() });
672+
const history = `/api/projects/${encodeURIComponent(basename(projectDir))}/history`;
673+
const post = (path: string, body: object, headers: Record<string, string> = {}) =>
674+
server!.app.request(`${history}${path}`, {
675+
method: "POST",
676+
headers: { "Content-Type": "application/json", ...headers },
677+
body: JSON.stringify(body),
678+
});
679+
await server.app.request(history); // opens the history, as Studio's first load does
680+
writeFileSync(join(projectDir, "extra.html"), "<html>added</html>");
681+
await post("/claim", { label: "Added a section", paths: ["extra.html"] });
682+
const streams = await subscribe(1);
683+
684+
await post("/step", { direction: "back" }, { "X-Hyperframes-Write-Token": "studio-undo-1" });
685+
expect(existsSync(join(projectDir, "extra.html"))).toBe(false);
686+
mockWatcher.emit("change", "rename", "extra.html");
687+
688+
const [payload] = await Promise.all(streams.map(nextEvent));
689+
expect(payload).toContain("studio-undo-1");
690+
});
691+
668692
// `/api/events` is one connection per SERVER, not per project: a tab left
669693
// open from a `preview` run whose port was later reused by a DIFFERENT
670694
// project shares this exact stream. Without `projectId` on the wire, that

‎packages/cli/src/server/studioServer.ts‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import { existsSync, readFileSync, writeFileSync, unlinkSync } from "node:fs";
1111
import { createHash } from "node:crypto";
1212
import { fileURLToPath } from "node:url";
1313
import { resolve, join, basename } from "node:path";
14-
import { homedir } from "node:os";
1514
import { readBundleFile } from "./readBundleFile.js";
1615
import {
1716
createProjectWatcher,
@@ -41,6 +40,7 @@ import {
4140
createProjectSignature,
4241
createBackgroundRemovalJob,
4342
identifyFileWrite,
43+
DELETED_VERSION,
4444
fileContentVersion,
4545
getMimeType,
4646
affectsProjectSignature,
@@ -53,6 +53,7 @@ import {
5353
type RenderJobState,
5454
type BackgroundRemovalRender,
5555
stampProjectHfIds,
56+
DEFAULT_HISTORY_ROOT,
5657
openProjectHistory,
5758
type ProjectHistory,
5859
} from "@hyperframes/studio-server";
@@ -74,9 +75,6 @@ import {
7475

7576
const STUDIO_MANUAL_EDITS_PATH = ".hyperframes/studio-manual-edits.json";
7677

77-
/** Where `hyperframes preview` keeps project histories: outside every project, so no tidy-up takes one away. */
78-
const DEFAULT_HISTORY_ROOT = join(homedir(), ".cache", "hyperframes", "history");
79-
8078
// Under preview.ts's 3s process-exit watchdog, so shutdown() always returns
8179
// before that watchdog can fire and skip this file's browser cleanup.
8280
const RENDER_SHUTDOWN_WAIT_MS = 2_000;
@@ -866,7 +864,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
866864
// `version` ships even when no receipt matches: it is the client's only
867865
// identity for an unlabelled change, and without it every duplicate
868866
// delivery of one watcher event drains and reloads again.
869-
const receipt = version ? identifyFileWrite(absPath, version) : null;
867+
const receipt = identifyFileWrite(absPath, version ?? DELETED_VERSION);
870868
// `projectId` so a stale tab — one still pointed at a project this
871869
// server no longer serves, because `hyperframes preview` reused this
872870
// port for a different folder (see ProjectUnreachableBanner's doc

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

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,19 @@ const receipts = new Map<string, StoredReceipt[]>();
1515

1616
/** Strong content version used as both the JSON version and HTTP ETag. */
1717
export function fileContentVersion(content: string | Uint8Array): string {
18-
return `"sha256:${createHash("sha256").update(content).digest("hex")}"`;
18+
return hashVersion(createHash("sha256").update(content).digest("hex"));
19+
}
20+
21+
/** The version a deletion's receipt is kept under: a deleted file has no bytes to hash. */
22+
export const DELETED_VERSION = '"deleted"';
23+
24+
export function hashVersion(hex: string): string {
25+
return `"sha256:${hex}"`;
26+
}
27+
28+
/** The sha256 a version names, or undefined when it is not a content version. */
29+
export function hashOfVersion(version: string): string | undefined {
30+
return /^"sha256:([0-9a-f]{64})"$/.exec(version)?.[1];
1931
}
2032

2133
/** A validator from a file's inode, change time and size, or null while the change is under three

‎packages/studio-server/src/history/blobStore.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,17 @@ import { dirname, join } from "node:path";
77
export interface BlobStore {
88
/** Copies the file in (a clone where the file system can) and returns the copy's hash. */
99
put(absPath: string): Promise<string>;
10+
has(hash: string): boolean;
1011
read(hash: string): Promise<Buffer>;
1112
/** Writes the blob's bytes to `absPath` by clone-or-copy and rename, so a reader never sees half a file. */
1213
writeTo(hash: string, absPath: string): Promise<void>;
1314
bytes(): number;
1415
size(hash: string): number;
15-
/** Deletes every blob not in `keep`. */
1616
prune(keep: ReadonlySet<string>): Promise<void>;
1717
}
1818

19+
const BLOB_HASH = /^[0-9a-f]{64}$/;
20+
1921
async function hashFile(path: string): Promise<string> {
2022
const hash = createHash("sha256");
2123
for await (const chunk of createReadStream(path)) hash.update(chunk);
@@ -40,7 +42,11 @@ export async function openBlobStore(dir: string): Promise<BlobStore> {
4042
for (const shard of await readdir(dir))
4143
for (const hash of await readdir(join(dir, shard)).catch(() => []))
4244
sizes.set(hash, (await stat(join(dir, shard, hash))).size);
43-
const pathOf = (hash: string) => join(dir, hash.slice(0, 2), hash);
45+
const pathOf = (hash: string) => {
46+
// Checked where the path is joined, so no caller can read or write outside the store.
47+
if (!BLOB_HASH.test(hash)) throw new Error("That is not a history blob.");
48+
return join(dir, hash.slice(0, 2), hash);
49+
};
4450
let total = [...sizes.values()].reduce((sum, size) => sum + size, 0);
4551

4652
return {
@@ -62,8 +68,9 @@ export async function openBlobStore(dir: string): Promise<BlobStore> {
6268
total += size;
6369
return hash;
6470
},
65-
read: (hash) => readFile(pathOf(hash)),
66-
writeTo: (hash, absPath) => cloneOrCopy(pathOf(hash), absPath),
71+
has: (hash) => sizes.has(hash),
72+
read: async (hash) => readFile(pathOf(hash)),
73+
writeTo: async (hash, absPath) => cloneOrCopy(pathOf(hash), absPath),
6774
bytes: () => total,
6875
size: (hash) => sizes.get(hash) ?? 0,
6976
async prune(keep) {

0 commit comments

Comments
 (0)