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