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

npm-github-chat.tsx

932 lines33.5 KB

1import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import {
4 ChevronDown,
5 ChevronRight,
6 Download,
7 Send,
8 Sparkles,
9 Square,
10} from 'lucide-react'
11import ReactMarkdown from 'react-markdown'
12import rehypeRaw from 'rehype-raw'
13import rehypeSanitize from 'rehype-sanitize'
14import rehypeHighlight from 'rehype-highlight'
15import remarkGfm from 'remark-gfm'
16import { parsePartialJSON } from '@tanstack/ai'
17import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
18import type { UIMessage } from '@tanstack/ai-react'
19import type { VMEvent, IsolateVM } from '@/components'
20import { getClientDefaultIsolateVM } from '@/lib/create-isolate-driver'
21import {
22 CodeBlock,
23 ExecutionResult,
24 JavaScriptVM,
25 ToolSidebar,
26 Header,
27 NoCodeMetrics,
28} from '@/components'
29import { NpmDataSidebar } from '@/components/NpmDataSidebar'
30import { exportConversationToPdfTool } from '@/lib/tools/export-pdf-tool'
31import { toolResultContentToString } from '@/lib/tool-result-content'
32​
33export const Route = createFileRoute('/_npm-github-chat/npm-github-chat')({
34 component: CodeModePage,
35})
36​
37type Provider = 'anthropic' | 'openai' | 'gemini'
38​
39interface ModelOption {
40 provider: Provider
41 model: string
42 label: string
44​
45const MODEL_OPTIONS: Array<ModelOption> = [
46 {
47 provider: 'anthropic',
48 model: 'claude-haiku-4-5',
49 label: 'Claude Haiku 4.5',
50 },
51 {
52 provider: 'anthropic',
53 model: 'claude-haiku-4-20250514',
54 label: 'Claude Haiku 4',
55 },
56 { provider: 'openai', model: 'gpt-4o', label: 'GPT-4o' },
57 { provider: 'gemini', model: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash' },
59​
60const PROMPT_SUGGESTIONS = [
61 {
62 label: 'πŸ”₯ Hottest React State Libraries',
63 prompt: 'What are the hottest React state management libraries?',
64 },
65 {
66 label: 'πŸ“Š Compare Query Libraries',
67 prompt:
68 'Compare React Query vs SWR - which has more downloads and GitHub stars?',
69 },
70 {
71 label: 'πŸ“ˆ Zustand Trends',
72 prompt: 'How many downloads did zustand get last month? Show me the trend.',
73 },
74 {
75 label: 'πŸ† Top TypeScript Frameworks',
76 prompt:
77 'What are the most popular TypeScript web frameworks by GitHub stars?',
78 },
79 {
80 label: 'πŸ” TanStack Query Stats',
81 prompt: 'Get me the GitHub stats and NPM downloads for @tanstack/query',
82 },
84​
85// Generic tool call display component
86function ToolCallDisplay({
87 name,
88 arguments: args,
89 output,
90 state,
91 hasResult = false,
92}: {
93 name: string
94 arguments: string
95 output?: unknown
96 state: string
97 hasResult?: boolean
98}) {
99 // ToolCallState: 'awaiting-input' | 'input-streaming' | 'input-complete' | 'approval-requested' | 'approval-responded'
100 const isInputStreaming = state === 'input-streaming'
101 const isInputComplete = state === 'input-complete'
102 // Consider complete if we have output OR a tool-result part exists
103 const hasOutput = output !== undefined || hasResult
104 const isExecuting = isInputComplete && !hasOutput
105 const isRunning = isInputStreaming || isExecuting
106​
107 const [inputOpen, setInputOpen] = useState(isRunning)
108 const [outputOpen, setOutputOpen] = useState(isRunning)
109 const [userControlledInput, setUserControlledInput] = useState(false)
110 const [userControlledOutput, setUserControlledOutput] = useState(false)
111 const prevStateRef = useRef(state)
112 const prevOutputRef = useRef(output)
113​
114 // Auto-collapse when execution completes (output becomes available)
115 useEffect(() => {
116 const hadNoOutput = prevOutputRef.current === undefined
117 const hasOutput = output !== undefined
118​
119 if (hadNoOutput && hasOutput) {
120 if (!userControlledInput) setInputOpen(false)
121 if (!userControlledOutput) setOutputOpen(false)
122 }
123 prevStateRef.current = state
124 prevOutputRef.current = output
125 }, [state, output, userControlledInput, userControlledOutput])
126​
127 let parsedArgs: unknown
128 try {
129 parsedArgs = JSON.parse(args)
130 } catch {
131 parsedArgs = args
132 }
133​
134 return (
135 <div className="mt-3 rounded-lg border border-amber-500/30 bg-amber-900/10 overflow-hidden">
136 {/* Header */}
137 <div className="flex items-center gap-2 px-3 py-2 bg-amber-900/20 text-amber-300 text-sm">
138 {isRunning ? (
139 <div className="w-4 h-4 border-2 border-amber-400 border-t-transparent rounded-full animate-spin" />
140 ) : (
141 <div className="w-4 h-4 rounded-full bg-amber-500/50" />
142 )}
143 <span className="font-mono font-medium">{name}</span>
144 {isRunning && (
145 <span className="text-xs px-2 py-0.5 rounded-full bg-amber-600 animate-pulse">
146 Running...
147 </span>
148 )}
149 </div>
150​
151 {/* Input section */}
152 <div className="border-t border-amber-500/20">
153 <button
154 onClick={() => {
155 setUserControlledInput(true)
156 setInputOpen(!inputOpen)
157 }}
158 className="w-full flex items-center gap-2 px-3 py-2 text-xs text-gray-400 hover:bg-white/5 transition-colors"
159 >
160 {inputOpen ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
161 <span>Input</span>
162 </button>
163 {inputOpen && (
164 <pre className="px-3 pb-3 text-xs text-gray-300 overflow-x-auto max-h-48 overflow-y-auto">
165 {typeof parsedArgs === 'string'
166 ? parsedArgs
167 : JSON.stringify(parsedArgs, null, 2)}
168 </pre>
169 )}
170 </div>
171​
172 {/* Output section - show when executing or has output */}
173 {(isExecuting || output !== undefined) && (
174 <div className="border-t border-amber-500/20">
175 <button
176 onClick={() => {
177 setUserControlledOutput(true)
178 setOutputOpen(!outputOpen)
179 }}
180 className="w-full flex items-center gap-2 px-3 py-2 text-xs text-gray-400 hover:bg-white/5 transition-colors"
181 >
182 {outputOpen ? (
183 <ChevronDown size={14} />
184 ) : (
185 <ChevronRight size={14} />
186 )}
187 <span>Output</span>
188 {isExecuting && (
189 <div className="w-3 h-3 border-2 border-amber-400 border-t-transparent rounded-full animate-spin ml-1" />
190 )}
191 </button>
192 {outputOpen && (
193 <div className="px-3 pb-3">
194 {isExecuting ? (
195 <div className="flex items-center gap-2 text-xs text-amber-300">
196 <div className="w-4 h-4 border-2 border-amber-400 border-t-transparent rounded-full animate-spin" />
197 <span>Executing...</span>
198 </div>
199 ) : (
200 <pre className="text-xs text-gray-300 overflow-x-auto max-h-48 overflow-y-auto">
201 {typeof output === 'string'
202 ? output
203 : JSON.stringify(output, null, 2)}
204 </pre>
205 )}
206 </div>
207 )}
208 </div>
209 )}
210 </div>
211 )
213​
214function Messages({
215 messages,
216 toolCallEvents,
217}: {
218 messages: Array<UIMessage>
219 toolCallEvents: Map<string, Array<VMEvent>>
220}) {
221 const messagesContainerRef = useRef<HTMLDivElement>(null)
222​
223 useEffect(() => {
224 if (messagesContainerRef.current) {
225 messagesContainerRef.current.scrollTop =
226 messagesContainerRef.current.scrollHeight
227 }
228 }, [messages])
229​
230 if (!messages.length) {
231 return (
232 <div className="flex-1 flex items-center justify-center text-gray-500">
233 <p>Ask a question about GitHub or NPM analytics...</p>
234 </div>
235 )
236 }
237​
238 return (
239 <div
240 ref={messagesContainerRef}
241 className="flex-1 overflow-y-auto px-4 py-4 scrollbar-thin scrollbar-track-transparent scrollbar-thumb-gray-700 hover:scrollbar-thumb-gray-600"
242 style={{
243 scrollbarWidth: 'thin',
244 scrollbarColor: 'rgba(75, 85, 99, 0.5) transparent',
245 }}
246 >
247 {messages.map((message) => {
248 // Build a map of tool results by toolCallId for quick lookup
249 // This handles the case where results come as separate tool-result parts
250 const toolResults = new Map<
251 string,
252 { content: string; state: string; error?: string }
253 >()
254 for (const p of message.parts) {
255 if (p.type === 'tool-result') {
256 toolResults.set(p.toolCallId, {
257 content: toolResultContentToString(p.content),
258 state: p.state,
259 error: p.error,
260 })
261 }
262 }
263​
264 return (
265 <div
266 key={message.id}
267 className={`p-4 rounded-lg mb-2 ${
268 message.role === 'assistant'
269 ? 'bg-linear-to-r from-cyan-500/5 to-blue-600/5'
270 : 'bg-transparent'
271 }`}
272 >
273 <div className="flex items-start gap-4">
274 {message.role === 'assistant' ? (
275 <div className="w-8 h-8 rounded-lg bg-linear-to-r from-cyan-500 to-blue-600 flex items-center justify-center text-sm font-medium text-white shrink-0">
276 AI
277 </div>
278 ) : (
279 <div className="w-8 h-8 rounded-lg bg-gray-700 flex items-center justify-center text-sm font-medium text-white shrink-0">
280 U
281 </div>
282 )}
283 <div className="flex-1 min-w-0">
284 {message.parts.map((part, index) => {
285 // Text content
286 if (part.type === 'text' && part.content) {
287 return (
288 <div key={`text-${index}`} className="markdown-content">
289 <ReactMarkdown
290 remarkPlugins={[remarkGfm]}
291 rehypePlugins={[
292 rehypeRaw,
293 rehypeSanitize,
294 rehypeHighlight,
295 ]}
296 >
297 {part.content}
298 </ReactMarkdown>
299 </div>
300 )
301 }
302​
303 // Tool call - execute_typescript (special display)
304 if (
305 part.type === 'tool-call' &&
306 part.name === 'execute_typescript'
307 ) {
308 // Parse the code from arguments (supports partial JSON during streaming)
309 let code = ''
310 const parsedArgs = parsePartialJSON(part.arguments)
311 if (parsedArgs?.typescriptCode) {
312 code = parsedArgs.typescriptCode
313 }
314​
315 // Check for tool result (either from part.output or from tool-result parts)
316 const toolResult = toolResults.get(part.id)
317 const hasOutput =
318 part.output !== undefined || toolResult !== undefined
319​
320 // Parse the output - could be from part.output or from tool-result content
321 let parsedOutput = part.output
322 if (!parsedOutput && toolResult?.content) {
323 try {
324 parsedOutput = JSON.parse(toolResult.content)
325 } catch {
326 parsedOutput = { result: toolResult.content }
327 }
328 }
329​
330 // Determine status based on tool call state
331 // ToolCallState: 'awaiting-input' | 'input-streaming' | 'input-complete' | 'approval-requested' | 'approval-responded'
332 const isAwaitingInput = part.state === 'awaiting-input'
333 const isInputStreaming = part.state === 'input-streaming'
334 const isInputComplete = part.state === 'input-complete'
335 const isStillGenerating =
336 isAwaitingInput || isInputStreaming
337 const isExecuting = isInputComplete && !hasOutput
338 const hasError =
339 parsedOutput?.success === false ||
340 toolResult?.error !== undefined
341​
342 // Code block status: running while streaming input or executing
343 // Only show success/error when we have actual output
344 const codeStatus =
345 isStillGenerating || isExecuting
346 ? 'running'
347 : hasError
348 ? 'error'
349 : 'success'
350​
351 // Execution result status
352 const executionStatus = isExecuting
353 ? 'running'
354 : hasError
355 ? 'error'
356 : 'success'
357​
358 // Get events for this tool call
359 const events = toolCallEvents.get(part.id) || []
360​
361 return (
362 <div key={part.id} className="mt-3 space-y-2">
363 {/* Show spinner while waiting for code, CodeBlock once we have code */}
364 {!code && isStillGenerating ? (
365 <div className="rounded-lg border border-blue-700 bg-blue-900/30 overflow-hidden">
366 <div className="flex items-center gap-3 px-4 py-3">
367 <div className="w-5 h-5 border-2 border-blue-400 border-t-transparent rounded-full animate-spin" />
368 <span className="text-blue-300 font-medium">
369 LLM is generating the TypeScript code...
370 </span>
371 </div>
372 </div>
373 ) : (
374 <CodeBlock code={code} status={codeStatus} />
375 )}
376 {/* Show JavaScript VM when input is complete (executing or has output) */}
377 {isInputComplete &&
378 (events.length > 0 || isExecuting || hasError) && (
379 <JavaScriptVM
380 events={events}
381 isExecuting={isExecuting}
382 />
383 )}
384 {/* Show ExecutionResult when input is complete (executing or has output) */}
385 {isInputComplete && (
386 <ExecutionResult
387 status={executionStatus}
388 result={parsedOutput?.result}
389 error={
390 parsedOutput?.error?.message ||
391 (typeof toolResult?.error === 'string'
392 ? toolResult.error
393 : undefined)
394 }
395 errorName={
396 typeof parsedOutput?.error?.name === 'string'
397 ? parsedOutput.error.name
398 : undefined
399 }
400 errorStack={
401 typeof parsedOutput?.error?.stack === 'string'
402 ? parsedOutput.error.stack
403 : undefined
404 }
405 logs={parsedOutput?.logs}
406 />
407 )}
408 </div>
409 )
410 }
411​
412 // Other tool calls - generic display
413 if (part.type === 'tool-call') {
414 // Check for tool result
415 const toolResult = toolResults.get(part.id)
416 const effectiveOutput =
417 part.output ??
418 (toolResult?.content
419 ? (() => {
420 try {
421 return JSON.parse(toolResult.content)
422 } catch {
423 return toolResult.content
424 }
425 })()
426 : undefined)
427​
428 return (
429 <ToolCallDisplay
430 key={part.id}
431 name={part.name}
432 arguments={part.arguments}
433 output={effectiveOutput}
434 state={part.state}
435 hasResult={toolResult !== undefined}
436 />
437 )
438 }
439​
440 // Skip tool-result parts (we handle them above via the map)
441 if (part.type === 'tool-result') {
442 return null
443 }
444​
445 return null
446 })}
447 </div>
448 </div>
449 </div>
450 )
451 })}
452 </div>
453 )
455​
456// Calculate context sizes for the chat metrics
457function calculateActualSize(messages: Array<UIMessage>): number {
458 return new TextEncoder().encode(JSON.stringify(messages)).length
460​
461function CodeModePage() {
462 const [selectedModel, setSelectedModel] = useState<ModelOption>(
463 MODEL_OPTIONS[0],
464 )
465 const [selectedVM, setSelectedVM] = useState<IsolateVM>(
466 // Prefer Bun native isolate when started with `pnpm dev:bun` /
467 // CODE_MODE_BUN=1 (see vite.config + getClientDefaultIsolateVM).
468 getClientDefaultIsolateVM,
469 )
470 const [chatLayout, setChatLayout] = useState<
471 'tools-data' | 'full' | 'tools' | 'data'
472 >('tools-data')
473 // Track events per tool call
474 const [toolCallEvents, setToolCallEvents] = useState<
475 Map<string, Array<VMEvent>>
476 >(new Map())
477 // Track invocation counts for VM tools (external_* functions)
478 const [toolInvocationCounts, setToolInvocationCounts] = useState<
479 Map<string, number>
480 >(new Map())
481 const [llmCallCount, setLlmCallCount] = useState(0)
482 const [totalContextBytes, setTotalContextBytes] = useState(0)
483 const [averageContextBytes, setAverageContextBytes] = useState(0)
484 const [totalTimeMs, setTotalTimeMs] = useState<number | null>(null)
485 const eventIdCounter = useRef(0)
486 const [isExporting, setIsExporting] = useState(false)
487 // Track NPM data components
488 const [npmDataComponents, setNpmDataComponents] = useState<
489 Array<{
490 id: string
491 type: string
492 data: any
493 timestamp: number
494 }>
495 >([])
496 const npmDataIdCounter = useRef(0)
497​
498 // Ref to hold current messages for the client tool to access
499 const messagesRef = useRef<Array<UIMessage>>([])
500​
501 const body = useMemo(
502 () => ({
503 provider: selectedModel.provider,
504 model: selectedModel.model,
505 vm: selectedVM,
506 }),
507 [selectedModel.provider, selectedModel.model, selectedVM],
508 )
509​
510 const handleCustomEvent = useCallback(
511 (eventType: string, data: unknown, context: { toolCallId?: string }) => {
512 const toolCallId = context.toolCallId
513​
514 // Handle npm:data events - store JSON data for sidebar display
515 if (eventType === 'npm:data') {
516 const npmData = data as {
517 componentType: string
518 toolName?: string
519 data: any
520 }
521 setNpmDataComponents((prev) => [
522 {
523 id: `npm-${npmDataIdCounter.current++}`,
524 type: npmData.componentType,
525 data: npmData.data,
526 timestamp: Date.now(),
527 },
528 ...prev,
529 ])
530 return
531 }
532​
533 if (eventType === 'code_mode:llm_call') {
534 let count: number | undefined
535 let nextTotalContextBytes: number | undefined
536 let nextAverageContextBytes: number | undefined
537 if (data && typeof data === 'object' && 'count' in data) {
538 const rawCount = (data as { count?: unknown }).count
539 if (typeof rawCount === 'number') {
540 count = rawCount
541 }
542 }
543 if (data && typeof data === 'object' && 'totalContextBytes' in data) {
544 const rawTotal = (data as { totalContextBytes?: unknown })
545 .totalContextBytes
546 if (typeof rawTotal === 'number') {
547 nextTotalContextBytes = rawTotal
548 }
549 }
550 if (data && typeof data === 'object' && 'averageContextBytes' in data) {
551 const rawAverage = (data as { averageContextBytes?: unknown })
552 .averageContextBytes
553 if (typeof rawAverage === 'number') {
554 nextAverageContextBytes = rawAverage
555 }
556 }
557 setLlmCallCount((prev) =>
558 typeof count === 'number' ? Math.max(prev, count) : prev + 1,
559 )
560 if (typeof nextTotalContextBytes === 'number') {
561 setTotalContextBytes(nextTotalContextBytes)
562 }
563 if (typeof nextAverageContextBytes === 'number') {
564 setAverageContextBytes(nextAverageContextBytes)
565 }
566 return
567 }
568​
569 if (eventType === 'code_mode:chat_start') {
570 setTotalTimeMs(null)
571 return
572 }
573​
574 if (eventType === 'code_mode:chat_end') {
575 if (data && typeof data === 'object' && 'durationMs' in data) {
576 const rawDuration = (data as { durationMs?: unknown }).durationMs
577 if (typeof rawDuration === 'number') {
578 setTotalTimeMs(rawDuration)
579 }
580 }
581 return
582 }
583​
584 if (!toolCallId) {
585 // Events without toolCallId are ignored (shouldn't happen with code mode)
586 return
587 }
588​
589 const event: VMEvent = {
590 id: `event-${eventIdCounter.current++}`,
591 eventType,
592 data,
593 timestamp: Date.now(),
594 }
595​
596 setToolCallEvents((prev) => {
597 const newMap = new Map(prev)
598 const events = newMap.get(toolCallId) || []
599 newMap.set(toolCallId, [...events, event])
600 return newMap
601 })
602​
603 // Track invocation counts for external_* calls
604 if (eventType === 'code_mode:external_call') {
605 const functionName = (data as { function?: string })?.function
606 if (functionName) {
607 setToolInvocationCounts((prev) => {
608 const newMap = new Map(prev)
609 newMap.set(functionName, (prev.get(functionName) || 0) + 1)
610 return newMap
611 })
612 }
613 }
614 },
615 [],
616 )
617​
618 // Create the client tool with execute function that uses messagesRef
619 const exportPdfClientTool = useMemo(
620 () =>
621 exportConversationToPdfTool.client(async (args) => {
622 console.log('exportPdfClientTool', args)
623​
624 const currentMessages = messagesRef.current
625 if (currentMessages.length === 0) {
626 return {
627 success: false,
628 message: 'No messages to export',
629 }
630 }
631​
632 try {
633 const response = await fetch('/api/generate-pdf', {
634 method: 'POST',
635 headers: {
636 'Content-Type': 'application/json',
637 },
638 body: JSON.stringify({
639 messages: currentMessages,
640 title: args.title,
641 }),
642 })
643​
644 if (!response.ok) {
645 const error = await response.json()
646 throw new Error(error.error || 'Failed to generate PDF')
647 }
648​
649 // Get the blob and trigger download
650 const blob = await response.blob()
651 const url = window.URL.createObjectURL(blob)
652 const a = document.createElement('a')
653 a.href = url
654 // Extract filename from Content-Disposition header or use default
655 const contentDisposition = response.headers.get('Content-Disposition')
656 const filenameMatch = contentDisposition?.match(/filename="(.+)"/)
657 const filename = filenameMatch?.[1] || 'conversation.pdf'
658 a.download = filename
659 document.body.appendChild(a)
660 a.click()
661 document.body.removeChild(a)
662 window.URL.revokeObjectURL(url)
663​
664 return {
665 success: true,
666 message: 'PDF exported successfully',
667 filename,
668 }
669 } catch (error) {
670 console.error('Failed to export PDF:', error)
671 return {
672 success: false,
673 message:
674 error instanceof Error ? error.message : 'Failed to export PDF',
675 }
676 }
677 }),
678 [],
679 )
680​
681 const { messages, sendMessage, isLoading, stop } = useChat({
682 connection: fetchServerSentEvents('/api/codemode'),
683 body,
684 onCustomEvent: handleCustomEvent,
685 tools: [exportPdfClientTool],
686 })
687​
688 // Keep messagesRef in sync with messages
689 useEffect(() => {
690 messagesRef.current = messages
691 }, [messages])
692​
693 const [input, setInput] = useState('')
694 const chatLayoutOptions = [
695 { id: 'tools-data', label: 'Show tools & data' },
696 { id: 'full', label: 'Full width chat' },
697 { id: 'tools', label: 'Show tools' },
698 { id: 'data', label: 'Show data' },
699 ] as const
700 const chatWidthClass = chatLayout === 'full' ? 'max-w-none' : 'max-w-4xl'
701 const showTools = chatLayout === 'tools-data' || chatLayout === 'tools'
702 const showData = chatLayout === 'tools-data' || chatLayout === 'data'
703 const chatLayoutIndex = chatLayoutOptions.findIndex(
704 (option) => option.id === chatLayout,
705 )
706 const nextChatLayoutIndex = (chatLayoutIndex + 1) % chatLayoutOptions.length
707 const nextChatLayout = chatLayoutOptions[nextChatLayoutIndex]
708​
709 // Compute LLM tool call counts from messages
710 const llmToolCounts = useMemo(() => {
711 const counts = new Map<string, number>()
712 for (const message of messages) {
713 for (const part of message.parts) {
714 if (part.type === 'tool-call') {
715 counts.set(part.name, (counts.get(part.name) || 0) + 1)
716 }
717 }
718 }
719 return counts
720 }, [messages])
721​
722 const messageBytes = useMemo(() => calculateActualSize(messages), [messages])
723​
724 // Manual export function for the UI button
725 const exportConversationToPdf = useCallback(async () => {
726 if (messages.length === 0) return
727​
728 setIsExporting(true)
729 try {
730 const response = await fetch('/api/generate-pdf', {
731 method: 'POST',
732 headers: {
733 'Content-Type': 'application/json',
734 },
735 body: JSON.stringify({ messages }),
736 })
737​
738 if (!response.ok) {
739 const error = await response.json()
740 throw new Error(error.error || 'Failed to generate PDF')
741 }
742​
743 // Get the blob and trigger download
744 const blob = await response.blob()
745 const url = window.URL.createObjectURL(blob)
746 const a = document.createElement('a')
747 a.href = url
748 // Extract filename from Content-Disposition header or use default
749 const contentDisposition = response.headers.get('Content-Disposition')
750 const filenameMatch = contentDisposition?.match(/filename="(.+)"/)
751 a.download = filenameMatch?.[1] || 'conversation.pdf'
752 document.body.appendChild(a)
753 a.click()
754 document.body.removeChild(a)
755 window.URL.revokeObjectURL(url)
756 } catch (error) {
757 console.error('Failed to export PDF:', error)
758 alert(error instanceof Error ? error.message : 'Failed to export PDF')
759 } finally {
760 setIsExporting(false)
761 }
762 }, [messages])
763​
764 return (
765 <div className="flex flex-col h-screen bg-gray-900">
766 {/* Header */}
767 <Header>
768 <NoCodeMetrics
769 totalBytes={messageBytes}
770 llmCalls={llmCallCount}
771 totalContextBytes={totalContextBytes}
772 averageContextBytes={averageContextBytes}
773 totalTimeMs={totalTimeMs ?? undefined}
774 model={selectedModel.model}
775 />
776​
777 {/* Model Selector */}
778 <select
779 value={MODEL_OPTIONS.findIndex(
780 (opt) =>
781 opt.provider === selectedModel.provider &&
782 opt.model === selectedModel.model,
783 )}
784 onChange={(e) => {
785 const option = MODEL_OPTIONS[parseInt(e.target.value)]
786 setSelectedModel(option)
787 }}
788 disabled={isLoading}
789 className="rounded-lg border border-cyan-500/20 bg-gray-900 px-3 py-1.5 text-sm text-white focus:outline-none focus:ring-1 focus:ring-cyan-500/50 disabled:opacity-50"
790 >
791 {MODEL_OPTIONS.map((option, index) => (
792 <option key={index} value={index}>
793 {option.label}
794 </option>
795 ))}
796 </select>
797​
798 {/* Export PDF Button */}
799 <button
800 onClick={exportConversationToPdf}
801 disabled={messages.length === 0 || isExporting || isLoading}
802 className="flex items-center gap-2 px-3 py-1.5 rounded-lg border border-cyan-500/30 bg-cyan-900/20 text-cyan-300 hover:bg-cyan-900/40 hover:border-cyan-500/50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
803 title="Export conversation to PDF"
804 >
805 {isExporting ? (
806 <div className="w-4 h-4 border-2 border-cyan-400 border-t-transparent rounded-full animate-spin" />
807 ) : (
808 <Download className="w-4 h-4" />
809 )}
810 <span className="text-sm font-medium">
811 {isExporting ? 'Exporting...' : 'Export PDF'}
812 </span>
813 </button>
814 </Header>
815​
816 <div className="flex flex-1 overflow-hidden">
817 {/* Left Sidebar */}
818 {showTools && (
819 <ToolSidebar
820 selectedVM={selectedVM}
821 onVMChange={setSelectedVM}
822 toolInvocationCounts={toolInvocationCounts}
823 llmToolCounts={llmToolCounts}
824 llmCallCount={llmCallCount}
825 totalContextBytes={totalContextBytes}
826 averageContextBytes={averageContextBytes}
827 />
828 )}
829​
830 {/* Chat area */}
831 <div className="flex-1 flex flex-col min-w-0">
832 {/* Messages */}
833 <div className="flex-1 flex flex-col overflow-hidden">
834 <div className="border-b border-cyan-500/10 bg-gray-900/80 backdrop-blur-sm">
835 <div className={`${chatWidthClass} mx-auto w-full px-4 py-2`}>
836 <button
837 onClick={() => setChatLayout(nextChatLayout.id)}
838 className="inline-flex items-center gap-2 rounded-md border border-cyan-500/30 bg-gray-800/60 px-3 py-1.5 text-xs text-cyan-200 hover:bg-gray-800/90 hover:border-cyan-500/50 transition-colors"
839 >
840 {nextChatLayout.label}
841 </button>
842 </div>
843 </div>
844 <div
845 className={`flex-1 flex flex-col h-full ${chatWidthClass} mx-auto w-full overflow-hidden`}
846 >
847 <Messages messages={messages} toolCallEvents={toolCallEvents} />
848 </div>
849 </div>
850​
851 {/* Input area */}
852 <div className="border-t border-cyan-500/10 bg-gray-900/80 backdrop-blur-sm">
853 <div className={`${chatWidthClass} mx-auto px-4 py-3 space-y-3`}>
854 {isLoading && (
855 <div className="flex items-center justify-center">
856 <button
857 onClick={stop}
858 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"
859 >
860 <Square className="w-4 h-4 fill-current" />
861 Stop
862 </button>
863 </div>
864 )}
865 <div className="relative">
866 <textarea
867 value={input}
868 onChange={(e) => setInput(e.target.value)}
869 placeholder="Ask about GitHub repos, NPM packages, or analytics..."
870 className="w-full rounded-lg border border-cyan-500/20 bg-gray-800/50 pl-4 pr-12 py-3 text-sm text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-cyan-500/50 focus:border-transparent resize-none overflow-hidden shadow-lg"
871 rows={1}
872 style={{ minHeight: '44px', maxHeight: '200px' }}
873 disabled={isLoading}
874 onInput={(e) => {
875 const target = e.target as HTMLTextAreaElement
876 target.style.height = 'auto'
877 target.style.height =
878 Math.min(target.scrollHeight, 200) + 'px'
879 }}
880 onKeyDown={(e) => {
881 if (e.key === 'Enter' && !e.shiftKey && input.trim()) {
882 e.preventDefault()
883 sendMessage(input)
884 setInput('')
885 }
886 }}
887 />
888 <button
889 onClick={() => {
890 if (input.trim()) {
891 sendMessage(input)
892 setInput('')
893 }
894 }}
895 disabled={!input.trim() || isLoading}
896 className="absolute right-2 top-1/2 -translate-y-1/2 p-2 text-cyan-500 hover:text-cyan-400 disabled:text-gray-500 transition-colors focus:outline-none"
897 >
898 <Send className="w-4 h-4" />
899 </button>
900 </div>
901​
902 {/* Prompt suggestions */}
903 <div className="flex flex-wrap gap-2">
904 <div className="flex items-center gap-1.5 text-xs text-gray-500">
905 <Sparkles className="w-3 h-3" />
906 <span>Try:</span>
907 </div>
908 {PROMPT_SUGGESTIONS.map((suggestion, index) => (
909 <button
910 key={index}
911 onClick={() => {
912 if (!isLoading) {
913 sendMessage(suggestion.prompt)
914 }
915 }}
916 disabled={isLoading}
917 className="px-3 py-1.5 text-xs bg-gray-800 hover:bg-gray-700 border border-cyan-500/20 hover:border-cyan-500/40 text-gray-300 hover:text-white rounded-full transition-all disabled:opacity-50 disabled:cursor-not-allowed"
918 >
919 {suggestion.label}
920 </button>
921 ))}
922 </div>
923 </div>
924 </div>
925 </div>
926​
927 {/* Right Sidebar - NPM Data */}
928 {showData && <NpmDataSidebar components={npmDataComponents} />}
929 </div>
930 </div>
931 )