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 from-start join replays the run-accepted marker first, then the run.
108 expect(eventType(joined[0]!)).toBe('CUSTOM')
109 expect(eventType(joined[1]!)).toBe('RUN_STARTED')
110 expect(eventType(joined[joined.length - 1]!)).toBe('RUN_FINISHED')
111 })
112})
113
114test.describe('delivery durability (live text)', () => {
115 test('streams text while the run is still going, with the default batch', async ({
116 page,
117 }) => {
118 // The `slow` run sends 5 text chunks 300ms apart. Chunks reach the client
119 // only after they are appended to the log, and a batch of 32 never fills
120 // here. So the batch must flush on its own while the run waits, not hold
121 // every chunk until RUN_FINISHED.
122 await page.goto('/')
123 const timing = await page.evaluate(async () => {
124 const startedAt = performance.now()
125 const response = await fetch('/api/durable-delivery?scenario=slow', {
126 method: 'POST',
127 headers: { 'content-type': 'application/json' },
128 body: '{}',
129 })
130 if (!response.body) throw new Error('Expected a response body')
131 const reader = response.body.getReader()
132 const decoder = new TextDecoder()
133 let body = ''
134 let firstTextAt = -1
135 for (;;) {
136 const { done, value } = await reader.read()
137 if (done) break
138 body += decoder.decode(value, { stream: true })
139 if (firstTextAt < 0 && body.includes('"TEXT_MESSAGE_CONTENT"')) {
140 firstTextAt = performance.now() - startedAt
141 }
142 }
143 return { firstTextAt, endAt: performance.now() - startedAt }
144 })
145
146 expect(timing.firstTextAt).toBeGreaterThan(0)
147 // The first chunk comes about 1.2s before the end. Held until the end, the
148 // gap would be about 0.
149 expect(timing.endAt - timing.firstTextAt).toBeGreaterThan(800)
150 })
151})
152
153test.describe('delivery durability (agent loop)', () => {
154 test('delivers a full tool-calling run, not truncated at the first RUN_FINISHED', async ({
155 request,
156 }) => {
157 // A tool-calling run emits a RUN_FINISHED per iteration (finishReason
158 // "tool_calls" then "stop"). Regression guard: the durable sink must deliver
159 // the tool result and the second iteration that follow the FIRST terminal —
160 // a sink that ended the log on the first RUN_FINISHED stranded tool-calling
161 // runs at the tool call.
162 const produce = await request.post(
163 '/api/durable-delivery?scenario=agent-loop',
164 { data: {} },
165 )
166 expect(produce.ok()).toBeTruthy()
167 const events = parseSse(await produce.text())
168 const types = events.map(eventType)
169
170 // Both per-iteration terminals arrive (old behaviour stopped after the first).
171 expect(types.filter((t) => t === 'RUN_FINISHED')).toHaveLength(2)
172 // The tool result and the second iteration's reply survive the first terminal.
173 expect(types).toContain('TOOL_CALL_RESULT')
174 expect(contentDeltas(events)).toEqual(['done'])
175 // Every event is offset-tagged, and the log ends on the final 'stop' terminal.
176 expect(events.every((e) => e.id !== undefined)).toBeTruthy()
177 const last = events[events.length - 1]!
178 expect(eventType(last)).toBe('RUN_FINISHED')
179 const metadata = (
180 last.data as { metadata?: { tanstack?: { finishReason?: string } } }
181 ).metadata
182 expect(metadata?.tanstack?.finishReason).toBe('stop')
183 })
184
185 test('a second tab joins a finished tool-calling run in full', async ({
186 request,
187 }) => {
188 const produce = await request.post(
189 '/api/durable-delivery?scenario=agent-loop',
190 { data: {} },
191 )
192 const runId = produce.headers()['x-run-id']
193 if (!runId) throw new Error('Missing X-Run-Id response header')
194
195 const join = await request.get(
196 `/api/durable-delivery?offset=-1&runId=${encodeURIComponent(runId)}`,
197 )
198 expect(join.ok()).toBeTruthy()
199 const joined = parseSse(await join.text())
200 const types = joined.map(eventType)
201 // The replayed log is complete: both terminals, the tool result, the reply.
202 expect(types.filter((t) => t === 'RUN_FINISHED')).toHaveLength(2)
203 expect(types).toContain('TOOL_CALL_RESULT')
204 expect(contentDeltas(joined)).toEqual(['done'])
205 })
206})
207
208/**
209 * The same delivery-durability guarantees over the NDJSON wire encoding
210 * (`?transport=ndjson`). NDJSON has no native event-id, so each durable line is
211 * an `{ id, chunk }` envelope carrying the opaque offset. The durability layer
212 * is shared with SSE — only the parsing differs.
213 */
214function parseNdjson(body: string): Array<SseEvent> {
215 return body
216 .split('\n')
217 .filter((line) => line.trim().length > 0)
218 .map((line) => {
219 const parsed = JSON.parse(line) as Record<string, unknown>
220 // Mirror the production `isNdjsonEnvelope` discriminator exactly: an
221 // envelope carries `id` + `chunk` and no top-level `type`.
222 if (
223 'chunk' in parsed &&
224 'id' in parsed &&
225 typeof parsed.id === 'string' &&
226 !('type' in parsed)
227 ) {
228 return { id: parsed.id, data: parsed.chunk }
229 }
230 return { data: parsed }
231 })
232}
233
234test.describe('delivery durability (ndjson)', () => {
235 test('disconnect → reconnect resumes the ordered stream exactly once', async ({
236 request,
237 }) => {
238 const produce = await request.post(
239 '/api/durable-delivery?transport=ndjson',
240 {
241 data: {},
242 },
243 )
244 expect(produce.ok()).toBeTruthy()
245 const produced = parseNdjson(await produce.text())
246
247 expect(contentDeltas(produced)).toEqual(['1', '2', '3', '4', '5'])
248 expect(produced.every((e) => e.id !== undefined)).toBeTruthy()
249
250 // Index 3: marker, RUN_STARTED, "1", "2" — dropped after content "2".
251 const resumeFrom = produced[3]!.id!
252 const reconnect = await request.post(
253 '/api/durable-delivery?transport=ndjson',
254 {
255 headers: { 'Last-Event-ID': resumeFrom },
256 data: {},
257 },
258 )
259 expect(reconnect.ok()).toBeTruthy()
260 const resumed = parseNdjson(await reconnect.text())
261
262 expect(contentDeltas(resumed)).toEqual(['3', '4', '5'])
263 expect(eventType(resumed[resumed.length - 1]!)).toBe('RUN_FINISHED')
264 expect(resumed.map((event) => event.id)).not.toContain(resumeFrom)
265 })
266
267 test('a second tab joins an existing run from the start', async ({
268 request,
269 }) => {
270 const produce = await request.post(
271 '/api/durable-delivery?transport=ndjson',
272 {
273 data: {},
274 },
275 )
276 const produced = parseNdjson(await produce.text())
277 const runId = produce.headers()['x-run-id']
278 if (!runId) throw new Error('Missing X-Run-Id response header')
279 expect(produced.length).toBeGreaterThan(0)
280
281 const join = await request.get(
282 `/api/durable-delivery?transport=ndjson&offset=-1&runId=${encodeURIComponent(runId)}`,
283 )
284 expect(join.ok()).toBeTruthy()
285 const joined = parseNdjson(await join.text())
286
287 expect(contentDeltas(joined)).toEqual(['1', '2', '3', '4', '5'])
288 // The from-start join replays the run-accepted marker first, then the run.
289 expect(eventType(joined[0]!)).toBe('CUSTOM')
290 expect(eventType(joined[1]!)).toBe('RUN_STARTED')
291 expect(eventType(joined[joined.length - 1]!)).toBe('RUN_FINISHED')
292 })
293})