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(inspector): keep queued zoom writes from crossing replacements or a stalled save

超超超超超级喜欢你的达妮娅072414671c84
diff --git a/src/lib/ai-edition/store/useTimeline.test.ts b/src/lib/ai-edition/store/useTimeline.test.ts
index fc267a771..d17268bbd 100644
--- a/src/lib/ai-edition/store/useTimeline.test.ts
+++ b/src/lib/ai-edition/store/useTimeline.test.ts
@@ -1277,6 +1277,139 @@ describe("useTimeline undo history", () => {
});
});
+ // Rebase-review finding (queued zoom writes vs. document replacement): a zoom write
+ // queued behind a still-pending one starts AFTER an undo has restored the document,
+ // and must not apply its stale patch to the replacement. The in-flight write itself
+ // is dropped by `saveDocument`'s epoch check; the queued one is the hole.
+ it("drops a queued zoom write that starts after an undo replaces the document", async () => {
+ seed(docWithZoom);
+ const { result } = renderTimeline();
+ // One settled write so the undo has a recorded state to restore.
+ await act(async () => {
+ await result.current.updateZoomDepth("zoom_a", 4);
+ });
+ expect(useProjectStore.getState().document?.zoomRanges[0]?.depth).toBe(4);
+
+ const gate = gateFirstSave();
+ const pRotation = result.current.updateZoomRotation("zoom_a", "iso");
+ const pCursor = result.current.updateZoomHideCursor("zoom_a", true);
+ await waitFor(() => expect(gate.release).toEqual(expect.any(Function)));
+ let undid = false;
+ act(() => {
+ undid = undo();
+ });
+ expect(undid).toBe(true);
+ expect(useProjectStore.getState().document?.zoomRanges[0]?.depth).toBe(3);
+
+ await act(async () => {
+ gate.release?.();
+ await Promise.allSettled([pRotation, pCursor]);
+ });
+
+ // The undo's result stands; neither queued write landed on the restored document.
+ expect(useProjectStore.getState().document?.zoomRanges[0]).toMatchObject({ depth: 3 });
+ expect(useProjectStore.getState().document?.zoomRanges[0]?.rotationPreset).toBeUndefined();
+ expect(useProjectStore.getState().document?.zoomRanges[0]?.hideCursor).toBeUndefined();
+ });
+
+ // Same finding through the project-switch path: `loadProject` replaces projectId and
+ // document without superseding the queue, and project B deliberately contains the same
+ // region id, so a stale patch must not escape detection by id coincidence.
+ it("drops queued zoom writes when a project switch replaces the document", async () => {
+ seed(docWithZoom);
+ const { result } = renderTimeline();
+ const projectB: AxcutDocument = {
+ ...docWithZoom,
+ project: { ...docWithZoom.project, id: "proj_b", title: "Project B" },
+ zoomRanges: [{ ...docWithZoom.zoomRanges[0]!, depth: 2 }],
+ };
+
+ const gate = gateFirstSave();
+ const pRotation = result.current.updateZoomRotation("zoom_a", "iso");
+ const pCursor = result.current.updateZoomHideCursor("zoom_a", true);
+ await waitFor(() => expect(gate.release).toEqual(expect.any(Function)));
+ bridgeMocks.get.mockResolvedValue({ success: true, document: projectB });
+ await act(async () => {
+ await useProjectStore.getState().loadProject("proj_b");
+ });
+ expect(useProjectStore.getState().projectId).toBe("proj_b");
+
+ await act(async () => {
+ gate.release?.();
+ await Promise.allSettled([pRotation, pCursor]);
+ });
+
+ // Project B's own zoom_a is untouched by the stale project-A queue.
+ expect(useProjectStore.getState().document?.zoomRanges[0]).toMatchObject({
+ id: "zoom_a",
+ depth: 2,
+ });
+ expect(useProjectStore.getState().document?.zoomRanges[0]?.rotationPreset).toBeUndefined();
+ expect(useProjectStore.getState().document?.zoomRanges[0]?.hideCursor).toBeUndefined();
+ });
+
+ // Rebase-review finding (stalled save blocks the zoom queue): while one zoom save's
+ // answer is unknown (bridge never settles), later zoom-pane writes must not queue
+ // behind it forever — they are refused until the unknown save settles, then work
+ // again. The refusal is the safe half: the unknown save may still land, so racing
+ // it would recreate the stale-document overwrite this chain exists to prevent.
+ it("refuses zoom writes while a save is unknown and recovers when it settles", async () => {
+ seed(docWithZoom);
+ vi.useFakeTimers();
+ try {
+ let hungDoc: AxcutDocument | undefined;
+ let releaseHungSave: (result: { success: boolean; document: AxcutDocument }) => void;
+ bridgeMocks.save.mockImplementation((doc: AxcutDocument) => {
+ hungDoc = doc;
+ return new Promise((resolve) => {
+ releaseHungSave = (result) => {
+ // Settle this one call only; later saves answer immediately.
+ bridgeMocks.save.mockImplementation(async (next: AxcutDocument) => ({
+ success: true,
+ document: next,
+ }));
+ resolve(result);
+ };
+ });
+ });
+ const { result } = renderTimeline();
+
+ let depthOk: boolean | undefined;
+ act(() => {
+ void result.current.updateZoomDepth("zoom_a", 4).then((ok) => {
+ depthOk = ok;
+ });
+ });
+ // Deadline passes with the bridge still silent: the write's result is unknown,
+ // reported to the caller as not-taken, and the document is left alone.
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(10_000);
+ });
+ expect(depthOk).toBe(false);
+ expect(useProjectStore.getState().document?.zoomRanges[0]?.depth).toBe(3);
+
+ // A later zoom write is refused while that save is still unknown.
+ let rotationOk: boolean | undefined;
+ await act(async () => {
+ rotationOk = await result.current.updateZoomRotation("zoom_a", "iso");
+ });
+ expect(rotationOk).toBe(false);
+ expect(useProjectStore.getState().document?.zoomRanges[0]?.rotationPreset).toBeUndefined();
+
+ // The unknown save settles late — it may land — and the refusal clears.
+ await act(async () => {
+ releaseHungSave({ success: true, document: hungDoc! });
+ for (let i = 0; i < 20; i++) await Promise.resolve();
+ });
+ await act(async () => {
+ await result.current.updateZoomDepth("zoom_a", 5);
+ });
+ expect(useProjectStore.getState().document?.zoomRanges[0]?.depth).toBe(5);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("resolves a zoom-level write with whether the save took effect", async () => {
seed(docWithZoom);
const { result } = renderTimeline();
diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.ts
index 724127dd6..2e5dfff10 100644
--- a/src/lib/ai-edition/store/useTimeline.ts
+++ b/src/lib/ai-edition/store/useTimeline.ts
@@ -43,7 +43,8 @@ import {
} from "../timeline/timelineMap";
import { dropTrimPillsByIds, resolveTimelineSpanToTrim } from "../timeline/trim-mapping";
import type { AutoZoomSuggestion } from "../timeline/zoom-suggestions";
-import { useProjectStore, waitForDocumentSaves } from "./projectStore";
+import { saveWithDeadline, useProjectStore, waitForDocumentSaves } from "./projectStore";
+import { currentWriteEpoch } from "./undoStack";
import { useSequentialTimelineOps } from "./useSequentialTimelineOps";
// How long a region lasts when the caller doesn't say. The timeline's toolbar
@@ -713,26 +714,56 @@ export function useTimeline() {
saveDocument,
});
- // The zoom pane's one-field writes: level, 3D tilt, focus mode, cursor. Each is a
- // whole-document save, so they share one chain and read the document INSIDE it. The level
- // buttons step while the previous save is still out, and 3 -> 4 -> 5 built both saves from
- // the render's depth-3 document: the main process does not order them, so the 4 could land
- // last, and even in order one Ctrl+Z skipped a level. A neighbouring select changed while a
- // level was pending rebuilt from that same document and put 3 back. Resolves
+ // The zoom pane's one-field writes: level, 3D tilt, focus mode, cursor, click impact. Each
+ // is a whole-document save, so they share one chain and read the document INSIDE it. The
+ // level buttons step while the previous save is still out, and 3 -> 4 -> 5 built both saves
+ // from the render's depth-3 document: the main process does not order them, so the 4 could
+ // land last, and even in order one Ctrl+Z skipped a level. A neighbouring select changed
+ // while a level was pending rebuilt from that same document and put 3 back. Resolves
// `saveDocument`'s answer, so the level buttons can retry a failed write.
+ //
+ // Each request is bound to the project and write epoch it was asked against — the same
+ // pair `addAsset` samples: an undo bumps the epoch, a project switch swaps both, and a
+ // queued patch that only STARTS after such a replacement must not apply to the document
+ // that replaced its target. A save whose answer is unknown (`saveWithDeadline` timed out
+ // with the bridge still silent) may still land, so later zoom writes are refused until it
+ // settles instead of racing it — the same "a queued write racing a stuck one" the
+ // `waitForDocumentSaves` header calls out.
+ const unknownZoomSavesRef = useRef(0);
const saveZoomPatch = useCallback(
- (id: string, patch: Partial<AxcutDocument["zoomRanges"][number]>) =>
- enqueueZoomWrite(async () => {
+ (id: string, patch: Partial<AxcutDocument["zoomRanges"][number]>) => {
+ const epoch = currentWriteEpoch();
+ const projectId = useProjectStore.getState().projectId;
+ return enqueueZoomWrite(async () => {
+ if (useProjectStore.getState().projectId !== projectId || currentWriteEpoch() !== epoch) {
+ return false;
+ }
+ if (unknownZoomSavesRef.current > 0) return false;
const doc = useProjectStore.getState().document;
if (!doc) return false;
- return saveDocument(
+ const save = saveDocument(
{
...doc,
zoomRanges: patchPillById(doc.zoomRanges, id, patch) as AxcutDocument["zoomRanges"],
},
{ history: true },
);
- }),
+ const outcome = await saveWithDeadline(save);
+ if (outcome !== "timeout") return outcome === true;
+ // Unknown, not failed: the write may still land. Report not-taken (the
+ // buttons retry) and refuse later zoom writes until the save settles.
+ unknownZoomSavesRef.current += 1;
+ void save
+ .then(
+ () => undefined,
+ () => undefined,
+ )
+ .finally(() => {
+ unknownZoomSavesRef.current -= 1;
+ });
+ return false;
+ });
+ },
[enqueueZoomWrite, saveDocument],
);