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): stop a drag's snapshot outliving the drag, and the project

EtienneLescotdd4255905d75
diff --git a/src/lib/ai-edition/store/useCaptions.test.ts b/src/lib/ai-edition/store/useCaptions.test.ts
new file mode 100644
index 000000000..b0761c225
--- /dev/null
+++ b/src/lib/ai-edition/store/useCaptions.test.ts
@@ -0,0 +1,170 @@
+// @vitest-environment jsdom
+//
+// `useEditorSettings.test.ts`'s two cases, on the hook that shares its live/commit
+// split. Both hooks hold the pre-drag document in `liveBaseRef` until a commit
+// records it, both are driven by the same `SliderCell` — which fires `commit` from
+// a bare mouseup, with no `onChange` in front of it — and neither `set` empties
+// the refs, so a drag that never commits leaves a base behind for that click to
+// pick up.
+
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { getCaptionSettings } from "../captions";
+import type { AxcutDocument } from "../schema";
+import { axcutSchemaVersion } from "../schema";
+import { useProjectStore } from "./projectStore";
+import { clearHistory, undo } from "./undo";
+import { past } from "./undoStack";
+import { useCaptions } from "./useCaptions";
+
+const bridgeMocks = vi.hoisted(() => ({
+ get: vi.fn(),
+ create: vi.fn(),
+ save: vi.fn(),
+ addAsset: vi.fn(),
+ removeAsset: vi.fn(),
+ listProjects: vi.fn(),
+}));
+
+vi.mock("@/native/client", () => ({
+ nativeBridgeClient: {
+ aiEdition: {
+ get: bridgeMocks.get,
+ create: bridgeMocks.create,
+ save: bridgeMocks.save,
+ addAsset: bridgeMocks.addAsset,
+ removeAsset: bridgeMocks.removeAsset,
+ listProjects: bridgeMocks.listProjects,
+ },
+ },
+}));
+
+const docA: AxcutDocument = {
+ schemaVersion: axcutSchemaVersion,
+ project: {
+ id: "proj_a",
+ title: "A",
+ createdAt: "2026-06-25T10:00:00.000Z",
+ updatedAt: "2026-06-25T10:00:00.000Z",
+ primaryAssetId: "asset_1",
+ },
+ assets: [
+ {
+ id: "asset_1",
+ kind: "video",
+ label: "screen.webm",
+ originalPath: "/tmp/screen.webm",
+ durationSec: 30,
+ video: { codec: "unknown", width: 1920, height: 1080, fps: 0 },
+ cameraTrack: null,
+ },
+ ],
+ transcript: null,
+ transcripts: [],
+ timeline: {
+ clips: [],
+ gaps: [],
+ trimRanges: [],
+ muteRanges: [],
+ speedRanges: [],
+ captionRanges: [],
+ },
+ annotations: [],
+ zoomRanges: [],
+ legacyEditor: null,
+};
+
+const docB: AxcutDocument = {
+ ...docA,
+ project: { ...docA.project, id: "proj_b", title: "B" },
+};
+
+/** `fontSize` of the document a snapshot holds. 48 is the untouched default, so
+ * reading it back says "this is the pre-drag document" in one number. */
+const fontSizeOf = (doc: unknown) => getCaptionSettings(doc as AxcutDocument).fontSize;
+
+describe("useCaptions drag snapshots", () => {
+ beforeEach(() => {
+ useProjectStore.getState().clear();
+ clearHistory();
+ for (const mock of Object.values(bridgeMocks)) mock.mockReset();
+ bridgeMocks.save.mockImplementation(async (doc: AxcutDocument) => ({
+ success: true,
+ document: doc,
+ }));
+ useProjectStore.setState({
+ projectId: "proj_a",
+ document: docA,
+ revision: 1,
+ status: "ready",
+ error: null,
+ });
+ });
+
+ afterEach(() => {
+ clearHistory();
+ vi.clearAllMocks();
+ });
+
+ it("does not record a snapshot of the project the user left", async () => {
+ const { result, rerender } = renderHook(() => useCaptions());
+
+ act(() => result.current.setLive({ width: 60 }));
+
+ act(() => {
+ useProjectStore.setState({ projectId: "proj_b", document: docB });
+ });
+ rerender();
+
+ await act(async () => {
+ await result.current.set({ fontSize: 30 });
+ });
+ expect(past.map((s) => s.projectId)).toEqual(["proj_b"]);
+
+ await act(async () => {
+ await result.current.commit();
+ });
+
+ expect(past.map((s) => s.projectId)).toEqual(["proj_b"]);
+ // A foreign snapshot costs more than the one bogus step: `undo` answers a
+ // projectId that is not the store's by clearing the whole stack.
+ expect(undo()).toBe(true);
+ expect(fontSizeOf(useProjectStore.getState().document)).toBe(48);
+ });
+
+ it("does not hand a bare commit a base the edits since have already buried", async () => {
+ const { result } = renderHook(() => useCaptions());
+
+ act(() => result.current.setLive({ width: 60 }));
+
+ await act(async () => {
+ await result.current.set({ fontSize: 30 });
+ });
+ await act(async () => {
+ await result.current.set({ fontSize: 20 });
+ });
+ expect(past).toHaveLength(2);
+
+ await act(async () => {
+ await result.current.commit();
+ });
+
+ expect(past).toHaveLength(2);
+ expect(undo()).toBe(true);
+ expect(fontSizeOf(useProjectStore.getState().document)).toBe(30);
+ });
+
+ it("still records the pre-drag document when the drag does reach its commit", async () => {
+ const { result } = renderHook(() => useCaptions());
+
+ act(() => result.current.setLive({ fontSize: 60 }));
+ act(() => result.current.setLive({ fontSize: 72 }));
+ await act(async () => {
+ await result.current.commit();
+ });
+
+ expect(past).toHaveLength(1);
+ expect(undo()).toBe(true);
+ expect(fontSizeOf(useProjectStore.getState().document)).toBe(48);
+ });
+});
diff --git a/src/lib/ai-edition/store/useCaptions.ts b/src/lib/ai-edition/store/useCaptions.ts
index b7e05c3e6..36b13c95e 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, useRef } from "react";
+import { useCallback, useEffect, useMemo, useRef } from "react";
import {
type CaptionCue,
type CaptionSettings,
@@ -44,6 +44,7 @@ export interface UseCaptionsResult {
export function useCaptions(): UseCaptionsResult {
const document = useProjectStore((s) => s.document);
+ const projectId = useProjectStore((s) => s.projectId);
const setDocument = useProjectStore((s) => s.setDocument);
const saveDocument = useProjectStore((s) => s.saveDocument);
@@ -81,6 +82,15 @@ export function useCaptions(): UseCaptionsResult {
const liveDocRef = useRef<AxcutDocument | null>(null);
const liveBaseRef = useRef<AxcutDocument | null>(null);
+ // The same release `useEditorSettings` does, for the same reason: a drag that never
+ // commits leaves these holding two whole documents for the lifetime of the hook
+ // instance. `commit` below is what keeps a stale one off the undo stack.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: projectId is the trigger, not a read — the body only clears refs.
+ useEffect(() => {
+ liveDocRef.current = null;
+ liveBaseRef.current = null;
+ }, [projectId]);
+
const setLive = useCallback(
(patch: CaptionSettingsPatch) => {
const doc = useProjectStore.getState().document;
@@ -96,7 +106,9 @@ export function useCaptions(): UseCaptionsResult {
const commit = useCallback(async () => {
const doc = useProjectStore.getState().document;
if (!doc) return;
- const base = liveBaseRef.current;
+ // See `useEditorSettings.commit`: a base is only worth recording while the
+ // document on screen is still the one this hook's live writes produced.
+ const base = liveDocRef.current === doc ? liveBaseRef.current : null;
liveBaseRef.current = null;
liveDocRef.current = null;
await saveDocument(doc, { history: true, historyBase: base });
diff --git a/src/lib/ai-edition/store/useEditorSettings.test.ts b/src/lib/ai-edition/store/useEditorSettings.test.ts
new file mode 100644
index 000000000..bd47cb452
--- /dev/null
+++ b/src/lib/ai-edition/store/useEditorSettings.test.ts
@@ -0,0 +1,184 @@
+// @vitest-environment jsdom
+//
+// What a slider drag is allowed to put on the undo stack, and — the part that
+// went wrong — what it is allowed to still be holding once the drag is over.
+//
+// `liveBaseRef` is the document a drag started from, kept until the commit that
+// records it. Nothing else emptied it: `set` leaves it alone, and a drag does not
+// always reach a commit (the gradient editor's is a 400ms timer its own unmount
+// cleanup cancels). `SliderCell` then wires mouseup/touchend/keyup straight to
+// `commit` with no `onChange` in front, so a bare click on a thumb is enough to
+// hand that leftover on as `historyBase`.
+
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { AxcutDocument } from "../schema";
+import { axcutSchemaVersion } from "../schema";
+import { getEditorSettings } from "./editorSettings";
+import { useProjectStore } from "./projectStore";
+import { clearHistory, undo } from "./undo";
+import { past } from "./undoStack";
+import { useEditorSettings } from "./useEditorSettings";
+
+const bridgeMocks = vi.hoisted(() => ({
+ get: vi.fn(),
+ create: vi.fn(),
+ save: vi.fn(),
+ addAsset: vi.fn(),
+ removeAsset: vi.fn(),
+ listProjects: vi.fn(),
+}));
+
+vi.mock("@/native/client", () => ({
+ nativeBridgeClient: {
+ aiEdition: {
+ get: bridgeMocks.get,
+ create: bridgeMocks.create,
+ save: bridgeMocks.save,
+ addAsset: bridgeMocks.addAsset,
+ removeAsset: bridgeMocks.removeAsset,
+ listProjects: bridgeMocks.listProjects,
+ },
+ },
+}));
+
+const docA: AxcutDocument = {
+ schemaVersion: axcutSchemaVersion,
+ project: {
+ id: "proj_a",
+ title: "A",
+ createdAt: "2026-06-25T10:00:00.000Z",
+ updatedAt: "2026-06-25T10:00:00.000Z",
+ primaryAssetId: "asset_1",
+ },
+ assets: [
+ {
+ id: "asset_1",
+ kind: "video",
+ label: "screen.webm",
+ originalPath: "/tmp/screen.webm",
+ durationSec: 30,
+ video: { codec: "unknown", width: 1920, height: 1080, fps: 0 },
+ cameraTrack: null,
+ },
+ ],
+ transcript: null,
+ transcripts: [],
+ timeline: {
+ clips: [],
+ gaps: [],
+ trimRanges: [],
+ muteRanges: [],
+ speedRanges: [],
+ captionRanges: [],
+ },
+ annotations: [],
+ zoomRanges: [],
+ legacyEditor: null,
+};
+
+const docB: AxcutDocument = {
+ ...docA,
+ project: { ...docA.project, id: "proj_b", title: "B" },
+};
+
+/** `borderRadius` of the document a snapshot holds. The defaults are the tell:
+ * 40 is what nobody has touched, so an assertion on it says "this is the
+ * pre-drag document" without spelling the whole fixture out again. */
+const radiusOf = (doc: unknown) => getEditorSettings(doc as AxcutDocument).borderRadius;
+
+describe("useEditorSettings drag snapshots", () => {
+ beforeEach(() => {
+ useProjectStore.getState().clear();
+ clearHistory();
+ for (const mock of Object.values(bridgeMocks)) mock.mockReset();
+ bridgeMocks.save.mockImplementation(async (doc: AxcutDocument) => ({
+ success: true,
+ document: doc,
+ }));
+ useProjectStore.setState({
+ projectId: "proj_a",
+ document: docA,
+ revision: 1,
+ status: "ready",
+ error: null,
+ });
+ });
+
+ afterEach(() => {
+ clearHistory();
+ vi.clearAllMocks();
+ });
+
+ it("does not record a snapshot of the project the user left", async () => {
+ const { result, rerender } = renderHook(() => useEditorSettings());
+
+ // The drag that never commits. `liveBaseRef` now holds project A's document.
+ act(() => result.current.setLive({ padding: 80 }));
+
+ act(() => {
+ useProjectStore.setState({ projectId: "proj_b", document: docB });
+ });
+ rerender();
+
+ // One real edit in project B, so the stack has something to lose.
+ await act(async () => {
+ await result.current.set({ borderRadius: 10 });
+ });
+ expect(past.map((s) => s.projectId)).toEqual(["proj_b"]);
+
+ // The bare click on a slider thumb.
+ await act(async () => {
+ await result.current.commit();
+ });
+
+ expect(past.map((s) => s.projectId)).toEqual(["proj_b"]);
+ // And what the foreign snapshot cost is more than one step: `undo` answers a
+ // projectId that is not the store's by throwing the WHOLE stack away, so the
+ // user loses this edit's undo as well as the bogus one.
+ expect(undo()).toBe(true);
+ expect(radiusOf(useProjectStore.getState().document)).toBe(40);
+ });
+
+ it("does not hand a bare commit a base the edits since have already buried", async () => {
+ const { result } = renderHook(() => useEditorSettings());
+
+ act(() => result.current.setLive({ padding: 80 }));
+
+ // Two edits the user makes next, each recording its own step.
+ await act(async () => {
+ await result.current.set({ borderRadius: 10 });
+ });
+ await act(async () => {
+ await result.current.set({ borderRadius: 20 });
+ });
+ expect(past).toHaveLength(2);
+
+ await act(async () => {
+ await result.current.commit();
+ });
+
+ // Same project, so no clearing happens — the cost here is that one Ctrl+Z
+ // jumps over both edits and lands on the document the abandoned drag started
+ // from (radius 40, the untouched default).
+ expect(past).toHaveLength(2);
+ expect(undo()).toBe(true);
+ expect(radiusOf(useProjectStore.getState().document)).toBe(10);
+ });
+
+ it("still records the pre-drag document when the drag does reach its commit", async () => {
+ // The guards above must not cost the feature they are guarding: a drag that
+ // ends the way a drag normally ends is still ONE undo step, back to before it.
+ const { result } = renderHook(() => useEditorSettings());
+
+ act(() => result.current.setLive({ borderRadius: 12 }));
+ act(() => result.current.setLive({ borderRadius: 14 }));
+ await act(async () => {
+ await result.current.commit();
+ });
+
+ expect(past).toHaveLength(1);
+ expect(undo()).toBe(true);
+ expect(radiusOf(useProjectStore.getState().document)).toBe(40);
+ });
+});
diff --git a/src/lib/ai-edition/store/useEditorSettings.ts b/src/lib/ai-edition/store/useEditorSettings.ts
index 032ec8230..eb4bce991 100644
--- a/src/lib/ai-edition/store/useEditorSettings.ts
+++ b/src/lib/ai-edition/store/useEditorSettings.ts
@@ -12,7 +12,7 @@
// 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, useRef } from "react";
+import { useCallback, useEffect, useMemo, useRef } from "react";
import type { AxcutDocument } from "../schema";
import {
type EditorSettingsPatch,
@@ -36,6 +36,7 @@ export interface UseEditorSettingsResult {
export function useEditorSettings(): UseEditorSettingsResult {
const document = useProjectStore((s) => s.document);
+ const projectId = useProjectStore((s) => s.projectId);
const setDocument = useProjectStore((s) => s.setDocument);
const saveDocument = useProjectStore((s) => s.saveDocument);
@@ -66,6 +67,21 @@ export function useEditorSettings(): UseEditorSettingsResult {
const liveDocRef = useRef<AxcutDocument | null>(null);
const liveBaseRef = useRef<AxcutDocument | null>(null);
+ // A drag does not always end in a commit -- the gradient editor's is a 400ms timer
+ // its own unmount cleanup cancels -- and nothing else empties these, so left alone
+ // they pin two whole documents for the lifetime of the hook instance. The editor
+ // mounts six `useEditorSettings()` at once and annotations can carry base64 image
+ // data URLs, so that is not a small pin. Release them when the project changes,
+ // which is the guard `useTimeline` carries, keyed on the same thing, for the same
+ // reason. What it is NOT is the reason a snapshot of the project the user left
+ // cannot reach the undo stack: `commit` below decides that, and decides it for a
+ // project that never changed too.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: projectId is the trigger, not a read — the body only clears refs.
+ useEffect(() => {
+ liveDocRef.current = null;
+ liveBaseRef.current = null;
+ }, [projectId]);
+
const setLive = useCallback(
(patch: EditorSettingsPatch) => {
const doc = useProjectStore.getState().document;
@@ -81,7 +97,16 @@ export function useEditorSettings(): UseEditorSettingsResult {
const commit = useCallback(async () => {
const doc = useProjectStore.getState().document;
if (!doc) return;
- const base = liveBaseRef.current;
+ // The base counts only while the document on screen is still the one this hook's
+ // last `setLive` produced -- `setLive`'s own identity test, read the other way
+ // round. `SliderCell` fires `commit` from a bare mouseup with no `onChange` in
+ // front of it, so a click on a thumb arrives here carrying whatever base a drag
+ // that never committed left behind, and every recording write since has already
+ // put the states in between on the stack: handing that base on made one Ctrl+Z
+ // step over the lot of them. Across a project switch it is worse than a wrong
+ // step -- the snapshot names the OLD project, and `undo` answers a projectId
+ // that is not the store's by throwing the whole stack away.
+ const base = liveDocRef.current === doc ? liveBaseRef.current : null;
liveBaseRef.current = null;
liveDocRef.current = null;
await saveDocument(doc, { history: true, historyBase: base });