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

websocket-adapter.tsx

81 lines2.8 KB

1import { useEffect, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { webSocket } from '@tanstack/ai-react'
4​
5export const Route = createFileRoute('/websocket-adapter')({
6 component: WebSocketAdapterPage,
7})
8​
9/**
10 * Client-adapter arm of the WebSocket delivery-durability harness: drives the
11 * REAL `webSocket()` connection adapter (not a hand-rolled socket) against
12 * `/api/durable-delivery-ws`, so the adapter's envelope unwrapping, ping
13 * filtering, offset de-dupe, and auto-reconnect are what the e2e asserts.
14 *
15 * "run" streams the fixed sequence over one socket. "run with drop" adds
16 * `?dropAfter=2`, making the server drop the socket after two frames — the
17 * adapter must then reconnect at `?runId=&offset=` and resume the remainder
18 * from the durability log, exactly once and in order.
19 */
20function WebSocketAdapterPage() {
21 const [result, setResult] = useState('')
22 // Buttons enable only after hydration so a Playwright click can't land
23 // before React has attached the handlers (click auto-waits for enabled).
24 const [ready, setReady] = useState(false)
25 useEffect(() => setReady(true), [])
26​
27 async function run(dropAfter: number | null) {
28 const runId = `e2e-ws-adapter-${dropAfter === null ? 'plain' : 'drop'}-${Date.now()}`
29 const base = `${location.origin.replace(/^http/, 'ws')}/api/durable-delivery-ws`
30 const connection = webSocket(
31 dropAfter === null ? base : `${base}?dropAfter=${dropAfter}`,
32 { reconnect: { delayMs: 25, maxAttempts: 5 } },
33 )
34 const controller = new AbortController()
35 const received: Array<{ type: string; delta?: string }> = []
36 const consume = (async () => {
37 for await (const chunk of connection.subscribe(controller.signal)) {
38 received.push({
39 type: chunk.type,
40 ...('delta' in chunk && typeof chunk.delta === 'string'
41 ? { delta: chunk.delta }
42 : {}),
43 })
44 if (chunk.type === 'RUN_FINISHED' || chunk.type === 'RUN_ERROR') {
45 controller.abort()
46 }
47 }
48 })()
49 try {
50 await connection.send([], undefined, undefined, {
51 threadId: 'thread-durable',
52 runId,
53 })
54 await consume
55 setResult(JSON.stringify({ runId, received }))
56 } catch (error) {
57 setResult(JSON.stringify({ runId, received, error: String(error) }))
58 }
59 }
60​
61 return (
62 <div>
63 <h1>webSocket() adapter harness</h1>
64 <button
65 data-testid="ws-adapter-run"
66 disabled={!ready}
67 onClick={() => void run(null)}
68 >
69 run
70 </button>
71 <button
72 data-testid="ws-adapter-run-drop"
73 disabled={!ready}
74 onClick={() => void run(2)}
75 >
76 run with drop
77 </button>
78 <pre data-testid="ws-adapter-result">{result}</pre>
79 </div>
80 )