Skip to content

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

refactor: extract useSequentialTimelineOps hook from NewEditorShell

Etienne Lescotc4568ba219d6
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index b530662c8..7af5ccc01 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -12,6 +12,7 @@ import {
import { transcribeAsset } from "@/lib/ai-edition/document/transcribe";
import { type AxcutClip, documentSchema } from "@/lib/ai-edition/schema";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
+import { useSequentialTimelineOps } from "@/lib/ai-edition/store/useSequentialTimelineOps";
import { useUndoRedoShortcuts } from "@/lib/ai-edition/store/undo";
import { useTimeline } from "@/lib/ai-edition/store/useTimeline";
import { matchesShortcut } from "@/lib/shortcuts";
@@ -111,10 +112,13 @@ export function NewEditorShell() {
}
// ponytail: serialise timeline-edit saves so two rapid Backspaces
- // don't race each other's IPC save and overwrite one another in the
- // store. Each new save chains off the previous one, so the store is
- // always updated in the order the user issued the trims.
- const saveQueueRef = useRef<Promise<void>>(Promise.resolve());
+ // don't race each other's save and overwrite one another in the
+ // store. The hook reads the doc inside the chain (after awaiting the
+ // previous save) — see its source for the race this fixes.
+ const { apply: applyTimelineOp } = useSequentialTimelineOps({
+ fallbackDocument: document,
+ saveDocument,
+ });
const promptUnsaved = useCallback(
(action: "close" | "new" | "open" | "record"): Promise<UnsavedChoice> => {
@@ -537,63 +541,24 @@ export function NewEditorShell() {
// trimRange (NOT a destructive word removal — the source text stays
// intact, the word is just hidden by the skip overlay). Mirrors
// axcut's `queueAddTrimRange` / `queueRemoveTrimRange` callbacks in
- // apps/web/src/App.tsx.
+ // apps/web/src/App.tsx. The serialised save + inside-the-chain doc
+ // read is owned by `useSequentialTimelineOps` above.
const handleAddTrimRange = useCallback(
(assetId: string, startSec: number, endSec: number, reason: string) => {
- // BUG corrigé : `doc` était lu de façon SYNCHRONE au moment de l'appel, puis seule la
- // SAUVEGARDE était sérialisée via `saveQueueRef` — pas la LECTURE. Éditer le clip 1 puis
- // le clip 2 avant que la chaîne async du premier save (import() + applyTimelineOperation +
- // saveDocument, qui fait un aller-retour IPC) n'ait commit dans le store faisait lire au
- // second appel le MÊME doc pré-edit-1 ; son propre saveDocument(next.document) écrasait
- // alors le store avec un doc qui contient le trim du clip 2 mais PAS celui du clip 1 — les
- // edits du clip 1 disparaissaient. La lecture doit donc elle aussi être mise dans la
- // chaîne, après avoir attendu le tour précédent, pour toujours partir du doc déjà commit.
- const queued = saveQueueRef.current
- .then(() => import("@/lib/ai-edition/document/operations"))
- .then(({ applyTimelineOperation }) => {
- const doc = useProjectStore.getState().document ?? document;
- if (!doc) return null;
- return applyTimelineOperation(doc, {
- type: "add_trim_range",
- assetId,
- startSec,
- endSec,
- reason,
- });
- })
- .then((next) => next && saveDocument(next.document));
- saveQueueRef.current = queued.then(
- () => undefined,
- () => undefined,
- );
- return queued;
+ void applyTimelineOp({ type: "add_trim_range", assetId, startSec, endSec, reason });
},
- [document, saveDocument],
+ [applyTimelineOp],
);
const handleRemoveTrimRange = useCallback(
(trimId: string) => {
- // See handleAddTrimRange above — same fix: the document read must be
- // inside the queued chain, after awaiting the previous save.
- const queued = saveQueueRef.current
- .then(() => import("@/lib/ai-edition/document/operations"))
- .then(({ applyTimelineOperation }) => {
- const doc = useProjectStore.getState().document ?? document;
- if (!doc) return null;
- return applyTimelineOperation(doc, {
- type: "remove_trim_range",
- trimId,
- reason: "Restored from transcript pane.",
- });
- })
- .then((next) => next && saveDocument(next.document));
- saveQueueRef.current = queued.then(
- () => undefined,
- () => undefined,
- );
- return queued;
+ void applyTimelineOp({
+ type: "remove_trim_range",
+ trimId,
+ reason: "Restored from transcript pane.",
+ });
},
- [document, saveDocument],
+ [applyTimelineOp],
);
const handleSelectProject = useCallback(
diff --git a/src/lib/ai-edition/store/useSequentialTimelineOps.test.ts b/src/lib/ai-edition/store/useSequentialTimelineOps.test.ts
new file mode 100644
index 000000000..9ec6c401b
--- /dev/null
+++ b/src/lib/ai-edition/store/useSequentialTimelineOps.test.ts
@@ -0,0 +1,215 @@
+// ponytail: tests for the queued timeline-op hook. The hook used to live
+// inline in NewEditorShell.tsx (saveQueueRef + handleAddTrimRange /
+// handleRemoveTrimRange) and was untested; the bug it fixed (synchronous
+// doc read vs async save) is the kind of regression that slips back in
+// without a test. These cover the three properties the inline pattern
+// depended on:
+// 1. Two concurrent calls are serialised — op N+1 reads the doc op N
+// committed, not the pre-op-N doc.
+// 2. A save rejection doesn't poison the queue; the next call still
+// has a resolved promise to chain off.
+// 3. The store-empty fallback (no project loaded) returns null instead
+// of crashing.
+
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { createEmptyDocument, type AxcutDocument } from "@/lib/ai-edition/schema";
+import { useProjectStore } from "./projectStore";
+import { useSequentialTimelineOps } from "./useSequentialTimelineOps";
+
+function makeDocWithAsset(): AxcutDocument {
+ const base = createEmptyDocument({ projectId: "proj_seq", title: "seq" });
+ return {
+ ...base,
+ assets: [
+ {
+ id: "asset_1",
+ kind: "video",
+ label: "screen.webm",
+ originalPath: "/tmp/screen.webm",
+ durationSec: 30,
+ video: { codec: "unknown", width: 1920, height: 1080, fps: 0 },
+ },
+ ],
+ project: { ...base.project, primaryAssetId: "asset_1" },
+ timeline: {
+ ...base.timeline,
+ clips: [
+ {
+ id: "clip_a",
+ assetId: "asset_1",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ },
+ ],
+ },
+ };
+}
+
+beforeEach(() => {
+ useProjectStore.getState().clear();
+});
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("useSequentialTimelineOps", () => {
+ it("serialises calls: op N+1 reads the doc op N committed", async () => {
+ const seed = makeDocWithAsset();
+ useProjectStore.setState({ document: seed });
+
+ const callOrder: string[] = [];
+ const saveDocument = vi.fn(async (doc: AxcutDocument) => {
+ // Mirror the real store: write the saved doc back so the next
+ // call in the queue sees the latest committed state.
+ useProjectStore.getState().setDocument(doc);
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ callOrder.push(doc.timeline.trimRanges[0]?.startSec.toString() ?? "empty");
+ });
+
+ const { result } = renderHook(() =>
+ useSequentialTimelineOps({ fallbackDocument: seed, saveDocument }),
+ );
+
+ const op1 = {
+ type: "add_trim_range" as const,
+ assetId: "asset_1",
+ startSec: 1,
+ endSec: 2,
+ reason: "first",
+ };
+ const op2 = {
+ type: "add_trim_range" as const,
+ assetId: "asset_1",
+ startSec: 5,
+ endSec: 6,
+ reason: "second",
+ };
+
+ await act(async () => {
+ const r1 = result.current.apply(op1);
+ const r2 = result.current.apply(op2);
+ await Promise.all([r1, r2]);
+ });
+
+ // Both saves fired in queue order (callOrder), and the second save
+ // saw a doc that ALREADY had the first trim applied.
+ expect(callOrder).toEqual(["1", "1"]);
+ expect(saveDocument).toHaveBeenCalledTimes(2);
+ const doc1 = saveDocument.mock.calls[0]?.[0] as AxcutDocument;
+ const doc2 = saveDocument.mock.calls[1]?.[0] as AxcutDocument;
+ expect(doc1.timeline.trimRanges).toHaveLength(1);
+ expect(doc1.timeline.trimRanges[0]?.startSec).toBe(1);
+ expect(doc2.timeline.trimRanges).toHaveLength(2);
+ expect(doc2.timeline.trimRanges.map((t) => t.startSec).sort()).toEqual([1, 5]);
+ });
+
+ it("swallows save errors so the next call can still proceed", async () => {
+ const seed = makeDocWithAsset();
+ useProjectStore.setState({ document: seed });
+
+ const saveDocument = vi
+ .fn<(doc: AxcutDocument) => Promise<void>>()
+ .mockRejectedValueOnce(new Error("save failed"))
+ .mockImplementationOnce(async (doc) => {
+ useProjectStore.getState().setDocument(doc);
+ });
+
+ const { result } = renderHook(() =>
+ useSequentialTimelineOps({ fallbackDocument: seed, saveDocument }),
+ );
+
+ const op1 = {
+ type: "add_trim_range" as const,
+ assetId: "asset_1",
+ startSec: 1,
+ endSec: 2,
+ reason: "first",
+ };
+ const op2 = {
+ type: "remove_trim_range" as const,
+ trimId: "trim_doesnt_exist",
+ reason: "second",
+ };
+
+ let firstSettled = false;
+ let secondSettled = false;
+ await act(async () => {
+ const p1 = result.current.apply(op1);
+ const p2 = result.current.apply(op2);
+ await p1.catch((err: unknown) => {
+ firstSettled = true;
+ expect((err as Error).message).toBe("save failed");
+ });
+ await p2.then(() => {
+ secondSettled = true;
+ });
+ });
+
+ expect(firstSettled).toBe(true);
+ expect(secondSettled).toBe(true);
+ // The queue survived the first failure — both saves were attempted.
+ expect(saveDocument).toHaveBeenCalledTimes(2);
+ });
+
+ it("returns null when the store has no document and no fallback is supplied", async () => {
+ const saveDocument = vi.fn(async () => undefined);
+ const { result } = renderHook(() =>
+ useSequentialTimelineOps({ fallbackDocument: null, saveDocument }),
+ );
+
+ const op = {
+ type: "add_trim_range" as const,
+ assetId: "asset_1",
+ startSec: 1,
+ endSec: 2,
+ reason: "no doc",
+ };
+
+ let resolved: AxcutDocument | null | undefined;
+ await act(async () => {
+ resolved = await result.current.apply(op);
+ });
+
+ expect(resolved).toBeNull();
+ // And the queue should NOT have called saveDocument — nothing to save.
+ expect(saveDocument).not.toHaveBeenCalled();
+ });
+
+ it("returns the saved document from the apply() promise", async () => {
+ const seed = makeDocWithAsset();
+ useProjectStore.setState({ document: seed });
+
+ const saveDocument = vi.fn(async (doc: AxcutDocument) => {
+ useProjectStore.getState().setDocument(doc);
+ });
+
+ const { result } = renderHook(() =>
+ useSequentialTimelineOps({ fallbackDocument: seed, saveDocument }),
+ );
+
+ const op = {
+ type: "add_trim_range" as const,
+ assetId: "asset_1",
+ startSec: 1,
+ endSec: 2,
+ reason: "x",
+ };
+
+ let returned: AxcutDocument | null | undefined;
+ await act(async () => {
+ returned = await result.current.apply(op);
+ });
+
+ expect(returned).toBeDefined();
+ expect(returned?.timeline.trimRanges).toHaveLength(1);
+ expect(returned?.timeline.trimRanges[0]?.startSec).toBe(1);
+ expect(returned?.timeline.trimRanges[0]?.endSec).toBe(2);
+ });
+});
diff --git a/src/lib/ai-edition/store/useSequentialTimelineOps.ts b/src/lib/ai-edition/store/useSequentialTimelineOps.ts
new file mode 100644
index 000000000..642c5a435
--- /dev/null
+++ b/src/lib/ai-edition/store/useSequentialTimelineOps.ts
@@ -0,0 +1,71 @@
+// ponytail: serialise timeline-edit saves so two rapid calls don't race
+// each other's save and overwrite one another in the store. The previous
+// in-component implementation in NewEditorShell.tsx had a subtle race
+// where the doc was read SYNCHRONOUSLY at call time but the save was
+// serialised; two concurrent calls would both read the same pre-edit
+// doc and the second save would clobber the first edit. The fix is to
+// read the doc INSIDE the chain, after awaiting the previous save, so
+// every call sees the doc state the previous call committed.
+//
+// Errors are swallowed when advancing the queue ref so a failed save
+// doesn't poison the queue (the next call still has a resolved promise
+// to chain off). The original promise returned to the caller is NOT
+// swallowed — the caller can await it and observe the rejection.
+
+import { useCallback, useRef } from "react";
+import type { AxcutTimelineOperation } from "@/lib/ai-edition/document/operations";
+import type { AxcutDocument } from "@/lib/ai-edition/schema";
+import { useProjectStore } from "./projectStore";
+
+export interface SequentialTimelineOps {
+ /**
+ * Queue a timeline op. The op is applied to the latest committed
+ * document (read from the project store inside the queue, after the
+ * previous op's save has resolved), and the resulting document is
+ * saved. Calls are serialised — op N+1 reads the doc op N wrote.
+ *
+ * Returns the saved document, or `null` if no project document is
+ * loaded (store empty AND no fallback supplied).
+ */
+ apply: (op: AxcutTimelineOperation) => Promise<AxcutDocument | null>;
+}
+
+export function useSequentialTimelineOps(options: {
+ /** Used only when the project store has no document yet. */
+ fallbackDocument: AxcutDocument | null;
+ /** Persist a document. The hook awaits this before unblocking the queue. */
+ saveDocument: (doc: AxcutDocument) => Promise<unknown>;
+}): SequentialTimelineOps {
+ const { fallbackDocument, saveDocument } = options;
+ const saveQueueRef = useRef<Promise<unknown>>(Promise.resolve());
+
+ const apply = useCallback(
+ (op: AxcutTimelineOperation): Promise<AxcutDocument | null> => {
+ const queued = saveQueueRef.current
+ .then(() => import("@/lib/ai-edition/document/operations"))
+ .then(({ applyTimelineOperation }) => {
+ // Read the doc inside the chain. The store holds the
+ // latest committed state because the previous call's
+ // save has already resolved by the time this .then
+ // runs — see the file header for the race this fixes.
+ const doc = useProjectStore.getState().document ?? fallbackDocument;
+ if (!doc) return null;
+ const applied = applyTimelineOperation(doc, op);
+ return saveDocument(applied.document).then(() => applied.document);
+ });
+ // Swallow rejection when advancing the queue so a failed save
+ // doesn't poison the queue — the next call still has a
+ // resolved promise to chain off. The original `queued` is
+ // returned to the caller, who can await it and observe the
+ // rejection.
+ saveQueueRef.current = queued.then(
+ () => undefined,
+ () => undefined,
+ );
+ return queued;
+ },
+ [fallbackDocument, saveDocument],
+ );
+
+ return { apply };
+}