@cloudflare/ai-chat 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/dist/react.js +1 -3
- package/dist/react.js.map +1 -1
- package/e2e/global-setup.ts +34 -0
- package/e2e/playwright.config.ts +2 -0
- package/package.json +3 -2
- package/src/react-tests/use-agent-chat.test.tsx +75 -0
- package/src/react.tsx +8 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# @cloudflare/ai-chat
|
|
2
2
|
|
|
3
|
+
## 0.1.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#930](https://github.com/cloudflare/agents/pull/930) [`cd408fe`](https://github.com/cloudflare/agents/commit/cd408fe495176e67066ebbb3962c224ada702124) Thanks [@threepointone](https://github.com/threepointone)! - Fix stale agent reference in useAgentChat transport under React StrictMode
|
|
8
|
+
|
|
9
|
+
The `agentRef` was updated via `useEffect` (async, after render), but the `WebSocketChatTransport` is created in `useMemo` (sync, during render). When the agent reconnects or switches, `useMemo` would capture the old (closed) agent because the effect hadn't fired yet — causing `sendMessage` to send to a dead WebSocket. Fixed by updating `agentRef.current` synchronously during render, matching the pattern already used by other refs in the same hook.
|
|
10
|
+
|
|
11
|
+
## 0.1.1
|
|
12
|
+
|
|
13
|
+
### Patch Changes
|
|
14
|
+
|
|
15
|
+
- [`eeadbf4`](https://github.com/cloudflare/agents/commit/eeadbf4e780e2477798185cbc7a8abbeff2eadda) Thanks [@threepointone](https://github.com/threepointone)! - Add @ai-sdk/react as peer dependency to ai-chat
|
|
16
|
+
|
|
17
|
+
Declare @ai-sdk/react ^3.0.0 as a peerDependency in packages/ai-chat/package.json to express runtime compatibility with the React SDK. package-lock.json was updated to reflect the resulting dependency graph changes.
|
|
18
|
+
|
|
3
19
|
## 0.1.0
|
|
4
20
|
|
|
5
21
|
The first minor release of `@cloudflare/ai-chat` — a major step up from the `agents/ai-chat-agent` re-export. This release refactors the internals (extracting ResumableStream, adding a WebSocket ChatTransport, simplifying SSE parsing) and ships a wave of bug fixes for streaming, tool continuations, and message persistence. New features include `maxPersistedMessages` for storage caps, `body` for custom request data, row size protection, incremental persistence, and data parts — typed JSON blobs that can be attached to messages alongside text for citations, progress indicators, and usage metadata. Tool approval (`needsApproval`) now persists across page refresh, client tools survive DO hibernation, and `autoContinueAfterToolResult` defaults to `true` so the LLM responds after tool results without explicit opt-in.
|
package/dist/react.js
CHANGED
|
@@ -171,9 +171,7 @@ function useAgentChat(options) {
|
|
|
171
171
|
const agentUrlString = agentUrl.toString();
|
|
172
172
|
const initialMessagesCacheKey = `${agentUrlString}|${agent.agent ?? ""}|${agent.name ?? ""}`;
|
|
173
173
|
const agentRef = useRef(agent);
|
|
174
|
-
|
|
175
|
-
agentRef.current = agent;
|
|
176
|
-
}, [agent]);
|
|
174
|
+
agentRef.current = agent;
|
|
177
175
|
async function defaultGetInitialMessagesFetch({ url }) {
|
|
178
176
|
const getMessagesUrl = new URL(url);
|
|
179
177
|
getMessagesUrl.pathname += "/get-messages";
|
package/dist/react.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react.js","names":[],"sources":["../src/ws-chat-transport.ts","../src/react.tsx"],"sourcesContent":["/**\n * WebSocket-based ChatTransport for useAgentChat.\n *\n * Replaces the aiFetch + DefaultChatTransport indirection with a direct\n * WebSocket implementation that speaks the CF_AGENT protocol natively.\n *\n * Data flow (old): WS → aiFetch fake Response → DefaultChatTransport → useChat\n * Data flow (new): WS → WebSocketChatTransport → useChat\n */\n\nimport type { ChatTransport, UIMessage, UIMessageChunk } from \"ai\";\nimport { nanoid } from \"nanoid\";\nimport { MessageType, type OutgoingMessage } from \"./types\";\n\n/**\n * Agent-like interface for sending/receiving WebSocket messages.\n * Matches the shape returned by useAgent from agents/react.\n */\nexport interface AgentConnection {\n send: (data: string) => void;\n addEventListener: (\n type: string,\n listener: (event: MessageEvent) => void,\n options?: { signal?: AbortSignal }\n ) => void;\n removeEventListener: (\n type: string,\n listener: (event: MessageEvent) => void\n ) => void;\n}\n\nexport type WebSocketChatTransportOptions<\n ChatMessage extends UIMessage = UIMessage\n> = {\n /** The agent connection from useAgent */\n agent: AgentConnection;\n /**\n * Callback to prepare the request body before sending.\n * Can add custom headers, body fields, or credentials.\n */\n prepareBody?: (options: {\n messages: ChatMessage[];\n trigger: \"submit-message\" | \"regenerate-message\";\n messageId?: string;\n }) => Promise<Record<string, unknown>> | Record<string, unknown>;\n /**\n * Optional set to track active request IDs.\n * IDs are added when a request starts and removed when it completes.\n * Used by the onAgentMessage handler to skip messages already handled by the transport.\n */\n activeRequestIds?: Set<string>;\n};\n\n/**\n * ChatTransport that sends messages over WebSocket and returns a\n * ReadableStream<UIMessageChunk> that the AI SDK's useChat consumes directly.\n * No fake fetch, no Response reconstruction, no double SSE parsing.\n */\nexport class WebSocketChatTransport<\n ChatMessage extends UIMessage = UIMessage\n> implements ChatTransport<ChatMessage> {\n private agent: AgentConnection;\n private prepareBody?: WebSocketChatTransportOptions<ChatMessage>[\"prepareBody\"];\n private activeRequestIds?: Set<string>;\n\n constructor(options: WebSocketChatTransportOptions<ChatMessage>) {\n this.agent = options.agent;\n this.prepareBody = options.prepareBody;\n this.activeRequestIds = options.activeRequestIds;\n }\n\n async sendMessages(options: {\n chatId: string;\n messages: ChatMessage[];\n abortSignal: AbortSignal | undefined;\n trigger: \"submit-message\" | \"regenerate-message\";\n messageId?: string;\n body?: object;\n headers?: Record<string, string> | Headers;\n metadata?: unknown;\n }): Promise<ReadableStream<UIMessageChunk>> {\n const requestId = nanoid(8);\n const abortController = new AbortController();\n let completed = false;\n\n // Build the request body\n let extraBody: Record<string, unknown> = {};\n if (this.prepareBody) {\n extraBody = await this.prepareBody({\n messages: options.messages,\n trigger: options.trigger,\n messageId: options.messageId\n });\n }\n if (options.body) {\n extraBody = {\n ...extraBody,\n ...(options.body as Record<string, unknown>)\n };\n }\n\n const bodyPayload = JSON.stringify({\n messages: options.messages,\n ...extraBody\n });\n\n // Track this request so the onAgentMessage handler skips it\n this.activeRequestIds?.add(requestId);\n\n // Handle abort from the caller (only if the stream has not already completed)\n options.abortSignal?.addEventListener(\"abort\", () => {\n if (completed) return;\n this.agent.send(\n JSON.stringify({\n id: requestId,\n type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL\n })\n );\n this.activeRequestIds?.delete(requestId);\n abortController.abort();\n });\n\n // Create a ReadableStream<UIMessageChunk> that emits parsed chunks\n // as they arrive over the WebSocket\n const agent = this.agent;\n const activeIds = this.activeRequestIds;\n const stream = new ReadableStream<UIMessageChunk>({\n start(controller) {\n const onMessage = (event: MessageEvent) => {\n try {\n const data = JSON.parse(\n event.data as string\n ) as OutgoingMessage<ChatMessage>;\n\n if (data.type !== MessageType.CF_AGENT_USE_CHAT_RESPONSE) return;\n if (data.id !== requestId) return;\n\n if (data.error) {\n completed = true;\n controller.error(new Error(data.body));\n activeIds?.delete(requestId);\n abortController.abort();\n return;\n }\n\n // Parse the body as UIMessageChunk and enqueue\n if (data.body?.trim()) {\n try {\n const chunk = JSON.parse(data.body) as UIMessageChunk;\n controller.enqueue(chunk);\n } catch {\n // Skip malformed chunk bodies\n }\n }\n\n if (data.done) {\n completed = true;\n try {\n controller.close();\n } catch {\n // Stream may already be closed\n }\n activeIds?.delete(requestId);\n abortController.abort();\n }\n } catch {\n // Ignore non-JSON messages\n }\n };\n\n agent.addEventListener(\"message\", onMessage, {\n signal: abortController.signal\n });\n },\n cancel() {\n abortController.abort();\n }\n });\n\n // Send the request over WebSocket\n agent.send(\n JSON.stringify({\n id: requestId,\n init: {\n method: \"POST\",\n body: bodyPayload\n },\n type: MessageType.CF_AGENT_USE_CHAT_REQUEST\n })\n );\n\n return stream;\n }\n\n async reconnectToStream(_options: {\n chatId: string;\n }): Promise<ReadableStream<UIMessageChunk> | null> {\n // Stream resumption is handled by the onAgentMessage handler\n // in useAgentChat (CF_AGENT_STREAM_RESUME_REQUEST flow).\n // The transport returns null to let the hook handle it.\n return null;\n }\n}\n","import { useChat, type UseChatOptions } from \"@ai-sdk/react\";\nimport { getToolName, isToolUIPart } from \"ai\";\nimport type {\n ChatInit,\n JSONSchema7,\n Tool,\n UIMessage as Message,\n UIMessage\n} from \"ai\";\nimport { nanoid } from \"nanoid\";\nimport { use, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { OutgoingMessage } from \"./types\";\nimport { MessageType } from \"./types\";\nimport { applyChunkToParts, type MessageParts } from \"./message-builder\";\nimport { WebSocketChatTransport } from \"./ws-chat-transport\";\nimport type { useAgent } from \"agents/react\";\n\n/**\n * One-shot deprecation warnings (warns once per key per session).\n */\nconst _deprecationWarnings = new Set<string>();\nfunction warnDeprecated(id: string, message: string) {\n if (!_deprecationWarnings.has(id)) {\n _deprecationWarnings.add(id);\n console.warn(`[@cloudflare/ai-chat] Deprecated: ${message}`);\n }\n}\n\n// ── DEPRECATED TYPES AND FUNCTIONS ──────────────────────────────────\n// Everything in this section is deprecated and will be removed in the\n// next major version. Use server-side tools with tool() from \"ai\" and\n// the onToolCall callback in useAgentChat instead.\n\n/**\n * JSON Schema type for tool parameters.\n * Re-exported from the AI SDK for convenience.\n * @deprecated Import JSONSchema7 directly from \"ai\" instead. Will be removed in the next major version.\n */\nexport type JSONSchemaType = JSONSchema7;\n\n/**\n * Definition for a tool that can be executed on the client.\n * Tools with an `execute` function are automatically registered with the server.\n *\n * Note: Uses `parameters` (JSONSchema7) rather than AI SDK's `inputSchema` (FlexibleSchema)\n * because client tools must be serializable for the wire format. Zod schemas cannot be\n * serialized, so we require raw JSON Schema here.\n *\n * @deprecated Use AI SDK's native tool pattern instead. Define tools on the server with\n * `tool()` from \"ai\", and handle client-side execution via the `onToolCall` callback\n * in `useAgentChat`. For tools requiring user approval, use `needsApproval` on the server.\n */\nexport type AITool<Input = unknown, Output = unknown> = {\n /** Human-readable description of what the tool does */\n description?: Tool[\"description\"];\n /** JSON Schema defining the tool's input parameters */\n parameters?: JSONSchema7;\n /**\n * @deprecated Use `parameters` instead. Will be removed in a future version.\n */\n inputSchema?: JSONSchema7;\n /**\n * Function to execute the tool on the client.\n * If provided, the tool schema is automatically sent to the server.\n */\n execute?: (input: Input) => Output | Promise<Output>;\n};\n\n/**\n * Schema for a client tool sent to the server.\n * This is the wire format - what gets sent in the request body.\n * Must match the server-side ClientToolSchema type in ai-chat-agent.ts.\n *\n * @deprecated Use AI SDK's native tool pattern instead. Define tools on the server.\n */\nexport type ClientToolSchema = {\n /** Unique name for the tool */\n name: string;\n /** Human-readable description of what the tool does */\n description?: Tool[\"description\"];\n /** JSON Schema defining the tool's input parameters */\n parameters?: JSONSchema7;\n};\n\n/**\n * Extracts tool schemas from tools that have client-side execute functions.\n * These schemas are automatically sent to the server with each request.\n * @param tools - Record of tool name to tool definition\n * @returns Array of tool schemas to send to server, or undefined if none\n *\n * @deprecated Use AI SDK's native tool pattern instead. Define tools on the server\n * and use `onToolCall` callback for client-side execution.\n */\nexport function extractClientToolSchemas(\n tools?: Record<string, AITool<unknown, unknown>>\n): ClientToolSchema[] | undefined {\n warnDeprecated(\n \"extractClientToolSchemas\",\n \"extractClientToolSchemas() is deprecated. Define tools on the server and use onToolCall for client execution. Will be removed in the next major version.\"\n );\n if (!tools) return undefined;\n\n const schemas: ClientToolSchema[] = Object.entries(tools)\n .filter(([_, tool]) => tool.execute) // Only tools with client-side execute\n .map(([name, tool]) => {\n if (tool.inputSchema && !tool.parameters) {\n console.warn(\n `[useAgentChat] Tool \"${name}\" uses deprecated 'inputSchema'. Please migrate to 'parameters'.`\n );\n }\n return {\n name,\n description: tool.description,\n parameters: tool.parameters ?? tool.inputSchema\n };\n });\n\n return schemas.length > 0 ? schemas : undefined;\n}\n\n// ── END DEPRECATED TYPES AND FUNCTIONS ─────────────────────────────\n\ntype GetInitialMessagesOptions = {\n agent: string;\n name: string;\n url: string;\n};\n\n// v5 useChat parameters\ntype UseChatParams<M extends UIMessage = UIMessage> = ChatInit<M> &\n UseChatOptions<M>;\n\n/**\n * Options for preparing the send messages request.\n * Used by prepareSendMessagesRequest callback.\n */\nexport type PrepareSendMessagesRequestOptions<\n ChatMessage extends UIMessage = UIMessage\n> = {\n /** The chat ID */\n id: string;\n /** Messages to send */\n messages: ChatMessage[];\n /** What triggered this request */\n trigger: \"submit-message\" | \"regenerate-message\";\n /** ID of the message being sent (if applicable) */\n messageId?: string;\n /** Request metadata */\n requestMetadata?: unknown;\n /** Current body (if any) */\n body?: Record<string, unknown>;\n /** Current credentials (if any) */\n credentials?: RequestCredentials;\n /** Current headers (if any) */\n headers?: HeadersInit;\n /** API endpoint */\n api?: string;\n};\n\n/**\n * Return type for prepareSendMessagesRequest callback.\n * Allows customizing headers, body, and credentials for each request.\n * All fields are optional; only specify what you need to customize.\n */\nexport type PrepareSendMessagesRequestResult = {\n /** Custom headers to send with the request */\n headers?: HeadersInit;\n /** Custom body data to merge with the request */\n body?: Record<string, unknown>;\n /** Custom credentials option */\n credentials?: RequestCredentials;\n /** Custom API endpoint */\n api?: string;\n};\n\n/**\n * Callback for handling client-side tool execution.\n * Called when a tool without server-side execute is invoked.\n */\nexport type OnToolCallCallback = (options: {\n /** The tool call that needs to be handled */\n toolCall: {\n toolCallId: string;\n toolName: string;\n input: unknown;\n };\n /** Function to provide the tool output */\n addToolOutput: (options: { toolCallId: string; output: unknown }) => void;\n}) => void | Promise<void>;\n\n/**\n * Options for the useAgentChat hook\n */\ntype UseAgentChatOptions<\n State,\n ChatMessage extends UIMessage = UIMessage\n> = Omit<UseChatParams<ChatMessage>, \"fetch\" | \"onToolCall\"> & {\n /** Agent connection from useAgent */\n agent: ReturnType<typeof useAgent<State>>;\n getInitialMessages?:\n | undefined\n | null\n | ((options: GetInitialMessagesOptions) => Promise<ChatMessage[]>);\n /** Request credentials */\n credentials?: RequestCredentials;\n /** Request headers */\n headers?: HeadersInit;\n /**\n * Callback for handling client-side tool execution.\n * Called when a tool without server-side `execute` is invoked by the LLM.\n *\n * Use this for:\n * - Tools that need browser APIs (geolocation, camera, etc.)\n * - Tools that need user interaction before providing a result\n * - Tools requiring approval before execution\n *\n * @example\n * ```typescript\n * onToolCall: async ({ toolCall, addToolOutput }) => {\n * if (toolCall.toolName === 'getLocation') {\n * const position = await navigator.geolocation.getCurrentPosition();\n * addToolOutput({\n * toolCallId: toolCall.toolCallId,\n * output: { lat: position.coords.latitude, lng: position.coords.longitude }\n * });\n * }\n * }\n * ```\n */\n onToolCall?: OnToolCallCallback;\n /**\n * @deprecated Use `onToolCall` callback instead for automatic tool execution.\n * @description Whether to automatically resolve tool calls that do not require human interaction.\n * @experimental\n */\n experimental_automaticToolResolution?: boolean;\n /**\n * @deprecated Use `onToolCall` callback instead. Define tools on the server\n * and handle client-side execution via `onToolCall`.\n *\n * Tools that can be executed on the client.\n */\n tools?: Record<string, AITool<unknown, unknown>>;\n /**\n * @deprecated Use `needsApproval` on server-side tools instead.\n * @description Manual override for tools requiring confirmation.\n * If not provided, will auto-detect from tools object (tools without execute require confirmation).\n */\n toolsRequiringConfirmation?: string[];\n /**\n * When true (default), the server automatically continues the conversation\n * after receiving client-side tool results or approvals, similar to how\n * server-executed tools work with maxSteps in streamText. The continuation\n * is merged into the same assistant message.\n *\n * When false, the client must call sendMessage() after tool results\n * to continue the conversation, which creates a new assistant message.\n *\n * @default true\n */\n autoContinueAfterToolResult?: boolean;\n /**\n * @deprecated Use `sendAutomaticallyWhen` from AI SDK instead.\n *\n * When true (default), automatically sends the next message only after\n * all pending confirmation-required tool calls have been resolved.\n * When false, sends immediately after each tool result.\n *\n * Only applies when `autoContinueAfterToolResult` is false.\n *\n * @default true\n */\n autoSendAfterAllConfirmationsResolved?: boolean;\n /**\n * Set to false to disable automatic stream resumption.\n * @default true\n */\n resume?: boolean;\n /**\n * Custom data to include in every chat request body.\n * Accepts a static object or a function that returns one (for dynamic values).\n * These fields are available in `onChatMessage` via `options.body`.\n *\n * @example\n * ```typescript\n * // Static\n * body: { timezone: \"America/New_York\", userId: \"abc\" }\n *\n * // Dynamic (called on each send)\n * body: () => ({ token: getAuthToken(), timestamp: Date.now() })\n * ```\n */\n body?:\n | Record<string, unknown>\n | (() => Record<string, unknown> | Promise<Record<string, unknown>>);\n /**\n * Callback to customize the request before sending messages.\n * For most cases, use the `body` option instead.\n * Use this for advanced scenarios that need access to the messages or trigger type.\n *\n * Note: Client tool schemas are automatically sent when tools have `execute` functions.\n * This callback can add additional data alongside the auto-extracted schemas.\n */\n prepareSendMessagesRequest?: (\n options: PrepareSendMessagesRequestOptions<ChatMessage>\n ) =>\n | PrepareSendMessagesRequestResult\n | Promise<PrepareSendMessagesRequestResult>;\n};\n\n/**\n * Module-level cache for initial message fetches. Intentionally shared across\n * all useAgentChat instances to deduplicate requests during React Strict Mode\n * double-renders and re-renders. Cache keys include the agent URL, agent type,\n * and thread name to prevent cross-agent collisions.\n */\nconst requestCache = new Map<string, Promise<Message[]>>();\n\n/**\n * React hook for building AI chat interfaces using an Agent\n * @param options Chat options including the agent connection\n * @returns Chat interface controls and state with added clearHistory method\n */\n/**\n * Automatically detects which tools require confirmation based on their configuration.\n * Tools require confirmation if they have no execute function AND are not server-executed.\n * @param tools - Record of tool name to tool definition\n * @returns Array of tool names that require confirmation\n *\n * @deprecated Use `needsApproval` on server-side tools instead.\n */\nexport function detectToolsRequiringConfirmation(\n tools?: Record<string, AITool<unknown, unknown>>\n): string[] {\n warnDeprecated(\n \"detectToolsRequiringConfirmation\",\n \"detectToolsRequiringConfirmation() is deprecated. Use needsApproval on server-side tools instead. Will be removed in the next major version.\"\n );\n if (!tools) return [];\n\n return Object.entries(tools)\n .filter(([_name, tool]) => !tool.execute)\n .map(([name]) => name);\n}\n\n/**\n * Return type for addToolOutput function\n */\ntype AddToolOutputOptions = {\n /** The ID of the tool call to provide output for */\n toolCallId: string;\n /** The name of the tool (optional, for type safety) */\n toolName?: string;\n /** The output to provide */\n output: unknown;\n};\n\nexport function useAgentChat<\n State = unknown,\n ChatMessage extends UIMessage = UIMessage\n>(\n options: UseAgentChatOptions<State, ChatMessage>\n): Omit<ReturnType<typeof useChat<ChatMessage>>, \"addToolOutput\"> & {\n clearHistory: () => void;\n /**\n * Provide output for a tool call. Use this for tools that require user interaction\n * or client-side execution.\n */\n addToolOutput: (opts: AddToolOutputOptions) => void;\n} {\n const {\n agent,\n getInitialMessages,\n messages: optionsInitialMessages,\n onToolCall,\n onData,\n experimental_automaticToolResolution,\n tools,\n toolsRequiringConfirmation: manualToolsRequiringConfirmation,\n autoContinueAfterToolResult = true, // Server auto-continues after tool results/approvals\n autoSendAfterAllConfirmationsResolved = true, // Legacy option for client-side batching\n resume = true, // Enable stream resumption by default\n body: bodyOption,\n prepareSendMessagesRequest,\n ...rest\n } = options;\n\n // Emit deprecation warnings for deprecated options (once per session)\n if (tools) {\n warnDeprecated(\n \"useAgentChat.tools\",\n \"The 'tools' option in useAgentChat is deprecated. Define tools on the server using tool() from 'ai' and handle client execution via the onToolCall callback. Will be removed in the next major version.\"\n );\n }\n if (manualToolsRequiringConfirmation) {\n warnDeprecated(\n \"useAgentChat.toolsRequiringConfirmation\",\n \"The 'toolsRequiringConfirmation' option is deprecated. Use needsApproval on server-side tools instead. Will be removed in the next major version.\"\n );\n }\n if (experimental_automaticToolResolution) {\n warnDeprecated(\n \"useAgentChat.experimental_automaticToolResolution\",\n \"The 'experimental_automaticToolResolution' option is deprecated. Use the onToolCall callback instead. Will be removed in the next major version.\"\n );\n }\n if (options.autoSendAfterAllConfirmationsResolved !== undefined) {\n warnDeprecated(\n \"useAgentChat.autoSendAfterAllConfirmationsResolved\",\n \"The 'autoSendAfterAllConfirmationsResolved' option is deprecated. Use sendAutomaticallyWhen from AI SDK instead. Will be removed in the next major version.\"\n );\n }\n\n // ── DEPRECATED: client-side tool confirmation ──────────────────────\n // This block will be removed when toolsRequiringConfirmation is removed.\n // Only call the deprecated function when deprecated options are actually used.\n const toolsRequiringConfirmation = useMemo(\n () =>\n manualToolsRequiringConfirmation ??\n (tools ? detectToolsRequiringConfirmation(tools) : []),\n [manualToolsRequiringConfirmation, tools]\n );\n\n // Keep refs to always point to the latest callbacks\n const onToolCallRef = useRef(onToolCall);\n onToolCallRef.current = onToolCall;\n const onDataRef = useRef(onData);\n onDataRef.current = onData;\n\n const agentUrl = new URL(\n `${\n // @ts-expect-error we're using a protected _url property that includes query params\n ((agent._url as string | null) || agent._pkurl)\n ?.replace(\"ws://\", \"http://\")\n .replace(\"wss://\", \"https://\")\n }`\n );\n\n agentUrl.searchParams.delete(\"_pk\");\n const agentUrlString = agentUrl.toString();\n\n // we need to include agent.name in cache key to prevent collisions during agent switching.\n // The URL may be stale between updateProperties() and reconnect(), but agent.name\n // is updated synchronously, so each thread gets its own cache entry\n const initialMessagesCacheKey = `${agentUrlString}|${agent.agent ?? \"\"}|${agent.name ?? \"\"}`;\n\n // Keep a ref to always point to the latest agent instance\n const agentRef = useRef(agent);\n useEffect(() => {\n agentRef.current = agent;\n }, [agent]);\n\n async function defaultGetInitialMessagesFetch({\n url\n }: GetInitialMessagesOptions) {\n const getMessagesUrl = new URL(url);\n getMessagesUrl.pathname += \"/get-messages\";\n const response = await fetch(getMessagesUrl.toString(), {\n credentials: options.credentials,\n headers: options.headers\n });\n\n if (!response.ok) {\n console.warn(\n `Failed to fetch initial messages: ${response.status} ${response.statusText}`\n );\n return [];\n }\n\n const text = await response.text();\n if (!text.trim()) {\n return [];\n }\n\n try {\n return JSON.parse(text) as ChatMessage[];\n } catch (error) {\n console.warn(\"Failed to parse initial messages JSON:\", error);\n return [];\n }\n }\n\n const getInitialMessagesFetch =\n getInitialMessages || defaultGetInitialMessagesFetch;\n\n function doGetInitialMessages(\n getInitialMessagesOptions: GetInitialMessagesOptions,\n cacheKey: string\n ) {\n if (requestCache.has(cacheKey)) {\n return requestCache.get(cacheKey)! as Promise<ChatMessage[]>;\n }\n const promise = getInitialMessagesFetch(getInitialMessagesOptions);\n requestCache.set(cacheKey, promise);\n return promise;\n }\n\n const initialMessagesPromise =\n getInitialMessages === null\n ? null\n : doGetInitialMessages(\n {\n agent: agent.agent,\n name: agent.name,\n url: agentUrlString\n },\n initialMessagesCacheKey\n );\n const initialMessages = initialMessagesPromise\n ? use(initialMessagesPromise)\n : (optionsInitialMessages ?? []);\n\n useEffect(() => {\n if (!initialMessagesPromise) {\n return;\n }\n requestCache.set(initialMessagesCacheKey, initialMessagesPromise!);\n return () => {\n if (\n requestCache.get(initialMessagesCacheKey) === initialMessagesPromise\n ) {\n requestCache.delete(initialMessagesCacheKey);\n }\n };\n }, [initialMessagesCacheKey, initialMessagesPromise]);\n\n // Use synchronous ref updates to avoid race conditions between effect runs.\n // This ensures the ref always has the latest value before any effect reads it.\n const toolsRef = useRef(tools);\n toolsRef.current = tools;\n\n const prepareSendMessagesRequestRef = useRef(prepareSendMessagesRequest);\n prepareSendMessagesRequestRef.current = prepareSendMessagesRequest;\n\n const bodyOptionRef = useRef(bodyOption);\n bodyOptionRef.current = bodyOption;\n\n /**\n * Tracks request IDs initiated by this tab via the transport.\n * Used by onAgentMessage to skip messages already handled by the transport.\n */\n const localRequestIdsRef = useRef<Set<string>>(new Set());\n\n // WebSocket-based transport that speaks the CF_AGENT protocol natively.\n // Replaces the old aiFetch + DefaultChatTransport indirection.\n const customTransport = useMemo(\n () =>\n new WebSocketChatTransport<ChatMessage>({\n agent: agentRef.current,\n activeRequestIds: localRequestIdsRef.current,\n prepareBody: async ({ messages: msgs, trigger, messageId }) => {\n // Start with the top-level body option (static or dynamic)\n let extraBody: Record<string, unknown> = {};\n const currentBody = bodyOptionRef.current;\n if (currentBody) {\n const resolved =\n typeof currentBody === \"function\"\n ? await currentBody()\n : currentBody;\n extraBody = { ...resolved };\n }\n\n // Extract schemas from deprecated client tools (if any)\n // Only extract client tool schemas when deprecated tools option is used\n if (toolsRef.current) {\n const clientToolSchemas = extractClientToolSchemas(\n toolsRef.current\n );\n if (clientToolSchemas) {\n extraBody.clientTools = clientToolSchemas;\n }\n }\n\n // Apply user's prepareSendMessagesRequest callback (overrides body option)\n if (prepareSendMessagesRequestRef.current) {\n const userResult = await prepareSendMessagesRequestRef.current({\n id: agent._pk,\n messages: msgs,\n trigger,\n messageId\n });\n if (userResult.body) {\n Object.assign(extraBody, userResult.body);\n }\n }\n\n return extraBody;\n }\n }),\n [agent._pk]\n );\n\n const useChatHelpers = useChat<ChatMessage>({\n ...rest,\n onData,\n messages: initialMessages,\n transport: customTransport,\n id: agent._pk\n // Note: We handle stream resumption via WebSocket instead of HTTP,\n // so we don't pass 'resume' to useChat. The onStreamResuming handler\n // automatically resumes active streams when the WebSocket reconnects.\n });\n\n // Destructure stable method references from useChatHelpers.\n // These are individually memoized by the AI SDK (via useCallback), so they're\n // safe to use in dependency arrays without causing re-renders. Using them\n // directly instead of `useChatHelpers.method` avoids the exhaustive-deps\n // warning about the unstable `useChatHelpers` object.\n const {\n messages: chatMessages,\n setMessages,\n addToolResult,\n addToolApprovalResponse,\n sendMessage\n } = useChatHelpers;\n\n const processedToolCalls = useRef(new Set<string>());\n const isResolvingToolsRef = useRef(false);\n // Counter to force the tool resolution effect to re-run after completing\n // a batch of tool calls. Without this, if new tool calls arrive while\n // isResolvingToolsRef is true (e.g. server auto-continuation), the effect\n // exits early and never retriggers because the ref reset doesn't cause\n // a re-render.\n const [toolResolutionTrigger, setToolResolutionTrigger] = useState(0);\n\n // Fix for issue #728: Track client-side tool results in local state\n // to ensure tool parts show output-available immediately after execution.\n const [clientToolResults, setClientToolResults] = useState<\n Map<string, unknown>\n >(new Map());\n\n // Ref to access current messages in callbacks without stale closures\n const messagesRef = useRef(chatMessages);\n messagesRef.current = chatMessages;\n\n // Calculate pending confirmations for the latest assistant message\n const lastMessage = chatMessages[chatMessages.length - 1];\n\n const pendingConfirmations = (() => {\n if (!lastMessage || lastMessage.role !== \"assistant\") {\n return { messageId: undefined, toolCallIds: new Set<string>() };\n }\n\n const pendingIds = new Set<string>();\n for (const part of lastMessage.parts ?? []) {\n if (\n isToolUIPart(part) &&\n part.state === \"input-available\" &&\n toolsRequiringConfirmation.includes(getToolName(part))\n ) {\n pendingIds.add(part.toolCallId);\n }\n }\n return { messageId: lastMessage.id, toolCallIds: pendingIds };\n })();\n\n const pendingConfirmationsRef = useRef(pendingConfirmations);\n pendingConfirmationsRef.current = pendingConfirmations;\n\n // ── DEPRECATED: automatic tool resolution effect ────────────────────\n // This entire useEffect is deprecated. Use onToolCall instead.\n useEffect(() => {\n if (!experimental_automaticToolResolution) {\n return;\n }\n\n // Prevent re-entry while async operations are in progress\n if (isResolvingToolsRef.current) {\n return;\n }\n\n const lastMsg = chatMessages[chatMessages.length - 1];\n if (!lastMsg || lastMsg.role !== \"assistant\") {\n return;\n }\n\n const toolCalls = lastMsg.parts.filter(\n (part) =>\n isToolUIPart(part) &&\n part.state === \"input-available\" &&\n !processedToolCalls.current.has(part.toolCallId)\n );\n\n if (toolCalls.length > 0) {\n // Capture tools synchronously before async work\n const currentTools = toolsRef.current;\n const toolCallsToResolve = toolCalls.filter(\n (part) =>\n isToolUIPart(part) &&\n !toolsRequiringConfirmation.includes(getToolName(part)) &&\n currentTools?.[getToolName(part)]?.execute\n );\n\n if (toolCallsToResolve.length > 0) {\n isResolvingToolsRef.current = true;\n\n (async () => {\n try {\n const toolResults: Array<{\n toolCallId: string;\n toolName: string;\n output: unknown;\n }> = [];\n\n for (const part of toolCallsToResolve) {\n if (isToolUIPart(part)) {\n let toolOutput: unknown = null;\n const toolName = getToolName(part);\n const tool = currentTools?.[toolName];\n\n if (tool?.execute && part.input !== undefined) {\n try {\n toolOutput = await tool.execute(part.input);\n } catch (error) {\n toolOutput = `Error executing tool: ${error instanceof Error ? error.message : String(error)}`;\n }\n }\n\n processedToolCalls.current.add(part.toolCallId);\n\n toolResults.push({\n toolCallId: part.toolCallId,\n toolName,\n output: toolOutput\n });\n }\n }\n\n if (toolResults.length > 0) {\n // Send tool results to server first (server is source of truth)\n const clientToolSchemas = extractClientToolSchemas(currentTools);\n for (const result of toolResults) {\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_TOOL_RESULT,\n toolCallId: result.toolCallId,\n toolName: result.toolName,\n output: result.output,\n autoContinue: autoContinueAfterToolResult,\n clientTools: clientToolSchemas\n })\n );\n }\n\n // Also update local state via AI SDK for immediate UI feedback\n await Promise.all(\n toolResults.map((result) =>\n addToolResult({\n tool: result.toolName,\n toolCallId: result.toolCallId,\n output: result.output\n })\n )\n );\n\n setClientToolResults((prev) => {\n const newMap = new Map(prev);\n for (const result of toolResults) {\n newMap.set(result.toolCallId, result.output);\n }\n return newMap;\n });\n }\n\n // Note: We don't call sendMessage() here anymore.\n // The server will continue the conversation after applying tool results.\n } finally {\n isResolvingToolsRef.current = false;\n // Trigger a re-run so any tool calls that arrived while we were\n // busy (e.g. from server auto-continuation) get picked up.\n setToolResolutionTrigger((c) => c + 1);\n }\n })();\n }\n }\n }, [\n chatMessages,\n experimental_automaticToolResolution,\n addToolResult,\n toolsRequiringConfirmation,\n autoContinueAfterToolResult,\n toolResolutionTrigger\n ]);\n\n // Helper function to send tool output to server\n const sendToolOutputToServer = useCallback(\n (toolCallId: string, toolName: string, output: unknown) => {\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_TOOL_RESULT,\n toolCallId,\n toolName,\n output,\n autoContinue: autoContinueAfterToolResult,\n clientTools: toolsRef.current\n ? extractClientToolSchemas(toolsRef.current)\n : undefined\n })\n );\n\n setClientToolResults((prev) => new Map(prev).set(toolCallId, output));\n },\n [autoContinueAfterToolResult]\n );\n\n // Helper function to send tool approval to server\n const sendToolApprovalToServer = useCallback(\n (toolCallId: string, approved: boolean) => {\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_TOOL_APPROVAL,\n toolCallId,\n approved,\n autoContinue: autoContinueAfterToolResult\n })\n );\n },\n [autoContinueAfterToolResult]\n );\n\n // Effect for new onToolCall callback pattern (v6 style)\n // This fires when there are tool calls that need client-side handling\n useEffect(() => {\n const currentOnToolCall = onToolCallRef.current;\n if (!currentOnToolCall) {\n return;\n }\n\n const lastMsg = chatMessages[chatMessages.length - 1];\n if (!lastMsg || lastMsg.role !== \"assistant\") {\n return;\n }\n\n // Find tool calls in input-available state that haven't been processed\n const pendingToolCalls = lastMsg.parts.filter(\n (part) =>\n isToolUIPart(part) &&\n part.state === \"input-available\" &&\n !processedToolCalls.current.has(part.toolCallId)\n );\n\n for (const part of pendingToolCalls) {\n if (isToolUIPart(part)) {\n const toolCallId = part.toolCallId;\n const toolName = getToolName(part);\n\n // Mark as processed to prevent re-triggering\n processedToolCalls.current.add(toolCallId);\n\n // Create addToolOutput function for this specific tool call\n const addToolOutput = (opts: {\n toolCallId: string;\n output: unknown;\n }) => {\n sendToolOutputToServer(opts.toolCallId, toolName, opts.output);\n\n // Update local state via AI SDK\n addToolResult({\n tool: toolName,\n toolCallId: opts.toolCallId,\n output: opts.output\n });\n };\n\n // Call the onToolCall callback\n // The callback is responsible for calling addToolOutput when ready\n currentOnToolCall({\n toolCall: {\n toolCallId,\n toolName,\n input: part.input\n },\n addToolOutput\n });\n }\n }\n }, [chatMessages, sendToolOutputToServer, addToolResult]);\n\n /**\n * Contains the request ID, accumulated message parts, metadata, and a unique message ID.\n * Used for both resumed streams and real-time broadcasts from other tabs.\n * Metadata is captured from start/finish/message-metadata stream chunks\n * so that it's included when the partial message is flushed to React state.\n */\n const activeStreamRef = useRef<{\n id: string;\n messageId: string;\n parts: ChatMessage[\"parts\"];\n metadata?: Record<string, unknown>;\n } | null>(null);\n\n /**\n * Flush the active stream's accumulated parts into React state.\n * Extracted as a helper so it can be called both during live streaming\n * (per-chunk) and after replay completes (once, at done).\n */\n const flushActiveStreamToMessages = useCallback(\n (activeMsg: {\n id: string;\n messageId: string;\n parts: ChatMessage[\"parts\"];\n metadata?: Record<string, unknown>;\n }) => {\n setMessages((prevMessages: ChatMessage[]) => {\n const existingIdx = prevMessages.findIndex(\n (m) => m.id === activeMsg.messageId\n );\n\n const partialMessage = {\n id: activeMsg.messageId,\n role: \"assistant\" as const,\n parts: [...activeMsg.parts],\n ...(activeMsg.metadata != null && { metadata: activeMsg.metadata })\n } as unknown as ChatMessage;\n\n if (existingIdx >= 0) {\n const updated = [...prevMessages];\n updated[existingIdx] = partialMessage;\n return updated;\n }\n return [...prevMessages, partialMessage];\n });\n },\n [setMessages]\n );\n\n useEffect(() => {\n /**\n * Unified message handler that parses JSON once and dispatches based on type.\n * Avoids duplicate parsing overhead from separate listeners.\n */\n function onAgentMessage(event: MessageEvent) {\n if (typeof event.data !== \"string\") return;\n\n let data: OutgoingMessage<ChatMessage>;\n try {\n data = JSON.parse(event.data) as OutgoingMessage<ChatMessage>;\n } catch (_error) {\n return;\n }\n\n switch (data.type) {\n case MessageType.CF_AGENT_CHAT_CLEAR:\n setMessages([]);\n break;\n\n case MessageType.CF_AGENT_CHAT_MESSAGES:\n setMessages(data.messages);\n break;\n\n case MessageType.CF_AGENT_MESSAGE_UPDATED:\n // Server updated a message (e.g., applied tool result)\n // Update the specific message in local state\n setMessages((prevMessages: ChatMessage[]) => {\n const updatedMessage = data.message;\n\n // First try to find by message ID\n let idx = prevMessages.findIndex((m) => m.id === updatedMessage.id);\n\n // If not found by ID, try to find by toolCallId\n // This handles the case where client has AI SDK-generated IDs\n // but server has server-generated IDs\n if (idx < 0) {\n const updatedToolCallIds = new Set(\n updatedMessage.parts\n .filter(\n (p: ChatMessage[\"parts\"][number]) =>\n \"toolCallId\" in p && p.toolCallId\n )\n .map(\n (p: ChatMessage[\"parts\"][number]) =>\n (p as { toolCallId: string }).toolCallId\n )\n );\n\n if (updatedToolCallIds.size > 0) {\n idx = prevMessages.findIndex((m) =>\n m.parts.some(\n (p) =>\n \"toolCallId\" in p &&\n updatedToolCallIds.has(\n (p as { toolCallId: string }).toolCallId\n )\n )\n );\n }\n }\n\n if (idx >= 0) {\n const updated = [...prevMessages];\n // Preserve the client's message ID but update the content\n updated[idx] = {\n ...updatedMessage,\n id: prevMessages[idx].id\n };\n return updated;\n }\n // Message not found, append it\n return [...prevMessages, updatedMessage];\n });\n break;\n\n case MessageType.CF_AGENT_STREAM_RESUMING:\n if (!resume) return;\n // Clear any previous incomplete active stream to prevent memory leak\n activeStreamRef.current = null;\n // Initialize active stream state with unique ID\n activeStreamRef.current = {\n id: data.id,\n messageId: nanoid(),\n parts: []\n };\n // Send ACK to server - we're ready to receive chunks\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUME_ACK,\n id: data.id\n })\n );\n break;\n\n case MessageType.CF_AGENT_USE_CHAT_RESPONSE: {\n // Skip if this is a response to a request this tab initiated\n // (handled by the aiFetch listener instead)\n if (localRequestIdsRef.current.has(data.id)) return;\n\n // For continuations, find the last assistant message ID to append to\n const isContinuation = data.continuation === true;\n\n // Initialize stream state for broadcasts from other tabs\n if (\n !activeStreamRef.current ||\n activeStreamRef.current.id !== data.id\n ) {\n let messageId = nanoid();\n let existingParts: ChatMessage[\"parts\"] = [];\n let existingMetadata: Record<string, unknown> | undefined;\n\n // For continuations, use the last assistant message's ID, parts, and metadata\n if (isContinuation) {\n const currentMessages = messagesRef.current;\n for (let i = currentMessages.length - 1; i >= 0; i--) {\n if (currentMessages[i].role === \"assistant\") {\n messageId = currentMessages[i].id;\n existingParts = [...currentMessages[i].parts];\n if (currentMessages[i].metadata != null) {\n existingMetadata = {\n ...(currentMessages[i].metadata as Record<\n string,\n unknown\n >)\n };\n }\n break;\n }\n }\n }\n\n activeStreamRef.current = {\n id: data.id,\n messageId,\n parts: existingParts,\n metadata: existingMetadata\n };\n }\n\n const activeMsg = activeStreamRef.current;\n const isReplay = data.replay === true;\n\n if (data.body?.trim()) {\n try {\n const chunkData = JSON.parse(data.body);\n\n // Apply chunk to parts using shared parser.\n // Handles text, reasoning, file, source, tool, step, and data-* chunks.\n // Unrecognized types (tool-input-start, tool-input-delta, etc.)\n // are intermediate states — the final state is captured by\n // tool-input-available / tool-output-available.\n const handled = applyChunkToParts(\n activeMsg.parts as MessageParts,\n chunkData\n );\n\n // Fire onData callback for data-* parts (stream resumption\n // and cross-tab broadcasts). For the transport path (new\n // messages from this tab), the AI SDK's pipeline invokes\n // onData internally.\n if (\n typeof chunkData.type === \"string\" &&\n chunkData.type.startsWith(\"data-\") &&\n onDataRef.current\n ) {\n onDataRef.current(chunkData);\n }\n\n // Capture message metadata from start/finish/message-metadata\n // chunks. These carry metadata like timestamps, model info, and\n // token usage that should be attached at the message level.\n if (\n !handled &&\n (chunkData.type === \"start\" ||\n chunkData.type === \"finish\" ||\n chunkData.type === \"message-metadata\")\n ) {\n if (chunkData.messageId != null && chunkData.type === \"start\") {\n activeMsg.messageId = chunkData.messageId;\n }\n if (chunkData.messageMetadata != null) {\n activeMsg.metadata = activeMsg.metadata\n ? { ...activeMsg.metadata, ...chunkData.messageMetadata }\n : { ...chunkData.messageMetadata };\n }\n }\n\n // For replayed chunks, skip intermediate setMessages calls.\n // Replayed chunks arrive synchronously in a tight loop, so React\n // would batch all state updates into a single render anyway —\n // causing intermediate states (like \"Thinking...\") to be lost.\n // We defer the render until replay is complete (done signal).\n if (!isReplay) {\n flushActiveStreamToMessages(activeMsg);\n }\n } catch (parseError) {\n console.warn(\n \"[useAgentChat] Failed to parse stream chunk:\",\n parseError instanceof Error ? parseError.message : parseError,\n \"body:\",\n data.body?.slice(0, 100)\n );\n }\n }\n\n // On completion or error, flush final state to messages\n if (data.done || data.error) {\n // For replayed streams, this is the single render point —\n // all parts have been accumulated, now render them at once.\n if (isReplay && activeMsg) {\n flushActiveStreamToMessages(activeMsg);\n }\n activeStreamRef.current = null;\n }\n break;\n }\n }\n }\n\n agent.addEventListener(\"message\", onAgentMessage);\n\n // Request stream resume check AFTER the handler is registered.\n // This avoids the race condition where CF_AGENT_STREAM_RESUMING sent\n // in onConnect arrives before this useEffect runs. The server also\n // sends it in onConnect as a fallback for older clients.\n if (resume) {\n agent.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST\n })\n );\n }\n\n return () => {\n agent.removeEventListener(\"message\", onAgentMessage);\n // Clear active stream state on cleanup to prevent memory leak\n activeStreamRef.current = null;\n };\n }, [agent, setMessages, resume, flushActiveStreamToMessages]);\n\n // ── DEPRECATED: addToolResult wrapper with confirmation batching ────\n // This wrapper is deprecated. Use addToolOutput or addToolApprovalResponse instead.\n const addToolResultAndSendMessage: typeof addToolResult = async (args) => {\n const { toolCallId } = args;\n const toolName = \"tool\" in args ? args.tool : \"\";\n const output = \"output\" in args ? args.output : undefined;\n\n // Send tool result to server (server is source of truth)\n // Include flag to tell server whether to auto-continue\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_TOOL_RESULT,\n toolCallId,\n toolName,\n output,\n autoContinue: autoContinueAfterToolResult,\n clientTools: toolsRef.current\n ? extractClientToolSchemas(toolsRef.current)\n : undefined\n })\n );\n\n setClientToolResults((prev) => new Map(prev).set(toolCallId, output));\n\n // Call AI SDK's addToolResult for local state update (non-blocking)\n // We don't await this since clientToolResults provides immediate UI feedback\n addToolResult(args);\n\n // If server auto-continuation is disabled, client needs to trigger continuation\n if (!autoContinueAfterToolResult) {\n // Use legacy behavior: batch confirmations or send immediately\n if (!autoSendAfterAllConfirmationsResolved) {\n // Always send immediately\n sendMessage();\n return;\n }\n\n // Wait for all confirmations before sending\n const pending = pendingConfirmationsRef.current?.toolCallIds;\n if (!pending) {\n sendMessage();\n return;\n }\n\n const wasLast = pending.size === 1 && pending.has(toolCallId);\n if (pending.has(toolCallId)) {\n pending.delete(toolCallId);\n }\n\n if (wasLast || pending.size === 0) {\n sendMessage();\n }\n }\n // If autoContinueAfterToolResult is true, server handles continuation\n };\n\n // Wrapper that sends tool approval to server before updating local state.\n // This prevents duplicate messages by ensuring server updates the message\n // in place with the existing ID, rather than relying on ID resolution\n // when sendMessage() is called later.\n const addToolApprovalResponseAndNotifyServer: typeof addToolApprovalResponse =\n (args) => {\n const { id: approvalId, approved } = args;\n\n // Find the toolCallId from the approval ID\n // The approval ID is stored on the tool part's approval.id field\n let toolCallId: string | undefined;\n for (const msg of messagesRef.current) {\n for (const part of msg.parts) {\n if (\n \"toolCallId\" in part &&\n \"approval\" in part &&\n (part.approval as { id?: string })?.id === approvalId\n ) {\n toolCallId = part.toolCallId as string;\n break;\n }\n }\n if (toolCallId) break;\n }\n\n if (toolCallId) {\n // Send approval to server first (server updates message in place)\n sendToolApprovalToServer(toolCallId, approved);\n } else {\n console.warn(\n `[useAgentChat] addToolApprovalResponse: Could not find toolCallId for approval ID \"${approvalId}\". ` +\n \"Server will not be notified, which may cause duplicate messages.\"\n );\n }\n\n // Call AI SDK's addToolApprovalResponse for local state update\n addToolApprovalResponse(args);\n };\n\n // Fix for issue #728: Merge client-side tool results with messages\n // so tool parts show output-available immediately after execution\n const messagesWithToolResults = useMemo(() => {\n if (clientToolResults.size === 0) {\n return chatMessages;\n }\n return chatMessages.map((msg) => ({\n ...msg,\n parts: msg.parts.map((p) => {\n if (\n !(\"toolCallId\" in p) ||\n !(\"state\" in p) ||\n p.state !== \"input-available\" ||\n !clientToolResults.has(p.toolCallId)\n ) {\n return p;\n }\n return {\n ...p,\n state: \"output-available\" as const,\n output: clientToolResults.get(p.toolCallId)\n };\n })\n })) as ChatMessage[];\n }, [chatMessages, clientToolResults]);\n\n // Cleanup stale entries from clientToolResults when messages change\n // to prevent memory leak in long conversations.\n // Note: We intentionally exclude clientToolResults from deps to avoid infinite loops.\n // The functional update form gives us access to the previous state.\n useEffect(() => {\n // Collect all current toolCallIds from messages\n const currentToolCallIds = new Set<string>();\n for (const msg of chatMessages) {\n for (const part of msg.parts) {\n if (\"toolCallId\" in part && part.toolCallId) {\n currentToolCallIds.add(part.toolCallId);\n }\n }\n }\n\n // Use functional update to check and clean stale entries atomically\n setClientToolResults((prev) => {\n if (prev.size === 0) return prev;\n\n // Check if any entries are stale\n let hasStaleEntries = false;\n for (const toolCallId of prev.keys()) {\n if (!currentToolCallIds.has(toolCallId)) {\n hasStaleEntries = true;\n break;\n }\n }\n\n // Only create new Map if there are stale entries to remove\n if (!hasStaleEntries) return prev;\n\n const newMap = new Map<string, unknown>();\n for (const [id, output] of prev) {\n if (currentToolCallIds.has(id)) {\n newMap.set(id, output);\n }\n }\n return newMap;\n });\n\n // Also cleanup processedToolCalls to prevent issues in long conversations\n for (const toolCallId of processedToolCalls.current) {\n if (!currentToolCallIds.has(toolCallId)) {\n processedToolCalls.current.delete(toolCallId);\n }\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [chatMessages]);\n\n // Create addToolOutput function for external use\n const addToolOutput = useCallback(\n (opts: { toolCallId: string; toolName?: string; output: unknown }) => {\n const toolName = opts.toolName ?? \"\";\n sendToolOutputToServer(opts.toolCallId, toolName, opts.output);\n\n // Update local state via AI SDK\n addToolResult({\n tool: toolName,\n toolCallId: opts.toolCallId,\n output: opts.output\n });\n },\n [sendToolOutputToServer, addToolResult]\n );\n\n return {\n ...useChatHelpers,\n messages: messagesWithToolResults,\n /**\n * Provide output for a tool call. Use this for tools that require user interaction\n * or client-side execution.\n */\n addToolOutput,\n /**\n * @deprecated Use `addToolOutput` instead.\n */\n addToolResult: addToolResultAndSendMessage,\n /**\n * Respond to a tool approval request. Use this for tools with `needsApproval`.\n * This wrapper notifies the server before updating local state, preventing\n * duplicate messages when sendMessage() is called afterward.\n */\n addToolApprovalResponse: addToolApprovalResponseAndNotifyServer,\n clearHistory: () => {\n setMessages([]);\n setClientToolResults(new Map());\n processedToolCalls.current.clear();\n agent.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_CHAT_CLEAR\n })\n );\n },\n setMessages: (messagesOrUpdater: Parameters<typeof setMessages>[0]) => {\n // Resolve functional updaters to get the actual messages array\n // before syncing to server. Without this, updater functions would\n // send an empty array and wipe server-side messages.\n let resolvedMessages: ChatMessage[];\n if (typeof messagesOrUpdater === \"function\") {\n resolvedMessages = messagesOrUpdater(messagesRef.current);\n } else {\n resolvedMessages = messagesOrUpdater;\n }\n\n setMessages(resolvedMessages);\n agent.send(\n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AAM,KACJ,KAAK,UAAU;IACb,UAAU;IACV,MAAM,YAAY;IACnB,CAAC,CACH;;EAEJ"}
|
|
1
|
+
{"version":3,"file":"react.js","names":[],"sources":["../src/ws-chat-transport.ts","../src/react.tsx"],"sourcesContent":["/**\n * WebSocket-based ChatTransport for useAgentChat.\n *\n * Replaces the aiFetch + DefaultChatTransport indirection with a direct\n * WebSocket implementation that speaks the CF_AGENT protocol natively.\n *\n * Data flow (old): WS → aiFetch fake Response → DefaultChatTransport → useChat\n * Data flow (new): WS → WebSocketChatTransport → useChat\n */\n\nimport type { ChatTransport, UIMessage, UIMessageChunk } from \"ai\";\nimport { nanoid } from \"nanoid\";\nimport { MessageType, type OutgoingMessage } from \"./types\";\n\n/**\n * Agent-like interface for sending/receiving WebSocket messages.\n * Matches the shape returned by useAgent from agents/react.\n */\nexport interface AgentConnection {\n send: (data: string) => void;\n addEventListener: (\n type: string,\n listener: (event: MessageEvent) => void,\n options?: { signal?: AbortSignal }\n ) => void;\n removeEventListener: (\n type: string,\n listener: (event: MessageEvent) => void\n ) => void;\n}\n\nexport type WebSocketChatTransportOptions<\n ChatMessage extends UIMessage = UIMessage\n> = {\n /** The agent connection from useAgent */\n agent: AgentConnection;\n /**\n * Callback to prepare the request body before sending.\n * Can add custom headers, body fields, or credentials.\n */\n prepareBody?: (options: {\n messages: ChatMessage[];\n trigger: \"submit-message\" | \"regenerate-message\";\n messageId?: string;\n }) => Promise<Record<string, unknown>> | Record<string, unknown>;\n /**\n * Optional set to track active request IDs.\n * IDs are added when a request starts and removed when it completes.\n * Used by the onAgentMessage handler to skip messages already handled by the transport.\n */\n activeRequestIds?: Set<string>;\n};\n\n/**\n * ChatTransport that sends messages over WebSocket and returns a\n * ReadableStream<UIMessageChunk> that the AI SDK's useChat consumes directly.\n * No fake fetch, no Response reconstruction, no double SSE parsing.\n */\nexport class WebSocketChatTransport<\n ChatMessage extends UIMessage = UIMessage\n> implements ChatTransport<ChatMessage> {\n private agent: AgentConnection;\n private prepareBody?: WebSocketChatTransportOptions<ChatMessage>[\"prepareBody\"];\n private activeRequestIds?: Set<string>;\n\n constructor(options: WebSocketChatTransportOptions<ChatMessage>) {\n this.agent = options.agent;\n this.prepareBody = options.prepareBody;\n this.activeRequestIds = options.activeRequestIds;\n }\n\n async sendMessages(options: {\n chatId: string;\n messages: ChatMessage[];\n abortSignal: AbortSignal | undefined;\n trigger: \"submit-message\" | \"regenerate-message\";\n messageId?: string;\n body?: object;\n headers?: Record<string, string> | Headers;\n metadata?: unknown;\n }): Promise<ReadableStream<UIMessageChunk>> {\n const requestId = nanoid(8);\n const abortController = new AbortController();\n let completed = false;\n\n // Build the request body\n let extraBody: Record<string, unknown> = {};\n if (this.prepareBody) {\n extraBody = await this.prepareBody({\n messages: options.messages,\n trigger: options.trigger,\n messageId: options.messageId\n });\n }\n if (options.body) {\n extraBody = {\n ...extraBody,\n ...(options.body as Record<string, unknown>)\n };\n }\n\n const bodyPayload = JSON.stringify({\n messages: options.messages,\n ...extraBody\n });\n\n // Track this request so the onAgentMessage handler skips it\n this.activeRequestIds?.add(requestId);\n\n // Handle abort from the caller (only if the stream has not already completed)\n options.abortSignal?.addEventListener(\"abort\", () => {\n if (completed) return;\n this.agent.send(\n JSON.stringify({\n id: requestId,\n type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL\n })\n );\n this.activeRequestIds?.delete(requestId);\n abortController.abort();\n });\n\n // Create a ReadableStream<UIMessageChunk> that emits parsed chunks\n // as they arrive over the WebSocket\n const agent = this.agent;\n const activeIds = this.activeRequestIds;\n const stream = new ReadableStream<UIMessageChunk>({\n start(controller) {\n const onMessage = (event: MessageEvent) => {\n try {\n const data = JSON.parse(\n event.data as string\n ) as OutgoingMessage<ChatMessage>;\n\n if (data.type !== MessageType.CF_AGENT_USE_CHAT_RESPONSE) return;\n if (data.id !== requestId) return;\n\n if (data.error) {\n completed = true;\n controller.error(new Error(data.body));\n activeIds?.delete(requestId);\n abortController.abort();\n return;\n }\n\n // Parse the body as UIMessageChunk and enqueue\n if (data.body?.trim()) {\n try {\n const chunk = JSON.parse(data.body) as UIMessageChunk;\n controller.enqueue(chunk);\n } catch {\n // Skip malformed chunk bodies\n }\n }\n\n if (data.done) {\n completed = true;\n try {\n controller.close();\n } catch {\n // Stream may already be closed\n }\n activeIds?.delete(requestId);\n abortController.abort();\n }\n } catch {\n // Ignore non-JSON messages\n }\n };\n\n agent.addEventListener(\"message\", onMessage, {\n signal: abortController.signal\n });\n },\n cancel() {\n abortController.abort();\n }\n });\n\n // Send the request over WebSocket\n agent.send(\n JSON.stringify({\n id: requestId,\n init: {\n method: \"POST\",\n body: bodyPayload\n },\n type: MessageType.CF_AGENT_USE_CHAT_REQUEST\n })\n );\n\n return stream;\n }\n\n async reconnectToStream(_options: {\n chatId: string;\n }): Promise<ReadableStream<UIMessageChunk> | null> {\n // Stream resumption is handled by the onAgentMessage handler\n // in useAgentChat (CF_AGENT_STREAM_RESUME_REQUEST flow).\n // The transport returns null to let the hook handle it.\n return null;\n }\n}\n","import { useChat, type UseChatOptions } from \"@ai-sdk/react\";\nimport { getToolName, isToolUIPart } from \"ai\";\nimport type {\n ChatInit,\n JSONSchema7,\n Tool,\n UIMessage as Message,\n UIMessage\n} from \"ai\";\nimport { nanoid } from \"nanoid\";\nimport { use, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { OutgoingMessage } from \"./types\";\nimport { MessageType } from \"./types\";\nimport { applyChunkToParts, type MessageParts } from \"./message-builder\";\nimport { WebSocketChatTransport } from \"./ws-chat-transport\";\nimport type { useAgent } from \"agents/react\";\n\n/**\n * One-shot deprecation warnings (warns once per key per session).\n */\nconst _deprecationWarnings = new Set<string>();\nfunction warnDeprecated(id: string, message: string) {\n if (!_deprecationWarnings.has(id)) {\n _deprecationWarnings.add(id);\n console.warn(`[@cloudflare/ai-chat] Deprecated: ${message}`);\n }\n}\n\n// ── DEPRECATED TYPES AND FUNCTIONS ──────────────────────────────────\n// Everything in this section is deprecated and will be removed in the\n// next major version. Use server-side tools with tool() from \"ai\" and\n// the onToolCall callback in useAgentChat instead.\n\n/**\n * JSON Schema type for tool parameters.\n * Re-exported from the AI SDK for convenience.\n * @deprecated Import JSONSchema7 directly from \"ai\" instead. Will be removed in the next major version.\n */\nexport type JSONSchemaType = JSONSchema7;\n\n/**\n * Definition for a tool that can be executed on the client.\n * Tools with an `execute` function are automatically registered with the server.\n *\n * Note: Uses `parameters` (JSONSchema7) rather than AI SDK's `inputSchema` (FlexibleSchema)\n * because client tools must be serializable for the wire format. Zod schemas cannot be\n * serialized, so we require raw JSON Schema here.\n *\n * @deprecated Use AI SDK's native tool pattern instead. Define tools on the server with\n * `tool()` from \"ai\", and handle client-side execution via the `onToolCall` callback\n * in `useAgentChat`. For tools requiring user approval, use `needsApproval` on the server.\n */\nexport type AITool<Input = unknown, Output = unknown> = {\n /** Human-readable description of what the tool does */\n description?: Tool[\"description\"];\n /** JSON Schema defining the tool's input parameters */\n parameters?: JSONSchema7;\n /**\n * @deprecated Use `parameters` instead. Will be removed in a future version.\n */\n inputSchema?: JSONSchema7;\n /**\n * Function to execute the tool on the client.\n * If provided, the tool schema is automatically sent to the server.\n */\n execute?: (input: Input) => Output | Promise<Output>;\n};\n\n/**\n * Schema for a client tool sent to the server.\n * This is the wire format - what gets sent in the request body.\n * Must match the server-side ClientToolSchema type in ai-chat-agent.ts.\n *\n * @deprecated Use AI SDK's native tool pattern instead. Define tools on the server.\n */\nexport type ClientToolSchema = {\n /** Unique name for the tool */\n name: string;\n /** Human-readable description of what the tool does */\n description?: Tool[\"description\"];\n /** JSON Schema defining the tool's input parameters */\n parameters?: JSONSchema7;\n};\n\n/**\n * Extracts tool schemas from tools that have client-side execute functions.\n * These schemas are automatically sent to the server with each request.\n * @param tools - Record of tool name to tool definition\n * @returns Array of tool schemas to send to server, or undefined if none\n *\n * @deprecated Use AI SDK's native tool pattern instead. Define tools on the server\n * and use `onToolCall` callback for client-side execution.\n */\nexport function extractClientToolSchemas(\n tools?: Record<string, AITool<unknown, unknown>>\n): ClientToolSchema[] | undefined {\n warnDeprecated(\n \"extractClientToolSchemas\",\n \"extractClientToolSchemas() is deprecated. Define tools on the server and use onToolCall for client execution. Will be removed in the next major version.\"\n );\n if (!tools) return undefined;\n\n const schemas: ClientToolSchema[] = Object.entries(tools)\n .filter(([_, tool]) => tool.execute) // Only tools with client-side execute\n .map(([name, tool]) => {\n if (tool.inputSchema && !tool.parameters) {\n console.warn(\n `[useAgentChat] Tool \"${name}\" uses deprecated 'inputSchema'. Please migrate to 'parameters'.`\n );\n }\n return {\n name,\n description: tool.description,\n parameters: tool.parameters ?? tool.inputSchema\n };\n });\n\n return schemas.length > 0 ? schemas : undefined;\n}\n\n// ── END DEPRECATED TYPES AND FUNCTIONS ─────────────────────────────\n\ntype GetInitialMessagesOptions = {\n agent: string;\n name: string;\n url: string;\n};\n\n// v5 useChat parameters\ntype UseChatParams<M extends UIMessage = UIMessage> = ChatInit<M> &\n UseChatOptions<M>;\n\n/**\n * Options for preparing the send messages request.\n * Used by prepareSendMessagesRequest callback.\n */\nexport type PrepareSendMessagesRequestOptions<\n ChatMessage extends UIMessage = UIMessage\n> = {\n /** The chat ID */\n id: string;\n /** Messages to send */\n messages: ChatMessage[];\n /** What triggered this request */\n trigger: \"submit-message\" | \"regenerate-message\";\n /** ID of the message being sent (if applicable) */\n messageId?: string;\n /** Request metadata */\n requestMetadata?: unknown;\n /** Current body (if any) */\n body?: Record<string, unknown>;\n /** Current credentials (if any) */\n credentials?: RequestCredentials;\n /** Current headers (if any) */\n headers?: HeadersInit;\n /** API endpoint */\n api?: string;\n};\n\n/**\n * Return type for prepareSendMessagesRequest callback.\n * Allows customizing headers, body, and credentials for each request.\n * All fields are optional; only specify what you need to customize.\n */\nexport type PrepareSendMessagesRequestResult = {\n /** Custom headers to send with the request */\n headers?: HeadersInit;\n /** Custom body data to merge with the request */\n body?: Record<string, unknown>;\n /** Custom credentials option */\n credentials?: RequestCredentials;\n /** Custom API endpoint */\n api?: string;\n};\n\n/**\n * Callback for handling client-side tool execution.\n * Called when a tool without server-side execute is invoked.\n */\nexport type OnToolCallCallback = (options: {\n /** The tool call that needs to be handled */\n toolCall: {\n toolCallId: string;\n toolName: string;\n input: unknown;\n };\n /** Function to provide the tool output */\n addToolOutput: (options: { toolCallId: string; output: unknown }) => void;\n}) => void | Promise<void>;\n\n/**\n * Options for the useAgentChat hook\n */\ntype UseAgentChatOptions<\n State,\n ChatMessage extends UIMessage = UIMessage\n> = Omit<UseChatParams<ChatMessage>, \"fetch\" | \"onToolCall\"> & {\n /** Agent connection from useAgent */\n agent: ReturnType<typeof useAgent<State>>;\n getInitialMessages?:\n | undefined\n | null\n | ((options: GetInitialMessagesOptions) => Promise<ChatMessage[]>);\n /** Request credentials */\n credentials?: RequestCredentials;\n /** Request headers */\n headers?: HeadersInit;\n /**\n * Callback for handling client-side tool execution.\n * Called when a tool without server-side `execute` is invoked by the LLM.\n *\n * Use this for:\n * - Tools that need browser APIs (geolocation, camera, etc.)\n * - Tools that need user interaction before providing a result\n * - Tools requiring approval before execution\n *\n * @example\n * ```typescript\n * onToolCall: async ({ toolCall, addToolOutput }) => {\n * if (toolCall.toolName === 'getLocation') {\n * const position = await navigator.geolocation.getCurrentPosition();\n * addToolOutput({\n * toolCallId: toolCall.toolCallId,\n * output: { lat: position.coords.latitude, lng: position.coords.longitude }\n * });\n * }\n * }\n * ```\n */\n onToolCall?: OnToolCallCallback;\n /**\n * @deprecated Use `onToolCall` callback instead for automatic tool execution.\n * @description Whether to automatically resolve tool calls that do not require human interaction.\n * @experimental\n */\n experimental_automaticToolResolution?: boolean;\n /**\n * @deprecated Use `onToolCall` callback instead. Define tools on the server\n * and handle client-side execution via `onToolCall`.\n *\n * Tools that can be executed on the client.\n */\n tools?: Record<string, AITool<unknown, unknown>>;\n /**\n * @deprecated Use `needsApproval` on server-side tools instead.\n * @description Manual override for tools requiring confirmation.\n * If not provided, will auto-detect from tools object (tools without execute require confirmation).\n */\n toolsRequiringConfirmation?: string[];\n /**\n * When true (default), the server automatically continues the conversation\n * after receiving client-side tool results or approvals, similar to how\n * server-executed tools work with maxSteps in streamText. The continuation\n * is merged into the same assistant message.\n *\n * When false, the client must call sendMessage() after tool results\n * to continue the conversation, which creates a new assistant message.\n *\n * @default true\n */\n autoContinueAfterToolResult?: boolean;\n /**\n * @deprecated Use `sendAutomaticallyWhen` from AI SDK instead.\n *\n * When true (default), automatically sends the next message only after\n * all pending confirmation-required tool calls have been resolved.\n * When false, sends immediately after each tool result.\n *\n * Only applies when `autoContinueAfterToolResult` is false.\n *\n * @default true\n */\n autoSendAfterAllConfirmationsResolved?: boolean;\n /**\n * Set to false to disable automatic stream resumption.\n * @default true\n */\n resume?: boolean;\n /**\n * Custom data to include in every chat request body.\n * Accepts a static object or a function that returns one (for dynamic values).\n * These fields are available in `onChatMessage` via `options.body`.\n *\n * @example\n * ```typescript\n * // Static\n * body: { timezone: \"America/New_York\", userId: \"abc\" }\n *\n * // Dynamic (called on each send)\n * body: () => ({ token: getAuthToken(), timestamp: Date.now() })\n * ```\n */\n body?:\n | Record<string, unknown>\n | (() => Record<string, unknown> | Promise<Record<string, unknown>>);\n /**\n * Callback to customize the request before sending messages.\n * For most cases, use the `body` option instead.\n * Use this for advanced scenarios that need access to the messages or trigger type.\n *\n * Note: Client tool schemas are automatically sent when tools have `execute` functions.\n * This callback can add additional data alongside the auto-extracted schemas.\n */\n prepareSendMessagesRequest?: (\n options: PrepareSendMessagesRequestOptions<ChatMessage>\n ) =>\n | PrepareSendMessagesRequestResult\n | Promise<PrepareSendMessagesRequestResult>;\n};\n\n/**\n * Module-level cache for initial message fetches. Intentionally shared across\n * all useAgentChat instances to deduplicate requests during React Strict Mode\n * double-renders and re-renders. Cache keys include the agent URL, agent type,\n * and thread name to prevent cross-agent collisions.\n */\nconst requestCache = new Map<string, Promise<Message[]>>();\n\n/**\n * React hook for building AI chat interfaces using an Agent\n * @param options Chat options including the agent connection\n * @returns Chat interface controls and state with added clearHistory method\n */\n/**\n * Automatically detects which tools require confirmation based on their configuration.\n * Tools require confirmation if they have no execute function AND are not server-executed.\n * @param tools - Record of tool name to tool definition\n * @returns Array of tool names that require confirmation\n *\n * @deprecated Use `needsApproval` on server-side tools instead.\n */\nexport function detectToolsRequiringConfirmation(\n tools?: Record<string, AITool<unknown, unknown>>\n): string[] {\n warnDeprecated(\n \"detectToolsRequiringConfirmation\",\n \"detectToolsRequiringConfirmation() is deprecated. Use needsApproval on server-side tools instead. Will be removed in the next major version.\"\n );\n if (!tools) return [];\n\n return Object.entries(tools)\n .filter(([_name, tool]) => !tool.execute)\n .map(([name]) => name);\n}\n\n/**\n * Return type for addToolOutput function\n */\ntype AddToolOutputOptions = {\n /** The ID of the tool call to provide output for */\n toolCallId: string;\n /** The name of the tool (optional, for type safety) */\n toolName?: string;\n /** The output to provide */\n output: unknown;\n};\n\nexport function useAgentChat<\n State = unknown,\n ChatMessage extends UIMessage = UIMessage\n>(\n options: UseAgentChatOptions<State, ChatMessage>\n): Omit<ReturnType<typeof useChat<ChatMessage>>, \"addToolOutput\"> & {\n clearHistory: () => void;\n /**\n * Provide output for a tool call. Use this for tools that require user interaction\n * or client-side execution.\n */\n addToolOutput: (opts: AddToolOutputOptions) => void;\n} {\n const {\n agent,\n getInitialMessages,\n messages: optionsInitialMessages,\n onToolCall,\n onData,\n experimental_automaticToolResolution,\n tools,\n toolsRequiringConfirmation: manualToolsRequiringConfirmation,\n autoContinueAfterToolResult = true, // Server auto-continues after tool results/approvals\n autoSendAfterAllConfirmationsResolved = true, // Legacy option for client-side batching\n resume = true, // Enable stream resumption by default\n body: bodyOption,\n prepareSendMessagesRequest,\n ...rest\n } = options;\n\n // Emit deprecation warnings for deprecated options (once per session)\n if (tools) {\n warnDeprecated(\n \"useAgentChat.tools\",\n \"The 'tools' option in useAgentChat is deprecated. Define tools on the server using tool() from 'ai' and handle client execution via the onToolCall callback. Will be removed in the next major version.\"\n );\n }\n if (manualToolsRequiringConfirmation) {\n warnDeprecated(\n \"useAgentChat.toolsRequiringConfirmation\",\n \"The 'toolsRequiringConfirmation' option is deprecated. Use needsApproval on server-side tools instead. Will be removed in the next major version.\"\n );\n }\n if (experimental_automaticToolResolution) {\n warnDeprecated(\n \"useAgentChat.experimental_automaticToolResolution\",\n \"The 'experimental_automaticToolResolution' option is deprecated. Use the onToolCall callback instead. Will be removed in the next major version.\"\n );\n }\n if (options.autoSendAfterAllConfirmationsResolved !== undefined) {\n warnDeprecated(\n \"useAgentChat.autoSendAfterAllConfirmationsResolved\",\n \"The 'autoSendAfterAllConfirmationsResolved' option is deprecated. Use sendAutomaticallyWhen from AI SDK instead. Will be removed in the next major version.\"\n );\n }\n\n // ── DEPRECATED: client-side tool confirmation ──────────────────────\n // This block will be removed when toolsRequiringConfirmation is removed.\n // Only call the deprecated function when deprecated options are actually used.\n const toolsRequiringConfirmation = useMemo(\n () =>\n manualToolsRequiringConfirmation ??\n (tools ? detectToolsRequiringConfirmation(tools) : []),\n [manualToolsRequiringConfirmation, tools]\n );\n\n // Keep refs to always point to the latest callbacks\n const onToolCallRef = useRef(onToolCall);\n onToolCallRef.current = onToolCall;\n const onDataRef = useRef(onData);\n onDataRef.current = onData;\n\n const agentUrl = new URL(\n `${\n // @ts-expect-error we're using a protected _url property that includes query params\n ((agent._url as string | null) || agent._pkurl)\n ?.replace(\"ws://\", \"http://\")\n .replace(\"wss://\", \"https://\")\n }`\n );\n\n agentUrl.searchParams.delete(\"_pk\");\n const agentUrlString = agentUrl.toString();\n\n // we need to include agent.name in cache key to prevent collisions during agent switching.\n // The URL may be stale between updateProperties() and reconnect(), but agent.name\n // is updated synchronously, so each thread gets its own cache entry\n const initialMessagesCacheKey = `${agentUrlString}|${agent.agent ?? \"\"}|${agent.name ?? \"\"}`;\n\n // Keep a ref to always point to the latest agent instance.\n // Updated synchronously during render (not in useEffect) to ensure\n // useMemo and other synchronous code always sees the latest agent.\n // Using useEffect would cause a race: when agent._pk changes, useMemo\n // re-evaluates during render but the effect hasn't fired yet, so\n // agentRef.current would still hold the old (closed) agent — causing\n // the transport to send messages to a dead WebSocket (issue #929).\n const agentRef = useRef(agent);\n agentRef.current = agent;\n\n async function defaultGetInitialMessagesFetch({\n url\n }: GetInitialMessagesOptions) {\n const getMessagesUrl = new URL(url);\n getMessagesUrl.pathname += \"/get-messages\";\n const response = await fetch(getMessagesUrl.toString(), {\n credentials: options.credentials,\n headers: options.headers\n });\n\n if (!response.ok) {\n console.warn(\n `Failed to fetch initial messages: ${response.status} ${response.statusText}`\n );\n return [];\n }\n\n const text = await response.text();\n if (!text.trim()) {\n return [];\n }\n\n try {\n return JSON.parse(text) as ChatMessage[];\n } catch (error) {\n console.warn(\"Failed to parse initial messages JSON:\", error);\n return [];\n }\n }\n\n const getInitialMessagesFetch =\n getInitialMessages || defaultGetInitialMessagesFetch;\n\n function doGetInitialMessages(\n getInitialMessagesOptions: GetInitialMessagesOptions,\n cacheKey: string\n ) {\n if (requestCache.has(cacheKey)) {\n return requestCache.get(cacheKey)! as Promise<ChatMessage[]>;\n }\n const promise = getInitialMessagesFetch(getInitialMessagesOptions);\n requestCache.set(cacheKey, promise);\n return promise;\n }\n\n const initialMessagesPromise =\n getInitialMessages === null\n ? null\n : doGetInitialMessages(\n {\n agent: agent.agent,\n name: agent.name,\n url: agentUrlString\n },\n initialMessagesCacheKey\n );\n const initialMessages = initialMessagesPromise\n ? use(initialMessagesPromise)\n : (optionsInitialMessages ?? []);\n\n useEffect(() => {\n if (!initialMessagesPromise) {\n return;\n }\n requestCache.set(initialMessagesCacheKey, initialMessagesPromise!);\n return () => {\n if (\n requestCache.get(initialMessagesCacheKey) === initialMessagesPromise\n ) {\n requestCache.delete(initialMessagesCacheKey);\n }\n };\n }, [initialMessagesCacheKey, initialMessagesPromise]);\n\n // Use synchronous ref updates to avoid race conditions between effect runs.\n // This ensures the ref always has the latest value before any effect reads it.\n const toolsRef = useRef(tools);\n toolsRef.current = tools;\n\n const prepareSendMessagesRequestRef = useRef(prepareSendMessagesRequest);\n prepareSendMessagesRequestRef.current = prepareSendMessagesRequest;\n\n const bodyOptionRef = useRef(bodyOption);\n bodyOptionRef.current = bodyOption;\n\n /**\n * Tracks request IDs initiated by this tab via the transport.\n * Used by onAgentMessage to skip messages already handled by the transport.\n */\n const localRequestIdsRef = useRef<Set<string>>(new Set());\n\n // WebSocket-based transport that speaks the CF_AGENT protocol natively.\n // Replaces the old aiFetch + DefaultChatTransport indirection.\n const customTransport = useMemo(\n () =>\n new WebSocketChatTransport<ChatMessage>({\n agent: agentRef.current,\n activeRequestIds: localRequestIdsRef.current,\n prepareBody: async ({ messages: msgs, trigger, messageId }) => {\n // Start with the top-level body option (static or dynamic)\n let extraBody: Record<string, unknown> = {};\n const currentBody = bodyOptionRef.current;\n if (currentBody) {\n const resolved =\n typeof currentBody === \"function\"\n ? await currentBody()\n : currentBody;\n extraBody = { ...resolved };\n }\n\n // Extract schemas from deprecated client tools (if any)\n // Only extract client tool schemas when deprecated tools option is used\n if (toolsRef.current) {\n const clientToolSchemas = extractClientToolSchemas(\n toolsRef.current\n );\n if (clientToolSchemas) {\n extraBody.clientTools = clientToolSchemas;\n }\n }\n\n // Apply user's prepareSendMessagesRequest callback (overrides body option)\n if (prepareSendMessagesRequestRef.current) {\n const userResult = await prepareSendMessagesRequestRef.current({\n id: agent._pk,\n messages: msgs,\n trigger,\n messageId\n });\n if (userResult.body) {\n Object.assign(extraBody, userResult.body);\n }\n }\n\n return extraBody;\n }\n }),\n [agent._pk]\n );\n\n const useChatHelpers = useChat<ChatMessage>({\n ...rest,\n onData,\n messages: initialMessages,\n transport: customTransport,\n id: agent._pk\n // Note: We handle stream resumption via WebSocket instead of HTTP,\n // so we don't pass 'resume' to useChat. The onStreamResuming handler\n // automatically resumes active streams when the WebSocket reconnects.\n });\n\n // Destructure stable method references from useChatHelpers.\n // These are individually memoized by the AI SDK (via useCallback), so they're\n // safe to use in dependency arrays without causing re-renders. Using them\n // directly instead of `useChatHelpers.method` avoids the exhaustive-deps\n // warning about the unstable `useChatHelpers` object.\n const {\n messages: chatMessages,\n setMessages,\n addToolResult,\n addToolApprovalResponse,\n sendMessage\n } = useChatHelpers;\n\n const processedToolCalls = useRef(new Set<string>());\n const isResolvingToolsRef = useRef(false);\n // Counter to force the tool resolution effect to re-run after completing\n // a batch of tool calls. Without this, if new tool calls arrive while\n // isResolvingToolsRef is true (e.g. server auto-continuation), the effect\n // exits early and never retriggers because the ref reset doesn't cause\n // a re-render.\n const [toolResolutionTrigger, setToolResolutionTrigger] = useState(0);\n\n // Fix for issue #728: Track client-side tool results in local state\n // to ensure tool parts show output-available immediately after execution.\n const [clientToolResults, setClientToolResults] = useState<\n Map<string, unknown>\n >(new Map());\n\n // Ref to access current messages in callbacks without stale closures\n const messagesRef = useRef(chatMessages);\n messagesRef.current = chatMessages;\n\n // Calculate pending confirmations for the latest assistant message\n const lastMessage = chatMessages[chatMessages.length - 1];\n\n const pendingConfirmations = (() => {\n if (!lastMessage || lastMessage.role !== \"assistant\") {\n return { messageId: undefined, toolCallIds: new Set<string>() };\n }\n\n const pendingIds = new Set<string>();\n for (const part of lastMessage.parts ?? []) {\n if (\n isToolUIPart(part) &&\n part.state === \"input-available\" &&\n toolsRequiringConfirmation.includes(getToolName(part))\n ) {\n pendingIds.add(part.toolCallId);\n }\n }\n return { messageId: lastMessage.id, toolCallIds: pendingIds };\n })();\n\n const pendingConfirmationsRef = useRef(pendingConfirmations);\n pendingConfirmationsRef.current = pendingConfirmations;\n\n // ── DEPRECATED: automatic tool resolution effect ────────────────────\n // This entire useEffect is deprecated. Use onToolCall instead.\n useEffect(() => {\n if (!experimental_automaticToolResolution) {\n return;\n }\n\n // Prevent re-entry while async operations are in progress\n if (isResolvingToolsRef.current) {\n return;\n }\n\n const lastMsg = chatMessages[chatMessages.length - 1];\n if (!lastMsg || lastMsg.role !== \"assistant\") {\n return;\n }\n\n const toolCalls = lastMsg.parts.filter(\n (part) =>\n isToolUIPart(part) &&\n part.state === \"input-available\" &&\n !processedToolCalls.current.has(part.toolCallId)\n );\n\n if (toolCalls.length > 0) {\n // Capture tools synchronously before async work\n const currentTools = toolsRef.current;\n const toolCallsToResolve = toolCalls.filter(\n (part) =>\n isToolUIPart(part) &&\n !toolsRequiringConfirmation.includes(getToolName(part)) &&\n currentTools?.[getToolName(part)]?.execute\n );\n\n if (toolCallsToResolve.length > 0) {\n isResolvingToolsRef.current = true;\n\n (async () => {\n try {\n const toolResults: Array<{\n toolCallId: string;\n toolName: string;\n output: unknown;\n }> = [];\n\n for (const part of toolCallsToResolve) {\n if (isToolUIPart(part)) {\n let toolOutput: unknown = null;\n const toolName = getToolName(part);\n const tool = currentTools?.[toolName];\n\n if (tool?.execute && part.input !== undefined) {\n try {\n toolOutput = await tool.execute(part.input);\n } catch (error) {\n toolOutput = `Error executing tool: ${error instanceof Error ? error.message : String(error)}`;\n }\n }\n\n processedToolCalls.current.add(part.toolCallId);\n\n toolResults.push({\n toolCallId: part.toolCallId,\n toolName,\n output: toolOutput\n });\n }\n }\n\n if (toolResults.length > 0) {\n // Send tool results to server first (server is source of truth)\n const clientToolSchemas = extractClientToolSchemas(currentTools);\n for (const result of toolResults) {\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_TOOL_RESULT,\n toolCallId: result.toolCallId,\n toolName: result.toolName,\n output: result.output,\n autoContinue: autoContinueAfterToolResult,\n clientTools: clientToolSchemas\n })\n );\n }\n\n // Also update local state via AI SDK for immediate UI feedback\n await Promise.all(\n toolResults.map((result) =>\n addToolResult({\n tool: result.toolName,\n toolCallId: result.toolCallId,\n output: result.output\n })\n )\n );\n\n setClientToolResults((prev) => {\n const newMap = new Map(prev);\n for (const result of toolResults) {\n newMap.set(result.toolCallId, result.output);\n }\n return newMap;\n });\n }\n\n // Note: We don't call sendMessage() here anymore.\n // The server will continue the conversation after applying tool results.\n } finally {\n isResolvingToolsRef.current = false;\n // Trigger a re-run so any tool calls that arrived while we were\n // busy (e.g. from server auto-continuation) get picked up.\n setToolResolutionTrigger((c) => c + 1);\n }\n })();\n }\n }\n }, [\n chatMessages,\n experimental_automaticToolResolution,\n addToolResult,\n toolsRequiringConfirmation,\n autoContinueAfterToolResult,\n toolResolutionTrigger\n ]);\n\n // Helper function to send tool output to server\n const sendToolOutputToServer = useCallback(\n (toolCallId: string, toolName: string, output: unknown) => {\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_TOOL_RESULT,\n toolCallId,\n toolName,\n output,\n autoContinue: autoContinueAfterToolResult,\n clientTools: toolsRef.current\n ? extractClientToolSchemas(toolsRef.current)\n : undefined\n })\n );\n\n setClientToolResults((prev) => new Map(prev).set(toolCallId, output));\n },\n [autoContinueAfterToolResult]\n );\n\n // Helper function to send tool approval to server\n const sendToolApprovalToServer = useCallback(\n (toolCallId: string, approved: boolean) => {\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_TOOL_APPROVAL,\n toolCallId,\n approved,\n autoContinue: autoContinueAfterToolResult\n })\n );\n },\n [autoContinueAfterToolResult]\n );\n\n // Effect for new onToolCall callback pattern (v6 style)\n // This fires when there are tool calls that need client-side handling\n useEffect(() => {\n const currentOnToolCall = onToolCallRef.current;\n if (!currentOnToolCall) {\n return;\n }\n\n const lastMsg = chatMessages[chatMessages.length - 1];\n if (!lastMsg || lastMsg.role !== \"assistant\") {\n return;\n }\n\n // Find tool calls in input-available state that haven't been processed\n const pendingToolCalls = lastMsg.parts.filter(\n (part) =>\n isToolUIPart(part) &&\n part.state === \"input-available\" &&\n !processedToolCalls.current.has(part.toolCallId)\n );\n\n for (const part of pendingToolCalls) {\n if (isToolUIPart(part)) {\n const toolCallId = part.toolCallId;\n const toolName = getToolName(part);\n\n // Mark as processed to prevent re-triggering\n processedToolCalls.current.add(toolCallId);\n\n // Create addToolOutput function for this specific tool call\n const addToolOutput = (opts: {\n toolCallId: string;\n output: unknown;\n }) => {\n sendToolOutputToServer(opts.toolCallId, toolName, opts.output);\n\n // Update local state via AI SDK\n addToolResult({\n tool: toolName,\n toolCallId: opts.toolCallId,\n output: opts.output\n });\n };\n\n // Call the onToolCall callback\n // The callback is responsible for calling addToolOutput when ready\n currentOnToolCall({\n toolCall: {\n toolCallId,\n toolName,\n input: part.input\n },\n addToolOutput\n });\n }\n }\n }, [chatMessages, sendToolOutputToServer, addToolResult]);\n\n /**\n * Contains the request ID, accumulated message parts, metadata, and a unique message ID.\n * Used for both resumed streams and real-time broadcasts from other tabs.\n * Metadata is captured from start/finish/message-metadata stream chunks\n * so that it's included when the partial message is flushed to React state.\n */\n const activeStreamRef = useRef<{\n id: string;\n messageId: string;\n parts: ChatMessage[\"parts\"];\n metadata?: Record<string, unknown>;\n } | null>(null);\n\n /**\n * Flush the active stream's accumulated parts into React state.\n * Extracted as a helper so it can be called both during live streaming\n * (per-chunk) and after replay completes (once, at done).\n */\n const flushActiveStreamToMessages = useCallback(\n (activeMsg: {\n id: string;\n messageId: string;\n parts: ChatMessage[\"parts\"];\n metadata?: Record<string, unknown>;\n }) => {\n setMessages((prevMessages: ChatMessage[]) => {\n const existingIdx = prevMessages.findIndex(\n (m) => m.id === activeMsg.messageId\n );\n\n const partialMessage = {\n id: activeMsg.messageId,\n role: \"assistant\" as const,\n parts: [...activeMsg.parts],\n ...(activeMsg.metadata != null && { metadata: activeMsg.metadata })\n } as unknown as ChatMessage;\n\n if (existingIdx >= 0) {\n const updated = [...prevMessages];\n updated[existingIdx] = partialMessage;\n return updated;\n }\n return [...prevMessages, partialMessage];\n });\n },\n [setMessages]\n );\n\n useEffect(() => {\n /**\n * Unified message handler that parses JSON once and dispatches based on type.\n * Avoids duplicate parsing overhead from separate listeners.\n */\n function onAgentMessage(event: MessageEvent) {\n if (typeof event.data !== \"string\") return;\n\n let data: OutgoingMessage<ChatMessage>;\n try {\n data = JSON.parse(event.data) as OutgoingMessage<ChatMessage>;\n } catch (_error) {\n return;\n }\n\n switch (data.type) {\n case MessageType.CF_AGENT_CHAT_CLEAR:\n setMessages([]);\n break;\n\n case MessageType.CF_AGENT_CHAT_MESSAGES:\n setMessages(data.messages);\n break;\n\n case MessageType.CF_AGENT_MESSAGE_UPDATED:\n // Server updated a message (e.g., applied tool result)\n // Update the specific message in local state\n setMessages((prevMessages: ChatMessage[]) => {\n const updatedMessage = data.message;\n\n // First try to find by message ID\n let idx = prevMessages.findIndex((m) => m.id === updatedMessage.id);\n\n // If not found by ID, try to find by toolCallId\n // This handles the case where client has AI SDK-generated IDs\n // but server has server-generated IDs\n if (idx < 0) {\n const updatedToolCallIds = new Set(\n updatedMessage.parts\n .filter(\n (p: ChatMessage[\"parts\"][number]) =>\n \"toolCallId\" in p && p.toolCallId\n )\n .map(\n (p: ChatMessage[\"parts\"][number]) =>\n (p as { toolCallId: string }).toolCallId\n )\n );\n\n if (updatedToolCallIds.size > 0) {\n idx = prevMessages.findIndex((m) =>\n m.parts.some(\n (p) =>\n \"toolCallId\" in p &&\n updatedToolCallIds.has(\n (p as { toolCallId: string }).toolCallId\n )\n )\n );\n }\n }\n\n if (idx >= 0) {\n const updated = [...prevMessages];\n // Preserve the client's message ID but update the content\n updated[idx] = {\n ...updatedMessage,\n id: prevMessages[idx].id\n };\n return updated;\n }\n // Message not found, append it\n return [...prevMessages, updatedMessage];\n });\n break;\n\n case MessageType.CF_AGENT_STREAM_RESUMING:\n if (!resume) return;\n // Clear any previous incomplete active stream to prevent memory leak\n activeStreamRef.current = null;\n // Initialize active stream state with unique ID\n activeStreamRef.current = {\n id: data.id,\n messageId: nanoid(),\n parts: []\n };\n // Send ACK to server - we're ready to receive chunks\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUME_ACK,\n id: data.id\n })\n );\n break;\n\n case MessageType.CF_AGENT_USE_CHAT_RESPONSE: {\n // Skip if this is a response to a request this tab initiated\n // (handled by the aiFetch listener instead)\n if (localRequestIdsRef.current.has(data.id)) return;\n\n // For continuations, find the last assistant message ID to append to\n const isContinuation = data.continuation === true;\n\n // Initialize stream state for broadcasts from other tabs\n if (\n !activeStreamRef.current ||\n activeStreamRef.current.id !== data.id\n ) {\n let messageId = nanoid();\n let existingParts: ChatMessage[\"parts\"] = [];\n let existingMetadata: Record<string, unknown> | undefined;\n\n // For continuations, use the last assistant message's ID, parts, and metadata\n if (isContinuation) {\n const currentMessages = messagesRef.current;\n for (let i = currentMessages.length - 1; i >= 0; i--) {\n if (currentMessages[i].role === \"assistant\") {\n messageId = currentMessages[i].id;\n existingParts = [...currentMessages[i].parts];\n if (currentMessages[i].metadata != null) {\n existingMetadata = {\n ...(currentMessages[i].metadata as Record<\n string,\n unknown\n >)\n };\n }\n break;\n }\n }\n }\n\n activeStreamRef.current = {\n id: data.id,\n messageId,\n parts: existingParts,\n metadata: existingMetadata\n };\n }\n\n const activeMsg = activeStreamRef.current;\n const isReplay = data.replay === true;\n\n if (data.body?.trim()) {\n try {\n const chunkData = JSON.parse(data.body);\n\n // Apply chunk to parts using shared parser.\n // Handles text, reasoning, file, source, tool, step, and data-* chunks.\n // Unrecognized types (tool-input-start, tool-input-delta, etc.)\n // are intermediate states — the final state is captured by\n // tool-input-available / tool-output-available.\n const handled = applyChunkToParts(\n activeMsg.parts as MessageParts,\n chunkData\n );\n\n // Fire onData callback for data-* parts (stream resumption\n // and cross-tab broadcasts). For the transport path (new\n // messages from this tab), the AI SDK's pipeline invokes\n // onData internally.\n if (\n typeof chunkData.type === \"string\" &&\n chunkData.type.startsWith(\"data-\") &&\n onDataRef.current\n ) {\n onDataRef.current(chunkData);\n }\n\n // Capture message metadata from start/finish/message-metadata\n // chunks. These carry metadata like timestamps, model info, and\n // token usage that should be attached at the message level.\n if (\n !handled &&\n (chunkData.type === \"start\" ||\n chunkData.type === \"finish\" ||\n chunkData.type === \"message-metadata\")\n ) {\n if (chunkData.messageId != null && chunkData.type === \"start\") {\n activeMsg.messageId = chunkData.messageId;\n }\n if (chunkData.messageMetadata != null) {\n activeMsg.metadata = activeMsg.metadata\n ? { ...activeMsg.metadata, ...chunkData.messageMetadata }\n : { ...chunkData.messageMetadata };\n }\n }\n\n // For replayed chunks, skip intermediate setMessages calls.\n // Replayed chunks arrive synchronously in a tight loop, so React\n // would batch all state updates into a single render anyway —\n // causing intermediate states (like \"Thinking...\") to be lost.\n // We defer the render until replay is complete (done signal).\n if (!isReplay) {\n flushActiveStreamToMessages(activeMsg);\n }\n } catch (parseError) {\n console.warn(\n \"[useAgentChat] Failed to parse stream chunk:\",\n parseError instanceof Error ? parseError.message : parseError,\n \"body:\",\n data.body?.slice(0, 100)\n );\n }\n }\n\n // On completion or error, flush final state to messages\n if (data.done || data.error) {\n // For replayed streams, this is the single render point —\n // all parts have been accumulated, now render them at once.\n if (isReplay && activeMsg) {\n flushActiveStreamToMessages(activeMsg);\n }\n activeStreamRef.current = null;\n }\n break;\n }\n }\n }\n\n agent.addEventListener(\"message\", onAgentMessage);\n\n // Request stream resume check AFTER the handler is registered.\n // This avoids the race condition where CF_AGENT_STREAM_RESUMING sent\n // in onConnect arrives before this useEffect runs. The server also\n // sends it in onConnect as a fallback for older clients.\n if (resume) {\n agent.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST\n })\n );\n }\n\n return () => {\n agent.removeEventListener(\"message\", onAgentMessage);\n // Clear active stream state on cleanup to prevent memory leak\n activeStreamRef.current = null;\n };\n }, [agent, setMessages, resume, flushActiveStreamToMessages]);\n\n // ── DEPRECATED: addToolResult wrapper with confirmation batching ────\n // This wrapper is deprecated. Use addToolOutput or addToolApprovalResponse instead.\n const addToolResultAndSendMessage: typeof addToolResult = async (args) => {\n const { toolCallId } = args;\n const toolName = \"tool\" in args ? args.tool : \"\";\n const output = \"output\" in args ? args.output : undefined;\n\n // Send tool result to server (server is source of truth)\n // Include flag to tell server whether to auto-continue\n agentRef.current.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_TOOL_RESULT,\n toolCallId,\n toolName,\n output,\n autoContinue: autoContinueAfterToolResult,\n clientTools: toolsRef.current\n ? extractClientToolSchemas(toolsRef.current)\n : undefined\n })\n );\n\n setClientToolResults((prev) => new Map(prev).set(toolCallId, output));\n\n // Call AI SDK's addToolResult for local state update (non-blocking)\n // We don't await this since clientToolResults provides immediate UI feedback\n addToolResult(args);\n\n // If server auto-continuation is disabled, client needs to trigger continuation\n if (!autoContinueAfterToolResult) {\n // Use legacy behavior: batch confirmations or send immediately\n if (!autoSendAfterAllConfirmationsResolved) {\n // Always send immediately\n sendMessage();\n return;\n }\n\n // Wait for all confirmations before sending\n const pending = pendingConfirmationsRef.current?.toolCallIds;\n if (!pending) {\n sendMessage();\n return;\n }\n\n const wasLast = pending.size === 1 && pending.has(toolCallId);\n if (pending.has(toolCallId)) {\n pending.delete(toolCallId);\n }\n\n if (wasLast || pending.size === 0) {\n sendMessage();\n }\n }\n // If autoContinueAfterToolResult is true, server handles continuation\n };\n\n // Wrapper that sends tool approval to server before updating local state.\n // This prevents duplicate messages by ensuring server updates the message\n // in place with the existing ID, rather than relying on ID resolution\n // when sendMessage() is called later.\n const addToolApprovalResponseAndNotifyServer: typeof addToolApprovalResponse =\n (args) => {\n const { id: approvalId, approved } = args;\n\n // Find the toolCallId from the approval ID\n // The approval ID is stored on the tool part's approval.id field\n let toolCallId: string | undefined;\n for (const msg of messagesRef.current) {\n for (const part of msg.parts) {\n if (\n \"toolCallId\" in part &&\n \"approval\" in part &&\n (part.approval as { id?: string })?.id === approvalId\n ) {\n toolCallId = part.toolCallId as string;\n break;\n }\n }\n if (toolCallId) break;\n }\n\n if (toolCallId) {\n // Send approval to server first (server updates message in place)\n sendToolApprovalToServer(toolCallId, approved);\n } else {\n console.warn(\n `[useAgentChat] addToolApprovalResponse: Could not find toolCallId for approval ID \"${approvalId}\". ` +\n \"Server will not be notified, which may cause duplicate messages.\"\n );\n }\n\n // Call AI SDK's addToolApprovalResponse for local state update\n addToolApprovalResponse(args);\n };\n\n // Fix for issue #728: Merge client-side tool results with messages\n // so tool parts show output-available immediately after execution\n const messagesWithToolResults = useMemo(() => {\n if (clientToolResults.size === 0) {\n return chatMessages;\n }\n return chatMessages.map((msg) => ({\n ...msg,\n parts: msg.parts.map((p) => {\n if (\n !(\"toolCallId\" in p) ||\n !(\"state\" in p) ||\n p.state !== \"input-available\" ||\n !clientToolResults.has(p.toolCallId)\n ) {\n return p;\n }\n return {\n ...p,\n state: \"output-available\" as const,\n output: clientToolResults.get(p.toolCallId)\n };\n })\n })) as ChatMessage[];\n }, [chatMessages, clientToolResults]);\n\n // Cleanup stale entries from clientToolResults when messages change\n // to prevent memory leak in long conversations.\n // Note: We intentionally exclude clientToolResults from deps to avoid infinite loops.\n // The functional update form gives us access to the previous state.\n useEffect(() => {\n // Collect all current toolCallIds from messages\n const currentToolCallIds = new Set<string>();\n for (const msg of chatMessages) {\n for (const part of msg.parts) {\n if (\"toolCallId\" in part && part.toolCallId) {\n currentToolCallIds.add(part.toolCallId);\n }\n }\n }\n\n // Use functional update to check and clean stale entries atomically\n setClientToolResults((prev) => {\n if (prev.size === 0) return prev;\n\n // Check if any entries are stale\n let hasStaleEntries = false;\n for (const toolCallId of prev.keys()) {\n if (!currentToolCallIds.has(toolCallId)) {\n hasStaleEntries = true;\n break;\n }\n }\n\n // Only create new Map if there are stale entries to remove\n if (!hasStaleEntries) return prev;\n\n const newMap = new Map<string, unknown>();\n for (const [id, output] of prev) {\n if (currentToolCallIds.has(id)) {\n newMap.set(id, output);\n }\n }\n return newMap;\n });\n\n // Also cleanup processedToolCalls to prevent issues in long conversations\n for (const toolCallId of processedToolCalls.current) {\n if (!currentToolCallIds.has(toolCallId)) {\n processedToolCalls.current.delete(toolCallId);\n }\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [chatMessages]);\n\n // Create addToolOutput function for external use\n const addToolOutput = useCallback(\n (opts: { toolCallId: string; toolName?: string; output: unknown }) => {\n const toolName = opts.toolName ?? \"\";\n sendToolOutputToServer(opts.toolCallId, toolName, opts.output);\n\n // Update local state via AI SDK\n addToolResult({\n tool: toolName,\n toolCallId: opts.toolCallId,\n output: opts.output\n });\n },\n [sendToolOutputToServer, addToolResult]\n );\n\n return {\n ...useChatHelpers,\n messages: messagesWithToolResults,\n /**\n * Provide output for a tool call. Use this for tools that require user interaction\n * or client-side execution.\n */\n addToolOutput,\n /**\n * @deprecated Use `addToolOutput` instead.\n */\n addToolResult: addToolResultAndSendMessage,\n /**\n * Respond to a tool approval request. Use this for tools with `needsApproval`.\n * This wrapper notifies the server before updating local state, preventing\n * duplicate messages when sendMessage() is called afterward.\n */\n addToolApprovalResponse: addToolApprovalResponseAndNotifyServer,\n clearHistory: () => {\n setMessages([]);\n setClientToolResults(new Map());\n processedToolCalls.current.clear();\n agent.send(\n JSON.stringify({\n type: MessageType.CF_AGENT_CHAT_CLEAR\n })\n );\n },\n setMessages: (messagesOrUpdater: Parameters<typeof setMessages>[0]) => {\n // Resolve functional updaters to get the actual messages array\n // before syncing to server. Without this, updater functions would\n // send an empty array and wipe server-side messages.\n let resolvedMessages: ChatMessage[];\n if (typeof messagesOrUpdater === \"function\") {\n resolvedMessages = messagesOrUpdater(messagesRef.current);\n } else {\n resolvedMessages = messagesOrUpdater;\n }\n\n setMessages(resolvedMessages);\n agent.send(\n JSON.stringify({\n messages: resolvedMessages,\n type: MessageType.CF_AGENT_CHAT_MESSAGES\n })\n );\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;AA0DA,IAAa,yBAAb,MAEwC;CAKtC,YAAY,SAAqD;AAC/D,OAAK,QAAQ,QAAQ;AACrB,OAAK,cAAc,QAAQ;AAC3B,OAAK,mBAAmB,QAAQ;;CAGlC,MAAM,aAAa,SASyB;EAC1C,MAAM,YAAY,OAAO,EAAE;EAC3B,MAAM,kBAAkB,IAAI,iBAAiB;EAC7C,IAAI,YAAY;EAGhB,IAAI,YAAqC,EAAE;AAC3C,MAAI,KAAK,YACP,aAAY,MAAM,KAAK,YAAY;GACjC,UAAU,QAAQ;GAClB,SAAS,QAAQ;GACjB,WAAW,QAAQ;GACpB,CAAC;AAEJ,MAAI,QAAQ,KACV,aAA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CAAC,mBAAmB,IAAI,WAAW,CACrC,oBAAmB,QAAQ,OAAO,WAAW;IAIhD,CAAC,aAAa,CAAC;CAGlB,MAAM,gBAAgB,aACnB,SAAqE;EACpE,MAAM,WAAW,KAAK,YAAY;AAClC,yBAAuB,KAAK,YAAY,UAAU,KAAK,OAAO;AAG9D,gBAAc;GACZ,MAAM;GACN,YAAY,KAAK;GACjB,QAAQ,KAAK;GACd,CAAC;IAEJ,CAAC,wBAAwB,cAAc,CACxC;AAED,QAAO;EACL,GAAG;EACH,UAAU;EAKV;EAIA,eAAe;EAMf,yBAAyB;EACzB,oBAAoB;AAClB,eAAY,EAAE,CAAC;AACf,wCAAqB,IAAI,KAAK,CAAC;AAC/B,sBAAmB,QAAQ,OAAO;AAClC,SAAM,KACJ,KAAK,UAAU,EACb,MAAM,YAAY,qBACnB,CAAC,CACH;;EAEH,cAAc,sBAAyD;GAIrE,IAAI;AACJ,OAAI,OAAO,sBAAsB,WAC/B,oBAAmB,kBAAkB,YAAY,QAAQ;OAEzD,oBAAmB;AAGrB,eAAY,iBAAiB;AAC7B,SAAM,KACJ,KAAK,UAAU;IACb,UAAU;IACV,MAAM,YAAY;IACnB,CAAC,CACH;;EAEJ"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Playwright global setup: kill any stale process on the test port
|
|
3
|
+
* left behind by a previous run that was forcefully terminated.
|
|
4
|
+
*/
|
|
5
|
+
import { execSync } from "node:child_process";
|
|
6
|
+
|
|
7
|
+
const PORT = 8799;
|
|
8
|
+
|
|
9
|
+
function killProcessOnPort(port: number): void {
|
|
10
|
+
try {
|
|
11
|
+
const output = execSync(`lsof -ti tcp:${port} 2>/dev/null || true`)
|
|
12
|
+
.toString()
|
|
13
|
+
.trim();
|
|
14
|
+
if (output) {
|
|
15
|
+
const pids = output.split("\n").filter(Boolean);
|
|
16
|
+
for (const pid of pids) {
|
|
17
|
+
try {
|
|
18
|
+
process.kill(Number(pid), "SIGKILL");
|
|
19
|
+
console.log(
|
|
20
|
+
`[global-setup] Killed stale process ${pid} on port ${port}`
|
|
21
|
+
);
|
|
22
|
+
} catch {
|
|
23
|
+
// Process may have already exited
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
} catch {
|
|
28
|
+
// lsof not available or other error — ignore
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export default function globalSetup() {
|
|
33
|
+
killProcessOnPort(PORT);
|
|
34
|
+
}
|
package/e2e/playwright.config.ts
CHANGED
|
@@ -12,6 +12,8 @@ export default defineConfig({
|
|
|
12
12
|
timeout: 30_000,
|
|
13
13
|
retries: 0,
|
|
14
14
|
workers: 1, // Sequential — single wrangler dev instance
|
|
15
|
+
// Kill stale processes on the test port before starting
|
|
16
|
+
globalSetup: [join(e2eDir, "global-setup.ts")],
|
|
15
17
|
use: {
|
|
16
18
|
baseURL: `http://localhost:${PORT}`
|
|
17
19
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cloudflare/ai-chat",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "Cloudflare Agents (x) AI SDK Chat",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -21,12 +21,13 @@
|
|
|
21
21
|
"devDependencies": {
|
|
22
22
|
"@playwright/test": "^1.58.2",
|
|
23
23
|
"@types/react": "^19.2.14",
|
|
24
|
-
"ai": "^6.0.
|
|
24
|
+
"ai": "^6.0.88",
|
|
25
25
|
"react": "^19.2.4",
|
|
26
26
|
"vitest-browser-react": "^1.0.1",
|
|
27
27
|
"zod": "^4.3.6"
|
|
28
28
|
},
|
|
29
29
|
"peerDependencies": {
|
|
30
|
+
"@ai-sdk/react": "^3.0.0",
|
|
30
31
|
"agents": "^0.5.0",
|
|
31
32
|
"ai": "^6.0.0",
|
|
32
33
|
"react": "^19.0.0",
|
|
@@ -1358,3 +1358,78 @@ describe("useAgentChat body option", () => {
|
|
|
1358
1358
|
expect(sentMessages).toBeDefined();
|
|
1359
1359
|
});
|
|
1360
1360
|
});
|
|
1361
|
+
|
|
1362
|
+
describe("useAgentChat stale agent ref (issue #929)", () => {
|
|
1363
|
+
it("should use the new agent's send method after agent switch, not the old one", async () => {
|
|
1364
|
+
const oldSend = vi.fn();
|
|
1365
|
+
const newSend = vi.fn();
|
|
1366
|
+
|
|
1367
|
+
const agentOld = createAgent({
|
|
1368
|
+
name: "thread-old",
|
|
1369
|
+
url: "ws://localhost:3000/agents/chat/thread-old?_pk=old",
|
|
1370
|
+
send: oldSend
|
|
1371
|
+
});
|
|
1372
|
+
|
|
1373
|
+
const agentNew = createAgent({
|
|
1374
|
+
name: "thread-new",
|
|
1375
|
+
url: "ws://localhost:3000/agents/chat/thread-new?_pk=new",
|
|
1376
|
+
send: newSend
|
|
1377
|
+
});
|
|
1378
|
+
|
|
1379
|
+
let chatInstance: ReturnType<typeof useAgentChat> | null = null;
|
|
1380
|
+
|
|
1381
|
+
const TestComponent = ({
|
|
1382
|
+
agent
|
|
1383
|
+
}: {
|
|
1384
|
+
agent: ReturnType<typeof useAgent>;
|
|
1385
|
+
}) => {
|
|
1386
|
+
const chat = useAgentChat({
|
|
1387
|
+
agent,
|
|
1388
|
+
getInitialMessages: null,
|
|
1389
|
+
messages: [] as UIMessage[]
|
|
1390
|
+
});
|
|
1391
|
+
chatInstance = chat;
|
|
1392
|
+
return <div data-testid="status">{chat.status}</div>;
|
|
1393
|
+
};
|
|
1394
|
+
|
|
1395
|
+
const screen = await act(async () => {
|
|
1396
|
+
const screen = render(<TestComponent agent={agentOld} />, {
|
|
1397
|
+
wrapper: ({ children }) => (
|
|
1398
|
+
<StrictMode>
|
|
1399
|
+
<Suspense fallback="Loading...">{children}</Suspense>
|
|
1400
|
+
</StrictMode>
|
|
1401
|
+
)
|
|
1402
|
+
});
|
|
1403
|
+
await sleep(10);
|
|
1404
|
+
return screen;
|
|
1405
|
+
});
|
|
1406
|
+
|
|
1407
|
+
// Switch to the new agent
|
|
1408
|
+
await act(async () => {
|
|
1409
|
+
screen.rerender(<TestComponent agent={agentNew} />);
|
|
1410
|
+
await sleep(10);
|
|
1411
|
+
});
|
|
1412
|
+
|
|
1413
|
+
// Clear any sends that happened during setup (e.g., stream resume requests)
|
|
1414
|
+
oldSend.mockClear();
|
|
1415
|
+
newSend.mockClear();
|
|
1416
|
+
|
|
1417
|
+
// Clear history triggers agent.send() — this should go to the NEW agent
|
|
1418
|
+
await act(async () => {
|
|
1419
|
+
chatInstance!.clearHistory();
|
|
1420
|
+
await sleep(10);
|
|
1421
|
+
});
|
|
1422
|
+
|
|
1423
|
+
// The clear message should have been sent to the NEW agent, not the old one
|
|
1424
|
+
const newSendCalls = newSend.mock.calls
|
|
1425
|
+
.map((args) => JSON.parse(args[0] as string))
|
|
1426
|
+
.filter((m: Record<string, unknown>) => m.type === "cf_agent_chat_clear");
|
|
1427
|
+
expect(newSendCalls.length).toBe(1);
|
|
1428
|
+
|
|
1429
|
+
// The old agent should NOT have received the clear message
|
|
1430
|
+
const oldSendCalls = oldSend.mock.calls
|
|
1431
|
+
.map((args) => JSON.parse(args[0] as string))
|
|
1432
|
+
.filter((m: Record<string, unknown>) => m.type === "cf_agent_chat_clear");
|
|
1433
|
+
expect(oldSendCalls.length).toBe(0);
|
|
1434
|
+
});
|
|
1435
|
+
});
|
package/src/react.tsx
CHANGED
|
@@ -444,11 +444,15 @@ export function useAgentChat<
|
|
|
444
444
|
// is updated synchronously, so each thread gets its own cache entry
|
|
445
445
|
const initialMessagesCacheKey = `${agentUrlString}|${agent.agent ?? ""}|${agent.name ?? ""}`;
|
|
446
446
|
|
|
447
|
-
// Keep a ref to always point to the latest agent instance
|
|
447
|
+
// Keep a ref to always point to the latest agent instance.
|
|
448
|
+
// Updated synchronously during render (not in useEffect) to ensure
|
|
449
|
+
// useMemo and other synchronous code always sees the latest agent.
|
|
450
|
+
// Using useEffect would cause a race: when agent._pk changes, useMemo
|
|
451
|
+
// re-evaluates during render but the effect hasn't fired yet, so
|
|
452
|
+
// agentRef.current would still hold the old (closed) agent — causing
|
|
453
|
+
// the transport to send messages to a dead WebSocket (issue #929).
|
|
448
454
|
const agentRef = useRef(agent);
|
|
449
|
-
|
|
450
|
-
agentRef.current = agent;
|
|
451
|
-
}, [agent]);
|
|
455
|
+
agentRef.current = agent;
|
|
452
456
|
|
|
453
457
|
async function defaultGetInitialMessagesFetch({
|
|
454
458
|
url
|