feat(persistence): client-side generation resume snapshot #997
- examples/ts-react-chat/src/routes/generations.image.tsx lines 119 to 125OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -71,0 +105,21 @@105+ </p>106+ ) : snapshot ? (107+ <p className="text-gray-400">108+ Last run:{' '}109+ <span className="text-white">110+ {snapshot.status}111+ {snapshot.error ? ` — ${snapshot.error.message}` : ''}112+ {snapshot.result?.model ? ` (${snapshot.result.model})` : ''}113+ </span>114+ </p>115+ ) : (116+ <p className="text-gray-500">No persisted run yet.</p>117+ )}118+ </div>119+ <ImageGenerationUI120+ {...hookReturn}121+ prompt={prompt}122+ setPrompt={setPrompt}123+ numberOfImages={numberOfImages}124+ setNumberOfImages={setNumberOfImages}125+ />@@ -330,0 +587,21 @@587+export function createGenerationResultSnapshot(588+ value: unknown,589+): GenerationResultSnapshot | undefined {590+ if (!isObject(value)) return undefined591+592+ const artifacts = collectArtifactRefs(Reflect.get(value, 'artifacts'))593+ const snapshot: GenerationResultSnapshot = {}594+ const id = stringField(value, 'id')595+ const model = stringField(value, 'model')596+ const status = stringField(value, 'status')597+ const jobId = stringField(value, 'jobId')598+ if (id) snapshot.id = id599+ if (model) snapshot.model = model600+ if (status) snapshot.status = status601+ if (jobId) snapshot.jobId = jobId602+ const expiresAt = Reflect.get(value, 'expiresAt')603+ if (typeof expiresAt === 'string') {604+ snapshot.expiresAt = expiresAt605+ } else if (expiresAt instanceof Date) {606+ snapshot.expiresAt = expiresAt.toISOString()607+ }@@ -145,4 +176,20 @@176+ if (!disposedRef.current) optionsRef.current.onProgress?.(p, m)145177 },146178 onChunk: (c: StreamChunk) => {147- optionsRef.current.onChunk?.(c)179+ if (!disposedRef.current) optionsRef.current.onChunk?.(c)180+ },181+ onResultChange: (r) => {182+ if (!disposedRef.current) setResult(r)183+ },184+ onLoadingChange: (l) => {185+ if (!disposedRef.current) setIsLoading(l)186+ },187+ onErrorChange: (e) => {188+ if (!disposedRef.current) setError(e)189+ },190+ onStatusChange: (s) => {191+ if (!disposedRef.current) setStatus(s)192+ },193+ onResumeSnapshotChange: (snapshot) => {194+ if (!disposedRef.current) setResumeSnapshot(snapshot)148195 },packages/ai-svelte/src/create-generation.svelte.ts lines 298 to 303OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -225,8 +284,20 @@225284 get status() {226285 return status227286 },228- generate: generate as (input: Record<string, any>) => Promise<void>,287+ generate,229288 stop,230289 reset,231290 dispose,232291 updateBody,292+ get resumeSnapshot() {293+ return resumeSnapshot294+ },295+ get resumeState() {296+ return resumeSnapshot?.resumeState ?? null297+ },298+ get pendingArtifacts() {299+ return resumeSnapshot?.pendingArtifacts ?? []300+ },301+ get resultArtifacts() {302+ return resumeSnapshot?.result?.artifacts ?? []303+ },packages/ai-vue/src/use-generate-video.ts lines 93 to 100OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -81,3 +90,11 @@8190 stop: () => void8291 /** Clear all state and return to idle */8392 reset: () => void93+ /** Lightweight generation resume snapshot, if one is available */94+ resumeSnapshot: DeepReadonly<ShallowRef<GenerationResumeSnapshot | undefined>>95+ /** Identity of the in-flight run while one is streaming, or null after it ends */96+ resumeState: DeepReadonly<ShallowRef<GenerationResumeState | null>>97+ /** Pending persisted artifact refs observed mid-run. Currently always empty: nothing emits `generation:artifacts` until the server-side artifact pipeline ships in a follow-up */98+ pendingArtifacts: DeepReadonly<ShallowRef<Array<GenerationPendingArtifact>>>99+ /** Persisted artifact refs from the final result. Currently always empty: results carry no artifacts until the server-side artifact pipeline ships in a follow-up */100+ resultArtifacts: DeepReadonly<ShallowRef<Array<PersistedArtifactRef>>>
- @@ -0,0 +139,21 @@139+}140+141+// Serve a stored artifact's bytes by id. This is a plain file endpoint: it142+// serves one stored file, it does not resume a run or rebuild a conversation.143+export async function GET(request: Request) {144+ const artifactId = new URL(request.url).searchParams.get('id')145+ if (!artifactId) return new Response('missing id', { status: 400 })146+147+ const artifact = await retrieveArtifact(persistence, artifactId)148+ if (!artifact) return new Response('not found', { status: 404 })149+150+ const blob = await retrieveBlob(persistence, artifact)151+ if (!blob) return new Response('not found', { status: 404 })152+153+ return new Response(blob.body ?? (await blob.arrayBuffer()), {154+ headers: {155+ 'content-type': artifact.mimeType,156+ 'content-length': String(artifact.size),157+ },158+ })159+}@@ -261,0 +325,21 @@325+ activity === 'tts' ||326+ activity === 'video' ||327+ activity === 'transcription'328+ ? activity329+ : undefined330+}331+332+function parseDataUrl(333+ value: string,334+): { mimeType: string; bytes: Uint8Array } | undefined {335+ const match = /^data:([^;,]+)?(;base64)?,(.*)$/s.exec(value)336+ if (!match) return undefined337+ const mimeType = match[1] || 'application/octet-stream'338+ const payload = decodeURIComponent(match[3] ?? '')339+ return {340+ mimeType,341+ bytes: match[2]342+ ? base64ToUint8Array(payload)343+ : new TextEncoder().encode(payload),344+ }345+}packages/ai-persistence/src/middleware.ts lines 403 to 404Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -261,0 +375,21 @@375+ const ext = extensionForMime(descriptor.mimeType)376+ return `${activity}-${descriptor.role}-${descriptor.mediaType ?? 'artifact'}-${index}.${ext}`377+}378+379+function sourcePartDescriptors(380+ part: unknown,381+ role: PersistedArtifactRole,382+ path: string,383+): Array<GenerationArtifactDescriptor> {384+ const record = objectValue(part)385+ const type = stringField(record ?? {}, 'type')386+ const source = objectValue(record?.source)387+ if (388+ !record ||389+ !source ||390+ (type !== 'image' && type !== 'audio' && type !== 'video')391+ ) {392+ return []393+ }394+ const sourceType = stringField(source, 'type')395+ const mimeType = stringField(source, 'mimeType') ?? `${type}/mpeg`packages/ai-persistence/src/middleware.ts lines 533 to 544Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -261,0 +515,21 @@515+ mediaType: 'audio',516+ mimeType:517+ stringField(output, 'contentType') ??518+ (format ? `audio/${format}` : 'audio/mpeg'),519+ bytes: base64ToUint8Array(audio),520+ })521+ }522+ }523+524+ if (activity === 'video' && typeof output.url === 'string') {525+ descriptors.push({526+ role: 'output',527+ path: 'video',528+ mediaType: 'video',529+ mimeType: 'video/mp4',530+ url: output.url,531+ jobId: stringField(output, 'jobId'),532+ expiresAt:533+ output.expiresAt instanceof Date ? output.expiresAt : undefined,534+ })535+ }@@ -261,0 +635,21 @@635+ 'application/octet-stream'636+ // Stream the body straight into the blob store instead of buffering the637+ // whole artifact in memory. `size` is left 0 (unknown up front); the store638+ // records the actual byte length as it drains the stream. Fall back to639+ // buffering only when the response has no body to stream.640+ if (response.body) {641+ return {642+ body: response.body,643+ size: 0,644+ mimeType,645+ externalUrl: descriptor.url,646+ }647+ }648+ const body = await response.arrayBuffer()649+ return {650+ body,651+ size: body.byteLength,652+ mimeType,653+ externalUrl: descriptor.url,654+ }655+ }
- @@ -0,0 +115,21 @@115+ // withGenerationPersistence records the job's status, result metadata, and116+ // usage in the jobs store. durability records the stream so a reload can117+ // re-attach to it.118+ return toServerSentEventsResponse(stream, {119+ durability: { adapter: durability },120+ })121+}122+123+export function GET(request: Request): Response | Promise<Response> {124+ const durability = memoryStream(request)125+ // A reconnecting client carries a resume cursor (Last-Event-ID / ?offset and126+ // X-Run-Id / ?runId). Replay the durability log so a run still streaming127+ // finishes in place. No provider call here.128+ if (durability.resumeFrom() !== null) {129+ return resumeServerSentEventsResponse({ adapter: durability })130+ }131+ // Otherwise this is the mount-time hydration GET (?threadId): return the last132+ // generation job for the thread. Guard access in multi-user apps with the133+ // `authorize` option (session → owned thread/job).134+ return reconstructGeneration(persistence, request)135+}@@ -455,0 +466,21 @@466+ headers: Record<string, string>,467+ credentials: RequestCredentials,468+ threadId: string,469+): Promise<GenerationHydrationResult> {470+ const response = await fetchClient(withSearchParams(url, { threadId }), {471+ method: 'GET',472+ headers: { Accept: 'application/json', ...headers },473+ credentials,474+ })475+ assertResponseOk(response)476+ const data = (await response.json()) as {477+ resumeSnapshot?: GenerationHydrationResult['resumeSnapshot']478+ activeRun?: { runId?: unknown } | null479+ }480+ const activeRun =481+ data.activeRun && typeof data.activeRun.runId === 'string'482+ ? { runId: data.activeRun.runId }483+ : null484+ return {485+ resumeSnapshot: data.resumeSnapshot ?? null,486+ activeRun,@@ -0,0 +116,21 @@116+ async head(key) {117+ const obj = await bucket.head(key)118+ return obj ? toRecord(obj) : null119+ },120+121+ async delete(key) {122+ await bucket.delete(key)123+ },124+125+ async list(options) {126+ const page = await bucket.list({127+ ...(options?.prefix !== undefined ? { prefix: options.prefix } : {}),128+ ...(options?.cursor !== undefined ? { cursor: options.cursor } : {}),129+ ...(options?.limit !== undefined ? { limit: options.limit } : {}),130+ // R2 omits httpMetadata/customMetadata from list rows unless asked.131+ include: ['httpMetadata', 'customMetadata'],132+ })133+ return {134+ objects: page.objects.map(toRecord),135+ ...(page.truncated ? { cursor: page.cursor, truncated: true } : {}),136+ }@@ -112,0 +145,21 @@145+### Mode B — server-driven (`persistence: true`)146+147+```tsx148+const image = useGenerateImage({149+ threadId, // stable — the key the last generation is hydrated under (falls back to id)150+ connection: fetchServerSentEvents('/api/generate/image'),151+ persistence: true,152+})153+// After a reload: image.resumeSnapshot is the last generation for `threadId`,154+// fetched from the server — nothing was cached in the browser.155+```156+157+Nothing is cached client-side. On mount the client hydrates the **last158+ generation** for its `threadId` from the server via the connection's159+ `hydrateGeneration` handler (the SSE/HTTP adapters issue a `GET` with160+ `?threadId=` to the same endpoint URL) and repaints that snapshot.161+The server `GET` returns `reconstructGeneration(persistence, request)` from162+ `@tanstack/ai-persistence` — it resolves the job by `?jobId=` (preferred) or163+ the latest job linked to `?threadId=`, and needs `stores.jobs`. Pair it with164+ `withGenerationPersistence` on the generation route. See165+ `ai-core/media-generation` and `ai-persistence`.packages/ai/skills/ai-core/media-generation/SKILL.md lines 609 to 618Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -565,0 +591,21 @@591+ return toServerSentEventsResponse(592+ generateImage({593+ adapter: openaiImage('gpt-image-1'),594+ prompt,595+ threadId, // optional link recorded on the job + artifacts596+ stream: true,597+ middleware: [withGenerationPersistence(persistence)],598+ }),599+ )600+}601+602+// Serve the stored bytes back (GET /api/artifacts?id=…):603+export async function GET(req: Request) {604+ const id = new URL(req.url).searchParams.get('id') ?? ''605+ const record = await retrieveArtifact(persistence, id)606+ if (!record) return new Response('Not found', { status: 404 })607+ const blob = await retrieveBlob(persistence, record)608+ if (!blob?.body) return new Response('Not found', { status: 404 })609+ return new Response(blob.body, {610+ headers: { 'content-type': record.mimeType },611+ })testing/e2e/src/routes/api.generation-persistence-server.ts lines 66 to 76OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +56,21 @@56+ value: {57+ id: 'image-1',58+ model: 'mock-image-model',59+ images: [{ b64Json: TINY_PNG_B64 }],60+ },61+ threadId,62+ runId,63+ timestamp: Date.now(),64+ } as StreamChunk65+ yield {66+ type: 'RUN_FINISHED',67+ threadId,68+ runId,69+ timestamp: Date.now(),70+ } as StreamChunk71+ // The run finished: record the job the way `withGenerationPersistence`72+ // would, so the GET hydrate below can restore it after a reload.73+ completedByThread.set(threadId, {74+ id: 'image-1',75+ model: 'mock-image-model',76+ })
- @@ -254,5 +254,16 @@254254 "label": "Client Persistence",255255 "to": "persistence/client-persistence",256256 "addedAt": "2026-07-22",257- "updatedAt": "2026-07-27"257+ "updatedAt": "2026-07-28"258+ },259+ {260+ "label": "Generation Persistence",261+ "to": "persistence/generation-persistence",262+ "addedAt": "2026-07-28",263+ "updatedAt": "2026-07-28"264+ },265+ {266+ "label": "Keep Generated Files",267+ "to": "persistence/keep-generated-files",268+ "addedAt": "2026-07-28"258269 },docs/media/audio-generation.md lines 164 to 167Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -161,3 +161,7 @@161161 other media hooks — see [Generation Hooks](./generation-hooks) for the full162162 shape.163163164+ **Note:** For long tracks, keep the run's status and result across a reload or165+ a dropped connection — and the audio after the provider's URL expires — with166+ [Generation Persistence](../persistence/generation-persistence).167+@@ -70,3 +70,8 @@7070 **`true`** is server-authoritative.7171 **`false`** (or omitted) is off: messages live in memory only and a reload starts empty.727273+The generation hooks (`useGenerateImage` / `useGenerateVideo` / …) make the same74+choice: `persistence: true` is server-driven and a storage adapter is75+client-driven, so a long media run survives a reload the way a conversation does.76+See [Generation persistence](./generation-persistence) for the generation-specific77+setup.@@ -0,0 +1,20 @@1+---2+title: Keep Generated Files3+id: keep-generated-files4+---5+6+# Keep Generated Files7+8+Provider URLs for generated media expire. A Sora clip, a batch of images, a long9+audio track — the model hands you a URL that stops working after a while, and10+once it does the output is gone. To keep the output, save the generated bytes to11+your own storage and serve them from your own origin, where they outlive the12+provider's link.13+14+This is a server-side opt-in that layers on **top of** the `jobs` store15+[Generation persistence](./generation-persistence) already requires. Byte storage16+adds two more stores: an `artifacts` store (metadata) and a `blobs` store (the17+bytes). They are a both-or-neither pair — provide both and18+`withGenerationPersistence` writes each generated file's bytes to the blob store,19+records an `ArtifactRecord`, and attaches durable references to the result and the20+job record; provide neither and only the job record is kept.@@ -0,0 +56,21 @@56+ const stream = generateImage({57+ adapter: openaiImage('gpt-image-2'),58+ prompt: input.prompt,59+ stream: true,60+ middleware: [withGenerationPersistence(persistence)],61+ })62+63+ return toServerSentEventsResponse(stream)64+}65+66+// Serve a stored artifact's bytes by id. This is a plain file endpoint: it67+// serves one stored file, it does not resume a run or rebuild a conversation.68+export async function GET(request: Request) {69+ const artifactId = new URL(request.url).searchParams.get('id')70+ if (!artifactId) return new Response('missing id', { status: 400 })71+72+ const artifact = await retrieveArtifact(persistence, artifactId)73+ if (!artifact) return new Response('not found', { status: 404 })74+75+ const blob = await retrieveBlob(persistence, artifact)76+ if (!blob) return new Response('not found', { status: 404 })docs/persistence/keep-generated-files.md lines 87 to 93OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +73,21 @@73+ if (!artifact) return new Response('not found', { status: 404 })74+75+ const blob = await retrieveBlob(persistence, artifact)76+ if (!blob) return new Response('not found', { status: 404 })77+78+ return new Response(blob.body ?? (await blob.arrayBuffer()), {79+ headers: {80+ 'content-type': artifact.mimeType,81+ 'content-length': String(artifact.size),82+ },83+ })84+}85+```86+87+`memoryPersistence` keeps everything in process memory, which is right for88+development and tests; point `jobs` / `artifacts` / `blobs` at a durable backend89+for production. Control what gets captured with `withGenerationPersistence`'s90+`extractArtifacts` (return your own descriptors) and `nameArtifact` (name each91+file) options. On the client, the observed references show up on the generation92+hook as `resultArtifacts` (and `pendingArtifacts` while streaming), so the UI93+can link straight to this serve route.docs/persistence/keep-generated-files.md lines 91 to 93OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +73,21 @@73+ if (!artifact) return new Response('not found', { status: 404 })74+75+ const blob = await retrieveBlob(persistence, artifact)76+ if (!blob) return new Response('not found', { status: 404 })77+78+ return new Response(blob.body ?? (await blob.arrayBuffer()), {79+ headers: {80+ 'content-type': artifact.mimeType,81+ 'content-length': String(artifact.size),82+ },83+ })84+}85+```86+87+`memoryPersistence` keeps everything in process memory, which is right for88+development and tests; point `jobs` / `artifacts` / `blobs` at a durable backend89+for production. Control what gets captured with `withGenerationPersistence`'s90+`extractArtifacts` (return your own descriptors) and `nameArtifact` (name each91+file) options. On the client, the observed references show up on the generation92+hook as `resultArtifacts` (and `pendingArtifacts` while streaming), so the UI93+can link straight to this serve route.@@ -0,0 +79,21 @@79+ headers: {80+ 'content-type': artifact.mimeType,81+ 'content-length': String(artifact.size),82+ },83+ })84+}85+```86+87+`memoryPersistence` keeps everything in process memory, which is right for88+development and tests; point `jobs` / `artifacts` / `blobs` at a durable backend89+for production. Control what gets captured with `withGenerationPersistence`'s90+`extractArtifacts` (return your own descriptors) and `nameArtifact` (name each91+file) options. On the client, the observed references show up on the generation92+hook as `resultArtifacts` (and `pendingArtifacts` while streaming), so the UI93+can link straight to this serve route.94+95+## Where to go next96+97+[Generation persistence](./generation-persistence): the two-mode record that98+ survives a reload or a dropped connection, and the `jobs` store byte storage99+ builds on.
- @@ -0,0 +1,18 @@1+---2+'@tanstack/ai': minor3+'@tanstack/ai-utils': minor4+'@tanstack/ai-persistence': minor5+'@tanstack/ai-client': minor6+'@tanstack/ai-event-client': minor7+'@tanstack/ai-react': minor8+'@tanstack/ai-solid': minor9+'@tanstack/ai-vue': minor10+'@tanstack/ai-svelte': minor11+'@tanstack/ai-angular': minor12+---13+14+Add generation persistence, mirroring chat: media generation runs survive a reload or dropped connection, restoring transparently into the normal hook fields, with optional durable storage of the generated bytes.15+16+**Generation job store (server).** `withGenerationPersistence` records each run in a dedicated `jobs` (`GenerationJobStore`) store, keyed by the job's `jobId` (`runId`), with `threadId` only an optional link — it no longer overloads the chat `RunStore`. The record holds the activity/provider/model, lifecycle status, result metadata, and (when byte storage is on) the durable artifact refs. `memoryPersistence()` ships an in-memory `jobs` store, and `defineGenerationJobStore` / `defineArtifactStore` / `defineBlobStore` type a custom store inline the way `defineMessageStore` / `defineRunStore` already do.17+18+**Server-side load (`reconstructGeneration`).** A new `reconstructGeneration(persistence, request, options?)` server helper — the generation parallel of `reconstructChat` — reads a `?jobId=` (or `?threadId=`) from the request, authorizes it via an optional `authorize` callback, and returns `{ resumeSnapshot, activeRun }` JSON so a server-authoritative client restores the last run on mount. Requires the `jobs` store.docs/persistence/generation-persistence.md lines 315 to 326OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +306,21 @@306+`@tanstack/ai-durable-stream`, where requests span processes.307+308+A full page reload is different: the hooks never start or resume a run on309+mount, and the record alone cannot re-attach to the stream — it records that a310+run was in flight, not a stream position. After a reload, a non-null311+`resumeState` is informational ("a run was still going when the page closed").312+See [Resumable Streams](../resumable-streams/overview) for the durability313+contract, production adapters, and the one-time-side-effects note.314+315+## What the record holds316+317+The generation record — whether hydrated from the server or read from the318+browser snapshot — holds run identity and result metadata (ids, model, status,319+a video `jobId`, an expiry timestamp), never the generated bytes. On its own it320+does not carry a usable media URL, so a reload restores `status` and `error`321+while `result` stays `null`. To bring the media back too, persist the bytes on322+the server with an `artifacts` + `blobs` backend and stamp a durable serve URL323+onto each ref with `withGenerationPersistence`'s `artifactUrl` (see324+[Keep generated files](./keep-generated-files)). Those durable refs travel on325+the record, so the restored `result` is rebuilt with its media resolved to your326+own origin.
tombeckenham closed this
Sign in to join this conversation.
Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
📝 Walkthrough
Walkthrough#
Generation persistence adds validated client resume snapshots, server-authoritative hydration, dedicated generation jobs, optional artifact/blob storage, framework integrations, documentation, and end-to-end coverage.
Changes#
Generation persistence
packages/ai-client/...packages/ai-persistence/...,packages/ai/src/activities/...,packages/ai-utils/...packages/ai-react/...,packages/ai-vue/...,packages/ai-solid/...,packages/ai-svelte/...,packages/ai-angular/...packages/*/tests/...,examples/...,docs/...,testing/e2e/...Estimated code review effort: 5 (Critical) | ~120 minutes
Possibly related PRs
Suggested reviewers:
alemtuzlak,jherr🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share