Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-9272 fix(settings): preserve reverted drafts during autosave (#10600)

沙雕的小鱼儿 boyfeiyu632fd482a118
diff --git a/packages/views/settings/components/use-auto-save.test.tsx b/packages/views/settings/components/use-auto-save.test.tsx
index 55ea0f16db..49dea7b199 100644
--- a/packages/views/settings/components/use-auto-save.test.tsx
+++ b/packages/views/settings/components/use-auto-save.test.tsx
@@ -1,5 +1,5 @@
import { StrictMode } from "react";
-import { act, render, waitFor } from "@testing-library/react";
+import { act, render, renderHook, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { useAutoSave } from "./use-auto-save";
@@ -101,3 +101,199 @@ describe("useAutoSave success feedback", () => {
expect(onSuccess).toHaveBeenCalledTimes(1);
});
});
+
+const equalStrings = (left: string, right: string) => left === right;
+
+describe("useAutoSave reverted drafts", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ function setup() {
+ vi.useFakeTimers();
+ const first = deferred<void>();
+ const second = deferred<void>();
+ const onSave = vi
+ .fn<(value: string) => Promise<void>>()
+ .mockReturnValueOnce(first.promise)
+ .mockReturnValueOnce(second.promise);
+ const onSuccess = vi.fn();
+ const onError = vi.fn();
+ const hook = renderHook(
+ ({ value, enabled, savedValue }) =>
+ useAutoSave({
+ value,
+ savedValue,
+ enabled,
+ onSave,
+ onSuccess,
+ onError,
+ isEqual: equalStrings,
+ }),
+ { initialProps: { value: "A", enabled: true, savedValue: "A" } },
+ );
+ const edit = (value: string) =>
+ hook.rerender({ value, enabled: true, savedValue: "A" });
+ edit("B");
+ act(() => hook.result.current.flush());
+ expect(onSave).toHaveBeenCalledExactlyOnceWith("B");
+ return { ...hook, edit, first, second, onSave, onSuccess, onError };
+ }
+
+ it.each(["blur", "debounce"])(
+ "persists a revert to the original value through %s",
+ async (trigger) => {
+ const hook = setup();
+ hook.edit("A");
+ act(() => {
+ if (trigger === "blur") hook.result.current.flush();
+ else vi.advanceTimersByTime(650);
+ });
+ expect(hook.onSave).toHaveBeenCalledTimes(1);
+ await act(async () => hook.first.resolve());
+ expect(hook.onSave.mock.calls).toEqual([["B"], ["A"]]);
+ expect(hook.result.current.status).toBe("saving");
+ expect(hook.onSuccess).not.toHaveBeenCalled();
+ await act(async () => hook.second.resolve());
+ expect(hook.result.current.status).toBe("saved");
+ expect(hook.onSuccess).toHaveBeenCalledExactlyOnceWith("A");
+ },
+ );
+
+ it("replaces an already queued draft with the latest revert", async () => {
+ const hook = setup();
+ hook.edit("C");
+ act(() => hook.result.current.flush());
+ hook.edit("A");
+ await act(async () => hook.first.resolve());
+ expect(hook.onSave.mock.calls).toEqual([["B"], ["A"]]);
+ await act(async () => hook.second.resolve());
+ expect(hook.onSuccess).toHaveBeenCalledExactlyOnceWith("A");
+ });
+
+ it("keeps success pending until a still-debouncing revert is saved", async () => {
+ const hook = setup();
+ hook.edit("A");
+ act(() => vi.advanceTimersByTime(649));
+ await act(async () => hook.first.resolve());
+ expect(hook.onSave).toHaveBeenCalledTimes(1);
+ expect(hook.onSuccess).not.toHaveBeenCalled();
+ expect(hook.result.current.status).toBe("saving");
+ act(() => vi.advanceTimersByTime(1));
+ expect(hook.onSave.mock.calls).toEqual([["B"], ["A"]]);
+ await act(async () => hook.second.resolve());
+ expect(hook.onSuccess).toHaveBeenCalledExactlyOnceWith("A");
+ });
+
+ it("avoids a redundant correction when the earlier request fails", async () => {
+ const hook = setup();
+ hook.edit("A");
+ act(() => hook.result.current.flush());
+ const error = new Error("Save rejected");
+ await act(async () => hook.first.reject(error));
+ expect(hook.onSave).toHaveBeenCalledTimes(1);
+ expect(hook.onSuccess).not.toHaveBeenCalled();
+ expect(hook.onError).toHaveBeenCalledExactlyOnceWith(error);
+ expect(hook.result.current.status).toBe("error");
+ });
+
+ it("honors permission revocation before draining a queued revert", async () => {
+ const hook = setup();
+ hook.edit("A");
+ act(() => hook.result.current.flush());
+ hook.rerender({ value: "A", enabled: false, savedValue: "A" });
+ await act(async () => hook.first.resolve());
+ expect(hook.onSave).toHaveBeenCalledTimes(1);
+ expect(hook.onSuccess).not.toHaveBeenCalled();
+ expect(hook.result.current.status).toBe("idle");
+ });
+
+ it("cancels pending debounce and success feedback on unmount", async () => {
+ const hook = setup();
+ hook.edit("A");
+ hook.unmount();
+ await act(async () => hook.first.resolve());
+ act(() => vi.advanceTimersByTime(650));
+ expect(hook.onSave).toHaveBeenCalledTimes(1);
+ expect(hook.onSuccess).not.toHaveBeenCalled();
+ });
+
+ it("persists a draft queued by blur after unmount without success feedback", async () => {
+ const hook = setup();
+ hook.edit("BC");
+ act(() => hook.result.current.flush());
+ expect(hook.onSave).toHaveBeenCalledExactlyOnceWith("B");
+
+ hook.unmount();
+ await act(async () => hook.first.resolve());
+ expect(hook.onSave.mock.calls).toEqual([["B"], ["BC"]]);
+
+ await act(async () => hook.second.resolve());
+ expect(hook.onSuccess).not.toHaveBeenCalled();
+ });
+
+ it("persists an empty reverted draft after the in-flight write", async () => {
+ vi.useFakeTimers();
+ const first = deferred<void>();
+ const second = deferred<void>();
+ const onSave = vi
+ .fn<(value: string) => Promise<void>>()
+ .mockReturnValueOnce(first.promise)
+ .mockReturnValueOnce(second.promise);
+ const hook = renderHook(
+ ({ value }) =>
+ useAutoSave({
+ value,
+ savedValue: "",
+ onSave,
+ isEqual: equalStrings,
+ }),
+ { initialProps: { value: "" } },
+ );
+ hook.rerender({ value: "B" });
+ act(() => hook.result.current.flush());
+ hook.rerender({ value: "" });
+ act(() => hook.result.current.flush());
+ await act(async () => first.resolve());
+ expect(onSave.mock.calls).toEqual([["B"], [""]]);
+ await act(async () => second.resolve());
+ expect(hook.result.current.status).toBe("saved");
+ });
+
+ it("keeps an unchanged confirmed value idle without issuing requests", () => {
+ vi.useFakeTimers();
+ const onSave = vi.fn(async () => undefined);
+ const hook = renderHook(() =>
+ useAutoSave({
+ value: "A",
+ savedValue: "A",
+ onSave,
+ isEqual: equalStrings,
+ }),
+ );
+ act(() => {
+ hook.result.current.flush();
+ vi.advanceTimersByTime(650);
+ });
+ expect(onSave).not.toHaveBeenCalled();
+ expect(hook.result.current.status).toBe("idle");
+ });
+
+ it("accepts externally confirmed saved values without writing them back", () => {
+ vi.useFakeTimers();
+ const onSave = vi.fn(async () => undefined);
+ const hook = renderHook(
+ ({ value }) =>
+ useAutoSave({
+ value,
+ savedValue: value,
+ onSave,
+ isEqual: equalStrings,
+ }),
+ { initialProps: { value: "A" } },
+ );
+ hook.rerender({ value: "B" });
+ act(() => vi.advanceTimersByTime(650));
+ expect(onSave).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/settings/components/use-auto-save.ts b/packages/views/settings/components/use-auto-save.ts
index a8656213de..bfa5964f41 100644
--- a/packages/views/settings/components/use-auto-save.ts
+++ b/packages/views/settings/components/use-auto-save.ts
@@ -39,7 +39,7 @@ export function useAutoSave<T>({
const mountedRef = useRef(true);
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const savingRef = useRef(false);
- const queuedRef = useRef<T | null>(null);
+ const queuedRef = useRef<{ value: T } | null>(null);
const latestValueRef = useRef(value);
const persistedRef = useRef(savedValue);
const observedSavedRef = useRef(savedValue);
@@ -62,14 +62,16 @@ export function useAutoSave<T>({
}
const runSave = useCallback(async (next: T) => {
- if (!enabledRef.current || isEqualRef.current(next, persistedRef.current)) {
+ if (!enabledRef.current) {
return;
}
if (savingRef.current) {
- queuedRef.current = next;
+ queuedRef.current = { value: next };
return;
}
+ if (isEqualRef.current(next, persistedRef.current)) return;
+
savingRef.current = true;
let succeeded = false;
if (mountedRef.current) setStatus("saving");
@@ -84,9 +86,14 @@ export function useAutoSave<T>({
savingRef.current = false;
const queued = queuedRef.current;
queuedRef.current = null;
- if (queued && !isEqualRef.current(queued, persistedRef.current)) {
- void runSave(queued);
- } else if (succeeded && mountedRef.current) {
+ if (queued && !isEqualRef.current(queued.value, persistedRef.current)) {
+ void runSave(queued.value);
+ } else if (
+ succeeded &&
+ mountedRef.current &&
+ enabledRef.current &&
+ isEqualRef.current(next, latestValueRef.current)
+ ) {
setStatus("saved");
onSuccessRef.current?.(next);
}
@@ -111,12 +118,18 @@ export function useAutoSave<T>({
useEffect(() => {
if (timerRef.current) clearTimeout(timerRef.current);
- if (!enabled || isEqual(value, persistedRef.current)) {
+ if (!enabled) queuedRef.current = null;
+ if (!enabled || (!savingRef.current && isEqual(value, persistedRef.current))) {
timerRef.current = null;
if (!enabled) setStatus("idle");
return;
}
+ // A ready queue must follow edits even when they match the old saved value.
+ if (savingRef.current && queuedRef.current) {
+ queuedRef.current = { value };
+ }
+
setStatus("saving");
timerRef.current = setTimeout(() => {
timerRef.current = null;