@cloudflare/ai-chat 0.0.7 → 0.1.0

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 (60) hide show
  1. package/CHANGELOG.md +105 -0
  2. package/README.md +225 -459
  3. package/dist/ai-chat-v5-migration.d.ts +9 -9
  4. package/dist/ai-chat-v5-migration.js +25 -4
  5. package/dist/ai-chat-v5-migration.js.map +1 -1
  6. package/dist/experimental/forever.d.ts +29 -0
  7. package/dist/experimental/forever.js +55 -0
  8. package/dist/experimental/forever.js.map +1 -0
  9. package/dist/index.d.ts +126 -74
  10. package/dist/index.js +753 -632
  11. package/dist/index.js.map +1 -1
  12. package/dist/message-builder-Bwc_Umye.js +231 -0
  13. package/dist/message-builder-Bwc_Umye.js.map +1 -0
  14. package/dist/react.d.ts +27 -9
  15. package/dist/react.js +248 -259
  16. package/dist/react.js.map +1 -1
  17. package/dist/resumable-stream-DqXxQVjf.d.ts +103 -0
  18. package/dist/types.d.ts +16 -4
  19. package/dist/types.js +2 -0
  20. package/dist/types.js.map +1 -1
  21. package/e2e/chat.spec.ts +1703 -0
  22. package/e2e/client-tools.spec.ts +504 -0
  23. package/e2e/llm.spec.ts +637 -0
  24. package/e2e/playwright.config.ts +24 -0
  25. package/e2e/worker.ts +176 -0
  26. package/e2e/wrangler.jsonc +23 -0
  27. package/package.json +12 -5
  28. package/scripts/build.ts +2 -1
  29. package/src/ai-chat-v5-migration.ts +32 -5
  30. package/src/experimental/forever.ts +66 -0
  31. package/src/index.ts +850 -1132
  32. package/src/message-builder.ts +384 -0
  33. package/src/react-tests/use-agent-chat.test.tsx +738 -2
  34. package/src/react.tsx +396 -462
  35. package/src/resumable-stream.ts +441 -0
  36. package/src/tests/chat-context.test.ts +1 -1
  37. package/src/tests/chat-persistence.test.ts +5 -5
  38. package/src/tests/clear-history.test.ts +132 -0
  39. package/src/tests/client-tool-duplicate-message.test.ts +457 -14
  40. package/src/tests/client-tools-broadcast.test.ts +2 -2
  41. package/src/tests/client-tools-continuation.test.ts +314 -0
  42. package/src/tests/client-tools-reconnect.test.ts +143 -0
  43. package/src/tests/custom-body-continuation.test.ts +309 -0
  44. package/src/tests/custom-body.test.ts +186 -0
  45. package/src/tests/destroy.test.ts +57 -0
  46. package/src/tests/get-messages-endpoint.test.ts +79 -0
  47. package/src/tests/max-persisted-messages.test.ts +201 -0
  48. package/src/tests/merge-server-state.test.ts +106 -0
  49. package/src/tests/message-builder.test.ts +808 -0
  50. package/src/tests/migration.test.ts +282 -0
  51. package/src/tests/non-sse-response.test.ts +2 -2
  52. package/src/tests/onfinish-cleanup.test.ts +362 -0
  53. package/src/tests/plaintext-response.test.ts +87 -0
  54. package/src/tests/resumable-streaming.test.ts +220 -14
  55. package/src/tests/row-size-guard.test.ts +374 -0
  56. package/src/tests/sanitize-messages.test.ts +215 -0
  57. package/src/tests/validate-messages.test.ts +269 -0
  58. package/src/tests/worker.ts +85 -23
  59. package/src/types.ts +17 -1
  60. package/src/ws-chat-transport.ts +203 -0
package/src/react.tsx CHANGED
@@ -2,23 +2,39 @@ import { useChat, type UseChatOptions } from "@ai-sdk/react";
2
2
  import { getToolName, isToolUIPart } from "ai";
3
3
  import type {
4
4
  ChatInit,
5
- ChatTransport,
6
5
  JSONSchema7,
7
6
  Tool,
8
7
  UIMessage as Message,
9
8
  UIMessage
10
9
  } from "ai";
11
- import { DefaultChatTransport } from "ai";
12
10
  import { nanoid } from "nanoid";
13
11
  import { use, useCallback, useEffect, useMemo, useRef, useState } from "react";
14
12
  import type { OutgoingMessage } from "./types";
15
13
  import { MessageType } from "./types";
14
+ import { applyChunkToParts, type MessageParts } from "./message-builder";
15
+ import { WebSocketChatTransport } from "./ws-chat-transport";
16
16
  import type { useAgent } from "agents/react";
17
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
+
18
34
  /**
19
35
  * JSON Schema type for tool parameters.
20
36
  * Re-exported from the AI SDK for convenience.
21
- * @deprecated Import JSONSchema7 directly from "ai" instead.
37
+ * @deprecated Import JSONSchema7 directly from "ai" instead. Will be removed in the next major version.
22
38
  */
23
39
  export type JSONSchemaType = JSONSchema7;
24
40
 
@@ -78,6 +94,10 @@ export type ClientToolSchema = {
78
94
  export function extractClientToolSchemas(
79
95
  tools?: Record<string, AITool<unknown, unknown>>
80
96
  ): ClientToolSchema[] | undefined {
97
+ warnDeprecated(
98
+ "extractClientToolSchemas",
99
+ "extractClientToolSchemas() is deprecated. Define tools on the server and use onToolCall for client execution. Will be removed in the next major version."
100
+ );
81
101
  if (!tools) return undefined;
82
102
 
83
103
  const schemas: ClientToolSchema[] = Object.entries(tools)
@@ -98,6 +118,8 @@ export function extractClientToolSchemas(
98
118
  return schemas.length > 0 ? schemas : undefined;
99
119
  }
100
120
 
121
+ // ── END DEPRECATED TYPES AND FUNCTIONS ─────────────────────────────
122
+
101
123
  type GetInitialMessagesOptions = {
102
124
  agent: string;
103
125
  name: string;
@@ -151,17 +173,6 @@ export type PrepareSendMessagesRequestResult = {
151
173
  api?: string;
152
174
  };
153
175
 
154
- /**
155
- * Internal type for AI SDK transport
156
- * @internal
157
- */
158
- type InternalPrepareResult = {
159
- body: Record<string, unknown>;
160
- headers?: HeadersInit;
161
- credentials?: RequestCredentials;
162
- api?: string;
163
- };
164
-
165
176
  /**
166
177
  * Callback for handling client-side tool execution.
167
178
  * Called when a tool without server-side execute is invoked.
@@ -183,7 +194,7 @@ export type OnToolCallCallback = (options: {
183
194
  type UseAgentChatOptions<
184
195
  State,
185
196
  ChatMessage extends UIMessage = UIMessage
186
- > = Omit<UseChatParams<ChatMessage>, "fetch"> & {
197
+ > = Omit<UseChatParams<ChatMessage>, "fetch" | "onToolCall"> & {
187
198
  /** Agent connection from useAgent */
188
199
  agent: ReturnType<typeof useAgent<State>>;
189
200
  getInitialMessages?:
@@ -237,15 +248,15 @@ type UseAgentChatOptions<
237
248
  */
238
249
  toolsRequiringConfirmation?: string[];
239
250
  /**
240
- * When true, the server automatically continues the conversation after
241
- * receiving client-side tool results, similar to how server-executed tools
242
- * work with maxSteps in streamText. The continuation is merged into the
243
- * same assistant message.
251
+ * When true (default), the server automatically continues the conversation
252
+ * after receiving client-side tool results or approvals, similar to how
253
+ * server-executed tools work with maxSteps in streamText. The continuation
254
+ * is merged into the same assistant message.
244
255
  *
245
- * When false (default), the client calls sendMessage() after tool results
256
+ * When false, the client must call sendMessage() after tool results
246
257
  * to continue the conversation, which creates a new assistant message.
247
258
  *
248
- * @default false
259
+ * @default true
249
260
  */
250
261
  autoContinueAfterToolResult?: boolean;
251
262
  /**
@@ -265,9 +276,27 @@ type UseAgentChatOptions<
265
276
  * @default true
266
277
  */
267
278
  resume?: boolean;
279
+ /**
280
+ * Custom data to include in every chat request body.
281
+ * Accepts a static object or a function that returns one (for dynamic values).
282
+ * These fields are available in `onChatMessage` via `options.body`.
283
+ *
284
+ * @example
285
+ * ```typescript
286
+ * // Static
287
+ * body: { timezone: "America/New_York", userId: "abc" }
288
+ *
289
+ * // Dynamic (called on each send)
290
+ * body: () => ({ token: getAuthToken(), timestamp: Date.now() })
291
+ * ```
292
+ */
293
+ body?:
294
+ | Record<string, unknown>
295
+ | (() => Record<string, unknown> | Promise<Record<string, unknown>>);
268
296
  /**
269
297
  * Callback to customize the request before sending messages.
270
- * Use this for advanced scenarios like adding custom headers or dynamic context.
298
+ * For most cases, use the `body` option instead.
299
+ * Use this for advanced scenarios that need access to the messages or trigger type.
271
300
  *
272
301
  * Note: Client tool schemas are automatically sent when tools have `execute` functions.
273
302
  * This callback can add additional data alongside the auto-extracted schemas.
@@ -279,6 +308,12 @@ type UseAgentChatOptions<
279
308
  | Promise<PrepareSendMessagesRequestResult>;
280
309
  };
281
310
 
311
+ /**
312
+ * Module-level cache for initial message fetches. Intentionally shared across
313
+ * all useAgentChat instances to deduplicate requests during React Strict Mode
314
+ * double-renders and re-renders. Cache keys include the agent URL, agent type,
315
+ * and thread name to prevent cross-agent collisions.
316
+ */
282
317
  const requestCache = new Map<string, Promise<Message[]>>();
283
318
 
284
319
  /**
@@ -297,6 +332,10 @@ const requestCache = new Map<string, Promise<Message[]>>();
297
332
  export function detectToolsRequiringConfirmation(
298
333
  tools?: Record<string, AITool<unknown, unknown>>
299
334
  ): string[] {
335
+ warnDeprecated(
336
+ "detectToolsRequiringConfirmation",
337
+ "detectToolsRequiringConfirmation() is deprecated. Use needsApproval on server-side tools instead. Will be removed in the next major version."
338
+ );
300
339
  if (!tools) return [];
301
340
 
302
341
  return Object.entries(tools)
@@ -334,24 +373,59 @@ export function useAgentChat<
334
373
  getInitialMessages,
335
374
  messages: optionsInitialMessages,
336
375
  onToolCall,
376
+ onData,
337
377
  experimental_automaticToolResolution,
338
378
  tools,
339
379
  toolsRequiringConfirmation: manualToolsRequiringConfirmation,
340
- autoContinueAfterToolResult = false, // Opt-in to server auto-continuation
380
+ autoContinueAfterToolResult = true, // Server auto-continues after tool results/approvals
341
381
  autoSendAfterAllConfirmationsResolved = true, // Legacy option for client-side batching
342
382
  resume = true, // Enable stream resumption by default
383
+ body: bodyOption,
343
384
  prepareSendMessagesRequest,
344
385
  ...rest
345
386
  } = options;
346
387
 
347
- // Auto-detect tools requiring confirmation, or use manual override
348
- // @deprecated - this will be removed when toolsRequiringConfirmation is removed
349
- const toolsRequiringConfirmation =
350
- manualToolsRequiringConfirmation ?? detectToolsRequiringConfirmation(tools);
388
+ // Emit deprecation warnings for deprecated options (once per session)
389
+ if (tools) {
390
+ warnDeprecated(
391
+ "useAgentChat.tools",
392
+ "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."
393
+ );
394
+ }
395
+ if (manualToolsRequiringConfirmation) {
396
+ warnDeprecated(
397
+ "useAgentChat.toolsRequiringConfirmation",
398
+ "The 'toolsRequiringConfirmation' option is deprecated. Use needsApproval on server-side tools instead. Will be removed in the next major version."
399
+ );
400
+ }
401
+ if (experimental_automaticToolResolution) {
402
+ warnDeprecated(
403
+ "useAgentChat.experimental_automaticToolResolution",
404
+ "The 'experimental_automaticToolResolution' option is deprecated. Use the onToolCall callback instead. Will be removed in the next major version."
405
+ );
406
+ }
407
+ if (options.autoSendAfterAllConfirmationsResolved !== undefined) {
408
+ warnDeprecated(
409
+ "useAgentChat.autoSendAfterAllConfirmationsResolved",
410
+ "The 'autoSendAfterAllConfirmationsResolved' option is deprecated. Use sendAutomaticallyWhen from AI SDK instead. Will be removed in the next major version."
411
+ );
412
+ }
413
+
414
+ // ── DEPRECATED: client-side tool confirmation ──────────────────────
415
+ // This block will be removed when toolsRequiringConfirmation is removed.
416
+ // Only call the deprecated function when deprecated options are actually used.
417
+ const toolsRequiringConfirmation = useMemo(
418
+ () =>
419
+ manualToolsRequiringConfirmation ??
420
+ (tools ? detectToolsRequiringConfirmation(tools) : []),
421
+ [manualToolsRequiringConfirmation, tools]
422
+ );
351
423
 
352
- // Keep a ref to always point to the latest onToolCall callback
424
+ // Keep refs to always point to the latest callbacks
353
425
  const onToolCallRef = useRef(onToolCall);
354
426
  onToolCallRef.current = onToolCall;
427
+ const onDataRef = useRef(onData);
428
+ onDataRef.current = onData;
355
429
 
356
430
  const agentUrl = new URL(
357
431
  `${
@@ -450,139 +524,6 @@ export function useAgentChat<
450
524
  };
451
525
  }, [initialMessagesCacheKey, initialMessagesPromise]);
452
526
 
453
- const aiFetch = useCallback(
454
- async (request: RequestInfo | URL, options: RequestInit = {}) => {
455
- const {
456
- method,
457
- keepalive,
458
- headers,
459
- body,
460
- redirect,
461
- integrity,
462
- signal,
463
- credentials,
464
- mode,
465
- referrer,
466
- referrerPolicy,
467
- window
468
- } = options;
469
- const id = nanoid(8);
470
- const abortController = new AbortController();
471
- let controller: ReadableStreamDefaultController;
472
- const currentAgent = agentRef.current;
473
-
474
- // Track this request ID so the onAgentMessage handler knows to skip it
475
- // (this tab's aiFetch listener handles its own stream)
476
- localRequestIdsRef.current.add(id);
477
-
478
- signal?.addEventListener("abort", () => {
479
- currentAgent.send(
480
- JSON.stringify({
481
- id,
482
- type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL
483
- })
484
- );
485
-
486
- // NOTE - If we wanted to, we could preserve the "interrupted" message here, with the code below
487
- // However, I think it might be the responsibility of the library user to implement that behavior manually?
488
- // Reasoning: This code could be subject to collisions, as it "force saves" the messages we have locally
489
- //
490
- // agent.send(JSON.stringify({
491
- // type: MessageType.CF_AGENT_CHAT_MESSAGES,
492
- // messages: ... /* some way of getting current messages ref? */
493
- // }))
494
- abortController.abort();
495
- // Make sure to also close the stream (cf. https://github.com/cloudflare/agents-starter/issues/69)
496
- try {
497
- controller.close();
498
- } catch {
499
- // Stream may already be errored or closed
500
- }
501
- // Clean up the request ID tracking
502
- localRequestIdsRef.current.delete(id);
503
- });
504
-
505
- currentAgent.addEventListener(
506
- "message",
507
- (event) => {
508
- let data: OutgoingMessage<ChatMessage>;
509
- try {
510
- data = JSON.parse(event.data) as OutgoingMessage<ChatMessage>;
511
- } catch (_error) {
512
- // silently ignore invalid messages for now
513
- // TODO: log errors with log levels
514
- return;
515
- }
516
- if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE) {
517
- if (data.id === id) {
518
- if (data.error) {
519
- controller.error(new Error(data.body));
520
- abortController.abort();
521
- // Clean up the request ID tracking
522
- localRequestIdsRef.current.delete(id);
523
- } else {
524
- // Only enqueue non-empty data to prevent JSON parsing errors
525
- if (data.body?.trim()) {
526
- controller.enqueue(
527
- new TextEncoder().encode(`data: ${data.body}\n\n`)
528
- );
529
- }
530
- if (data.done) {
531
- try {
532
- controller.close();
533
- } catch {
534
- // Stream may already be errored or closed
535
- }
536
- abortController.abort();
537
- // Clean up the request ID tracking
538
- localRequestIdsRef.current.delete(id);
539
- }
540
- }
541
- }
542
- }
543
- },
544
- { signal: abortController.signal }
545
- );
546
-
547
- const stream = new ReadableStream({
548
- start(c) {
549
- controller = c;
550
- },
551
- cancel(reason?: unknown) {
552
- console.warn(
553
- "[@cloudflare/ai-chat/react] cancelling stream",
554
- id,
555
- reason || "no reason"
556
- );
557
- }
558
- });
559
-
560
- currentAgent.send(
561
- JSON.stringify({
562
- id,
563
- init: {
564
- body,
565
- credentials,
566
- headers,
567
- integrity,
568
- keepalive,
569
- method,
570
- mode,
571
- redirect,
572
- referrer,
573
- referrerPolicy,
574
- window
575
- },
576
- type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
577
- url: request.toString()
578
- })
579
- );
580
-
581
- return new Response(stream);
582
- },
583
- []
584
- );
585
-
586
527
  // Use synchronous ref updates to avoid race conditions between effect runs.
587
528
  // This ensures the ref always has the latest value before any effect reads it.
588
529
  const toolsRef = useRef(tools);
@@ -591,69 +532,67 @@ export function useAgentChat<
591
532
  const prepareSendMessagesRequestRef = useRef(prepareSendMessagesRequest);
592
533
  prepareSendMessagesRequestRef.current = prepareSendMessagesRequest;
593
534
 
594
- const customTransport: ChatTransport<ChatMessage> = useMemo(
595
- () => ({
596
- sendMessages: async (
597
- sendMessageOptions: Parameters<
598
- typeof DefaultChatTransport.prototype.sendMessages
599
- >[0]
600
- ) => {
601
- // Extract schemas from tools with execute functions
602
- const clientToolSchemas = extractClientToolSchemas(toolsRef.current);
603
-
604
- const combinedPrepare =
605
- clientToolSchemas || prepareSendMessagesRequestRef.current
606
- ? async (
607
- prepareOptions: PrepareSendMessagesRequestOptions<ChatMessage>
608
- ): Promise<InternalPrepareResult> => {
609
- // Start with auto-extracted client tool schemas
610
- let body: Record<string, unknown> = {};
611
- let headers: HeadersInit | undefined;
612
- let credentials: RequestCredentials | undefined;
613
- let api: string | undefined;
614
-
615
- if (clientToolSchemas) {
616
- body = {
617
- id: prepareOptions.id,
618
- messages: prepareOptions.messages,
619
- trigger: prepareOptions.trigger,
620
- clientTools: clientToolSchemas
621
- };
622
- }
535
+ const bodyOptionRef = useRef(bodyOption);
536
+ bodyOptionRef.current = bodyOption;
623
537
 
624
- // Apply prepareSendMessagesRequest callback for additional customization
625
- if (prepareSendMessagesRequestRef.current) {
626
- const userResult =
627
- await prepareSendMessagesRequestRef.current(prepareOptions);
628
-
629
- // user's callback can override or extend
630
- headers = userResult.headers;
631
- credentials = userResult.credentials;
632
- api = userResult.api;
633
- body = {
634
- ...body,
635
- ...(userResult.body ?? {})
636
- };
637
- }
538
+ /**
539
+ * Tracks request IDs initiated by this tab via the transport.
540
+ * Used by onAgentMessage to skip messages already handled by the transport.
541
+ */
542
+ const localRequestIdsRef = useRef<Set<string>>(new Set());
638
543
 
639
- return { body, headers, credentials, api };
640
- }
641
- : undefined;
544
+ // WebSocket-based transport that speaks the CF_AGENT protocol natively.
545
+ // Replaces the old aiFetch + DefaultChatTransport indirection.
546
+ const customTransport = useMemo(
547
+ () =>
548
+ new WebSocketChatTransport<ChatMessage>({
549
+ agent: agentRef.current,
550
+ activeRequestIds: localRequestIdsRef.current,
551
+ prepareBody: async ({ messages: msgs, trigger, messageId }) => {
552
+ // Start with the top-level body option (static or dynamic)
553
+ let extraBody: Record<string, unknown> = {};
554
+ const currentBody = bodyOptionRef.current;
555
+ if (currentBody) {
556
+ const resolved =
557
+ typeof currentBody === "function"
558
+ ? await currentBody()
559
+ : currentBody;
560
+ extraBody = { ...resolved };
561
+ }
642
562
 
643
- const transport = new DefaultChatTransport<ChatMessage>({
644
- api: agentUrlString,
645
- fetch: aiFetch,
646
- prepareSendMessagesRequest: combinedPrepare
647
- });
648
- return transport.sendMessages(sendMessageOptions);
649
- },
650
- reconnectToStream: async () => null
651
- }),
652
- [agentUrlString, aiFetch]
563
+ // Extract schemas from deprecated client tools (if any)
564
+ // Only extract client tool schemas when deprecated tools option is used
565
+ if (toolsRef.current) {
566
+ const clientToolSchemas = extractClientToolSchemas(
567
+ toolsRef.current
568
+ );
569
+ if (clientToolSchemas) {
570
+ extraBody.clientTools = clientToolSchemas;
571
+ }
572
+ }
573
+
574
+ // Apply user's prepareSendMessagesRequest callback (overrides body option)
575
+ if (prepareSendMessagesRequestRef.current) {
576
+ const userResult = await prepareSendMessagesRequestRef.current({
577
+ id: agent._pk,
578
+ messages: msgs,
579
+ trigger,
580
+ messageId
581
+ });
582
+ if (userResult.body) {
583
+ Object.assign(extraBody, userResult.body);
584
+ }
585
+ }
586
+
587
+ return extraBody;
588
+ }
589
+ }),
590
+ [agent._pk]
653
591
  );
654
592
 
655
593
  const useChatHelpers = useChat<ChatMessage>({
656
594
  ...rest,
595
+ onData,
657
596
  messages: initialMessages,
658
597
  transport: customTransport,
659
598
  id: agent._pk
@@ -662,8 +601,27 @@ export function useAgentChat<
662
601
  // automatically resumes active streams when the WebSocket reconnects.
663
602
  });
664
603
 
604
+ // Destructure stable method references from useChatHelpers.
605
+ // These are individually memoized by the AI SDK (via useCallback), so they're
606
+ // safe to use in dependency arrays without causing re-renders. Using them
607
+ // directly instead of `useChatHelpers.method` avoids the exhaustive-deps
608
+ // warning about the unstable `useChatHelpers` object.
609
+ const {
610
+ messages: chatMessages,
611
+ setMessages,
612
+ addToolResult,
613
+ addToolApprovalResponse,
614
+ sendMessage
615
+ } = useChatHelpers;
616
+
665
617
  const processedToolCalls = useRef(new Set<string>());
666
618
  const isResolvingToolsRef = useRef(false);
619
+ // Counter to force the tool resolution effect to re-run after completing
620
+ // a batch of tool calls. Without this, if new tool calls arrive while
621
+ // isResolvingToolsRef is true (e.g. server auto-continuation), the effect
622
+ // exits early and never retriggers because the ref reset doesn't cause
623
+ // a re-render.
624
+ const [toolResolutionTrigger, setToolResolutionTrigger] = useState(0);
667
625
 
668
626
  // Fix for issue #728: Track client-side tool results in local state
669
627
  // to ensure tool parts show output-available immediately after execution.
@@ -672,12 +630,11 @@ export function useAgentChat<
672
630
  >(new Map());
673
631
 
674
632
  // Ref to access current messages in callbacks without stale closures
675
- const messagesRef = useRef(useChatHelpers.messages);
676
- messagesRef.current = useChatHelpers.messages;
633
+ const messagesRef = useRef(chatMessages);
634
+ messagesRef.current = chatMessages;
677
635
 
678
636
  // Calculate pending confirmations for the latest assistant message
679
- const lastMessage =
680
- useChatHelpers.messages[useChatHelpers.messages.length - 1];
637
+ const lastMessage = chatMessages[chatMessages.length - 1];
681
638
 
682
639
  const pendingConfirmations = (() => {
683
640
  if (!lastMessage || lastMessage.role !== "assistant") {
@@ -700,7 +657,8 @@ export function useAgentChat<
700
657
  const pendingConfirmationsRef = useRef(pendingConfirmations);
701
658
  pendingConfirmationsRef.current = pendingConfirmations;
702
659
 
703
- // Automatic tool resolution effect.
660
+ // ── DEPRECATED: automatic tool resolution effect ────────────────────
661
+ // This entire useEffect is deprecated. Use onToolCall instead.
704
662
  useEffect(() => {
705
663
  if (!experimental_automaticToolResolution) {
706
664
  return;
@@ -711,13 +669,12 @@ export function useAgentChat<
711
669
  return;
712
670
  }
713
671
 
714
- const lastMessage =
715
- useChatHelpers.messages[useChatHelpers.messages.length - 1];
716
- if (!lastMessage || lastMessage.role !== "assistant") {
672
+ const lastMsg = chatMessages[chatMessages.length - 1];
673
+ if (!lastMsg || lastMsg.role !== "assistant") {
717
674
  return;
718
675
  }
719
676
 
720
- const toolCalls = lastMessage.parts.filter(
677
+ const toolCalls = lastMsg.parts.filter(
721
678
  (part) =>
722
679
  isToolUIPart(part) &&
723
680
  part.state === "input-available" &&
@@ -771,6 +728,7 @@ export function useAgentChat<
771
728
 
772
729
  if (toolResults.length > 0) {
773
730
  // Send tool results to server first (server is source of truth)
731
+ const clientToolSchemas = extractClientToolSchemas(currentTools);
774
732
  for (const result of toolResults) {
775
733
  agentRef.current.send(
776
734
  JSON.stringify({
@@ -778,7 +736,8 @@ export function useAgentChat<
778
736
  toolCallId: result.toolCallId,
779
737
  toolName: result.toolName,
780
738
  output: result.output,
781
- autoContinue: autoContinueAfterToolResult
739
+ autoContinue: autoContinueAfterToolResult,
740
+ clientTools: clientToolSchemas
782
741
  })
783
742
  );
784
743
  }
@@ -786,7 +745,7 @@ export function useAgentChat<
786
745
  // Also update local state via AI SDK for immediate UI feedback
787
746
  await Promise.all(
788
747
  toolResults.map((result) =>
789
- useChatHelpers.addToolResult({
748
+ addToolResult({
790
749
  tool: result.toolName,
791
750
  toolCallId: result.toolCallId,
792
751
  output: result.output
@@ -807,16 +766,20 @@ export function useAgentChat<
807
766
  // The server will continue the conversation after applying tool results.
808
767
  } finally {
809
768
  isResolvingToolsRef.current = false;
769
+ // Trigger a re-run so any tool calls that arrived while we were
770
+ // busy (e.g. from server auto-continuation) get picked up.
771
+ setToolResolutionTrigger((c) => c + 1);
810
772
  }
811
773
  })();
812
774
  }
813
775
  }
814
776
  }, [
815
- useChatHelpers.messages,
777
+ chatMessages,
816
778
  experimental_automaticToolResolution,
817
- useChatHelpers.addToolResult,
779
+ addToolResult,
818
780
  toolsRequiringConfirmation,
819
- autoContinueAfterToolResult
781
+ autoContinueAfterToolResult,
782
+ toolResolutionTrigger
820
783
  ]);
821
784
 
822
785
  // Helper function to send tool output to server
@@ -828,7 +791,10 @@ export function useAgentChat<
828
791
  toolCallId,
829
792
  toolName,
830
793
  output,
831
- autoContinue: autoContinueAfterToolResult
794
+ autoContinue: autoContinueAfterToolResult,
795
+ clientTools: toolsRef.current
796
+ ? extractClientToolSchemas(toolsRef.current)
797
+ : undefined
832
798
  })
833
799
  );
834
800
 
@@ -844,11 +810,12 @@ export function useAgentChat<
844
810
  JSON.stringify({
845
811
  type: MessageType.CF_AGENT_TOOL_APPROVAL,
846
812
  toolCallId,
847
- approved
813
+ approved,
814
+ autoContinue: autoContinueAfterToolResult
848
815
  })
849
816
  );
850
817
  },
851
- []
818
+ [autoContinueAfterToolResult]
852
819
  );
853
820
 
854
821
  // Effect for new onToolCall callback pattern (v6 style)
@@ -859,14 +826,13 @@ export function useAgentChat<
859
826
  return;
860
827
  }
861
828
 
862
- const lastMessage =
863
- useChatHelpers.messages[useChatHelpers.messages.length - 1];
864
- if (!lastMessage || lastMessage.role !== "assistant") {
829
+ const lastMsg = chatMessages[chatMessages.length - 1];
830
+ if (!lastMsg || lastMsg.role !== "assistant") {
865
831
  return;
866
832
  }
867
833
 
868
834
  // Find tool calls in input-available state that haven't been processed
869
- const pendingToolCalls = lastMessage.parts.filter(
835
+ const pendingToolCalls = lastMsg.parts.filter(
870
836
  (part) =>
871
837
  isToolUIPart(part) &&
872
838
  part.state === "input-available" &&
@@ -889,7 +855,7 @@ export function useAgentChat<
889
855
  sendToolOutputToServer(opts.toolCallId, toolName, opts.output);
890
856
 
891
857
  // Update local state via AI SDK
892
- useChatHelpers.addToolResult({
858
+ addToolResult({
893
859
  tool: toolName,
894
860
  toolCallId: opts.toolCallId,
895
861
  output: opts.output
@@ -908,27 +874,55 @@ export function useAgentChat<
908
874
  });
909
875
  }
910
876
  }
911
- }, [
912
- useChatHelpers.messages,
913
- sendToolOutputToServer,
914
- useChatHelpers.addToolResult
915
- ]);
877
+ }, [chatMessages, sendToolOutputToServer, addToolResult]);
916
878
 
917
879
  /**
918
- * Contains the request ID, accumulated message parts, and a unique message ID.
880
+ * Contains the request ID, accumulated message parts, metadata, and a unique message ID.
919
881
  * Used for both resumed streams and real-time broadcasts from other tabs.
882
+ * Metadata is captured from start/finish/message-metadata stream chunks
883
+ * so that it's included when the partial message is flushed to React state.
920
884
  */
921
885
  const activeStreamRef = useRef<{
922
886
  id: string;
923
887
  messageId: string;
924
888
  parts: ChatMessage["parts"];
889
+ metadata?: Record<string, unknown>;
925
890
  } | null>(null);
926
891
 
927
892
  /**
928
- * Tracks request IDs initiated by this tab via aiFetch.
929
- * Used to distinguish local requests from broadcasts.
893
+ * Flush the active stream's accumulated parts into React state.
894
+ * Extracted as a helper so it can be called both during live streaming
895
+ * (per-chunk) and after replay completes (once, at done).
930
896
  */
931
- const localRequestIdsRef = useRef<Set<string>>(new Set());
897
+ const flushActiveStreamToMessages = useCallback(
898
+ (activeMsg: {
899
+ id: string;
900
+ messageId: string;
901
+ parts: ChatMessage["parts"];
902
+ metadata?: Record<string, unknown>;
903
+ }) => {
904
+ setMessages((prevMessages: ChatMessage[]) => {
905
+ const existingIdx = prevMessages.findIndex(
906
+ (m) => m.id === activeMsg.messageId
907
+ );
908
+
909
+ const partialMessage = {
910
+ id: activeMsg.messageId,
911
+ role: "assistant" as const,
912
+ parts: [...activeMsg.parts],
913
+ ...(activeMsg.metadata != null && { metadata: activeMsg.metadata })
914
+ } as unknown as ChatMessage;
915
+
916
+ if (existingIdx >= 0) {
917
+ const updated = [...prevMessages];
918
+ updated[existingIdx] = partialMessage;
919
+ return updated;
920
+ }
921
+ return [...prevMessages, partialMessage];
922
+ });
923
+ },
924
+ [setMessages]
925
+ );
932
926
 
933
927
  useEffect(() => {
934
928
  /**
@@ -947,17 +941,17 @@ export function useAgentChat<
947
941
 
948
942
  switch (data.type) {
949
943
  case MessageType.CF_AGENT_CHAT_CLEAR:
950
- useChatHelpers.setMessages([]);
944
+ setMessages([]);
951
945
  break;
952
946
 
953
947
  case MessageType.CF_AGENT_CHAT_MESSAGES:
954
- useChatHelpers.setMessages(data.messages);
948
+ setMessages(data.messages);
955
949
  break;
956
950
 
957
951
  case MessageType.CF_AGENT_MESSAGE_UPDATED:
958
952
  // Server updated a message (e.g., applied tool result)
959
953
  // Update the specific message in local state
960
- useChatHelpers.setMessages((prevMessages: ChatMessage[]) => {
954
+ setMessages((prevMessages: ChatMessage[]) => {
961
955
  const updatedMessage = data.message;
962
956
 
963
957
  // First try to find by message ID
@@ -1040,14 +1034,23 @@ export function useAgentChat<
1040
1034
  ) {
1041
1035
  let messageId = nanoid();
1042
1036
  let existingParts: ChatMessage["parts"] = [];
1037
+ let existingMetadata: Record<string, unknown> | undefined;
1043
1038
 
1044
- // For continuations, use the last assistant message's ID and parts
1039
+ // For continuations, use the last assistant message's ID, parts, and metadata
1045
1040
  if (isContinuation) {
1046
1041
  const currentMessages = messagesRef.current;
1047
1042
  for (let i = currentMessages.length - 1; i >= 0; i--) {
1048
1043
  if (currentMessages[i].role === "assistant") {
1049
1044
  messageId = currentMessages[i].id;
1050
1045
  existingParts = [...currentMessages[i].parts];
1046
+ if (currentMessages[i].metadata != null) {
1047
+ existingMetadata = {
1048
+ ...(currentMessages[i].metadata as Record<
1049
+ string,
1050
+ unknown
1051
+ >)
1052
+ };
1053
+ }
1051
1054
  break;
1052
1055
  }
1053
1056
  }
@@ -1056,177 +1059,84 @@ export function useAgentChat<
1056
1059
  activeStreamRef.current = {
1057
1060
  id: data.id,
1058
1061
  messageId,
1059
- parts: existingParts
1062
+ parts: existingParts,
1063
+ metadata: existingMetadata
1060
1064
  };
1061
1065
  }
1062
1066
 
1063
1067
  const activeMsg = activeStreamRef.current;
1068
+ const isReplay = data.replay === true;
1064
1069
 
1065
1070
  if (data.body?.trim()) {
1066
1071
  try {
1067
1072
  const chunkData = JSON.parse(data.body);
1068
1073
 
1069
- // Handle all chunk types for complete message reconstruction
1070
- switch (chunkData.type) {
1071
- case "text-start": {
1072
- activeMsg.parts.push({
1073
- type: "text",
1074
- text: "",
1075
- state: "streaming"
1076
- });
1077
- break;
1078
- }
1079
- case "text-delta": {
1080
- const lastTextPart = [...activeMsg.parts]
1081
- .reverse()
1082
- .find((p) => p.type === "text");
1083
- if (lastTextPart && lastTextPart.type === "text") {
1084
- lastTextPart.text += chunkData.delta;
1085
- } else {
1086
- // Handle plain text responses (no text-start)
1087
- activeMsg.parts.push({
1088
- type: "text",
1089
- text: chunkData.delta
1090
- });
1091
- }
1092
- break;
1093
- }
1094
- case "text-end": {
1095
- const lastTextPart = [...activeMsg.parts]
1096
- .reverse()
1097
- .find((p) => p.type === "text");
1098
- if (lastTextPart && "state" in lastTextPart) {
1099
- lastTextPart.state = "done";
1100
- }
1101
- break;
1102
- }
1103
- case "reasoning-start": {
1104
- activeMsg.parts.push({
1105
- type: "reasoning",
1106
- text: "",
1107
- state: "streaming"
1108
- });
1109
- break;
1110
- }
1111
- case "reasoning-delta": {
1112
- const lastReasoningPart = [...activeMsg.parts]
1113
- .reverse()
1114
- .find((p) => p.type === "reasoning");
1115
- if (
1116
- lastReasoningPart &&
1117
- lastReasoningPart.type === "reasoning"
1118
- ) {
1119
- lastReasoningPart.text += chunkData.delta;
1120
- }
1121
- break;
1122
- }
1123
- case "reasoning-end": {
1124
- const lastReasoningPart = [...activeMsg.parts]
1125
- .reverse()
1126
- .find((p) => p.type === "reasoning");
1127
- if (lastReasoningPart && "state" in lastReasoningPart) {
1128
- lastReasoningPart.state = "done";
1129
- }
1130
- break;
1131
- }
1132
- case "file": {
1133
- activeMsg.parts.push({
1134
- type: "file",
1135
- mediaType: chunkData.mediaType,
1136
- url: chunkData.url
1137
- });
1138
- break;
1139
- }
1140
- case "source-url": {
1141
- activeMsg.parts.push({
1142
- type: "source-url",
1143
- sourceId: chunkData.sourceId,
1144
- url: chunkData.url,
1145
- title: chunkData.title
1146
- });
1147
- break;
1148
- }
1149
- case "source-document": {
1150
- activeMsg.parts.push({
1151
- type: "source-document",
1152
- sourceId: chunkData.sourceId,
1153
- mediaType: chunkData.mediaType,
1154
- title: chunkData.title,
1155
- filename: chunkData.filename
1156
- });
1157
- break;
1158
- }
1159
- case "tool-input-available": {
1160
- // Add tool call part when input is available
1161
- activeMsg.parts.push({
1162
- type: `tool-${chunkData.toolName}`,
1163
- toolCallId: chunkData.toolCallId,
1164
- toolName: chunkData.toolName,
1165
- state: "input-available",
1166
- input: chunkData.input
1167
- } as ChatMessage["parts"][number]);
1168
- break;
1169
- }
1170
- case "tool-output-available": {
1171
- // Update existing tool part with output using immutable pattern
1172
- activeMsg.parts = activeMsg.parts.map((p) => {
1173
- if (
1174
- "toolCallId" in p &&
1175
- p.toolCallId === chunkData.toolCallId &&
1176
- "state" in p
1177
- ) {
1178
- return {
1179
- ...p,
1180
- state: "output-available",
1181
- output: chunkData.output
1182
- } as ChatMessage["parts"][number];
1183
- }
1184
- return p;
1185
- });
1186
- break;
1074
+ // Apply chunk to parts using shared parser.
1075
+ // Handles text, reasoning, file, source, tool, step, and data-* chunks.
1076
+ // Unrecognized types (tool-input-start, tool-input-delta, etc.)
1077
+ // are intermediate states — the final state is captured by
1078
+ // tool-input-available / tool-output-available.
1079
+ const handled = applyChunkToParts(
1080
+ activeMsg.parts as MessageParts,
1081
+ chunkData
1082
+ );
1083
+
1084
+ // Fire onData callback for data-* parts (stream resumption
1085
+ // and cross-tab broadcasts). For the transport path (new
1086
+ // messages from this tab), the AI SDK's pipeline invokes
1087
+ // onData internally.
1088
+ if (
1089
+ typeof chunkData.type === "string" &&
1090
+ chunkData.type.startsWith("data-") &&
1091
+ onDataRef.current
1092
+ ) {
1093
+ onDataRef.current(chunkData);
1094
+ }
1095
+
1096
+ // Capture message metadata from start/finish/message-metadata
1097
+ // chunks. These carry metadata like timestamps, model info, and
1098
+ // token usage that should be attached at the message level.
1099
+ if (
1100
+ !handled &&
1101
+ (chunkData.type === "start" ||
1102
+ chunkData.type === "finish" ||
1103
+ chunkData.type === "message-metadata")
1104
+ ) {
1105
+ if (chunkData.messageId != null && chunkData.type === "start") {
1106
+ activeMsg.messageId = chunkData.messageId;
1187
1107
  }
1188
- case "step-start": {
1189
- activeMsg.parts.push({ type: "step-start" });
1190
- break;
1108
+ if (chunkData.messageMetadata != null) {
1109
+ activeMsg.metadata = activeMsg.metadata
1110
+ ? { ...activeMsg.metadata, ...chunkData.messageMetadata }
1111
+ : { ...chunkData.messageMetadata };
1191
1112
  }
1192
- // Other chunk types (tool-input-start, tool-input-delta, etc.)
1193
- // are intermediate states - the final state will be captured above
1194
1113
  }
1195
1114
 
1196
- // Update messages with the partial response
1197
- useChatHelpers.setMessages((prevMessages: ChatMessage[]) => {
1198
- if (!activeMsg) return prevMessages;
1199
-
1200
- const existingIdx = prevMessages.findIndex(
1201
- (m) => m.id === activeMsg.messageId
1202
- );
1203
-
1204
- const partialMessage = {
1205
- id: activeMsg.messageId,
1206
- role: "assistant" as const,
1207
- parts: [...activeMsg.parts]
1208
- } as unknown as ChatMessage;
1209
-
1210
- if (existingIdx >= 0) {
1211
- const updated = [...prevMessages];
1212
- updated[existingIdx] = partialMessage;
1213
- return updated;
1214
- }
1215
- return [...prevMessages, partialMessage];
1216
- });
1115
+ // For replayed chunks, skip intermediate setMessages calls.
1116
+ // Replayed chunks arrive synchronously in a tight loop, so React
1117
+ // would batch all state updates into a single render anyway —
1118
+ // causing intermediate states (like "Thinking...") to be lost.
1119
+ // We defer the render until replay is complete (done signal).
1120
+ if (!isReplay) {
1121
+ flushActiveStreamToMessages(activeMsg);
1122
+ }
1217
1123
  } catch (parseError) {
1218
- // Log corrupted chunk for debugging - could indicate data loss
1219
1124
  console.warn(
1220
1125
  "[useAgentChat] Failed to parse stream chunk:",
1221
1126
  parseError instanceof Error ? parseError.message : parseError,
1222
1127
  "body:",
1223
- data.body?.slice(0, 100) // Truncate for logging
1128
+ data.body?.slice(0, 100)
1224
1129
  );
1225
1130
  }
1226
1131
  }
1227
1132
 
1228
- // Clear on completion or error
1133
+ // On completion or error, flush final state to messages
1229
1134
  if (data.done || data.error) {
1135
+ // For replayed streams, this is the single render point —
1136
+ // all parts have been accumulated, now render them at once.
1137
+ if (isReplay && activeMsg) {
1138
+ flushActiveStreamToMessages(activeMsg);
1139
+ }
1230
1140
  activeStreamRef.current = null;
1231
1141
  }
1232
1142
  break;
@@ -1235,71 +1145,87 @@ export function useAgentChat<
1235
1145
  }
1236
1146
 
1237
1147
  agent.addEventListener("message", onAgentMessage);
1148
+
1149
+ // Request stream resume check AFTER the handler is registered.
1150
+ // This avoids the race condition where CF_AGENT_STREAM_RESUMING sent
1151
+ // in onConnect arrives before this useEffect runs. The server also
1152
+ // sends it in onConnect as a fallback for older clients.
1153
+ if (resume) {
1154
+ agent.send(
1155
+ JSON.stringify({
1156
+ type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST
1157
+ })
1158
+ );
1159
+ }
1160
+
1238
1161
  return () => {
1239
1162
  agent.removeEventListener("message", onAgentMessage);
1240
1163
  // Clear active stream state on cleanup to prevent memory leak
1241
1164
  activeStreamRef.current = null;
1242
1165
  };
1243
- }, [agent, useChatHelpers.setMessages, resume]);
1166
+ }, [agent, setMessages, resume, flushActiveStreamToMessages]);
1167
+
1168
+ // ── DEPRECATED: addToolResult wrapper with confirmation batching ────
1169
+ // This wrapper is deprecated. Use addToolOutput or addToolApprovalResponse instead.
1170
+ const addToolResultAndSendMessage: typeof addToolResult = async (args) => {
1171
+ const { toolCallId } = args;
1172
+ const toolName = "tool" in args ? args.tool : "";
1173
+ const output = "output" in args ? args.output : undefined;
1174
+
1175
+ // Send tool result to server (server is source of truth)
1176
+ // Include flag to tell server whether to auto-continue
1177
+ agentRef.current.send(
1178
+ JSON.stringify({
1179
+ type: MessageType.CF_AGENT_TOOL_RESULT,
1180
+ toolCallId,
1181
+ toolName,
1182
+ output,
1183
+ autoContinue: autoContinueAfterToolResult,
1184
+ clientTools: toolsRef.current
1185
+ ? extractClientToolSchemas(toolsRef.current)
1186
+ : undefined
1187
+ })
1188
+ );
1244
1189
 
1245
- // Wrapper that sends tool result to server and optionally continues conversation.
1246
- const addToolResultAndSendMessage: typeof useChatHelpers.addToolResult =
1247
- async (args) => {
1248
- const { toolCallId } = args;
1249
- const toolName = "tool" in args ? args.tool : "";
1250
- const output = "output" in args ? args.output : undefined;
1190
+ setClientToolResults((prev) => new Map(prev).set(toolCallId, output));
1251
1191
 
1252
- // Send tool result to server (server is source of truth)
1253
- // Include flag to tell server whether to auto-continue
1254
- agentRef.current.send(
1255
- JSON.stringify({
1256
- type: MessageType.CF_AGENT_TOOL_RESULT,
1257
- toolCallId,
1258
- toolName,
1259
- output,
1260
- autoContinue: autoContinueAfterToolResult
1261
- })
1262
- );
1263
-
1264
- setClientToolResults((prev) => new Map(prev).set(toolCallId, output));
1192
+ // Call AI SDK's addToolResult for local state update (non-blocking)
1193
+ // We don't await this since clientToolResults provides immediate UI feedback
1194
+ addToolResult(args);
1265
1195
 
1266
- // Call AI SDK's addToolResult for local state update (non-blocking)
1267
- // We don't await this since clientToolResults provides immediate UI feedback
1268
- useChatHelpers.addToolResult(args);
1269
-
1270
- // If server auto-continuation is disabled, client needs to trigger continuation
1271
- if (!autoContinueAfterToolResult) {
1272
- // Use legacy behavior: batch confirmations or send immediately
1273
- if (!autoSendAfterAllConfirmationsResolved) {
1274
- // Always send immediately
1275
- useChatHelpers.sendMessage();
1276
- return;
1277
- }
1196
+ // If server auto-continuation is disabled, client needs to trigger continuation
1197
+ if (!autoContinueAfterToolResult) {
1198
+ // Use legacy behavior: batch confirmations or send immediately
1199
+ if (!autoSendAfterAllConfirmationsResolved) {
1200
+ // Always send immediately
1201
+ sendMessage();
1202
+ return;
1203
+ }
1278
1204
 
1279
- // Wait for all confirmations before sending
1280
- const pending = pendingConfirmationsRef.current?.toolCallIds;
1281
- if (!pending) {
1282
- useChatHelpers.sendMessage();
1283
- return;
1284
- }
1205
+ // Wait for all confirmations before sending
1206
+ const pending = pendingConfirmationsRef.current?.toolCallIds;
1207
+ if (!pending) {
1208
+ sendMessage();
1209
+ return;
1210
+ }
1285
1211
 
1286
- const wasLast = pending.size === 1 && pending.has(toolCallId);
1287
- if (pending.has(toolCallId)) {
1288
- pending.delete(toolCallId);
1289
- }
1212
+ const wasLast = pending.size === 1 && pending.has(toolCallId);
1213
+ if (pending.has(toolCallId)) {
1214
+ pending.delete(toolCallId);
1215
+ }
1290
1216
 
1291
- if (wasLast || pending.size === 0) {
1292
- useChatHelpers.sendMessage();
1293
- }
1217
+ if (wasLast || pending.size === 0) {
1218
+ sendMessage();
1294
1219
  }
1295
- // If autoContinueAfterToolResult is true, server handles continuation
1296
- };
1220
+ }
1221
+ // If autoContinueAfterToolResult is true, server handles continuation
1222
+ };
1297
1223
 
1298
1224
  // Wrapper that sends tool approval to server before updating local state.
1299
1225
  // This prevents duplicate messages by ensuring server updates the message
1300
1226
  // in place with the existing ID, rather than relying on ID resolution
1301
1227
  // when sendMessage() is called later.
1302
- const addToolApprovalResponseAndNotifyServer: typeof useChatHelpers.addToolApprovalResponse =
1228
+ const addToolApprovalResponseAndNotifyServer: typeof addToolApprovalResponse =
1303
1229
  (args) => {
1304
1230
  const { id: approvalId, approved } = args;
1305
1231
 
@@ -1331,16 +1257,16 @@ export function useAgentChat<
1331
1257
  }
1332
1258
 
1333
1259
  // Call AI SDK's addToolApprovalResponse for local state update
1334
- useChatHelpers.addToolApprovalResponse(args);
1260
+ addToolApprovalResponse(args);
1335
1261
  };
1336
1262
 
1337
1263
  // Fix for issue #728: Merge client-side tool results with messages
1338
1264
  // so tool parts show output-available immediately after execution
1339
1265
  const messagesWithToolResults = useMemo(() => {
1340
1266
  if (clientToolResults.size === 0) {
1341
- return useChatHelpers.messages;
1267
+ return chatMessages;
1342
1268
  }
1343
- return useChatHelpers.messages.map((msg) => ({
1269
+ return chatMessages.map((msg) => ({
1344
1270
  ...msg,
1345
1271
  parts: msg.parts.map((p) => {
1346
1272
  if (
@@ -1358,7 +1284,7 @@ export function useAgentChat<
1358
1284
  };
1359
1285
  })
1360
1286
  })) as ChatMessage[];
1361
- }, [useChatHelpers.messages, clientToolResults]);
1287
+ }, [chatMessages, clientToolResults]);
1362
1288
 
1363
1289
  // Cleanup stale entries from clientToolResults when messages change
1364
1290
  // to prevent memory leak in long conversations.
@@ -1367,7 +1293,7 @@ export function useAgentChat<
1367
1293
  useEffect(() => {
1368
1294
  // Collect all current toolCallIds from messages
1369
1295
  const currentToolCallIds = new Set<string>();
1370
- for (const msg of useChatHelpers.messages) {
1296
+ for (const msg of chatMessages) {
1371
1297
  for (const part of msg.parts) {
1372
1298
  if ("toolCallId" in part && part.toolCallId) {
1373
1299
  currentToolCallIds.add(part.toolCallId);
@@ -1407,7 +1333,7 @@ export function useAgentChat<
1407
1333
  }
1408
1334
  }
1409
1335
  // eslint-disable-next-line react-hooks/exhaustive-deps
1410
- }, [useChatHelpers.messages]);
1336
+ }, [chatMessages]);
1411
1337
 
1412
1338
  // Create addToolOutput function for external use
1413
1339
  const addToolOutput = useCallback(
@@ -1416,13 +1342,13 @@ export function useAgentChat<
1416
1342
  sendToolOutputToServer(opts.toolCallId, toolName, opts.output);
1417
1343
 
1418
1344
  // Update local state via AI SDK
1419
- useChatHelpers.addToolResult({
1345
+ addToolResult({
1420
1346
  tool: toolName,
1421
1347
  toolCallId: opts.toolCallId,
1422
1348
  output: opts.output
1423
1349
  });
1424
1350
  },
1425
- [sendToolOutputToServer, useChatHelpers.addToolResult]
1351
+ [sendToolOutputToServer, addToolResult]
1426
1352
  );
1427
1353
 
1428
1354
  return {
@@ -1444,7 +1370,7 @@ export function useAgentChat<
1444
1370
  */
1445
1371
  addToolApprovalResponse: addToolApprovalResponseAndNotifyServer,
1446
1372
  clearHistory: () => {
1447
- useChatHelpers.setMessages([]);
1373
+ setMessages([]);
1448
1374
  setClientToolResults(new Map());
1449
1375
  processedToolCalls.current.clear();
1450
1376
  agent.send(
@@ -1453,13 +1379,21 @@ export function useAgentChat<
1453
1379
  })
1454
1380
  );
1455
1381
  },
1456
- setMessages: (
1457
- messages: Parameters<typeof useChatHelpers.setMessages>[0]
1458
- ) => {
1459
- useChatHelpers.setMessages(messages);
1382
+ setMessages: (messagesOrUpdater: Parameters<typeof setMessages>[0]) => {
1383
+ // Resolve functional updaters to get the actual messages array
1384
+ // before syncing to server. Without this, updater functions would
1385
+ // send an empty array and wipe server-side messages.
1386
+ let resolvedMessages: ChatMessage[];
1387
+ if (typeof messagesOrUpdater === "function") {
1388
+ resolvedMessages = messagesOrUpdater(messagesRef.current);
1389
+ } else {
1390
+ resolvedMessages = messagesOrUpdater;
1391
+ }
1392
+
1393
+ setMessages(resolvedMessages);
1460
1394
  agent.send(
1461
1395
  JSON.stringify({
1462
- messages: Array.isArray(messages) ? messages : [],
1396
+ messages: resolvedMessages,
1463
1397
  type: MessageType.CF_AGENT_CHAT_MESSAGES
1464
1398
  })
1465
1399
  );