Revert "feat: Persist Studio manual edits via manifest (#593)"

This reverts commit d0abe90a82.
This commit is contained in:
Miguel Ángel
2026-05-04 09:41:36 -07:00
parent 8d83d4f132
commit 26b8e2a985
82 changed files with 711 additions and 15345 deletions
@@ -1,256 +0,0 @@
import { describe, expect, it } from "vitest";
import { createEmptyEditHistory } from "../utils/editHistory";
import type { EditHistoryStorageAdapter } from "../utils/editHistoryStorage";
import { createMemoryEditHistoryStorage } from "../utils/editHistoryStorage";
import {
createPersistentEditHistoryController,
createPersistentEditHistoryStore,
} from "./usePersistentEditHistory";
describe("createPersistentEditHistoryController", () => {
it("records history and reloads it for the same project", async () => {
const storage = createMemoryEditHistoryStorage();
const first = await createPersistentEditHistoryController({
projectId: "project-1",
storage,
now: () => 100,
onChange: () => {},
});
await first.recordEdit({
label: "Move layer",
kind: "manual",
files: { "index.html": { before: "a", after: "b" } },
});
const second = await createPersistentEditHistoryController({
projectId: "project-1",
storage,
now: () => 200,
onChange: () => {},
});
expect(second.snapshot().canUndo).toBe(true);
expect(second.snapshot().undoLabel).toBe("Move layer");
expect(second.snapshot().undoPaths).toEqual(["index.html"]);
});
it("undo applies files through the provided callback and persists redo state", async () => {
const storage = createMemoryEditHistoryStorage();
const controller = await createPersistentEditHistoryController({
projectId: "project-1",
storage,
now: () => 100,
onChange: () => {},
});
await controller.recordEdit({
label: "Move layer",
kind: "manual",
files: { "index.html": { before: "a", after: "b" } },
});
const result = await controller.undo({
readFile: async (path) => {
expect(path).toBe("index.html");
return "b";
},
writeFile: async (path, content) => {
expect(path).toBe("index.html");
expect(content).toBe("a");
},
});
expect(result.ok).toBe(true);
expect(result.paths).toEqual(["index.html"]);
expect(controller.snapshot().canUndo).toBe(false);
expect(controller.snapshot().canRedo).toBe(true);
expect(controller.snapshot().redoPaths).toEqual(["index.html"]);
});
it("keeps in-memory history when storage saves fail", async () => {
const storage: EditHistoryStorageAdapter = {
async get() {
return null;
},
async set() {
throw new Error("IndexedDB unavailable");
},
async delete() {},
};
const controller = await createPersistentEditHistoryController({
projectId: "project-1",
storage,
now: () => 100,
onChange: () => {},
});
await expect(
controller.recordEdit({
label: "Move layer",
kind: "manual",
files: { "index.html": { before: "a", after: "b" } },
}),
).resolves.toBeUndefined();
expect(controller.snapshot().canUndo).toBe(true);
});
it("serializes concurrent record edits against the latest state", async () => {
const storage = createMemoryEditHistoryStorage();
let timestamp = 100;
const store = createPersistentEditHistoryStore({
projectId: "project-1",
storage,
initialState: createEmptyEditHistory(),
now: () => timestamp++,
onChange: () => {},
});
await Promise.all([
store.recordEdit({
label: "Move layer",
kind: "manual",
files: { "index.html": { before: "a", after: "b" } },
}),
store.recordEdit({
label: "Resize layer",
kind: "manual",
files: { "index.html": { before: "b", after: "c" } },
}),
]);
expect(store.snapshot().state.undo.map((entry) => entry.label)).toEqual([
"Move layer",
"Resize layer",
]);
});
it("still coalesces concurrent source edits that share a coalesce key", async () => {
const storage = createMemoryEditHistoryStorage();
let timestamp = 100;
const store = createPersistentEditHistoryStore({
projectId: "project-1",
storage,
initialState: createEmptyEditHistory(),
now: () => timestamp++,
onChange: () => {},
});
await Promise.all([
store.recordEdit({
label: "Edit source",
kind: "source",
coalesceKey: "source:index.html",
files: { "index.html": { before: "a", after: "b" } },
}),
store.recordEdit({
label: "Edit source",
kind: "source",
coalesceKey: "source:index.html",
files: { "index.html": { before: "b", after: "c" } },
}),
]);
expect(store.snapshot().state.undo).toHaveLength(1);
expect(store.snapshot().state.undo[0].files["index.html"].before).toBe("a");
expect(store.snapshot().state.undo[0].files["index.html"].after).toBe("c");
});
it("reads undo hashes from the live top entry during queued undo calls", async () => {
const storage = createMemoryEditHistoryStorage();
let timestamp = 100;
const store = createPersistentEditHistoryStore({
projectId: "project-1",
storage,
initialState: createEmptyEditHistory(),
now: () => timestamp++,
onChange: () => {},
});
await store.recordEdit({
label: "Edit first file",
kind: "manual",
files: { "first.html": { before: "first-before", after: "first-after" } },
});
await store.recordEdit({
label: "Edit second file",
kind: "manual",
files: { "second.html": { before: "second-before", after: "second-after" } },
});
const files: Record<string, string> = {
"first.html": "first-after",
"second.html": "second-after",
};
const readPaths: string[] = [];
await Promise.all([
store.undo({
readFile: async (path) => {
readPaths.push(path);
return files[path];
},
writeFile: async (path, content) => {
files[path] = content;
},
}),
store.undo({
readFile: async (path) => {
readPaths.push(path);
return files[path];
},
writeFile: async (path, content) => {
files[path] = content;
},
}),
]);
expect(readPaths).toEqual(["second.html", "first.html"]);
expect(files).toEqual({
"first.html": "first-before",
"second.html": "second-before",
});
expect(store.snapshot().canUndo).toBe(false);
expect(store.snapshot().canRedo).toBe(true);
});
it("rolls back files when an undo write fails partway through", async () => {
const storage = createMemoryEditHistoryStorage();
const store = createPersistentEditHistoryStore({
projectId: "project-1",
storage,
initialState: createEmptyEditHistory(),
now: () => 100,
onChange: () => {},
});
await store.recordEdit({
label: "Edit files",
kind: "manual",
files: {
"first.html": { before: "first-before", after: "first-after" },
"second.html": { before: "second-before", after: "second-after" },
},
});
const files: Record<string, string> = {
"first.html": "first-after",
"second.html": "second-after",
};
const result = store.undo({
readFile: async (path) => files[path],
writeFile: async (path, content) => {
if (path === "second.html" && content === "second-before") {
throw new Error("write failed");
}
files[path] = content;
},
});
await expect(result).rejects.toThrow("write failed");
expect(files).toEqual({
"first.html": "first-after",
"second.html": "second-after",
});
expect(store.snapshot().undoLabel).toBe("Edit files");
expect(store.snapshot().canRedo).toBe(false);
});
});
@@ -1,337 +0,0 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
buildEditHistoryEntry,
createEmptyEditHistory,
hashEditHistoryContent,
pushEditHistoryEntry,
redoEditHistory,
undoEditHistory,
type BuildEditHistoryEntryInput,
type EditHistoryKind,
type EditHistoryState,
} from "../utils/editHistory";
import {
createIndexedDbEditHistoryStorage,
loadEditHistoryState,
saveEditHistoryState,
type EditHistoryStorageAdapter,
} from "../utils/editHistoryStorage";
interface RecordEditInput {
label: string;
kind: EditHistoryKind;
coalesceKey?: string;
files: BuildEditHistoryEntryInput["files"];
}
interface ApplyCallbacks {
readFile: (path: string) => Promise<string>;
writeFile: (path: string, content: string) => Promise<void>;
}
interface UsePersistentEditHistoryOptions {
projectId: string | null;
storage?: EditHistoryStorageAdapter;
now?: () => number;
}
interface ApplyResult {
ok: boolean;
reason?: "empty" | "content-mismatch";
label?: string;
paths?: string[];
}
interface PersistentEditHistoryStoreOptions {
projectId: string;
storage: EditHistoryStorageAdapter;
initialState: EditHistoryState;
now?: () => number;
onChange: (state: EditHistoryState) => void;
}
type EditHistoryMutation<T> = (state: EditHistoryState) => Promise<{
state: EditHistoryState;
result: T;
}>;
function createEntryId(now: number): string {
return `edit-${now.toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
}
function snapshotEditHistoryState(state: EditHistoryState) {
const undoEntry = state.undo[state.undo.length - 1] ?? null;
const redoEntry = state.redo[state.redo.length - 1] ?? null;
return {
canUndo: Boolean(undoEntry),
canRedo: Boolean(redoEntry),
undoLabel: undoEntry?.label ?? null,
redoLabel: redoEntry?.label ?? null,
undoPaths: undoEntry ? Object.keys(undoEntry.files) : [],
redoPaths: redoEntry ? Object.keys(redoEntry.files) : [],
state,
};
}
async function readCurrentFileHashes(
paths: string[],
readFile: (path: string) => Promise<string>,
): Promise<{
currentFiles: Record<string, string>;
currentHashes: Record<string, string>;
}> {
const currentFiles: Record<string, string> = {};
const currentHashes: Record<string, string> = {};
for (const path of paths) {
const content = await readFile(path);
currentFiles[path] = content;
currentHashes[path] = hashEditHistoryContent(content);
}
return { currentFiles, currentHashes };
}
async function writeFilesWithRollback({
files,
rollbackFiles,
writeFile,
}: {
files: Record<string, string>;
rollbackFiles: Record<string, string>;
writeFile: (path: string, content: string) => Promise<void>;
}): Promise<void> {
const writtenPaths: string[] = [];
try {
for (const [path, content] of Object.entries(files)) {
await writeFile(path, content);
writtenPaths.push(path);
}
} catch (error) {
try {
for (const path of writtenPaths.reverse()) {
await writeFile(path, rollbackFiles[path]);
}
} catch (rollbackError) {
throw new AggregateError(
[error, rollbackError],
"Failed to apply edit history and rollback did not complete",
);
}
throw error;
}
}
export function createPersistentEditHistoryStore({
projectId,
storage,
initialState,
now = Date.now,
onChange,
}: PersistentEditHistoryStoreOptions) {
let state = initialState;
let queue = Promise.resolve();
const save = async (nextState: EditHistoryState) => {
state = nextState;
onChange(nextState);
try {
await saveEditHistoryState(storage, projectId, nextState);
} catch {
// Keep in-memory history usable when IndexedDB is unavailable.
}
};
const mutate = async <T>(mutation: EditHistoryMutation<T>): Promise<T> => {
const run = queue.then(async () => {
const { state: nextState, result } = await mutation(state);
if (nextState !== state) await save(nextState);
return result;
});
queue = run.then(
() => undefined,
() => undefined,
);
return run;
};
return {
snapshot: () => snapshotEditHistoryState(state),
async recordEdit(input: RecordEditInput) {
await mutate<void>(async (currentState) => {
const timestamp = now();
const entry = buildEditHistoryEntry({
...input,
id: createEntryId(timestamp),
projectId,
now: timestamp,
});
return {
state: pushEditHistoryEntry(currentState, entry),
result: undefined,
};
});
},
async undo(callbacks: ApplyCallbacks): Promise<ApplyResult> {
return mutate<ApplyResult>(async (currentState) => {
const entry = currentState.undo[currentState.undo.length - 1];
if (!entry) {
return {
state: currentState,
result: { ok: false, reason: "empty" },
};
}
const { currentFiles, currentHashes } = await readCurrentFileHashes(
Object.keys(entry.files),
callbacks.readFile,
);
const result = undoEditHistory(currentState, currentHashes, now());
if (!result.ok) {
return {
state: currentState,
result: { ok: false, reason: result.reason },
};
}
await writeFilesWithRollback({
files: result.filesToWrite,
rollbackFiles: currentFiles,
writeFile: callbacks.writeFile,
});
return {
state: result.state,
result: { ok: true, label: result.entry.label, paths: Object.keys(result.entry.files) },
};
});
},
async redo(callbacks: ApplyCallbacks): Promise<ApplyResult> {
return mutate<ApplyResult>(async (currentState) => {
const entry = currentState.redo[currentState.redo.length - 1];
if (!entry) {
return {
state: currentState,
result: { ok: false, reason: "empty" },
};
}
const { currentFiles, currentHashes } = await readCurrentFileHashes(
Object.keys(entry.files),
callbacks.readFile,
);
const result = redoEditHistory(currentState, currentHashes, now());
if (!result.ok) {
return {
state: currentState,
result: { ok: false, reason: result.reason },
};
}
await writeFilesWithRollback({
files: result.filesToWrite,
rollbackFiles: currentFiles,
writeFile: callbacks.writeFile,
});
return {
state: result.state,
result: { ok: true, label: result.entry.label, paths: Object.keys(result.entry.files) },
};
});
},
};
}
export async function createPersistentEditHistoryController({
projectId,
storage,
now = Date.now,
onChange,
}: {
projectId: string;
storage: EditHistoryStorageAdapter;
now?: () => number;
onChange: (state: EditHistoryState) => void;
}) {
let state = await loadEditHistoryState(storage, projectId);
const store = createPersistentEditHistoryStore({
projectId,
storage,
initialState: state,
now,
onChange: (nextState) => {
state = nextState;
onChange(nextState);
},
});
return store;
}
export function usePersistentEditHistory(options: UsePersistentEditHistoryOptions) {
const storage = useMemo(
() => options.storage ?? createIndexedDbEditHistoryStorage(),
[options.storage],
);
const now = options.now ?? Date.now;
const [state, setState] = useState<EditHistoryState>(() => createEmptyEditHistory());
const [loaded, setLoaded] = useState(false);
const projectId = options.projectId;
const storeRef = useRef<ReturnType<typeof createPersistentEditHistoryStore> | null>(null);
useEffect(() => {
let cancelled = false;
const emptyState = createEmptyEditHistory();
storeRef.current = null;
setState(emptyState);
setLoaded(false);
if (!projectId) {
setLoaded(true);
return;
}
loadEditHistoryState(storage, projectId)
.then((loadedState) => {
if (cancelled) return;
storeRef.current = createPersistentEditHistoryStore({
projectId,
storage,
initialState: loadedState,
now,
onChange: setState,
});
setState(loadedState);
})
.catch(() => {
if (cancelled) return;
storeRef.current = createPersistentEditHistoryStore({
projectId,
storage,
initialState: emptyState,
now,
onChange: setState,
});
setState(emptyState);
})
.finally(() => {
if (!cancelled) setLoaded(true);
});
return () => {
cancelled = true;
};
}, [now, projectId, storage]);
const recordEdit = useCallback(async (input: RecordEditInput) => {
await storeRef.current?.recordEdit(input);
}, []);
const undo = useCallback(async (callbacks: ApplyCallbacks): Promise<ApplyResult> => {
return storeRef.current?.undo(callbacks) ?? { ok: false, reason: "empty" };
}, []);
const redo = useCallback(async (callbacks: ApplyCallbacks): Promise<ApplyResult> => {
return storeRef.current?.redo(callbacks) ?? { ok: false, reason: "empty" };
}, []);
return {
loaded,
...snapshotEditHistoryState(state),
recordEdit,
undo,
redo,
};
}