feat: WebSocket transport — full-duplex resumable streams #969
main fromrefs/pull/969/headmerged by AlemTuzlak View on GitHub- docs/chat/connection-adapters.md lines 318 to 353Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -295,3 +296,17 @@295296 });296297 ```297298299+## WebSockets300+301+For a persistent, resumable WebSocket, use the built-in `webSocket()` adapter instead of hand-rolling a `SubscribeConnectionAdapter`. It opens one socket for the whole conversation, reconnects a dropped durable run automatically, and pairs with the server's `toWebSocketStream` / `toWebSocketResponse`:302+303+```typescript304+import { useChat, webSocket } from "@tanstack/ai-react";305+306+const connection = webSocket("/api/chat-ws");307+308+const { messages, sendMessage } = useChat({ connection });309+```310+311+See [WebSockets](../resumable-streams/websockets) for the server side, the wire protocol, reconnect details, and hosting on Node vs Cloudflare.312+docs/resumable-streams/websockets.md line 243OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +223,21 @@223+import { memoryStream, resumeWebSocketStream, toWebSocketStream } from '@tanstack/ai'224+import type { Plugin } from 'vite'225+import type { WebSocketLike } from '@tanstack/ai'226+import { handleChatSocket } from './handle-chat-socket'227+228+const WS_PATH = '/api/chat-ws'229+230+export function webSocketChatPlugin(): Plugin {231+ return {232+ name: 'websocket-chat-plugin',233+ configureServer(server) {234+ if (!server.httpServer) return235+ const wss = new WebSocketServer({ noServer: true })236+237+ server.httpServer.on('upgrade', (req, socket, head) => {238+ const url = new URL(req.url ?? '/', `http://${req.headers.host}`)239+ if (url.pathname !== WS_PATH) return240+241+ wss.handleUpgrade(req, socket, head, (ws) => {242+ const request = new Request(url)243+ const socketLike = ws as unknown as WebSocketLikepackages/ai-client/src/connection-adapters.ts lines 1690 to 1691OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1562,0 +1671,21 @@1671+ let currentSession: WebSocketRunSession | undefined1672+1673+ function failAll(error: unknown): void {1674+ for (const l of listeners) l.fail(error)1675+ }1676+1677+ function openOnce(target: string): WebSocket {1678+ if (socket && socket.readyState <= 1) return socket1679+ const ws = options.protocols1680+ ? new Impl(target, options.protocols)1681+ : new Impl(target)1682+ socket = ws1683+ openPromise = new Promise<void>((resolve, reject) => {1684+ ws.onopen = () => resolve()1685+ ws.onerror = (e) => reject(new StreamReadError(e))1686+ })1687+ // Attach a no-op handler so a socket nobody awaits (e.g. joinRun) can't raise1688+ // an unhandled rejection if it errors. Awaiters of openPromise still see the rejection.1689+ openPromise.catch(() => {})1690+ ws.onmessage = (event: MessageEvent) => {1691+ const parsed: unknown = JSON.parse(String(event.data))packages/ai-client/src/connection-adapters.ts lines 2161 to 2182Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1562,0 +1714,21 @@1714+ }1715+ if (chunk.type === 'RUN_FINISHED' || chunk.type === 'RUN_ERROR') {1716+ session.sawTerminal = true1717+ }1718+ }1719+ for (const l of listeners) l.push(chunk)1720+ }1721+ ws.onclose = () => {1722+ const session = currentSession1723+ if (!session || session.signal?.aborted || session.sawTerminal) return1724+ const lastEventId = session.tracker.lastEventId1725+ if (lastEventId === undefined) {1726+ // Non-durable run (no offset ever observed) — nothing to resume1727+ // from. Surface a hard failure rather than silently reconnecting1728+ // forever against a server that never tags its events.1729+ currentSession = undefined1730+ failAll(new StreamReadError(new Error('WebSocket connection closed')))1731+ return1732+ }1733+ void reconnect(session, lastEventId)1734+ }packages/ai/src/stream-to-websocket.ts lines 214 to 278Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +201,21 @@201+ logger,202+ },203+ )204+ for await (const chunk of source) {205+ socket.send(encodeWsFrame(chunk, getId(chunk)))206+ }207+ } else {208+ for await (const chunk of init.onRun(ctx)) {209+ socket.send(encodeWsFrame(chunk, undefined))210+ }211+ }212+ } finally {213+ // Only delete if this turn still owns the entry: a duplicate in-flight214+ // runId (e.g. a client resubmitting before the first turn finished)215+ // would otherwise let the OLDER turn's cleanup delete the NEWER turn's216+ // still-active controller (TOCTOU).217+ if (activeTurns.get(params.runId) === turnAbort) {218+ activeTurns.delete(params.runId)219+ }220+ }221+ }
tombeckenham assignedjherr
tombeckenham added labelswaiting-on: author
AlemTuzlak removed labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) added labelsmerge-conflicts
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelsmerge-conflicts
github-actions[bot](GitHub profile, opens in a new tab) added labelsmerge-conflicts
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelsmerge-conflicts
github-actions[bot](GitHub profile, opens in a new tab) added labelsmerge-conflicts
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelsmerge-conflicts
github-actions[bot](GitHub profile, opens in a new tab) added labelsmerge-conflicts
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelsmerge-conflicts
github-actions[bot](GitHub profile, opens in a new tab) added labelsmerge-conflicts
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelsmerge-conflicts
- @@ -0,0 +46,21 @@46+ return true47+}48+49+export function durableDeliveryWebSocketPlugin(): Plugin {50+ return {51+ name: 'durable-delivery-websocket-plugin',52+ enforce: 'pre',53+ configureServer(server) {54+ if (!server.httpServer) return55+ 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) return63+64+ wss.handleUpgrade(req, socket, head, (ws) => {65+ const request = new Request(url)66+ if (!isWebSocketLike(ws)) return
- @@ -0,0 +100,21 @@100+## Client: `webSocket()`101+102+`webSocket()` is a `SubscribeConnectionAdapter` for `useChat` (also exported103+from `@tanstack/ai-solid`, `@tanstack/ai-vue`, `@tanstack/ai-svelte`, and104+`@tanstack/ai-angular`). It opens the socket lazily on the first105+`sendMessage`, and reuses it for every later turn in the conversation:106+107+```tsx108+import { useChat, webSocket } from '@tanstack/ai-react'109+110+const connection = webSocket('/api/chat-ws')111+112+export function Chat() {113+ const { messages, sendMessage } = useChat({ connection })114+115+ return <button onClick={() => void sendMessage('Hello')}>Send</button>116+}117+```118+119+Nothing else changes: `messages`, `sendMessage`, `stop()`, tool calls, and120+persistence all work the same as with any other connection adapter. Options:@@ -0,0 +172,21 @@172+173+`resumeWebSocketStream` closes the socket with code `1008` if the request174+carries no resume offset: there's nothing to replay.175+176+## Durability is per turn177+178+A conversation-scoped socket carries many turns, so its durability adapter179+can't be built once for the whole connection. Each turn needs its own log,180+keyed by that turn's `runId`. That's why `durability` in `toWebSocketStream`181+is a factory, not a value: it receives the per-turn `ctx` and reads182+`ctx.request`, whose URL already carries that turn's `?runId=`183+(`memoryStream`/`durableStream` key off it automatically).184+185+## Abort a turn186+187+An `{ type: 'abort', runId }` frame aborts only that turn's `onRun` iteration188+(`ctx.signal` fires); the socket itself stays open for the next turn. The189+built-in `webSocket()` client adapter sends this frame when the run's abort190+signal fires (`stop()` in `useChat`), so the server actually stops generating191+instead of running the model call to completion against a client that stopped192+listening. A hand-rolled client should send the same frame to cancel a turn.@@ -1900,0 +2291,21 @@2291+ const body = buildRunAgentInputBody(messages, data, runContext, {2292+ body: options.body,2293+ })2294+ ws.send(JSON.stringify(body))2295+ },2296+ joinRun(runId, abortSignal): AsyncIterable<StreamChunk> {2297+ const target = withSearchParams(typeof url === 'function' ? url() : url, {2298+ offset: '-1',2299+ runId,2300+ })2301+ // A replay handshake must reach the server as its own connection:2302+ // reusing the conversation socket would discard the ?offset query (no2303+ // replay ever requested), and the conversation socket must not be2304+ // replaced by a read-only replay socket. So joinRun owns a dedicated2305+ // socket and never touches the shared socket or run session.2306+ const ws = options.protocols2307+ ? new Impl(target, options.protocols)2308+ : new Impl(target)2309+ const pipe = createChunkPipe(abortSignal, () => {2310+ if (ws.readyState <= 1) ws.close()2311+ })@@ -0,0 +103,21 @@103+ debug?: DebugOption104+}105+106+/**107+ * Run a full-duplex, conversation-scoped chat over an already-accepted server108+ * socket. Each inbound RunAgentInput frame starts one chat() turn (via onRun)109+ * whose chunks are pumped back as frames; the socket stays open across turns110+ * (pending client-tool resubmit, next user message) until the client closes it111+ * or the idle timeout fires. An abort control frame aborts only its turn.112+ */113+export function toWebSocketStream<TOffset extends string = string>(114+ socket: WebSocketLike,115+ request: Request,116+ init: WebSocketStreamInit<TOffset>,117+): void {118+ const logger = resolveDebugOption(init.debug)119+ const activeTurns = new Map<string, AbortController>()120+ // Abort frames that raced ahead of their run's registration: `handleInbound`121+ // awaits body validation before it registers into `activeTurns`, so an abort122+ // arriving inside that window would otherwise be silently discarded.123+ const earlyAborts = new Set<string>()
tombeckenham approved these changes
AlemTuzlak merged thisecd12a4
AlemTuzlak closed this
Sign in to join this conversation.
🚀 Changeset Version Preview#
8 package(s) bumped directly, 39 bumped as dependents.
🟥 Major bumps#
@tanstack/ai-angular@tanstack/ai-durable-stream@tanstack/ai-react@tanstack/ai-solid@tanstack/ai-svelte@tanstack/ai-vue@tanstack/ai-acp@tanstack/ai-anthropic@tanstack/ai-bedrock@tanstack/ai-claude-code@tanstack/ai-code-mode@tanstack/ai-code-mode-skills@tanstack/ai-codex@tanstack/ai-elevenlabs@tanstack/ai-fal@tanstack/ai-gemini@tanstack/ai-grok@tanstack/ai-grok-build@tanstack/ai-groq@tanstack/ai-isolate-node@tanstack/ai-isolate-quickjs@tanstack/ai-mistral@tanstack/ai-ollama@tanstack/ai-openai@tanstack/ai-opencode@tanstack/ai-openrouter@tanstack/ai-preact@tanstack/ai-react-ui@tanstack/ai-sandbox@tanstack/ai-sandbox-cloudflare@tanstack/ai-sandbox-daytona@tanstack/ai-sandbox-docker@tanstack/ai-sandbox-local-process@tanstack/ai-sandbox-sprites@tanstack/ai-sandbox-vercel@tanstack/ai-solid-ui@tanstack/openai-base🟨 Minor bumps#
@tanstack/ai@tanstack/ai-client🟩 Patch bumps#
@tanstack/ai-devtools-core@tanstack/ai-isolate-cloudflare@tanstack/ai-mcp@tanstack/ai-vue-ui@tanstack/preact-ai-devtools@tanstack/react-ai-devtools@tanstack/solid-ai-devtoolsag-ui