Open History to see the last commit
1import { useEffect, useRef, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
4import { clientTools } from '@tanstack/ai-client'
5import { ThinkingPart } from '@tanstack/ai-react/ui'
6import ReactMarkdown from 'react-markdown'
7import rehypeRaw from 'rehype-raw'
8import rehypeSanitize from 'rehype-sanitize'
9import rehypeHighlight from 'rehype-highlight'
10import remarkGfm from 'remark-gfm'
11import { MessageSquare, Plus, Square, Trash2 } from 'lucide-react'
12import type {
13 ChatClientPersistence,
14 ChatPersistedState,
15 UIMessage,
16} from '@tanstack/ai-client'
17import GuitarRecommendation from '@/components/example-GuitarRecommendation'
18import {
19 addToCartToolDef,
20 addToWishListToolDef,
21 getPersonalGuitarPreferenceToolDef,
22 recommendGuitarToolDef,
23} from '@/lib/guitar-tools'
24
25// ---------------------------------------------------------------------------
26// Client tool implementations (same set the index route uses). The
27// /api/tanchat endpoint always merges the guitar *server* tools, and its
28// system prompt forces a `recommendGuitar` call — a *client* tool — so the
29// agent loop only completes if we provide these client implementations.
30// Reasoning + tool-call parts both live on the persisted UIMessage, so they
31// round-trip through the persistence adapter for free.
32// ---------------------------------------------------------------------------
33
34const getPersonalGuitarPreferenceToolClient =
35 getPersonalGuitarPreferenceToolDef.client(() => ({ preference: 'acoustic' }))
36
37const addToWishListToolClient = addToWishListToolDef.client((args) => {
38 const wishList = JSON.parse(localStorage.getItem('wishList') || '[]')
39 wishList.push(args.guitarId)
40 localStorage.setItem('wishList', JSON.stringify(wishList))
41 return { success: true, guitarId: args.guitarId, totalItems: wishList.length }
42})
43
44const addToCartToolClient = addToCartToolDef.client((args) => ({
45 success: true,
46 cartId: 'CART_CLIENT_' + Date.now(),
47 guitarId: args.guitarId,
48 quantity: args.quantity,
49 totalItems: args.quantity,
50}))
51
52const recommendGuitarToolClient = recommendGuitarToolDef.client(({ id }) => ({
53 id: +id,
54}))
55
56const tools = clientTools(
57 getPersonalGuitarPreferenceToolClient,
58 addToWishListToolClient,
59 addToCartToolClient,
60 recommendGuitarToolClient,
61)
62
63export const Route = createFileRoute('/threads')({
64 component: ThreadsRoute,
65})
66
67// ---------------------------------------------------------------------------
68// Storage layer
69//
70// Two concerns, two key spaces — this is the whole point of the demo:
71//
72// 1. Per-thread message history → the PR's persistence adapter, keyed by the
73// ChatClient `id`. We namespace it under `THREAD_KEY_PREFIX + id` so every
74// thread is its own localStorage entry and threads never overwrite each
75// other.
76// 2. The thread catalog (which threads exist, their titles, recency) → a
77// separate index the example owns. The persistence adapter is deliberately
78// single-conversation and knows nothing about "all my chats", so listing
79// and ordering threads is an app-level layer built on top.
80// ---------------------------------------------------------------------------
81
82const INDEX_KEY = 'tanstack-ai:threads'
83const THREAD_KEY_PREFIX = 'tanstack-ai:thread:'
84const NEW_CHAT_TITLE = 'New chat'
85const TITLE_MAX = 40
86
87interface ThreadMeta {
88 id: string
89 title: string
90 updatedAt: number
91}
92
93const hasWindow = () => typeof window !== 'undefined'
94
95/**
96 * Per-thread history adapter. Each thread's messages live under their own
97 * namespaced key, so this satisfies the PR's `ChatClientPersistence` contract
98 * (get/set/remove by id) while keeping threads isolated from each other.
99 */
100const threadPersistence: ChatClientPersistence = {
101 getItem: (id) => {
102 if (!hasWindow()) return null
103 const raw = window.localStorage.getItem(THREAD_KEY_PREFIX + id)
104 if (!raw) return null
105 // `UIMessage.createdAt` is a Date that JSON.stringify turned into a string —
106 // revive it on read.
107 const state = JSON.parse(raw) as ChatPersistedState
108 return {
109 ...state,
110 messages: state.messages.map((message) => ({
111 ...message,
112 createdAt:
113 typeof message.createdAt === 'string'
114 ? new Date(message.createdAt)
115 : message.createdAt,
116 })),
117 }
118 },
119 setItem: (id, state) => {
120 if (!hasWindow()) return
121 window.localStorage.setItem(THREAD_KEY_PREFIX + id, JSON.stringify(state))
122 },
123 removeItem: (id) => {
124 if (!hasWindow()) return
125 window.localStorage.removeItem(THREAD_KEY_PREFIX + id)
126 },
127}
128
129function readIndex(): Array<ThreadMeta> {
130 if (!hasWindow()) return []
131 try {
132 const raw = window.localStorage.getItem(INDEX_KEY)
133 return raw ? (JSON.parse(raw) as Array<ThreadMeta>) : []
134 } catch {
135 return []
136 }
137}
138
139function writeIndex(threads: Array<ThreadMeta>): void {
140 if (!hasWindow()) return
141 try {
142 window.localStorage.setItem(INDEX_KEY, JSON.stringify(threads))
143 } catch {
144 // Best-effort, mirroring the persistence adapter: a full or unavailable
145 // store should never break the chat.
146 }
147}
148
149const byRecency = (a: ThreadMeta, b: ThreadMeta) => b.updatedAt - a.updatedAt
150
151function truncateTitle(text: string): string {
152 const trimmed = text.trim()
153 return trimmed.length > TITLE_MAX
154 ? `${trimmed.slice(0, TITLE_MAX).trimEnd()}…`
155 : trimmed
156}
157
158function relativeTime(ts: number): string {
159 const seconds = Math.floor((Date.now() - ts) / 1000)
160 if (seconds < 60) return 'just now'
161 const minutes = Math.floor(seconds / 60)
162 if (minutes < 60) return `${minutes}m ago`
163 const hours = Math.floor(minutes / 60)
164 if (hours < 24) return `${hours}h ago`
165 return `${Math.floor(hours / 24)}d ago`
166}
167
168/**
169 * Owns the thread catalog in localStorage. This is the layer the persistence
170 * adapter doesn't provide: the list of conversations, their titles, and recency.
171 */
172function useThreadIndex() {
173 const [threads, setThreads] = useState<Array<ThreadMeta>>([])
174 // SSR-safety: the server has no localStorage, so we render an empty list and
175 // load the real catalog on the client after mount. `loaded` gates bootstrap
176 // logic so we don't auto-create a spurious thread before the real one loads.
177 const [loaded, setLoaded] = useState(false)
178 // Mirror of the catalog read synchronously by mutators. State closures are
179 // stale between two calls in the same event handler (e.g. set-title then
180 // bump-recency), which would make the second call clobber the first; the ref
181 // is always current, so sequential mutations compose correctly.
182 const threadsRef = useRef<Array<ThreadMeta>>([])
183
184 useEffect(() => {
185 const initial = readIndex().sort(byRecency)
186 threadsRef.current = initial
187 setThreads(initial)
188 setLoaded(true)
189 }, [])
190
191 const commit = (next: Array<ThreadMeta>) => {
192 const sorted = [...next].sort(byRecency)
193 threadsRef.current = sorted
194 setThreads(sorted)
195 writeIndex(sorted)
196 }
197
198 const createThread = (): ThreadMeta => {
199 const thread: ThreadMeta = {
200 id: crypto.randomUUID(),
201 title: NEW_CHAT_TITLE,
202 updatedAt: Date.now(),
203 }
204 commit([thread, ...threadsRef.current])
205 return thread
206 }
207
208 const deleteThread = (id: string) => {
209 threadPersistence.removeItem(id)
210 commit(threadsRef.current.filter((t) => t.id !== id))
211 }
212
213 /** Bump recency, and set the title the first time a thread gets one. */
214 const touchThread = (id: string, title?: string) => {
215 commit(
216 threadsRef.current.map((t) =>
217 t.id === id
218 ? {
219 ...t,
220 updatedAt: Date.now(),
221 title:
222 title && t.title === NEW_CHAT_TITLE
223 ? truncateTitle(title)
224 : t.title,
225 }
226 : t,
227 ),
228 )
229 }
230
231 return { threads, loaded, createThread, deleteThread, touchThread }
232}
233
234// ---------------------------------------------------------------------------
235// Route
236// ---------------------------------------------------------------------------
237
238function ThreadsRoute() {
239 const { threads, loaded, createThread, deleteThread, touchThread } =
240 useThreadIndex()
241 const [activeId, setActiveId] = useState<string | null>(null)
242
243 // Ensure there's always an active thread: keep the current one if it still
244 // exists, otherwise fall back to the most recent, otherwise create one.
245 useEffect(() => {
246 if (!loaded) return
247 if (activeId && threads.some((t) => t.id === activeId)) return
248 if (threads.length > 0) {
249 setActiveId(threads[0].id)
250 return
251 }
252 setActiveId(createThread().id)
253 // `threads`/`createThread` are derived from the same state; depending on
254 // `activeId` + `loaded` is enough to re-run when the active thread vanishes.
255 }, [loaded, activeId, threads.length])
256
257 const handleNewChat = () => {
258 // Don't pile up empty chats — if an untouched "New chat" exists, focus it.
259 const empty = threads.find((t) => t.title === NEW_CHAT_TITLE)
260 setActiveId(empty ? empty.id : createThread().id)
261 }
262
263 const handleDelete = (id: string) => {
264 deleteThread(id)
265 if (id === activeId) {
266 const next = threads.find((t) => t.id !== id)
267 // If nothing remains the bootstrap effect creates a fresh thread.
268 setActiveId(next ? next.id : null)
269 }
270 }
271
272 return (
273 <div className="flex h-[calc(100vh-72px)] bg-gray-900 text-white">
274 <aside className="flex w-72 flex-col border-r border-gray-800 bg-gray-950">
275 <div className="p-3">
276 <button
277 type="button"
278 onClick={handleNewChat}
279 className="flex w-full items-center justify-center gap-2 rounded-lg border border-orange-500/30 bg-orange-500/10 px-3 py-2 text-sm font-medium text-orange-300 transition-colors hover:bg-orange-500/20"
280 >
281 <Plus size={16} />
282 New chat
283 </button>
284 </div>
285 <nav className="flex-1 overflow-y-auto px-2 pb-3">
286 {threads.length === 0 && (
287 <p className="px-3 py-4 text-sm text-gray-500">No chats yet.</p>
288 )}
289 {threads.map((thread) => {
290 const isActive = thread.id === activeId
291 return (
292 <div
293 key={thread.id}
294 className={`group mb-1 flex items-center gap-2 rounded-lg px-3 py-2 text-sm transition-colors ${
295 isActive
296 ? 'bg-orange-500/15 text-orange-200'
297 : 'text-gray-300 hover:bg-gray-800'
298 }`}
299 >
300 <button
301 type="button"
302 onClick={() => setActiveId(thread.id)}
303 className="flex min-w-0 flex-1 items-center gap-2 text-left"
304 >
305 <MessageSquare
306 size={16}
307 className={isActive ? 'text-orange-300' : 'text-gray-500'}
308 />
309 <span className="min-w-0 flex-1">
310 <span className="block truncate">{thread.title}</span>
311 <span className="block text-xs text-gray-500">
312 {relativeTime(thread.updatedAt)}
313 </span>
314 </span>
315 </button>
316 <button
317 type="button"
318 onClick={() => handleDelete(thread.id)}
319 aria-label="Delete chat"
320 className="rounded p-1 text-gray-600 opacity-0 transition-opacity hover:text-red-400 group-hover:opacity-100"
321 >
322 <Trash2 size={15} />
323 </button>
324 </div>
325 )
326 })}
327 </nav>
328 </aside>
329
330 <main className="flex flex-1 flex-col">
331 {activeId ? (
332 <ThreadChat
333 key={activeId}
334 threadId={activeId}
335 onFirstMessage={(text) => touchThread(activeId, text)}
336 onActivity={() => touchThread(activeId)}
337 />
338 ) : (
339 <div className="flex flex-1 items-center justify-center text-gray-500">
340 Loading…
341 </div>
342 )}
343 </main>
344 </div>
345 )
346}
347
348// ---------------------------------------------------------------------------
349// Chat panel — one ChatClient per thread, hydrated from + saved to the adapter.
350// Remounted via `key={threadId}` on the parent so switching threads is a clean
351// swap; useChat then hydrates the newly-keyed thread's history. Reasoning
352// (`thinking`) and `tool-call` parts live on the persisted UIMessage, so they
353// are restored on reload / thread-switch alongside the text. Hardcoded to
354// OpenRouter GPT-5.1 because the /api/tanchat endpoint enables a reasoning
355// summary for the openrouter provider, so reasoning parts actually stream.
356// ---------------------------------------------------------------------------
357
358const CHAT_BODY = { provider: 'openrouter', model: 'openai/gpt-5.1' } as const
359
360const REHYPE_PLUGINS = [rehypeRaw, rehypeSanitize, rehypeHighlight]
361const REMARK_PLUGINS = [remarkGfm]
362
363/** Render a single UIMessage part: reasoning, text, or guitar card. Approval
364 * prompts are surfaced separately from the `interrupts` array (see ThreadChat). */
365function MessagePart({
366 part,
367 index,
368 message,
369}: {
370 part: UIMessage['parts'][number]
371 index: number
372 message: UIMessage
373}) {
374 if (part.type === 'thinking') {
375 // "Complete" once any text part follows it in the same message.
376 const isComplete = message.parts
377 .slice(index + 1)
378 .some((p) => p.type === 'text')
379 return (
380 <ThinkingPart
381 content={part.content}
382 isComplete={isComplete}
383 className="rounded-lg border border-gray-700/50 bg-gray-800/50 p-4"
384 />
385 )
386 }
387
388 if (part.type === 'text' && part.content) {
389 return (
390 <div className="prose prose-invert max-w-none text-white">
391 <ReactMarkdown
392 rehypePlugins={REHYPE_PLUGINS}
393 remarkPlugins={REMARK_PLUGINS}
394 >
395 {part.content}
396 </ReactMarkdown>
397 </div>
398 )
399 }
400
401 if (
402 part.type === 'tool-call' &&
403 part.name === 'recommendGuitar' &&
404 part.output
405 ) {
406 return <GuitarRecommendation id={part.output.id} />
407 }
408
409 return null
410}
411
412function ThreadChat({
413 threadId,
414 onFirstMessage,
415 onActivity,
416}: {
417 threadId: string
418 onFirstMessage: (text: string) => void
419 onActivity: () => void
420}) {
421 const {
422 messages,
423 sendMessage,
424 isLoading,
425 error,
426 interrupts,
427 resuming,
428 stop,
429 } = useChat<typeof tools>({
430 threadId,
431 connection: fetchServerSentEvents('/api/tanchat'),
432 persistence: threadPersistence,
433 tools,
434 forwardedProps: CHAT_BODY,
435 onFinish: () => onActivity(),
436 })
437 const [input, setInput] = useState('')
438
439 const handleSubmit = (e: React.FormEvent) => {
440 e.preventDefault()
441 const text = input.trim()
442 if (!text || isLoading) return
443 if (messages.length === 0) onFirstMessage(text)
444 onActivity()
445 setInput('')
446 void sendMessage(text)
447 }
448
449 return (
450 <>
451 <div className="flex-1 overflow-y-auto px-4 py-8">
452 <div className="mx-auto max-w-2xl space-y-6">
453 {messages.length === 0 && (
454 <div className="pt-16 text-center text-gray-500">
455 <MessageSquare size={32} className="mx-auto mb-3 text-gray-700" />
456 <p>Send a message to start this chat.</p>
457 <p className="mt-1 text-sm">
458 Try “Recommend me an acoustic guitar” to see reasoning + tool
459 calls — then reload or switch threads and they're restored from
460 localStorage.
461 </p>
462 </div>
463 )}
464 {messages.map((message) => (
465 <div
466 key={message.id}
467 className={
468 message.role === 'user'
469 ? 'flex justify-end'
470 : 'flex justify-start'
471 }
472 >
473 <div
474 className={`min-w-0 max-w-full space-y-2 rounded-2xl px-4 py-3 ${
475 message.role === 'user'
476 ? 'bg-orange-500/20 text-orange-50'
477 : 'bg-gray-800/60 text-gray-100'
478 }`}
479 >
480 <div className="text-xs font-semibold uppercase tracking-wide text-gray-500">
481 {message.role}
482 </div>
483 {message.parts.map((part, index) => (
484 <MessagePart
485 key={`${message.id}-${index}`}
486 part={part}
487 index={index}
488 message={message}
489 />
490 ))}
491 </div>
492 </div>
493 ))}
494 {interrupts.map((interrupt) =>
495 interrupt.kind === 'tool-approval' ? (
496 <div
497 key={interrupt.id}
498 className="rounded-lg border border-yellow-500/20 bg-yellow-500/10 p-4"
499 >
500 <p className="mb-2 font-medium text-white">
501 🔒 Approval required: {interrupt.toolName}
502 </p>
503 <pre className="mb-3 overflow-x-auto rounded bg-gray-800 p-2 text-xs text-gray-300">
504 {JSON.stringify(interrupt.originalArgs, null, 2)}
505 </pre>
506 <div className="flex gap-2">
507 <button
508 onClick={() => interrupt.resolveInterrupt(true)}
509 disabled={!interrupt.canResolve || resuming}
510 className="rounded-lg bg-green-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-green-700 disabled:opacity-50"
511 >
512 ✓ Approve
513 </button>
514 <button
515 onClick={() => interrupt.resolveInterrupt(false)}
516 disabled={!interrupt.canResolve || resuming}
517 className="rounded-lg bg-red-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-red-700 disabled:opacity-50"
518 >
519 ✗ Deny
520 </button>
521 </div>
522 </div>
523 ) : null,
524 )}
525 {error && (
526 <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-2 text-sm text-red-300">
527 {error.message}
528 </div>
529 )}
530 </div>
531 </div>
532
533 <div className="border-t border-gray-800 bg-gray-900/80 px-4 py-3 backdrop-blur-sm">
534 <form onSubmit={handleSubmit} className="mx-auto flex max-w-2xl gap-2">
535 <input
536 value={input}
537 onChange={(e) => setInput(e.target.value)}
538 placeholder="Try “Recommend me an acoustic guitar”…"
539 className="flex-1 rounded-lg border border-gray-700 bg-gray-800 px-4 py-2 text-white placeholder-gray-500 focus:border-orange-500/50 focus:outline-none"
540 />
541 {isLoading ? (
542 <button
543 type="button"
544 onClick={() => void stop()}
545 className="flex items-center gap-2 rounded-lg bg-gray-700 px-5 py-2 font-medium text-white transition-colors hover:bg-gray-600"
546 >
547 <Square size={16} />
548 Stop
549 </button>
550 ) : (
551 <button
552 type="submit"
553 className="rounded-lg bg-orange-500 px-5 py-2 font-medium text-white transition-colors hover:bg-orange-600 disabled:cursor-not-allowed disabled:opacity-50"
554 >
555 Send
556 </button>
557 )}
558 </form>
559 </div>
560 </>
561 )
562}