Open History to see the last commit
1import { useEffect, useRef, useState } from 'react'
2import type { UIMessage } from '@tanstack/ai-react'
3import ReactMarkdown from 'react-markdown'
4import rehypeRaw from 'rehype-raw'
5import rehypeSanitize from 'rehype-sanitize'
6import remarkGfm from 'remark-gfm'
7import { ToolCallDisplay } from '@/components/ToolCallDisplay'
8import { ApprovalPrompt } from '@/components/ApprovalPrompt'
9
10interface ChatUIProps {
11 messages: Array<UIMessage>
12 isLoading: boolean
13 onSendMessage: (text: string) => void
14 onSendMessageWithImage?: (text: string, file: File) => void
15 addToolApprovalResponse?: (response: {
16 id: string
17 approved: boolean
18 }) => Promise<void>
19 showImageInput?: boolean
20 onStop?: () => void
21 /** When the streaming structured-output CUSTOM event lands, the page
22 * exposes the parsed object here so e2e tests can assert that the event
23 * reached the client (not just that the JSON text was rendered). */
24 structuredObject?: unknown
25 /** Number of TEXT_MESSAGE_CONTENT chunks observed. Used by streaming e2e
26 * tests to verify the response actually streamed in multiple deltas. */
27 contentDeltaCount?: number
28}
29
30export function ChatUI({
31 messages,
32 isLoading,
33 onSendMessage,
34 onSendMessageWithImage,
35 addToolApprovalResponse,
36 showImageInput,
37 onStop,
38 structuredObject,
39 contentDeltaCount,
40}: ChatUIProps) {
41 const [input, setInput] = useState('')
42 const messagesRef = useRef<HTMLDivElement>(null)
43
44 useEffect(() => {
45 if (messagesRef.current) {
46 messagesRef.current.scrollTop = messagesRef.current.scrollHeight
47 }
48 }, [messages])
49
50 const handleSubmit = () => {
51 if (!input.trim()) return
52 onSendMessage(input.trim())
53 setInput('')
54 }
55
56 return (
57 <div className="flex flex-col h-[calc(100vh-60px)]">
58 {structuredObject != null && (
59 <div
60 data-testid="structured-output-complete"
61 data-structured-output={JSON.stringify(structuredObject)}
62 hidden
63 />
64 )}
65 {contentDeltaCount != null && (
66 <div
67 data-testid="content-delta-count"
68 data-count={String(contentDeltaCount)}
69 hidden
70 />
71 )}
72 <div
73 ref={messagesRef}
74 data-testid="message-list"
75 className="flex-1 overflow-y-auto p-4 space-y-4"
76 >
77 {messages.map((message) => (
78 <div
79 key={message.id}
80 data-testid={
81 message.role === 'user' ? 'user-message' : 'assistant-message'
82 }
83 className={`p-3 rounded-lg ${
84 message.role === 'user'
85 ? 'bg-orange-500/10 border border-orange-500/20 ml-12'
86 : 'bg-gray-800/50 border border-gray-700 mr-12'
87 }`}
88 >
89 {message.parts.map((part, i) => {
90 if (part.type === 'text') {
91 return (
92 <div
93 key={i}
94 data-testid="text-part"
95 className="prose prose-invert prose-sm max-w-none"
96 >
97 <ReactMarkdown
98 remarkPlugins={[remarkGfm]}
99 rehypePlugins={[rehypeRaw, rehypeSanitize]}
100 >
101 {part.content}
102 </ReactMarkdown>
103 </div>
104 )
105 }
106 if (part.type === 'image') {
107 const imgPart = part as any
108 const src =
109 imgPart.source?.type === 'data'
110 ? `data:${imgPart.source.mimeType};base64,${imgPart.source.value}`
111 : imgPart.source?.type === 'url'
112 ? imgPart.source.value
113 : undefined
114 return src ? (
115 <img
116 key={i}
117 src={src}
118 alt="uploaded"
119 data-testid="image-part"
120 className="max-w-xs max-h-48 rounded mt-1"
121 />
122 ) : null
123 }
124 if (part.type === 'thinking') {
125 return (
126 <div
127 key={i}
128 data-testid="thinking-block"
129 className="text-xs text-gray-500 italic border-l-2 border-gray-600 pl-2 my-2"
130 >
131 {part.content}
132 </div>
133 )
134 }
135 if (
136 part.type === 'tool-call' &&
137 (part as any).state === 'approval-requested' &&
138 addToolApprovalResponse
139 ) {
140 return (
141 <ApprovalPrompt
142 key={i}
143 part={part as any}
144 onRespond={addToolApprovalResponse}
145 />
146 )
147 }
148 if (part.type === 'tool-call') {
149 return <ToolCallDisplay key={i} part={part as any} />
150 }
151 if (part.type === 'tool-result') {
152 return (
153 <div
154 key={i}
155 data-testid={`tool-call-result-${(part as any).toolCallId}`}
156 className="text-gray-300 text-xs mt-1"
157 >
158 Result: <code>{(part as any).content}</code>
159 </div>
160 )
161 }
162 if (part.type === 'structured-output') {
163 // Render the streamed JSON so the assistant message has
164 // visible content for selectors (e.g. `getLastAssistantMessage`).
165 // Previously this content arrived as a `text` part — the new
166 // routing puts it on a `structured-output` part instead.
167 const sop = part as any
168 const text =
169 sop.raw ||
170 (sop.data !== undefined ? JSON.stringify(sop.data) : '')
171 if (text === '') return null
172 return (
173 <div
174 key={i}
175 data-testid="structured-output-part"
176 className="prose prose-invert prose-sm max-w-none whitespace-pre-wrap break-words"
177 >
178 {text}
179 </div>
180 )
181 }
182 return null
183 })}
184 </div>
185 ))}
186 </div>
187
188 {isLoading && (
189 <div
190 data-testid="loading-indicator"
191 className="px-4 py-1 text-xs text-gray-400"
192 >
193 Generating...
194 </div>
195 )}
196
197 <div className="border-t border-gray-700 p-3 flex gap-2">
198 {showImageInput && (
199 <input
200 type="file"
201 accept="image/*"
202 data-testid="image-attachment-input"
203 className="text-xs text-gray-400"
204 onChange={(e) => {
205 const file = e.target.files?.[0]
206 if (file && input.trim() && onSendMessageWithImage) {
207 onSendMessageWithImage(input.trim(), file)
208 setInput('')
209 }
210 }}
211 />
212 )}
213 <input
214 data-testid="chat-input"
215 type="text"
216 value={input}
217 onChange={(e) => setInput(e.target.value)}
218 onKeyDown={(e) => {
219 if (e.key === 'Enter' && !e.shiftKey) {
220 e.preventDefault()
221 handleSubmit()
222 }
223 }}
224 placeholder="Type a message..."
225 className="flex-1 bg-gray-800 border border-gray-700 rounded px-3 py-2 text-sm focus:outline-none focus:border-orange-500/50"
226 />
227 <button
228 data-testid="send-button"
229 onClick={handleSubmit}
230 disabled={!input.trim() || isLoading}
231 className="px-4 py-2 bg-orange-500 text-white rounded text-sm font-medium disabled:opacity-50"
232 >
233 Send
234 </button>
235 {isLoading && onStop && (
236 <button
237 data-testid="stop-button"
238 onClick={onStop}
239 className="px-4 py-2 bg-red-500 text-white rounded text-sm font-medium"
240 >
241 Stop
242 </button>
243 )}
244 </div>
245 </div>
246 )
247}