chore: archive dq7-history worktree state 2026-09-26

This commit is contained in:
Miguel Ángel
2026-09-26 04:05:30 -04:00
parent cbaddec51a
commit 9473347e1e
12 changed files with 1129 additions and 3 deletions
View File
@@ -12,6 +12,7 @@ import { registerRegistryRoutes } from "./routes/registry.js";
import { registerSelectionRoutes } from "./routes/selection.js";
import { registerMediaRoutes } from "./routes/media.js";
import { registerGlobalAssetRoutes } from "./routes/globalAssets.js";
import { registerHistoryRoutes } from "./routes/history.js";
/**
* Create a Hono sub-app with all studio API routes.
@@ -34,6 +35,7 @@ export function createStudioApi(adapter: StudioApiAdapter): Hono {
registerFontRoutes(api);
registerRegistryRoutes(api, adapter);
registerGlobalAssetRoutes(api);
registerHistoryRoutes(api, adapter);
return api;
}
@@ -176,6 +176,26 @@ function createProjectFingerprint(projectDir: string, files: ProjectSignatureFil
return hash.digest("hex").slice(0, 24);
}
function collectProjectFiles(normalizedProjectDir: string): ProjectSignatureFile[] {
const collected: ProjectSignatureFile[] = [];
collectProjectSignatureFiles(normalizedProjectDir, normalizedProjectDir, collected);
collectProjectSignatureManifestFiles(normalizedProjectDir, collected);
return collected;
}
/** The files a project is made of (the signature's set: source plus Studio's two manifests), paths with `/`. */
export function listProjectFiles(
projectDir: string,
): Array<{ path: string; size: number; mtimeMs: number; ctimeMs: number }> {
const normalizedProjectDir = resolve(projectDir);
return collectProjectFiles(normalizedProjectDir).map((entry) => ({
path: relative(normalizedProjectDir, entry.file).split(sep).join("/"),
size: entry.size,
mtimeMs: entry.mtimeMs,
ctimeMs: entry.ctimeMs,
}));
}
/**
* Resolve the project signature through the adapter's cached path when the host
* provides one (the CLI invalidates its cache from the file watcher), falling
@@ -204,9 +224,7 @@ export function createProjectSignature(
excluding: ReadonlySet<string> = new Set(),
): string {
const normalizedProjectDir = resolve(projectDir);
const collected: ProjectSignatureFile[] = [];
collectProjectSignatureFiles(normalizedProjectDir, normalizedProjectDir, collected);
collectProjectSignatureManifestFiles(normalizedProjectDir, collected);
const collected = collectProjectFiles(normalizedProjectDir);
const files = collected.filter(
(entry) => !excluding.has(relative(normalizedProjectDir, entry.file).split(sep).join("/")),
);
@@ -0,0 +1,74 @@
import { createHash, randomUUID } from "node:crypto";
import { constants, createReadStream } from "node:fs";
import { copyFile, mkdir, readdir, readFile, rename, rm, stat } from "node:fs/promises";
import { dirname, join } from "node:path";
/** File contents stored once by sha256, text and binary alike. */
export interface BlobStore {
/** Copies the file in (a clone where the file system can) and returns the copy's hash. */
put(absPath: string): Promise<string>;
read(hash: string): Promise<Buffer>;
/** Writes the blob's bytes to `absPath` by clone-or-copy and rename, so a reader never sees half a file. */
writeTo(hash: string, absPath: string): Promise<void>;
bytes(): number;
/** Deletes every blob not in `keep`. */
prune(keep: ReadonlySet<string>): Promise<void>;
}
async function hashFile(path: string): Promise<string> {
const hash = createHash("sha256");
for await (const chunk of createReadStream(path)) hash.update(chunk);
return hash.digest("hex");
}
async function cloneOrCopy(from: string, to: string): Promise<void> {
await mkdir(dirname(to), { recursive: true });
const temp = `${to}.${randomUUID()}.tmp`;
try {
await copyFile(from, temp, constants.COPYFILE_FICLONE);
await rename(temp, to);
} catch (error) {
await rm(temp, { force: true });
throw error;
}
}
export async function openBlobStore(dir: string): Promise<BlobStore> {
const sizes = new Map<string, number>();
await mkdir(dir, { recursive: true });
for (const shard of await readdir(dir))
for (const hash of await readdir(join(dir, shard)).catch(() => []))
sizes.set(hash, (await stat(join(dir, shard, hash))).size);
const pathOf = (hash: string) => join(dir, hash.slice(0, 2), hash);
let total = [...sizes.values()].reduce((sum, size) => sum + size, 0);
return {
async put(absPath) {
// Hash the copy, not the source, so a write racing the copy can never file bytes under the wrong hash.
const temp = join(dir, `incoming-${randomUUID()}`);
await copyFile(absPath, temp, constants.COPYFILE_FICLONE);
const hash = await hashFile(temp);
if (sizes.has(hash)) {
await rm(temp, { force: true });
return hash;
}
await mkdir(dirname(pathOf(hash)), { recursive: true });
const size = (await stat(temp)).size;
await rename(temp, pathOf(hash));
sizes.set(hash, size);
total += size;
return hash;
},
read: (hash) => readFile(pathOf(hash)),
writeTo: (hash, absPath) => cloneOrCopy(pathOf(hash), absPath),
bytes: () => total,
async prune(keep) {
for (const [hash, size] of sizes) {
if (keep.has(hash)) continue;
await rm(pathOf(hash), { force: true });
sizes.delete(hash);
total -= size;
}
},
};
}
@@ -0,0 +1,39 @@
import { randomUUID } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join, resolve } from "node:path";
const ID_PATH = join(".hyperframes", "history-id");
function readId(projectDir: string): string | null {
try {
return readFileSync(join(projectDir, ID_PATH), "utf-8").trim() || null;
} catch {
return null;
}
}
function recordedDir(historyDir: string): string | null {
try {
return JSON.parse(readFileSync(join(historyDir, "project.json"), "utf-8")).dir ?? null;
} catch {
return null;
}
}
/**
* The project's history id, kept in the project so a rename or move keeps its history. A folder whose id is
* still carried by the folder that history was recorded for is a copy, and gets an id of its own.
*/
export function projectHistoryId(projectDir: string, historyRoot: string): string {
const dir = resolve(projectDir);
let id = readId(dir);
const was = id && recordedDir(join(historyRoot, id));
if (!id || (was && was !== dir && existsSync(was) && readId(was) === id)) {
id = randomUUID();
mkdirSync(join(dir, ".hyperframes"), { recursive: true });
writeFileSync(join(dir, ID_PATH), `${id}\n`);
}
mkdirSync(join(historyRoot, id), { recursive: true });
writeFileSync(join(historyRoot, id, "project.json"), JSON.stringify({ dir }));
return id;
}
@@ -0,0 +1,158 @@
import { appendFileSync, readFileSync } from "node:fs";
import { replaceFileAtomically } from "../helpers/atomicFile.js";
export interface HistoryWho {
kind: "person" | "agent" | "outside";
/** Shown in the History list: "You", "Nib", "Codex", "Outside". */
name: string;
}
/** A file's sha256 before and after; null is "did not exist", so a create or delete undoes like any edit. */
export interface HistoryFileChange {
path: string;
before: string | null;
after: string | null;
}
export interface HistoryEntry {
id: string;
who: HistoryWho;
label: string;
startedAt: number;
endedAt: number;
files: HistoryFileChange[];
/** Set on an undo: the entry it reverted. Redo is undoing the undo. */
undoes?: string;
/** Set on a restore: the point (an entry id, or START) the files were made equal to. */
restoredTo?: string;
}
/** The point before the first kept entry. */
export const START = "start";
/** Path to hash. */
export type Manifest = Map<string, string>;
export interface HistoryLog {
baseline: Manifest;
entries: HistoryEntry[];
pins: Set<string>;
}
type LogRecord =
| { type: "baseline"; files: Record<string, string> }
| { type: "entry"; entry: HistoryEntry }
| { type: "pin"; id: string; pinned: boolean };
export function readLog(file: string): HistoryLog | null {
let text: string;
try {
text = readFileSync(file, "utf-8");
} catch {
return null;
}
const log: HistoryLog = { baseline: new Map(), entries: [], pins: new Set() };
for (const line of text.split("\n")) {
// A torn last line from a crash mid-append is dropped; every line before it is whole.
let record: LogRecord;
try {
record = JSON.parse(line);
} catch {
continue;
}
applyRecord(log, record);
}
return log;
}
function applyRecord(log: HistoryLog, record: LogRecord): void {
if (record.type === "baseline") log.baseline = new Map(Object.entries(record.files));
else if (record.type === "entry") log.entries.push(record.entry);
else if (record.pinned) log.pins.add(record.id);
else log.pins.delete(record.id);
}
export function appendRecord(file: string, record: LogRecord): void {
appendFileSync(file, `${JSON.stringify(record)}\n`);
}
export function writeLog(file: string, log: HistoryLog): void {
const records: LogRecord[] = [
{ type: "baseline", files: Object.fromEntries(log.baseline) },
...log.entries.map((entry) => ({ type: "entry" as const, entry })),
...[...log.pins].map((id) => ({ type: "pin" as const, id, pinned: true })),
];
replaceFileAtomically(file, records.map((r) => `${JSON.stringify(r)}\n`).join(""), 0o644);
}
export function applyEntry(manifest: Manifest, entry: HistoryEntry): void {
for (const file of entry.files)
if (file.after === null) manifest.delete(file.path);
else manifest.set(file.path, file.after);
}
/** The files as they were right after `point`. Null when that point is no longer kept. */
export function manifestAt(log: HistoryLog, point: string): Manifest | null {
const manifest = new Map(log.baseline);
if (point === START) return manifest;
for (const entry of log.entries) {
applyEntry(manifest, entry);
if (entry.id === point) return manifest;
}
return null;
}
/** Entries currently reverted: an undo that is itself in effect reverts its target. */
export function undoneIds(entries: readonly HistoryEntry[]): Set<string> {
const undone = new Set<string>();
for (let i = entries.length - 1; i >= 0; i -= 1) {
const entry = entries[i]!;
if (entry.undoes && !undone.has(entry.id)) undone.add(entry.undoes);
}
return undone;
}
/**
* What Cmd+Z (back) or Cmd+Shift+Z (forward) reverts, whoever made the change. Back: the newest change still in
* effect. Forward: the newest undo of a change that is still in effect, while no change has been made since.
*/
export function stepTarget(
entries: readonly HistoryEntry[],
direction: "back" | "forward",
): HistoryEntry | undefined {
const undone = undoneIds(entries);
const byId = new Map(entries.map((entry) => [entry.id, entry]));
for (let i = entries.length - 1; i >= 0; i -= 1) {
const entry = entries[i]!;
const isChange = !entry.undoes;
if (direction === "back" && isChange && !undone.has(entry.id)) return entry;
if (direction !== "forward") continue;
if (isChange) return undefined;
const target = byId.get(entry.undoes!);
if (!undone.has(entry.id) && target && !target.undoes) return entry;
}
return undefined;
}
/**
* Folds the oldest entry into the baseline unless it is pinned. ponytail: an old pin therefore holds everything
* after it; per-point snapshots would lift that. Returns whether one was folded.
*/
export function foldOldest(log: HistoryLog): boolean {
const oldest = log.entries[0];
if (!oldest || log.pins.has(oldest.id)) return false;
applyEntry(log.baseline, oldest);
log.entries.shift();
return true;
}
/** Every hash a kept point can still need. */
export function referencedHashes(log: HistoryLog, current: Manifest): Set<string> {
const keep = new Set([...log.baseline.values(), ...current.values()]);
for (const entry of log.entries)
for (const file of entry.files) {
if (file.before) keep.add(file.before);
if (file.after) keep.add(file.after);
}
return keep;
}
@@ -0,0 +1,212 @@
// @vitest-environment node
import {
cpSync,
existsSync,
mkdirSync,
mkdtempSync,
readFileSync,
renameSync,
rmSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { openProjectHistory, type ProjectHistory } from "./projectHistory";
import { START, type HistoryWho } from "./historyLog";
const you: HistoryWho = { kind: "person", name: "You" };
const nib: HistoryWho = { kind: "agent", name: "Nib" };
const cleanup: Array<() => unknown> = [];
afterEach(async () => {
for (const step of cleanup.splice(0).reverse()) await step();
});
function tempDir(prefix: string): string {
const dir = mkdtempSync(join(tmpdir(), prefix));
cleanup.push(() => rmSync(dir, { recursive: true, force: true }));
return dir;
}
async function open(projectDir: string, historyRoot: string, options = {}) {
const history = await openProjectHistory({ projectDir, historyRoot, ...options });
cleanup.push(() => history.close());
return history;
}
async function project(files: Record<string, string | Buffer>, options = {}) {
const projectDir = tempDir("hf-history-project-");
const historyRoot = tempDir("hf-history-root-");
const write = (path: string, content: string | Buffer) => {
mkdirSync(dirname(join(projectDir, path)), { recursive: true });
writeFileSync(join(projectDir, path), content);
};
for (const [path, content] of Object.entries(files)) write(path, content);
const history = await open(projectDir, historyRoot, options);
const read = (path: string) => readFileSync(join(projectDir, path), "utf-8");
const has = (path: string) => existsSync(join(projectDir, path));
return { projectDir, historyRoot, history, write, read, has };
}
/** Runs `writes` inside a window of `who`'s and returns the entry it became. */
async function change(history: ProjectHistory, who: HistoryWho, label: string, writes: () => void) {
const window = await history.beginWindow(who, label);
writes();
const entry = await window.close();
if (!entry) throw new Error("the window recorded nothing");
return entry;
}
describe("openProjectHistory", () => {
it("records a write nobody announced as one outside entry, and undo puts the bytes back as a new entry", async () => {
const { history, write, read, projectDir } = await project(
{ "index.html": "<h1>Hello</h1>", "assets/logo.png": Buffer.from([1, 2, 3]) },
{ quietMs: 30 },
);
write("index.html", "<h1>Bye</h1>");
write("assets/logo.png", Buffer.from([9, 9]));
history.noteChange("index.html");
history.noteChange(join(projectDir, "assets/logo.png"));
await vi.waitFor(() => expect(history.list()).toHaveLength(1));
const [outside] = history.list();
expect(outside).toMatchObject({ who: { kind: "outside" }, label: "Changed outside the app" });
expect(outside!.files.map((file) => file.path)).toEqual(["assets/logo.png", "index.html"]);
const undone = await history.undo(outside!.id, { who: you });
expect(undone).toMatchObject({ ok: true, entry: { label: "Undid: Changed outside the app" } });
expect(read("index.html")).toBe("<h1>Hello</h1>");
expect([...readFileSync(join(projectDir, "assets/logo.png"))]).toEqual([1, 2, 3]);
expect(history.list().find((entry) => entry.id === outside!.id)?.undone).toBe(true);
expect(await history.step("forward", you)).toMatchObject({
entry: { label: "Redid: Changed outside the app" },
});
expect(read("index.html")).toBe("<h1>Bye</h1>");
await history.step("back", you);
expect(read("index.html")).toBe("<h1>Hello</h1>");
expect(history.list()).toHaveLength(4);
});
it("gives a window's writes to its writer, and undoes a create, a delete and Studio's manifest", async () => {
const { history, write, read, has, projectDir } = await project({
"index.html": "<h1>Hello</h1>",
"old.css": "h1 {}",
});
expect(await (await history.beginWindow(nib, "nothing")).close()).toBeNull();
const entry = await change(history, nib, "add Flash Through White", () => {
write("index.html", "<h1>Flash</h1>");
write("new.html", "<p>new</p>");
write(".hyperframes/studio-manual-edits.json", "{}");
rmSync(join(projectDir, "old.css"));
});
expect(entry.who).toEqual(nib);
expect(entry.files.map((file) => [file.path, !!file.before, !!file.after])).toEqual([
[".hyperframes/studio-manual-edits.json", false, true],
["index.html", true, true],
["new.html", false, true],
["old.css", true, false],
]);
expect((await history.undo(entry.id, { who: you })).ok).toBe(true);
expect(read("index.html")).toBe("<h1>Hello</h1>");
expect(read("old.css")).toBe("h1 {}");
expect(has("new.html")).toBe(false);
expect(has(".hyperframes/studio-manual-edits.json")).toBe(false);
});
it("names a file changed since and the newer change, then takes 'undo just this' when asked", async () => {
const { history, write, read } = await project({ "index.html": "A", "notes.txt": "n1" });
const first = await change(history, you, "Title", () => {
write("index.html", "B");
write("notes.txt", "n2");
});
const newer = await change(history, nib, "Retitle", () => write("index.html", "C"));
expect(await history.undo(first.id, { who: you })).toEqual({
ok: false,
conflict: { files: ["index.html"], newer: [newer.id] },
});
expect([read("index.html"), read("notes.txt")]).toEqual(["C", "n2"]);
expect((await history.undo(first.id, { who: you, mode: "just-this" })).ok).toBe(true);
expect([read("index.html"), read("notes.txt")]).toEqual(["A", "n1"]);
});
it("'go back to before this' reverts the change and everything after it as one entry", async () => {
const { history, write, read, has } = await project({ "index.html": "A" });
const first = await change(history, you, "Title", () => write("index.html", "B"));
await change(history, nib, "Extra", () => {
write("index.html", "C");
write("extra.txt", "x");
});
const back = await history.undo(first.id, { who: you, mode: "back-to-before" });
expect(back).toMatchObject({ ok: true, entry: { restoredTo: START } });
expect(read("index.html")).toBe("A");
expect(has("extra.txt")).toBe(false);
});
it("restores any point, and peek reads a point's bytes without writing", async () => {
const { history, write, read } = await project({ "index.html": "v1" });
const second = await change(history, you, "Second", () => write("index.html", "v2"));
await change(history, you, "Third", () => write("index.html", "v3"));
const at = (point: string) => history.peek(point)!["index.html"]!;
expect((await history.readBlob(at(second.id))).toString()).toBe("v2");
expect((await history.readBlob(at(START))).toString()).toBe("v1");
expect(read("index.html")).toBe("v3");
const restored = await history.restore(second.id, you);
expect(restored).toMatchObject({ label: "Restored: Second", restoredTo: second.id });
expect(read("index.html")).toBe("v2");
});
it("keeps the history across a move and a reopen, and a copy of the folder starts its own", async () => {
const { history, write, projectDir, historyRoot } = await project({ "index.html": "v1" });
write("index.html", "v2");
await history.flush();
const moved = `${projectDir}-moved`;
renameSync(projectDir, moved);
cleanup.push(() => rmSync(moved, { recursive: true, force: true }));
await history.flush();
expect(history.list(), "a moved folder is not every file deleted").toHaveLength(1);
await history.close();
writeFileSync(join(moved, "index.html"), "v3");
const reopened = await open(moved, historyRoot);
expect(reopened.projectId).toBe(history.projectId);
expect(reopened.list()).toHaveLength(2);
await reopened.step("back", you);
expect(readFileSync(join(moved, "index.html"), "utf-8")).toBe("v2");
const copy = tempDir("hf-history-copy-");
cpSync(moved, copy, { recursive: true });
const copied = await open(copy, historyRoot);
expect(copied.projectId).not.toBe(history.projectId);
expect(copied.list()).toEqual([]);
});
it("past its budget folds the oldest entries away and deletes their bytes, but never past a pin", async () => {
const { history, write, read } = await project(
{ "index.html": "a".repeat(40) },
{ budgetBytes: 100 },
);
const pinned = await change(history, you, "B", () => write("index.html", "b".repeat(40)));
history.pin(pinned.id, true);
await change(history, you, "C", () => write("index.html", "c".repeat(40)));
expect(history.list()).toHaveLength(2);
history.pin(pinned.id, false);
const last = await change(history, you, "D", () => write("index.html", "d".repeat(40)));
expect(history.list().map((entry) => entry.id)).toEqual([last.id]);
expect(history.peek(pinned.id)).toBeNull();
await expect(history.readBlob(history.peek(START)!["index.html"]!)).resolves.toEqual(
Buffer.from("c".repeat(40)),
);
expect((await history.undo(last.id, { who: you })).ok).toBe(true);
expect(read("index.html")).toBe("c".repeat(40));
});
});
@@ -0,0 +1,460 @@
import { randomUUID } from "node:crypto";
import { rm } from "node:fs/promises";
import { existsSync, readFileSync } from "node:fs";
import { join, resolve } from "node:path";
import { replaceFileAtomically } from "../helpers/atomicFile.js";
import { affectsProjectSignature, listProjectFiles } from "../helpers/projectSignature.js";
import { openBlobStore, type BlobStore } from "./blobStore.js";
import { projectHistoryId } from "./historyId.js";
import {
START,
appendRecord,
foldOldest,
manifestAt,
readLog,
referencedHashes,
stepTarget,
undoneIds,
writeLog,
type HistoryEntry,
type HistoryFileChange,
type HistoryLog,
type HistoryWho,
type Manifest,
} from "./historyLog.js";
export interface ProjectHistoryOptions {
projectDir: string;
/** Kept outside the project, so nothing tidying the project can take its history with it. */
historyRoot: string;
now?: () => number;
/** Writes with no window open group into one entry until this long without another (default 2 s)... */
quietMs?: number;
/** ...or this long after the first (default 30 s). */
maxGroupMs?: number;
/** Past this many stored bytes the oldest unpinned entries are folded away (default 2 GB). */
budgetBytes?: number;
/** A sweep or commit that a watcher or timer started failed. */
onError?: (error: unknown) => void;
}
export interface HistoryListItem extends HistoryEntry {
pinned: boolean;
undone: boolean;
}
export type HistoryResult =
| { ok: true; entry: HistoryEntry | null }
| { ok: false; conflict: { files: string[]; newer: string[] } };
export interface HistoryWindow {
readonly id: string;
/** Records everything written since the window opened as one entry; null when nothing changed. */
close(): Promise<HistoryEntry | null>;
}
export interface ProjectHistory {
readonly projectId: string;
/** Writes until close() are this writer's, as one entry. ponytail: overlapping windows give a write to the newest. */
beginWindow(who: HistoryWho, label: string): Promise<HistoryWindow>;
/** A watcher saw `path` change (project-relative or absolute). */
noteChange(path: string): void;
list(): HistoryListItem[];
/** Cmd+Z (back) and Cmd+Shift+Z (forward), whoever made the change. */
step(direction: "back" | "forward", who: HistoryWho): Promise<HistoryResult>;
/** A conflict (a file changed since) returns the choice; pass `mode` to take one. */
undo(
id: string,
options: { who: HistoryWho; mode?: "just-this" | "back-to-before" },
): Promise<HistoryResult>;
/** Makes the files equal what they were right after `point` (an entry id, or START). */
restore(point: string, who: HistoryWho): Promise<HistoryEntry | null>;
/** The files at `point` without writing anything: path to hash, read through readBlob. */
peek(point: string): Record<string, string> | null;
readBlob(hash: string): Promise<Buffer>;
pin(id: string, pinned: boolean): void;
onEntry(listener: (entry: HistoryEntry) => void): () => void;
/** Takes in every pending write and closes the outside group. */
flush(): Promise<void>;
close(): Promise<void>;
}
const OUTSIDE: HistoryWho = { kind: "outside", name: "Outside" };
const OUTSIDE_LABEL = "Changed outside the app";
interface Tracked {
hash: string;
stat: string;
}
interface Group {
id: string;
who: HistoryWho;
label: string;
startedAt: number;
changes: Map<string, HistoryFileChange>;
}
const statKey = (file: { size: number; mtimeMs: number; ctimeMs: number }) =>
`${file.size}:${file.mtimeMs}:${file.ctimeMs}`;
class Engine {
readonly dir: string;
readonly home: string;
log: HistoryLog = { baseline: new Map(), entries: [], pins: new Set() };
tracked = new Map<string, Tracked>();
windows: Group[] = [];
outside: Group | null = null;
quietTimer: NodeJS.Timeout | undefined;
maxTimer: NodeJS.Timeout | undefined;
notedTimer: NodeJS.Timeout | null = null;
listeners = new Set<(entry: HistoryEntry) => void>();
tail: Promise<unknown> = Promise.resolve();
constructor(
readonly options: ProjectHistoryOptions,
readonly projectId: string,
readonly blobs: BlobStore,
) {
this.dir = resolve(options.projectDir);
this.home = join(options.historyRoot, projectId);
}
get logFile() {
return join(this.home, "log.jsonl");
}
now() {
return (this.options.now ?? Date.now)();
}
/** One operation at a time, in order: sweeps, windows and undos never interleave. */
queue<T>(task: () => Promise<T>): Promise<T> {
const run = this.tail.then(task);
this.tail = run.catch(() => undefined);
return run;
}
async start(): Promise<void> {
const log = readLog(this.logFile);
if (!log) return this.firstOpen();
this.log = log;
const cache = this.readStatCache();
const last = this.log.entries.at(-1)?.id ?? START;
for (const [path, hash] of manifestAt(this.log, last) ?? []) {
const cached = cache.get(path);
this.tracked.set(path, { hash, stat: cached?.hash === hash ? cached.stat : "" });
}
// What changed while the project was closed is one outside entry.
await this.sweep();
await this.commitOutside();
}
async firstOpen(): Promise<void> {
for (const file of listProjectFiles(this.dir))
this.tracked.set(file.path, {
hash: await this.blobs.put(join(this.dir, file.path)),
stat: statKey(file),
});
this.log.baseline = this.manifest();
writeLog(this.logFile, this.log);
this.saveStatCache();
}
manifest(): Manifest {
return new Map([...this.tracked].map(([path, file]) => [path, file.hash]));
}
readStatCache(): Map<string, Tracked> {
try {
const files = JSON.parse(readFileSync(join(this.home, "stat.json"), "utf-8"));
return new Map(Object.entries(files as Record<string, Tracked>));
} catch {
return new Map();
}
}
saveStatCache(): void {
const files = JSON.stringify(Object.fromEntries(this.tracked));
replaceFileAtomically(join(this.home, "stat.json"), files, 0o644);
}
/**
* Takes in every write since the last sweep and files each change to its writer. ponytail: always the whole
* project (a stat per file, a hash only when the stat moved); per-path sweeps if projects reach tens of thousands.
*/
async sweep(): Promise<void> {
// A missing project folder was moved or removed, not emptied: that is no change to its files.
if (!existsSync(this.dir)) return;
const seen = listProjectFiles(this.dir);
let changed = false;
for (const file of seen) changed = (await this.observe(file.path, statKey(file))) || changed;
const present = new Set(seen.map((file) => file.path));
for (const [path, known] of this.tracked) {
if (present.has(path)) continue;
this.tracked.delete(path);
this.record(path, known.hash, null);
changed = true;
}
if (changed) this.saveStatCache();
}
async observe(path: string, stat: string): Promise<boolean> {
const known = this.tracked.get(path);
if (known?.stat === stat) return false;
const hash = await this.blobs.put(join(this.dir, path)).catch((error) => {
// Gone between the stat and the copy: the next sweep records the delete.
if (error?.code === "ENOENT") return null;
throw error;
});
if (hash === null) return false;
this.tracked.set(path, { hash, stat });
if (known?.hash !== hash) this.record(path, known?.hash ?? null, hash);
return true;
}
record(path: string, before: string | null, after: string | null): void {
const group = this.windows.at(-1) ?? this.outsideGroup();
const earlier = group.changes.get(path);
const from = earlier ? earlier.before : before;
if (from === after) group.changes.delete(path);
else group.changes.set(path, { path, before: from, after });
}
outsideGroup(): Group {
const { quietMs = 2000, maxGroupMs = 30_000 } = this.options;
const closeIn = (ms: number) => {
const timer = setTimeout(() => this.background(() => this.commitOutside()), ms);
timer.unref?.();
return timer;
};
if (!this.outside) {
this.outside = this.newGroup(OUTSIDE, OUTSIDE_LABEL);
this.maxTimer = closeIn(maxGroupMs);
}
clearTimeout(this.quietTimer);
this.quietTimer = closeIn(quietMs);
return this.outside;
}
newGroup(who: HistoryWho, label: string): Group {
return { id: randomUUID(), who, label, startedAt: this.now(), changes: new Map() };
}
async commitOutside(): Promise<void> {
clearTimeout(this.quietTimer);
clearTimeout(this.maxTimer);
const group = this.outside;
this.outside = null;
if (group) await this.commit(group);
}
async commit(group: Group, extra: Partial<HistoryEntry> = {}): Promise<HistoryEntry | null> {
if (!group.changes.size) return null;
const { changes, ...rest } = group;
const files = [...changes.values()].sort((a, b) => a.path.localeCompare(b.path));
const entry: HistoryEntry = { ...rest, endedAt: this.now(), files, ...extra };
this.log.entries.push(entry);
appendRecord(this.logFile, { type: "entry", entry });
for (const listener of this.listeners) listener(entry);
await this.keepWithinBudget();
return entry;
}
/** Every hash a kept point or a still-open group can need. */
inUse(): Set<string> {
const keep = referencedHashes(this.log, this.manifest());
for (const group of [...this.windows, ...(this.outside ? [this.outside] : [])])
for (const file of group.changes.values()) if (file.before) keep.add(file.before);
return keep;
}
async keepWithinBudget(): Promise<void> {
const budget = this.options.budgetBytes ?? 2 * 1024 ** 3;
let folded = false;
while (this.blobs.bytes() > budget && foldOldest(this.log)) {
folded = true;
await this.blobs.prune(this.inUse());
}
if (folded) writeLog(this.logFile, this.log);
}
/** Before an operation: every write so far is filed, and the outside group is closed so it sorts first. */
async settle(): Promise<void> {
await this.sweep();
await this.commitOutside();
}
/** A watcher saw a write: one sweep per burst takes it in (a deleted folder is reported by its name alone). */
noteChange(path: string): void {
if (this.notedTimer || !affectsProjectSignature(this.dir, resolve(this.dir, path))) return;
this.notedTimer = setTimeout(() => {
this.notedTimer = null;
this.background(() => this.sweep());
}, 20);
this.notedTimer.unref?.();
}
background(task: () => Promise<unknown>): void {
this.queue(task).catch((error) => this.options.onError?.(error));
}
beginWindow(who: HistoryWho, label: string): Promise<HistoryWindow> {
return this.queue(async () => {
// Writes before the window opened are not this writer's.
await this.sweep();
const group = this.newGroup(who, label);
this.windows.push(group);
return {
id: group.id,
close: () =>
this.queue(async () => {
await this.sweep();
this.windows = this.windows.filter((open) => open !== group);
return this.commit(group);
}),
};
});
}
/** Writes `target` (path to hash, null deletes) as one entry of `who`'s. */
async writeAs(
who: HistoryWho,
label: string,
target: Map<string, string | null>,
extra: Partial<HistoryEntry>,
): Promise<HistoryEntry | null> {
const group = this.newGroup(who, label);
this.windows.push(group);
try {
for (const [path, hash] of target) {
if ((this.tracked.get(path)?.hash ?? null) === hash) continue;
if (hash === null) await rm(join(this.dir, path), { force: true });
else await this.blobs.writeTo(hash, join(this.dir, path));
}
await this.sweep();
} finally {
this.windows = this.windows.filter((open) => open !== group);
}
return this.commit(group, extra);
}
entry(id: string): HistoryEntry {
const entry = this.log.entries.find((candidate) => candidate.id === id);
if (!entry) throw new Error("That change is no longer kept in this project's history.");
return entry;
}
undoLabel(entry: HistoryEntry): string {
if (!entry.undoes) return `Undid: ${entry.label}`;
const original = this.log.entries.find((candidate) => candidate.id === entry.undoes);
return `Redid: ${original?.label ?? entry.label}`;
}
async undoNow(
id: string,
who: HistoryWho,
mode?: "just-this" | "back-to-before",
): Promise<HistoryResult> {
const entry = this.entry(id);
const changed = entry.files.filter(
(file) => (this.tracked.get(file.path)?.hash ?? null) !== file.after,
);
if (changed.length && !mode) return { ok: false, conflict: this.conflict(entry, changed) };
if (mode === "back-to-before") {
const index = this.log.entries.indexOf(entry);
const point = index > 0 ? this.log.entries[index - 1]!.id : START;
return {
ok: true,
entry: await this.restoreNow(point, who, `Went back to before: ${entry.label}`),
};
}
const target = new Map(entry.files.map((file) => [file.path, file.before]));
return {
ok: true,
entry: await this.writeAs(who, this.undoLabel(entry), target, { undoes: id }),
};
}
conflict(entry: HistoryEntry, changed: HistoryFileChange[]) {
const paths = new Set(changed.map((file) => file.path));
const after = this.log.entries.slice(this.log.entries.indexOf(entry) + 1);
const newer = after.filter((later) => later.files.some((file) => paths.has(file.path)));
return { files: [...paths], newer: newer.map((later) => later.id) };
}
async restoreNow(point: string, who: HistoryWho, label: string): Promise<HistoryEntry | null> {
const files = manifestAt(this.log, point);
if (!files) throw new Error("That point is no longer kept in this project's history.");
const target = new Map<string, string | null>(
[...this.tracked.keys()].map((path) => [path, null]),
);
for (const [path, hash] of files) target.set(path, hash);
return this.writeAs(who, label, target, { restoredTo: point });
}
pointLabel(point: string): string {
return point === START ? "the start" : this.entry(point).label;
}
api(): ProjectHistory {
return {
projectId: this.projectId,
beginWindow: (who, label) => this.beginWindow(who, label),
noteChange: (path) => this.noteChange(path),
list: () => {
const undone = undoneIds(this.log.entries);
return this.log.entries.map((entry) => ({
...entry,
pinned: this.log.pins.has(entry.id),
undone: undone.has(entry.id),
}));
},
step: (direction, who) =>
this.queue(async () => {
await this.settle();
const target = stepTarget(this.log.entries, direction);
return target ? this.undoNow(target.id, who) : { ok: true, entry: null };
}),
undo: (id, { who, mode }) =>
this.queue(async () => {
await this.settle();
return this.undoNow(id, who, mode);
}),
restore: (point, who) =>
this.queue(async () => {
await this.settle();
return this.restoreNow(point, who, `Restored: ${this.pointLabel(point)}`);
}),
peek: (point) => {
const files = manifestAt(this.log, point);
return files && Object.fromEntries(files);
},
readBlob: (hash) => this.blobs.read(hash),
pin: (id, pinned) => {
this.entry(id);
if (pinned) this.log.pins.add(id);
else this.log.pins.delete(id);
appendRecord(this.logFile, { type: "pin", id, pinned });
},
onEntry: (listener) => {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
},
flush: () => this.queue(() => this.settle()),
close: async () => {
if (this.notedTimer) clearTimeout(this.notedTimer);
await this.queue(() => this.settle());
},
};
}
}
/** Opens a project's history: every write to its files becomes an entry that can be undone or restored. */
export async function openProjectHistory(options: ProjectHistoryOptions): Promise<ProjectHistory> {
const projectId = projectHistoryId(options.projectDir, options.historyRoot);
const blobs = await openBlobStore(join(options.historyRoot, projectId, "blobs"));
const engine = new Engine(options, projectId, blobs);
await engine.queue(() => engine.start());
return engine.api();
}
+14
View File
@@ -1,6 +1,20 @@
export { createStudioApi } from "./createStudioApi.js";
export { createProjectSignature, affectsProjectSignature } from "./helpers/projectSignature.js";
export { compositionsAffectedBy } from "./helpers/compositionInputs.js";
export {
openProjectHistory,
type ProjectHistory,
type ProjectHistoryOptions,
type HistoryListItem,
type HistoryResult,
type HistoryWindow,
} from "./history/projectHistory.js";
export {
START as HISTORY_START,
type HistoryEntry,
type HistoryFileChange,
type HistoryWho,
} from "./history/historyLog.js";
export type {
StudioApiAdapter,
ResolvedProject,
@@ -0,0 +1,62 @@
// @vitest-environment node
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { createStudioApi } from "../createStudioApi";
import { openProjectHistory, type ProjectHistory } from "../history/projectHistory";
import type { StudioApiAdapter } from "../types";
const cleanup: Array<() => unknown> = [];
afterEach(async () => {
for (const step of cleanup.splice(0).reverse()) await step();
});
function tempDir(prefix: string): string {
const dir = mkdtempSync(join(tmpdir(), prefix));
cleanup.push(() => rmSync(dir, { recursive: true, force: true }));
return dir;
}
function apiFor(projectDir: string, history?: ProjectHistory) {
const adapter = {
listProjects: () => [],
resolveProject: (id: string) => (id === "demo" ? { id, dir: projectDir } : null),
...(history && { history: () => history }),
} as unknown as StudioApiAdapter;
const api = createStudioApi(adapter);
return (path: string, body?: object) =>
api.request(
`/projects/demo/history${path}`,
body ? { method: "POST", body: JSON.stringify(body) } : undefined,
);
}
describe("history routes", () => {
it("record a Studio edit window as the person's entry, and step back undoes it", async () => {
const projectDir = tempDir("hf-history-routes-");
writeFileSync(join(projectDir, "index.html"), "A");
const history = await openProjectHistory({
projectDir,
historyRoot: tempDir("hf-history-routes-root-"),
});
cleanup.push(() => history.close());
const call = apiFor(projectDir, history);
const { windowId } = await (await call("/window", { label: "Moved Title" })).json();
writeFileSync(join(projectDir, "index.html"), "B");
const { entry } = await (await call(`/window/${windowId}/close`, {})).json();
expect(entry).toMatchObject({ label: "Moved Title", who: { kind: "person", name: "You" } });
const step = await (await call("/step", { direction: "back" })).json();
expect(step).toMatchObject({ ok: true, entry: { label: "Undid: Moved Title" } });
expect(readFileSync(join(projectDir, "index.html"), "utf-8")).toBe("A");
expect((await (await call("")).json()).entries).toHaveLength(2);
});
it("answer 404 when the host keeps no history for the project", async () => {
const call = apiFor(tempDir("hf-history-routes-none-"));
expect((await call("")).status).toBe(404);
});
});
@@ -0,0 +1,80 @@
import type { Context, Hono } from "hono";
import type { StudioApiAdapter } from "../types.js";
import type { HistoryWindow, ProjectHistory } from "../history/projectHistory.js";
import type { HistoryWho } from "../history/historyLog.js";
const YOU: HistoryWho = { kind: "person", name: "You" };
async function historyOf(adapter: StudioApiAdapter, c: Context): Promise<ProjectHistory | null> {
const project = await adapter.resolveProject(c.req.param("id") ?? "");
return project ? ((await adapter.history?.(project)) ?? null) : null;
}
async function bodyOf(c: Context): Promise<Record<string, unknown>> {
const body = await c.req.json().catch(() => null);
return body && typeof body === "object" ? (body as Record<string, unknown>) : {};
}
const text = (value: unknown) => (typeof value === "string" && value ? value : null);
/** Runs `task` on the project's history; no history is a 404, an engine refusal ("no longer kept") a 409. */
async function withHistory(
adapter: StudioApiAdapter,
c: Context,
task: (history: ProjectHistory, body: Record<string, unknown>) => Promise<unknown> | unknown,
) {
const history = await historyOf(adapter, c);
if (!history) return c.json({ error: "This project has no history here." }, 404);
try {
return c.json((await task(history, await bodyOf(c))) ?? null);
} catch (error) {
return c.json({ error: error instanceof Error ? error.message : String(error) }, 409);
}
}
/** Studio's history: list, Cmd+Z and Shift+Z, undo with the conflict choice, restore, peek, pin, edit windows. */
export function registerHistoryRoutes(api: Hono, adapter: StudioApiAdapter): void {
// ponytail: a window whose close never arrives stays open until the server stops.
const windows = new Map<string, HistoryWindow>();
const base = "/projects/:id/history";
api.get(base, (c) => withHistory(adapter, c, (history) => ({ entries: history.list() })));
api.post(`${base}/step`, (c) =>
withHistory(adapter, c, (history, body) =>
history.step(body.direction === "forward" ? "forward" : "back", YOU),
),
);
api.post(`${base}/undo`, (c) =>
withHistory(adapter, c, (history, body) => {
const mode =
body.mode === "just-this" || body.mode === "back-to-before" ? body.mode : undefined;
return history.undo(text(body.entryId) ?? "", { who: YOU, mode });
}),
);
api.post(`${base}/restore`, (c) =>
withHistory(adapter, c, (history, body) => history.restore(text(body.point) ?? "", YOU)),
);
api.get(`${base}/peek/:point`, (c) =>
withHistory(adapter, c, (history) => ({ files: history.peek(c.req.param("point")) })),
);
api.post(`${base}/pin`, (c) =>
withHistory(adapter, c, (history, body) => {
history.pin(text(body.entryId) ?? "", body.pinned === true);
return { ok: true };
}),
);
api.post(`${base}/window`, (c) =>
withHistory(adapter, c, async (history, body) => {
const window = await history.beginWindow(YOU, text(body.label) ?? "Edited in Studio");
windows.set(window.id, window);
return { windowId: window.id };
}),
);
api.post(`${base}/window/:windowId/close`, (c) =>
withHistory(adapter, c, async () => {
const window = windows.get(c.req.param("windowId") ?? "");
windows.delete(c.req.param("windowId") ?? "");
return { entry: window ? await window.close() : null };
}),
);
}
+7
View File
@@ -1,5 +1,6 @@
import type { CanvasResolution } from "@hyperframes/parsers";
import type { RegistryItem } from "@hyperframes/core";
import type { ProjectHistory } from "./history/projectHistory.js";
/** Resolved info about a single project. */
export interface ResolvedProject {
@@ -106,6 +107,12 @@ export interface StudioApiAdapter {
/** Resolve a project ID (or session ID) to its directory. Returns null if not found. */
resolveProject(id: string): Promise<ResolvedProject | null> | ResolvedProject | null;
/**
* Optional: the project's history (openProjectHistory), one per project for the host's lifetime. Without it
* the history routes answer 404.
*/
history?: (project: ResolvedProject) => Promise<ProjectHistory | null> | ProjectHistory | null;
/** Bundle a project directory into a single HTML string. Returns null if unavailable. */
bundle(projectDir: string): Promise<string | null>;