Open History to see the last commit
1import { useEffect, useRef, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import {
4 FlaskConical,
5 Monitor,
6 Send,
7 Server,
8 ShieldCheck,
9 Square,
10 Zap,
11} from 'lucide-react'
12import ReactMarkdown from 'react-markdown'
13import rehypeRaw from 'rehype-raw'
14import rehypeSanitize from 'rehype-sanitize'
15import rehypeHighlight from 'rehype-highlight'
16import remarkGfm from 'remark-gfm'
17import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
18import { clientTools } from '@tanstack/ai-client'
19
20import type { UIMessage } from '@tanstack/ai-react'
21
22import {
23 clientServerToolDef,
24 clientServerToolWithApprovalDef,
25 clientToolDef,
26 clientToolWithApprovalDef,
27 createClientResult,
28} from '@/lib/simulator-tools'
29
30// Client tool implementations
31const clientToolClient = clientToolDef.client((args) =>
32 createClientResult('clientTool', args),
33)
34
35const clientToolWithApprovalClient = clientToolWithApprovalDef.client((args) =>
36 createClientResult('clientToolWithApproval', args),
37)
38
39const clientServerToolClient = clientServerToolDef.client((args) =>
40 createClientResult('clientServerTool', args),
41)
42
43const clientServerToolWithApprovalClient =
44 clientServerToolWithApprovalDef.client((args) =>
45 createClientResult('clientServerToolWithApproval', args),
46 )
47
48const tools = clientTools(
49 clientToolClient,
50 clientToolWithApprovalClient,
51 clientServerToolClient,
52 clientServerToolWithApprovalClient,
53)
54
55// Static Tailwind class mappings for JIT compatibility
56const categoryColors: Record<string, { text: string; hoverBorder: string }> = {
57 cyan: { text: 'text-cyan-400', hoverBorder: 'hover:border-cyan-500/30' },
58 purple: {
59 text: 'text-purple-400',
60 hoverBorder: 'hover:border-purple-500/30',
61 },
62 yellow: {
63 text: 'text-yellow-400',
64 hoverBorder: 'hover:border-yellow-500/30',
65 },
66 green: { text: 'text-green-400', hoverBorder: 'hover:border-green-500/30' },
67}
68
69// Tool injection templates
70const TOOL_TEMPLATES = [
71 {
72 category: 'Server Tools',
73 icon: Server,
74 color: 'cyan',
75 tools: [
76 {
77 name: 'Server Tool',
78 template: 'serverTool({ text: "hello from server" })',
79 description: 'Executes on server only',
80 },
81 {
82 name: 'Server + Approval',
83 template: 'serverToolWithApproval({ text: "needs approval" })',
84 description: 'Server execution with approval',
85 },
86 ],
87 },
88 {
89 category: 'Client Tools',
90 icon: Monitor,
91 color: 'purple',
92 tools: [
93 {
94 name: 'Client Tool',
95 template: 'clientTool({ text: "hello from client" })',
96 description: 'Executes in browser only',
97 },
98 {
99 name: 'Client + Approval',
100 template: 'clientToolWithApproval({ text: "client needs approval" })',
101 description: 'Client execution with approval',
102 },
103 ],
104 },
105 {
106 category: 'Hybrid Tools',
107 icon: Zap,
108 color: 'yellow',
109 tools: [
110 {
111 name: 'Client/Server Tool',
112 template: 'clientServerTool({ text: "hybrid tool" })',
113 description: 'Client takes precedence over server',
114 },
115 {
116 name: 'Hybrid + Approval',
117 template: 'clientServerToolWithApproval({ text: "hybrid approval" })',
118 description: 'Hybrid with approval required',
119 },
120 ],
121 },
122 {
123 category: 'Delayed Calls',
124 icon: ShieldCheck,
125 color: 'green',
126 tools: [
127 {
128 name: '2s Delay',
129 template: 'serverTool({ text: "delayed", delay: 2 })',
130 description: 'Server tool with 2 second delay',
131 },
132 {
133 name: 'Multi-Tool',
134 template:
135 'serverTool({ text: "first" })\nclientTool({ text: "second" })',
136 description: 'Multiple tool calls',
137 },
138 ],
139 },
140]
141
142function ChatInputArea({ children }: { children: React.ReactNode }) {
143 return (
144 <div className="border-t border-purple-500/10 bg-gray-900/80 backdrop-blur-sm">
145 <div className="w-full px-4 py-3">{children}</div>
146 </div>
147 )
148}
149
150function Messages({
151 messages,
152 addToolApprovalResponse,
153}: {
154 messages: ReadonlyArray<UIMessage>
155 addToolApprovalResponse: (response: {
156 id: string
157 approved: boolean
158 }) => Promise<void>
159}) {
160 const messagesContainerRef = useRef<HTMLDivElement>(null)
161
162 useEffect(() => {
163 if (messagesContainerRef.current) {
164 messagesContainerRef.current.scrollTop =
165 messagesContainerRef.current.scrollHeight
166 }
167 }, [messages])
168
169 if (!messages.length) {
170 return (
171 <div className="flex-1 flex items-center justify-center text-gray-500">
172 <div className="text-center">
173 <FlaskConical className="w-16 h-16 mx-auto mb-4 text-purple-500/50" />
174 <p className="text-lg font-medium">Tool Simulator</p>
175 <p className="text-sm mt-2">
176 Type a message or use the buttons below to inject tool calls
177 </p>
178 </div>
179 </div>
180 )
181 }
182
183 return (
184 <div
185 ref={messagesContainerRef}
186 className="flex-1 overflow-y-auto px-4 py-4"
187 >
188 {messages.map(({ id, role, parts }) => {
189 return (
190 <div
191 key={id}
192 className={`p-4 rounded-lg mb-2 ${
193 role === 'assistant'
194 ? 'bg-linear-to-r from-purple-500/5 to-cyan-600/5'
195 : 'bg-transparent'
196 }`}
197 >
198 <div className="flex items-start gap-4">
199 {role === 'assistant' ? (
200 <div className="w-8 h-8 rounded-lg bg-linear-to-r from-purple-500 to-cyan-600 flex items-center justify-center text-sm font-medium text-white shrink-0">
201 🤖
202 </div>
203 ) : (
204 <div className="w-8 h-8 rounded-lg bg-gray-700 flex items-center justify-center text-sm font-medium text-white shrink-0">
205 U
206 </div>
207 )}
208 <div className="flex-1 min-w-0">
209 {parts.map((part, index) => {
210 if (part.type === 'text' && part.content) {
211 return (
212 <div
213 key={`text-${index}`}
214 className="text-white prose dark:prose-invert max-w-none"
215 >
216 <ReactMarkdown
217 remarkPlugins={[remarkGfm]}
218 rehypePlugins={[
219 rehypeRaw,
220 rehypeSanitize,
221 rehypeHighlight,
222 ]}
223 >
224 {part.content}
225 </ReactMarkdown>
226 </div>
227 )
228 }
229
230 // Tool call display
231 if (part.type === 'tool-call') {
232 const isApprovalRequired =
233 part.state === 'approval-requested' && part.approval
234
235 // Approval UI
236 if (isApprovalRequired) {
237 return (
238 <div
239 key={part.id}
240 className="p-4 bg-yellow-500/10 border border-yellow-500/20 rounded-lg mt-2"
241 >
242 <p className="text-white font-medium mb-2">
243 🔒 Approval Required: {part.name}
244 </p>
245 <div className="text-gray-300 text-sm mb-3">
246 <pre className="bg-gray-800 p-2 rounded text-xs overflow-x-auto">
247 {JSON.stringify(
248 (() => {
249 try {
250 return JSON.parse(part.arguments)
251 } catch {
252 return part.arguments
253 }
254 })(),
255 null,
256 2,
257 )}
258 </pre>
259 </div>
260 <div className="flex gap-2">
261 <button
262 onClick={() =>
263 addToolApprovalResponse({
264 id: part.approval!.id,
265 approved: true,
266 })
267 }
268 className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg text-sm font-medium transition-colors"
269 >
270 ✓ Approve
271 </button>
272 <button
273 onClick={() =>
274 addToolApprovalResponse({
275 id: part.approval!.id,
276 approved: false,
277 })
278 }
279 className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg text-sm font-medium transition-colors"
280 >
281 ✗ Deny
282 </button>
283 </div>
284 </div>
285 )
286 }
287
288 // Regular tool call (completed or in progress)
289 const hasOutput = part.output !== undefined
290 const hasError = part.output?.error !== undefined
291
292 const getStateColor = () => {
293 if (hasError) return 'bg-red-500/10 border-red-500/30'
294 if (hasOutput)
295 return 'bg-green-500/10 border-green-500/30'
296 if (
297 part.state === 'input-streaming' ||
298 part.state === 'input-complete'
299 ) {
300 return 'bg-blue-500/10 border-blue-500/30'
301 }
302 return 'bg-gray-800/50 border-gray-700/50'
303 }
304
305 const getStatusDisplay = () => {
306 if (hasError) return 'error'
307 if (hasOutput) return 'complete'
308 return part.state
309 }
310
311 return (
312 <div
313 key={part.id}
314 className={`p-3 rounded-lg mt-2 border ${getStateColor()}`}
315 >
316 <div className="flex items-center gap-2 mb-2">
317 <Zap className="w-4 h-4 text-purple-400" />
318 <span className="text-white font-medium text-sm">
319 {part.name}
320 </span>
321 <span
322 className={`text-xs px-2 py-0.5 rounded ${
323 hasOutput
324 ? 'bg-green-500/20 text-green-400'
325 : hasError
326 ? 'bg-red-500/20 text-red-400'
327 : 'bg-blue-500/20 text-blue-400'
328 }`}
329 >
330 {getStatusDisplay()}
331 </span>
332 </div>
333 <pre className="text-xs text-gray-400 bg-gray-900/50 p-2 rounded overflow-x-auto">
334 <span className="text-gray-500">Args: </span>
335 {part.arguments}
336 </pre>
337 {part.output && (
338 <pre className="text-xs text-green-400 bg-gray-900/50 p-2 rounded mt-2 overflow-x-auto">
339 <span className="text-gray-500">Output: </span>
340 {JSON.stringify(part.output, null, 2)}
341 </pre>
342 )}
343 </div>
344 )
345 }
346
347 return null
348 })}
349 </div>
350 </div>
351 </div>
352 )
353 })}
354 </div>
355 )
356}
357
358function DebugPanel({
359 messages,
360 chunks,
361 onClearChunks,
362}: {
363 messages: ReadonlyArray<UIMessage>
364 chunks: Array<any>
365 onClearChunks: () => void
366}) {
367 const [activeTab, setActiveTab] = useState<'messages' | 'chunks'>('messages')
368
369 const exportToTypeScript = () => {
370 const tsCode = `const rawChunks = ${JSON.stringify(chunks, null, 2)};`
371 navigator.clipboard.writeText(tsCode)
372 alert('TypeScript code copied to clipboard!')
373 }
374
375 return (
376 <div className="flex flex-col h-full">
377 <div className="p-4 border-b border-purple-500/20">
378 <h2 className="text-white font-semibold text-lg">Debug Panel</h2>
379 <p className="text-gray-400 text-sm mt-1">
380 View messages and raw stream chunks
381 </p>
382
383 <div className="flex gap-2 mt-4">
384 <button
385 onClick={() => setActiveTab('messages')}
386 className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
387 activeTab === 'messages'
388 ? 'bg-purple-500 text-white'
389 : 'bg-gray-800 text-gray-400 hover:text-white'
390 }`}
391 >
392 Messages
393 </button>
394 <button
395 onClick={() => setActiveTab('chunks')}
396 className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
397 activeTab === 'chunks'
398 ? 'bg-purple-500 text-white'
399 : 'bg-gray-800 text-gray-400 hover:text-white'
400 }`}
401 >
402 Raw Chunks ({chunks.length})
403 </button>
404 </div>
405 </div>
406
407 <div className="flex-1 overflow-y-auto p-4">
408 {activeTab === 'messages' && (
409 <div>
410 <pre className="text-xs text-gray-300 font-mono bg-gray-800 p-4 rounded-lg overflow-x-auto">
411 {JSON.stringify(messages, null, 2)}
412 </pre>
413 </div>
414 )}
415
416 {activeTab === 'chunks' && (
417 <div className="space-y-4">
418 <div className="flex gap-2">
419 <button
420 onClick={exportToTypeScript}
421 disabled={chunks.length === 0}
422 className="px-4 py-2 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 text-white rounded-lg text-sm font-medium transition-colors"
423 >
424 📋 Export to TypeScript
425 </button>
426 <button
427 onClick={onClearChunks}
428 disabled={chunks.length === 0}
429 className="px-4 py-2 bg-red-600 hover:bg-red-700 disabled:bg-gray-600 text-white rounded-lg text-sm font-medium transition-colors"
430 >
431 🗑️ Clear Chunks
432 </button>
433 </div>
434
435 <div className="bg-gray-800 rounded-lg overflow-hidden">
436 <table className="w-full text-xs text-left">
437 <thead className="bg-gray-900 text-gray-400 uppercase">
438 <tr>
439 <th className="px-4 py-3 w-32">Type</th>
440 <th className="px-4 py-3 w-32">Tool Name</th>
441 <th className="px-4 py-3">Detail</th>
442 </tr>
443 </thead>
444 <tbody className="text-gray-300">
445 {chunks.map((chunk, idx) => {
446 const toolName = chunk.toolCall?.function?.name || '-'
447
448 let detail = '-'
449 if (chunk.type === 'content' && chunk.content) {
450 detail = chunk.content
451 } else if (
452 chunk.type === 'tool_call' &&
453 chunk.toolCall?.function?.arguments
454 ) {
455 detail = chunk.toolCall.function.arguments
456 } else if (chunk.type === 'tool_result' && chunk.content) {
457 detail = chunk.content
458 } else if (chunk.type === 'done') {
459 detail = `Finish: ${chunk.finishReason || 'unknown'}`
460 } else if (chunk.type === 'approval-requested') {
461 detail = `Approval for: ${chunk.toolName}`
462 } else if (chunk.type === 'tool-input-available') {
463 detail = `Input ready for: ${chunk.toolName}`
464 }
465
466 if (detail.length > 150) {
467 detail = detail.substring(0, 150) + '...'
468 }
469
470 return (
471 <tr
472 key={idx}
473 className="border-b border-gray-700 hover:bg-gray-750"
474 >
475 <td className="px-4 py-3 font-medium">{chunk.type}</td>
476 <td className="px-4 py-3">{toolName}</td>
477 <td className="px-4 py-3 font-mono text-xs break-all">
478 {detail}
479 </td>
480 </tr>
481 )
482 })}
483 </tbody>
484 </table>
485 </div>
486 </div>
487 )}
488 </div>
489 </div>
490 )
491}
492
493function ToolInjectionPanel({
494 onInject,
495}: {
496 onInject: (template: string) => void
497}) {
498 return (
499 <div className="border-t border-purple-500/20 bg-gray-900/50 p-4">
500 <h3 className="text-white font-medium text-sm mb-3 flex items-center gap-2">
501 <FlaskConical className="w-4 h-4 text-purple-400" />
502 Quick Inject Tool Calls
503 </h3>
504 <div className="grid grid-cols-2 gap-4">
505 {TOOL_TEMPLATES.map((category) => (
506 <div key={category.category}>
507 <div className="flex items-center gap-2 mb-2">
508 <category.icon
509 className={`w-3 h-3 ${categoryColors[category.color].text}`}
510 />
511 <span className="text-xs font-medium text-gray-400 uppercase">
512 {category.category}
513 </span>
514 </div>
515 <div className="space-y-1">
516 {category.tools.map((tool) => (
517 <button
518 key={tool.name}
519 onClick={() => onInject(tool.template)}
520 className={`w-full text-left px-3 py-2 rounded-lg text-sm transition-colors bg-gray-800/50 hover:bg-gray-700/50 border border-gray-700/50 ${categoryColors[category.color].hoverBorder}`}
521 title={tool.description}
522 >
523 <span className="text-white font-medium">{tool.name}</span>
524 <span className="text-gray-500 text-xs block truncate">
525 {tool.template.split('\n')[0]}
526 </span>
527 </button>
528 ))}
529 </div>
530 </div>
531 ))}
532 </div>
533 </div>
534 )
535}
536
537function SimulatorPage() {
538 const [chunks, setChunks] = useState<Array<any>>([])
539 const [input, setInput] = useState('')
540
541 const { messages, sendMessage, isLoading, addToolApprovalResponse, stop } =
542 useChat({
543 connection: fetchServerSentEvents('/api/simulator-chat'),
544 tools,
545 onChunk: (chunk: any) => {
546 setChunks((prev) => [...prev, chunk])
547 },
548 })
549
550 const clearChunks = () => setChunks([])
551
552 const handleInject = (template: string) => {
553 setInput((prev) => (prev ? `${prev}\n${template}` : template))
554 }
555
556 return (
557 <div className="flex h-[calc(100vh-72px)] bg-gray-900">
558 {/* Left side - Chat (1/2 width) */}
559 <div className="w-1/2 flex flex-col border-r border-purple-500/20">
560 {/* Header bar */}
561 <div className="border-b border-purple-500/20 bg-gray-800 px-4 py-3">
562 <div className="flex items-center gap-3">
563 <div className="flex items-center gap-2">
564 <FlaskConical className="w-5 h-5 text-purple-400" />
565 <h1 className="text-white font-semibold">Tool Simulator</h1>
566 </div>
567 <span className="text-xs px-2 py-1 bg-purple-500/20 text-purple-400 rounded">
568 Mock LLM
569 </span>
570 </div>
571 <p className="text-gray-400 text-xs mt-1">
572 Test tool execution flows with a simulated LLM. Use the syntax:{' '}
573 <code className="bg-gray-700 px-1 rounded">
574 toolName({'{ args }'})
575 </code>
576 </p>
577 </div>
578
579 <Messages
580 messages={messages}
581 addToolApprovalResponse={addToolApprovalResponse}
582 />
583
584 <ToolInjectionPanel onInject={handleInject} />
585
586 <ChatInputArea>
587 <div className="space-y-3">
588 {isLoading && (
589 <div className="flex items-center justify-center">
590 <button
591 onClick={stop}
592 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"
593 >
594 <Square className="w-4 h-4 fill-current" />
595 Stop
596 </button>
597 </div>
598 )}
599 <div className="relative">
600 <textarea
601 value={input}
602 onChange={(e) => setInput(e.target.value)}
603 placeholder="Type a message or tool call like: serverTool({ text: 'hello' })"
604 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"
605 rows={2}
606 style={{ minHeight: '60px', maxHeight: '200px' }}
607 disabled={isLoading}
608 onInput={(e) => {
609 const target = e.target as HTMLTextAreaElement
610 target.style.height = 'auto'
611 target.style.height =
612 Math.min(target.scrollHeight, 200) + 'px'
613 }}
614 onKeyDown={(e) => {
615 if (e.key === 'Enter' && !e.shiftKey && input.trim()) {
616 e.preventDefault()
617 sendMessage(input)
618 setInput('')
619 }
620 }}
621 />
622 <button
623 onClick={() => {
624 if (input.trim()) {
625 sendMessage(input)
626 setInput('')
627 }
628 }}
629 disabled={!input.trim() || isLoading}
630 className="absolute right-2 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"
631 >
632 <Send className="w-4 h-4" />
633 </button>
634 </div>
635 </div>
636 </ChatInputArea>
637 </div>
638
639 <div className="w-1/2 bg-gray-950 flex flex-col">
640 <DebugPanel
641 messages={messages}
642 chunks={chunks}
643 onClearChunks={clearChunks}
644 />
645 </div>
646 </div>
647 )
648}
649
650export const Route = createFileRoute('/simulator')({
651 component: SimulatorPage,
652})