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

delivery-durability.spec.ts

254 lines9.7 KB

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
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 })
47​
48function eventType(e: SseEvent): string {
49 return (e.data as { type: string }).type
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)
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 (agent loop)', () => {
115 test('delivers a full tool-calling run, not truncated at the first RUN_FINISHED', async ({
116 request,
117 }) => {
118 // A tool-calling run emits a RUN_FINISHED per iteration (finishReason
119 // "tool_calls" then "stop"). Regression guard: the durable sink must deliver
120 // the tool result and the second iteration that follow the FIRST terminal —
121 // a sink that ended the log on the first RUN_FINISHED stranded tool-calling
122 // runs at the tool call.
123 const produce = await request.post(
124 '/api/durable-delivery?scenario=agent-loop',
125 { data: {} },
126 )
127 expect(produce.ok()).toBeTruthy()
128 const events = parseSse(await produce.text())
129 const types = events.map(eventType)
130​
131 // Both per-iteration terminals arrive (old behaviour stopped after the first).
132 expect(types.filter((t) => t === 'RUN_FINISHED')).toHaveLength(2)
133 // The tool result and the second iteration's reply survive the first terminal.
134 expect(types).toContain('TOOL_CALL_RESULT')
135 expect(contentDeltas(events)).toEqual(['done'])
136 // Every event is offset-tagged, and the log ends on the final 'stop' terminal.
137 expect(events.every((e) => e.id !== undefined)).toBeTruthy()
138 const last = events[events.length - 1]!
139 expect(eventType(last)).toBe('RUN_FINISHED')
140 const metadata = (
141 last.data as { metadata?: { tanstack?: { finishReason?: string } } }
142 ).metadata
143 expect(metadata?.tanstack?.finishReason).toBe('stop')
144 })
145​
146 test('a second tab joins a finished tool-calling run in full', async ({
147 request,
148 }) => {
149 const produce = await request.post(
150 '/api/durable-delivery?scenario=agent-loop',
151 { data: {} },
152 )
153 const runId = produce.headers()['x-run-id']
154 if (!runId) throw new Error('Missing X-Run-Id response header')
155​
156 const join = await request.get(
157 `/api/durable-delivery?offset=-1&runId=${encodeURIComponent(runId)}`,
158 )
159 expect(join.ok()).toBeTruthy()
160 const joined = parseSse(await join.text())
161 const types = joined.map(eventType)
162 // The replayed log is complete: both terminals, the tool result, the reply.
163 expect(types.filter((t) => t === 'RUN_FINISHED')).toHaveLength(2)
164 expect(types).toContain('TOOL_CALL_RESULT')
165 expect(contentDeltas(joined)).toEqual(['done'])
166 })
167})
168​
169/**
170 * The same delivery-durability guarantees over the NDJSON wire encoding
171 * (`?transport=ndjson`). NDJSON has no native event-id, so each durable line is
172 * an `{ id, chunk }` envelope carrying the opaque offset. The durability layer
173 * is shared with SSE — only the parsing differs.
174 */
175function parseNdjson(body: string): Array<SseEvent> {
176 return body
177 .split('\n')
178 .filter((line) => line.trim().length > 0)
179 .map((line) => {
180 const parsed = JSON.parse(line) as Record<string, unknown>
181 // Mirror the production `isNdjsonEnvelope` discriminator exactly: an
182 // envelope carries `id` + `chunk` and no top-level `type`.
183 if (
184 'chunk' in parsed &&
185 'id' in parsed &&
186 typeof parsed.id === 'string' &&
187 !('type' in parsed)
188 ) {
189 return { id: parsed.id, data: parsed.chunk }
190 }
191 return { data: parsed }
192 })
194​
195test.describe('delivery durability (ndjson)', () => {
196 test('disconnect → reconnect resumes the ordered stream exactly once', async ({
197 request,
198 }) => {
199 const produce = await request.post(
200 '/api/durable-delivery?transport=ndjson',
201 {
202 data: {},
203 },
204 )
205 expect(produce.ok()).toBeTruthy()
206 const produced = parseNdjson(await produce.text())
207​
208 expect(contentDeltas(produced)).toEqual(['1', '2', '3', '4', '5'])
209 expect(produced.every((e) => e.id !== undefined)).toBeTruthy()
210​
211 // Index 3: marker, RUN_STARTED, "1", "2" — dropped after content "2".
212 const resumeFrom = produced[3]!.id!
213 const reconnect = await request.post(
214 '/api/durable-delivery?transport=ndjson',
215 {
216 headers: { 'Last-Event-ID': resumeFrom },
217 data: {},
218 },
219 )
220 expect(reconnect.ok()).toBeTruthy()
221 const resumed = parseNdjson(await reconnect.text())
222​
223 expect(contentDeltas(resumed)).toEqual(['3', '4', '5'])
224 expect(eventType(resumed[resumed.length - 1]!)).toBe('RUN_FINISHED')
225 expect(resumed.map((event) => event.id)).not.toContain(resumeFrom)
226 })
227​
228 test('a second tab joins an existing run from the start', async ({
229 request,
230 }) => {
231 const produce = await request.post(
232 '/api/durable-delivery?transport=ndjson',
233 {
234 data: {},
235 },
236 )
237 const produced = parseNdjson(await produce.text())
238 const runId = produce.headers()['x-run-id']
239 if (!runId) throw new Error('Missing X-Run-Id response header')
240 expect(produced.length).toBeGreaterThan(0)
241​
242 const join = await request.get(
243 `/api/durable-delivery?transport=ndjson&offset=-1&runId=${encodeURIComponent(runId)}`,
244 )
245 expect(join.ok()).toBeTruthy()
246 const joined = parseNdjson(await join.text())
247​
248 expect(contentDeltas(joined)).toEqual(['1', '2', '3', '4', '5'])
249 // The from-start join replays the run-accepted marker first, then the run.
250 expect(eventType(joined[0]!)).toBe('CUSTOM')
251 expect(eventType(joined[1]!)).toBe('RUN_STARTED')
252 expect(eventType(joined[joined.length - 1]!)).toBe('RUN_FINISHED')
253 })
254})