Open History to see the last commit
1'use client'
2
3import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
4import { createFileRoute } from '@tanstack/react-router'
5import { parsePartialJSON } from '@tanstack/ai'
6import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
7import type { UIMessage } from '@tanstack/ai-react'
8import {
9 ChevronDown,
10 ChevronRight,
11 Download,
12 Sparkles,
13 Trash2,
14 X,
15 RefreshCw,
16} from 'lucide-react'
17import ReactMarkdown from 'react-markdown'
18import rehypeRaw from 'rehype-raw'
19import rehypeSanitize from 'rehype-sanitize'
20import rehypeHighlight from 'rehype-highlight'
21import remarkGfm from 'remark-gfm'
22import type { VMEvent } from '@/components'
23import { CodeBlock, ExecutionResult, JavaScriptVM, Header } from '@/components'
24import ChatInput from '@/components/ChatInput'
25import { formatDuration } from '@/lib/efficiency'
26import { toolResultContentToString } from '@/lib/tool-result-content'
27
28export const Route = createFileRoute('/_database-demo/database-demo')({
29 component: DatabaseDemoPage,
30})
31
32type Provider = 'anthropic' | 'openai' | 'gemini'
33
34interface ModelOption {
35 provider: Provider
36 model: string
37 label: string
38}
39
40const MODEL_OPTIONS: Array<ModelOption> = [
41 {
42 provider: 'anthropic',
43 model: 'claude-haiku-4-5',
44 label: 'Claude Haiku 4.5',
45 },
46 {
47 provider: 'anthropic',
48 model: 'claude-haiku-4-20250514',
49 label: 'Claude Haiku 4',
50 },
51 { provider: 'openai', model: 'gpt-4o', label: 'GPT-4o' },
52 {
53 provider: 'gemini',
54 model: 'gemini-2.5-flash',
55 label: 'Gemini 2.5 Flash',
56 },
57]
58
59interface SnippetWithCode {
60 id: string
61 name: string
62 description: string
63 code: string
64 trustLevel: 'untrusted' | 'provisional' | 'trusted'
65 usageHints?: Array<string>
66 stats?: { executions: number; successRate: number }
67}
68
69function SnippetsDialog({
70 open,
71 onClose,
72 snippets,
73 onDelete,
74 onDeleteAll,
75 onRefresh,
76 isLoading,
77}: {
78 open: boolean
79 onClose: () => void
80 snippets: Array<SnippetWithCode>
81 onDelete: (name: string) => void
82 onDeleteAll: () => void
83 onRefresh: () => void
84 isLoading: boolean
85}) {
86 const [expandedId, setExpandedId] = useState<string | null>(null)
87
88 if (!open) return null
89
90 const trustColors: Record<string, string> = {
91 untrusted: 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30',
92 provisional: 'bg-blue-500/20 text-blue-400 border-blue-500/30',
93 trusted: 'bg-green-500/20 text-green-400 border-green-500/30',
94 }
95
96 return (
97 <div className="fixed inset-0 z-50 flex items-center justify-center">
98 <div className="absolute inset-0 bg-black/60" onClick={onClose} />
99 <div className="relative z-10 w-full max-w-2xl max-h-[80vh] flex flex-col bg-gray-900 border border-gray-700 rounded-xl shadow-2xl mx-4">
100 <div className="flex items-center justify-between px-5 py-4 border-b border-gray-700">
101 <div className="flex items-center gap-2">
102 <Sparkles className="w-4 h-4 text-purple-400" />
103 <h2 className="font-semibold text-white">
104 Database Snippets
105 <span className="ml-2 text-sm text-gray-400 font-normal">
106 ({snippets.length})
107 </span>
108 </h2>
109 </div>
110 <div className="flex items-center gap-2">
111 <button
112 onClick={onRefresh}
113 disabled={isLoading}
114 className="p-1.5 rounded-lg text-gray-400 hover:text-white hover:bg-gray-700/50 transition-colors disabled:opacity-50"
115 title="Refresh snippets"
116 >
117 <RefreshCw
118 className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`}
119 />
120 </button>
121 {snippets.length > 0 && (
122 <button
123 onClick={() => {
124 if (confirm(`Delete all ${snippets.length} snippets?`)) {
125 onDeleteAll()
126 }
127 }}
128 className="px-3 py-1.5 text-xs bg-red-600/20 hover:bg-red-600/40 text-red-400 border border-red-500/30 rounded-lg transition-colors flex items-center gap-1.5"
129 >
130 <Trash2 className="w-3.5 h-3.5" />
131 Delete All
132 </button>
133 )}
134 <button
135 onClick={onClose}
136 className="p-1.5 rounded-lg text-gray-400 hover:text-white hover:bg-gray-700/50 transition-colors"
137 >
138 <X className="w-4 h-4" />
139 </button>
140 </div>
141 </div>
142
143 <div className="flex-1 overflow-y-auto p-3 space-y-1">
144 {snippets.length === 0 ? (
145 <div className="py-12 text-center text-gray-500">
146 <Sparkles className="w-8 h-8 mx-auto mb-3 text-gray-600" />
147 <p className="text-sm font-medium">No snippets registered yet</p>
148 <p className="text-xs mt-1 text-gray-600">
149 Enable "With Snippets" and the AI will create reusable snippets
150 as it works.
151 </p>
152 </div>
153 ) : (
154 snippets.map((snippet) => {
155 const isExpanded = expandedId === snippet.id
156 return (
157 <div
158 key={snippet.id}
159 className="rounded-lg border border-gray-700 overflow-hidden"
160 >
161 <button
162 className="w-full flex items-center gap-3 px-4 py-3 bg-gray-800/50 hover:bg-gray-800 transition-colors text-left"
163 onClick={() =>
164 setExpandedId(isExpanded ? null : snippet.id)
165 }
166 >
167 {isExpanded ? (
168 <ChevronDown className="w-4 h-4 text-gray-400 shrink-0" />
169 ) : (
170 <ChevronRight className="w-4 h-4 text-gray-400 shrink-0" />
171 )}
172 <div className="flex-1 min-w-0">
173 <div className="flex items-center gap-2">
174 <code className="text-sm font-mono text-purple-300">
175 snippet_{snippet.name}
176 </code>
177 <span
178 className={`text-xs px-1.5 py-0.5 rounded border ${trustColors[snippet.trustLevel] ?? ''}`}
179 >
180 {snippet.trustLevel}
181 </span>
182 </div>
183 {snippet.description && (
184 <p className="text-xs text-gray-400 mt-0.5 truncate">
185 {snippet.description}
186 </p>
187 )}
188 </div>
189 <button
190 onClick={(e) => {
191 e.stopPropagation()
192 if (confirm(`Delete snippet "${snippet.name}"?`)) {
193 onDelete(snippet.name)
194 }
195 }}
196 className="p-1.5 rounded text-gray-500 hover:text-red-400 hover:bg-red-400/10 transition-colors shrink-0"
197 title="Delete snippet"
198 >
199 <Trash2 className="w-3.5 h-3.5" />
200 </button>
201 </button>
202
203 {isExpanded && (
204 <div className="border-t border-gray-700 bg-gray-950">
205 <pre className="p-4 text-xs text-gray-300 overflow-x-auto max-h-64 overflow-y-auto font-mono leading-relaxed">
206 {snippet.code || '// No code available'}
207 </pre>
208 </div>
209 )}
210 </div>
211 )
212 })
213 )}
214 </div>
215 </div>
216 </div>
217 )
218}
219
220function ToolCallDisplay({
221 name,
222 arguments: args,
223 output,
224 state,
225 hasResult = false,
226}: {
227 name: string
228 arguments: string
229 output?: unknown
230 state: string
231 hasResult?: boolean
232}) {
233 const isInputStreaming = state === 'input-streaming'
234 const isInputComplete = state === 'input-complete'
235 const hasOutput = output !== undefined || hasResult
236 const isExecuting = isInputComplete && !hasOutput
237 const isRunning = isInputStreaming || isExecuting
238
239 const [inputOpen, setInputOpen] = useState(isRunning)
240 const [outputOpen, setOutputOpen] = useState(false)
241
242 let parsedArgs: unknown
243 try {
244 parsedArgs = JSON.parse(args)
245 } catch {
246 parsedArgs = args
247 }
248
249 // Get code from execute_typescript calls
250 let code = ''
251 if (
252 name === 'execute_typescript' &&
253 typeof parsedArgs === 'object' &&
254 parsedArgs !== null
255 ) {
256 code = (parsedArgs as { typescriptCode?: string }).typescriptCode || ''
257 }
258
259 const isCodeMode = name === 'execute_typescript'
260 const borderColor = isCodeMode
261 ? 'border-purple-500/30'
262 : 'border-emerald-500/30'
263 const bgColor = isCodeMode ? 'bg-purple-900/10' : 'bg-emerald-900/10'
264 const headerBg = isCodeMode ? 'bg-purple-900/20' : 'bg-emerald-900/20'
265 const textColor = isCodeMode ? 'text-purple-300' : 'text-emerald-300'
266 const spinnerColor = isCodeMode ? 'border-purple-400' : 'border-emerald-400'
267 const pillColor = isCodeMode ? 'bg-purple-600' : 'bg-emerald-600'
268 const dotColor = isCodeMode ? 'bg-purple-500/50' : 'bg-emerald-500/50'
269
270 return (
271 <div
272 className={`mt-2 rounded-lg border ${borderColor} ${bgColor} overflow-hidden text-sm`}
273 >
274 <div
275 className={`flex items-center gap-2 px-3 py-1.5 ${headerBg} ${textColor}`}
276 >
277 {isRunning ? (
278 <div
279 className={`w-3 h-3 border-2 ${spinnerColor} border-t-transparent rounded-full animate-spin`}
280 />
281 ) : (
282 <div className={`w-3 h-3 rounded-full ${dotColor}`} />
283 )}
284 <span className="font-mono font-medium text-xs">{name}</span>
285 {isRunning && (
286 <span
287 className={`text-xs px-2 py-0.5 rounded-full ${pillColor} animate-pulse`}
288 >
289 Running...
290 </span>
291 )}
292 </div>
293
294 {code ? (
295 <div className={`border-t ${borderColor.replace('/30', '/20')}`}>
296 <button
297 onClick={() => setInputOpen(!inputOpen)}
298 className="w-full flex items-center gap-2 px-3 py-1.5 text-xs text-gray-400 hover:bg-white/5 transition-colors"
299 >
300 {inputOpen ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
301 <span>Code</span>
302 </button>
303 {inputOpen && (
304 <pre className="px-3 pb-2 text-xs text-gray-300 overflow-x-auto max-h-48 overflow-y-auto font-mono whitespace-pre-wrap">
305 {code}
306 </pre>
307 )}
308 </div>
309 ) : (
310 <div className={`border-t ${borderColor.replace('/30', '/20')}`}>
311 <button
312 onClick={() => setInputOpen(!inputOpen)}
313 className="w-full flex items-center gap-2 px-3 py-1.5 text-xs text-gray-400 hover:bg-white/5 transition-colors"
314 >
315 {inputOpen ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
316 <span>Input</span>
317 </button>
318 {inputOpen && (
319 <pre className="px-3 pb-2 text-xs text-gray-300 overflow-x-auto max-h-32 overflow-y-auto font-mono whitespace-pre-wrap">
320 {typeof parsedArgs === 'object'
321 ? JSON.stringify(parsedArgs, null, 2)
322 : String(parsedArgs)}
323 </pre>
324 )}
325 </div>
326 )}
327
328 {hasOutput && output !== undefined && (
329 <div className={`border-t ${borderColor.replace('/30', '/20')}`}>
330 <button
331 onClick={() => setOutputOpen(!outputOpen)}
332 className="w-full flex items-center gap-2 px-3 py-1.5 text-xs text-gray-400 hover:bg-white/5 transition-colors"
333 >
334 {outputOpen ? (
335 <ChevronDown size={12} />
336 ) : (
337 <ChevronRight size={12} />
338 )}
339 <span>Output</span>
340 </button>
341 {outputOpen && (
342 <pre className="px-3 pb-2 text-xs text-gray-300 overflow-x-auto max-h-48 overflow-y-auto font-mono whitespace-pre-wrap">
343 {typeof output === 'object'
344 ? JSON.stringify(output, null, 2)
345 : String(output)}
346 </pre>
347 )}
348 </div>
349 )}
350 </div>
351 )
352}
353
354function Messages({
355 messages,
356 toolCallEvents,
357}: {
358 messages: ReadonlyArray<UIMessage>
359 toolCallEvents: Map<string, Array<VMEvent>>
360}) {
361 const containerRef = useRef<HTMLDivElement>(null)
362
363 useEffect(() => {
364 if (containerRef.current) {
365 containerRef.current.scrollTop = containerRef.current.scrollHeight
366 }
367 }, [messages])
368
369 if (!messages.length) return null
370
371 return (
372 <div
373 ref={containerRef}
374 className="flex-1 overflow-y-auto px-4 py-4 space-y-4"
375 >
376 {messages.map((message) => {
377 const toolResults = new Map<
378 string,
379 { content: string; state: string; error?: string }
380 >()
381 for (const p of message.parts) {
382 if (p.type === 'tool-result') {
383 toolResults.set(p.toolCallId, {
384 content: toolResultContentToString(p.content),
385 state: p.state,
386 error: p.error,
387 })
388 }
389 }
390
391 return (
392 <div
393 key={message.id}
394 className={`rounded-lg p-4 ${
395 message.role === 'user'
396 ? 'bg-indigo-900/30 text-indigo-100 ml-8'
397 : 'bg-gray-800/60 text-gray-100 mr-8'
398 }`}
399 >
400 <div className="flex items-start gap-3">
401 <div
402 className={`w-7 h-7 rounded-md flex items-center justify-center text-xs font-medium shrink-0 ${
403 message.role === 'assistant'
404 ? 'bg-gradient-to-r from-emerald-500 to-cyan-500 text-white'
405 : 'bg-gray-700 text-white'
406 }`}
407 >
408 {message.role === 'assistant' ? 'AI' : 'U'}
409 </div>
410 <div className="flex-1 min-w-0 text-sm">
411 {message.parts.map((part, index) => {
412 if (part.type === 'text' && part.content) {
413 return (
414 <div key={`text-${index}`} className="markdown-content">
415 <ReactMarkdown
416 remarkPlugins={[remarkGfm]}
417 rehypePlugins={[
418 rehypeRaw,
419 rehypeSanitize,
420 rehypeHighlight,
421 ]}
422 >
423 {part.content}
424 </ReactMarkdown>
425 </div>
426 )
427 }
428
429 // execute_typescript — use shared CodeBlock/ExecutionResult/JavaScriptVM
430 if (
431 part.type === 'tool-call' &&
432 part.name === 'execute_typescript'
433 ) {
434 let code = ''
435 const parsedArgs = parsePartialJSON(part.arguments)
436 if (parsedArgs?.typescriptCode) {
437 code = parsedArgs.typescriptCode
438 }
439
440 const toolResult = toolResults.get(part.id)
441 const hasOutput =
442 part.output !== undefined || toolResult !== undefined
443
444 let parsedOutput = part.output
445 if (!parsedOutput && toolResult?.content) {
446 try {
447 parsedOutput = JSON.parse(toolResult.content)
448 } catch {
449 parsedOutput = { result: toolResult.content }
450 }
451 }
452
453 const isAwaitingInput = part.state === 'awaiting-input'
454 const isInputStreaming = part.state === 'input-streaming'
455 const isInputComplete = part.state === 'input-complete'
456 const isStillGenerating =
457 isAwaitingInput || isInputStreaming
458 const isExecuting = isInputComplete && !hasOutput
459 const hasError =
460 parsedOutput?.success === false ||
461 toolResult?.error !== undefined
462
463 const codeStatus =
464 isStillGenerating || isExecuting
465 ? 'running'
466 : hasError
467 ? 'error'
468 : 'success'
469
470 const executionStatus = isExecuting
471 ? 'running'
472 : hasError
473 ? 'error'
474 : 'success'
475
476 const events = toolCallEvents.get(part.id) || []
477
478 return (
479 <div key={part.id} className="mt-3 space-y-2">
480 {!code && isStillGenerating ? (
481 <div className="rounded-lg border border-blue-700 bg-blue-900/30 overflow-hidden">
482 <div className="flex items-center gap-3 px-4 py-3">
483 <div className="w-5 h-5 border-2 border-blue-400 border-t-transparent rounded-full animate-spin" />
484 <span className="text-blue-300 font-medium">
485 LLM is generating the TypeScript code...
486 </span>
487 </div>
488 </div>
489 ) : (
490 <CodeBlock code={code} status={codeStatus} />
491 )}
492 {isInputComplete &&
493 (events.length > 0 || isExecuting) && (
494 <JavaScriptVM
495 events={events}
496 isExecuting={isExecuting}
497 />
498 )}
499 {isInputComplete && (
500 <ExecutionResult
501 status={executionStatus}
502 result={parsedOutput?.result}
503 error={
504 parsedOutput?.error?.message || toolResult?.error
505 }
506 logs={parsedOutput?.logs}
507 />
508 )}
509 </div>
510 )
511 }
512
513 // Other tool calls — generic display
514 if (part.type === 'tool-call') {
515 const toolResult = toolResults.get(part.id)
516 const effectiveOutput =
517 part.output ??
518 (toolResult?.content
519 ? (() => {
520 try {
521 return JSON.parse(toolResult.content)
522 } catch {
523 return toolResult.content
524 }
525 })()
526 : undefined)
527
528 return (
529 <ToolCallDisplay
530 key={part.id}
531 name={part.name}
532 arguments={part.arguments}
533 output={effectiveOutput}
534 state={part.state}
535 hasResult={toolResult !== undefined}
536 />
537 )
538 }
539
540 return null
541 })}
542 </div>
543 </div>
544 </div>
545 )
546 })}
547 </div>
548 )
549}
550
551// Schema display sidebar
552function SchemaPanel() {
553 return (
554 <div className="p-4 space-y-4 text-sm">
555 <div>
556 <h3 className="text-emerald-400 font-semibold mb-2">customers</h3>
557 <div className="space-y-1 text-gray-300 font-mono text-xs">
558 <div>
559 <span className="text-gray-500">id</span> number
560 </div>
561 <div>
562 <span className="text-gray-500">name</span> string
563 </div>
564 <div>
565 <span className="text-gray-500">email</span> string
566 </div>
567 <div>
568 <span className="text-gray-500">city</span> string
569 </div>
570 <div>
571 <span className="text-gray-500">joined</span> date
572 </div>
573 </div>
574 <div className="text-xs text-gray-500 mt-1">10 rows</div>
575 </div>
576
577 <div>
578 <h3 className="text-emerald-400 font-semibold mb-2">products</h3>
579 <div className="space-y-1 text-gray-300 font-mono text-xs">
580 <div>
581 <span className="text-gray-500">id</span> number
582 </div>
583 <div>
584 <span className="text-gray-500">name</span> string
585 </div>
586 <div>
587 <span className="text-gray-500">category</span> string
588 </div>
589 <div>
590 <span className="text-gray-500">price</span> number
591 </div>
592 <div>
593 <span className="text-gray-500">stock</span> number
594 </div>
595 </div>
596 <div className="text-xs text-gray-500 mt-1">10 rows</div>
597 </div>
598
599 <div>
600 <h3 className="text-emerald-400 font-semibold mb-2">purchases</h3>
601 <div className="space-y-1 text-gray-300 font-mono text-xs">
602 <div>
603 <span className="text-gray-500">id</span> number
604 </div>
605 <div>
606 <span className="text-gray-500">customer_id</span> number
607 </div>
608 <div>
609 <span className="text-gray-500">product_id</span> number
610 </div>
611 <div>
612 <span className="text-gray-500">quantity</span> number
613 </div>
614 <div>
615 <span className="text-gray-500">total</span> number
616 </div>
617 <div>
618 <span className="text-gray-500">purchased_at</span> date
619 </div>
620 </div>
621 <div className="text-xs text-gray-500 mt-1">25 rows</div>
622 </div>
623 </div>
624 )
625}
626
627const EXAMPLE_QUERIES = [
628 'For each city, show the total revenue, number of unique customers, and the most purchased product category',
629 'Rank every customer by total spending and show what percentage of their purchases were electronics vs furniture vs office products',
630 'Show a monthly breakdown of purchases with total revenue, average order value, and the number of distinct products sold each month',
631 'Which customers have purchased from all three product categories? Show their names, cities, and total spend per category',
632 'Find the top 3 products by revenue and for each one list every customer who bought it, their city, and how many units they ordered',
633 'Compare average order value across cities and product categories — which city-category combination has the highest spend?',
634]
635
636// Map gold-standard prompts to their file numbers
637const GOLD_PROMPT_MAP: Record<string, number> = {
638 'Which customers have purchased from all three product categories? Show their names, cities, and total spend per category': 1,
639 'Show a monthly breakdown of purchases with total revenue, average order value, and the number of distinct products sold each month': 2,
640 'Rank every customer by total spending and show what percentage of their purchases were electronics vs furniture vs office products': 3,
641 'For each city, show the total revenue, number of unique customers, and the most purchased product category': 4,
642}
643
644function extractReportText(messages: ReadonlyArray<UIMessage>): string {
645 return messages
646 .filter((m) => m.role === 'assistant')
647 .flatMap((m) =>
648 m.parts.filter((p) => p.type === 'text').map((p) => p.content),
649 )
650 .join('\n\n')
651}
652
653interface JudgeResult {
654 accuracy: number
655 comprehensiveness: number
656 summary: string
657}
658
659interface MessageMetrics {
660 query: string
661 codeMode: boolean
662 llmCalls: number
663 toolCalls: number
664 durationMs: number | null
665 judging?: 'pending' | JudgeResult
666}
667
668function MetricsSidebar({ entries }: { entries: Array<MessageMetrics> }) {
669 return (
670 <div className="w-72 shrink-0 flex flex-col border-l border-gray-800 bg-gray-900/50">
671 <div className="p-4 border-b border-gray-800">
672 <div className="text-sm font-semibold text-white">Metrics</div>
673 </div>
674 <div className="flex-1 overflow-y-auto p-4 space-y-3">
675 {entries.length === 0 && (
676 <div className="text-xs text-gray-500">
677 Metrics will appear here after each response.
678 </div>
679 )}
680 {entries.map((entry, i) => (
681 <div
682 key={i}
683 className={`rounded-lg border p-3 text-xs ${
684 entry.codeMode
685 ? 'border-purple-500/30 bg-purple-900/10'
686 : 'border-amber-500/30 bg-amber-900/10'
687 }`}
688 >
689 <div className="text-gray-300 font-medium mb-2 line-clamp-2">
690 {entry.query}
691 </div>
692 <div
693 className={`inline-block text-[10px] font-medium px-1.5 py-0.5 rounded mb-2 ${
694 entry.codeMode
695 ? 'bg-purple-600/50 text-purple-200'
696 : 'bg-amber-600/50 text-amber-200'
697 }`}
698 >
699 {entry.codeMode ? 'Code Mode' : 'Direct Tools'}
700 </div>
701 <div className="grid grid-cols-3 gap-2 text-center">
702 <div>
703 <div className="text-gray-500">LLM Calls</div>
704 <div className="text-white font-mono font-semibold">
705 {entry.llmCalls}
706 </div>
707 </div>
708 <div>
709 <div className="text-gray-500">Tool Calls</div>
710 <div className="text-white font-mono font-semibold">
711 {entry.toolCalls}
712 </div>
713 </div>
714 <div>
715 <div className="text-gray-500">Time</div>
716 <div className="text-white font-mono font-semibold">
717 {entry.durationMs !== null
718 ? formatDuration(entry.durationMs)
719 : '...'}
720 </div>
721 </div>
722 </div>
723 {entry.judging === 'pending' && (
724 <div className="mt-2 pt-2 border-t border-gray-700/50 flex items-center gap-2">
725 <div className="w-3 h-3 border-2 border-cyan-400 border-t-transparent rounded-full animate-spin" />
726 <span className="text-[10px] text-cyan-300">
727 Judging against gold standard...
728 </span>
729 </div>
730 )}
731 {entry.judging && entry.judging !== 'pending' && (
732 <div className="mt-2 pt-2 border-t border-gray-700/50">
733 <div className="grid grid-cols-2 gap-2 text-center mb-2">
734 <div>
735 <div className="text-gray-500 text-[10px]">Accuracy</div>
736 <div
737 className={`font-mono font-semibold ${entry.judging.accuracy >= 8 ? 'text-green-400' : entry.judging.accuracy >= 5 ? 'text-yellow-400' : 'text-red-400'}`}
738 >
739 {entry.judging.accuracy}/10
740 </div>
741 </div>
742 <div>
743 <div className="text-gray-500 text-[10px]">
744 Comprehensive
745 </div>
746 <div
747 className={`font-mono font-semibold ${entry.judging.comprehensiveness >= 8 ? 'text-green-400' : entry.judging.comprehensiveness >= 5 ? 'text-yellow-400' : 'text-red-400'}`}
748 >
749 {entry.judging.comprehensiveness}/10
750 </div>
751 </div>
752 </div>
753 <p className="text-[10px] text-gray-400 leading-relaxed">
754 {entry.judging.summary}
755 </p>
756 </div>
757 )}
758 </div>
759 ))}
760 </div>
761 </div>
762 )
763}
764
765function DatabaseDemoPage() {
766 const [selectedModel, setSelectedModel] = useState<ModelOption>(
767 MODEL_OPTIONS[0],
768 )
769 const [useCodeMode, setUseCodeMode] = useState(true)
770 const [toolCallEvents, setToolCallEvents] = useState<
771 Map<string, Array<VMEvent>>
772 >(new Map())
773 const eventIdCounter = useRef(0)
774
775 // Snippets state
776 const [withSnippets, setWithSnippets] = useState(false)
777 const [snippets, setSnippets] = useState<Array<SnippetWithCode>>([])
778 const [isLoadingSnippets, setIsLoadingSnippets] = useState(false)
779 const [snippetsDialogOpen, setSnippetsDialogOpen] = useState(false)
780
781 // Per-message metrics tracking
782 const [metricsEntries, setMetricsEntries] = useState<Array<MessageMetrics>>(
783 [],
784 )
785 const pendingMetricsRef = useRef<{
786 llmCalls: number
787 durationMs: number | null
788 codeMode: boolean
789 } | null>(null)
790 const wasLoadingRef = useRef(false)
791 const useCodeModeRef = useRef(useCodeMode)
792 useCodeModeRef.current = useCodeMode
793
794 const body = useMemo(
795 () => ({
796 provider: selectedModel.provider,
797 model: selectedModel.model,
798 useCodeMode,
799 withSnippets,
800 }),
801 [selectedModel.provider, selectedModel.model, useCodeMode, withSnippets],
802 )
803
804 const loadSnippets = useCallback(async () => {
805 setIsLoadingSnippets(true)
806 try {
807 const response = await fetch('/api/db-snippets')
808 if (response.ok) {
809 const data = await response.json()
810 setSnippets(data)
811 }
812 } catch (error) {
813 console.error('Failed to load snippets:', error)
814 } finally {
815 setIsLoadingSnippets(false)
816 }
817 }, [])
818
819 const deleteSnippet = useCallback(async (name: string) => {
820 try {
821 const response = await fetch(
822 `/api/db-snippets?name=${encodeURIComponent(name)}`,
823 { method: 'DELETE' },
824 )
825 if (response.ok) {
826 setSnippets((prev) => prev.filter((s) => s.name !== name))
827 }
828 } catch (error) {
829 console.error('Failed to delete snippet:', error)
830 }
831 }, [])
832
833 const deleteAllSnippets = useCallback(async () => {
834 try {
835 const response = await fetch('/api/db-snippets?all=true', {
836 method: 'DELETE',
837 })
838 if (response.ok) {
839 setSnippets([])
840 }
841 } catch (error) {
842 console.error('Failed to delete all snippets:', error)
843 }
844 }, [])
845
846 const handleNewSnippet = useCallback(() => {
847 loadSnippets()
848 }, [loadSnippets])
849
850 // Load snippets when "With Snippets" is first enabled
851 useEffect(() => {
852 if (withSnippets) {
853 loadSnippets()
854 }
855 }, [withSnippets, loadSnippets])
856
857 const handleCustomEvent = useCallback(
858 (eventType: string, data: unknown, context: { toolCallId?: string }) => {
859 // Track metrics events
860 if (eventType === 'db_demo:chat_start') {
861 pendingMetricsRef.current = {
862 llmCalls: 0,
863 durationMs: null,
864 codeMode: useCodeModeRef.current,
865 }
866 return
867 }
868
869 if (eventType === 'db_demo:llm_call') {
870 if (
871 pendingMetricsRef.current &&
872 data &&
873 typeof data === 'object' &&
874 'count' in data
875 ) {
876 const count = (data as { count?: number }).count
877 if (typeof count === 'number') {
878 pendingMetricsRef.current.llmCalls = count
879 }
880 }
881 return
882 }
883
884 if (eventType === 'db_demo:chat_end') {
885 if (
886 pendingMetricsRef.current &&
887 data &&
888 typeof data === 'object' &&
889 'durationMs' in data
890 ) {
891 const dur = (data as { durationMs?: number }).durationMs
892 if (typeof dur === 'number') {
893 pendingMetricsRef.current.durationMs = dur
894 }
895 }
896 return
897 }
898
899 if (eventType === 'snippet:registered') {
900 handleNewSnippet()
901 return
902 }
903
904 // VM events for tool call display
905 const toolCallId = context.toolCallId
906 if (!toolCallId) return
907
908 const event: VMEvent = {
909 id: `event-${eventIdCounter.current++}`,
910 eventType,
911 data,
912 timestamp: Date.now(),
913 }
914
915 setToolCallEvents((prev) => {
916 const newMap = new Map(prev)
917 const events = newMap.get(toolCallId) || []
918 newMap.set(toolCallId, [...events, event])
919 return newMap
920 })
921 },
922 [handleNewSnippet],
923 )
924
925 const { messages, sendMessage, setMessages, isLoading } = useChat({
926 threadId: 'database-demo',
927 connection: fetchServerSentEvents('/api/database-demo'),
928 forwardedProps: body,
929 onCustomEvent: handleCustomEvent,
930 })
931
932 // Finalize metrics entry when isLoading transitions from true → false
933 useEffect(() => {
934 if (wasLoadingRef.current && !isLoading && pendingMetricsRef.current) {
935 const pending = pendingMetricsRef.current
936 pendingMetricsRef.current = null
937
938 // Find the user message that triggered this response
939 const userMessages = messages.filter((m) => m.role === 'user')
940 const lastUserMessage = userMessages[userMessages.length - 1]
941 const query =
942 lastUserMessage?.parts.find((p) => p.type === 'text')?.content ||
943 'Unknown query'
944
945 // Count tool calls from the latest assistant message
946 const lastAssistantMessage = [...messages]
947 .reverse()
948 .find((m) => m.role === 'assistant')
949 const toolCalls = lastAssistantMessage
950 ? lastAssistantMessage.parts.filter((p) => p.type === 'tool-call')
951 .length
952 : 0
953
954 const goldFileNum = GOLD_PROMPT_MAP[query]
955 const candidateReport = extractReportText(messages)
956
957 setMetricsEntries((prev) => [
958 ...prev,
959 {
960 query,
961 codeMode: pending.codeMode,
962 llmCalls: pending.llmCalls,
963 toolCalls,
964 durationMs: pending.durationMs,
965 judging: goldFileNum ? 'pending' : undefined,
966 },
967 ])
968
969 // If there's a gold standard, kick off judging
970 if (goldFileNum) {
971 const entryIndex = metricsEntries.length // index of the entry we just pushed
972 ;(async () => {
973 try {
974 const goldRes = await fetch(
975 `/gold-results/db-gold-messages-${goldFileNum}.json`,
976 )
977 const goldData = await goldRes.json()
978 const goldReport = extractReportText(goldData.messages)
979
980 const judgeRes = await fetch('/api/judge', {
981 method: 'POST',
982 headers: { 'Content-Type': 'application/json' },
983 body: JSON.stringify({
984 query,
985 goldReport,
986 candidateReport,
987 }),
988 })
989 const judgeResult: JudgeResult = await judgeRes.json()
990
991 setMetricsEntries((prev) =>
992 prev.map((e, i) =>
993 i === entryIndex ? { ...e, judging: judgeResult } : e,
994 ),
995 )
996 } catch (error) {
997 console.error('Judging failed:', error)
998 setMetricsEntries((prev) =>
999 prev.map((e, i) =>
1000 i === entryIndex
1001 ? {
1002 ...e,
1003 judging: {
1004 accuracy: 0,
1005 comprehensiveness: 0,
1006 summary:
1007 'Judging failed — could not reach the judge API.',
1008 },
1009 }
1010 : e,
1011 ),
1012 )
1013 }
1014 })()
1015 }
1016 }
1017 wasLoadingRef.current = isLoading
1018 }, [isLoading, messages, metricsEntries.length])
1019
1020 const clearMessages = useCallback(() => {
1021 setMessages([])
1022 setToolCallEvents(new Map())
1023 }, [setMessages])
1024
1025 const exportMessages = useCallback(() => {
1026 if (messages.length === 0) return
1027 const firstUserMessage = messages.find((m) => m.role === 'user')
1028 const prompt =
1029 firstUserMessage?.parts.find((p) => p.type === 'text')?.content ?? ''
1030 const blob = new Blob([JSON.stringify({ prompt, messages }, null, 2)], {
1031 type: 'application/json',
1032 })
1033 const url = URL.createObjectURL(blob)
1034 const a = document.createElement('a')
1035 a.href = url
1036 a.download = `chat-export-${Date.now()}.json`
1037 a.click()
1038 URL.revokeObjectURL(url)
1039 }, [messages])
1040
1041 return (
1042 <div className="flex flex-col h-screen bg-gray-900">
1043 <Header />
1044 <div className="flex flex-1 overflow-hidden">
1045 {/* Left sidebar */}
1046 <div className="w-64 shrink-0 flex flex-col border-r border-gray-800 bg-gray-900/50">
1047 <div className="p-4 border-b border-gray-800">
1048 <div className="text-sm font-semibold text-white mb-3">
1049 Database Schema
1050 </div>
1051 <SchemaPanel />
1052 </div>
1053
1054 <div className="p-4 border-b border-gray-800">
1055 <div className="text-sm font-semibold text-white mb-2">
1056 Settings
1057 </div>
1058 <select
1059 value={MODEL_OPTIONS.findIndex(
1060 (opt) =>
1061 opt.provider === selectedModel.provider &&
1062 opt.model === selectedModel.model,
1063 )}
1064 onChange={(e) => {
1065 const option = MODEL_OPTIONS[parseInt(e.target.value)]
1066 setSelectedModel(option)
1067 }}
1068 disabled={isLoading}
1069 className="w-full rounded-lg border border-gray-700 bg-gray-900 px-3 py-1.5 text-xs text-white focus:outline-none focus:ring-1 focus:ring-emerald-500/50 disabled:opacity-50 mb-2"
1070 >
1071 {MODEL_OPTIONS.map((option, index) => (
1072 <option key={index} value={index}>
1073 {option.label}
1074 </option>
1075 ))}
1076 </select>
1077 <label className="flex items-center gap-2 text-xs text-gray-300 cursor-pointer mb-2">
1078 <input
1079 type="checkbox"
1080 checked={useCodeMode}
1081 onChange={(e) => setUseCodeMode(e.target.checked)}
1082 disabled={isLoading}
1083 className="rounded border-gray-600 bg-gray-800 text-emerald-500 focus:ring-emerald-500/50"
1084 />
1085 Code Mode
1086 </label>
1087 <div className="flex items-center gap-2 mb-2">
1088 <label className="flex items-center gap-2 text-xs text-gray-300 cursor-pointer">
1089 <input
1090 type="checkbox"
1091 checked={withSnippets}
1092 onChange={(e) => setWithSnippets(e.target.checked)}
1093 disabled={isLoading || !useCodeMode}
1094 className="rounded border-gray-600 bg-gray-800 text-purple-500 focus:ring-purple-500/50"
1095 />
1096 <span className="text-[11px] text-gray-400">With Snippets</span>
1097 </label>
1098 {withSnippets && (
1099 <button
1100 onClick={() => setSnippetsDialogOpen(true)}
1101 className="text-[11px] px-2 py-0.5 rounded border border-purple-500/30 bg-purple-900/20 text-purple-300 hover:bg-purple-900/40 transition-colors"
1102 >
1103 {snippets.length} Snippets
1104 </button>
1105 )}
1106 </div>
1107 <div className="flex gap-2">
1108 <button
1109 onClick={clearMessages}
1110 disabled={isLoading || messages.length === 0}
1111 className="flex-1 text-xs px-3 py-1.5 rounded-lg border border-gray-700 bg-gray-800/50 text-gray-300 hover:bg-gray-800 hover:text-white disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
1112 >
1113 Clear Chat
1114 </button>
1115 <button
1116 onClick={exportMessages}
1117 disabled={messages.length === 0}
1118 title="Export messages as JSON"
1119 className="text-xs px-2 py-1.5 rounded-lg border border-gray-700 bg-gray-800/50 text-gray-300 hover:bg-gray-800 hover:text-white disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
1120 >
1121 <Download className="w-3.5 h-3.5" />
1122 </button>
1123 </div>
1124 </div>
1125 </div>
1126
1127 {/* Main chat area */}
1128 <div className="flex-1 min-w-0 flex flex-col">
1129 {messages.length === 0 ? (
1130 <div className="flex-1 flex items-center justify-center px-8">
1131 <div className="text-center max-w-md">
1132 <div className="text-4xl mb-4">
1133 <span role="img" aria-label="database">
1134 {''}
1135 </span>
1136 </div>
1137 <h2 className="text-xl font-semibold text-white mb-2">
1138 Database Query Demo
1139 </h2>
1140 <p className="text-sm text-gray-400 mb-6">
1141 Ask questions about customers, products, and purchases. The AI
1142 will query the in-memory database to find answers.
1143 </p>
1144 <div className="grid grid-cols-2 gap-2">
1145 {EXAMPLE_QUERIES.slice(0, 4).map((query) => (
1146 <button
1147 key={query}
1148 onClick={() => sendMessage(query)}
1149 disabled={isLoading}
1150 className="text-left text-xs p-3 rounded-lg bg-gray-800/60 hover:bg-gray-800 text-gray-300 disabled:opacity-60 border border-gray-700/50 transition-colors"
1151 >
1152 {query}
1153 </button>
1154 ))}
1155 </div>
1156 </div>
1157 </div>
1158 ) : (
1159 <Messages messages={messages} toolCallEvents={toolCallEvents} />
1160 )}
1161
1162 <ChatInput
1163 onSend={(content) => sendMessage(content)}
1164 disabled={isLoading}
1165 placeholder="Ask about customers, products, or purchases..."
1166 exampleQueries={
1167 '"Top customers by spending" | "Most popular products" | "Revenue by category"'
1168 }
1169 />
1170 </div>
1171
1172 {/* Right sidebar — Metrics */}
1173 <MetricsSidebar entries={metricsEntries} />
1174 </div>
1175
1176 {/* Snippets Dialog */}
1177 <SnippetsDialog
1178 open={snippetsDialogOpen}
1179 onClose={() => setSnippetsDialogOpen(false)}
1180 snippets={snippets}
1181 onDelete={deleteSnippet}
1182 onDeleteAll={deleteAllSnippets}
1183 onRefresh={loadSnippets}
1184 isLoading={isLoadingSnippets}
1185 />
1186 </div>
1187 )
1188}