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