Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { EventType } from '@tanstack/ai/client'
3import {
4 StreamReconnectLimitError,
5 fetchHttpStream,
6 fetchJson,
7} from '../src/connection-adapters'
8import type { RunAgentInputContext } from '../src/connection-adapters'
9import type { StreamChunk, UIMessage } from '@tanstack/ai/client'
10
11const messages: Array<UIMessage> = [
12 { id: 'msg-1', role: 'user', parts: [{ type: 'text', content: 'Hi' }] },
13]
14
15const runContext: RunAgentInputContext = {
16 threadId: 'thread-1',
17 runId: 'run-1',
18 headers: { 'X-Byok': 'key-1' },
19}
20
21function contentChunk(delta: string) {
22 return {
23 type: EventType.TEXT_MESSAGE_CONTENT,
24 messageId: 'm',
25 timestamp: 0,
26 delta,
27 }
28}
29
30/** A RUN_FINISHED as the server puts it on the wire (spec usage[] + metadata). */
31function wireFinishedChunk() {
32 return {
33 type: EventType.RUN_FINISHED,
34 threadId: 'thread-1',
35 runId: 'run-1',
36 timestamp: 0,
37 usage: [{ inputTokens: 3, outputTokens: 5, totalTokens: 8 }],
38 metadata: { tanstack: { finishReason: 'stop' } },
39 }
40}
41
42function jsonResponse(body: unknown, init?: ResponseInit) {
43 return new Response(JSON.stringify(body), {
44 headers: { 'Content-Type': 'application/json' },
45 ...init,
46 })
47}
48
49type FetchStep = Response | Error
50
51/** A fetch mock that answers each call with the next step (a reply or a network failure). */
52function fetchSequence(...steps: Array<FetchStep>) {
53 return vi.fn<typeof fetch>(async () => {
54 const step = steps.shift()
55 if (step === undefined) throw new Error('unexpected extra request')
56 if (step instanceof Error) throw step
57 return step
58 })
59}
60
61function requestAt(
62 fetchClient: ReturnType<typeof fetchSequence>,
63 index: number,
64) {
65 const call = fetchClient.mock.calls[index]
66 if (call === undefined) throw new Error(`no request #${index}`)
67 const [input, init] = call
68 return {
69 url: String(input),
70 method: init?.method,
71 headers: new Headers(init?.headers),
72 body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
73 credentials: init?.credentials,
74 }
75}
76
77function requestedUrls(fetchClient: ReturnType<typeof fetchSequence>) {
78 return fetchClient.mock.calls.map(([input]) => String(input))
79}
80
81async function collect(iterable: AsyncIterable<StreamChunk>) {
82 const chunks: Array<StreamChunk> = []
83 for await (const chunk of iterable) chunks.push(chunk)
84 return chunks
85}
86
87function deltasOf(chunks: Array<StreamChunk>) {
88 return chunks
89 .filter((c) => c.type === EventType.TEXT_MESSAGE_CONTENT)
90 .map((c) => c.delta)
91}
92
93function connectWith(
94 fetchClient: ReturnType<typeof fetchSequence>,
95 signal?: AbortSignal,
96 pollIntervalMs = 0,
97) {
98 const adapter = fetchJson('/api/chat', {
99 fetchClient,
100 pollIntervalMs,
101 reconnect: { delayMs: 0 },
102 })
103 return adapter.connect(messages, undefined, signal, runContext)
104}
105
106describe('fetchJson', () => {
107 it('POSTs the same body and headers as fetchHttpStream, plus Accept: application/json', async () => {
108 const jsonFetch = fetchSequence(jsonResponse({ chunks: [], done: true }))
109 const streamFetch = fetchSequence(new Response(''))
110 const options = {
111 headers: { Authorization: 'Bearer token' },
112 credentials: 'include' as const,
113 body: { model: 'gpt-5.5' },
114 }
115
116 await collect(
117 fetchJson('/api/chat', { ...options, fetchClient: jsonFetch }).connect(
118 messages,
119 { extra: 1 },
120 undefined,
121 runContext,
122 ),
123 )
124 await collect(
125 fetchHttpStream('/api/chat', {
126 ...options,
127 fetchClient: streamFetch,
128 }).connect(messages, { extra: 1 }, undefined, runContext),
129 )
130
131 const json = requestAt(jsonFetch, 0)
132 const stream = requestAt(streamFetch, 0)
133 expect(json.url).toBe('/api/chat')
134 expect(json.method).toBe('POST')
135 expect(json.credentials).toBe('include')
136 expect(json.body).toEqual(stream.body)
137 expect(json.body).toMatchObject({
138 threadId: 'thread-1',
139 runId: 'run-1',
140 forwardedProps: { model: 'gpt-5.5', extra: 1 },
141 })
142 expect(json.headers.get('Accept')).toBe('application/json')
143 expect(json.headers.get('Content-Type')).toBe('application/json')
144 expect(json.headers.get('Authorization')).toBe('Bearer token')
145 expect(json.headers.get('X-Byok')).toBe('key-1')
146 expect(json.headers.get('X-Run-Id')).toBe('run-1')
147 expect(stream.headers.get('X-Run-Id')).toBe('run-1')
148 })
149
150 it('restores usage and extras on each chunk, in order', async () => {
151 const fetchClient = fetchSequence(
152 jsonResponse({
153 chunks: [contentChunk('Hello'), wireFinishedChunk()],
154 done: true,
155 }),
156 )
157
158 const chunks = await collect(connectWith(fetchClient))
159
160 expect(chunks.map((c) => c.type)).toEqual([
161 EventType.TEXT_MESSAGE_CONTENT,
162 EventType.RUN_FINISHED,
163 ])
164 expect(chunks[1]).toMatchObject({
165 finishReason: 'stop',
166 usage: { promptTokens: 3, completionTokens: 5, totalTokens: 8 },
167 })
168 })
169
170 it('polls GET ?runId&offset until done: true, with no duplicate chunks', async () => {
171 const fetchClient = fetchSequence(
172 jsonResponse({ chunks: [contentChunk('a')], offset: '1', done: false }),
173 jsonResponse({ chunks: [], offset: '1', done: false }),
174 jsonResponse({ chunks: [contentChunk('b')], offset: '2', done: false }),
175 jsonResponse({
176 chunks: [contentChunk('c'), wireFinishedChunk()],
177 offset: '4',
178 done: true,
179 }),
180 )
181
182 const chunks = await collect(connectWith(fetchClient))
183
184 expect(deltasOf(chunks)).toEqual(['a', 'b', 'c'])
185 expect(chunks).toHaveLength(4)
186 expect(requestedUrls(fetchClient)).toEqual([
187 '/api/chat',
188 '/api/chat?runId=run-1&offset=1',
189 '/api/chat?runId=run-1&offset=1',
190 '/api/chat?runId=run-1&offset=2',
191 ])
192 expect(requestAt(fetchClient, 1).method).toBe('GET')
193 expect(requestAt(fetchClient, 1).headers.get('Accept')).toBe(
194 'application/json',
195 )
196 })
197
198 it('throws the HTTP status on a non-2xx reply', async () => {
199 const fetchClient = fetchSequence(
200 new Response('upstream down', { status: 502, statusText: 'Bad Gateway' }),
201 )
202
203 await expect(collect(connectWith(fetchClient))).rejects.toThrow(
204 'HTTP error! status: 502 Bad Gateway',
205 )
206 })
207
208 it('throws a clear error, not a SyntaxError, when the body is not JSON', async () => {
209 const fetchClient = fetchSequence(
210 new Response('<html><body>Proxy error</body></html>', {
211 headers: { 'Content-Type': 'text/html' },
212 }),
213 )
214
215 const error = await collect(connectWith(fetchClient)).catch(
216 (caught: unknown) => caught,
217 )
218
219 expect(error).toBeInstanceOf(Error)
220 expect(error).not.toBeInstanceOf(SyntaxError)
221 expect(error).toHaveProperty(
222 'message',
223 expect.stringContaining('not JSON (content-type: text/html)'),
224 )
225 })
226
227 it('throws a clear error when the JSON body has the wrong shape', async () => {
228 const fetchClient = fetchSequence(jsonResponse({ messages: [] }))
229
230 await expect(collect(connectWith(fetchClient))).rejects.toThrow(
231 '{ chunks, done, offset? }',
232 )
233 })
234
235 it('throws when done: false has no offset to resume from', async () => {
236 const fetchClient = fetchSequence(
237 jsonResponse({ chunks: [contentChunk('a')], done: false }),
238 )
239
240 await expect(collect(connectWith(fetchClient))).rejects.toThrow(
241 'done: false without an offset',
242 )
243 })
244
245 it('retries a failed poll', async () => {
246 const fetchClient = fetchSequence(
247 jsonResponse({ chunks: [contentChunk('a')], offset: '1', done: false }),
248 new TypeError('Failed to fetch'),
249 jsonResponse({ chunks: [contentChunk('b')], offset: '2', done: true }),
250 )
251
252 const chunks = await collect(connectWith(fetchClient))
253
254 expect(deltasOf(chunks)).toEqual(['a', 'b'])
255 expect(requestedUrls(fetchClient)).toEqual([
256 '/api/chat',
257 '/api/chat?runId=run-1&offset=1',
258 '/api/chat?runId=run-1&offset=1',
259 ])
260 })
261
262 it('retries a poll answered 503', async () => {
263 const fetchClient = fetchSequence(
264 jsonResponse({ chunks: [contentChunk('a')], offset: '1', done: false }),
265 new Response('restarting', { status: 503 }),
266 jsonResponse({ chunks: [contentChunk('b')], offset: '2', done: true }),
267 )
268
269 const chunks = await collect(connectWith(fetchClient))
270
271 expect(deltasOf(chunks)).toEqual(['a', 'b'])
272 expect(fetchClient).toHaveBeenCalledTimes(3)
273 })
274
275 it('gives up on a poll after the reconnect ceiling', async () => {
276 const fetchClient = fetchSequence(
277 jsonResponse({ chunks: [], offset: '1', done: false }),
278 new TypeError('Failed to fetch'),
279 new TypeError('Failed to fetch'),
280 )
281 const adapter = fetchJson('/api/chat', {
282 fetchClient,
283 pollIntervalMs: 0,
284 reconnect: { maxAttempts: 1, delayMs: 0 },
285 })
286
287 await expect(
288 collect(adapter.connect(messages, undefined, undefined, runContext)),
289 ).rejects.toBeInstanceOf(StreamReconnectLimitError)
290 expect(fetchClient).toHaveBeenCalledTimes(3)
291 })
292
293 it('does not retry a failed first POST', async () => {
294 const networkError = new TypeError('Failed to fetch')
295 const fetchClient = fetchSequence(
296 networkError,
297 jsonResponse({ chunks: [], done: true }),
298 )
299
300 await expect(collect(connectWith(fetchClient))).rejects.toMatchObject({
301 cause: networkError,
302 })
303 expect(fetchClient).toHaveBeenCalledTimes(1)
304 })
305
306 it('ends at once with no further request when stopped during the poll delay', async () => {
307 const fetchClient = fetchSequence(
308 jsonResponse({ chunks: [contentChunk('a')], offset: '1', done: false }),
309 jsonResponse({ chunks: [contentChunk('b')], offset: '2', done: true }),
310 )
311 const controller = new AbortController()
312 setTimeout(() => controller.abort(), 20)
313
314 const chunks = await collect(
315 connectWith(fetchClient, controller.signal, 60_000),
316 )
317
318 expect(deltasOf(chunks)).toEqual(['a'])
319 expect(fetchClient).toHaveBeenCalledTimes(1)
320 })
321
322 it('joinRun starts with GET ?runId&offset=-1', async () => {
323 const fetchClient = fetchSequence(
324 jsonResponse({ chunks: [contentChunk('a')], offset: '1', done: false }),
325 jsonResponse({ chunks: [contentChunk('b')], offset: '2', done: true }),
326 )
327 const adapter = fetchJson('/api/chat', { fetchClient, pollIntervalMs: 0 })
328
329 const chunks = await collect(adapter.joinRun('run-9'))
330
331 expect(deltasOf(chunks)).toEqual(['a', 'b'])
332 expect(requestAt(fetchClient, 0).method).toBe('GET')
333 expect(requestedUrls(fetchClient)).toEqual([
334 '/api/chat?runId=run-9&offset=-1',
335 '/api/chat?runId=run-9&offset=1',
336 ])
337 })
338
339 it('hydrate GETs ?threadId', async () => {
340 const fetchClient = fetchSequence(
341 jsonResponse({ messages: [], activeRun: { runId: 'run-3' } }),
342 )
343 const adapter = fetchJson('/api/chat', { fetchClient })
344 if (adapter.hydrate === undefined) {
345 throw new Error('expected hydration support')
346 }
347
348 const result = await adapter.hydrate('thread-1')
349
350 expect(result.activeRun).toEqual({ runId: 'run-3' })
351 expect(requestedUrls(fetchClient)).toEqual(['/api/chat?threadId=thread-1'])
352 })
353})