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

index.tsx

624 lines22.2 KB

1import { useEffect, useMemo, useRef, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { Loader2, Mic, MicOff, Send, Square, Volume2 } from 'lucide-react'
4import ReactMarkdown from 'react-markdown'
5import rehypeRaw from 'rehype-raw'
6import rehypeSanitize from 'rehype-sanitize'
7import rehypeHighlight from 'rehype-highlight'
8import remarkGfm from 'remark-gfm'
9import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
10import { clientTools } from '@tanstack/ai-client'
11import { ThinkingPart } from '@tanstack/ai-react/ui'
12​
13import type { UIMessage } from '@tanstack/ai-react'
14import type { BoundInterrupts } from '@tanstack/ai-client'
15​
16import type { ModelOption } from '@/lib/model-selection'
17​
18import GuitarRecommendation from '@/components/example-GuitarRecommendation'
19import {
20 addToCartToolDef,
21 addToWishListToolDef,
22 getPersonalGuitarPreferenceToolDef,
23 recommendGuitarToolDef,
24} from '@/lib/guitar-tools'
25​
26import { MODEL_OPTIONS, getDefaultModelOption } from '@/lib/model-selection'
27​
28import './tanchat.css'
29​
30import { useAudioRecorder, useTTS } from '@/hooks'
31​
32const getPersonalGuitarPreferenceToolClient =
33 getPersonalGuitarPreferenceToolDef.client(() => ({ preference: 'acoustic' }))
34​
35const addToWishListToolClient = addToWishListToolDef.client((args) => {
36 const wishList = JSON.parse(localStorage.getItem('wishList') || '[]')
37 wishList.push(args.guitarId)
38 localStorage.setItem('wishList', JSON.stringify(wishList))
39 return {
40 success: true,
41 guitarId: args.guitarId,
42 totalItems: wishList.length,
43 }
44})
45​
46const addToCartToolClient = addToCartToolDef.client((args) => ({
47 success: true,
48 cartId: 'CART_CLIENT_' + Date.now(),
49 guitarId: args.guitarId,
50 quantity: args.quantity,
51 totalItems: args.quantity,
52}))
53​
54const recommendGuitarToolClient = recommendGuitarToolDef.client(({ id }) => ({
55 id: +id,
56}))
57​
58const tools = clientTools(
59 getPersonalGuitarPreferenceToolClient,
60 addToWishListToolClient,
61 addToCartToolClient,
62 recommendGuitarToolClient,
64​
65function ChatInputArea({ children }: { children: React.ReactNode }) {
66 return (
67 <div className="border-t border-orange-500/10 bg-gray-900/80 backdrop-blur-sm">
68 <div className="w-full px-4 py-3">{children}</div>
69 </div>
70 )
72​
73function Messages({
74 messages,
75 interrupts,
76 playingId,
77 onSpeak,
78 onStopSpeaking,
79}: {
80 messages: ReadonlyArray<UIMessage>
81 interrupts: BoundInterrupts<typeof tools>
82 playingId: string | null
83 onSpeak: (text: string, id: string) => void
84 onStopSpeaking: () => void
85}) {
86 const messagesContainerRef = useRef<HTMLDivElement>(null)
87​
88 useEffect(() => {
89 if (messagesContainerRef.current) {
90 messagesContainerRef.current.scrollTop =
91 messagesContainerRef.current.scrollHeight
92 }
93 }, [messages])
94​
95 if (!messages.length) {
96 return null
97 }
98​
99 // Extract text content from a message for TTS
100 const getMessageText = (parts: UIMessage['parts']): string => {
101 return parts
102 .filter((part) => part.type === 'text' && part.content)
103 .map((part) => (part as { type: 'text'; content: string }).content)
104 .join(' ')
105 }
106​
107 return (
108 <div
109 ref={messagesContainerRef}
110 className="flex-1 overflow-y-auto px-4 py-4"
111 >
112 {messages.map(({ id, role, parts }) => {
113 const messageText = role === 'assistant' ? getMessageText(parts) : ''
114 const isPlaying = playingId === id
115​
116 return (
117 <div
118 key={id}
119 className={`p-4 rounded-lg mb-2 ${
120 role === 'assistant'
121 ? 'bg-linear-to-r from-orange-500/5 to-red-600/5'
122 : 'bg-transparent'
123 }`}
124 >
125 <div className="flex items-start gap-4">
126 {role === 'assistant' ? (
127 <div className="w-8 h-8 rounded-lg bg-linear-to-r from-orange-500 to-red-600 flex items-center justify-center text-sm font-medium text-white shrink-0">
128 AI
129 </div>
130 ) : (
131 <div className="w-8 h-8 rounded-lg bg-gray-700 flex items-center justify-center text-sm font-medium text-white shrink-0">
132 U
133 </div>
134 )}
135 <div className="flex-1 min-w-0">
136 {/* Render parts in order */}
137 {parts.map((part, index) => {
138 // Thinking part
139 if (part.type === 'thinking') {
140 // Check if thinking is complete (if there's a text part after)
141 const isComplete = parts
142 .slice(index + 1)
143 .some((p) => p.type === 'text')
144 return (
145 <div key={`thinking-${index}`} className="mt-2 mb-2">
146 <ThinkingPart
147 content={part.content}
148 isComplete={isComplete}
149 className="p-4 bg-gray-800/50 border border-gray-700/50 rounded-lg"
150 />
151 </div>
152 )
153 }
154​
155 if (part.type === 'text' && part.content) {
156 return (
157 <div
158 key={`text-${index}`}
159 className="text-white prose dark:prose-invert max-w-none"
160 >
161 <ReactMarkdown
162 rehypePlugins={[
163 rehypeRaw,
164 rehypeSanitize,
165 rehypeHighlight,
166 remarkGfm,
167 ]}
168 >
169 {part.content}
170 </ReactMarkdown>
171 </div>
172 )
173 }
174​
175 // Approval UI: resolve the bound interrupt for this tool call.
176 const approval =
177 part.type === 'tool-call'
178 ? interrupts.find(
179 (interrupt) =>
180 interrupt.kind === 'tool-approval' &&
181 interrupt.id === part.approval?.id,
182 )
183 : undefined
184 if (
185 part.type === 'tool-call' &&
186 approval?.kind === 'tool-approval'
187 ) {
188 return (
189 <div
190 key={part.id}
191 className="p-4 bg-yellow-500/10 border border-yellow-500/20 rounded-lg mt-2"
192 >
193 <p className="text-white font-medium mb-2">
194 🔒 Approval Required: {part.name}
195 </p>
196 <div className="text-gray-300 text-sm mb-3">
197 <pre className="bg-gray-800 p-2 rounded text-xs overflow-x-auto">
198 {JSON.stringify(
199 JSON.parse(part.arguments),
200 null,
201 2,
202 )}
203 </pre>
204 </div>
205 <div className="flex gap-2">
206 <button
207 onClick={() => approval.resolveInterrupt(true)}
208 className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg text-sm font-medium transition-colors"
209 >
210 ✓ Approve
211 </button>
212 <button
213 onClick={() => approval.resolveInterrupt(false)}
214 className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg text-sm font-medium transition-colors"
215 >
216 ✗ Deny
217 </button>
218 </div>
219 </div>
220 )
221 }
222​
223 // Guitar recommendation card
224 if (
225 part.type === 'tool-call' &&
226 part.name === 'recommendGuitar' &&
227 part.output
228 ) {
229 try {
230 return (
231 <div key={part.id} className="mt-2">
232 <GuitarRecommendation id={part.output.id} />
233 </div>
234 )
235 } catch {
236 return null
237 }
238 }
239​
240 return null
241 })}
242 </div>
243 {/* Speaker button for assistant messages */}
244 {role === 'assistant' && messageText && (
245 <button
246 onClick={() => {
247 if (isPlaying) {
248 onStopSpeaking()
249 } else {
250 onSpeak(messageText, id)
251 }
252 }}
253 className={`shrink-0 p-2 rounded-lg transition-colors ${
254 isPlaying
255 ? 'bg-orange-500 text-white'
256 : 'text-gray-400 hover:text-orange-400 hover:bg-gray-800'
257 }`}
258 title={isPlaying ? 'Stop speaking' : 'Read aloud'}
259 >
260 {isPlaying ? (
261 <Loader2 className="w-5 h-5 animate-spin" />
262 ) : (
263 <Volume2 className="w-5 h-5" />
264 )}
265 </button>
266 )}
267 </div>
268 </div>
269 )
270 })}
271 </div>
272 )
274​
275function DebugPanel({
276 messages,
277 chunks,
278 onClearChunks,
279}: {
280 messages: ReadonlyArray<UIMessage>
281 chunks: Array<any>
282 onClearChunks: () => void
283}) {
284 const [activeTab, setActiveTab] = useState<'messages' | 'chunks'>('messages')
285​
286 const exportToTypeScript = () => {
287 const tsCode = `const rawChunks = ${JSON.stringify(chunks, null, 2)};`
288 navigator.clipboard.writeText(tsCode)
289 alert('TypeScript code copied to clipboard!')
290 }
291​
292 return (
293 <div className="flex flex-col h-full">
294 <div className="p-4 border-b border-orange-500/20">
295 <h2 className="text-white font-semibold text-lg">Debug Panel</h2>
296 <p className="text-gray-400 text-sm mt-1">
297 View messages and raw stream chunks
298 </p>
299​
300 {/* Tabs */}
301 <div className="flex gap-2 mt-4">
302 <button
303 onClick={() => setActiveTab('messages')}
304 className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
305 activeTab === 'messages'
306 ? 'bg-orange-500 text-white'
307 : 'bg-gray-800 text-gray-400 hover:text-white'
308 }`}
309 >
310 Messages
311 </button>
312 <button
313 onClick={() => setActiveTab('chunks')}
314 className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
315 activeTab === 'chunks'
316 ? 'bg-orange-500 text-white'
317 : 'bg-gray-800 text-gray-400 hover:text-white'
318 }`}
319 >
320 Raw Chunks ({chunks.length})
321 </button>
322 </div>
323 </div>
324​
325 <div className="flex-1 overflow-y-auto p-4">
326 {activeTab === 'messages' && (
327 <div>
328 <pre className="text-xs text-gray-300 font-mono bg-gray-800 p-4 rounded-lg overflow-x-auto">
329 {JSON.stringify(messages, null, 2)}
330 </pre>
331 </div>
332 )}
333​
334 {activeTab === 'chunks' && (
335 <div className="space-y-4">
336 <div className="flex gap-2">
337 <button
338 onClick={exportToTypeScript}
339 disabled={chunks.length === 0}
340 className="px-4 py-2 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 text-white rounded-lg text-sm font-medium transition-colors"
341 >
342 📋 Export to TypeScript
343 </button>
344 <button
345 onClick={onClearChunks}
346 disabled={chunks.length === 0}
347 className="px-4 py-2 bg-red-600 hover:bg-red-700 disabled:bg-gray-600 text-white rounded-lg text-sm font-medium transition-colors"
348 >
349 🗑️ Clear Chunks
350 </button>
351 </div>
352​
353 {/* Chunks Table */}
354 <div className="bg-gray-800 rounded-lg overflow-hidden">
355 <table className="w-full text-xs text-left">
356 <thead className="bg-gray-900 text-gray-400 uppercase">
357 <tr>
358 <th className="px-4 py-3 w-32">Type</th>
359 <th className="px-4 py-3 w-24">Role</th>
360 <th className="px-4 py-3 w-24">Tool Type</th>
361 <th className="px-4 py-3 w-32">Tool Name</th>
362 <th className="px-4 py-3">Detail</th>
363 </tr>
364 </thead>
365 <tbody className="text-gray-300">
366 {chunks.map((chunk, idx) => {
367 const role = chunk.role || '-'
368 const toolType = chunk.toolCall?.type || '-'
369 const toolName = chunk.toolCallName || '-'
370​
371 let detail = '-'
372 if (
373 chunk.type === 'TEXT_MESSAGE_CONTENT' ||
374 chunk.type === 'TOOL_CALL_ARGS'
375 ) {
376 detail = chunk.delta
377 } else if (chunk.type === 'TOOL_CALL_RESULT') {
378 detail = chunk.content
379 } else if (chunk.type === 'RUN_FINISHED') {
380 detail = `Finish: ${chunk.finishReason || 'unknown'}`
381 }
382​
383 // Truncate at 200 chars
384 if (detail.length > 200) {
385 detail = detail.substring(0, 200) + '...'
386 }
387​
388 return (
389 <tr
390 key={idx}
391 className="border-b border-gray-700 hover:bg-gray-750"
392 >
393 <td className="px-4 py-3 font-medium">{chunk.type}</td>
394 <td className="px-4 py-3">{role}</td>
395 <td className="px-4 py-3">{toolType}</td>
396 <td className="px-4 py-3">{toolName}</td>
397 <td className="px-4 py-3 font-mono text-xs break-all">
398 {detail}
399 </td>
400 </tr>
401 )
402 })}
403 </tbody>
404 </table>
405 </div>
406 </div>
407 )}
408 </div>
409 </div>
410 )
412​
413function ChatPage() {
414 const [chunks, setChunks] = useState<Array<any>>([])
415 const [selectedModel, setSelectedModel] = useState<ModelOption>(() =>
416 getDefaultModelOption(),
417 )
418​
419 // Audio hooks
420 const { isRecording, isTranscribing, startRecording, stopRecording } =
421 useAudioRecorder()
422 const { playingId, speak, stop: stopSpeaking } = useTTS()
423​
424 // Generate trace ID on mount: chat_YYMMDD_HHMMSS
425 const [traceId] = useState(() => {
426 const now = new Date()
427 const year = String(now.getFullYear()).slice(-2)
428 const month = String(now.getMonth() + 1).padStart(2, '0')
429 const day = String(now.getDate()).padStart(2, '0')
430 const hours = String(now.getHours()).padStart(2, '0')
431 const minutes = String(now.getMinutes()).padStart(2, '0')
432 const seconds = String(now.getSeconds()).padStart(2, '0')
433 return `chat_${year}${month}${day}_${hours}${minutes}${seconds}`
434 })
435​
436 const body = useMemo(
437 () => ({
438 provider: selectedModel.provider,
439 model: selectedModel.model,
440 traceId,
441 }),
442 [selectedModel.provider, selectedModel.model, traceId],
443 )
444​
445 const { messages, sendMessage, isLoading, interrupts, stop } = useChat({
446 threadId: 'panel-chat',
447 connection: fetchServerSentEvents('/api/chat'),
448 tools,
449 onChunk: (chunk: any) => {
450 setChunks((prev) => [...prev, chunk])
451 },
452 forwardedProps: body,
453 })
454 const [input, setInput] = useState('')
455​
456 const clearChunks = () => setChunks([])
457​
458 // Handle microphone toggle
459 const handleMicToggle = async () => {
460 if (isRecording) {
461 const transcribedText = await stopRecording()
462 if (transcribedText) {
463 setInput((prev) =>
464 prev ? `${prev} ${transcribedText}` : transcribedText,
465 )
466 }
467 } else {
468 await startRecording()
469 }
470 }
471​
472 return (
473 <div className="flex h-[calc(100vh-72px)] bg-gray-900">
474 {/* Left side - Chat (1/2 width) */}
475 <div className="w-1/2 flex flex-col border-r border-orange-500/20">
476 {/* Model selector bar */}
477 <div className="border-b border-orange-500/20 bg-gray-800 px-4 py-3">
478 <div className="flex items-end gap-3">
479 <div className="flex-1">
480 <label className="text-sm text-gray-400 mb-2 block">
481 Select Model:
482 </label>
483 <select
484 value={MODEL_OPTIONS.findIndex(
485 (opt) =>
486 opt.provider === selectedModel.provider &&
487 opt.model === selectedModel.model,
488 )}
489 onChange={(e) => {
490 const option = MODEL_OPTIONS[parseInt(e.target.value)]
491 setSelectedModel(option)
492 }}
493 disabled={isLoading}
494 className="w-full rounded-lg border border-orange-500/20 bg-gray-900 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-orange-500/50 disabled:opacity-50"
495 >
496 {MODEL_OPTIONS.map((option, index) => (
497 <option key={index} value={index}>
498 {option.label}
499 </option>
500 ))}
501 </select>
502 </div>
503 <a
504 href={`/stream-debugger?trace=${traceId}`}
505 className="shrink-0 px-4 py-2 bg-orange-600 hover:bg-orange-700 text-white text-sm font-medium rounded-lg transition-colors"
506 >
507 Debug Trace
508 </a>
509 </div>
510 </div>
511​
512 <Messages
513 messages={messages}
514 interrupts={interrupts}
515 playingId={playingId}
516 onSpeak={speak}
517 onStopSpeaking={stopSpeaking}
518 />
519​
520 <ChatInputArea>
521 <div className="space-y-3">
522 {isLoading && (
523 <div className="flex items-center justify-center">
524 <button
525 onClick={stop}
526 className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg text-sm font-medium transition-colors flex items-center gap-2"
527 >
528 <Square className="w-4 h-4 fill-current" />
529 Stop
530 </button>
531 </div>
532 )}
533 <div className="relative">
534 <textarea
535 value={input}
536 onChange={(e) => setInput(e.target.value)}
537 placeholder={
538 isRecording
539 ? 'Recording... Click mic to stop'
540 : isTranscribing
541 ? 'Transcribing...'
542 : "Type something clever (or don't, we won't judge)..."
543 }
544 className="w-full rounded-lg border border-orange-500/20 bg-gray-800/50 pl-4 pr-24 py-3 text-sm text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-orange-500/50 focus:border-transparent resize-none overflow-hidden shadow-lg"
545 rows={1}
546 style={{ minHeight: '44px', maxHeight: '200px' }}
547 disabled={isLoading || isRecording || isTranscribing}
548 onInput={(e) => {
549 const target = e.target as HTMLTextAreaElement
550 target.style.height = 'auto'
551 target.style.height =
552 Math.min(target.scrollHeight, 200) + 'px'
553 }}
554 onKeyDown={(e) => {
555 if (e.key === 'Enter' && !e.shiftKey && input.trim()) {
556 e.preventDefault()
557 sendMessage(input)
558 setInput('')
559 }
560 }}
561 />
562 <div className="absolute right-2 top-1/2 -translate-y-1/2 flex items-center gap-1">
563 {/* Microphone button */}
564 <button
565 onClick={handleMicToggle}
566 disabled={isLoading || isTranscribing}
567 className={`p-2 transition-colors focus:outline-none rounded-lg ${
568 isRecording
569 ? 'text-red-500 bg-red-500/20 animate-pulse'
570 : isTranscribing
571 ? 'text-orange-400'
572 : 'text-gray-400 hover:text-orange-400 hover:bg-gray-700'
573 } disabled:opacity-50`}
574 title={
575 isRecording
576 ? 'Stop recording'
577 : isTranscribing
578 ? 'Transcribing...'
579 : 'Start voice input'
580 }
581 >
582 {isTranscribing ? (
583 <Loader2 className="w-4 h-4 animate-spin" />
584 ) : isRecording ? (
585 <MicOff className="w-4 h-4" />
586 ) : (
587 <Mic className="w-4 h-4" />
588 )}
589 </button>
590 {/* Send button */}
591 <button
592 onClick={() => {
593 if (input.trim()) {
594 sendMessage(input)
595 setInput('')
596 }
597 }}
598 disabled={
599 !input.trim() || isLoading || isRecording || isTranscribing
600 }
601 className="p-2 text-orange-500 hover:text-orange-400 disabled:text-gray-500 transition-colors focus:outline-none"
602 >
603 <Send className="w-4 h-4" />
604 </button>
605 </div>
606 </div>
607 </div>
608 </ChatInputArea>
609 </div>
610​
611 <div className="w-1/2 bg-gray-950 flex flex-col">
612 <DebugPanel
613 messages={messages}
614 chunks={chunks}
615 onClearChunks={clearChunks}
616 />
617 </div>
618 </div>
619 )
621​
622export const Route = createFileRoute('/')({
623 component: ChatPage,
624})