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

chat-client-default-bridge.tsx

79 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 fetcher: () =>
28 new Response(SSE_BODY, {
29 headers: { 'Content-Type': 'text/event-stream' },
30 }),
31 onMessagesChange: setMessages,
32 }),
33 )
34​
35 // The button starts disabled in the server-rendered HTML and enables on
36 // hydration, so Playwright's actionability check cannot click before the
37 // onClick handler is attached.
38 const [hydrated, setHydrated] = useState(false)
39 useEffect(() => {
40 setHydrated(true)
41 }, [])
42​
43 const handleSend = () => {
44 client
45 .sendMessage('hello from the vanilla client')
46 .catch((sendError: unknown) => setError(String(sendError)))
47 }
48​
49 return (
50 <div className="p-6 max-w-2xl mx-auto space-y-4">
51 <h1 className="text-xl font-semibold">
52 Vanilla ChatClient (default no-op devtools bridge)
53 </h1>
54 <button
55 data-testid="send-button"
56 type="button"
57 disabled={!hydrated}
58 onClick={handleSend}
59 >
60 Send
61 </button>
62 {error !== null && <div data-testid="send-error">{error}</div>}
63 <div data-testid="messages">
64 {messages.map((message) => (
65 <div
66 key={message.id}
67 data-testid={
68 message.role === 'user' ? 'user-message' : 'assistant-message'
69 }
70 >
71 {message.parts
72 .map((part) => (part.type === 'text' ? part.content : ''))
73 .join('')}
74 </div>
75 ))}
76 </div>
77 </div>
78 )