Open History to see the last commit
1---
2title: Generation Persistence
3id: generation-persistence
4---
5
6Generation persistence stores a media run. A reload or a dropped connection can resume a video that takes minutes.
7
8Generation persistence keeps a small record of each run. On reload, it puts the run back into the normal `status`, `result`, and `error` fields of the hook. So a restored run looks like a live run.
9
10Use it when a run is long enough that a reload matters: video, batch images, long audio, or a big transcription. For a quick image that you show once, you do not need it.
11
12## Quick setup
13
14### 1. Install the package
15
16<!-- ::start:tabs variant="package-manager" mode="install" -->
17
18react: @tanstack/ai-persistence
19vue: @tanstack/ai-persistence
20solid: @tanstack/ai-persistence
21svelte: @tanstack/ai-persistence
22preact: @tanstack/ai-persistence
23angular: @tanstack/ai-persistence
24vanilla: @tanstack/ai-persistence
25octane: @tanstack/ai-persistence
26
27<!-- ::end:tabs -->
28
29### 2. Add the server route
30
31Add a `POST` that runs the generation, and a `GET` on the same route that answers the hydration on mount:
32
33```ts group=generation-server-driven
34import {
35 generateImage,
36 generationParamsFromRequest,
37 memoryStream,
38 resumeServerSentEventsResponse,
39 toServerSentEventsResponse,
40} from '@tanstack/ai'
41import { openaiImage } from '@tanstack/ai-openai'
42import {
43 memoryPersistence,
44 reconstructGeneration,
45 withGenerationPersistence,
46} from '@tanstack/ai-persistence'
47
48const persistence = memoryPersistence()
49
50export async function POST(request: Request) {
51 const durability = memoryStream(request)
52 const { input, threadId, runId } = await generationParamsFromRequest(
53 'image',
54 request,
55 )
56
57 if (typeof input.prompt !== 'string') {
58 throw new Error('This endpoint accepts text image prompts only.')
59 }
60
61
62 const stream = generateImage({
63 adapter: openaiImage('gpt-image-2.5-flare'),
64 prompt: input.prompt,
65 // The same slot the GET below finds the last run for.
66 threadId,
67 // The client's run id. `memoryStream` stores the stream under it.
68 runId,
69 stream: true,
70 // `artifactUrl` is optional. It makes the restored media load from your
71 // own origin. See Keep generated files for the route it points at.
72 middleware: [
73 withGenerationPersistence(persistence, {
74 artifactUrl: (ref) => `/api/generate/image/artifact?id=${ref.artifactId}`,
75 }),
76 ],
77 })
78
79 return toServerSentEventsResponse(stream, {
80 durability: { adapter: durability },
81 })
82}
83
84export function GET(request: Request): Response | Promise<Response> {
85 const durability = memoryStream(request)
86 // A reconnecting client sends a resume cursor. Replay the live stream.
87 if (durability.resumeFrom() !== null) {
88 return resumeServerSentEventsResponse({ adapter: durability })
89 }
90 // Otherwise this is the hydration on mount (?threadId). In a multi-user app,
91 // pass the `authorize` option so a guessed threadId cannot read another
92 // user's generation.
93 return reconstructGeneration(persistence, request)
94}
95```
96
97### 3. Turn it on in the hook
98
99Pass a connection, a stable `threadId`, and `persistence: true`:
100
101```tsx
102import { fetchServerSentEvents, useGenerateImage } from '@tanstack/ai-react'
103
104const connection = fetchServerSentEvents('/api/generate/image')
105
106export function HeroImageGenerator({ threadId }: { threadId: string }) {
107 const image = useGenerateImage({
108 threadId,
109 connection,
110 persistence: true,
111 })
112
113 return (
114 <section>
115 <button
116 type="button"
117 disabled={image.isLoading}
118 onClick={() =>
119 void image.generate({ prompt: 'A glass cabin in a pine forest' })
120 }
121 >
122 Generate
123 </button>
124
125 {image.status === 'success' ? (
126 <p>Last run finished{image.result?.id ? ` (${image.result.id})` : ''}.</p>
127 ) : null}
128 {image.error ? <p>Last run failed: {image.error.message}</p> : null}
129 {image.result?.images.map((img, index) =>
130 img.url ? <img key={index} src={img.url} alt="" /> : null,
131 )}
132 </section>
133 )
134}
135```
136
137Generate an image, then reload the page. The hook shows the last run again. Reload while the run still generates, and the hook joins the run and finishes it in place.
138
139## The thread id is a slot
140
141For a generation, the `threadId` is a **slot**, not a conversation. It is a stable name that you choose for the place that runs fill, for example `product-7-hero` or `video-9-start-frame`.
142
143- Each run gets its own `runId` and its own record.
144- On reload, the hook gets the newest run in the slot.
145- Pass the same string to the hook and to the activity, and keep it stable across reloads. The middleware reads it from the activity.
146
147[Id map](./id-map) explains how to choose one, and what goes wrong when it changes.
148
149## How it works
150
151`persistence` on the hook is a boolean:
152
153- **`true`**: the server keeps the record. On mount, the hook loads the last run for its `threadId` and shows it again.
154- **`false` or omitted**: off. The run lives in memory only, and a reload starts empty.
155
156`withGenerationPersistence` writes the record to a `generationRuns` store. That store is keyed by the `runId` of the run, and it records the `threadId` as the slot. `memoryPersistence()` has one by default. For your own backend, see [Build a generation adapter](./build-your-own-generation-adapter).
157
158The browser caches nothing. So the history is never copied into local storage, and a second device sees the same run.
159
160A run can be **still generating** when the connection drops or the page reloads. Then the client joins it again and finishes it in place, like `useChat` does. Two parts make this work:
161
162- The `durability` adapter on `toServerSentEventsResponse`.
163- The resume branch of the `GET`. On mount, `reconstructGeneration` reports the live run, and the client follows it through the durability log.
164
165In production, replace `memoryStream` with `durableStream` from `@tanstack/ai-durable-stream`, because requests then run in many processes. See [Resumable Streams](../resumable-streams/overview).
166
167## What a reload restores
168
169- **The hook looks the same as a live run.** After a reload, it shows `status` (`'idle'`, `'generating'`, `'success'`, or `'error'`), `error`, and `result`. There is no separate snapshot field to show.
170- **`result` comes back only with byte storage.** The run record keeps result metadata, never the media bytes. Without byte storage, a reload restores `status` and `error`, and `result` stays `null`. Add byte storage and `artifactUrl` ([Keep generated files](./keep-generated-files)), and the hook rebuilds `result` with media from your own origin.
171
172## Advanced
173
174### The run lifecycle
175
176The record has one status field that the middleware moves forward:
177
178```mermaid
179stateDiagram-v2
180 [*] --> running : generation starts (idempotent createOrResume)
181 running --> completed : finish, result metadata saved
182 running --> failed : error
183 running --> aborted : abort
184 completed --> [*]
185 failed --> [*]
186 aborted --> [*]
187```
188
189A restored `aborted` run shows in the hook as an error. You cannot resume an aborted generation. You can only run it again.
190
191This is the flow on mount:
192
193```mermaid
194sequenceDiagram
195 participant Hook as useGenerateImage (persistence: true)
196 participant Route as GET /api/generate/image
197 participant Runs as generationRuns store
198 participant Log as Delivery log
199
200 Note over Hook: mount (or reload) with a threadId
201 Hook->>Route: ?threadId=...
202 Route->>Runs: reconstructGeneration, latest run for the thread
203 Runs-->>Route: run record (status, result metadata, artifact refs)
204 Route-->>Hook: status / error / result shown again
205 alt run still generating
206 Hook->>Route: ?runId=...&offset=-1
207 Route->>Log: resumeServerSentEventsResponse
208 Log-->>Hook: replay + live tail, run finishes in place
209 end
210```
211
212### Server functions / direct
213
214The HTTP adapters handle hydration and rejoin for you. With [TanStack Start](https://tanstack.com/start) server functions, or any direct in-process call, there is no `GET` route. So you supply two handlers yourself:
215
216- One for the hydration on mount.
217- One that replays a run that still generates.
218
219Pass them as options next to the `fetcher`, or to `stream()` or `rpcStream()`.
220
221Three server functions cover it:
222
2231. `generateImageFn` runs the generation.
2242. `getImageHydrationFn` answers the hydration with `getGenerationHydration`.
2253. `joinImageRunFn` replays the durability log of the run with `replayRunStream`.
226
227The two streaming functions both return an SSE `Response` from `toServerSentEventsResponse`, so the client decodes them the same way:
228
229```ts group=generation-server-functions
230// server/image.ts
231import { createServerFn } from '@tanstack/react-start'
232import { z } from 'zod'
233import {
234 generateImage,
235 memoryStream,
236 replayRunStream,
237 toServerSentEventsResponse,
238} from '@tanstack/ai'
239import { openaiImage } from '@tanstack/ai-openai'
240import {
241 getGenerationHydration,
242 memoryPersistence,
243 withGenerationPersistence,
244} from '@tanstack/ai-persistence'
245import type { ImageGenerateInput } from '@tanstack/ai-client'
246
247const persistence = memoryPersistence()
248
249export const generateImageFn = createServerFn({ method: 'POST' })
250 .inputValidator((data: ImageGenerateInput & { threadId: string }) => data)
251 .handler(({ data: { threadId, ...input } }) => {
252 if (typeof input.prompt !== 'string') {
253 throw new Error('This endpoint accepts text image prompts only.')
254 }
255 // One run id for both the durability log and the run record, so the
256 // rejoin below replays the same run that hydration reports.
257 const runId = crypto.randomUUID()
258 const stream = generateImage({
259 adapter: openaiImage('gpt-image-2.5-flare'),
260 prompt: input.prompt,
261 threadId,
262 runId,
263 stream: true,
264 // `artifactUrl` is optional. See Keep generated files.
265 middleware: [
266 withGenerationPersistence(persistence, {
267 artifactUrl: (ref) => `/api/generate/image/artifact?id=${ref.artifactId}`,
268 }),
269 ],
270 })
271 return toServerSentEventsResponse(stream, {
272 durability: { adapter: memoryStream({ runId }) },
273 })
274 })
275
276/**
277 * The wire shape for mount hydration, parsed with Zod so that:
278 * - TanStack Start gets a JSON-serializable return type (the `result` of the
279 * run record is loosely typed, and the Start serializer rejects `unknown`)
280 * - the stored record is validated before it goes over the wire
281 */
282const hydrationSchema = z.object({
283 resumeSnapshot: z
284 .object({
285 schemaVersion: z.literal(1),
286 resumeState: z
287 .object({ threadId: z.string(), runId: z.string() })
288 .nullable(),
289 status: z.enum(['idle', 'running', 'complete', 'error']),
290 // `z.any()` (not `z.unknown()`) so the Start serializer accepts the values.
291 result: z.record(z.string(), z.any()).optional(),
292 error: z
293 .object({ message: z.string(), code: z.string().optional() })
294 .optional(),
295 activity: z.string().optional(),
296 })
297 .nullable(),
298 activeRun: z.object({ runId: z.string() }).nullable(),
299})
300
301export const getImageHydrationFn = createServerFn({ method: 'GET' })
302 .inputValidator(z.string().min(1))
303 .handler(async ({ data: threadId }) => {
304 // `getGenerationHydration` does no auth. Check the session here, the
305 // way you pass `authorize` to `reconstructGeneration`.
306 return hydrationSchema.parse(
307 await getGenerationHydration(persistence, threadId),
308 )
309 })
310
311export const joinImageRunFn = createServerFn({ method: 'GET' })
312 .inputValidator(z.string().min(1))
313 .handler(({ data: runId }) =>
314 // The same SSE envelope that `generateImageFn` returns, so one client-side
315 // decoder covers both.
316 toServerSentEventsResponse(replayRunStream(memoryStream({ runId }))),
317 )
318```
319
320On the client, pass the two handlers next to the `fetcher`. A reload then loads the last run through `getImageHydrationFn`. A run that still generates finishes through `joinImageRunFn`.
321
322`joinRun` yields `StreamChunk`s, not a `Response`. So decode the SSE body yourself and apply the `signal` there. The server function itself takes only its `data`:
323
324```tsx
325import { useGenerateImage } from '@tanstack/ai-react'
326import type { StreamChunk } from '@tanstack/ai'
327import {
328 generateImageFn,
329 getImageHydrationFn,
330 joinImageRunFn,
331} from './server/image'
332
333/** Decode an SSE `Response` from a server function into `StreamChunk`s. */
334async function* chunksFromSseResponse(
335 response: Response,
336 signal?: AbortSignal,
337): AsyncGenerator<StreamChunk> {
338 if (!response.ok) throw new Error(`Join failed: ${response.status}`)
339 const reader = response.body?.getReader()
340 if (!reader) return
341 const decoder = new TextDecoder()
342 let buffer = ''
343 try {
344 while (!signal?.aborted) {
345 const { done, value } = await reader.read()
346 if (done) break
347 buffer += decoder.decode(value, { stream: true })
348 const lines = buffer.split('\n')
349 buffer = lines.pop() ?? ''
350 for (const line of lines) {
351 if (!line.startsWith('data:')) continue
352 const data = line.slice(5).trimStart()
353 // `JSON.parse` returns the chunk that the server encoded.
354 if (data) yield JSON.parse(data)
355 }
356 }
357 } finally {
358 reader.releaseLock()
359 }
360}
361
362export function HeroImageGenerator({ threadId }: { threadId: string }) {
363 const image = useGenerateImage({
364 threadId,
365 fetcher: (input) => generateImageFn({ data: { ...input, threadId } }),
366 hydrateGeneration: (id) => getImageHydrationFn({ data: id }),
367 joinRun: async function* (runId, signal) {
368 const response = await joinImageRunFn({ data: runId })
369 if (!(response instanceof Response)) {
370 throw new Error('joinImageRunFn should return an SSE Response')
371 }
372 yield* chunksFromSseResponse(response, signal)
373 },
374 persistence: true,
375 })
376 // The render is the same as in the HTTP example above.
377 return <p>{image.status}</p>
378}
379```
380
381Some facts about these handlers:
382
383- A non-streaming `fetcher` returns a plain `Promise<ImageGenerationResult>`, not an SSE `Response`. It has no live stream to rejoin, so it needs only `hydrateGeneration`. Remove `joinRun` and the decoder.
384- A restored run can still be generating with **no** `joinRun` handler to follow it. Then it shows as an interrupted error, which you can run again. It does not stay on `generating` forever.
385- The same handlers fit the lightweight connection adapters: `stream(factory, { hydrateGeneration, joinRun })` and `rpcStream(call, { hydrateGeneration, joinRun })`. These adapters also accept a chat `hydrate` handler for the server-driven persistence of `useChat`.
386
387### Non-streaming video is two calls
388
389`generateVideo({ stream: true })` runs the full create, poll, and complete lifecycle in one call. So persistence sees one run, and this section does not apply.
390
391Without `stream: true`, it is two calls, and the video does not exist when the first call returns:
392
393```ts
394import { generateVideo, getVideoJobStatus } from '@tanstack/ai'
395import {
396 memoryPersistence,
397 withGenerationPersistence,
398} from '@tanstack/ai-persistence'
399import { openaiVideo } from '@tanstack/ai-openai'
400
401const persistence = memoryPersistence()
402const adapter = openaiVideo('sora-2')
403const middleware = [withGenerationPersistence(persistence)]
404const threadId = 'product-7-launch-clip'
405
406// Opens the run. Status `running`, and there is no video yet.
407const { jobId } = await generateVideo({
408 adapter,
409 prompt: 'A cat chasing a dog in a sunny park',
410 threadId,
411 middleware,
412})
413
414// Completes that same run. This call writes the video and its artifacts.
415const status = await getVideoJobStatus({ adapter, jobId, threadId, middleware })
416```
417
418Pass the same `threadId` and `middleware` to both calls.
419
420- **The `jobId` links the two calls.** The run id comes from it. So the poll finds the run that the submit opened, even from a different request or process. You store nothing.
421- Until a poll sees a terminal job state, the record stays `running`. That is correct: a client that loads that slot sees a generation that is still running.
422- A submit that fails records a terminal `error` run. So a reload shows the failure, not an empty slot.