Open History to see the last commit
1import { expect, test } from '@playwright/test'
2
3/**
4 * Delivery durability (transport layer) over real HTTP.
5 *
6 * These exercise the server-side `durability` sink end-to-end: a fresh run is
7 * appended to the log and each SSE event is tagged with an opaque adapter-owned
8 * offset; a reconnect (native `Last-Event-ID`) or a `?offset` join replays from
9 * the log without re-producing.
10 *
11 * We test only the **producer-alive** path deterministically (the log is fully
12 * written by the first request). The **producer-dead** case — where the client
13 * disconnects mid-run and the producer process is torn down with it — cannot be
14 * resumed by the log alone; it needs the producer to outlive the socket
15 * (`waitUntil` / durable object / queue), which is a per-platform deployment
16 * concern, not something this transport can guarantee. The client-side
17 * auto-reconnect (Last-Event-ID resend + de-dupe) is covered by unit tests in
18 * `@tanstack/ai-client`.
19 *
20 * Exempt from the aimock policy: the `api.durable-delivery` harness route
21 * streams a fixed AG-UI sequence and never reaches an LLM provider's HTTP layer,
22 * so there is nothing to mock.
23 */
24
25interface SseEvent {
26 id?: string
27 data: unknown
28}
29
30function parseSse(body: string): Array<SseEvent> {
31 return body
32 .split('\n\n')
33 .filter((block) => block.trim().length > 0)
34 .map((block) => {
35 const lines = block.split('\n')
36 const idLine = lines.find((l) => l.startsWith('id:'))
37 const dataLine = lines.find((l) => l.startsWith('data:'))
38 const rawData = dataLine
39 ? dataLine.slice(dataLine.indexOf(':') + 1).trim()
40 : ''
41 return {
42 ...(idLine ? { id: idLine.slice(idLine.indexOf(':') + 1).trim() } : {}),
43 data: JSON.parse(rawData),
44 }
45 })
46}
47
48function eventType(e: SseEvent): string {
49 return (e.data as { type: string }).type
50}
51
52function contentDeltas(events: Array<SseEvent>): Array<string> {
53 return events
54 .filter((e) => eventType(e) === 'TEXT_MESSAGE_CONTENT')
55 .map((e) => (e.data as { delta: string }).delta)
56}
57
58test.describe('delivery durability', () => {
59 test('disconnect → reconnect resumes the ordered stream exactly once', async ({
60 request,
61 }) => {
62 // Fresh run: produce + persist the full ordered sequence.
63 const produce = await request.post('/api/durable-delivery', { data: {} })
64 expect(produce.ok()).toBeTruthy()
65 const produced = parseSse(await produce.text())
66
67 // Sequence: run-accepted marker(1), RUN_STARTED(2), content 1..5 (seq
68 // 3..7), RUN_FINISHED(8). The marker is what a fresh durable producer
69 // appends so a joiner never sees an empty log.
70 expect(contentDeltas(produced)).toEqual(['1', '2', '3', '4', '5'])
71 expect(produced.every((e) => e.id !== undefined)).toBeTruthy()
72
73 // Client received through content "2" (marker, RUN_STARTED, "1", "2") then
74 // dropped. Reconnect from that offset via native Last-Event-ID.
75 const resumeFrom = produced[3]!.id!
76 const reconnect = await request.post('/api/durable-delivery', {
77 headers: { 'Last-Event-ID': resumeFrom },
78 data: {},
79 })
80 expect(reconnect.ok()).toBeTruthy()
81 const resumed = parseSse(await reconnect.text())
82
83 // Exactly the tail, in order, exactly once — content "3","4","5" then RUN_FINISHED.
84 expect(contentDeltas(resumed)).toEqual(['3', '4', '5'])
85 expect(eventType(resumed[resumed.length - 1]!)).toBe('RUN_FINISHED')
86 // Adapter offsets are opaque; no replayed event may reuse the acknowledged
87 // resume offset.
88 expect(resumed.map((event) => event.id)).not.toContain(resumeFrom)
89 })
90
91 test('a second tab joins an existing run from the start', async ({
92 request,
93 }) => {
94 const produce = await request.post('/api/durable-delivery', { data: {} })
95 const produced = parseSse(await produce.text())
96 const runId = produce.headers()['x-run-id']
97 if (!runId) throw new Error('Missing X-Run-Id response header')
98
99 // Join from the start with ?offset=-1 (a fresh tab attaching to the run).
100 const join = await request.get(
101 `/api/durable-delivery?offset=-1&runId=${encodeURIComponent(runId)}`,
102 )
103 expect(join.ok()).toBeTruthy()
104 const joined = parseSse(await join.text())
105
106 expect(contentDeltas(joined)).toEqual(['1', '2', '3', '4', '5'])
107 // The joining tab sees the same content the producing tab saw.
108 expect(contentDeltas(joined)).toEqual(contentDeltas(produced))
109 // The from-start join replays the run-accepted marker first, then the run.
110 expect(eventType(joined[0]!)).toBe('CUSTOM')
111 expect(eventType(joined[1]!)).toBe('RUN_STARTED')
112 expect(eventType(joined[joined.length - 1]!)).toBe('RUN_FINISHED')
113 })
114})
115
116test.describe('delivery durability (live text)', () => {
117 test('streams text while the run is still going, with the default batch', async ({
118 page,
119 }) => {
120 // The `slow` run sends 5 text chunks 300ms apart. Chunks reach the client
121 // only after they are appended to the log, and a batch of 32 never fills
122 // here. So the batch must flush on its own while the run waits, not hold
123 // every chunk until RUN_FINISHED.
124 await page.goto('/')
125 const timing = await page.evaluate(async () => {
126 const startedAt = performance.now()
127 const response = await fetch('/api/durable-delivery?scenario=slow', {
128 method: 'POST',
129 headers: { 'content-type': 'application/json' },
130 body: '{}',
131 })
132 if (!response.body) throw new Error('Expected a response body')
133 const reader = response.body.getReader()
134 const decoder = new TextDecoder()
135 let body = ''
136 let firstTextAt = -1
137 for (;;) {
138 const { done, value } = await reader.read()
139 if (done) break
140 body += decoder.decode(value, { stream: true })
141 if (firstTextAt < 0 && body.includes('"TEXT_MESSAGE_CONTENT"')) {
142 firstTextAt = performance.now() - startedAt
143 }
144 }
145 return { firstTextAt, endAt: performance.now() - startedAt }
146 })
147
148 expect(timing.firstTextAt).toBeGreaterThan(0)
149 // The first chunk comes about 1.2s before the end. Held until the end, the
150 // gap would be about 0.
151 expect(timing.endAt - timing.firstTextAt).toBeGreaterThan(800)
152 })
153})
154
155test.describe('delivery durability (agent loop)', () => {
156 test('delivers a full tool-calling run, not truncated at the first RUN_FINISHED', async ({
157 request,
158 }) => {
159 // A tool-calling run emits a RUN_FINISHED per iteration (finishReason
160 // "tool_calls" then "stop"). Regression guard: the durable sink must deliver
161 // the tool result and the second iteration that follow the FIRST terminal —
162 // a sink that ended the log on the first RUN_FINISHED stranded tool-calling
163 // runs at the tool call.
164 const produce = await request.post(
165 '/api/durable-delivery?scenario=agent-loop',
166 { data: {} },
167 )
168 expect(produce.ok()).toBeTruthy()
169 const events = parseSse(await produce.text())
170 const types = events.map(eventType)
171
172 // Both per-iteration terminals arrive (old behaviour stopped after the first).
173 expect(types.filter((t) => t === 'RUN_FINISHED')).toHaveLength(2)
174 // The tool result and the second iteration's reply survive the first terminal.
175 expect(types).toContain('TOOL_CALL_RESULT')
176 expect(contentDeltas(events)).toEqual(['done'])
177 // Every event is offset-tagged, and the log ends on the final 'stop' terminal.
178 expect(events.every((e) => e.id !== undefined)).toBeTruthy()
179 const last = events[events.length - 1]!
180 expect(eventType(last)).toBe('RUN_FINISHED')
181 const metadata = (
182 last.data as { metadata?: { tanstack?: { finishReason?: string } } }
183 ).metadata
184 expect(metadata?.tanstack?.finishReason).toBe('stop')
185 })
186
187 test('a second tab joins a finished tool-calling run in full', async ({
188 request,
189 }) => {
190 const produce = await request.post(
191 '/api/durable-delivery?scenario=agent-loop',
192 { data: {} },
193 )
194 const runId = produce.headers()['x-run-id']
195 if (!runId) throw new Error('Missing X-Run-Id response header')
196
197 const join = await request.get(
198 `/api/durable-delivery?offset=-1&runId=${encodeURIComponent(runId)}`,
199 )
200 expect(join.ok()).toBeTruthy()
201 const joined = parseSse(await join.text())
202 const types = joined.map(eventType)
203 // The replayed log is complete: both terminals, the tool result, the reply.
204 expect(types.filter((t) => t === 'RUN_FINISHED')).toHaveLength(2)
205 expect(types).toContain('TOOL_CALL_RESULT')
206 expect(contentDeltas(joined)).toEqual(['done'])
207 })
208})
209
210/**
211 * The same delivery-durability guarantees over the NDJSON wire encoding
212 * (`?transport=ndjson`). NDJSON has no native event-id, so each durable line is
213 * an `{ id, chunk }` envelope carrying the opaque offset. The durability layer
214 * is shared with SSE — only the parsing differs.
215 */
216function parseNdjson(body: string): Array<SseEvent> {
217 return body
218 .split('\n')
219 .filter((line) => line.trim().length > 0)
220 .map((line) => {
221 const parsed = JSON.parse(line) as Record<string, unknown>
222 // Mirror the production `isNdjsonEnvelope` discriminator exactly: an
223 // envelope carries `id` + `chunk` and no top-level `type`.
224 if (
225 'chunk' in parsed &&
226 'id' in parsed &&
227 typeof parsed.id === 'string' &&
228 !('type' in parsed)
229 ) {
230 return { id: parsed.id, data: parsed.chunk }
231 }
232 return { data: parsed }
233 })
234}
235
236test.describe('delivery durability (ndjson)', () => {
237 test('disconnect → reconnect resumes the ordered stream exactly once', async ({
238 request,
239 }) => {
240 const produce = await request.post(
241 '/api/durable-delivery?transport=ndjson',
242 {
243 data: {},
244 },
245 )
246 expect(produce.ok()).toBeTruthy()
247 const produced = parseNdjson(await produce.text())
248
249 expect(contentDeltas(produced)).toEqual(['1', '2', '3', '4', '5'])
250 expect(produced.every((e) => e.id !== undefined)).toBeTruthy()
251
252 // Index 3: marker, RUN_STARTED, "1", "2" — dropped after content "2".
253 const resumeFrom = produced[3]!.id!
254 const reconnect = await request.post(
255 '/api/durable-delivery?transport=ndjson',
256 {
257 headers: { 'Last-Event-ID': resumeFrom },
258 data: {},
259 },
260 )
261 expect(reconnect.ok()).toBeTruthy()
262 const resumed = parseNdjson(await reconnect.text())
263
264 expect(contentDeltas(resumed)).toEqual(['3', '4', '5'])
265 expect(eventType(resumed[resumed.length - 1]!)).toBe('RUN_FINISHED')
266 expect(resumed.map((event) => event.id)).not.toContain(resumeFrom)
267 })
268
269 test('a second tab joins an existing run from the start', async ({
270 request,
271 }) => {
272 const produce = await request.post(
273 '/api/durable-delivery?transport=ndjson',
274 {
275 data: {},
276 },
277 )
278 const produced = parseNdjson(await produce.text())
279 const runId = produce.headers()['x-run-id']
280 if (!runId) throw new Error('Missing X-Run-Id response header')
281 expect(produced.length).toBeGreaterThan(0)
282
283 const join = await request.get(
284 `/api/durable-delivery?transport=ndjson&offset=-1&runId=${encodeURIComponent(runId)}`,
285 )
286 expect(join.ok()).toBeTruthy()
287 const joined = parseNdjson(await join.text())
288
289 expect(contentDeltas(joined)).toEqual(['1', '2', '3', '4', '5'])
290 // The from-start join replays the run-accepted marker first, then the run.
291 expect(eventType(joined[0]!)).toBe('CUSTOM')
292 expect(eventType(joined[1]!)).toBe('RUN_STARTED')
293 expect(eventType(joined[joined.length - 1]!)).toBe('RUN_FINISHED')
294 })
295})