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

client-snapshots.test.ts

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