@cloudflare/ai-chat 0.0.8 → 0.1.1

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 +97 -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 +114 -76
  10. package/dist/index.js +745 -629
  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 +244 -258
  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 +13 -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 +831 -1137
  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 +385 -461
  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 +3 -3
  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 +3 -3
  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 +59 -24
  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,6 +601,19 @@ 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);
667
619
  // Counter to force the tool resolution effect to re-run after completing
@@ -678,12 +630,11 @@ export function useAgentChat<
678
630
  >(new Map());
679
631
 
680
632
  // Ref to access current messages in callbacks without stale closures
681
- const messagesRef = useRef(useChatHelpers.messages);
682
- messagesRef.current = useChatHelpers.messages;
633
+ const messagesRef = useRef(chatMessages);
634
+ messagesRef.current = chatMessages;
683
635
 
684
636
  // Calculate pending confirmations for the latest assistant message
685
- const lastMessage =
686
- useChatHelpers.messages[useChatHelpers.messages.length - 1];
637
+ const lastMessage = chatMessages[chatMessages.length - 1];
687
638
 
688
639
  const pendingConfirmations = (() => {
689
640
  if (!lastMessage || lastMessage.role !== "assistant") {
@@ -706,7 +657,8 @@ export function useAgentChat<
706
657
  const pendingConfirmationsRef = useRef(pendingConfirmations);
707
658
  pendingConfirmationsRef.current = pendingConfirmations;
708
659
 
709
- // Automatic tool resolution effect.
660
+ // ── DEPRECATED: automatic tool resolution effect ────────────────────
661
+ // This entire useEffect is deprecated. Use onToolCall instead.
710
662
  useEffect(() => {
711
663
  if (!experimental_automaticToolResolution) {
712
664
  return;
@@ -717,13 +669,12 @@ export function useAgentChat<
717
669
  return;
718
670
  }
719
671
 
720
- const lastMessage =
721
- useChatHelpers.messages[useChatHelpers.messages.length - 1];
722
- if (!lastMessage || lastMessage.role !== "assistant") {
672
+ const lastMsg = chatMessages[chatMessages.length - 1];
673
+ if (!lastMsg || lastMsg.role !== "assistant") {
723
674
  return;
724
675
  }
725
676
 
726
- const toolCalls = lastMessage.parts.filter(
677
+ const toolCalls = lastMsg.parts.filter(
727
678
  (part) =>
728
679
  isToolUIPart(part) &&
729
680
  part.state === "input-available" &&
@@ -777,6 +728,7 @@ export function useAgentChat<
777
728
 
778
729
  if (toolResults.length > 0) {
779
730
  // Send tool results to server first (server is source of truth)
731
+ const clientToolSchemas = extractClientToolSchemas(currentTools);
780
732
  for (const result of toolResults) {
781
733
  agentRef.current.send(
782
734
  JSON.stringify({
@@ -784,7 +736,8 @@ export function useAgentChat<
784
736
  toolCallId: result.toolCallId,
785
737
  toolName: result.toolName,
786
738
  output: result.output,
787
- autoContinue: autoContinueAfterToolResult
739
+ autoContinue: autoContinueAfterToolResult,
740
+ clientTools: clientToolSchemas
788
741
  })
789
742
  );
790
743
  }
@@ -792,7 +745,7 @@ export function useAgentChat<
792
745
  // Also update local state via AI SDK for immediate UI feedback
793
746
  await Promise.all(
794
747
  toolResults.map((result) =>
795
- useChatHelpers.addToolResult({
748
+ addToolResult({
796
749
  tool: result.toolName,
797
750
  toolCallId: result.toolCallId,
798
751
  output: result.output
@@ -821,9 +774,9 @@ export function useAgentChat<
821
774
  }
822
775
  }
823
776
  }, [
824
- useChatHelpers.messages,
777
+ chatMessages,
825
778
  experimental_automaticToolResolution,
826
- useChatHelpers.addToolResult,
779
+ addToolResult,
827
780
  toolsRequiringConfirmation,
828
781
  autoContinueAfterToolResult,
829
782
  toolResolutionTrigger
@@ -838,7 +791,10 @@ export function useAgentChat<
838
791
  toolCallId,
839
792
  toolName,
840
793
  output,
841
- autoContinue: autoContinueAfterToolResult
794
+ autoContinue: autoContinueAfterToolResult,
795
+ clientTools: toolsRef.current
796
+ ? extractClientToolSchemas(toolsRef.current)
797
+ : undefined
842
798
  })
843
799
  );
844
800
 
@@ -854,11 +810,12 @@ export function useAgentChat<
854
810
  JSON.stringify({
855
811
  type: MessageType.CF_AGENT_TOOL_APPROVAL,
856
812
  toolCallId,
857
- approved
813
+ approved,
814
+ autoContinue: autoContinueAfterToolResult
858
815
  })
859
816
  );
860
817
  },
861
- []
818
+ [autoContinueAfterToolResult]
862
819
  );
863
820
 
864
821
  // Effect for new onToolCall callback pattern (v6 style)
@@ -869,14 +826,13 @@ export function useAgentChat<
869
826
  return;
870
827
  }
871
828
 
872
- const lastMessage =
873
- useChatHelpers.messages[useChatHelpers.messages.length - 1];
874
- if (!lastMessage || lastMessage.role !== "assistant") {
829
+ const lastMsg = chatMessages[chatMessages.length - 1];
830
+ if (!lastMsg || lastMsg.role !== "assistant") {
875
831
  return;
876
832
  }
877
833
 
878
834
  // Find tool calls in input-available state that haven't been processed
879
- const pendingToolCalls = lastMessage.parts.filter(
835
+ const pendingToolCalls = lastMsg.parts.filter(
880
836
  (part) =>
881
837
  isToolUIPart(part) &&
882
838
  part.state === "input-available" &&
@@ -899,7 +855,7 @@ export function useAgentChat<
899
855
  sendToolOutputToServer(opts.toolCallId, toolName, opts.output);
900
856
 
901
857
  // Update local state via AI SDK
902
- useChatHelpers.addToolResult({
858
+ addToolResult({
903
859
  tool: toolName,
904
860
  toolCallId: opts.toolCallId,
905
861
  output: opts.output
@@ -918,27 +874,55 @@ export function useAgentChat<
918
874
  });
919
875
  }
920
876
  }
921
- }, [
922
- useChatHelpers.messages,
923
- sendToolOutputToServer,
924
- useChatHelpers.addToolResult
925
- ]);
877
+ }, [chatMessages, sendToolOutputToServer, addToolResult]);
926
878
 
927
879
  /**
928
- * 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.
929
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.
930
884
  */
931
885
  const activeStreamRef = useRef<{
932
886
  id: string;
933
887
  messageId: string;
934
888
  parts: ChatMessage["parts"];
889
+ metadata?: Record<string, unknown>;
935
890
  } | null>(null);
936
891
 
937
892
  /**
938
- * Tracks request IDs initiated by this tab via aiFetch.
939
- * 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).
940
896
  */
941
- 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
+ );
942
926
 
943
927
  useEffect(() => {
944
928
  /**
@@ -957,17 +941,17 @@ export function useAgentChat<
957
941
 
958
942
  switch (data.type) {
959
943
  case MessageType.CF_AGENT_CHAT_CLEAR:
960
- useChatHelpers.setMessages([]);
944
+ setMessages([]);
961
945
  break;
962
946
 
963
947
  case MessageType.CF_AGENT_CHAT_MESSAGES:
964
- useChatHelpers.setMessages(data.messages);
948
+ setMessages(data.messages);
965
949
  break;
966
950
 
967
951
  case MessageType.CF_AGENT_MESSAGE_UPDATED:
968
952
  // Server updated a message (e.g., applied tool result)
969
953
  // Update the specific message in local state
970
- useChatHelpers.setMessages((prevMessages: ChatMessage[]) => {
954
+ setMessages((prevMessages: ChatMessage[]) => {
971
955
  const updatedMessage = data.message;
972
956
 
973
957
  // First try to find by message ID
@@ -1050,14 +1034,23 @@ export function useAgentChat<
1050
1034
  ) {
1051
1035
  let messageId = nanoid();
1052
1036
  let existingParts: ChatMessage["parts"] = [];
1037
+ let existingMetadata: Record<string, unknown> | undefined;
1053
1038
 
1054
- // For continuations, use the last assistant message's ID and parts
1039
+ // For continuations, use the last assistant message's ID, parts, and metadata
1055
1040
  if (isContinuation) {
1056
1041
  const currentMessages = messagesRef.current;
1057
1042
  for (let i = currentMessages.length - 1; i >= 0; i--) {
1058
1043
  if (currentMessages[i].role === "assistant") {
1059
1044
  messageId = currentMessages[i].id;
1060
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
+ }
1061
1054
  break;
1062
1055
  }
1063
1056
  }
@@ -1066,177 +1059,84 @@ export function useAgentChat<
1066
1059
  activeStreamRef.current = {
1067
1060
  id: data.id,
1068
1061
  messageId,
1069
- parts: existingParts
1062
+ parts: existingParts,
1063
+ metadata: existingMetadata
1070
1064
  };
1071
1065
  }
1072
1066
 
1073
1067
  const activeMsg = activeStreamRef.current;
1068
+ const isReplay = data.replay === true;
1074
1069
 
1075
1070
  if (data.body?.trim()) {
1076
1071
  try {
1077
1072
  const chunkData = JSON.parse(data.body);
1078
1073
 
1079
- // Handle all chunk types for complete message reconstruction
1080
- switch (chunkData.type) {
1081
- case "text-start": {
1082
- activeMsg.parts.push({
1083
- type: "text",
1084
- text: "",
1085
- state: "streaming"
1086
- });
1087
- break;
1088
- }
1089
- case "text-delta": {
1090
- const lastTextPart = [...activeMsg.parts]
1091
- .reverse()
1092
- .find((p) => p.type === "text");
1093
- if (lastTextPart && lastTextPart.type === "text") {
1094
- lastTextPart.text += chunkData.delta;
1095
- } else {
1096
- // Handle plain text responses (no text-start)
1097
- activeMsg.parts.push({
1098
- type: "text",
1099
- text: chunkData.delta
1100
- });
1101
- }
1102
- break;
1103
- }
1104
- case "text-end": {
1105
- const lastTextPart = [...activeMsg.parts]
1106
- .reverse()
1107
- .find((p) => p.type === "text");
1108
- if (lastTextPart && "state" in lastTextPart) {
1109
- lastTextPart.state = "done";
1110
- }
1111
- break;
1112
- }
1113
- case "reasoning-start": {
1114
- activeMsg.parts.push({
1115
- type: "reasoning",
1116
- text: "",
1117
- state: "streaming"
1118
- });
1119
- break;
1120
- }
1121
- case "reasoning-delta": {
1122
- const lastReasoningPart = [...activeMsg.parts]
1123
- .reverse()
1124
- .find((p) => p.type === "reasoning");
1125
- if (
1126
- lastReasoningPart &&
1127
- lastReasoningPart.type === "reasoning"
1128
- ) {
1129
- lastReasoningPart.text += chunkData.delta;
1130
- }
1131
- break;
1132
- }
1133
- case "reasoning-end": {
1134
- const lastReasoningPart = [...activeMsg.parts]
1135
- .reverse()
1136
- .find((p) => p.type === "reasoning");
1137
- if (lastReasoningPart && "state" in lastReasoningPart) {
1138
- lastReasoningPart.state = "done";
1139
- }
1140
- break;
1141
- }
1142
- case "file": {
1143
- activeMsg.parts.push({
1144
- type: "file",
1145
- mediaType: chunkData.mediaType,
1146
- url: chunkData.url
1147
- });
1148
- break;
1149
- }
1150
- case "source-url": {
1151
- activeMsg.parts.push({
1152
- type: "source-url",
1153
- sourceId: chunkData.sourceId,
1154
- url: chunkData.url,
1155
- title: chunkData.title
1156
- });
1157
- break;
1158
- }
1159
- case "source-document": {
1160
- activeMsg.parts.push({
1161
- type: "source-document",
1162
- sourceId: chunkData.sourceId,
1163
- mediaType: chunkData.mediaType,
1164
- title: chunkData.title,
1165
- filename: chunkData.filename
1166
- });
1167
- break;
1168
- }
1169
- case "tool-input-available": {
1170
- // Add tool call part when input is available
1171
- activeMsg.parts.push({
1172
- type: `tool-${chunkData.toolName}`,
1173
- toolCallId: chunkData.toolCallId,
1174
- toolName: chunkData.toolName,
1175
- state: "input-available",
1176
- input: chunkData.input
1177
- } as ChatMessage["parts"][number]);
1178
- break;
1179
- }
1180
- case "tool-output-available": {
1181
- // Update existing tool part with output using immutable pattern
1182
- activeMsg.parts = activeMsg.parts.map((p) => {
1183
- if (
1184
- "toolCallId" in p &&
1185
- p.toolCallId === chunkData.toolCallId &&
1186
- "state" in p
1187
- ) {
1188
- return {
1189
- ...p,
1190
- state: "output-available",
1191
- output: chunkData.output
1192
- } as ChatMessage["parts"][number];
1193
- }
1194
- return p;
1195
- });
1196
- 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;
1197
1107
  }
1198
- case "step-start": {
1199
- activeMsg.parts.push({ type: "step-start" });
1200
- break;
1108
+ if (chunkData.messageMetadata != null) {
1109
+ activeMsg.metadata = activeMsg.metadata
1110
+ ? { ...activeMsg.metadata, ...chunkData.messageMetadata }
1111
+ : { ...chunkData.messageMetadata };
1201
1112
  }
1202
- // Other chunk types (tool-input-start, tool-input-delta, etc.)
1203
- // are intermediate states - the final state will be captured above
1204
1113
  }
1205
1114
 
1206
- // Update messages with the partial response
1207
- useChatHelpers.setMessages((prevMessages: ChatMessage[]) => {
1208
- if (!activeMsg) return prevMessages;
1209
-
1210
- const existingIdx = prevMessages.findIndex(
1211
- (m) => m.id === activeMsg.messageId
1212
- );
1213
-
1214
- const partialMessage = {
1215
- id: activeMsg.messageId,
1216
- role: "assistant" as const,
1217
- parts: [...activeMsg.parts]
1218
- } as unknown as ChatMessage;
1219
-
1220
- if (existingIdx >= 0) {
1221
- const updated = [...prevMessages];
1222
- updated[existingIdx] = partialMessage;
1223
- return updated;
1224
- }
1225
- return [...prevMessages, partialMessage];
1226
- });
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
+ }
1227
1123
  } catch (parseError) {
1228
- // Log corrupted chunk for debugging - could indicate data loss
1229
1124
  console.warn(
1230
1125
  "[useAgentChat] Failed to parse stream chunk:",
1231
1126
  parseError instanceof Error ? parseError.message : parseError,
1232
1127
  "body:",
1233
- data.body?.slice(0, 100) // Truncate for logging
1128
+ data.body?.slice(0, 100)
1234
1129
  );
1235
1130
  }
1236
1131
  }
1237
1132
 
1238
- // Clear on completion or error
1133
+ // On completion or error, flush final state to messages
1239
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
+ }
1240
1140
  activeStreamRef.current = null;
1241
1141
  }
1242
1142
  break;
@@ -1245,71 +1145,87 @@ export function useAgentChat<
1245
1145
  }
1246
1146
 
1247
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
+
1248
1161
  return () => {
1249
1162
  agent.removeEventListener("message", onAgentMessage);
1250
1163
  // Clear active stream state on cleanup to prevent memory leak
1251
1164
  activeStreamRef.current = null;
1252
1165
  };
1253
- }, [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
+ );
1254
1189
 
1255
- // Wrapper that sends tool result to server and optionally continues conversation.
1256
- const addToolResultAndSendMessage: typeof useChatHelpers.addToolResult =
1257
- async (args) => {
1258
- const { toolCallId } = args;
1259
- const toolName = "tool" in args ? args.tool : "";
1260
- const output = "output" in args ? args.output : undefined;
1190
+ setClientToolResults((prev) => new Map(prev).set(toolCallId, output));
1261
1191
 
1262
- // Send tool result to server (server is source of truth)
1263
- // Include flag to tell server whether to auto-continue
1264
- agentRef.current.send(
1265
- JSON.stringify({
1266
- type: MessageType.CF_AGENT_TOOL_RESULT,
1267
- toolCallId,
1268
- toolName,
1269
- output,
1270
- autoContinue: autoContinueAfterToolResult
1271
- })
1272
- );
1273
-
1274
- 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);
1275
1195
 
1276
- // Call AI SDK's addToolResult for local state update (non-blocking)
1277
- // We don't await this since clientToolResults provides immediate UI feedback
1278
- useChatHelpers.addToolResult(args);
1279
-
1280
- // If server auto-continuation is disabled, client needs to trigger continuation
1281
- if (!autoContinueAfterToolResult) {
1282
- // Use legacy behavior: batch confirmations or send immediately
1283
- if (!autoSendAfterAllConfirmationsResolved) {
1284
- // Always send immediately
1285
- useChatHelpers.sendMessage();
1286
- return;
1287
- }
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
+ }
1288
1204
 
1289
- // Wait for all confirmations before sending
1290
- const pending = pendingConfirmationsRef.current?.toolCallIds;
1291
- if (!pending) {
1292
- useChatHelpers.sendMessage();
1293
- return;
1294
- }
1205
+ // Wait for all confirmations before sending
1206
+ const pending = pendingConfirmationsRef.current?.toolCallIds;
1207
+ if (!pending) {
1208
+ sendMessage();
1209
+ return;
1210
+ }
1295
1211
 
1296
- const wasLast = pending.size === 1 && pending.has(toolCallId);
1297
- if (pending.has(toolCallId)) {
1298
- pending.delete(toolCallId);
1299
- }
1212
+ const wasLast = pending.size === 1 && pending.has(toolCallId);
1213
+ if (pending.has(toolCallId)) {
1214
+ pending.delete(toolCallId);
1215
+ }
1300
1216
 
1301
- if (wasLast || pending.size === 0) {
1302
- useChatHelpers.sendMessage();
1303
- }
1217
+ if (wasLast || pending.size === 0) {
1218
+ sendMessage();
1304
1219
  }
1305
- // If autoContinueAfterToolResult is true, server handles continuation
1306
- };
1220
+ }
1221
+ // If autoContinueAfterToolResult is true, server handles continuation
1222
+ };
1307
1223
 
1308
1224
  // Wrapper that sends tool approval to server before updating local state.
1309
1225
  // This prevents duplicate messages by ensuring server updates the message
1310
1226
  // in place with the existing ID, rather than relying on ID resolution
1311
1227
  // when sendMessage() is called later.
1312
- const addToolApprovalResponseAndNotifyServer: typeof useChatHelpers.addToolApprovalResponse =
1228
+ const addToolApprovalResponseAndNotifyServer: typeof addToolApprovalResponse =
1313
1229
  (args) => {
1314
1230
  const { id: approvalId, approved } = args;
1315
1231
 
@@ -1341,16 +1257,16 @@ export function useAgentChat<
1341
1257
  }
1342
1258
 
1343
1259
  // Call AI SDK's addToolApprovalResponse for local state update
1344
- useChatHelpers.addToolApprovalResponse(args);
1260
+ addToolApprovalResponse(args);
1345
1261
  };
1346
1262
 
1347
1263
  // Fix for issue #728: Merge client-side tool results with messages
1348
1264
  // so tool parts show output-available immediately after execution
1349
1265
  const messagesWithToolResults = useMemo(() => {
1350
1266
  if (clientToolResults.size === 0) {
1351
- return useChatHelpers.messages;
1267
+ return chatMessages;
1352
1268
  }
1353
- return useChatHelpers.messages.map((msg) => ({
1269
+ return chatMessages.map((msg) => ({
1354
1270
  ...msg,
1355
1271
  parts: msg.parts.map((p) => {
1356
1272
  if (
@@ -1368,7 +1284,7 @@ export function useAgentChat<
1368
1284
  };
1369
1285
  })
1370
1286
  })) as ChatMessage[];
1371
- }, [useChatHelpers.messages, clientToolResults]);
1287
+ }, [chatMessages, clientToolResults]);
1372
1288
 
1373
1289
  // Cleanup stale entries from clientToolResults when messages change
1374
1290
  // to prevent memory leak in long conversations.
@@ -1377,7 +1293,7 @@ export function useAgentChat<
1377
1293
  useEffect(() => {
1378
1294
  // Collect all current toolCallIds from messages
1379
1295
  const currentToolCallIds = new Set<string>();
1380
- for (const msg of useChatHelpers.messages) {
1296
+ for (const msg of chatMessages) {
1381
1297
  for (const part of msg.parts) {
1382
1298
  if ("toolCallId" in part && part.toolCallId) {
1383
1299
  currentToolCallIds.add(part.toolCallId);
@@ -1417,7 +1333,7 @@ export function useAgentChat<
1417
1333
  }
1418
1334
  }
1419
1335
  // eslint-disable-next-line react-hooks/exhaustive-deps
1420
- }, [useChatHelpers.messages]);
1336
+ }, [chatMessages]);
1421
1337
 
1422
1338
  // Create addToolOutput function for external use
1423
1339
  const addToolOutput = useCallback(
@@ -1426,13 +1342,13 @@ export function useAgentChat<
1426
1342
  sendToolOutputToServer(opts.toolCallId, toolName, opts.output);
1427
1343
 
1428
1344
  // Update local state via AI SDK
1429
- useChatHelpers.addToolResult({
1345
+ addToolResult({
1430
1346
  tool: toolName,
1431
1347
  toolCallId: opts.toolCallId,
1432
1348
  output: opts.output
1433
1349
  });
1434
1350
  },
1435
- [sendToolOutputToServer, useChatHelpers.addToolResult]
1351
+ [sendToolOutputToServer, addToolResult]
1436
1352
  );
1437
1353
 
1438
1354
  return {
@@ -1454,7 +1370,7 @@ export function useAgentChat<
1454
1370
  */
1455
1371
  addToolApprovalResponse: addToolApprovalResponseAndNotifyServer,
1456
1372
  clearHistory: () => {
1457
- useChatHelpers.setMessages([]);
1373
+ setMessages([]);
1458
1374
  setClientToolResults(new Map());
1459
1375
  processedToolCalls.current.clear();
1460
1376
  agent.send(
@@ -1463,13 +1379,21 @@ export function useAgentChat<
1463
1379
  })
1464
1380
  );
1465
1381
  },
1466
- setMessages: (
1467
- messages: Parameters<typeof useChatHelpers.setMessages>[0]
1468
- ) => {
1469
- 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);
1470
1394
  agent.send(
1471
1395
  JSON.stringify({
1472
- messages: Array.isArray(messages) ? messages : [],
1396
+ messages: resolvedMessages,
1473
1397
  type: MessageType.CF_AGENT_CHAT_MESSAGES
1474
1398
  })
1475
1399
  );