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

chat-client-abort.test.ts

425 lines12.0 KB

1import { beforeEach, describe, expect, it, vi } from 'vitest'
2import { EventType } from '@tanstack/ai/client'
3import { ChatClient } from '../src/chat-client'
4import type { ConnectionAdapter } from '../src/connection-adapters'
5import type { StreamChunk } from '@tanstack/ai/client'
6​
7describe('ChatClient - Abort Signal Handling', () => {
8 let mockAdapter: ConnectionAdapter
9 let receivedAbortSignal: AbortSignal | undefined
10​
11 beforeEach(() => {
12 receivedAbortSignal = undefined
13​
14 mockAdapter = {
15 // eslint-disable-next-line @typescript-eslint/require-await
16 async *connect(_messages, _data, abortSignal) {
17 receivedAbortSignal = abortSignal
18​
19 // Simulate streaming chunks (AG-UI format)
20 yield {
21 type: EventType.TEXT_MESSAGE_CONTENT,
22 messageId: '1',
23 model: 'test',
24 timestamp: Date.now(),
25 delta: 'Hello',
26 content: 'Hello',
27 }
28 yield {
29 type: EventType.TEXT_MESSAGE_CONTENT,
30 messageId: '1',
31 model: 'test',
32 timestamp: Date.now(),
33 delta: ' World',
34 content: 'Hello World',
35 }
36 yield {
37 type: EventType.RUN_FINISHED,
38 runId: 'run-1',
39 threadId: 'thread-1',
40 model: 'test',
41 timestamp: Date.now(),
42 metadata: { tanstack: { finishReason: 'stop' } },
43 }
44 },
45 }
46 })
47​
48 it('should create AbortController and pass signal to adapter', async () => {
49 const client = new ChatClient({
50 threadId: 'thread-1',
51 connection: mockAdapter,
52 })
53​
54 const appendPromise = client.append({
55 id: 'user-1',
56 role: 'user',
57 parts: [{ type: 'text', content: 'Hello' }],
58 createdAt: new Date(),
59 })
60​
61 // Wait a bit to ensure connect is called
62 await new Promise((resolve) => setTimeout(resolve, 10))
63​
64 expect(receivedAbortSignal).toBeDefined()
65 expect(receivedAbortSignal).toBeInstanceOf(AbortSignal)
66 expect(receivedAbortSignal?.aborted).toBe(false)
67​
68 await appendPromise
69 })
70​
71 it('should abort request when stop() is called', async () => {
72 let abortControllerRef: AbortController | null = null
73​
74 const adapterWithAbort: ConnectionAdapter = {
75 async *connect(_messages, _data, abortSignal) {
76 abortControllerRef = new AbortController()
77 if (abortSignal) {
78 abortSignal.addEventListener('abort', () => {
79 abortControllerRef?.abort()
80 })
81 }
82​
83 try {
84 yield {
85 type: EventType.TEXT_MESSAGE_CONTENT,
86 messageId: '1',
87 model: 'test',
88 timestamp: Date.now(),
89 delta: 'Hello',
90 content: 'Hello',
91 }
92 // Simulate long-running stream
93 await new Promise((resolve) => setTimeout(resolve, 100))
94 yield {
95 type: EventType.TEXT_MESSAGE_CONTENT,
96 messageId: '1',
97 model: 'test',
98 timestamp: Date.now(),
99 delta: ' World',
100 content: 'Hello World',
101 }
102 } catch (err) {
103 // Abort errors are expected
104 if (err instanceof Error && err.name === 'AbortError') {
105 return
106 }
107 throw err
108 }
109 },
110 }
111​
112 const client = new ChatClient({
113 threadId: 'thread-1',
114 connection: adapterWithAbort,
115 })
116​
117 const appendPromise = client.append({
118 id: 'user-1',
119 role: 'user',
120 parts: [{ type: 'text', content: 'Hello' }],
121 createdAt: new Date(),
122 })
123​
124 // Wait a bit then stop
125 await new Promise((resolve) => setTimeout(resolve, 10))
126 client.stop()
127​
128 await appendPromise
129​
130 expect(client.getIsLoading()).toBe(false)
131 })
132​
133 it('should preserve partial content when aborted', async () => {
134 const chunks: Array<StreamChunk> = []
135 let yieldedChunks = 0
136​
137 const adapterWithPartial: ConnectionAdapter = {
138 // eslint-disable-next-line @typescript-eslint/require-await
139 async *connect(_messages, _data, abortSignal) {
140 yield {
141 type: EventType.TEXT_MESSAGE_CONTENT,
142 messageId: '1',
143 model: 'test',
144 timestamp: Date.now(),
145 delta: 'Hello',
146 content: 'Hello',
147 }
148 yieldedChunks++
149​
150 if (abortSignal?.aborted) {
151 return
152 }
153​
154 yield {
155 type: EventType.TEXT_MESSAGE_CONTENT,
156 messageId: '1',
157 model: 'test',
158 timestamp: Date.now(),
159 delta: ' World',
160 content: 'Hello World',
161 }
162 yieldedChunks++
163 },
164 }
165​
166 const client = new ChatClient({
167 threadId: 'thread-1',
168 connection: adapterWithPartial,
169 onChunk: (chunk) => {
170 chunks.push(chunk)
171 },
172 })
173​
174 const appendPromise = client.append({
175 id: 'user-1',
176 role: 'user',
177 parts: [{ type: 'text', content: 'Hello' }],
178 createdAt: new Date(),
179 })
180​
181 // Wait for first chunk then abort
182 await new Promise((resolve) => setTimeout(resolve, 10))
183 client.stop()
184​
185 await appendPromise
186​
187 // Should have received at least one chunk before abort
188 expect(chunks.length).toBeGreaterThan(0)
189 expect(client.getMessages().length).toBeGreaterThan(0)
190 })
191​
192 it('should handle abort gracefully without throwing error', async () => {
193 const errorSpy = vi.fn()
194​
195 const adapterWithAbort: ConnectionAdapter = {
196 // eslint-disable-next-line @typescript-eslint/require-await
197 async *connect(_messages, _data, abortSignal) {
198 yield {
199 type: EventType.TEXT_MESSAGE_CONTENT,
200 messageId: '1',
201 model: 'test',
202 timestamp: Date.now(),
203 delta: 'Hello',
204 content: 'Hello',
205 }
206​
207 if (abortSignal?.aborted) {
208 return
209 }
210 },
211 }
212​
213 const client = new ChatClient({
214 threadId: 'thread-1',
215 connection: adapterWithAbort,
216 onError: errorSpy,
217 })
218​
219 const appendPromise = client.append({
220 id: 'user-1',
221 role: 'user',
222 parts: [{ type: 'text', content: 'Hello' }],
223 createdAt: new Date(),
224 })
225​
226 await new Promise((resolve) => setTimeout(resolve, 10))
227 client.stop()
228​
229 await appendPromise
230​
231 // Should not have called onError for abort
232 expect(errorSpy).not.toHaveBeenCalled()
233 expect(client.getError()).toBeUndefined()
234 })
235​
236 it('should set isLoading to false after abort', async () => {
237 const adapterWithAbort: ConnectionAdapter = {
238 async *connect(_messages, _data, _abortSignal) {
239 yield {
240 type: EventType.TEXT_MESSAGE_CONTENT,
241 messageId: '1',
242 model: 'test',
243 timestamp: Date.now(),
244 delta: 'Hello',
245 content: 'Hello',
246 }
247 await new Promise((resolve) => setTimeout(resolve, 50))
248 },
249 }
250​
251 const client = new ChatClient({
252 threadId: 'thread-1',
253 connection: adapterWithAbort,
254 })
255​
256 const appendPromise = client.append({
257 id: 'user-1',
258 role: 'user',
259 parts: [{ type: 'text', content: 'Hello' }],
260 createdAt: new Date(),
261 })
262​
263 expect(client.getIsLoading()).toBe(true)
264​
265 await new Promise((resolve) => setTimeout(resolve, 10))
266 client.stop()
267​
268 await appendPromise
269​
270 expect(client.getIsLoading()).toBe(false)
271 })
272​
273 it('should create new AbortController for each request', async () => {
274 const abortSignals: Array<AbortSignal> = []
275​
276 const adapter: ConnectionAdapter = {
277 // eslint-disable-next-line @typescript-eslint/require-await
278 async *connect(_messages, _data, abortSignal) {
279 if (abortSignal) {
280 abortSignals.push(abortSignal)
281 }
282 yield {
283 type: EventType.RUN_FINISHED,
284 runId: 'run-1',
285 threadId: 'thread-1',
286 model: 'test',
287 timestamp: Date.now(),
288 metadata: { tanstack: { finishReason: 'stop' } },
289 }
290 },
291 }
292​
293 const client = new ChatClient({
294 threadId: 'thread-1',
295 connection: adapter,
296 })
297​
298 // First request
299 await client.append({
300 id: 'user-1',
301 role: 'user',
302 parts: [{ type: 'text', content: 'Hello 1' }],
303 createdAt: new Date(),
304 })
305​
306 // Second request
307 await client.append({
308 id: 'user-2',
309 role: 'user',
310 parts: [{ type: 'text', content: 'Hello 2' }],
311 createdAt: new Date(),
312 })
313​
314 expect(abortSignals.length).toBe(2)
315 // Each should be a different signal instance
316 expect(abortSignals[0]).not.toBe(abortSignals[1])
317 })
318​
319 it('should resolve cleanly when stop() is called during onResponse', async () => {
320 let connectCalled = false
321 const errorSpy = vi.fn()
322​
323 const adapter: ConnectionAdapter = {
324 // eslint-disable-next-line @typescript-eslint/require-await
325 async *connect(_messages, _data, _abortSignal) {
326 connectCalled = true
327 yield {
328 type: EventType.RUN_FINISHED,
329 runId: 'run-1',
330 threadId: 'thread-1',
331 model: 'test',
332 timestamp: Date.now(),
333 metadata: { tanstack: { finishReason: 'stop' } },
334 }
335 },
336 }
337​
338 const client = new ChatClient({
339 threadId: 'thread-1',
340 connection: adapter,
341 onError: errorSpy,
342 onResponse: () => {
343 // stop() during the onResponse await aborts the captured signal and
344 // nulls this.abortController. Pre-fix this dereferenced null and
345 // threw a TypeError; with the captured-signal fix and the post-await
346 // signal.aborted check, streamResponse short-circuits cleanly.
347 client.stop()
348 },
349 })
350​
351 await client.append({
352 id: 'user-1',
353 role: 'user',
354 parts: [{ type: 'text', content: 'Hello' }],
355 createdAt: new Date(),
356 })
357​
358 // Cancelled streams must not invoke the connection (no wasted request),
359 // surface no error to user code, and not deadlock the append() promise.
360 expect(connectCalled).toBe(false)
361 expect(errorSpy).not.toHaveBeenCalled()
362 expect(client.getError()).toBeUndefined()
363 expect(client.getIsLoading()).toBe(false)
364 })
365​
366 it('should resolve cleanly when reload() supersedes the stream during onResponse', async () => {
367 const signalsPassedToConnect: Array<AbortSignal> = []
368 let reloadPromise: Promise<unknown> | undefined
369 const errorSpy = vi.fn()
370​
371 const adapter: ConnectionAdapter = {
372 // eslint-disable-next-line @typescript-eslint/require-await
373 async *connect(_messages, _data, abortSignal) {
374 if (abortSignal) {
375 signalsPassedToConnect.push(abortSignal)
376 }
377 yield {
378 type: EventType.RUN_FINISHED,
379 runId: 'run-1',
380 threadId: 'thread-1',
381 model: 'test',
382 timestamp: Date.now(),
383 metadata: { tanstack: { finishReason: 'stop' } },
384 }
385 },
386 }
387​
388 let firstCall = true
389 const client = new ChatClient({
390 threadId: 'thread-1',
391 connection: adapter,
392 onError: errorSpy,
393 onResponse: () => {
394 if (firstCall) {
395 firstCall = false
396 // reload() aborts the in-flight stream's signal and starts a fresh
397 // streamResponse that assigns a new AbortController. Pre-fix, the
398 // first stream re-read this.abortController.signal after this
399 // await and would either crash or pass the second stream's signal
400 // to its own connect() call. With the fix, the first stream
401 // short-circuits because its captured signal was aborted.
402 reloadPromise = client.reload()
403 }
404 },
405 })
406​
407 await client.append({
408 id: 'user-1',
409 role: 'user',
410 parts: [{ type: 'text', content: 'Hello' }],
411 createdAt: new Date(),
412 })
413​
414 await reloadPromise
415​
416 // Only the surviving (reload) stream invokes connect(); the cancelled
417 // first stream short-circuits before reaching the connection layer.
418 // Its signal must be fresh (not the aborted one from the cancelled stream).
419 expect(signalsPassedToConnect.length).toBe(1)
420 expect(signalsPassedToConnect[0]).toBeInstanceOf(AbortSignal)
421 expect(signalsPassedToConnect[0]?.aborted).toBe(false)
422 expect(errorSpy).not.toHaveBeenCalled()
423 expect(client.getError()).toBeUndefined()
424 })
425})