Skip to content

Commit 17e2c91

Browse files
committed
fix(web): verify deferred draft writes through storage
1 parent 2300739 commit 17e2c91

3 files changed

Lines changed: 105 additions & 53 deletions

File tree

‎apps/web/src/composerDraftStore.test.ts‎

Lines changed: 99 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -197,37 +197,42 @@ describe("composerDraftStore assistant citations", () => {
197197
beforeEach(resetComposerDraftStore);
198198
afterEach(resetComposerDraftStore);
199199

200-
it("keeps quotes, comments, and remote source IDs through persistence and removes them on clear", () => {
201-
const threadId = ThreadId.make("citation-draft");
202-
const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
203-
const citation = {
204-
version: 1 as const,
205-
environmentId: EnvironmentId.make("remote-source"),
206-
threadId: ThreadId.make("source-thread"),
207-
messageId: MessageId.make("source-message"),
208-
text: "Preserve the selected text after reload.",
209-
comment: "Why is this important?\nPlease show an example.",
210-
start: 12,
211-
end: 52,
212-
prefix: "Before. ",
213-
suffix: " After.",
214-
};
215-
const prompt = `Explain ${serializeAssistantCitation(citation)} further.`;
216-
useComposerDraftStore.getState().setPrompt(threadRef, prompt);
217-
const options = useComposerDraftStore.persist.getOptions();
218-
const saved = JSON.parse(
219-
JSON.stringify(options.partialize!(useComposerDraftStore.getState())),
220-
) as unknown;
221-
resetComposerDraftStore();
222-
const hydrated = options.merge!(saved, useComposerDraftStore.getState());
223-
useComposerDraftStore.setState(hydrated);
224-
const restored = draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt ?? "";
225-
expect(restored).toBe(prompt);
226-
expect(collectAssistantCitations(restored).map((entry) => entry.citation)).toEqual([citation]);
227-
useComposerDraftStore.getState().clearComposerContent(threadRef);
228-
expect(
229-
collectAssistantCitations(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt ?? ""),
230-
).toEqual([]);
200+
it("keeps quotes, comments, and remote source IDs through persistence and removes them on clear", async () => {
201+
await useComposerDraftStore.persist.clearStorage();
202+
vi.useFakeTimers();
203+
try {
204+
const threadId = ThreadId.make("citation-draft");
205+
const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
206+
const citation = {
207+
version: 1 as const,
208+
environmentId: EnvironmentId.make("remote-source"),
209+
threadId: ThreadId.make("source-thread"),
210+
messageId: MessageId.make("source-message"),
211+
text: "Preserve the selected text after reload.",
212+
comment: "Why is this important?\nPlease show an example.",
213+
start: 12,
214+
end: 52,
215+
prefix: "Before. ",
216+
suffix: " After.",
217+
};
218+
const prompt = `Explain ${serializeAssistantCitation(citation)} further.`;
219+
useComposerDraftStore.getState().setPrompt(threadRef, prompt);
220+
await vi.advanceTimersByTimeAsync(300);
221+
resetComposerDraftStore();
222+
await useComposerDraftStore.persist.rehydrate();
223+
const restored = draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt ?? "";
224+
expect(restored).toBe(prompt);
225+
expect(collectAssistantCitations(restored).map((entry) => entry.citation)).toEqual([
226+
citation,
227+
]);
228+
useComposerDraftStore.getState().clearComposerContent(threadRef);
229+
expect(
230+
collectAssistantCitations(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt ?? ""),
231+
).toEqual([]);
232+
} finally {
233+
await useComposerDraftStore.persist.clearStorage();
234+
vi.useRealTimers();
235+
}
231236
});
232237
});
233238

@@ -2519,6 +2524,69 @@ function createMockStorage() {
25192524
};
25202525
}
25212526

2527+
describe("composer draft persistence", () => {
2528+
it("defers attachment reads and serialization until typing stops, then restores the last draft", async () => {
2529+
await useComposerDraftStore.persist.clearStorage();
2530+
vi.useFakeTimers();
2531+
const stringify = vi.spyOn(JSON, "stringify");
2532+
try {
2533+
resetComposerDraftStore();
2534+
const heavyThreadId = ThreadId.make("heavy-draft");
2535+
const typingThreadId = ThreadId.make("typing-draft");
2536+
const heavyRef = scopeThreadRef(TEST_ENVIRONMENT_ID, heavyThreadId);
2537+
const typingRef = scopeThreadRef(TEST_ENVIRONMENT_ID, typingThreadId);
2538+
const heavyKey = scopedThreadKey(heavyRef);
2539+
useComposerDraftStore.getState().setPrompt(heavyRef, "Keep this image");
2540+
const attachments = [
2541+
{
2542+
id: "heavy-image",
2543+
name: "image.png",
2544+
mimeType: "image/png",
2545+
sizeBytes: 49_152,
2546+
dataUrl: `data:image/png;base64,${"AQID".repeat(16_384)}`,
2547+
},
2548+
];
2549+
let attachmentReads = 0;
2550+
useComposerDraftStore.setState((state) => ({
2551+
draftsByThreadKey: {
2552+
...state.draftsByThreadKey,
2553+
[heavyKey]: {
2554+
...state.draftsByThreadKey[heavyKey]!,
2555+
get persistedAttachments() {
2556+
attachmentReads += 1;
2557+
return attachments;
2558+
},
2559+
},
2560+
},
2561+
}));
2562+
attachmentReads = 0;
2563+
stringify.mockClear();
2564+
2565+
for (let index = 1; index <= 20; index++) {
2566+
useComposerDraftStore.getState().setPrompt(typingRef, `Draft ${index}`);
2567+
}
2568+
expect(attachmentReads).toBe(0);
2569+
expect(stringify).not.toHaveBeenCalled();
2570+
2571+
await vi.advanceTimersByTimeAsync(300);
2572+
expect(attachmentReads).toBe(1);
2573+
expect(stringify).toHaveBeenCalledTimes(1);
2574+
2575+
resetComposerDraftStore();
2576+
await useComposerDraftStore.persist.rehydrate();
2577+
expect(draftFor(typingThreadId, TEST_ENVIRONMENT_ID)?.prompt).toBe("Draft 20");
2578+
expect(draftFor(heavyThreadId, TEST_ENVIRONMENT_ID)?.persistedAttachments).toEqual(
2579+
attachments,
2580+
);
2581+
} finally {
2582+
stringify.mockRestore();
2583+
await useComposerDraftStore.persist.clearStorage();
2584+
vi.useRealTimers();
2585+
resetComposerDraftStore();
2586+
}
2587+
});
2588+
});
2589+
25222590
describe("createDeferredStorage", () => {
25232591
const serialize = vi.fn((value: string) => `s:${value}`);
25242592

‎apps/web/src/composerDraftStore.ts‎

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -73,15 +73,7 @@ export type DraftId = typeof DraftId.Type;
7373

7474
const COMPOSER_PERSIST_DEBOUNCE_MS = 300;
7575

76-
/**
77-
* What flows from `partialize` into the debounced storage. The persist
78-
* pipeline used to run the full draft walk + JSON.stringify on every store
79-
* write — every keystroke serialized all persisted drafts, including base64
80-
* image attachments. `partialize` now only captures the live state reference,
81-
* and the real walk + stringify run once per debounced flush. Already
82-
* persisted-shape values (migration seeds written straight to storage) pass
83-
* through serialization untouched.
84-
*/
76+
// Keep the immutable state until flush. Migration writebacks already have the persisted shape.
8577
type ComposerPersistState =
8678
| { capturedState: ComposerDraftStoreState }
8779
| PersistedComposerDraftStoreState;
@@ -2049,11 +2041,7 @@ function migratePersistedComposerDraftStoreState(
20492041
};
20502042
}
20512043

2052-
/**
2053-
* Produces the persisted draft-store shape. Runs once per debounced storage
2054-
* flush (see ComposerPersistState), not on every store write. Exported so
2055-
* tests can exercise the persistence round trip directly.
2056-
*/
2044+
/** Select the persisted draft fields when the storage write is ready to flush. */
20572045
export function partializeComposerDraftStoreState(
20582046
state: ComposerDraftStoreState,
20592047
): PersistedComposerDraftStoreState {
@@ -3919,8 +3907,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
39193907
version: COMPOSER_DRAFT_STORAGE_VERSION,
39203908
storage: composerPersistStorage,
39213909
migrate: migratePersistedComposerDraftStoreState,
3922-
// Cheap capture only; the draft walk + stringify happen at flush time
3923-
// inside composerDebouncedStorage. See ComposerPersistState.
3910+
// Defer the draft walk and serialization until the storage write flushes.
39243911
partialize: (state): ComposerPersistState => ({ capturedState: state }),
39253912
merge: (persistedState, currentState) => {
39263913
const normalizedPersisted =

‎apps/web/src/lib/storage.ts‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,7 @@ export function resolveStorage(storage: Partial<StateStorage> | null | undefined
4242
return isStateStorage(storage) ? storage : createMemoryStorage();
4343
}
4444

45-
/**
46-
* Debounced storage that also defers serialization: `setItem` only holds the
47-
* latest raw value, and `serialize` runs once when the debounce fires (or on
48-
* `flush`). This keeps rapid updates — such as composer keystrokes — at
49-
* "store a reference" cost instead of serializing the full value every time.
50-
*/
45+
/** Keep the latest value and serialize it when the debounce fires or `flush` runs. */
5146
export function createDeferredStorage<TValue>(
5247
baseStorage: Partial<StateStorage> | null | undefined,
5348
serialize: (value: TValue) => string,
@@ -68,6 +63,8 @@ export function createDeferredStorage<TValue>(
6863
},
6964
removeItem: (name) => {
7065
debouncedSetItem.cancel();
66+
// cancel() leaves the captured value in Pacer's lastArgs.
67+
debouncedSetItem.reset();
7168
resolvedStorage.removeItem(name);
7269
},
7370
flush: () => {

0 commit comments

Comments
 (0)