@cloudflare/ai-chat 0.1.4 → 0.1.6

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.
Files changed (66) hide show
  1. package/dist/experimental/forever.d.ts +4 -13
  2. package/dist/experimental/forever.js +1 -46
  3. package/dist/experimental/forever.js.map +1 -1
  4. package/dist/index.d.ts +59 -4
  5. package/dist/index.js +170 -28
  6. package/dist/index.js.map +1 -1
  7. package/dist/{message-builder-Bwc_Umye.js → message-builder-uSvexDl2.js} +17 -4
  8. package/dist/message-builder-uSvexDl2.js.map +1 -0
  9. package/dist/react.js +125 -31
  10. package/dist/react.js.map +1 -1
  11. package/dist/{resumable-stream-DqXxQVjf.d.ts → resumable-stream-DTLAk9XC.d.ts} +25 -2
  12. package/dist/types.d.ts +2 -1
  13. package/dist/types.js.map +1 -1
  14. package/package.json +7 -3
  15. package/CHANGELOG.md +0 -244
  16. package/dist/message-builder-Bwc_Umye.js.map +0 -1
  17. package/e2e/chat.spec.ts +0 -1703
  18. package/e2e/client-tools.spec.ts +0 -504
  19. package/e2e/llm.spec.ts +0 -637
  20. package/e2e/playwright.config.ts +0 -27
  21. package/e2e/worker.ts +0 -174
  22. package/e2e/wrangler.jsonc +0 -23
  23. package/scripts/build.ts +0 -32
  24. package/src/ai-chat-v5-migration.ts +0 -403
  25. package/src/experimental/forever.ts +0 -66
  26. package/src/index.ts +0 -2269
  27. package/src/message-builder.ts +0 -384
  28. package/src/react-tests/setup.ts +0 -3
  29. package/src/react-tests/use-agent-chat.test.tsx +0 -1435
  30. package/src/react-tests/vitest.config.ts +0 -20
  31. package/src/react.tsx +0 -1447
  32. package/src/resumable-stream.ts +0 -441
  33. package/src/tests/cancel-request.test.ts +0 -280
  34. package/src/tests/chat-context.test.ts +0 -85
  35. package/src/tests/chat-persistence.test.ts +0 -426
  36. package/src/tests/clear-history.test.ts +0 -132
  37. package/src/tests/client-tool-duplicate-message.test.ts +0 -1957
  38. package/src/tests/client-tools-broadcast.test.ts +0 -138
  39. package/src/tests/client-tools-continuation.test.ts +0 -314
  40. package/src/tests/client-tools-reconnect.test.ts +0 -143
  41. package/src/tests/cloudflare-test.d.ts +0 -5
  42. package/src/tests/custom-body-continuation.test.ts +0 -309
  43. package/src/tests/custom-body.test.ts +0 -186
  44. package/src/tests/destroy.test.ts +0 -57
  45. package/src/tests/get-messages-endpoint.test.ts +0 -153
  46. package/src/tests/max-persisted-messages.test.ts +0 -201
  47. package/src/tests/merge-server-state.test.ts +0 -343
  48. package/src/tests/message-builder.test.ts +0 -808
  49. package/src/tests/migration.test.ts +0 -282
  50. package/src/tests/non-sse-response.test.ts +0 -186
  51. package/src/tests/onfinish-cleanup.test.ts +0 -362
  52. package/src/tests/plaintext-response.test.ts +0 -87
  53. package/src/tests/request-id.test.ts +0 -312
  54. package/src/tests/resumable-streaming.test.ts +0 -758
  55. package/src/tests/row-size-guard.test.ts +0 -374
  56. package/src/tests/sanitize-messages.test.ts +0 -325
  57. package/src/tests/test-utils.ts +0 -39
  58. package/src/tests/tsconfig.json +0 -10
  59. package/src/tests/validate-messages.test.ts +0 -269
  60. package/src/tests/vitest.config.ts +0 -30
  61. package/src/tests/worker.ts +0 -456
  62. package/src/tests/wrangler.jsonc +0 -50
  63. package/src/types.ts +0 -152
  64. package/src/ws-chat-transport.ts +0 -203
  65. package/tsconfig.json +0 -4
  66. package/vitest.config.ts +0 -7
package/src/react.tsx DELETED
@@ -1,1447 +0,0 @@
1
- import { useChat, type UseChatOptions } from "@ai-sdk/react";
2
- import { getToolName, isToolUIPart } from "ai";
3
- import type {
4
- ChatInit,
5
- JSONSchema7,
6
- Tool,
7
- UIMessage as Message,
8
- UIMessage
9
- } from "ai";
10
- import { nanoid } from "nanoid";
11
- import { use, useCallback, useEffect, useMemo, useRef, useState } from "react";
12
- import type { OutgoingMessage } from "./types";
13
- import { MessageType } from "./types";
14
- import { applyChunkToParts, type MessageParts } from "./message-builder";
15
- import { WebSocketChatTransport } from "./ws-chat-transport";
16
- import type { useAgent } from "agents/react";
17
-
18
- /**
19
- * One-shot deprecation warnings (warns once per key per session).
20
- */
21
- const _deprecationWarnings = new Set<string>();
22
- function warnDeprecated(id: string, message: string) {
23
- if (!_deprecationWarnings.has(id)) {
24
- _deprecationWarnings.add(id);
25
- console.warn(`[@cloudflare/ai-chat] Deprecated: ${message}`);
26
- }
27
- }
28
-
29
- // ── DEPRECATED TYPES AND FUNCTIONS ──────────────────────────────────
30
- // Everything in this section is deprecated and will be removed in the
31
- // next major version. Use server-side tools with tool() from "ai" and
32
- // the onToolCall callback in useAgentChat instead.
33
-
34
- /**
35
- * JSON Schema type for tool parameters.
36
- * Re-exported from the AI SDK for convenience.
37
- * @deprecated Import JSONSchema7 directly from "ai" instead. Will be removed in the next major version.
38
- */
39
- export type JSONSchemaType = JSONSchema7;
40
-
41
- /**
42
- * Definition for a tool that can be executed on the client.
43
- * Tools with an `execute` function are automatically registered with the server.
44
- *
45
- * **For most apps**, define tools on the server with `tool()` from `"ai"` —
46
- * you get full Zod type safety and simpler code. Use `onToolCall` in
47
- * `useAgentChat` for tools that need browser-side execution.
48
- *
49
- * **For SDKs and platforms** where the tool surface is determined dynamically
50
- * by the embedding application at runtime, this type lets the client register
51
- * tools the server does not know about at deploy time.
52
- *
53
- * Note: Uses `parameters` (JSONSchema7) because client tools must be
54
- * serializable for the wire format. Zod schemas cannot be serialized.
55
- */
56
- export type AITool<Input = unknown, Output = unknown> = {
57
- /** Human-readable description of what the tool does */
58
- description?: Tool["description"];
59
- /** JSON Schema defining the tool's input parameters */
60
- parameters?: JSONSchema7;
61
- /**
62
- * @deprecated Use `parameters` instead. Will be removed in a future version.
63
- */
64
- inputSchema?: JSONSchema7;
65
- /**
66
- * Function to execute the tool on the client.
67
- * If provided, the tool schema is automatically sent to the server.
68
- */
69
- execute?: (input: Input) => Output | Promise<Output>;
70
- };
71
-
72
- /**
73
- * Schema for a client tool sent to the server.
74
- * This is the wire format — what gets sent in the request body.
75
- * Must match the server-side ClientToolSchema type.
76
- *
77
- * Most apps do not need this directly — it is used internally when the
78
- * `tools` option on `useAgentChat` contains tools with `execute` functions.
79
- */
80
- export type ClientToolSchema = {
81
- /** Unique name for the tool */
82
- name: string;
83
- /** Human-readable description of what the tool does */
84
- description?: Tool["description"];
85
- /** JSON Schema defining the tool's input parameters */
86
- parameters?: JSONSchema7;
87
- };
88
-
89
- /**
90
- * Extracts tool schemas from tools that have client-side execute functions.
91
- * These schemas are automatically sent to the server with each request.
92
- *
93
- * Called internally by `useAgentChat` when `tools` are provided.
94
- * Most apps do not need to call this directly.
95
- *
96
- * @param tools - Record of tool name to tool definition
97
- * @returns Array of tool schemas to send to server, or undefined if none
98
- */
99
- export function extractClientToolSchemas(
100
- tools?: Record<string, AITool<unknown, unknown>>
101
- ): ClientToolSchema[] | undefined {
102
- if (!tools) return undefined;
103
-
104
- const schemas: ClientToolSchema[] = Object.entries(tools)
105
- .filter(([_, tool]) => tool.execute) // Only tools with client-side execute
106
- .map(([name, tool]) => {
107
- if (tool.inputSchema && !tool.parameters) {
108
- console.warn(
109
- `[useAgentChat] Tool "${name}" uses deprecated 'inputSchema'. Please migrate to 'parameters'.`
110
- );
111
- }
112
- return {
113
- name,
114
- description: tool.description,
115
- parameters: tool.parameters ?? tool.inputSchema
116
- };
117
- });
118
-
119
- return schemas.length > 0 ? schemas : undefined;
120
- }
121
-
122
- // ── END DEPRECATED TYPES AND FUNCTIONS ─────────────────────────────
123
-
124
- type GetInitialMessagesOptions = {
125
- agent: string;
126
- name: string;
127
- url: string;
128
- };
129
-
130
- // v5 useChat parameters
131
- type UseChatParams<M extends UIMessage = UIMessage> = ChatInit<M> &
132
- UseChatOptions<M>;
133
-
134
- /**
135
- * Options for preparing the send messages request.
136
- * Used by prepareSendMessagesRequest callback.
137
- */
138
- export type PrepareSendMessagesRequestOptions<
139
- ChatMessage extends UIMessage = UIMessage
140
- > = {
141
- /** The chat ID */
142
- id: string;
143
- /** Messages to send */
144
- messages: ChatMessage[];
145
- /** What triggered this request */
146
- trigger: "submit-message" | "regenerate-message";
147
- /** ID of the message being sent (if applicable) */
148
- messageId?: string;
149
- /** Request metadata */
150
- requestMetadata?: unknown;
151
- /** Current body (if any) */
152
- body?: Record<string, unknown>;
153
- /** Current credentials (if any) */
154
- credentials?: RequestCredentials;
155
- /** Current headers (if any) */
156
- headers?: HeadersInit;
157
- /** API endpoint */
158
- api?: string;
159
- };
160
-
161
- /**
162
- * Return type for prepareSendMessagesRequest callback.
163
- * Allows customizing headers, body, and credentials for each request.
164
- * All fields are optional; only specify what you need to customize.
165
- */
166
- export type PrepareSendMessagesRequestResult = {
167
- /** Custom headers to send with the request */
168
- headers?: HeadersInit;
169
- /** Custom body data to merge with the request */
170
- body?: Record<string, unknown>;
171
- /** Custom credentials option */
172
- credentials?: RequestCredentials;
173
- /** Custom API endpoint */
174
- api?: string;
175
- };
176
-
177
- /**
178
- * Options for addToolOutput function
179
- */
180
- type AddToolOutputOptions = {
181
- /** The ID of the tool call to provide output for */
182
- toolCallId: string;
183
- /** The name of the tool (optional, for type safety) */
184
- toolName?: string;
185
- /** The output to provide */
186
- output?: unknown;
187
- /** Override the tool part state (e.g. "output-error" for custom denial) */
188
- state?: "output-available" | "output-error";
189
- /** Error message when state is "output-error" */
190
- errorText?: string;
191
- };
192
-
193
- /**
194
- * Callback for handling client-side tool execution.
195
- * Called when a tool without server-side execute is invoked.
196
- */
197
- export type OnToolCallCallback = (options: {
198
- /** The tool call that needs to be handled */
199
- toolCall: {
200
- toolCallId: string;
201
- toolName: string;
202
- input: unknown;
203
- };
204
- /** Function to provide the tool output (or signal an error/denial) */
205
- addToolOutput: (options: Omit<AddToolOutputOptions, "toolName">) => void;
206
- }) => void | Promise<void>;
207
-
208
- /**
209
- * Options for the useAgentChat hook
210
- */
211
- type UseAgentChatOptions<
212
- State,
213
- ChatMessage extends UIMessage = UIMessage
214
- > = Omit<UseChatParams<ChatMessage>, "fetch" | "onToolCall"> & {
215
- /** Agent connection from useAgent */
216
- agent: ReturnType<typeof useAgent<State>>;
217
- getInitialMessages?:
218
- | undefined
219
- | null
220
- | ((options: GetInitialMessagesOptions) => Promise<ChatMessage[]>);
221
- /** Request credentials */
222
- credentials?: RequestCredentials;
223
- /** Request headers */
224
- headers?: HeadersInit;
225
- /**
226
- * Callback for handling client-side tool execution.
227
- * Called when a tool without server-side `execute` is invoked by the LLM.
228
- *
229
- * Use this for:
230
- * - Tools that need browser APIs (geolocation, camera, etc.)
231
- * - Tools that need user interaction before providing a result
232
- * - Tools requiring approval before execution
233
- *
234
- * @example
235
- * ```typescript
236
- * onToolCall: async ({ toolCall, addToolOutput }) => {
237
- * if (toolCall.toolName === 'getLocation') {
238
- * const position = await navigator.geolocation.getCurrentPosition();
239
- * addToolOutput({
240
- * toolCallId: toolCall.toolCallId,
241
- * output: { lat: position.coords.latitude, lng: position.coords.longitude }
242
- * });
243
- * }
244
- * }
245
- * ```
246
- */
247
- onToolCall?: OnToolCallCallback;
248
- /**
249
- * @deprecated Use `onToolCall` callback instead for automatic tool execution.
250
- * @description Whether to automatically resolve tool calls that do not require human interaction.
251
- * @experimental
252
- */
253
- experimental_automaticToolResolution?: boolean;
254
- /**
255
- * Tools that can be executed on the client. Tool schemas are automatically
256
- * sent to the server and tool calls are routed back for client execution.
257
- *
258
- * **For most apps**, define tools on the server with `tool()` from `"ai"`
259
- * and handle client-side execution via `onToolCall`. This gives you full
260
- * Zod type safety and keeps tool definitions in one place.
261
- *
262
- * **For SDKs and platforms** where tools are defined dynamically by the
263
- * embedding application at runtime, this option lets the client register
264
- * tools the server does not know about at deploy time.
265
- */
266
- tools?: Record<string, AITool<unknown, unknown>>;
267
- /**
268
- * @deprecated Use `needsApproval` on server-side tools instead.
269
- * @description Manual override for tools requiring confirmation.
270
- * If not provided, will auto-detect from tools object (tools without execute require confirmation).
271
- */
272
- toolsRequiringConfirmation?: string[];
273
- /**
274
- * When true (default), the server automatically continues the conversation
275
- * after receiving client-side tool results or approvals, similar to how
276
- * server-executed tools work with maxSteps in streamText. The continuation
277
- * is merged into the same assistant message.
278
- *
279
- * When false, the client must call sendMessage() after tool results
280
- * to continue the conversation, which creates a new assistant message.
281
- *
282
- * @default true
283
- */
284
- autoContinueAfterToolResult?: boolean;
285
- /**
286
- * @deprecated Use `sendAutomaticallyWhen` from AI SDK instead.
287
- *
288
- * When true (default), automatically sends the next message only after
289
- * all pending confirmation-required tool calls have been resolved.
290
- * When false, sends immediately after each tool result.
291
- *
292
- * Only applies when `autoContinueAfterToolResult` is false.
293
- *
294
- * @default true
295
- */
296
- autoSendAfterAllConfirmationsResolved?: boolean;
297
- /**
298
- * Set to false to disable automatic stream resumption.
299
- * @default true
300
- */
301
- resume?: boolean;
302
- /**
303
- * Custom data to include in every chat request body.
304
- * Accepts a static object or a function that returns one (for dynamic values).
305
- * These fields are available in `onChatMessage` via `options.body`.
306
- *
307
- * @example
308
- * ```typescript
309
- * // Static
310
- * body: { timezone: "America/New_York", userId: "abc" }
311
- *
312
- * // Dynamic (called on each send)
313
- * body: () => ({ token: getAuthToken(), timestamp: Date.now() })
314
- * ```
315
- */
316
- body?:
317
- | Record<string, unknown>
318
- | (() => Record<string, unknown> | Promise<Record<string, unknown>>);
319
- /**
320
- * Callback to customize the request before sending messages.
321
- * For most cases, use the `body` option instead.
322
- * Use this for advanced scenarios that need access to the messages or trigger type.
323
- *
324
- * Note: Client tool schemas are automatically sent when tools have `execute` functions.
325
- * This callback can add additional data alongside the auto-extracted schemas.
326
- */
327
- prepareSendMessagesRequest?: (
328
- options: PrepareSendMessagesRequestOptions<ChatMessage>
329
- ) =>
330
- | PrepareSendMessagesRequestResult
331
- | Promise<PrepareSendMessagesRequestResult>;
332
- };
333
-
334
- /**
335
- * Module-level cache for initial message fetches. Intentionally shared across
336
- * all useAgentChat instances to deduplicate requests during React Strict Mode
337
- * double-renders and re-renders. Cache keys include the agent URL, agent type,
338
- * and thread name to prevent cross-agent collisions.
339
- */
340
- const requestCache = new Map<string, Promise<Message[]>>();
341
-
342
- /**
343
- * React hook for building AI chat interfaces using an Agent
344
- * @param options Chat options including the agent connection
345
- * @returns Chat interface controls and state with added clearHistory method
346
- */
347
- /**
348
- * Automatically detects which tools require confirmation based on their configuration.
349
- * Tools require confirmation if they have no execute function AND are not server-executed.
350
- * @param tools - Record of tool name to tool definition
351
- * @returns Array of tool names that require confirmation
352
- *
353
- * @deprecated Use `needsApproval` on server-side tools instead.
354
- */
355
- export function detectToolsRequiringConfirmation(
356
- tools?: Record<string, AITool<unknown, unknown>>
357
- ): string[] {
358
- warnDeprecated(
359
- "detectToolsRequiringConfirmation",
360
- "detectToolsRequiringConfirmation() is deprecated. Use needsApproval on server-side tools instead. Will be removed in the next major version."
361
- );
362
- if (!tools) return [];
363
-
364
- return Object.entries(tools)
365
- .filter(([_name, tool]) => !tool.execute)
366
- .map(([name]) => name);
367
- }
368
-
369
- export function useAgentChat<
370
- State = unknown,
371
- ChatMessage extends UIMessage = UIMessage
372
- >(
373
- options: UseAgentChatOptions<State, ChatMessage>
374
- ): Omit<ReturnType<typeof useChat<ChatMessage>>, "addToolOutput"> & {
375
- clearHistory: () => void;
376
- /**
377
- * Provide output for a tool call. Use this for tools that require user interaction
378
- * or client-side execution.
379
- */
380
- addToolOutput: (opts: AddToolOutputOptions) => void;
381
- } {
382
- const {
383
- agent,
384
- getInitialMessages,
385
- messages: optionsInitialMessages,
386
- onToolCall,
387
- onData,
388
- experimental_automaticToolResolution,
389
- tools,
390
- toolsRequiringConfirmation: manualToolsRequiringConfirmation,
391
- autoContinueAfterToolResult = true, // Server auto-continues after tool results/approvals
392
- autoSendAfterAllConfirmationsResolved = true, // Legacy option for client-side batching
393
- resume = true, // Enable stream resumption by default
394
- body: bodyOption,
395
- prepareSendMessagesRequest,
396
- ...rest
397
- } = options;
398
-
399
- // Emit deprecation warnings for deprecated options (once per session)
400
- if (manualToolsRequiringConfirmation) {
401
- warnDeprecated(
402
- "useAgentChat.toolsRequiringConfirmation",
403
- "The 'toolsRequiringConfirmation' option is deprecated. Use needsApproval on server-side tools instead. Will be removed in the next major version."
404
- );
405
- }
406
- if (experimental_automaticToolResolution) {
407
- warnDeprecated(
408
- "useAgentChat.experimental_automaticToolResolution",
409
- "The 'experimental_automaticToolResolution' option is deprecated. Use the onToolCall callback instead. Will be removed in the next major version."
410
- );
411
- }
412
- if (options.autoSendAfterAllConfirmationsResolved !== undefined) {
413
- warnDeprecated(
414
- "useAgentChat.autoSendAfterAllConfirmationsResolved",
415
- "The 'autoSendAfterAllConfirmationsResolved' option is deprecated. Use sendAutomaticallyWhen from AI SDK instead. Will be removed in the next major version."
416
- );
417
- }
418
-
419
- // ── DEPRECATED: client-side tool confirmation ──────────────────────
420
- // This block will be removed when toolsRequiringConfirmation is removed.
421
- // Only call the deprecated function when deprecated options are actually used.
422
- const toolsRequiringConfirmation = useMemo(() => {
423
- if (manualToolsRequiringConfirmation) {
424
- return manualToolsRequiringConfirmation;
425
- }
426
- // Inline the logic from detectToolsRequiringConfirmation to avoid
427
- // emitting a deprecation warning when tools are provided via the
428
- // non-deprecated `tools` option.
429
- if (!tools) return [];
430
- return Object.entries(tools)
431
- .filter(([_name, tool]) => !tool.execute)
432
- .map(([name]) => name);
433
- }, [manualToolsRequiringConfirmation, tools]);
434
-
435
- // Keep refs to always point to the latest callbacks
436
- const onToolCallRef = useRef(onToolCall);
437
- onToolCallRef.current = onToolCall;
438
- const onDataRef = useRef(onData);
439
- onDataRef.current = onData;
440
-
441
- const agentUrl = new URL(
442
- `${
443
- // @ts-expect-error we're using a protected _url property that includes query params
444
- ((agent._url as string | null) || agent._pkurl)
445
- ?.replace("ws://", "http://")
446
- .replace("wss://", "https://")
447
- }`
448
- );
449
-
450
- agentUrl.searchParams.delete("_pk");
451
- const agentUrlString = agentUrl.toString();
452
-
453
- // we need to include agent.name in cache key to prevent collisions during agent switching.
454
- // The URL may be stale between updateProperties() and reconnect(), but agent.name
455
- // is updated synchronously, so each thread gets its own cache entry
456
- const initialMessagesCacheKey = `${agentUrlString}|${agent.agent ?? ""}|${agent.name ?? ""}`;
457
-
458
- // Keep a ref to always point to the latest agent instance.
459
- // Updated synchronously during render (not in useEffect) to ensure
460
- // useMemo and other synchronous code always sees the latest agent.
461
- // Using useEffect would cause a race: when agent._pk changes, useMemo
462
- // re-evaluates during render but the effect hasn't fired yet, so
463
- // agentRef.current would still hold the old (closed) agent — causing
464
- // the transport to send messages to a dead WebSocket (issue #929).
465
- const agentRef = useRef(agent);
466
- agentRef.current = agent;
467
-
468
- async function defaultGetInitialMessagesFetch({
469
- url
470
- }: GetInitialMessagesOptions) {
471
- const getMessagesUrl = new URL(url);
472
- getMessagesUrl.pathname += "/get-messages";
473
- const response = await fetch(getMessagesUrl.toString(), {
474
- credentials: options.credentials,
475
- headers: options.headers
476
- });
477
-
478
- if (!response.ok) {
479
- console.warn(
480
- `Failed to fetch initial messages: ${response.status} ${response.statusText}`
481
- );
482
- return [];
483
- }
484
-
485
- const text = await response.text();
486
- if (!text.trim()) {
487
- return [];
488
- }
489
-
490
- try {
491
- return JSON.parse(text) as ChatMessage[];
492
- } catch (error) {
493
- console.warn("Failed to parse initial messages JSON:", error);
494
- return [];
495
- }
496
- }
497
-
498
- const getInitialMessagesFetch =
499
- getInitialMessages || defaultGetInitialMessagesFetch;
500
-
501
- function doGetInitialMessages(
502
- getInitialMessagesOptions: GetInitialMessagesOptions,
503
- cacheKey: string
504
- ) {
505
- if (requestCache.has(cacheKey)) {
506
- return requestCache.get(cacheKey)! as Promise<ChatMessage[]>;
507
- }
508
- const promise = getInitialMessagesFetch(getInitialMessagesOptions);
509
- requestCache.set(cacheKey, promise);
510
- return promise;
511
- }
512
-
513
- const initialMessagesPromise =
514
- getInitialMessages === null
515
- ? null
516
- : doGetInitialMessages(
517
- {
518
- agent: agent.agent,
519
- name: agent.name,
520
- url: agentUrlString
521
- },
522
- initialMessagesCacheKey
523
- );
524
- const initialMessages = initialMessagesPromise
525
- ? use(initialMessagesPromise)
526
- : (optionsInitialMessages ?? []);
527
-
528
- useEffect(() => {
529
- if (!initialMessagesPromise) {
530
- return;
531
- }
532
- requestCache.set(initialMessagesCacheKey, initialMessagesPromise!);
533
- return () => {
534
- if (
535
- requestCache.get(initialMessagesCacheKey) === initialMessagesPromise
536
- ) {
537
- requestCache.delete(initialMessagesCacheKey);
538
- }
539
- };
540
- }, [initialMessagesCacheKey, initialMessagesPromise]);
541
-
542
- // Use synchronous ref updates to avoid race conditions between effect runs.
543
- // This ensures the ref always has the latest value before any effect reads it.
544
- const toolsRef = useRef(tools);
545
- toolsRef.current = tools;
546
-
547
- const prepareSendMessagesRequestRef = useRef(prepareSendMessagesRequest);
548
- prepareSendMessagesRequestRef.current = prepareSendMessagesRequest;
549
-
550
- const bodyOptionRef = useRef(bodyOption);
551
- bodyOptionRef.current = bodyOption;
552
-
553
- /**
554
- * Tracks request IDs initiated by this tab via the transport.
555
- * Used by onAgentMessage to skip messages already handled by the transport.
556
- */
557
- const localRequestIdsRef = useRef<Set<string>>(new Set());
558
-
559
- // WebSocket-based transport that speaks the CF_AGENT protocol natively.
560
- // Replaces the old aiFetch + DefaultChatTransport indirection.
561
- const customTransport = useMemo(
562
- () =>
563
- new WebSocketChatTransport<ChatMessage>({
564
- agent: agentRef.current,
565
- activeRequestIds: localRequestIdsRef.current,
566
- prepareBody: async ({ messages: msgs, trigger, messageId }) => {
567
- // Start with the top-level body option (static or dynamic)
568
- let extraBody: Record<string, unknown> = {};
569
- const currentBody = bodyOptionRef.current;
570
- if (currentBody) {
571
- const resolved =
572
- typeof currentBody === "function"
573
- ? await currentBody()
574
- : currentBody;
575
- extraBody = { ...resolved };
576
- }
577
-
578
- // Extract schemas from deprecated client tools (if any)
579
- // Only extract client tool schemas when deprecated tools option is used
580
- if (toolsRef.current) {
581
- const clientToolSchemas = extractClientToolSchemas(
582
- toolsRef.current
583
- );
584
- if (clientToolSchemas) {
585
- extraBody.clientTools = clientToolSchemas;
586
- }
587
- }
588
-
589
- // Apply user's prepareSendMessagesRequest callback (overrides body option)
590
- if (prepareSendMessagesRequestRef.current) {
591
- const userResult = await prepareSendMessagesRequestRef.current({
592
- id: agent._pk,
593
- messages: msgs,
594
- trigger,
595
- messageId
596
- });
597
- if (userResult.body) {
598
- Object.assign(extraBody, userResult.body);
599
- }
600
- }
601
-
602
- return extraBody;
603
- }
604
- }),
605
- [agent._pk]
606
- );
607
-
608
- const useChatHelpers = useChat<ChatMessage>({
609
- ...rest,
610
- onData,
611
- messages: initialMessages,
612
- transport: customTransport,
613
- id: agent._pk
614
- // Note: We handle stream resumption via WebSocket instead of HTTP,
615
- // so we don't pass 'resume' to useChat. The onStreamResuming handler
616
- // automatically resumes active streams when the WebSocket reconnects.
617
- });
618
-
619
- // Destructure stable method references from useChatHelpers.
620
- // These are individually memoized by the AI SDK (via useCallback), so they're
621
- // safe to use in dependency arrays without causing re-renders. Using them
622
- // directly instead of `useChatHelpers.method` avoids the exhaustive-deps
623
- // warning about the unstable `useChatHelpers` object.
624
- const {
625
- messages: chatMessages,
626
- setMessages,
627
- addToolResult,
628
- addToolApprovalResponse,
629
- sendMessage
630
- } = useChatHelpers;
631
-
632
- const processedToolCalls = useRef(new Set<string>());
633
- const isResolvingToolsRef = useRef(false);
634
- // Counter to force the tool resolution effect to re-run after completing
635
- // a batch of tool calls. Without this, if new tool calls arrive while
636
- // isResolvingToolsRef is true (e.g. server auto-continuation), the effect
637
- // exits early and never retriggers because the ref reset doesn't cause
638
- // a re-render.
639
- const [toolResolutionTrigger, setToolResolutionTrigger] = useState(0);
640
-
641
- // Fix for issue #728: Track client-side tool results in local state
642
- // to ensure tool parts show output-available immediately after execution.
643
- const [clientToolResults, setClientToolResults] = useState<
644
- Map<string, unknown>
645
- >(new Map());
646
-
647
- // Ref to access current messages in callbacks without stale closures
648
- const messagesRef = useRef(chatMessages);
649
- messagesRef.current = chatMessages;
650
-
651
- // Calculate pending confirmations for the latest assistant message
652
- const lastMessage = chatMessages[chatMessages.length - 1];
653
-
654
- const pendingConfirmations = (() => {
655
- if (!lastMessage || lastMessage.role !== "assistant") {
656
- return { messageId: undefined, toolCallIds: new Set<string>() };
657
- }
658
-
659
- const pendingIds = new Set<string>();
660
- for (const part of lastMessage.parts ?? []) {
661
- if (
662
- isToolUIPart(part) &&
663
- part.state === "input-available" &&
664
- toolsRequiringConfirmation.includes(getToolName(part))
665
- ) {
666
- pendingIds.add(part.toolCallId);
667
- }
668
- }
669
- return { messageId: lastMessage.id, toolCallIds: pendingIds };
670
- })();
671
-
672
- const pendingConfirmationsRef = useRef(pendingConfirmations);
673
- pendingConfirmationsRef.current = pendingConfirmations;
674
-
675
- // ── DEPRECATED: automatic tool resolution effect ────────────────────
676
- // This entire useEffect is deprecated. Use onToolCall instead.
677
- useEffect(() => {
678
- if (!experimental_automaticToolResolution) {
679
- return;
680
- }
681
-
682
- // Prevent re-entry while async operations are in progress
683
- if (isResolvingToolsRef.current) {
684
- return;
685
- }
686
-
687
- const lastMsg = chatMessages[chatMessages.length - 1];
688
- if (!lastMsg || lastMsg.role !== "assistant") {
689
- return;
690
- }
691
-
692
- const toolCalls = lastMsg.parts.filter(
693
- (part) =>
694
- isToolUIPart(part) &&
695
- part.state === "input-available" &&
696
- !processedToolCalls.current.has(part.toolCallId)
697
- );
698
-
699
- if (toolCalls.length > 0) {
700
- // Capture tools synchronously before async work
701
- const currentTools = toolsRef.current;
702
- const toolCallsToResolve = toolCalls.filter(
703
- (part) =>
704
- isToolUIPart(part) &&
705
- !toolsRequiringConfirmation.includes(getToolName(part)) &&
706
- currentTools?.[getToolName(part)]?.execute
707
- );
708
-
709
- if (toolCallsToResolve.length > 0) {
710
- isResolvingToolsRef.current = true;
711
-
712
- (async () => {
713
- try {
714
- const toolResults: Array<{
715
- toolCallId: string;
716
- toolName: string;
717
- output: unknown;
718
- }> = [];
719
-
720
- for (const part of toolCallsToResolve) {
721
- if (isToolUIPart(part)) {
722
- let toolOutput: unknown = null;
723
- const toolName = getToolName(part);
724
- const tool = currentTools?.[toolName];
725
-
726
- if (tool?.execute && part.input !== undefined) {
727
- try {
728
- toolOutput = await tool.execute(part.input);
729
- } catch (error) {
730
- toolOutput = `Error executing tool: ${error instanceof Error ? error.message : String(error)}`;
731
- }
732
- }
733
-
734
- processedToolCalls.current.add(part.toolCallId);
735
-
736
- toolResults.push({
737
- toolCallId: part.toolCallId,
738
- toolName,
739
- output: toolOutput
740
- });
741
- }
742
- }
743
-
744
- if (toolResults.length > 0) {
745
- // Send tool results to server first (server is source of truth)
746
- const clientToolSchemas = extractClientToolSchemas(currentTools);
747
- for (const result of toolResults) {
748
- agentRef.current.send(
749
- JSON.stringify({
750
- type: MessageType.CF_AGENT_TOOL_RESULT,
751
- toolCallId: result.toolCallId,
752
- toolName: result.toolName,
753
- output: result.output,
754
- autoContinue: autoContinueAfterToolResult,
755
- clientTools: clientToolSchemas
756
- })
757
- );
758
- }
759
-
760
- // Also update local state via AI SDK for immediate UI feedback
761
- await Promise.all(
762
- toolResults.map((result) =>
763
- addToolResult({
764
- tool: result.toolName,
765
- toolCallId: result.toolCallId,
766
- output: result.output
767
- })
768
- )
769
- );
770
-
771
- setClientToolResults((prev) => {
772
- const newMap = new Map(prev);
773
- for (const result of toolResults) {
774
- newMap.set(result.toolCallId, result.output);
775
- }
776
- return newMap;
777
- });
778
- }
779
-
780
- // Note: We don't call sendMessage() here anymore.
781
- // The server will continue the conversation after applying tool results.
782
- } finally {
783
- isResolvingToolsRef.current = false;
784
- // Trigger a re-run so any tool calls that arrived while we were
785
- // busy (e.g. from server auto-continuation) get picked up.
786
- setToolResolutionTrigger((c) => c + 1);
787
- }
788
- })();
789
- }
790
- }
791
- }, [
792
- chatMessages,
793
- experimental_automaticToolResolution,
794
- addToolResult,
795
- toolsRequiringConfirmation,
796
- autoContinueAfterToolResult,
797
- toolResolutionTrigger
798
- ]);
799
-
800
- // Helper function to send tool output to server
801
- const sendToolOutputToServer = useCallback(
802
- (
803
- toolCallId: string,
804
- toolName: string,
805
- output: unknown,
806
- state?: "output-available" | "output-error",
807
- errorText?: string
808
- ) => {
809
- agentRef.current.send(
810
- JSON.stringify({
811
- type: MessageType.CF_AGENT_TOOL_RESULT,
812
- toolCallId,
813
- toolName,
814
- output,
815
- ...(state ? { state } : {}),
816
- ...(errorText !== undefined ? { errorText } : {}),
817
- // output-error is a deliberate client action — don't auto-continue.
818
- // This differs from addToolApprovalResponse (which auto-continues for
819
- // both approvals and rejections). To have the LLM respond to the error,
820
- // call sendMessage() after addToolOutput.
821
- autoContinue:
822
- state === "output-error" ? false : autoContinueAfterToolResult,
823
- clientTools: toolsRef.current
824
- ? extractClientToolSchemas(toolsRef.current)
825
- : undefined
826
- })
827
- );
828
-
829
- if (state !== "output-error") {
830
- setClientToolResults((prev) => new Map(prev).set(toolCallId, output));
831
- }
832
- },
833
- [autoContinueAfterToolResult]
834
- );
835
-
836
- // Helper function to send tool approval to server
837
- const sendToolApprovalToServer = useCallback(
838
- (toolCallId: string, approved: boolean) => {
839
- agentRef.current.send(
840
- JSON.stringify({
841
- type: MessageType.CF_AGENT_TOOL_APPROVAL,
842
- toolCallId,
843
- approved,
844
- autoContinue: autoContinueAfterToolResult
845
- })
846
- );
847
- },
848
- [autoContinueAfterToolResult]
849
- );
850
-
851
- // Effect for new onToolCall callback pattern (v6 style)
852
- // This fires when there are tool calls that need client-side handling
853
- useEffect(() => {
854
- const currentOnToolCall = onToolCallRef.current;
855
- if (!currentOnToolCall) {
856
- return;
857
- }
858
-
859
- const lastMsg = chatMessages[chatMessages.length - 1];
860
- if (!lastMsg || lastMsg.role !== "assistant") {
861
- return;
862
- }
863
-
864
- // Find tool calls in input-available state that haven't been processed
865
- const pendingToolCalls = lastMsg.parts.filter(
866
- (part) =>
867
- isToolUIPart(part) &&
868
- part.state === "input-available" &&
869
- !processedToolCalls.current.has(part.toolCallId)
870
- );
871
-
872
- for (const part of pendingToolCalls) {
873
- if (isToolUIPart(part)) {
874
- const toolCallId = part.toolCallId;
875
- const toolName = getToolName(part);
876
-
877
- // Mark as processed to prevent re-triggering
878
- processedToolCalls.current.add(toolCallId);
879
-
880
- // Create addToolOutput function for this specific tool call
881
- const addToolOutput = (opts: AddToolOutputOptions) => {
882
- sendToolOutputToServer(
883
- opts.toolCallId,
884
- toolName,
885
- opts.output,
886
- opts.state,
887
- opts.errorText
888
- );
889
-
890
- // Update local state via AI SDK
891
- addToolResult({
892
- tool: toolName,
893
- toolCallId: opts.toolCallId,
894
- output:
895
- opts.state === "output-error"
896
- ? (opts.errorText ?? "Tool execution denied by user")
897
- : opts.output
898
- });
899
- };
900
-
901
- // Call the onToolCall callback
902
- // The callback is responsible for calling addToolOutput when ready
903
- currentOnToolCall({
904
- toolCall: {
905
- toolCallId,
906
- toolName,
907
- input: part.input
908
- },
909
- addToolOutput
910
- });
911
- }
912
- }
913
- }, [chatMessages, sendToolOutputToServer, addToolResult]);
914
-
915
- /**
916
- * Contains the request ID, accumulated message parts, metadata, and a unique message ID.
917
- * Used for both resumed streams and real-time broadcasts from other tabs.
918
- * Metadata is captured from start/finish/message-metadata stream chunks
919
- * so that it's included when the partial message is flushed to React state.
920
- */
921
- const activeStreamRef = useRef<{
922
- id: string;
923
- messageId: string;
924
- parts: ChatMessage["parts"];
925
- metadata?: Record<string, unknown>;
926
- } | null>(null);
927
-
928
- /**
929
- * Flush the active stream's accumulated parts into React state.
930
- * Extracted as a helper so it can be called both during live streaming
931
- * (per-chunk) and after replay completes (once, at done).
932
- */
933
- const flushActiveStreamToMessages = useCallback(
934
- (activeMsg: {
935
- id: string;
936
- messageId: string;
937
- parts: ChatMessage["parts"];
938
- metadata?: Record<string, unknown>;
939
- }) => {
940
- setMessages((prevMessages: ChatMessage[]) => {
941
- const existingIdx = prevMessages.findIndex(
942
- (m) => m.id === activeMsg.messageId
943
- );
944
-
945
- const partialMessage = {
946
- id: activeMsg.messageId,
947
- role: "assistant" as const,
948
- parts: [...activeMsg.parts],
949
- ...(activeMsg.metadata != null && { metadata: activeMsg.metadata })
950
- } as unknown as ChatMessage;
951
-
952
- if (existingIdx >= 0) {
953
- const updated = [...prevMessages];
954
- updated[existingIdx] = partialMessage;
955
- return updated;
956
- }
957
- return [...prevMessages, partialMessage];
958
- });
959
- },
960
- [setMessages]
961
- );
962
-
963
- useEffect(() => {
964
- /**
965
- * Unified message handler that parses JSON once and dispatches based on type.
966
- * Avoids duplicate parsing overhead from separate listeners.
967
- */
968
- function onAgentMessage(event: MessageEvent) {
969
- if (typeof event.data !== "string") return;
970
-
971
- let data: OutgoingMessage<ChatMessage>;
972
- try {
973
- data = JSON.parse(event.data) as OutgoingMessage<ChatMessage>;
974
- } catch (_error) {
975
- return;
976
- }
977
-
978
- switch (data.type) {
979
- case MessageType.CF_AGENT_CHAT_CLEAR:
980
- setMessages([]);
981
- break;
982
-
983
- case MessageType.CF_AGENT_CHAT_MESSAGES:
984
- setMessages(data.messages);
985
- break;
986
-
987
- case MessageType.CF_AGENT_MESSAGE_UPDATED:
988
- // Server updated a message (e.g., applied tool result)
989
- // Update the specific message in local state
990
- setMessages((prevMessages: ChatMessage[]) => {
991
- const updatedMessage = data.message;
992
-
993
- // First try to find by message ID
994
- let idx = prevMessages.findIndex((m) => m.id === updatedMessage.id);
995
-
996
- // If not found by ID, try to find by toolCallId
997
- // This handles the case where client has AI SDK-generated IDs
998
- // but server has server-generated IDs
999
- if (idx < 0) {
1000
- const updatedToolCallIds = new Set(
1001
- updatedMessage.parts
1002
- .filter(
1003
- (p: ChatMessage["parts"][number]) =>
1004
- "toolCallId" in p && p.toolCallId
1005
- )
1006
- .map(
1007
- (p: ChatMessage["parts"][number]) =>
1008
- (p as { toolCallId: string }).toolCallId
1009
- )
1010
- );
1011
-
1012
- if (updatedToolCallIds.size > 0) {
1013
- idx = prevMessages.findIndex((m) =>
1014
- m.parts.some(
1015
- (p) =>
1016
- "toolCallId" in p &&
1017
- updatedToolCallIds.has(
1018
- (p as { toolCallId: string }).toolCallId
1019
- )
1020
- )
1021
- );
1022
- }
1023
- }
1024
-
1025
- if (idx >= 0) {
1026
- const updated = [...prevMessages];
1027
- // Preserve the client's message ID but update the content
1028
- updated[idx] = {
1029
- ...updatedMessage,
1030
- id: prevMessages[idx].id
1031
- };
1032
- return updated;
1033
- }
1034
- // Message not found, append it
1035
- return [...prevMessages, updatedMessage];
1036
- });
1037
- break;
1038
-
1039
- case MessageType.CF_AGENT_STREAM_RESUMING:
1040
- if (!resume) return;
1041
- // Clear any previous incomplete active stream to prevent memory leak
1042
- activeStreamRef.current = null;
1043
- // Initialize active stream state with unique ID
1044
- activeStreamRef.current = {
1045
- id: data.id,
1046
- messageId: nanoid(),
1047
- parts: []
1048
- };
1049
- // Send ACK to server - we're ready to receive chunks
1050
- agentRef.current.send(
1051
- JSON.stringify({
1052
- type: MessageType.CF_AGENT_STREAM_RESUME_ACK,
1053
- id: data.id
1054
- })
1055
- );
1056
- break;
1057
-
1058
- case MessageType.CF_AGENT_USE_CHAT_RESPONSE: {
1059
- // Skip if this is a response to a request this tab initiated
1060
- // (handled by the aiFetch listener instead)
1061
- if (localRequestIdsRef.current.has(data.id)) return;
1062
-
1063
- // For continuations, find the last assistant message ID to append to
1064
- const isContinuation = data.continuation === true;
1065
-
1066
- // Initialize stream state for broadcasts from other tabs
1067
- if (
1068
- !activeStreamRef.current ||
1069
- activeStreamRef.current.id !== data.id
1070
- ) {
1071
- let messageId = nanoid();
1072
- let existingParts: ChatMessage["parts"] = [];
1073
- let existingMetadata: Record<string, unknown> | undefined;
1074
-
1075
- // For continuations, use the last assistant message's ID, parts, and metadata
1076
- if (isContinuation) {
1077
- const currentMessages = messagesRef.current;
1078
- for (let i = currentMessages.length - 1; i >= 0; i--) {
1079
- if (currentMessages[i].role === "assistant") {
1080
- messageId = currentMessages[i].id;
1081
- existingParts = [...currentMessages[i].parts];
1082
- if (currentMessages[i].metadata != null) {
1083
- existingMetadata = {
1084
- ...(currentMessages[i].metadata as Record<
1085
- string,
1086
- unknown
1087
- >)
1088
- };
1089
- }
1090
- break;
1091
- }
1092
- }
1093
- }
1094
-
1095
- activeStreamRef.current = {
1096
- id: data.id,
1097
- messageId,
1098
- parts: existingParts,
1099
- metadata: existingMetadata
1100
- };
1101
- }
1102
-
1103
- const activeMsg = activeStreamRef.current;
1104
- const isReplay = data.replay === true;
1105
-
1106
- if (data.body?.trim()) {
1107
- try {
1108
- const chunkData = JSON.parse(data.body);
1109
-
1110
- // Apply chunk to parts using shared parser.
1111
- // Handles text, reasoning, file, source, tool, step, and data-* chunks.
1112
- // Unrecognized types (tool-input-start, tool-input-delta, etc.)
1113
- // are intermediate states — the final state is captured by
1114
- // tool-input-available / tool-output-available.
1115
- const handled = applyChunkToParts(
1116
- activeMsg.parts as MessageParts,
1117
- chunkData
1118
- );
1119
-
1120
- // Fire onData callback for data-* parts (stream resumption
1121
- // and cross-tab broadcasts). For the transport path (new
1122
- // messages from this tab), the AI SDK's pipeline invokes
1123
- // onData internally.
1124
- if (
1125
- typeof chunkData.type === "string" &&
1126
- chunkData.type.startsWith("data-") &&
1127
- onDataRef.current
1128
- ) {
1129
- onDataRef.current(chunkData);
1130
- }
1131
-
1132
- // Capture message metadata from start/finish/message-metadata
1133
- // chunks. These carry metadata like timestamps, model info, and
1134
- // token usage that should be attached at the message level.
1135
- if (
1136
- !handled &&
1137
- (chunkData.type === "start" ||
1138
- chunkData.type === "finish" ||
1139
- chunkData.type === "message-metadata")
1140
- ) {
1141
- if (chunkData.messageId != null && chunkData.type === "start") {
1142
- activeMsg.messageId = chunkData.messageId;
1143
- }
1144
- if (chunkData.messageMetadata != null) {
1145
- activeMsg.metadata = activeMsg.metadata
1146
- ? { ...activeMsg.metadata, ...chunkData.messageMetadata }
1147
- : { ...chunkData.messageMetadata };
1148
- }
1149
- }
1150
-
1151
- // For replayed chunks, skip intermediate setMessages calls.
1152
- // Replayed chunks arrive synchronously in a tight loop, so React
1153
- // would batch all state updates into a single render anyway —
1154
- // causing intermediate states (like "Thinking...") to be lost.
1155
- // We defer the render until replay is complete (done signal).
1156
- if (!isReplay) {
1157
- flushActiveStreamToMessages(activeMsg);
1158
- }
1159
- } catch (parseError) {
1160
- console.warn(
1161
- "[useAgentChat] Failed to parse stream chunk:",
1162
- parseError instanceof Error ? parseError.message : parseError,
1163
- "body:",
1164
- data.body?.slice(0, 100)
1165
- );
1166
- }
1167
- }
1168
-
1169
- // On completion or error, flush final state to messages
1170
- if (data.done || data.error) {
1171
- // For replayed streams, this is the single render point —
1172
- // all parts have been accumulated, now render them at once.
1173
- if (isReplay && activeMsg) {
1174
- flushActiveStreamToMessages(activeMsg);
1175
- }
1176
- activeStreamRef.current = null;
1177
- }
1178
- break;
1179
- }
1180
- }
1181
- }
1182
-
1183
- agent.addEventListener("message", onAgentMessage);
1184
-
1185
- // Request stream resume check AFTER the handler is registered.
1186
- // This avoids the race condition where CF_AGENT_STREAM_RESUMING sent
1187
- // in onConnect arrives before this useEffect runs. The server also
1188
- // sends it in onConnect as a fallback for older clients.
1189
- if (resume) {
1190
- agent.send(
1191
- JSON.stringify({
1192
- type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST
1193
- })
1194
- );
1195
- }
1196
-
1197
- return () => {
1198
- agent.removeEventListener("message", onAgentMessage);
1199
- // Clear active stream state on cleanup to prevent memory leak
1200
- activeStreamRef.current = null;
1201
- };
1202
- }, [agent, setMessages, resume, flushActiveStreamToMessages]);
1203
-
1204
- // ── DEPRECATED: addToolResult wrapper with confirmation batching ────
1205
- // This wrapper is deprecated. Use addToolOutput or addToolApprovalResponse instead.
1206
- const addToolResultAndSendMessage: typeof addToolResult = async (args) => {
1207
- const { toolCallId } = args;
1208
- const toolName = "tool" in args ? args.tool : "";
1209
- const output = "output" in args ? args.output : undefined;
1210
-
1211
- // Send tool result to server (server is source of truth)
1212
- // Include flag to tell server whether to auto-continue
1213
- agentRef.current.send(
1214
- JSON.stringify({
1215
- type: MessageType.CF_AGENT_TOOL_RESULT,
1216
- toolCallId,
1217
- toolName,
1218
- output,
1219
- autoContinue: autoContinueAfterToolResult,
1220
- clientTools: toolsRef.current
1221
- ? extractClientToolSchemas(toolsRef.current)
1222
- : undefined
1223
- })
1224
- );
1225
-
1226
- setClientToolResults((prev) => new Map(prev).set(toolCallId, output));
1227
-
1228
- // Call AI SDK's addToolResult for local state update (non-blocking)
1229
- // We don't await this since clientToolResults provides immediate UI feedback
1230
- addToolResult(args);
1231
-
1232
- // If server auto-continuation is disabled, client needs to trigger continuation
1233
- if (!autoContinueAfterToolResult) {
1234
- // Use legacy behavior: batch confirmations or send immediately
1235
- if (!autoSendAfterAllConfirmationsResolved) {
1236
- // Always send immediately
1237
- sendMessage();
1238
- return;
1239
- }
1240
-
1241
- // Wait for all confirmations before sending
1242
- const pending = pendingConfirmationsRef.current?.toolCallIds;
1243
- if (!pending) {
1244
- sendMessage();
1245
- return;
1246
- }
1247
-
1248
- const wasLast = pending.size === 1 && pending.has(toolCallId);
1249
- if (pending.has(toolCallId)) {
1250
- pending.delete(toolCallId);
1251
- }
1252
-
1253
- if (wasLast || pending.size === 0) {
1254
- sendMessage();
1255
- }
1256
- }
1257
- // If autoContinueAfterToolResult is true, server handles continuation
1258
- };
1259
-
1260
- // Wrapper that sends tool approval to server before updating local state.
1261
- // This prevents duplicate messages by ensuring server updates the message
1262
- // in place with the existing ID, rather than relying on ID resolution
1263
- // when sendMessage() is called later.
1264
- const addToolApprovalResponseAndNotifyServer: typeof addToolApprovalResponse =
1265
- (args) => {
1266
- const { id: approvalId, approved } = args;
1267
-
1268
- // Find the toolCallId from the approval ID
1269
- // The approval ID is stored on the tool part's approval.id field
1270
- let toolCallId: string | undefined;
1271
- for (const msg of messagesRef.current) {
1272
- for (const part of msg.parts) {
1273
- if (
1274
- "toolCallId" in part &&
1275
- "approval" in part &&
1276
- (part.approval as { id?: string })?.id === approvalId
1277
- ) {
1278
- toolCallId = part.toolCallId as string;
1279
- break;
1280
- }
1281
- }
1282
- if (toolCallId) break;
1283
- }
1284
-
1285
- if (toolCallId) {
1286
- // Send approval to server first (server updates message in place)
1287
- sendToolApprovalToServer(toolCallId, approved);
1288
- } else {
1289
- console.warn(
1290
- `[useAgentChat] addToolApprovalResponse: Could not find toolCallId for approval ID "${approvalId}". ` +
1291
- "Server will not be notified, which may cause duplicate messages."
1292
- );
1293
- }
1294
-
1295
- // Call AI SDK's addToolApprovalResponse for local state update
1296
- addToolApprovalResponse(args);
1297
- };
1298
-
1299
- // Fix for issue #728: Merge client-side tool results with messages
1300
- // so tool parts show output-available immediately after execution
1301
- const messagesWithToolResults = useMemo(() => {
1302
- if (clientToolResults.size === 0) {
1303
- return chatMessages;
1304
- }
1305
- return chatMessages.map((msg) => ({
1306
- ...msg,
1307
- parts: msg.parts.map((p) => {
1308
- if (
1309
- !("toolCallId" in p) ||
1310
- !("state" in p) ||
1311
- p.state !== "input-available" ||
1312
- !clientToolResults.has(p.toolCallId)
1313
- ) {
1314
- return p;
1315
- }
1316
- return {
1317
- ...p,
1318
- state: "output-available" as const,
1319
- output: clientToolResults.get(p.toolCallId)
1320
- };
1321
- })
1322
- })) as ChatMessage[];
1323
- }, [chatMessages, clientToolResults]);
1324
-
1325
- // Cleanup stale entries from clientToolResults when messages change
1326
- // to prevent memory leak in long conversations.
1327
- // Note: We intentionally exclude clientToolResults from deps to avoid infinite loops.
1328
- // The functional update form gives us access to the previous state.
1329
- useEffect(() => {
1330
- // Collect all current toolCallIds from messages
1331
- const currentToolCallIds = new Set<string>();
1332
- for (const msg of chatMessages) {
1333
- for (const part of msg.parts) {
1334
- if ("toolCallId" in part && part.toolCallId) {
1335
- currentToolCallIds.add(part.toolCallId);
1336
- }
1337
- }
1338
- }
1339
-
1340
- // Use functional update to check and clean stale entries atomically
1341
- setClientToolResults((prev) => {
1342
- if (prev.size === 0) return prev;
1343
-
1344
- // Check if any entries are stale
1345
- let hasStaleEntries = false;
1346
- for (const toolCallId of prev.keys()) {
1347
- if (!currentToolCallIds.has(toolCallId)) {
1348
- hasStaleEntries = true;
1349
- break;
1350
- }
1351
- }
1352
-
1353
- // Only create new Map if there are stale entries to remove
1354
- if (!hasStaleEntries) return prev;
1355
-
1356
- const newMap = new Map<string, unknown>();
1357
- for (const [id, output] of prev) {
1358
- if (currentToolCallIds.has(id)) {
1359
- newMap.set(id, output);
1360
- }
1361
- }
1362
- return newMap;
1363
- });
1364
-
1365
- // Also cleanup processedToolCalls to prevent issues in long conversations
1366
- for (const toolCallId of processedToolCalls.current) {
1367
- if (!currentToolCallIds.has(toolCallId)) {
1368
- processedToolCalls.current.delete(toolCallId);
1369
- }
1370
- }
1371
- // eslint-disable-next-line react-hooks/exhaustive-deps
1372
- }, [chatMessages]);
1373
-
1374
- // Create addToolOutput function for external use
1375
- const addToolOutput = useCallback(
1376
- (opts: AddToolOutputOptions) => {
1377
- const toolName = opts.toolName ?? "";
1378
- sendToolOutputToServer(
1379
- opts.toolCallId,
1380
- toolName,
1381
- opts.output,
1382
- opts.state,
1383
- opts.errorText
1384
- );
1385
-
1386
- // Update local state via AI SDK
1387
- addToolResult({
1388
- tool: toolName,
1389
- toolCallId: opts.toolCallId,
1390
- output:
1391
- opts.state === "output-error"
1392
- ? (opts.errorText ?? "Tool execution denied by user")
1393
- : opts.output
1394
- });
1395
- },
1396
- [sendToolOutputToServer, addToolResult]
1397
- );
1398
-
1399
- return {
1400
- ...useChatHelpers,
1401
- messages: messagesWithToolResults,
1402
- /**
1403
- * Provide output for a tool call. Use this for tools that require user interaction
1404
- * or client-side execution.
1405
- */
1406
- addToolOutput,
1407
- /**
1408
- * @deprecated Use `addToolOutput` instead.
1409
- */
1410
- addToolResult: addToolResultAndSendMessage,
1411
- /**
1412
- * Respond to a tool approval request. Use this for tools with `needsApproval`.
1413
- * This wrapper notifies the server before updating local state, preventing
1414
- * duplicate messages when sendMessage() is called afterward.
1415
- */
1416
- addToolApprovalResponse: addToolApprovalResponseAndNotifyServer,
1417
- clearHistory: () => {
1418
- setMessages([]);
1419
- setClientToolResults(new Map());
1420
- processedToolCalls.current.clear();
1421
- agent.send(
1422
- JSON.stringify({
1423
- type: MessageType.CF_AGENT_CHAT_CLEAR
1424
- })
1425
- );
1426
- },
1427
- setMessages: (messagesOrUpdater: Parameters<typeof setMessages>[0]) => {
1428
- // Resolve functional updaters to get the actual messages array
1429
- // before syncing to server. Without this, updater functions would
1430
- // send an empty array and wipe server-side messages.
1431
- let resolvedMessages: ChatMessage[];
1432
- if (typeof messagesOrUpdater === "function") {
1433
- resolvedMessages = messagesOrUpdater(messagesRef.current);
1434
- } else {
1435
- resolvedMessages = messagesOrUpdater;
1436
- }
1437
-
1438
- setMessages(resolvedMessages);
1439
- agent.send(
1440
- JSON.stringify({
1441
- messages: resolvedMessages,
1442
- type: MessageType.CF_AGENT_CHAT_MESSAGES
1443
- })
1444
- );
1445
- }
1446
- };
1447
- }