From 79c115e0ff309a0e1bd015064a8310f000d08305 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Thu, 17 Sep 2026 02:09:18 +0800 Subject: [PATCH] fix(web): stop reactive proxies freezing tab persistence --- .../__tests__/browserAppStateStorage.spec.ts | 38 ++++++++++++++++++- .../src/lib/backend/browserAppStateStorage.ts | 37 +++++++++++++++--- 2 files changed, 68 insertions(+), 7 deletions(-) diff --git a/apps/desktop/src/lib/backend/__tests__/browserAppStateStorage.spec.ts b/apps/desktop/src/lib/backend/__tests__/browserAppStateStorage.spec.ts index b3dab820da..7ba2e59323 100644 --- a/apps/desktop/src/lib/backend/__tests__/browserAppStateStorage.spec.ts +++ b/apps/desktop/src/lib/backend/__tests__/browserAppStateStorage.spec.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -function installIndexedDb(transactionOutcome: "complete" | "abort") { +function installIndexedDb(transactionOutcome: "complete" | "abort", capturedPuts?: unknown[]) { const transaction: Record = { error: null, oncomplete: null, @@ -8,7 +8,8 @@ function installIndexedDb(transactionOutcome: "complete" | "abort") { onerror: null, }; const store = { - put(_value: unknown, key: IDBValidKey) { + put(value: unknown, key: IDBValidKey) { + capturedPuts?.push(value); const request: Record = { result: undefined, error: null, onsuccess: null, onerror: null }; queueMicrotask(() => { request.result = key; @@ -57,6 +58,7 @@ describe("saveBrowserAppState", () => { it("waits for transaction commit and falls back after an IndexedDB abort", async () => { installIndexedDb("abort"); installLocalStorage(() => undefined); + vi.spyOn(console, "warn").mockImplementation(() => undefined); const { saveBrowserAppState } = await import("@/lib/backend/browserAppStateStorage"); await expect(saveBrowserAppState("transfer_task_library", { version: 1 })).resolves.toBeUndefined(); @@ -64,6 +66,38 @@ describe("saveBrowserAppState", () => { expect(globalThis.localStorage.setItem).toHaveBeenCalledWith("dbx-app-state:transfer_task_library", JSON.stringify({ version: 1 })); }); + it("normalizes reactive proxies so IndexedDB structured clone cannot reject the put", async () => { + const captured: unknown[] = []; + installIndexedDb("complete", captured); + installLocalStorage(() => undefined); + vi.spyOn(console, "warn").mockImplementation(() => undefined); + const { saveBrowserAppState } = await import("@/lib/backend/browserAppStateStorage"); + + // Vue reactive objects are proxies; structured clone (IndexedDB's put + // serialization) rejects them wholesale with a DataCloneError. + const reactiveSelection = new Proxy({ anchor: 3, head: 7 }, {}); + expect(() => structuredClone(reactiveSelection)).toThrow(); + + await expect( + saveBrowserAppState("open_tabs", { + tabs: [{ id: "t1", sql: "SELECT 1", editorSelection: reactiveSelection, untouched: undefined }], + }), + ).resolves.toBeUndefined(); + + expect(captured).toHaveLength(1); + // The stored value must itself be structured-cloneable. + expect(() => structuredClone(captured[0])).not.toThrow(); + const storedTabs = (captured[0] as { tabs: Array> }).tabs; + expect(storedTabs[0].editorSelection).toEqual({ anchor: 3, head: 7 }); + // Undefined fields drop out, matching the localStorage fallback's JSON + // representation exactly. + expect("untouched" in storedTabs[0]).toBe(false); + // A successful IndexedDB write clears any stale fallback copy instead of + // leaving an older localStorage value that a future load could resurrect. + expect(globalThis.localStorage.removeItem).toHaveBeenCalledWith("dbx-app-state:open_tabs"); + expect(globalThis.localStorage.setItem).not.toHaveBeenCalled(); + }); + it("throws when localStorage quota prevents the fallback write", async () => { vi.stubGlobal("indexedDB", undefined); installLocalStorage(() => { diff --git a/apps/desktop/src/lib/backend/browserAppStateStorage.ts b/apps/desktop/src/lib/backend/browserAppStateStorage.ts index ad474cd541..0a94b29dc0 100644 --- a/apps/desktop/src/lib/backend/browserAppStateStorage.ts +++ b/apps/desktop/src/lib/backend/browserAppStateStorage.ts @@ -1,4 +1,4 @@ -import { safeLocalStorageGet, safeLocalStorageSet } from "@/lib/backend/safeStorage"; +import { safeLocalStorageGet, safeLocalStorageRemove, safeLocalStorageSet } from "@/lib/backend/safeStorage"; const DB_NAME = "dbx-app-state"; const DB_VERSION = 1; @@ -59,7 +59,12 @@ async function withStore(mode: IDBTransactionMode, run: (store: IDBObjectStor return result; } return await request; - } catch { + } catch (error) { + // Never fully silent: a persistent failure here degrades every save to the + // localStorage fallback while loads keep preferring the stale IndexedDB + // snapshot — exactly the workspace-freeze regression this module guards + // against elsewhere. + console.warn("[DBX][browserAppStateStorage] IndexedDB operation failed; falling back to localStorage", error); return null; } } @@ -77,9 +82,31 @@ export async function loadBrowserAppState(key: string): Promise } } +/** + * Values handed to this module frequently come straight out of reactive stores + * (open tabs carry reactive editor selection/viewport objects, editor settings + * are store objects). IndexedDB's structured clone rejects Vue reactive + * proxies with a DataCloneError, which used to silently degrade every save to + * the localStorage fallback while loadBrowserAppState kept preferring the + * stale IndexedDB snapshot — freezing workspace persistence in web mode after + * the first cursor move. JSON round-tripping yields the exact plain + * representation the fallback already stores (proxies unwrapped, undefined + * fields dropped), keeping both copies equivalent. + */ +function toStorableValue(value: unknown): unknown { + return JSON.parse(JSON.stringify(value)); +} + export async function saveBrowserAppState(key: string, value: unknown): Promise { - const result = await withStore("readwrite", (store) => store.put(value, key)); - if (result !== null) return; - if (safeLocalStorageSet(fallbackKey(key), JSON.stringify(value))) return; + const stored = toStorableValue(value); + const result = await withStore("readwrite", (store) => store.put(stored, key)); + if (result !== null) { + // Drop any fallback copy left behind by an earlier failed save: it is now + // older than the IndexedDB value and must never be resurrected by a future + // load that cannot reach IndexedDB. + safeLocalStorageRemove(fallbackKey(key)); + return; + } + if (safeLocalStorageSet(fallbackKey(key), JSON.stringify(stored))) return; throw new Error(`Failed to persist browser app state: ${key}`); }