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

ChatUI.tsx

399 lines14.5 KB

1import { useEffect, useRef, useState } from 'react'
2import ReactMarkdown from 'react-markdown'
3import rehypeRaw from 'rehype-raw'
4import rehypeSanitize from 'rehype-sanitize'
5import remarkGfm from 'remark-gfm'
6import type { UIMessage } from '@tanstack/ai-react'
7import type {
8 AnyClientTool,
9 BoundInterrupts,
10 QueuedMessage,
11} from '@tanstack/ai-client'
12import { ToolCallDisplay } from '@/components/ToolCallDisplay'
13import { ApprovalPrompt } from '@/components/ApprovalPrompt'
14​
15interface ChatUIProps<
16 TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>,
17> {
18 messages: Array<UIMessage>
19 isLoading: boolean
20 onSendMessage: (text: string) => void
21 /** Sends the typed prompt plus an attached image as an image content part. */
22 onSendMessageWithImage?: (text: string, file: File) => void
23 /** Sends the typed prompt plus an attached PDF as a document content part. */
24 onSendMessageWithDocument?: (text: string, file: File) => void
25 /**
26 * Bound AG-UI interrupts from `useChat({ tools })` —
27 * `BoundInterrupts<TTools>` (library type, not a harness DTO).
28 */
29 interrupts?: BoundInterrupts<TTools>
30 /** @deprecated Prefer `interrupts` + resolveInterrupt. */
31 addToolApprovalResponse?: (response: {
32 id: string
33 approved: boolean
34 }) => Promise<void>
35 /** Renders the image file input (multimodal image features only). */
36 showImageInput?: boolean
37 /** Renders the PDF file input (multimodal-document feature only). */
38 showDocumentInput?: boolean
39 onStop?: () => void
40 /** When the streaming structured-output CUSTOM event lands, the page
41 * exposes the parsed object here so e2e tests can assert that the event
42 * reached the client (not just that the JSON text was rendered). */
43 structuredObject?: unknown
44 /** Number of TEXT_MESSAGE_CONTENT chunks observed. Used by streaming e2e
45 * tests to verify the response actually streamed in multiple deltas. */
46 contentDeltaCount?: number
47 /** Messages sent while a stream was already in flight — held here by
48 * `useChat` and auto-sent FIFO once the run settles. Rendered in a
49 * region separate from `messages` so e2e tests can assert queued state
50 * distinctly from the delivered conversation. */
51 queue?: Array<QueuedMessage>
52 /** Remove a queued message before it drains. */
53 cancelQueued?: (id: string) => void
54 /** Block new input while pending interrupts await resolution. */
55 hasPendingInterrupt?: boolean
57​
58export function ChatUI<
59 TTools extends ReadonlyArray<AnyClientTool> = ReadonlyArray<AnyClientTool>,
60>({
61 messages,
62 isLoading,
63 onSendMessage,
64 onSendMessageWithImage,
65 onSendMessageWithDocument,
66 interrupts = [],
67 addToolApprovalResponse,
68 showImageInput,
69 showDocumentInput,
70 onStop,
71 structuredObject,
72 contentDeltaCount,
73 queue,
74 cancelQueued,
75 hasPendingInterrupt = false,
76}: ChatUIProps<TTools>) {
77 const [input, setInput] = useState('')
78 const messagesRef = useRef<HTMLDivElement>(null)
79 const inputRef = useRef<HTMLInputElement>(null)
80​
81 useEffect(() => {
82 if (messagesRef.current) {
83 messagesRef.current.scrollTop = messagesRef.current.scrollHeight
84 }
85 }, [messages])
86​
87 const handleSubmit = () => {
88 if (hasPendingInterrupt) return
89 if (!input.trim()) return
90 onSendMessage(input.trim())
91 setInput('')
92 }
93​
94 return (
95 <div className="flex flex-col h-[calc(100vh-60px)]">
96 {structuredObject != null && (
97 <div
98 data-testid="structured-output-complete"
99 data-structured-output={JSON.stringify(structuredObject)}
100 hidden
101 />
102 )}
103 {contentDeltaCount != null && (
104 <div
105 data-testid="content-delta-count"
106 data-count={String(contentDeltaCount)}
107 hidden
108 />
109 )}
110 <div
111 ref={messagesRef}
112 data-testid="message-list"
113 className="flex-1 overflow-y-auto p-4 space-y-4"
114 >
115 {interrupts
116 // Only actionable pauses — staged/error are not clickable Approve
117 // prompts; submitting is already omitted from the public list.
118 .filter((interrupt) => interrupt.status === 'pending')
119 .map((interrupt) => {
120 // Tool-approval interrupts expose `toolName` / `originalArgs`.
121 // Structural narrow (not only `kind ===`) so this stays valid when
122 // `TTools` defaults to a tools array whose `ChatInterrupt` union is
123 // generic-only at the type level but still carries approval at runtime.
124 if (
125 !('toolName' in interrupt) ||
126 !('originalArgs' in interrupt) ||
127 // `unbound` pauses carry no resolver — they belong to another
128 // producer on the stream.
129 !('resolveInterrupt' in interrupt)
130 ) {
131 return null
132 }
133 const toolName = String(interrupt.toolName)
134 return (
135 <div
136 key={interrupt.id}
137 data-testid={`approval-prompt-${toolName}`}
138 className="my-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded"
139 >
140 <div className="text-sm text-yellow-300 mb-2">
141 Tool <span className="font-mono font-bold">{toolName}</span>{' '}
142 requires approval
143 </div>
144 <div className="text-xs text-gray-400 mb-2">
145 Args: <code>{JSON.stringify(interrupt.originalArgs)}</code>
146 </div>
147 <div className="flex gap-2">
148 <button
149 data-testid={`approve-button-${toolName}`}
150 onClick={() => interrupt.resolveInterrupt(true)}
151 className="px-3 py-1 bg-green-600 text-white rounded text-xs"
152 >
153 Approve
154 </button>
155 <button
156 data-testid={`deny-button-${toolName}`}
157 onClick={() => interrupt.resolveInterrupt(false)}
158 className="px-3 py-1 bg-red-600 text-white rounded text-xs"
159 >
160 Deny
161 </button>
162 </div>
163 </div>
164 )
165 })}
166 {messages.map((message) => (
167 <div
168 key={message.id}
169 data-testid={
170 message.role === 'user' ? 'user-message' : 'assistant-message'
171 }
172 className={`p-3 rounded-lg ${
173 message.role === 'user'
174 ? 'bg-orange-500/10 border border-orange-500/20 ml-12'
175 : 'bg-gray-800/50 border border-gray-700 mr-12'
176 }`}
177 >
178 {message.parts.map((part, i) => {
179 if (part.type === 'text') {
180 return (
181 <div
182 key={i}
183 data-testid="text-part"
184 className="prose prose-invert prose-sm max-w-none"
185 >
186 <ReactMarkdown
187 remarkPlugins={[remarkGfm]}
188 rehypePlugins={[rehypeRaw, rehypeSanitize]}
189 >
190 {part.content}
191 </ReactMarkdown>
192 </div>
193 )
194 }
195 if (part.type === 'image') {
196 const imgPart = part as any
197 const src =
198 imgPart.source?.type === 'data'
199 ? `data:${imgPart.source.mimeType};base64,${imgPart.source.value}`
200 : imgPart.source?.type === 'url'
201 ? imgPart.source.value
202 : undefined
203 return src ? (
204 <img
205 key={i}
206 src={src}
207 alt="uploaded"
208 data-testid="image-part"
209 className="max-w-xs max-h-48 rounded mt-1"
210 />
211 ) : null
212 }
213 if (part.type === 'thinking') {
214 return (
215 <div
216 key={i}
217 data-testid="thinking-block"
218 className="text-xs text-gray-500 italic border-l-2 border-gray-600 pl-2 my-2"
219 >
220 {part.content}
221 </div>
222 )
223 }
224 // Prefer bound `interrupts` UI above. Legacy message-part prompts
225 // remain only when no interrupt list was provided (compat path).
226 if (
227 interrupts.length === 0 &&
228 part.type === 'tool-call' &&
229 (part as any).state === 'approval-requested' &&
230 addToolApprovalResponse
231 ) {
232 return (
233 <ApprovalPrompt
234 key={i}
235 part={part}
236 onRespond={addToolApprovalResponse}
237 />
238 )
239 }
240 if (part.type === 'tool-call') {
241 return <ToolCallDisplay key={i} part={part} />
242 }
243 if (part.type === 'tool-result') {
244 return (
245 <div
246 key={i}
247 data-testid={`tool-call-result-${(part as any).toolCallId}`}
248 className="text-gray-300 text-xs mt-1"
249 >
250 Result: <code>{(part as any).content}</code>
251 </div>
252 )
253 }
254 if (part.type === 'structured-output') {
255 // Render the streamed JSON so the assistant message has
256 // visible content for selectors (e.g. `getLastAssistantMessage`).
257 // Previously this content arrived as a `text` part — the new
258 // routing puts it on a `structured-output` part instead.
259 const sop = part as any
260 const text =
261 sop.raw ||
262 (sop.data !== undefined ? JSON.stringify(sop.data) : '')
263 if (text === '') return null
264 return (
265 <div
266 key={i}
267 data-testid="structured-output-part"
268 className="prose prose-invert prose-sm max-w-none whitespace-pre-wrap break-words"
269 >
270 {text}
271 </div>
272 )
273 }
274 return null
275 })}
276 </div>
277 ))}
278 </div>
279​
280 {isLoading && (
281 <div
282 data-testid="loading-indicator"
283 className="px-4 py-1 text-xs text-gray-400"
284 >
285 Generating...
286 </div>
287 )}
288​
289 {queue != null && queue.length > 0 && (
290 <div
291 data-testid="queue-list"
292 className="border-t border-gray-700 p-2 space-y-1"
293 >
294 {queue.map((queued) => (
295 <div
296 key={queued.id}
297 data-testid="queued-message"
298 className="flex items-center justify-between gap-2 text-xs text-gray-400 bg-gray-800/40 rounded px-2 py-1"
299 >
300 <span data-testid="queued-message-text">
301 {typeof queued.content === 'string'
302 ? queued.content
303 : JSON.stringify(queued.content)}
304 </span>
305 {cancelQueued && (
306 <button
307 type="button"
308 data-testid="cancel-queued-button"
309 onClick={() => cancelQueued(queued.id)}
310 className="px-2 py-0.5 bg-gray-700 text-white rounded text-xs"
311 >
312 Cancel
313 </button>
314 )}
315 </div>
316 ))}
317 </div>
318 )}
319​
320 <div className="border-t border-gray-700 p-3 flex gap-2">
321 {showImageInput && (
322 <input
323 type="file"
324 accept="image/*"
325 data-testid="image-attachment-input"
326 className="text-xs text-gray-400"
327 onChange={(e) => {
328 const file = e.target.files?.[0]
329 // Read the prompt from the live input DOM value rather than the
330 // `input` React state. Attaching a file auto-sends, and under
331 // load a controlled input's state can lag the committed DOM
332 // value — reading state here would send an empty/partial prompt.
333 const text = (inputRef.current?.value ?? input).trim()
334 if (file && text && onSendMessageWithImage) {
335 onSendMessageWithImage(text, file)
336 setInput('')
337 }
338 }}
339 />
340 )}
341 {showDocumentInput && (
342 <input
343 type="file"
344 accept="application/pdf,.pdf"
345 data-testid="document-attachment-input"
346 className="text-xs text-gray-400"
347 onChange={(e) => {
348 const file = e.target.files?.[0]
349 // Same DOM-value read as the image input above.
350 const text = (inputRef.current?.value ?? input).trim()
351 if (file && text && onSendMessageWithDocument) {
352 onSendMessageWithDocument(text, file)
353 setInput('')
354 e.target.value = ''
355 }
356 }}
357 />
358 )}
359 <input
360 ref={inputRef}
361 data-testid="chat-input"
362 type="text"
363 value={input}
364 onChange={(e) => setInput(e.target.value)}
365 onKeyDown={(e) => {
366 if (e.key === 'Enter' && !e.shiftKey) {
367 e.preventDefault()
368 handleSubmit()
369 }
370 }}
371 placeholder="Type a message..."
372 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"
373 />
374 <button
375 data-testid="send-button"
376 onClick={handleSubmit}
377 // Intentionally clickable while `isLoading` — sending here doesn't
378 // start a second concurrent stream; `useChat`/`ChatClient` queues
379 // it (default `whenBusy: 'queue'`) and auto-sends it FIFO once the
380 // in-flight run settles. Disabling on `isLoading` would make the
381 // queue feature unreachable from the UI.
382 disabled={!input.trim()}
383 className="px-4 py-2 bg-orange-500 text-white rounded text-sm font-medium disabled:opacity-50"
384 >
385 Send
386 </button>
387 {isLoading && onStop && (
388 <button
389 data-testid="stop-button"
390 onClick={onStop}
391 className="px-4 py-2 bg-red-500 text-white rounded text-sm font-medium"
392 >
393 Stop
394 </button>
395 )}
396 </div>
397 </div>
398 )