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