Skip to content
AnswerWell geo Documentation

Research · 7 min read · Answerwell

Chat Agent Resumable Streaming, Durable Recovery and Message Persistence

How Cloudflare AIChatAgent and useAgentChat keep chat turns alive across disconnects, deploys, and evictions with SQLite persistence.

This page summarises Cloudflare Agents documentation on building chat interfaces with AIChatAgent and useAgentChat. The cluster centres on one production problem: LLM responses can take minutes, clients drop offline, Workers redeploy, and Durable Objects evict—yet users expect the conversation and the in-flight answer to survive. The SDK splits that into resumable client streaming (reconnect without losing buffered tokens), durable chat recovery (finish or continue turns after isolate loss), and SQLite-backed message persistence.

AIChatAgent and useAgentChat: when to use them

Section titled “AIChatAgent and useAgentChat: when to use them”

AIChatAgent from @cloudflare/ai-chat is the opinionated chat layer on top of the base Agent class. Cloudflare documents the stack as Durable Object → Server → Agent → AIChatAgent, and recommends starting there for chat UIs rather than raw Agent unless you need lower-level control.

The AIChatAgent class from @cloudflare/ai-chat extends Agent with an opinionated layer for AI chat. It adds automatic message persistence to SQLite, resumable streaming, tool support (server-side, client-side, and human-in-the-loop), and a React hook (useAgentChat) for building chat UIs.

— Cloudflare, Agent class internals

On the client, useAgentChat (@cloudflare/ai-chat/react, with shared primitives in agents/chat/react) drives the WebSocket chat protocol: send messages, receive streamed chunks, sync history across tabs, and surface recovery state. For custom agents without the chat package, you can persist responses yourself—see Calling LLMs: Surviving disconnections—but AIChatAgent bundles persistence, streaming, and tools by default.

Resumable streaming: survive refresh, tab close, and bad networks

Section titled “Resumable streaming: survive refresh, tab close, and bad networks”

Resumable streaming means the server keeps generating and buffering while the browser is gone; when the client returns, it catches up from SQLite and continues live chunks. That is separate from durable recovery (handled in the next section), which deals with Durable Object eviction or deploy mid-turn.

AIChatAgent now supports resumable streaming, allowing clients to reconnect and continue receiving streamed responses without losing data. This is useful for: Long-running AI responses; Users on unreliable networks; Users switching between devices mid-conversation; Background tasks where users navigate away and return; Real-time collaboration where multiple clients need to stay in sync. Streams are maintained across page refreshes, broken connections, and syncing across open tabs and devices.

— Cloudflare, Agents SDK v0.2.24 — resumable streaming

While a stream is active, chunks buffer in SQLite; after disconnect the server keeps streaming; on reconnect the client receives buffered data plus new events (Chat agents: Resumable streaming). Resumption is on by default—set resume: false on useAgentChat only if you want a fresh stream each session.

cancelOnClientAbort: should the server stop when the browser leaves?

Section titled “cancelOnClientAbort: should the server stop when the browser leaves?”

By default, a generic client abort does not cancel the durable turn—the server keeps working so the user can resume later. Explicit stop() still cancels server work.

@cloudflare/ai-chat now keeps server turns running when a browser or client stream is interrupted. This is useful for long-running AI responses where users refresh the page, close a tab, or temporarily lose connection. Calling stop() still cancels the server turn.

— Cloudflare, Agents SDK v0.12.4 — chat recovery improvements

Set cancelOnClientAbort: true when browser lifecycle should own the server turn (token-saving or request-scoped flows):

const chat = useAgentChat({
agent: "assistant",
name: "user-123",
cancelOnClientAbort: true,
});

Durable chat recovery: deploys, eviction, and stalled provider streams

Section titled “Durable chat recovery: deploys, eviction, and stalled provider streams”

Client resumption cannot fix a severed model connection after Durable Object eviction. Durable chat recovery wraps each turn in a fiber (runFiber()), keeps partial output in SQLite, and on restart runs recovery hooks—documented in Chat agents: Stream recovery and Durable execution with fibers.

Durable chat turns have always been designed to survive a mid-turn deploy or Durable Object eviction. This release is a major hardening pass on that machinery for production. Better recovery during deploys. Turns now ride through continuous deploys and evictions without losing completed work or re-running tools that already ran.

— Cloudflare, Agents SDK v0.14.0 — production hardening for durable chat recovery

Recovery is always on; tune behaviour with chatRecovery on AIChatAgent (attempt caps, noProgressTimeoutMs, maxRecoveryWork, shouldKeepRecovering for cost budgets, terminalMessage, onExhausted). Provider-specific continuation strategies (Workers AI continueLastTurn, OpenAI Responses retrieval, Anthropic synthetic user continuation) are summarised in the same Stream recovery section. Use this.stash() in onChatMessage when a provider needs IDs across recovery.

chatStreamStallTimeoutMs: hung model or transport streams

Section titled “chatStreamStallTimeoutMs: hung model or transport streams”

An opt-in stream stall watchdog treats silence longer than chatStreamStallTimeoutMs as a stall. With chatRecovery enabled, the stall enters the same bounded recovery path as deploy/eviction; otherwise the client gets a terminal stream error so spinners clear (Agents SDK v0.17.0).

Interrupted server tool calls are repaired before re-inference via repairInterruptedToolPart(part), avoiding AI_MissingToolResultsError after recovery. Long-running agent-tool children re-attach instead of being abandoned on deploy.

isRecovering and connection errors on the client

Section titled “isRecovering and connection errors on the client”

useAgentChat exposes isRecovering while a turn is being rebuilt. UIs typically treat isStreaming || isRecovering as busy (Agents SDK v0.14.0). Newer releases replay recovering status to clients that connect mid-recovery so the indicator is not stuck false (Agents SDK v0.17.0).

Terminal WebSocket closes stop endless reconnect loops; errors surface through connectionError / onConnectionError on AgentClient, useAgent, and useAgentChat.

SQLite message persistence, tools, and multi-client sync

Section titled “SQLite message persistence, tools, and multi-client sync”

Conversations live in the agent’s SQLite store: history survives restarts, tool approval state survives refresh and hibernation, and broadcasts keep multiple clients aligned (Chat agents overview).

Mechanism Purpose
maxPersistedMessages Cap stored rows; oldest messages deleted automatically (Agents SDK v0.5.0)
Row size guard Two-pass compaction near SQLite’s ~2 MB row limit (Chat agents)
autoContinueAfterToolResult Default true: client tool results and approvals continue the server turn (Agents SDK v0.5.0)
Data parts (data-*) Typed JSON alongside text (citations, progress, usage)

The WebSocket protocol uses typed messages such as CF_AGENT_USE_CHAT_REQUEST, CF_AGENT_USE_CHAT_RESPONSE, CF_AGENT_CHAT_MESSAGES, CF_AGENT_STREAM_RESUMING, and CF_AGENT_CHAT_REQUEST_CANCEL (Chat agents: WebSocket protocol). The originating client gets live chunks; other connections receive finalized messages via broadcast (Multi-client sync).

In onChatMessage, forward options.abortSignal into streamText so user Stop cancels the model call—otherwise the LLM may keep running after cancel (Chat agents: Request cancellation).

Client streaming flags: user-initiated vs server-initiated work

Section titled “Client streaming flags: user-initiated vs server-initiated work”

AI SDK status ("submitted", "streaming", "ready", "error") applies only to client-initiated requests. Server-driven streams (for example after saveMessages) need extra flags from Autonomous responses:

Flag Meaning
isStreaming Any client or server stream active—default for disabling Send
isServerStreaming Server-initiated stream only
isRecovering Durable recovery in progress

Use isServerStreaming when you want copy such as “Agent is working in the background…” instead of a normal reply spinner.

AI Gateway and catalog models: another layer of stream resume

Section titled “AI Gateway and catalog models: another layer of stream resume”

At the model binding layer, AI SDK integration documents automatic resume for catalog models and dynamic routes: AI Gateway stores events under cf-aig-run-id, reconnects, and replays from the last complete event. Limits matter: the provider stops after five drops in one stream or when the gateway no longer holds the run; Workers AI @cf/ streams without a run id do not resume; aborting never resumes. That complements agent-side buffering—it does not replace fiber recovery when the Durable Object restarts.

Reasoning models that run 30 seconds to minutes are the motivating case in Calling LLMs: a stateless HTTP client must stay connected the whole time, while an Agent can persist and deliver when the client returns.

Diagnostics channels emit chat:recovery:* and chat:stream:stalled events; transcript repairs emit chat:transcript:repaired. Pair these with chatRecovery.onExhausted when debugging production incidents (Durable recovery).

  1. Deploy an AIChatAgent following the chat agent example and confirm messages reload after a Worker restart (SQLite persistence).

  2. Start a long streamed reply, refresh or disconnect the browser mid-stream, then reconnect with default resume: true and confirm tokens continue without duplication (resumable streaming).

  3. During an in-flight turn, redeploy the Worker or trigger Durable Object eviction; verify the UI shows isRecovering and the turn completes or surfaces terminalMessage per your chatRecovery config (Stream recovery).

  4. Subscribe to chat diagnostics (Diagnostics channels) and confirm chat:recovery:detected / chat:recovery:completed (or chat:recovery:exhausted with a reason) match what you saw in the UI.

  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page does not match the behaviour you see in your deployment, email yimasynthetic@gmail.com with the page URL and the exact statement you believe is wrong so it can be corrected or clarified.