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

sse-parser-cleanup.test.ts

96 lines3.0 KB

1import { expect, it, vi } from 'vitest'
2import { parseSSEResponse } from '../src/sse-parser'
3import { GenerationClient } from '../src/generation-client'
4​
5const chunk = { type: 'RUN_STARTED', threadId: 'thread', runId: 'run' }
6const frame = `data: ${JSON.stringify(chunk)}\n\n`
7​
8it.each(['resolves', 'throws', 'rejects', 'never settles'] as const)(
9 'cancels a generation response on early return when cancellation %s',
10 async (behavior) => {
11 const cancel = vi.fn(() => {
12 const error = new Error('cleanup failed')
13 if (behavior === 'throws') throw error
14 if (behavior === 'rejects') return Promise.reject(error)
15 if (behavior === 'never settles') return new Promise<void>(() => {})
16 return undefined
17 })
18 const body = new ReadableStream<Uint8Array>({
19 start(controller) {
20 controller.enqueue(new TextEncoder().encode(frame))
21 },
22 cancel,
23 })
24 for await (const received of parseSSEResponse(new Response(body))) {
25 expect(received).toEqual(chunk)
26 break
27 }
28 expect(cancel).toHaveBeenCalledOnce()
29 expect(body.locked).toBe(false)
30 },
32​
33it('reports a generation error without waiting for custom cancellation', async () => {
34 const cancel = vi.fn(() => new Promise<void>(() => {}))
35 const body = new ReadableStream<Uint8Array>({
36 start(controller) {
37 controller.enqueue(
38 new TextEncoder().encode(
39 'data: {"type":"RUN_ERROR","message":"generation failed"}\n\n',
40 ),
41 )
42 },
43 cancel,
44 })
45 const client = new GenerationClient({
46 threadId: 'thread-1',
47 fetcher: async () => new Response(body),
48 })
49 try {
50 await client.generate({})
51 expect(client.getError()?.message).toBe('generation failed')
52 expect(client.getIsLoading()).toBe(false)
53 expect(cancel).toHaveBeenCalledOnce()
54 expect(body.locked).toBe(false)
55 } finally {
56 client.dispose()
57 }
58})
59​
60it('preserves generation reader errors and releases the lock', async () => {
61 const error = new Error('response reader failed')
62 const body = new ReadableStream<Uint8Array>({
63 start(controller) {
64 controller.error(error)
65 },
66 })
67 await expect(parseSSEResponse(new Response(body)).next()).rejects.toBe(error)
68 expect(body.locked).toBe(false)
69})
70​
71it('drains generation EOF and keeps ignoring malformed JSON and DONE markers', async () => {
72 const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
73 const cancel = vi.fn()
74 const body = new ReadableStream<Uint8Array>({
75 start(controller) {
76 controller.enqueue(
77 new TextEncoder().encode(
78 `data: {invalid json}\n\ndata: [DONE]\n\n${frame}`,
79 ),
80 )
81 controller.close()
82 },
83 cancel,
84 })
85 try {
86 const chunks = []
87 for await (const received of parseSSEResponse(new Response(body)))
88 chunks.push(received)
89 expect(chunks).toEqual([chunk])
90 expect(warn).toHaveBeenCalledTimes(2)
91 expect(cancel).not.toHaveBeenCalled()
92 expect(body.locked).toBe(false)
93 } finally {
94 warn.mockRestore()
95 }
96})