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): put clip insertion on the timeline queue, not beside it

EtienneLescotc2ccca289a86
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index 3145cea6d..236c84527 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -172,7 +172,7 @@ export function NewEditorShell() {
// 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({
+ const { apply: applyTimelineOp, enqueue: enqueueTimelineWrite } = useSequentialTimelineOps({
fallbackDocument: document,
saveDocument,
});
@@ -393,38 +393,33 @@ export function NewEditorShell() {
[setCurrentTime],
);
- // Same race, same shape of fix as `useSequentialTimelineOps` — see that file's header.
- // `insertClipAt` is a read-modify-write of the whole document, so two adds in flight at
- // once both read the pre-insert doc and the second `saveDocument` clobbers the first,
- // silently dropping a clip. Two adds is one double-click on **Add to timeline** (the
- // button has no pending state) or two quick drags. It can't route through `apply()`
- // because inserting a clip is not an AxcutTimelineOperation — it carries its own
- // background duration probe — so the queue is here, built the same way.
+ // Same race as `useSequentialTimelineOps` — see that file's header. `insertClipAt` is a
+ // read-modify-write of the whole document, so two adds in flight at once both read the
+ // pre-insert doc and the second `saveDocument` clobbers the first, silently dropping a
+ // clip. Two adds is one double-click on **Add to timeline** (the button has no pending
+ // state) or two quick drags.
+ //
+ // It goes on that hook's queue rather than one of its own: a second queue serialises
+ // adds against adds and nothing else, so an add still clobbers a trim landing at the
+ // same moment. It can't route through `apply()` — inserting a clip is not an
+ // AxcutTimelineOperation, it carries its own background duration probe — hence
+ // `enqueue`, which is the same chain without that constraint.
//
// The append index is read INSIDE the chain for the same reason the doc is: off the
// closure, `clips.length` stays frozen at the last render, so the second add lands
// before the first instead of after it.
- const addToTimelineQueueRef = useRef<Promise<unknown>>(Promise.resolve());
const handleDropAsset = useCallback(
- (assetId: string) => {
- const queued = addToTimelineQueueRef.current.then(() => {
+ (assetId: string) =>
+ enqueueTimelineWrite(() => {
const at = useProjectStore.getState().document?.timeline.clips.length ?? 0;
return tl.insertClipAt(assetId, at);
- });
- // Swallow on the STORED promise only, so a failed add doesn't poison the queue;
- // the caller still gets `queued` and can observe the rejection.
- addToTimelineQueueRef.current = queued.then(
- () => undefined,
- () => undefined,
- );
- return queued.catch((error) => {
+ }).catch((error) => {
toast.error(te("mediaStage.couldNotAddAsset"), {
description: error instanceof Error ? error.message : String(error),
});
throw error;
- });
- },
- [tl, te],
+ }),
+ [tl, te, enqueueTimelineWrite],
);
// Ref so the 'ended' listener below always sees the latest clips without tearing
diff --git a/src/lib/ai-edition/store/useSequentialTimelineOps.test.ts b/src/lib/ai-edition/store/useSequentialTimelineOps.test.ts
index 91f69aac5..556b381b4 100644
--- a/src/lib/ai-edition/store/useSequentialTimelineOps.test.ts
+++ b/src/lib/ai-edition/store/useSequentialTimelineOps.test.ts
@@ -11,6 +11,9 @@
// has a resolved promise to chain off.
// 3. The store-empty fallback (no project loaded) returns null instead
// of crashing.
+// 4. `enqueue` shares that one chain with `apply`, so a document write
+// that isn't an operation — the media panel's clip insertion — can't
+// race an op. A second queue would only serialise it against itself.
import { act, renderHook } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -162,6 +165,71 @@ describe("useSequentialTimelineOps", () => {
expect(saveDocument).toHaveBeenNthCalledWith(2, secondResult);
});
+ it("runs an enqueued write after the op ahead of it has committed", 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 }),
+ );
+
+ // What the insertion actually needs: the clip count, read at the moment
+ // 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 taskPromise = result.current.enqueue(() => {
+ trimsSeenByTask = useProjectStore.getState().document?.timeline.trimRanges.length ?? -1;
+ });
+ await Promise.all([opPromise, taskPromise]);
+ });
+
+ expect(trimsSeenByTask).toBe(1);
+ });
+
+ it("keeps the chain usable after an enqueued write throws", 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 }),
+ );
+
+ let rejection: unknown;
+ let ranAfterTheFailure = false;
+ await act(async () => {
+ const failing = result.current.enqueue(() => {
+ throw new Error("insert failed");
+ });
+ const next = result.current.enqueue(() => {
+ ranAfterTheFailure = true;
+ });
+ await failing.catch((err: unknown) => {
+ rejection = err;
+ });
+ await next;
+ });
+
+ // The caller sees the failure...
+ expect((rejection as Error).message).toBe("insert failed");
+ // ...and the queue behind it did not stall.
+ expect(ranAfterTheFailure).toBe(true);
+ });
+
it("returns null when the store has no document and no fallback is supplied", async () => {
const saveDocument = vi.fn(async () => true);
const { result } = renderHook(() =>
diff --git a/src/lib/ai-edition/store/useSequentialTimelineOps.ts b/src/lib/ai-edition/store/useSequentialTimelineOps.ts
index 0bcdd842f..b77756bf4 100644
--- a/src/lib/ai-edition/store/useSequentialTimelineOps.ts
+++ b/src/lib/ai-edition/store/useSequentialTimelineOps.ts
@@ -12,6 +12,20 @@
// reject the promise handed to the caller; both call sites `void` it, so those remain
// unhandled rejections. They are also the two failures that mean the code is broken
// rather than the disk, so they belong in the console.
+//
+// The chain is exposed as `enqueue` as well as `apply`, because the race
+// belongs to the DOCUMENT, not to AxcutTimelineOperation: every timeline
+// edit is a read-modify-write of the whole document, so a mutation that
+// serialises on its own second queue still clobbers one running on this
+// one. `insertClipAt` is the case in point — it can't be expressed as an
+// operation, since it carries a background duration probe, but it has to
+// share the queue with the ops. Anything that reads the doc and saves it
+// back belongs here.
+//
+// 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";
@@ -32,6 +46,17 @@ export interface SequentialTimelineOps {
* caller that needs to tell them apart has to widen this return type first.
*/
apply: (op: AxcutTimelineOperation) => Promise<AxcutDocument | null>;
+
+ /**
+ * Queue a document mutation that isn't an `AxcutTimelineOperation` on
+ * the same chain `apply` uses, so the two can't overwrite each other.
+ *
+ * `task` runs only once the previous queued call has settled. Read the
+ * document — and anything derived from it, an append index included —
+ * inside `task` rather than closing over it: a value captured at call
+ * time is the pre-mutation one, which is the whole race.
+ */
+ enqueue: <T>(task: () => Promise<T> | T) => Promise<T>;
}
export function useSequentialTimelineOps(options: {
@@ -44,30 +69,35 @@ export function useSequentialTimelineOps(options: {
const { fallbackDocument, saveDocument } = options;
const saveQueueRef = useRef<Promise<unknown>>(Promise.resolve());
+ const enqueue = useCallback(<T>(task: () => Promise<T> | T): Promise<T> => {
+ const queued = saveQueueRef.current.then(() => task());
+ // 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;
+ }, []);
+
const apply = useCallback(
- (op: AxcutTimelineOperation): Promise<AxcutDocument | null> => {
- const queued = saveQueueRef.current
- .then(() => import("@/lib/ai-edition/document/operations"))
- .then(async ({ 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 (await saveDocument(applied.document)) ? applied.document : null;
- });
- // Keep operation/import errors from poisoning the queue -- the next call still
- // needs a resolved promise to chain off. Save failures already resolve to null.
- saveQueueRef.current = queued.then(
- () => undefined,
- () => undefined,
- );
- return queued;
- },
- [fallbackDocument, saveDocument],
+ (op: AxcutTimelineOperation): Promise<AxcutDocument | null> =>
+ enqueue(async () => {
+ const { applyTimelineOperation } = await import("@/lib/ai-edition/document/operations");
+ // 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 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 (await saveDocument(applied.document)) ? applied.document : null;
+ }),
+ [enqueue, fallbackDocument, saveDocument],
);
- return { apply };
+ return { apply, enqueue };
}