@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/dist/react.js CHANGED
@@ -1,11 +1,114 @@
1
1
  import { MessageType } from "./types.js";
2
- import { DefaultChatTransport, getToolName, isToolUIPart } from "ai";
2
+ import { t as applyChunkToParts } from "./message-builder-Bwc_Umye.js";
3
+ import { getToolName, isToolUIPart } from "ai";
3
4
  import { nanoid } from "nanoid";
4
5
  import { useChat } from "@ai-sdk/react";
5
6
  import { use, useCallback, useEffect, useMemo, useRef, useState } from "react";
6
7
 
8
+ //#region src/ws-chat-transport.ts
9
+ /**
10
+ * ChatTransport that sends messages over WebSocket and returns a
11
+ * ReadableStream<UIMessageChunk> that the AI SDK's useChat consumes directly.
12
+ * No fake fetch, no Response reconstruction, no double SSE parsing.
13
+ */
14
+ var WebSocketChatTransport = class {
15
+ constructor(options) {
16
+ this.agent = options.agent;
17
+ this.prepareBody = options.prepareBody;
18
+ this.activeRequestIds = options.activeRequestIds;
19
+ }
20
+ async sendMessages(options) {
21
+ const requestId = nanoid(8);
22
+ const abortController = new AbortController();
23
+ let completed = false;
24
+ let extraBody = {};
25
+ if (this.prepareBody) extraBody = await this.prepareBody({
26
+ messages: options.messages,
27
+ trigger: options.trigger,
28
+ messageId: options.messageId
29
+ });
30
+ if (options.body) extraBody = {
31
+ ...extraBody,
32
+ ...options.body
33
+ };
34
+ const bodyPayload = JSON.stringify({
35
+ messages: options.messages,
36
+ ...extraBody
37
+ });
38
+ this.activeRequestIds?.add(requestId);
39
+ options.abortSignal?.addEventListener("abort", () => {
40
+ if (completed) return;
41
+ this.agent.send(JSON.stringify({
42
+ id: requestId,
43
+ type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL
44
+ }));
45
+ this.activeRequestIds?.delete(requestId);
46
+ abortController.abort();
47
+ });
48
+ const agent = this.agent;
49
+ const activeIds = this.activeRequestIds;
50
+ const stream = new ReadableStream({
51
+ start(controller) {
52
+ const onMessage = (event) => {
53
+ try {
54
+ const data = JSON.parse(event.data);
55
+ if (data.type !== MessageType.CF_AGENT_USE_CHAT_RESPONSE) return;
56
+ if (data.id !== requestId) return;
57
+ if (data.error) {
58
+ completed = true;
59
+ controller.error(new Error(data.body));
60
+ activeIds?.delete(requestId);
61
+ abortController.abort();
62
+ return;
63
+ }
64
+ if (data.body?.trim()) try {
65
+ const chunk = JSON.parse(data.body);
66
+ controller.enqueue(chunk);
67
+ } catch {}
68
+ if (data.done) {
69
+ completed = true;
70
+ try {
71
+ controller.close();
72
+ } catch {}
73
+ activeIds?.delete(requestId);
74
+ abortController.abort();
75
+ }
76
+ } catch {}
77
+ };
78
+ agent.addEventListener("message", onMessage, { signal: abortController.signal });
79
+ },
80
+ cancel() {
81
+ abortController.abort();
82
+ }
83
+ });
84
+ agent.send(JSON.stringify({
85
+ id: requestId,
86
+ init: {
87
+ method: "POST",
88
+ body: bodyPayload
89
+ },
90
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST
91
+ }));
92
+ return stream;
93
+ }
94
+ async reconnectToStream(_options) {
95
+ return null;
96
+ }
97
+ };
98
+
99
+ //#endregion
7
100
  //#region src/react.tsx
8
101
  /**
102
+ * One-shot deprecation warnings (warns once per key per session).
103
+ */
104
+ const _deprecationWarnings = /* @__PURE__ */ new Set();
105
+ function warnDeprecated(id, message) {
106
+ if (!_deprecationWarnings.has(id)) {
107
+ _deprecationWarnings.add(id);
108
+ console.warn(`[@cloudflare/ai-chat] Deprecated: ${message}`);
109
+ }
110
+ }
111
+ /**
9
112
  * Extracts tool schemas from tools that have client-side execute functions.
10
113
  * These schemas are automatically sent to the server with each request.
11
114
  * @param tools - Record of tool name to tool definition
@@ -15,6 +118,7 @@ import { use, useCallback, useEffect, useMemo, useRef, useState } from "react";
15
118
  * and use `onToolCall` callback for client-side execution.
16
119
  */
17
120
  function extractClientToolSchemas(tools) {
121
+ warnDeprecated("extractClientToolSchemas", "extractClientToolSchemas() is deprecated. Define tools on the server and use onToolCall for client execution. Will be removed in the next major version.");
18
122
  if (!tools) return void 0;
19
123
  const schemas = Object.entries(tools).filter(([_, tool]) => tool.execute).map(([name, tool]) => {
20
124
  if (tool.inputSchema && !tool.parameters) console.warn(`[useAgentChat] Tool "${name}" uses deprecated 'inputSchema'. Please migrate to 'parameters'.`);
@@ -26,6 +130,12 @@ function extractClientToolSchemas(tools) {
26
130
  });
27
131
  return schemas.length > 0 ? schemas : void 0;
28
132
  }
133
+ /**
134
+ * Module-level cache for initial message fetches. Intentionally shared across
135
+ * all useAgentChat instances to deduplicate requests during React Strict Mode
136
+ * double-renders and re-renders. Cache keys include the agent URL, agent type,
137
+ * and thread name to prevent cross-agent collisions.
138
+ */
29
139
  const requestCache = /* @__PURE__ */ new Map();
30
140
  /**
31
141
  * React hook for building AI chat interfaces using an Agent
@@ -41,14 +151,21 @@ const requestCache = /* @__PURE__ */ new Map();
41
151
  * @deprecated Use `needsApproval` on server-side tools instead.
42
152
  */
43
153
  function detectToolsRequiringConfirmation(tools) {
154
+ warnDeprecated("detectToolsRequiringConfirmation", "detectToolsRequiringConfirmation() is deprecated. Use needsApproval on server-side tools instead. Will be removed in the next major version.");
44
155
  if (!tools) return [];
45
156
  return Object.entries(tools).filter(([_name, tool]) => !tool.execute).map(([name]) => name);
46
157
  }
47
158
  function useAgentChat(options) {
48
- const { agent, getInitialMessages, messages: optionsInitialMessages, onToolCall, experimental_automaticToolResolution, tools, toolsRequiringConfirmation: manualToolsRequiringConfirmation, autoContinueAfterToolResult = false, autoSendAfterAllConfirmationsResolved = true, resume = true, prepareSendMessagesRequest, ...rest } = options;
49
- const toolsRequiringConfirmation = manualToolsRequiringConfirmation ?? detectToolsRequiringConfirmation(tools);
159
+ const { agent, getInitialMessages, messages: optionsInitialMessages, onToolCall, onData, experimental_automaticToolResolution, tools, toolsRequiringConfirmation: manualToolsRequiringConfirmation, autoContinueAfterToolResult = true, autoSendAfterAllConfirmationsResolved = true, resume = true, body: bodyOption, prepareSendMessagesRequest, ...rest } = options;
160
+ if (tools) warnDeprecated("useAgentChat.tools", "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.");
161
+ if (manualToolsRequiringConfirmation) warnDeprecated("useAgentChat.toolsRequiringConfirmation", "The 'toolsRequiringConfirmation' option is deprecated. Use needsApproval on server-side tools instead. Will be removed in the next major version.");
162
+ if (experimental_automaticToolResolution) warnDeprecated("useAgentChat.experimental_automaticToolResolution", "The 'experimental_automaticToolResolution' option is deprecated. Use the onToolCall callback instead. Will be removed in the next major version.");
163
+ if (options.autoSendAfterAllConfirmationsResolved !== void 0) warnDeprecated("useAgentChat.autoSendAfterAllConfirmationsResolved", "The 'autoSendAfterAllConfirmationsResolved' option is deprecated. Use sendAutomaticallyWhen from AI SDK instead. Will be removed in the next major version.");
164
+ const toolsRequiringConfirmation = useMemo(() => manualToolsRequiringConfirmation ?? (tools ? detectToolsRequiringConfirmation(tools) : []), [manualToolsRequiringConfirmation, tools]);
50
165
  const onToolCallRef = useRef(onToolCall);
51
166
  onToolCallRef.current = onToolCall;
167
+ const onDataRef = useRef(onData);
168
+ onDataRef.current = onData;
52
169
  const agentUrl = new URL(`${(agent._url || agent._pkurl)?.replace("ws://", "http://").replace("wss://", "https://")}`);
53
170
  agentUrl.searchParams.delete("_pk");
54
171
  const agentUrlString = agentUrl.toString();
@@ -97,131 +214,55 @@ function useAgentChat(options) {
97
214
  if (requestCache.get(initialMessagesCacheKey) === initialMessagesPromise) requestCache.delete(initialMessagesCacheKey);
98
215
  };
99
216
  }, [initialMessagesCacheKey, initialMessagesPromise]);
100
- const aiFetch = useCallback(async (request, options = {}) => {
101
- const { method, keepalive, headers, body, redirect, integrity, signal, credentials, mode, referrer, referrerPolicy, window } = options;
102
- const id = nanoid(8);
103
- const abortController = new AbortController();
104
- let controller;
105
- const currentAgent = agentRef.current;
106
- localRequestIdsRef.current.add(id);
107
- signal?.addEventListener("abort", () => {
108
- currentAgent.send(JSON.stringify({
109
- id,
110
- type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL
111
- }));
112
- abortController.abort();
113
- try {
114
- controller.close();
115
- } catch {}
116
- localRequestIdsRef.current.delete(id);
117
- });
118
- currentAgent.addEventListener("message", (event) => {
119
- let data;
120
- try {
121
- data = JSON.parse(event.data);
122
- } catch (_error) {
123
- return;
124
- }
125
- if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE) {
126
- if (data.id === id) if (data.error) {
127
- controller.error(new Error(data.body));
128
- abortController.abort();
129
- localRequestIdsRef.current.delete(id);
130
- } else {
131
- if (data.body?.trim()) controller.enqueue(new TextEncoder().encode(`data: ${data.body}\n\n`));
132
- if (data.done) {
133
- try {
134
- controller.close();
135
- } catch {}
136
- abortController.abort();
137
- localRequestIdsRef.current.delete(id);
138
- }
139
- }
140
- }
141
- }, { signal: abortController.signal });
142
- const stream = new ReadableStream({
143
- start(c) {
144
- controller = c;
145
- },
146
- cancel(reason) {
147
- console.warn("[@cloudflare/ai-chat/react] cancelling stream", id, reason || "no reason");
148
- }
149
- });
150
- currentAgent.send(JSON.stringify({
151
- id,
152
- init: {
153
- body,
154
- credentials,
155
- headers,
156
- integrity,
157
- keepalive,
158
- method,
159
- mode,
160
- redirect,
161
- referrer,
162
- referrerPolicy,
163
- window
164
- },
165
- type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
166
- url: request.toString()
167
- }));
168
- return new Response(stream);
169
- }, []);
170
217
  const toolsRef = useRef(tools);
171
218
  toolsRef.current = tools;
172
219
  const prepareSendMessagesRequestRef = useRef(prepareSendMessagesRequest);
173
220
  prepareSendMessagesRequestRef.current = prepareSendMessagesRequest;
174
- const customTransport = useMemo(() => ({
175
- sendMessages: async (sendMessageOptions) => {
176
- const clientToolSchemas = extractClientToolSchemas(toolsRef.current);
177
- return new DefaultChatTransport({
178
- api: agentUrlString,
179
- fetch: aiFetch,
180
- prepareSendMessagesRequest: clientToolSchemas || prepareSendMessagesRequestRef.current ? async (prepareOptions) => {
181
- let body = {};
182
- let headers;
183
- let credentials;
184
- let api;
185
- if (clientToolSchemas) body = {
186
- id: prepareOptions.id,
187
- messages: prepareOptions.messages,
188
- trigger: prepareOptions.trigger,
189
- clientTools: clientToolSchemas
190
- };
191
- if (prepareSendMessagesRequestRef.current) {
192
- const userResult = await prepareSendMessagesRequestRef.current(prepareOptions);
193
- headers = userResult.headers;
194
- credentials = userResult.credentials;
195
- api = userResult.api;
196
- body = {
197
- ...body,
198
- ...userResult.body ?? {}
199
- };
200
- }
201
- return {
202
- body,
203
- headers,
204
- credentials,
205
- api
206
- };
207
- } : void 0
208
- }).sendMessages(sendMessageOptions);
209
- },
210
- reconnectToStream: async () => null
211
- }), [agentUrlString, aiFetch]);
221
+ const bodyOptionRef = useRef(bodyOption);
222
+ bodyOptionRef.current = bodyOption;
223
+ /**
224
+ * Tracks request IDs initiated by this tab via the transport.
225
+ * Used by onAgentMessage to skip messages already handled by the transport.
226
+ */
227
+ const localRequestIdsRef = useRef(/* @__PURE__ */ new Set());
228
+ const customTransport = useMemo(() => new WebSocketChatTransport({
229
+ agent: agentRef.current,
230
+ activeRequestIds: localRequestIdsRef.current,
231
+ prepareBody: async ({ messages: msgs, trigger, messageId }) => {
232
+ let extraBody = {};
233
+ const currentBody = bodyOptionRef.current;
234
+ if (currentBody) extraBody = { ...typeof currentBody === "function" ? await currentBody() : currentBody };
235
+ if (toolsRef.current) {
236
+ const clientToolSchemas = extractClientToolSchemas(toolsRef.current);
237
+ if (clientToolSchemas) extraBody.clientTools = clientToolSchemas;
238
+ }
239
+ if (prepareSendMessagesRequestRef.current) {
240
+ const userResult = await prepareSendMessagesRequestRef.current({
241
+ id: agent._pk,
242
+ messages: msgs,
243
+ trigger,
244
+ messageId
245
+ });
246
+ if (userResult.body) Object.assign(extraBody, userResult.body);
247
+ }
248
+ return extraBody;
249
+ }
250
+ }), [agent._pk]);
212
251
  const useChatHelpers = useChat({
213
252
  ...rest,
253
+ onData,
214
254
  messages: initialMessages,
215
255
  transport: customTransport,
216
256
  id: agent._pk
217
257
  });
258
+ const { messages: chatMessages, setMessages, addToolResult, addToolApprovalResponse, sendMessage } = useChatHelpers;
218
259
  const processedToolCalls = useRef(/* @__PURE__ */ new Set());
219
260
  const isResolvingToolsRef = useRef(false);
220
261
  const [toolResolutionTrigger, setToolResolutionTrigger] = useState(0);
221
262
  const [clientToolResults, setClientToolResults] = useState(/* @__PURE__ */ new Map());
222
- const messagesRef = useRef(useChatHelpers.messages);
223
- messagesRef.current = useChatHelpers.messages;
224
- const lastMessage = useChatHelpers.messages[useChatHelpers.messages.length - 1];
263
+ const messagesRef = useRef(chatMessages);
264
+ messagesRef.current = chatMessages;
265
+ const lastMessage = chatMessages[chatMessages.length - 1];
225
266
  const pendingConfirmations = (() => {
226
267
  if (!lastMessage || lastMessage.role !== "assistant") return {
227
268
  messageId: void 0,
@@ -239,9 +280,9 @@ function useAgentChat(options) {
239
280
  useEffect(() => {
240
281
  if (!experimental_automaticToolResolution) return;
241
282
  if (isResolvingToolsRef.current) return;
242
- const lastMessage = useChatHelpers.messages[useChatHelpers.messages.length - 1];
243
- if (!lastMessage || lastMessage.role !== "assistant") return;
244
- const toolCalls = lastMessage.parts.filter((part) => isToolUIPart(part) && part.state === "input-available" && !processedToolCalls.current.has(part.toolCallId));
283
+ const lastMsg = chatMessages[chatMessages.length - 1];
284
+ if (!lastMsg || lastMsg.role !== "assistant") return;
285
+ const toolCalls = lastMsg.parts.filter((part) => isToolUIPart(part) && part.state === "input-available" && !processedToolCalls.current.has(part.toolCallId));
245
286
  if (toolCalls.length > 0) {
246
287
  const currentTools = toolsRef.current;
247
288
  const toolCallsToResolve = toolCalls.filter((part) => isToolUIPart(part) && !toolsRequiringConfirmation.includes(getToolName(part)) && currentTools?.[getToolName(part)]?.execute);
@@ -267,14 +308,16 @@ function useAgentChat(options) {
267
308
  });
268
309
  }
269
310
  if (toolResults.length > 0) {
311
+ const clientToolSchemas = extractClientToolSchemas(currentTools);
270
312
  for (const result of toolResults) agentRef.current.send(JSON.stringify({
271
313
  type: MessageType.CF_AGENT_TOOL_RESULT,
272
314
  toolCallId: result.toolCallId,
273
315
  toolName: result.toolName,
274
316
  output: result.output,
275
- autoContinue: autoContinueAfterToolResult
317
+ autoContinue: autoContinueAfterToolResult,
318
+ clientTools: clientToolSchemas
276
319
  }));
277
- await Promise.all(toolResults.map((result) => useChatHelpers.addToolResult({
320
+ await Promise.all(toolResults.map((result) => addToolResult({
278
321
  tool: result.toolName,
279
322
  toolCallId: result.toolCallId,
280
323
  output: result.output
@@ -293,9 +336,9 @@ function useAgentChat(options) {
293
336
  }
294
337
  }
295
338
  }, [
296
- useChatHelpers.messages,
339
+ chatMessages,
297
340
  experimental_automaticToolResolution,
298
- useChatHelpers.addToolResult,
341
+ addToolResult,
299
342
  toolsRequiringConfirmation,
300
343
  autoContinueAfterToolResult,
301
344
  toolResolutionTrigger
@@ -306,7 +349,8 @@ function useAgentChat(options) {
306
349
  toolCallId,
307
350
  toolName,
308
351
  output,
309
- autoContinue: autoContinueAfterToolResult
352
+ autoContinue: autoContinueAfterToolResult,
353
+ clientTools: toolsRef.current ? extractClientToolSchemas(toolsRef.current) : void 0
310
354
  }));
311
355
  setClientToolResults((prev) => new Map(prev).set(toolCallId, output));
312
356
  }, [autoContinueAfterToolResult]);
@@ -314,22 +358,23 @@ function useAgentChat(options) {
314
358
  agentRef.current.send(JSON.stringify({
315
359
  type: MessageType.CF_AGENT_TOOL_APPROVAL,
316
360
  toolCallId,
317
- approved
361
+ approved,
362
+ autoContinue: autoContinueAfterToolResult
318
363
  }));
319
- }, []);
364
+ }, [autoContinueAfterToolResult]);
320
365
  useEffect(() => {
321
366
  const currentOnToolCall = onToolCallRef.current;
322
367
  if (!currentOnToolCall) return;
323
- const lastMessage = useChatHelpers.messages[useChatHelpers.messages.length - 1];
324
- if (!lastMessage || lastMessage.role !== "assistant") return;
325
- const pendingToolCalls = lastMessage.parts.filter((part) => isToolUIPart(part) && part.state === "input-available" && !processedToolCalls.current.has(part.toolCallId));
368
+ const lastMsg = chatMessages[chatMessages.length - 1];
369
+ if (!lastMsg || lastMsg.role !== "assistant") return;
370
+ const pendingToolCalls = lastMsg.parts.filter((part) => isToolUIPart(part) && part.state === "input-available" && !processedToolCalls.current.has(part.toolCallId));
326
371
  for (const part of pendingToolCalls) if (isToolUIPart(part)) {
327
372
  const toolCallId = part.toolCallId;
328
373
  const toolName = getToolName(part);
329
374
  processedToolCalls.current.add(toolCallId);
330
375
  const addToolOutput = (opts) => {
331
376
  sendToolOutputToServer(opts.toolCallId, toolName, opts.output);
332
- useChatHelpers.addToolResult({
377
+ addToolResult({
333
378
  tool: toolName,
334
379
  toolCallId: opts.toolCallId,
335
380
  output: opts.output
@@ -345,20 +390,39 @@ function useAgentChat(options) {
345
390
  });
346
391
  }
347
392
  }, [
348
- useChatHelpers.messages,
393
+ chatMessages,
349
394
  sendToolOutputToServer,
350
- useChatHelpers.addToolResult
395
+ addToolResult
351
396
  ]);
352
397
  /**
353
- * Contains the request ID, accumulated message parts, and a unique message ID.
398
+ * Contains the request ID, accumulated message parts, metadata, and a unique message ID.
354
399
  * Used for both resumed streams and real-time broadcasts from other tabs.
400
+ * Metadata is captured from start/finish/message-metadata stream chunks
401
+ * so that it's included when the partial message is flushed to React state.
355
402
  */
356
403
  const activeStreamRef = useRef(null);
357
404
  /**
358
- * Tracks request IDs initiated by this tab via aiFetch.
359
- * Used to distinguish local requests from broadcasts.
405
+ * Flush the active stream's accumulated parts into React state.
406
+ * Extracted as a helper so it can be called both during live streaming
407
+ * (per-chunk) and after replay completes (once, at done).
360
408
  */
361
- const localRequestIdsRef = useRef(/* @__PURE__ */ new Set());
409
+ const flushActiveStreamToMessages = useCallback((activeMsg) => {
410
+ setMessages((prevMessages) => {
411
+ const existingIdx = prevMessages.findIndex((m) => m.id === activeMsg.messageId);
412
+ const partialMessage = {
413
+ id: activeMsg.messageId,
414
+ role: "assistant",
415
+ parts: [...activeMsg.parts],
416
+ ...activeMsg.metadata != null && { metadata: activeMsg.metadata }
417
+ };
418
+ if (existingIdx >= 0) {
419
+ const updated = [...prevMessages];
420
+ updated[existingIdx] = partialMessage;
421
+ return updated;
422
+ }
423
+ return [...prevMessages, partialMessage];
424
+ });
425
+ }, [setMessages]);
362
426
  useEffect(() => {
363
427
  /**
364
428
  * Unified message handler that parses JSON once and dispatches based on type.
@@ -374,13 +438,13 @@ function useAgentChat(options) {
374
438
  }
375
439
  switch (data.type) {
376
440
  case MessageType.CF_AGENT_CHAT_CLEAR:
377
- useChatHelpers.setMessages([]);
441
+ setMessages([]);
378
442
  break;
379
443
  case MessageType.CF_AGENT_CHAT_MESSAGES:
380
- useChatHelpers.setMessages(data.messages);
444
+ setMessages(data.messages);
381
445
  break;
382
446
  case MessageType.CF_AGENT_MESSAGE_UPDATED:
383
- useChatHelpers.setMessages((prevMessages) => {
447
+ setMessages((prevMessages) => {
384
448
  const updatedMessage = data.message;
385
449
  let idx = prevMessages.findIndex((m) => m.id === updatedMessage.id);
386
450
  if (idx < 0) {
@@ -417,141 +481,59 @@ function useAgentChat(options) {
417
481
  if (!activeStreamRef.current || activeStreamRef.current.id !== data.id) {
418
482
  let messageId = nanoid();
419
483
  let existingParts = [];
484
+ let existingMetadata;
420
485
  if (isContinuation) {
421
486
  const currentMessages = messagesRef.current;
422
487
  for (let i = currentMessages.length - 1; i >= 0; i--) if (currentMessages[i].role === "assistant") {
423
488
  messageId = currentMessages[i].id;
424
489
  existingParts = [...currentMessages[i].parts];
490
+ if (currentMessages[i].metadata != null) existingMetadata = { ...currentMessages[i].metadata };
425
491
  break;
426
492
  }
427
493
  }
428
494
  activeStreamRef.current = {
429
495
  id: data.id,
430
496
  messageId,
431
- parts: existingParts
497
+ parts: existingParts,
498
+ metadata: existingMetadata
432
499
  };
433
500
  }
434
501
  const activeMsg = activeStreamRef.current;
502
+ const isReplay = data.replay === true;
435
503
  if (data.body?.trim()) try {
436
504
  const chunkData = JSON.parse(data.body);
437
- switch (chunkData.type) {
438
- case "text-start":
439
- activeMsg.parts.push({
440
- type: "text",
441
- text: "",
442
- state: "streaming"
443
- });
444
- break;
445
- case "text-delta": {
446
- const lastTextPart = [...activeMsg.parts].reverse().find((p) => p.type === "text");
447
- if (lastTextPart && lastTextPart.type === "text") lastTextPart.text += chunkData.delta;
448
- else activeMsg.parts.push({
449
- type: "text",
450
- text: chunkData.delta
451
- });
452
- break;
453
- }
454
- case "text-end": {
455
- const lastTextPart = [...activeMsg.parts].reverse().find((p) => p.type === "text");
456
- if (lastTextPart && "state" in lastTextPart) lastTextPart.state = "done";
457
- break;
458
- }
459
- case "reasoning-start":
460
- activeMsg.parts.push({
461
- type: "reasoning",
462
- text: "",
463
- state: "streaming"
464
- });
465
- break;
466
- case "reasoning-delta": {
467
- const lastReasoningPart = [...activeMsg.parts].reverse().find((p) => p.type === "reasoning");
468
- if (lastReasoningPart && lastReasoningPart.type === "reasoning") lastReasoningPart.text += chunkData.delta;
469
- break;
470
- }
471
- case "reasoning-end": {
472
- const lastReasoningPart = [...activeMsg.parts].reverse().find((p) => p.type === "reasoning");
473
- if (lastReasoningPart && "state" in lastReasoningPart) lastReasoningPart.state = "done";
474
- break;
475
- }
476
- case "file":
477
- activeMsg.parts.push({
478
- type: "file",
479
- mediaType: chunkData.mediaType,
480
- url: chunkData.url
481
- });
482
- break;
483
- case "source-url":
484
- activeMsg.parts.push({
485
- type: "source-url",
486
- sourceId: chunkData.sourceId,
487
- url: chunkData.url,
488
- title: chunkData.title
489
- });
490
- break;
491
- case "source-document":
492
- activeMsg.parts.push({
493
- type: "source-document",
494
- sourceId: chunkData.sourceId,
495
- mediaType: chunkData.mediaType,
496
- title: chunkData.title,
497
- filename: chunkData.filename
498
- });
499
- break;
500
- case "tool-input-available":
501
- activeMsg.parts.push({
502
- type: `tool-${chunkData.toolName}`,
503
- toolCallId: chunkData.toolCallId,
504
- toolName: chunkData.toolName,
505
- state: "input-available",
506
- input: chunkData.input
507
- });
508
- break;
509
- case "tool-output-available":
510
- activeMsg.parts = activeMsg.parts.map((p) => {
511
- if ("toolCallId" in p && p.toolCallId === chunkData.toolCallId && "state" in p) return {
512
- ...p,
513
- state: "output-available",
514
- output: chunkData.output
515
- };
516
- return p;
517
- });
518
- break;
519
- case "step-start":
520
- activeMsg.parts.push({ type: "step-start" });
521
- break;
505
+ const handled = applyChunkToParts(activeMsg.parts, chunkData);
506
+ if (typeof chunkData.type === "string" && chunkData.type.startsWith("data-") && onDataRef.current) onDataRef.current(chunkData);
507
+ if (!handled && (chunkData.type === "start" || chunkData.type === "finish" || chunkData.type === "message-metadata")) {
508
+ if (chunkData.messageId != null && chunkData.type === "start") activeMsg.messageId = chunkData.messageId;
509
+ if (chunkData.messageMetadata != null) activeMsg.metadata = activeMsg.metadata ? {
510
+ ...activeMsg.metadata,
511
+ ...chunkData.messageMetadata
512
+ } : { ...chunkData.messageMetadata };
522
513
  }
523
- useChatHelpers.setMessages((prevMessages) => {
524
- if (!activeMsg) return prevMessages;
525
- const existingIdx = prevMessages.findIndex((m) => m.id === activeMsg.messageId);
526
- const partialMessage = {
527
- id: activeMsg.messageId,
528
- role: "assistant",
529
- parts: [...activeMsg.parts]
530
- };
531
- if (existingIdx >= 0) {
532
- const updated = [...prevMessages];
533
- updated[existingIdx] = partialMessage;
534
- return updated;
535
- }
536
- return [...prevMessages, partialMessage];
537
- });
514
+ if (!isReplay) flushActiveStreamToMessages(activeMsg);
538
515
  } catch (parseError) {
539
516
  console.warn("[useAgentChat] Failed to parse stream chunk:", parseError instanceof Error ? parseError.message : parseError, "body:", data.body?.slice(0, 100));
540
517
  }
541
- if (data.done || data.error) activeStreamRef.current = null;
518
+ if (data.done || data.error) {
519
+ if (isReplay && activeMsg) flushActiveStreamToMessages(activeMsg);
520
+ activeStreamRef.current = null;
521
+ }
542
522
  break;
543
523
  }
544
524
  }
545
525
  }
546
526
  agent.addEventListener("message", onAgentMessage);
527
+ if (resume) agent.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST }));
547
528
  return () => {
548
529
  agent.removeEventListener("message", onAgentMessage);
549
530
  activeStreamRef.current = null;
550
531
  };
551
532
  }, [
552
533
  agent,
553
- useChatHelpers.setMessages,
554
- resume
534
+ setMessages,
535
+ resume,
536
+ flushActiveStreamToMessages
555
537
  ]);
556
538
  const addToolResultAndSendMessage = async (args) => {
557
539
  const { toolCallId } = args;
@@ -562,23 +544,24 @@ function useAgentChat(options) {
562
544
  toolCallId,
563
545
  toolName,
564
546
  output,
565
- autoContinue: autoContinueAfterToolResult
547
+ autoContinue: autoContinueAfterToolResult,
548
+ clientTools: toolsRef.current ? extractClientToolSchemas(toolsRef.current) : void 0
566
549
  }));
567
550
  setClientToolResults((prev) => new Map(prev).set(toolCallId, output));
568
- useChatHelpers.addToolResult(args);
551
+ addToolResult(args);
569
552
  if (!autoContinueAfterToolResult) {
570
553
  if (!autoSendAfterAllConfirmationsResolved) {
571
- useChatHelpers.sendMessage();
554
+ sendMessage();
572
555
  return;
573
556
  }
574
557
  const pending = pendingConfirmationsRef.current?.toolCallIds;
575
558
  if (!pending) {
576
- useChatHelpers.sendMessage();
559
+ sendMessage();
577
560
  return;
578
561
  }
579
562
  const wasLast = pending.size === 1 && pending.has(toolCallId);
580
563
  if (pending.has(toolCallId)) pending.delete(toolCallId);
581
- if (wasLast || pending.size === 0) useChatHelpers.sendMessage();
564
+ if (wasLast || pending.size === 0) sendMessage();
582
565
  }
583
566
  };
584
567
  const addToolApprovalResponseAndNotifyServer = (args) => {
@@ -593,11 +576,11 @@ function useAgentChat(options) {
593
576
  }
594
577
  if (toolCallId) sendToolApprovalToServer(toolCallId, approved);
595
578
  else console.warn(`[useAgentChat] addToolApprovalResponse: Could not find toolCallId for approval ID "${approvalId}". Server will not be notified, which may cause duplicate messages.`);
596
- useChatHelpers.addToolApprovalResponse(args);
579
+ addToolApprovalResponse(args);
597
580
  };
598
581
  const messagesWithToolResults = useMemo(() => {
599
- if (clientToolResults.size === 0) return useChatHelpers.messages;
600
- return useChatHelpers.messages.map((msg) => ({
582
+ if (clientToolResults.size === 0) return chatMessages;
583
+ return chatMessages.map((msg) => ({
601
584
  ...msg,
602
585
  parts: msg.parts.map((p) => {
603
586
  if (!("toolCallId" in p) || !("state" in p) || p.state !== "input-available" || !clientToolResults.has(p.toolCallId)) return p;
@@ -608,10 +591,10 @@ function useAgentChat(options) {
608
591
  };
609
592
  })
610
593
  }));
611
- }, [useChatHelpers.messages, clientToolResults]);
594
+ }, [chatMessages, clientToolResults]);
612
595
  useEffect(() => {
613
596
  const currentToolCallIds = /* @__PURE__ */ new Set();
614
- for (const msg of useChatHelpers.messages) for (const part of msg.parts) if ("toolCallId" in part && part.toolCallId) currentToolCallIds.add(part.toolCallId);
597
+ for (const msg of chatMessages) for (const part of msg.parts) if ("toolCallId" in part && part.toolCallId) currentToolCallIds.add(part.toolCallId);
615
598
  setClientToolResults((prev) => {
616
599
  if (prev.size === 0) return prev;
617
600
  let hasStaleEntries = false;
@@ -625,16 +608,16 @@ function useAgentChat(options) {
625
608
  return newMap;
626
609
  });
627
610
  for (const toolCallId of processedToolCalls.current) if (!currentToolCallIds.has(toolCallId)) processedToolCalls.current.delete(toolCallId);
628
- }, [useChatHelpers.messages]);
611
+ }, [chatMessages]);
629
612
  const addToolOutput = useCallback((opts) => {
630
613
  const toolName = opts.toolName ?? "";
631
614
  sendToolOutputToServer(opts.toolCallId, toolName, opts.output);
632
- useChatHelpers.addToolResult({
615
+ addToolResult({
633
616
  tool: toolName,
634
617
  toolCallId: opts.toolCallId,
635
618
  output: opts.output
636
619
  });
637
- }, [sendToolOutputToServer, useChatHelpers.addToolResult]);
620
+ }, [sendToolOutputToServer, addToolResult]);
638
621
  return {
639
622
  ...useChatHelpers,
640
623
  messages: messagesWithToolResults,
@@ -642,15 +625,18 @@ function useAgentChat(options) {
642
625
  addToolResult: addToolResultAndSendMessage,
643
626
  addToolApprovalResponse: addToolApprovalResponseAndNotifyServer,
644
627
  clearHistory: () => {
645
- useChatHelpers.setMessages([]);
628
+ setMessages([]);
646
629
  setClientToolResults(/* @__PURE__ */ new Map());
647
630
  processedToolCalls.current.clear();
648
631
  agent.send(JSON.stringify({ type: MessageType.CF_AGENT_CHAT_CLEAR }));
649
632
  },
650
- setMessages: (messages) => {
651
- useChatHelpers.setMessages(messages);
633
+ setMessages: (messagesOrUpdater) => {
634
+ let resolvedMessages;
635
+ if (typeof messagesOrUpdater === "function") resolvedMessages = messagesOrUpdater(messagesRef.current);
636
+ else resolvedMessages = messagesOrUpdater;
637
+ setMessages(resolvedMessages);
652
638
  agent.send(JSON.stringify({
653
- messages: Array.isArray(messages) ? messages : [],
639
+ messages: resolvedMessages,
654
640
  type: MessageType.CF_AGENT_CHAT_MESSAGES
655
641
  }));
656
642
  }