Open History to see the last commit
1import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import {
4 Check,
5 Loader2,
6 Package,
7 Send,
8 Square,
9 X,
10 CreditCard,
11 Database,
12 Paintbrush,
13 LayoutGrid,
14 AlertTriangle,
15 BarChart3,
16 Shield,
17} from 'lucide-react'
18import ReactMarkdown from 'react-markdown'
19import rehypeRaw from 'rehype-raw'
20import rehypeSanitize from 'rehype-sanitize'
21import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
22import { clientTools } from '@tanstack/ai-client'
23import type { UIMessage } from '@tanstack/ai-react'
24import {
25 availableAddOns,
26 getAvailableAddOnsToolDef,
27 selectAddOnsToolDef,
28 unselectAddOnsToolDef,
29} from '@/lib/addon-tools'
30
31// Type for add-on state
32interface AddOnState {
33 selected: boolean
34 enabled: boolean
35}
36
37// Icons for different add-on types
38const typeIcons: Record<string, React.ReactNode> = {
39 authentication: <Shield className="w-4 h-4" />,
40 payments: <CreditCard className="w-4 h-4" />,
41 database: <Database className="w-4 h-4" />,
42 styling: <Paintbrush className="w-4 h-4" />,
43 'ui-components': <LayoutGrid className="w-4 h-4" />,
44 monitoring: <AlertTriangle className="w-4 h-4" />,
45 analytics: <BarChart3 className="w-4 h-4" />,
46}
47
48function AddOnCard({
49 addOn,
50 state,
51 onToggle,
52}: {
53 addOn: (typeof availableAddOns)[0]
54 state: AddOnState
55 onToggle: () => void
56}) {
57 const Icon = typeIcons[addOn.type] || <Package className="w-4 h-4" />
58
59 return (
60 <div
61 className={`p-4 rounded-lg border transition-all ${
62 state.selected
63 ? 'border-green-500 bg-green-500/10'
64 : 'border-gray-700 bg-gray-800/50 hover:border-gray-600'
65 } ${!state.enabled ? 'opacity-50' : ''}`}
66 >
67 <div className="flex items-start gap-3">
68 <div
69 className={`p-2 rounded-lg ${state.selected ? 'bg-green-500/20 text-green-400' : 'bg-gray-700 text-gray-400'}`}
70 >
71 {Icon}
72 </div>
73 <div className="flex-1 min-w-0">
74 <div className="flex items-center gap-2">
75 <h3 className="font-medium text-white truncate">{addOn.name}</h3>
76 <span className="text-xs px-2 py-0.5 rounded-full bg-gray-700 text-gray-400">
77 {addOn.type}
78 </span>
79 </div>
80 <p className="text-sm text-gray-400 mt-1 line-clamp-2">
81 {addOn.description}
82 </p>
83 </div>
84 <button
85 onClick={onToggle}
86 disabled={!state.enabled}
87 className={`p-2 rounded-lg transition-colors ${
88 state.selected
89 ? 'bg-green-500 text-white hover:bg-green-600'
90 : 'bg-gray-700 text-gray-400 hover:bg-gray-600 hover:text-white'
91 } disabled:opacity-50 disabled:cursor-not-allowed`}
92 >
93 {state.selected ? (
94 <Check className="w-4 h-4" />
95 ) : (
96 <X className="w-4 h-4" />
97 )}
98 </button>
99 </div>
100 </div>
101 )
102}
103
104function AddOnPanel({
105 addOnState,
106 onToggle,
107}: {
108 addOnState: Record<string, AddOnState>
109 onToggle: (id: string) => void
110}) {
111 const selectedCount = Object.values(addOnState).filter(
112 (s) => s.selected,
113 ).length
114
115 return (
116 <div className="h-full flex flex-col">
117 <div className="p-4 border-b border-gray-700">
118 <h2 className="text-lg font-semibold text-white flex items-center gap-2">
119 <Package className="w-5 h-5 text-orange-500" />
120 Project Add-ons
121 </h2>
122 <p className="text-sm text-gray-400 mt-1">
123 {selectedCount} of {availableAddOns.length} add-ons selected
124 </p>
125 </div>
126 <div className="flex-1 overflow-y-auto p-4 space-y-3">
127 {availableAddOns.map((addOn) => (
128 <AddOnCard
129 key={addOn.id}
130 addOn={addOn}
131 state={addOnState[addOn.id] || { selected: false, enabled: true }}
132 onToggle={() => onToggle(addOn.id)}
133 />
134 ))}
135 </div>
136 </div>
137 )
138}
139
140function Messages({ messages }: { messages: ReadonlyArray<UIMessage> }) {
141 const messagesContainerRef = useRef<HTMLDivElement>(null)
142
143 useEffect(() => {
144 if (messagesContainerRef.current) {
145 messagesContainerRef.current.scrollTop =
146 messagesContainerRef.current.scrollHeight
147 }
148 }, [messages])
149
150 if (!messages.length) {
151 return (
152 <div className="flex-1 flex items-center justify-center text-gray-500">
153 <div className="text-center">
154 <Package className="w-12 h-12 mx-auto mb-4 opacity-50" />
155 <p>Ask the AI to configure your add-ons</p>
156 <p className="text-sm mt-2">
157 Try: "Add authentication and payments" or "Show me what's available"
158 </p>
159 </div>
160 </div>
161 )
162 }
163
164 return (
165 <div
166 ref={messagesContainerRef}
167 className="flex-1 overflow-y-auto px-4 py-4"
168 >
169 {messages.map(({ id, role, parts }) => (
170 <div
171 key={id}
172 className={`p-4 rounded-lg mb-2 ${
173 role === 'assistant'
174 ? 'bg-linear-to-r from-orange-500/5 to-red-600/5'
175 : 'bg-transparent'
176 }`}
177 >
178 <div className="flex items-start gap-4">
179 {role === 'assistant' ? (
180 <div className="w-8 h-8 rounded-lg bg-linear-to-r from-orange-500 to-red-600 flex items-center justify-center text-sm font-medium text-white shrink-0">
181 AI
182 </div>
183 ) : (
184 <div className="w-8 h-8 rounded-lg bg-gray-700 flex items-center justify-center text-sm font-medium text-white shrink-0">
185 U
186 </div>
187 )}
188 <div className="flex-1 min-w-0">
189 {parts.map((part, index) => {
190 if (part.type === 'text' && part.content) {
191 return (
192 <div
193 key={`text-${index}`}
194 className="text-white prose dark:prose-invert max-w-none"
195 >
196 <ReactMarkdown
197 rehypePlugins={[rehypeRaw, rehypeSanitize]}
198 >
199 {part.content}
200 </ReactMarkdown>
201 </div>
202 )
203 }
204
205 // Show tool call status
206 if (part.type === 'tool-call') {
207 return (
208 <div
209 key={part.id}
210 className="mt-2 p-3 bg-gray-800 rounded-lg border border-gray-700"
211 >
212 <div className="flex items-center gap-2 text-sm">
213 <span className="text-gray-400">Tool:</span>
214 <span className="text-orange-400 font-mono">
215 {part.name}
216 </span>
217 {part.state === 'input-streaming' && (
218 <Loader2 className="w-3 h-3 animate-spin text-orange-500" />
219 )}
220 {part.output !== undefined && (
221 <Check className="w-3 h-3 text-green-500" />
222 )}
223 </div>
224 {part.output !== undefined && (
225 <div className="mt-2 text-xs text-gray-500 font-mono overflow-x-auto">
226 <pre>
227 {JSON.stringify(part.output, null, 2).slice(0, 200)}
228 {JSON.stringify(part.output).length > 200
229 ? '...'
230 : ''}
231 </pre>
232 </div>
233 )}
234 </div>
235 )
236 }
237
238 return null
239 })}
240 </div>
241 </div>
242 </div>
243 ))}
244 </div>
245 )
246}
247
248function DebugPanel({
249 messages,
250 chunks,
251 onClearChunks,
252}: {
253 messages: ReadonlyArray<UIMessage>
254 chunks: Array<any>
255 onClearChunks: () => void
256}) {
257 const [activeTab, setActiveTab] = useState<'messages' | 'chunks'>('chunks')
258
259 return (
260 <div className="flex flex-col h-full">
261 <div className="p-4 border-b border-orange-500/20">
262 <h2 className="text-white font-semibold text-lg">Debug Panel</h2>
263 <p className="text-gray-400 text-sm mt-1">
264 Monitor multi-tool execution
265 </p>
266
267 <div className="flex gap-2 mt-4">
268 <button
269 onClick={() => setActiveTab('messages')}
270 className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
271 activeTab === 'messages'
272 ? 'bg-orange-500 text-white'
273 : 'bg-gray-800 text-gray-400 hover:text-white'
274 }`}
275 >
276 Messages
277 </button>
278 <button
279 onClick={() => setActiveTab('chunks')}
280 className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
281 activeTab === 'chunks'
282 ? 'bg-orange-500 text-white'
283 : 'bg-gray-800 text-gray-400 hover:text-white'
284 }`}
285 >
286 Raw Chunks ({chunks.length})
287 </button>
288 </div>
289 </div>
290
291 <div className="flex-1 overflow-y-auto p-4">
292 {activeTab === 'messages' && (
293 <pre className="text-xs text-gray-300 font-mono bg-gray-800 p-4 rounded-lg overflow-x-auto">
294 {JSON.stringify(messages, null, 2)}
295 </pre>
296 )}
297
298 {activeTab === 'chunks' && (
299 <div className="space-y-4">
300 <button
301 onClick={onClearChunks}
302 disabled={chunks.length === 0}
303 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"
304 >
305 🗑️ Clear Chunks
306 </button>
307
308 <div className="bg-gray-800 rounded-lg overflow-hidden">
309 <table className="w-full text-xs text-left">
310 <thead className="bg-gray-900 text-gray-400 uppercase">
311 <tr>
312 <th className="px-4 py-3 w-24">Type</th>
313 <th className="px-4 py-3 w-32">Tool Name</th>
314 <th className="px-4 py-3">Detail</th>
315 </tr>
316 </thead>
317 <tbody className="text-gray-300">
318 {chunks.map((chunk, idx) => {
319 const toolName = chunk.toolCallName || '-'
320
321 let detail = '-'
322 if (
323 chunk.type === 'TEXT_MESSAGE_CONTENT' ||
324 chunk.type === 'TOOL_CALL_ARGS'
325 ) {
326 detail = chunk.delta
327 } else if (chunk.type === 'TOOL_CALL_RESULT') {
328 detail = chunk.content
329 } else if (chunk.type === 'RUN_FINISHED') {
330 detail = `Finish: ${chunk.finishReason || 'unknown'}`
331 }
332
333 if (detail.length > 100) {
334 detail = detail.substring(0, 100) + '...'
335 }
336
337 return (
338 <tr
339 key={idx}
340 className="border-b border-gray-700 hover:bg-gray-750"
341 >
342 <td className="px-4 py-3 font-medium">{chunk.type}</td>
343 <td className="px-4 py-3">{toolName}</td>
344 <td className="px-4 py-3 font-mono text-xs break-all">
345 {detail}
346 </td>
347 </tr>
348 )
349 })}
350 </tbody>
351 </table>
352 </div>
353 </div>
354 )}
355 </div>
356 </div>
357 )
358}
359
360function AddonManagerPage() {
361 const [chunks, setChunks] = useState<Array<any>>([])
362 const [input, setInput] = useState('')
363
364 // Initialize add-on state
365 const [addOnState, setAddOnState] = useState<Record<string, AddOnState>>(
366 () => {
367 const initial: Record<string, AddOnState> = {}
368 for (const addOn of availableAddOns) {
369 initial[addOn.id] = { selected: false, enabled: true }
370 }
371 return initial
372 },
373 )
374
375 // Toggle add-on selection (for manual UI interaction)
376 const toggleAddOn = useCallback((id: string) => {
377 setAddOnState((prev) => ({
378 ...prev,
379 [id]: {
380 ...prev[id],
381 selected: !prev[id]?.selected,
382 },
383 }))
384 }, [])
385
386 // Client tool 1: Returns current add-on state
387 const getAvailableAddOnsClient = useMemo(
388 () =>
389 getAvailableAddOnsToolDef.client(() => {
390 console.log('[Client Tool] getAvailableAddOns called')
391 return availableAddOns.map((addOn) => ({
392 id: addOn.id,
393 name: addOn.name,
394 description: addOn.description,
395 type: addOn.type,
396 selected: addOnState[addOn.id]?.selected ?? false,
397 enabled: addOnState[addOn.id]?.enabled ?? true,
398 }))
399 }),
400 [addOnState],
401 )
402
403 // Client tool 2: Selects add-ons
404 const selectAddOnsClient = useMemo(
405 () =>
406 selectAddOnsToolDef.client((args) => {
407 console.log('[Client Tool] selectAddOns called with:', args)
408
409 // Calculate what will be selected BEFORE calling setState
410 // (setState callback is async, so we can't read results from it)
411 const toSelect: string[] = []
412 for (const addOnId of args.addOnIds) {
413 const state = addOnState[addOnId]
414 if (state && !state.selected && state.enabled) {
415 toSelect.push(addOnId)
416 }
417 }
418
419 // Update state if there's anything to select
420 if (toSelect.length > 0) {
421 setAddOnState((prev) => {
422 const next = { ...prev }
423 for (const addOnId of toSelect) {
424 next[addOnId] = { ...next[addOnId], selected: true }
425 }
426 return next
427 })
428 }
429
430 return {
431 success: toSelect.length > 0,
432 selectedAddOns: toSelect,
433 message:
434 toSelect.length > 0
435 ? `Successfully selected: ${toSelect.join(', ')}`
436 : 'No add-ons were selected (may already be selected or not found).',
437 }
438 }),
439 [addOnState],
440 )
441
442 // Client tool 3: Unselects add-ons
443 const unselectAddOnsClient = useMemo(
444 () =>
445 unselectAddOnsToolDef.client((args) => {
446 console.log('[Client Tool] unselectAddOns called with:', args)
447
448 // Calculate what will be unselected BEFORE calling setState
449 // (setState callback is async, so we can't read results from it)
450 const toUnselect: string[] = []
451 for (const addOnId of args.addOnIds) {
452 const state = addOnState[addOnId]
453 if (state && state.selected && state.enabled) {
454 toUnselect.push(addOnId)
455 }
456 }
457
458 // Update state if there's anything to unselect
459 if (toUnselect.length > 0) {
460 setAddOnState((prev) => {
461 const next = { ...prev }
462 for (const addOnId of toUnselect) {
463 next[addOnId] = { ...next[addOnId], selected: false }
464 }
465 return next
466 })
467 }
468
469 return {
470 success: toUnselect.length > 0,
471 unselectedAddOns: toUnselect,
472 message:
473 toUnselect.length > 0
474 ? `Successfully unselected: ${toUnselect.join(', ')}`
475 : 'No add-ons were unselected (may not be selected or not found).',
476 }
477 }),
478 [addOnState],
479 )
480
481 // Combine client tools
482 const tools = useMemo(
483 () =>
484 clientTools(
485 getAvailableAddOnsClient,
486 selectAddOnsClient,
487 unselectAddOnsClient,
488 ),
489 [getAvailableAddOnsClient, selectAddOnsClient, unselectAddOnsClient],
490 )
491
492 const { messages, sendMessage, isLoading, stop } = useChat({
493 threadId: 'addon-manager',
494 connection: fetchServerSentEvents('/api/addon-chat'),
495 tools,
496 onChunk: (chunk: any) => {
497 setChunks((prev) => [...prev, chunk])
498 },
499 })
500
501 const clearChunks = () => setChunks([])
502
503 return (
504 <div className="flex h-[calc(100vh-72px)] bg-gray-900">
505 {/* Left side - Add-on Selection Panel (1/4 width) */}
506 <div className="w-1/4 border-r border-gray-700 bg-gray-900">
507 <AddOnPanel addOnState={addOnState} onToggle={toggleAddOn} />
508 </div>
509
510 {/* Middle - Chat (1/2 width) */}
511 <div className="w-1/2 flex flex-col border-r border-orange-500/20">
512 <div className="border-b border-orange-500/20 bg-gray-800 px-4 py-3">
513 <h2 className="text-white font-semibold">AI Add-on Assistant</h2>
514 <p className="text-sm text-gray-400">
515 Ask me to configure your project add-ons
516 </p>
517 </div>
518
519 <Messages messages={messages} />
520
521 <div className="border-t border-orange-500/10 bg-gray-900/80 backdrop-blur-sm p-4">
522 {isLoading && (
523 <div className="flex items-center justify-center mb-3">
524 <button
525 onClick={stop}
526 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"
527 >
528 <Square className="w-4 h-4 fill-current" />
529 Stop
530 </button>
531 </div>
532 )}
533 <div className="relative">
534 <textarea
535 value={input}
536 onChange={(e) => setInput(e.target.value)}
537 placeholder="Ask me to add or remove add-ons..."
538 className="w-full rounded-lg border border-orange-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-orange-500/50 resize-none"
539 rows={2}
540 disabled={isLoading}
541 onKeyDown={(e) => {
542 if (e.key === 'Enter' && !e.shiftKey && input.trim()) {
543 e.preventDefault()
544 sendMessage(input)
545 setInput('')
546 }
547 }}
548 />
549 <button
550 onClick={() => {
551 if (input.trim()) {
552 sendMessage(input)
553 setInput('')
554 }
555 }}
556 disabled={!input.trim() || isLoading}
557 className="absolute right-2 bottom-2 p-2 text-orange-500 hover:text-orange-400 disabled:text-gray-500 transition-colors"
558 >
559 <Send className="w-4 h-4" />
560 </button>
561 </div>
562 </div>
563 </div>
564
565 {/* Right side - Debug Panel (1/4 width) */}
566 <div className="w-1/4 bg-gray-950 flex flex-col">
567 <DebugPanel
568 messages={messages}
569 chunks={chunks}
570 onClearChunks={clearChunks}
571 />
572 </div>
573 </div>
574 )
575}
576
577export const Route = createFileRoute('/addon-manager')({
578 component: AddonManagerPage,
579})