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

websocket-chat-plugin.ts

89 lines3.3 KB

1import { WebSocketServer } from 'ws'
2import {
3 chat,
4 memoryStream,
5 resumeWebSocketStream,
6 toWebSocketStream,
7} from '@tanstack/ai'
8import { openaiText } from '@tanstack/ai-openai'
9import type { Plugin } from 'vite'
10​
11/**
12 * A Vite dev-server plugin exposing a full-duplex WebSocket chat endpoint.
13 * This app is served by Vite/Nitro on plain Node, which has no
14 * `WebSocketPair`, so `toWebSocketResponse`/`resumeWebSocketResponse` (the
15 * Cloudflare wrapper) can't be used here. Instead this hooks the underlying
16 * Node http server's `upgrade` event directly — obtains a server socket via
17 * `ws`'s `WebSocketServer({ noServer: true })`, and hands it to
18 * `toWebSocketStream`/`resumeWebSocketStream`. Mirrors
19 * `testing/e2e/src/lib/durable-delivery-ws-plugin.ts`, which uses the same
20 * pattern for a provider-free harness.
21 *
22 * Wire protocol (client side is `webSocket('/api/chat-ws')` from
23 * `@tanstack/ai-react`):
24 * - Connect to `/api/chat-ws` and send one `RunAgentInput`-shaped JSON frame
25 * per turn to run the model — frames come back as `{ id, chunk }`
26 * envelopes (durable) plus periodic `{ type: 'ping' }` heartbeats.
27 * - Connect to `/api/chat-ws?offset=<lastId>` to resume a dropped run: no
28 * input frame is sent, the durability log replays strictly after `offset`.
29 */
30const WS_PATH = '/api/chat-ws'
31​
32/**
33 * `chat()` cancels via an `AbortController` it can read `.signal` off of, but
34 * `WsRunContext` (the per-turn context `toWebSocketStream` hands `onRun`)
35 * only carries the `AbortSignal` half — it aborts on socket close or an
36 * `{ type: 'abort', runId }` control frame. Bridge the two by mirroring the
37 * signal onto a fresh controller.
38 */
39function abortControllerFromSignal(signal: AbortSignal): AbortController {
40 const controller = new AbortController()
41 if (signal.aborted) controller.abort(signal.reason)
42 else
43 signal.addEventListener('abort', () => controller.abort(signal.reason), {
44 once: true,
45 })
46 return controller
48​
49export function webSocketChatPlugin(): Plugin {
50 return {
51 name: 'websocket-chat-plugin',
52 enforce: 'pre',
53 configureServer(server) {
54 if (!server.httpServer) return
55 const wss = new WebSocketServer({ noServer: true })
56​
57 server.httpServer.on('upgrade', (req, socket, head) => {
58 const url = new URL(
59 req.url ?? '/',
60 `http://${req.headers.host ?? 'localhost'}`,
61 )
62 if (url.pathname !== WS_PATH) return
63​
64 wss.handleUpgrade(req, socket, head, (ws) => {
65 // `ws`'s socket satisfies WebSocketLike structurally — no adapter
66 // (and no runtime guard) needed.
67 const request = new Request(url)
68 if (url.searchParams.get('offset') !== null) {
69 resumeWebSocketStream(ws, {
70 adapter: memoryStream(request),
71 })
72 } else {
73 toWebSocketStream(ws, request, {
74 durability: (ctx) => memoryStream(ctx.request),
75 onRun: ({ messages, threadId, runId, signal }) =>
76 chat({
77 adapter: openaiText('gpt-5.5'),
78 messages,
79 threadId,
80 runId,
81 abortController: abortControllerFromSignal(signal),
82 }),
83 })
84 }
85 })
86 })
87 },
88 }