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

chat-client-default-bridge.tsx

80 lines2.8 KB

1import { useEffect, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { ChatClient } from '@tanstack/ai-client'
4import type { UIMessage } from '@tanstack/ai-client'
5​
6export const Route = createFileRoute('/chat-client-default-bridge')({
7 component: ChatClientDefaultBridgePage,
8})
9​
10// Covers the vanilla `ChatClient` shipping default: no `devtoolsBridgeFactory`,
11// so the client falls back to the no-op devtools bridge. The framework hooks
12// (`useChat` etc.) always inject the real bridge, so every other route in this
13// suite bypasses the no-op path entirely. A static SSE body keeps the scenario
14// deterministic; the transport is not what is under test here.
15const SSE_BODY = [
16 'data: {"type":"RUN_STARTED","threadId":"thread-default-bridge","runId":"run-default-bridge"}\n\n',
17 'data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg-default-bridge","model":"test","timestamp":0,"delta":"Hi from the assistant","content":"Hi from the assistant"}\n\n',
18 'data: {"type":"RUN_FINISHED","threadId":"thread-default-bridge","runId":"run-default-bridge","model":"test","timestamp":0,"finishReason":"stop"}\n\n',
19].join('')
20​
21function ChatClientDefaultBridgePage() {
22 const [messages, setMessages] = useState<Array<UIMessage>>([])
23 const [error, setError] = useState<string | null>(null)
24 const [client] = useState(
25 () =>
26 new ChatClient({
27 threadId: 'thread-default-bridge',
28 fetcher: () =>
29 new Response(SSE_BODY, {
30 headers: { 'Content-Type': 'text/event-stream' },
31 }),
32 onMessagesChange: setMessages,
33 }),
34 )
35​
36 // The button starts disabled in the server-rendered HTML and enables on
37 // hydration, so Playwright's actionability check cannot click before the
38 // onClick handler is attached.
39 const [hydrated, setHydrated] = useState(false)
40 useEffect(() => {
41 setHydrated(true)
42 }, [])
43​
44 const handleSend = () => {
45 client
46 .sendMessage('hello from the vanilla client')
47 .catch((sendError: unknown) => setError(String(sendError)))
48 }
49​
50 return (
51 <div className="p-6 max-w-2xl mx-auto space-y-4">
52 <h1 className="text-xl font-semibold">
53 Vanilla ChatClient (default no-op devtools bridge)
54 </h1>
55 <button
56 data-testid="send-button"
57 type="button"
58 disabled={!hydrated}
59 onClick={handleSend}
60 >
61 Send
62 </button>
63 {error !== null && <div data-testid="send-error">{error}</div>}
64 <div data-testid="messages">
65 {messages.map((message) => (
66 <div
67 key={message.id}
68 data-testid={
69 message.role === 'user' ? 'user-message' : 'assistant-message'
70 }
71 >
72 {message.parts
73 .map((part) => (part.type === 'text' ? part.content : ''))
74 .join('')}
75 </div>
76 ))}
77 </div>
78 </div>
79 )