Skip to content
Source
Sign inSign up
TanStack/ai

feat(persistence): server persistence + client browser-refresh durability #984

MergedAlemTuzlakmerged 76 commits intomain fromrefs/pull/984/headmerged by jherr View on GitHub

AlemTuzlakcommented

🎯 Changes

Adds durable chat state on the server and full-page-reload durability on the client, on top of the shipped ephemeral interrupts (#970), resumable streams (#955), and the shared Scope type (#980). Uses #785 as reference; #987 (generation persistence) and #988 (sandbox persistence) stack on this branch.

Server: one new package, @tanstack/ai-persistence

It ships the contract, not backends — four store interfaces (MessageStore, RunStore, InterruptStore, MetadataStore), the withPersistence / withGenerationPersistence middleware, reconstructChat for server-side hydrate, an in-memory reference backend, and a conformance testkit.

An earlier revision of this branch also published -drizzle, -prisma, and -cloudflare packages. Those were removed in 62c9975: a backend package has to own DDL, which puts it in permanent conflict with the migration tooling the consuming app already runs. You implement the stores against your own database instead — the guide and the agent skills walk through it per stack, and the conformance suite is what proves an adapter correct.

Locks live in @tanstack/ai, not in the persistence package

Multi-instance coordination started out inside @tanstack/ai-persistence and moved to core in cd8b731. LockStore / InMemoryLockStore / LocksCapability / withLocks are exported from @tanstack/ai.

The split is deliberate: state stores answer "what is durable chat data?", locks answer "who may run this critical section right now?" Locks are not a stores key, are not composable via composePersistence, and are not covered by the conformance testkit. withPersistence does not lock a turn for you. Keeping them in core also means the consumer that actually needs them today — @tanstack/ai-sandbox, which reads LocksCapability off the middleware chain — doesn't drag in a persistence dependency to get mutual exclusion.

InMemoryLockStore is a per-key promise chain, correct within a single process only; multi-instance deployments implement the one-method LockStore interface themselves, and the Cloudflare Durable Object recipe walks through a lease-based one. New guide at docs/advanced/locks.md.

Client: browser-refresh durability

The persistence option now stores one combined { messages, resume? } record per chat id, so a full page reload restores the transcript, rehydrates pending interrupts, and rejoins an in-flight run via joinRun on a durability-backed connection. Adds localStoragePersistence / sessionStoragePersistence / indexedDBPersistence, and an object form { store, messages: false } that keeps large transcripts off the client while still persisting the resume pointer.

Because it rides the existing option, all six framework integrations get it with no framework-specific code.

Breaking

  • The chat hooks no longer accept id — a hook's identity is its threadId (usechat-threadid-identity). ChatClient keeps id as a lower-level escape hatch.
  • Hand-rolled persistence adapters must update their write path. setItem now receives the combined { messages, resume? } record instead of a bare UIMessage[]. getItem still reads legacy arrays, but an adapter that assumed an array will write the new shape and fail to parse it back — and because adapter reads are best-effort, the conversation silently does not restore. This bit the e2e harness in this very PR; docs/persistence/client-persistence.md now documents the round-trip.

Docs, skills, example, e2e

  • New docs/persistence/ section: overview, chat persistence, client persistence, controls, build-your-own-adapter, migrations, internals. Replaces docs/chat/persistence.md. Locks get their own page under advanced, docs/advanced/locks.md.
  • @tanstack/ai-persistence ships 7 agent skills, nested ai-core-style under skills/ai-persistence/ — an entry point, server, stores, and four build-*-adapter recipes that read the app's existing ORM config and schema and write a single chat-persistence.ts against it (Drizzle, Prisma, Cloudflare D1, and a custom recipe for raw pg / Kysely / Mongo / Supabase).
  • Two skills ship in @tanstack/ai instead, because that's where the code they teach lives: ai-core/client-persistence (browser persistence is in the framework packages — an app persisting only in the browser never installs the server package) and ai-core/locks. Also fixes three packages (ai-mcp, ai-memory, ai-sandbox) whose skills TanStack Intent could never load.
  • examples/ts-react-chat /persistent-chat route (SQLite server + localStorage client), with sqlite-persistence.ts as the runnable reference the docs point at.
  • E2E: persistence-durability.spec.ts (message restore after reload, interrupt survives reload) plus localStorage persistence cases in chat.spec.ts.

✅ Checklist

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

test:pr green on the current head. Full Playwright suite run locally: 385 passed, 1 skipped. Three tools-test specs failed only under unbounded local parallelism and pass at CI's --workers=4; Nx separately flagged @tanstack/ai-sandbox-local-process:test:lib as a flaky task and it passes on re-run.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.

Ten changesets on this branch: persistence-packages and fresh-client-tail (minor, @tanstack/ai-persistence), client-browser-refresh-durability and usechat-threadid-identity (minor, ai-client + all six frameworks), seamless-reload-resume and fast-fail-rejoin (@tanstack/ai), locks-to-core (minor, ai / ai-persistence / ai-sandbox), memorystream-agent-loop-delivery and rejoin-not-aborted-on-mount (patch), and skill-discoverability (patch, ai / ai-mcp / ai-memory / ai-sandbox). No majors — the two breaking changes above land in pre-1.0 minors.

    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Review Change Stack

      Note

      Reviews paused

      It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

      Use the following commands to manage reviews:

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

      Use the checkboxes below for quick actions:

      • ▶️ Resume reviews
      • 🔍 Trigger review
      📝 Walkthrough

      Walkthrough

      This PR adds durable client chat persistence, server-side transcript/run/interrupt persistence, Drizzle, Prisma, and Cloudflare backends, browser storage adapters, resumable run rejoining, migration tooling, framework exports, documentation, examples, and end-to-end browser-refresh coverage.

      Changes

      Persistence durability

      Layer / File(s)Summary
      Client persistence and run rejoin
      packages/ai-client/*
      Persists combined transcript and resume state, supports legacy records, browser storage adapters, and joinRun reattachment.
      Server persistence contracts and middleware
      packages/ai-persistence/*
      Adds store contracts, middleware lifecycle handling, interrupt recovery, composition, in-memory stores, and chat reconstruction.
      Persistence backend adapters
      packages/ai-persistence-drizzle/*, packages/ai-persistence-prisma/*, packages/ai-persistence-cloudflare/*
      Adds SQL and Cloudflare persistence implementations, schemas, migration CLIs, Durable Object locks, and conformance coverage.
      Examples and browser durability tests
      examples/ts-react-chat/*, testing/e2e/*
      Adds persistent chat examples and deterministic reload tests for transcript and interrupt restoration.
      Documentation and release wiring
      docs/persistence/*, packages/ai-*/src/index.ts, .changeset/*
      Documents persistence configuration and publishes new client and backend APIs across framework packages.

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

      Possibly related PRs

      • TanStack/ai#661 — Earlier client persistence and hydration changes.
      • TanStack/ai#955 — Resumable stream delivery used for in-flight run reattachment.
      • TanStack/ai#970 — Interrupt and resume protocol changes used by persisted resume state.

      Sequence Diagram(s)

      sequenceDiagram
        participant Browser
        participant ChatClient
        participant Storage
        participant Server
        participant Persistence
        Browser->>ChatClient: Reload chat
        ChatClient->>Storage: Read persisted transcript and resume snapshot
        ChatClient->>Server: GET thread or joinRun(runId)
        Server->>Persistence: Load thread/run/interrupt state
        Persistence-->>Server: Stored state
        Server-->>ChatClient: Transcript or replayed stream chunks
        ChatClient-->>Browser: Restore messages and interrupts
      🚥 Pre-merge checks | ✅ 4 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 28.95% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (4 passed)
      Check nameStatusExplanation
      Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
      Title check✅ PassedThe title accurately summarizes the main change: server persistence plus client browser-refresh durability.
      Description check✅ PassedThe description matches the template with Changes, Checklist, and Release Impact sections and includes the required details.
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Commit unit tests in branch `feat/persistence-core`

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands.
    2. socket-security[bot](GitHub profile, opens in a new tab)commented

      Warning

      Review the following alerts detected in dependencies.

      According to your organization's Security Policy, it is recommended to resolve "Warn" alerts. Learn more about Socket for GitHub.

      Action Severity Alert  (click "▶" to expand/collapse)
      Warn High
      Obfuscated code: npm better-sqlite3 is 90.0% likely obfuscated

      Confidence: 0.90

      Location: Package overview

      From: pnpm-lock.yaml → npm/@tanstack/nitro-v2-vite-plugin@1.155.0 → npm/nitro@3.0.260610-beta → npm/@tanstack/start@1.120.20 → npm/better-sqlite3@12.11.1

      ℹ Read more on: This package | This alert | What is obfuscated code?

      Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

      Suggestion: Packages should not obfuscate their code. Consider not using packages with obfuscated code.

      Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/better-sqlite3@12.11.1. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

      Warn High
      Obfuscated code: npm drizzle-orm is 90.0% likely obfuscated

      Confidence: 0.90

      Location: Package overview

      From: pnpm-lock.yaml → npm/@tanstack/nitro-v2-vite-plugin@1.155.0 → npm/nitro@3.0.260610-beta → npm/@tanstack/start@1.120.20 → npm/drizzle-orm@0.45.2

      ℹ Read more on: This package | This alert | What is obfuscated code?

      Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

      Suggestion: Packages should not obfuscate their code. Consider not using packages with obfuscated code.

      Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/drizzle-orm@0.45.2. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

      Warn High
      Obfuscated code: npm effect is 90.0% likely obfuscated

      Confidence: 0.90

      Location: Package overview

      From: pnpm-lock.yaml → npm/@tanstack/nitro-v2-vite-plugin@1.155.0 → npm/nitro@3.0.260610-beta → npm/@tanstack/start@1.120.20 → npm/effect@3.20.0

      ℹ Read more on: This package | This alert | What is obfuscated code?

      Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

      Suggestion: Packages should not obfuscate their code. Consider not using packages with obfuscated code.

      Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/effect@3.20.0. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

      Warn High
      Obfuscated code: npm robust-predicates is 90.0% likely obfuscated

      Confidence: 0.90

      Location: Package overview

      From: pnpm-lock.yaml → npm/@tanstack/nitro-v2-vite-plugin@1.155.0 → npm/nitro@3.0.260610-beta → npm/@tanstack/start@1.120.20 → npm/robust-predicates@3.0.3

      ℹ Read more on: This package | This alert | What is obfuscated code?

      Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

      Suggestion: Packages should not obfuscate their code. Consider not using packages with obfuscated code.

      Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/robust-predicates@3.0.3. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

      Warn Medium
      Deprecated by its maintainer: npm prebuild-install

      Reason: No longer maintained. Please contact the author of the relevant native addon; alternatives are available.

      From: pnpm-lock.yaml → npm/@tanstack/nitro-v2-vite-plugin@1.155.0 → npm/nitro@3.0.260610-beta → npm/@tanstack/start@1.120.20 → npm/prebuild-install@7.1.3

      ℹ Read more on: This package | This alert | What is a deprecated package?

      Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

      Suggestion: Research the state of the package and determine if there are non-deprecated versions that can be used, or if it should be replaced with a new, supported solution.

      Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/prebuild-install@7.1.3. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

      View full report

    3. github-actions[bot](GitHub profile, opens in a new tab)commented

      🚀 Changeset Version Preview

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

      🟥 Major bumps

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

      🟨 Minor bumps

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

      🟩 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
    4. nx-cloud[bot](GitHub profile, opens in a new tab)commented

      View your CI Pipeline Execution ↗ for commit 043327cf016a3f16141cea1870ec047ed0b9ef11

      CommandStatusDurationResult
      nx run-many --targets=build --exclude=examples/...✅ Succeeded23sView ↗

      ☁️ Nx Cloud last updated this comment at 2026-07-27 16:20:23 UTC

    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 (2)
      packages/ai-persistence-cloudflare/tests/migration-cli.test.ts (1)

      1-66: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

      Colocate this test with migration-cli.ts.

      Move this to packages/ai-persistence-cloudflare/src/migration-cli.test.ts so its location follows the repository test-layout rule.

      As per coding guidelines, “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-persistence-cloudflare/tests/migration-cli.test.ts` around lines
      1 - 66, Move the migration CLI test suite from the tests directory to a
      *.test.ts file alongside migration-cli.ts under src, preserving its existing
      imports, test cases, and behavior.

      Source: Coding guidelines

      packages/ai-client/src/chat-client.ts (1)

      1-1: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

      IndexedDB rejoin needs an async callback path readInitial() only computes rejoinRunId on the synchronous path. For promise-backed persistence, hydrateAsync() reapplies the resume snapshot but never calls resumeInFlightRun(), so reloads from indexedDBPersistence won’t reattach to an in-flight run. Thread a rejoin callback through the async hydration path and invoke it once the processor is ready.

      🤖 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/chat-client.ts` at line 1, Update the async hydration
      flow around readInitial() and hydrateAsync() to carry the computed rejoinRunId
      through promise-backed persistence, then invoke resumeInFlightRun() once the
      processor is ready. Preserve the existing synchronous rejoin behavior and ensure
      the callback runs only after the resume snapshot has been reapplied.
      🟡 Minor comments (10)
      examples/ts-react-chat/src/routes/persistent-chat.tsx-20-23 (1)

      20-23: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

      Restore Date fields when hydrating persisted chat state. JSON.stringify converts Date values to strings and JSON.parse does not revive them, so rehydrated messages no longer match the ChatPersistedState runtime shape.

      • examples/ts-react-chat/src/routes/persistent-chat.tsx#L20-L23: use a matching serializer/reviver that restores persisted message dates.
      • testing/e2e/src/routes/persistence-durability.tsx#L25-L28: use the same codec and assert a rehydrated timestamp remains a Date.
      🤖 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/persistent-chat.tsx` around lines 20 - 23,
      Update the localStorage persistence codec in
      examples/ts-react-chat/src/routes/persistent-chat.tsx (lines 20-23) to revive
      persisted message date fields as Date instances, while preserving JSON
      serialization. Apply the same codec in
      testing/e2e/src/routes/persistence-durability.tsx (lines 25-28) and add an
      assertion that the rehydrated timestamp is a Date.
      packages/ai-persistence-cloudflare/bin/tanstack-ai-cloudflare-migrations.mjs-1-2 (1)

      1-2: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

      Wrap the CLI entrypoint in a try/catch. packages/ai-persistence-cloudflare/src/cli.ts awaits runCloudflareMigrationsCli(...) directly, so MigrationCliError rejections will surface as raw stack traces. Print the message to stderr and set process.exitCode = 1 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 `@packages/ai-persistence-cloudflare/bin/tanstack-ai-cloudflare-migrations.mjs`
      around lines 1 - 2, Wrap the CLI import and execution in the migration
      entrypoint around runCloudflareMigrationsCli with try/catch handling for
      MigrationCliError rejections; print the error message to stderr and set
      process.exitCode to 1 instead of allowing a raw stack trace. Preserve normal
      successful CLI execution.
      packages/ai-persistence-prisma/package.json-81-82 (1)

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

      Use workspace:* for internal peer dependencies.

      Replace workspace:^ with the required workspace:* protocol.

      🤖 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-prisma/package.json` around lines 81 - 82, Update the
      internal dependencies "`@tanstack/ai`" and "`@tanstack/ai-persistence`" in
      package.json to use the workspace:* protocol instead of workspace:^.

      Source: Coding guidelines

      packages/ai-persistence-drizzle/tests/package-contract.test.ts-42-49 (1)

      42-49: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

      Detect dynamic Node and SQLite imports too.

      await import('node:sqlite') or await import('./sqlite') passes these from-only checks while making the root entry unsafe for edge runtimes.

      Suggested update
      -      expect(contents, filename).not.toMatch(/from ['"]node:/)
      +      expect(contents, filename).not.toMatch(
      +        /(?:from\s*|import\s*\()\s*['"]node:/,
      +      )
      ...
      -    expect(root).not.toMatch(/from ['"].*sqlite/)
      +    expect(root).not.toMatch(
      +      /(?:from\s*|import\s*\()\s*['"][^'"]*sqlite/,
      +    )
      🤖 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-drizzle/tests/package-contract.test.ts` around lines
      42 - 49, Extend the import checks in the package contract test to reject dynamic
      import syntax as well as static from imports. Update the assertions covering
      package files and the root index loaded via fileURLToPath so await import
      references to node: modules, Buffer usage, and SQLite paths such as node:sqlite
      or relative sqlite imports are detected.
      packages/ai/skills/ai-core/chat-experience/SKILL.md-506-508 (1)

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

      Garbled sentence — fix the parenthetical.

      "(the one exception to mistake j below)" doesn't parse; likely a leftover editing artifact.

      🤖 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/chat-experience/SKILL.md` around lines 506 - 508,
      Fix the parenthetical sentence in the storage adapter and ChatPersistedState
      guidance by removing the garbled “one exception to mistake j below” wording and
      replacing it with a clear, grammatically correct statement consistent with the
      intended import guidance. Keep the surrounding distinction between
      `@tanstack/ai-client` imports and framework-package useChat imports unchanged.
      packages/ai-persistence/package.json-49-51 (1)

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

      Use the required workspace protocol.

      Change @tanstack/ai from workspace:^ to workspace:*.

      As per coding guidelines, “Use the workspace:* protocol for internal package dependencies in package.json.”

      🤖 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/package.json` around lines 49 - 51, Update the
      `@tanstack/ai` entry in the peerDependencies object of package.json from the
      workspace:^ protocol to workspace:* while leaving the vitest dependency
      unchanged.

      Source: Coding guidelines

      docs/persistence/browser-refresh.md-45-47 (1)

      45-47: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

      Do not promise restoration before first paint for async storage.

      indexedDBPersistence is documented as async on Lines 55-63, so its record cannot be guaranteed before the initial paint. Describe restoration as completing after hydration/storage loading and recommend a loading state where 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 `@docs/persistence/browser-refresh.md` around lines 45 - 47, Update the
      persistence documentation around the “next load” description to avoid promising
      transcript or interrupt restoration before first paint when using async storage
      such as indexedDBPersistence. State that restoration completes after
      hydration/storage loading, and recommend showing a loading state when the UI
      must wait for restored data.
      packages/ai-client/tests/resume-snapshot.test.ts-1-16 (1)

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

      Colocate these unit tests with their source modules.

      Split this new cross-module suite into tests beside src/client-persistor.ts, src/connection-adapters.ts, and src/chat-client.ts.

      As per coding guidelines, “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-client/tests/resume-snapshot.test.ts` around lines 1 - 16, Split
      the cross-module tests in resume-snapshot.test.ts into colocated *.test.ts files
      beside client-persistor.ts, connection-adapters.ts, and chat-client.ts, placing
      each test with the source module it covers. Preserve the existing assertions and
      shared test setup while removing the standalone cross-module suite.

      Source: Coding guidelines

      docs/persistence/browser-refresh.md-69-77 (1)

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

      Add the server-side resumable endpoint example.

      This section requires a server route that records and replays the stream, but only shows client consumption. Include the replay endpoint alongside the useChat example.

      As per coding guidelines, “When a documentation page covers both server and client behavior, include snippets for both halves: the server endpoint and the client consumption.”

      🤖 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/browser-refresh.md` around lines 69 - 77, Update the “Rejoin
      an in-flight run” section to include a server-side resumable endpoint example
      alongside the existing useChat/joinRun client explanation. Show the route’s
      stream recording and GET replay behavior, reusing the documented resumable
      connection pattern from “Resumable streams,” while preserving the existing
      client flow.

      Source: Coding guidelines

      docs/persistence/internals.md-31-35 (1)

      31-35: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

      Correct the documented onConfig ordering.

      Pending interrupts are loaded and resume input is validated before createOrResumeRun. As written, the page incorrectly implies invalid resumes create a run record first.

      🤖 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/internals.md` around lines 31 - 35, Update the onConfig
      description in the persistence internals documentation to state that pending
      interrupts are loaded and the request’s resume batch is validated before
      createOrResumeRun, then describe run creation or resumption and stored-message
      merging in the correct order.
      🧹 Nitpick comments (6)
      packages/ai-persistence-cloudflare/migrations/0000_tanstack_ai_initial.sql (1)

      1-32: 🚀 Performance & Scalability | 🔵 Trivial

      Consider secondary indexes for thread/run lookups.

      Interrupts and runs are keyed only by their primary IDs, but list-style access (e.g. interrupts for a run/thread, runs for a thread) filters on interrupts.run_id, interrupts.thread_id, and runs.thread_id. Without indexes these become full table scans as rows accumulate. Since this file must stay byte-for-byte identical to the Drizzle asset, add the indexes in the Drizzle schema source and regenerate both assets rather than editing here.

      🤖 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-cloudflare/migrations/0000_tanstack_ai_initial.sql`
      around lines 1 - 32, Add secondary indexes for interrupts.run_id,
      interrupts.thread_id, and runs.thread_id in the corresponding Drizzle schema
      definitions, then regenerate the migration assets so this SQL file remains
      byte-for-byte identical to generated output.
      packages/ai-persistence-cloudflare/tsconfig.json (1)

      1-9: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

      Global "node" types leak into src, past the Workers-compatibility guard.

      types: ["node", ...] applies across include: ["src", "tests"], so Node's ambient globals (process, __dirname, etc.) typecheck fine inside src even though this package targets Cloudflare Workers. The sibling package-contract.test.ts only regex-checks for from 'node:' imports and the literal Buffer, so use of other Node globals in src wouldn't be caught by that guard and would only fail at runtime on Workers.

      Consider scoping "node" types to a tests-only tsconfig (or project reference) so src typechecking reflects the actual Workers runtime.

      🤖 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-cloudflare/tsconfig.json` around lines 1 - 9, Remove
      the global "node" type declaration from the package tsconfig's shared
      compilerOptions so src is checked only against Cloudflare Workers types. Add a
      tests-only tsconfig or project reference that supplies "node" types for tests,
      while preserving the existing source and test includes and Workers-compatible
      source typechecking.
      packages/ai-persistence-drizzle/src/sqlite.ts (1)

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

      Use the native drizzle-orm/node-sqlite driver here drizzle-orm/node-sqlite already accepts DatabaseSync directly, so this custom sqlite-proxy callback and row-to-array conversion can be removed.

      🤖 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-drizzle/src/sqlite.ts` around lines 32 - 44, Replace
      the custom drizzle sqlite-proxy callback around the database initialization with
      the native drizzle-orm/node-sqlite driver, passing the existing DatabaseSync
      instance directly to drizzle. Remove the statement preparation, method
      branching, and Object.values row conversion while preserving the resulting
      database handle used by the rest of the module.
      packages/ai-persistence-prisma/src/assets/tanstack-ai.prisma (1)

      15-40: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

      Add indexes for threadId/runId on Interrupt.

      stores.ts queries Interrupt via findMany({ where: { threadId } }) and findMany({ where: { runId } }) (list/listPending/listByRun/listPendingByRun), but no @@index is declared for either column here. As interrupt volume grows this forces full table scans on every listing call.

      ⚡ Proposed indexes
       model Interrupt {
         interruptId  String  `@id` `@map`("interrupt_id")
         runId        String  `@map`("run_id")
         threadId     String  `@map`("thread_id")
         status       String
         requestedAt  BigInt  `@map`("requested_at")
         resolvedAt   BigInt? `@map`("resolved_at")
         payloadJson  String  `@map`("payload_json")
         responseJson String? `@map`("response_json")
      
      +  @@index([threadId])
      +  @@index([runId])
         @@map("interrupts")
       }
      🤖 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-prisma/src/assets/tanstack-ai.prisma` around lines 15
      - 40, Add separate Prisma indexes for both threadId and runId in the Interrupt
      model, alongside its existing fields and mapping, so the
      list/listPending/listByRun/listPendingByRun queries can use indexed lookups.
      packages/ai-persistence/tests/memory.conformance.test.ts (1)

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

      Colocate the memory-store unit tests with their covered source.

      • packages/ai-persistence/tests/memory.conformance.test.ts#L1-L4: move beside packages/ai-persistence/src/memory.ts.
      • packages/ai-persistence/tests/memory.test.ts#L1-L132: move beside packages/ai-persistence/src/memory.ts.

      As per coding guidelines, “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-persistence/tests/memory.conformance.test.ts` around lines 1 - 4,
      Move the tests covering memoryPersistence from
      packages/ai-persistence/tests/memory.conformance.test.ts (lines 1-4) and
      packages/ai-persistence/tests/memory.test.ts (lines 1-132) to *.test.ts files
      alongside packages/ai-persistence/src/memory.ts, preserving their existing test
      behavior and updating relative imports as needed.

      Source: Coding guidelines

      packages/ai-persistence/src/middleware.ts (1)

      333-338: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

      Prefer EventType.RUN_FINISHED here. Using the enum keeps this guard aligned with the shared event type and avoids a silent mismatch if the event name changes.

      🤖 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 333 - 338, Update the
      guard in the RUN_FINISHED handling flow to compare chunk.type against the shared
      EventType.RUN_FINISHED enum member instead of the string literal, while
      preserving the existing interrupt outcome check and early return behavior.
      🤖 Prompt for all review comments with AI agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      Inline comments:
      In `@examples/ts-react-chat/src/routes/api.persistent-chat.ts`:
      - Around line 51-53: Scope persisted chat threads to the authenticated tenant:
      in examples/ts-react-chat/src/routes/api.persistent-chat.ts#L51-L53, derive and
      authorize the persistence thread identity server-side before invoking
      withChatPersistence instead of trusting caller-controlled params.threadId; in
      examples/ts-react-chat/src/routes/persistent-chat.tsx#L28-L32, replace the
      globally shared persistent ID demonstration with an authenticated/session-scoped
      thread ID.
      
      In `@packages/ai-client/src/chat-client.ts`:
      - Around line 445-466: Update the chat client initialization and hydrateAsync
      flow so asynchronously loaded persistence also extracts a bare in-flight run’s
      resumeState.runId and passes it to resumeInFlightRun() after the processor is
      ready. Preserve pending-interrupt handling through applyResumeSnapshot(), while
      ensuring the synchronous and asynchronous paths use consistent rejoin behavior.
      
      In `@packages/ai-client/src/connection-adapters.ts`:
      - Around line 875-885: Update the normalized adapter’s conditional spread around
      joinRun to expose the wrapper only when typeof connection.joinRun is "function",
      rather than merely checking property presence. Preserve the existing
      ResumableConnectConnectionAdapter delegation and ensure an explicit undefined
      joinRun is omitted.
      
      In `@packages/ai-persistence-drizzle/package.json`:
      - Around line 55-56: Update the internal dependency declarations in package.json
      for `@tanstack/ai` and `@tanstack/ai-persistence` from workspace:^ to workspace:*.
      Leave external dependencies unchanged.
      
      In `@packages/ai-persistence-drizzle/src/sqlite.ts`:
      - Around line 20-30: Add an engines.node declaration to
      packages/ai-persistence-drizzle/package.json requiring Node 22.13.0 or newer, or
      the equivalent supported Node release range that excludes versions where
      node:sqlite requires the experimental flag. Keep the sqlitePersistence
      implementation unchanged.
      
      In `@packages/ai-persistence-drizzle/tests/custom-schema.test.ts`:
      - Around line 1-113: Move the tests beside the source modules they cover,
      preserving their contents and behavior: relocate
      packages/ai-persistence-drizzle/tests/custom-schema.test.ts (lines 1-113) beside
      the Drizzle persistence/schema sources,
      packages/ai-persistence-drizzle/tests/package-contract.test.ts (lines 1-67)
      beside the Drizzle package-contract surface, and
      packages/ai-persistence-prisma/tests/package-contract.test.ts (lines 1-28)
      beside the Prisma package-contract surface.
      
      In `@packages/ai-persistence-drizzle/tests/migration-cli.test.ts`:
      - Around line 1-6: Move the migration CLI tests from
      packages/ai-persistence-drizzle/tests/migration-cli.test.ts to
      packages/ai-persistence-drizzle/src/migration-cli.test.ts alongside
      runDrizzleMigrationsCli. Update packages/ai-persistence-drizzle/vite.config.ts
      at line 13 to discover colocated tests such as src/**/*.test.ts, preserving test
      execution after the move.
      
      In `@packages/ai-persistence-drizzle/tests/schema-source.test.ts`:
      - Around line 1-31: Move the schema comparison test from the package tests
      directory to a *.test.ts file alongside src/schema.ts, preserving normalize and
      the emitted-schema structural assertions. Update the package’s test include
      configuration only if needed so the colocated test is discovered.
      
      In `@packages/ai-persistence-prisma/src/index.ts`:
      - Around line 44-48: Update the prismaPersistence parameter to accept the
      minimal delegate-surface type required by resolveDelegates instead of this
      package’s generated PrismaClient type. Ensure consumer-generated Prisma clients,
      including clients with renamed models, can be passed directly without casts,
      while preserving the existing options?.models delegation flow.
      
      In `@packages/ai-persistence-prisma/vite.config.ts`:
      - Line 13: Update the test include configuration in vite.config.ts to discover
      colocated *.test.ts files throughout the source tree, not only
      tests/**/*.test.ts. Move existing package tests alongside the modules they cover
      while preserving their test names and coverage.
      
      In `@packages/ai-persistence/src/locks.ts`:
      - Around line 46-57: Update the lock-chain cleanup around the chains map so a
      key is removed once its current run settles, while preserving newer work that
      may have been queued for the same key. Use the existing key and chain identity
      to ensure an older completion cannot delete a replacement chain, and keep
      rejection swallowing behavior unchanged.
      
      In `@packages/ai-persistence/src/memory.ts`:
      - Around line 98-127: Update the interrupt query methods list, listPending,
      listByRun, and listPendingByRun to sort their filtered results by ascending
      requestedAt before returning them. Preserve each method’s existing threadId,
      runId, and pending-status filters while ensuring all query results follow the
      InterruptStore ordering contract rather than Map insertion order.
      - Around line 131-143: Replace the flat string-key storage in the metadata
      methods get, set, and delete with nested maps or another collision-free
      representation that preserves scope and key as separate components. Ensure
      distinct pairs such as scope “a:b” with key “c” and scope “a” with key “b:c”
      remain independently retrievable, writable, and deletable.
      
      In `@testing/e2e/tests/persistence-durability.spec.ts`:
      - Around line 17-21: Extend the persistence durability E2E fixture to pause
      deterministically mid-stream, reload during the active run, and verify useChat
      issues a resume/joinRun request and renders exactly one continuation. During the
      interrupt reload, block API traffic to prove recovery uses local storage only,
      then restore traffic for the resumed request; update the existing excluded-path
      note and assertions accordingly.
      
      ---
      
      Outside diff comments:
      In `@packages/ai-client/src/chat-client.ts`:
      - Line 1: Update the async hydration flow around readInitial() and
      hydrateAsync() to carry the computed rejoinRunId through promise-backed
      persistence, then invoke resumeInFlightRun() once the processor is ready.
      Preserve the existing synchronous rejoin behavior and ensure the callback runs
      only after the resume snapshot has been reapplied.
      
      In `@packages/ai-persistence-cloudflare/tests/migration-cli.test.ts`:
      - Around line 1-66: Move the migration CLI test suite from the tests directory
      to a *.test.ts file alongside migration-cli.ts under src, preserving its
      existing imports, test cases, and behavior.
      
      ---
      
      Minor comments:
      In `@docs/persistence/browser-refresh.md`:
      - Around line 45-47: Update the persistence documentation around the “next load”
      description to avoid promising transcript or interrupt restoration before first
      paint when using async storage such as indexedDBPersistence. State that
      restoration completes after hydration/storage loading, and recommend showing a
      loading state when the UI must wait for restored data.
      - Around line 69-77: Update the “Rejoin an in-flight run” section to include a
      server-side resumable endpoint example alongside the existing useChat/joinRun
      client explanation. Show the route’s stream recording and GET replay behavior,
      reusing the documented resumable connection pattern from “Resumable streams,”
      while preserving the existing client flow.
      
      In `@docs/persistence/internals.md`:
      - Around line 31-35: Update the onConfig description in the persistence
      internals documentation to state that pending interrupts are loaded and the
      request’s resume batch is validated before createOrResumeRun, then describe run
      creation or resumption and stored-message merging in the correct order.
      
      In `@examples/ts-react-chat/src/routes/persistent-chat.tsx`:
      - Around line 20-23: Update the localStorage persistence codec in
      examples/ts-react-chat/src/routes/persistent-chat.tsx (lines 20-23) to revive
      persisted message date fields as Date instances, while preserving JSON
      serialization. Apply the same codec in
      testing/e2e/src/routes/persistence-durability.tsx (lines 25-28) and add an
      assertion that the rehydrated timestamp is a Date.
      
      In `@packages/ai-client/tests/resume-snapshot.test.ts`:
      - Around line 1-16: Split the cross-module tests in resume-snapshot.test.ts into
      colocated *.test.ts files beside client-persistor.ts, connection-adapters.ts,
      and chat-client.ts, placing each test with the source module it covers. Preserve
      the existing assertions and shared test setup while removing the standalone
      cross-module suite.
      
      In
      `@packages/ai-persistence-cloudflare/bin/tanstack-ai-cloudflare-migrations.mjs`:
      - Around line 1-2: Wrap the CLI import and execution in the migration entrypoint
      around runCloudflareMigrationsCli with try/catch handling for MigrationCliError
      rejections; print the error message to stderr and set process.exitCode to 1
      instead of allowing a raw stack trace. Preserve normal successful CLI execution.
      
      In `@packages/ai-persistence-drizzle/tests/package-contract.test.ts`:
      - Around line 42-49: Extend the import checks in the package contract test to
      reject dynamic import syntax as well as static from imports. Update the
      assertions covering package files and the root index loaded via fileURLToPath so
      await import references to node: modules, Buffer usage, and SQLite paths such as
      node:sqlite or relative sqlite imports are detected.
      
      In `@packages/ai-persistence-prisma/package.json`:
      - Around line 81-82: Update the internal dependencies "`@tanstack/ai`" and
      "`@tanstack/ai-persistence`" in package.json to use the workspace:* protocol
      instead of workspace:^.
      
      In `@packages/ai-persistence/package.json`:
      - Around line 49-51: Update the `@tanstack/ai` entry in the peerDependencies
      object of package.json from the workspace:^ protocol to workspace:* while
      leaving the vitest dependency unchanged.
      
      In `@packages/ai/skills/ai-core/chat-experience/SKILL.md`:
      - Around line 506-508: Fix the parenthetical sentence in the storage adapter and
      ChatPersistedState guidance by removing the garbled “one exception to mistake j
      below” wording and replacing it with a clear, grammatically correct statement
      consistent with the intended import guidance. Keep the surrounding distinction
      between `@tanstack/ai-client` imports and framework-package useChat imports
      unchanged.
      
      ---
      
      Nitpick comments:
      In `@packages/ai-persistence-cloudflare/migrations/0000_tanstack_ai_initial.sql`:
      - Around line 1-32: Add secondary indexes for interrupts.run_id,
      interrupts.thread_id, and runs.thread_id in the corresponding Drizzle schema
      definitions, then regenerate the migration assets so this SQL file remains
      byte-for-byte identical to generated output.
      
      In `@packages/ai-persistence-cloudflare/tsconfig.json`:
      - Around line 1-9: Remove the global "node" type declaration from the package
      tsconfig's shared compilerOptions so src is checked only against Cloudflare
      Workers types. Add a tests-only tsconfig or project reference that supplies
      "node" types for tests, while preserving the existing source and test includes
      and Workers-compatible source typechecking.
      
      In `@packages/ai-persistence-drizzle/src/sqlite.ts`:
      - Around line 32-44: Replace the custom drizzle sqlite-proxy callback around the
      database initialization with the native drizzle-orm/node-sqlite driver, passing
      the existing DatabaseSync instance directly to drizzle. Remove the statement
      preparation, method branching, and Object.values row conversion while preserving
      the resulting database handle used by the rest of the module.
      
      In `@packages/ai-persistence-prisma/src/assets/tanstack-ai.prisma`:
      - Around line 15-40: Add separate Prisma indexes for both threadId and runId in
      the Interrupt model, alongside its existing fields and mapping, so the
      list/listPending/listByRun/listPendingByRun queries can use indexed lookups.
      
      In `@packages/ai-persistence/src/middleware.ts`:
      - Around line 333-338: Update the guard in the RUN_FINISHED handling flow to
      compare chunk.type against the shared EventType.RUN_FINISHED enum member instead
      of the string literal, while preserving the existing interrupt outcome check and
      early return behavior.
      
      In `@packages/ai-persistence/tests/memory.conformance.test.ts`:
      - Around line 1-4: Move the tests covering memoryPersistence from
      packages/ai-persistence/tests/memory.conformance.test.ts (lines 1-4) and
      packages/ai-persistence/tests/memory.test.ts (lines 1-132) to *.test.ts files
      alongside packages/ai-persistence/src/memory.ts, preserving their existing test
      behavior and updating relative imports as needed.
      🪄 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

      Run ID: e3a12367-1bdc-4ac2-b7bf-8d3f28b91b6d

      📥 Commits

      Reviewing files that changed from the base of the PR and between 50d7a7da319bd39c578548390a723302f90068c7 and b443a9f6e20b679282ad484e01253137efcb5ed6.

      ⛔ Files ignored due to path filters (1)
      • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
      📒 Files selected for processing (134)
      • .changeset/client-browser-refresh-durability.md
      • .changeset/persistence-packages.md
      • docs/chat/persistence.md
      • docs/config.json
      • docs/persistence/browser-refresh.md
      • docs/persistence/chat-persistence.md
      • docs/persistence/cloudflare.md
      • docs/persistence/controls.md
      • docs/persistence/custom-stores.md
      • docs/persistence/drizzle.md
      • docs/persistence/internals.md
      • docs/persistence/migrations.md
      • docs/persistence/overview.md
      • docs/persistence/prisma.md
      • docs/persistence/sql-backends.md
      • examples/ts-react-chat/.gitignore
      • examples/ts-react-chat/README.md
      • examples/ts-react-chat/package.json
      • examples/ts-react-chat/src/components/Header.tsx
      • examples/ts-react-chat/src/routes/api.persistent-chat.ts
      • examples/ts-react-chat/src/routes/persistent-chat.tsx
      • packages/ai-client/src/chat-client.ts
      • packages/ai-client/src/client-persistor.ts
      • packages/ai-client/src/connection-adapters.ts
      • packages/ai-client/src/index.ts
      • packages/ai-client/src/storage-adapters.ts
      • packages/ai-client/src/types.ts
      • packages/ai-client/tests/resume-snapshot.test.ts
      • packages/ai-persistence-cloudflare/bin/tanstack-ai-cloudflare-migrations.mjs
      • packages/ai-persistence-cloudflare/migrations/0000_tanstack_ai_initial.sql
      • packages/ai-persistence-cloudflare/package.json
      • packages/ai-persistence-cloudflare/src/assets.d.ts
      • packages/ai-persistence-cloudflare/src/assets/0000_tanstack_ai_initial.sql
      • packages/ai-persistence-cloudflare/src/bindings.ts
      • packages/ai-persistence-cloudflare/src/cli.ts
      • packages/ai-persistence-cloudflare/src/d1.ts
      • packages/ai-persistence-cloudflare/src/index.ts
      • packages/ai-persistence-cloudflare/src/locks.ts
      • packages/ai-persistence-cloudflare/src/migration-cli.ts
      • packages/ai-persistence-cloudflare/src/migrations.ts
      • packages/ai-persistence-cloudflare/tests/api-types.test-d.ts
      • packages/ai-persistence-cloudflare/tests/locks.test.ts
      • packages/ai-persistence-cloudflare/tests/migration-cli.test.ts
      • packages/ai-persistence-cloudflare/tests/migrations.test.ts
      • packages/ai-persistence-cloudflare/tests/package-contract.test.ts
      • packages/ai-persistence-cloudflare/tests/runtime.conformance.test.ts
      • packages/ai-persistence-cloudflare/tsconfig.json
      • packages/ai-persistence-cloudflare/vite.config.ts
      • packages/ai-persistence-drizzle/bin/tanstack-ai-drizzle-migrations.mjs
      • packages/ai-persistence-drizzle/bin/tanstack-ai-drizzle-schema.mjs
      • packages/ai-persistence-drizzle/drizzle.config.ts
      • packages/ai-persistence-drizzle/drizzle/0000_tanstack_ai_initial.sql
      • packages/ai-persistence-drizzle/drizzle/meta/0000_snapshot.json
      • packages/ai-persistence-drizzle/drizzle/meta/_journal.json
      • packages/ai-persistence-drizzle/package.json
      • packages/ai-persistence-drizzle/src/assets.d.ts
      • packages/ai-persistence-drizzle/src/assets/0000_tanstack_ai_initial.sql
      • packages/ai-persistence-drizzle/src/assets/tanstack-ai-schema.ts
      • packages/ai-persistence-drizzle/src/cli.ts
      • packages/ai-persistence-drizzle/src/index.ts
      • packages/ai-persistence-drizzle/src/migration-cli.ts
      • packages/ai-persistence-drizzle/src/migrations.ts
      • packages/ai-persistence-drizzle/src/schema-cli-main.ts
      • packages/ai-persistence-drizzle/src/schema-cli.ts
      • packages/ai-persistence-drizzle/src/schema-contract.ts
      • packages/ai-persistence-drizzle/src/schema-source.ts
      • packages/ai-persistence-drizzle/src/schema.ts
      • packages/ai-persistence-drizzle/src/sqlite-migrations.ts
      • packages/ai-persistence-drizzle/src/sqlite.ts
      • packages/ai-persistence-drizzle/src/stores.ts
      • packages/ai-persistence-drizzle/tests/api-types.test-d.ts
      • packages/ai-persistence-drizzle/tests/custom-schema.test.ts
      • packages/ai-persistence-drizzle/tests/drizzle.conformance.test.ts
      • packages/ai-persistence-drizzle/tests/migration-cli.test.ts
      • packages/ai-persistence-drizzle/tests/migrations.test.ts
      • packages/ai-persistence-drizzle/tests/package-contract.test.ts
      • packages/ai-persistence-drizzle/tests/schema-cli.test.ts
      • packages/ai-persistence-drizzle/tests/schema-source.test.ts
      • packages/ai-persistence-drizzle/tests/sqlite.test.ts
      • packages/ai-persistence-drizzle/tests/store-behavior.test.ts
      • packages/ai-persistence-drizzle/tests/variant-schema.ts
      • packages/ai-persistence-drizzle/tsconfig.json
      • packages/ai-persistence-drizzle/vite.config.ts
      • packages/ai-persistence-prisma/.gitignore
      • packages/ai-persistence-prisma/bin/tanstack-ai-prisma-models.mjs
      • packages/ai-persistence-prisma/package.json
      • packages/ai-persistence-prisma/prisma/schema.prisma
      • packages/ai-persistence-prisma/prisma/tanstack-ai.prisma
      • packages/ai-persistence-prisma/src/assets.d.ts
      • packages/ai-persistence-prisma/src/assets/tanstack-ai.prisma
      • packages/ai-persistence-prisma/src/cli.ts
      • packages/ai-persistence-prisma/src/index.ts
      • packages/ai-persistence-prisma/src/model-contract.ts
      • packages/ai-persistence-prisma/src/models-cli.ts
      • packages/ai-persistence-prisma/src/models.ts
      • packages/ai-persistence-prisma/src/stores.ts
      • packages/ai-persistence-prisma/tests/api-types.test-d.ts
      • packages/ai-persistence-prisma/tests/model-mapping.test.ts
      • packages/ai-persistence-prisma/tests/models-cli.test.ts
      • packages/ai-persistence-prisma/tests/models.test.ts
      • packages/ai-persistence-prisma/tests/package-contract.test.ts
      • packages/ai-persistence-prisma/tests/prisma.conformance.test.ts
      • packages/ai-persistence-prisma/tests/store-behavior.test.ts
      • packages/ai-persistence-prisma/tsconfig.json
      • packages/ai-persistence-prisma/vite.config.ts
      • packages/ai-persistence/package.json
      • packages/ai-persistence/src/capabilities.ts
      • packages/ai-persistence/src/index.ts
      • packages/ai-persistence/src/interrupts.ts
      • packages/ai-persistence/src/locks.ts
      • packages/ai-persistence/src/memory.ts
      • packages/ai-persistence/src/middleware.ts
      • packages/ai-persistence/src/testkit/conformance.ts
      • packages/ai-persistence/src/types.ts
      • packages/ai-persistence/tests/capabilities.test.ts
      • packages/ai-persistence/tests/error-abort.test.ts
      • packages/ai-persistence/tests/interrupts.test.ts
      • packages/ai-persistence/tests/memory.conformance.test.ts
      • packages/ai-persistence/tests/memory.test.ts
      • packages/ai-persistence/tests/persistence-composition.test.ts
      • packages/ai-persistence/tests/persistence-fixtures.ts
      • packages/ai-persistence/tests/persistence-types.test-d.ts
      • packages/ai-persistence/tests/persistence-validation.test.ts
      • packages/ai-persistence/tests/state-only.test.ts
      • packages/ai-persistence/tests/with-persistence.test.ts
      • packages/ai-persistence/tsconfig.json
      • packages/ai-persistence/vite.config.ts
      • packages/ai/skills/ai-core/chat-experience/SKILL.md
      • packages/ai/skills/ai-core/middleware/SKILL.md
      • pnpm-workspace.yaml
      • testing/e2e/src/routeTree.gen.ts
      • testing/e2e/src/routes/api.persistence-durability.ts
      • testing/e2e/src/routes/persistence-durability.tsx
      • testing/e2e/tests/persistence-durability.spec.ts
      @@ -0,0 +1,21 @@
      1+import { expect, test } from '@playwright/test'
      2+import { sendMessage, waitForResponse } from './helpers'
      3+import type { Page } from '@playwright/test'
      4+
      5+/**
      6+ * Client browser-refresh durability (persistence layer).
      7+ *
      8+ * Proves the story wired by `localStoragePersistence` + `useChat({ persistence,
      9+ * id, threadId })`: a single combined `{ messages, resume }` record per chat id
      10+ * survives a full `page.reload()`, so the conversation — and any pending
      11+ * interrupt — is restored from `localStorage` with no server round-trip.
      12+ *
      13+ * Provider-free: the `/api/persistence-durability` harness route streams a fixed
      14+ * AG-UI sequence through a `memoryStream` delivery sink, so there is no LLM in
      15+ * the loop and nothing to mock (exempt from the aimock policy).
      16+ *
      17+ * The mid-stream "rejoin an in-flight run via joinRun after reload" path is NOT
      18+ * covered here: the harness stream completes in a single tick, so there is no
      19+ * deterministic window to reload while a run is still producing. That resume
      20+ * cursor is covered at the transport layer by `delivery-durability.spec.ts` and
      21+ * in `@tanstack/ai-client` unit tests.
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

      Add E2E coverage for useChat rejoining an in-flight run.

      This explicitly excludes the new reload-and-joinRun behavior. Make the fixture pause mid-stream, reload, assert the client issues a resume request, and verify exactly one continuation is rendered. Also block API traffic during the interrupt reload to prove that case is local-storage-only.

      As per coding guidelines, “Every feature, bug fix, or behavior change must include E2E test coverage in testing/e2e/.”

      🤖 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/tests/persistence-durability.spec.ts` around lines 17 - 21,
      Extend the persistence durability E2E fixture to pause deterministically
      mid-stream, reload during the active run, and verify useChat issues a
      resume/joinRun request and renders exactly one continuation. During the
      interrupt reload, block API traffic to prove recovery uses local storage only,
      then restore traffic for the resumed request; update the existing excluded-path
      note and assertions accordingly.

      Source: Coding guidelines

      Acknowledged — mid-stream reload/joinRun is intentionally out of this E2E file (see the header comment in persistence-durability.spec.ts).

      What is covered today:

      • Unit (@tanstack/ai-client): combined { messages, resume } record, async hydrate rejoin, resumeInFlightRun / applyResumeSnapshot, and the explicit-undefined joinRun guard on the connection adapter.
      • E2E: transcript restore after clean finish, and interrupt survival across reload (local resume snapshot + server-authoritative reconstruction).

      A deterministic mid-stream pause + reload harness needs a fixture that freezes the stream mid-token, reloads, asserts the client issues the resume/join request, and checks single continuation — that is real work (aimock fixture + transport coordination) and is tracked as follow-up rather than blocking this PR. The durable-stream e2e (e87998db8) already guards full agent-loop delivery through durability-backed streams; the missing piece is specifically the browser reload while streaming path.

      🧩 Analysis chain

      🏁 Script executed:

      #!/bin/bash
      set -euo pipefail
      
      echo '--- current persistence durability spec header and test names ---'
      sed -n '1,140p' testing/e2e/tests/persistence-durability.spec.ts
      
      echo '--- client unit-test references to in-flight rejoin ---'
      rg -n -C 4 'resumeInFlightRun|joinRun|in-flight|rejoin' packages/ai-client/tests packages/ai-client/src
      
      echo '--- referenced commit metadata and changed paths (if available) ---'
      git show --no-patch --format='%H%n%s%n%b' e87998db8 2>&1 || true
      git diff-tree --no-commit-id --name-status -r e87998db8 2>&1 || true

      Length of output: 99489


      @tombeckenham, verified. The unit suite covers persisted and async rejoin paths, including duplicate-message handling, and e87998db8 covers durable agent-loop delivery plus a second-tab join.

      The missing coverage is specifically the composed browser scenario—page.reload() during an active run—which is not exercised by either suite. Given the focused coverage already present and the fixture work required, I’m okay treating it as non-blocking follow-up rather than requiring it in this PR.

      Would you like me to open a GitHub issue for the deterministic mid-stream reload/rejoin E2E scenario, with the acceptance criteria from the original finding?


      🧠 Learnings used
      Learnt from: season179
      Repo: TanStack/ai PR: 734
      File: testing/e2e/tests/workerd-console-logger.spec.ts:57-100
      Timestamp: 2026-06-10T00:45:26.781Z
      Learning: In `testing/e2e/**/*.spec.ts`, apply the “Playwright + aimock” policy for E2E features/fixes that exercise LLM provider HTTP calls: wire aimock to mock LLM provider responses instead of hitting the provider over the network. Exception: if the E2E spec only tests runtime/infrastructure behavior (e.g., rendering/logging inside real `workerd` via Miniflare) and the code path under test never reaches the provider HTTP layer, do not add aimock wiring. For these exempt specs, document the policy exception in the spec’s header comment (i.e., explain why the test does not reach the LLM provider HTTP layer).
    6. tombeckenham assignedjherr

    7. tombeckenham added labelswaiting-on: author

    8. Actionable comments posted: 2

      Caution

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

      ⚠️ Outside diff range comments (3)
      packages/ai/skills/ai-core/chat-experience/SKILL.md (2)

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

      Fix the malformed import guidance sentence.

      “the one exception to mistake j below” is unclear and appears to contain an accidental edit. Replace it with the intended wording before publishing the skill.

      🤖 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/chat-experience/SKILL.md` around lines 507 - 508,
      Correct the import guidance sentence in the skill documentation so it clearly
      states that framework packages should be imported from `@tanstack/ai-client`, with
      useChat remaining the exception sourced from the framework package. Remove the
      malformed “mistake j below” wording without changing the surrounding guidance.

      517-520: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

      Use a Date-aware deserializer.

      UIMessage.createdAt is a Date, but this example uses JSON.stringify / JSON.parse, so the timestamp is restored as a string on reload and does not preserve the documented ChatPersistedState shape. Use the repository’s Date-aware codec or a deserializer that reconstructs Date fields.

      🤖 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/chat-experience/SKILL.md` around lines 517 - 520,
      Update the localStoragePersistence configuration around ChatPersistedState to
      use the repository’s Date-aware serialization/deserialization codec, or
      reconstruct Date fields during deserialize, so UIMessage.createdAt is restored
      as a Date while preserving the existing persisted state shape.
      docs/persistence/browser-refresh.md (1)

      28-30: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

      Make the localStorage codec Date-aware.

      UIMessage.createdAt is typed as Date, so JSON.stringify stores it as a string and JSON.parse returns that string instead of a Date; the useChat transcript is then restored with mutated timestamps. Use a Date-aware validated codec here, or switch this sample to indexedDBPersistence since it already supports structured cloning.

      🤖 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/browser-refresh.md` around lines 28 - 30, Update the
      localStoragePersistence codec for ChatPersistedState so UIMessage.createdAt
      values are restored as Date instances rather than strings; use an existing
      Date-aware validated codec, or replace localStoragePersistence with
      indexedDBPersistence to preserve structured-cloned dates.
      🤖 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/browser-refresh.md`:
      - Around line 99-102: Expand the server-authoritative reload example around the
      router-loader discussion to include a concrete server endpoint that derives and
      authorizes the thread ID, calls
      persistence.stores.messages.loadThread(threadId), and returns the messages. Add
      the corresponding client-side consumption showing how the endpoint response
      seeds initialMessages, while preserving the distinction from the delivery replay
      endpoint.
      
      In `@examples/ts-react-chat/src/routes/api.persistent-chat.ts`:
      - Around line 78-80: Update the history-loading branch around loadThread so it
      does not trust the caller-controlled threadId query parameter. Derive the thread
      identity from the authenticated session and authorize it for the current tenant
      before calling persistence.stores.messages.loadThread, preserving the existing
      JSON response only for authorized sessions.
      
      ---
      
      Outside diff comments:
      In `@docs/persistence/browser-refresh.md`:
      - Around line 28-30: Update the localStoragePersistence codec for
      ChatPersistedState so UIMessage.createdAt values are restored as Date instances
      rather than strings; use an existing Date-aware validated codec, or replace
      localStoragePersistence with indexedDBPersistence to preserve structured-cloned
      dates.
      
      In `@packages/ai/skills/ai-core/chat-experience/SKILL.md`:
      - Around line 507-508: Correct the import guidance sentence in the skill
      documentation so it clearly states that framework packages should be imported
      from `@tanstack/ai-client`, with useChat remaining the exception sourced from the
      framework package. Remove the malformed “mistake j below” wording without
      changing the surrounding guidance.
      - Around line 517-520: Update the localStoragePersistence configuration around
      ChatPersistedState to use the repository’s Date-aware
      serialization/deserialization codec, or reconstruct Date fields during
      deserialize, so UIMessage.createdAt is restored as a Date while preserving the
      existing persisted state shape.
      🪄 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: 177c8b89-cf85-45bd-9516-9a7d3ad5c65e

      📥 Commits

      Reviewing files that changed from the base of the PR and between b443a9f6e20b679282ad484e01253137efcb5ed6 and 89932a87b8ff2abc09d1647b06d662db15a3418f.

      📒 Files selected for processing (13)
      • .changeset/client-browser-refresh-durability.md
      • docs/chat/persistence.md
      • docs/config.json
      • docs/persistence/browser-refresh.md
      • docs/persistence/controls.md
      • examples/ts-react-chat/src/routes/api.persistent-chat.ts
      • examples/ts-react-chat/src/routes/persistent-chat.tsx
      • packages/ai-client/src/chat-client.ts
      • packages/ai-client/src/client-persistor.ts
      • packages/ai-client/src/index.ts
      • packages/ai-client/src/types.ts
      • packages/ai-client/tests/resume-snapshot.test.ts
      • packages/ai/skills/ai-core/chat-experience/SKILL.md
      🚧 Files skipped from review as they are similar to previous changes (10)
      • .changeset/client-browser-refresh-durability.md
      • docs/config.json
      • packages/ai-client/src/index.ts
      • docs/persistence/controls.md
      • packages/ai-client/tests/resume-snapshot.test.ts
      • docs/chat/persistence.md
      • packages/ai-client/src/types.ts
      • examples/ts-react-chat/src/routes/persistent-chat.tsx
      • packages/ai-client/src/chat-client.ts
      • packages/ai-client/src/client-persistor.ts
    9. Actionable comments posted: 3

      🤖 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/overview.md`:
      - Line 40: Update the Client row in the persistence options table to mention
      sessionStorage alongside localStorage and IndexedDB, preserving the existing
      description and formatting.
      - Line 32: Update the persistence-layer comparison around the sentence stating
      that the layers share “no code.” Replace it with wording that preserves their
      separate responsibilities while acknowledging the integration contract between
      client-persisted resume/runId metadata and delivery-durable run rejoining.
      - Around line 81-84: Update the localStoragePersistence example’s deserialize
      callback to validate and narrow the JSON.parse result to ChatPersistedState
      before returning it, using the project’s established Standard Schema parser or
      type guard rather than trusting the parsed value directly; preserve the existing
      serialization behavior.
      🪄 Autofix (Beta)

      Fix all unresolved CodeRabbit comments on this PR:

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

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 4bab97e0-76be-49ac-b3f5-d16b75985bdd

      📥 Commits

      Reviewing files that changed from the base of the PR and between 89932a87b8ff2abc09d1647b06d662db15a3418f and e8aef353438967dd354a3fff3242c333307b3b2b.

      📒 Files selected for processing (3)
      • docs/config.json
      • docs/persistence/overview.md
      • docs/resumable-streams/overview.md
    10. Actionable comments posted: 5

      Caution

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

      ⚠️ Outside diff range comments (2)
      packages/ai/skills/ai-core/chat-experience/SKILL.md (1)

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

      Use threadId consistently as the persistence key.

      This section alternates between chat id, threadId, and stable id. Align the prose and framework example on threadId, and document id only as the explicit storage-key override if that is the intended API; otherwise users may fail to restore records after reload.

      Also applies to: 548-551

      🤖 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/chat-experience/SKILL.md` around lines 495 - 506,
      Update the persistence documentation and framework example to use threadId
      consistently as the stable persistence key. Remove ambiguous references to chat
      id or stable id, and document id only if it is the explicit storage-key override
      supported by the API; otherwise ensure the example passes threadId so reloads
      restore the same record.
      packages/ai-client/src/storage-adapters.ts (1)

      149-160: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

      Handle existing IndexedDB databases whose configured object store is missing.

      factory.open(databaseName) without a version only raises onupgradeneeded for a new database; an existing database opened at its current version will create no object store in this branch. If objectStoreName was changed later, runRequest() will open a transaction for a non-existent store and start failing. Add a schema/version migration path, or clear/reject before caching the connection.

      🤖 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/storage-adapters.ts` around lines 149 - 160, The
      IndexedDB open flow does not migrate existing databases when the configured
      object store is missing. Update the database-opening logic around factory.open
      and request.onupgradeneeded to detect absent objectStoreName stores and trigger
      a versioned schema upgrade that creates the store before caching or using the
      connection; otherwise reject and avoid caching an unusable connection.
      🤖 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/overview.md`:
      - Around line 216-218: The “A cheap client” bullet incorrectly claims the
      browser never parses or stores the transcript. Update that bullet to state that
      the browser does not persist the long transcript in browser storage, while
      preserving the existing claims about avoiding localStorage quota and
      startup-persistence costs.
      - Around line 85-87: Update the persistence examples in the affected sections to
      derive thread IDs from the authenticated user rather than using the shared
      literal support-chat or caller-controlled params.threadId. Ensure both POST and
      GET history flows authorize the requested thread ID against the authenticated
      user before persisting, reading, or reconstructing conversation history.
      
      In `@packages/ai-persistence/src/reconstruct.ts`:
      - Around line 18-35: The reconstructChat function must enforce authorization or
      tenant scoping before calling persistence.stores.messages.loadThread(threadId).
      Add a mandatory authorization/scoping contract, such as an auth callback or
      caller-provided validated thread ID, and ensure unauthorized or out-of-scope
      requests return without loading or exposing the transcript.
      - Around line 31-35: The reconstructChat hydration response currently returns
      stored ModelMessage values instead of the UIMessage contract. Update the
      messages flow around persistence.stores.messages.loadThread and the returned
      Response to convert loaded model messages with the existing
      modelMessagesToUIMessages or equivalent typed converter, and declare the
      response as the supported ChatPersistedState<{ messages: Array<UIMessage> }> or
      Array<UIMessage> contract while preserving the empty-message behavior.
      - Around line 35-37: Update the Response construction in reconstruct.ts to
      include a no-store cache-control header alongside the existing content-type
      header, ensuring transcript responses are not cached or reused while preserving
      the serialized messages payload.
      
      ---
      
      Outside diff comments:
      In `@packages/ai-client/src/storage-adapters.ts`:
      - Around line 149-160: The IndexedDB open flow does not migrate existing
      databases when the configured object store is missing. Update the
      database-opening logic around factory.open and request.onupgradeneeded to detect
      absent objectStoreName stores and trigger a versioned schema upgrade that
      creates the store before caching or using the connection; otherwise reject and
      avoid caching an unusable connection.
      
      In `@packages/ai/skills/ai-core/chat-experience/SKILL.md`:
      - Around line 495-506: Update the persistence documentation and framework
      example to use threadId consistently as the stable persistence key. Remove
      ambiguous references to chat id or stable id, and document id only if it is the
      explicit storage-key override supported by the API; otherwise ensure the example
      passes threadId so reloads restore the same record.
      🪄 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: 4f79e751-1747-4eb2-942c-33aacb3c8bcb

      📥 Commits

      Reviewing files that changed from the base of the PR and between e8aef353438967dd354a3fff3242c333307b3b2b and e5c4064c076b51ccd71f133f058948772e49981a.

      📒 Files selected for processing (22)
      • .changeset/client-browser-refresh-durability.md
      • .changeset/persistence-packages.md
      • docs/chat/persistence.md
      • docs/persistence/browser-refresh.md
      • docs/persistence/overview.md
      • examples/ts-react-chat/src/routes/api.persistent-chat.ts
      • examples/ts-react-chat/src/routes/persistent-chat.tsx
      • packages/ai-angular/src/index.ts
      • packages/ai-client/src/chat-client.ts
      • packages/ai-client/src/index.ts
      • packages/ai-client/src/storage-adapters.ts
      • packages/ai-client/src/types.ts
      • packages/ai-client/tests/resume-snapshot.test.ts
      • packages/ai-persistence/src/index.ts
      • packages/ai-persistence/src/reconstruct.ts
      • packages/ai-preact/src/index.ts
      • packages/ai-react/src/index.ts
      • packages/ai-solid/src/index.ts
      • packages/ai-svelte/src/index.ts
      • packages/ai-vue/src/index.ts
      • packages/ai/skills/ai-core/chat-experience/SKILL.md
      • testing/e2e/src/routes/persistence-durability.tsx
      💤 Files with no reviewable changes (1)
      • packages/ai-client/src/index.ts
      🚧 Files skipped from review as they are similar to previous changes (10)
      • packages/ai-persistence/src/index.ts
      • .changeset/persistence-packages.md
      • .changeset/client-browser-refresh-durability.md
      • examples/ts-react-chat/src/routes/persistent-chat.tsx
      • packages/ai-client/tests/resume-snapshot.test.ts
      • docs/persistence/browser-refresh.md
      • docs/chat/persistence.md
      • testing/e2e/src/routes/persistence-durability.tsx
      • packages/ai-client/src/types.ts
      • packages/ai-client/src/chat-client.ts
    11. Actionable comments posted: 2

      🤖 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/client-persistence.md`:
      - Around line 75-77: The documentation section describing server-authoritative
      persistence needs a concrete server example. Add a minimal GET endpoint snippet
      using reconstructChat(persistence, request), positioned alongside the existing
      client usage and aligned with the documented loader flow; keep the example
      focused on returning the reconstructed transcript.
      - Around line 41-50: Update the “Repaints the transcript” documentation in the
      client persistence overview to describe initialization-time hydration rather
      than hydration before the first render. Explicitly distinguish synchronous Web
      Storage, which may hydrate immediately, from asynchronous lazily opened
      IndexedDB, whose transcript and resume snapshot apply only after hydration
      resolves; keep the pending-interrupt and in-flight-run behavior unchanged.
      🪄 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: 11e079f7-59fc-4078-984b-71126e311805

      📥 Commits

      Reviewing files that changed from the base of the PR and between e5c4064c076b51ccd71f133f058948772e49981a and 8f408cb847a66e560a18a7bc5edc4124882aa2aa.

      📒 Files selected for processing (11)
      • docs/chat/persistence.md
      • docs/config.json
      • docs/persistence/chat-persistence.md
      • docs/persistence/client-persistence.md
      • docs/persistence/controls.md
      • docs/persistence/internals.md
      • docs/persistence/overview.md
      • docs/resumable-streams/advanced.md
      • packages/ai-persistence/src/reconstruct.ts
      • packages/ai/skills/ai-core/chat-experience/SKILL.md
      • packages/ai/skills/ai-core/middleware/SKILL.md
      💤 Files with no reviewable changes (1)
      • docs/chat/persistence.md
      🚧 Files skipped from review as they are similar to previous changes (5)
      • docs/persistence/chat-persistence.md
      • packages/ai-persistence/src/reconstruct.ts
      • docs/persistence/overview.md
      • docs/persistence/controls.md
      • docs/config.json
    12. jherr reviewed

      @@ -0,0 +141,21 @@
      141+For durable infrastructure, preserve the same semantics with database
      142+transactions, conditional writes, or stable idempotency keys.
      143+
      144+## Override selected packaged stores
      145+
      146+```ts ignore
      147+import { composePersistence } from '@tanstack/ai-persistence'
      148+import { cloudflarePersistence } from '@tanstack/ai-persistence-cloudflare'
      149+import { interrupts, runs } from './stores'
      150+
      151+export function createPersistence(state: D1Database) {
      152+ const base = cloudflarePersistence({ d1: state })
      153+ return composePersistence(base, {
      154+ overrides: { interrupts, runs },
      155+ })
      156+}
      157+```
      158+
      159+Only those two stores move to the custom database; D1 still owns messages and
      160+metadata. Composition does not create a transaction across those systems;
      161+design related writes accordingly.

      It would be good to have specifics for each of the events that trigger persistence and what the flow is through the persistence store at that point. (e.g. this is when/how we load the thread, this is when/how we store messages, this is what happens when there is an interrupt, etc.) Maybe as swim lanes.

      Basically I don't think folks are going to have a different store for chats. They are going to want to integrate it in with the rest of the customer data. So we should invest pretty heavily in this doc.

      Agreed — most apps fold chat into the existing customer DB rather than standing up a separate store.

      That is now spelled out in docs/persistence/custom-stores.md under When each store is called:

      1. Chat middleware lifecycle table — which store methods fire on onConfig / onStart / stream onChunk / interrupt boundary / onFinish / onError / onAbort, and hard-fail vs best-effort.
      2. Swimlanes (request → store) — ASCII flow from client POST through load/createOrResume/listPending → saveThread/update/commit.
      3. Invariants — full-overwrite saveThread, idempotent createOrResume, insert-if-absent interrupts, authorize-at-boundary, locks via withLocks not the state bag.

      If anything is still thin for the integrate-with-my-tables path (e.g. mapping each method onto a concrete threads/messages/approvals schema, or transaction boundaries across stores), say which event you want expanded and we can add a worked example in a follow-up.

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

      Open in StackBlitz

      @tanstack/ai

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

      @tanstack/ai-acp

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

      @tanstack/ai-angular

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

      @tanstack/ai-anthropic

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

      @tanstack/ai-bedrock

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

      @tanstack/ai-claude-code

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

      @tanstack/ai-client

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

      @tanstack/ai-code-mode

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

      @tanstack/ai-code-mode-skills

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

      @tanstack/ai-codex

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

      @tanstack/ai-devtools-core

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

      @tanstack/ai-durable-stream

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

      @tanstack/ai-elevenlabs

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

      @tanstack/ai-event-client

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

      @tanstack/ai-fal

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

      @tanstack/ai-gemini

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

      @tanstack/ai-grok

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

      @tanstack/ai-grok-build

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

      @tanstack/ai-groq

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

      @tanstack/ai-isolate-cloudflare

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

      @tanstack/ai-isolate-node

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

      @tanstack/ai-isolate-quickjs

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

      @tanstack/ai-mcp

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

      @tanstack/ai-memory

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

      @tanstack/ai-mistral

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

      @tanstack/ai-ollama

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

      @tanstack/ai-openai

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

      @tanstack/ai-opencode

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

      @tanstack/ai-openrouter

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

      @tanstack/ai-persistence

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

      @tanstack/ai-preact

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

      @tanstack/ai-react

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

      @tanstack/ai-react-ui

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

      @tanstack/ai-sandbox

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

      @tanstack/ai-sandbox-cloudflare

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

      @tanstack/ai-sandbox-daytona

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

      @tanstack/ai-sandbox-docker

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

      @tanstack/ai-sandbox-local-process

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

      @tanstack/ai-sandbox-sprites

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

      @tanstack/ai-sandbox-vercel

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

      @tanstack/ai-solid

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

      @tanstack/ai-solid-ui

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

      @tanstack/ai-svelte

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

      @tanstack/ai-utils

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

      @tanstack/ai-vue

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

      @tanstack/ai-vue-ui

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

      @tanstack/openai-base

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

      @tanstack/preact-ai-devtools

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

      @tanstack/react-ai-devtools

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

      @tanstack/solid-ai-devtools

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

      commit: 043327c

    14. tombeckenham reviewed

      @@ -0,0 +1,8 @@
      1+---
      2+title: Persistence with Drizzle
      3+id: drizzle
      4+---
      5+
      6+# Persistence with Drizzle
      7+
      8+`@tanstack/ai-persistence-drizzle` supports SQLite-family Drizzle databases.
      tombeckenhamcommented

      Drizzle should support every type of database shouldn't it?

      Not every Drizzle dialect is first-class in this package (yet).

      Shipped providers:

      • provider: 'sqlite' — including the Node node:sqlite convenience factory and D1 (via the Cloudflare package, which delegates to the drizzle SQLite path).
      • provider: 'pg' — BYO Postgres Drizzle DB (node-postgres, postgres.js, Neon, etc.) + /pg-schema.

      MySQL / libsql / other Drizzle dialects are not typed or schema-codegen’d here. The runtime needs dialect-specific table definitions and type maps; we intentionally narrowed to the two backends we test and document rather than claiming “any Drizzle DB.” Adding another dialect is mostly schema + provider discriminant + conformance — happy to take MySQL as a follow-up if that is the missing one for you.

    15. tombeckenham reviewed

      @@ -0,0 +220,21 @@
      220+ * CAVEAT: the return type is `unknown | null`, where `| null` collapses into
      221+ * `unknown` — a stored value of `null` is therefore **indistinguishable from
      222+ * absence** at the type level. Callers that must persist a real `null`
      223+ * distinctly from "not set" should wrap it (e.g. store `{ value: null }`).
      224+ */
      225+ get: (namespace: string, key: string) => Promise<unknown | null>
      226+ /** Insert or overwrite the value for `(namespace, key)`. */
      227+ set: (namespace: string, key: string, value: unknown) => Promise<void>
      228+ /**
      229+ * Remove `(namespace, key)`. A no-op if absent. Does not affect other
      230+ * namespaces.
      231+ */
      232+ delete: (namespace: string, key: string) => Promise<void>
      233+}
      234+
      235+export interface AIPersistenceStores {
      236+ messages?: MessageStore
      237+ runs?: RunStore
      238+ interrupts?: InterruptStore
      239+ metadata?: MetadataStore
      240+ locks?: LockStore
      tombeckenhamcommented

      This feels off. Locks is not really chat state. It shoudn't be on this type

      tombeckenhamcommented

      It also feels off that all other fields are optional. Looking further

      Agreed — and this is already landed on the branch (see 43cd409d5 and the current packages/ai-persistence/src/types.ts).

      • AIPersistenceStores / named chat shapes hold only state stores (messages / runs / interrupts / metadata). Locks are not on these types.
      • Locks are a separate capability: LockStore + withLocks(...) / LocksCapability (and the shared core token used by sandbox in the stacked PR).
      • Optional vs required: the sparse bag stays optional for composition, but the named product shapes require what they claim — e.g. ChatTranscriptStores.messages is required, ChatPersistenceStores requires all four state stores. Prefer those named types at call sites over the sparse bag.

      On the “all other fields optional” feel: that was the sparse internal bag; packaged backends return ChatPersistenceStores (all present). Custom apps that only need a transcript use ChatTranscriptStores.

    16. tombeckenham approved these changes

      I'm happy with this now. I've reworked drizzle a bit. I've added skills and I'm happy with the type structure.

    17. tombeckenham added labelspersistence

    18. jherr approved these changes

    19. jherr merged this4ab149f

    20. jherr closed this

Sign in to join this conversation.