Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { z } from 'zod'
3import {
4 EventType,
5 chat,
6 chatParamsFromRequestBody,
7 maxIterations,
8 memoryStream,
9 resumeServerSentEventsResponse,
10 toolDefinition,
11} from '@tanstack/ai'
12import { openaiText } from '@tanstack/ai-openai'
13import { reconstructChat, withPersistence } from '@tanstack/ai-persistence'
14import type { StreamChunk } from '@tanstack/ai'
15import { persistentChatPersistence } from '../lib/persistent-chat-store'
16import { sendEmailTool } from '../lib/persistent-chat-tools'
17
18const persistence = persistentChatPersistence()
19
20// Delivery-layer producer dedup: run ids whose detached producer is currently
21// pumping the memoryStream log. Prevents a duplicate POST (client retry, React
22// strict-mode double render) from starting a second model call / double-writing
23// the same log. Process-local, like the `memoryStream` log it guards — NOT the
24// source of truth for "is this thread active" (that is the persistence runs
25// store, resolved by `reconstructChat` via `findActiveRun(threadId)`).
26const activeProducers = new Set<string>()
27
28// Two server-executed tools so the demo exercises the agent loop AND tool-call
29// persistence: the assistant's tool calls and their results are written to the
30// stored transcript, so a reload rehydrates them too — not just plain text.
31
32const WEATHER = {
33 sunny: { emoji: '☀️', tempC: 24 },
34 cloudy: { emoji: '☁️', tempC: 17 },
35 rainy: { emoji: '🌧️', tempC: 12 },
36} as const
37const CONDITIONS = Object.keys(WEATHER) as Array<keyof typeof WEATHER>
38
39const getWeather = toolDefinition({
40 name: 'getWeather',
41 description: 'Get the current weather for a city.',
42 inputSchema: z.object({ city: z.string().describe('City name') }),
43 outputSchema: z.object({
44 city: z.string(),
45 condition: z.string(),
46 emoji: z.string(),
47 tempC: z.number(),
48 }),
49}).server(({ city }) => {
50 // Deterministic mock: pick a condition from the city name so a given city
51 // always reports the same weather (no external API needed for the demo).
52 const seed = [...city].reduce((sum, char) => sum + char.charCodeAt(0), 0)
53 const condition = CONDITIONS[seed % CONDITIONS.length]!
54 return { city, condition, ...WEATHER[condition] }
55})
56
57const rollDice = toolDefinition({
58 name: 'rollDice',
59 description: 'Roll one or more dice and return the results.',
60 inputSchema: z.object({
61 sides: z.number().int().min(2).max(100).default(6),
62 count: z.number().int().min(1).max(10).default(1),
63 }),
64 outputSchema: z.object({
65 rolls: z.array(z.number()),
66 total: z.number(),
67 }),
68}).server(({ sides = 6, count = 1 }) => {
69 const rolls = Array.from(
70 { length: count },
71 () => Math.floor(Math.random() * sides) + 1,
72 )
73 return { rolls, total: rolls.reduce((sum, roll) => sum + roll, 0) }
74})
75
76// A human-in-the-loop tool. The DEFINITION is shared with the client (see
77// `../lib/persistent-chat-tools`); here we attach the server implementation.
78// `needsApproval` pauses the run on an interrupt before the tool runs; the
79// interrupt is persisted by `withPersistence` and survives a reload — approve or
80// reject after refreshing and the run resumes from exactly where it paused.
81const sendEmail = sendEmailTool.server(({ to }) => {
82 // Demo: no real email is sent — the approval pause is the point.
83 return {
84 messageId: `msg-${Math.random().toString(36).slice(2, 10)}`,
85 to,
86 }
87})
88
89const SYSTEM_PROMPT =
90 'You are a concise, friendly assistant. When the user asks about the ' +
91 'weather or to roll dice, use the getWeather / rollDice tools. When the user ' +
92 'asks to send an email, use the sendEmail tool (it pauses for their ' +
93 'approval). Use tools rather than guessing, then summarize the result in a ' +
94 'sentence.'
95
96/**
97 * Start the model run **detached from the HTTP connection** and let it run to
98 * completion into the delivery log, regardless of whether the requesting client
99 * stays connected. This is the "don't abort on disconnect, because it's
100 * persisted" policy: because `withPersistence` writes the transcript on finish,
101 * it's safe to keep generating after a reload — the result is captured either
102 * way (the loader rehydrates it, and a rejoining client tails the same log).
103 *
104 * Contrast the plain resumable route (`/api/resumable`), which ties the run to
105 * the request's `abortController`: with no persistence, continuing after a
106 * disconnect would just burn tokens no one reads, so it aborts.
107 */
108type ChatParams = Awaited<ReturnType<typeof chatParamsFromRequestBody>>
109
110function startDetachedRun(
111 runId: string,
112 threadId: string,
113 messages: ChatParams['messages'],
114 // Present on the follow-up request after the user answers an interrupt: the
115 // parent (interrupted) run and the approval/rejection batch. Forwarded to
116 // chat() so it rebuilds the paused tool call and continues.
117 resume?: ChatParams['resume'],
118 parentRunId?: string,
119): void {
120 if (activeProducers.has(runId)) return
121 activeProducers.add(runId)
122
123 // Producer-mode durability handle, keyed by runId via the X-Run-Id header.
124 const sink = memoryStream(
125 new Request('http://persistent-chat.internal/', {
126 headers: { 'X-Run-Id': runId },
127 }),
128 )
129
130 const stream = chat({
131 adapter: openaiText('gpt-5.5'),
132 // Reasoning on, effort "low" so it stays fast. `summary: 'auto'` asks OpenAI
133 // for a readable reasoning summary; when returned it streams as REASONING
134 // events, is persisted, and reconstructs like text/tool calls (the pane
135 // renders it as a "reasoning" block). NOTE: OpenAI only returns reasoning
136 // summary text to organizations verified for it — unverified keys still
137 // reason (you see reasoning tokens in usage) but get no summary to display.
138 modelOptions: { reasoning: { effort: 'low', summary: 'auto' } },
139 // Snapshot streaming on: even the partial reply is persisted, so a reload
140 // mid-generation (or a crash) still shows the story-so-far, and the detached
141 // run below finishes and persists the rest.
142 middleware: [withPersistence(persistence, { snapshotStreaming: true })],
143 agentLoopStrategy: maxIterations(10),
144 systemPrompts: [SYSTEM_PROMPT],
145 tools: [getWeather, rollDice, sendEmail],
146 messages,
147 threadId,
148 runId,
149 ...(parentRunId ? { parentRunId } : {}),
150 ...(resume ? { resume } : {}),
151 // No client abortController: the run owns its own lifetime.
152 })
153
154 void (async () => {
155 try {
156 for await (const chunk of stream) {
157 await sink.append([chunk])
158 }
159 } catch (error) {
160 // The run threw before emitting a terminal chunk (withPersistence.onError
161 // already recorded the failure). Append a RUN_ERROR so log readers unblock
162 // instead of waiting on a stream that will never finish.
163 await sink.append([
164 {
165 type: EventType.RUN_ERROR,
166 message: error instanceof Error ? error.message : String(error),
167 timestamp: Date.now(),
168 } as StreamChunk,
169 ])
170 } finally {
171 await sink.close()
172 activeProducers.delete(runId)
173 }
174 })()
175}
176
177/**
178 * Persistent-chat demo endpoint.
179 *
180 * Three kinds of durability stack here:
181 *
182 * 1. STATE — `withPersistence` writes the thread transcript (including the
183 * pending user turn at start and throttled streaming snapshots), run records,
184 * and interrupt state to SQLite. Survives a server restart.
185 *
186 * 2. DELIVERY — the `memoryStream` log records each chunk so a reconnecting or
187 * rejoining client replays without re-running the model. Swap it for
188 * `durableStream(request, { server })` from `@tanstack/ai-durable-stream` in
189 * production (memoryStream is process-local).
190 *
191 * 3. RUN LIFETIME — the run is detached from the HTTP request (see
192 * `startDetachedRun`), so a mid-stream reload does not abort it. It finishes,
193 * persists, and the reload rehydrates the full conversation.
194 *
195 * The client runs server-authoritative (`persistence: true`) and keeps no
196 * messages, and no run pointer, of its own. On mount `useChat`
197 * hits this GET itself (keyed by threadId) and `reconstructChat` returns the
198 * transcript plus a cursor to any in-flight run, which the client then tails via
199 * the delivery replay branch below. No loader, no client hydration code.
200 */
201
202export const Route = createFileRoute('/api/persistent-chat')({
203 server: {
204 handlers: {
205 POST: async ({ request }) => {
206 const params = await chatParamsFromRequestBody(await request.json())
207
208 // Kick off (or attach to) the detached run, then stream it to THIS
209 // client by tailing the delivery log from the start. Cancelling this
210 // response (a reload) cancels only the reader — never the producer.
211 // `resume`/`parentRunId` are set on the follow-up after an interrupt is
212 // answered, so the paused tool call continues.
213 startDetachedRun(
214 params.runId,
215 params.threadId,
216 params.messages,
217 params.resume,
218 params.parentRunId,
219 )
220
221 // This reader genuinely races the producer it just started, so give it a
222 // generous first-chunk deadline (the default is tuned short for reload
223 // rejoins, where the producer ran in a prior request and an empty log
224 // means "gone").
225 const reader = memoryStream(
226 new Request(
227 `http://persistent-chat.internal/?offset=-1&runId=${encodeURIComponent(params.runId)}`,
228 ),
229 { firstChunkDeadlineMs: 10_000 },
230 )
231 return resumeServerSentEventsResponse({ adapter: reader })
232 },
233
234 // GET serves two independent jobs off one route:
235 //
236 // 1. Delivery replay — re-attach to an in-flight run off the ephemeral,
237 // per-run durability log. The run id rides the `X-Run-Id` header (or
238 // `?runId`) and the resume offset the `Last-Event-ID` header (or
239 // `?offset`), so ask the adapter via `resumeFrom()` rather than
240 // sniffing query params.
241 // 2. History hydration — read the DURABLE thread transcript from the
242 // persistence store. This is what a server-authoritative client
243 // (`persistence: true`) fetches on reload, since the delivery log only
244 // holds one run, never prior turns.
245 GET: ({ request }) => {
246 // `memoryStream` fails a from-start join to a gone/empty run fast (its
247 // ~100ms default first-chunk deadline), so an unresumable reload frees
248 // the input near-instantly instead of hanging. Raise
249 // `firstChunkDeadlineMs` here if your producer can start well after a
250 // joiner attaches.
251 const durability = memoryStream(request)
252 if (durability.resumeFrom() !== null) {
253 return resumeServerSentEventsResponse({ adapter: durability })
254 }
255 // Demo only: single shared thread, no multi-user auth. Production routes
256 // must authorize ownership (session → allowed thread ids) before load —
257 // without `authorize`, any caller who knows `?threadId=` gets the full
258 // transcript.
259 return reconstructChat(persistence, request, {
260 authorize: async (threadId) => {
261 // e.g. return (await getSessionUser())?.canAccess(threadId) ?? false
262 return threadId.length > 0
263 },
264 })
265 },
266 },
267 },
268})