Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { useEffect, useMemo, useRef, useState } from 'react'
3import { fetchServerSentEvents } from '@tanstack/ai-client'
4import { useChat } from '@tanstack/ai-react'
5
6export const Route = createFileRoute('/durable-persistence')({
7 component: DurablePersistencePage,
8})
9
10/**
11 * A fetch that reports how many text chunks each network read of an SSE
12 * response carries. It counts before the client parses anything, so the
13 * numbers show what the server sent and when, not when React rendered it.
14 */
15function countingFetch(onRead: (textChunks: number) => void): typeof fetch {
16 return async (input, init) => {
17 const response = await fetch(input, init)
18 const isSse = response.headers
19 .get('content-type')
20 ?.includes('text/event-stream')
21 if (!response.body || !isSse) return response
22 const decoder = new TextDecoder()
23 let pending = ''
24 const counted = response.body.pipeThrough(
25 new TransformStream<Uint8Array, Uint8Array>({
26 transform(bytes, controller) {
27 pending += decoder.decode(bytes, { stream: true })
28 const events = pending.split('\n\n')
29 pending = events.pop() ?? ''
30 const textChunks = events.filter((event) =>
31 event.includes('"type":"TEXT_MESSAGE_CONTENT"'),
32 ).length
33 if (textChunks > 0) onRead(textChunks)
34 controller.enqueue(bytes)
35 },
36 }),
37 )
38 return new Response(counted, {
39 status: response.status,
40 statusText: response.statusText,
41 headers: response.headers,
42 })
43 }
44}
45
46// The thread id lives in localStorage, so a reload opens the same thread. The
47// transcript itself lives on the server.
48const THREAD_KEY = 'durable-persistence:thread'
49
50function newThreadId(): string {
51 const id = `thread-${crypto.randomUUID()}`
52 window.localStorage.setItem(THREAD_KEY, id)
53 return id
54}
55
56function DurablePersistencePage() {
57 // Read on the client only: the server render has no localStorage.
58 const [threadId, setThreadId] = useState<string | null>(null)
59 useEffect(() => {
60 setThreadId(window.localStorage.getItem(THREAD_KEY) ?? newThreadId())
61 }, [])
62
63 return (
64 <div style={page}>
65 <h1>Durable persistence</h1>
66 <p style={{ color: '#555' }}>
67 <code>persistence: true</code> on the client. The server POST is the
68 persistence guide's POST plus{' '}
69 <code>durability: {'{ adapter: memoryStream(request) }'}</code>. Send a
70 long prompt and watch the counter. Reload while it streams: the reply
71 continues where it was. After a reload, the part you missed arrives as
72 one step, then the rest streams.
73 </p>
74 <button
75 type="button"
76 onClick={() => setThreadId(newThreadId())}
77 style={{ marginBottom: 12 }}
78 >
79 New thread
80 </button>
81 {threadId ? <ChatPane key={threadId} threadId={threadId} /> : null}
82 </div>
83 )
84}
85
86interface ChunkStats {
87 chunks: number
88 steps: number
89 biggestStep: number
90}
91
92const NO_STATS: ChunkStats = { chunks: 0, steps: 0, biggestStep: 0 }
93
94function ChatPane({ threadId }: { threadId: string }) {
95 const [oldBatching, setOldBatching] = useState(false)
96 const [slowModel, setSlowModel] = useState(true)
97 const [stats, setStats] = useState<ChunkStats>(NO_STATS)
98 // Network reads within 5ms of each other count as one step on screen.
99 const tracker = useRef({ lastAt: 0, currentStep: 0 })
100
101 const connection = useMemo(
102 () =>
103 fetchServerSentEvents('/api/durable-persistence', {
104 fetchClient: countingFetch((textChunks) => {
105 const now = performance.now()
106 const t = tracker.current
107 const newStep = now - t.lastAt > 5
108 t.currentStep = (newStep ? 0 : t.currentStep) + textChunks
109 t.lastAt = now
110 const step = t.currentStep
111 setStats((s) => ({
112 chunks: s.chunks + textChunks,
113 steps: s.steps + (newStep ? 1 : 0),
114 biggestStep: Math.max(s.biggestStep, step),
115 }))
116 }),
117 }),
118 [],
119 )
120
121 const { messages, sendMessage, isLoading, connectionStatus } = useChat({
122 threadId,
123 connection,
124 persistence: true,
125 forwardedProps: { oldBatching, slowModel },
126 })
127 const [input, setInput] = useState(
128 'Write a 700-word story about a lighthouse keeper.',
129 )
130
131 const handleSubmit = (e: React.FormEvent) => {
132 e.preventDefault()
133 const text = input.trim()
134 if (!text || isLoading) return
135 setInput('')
136 setStats(NO_STATS)
137 tracker.current = { lastAt: 0, currentStep: 0 }
138 void sendMessage(text)
139 }
140
141 return (
142 <>
143 <label style={{ display: 'block', margin: '8px 0' }}>
144 <input
145 type="checkbox"
146 checked={oldBatching}
147 onChange={(e) => setOldBatching(e.target.checked)}
148 />{' '}
149 Old batching (no <code>batchWaitMs</code>, how <code>main</code>{' '}
150 behaves)
151 </label>
152 <label style={{ display: 'block', margin: '8px 0' }}>
153 <input
154 type="checkbox"
155 checked={slowModel}
156 onChange={(e) => setSlowModel(e.target.checked)}
157 />{' '}
158 Slow model (30ms between text chunks, so the batching is easy to see)
159 </label>
160 <div style={{ margin: '12px 0', color: '#888', fontSize: 13 }}>
161 thread: <code>{threadId}</code> | connection:{' '}
162 <code>{connectionStatus}</code>
163 <br />
164 text chunks: <strong>{stats.chunks}</strong> | arrived in{' '}
165 <strong>{stats.steps}</strong> steps | biggest step:{' '}
166 <strong>{stats.biggestStep}</strong> chunks
167 </div>
168
169 <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
170 {messages.map((message) => (
171 <div
172 key={message.id}
173 style={message.role === 'user' ? userBubble : assistantBubble}
174 >
175 <div style={roleLabel}>{message.role}</div>
176 {message.parts.map((part, index) =>
177 part.type === 'text' && part.content ? (
178 <p
179 key={`${message.id}-${index}`}
180 style={{ margin: 0, whiteSpace: 'pre-wrap' }}
181 >
182 {part.content}
183 </p>
184 ) : null,
185 )}
186 </div>
187 ))}
188 </div>
189
190 <form
191 onSubmit={handleSubmit}
192 style={{ marginTop: 16, display: 'flex', gap: 8 }}
193 >
194 <input
195 value={input}
196 onChange={(e) => setInput(e.target.value)}
197 placeholder="Ask something..."
198 style={{ flex: 1, padding: 8 }}
199 />
200 <button type="submit" disabled={isLoading}>
201 {isLoading ? 'Streaming...' : 'Send'}
202 </button>
203 </form>
204 </>
205 )
206}
207
208const page: React.CSSProperties = {
209 maxWidth: 720,
210 margin: '0 auto',
211 padding: 24,
212 fontFamily: 'system-ui, sans-serif',
213}
214
215const bubble: React.CSSProperties = {
216 borderRadius: 8,
217 padding: '10px 14px',
218 maxWidth: '85%',
219}
220
221const userBubble: React.CSSProperties = {
222 ...bubble,
223 alignSelf: 'flex-end',
224 background: '#eef2ff',
225}
226
227const assistantBubble: React.CSSProperties = {
228 ...bubble,
229 alignSelf: 'flex-start',
230 background: '#f6f6f6',
231}
232
233const roleLabel: React.CSSProperties = {
234 fontSize: 11,
235 textTransform: 'uppercase',
236 letterSpacing: '0.05em',
237 color: '#999',
238 marginBottom: 4,
239}