Open History to see the last commit
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
43}
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' },
58]
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 },
83]
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 )
212}
213β
214function Messages({
215 messages,
216 toolCallEvents,
217}: {
218 messages: ReadonlyArray<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 )
454}
455β
456// Calculate context sizes for the chat metrics
457function calculateActualSize(messages: ReadonlyArray<UIMessage>): number {
458 return new TextEncoder().encode(JSON.stringify(messages)).length
459}
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<ReadonlyArray<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 threadId: 'npm-github-chat',
683 connection: fetchServerSentEvents('/api/codemode'),
684 forwardedProps: body,
685 onCustomEvent: handleCustomEvent,
686 tools: [exportPdfClientTool],
687 })
688β
689 // Keep messagesRef in sync with messages
690 useEffect(() => {
691 messagesRef.current = messages
692 }, [messages])
693β
694 const [input, setInput] = useState('')
695 const chatLayoutOptions = [
696 { id: 'tools-data', label: 'Show tools & data' },
697 { id: 'full', label: 'Full width chat' },
698 { id: 'tools', label: 'Show tools' },
699 { id: 'data', label: 'Show data' },
700 ] as const
701 const chatWidthClass = chatLayout === 'full' ? 'max-w-none' : 'max-w-4xl'
702 const showTools = chatLayout === 'tools-data' || chatLayout === 'tools'
703 const showData = chatLayout === 'tools-data' || chatLayout === 'data'
704 const chatLayoutIndex = chatLayoutOptions.findIndex(
705 (option) => option.id === chatLayout,
706 )
707 const nextChatLayoutIndex = (chatLayoutIndex + 1) % chatLayoutOptions.length
708 const nextChatLayout = chatLayoutOptions[nextChatLayoutIndex]
709β
710 // Compute LLM tool call counts from messages
711 const llmToolCounts = useMemo(() => {
712 const counts = new Map<string, number>()
713 for (const message of messages) {
714 for (const part of message.parts) {
715 if (part.type === 'tool-call') {
716 counts.set(part.name, (counts.get(part.name) || 0) + 1)
717 }
718 }
719 }
720 return counts
721 }, [messages])
722β
723 const messageBytes = useMemo(() => calculateActualSize(messages), [messages])
724β
725 // Manual export function for the UI button
726 const exportConversationToPdf = useCallback(async () => {
727 if (messages.length === 0) return
728β
729 setIsExporting(true)
730 try {
731 const response = await fetch('/api/generate-pdf', {
732 method: 'POST',
733 headers: {
734 'Content-Type': 'application/json',
735 },
736 body: JSON.stringify({ messages }),
737 })
738β
739 if (!response.ok) {
740 const error = await response.json()
741 throw new Error(error.error || 'Failed to generate PDF')
742 }
743β
744 // Get the blob and trigger download
745 const blob = await response.blob()
746 const url = window.URL.createObjectURL(blob)
747 const a = document.createElement('a')
748 a.href = url
749 // Extract filename from Content-Disposition header or use default
750 const contentDisposition = response.headers.get('Content-Disposition')
751 const filenameMatch = contentDisposition?.match(/filename="(.+)"/)
752 a.download = filenameMatch?.[1] || 'conversation.pdf'
753 document.body.appendChild(a)
754 a.click()
755 document.body.removeChild(a)
756 window.URL.revokeObjectURL(url)
757 } catch (error) {
758 console.error('Failed to export PDF:', error)
759 alert(error instanceof Error ? error.message : 'Failed to export PDF')
760 } finally {
761 setIsExporting(false)
762 }
763 }, [messages])
764β
765 return (
766 <div className="flex flex-col h-screen bg-gray-900">
767 {/* Header */}
768 <Header>
769 <NoCodeMetrics
770 totalBytes={messageBytes}
771 llmCalls={llmCallCount}
772 totalContextBytes={totalContextBytes}
773 averageContextBytes={averageContextBytes}
774 totalTimeMs={totalTimeMs ?? undefined}
775 model={selectedModel.model}
776 />
777β
778 {/* Model Selector */}
779 <select
780 value={MODEL_OPTIONS.findIndex(
781 (opt) =>
782 opt.provider === selectedModel.provider &&
783 opt.model === selectedModel.model,
784 )}
785 onChange={(e) => {
786 const option = MODEL_OPTIONS[parseInt(e.target.value)]
787 setSelectedModel(option)
788 }}
789 disabled={isLoading}
790 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"
791 >
792 {MODEL_OPTIONS.map((option, index) => (
793 <option key={index} value={index}>
794 {option.label}
795 </option>
796 ))}
797 </select>
798β
799 {/* Export PDF Button */}
800 <button
801 onClick={exportConversationToPdf}
802 disabled={messages.length === 0 || isExporting || isLoading}
803 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"
804 title="Export conversation to PDF"
805 >
806 {isExporting ? (
807 <div className="w-4 h-4 border-2 border-cyan-400 border-t-transparent rounded-full animate-spin" />
808 ) : (
809 <Download className="w-4 h-4" />
810 )}
811 <span className="text-sm font-medium">
812 {isExporting ? 'Exporting...' : 'Export PDF'}
813 </span>
814 </button>
815 </Header>
816β
817 <div className="flex flex-1 overflow-hidden">
818 {/* Left Sidebar */}
819 {showTools && (
820 <ToolSidebar
821 selectedVM={selectedVM}
822 onVMChange={setSelectedVM}
823 toolInvocationCounts={toolInvocationCounts}
824 llmToolCounts={llmToolCounts}
825 llmCallCount={llmCallCount}
826 totalContextBytes={totalContextBytes}
827 averageContextBytes={averageContextBytes}
828 />
829 )}
830β
831 {/* Chat area */}
832 <div className="flex-1 flex flex-col min-w-0">
833 {/* Messages */}
834 <div className="flex-1 flex flex-col overflow-hidden">
835 <div className="border-b border-cyan-500/10 bg-gray-900/80 backdrop-blur-sm">
836 <div className={`${chatWidthClass} mx-auto w-full px-4 py-2`}>
837 <button
838 onClick={() => setChatLayout(nextChatLayout.id)}
839 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"
840 >
841 {nextChatLayout.label}
842 </button>
843 </div>
844 </div>
845 <div
846 className={`flex-1 flex flex-col h-full ${chatWidthClass} mx-auto w-full overflow-hidden`}
847 >
848 <Messages messages={messages} toolCallEvents={toolCallEvents} />
849 </div>
850 </div>
851β
852 {/* Input area */}
853 <div className="border-t border-cyan-500/10 bg-gray-900/80 backdrop-blur-sm">
854 <div className={`${chatWidthClass} mx-auto px-4 py-3 space-y-3`}>
855 {isLoading && (
856 <div className="flex items-center justify-center">
857 <button
858 onClick={stop}
859 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"
860 >
861 <Square className="w-4 h-4 fill-current" />
862 Stop
863 </button>
864 </div>
865 )}
866 <div className="relative">
867 <textarea
868 value={input}
869 onChange={(e) => setInput(e.target.value)}
870 placeholder="Ask about GitHub repos, NPM packages, or analytics..."
871 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"
872 rows={1}
873 style={{ minHeight: '44px', maxHeight: '200px' }}
874 disabled={isLoading}
875 onInput={(e) => {
876 const target = e.target as HTMLTextAreaElement
877 target.style.height = 'auto'
878 target.style.height =
879 Math.min(target.scrollHeight, 200) + 'px'
880 }}
881 onKeyDown={(e) => {
882 if (e.key === 'Enter' && !e.shiftKey && input.trim()) {
883 e.preventDefault()
884 sendMessage(input)
885 setInput('')
886 }
887 }}
888 />
889 <button
890 onClick={() => {
891 if (input.trim()) {
892 sendMessage(input)
893 setInput('')
894 }
895 }}
896 disabled={!input.trim() || isLoading}
897 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"
898 >
899 <Send className="w-4 h-4" />
900 </button>
901 </div>
902β
903 {/* Prompt suggestions */}
904 <div className="flex flex-wrap gap-2">
905 <div className="flex items-center gap-1.5 text-xs text-gray-500">
906 <Sparkles className="w-3 h-3" />
907 <span>Try:</span>
908 </div>
909 {PROMPT_SUGGESTIONS.map((suggestion, index) => (
910 <button
911 key={index}
912 onClick={() => {
913 if (!isLoading) {
914 sendMessage(suggestion.prompt)
915 }
916 }}
917 disabled={isLoading}
918 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"
919 >
920 {suggestion.label}
921 </button>
922 ))}
923 </div>
924 </div>
925 </div>
926 </div>
927β
928 {/* Right Sidebar - NPM Data */}
929 {showData && <NpmDataSidebar components={npmDataComponents} />}
930 </div>
931 </div>
932 )
933}