Skip to content
TypeScript

perf(web): defer composer draft serialization (#9695)

Theo Brownedab5f6e6e02e
diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts
index 1310c1e9289..8e7934a2121 100644
--- a/apps/web/src/composerDraftStore.test.ts
+++ b/apps/web/src/composerDraftStore.test.ts
@@ -75,6 +75,7 @@ import {
type ComposerFileAttachment,
type ComposerImageAttachment,
composerFileNeedsReattach,
+ partializeComposerDraftStoreState,
useComposerDraftStore,
DraftId,
} from "./composerDraftStore";
@@ -84,7 +85,7 @@ import {
insertInlineTerminalContextPlaceholder,
type TerminalContextDraft,
} from "./lib/terminalContext";
-import { createDebouncedStorage } from "./lib/storage";
+import { createDeferredStorage } from "./lib/storage";
function makeImage(input: {
id: string;
@@ -196,37 +197,42 @@ describe("composerDraftStore assistant citations", () => {
beforeEach(resetComposerDraftStore);
afterEach(resetComposerDraftStore);
- it("keeps quotes, comments, and remote source IDs through persistence and removes them on clear", () => {
- const threadId = ThreadId.make("citation-draft");
- const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
- const citation = {
- version: 1 as const,
- environmentId: EnvironmentId.make("remote-source"),
- threadId: ThreadId.make("source-thread"),
- messageId: MessageId.make("source-message"),
- text: "Preserve the selected text after reload.",
- comment: "Why is this important?\nPlease show an example.",
- start: 12,
- end: 52,
- prefix: "Before. ",
- suffix: " After.",
- };
- const prompt = `Explain ${serializeAssistantCitation(citation)} further.`;
- useComposerDraftStore.getState().setPrompt(threadRef, prompt);
- const options = useComposerDraftStore.persist.getOptions();
- const saved = JSON.parse(
- JSON.stringify(options.partialize!(useComposerDraftStore.getState())),
- ) as unknown;
- resetComposerDraftStore();
- const hydrated = options.merge!(saved, useComposerDraftStore.getState());
- useComposerDraftStore.setState(hydrated);
- const restored = draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt ?? "";
- expect(restored).toBe(prompt);
- expect(collectAssistantCitations(restored).map((entry) => entry.citation)).toEqual([citation]);
- useComposerDraftStore.getState().clearComposerContent(threadRef);
- expect(
- collectAssistantCitations(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt ?? ""),
- ).toEqual([]);
+ it("keeps quotes, comments, and remote source IDs through persistence and removes them on clear", async () => {
+ await useComposerDraftStore.persist.clearStorage();
+ vi.useFakeTimers();
+ try {
+ const threadId = ThreadId.make("citation-draft");
+ const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
+ const citation = {
+ version: 1 as const,
+ environmentId: EnvironmentId.make("remote-source"),
+ threadId: ThreadId.make("source-thread"),
+ messageId: MessageId.make("source-message"),
+ text: "Preserve the selected text after reload.",
+ comment: "Why is this important?\nPlease show an example.",
+ start: 12,
+ end: 52,
+ prefix: "Before. ",
+ suffix: " After.",
+ };
+ const prompt = `Explain ${serializeAssistantCitation(citation)} further.`;
+ useComposerDraftStore.getState().setPrompt(threadRef, prompt);
+ await vi.advanceTimersByTimeAsync(300);
+ resetComposerDraftStore();
+ await useComposerDraftStore.persist.rehydrate();
+ const restored = draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt ?? "";
+ expect(restored).toBe(prompt);
+ expect(collectAssistantCitations(restored).map((entry) => entry.citation)).toEqual([
+ citation,
+ ]);
+ useComposerDraftStore.getState().clearComposerContent(threadRef);
+ expect(
+ collectAssistantCitations(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt ?? ""),
+ ).toEqual([]);
+ } finally {
+ await useComposerDraftStore.persist.clearStorage();
+ vi.useRealTimers();
+ }
});
});
@@ -388,7 +394,6 @@ describe("composerDraftStore file attachments", () => {
const persistApi = useComposerDraftStore.persist as unknown as {
getOptions: () => {
- partialize: (state: ReturnType<typeof useComposerDraftStore.getState>) => unknown;
merge: (
persistedState: unknown,
currentState: ReturnType<typeof useComposerDraftStore.getState>,
@@ -396,9 +401,7 @@ describe("composerDraftStore file attachments", () => {
};
};
const options = persistApi.getOptions();
- const persisted = options.partialize(useComposerDraftStore.getState()) as {
- draftsByThreadKey: Record<string, { files?: Array<Record<string, unknown>> }>;
- };
+ const persisted = partializeComposerDraftStoreState(useComposerDraftStore.getState());
expect(persisted.draftsByThreadKey[threadKeyFor(threadId, TEST_ENVIRONMENT_ID)]?.files).toEqual(
[
@@ -436,7 +439,6 @@ describe("composerDraftStore file attachments", () => {
const persistApi = useComposerDraftStore.persist as unknown as {
getOptions: () => {
- partialize: (state: ReturnType<typeof useComposerDraftStore.getState>) => unknown;
merge: (
persistedState: unknown,
currentState: ReturnType<typeof useComposerDraftStore.getState>,
@@ -444,9 +446,7 @@ describe("composerDraftStore file attachments", () => {
};
};
const options = persistApi.getOptions();
- const persisted = options.partialize(useComposerDraftStore.getState()) as {
- draftsByThreadKey: Record<string, { files?: Array<Record<string, unknown>> }>;
- };
+ const persisted = partializeComposerDraftStoreState(useComposerDraftStore.getState());
expect(persisted.draftsByThreadKey[threadKeyFor(threadId, TEST_ENVIRONMENT_ID)]?.files).toEqual(
[
@@ -835,12 +835,9 @@ describe("composerDraftStore terminal contexts", () => {
.getState()
.addTerminalContext(threadRef, makeTerminalContext({ id: "ctx-persist" }));
- const persistApi = useComposerDraftStore.persist as unknown as {
- getOptions: () => {
- partialize: (state: ReturnType<typeof useComposerDraftStore.getState>) => unknown;
- };
- };
- const persistedState = persistApi.getOptions().partialize(useComposerDraftStore.getState()) as {
+ const persistedState = partializeComposerDraftStoreState(
+ useComposerDraftStore.getState(),
+ ) as unknown as {
draftsByThreadKey?: Record<string, { terminalContexts?: Array<Record<string, unknown>> }>;
};
@@ -1009,12 +1006,9 @@ describe("composerDraftStore element contexts", () => {
it("persists element contexts via the partializer (round-trippable)", () => {
useComposerDraftStore.getState().addElementContext(threadRef, baseSelection);
- const persistApi = useComposerDraftStore.persist as unknown as {
- getOptions: () => {
- partialize: (state: ReturnType<typeof useComposerDraftStore.getState>) => unknown;
- };
- };
- const persisted = persistApi.getOptions().partialize(useComposerDraftStore.getState()) as {
+ const persisted = partializeComposerDraftStoreState(
+ useComposerDraftStore.getState(),
+ ) as unknown as {
draftsByThreadKey?: Record<string, { elementContexts?: Array<Record<string, unknown>> }>;
};
const entry =
@@ -1067,12 +1061,9 @@ describe("composerDraftStore review comments", () => {
it("persists review comments and clears them with composer content", () => {
const store = useComposerDraftStore.getState();
store.addReviewComment(threadRef, comment);
- const persistApi = useComposerDraftStore.persist as unknown as {
- getOptions: () => {
- partialize: (state: ReturnType<typeof useComposerDraftStore.getState>) => unknown;
- };
- };
- const persisted = persistApi.getOptions().partialize(useComposerDraftStore.getState()) as {
+ const persisted = partializeComposerDraftStoreState(
+ useComposerDraftStore.getState(),
+ ) as unknown as {
draftsByThreadKey?: Record<string, { reviewComments?: Array<Record<string, unknown>> }>;
};
@@ -2517,7 +2508,7 @@ describe("composerDraftStore runtime and interaction settings", () => {
});
// ---------------------------------------------------------------------------
-// createDebouncedStorage
+// createDeferredStorage
// ---------------------------------------------------------------------------
function createMockStorage() {
@@ -2533,9 +2524,75 @@ function createMockStorage() {
};
}
-describe("createDebouncedStorage", () => {
+describe("composer draft persistence", () => {
+ it("defers attachment reads and serialization until typing stops, then restores the last draft", async () => {
+ await useComposerDraftStore.persist.clearStorage();
+ vi.useFakeTimers();
+ const stringify = vi.spyOn(JSON, "stringify");
+ try {
+ resetComposerDraftStore();
+ const heavyThreadId = ThreadId.make("heavy-draft");
+ const typingThreadId = ThreadId.make("typing-draft");
+ const heavyRef = scopeThreadRef(TEST_ENVIRONMENT_ID, heavyThreadId);
+ const typingRef = scopeThreadRef(TEST_ENVIRONMENT_ID, typingThreadId);
+ const heavyKey = scopedThreadKey(heavyRef);
+ useComposerDraftStore.getState().setPrompt(heavyRef, "Keep this image");
+ const attachments = [
+ {
+ id: "heavy-image",
+ name: "image.png",
+ mimeType: "image/png",
+ sizeBytes: 49_152,
+ dataUrl: `data:image/png;base64,${"AQID".repeat(16_384)}`,
+ },
+ ];
+ let attachmentReads = 0;
+ useComposerDraftStore.setState((state) => ({
+ draftsByThreadKey: {
+ ...state.draftsByThreadKey,
+ [heavyKey]: {
+ ...state.draftsByThreadKey[heavyKey]!,
+ get persistedAttachments() {
+ attachmentReads += 1;
+ return attachments;
+ },
+ },
+ },
+ }));
+ attachmentReads = 0;
+ stringify.mockClear();
+
+ for (let index = 1; index <= 20; index++) {
+ useComposerDraftStore.getState().setPrompt(typingRef, `Draft ${index}`);
+ }
+ expect(attachmentReads).toBe(0);
+ expect(stringify).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(300);
+ expect(attachmentReads).toBe(1);
+ expect(stringify).toHaveBeenCalledTimes(1);
+
+ resetComposerDraftStore();
+ await useComposerDraftStore.persist.rehydrate();
+ expect(draftFor(typingThreadId, TEST_ENVIRONMENT_ID)?.prompt).toBe("Draft 20");
+ expect(draftFor(heavyThreadId, TEST_ENVIRONMENT_ID)?.persistedAttachments).toEqual(
+ attachments,
+ );
+ } finally {
+ stringify.mockRestore();
+ await useComposerDraftStore.persist.clearStorage();
+ vi.useRealTimers();
+ resetComposerDraftStore();
+ }
+ });
+});
+
+describe("createDeferredStorage", () => {
+ const serialize = vi.fn((value: string) => `s:${value}`);
+
beforeEach(() => {
vi.useFakeTimers();
+ serialize.mockClear();
});
afterEach(() => {
@@ -2545,69 +2602,74 @@ describe("createDebouncedStorage", () => {
it("delegates getItem immediately", () => {
const base = createMockStorage();
base.getItem.mockReturnValueOnce("value");
- const storage = createDebouncedStorage(base);
+ const storage = createDeferredStorage(base, serialize);
expect(storage.getItem("key")).toBe("value");
expect(base.getItem).toHaveBeenCalledWith("key");
});
- it("does not write to base storage until the debounce fires", () => {
+ it("neither serializes nor writes until the debounce fires", () => {
const base = createMockStorage();
- const storage = createDebouncedStorage(base);
+ const storage = createDeferredStorage(base, serialize);
storage.setItem("key", "v1");
+ expect(serialize).not.toHaveBeenCalled();
expect(base.setItem).not.toHaveBeenCalled();
vi.advanceTimersByTime(299);
+ expect(serialize).not.toHaveBeenCalled();
expect(base.setItem).not.toHaveBeenCalled();
vi.advanceTimersByTime(1);
- expect(base.setItem).toHaveBeenCalledWith("key", "v1");
+ expect(base.setItem).toHaveBeenCalledWith("key", "s:v1");
});
- it("only writes the last value when setItem is called rapidly", () => {
+ it("serializes and writes only the last value when setItem is called rapidly", () => {
const base = createMockStorage();
- const storage = createDebouncedStorage(base);
+ const storage = createDeferredStorage(base, serialize);
storage.setItem("key", "v1");
storage.setItem("key", "v2");
storage.setItem("key", "v3");
vi.advanceTimersByTime(300);
+ expect(serialize).toHaveBeenCalledTimes(1);
expect(base.setItem).toHaveBeenCalledTimes(1);
- expect(base.setItem).toHaveBeenCalledWith("key", "v3");
+ expect(base.setItem).toHaveBeenCalledWith("key", "s:v3");
});
it("removeItem cancels a pending setItem write", () => {
const base = createMockStorage();
- const storage = createDebouncedStorage(base);
+ const storage = createDeferredStorage(base, serialize);
storage.setItem("key", "v1");
storage.removeItem("key");
vi.advanceTimersByTime(300);
+ expect(serialize).not.toHaveBeenCalled();
expect(base.setItem).not.toHaveBeenCalled();
expect(base.removeItem).toHaveBeenCalledWith("key");
});
- it("flush writes the pending value immediately", () => {
+ it("flush serializes and writes the pending value immediately", () => {
const base = createMockStorage();
- const storage = createDebouncedStorage(base);
+ const storage = createDeferredStorage(base, serialize);
storage.setItem("key", "v1");
expect(base.setItem).not.toHaveBeenCalled();
storage.flush();
- expect(base.setItem).toHaveBeenCalledWith("key", "v1");
+ expect(base.setItem).toHaveBeenCalledWith("key", "s:v1");
// Timer should be cancelled; no duplicate write.
vi.advanceTimersByTime(300);
+ expect(serialize).toHaveBeenCalledTimes(1);
expect(base.setItem).toHaveBeenCalledTimes(1);
});
it("flush is a no-op when nothing is pending", () => {
const base = createMockStorage();
- const storage = createDebouncedStorage(base);
+ const storage = createDeferredStorage(base, serialize);
storage.flush();
expect(base.setItem).not.toHaveBeenCalled();
@@ -2615,7 +2677,7 @@ describe("createDebouncedStorage", () => {
it("flush after removeItem is a no-op", () => {
const base = createMockStorage();
- const storage = createDebouncedStorage(base);
+ const storage = createDeferredStorage(base, serialize);
storage.setItem("key", "v1");
storage.removeItem("key");
@@ -2626,7 +2688,7 @@ describe("createDebouncedStorage", () => {
it("setItem works normally after removeItem cancels a pending write", () => {
const base = createMockStorage();
- const storage = createDebouncedStorage(base);
+ const storage = createDeferredStorage(base, serialize);
storage.setItem("key", "v1");
storage.removeItem("key");
@@ -2634,6 +2696,6 @@ describe("createDebouncedStorage", () => {
vi.advanceTimersByTime(300);
expect(base.setItem).toHaveBeenCalledTimes(1);
- expect(base.setItem).toHaveBeenCalledWith("key", "v2");
+ expect(base.setItem).toHaveBeenCalledWith("key", "s:v2");
});
});
diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts
index 4420f61837b..189ccb4fe68 100644
--- a/apps/web/src/composerDraftStore.ts
+++ b/apps/web/src/composerDraftStore.ts
@@ -53,9 +53,9 @@ import {
newElementContextId,
} from "./lib/elementContext";
import { create } from "zustand";
-import { createJSONStorage, persist } from "zustand/middleware";
+import { persist, type PersistStorage, type StorageValue } from "zustand/middleware";
import { useShallow } from "zustand/react/shallow";
-import { createDebouncedStorage, createMemoryStorage } from "./lib/storage";
+import { createDeferredStorage, createMemoryStorage } from "./lib/storage";
import { getDefaultServerModel } from "./providerModels";
import { UnifiedSettings } from "@t3tools/contracts/settings";
import { ReviewCommentContextSchema, type ReviewCommentContext } from "./reviewCommentContext";
@@ -73,11 +73,39 @@ export type DraftId = typeof DraftId.Type;
const COMPOSER_PERSIST_DEBOUNCE_MS = 300;
-const composerDebouncedStorage = createDebouncedStorage(
+// Keep the immutable state until flush. Migration writebacks already have the persisted shape.
+type ComposerPersistState =
+ | { capturedState: ComposerDraftStoreState }
+ | PersistedComposerDraftStoreState;
+
+const composerDebouncedStorage = createDeferredStorage<StorageValue<ComposerPersistState>>(
typeof localStorage !== "undefined" ? localStorage : createMemoryStorage(),
+ (value) =>
+ JSON.stringify({
+ state:
+ "capturedState" in value.state
+ ? partializeComposerDraftStoreState(value.state.capturedState)
+ : value.state,
+ version: value.version,
+ }),
COMPOSER_PERSIST_DEBOUNCE_MS,
);
+const composerPersistStorage: PersistStorage<ComposerPersistState> = {
+ getItem: (name) => {
+ // The base storage is localStorage (or in-memory), which is synchronous.
+ const raw = composerDebouncedStorage.getItem(name);
+ if (typeof raw !== "string") {
+ return null;
+ }
+ // Parsed persisted JSON. `migrate` and `merge` normalize it from unknown,
+ // so the cast mirrors the one zustand's createJSONStorage performs.
+ return JSON.parse(raw) as StorageValue<ComposerPersistState>;
+ },
+ setItem: (name, value) => composerDebouncedStorage.setItem(name, value),
+ removeItem: (name) => composerDebouncedStorage.removeItem(name),
+};
+
// Flush pending composer draft writes before page unload to prevent data loss.
if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
window.addEventListener("beforeunload", () => {
@@ -2013,7 +2041,8 @@ function migratePersistedComposerDraftStoreState(
};
}
-function partializeComposerDraftStoreState(
+/** Select the persisted draft fields when the storage write is ready to flush. */
+export function partializeComposerDraftStoreState(
state: ComposerDraftStoreState,
): PersistedComposerDraftStoreState {
// Draft sessions worth persisting: mapped (a new-thread flow targets
@@ -3876,9 +3905,10 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
{
name: COMPOSER_DRAFT_STORAGE_KEY,
version: COMPOSER_DRAFT_STORAGE_VERSION,
- storage: createJSONStorage(() => composerDebouncedStorage),
+ storage: composerPersistStorage,
migrate: migratePersistedComposerDraftStoreState,
- partialize: partializeComposerDraftStoreState,
+ // Defer the draft walk and serialization until the storage write flushes.
+ partialize: (state): ComposerPersistState => ({ capturedState: state }),
merge: (persistedState, currentState) => {
const normalizedPersisted =
normalizeCurrentPersistedComposerDraftStoreState(persistedState);
diff --git a/apps/web/src/lib/storage.ts b/apps/web/src/lib/storage.ts
index a37c67064aa..87b9b12ea8b 100644
--- a/apps/web/src/lib/storage.ts
+++ b/apps/web/src/lib/storage.ts
@@ -6,7 +6,10 @@ export interface StateStorage<R = unknown> {
removeItem: (name: string) => R;
}
-export interface DebouncedStorage<R = unknown> extends StateStorage<R> {
+export interface DeferredStorage<TValue> {
+ getItem: (name: string) => string | null | Promise<string | null>;
+ setItem: (name: string, value: TValue) => void;
+ removeItem: (name: string) => void;
flush: () => void;
}
@@ -39,14 +42,16 @@ export function resolveStorage(storage: Partial<StateStorage> | null | undefined
return isStateStorage(storage) ? storage : createMemoryStorage();
}
-export function createDebouncedStorage(
+/** Keep the latest value and serialize it when the debounce fires or `flush` runs. */
+export function createDeferredStorage<TValue>(
baseStorage: Partial<StateStorage> | null | undefined,
+ serialize: (value: TValue) => string,
debounceMs: number = 300,
-): DebouncedStorage {
+): DeferredStorage<TValue> {
const resolvedStorage = resolveStorage(baseStorage);
const debouncedSetItem = new Debouncer(
- (name: string, value: string) => {
- resolvedStorage.setItem(name, value);
+ (name: string, value: TValue) => {
+ resolvedStorage.setItem(name, serialize(value));
},
{ wait: debounceMs },
);
@@ -58,6 +63,8 @@ export function createDebouncedStorage(
},
removeItem: (name) => {
debouncedSetItem.cancel();
+ // cancel() leaves the captured value in Pacer's lastArgs.
+ debouncedSetItem.reset();
resolvedStorage.removeItem(name);
},
flush: () => {