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

client-snapshots.test.ts

400 lines13.1 KB

1import { describe, expect, it, vi } from 'vitest'
2import { createMockConnectionAdapter, createTextChunks } from './test-utils'
3import {
4 AudioRecorder,
5 ChatClient,
6 GenerationClient,
7 RealtimeClient,
8 VideoGenerationClient,
9} from '../src'
10import type { RealtimeAdapter, RealtimeConnection } from '@tanstack/ai/client'
11​
12describe('client UI snapshots', () => {
13 it('publishes and clears the active generation run id', async () => {
14 let resolve!: (value: { id: string }) => void
15 const pending = new Promise<{ id: string }>((done) => {
16 resolve = done
17 })
18 const client = new GenerationClient({
19 threadId: 'thread-1',
20 fetcher: async () => pending,
21 })
22​
23 const generating = client.generate({ prompt: 'test' })
24 expect(client.getSnapshot().runId).toEqual(expect.any(String))
25 expect(client.getSnapshot().runId).not.toBe('')
26​
27 resolve({ id: '1' })
28 await generating
29 expect(client.getSnapshot().runId).toBeNull()
30 })
31​
32 it('GenerationClient notifies subscribe and keeps getSnapshot identity until a change', async () => {
33 const client = new GenerationClient({
34 threadId: 'thread-1',
35 fetcher: async () => ({ id: '1' }),
36 })
37 const snapshot = client.getSnapshot()
38 expect(snapshot).toEqual({
39 result: null,
40 isLoading: false,
41 error: undefined,
42 status: 'idle',
43 runId: null,
44 })
45 expect(client.getSnapshot()).toBe(snapshot)
46​
47 const listener = vi.fn()
48 const stop = client.subscribe(listener)
49 await client.generate({ prompt: 'test' })
50​
51 expect(listener).toHaveBeenCalled()
52 expect(client.getSnapshot().status).toBe('success')
53 expect(client.getSnapshot().result).toEqual({ id: '1' })
54 expect(client.getSnapshot()).not.toBe(snapshot)
55 const published = client.getSnapshot().result
56 expect(published).toEqual({ id: '1' })
57 if (published) {
58 Reflect.set(published, 'id', 'mutated')
59 }
60 expect(client.getResult()).toEqual({ id: '1' })
61 expect(Object.isFrozen(published)).toBe(true)
62 expect(client.getSnapshot().result).toEqual({ id: '1' })
63 const calls = listener.mock.calls.length
64 stop()
65 await client.generate({ prompt: 'again' })
66 expect(listener).toHaveBeenCalledTimes(calls)
67 })
68​
69 it('a throwing generation subscriber does not stick isLoading', async () => {
70 const client = new GenerationClient({
71 threadId: 'thread-1',
72 fetcher: async () => ({ id: '1' }),
73 })
74 const error = vi.spyOn(console, 'error').mockImplementation(() => {})
75 const stop = client.subscribe(() => {
76 throw new Error('boom')
77 })
78​
79 await client.generate({ prompt: 'test' })
80​
81 expect(client.getSnapshot().isLoading).toBe(false)
82 expect(client.getSnapshot().status).toBe('success')
83 stop()
84 error.mockRestore()
85 await client.generate({ prompt: 'next' })
86 expect(client.getSnapshot().isLoading).toBe(false)
87 expect(client.getSnapshot().status).toBe('success')
88 })
89​
90 it('a throwing chat snapshot subscriber does not stick isLoading', async () => {
91 const client = new ChatClient({
92 threadId: 'thread-1',
93 connection: createMockConnectionAdapter({
94 chunks: createTextChunks('Hello'),
95 }),
96 })
97 const error = vi.spyOn(console, 'error').mockImplementation(() => {})
98 const second = vi.fn()
99 const stopFirst = client.subscribeSnapshot(() => {
100 throw new Error('listener failed')
101 })
102 const stopSecond = client.subscribeSnapshot(second)
103​
104 await client.sendMessage('Hi')
105​
106 expect(second).toHaveBeenCalled()
107 expect(client.getSnapshot().isLoading).toBe(false)
108 expect(client.getSnapshot().status).toBe('ready')
109 expect(client.getSnapshot().messages.at(-1)?.role).toBe('assistant')
110 stopFirst()
111 stopSecond()
112 error.mockRestore()
113 })
114​
115 it('VideoGenerationClient snapshot includes job fields', async () => {
116 const result = {
117 jobId: 'job-1',
118 status: 'completed' as const,
119 url: 'https://example.com/video.mp4',
120 }
121 const client = new VideoGenerationClient({
122 threadId: 'thread-1',
123 fetcher: async () => result,
124 })
125 const snapshot = client.getSnapshot()
126 expect(snapshot.jobId).toBeNull()
127 expect(snapshot.videoStatus).toBeNull()
128 expect(client.getSnapshot()).toBe(snapshot)
129​
130 const listener = vi.fn()
131 const stop = client.subscribe(listener)
132 await client.generate({ prompt: 'test video' })
133​
134 expect(listener).toHaveBeenCalled()
135 expect(client.getSnapshot().status).toBe('success')
136 expect(client.getSnapshot().result).toEqual(result)
137 expect(client.getSnapshot().jobId).toBe('job-1')
138 expect(client.getSnapshot().videoStatus?.status).toBe('completed')
139 expect(client.getSnapshot()).not.toBe(snapshot)
140 const completed = client.getSnapshot()
141 expect(Object.isFrozen(completed.videoStatus)).toBe(true)
142 Reflect.set(completed.videoStatus!, 'status', 'failed')
143 expect(client.getVideoStatus()?.status).toBe('completed')
144 const calls = listener.mock.calls.length
145 stop()
146 await client.generate({ prompt: 'again' })
147 expect(listener).toHaveBeenCalledTimes(calls)
148 })
149​
150 it('AudioRecorder getSnapshot matches state', () => {
151 const recorder = new AudioRecorder()
152 expect(recorder.getSnapshot()).toBe('idle')
153 expect(recorder.getSnapshot()).toBe(recorder.state)
154 })
155​
156 it('RealtimeClient subscribe fires when connect fails', async () => {
157 const adapter: RealtimeAdapter = {
158 provider: 'test',
159 connect: async () => {
160 throw new Error('unused')
161 },
162 }
163 const client = new RealtimeClient({
164 getToken: async () => {
165 throw new Error('no token')
166 },
167 adapter,
168 })
169 const snapshot = client.getSnapshot()
170 expect(snapshot.status).toBe('idle')
171 expect(client.getSnapshot()).toBe(snapshot)
172​
173 const listener = vi.fn()
174 const stop = client.subscribe(listener)
175 await expect(client.connect()).rejects.toThrow('no token')
176​
177 expect(listener).toHaveBeenCalled()
178 expect(client.getSnapshot().status).toBe('error')
179 expect(client.getSnapshot()).not.toBe(snapshot)
180 const calls = listener.mock.calls.length
181 stop()
182 await expect(client.connect()).rejects.toThrow('no token')
183 expect(listener).toHaveBeenCalledTimes(calls)
184 client.destroy()
185 })
186​
187 it('RealtimeClient does not read connection control from its public snapshot', async () => {
188 const getToken = vi.fn(async () => {
189 throw new Error('token attempted')
190 })
191 const client = new RealtimeClient({
192 getToken,
193 adapter: { provider: 'test', connect: vi.fn() },
194 })
195​
196 Reflect.set(client.getSnapshot(), 'status', 'connected')
197 await expect(client.connect()).rejects.toThrow('token attempted')
198 expect(getToken).toHaveBeenCalledOnce()
199 })
200​
201 it('RealtimeClient isolates connection control from state change callbacks', async () => {
202 const getToken = vi.fn(async () => ({
203 provider: 'test',
204 token: 'token',
205 expiresAt: Date.now() + 120_000,
206 config: {},
207 }))
208 const connect = vi.fn(async () => {
209 throw new Error('connect attempted')
210 })
211 const client = new RealtimeClient({
212 getToken,
213 adapter: { provider: 'test', connect },
214 })
215 client.onStateChange((state) => {
216 Reflect.set(state, 'status', 'connected')
217 })
218​
219 await expect(client.connect()).rejects.toThrow('connect attempted')
220 await expect(client.connect()).rejects.toThrow('connect attempted')
221​
222 expect(getToken).toHaveBeenCalledTimes(2)
223 expect(connect).toHaveBeenCalledTimes(2)
224 })
225​
226 it('keeps the transcript when connect fails and clears it after a later success', async () => {
227 let connects = 0
228 const connection: RealtimeConnection = {
229 disconnect: async () => {},
230 startAudioCapture: async () => {},
231 stopAudioCapture: () => {},
232 sendText: () => {},
233 sendImage: () => {},
234 sendToolResult: () => {},
235 updateSession: () => {},
236 interrupt: () => {},
237 on: () => () => {},
238 getAudioVisualization: () => ({
239 inputLevel: 0,
240 outputLevel: 0,
241 getInputFrequencyData: () => new Uint8Array(),
242 getOutputFrequencyData: () => new Uint8Array(),
243 getInputTimeDomainData: () => new Uint8Array(),
244 getOutputTimeDomainData: () => new Uint8Array(),
245 inputSampleRate: 0,
246 outputSampleRate: 0,
247 }),
248 }
249 const client = new RealtimeClient({
250 getToken: async () => {
251 connects++
252 if (connects === 2) throw new Error('no token')
253 return {
254 provider: 'test',
255 token: 'token',
256 expiresAt: Date.now() + 120_000,
257 config: {},
258 }
259 },
260 adapter: { provider: 'test', connect: async () => connection },
261 autoCapture: false,
262 })
263​
264 await client.connect()
265 client.sendText('keep me')
266 expect(client.getSnapshot().messages).toHaveLength(1)
267 await client.disconnect()
268 expect(client.getSnapshot().messages).toHaveLength(1)
269​
270 await expect(client.connect()).rejects.toThrow('no token')
271 expect(client.getSnapshot().status).toBe('error')
272 expect(client.getSnapshot().messages).toHaveLength(1)
273​
274 await client.connect()
275 expect(client.getSnapshot().status).toBe('connected')
276 expect(client.getSnapshot().messages).toEqual([])
277 client.destroy()
278 })
279​
280 it('RealtimeClient keeps a transcript that arrives while audio capture starts', async () => {
281 const handlers = new Map<string, (payload: any) => void>()
282 const connection: RealtimeConnection = {
283 disconnect: async () => {},
284 // The provider greets the user while the mic permission prompt is open.
285 startAudioCapture: async () => {
286 handlers.get('transcript')?.({
287 role: 'assistant',
288 transcript: 'Hello',
289 isFinal: false,
290 })
291 },
292 stopAudioCapture: () => {},
293 sendText: () => {},
294 sendImage: () => {},
295 sendToolResult: () => {},
296 updateSession: () => {},
297 interrupt: () => {},
298 on: (event: string, handler: (payload: any) => void) => {
299 handlers.set(event, handler)
300 return () => handlers.delete(event)
301 },
302 getAudioVisualization: () => ({
303 inputLevel: 0,
304 outputLevel: 0,
305 getInputFrequencyData: () => new Uint8Array(),
306 getOutputFrequencyData: () => new Uint8Array(),
307 getInputTimeDomainData: () => new Uint8Array(),
308 getOutputTimeDomainData: () => new Uint8Array(),
309 inputSampleRate: 0,
310 outputSampleRate: 0,
311 }),
312 } as RealtimeConnection
313 const client = new RealtimeClient({
314 getToken: async () => ({
315 provider: 'test',
316 token: 'token',
317 expiresAt: Date.now() + 120_000,
318 config: {},
319 }),
320 adapter: { provider: 'test', connect: async () => connection },
321 })
322​
323 await client.connect()
324​
325 expect(client.getSnapshot().status).toBe('connected')
326 expect(client.getSnapshot().pendingAssistantTranscript).toBe('Hello')
327 client.destroy()
328 })
329​
330 it('RealtimeClient state change callbacks are isolated from a throwing one', async () => {
331 const client = new RealtimeClient({
332 getToken: async () => {
333 throw new Error('no token')
334 },
335 adapter: { provider: 'test', connect: vi.fn() },
336 })
337 const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
338 const seen: Array<string> = []
339 client.onStateChange(() => {
340 throw new Error('listener failed')
341 })
342 client.onStateChange((state) => seen.push(state.status))
343​
344 await expect(client.connect()).rejects.toThrow('no token')
345​
346 expect(seen).toEqual(['connecting', 'error'])
347 expect(consoleError).toHaveBeenCalledWith(new Error('listener failed'))
348 consoleError.mockRestore()
349 })
350​
351 it('RealtimeClient keeps the identity of unchanged messages across snapshots', async () => {
352 const connection: RealtimeConnection = {
353 disconnect: async () => {},
354 startAudioCapture: async () => {},
355 stopAudioCapture: () => {},
356 sendText: () => {},
357 sendImage: () => {},
358 sendToolResult: () => {},
359 updateSession: () => {},
360 interrupt: () => {},
361 on: () => () => {},
362 getAudioVisualization: () => ({
363 inputLevel: 0,
364 outputLevel: 0,
365 getInputFrequencyData: () => new Uint8Array(),
366 getOutputFrequencyData: () => new Uint8Array(),
367 getInputTimeDomainData: () => new Uint8Array(),
368 getOutputTimeDomainData: () => new Uint8Array(),
369 inputSampleRate: 0,
370 outputSampleRate: 0,
371 }),
372 }
373 const client = new RealtimeClient({
374 getToken: async () => ({
375 provider: 'test',
376 token: 'token',
377 expiresAt: Date.now() + 120_000,
378 config: {},
379 }),
380 adapter: { provider: 'test', connect: async () => connection },
381 autoCapture: false,
382 })
383 await client.connect()
384​
385 client.sendText('first')
386 const first = client.getSnapshot().messages[0]
387 client.sendText('second')
388​
389 const messages = client.getSnapshot().messages
390 expect(messages).toHaveLength(2)
391 expect(messages[0]).toBe(first)
392 expect(Object.isFrozen(first)).toBe(true)
393​
394 // A state change that is not a message change keeps the same array.
395 client.stopListening()
396 expect(client.getSnapshot().mode).toBe('idle')
397 expect(client.getSnapshot().messages).toBe(messages)
398 client.destroy()
399 })
400})