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

generation-persistence.md

451 lines16.4 KB

1---
2title: Generation Persistence
3id: generation-persistence
4---
5​
6Media generation takes time, and video can take minutes. If the user reloads the
7page or their connection drops mid-run, that run is easy to lose. Generation
8persistence keeps a small record of each run and restores it into the hook's
9normal `status` / `result` / `error` fields, so a reload reads exactly like a
10fresh run.
11​
12Reach for it when a run is long enough that a reload matters: video, batch
13images, long audio, a big transcription. For a quick one-shot image you show and
14forget, skip it.
15​
16## The id it all hangs on
17​
18All of this keys on `threadId`, and for a generation that is a **slot**, not a
19conversation: a stable, app-chosen name for the place successive runs fill
20(`product-7-hero`, `video-9-start-frame`). Each run gets its own `runId` and its
21own record, and restore hands back the newest run in the slot.
22​
23Pass the same string to the hook and to the activity, and keep it stable across
24reloads. The middleware reads it off the activity, so you never repeat it there.
25​
26[Id map](./id-map) covers how to choose one and what goes wrong when it drifts.
27​
28## Turn it on
29​
30`persistence` is a boolean:
31​
32- **`persistence: true`**: the server keeps the record. On mount the hook
33 hydrates the last run for its `threadId` and repaints it.
34- **omitted / `false`**: off. The run lives in memory only, and a reload starts
35 empty.
36​
37The record lives on the server, written by `withGenerationPersistence`, which
38needs a `generationRuns` store (a `GenerationRunStore` keyed by the run's own
39`runId`, with the `threadId` recorded as the slot the run belongs to).
40`memoryPersistence()` ships one out of the box; see
41[Build a generation adapter](./build-your-own-generation-adapter) for
42your own backend.
43​
44The browser caches nothing, so a generation's history is never duplicated into
45local storage and a second device sees the same run.
46​
47The record never holds the generated bytes, so on its own a reload restores
48`status` and `error` while `result` stays `null`. To bring the media back too,
49add server byte storage: see [Keep generated files](./keep-generated-files).
50​
51The record's lifecycle is small, one status field the middleware advances:
52​
53```mermaid
54stateDiagram-v2
55 [*] --> running : generation starts (idempotent createOrResume)
56 running --> completed : finish, result metadata saved
57 running --> failed : error
58 running --> interrupted : abort
59 completed --> [*]
60 failed --> [*]
61 interrupted --> [*]
62```
63​
64A restored `interrupted` run surfaces to the hook as an error. An aborted
65generation cannot be resumed, only re-run.
66​
67## Wire the route
68​
69One `POST` that runs the generation, and a `GET` on the same route that answers
70the mount-time hydration with `reconstructGeneration`:
71​
72```ts group=generation-server-driven
73import {
74 generateImage,
75 generationParamsFromRequest,
76 memoryStream,
77 resumeServerSentEventsResponse,
78 toServerSentEventsResponse,
79} from '@tanstack/ai'
80import { openaiImage } from '@tanstack/ai-openai'
81import {
82 memoryPersistence,
83 reconstructGeneration,
84 withGenerationPersistence,
85} from '@tanstack/ai-persistence'
86​
87const persistence = memoryPersistence()
88​
89export async function POST(request: Request) {
90 const durability = memoryStream(request)
91 const { input, threadId } = await generationParamsFromRequest('image', request)
92​
93 if (typeof input.prompt !== 'string') {
94 throw new Error('This endpoint accepts text image prompts only.')
95 }
96​
97 // Persistence requires the scope, so a request without one cannot be served:
98 // the run would be filed nowhere the client could hydrate from.
99 if (threadId === undefined) {
100 return new Response('`threadId` is required', { status: 400 })
101 }
102​
103 const stream = generateImage({
104 adapter: openaiImage('gpt-image-2'),
105 prompt: input.prompt,
106 // The same scope the GET below finds the last run for.
107 threadId,
108 stream: true,
109 // `artifactUrl` makes the restored media render from your own origin. It is
110 // optional; see Keep generated files for the serve route it points at.
111 middleware: [
112 withGenerationPersistence(persistence, {
113 artifactUrl: (ref) => `/api/generate/image/artifact?id=${ref.artifactId}`,
114 }),
115 ],
116 })
117​
118 return toServerSentEventsResponse(stream, {
119 durability: { adapter: durability },
120 })
122​
123export function GET(request: Request): Response | Promise<Response> {
124 const durability = memoryStream(request)
125 // A reconnecting client carries a resume cursor; replay the live stream.
126 if (durability.resumeFrom() !== null) {
127 return resumeServerSentEventsResponse({ adapter: durability })
128 }
129 // Otherwise this is the mount-time hydration (?threadId). In multi-user apps
130 // pass reconstructGeneration's `authorize` option so a guessed threadId can't
131 // read another user's generation.
132 return reconstructGeneration(persistence, request)
134```
135​
136On the client, pass a connection, a stable `threadId`, and `persistence: true`.
137The hook is transparent: a reload repaints the last run into the same fields a
138fresh run uses, the way `useChat` restores into `messages`:
139​
140```tsx
141import { fetchServerSentEvents, useGenerateImage } from '@tanstack/ai-react'
142​
143const connection = fetchServerSentEvents('/api/generate/image')
144​
145export function HeroImageGenerator({ threadId }: { threadId: string }) {
146 const image = useGenerateImage({
147 threadId,
148 connection,
149 persistence: true,
150 })
151​
152 return (
153 <section>
154 <button
155 type="button"
156 disabled={image.isLoading}
157 onClick={() =>
158 void image.generate({ prompt: 'A glass cabin in a pine forest' })
159 }
160 >
161 Generate
162 </button>
163​
164 {image.status === 'success' ? (
165 <p>Last run finished{image.result?.id ? ` (${image.result.id})` : ''}.</p>
166 ) : null}
167 {image.error ? <p>Last run failed: {image.error.message}</p> : null}
168 {image.result?.images.map((img, index) =>
169 img.url ? <img key={index} src={img.url} alt="" /> : null,
170 )}
171 </section>
172 )
174```
175​
176Because the server stamps a durable `artifactUrl`, the restored
177`image.result.images[i].url` serves from your own origin, so the image renders
178after a reload just as it did live. You never fetch or seed anything: the thread
179id is the stable key, and a reload or the same thread on another device follow
180the identical path.
181​
182If a run is **still generating** when the connection drops or the page reloads,
183the client re-attaches to it and finishes it in place, exactly like `useChat`.
184The `durability` adapter on `toServerSentEventsResponse` plus the `GET` resume
185branch above are all it needs: on mount `reconstructGeneration` reports the live
186run and the client tails it through the durability log. In production, swap
187`memoryStream` for `durableStream` from `@tanstack/ai-durable-stream`, where
188requests span processes. See [Resumable Streams](../resumable-streams/overview).
189​
190```mermaid
191sequenceDiagram
192 participant Hook as useGenerateImage (persistence: true)
193 participant Route as GET /api/generate/image
194 participant Runs as generationRuns store
195 participant Log as Delivery log
196​
197 Note over Hook: mount (or reload) with a threadId
198 Hook->>Route: ?threadId=…
199 Route->>Runs: reconstructGeneration, latest run for the thread
200 Runs-->>Route: run record (status, result metadata, artifact refs)
201 Route-->>Hook: status / error / result repainted
202 alt run still generating
203 Hook->>Route: ?runId=…&offset=-1
204 Route->>Log: resumeServerSentEventsResponse
205 Log-->>Hook: replay + live tail, run finishes in place
206 end
207```
208​
209## Server functions / direct
210​
211The HTTP adapters above implement hydration and rejoin for you. With
212[TanStack Start](https://tanstack.com/start) server functions (or any direct,
213in-process call) there is no `GET` route to hang them on, so you supply the
214two handlers yourself (one for mount-time hydration, one for replaying an
215in-flight run) and pass them as options alongside the `fetcher` (or to
216`stream()` / `rpcStream()`).
217​
218Three server functions cover it: one runs the generation, one answers
219hydration with `getGenerationHydration`, and one replays the run's durability
220log with `replayRunStream`. Both streaming functions return the same thing,
221an SSE `Response` from `toServerSentEventsResponse`, so the client decodes
222them the same way:
223​
224```ts group=generation-server-functions
225// server/image.ts
226import { createServerFn } from '@tanstack/react-start'
227import { z } from 'zod'
228import {
229 generateImage,
230 memoryStream,
231 replayRunStream,
232 toServerSentEventsResponse,
233} from '@tanstack/ai'
234import { openaiImage } from '@tanstack/ai-openai'
235import {
236 getGenerationHydration,
237 memoryPersistence,
238 withGenerationPersistence,
239} from '@tanstack/ai-persistence'
240import type { ImageGenerateInput } from '@tanstack/ai-client'
241​
242const persistence = memoryPersistence()
243​
244export const generateImageFn = createServerFn({ method: 'POST' })
245 .inputValidator((data: ImageGenerateInput & { threadId: string }) => data)
246 .handler(({ data: { threadId, ...input } }) => {
247 if (typeof input.prompt !== 'string') {
248 throw new Error('This endpoint accepts text image prompts only.')
249 }
250 // One run id for both the durability log and the run record, so the
251 // rejoin below replays exactly the run hydration reports.
252 const runId = crypto.randomUUID()
253 const stream = generateImage({
254 adapter: openaiImage('gpt-image-2'),
255 prompt: input.prompt,
256 threadId,
257 runId,
258 stream: true,
259 // `artifactUrl` is optional; see Keep generated files.
260 middleware: [
261 withGenerationPersistence(persistence, {
262 artifactUrl: (ref) => `/api/generate/image/artifact?id=${ref.artifactId}`,
263 }),
264 ],
265 })
266 return toServerSentEventsResponse(stream, {
267 durability: { adapter: memoryStream({ runId }) },
268 })
269 })
270​
271/**
272 * The wire shape for mount hydration, parsed with Zod so that:
273 * - TanStack Start gets a JSON-serializable return type (the run record's
274 * `result` is loosely typed, and Start's serializer rejects `unknown`)
275 * - the stored record is validated before it crosses the wire
276 */
277const hydrationSchema = z.object({
278 resumeSnapshot: z
279 .object({
280 schemaVersion: z.literal(1),
281 resumeState: z
282 .object({ threadId: z.string(), runId: z.string() })
283 .nullable(),
284 status: z.enum(['idle', 'running', 'complete', 'error']),
285 // `z.any()` (not `z.unknown()`) so Start's serializer accepts the values.
286 result: z.record(z.string(), z.any()).optional(),
287 error: z
288 .object({ message: z.string(), code: z.string().optional() })
289 .optional(),
290 activity: z.string().optional(),
291 })
292 .nullable(),
293 activeRun: z.object({ runId: z.string() }).nullable(),
294})
295​
296export const getImageHydrationFn = createServerFn({ method: 'GET' })
297 .inputValidator(z.string().min(1))
298 .handler(async ({ data: threadId }) => {
299 // `getGenerationHydration` does no auth, so gate on your session here, the
300 // way you would pass `authorize` to `reconstructGeneration`.
301 return hydrationSchema.parse(
302 await getGenerationHydration(persistence, threadId),
303 )
304 })
305​
306export const joinImageRunFn = createServerFn({ method: 'GET' })
307 .inputValidator(z.string().min(1))
308 .handler(({ data: runId }) =>
309 // Same SSE envelope `generateImageFn` returns, so one client-side decoder
310 // covers both.
311 toServerSentEventsResponse(replayRunStream(memoryStream({ runId }))),
312 )
313```
314​
315On the client, pass the two handlers next to the `fetcher`. A reload now
316hydrates the last run through `getImageHydrationFn`, and a run still
317generating is tailed to completion through `joinImageRunFn`. `joinRun` yields
318`StreamChunk`s rather than a `Response`, so decode the SSE body yourself and
319apply the `signal` there. The server function itself takes only its `data`:
320​
321```tsx
322import { useGenerateImage } from '@tanstack/ai-react'
323import type { StreamChunk } from '@tanstack/ai'
324import {
325 generateImageFn,
326 getImageHydrationFn,
327 joinImageRunFn,
328} from './server/image'
329​
330/** Decode an SSE `Response` from a server function into `StreamChunk`s. */
331async function* chunksFromSseResponse(
332 response: Response,
333 signal?: AbortSignal,
334): AsyncGenerator<StreamChunk> {
335 if (!response.ok) throw new Error(`Join failed: ${response.status}`)
336 const reader = response.body?.getReader()
337 if (!reader) return
338 const decoder = new TextDecoder()
339 let buffer = ''
340 try {
341 while (!signal?.aborted) {
342 const { done, value } = await reader.read()
343 if (done) break
344 buffer += decoder.decode(value, { stream: true })
345 const lines = buffer.split('\n')
346 buffer = lines.pop() ?? ''
347 for (const line of lines) {
348 if (!line.startsWith('data:')) continue
349 const data = line.slice(5).trimStart()
350 // `JSON.parse` returns the chunk the server encoded.
351 if (data) yield JSON.parse(data)
352 }
353 }
354 } finally {
355 reader.releaseLock()
356 }
358​
359export function HeroImageGenerator({ threadId }: { threadId: string }) {
360 const image = useGenerateImage({
361 threadId,
362 fetcher: (input) => generateImageFn({ data: { ...input, threadId } }),
363 hydrateGeneration: (id) => getImageHydrationFn({ data: id }),
364 joinRun: async function* (runId, signal) {
365 const response = await joinImageRunFn({ data: runId })
366 if (!(response instanceof Response)) {
367 throw new Error('joinImageRunFn should return an SSE Response')
368 }
369 yield* chunksFromSseResponse(response, signal)
370 },
371 persistence: true,
372 })
373 // The render is identical to the HTTP example above.
374 return <p>{image.status}</p>
376```
377​
378A non-streaming `fetcher` (a plain `Promise<ImageGenerationResult>` rather than
379an SSE `Response`) has no in-flight stream to rejoin, so it needs only
380`hydrateGeneration`. Drop `joinRun` and the decoder with it.
381​
382A restored run that was still generating but has **no** `joinRun` handler to
383tail it surfaces as an interrupted error (it cannot be resumed, only re-run)
384instead of hanging on `generating` forever.
385​
386The same handlers fit the lightweight connection adapters directly,
387`stream(factory, { hydrateGeneration, joinRun })` and
388`rpcStream(call, { hydrateGeneration, joinRun })`, for in-process or RPC
389transports; they also accept a chat `hydrate` handler for `useChat`'s
390server-driven persistence.
391​
392## What a reload restores
393​
394Two things to keep in mind, whichever wiring you used:
395​
396- **The hook is transparent.** After a reload it repaints `status`
397 (`'idle'` / `'generating'` / `'success'` / `'error'`), `error`, and `result`
398 just like a live run. There is no snapshot field to render yourself.
399- **`result` needs byte storage to come back.** The run record holds result
400 metadata, never the media bytes, so on its own a reload restores `status` and
401 `error` while `result` stays `null`. Add byte storage and `artifactUrl`
402 ([Keep generated files](./keep-generated-files)) and the restored `result` is
403 rebuilt, its media served from your own origin.
404​
405## Non-streaming video is two calls
406​
407`generateVideo({ stream: true })` runs the whole create → poll → complete
408lifecycle inside one call, so persistence sees one run and nothing here applies.
409​
410Without `stream: true` it is two calls, and the video does not exist when the
411first one returns:
412​
413```ts
414import { generateVideo, getVideoJobStatus } from '@tanstack/ai'
415import {
416 memoryPersistence,
417 withGenerationPersistence,
418} from '@tanstack/ai-persistence'
419import { openaiVideo } from '@tanstack/ai-openai'
420​
421const persistence = memoryPersistence()
422const adapter = openaiVideo('sora-2')
423const middleware = [withGenerationPersistence(persistence)]
424const threadId = 'product-7-launch-clip'
425​
426// Opens the run. Status `running`, and there is no video yet.
427const { jobId } = await generateVideo({
428 adapter,
429 prompt: 'A cat chasing a dog in a sunny park',
430 threadId,
431 middleware,
432})
433​
434// Completes that same run. This is what writes the video and its artifacts.
435const status = await getVideoJobStatus({ adapter, jobId, threadId, middleware })
436```
437​
438Pass the same `threadId` and `middleware` to both. **The `jobId` is the whole
439correlation**: the run id is derived from it, so the poll finds the run the
440submit opened without you storing anything, even from a different request or
441process. There is no run id to thread.
442​
443Until a poll observes a terminal job state the record stays `running`, which is
444the truth: a client hydrating that slot sees a generation still in flight. A
445submission that fails records a terminal `error` run instead, so a reload shows
446the failure rather than an empty slot.
447​
448## Going further
449​
450- [Keep generated files](./keep-generated-files): store the generated bytes so
451 the media itself survives, not just the record.