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