Open History to see the last commit
1import { beforeEach, describe, expect, it, vi } from 'vitest'
2import { EventType } from '@tanstack/ai/client'
3import { ChatPersistor } from '../src/client-persistor'
4import { createMockPersistence, createUIMessage } from './test-utils'
5import type { StreamChunk } from '@tanstack/ai/client'
6import type {
7 ChatClientPersistence,
8 ChatPersistedState,
9 UIMessage,
10} from '../src/types'
11
12const CHAT_ID = 'chat-1'
13
14/** Resolve after pending micro- and macro-tasks have drained. */
15function flushAsync(): Promise<void> {
16 return new Promise((resolve) => setTimeout(resolve, 0))
17}
18
19/** A promise with externally accessible resolve/reject. */
20function createDeferred<T>() {
21 let resolve!: (value: T) => void
22 let reject!: (reason?: unknown) => void
23 const promise = new Promise<T>((res, rej) => {
24 resolve = res
25 reject = rej
26 })
27 return { promise, resolve, reject }
28}
29
30/**
31 * Build a persistor wired to `adapter` with a spy `applyMessages` callback so
32 * tests can assert what (if anything) gets re-applied to the client.
33 */
34function createPersistor(adapter: ChatClientPersistence, id: string = CHAT_ID) {
35 const applyMessages = vi.fn<(messages: Array<UIMessage>) => void>()
36 const persistor = new ChatPersistor(adapter, id, applyMessages)
37 return { persistor, applyMessages }
38}
39
40// --- typed StreamChunk fixtures -------------------------------------------
41// These satisfy the StreamChunk union directly (no casts). The persistor only
42// ever reads `type` and the relevant id field off a chunk, and unit-test chunks
43// are never run through the connection adapter's run-context map, so the run id
44// must live on the chunk itself (only RUN_STARTED/RUN_FINISHED carry one).
45
46function runStarted(runId: string, threadId: string = 'thread-1'): StreamChunk {
47 return { type: EventType.RUN_STARTED, threadId, runId }
48}
49
50function runFinished(
51 runId: string,
52 threadId: string = 'thread-1',
53): StreamChunk {
54 return { type: EventType.RUN_FINISHED, threadId, runId }
55}
56
57function runError(message: string = 'boom'): StreamChunk {
58 return { type: EventType.RUN_ERROR, message }
59}
60
61function textContent(messageId: string, delta: string = 'hi'): StreamChunk {
62 return { type: EventType.TEXT_MESSAGE_CONTENT, messageId, delta }
63}
64
65function toolCallStart(
66 toolCallId: string,
67 parentMessageId?: string,
68): StreamChunk {
69 return {
70 type: EventType.TOOL_CALL_START,
71 toolCallId,
72 toolCallName: 'tool',
73 ...(parentMessageId ? { parentMessageId } : {}),
74 } as StreamChunk
75}
76
77function messagesSnapshot(): StreamChunk {
78 return { type: EventType.MESSAGES_SNAPSHOT, messages: [] }
79}
80
81describe('ChatPersistor', () => {
82 describe('readInitial', () => {
83 it('returns the stored messages from a synchronous getItem', () => {
84 const stored = [createUIMessage('m-1')]
85 const adapter = createMockPersistence(stored)
86 const { persistor } = createPersistor(adapter)
87
88 // A legacy bare-array record is normalized to the combined shape.
89 expect(persistor.readInitial()).toEqual({ messages: stored })
90 expect(adapter.getItem).toHaveBeenCalledWith(CHAT_ID)
91 })
92
93 it('returns the promise from an asynchronous getItem', () => {
94 const stored = [createUIMessage('m-1')]
95 const adapter = createMockPersistence()
96 adapter.getItem = vi.fn(() => Promise.resolve(stored))
97 const { persistor } = createPersistor(adapter)
98
99 expect(persistor.readInitial()).toBeInstanceOf(Promise)
100 })
101
102 it('swallows a throwing getItem and returns undefined', () => {
103 const adapter = createMockPersistence()
104 adapter.getItem = vi.fn(() => {
105 throw new Error('storage unavailable')
106 })
107 const { persistor } = createPersistor(adapter)
108
109 expect(persistor.readInitial()).toBeUndefined()
110 })
111 })
112
113 describe('hydrateAsync', () => {
114 it('applies messages once the promise resolves to a record', async () => {
115 const stored = [createUIMessage('persisted-1')]
116 const { persistor, applyMessages } = createPersistor(
117 createMockPersistence(),
118 )
119
120 persistor.hydrateAsync(Promise.resolve({ messages: stored }))
121 await flushAsync()
122
123 expect(applyMessages).toHaveBeenCalledWith(stored)
124 })
125
126 it('does not apply when the promise resolves to undefined', async () => {
127 const { persistor, applyMessages } = createPersistor(
128 createMockPersistence(),
129 )
130
131 persistor.hydrateAsync(Promise.resolve(undefined))
132 await flushAsync()
133
134 expect(applyMessages).not.toHaveBeenCalled()
135 })
136
137 it('does nothing for a synchronous (non-promise) value', async () => {
138 const { persistor, applyMessages } = createPersistor(
139 createMockPersistence(),
140 )
141
142 persistor.hydrateAsync({ messages: [createUIMessage('m-1')] })
143 await flushAsync()
144
145 expect(applyMessages).not.toHaveBeenCalled()
146 })
147
148 it('does not apply if messages changed before hydration resolves', async () => {
149 const deferred = createDeferred<ChatPersistedState>()
150 const { persistor, applyMessages } = createPersistor(
151 createMockPersistence(),
152 )
153
154 persistor.hydrateAsync(deferred.promise)
155 // A local change lands before the slow getItem resolves.
156 persistor.notifyMessagesChanged([createUIMessage('local-1')])
157 deferred.resolve({ messages: [createUIMessage('persisted-1')] })
158 await flushAsync()
159
160 expect(applyMessages).not.toHaveBeenCalled()
161 })
162
163 it('swallows a rejected hydration promise', async () => {
164 const { persistor, applyMessages } = createPersistor(
165 createMockPersistence(),
166 )
167
168 persistor.hydrateAsync(Promise.reject(new Error('read failed')))
169 await flushAsync()
170
171 expect(applyMessages).not.toHaveBeenCalled()
172 })
173 })
174
175 describe('notifyMessagesChanged', () => {
176 it('persists the messages on change', () => {
177 const adapter = createMockPersistence()
178 const { persistor } = createPersistor(adapter)
179 const messages = [createUIMessage('m-1')]
180
181 persistor.notifyMessagesChanged(messages)
182
183 expect(adapter.setItem).toHaveBeenCalledWith(CHAT_ID, { messages })
184 })
185
186 it('persists a snapshot, not the live array reference', () => {
187 const adapter = createMockPersistence()
188 const { persistor } = createPersistor(adapter)
189 const messages = [createUIMessage('m-1')]
190
191 persistor.notifyMessagesChanged(messages)
192 messages.push(createUIMessage('m-2'))
193
194 const persisted = vi.mocked(adapter.setItem).mock.calls[0]?.[1]
195 expect(persisted?.messages).toHaveLength(1)
196 })
197
198 it('skips exactly one write after beginClear, then resumes', () => {
199 const adapter = createMockPersistence()
200 const { persistor } = createPersistor(adapter)
201
202 persistor.notifyMessagesChanged([createUIMessage('m-1')])
203 persistor.beginClear()
204 persistor.notifyMessagesChanged([]) // the clear's empty snapshot — skipped
205 persistor.notifyMessagesChanged([createUIMessage('m-2')])
206
207 expect(adapter.setItem).toHaveBeenCalledTimes(2)
208 })
209
210 it('swallows a synchronous setItem error', () => {
211 const adapter = createMockPersistence()
212 adapter.setItem = vi.fn(() => {
213 throw new Error('quota exceeded')
214 })
215 const { persistor } = createPersistor(adapter)
216
217 expect(() =>
218 persistor.notifyMessagesChanged([createUIMessage('m-1')]),
219 ).not.toThrow()
220 })
221
222 it('runs async writes sequentially (FIFO, no overlap)', async () => {
223 const first = createDeferred<void>()
224 const second = createDeferred<void>()
225 const adapter = createMockPersistence()
226 adapter.setItem = vi
227 .fn()
228 .mockReturnValueOnce(first.promise)
229 .mockReturnValueOnce(second.promise)
230 const { persistor } = createPersistor(adapter)
231
232 persistor.notifyMessagesChanged([createUIMessage('a')])
233 persistor.notifyMessagesChanged([createUIMessage('b')])
234 // Second write is queued behind the first and must not have started yet.
235 expect(adapter.setItem).toHaveBeenCalledTimes(1)
236
237 first.resolve()
238 await flushAsync()
239
240 expect(adapter.setItem).toHaveBeenCalledTimes(2)
241 expect(vi.mocked(adapter.setItem).mock.calls[1]?.[1]).toEqual({
242 messages: [createUIMessage('b')],
243 })
244 })
245
246 it('keeps writing after an async write rejects', async () => {
247 const adapter = createMockPersistence()
248 adapter.setItem = vi
249 .fn()
250 .mockRejectedValueOnce(new Error('transient'))
251 .mockResolvedValue(undefined)
252 const { persistor } = createPersistor(adapter)
253
254 persistor.notifyMessagesChanged([createUIMessage('a')])
255 persistor.notifyMessagesChanged([createUIMessage('b')])
256 await flushAsync()
257
258 expect(adapter.setItem).toHaveBeenCalledTimes(2)
259 })
260 })
261
262 describe('remove', () => {
263 it('removes the persisted conversation', () => {
264 const adapter = createMockPersistence()
265 const { persistor } = createPersistor(adapter)
266
267 persistor.remove()
268
269 expect(adapter.removeItem).toHaveBeenCalledWith(CHAT_ID)
270 })
271
272 it('swallows a synchronous removeItem error', () => {
273 const adapter = createMockPersistence()
274 adapter.removeItem = vi.fn(() => {
275 throw new Error('locked')
276 })
277 const { persistor } = createPersistor(adapter)
278
279 expect(() => persistor.remove()).not.toThrow()
280 })
281
282 it('invalidates a queued write that a removal supersedes', async () => {
283 const inFlight = createDeferred<void>()
284 const adapter = createMockPersistence()
285 adapter.setItem = vi
286 .fn()
287 .mockReturnValueOnce(inFlight.promise) // write A (in flight)
288 .mockResolvedValue(undefined) // write B (would run later)
289 const { persistor } = createPersistor(adapter)
290
291 persistor.notifyMessagesChanged([createUIMessage('a')]) // starts, in flight
292 persistor.notifyMessagesChanged([createUIMessage('b')]) // queued behind A
293 persistor.remove() // bumps generation, queued behind B
294
295 inFlight.resolve()
296 await flushAsync()
297
298 // B's generation was superseded by remove(), so only A was written.
299 expect(adapter.setItem).toHaveBeenCalledTimes(1)
300 expect(adapter.removeItem).toHaveBeenCalledTimes(1)
301 })
302 })
303
304 describe('clear-during-stream suppression', () => {
305 it('does not ignore chunks before a clear', () => {
306 const { persistor } = createPersistor(createMockPersistence())
307
308 expect(persistor.shouldIgnoreChunk(runStarted('run-1'))).toBe(false)
309 expect(persistor.shouldIgnoreChunk(textContent('msg-1'))).toBe(false)
310 })
311
312 it('ignores chunks for a message id captured at clear time', () => {
313 const { persistor } = createPersistor(createMockPersistence())
314 persistor.snapshotClear({
315 messages: [createUIMessage('msg-1')],
316 activeRunIds: new Set(),
317 currentRunId: null,
318 })
319
320 expect(persistor.shouldIgnoreChunk(textContent('msg-1'))).toBe(true)
321 expect(persistor.shouldIgnoreChunk(textContent('msg-other'))).toBe(false)
322 })
323
324 it('ignores a RUN_STARTED for an active run captured at clear time', () => {
325 const { persistor } = createPersistor(createMockPersistence())
326 persistor.snapshotClear({
327 messages: [],
328 activeRunIds: new Set(['run-1']),
329 currentRunId: null,
330 })
331
332 expect(persistor.shouldIgnoreChunk(runStarted('run-1'))).toBe(true)
333 })
334
335 it('ignores the in-flight currentRunId captured at clear time', () => {
336 const { persistor } = createPersistor(createMockPersistence())
337 persistor.snapshotClear({
338 messages: [],
339 activeRunIds: new Set(),
340 currentRunId: 'run-current',
341 })
342
343 expect(persistor.shouldIgnoreChunk(runStarted('run-current'))).toBe(true)
344 })
345
346 it('ignores runless content chunks belonging to a cleared run', () => {
347 const { persistor } = createPersistor(createMockPersistence())
348 persistor.snapshotClear({
349 messages: [],
350 activeRunIds: new Set(['run-1']),
351 currentRunId: null,
352 })
353 // The cleared run starts again, pinning it as the current runless run.
354 persistor.shouldIgnoreChunk(runStarted('run-1'))
355
356 expect(persistor.shouldIgnoreChunk(textContent('late-msg'))).toBe(true)
357 expect(persistor.shouldIgnoreChunk(messagesSnapshot())).toBe(true)
358 })
359
360 it('ignores tool chunks by cleared parentMessageId and remembers the toolCallId', () => {
361 const { persistor } = createPersistor(createMockPersistence())
362 persistor.snapshotClear({
363 messages: [createUIMessage('parent-msg')],
364 activeRunIds: new Set(),
365 currentRunId: null,
366 })
367
368 // First seen via its parent message id...
369 expect(
370 persistor.shouldIgnoreChunk(toolCallStart('tc-1', 'parent-msg')),
371 ).toBe(true)
372 // ...then a later chunk for the same tool call (no parent) is still ignored.
373 expect(persistor.shouldIgnoreChunk(toolCallStart('tc-1'))).toBe(true)
374 })
375 })
376
377 describe('run lifecycle hooks', () => {
378 beforeEach(() => {
379 vi.clearAllMocks()
380 })
381
382 it('forgets a settled run so a later run with the same id is not ignored', () => {
383 const { persistor } = createPersistor(createMockPersistence())
384 persistor.snapshotClear({
385 messages: [],
386 activeRunIds: new Set(['run-1']),
387 currentRunId: null,
388 })
389 expect(persistor.shouldIgnoreChunk(runStarted('run-1'))).toBe(true)
390
391 persistor.onRunSettled('run-1')
392
393 expect(persistor.shouldIgnoreChunk(runStarted('run-1'))).toBe(false)
394 })
395
396 it('stops ignoring runless chunks after a session-level run error', () => {
397 const { persistor } = createPersistor(createMockPersistence())
398 persistor.snapshotClear({
399 messages: [],
400 activeRunIds: new Set(['run-1']),
401 currentRunId: null,
402 })
403 persistor.shouldIgnoreChunk(runStarted('run-1'))
404 expect(persistor.shouldIgnoreChunk(textContent('late-1'))).toBe(true)
405
406 persistor.onSessionRunError()
407
408 // A fresh runless chunk is no longer attributed to the cleared run. (An
409 // already-seen message id stays ignored — shouldIgnoreChunk records it.)
410 expect(persistor.shouldIgnoreChunk(textContent('late-2'))).toBe(false)
411 })
412
413 it('takeRunlessRunId returns and clears the current runless run, then null', () => {
414 const { persistor } = createPersistor(createMockPersistence())
415 persistor.snapshotClear({
416 messages: [],
417 activeRunIds: new Set(['run-1']),
418 currentRunId: null,
419 })
420 persistor.shouldIgnoreChunk(runStarted('run-1'))
421
422 expect(persistor.takeRunlessRunId()).toBe('run-1')
423 expect(persistor.takeRunlessRunId()).toBeNull()
424 // The drained run is no longer pinned, so runless chunks aren't ignored.
425 expect(persistor.shouldIgnoreChunk(textContent('late'))).toBe(false)
426 })
427
428 it('resetIgnored only clears active-run markers, not cleared ids', () => {
429 const { persistor } = createPersistor(createMockPersistence())
430 persistor.snapshotClear({
431 messages: [createUIMessage('msg-1')],
432 activeRunIds: new Set(['run-1']),
433 currentRunId: null,
434 })
435
436 persistor.resetIgnored()
437
438 // Cleared run/message ids survive a reset (they outlive the active run).
439 expect(persistor.shouldIgnoreChunk(runStarted('run-1'))).toBe(true)
440 expect(persistor.shouldIgnoreChunk(textContent('msg-1'))).toBe(true)
441 })
442
443 it('does not ignore an unrelated runId-less run error', () => {
444 const { persistor } = createPersistor(createMockPersistence())
445
446 expect(persistor.shouldIgnoreChunk(runError())).toBe(false)
447 })
448
449 it('onRunStarted for a non-cleared run does not suppress runless chunks', () => {
450 const { persistor } = createPersistor(createMockPersistence())
451
452 // Pinning a live (never-cleared) run must not start swallowing its output.
453 persistor.onRunStarted('run-live')
454
455 expect(persistor.shouldIgnoreChunk(textContent('content'))).toBe(false)
456 })
457
458 it('advances the runless pointer when the active run finishes', () => {
459 const { persistor } = createPersistor(createMockPersistence())
460 persistor.snapshotClear({
461 messages: [],
462 activeRunIds: new Set(['run-1', 'run-2']),
463 currentRunId: null,
464 })
465 persistor.shouldIgnoreChunk(runStarted('run-1'))
466 persistor.shouldIgnoreChunk(runStarted('run-2'))
467
468 // run-2 was the pinned runless run; settling it falls back to run-1.
469 persistor.onRunSettled('run-2')
470
471 expect(persistor.shouldIgnoreChunk(runFinished('run-2'))).toBe(false)
472 expect(persistor.shouldIgnoreChunk(textContent('late'))).toBe(true)
473 })
474
475 it('keeps suppressing a second cleared run after the first drains via a runless error', () => {
476 const { persistor } = createPersistor(createMockPersistence())
477 persistor.snapshotClear({
478 messages: [],
479 activeRunIds: new Set(['run-1', 'run-2']),
480 currentRunId: null,
481 })
482 persistor.shouldIgnoreChunk(runStarted('run-1'))
483 persistor.shouldIgnoreChunk(runStarted('run-2')) // run-2 now pinned
484
485 // A runId-less RUN_ERROR drains the pinned run (run-2)...
486 expect(persistor.takeRunlessRunId()).toBe('run-2')
487
488 // ...but run-1 is still cleared, so its runless content stays suppressed
489 // instead of leaking through once the pointer advances back to it.
490 expect(persistor.shouldIgnoreChunk(textContent('late-from-run-1'))).toBe(
491 true,
492 )
493 })
494 })
495})