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 the save-failure boundary where every save already goes

EtienneLescotc5afdd11642f
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index a3f09a9ab..b28f8558e 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -14,7 +14,6 @@ import {
} from "@/lib/ai-edition/document/timeline";
import { type AxcutClip, documentSchema } from "@/lib/ai-edition/schema";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
-import { saveTimelineMutation } from "@/lib/ai-edition/store/timelineSave";
import {
useAssetTranscriptions,
useAutoTranscription,
@@ -303,15 +302,9 @@ export function NewEditorShell() {
// 3. Handle request-save-before-close from Electron
const unsubSaveBeforeClose = window.electronAPI.onRequestSaveBeforeClose(async () => {
const doc = useProjectStore.getState().document;
- if (doc) {
- try {
- await saveDocument(doc);
- return true;
- } catch {
- toast.error("Failed to save before closing");
- return false;
- }
- }
+ // The store already toasted the reason; answering false is what keeps the
+ // window open on top of it.
+ if (doc) return await saveDocument(doc);
return true;
});
@@ -345,7 +338,6 @@ export function NewEditorShell() {
// stale-closure bugs.
const known = Number.isFinite(durationSec) && durationSec > 0 ? durationSec : 60;
const state = useProjectStore.getState();
- const persist = state.saveDocument;
setSourceDuration(known);
const doc = state.document;
if (!doc || doc.assets.length === 0) return;
@@ -368,7 +360,7 @@ export function NewEditorShell() {
[{ startSec: 0, endSec: known }],
"Auto-created full-duration clip",
);
- void saveTimelineMutation(persist, next);
+ void state.saveDocument(next);
return;
}
// Hand the probed duration to the pure document layer: it patches only the
@@ -379,7 +371,7 @@ export function NewEditorShell() {
// nothing is waiting, so there is nothing to guard here.
const next = applyProbedDuration(doc, assetId, known);
if (next !== doc) {
- void saveTimelineMutation(persist, next);
+ void state.saveDocument(next);
}
},
[setSourceDuration],
@@ -620,14 +612,7 @@ export function NewEditorShell() {
const handleSave = useCallback(async () => {
const doc = useProjectStore.getState().document;
if (!doc) return;
- try {
- await saveDocument(doc);
- toast.success("Project saved");
- } catch (err) {
- toast.error("Save failed", {
- description: err instanceof Error ? err.message : String(err),
- });
- }
+ if (await saveDocument(doc)) toast.success("Project saved");
}, [saveDocument]);
// Native File menu (electron/main.ts) → v4 actions. The menu is shown via
@@ -655,13 +640,7 @@ export function NewEditorShell() {
const doc = useProjectStore.getState().document;
if (!doc) return;
if (title === doc.project.title) return;
- try {
- await saveDocument({ ...doc, project: { ...doc.project, title } });
- } catch (err) {
- toast.error("Rename failed", {
- description: err instanceof Error ? err.message : String(err),
- });
- }
+ await saveDocument({ ...doc, project: { ...doc.project, title } });
},
[saveDocument],
);
@@ -682,13 +661,12 @@ export function NewEditorShell() {
}
if (choice === "save") {
const doc = useProjectStore.getState().document;
- if (doc) {
- try {
- await saveDocument(doc);
- } catch {
- resolve("cancel");
- return;
- }
+ // A failed save cancels the action that prompted this dialog. The store has
+ // already said why -- which is what the bare `catch {}` here used to swallow,
+ // leaving the window refusing to close with nothing on screen explaining it.
+ if (doc && !(await saveDocument(doc))) {
+ resolve("cancel");
+ return;
}
}
if (action === "record") {
@@ -847,13 +825,8 @@ export function NewEditorShell() {
if (choice === "cancel") return;
if (choice === "save") {
const doc = useProjectStore.getState().document;
- if (doc) {
- try {
- await saveDocument(doc);
- } catch {
- return;
- }
- }
+ // Stay put if the save did not land -- the store has already said why.
+ if (doc && !(await saveDocument(doc))) return;
}
setNewProjectOpen(true);
})();
@@ -866,13 +839,8 @@ export function NewEditorShell() {
if (choice === "cancel") return;
if (choice === "save") {
const doc = useProjectStore.getState().document;
- if (doc) {
- try {
- await saveDocument(doc);
- } catch {
- return;
- }
- }
+ // Stay put if the save did not land -- the store has already said why.
+ if (doc && !(await saveDocument(doc))) return;
}
setOpenProjectOpen(true);
})();
diff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsx
index 22b79aa8d..ba549180f 100644
--- a/src/components/ai-edition/v4/V4Timeline.tsx
+++ b/src/components/ai-edition/v4/V4Timeline.tsx
@@ -1059,6 +1059,10 @@ export function V4Timeline({
return;
}
const added = await tl.addZoomsBulk(suggestions);
+ // A failed write returns 0 and has already toasted why. Without this the user
+ // got "Added 0 automatic zooms" stacked on top of "Failed to save project",
+ // with no zoom anywhere -- a success message for something that did not happen.
+ if (added === 0) return;
toast.success(
t(added === 1 ? "toolbar.addedAutoZoom" : "toolbar.addedAutoZoomPlural", { count: added }),
);
diff --git a/src/lib/ai-edition/store/projectStore.test.ts b/src/lib/ai-edition/store/projectStore.test.ts
index 5483f2b88..7435eb733 100644
--- a/src/lib/ai-edition/store/projectStore.test.ts
+++ b/src/lib/ai-edition/store/projectStore.test.ts
@@ -297,6 +297,58 @@ describe("useProjectStore", () => {
expect(toastMocks.error.mock.calls[0][0]).toContain("video.mp4");
});
+ // The save boundary. Every write in the app funnels through `saveDocument`, and
+ // almost every caller `void`s it from a click handler, so what this function does
+ // with a failure IS what the user sees.
+ describe("saveDocument reports a failed write instead of rejecting", () => {
+ it("resolves false, tells the user, and leaves the document alone", async () => {
+ useProjectStore.setState({
+ projectId: "proj_test",
+ document: sampleDoc,
+ revision: 3,
+ status: "ready",
+ dirty: true,
+ });
+ bridgeMocks.save.mockResolvedValue({ success: false, error: "EACCES" });
+
+ const edited = { ...sampleDoc, project: { ...sampleDoc.project, title: "Edited" } };
+ await expect(useProjectStore.getState().saveDocument(edited)).resolves.toBe(false);
+
+ expect(toastMocks.error).toHaveBeenCalledWith("Failed to save project", {
+ description: "EACCES",
+ });
+ const state = useProjectStore.getState();
+ expect(state.document?.project.title).toBe("Test");
+ expect(state.revision).toBe(3);
+ // Still dirty: `dirty` is the only input to the beforeunload guard and to
+ // `setHasUnsavedChanges`, so a failed write is the last moment to claim clean.
+ expect(state.dirty).toBe(true);
+ });
+
+ it("never rejects, so a detached caller cannot leak an unhandled rejection", async () => {
+ useProjectStore.setState({ projectId: "proj_test", document: sampleDoc, dirty: true });
+ bridgeMocks.save.mockRejectedValue(new Error("bridge is gone"));
+
+ await expect(useProjectStore.getState().saveDocument(sampleDoc)).resolves.toBe(false);
+ expect(toastMocks.error).toHaveBeenCalledWith("Failed to save project", {
+ description: "bridge is gone",
+ });
+ });
+
+ it("resolves true and commits on success", async () => {
+ const saved = { ...sampleDoc, project: { ...sampleDoc.project, title: "Saved" } };
+ useProjectStore.setState({ projectId: "proj_test", document: sampleDoc, dirty: true });
+ bridgeMocks.save.mockResolvedValue({ success: true, document: saved });
+
+ await expect(useProjectStore.getState().saveDocument(saved)).resolves.toBe(true);
+
+ expect(toastMocks.error).not.toHaveBeenCalled();
+ const state = useProjectStore.getState();
+ expect(state.document?.project.title).toBe("Saved");
+ expect(state.dirty).toBe(false);
+ });
+ });
+
it("removeAsset requires a loaded project", async () => {
await expect(useProjectStore.getState().removeAsset("asset_x")).rejects.toThrow(
"No project loaded",
diff --git a/src/lib/ai-edition/store/projectStore.ts b/src/lib/ai-edition/store/projectStore.ts
index 539449dab..60b42e767 100644
--- a/src/lib/ai-edition/store/projectStore.ts
+++ b/src/lib/ai-edition/store/projectStore.ts
@@ -1,4 +1,6 @@
+import { toast } from "sonner";
import { create } from "zustand";
+import { toastText } from "@/i18n/toastText";
import { nativeBridgeClient } from "@/native/client";
import {
type Interval,
@@ -36,7 +38,17 @@ export interface ProjectState {
refresh: () => Promise<void>;
addAsset: (path: string, label?: string) => Promise<AxcutAsset | null>;
removeAsset: (assetId: string) => Promise<void>;
- saveDocument: (document: AxcutDocument) => Promise<void>;
+ /**
+ * Write the document to disk. Resolves `true` when it landed, `false` when it did
+ * not -- and a `false` has ALREADY been reported to the user and logged, so a
+ * caller that ignores it is choosing not to react, not choosing to stay silent.
+ *
+ * It never rejects, by design. Every save in the app funnels through here and
+ * almost all of them are `void`-ed from a click handler, so a rejection here was
+ * 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;
replaceTimeline: (intervals: Interval[], reason: string) => Promise<void>;
restoreFullTimeline: () => Promise<void>;
@@ -169,8 +181,10 @@ export const useProjectStore = create<ProjectState>((set, get) => ({
a.id === addedAsset.id ? { ...a, cameraTrack: linked } : a,
),
};
- await get().saveDocument(next);
- document = parseDocument(next);
+ // 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);
}
// success:false just means no camera was found for this asset —
// the normal case for a plain imported video. Nothing to surface.
@@ -212,17 +226,32 @@ export const useProjectStore = create<ProjectState>((set, get) => ({
},
async saveDocument(document) {
- const result = await nativeBridgeClient.aiEdition.save(document);
- if (!result.success || !result.document) {
- throw new Error(result.error ?? "Failed to save project");
+ try {
+ const result = await nativeBridgeClient.aiEdition.save(document);
+ if (!result.success || !result.document) {
+ throw new Error(result.error ?? "Failed to save project");
+ }
+ const parsed = parseDocument(result.document);
+ set({
+ document: parsed,
+ revision: get().revision + 1,
+ dirty: false,
+ lastSavedAt: new Date(),
+ });
+ return true;
+ } catch (error) {
+ // Logged as well as toasted: a toast is gone in five seconds, and "my edit
+ // disappeared" gets reported much later than that.
+ console.error("[project] failed to save document:", error);
+ toast.error(toastText("editor", "project.failedToSave"), {
+ description: error instanceof Error ? error.message : String(error),
+ });
+ // `dirty` is deliberately left alone. It is the only input to the
+ // `beforeunload` guard and to `setHasUnsavedChanges`, so clearing it here
+ // would let the window close without a prompt on the one path where there is
+ // definitely something unsaved.
+ return false;
}
- const parsed = parseDocument(result.document);
- set({
- document: parsed,
- revision: get().revision + 1,
- dirty: false,
- lastSavedAt: new Date(),
- });
},
setDocument(document) {
diff --git a/src/lib/ai-edition/store/timelineSave.ts b/src/lib/ai-edition/store/timelineSave.ts
deleted file mode 100644
index 075dcaf29..000000000
--- a/src/lib/ai-edition/store/timelineSave.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { toast } from "sonner";
-import type { AxcutDocument } from "../schema";
-
-type SaveDocument = (document: AxcutDocument) => Promise<unknown>;
-
-/**
- * Persist a user-initiated timeline mutation without letting a detached caller
- * turn a write failure into an unhandled rejection.
- */
-export async function saveTimelineMutation(
- saveDocument: SaveDocument,
- document: AxcutDocument,
-): Promise<boolean> {
- try {
- await saveDocument(document);
- return true;
- } catch (error) {
- console.error("[timeline] failed to save mutation:", error);
- toast.error("Save failed", {
- description: error instanceof Error ? error.message : String(error),
- });
- return false;
- }
-}
diff --git a/src/lib/ai-edition/store/useSequentialTimelineOps.test.ts b/src/lib/ai-edition/store/useSequentialTimelineOps.test.ts
index 4b85a62d5..91f69aac5 100644
--- a/src/lib/ai-edition/store/useSequentialTimelineOps.test.ts
+++ b/src/lib/ai-edition/store/useSequentialTimelineOps.test.ts
@@ -18,10 +18,6 @@ import { type AxcutDocument, createEmptyDocument } from "@/lib/ai-edition/schema
import { useProjectStore } from "./projectStore";
import { useSequentialTimelineOps } from "./useSequentialTimelineOps";
-const toastErrorMock = vi.hoisted(() => vi.fn());
-
-vi.mock("sonner", () => ({ toast: { error: toastErrorMock } }));
-
function makeDocWithAsset(): AxcutDocument {
const base = createEmptyDocument({ projectId: "proj_seq", title: "seq" });
return {
@@ -59,7 +55,6 @@ function makeDocWithAsset(): AxcutDocument {
beforeEach(() => {
useProjectStore.getState().clear();
- toastErrorMock.mockReset();
});
afterEach(() => {
@@ -74,10 +69,11 @@ describe("useSequentialTimelineOps", () => {
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.
+ // call in the queue sees the latest committed state, and report
+ // success the way `projectStore.saveDocument` does.
useProjectStore.getState().setDocument(doc);
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
callOrder.push(doc.timeline.trimRanges[0]?.startSec.toString() ?? "empty");
+ return true;
});
const { result } = renderHook(() =>
@@ -117,15 +113,20 @@ describe("useSequentialTimelineOps", () => {
expect(doc2.timeline.trimRanges.map((t) => t.startSec).sort()).toEqual([1, 5]);
});
- it("surfaces save errors without rejecting or poisoning the queue", async () => {
+ it("keeps the queue healthy when a save reports failure", async () => {
+ // `projectStore.saveDocument` resolves false rather than rejecting -- it has
+ // already told the user why. What this hook owes is that the failed op resolves
+ // to null and the NEXT op still runs, off a document that never took the failed
+ // edit.
const seed = makeDocWithAsset();
useProjectStore.setState({ document: seed });
const saveDocument = vi
- .fn<(doc: AxcutDocument) => Promise<void>>()
- .mockRejectedValueOnce(new Error("save failed"))
+ .fn<(doc: AxcutDocument) => Promise<boolean>>()
+ .mockResolvedValueOnce(false)
.mockImplementationOnce(async (doc) => {
useProjectStore.getState().setDocument(doc);
+ return true;
});
const { result } = renderHook(() =>
@@ -156,16 +157,13 @@ describe("useSequentialTimelineOps", () => {
expect(firstResult).toBeNull();
expect(secondResult).not.toBeNull();
- expect(toastErrorMock).toHaveBeenCalledWith("Save failed", {
- description: "save failed",
- });
// The queue survived the first failure — both saves were attempted.
expect(saveDocument).toHaveBeenCalledTimes(2);
expect(saveDocument).toHaveBeenNthCalledWith(2, secondResult);
});
it("returns null when the store has no document and no fallback is supplied", async () => {
- const saveDocument = vi.fn(async () => undefined);
+ const saveDocument = vi.fn(async () => true);
const { result } = renderHook(() =>
useSequentialTimelineOps({ fallbackDocument: null, saveDocument }),
);
@@ -194,6 +192,7 @@ describe("useSequentialTimelineOps", () => {
const saveDocument = vi.fn(async (doc: AxcutDocument) => {
useProjectStore.getState().setDocument(doc);
+ return true;
});
const { result } = renderHook(() =>
diff --git a/src/lib/ai-edition/store/useSequentialTimelineOps.ts b/src/lib/ai-edition/store/useSequentialTimelineOps.ts
index c9c25383f..0bcdd842f 100644
--- a/src/lib/ai-edition/store/useSequentialTimelineOps.ts
+++ b/src/lib/ai-edition/store/useSequentialTimelineOps.ts
@@ -7,15 +7,16 @@
// read the doc INSIDE the chain, after awaiting the previous save, so
// every call sees the doc state the previous call committed.
//
-// Save failures are surfaced once by the shared mutation boundary and resolve
-// to null. This keeps detached UI calls from emitting unhandled rejections and
-// also leaves the queue healthy for the next edit.
+// A failed save resolves to null rather than rejecting -- `projectStore.saveDocument`
+// reports it to the user and returns false. Operation and dynamic-import errors still
+// 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.
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";
-import { saveTimelineMutation } from "./timelineSave";
export interface SequentialTimelineOps {
/**
@@ -24,8 +25,11 @@ export interface SequentialTimelineOps {
* 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) or the save fails.
+ * Returns the saved document, or `null` for either of two different things:
+ * no project document is loaded (store empty AND no fallback supplied), which
+ * is a silent no-op, or the save failed, which the user has already been told
+ * about. Both call sites `void` the result, so they are not distinguished; a
+ * caller that needs to tell them apart has to widen this return type first.
*/
apply: (op: AxcutTimelineOperation) => Promise<AxcutDocument | null>;
}
@@ -33,8 +37,9 @@ export interface SequentialTimelineOps {
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>;
+ /** Persist a document, resolving false if the write failed (already reported).
+ * The hook awaits this before unblocking the queue. */
+ saveDocument: (doc: AxcutDocument) => Promise<boolean>;
}): SequentialTimelineOps {
const { fallbackDocument, saveDocument } = options;
const saveQueueRef = useRef<Promise<unknown>>(Promise.resolve());
@@ -51,11 +56,10 @@ export function useSequentialTimelineOps(options: {
const doc = useProjectStore.getState().document ?? fallbackDocument;
if (!doc) return null;
const applied = applyTimelineOperation(doc, op);
- const saved = await saveTimelineMutation(saveDocument, applied.document);
- return saved ? applied.document : null;
+ return (await saveDocument(applied.document)) ? applied.document : null;
});
- // Keep operation/import errors from poisoning the queue. Save
- // failures already resolve to null after showing user feedback.
+ // 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,
diff --git a/src/lib/ai-edition/store/useTimeline.test.ts b/src/lib/ai-edition/store/useTimeline.test.ts
index 52f39d5e0..cc51b3a01 100644
--- a/src/lib/ai-edition/store/useTimeline.test.ts
+++ b/src/lib/ai-edition/store/useTimeline.test.ts
@@ -568,15 +568,44 @@ describe("useTimeline zoom modifiers (rotation + focus mode)", () => {
cx: 0.5,
cy: 0.5,
});
- expect(useProjectStore.getState().dirty).toBe(false);
+ // Still dirty, deliberately. The rollback target is the document this drag
+ // started from, not the last SAVED one, so claiming "clean" would let the window
+ // close on unsaved work without a prompt.
+ expect(useProjectStore.getState().dirty).toBe(true);
// The live edit advanced revision once; restoring a different document
// advances it again so async work cannot mistake the rollback for the
// optimistic document it replaced.
expect(useProjectStore.getState().revision).toBe(3);
- expect(toastErrorMock).toHaveBeenCalledWith("Save failed", {
+ expect(toastErrorMock).toHaveBeenCalledWith("Failed to save project", {
description: "project file locked",
});
});
+
+ it("does not restore another project's document after the project changed", async () => {
+ // A drag does not always end in a commit: `ZoomFocusOverlay` unmounts the instant
+ // `focusMode` flips to "auto", so `endDrag` never runs and the snapshot outlives
+ // the project. Restoring it into the NEXT project put project A's document in
+ // project B, and the following successful save wrote A over B on disk.
+ const { result, rerender } = renderTimeline();
+
+ act(() => result.current.updateZoomFocusLive("zoom_a", { cx: 0.8, cy: 0.2 }));
+
+ const otherProjectDoc: AxcutDocument = {
+ ...docWithZoom,
+ project: { ...docWithZoom.project, id: "proj_other", title: "Other" },
+ };
+ act(() => {
+ useProjectStore.setState({ projectId: "proj_other", document: otherProjectDoc });
+ });
+ rerender();
+
+ bridgeMocks.save.mockResolvedValueOnce({ success: false, error: "project file locked" });
+ await act(async () => {
+ await result.current.commitZoomFocus();
+ });
+
+ expect(useProjectStore.getState().document?.project.id).toBe("proj_other");
+ });
});
// Regression guard for the playhead-stutter fix. `currentTimeSec` is rewritten on
@@ -702,6 +731,10 @@ describe("useTimeline selection", () => {
});
describe("useTimeline save failures", () => {
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
beforeEach(() => {
useProjectStore.getState().clear();
for (const mock of Object.values(bridgeMocks)) mock.mockReset();
@@ -723,10 +756,28 @@ describe("useTimeline save failures", () => {
await expect(result.current.removeClip("clip_a")).resolves.toBeUndefined();
});
- expect(toastErrorMock).toHaveBeenCalledWith("Save failed", {
+ expect(toastErrorMock).toHaveBeenCalledWith("Failed to save project", {
description: "disk full",
});
expect(useProjectStore.getState().document?.timeline.clips).toHaveLength(1);
expect(useProjectStore.getState().document?.timeline.clips[0]?.id).toBe("clip_a");
});
+
+ it("reports 0 zooms added when the bulk write fails", async () => {
+ // The count is what the Auto-enhance caller shows in its success toast, so a
+ // failed write returning `suggestions.length` produced "Added 3 automatic zooms"
+ // stacked on "Failed to save project", with no zoom anywhere. The caller guards
+ // on this 0 (`V4Timeline` runAutoZooms).
+ const { result } = renderTimeline();
+
+ let added: number | undefined;
+ await act(async () => {
+ added = await result.current.addZoomsBulk([
+ { span: { start: 1000, end: 2000 }, focus: { cx: 0.5, cy: 0.5 } },
+ ]);
+ });
+
+ expect(added).toBe(0);
+ expect(useProjectStore.getState().document?.zoomRanges).toHaveLength(0);
+ });
});
diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.ts
index 98038eca2..f921a9917 100644
--- a/src/lib/ai-edition/store/useTimeline.ts
+++ b/src/lib/ai-edition/store/useTimeline.ts
@@ -30,7 +30,6 @@ import {
import { dropTrimPillsByIds, resolveTimelineSpanToTrim } from "../timeline/trim-mapping";
import type { AutoZoomSuggestion } from "../timeline/zoom-suggestions";
import { useProjectStore } from "./projectStore";
-import { saveTimelineMutation } from "./timelineSave";
// How long a region lasts when the caller doesn't say. The timeline's toolbar
// passes its own duration instead, derived from the current zoom so the new pill
@@ -97,11 +96,7 @@ export function useTimeline() {
const ts = useScopedT("settings");
const document = useProjectStore((s) => s.document);
const projectId = useProjectStore((s) => s.projectId);
- const saveProjectDocument = useProjectStore((s) => s.saveDocument);
- const saveDocument = useCallback(
- (document: AxcutDocument) => saveTimelineMutation(saveProjectDocument, document),
- [saveProjectDocument],
- );
+ const saveDocument = useProjectStore((s) => s.saveDocument);
const setDocument = useProjectStore((s) => s.setDocument);
const [selection, setSelection] = useState<RegionHandle | null>(null);
// F2.7 — shift-click multi-selection. `selection` stays the inspector's
@@ -109,11 +104,28 @@ export function useTimeline() {
// the Delete key operates on.
const [multiSelection, setMultiSelection] = useState<RegionHandle[]>([]);
const [clipSelection, setClipSelection] = useState<string | null>(null);
+ // Pre-drag snapshots for the two optimistic paths (zoom focus, annotations), so a
+ // failed commit can put the document back instead of leaving an edit on screen that
+ // was never written.
const zoomFocusRollbackRef = useRef<AxcutDocument | null>(null);
const zoomFocusLiveRef = useRef<AxcutDocument | null>(null);
const annotationRollbackRef = useRef<AxcutDocument | null>(null);
const annotationLiveRef = useRef<AxcutDocument | null>(null);
+ // A drag does not always end in a commit: `ZoomFocusOverlay` unmounts the moment
+ // `focusMode` flips to "auto", so `endDrag` never runs and the snapshot outlives the
+ // project. Left alone, resetting focus in project B and failing that save restored
+ // project A's document into B -- the next successful save then wrote A over B. It
+ // also pinned two whole documents per hook instance, and annotations can carry
+ // base64 image data URLs.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: projectId is the trigger, not a read — the body only clears refs.
+ useEffect(() => {
+ zoomFocusRollbackRef.current = null;
+ zoomFocusLiveRef.current = null;
+ annotationRollbackRef.current = null;
+ annotationLiveRef.current = null;
+ }, [projectId]);
+
const hasDoc = document !== null && projectId !== null;
// Backfill missing source dimensions for any USED asset whose `video` was never probed.
@@ -517,9 +529,12 @@ export function useTimeline() {
zoomFocusLiveRef.current = null;
if (!(await saveDocument(doc)) && rollback) {
useProjectStore.setState((state) =>
- state.document === doc
- ? { document: rollback, revision: state.revision + 1, dirty: false }
- : {},
+ // `dirty` is deliberately NOT cleared. The rollback target is the last document
+ // this drag started from, which is not the same as the last SAVED one: with two
+ // commits in flight the first one's unsaved document is what we restore. Saying
+ // "clean" there tells `beforeunload` and `setHasUnsavedChanges` there is nothing
+ // to save, and the window closes on real work without prompting.
+ state.document === doc ? { document: rollback, revision: state.revision + 1 } : {},
);
}
}, [saveDocument]);
@@ -629,9 +644,12 @@ export function useTimeline() {
annotationLiveRef.current = null;
if (!(await saveDocument(doc)) && rollback) {
useProjectStore.setState((state) =>
- state.document === doc
- ? { document: rollback, revision: state.revision + 1, dirty: false }
- : {},
+ // `dirty` is deliberately NOT cleared. The rollback target is the last document
+ // this drag started from, which is not the same as the last SAVED one: with two
+ // commits in flight the first one's unsaved document is what we restore. Saying
+ // "clean" there tells `beforeunload` and `setHasUnsavedChanges` there is nothing
+ // to save, and the window closes on real work without prompting.
+ state.document === doc ? { document: rollback, revision: state.revision + 1 } : {},
);
}
}, [saveDocument]);