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

websocket.spec.ts

201 lines7.3 KB

1import { expect, test } from '@playwright/test'
2​
3/**
4 * Delivery durability (transport layer) over a real WebSocket.
5 *
6 * Mirrors `delivery-durability.spec.ts` (SSE/NDJSON) but exercises the WS arm
7 * of the same provider-free harness: `api.durable-delivery-ws` streams the
8 * same fixed AG-UI sequence (`fixedRun`) through the same `memoryStream`
9 * durability sink, so join/reconnect assertions stay deterministic. See
10 * `testing/e2e/src/lib/durable-delivery-ws-plugin.ts` for the server side —
11 * the Vite/Nitro dev server runs on plain Node (no `WebSocketPair`), so the
12 * plugin hooks the underlying http server's `upgrade` event directly and
13 * drives `toWebSocketStream`/`resumeWebSocketStream` over a `ws` socket.
14 *
15 * Exempt from the aimock policy: this harness streams a fixed sequence and
16 * never reaches an LLM provider's HTTP layer, so there is nothing to mock.
17 */
18​
19const FIXED_TYPES = [
20 'CUSTOM',
21 'RUN_STARTED',
22 'TEXT_MESSAGE_CONTENT',
23 'TEXT_MESSAGE_CONTENT',
24 'TEXT_MESSAGE_CONTENT',
25 'TEXT_MESSAGE_CONTENT',
26 'TEXT_MESSAGE_CONTENT',
27 'RUN_FINISHED',
29​
30function runInput(runId: string): Record<string, unknown> {
31 return {
32 threadId: 'thread-durable',
33 runId,
34 messages: [],
35 tools: [],
36 context: [],
37 forwardedProps: {},
38 state: {},
39 }
41​
42test.describe('delivery durability (websocket)', () => {
43 test('streams the fixed run in order over a single connection', async ({
44 page,
45 }) => {
46 await page.goto('/')
47​
48 const result = await page.evaluate(
49 async ({ runId, input }) => {
50 const wsUrl = `${location.origin.replace(/^http/, 'ws')}/api/durable-delivery-ws?runId=${encodeURIComponent(runId)}`
51 const ws = new WebSocket(wsUrl)
52 await new Promise<void>((resolve, reject) => {
53 ws.onopen = () => resolve()
54 ws.onerror = () => reject(new Error('ws open failed'))
55 })
56​
57 const received: Array<{ type: string; id?: string }> = []
58 const done = new Promise<void>((resolve) => {
59 ws.onmessage = (e) => {
60 const frame = JSON.parse(e.data as string) as {
61 type?: string
62 id?: string
63 chunk?: { type: string }
64 }
65 const chunk = frame.chunk ?? (frame as { type: string })
66 if (chunk.type === 'ping') return
67 received.push({ type: chunk.type, id: frame.id })
68 if (chunk.type === 'RUN_FINISHED') resolve()
69 }
70 })
71 ws.send(JSON.stringify(input))
72 await done
73 ws.close()
74 return received
75 },
76 { runId: 'e2e-ws-1', input: runInput('e2e-ws-1') },
77 )
78​
79 expect(result.map((r) => r.type)).toEqual(FIXED_TYPES)
80 // Durable frames are tagged with an opaque offset id.
81 expect(result.every((r) => typeof r.id === 'string')).toBeTruthy()
82 })
83​
84 test('reconnect with ?offset resumes the remainder exactly once, in order', async ({
85 page,
86 }) => {
87 await page.goto('/')
88​
89 const result = await page.evaluate(
90 async ({ runId, input }) => {
91 const base = `${location.origin.replace(/^http/, 'ws')}/api/durable-delivery-ws`
92​
93 // First connection: read only the first two chunks, then disconnect.
94 const first = new WebSocket(
95 `${base}?runId=${encodeURIComponent(runId)}`,
96 )
97 await new Promise<void>((resolve, reject) => {
98 first.onopen = () => resolve()
99 first.onerror = () => reject(new Error('ws open failed'))
100 })
101​
102 const firstChunks: Array<{ type: string; id?: string }> = []
103 const gotTwo = new Promise<void>((resolve) => {
104 first.onmessage = (e) => {
105 const frame = JSON.parse(e.data as string) as {
106 id?: string
107 chunk?: { type: string }
108 type?: string
109 }
110 const chunk = frame.chunk ?? (frame as { type: string })
111 if (chunk.type === 'ping') return
112 firstChunks.push({ type: chunk.type, id: frame.id })
113 if (firstChunks.length === 2) resolve()
114 }
115 })
116 first.send(JSON.stringify(input))
117 await gotTwo
118 first.close()
119 // Let the close propagate server-side before reconnecting.
120 await new Promise((r) => setTimeout(r, 50))
121​
122 const lastId = firstChunks[1]!.id!
123​
124 // Second connection: resume from the last acknowledged offset.
125 const second = new WebSocket(
126 `${base}?runId=${encodeURIComponent(runId)}&offset=${encodeURIComponent(lastId)}`,
127 )
128 await new Promise<void>((resolve, reject) => {
129 second.onopen = () => resolve()
130 second.onerror = () => reject(new Error('ws reopen failed'))
131 })
132​
133 const resumedChunks: Array<{ type: string; id?: string }> = []
134 const finished = new Promise<void>((resolve) => {
135 second.onmessage = (e) => {
136 const frame = JSON.parse(e.data as string) as {
137 id?: string
138 chunk?: { type: string }
139 type?: string
140 }
141 const chunk = frame.chunk ?? (frame as { type: string })
142 if (chunk.type === 'ping') return
143 resumedChunks.push({ type: chunk.type, id: frame.id })
144 if (chunk.type === 'RUN_FINISHED') resolve()
145 }
146 })
147 await finished
148 second.close()
149​
150 return { firstChunks, resumedChunks, lastId }
151 },
152 { runId: 'e2e-ws-2', input: runInput('e2e-ws-2') },
153 )
154​
155 // First connection saw the run-accepted marker + RUN_STARTED, then
156 // dropped. A fresh durable producer prepends CUSTOM run.accepted so a
157 // joiner never sees an empty log.
158 expect(result.firstChunks.map((c) => c.type)).toEqual([
159 'CUSTOM',
160 'RUN_STARTED',
161 ])
162​
163 // Resume delivers the 5 content deltas + RUN_FINISHED, in order, with
164 // no duplicates of anything already delivered.
165 expect(result.resumedChunks.map((c) => c.type)).toEqual([
166 'TEXT_MESSAGE_CONTENT',
167 'TEXT_MESSAGE_CONTENT',
168 'TEXT_MESSAGE_CONTENT',
169 'TEXT_MESSAGE_CONTENT',
170 'TEXT_MESSAGE_CONTENT',
171 'RUN_FINISHED',
172 ])
173 const resumedIds = result.resumedChunks.map((c) => c.id)
174 expect(resumedIds).not.toContain(result.lastId)
175 expect(new Set(resumedIds).size).toBe(resumedIds.length)
176 })
177​
178 test('the webSocket() client adapter auto-resumes a server-side drop exactly once, in order', async ({
179 page,
180 }) => {
181 // Unlike the raw-WebSocket tests above, this drives the REAL client
182 // adapter (see /websocket-adapter): the server drops the socket after two
183 // frames (?dropAfter=2), and the adapter's own reconnect machinery must
184 // reopen at ?runId=&offset= and resume the remainder from the log.
185 await page.goto('/websocket-adapter')
186 await page.getByTestId('ws-adapter-run-drop').click()
187​
188 const resultText = page.getByTestId('ws-adapter-result')
189 await expect(resultText).toContainText('RUN_FINISHED', { timeout: 15_000 })
190 const { received } = JSON.parse(
191 (await resultText.textContent()) ?? '{}',
192 ) as { received: Array<{ type: string; delta?: string }> }
193​
194 // The full fixed sequence arrived despite the mid-run drop — no gap where
195 // the connection died, no duplicate around the resume boundary.
196 expect(received.map((c) => c.type)).toEqual(FIXED_TYPES)
197 expect(
198 received.filter((c) => c.delta !== undefined).map((c) => c.delta),
199 ).toEqual(['1', '2', '3', '4', '5'])
200 })
201})