Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

threads.tsx

557 lines19.1 KB

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