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 undo/redo actually apply

EtienneLescot874dc209d70c
diff --git a/electron/main.ts b/electron/main.ts
index 9992a27c7..b02d50246 100644
--- a/electron/main.ts
+++ b/electron/main.ts
@@ -275,8 +275,22 @@ function setupApplicationMenu() {
{
label: mainT("common", "actions.edit") || "Edit",
submenu: [
- { role: "undo", label: mainT("common", "actions.undo") || "Undo" },
- { role: "redo", label: mainT("common", "actions.redo") || "Redo" },
+ // `registerAccelerator: false` on both: the roles run `webContents.undo()`,
+ // the WEB EDITING undo, which does nothing outside a focused text field —
+ // and registering their accelerators lets the native menu eat Ctrl+Z /
+ // Ctrl+Shift+Z before the renderer's document-level handler
+ // (`useUndoRedoShortcuts`) ever sees the keydown. The items stay, greyed
+ // shortcut text and all, so text fields keep their menu entries.
+ {
+ role: "undo",
+ label: mainT("common", "actions.undo") || "Undo",
+ registerAccelerator: false,
+ },
+ {
+ role: "redo",
+ label: mainT("common", "actions.redo") || "Redo",
+ registerAccelerator: false,
+ },
{ type: "separator" },
{ role: "cut", label: mainT("common", "actions.cut") || "Cut" },
{ role: "copy", label: mainT("common", "actions.copy") || "Copy" },
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index 4026266cb..1d650d5cf 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -160,8 +160,14 @@ export function NewEditorShell() {
[transcriptions],
);
const tl = useTimeline();
+ // An undo only puts the restored document back in the store and marks it dirty,
+ // so without this the reverted state never reached disk: close the window and the
+ // edit the user just undid came back. `history: false` is load-bearing — a
+ // recording save here would push the restored document straight back onto the
+ // stack and clear the redo the undo had just created.
useUndoRedoShortcuts(() => {
- // ponytail: placeholder, wire when undo stack merges with history
+ const doc = useProjectStore.getState().document;
+ if (doc) void useProjectStore.getState().saveDocument(doc, { history: false });
});
const [copiedClipId, setCopiedClipId] = useState<string | null>(null);
const [projectSummaries, setProjectSummaries] = useState<AiEditionProjectSummary[]>([]);
@@ -368,7 +374,10 @@ export function NewEditorShell() {
[{ startSec: 0, endSec: known }],
"Auto-created full-duration clip",
);
- void state.saveDocument(next);
+ // `history: false` for both writes in this callback: they are the probed
+ // duration being folded into the document on load, not something the user
+ // did — an undo landing on one of them would empty their timeline.
+ void state.saveDocument(next, { history: false });
return;
}
// Hand the probed duration to the pure document layer: it patches only the
@@ -379,7 +388,7 @@ export function NewEditorShell() {
// nothing is waiting, so there is nothing to guard here.
const next = applyProbedDuration(doc, assetId, known);
if (next !== doc) {
- void state.saveDocument(next);
+ void state.saveDocument(next, { history: false });
}
},
[setSourceDuration],
diff --git a/src/lib/ai-edition/store/agentDocumentApply.ts b/src/lib/ai-edition/store/agentDocumentApply.ts
index 781abbc6a..52b2c1b1a 100644
--- a/src/lib/ai-edition/store/agentDocumentApply.ts
+++ b/src/lib/ai-edition/store/agentDocumentApply.ts
@@ -24,10 +24,10 @@ export async function applyAgentDocumentIfCurrent(
const parsed = ensureDocument(document);
const previous = store.document;
const previousDirty = store.dirty;
- // Both calls, not just the save. `setDocument` is the only thing that pushes the
- // outgoing document onto the undo stack, so deleting it as "redundant next to
- // saveDocument, which sets `document` too" silently breaks Ctrl+Z after an agent edit.
- // `saveDocument` is what reaches the disk.
+ // Both calls, not just the save. `setDocument` puts the agent's document on screen
+ // NOW, without waiting on the disk round-trip `saveDocument` awaits. Both record the
+ // outgoing document on the undo stack, and recording it twice is not a risk: the
+ // second sees the document the first already installed and skips.
store.setDocument(parsed);
if (await store.saveDocument(parsed)) return "applied";
diff --git a/src/lib/ai-edition/store/projectStore.ts b/src/lib/ai-edition/store/projectStore.ts
index 4b48ccd27..85245f595 100644
--- a/src/lib/ai-edition/store/projectStore.ts
+++ b/src/lib/ai-edition/store/projectStore.ts
@@ -10,6 +10,7 @@ import {
} from "../document/timeline";
import { type AxcutAsset, type AxcutDocument, documentSchema } from "../schema";
import { probeVideoDimensions } from "../timeline/duration";
+import { clearHistory, pushHistory } from "./undoStack";
// ponytail: thin Zustand wrapper over the native-bridge client. Keeps the
// current project + revision counter in renderer memory; mutations round-trip
@@ -17,6 +18,19 @@ import { probeVideoDimensions } from "../timeline/duration";
export type ProjectStatus = "idle" | "loading" | "ready" | "error";
+export interface DocumentWriteOptions {
+ /**
+ * Record the outgoing document on the undo stack. Defaults to `true`: a write
+ * is a user edit unless the caller says otherwise.
+ *
+ * Pass `false` for writes the user never asked for -- probe backfills,
+ * transcripts arriving from a background job, the restore an undo itself
+ * persists. Those must not become Ctrl+Z steps, and a persist that re-recorded
+ * the document it just restored would undo the undo.
+ */
+ history?: boolean;
+}
+
export interface ProjectState {
projectId: string | null;
document: AxcutDocument | null;
@@ -50,8 +64,8 @@ export interface ProjectState {
* an unhandled rejection in the renderer with no toast, no log and no clue --
* change a caption font on a read-only project and the edit was simply gone.
*/
- saveDocument: (document: AxcutDocument) => Promise<boolean>;
- setDocument: (document: AxcutDocument) => void;
+ saveDocument: (document: AxcutDocument, opts?: DocumentWriteOptions) => Promise<boolean>;
+ setDocument: (document: AxcutDocument, opts?: DocumentWriteOptions) => void;
replaceTimeline: (intervals: Interval[], reason: string) => Promise<void>;
restoreFullTimeline: () => Promise<void>;
setSourceDuration: (sec: number) => void;
@@ -65,6 +79,25 @@ function parseDocument(value: unknown): AxcutDocument {
return documentSchema.parse(value);
}
+/**
+ * Record `prev` as the state Ctrl+Z returns to, unless the caller opted out or
+ * this write is not a change (`commit`-style re-saves hand back the very object
+ * the store already holds, and a live drag's `setLive` then `commit` pair would
+ * otherwise take two undos to reverse one gesture).
+ *
+ * Synchronous on purpose -- see the header of `undoStack.ts` for what the
+ * deferred `import("./undo")` this replaced did to redo.
+ */
+function recordHistory(
+ prev: AxcutDocument | null,
+ next: AxcutDocument,
+ opts?: DocumentWriteOptions,
+) {
+ if (opts?.history === false) return;
+ if (!prev || prev === next) return;
+ pushHistory({ projectId: prev.project.id, doc: structuredClone(prev) });
+}
+
export const useProjectStore = create<ProjectState>((set, get) => ({
projectId: null,
document: null,
@@ -94,7 +127,7 @@ export const useProjectStore = create<ProjectState>((set, get) => ({
dirty: false,
lastSavedAt: new Date(),
});
- void import("./undo").then(({ clearHistory }) => clearHistory());
+ clearHistory();
} catch (error) {
set({
status: "error",
@@ -120,7 +153,7 @@ export const useProjectStore = create<ProjectState>((set, get) => ({
dirty: false,
lastSavedAt: new Date(),
});
- void import("./undo").then(({ clearHistory }) => clearHistory());
+ clearHistory();
return document;
} catch (error) {
set({
@@ -198,7 +231,10 @@ export const useProjectStore = create<ProjectState>((set, get) => ({
// Only adopt the linked document if it actually reached disk -- otherwise
// the caller is handed a document claiming a camera link the file does not
// have. The store has already told the user the write failed.
- if (await get().saveDocument(next)) document = parseDocument(next);
+ // `history: false`: linking a camera is part of adding the asset, not an
+ // edit of its own -- and `get().document` here is still the pre-add document,
+ // so recording it would make Ctrl+Z jump back past the import.
+ if (await get().saveDocument(next, { history: false })) document = parseDocument(next);
}
// success:false just means no camera was found for this asset —
// the normal case for a plain imported video. Nothing to surface.
@@ -239,7 +275,14 @@ export const useProjectStore = create<ProjectState>((set, get) => ({
});
},
- async saveDocument(document) {
+ async saveDocument(document, opts) {
+ // Snapshot BEFORE the await, while `get().document` is still the pre-edit one.
+ // This is where undo history actually comes from: the editor writes through
+ // `saveDocument` for every user edit -- add a region, delete one, rename the
+ // project, every timeline op -- and `setDocument` is reserved for the handful
+ // of live/optimistic paths. Recording only in `setDocument` left `past` empty
+ // for everything the user does, so Ctrl+Z was a no-op (#433).
+ recordHistory(get().document, document, opts);
try {
const result = await nativeBridgeClient.aiEdition.save(document);
if (!result.success || !result.document) {
@@ -268,15 +311,8 @@ export const useProjectStore = create<ProjectState>((set, get) => ({
}
},
- setDocument(document) {
- const prev = get().document;
- if (prev && prev !== document) {
- // ponytail: push snapshot to undo history. Defer import to avoid
- // pulling the undo module into the store at module-load time.
- void import("./undo").then(({ pushHistory }) => {
- pushHistory({ projectId: prev.project.id, doc: structuredClone(prev) });
- });
- }
+ setDocument(document, opts) {
+ recordHistory(get().document, document, opts);
set({
document,
revision: get().revision + 1,
diff --git a/src/lib/ai-edition/store/transcriptionStore.ts b/src/lib/ai-edition/store/transcriptionStore.ts
index d851bd4a8..64d910b13 100644
--- a/src/lib/ai-edition/store/transcriptionStore.ts
+++ b/src/lib/ai-edition/store/transcriptionStore.ts
@@ -318,21 +318,25 @@ async function persistPermanentFailure(
// Best-effort bookkeeping: `saveDocument` reports its own failures and resolves
// false rather than throwing, and a note on the asset is not worth a second
// message on top of the one the user already got.
- const persisted = await project.saveDocument({
- ...doc,
- assets: doc.assets.map((a) =>
- a.id === assetId
- ? {
- ...a,
- transcriptionFailure: {
- kind,
- message: failure.message,
- at: new Date().toISOString(),
- },
- }
- : a,
- ),
- });
+ const persisted = await project.saveDocument(
+ {
+ ...doc,
+ assets: doc.assets.map((a) =>
+ a.id === assetId
+ ? {
+ ...a,
+ transcriptionFailure: {
+ kind,
+ message: failure.message,
+ at: new Date().toISOString(),
+ },
+ }
+ : a,
+ ),
+ },
+ // Bookkeeping, not an edit — it must not become an undo step.
+ { history: false },
+ );
if (!persisted) {
console.warn("[transcription] could not persist the failure on the asset");
}
@@ -397,6 +401,9 @@ async function runJob(assetId: string, job: TranscriptionJob): Promise<void> {
}
// One save: the transcript, and (on a successful retry) the removal of
// the verdict remembered on the asset.
+ // `history: false`: a transcript landing from a background job is not an edit
+ // the user made, and making it the target of the next Ctrl+Z would both surprise
+ // them and throw the transcript away.
await useProjectStore.getState().saveDocument(
withTranscript(
{
@@ -407,6 +414,7 @@ async function runJob(assetId: string, job: TranscriptionJob): Promise<void> {
},
transcript,
),
+ { history: false },
);
dropJob(assetId, runId);
if (job.manual) toast.success(toastText("mediaStage.transcriptReady"));
diff --git a/src/lib/ai-edition/store/undo.test.ts b/src/lib/ai-edition/store/undo.test.ts
new file mode 100644
index 000000000..4666a2b56
--- /dev/null
+++ b/src/lib/ai-edition/store/undo.test.ts
@@ -0,0 +1,160 @@
+// @vitest-environment jsdom
+//
+// Regression cover for #433: undo/redo silently did nothing. `undo.ts` had no
+// test at all, which is exactly why CI stayed green while Ctrl+Z was dead —
+// the history stack was only ever written by `setDocument`, and every edit the
+// editor actually makes (add a region, delete one, rename the project) goes
+// through `saveDocument`.
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { createEmptyDocument } from "../schema";
+import { useProjectStore } from "./projectStore";
+import { clearHistory, redo, undo } from "./undo";
+import { future, past } from "./undoStack";
+
+const saveMock = vi.hoisted(() => vi.fn());
+
+vi.mock("@/native/client", () => ({
+ nativeBridgeClient: {
+ aiEdition: { save: saveMock },
+ },
+}));
+
+const PROJECT_ID = "project_1";
+
+function titled(title: string) {
+ return createEmptyDocument({ projectId: PROJECT_ID, title });
+}
+
+function currentTitle(): string | undefined {
+ return useProjectStore.getState().document?.project.title;
+}
+
+describe("undo/redo", () => {
+ beforeEach(() => {
+ useProjectStore.getState().clear();
+ clearHistory();
+ saveMock.mockReset();
+ // The bridge hands the document back; `saveDocument` re-parses what it returns,
+ // so the store ends up holding a structurally equal but distinct object — same
+ // as in the app.
+ saveMock.mockImplementation(async (document: unknown) => ({ success: true, document }));
+ useProjectStore.setState({ projectId: PROJECT_ID, document: titled("Original") });
+ });
+
+ it("records a saveDocument edit and reverts it", async () => {
+ // The path every region add / delete / rename takes. It recorded nothing
+ // before this fix, so `past` stayed empty and `undo()` returned false.
+ await useProjectStore.getState().saveDocument(titled("Renamed"));
+ expect(currentTitle()).toBe("Renamed");
+ expect(past).toHaveLength(1);
+
+ expect(undo()).toBe(true);
+ expect(currentTitle()).toBe("Original");
+ });
+
+ it("reapplies the edit on redo", async () => {
+ const renamed = titled("Renamed");
+ await useProjectStore.getState().saveDocument(renamed);
+
+ expect(undo()).toBe(true);
+ expect(currentTitle()).toBe("Original");
+ expect(redo()).toBe(true);
+ expect(currentTitle()).toBe("Renamed");
+ });
+
+ it("does not record the undo's own write as a new edit", async () => {
+ // The bug that made redo unreachable: the restore used to go back through
+ // `setDocument`, whose deferred `import("./undo")` pushed in a later microtask —
+ // after the re-entrancy guard had already been re-armed. The pre-undo document
+ // landed on `past` and `pushHistory` cleared `future`, so one Ctrl+Z turned the
+ // history into an A/B toggle with redo permanently gone.
+ await useProjectStore.getState().saveDocument(titled("Renamed"));
+ expect(past).toHaveLength(1);
+
+ expect(undo()).toBe(true);
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(past).toHaveLength(0);
+ expect(future).toHaveLength(1);
+ });
+
+ it("walks back more than one level", async () => {
+ // The microtask race silently capped this at one: the second Ctrl+Z replayed
+ // the document the first had just pushed back on, so undo oscillated.
+ await useProjectStore.getState().saveDocument(titled("Second"));
+ await useProjectStore.getState().saveDocument(titled("Third"));
+ expect(currentTitle()).toBe("Third");
+
+ expect(undo()).toBe(true);
+ expect(currentTitle()).toBe("Second");
+ expect(undo()).toBe(true);
+ expect(currentTitle()).toBe("Original");
+ expect(undo()).toBe(false);
+
+ expect(redo()).toBe(true);
+ expect(currentTitle()).toBe("Second");
+ expect(redo()).toBe(true);
+ expect(currentTitle()).toBe("Third");
+ });
+
+ it("skips history for writes the user did not make", async () => {
+ // Probe backfills, background transcripts and the persist an undo itself
+ // triggers all opt out — a Ctrl+Z that reverted one of those would either do
+ // nothing visible or throw the transcript away.
+ await useProjectStore.getState().saveDocument(titled("Backfilled"), { history: false });
+
+ expect(past).toHaveLength(0);
+ expect(undo()).toBe(false);
+ expect(currentTitle()).toBe("Backfilled");
+ });
+
+ it("keeps the redo entry when the restored document is persisted", async () => {
+ // What `NewEditorShell` does in `useUndoRedoShortcuts`'s callback. Without
+ // `history: false` there, the persist re-records the restored document and
+ // wipes the redo the undo just created.
+ await useProjectStore.getState().saveDocument(titled("Renamed"));
+ expect(undo()).toBe(true);
+
+ const restored = useProjectStore.getState().document;
+ if (!restored) throw new Error("no document to persist");
+ await useProjectStore.getState().saveDocument(restored, { history: false });
+
+ expect(future).toHaveLength(1);
+ expect(redo()).toBe(true);
+ expect(currentTitle()).toBe("Renamed");
+ });
+
+ it("drops the redo stack once a new edit lands on an undone document", async () => {
+ await useProjectStore.getState().saveDocument(titled("Renamed"));
+ expect(undo()).toBe(true);
+ expect(future).toHaveLength(1);
+
+ await useProjectStore.getState().saveDocument(titled("Different branch"));
+
+ expect(future).toHaveLength(0);
+ expect(redo()).toBe(false);
+ });
+
+ it("refuses to restore a snapshot from another project", async () => {
+ await useProjectStore.getState().saveDocument(titled("Renamed"));
+ useProjectStore.setState({ projectId: "project_2" });
+
+ expect(undo()).toBe(false);
+ expect(past).toHaveLength(0);
+ expect(future).toHaveLength(0);
+ });
+
+ it("marks the document dirty so the restore can be persisted", async () => {
+ await useProjectStore.getState().saveDocument(titled("Renamed"));
+ expect(useProjectStore.getState().dirty).toBe(false);
+
+ const revisionBefore = useProjectStore.getState().revision;
+ expect(undo()).toBe(true);
+
+ expect(useProjectStore.getState().dirty).toBe(true);
+ // Consumers repaint off `document`; `revision` is what the agent-apply guard reads.
+ expect(useProjectStore.getState().revision).toBe(revisionBefore + 1);
+ });
+});
diff --git a/src/lib/ai-edition/store/undo.ts b/src/lib/ai-edition/store/undo.ts
index 80cda0d8d..875faaaaa 100644
--- a/src/lib/ai-edition/store/undo.ts
+++ b/src/lib/ai-edition/store/undo.ts
@@ -1,31 +1,33 @@
-// Lightweight undo/redo for the project document. The store fires
-// `documentChanged` whenever `setDocument` is called; subscribers record
-// snapshots up to a bounded history. Cmd+Z / Cmd+Shift+Z use the snapshot
-// stack to roll back / roll forward. Designed to be small and side-effect
-// free so it works in any renderer.
+// Lightweight undo/redo for the project document. Every write that goes through
+// `projectStore`'s `saveDocument` / `setDocument` records the outgoing document
+// on the stack in `undoStack.ts` (callers opt out with `{ history: false }` for
+// background writes). Ctrl+Z / Ctrl+Shift+Z / Ctrl+Y walk that stack.
+//
+// The restore writes `useProjectStore.setState` DIRECTLY rather than calling
+// back into `setDocument`, which is what makes redo work: routing it through a
+// recording write meant an undo re-recorded the document it had just replaced
+// and cleared `future` on the way past, so redo was gone before the user could
+// reach for it and Ctrl+Z degraded into an A/B toggle. Writing the state is also
+// all a repaint needs — the timeline, preview and shell all subscribe to
+// `s.document`.
import { useEffect, useRef } from "react";
import { isModalOpen } from "../modalGuard";
+import type { AxcutDocument } from "../schema";
import { useProjectStore } from "./projectStore";
+import { clearHistory, future, past } from "./undoStack";
-type Snapshot = { projectId: string; doc: unknown };
+export { clearHistory, pushHistory } from "./undoStack";
-const MAX_HISTORY = 50;
-const past: Snapshot[] = [];
-const future: Snapshot[] = [];
-
-let enabled = true;
-
-export function pushHistory(snapshot: Snapshot) {
- if (!enabled) return;
- past.push(snapshot);
- if (past.length > MAX_HISTORY) past.shift();
- future.length = 0;
-}
-
-export function clearHistory() {
- past.length = 0;
- future.length = 0;
+/** 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) {
+ useProjectStore.setState((state) => ({
+ document: doc as AxcutDocument,
+ revision: state.revision + 1,
+ dirty: true,
+ }));
}
export function undo(): boolean {
@@ -38,9 +40,7 @@ export function undo(): boolean {
}
const doc = state.document;
if (doc) future.push({ projectId: prev.projectId, doc: structuredClone(doc) });
- enabled = false;
- state.setDocument(prev.doc as never);
- enabled = true;
+ restore(prev.doc);
return true;
}
@@ -54,9 +54,7 @@ export function redo(): boolean {
}
const doc = state.document;
if (doc) past.push({ projectId: doc.project.id, doc: structuredClone(doc) });
- enabled = false;
- state.setDocument(next.doc as never);
- enabled = true;
+ restore(next.doc);
return true;
}
@@ -82,7 +80,9 @@ export function useUndoRedoShortcuts(onAfter: () => void) {
if (redo()) onAfterRef.current();
return;
}
- if (ctrl && e.key === "z") {
+ // `toLowerCase()`, like the two branches above: with Caps Lock on the browser
+ // reports "Z", and the bare `=== "z"` here fell through to nothing at all.
+ if (ctrl && e.key.toLowerCase() === "z") {
e.preventDefault();
if (undo()) onAfterRef.current();
return;
diff --git a/src/lib/ai-edition/store/undoStack.ts b/src/lib/ai-edition/store/undoStack.ts
new file mode 100644
index 000000000..8cf1c3b56
--- /dev/null
+++ b/src/lib/ai-edition/store/undoStack.ts
@@ -0,0 +1,34 @@
+// The undo/redo snapshot stacks, in their own module so `projectStore` can push
+// to them with a STATIC import.
+//
+// `setDocument` used to `void import("./undo").then(({ pushHistory }) => ...)`,
+// which put the push in a LATER microtask. `undo()` restored its snapshot inside
+// a synchronous `enabled = false` / `enabled = true` bracket, so by the time the
+// deferred push ran the guard was armed again: an undo's own write was recorded
+// as a fresh edit, `pushHistory` wiped `future`, and redo could never fire. The
+// import bought nothing either — `NewEditorShell` already pulls `undo.ts` into
+// the same chunk statically.
+//
+// This module deliberately imports nothing from the store, so `projectStore ->
+// undoStack` is a leaf edge and there is no cycle to reason about. `undo.ts`
+// re-exports `pushHistory` / `clearHistory` from here for existing callers.
+
+export type Snapshot = { projectId: string; doc: unknown };
+
+const MAX_HISTORY = 50;
+
+export const past: Snapshot[] = [];
+export const future: Snapshot[] = [];
+
+/** 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;
+}
+
+export function clearHistory() {
+ past.length = 0;
+ future.length = 0;
+}
diff --git a/src/lib/ai-edition/store/useCaptions.ts b/src/lib/ai-edition/store/useCaptions.ts
index 981be3cf8..dabf3f8d9 100644
--- a/src/lib/ai-edition/store/useCaptions.ts
+++ b/src/lib/ai-edition/store/useCaptions.ts
@@ -4,7 +4,7 @@
// writes only (for sliders), `commit` flushes. The document stays the single
// source of truth — nothing is cached here.
-import { useCallback, useMemo } from "react";
+import { useCallback, useMemo, useRef } from "react";
import {
type CaptionCue,
type CaptionSettings,
@@ -17,6 +17,7 @@ import {
putCaptionTranslation,
removeCaptionTranslation,
} from "../captions";
+import type { AxcutDocument } from "../schema";
import { useProjectStore } from "./projectStore";
export interface UseCaptionsResult {
@@ -70,11 +71,18 @@ export function useCaptions(): UseCaptionsResult {
[setDocument, saveDocument],
);
+ // See `useEditorSettings.setLive`: one undo step per slider drag, not one per
+ // pointer move. `liveDocRef` holds what this hook last wrote, so only a write
+ // landing on someone else's document opens a new history entry.
+ const liveDocRef = useRef<AxcutDocument | null>(null);
+
const setLive = useCallback(
(patch: CaptionSettingsPatch) => {
const doc = useProjectStore.getState().document;
if (!doc) return;
- setDocument(patchCaptionSettings(doc, patch));
+ const next = patchCaptionSettings(doc, patch);
+ setDocument(next, { history: liveDocRef.current !== doc });
+ liveDocRef.current = next;
},
[setDocument],
);
diff --git a/src/lib/ai-edition/store/useEditorSettings.ts b/src/lib/ai-edition/store/useEditorSettings.ts
index 8dade1065..9af58dd79 100644
--- a/src/lib/ai-edition/store/useEditorSettings.ts
+++ b/src/lib/ai-edition/store/useEditorSettings.ts
@@ -12,7 +12,8 @@
// the patch through `patchEditorSettings`, and persists via the store. No
// extra state, no caches — the document is the single source of truth.
-import { useCallback, useMemo } from "react";
+import { useCallback, useMemo, useRef } from "react";
+import type { AxcutDocument } from "../schema";
import {
type EditorSettingsPatch,
type EditorSettingsSnapshot,
@@ -53,11 +54,19 @@ export function useEditorSettings(): UseEditorSettingsResult {
[setDocument, saveDocument],
);
+ // The document this hook's own last `setLive` produced. A slider drag fires one
+ // `setLive` per pointer move, and recording each of them buried the real history
+ // under sixty one-pixel steps; only the first write of a drag — the one editing a
+ // document this callback did not produce — is a state worth returning to.
+ const liveDocRef = useRef<AxcutDocument | null>(null);
+
const setLive = useCallback(
(patch: EditorSettingsPatch) => {
const doc = useProjectStore.getState().document;
if (!doc) return;
- setDocument(patchEditorSettings(doc, patch));
+ const next = patchEditorSettings(doc, patch);
+ setDocument(next, { history: liveDocRef.current !== doc });
+ liveDocRef.current = next;
},
[setDocument],
);
diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.ts
index 788a8a4fc..c1fb293bf 100644
--- a/src/lib/ai-edition/store/useTimeline.ts
+++ b/src/lib/ai-edition/store/useTimeline.ts
@@ -137,10 +137,11 @@ export function useTimeline() {
// (collectNativeFormats), the output resolution (referenceClipDims) and the export badges all
// read it, so an unpopulated one silently drops that clip from ALL of them — which is why a
// cropped clip could show under ORIGINAL while an un-probed 16:9 sibling was missing entirely.
- // Probe once on load and persist via saveDocument (which doesn't touch undo/dirty), so the fix
- // sticks and every consumer agrees without each re-probing on its own (what the export dialog
- // used to do). Attempt each asset at most once per session, even on failure, so a file that
- // can't be probed doesn't spin the effect on every document change.
+ // Probe once on load and persist via saveDocument with `history: false` (a write the user
+ // never made must not be what the next Ctrl+Z reverses), so the fix sticks and every consumer
+ // agrees without each re-probing on its own (what the export dialog used to do). Attempt each
+ // asset at most once per session, even on failure, so a file that can't be probed doesn't
+ // spin the effect on every document change.
const probedAssetIdsRef = useRef<Set<string>>(new Set());
useEffect(() => {
if (!document) return;
@@ -185,22 +186,27 @@ export function useTimeline() {
// Re-read fresh state so a concurrent edit made while probing isn't stomped.
const current = useProjectStore.getState().document;
if (!current) return;
- await useProjectStore.getState().saveDocument({
- ...current,
- assets: current.assets.map((a) => {
- const found = probed[a.id];
- if (!found) return a;
- return {
- ...a,
- ...(found.video
- ? { video: { codec: "unknown", fps: 0, ...a.video, ...found.video } }
- : {}),
- ...(found.camera && a.cameraTrack
- ? { cameraTrack: { ...a.cameraTrack, ...found.camera } }
- : {}),
- };
- }),
- });
+ // `history: false` — see the comment above: a backfill nobody asked for must
+ // not become the thing the next Ctrl+Z reverses.
+ await useProjectStore.getState().saveDocument(
+ {
+ ...current,
+ assets: current.assets.map((a) => {
+ const found = probed[a.id];
+ if (!found) return a;
+ return {
+ ...a,
+ ...(found.video
+ ? { video: { codec: "unknown", fps: 0, ...a.video, ...found.video } }
+ : {}),
+ ...(found.camera && a.cameraTrack
+ ? { cameraTrack: { ...a.cameraTrack, ...found.camera } }
+ : {}),
+ };
+ }),
+ },
+ { history: false },
+ );
})();
return () => {
cancelled = true;
@@ -548,14 +554,19 @@ export function useTimeline() {
(id: string, focus: { cx: number; cy: number }) => {
const doc = useProjectStore.getState().document;
if (!doc) return;
- if (zoomFocusLiveRef.current !== doc) zoomFocusRollbackRef.current = doc;
+ // The first live write of a drag is the one editing a document this callback
+ // did not itself produce — so it is the pre-drag state, and the only one worth
+ // recording. Without the flag a pointermove-frequency drag pushed ~60 snapshots
+ // a second and evicted the real history behind it.
+ const dragStart = zoomFocusLiveRef.current !== doc;
+ if (dragStart) zoomFocusRollbackRef.current = doc;
const next: AxcutDocument = {
...doc,
zoomRanges: patchPillById(doc.zoomRanges, id, {
focus: { cx: finiteFraction(focus.cx), cy: finiteFraction(focus.cy) },
}) as AxcutDocument["zoomRanges"],
};
- setDocument(next);
+ setDocument(next, { history: dragStart });
zoomFocusLiveRef.current = next;
},
[setDocument],
@@ -665,12 +676,15 @@ export function useTimeline() {
(id: string, patch: Partial<AxcutDocument["annotations"][number]>) => {
const doc = useProjectStore.getState().document;
if (!doc) return;
- if (annotationLiveRef.current !== doc) annotationRollbackRef.current = doc;
+ // One undo step per drag, not per pointermove — same reasoning as
+ // `updateZoomFocusLive` above.
+ const dragStart = annotationLiveRef.current !== doc;
+ if (dragStart) annotationRollbackRef.current = doc;
const next: AxcutDocument = {
...doc,
annotations: patchPillById(doc.annotations, id, patch),
};
- setDocument(next);
+ setDocument(next, { history: dragStart });
annotationLiveRef.current = next;
},
[setDocument],