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