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