Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { useEffect, useLayoutEffect, useRef, useState } from 'react'
3import { fetchServerSentEvents } from '@tanstack/ai-client'
4import { useChat } from '@tanstack/ai-react'
5import { sendEmailTool } from '../lib/persistent-chat-tools'
6import './persistent-chat.css'
7
8export const Route = createFileRoute('/persistent-chat')({
9 component: PersistentChatPage,
10})
11
12// One SSE connection serves every thread: useChat keys persistence and the
13// server GET (?threadId) on the thread id, so switching threads reuses it.
14const connection = fetchServerSentEvents('/api/persistent-chat')
15
16// Server-authoritative persistence: the client caches nothing. On mount useChat
17// hydrates a thread from the server by its id (the stored transcript plus a
18// cursor to any run still generating), so switching threads, reloading, or
19// opening a thread on another device all just resume. The server (SQLite) owns
20// every conversation.
21const persistence = true
22
23// Share the tool DEFINITION with the client via an argless `.client()`: the
24// browser gets no implementation (the server runs sendEmail), but it learns the
25// tool's approval shape so it can bind the pending approval interrupt and type
26// it as `tool-approval`. Defined once at module scope so the array identity is
27// stable across renders.
28const chatTools = [sendEmailTool.client()] as const
29
30// The thread INDEX (which threads exist and their titles) is small app state,
31// kept in localStorage. The transcripts themselves live on the server, one per
32// thread id — this list is only how the UI enumerates and labels them.
33const THREADS_KEY = 'persistent-chat:threads'
34
35interface Thread {
36 id: string
37 title: string
38}
39
40function loadThreads(): Array<Thread> {
41 if (typeof window === 'undefined') return []
42 try {
43 const raw = window.localStorage.getItem(THREADS_KEY)
44 const parsed: unknown = raw ? JSON.parse(raw) : null
45 return Array.isArray(parsed) ? (parsed as Array<Thread>) : []
46 } catch {
47 return []
48 }
49}
50
51function newThread(): Thread {
52 return { id: `thread-${crypto.randomUUID()}`, title: 'New chat' }
53}
54
55const SUGGESTIONS = [
56 "What's the weather in Tokyo?",
57 'Roll two 20-sided dice.',
58 'Write a long story about a lighthouse.',
59]
60
61function formatValue(value: unknown): string {
62 if (value === undefined) return ''
63 if (typeof value === 'string') return value
64 return JSON.stringify(value, null, 2)
65}
66
67function PersistentChatPage() {
68 const [threads, setThreads] = useState<Array<Thread>>([])
69 const [activeId, setActiveId] = useState<string | null>(null)
70 const [hydrated, setHydrated] = useState(false)
71
72 // Load the index on the client (localStorage is not available during SSR, so
73 // the first render is empty on both sides — no hydration mismatch). Start a
74 // thread if there are none, so there is always an active conversation.
75 useEffect(() => {
76 const loaded = loadThreads()
77 if (loaded.length === 0) {
78 const first = newThread()
79 setThreads([first])
80 setActiveId(first.id)
81 } else {
82 setThreads(loaded)
83 setActiveId(loaded[0]!.id)
84 }
85 setHydrated(true)
86 }, [])
87
88 useEffect(() => {
89 if (!hydrated) return
90 window.localStorage.setItem(THREADS_KEY, JSON.stringify(threads))
91 }, [threads, hydrated])
92
93 const createThread = () => {
94 const thread = newThread()
95 setThreads((prev) => [thread, ...prev])
96 setActiveId(thread.id)
97 }
98
99 // Name a thread after its first user message so the sidebar is readable.
100 // A no-op (returns the same array) once the thread already has a title, so it
101 // never churns state.
102 const titleFromFirstMessage = (id: string, title: string) => {
103 setThreads((prev) => {
104 const current = prev.find((t) => t.id === id)
105 if (!current || current.title !== 'New chat') return prev
106 return prev.map((t) => (t.id === id ? { ...t, title } : t))
107 })
108 }
109
110 return (
111 <div className="pc-page">
112 <aside className="pc-sidebar">
113 <button type="button" className="pc-new" onClick={createThread}>
114 + New chat
115 </button>
116 <div className="pc-threadlist">
117 {threads.map((thread) => (
118 <button
119 key={thread.id}
120 type="button"
121 className={`pc-threaditem ${thread.id === activeId ? 'active' : ''}`}
122 onClick={() => setActiveId(thread.id)}
123 >
124 {thread.title}
125 </button>
126 ))}
127 </div>
128 </aside>
129
130 <main className="pc-main">
131 {activeId ? (
132 <ChatPane
133 key={activeId}
134 threadId={activeId}
135 onFirstMessage={(text) => titleFromFirstMessage(activeId, text)}
136 />
137 ) : null}
138 </main>
139 </div>
140 )
141}
142
143function ChatPane({
144 threadId,
145 onFirstMessage,
146}: {
147 threadId: string
148 onFirstMessage: (text: string) => void
149}) {
150 // Keyed by threadId in the parent, so a fresh instance mounts per thread and
151 // hydrates that thread from the server. Nothing to wire beyond threadId.
152 const {
153 messages,
154 sendMessage,
155 isLoading,
156 connectionStatus,
157 interrupts,
158 resuming,
159 hasOlderMessages,
160 loadOlderMessages,
161 } = useChat({
162 threadId,
163 connection,
164 persistence,
165 history: { pageSize: 2 },
166 // Share the tool definition so the client can bind the approval interrupt
167 // (verify its schema hashes) and resolve it.
168 tools: chatTools,
169 })
170 const [input, setInput] = useState('')
171 const [olderLoadError, setOlderLoadError] = useState<string | null>(null)
172 const threadRef = useRef<HTMLDivElement>(null)
173 const scrollRestore = useRef<{ height: number; top: number } | null>(null)
174 const lastMessageId = messages.at(-1)?.id
175
176 useEffect(() => {
177 threadRef.current?.scrollTo({ top: threadRef.current.scrollHeight })
178 }, [lastMessageId])
179
180 useLayoutEffect(() => {
181 const restore = scrollRestore.current
182 const el = threadRef.current
183 if (restore === null || !el) return
184 el.scrollTop = el.scrollHeight - restore.height + restore.top
185 scrollRestore.current = null
186 }, [messages])
187
188 useEffect(() => {
189 const firstUser = messages.find((m) => m.role === 'user')
190 const part = firstUser?.parts.find((p) => p.type === 'text' && p.content)
191 if (part && 'content' in part && typeof part.content === 'string') {
192 onFirstMessage(part.content.slice(0, 40))
193 }
194 }, [messages, onFirstMessage])
195
196 const send = (text: string) => {
197 const trimmed = text.trim()
198 if (!trimmed || isLoading) return
199 setInput('')
200 void sendMessage(trimmed)
201 }
202
203 return (
204 <>
205 <div className="pc-header">
206 <h1>Persistent chat</h1>
207 <span className="pc-status">
208 <span className={`pc-dot ${connectionStatus}`} />
209 {connectionStatus}
210 </span>
211 </div>
212
213 <p className="pc-blurb">
214 The server owns every conversation (transcript, runs, interrupts, tool
215 calls) in SQLite via <code>withPersistence</code>. The client caches
216 nothing (<code>persistence: true</code>); on mount <code>useChat</code>{' '}
217 hydrates this thread from the server by its id, no loader, no props.
218 Start a long reply, then switch threads or reload: it resumes exactly
219 where it was.
220 </p>
221
222 <div className="pc-thread" ref={threadRef}>
223 {hasOlderMessages ? (
224 <button
225 type="button"
226 className="pc-chip"
227 onClick={() => {
228 const el = threadRef.current
229 if (el) {
230 scrollRestore.current = {
231 height: el.scrollHeight,
232 top: el.scrollTop,
233 }
234 }
235 setOlderLoadError(null)
236 void loadOlderMessages().catch(() => {
237 scrollRestore.current = null
238 setOlderLoadError('Could not load older messages.')
239 })
240 }}
241 >
242 Load older
243 </button>
244 ) : null}
245 {olderLoadError ? <p className="pc-empty">{olderLoadError}</p> : null}
246 {messages.length === 0 ? (
247 <p className="pc-empty">
248 No messages yet — try a suggestion below, then reload or switch
249 threads to see it resume.
250 </p>
251 ) : (
252 messages.map((message) => (
253 <div key={message.id} className={`pc-row ${message.role}`}>
254 <span className="pc-role">{message.role}</span>
255 {message.parts.map((part, index) => {
256 const key = `${message.id}-${index}`
257 if (part.type === 'thinking' && part.content) {
258 return (
259 <div key={key} className="pc-reasoning">
260 <span className="pc-reasoning-label">reasoning</span>
261 {part.content}
262 </div>
263 )
264 }
265 if (part.type === 'text' && part.content) {
266 return (
267 <div key={key} className="pc-bubble">
268 {part.content}
269 </div>
270 )
271 }
272 if (part.type === 'tool-call') {
273 const args = part.input ?? part.arguments
274 return (
275 <div key={key} className="pc-tool">
276 <div className="pc-tool-head">🔧 {part.name}</div>
277 {formatValue(args) ? (
278 <pre className="pc-tool-io">{formatValue(args)}</pre>
279 ) : null}
280 {part.output !== undefined ? (
281 <pre className="pc-tool-io">
282 {formatValue(part.output)}
283 </pre>
284 ) : (
285 <div className="pc-tool-pending">running…</div>
286 )}
287 </div>
288 )
289 }
290 return null
291 })}
292 </div>
293 ))
294 )}
295 </div>
296
297 {interrupts.map((interrupt) =>
298 interrupt.kind === 'tool-approval' ? (
299 <div key={interrupt.id} className="pc-approval">
300 <div className="pc-approval-head">
301 🔐 Approve <strong>{interrupt.toolName}</strong>?
302 </div>
303 <pre className="pc-tool-io">
304 {formatValue(interrupt.originalArgs)}
305 </pre>
306 <div className="pc-approval-actions">
307 <button
308 type="button"
309 className="pc-approve"
310 disabled={!interrupt.canResolve || resuming}
311 onClick={() => interrupt.resolveInterrupt(true)}
312 >
313 Approve
314 </button>
315 <button
316 type="button"
317 className="pc-reject"
318 disabled={!interrupt.canResolve || resuming}
319 onClick={() => interrupt.resolveInterrupt(false)}
320 >
321 Reject
322 </button>
323 </div>
324 </div>
325 ) : null,
326 )}
327
328 <div className="pc-composer">
329 <div style={{ flex: 1 }}>
330 {messages.length === 0 ? (
331 <div className="pc-suggestions">
332 {SUGGESTIONS.map((suggestion) => (
333 <button
334 key={suggestion}
335 type="button"
336 className="pc-chip"
337 onClick={() => send(suggestion)}
338 >
339 {suggestion}
340 </button>
341 ))}
342 </div>
343 ) : null}
344 <form
345 onSubmit={(e) => {
346 e.preventDefault()
347 send(input)
348 }}
349 style={{ display: 'flex', gap: 10 }}
350 >
351 <input
352 className="pc-input"
353 value={input}
354 onChange={(e) => setInput(e.target.value)}
355 placeholder="Ask about the weather, roll some dice…"
356 />
357 <button className="pc-send" type="submit" disabled={isLoading}>
358 {isLoading ? 'Streaming…' : 'Send'}
359 </button>
360 </form>
361 </div>
362 </div>
363 </>
364 )
365}