In a Cloudflare AIChatAgent support chat, how does a half-streamed reply survive the customer's tab reconnecting, and a deploy evicting the agent mid-stream?
answer
- messages and chunks in SQLite
- client drop versus server eviction
- buffered chunks replayed on reconnect
- fiber row, onChatRecovery()
- continueLastTurn() appends
basics
~20 sAIChatAgent buffers stream chunks in SQLite, so a reconnecting tab replays them and continues live. An eviction kills the model connection; on restart durable recovery rebuilds the partial reply and, by default, continues it with continueLastTurn().
solid answer
~40 s`AIChatAgent` from `@cloudflare/ai-chat` persists every message and buffers each stream chunk in the agent's SQLite. If the tab drops, the server keeps streaming; `useAgentChat()` reconnects (`resume` defaults to `true`), receives the buffered chunks and carries on with the live stream, and a browser-side abort does not cancel the server turn unless `stop()` is called. A deploy that evicts the agent is different: the model connection is gone, so there is nothing to resume. Each turn runs in a durable fiber whose row survives; on the next activation the SDK rebuilds the partial reply and calls `onChatRecovery()`, whose default persists the partial and continues it with `continueLastTurn()`. Bound it with `chatRecovery` budgets, and return `{ continue: false }` when a repeat model call or tool could cause harm.
code
typescript · 19 linesimport { AIChatAgent, type ChatRecoveryContext, type ChatRecoveryOptions } from "@cloudflare/ai-chat";
export class SupportChat extends AIChatAgent {
maxPersistedMessages = 500; // storage cap only, not model context
override chatRecovery = {
maxAttempts: 10,
noProgressTimeoutMs: 5 * 60 * 1000,
terminalMessage: "The assistant was interrupted. Please send your message again.",
};
override async onChatRecovery(ctx: ChatRecoveryContext): Promise<ChatRecoveryOptions> {
// A reply interrupted more than two minutes ago is not worth continuing.
if (Date.now() - ctx.createdAt > 2 * 60 * 1000) {
return { continue: false };
}
return {}; // persist the partial reply and continue it
}
}go deeper
Recall that AIChatAgent stores messages in the agent's SQLite and that useAgentChat() reconnects and resumes a stream on its own.
Explain how chunks are buffered as they stream, how a reconnect replays them, and why maxPersistedMessages limits storage but not model context.
Separate a client drop from a server eviction, and walk through the fiber row, onChatRecovery() and continueLastTurn(), including when to return continue: false.
Set the recovery budget and the continue-or-stop policy as a cost and safety decision, since each recovery is another paid model call and may repeat tool side effects.
## Where a chat agent's memory lives `AIChatAgent` comes from the separate **`@cloudflare/ai-chat`** package and extends `Agent`. The full chain is `DurableObject` > `Server` > `Agent` > `AIChatAgent`. You override `onChatMessage()` and return a streaming `Response`, usually from the AI SDK's `streamText(...).toUIMessageStreamResponse()`; the browser side is `useAgentChat({ agent })` from `@cloudflare/ai-chat/react`, on top of `useAgent()`. Its memory is the agent's own SQLite database: - **Messages**: every user and assistant message is persisted, and `this.messages` loads the conversation from SQLite. That is why the class needs SQLite storage in the Wrangler file. - **Stream chunks**: while a reply streams, each chunk is **buffered in SQLite** as well as sent to the client. - **Recovery rows**: each chat turn runs inside a durable **fiber** (`runFiber()`), whose row also lives in SQLite. Nothing that matters lives only in memory. That is the whole answer to "how does it resume": whatever woke the agent, it reads what it needs back from disk. ## Case 1: the customer's tab drops A dropped tab is a **client** problem. The agent did not stop: 1. The server keeps streaming from the model and keeps buffering chunks. 2. `useAgent()` reconnects automatically with backoff. 3. On reconnect, `useAgentChat()` (whose `resume` option defaults to `true`) asks for the active stream, receives every buffered chunk and then continues with the live stream. The customer sees the reply catch up where it left off. A generic abort or cleanup in the browser stays local by default, so the server turn keeps running; only an explicit `stop()` cancels it, unless you opt into `cancelOnClientAbort: true`. Other tabs open on the same agent do not get the token stream; they receive the finished message list in a `CF_AGENT_CHAT_MESSAGES` broadcast. ## Case 2: a deploy evicts the agent mid-stream Eviction is a **server** problem, and client resumption cannot fix it: the outbound connection to the model provider died with the isolate, and there is no stream left to resume. Durable Objects are evicted after inactivity, on code updates and runtime restarts, and when an alarm handler runs too long. `AIChatAgent` holds a `keepAlive` heartbeat while streaming, which prevents only the first kind. Durable chat recovery handles the rest. In current releases it is always on: 1. The interrupted fiber's row survives in SQLite. 2. On the next activation the SDK detects it and rebuilds the partial reply from the buffered chunks. 3. It calls **`onChatRecovery(ctx)`**, which receives `partialText`, `partialParts`, `messages`, the original request body and any data you saved with `this.stash()`. 4. The default return value `{}` means **persist the partial reply and continue it** with `continueLastTurn()`, which calls `onChatMessage()` again with the saved body and appends to the same assistant message. If no chunk was written before the eviction, the unanswered user turn is simply retried. `useAgentChat()` exposes `isRecovering` so the UI can show that state. ## Tuning and bounding recovery | Setting | Default | Purpose | | --- | --- | --- | | `chatRecovery.maxAttempts` | `10` | Cap on attempts that make no progress | | `chatRecovery.noProgressTimeoutMs` | `300000` | Seal a turn stuck without progress for five minutes | | `chatRecovery.maxRecoveryWork` | `1000` | Guard against a runaway turn that keeps producing | | `chatRecovery.terminalMessage` | generic text | What the customer sees when recovery gives up | Return `{ continue: false }` from `onChatRecovery()` when another model call would be unsafe, for example after a long gap (check `ctx.createdAt`) or when a tool with side effects may already have run. A partial reply that already carries completed tool results is persisted even if you also return `persist: false`. A turn waiting on a human approval or a client-side tool is exempt from these budgets. ## Storage limits that shape memory - A Workers SQLite row is capped at **2 MB**; the agent compacts a message that approaches it, first by summarising huge tool outputs, then by truncating text. - **`maxPersistedMessages`** caps how many messages SQLite keeps, deleting the oldest. It does **not** control what the model sees; trim the model's context separately, for example with the AI SDK's `pruneMessages()`. ## Diagnosing a reply that "vanished" When a customer reports that a reply stopped halfway, the cases look alike from the browser but leave different traces: 1. **Client drop**: the turn finished on the server. The full assistant message is in `this.messages`, and the customer saw it complete after reconnecting (or will on reload). 2. **Eviction with recovery**: the partial message was persisted and continued with a second model call. 3. **Eviction with recovery exhausted**: the customer saw the `terminalMessage`, and the SDK emitted a `chat:recovery:exhausted` observability event, which is the one worth alerting on. Knowing which of the three happened tells you whether to look at the network path, the deploy cadence, or the recovery budget.
- Why can't the client-side resume handle a mid-stream eviction?Resume replays chunks the server buffered from a stream that is still running. After an eviction the isolate and its outbound connection to the model are gone, so no stream exists. Only server-side recovery, triggered when the agent next activates, can rebuild the partial reply and start a continuation.
- What does maxPersistedMessages change about what the model sees?Nothing. It caps how many messages SQLite keeps and deletes the oldest beyond that. The context sent to the model is whatever `onChatMessage()` builds from `this.messages`, so you trim it separately, for example with the AI SDK's `pruneMessages()`.
- Believing a reconnecting browser restarts the model call from scratch.
- Thinking the client's resume option also recovers a reply after a deploy evicts the agent.
- Keeping the in-progress reply in a class field and expecting it after eviction.
- Using maxPersistedMessages to limit the tokens sent to the model.
- Letting recovery continue blindly after a tool with side effects may already have run.
Assumes the Agents SDK as of 2026-10-10: AIChatAgent ships in the separate @cloudflare/ai-chat package (stable since February 2026), and the current reference describes durable chat recovery as always on, tuned through chatRecovery.