Open History to see the last commit
1import { expect, it, vi } from 'vitest'
2import { EventType } from '@tanstack/ai/client'
3import { normalizeConnectionAdapter, stream } from '../src/connection-adapters'
4
5it('waits for a slow subscriber before resolving send', async () => {
6 vi.useFakeTimers()
7 let release = () => {}
8 const gate = new Promise<void>((resolve) => {
9 release = resolve
10 })
11 const controller = new AbortController()
12 const adapter = normalizeConnectionAdapter(
13 stream(async function* () {
14 yield {
15 type: EventType.RUN_FINISHED,
16 threadId: 'thread',
17 runId: 'run',
18 timestamp: 0,
19 }
20 }),
21 )
22 let processed = false
23 const consuming = (async () => {
24 for await (const _chunk of adapter.subscribe(controller.signal)) {
25 await gate
26 processed = true
27 }
28 })()
29 let settled = false
30 const sending = adapter.send([]).then(() => {
31 settled = true
32 })
33 try {
34 await vi.advanceTimersByTimeAsync(1000)
35 expect(settled).toBe(false)
36 release()
37 await vi.runAllTimersAsync()
38 await sending
39 expect(processed).toBe(true)
40 } finally {
41 release()
42 controller.abort()
43 await vi.runAllTimersAsync()
44 await Promise.all([sending, consuming])
45 vi.useRealTimers()
46 }
47})
48
49it('does not wait for a subscriber that has exited', async () => {
50 const adapter = normalizeConnectionAdapter(
51 stream(async function* () {
52 yield {
53 type: EventType.RUN_FINISHED,
54 threadId: 'thread',
55 runId: 'run',
56 timestamp: 0,
57 }
58 }),
59 )
60 const consuming = (async () => {
61 for await (const _chunk of adapter.subscribe()) break
62 })()
63 await adapter.send([])
64 await consuming
65})