diff --git a/packages/studio-server/src/history/projectHistory.test.ts b/packages/studio-server/src/history/projectHistory.test.ts
index cde3e64035..59d3ca7217 100644
--- a/packages/studio-server/src/history/projectHistory.test.ts
+++ b/packages/studio-server/src/history/projectHistory.test.ts
@@ -521,6 +521,138 @@ describe("openProjectHistory", () => {
expect(history.list()).toHaveLength(1);
});
+ // fails without the fix: a host's temporary page beside the film was recorded like the film's own files.
+ it("never records a path its ignores option names: not at open, in a change, or for a reader", async () => {
+ const ignores = (path: string) => path.endsWith(".hf-flat.html");
+ const { history, write, projectDir, historyRoot } = await project(
+ { "index.html": "A", "index.hf-flat.html": "x" },
+ { ignores },
+ );
+ const entry = await change(history, agent, "Turn", () => {
+ write("index.html", "B");
+ write("index.hf-flat.html", "y");
+ });
+ expect(entry.files.map((file) => file.path)).toEqual(["index.html"]);
+ expect(Object.keys(history.peek(entry.id)!)).toEqual(["index.html"]);
+ const reader = readProjectHistory({ projectDir, historyRoot, ignores });
+ expect(Object.keys(reader.peek(entry.id)!)).toEqual(["index.html"]);
+ });
+
+ // fails without the fix: an entry written before the rule kept its target on the ignored file.
+ it("drops an older entry's targets on a path it now ignores", async () => {
+ const { history, write, projectDir, historyRoot } = await project({
+ "index.html": "A",
+ "temp.html": "x",
+ });
+ write("index.html", "B");
+ write("temp.html", "y");
+ await history.claim(you, "Edited", ["index.html", "temp.html"], {
+ targets: [
+ { file: "index.html", selector: "#i" },
+ { file: "temp.html", selector: "#t" },
+ ],
+ });
+ await history.close();
+ const ignores = (path: string) => path === "temp.html";
+ const again = await open(projectDir, historyRoot, { ignores });
+ const reader = readProjectHistory({ projectDir, historyRoot, ignores });
+ for (const [entry] of [again.list(), reader.list()])
+ expect(entry!.targets).toEqual([{ file: "index.html", selector: "#i" }]);
+ });
+
+ // fails without the fix: pruning kept only what the filtered log named, but the log on disk still named the rest.
+ it("never leaves a version on disk named that pruning removed, once a path is ignored", async () => {
+ const { history, write, projectDir, historyRoot } = await project({
+ "index.html": "A",
+ "big.bin": "a".repeat(1000),
+ });
+ write("big.bin", "b".repeat(1000));
+ await history.claim(you, "Edited", ["big.bin"]);
+ await history.close();
+ const again = await open(projectDir, historyRoot, {
+ ignores: (path: string) => path === "big.bin",
+ budgetBytes: 10,
+ });
+ write("index.html", "B");
+ await again.claim(you, "Page", ["index.html"]);
+ const reader = readProjectHistory({ projectDir, historyRoot });
+ for (const point of [START, ...reader.list().map((entry) => entry.id)])
+ for (const hash of Object.values(reader.peek(point) ?? {}))
+ await expect(reader.readBlob(hash)).resolves.toBeInstanceOf(Buffer);
+ });
+
+ // fails without the fix where the disk ignores case: an undo wrote the older spelling over the host's own file.
+ it.skipIf(!caseInsensitive())(
+ "never writes over an ignored file through an older spelling of its name",
+ async () => {
+ const { history, write, read, projectDir, historyRoot } = await project({
+ "Temp.html": "v1",
+ });
+ write("Temp.html", "v2");
+ await history.claim(you, "Edited", ["Temp.html"]);
+ await history.close();
+ renameSync(join(projectDir, "Temp.html"), join(projectDir, "t.tmp"));
+ renameSync(join(projectDir, "t.tmp"), join(projectDir, "temp.html"));
+ write("temp.html", "host");
+ const again = await open(projectDir, historyRoot, {
+ ignores: (path: string) => path === "temp.html",
+ });
+ await again.step("back", you);
+ expect(read("temp.html")).toBe("host");
+ },
+ );
+
+ // fails without the fix: Undo stopped on the folder link instead of skipping the file the host ignores.
+ it("never writes an ignored file through a folder that now links to it", async () => {
+ const { history, write, read, projectDir, historyRoot } = await project({
+ "pages/a.html": "v1",
+ });
+ write("pages/a.html", "v2");
+ await history.claim(you, "Edited", ["pages/a.html"]);
+ await history.close();
+ renameSync(join(projectDir, "pages"), join(projectDir, "private"));
+ symlinkSync("private", join(projectDir, "pages"), "dir");
+ write("private/a.html", "host");
+ const again = await open(projectDir, historyRoot, {
+ ignores: (path: string) => path.startsWith("private/"),
+ });
+ await again.step("back", you);
+ expect(read("private/a.html")).toBe("host");
+ });
+
+ // fails without the fix: with no ignores option, Undo through a folder now linked to a hidden one said nothing.
+ it("still refuses an undo through a folder link when the host passes no ignores option", async () => {
+ const { history, write, projectDir, historyRoot } = await project({ "pages/a.html": "v1" });
+ write("pages/a.html", "v2");
+ await history.claim(you, "Edited", ["pages/a.html"]);
+ await history.close();
+ renameSync(join(projectDir, "pages"), join(projectDir, ".hold"));
+ symlinkSync(".hold", join(projectDir, "pages"), "dir");
+ const again = await open(projectDir, historyRoot);
+ await expect(again.step("back", you)).rejects.toThrow("pages is in the way");
+ });
+
+ // fails without the fix: an older undo's kept file stayed in both views, and Redo still offered it.
+ it("an ignores option drops an older undo's kept file from both views and from Redo", async () => {
+ const { history, write, projectDir, historyRoot } = await project({ "index.html": "a" });
+ write("assets/song.mp3", "mp3");
+ await history.claim(you, "Uploaded", ["assets/song.mp3"]);
+ write(
+ "compositions/scene.html",
+ '',
+ );
+ await history.claim(agent, "Music in a scene", ["compositions/scene.html"]);
+ expect(await history.step("back", you)).toMatchObject({ ok: true });
+ expect(history.next("forward", you)?.label).toBe("Undid: Uploaded");
+ await history.close();
+ const ignores = (path: string) => path === "assets/song.mp3";
+ const again = await open(projectDir, historyRoot, { ignores });
+ const reader = readProjectHistory({ projectDir, historyRoot, ignores });
+ expect(JSON.stringify(again.list())).not.toContain("song.mp3");
+ expect(JSON.stringify(reader.list())).not.toContain("song.mp3");
+ expect(again.next("forward", you)).toBeUndefined();
+ });
+
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": "
Hello
", "assets/logo.png": Buffer.from([1, 2, 3]) },
diff --git a/packages/studio-server/src/history/projectHistory.ts b/packages/studio-server/src/history/projectHistory.ts
index 1e2baac398..1d5d45170c 100644
--- a/packages/studio-server/src/history/projectHistory.ts
+++ b/packages/studio-server/src/history/projectHistory.ts
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto";
-import { mkdir, readdir, rm, rmdir, stat, writeFile } from "node:fs/promises";
+import { lstat, mkdir, readdir, realpath, rm, rmdir, stat, writeFile } from "node:fs/promises";
import {
type Dirent,
type Stats,
@@ -100,6 +100,7 @@ export interface ProjectHistoryOptions {
closedWindowAfterOwnership?: () => ClosedWindow | undefined;
undoScope?: "own" | "everyone";
pruneGoneProjectsBudgetMs?: number;
+ ignores?: (path: string) => boolean;
}
interface ClaimOptions {
@@ -252,8 +253,9 @@ async function inFirstCopySlot(copy: () => Promise): Promise {
const MEDIA_LEDGER = ".media/manifest.jsonl";
const KEPT_HIDDEN_PATHS = new Set([...STUDIO_SIGNATURE_MANIFEST_PATHS, MEDIA_LEDGER]);
-/** A hidden name (a tool's own record) is nobody's work, except the kept ones above; nor is a path out or a private file. */
-function isHistoryPath(path: string): boolean {
+/** A hidden name (a tool's record) is nobody's work, bar those kept above; nor an outside, private or ignored path. */
+function isHistoryPath(path: string, ignores?: (path: string) => boolean): boolean {
+ if (ignores?.(path)) return false;
if (!isRelativeProjectPath(path) || isStudioPrivatePath(path)) return false;
if (KEPT_HIDDEN_PATHS.has(path)) return true;
return !path.split("/").some((segment) => segment.startsWith("."));
@@ -282,15 +284,37 @@ function namesBlob(log: HistoryLog, hash: string): boolean {
);
}
-function withoutHiddenPaths(log: HistoryLog): HistoryLog {
- for (const path of log.baseline.keys()) if (!isHistoryPath(path)) log.baseline.delete(path);
- for (const entry of log.entries)
- entry.files = entry.files.filter((file) => isHistoryPath(file.path));
+function withoutHiddenPaths(log: HistoryLog, ignores?: (path: string) => boolean): HistoryLog {
+ dropUnrecordedPaths(log, ignores);
return log;
}
-const historyFiles = async (dir: string) =>
- (await listProjectFilesAsync(dir)).filter((file) => isHistoryPath(file.path));
+function dropKeptOutside(entry: HistoryEntry, ignores?: (path: string) => boolean): boolean {
+ const kept = Object.entries(entry.keptInPlace ?? {});
+ const left = kept.filter(([path]) => isHistoryPath(path, ignores));
+ if (left.length === kept.length) return false;
+ if (left.length) entry.keptInPlace = Object.fromEntries(left);
+ else delete entry.keptInPlace;
+ return true;
+}
+
+function dropUnrecordedPaths(log: HistoryLog, ignores?: (path: string) => boolean): boolean {
+ let dropped = false;
+ for (const path of log.baseline.keys())
+ if (!isHistoryPath(path, ignores)) dropped = log.baseline.delete(path) || dropped;
+ for (const entry of log.entries) {
+ dropped = dropKeptOutside(entry, ignores) || dropped;
+ const files = entry.files.filter((file) => isHistoryPath(file.path, ignores));
+ if (files.length === entry.files.length) continue;
+ entry.files = files;
+ keepTargetsOfItsFiles(entry);
+ dropped = true;
+ }
+ return dropped;
+}
+
+const historyFiles = async (dir: string, ignores?: (path: string) => boolean) =>
+ (await listProjectFilesAsync(dir)).filter((file) => isHistoryPath(file.path, ignores));
type ListedFile = ListedProjectFile;
const COPY_LATER_ABOVE_BYTES = 1024 ** 2;
@@ -461,6 +485,20 @@ class Engine {
closed = false;
closing: Promise | undefined;
+ readonly records = (path: string) => isHistoryPath(path, this.options.ignores);
+ readonly historyFiles = () => historyFiles(this.dir, this.options.ignores);
+ readonly recordsOnDisk = async (path: string) => {
+ const { ignores } = this.options;
+ if (!this.records(path)) return false;
+ if (!ignores) return true;
+ const at = join(this.dir, path);
+ const found = await lstat(at).catch(() => null);
+ if (!found || found.isSymbolicLink()) return true;
+ const [real, root] = await Promise.all([realpath(at), realpath(this.dir)]);
+ const onDisk = relative(root, real).split(sep).join("/");
+ return onDisk.startsWith("../") || isAbsolute(onDisk) || !ignores(onDisk);
+ };
+
constructor(
readonly options: ProjectHistoryOptions,
readonly projectId: string,
@@ -555,7 +593,7 @@ class Engine {
),
);
if (!log) return this.firstOpen();
- this.log = withoutHiddenPaths(log);
+ this.takeLog(log);
await this.reclaimUncopied();
if (!this.log.keepsLedger) await this.takeInUnnamedLedger();
const cache = this.readStatCache();
@@ -567,12 +605,19 @@ class Engine {
const left = this.readAdopting();
const unadopted = (file: { path: string }) =>
left.has(file.path) && !this.tracked.has(file.path);
- this.adoptMediaInBackground((await historyFiles(this.dir)).filter(unadopted), this.now());
+ this.adoptMediaInBackground((await this.historyFiles()).filter(unadopted), this.now());
// What changed while the project was closed is one outside entry, or the closed window's.
this.reopenClosedWindow();
await this.settleAll();
}
+ /** Pruning keeps only what this log names, so the log on disk must not name more than the one in memory. */
+ takeLog(log: HistoryLog): void {
+ const dropped = dropUnrecordedPaths(log, this.options.ignores);
+ this.log = log;
+ if (dropped) this.persistLog();
+ }
+
/** Copies an older version took of files that are no longer copied; text and small files are never touched. */
async reclaimUncopied(): Promise {
await this.blobs.drop(uncopiedOnlyHashes(this.log, (hash) => this.blobs.size(hash)));
@@ -586,7 +631,7 @@ class Engine {
const replaced = hashOfVersion(fileContentVersion(bytes));
if (!replaced || replaced === after) return;
const path = relative(realDir, absPath).split(sep).join("/");
- if (!isHistoryPath(path)) return;
+ if (!this.records(path)) return;
this.seen.note(path, replaced);
this.seen.note(path, after);
// One chain per file, a new Map per write (forgetWritesBefore checks identity); off-chain notes were overwritten.
@@ -632,7 +677,7 @@ class Engine {
async takeInUnnamedLedger(): Promise {
const named = (path: string) =>
this.log.entries.some((entry) => entry.files.some((file) => file.path === path));
- const ledger = (await historyFiles(this.dir)).find((file) => file.path === MEDIA_LEDGER);
+ const ledger = (await this.historyFiles()).find((file) => file.path === MEDIA_LEDGER);
if (ledger && !this.log.baseline.has(MEDIA_LEDGER) && !named(MEDIA_LEDGER)) {
const copied = await this.storeIfPresent(MEDIA_LEDGER);
if (typeof copied === "object") this.log.baseline.set(MEDIA_LEDGER, copied.hash);
@@ -644,7 +689,7 @@ class Engine {
async firstOpen(): Promise {
const sweptAt = this.now();
- const files = await historyFiles(this.dir);
+ const files = await this.historyFiles();
const copied = files.filter((file) => file.size <= COPY_LATER_ABOVE_BYTES);
const hashes = await Promise.allSettled(
copied.map((file) => inFirstCopySlot(() => this.storeIfPresent(file.path))),
@@ -795,7 +840,7 @@ class Engine {
const sweptAt = this.now();
const changedAt = (file: { mtimeMs: number; ctimeMs: number }) =>
Math.min(sweptAt, Math.max(file.mtimeMs, file.ctimeMs));
- const seen = (await historyFiles(this.dir)).filter((file) => !this.adopting.has(file.path));
+ const seen = (await this.historyFiles()).filter((file) => !this.adopting.has(file.path));
const heard = new Map(this.overwritten);
const present = new Set(seen.map((file) => file.path));
const removed = [...this.tracked.keys()]
@@ -1155,7 +1200,7 @@ class Engine {
noteChange(path: string): void {
const absolute = resolve(this.dir, path);
if (this.notedTimer || !affectsProjectSignature(this.dir, absolute)) return;
- if (!isHistoryPath(relative(this.dir, absolute).split(sep).join("/"))) return;
+ if (!this.records(relative(this.dir, absolute).split(sep).join("/"))) return;
this.sweepIn(20);
}
@@ -1278,10 +1323,12 @@ class Engine {
extra: Partial,
): Promise {
this.assertWritable();
- const wanted = [...target].filter(
+ const candidates = [...target].filter(
([path, hash]) =>
this.studioWouldWrite(path) && (this.tracked.get(path)?.hash ?? null) !== hash,
);
+ const onDisk = await Promise.all(candidates.map(([path]) => this.recordsOnDisk(path)));
+ const wanted = candidates.filter((_, i) => onDisk[i]);
const named = await this.stillNamed(wanted);
const changes = wanted
.filter(([path, hash]) => hash !== null || !named.has(path))
@@ -1721,7 +1768,7 @@ export interface ProjectHistoryView {
/** Reads only: takes no lock and files, prunes or writes nothing; an owner's half-appended last line is skipped. */
export function readProjectHistory(
- options: Pick,
+ options: Pick,
): ProjectHistoryView {
const dir = resolve(options.projectDir);
const id = readId(dir);
@@ -1730,7 +1777,10 @@ export function readProjectHistory(
? join(options.historyRoot, id)
: null;
const read = home && readLog(logFileIn(home), () => {});
- const log = withoutHiddenPaths(read || { baseline: new Map(), entries: [], pins: new Set() });
+ const log = withoutHiddenPaths(
+ read || { baseline: new Map(), entries: [], pins: new Set() },
+ options.ignores,
+ );
return {
list: () => listOf(log),
peek: (point) => peekOf(log, point),