feat(persistence): server persistence + client browser-refresh durability #984
- examples/ts-react-chat/src/routes/api.persistent-chat.ts lines 51 to 53OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +33,21 @@33+const persistence = sqlitePersistence({34+ url: './.data/persistent-chat.db',35+ migrate: true,36+})37+38+export const Route = createFileRoute('/api/persistent-chat')({39+ server: {40+ handlers: {41+ POST: async ({ request }) => {42+ const abortController = new AbortController()43+ const params = await chatParamsFromRequestBody(await request.json())44+45+ const stream = chat({46+ adapter: openaiText('gpt-5.5'),47+ // `withChatPersistence` loads the stored transcript when `messages` is48+ // empty and overwrites it (authoritative-history contract) on finish.49+ middleware: [withChatPersistence(persistence)],50+ agentLoopStrategy: maxIterations(10),51+ messages: params.messages,52+ threadId: params.threadId,53+ runId: params.runId,packages/ai-client/src/chat-client.ts lines 491 to 518Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -445 +446,21 @@446+ const syncPersistedState =447+ persistedState instanceof Promise ? undefined : persistedState448+ const initialMessages = syncPersistedState449+ ? syncPersistedState.messages445450 : options.initialMessages451+ // A durable snapshot read synchronously from storage wins over the452+ // in-memory `initialResumeSnapshot` fallback applied above. A snapshot with453+ // pending interrupts rehydrates the interrupt UI; a bare in-flight run is454+ // rejoined after the processor is ready (see `rejoinRunId` below).455+ let rejoinRunId: string | null = null456+ if (syncPersistedState?.resume) {457+ const snapshot = syncPersistedState.resume458+ const hasPendingInterrupts =459+ Array.isArray(snapshot.pendingInterrupts) &&460+ snapshot.pendingInterrupts.length > 0461+ if (hasPendingInterrupts) {462+ this.applyResumeSnapshot(snapshot)463+ } else if (snapshot.resumeState.runId) {464+ rejoinRunId = snapshot.resumeState.runId465+ }466+ }packages/ai-client/src/connection-adapters.ts lines 875 to 885OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -858,3 +872,14 @@858872 throw err859873 }860874 },875+ // Expose joinRun only when the underlying connection is resumable. Returns876+ // the replay iterable directly; the client consumes it like a subscription.877+ ...('joinRun' in connection878+ ? {879+ joinRun: (runId: string, abortSignal?: AbortSignal) =>880+ (connection as ResumableConnectConnectionAdapter).joinRun(881+ runId,882+ abortSignal,883+ ),884+ }885+ : {}),packages/ai-persistence-drizzle/package.json lines 55 to 56OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +36,21 @@36+ "files": [37+ "bin",38+ "dist",39+ "src",40+ "drizzle",41+ "drizzle.config.ts"42+ ],43+ "scripts": {44+ "build": "vite build",45+ "clean": "premove ./build ./dist",46+ "db:generate": "drizzle-kit generate",47+ "lint:fix": "oxlint src --type-aware --fix",48+ "test:build": "publint --strict",49+ "test:lib": "vitest",50+ "test:lib:dev": "pnpm test:lib --watch",51+ "test:types": "tsc",52+ "test:oxlint": "oxlint src --type-aware"53+ },54+ "peerDependencies": {55+ "@tanstack/ai": "workspace:^",56+ "@tanstack/ai-persistence": "workspace:^",packages/ai-persistence-drizzle/src/sqlite.ts lines 20 to 30OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +10,21 @@10+11+export { SqliteMigrationError } from './sqlite-migrations'12+13+export interface SqlitePersistenceOptions {14+ /** `:memory:`, a filesystem path, or a `file:`-prefixed filesystem path. */15+ url: string16+ /** Apply the bundled TanStack AI migrations before creating stores. */17+ migrate?: boolean18+}19+20+/** Build persistence over Node's built-in SQLite driver. */21+export function sqlitePersistence(options: SqlitePersistenceOptions) {22+ const filename = normalizeSqliteUrl(options.url)23+ ensureParentDirectory(filename)24+ const sqlite = new DatabaseSync(filename)25+ try {26+ if (options.migrate) applySqliteMigrations(sqlite, sqliteMigrations)27+ } catch (error) {28+ sqlite.close()29+ throw error30+ }packages/ai-persistence-drizzle/tests/custom-schema.test.ts lines 1 to 113OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +93,21 @@93+ }),94+ ).toThrow(DrizzleSchemaError)95+ expect(() =>96+ drizzlePersistence(db, {97+ schema: withoutMetadata as unknown as TanstackAiSqliteSchema,98+ }),99+ ).toThrow(/`metadata` is not a Drizzle SQLite table/)100+101+ const incompleteMessages = sqliteTable('messages', {102+ threadId: text('thread_id').primaryKey(),103+ })104+ expect(() =>105+ drizzlePersistence(db, {106+ schema: {107+ ...schema,108+ messages: incompleteMessages,109+ } as unknown as TanstackAiSqliteSchema,110+ }),111+ ).toThrow(/`messages\.messagesJson` is missing/)112+ })113+})packages/ai-persistence-drizzle/tests/migration-cli.test.ts lines 1 to 6OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,6 @@1+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'2+import { tmpdir } from 'node:os'3+import { join } from 'node:path'4+import { afterEach, describe, expect, it } from 'vitest'5+import { sqliteMigrations } from '../src/migrations'6+import { runDrizzleMigrationsCli } from '../src/migration-cli'packages/ai-persistence-drizzle/tests/schema-source.test.ts lines 1 to 31OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +11,21 @@11+ columns: config.columns.map((column) => ({12+ name: column.name,13+ sqlType: column.getSQLType(),14+ notNull: column.notNull,15+ primary: column.primary,16+ })),17+ primaryKeys: config.primaryKeys.map((primaryKey) =>18+ primaryKey.columns.map((column) => column.name),19+ ),20+ }21+}22+23+describe('emitted schema asset', () => {24+ it('is structurally identical to the bundled schema', () => {25+ const tableKeys = Object.keys(bundled) as Array<keyof typeof bundled>26+ expect(Object.keys(emitted)).toEqual(Object.keys(bundled))27+ for (const key of tableKeys) {28+ expect(normalize(emitted[key]), key).toEqual(normalize(bundled[key]))29+ }30+ })31+})packages/ai-persistence-prisma/src/index.ts lines 44 to 48OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +28,21 @@28+ * Keep the field names and types from the fragment; database table and29+ * column names are already yours via `@@map` / `@map`.30+ */31+ models?: PrismaModelMap32+}33+34+/**35+ * Wire TanStack AI persistence stores over a migrated Prisma client.36+ *37+ * No `locks` store is returned: this backend has no distributed lock primitive,38+ * and bundling an `InMemoryLockStore` would silently hand multi-instance39+ * deployments a lock that does not lock across instances. Consumers that need a40+ * lock (e.g. `withSandbox`) transparently fall back to an in-process41+ * `InMemoryLockStore`; for cross-instance locking use a distributed backend such42+ * as the Cloudflare Durable Object lock (`@tanstack/ai-persistence-cloudflare`).43+ */44+export function prismaPersistence(45+ prisma: PrismaClient,46+ options?: PrismaPersistenceOptions,47+) {48+ const delegates = resolveDelegates(prisma, options?.models)packages/ai-persistence-prisma/vite.config.ts line 12OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,13 @@1+import { defineConfig, mergeConfig } from 'vitest/config'2+import { tanstackViteConfig } from '@tanstack/vite-config'3+import packageJson from './package.json'4+5+const config = defineConfig({6+ test: {7+ name: packageJson.name,8+ dir: './',9+ watch: false,10+11+ globals: true,12+ environment: 'node',13+ include: ['tests/**/*.test.ts'],packages/ai-persistence/src/locks.ts lines 46 to 57OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +37,21 @@37+ * process; multi-instance correctness needs a distributed lock from the backend.38+ */39+export class InMemoryLockStore implements LockStore {40+ private readonly chains = new Map<string, Promise<unknown>>()41+42+ withLock<T>(43+ key: string,44+ fn: (signal: AbortSignal) => Promise<T>,45+ ): Promise<T> {46+ const prior = this.chains.get(key) ?? Promise.resolve()47+ const runCriticalSection = () => fn(new AbortController().signal)48+ // Chain after the prior holder regardless of how it settled.49+ const run = prior.then(runCriticalSection, runCriticalSection)50+ // Keep the chain alive but swallow rejections so one failure doesn't poison the lock.51+ this.chains.set(52+ key,53+ run.then(54+ () => undefined,55+ () => undefined,56+ ),57+ )packages/ai-persistence/src/memory.ts lines 107 to 140Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +107,21 @@107+ [...this.interrupts.values()].filter(108+ (interrupt) =>109+ interrupt.threadId === threadId && interrupt.status === 'pending',110+ ),111+ )112+ }113+ listByRun(runId: string): Promise<Array<InterruptRecord>> {114+ return Promise.resolve(115+ [...this.interrupts.values()].filter(116+ (interrupt) => interrupt.runId === runId,117+ ),118+ )119+ }120+ listPendingByRun(runId: string): Promise<Array<InterruptRecord>> {121+ return Promise.resolve(122+ [...this.interrupts.values()].filter(123+ (interrupt) =>124+ interrupt.runId === runId && interrupt.status === 'pending',125+ ),126+ )127+ }packages/ai-persistence/src/memory.ts lines 131 to 143OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +123,21 @@123+ (interrupt) =>124+ interrupt.runId === runId && interrupt.status === 'pending',125+ ),126+ )127+ }128+}129+130+class MemoryMetadataStore implements MetadataStore {131+ private readonly values = new Map<string, unknown>()132+ get(scope: string, key: string): Promise<unknown | null> {133+ const storageKey = `${scope}:${key}`134+ return Promise.resolve(135+ this.values.has(storageKey) ? this.values.get(storageKey) : null,136+ )137+ }138+ set(scope: string, key: string, value: unknown): Promise<void> {139+ this.values.set(`${scope}:${key}`, value)140+ return Promise.resolve()141+ }142+ delete(scope: string, key: string): Promise<void> {143+ this.values.delete(`${scope}:${key}`)@@ -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 id10+ * survives a full `page.reload()`, so the conversation — and any pending11+ * interrupt — is restored from `localStorage` with no server round-trip.12+ *13+ * Provider-free: the `/api/persistence-durability` harness route streams a fixed14+ * AG-UI sequence through a `memoryStream` delivery sink, so there is no LLM in15+ * 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 NOT18+ * covered here: the harness stream completes in a single tick, so there is no19+ * deterministic window to reload while a run is still producing. That resume20+ * cursor is covered at the transport layer by `delivery-durability.spec.ts` and21+ * in `@tanstack/ai-client` unit tests.
tombeckenham assignedjherr
tombeckenham added labelswaiting-on: author
- docs/persistence/browser-refresh.md lines 99 to 102OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +82,21 @@82+ deserialize: (value) => JSON.parse(value),83+})84+85+function Chat() {86+ const { messages, sendMessage } = useChat({87+ id: 'support-chat',88+ connection: fetchServerSentEvents('/api/chat'),89+ // Only the tiny resume pointer is cached; the transcript is NOT.90+ persistence: { store, messages: false },91+ })92+ // ...93+}94+```95+96+Now only the resume pointer (which run to rejoin, which interrupts are pending)97+is cached. Durability rejoin and interrupt restore still work, but the transcript98+lives on the server, which is authoritative. On reload the client starts empty,99+so hydrate the history from the server, for example a router loader that reads a100+`GET /thread/:id` endpoint backed by `persistence.stores.messages.loadThread(id)`101+and seeds `initialMessages`. The delivery replay endpoint cannot supply this: its102+log holds one run, not the thread.examples/ts-react-chat/src/routes/api.persistent-chat.ts lines 78 to 80OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +60,21 @@60+ })61+ },62+63+ // GET serves two independent jobs off one route:64+ //65+ // 1. Delivery replay (`?offset=-1&runId=…`) — re-attach to an in-flight66+ // run by id off the ephemeral, per-run durability log. Read-only.67+ // 2. History hydration (`?threadId=…`) — read the DURABLE thread transcript68+ // from the persistence store. This is what a server-authoritative69+ // client (persistence `{ messages: false }`) fetches on reload, since70+ // the delivery log only holds one run, never prior turns.71+ GET: async ({ request }) => {72+ const url = new URL(request.url)73+ if (url.searchParams.has('offset') || url.searchParams.has('runId')) {74+ return resumeServerSentEventsResponse({75+ adapter: memoryStream(request),76+ })77+ }78+ const threadId = url.searchParams.get('threadId') ?? ''79+ const messages = await persistence.stores.messages.loadThread(threadId)80+ return Response.json(messages)
- docs/persistence/overview.md line 52Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +12,21 @@12+client authoritative13+---14+15+# Durability and Persistence16+17+Three things can go wrong with an AI chat, and they have different fixes:18+19+The connection drops mid-answer. The user watched half a reply appear, then the socket died. You don't want to re-run the model and pay for it twice.20+The user reloads the page. The whole conversation is gone, because it only lived in memory.21+The user opens the app on another device, or your server restarts. There is no record of the conversation anywhere durable.22+23+TanStack AI solves these with two independent layers. You can use either alone or both together.24+25+## The two layers26+27+| Layer | Answers | Lives | Docs |28+| --- | --- | --- | --- |29+| **Delivery durability** | "how do I reconnect to a stream that's still running?" | a per-run log, keyed by `runId` | [Resumable Streams](../resumable-streams/overview) |30+| **State persistence** | "what is the conversation, and is it still there later?" | a durable store (client and/or server) | this section |31+32+They share no code and solve different problems. Delivery durability replays a live byte stream so a dropped connection resumes exactly where it stopped. State persistence stores the conversation itself, so it survives a reload or exists on another device. A replayable stream is not a saved conversation, and a saved conversation is not a live stream. Real apps usually want both.docs/persistence/overview.md line 40OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +20,21 @@20+The user reloads the page. The whole conversation is gone, because it only lived in memory.21+The user opens the app on another device, or your server restarts. There is no record of the conversation anywhere durable.22+23+TanStack AI solves these with two independent layers. You can use either alone or both together.24+25+## The two layers26+27+| Layer | Answers | Lives | Docs |28+| --- | --- | --- | --- |29+| **Delivery durability** | "how do I reconnect to a stream that's still running?" | a per-run log, keyed by `runId` | [Resumable Streams](../resumable-streams/overview) |30+| **State persistence** | "what is the conversation, and is it still there later?" | a durable store (client and/or server) | this section |31+32+They share no code and solve different problems. Delivery durability replays a live byte stream so a dropped connection resumes exactly where it stopped. State persistence stores the conversation itself, so it survives a reload or exists on another device. A replayable stream is not a saved conversation, and a saved conversation is not a live stream. Real apps usually want both.33+34+## State persistence has two halves35+36+Persistence runs on the client, the server, or both. They are independent, and they answer different questions.37+38+| Half | Stores | Survives | Use it for |39+| --- | --- | --- | --- |40+| **Client** ([Browser refresh](./browser-refresh)) | the transcript + a resume pointer, in `localStorage` / `IndexedDB` | a page reload in that browser | instant restore on reload, SPA / offline apps |docs/persistence/overview.md lines 81 to 84OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +64,21 @@64+ messages: params.messages,65+ threadId: params.threadId,66+ runId: params.runId,67+ ...(params.resume ? { resume: params.resume } : {}),68+ middleware: [withChatPersistence(persistence)],69+ })70+ return toServerSentEventsResponse(stream)71+}72+```73+74+The minimal client setup adds one option to `useChat`:75+76+```tsx77+import { fetchServerSentEvents, localStoragePersistence } from '@tanstack/ai-client'78+import { useChat } from '@tanstack/ai-react'79+import type { ChatPersistedState } from '@tanstack/ai-client'80+81+const store = localStoragePersistence<ChatPersistedState>({82+ serialize: (value) => JSON.stringify(value),83+ deserialize: (value) => JSON.parse(value),84+})
- docs/persistence/overview.md lines 85 to 87OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +67,21 @@67+ ...(params.resume ? { resume: params.resume } : {}),68+ middleware: [withChatPersistence(persistence)],69+ })70+ return toServerSentEventsResponse(stream)71+}72+```73+74+The minimal client setup adds one option to `useChat`:75+76+```tsx77+import {78+ fetchServerSentEvents,79+ localStoragePersistence,80+ useChat,81+} from '@tanstack/ai-react'82+83+function Chat() {84+ const { messages, sendMessage } = useChat({85+ threadId: 'support-chat',86+ connection: fetchServerSentEvents('/api/chat'),87+ persistence: localStoragePersistence(),docs/persistence/overview.md lines 271 to 273Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +198,21 @@198+199+const store = localStoragePersistence()200+201+function Chat() {202+ const { messages, sendMessage } = useChat({203+ threadId: 'support-chat',204+ connection: fetchServerSentEvents('/api/chat'),205+ persistence: { store, messages: false },206+ })207+ // On mount, fetch GET /api/chat?threadId=support-chat and seed the thread208+ // (a router loader is the natural place). The resume pointer in localStorage209+ // then rejoins any run that was still streaming.210+}211+```212+213+Why this wins over the alternatives:214+215+**One source of truth.** History lives on the server, so there is no client/server copy to drift or reconcile. The same conversation opens on any device and survives a server restart.216+**A cheap client.** The browser never parses or stores a long transcript, so there is no `localStorage` quota or startup-parse cost, even for huge threads.217+**Full reload durability anyway.** The tiny resume pointer is enough to rejoin a mid-stream run and restore pending interrupts instantly, so dropping the transcript costs nothing on reload.218+**No wasted work.** The `GET` reuses the same route as the durable-stream resume, and `loadThread` returns ready-made messages instead of replaying a stream to reconstruct them.packages/ai-persistence/src/reconstruct.ts lines 18 to 35OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +15,21 @@15+ * configured, or the thread is unknown, so the caller never has to special-case16+ * a first load.17+ *18+ * ```ts19+ * export async function GET(request: Request) {20+ * return reconstructChat(persistence, request)21+ * }22+ * ```23+ */24+export async function reconstructChat(25+ persistence: AIPersistence,26+ request: Request,27+ options?: ReconstructChatOptions,28+): Promise<Response> {29+ const param = options?.param ?? 'threadId'30+ const threadId = new URL(request.url).searchParams.get(param) ?? ''31+ const messages =32+ threadId && persistence.stores.messages33+ ? await persistence.stores.messages.loadThread(threadId)34+ : []35+ return new Response(JSON.stringify(messages), {packages/ai-persistence/src/reconstruct.ts lines 31 to 35OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +15,21 @@15+ * configured, or the thread is unknown, so the caller never has to special-case16+ * a first load.17+ *18+ * ```ts19+ * export async function GET(request: Request) {20+ * return reconstructChat(persistence, request)21+ * }22+ * ```23+ */24+export async function reconstructChat(25+ persistence: AIPersistence,26+ request: Request,27+ options?: ReconstructChatOptions,28+): Promise<Response> {29+ const param = options?.param ?? 'threadId'30+ const threadId = new URL(request.url).searchParams.get(param) ?? ''31+ const messages =32+ threadId && persistence.stores.messages33+ ? await persistence.stores.messages.loadThread(threadId)34+ : []35+ return new Response(JSON.stringify(messages), {packages/ai-persistence/src/reconstruct.ts lines 35 to 37OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +17,21 @@17+ *18+ * ```ts19+ * export async function GET(request: Request) {20+ * return reconstructChat(persistence, request)21+ * }22+ * ```23+ */24+export async function reconstructChat(25+ persistence: AIPersistence,26+ request: Request,27+ options?: ReconstructChatOptions,28+): Promise<Response> {29+ const param = options?.param ?? 'threadId'30+ const threadId = new URL(request.url).searchParams.get(param) ?? ''31+ const messages =32+ threadId && persistence.stores.messages33+ ? await persistence.stores.messages.loadThread(threadId)34+ : []35+ return new Response(JSON.stringify(messages), {36+ headers: { 'content-type': 'application/json' },37+ })
- docs/persistence/client-persistence.md lines 51 to 63Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +30,21 @@30+ persistence: localStoragePersistence(),31+ })32+ // ...render messages, call sendMessage(text)33+}34+```35+36+`localStoragePersistence()` needs no type argument and no codec: it defaults to37+the chat record shape and a JSON codec. That is the whole opt-in.38+39+## What a reload restores40+41+The client stores one record per `threadId`, the transcript plus a small resume42+pointer. On the next load `useChat` reads it and:43+44+**Repaints the transcript** before the first render, from storage, no network.45+**Rehydrates a pending interrupt**, so an approval prompt comes back exactly as46+ it was.47+**Rejoins an in-flight run**, if a reply was still streaming when the page48+ reloaded, so it finishes in place instead of freezing half-done. This one needs49+ a durability-backed connection (a route that records the stream and exposes a50+ replay handler); see [Resumable streams](../resumable-streams/overview).docs/persistence/client-persistence.md lines 75 to 77OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +57,21 @@57+### Cache everything (default): client-authoritative58+59+Pass the adapter directly, `persistence: localStoragePersistence()`. The60+transcript and the resume pointer both live in the browser. The client owns the61+history; the server, if any, mirrors it. Best when the browser is the source of62+truth: single-page apps, offline-first, one device, small to moderate63+conversations.64+65+### Resume pointer only: server-authoritative66+67+Pass the object form, `persistence: { store, messages: false }`, where `store`68+is your adapter. Only the tiny resume pointer is cached (which run to rejoin,69+which interrupts are pending). Reload durability still works, but the transcript70+stays off the client and the server owns history. Best when transcripts are71+large (localStorage is synchronous and quota-bound), when the same conversation72+must open on another device, or when you simply do not want message content in73+the browser.74+75+The transcript is not in storage, so hydrate it from the server on load: expose a76+`GET` endpoint with `reconstructChat(persistence, request)` and read it from a77+router loader to seed `initialMessages`. See [Chat persistence](./chat-persistence).
jherr reviewed
@@ -0,0 +141,21 @@141+For durable infrastructure, preserve the same semantics with database142+transactions, conditional writes, or stable idempotency keys.143+144+## Override selected packaged stores145+146+```ts ignore147+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 and160+metadata. Composition does not create a transaction across those systems;161+design related writes accordingly.tombeckenham reviewed
@@ -0,0 +1,8 @@1+---2+title: Persistence with Drizzle3+id: drizzle4+---5+6+# Persistence with Drizzle7+8+`@tanstack/ai-persistence-drizzle` supports SQLite-family Drizzle databases.tombeckenham reviewed
@@ -0,0 +220,21 @@220+ * CAVEAT: the return type is `unknown | null`, where `| null` collapses into221+ * `unknown` — a stored value of `null` is therefore **indistinguishable from222+ * 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 other230+ * namespaces.231+ */232+ delete: (namespace: string, key: string) => Promise<void>233+}234+235+export interface AIPersistenceStores {236+ messages?: MessageStore237+ runs?: RunStore238+ interrupts?: InterruptStore239+ metadata?: MetadataStore240+ locks?: LockStoretombeckenham approved these changes
tombeckenham added labelspersistence
jherr approved these changes
jherr merged this4ab149f
jherr closed this
Sign in to join this conversation.
Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
📝 Walkthrough
Walkthrough#
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
packages/ai-client/*joinRunreattachment.packages/ai-persistence/*packages/ai-persistence-drizzle/*,packages/ai-persistence-prisma/*,packages/ai-persistence-cloudflare/*examples/ts-react-chat/*,testing/e2e/*docs/persistence/*,packages/ai-*/src/index.ts,.changeset/*Estimated code review effort: 5 (Critical) | ~120 minutes
Possibly related PRs
Sequence Diagram(s)#
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share