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

websockets.md

286 lines12.8 KB

1---
2title: WebSockets
3id: websockets
4description: "Run resumable streams over one WebSocket for the whole chat. Use toWebSocketStream or toWebSocketResponse on the server and webSocket() in the client. The socket resumes after a drop."
5keywords:
6 - websocket transport
7 - toWebSocketStream
8 - toWebSocketResponse
9 - resumeWebSocketStream
10 - resumeWebSocketResponse
11 - full-duplex chat
12 - conversation-scoped socket
13 - websocket reconnect
14 - websocket heartbeat
15---
16​
17`webSocket()` keeps one socket open for the conversation. A durable run reconnects on that socket.
18​
19Every turn goes over the socket, and a resume after a drop does not call the model again.
20​
21## Quick setup
22​
23### 1. Handle a turn on the server
24​
25`toWebSocketStream` reads each frame from the client, starts one `chat()` turn through `onRun`, and sends the chunks back:
26​
27```ts
28// handle-chat-socket.ts
29import { chat, memoryStream, toWebSocketStream } from '@tanstack/ai'
30import { openaiText } from '@tanstack/ai-openai'
31import type { WebSocketLike } from '@tanstack/ai'
32​
33// Connect the per-turn AbortSignal from WsRunContext to the
34// AbortController that chat() expects.
35function abortControllerFromSignal(signal: AbortSignal): AbortController {
36 const controller = new AbortController()
37 if (signal.aborted) controller.abort(signal.reason)
38 else
39 signal.addEventListener('abort', () => controller.abort(signal.reason), {
40 once: true,
41 })
42 return controller
44​
45// `socket` is a WHATWG-shaped server socket that you already accepted (see
46// step 2) and `request` is the original handshake request.
47export function handleChatSocket(socket: WebSocketLike, request: Request) {
48 toWebSocketStream(socket, request, {
49 // One durability log per turn, keyed by the runId of the frame.
50 durability: (ctx) => memoryStream(ctx.request),
51 onRun: ({ messages, threadId, runId, signal }) =>
52 chat({
53 adapter: openaiText('gpt-6.1-sol'),
54 messages,
55 threadId,
56 runId,
57 abortController: abortControllerFromSignal(signal),
58 }),
59 })
61```
62​
63### 2. Accept the socket
64​
65How you accept the socket depends on where you host. See [Hosting on Node](#hosting-on-node) or [Hosting on Cloudflare](#hosting-on-cloudflare) below.
66​
67### 3. Connect from the client
68​
69```tsx
70import { useChat, webSocket } from '@tanstack/ai-react'
71​
72const connection = webSocket('/api/chat-ws')
73​
74export function Chat() {
75 const { messages, sendMessage } = useChat({ connection, threadId: 'support-chat' })
76 return (
77 <div>
78 {messages.map((message) => (
79 <div key={message.id}>{message.role}</div>
80 ))}
81 <button type="button" onClick={() => void sendMessage('Hello')}>
82 Send
83 </button>
84 </div>
85 )
87```
88​
89`webSocket()` opens the socket on the first `sendMessage`, and uses it again for every later turn. The Solid, Vue, Svelte, and Angular packages export it too.
90​
91Everything else stays the same: `messages`, `sendMessage`, `stop()`, tool calls, and persistence work as with any other connection.
92​
93If the network drops during a reply, the server stops that reply. The client keeps the part it already got. See [Producer vs. socket lifecycle](#producer-vs-socket-lifecycle).
94​
95## How it works
96​
97One socket carries many turns:
98​
991. The client opens the socket once.
1002. Each user message becomes one JSON frame, with the same shape as the SSE or NDJSON `POST` body.
1013. The server runs one `chat()` turn for each frame, and streams the chunks back over the same socket.
1024. After `RUN_FINISHED`, the socket stays open for the next frame. It closes when the client closes it, an idle timeout fires, or the process aborts.
103​
104This page covers request and reply only. For pushes that the server starts by itself, you need your own framing on top.
105​
106## Hosting on Node
107​
108Plain Node has no global `WebSocketPair`, so it cannot accept a WebSocket upgrade by itself. Accept the socket yourself, then give it to `toWebSocketStream`:
109​
1101. Listen to the `upgrade` event of the HTTP server.
1112. Accept the socket with `new WebSocketServer({ noServer: true })` from [`ws`](https://github.com/websockets/ws).
1123. Pass the socket on. The `ws` socket already has the `send`, `close`, and `addEventListener` methods that `WebSocketLike` needs.
113​
114```ts ignore
115import { WebSocketServer } from 'ws'
116import { memoryStream, resumeWebSocketStream } from '@tanstack/ai'
117import type { Plugin } from 'vite'
118import { handleChatSocket } from './handle-chat-socket'
119​
120const WS_PATH = '/api/chat-ws'
121​
122export function webSocketChatPlugin(): Plugin {
123 return {
124 name: 'websocket-chat-plugin',
125 configureServer(server) {
126 if (!server.httpServer) return
127 const wss = new WebSocketServer({ noServer: true })
128​
129 server.httpServer.on('upgrade', (req, socket, head) => {
130 const url = new URL(req.url ?? '/', `http://${req.headers.host}`)
131 if (url.pathname !== WS_PATH) return
132​
133 wss.handleUpgrade(req, socket, head, (ws) => {
134 // The `ws` socket satisfies WebSocketLike as it is. No adapter needed.
135 const request = new Request(url)
136 if (url.searchParams.get('offset') !== null) {
137 resumeWebSocketStream(ws, { adapter: memoryStream(request) })
138 } else {
139 handleChatSocket(ws, request)
140 }
141 })
142 })
143 },
144 }
146```
147​
148The [`examples/ts-react-chat`](https://github.com/TanStack/ai/blob/main/examples/ts-react-chat/src/lib/websocket-chat-plugin.ts) WebSocket example and the e2e suite's [`durable-delivery-ws-plugin.ts`](https://github.com/TanStack/ai/blob/main/testing/e2e/src/lib/durable-delivery-ws-plugin.ts) use the same pattern.
149​
150Other runtimes follow the same steps: accept the socket of the platform, then call `toWebSocketStream` or `resumeWebSocketStream` with it.
151​
152- A socket from `Deno.upgradeWebSocket` is WHATWG-shaped and satisfies `WebSocketLike` directly.
153- The Bun `ServerWebSocket` (handler-object API) needs a small adapter first.
154​
155## Hosting on Cloudflare
156​
157Cloudflare Workers and Durable Objects have a global `WebSocketPair`, so you do not upgrade by hand. `toWebSocketResponse` creates the pair, accepts the server half, connects it to `toWebSocketStream`, and returns the `101` upgrade `Response`:
158​
159```ts
160import { chat, toWebSocketResponse } from '@tanstack/ai'
161import { openaiText } from '@tanstack/ai-openai'
162​
163export default {
164 fetch(request: Request): Response {
165 return toWebSocketResponse(request, {
166 onRun: ({ messages, threadId, runId }) =>
167 chat({ adapter: openaiText('gpt-6.1-sol'), messages, threadId, runId }),
168 })
169 },
171```
172​
173`resumeWebSocketResponse({ adapter })` is the matching read-only wrapper for a `?offset=` resume.
174​
175If you call either one in a runtime without `WebSocketPair` (Node, for example), it throws. The message points to its `*Stream` version. So you cannot ship the Cloudflare wrapper to a runtime that cannot upgrade a socket.
176​
177## Advanced
178​
179### The `onRun` context
180​
181`onRun` gets one `WsRunContext` for each frame from the client:
182​
183| Field | What it is |
184| --- | --- |
185| `messages` | The `UIMessage[]` or `ModelMessage[]` of the turn, read from the frame. |
186| `threadId` / `runId` | The AG-UI ids for this turn. |
187| `forwardedProps` | Any extra data that the client sent with the frame. |
188| `request` | A synthetic `Request` for the turn, with `?runId=` in its URL. Use it to key a durability adapter. |
189| `signal` | Aborts when the socket closes, or when this turn gets an `abort` frame. It does not abort other turns on the same socket. |
190​
191If a socket does not need to survive a drop, leave out `durability`. `toWebSocketStream` still sends the chunks, but it cannot replay them on reconnect.
192​
193### Client options
194​
195| Option | What it does |
196| --- | --- |
197| `protocols` | WebSocket subprotocols, passed to the `WebSocket` constructor as they are. |
198| `body` | Static extra fields added to every outgoing `RunAgentInput` frame. Same as `body` on the HTTP connections. |
199| `reconnect` | Reconnect limits (`maxAttempts`, `delayMs`). They work the same as on `fetchServerSentEvents`. See [Advanced](./advanced). |
200| `WebSocketImpl` | Your own `WebSocket` implementation, for tests and non-browser runtimes. |
201​
202[Transports](../transports/overview) shows where `webSocket()` fits next to the other connections.
203​
204### Wire protocol
205​
206| Direction | Frame | Meaning |
207| --- | --- | --- |
208| Client to server | A `RunAgentInput`-shaped JSON object (same shape as the SSE or NDJSON `POST` body) | Start one `chat()` turn. |
209| Client to server | `{ "type": "abort", "runId": "..." }` | Abort one running turn. |
210| Server to client | `{ "id": "...", "chunk": <StreamChunk> }` | One chunk with a durability offset. Only when `durability` is set. |
211| Server to client | A bare `StreamChunk` | One chunk with no offset. When `durability` is not set. |
212| Server to client | `{ "type": "ping" }` | Heartbeat. `webSocket()` drops these. A hand-written client must ignore anything with `type: "ping"`. |
213​
214The two chunk shapes from the server cannot be confused. The envelope never has a top-level `type`, and every bare `StreamChunk` has one.
215​
216### Resume rides in the URL, not a header
217​
218SSE and NDJSON resume with the `Last-Event-ID` header, because a `fetch` or XHR request can set headers. The browser `WebSocket` constructor cannot set custom headers on the handshake. So the offset goes in the URL: `?runId=<id>&offset=<lastId>`.
219​
220`webSocket()` does this for you:
221​
222- A durable run sends envelopes with offsets. If the socket drops before the terminal chunk of that run (`RUN_FINISHED` or `RUN_ERROR`), the client opens the socket again at `?runId=&offset=`. It also removes the duplicate at the replay boundary. This is the same reconnect guarantee as `fetchServerSentEvents`.
223- If a run never sent an offset (no `durability`), there is nothing to resume from. The drop shows as a connection error, and the client does not retry forever.
224​
225On the server, a URL with `?offset=` is a resume, not a new turn. Send it to `resumeWebSocketStream`. It replays the durability log, read-only, with no model call:
226​
227```ts
228import { memoryStream, resumeWebSocketStream } from '@tanstack/ai'
229import type { WebSocketLike } from '@tanstack/ai'
230​
231export function handleResumeSocket(socket: WebSocketLike, request: Request) {
232 resumeWebSocketStream(socket, { adapter: memoryStream(request) })
234```
235​
236If the request has no resume offset, `resumeWebSocketStream` closes the socket with code `1008`, because there is nothing to replay.
237​
238### Durability is per turn
239​
240One socket carries many turns, so you cannot make one durability adapter for the whole connection. Each turn needs its own log, keyed by the `runId` of that turn.
241​
242That is why `durability` in `toWebSocketStream` is a factory, not a value. It gets the per-turn `ctx` and reads `ctx.request`. The URL of that request already has the `?runId=` of the turn, and `memoryStream` and `durableStream` read it.
243​
244### Abort a turn
245​
246An `{ type: 'abort', runId }` frame aborts only the `onRun` work of that turn (`ctx.signal` fires). The socket stays open for the next turn.
247​
248The built-in `webSocket()` connection sends this frame when the abort signal of the run fires, for example on `stop()` in `useChat`. So the server stops the generation, and does not run the model call to the end for a client that stopped listening. A hand-written client must send the same frame to cancel a turn.
249​
250When the whole socket closes, every turn that still runs on it aborts.
251​
252### Heartbeat and idle timeout
253​
254`toWebSocketStream` sends a `{ type: 'ping' }` frame every `heartbeatMs` (default 30 seconds). This keeps the connection alive through proxies that drop idle sockets.
255​
256It closes the socket if no frame arrives from the client for `idleTimeoutMs` (default 5 minutes).
257​
258- A heartbeat does not count as activity. Only a frame from the client counts.
259- The idle timeout never fires while a turn still streams. So a long generation, such as an agent loop longer than the timeout, is never cut off.
260​
261```ts
262import { chat, toWebSocketStream } from '@tanstack/ai'
263import { openaiText } from '@tanstack/ai-openai'
264import type { WebSocketLike } from '@tanstack/ai'
265​
266function handleChatSocket(socket: WebSocketLike, request: Request) {
267 toWebSocketStream(socket, request, {
268 onRun: ({ messages, threadId, runId }) =>
269 chat({ adapter: openaiText('gpt-6.1-sol'), messages, threadId, runId }),
270 heartbeatMs: 15_000,
271 idleTimeoutMs: 60_000,
272 })
274```
275​
276### Producer vs. socket lifecycle
277​
278On a WebSocket, the producer is tied to the socket. When the socket closes or errors, `toWebSocketStream` aborts every turn on it. That abort stops the `chat()` call behind each turn. This is true with `memoryStream` and with `durableStream`.
279​
280So after a drop:
281​
2821. The server stops the reply.
2832. The durability log keeps the chunks produced up to the drop, then ends with an abort `RUN_ERROR`.
2843. A reconnect replays that partial reply. It does not continue the run.
285​
286To keep a reply going across a dropped connection, use SSE or NDJSON with `durableStream`. There the producer does not stop when the client goes away. See [memoryStream in production](./advanced#memorystream-in-production).