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

reporting-agent.tsx

764 lines25.8 KB

1import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { ChevronDown, ChevronRight, Send, Sparkles, Square } from 'lucide-react'
4import ReactMarkdown from 'react-markdown'
5import rehypeRaw from 'rehype-raw'
6import rehypeSanitize from 'rehype-sanitize'
7import rehypeHighlight from 'rehype-highlight'
8import remarkGfm from 'remark-gfm'
9import { motion, AnimatePresence } from 'framer-motion'
10import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
11import type { UIMessage } from '@tanstack/ai-react'
12import { parsePartialJSON } from '@tanstack/ai'
13import {
14 CodeBlock,
15 ExecutionResult,
16 JavaScriptVM,
17 Header,
18 ContextSavings,
19} from '@/components'
20import type { VMEvent } from '@/components'
21​
22// Report components
23import {
24 ReportRenderer,
25 ReportSelector,
26 usePersistedReports,
27} from '@/components/reports'
28import type { Report, UIEvent } from '@/lib/reports/types'
29import { toolResultContentToString } from '@/lib/tool-result-content'
30​
31export const Route = createFileRoute('/_reporting/reporting-agent')({
32 component: ReportingAgentPage,
33})
34​
35type Provider = 'anthropic' | 'openai' | 'gemini'
36​
37interface ModelOption {
38 provider: Provider
39 model: string
40 label: string
42​
43const MODEL_OPTIONS: Array<ModelOption> = [
44 {
45 provider: 'anthropic',
46 model: 'claude-haiku-4-5',
47 label: 'Claude Haiku 4.5',
48 },
49 {
50 provider: 'anthropic',
51 model: 'claude-haiku-4-20250514',
52 label: 'Claude Haiku 4',
53 },
54 { provider: 'openai', model: 'gpt-4o', label: 'GPT-4o' },
55 { provider: 'gemini', model: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash' },
57​
58const PROMPT_SUGGESTIONS = [
59 {
60 label: 'πŸ“Š Create Report',
61 prompt:
62 'Create a report comparing zustand, jotai, and redux-toolkit with download stats and trends.',
63 },
64 {
65 label: 'πŸ”₯ State Libraries',
66 prompt:
67 'What are the hottest React state management libraries? Create a report on them containing download stats and trends.',
68 },
69 {
70 label: 'πŸ“ˆ Package Trends',
71 prompt: 'Create a report showing download trends for @tanstack/query.',
72 },
74​
75// Generic tool call display component
76function ToolCallDisplay({
77 name,
78 arguments: args,
79 output,
80 state,
81 hasResult = false,
82}: {
83 name: string
84 arguments: string
85 output?: unknown
86 state: string
87 hasResult?: boolean
88}) {
89 const isInputStreaming = state === 'input-streaming'
90 const isInputComplete = state === 'input-complete'
91 const hasOutput = output !== undefined || hasResult
92 const isExecuting = isInputComplete && !hasOutput
93 const isRunning = isInputStreaming || isExecuting
94​
95 const [inputOpen, setInputOpen] = useState(isRunning)
96 const [outputOpen, setOutputOpen] = useState(isRunning)
97 const [userControlledInput, setUserControlledInput] = useState(false)
98 const [userControlledOutput, setUserControlledOutput] = useState(false)
99 const prevStateRef = useRef(state)
100 const prevOutputRef = useRef(output)
101​
102 useEffect(() => {
103 const hadNoOutput = prevOutputRef.current === undefined
104 const hasOutputNow = output !== undefined
105​
106 if (hadNoOutput && hasOutputNow) {
107 if (!userControlledInput) setInputOpen(false)
108 if (!userControlledOutput) setOutputOpen(false)
109 }
110 prevStateRef.current = state
111 prevOutputRef.current = output
112 }, [state, output, userControlledInput, userControlledOutput])
113​
114 let parsedArgs: unknown
115 try {
116 parsedArgs = JSON.parse(args)
117 } catch {
118 parsedArgs = args
119 }
120​
121 // Determine colors based on tool name
122 const isReportTool = name.includes('report')
123 const borderColor = isReportTool
124 ? 'border-cyan-500/30'
125 : 'border-amber-500/30'
126 const bgColor = isReportTool ? 'bg-cyan-900/10' : 'bg-amber-900/10'
127 const headerBg = isReportTool ? 'bg-cyan-900/20' : 'bg-amber-900/20'
128 const textColor = isReportTool ? 'text-cyan-300' : 'text-amber-300'
129 const spinnerColor = isReportTool ? 'border-cyan-400' : 'border-amber-400'
130 const pillColor = isReportTool ? 'bg-cyan-600' : 'bg-amber-600'
131 const dotColor = isReportTool ? 'bg-cyan-500/50' : 'bg-amber-500/50'
132​
133 return (
134 <div
135 className={`mt-3 rounded-lg border ${borderColor} ${bgColor} overflow-hidden`}
136 >
137 <div
138 className={`flex items-center gap-2 px-3 py-2 ${headerBg} ${textColor} text-sm`}
139 >
140 {isRunning ? (
141 <div
142 className={`w-4 h-4 border-2 ${spinnerColor} border-t-transparent rounded-full animate-spin`}
143 />
144 ) : (
145 <div className={`w-4 h-4 rounded-full ${dotColor}`} />
146 )}
147 <span className="font-mono font-medium">{name}</span>
148 {isRunning && (
149 <span
150 className={`text-xs px-2 py-0.5 rounded-full ${pillColor} animate-pulse`}
151 >
152 Running...
153 </span>
154 )}
155 </div>
156​
157 <div className={`border-t ${borderColor.replace('/30', '/20')}`}>
158 <button
159 onClick={() => {
160 setUserControlledInput(true)
161 setInputOpen(!inputOpen)
162 }}
163 className="w-full flex items-center gap-2 px-3 py-2 text-xs text-gray-400 hover:bg-white/5 transition-colors"
164 >
165 {inputOpen ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
166 <span>Input</span>
167 </button>
168 {inputOpen && (
169 <pre className="px-3 pb-3 text-xs text-gray-300 overflow-x-auto max-h-48 overflow-y-auto">
170 {typeof parsedArgs === 'string'
171 ? parsedArgs
172 : JSON.stringify(parsedArgs, null, 2)}
173 </pre>
174 )}
175 </div>
176​
177 {(isExecuting || output !== undefined) && (
178 <div className={`border-t ${borderColor.replace('/30', '/20')}`}>
179 <button
180 onClick={() => {
181 setUserControlledOutput(true)
182 setOutputOpen(!outputOpen)
183 }}
184 className="w-full flex items-center gap-2 px-3 py-2 text-xs text-gray-400 hover:bg-white/5 transition-colors"
185 >
186 {outputOpen ? (
187 <ChevronDown size={14} />
188 ) : (
189 <ChevronRight size={14} />
190 )}
191 <span>Output</span>
192 {isExecuting && (
193 <div
194 className={`w-3 h-3 border-2 ${spinnerColor} border-t-transparent rounded-full animate-spin ml-1`}
195 />
196 )}
197 </button>
198 {outputOpen && (
199 <div className="px-3 pb-3">
200 {isExecuting ? (
201 <div className={`flex items-center gap-2 text-xs ${textColor}`}>
202 <div
203 className={`w-4 h-4 border-2 ${spinnerColor} border-t-transparent rounded-full animate-spin`}
204 />
205 <span>Executing...</span>
206 </div>
207 ) : (
208 <pre className="text-xs text-gray-300 overflow-x-auto max-h-48 overflow-y-auto">
209 {typeof output === 'string'
210 ? output
211 : JSON.stringify(output, null, 2)}
212 </pre>
213 )}
214 </div>
215 )}
216 </div>
217 )}
218 </div>
219 )
221​
222function Messages({
223 messages,
224 toolCallEvents,
225}: {
226 messages: ReadonlyArray<UIMessage>
227 toolCallEvents: Map<string, Array<VMEvent>>
228}) {
229 const messagesContainerRef = useRef<HTMLDivElement>(null)
230​
231 useEffect(() => {
232 if (messagesContainerRef.current) {
233 messagesContainerRef.current.scrollTop =
234 messagesContainerRef.current.scrollHeight
235 }
236 }, [messages])
237​
238 if (!messages.length) {
239 return null
240 }
241​
242 return (
243 <div
244 ref={messagesContainerRef}
245 className="flex-1 min-h-0 overflow-y-auto px-4 py-4 scrollbar-thin scrollbar-track-transparent scrollbar-thumb-gray-700 hover:scrollbar-thumb-gray-600"
246 >
247 {messages.map((message) => {
248 const toolResults = new Map<
249 string,
250 { content: string; state: string; error?: string }
251 >()
252 for (const p of message.parts) {
253 if (p.type === 'tool-result') {
254 toolResults.set(p.toolCallId, {
255 content: toolResultContentToString(p.content),
256 state: p.state,
257 error: p.error,
258 })
259 }
260 }
261​
262 return (
263 <div
264 key={message.id}
265 className={`p-4 rounded-lg mb-2 ${
266 message.role === 'assistant'
267 ? 'bg-linear-to-r from-purple-500/5 to-cyan-500/5'
268 : 'bg-transparent'
269 }`}
270 >
271 <div className="flex items-start gap-4">
272 {message.role === 'assistant' ? (
273 <div className="w-8 h-8 rounded-lg bg-linear-to-r from-purple-500 to-cyan-500 flex items-center justify-center text-sm font-medium text-white shrink-0">
274 AI
275 </div>
276 ) : (
277 <div className="w-8 h-8 rounded-lg bg-gray-700 flex items-center justify-center text-sm font-medium text-white shrink-0">
278 U
279 </div>
280 )}
281 <div className="flex-1 min-w-0">
282 {message.parts.map((part, index) => {
283 if (part.type === 'text' && part.content) {
284 return (
285 <div key={`text-${index}`} className="markdown-content">
286 <ReactMarkdown
287 remarkPlugins={[remarkGfm]}
288 rehypePlugins={[
289 rehypeRaw,
290 rehypeSanitize,
291 rehypeHighlight,
292 ]}
293 >
294 {part.content}
295 </ReactMarkdown>
296 </div>
297 )
298 }
299​
300 if (
301 part.type === 'tool-call' &&
302 part.name === 'execute_typescript'
303 ) {
304 let code = ''
305 const parsedArgs = parsePartialJSON(part.arguments)
306 if (parsedArgs?.typescriptCode) {
307 code = parsedArgs.typescriptCode
308 }
309​
310 const toolResult = toolResults.get(part.id)
311 const hasOutput =
312 part.output !== undefined || toolResult !== undefined
313​
314 let parsedOutput = part.output
315 if (!parsedOutput && toolResult?.content) {
316 try {
317 parsedOutput = JSON.parse(toolResult.content)
318 } catch {
319 parsedOutput = { result: toolResult.content }
320 }
321 }
322​
323 const isAwaitingInput = part.state === 'awaiting-input'
324 const isInputStreaming = part.state === 'input-streaming'
325 const isInputComplete = part.state === 'input-complete'
326 const isStillGenerating =
327 isAwaitingInput || isInputStreaming
328 const isExecuting = isInputComplete && !hasOutput
329 const hasError =
330 parsedOutput?.success === false ||
331 toolResult?.error !== undefined
332​
333 const codeStatus =
334 isStillGenerating || isExecuting
335 ? 'running'
336 : hasError
337 ? 'error'
338 : 'success'
339​
340 const executionStatus = isExecuting
341 ? 'running'
342 : hasError
343 ? 'error'
344 : 'success'
345​
346 const events = toolCallEvents.get(part.id) || []
347​
348 return (
349 <div key={part.id} className="mt-3 space-y-2">
350 {!code && isStillGenerating ? (
351 <div className="rounded-lg border border-blue-700 bg-blue-900/30 overflow-hidden">
352 <div className="flex items-center gap-3 px-4 py-3">
353 <div className="w-5 h-5 border-2 border-blue-400 border-t-transparent rounded-full animate-spin" />
354 <span className="text-blue-300 font-medium text-sm">
355 Generating code...
356 </span>
357 </div>
358 </div>
359 ) : (
360 <CodeBlock code={code} status={codeStatus} />
361 )}
362 {isInputComplete &&
363 (events.length > 0 || isExecuting) && (
364 <JavaScriptVM
365 events={events}
366 isExecuting={isExecuting}
367 />
368 )}
369 {isInputComplete && (
370 <ExecutionResult
371 status={executionStatus}
372 result={parsedOutput?.result}
373 error={
374 parsedOutput?.error?.message || toolResult?.error
375 }
376 logs={parsedOutput?.logs}
377 />
378 )}
379 </div>
380 )
381 }
382​
383 if (part.type === 'tool-call') {
384 const toolResult = toolResults.get(part.id)
385 const effectiveOutput =
386 part.output ??
387 (toolResult?.content
388 ? (() => {
389 try {
390 return JSON.parse(toolResult.content)
391 } catch {
392 return toolResult.content
393 }
394 })()
395 : undefined)
396​
397 return (
398 <ToolCallDisplay
399 key={part.id}
400 name={part.name}
401 arguments={part.arguments}
402 output={effectiveOutput}
403 state={part.state}
404 hasResult={toolResult !== undefined}
405 />
406 )
407 }
408​
409 if (part.type === 'tool-result') {
410 return null
411 }
412​
413 return null
414 })}
415 </div>
416 </div>
417 </div>
418 )
419 })}
420 </div>
421 )
423​
424// Empty state for chat when no messages
425function EmptyState() {
426 return (
427 <div className="flex-1 flex items-center justify-center text-gray-500 p-8">
428 <div className="text-center max-w-md">
429 <Sparkles size={48} className="mx-auto mb-4 text-purple-400/50" />
430 <p className="text-xl font-medium mb-3 text-white">Dynamic Reports</p>
431 <p className="text-sm text-gray-400">
432 Ask the AI to create reports, compare packages, or analyze data.
433 </p>
434 </div>
435 </div>
436 )
438​
439// Calculate context sizes
440function calculateActualSize(messages: ReadonlyArray<UIMessage>): number {
441 return new TextEncoder().encode(JSON.stringify(messages)).length
443​
444function calculateTheoreticalSize(
445 messages: ReadonlyArray<UIMessage>,
446 toolCallEvents: Map<string, Array<VMEvent>>,
447): number {
448 let theoreticalSize = calculateActualSize(messages)
449​
450 for (const events of toolCallEvents.values()) {
451 const externalCalls: Array<{ call: VMEvent; result?: VMEvent }> = []
452​
453 for (const event of events) {
454 if (event.eventType === 'code_mode:external_call') {
455 externalCalls.push({ call: event })
456 } else if (event.eventType === 'code_mode:external_result') {
457 const callData = event.data as { function?: string }
458 const matchingCall = [...externalCalls]
459 .reverse()
460 .find(
461 (c) =>
462 !c.result &&
463 (c.call.data as { function?: string })?.function ===
464 callData?.function,
465 )
466 if (matchingCall) {
467 matchingCall.result = event
468 }
469 }
470 }
471​
472 for (const { call, result } of externalCalls) {
473 const callData = call.data as {
474 function?: string
475 args?: unknown
476 }
477 const resultData = result?.data as { result?: unknown }
478​
479 const syntheticToolCall = {
480 type: 'tool-call',
481 id: `synthetic-${call.id}`,
482 name: callData?.function || 'unknown',
483 arguments: JSON.stringify(callData?.args || {}),
484 state: 'input-complete',
485 output: resultData?.result,
486 }
487​
488 theoreticalSize += new TextEncoder().encode(
489 JSON.stringify(syntheticToolCall),
490 ).length
491 }
492 }
493​
494 return theoreticalSize
496​
497function ReportingAgentPage() {
498 const [selectedModel, setSelectedModel] = useState<ModelOption>(
499 MODEL_OPTIONS[0],
500 )
501 const [toolCallEvents, setToolCallEvents] = useState<
502 Map<string, Array<VMEvent>>
503 >(new Map())
504 const eventIdCounter = useRef(0)
505​
506 // Reports state (persisted)
507 const {
508 reports,
509 activeReportId,
510 activeReport,
511 setActiveReportId,
512 createReport,
513 deleteReport,
514 dispatchUIEvent,
515 clearAll: clearAllReports,
516 isHydrated,
517 } = usePersistedReports()
518​
519 const hasActiveReport = activeReportId !== null
520​
521 const body = useMemo(
522 () => ({
523 provider: selectedModel.provider,
524 model: selectedModel.model,
525 }),
526 [selectedModel.provider, selectedModel.model],
527 )
528​
529 const handleCustomEvent = useCallback(
530 (eventType: string, data: unknown, context: { toolCallId?: string }) => {
531 const toolCallId = context.toolCallId
532​
533 // Handle report events
534 if (eventType === 'report:created') {
535 const { report, autoSelect } = data as {
536 report: Report
537 autoSelect: boolean
538 }
539 createReport(report, autoSelect)
540 return
541 }
542​
543 if (eventType === 'report:deleted') {
544 const { reportId } = data as { reportId: string }
545 deleteReport(reportId)
546 return
547 }
548​
549 if (eventType === 'report:ui') {
550 const { reportId, event } = data as {
551 reportId: string
552 event: UIEvent
553 }
554 dispatchUIEvent(reportId, event)
555 return
556 }
557​
558 // Handle VM events
559 if (!toolCallId) return
560​
561 const event: VMEvent = {
562 id: `event-${eventIdCounter.current++}`,
563 eventType,
564 data,
565 timestamp: Date.now(),
566 }
567​
568 setToolCallEvents((prev) => {
569 const newMap = new Map(prev)
570 const events = newMap.get(toolCallId) || []
571 newMap.set(toolCallId, [...events, event])
572 return newMap
573 })
574 },
575 [createReport, deleteReport, dispatchUIEvent],
576 )
577​
578 const { messages, sendMessage, isLoading, stop } = useChat({
579 threadId: 'reporting-agent',
580 connection: fetchServerSentEvents('/api/reports'),
581 forwardedProps: body,
582 onCustomEvent: handleCustomEvent,
583 })
584​
585 const [input, setInput] = useState('')
586​
587 // Calculate context savings
588 const contextData = useMemo(() => {
589 if (messages.length === 0 || toolCallEvents.size === 0) return null
590 const actual = calculateActualSize(messages)
591 const theoretical = calculateTheoreticalSize(messages, toolCallEvents)
592 return { actual, theoretical }
593 }, [messages, toolCallEvents])
594​
595 // Don't render until hydrated to avoid flash
596 if (!isHydrated) {
597 return (
598 <div className="flex h-screen bg-gray-900 items-center justify-center">
599 <div className="w-8 h-8 border-2 border-purple-400 border-t-transparent rounded-full animate-spin" />
600 </div>
601 )
602 }
603​
604 return (
605 <div className="flex flex-col h-screen bg-gray-900">
606 {/* Header */}
607 <Header>
608 {/* Context Savings - only when report exists and we have data */}
609 {hasActiveReport && contextData && (
610 <ContextSavings
611 actual={contextData.actual}
612 theoretical={contextData.theoretical}
613 model={selectedModel.model}
614 />
615 )}
616​
617 {/* Model Selector */}
618 <select
619 value={MODEL_OPTIONS.findIndex(
620 (opt) =>
621 opt.provider === selectedModel.provider &&
622 opt.model === selectedModel.model,
623 )}
624 onChange={(e) => {
625 const option = MODEL_OPTIONS[parseInt(e.target.value)]
626 setSelectedModel(option)
627 }}
628 disabled={isLoading}
629 className="rounded-lg border border-purple-500/20 bg-gray-900 px-3 py-1.5 text-sm text-white focus:outline-none focus:ring-1 focus:ring-purple-500/50 disabled:opacity-50"
630 >
631 {MODEL_OPTIONS.map((option, index) => (
632 <option key={index} value={index}>
633 {option.label}
634 </option>
635 ))}
636 </select>
637 </Header>
638​
639 {/* Main Content */}
640 <div className="flex flex-1 overflow-hidden">
641 {/* Chat Panel */}
642 <motion.div
643 animate={{ width: hasActiveReport ? '50%' : '100%' }}
644 transition={{ type: 'spring', stiffness: 300, damping: 30 }}
645 className="flex flex-col bg-gray-900 overflow-hidden"
646 >
647 <div className="flex-1 flex flex-col overflow-hidden">
648 <div className="flex-1 flex flex-col h-full max-w-4xl mx-auto w-full overflow-hidden">
649 {messages.length === 0 ? (
650 <EmptyState />
651 ) : (
652 <Messages messages={messages} toolCallEvents={toolCallEvents} />
653 )}
654 </div>
655 </div>
656​
657 {/* Input area */}
658 <div className="border-t border-gray-700/50 bg-gray-900/80 backdrop-blur-sm">
659 <div className="max-w-4xl mx-auto px-4 py-4 space-y-3">
660 {isLoading && (
661 <div className="flex items-center justify-center">
662 <button
663 onClick={stop}
664 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"
665 >
666 <Square className="w-4 h-4 fill-current" />
667 Stop
668 </button>
669 </div>
670 )}
671 <div className="relative">
672 <textarea
673 value={input}
674 onChange={(e) => setInput(e.target.value)}
675 placeholder="Ask about packages or create a report..."
676 className="w-full rounded-lg border border-purple-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-purple-500/50 focus:border-transparent resize-none overflow-hidden shadow-lg"
677 rows={1}
678 style={{ minHeight: '48px', maxHeight: '200px' }}
679 disabled={isLoading}
680 onInput={(e) => {
681 const target = e.target as HTMLTextAreaElement
682 target.style.height = 'auto'
683 target.style.height =
684 Math.min(target.scrollHeight, 200) + 'px'
685 }}
686 onKeyDown={(e) => {
687 if (e.key === 'Enter' && !e.shiftKey && input.trim()) {
688 e.preventDefault()
689 sendMessage(input)
690 setInput('')
691 }
692 }}
693 />
694 <button
695 onClick={() => {
696 if (input.trim()) {
697 sendMessage(input)
698 setInput('')
699 }
700 }}
701 disabled={!input.trim() || isLoading}
702 className="absolute right-3 top-1/2 -translate-y-1/2 p-2 text-purple-500 hover:text-purple-400 disabled:text-gray-500 transition-colors focus:outline-none"
703 >
704 <Send className="w-4 h-4" />
705 </button>
706 </div>
707​
708 {/* Prompt suggestions - only show when no report is active */}
709 {!hasActiveReport && (
710 <div className="flex flex-wrap gap-2">
711 {PROMPT_SUGGESTIONS.map((suggestion, index) => (
712 <button
713 key={index}
714 onClick={() => {
715 if (!isLoading) {
716 sendMessage(suggestion.prompt)
717 }
718 }}
719 disabled={isLoading}
720 className="px-3 py-1.5 text-xs bg-gray-800 hover:bg-gray-700 border border-purple-500/20 hover:border-purple-500/40 text-gray-300 hover:text-white rounded-full transition-all disabled:opacity-50 disabled:cursor-not-allowed"
721 >
722 {suggestion.label}
723 </button>
724 ))}
725 </div>
726 )}
727 </div>
728 </div>
729 </motion.div>
730​
731 {/* Report Panel - slides in from right with light theme */}
732 <AnimatePresence>
733 {hasActiveReport && activeReport && (
734 <motion.div
735 initial={{ width: 0, opacity: 0 }}
736 animate={{ width: '50%', opacity: 1 }}
737 exit={{ width: 0, opacity: 0 }}
738 transition={{ type: 'spring', stiffness: 300, damping: 30 }}
739 className="flex flex-col bg-sky-50/70 border-l border-sky-200/50 overflow-hidden"
740 >
741 <ReportSelector
742 reports={Array.from(reports.values()).map((r) => r.report)}
743 activeReportId={activeReportId}
744 onSelectReport={setActiveReportId}
745 onCloseReport={() => setActiveReportId(null)}
746 onClearAll={clearAllReports}
747 />
748​
749 <div
750 id={`report-${activeReport.report.id}`}
751 className="flex-1 overflow-auto p-6"
752 >
753 <ReportRenderer
754 nodes={activeReport.nodes}
755 rootIds={activeReport.rootIds}
756 />
757 </div>
758 </motion.div>
759 )}
760 </AnimatePresence>
761 </div>
762 </div>
763 )