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