Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(undo): close the two holes in the write audit's guarantee
EtienneLescotefc7544f312e
diff --git a/electron/edit-menu.test.ts b/electron/edit-menu.test.tsindex 47ff19121..3b547895f 100644--- a/electron/edit-menu.test.ts+++ b/electron/edit-menu.test.ts@@ -7,10 +7,19 @@// the web contents, and the editor's own keydown handler never runs.//// These tests pin the shape that actually reaches the renderer on every platform:-// an explicit accelerator and a click that dispatches to the editor.+// an explicit accelerator and a click that dispatches to the editor -- and, in the+// second describe, where that dispatch actually lands. Dropping the roles took+// `webContents.undo()` away from every window, so the non-editor fallback is not a+// detail: it is the half of the design that keeps the launch and notes windows+// working.import { describe, expect, it, vi } from "vitest";-import { buildEditMenuSubmenu, type EditorUndoRedoChannel } from "./edit-menu";+import {+ buildEditMenuSubmenu,+ type EditorUndoRedoChannel,+ routeEditorUndoRedo,+ type UndoRedoWindow,+} from "./edit-menu";function build() {const dispatch = vi.fn<(channel: EditorUndoRedoChannel) => void>();@@ -71,3 +80,65 @@ describe("buildEditMenuSubmenu", () => {expect(items.map((i) => i.role).filter(Boolean)).toEqual(["cut", "copy", "paste", "selectAll"]);});});++function editorWindow() {+ const webContents = {+ send: vi.fn<(channel: EditorUndoRedoChannel) => void>(),+ undo: vi.fn(),+ redo: vi.fn(),+ };+ const isDestroyed = vi.fn(() => false);+ return {+ window: { isDestroyed, webContents } satisfies UndoRedoWindow,+ webContents,+ isDestroyed,+ };+}++describe("routeEditorUndoRedo", () => {+ it("hands the editor window the request over IPC", () => {+ // The editor renderer owns the document's undo stack, and applies the text-field+ // rule its own keydown path applies. `webContents.undo()` could not do either.+ const target = editorWindow();++ routeEditorUndoRedo("menu-undo", target.window, () => true);+ routeEditorUndoRedo("menu-redo", target.window, () => true);++ expect(target.webContents.send.mock.calls).toEqual([["menu-undo"], ["menu-redo"]]);+ expect(target.webContents.undo).not.toHaveBeenCalled();+ expect(target.webContents.redo).not.toHaveBeenCalled();+ });++ it("falls back to the web-editing undo when the focused window is not the editor", () => {+ // The case the whole design rests on. Dropping `role: "undo"` took the menu's+ // built-in `webContents.undo()` away from EVERY window, so the launch window and+ // the notes window -- where the role was the right answer -- get it back here.+ const target = editorWindow();++ routeEditorUndoRedo("menu-undo", target.window, () => false);+ expect(target.webContents.undo).toHaveBeenCalledOnce();+ expect(target.webContents.redo).not.toHaveBeenCalled();++ routeEditorUndoRedo("menu-redo", target.window, () => false);+ expect(target.webContents.redo).toHaveBeenCalledOnce();++ expect(target.webContents.send).not.toHaveBeenCalled();+ });++ it("does nothing when there is no window, or it has been destroyed", () => {+ // Unlike `sendEditorMenuAction` this never creates one: Cmd+Z is not a request to+ // open the editor. And the destroyed check runs before anything reads the window,+ // which is why `isEditor` is a callback -- `webContents.getURL()` on a destroyed+ // window throws.+ const isEditor = vi.fn(() => true);+ expect(() => routeEditorUndoRedo("menu-undo", null, isEditor)).not.toThrow();++ const target = editorWindow();+ target.isDestroyed.mockReturnValue(true);+ routeEditorUndoRedo("menu-undo", target.window, isEditor);++ expect(target.webContents.send).not.toHaveBeenCalled();+ expect(target.webContents.undo).not.toHaveBeenCalled();+ expect(isEditor).not.toHaveBeenCalled();+ });+});diff --git a/electron/edit-menu.ts b/electron/edit-menu.tsindex 69e798a2b..a01b87297 100644--- a/electron/edit-menu.ts+++ b/electron/edit-menu.ts@@ -35,6 +35,51 @@ export interface EditMenuOptions {dispatch: (channel: EditorUndoRedoChannel) => void;}+/** The slice of `WebContents` the routing below touches. */+export interface UndoRedoWebContents {+ send: (channel: EditorUndoRedoChannel) => void;+ undo: () => void;+ redo: () => void;+}++/** The slice of `BrowserWindow` the routing below touches. */+export interface UndoRedoWindow {+ isDestroyed: () => boolean;+ webContents: UndoRedoWebContents;+}++/**+ * Deliver an undo/redo request to the window that should service it.+ *+ * Lives here rather than in `main.ts` for the reason `about.ts` does: `main.ts`+ * calls `app.requestSingleInstanceLock()` at import time and cannot be loaded by a+ * test, so anything left in it is untested by construction.+ *+ * Three cases, and the middle one is the whole reason the menu items dropped their+ * `role`. There is no window, or it is gone: nothing to do — unlike+ * `sendEditorMenuAction` this never CREATES an editor window, because Cmd+Z is not+ * a request to open the editor. The window is not the editor — the launch window,+ * the notes window — so the web-editing undo the `undo` role used to provide is the+ * right one after all, and it is reached directly. Otherwise it is the editor, and+ * the editor's renderer owns the document's undo stack.+ *+ * `isEditor` is a callback, not a flag, so nothing reads the window's URL before+ * the destroyed check has run.+ */+export function routeEditorUndoRedo(+ channel: EditorUndoRedoChannel,+ window: UndoRedoWindow | null | undefined,+ isEditor: () => boolean,+): void {+ if (!window || window.isDestroyed()) return;+ if (!isEditor()) {+ if (channel === "menu-undo") window.webContents.undo();+ else window.webContents.redo();+ return;+ }+ window.webContents.send(channel);+}+export function buildEditMenuSubmenu({label,dispatch,diff --git a/electron/main.ts b/electron/main.tsindex 5a755b824..85eb063b8 100644--- a/electron/main.ts+++ b/electron/main.ts@@ -33,7 +33,7 @@ import {import { parseCliArgs } from "./cli/args";import { runCli } from "./cli/cliMain";import { isDiagnosticModeEnabled, mainLogBuffer } from "./diagnostics/main-log-buffer";-import { buildEditMenuSubmenu, type EditorUndoRedoChannel } from "./edit-menu";+import { buildEditMenuSubmenu, type EditorUndoRedoChannel, routeEditorUndoRedo } from "./edit-menu";import {loadAndRegisterGlobalShortcut,registerOpenAppShortcut,@@ -191,22 +191,12 @@ function sendEditorMenuAction(}/**- * Route the Edit menu's Undo/Redo to whoever should service it.- *- * Unlike `sendEditorMenuAction` this never CREATES an editor window: Cmd+Z is not- * a request to open the editor. And when the focused window is not the editor --- * the launch window, the notes window -- the web-editing undo the `undo` role used- * to provide is the right one after all, so fall through to it.+ * Resolve which window the Edit menu's Undo/Redo is aimed at. The routing itself+ * is `routeEditorUndoRedo`, in `edit-menu.ts`, where a test can reach it.*/function sendEditorUndoRedo(channel: EditorUndoRedoChannel) {const targetWindow = BrowserWindow.getFocusedWindow() ?? mainWindow;- if (!targetWindow || targetWindow.isDestroyed()) return;- if (!isEditorWindow(targetWindow)) {- if (channel === "menu-undo") targetWindow.webContents.undo();- else targetWindow.webContents.redo();- return;- }- targetWindow.webContents.send(channel);+ routeEditorUndoRedo(channel, targetWindow, () => !!targetWindow && isEditorWindow(targetWindow));}function setupApplicationMenu() {diff --git a/src/components/ai-edition/recordingImport.test.ts b/src/components/ai-edition/recordingImport.test.tsindex a5810e342..4faea3d5c 100644--- a/src/components/ai-edition/recordingImport.test.ts+++ b/src/components/ai-edition/recordingImport.test.ts@@ -4,7 +4,7 @@ import { replaceTimeline as replaceTimelineOp } from "@/lib/ai-edition/document/import { type AxcutDocument, createEmptyDocument } from "@/lib/ai-edition/schema";import { useProjectStore } from "@/lib/ai-edition/store/projectStore";import { undo } from "@/lib/ai-edition/store/undo";-import { past } from "@/lib/ai-edition/store/undoStack";+import { clearHistory, past } from "@/lib/ai-edition/store/undoStack";import { importPendingRecording } from "./recordingImport";// The first describe stubs the store actions, so the bridge is never reached@@ -146,7 +146,7 @@ describe("what the recording import leaves on the undo stack", () => {vi.clearAllMocks();useProjectStore.getState().clear();useProjectStore.setState(realActions);- past.length = 0;+ clearHistory();bridge.create.mockImplementation(async () => ({success: true,document: createEmptyDocument({ projectId: PROJECT_ID, title: "Recording" }),diff --git a/src/lib/ai-edition/store/documentWriteAudit.test.ts b/src/lib/ai-edition/store/documentWriteAudit.test.tsindex 16f8aff29..f798c35f7 100644--- a/src/lib/ai-edition/store/documentWriteAudit.test.ts+++ b/src/lib/ai-edition/store/documentWriteAudit.test.ts@@ -24,13 +24,16 @@// So: this file is the table. A new write, a moved one, or a changed `history`// value fails here with a diff, and the only way to make it pass is to write down// what triggers it. `recordHistory` is unreachable except through the two writers-// enumerated below, which the last two tests pin as well -- so the table is the-// whole surface, not a sample of it.+// enumerated below, and the only other way an entry reaches a stack is undo/redo+// stepping over one -- the tests after the table pin both, and the stacks are+// `readonly` so there is no third way that skips a name this file can count. The+// table is the whole surface, not a sample of it.import { readdirSync, readFileSync, statSync } from "node:fs";import { relative, resolve } from "node:path";import ts from "typescript";import { describe, expect, it } from "vitest";+import { clearHistory, future, past } from "./undoStack";const ROOT = process.cwd();const SRC = resolve(ROOT, "src");@@ -45,7 +48,9 @@ type Trigger =| "automatic"/** A wrapper. Hands its caller's option straight through, so the decision stays* with whoever knows the answer. `forwarded` is checked structurally: the- * identifier passed on must be a PARAMETER of the enclosing function. */+ * identifier passed on must resolve to a PARAMETER, in the first enclosing+ * scope that binds that name — a local `const` of the same name is not a+ * forward, however many outer functions have a parameter called that. */| "forwarded";interface WritePath {@@ -248,32 +253,96 @@ function nameOf(fn: FunctionLike): string | null {return null;}-/** The innermost enclosing function that has a name, and the chain down to the call —- * `forwarded` needs the chain to check the identifier really is a parameter. */-function enclosingFunctions(call: ts.Node): { name: string; functions: FunctionLike[] } {- const functions: FunctionLike[] = [];+/** The innermost enclosing function that has a name. */+function enclosingFunctionName(call: ts.Node): string {let node: ts.Node | undefined = call.parent;- let name: string | null = null;while (node) {if (isFunctionLike(node)) {- functions.push(node);- name ??= nameOf(node);+ const name = nameOf(node);+ if (name) return name;}node = node.parent;}- return { name: name ?? "<module>", functions };+ return "<module>";}-function triggerOf(call: ts.CallExpression, functions: FunctionLike[]): Trigger | string {+/** Every name a binding introduces, destructuring included. */+function bindsName(binding: ts.BindingName, name: string): boolean {+ if (ts.isIdentifier(binding)) return binding.text === name;+ return binding.elements.some(+ (element) => ts.isBindingElement(element) && bindsName(element.name, name),+ );+}++function declaresInList(list: ts.VariableDeclarationList, name: string): boolean {+ return list.declarations.some((declaration) => bindsName(declaration.name, name));+}++/** Whether this scope binds `name` as a LOCAL — the thing a forward is not. */+function scopeDeclaresLocal(scope: ts.Node, name: string): boolean {+ const inStatements = (statements: readonly ts.Statement[]) =>+ statements.some(+ (statement) =>+ ts.isVariableStatement(statement) && declaresInList(statement.declarationList, name),+ );+ if (ts.isSourceFile(scope) || ts.isBlock(scope) || ts.isModuleBlock(scope))+ return inStatements(scope.statements);+ if (ts.isCaseBlock(scope)) return scope.clauses.some((clause) => inStatements(clause.statements));+ if (ts.isForStatement(scope) || ts.isForInStatement(scope) || ts.isForOfStatement(scope))+ return (+ !!scope.initializer &&+ ts.isVariableDeclarationList(scope.initializer) &&+ declaresInList(scope.initializer, name)+ );+ if (ts.isCatchClause(scope))+ return !!scope.variableDeclaration && bindsName(scope.variableDeclaration.name, name);+ return false;+}++/**+ * Where the identifier handed to a writer as its options argument was bound.+ *+ * The walk goes OUTWARD from the call and stops at the FIRST scope that binds the+ * name. Stopping is the point. The previous version collected every function-like+ * ancestor up to the module and asked whether ANY of them had a parameter of that+ * name, so a local `const opts = { history: true }` read as `forwarded` the moment+ * an unrelated outer function happened to have an `opts` parameter — which+ * `useSequentialTimelineOps` does, on the hook itself. That is precisely the+ * hardcode-in-a-disguise the check exists to expose.+ *+ * "The innermost function's parameters" is not the rule either, though, and the+ * walk has to leave that function: `useSequentialTimelineOps.apply` calls+ * `saveDocument(applied.document, opts)` inside a zero-parameter `async () => {}`,+ * and `opts` is the parameter of the `useCallback` arrow two scopes further out.+ */+function bindingOf(call: ts.Node, name: string): "parameter" | "local" {+ let node: ts.Node | undefined = call.parent;+ while (node) {+ if (scopeDeclaresLocal(node, name)) return "local";+ if (isFunctionLike(node) && node.parameters.some((p) => bindsName(p.name, name)))+ return "parameter";+ node = node.parent;+ }+ // Bound nowhere on the way out: a module binding, an import, or a global. None of+ // them is the caller's decision either.+ return "local";+}++function triggerOf(call: ts.CallExpression): Trigger | string {+ // Arity before `at(-1)`. On a one-argument call the last argument is the DOCUMENT,+ // and if that document is an identifier naming an enclosing parameter the call+ // reads as `forwarded` instead of as the mistake it is. Both writers require the+ // options argument today, so this cannot bite — but "the compiler would have+ // caught it" is exactly the reasoning this file exists not to rely on.+ if (call.arguments.length < 2) return "no options argument";const opts = call.arguments.at(-1);if (!opts) return "no options argument";if (ts.isIdentifier(opts)) {// A wrapper only counts as forwarding if what it passes on came from OUTSIDE.// A local `const opts = { history: true }` is a hardcode wearing a disguise.- const isParameter = functions.some((fn) =>- fn.parameters.some((p) => ts.isIdentifier(p.name) && p.name.text === opts.text),- );- return isParameter ? "forwarded" : `local variable \`${opts.text}\``;+ return bindingOf(call, opts.text) === "parameter"+ ? "forwarded"+ : `local variable \`${opts.text}\``;}if (!ts.isObjectLiteralExpression(opts)) return "options are not an object literal";const history = opts.properties.find(@@ -297,6 +366,12 @@ function scan(): Scan {const callsTo = new Map<string, { file: string; fn: string }[]>([["pushHistory", []],["recordHistory", []],+ // The other two ways an entry can land on a stack. They exist because the+ // arrays are `readonly` now, which is what turned "somebody called `.push` on+ // an exported array" — invisible here, the callee name is `push` — into a+ // named call this scan can count.+ ["pushPast", []],+ ["pushFuture", []],]);for (const path of sourceFiles(SRC)) {const file = relative(ROOT, path).split("\\").join("/");@@ -310,14 +385,14 @@ function scan(): Scan {const visit = (node: ts.Node) => {if (ts.isCallExpression(node)) {const callee = calleeName(node);- const { name, functions } = callee ? enclosingFunctions(node) : { name: "", functions: [] };+ const name = callee ? enclosingFunctionName(node) : "";if (callee) callsTo.get(callee)?.push({ file, fn: name });if (callee && WRITERS.has(callee)) {writes.push({file,fn: name,writer: callee as WritePath["writer"],- trigger: triggerOf(node, functions) as Trigger,+ trigger: triggerOf(node) as Trigger,});}}@@ -358,4 +433,124 @@ describe("every write that can reach the undo stack", () => {{ file: "src/lib/ai-edition/store/projectStore.ts", fn: "recordHistory" },]);});++ it("grows the stacks only through `pushHistory` and undo/redo's own two pushes", () => {+ // `undo` and `redo` hand each other the document they are stepping over, which+ // is not a new edit and must not clear the other stack -- so they cannot go+ // through `pushHistory`. Those two calls are the whole remainder, and the rows+ // below are what makes that a checked statement rather than a claim.+ expect(scanned.callsTo.get("pushPast")).toEqual([+ { file: "src/lib/ai-edition/store/undo.ts", fn: "redo" },+ ]);+ expect(scanned.callsTo.get("pushFuture")).toEqual([+ { file: "src/lib/ai-edition/store/undo.ts", fn: "undo" },+ ]);+ });++ it("cannot be grown by an importer reaching around those names", () => {+ // The hole this closes. `past` and `future` were exported as `Snapshot[]`, and+ // `const` binds the reference, not the contents -- so `past.push(...)` from any+ // importer recorded history, and the scan above could not see it: it keys on the+ // callee NAME, and the name there is `push`.+ //+ // The assertions are the `@ts-expect-error`s. Each one is an error itself the+ // moment the directive stops suppressing anything, so this test fails the+ // typecheck pass if the stacks ever go mutable again.+ // @ts-expect-error `past` is `readonly Snapshot[]`; record through `pushHistory`.+ past.push({ projectId: "project_x", doc: {} });+ // @ts-expect-error `future` is `readonly Snapshot[]`; step forward through `pushFuture`.+ future.push({ projectId: "project_x", doc: {} });+ // @ts-expect-error `length` is read-only too; empty the stacks with `clearHistory`.+ past.length = 0;++ // The lines above still RUN -- `readonly` is erased, it is the same array -- so+ // leave the module the way this file found it.+ clearHistory();+ expect(past).toHaveLength(0);+ expect(future).toHaveLength(0);+ });+});++// ---------------------------------------------------------------------------+// The audit's own rule, pinned. The table above is worth exactly as much as+// `triggerOf`, and a `forwarded` that an unrelated outer parameter name can spoof+// is the hole the audit exists to close.+// ---------------------------------------------------------------------------++/** Classify the first `saveDocument(...)` call in a snippet. Parsed, not+ * type-checked, so the fixtures can leave their free variables undeclared. */+function classify(fixture: string): Trigger | string {+ const source = ts.createSourceFile(+ "fixture.ts",+ fixture,+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TS,+ );+ const calls: ts.CallExpression[] = [];+ const visit = (node: ts.Node) => {+ if (ts.isCallExpression(node) && calleeName(node) === "saveDocument") calls.push(node);+ ts.forEachChild(node, visit);+ };+ visit(source);+ const [call] = calls;+ if (!call) throw new Error("fixture has no `saveDocument` call");+ return triggerOf(call);+}++describe("how a write's trigger is read off its call site", () => {+ it("does not call a local `opts` forwarded because an OUTER function has one", () => {+ // The shape that was live: `useSequentialTimelineOps` takes a parameter called+ // `options`, so anything written inside that hook as a local `options` would have+ // read as `forwarded` -- a hardcode wearing exactly the disguise the check is+ // supposed to strip off.+ expect(+ classify(`+ function useOps(opts) {+ return () => {+ const opts = { history: true };+ saveDocument(doc, opts);+ };+ }+ `),+ ).toBe("local variable `opts`");+ });++ it("still forwards across an inner function that takes no parameters", () => {+ // `useSequentialTimelineOps.apply`, reduced: the call sits in a zero-parameter+ // `async () => {}` and `opts` is bound two scopes out. Stopping the walk at the+ // innermost function would break this row.+ expect(+ classify(`+ const apply = (op, opts) =>+ enqueue(async () => {+ const doc = current();+ return saveDocument(doc, opts);+ });+ `),+ ).toBe("forwarded");+ });++ it("reads a destructured local as a local, not as a forward", () => {+ expect(+ classify(`+ function wrapper(opts) {+ const { opts } = defaults;+ saveDocument(doc, opts);+ }+ `),+ ).toBe("local variable `opts`");+ });++ it("says so when there is no options argument at all", () => {+ // Without the arity check the last argument here is the DOCUMENT, and `doc` names+ // an enclosing parameter -- so the call reported itself as forwarding.+ expect(+ classify(`+ function wrapper(doc) {+ saveDocument(doc);+ }+ `),+ ).toBe("no options argument");+ });});diff --git a/src/lib/ai-edition/store/projectStore.test.ts b/src/lib/ai-edition/store/projectStore.test.tsindex 9ad09572e..40f043976 100644--- a/src/lib/ai-edition/store/projectStore.test.ts+++ b/src/lib/ai-edition/store/projectStore.test.ts@@ -1,6 +1,7 @@// @vitest-environment jsdomimport { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { useProjectStore } from "./projectStore";+import { clearHistory, past, pushHistory } from "./undoStack";const bridgeMocks = vi.hoisted(() => ({get: vi.fn(),@@ -378,4 +379,47 @@ describe("useProjectStore", () => {error: null,});});++ it("clear drops the undo history with the project", () => {+ // Explicit rather than leaning on the `beforeEach`, which reaches this same code.+ clearHistory();+ useProjectStore.setState({ projectId: "proj_test", document: sampleDoc });+ pushHistory({ projectId: "proj_test", doc: sampleDoc });+ expect(past).toHaveLength(1);++ useProjectStore.getState().clear();++ // Hygiene rather than a restore hazard -- `undo` refuses a snapshot whose+ // projectId does not match, and there is no projectId left to match. What the+ // stack was actually holding is up to fifty cloned documents, kept alive until+ // the next project load.+ expect(past).toHaveLength(0);+ });++ it("clear supersedes a save that was already in flight", async () => {+ // `clear()`'s one production caller deletes the open project. A background save+ // issued a moment earlier -- a transcript, a duration probe -- used to resolve+ // after it and reinstall the deleted project's document over the empty state,+ // with `dirty: false` and a fresh `lastSavedAt` claiming it was on disk.+ const renamed = { ...sampleDoc, project: { ...sampleDoc.project, title: "Renamed" } };+ clearHistory();+ useProjectStore.setState({ projectId: "proj_test", document: sampleDoc, dirty: true });+ let release: (() => void) | undefined;+ bridgeMocks.save.mockReturnValue(+ new Promise((resolve) => {+ release = () => resolve({ success: true, document: renamed });+ }),+ );++ const inFlight = useProjectStore.getState().saveDocument(renamed, { history: true });+ useProjectStore.getState().clear();+ release?.();++ await expect(inFlight).resolves.toBe(false);+ expect(useProjectStore.getState().document).toBeNull();+ expect(useProjectStore.getState().dirty).toBe(false);+ // And nothing recorded either: the write that would have pushed the pre-rename+ // document is the one being dropped.+ expect(past).toHaveLength(0);+ });});diff --git a/src/lib/ai-edition/store/projectStore.ts b/src/lib/ai-edition/store/projectStore.tsindex b29bbec49..90584ee54 100644--- a/src/lib/ai-edition/store/projectStore.ts+++ b/src/lib/ai-edition/store/projectStore.ts@@ -111,6 +111,11 @@ export interface ProjectState {setCurrentTime: (sec: number) => void;setPlaying: (playing: boolean) => void;markClean: () => void;+ /**+ * Drop the open project. Clears the undo history and supersedes every in-flight+ * write, the same as `loadProject` and `createProject` — this is a project+ * switch too, just one with nothing on the other side of it.+ */clear: () => void;}@@ -413,6 +418,21 @@ export const useProjectStore = create<ProjectState>((set, get) => ({},clear() {+ // The epoch bump inside `clearHistory` is the load-bearing half, not the stack+ // drop. `clear()`'s one production caller deletes the project that is open+ // (`NewEditorShell`), and a background save issued a moment earlier -- a+ // transcript, a duration probe, a dimension backfill -- was still in flight. On+ // resolving it installed its document and set `dirty: false, lastSavedAt: now`,+ // so the editor that had just shown the empty state and toasted "Project+ // deleted" put the deleted project's document back on screen with+ // `projectId: null`, claiming it was freshly saved. Superseding those writes is+ // exactly what this moment means.+ //+ // Dropping the stacks is hygiene by comparison: `undo` already refuses a+ // snapshot whose `projectId` does not match the store's, and after this `set`+ // there is no `projectId` at all -- so a stale stack could only leak up to+ // MAX_HISTORY cloned documents until the next project load, never restore one.+ clearHistory();set({projectId: null,document: null,diff --git a/src/lib/ai-edition/store/undo.test.ts b/src/lib/ai-edition/store/undo.test.tsindex 9e07ceb30..dbf659358 100644--- a/src/lib/ai-edition/store/undo.test.ts+++ b/src/lib/ai-edition/store/undo.test.ts@@ -11,7 +11,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import { createEmptyDocument } from "../schema";import { useProjectStore } from "./projectStore";import { clearHistory, redo, undo, useUndoRedoShortcuts } from "./undo";-import { future, past } from "./undoStack";+import { future, past, pushHistory } from "./undoStack";const saveMock = vi.hoisted(() => vi.fn());@@ -348,7 +348,7 @@ describe("the Edit menu's undo/redo route", () => {// two tests either side of this one passed without a guard.const persist = vi.fn();const { result } = renderHook(() => useUndoRedoShortcuts(persist));- past.push({ projectId: PROJECT_ID, doc: titled("Older") });+ pushHistory({ projectId: PROJECT_ID, doc: titled("Older") });const modal = window.document.createElement("div");modal.setAttribute("aria-modal", "true");@@ -380,7 +380,7 @@ describe("the Edit menu's undo/redo route", () => {// still good for.const persist = vi.fn();const { result } = renderHook(() => useUndoRedoShortcuts(persist));- past.push({ projectId: PROJECT_ID, doc: titled("Older") });+ pushHistory({ projectId: PROJECT_ID, doc: titled("Older") });const input = window.document.createElement("input");window.document.body.appendChild(input);diff --git a/src/lib/ai-edition/store/undo.ts b/src/lib/ai-edition/store/undo.tsindex 3b9b28bff..bc70ea53b 100644--- a/src/lib/ai-edition/store/undo.ts+++ b/src/lib/ai-edition/store/undo.ts@@ -15,7 +15,14 @@ import { useCallback, useEffect, useRef } from "react";import { isModalOpen } from "../modalGuard";import type { AxcutDocument } from "../schema";import { useProjectStore } from "./projectStore";-import { clearHistory, future, past, supersedeInFlightWrites } from "./undoStack";+import {+ clearHistory,+ popFuture,+ popPast,+ pushFuture,+ pushPast,+ supersedeInFlightWrites,+} from "./undoStack";export { clearHistory } from "./undoStack";@@ -36,7 +43,7 @@ function restore(doc: unknown) {}export function undo(): boolean {- const prev = past.pop();+ const prev = popPast();if (!prev) return false;const state = useProjectStore.getState();if (!state.projectId || state.projectId !== prev.projectId) {@@ -44,13 +51,13 @@ export function undo(): boolean {return false;}const doc = state.document;- if (doc) future.push({ projectId: prev.projectId, doc: structuredClone(doc) });+ if (doc) pushFuture({ projectId: prev.projectId, doc: structuredClone(doc) });restore(prev.doc);return true;}export function redo(): boolean {- const next = future.pop();+ const next = popFuture();if (!next) return false;const state = useProjectStore.getState();if (!state.projectId || state.projectId !== next.projectId) {@@ -58,7 +65,7 @@ export function redo(): boolean {return false;}const doc = state.document;- if (doc) past.push({ projectId: doc.project.id, doc: structuredClone(doc) });+ if (doc) pushPast({ projectId: doc.project.id, doc: structuredClone(doc) });restore(next.doc);return true;}diff --git a/src/lib/ai-edition/store/undoStack.ts b/src/lib/ai-edition/store/undoStack.tsindex be56a89cc..8d13da699 100644--- a/src/lib/ai-edition/store/undoStack.ts+++ b/src/lib/ai-edition/store/undoStack.ts@@ -16,25 +16,63 @@// keeps the audit in `documentWriteAudit.test.ts` honest: `recordHistory` in// `projectStore` is its only production caller, and a second import path would// be a second way to record history without saying so at the call site.+//+// The arrays themselves are module-private for the same reason. They used to be+// exported as `Snapshot[]`, and `const` binds the reference, not the contents --+// so `past.push(...)` from any importer was a second way to record history that+// the audit could not see at all: it keys on the callee NAME, and the name there+// is `push`. The exported `past` / `future` are `readonly` views, and every+// mutation is a named function the audit can count call sites of.export type Snapshot = { projectId: string; doc: unknown };const MAX_HISTORY = 50;-export const past: Snapshot[] = [];-export const future: Snapshot[] = [];+const pastStack: Snapshot[] = [];+const futureStack: Snapshot[] = [];++/** The undo stack, read-only. Mutate it through the functions below, which is+ * what makes `documentWriteAudit.test.ts` able to enumerate the writers. */+export const past: readonly Snapshot[] = pastStack;+/** The redo stack, on the same terms as `past`. */+export const future: readonly Snapshot[] = futureStack;/** Record a document as the state to return to. Drops the redo stack: history* branched the moment a new edit landed on top of an undone one. */export function pushHistory(snapshot: Snapshot) {- past.push(snapshot);- if (past.length > MAX_HISTORY) past.shift();- future.length = 0;+ pastStack.push(snapshot);+ if (pastStack.length > MAX_HISTORY) pastStack.shift();+ futureStack.length = 0;+}++/**+ * Put the document a REDO is replacing back on `past`, so the redo is itself+ * undoable.+ *+ * Not `pushHistory`: that one clears `future`, which is right for a new edit+ * (history branched) and wrong here, where the remaining redo steps are still+ * ahead of the user and the entry being pushed is one they just walked past.+ */+export function pushPast(snapshot: Snapshot) {+ pastStack.push(snapshot);+}++/** Put the document an UNDO is leaving on `future`, so redo can get back to it. */+export function pushFuture(snapshot: Snapshot) {+ futureStack.push(snapshot);+}++export function popPast(): Snapshot | undefined {+ return pastStack.pop();+}++export function popFuture(): Snapshot | undefined {+ return futureStack.pop();}export function clearHistory() {- past.length = 0;- future.length = 0;+ pastStack.length = 0;+ futureStack.length = 0;supersedeInFlightWrites();}