Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(editor): make every write name its own history decision, wrapper or not

EtienneLescota53612614d7b
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index fd8607cd4..64987dea9 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -575,25 +575,31 @@ export function NewEditorShell() {
(target: TrimTarget, startSec: number, endSec: number, reason: string) => {
// `clipId` is what keeps the cut on the block the user typed in: with two clips
// over the same media, an asset-only trim showed up on both (see `trimAppliesToClip`).
- void applyTimelineOp({
- type: "add_trim_range",
- assetId: target.assetId,
- clipId: target.clipId,
- startSec,
- endSec,
- reason,
- });
+ void applyTimelineOp(
+ {
+ type: "add_trim_range",
+ assetId: target.assetId,
+ clipId: target.clipId,
+ startSec,
+ endSec,
+ reason,
+ },
+ { history: true },
+ );
},
[applyTimelineOp],
);
const handleRemoveTrimRange = useCallback(
(trimId: string) => {
- void applyTimelineOp({
- type: "remove_trim_range",
- trimId,
- reason: "Restored from transcript pane.",
- });
+ void applyTimelineOp(
+ {
+ type: "remove_trim_range",
+ trimId,
+ reason: "Restored from transcript pane.",
+ },
+ { history: true },
+ );
},
[applyTimelineOp],
);
diff --git a/src/components/ai-edition/recordingImport.test.ts b/src/components/ai-edition/recordingImport.test.ts
index 2c9728d44..a5810e342 100644
--- a/src/components/ai-edition/recordingImport.test.ts
+++ b/src/components/ai-edition/recordingImport.test.ts
@@ -1,16 +1,34 @@
// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { replaceTimeline as replaceTimelineOp } from "@/lib/ai-edition/document/timeline";
+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 { importPendingRecording } from "./recordingImport";
-// The store's own bridge calls are never reached — every action the import uses
-// is stubbed below — but importing the store pulls the client in, so stub it.
-vi.mock("@/native/client", () => ({ nativeBridgeClient: { aiEdition: {} } }));
+// The first describe stubs the store actions, so the bridge is never reached
+// there. The second one runs the REAL store against these, which is the only way
+// to see what the import leaves on the undo stack.
+const bridge = vi.hoisted(() => ({
+ create: vi.fn(),
+ addAsset: vi.fn(),
+ save: vi.fn(),
+}));
+vi.mock("@/native/client", () => ({ nativeBridgeClient: { aiEdition: bridge } }));
const createProject = vi.fn(async () => undefined);
const addAsset = vi.fn(async () => null);
const replaceTimeline = vi.fn(async () => undefined);
+// Read before anything stubs them: the first describe replaces these actions on the
+// live store, and `clear()` resets the DATA, not the actions.
+const realActions = {
+ createProject: useProjectStore.getState().createProject,
+ addAsset: useProjectStore.getState().addAsset,
+ replaceTimeline: useProjectStore.getState().replaceTimeline,
+};
+
/** Stands in for the main-process recording slot: one value, set and read. */
function stubElectronApi(screenVideoPath: string | null) {
let session = screenVideoPath ? { screenVideoPath, createdAt: 0 } : null;
@@ -86,6 +104,86 @@ describe("importPendingRecording", () => {
expect(replaceTimeline).toHaveBeenCalledWith(
[{ startSec: 0, endSec: 60 }],
"Auto-imported recording",
+ { history: false },
);
});
});
+
+// The whole hand-off, against the real store: stop the recording, land in the
+// editor, press Ctrl+Z.
+//
+// The user has made no edit at this point -- the editor built this project for
+// them, unattended, on mount. The seed below used to record itself as an undo
+// step because `projectStore.replaceTimeline` hardcoded `{ history: true }` inside
+// itself, where the option was invisible to its caller. So a brand-new project
+// opened with `past.length === 1`, the first Ctrl+Z restored the state before the
+// seed -- an empty timeline -- and `NewEditorShell`'s post-undo persist wrote that
+// empty timeline to disk.
+describe("what the recording import leaves on the undo stack", () => {
+ const PROJECT_ID = "project_imported";
+ const SCREEN_PATH = "/recordings/recording-1.webm";
+
+ /** The document the main process actually returns from `addAsset`: an asset with
+ * no `durationSec` (it stats the file, it does not probe it). */
+ function withAsset(): AxcutDocument {
+ const doc = createEmptyDocument({ projectId: PROJECT_ID, title: "Recording" });
+ return {
+ ...doc,
+ assets: [
+ {
+ id: "asset_1",
+ kind: "video",
+ label: "recording-1.webm",
+ originalPath: SCREEN_PATH,
+ cameraTrack: null,
+ },
+ ],
+ project: { ...doc.project, primaryAssetId: "asset_1" },
+ };
+ }
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ useProjectStore.getState().clear();
+ useProjectStore.setState(realActions);
+ past.length = 0;
+ bridge.create.mockImplementation(async () => ({
+ success: true,
+ document: createEmptyDocument({ projectId: PROJECT_ID, title: "Recording" }),
+ }));
+ bridge.addAsset.mockImplementation(async () => ({ success: true, document: withAsset() }));
+ bridge.save.mockImplementation(async (document: unknown) => ({ success: true, document }));
+ stubElectronApi(SCREEN_PATH);
+ });
+
+ it("leaves it empty: the user has not edited anything yet", async () => {
+ await importPendingRecording();
+
+ expect(past).toHaveLength(0);
+ expect(undo()).toBe(false);
+ });
+
+ it("still has its clip after the first Ctrl+Z", async () => {
+ await importPendingRecording();
+
+ // The `<video>` reports its duration and `NewEditorShell.handleLoadedMetadata`
+ // folds it in -- which is when the clip the user sees actually appears, since
+ // `replaceTimeline` sizes clips from `asset.durationSec` and the import has none.
+ // Automatic too, hence `history: false`.
+ const loaded = useProjectStore.getState().document as AxcutDocument;
+ const probed: AxcutDocument = {
+ ...loaded,
+ assets: loaded.assets.map((a) => ({ ...a, durationSec: 42 })),
+ };
+ await useProjectStore
+ .getState()
+ .saveDocument(replaceTimelineOp(probed, [{ startSec: 0, endSec: 42 }], "Auto-created"), {
+ history: false,
+ });
+ expect(useProjectStore.getState().document?.timeline.clips).toHaveLength(1);
+
+ undo();
+
+ expect(useProjectStore.getState().document?.timeline.clips).toHaveLength(1);
+ });
+});
diff --git a/src/components/ai-edition/recordingImport.ts b/src/components/ai-edition/recordingImport.ts
index 0b9b656b0..9a3474397 100644
--- a/src/components/ai-edition/recordingImport.ts
+++ b/src/components/ai-edition/recordingImport.ts
@@ -47,9 +47,16 @@ export async function importPendingRecording(): Promise<boolean> {
// overwrites this when handleLoadedMetadata fires with a finite value.
const doc = useProjectStore.getState().document;
if (doc && doc.timeline.clips.length === 0 && doc.assets.length > 0) {
+ // `history: false`. Nothing here is an edit: the user finished a recording and the
+ // editor built them a project around it, unattended, on mount. Recording it left a
+ // brand-new project sitting at `past.length === 1` before the user had touched
+ // anything, so their FIRST Ctrl+Z restored the state before the seed -- an empty
+ // timeline -- and the persist that follows an undo wrote that empty timeline to disk.
await useProjectStore
.getState()
- .replaceTimeline([{ startSec: 0, endSec: 60 }], "Auto-imported recording");
+ .replaceTimeline([{ startSec: 0, endSec: 60 }], "Auto-imported recording", {
+ history: false,
+ });
}
return true;
}
diff --git a/src/lib/ai-edition/store/agentDocumentApply.test.ts b/src/lib/ai-edition/store/agentDocumentApply.test.ts
index a7b3fe698..b5484e141 100644
--- a/src/lib/ai-edition/store/agentDocumentApply.test.ts
+++ b/src/lib/ai-edition/store/agentDocumentApply.test.ts
@@ -109,6 +109,43 @@ describe("applyAgentDocumentIfCurrent", () => {
expect(useProjectStore.getState().document?.project.title).toBe("User edit");
});
+ it("does not roll back over an undo that overtook its save", async () => {
+ // `saveDocument` resolves false for two different things now: the write failed,
+ // and the write was superseded by an undo while it was in flight. The rollback
+ // above is right for the first and catastrophic for the second -- it would put
+ // the agent's pre-edit document over the one the user just asked to return to,
+ // on the agent's behalf, seconds after they pressed Ctrl+Z.
+ const before = createEmptyDocument({ projectId: "project_1", title: "Before" });
+ useProjectStore.setState({ projectId: "project_1", document: before, revision: 4 });
+
+ // A user edit to have something to undo TO, then hold the agent's save open.
+ saveMock.mockImplementation(async (document: unknown) => ({ success: true, document }));
+ await useProjectStore
+ .getState()
+ .saveDocument(
+ { ...before, project: { ...before.project, title: "User edit" } },
+ { history: true },
+ );
+
+ let release: (() => void) | undefined;
+ saveMock.mockImplementationOnce(async (document: unknown) => {
+ await new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ return { success: true, document };
+ });
+ const agentResult = { ...before, project: { ...before.project, title: "Agent edit" } };
+ const applying = applyAgentDocumentIfCurrent(agentResult);
+
+ expect(undo()).toBe(true);
+ expect(useProjectStore.getState().document?.project.title).toBe("Before");
+
+ release?.();
+ await expect(applying).resolves.toBe("save-failed");
+
+ expect(useProjectStore.getState().document?.project.title).toBe("Before");
+ });
+
it("records exactly one undo step for an agent edit that lands", async () => {
// Two writes, one step: the optimistic `setDocument` opts out and the save
// names the pre-agent document as its base. Losing the step altogether would
diff --git a/src/lib/ai-edition/store/agentDocumentApply.ts b/src/lib/ai-edition/store/agentDocumentApply.ts
index 6b0715fd5..efd6cc632 100644
--- a/src/lib/ai-edition/store/agentDocumentApply.ts
+++ b/src/lib/ai-edition/store/agentDocumentApply.ts
@@ -54,7 +54,14 @@ export async function applyAgentDocumentIfCurrent(
// `saveDocument` that threw -- the two landed within minutes of each other, and a
// dead `catch` type-checks, so the rollback stopped firing and this returned
// "applied" for a write that never happened.
- if (previous) useProjectStore.setState({ document: previous, dirty: previousDirty });
+ //
+ // Guarded on the store still holding the agent's document, the same way the drag
+ // commits in `useTimeline` guard theirs. `false` also means "an undo overtook this
+ // write" now, and there the store holds the document the user asked to return to --
+ // restoring `previous` over it would revert their Ctrl+Z on the agent's behalf.
+ if (previous && useProjectStore.getState().document === parsed) {
+ useProjectStore.setState({ document: previous, dirty: previousDirty });
+ }
return "save-failed";
}
diff --git a/src/lib/ai-edition/store/documentWriteAudit.test.ts b/src/lib/ai-edition/store/documentWriteAudit.test.ts
new file mode 100644
index 000000000..16f8aff29
--- /dev/null
+++ b/src/lib/ai-edition/store/documentWriteAudit.test.ts
@@ -0,0 +1,361 @@
+// Every path that can reach the undo stack, pinned.
+//
+// #433 has now produced three rounds of the SAME defect: a write the user never
+// made recording itself as the thing their next Ctrl+Z reverses. Each round the
+// fix was aimed at the instance.
+//
+// 1. `setDocument` was the only writer that recorded, so nothing the user did
+// was on the stack at all.
+// 2. `probeAndCorrectClip` -- a background duration probe -- recorded, because
+// `history` defaulted to `true` and the probe said nothing. Making the option
+// REQUIRED was supposed to end it: omitting it is now a compile error.
+// 3. It did not. `projectStore.replaceTimeline(intervals, reason)` hardcoded
+// `{ history: true }` INSIDE itself, so the option never appeared in the
+// signature its callers see and no compile error could reach them. Its one
+// caller is the unattended recording import that runs on editor mount, so a
+// user landed in a brand-new project with `past.length === 1` and their first
+// Ctrl+Z emptied the timeline.
+//
+// The compiler can force a DIRECT call site to decide. It cannot see that the
+// function doing the deciding had no business deciding. That is a judgement about
+// who triggered the write, and the only place to record a judgement is next to the
+// code, in a table somebody has to edit.
+//
+// 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.
+
+import { readdirSync, readFileSync, statSync } from "node:fs";
+import { relative, resolve } from "node:path";
+import ts from "typescript";
+import { describe, expect, it } from "vitest";
+
+const ROOT = process.cwd();
+const SRC = resolve(ROOT, "src");
+
+/** What made this write happen. The judgement the compiler cannot make. */
+type Trigger =
+ /** The user did something. Records an undo step. */
+ | "gesture"
+ /** Nobody asked: a probe, a background job, an auto-import, a persist that
+ * follows an undo, or the optimistic half of an optimistic-then-save pair.
+ * Records nothing. */
+ | "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. */
+ | "forwarded";
+
+interface WritePath {
+ file: string;
+ /** Nearest named function around the call. */
+ fn: string;
+ writer: "saveDocument" | "setDocument";
+ trigger: Trigger;
+}
+
+// ---------------------------------------------------------------------------
+// The table. Sorted by file, then function, then writer — same order the scan
+// produces, so a failure reads as a plain diff.
+// ---------------------------------------------------------------------------
+
+const DECLARED: WritePath[] = [
+ // Dropping the legacy auto-caption annotations is a button in the captions pane.
+ w(
+ "src/components/ai-edition/CaptionsPane.tsx",
+ "clearLegacyCaptionAnnotations",
+ "save",
+ "gesture",
+ ),
+
+ // The persist that follows an undo. Recording it would undo the undo.
+ w("src/components/ai-edition/NewEditorShell.tsx", "NewEditorShell", "save", "automatic"),
+ // "Save" on the unsaved-changes prompt.
+ w("src/components/ai-edition/NewEditorShell.tsx", "handleConfirmUnsaved", "save", "gesture"),
+ // The probed duration folded into the document when the <video> loads. Twice:
+ // the first clip seed, and the backfill for clips still on a placeholder length.
+ w("src/components/ai-edition/NewEditorShell.tsx", "handleLoadedMetadata", "save", "automatic"),
+ w("src/components/ai-edition/NewEditorShell.tsx", "handleLoadedMetadata", "save", "automatic"),
+ // Renaming the project from the title field.
+ w("src/components/ai-edition/NewEditorShell.tsx", "handleRenameProject", "save", "gesture"),
+ // Ctrl+S / File > Save.
+ w("src/components/ai-edition/NewEditorShell.tsx", "handleSave", "save", "gesture"),
+ // "Save" chosen on the way out of Ctrl+N and Ctrl+O.
+ w("src/components/ai-edition/NewEditorShell.tsx", "onKey", "save", "gesture"),
+ w("src/components/ai-edition/NewEditorShell.tsx", "onKey", "save", "gesture"),
+ // Ctrl+V of a copied region: zoom, annotation, or a legacy span.
+ w("src/components/ai-edition/NewEditorShell.tsx", "pasteRegion", "save", "gesture"),
+ w("src/components/ai-edition/NewEditorShell.tsx", "pasteRegion", "save", "gesture"),
+ w("src/components/ai-edition/NewEditorShell.tsx", "pasteRegion", "save", "gesture"),
+ // The window is closing and the user answered "save".
+ w("src/components/ai-edition/NewEditorShell.tsx", "unsubSaveBeforeClose", "save", "gesture"),
+
+ // The agent's document. The optimistic write is not the edit — the save is, and
+ // it names the pre-agent document as what Ctrl+Z returns to.
+ w(
+ "src/lib/ai-edition/store/agentDocumentApply.ts",
+ "applyAgentDocumentIfCurrent",
+ "save",
+ "gesture",
+ ),
+ w(
+ "src/lib/ai-edition/store/agentDocumentApply.ts",
+ "applyAgentDocumentIfCurrent",
+ "set",
+ "automatic",
+ ),
+
+ // Linking the camera track found next to a newly added asset. Part of the
+ // import, not an edit of its own.
+ w("src/lib/ai-edition/store/projectStore.ts", "addAsset", "save", "automatic"),
+ // THE round-3 fix. This is the shape that defeated round 2: a store action that
+ // writes on someone else's behalf. It forwards now, so its callers decide.
+ w("src/lib/ai-edition/store/projectStore.ts", "replaceTimeline", "save", "forwarded"),
+
+ // A transcription verdict remembered on the asset, and a transcript arriving
+ // from a background whisper job. Neither is an edit.
+ w(
+ "src/lib/ai-edition/store/transcriptionStore.ts",
+ "persistPermanentFailure",
+ "save",
+ "automatic",
+ ),
+ w("src/lib/ai-edition/store/transcriptionStore.ts", "runJob", "save", "automatic"),
+
+ // Caption settings. Every pair is one optimistic `setDocument` (automatic) plus
+ // the save that is the actual edit and names the pre-edit document.
+ w("src/lib/ai-edition/store/useCaptions.ts", "commit", "save", "gesture"),
+ w("src/lib/ai-edition/store/useCaptions.ts", "deleteTranslation", "save", "gesture"),
+ w("src/lib/ai-edition/store/useCaptions.ts", "deleteTranslation", "set", "automatic"),
+ w("src/lib/ai-edition/store/useCaptions.ts", "saveTranslation", "save", "gesture"),
+ w("src/lib/ai-edition/store/useCaptions.ts", "saveTranslation", "set", "automatic"),
+ w("src/lib/ai-edition/store/useCaptions.ts", "set", "save", "gesture"),
+ w("src/lib/ai-edition/store/useCaptions.ts", "set", "set", "automatic"),
+ // A slider mid-drag: sixty of these a second, one undo step for the lot, opened
+ // by the commit above.
+ w("src/lib/ai-edition/store/useCaptions.ts", "setLive", "set", "automatic"),
+
+ // Editor settings — same live/commit split, same reasoning.
+ w("src/lib/ai-edition/store/useEditorSettings.ts", "commit", "save", "gesture"),
+ w("src/lib/ai-edition/store/useEditorSettings.ts", "set", "save", "gesture"),
+ w("src/lib/ai-edition/store/useEditorSettings.ts", "set", "set", "automatic"),
+ w("src/lib/ai-edition/store/useEditorSettings.ts", "setLive", "set", "automatic"),
+
+ // The serialised timeline-op queue. Another wrapper: it used to hardcode
+ // `{ history: true }`, which was right for both of today's callers and would have
+ // been wrong for the first background one.
+ w("src/lib/ai-edition/store/useSequentialTimelineOps.ts", "apply", "save", "forwarded"),
+
+ // Every timeline edit the user makes with the mouse or the keyboard.
+ w("src/lib/ai-edition/store/useTimeline.ts", "addAnnotation", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "addCameraFullscreen", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "addSpeed", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "addTrim", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "addZoom", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "addZoomsBulk", "save", "gesture"),
+ // The two drag commits. One undo step per gesture, recorded on release and only
+ // if the write lands — `historyBase` carries the pre-drag document.
+ w("src/lib/ai-edition/store/useTimeline.ts", "commitAnnotationChange", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "commitZoomFocus", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "duplicateClip", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "insertClipAt", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "moveClip", "save", "gesture"),
+ // The round-2 defect: a background duration probe every freshly imported asset
+ // fires, because `addAsset` never populates `durationSec`.
+ w("src/lib/ai-edition/store/useTimeline.ts", "probeAndCorrectClip", "save", "automatic"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "removeClip", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "removeRegion", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "removeRegions", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "setTrimEntries", "save", "gesture"),
+ // The live halves of the two drags.
+ w("src/lib/ai-edition/store/useTimeline.ts", "updateAnnotationLive", "set", "automatic"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "updateAnnotationSpan", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "updateCameraFullscreenSpan", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "updateClipCrop", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "updateClipSourceRange", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "updateSpeedSpan", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "updateSpeedValue", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "updateTrim", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "updateZoomDepth", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "updateZoomFocusLive", "set", "automatic"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "updateZoomFocusMode", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "updateZoomRotation", "save", "gesture"),
+ w("src/lib/ai-edition/store/useTimeline.ts", "updateZoomSpan", "save", "gesture"),
+ // Source-dimension backfill for assets a migration left unprobed. On load, for
+ // every project, whether or not the user touches anything.
+ w("src/lib/ai-edition/store/useTimeline.ts", "useTimeline", "save", "automatic"),
+];
+
+function w(file: string, fn: string, writer: "save" | "set", trigger: Trigger): WritePath {
+ return { file, fn, writer: writer === "save" ? "saveDocument" : "setDocument", trigger };
+}
+
+// ---------------------------------------------------------------------------
+// The scan
+// ---------------------------------------------------------------------------
+
+const WRITERS = new Set(["saveDocument", "setDocument"]);
+
+function sourceFiles(dir: string): string[] {
+ return readdirSync(dir).flatMap((entry) => {
+ const full = resolve(dir, entry);
+ if (statSync(full).isDirectory()) return sourceFiles(full);
+ if (!/\.tsx?$/.test(entry) || /\.(test|spec)\.tsx?$/.test(entry)) return [];
+ return [full];
+ });
+}
+
+function calleeName(call: ts.CallExpression): string | null {
+ if (ts.isIdentifier(call.expression)) return call.expression.text;
+ if (ts.isPropertyAccessExpression(call.expression)) return call.expression.name.text;
+ return null;
+}
+
+type FunctionLike =
+ | ts.FunctionDeclaration
+ | ts.FunctionExpression
+ | ts.ArrowFunction
+ | ts.MethodDeclaration;
+
+function isFunctionLike(node: ts.Node): node is FunctionLike {
+ return (
+ ts.isFunctionDeclaration(node) ||
+ ts.isFunctionExpression(node) ||
+ ts.isArrowFunction(node) ||
+ ts.isMethodDeclaration(node)
+ );
+}
+
+/** The name a reader would use for this function: its own, or the binding it is
+ * assigned to through however many `useCallback(...)` wrappers. */
+function nameOf(fn: FunctionLike): string | null {
+ if (
+ !ts.isArrowFunction(fn) &&
+ !ts.isFunctionExpression(fn) &&
+ fn.name &&
+ ts.isIdentifier(fn.name)
+ )
+ return fn.name.text;
+ let node: ts.Node | undefined = fn.parent;
+ while (node && (ts.isCallExpression(node) || ts.isParenthesizedExpression(node))) {
+ node = node.parent;
+ }
+ if (node && ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) return node.name.text;
+ if (node && ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) return node.name.text;
+ if (node && ts.isMethodDeclaration(node) && ts.isIdentifier(node.name)) return node.name.text;
+ 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[] = [];
+ let node: ts.Node | undefined = call.parent;
+ let name: string | null = null;
+ while (node) {
+ if (isFunctionLike(node)) {
+ functions.push(node);
+ name ??= nameOf(node);
+ }
+ node = node.parent;
+ }
+ return { name: name ?? "<module>", functions };
+}
+
+function triggerOf(call: ts.CallExpression, functions: FunctionLike[]): Trigger | string {
+ 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}\``;
+ }
+ if (!ts.isObjectLiteralExpression(opts)) return "options are not an object literal";
+ const history = opts.properties.find(
+ (p) => p.name && ts.isIdentifier(p.name) && p.name.text === "history",
+ );
+ if (!history || !ts.isPropertyAssignment(history)) return "no `history` property";
+ if (history.initializer.kind === ts.SyntaxKind.TrueKeyword) return "gesture";
+ if (history.initializer.kind === ts.SyntaxKind.FalseKeyword) return "automatic";
+ return "`history` is computed, so nobody decided";
+}
+
+interface Scan {
+ writes: WritePath[];
+ /** A Map, not an object: `calleeName` returns whatever the source says, and
+ * `"toString" in {}` is true. */
+ callsTo: Map<string, { file: string; fn: string }[]>;
+}
+
+function scan(): Scan {
+ const writes: WritePath[] = [];
+ const callsTo = new Map<string, { file: string; fn: string }[]>([
+ ["pushHistory", []],
+ ["recordHistory", []],
+ ]);
+ for (const path of sourceFiles(SRC)) {
+ const file = relative(ROOT, path).split("\\").join("/");
+ const source = ts.createSourceFile(
+ path,
+ readFileSync(path, "utf8"),
+ ts.ScriptTarget.Latest,
+ true,
+ path.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
+ );
+ const visit = (node: ts.Node) => {
+ if (ts.isCallExpression(node)) {
+ const callee = calleeName(node);
+ const { name, functions } = callee ? enclosingFunctions(node) : { name: "", functions: [] };
+ 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,
+ });
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ }
+ return { writes, callsTo };
+}
+
+function sortKey(path: WritePath): string {
+ return `${path.file}#${path.fn}#${path.writer}#${path.trigger}`;
+}
+
+const scanned = scan();
+
+describe("every write that can reach the undo stack", () => {
+ it("is declared in the table above, with the trigger it actually writes", () => {
+ // A failure here is not a broken test. It means a write path was added, moved
+ // or reclassified, and nobody has said whether the user asked for it. Read the
+ // diff, decide, and put the row in `DECLARED`.
+ expect(scanned.writes.map(sortKey).sort()).toEqual(DECLARED.map(sortKey).sort());
+ });
+
+ // The table is only the whole surface while these two hold. `recordHistory` is
+ // module-private to `projectStore`, and `pushHistory` is reachable from anywhere
+ // that imports `undoStack` — so the stack grows one more entry point the moment
+ // somebody calls it directly, and the table would stop being the audit.
+ it("goes through `recordHistory`, which only `saveDocument` and `setDocument` call", () => {
+ expect(scanned.callsTo.get("recordHistory")).toEqual([
+ { file: "src/lib/ai-edition/store/projectStore.ts", fn: "saveDocument" },
+ { file: "src/lib/ai-edition/store/projectStore.ts", fn: "setDocument" },
+ ]);
+ });
+
+ it("reaches `pushHistory` from `recordHistory` and nowhere else", () => {
+ expect(scanned.callsTo.get("pushHistory")).toEqual([
+ { file: "src/lib/ai-edition/store/projectStore.ts", fn: "recordHistory" },
+ ]);
+ });
+});
diff --git a/src/lib/ai-edition/store/projectStore.ts b/src/lib/ai-edition/store/projectStore.ts
index a5432e784..b29bbec49 100644
--- a/src/lib/ai-edition/store/projectStore.ts
+++ b/src/lib/ai-edition/store/projectStore.ts
@@ -3,14 +3,10 @@ import { create } from "zustand";
import { toFileUrl } from "@/components/video-editor/projectPersistence";
import { toastText } from "@/i18n/toastText";
import { nativeBridgeClient } from "@/native/client";
-import {
- type Interval,
- replaceTimeline as replaceTimelineOp,
- restoreFullTimeline as restoreFullTimelineOp,
-} from "../document/timeline";
+import { type Interval, replaceTimeline as replaceTimelineOp } from "../document/timeline";
import { type AxcutAsset, type AxcutDocument, documentSchema } from "../schema";
import { probeVideoDimensions } from "../timeline/duration";
-import { clearHistory, pushHistory } from "./undoStack";
+import { clearHistory, currentWriteEpoch, pushHistory } from "./undoStack";
// ponytail: thin Zustand wrapper over the native-bridge client. Keeps the
// current project + revision counter in renderer memory; mutations round-trip
@@ -78,9 +74,15 @@ export interface ProjectState {
addAsset: (path: string, label?: string) => Promise<AxcutAsset | null>;
removeAsset: (assetId: string) => Promise<void>;
/**
- * Write the document to disk. Resolves `true` when it landed, `false` when it did
- * not -- and a `false` has ALREADY been reported to the user and logged, so a
- * caller that ignores it is choosing not to react, not choosing to stay silent.
+ * Write the document to disk. Resolves `true` when it took effect, `false` when it
+ * did not.
+ *
+ * `false` means one of two things, and neither needs the caller to say anything:
+ * the write FAILED, which has already been reported to the user and logged; or an
+ * undo / redo / project switch happened while it was in flight, which the user did
+ * on purpose and can see on screen. Either way the store does not hold what was
+ * asked for, so a caller that reacts to `false` by undoing its own optimistic write
+ * must check the store still holds that write first -- see `agentDocumentApply`.
*
* It never rejects, by design. Every save in the app funnels through here and
* almost all of them are `void`-ed from a click handler, so a rejection here was
@@ -89,8 +91,22 @@ export interface ProjectState {
*/
saveDocument: (document: AxcutDocument, opts: DocumentWriteOptions) => Promise<boolean>;
setDocument: (document: AxcutDocument, opts: DocumentWriteOptions) => void;
- replaceTimeline: (intervals: Interval[], reason: string) => Promise<void>;
- restoreFullTimeline: () => Promise<void>;
+ /**
+ * Rebuild the timeline from `intervals` and save it.
+ *
+ * `opts` is NOT optional and NOT defaulted, for the same reason `history` itself is
+ * not: this used to hardcode `{ history: true }`, and because the option was invisible
+ * in this signature, no compile error could reach the one caller. That caller is the
+ * unattended recording import, which runs on editor mount -- so the user arrived in a
+ * brand-new project with `past.length === 1`, and their first Ctrl+Z emptied the
+ * timeline. A wrapper that writes has to let its caller decide, or it decides wrong on
+ * that caller's behalf.
+ */
+ replaceTimeline: (
+ intervals: Interval[],
+ reason: string,
+ opts: DocumentWriteOptions,
+ ) => Promise<void>;
setSourceDuration: (sec: number) => void;
setCurrentTime: (sec: number) => void;
setPlaying: (playing: boolean) => void;
@@ -315,11 +331,26 @@ export const useProjectStore = create<ProjectState>((set, get) => ({
// of live/optimistic paths. Recording only in `setDocument` left `past` empty
// for everything the user does, so Ctrl+Z was a no-op (#433).
const base = historyBaseFor(opts, get().document);
+ // Read alongside it, and for the same reason: both describe the world this write
+ // is building on, and the await is where that world can change underneath it.
+ const epoch = currentWriteEpoch();
try {
const result = await nativeBridgeClient.aiEdition.save(document);
if (!result.success || !result.document) {
throw new Error(result.error ?? "Failed to save project");
}
+ // The undo wins, and this write is dropped -- store and history both. It was
+ // in flight when the user pressed Ctrl+Z (or switched projects), so its document
+ // is the one they just asked to leave: installing it reverted the undo on screen,
+ // and recording it put a FORWARD state on `past` and cleared `future`, so the
+ // redo they had just earned was gone.
+ //
+ // Dropped rather than reverted, because reverting is not this write's to do: the
+ // bytes are already on disk, and it is the undo's own persist -- issued from
+ // `useUndoRedoShortcuts`'s `onAfter` the moment it ran, so ordered after this one
+ // on the same IPC channel -- that puts the restored document back over them.
+ // `dirty` is deliberately left set for exactly that reason.
+ if (currentWriteEpoch() !== epoch) return false;
const parsed = parseDocument(result.document);
set({
document: parsed,
@@ -362,18 +393,11 @@ export const useProjectStore = create<ProjectState>((set, get) => ({
});
},
- async replaceTimeline(intervals, reason) {
+ async replaceTimeline(intervals, reason, opts) {
const doc = get().document;
if (!doc) throw new Error("No project loaded");
const next = replaceTimelineOp(doc, intervals, reason);
- await get().saveDocument(next, { history: true });
- },
-
- async restoreFullTimeline() {
- const doc = get().document;
- if (!doc) throw new Error("No project loaded");
- const next = restoreFullTimelineOp(doc);
- await get().saveDocument(next, { history: true });
+ await get().saveDocument(next, opts);
},
setSourceDuration(sec) {
diff --git a/src/lib/ai-edition/store/undo.test.ts b/src/lib/ai-edition/store/undo.test.ts
index b85d805b6..9e07ceb30 100644
--- a/src/lib/ai-edition/store/undo.test.ts
+++ b/src/lib/ai-edition/store/undo.test.ts
@@ -211,6 +211,84 @@ describe("undo/redo", () => {
});
});
+ describe("a save that was already in flight when Ctrl+Z was pressed", () => {
+ // `saveDocument` records BELOW its await, which is what makes a failed write
+ // record nothing -- and what let a save that started before the undo land on top
+ // of it. Its result installed the document the user had just asked to leave, and
+ // its record pushed a state FORWARD of the one they returned to while clearing
+ // `future`: the undo was visually reverted and the redo was gone.
+ //
+ // The undo wins. The write is dropped -- store and history both -- and the undo's
+ // own persist, issued right behind it, is what puts the restored document back
+ // over the bytes already on disk.
+
+ /** A save the test holds open, so an undo can happen underneath it. */
+ function heldSave() {
+ let release: (() => void) | undefined;
+ saveMock.mockImplementationOnce(async (document: unknown) => {
+ await new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ return { success: true, document };
+ });
+ return () => release?.();
+ }
+
+ it("does not put its document back on screen", async () => {
+ const release = heldSave();
+ const inFlight = useProjectStore.getState().saveDocument(titled("In flight"), {
+ history: true,
+ });
+
+ expect(undo()).toBe(false); // nothing recorded yet -- the save has not landed
+ await useProjectStore.getState().saveDocument(titled("Landed"), { history: true });
+ expect(undo()).toBe(true);
+ expect(currentTitle()).toBe("Original");
+
+ release();
+ expect(await inFlight).toBe(false);
+
+ expect(currentTitle()).toBe("Original");
+ });
+
+ it("does not record a step forward of the one the user returned to", async () => {
+ await useProjectStore.getState().saveDocument(titled("Second"), { history: true });
+
+ const release = heldSave();
+ const inFlight = useProjectStore.getState().saveDocument(titled("Third"), { history: true });
+ expect(undo()).toBe(true);
+ expect(currentTitle()).toBe("Original");
+ expect(past).toHaveLength(0);
+ expect(future).toHaveLength(1);
+
+ release();
+ await inFlight;
+
+ // `past` held "Second" here, which is FORWARD of "Original" -- Ctrl+Z would have
+ // walked the user the wrong way -- and `pushHistory` had wiped the redo.
+ expect(past).toHaveLength(0);
+ expect(future).toHaveLength(1);
+ expect(redo()).toBe(true);
+ expect(currentTitle()).toBe("Second");
+ });
+
+ it("leaves the document dirty, so the restore still reaches disk", async () => {
+ const release = heldSave();
+ const inFlight = useProjectStore.getState().saveDocument(titled("In flight"), {
+ history: true,
+ });
+ await useProjectStore.getState().saveDocument(titled("Landed"), { history: true });
+ expect(undo()).toBe(true);
+
+ release();
+ await inFlight;
+
+ // A dropped write must not claim the document is on disk: it is the undo's
+ // document that is in memory, and only `onAfter` puts that one on disk.
+ expect(useProjectStore.getState().dirty).toBe(true);
+ });
+ });
+
it("records the pre-drag document a commit names, not the one on screen", async () => {
// `historyBase`. A live drag writes every pointermove into the store with
// `history: false`, so by commit time the store's own "previous" document is the
@@ -261,6 +339,42 @@ describe("the Edit menu's undo/redo route", () => {
expect(currentTitle()).toBe("Renamed");
});
+ it("keeps its hands off the document while a modal is open", () => {
+ // #434's bug, on the route this branch added. A modal's controls are buttons, so
+ // the text-field check waves them straight through -- and on macOS this menu route
+ // is the ONLY path Cmd+Z has, with no keydown handler upstream to stop it, so
+ // undo rewrote the document under an open Export / Edit clip / unsaved-changes
+ // dialog. The `beforeEach` above empties `document.body`, which is exactly why the
+ // 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") });
+
+ const modal = window.document.createElement("div");
+ modal.setAttribute("aria-modal", "true");
+ window.document.body.appendChild(modal);
+
+ act(() => {
+ result.current.runUndo();
+ });
+ expect(currentTitle()).toBe("Original");
+ expect(past).toHaveLength(1);
+
+ act(() => {
+ result.current.runRedo();
+ });
+ expect(currentTitle()).toBe("Original");
+ expect(future).toHaveLength(0);
+ expect(persist).not.toHaveBeenCalled();
+
+ // And it comes back the moment the modal closes.
+ modal.remove();
+ act(() => {
+ result.current.runUndo();
+ });
+ expect(currentTitle()).toBe("Older");
+ });
+
it("leaves a focused text field to the browser's own text undo", () => {
// Same rule the keydown path applies, and the one thing the `undo` role was
// still good for.
diff --git a/src/lib/ai-edition/store/undo.ts b/src/lib/ai-edition/store/undo.ts
index 3c1800f9f..3b9b28bff 100644
--- a/src/lib/ai-edition/store/undo.ts
+++ b/src/lib/ai-edition/store/undo.ts
@@ -15,14 +15,19 @@ import { useCallback, useEffect, useRef } from "react";
import { isModalOpen } from "../modalGuard";
import type { AxcutDocument } from "../schema";
import { useProjectStore } from "./projectStore";
-import { clearHistory, future, past } from "./undoStack";
+import { clearHistory, future, past, supersedeInFlightWrites } from "./undoStack";
-export { clearHistory, pushHistory } from "./undoStack";
+export { clearHistory } from "./undoStack";
/** Put a snapshot back on screen without recording it as a new edit. `dirty` is
* set because the document on disk is no longer the one in memory — the caller
* of `useUndoRedoShortcuts` persists it. */
function restore(doc: unknown) {
+ // Before the state write, so a save that resolves between here and the caller's
+ // persist cannot slip its result in. See `undoStack.ts`: a save already in flight
+ // when Ctrl+Z was pressed used to install its document over the restored one and
+ // push a FORWARD state onto `past`, wiping the redo the undo had just created.
+ supersedeInFlightWrites();
useProjectStore.setState((state) => ({
document: doc as AxcutDocument,
revision: state.revision + 1,
@@ -124,6 +129,13 @@ export function useUndoRedoShortcuts(onAfter: () => void): UndoRedoHandlers {
window.document.execCommand?.("undo");
return;
}
+ // AFTER the text-field check, so a rename dialog's input still gets the browser's
+ // own text undo. Before it, this route rewrote the DOCUMENT under an open modal:
+ // a modal's controls are buttons, so `isTextEditingTarget` waves them through, and
+ // on macOS the menu is the only path Cmd+Z has -- there is no keydown handler
+ // upstream of this one to stop it. See `../modalGuard`, and #434, which fixes the
+ // same hole on the keydown path.
+ if (isModalOpen()) return;
if (undo()) onAfterRef.current();
}, []);
@@ -132,6 +144,7 @@ export function useUndoRedoShortcuts(onAfter: () => void): UndoRedoHandlers {
window.document.execCommand?.("redo");
return;
}
+ if (isModalOpen()) return;
if (redo()) onAfterRef.current();
}, []);
diff --git a/src/lib/ai-edition/store/undoStack.ts b/src/lib/ai-edition/store/undoStack.ts
index 8cf1c3b56..6f28bc197 100644
--- a/src/lib/ai-edition/store/undoStack.ts
+++ b/src/lib/ai-edition/store/undoStack.ts
@@ -31,4 +31,34 @@ export function pushHistory(snapshot: Snapshot) {
export function clearHistory() {
past.length = 0;
future.length = 0;
+ supersedeInFlightWrites();
+}
+
+// The write epoch. `saveDocument` reads it before its `await` and again after,
+// and throws its result away if it moved.
+//
+// Without it, a save that was ALREADY IN FLIGHT when the user pressed Ctrl+Z
+// landed on top of the undo: `saveDocument` records below the await, so it put
+// the pre-save document on `past` (which is FORWARD of where the user asked to
+// go) and cleared `future` on the way past, then installed its own document in
+// the store. The undo was visually reverted and redo was gone -- for a write the
+// user had superseded a moment earlier.
+//
+// Everything that replaces the document out from under an in-flight write bumps
+// it: `undo`, `redo` (both via `restore`), and `clearHistory`, which is a project
+// switch -- a save of the OLD project resolving after `loadProject` would
+// otherwise overwrite the new one.
+let writeEpoch = 0;
+
+/** The epoch a write should still belong to when it lands. */
+export function currentWriteEpoch(): number {
+ return writeEpoch;
+}
+
+/**
+ * Declare that the document on screen is no longer the one any in-flight write
+ * was building on, so those writes must not install their result.
+ */
+export function supersedeInFlightWrites() {
+ writeEpoch += 1;
}
diff --git a/src/lib/ai-edition/store/useSequentialTimelineOps.test.ts b/src/lib/ai-edition/store/useSequentialTimelineOps.test.ts
index a72b146bd..404f78350 100644
--- a/src/lib/ai-edition/store/useSequentialTimelineOps.test.ts
+++ b/src/lib/ai-edition/store/useSequentialTimelineOps.test.ts
@@ -99,8 +99,8 @@ describe("useSequentialTimelineOps", () => {
};
await act(async () => {
- const r1 = result.current.apply(op1);
- const r2 = result.current.apply(op2);
+ const r1 = result.current.apply(op1, { history: true });
+ const r2 = result.current.apply(op2, { history: true });
await Promise.all([r1, r2]);
});
@@ -152,8 +152,8 @@ describe("useSequentialTimelineOps", () => {
let firstResult: AxcutDocument | null | undefined;
let secondResult: AxcutDocument | null | undefined;
await act(async () => {
- const p1 = result.current.apply(op1);
- const p2 = result.current.apply(op2);
+ const p1 = result.current.apply(op1, { history: true });
+ const p2 = result.current.apply(op2, { history: true });
firstResult = await p1;
secondResult = await p2;
});
@@ -182,13 +182,16 @@ describe("useSequentialTimelineOps", () => {
// it runs. On its own queue this would still be the pre-op count.
let trimsSeenByTask = -1;
await act(async () => {
- const opPromise = result.current.apply({
- type: "add_trim_range" as const,
- assetId: "asset_1",
- startSec: 1,
- endSec: 2,
- reason: "ahead of the insertion",
- });
+ const opPromise = result.current.apply(
+ {
+ type: "add_trim_range" as const,
+ assetId: "asset_1",
+ startSec: 1,
+ endSec: 2,
+ reason: "ahead of the insertion",
+ },
+ { history: true },
+ );
const taskPromise = result.current.enqueue(() => {
trimsSeenByTask = useProjectStore.getState().document?.timeline.trimRanges.length ?? -1;
});
@@ -248,7 +251,7 @@ describe("useSequentialTimelineOps", () => {
let resolved: AxcutDocument | null | undefined;
await act(async () => {
- resolved = await result.current.apply(op);
+ resolved = await result.current.apply(op, { history: true });
});
expect(resolved).toBeNull();
@@ -279,7 +282,7 @@ describe("useSequentialTimelineOps", () => {
let returned: AxcutDocument | null | undefined;
await act(async () => {
- returned = await result.current.apply(op);
+ returned = await result.current.apply(op, { history: true });
});
expect(returned).toBeDefined();
@@ -287,4 +290,35 @@ describe("useSequentialTimelineOps", () => {
expect(returned?.timeline.trimRanges[0]?.startSec).toBe(1);
expect(returned?.timeline.trimRanges[0]?.endSec).toBe(2);
});
+
+ it("hands the caller's write options through instead of picking them", async () => {
+ // This used to hardcode `{ history: true }`, which was right for both of today's
+ // callers and invisible to any future one. That is the exact shape of the #433
+ // regression `projectStore.replaceTimeline` shipped with: a wrapper whose
+ // signature hides the option decides it, so no compile error can reach the call
+ // site that got it wrong. `documentWriteAudit.test.ts` pins the shape; this pins
+ // the behaviour.
+ const seed = makeDocWithAsset();
+ useProjectStore.setState({ document: seed });
+ const saveDocument = vi.fn(async () => true);
+
+ const { result } = renderHook(() =>
+ useSequentialTimelineOps({ fallbackDocument: seed, saveDocument }),
+ );
+
+ await act(async () => {
+ await result.current.apply(
+ {
+ type: "add_trim_range" as const,
+ assetId: "asset_1",
+ startSec: 1,
+ endSec: 2,
+ reason: "a background job, not the user",
+ },
+ { history: false },
+ );
+ });
+
+ expect(saveDocument).toHaveBeenCalledWith(expect.anything(), { history: false });
+ });
});
diff --git a/src/lib/ai-edition/store/useSequentialTimelineOps.ts b/src/lib/ai-edition/store/useSequentialTimelineOps.ts
index 45742754e..538f1cd32 100644
--- a/src/lib/ai-edition/store/useSequentialTimelineOps.ts
+++ b/src/lib/ai-edition/store/useSequentialTimelineOps.ts
@@ -41,11 +41,17 @@ export interface SequentialTimelineOps {
*
* Returns the saved document, or `null` for either of two different things:
* no project document is loaded (store empty AND no fallback supplied), which
- * is a silent no-op, or the save failed, which the user has already been told
- * about. Both call sites `void` the result, so they are not distinguished; a
- * caller that needs to tell them apart has to widen this return type first.
+ * is a silent no-op, or the write did not take effect -- see `saveDocument` for
+ * the two ways that happens, neither of which needs anything said here. Both call
+ * sites `void` the result, so they are not distinguished; a caller that needs to
+ * tell them apart has to widen this return type first.
+ *
+ * `opts` is forwarded verbatim to `saveDocument`, and is required for the same
+ * reason `history` itself is: a wrapper that picks the value on its caller's
+ * behalf hides the decision from the compiler. Both of today's callers are user
+ * gestures and pass `{ history: true }`; the next one might not be.
*/
- apply: (op: AxcutTimelineOperation) => Promise<AxcutDocument | null>;
+ apply: (op: AxcutTimelineOperation, opts: DocumentWriteOptions) => Promise<AxcutDocument | null>;
/**
* Queue a document mutation that isn't an `AxcutTimelineOperation` on
@@ -88,7 +94,7 @@ export function useSequentialTimelineOps(options: {
}, []);
const apply = useCallback(
- (op: AxcutTimelineOperation): Promise<AxcutDocument | null> =>
+ (op: AxcutTimelineOperation, opts: DocumentWriteOptions): Promise<AxcutDocument | null> =>
enqueue(async () => {
const { applyTimelineOperation } = await import("@/lib/ai-edition/document/operations");
// Read the doc inside the chain. The store holds the
@@ -98,7 +104,7 @@ export function useSequentialTimelineOps(options: {
const doc = useProjectStore.getState().document ?? fallbackDocument;
if (!doc) return null;
const applied = applyTimelineOperation(doc, op);
- return (await saveDocument(applied.document, { history: true })) ? applied.document : null;
+ return (await saveDocument(applied.document, opts)) ? applied.document : null;
}),
[enqueue, fallbackDocument, saveDocument],
);