Skip to content
Source
Sign inSign up
TanStack/ai

feat(persistence): generation run persistence (client + server) #1011

Mergedtombeckenhammerged 67 commits intomain fromrefs/pull/1011/headmerged by tombeckenham 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.

Supersedes #997 (same change, renamed from feat/generation-persistence-client — the branch always contained the server half too) and folds in #998.

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).

Summary by CodeRabbit

  • New Features
    • Added end-to-end generation persistence across reloads/dropped connections, including resumable generation identity via threadId + ephemeral runId.
    • Durably restore generated media using application-served artifact URLs (optional artifact metadata + durable byte storage).
    • Generation hooks now expose resumeState and correctly repaint status/result/error when persistence is enabled.
    • Introduced server-driven generation hydration keyed by threadId, plus secure URL input fetching protections.
    • Generation events now include threadId/runId for better correlation.
  • Documentation
    • Expanded threads/runs, generation persistence, durable media, adapter/store contracts, and server route examples.
  • Tests
    • Added extensive resume/persistence coverage across client/server modes, plus new type-level and unit/integration tests.
    1. 🚀 Changeset Version Preview

      19 package(s) bumped directly, 32 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-openai0.17.1 → 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/openai-base0.9.9 → 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-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

      🟨 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
    2. View your CI Pipeline Execution ↗ for commit 8f2305e3116b95d5dbc7c7e1453ccb9ee4096bd9

      CommandStatusDurationResult
      nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded7m 51sView ↗
      nx run-many --targets=build --exclude=examples/...✅ Succeeded1m 52sView ↗

      ☁️ Nx Cloud last updated this comment at 2026-07-31 02:10:05 UTC

    3. 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 resumable generation snapshots, server-side generation-run and artifact/blob stores, durable media URLs, secure artifact fetching, reconstruction endpoints, framework hook support, documentation, examples, and end-to-end tests.

      Changes

      Generation persistence

      Layer / File(s)Summary
      Client resume state and hydration
      packages/ai-client/...
      Generation clients persist and validate snapshots, restore statuses and results, expose resumeState, hydrate through connection adapters, rejoin active runs, and guard updates after disposal.
      Server stores and middleware
      packages/ai-persistence/..., packages/ai-utils/...
      Generation-run, artifact, and blob contracts are added with in-memory implementations, artifact extraction, bounded URL fetching, durable URL rewriting, reconstruction, retrieval, and authorization support.
      Core generation pipeline
      packages/ai/src/..., packages/ai-event-client/src/index.ts
      Generation activities propagate threadId/runId, apply middleware result transforms, and emit persisted artifact references.
      Framework integrations
      packages/ai-react/..., packages/ai-vue/..., packages/ai-solid/..., packages/ai-svelte/..., packages/ai-angular/...
      Generation hooks and injectables accept persistence and resume options, reconstruct typed results, expose resume state, and suppress post-disposal updates.
      Documentation and examples
      docs/..., examples/ts-react-chat/..., packages/ai/skills/..., packages/ai-persistence/skills/...
      Persistence concepts, adapter contracts, artifact serving, security controls, and example configurations are documented; example generation routes use persistence and Grok adapters.
      End-to-end coverage
      testing/e2e/...
      Provider-free client-driven and server-driven persistence routes and Playwright tests cover reload restoration, durable image URLs, local-storage behavior, and reset.

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

      Possibly related PRs

      • TanStack/ai#997: Overlaps with generation resume snapshots, persistence naming, and storage behavior.
      • TanStack/ai#999: Overlaps with generation persistence middleware, reconstruction, artifact/blob storage, and framework integration.

      Suggested reviewers: jherr

      🚥 Pre-merge checks | ✅ 4 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 49.66% 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
      Title check✅ PassedThe title is concise and accurately summarizes the main change: generation run persistence for client and server.
      Description check✅ PassedThe description follows the required template and includes the changes, checklist, and release impact sections.
      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.
      ✨ Finishing Touches 💡 1
      📝 Generate docstrings 💡
      • Create stacked PR
      • Commit on current branch
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Commit unit tests in branch `feat/generation-persistence-full`

      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.
    4. Open in StackBlitz

      @tanstack/ai

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

      @tanstack/ai-acp

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

      @tanstack/ai-angular

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

      @tanstack/ai-anthropic

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

      @tanstack/ai-bedrock

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

      @tanstack/ai-claude-code

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

      @tanstack/ai-client

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

      @tanstack/ai-code-mode

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

      @tanstack/ai-code-mode-skills

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

      @tanstack/ai-codex

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

      @tanstack/ai-devtools-core

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

      @tanstack/ai-durable-stream

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

      @tanstack/ai-elevenlabs

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

      @tanstack/ai-event-client

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

      @tanstack/ai-fal

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

      @tanstack/ai-gemini

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

      @tanstack/ai-grok

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

      @tanstack/ai-grok-build

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

      @tanstack/ai-groq

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

      @tanstack/ai-isolate-cloudflare

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

      @tanstack/ai-isolate-node

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

      @tanstack/ai-isolate-quickjs

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

      @tanstack/ai-mcp

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

      @tanstack/ai-memory

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

      @tanstack/ai-mistral

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

      @tanstack/ai-ollama

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

      @tanstack/ai-openai

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

      @tanstack/ai-opencode

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

      @tanstack/ai-openrouter

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

      @tanstack/ai-persistence

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

      @tanstack/ai-preact

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

      @tanstack/ai-react

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

      @tanstack/ai-react-ui

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

      @tanstack/ai-sandbox

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

      @tanstack/ai-sandbox-cloudflare

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

      @tanstack/ai-sandbox-daytona

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

      @tanstack/ai-sandbox-docker

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

      @tanstack/ai-sandbox-local-process

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

      @tanstack/ai-sandbox-sprites

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

      @tanstack/ai-sandbox-vercel

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

      @tanstack/ai-solid

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

      @tanstack/ai-solid-ui

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

      @tanstack/ai-svelte

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

      @tanstack/ai-utils

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

      @tanstack/ai-vue

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

      @tanstack/ai-vue-ui

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

      @tanstack/openai-base

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

      @tanstack/preact-ai-devtools

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

      @tanstack/react-ai-devtools

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

      @tanstack/solid-ai-devtools

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

      commit: 8f2305e

    5. Actionable comments posted: 14

      Note

      Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

      Caution

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

      ⚠️ Outside diff range comments (1)
      packages/ai-svelte/src/create-generate-speech.svelte.ts (1)

      111-114: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

      Document TTS persistence returning result === null.

      createGenerateSpeech supports persistence / threadId / initialResumeSnapshot, but it passes no reconstructResult to createGeneration and there is no speech reconstruct mapper. Since TTSResult.audio is base64 bytes plus format, persisted speech metadata reloads with status/restoration state, but the audio cannot be rebuilt from storage — document this in CreateGenerateSpeechOptions to avoid leaving users with a persisting run that never plays.

      🤖 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-speech.svelte.ts` around lines 111 -
      114, Document in CreateGenerateSpeechOptions that persistence, threadId, and
      initialResumeSnapshot restore speech state but do not reconstruct
      TTSResult.audio; persisted runs may therefore return result === null and cannot
      play audio after reload. Keep the existing createGeneration call unchanged
      unless needed to align the option documentation.
      🟡 Minor comments (16)
      packages/ai/skills/ai-core/media-generation/SKILL.md-628-632 (1)

      628-632: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

      Scope the no-byte-storage limitation to media payloads.

      Transcription and summarize rebuild result from persisted text/metadata (reconstructTranscriptionResult and reconstructSummarizeResult), while only image/audio/video refs require the durable artifactUrl blob route. Change this paragraph to say the media refs/media results need byte storage, not that result stays null generally.

      🤖 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/media-generation/SKILL.md` around lines 628 - 632,
      Revise the no-byte-storage paragraph to scope the limitation specifically to
      image, audio, and video media refs/results that depend on durable artifact
      storage. Preserve that transcription and summarize restore their results from
      persisted text/metadata via reconstructTranscriptionResult and
      reconstructSummarizeResult, and remove the blanket claim that a reload leaves
      result null.
      packages/ai/skills/ai-core/client-persistence/SKILL.md-156-158 (1)

      156-158: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

      Clarify which results need byte storage on reload.

      The client snapshot already preserves text results (transcription.text and summary) and artifact refs, so this should say media-bearing results need server byte storage / artifactUrl while text-output results restore without it.

      🤖 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 156 -
      158, The client snapshot preserves text outputs such as transcription.text and
      summary, so revise the result persistence guidance to distinguish them from
      media-bearing results. State that only media-bearing results require server byte
      storage or artifactUrl for reload, while text-output results restore without it,
      and update the surrounding examples accordingly.
      packages/ai-persistence/skills/ai-persistence/SKILL.md-45-63 (1)

      45-63: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

      New store keys contradict "Critical rule 5".

      This section documents generationRuns / artifacts / blobs, but rule 5 (Line 197) still states stores accepts only messages, runs, interrupts, metadata. An agent reading the rules section will reject valid configs — update that line alongside this table.

      🤖 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/SKILL.md` around lines 45 - 63,
      The “Critical rule 5” store-key list must include the generation persistence
      stores documented in the table. Update the rule’s `stores` description to accept
      `generationRuns`, `artifacts`, and `blobs` in addition to the existing chat
      stores, preserving the requirement that `artifacts` and `blobs` are provided
      together.
      packages/ai-persistence/src/middleware.ts-454-455 (1)

      454-455: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

      Fallback mime ${type}/mpeg yields bogus image/mpeg / video/mpeg for prompt media.

      When a prompt part omits source.mimeType, images get stored (and later served) as image/mpeg. A per-type default is cheap:

      🐛 Proposed fix
      -  const mimeType = stringField(source, 'mimeType') ?? `${type}/mpeg`
      +  const defaultMime =
      +    type === 'image' ? 'image/png' : type === 'video' ? 'video/mp4' : 'audio/mpeg'
      +  const mimeType = stringField(source, 'mimeType') ?? defaultMime
      🤖 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 454 - 455, Update the
      mimeType fallback in the source-processing logic near sourceType to use a valid
      per-type default instead of always constructing `${type}/mpeg`; preserve an
      explicitly provided source.mimeType and ensure image and video prompt media
      receive appropriate media types.
      packages/ai-persistence/src/middleware.ts-383-405 (1)

      383-405: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

      parseDataUrl rejects data URLs carrying media-type parameters.

      data:image/png;charset=utf-8;base64,… doesn't match the regex (only a bare ;base64 may follow the mime), so descriptorBody falls through to the URL branch and throws Refusing to fetch artifact over data: — failing the whole run instead of storing the inline bytes. Allowing arbitrary ;param=value segments before the optional ;base64 fixes it.

      🐛 Proposed fix
      -  const match = /^data:([^;,]+)?(;base64)?,(.*)$/s.exec(value)
      +  const match = /^data:([^;,]+)?((?:;[^;,]*)*?)(;base64)?,(.*)$/s.exec(value)
         if (!match) return undefined
         const mimeType = match[1] || 'application/octet-stream'
      -  const raw = match[3] ?? ''
      +  const raw = match[4] ?? ''

      and switch the base64 check to match[3].

      🤖 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 383 - 405, Update
      parseDataUrl’s data-URL regex to accept arbitrary media-type parameter segments
      before the optional ;base64 marker, while preserving the existing MIME type and
      payload captures. Adjust the base64 detection to use the new capture index
      (match[3]) so parameterized URLs such as data:image/png;charset=utf-8;base64,...
      are decoded as inline bytes.
      packages/ai-persistence/skills/ai-persistence/build-cloudflare-artifact-store/SKILL.md-345-355 (1)

      345-355: 🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

      The serve-route sample tells readers to authorize but shows no check.

      Agents copy this handler as-is, producing an endpoint where any guessed artifactId streams bytes. Show the actual check against the session-derived owner and record.threadId, returning 404.

      🛡️ Proposed fix
         const record = await retrieveArtifact(persistence, artifactId)
         if (!record) return new Response('Not found', { status: 404 })
      +
      +  // Ownership comes from server-side session state, never from the caller's id.
      +  const session = await getSession(request, env)
      +  if (!session || !(await ownsThread(env, session.userId, record.threadId))) {
      +    return new Response('Not found', { status: 404 })
      +  }
      🤖 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 345 - 355, Update the GET handler sample to derive the
      authenticated owner from the session and validate it against the retrieved
      record’s record.threadId before calling retrieveBlob. Return a 404 response when
      authorization fails, ensuring artifact bytes are never served for an
      unauthorized artifactId.

      Source: Learnings

      packages/ai-client/src/connection-adapters.ts-781-791 (1)

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

      resumeState.threadId is typed optional but is required by the client parser.

      parseGenerationResumeSnapshot (packages/ai-client/src/generation-types.ts, Lines 463-465) rejects the entire snapshot when resumeState lacks a threadId, so a server response matching this declared type is silently dropped rather than partially adopted. Either make threadId required here or have the parser tolerate its absence.

      🛠️ Proposed fix (tighten the type)
      -    resumeState: { threadId?: string; runId: string } | null
      +    resumeState: { threadId: string; runId: string } | null
      🤖 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 781 - 791, Make
      resumeState.threadId required in the GenerationHydrationResult interface,
      matching the validation behavior of parseGenerationResumeSnapshot. Update the
      nested resumeState type while preserving its nullable state and existing runId
      requirement.
      packages/ai-client/src/generation-client.ts-851-885 (1)

      851-885: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

      Failed rejoin leaves the visible state stuck on generating.

      The catch only records the snapshot error; status / error are never repainted, so a rejoin that throws (network drop, joinRun 404 after the log expired) leaves status: 'generating' with isLoading: false and no error surfaced — the exact stuck state recordResumeSnapshotError exists to avoid. generate()'s catch sets both.

      🛠️ Proposed fix
             } catch (error) {
               if (!controller.signal.aborted) {
      -          this.recordResumeSnapshotError(
      -            error instanceof Error ? error : new Error(String(error)),
      -          )
      +          const err = error instanceof Error ? error : new Error(String(error))
      +          this.setError(err)
      +          this.setStatus('error')
      +          this.recordResumeSnapshotError(err)
      +          this.callbacksRef.onError?.(err)
               }
             } finally {
      🤖 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 851 - 885, Update
      the catch block in rejoinInFlight to surface failed rejoin errors through the
      same status and error state updates used by generate(), while preserving the
      existing abort check and snapshot error recording. Ensure a non-aborted
      joinRun/processStream failure repaints the visible error state instead of
      leaving status as generating.
      packages/ai-react/src/use-generate-speech.ts-125-134 (1)

      125-134: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

      Document the missing speech snapshot restore path.

      Speech result contains base64 audio bytes, and client-driven persistence only stores the lightweight GenerationResultSnapshot artifacts/ref metadata. Because useGenerateSpeech has no reconstructResult, a restored completed run will repaint result = null even when status/resumeState are restored — update the speech options docs to say restored result data is unavailable unless an onResult transform provides durable restore data.

      🤖 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 125 - 134, Update
      the options documentation for useGenerateSpeech and its useGeneration
      configuration to document that completed speech results cannot be reconstructed
      from restored snapshots because audio bytes are not persisted; restored runs may
      have status/resumeState without result data unless an onResult transform
      supplies durable restore data.
      .changeset/generation-persistence.md-22-22 (1)

      22-22: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

      Clarify the result.artifacts wording.

      “Refs on result.artifacts” is awkward; use “refs in result.artifacts” for clearer documentation.

      🤖 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 22, Update the generation
      persistence documentation sentence describing restored media references,
      replacing “refs on result.artifacts” with “refs in result.artifacts” while
      preserving the surrounding behavior and wording.

      Source: Linters/SAST tools

      docs/interrupts/overview.md-44-49 (1)

      44-49: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

      Avoid implying that every continuation immediately finishes.

      A continuation can hit another interrupt, so “final answer” and “two run lifecycles” are only guaranteed for a single interrupt/continuation pair. Say “continues the agent” and “at least two runs” instead.

      🤖 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/interrupts/overview.md` around lines 44 - 49, Update the interrupt
      sequence description in the overview diagram and accompanying note to say the
      continuation continues the agent rather than producing a final answer, and
      describe the lifecycle as at least two runs. Preserve the explanation that the
      interrupted run ends and continuation starts a new run, while allowing for
      additional interrupts and runs.
      docs/config.json-392-392 (1)

      392-392: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

      Refresh the media documentation timestamps to July 29, 2026.

      The corresponding documentation files were changed in this PR, but these entries still use 2026-07-28. Update their updatedAt values without changing addedAt.

      As per coding guidelines, substantive documentation changes must refresh updatedAt to today’s date.

      Also applies to: 404-422

      🤖 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/config.json` at line 392, Update the updatedAt values for the affected
      media documentation entries in docs/config.json, including entries 392 and
      404-422, from 2026-07-28 to 2026-07-29. Leave each corresponding addedAt value
      unchanged.

      Source: Coding guidelines

      docs/media/generation-hooks.md-22-25 (1)

      22-25: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

      Qualify the persistence guarantees across the documentation.

      The callouts overpromise what persistence alone provides: client snapshots are lightweight, expired media requires durable server-side artifact/blob storage, and result reconstruction is conditional.

      • docs/media/generation-hooks.md#L22-L25: qualify that restored result depends on the configured persistence mode.
      • docs/media/audio-generation.md#L164-L166: state that retaining audio after provider URL expiry requires durable artifact/blob storage.
      • docs/media/image-generation.md#L511-L512: state that retaining images after provider URL expiry requires durable artifact/blob storage.
      🤖 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/media/generation-hooks.md` around lines 22 - 25, Qualify the persistence
      documentation across all three sites: in docs/media/generation-hooks.md lines
      22-25, state that restored result availability depends on the configured
      persistence mode; in docs/media/audio-generation.md lines 164-166 and
      docs/media/image-generation.md lines 511-512, clarify that retaining media after
      provider URL expiry requires durable server-side artifact/blob storage.
      examples/ts-react-chat/src/routes/generations.image.tsx-21-24 (1)

      21-24: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

      Make reset available after persisted failures.

      Both examples enable persistence that can restore an error or status without a result, while their shared UIs only expose Clear when result exists.

      • examples/ts-react-chat/src/routes/generations.image.tsx#L21-L24: update the streaming hook’s UI path to expose reset for restored error/non-idle states.
      • examples/ts-react-chat/src/routes/generations.image.tsx#L42-L49: apply the same reset condition to the direct image variant.
      • examples/ts-react-chat/src/routes/generations.image.tsx#L66-L73: apply the same reset condition to the server-function image variant.
      • examples/ts-react-chat/src/routes/generations.video.tsx#L17-L20: update the streaming video variant.
      • examples/ts-react-chat/src/routes/generations.video.tsx#L31-L38: update the direct video variant.
      • examples/ts-react-chat/src/routes/generations.video.tsx#L48-L55: update the server-function video variant.
      🤖 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 `@examples/ts-react-chat/src/routes/generations.image.tsx` around lines 21 -
      24, Update the UI reset/Clear visibility condition for the generation hook
      results: examples/ts-react-chat/src/routes/generations.image.tsx lines 21-24,
      42-49, and 66-73, and examples/ts-react-chat/src/routes/generations.video.tsx
      lines 17-20, 31-38, and 48-55. Expose reset when persisted state has an error or
      any non-idle status, even without a result, while preserving the existing
      result-based behavior.
      docs/persistence/build-your-own-adapter.md-938-971 (1)

      938-971: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

      Reject negative page limits.

      With limit: -1, this code executes LIMIT 0, then returns truncated: true without a cursor. Validate that limits are non-negative integers before constructing the query.

      🤖 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/build-your-own-adapter.md` around lines 938 - 971, Validate
      options.limit in list before constructing the SQL query, rejecting values that
      are negative or not integers; allow undefined and non-negative integers,
      including zero. Preserve the existing zero-limit response and pagination
      behavior for valid limits.
      docs/persistence/keep-generated-files.md-94-95 (1)

      94-95: 🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

      Correct the 404/403 explanation.

      Returning the same 404 for missing and unauthorized artifacts avoids confirming whether an ID exists; a 403 would be the distinguishable response. The current prose says the opposite.

      🤖 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 94 - 95, Correct the
      explanation associated with the owned check so it states that returning 404 for
      both missing and unauthorized artifacts prevents confirming whether an ID
      exists, while 403 would distinguish an existing but forbidden artifact. Keep the
      `if (!owned) return new Response('not found', { status: 404 })` behavior
      unchanged.
      🧹 Nitpick comments (15)
      packages/ai/skills/ai-core/media-generation/SKILL.md (1)

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

      Use one verified latest provider model across both examples.

      • packages/ai/skills/ai-core/media-generation/SKILL.md#L593-L593: verify whether gpt-image-1 is current.
      • packages/ai/skills/ai-core/client-persistence/SKILL.md#L199-L199: verify whether gpt-image-2 is current.

      As per coding guidelines, use the latest model from the adapter’s model-meta.ts and keep edited examples consistent.

      🤖 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/media-generation/SKILL.md` at line 593, The OpenAI
      image model examples are inconsistent and may not use the latest verified
      provider model. Check the adapter’s model-meta.ts, update the adapter
      configuration at packages/ai/skills/ai-core/media-generation/SKILL.md:593-593
      and the corresponding example at
      packages/ai/skills/ai-core/client-persistence/SKILL.md:199-199 to the latest
      model, and keep both examples consistent.

      Source: Coding guidelines

      packages/ai-persistence/tests/persistence-validation.test.ts (1)

      76-78: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

      The artifacts/blobs both-or-neither invariant is enforced twice but tested nowhere. validateGenerationPersistenceStores enforces it at runtime and InvalidGenerationPersistence enforces it at the type level; neither branch has a test, so a regression in either would pass CI.

      • packages/ai-persistence/tests/persistence-validation.test.ts#L76-L78: add cases with { generationRuns, artifacts } and { generationRuns, blobs } expecting /requires both stores\.artifacts and stores\.blobs/i.
      • packages/ai-persistence/tests/persistence-types.test-d.ts#L155-L160: add @ts-expect-error calls to withGenerationPersistence for the same two half-configured store sets.
      🤖 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/persistence-validation.test.ts` around lines 76
      - 78, The artifacts/blobs both-or-neither invariant lacks runtime and type-level
      coverage. In packages/ai-persistence/tests/persistence-validation.test.ts:76-78,
      add validation cases for { generationRuns, artifacts } and { generationRuns,
      blobs }, expecting /requires both stores\.artifacts and stores\.blobs/i. In
      packages/ai-persistence/tests/persistence-types.test-d.ts:155-160, add
      `@ts-expect-error` calls to withGenerationPersistence for those same
      half-configured store sets.
      packages/ai-persistence/src/memory.ts (1)

      72-116: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      Consider returning copies of run records. createOrResume/get hand back the live map entry, so a caller mutating the returned object silently edits store state — MemoryArtifactStore.save (Line 229) already copies. A { ...record } on return keeps the reference backend honest as a conformance target for real backends.

      🤖 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/memory.ts` around lines 72 - 116, The
      MemoryGenerationRunStore currently exposes live GenerationRunRecord objects,
      allowing callers to mutate stored state. Update createOrResume, get, and
      findLatestForThread to return shallow copies of records while preserving the
      map’s internal references; align this behavior with MemoryArtifactStore.save and
      keep update’s merge semantics unchanged.
      packages/ai-persistence/tests/reconstruct-generation.test.ts (1)

      119-137: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      Consider covering authorize returning a Response and custom param/runParam. The decision instanceof Response branch and the option-renamed query params are unexercised; both are one-liner tests.

      🤖 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
      119 - 137, Add focused tests alongside the existing authorization test for
      reconstructGeneration: verify an authorize callback returning a Response is
      returned unchanged, and verify custom param/runParam option names are used to
      locate the generation run. Keep each case minimal and assert the expected
      response behavior.
      packages/ai-persistence/src/reconstruct-generation.ts (1)

      42-51: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

      authorize cannot tell a runId from a threadId. The callback gets a bare id, so an ownership check has to guess which lookup to run (or check both, widening what it accepts). Consider passing the kind alongside the id, e.g. authorize({ runId, threadId }, request) or a second kind: 'run' | 'thread' argument, so tenancy checks stay precise.

      Authorization ordering itself is correct — it runs before any store read.

      Also applies to: 157-171

      🤖 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/reconstruct-generation.ts` around lines 42 - 51,
      The authorize callback currently receives only a bare id, preventing precise
      distinction between run and thread authorization. Update the authorize contract
      and its invocation in the reconstruction flow to pass the identifier kind
      alongside the id, such as an explicit runId/threadId object or run/thread kind
      argument, while preserving authorization before store reads and existing
      boolean/Response handling.

      Source: Learnings

      packages/ai-persistence/tests/error-abort.test.ts (1)

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

      Test titles still say "job" after the jobs → runs rename. Store, records, and ids are all run-flavoured now; renaming these titles to "run" keeps failure output consistent with the API.

      Also applies to: 289-289, 313-313, 338-338

      🤖 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/error-abort.test.ts` at line 265, Rename the
      test titles at the cases around lines 265, 289, 313, and 338 from “job”
      terminology to “run” terminology, preserving each test’s existing behavior and
      wording aside from the renamed entity.
      packages/ai-persistence/src/middleware.ts (1)

      1404-1408: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      Docblock contradicts the artifact fallback.

      persistGenerationArtifacts (Line 872) does set threadId = ctx.threadId ?? ctx.requestId on every ArtifactRecord/PersistedArtifactRef (required field), so "never faked from the request id" only holds for the run record. Worth wording it as "the run record never fakes a threadId; artifact records fall back to the request id".

      🤖 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 1404 - 1408, The
      docblock above persistGenerationArtifacts incorrectly claims threadId is never
      faked from the request id. Clarify that only the generation run record preserves
      an optional caller-supplied threadId without fallback, while artifact records
      use ctx.threadId ?? ctx.requestId as their required threadId.
      packages/ai-persistence/tests/generation-artifacts.test.ts (1)

      28-30: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      These void (undefined as unknown as T) lines look like leftover scaffolding.

      The three types are only imported to be discarded here; either drop them (and the imports) or add real assertions, e.g. a satisfies GenerationArtifactDescriptor on the literal passed to extractArtifacts at Line 388.

      🤖 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/generation-artifacts.test.ts` around lines 28 -
      30, Remove the unused GenerationArtifactDescriptor,
      GenerationArtifactExtractionInput, and GenerationArtifactNameInput imports and
      their corresponding void-cast scaffolding in generation-artifacts.test.ts. If
      type coverage is needed, replace the scaffolding with a real satisfies assertion
      on the extractArtifacts input literal, but do not retain discarded type
      references.
      packages/ai-client/src/generation-reconstruct.ts (1)

      23-35: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      Optional: drop the as string cast with flatMap.

      -  return restored.artifacts
      -    .filter(
      -      (a) =>
      -        a.role === 'output' &&
      -        a.source.mediaType === mediaType &&
      -        a.url != null,
      -    )
      -    .map((a) => a.url as string)
      +  return restored.artifacts.flatMap((a) =>
      +    a.role === 'output' && a.source.mediaType === mediaType && a.url != null
      +      ? [a.url]
      +      : [],
      +  )
      🤖 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-reconstruct.ts` around lines 23 - 35,
      Update mediaUrls to use flatMap so it returns each matching artifact URL only
      when present, allowing TypeScript to infer string values and removing the `as
      string` cast while preserving the existing output-role and media-type filters.
      packages/ai-angular/tests/inject-generation.test.ts (1)

      50-80: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      Optional: collapse the three near-identical render helpers.

      renderInjectGenerateVideo / renderInjectGenerateImage differ from renderInjectGeneration only in which injectable is called; a small factory taking the injectable would remove two copies.

      ♻️ Sketch
      function renderWith<T>(inject: (options: any) => T) {
        return (options: any) => {
          `@Component`({ standalone: true, template: '' })
          class Host {
            gen = inject(options)
          }
          const fixture = TestBed.createComponent(Host)
          fixture.detectChanges()
          return {
            get result() {
              return fixture.componentInstance.gen
            },
            flush: () => fixture.detectChanges(),
            destroy: () => fixture.destroy(),
          }
        }
      }
      🤖 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 50 - 80,
      Optionally replace the duplicated renderInjectGenerateVideo and
      renderInjectGenerateImage helpers, along with renderInjectGeneration, with a
      shared renderWith factory that accepts the injectable function and returns the
      options-based renderer. Preserve the existing Host component setup, fixture
      lifecycle methods, and result access behavior for each injectable.
      packages/ai-client/src/video-generation-client.ts (1)

      529-554: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      Consider a single clone helper instead of hand-rolled field spreads.

      This copies each nested field explicitly, so any new field added to GenerationResumeSnapshot silently starts leaking an internal reference. structuredClone(this.resumeSnapshot) (or a shared cloneResumeSnapshot helper in generation-types.ts, reusable by the other generation clients) keeps this correct as the shape grows. Note the current copy is also shallow at the element level — artifacts/pendingArtifacts entries are still shared references.

      🤖 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 529 - 554,
      Replace the hand-rolled cloning in getResumeSnapshot with structuredClone or a
      shared cloneResumeSnapshot helper, ensuring the entire
      GenerationResumeSnapshot—including nested objects and pendingArtifacts/artifacts
      entries—is deeply copied. If introducing the helper, place it with the
      generation types and reuse the established helper across generation clients.
      packages/ai-angular/src/inject-generate-video.ts (1)

      38-52: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      Inconsistent with the sibling injectables: consider Pick<InjectGenerationOptions, …>.

      InjectGenerateAudioOptions (and the image/speech variants) inherit these three fields via extends Pick<InjectGenerationOptions<…>, 'persistence' | 'threadId' | 'initialResumeSnapshot'>, while this file re-declares them plus the doc comment inline. Same for the Svelte/React/Vue video hooks. Inheriting keeps the docs and types in one place as the persistence surface evolves.

      Video's client is a separate class (VideoGenerationClient, not GenerationClient), so this may be deliberate — if so, no change needed.

      🤖 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 38 - 52, Align
      the video injectable options with the sibling audio, image, and speech variants
      by inheriting persistence, threadId, and initialResumeSnapshot through
      Pick<InjectGenerationOptions<…>, 'persistence' | 'threadId' |
      'initialResumeSnapshot'> instead of redeclaring them inline. Verify
      VideoGenerationClient supports the same option types; if it does not, preserve
      the current declarations and make no change.
      packages/ai-react/tests/use-generation.test.ts (1)

      143-160: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      Nit: the spy and the generator share the name connect, and runContexts is unused in the added tests.

      The inner async *connect and the outer const connect = vi.fn() reading the same identifier makes the helper harder to follow; consider connectSpy. Also drop runContexts unless a test asserts on it.

      🤖 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/tests/use-generation.test.ts` around lines 143 - 160, In
      createRunContextCaptureAdapter, rename the outer vi.fn() variable from connect
      to connectSpy and update the returned property and all references accordingly,
      while retaining the adapter’s connect method. Remove the unused runContexts
      array, its push call, and its return property unless the added tests assert on
      it.
      packages/ai-vue/src/use-generation.ts (1)

      165-170: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      Comment contradicts the code.

      The comment says the body key must be omitted when absent under EOPT, but Line 170 assigns body: options.body unconditionally (possibly undefined). Either drop/reword the comment or apply the conditional spread used for the neighbouring options.

      ♻️ Suggested change
      -  // Conditional spread on `body`: `GenerationClientOptions.body` is a strict
      -  // optional (`body?: Record<string, any>`), and under EOPT we must omit the
      -  // key when absent rather than assign `undefined`.
         const clientOptions: GenerationClientOptions<TInput, TResult, TOutput> = {
           id: clientId,
      -    body: options.body,
      +    ...(options.body !== undefined && { body: options.body }),
      🤖 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-vue/src/use-generation.ts` around lines 165 - 170, Update the
      clientOptions construction near GenerationClientOptions so body is conditionally
      spread only when options.body is present, matching the comment and strict
      optional-property requirements; preserve the existing id and other option
      handling.
      packages/ai-vue/src/use-generate-speech.ts (1)

      114-123: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      Speech has no reconstructResult, so result never repaints on restore — document it.

      Every other Vue generation composable injects a reconstructor (reconstructImageResult, reconstructTranscriptionResult, reconstructSummarizeResult). Speech can't rebuild a TTSResult from a durable URL because audio is base64 plus a required format, so omitting it looks deliberate — but the inherited persistence option at Lines 22-25 now implies restore support. Add a short note on the option docs (or the hook JSDoc) that a restored speech snapshot repaints status / error only.

      🤖 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-vue/src/use-generate-speech.ts` around lines 114 - 123, Add a
      concise documentation note near the inherited persistence option or the
      use-generate-speech hook JSDoc explaining that restored speech snapshots repaint
      only status and error; result is not reconstructed because TTS audio requires
      base64 data and its format. Keep the existing useGeneration configuration
      unchanged.
      🤖 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/build-your-own-adapter.md`:
      - Around line 893-923: The put method’s selectCreated-before-upsert flow is
      race-prone and can return values that differ from the stored row. Update put to
      atomically upsert the record and then re-read the persisted row, or use an
      atomic RETURNING-supported upsert, deriving createdAt and returned metadata from
      the record actually stored.
      - Around line 617-640: Validate and narrow persisted database values before
      hydrating records in mapGenerationRun, mapArtifact, and mapBlobRecord. Replace
      direct coercions and unguarded JSON.parse calls with schema validation or type
      guards, rejecting or safely handling malformed and partially migrated rows
      before constructing domain objects. Preserve valid-row hydration while
      preventing invalid state from reaching get and findLatestForThread.
      - Around line 655-676: Update createOrResume so it returns the persisted record
      after insert rather than reconstructing and returning the attempted input.
      Re-read the run using select.get(input.runId) after insert, including when ON
      CONFLICT DO NOTHING means another caller created it first, and map that stored
      record with mapGenerationRun.
      
      In `@docs/persistence/generation-persistence.md`:
      - Around line 29-35: Update the generation persistence documentation around
      withGenerationPersistence and generationRuns to distinguish client-side adapters
      from server persistence. State that a server run record is created only when the
      server route opts into withGenerationPersistence, and that server persistence is
      required for server-driven hydration and/or durable artifacts rather than for
      every persistence mode.
      - Around line 37-39: The persistence documentation should distinguish result
      metadata from durable media bytes. In docs/persistence/generation-persistence.md
      lines 37-39, remove the claim that result always remains null without byte
      storage; in lines 224-228, state that artifacts/blobs are required to restore
      durable media, while metadata and non-binary results can still be restored.
      - Around line 113-116: Make both persistence examples fail closed: in
      docs/persistence/generation-persistence.md lines 113-116, update the
      reconstructGeneration call to provide a real server-side authorize callback that
      validates the authenticated user’s ownership before using the client-supplied
      threadId; in docs/persistence/keep-generated-files.md lines 77-95, replace the
      const owned = true placeholder with session-derived artifact ownership
      validation. Ensure neither example permits client-provided identifiers alone to
      read another user’s generation.
      
      In `@docs/persistence/keep-generated-files.md`:
      - Around line 151-167: Add a concise client-side hook or component example to
      the “Wire the durable URL through to the client” section, showing consumption of
      durable media URLs from the result fields (such as result.images, result.url, or
      result.audio.url). Keep the snippet focused on rendering the persisted URL and
      complement the existing server-side explanation without changing the documented
      artifact flow.
      
      In `@examples/ts-react-chat/src/routes/generations.audio.tsx`:
      - Around line 81-94: Update the audio persistence configuration in
      examples/ts-react-chat/src/routes/generations.audio.tsx:81-94 and the speech
      persistence configuration in
      examples/ts-react-chat/src/routes/generations.speech.tsx:55-79 so persisted
      AudioOutput.url and SpeechOutput.audioUrl values are not stored as
      document-scoped object URLs; omit those fields or reconstruct them during
      hydration from a durable source while preserving the existing generation and
      playback behavior.
      - Around line 81-94: Update the audio generation persistence ids in
      examples/ts-react-chat/src/routes/generations.audio.tsx (lines 81-94) to include
      selectedModel. Update the speech generation persistence id and its useMemo
      dependencies in examples/ts-react-chat/src/routes/generations.speech.tsx (lines
      55-79) to include voice, ensuring distinct models or voices cannot hydrate stale
      persisted output.
      
      In `@packages/ai-client/src/video-generation-client.ts`:
      - Around line 850-860: Update maybeHydrateResumeSnapshot and hydrateFromServer
      to check this.disposed immediately after their awaited storage/server hydration
      calls and return before applying state or rejoining work. Ensure disposed
      clients cannot call repaintFromSnapshot or start rejoinInFlight/joinRun, while
      preserving the existing live-state guards for active clients.
      
      In `@packages/ai/skills/ai-core/client-persistence/SKILL.md`:
      - Around line 209-219: Authorize all caller-supplied persistence identifiers
      using server-side session ownership checks. In
      packages/ai/skills/ai-core/client-persistence/SKILL.md lines 209-219, replace
      the unconditional authorization in GET with a real ownership check or
      fail-closed behavior; in packages/ai/skills/ai-core/media-generation/SKILL.md
      lines 590-595, authorize the submitted thread before persisting the run; and in
      lines 609-618, authorize record.threadId before retrieving or returning blob
      bytes.
      - Around line 191-203: Update the POST handler’s generation flow around
      generationParamsFromRequest and generateImage to ensure every request carries a
      stable threadId into withGenerationPersistence, including bare prompt requests.
      Use the request envelope or an equivalent propagated identifier so the persisted
      run identity matches the threadId used by hydration, and cover the
      POST-to-hydration path.
      
      In `@packages/ai/src/activities/generateAudio/index.ts`:
      - Around line 163-164: Propagate threadId and runId from the activity context
      into every aiEventClient.emit lifecycle payload. Update started, completed,
      error, and usage events in packages/ai/src/activities/generateAudio/index.ts
      (163-164), packages/ai/src/activities/generateImage/index.ts (256-257),
      packages/ai/src/activities/generateSpeech/index.ts (171-172), and
      packages/ai/src/activities/generateTranscription/index.ts (206-207); ensure all
      emitted payloads include both IDs.
      
      In `@testing/e2e/src/routes/api.generation-persistence-server.ts`:
      - Around line 36-39: Add a test-only reset path for the completedByThread record
      keyed by generation-server-thread, either through a DELETE handler or by
      clearing it in the persistence spec before the first page.goto. Ensure retries
      start with no prior completed generation while preserving the existing
      server-authoritative record behavior.
      
      ---
      
      Outside diff comments:
      In `@packages/ai-svelte/src/create-generate-speech.svelte.ts`:
      - Around line 111-114: Document in CreateGenerateSpeechOptions that persistence,
      threadId, and initialResumeSnapshot restore speech state but do not reconstruct
      TTSResult.audio; persisted runs may therefore return result === null and cannot
      play audio after reload. Keep the existing createGeneration call unchanged
      unless needed to align the option documentation.
      
      ---
      
      Minor comments:
      In @.changeset/generation-persistence.md:
      - Line 22: Update the generation persistence documentation sentence describing
      restored media references, replacing “refs on result.artifacts” with “refs in
      result.artifacts” while preserving the surrounding behavior and wording.
      
      In `@docs/config.json`:
      - Line 392: Update the updatedAt values for the affected media documentation
      entries in docs/config.json, including entries 392 and 404-422, from 2026-07-28
      to 2026-07-29. Leave each corresponding addedAt value unchanged.
      
      In `@docs/interrupts/overview.md`:
      - Around line 44-49: Update the interrupt sequence description in the overview
      diagram and accompanying note to say the continuation continues the agent rather
      than producing a final answer, and describe the lifecycle as at least two runs.
      Preserve the explanation that the interrupted run ends and continuation starts a
      new run, while allowing for additional interrupts and runs.
      
      In `@docs/media/generation-hooks.md`:
      - Around line 22-25: Qualify the persistence documentation across all three
      sites: in docs/media/generation-hooks.md lines 22-25, state that restored result
      availability depends on the configured persistence mode; in
      docs/media/audio-generation.md lines 164-166 and docs/media/image-generation.md
      lines 511-512, clarify that retaining media after provider URL expiry requires
      durable server-side artifact/blob storage.
      
      In `@docs/persistence/build-your-own-adapter.md`:
      - Around line 938-971: Validate options.limit in list before constructing the
      SQL query, rejecting values that are negative or not integers; allow undefined
      and non-negative integers, including zero. Preserve the existing zero-limit
      response and pagination behavior for valid limits.
      
      In `@docs/persistence/keep-generated-files.md`:
      - Around line 94-95: Correct the explanation associated with the owned check so
      it states that returning 404 for both missing and unauthorized artifacts
      prevents confirming whether an ID exists, while 403 would distinguish an
      existing but forbidden artifact. Keep the `if (!owned) return new Response('not
      found', { status: 404 })` behavior unchanged.
      
      In `@examples/ts-react-chat/src/routes/generations.image.tsx`:
      - Around line 21-24: Update the UI reset/Clear visibility condition for the
      generation hook results: examples/ts-react-chat/src/routes/generations.image.tsx
      lines 21-24, 42-49, and 66-73, and
      examples/ts-react-chat/src/routes/generations.video.tsx lines 17-20, 31-38, and
      48-55. Expose reset when persisted state has an error or any non-idle status,
      even without a result, while preserving the existing result-based behavior.
      
      In `@packages/ai-client/src/connection-adapters.ts`:
      - Around line 781-791: Make resumeState.threadId required in the
      GenerationHydrationResult interface, matching the validation behavior of
      parseGenerationResumeSnapshot. Update the nested resumeState type while
      preserving its nullable state and existing runId requirement.
      
      In `@packages/ai-client/src/generation-client.ts`:
      - Around line 851-885: Update the catch block in rejoinInFlight to surface
      failed rejoin errors through the same status and error state updates used by
      generate(), while preserving the existing abort check and snapshot error
      recording. Ensure a non-aborted joinRun/processStream failure repaints the
      visible error state instead of leaving status as generating.
      
      In
      `@packages/ai-persistence/skills/ai-persistence/build-cloudflare-artifact-store/SKILL.md`:
      - Around line 345-355: Update the GET handler sample to derive the authenticated
      owner from the session and validate it against the retrieved record’s
      record.threadId before calling retrieveBlob. Return a 404 response when
      authorization fails, ensuring artifact bytes are never served for an
      unauthorized artifactId.
      
      In `@packages/ai-persistence/skills/ai-persistence/SKILL.md`:
      - Around line 45-63: The “Critical rule 5” store-key list must include the
      generation persistence stores documented in the table. Update the rule’s
      `stores` description to accept `generationRuns`, `artifacts`, and `blobs` in
      addition to the existing chat stores, preserving the requirement that
      `artifacts` and `blobs` are provided together.
      
      In `@packages/ai-persistence/src/middleware.ts`:
      - Around line 454-455: Update the mimeType fallback in the source-processing
      logic near sourceType to use a valid per-type default instead of always
      constructing `${type}/mpeg`; preserve an explicitly provided source.mimeType and
      ensure image and video prompt media receive appropriate media types.
      - Around line 383-405: Update parseDataUrl’s data-URL regex to accept arbitrary
      media-type parameter segments before the optional ;base64 marker, while
      preserving the existing MIME type and payload captures. Adjust the base64
      detection to use the new capture index (match[3]) so parameterized URLs such as
      data:image/png;charset=utf-8;base64,... are decoded as inline bytes.
      
      In `@packages/ai-react/src/use-generate-speech.ts`:
      - Around line 125-134: Update the options documentation for useGenerateSpeech
      and its useGeneration configuration to document that completed speech results
      cannot be reconstructed from restored snapshots because audio bytes are not
      persisted; restored runs may have status/resumeState without result data unless
      an onResult transform supplies durable restore data.
      
      In `@packages/ai/skills/ai-core/client-persistence/SKILL.md`:
      - Around line 156-158: The client snapshot preserves text outputs such as
      transcription.text and summary, so revise the result persistence guidance to
      distinguish them from media-bearing results. State that only media-bearing
      results require server byte storage or artifactUrl for reload, while text-output
      results restore without it, and update the surrounding examples accordingly.
      
      In `@packages/ai/skills/ai-core/media-generation/SKILL.md`:
      - Around line 628-632: Revise the no-byte-storage paragraph to scope the
      limitation specifically to image, audio, and video media refs/results that
      depend on durable artifact storage. Preserve that transcription and summarize
      restore their results from persisted text/metadata via
      reconstructTranscriptionResult and reconstructSummarizeResult, and remove the
      blanket claim that a reload leaves result null.
      
      ---
      
      Nitpick comments:
      In `@packages/ai-angular/src/inject-generate-video.ts`:
      - Around line 38-52: Align the video injectable options with the sibling audio,
      image, and speech variants by inheriting persistence, threadId, and
      initialResumeSnapshot through Pick<InjectGenerationOptions<…>, 'persistence' |
      'threadId' | 'initialResumeSnapshot'> instead of redeclaring them inline. Verify
      VideoGenerationClient supports the same option types; if it does not, preserve
      the current declarations and make no change.
      
      In `@packages/ai-angular/tests/inject-generation.test.ts`:
      - Around line 50-80: Optionally replace the duplicated renderInjectGenerateVideo
      and renderInjectGenerateImage helpers, along with renderInjectGeneration, with a
      shared renderWith factory that accepts the injectable function and returns the
      options-based renderer. Preserve the existing Host component setup, fixture
      lifecycle methods, and result access behavior for each injectable.
      
      In `@packages/ai-client/src/generation-reconstruct.ts`:
      - Around line 23-35: Update mediaUrls to use flatMap so it returns each matching
      artifact URL only when present, allowing TypeScript to infer string values and
      removing the `as string` cast while preserving the existing output-role and
      media-type filters.
      
      In `@packages/ai-client/src/video-generation-client.ts`:
      - Around line 529-554: Replace the hand-rolled cloning in getResumeSnapshot with
      structuredClone or a shared cloneResumeSnapshot helper, ensuring the entire
      GenerationResumeSnapshot—including nested objects and pendingArtifacts/artifacts
      entries—is deeply copied. If introducing the helper, place it with the
      generation types and reuse the established helper across generation clients.
      
      In `@packages/ai-persistence/src/memory.ts`:
      - Around line 72-116: The MemoryGenerationRunStore currently exposes live
      GenerationRunRecord objects, allowing callers to mutate stored state. Update
      createOrResume, get, and findLatestForThread to return shallow copies of records
      while preserving the map’s internal references; align this behavior with
      MemoryArtifactStore.save and keep update’s merge semantics unchanged.
      
      In `@packages/ai-persistence/src/middleware.ts`:
      - Around line 1404-1408: The docblock above persistGenerationArtifacts
      incorrectly claims threadId is never faked from the request id. Clarify that
      only the generation run record preserves an optional caller-supplied threadId
      without fallback, while artifact records use ctx.threadId ?? ctx.requestId as
      their required threadId.
      
      In `@packages/ai-persistence/src/reconstruct-generation.ts`:
      - Around line 42-51: The authorize callback currently receives only a bare id,
      preventing precise distinction between run and thread authorization. Update the
      authorize contract and its invocation in the reconstruction flow to pass the
      identifier kind alongside the id, such as an explicit runId/threadId object or
      run/thread kind argument, while preserving authorization before store reads and
      existing boolean/Response handling.
      
      In `@packages/ai-persistence/tests/error-abort.test.ts`:
      - Line 265: Rename the test titles at the cases around lines 265, 289, 313, and
      338 from “job” terminology to “run” terminology, preserving each test’s existing
      behavior and wording aside from the renamed entity.
      
      In `@packages/ai-persistence/tests/generation-artifacts.test.ts`:
      - Around line 28-30: Remove the unused GenerationArtifactDescriptor,
      GenerationArtifactExtractionInput, and GenerationArtifactNameInput imports and
      their corresponding void-cast scaffolding in generation-artifacts.test.ts. If
      type coverage is needed, replace the scaffolding with a real satisfies assertion
      on the extractArtifacts input literal, but do not retain discarded type
      references.
      
      In `@packages/ai-persistence/tests/persistence-validation.test.ts`:
      - Around line 76-78: The artifacts/blobs both-or-neither invariant lacks runtime
      and type-level coverage. In
      packages/ai-persistence/tests/persistence-validation.test.ts:76-78, add
      validation cases for { generationRuns, artifacts } and { generationRuns, blobs
      }, expecting /requires both stores\.artifacts and stores\.blobs/i. In
      packages/ai-persistence/tests/persistence-types.test-d.ts:155-160, add
      `@ts-expect-error` calls to withGenerationPersistence for those same
      half-configured store sets.
      
      In `@packages/ai-persistence/tests/reconstruct-generation.test.ts`:
      - Around line 119-137: Add focused tests alongside the existing authorization
      test for reconstructGeneration: verify an authorize callback returning a
      Response is returned unchanged, and verify custom param/runParam option names
      are used to locate the generation run. Keep each case minimal and assert the
      expected response behavior.
      
      In `@packages/ai-react/tests/use-generation.test.ts`:
      - Around line 143-160: In createRunContextCaptureAdapter, rename the outer
      vi.fn() variable from connect to connectSpy and update the returned property and
      all references accordingly, while retaining the adapter’s connect method. Remove
      the unused runContexts array, its push call, and its return property unless the
      added tests assert on it.
      
      In `@packages/ai-vue/src/use-generate-speech.ts`:
      - Around line 114-123: Add a concise documentation note near the inherited
      persistence option or the use-generate-speech hook JSDoc explaining that
      restored speech snapshots repaint only status and error; result is not
      reconstructed because TTS audio requires base64 data and its format. Keep the
      existing useGeneration configuration unchanged.
      
      In `@packages/ai-vue/src/use-generation.ts`:
      - Around line 165-170: Update the clientOptions construction near
      GenerationClientOptions so body is conditionally spread only when options.body
      is present, matching the comment and strict optional-property requirements;
      preserve the existing id and other option handling.
      
      In `@packages/ai/skills/ai-core/media-generation/SKILL.md`:
      - Line 593: The OpenAI image model examples are inconsistent and may not use the
      latest verified provider model. Check the adapter’s model-meta.ts, update the
      adapter configuration at
      packages/ai/skills/ai-core/media-generation/SKILL.md:593-593 and the
      corresponding example at
      packages/ai/skills/ai-core/client-persistence/SKILL.md:199-199 to the latest
      model, and keep both examples consistent.
      🪄 Autofix (Beta)

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes
      Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)
      docs/persistence/build-your-own-adapter.md lines 726 to 747
      @@ -477,0 +656,21 @@
      656+ const existing = select.get(input.runId)
      657+ if (existing) return mapGenerationRun(existing)
      658+ const status: GenerationRunStatus = input.status ?? 'running'
      659+ insert.run(
      660+ input.runId,
      661+ input.threadId ?? null,
      662+ input.activity,
      663+ input.provider,
      664+ input.model,
      665+ status,
      666+ input.startedAt,
      667+ )
      668+ return {
      669+ runId: input.runId,
      670+ activity: input.activity,
      671+ provider: input.provider,
      672+ model: input.model,
      673+ status,
      674+ startedAt: input.startedAt,
      675+ ...(input.threadId !== undefined ? { threadId: input.threadId } : {}),
      676+ }

      🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

      Return the record after the insert.

      Two concurrent callers can both miss select.get; the loser’s ON CONFLICT DO NOTHING is ignored, and it returns its attempted input instead of the stored winner. That violates the documented idempotency contract and can report incorrect run metadata.

      Proposed fix
             insert.run(
               input.runId,
               input.threadId ?? null,
               input.activity,
               input.provider,
               input.model,
               status,
               input.startedAt,
             )
      -      return {
      -        runId: input.runId,
      -        activity: input.activity,
      -        provider: input.provider,
      -        model: input.model,
      -        status,
      -        startedAt: input.startedAt,
      -        ...(input.threadId !== undefined ? { threadId: input.threadId } : {}),
      -      }
      +      const created = select.get(input.runId)
      +      if (!created) throw new Error('Generation run was not created')
      +      return mapGenerationRun(created)
      📝 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.

          async createOrResume(input) {
            const existing = select.get(input.runId)
            if (existing) return mapGenerationRun(existing)
            const status: GenerationRunStatus = input.status ?? 'running'
            insert.run(
              input.runId,
              input.threadId ?? null,
              input.activity,
              input.provider,
              input.model,
              status,
              input.startedAt,
            )
            const created = select.get(input.runId)
            if (!created) throw new Error('Generation run was not created')
            return mapGenerationRun(created)
      🤖 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/build-your-own-adapter.md` around lines 655 - 676, Update
      createOrResume so it returns the persisted record after insert rather than
      reconstructing and returning the attempted input. Re-read the run using
      select.get(input.runId) after insert, including when ON CONFLICT DO NOTHING
      means another caller created it first, and map that stored record with
      mapGenerationRun.
      Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)
      OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)
      Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)
      Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)
      docs/persistence/keep-generated-files.md lines 151 to 167Outdated
      @@ -0,0 +147,21 @@
      147+private address still passes a literal-IP check. Keep `allowInputUrl` narrow,
      148+and for stronger isolation inject `artifactFetch` to route downloads through an
      149+egress-restricted proxy that can check the address actually connected to.
      150+
      151+## Wire the durable URL through to the client
      152+
      153+`artifactUrl` is what makes the stored bytes reachable from the client without
      154+any extra plumbing. For each persisted ref it returns the app-origin URL that
      155+serves those bytes (the `GET` route above), and `withGenerationPersistence`
      156+does two things with it: it stamps the URL onto the ref (`ref.url`) and it
      157+rewrites the live result's media field to the same URL — `result.images[i].url`
      158+for images, `result.url` for a video, `result.audio.url` for audio. So the live
      159+result already points at your origin, not the provider's expiring link.
      160+
      161+Those durable refs ride along on `result.artifacts`, and they are what a reload
      162+restores from. In [Generation persistence](./generation-persistence), the
      163+generation hook rebuilds `result` from the persisted refs on mount, resolving
      164+each media field to its durable `ref.url` — so the restored result renders the
      165+same media the live run showed. The refs are the only artifact surface: there
      166+are no separate top-level artifact fields on the hook, final refs live on
      167+`result.artifacts` and in-flight ones on `resumeState.pendingArtifacts`.

      📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

      Add a client-side consumption snippet.

      This page explains how artifactUrl rewrites the result and how the client renders it, but only shows server code. As per coding guidelines, include a small client hook/component snippet that consumes the durable URL.

      🤖 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 151 - 167, Add a
      concise client-side hook or component example to the “Wire the durable URL
      through to the client” section, showing consumption of durable media URLs from
      the result fields (such as result.images, result.url, or result.audio.url). Keep
      the snippet focused on rendering the persisted URL and complement the existing
      server-side explanation without changing the documented artifact flow.

      Source: Coding guidelines

      examples/ts-react-chat/src/routes/generations.audio.tsx lines 81 to 94Outdated
      @@ -74,13 +78,17 @@
      7478 const hookOptions = useMemo(() => {
      7579 if (mode === 'hooks') {
      7680 return {
      81+ id: `audio:${mode}:${config.id}`,
      7782 connection: fetchServerSentEvents('/api/generate/audio'),
      7883 body: { provider: config.id, model: selectedModel },
      84+ persistence: audioPersistence,
      7985 onResult: toAudioOutput,
      8086 }
      8187 }
      8288 return {
      89+ id: `audio:${mode}:${config.id}`,
      8390 fetcher: (input: { prompt: string; duration?: number }) =>
      8491 generateAudioFn({
      8592 data: { ...input, provider: config.id, model: selectedModel },
      8693 }),
      94+ persistence: audioPersistence,

      🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

      Client persistence can restore dead object URLs. Both routes persist UI results whose media URLs are scoped to the current browser document, so a full reload cannot play the restored result without reconstructing the media.

      • examples/ts-react-chat/src/routes/generations.audio.tsx#L81-L94: avoid persisting the AudioOutput.url object URL, or rebuild it from a durable/reconstructable source during hydration.
      • examples/ts-react-chat/src/routes/generations.speech.tsx#L55-L79: avoid persisting the SpeechOutput.audioUrl object URL, or rebuild it from a durable/reconstructable source during hydration.
      📍 Affects 2 files
      • examples/ts-react-chat/src/routes/generations.audio.tsx#L81-L94 (this comment)
      • examples/ts-react-chat/src/routes/generations.speech.tsx#L55-L79
      🤖 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 `@examples/ts-react-chat/src/routes/generations.audio.tsx` around lines 81 -
      94, Update the audio persistence configuration in
      examples/ts-react-chat/src/routes/generations.audio.tsx:81-94 and the speech
      persistence configuration in
      examples/ts-react-chat/src/routes/generations.speech.tsx:55-79 so persisted
      AudioOutput.url and SpeechOutput.audioUrl values are not stored as
      document-scoped object URLs; omit those fields or reconstruct them during
      hydration from a durable source while preserving the existing generation and
      playback behavior.

      🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

      Generation persistence keys omit user-selected inputs. A persistence id must distinguish configurations whose generated results differ; otherwise reloads can hydrate stale output from another model or voice.

      • examples/ts-react-chat/src/routes/generations.audio.tsx#L81-L94: include selectedModel in the id.
      • examples/ts-react-chat/src/routes/generations.speech.tsx#L55-L79: include voice in the id and its useMemo dependencies.
      📍 Affects 2 files
      • examples/ts-react-chat/src/routes/generations.audio.tsx#L81-L94 (this comment)
      • examples/ts-react-chat/src/routes/generations.speech.tsx#L55-L79
      🤖 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 `@examples/ts-react-chat/src/routes/generations.audio.tsx` around lines 81 -
      94, Update the audio generation persistence ids in
      examples/ts-react-chat/src/routes/generations.audio.tsx (lines 81-94) to include
      selectedModel. Update the speech generation persistence id and its useMemo
      dependencies in examples/ts-react-chat/src/routes/generations.speech.tsx (lines
      55-79) to include voice, ensuring distinct models or voices cannot hydrate stale
      persisted output.
      OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)
      Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)
      Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)
      packages/ai/src/activities/generateAudio/index.ts lines 168 to 169
      @@ -154,3 +160,5 @@
      154160 stream: _stream,
      155161 debug: _debug,
      156162 middleware,
      163+ threadId,
      164+ runId,

      🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

      Propagate correlation IDs into lifecycle events.

      The IDs are only placed in middleware context; every aiEventClient.emit payload still omits them. Event subscribers therefore receive no threadId/runId, despite the newly expanded event contracts.

      • packages/ai/src/activities/generateAudio/index.ts#L163-L164: add both IDs to each started, completed, error, and usage payload.
      • packages/ai/src/activities/generateImage/index.ts#L256-L257: add both IDs to each emitted lifecycle payload.
      • packages/ai/src/activities/generateSpeech/index.ts#L171-L172: add both IDs to each started, completed, error, and usage payload.
      • packages/ai/src/activities/generateTranscription/index.ts#L206-L207: add both IDs to each started, completed, error, and usage payload.
      📍 Affects 4 files
      • packages/ai/src/activities/generateAudio/index.ts#L163-L164 (this comment)
      • packages/ai/src/activities/generateImage/index.ts#L256-L257
      • packages/ai/src/activities/generateSpeech/index.ts#L171-L172
      • packages/ai/src/activities/generateTranscription/index.ts#L206-L207
      🤖 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 - 164,
      Propagate threadId and runId from the activity context into every
      aiEventClient.emit lifecycle payload. Update started, completed, error, and
      usage events in packages/ai/src/activities/generateAudio/index.ts (163-164),
      packages/ai/src/activities/generateImage/index.ts (256-257),
      packages/ai/src/activities/generateSpeech/index.ts (171-172), and
      packages/ai/src/activities/generateTranscription/index.ts (206-207); ensure all
      emitted payloads include both IDs.
      testing/e2e/src/routes/api.generation-persistence-server.ts lines 36 to 39
      @@ -0,0 +19,21 @@
      19+ * We hand-build the JSON here rather than pull `@tanstack/ai-persistence` into
      20+ * the e2e app (it is not a dependency), mirroring the `server-interrupt`
      21+ * scenario in `api.persistence-durability.ts`. `reconstructGeneration` itself is
      22+ * unit-tested in `@tanstack/ai-persistence`; this proves the CLIENT restore.
      23+ *
      24+ * Exempt from the aimock policy: this route streams a fixed AG-UI sequence and
      25+ * never reaches an LLM provider's HTTP layer, so there is nothing to mock.
      26+ */
      27+
      28+// 1x1 transparent PNG — the live result's inline bytes, never persisted.
      29+const TINY_PNG_B64 =
      30+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=='
      31+
      32+// Durable app-origin serve URL for the generated image (as
      33+// `withGenerationPersistence`'s `artifactUrl` would stamp it).
      34+const DURABLE_IMAGE_URL = '/durable/generation-server/image-1.png'
      35+
      36+// Server-authoritative record of the last completed generation per thread. In
      37+// production this is a `GenerationRunStore` row; here a process-lifetime map is
      38+// enough for the reload round-trip (the e2e server stays up across reloads).
      39+const completedByThread = new Map<string, Record<string, unknown>>()

      🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

      🧩 Analysis chain

      🏁 Script executed:

      #!/bin/bash
      set -euo pipefail
      
      echo "== locate files =="
      git ls-files | rg 'generation-persistence-server|playwright.config|package.json' | sed -n '1,120p'
      
      echo
      echo "== target route outline =="
      ast-grep outline testing/e2e/src/routes/api.generation-persistence-server.ts --view expanded || true
      
      echo
      echo "== target route relevant lines =="
      cat -n testing/e2e/src/routes/api.generation-persistence-server.ts | sed -n '1,220p'
      
      echo
      echo "== companion files relevant lines =="
      fd 'generation-persistence-server' testing/e2e -t f -x sh -c 'echo "--- $1"; wc -l "$1"; cat -n "$1" | sed -n "1,220p"' sh {}
      
      echo
      echo "== playwirght config candidates summary =="
      for f in $(git ls-files | rg '(^|/)(playwright\.config|.*playwright.*\.config).*\.(ts|js|mjs)$' | sed -n '1,50p'); do
        echo "--- $f"
        wc -l "$f"
        rg -n "webServer|timeout|retries|workers|projects|testDir|reporters|use:|useWebServer|web_servers|server" "$f" || true
      done
      
      echo
      echo "== relevant searches =="
      rg -n "completedByThread|persistedResult|generation-persistence-server|THREAD_ID|generation-server-thread|DELETE|reset|webServer|retries" testing/e2e | sed -n '1,240p'

      Repository: TanStack/ai

      Length of output: 31542


      🏁 Script executed:

      #!/bin/bash
      set -euo pipefail
      
      echo "== e2e playwright config relevant lines =="
      cat -n testing/e2e/playwright.config.ts | sed -n '1,90p'
      
      echo
      echo "== e2e global setup/teardown =="
      fd 'global|teardown|setup' testing/e2e -t f | sed -n '1,120p'
      for f in $(fd 'global|teardown|setup' testing/e2e -t f | sed -n '1,40p'); do
        echo "--- $f"
        rg -n "export default|testDir|globalSetup|globalTeardown|process|port|webServer|retries|shard|environmentVariables|playwright" "$f" || true
      done
      
      echo
      echo "== all shared server routes with DELETE/reset endpoints nearby generation-persistence server =="
      cat -n testing/e2e/src/routes/api.middleware-test.ts | sed -n '360,455p'
      rg -n "DELETE:|reset|completedByThread|generation-server-thread|generation-persistence-server|threadId" testing/e2e/src/routes testing/e2e/tests/generation-persistence-server.spec.ts | sed -n '1,220p'
      
      echo
      echo "== deterministic probe: route behavior after first completed job without reset =="
      python3 - <<'PY'
      completed_by_thread = {}
      thread_id = 'generation-server-thread'
      
      def persisted_result(thread_id, run_id):
          return {'id': 'image-1', 'model': 'mock-image-model', 'artifacts': [{'threadId': thread_id, 'runId': run_id}]}
      
      # Simulate the fixed-thread POST completing once
      completed_by_thread[thread_id] = persisted_result(thread_id, 'run-1')
      
      for i in range(3):
          result = completed_by_thread.get(thread_id)
          body = (
              {
                  'resumeSnapshot': {'schemaVersion': 1, 'resumeState': None, 'status': 'complete', 'activity': 'image', 'result': result},
                  'activeRun': None,
              }
              if result else {'resumeSnapshot': None, 'activeRun': None}
          )
          print(f'request {i}: status={body["resumeSnapshot"]["status"] if body["resumeSnapshot"] else None}')
      
      print("no_route_deletion_found", all(
          'completedByThread.delete' in code or "completedByThread.delete" in code
          for _ in []
      ))
      PY

      Repository: TanStack/ai

      Length of output: 20753


      Add a reset/cleanup path for the server-driven persistence record.

      completedByThread is keyed by the hardcoded generation-server-thread ID and is never cleared, while the e2e setup has no global teardown and Playwright reuses the dev server across retries. After the run completes once, the initial status → 'idle' assertion can fail deterministically on retry. Add a test-only DELETE/reset handler for the thread record, or clear it from the spec before the first page.goto.

      🤖 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 `@testing/e2e/src/routes/api.generation-persistence-server.ts` around lines 36
      - 39, Add a test-only reset path for the completedByThread record keyed by
      generation-server-thread, either through a DELETE handler or by clearing it in
      the persistence spec before the first page.goto. Ensure retries start with no
      prior completed generation while preserving the existing server-authoritative
      record behavior.
    6. 🧹 Nitpick comments (1)
      packages/ai-react/tests/use-generation.test.ts (1)

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

      Place this test alongside its source module.

      Move packages/ai-react/tests/use-generation.test.ts next to packages/ai-react/src/use-generation.ts (for example, packages/ai-react/src/use-generation.test.ts) to comply with the repository rule for **/*.test.ts.

      As per coding guidelines, unit tests must be placed in *.test.ts files alongside the source they cover.

      🤖 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/tests/use-generation.test.ts` around lines 1 - 24, Move the
      use-generation test file from the package-level tests directory to sit alongside
      the useGeneration source module, preserving its existing contents and imports.
      Place it as use-generation.test.ts next to use-generation.ts so the repository’s
      test placement rule is satisfied.

      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.
      
      Nitpick comments:
      In `@packages/ai-react/tests/use-generation.test.ts`:
      - Around line 1-24: Move the use-generation test file from the package-level
      tests directory to sit alongside the useGeneration source module, preserving its
      existing contents and imports. Place it as use-generation.test.ts next to
      use-generation.ts so the repository’s test placement rule is satisfied.

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: d175f848-bc98-48ce-9a08-7dd8c82bf67a

      📥 Commits

      Reviewing files that changed from the base of the PR and between 7d87a30f73c7b2ba382e2c11e139d745ded00860 and 951030f855fda23ce7a831b5d1e17eb49fe3be98.

      📒 Files selected for processing (9)
      • docs/persistence/build-your-own-adapter.md
      • packages/ai-client/src/generation-types.ts
      • packages/ai-client/tests/generation-resume-state.test.ts
      • packages/ai-persistence/skills/ai-persistence/build-cloudflare-artifact-store/SKILL.md
      • packages/ai-persistence/src/middleware.ts
      • packages/ai-persistence/src/types.ts
      • packages/ai-persistence/tests/generation-artifacts.test.ts
      • packages/ai-react/tests/use-generation.test.ts
      • packages/ai/src/types.ts
      🚧 Files skipped from review as they are similar to previous changes (6)
      • packages/ai-client/tests/generation-resume-state.test.ts
      • docs/persistence/build-your-own-adapter.md
      • packages/ai-persistence/tests/generation-artifacts.test.ts
      • packages/ai-persistence/src/middleware.ts
      • packages/ai-client/src/generation-types.ts
      • packages/ai-persistence/src/types.ts
    7. Caution

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

      ⚠️ Outside diff range comments (2)
      packages/ai-solid/src/use-generation.ts (2)

      259-265: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

      Clear the previous body when the option becomes undefined.

      The conditional spread on Line 263 skips the update when currentBody is removed, so the client keeps sending the previous body on later generations. Explicitly clear it using the supported empty/unset representation.

      Proposed fix
         createEffect(() => {
           const currentBody = options.body
      -    client.updateOptions({
      -      ...(currentBody !== undefined && { body: currentBody }),
      -    })
      +    client.updateOptions({ body: currentBody ?? {} })
         })
      🤖 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/src/use-generation.ts` around lines 259 - 265, Update the
      body synchronization effect around currentBody and client.updateOptions so it
      explicitly clears the client’s previous body when options.body becomes
      undefined, using the client’s supported empty or unset representation; preserve
      passing the current body when it is defined.

      186-201: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

      Use the conditional body spread described by this implementation comment.

      options.body may be absent while GenerationClientOptions.body is a strict optional, so this direct assignment can fail under exactOptionalPropertyTypes. Match the similar Svelte/React use-generation handling and omit the key when it is undefined.

      Proposed fix
      -      body: options.body,
      +      ...(options.body !== undefined && { body: options.body }),
      🤖 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/src/use-generation.ts` around lines 186 - 201, Update the
      clientOptions construction in useGeneration to remove the direct body assignment
      and conditionally spread body only when options.body is defined. Preserve the
      existing body value when present and omit the property when absent, matching the
      handling in the Svelte/React use-generation implementations.
      ♻️ Duplicate comments (1)
      packages/ai/skills/ai-core/client-persistence/SKILL.md (1)

      198-210: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

      Make every persisted generation route require and propagate threadId.

      • packages/ai/skills/ai-core/client-persistence/SKILL.md#L198-L210: pass the validated client threadId into generateImage.
      • packages/ai/skills/ai-core/media-generation/SKILL.md#L589-L595: reject missing threadId instead of documenting it as optional.
      🤖 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 198 -
      210, Make every persisted generation route require a validated client threadId
      and propagate it through the generation call. In
      packages/ai/skills/ai-core/client-persistence/SKILL.md lines 198-210, update the
      POST handler and generateImage invocation to pass threadId; in
      packages/ai/skills/ai-core/media-generation/SKILL.md lines 589-595, change the
      documented contract to reject missing threadId rather than treating it as
      optional.
      🧹 Nitpick comments (1)
      packages/ai-react/tests/use-generation-persistence-types.test.ts (1)

      18-24: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoff

      Place these tests alongside their covered hooks.

      This shared test is under tests/ while it covers modules in src/. Split or relocate the assertions into colocated *.test.ts files. As per coding guidelines, **/*.test.ts: “Place unit tests in *.test.ts files alongside the source they cover.”

      🤖 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/tests/use-generation-persistence-types.test.ts` around
      lines 18 - 24, The shared persistence type tests in
      use-generation-persistence-types.test.ts should be colocated with the hooks they
      cover. Split the assertions into *.test.ts files alongside useGenerateImage,
      useGenerateVideo, useGeneration, useSummarize, and useTranscription, preserving
      the existing coverage and removing the centralized tests/placement.

      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.
      
      Outside diff comments:
      In `@packages/ai-solid/src/use-generation.ts`:
      - Around line 259-265: Update the body synchronization effect around currentBody
      and client.updateOptions so it explicitly clears the client’s previous body when
      options.body becomes undefined, using the client’s supported empty or unset
      representation; preserve passing the current body when it is defined.
      - Around line 186-201: Update the clientOptions construction in useGeneration to
      remove the direct body assignment and conditionally spread body only when
      options.body is defined. Preserve the existing body value when present and omit
      the property when absent, matching the handling in the Svelte/React
      use-generation implementations.
      
      ---
      
      Duplicate comments:
      In `@packages/ai/skills/ai-core/client-persistence/SKILL.md`:
      - Around line 198-210: Make every persisted generation route require a validated
      client threadId and propagate it through the generation call. In
      packages/ai/skills/ai-core/client-persistence/SKILL.md lines 198-210, update the
      POST handler and generateImage invocation to pass threadId; in
      packages/ai/skills/ai-core/media-generation/SKILL.md lines 589-595, change the
      documented contract to reject missing threadId rather than treating it as
      optional.
      
      ---
      
      Nitpick comments:
      In `@packages/ai-react/tests/use-generation-persistence-types.test.ts`:
      - Around line 18-24: The shared persistence type tests in
      use-generation-persistence-types.test.ts should be colocated with the hooks they
      cover. Split the assertions into *.test.ts files alongside useGenerateImage,
      useGenerateVideo, useGeneration, useSummarize, and useTranscription, preserving
      the existing coverage and removing the centralized tests/placement.

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: c3d1d0d8-9105-4d15-9bf4-26d4ae4a53f1

      📥 Commits

      Reviewing files that changed from the base of the PR and between 951030f855fda23ce7a831b5d1e17eb49fe3be98 and 14b8d008c4f7e6a30b0adeb1cef1bd1cceedf153.

      📒 Files selected for processing (65)
      • .changeset/generation-persistence.md
      • docs/persistence/generation-persistence.md
      • docs/persistence/keep-generated-files.md
      • examples/ts-react-chat/src/routes/generation-hooks.tsx
      • examples/ts-react-chat/src/routes/generations.audio.tsx
      • examples/ts-react-chat/src/routes/generations.image.tsx
      • examples/ts-react-chat/src/routes/generations.speech.tsx
      • examples/ts-react-chat/src/routes/generations.summarize.tsx
      • examples/ts-react-chat/src/routes/generations.transcription.tsx
      • examples/ts-react-chat/src/routes/generations.video.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-types.ts
      • packages/ai-client/src/index.ts
      • packages/ai-persistence/skills/ai-persistence/SKILL.md
      • packages/ai-persistence/src/index.ts
      • packages/ai-persistence/src/middleware.ts
      • packages/ai-persistence/src/reconstruct-generation.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/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-persistence-types.test.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-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-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/routes/generation-persistence.tsx
      🚧 Files skipped from review as they are similar to previous changes (55)
      • examples/ts-react-chat/src/routes/generations.audio.tsx
      • packages/ai-persistence/src/retrieve.ts
      • examples/ts-react-chat/src/routes/generations.speech.tsx
      • packages/ai-client/src/index.ts
      • examples/ts-react-chat/src/routes/generation-hooks.tsx
      • docs/persistence/generation-persistence.md
      • examples/ts-react-chat/src/routes/generations.image.tsx
      • examples/ts-react-chat/src/routes/generations.summarize.tsx
      • packages/ai-persistence/tests/reconstruct-generation.test.ts
      • packages/ai-persistence/src/index.ts
      • examples/ts-react-chat/src/routes/generations.video.tsx
      • packages/ai-react/src/use-generate-speech.ts
      • packages/ai-react/src/use-summarize.ts
      • packages/ai-react/src/use-transcription.ts
      • packages/ai-persistence/src/reconstruct-generation.ts
      • packages/ai-solid/src/use-generate-audio.ts
      • packages/ai-vue/src/use-generate-video.ts
      • packages/ai-angular/src/inject-generate-video.ts
      • packages/ai-vue/src/use-transcription.ts
      • examples/ts-react-chat/src/routes/generations.transcription.tsx
      • docs/persistence/keep-generated-files.md
      • packages/ai-react/src/use-generate-audio.ts
      • testing/e2e/src/routes/generation-persistence.tsx
      • packages/ai-angular/src/inject-generate-image.ts
      • packages/ai-react/src/use-generate-image.ts
      • packages/ai-vue/src/use-generate-speech.ts
      • packages/ai-solid/src/use-summarize.ts
      • packages/ai-solid/src/use-generate-image.ts
      • packages/ai-vue/src/use-summarize.ts
      • packages/ai-svelte/src/create-generate-audio.svelte.ts
      • packages/ai-solid/src/use-generate-video.ts
      • packages/ai-persistence/tests/generation-artifacts.test.ts
      • packages/ai-svelte/src/create-generate-video.svelte.ts
      • packages/ai-angular/src/inject-generation.ts
      • packages/ai-vue/src/use-generate-audio.ts
      • packages/ai-angular/src/inject-generate-speech.ts
      • packages/ai-solid/src/use-generate-speech.ts
      • packages/ai-angular/src/inject-summarize.ts
      • packages/ai-svelte/src/create-summarize.svelte.ts
      • packages/ai-vue/src/use-generate-image.ts
      • packages/ai-angular/src/inject-transcription.ts
      • packages/ai-react/src/use-generation.ts
      • packages/ai-vue/tests/use-generation.test.ts
      • packages/ai-svelte/tests/create-generation.test.ts
      • packages/ai-solid/src/use-transcription.ts
      • packages/ai-solid/tests/use-generation.test.ts
      • packages/ai-react/tests/use-generation.test.ts
      • packages/ai-svelte/src/create-generation.svelte.ts
      • packages/ai-client/src/generation-types.ts
      • packages/ai-react/src/use-generate-video.ts
      • packages/ai-svelte/src/create-transcription.svelte.ts
      • packages/ai-persistence/src/middleware.ts
      • packages/ai-client/src/generation-client.ts
      • packages/ai-vue/src/use-generation.ts
      • packages/ai-persistence/src/types.ts
    8. Actionable comments posted: 1

      Caution

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

      ⚠️ Outside diff range comments (1)
      examples/ts-react-chat/src/routes/generations.image.tsx (1)

      186-195: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

      Avoid rendering a broken data URL after client-side restoration.

      The documented direct/server-function restore path has no image bytes. When img.url and img.b64Json are both absent, this renders data:image/png;base64,undefined instead of a meaningful unavailable state.

      Proposed fix
             {result && (
               <div className="space-y-4">
      -          {result.images.map((img, i) => (
      +          {result.images
      +            .filter((img) => img.url || img.b64Json)
      +            .map((img, i) => (
                   <img
                     key={i}
                     src={img.url || `data:image/png;base64,${img.b64Json}`}
                     alt={img.revisedPrompt || prompt}
                     className="w-full rounded-lg border border-gray-700"
                   />
      -          ))}
      +            ))}
               </div>
             )}
      🤖 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 `@examples/ts-react-chat/src/routes/generations.image.tsx` around lines 186 -
      195, Update the image rendering in the result.images map to handle entries where
      both img.url and img.b64Json are absent: avoid constructing a data URL with
      undefined and render a meaningful unavailable state instead. Preserve the
      existing URL and base64 image rendering for entries that contain image data.
      🤖 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/api.generate.image.ts`:
      - Around line 41-64: Authorize image-generation persistence using a
      server-derived per-session identity rather than trusting supplied opaque IDs. In
      examples/ts-react-chat/src/routes/api.generate.image.ts:41-64, validate
      ownership of supplied threadId/runId before passing them to generateImage and
      withGenerationPersistence; in
      examples/ts-react-chat/src/routes/api.generate.image.ts:71-96, provide the
      authorization callback during reconstruction and verify the artifact record’s
      threadId before returning bytes. In
      examples/ts-react-chat/src/routes/generations.image.tsx:29-38, replace the
      shared "image:streaming" identifier with a per-user/per-thread identifier, while
      continuing to authorize it at the route boundary.
      
      ---
      
      Outside diff comments:
      In `@examples/ts-react-chat/src/routes/generations.image.tsx`:
      - Around line 186-195: Update the image rendering in the result.images map to
      handle entries where both img.url and img.b64Json are absent: avoid constructing
      a data URL with undefined and render a meaningful unavailable state instead.
      Preserve the existing URL and base64 image rendering for entries that contain
      image data.
      🪄 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: be02f6ef-0654-4d85-b07c-48aa8fc75311

      📥 Commits

      Reviewing files that changed from the base of the PR and between 14b8d008c4f7e6a30b0adeb1cef1bd1cceedf153 and 4c0a9b4c7b44c4f8f649a57313f0e1a711ba912f.

      📒 Files selected for processing (11)
      • docs/persistence/build-your-own-adapter.md
      • examples/ts-react-chat/src/lib/generation-persistence.ts
      • examples/ts-react-chat/src/lib/generation-server-store.ts
      • examples/ts-react-chat/src/routes/api.generate.image.ts
      • examples/ts-react-chat/src/routes/api.interrupts.test.ts
      • examples/ts-react-chat/src/routes/generations.image.tsx
      • packages/ai-persistence/skills/ai-persistence/build-cloudflare-artifact-store/SKILL.md
      • packages/ai-persistence/src/reconstruct-generation.ts
      • packages/ai-persistence/src/types.ts
      • packages/ai-persistence/tests/persistence-fixtures.ts
      • packages/ai-persistence/tests/reconstruct-generation.test.ts
      💤 Files with no reviewable changes (2)
      • examples/ts-react-chat/src/routes/api.interrupts.test.ts
      • packages/ai-persistence/tests/reconstruct-generation.test.ts
      🚧 Files skipped from review as they are similar to previous changes (5)
      • examples/ts-react-chat/src/lib/generation-persistence.ts
      • packages/ai-persistence/tests/persistence-fixtures.ts
      • packages/ai-persistence/src/reconstruct-generation.ts
      • packages/ai-persistence/src/types.ts
      • docs/persistence/build-your-own-adapter.md
      Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)
    9. Pushed: mid-run reload resumability + persistent-generation demo

      Three commits land the generation-persistence resumability work and a demo page that exercises every surface.

      What's in:

      • Durable runs survive a client disconnect. toServerSentEventsResponse(stream, { durability }) now decouples the producer from the HTTP response: a reload cancels only the reader, the run keeps draining into the log, and a mount-time joinRun tails it to completion. Persistence off (no durability) still aborts on disconnect. Additive, no public API change.
      • One-shot activities are resumable — RUN_STARTED is now a durability flush boundary, so image/speech/transcription/summarize populate the log at the start of the run instead of only at the terminal (which was fast-failing the rejoin as "run gone").
      • Summarize resumes mid-run — summarize() threads runId/threadId into the wrapped chat, and @tanstack/openai-base's Responses chatStream honors options.runId for RUN_STARTED, so its delivery log keys align with the client's rejoin.
      • TTS restore via new reconstructSpeechResult (surfaces the durable artifact URL, since TTSResult.audio has no URL slot).
      • Failed rejoin settles to error instead of hanging on generating; dispose() no longer wipes the resumable snapshot (that's stop()'s job).
      • OpenAI reasoning models drop unsupported temperature/top_p (fixes gpt-5.5 summarize/chat 400s).
      • Example: new /generations/persistent-generation page; server routes fall back to reconstructGeneration on GET; the video route drops the hand-rolled startDetachedGeneration/tailGenerationResponse and uses the plain library path (the whole point — the library owns run lifetime now).
      • Unit tests + changesets for all of the above. Targeted suites green: ai 1293, ai-client 587, openai-base 136, ai-openai 242; example type-checks + builds; docs links pass.

      Verified in-browser: image/video/speech/transcription/summarize all resume a mid-run reload and restore on a done-refresh; a gone/interrupted run shows a clean error.

      Still TODO (not in this push)

      • E2E tests (mandatory). Playwright specs in testing/e2e/ for: mid-run reload rejoins + completes; done-refresh restores; durable-run-survives-disconnect; failed-rejoin -> error.
      • Full pnpm test:pr gate. Ran targeted suites + example types/build + docs links, but not the whole affected gate (sherif/knip/oxlint across all).
      • Kiira: 1 pre-existing failure at docs/persistence/generation-persistence.md:263 (the createServerFn + getGenerationHydration server-fn snippet). Unrelated to this change and in a file it doesn't touch, but it will keep the docs gate red until fixed.
      • Code-review pass over the full diff.
      • Chat cleanup: api.persistent-chat.ts still hand-rolls startDetachedRun; now redundant since the library survives disconnect. Simplify + verify chat mid-reload separately.
      • Duplicate artifact-serve setup in the example: generation-server-store.ts + api.artifacts.ts (used by persistent-generation) vs generation-server-persistence.ts + api.generate.image.artifact.ts (used by generations.image). Worth consolidating to one.
      • Audio provider in the demo defaults to fal-audio, which 403s without a music-capable key (env-dependent; not a code bug).
    10. tombeckenham reviewed

      I've tested this thoroughly. Everything through to the skills themselves in other projects. It works beautifully.

    11. tombeckenham merged this996a980

    12. tombeckenham closed this

Sign in to join this conversation.