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

chat-client-queue.test.ts

909 lines27.9 KB

1import { describe, expect, it, vi } from 'vitest'
2import { EventType } from '@tanstack/ai/client'
3import { ChatClient, normalizeQueueOption } from '../src/chat-client'
4import { createTextChunks } from './test-utils'
5import type { ConnectConnectionAdapter } from '../src/connection-adapters'
6import type { StreamChunk } from '@tanstack/ai/client'
7​
8describe('normalizeQueueOption', () => {
9 it('defaults to queue + fifo + reject', () => {
10 expect(normalizeQueueOption(undefined)).toEqual({
11 whenBusy: 'queue',
12 drain: 'fifo',
13 onOverflow: 'reject',
14 })
15 })
16​
17 it('treats a string as whenBusy shorthand', () => {
18 expect(normalizeQueueOption('interrupt')).toMatchObject({
19 whenBusy: 'interrupt',
20 drain: 'fifo',
21 })
22 })
23​
24 it('carries a function as strategy and forces fifo', () => {
25 const fn = () => ({ action: 'queue' as const })
26 const cfg = normalizeQueueOption(fn)
27 expect(cfg.strategy).toBe(fn)
28 expect(cfg.drain).toBe('fifo')
29 })
30​
31 it('merges a config object over defaults', () => {
32 expect(normalizeQueueOption({ whenBusy: 'drop', maxSize: 3 })).toEqual({
33 whenBusy: 'drop',
34 drain: 'fifo',
35 onOverflow: 'reject',
36 maxSize: 3,
37 })
38 })
39​
40 it('rejects invalid maxSize', () => {
41 expect(() => normalizeQueueOption({ maxSize: -1 })).toThrow(/maxSize/)
42 expect(() => normalizeQueueOption({ maxSize: 1.5 })).toThrow(/maxSize/)
43 })
44})
45​
46/**
47 * Creates a deferred promise. `resolve` releases anything awaiting `promise`.
48 */
49function createDeferred<T>() {
50 let resolve!: (value: T) => void
51 const promise = new Promise<T>((promiseResolve) => {
52 resolve = promiseResolve
53 })
54 return { promise, resolve }
56​
57/**
58 * A `ConnectConnectionAdapter` whose stream stays open (keeping `isLoading`
59 * true) until `release()` is called, at which point it finishes with a
60 * simple text response.
61 */
62function createHoldingConnection(): {
63 connection: ConnectConnectionAdapter
64 release: () => void
65} {
66 const deferred = createDeferred<void>()
67 const connection: ConnectConnectionAdapter = {
68 async *connect() {
69 await deferred.promise
70 yield* createTextChunks('done', 'msg-1')
71 },
72 }
73 return { connection, release: () => deferred.resolve() }
75​
76describe('ChatClient message queue', () => {
77 it('enqueues (not drops) a send while streaming and reports via onQueueChange', async () => {
78 const { connection, release } = createHoldingConnection()
79 const onQueueChange = vi.fn()
80 const client = new ChatClient({
81 threadId: 'thread-1',
82 connection,
83 onQueueChange,
84 })
85​
86 const firstSend = client.sendMessage('first')
87 await vi.waitFor(() => {
88 expect(client.getIsLoading()).toBe(true)
89 })
90​
91 await client.sendMessage('second')
92​
93 const queue = client.getQueue()
94 expect(queue).toHaveLength(1)
95 expect(queue[0]?.content).toBe('second')
96 expect(onQueueChange).toHaveBeenCalledWith(
97 expect.arrayContaining([expect.objectContaining({ content: 'second' })]),
98 )
99 expect(onQueueChange.mock.calls.at(-1)?.[0]).toHaveLength(1)
100​
101 release()
102 await firstSend
103 })
104​
105 it('cancelQueued removes a queued item before it drains', async () => {
106 const { connection, release } = createHoldingConnection()
107 const client = new ChatClient({ threadId: 'thread-1', connection })
108​
109 const firstSend = client.sendMessage('first')
110 await vi.waitFor(() => {
111 expect(client.getIsLoading()).toBe(true)
112 })
113​
114 await client.sendMessage('second')
115 const queued = client.getQueue()
116 expect(queued).toHaveLength(1)
117 const queuedId = queued[0]!.id
118​
119 client.cancelQueued(queuedId)
120 expect(client.getQueue()).toEqual([])
121​
122 release()
123 await firstSend
124 })
125​
126 it("whenBusy: 'drop' ignores a mid-stream send", async () => {
127 const { connection, release } = createHoldingConnection()
128 const client = new ChatClient({
129 threadId: 'thread-1',
130 connection,
131 queue: 'drop',
132 })
133​
134 const firstSend = client.sendMessage('first')
135 await vi.waitFor(() => {
136 expect(client.getIsLoading()).toBe(true)
137 })
138​
139 await client.sendMessage('second')
140 expect(client.getQueue()).toEqual([])
141​
142 release()
143 await firstSend
144​
145 // The dropped message must never have become a real message either —
146 // it should be gone entirely, not just missing from the queue.
147 const userMessages = client.getMessages().filter((m) => m.role === 'user')
148 expect(userMessages.map((m) => m.parts[0])).toEqual([
149 { type: 'text', content: 'first' },
150 ])
151 })
152})
153​
154/**
155 * Like {@link createHoldingConnection}, but only the first `connect()` call
156 * waits on the deferred; every subsequent call (i.e. a drained queue item's
157 * own send) resolves immediately with a unique messageId so chained drains
158 * don't collide on the same assistant message id.
159 */
160function createSequencedHoldingConnection(): {
161 connection: ConnectConnectionAdapter
162 release: () => void
163} {
164 const deferred = createDeferred<void>()
165 let call = 0
166 const connection: ConnectConnectionAdapter = {
167 async *connect() {
168 call += 1
169 if (call === 1) {
170 await deferred.promise
171 }
172 yield* createTextChunks('done', `msg-${call}`)
173 },
174 }
175 return { connection, release: () => deferred.resolve() }
177​
178/**
179 * Like {@link createHoldingConnection}, but `release()` settles the stream
180 * with a `RUN_ERROR` chunk instead of a successful text response.
181 */
182function createErroringHoldingConnection(): {
183 connection: ConnectConnectionAdapter
184 release: () => void
185} {
186 const deferred = createDeferred<void>()
187 const connection: ConnectConnectionAdapter = {
188 async *connect(): AsyncGenerator<StreamChunk> {
189 await deferred.promise
190 yield {
191 type: EventType.RUN_ERROR,
192 threadId: 'thread-1',
193 timestamp: Date.now(),
194 message: 'boom',
195 error: { message: 'boom' },
196 }
197 },
198 }
199 return { connection, release: () => deferred.resolve() }
201​
202describe('ChatClient queue drain', () => {
203 it('drains FIFO after the stream settles, in order', async () => {
204 const { connection, release } = createSequencedHoldingConnection()
205 const client = new ChatClient({ threadId: 'thread-1', connection })
206​
207 const firstSend = client.sendMessage('first')
208 await vi.waitFor(() => {
209 expect(client.getIsLoading()).toBe(true)
210 })
211​
212 await client.sendMessage('second')
213 await client.sendMessage('third')
214 expect(client.getQueue().map((m) => m.content)).toEqual(['second', 'third'])
215​
216 release()
217 await firstSend
218​
219 expect(client.getQueue()).toEqual([])
220 const userMessages = client.getMessages().filter((m) => m.role === 'user')
221 expect(userMessages.map((m) => m.parts[0])).toEqual([
222 { type: 'text', content: 'first' },
223 { type: 'text', content: 'second' },
224 { type: 'text', content: 'third' },
225 ])
226 })
227​
228 it('batch drain merges string queued items with newlines', async () => {
229 const { connection, release } = createSequencedHoldingConnection()
230 const client = new ChatClient({
231 threadId: 'thread-1',
232 connection,
233 queue: { drain: 'batch' },
234 })
235​
236 const firstSend = client.sendMessage('first')
237 await vi.waitFor(() => {
238 expect(client.getIsLoading()).toBe(true)
239 })
240​
241 await client.sendMessage('a')
242 await client.sendMessage('b')
243 expect(client.getQueue().map((m) => m.content)).toEqual(['a', 'b'])
244​
245 release()
246 await firstSend
247​
248 expect(client.getQueue()).toEqual([])
249 const userMessages = client.getMessages().filter((m) => m.role === 'user')
250 expect(userMessages).toHaveLength(2)
251 expect(userMessages[1]?.parts[0]).toEqual({
252 type: 'text',
253 content: 'a\nb',
254 })
255 })
256​
257 it('batch drain flattens multimodal queued items into ContentPart[]', async () => {
258 const { connection, release } = createSequencedHoldingConnection()
259 const client = new ChatClient({
260 threadId: 'thread-1',
261 connection,
262 queue: { drain: 'batch' },
263 })
264​
265 const firstSend = client.sendMessage('first')
266 await vi.waitFor(() => {
267 expect(client.getIsLoading()).toBe(true)
268 })
269​
270 // Queued item 1: multimodal content (array of ContentPart).
271 await client.sendMessage({
272 content: [
273 { type: 'text', content: 'look' },
274 {
275 type: 'image',
276 source: { type: 'url', value: 'https://example.com/a.png' },
277 },
278 ],
279 })
280 // Queued item 2: plain string content.
281 await client.sendMessage('note')
282 expect(client.getQueue()).toHaveLength(2)
283​
284 release()
285 await firstSend
286​
287 expect(client.getQueue()).toEqual([])
288 const userMessages = client.getMessages().filter((m) => m.role === 'user')
289 // 'first' streamed immediately; the two queued sends above are merged
290 // into a single batched send, so there should be exactly 2 user messages.
291 expect(userMessages).toHaveLength(2)
292 // The merged message's parts must be the multimodal item's parts
293 // (flattened, in order) followed by the string item flattened to text —
294 // proving the MULTIMODAL branch of `mergeQueuedMessages` ran, not just
295 // the all-string join.
296 expect(userMessages[1]?.parts).toEqual([
297 { type: 'text', content: 'look' },
298 {
299 type: 'image',
300 source: { type: 'url', value: 'https://example.com/a.png' },
301 },
302 { type: 'text', content: 'note' },
303 ])
304 })
305​
306 it('flushes the queue on stop()', async () => {
307 const { connection, release } = createHoldingConnection()
308 const client = new ChatClient({ threadId: 'thread-1', connection })
309​
310 const firstSend = client.sendMessage('first')
311 await vi.waitFor(() => {
312 expect(client.getIsLoading()).toBe(true)
313 })
314​
315 await client.sendMessage('second')
316 expect(client.getQueue()).toHaveLength(1)
317​
318 client.stop()
319 expect(client.getQueue()).toEqual([])
320​
321 // Let the held-open stream settle so it doesn't leak into other tests.
322 release()
323 await firstSend
324 })
325​
326 it('flushes the queue when the stream errors', async () => {
327 const { connection, release } = createErroringHoldingConnection()
328 const client = new ChatClient({ threadId: 'thread-1', connection })
329​
330 const firstSend = client.sendMessage('first')
331 await vi.waitFor(() => {
332 expect(client.getIsLoading()).toBe(true)
333 })
334​
335 await client.sendMessage('second')
336 expect(client.getQueue()).toHaveLength(1)
337​
338 release()
339 await firstSend
340​
341 // The queue must be flushed, not stranded or auto-drained into the
342 // now-broken endpoint.
343 expect(client.getQueue()).toEqual([])
344 const userMessages = client.getMessages().filter((m) => m.role === 'user')
345 expect(userMessages.map((m) => m.parts[0])).toEqual([
346 { type: 'text', content: 'first' },
347 ])
348 })
349​
350 it('flushes the queue on clear()', async () => {
351 const { connection, release } = createHoldingConnection()
352 const client = new ChatClient({ threadId: 'thread-1', connection })
353​
354 const firstSend = client.sendMessage('first')
355 await vi.waitFor(() => {
356 expect(client.getIsLoading()).toBe(true)
357 })
358​
359 await client.sendMessage('second')
360 expect(client.getQueue()).toHaveLength(1)
361​
362 client.clear()
363 expect(client.getQueue()).toEqual([])
364​
365 release()
366 await firstSend
367 })
368})
369​
370describe('ChatClient queue policy branches', () => {
371 it("whenBusy: 'interrupt' aborts the in-flight stream and sends immediately", async () => {
372 const { connection, release } = createSequencedHoldingConnection()
373 const client = new ChatClient({
374 threadId: 'thread-1',
375 connection,
376 queue: 'interrupt',
377 })
378​
379 const firstSend = client.sendMessage('first')
380 await vi.waitFor(() => {
381 expect(client.getIsLoading()).toBe(true)
382 })
383​
384 const secondSend = client.sendMessage('urgent')
385 // Interrupt does not enqueue.
386 expect(client.getQueue()).toEqual([])
387​
388 // The interrupting send should be in messages immediately (and loading).
389 await vi.waitFor(() => {
390 const users = client.getMessages().filter((m) => m.role === 'user')
391 expect(users.map((m) => m.parts[0])).toEqual([
392 { type: 'text', content: 'first' },
393 { type: 'text', content: 'urgent' },
394 ])
395 })
396​
397 release()
398 await Promise.all([firstSend, secondSend])
399​
400 expect(client.getQueue()).toEqual([])
401 })
402​
403 it('per-call whenBusy override beats the client default', async () => {
404 const { connection, release } = createSequencedHoldingConnection()
405 // Default is queue; override one send to interrupt.
406 const client = new ChatClient({ threadId: 'thread-1', connection })
407​
408 const firstSend = client.sendMessage('first')
409 await vi.waitFor(() => {
410 expect(client.getIsLoading()).toBe(true)
411 })
412​
413 await client.sendMessage('queued-one')
414 expect(client.getQueue()).toHaveLength(1)
415​
416 const interruptSend = client.sendMessage('urgent', undefined, {
417 whenBusy: 'interrupt',
418 })
419 // Interrupt does not flush existing queue; item stays pending.
420 expect(client.getQueue()).toHaveLength(1)
421​
422 release()
423 await Promise.all([firstSend, interruptSend])
424​
425 // After interrupt settles, the previously queued item drains.
426 await vi.waitFor(() => {
427 expect(client.getQueue()).toEqual([])
428 })
429​
430 const userMessages = client.getMessages().filter((m) => m.role === 'user')
431 expect(userMessages.map((m) => m.parts[0])).toEqual([
432 { type: 'text', content: 'first' },
433 { type: 'text', content: 'urgent' },
434 { type: 'text', content: 'queued-one' },
435 ])
436 })
437​
438 it("maxSize + onOverflow: 'reject' drops the newest when full", async () => {
439 const { connection, release } = createHoldingConnection()
440 const client = new ChatClient({
441 threadId: 'thread-1',
442 connection,
443 queue: { maxSize: 1, onOverflow: 'reject' },
444 })
445​
446 const firstSend = client.sendMessage('first')
447 await vi.waitFor(() => {
448 expect(client.getIsLoading()).toBe(true)
449 })
450​
451 await client.sendMessage('a')
452 await client.sendMessage('b')
453 expect(client.getQueue().map((m) => m.content)).toEqual(['a'])
454​
455 release()
456 await firstSend
457 })
458​
459 it("maxSize + onOverflow: 'drop-oldest' rotates the queue", async () => {
460 const { connection, release } = createHoldingConnection()
461 const client = new ChatClient({
462 threadId: 'thread-1',
463 connection,
464 queue: { maxSize: 1, onOverflow: 'drop-oldest' },
465 })
466​
467 const firstSend = client.sendMessage('first')
468 await vi.waitFor(() => {
469 expect(client.getIsLoading()).toBe(true)
470 })
471​
472 await client.sendMessage('a')
473 await client.sendMessage('b')
474 expect(client.getQueue().map((m) => m.content)).toEqual(['b'])
475​
476 release()
477 await firstSend
478 })
479​
480 it('maxSize: 0 never enqueues under drop-oldest', async () => {
481 const { connection, release } = createHoldingConnection()
482 const client = new ChatClient({
483 threadId: 'thread-1',
484 connection,
485 queue: { maxSize: 0, onOverflow: 'drop-oldest' },
486 })
487​
488 const firstSend = client.sendMessage('first')
489 await vi.waitFor(() => {
490 expect(client.getIsLoading()).toBe(true)
491 })
492​
493 await client.sendMessage('should-not-queue')
494 expect(client.getQueue()).toEqual([])
495​
496 release()
497 await firstSend
498 })
499​
500 it('QueueStrategy pending.id matches the enqueued item id', async () => {
501 const { connection, release } = createHoldingConnection()
502 let seenId: string | undefined
503 let seenBusyReason: string | undefined
504 const client = new ChatClient({
505 threadId: 'thread-1',
506 connection,
507 queue: ({ pending, busyReason }) => {
508 seenId = pending.id
509 seenBusyReason = busyReason
510 return { action: 'queue' }
511 },
512 })
513​
514 const firstSend = client.sendMessage('first')
515 await vi.waitFor(() => {
516 expect(client.getIsLoading()).toBe(true)
517 })
518​
519 await client.sendMessage('second')
520 const queue = client.getQueue()
521 expect(queue).toHaveLength(1)
522 expect(seenId).toBe(queue[0]?.id)
523 expect(seenBusyReason).toBe('streaming')
524​
525 // cancelQueued with the strategy-visible id must work.
526 client.cancelQueued(seenId!)
527 expect(client.getQueue()).toEqual([])
528​
529 release()
530 await firstSend
531 })
532​
533 it('QueueStrategy drop and per-call whenBusy override', async () => {
534 const { connection, release } = createHoldingConnection()
535 const client = new ChatClient({
536 threadId: 'thread-1',
537 connection,
538 queue: () => ({ action: 'drop' }),
539 })
540​
541 const firstSend = client.sendMessage('first')
542 await vi.waitFor(() => {
543 expect(client.getIsLoading()).toBe(true)
544 })
545​
546 await client.sendMessage('ignored-by-strategy')
547 expect(client.getQueue()).toEqual([])
548​
549 // Per-call override beats strategy.
550 await client.sendMessage('queued-via-override', undefined, {
551 whenBusy: 'queue',
552 })
553 expect(client.getQueue().map((m) => m.content)).toEqual([
554 'queued-via-override',
555 ])
556​
557 release()
558 await firstSend
559 })
560​
561 it('concurrent rapid sends do not strand user messages without streams', async () => {
562 const { connection, release } = createSequencedHoldingConnection()
563 const client = new ChatClient({ threadId: 'thread-1', connection })
564​
565 // Fire several sends without awaiting between them (composer spam).
566 const sends = [
567 client.sendMessage('first'),
568 client.sendMessage('second'),
569 client.sendMessage('third'),
570 ]
571​
572 await vi.waitFor(() => {
573 expect(client.getIsLoading()).toBe(true)
574 })
575​
576 // While the first stream is open, at least one of the later sends must be
577 // sitting in the queue (not all three racing as concurrent streams).
578 await vi.waitFor(() => {
579 expect(client.getQueue().length).toBeGreaterThanOrEqual(1)
580 })
581​
582 release()
583 await Promise.all(sends)
584​
585 // Every user message must have been delivered with no stranded leftovers
586 // in the queue, and all three must appear in order.
587 expect(client.getQueue()).toEqual([])
588 const userMessages = client.getMessages().filter((m) => m.role === 'user')
589 expect(userMessages.map((m) => m.parts[0])).toEqual([
590 { type: 'text', content: 'first' },
591 { type: 'text', content: 'second' },
592 { type: 'text', content: 'third' },
593 ])
594 // Each user message should have a corresponding assistant reply after
595 // the full FIFO drain completes.
596 const assistantMessages = client
597 .getMessages()
598 .filter((m) => m.role === 'assistant')
599 expect(assistantMessages.length).toBe(3)
600 })
601​
602 it('flushes the queue on reload()', async () => {
603 const { connection, release } = createSequencedHoldingConnection()
604 const client = new ChatClient({ threadId: 'thread-1', connection })
605​
606 const firstSend = client.sendMessage('first')
607 await vi.waitFor(() => {
608 expect(client.getIsLoading()).toBe(true)
609 })
610​
611 await client.sendMessage('queued')
612 expect(client.getQueue()).toHaveLength(1)
613​
614 // Reload while the first stream is held open and something is queued.
615 const reloadPromise = client.reload()
616 expect(client.getQueue()).toEqual([])
617​
618 release()
619 await Promise.all([firstSend, reloadPromise])
620 expect(client.getQueue()).toEqual([])
621 })
622​
623 it('flushes the queue on unsubscribe()', async () => {
624 const { connection, release } = createHoldingConnection()
625 const client = new ChatClient({ threadId: 'thread-1', connection })
626​
627 const firstSend = client.sendMessage('first')
628 await vi.waitFor(() => {
629 expect(client.getIsLoading()).toBe(true)
630 })
631​
632 await client.sendMessage('queued')
633 expect(client.getQueue()).toHaveLength(1)
634​
635 client.unsubscribe()
636 expect(client.getQueue()).toEqual([])
637​
638 release()
639 await firstSend
640 })
641​
642 it('preserves per-message body through FIFO drain and batch last-wins', async () => {
643 const seenBodies: Array<Record<string, unknown> | undefined> = []
644 const deferred = createDeferred<void>()
645 let call = 0
646 const connection: ConnectConnectionAdapter = {
647 async *connect(_messages, data) {
648 call += 1
649 seenBodies.push(
650 data && typeof data === 'object'
651 ? (data as Record<string, unknown>)
652 : undefined,
653 )
654 if (call === 1) {
655 await deferred.promise
656 }
657 yield* createTextChunks('done', `msg-${call}`)
658 },
659 }
660​
661 // FIFO: each drained send keeps its own body.
662 const fifoClient = new ChatClient({ threadId: 'thread-1', connection })
663 const firstFifo = fifoClient.sendMessage('first', { tag: 'seed' })
664 await vi.waitFor(() => {
665 expect(fifoClient.getIsLoading()).toBe(true)
666 })
667 await fifoClient.sendMessage('a', { tag: 'a' })
668 await fifoClient.sendMessage('b', { tag: 'b' })
669 deferred.resolve()
670 await firstFifo
671 await vi.waitFor(() => {
672 expect(fifoClient.getQueue()).toEqual([])
673 })
674 // First send + two drained: tags seed, a, b (merged with base body).
675 expect(seenBodies.map((b) => b?.tag)).toEqual(['seed', 'a', 'b'])
676​
677 // Batch: last item's body wins.
678 seenBodies.length = 0
679 call = 0
680 const deferredBatch = createDeferred<void>()
681 const batchConnection: ConnectConnectionAdapter = {
682 async *connect(_messages, data) {
683 call += 1
684 seenBodies.push(
685 data && typeof data === 'object'
686 ? (data as Record<string, unknown>)
687 : undefined,
688 )
689 if (call === 1) {
690 await deferredBatch.promise
691 }
692 yield* createTextChunks('done', `batch-${call}`)
693 },
694 }
695 const batchClient = new ChatClient({
696 threadId: 'thread-1',
697 connection: batchConnection,
698 queue: { drain: 'batch' },
699 })
700 const firstBatch = batchClient.sendMessage('first', { tag: 'seed' })
701 await vi.waitFor(() => {
702 expect(batchClient.getIsLoading()).toBe(true)
703 })
704 await batchClient.sendMessage('x', { tag: 'x' })
705 await batchClient.sendMessage('y', { tag: 'y' })
706 deferredBatch.resolve()
707 await firstBatch
708 await vi.waitFor(() => {
709 expect(batchClient.getQueue()).toEqual([])
710 })
711 expect(seenBodies.map((b) => b?.tag)).toEqual(['seed', 'y'])
712 })
713​
714 it('preserves sendOptions.body for queued sends', async () => {
715 const seenBodies: Array<Record<string, unknown> | undefined> = []
716 const deferred = createDeferred<void>()
717 let call = 0
718 const connection: ConnectConnectionAdapter = {
719 async *connect(_messages, data) {
720 call += 1
721 seenBodies.push(
722 data && typeof data === 'object'
723 ? (data as Record<string, unknown>)
724 : undefined,
725 )
726 if (call === 1) {
727 await deferred.promise
728 }
729 yield* createTextChunks('done', `msg-${call}`)
730 },
731 }
732​
733 // Hook-style calls: body rides in sendOptions, positional arg unused.
734 const client = new ChatClient({ threadId: 'thread-1', connection })
735 const firstSend = client.sendMessage('first', undefined, {
736 body: { tag: 'seed' },
737 })
738 await vi.waitFor(() => {
739 expect(client.getIsLoading()).toBe(true)
740 })
741 await client.sendMessage('a', undefined, { body: { tag: 'a' } })
742 deferred.resolve()
743 await firstSend
744 await vi.waitFor(() => {
745 expect(client.getQueue()).toEqual([])
746 })
747 expect(seenBodies.map((b) => b?.tag)).toEqual(['seed', 'a'])
748 })
749​
750 it('batch drain does not strand messages enqueued during the batch stream', async () => {
751 const deferred1 = createDeferred<void>()
752 const deferred2 = createDeferred<void>()
753 let call = 0
754 const connection: ConnectConnectionAdapter = {
755 async *connect() {
756 call += 1
757 if (call === 1) {
758 await deferred1.promise
759 } else if (call === 2) {
760 await deferred2.promise
761 }
762 yield* createTextChunks('done', `msg-${call}`)
763 },
764 }
765 const client = new ChatClient({
766 threadId: 'thread-1',
767 connection,
768 queue: { drain: 'batch' },
769 })
770​
771 const firstSend = client.sendMessage('first')
772 await vi.waitFor(() => {
773 expect(client.getIsLoading()).toBe(true)
774 })
775 await client.sendMessage('a')
776 await client.sendMessage('b')
777​
778 deferred1.resolve()
779 // Wait until the batch of a+b is streaming.
780 await vi.waitFor(() => {
781 const users = client.getMessages().filter((m) => m.role === 'user')
782 expect(users).toHaveLength(2)
783 expect(users[1]?.parts[0]).toEqual({ type: 'text', content: 'a\nb' })
784 expect(client.getIsLoading()).toBe(true)
785 })
786​
787 await client.sendMessage('during-batch')
788 expect(client.getQueue().map((m) => m.content)).toEqual(['during-batch'])
789​
790 deferred2.resolve()
791 await firstSend
792 await vi.waitFor(() => {
793 expect(client.getQueue()).toEqual([])
794 })
795​
796 const users = client.getMessages().filter((m) => m.role === 'user')
797 expect(users.map((m) => m.parts[0])).toEqual([
798 { type: 'text', content: 'first' },
799 { type: 'text', content: 'a\nb' },
800 { type: 'text', content: 'during-batch' },
801 ])
802 })
803​
804 it('error during FIFO drain flushes remaining queued items', async () => {
805 const deferred = createDeferred<void>()
806 let call = 0
807 const connection: ConnectConnectionAdapter = {
808 async *connect(): AsyncGenerator<StreamChunk> {
809 call += 1
810 if (call === 1) {
811 await deferred.promise
812 yield* createTextChunks('done', 'msg-1')
813 return
814 }
815 if (call === 2) {
816 yield {
817 type: EventType.RUN_ERROR,
818 threadId: 'thread-1',
819 timestamp: Date.now(),
820 message: 'boom',
821 error: { message: 'boom' },
822 }
823 return
824 }
825 yield* createTextChunks('should-not-run', `msg-${call}`)
826 },
827 }
828 const client = new ChatClient({ threadId: 'thread-1', connection })
829​
830 const firstSend = client.sendMessage('first')
831 await vi.waitFor(() => {
832 expect(client.getIsLoading()).toBe(true)
833 })
834 await client.sendMessage('drains-then-errors')
835 await client.sendMessage('should-be-flushed')
836 expect(client.getQueue()).toHaveLength(2)
837​
838 deferred.resolve()
839 await firstSend
840 await vi.waitFor(() => {
841 expect(client.getQueue()).toEqual([])
842 })
843​
844 const users = client.getMessages().filter((m) => m.role === 'user')
845 // first + the drained item that errored; the third never sends.
846 expect(users.map((m) => m.parts[0])).toEqual([
847 { type: 'text', content: 'first' },
848 { type: 'text', content: 'drains-then-errors' },
849 ])
850 })
851​
852 it('interrupt during FIFO drain keeps remaining items for after the interrupt', async () => {
853 const deferred1 = createDeferred<void>()
854 const deferred2 = createDeferred<void>()
855 let call = 0
856 const connection: ConnectConnectionAdapter = {
857 async *connect() {
858 call += 1
859 if (call === 1) {
860 await deferred1.promise
861 } else if (call === 2) {
862 await deferred2.promise
863 }
864 yield* createTextChunks('done', `msg-${call}`)
865 },
866 }
867 const client = new ChatClient({ threadId: 'thread-1', connection })
868​
869 const firstSend = client.sendMessage('first')
870 await vi.waitFor(() => {
871 expect(client.getIsLoading()).toBe(true)
872 })
873 await client.sendMessage('second')
874 await client.sendMessage('third')
875​
876 deferred1.resolve()
877 // Wait until FIFO drain has started streaming "second".
878 await vi.waitFor(() => {
879 const users = client.getMessages().filter((m) => m.role === 'user')
880 expect(users.map((m) => m.parts[0])).toEqual([
881 { type: 'text', content: 'first' },
882 { type: 'text', content: 'second' },
883 ])
884 expect(client.getIsLoading()).toBe(true)
885 })
886 // "third" should still be queued while "second" streams.
887 expect(client.getQueue().map((m) => m.content)).toEqual(['third'])
888​
889 const interruptSend = client.sendMessage('urgent', undefined, {
890 whenBusy: 'interrupt',
891 })
892 // Interrupt does not flush remaining queue.
893 expect(client.getQueue().map((m) => m.content)).toEqual(['third'])
894​
895 deferred2.resolve()
896 await Promise.all([firstSend, interruptSend])
897 await vi.waitFor(() => {
898 expect(client.getQueue()).toEqual([])
899 })
900​
901 const users = client.getMessages().filter((m) => m.role === 'user')
902 expect(users.map((m) => m.parts[0])).toEqual([
903 { type: 'text', content: 'first' },
904 { type: 'text', content: 'second' },
905 { type: 'text', content: 'urgent' },
906 { type: 'text', content: 'third' },
907 ])
908 })
909})