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

state-only.test.ts

99 lines2.8 KB

1import { describe, expect, it } from 'vitest'
2import { EventType, chat } from '@tanstack/ai'
3import type { AnyTextAdapter, StreamChunk } from '@tanstack/ai'
4import { memoryPersistence } from '../src/memory'
5import { withPersistence } from '../src/middleware'
6import { threadMessages } from './persistence-fixtures'
7​
8function mockAdapter(iterations: Array<Array<StreamChunk>>) {
9 const calls: Array<unknown> = []
10 let i = 0
11 const adapter = {
12 kind: 'text',
13 name: 'mock',
14 model: 'test-model',
15 '~types': {},
16 chatStream: (opts: unknown) => {
17 calls.push(opts)
18 const chunks = iterations[i] ?? []
19 i++
20 return (async function* () {
21 for (const c of chunks) yield c
22 })()
23 },
24 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
25 } as unknown as AnyTextAdapter
26 return { adapter, calls }
28​
29const script = (): Array<Array<StreamChunk>> => [
30 [
31 { type: EventType.RUN_STARTED, runId: 'r1', threadId: 't1', timestamp: 1 },
32 {
33 type: EventType.TEXT_MESSAGE_CONTENT,
34 messageId: 'm1',
35 delta: 'hello world',
36 timestamp: 1,
37 },
38 {
39 type: EventType.RUN_FINISHED,
40 runId: 'r1',
41 threadId: 't1',
42 finishReason: 'stop',
43 timestamp: 1,
44 },
45 ],
47​
48async function collect(stream: AsyncIterable<StreamChunk>) {
49 const out: Array<StreamChunk> = []
50 for await (const c of stream) out.push(c)
51 return out
53​
54describe('state-only persistence', () => {
55 it('persists thread messages and run status', async () => {
56 const persistence = memoryPersistence()
57 const { adapter } = mockAdapter(script())
58​
59 await collect(
60 chat({
61 adapter,
62 messages: [{ role: 'user', content: 'hi' }],
63 runId: 'r1',
64 threadId: 't1',
65 middleware: [withPersistence(persistence)],
66 }) as AsyncIterable<StreamChunk>,
67 )
68​
69 expect((await persistence.stores.runs!.get('r1'))?.status).toBe('completed')
70 expect(
71 threadMessages(await persistence.stores.messages!.loadThread('t1'))
72 .length,
73 ).toBeGreaterThan(0)
74 })
75​
76 it('produces chunks byte-identical to a non-persisted run (no cursor)', async () => {
77 const persisted = await collect(
78 chat({
79 adapter: mockAdapter(script()).adapter,
80 messages: [{ role: 'user', content: 'hi' }],
81 runId: 'r1',
82 threadId: 't1',
83 middleware: [withPersistence(memoryPersistence())],
84 }) as AsyncIterable<StreamChunk>,
85 )
86​
87 const plain = await collect(
88 chat({
89 adapter: mockAdapter(script()).adapter,
90 messages: [{ role: 'user', content: 'hi' }],
91 runId: 'r1',
92 threadId: 't1',
93 }) as AsyncIterable<StreamChunk>,
94 )
95​
96 expect(JSON.stringify(persisted)).toEqual(JSON.stringify(plain))
97 expect(persisted.every((c) => !('cursor' in c))).toBe(true)
98 })
99})