Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

client-persistor.test.ts

573 lines19.7 KB

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))
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 }
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 }
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 }
49​
50function runFinished(
51 runId: string,
52 threadId: string = 'thread-1',
53): StreamChunk {
54 return { type: EventType.RUN_FINISHED, threadId, runId }
56​
57function runError(message: string = 'boom'): StreamChunk {
58 return { type: EventType.RUN_ERROR, message }
60​
61function textContent(messageId: string, delta: string = 'hi'): StreamChunk {
62 return { type: EventType.TEXT_MESSAGE_CONTENT, messageId, delta }
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
76​
77function messagesSnapshot(): StreamChunk {
78 return { type: EventType.MESSAGES_SNAPSHOT, messages: [] }
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 expect(persistor.readInitial()).toEqual({ messages: stored })
89 expect(adapter.getItem).toHaveBeenCalledWith(CHAT_ID)
90 })
91​
92 it('round-trips a mixed transcript that includes activity', () => {
93 let stored: ChatPersistedState | undefined
94 const adapter: ChatClientPersistence = {
95 getItem: vi.fn(() => stored),
96 setItem: vi.fn((_id, state) => {
97 stored = state
98 }),
99 removeItem: vi.fn(),
100 }
101 const mixed: Array<UIMessage> = [
102 { id: 'u1', role: 'user', parts: [{ type: 'text', content: 'hi' }] },
103 {
104 id: 'act-1',
105 role: 'activity',
106 parts: [
107 {
108 type: 'activity',
109 activityType: 'SEARCH',
110 content: { query: 'tanstack' },
111 },
112 ],
113 },
114 {
115 id: 'a1',
116 role: 'assistant',
117 parts: [{ type: 'text', content: 'ok' }],
118 },
119 ]
120​
121 const { persistor } = createPersistor(adapter)
122 persistor.notifyMessagesChanged(mixed)
123​
124 const { persistor: next } = createPersistor(adapter)
125 expect(next.readInitial()).toEqual({ messages: mixed })
126 })
127​
128 it('returns the promise from an asynchronous getItem', () => {
129 const stored = [createUIMessage('m-1')]
130 const adapter = createMockPersistence()
131 adapter.getItem = vi.fn(() => Promise.resolve({ messages: stored }))
132 const { persistor } = createPersistor(adapter)
133​
134 expect(persistor.readInitial()).toBeInstanceOf(Promise)
135 })
136​
137 it('logs a 0.x bare-array record and does not overwrite it until a clear', () => {
138 const error = vi.spyOn(console, 'error').mockImplementation(() => {})
139 const adapter = createMockPersistence()
140 adapter.getItem = vi.fn(() => [createUIMessage('old-1')] as never)
141 const { persistor } = createPersistor(adapter)
142​
143 expect(persistor.readInitial()).toBeUndefined()
144 expect(error).toHaveBeenCalledWith(
145 expect.stringContaining(`threadId "${CHAT_ID}" is in the 0.x format`),
146 )
147​
148 persistor.notifyMessagesChanged([createUIMessage('new-1')])
149 persistor.persistResumeSnapshot(null)
150 expect(adapter.setItem).not.toHaveBeenCalled()
151 expect(adapter.removeItem).not.toHaveBeenCalled()
152​
153 persistor.remove()
154 persistor.notifyMessagesChanged([createUIMessage('new-2')])
155 expect(adapter.removeItem).toHaveBeenCalledWith(CHAT_ID)
156 expect(adapter.setItem).toHaveBeenCalledTimes(1)
157 error.mockRestore()
158 })
159​
160 it('swallows a throwing getItem and returns undefined', () => {
161 const adapter = createMockPersistence()
162 adapter.getItem = vi.fn(() => {
163 throw new Error('storage unavailable')
164 })
165 const { persistor } = createPersistor(adapter)
166​
167 expect(persistor.readInitial()).toBeUndefined()
168 })
169 })
170​
171 describe('hydrateAsync', () => {
172 it('applies messages once the promise resolves to a record', async () => {
173 const stored = [createUIMessage('persisted-1')]
174 const { persistor, applyMessages } = createPersistor(
175 createMockPersistence(),
176 )
177​
178 persistor.hydrateAsync(Promise.resolve({ messages: stored }))
179 await flushAsync()
180​
181 expect(applyMessages).toHaveBeenCalledWith(stored)
182 })
183​
184 it('does not apply when the promise resolves to undefined', async () => {
185 const { persistor, applyMessages } = createPersistor(
186 createMockPersistence(),
187 )
188​
189 persistor.hydrateAsync(Promise.resolve(undefined))
190 await flushAsync()
191​
192 expect(applyMessages).not.toHaveBeenCalled()
193 })
194​
195 it('does nothing for a synchronous (non-promise) value', async () => {
196 const { persistor, applyMessages } = createPersistor(
197 createMockPersistence(),
198 )
199​
200 persistor.hydrateAsync({ messages: [createUIMessage('m-1')] })
201 await flushAsync()
202​
203 expect(applyMessages).not.toHaveBeenCalled()
204 })
205​
206 it('does not apply if messages changed before hydration resolves', async () => {
207 const deferred = createDeferred<ChatPersistedState>()
208 const { persistor, applyMessages } = createPersistor(
209 createMockPersistence(),
210 )
211​
212 persistor.hydrateAsync(deferred.promise)
213 // A local change lands before the slow getItem resolves.
214 persistor.notifyMessagesChanged([createUIMessage('local-1')])
215 deferred.resolve({ messages: [createUIMessage('persisted-1')] })
216 await flushAsync()
217​
218 expect(applyMessages).not.toHaveBeenCalled()
219 })
220​
221 it('swallows a rejected hydration promise', async () => {
222 const { persistor, applyMessages } = createPersistor(
223 createMockPersistence(),
224 )
225​
226 persistor.hydrateAsync(Promise.reject(new Error('read failed')))
227 await flushAsync()
228​
229 expect(applyMessages).not.toHaveBeenCalled()
230 })
231 })
232​
233 describe('notifyMessagesChanged', () => {
234 it('persists the messages on change', () => {
235 const adapter = createMockPersistence()
236 const { persistor } = createPersistor(adapter)
237 const messages = [createUIMessage('m-1')]
238​
239 persistor.notifyMessagesChanged(messages)
240​
241 expect(adapter.setItem).toHaveBeenCalledWith(CHAT_ID, { messages })
242 })
243​
244 it('persists a snapshot, not the live array reference', () => {
245 const adapter = createMockPersistence()
246 const { persistor } = createPersistor(adapter)
247 const messages = [createUIMessage('m-1')]
248​
249 persistor.notifyMessagesChanged(messages)
250 messages.push(createUIMessage('m-2'))
251​
252 const persisted = vi.mocked(adapter.setItem).mock.calls[0]?.[1]
253 expect(persisted?.messages).toHaveLength(1)
254 })
255​
256 it('skips exactly one write after beginClear, then resumes', () => {
257 const adapter = createMockPersistence()
258 const { persistor } = createPersistor(adapter)
259​
260 persistor.notifyMessagesChanged([createUIMessage('m-1')])
261 persistor.beginClear()
262 persistor.notifyMessagesChanged([]) // the clear's empty snapshot — skipped
263 persistor.notifyMessagesChanged([createUIMessage('m-2')])
264​
265 expect(adapter.setItem).toHaveBeenCalledTimes(2)
266 })
267​
268 it('swallows a synchronous setItem error', () => {
269 const adapter = createMockPersistence()
270 adapter.setItem = vi.fn(() => {
271 throw new Error('quota exceeded')
272 })
273 const { persistor } = createPersistor(adapter)
274​
275 expect(() =>
276 persistor.notifyMessagesChanged([createUIMessage('m-1')]),
277 ).not.toThrow()
278 })
279​
280 it('runs async writes sequentially (FIFO, no overlap)', async () => {
281 const first = createDeferred<void>()
282 const second = createDeferred<void>()
283 const adapter = createMockPersistence()
284 adapter.setItem = vi
285 .fn()
286 .mockReturnValueOnce(first.promise)
287 .mockReturnValueOnce(second.promise)
288 const { persistor } = createPersistor(adapter)
289​
290 persistor.notifyMessagesChanged([createUIMessage('a')])
291 persistor.notifyMessagesChanged([createUIMessage('b')])
292 // Second write is queued behind the first and must not have started yet.
293 expect(adapter.setItem).toHaveBeenCalledTimes(1)
294​
295 first.resolve()
296 await flushAsync()
297​
298 expect(adapter.setItem).toHaveBeenCalledTimes(2)
299 expect(vi.mocked(adapter.setItem).mock.calls[1]?.[1]).toEqual({
300 messages: [createUIMessage('b')],
301 })
302 })
303​
304 it('keeps writing after an async write rejects', async () => {
305 const adapter = createMockPersistence()
306 adapter.setItem = vi
307 .fn()
308 .mockRejectedValueOnce(new Error('transient'))
309 .mockResolvedValue(undefined)
310 const { persistor } = createPersistor(adapter)
311​
312 persistor.notifyMessagesChanged([createUIMessage('a')])
313 persistor.notifyMessagesChanged([createUIMessage('b')])
314 await flushAsync()
315​
316 expect(adapter.setItem).toHaveBeenCalledTimes(2)
317 })
318 })
319​
320 describe('remove', () => {
321 it('removes the persisted conversation', () => {
322 const adapter = createMockPersistence()
323 const { persistor } = createPersistor(adapter)
324​
325 persistor.remove()
326​
327 expect(adapter.removeItem).toHaveBeenCalledWith(CHAT_ID)
328 })
329​
330 it('swallows a synchronous removeItem error', () => {
331 const adapter = createMockPersistence()
332 adapter.removeItem = vi.fn(() => {
333 throw new Error('locked')
334 })
335 const { persistor } = createPersistor(adapter)
336​
337 expect(() => persistor.remove()).not.toThrow()
338 })
339​
340 it('invalidates a queued write that a removal supersedes', async () => {
341 const inFlight = createDeferred<void>()
342 const adapter = createMockPersistence()
343 adapter.setItem = vi
344 .fn()
345 .mockReturnValueOnce(inFlight.promise) // write A (in flight)
346 .mockResolvedValue(undefined) // write B (would run later)
347 const { persistor } = createPersistor(adapter)
348​
349 persistor.notifyMessagesChanged([createUIMessage('a')]) // starts, in flight
350 persistor.notifyMessagesChanged([createUIMessage('b')]) // queued behind A
351 persistor.remove() // bumps generation, queued behind B
352​
353 inFlight.resolve()
354 await flushAsync()
355​
356 // B's generation was superseded by remove(), so only A was written.
357 expect(adapter.setItem).toHaveBeenCalledTimes(1)
358 expect(adapter.removeItem).toHaveBeenCalledTimes(1)
359 })
360 })
361​
362 describe('clear-during-stream suppression', () => {
363 it('does not ignore chunks before a clear', () => {
364 const { persistor } = createPersistor(createMockPersistence())
365​
366 expect(persistor.shouldIgnoreChunk(runStarted('run-1'))).toBe(false)
367 expect(persistor.shouldIgnoreChunk(textContent('msg-1'))).toBe(false)
368 })
369​
370 it('ignores chunks for a message id captured at clear time', () => {
371 const { persistor } = createPersistor(createMockPersistence())
372 persistor.snapshotClear({
373 messages: [createUIMessage('msg-1')],
374 activeRunIds: new Set(),
375 currentRunId: null,
376 })
377​
378 expect(persistor.shouldIgnoreChunk(textContent('msg-1'))).toBe(true)
379 expect(persistor.shouldIgnoreChunk(textContent('msg-other'))).toBe(false)
380 })
381​
382 it('ignores a RUN_STARTED for an active run captured at clear time', () => {
383 const { persistor } = createPersistor(createMockPersistence())
384 persistor.snapshotClear({
385 messages: [],
386 activeRunIds: new Set(['run-1']),
387 currentRunId: null,
388 })
389​
390 expect(persistor.shouldIgnoreChunk(runStarted('run-1'))).toBe(true)
391 })
392​
393 it('ignores the in-flight currentRunId captured at clear time', () => {
394 const { persistor } = createPersistor(createMockPersistence())
395 persistor.snapshotClear({
396 messages: [],
397 activeRunIds: new Set(),
398 currentRunId: 'run-current',
399 })
400​
401 expect(persistor.shouldIgnoreChunk(runStarted('run-current'))).toBe(true)
402 })
403​
404 it('ignores runless content chunks belonging to a cleared run', () => {
405 const { persistor } = createPersistor(createMockPersistence())
406 persistor.snapshotClear({
407 messages: [],
408 activeRunIds: new Set(['run-1']),
409 currentRunId: null,
410 })
411 // The cleared run starts again, pinning it as the current runless run.
412 persistor.shouldIgnoreChunk(runStarted('run-1'))
413​
414 expect(persistor.shouldIgnoreChunk(textContent('late-msg'))).toBe(true)
415 expect(persistor.shouldIgnoreChunk(messagesSnapshot())).toBe(true)
416 })
417​
418 it.each([
419 { type: 'TEXT_MESSAGE_CHUNK', messageId: 'late-msg', delta: 'hi' },
420 { type: 'TOOL_CALL_CHUNK', toolCallId: 'tc-late', toolCallName: 'x' },
421 ])('ignores a runless $type belonging to a cleared run', (fields) => {
422 const { persistor } = createPersistor(createMockPersistence())
423 persistor.snapshotClear({
424 messages: [],
425 activeRunIds: new Set(['run-1']),
426 currentRunId: null,
427 })
428 persistor.shouldIgnoreChunk(runStarted('run-1'))
429​
430 expect(
431 persistor.shouldIgnoreChunk({
432 ...fields,
433 timestamp: Date.now(),
434 } as StreamChunk),
435 ).toBe(true)
436 })
437​
438 it('ignores tool chunks by cleared parentMessageId and remembers the toolCallId', () => {
439 const { persistor } = createPersistor(createMockPersistence())
440 persistor.snapshotClear({
441 messages: [createUIMessage('parent-msg')],
442 activeRunIds: new Set(),
443 currentRunId: null,
444 })
445​
446 // First seen via its parent message id...
447 expect(
448 persistor.shouldIgnoreChunk(toolCallStart('tc-1', 'parent-msg')),
449 ).toBe(true)
450 // ...then a later chunk for the same tool call (no parent) is still ignored.
451 expect(persistor.shouldIgnoreChunk(toolCallStart('tc-1'))).toBe(true)
452 })
453 })
454​
455 describe('run lifecycle hooks', () => {
456 beforeEach(() => {
457 vi.clearAllMocks()
458 })
459​
460 it('forgets a settled run so a later run with the same id is not ignored', () => {
461 const { persistor } = createPersistor(createMockPersistence())
462 persistor.snapshotClear({
463 messages: [],
464 activeRunIds: new Set(['run-1']),
465 currentRunId: null,
466 })
467 expect(persistor.shouldIgnoreChunk(runStarted('run-1'))).toBe(true)
468​
469 persistor.onRunSettled('run-1')
470​
471 expect(persistor.shouldIgnoreChunk(runStarted('run-1'))).toBe(false)
472 })
473​
474 it('stops ignoring runless chunks after a session-level run error', () => {
475 const { persistor } = createPersistor(createMockPersistence())
476 persistor.snapshotClear({
477 messages: [],
478 activeRunIds: new Set(['run-1']),
479 currentRunId: null,
480 })
481 persistor.shouldIgnoreChunk(runStarted('run-1'))
482 expect(persistor.shouldIgnoreChunk(textContent('late-1'))).toBe(true)
483​
484 persistor.onSessionRunError()
485​
486 // A fresh runless chunk is no longer attributed to the cleared run. (An
487 // already-seen message id stays ignored — shouldIgnoreChunk records it.)
488 expect(persistor.shouldIgnoreChunk(textContent('late-2'))).toBe(false)
489 })
490​
491 it('takeRunlessRunId returns and clears the current runless run, then null', () => {
492 const { persistor } = createPersistor(createMockPersistence())
493 persistor.snapshotClear({
494 messages: [],
495 activeRunIds: new Set(['run-1']),
496 currentRunId: null,
497 })
498 persistor.shouldIgnoreChunk(runStarted('run-1'))
499​
500 expect(persistor.takeRunlessRunId()).toBe('run-1')
501 expect(persistor.takeRunlessRunId()).toBeNull()
502 // The drained run is no longer pinned, so runless chunks aren't ignored.
503 expect(persistor.shouldIgnoreChunk(textContent('late'))).toBe(false)
504 })
505​
506 it('resetIgnored only clears active-run markers, not cleared ids', () => {
507 const { persistor } = createPersistor(createMockPersistence())
508 persistor.snapshotClear({
509 messages: [createUIMessage('msg-1')],
510 activeRunIds: new Set(['run-1']),
511 currentRunId: null,
512 })
513​
514 persistor.resetIgnored()
515​
516 // Cleared run/message ids survive a reset (they outlive the active run).
517 expect(persistor.shouldIgnoreChunk(runStarted('run-1'))).toBe(true)
518 expect(persistor.shouldIgnoreChunk(textContent('msg-1'))).toBe(true)
519 })
520​
521 it('does not ignore an unrelated runId-less run error', () => {
522 const { persistor } = createPersistor(createMockPersistence())
523​
524 expect(persistor.shouldIgnoreChunk(runError())).toBe(false)
525 })
526​
527 it('onRunStarted for a non-cleared run does not suppress runless chunks', () => {
528 const { persistor } = createPersistor(createMockPersistence())
529​
530 // Pinning a live (never-cleared) run must not start swallowing its output.
531 persistor.onRunStarted('run-live')
532​
533 expect(persistor.shouldIgnoreChunk(textContent('content'))).toBe(false)
534 })
535​
536 it('advances the runless pointer when the active run finishes', () => {
537 const { persistor } = createPersistor(createMockPersistence())
538 persistor.snapshotClear({
539 messages: [],
540 activeRunIds: new Set(['run-1', 'run-2']),
541 currentRunId: null,
542 })
543 persistor.shouldIgnoreChunk(runStarted('run-1'))
544 persistor.shouldIgnoreChunk(runStarted('run-2'))
545​
546 // run-2 was the pinned runless run; settling it falls back to run-1.
547 persistor.onRunSettled('run-2')
548​
549 expect(persistor.shouldIgnoreChunk(runFinished('run-2'))).toBe(false)
550 expect(persistor.shouldIgnoreChunk(textContent('late'))).toBe(true)
551 })
552​
553 it('keeps suppressing a second cleared run after the first drains via a runless error', () => {
554 const { persistor } = createPersistor(createMockPersistence())
555 persistor.snapshotClear({
556 messages: [],
557 activeRunIds: new Set(['run-1', 'run-2']),
558 currentRunId: null,
559 })
560 persistor.shouldIgnoreChunk(runStarted('run-1'))
561 persistor.shouldIgnoreChunk(runStarted('run-2')) // run-2 now pinned
562​
563 // A runId-less RUN_ERROR drains the pinned run (run-2)...
564 expect(persistor.takeRunlessRunId()).toBe('run-2')
565​
566 // ...but run-1 is still cleared, so its runless content stays suppressed
567 // instead of leaking through once the pointer advances back to it.
568 expect(persistor.shouldIgnoreChunk(textContent('late-from-run-1'))).toBe(
569 true,
570 )
571 })
572 })
573})