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

chat-persistence-advanced.md

268 lines13.1 KB

1---
2title: "Chat Persistence: Advanced"
3id: chat-persistence-advanced
4---
5​
6This page covers the details of `withPersistence` that you need only for special cases. Set up the basics first with [Chat persistence](./chat-persistence).
7​
8## Subagent cards on reload
9​
10When the run store keeps the link from a child run to its parent, a reload shows each subagent as a card.
11​
12Save these three fields on the child run. `createOrResume` writes them on the first insert:
13​
14- `parentRunId`: the chat run that started the child.
15- `subagentRunId`: the child run id.
16- `name`: the agent name.
17​
18`reconstructChat` calls `listByParentRun`. It puts one card on the parent assistant message for each child. Each card gets the full transcript of the child back: text, reasoning, tool calls, and tool results. Nested children come back as nested cards.
19​
20A child that waits for an approval comes back with `status: 'suspended'`, and its interrupt stays pending. The reloaded client can answer it, and the next run continues that child.
21​
22A tool call can start a child. Then the card sits on the message with that tool call. `reconstructChat` finds the parent run with `listByThread`, so implement that method too.
23​
24Put `withPersistence` on the parent `chat()` only. The parent stores the child runs. If a child also has `withPersistence`, it stores the same child a second time, and its interrupt records conflict with the records of the parent.
25​
26Subagent support is optional. If the store has no `listByParentRun`, a reload shows the saved text without the cards. The conformance suite skips the subagent checks, and you do not need a `skipMethods` entry.
27​
28The columns and the method are in the [store reference](./store-reference).
29​
30## AG-UI activity rows on reload
31​
32An AG-UI `ACTIVITY_SNAPSHOT` or `ACTIVITY_DELTA` event shows in the client as a `role: 'activity'` row, for example a search progress card. The `messages` store keeps only model messages, so a reload loses that row. Add an `activities` store to keep it.
33​
341. Give the backend an `activities` store. `memoryPersistence()` already has one. For your own backend, type it with `defineActivityStore`:
35​
36 ```ts
37 import {
38 composePersistence,
39 defineActivityStore,
40 } from '@tanstack/ai-persistence'
41 import type { ActivityRecord } from '@tanstack/ai-persistence'
42 import { persistence as base } from './persistence'
43​
44 const rows = new Map<string, Array<ActivityRecord>>()
45​
46 export const persistence = composePersistence(base, {
47 overrides: {
48 activities: defineActivityStore({
49 loadActivities: async (threadId) => rows.get(threadId) ?? [],
50 // Full overwrite: `list` is the complete activity list for the thread.
51 saveActivities: async (threadId, list) => {
52 rows.set(threadId, list)
53 },
54 }),
55 },
56 })
57 ```
58​
592. Keep your `withPersistence(persistence)` route and your `reconstructChat` `GET` endpoint. They save and restore the rows when `stores.activities` is set.
60​
613. Show the rows in the client. Each row has one part with `type: 'activity'`:
62​
63 ```tsx
64 import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
65​
66 function Chat({ threadId }: { threadId: string }) {
67 const { messages } = useChat({
68 threadId,
69 connection: fetchServerSentEvents('/api/chat'),
70 persistence: true,
71 })
72 return (
73 <div>
74 {messages.map((message) =>
75 message.role === 'activity' ? (
76 <div key={message.id}>
77 {message.parts.map((part, index) =>
78 part.type === 'activity' ? (
79 <pre key={index}>
80 {part.activityType}: {JSON.stringify(part.content)}
81 </pre>
82 ) : null,
83 )}
84 </div>
85 ) : (
86 <div key={message.id}>{message.role}</div>
87 ),
88 )}
89 </div>
90 )
91 }
92 ```
93​
94Some facts about activity rows:
95​
96- The model never gets activity rows as input.
97- A failed activity save does not fail the run.
98- Each `ActivityRecord` keeps the `metadata` of the row.
99​
100## Keep every stored message
101​
102`withPersistence` merges the incoming `messages` into the stored thread by id.
103​
104If `messages` is empty, the middleware loads the stored transcript, and the run continues from there.
105​
106If `messages` is not empty, the middleware merges by id:
107​
108- The last incoming id that is also in the stored thread is a cutoff. Stored messages after it are dropped. That is how a reload removes the old assistant message.
109- If no incoming id is in the stored thread, every stored message stays. This is a new turn.
110- If an id is in both lists, the incoming message wins.
111- New ids and messages with no id go at the end.
112​
113`saveThread` replaces the stored thread with the merged list.
114​
115A client with `history: { pageSize }` posts only the new turn. A reload posts the last user message. A resume posts from that user message through the assistant message on screen. See [Client persistence](./client-persistence).
116​
117## Compaction keeps the transcript complete
118​
119You can add [`withCompaction`](../advanced/compaction) to the same `chat()`. The saved thread stays the true copy:
120​
121- Compaction changes only the context sent to the provider, not `ctx.messages`.
122- The message store keeps the dropped content.
123- Summaries do not replace old turns.
124- Cleared tool output stays available for reloads.
125​
126If your adapter provides `stores.metadata`, `withPersistence` gives it to other middleware. Compaction uses it for validated checkpoints. See [Compaction and persistence](../advanced/compaction#compaction-and-persistence).
127​
128## What gets persisted, and when
129​
130`withPersistence` writes at four moments, so a reload never loses a turn:
131​
132| Moment | What is written | Best effort? |
133| --- | --- | --- |
134| **Start of a run** (`onStart`) | The pending turn: the user message that was just sent, plus the prior history. A reload during generation still shows the question. | Yes. A failure does not stop the run. The finish write is the one that counts. |
135| **Interrupt boundary** | New interrupt records, run status `interrupted`, known usage, and a snapshot of the current messages. | No. Store errors go to the caller. |
136| **Finish** (`onFinish`) | The complete transcript, run status `completed`, known usage, and the commit of the resumes that the run used. The transcript includes the completed assistant messages, the stream `messageId` of the last reply (so a reload keeps the same message id), and any completed structured-output part. | No. The transcript is saved **before** the run is marked completed. |
137| **While streaming** (optional) | Partial assistant text, throttled, when `snapshotStreaming: true`. | Yes. |
138​
139Streaming snapshots are off by default, because the finish write is the true save. Turn them on to keep partial output, at the cost of more writes:
140​
141```ts
142import { withPersistence } from '@tanstack/ai-persistence'
143import { persistence } from './persistence'
144​
145const streamingMiddleware = [
146 withPersistence(persistence, {
147 snapshotStreaming: true,
148 snapshotIntervalMs: 1000, // The default.
149 }),
151```
152​
153A snapshot row keeps the call metadata of a finished message, such as `source` and `responseId`, and no other chunk metadata. If the run fails or aborts after a snapshot, the snapshot stays as its assistant message. Its `metadata.tanstack.stopReason` is `'error'` or `'aborted'`.
154​
155### Structured output in the saved transcript
156​
157The chat engine completes the transcript before `onFinish` runs, and `withPersistence` saves that transcript as it is:
158​
159- Native-combined output keeps the structured result on the last assistant message.
160- Separate finalization can keep a plain-text assistant message, then a structured-output assistant message.
161- Harness adapters emit `structured-output.complete` during the run. A new message id stores the prose and the structured output as two assistant messages. The id of the last text message keeps both on one assistant message.
162​
163A client with `persistence: true` loads that transcript on mount. Read the structured-output part from `messages[].parts`:
164​
165```tsx
166import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
167import { z } from 'zod'
168​
169const PersonSchema = z.object({ name: z.string() })
170​
171function PersistentStructuredChat({ threadId }: { threadId: string }) {
172 const { messages } = useChat({
173 threadId,
174 connection: fetchServerSentEvents('/api/chat'),
175 persistence: true,
176 outputSchema: PersonSchema,
177 })
178​
179 return (
180 <div>
181 {messages.map((message) => {
182 const part = message.parts.find(
183 (candidate) => candidate.type === 'structured-output',
184 )
185 if (!part) return null
186 const person = part.data ?? part.partial
187 return <p key={message.id}>{person?.name}</p>
188 })}
189 </div>
190 )
192```
193​
194The matching server `GET` uses `reconstructChat`. See [Client persistence](./client-persistence).
195​
196### Errors and aborts
197​
198- On an **error**, the run is marked `failed`.
199- On an **abort**, the run is marked `aborted` with a `finishedAt`.
200- `interrupted` is written only at an interrupt boundary, and it is not terminal.
201- Both terminal paths keep the usage that the provider reported before the error or abort.
202​
203Resumes that `onConfig` accepts are **not** consumed until a success boundary (an interrupt or the finish). If a run fails before the resume commit, every pending interrupt stays open for a retry. The same is true when an atomic `commitBatch()` fails: the whole batch stays pending.
204​
205The sequential fallback (a store with no `commitBatch()`) is different. A write can fail after earlier entries were committed. In that case, load the current pending interrupt records of the thread again, and send only the batch that remains. Do not send the original full batch again.
206​
207### Detached runs
208​
209One abort does **not** end the run: a plain client disconnect on a run that other middleware marks as *detachable*. In practice, that is `withSandbox` with a durable event log and a run store.
210​
211For that run:
212​
213- `onAbort` writes nothing, and the record stays `'running'`.
214- The detach path records `detachedSince`, so a later request can take the run over.
215​
216The middleware never reads intent from the disconnect. A user who presses Stop and a user who closes the tab make the same connection close. A cancel arrives on a separate path: as the abort reason of the run, or as `RunRecord.cancelRequested`. Either one makes the abort terminal again. See [Takeover & Detached Runs](../sandbox/takeover#detach-vs-cancel).
217​
218### The run lifecycle
219​
220`completed`, `failed`, and `aborted` are terminal. `interrupted` is **parked**, not terminal.
221​
222The normal client flow starts a continuation with a new `runId`. A server integration can use the same `runId` again. Then `createOrResume` keeps the status `interrupted` until the next interrupt or terminal boundary. `findActiveRun` returns only `running` records, so it cannot find a same-id continuation while that continuation runs.
223​
224```mermaid
225stateDiagram-v2
226 [*] --> running : run starts (idempotent createOrResume)
227 running --> completed : finish, transcript saved first
228 running --> failed : error
229 running --> aborted : abort (explicit cancel, or a non-detachable run)
230 running --> interrupted : interrupt boundary
231 running --> running : plain disconnect on a DETACHABLE run (detachedSince set, taken over later)
232 completed --> [*]
233 failed --> [*]
234 aborted --> [*]
235 interrupted --> [*] : continuation can use a new runId
236 interrupted --> interrupted : same runId pauses again
237 interrupted --> completed : same runId completes
238 interrupted --> failed : same runId fails
239 interrupted --> aborted : same runId aborts
240```
241​
242## How interrupts resume
243​
244Persistence is the **server-authoritative resume path**. For each request with a `resume` batch, the middleware does these steps:
245​
2461. It validates every entry of the batch against the pending interrupts before it continues.
2472. It builds `ChatResumeToolState`: approvals, client-tool results, and generic requests.
2483. It **clears** `config.resume`, so the chat engine skips its own short-lived rebuild. That rebuild needs client message history, and the persistence flow does not send it.
2494. It commits all resolved and cancelled entries at one success boundary: the next interrupt or the finish.
250​
251An `InterruptStore` can implement `commitBatch()` to make that commit atomic. Without it, the fallback writes the entries one at a time, and the write is not atomic.
252​
253`onInterruptResolution` runs at the same moment as in a request without persistence: after the init `onConfig`, before `onStart`. See [Apply Answers](../interrupts/apply-answers).
254​
255An interrupt record starts as `pending`, and only a commit moves it. With `commitBatch()`, a failed commit leaves the full batch open for an answer again. With the sequential fallback, load the records again first, because some earlier entries can already be resolved or cancelled:
256​
257```mermaid
258stateDiagram-v2
259 [*] --> pending : run pauses, interrupt recorded
260 pending --> resolved : resume answers it, committed at a success boundary
261 pending --> cancelled : resume cancels it
262 resolved --> [*]
263 cancelled --> [*]
264```
265​
266## Locks across workers
267​
268If other middleware needs a mutex across server instances, add `withLocks` next to `withPersistence`. See [Locks](../advanced/locks).