Open History to see the last commit
1---
2title: Chat Persistence
3id: chat-persistence
4---
5
6You want a conversation to outlive a single request: the transcript, whether
7each run finished or is still waiting on an interrupt, all still there after the
8process restarts. `withPersistence` is a chat middleware that writes that
9state to a store you choose, so the server owns an authoritative copy of every
10thread.
11
12<!-- ::start:tabs variant="package-manager" mode="install" -->
13
14react: @tanstack/ai-persistence
15vue: @tanstack/ai-persistence
16solid: @tanstack/ai-persistence
17svelte: @tanstack/ai-persistence
18preact: @tanstack/ai-persistence
19angular: @tanstack/ai-persistence
20vanilla: @tanstack/ai-persistence
21octane: @tanstack/ai-persistence
22
23<!-- ::end:tabs -->
24
25<!-- ::start:tabs variant="package-manager" mode="local-install" -->
26
27react: @tanstack/intent@latest install
28vue: @tanstack/intent@latest install
29solid: @tanstack/intent@latest install
30svelte: @tanstack/intent@latest install
31preact: @tanstack/intent@latest install
32angular: @tanstack/intent@latest install
33vanilla: @tanstack/intent@latest install
34octane: @tanstack/intent@latest install
35
36<!-- ::end:tabs -->
37
38The second command wires this package's [Agent Skills](../getting-started/agent-skills)
39into your coding assistant. Run it before you start, because the recipes read your
40existing database setup and write the adapter to match, and they encode the
41invariants (full-overwrite `saveThread`, insert-if-absent run and interrupt
42creates) that are easy to get wrong and expensive to debug.
43
44## Persist state on the server
45
46Add the middleware to `chat()` and point it at a backend. Here `persistence` is a
47local `./persistence` module: an adapter you build on the core over the database
48you already run. [Build your own adapter](./build-your-own-adapter) walks through
49a complete SQLite version end to end.
50
51```ts group=chat-persistence
52import {
53 chat,
54 chatParamsFromRequestBody,
55 toServerSentEventsResponse,
56} from '@tanstack/ai'
57import { openaiText } from '@tanstack/ai-openai'
58import { withPersistence } from '@tanstack/ai-persistence'
59import { persistence } from './persistence'
60
61export async function POST(request: Request) {
62 const params = await chatParamsFromRequestBody(await request.json())
63 const stream = chat({
64 adapter: openaiText('gpt-5.5'),
65 messages: params.messages,
66 threadId: params.threadId,
67 runId: params.runId,
68 // Forward the resume batch so a thread with pending interrupts continues.
69 ...(params.resume ? { resume: params.resume } : {}),
70 middleware: [withPersistence(persistence)],
71 })
72 return toServerSentEventsResponse(stream)
73}
74```
75
76The middleware uses whichever **state** stores the backend provides, no feature
77flags. `messages` is required; the rest are optional:
78
79- `messages` (required) loads and saves the full model-message thread.
80- `runs` records running, interrupted, completed, failed, or aborted status.
81- `interrupts` records pending tool-approval / client-tool / generic waits, and
82 requires `runs`.
83
84Need a mutex across workers? Add `withLocks` when other middleware needs
85multi-instance coordination; see [Locks](../advanced/locks).
86
87Creating tables on open is convenient for local development. In production, apply
88schema changes through your deployment workflow instead. See
89[Migrations](./migrations).
90
91## Threads, runs, and turns
92
93The transcript is stored per `threadId`, and each run gets a `runs` record with its
94status, timings, and reported usage across provider calls. One thing follows from
95that and matters when you wire a client: a reconnecting client never has to present
96a run id it may no longer know. The store resolves the thread's live run with
97`findActiveRun(threadId)` and the client tails that.
98
99[Id map](./id-map) covers how to choose a thread id and what both ids mean on the
100generation hooks. [How persistence works](./internals) has the rest.
101
102## Subagent cards on reload
103
104When the run store keeps the child link, a refresh shows each subagent as a card.
105
106Save these three fields on the child run. `createOrResume` writes them on the first insert:
107
108- `parentRunId`: the chat run that started the child.
109- `subagentRunId`: the child run id.
110- `name`: the agent name.
111
112`reconstructChat` calls `listByParentRun`. It puts one card on the parent assistant message for each child. Each card gets the child's full transcript back: text, reasoning, tool calls, and tool results. Nested children come back as nested cards.
113
114A 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.
115
116A child that a tool call started sits on the message with that tool call. `reconstructChat` finds its parent run with `listByThread`, so implement that method too.
117
118Put `withPersistence` on the parent `chat()` only, not on a child `chat()`. The parent stores the child runs. A child with its own `withPersistence` stores the same child a second time, and its interrupt records conflict with the parent's.
119
120Subagent support is optional. If the store omits `listByParentRun`, a reload shows the saved text and the cards stay absent. The conformance suite skips the subagent checks with no `skipMethods` entry.
121
122The columns and the method are in the [store reference](./store-reference).
123
124## Keep every stored message
125
126`withPersistence` merges incoming `messages` into the stored thread by id.
127
128If `messages` is empty, the middleware loads the stored transcript and the run
129continues from there.
130
131If `messages` is not empty, the middleware merges by id:
132
133- The last incoming id that already exists in stored is a cutoff. Stored
134 messages after it are dropped. That is how reload removes the old assistant.
135- If no incoming id is in stored, every stored message stays (a new turn).
136- Same id in both lists: incoming wins.
137- New ids and messages with no id are appended.
138
139`saveThread` replaces the stored thread with that merged list.
140
141A client with `history: { pageSize }` posts only the new turn. Reload posts
142the last user. Resume posts from that user through the painted assistant.
143See [Client persistence](./client-persistence).
144
145## Compaction keeps the transcript complete
146
147Do you add [`withCompaction`](../advanced/compaction) to the same `chat()`? The
148saved thread remains canonical. Compaction changes only the provider context,
149not `ctx.messages`. The message store keeps dropped content, summaries do not
150replace old turns, and cleared tool output remains available for reloads.
151
152If your adapter provides `stores.metadata`, `withPersistence` exposes it to
153other middleware. Compaction uses it automatically for validated checkpoints.
154See
155[Compaction and persistence](../advanced/compaction#compaction-and-persistence).
156
157## What gets persisted, and when
158
159`withPersistence` writes at **four** moments so a reload never loses a turn:
160
161| Moment | What is written | Best-effort? |
162| --- | --- | --- |
163| **Start of a run** (`onStart`) | Pending turn (just-submitted user message + prior history) so a reload mid-generation still shows the question | Yes. Failure does not abort the run; finish is authoritative |
164| **Interrupt boundary** | New interrupt records, run status `interrupted`, known usage, and a thread snapshot of current messages | No. Store failures propagate |
165| **Finish** (`onFinish`) | Complete transcript (including completed assistant messages, the terminal reply's stream `messageId` for in-place reload identity, and any completed structured-output part), run status `completed`, known usage, and commit of consumed resumes | No. The transcript is saved **before** the run is marked completed |
166| **Optionally while streaming** | Throttled partial assistant text when `snapshotStreaming: true` | Yes |
167
168```ts group=chat-persistence
169const streamingMiddleware = [
170 withPersistence(persistence, { snapshotStreaming: true }),
171]
172```
173
174Streaming snapshots default off (finish is the authoritative save); enable
175them to trade extra writes for partial-output durability. Tune the interval
176with `snapshotIntervalMs` (default `1000`).
177
178The chat engine completes the canonical transcript before `onFinish` runs, and
179`withPersistence` saves that transcript directly.
180
181- Native-combined output keeps the structured result on its terminal assistant
182 message.
183- Separate finalization can preserve a plain-text assistant message followed by
184 a structured-output assistant message.
185- Harness adapters emit `structured-output.complete` during the run. A new
186 message id stores prose and structured output as two assistant messages. The
187 last text message id keeps both on one assistant message.
188
189A server-authoritative client hydrates that transcript on mount. Walk
190`messages[].parts` for the reconstructed structured-output part:
191
192```tsx group=chat-persistence
193import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
194import { z } from 'zod'
195
196const PersonSchema = z.object({ name: z.string() })
197
198function PersistentStructuredChat({ threadId }: { threadId: string }) {
199 const { messages } = useChat({
200 threadId,
201 connection: fetchServerSentEvents('/api/chat'),
202 persistence: true,
203 outputSchema: PersonSchema,
204 })
205
206 return (
207 <div>
208 {messages.map((message) => {
209 const part = message.parts.find(
210 (candidate) => candidate.type === 'structured-output',
211 )
212 if (!part) return null
213 const person = part.data ?? part.partial
214 return <p key={message.id}>{person?.name}</p>
215 })}
216 </div>
217 )
218}
219```
220
221The matching server `GET` uses `reconstructChat`. See
222[Client persistence](./client-persistence).
223
224On **error**, the run is marked `failed`. On **abort**, the run is marked
225`aborted` with a `finishedAt`; `interrupted` is written only at an interrupt
226boundary, and it is not terminal. Both terminal paths retain usage reported
227before the failure or abort. Resumes accepted in `onConfig` are **not**
228consumed until a success boundary (interrupt or finish). If a run fails before
229the resume commit, every pending interrupt stays retryable. The same is true
230when an atomic `commitBatch()` fails: the whole batch stays pending.
231
232The legacy sequential fallback is different. A write can fail after earlier
233entries were committed. Reload the thread's current pending interrupt records
234and submit only that remaining batch. Do not resend the original full batch.
235
236One abort does **not** terminalize: a plain client disconnect on a run that some
237other middleware has declared *detachable* (a durable event log plus a run
238store, in practice `withSandbox` with durability wired). There, `onAbort` writes
239nothing at all, the record stays `'running'`, and the detach path records
240`detachedSince` so a later request can take the run over. Intent is never
241inferred from the disconnect itself, because a user pressing Stop and a user
242closing the tab produce the identical connection close; a cancel arrives out of
243band, either as the run's own abort reason or as `RunRecord.cancelRequested`, and
244either one makes the abort terminal again. See
245[Takeover & Detached Runs](../sandbox/takeover#detach-vs-cancel).
246
247The lifecycle a run record moves through. `completed`, `failed`, and `aborted`
248are terminal; `interrupted` is **parked**, not terminal. The normal client flow
249starts a continuation with a fresh `runId`. A server integration can reuse the
250same `runId`; `createOrResume` leaves its status `interrupted` until the next
251interrupt or terminal boundary. `findActiveRun` only returns `running` records,
252so it cannot discover a same-ID continuation while that continuation executes.
253
254```mermaid
255stateDiagram-v2
256 [*] --> running : run starts (idempotent createOrResume)
257 running --> completed : finish, transcript saved first
258 running --> failed : error
259 running --> aborted : abort (explicit cancel, or a non-detachable run)
260 running --> interrupted : interrupt boundary
261 running --> running : plain disconnect on a DETACHABLE run (detachedSince set, taken over later)
262 completed --> [*]
263 failed --> [*]
264 aborted --> [*]
265 interrupted --> [*] : continuation may use a new runId
266 interrupted --> interrupted : same runId pauses again
267 interrupted --> completed : same runId completes
268 interrupted --> failed : same runId fails
269 interrupted --> aborted : same runId aborts
270```
271
272## Interrupts survive a restart
273
274When a run pauses on an interrupt (a tool approval, a client-side tool, or a
275generic middleware request), the middleware records it. A later request on that
276thread must carry a `resume` batch that answers the pending interrupts before
277new input is accepted, otherwise it is rejected, which is why the example above
278forwards `params.resume`.
279
280For a mixed batch, the persistence middleware validates every entry before it
281continues. It commits all resolved and cancelled entries at one success
282boundary. An `InterruptStore` can implement `commitBatch()` to make that write
283atomic. Without it, the compatibility fallback writes entries one at a time and
284is not atomic.
285
286Persistence is the **server-authoritative resume path**: the middleware
287validates the resume batch against pending interrupts, builds
288`ChatResumeToolState` (approvals / client-tool results / generic requests), and
289**clears** `config.resume` so the chat engine skips its ephemeral
290reconstruction (which needs client message history the persistence flow
291deliberately omits). Resumes are committed (resolved/cancelled in the store)
292only once the run reaches a successful interrupt or finish boundary.
293
294`onInterruptResolution` still runs at the same moment as a request without
295persistence: after init `onConfig`, before `onStart`. See
296[Apply Answers](../interrupts/apply-answers).
297
298An interrupt record is born `pending` and only a commit moves it. With
299`commitBatch()`, a failed commit leaves the full batch answerable again. With
300the sequential fallback, reload first because some earlier entries may already
301be resolved or cancelled:
302
303```mermaid
304stateDiagram-v2
305 [*] --> pending : run pauses, interrupt recorded
306 pending --> resolved : resume answers it, committed at a success boundary
307 pending --> cancelled : resume cancels it
308 resolved --> [*]
309 cancelled --> [*]
310```
311
312## Where to go next
313
314- Bring durability to the browser too, so a full page reload restores the
315 conversation and rejoins an in-flight run: [Client persistence](./client-persistence).
316- Build the backend on the core, and look up the store contracts:
317 [Build your own adapter](./build-your-own-adapter). Whatever you already run
318 (Drizzle, Prisma, Cloudflare D1, raw SQL), install the shipped
319 [Agent Skills](../getting-started/agent-skills) with
320 `npx @tanstack/intent@latest install` and have your assistant write the
321 `chat-persistence.ts` against your existing schema.
322- Choose which stores to run: [Controls](./controls).