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

chat-persistence.md

395 lines16.8 KB

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)
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## AG-UI activity rows on reload
125​
126An AG-UI `ACTIVITY_SNAPSHOT` or `ACTIVITY_DELTA` event shows in the client as a
127`role: 'activity'` row, for example a search progress card. The `messages`
128store keeps only model messages, so a reload loses that row. Add an
129`activities` store to keep it.
130​
1311. Give the backend an `activities` store. `memoryPersistence()` already has
132 one. For your own backend, type it with `defineActivityStore`:
133​
134 ```ts
135 import {
136 composePersistence,
137 defineActivityStore,
138 } from '@tanstack/ai-persistence'
139 import type { ActivityRecord } from '@tanstack/ai-persistence'
140 import { persistence as base } from './persistence'
141​
142 const rows = new Map<string, Array<ActivityRecord>>()
143​
144 export const persistence = composePersistence(base, {
145 overrides: {
146 activities: defineActivityStore({
147 loadActivities: async (threadId) => rows.get(threadId) ?? [],
148 // Full overwrite: `list` is the complete activity list for the thread.
149 saveActivities: async (threadId, list) => {
150 rows.set(threadId, list)
151 },
152 }),
153 },
154 })
155 ```
156​
1572. Keep your `withPersistence(persistence)` route and `reconstructChat` `GET`
158 endpoint. They save and restore the rows when `stores.activities` is set.
159​
1603. Render the rows on the client. Each one has one part with
161 `type: 'activity'`:
162​
163 ```tsx
164 import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
165​
166 function Chat({ threadId }: { threadId: string }) {
167 const { messages } = useChat({
168 threadId,
169 connection: fetchServerSentEvents('/api/chat'),
170 persistence: true,
171 })
172 return (
173 <div>
174 {messages.map((message) =>
175 message.role === 'activity' ? (
176 <div key={message.id}>
177 {message.parts.map((part, index) =>
178 part.type === 'activity' ? (
179 <pre key={index}>
180 {part.activityType}: {JSON.stringify(part.content)}
181 </pre>
182 ) : null,
183 )}
184 </div>
185 ) : (
186 <div key={message.id}>{message.role}</div>
187 ),
188 )}
189 </div>
190 )
191 }
192 ```
193​
194The model never gets activity rows as input. A failed activity save does not
195fail the run. Each `ActivityRecord` keeps the row's `metadata`.
196​
197## Keep every stored message
198​
199`withPersistence` merges incoming `messages` into the stored thread by id.
200​
201If `messages` is empty, the middleware loads the stored transcript and the run
202continues from there.
203​
204If `messages` is not empty, the middleware merges by id:
205​
206- The last incoming id that already exists in stored is a cutoff. Stored
207 messages after it are dropped. That is how reload removes the old assistant.
208- If no incoming id is in stored, every stored message stays (a new turn).
209- Same id in both lists: incoming wins.
210- New ids and messages with no id are appended.
211​
212`saveThread` replaces the stored thread with that merged list.
213​
214A client with `history: { pageSize }` posts only the new turn. Reload posts
215the last user. Resume posts from that user through the painted assistant.
216See [Client persistence](./client-persistence).
217​
218## Compaction keeps the transcript complete
219​
220Do you add [`withCompaction`](../advanced/compaction) to the same `chat()`? The
221saved thread remains canonical. Compaction changes only the provider context,
222not `ctx.messages`. The message store keeps dropped content, summaries do not
223replace old turns, and cleared tool output remains available for reloads.
224​
225If your adapter provides `stores.metadata`, `withPersistence` exposes it to
226other middleware. Compaction uses it automatically for validated checkpoints.
227See
228[Compaction and persistence](../advanced/compaction#compaction-and-persistence).
229​
230## What gets persisted, and when
231​
232`withPersistence` writes at **four** moments so a reload never loses a turn:
233​
234| Moment | What is written | Best-effort? |
235| --- | --- | --- |
236| **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 |
237| **Interrupt boundary** | New interrupt records, run status `interrupted`, known usage, and a thread snapshot of current messages | No. Store failures propagate |
238| **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 |
239| **Optionally while streaming** | Throttled partial assistant text when `snapshotStreaming: true` | Yes |
240​
241```ts group=chat-persistence
242const streamingMiddleware = [
243 withPersistence(persistence, { snapshotStreaming: true }),
245```
246​
247Streaming snapshots default off (finish is the authoritative save); enable
248them to trade extra writes for partial-output durability. Tune the interval
249with `snapshotIntervalMs` (default `1000`).
250​
251The chat engine completes the canonical transcript before `onFinish` runs, and
252`withPersistence` saves that transcript directly.
253​
254- Native-combined output keeps the structured result on its terminal assistant
255 message.
256- Separate finalization can preserve a plain-text assistant message followed by
257 a structured-output assistant message.
258- Harness adapters emit `structured-output.complete` during the run. A new
259 message id stores prose and structured output as two assistant messages. The
260 last text message id keeps both on one assistant message.
261​
262A server-authoritative client hydrates that transcript on mount. Walk
263`messages[].parts` for the reconstructed structured-output part:
264​
265```tsx group=chat-persistence
266import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
267import { z } from 'zod'
268​
269const PersonSchema = z.object({ name: z.string() })
270​
271function PersistentStructuredChat({ threadId }: { threadId: string }) {
272 const { messages } = useChat({
273 threadId,
274 connection: fetchServerSentEvents('/api/chat'),
275 persistence: true,
276 outputSchema: PersonSchema,
277 })
278​
279 return (
280 <div>
281 {messages.map((message) => {
282 const part = message.parts.find(
283 (candidate) => candidate.type === 'structured-output',
284 )
285 if (!part) return null
286 const person = part.data ?? part.partial
287 return <p key={message.id}>{person?.name}</p>
288 })}
289 </div>
290 )
292```
293​
294The matching server `GET` uses `reconstructChat`. See
295[Client persistence](./client-persistence).
296​
297On **error**, the run is marked `failed`. On **abort**, the run is marked
298`aborted` with a `finishedAt`; `interrupted` is written only at an interrupt
299boundary, and it is not terminal. Both terminal paths retain usage reported
300before the failure or abort. Resumes accepted in `onConfig` are **not**
301consumed until a success boundary (interrupt or finish). If a run fails before
302the resume commit, every pending interrupt stays retryable. The same is true
303when an atomic `commitBatch()` fails: the whole batch stays pending.
304​
305The legacy sequential fallback is different. A write can fail after earlier
306entries were committed. Reload the thread's current pending interrupt records
307and submit only that remaining batch. Do not resend the original full batch.
308​
309One abort does **not** terminalize: a plain client disconnect on a run that some
310other middleware has declared *detachable* (a durable event log plus a run
311store, in practice `withSandbox` with durability wired). There, `onAbort` writes
312nothing at all, the record stays `'running'`, and the detach path records
313`detachedSince` so a later request can take the run over. Intent is never
314inferred from the disconnect itself, because a user pressing Stop and a user
315closing the tab produce the identical connection close; a cancel arrives out of
316band, either as the run's own abort reason or as `RunRecord.cancelRequested`, and
317either one makes the abort terminal again. See
318[Takeover & Detached Runs](../sandbox/takeover#detach-vs-cancel).
319​
320The lifecycle a run record moves through. `completed`, `failed`, and `aborted`
321are terminal; `interrupted` is **parked**, not terminal. The normal client flow
322starts a continuation with a fresh `runId`. A server integration can reuse the
323same `runId`; `createOrResume` leaves its status `interrupted` until the next
324interrupt or terminal boundary. `findActiveRun` only returns `running` records,
325so it cannot discover a same-ID continuation while that continuation executes.
326​
327```mermaid
328stateDiagram-v2
329 [*] --> running : run starts (idempotent createOrResume)
330 running --> completed : finish, transcript saved first
331 running --> failed : error
332 running --> aborted : abort (explicit cancel, or a non-detachable run)
333 running --> interrupted : interrupt boundary
334 running --> running : plain disconnect on a DETACHABLE run (detachedSince set, taken over later)
335 completed --> [*]
336 failed --> [*]
337 aborted --> [*]
338 interrupted --> [*] : continuation may use a new runId
339 interrupted --> interrupted : same runId pauses again
340 interrupted --> completed : same runId completes
341 interrupted --> failed : same runId fails
342 interrupted --> aborted : same runId aborts
343```
344​
345## Interrupts survive a restart
346​
347When a run pauses on an interrupt (a tool approval, a client-side tool, or a
348generic middleware request), the middleware records it. A later request on that
349thread must carry a `resume` batch that answers the pending interrupts before
350new input is accepted, otherwise it is rejected, which is why the example above
351forwards `params.resume`.
352​
353For a mixed batch, the persistence middleware validates every entry before it
354continues. It commits all resolved and cancelled entries at one success
355boundary. An `InterruptStore` can implement `commitBatch()` to make that write
356atomic. Without it, the compatibility fallback writes entries one at a time and
357is not atomic.
358​
359Persistence is the **server-authoritative resume path**: the middleware
360validates the resume batch against pending interrupts, builds
361`ChatResumeToolState` (approvals / client-tool results / generic requests), and
362**clears** `config.resume` so the chat engine skips its ephemeral
363reconstruction (which needs client message history the persistence flow
364deliberately omits). Resumes are committed (resolved/cancelled in the store)
365only once the run reaches a successful interrupt or finish boundary.
366​
367`onInterruptResolution` still runs at the same moment as a request without
368persistence: after init `onConfig`, before `onStart`. See
369[Apply Answers](../interrupts/apply-answers).
370​
371An interrupt record is born `pending` and only a commit moves it. With
372`commitBatch()`, a failed commit leaves the full batch answerable again. With
373the sequential fallback, reload first because some earlier entries may already
374be resolved or cancelled:
375​
376```mermaid
377stateDiagram-v2
378 [*] --> pending : run pauses, interrupt recorded
379 pending --> resolved : resume answers it, committed at a success boundary
380 pending --> cancelled : resume cancels it
381 resolved --> [*]
382 cancelled --> [*]
383```
384​
385## Where to go next
386​
387- Bring durability to the browser too, so a full page reload restores the
388 conversation and rejoins an in-flight run: [Client persistence](./client-persistence).
389- Build the backend on the core, and look up the store contracts:
390 [Build your own adapter](./build-your-own-adapter). Whatever you already run
391 (Drizzle, Prisma, Cloudflare D1, raw SQL), install the shipped
392 [Agent Skills](../getting-started/agent-skills) with
393 `npx @tanstack/intent@latest install` and have your assistant write the
394 `chat-persistence.ts` against your existing schema.
395- Choose which stores to run: [Controls](./controls).