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

websocket-chat.tsx

116 lines3.3 KB

1import { createFileRoute } from '@tanstack/react-router'
2import { useState } from 'react'
3import { useChat, webSocket } from '@tanstack/ai-react'
4​
5export const Route = createFileRoute('/websocket-chat')({
6 component: WebSocketChatPage,
7})
8​
9// A full-duplex WebSocket connection. `/api/chat-ws` (see
10// `src/lib/websocket-chat-plugin.ts`) records every chunk to a durability
11// log and serves `?offset=` resumes over the same socket protocol, so a
12// dropped connection reconnects and resumes automatically — nothing on the
13// client opts in beyond using `useChat` with `webSocket()`.
14const connection = webSocket('/api/chat-ws')
15​
16function WebSocketChatPage() {
17 const { messages, sendMessage, isLoading, connectionStatus } = useChat({
18 threadId: 'websocket-chat',
19 connection,
20 })
21 const [input, setInput] = useState('Write a short haiku about WebSockets.')
22​
23 const handleSubmit = (e: React.FormEvent) => {
24 e.preventDefault()
25 const text = input.trim()
26 if (!text || isLoading) return
27 setInput('')
28 void sendMessage(text)
29 }
30​
31 return (
32 <div style={page}>
33 <h1>WebSocket chat</h1>
34 <p style={{ color: '#555' }}>
35 This chat talks to the model over a single full-duplex WebSocket instead
36 of HTTP/SSE. The server durably logs each chunk, so a dropped connection
37 reconnects with <code>?offset=</code> and resumes the run rather than
38 restarting the model — all through <code>useChat</code> with the{' '}
39 <code>webSocket()</code> connection adapter.
40 </p>
41​
42 <div style={{ margin: '12px 0', color: '#888', fontSize: 13 }}>
43 connection: <code>{connectionStatus}</code>
44 </div>
45​
46 <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
47 {messages.map((message) => (
48 <div
49 key={message.id}
50 style={message.role === 'user' ? userBubble : assistantBubble}
51 >
52 <div style={roleLabel}>{message.role}</div>
53 {message.parts.map((part, index) =>
54 part.type === 'text' && part.content ? (
55 <p
56 key={`${message.id}-${index}`}
57 style={{ margin: 0, whiteSpace: 'pre-wrap' }}
58 >
59 {part.content}
60 </p>
61 ) : null,
62 )}
63 </div>
64 ))}
65 </div>
66​
67 <form
68 onSubmit={handleSubmit}
69 style={{ marginTop: 16, display: 'flex', gap: 8 }}
70 >
71 <input
72 value={input}
73 onChange={(e) => setInput(e.target.value)}
74 placeholder="Ask something…"
75 style={{ flex: 1, padding: 8 }}
76 />
77 <button type="submit" disabled={isLoading}>
78 {isLoading ? 'Streaming…' : 'Send'}
79 </button>
80 </form>
81 </div>
82 )
84​
85const page: React.CSSProperties = {
86 maxWidth: 720,
87 margin: '0 auto',
88 padding: 24,
89 fontFamily: 'system-ui, sans-serif',
91​
92const bubble: React.CSSProperties = {
93 borderRadius: 8,
94 padding: '10px 14px',
95 maxWidth: '85%',
97​
98const userBubble: React.CSSProperties = {
99 ...bubble,
100 alignSelf: 'flex-end',
101 background: '#eef2ff',
103​
104const assistantBubble: React.CSSProperties = {
105 ...bubble,
106 alignSelf: 'flex-start',
107 background: '#f6f6f6',
109​
110const roleLabel: React.CSSProperties = {
111 fontSize: 11,
112 textTransform: 'uppercase',
113 letterSpacing: '0.05em',
114 color: '#999',
115 marginBottom: 4,