Open History to see the last commit
1import { createFileRoute } from '@tanstack/solid-router'
2import Send from 'lucide-solid/icons/send'
3import Square from 'lucide-solid/icons/square'
4import { fetchServerSentEvents, useChat } from '@tanstack/ai-solid'
5import { createChatClientOptions } from '@tanstack/ai-client'
6import { TextPart, ThinkingPart } from '@tanstack/ai-solid/ui'
7import { For, createSignal } from 'solid-js'
8
9import type { InferChatMessages, UIMessage } from '@tanstack/ai-client'
10
11import type { JSXElement } from 'solid-js'
12import GuitarRecommendation from '@/components/example-GuitarRecommendation'
13import { clientTools } from '@/lib/guitar-tools'
14
15// Create typed chat options for type inference
16const chatOptions = createChatClientOptions({
17 connection: fetchServerSentEvents('/api/chat'),
18 tools: clientTools,
19})
20
21// Extract the typed messages from the options
22type ChatMessages = InferChatMessages<typeof chatOptions>
23
24function ChatInputArea(props: { children: JSXElement }) {
25 return (
26 <div class="border-t border-orange-500/10 bg-gray-900/80 backdrop-blur-sm">
27 <div class="w-full px-4 py-3">{props.children}</div>
28 </div>
29 )
30}
31
32function Messages(props: {
33 messages: ChatMessages
34 addToolApprovalResponse: (response: {
35 id: string
36 approved: boolean
37 }) => Promise<void>
38}) {
39 return (
40 <div class="flex-1 overflow-y-auto px-4 py-4">
41 <For each={props.messages}>
42 {(message) => (
43 <div
44 class={`p-4 rounded-lg mb-2 ${
45 message.role === 'assistant'
46 ? 'bg-linear-to-r from-orange-500/5 to-red-600/5'
47 : 'bg-transparent'
48 }`}
49 >
50 <div class="flex items-start gap-4">
51 {message.role === 'assistant' ? (
52 <div class="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">
53 AI
54 </div>
55 ) : (
56 <div class="w-8 h-8 rounded-lg bg-gray-700 flex items-center justify-center text-sm font-medium text-white shrink-0">
57 U
58 </div>
59 )}
60 <div class="flex-1 min-w-0">
61 {/* Render parts in order */}
62 <For each={message.parts}>
63 {(part, index) => {
64 // Thinking part
65 if (part.type === 'thinking') {
66 // Check if thinking is complete (if there's a text part after)
67 const isComplete = message.parts
68 .slice(index() + 1)
69 .some((p) => p.type === 'text')
70 return (
71 <div class="mt-2 mb-2">
72 <ThinkingPart
73 content={part.content}
74 isComplete={isComplete}
75 class="p-4 bg-gray-800/50 border border-gray-700/50 rounded-lg"
76 />
77 </div>
78 )
79 }
80
81 if (part.type === 'text' && part.content) {
82 return (
83 <TextPart
84 content={part.content}
85 role={message.role}
86 class="text-white prose dark:prose-invert max-w-none"
87 />
88 )
89 }
90
91 // Approval UI. `'approval' in part` narrows the typed
92 // tool-call union to the tools declared `needsApproval: true`,
93 // which is where the `approval` field exists.
94 if (
95 part.type === 'tool-call' &&
96 part.state === 'approval-requested' &&
97 'approval' in part &&
98 part.approval
99 ) {
100 return (
101 <div class="p-4 bg-yellow-500/10 border border-yellow-500/20 rounded-lg mt-2">
102 <p class="text-white font-medium mb-2">
103 🔒 Approval Required: {part.name}
104 </p>
105 <div class="text-gray-300 text-sm mb-3">
106 <pre class="bg-gray-800 p-2 rounded text-xs overflow-x-auto">
107 {JSON.stringify(
108 JSON.parse(part.arguments),
109 null,
110 2,
111 )}
112 </pre>
113 </div>
114 <div class="flex gap-2">
115 <button
116 onClick={() =>
117 props.addToolApprovalResponse({
118 id: part.approval!.id,
119 approved: true,
120 })
121 }
122 class="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg text-sm font-medium transition-colors"
123 >
124 ✓ Approve
125 </button>
126 <button
127 onClick={() =>
128 props.addToolApprovalResponse({
129 id: part.approval!.id,
130 approved: false,
131 })
132 }
133 class="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg text-sm font-medium transition-colors"
134 >
135 ✗ Deny
136 </button>
137 </div>
138 </div>
139 )
140 }
141
142 // Guitar recommendation card
143 if (
144 part.type === 'tool-call' &&
145 part.name === 'recommendGuitar' &&
146 part.output
147 ) {
148 try {
149 return (
150 <div class="mt-2">
151 <GuitarRecommendation id={part.output.id} />
152 </div>
153 )
154 } catch {
155 return null
156 }
157 }
158
159 return null
160 }}
161 </For>
162 </div>
163 </div>
164 </div>
165 )}
166 </For>
167 </div>
168 )
169}
170
171function DebugPanel(props: {
172 messages: Array<UIMessage>
173 chunks: Array<any>
174 onClearChunks: () => void
175}) {
176 const [activeTab, setActiveTab] = createSignal<'messages' | 'chunks'>(
177 'messages',
178 )
179
180 const exportToTypeScript = () => {
181 const tsCode = `const rawChunks = ${JSON.stringify(props.chunks, null, 2)};`
182 navigator.clipboard.writeText(tsCode)
183 alert('TypeScript code copied to clipboard!')
184 }
185
186 return (
187 <div class="flex flex-col h-full">
188 <div class="p-4 border-b border-orange-500/20">
189 <h2 class="text-white font-semibold text-lg">Debug Panel</h2>
190 <p class="text-gray-400 text-sm mt-1">
191 View messages and raw stream chunks
192 </p>
193
194 {/* Tabs */}
195 <div class="flex gap-2 mt-4">
196 <button
197 onClick={() => setActiveTab('messages')}
198 class={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
199 activeTab() === 'messages'
200 ? 'bg-orange-500 text-white'
201 : 'bg-gray-800 text-gray-400 hover:text-white'
202 }`}
203 >
204 Messages
205 </button>
206 <button
207 onClick={() => setActiveTab('chunks')}
208 class={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
209 activeTab() === 'chunks'
210 ? 'bg-orange-500 text-white'
211 : 'bg-gray-800 text-gray-400 hover:text-white'
212 }`}
213 >
214 Raw Chunks ({props.chunks.length})
215 </button>
216 </div>
217 </div>
218
219 <div class="flex-1 overflow-y-auto p-4">
220 {activeTab() === 'messages' && (
221 <div>
222 <pre class="text-xs text-gray-300 font-mono bg-gray-800 p-4 rounded-lg overflow-x-auto">
223 {JSON.stringify(props.messages, null, 2)}
224 </pre>
225 </div>
226 )}
227
228 {activeTab() === 'chunks' && (
229 <div class="space-y-4">
230 <div class="flex gap-2">
231 <button
232 onClick={exportToTypeScript}
233 disabled={props.chunks.length === 0}
234 class="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"
235 >
236 📋 Export to TypeScript
237 </button>
238 <button
239 onClick={props.onClearChunks}
240 disabled={props.chunks.length === 0}
241 class="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"
242 >
243 🗑️ Clear Chunks
244 </button>
245 </div>
246
247 {/* Chunks Table */}
248 <div class="bg-gray-800 rounded-lg overflow-hidden">
249 <table class="w-full text-xs text-left">
250 <thead class="bg-gray-900 text-gray-400 uppercase">
251 <tr>
252 <th class="px-4 py-3 w-32">Type</th>
253 <th class="px-4 py-3 w-24">Role</th>
254 <th class="px-4 py-3 w-24">Tool Type</th>
255 <th class="px-4 py-3 w-32">Tool Name</th>
256 <th class="px-4 py-3">Detail</th>
257 </tr>
258 </thead>
259 <tbody class="text-gray-300">
260 <For each={props.chunks}>
261 {(chunk) => {
262 const role = chunk.role || '-'
263 const toolType = chunk.toolCall?.type || '-'
264 const toolName = chunk.toolCall?.function?.name || '-'
265
266 let detail = '-'
267 if (chunk.type === 'content' && chunk.content) {
268 detail = chunk.content
269 } else if (
270 chunk.type === 'tool_call' &&
271 chunk.toolCall?.function?.arguments
272 ) {
273 detail = chunk.toolCall.function.arguments
274 } else if (
275 chunk.type === 'tool_result' &&
276 chunk.content
277 ) {
278 detail = chunk.content
279 } else if (chunk.type === 'done') {
280 detail = `Finish: ${chunk.finishReason || 'unknown'}`
281 }
282
283 // Truncate at 200 chars
284 if (detail.length > 200) {
285 detail = detail.substring(0, 200) + '...'
286 }
287
288 return (
289 <tr class="border-b border-gray-700 hover:bg-gray-750">
290 <td class="px-4 py-3 font-medium">{chunk.type}</td>
291 <td class="px-4 py-3">{role}</td>
292 <td class="px-4 py-3">{toolType}</td>
293 <td class="px-4 py-3">{toolName}</td>
294 <td class="px-4 py-3 font-mono text-xs break-all">
295 {detail}
296 </td>
297 </tr>
298 )
299 }}
300 </For>
301 </tbody>
302 </table>
303 </div>
304 </div>
305 )}
306 </div>
307 </div>
308 )
309}
310
311function ChatPage() {
312 const [chunks, setChunks] = createSignal<Array<any>>([])
313
314 const { messages, sendMessage, isLoading, addToolApprovalResponse, stop } =
315 useChat({
316 ...chatOptions,
317 onChunk: (chunk: any) => {
318 setChunks((prev) => [...prev, chunk])
319 },
320 })
321 const [input, setInput] = createSignal('')
322
323 const clearChunks = () => setChunks([])
324
325 return (
326 <div class="flex h-[calc(100vh-72px)] bg-gray-900">
327 {/* Left side - Chat (1/4 width) */}
328 <div class="w-1/2 flex flex-col border-r border-orange-500/20">
329 <div class="p-4 border-b border-orange-500/20">
330 <h1 class="text-2xl font-bold bg-linear-to-r from-orange-500 to-red-600 text-transparent bg-clip-text">
331 TanStack AI on SolidJS
332 </h1>
333 </div>
334
335 <Messages
336 messages={messages()}
337 addToolApprovalResponse={addToolApprovalResponse}
338 />
339
340 <ChatInputArea>
341 <div class="space-y-3">
342 {isLoading() && (
343 <div class="flex items-center justify-center">
344 <button
345 onClick={stop}
346 class="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"
347 >
348 <Square class="w-4 h-4 fill-current" />
349 Stop
350 </button>
351 </div>
352 )}
353 <div class="relative">
354 <textarea
355 value={input()}
356 placeholder="Type something"
357 class="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 focus:border-transparent resize-none overflow-hidden shadow-lg"
358 rows={1}
359 style={{ 'min-height': '44px', 'max-height': '200px' }}
360 disabled={isLoading()}
361 onInput={(e) => {
362 const target = e.target as HTMLTextAreaElement
363 target.style.height = 'auto'
364 target.style.height =
365 Math.min(target.scrollHeight, 200) + 'px'
366 setInput(target.value)
367 }}
368 onKeyDown={(e) => {
369 if (e.key === 'Enter' && !e.shiftKey && input().trim()) {
370 e.preventDefault()
371 sendMessage(input())
372 setInput('')
373 }
374 }}
375 />
376 <button
377 onClick={() => {
378 if (input().trim()) {
379 sendMessage(input())
380 setInput('')
381 }
382 }}
383 disabled={!input().trim() || isLoading()}
384 class="absolute right-2 top-1/2 -translate-y-1/2 p-2 text-orange-500 hover:text-orange-400 disabled:text-gray-500 transition-colors focus:outline-none"
385 >
386 <Send class="w-4 h-4" />
387 </button>
388 </div>
389 </div>
390 </ChatInputArea>
391 </div>
392
393 {/* Right side - Debug Panel (3/4 width) */}
394 <div class="w-1/2 bg-gray-950 flex flex-col">
395 <DebugPanel
396 messages={messages()}
397 chunks={chunks()}
398 onClearChunks={clearChunks}
399 />
400 </div>
401 </div>
402 )
403}
404
405export const Route = createFileRoute('/')({
406 component: ChatPage,
407})