Open History to see the last commit
1---
2title: Persisted subagents
3id: subagents-persisted
4order: 6
5description: "Keep the blog desk after a refresh. The agent cards come back, and a run that is still in progress continues."
6---
7
8This tutorial saves the subagent thread on the server. A refresh shows the cards again, and an in-progress run continues.
9
10Save the thread on the server. Then a refresh shows the cards again, and a run that is still in progress continues in the same card. Finish the Subagents tutorial first. This page takes about 20 minutes.
11
12> [!NOTE]
13> In this tutorial, the saved chat lives in the memory of the dev server process. If you restart that process, the chat is gone. A database that saves the same fields keeps the chat.
14
15## 1. Install the persistence package
16
17You already have `@tanstack/ai` and `@tanstack/ai-react`. Add the store package:
18
19<!-- ::start:tabs variant="package-manager" mode="install" -->
20
21react: @tanstack/ai-persistence
22
23<!-- ::end:tabs -->
24
25## 2. Keep one thread id
26
27Create `src/lib/thread.ts`:
28
29```typescript
30export const THREAD_ID = 'blog-desk'
31```
32
33Use this id on the client and on the server. A new id on each load starts an empty chat.
34
35> [!WARNING]
36> This example has no login, so every visitor shares the `blog-desk` thread. In a real app, make sure that the caller owns the thread before POST or GET reads or writes it.
37
38## 3. Tell the hook that the server owns the chat
39
40In `src/chat-ui.tsx`, replace `chatOptions` with this object. Keep the rest of the file. Step 7 changes the researcher card.
41
42```tsx ignore
43import { fetchServerSentEvents } from '@tanstack/ai-react'
44import { blogAgents } from '@/lib/blog-agents'
45import { byok } from '@/lib/byok'
46
47export const chatOptions = {
48 connection: fetchServerSentEvents('/api/chat'),
49 byok,
50 persistence: true,
51 subagents: blogAgents,
52}
53```
54
55In `src/routes/index.tsx`, pass `THREAD_ID` to `useAppChat()`:
56
57```tsx ignore
58import { createFileRoute } from '@tanstack/react-router'
59import { useAppChat } from '@/chat-ui'
60import { THREAD_ID } from '@/lib/thread'
61
62function ChatPage() {
63 const chat = useAppChat({ threadId: THREAD_ID })
64 return <chat.AppChat />
65}
66
67export const Route = createFileRoute('/')({
68 component: ChatPage,
69})
70```
71
72In the layout, change the heading to `Saved blog desk`. Under the heading, add two sentences: "A refresh keeps this chat. A refresh during a run continues the stream."
73
74## 4. Replace the chat route
75
76Replace `src/routes/api.chat.ts` with this file. It is the full route from the example.
77
78```ts ignore
79import { createFileRoute } from '@tanstack/react-router'
80import {
81 chat,
82 chatParamsFromRequest,
83 decide,
84 memoryStream,
85 resumeServerSentEventsResponse,
86 subagentRoute,
87 toServerSentEventsResponse,
88} from '@tanstack/ai'
89import {
90 memoryPersistence,
91 reconstructChat,
92 withPersistence,
93} from '@tanstack/ai-persistence'
94import {
95 createOpenRouterDecider,
96 createOpenRouterText,
97} from '@tanstack/ai-openrouter'
98import { openrouterByok } from '@tanstack/ai-openrouter/byok'
99import { byokMissing, getByokKey } from '@tanstack/ai/byok/server'
100import { createBlogAgents } from '@/lib/agents'
101
102const FIRST_CHUNK_MS = 30_000
103
104const persistence = memoryPersistence()
105
106export const Route = createFileRoute('/api/chat')({
107 server: {
108 handlers: {
109 POST: async ({ request }) => {
110 const params = await chatParamsFromRequest(request)
111 const apiKey = getByokKey(request, openrouterByok.id)
112 if (!apiKey) return byokMissing(openrouterByok)
113 const agents = createBlogAgents(apiKey)
114 const stream = chat({
115 adapter: createOpenRouterText('openai/gpt-5.5', apiKey),
116 messages: params.messages,
117 threadId: params.threadId,
118 runId: params.runId,
119 middleware: [withPersistence(persistence)],
120 ...(params.parentRunId !== undefined
121 ? { parentRunId: params.parentRunId }
122 : {}),
123 ...(params.resume !== undefined ? { resume: params.resume } : {}),
124 subagents: {
125 agents,
126 strategy: 'exclusive',
127 router: async ({ messages, agents: routed, abortSignal }) => {
128 const state = messages.at(-1)
129 if (state === undefined) return 'main'
130 const route = subagentRoute(routed, { then: ['writer'] })
131 const result = await decide({
132 adapter: createOpenRouterDecider(
133 '~typesafe/jev-latest',
134 apiKey,
135 ),
136 state,
137 questions: route.questions,
138 abortSignal,
139 })
140 return route.pick(result)
141 },
142 },
143 })
144 return toServerSentEventsResponse(stream, {
145 durability: { adapter: memoryStream(request) },
146 })
147 },
148 GET: ({ request }) => {
149 const durability = memoryStream(request, {
150 firstChunkDeadlineMs: FIRST_CHUNK_MS,
151 })
152 if (durability.resumeFrom() !== null) {
153 return resumeServerSentEventsResponse({ adapter: durability })
154 }
155 return reconstructChat(persistence, request)
156 },
157 },
158 },
159})
160```
161
162One `memoryPersistence()` at module level is the store for every request:
163
164- `POST` starts a run and saves it.
165- `GET` replays a live run, or rebuilds the saved thread.
166
167At this point, a refresh keeps the cards. The next steps give the researcher more to restore than text.
168
169## 5. Give the researcher a tool
170
171In `src/lib/blog-agents.ts`, import `toolDefinition` from `@tanstack/ai`. Define the tool, then add it to the `tools` of the researcher:
172
173```ts ignore
174export const lookupWikipedia = toolDefinition({
175 name: 'lookupWikipedia',
176 description:
177 'Get the Wikipedia summary of one topic. Pass a short page title, for example "Octopus".',
178 inputSchema: {
179 type: 'object',
180 properties: { title: { type: 'string' } },
181 required: ['title'],
182 },
183})
184
185export const researcher = {
186 name: 'researcher',
187 description:
188 'Does this turn need facts or sources? Answer yes when the user asks to look something up, even if they also ask for a draft or for SEO. Answer no when they do not ask to look anything up.',
189 tools: [lookupWikipedia],
190} as const
191```
192
193The definition holds no server code, so the browser reads it too. It gives types to the tool calls of the researcher in the UI.
194
195## 6. Run the tool on the server
196
197In `src/lib/agents.ts`, import `lookupWikipedia`. Add the server side of the tool above `createBlogAgents`:
198
199```ts ignore
200const lookupWikipediaTool = lookupWikipedia.server(async (input) => {
201 const title =
202 typeof input === 'object' &&
203 input !== null &&
204 'title' in input &&
205 typeof input.title === 'string'
206 ? input.title
207 : ''
208 if (title.length === 0) {
209 throw new Error('lookupWikipedia needs a page title')
210 }
211 const response = await fetch(
212 `https://en.wikipedia.org/api/rest_v1/page/summary/${encodeURIComponent(title)}`,
213 { headers: { 'user-agent': 'tanstack-ai-subagents-persisted-example' } },
214 )
215 if (response.status === 404) return { title, found: false }
216 if (!response.ok) {
217 throw new Error(`Wikipedia returned ${response.status} for ${title}`)
218 }
219 const page: unknown = await response.json()
220 const extract =
221 typeof page === 'object' &&
222 page !== null &&
223 'extract' in page &&
224 typeof page.extract === 'string'
225 ? page.extract
226 : ''
227 if (extract.length === 0) return { title, found: false }
228 return {
229 title,
230 found: true,
231 extract,
232 url: `https://en.wikipedia.org/wiki/${encodeURIComponent(title)}`,
233 }
234})
235```
236
237A 404, or a page with no summary, returns `{ found: false }`. Any other HTTP status throws, so the card shows the error.
238
239In the researcher `chat()` call, add the tool and turn on reasoning. Keep `subagentRunId: ctx.subagentRunId` on each child `chat()`. Replace the system prompt so the model uses the tool:
240
241```ts ignore
242reasoning: 'medium',
243tools: [lookupWikipediaTool],
244systemPrompts: [
245 'You research for a blog desk. Call lookupWikipedia once for each topic before you reply. Then reply in Markdown with short notes, and give the Wikipedia URL as the source. Use a list. Do not write the full post.',
246],
247```
248
249## 7. Show the reasoning and the tool row
250
251In `src/chat-ui.tsx`, import `ThinkingPart` from `@tanstack/ai-react/ui`. Add a `thinking` entry to `partsComponents`:
252
253```tsx ignore
254thinking: ({ part }) => (
255 <ThinkingPart
256 content={part.content}
257 className="mb-2 rounded border border-gray-700 bg-gray-800/60 p-2 text-xs text-gray-400"
258 />
259),
260```
261
262In `src/components/subagent-card.tsx`, import the `SubagentPartsProps` type from `@tanstack/ai-react/ui`. Add the tool widget above the cards:
263
264```tsx ignore
265const researcherTools: SubagentPartsProps<
266 BlogChatOptions,
267 'researcher'
268>['toolsComponents'] = {
269 lookupWikipedia: ({ part, result }) => (
270 <details className="mb-2 rounded border border-emerald-500/30 bg-emerald-500/5 p-2 text-xs text-emerald-300">
271 <summary className="cursor-pointer font-mono">
272 lookupWikipedia({part.arguments}) ({part.state})
273 </summary>
274 <pre className="mt-1 whitespace-pre-wrap text-gray-400">
275 {result === undefined
276 ? 'No result yet'
277 : typeof result.content === 'string'
278 ? result.content
279 : JSON.stringify(result.content)}
280 </pre>
281 </details>
282 ),
283}
284```
285
286Replace the researcher card with this function. The notes stay open, so the tool row is visible:
287
288```tsx ignore
289export function Researcher({
290 subagent,
291 Parts,
292}: SubagentProps<BlogChatOptions, 'researcher'>) {
293 return (
294 <section className="mt-3 rounded-lg border border-orange-500/30 bg-gray-900/80 p-3 text-gray-100">
295 <AgentHeader
296 name={subagent.name}
297 status={subagent.status}
298 onStop={subagent.stop}
299 />
300 {subagent.error ? (
301 <p className="text-xs text-red-400">{subagent.error.message}</p>
302 ) : null}
303 <div className="mt-2">
304 <Parts toolsComponents={researcherTools} />
305 </div>
306 </section>
307 )
308}
309```
310
311How `toolsComponents` works on this card:
312
313- The keys come from the `tools` of the researcher. A tool name that the researcher does not have is a type error.
314- The chat UI renders a tool call only through a `toolsComponents` entry with the same name. A tool with no entry renders nothing.
315- The entry is on the researcher card, so only that card uses it. Its text and reasoning still use the root widgets.
316- `result` is the matching tool result, so the result shows inside the same row.
317
318To replace other widgets on one card, see [Style one child's parts](../chat/subagents-advanced#style-one-childs-parts).
319
320## 8. Try it
321
3221. Paste an OpenRouter key. Send `do research on octopuses and seo titles`. Wait until both cards say finished. The research card shows reasoning, a `lookupWikipedia` row, and the notes.
3232. Refresh the page. Both cards are still there. The research card still has its reasoning and its tool row.
3243. Send `Now write the article`. The writer uses the saved notes. Refresh, and all three cards stay.
3254. Send a longer prompt. Refresh while a card says running. The same card continues.
3265. Click Stop while a card says running. Refresh. The same card continues.
327
328<!-- ::client-example library=ai framework=react slug=subagents-persisted -->
329
330Your blog desk now survives a refresh, and a live run continues where it was.
331
332## How it works
333
334`persistence: true` makes the hook load the thread from the server when the page opens:
335
3361. The hook sends `GET ?threadId=blog-desk`.
3372. The response is `{ messages, activeRun }`. The hook shows `messages`.
3383. If `activeRun` is set, the hook joins that run. It sends `GET ?offset=-1&runId=` and plays the log, so the cards continue from that log.
339
340On the server:
341
342- `withPersistence` saves the parent run, each agent run, and each transcript.
343- `toServerSentEventsResponse` writes every chunk to a log. If the browser disconnects, the run continues and the log keeps filling.
344- `reconstructChat` rebuilds the messages and puts one card on the assistant message for each agent run.
345
346`chat.stop()` stops the view in this tab only. The server run continues, and a refresh joins it again.
347
348## Advanced
349
350### What the store keeps
351
352`withPersistence` writes two kinds of rows.
353
354The message store holds the transcript for `blog-desk`. `saveThread` replaces that transcript.
355
356The run store holds one row for each run:
357
358- **The parent row** uses the chat `runId` and the thread id `blog-desk`. `findActiveRun('blog-desk')` returns this run.
359- **A child row** stores the card id from `SUBAGENT_STARTED` as `runId` and as `subagentRunId`. `parentRunId` is the chat run. `name` is `researcher`, `writer`, or `seo`.
360- **The child thread id** is `subagent:` plus that card id. The middleware saves the child transcript on that thread: text, reasoning, tool calls, and tool results.
361
362Inside a child `chat()`:
363
364- `ctx.runId` is the parent run id, a colon, and the card id.
365- `ctx.threadId` is the parent thread id, a colon, and the agent name.
366
367The id of the parent assistant message is `assistant:` plus the parent run id. `metadata.tanstack.runId` is that same id. The saved text is `researcher:` and the notes, then `seo:` and the notes.
368
369`reconstructChat` reads `metadata.tanstack.runId`. It calls `listByParentRun`. It puts one card on the assistant message for each child. The card is the only place that the notes show.
370
371Your own database must save `parentRunId`, `subagentRunId`, and `name`. It must also implement `listByParentRun`, because `reconstructChat` uses that method to build the cards.
372
373### What POST does
374
375`chatParamsFromRequest` reads the body. The body has `messages`, `threadId`, and `runId`. The client also sends the run id in the `X-Run-Id` header. `memoryStream(request)` reads that header and opens the log for this run.
376
377`getByokKey` reads the OpenRouter key from the header that the page sends. The call passes `openrouterByok.id`, so the server does not read `OPENROUTER_API_KEY`. This example has no login. With a server key, any caller can spend that key.
378
379`memoryStorage()` keeps the key in memory only. After a refresh, the cards come back without a key. Paste the key again before you send the next message.
380
381`chat()` receives `middleware: [withPersistence(persistence)]`. On this path, the router runs before the main model. The persistence middleware records the child events:
382
3831. It opens the parent run and saves the messages from the request.
3842. When a child starts, it opens the child run and saves the link fields.
3853. When a child streams, it saves its text, reasoning, and tool calls.
3864. When the turn ends, it marks the parent run and the child runs complete.
387
388`toServerSentEventsResponse` does the delivery:
389
390- It writes a `run.accepted` chunk into the log before it pulls from `chat()`. So a refresh during the router can join.
391- It records every chunk, then sends that chunk to the browser.
392- If the browser disconnects, the helper continues to read `chat()` and writes each chunk into the log. The model continues.
393- When the run ends, it closes the log.
394
395### What GET does
396
397`memoryStream(request)` looks at the URL.
398
399If the URL has a resume offset, `resumeFrom()` is not null, and the request is a join. When the offset is `-1`, `resumeServerSentEventsResponse` replays the log from the start. The hook uses that replay to continue a live run.
400
401If there is no resume offset, the request is a normal load. `reconstructChat(persistence, request)` reads `?threadId=`. It returns the saved messages and `activeRun`.
402
403`activeRun` is the parent run while its status is `running`. After the run is complete, `activeRun` is null. Then the hook shows the cards from `messages`.
404
405### What the next message sends
406
407The hook sends the full thread on the next POST. Each card becomes text in the shape `name:` plus the notes. The system prompt of the writer tells the model to use earlier research text, so the writer receives the saved notes in `messages`.