Skip to content
Source
Sign inSign up
TanStack/ai

feat(persistence): client-side generation resume snapshot #997

Closedtombeckenhamwants to merge 33 commits intomain fromrefs/pull/997/headopened View on GitHub

tombeckenhamcommented

🎯 Changes

Generation persistence — the media-generation parallel of chat persistence. A media run (image, video, audio, TTS, transcription, summarize) now survives a page reload or a dropped connection, restoring transparently into the normal hook fields, with optional durable storage of the generated bytes.

Split out of #987 and rebuilt on the current feat/persistence-core. The previously-stacked byte-storage half has been folded in, so this is now the whole feature in one PR.

The shape

A generation run is recorded in its own store, keyed by its runId (the same AG-UI run id the client sends), with threadId an optional link — it no longer overloads the chat RunStore. On the client, the hook picks a mode exactly the way useChat does:

// Client-driven: the browser holds a lightweight snapshot under `generation:<id>`.
useGenerateImage({ id: 'hero', connection, persistence: localStoragePersistence() })

// Server-driven: nothing is cached; the last run for `threadId` is fetched on mount.
useGenerateImage({ threadId, connection, persistence: true })

Restore is invisible. There is no resumeSnapshot / pendingArtifacts / resultArtifacts hook field — a reload repaints result / status / error as if the run had just finished. resumeState carries the in-flight run identity only.

Crucially, this restores a record, not provider work: generation still only begins when generate(...) is called, and nothing is ever restarted. A run that is still streaming is re-attached and finished in place, via the connection's joinRun durability replay — the same mechanism useChat uses.

Server

  • withGenerationPersistence records each run in a dedicated generationRuns (GenerationRunStore) store: activity/provider/model, lifecycle status, result metadata, and — when byte storage is on — the durable artifact refs.
  • reconstructGeneration(persistence, request, options?) is the generation parallel of reconstructChat: it reads ?runId= (preferred) or the latest run linked to ?threadId=, authorizes via authorize, and returns { resumeSnapshot, activeRun } JSON for a server-authoritative client to hydrate from.
  • Byte storage (opt-in, layered on top): provide both an artifacts (ArtifactStore) and a blobs (BlobStore) store and the middleware writes each generated file's bytes under artifacts/<runId>/<artifactId>, records an ArtifactRecord, and attaches PersistedArtifactRefs to the result and the run record. The new artifactUrl option stamps a durable app-origin serve URL onto each ref and rewrites the live result's media URL to it, so live and restored results both render from your origin instead of the provider's expiring link. retrieveArtifact / retrieveBlob (and the shared artifactBlobKey) serve the bytes back; extraction is customizable via extractArtifacts / nameArtifact.
  • memoryPersistence() ships in-memory generationRuns / artifacts / blobs; defineGenerationRunStore / defineArtifactStore / defineBlobStore type a custom store inline the way defineMessageStore / defineRunStore already do.

Client

Generation hooks (useGenerateImage, useGenerateVideo, useGenerateAudio, useGenerateSpeech, useGeneration, useSummarize, useTranscription, and the Solid/Vue/Svelte/Angular equivalents) take the same persistence option chat does. The option reuses the ChatStorageAdapter contract, so localStoragePersistence / sessionStoragePersistence / indexedDBPersistence work for generations too with no type argument — a bare call is correct on either side. Untrusted snapshots are validated on read with the new parseGenerationResumeSnapshot.

With byte storage configured, a restored result is rebuilt whole, its media resolved to the durable serve URL and its refs on result.artifacts. Without it, status / error restore and result stays null — a client snapshot never holds bytes.

The base generation return types (UseGenerationReturn / CreateGenerationReturn / InjectGenerationResult) also gained a defaulted TInput generic across all five frameworks, so generate is precisely typed (input: TInput) => Promise<void>. That deleted the unsound internal narrow-to-wide casts and every wrapper-level generate as cast — twenty-five in total — with existing single-generic references unaffected.

Packages

  • @tanstack/ai-persistence — GenerationRunStore, reconstructGeneration, the byte-storage half (ArtifactStore / BlobStore / retrieveArtifact / retrieveBlob / artifactUrl), and the define* store helpers.
  • @tanstack/ai-client — the resume-snapshot reducer, parseGenerationResumeSnapshot, mount hydration (client store and server GET), result reconstruction from refs.
  • @tanstack/ai-utils — base64ToUint8Array.
  • framework hooks — react / solid / vue / svelte / angular.
  • @tanstack/ai — the generation activities gained threadId / runId options.

Docs, skills, examples, tests

  • Docs — new docs/persistence/generation-persistence.md and docs/persistence/keep-generated-files.md, plus updates across client-persistence, overview, controls, build-your-own-adapter, internals, the docs/media/* pages, docs/chat/streaming.md and docs/interrupts/overview.md (threads / runs / turns are now explained consistently). All kiira-verified.
  • Skills — ai-core/client-persistence, ai-core/media-generation, ai-persistence, and a new ai-persistence/build-cloudflare-artifact-store.
  • Example — examples/ts-react-chat wires generation persistence end to end (image + video via Grok Imagine).
  • E2E — generation-persistence.spec.ts (client-driven: stream → reload → transparent restore → reset) and generation-persistence-server.spec.ts (server-driven: persistence: true, restore from a ?threadId= GET, localStorage stays empty, no run auto-starts). Plus hydration/restore unit coverage in all five framework packages and the persistence package.

✅ Checklist

  • I have followed the steps in the Contributing guide.
  • I have tested this code locally with pnpm run test:pr.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Review Change Stack

      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_commits setting.

      Use the following commands to manage reviews:

      • @coderabbitai resume to resume automatic reviews.
      • @coderabbitai review to trigger a single review.

      Use the checkboxes below for quick actions:

      • ▶️ Resume reviews
      • 🔍 Trigger review
      📝 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

      Layer / File(s)Summary
      Snapshot contracts and client lifecycle
      packages/ai-client/...
      Adds snapshot reduction and validation, hydration, deduplicated persistence, terminal-state handling, reset cleanup, defensive getters, abort handling, and server-driven hydration.
      Server job and artifact persistence
      packages/ai-persistence/..., packages/ai/src/activities/..., packages/ai-utils/...
      Adds generation job, artifact, and blob contracts; in-memory stores; artifact extraction and retrieval; middleware result transforms; stable run/thread identifiers; and artifact stream events.
      Framework API integration
      packages/ai-react/..., packages/ai-vue/..., packages/ai-solid/..., packages/ai-svelte/..., packages/ai-angular/...
      Adds persistence options, seeded snapshots, typed generation inputs, disposal guards, and resume state across framework APIs.
      Validation, examples, and documentation
      packages/*/tests/..., examples/..., docs/..., testing/e2e/...
      Covers hydration precedence, no auto-start behavior, reset cleanup, artifact persistence, server and client modes, browser refresh, and generated-media retrieval.

      Estimated code review effort: 5 (Critical) | ~120 minutes

      Possibly related PRs

      • TanStack/ai#984: Shares the client storage-adapter contract used by generation persistence.
      • TanStack/ai#999: Directly overlaps the generation resume-snapshot and artifact persistence implementation.

      Suggested reviewers: alemtuzlak, jherr

      🚥 Pre-merge checks | ✅ 4 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 55.56% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (4 passed)
      Check nameStatusExplanation
      Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
      Title check✅ PassedRelated to the main feature, but it undersells the broader generation persistence and durable artifact restore work.
      Description check✅ PassedThe PR description matches the template and includes the changes, checklist, and release impact sections.
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Commit unit tests in branch `feat/generation-persistence-client`

      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
      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab)commented

      🚀 Changeset Version Preview

      17 package(s) bumped directly, 34 bumped as dependents.

      🟥 Major bumps

      PackageVersionReason
      @tanstack/ai-angular0.3.1 → 1.0.0Changeset
      @tanstack/ai-durable-stream0.0.0 → 1.0.0Changeset
      @tanstack/ai-memory0.0.0 → 1.0.0Changeset
      @tanstack/ai-openrouter0.15.10 → 1.0.0Changeset
      @tanstack/ai-persistence0.0.0 → 1.0.0Changeset
      @tanstack/ai-preact0.11.1 → 1.0.0Changeset
      @tanstack/ai-react0.18.1 → 1.0.0Changeset
      @tanstack/ai-sandbox0.2.4 → 1.0.0Changeset
      @tanstack/ai-solid0.15.1 → 1.0.0Changeset
      @tanstack/ai-svelte0.15.1 → 1.0.0Changeset
      @tanstack/ai-vue0.15.1 → 1.0.0Changeset
      @tanstack/ai-acp0.2.3 → 1.0.0Dependent
      @tanstack/ai-anthropic0.16.3 → 1.0.0Dependent
      @tanstack/ai-bedrock0.1.4 → 1.0.0Dependent
      @tanstack/ai-claude-code0.2.3 → 1.0.0Dependent
      @tanstack/ai-code-mode0.3.8 → 1.0.0Dependent
      @tanstack/ai-code-mode-skills0.3.11 → 1.0.0Dependent
      @tanstack/ai-codex0.2.3 → 1.0.0Dependent
      @tanstack/ai-elevenlabs0.2.34 → 1.0.0Dependent
      @tanstack/ai-fal0.9.12 → 1.0.0Dependent
      @tanstack/ai-gemini0.20.1 → 1.0.0Dependent
      @tanstack/ai-grok0.14.9 → 1.0.0Dependent
      @tanstack/ai-grok-build0.2.3 → 1.0.0Dependent
      @tanstack/ai-groq0.5.3 → 1.0.0Dependent
      @tanstack/ai-isolate-node0.1.47 → 1.0.0Dependent
      @tanstack/ai-isolate-quickjs0.1.47 → 1.0.0Dependent
      @tanstack/ai-mistral0.2.3 → 1.0.0Dependent
      @tanstack/ai-ollama0.8.16 → 1.0.0Dependent
      @tanstack/ai-openai0.17.1 → 1.0.0Dependent
      @tanstack/ai-opencode0.2.3 → 1.0.0Dependent
      @tanstack/ai-react-ui0.8.15 → 1.0.0Dependent
      @tanstack/ai-sandbox-cloudflare0.2.4 → 1.0.0Dependent
      @tanstack/ai-sandbox-daytona0.2.0 → 1.0.0Dependent
      @tanstack/ai-sandbox-docker0.2.0 → 1.0.0Dependent
      @tanstack/ai-sandbox-local-process0.2.0 → 1.0.0Dependent
      @tanstack/ai-sandbox-sprites0.2.1 → 1.0.0Dependent
      @tanstack/ai-sandbox-vercel0.2.0 → 1.0.0Dependent
      @tanstack/ai-solid-ui0.7.14 → 1.0.0Dependent
      @tanstack/openai-base0.9.9 → 1.0.0Dependent

      🟨 Minor bumps

      PackageVersionReason
      @tanstack/ai0.42.0 → 0.43.0Changeset
      @tanstack/ai-client0.22.1 → 0.23.0Changeset
      @tanstack/ai-devtools-core0.4.24 → 0.5.0Changeset
      @tanstack/ai-event-client0.6.8 → 0.7.0Changeset
      @tanstack/ai-utils0.3.1 → 0.4.0Changeset

      🟩 Patch bumps

      PackageVersionReason
      @tanstack/ai-mcp0.2.5 → 0.2.6Changeset
      @tanstack/ai-isolate-cloudflare0.2.38 → 0.2.39Dependent
      @tanstack/ai-vue-ui0.2.34 → 0.2.35Dependent
      @tanstack/preact-ai-devtools0.1.67 → 0.1.68Dependent
      @tanstack/react-ai-devtools0.2.67 → 0.2.68Dependent
      @tanstack/solid-ai-devtools0.2.67 → 0.2.68Dependent
      ag-ui0.0.2 → 0.0.3Dependent
    3. nx-cloud[bot](GitHub profile, opens in a new tab)commented

      View your CI Pipeline Execution ↗ for commit b6b9fa6c6eb642abd9f3a3e45dc9699b0da5be9a

      CommandStatusDurationResult
      nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded27sView ↗
      nx run-many --targets=build --exclude=examples/...✅ Succeeded2sView ↗

      ☁️ Nx Cloud last updated this comment at 2026-07-29 03:59:57 UTC

    4. pkg-pr-new[bot](GitHub profile, opens in a new tab)commented

      Open in StackBlitz

      @tanstack/ai

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai@997

      @tanstack/ai-acp

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-acp@997

      @tanstack/ai-angular

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-angular@997

      @tanstack/ai-anthropic

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-anthropic@997

      @tanstack/ai-bedrock

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-bedrock@997

      @tanstack/ai-claude-code

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-claude-code@997

      @tanstack/ai-client

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-client@997

      @tanstack/ai-code-mode

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-code-mode@997

      @tanstack/ai-code-mode-skills

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-code-mode-skills@997

      @tanstack/ai-codex

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-codex@997

      @tanstack/ai-devtools-core

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-devtools-core@997

      @tanstack/ai-durable-stream

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-durable-stream@997

      @tanstack/ai-elevenlabs

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-elevenlabs@997

      @tanstack/ai-event-client

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-event-client@997

      @tanstack/ai-fal

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-fal@997

      @tanstack/ai-gemini

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-gemini@997

      @tanstack/ai-grok

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-grok@997

      @tanstack/ai-grok-build

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-grok-build@997

      @tanstack/ai-groq

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-groq@997

      @tanstack/ai-isolate-cloudflare

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-cloudflare@997

      @tanstack/ai-isolate-node

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-node@997

      @tanstack/ai-isolate-quickjs

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-quickjs@997

      @tanstack/ai-mcp

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-mcp@997

      @tanstack/ai-memory

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-memory@997

      @tanstack/ai-mistral

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-mistral@997

      @tanstack/ai-ollama

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-ollama@997

      @tanstack/ai-openai

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openai@997

      @tanstack/ai-opencode

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-opencode@997

      @tanstack/ai-openrouter

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openrouter@997

      @tanstack/ai-persistence

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-persistence@997

      @tanstack/ai-preact

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-preact@997

      @tanstack/ai-react

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react@997

      @tanstack/ai-react-ui

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react-ui@997

      @tanstack/ai-sandbox

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox@997

      @tanstack/ai-sandbox-cloudflare

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-cloudflare@997

      @tanstack/ai-sandbox-daytona

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-daytona@997

      @tanstack/ai-sandbox-docker

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-docker@997

      @tanstack/ai-sandbox-local-process

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-local-process@997

      @tanstack/ai-sandbox-sprites

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-sprites@997

      @tanstack/ai-sandbox-vercel

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-vercel@997

      @tanstack/ai-solid

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid@997

      @tanstack/ai-solid-ui

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid-ui@997

      @tanstack/ai-svelte

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-svelte@997

      @tanstack/ai-utils

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-utils@997

      @tanstack/ai-vue

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue@997

      @tanstack/ai-vue-ui

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue-ui@997

      @tanstack/openai-base

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/openai-base@997

      @tanstack/preact-ai-devtools

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/preact-ai-devtools@997

      @tanstack/react-ai-devtools

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/react-ai-devtools@997

      @tanstack/solid-ai-devtools

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/solid-ai-devtools@997

      commit: 0ef4c34

    5. Actionable comments posted: 5

      🧹 Nitpick comments (10)
      packages/ai-react/src/use-generate-audio.ts (1)

      73-80: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

      React wrappers hand-copy the resume/artifact surface instead of inheriting it. The same four fields (resumeSnapshot, resumeState, pendingArtifacts, resultArtifacts) and their caveat JSDoc are duplicated across four React return types, while the Vue and Angular wrappers in this PR derive them via extends Omit<UseGenerationReturn<TOutput>, 'generate'> / Omit<InjectGenerationResult<TOutput>, 'generate'>. Any future change to the surface now needs four synchronized edits, and the "always empty until the artifact pipeline ships" note will drift.

      • packages/ai-react/src/use-generate-audio.ts#L73-L80: replace the four copied fields with extends Omit<UseGenerationReturn<TOutput, AudioGenerateInput>, 'generate'> and keep only the narrowed generate.
      • packages/ai-react/src/use-generate-image.ts#L73-L80: same, inheriting from UseGenerationReturn<TOutput, ImageGenerateInput>.
      • packages/ai-react/src/use-summarize.ts#L73-L80: same, inheriting from UseGenerationReturn<TOutput, SummarizeGenerateInput>.
      • packages/ai-react/src/use-generate-video.ts#L83-L90: useGenerateVideo builds its own client, so extract the four field declarations into a shared GenerationResumeSurface interface and extend that here instead of re-declaring them.
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-react/src/use-generate-audio.ts` around lines 73 - 80, Replace
      the duplicated resume/artifact field declarations with shared inherited types:
      in packages/ai-react/src/use-generate-audio.ts lines 73-80,
      packages/ai-react/src/use-generate-image.ts lines 73-80, and
      packages/ai-react/src/use-summarize.ts lines 73-80, extend
      Omit<UseGenerationReturn<TOutput, respective input type>, 'generate'> while
      retaining only the narrowed generate member. In
      packages/ai-react/src/use-generate-video.ts lines 83-90, extract those four
      fields and their caveat JSDoc into a shared GenerationResumeSurface interface,
      then extend it instead of re-declaring them.
      packages/ai-client/src/video-generation-client.ts (1)

      641-828: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

      Extract resume-snapshot persistence into a shared helper.

      GenerationClient and VideoGenerationClient both contain near-identical hydration/persist/dedupe/queue/clear/error-warn resume-snapshot lifecycle code. Move that implementation to a shared ResumeSnapshotStore (constructed with the storage adapter and key) so the two clients share the same semantics and avoid prefix-only naming drift like resumeSnapshotSignature vs videoResumeSnapshotSignature.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-client/src/video-generation-client.ts` around lines 641 - 828,
      Extract the resume snapshot lifecycle currently implemented by methods such as
      maybeHydrateResumeSnapshot, hydrateResumeSnapshot, persistResumeSnapshot,
      writeResumeSnapshot, removePersistedResumeSnapshot, and clearResumeSnapshot into
      a shared ResumeSnapshotStore that accepts the storage adapter and snapshot key.
      Update GenerationClient and VideoGenerationClient to delegate hydration,
      persistence, deduplication, queued writes, clearing, and warning/error state to
      this store, and replace the client-specific videoResumeSnapshotSignature with
      the shared implementation so both clients retain identical semantics.
      packages/ai-client/src/generation-client.ts (1)

      439-464: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      Consider extracting a snapshot-clone/carry helper.

      This nested conditional-spread clone is repeated in shape at Lines 574-587 (completePlainFetcherResumeSnapshot) and Lines 602-612 (recordResumeSnapshotError). A single cloneResumeSnapshot(snapshot) / carryForward(previous) helper would remove the duplication and keep the three sites from drifting when a new snapshot field is added.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-client/src/generation-client.ts` around lines 439 - 464, Extract
      the repeated resume-snapshot cloning logic from getResumeSnapshot,
      completePlainFetcherResumeSnapshot, and recordResumeSnapshotError into a shared
      cloneResumeSnapshot or carryForward helper. Update all three call sites to use
      it, preserving the existing shallow-copy behavior for nested pendingArtifacts,
      result.artifacts, error, and lastEvent fields so future snapshot fields remain
      consistent.
      packages/ai-client/tests/generation-client.test.ts (1)

      1329-1361: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

      Also assert the new getResumePersistenceError() surface.

      This case covers the console.warn side effect but not the public getter that exposes the failure (and its reset back to undefined after a later successful write). Adding those assertions here would lock in the only user-visible signal of persistence failure.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-client/tests/generation-client.test.ts` around lines 1329 - 1361,
      Extend the rejected-write test around GenerationClient.generate to assert
      getResumePersistenceError() returns persistenceError after the failed setItem
      call. Then make a subsequent successful persistence write and assert the getter
      resets to undefined, preserving the existing warning assertion and generation
      resolution behavior.
      packages/ai-react/src/use-generate-speech.ts (1)

      33-36: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

      React wrapper hooks hand-copy the resume surface instead of deriving it. Both hooks re-declare persistence / initialResumeSnapshot and the four resume/artifact return fields verbatim, while the Vue and Svelte wrappers now derive them (Pick<...Options, 'persistence' | 'initialResumeSnapshot'>, Omit<...Return, 'generate'>). The next field added to useGeneration will silently miss these public types.

      • packages/ai-react/src/use-generate-speech.ts#L33-L36: have UseGenerateSpeechOptions extend Pick<UseGenerationOptions<SpeechGenerateInput, TTSResult, TOutput>, 'persistence' | 'initialResumeSnapshot'> and UseGenerateSpeechReturn extend Omit<UseGenerationReturn<TOutput, SpeechGenerateInput>, 'generate'>.
      • packages/ai-react/src/use-transcription.ts#L33-L36: apply the same derivation with TranscriptionGenerateInput / TranscriptionResult.
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-react/src/use-generate-speech.ts` around lines 33 - 36, Derive
      the React wrapper types from the shared generation types instead of hand-copying
      resume and artifact fields. In packages/ai-react/src/use-generate-speech.ts at
      lines 33-36, make UseGenerateSpeechOptions extend
      Pick<UseGenerationOptions<SpeechGenerateInput, TTSResult, TOutput>,
      'persistence' | 'initialResumeSnapshot'> and UseGenerateSpeechReturn extend
      Omit<UseGenerationReturn<TOutput, SpeechGenerateInput>, 'generate'>; apply the
      same change in packages/ai-react/src/use-transcription.ts at lines 33-36 using
      TranscriptionGenerateInput and TranscriptionResult.
      packages/ai-svelte/tests/create-generation.test.ts (1)

      248-273: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

      Use flushAsync() instead of a single await Promise.resolve() in these negative-assertion tests.

      Hydration and persistence work run through detached promise queues (that's why flushAsync exists). One microtask isn't enough to prove getItem/connect were never called — a regression that hydrates a macrotask later would still pass.

      💚 Suggested change (both tests)
      -      await Promise.resolve()
      +      await flushAsync()

      Also applies to: 808-828

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-svelte/tests/create-generation.test.ts` around lines 248 - 273,
      Update both negative-assertion tests in create-generation.test.ts, including the
      test near the referenced additional range, to await the existing flushAsync()
      helper instead of a single Promise.resolve() microtask. Keep the assertions
      verifying that getItem and connect were not called, so detached hydration and
      persistence queues are fully drained before checking behavior.
      packages/ai-svelte/src/create-generate-video.svelte.ts (1)

      311-322: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

      Empty-artifact getters allocate a new array per read.

      packages/ai-vue/src/use-generate-video.ts deliberately uses shared EMPTY_* constants so empty lists keep a stable identity for downstream watchers; these getters return a fresh [] on every access, which defeats reference comparison in $derived/$effect consumers.

      ♻️ Use shared fallbacks
           get pendingArtifacts() {
      -      return resumeSnapshot?.pendingArtifacts ?? []
      +      return resumeSnapshot?.pendingArtifacts ?? EMPTY_PENDING_ARTIFACTS
           },
           get resultArtifacts() {
      -      return resumeSnapshot?.result?.artifacts ?? []
      +      return resumeSnapshot?.result?.artifacts ?? EMPTY_RESULT_ARTIFACTS
           },

      Add at module scope:

      const EMPTY_PENDING_ARTIFACTS: Array<GenerationPendingArtifact> = []
      const EMPTY_RESULT_ARTIFACTS: Array<PersistedArtifactRef> = []
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-svelte/src/create-generate-video.svelte.ts` around lines 311 -
      322, Update the module containing the resumeSnapshot getters to define shared
      EMPTY_PENDING_ARTIFACTS and EMPTY_RESULT_ARTIFACTS constants at module scope,
      then use them as the nullish fallbacks in pendingArtifacts and resultArtifacts
      instead of allocating [] on each read. Keep the existing non-empty artifact
      values unchanged.
      packages/ai-angular/tests/inject-generation.test.ts (2)

      73-103: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      Persistence/adapter test helpers copy-pasted per framework suite and already diverging. The same createMapPersistence / createRunContextCaptureAdapter / flushPromises trio is redefined in each framework test file with different return shapes, so the persistence contract is asserted slightly differently in each.

      • packages/ai-angular/tests/inject-generation.test.ts#L73-L103: import a shared GenerationPersistence mock util instead of the local wrapper-object variant.
      • packages/ai-vue/tests/use-generation.test.ts#L126-L142: replace the adapter-with-store variant with the same shared util.
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-angular/tests/inject-generation.test.ts` around lines 73 - 103,
      Replace the local createMapPersistence helper in
      packages/ai-angular/tests/inject-generation.test.ts (lines 73-103) and
      packages/ai-vue/tests/use-generation.test.ts (lines 126-142) with the shared
      GenerationPersistence mock utility, importing it wherever needed and updating
      call sites to its return shape. Remove the duplicated framework-specific
      wrapper/store variants so both suites assert the same persistence contract.

      105-111: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

      Prefer vi.waitFor over a fixed microtask count.

      Hydration and removal both go through chained promise queues inside the client; a hard-coded 5-tick drain will silently become insufficient if another .then link is added, producing intermittent failures rather than a clear one.

      ♻️ Suggested alternative
      -// Hydration and snapshot removal both run through awaited promise chains, so
      -// drain the microtask queue rather than awaiting a single tick.
      -async function flushPromises(): Promise<void> {
      -  for (let i = 0; i < 5; i++) {
      -    await Promise.resolve()
      -  }
      -}
      +// Hydration and snapshot removal both run through awaited promise chains;
      +// poll for the expected state instead of guessing a microtask count.
      +async function flushPromises(): Promise<void> {
      +  await vi.waitFor(() => Promise.resolve())
      +}

      Or assert with await vi.waitFor(() => expect(getItem).toHaveBeenCalledTimes(1)) at each call site.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-angular/tests/inject-generation.test.ts` around lines 105 - 111,
      Replace the fixed five-iteration flushPromises helper with vi.waitFor-based
      synchronization at the hydration and snapshot-removal assertions, waiting for
      the expected client call or state before continuing. Remove the hard-coded
      microtask drain while preserving the existing assertions and behavior.
      packages/ai-angular/src/inject-generate-video.ts (1)

      95-117: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      Optional: extract the resume-signal wiring into a shared internal helper.

      This block (signals seeded from initialResumeSnapshot + setResumeSnapshotState) is byte-for-byte identical to packages/ai-angular/src/inject-generation.ts Lines 127-149. A small internal/create-resume-signals.ts returning the four signals plus the setter (and taking a () => boolean disposed accessor) would keep the two clients from drifting.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-angular/src/inject-generate-video.ts` around lines 95 - 117,
      Extract the duplicated resume-signal initialization and update logic from
      injectGenerateVideo and injectGeneration into a shared internal
      create-resume-signals helper. Have the helper accept the initial snapshot and a
      disposed-state accessor, return the four signals plus setResumeSnapshotState,
      and update both clients to use it while preserving current initialization and
      disposal behavior.
      🤖 Prompt for all review comments with AI agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      Inline comments:
      In `@examples/ts-react-chat/src/routes/generations.image.tsx`:
      - Around line 119-125: Update the ImageGenerationUI reset-button visibility
      logic so the “Clear” action remains available when a hydrated resumeSnapshot
      exists, even if result is empty. Ensure the button invokes the existing reset()
      behavior and preserve the current visibility behavior for non-hydrated states.
      
      In `@packages/ai-client/src/generation-types.ts`:
      - Around line 602-607: Update the expiresAt handling in observeResumeSnapshot to
      validate Date values before calling toISOString, so invalid dates are ignored
      without throwing. Preserve the existing string handling and valid Date
      serialization behavior.
      
      In `@packages/ai-react/src/use-generation.ts`:
      - Around line 193-195: Update the onResumeSnapshotChange callback in the React
      hook and the corresponding Vue/Svelte integrations to suppress state updates
      when the resume snapshot has not materially changed. Reuse the existing
      resumeSnapshotSignature comparison or equivalent logic so lastEvent-only changes
      are ignored while meaningful snapshot changes still call setResumeSnapshot and
      update the reactive state.
      
      In `@packages/ai-svelte/src/create-generation.svelte.ts`:
      - Around line 298-303: Define module-level EMPTY_PENDING_ARTIFACTS and
      EMPTY_RESULT_ARTIFACTS constants with the appropriate artifact types, then
      update the pendingArtifacts and resultArtifacts getters to reuse these stable
      fallbacks instead of allocating a new empty array on each read.
      
      In `@packages/ai-vue/src/use-generate-video.ts`:
      - Around line 93-100: The artifact JSDoc incorrectly claims pendingArtifacts and
      resultArtifacts are always empty; update the documentation in
      packages/ai-vue/src/use-generate-video.ts lines 93-100 and
      packages/ai-svelte/src/create-generate-video.svelte.ts lines 88-95 to describe
      when each list is populated, and mirror the correction in other framework hooks
      with the copied text. Keep packages/ai-react/tests/use-generation.test.ts lines
      475-493 as the behavioral source of truth and make no test change unless the
      corrected documentation reveals the expectation is wrong.
      
      ---
      
      Nitpick comments:
      In `@packages/ai-angular/src/inject-generate-video.ts`:
      - Around line 95-117: Extract the duplicated resume-signal initialization and
      update logic from injectGenerateVideo and injectGeneration into a shared
      internal create-resume-signals helper. Have the helper accept the initial
      snapshot and a disposed-state accessor, return the four signals plus
      setResumeSnapshotState, and update both clients to use it while preserving
      current initialization and disposal behavior.
      
      In `@packages/ai-angular/tests/inject-generation.test.ts`:
      - Around line 73-103: Replace the local createMapPersistence helper in
      packages/ai-angular/tests/inject-generation.test.ts (lines 73-103) and
      packages/ai-vue/tests/use-generation.test.ts (lines 126-142) with the shared
      GenerationPersistence mock utility, importing it wherever needed and updating
      call sites to its return shape. Remove the duplicated framework-specific
      wrapper/store variants so both suites assert the same persistence contract.
      - Around line 105-111: Replace the fixed five-iteration flushPromises helper
      with vi.waitFor-based synchronization at the hydration and snapshot-removal
      assertions, waiting for the expected client call or state before continuing.
      Remove the hard-coded microtask drain while preserving the existing assertions
      and behavior.
      
      In `@packages/ai-client/src/generation-client.ts`:
      - Around line 439-464: Extract the repeated resume-snapshot cloning logic from
      getResumeSnapshot, completePlainFetcherResumeSnapshot, and
      recordResumeSnapshotError into a shared cloneResumeSnapshot or carryForward
      helper. Update all three call sites to use it, preserving the existing
      shallow-copy behavior for nested pendingArtifacts, result.artifacts, error, and
      lastEvent fields so future snapshot fields remain consistent.
      
      In `@packages/ai-client/src/video-generation-client.ts`:
      - Around line 641-828: Extract the resume snapshot lifecycle currently
      implemented by methods such as maybeHydrateResumeSnapshot,
      hydrateResumeSnapshot, persistResumeSnapshot, writeResumeSnapshot,
      removePersistedResumeSnapshot, and clearResumeSnapshot into a shared
      ResumeSnapshotStore that accepts the storage adapter and snapshot key. Update
      GenerationClient and VideoGenerationClient to delegate hydration, persistence,
      deduplication, queued writes, clearing, and warning/error state to this store,
      and replace the client-specific videoResumeSnapshotSignature with the shared
      implementation so both clients retain identical semantics.
      
      In `@packages/ai-client/tests/generation-client.test.ts`:
      - Around line 1329-1361: Extend the rejected-write test around
      GenerationClient.generate to assert getResumePersistenceError() returns
      persistenceError after the failed setItem call. Then make a subsequent
      successful persistence write and assert the getter resets to undefined,
      preserving the existing warning assertion and generation resolution behavior.
      
      In `@packages/ai-react/src/use-generate-audio.ts`:
      - Around line 73-80: Replace the duplicated resume/artifact field declarations
      with shared inherited types: in packages/ai-react/src/use-generate-audio.ts
      lines 73-80, packages/ai-react/src/use-generate-image.ts lines 73-80, and
      packages/ai-react/src/use-summarize.ts lines 73-80, extend
      Omit<UseGenerationReturn<TOutput, respective input type>, 'generate'> while
      retaining only the narrowed generate member. In
      packages/ai-react/src/use-generate-video.ts lines 83-90, extract those four
      fields and their caveat JSDoc into a shared GenerationResumeSurface interface,
      then extend it instead of re-declaring them.
      
      In `@packages/ai-react/src/use-generate-speech.ts`:
      - Around line 33-36: Derive the React wrapper types from the shared generation
      types instead of hand-copying resume and artifact fields. In
      packages/ai-react/src/use-generate-speech.ts at lines 33-36, make
      UseGenerateSpeechOptions extend Pick<UseGenerationOptions<SpeechGenerateInput,
      TTSResult, TOutput>, 'persistence' | 'initialResumeSnapshot'> and
      UseGenerateSpeechReturn extend Omit<UseGenerationReturn<TOutput,
      SpeechGenerateInput>, 'generate'>; apply the same change in
      packages/ai-react/src/use-transcription.ts at lines 33-36 using
      TranscriptionGenerateInput and TranscriptionResult.
      
      In `@packages/ai-svelte/src/create-generate-video.svelte.ts`:
      - Around line 311-322: Update the module containing the resumeSnapshot getters
      to define shared EMPTY_PENDING_ARTIFACTS and EMPTY_RESULT_ARTIFACTS constants at
      module scope, then use them as the nullish fallbacks in pendingArtifacts and
      resultArtifacts instead of allocating [] on each read. Keep the existing
      non-empty artifact values unchanged.
      
      In `@packages/ai-svelte/tests/create-generation.test.ts`:
      - Around line 248-273: Update both negative-assertion tests in
      create-generation.test.ts, including the test near the referenced additional
      range, to await the existing flushAsync() helper instead of a single
      Promise.resolve() microtask. Keep the assertions verifying that getItem and
      connect were not called, so detached hydration and persistence queues are fully
      drained before checking behavior.
      🪄 Autofix (Beta)

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: b2e31f65-38c8-47c9-8113-258d0c9c7aec

      📥 Commits

      Reviewing files that changed from the base of the PR and between 4ab149fd46a1cf55691266cdd118fdc9999c0b2a and a1fb4360a98b0b55ae6ad6a8e282aaebea7b5414.

      📒 Files selected for processing (62)
      • .changeset/generation-persistence.md
      • docs/config.json
      • docs/persistence/generation-persistence.md
      • examples/ts-react-chat/src/routes/generations.image.tsx
      • packages/ai-angular/src/index.ts
      • packages/ai-angular/src/inject-generate-audio.ts
      • packages/ai-angular/src/inject-generate-image.ts
      • packages/ai-angular/src/inject-generate-speech.ts
      • packages/ai-angular/src/inject-generate-video.ts
      • packages/ai-angular/src/inject-generation.ts
      • packages/ai-angular/src/inject-summarize.ts
      • packages/ai-angular/src/inject-transcription.ts
      • packages/ai-angular/tests/inject-generation.test.ts
      • packages/ai-client/src/generation-client.ts
      • packages/ai-client/src/generation-types.ts
      • packages/ai-client/src/index.ts
      • packages/ai-client/src/storage-adapters.ts
      • packages/ai-client/src/video-generation-client.ts
      • packages/ai-client/tests/generation-client.test.ts
      • packages/ai-client/tests/generation-resume-state.test.ts
      • packages/ai-react/src/index.ts
      • packages/ai-react/src/use-generate-audio.ts
      • packages/ai-react/src/use-generate-image.ts
      • packages/ai-react/src/use-generate-speech.ts
      • packages/ai-react/src/use-generate-video.ts
      • packages/ai-react/src/use-generation.ts
      • packages/ai-react/src/use-summarize.ts
      • packages/ai-react/src/use-transcription.ts
      • packages/ai-react/tests/use-generation.test.ts
      • packages/ai-solid/src/index.ts
      • packages/ai-solid/src/use-generate-audio.ts
      • packages/ai-solid/src/use-generate-image.ts
      • packages/ai-solid/src/use-generate-speech.ts
      • packages/ai-solid/src/use-generate-video.ts
      • packages/ai-solid/src/use-generation.ts
      • packages/ai-solid/src/use-summarize.ts
      • packages/ai-solid/src/use-transcription.ts
      • packages/ai-solid/tests/use-generation.test.ts
      • packages/ai-svelte/src/create-generate-audio.svelte.ts
      • packages/ai-svelte/src/create-generate-image.svelte.ts
      • packages/ai-svelte/src/create-generate-speech.svelte.ts
      • packages/ai-svelte/src/create-generate-video.svelte.ts
      • packages/ai-svelte/src/create-generation.svelte.ts
      • packages/ai-svelte/src/create-summarize.svelte.ts
      • packages/ai-svelte/src/create-transcription.svelte.ts
      • packages/ai-svelte/src/index.ts
      • packages/ai-svelte/tests/create-generation.test.ts
      • packages/ai-vue/src/index.ts
      • packages/ai-vue/src/use-generate-audio.ts
      • packages/ai-vue/src/use-generate-image.ts
      • packages/ai-vue/src/use-generate-speech.ts
      • packages/ai-vue/src/use-generate-video.ts
      • packages/ai-vue/src/use-generation.ts
      • packages/ai-vue/src/use-summarize.ts
      • packages/ai-vue/src/use-transcription.ts
      • packages/ai-vue/tests/use-generation.test.ts
      • packages/ai/skills/ai-core/client-persistence/SKILL.md
      • packages/ai/skills/ai-core/media-generation/SKILL.md
      • testing/e2e/src/routeTree.gen.ts
      • testing/e2e/src/routes/api.generation-persistence.ts
      • testing/e2e/src/routes/generation-persistence.tsx
      • testing/e2e/tests/generation-persistence.spec.ts
      @@ -330,0 +587,21 @@
      587+export function createGenerationResultSnapshot(
      588+ value: unknown,
      589+): GenerationResultSnapshot | undefined {
      590+ if (!isObject(value)) return undefined
      591+
      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 = id
      599+ if (model) snapshot.model = model
      600+ if (status) snapshot.status = status
      601+ if (jobId) snapshot.jobId = jobId
      602+ const expiresAt = Reflect.get(value, 'expiresAt')
      603+ if (typeof expiresAt === 'string') {
      604+ snapshot.expiresAt = expiresAt
      605+ } else if (expiresAt instanceof Date) {
      606+ snapshot.expiresAt = expiresAt.toISOString()
      607+ }
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

      Guard against an invalid Date in expiresAt.

      toISOString() throws RangeError on an invalid Date. This runs inside observeResumeSnapshot on live chunk values, so a malformed provider expiresAt would throw out of the stream loop rather than just being dropped like every other unusable field here.

      🛡️ Proposed fix
         } else if (expiresAt instanceof Date) {
      -    snapshot.expiresAt = expiresAt.toISOString()
      +    if (!Number.isNaN(expiresAt.getTime())) {
      +      snapshot.expiresAt = expiresAt.toISOString()
      +    }
         }
      📝 Committable suggestion

      ‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      Suggested change
      719+ const expiresAt = Reflect.get(value, 'expiresAt')
      720+ if (typeof expiresAt === 'string') {
      721+ snapshot.expiresAt = expiresAt
      722+ } else if (expiresAt instanceof Date) {
      723+ if (!Number.isNaN(expiresAt.getTime())) {
      724+ snapshot.expiresAt = expiresAt.toISOString()
      725+ }
      726+ }
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-client/src/generation-types.ts` around lines 602 - 607, Update
      the expiresAt handling in observeResumeSnapshot to validate Date values before
      calling toISOString, so invalid dates are ignored without throwing. Preserve the
      existing string handling and valid Date serialization behavior.
      @@ -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 },
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

      Per-chunk setResumeSnapshot re-renders the component on every stream event.

      GenerationClient.observeResumeSnapshot invokes onResumeSnapshotChange for every chunk with a freshly built object, so this always schedules a state update — including for lastEvent-only changes that the persistence layer deliberately dedupes (resumeSnapshotSignature). For a long streaming run that is one React render per chunk, on top of the existing progress/result renders.

      Consider suppressing the notification when the snapshot has not materially changed (reuse the signature comparison, or skip when only lastEvent differs) so the reactive surfaces stay as cheap as the writes. This also affects the Vue and Svelte hooks that wire the same callback.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-react/src/use-generation.ts` around lines 193 - 195, Update the
      onResumeSnapshotChange callback in the React hook and the corresponding
      Vue/Svelte integrations to suppress state updates when the resume snapshot has
      not materially changed. Reuse the existing resumeSnapshotSignature comparison or
      equivalent logic so lastEvent-only changes are ignored while meaningful snapshot
      changes still call setResumeSnapshot and update the reactive state.
    6. Actionable comments posted: 5

      Caution

      Some comments are outside the diff and can’t be posted inline due to platform limitations.

      ⚠️ Outside diff range comments (1)
      packages/ai/src/activities/generateAudio/index.ts (1)

      163-184: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

      Forward correlation IDs to every activity event.

      The IDs are retained only in middleware context; all aiEventClient.emit() calls still omit them, so observers cannot correlate request, completion, usage, and error events with the persisted run.

      • packages/ai/src/activities/generateAudio/index.ts#L163-L184: include threadId and runId in audio start, completion, usage, and error events.
      • packages/ai/src/activities/generateImage/index.ts#L256-L273: include threadId and runId in image start, completion, usage, and error events.
      • packages/ai/src/activities/generateSpeech/index.ts#L171-L197: include threadId and runId in speech start, completion, usage, and error events.
      • packages/ai/src/activities/generateTranscription/index.ts#L206-L232: include threadId and runId in transcription start, completion, usage, and error events.
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai/src/activities/generateAudio/index.ts` around lines 163 - 184,
      Forward threadId and runId through every aiEventClient.emit call for start,
      completion, usage, and error events in the audio activity around
      createGenerationContext and in
      packages/ai/src/activities/generateAudio/index.ts:163-184,
      packages/ai/src/activities/generateImage/index.ts:256-273,
      packages/ai/src/activities/generateSpeech/index.ts:171-197, and
      packages/ai/src/activities/generateTranscription/index.ts:206-232. Reuse the IDs
      already destructured from options and preserve the existing event payloads
      otherwise.
      🧹 Nitpick comments (2)
      .changeset/generation-persistence.md (1)

      14-18: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      Redundant lead sentence.

      Line 18 restates Line 14 in the published release notes.

      ✏️ Proposed fix
      -Add client-side generation persistence: a lightweight resume snapshot for media generation activities.
      -
      +**Resume snapshot (client).**
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In @.changeset/generation-persistence.md around lines 14 - 18, Remove the
      redundant “Add client-side generation persistence” sentence from the release
      note, keeping the preceding description of generation persistence and media byte
      storage intact.
      packages/ai-persistence/src/middleware.ts (1)

      46-53: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

      WithPersistenceOptions is declared twice in this module.

      Line 916 declares the same exported interface with snapshotStreaming / snapshotIntervalMs. TS merges them, so it compiles, but the merged type means withPersistence advertises extractArtifacts/nameArtifact (ignored) and withGenerationPersistence advertises snapshotStreaming (ignored), and jump-to-definition only shows half the surface. Consider a separate WithGenerationPersistenceOptions for the generation hooks, or at least merge both halves into one declaration.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-persistence/src/middleware.ts` around lines 46 - 53, Resolve the
      duplicate WithPersistenceOptions declarations in middleware.ts by separating the
      generation-hook options into a distinct WithGenerationPersistenceOptions type,
      or consolidating both declarations into one complete interface. Update
      withPersistence and withGenerationPersistence to reference only the options each
      implementation actually consumes, so ignored properties are no longer advertised
      and jump-to-definition exposes the full relevant API.
      🤖 Prompt for all review comments with AI agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      Inline comments:
      In `@docs/persistence/generation-persistence.md`:
      - Around line 141-159: Update the GET route to derive the authenticated user or
      session identity from server-side session state, then authorize ownership at the
      route boundary using the artifact’s opaque threadId (and existing
      thread-ownership mechanism) before calling retrieveArtifact or retrieveBlob.
      Return the existing not-found or unauthorized response for inaccessible
      artifacts, while preserving byte serving for authorized requests.
      
      In `@packages/ai-persistence/src/middleware.ts`:
      - Around line 524-535: Update the video descriptor construction in the activity
      handling block to preserve string expiry values as well as Date instances.
      Assign output.expiresAt when it is a supported string or Date, reusing the
      existing normalization behavior from the code around Line 761 rather than
      discarding ISO timestamp strings.
      - Around line 617-655: Harden URL handling in the descriptor.url branch by
      allowing only http/https URLs and validating hosts through the existing
      allowlist or caller-supplied allowArtifactUrl predicate before fetching; use
      manual redirects so validation cannot be bypassed. Add a fetch timeout and
      enforce a maximum response size while streaming or buffering, aborting oversized
      or timed-out responses. Preserve data-URL handling and existing artifact
      metadata behavior.
      - Around line 332-345: Update parseDataUrl so malformed percent-encoding in
      non-base64 payloads does not throw from decodeURIComponent; catch the URI
      decoding failure and return undefined so the result transform skips the invalid
      artifact. Preserve normal decoding for valid payloads and leave base64 handling
      unchanged.
      - Around line 394-395: Update the mimeType fallback in the source normalization
      logic near sourceType to use a valid MIME type derived from the actual source
      format, rather than constructing `${type}/mpeg`. Ensure omitted source.mimeType
      values for image and video parts produce renderable ArtifactRecord.mimeType and
      serve-route content-type values.
      
      ---
      
      Outside diff comments:
      In `@packages/ai/src/activities/generateAudio/index.ts`:
      - Around line 163-184: Forward threadId and runId through every
      aiEventClient.emit call for start, completion, usage, and error events in the
      audio activity around createGenerationContext and in
      packages/ai/src/activities/generateAudio/index.ts:163-184,
      packages/ai/src/activities/generateImage/index.ts:256-273,
      packages/ai/src/activities/generateSpeech/index.ts:171-197, and
      packages/ai/src/activities/generateTranscription/index.ts:206-232. Reuse the IDs
      already destructured from options and preserve the existing event payloads
      otherwise.
      
      ---
      
      Nitpick comments:
      In @.changeset/generation-persistence.md:
      - Around line 14-18: Remove the redundant “Add client-side generation
      persistence” sentence from the release note, keeping the preceding description
      of generation persistence and media byte storage intact.
      
      In `@packages/ai-persistence/src/middleware.ts`:
      - Around line 46-53: Resolve the duplicate WithPersistenceOptions declarations
      in middleware.ts by separating the generation-hook options into a distinct
      WithGenerationPersistenceOptions type, or consolidating both declarations into
      one complete interface. Update withPersistence and withGenerationPersistence to
      reference only the options each implementation actually consumes, so ignored
      properties are no longer advertised and jump-to-definition exposes the full
      relevant API.
      🪄 Autofix (Beta)

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 08256dca-5274-4daf-80eb-8136ed82297f

      📥 Commits

      Reviewing files that changed from the base of the PR and between a1fb4360a98b0b55ae6ad6a8e282aaebea7b5414 and cbde0c5fe2b005da8d0ef0e55e9feb3343fae4d1.

      ⛔ Files ignored due to path filters (1)
      • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
      📒 Files selected for processing (23)
      • .changeset/generation-persistence.md
      • docs/persistence/generation-persistence.md
      • packages/ai-event-client/src/index.ts
      • packages/ai-persistence/package.json
      • packages/ai-persistence/src/index.ts
      • packages/ai-persistence/src/memory.ts
      • packages/ai-persistence/src/middleware.ts
      • packages/ai-persistence/src/retrieve.ts
      • packages/ai-persistence/src/types.ts
      • packages/ai-persistence/tests/generation-artifacts.test.ts
      • packages/ai-persistence/tests/memory.test.ts
      • packages/ai-persistence/tests/persistence-types.test-d.ts
      • packages/ai-utils/src/base64.ts
      • packages/ai-utils/src/index.ts
      • packages/ai/src/activities/generateAudio/index.ts
      • packages/ai/src/activities/generateImage/index.ts
      • packages/ai/src/activities/generateSpeech/index.ts
      • packages/ai/src/activities/generateTranscription/index.ts
      • packages/ai/src/activities/middleware/index.ts
      • packages/ai/src/activities/middleware/run.ts
      • packages/ai/src/activities/middleware/types.ts
      • packages/ai/src/activities/stream-generation-result.ts
      • packages/ai/src/index.ts
      @@ -0,0 +139,21 @@
      139+}
      140+
      141+// Serve a stored artifact's bytes by id. This is a plain file endpoint: it
      142+// 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+}
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

      Add an ownership check to the artifact serve route.

      The sample maps ?id= straight into retrieveArtifact and streams the bytes, so anyone who learns or guesses an artifact id gets the generated media of any user. ArtifactRecord carries threadId / runId, so the snippet can authorize before serving — worth showing here since this is the pattern people copy into production.

      🔒 Proposed fix
       export async function GET(request: Request) {
         const artifactId = new URL(request.url).searchParams.get('id')
         if (!artifactId) return new Response('missing id', { status: 400 })
       
      +  // Derive identity from server-side session state, never from the request body.
      +  const session = await getSession(request)
      +  if (!session) return new Response('unauthorized', { status: 401 })
      +
         const artifact = await retrieveArtifact(persistence, artifactId)
         if (!artifact) return new Response('not found', { status: 404 })
      +
      +  // Treat the artifact id as an opaque key; authorize thread ownership.
      +  if (!(await userOwnsThread(session.userId, artifact.threadId))) {
      +    return new Response('not found', { status: 404 })
      +  }
       
         const blob = await retrieveBlob(persistence, artifact)

      Based on learnings: treat threadId as an opaque lookup key and derive the effective user/session identity from server-side session state, authorizing thread ownership at the route boundary before any persistence reads.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@docs/persistence/generation-persistence.md` around lines 141 - 159, Update
      the GET route to derive the authenticated user or session identity from
      server-side session state, then authorize ownership at the route boundary using
      the artifact’s opaque threadId (and existing thread-ownership mechanism) before
      calling retrieveArtifact or retrieveBlob. Return the existing not-found or
      unauthorized response for inaccessible artifacts, while preserving byte serving
      for authorized requests.

      Source: Learnings

      @@ -261,0 +325,21 @@
      325+ activity === 'tts' ||
      326+ activity === 'video' ||
      327+ activity === 'transcription'
      328+ ? activity
      329+ : undefined
      330+}
      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 undefined
      337+ 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+}
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

      decodeURIComponent can throw on a non-base64 data URL.

      For the plain (non-base64) branch, a payload with a bare % (e.g. data:text/plain,100%) makes decodeURIComponent throw URIError. Since parseDataUrl runs inside the result transform for user-supplied prompt/audio data URLs (Line 540, Line 618), that surfaces as a failed generation rather than a skipped artifact.

      🛡️ Proposed fix
         const mimeType = match[1] || 'application/octet-stream'
      -  const payload = decodeURIComponent(match[3] ?? '')
      +  const raw = match[3] ?? ''
      +  let payload: string
      +  try {
      +    payload = decodeURIComponent(raw)
      +  } catch {
      +    payload = raw
      +  }
      📝 Committable suggestion

      ‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      Suggested change
      341+function parseDataUrl(
      342+ value: string,
      343+): { mimeType: string; bytes: Uint8Array } | undefined {
      344+ const match = /^data:([^;,]+)?(;base64)?,(.*)$/s.exec(value)
      345+ if (!match) return undefined
      346+ const mimeType = match[1] || 'application/octet-stream'
      347+ const raw = match[3] ?? ''
      348+ let payload: string
      349+ try {
      350+ payload = decodeURIComponent(raw)
      351+ } catch {
      352+ payload = raw
      353+ }
      354+ return {
      355+ mimeType,
      356+ bytes: match[2]
      357+ ? base64ToUint8Array(payload)
      358+ : new TextEncoder().encode(payload),
      359+ }
      360+}
      🧰 Tools
      🪛 OpenGrep (1.25.0)

      [ERROR] 335-335: Dynamic command passed to child_process.exec/execSync. Use child_process.execFile or spawn with an argument array instead.

      (coderabbit.command-injection.exec-js)

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-persistence/src/middleware.ts` around lines 332 - 345, Update
      parseDataUrl so malformed percent-encoding in non-base64 payloads does not throw
      from decodeURIComponent; catch the URI decoding failure and return undefined so
      the result transform skips the invalid artifact. Preserve normal decoding for
      valid payloads and leave base64 handling unchanged.
      @@ -261,0 +635,21 @@
      635+ 'application/octet-stream'
      636+ // Stream the body straight into the blob store instead of buffering the
      637+ // whole artifact in memory. `size` is left 0 (unknown up front); the store
      638+ // records the actual byte length as it drains the stream. Fall back to
      639+ // 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+ }
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      🔒 Security & Privacy | 🔴 Critical | 🏗️ Heavy lift

      SSRF: client-controlled prompt URLs are fetched server-side and persisted.

      sourcePartDescriptors (Line 409-413) turns any prompt part with source: { type: 'url', value } into a descriptor with url, and this branch fetches it from the server with no scheme check, host allowlist, timeout, or size cap. Since the fetched bytes are stored as an artifact and served back by the documented GET artifact route, a caller can read internal endpoints (cloud metadata at 169.254.169.254, localhost admin services) through your server.

      Suggested hardening:

      • Restrict to http:/https: and validate the host against an allowlist (or a caller-supplied allowArtifactUrl predicate) before fetching; consider redirect: 'manual' so a redirect can't hop to an internal target.
      • Pass an AbortSignal.timeout(...) and enforce a maximum byte length while draining.
      • Consider not fetching role: 'input' URLs at all by default — the client already has those bytes.
      🔒 Sketch
      -    const response = await fetch(descriptor.url)
      +    const target = new URL(descriptor.url)
      +    if (target.protocol !== 'https:' && target.protocol !== 'http:') {
      +      throw new Error(`Refusing to fetch artifact from ${target.protocol}`)
      +    }
      +    if (!(await isArtifactUrlAllowed(target))) {
      +      throw new Error(`Refusing to fetch artifact from ${target.host}`)
      +    }
      +    const response = await fetch(target, {
      +      redirect: 'manual',
      +      signal: AbortSignal.timeout(artifactFetchTimeoutMs),
      +    })
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-persistence/src/middleware.ts` around lines 617 - 655, Harden URL
      handling in the descriptor.url branch by allowing only http/https URLs and
      validating hosts through the existing allowlist or caller-supplied
      allowArtifactUrl predicate before fetching; use manual redirects so validation
      cannot be bypassed. Add a fetch timeout and enforce a maximum response size
      while streaming or buffering, aborting oversized or timed-out responses.
      Preserve data-URL handling and existing artifact metadata behavior.
    7. Actionable comments posted: 6

      Caution

      Some comments are outside the diff and can’t be posted inline due to platform limitations.

      ⚠️ Outside diff range comments (1)
      .changeset/generation-persistence.md (1)

      28-28: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

      Keep client snapshot persistence independent from server job persistence.

      The release note and guide contradict the new architecture: client-driven adapters do not require server jobs, while withGenerationPersistence records into the dedicated GenerationJobStore, not the chat RunStore.

      • .changeset/generation-persistence.md#L28-L28: replace the RunStore statement with the dedicated GenerationJobStore contract.
      • docs/persistence/generation-persistence.md#L52-L60: state that the jobs store is required for server-side withGenerationPersistence / persistence: true, not client-driven storage-adapter snapshots.
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In @.changeset/generation-persistence.md at line 28, Update
      .changeset/generation-persistence.md at line 28 to reference the dedicated
      GenerationJobStore contract instead of the chat RunStore, and update
      docs/persistence/generation-persistence.md at lines 52-60 to clarify that the
      jobs store is required only for server-side withGenerationPersistence or
      persistence: true, not for client-driven storage-adapter snapshots.
      🧹 Nitpick comments (1)
      packages/ai-persistence/tests/reconstruct-generation.test.ts (1)

      1-4: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

      Co-locate this unit test with reconstruct-generation.ts.

      The repository rule requires *.test.ts files alongside the source they cover; move this to packages/ai-persistence/src/reconstruct-generation.test.ts.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-persistence/tests/reconstruct-generation.test.ts` around lines 1
      - 4, Move the unit test containing `reconstructGeneration` coverage from the
      tests directory to `src/reconstruct-generation.test.ts`, keeping its imports and
      test behavior unchanged so it is co-located with `reconstruct-generation.ts`.

      Source: Coding guidelines

      🤖 Prompt for all review comments with AI agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      Inline comments:
      In `@docs/persistence/generation-persistence.md`:
      - Around line 131-135: Update the hydration GET example around
      reconstructGeneration to derive the caller’s identity from server-side session
      state and pass an authorize callback that verifies the requested thread/job
      belongs to that identity before reading persistence. Preserve the existing
      reconstruction behavior after authorization.
      
      In `@packages/ai-client/src/connection-adapters.ts`:
      - Around line 476-486: Validate the parsed JSON envelope before accessing
      activeRun in the hydration response flow. Treat null, arrays, and primitive
      payloads as an empty hydration result, then only read data.resumeSnapshot and
      data.activeRun from a non-array object while preserving the existing activeRun
      runId validation.
      
      In
      `@packages/ai-persistence/skills/ai-persistence/build-cloudflare-artifact-store/SKILL.md`:
      - Around line 125-136: The R2 adapter’s list method must return no objects when
      options.limit is 0 instead of relying on R2’s default behavior. Update list to
      handle the zero-limit case explicitly while preserving the existing bucket.list
      pagination and mapping behavior for other limits.
      
      In `@packages/ai/skills/ai-core/client-persistence/SKILL.md`:
      - Around line 145-165: Add a minimal server endpoint example to the “Mode B —
      server-driven” section, alongside the existing useGenerateImage client snippet.
      Show the generation route using withGenerationPersistence and returning
      reconstructGeneration(persistence, request), including the required stores.jobs
      configuration, while preserving the existing hydration behavior and references.
      
      In `@packages/ai/skills/ai-core/media-generation/SKILL.md`:
      - Around line 602-611: Authorize artifact ownership at the route boundary before
      any persistence access: in packages/ai/skills/ai-core/media-generation/SKILL.md
      lines 602-611, derive the owner from the authenticated session and validate it
      before retrieveArtifact or retrieveBlob; in
      packages/ai-persistence/skills/ai-persistence/build-cloudflare-artifact-store/SKILL.md
      lines 345-351, replace the comment-only guidance with an authorization-scoped
      lookup that passes the session-derived owner before retrieveArtifact. Reject
      unauthorized or mismatched artifacts without resolving or streaming their
      contents.
      
      In `@testing/e2e/src/routes/api.generation-persistence-server.ts`:
      - Around line 66-76: Move the completedByThread.set call before yielding the
      RUN_FINISHED terminal event in the generator handling the mock run. Ensure the
      map is populated before clients can observe completion or trigger hydration,
      while preserving the existing completed job values and terminal event behavior.
      
      ---
      
      Outside diff comments:
      In @.changeset/generation-persistence.md:
      - Line 28: Update .changeset/generation-persistence.md at line 28 to reference
      the dedicated GenerationJobStore contract instead of the chat RunStore, and
      update docs/persistence/generation-persistence.md at lines 52-60 to clarify that
      the jobs store is required only for server-side withGenerationPersistence or
      persistence: true, not for client-driven storage-adapter snapshots.
      
      ---
      
      Nitpick comments:
      In `@packages/ai-persistence/tests/reconstruct-generation.test.ts`:
      - Around line 1-4: Move the unit test containing `reconstructGeneration`
      coverage from the tests directory to `src/reconstruct-generation.test.ts`,
      keeping its imports and test behavior unchanged so it is co-located with
      `reconstruct-generation.ts`.
      🪄 Autofix (Beta)

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: b70ec0cd-119d-4be2-9f7c-db8950dc434a

      📥 Commits

      Reviewing files that changed from the base of the PR and between cbde0c5fe2b005da8d0ef0e55e9feb3343fae4d1 and 36fc27fdc64cc19a4a000d42f960ac48368e0efa.

      📒 Files selected for processing (62)
      • .changeset/generation-persistence.md
      • docs/config.json
      • docs/persistence/build-your-own-adapter.md
      • docs/persistence/generation-persistence.md
      • packages/ai-angular/src/inject-generate-audio.ts
      • packages/ai-angular/src/inject-generate-video.ts
      • packages/ai-angular/src/inject-generation.ts
      • packages/ai-client/src/connection-adapters.ts
      • packages/ai-client/src/generation-client.ts
      • packages/ai-client/src/generation-types.ts
      • packages/ai-client/src/index.ts
      • packages/ai-client/src/video-generation-client.ts
      • packages/ai-client/tests/generation-client.test.ts
      • packages/ai-persistence/skills/ai-persistence/SKILL.md
      • packages/ai-persistence/skills/ai-persistence/build-cloudflare-artifact-store/SKILL.md
      • packages/ai-persistence/src/index.ts
      • packages/ai-persistence/src/memory.ts
      • packages/ai-persistence/src/middleware.ts
      • packages/ai-persistence/src/reconstruct-generation.ts
      • packages/ai-persistence/src/types.ts
      • packages/ai-persistence/tests/error-abort.test.ts
      • packages/ai-persistence/tests/generation-artifacts.test.ts
      • packages/ai-persistence/tests/memory.test.ts
      • packages/ai-persistence/tests/persistence-fixtures.ts
      • packages/ai-persistence/tests/persistence-types.test-d.ts
      • packages/ai-persistence/tests/persistence-validation.test.ts
      • packages/ai-persistence/tests/reconstruct-generation.test.ts
      • packages/ai-react/src/use-generate-audio.ts
      • packages/ai-react/src/use-generate-image.ts
      • packages/ai-react/src/use-generate-speech.ts
      • packages/ai-react/src/use-generate-video.ts
      • packages/ai-react/src/use-generation.ts
      • packages/ai-react/src/use-summarize.ts
      • packages/ai-react/src/use-transcription.ts
      • packages/ai-react/tests/use-generation.test.ts
      • packages/ai-solid/src/use-generate-audio.ts
      • packages/ai-solid/src/use-generate-image.ts
      • packages/ai-solid/src/use-generate-speech.ts
      • packages/ai-solid/src/use-generate-video.ts
      • packages/ai-solid/src/use-generation.ts
      • packages/ai-solid/src/use-summarize.ts
      • packages/ai-solid/src/use-transcription.ts
      • packages/ai-svelte/src/create-generate-audio.svelte.ts
      • packages/ai-svelte/src/create-generate-image.svelte.ts
      • packages/ai-svelte/src/create-generate-speech.svelte.ts
      • packages/ai-svelte/src/create-generate-video.svelte.ts
      • packages/ai-svelte/src/create-generation.svelte.ts
      • packages/ai-svelte/src/create-summarize.svelte.ts
      • packages/ai-svelte/src/create-transcription.svelte.ts
      • packages/ai-vue/src/use-generate-audio.ts
      • packages/ai-vue/src/use-generate-image.ts
      • packages/ai-vue/src/use-generate-speech.ts
      • packages/ai-vue/src/use-generate-video.ts
      • packages/ai-vue/src/use-generation.ts
      • packages/ai-vue/src/use-summarize.ts
      • packages/ai-vue/src/use-transcription.ts
      • packages/ai/skills/ai-core/client-persistence/SKILL.md
      • packages/ai/skills/ai-core/media-generation/SKILL.md
      • testing/e2e/src/routeTree.gen.ts
      • testing/e2e/src/routes/api.generation-persistence-server.ts
      • testing/e2e/src/routes/generation-persistence-server.tsx
      • testing/e2e/tests/generation-persistence-server.spec.ts
      🚧 Files skipped from review as they are similar to previous changes (35)
      • docs/config.json
      • packages/ai-client/src/index.ts
      • packages/ai-persistence/tests/memory.test.ts
      • packages/ai-react/src/use-transcription.ts
      • packages/ai-react/src/use-generate-image.ts
      • packages/ai-react/src/use-generate-speech.ts
      • packages/ai-angular/src/inject-generate-audio.ts
      • packages/ai-vue/src/use-generate-audio.ts
      • packages/ai-solid/src/use-generate-audio.ts
      • packages/ai-vue/src/use-generate-speech.ts
      • packages/ai-solid/src/use-summarize.ts
      • packages/ai-vue/src/use-generate-image.ts
      • packages/ai-svelte/src/create-generate-audio.svelte.ts
      • packages/ai-vue/src/use-transcription.ts
      • packages/ai-vue/src/use-summarize.ts
      • packages/ai-solid/src/use-generate-speech.ts
      • packages/ai-svelte/src/create-transcription.svelte.ts
      • packages/ai-react/src/use-generate-audio.ts
      • packages/ai-svelte/src/create-summarize.svelte.ts
      • packages/ai-svelte/src/create-generate-video.svelte.ts
      • packages/ai-solid/src/use-generate-image.ts
      • packages/ai-angular/src/inject-generate-video.ts
      • packages/ai-svelte/src/create-generation.svelte.ts
      • packages/ai-vue/src/use-generate-video.ts
      • packages/ai-svelte/src/create-generate-image.svelte.ts
      • packages/ai-solid/src/use-transcription.ts
      • packages/ai-vue/src/use-generation.ts
      • packages/ai-react/src/use-generate-video.ts
      • packages/ai-solid/src/use-generation.ts
      • packages/ai-client/src/generation-client.ts
      • packages/ai-solid/src/use-generate-video.ts
      • packages/ai-angular/src/inject-generation.ts
      • packages/ai-svelte/src/create-generate-speech.svelte.ts
      • packages/ai-react/src/use-generation.ts
      • packages/ai-client/src/generation-types.ts
      @@ -0,0 +115,21 @@
      115+ // withGenerationPersistence records the job's status, result metadata, and
      116+ // usage in the jobs store. durability records the stream so a reload can
      117+ // 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 and
      126+ // X-Run-Id / ?runId). Replay the durability log so a run still streaming
      127+ // 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 last
      132+ // generation job for the thread. Guard access in multi-user apps with the
      133+ // `authorize` option (session → owned thread/job).
      134+ return reconstructGeneration(persistence, request)
      135+}
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

      Authorize the hydration lookup in the sample.

      This public-route example loads job metadata from a caller-controlled jobId/threadId without an ownership check. Derive the session identity and pass authorize before calling reconstructGeneration.

      Proposed fix
      -  return reconstructGeneration(persistence, request)
      +  return reconstructGeneration(persistence, request, {
      +    authorize: async (id, request) => {
      +      const userId = await getSessionUserId(request)
      +      return userId != null && (await userOwnsGeneration(userId, id))
      +    },
      +  })

      Based on learnings: derive identity from server-side session state and authorize ownership before persistence reads.

      📝 Committable suggestion

      ‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      Suggested change
      131- // Otherwise this is the mount-time hydration GET (?threadId): return the last
      132- // generation job for the thread. Guard access in multi-user apps with the
      133- // `authorize` option (session → owned thread/job).
      134- return reconstructGeneration(persistence, request)
      135-}
      131+ // Otherwise this is the mount-time hydration GET (?threadId): return the last
      132+ // generation job for the thread. Guard access in multi-user apps with the
      133+ // `authorize` option (session → owned thread/job).
      134+ return reconstructGeneration(persistence, request, {
      135+ authorize: async (id, request) => {
      136+ const userId = await getSessionUserId(request)
      137+ return userId != null && (await userOwnsGeneration(userId, id))
      138+ },
      139+ })
      140+}
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@docs/persistence/generation-persistence.md` around lines 131 - 135, Update
      the hydration GET example around reconstructGeneration to derive the caller’s
      identity from server-side session state and pass an authorize callback that
      verifies the requested thread/job belongs to that identity before reading
      persistence. Preserve the existing reconstruction behavior after authorization.

      Source: Learnings

      @@ -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 } | null
      479+ }
      480+ const activeRun =
      481+ data.activeRun && typeof data.activeRun.runId === 'string'
      482+ ? { runId: data.activeRun.runId }
      483+ : null
      484+ return {
      485+ resumeSnapshot: data.resumeSnapshot ?? null,
      486+ activeRun,
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

      Validate the JSON envelope before reading activeRun.

      A 200 response containing null, an array, or a primitive throws at data.activeRun; treat a non-object payload as an empty hydration result instead.

      Proposed fix
      -  const data = (await response.json()) as {
      +  const raw: unknown = await response.json()
      +  if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
      +    return { resumeSnapshot: null, activeRun: null }
      +  }
      +  const data = raw as {
           resumeSnapshot?: GenerationHydrationResult['resumeSnapshot']
           activeRun?: { runId?: unknown } | null
         }
      📝 Committable suggestion

      ‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      Suggested change
      476- const data = (await response.json()) as {
      477- resumeSnapshot?: GenerationHydrationResult['resumeSnapshot']
      478- activeRun?: { runId?: unknown } | null
      479- }
      480- const activeRun =
      481- data.activeRun && typeof data.activeRun.runId === 'string'
      482- ? { runId: data.activeRun.runId }
      483- : null
      484- return {
      485- resumeSnapshot: data.resumeSnapshot ?? null,
      486- activeRun,
      476+ const raw: unknown = await response.json()
      477+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
      478+ return { resumeSnapshot: null, activeRun: null }
      479+ }
      480+ const data = raw as {
      481+ resumeSnapshot?: GenerationHydrationResult['resumeSnapshot']
      482+ activeRun?: { runId?: unknown } | null
      483+ }
      484+ const activeRun =
      485+ data.activeRun && typeof data.activeRun.runId === 'string'
      486+ ? { runId: data.activeRun.runId }
      487+ : null
      488+ return {
      489+ resumeSnapshot: data.resumeSnapshot ?? null,
      490+ activeRun,
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-client/src/connection-adapters.ts` around lines 476 - 486,
      Validate the parsed JSON envelope before accessing activeRun in the hydration
      response flow. Treat null, arrays, and primitive payloads as an empty hydration
      result, then only read data.resumeSnapshot and data.activeRun from a non-array
      object while preserving the existing activeRun runId validation.
      @@ -0,0 +116,21 @@
      116+ async head(key) {
      117+ const obj = await bucket.head(key)
      118+ return obj ? toRecord(obj) : null
      119+ },
      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+ }
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

      Honor limit: 0 in the R2 adapter sample.

      The guide correctly notes that R2 treats zero as its default limit, but the sample never applies the required special case. Consumers copying this implementation will return objects for limit: 0.

      Proposed fix
       async list(options) {
      +  if (options?.limit === 0) {
      +    return { objects: [] }
      +  }
         const page = await bucket.list({
      📝 Committable suggestion

      ‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      Suggested change
      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- }
      125+ async list(options) {
      126+ if (options?.limit === 0) {
      127+ return { objects: [] }
      128+ }
      129+ const page = await bucket.list({
      130+ ...(options?.prefix !== undefined ? { prefix: options.prefix } : {}),
      131+ ...(options?.cursor !== undefined ? { cursor: options.cursor } : {}),
      132+ ...(options?.limit !== undefined ? { limit: options.limit } : {}),
      133+ // R2 omits httpMetadata/customMetadata from list rows unless asked.
      134+ include: ['httpMetadata', 'customMetadata'],
      135+ })
      136+ return {
      137+ objects: page.objects.map(toRecord),
      138+ ...(page.truncated ? { cursor: page.cursor, truncated: true } : {}),
      139+ }
      🧰 Tools
      🪛 SkillSpector (2.3.11)

      [warning] 373: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.

      Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.

      (Memory Poisoning (MP2))


      [warning] 375: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.

      Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.

      (Memory Poisoning (MP2))


      [warning] 376: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.

      Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.

      (Memory Poisoning (MP2))


      [warning] 377: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.

      Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.

      (Memory Poisoning (MP2))


      [warning] 378: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.

      Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.

      (Memory Poisoning (MP2))

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In
      `@packages/ai-persistence/skills/ai-persistence/build-cloudflare-artifact-store/SKILL.md`
      around lines 125 - 136, The R2 adapter’s list method must return no objects when
      options.limit is 0 instead of relying on R2’s default behavior. Update list to
      handle the zero-limit case explicitly while preserving the existing bucket.list
      pagination and mapping behavior for other limits.
      @@ -112,0 +145,21 @@
      145+### Mode B — server-driven (`persistence: true`)
      146+
      147+```tsx
      148+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 **last
      158+ generation** for its `threadId` from the server via the connection's
      159+ `hydrateGeneration` handler (the SSE/HTTP adapters issue a `GET` with
      160+ `?threadId=` to the same endpoint URL) and repaints that snapshot.
      161+- The server `GET` returns `reconstructGeneration(persistence, request)` from
      162+ `@tanstack/ai-persistence` — it resolves the job by `?jobId=` (preferred) or
      163+ the latest job linked to `?threadId=`, and needs `stores.jobs`. Pair it with
      164+ `withGenerationPersistence` on the generation route. See
      165+ `ai-core/media-generation` and `ai-persistence`.
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

      Add a server-side example for server-driven persistence.

      This section documents server hydration and references withGenerationPersistence/reconstructGeneration, but only shows the client hook. Add a minimal server endpoint snippet so readers can implement both halves without leaving this guide.

      As per coding guidelines, documentation covering both server and client behavior must include snippets for both halves.

      🧰 Tools
      🪛 SkillSpector (2.3.11)

      [warning] 52: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.

      Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.

      (Memory Poisoning (MP2))

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai/skills/ai-core/client-persistence/SKILL.md` around lines 145 -
      165, Add a minimal server endpoint example to the “Mode B — server-driven”
      section, alongside the existing useGenerateImage client snippet. Show the
      generation route using withGenerationPersistence and returning
      reconstructGeneration(persistence, request), including the required stores.jobs
      configuration, while preserving the existing hydration behavior and references.

      Source: Coding guidelines

    8. Actionable comments posted: 8

      🤖 Prompt for all review comments with AI agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      Inline comments:
      In `@docs/config.json`:
      - Around line 265-269: Add the missing updatedAt field to the Keep Generated
      Files navigation entry, using the value 2026-07-28 to match its addedAt
      timestamp and the adjacent Generation Persistence entry.
      
      In `@docs/media/audio-generation.md`:
      - Around line 164-167: Update the guidance in docs/media/audio-generation.md
      lines 164-167 and docs/media/image-generation.md lines 511-513 to separate
      Generation Persistence from generated-media retention: describe Generation
      Persistence only as restoring run, status, result, or batch state across reloads
      or dropped connections, and link Keep Generated Files for retaining audio or
      image bytes after provider URLs expire.
      
      In `@docs/persistence/client-persistence.md`:
      - Around line 73-77: The persistence documentation must describe snapshot
      hydration rather than automatic generation resumption. In
      docs/persistence/client-persistence.md lines 73-77, replace the reload-survival
      wording with restoration of the last known generation status/result and
      explicitly state that provider work is not restarted. In
      docs/media/video-generation.md lines 49-54, replace the run-pickup wording with
      last-state restoration and clarify that only reconnection to an active
      server-side durable stream can replay live generation updates.
      
      In `@docs/persistence/keep-generated-files.md`:
      - Around line 91-93: Update the documentation wording around resultArtifacts and
      pendingArtifacts to replace “serve route” with clearer terminology such as
      “serving route,” “artifact route,” or “this route,” without changing the
      described behavior.
      - Around line 14-20: In the byte-storage documentation paragraph, replace “a
      both-or-neither pair” with clear all-or-nothing wording stating that the
      artifacts and blobs stores must be provided together. Preserve the surrounding
      behavior description unchanged.
      - Around line 68-76: Update the GET handler to authorize the requesting caller
      before invoking retrieveArtifact, using the existing ownership or tenant-check
      mechanism and artifactId as the lookup subject. Deny unauthorized requests
      without retrieving or serving the artifact/blob, while preserving the current
      missing-id and successful retrieval behavior.
      - Around line 87-93: Add a concise client-side example to the persistence
      documentation showing a generation hook reading resultArtifacts and
      pendingArtifacts, rendering the observed artifact references, and linking each
      artifact to the documented serve endpoint. Keep the existing server-side example
      unchanged and use the documented hook and reference fields.
      - Around line 97-99: Rewrite the final clause in the “Generation persistence”
      description so it forms a grammatically complete sentence, referring to the
      `jobs` store as the foundation that byte storage builds on.
      🪄 Autofix (Beta)

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: b64c2254-67be-4fd8-a198-c1c4ac62c205

      📥 Commits

      Reviewing files that changed from the base of the PR and between 36fc27fdc64cc19a4a000d42f960ac48368e0efa and 09460752bad0a46e301f25ebd585cbff284aea5b.

      📒 Files selected for processing (10)
      • docs/config.json
      • docs/media/audio-generation.md
      • docs/media/generation-hooks.md
      • docs/media/image-generation.md
      • docs/media/transcription.md
      • docs/media/video-generation.md
      • docs/persistence/client-persistence.md
      • docs/persistence/generation-persistence.md
      • docs/persistence/keep-generated-files.md
      • docs/persistence/overview.md
      @@ -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.
      7272
      73+The generation hooks (`useGenerateImage` / `useGenerateVideo` / …) make the same
      74+choice: `persistence: true` is server-driven and a storage adapter is
      75+client-driven, so a long media run survives a reload the way a conversation does.
      76+See [Generation persistence](./generation-persistence) for the generation-specific
      77+setup.
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

      Use snapshot-hydration language instead of automatic-resumption language.

      A full reload restores last-known generation metadata but does not automatically resume or restart provider work. Only an active server-side durable stream can support dropped-connection replay.

      • docs/persistence/client-persistence.md#L73-L77: replace “survives a reload the way a conversation does” with restoration of the last known status/result and explicitly state that provider work is not restarted.
      • docs/media/video-generation.md#L49-L54: replace “picks the run back up instead of starting over” with last-state restoration plus the narrower live-stream reconnection behavior.
      📍 Affects 2 files
      • docs/persistence/client-persistence.md#L73-L77 (this comment)
      • docs/media/video-generation.md#L49-L54
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@docs/persistence/client-persistence.md` around lines 73 - 77, The persistence
      documentation must describe snapshot hydration rather than automatic generation
      resumption. In docs/persistence/client-persistence.md lines 73-77, replace the
      reload-survival wording with restoration of the last known generation
      status/result and explicitly state that provider work is not restarted. In
      docs/media/video-generation.md lines 49-54, replace the run-pickup wording with
      last-state restoration and clarify that only reconnection to an active
      server-side durable stream can replay live generation updates.
      @@ -0,0 +1,20 @@
      1+---
      2+title: Keep Generated Files
      3+id: keep-generated-files
      4+---
      5+
      6+# Keep Generated Files
      7+
      8+Provider URLs for generated media expire. A Sora clip, a batch of images, a long
      9+audio track — the model hands you a URL that stops working after a while, and
      10+once it does the output is gone. To keep the output, save the generated bytes to
      11+your own storage and serve them from your own origin, where they outlive the
      12+provider's link.
      13+
      14+This is a server-side opt-in that layers on **top of** the `jobs` store
      15+[Generation persistence](./generation-persistence) already requires. Byte storage
      16+adds two more stores: an `artifacts` store (metadata) and a `blobs` store (the
      17+bytes). They are a both-or-neither pair — provide both and
      18+`withGenerationPersistence` writes each generated file's bytes to the blob store,
      19+records an `ArtifactRecord`, and attaches durable references to the result and the
      20+job record; provide neither and only the job record is kept.
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

      Clarify the all-or-nothing store requirement.

      Replace “a both-or-neither pair” with clearer wording such as “an all-or-nothing pair” or “both must be provided together.”

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@docs/persistence/keep-generated-files.md` around lines 14 - 20, In the
      byte-storage documentation paragraph, replace “a both-or-neither pair” with
      clear all-or-nothing wording stating that the artifacts and blobs stores must be
      provided together. Preserve the surrounding behavior description unchanged.
      @@ -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: it
      67+// 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 })
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

      Authorize artifact reads before serving bytes.

      This route accepts an arbitrary artifact ID and returns its stored contents without an ownership or tenant check. In a multi-user deployment, callers who obtain another user’s ID can read that media; add authorization before retrieveArtifact or explicitly constrain this route to trusted callers.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@docs/persistence/keep-generated-files.md` around lines 68 - 76, Update the
      GET handler to authorize the requesting caller before invoking retrieveArtifact,
      using the existing ownership or tenant-check mechanism and artifactId as the
      lookup subject. Deny unauthorized requests without retrieving or serving the
      artifact/blob, while preserving the current missing-id and successful retrieval
      behavior.
      @@ -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 for
      88+development and tests; point `jobs` / `artifacts` / `blobs` at a durable backend
      89+for production. Control what gets captured with `withGenerationPersistence`'s
      90+`extractArtifacts` (return your own descriptors) and `nameArtifact` (name each
      91+file) options. On the client, the observed references show up on the generation
      92+hook as `resultArtifacts` (and `pendingArtifacts` while streaming), so the UI
      93+can link straight to this serve route.
      94+
      95+## Where to go next
      96+
      97+- [Generation persistence](./generation-persistence): the two-mode record that
      98+ survives a reload or a dropped connection, and the `jobs` store byte storage
      99+ builds on.
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

      Fix the broken sentence about byte storage.

      Rewrite the final clause, for example: “...and the jobs store that byte storage builds on.”

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@docs/persistence/keep-generated-files.md` around lines 97 - 99, Rewrite the
      final clause in the “Generation persistence” description so it forms a
      grammatically complete sentence, referring to the `jobs` store as the foundation
      that byte storage builds on.
    9. Actionable comments posted: 2

      Caution

      Some comments are outside the diff and can’t be posted inline due to platform limitations.

      ⚠️ Outside diff range comments (1)
      packages/ai-client/src/generation-client.ts (1)

      595-631: 🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

      Per-chunk resumeState notification re-renders every framework consumer on every stream event.

      observeResumeSnapshot calls notifyResumeSnapshotChanged() → emitResumeState() on every chunk, and emitResumeState() always constructs a brand-new resumeState object via spread — even when only lastEvent changed. This mirrors the exact issue previously flagged against onResumeSnapshotChange (now on onResumeStateChange): every React setResumeState, Vue ref update, and Angular signal.set() downstream (use-generation.ts, use-generate-video.ts, inject-generate-video.ts) fires on every chunk of a long stream, on top of existing progress/result re-renders.

      Notably, persistResumeSnapshot already dedupes writes via resumeSnapshotSignature specifically because the snapshot reducer changes on every chunk including lastEvent-only changes — the same dedup should gate the notify path.

      ⚡ Proposed fix: dedupe notify path the same way persistence writes are deduped
         private observeResumeSnapshot(chunk: StreamChunk): void {
           this.resumeSnapshot = updateGenerationResumeSnapshot(
             this.resumeSnapshot,
             chunk,
           )
      -    this.notifyResumeSnapshotChanged()
      +    const signature = resumeSnapshotSignature(this.resumeSnapshot)
      +    if (signature !== this.lastNotifiedSnapshotSignature) {
      +      this.lastNotifiedSnapshotSignature = signature
      +      this.notifyResumeSnapshotChanged()
      +    }
           void this.persistResumeSnapshot(this.resumeSnapshot)
         }
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-client/src/generation-client.ts` around lines 595 - 631,
      Deduplicate resume notifications in observeResumeSnapshot using the existing
      resumeSnapshotSignature logic from persistResumeSnapshot. Only call
      notifyResumeSnapshotChanged, including onResumeStateChange and the internal
      snapshot callback, when the signature changes; suppress updates caused solely by
      per-chunk lastEvent changes while preserving notifications for meaningful
      resume-state or pending-artifact changes.
      🧹 Nitpick comments (1)
      packages/ai-solid/tests/use-generation.test.ts (1)

      1360-1372: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      Assertion doesn't prove resumeState was ever set.

      The run never observes a non-null resumeState, so this test would pass even if resumeState were never populated. Capturing it mid-stream (or asserting it was non-null before RUN_FINISHED) would make the "clears" claim real.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/ai-solid/tests/use-generation.test.ts` around lines 1360 - 1372,
      Update the test around useGeneration so it observes resumeState while the
      streamed run is still in progress, asserting it becomes non-null before
      completion and returns null after result.generate resolves. Coordinate the mock
      stream or completion trigger as needed to capture the mid-stream state, while
      preserving the existing success assertion.
      🤖 Prompt for all review comments with AI agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      Inline comments:
      In @.changeset/generation-persistence.md:
      - Line 18: Update the reconstructGeneration guidance to require ownership
      authorization before any persistence access, rather than describing authorize as
      optional. State that multi-user routes must derive the user identity server-side
      and validate the requested jobId or threadId through the authorize callback
      before loading data.
      
      In `@docs/persistence/generation-persistence.md`:
      - Around line 315-326: Update the “What the record holds” section to clarify
      that result === null after reload applies only to generated media results
      without persisted bytes, while text results and usage are restored normally.
      Keep the artifact/blob backend and durable artifactUrl guidance scoped to media
      restoration.
      
      ---
      
      Outside diff comments:
      In `@packages/ai-client/src/generation-client.ts`:
      - Around line 595-631: Deduplicate resume notifications in observeResumeSnapshot
      using the existing resumeSnapshotSignature logic from persistResumeSnapshot.
      Only call notifyResumeSnapshotChanged, including onResumeStateChange and the
      internal snapshot callback, when the signature changes; suppress updates caused
      solely by per-chunk lastEvent changes while preserving notifications for
      meaningful resume-state or pending-artifact changes.
      
      ---
      
      Nitpick comments:
      In `@packages/ai-solid/tests/use-generation.test.ts`:
      - Around line 1360-1372: Update the test around useGeneration so it observes
      resumeState while the streamed run is still in progress, asserting it becomes
      non-null before completion and returns null after result.generate resolves.
      Coordinate the mock stream or completion trigger as needed to capture the
      mid-stream state, while preserving the existing success assertion.
      🪄 Autofix (Beta)

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 7e9b5dba-4e70-488a-bc10-a6c563f8ebf6

      📥 Commits

      Reviewing files that changed from the base of the PR and between 09460752bad0a46e301f25ebd585cbff284aea5b and 1adbe2a2513e72efc96a377b4f2c6e26c4590d2f.

      📒 Files selected for processing (61)
      • .changeset/generation-persistence.md
      • docs/config.json
      • docs/persistence/generation-persistence.md
      • docs/persistence/keep-generated-files.md
      • examples/ts-react-chat/src/routes/generations.image.tsx
      • packages/ai-angular/src/inject-generate-audio.ts
      • packages/ai-angular/src/inject-generate-image.ts
      • packages/ai-angular/src/inject-generate-speech.ts
      • packages/ai-angular/src/inject-generate-video.ts
      • packages/ai-angular/src/inject-generation.ts
      • packages/ai-angular/src/inject-summarize.ts
      • packages/ai-angular/src/inject-transcription.ts
      • packages/ai-angular/tests/inject-generation.test.ts
      • packages/ai-client/src/generation-client.ts
      • packages/ai-client/src/generation-reconstruct.ts
      • packages/ai-client/src/generation-types.ts
      • packages/ai-client/src/index.ts
      • packages/ai-client/src/storage-adapters.ts
      • packages/ai-client/src/video-generation-client.ts
      • packages/ai-client/tests/generation-client.test.ts
      • packages/ai-persistence/src/middleware.ts
      • packages/ai-persistence/tests/generation-artifacts.test.ts
      • packages/ai-react/src/use-generate-audio.ts
      • packages/ai-react/src/use-generate-image.ts
      • packages/ai-react/src/use-generate-speech.ts
      • packages/ai-react/src/use-generate-video.ts
      • packages/ai-react/src/use-generation.ts
      • packages/ai-react/src/use-summarize.ts
      • packages/ai-react/src/use-transcription.ts
      • packages/ai-react/tests/use-generation.test.ts
      • packages/ai-solid/src/use-generate-audio.ts
      • packages/ai-solid/src/use-generate-image.ts
      • packages/ai-solid/src/use-generate-video.ts
      • packages/ai-solid/src/use-generation.ts
      • packages/ai-solid/src/use-summarize.ts
      • packages/ai-solid/src/use-transcription.ts
      • packages/ai-solid/tests/use-generation.test.ts
      • packages/ai-svelte/src/create-generate-audio.svelte.ts
      • packages/ai-svelte/src/create-generate-image.svelte.ts
      • packages/ai-svelte/src/create-generate-speech.svelte.ts
      • packages/ai-svelte/src/create-generate-video.svelte.ts
      • packages/ai-svelte/src/create-generation.svelte.ts
      • packages/ai-svelte/src/create-summarize.svelte.ts
      • packages/ai-svelte/src/create-transcription.svelte.ts
      • packages/ai-svelte/tests/create-generation.test.ts
      • packages/ai-vue/src/use-generate-audio.ts
      • packages/ai-vue/src/use-generate-image.ts
      • packages/ai-vue/src/use-generate-video.ts
      • packages/ai-vue/src/use-generation.ts
      • packages/ai-vue/src/use-summarize.ts
      • packages/ai-vue/src/use-transcription.ts
      • packages/ai-vue/tests/use-generation.test.ts
      • packages/ai/skills/ai-core/client-persistence/SKILL.md
      • packages/ai/skills/ai-core/media-generation/SKILL.md
      • packages/ai/src/types.ts
      • testing/e2e/src/routes/api.generation-persistence-server.ts
      • testing/e2e/src/routes/api.generation-persistence.ts
      • testing/e2e/src/routes/generation-persistence-server.tsx
      • testing/e2e/src/routes/generation-persistence.tsx
      • testing/e2e/tests/generation-persistence-server.spec.ts
      • testing/e2e/tests/generation-persistence.spec.ts
      💤 Files with no reviewable changes (2)
      • packages/ai-react/src/use-generate-speech.ts
      • packages/ai-svelte/src/create-generate-speech.svelte.ts
      🚧 Files skipped from review as they are similar to previous changes (27)
      • packages/ai-client/src/index.ts
      • examples/ts-react-chat/src/routes/generations.image.tsx
      • testing/e2e/tests/generation-persistence.spec.ts
      • testing/e2e/src/routes/generation-persistence.tsx
      • docs/persistence/keep-generated-files.md
      • packages/ai-angular/src/inject-generate-audio.ts
      • docs/config.json
      • packages/ai-vue/src/use-generate-image.ts
      • packages/ai-vue/tests/use-generation.test.ts
      • packages/ai-vue/src/use-transcription.ts
      • packages/ai-vue/src/use-summarize.ts
      • packages/ai-solid/src/use-transcription.ts
      • packages/ai-angular/src/inject-generate-speech.ts
      • packages/ai-solid/src/use-summarize.ts
      • packages/ai-solid/src/use-generate-image.ts
      • packages/ai-solid/src/use-generate-audio.ts
      • packages/ai-svelte/tests/create-generation.test.ts
      • testing/e2e/src/routes/api.generation-persistence-server.ts
      • testing/e2e/src/routes/api.generation-persistence.ts
      • packages/ai-svelte/src/create-generate-audio.svelte.ts
      • packages/ai-angular/src/inject-summarize.ts
      • packages/ai-vue/src/use-generate-audio.ts
      • packages/ai-persistence/src/middleware.ts
      • packages/ai-persistence/tests/generation-artifacts.test.ts
      • packages/ai-client/src/generation-types.ts
      • packages/ai-client/src/video-generation-client.ts
      • packages/ai-client/tests/generation-client.test.ts
      @@ -0,0 +1,18 @@
      1+---
      2+'@tanstack/ai': minor
      3+'@tanstack/ai-utils': minor
      4+'@tanstack/ai-persistence': minor
      5+'@tanstack/ai-client': minor
      6+'@tanstack/ai-event-client': minor
      7+'@tanstack/ai-react': minor
      8+'@tanstack/ai-solid': minor
      9+'@tanstack/ai-vue': minor
      10+'@tanstack/ai-svelte': minor
      11+'@tanstack/ai-angular': minor
      12+---
      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.
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

      Make ownership authorization mandatory in the guidance.

      authorize being optional means this helper can otherwise load a client-supplied jobId/threadId without an ownership check. State that multi-user routes must derive identity server-side and authorize before persistence access.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In @.changeset/generation-persistence.md at line 18, Update the
      reconstructGeneration guidance to require ownership authorization before any
      persistence access, rather than describing authorize as optional. State that
      multi-user routes must derive the user identity server-side and validate the
      requested jobId or threadId through the authorize callback before loading data.

      Source: Learnings

    10. Superseded by #1011 — same change on the renamed branch feat/generation-persistence-full (GitHub can't re-point a PR's head branch, so the rename required a replacement PR). Title updated too: the branch always contained the server-side persistence half, not just the client.

    11. tombeckenham closed this

Sign in to join this conversation.