Open History to see the last commit
1import { useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import {
4 fetchServerSentEvents,
5 localStoragePersistence,
6 useChat,
7} from '@tanstack/ai-react'
8
9/**
10 * Browser-refresh persistence harness (client half).
11 *
12 * A `localStoragePersistence` adapter stores ONE combined `{ messages, resume }`
13 * record per thread, so a full `page.reload()` restores the conversation — and
14 * any pending-interrupt resume snapshot — straight from `localStorage`, with no
15 * server round-trip. The matching provider-free durable endpoint is
16 * `/api/persistence-durability`.
17 *
18 * `?scenario=interrupt` points the connection at the interrupt variant of the
19 * endpoint and uses a distinct threadId, so the two scenarios never share a
20 * storage key.
21 *
22 * `?scenario=server-interrupt` is the SERVER-authoritative counterpart: the
23 * client runs `persistence: true` (caches nothing), so on mount it hydrates from
24 * the endpoint's GET, which returns a pending interrupt. Proves a fresh client
25 * re-prompts the approval from the server, not from `localStorage`.
26 */
27
28// The store the client-authoritative scenarios use. `text`/`interrupt` pass it
29// directly, caching the transcript to localStorage. `server-interrupt` instead
30// runs `persistence: true` (no store), so the server owns the transcript and the
31// client hydrates on mount.
32const store = localStoragePersistence()
33
34const textConnection = fetchServerSentEvents('/api/persistence-durability')
35const interruptConnection = fetchServerSentEvents(
36 '/api/persistence-durability?scenario=interrupt',
37)
38const serverInterruptConnection = fetchServerSentEvents(
39 '/api/persistence-durability?scenario=server-interrupt',
40)
41
42export const Route = createFileRoute('/persistence-durability')({
43 component: PersistenceDurabilityPage,
44 validateSearch: (search: Record<string, unknown>) => ({
45 scenario:
46 search.scenario === 'interrupt'
47 ? ('interrupt' as const)
48 : search.scenario === 'server-interrupt'
49 ? ('server-interrupt' as const)
50 : ('text' as const),
51 }),
52})
53
54function PersistenceDurabilityPage() {
55 const { scenario } = Route.useSearch()
56 const [interruptSource, setInterruptSource] = useState<
57 'hydrate' | 'live' | null
58 >(null)
59 const isInterrupt = scenario === 'interrupt'
60 const isServerInterrupt = scenario === 'server-interrupt'
61 const chatId = isServerInterrupt
62 ? 'persistence-durability-server-interrupt'
63 : isInterrupt
64 ? 'persistence-durability-interrupt'
65 : 'persistence-durability-text'
66
67 const { messages, sendMessage, isLoading, interrupts } = useChat({
68 // The threadId IS the hook's identity and its persistence key, so the
69 // localStorage record lives under `tanstack-ai:<chatId>` and a reload with
70 // the same threadId restores it.
71 threadId: chatId,
72 connection: isServerInterrupt
73 ? serverInterruptConnection
74 : isInterrupt
75 ? interruptConnection
76 : textConnection,
77 persistence: isServerInterrupt ? true : store,
78 onInterruptStateChange: (_state, context) => {
79 setInterruptSource(context.source)
80 },
81 })
82
83 const [input, setInput] = useState('')
84
85 const handleSubmit = () => {
86 const text = input.trim()
87 if (!text) return
88 setInput('')
89 void sendMessage(text)
90 }
91
92 return (
93 <div data-testid="persistence-durability-page" style={{ padding: 16 }}>
94 <div
95 data-testid="interrupt-count"
96 data-count={String(interrupts.length)}
97 hidden
98 />
99 <div
100 data-testid="message-count"
101 data-count={String(messages.length)}
102 hidden
103 />
104 <div data-testid="interrupt-source" hidden>
105 {interruptSource}
106 </div>
107
108 <div data-testid="message-list">
109 {messages.map((message) => (
110 <div
111 key={message.id}
112 data-testid={
113 message.role === 'user' ? 'user-message' : 'assistant-message'
114 }
115 >
116 {message.parts.map((part, index) =>
117 part.type === 'text' ? (
118 <span key={`${message.id}-${index}`} data-testid="text-part">
119 {part.content}
120 </span>
121 ) : null,
122 )}
123 </div>
124 ))}
125 </div>
126
127 {interrupts.map((interrupt) => (
128 <div key={interrupt.id} data-testid={`interrupt-${interrupt.id}`}>
129 <span data-testid="interrupt-kind">{interrupt.kind}</span>
130 <span data-testid="interrupt-message">
131 {interrupt.message ?? interrupt.reason}
132 </span>
133 <span
134 data-testid="interrupt-can-resolve"
135 data-can-resolve={String(interrupt.canResolve)}
136 >
137 {String(interrupt.canResolve)}
138 </span>
139 </div>
140 ))}
141
142 {isLoading && <div data-testid="loading-indicator">Generating...</div>}
143
144 <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
145 <input
146 data-testid="chat-input"
147 type="text"
148 value={input}
149 onChange={(e) => setInput(e.target.value)}
150 onKeyDown={(e) => {
151 if (e.key === 'Enter' && !e.shiftKey) {
152 e.preventDefault()
153 handleSubmit()
154 }
155 }}
156 placeholder="Type a message..."
157 />
158 <button
159 data-testid="send-button"
160 onClick={handleSubmit}
161 disabled={!input.trim()}
162 >
163 Send
164 </button>
165 </div>
166 </div>
167 )
168}