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

JavaScriptVM.tsx

271 lines8.3 KB

1import { useState, useEffect, useRef } from 'react'
2import {
3 ChevronDown,
4 ChevronRight,
5 Terminal,
6 Zap,
7 AlertCircle,
8 AlertTriangle,
9 MessageSquare,
10 Info,
11} from 'lucide-react'
12​
13// Custom event types
14export interface VMEvent {
15 id: string
16 eventType: string
17 data: unknown
18 timestamp: number
20​
21interface JavaScriptVMProps {
22 events: Array<VMEvent>
23 isExecuting?: boolean
25​
26export default function JavaScriptVM({
27 events,
28 isExecuting,
29}: JavaScriptVMProps) {
30 const scrollRef = useRef<HTMLDivElement>(null)
31 const [userControlled, setUserControlled] = useState(false)
32 const [isCollapsed, setIsCollapsed] = useState(false)
33 const prevExecutingRef = useRef(isExecuting)
34​
35 // Auto-collapse when execution completes (with delay)
36 useEffect(() => {
37 let timeoutId: ReturnType<typeof setTimeout> | null = null
38​
39 if (!userControlled) {
40 const wasExecuting = prevExecutingRef.current
41 const isComplete = !isExecuting
42​
43 if (wasExecuting && isComplete && events.length > 0) {
44 // Delay auto-collapse by 3 seconds so user can see the events
45 timeoutId = setTimeout(() => {
46 setIsCollapsed(true)
47 }, 3000)
48 } else if (isExecuting) {
49 setIsCollapsed(false)
50 }
51 }
52 prevExecutingRef.current = isExecuting
53​
54 return () => {
55 if (timeoutId) clearTimeout(timeoutId)
56 }
57 }, [isExecuting, userControlled, events.length])
58​
59 // Auto-scroll to bottom when new events arrive
60 useEffect(() => {
61 if (scrollRef.current && !isCollapsed) {
62 scrollRef.current.scrollTop = scrollRef.current.scrollHeight
63 }
64 }, [events, isCollapsed])
65​
66 const handleToggle = () => {
67 setUserControlled(true)
68 setIsCollapsed(!isCollapsed)
69 }
70​
71 if (events.length === 0 && !isExecuting) {
72 return null
73 }
74​
75 const getEventIcon = (eventType: string, data: unknown) => {
76 if (eventType === 'code_mode:execution_started') {
77 return <Terminal className="w-3.5 h-3.5 text-cyan-400" />
78 }
79 if (eventType === 'code_mode:console') {
80 const level = (data as { level?: string }).level || 'log'
81 switch (level) {
82 case 'error':
83 return <AlertCircle className="w-3.5 h-3.5 text-red-400" />
84 case 'warn':
85 return <AlertTriangle className="w-3.5 h-3.5 text-yellow-400" />
86 case 'info':
87 return <Info className="w-3.5 h-3.5 text-blue-400" />
88 default:
89 return <MessageSquare className="w-3.5 h-3.5 text-gray-400" />
90 }
91 }
92 if (eventType === 'code_mode:external_call') {
93 return <Zap className="w-3.5 h-3.5 text-amber-400" />
94 }
95 if (eventType === 'code_mode:external_result') {
96 return <Zap className="w-3.5 h-3.5 text-green-400" />
97 }
98 if (eventType === 'code_mode:external_error') {
99 return <AlertCircle className="w-3.5 h-3.5 text-red-400" />
100 }
101 return <Terminal className="w-3.5 h-3.5 text-cyan-400" />
102 }
103​
104 const formatTime = (timestamp: number) => {
105 const date = new Date(timestamp)
106 return date.toLocaleTimeString('en-US', {
107 hour12: false,
108 hour: '2-digit',
109 minute: '2-digit',
110 second: '2-digit',
111 fractionalSecondDigits: 3,
112 })
113 }
114​
115 const renderEventContent = (event: VMEvent) => {
116 const { eventType, data } = event
117 const typedData = data as Record<string, unknown>
118​
119 if (eventType === 'code_mode:execution_started') {
120 const codeLength = typedData.codeLength as number
121 return (
122 <span className="text-cyan-300">
123 <span className="text-gray-500">⚡</span> Executing {codeLength}{' '}
124 characters of TypeScript...
125 </span>
126 )
127 }
128​
129 if (eventType === 'code_mode:external_call') {
130 const funcName = typedData.function as string
131 return (
132 <span className="text-amber-300">
133 <span className="text-gray-500">{'>'}</span> {funcName}
134 <span className="text-gray-500">(</span>
135 <span className="text-cyan-300 text-xs">
136 {JSON.stringify(typedData.args)}
137 </span>
138 <span className="text-gray-500">)</span>
139 </span>
140 )
141 }
142​
143 if (eventType === 'code_mode:external_result') {
144 const funcName = typedData.function as string
145 const result = typedData.result
146 const resultStr = JSON.stringify(result)
147 const truncated =
148 resultStr.length > 60 ? resultStr.slice(0, 60) + '...' : resultStr
149 return (
150 <span className="text-green-300">
151 <span className="text-gray-500">{'<'}</span> {funcName}
152 <span className="text-gray-500"> → </span>
153 <span className="text-green-400 text-xs">{truncated}</span>
154 </span>
155 )
156 }
157​
158 if (eventType === 'code_mode:external_error') {
159 const funcName = typedData.function as string
160 const error = typedData.error as string
161 return (
162 <span className="text-red-300">
163 <span className="text-gray-500">{'!'}</span> {funcName}
164 <span className="text-gray-500"> → </span>
165 <span className="text-red-400 text-xs">{error}</span>
166 </span>
167 )
168 }
169​
170 if (eventType === 'code_mode:console') {
171 const message = typedData.message as string
172 const level = (typedData.level as string) || 'log'
173 const colorClass =
174 level === 'error'
175 ? 'text-red-300'
176 : level === 'warn'
177 ? 'text-yellow-300'
178 : level === 'info'
179 ? 'text-blue-300'
180 : 'text-gray-300'
181 return (
182 <span className={colorClass}>
183 <span className="text-gray-500">📝</span> {message}
184 </span>
185 )
186 }
187​
188 // Default for unknown events
189 return (
190 <span className="text-gray-400">
191 {eventType}: {JSON.stringify(data)}
192 </span>
193 )
194 }
195​
196 return (
197 <div className="rounded-lg border border-cyan-500/30 bg-gray-900/80 overflow-hidden">
198 {/* Header */}
199 <div
200 className="flex items-center gap-2 px-3 py-2 bg-gray-800/80 cursor-pointer hover:bg-gray-800 transition-colors"
201 onClick={handleToggle}
202 >
203 <button className="p-0.5">
204 {isCollapsed ? (
205 <ChevronRight size={16} className="text-gray-400" />
206 ) : (
207 <ChevronDown size={16} className="text-gray-400" />
208 )}
209 </button>
210 <Terminal className="w-4 h-4 text-cyan-400" />
211 <span className="text-sm font-medium text-cyan-300">JavaScript VM</span>
212 {isExecuting && (
213 <div className="w-3 h-3 border-2 border-cyan-400 border-t-transparent rounded-full animate-spin ml-1" />
214 )}
215 <span className="text-xs text-gray-500 ml-auto">
216 {events.length} event{events.length !== 1 ? 's' : ''}
217 </span>
218 </div>
219​
220 {/* Events list */}
221 {!isCollapsed && (
222 <div
223 ref={scrollRef}
224 className="max-h-48 overflow-y-auto px-3 py-2 space-y-1 font-mono text-xs"
225 style={{
226 scrollbarWidth: 'thin',
227 scrollbarColor: 'rgba(75, 85, 99, 0.5) transparent',
228 }}
229 >
230 {events.length === 0 && isExecuting ? (
231 <div className="flex items-center gap-2 text-gray-500 py-2">
232 <div className="w-3 h-3 border-2 border-cyan-400 border-t-transparent rounded-full animate-spin" />
233 <span>Waiting for external calls...</span>
234 </div>
235 ) : (
236 events.map((event) => <EventItem key={event.id} event={event} />)
237 )}
238 </div>
239 )}
240 </div>
241 )
242​
243 function EventItem({ event }: { event: VMEvent }) {
244 const [expanded, setExpanded] = useState(false)
245​
246 return (
247 <div className="group">
248 <div
249 className="flex items-start gap-2 py-1 px-2 rounded hover:bg-white/5 cursor-pointer transition-colors"
250 onClick={() => setExpanded(!expanded)}
251 >
252 {getEventIcon(event.eventType, event.data)}
253 <div className="flex-1 min-w-0 truncate">
254 {renderEventContent(event)}
255 </div>
256 <span className="text-[10px] text-gray-600 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
257 {formatTime(event.timestamp)}
258 </span>
259 </div>
260​
261 {expanded && (
262 <div className="ml-6 mt-1 mb-2 p-2 bg-black/30 rounded text-gray-400 overflow-x-auto">
263 <pre className="text-[10px]">
264 {JSON.stringify(event.data, null, 2)}
265 </pre>
266 </div>
267 )}
268 </div>
269 )
270 }