Open History to see the last commit
1import { afterEach, describe, expect, it, vi } from 'vitest'
2import { z } from 'zod'
3import { memoryPersistence } from '@tanstack/ai-persistence'
4import { createHarnessHost, defineHarness } from '../src'
5import { createHarnessHandler } from '../src/server'
6import { HarnessProtocolError, createHarnessClient } from '../src/client'
7import { mockAdapter, text } from './helpers'
8
9/** The part of a /control request body that these tests read. */
10const ControlBody = z.object({ input: z.object({ inputId: z.string() }) })
11
12afterEach(() => {
13 vi.useRealTimers()
14 vi.restoreAllMocks()
15})
16
17/** A 200 response whose body sends `chunks` as separate reads. */
18function streamed(chunks: ReadonlyArray<string>) {
19 const encoder = new TextEncoder()
20 const body = new ReadableStream<Uint8Array>({
21 start(controller) {
22 for (const chunk of chunks) controller.enqueue(encoder.encode(chunk))
23 controller.close()
24 },
25 })
26 return new Response(body, { status: 200 })
27}
28
29/** A client on `fetch`, for the thread `t`. */
30function clientOn(
31 fetch: typeof globalThis.fetch,
32 reconnectDelayMs?: number,
33 idleTimeoutMs?: number,
34) {
35 return createHarnessClient({
36 url: 'http://x/api/harness',
37 threadId: 't',
38 fetch,
39 ...(reconnectDelayMs === undefined ? {} : { reconnectDelayMs }),
40 ...(idleTimeoutMs === undefined ? {} : { idleTimeoutMs }),
41 })
42}
43
44/** Every frame of a host-events body made of `chunks`. */
45async function hostFrames(chunks: ReadonlyArray<string>) {
46 const client = clientOn(async () => streamed(chunks))
47 const frames: Array<unknown> = []
48 for await (const frame of client.hostEvents()) frames.push(frame)
49 return frames
50}
51
52/** One session event frame with the cursor `cursor`. */
53const sessionFrame = (cursor: string) =>
54 `data: ${JSON.stringify({
55 type: 'harness.event',
56 cursor,
57 operationId: 'op',
58 event: { type: 'CUSTOM', name: 'tick', value: cursor, timestamp: 1 },
59 })}\n\n`
60
61describe('SSE parsing', () => {
62 it('ends lines with CR, LF, or CRLF, also a CRLF split across two reads', async () => {
63 expect(
64 await hostFrames([
65 'data: {"n":1}\r\n\r',
66 '\ndata: {"n":2}\r\rdata: {"n":3}\n\n',
67 ]),
68 ).toEqual([{ n: 1 }, { n: 2 }, { n: 3 }])
69 })
70
71 it('joins the data lines of one event, with or without a space', async () => {
72 expect(
73 await hostFrames(['data: {"a":\n', 'data:1,\ndata: "b": 2}\n\n']),
74 ).toEqual([{ a: 1, b: 2 }])
75 })
76
77 it('skips comments and other fields', async () => {
78 expect(
79 await hostFrames([
80 ': heartbeat\n\n',
81 'event: status\nid: 7\n: note\ndata: {"n":1}\n\n',
82 ]),
83 ).toEqual([{ n: 1 }])
84 })
85
86 it('keeps an event split across reads until it ends', async () => {
87 expect(await hostFrames(['da', 'ta: {"n"', ':1}', '\n', '\n'])).toEqual([
88 { n: 1 },
89 ])
90 })
91})
92
93describe('events() reconnects', () => {
94 it('adds one abort listener for all its connections, and removes it', async () => {
95 let calls = 0
96 // Each connection sends one event and closes, so the client reconnects.
97 const client = clientOn(async () => {
98 calls += 1
99 return streamed([sessionFrame(String(calls))])
100 }, 1)
101 const controller = new AbortController()
102 const added = vi.spyOn(controller.signal, 'addEventListener')
103 const removed = vi.spyOn(controller.signal, 'removeEventListener')
104
105 const seen: Array<string> = []
106 // A cursor, so the client does not ask for the snapshot head first.
107 for await (const entry of client.events({
108 from: '0',
109 signal: controller.signal,
110 })) {
111 seen.push(entry.cursor)
112 if (seen.length === 20) break
113 }
114
115 expect(seen).toHaveLength(20)
116 expect(added).toHaveBeenCalledTimes(1)
117 expect(removed).toHaveBeenCalledTimes(1)
118 expect(removed.mock.calls[0]?.[1]).toBe(added.mock.calls[0]?.[1])
119 })
120
121 it('waits longer after each failure, with jitter, and starts again after a read', async () => {
122 vi.useFakeTimers()
123 // The random part takes a quarter of each wait away.
124 vi.spyOn(Math, 'random').mockReturnValue(0.5)
125 const times: Array<number> = []
126 const client = clientOn(async () => {
127 times.push(Date.now())
128 // The 8th connection reads one event. Every other one fails.
129 if (times.length === 8) return streamed([sessionFrame('1')])
130 throw new Error('network')
131 })
132 const controller = new AbortController()
133 const iterator = client
134 .events({ from: '0', signal: controller.signal })
135 [Symbol.asyncIterator]()
136
137 const first = iterator.next()
138 // The 7 waits before the 8th connection.
139 await vi.advanceTimersByTimeAsync(68_250)
140 expect((await first).value?.cursor).toBe('1')
141 const rest = iterator.next()
142 await vi.advanceTimersByTimeAsync(2_250)
143 controller.abort()
144 expect(await rest).toEqual({ done: true, value: undefined })
145
146 const waits = times.slice(1).map((time, index) => time - times[index]!)
147 // 1 s doubled each try, capped at 30 s, times 0.75. After the read,
148 // the wait is 0.75 s again.
149 expect(waits).toEqual([
150 750, 1500, 3000, 6000, 12_000, 22_500, 22_500, 750, 1500,
151 ])
152 })
153
154 it('waits idleTimeoutMs before it connects again, for a server with a long heartbeat', async () => {
155 vi.useFakeTimers()
156 const urls: Array<string> = []
157 // The connection sends nothing.
158 const client = clientOn(
159 async (input) => {
160 urls.push(String(input))
161 return new Response(new ReadableStream<Uint8Array>(), { status: 200 })
162 },
163 1,
164 120_000,
165 )
166 const controller = new AbortController()
167 const next = client
168 .events({ from: '0', signal: controller.signal })
169 [Symbol.asyncIterator]()
170 .next()
171
172 await vi.advanceTimersByTimeAsync(61_000)
173 expect(urls).toHaveLength(1)
174 await vi.advanceTimersByTimeAsync(60_000)
175 expect(urls).toHaveLength(2)
176 controller.abort()
177 await next
178 })
179
180 it('connects again from its last cursor when a connection sends nothing for 60 s', async () => {
181 vi.useFakeTimers()
182 const encoder = new TextEncoder()
183 const urls: Array<string> = []
184 // The first connection sends one event, then nothing: a half-open
185 // connection. The next ones send one event each.
186 const client = clientOn(async (input) => {
187 urls.push(String(input))
188 if (urls.length > 1) return streamed([sessionFrame(String(urls.length))])
189 const body = new ReadableStream<Uint8Array>({
190 start(controller) {
191 controller.enqueue(encoder.encode(sessionFrame('1')))
192 },
193 })
194 return new Response(body, { status: 200 })
195 }, 1)
196 const controller = new AbortController()
197 const iterator = client
198 .events({ from: '0', signal: controller.signal })
199 [Symbol.asyncIterator]()
200
201 expect((await iterator.next()).value?.cursor).toBe('1')
202 const next = iterator.next()
203 await vi.advanceTimersByTimeAsync(59_000)
204 expect(urls).toHaveLength(1)
205 await vi.advanceTimersByTimeAsync(1_100)
206
207 expect((await next).value?.cursor).toBe('2')
208 expect(urls[1]).toContain('from=1')
209 controller.abort()
210 })
211
212 it('stops the wait before a reconnect when the signal aborts', async () => {
213 vi.useFakeTimers()
214 const client = clientOn(async () => {
215 throw new Error('network')
216 })
217 const controller = new AbortController()
218 const next = client
219 .events({ signal: controller.signal })
220 [Symbol.asyncIterator]()
221 .next()
222 await vi.advanceTimersByTimeAsync(10)
223 controller.abort()
224
225 expect(await next).toEqual({ done: true, value: undefined })
226 })
227})
228
229describe('harness.error frames', () => {
230 const errorFrame = (code: string) =>
231 `data: ${JSON.stringify({ type: 'harness.error', code, message: `${code} happened`, requestId: 'r' })}\n\n`
232
233 it('events() connects again from its cursor after slow_consumer, and throws any other error', async () => {
234 const urls: Array<string> = []
235 const client = clientOn(async (input) => {
236 urls.push(String(input))
237 return urls.length === 1
238 ? streamed([sessionFrame('1'), errorFrame('slow_consumer')])
239 : streamed([sessionFrame('2'), errorFrame('internal')])
240 }, 1)
241 const seen: Array<string> = []
242
243 const reading = (async () => {
244 for await (const entry of client.events({ from: '0' })) {
245 seen.push(entry.cursor)
246 }
247 })()
248
249 await expect(reading).rejects.toMatchObject({
250 name: 'HarnessProtocolError',
251 code: 'internal',
252 message: 'internal happened',
253 })
254 await expect(reading).rejects.toBeInstanceOf(HarnessProtocolError)
255 expect(seen).toEqual(['1', '2'])
256 expect(urls).toHaveLength(2)
257 expect(urls[1]).toContain('from=1')
258 })
259
260 it('hostEvents() connects again after slow_consumer, and throws any other error', async () => {
261 let calls = 0
262 const client = clientOn(async () => {
263 calls += 1
264 return calls === 1
265 ? streamed(['data: {"n":1}\n\n', errorFrame('slow_consumer')])
266 : streamed(['data: {"n":2}\n\n', errorFrame('forbidden')])
267 })
268 const frames: Array<unknown> = []
269
270 const reading = (async () => {
271 for await (const frame of client.hostEvents()) frames.push(frame)
272 })()
273
274 await expect(reading).rejects.toMatchObject({ code: 'forbidden' })
275 expect(frames).toEqual([{ n: 1 }, { n: 2 }])
276 })
277})
278
279describe('control inputs', () => {
280 /** A client on a real handler that keeps each /control request body. */
281 function recorded() {
282 const { adapter, calls } = mockAdapter([() => text('once')])
283 const harness = defineHarness({ name: 'test/client-parse', adapter })
284 const host = createHarnessHost({ persistence: memoryPersistence() })
285 const handler = createHarnessHandler({
286 host,
287 harness,
288 openAccess: { user: { id: 'u' } },
289 })
290 const bodies: Array<string> = []
291 const client = createHarnessClient({
292 url: 'http://local/api/harness',
293 threadId: 'thread-ids',
294 fetch: async (input, init) => {
295 if (typeof init?.body === 'string') bodies.push(init.body)
296 return handler(new Request(input, init))
297 },
298 })
299 /** Send the body again, as a retry of the same request does. */
300 const retry = async (body: string) => {
301 const response = await handler(
302 new Request('http://local/api/harness/control', {
303 method: 'POST',
304 headers: { 'Content-Type': 'application/json' },
305 body,
306 }),
307 )
308 return response.json()
309 }
310 return { host, client, bodies, calls, retry }
311 }
312
313 /** The `inputId` of the input in a /control request body. */
314 const inputIdOf = (body: string | undefined) =>
315 ControlBody.parse(JSON.parse(body ?? 'null')).input.inputId
316
317 it('gives a send an inputId, so a retry of it is the same input', async () => {
318 const { host, client, bodies, calls, retry } = recorded()
319
320 const receipt = await client.send('hi')
321 const again = await retry(bodies[0] ?? '')
322 // Wait until the first turn ends. A second turn would start before.
323 await vi.waitFor(async () => {
324 expect(calls.length).toBeGreaterThan(0)
325 expect((await client.snapshot()).status).toBe('idle')
326 })
327 await host.close()
328
329 expect(inputIdOf(bodies[0])).toMatch(
330 /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,
331 )
332 expect(receipt.inputId).toBe(inputIdOf(bodies[0]))
333 expect(again).toEqual(receipt)
334 expect(calls).toHaveLength(1)
335 })
336
337 it('keeps the inputId of the input to change in cancelInput', async () => {
338 const { host, client, bodies } = recorded()
339
340 await client.cancelInput({ inputId: 'waiting-1' }).catch(() => undefined)
341 await host.close()
342
343 expect(inputIdOf(bodies[0])).toBe('waiting-1')
344 })
345})