Open History to see the last commit
1import { WebSocketServer } from 'ws'
2import {
3 memoryStream,
4 resumeWebSocketStream,
5 toWebSocketStream,
6} from '@tanstack/ai'
7import { fixedRun } from '../routes/api.durable-delivery'
8import type { Plugin } from 'vite'
9import type { WebSocketLike } from '@tanstack/ai'
10
11/**
12 * A Vite dev-server plugin exposing a WebSocket arm of the provider-free
13 * delivery-durability harness (see `api.durable-delivery.ts` for the SSE/
14 * NDJSON arms — same `fixedRun` sequence, same `memoryStream` durability
15 * sink). The e2e app is served by Vite/Nitro on plain Node, which has no
16 * `WebSocketPair`, so `toWebSocketResponse`/`resumeWebSocketResponse` (the
17 * Cloudflare wrapper) can't be used here. Instead this hooks the underlying
18 * Node http server's `upgrade` event directly — the same pattern
19 * `examples/ts-group-chat/chat-server/vite-plugin.ts` uses for its Cap'n Web
20 * socket — obtains a server socket via `ws`'s `WebSocketServer({ noServer:
21 * true })`, and hands it to `toWebSocketStream`/`resumeWebSocketStream`.
22 *
23 * Exempt from the aimock policy: this streams the same fixed AG-UI sequence
24 * as the SSE/NDJSON arms and never reaches an LLM provider's HTTP layer.
25 *
26 * Wire protocol (mirrors `stream-to-websocket.ts`):
27 * - Connect to `/api/durable-delivery-ws?runId=<id>` and send one
28 * `RunAgentInput`-shaped JSON frame to start a fresh run — frames come back
29 * as `{ id, chunk }` envelopes (durable) or bare chunks, plus periodic
30 * `{ type: 'ping' }` heartbeats to ignore.
31 * - Connect to `/api/durable-delivery-ws?runId=<id>&offset=<lastId>` to
32 * resume: no input frame is sent, the log replays strictly after `offset`.
33 * - `?dropAfter=<n>` (fresh runs only) simulates a mid-run connection drop for
34 * the client-adapter reconnect e2e: the server closes the socket after
35 * forwarding n frames while the run keeps producing into the durability
36 * log, so the client's auto-reconnect can replay the remainder.
37 */
38const WS_PATH = '/api/durable-delivery-ws'
39
40/**
41 * Wrap a socket so the client sees the connection drop after `dropAfter`
42 * outbound frames. Later frames are swallowed BY DESIGN (they're the "frames
43 * lost to a dead connection" half of the simulation) while the producer keeps
44 * appending them to the durability log; once the terminal frame has been
45 * produced (the log is complete) the socket closes, so the client's
46 * auto-reconnect deterministically replays the full remainder from the log.
47 */
48function dropAfterSocket(ws: WebSocketLike, dropAfter: number): WebSocketLike {
49 let sent = 0
50 const addEventListener: WebSocketLike['addEventListener'] = (
51 type: 'message' | 'close' | 'error',
52 handler: (ev: { data: unknown }) => void,
53 ) => {
54 if (type === 'message') ws.addEventListener(type, handler)
55 else ws.addEventListener(type, () => handler({ data: undefined }))
56 }
57 return {
58 send: (data) => {
59 sent += 1
60 if (sent <= dropAfter) {
61 ws.send(data)
62 return
63 }
64 if (data.includes('RUN_FINISHED')) ws.close()
65 },
66 close: (code, reason) => ws.close(code, reason),
67 addEventListener,
68 }
69}
70
71export function durableDeliveryWebSocketPlugin(): Plugin {
72 return {
73 name: 'durable-delivery-websocket-plugin',
74 enforce: 'pre',
75 configureServer(server) {
76 if (!server.httpServer) return
77 const wss = new WebSocketServer({ noServer: true })
78
79 server.httpServer.on('upgrade', (req, socket, head) => {
80 const url = new URL(
81 req.url ?? '/',
82 `http://${req.headers.host ?? 'localhost'}`,
83 )
84 if (url.pathname !== WS_PATH) return
85
86 wss.handleUpgrade(req, socket, head, (ws) => {
87 // `ws`'s socket satisfies WebSocketLike structurally — no adapter
88 // (and no runtime guard) needed.
89 const request = new Request(url)
90 if (url.searchParams.get('offset') !== null) {
91 resumeWebSocketStream(ws, {
92 adapter: memoryStream(request),
93 })
94 } else {
95 const dropAfter = Number(url.searchParams.get('dropAfter'))
96 toWebSocketStream(
97 dropAfter > 0 ? dropAfterSocket(ws, dropAfter) : ws,
98 request,
99 {
100 durability: (ctx) => memoryStream(ctx.request),
101 onRun: ({ runId, threadId }) => fixedRun(threadId, runId),
102 },
103 )
104 }
105 })
106 })
107 },
108 }
109}