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

chat-client-abort.test.ts

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