Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

subagents-persisted.md

369 lines14.7 KB

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