@cloudflare/ai-chat 0.6.2 → 0.7.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.
package/dist/react.d.ts CHANGED
@@ -316,6 +316,15 @@ type UseAgentChatOptions<
316
316
  * @default true
317
317
  */
318
318
  resume?: boolean;
319
+ /**
320
+ * Whether generic client-side stream abort/cleanup should cancel the server
321
+ * turn. By default, client cleanup is local-only so the server turn can
322
+ * continue and be resumed on reconnect. Explicit stop() always cancels the
323
+ * server turn.
324
+ *
325
+ * @default false
326
+ */
327
+ cancelOnClientAbort?: boolean;
319
328
  /**
320
329
  * Custom data to include in every chat request body.
321
330
  * Accepts a static object or a function that returns one (for dynamic values).
package/dist/react.js CHANGED
@@ -16,9 +16,50 @@ var WebSocketChatTransport = class {
16
16
  this._resumeNoneResolver = null;
17
17
  this._expectToolContinuation = false;
18
18
  this._abortToolContinuation = null;
19
+ this._activeServerTurnId = null;
20
+ this._cancelAttachedStream = null;
19
21
  this.agent = options.agent;
20
22
  this.prepareBody = options.prepareBody;
21
23
  this.activeRequestIds = options.activeRequestIds;
24
+ this.cancelOnClientAbort = options.cancelOnClientAbort ?? false;
25
+ }
26
+ setCancelOnClientAbort(cancelOnClientAbort) {
27
+ this.cancelOnClientAbort = cancelOnClientAbort;
28
+ }
29
+ /**
30
+ * Explicitly cancel the active server turn, if any.
31
+ * This is separate from generic client-side abort/cancel lifecycle so
32
+ * clients can detach locally without stopping server work.
33
+ */
34
+ cancelActiveServerTurn() {
35
+ const requestId = this._activeServerTurnId;
36
+ let cancelledRequest = false;
37
+ if (requestId) {
38
+ this.sendCancelFrame(requestId);
39
+ this._cancelAttachedStream?.();
40
+ this.clearActiveServerTurn(requestId);
41
+ cancelledRequest = true;
42
+ }
43
+ const cancelledToolContinuation = this.abortActiveToolContinuation();
44
+ return cancelledRequest || cancelledToolContinuation;
45
+ }
46
+ sendCancelFrame(requestId) {
47
+ try {
48
+ this.agent.send(JSON.stringify({
49
+ id: requestId,
50
+ type: "cf_agent_chat_request_cancel"
51
+ }));
52
+ } catch {}
53
+ }
54
+ setActiveServerTurn(requestId, cancelAttachedStream) {
55
+ this._activeServerTurnId = requestId;
56
+ this._cancelAttachedStream = cancelAttachedStream;
57
+ }
58
+ clearActiveServerTurn(requestId) {
59
+ if (this._activeServerTurnId === requestId) {
60
+ this._activeServerTurnId = null;
61
+ this._cancelAttachedStream = null;
62
+ }
22
63
  }
23
64
  /**
24
65
  * Mark that the next reconnectToStream() call should attach to a
@@ -61,10 +102,26 @@ var WebSocketChatTransport = class {
61
102
  this._resumeNoneResolver();
62
103
  return true;
63
104
  }
105
+ /**
106
+ * Called by the hook's shared message handler when a server turn finishes
107
+ * outside the currently attached transport stream, such as after local-only
108
+ * client cleanup.
109
+ */
110
+ handleServerTurnCompleted(requestId) {
111
+ this.clearActiveServerTurn(requestId);
112
+ }
113
+ /**
114
+ * Register a server turn that is being rendered outside a transport-owned
115
+ * stream, such as the hook's fallback cross-tab/resume observer path.
116
+ */
117
+ observeServerTurn(requestId) {
118
+ this.setActiveServerTurn(requestId, null);
119
+ }
64
120
  async sendMessages(options) {
65
121
  const requestId = nanoid(8);
66
122
  const abortController = new AbortController();
67
123
  let completed = false;
124
+ let requestSent = false;
68
125
  let extraBody = {};
69
126
  if (this.prepareBody) extraBody = await this.prepareBody({
70
127
  messages: options.messages,
@@ -83,9 +140,10 @@ var WebSocketChatTransport = class {
83
140
  this.activeRequestIds?.add(requestId);
84
141
  const agent = this.agent;
85
142
  const activeIds = this.activeRequestIds;
86
- const finish = (action, keepId = false) => {
143
+ const finish = (action, keepId = false, clearServerTurn = true) => {
87
144
  if (completed) return;
88
145
  completed = true;
146
+ if (clearServerTurn) this.clearActiveServerTurn(requestId);
89
147
  try {
90
148
  action();
91
149
  } catch {}
@@ -94,15 +152,18 @@ var WebSocketChatTransport = class {
94
152
  };
95
153
  const abortError = /* @__PURE__ */ new Error("Aborted");
96
154
  abortError.name = "AbortError";
155
+ const cancelActiveRequest = () => {
156
+ if (completed) return false;
157
+ finish(() => streamController.error(abortError), true);
158
+ return true;
159
+ };
160
+ this.setActiveServerTurn(requestId, cancelActiveRequest);
97
161
  const onAbort = () => {
98
162
  if (completed) return;
99
- try {
100
- agent.send(JSON.stringify({
101
- id: requestId,
102
- type: "cf_agent_chat_request_cancel"
103
- }));
104
- } catch {}
105
- finish(() => streamController.error(abortError), true);
163
+ if (this.cancelOnClientAbort) {
164
+ if (requestSent) this.sendCancelFrame(requestId);
165
+ finish(() => streamController.error(abortError), requestSent);
166
+ } else finish(() => streamController.error(abortError), false, !requestSent);
106
167
  };
107
168
  let streamController;
108
169
  const stream = new ReadableStream({
@@ -124,7 +185,11 @@ var WebSocketChatTransport = class {
124
185
  if (data.done) finish(() => controller.close());
125
186
  } catch {}
126
187
  };
188
+ const onClose = () => {
189
+ finish(() => controller.close(), false, false);
190
+ };
127
191
  agent.addEventListener("message", onMessage, { signal: abortController.signal });
192
+ agent.addEventListener("close", onClose, { signal: abortController.signal });
128
193
  },
129
194
  cancel() {
130
195
  onAbort();
@@ -134,6 +199,8 @@ var WebSocketChatTransport = class {
134
199
  options.abortSignal.addEventListener("abort", onAbort, { once: true });
135
200
  if (options.abortSignal.aborted) onAbort();
136
201
  }
202
+ if (completed) return stream;
203
+ requestSent = true;
137
204
  agent.send(JSON.stringify({
138
205
  id: requestId,
139
206
  init: {
@@ -270,7 +337,12 @@ var WebSocketChatTransport = class {
270
337
  if (data.done) finish(() => controller.close(), onResume, onResumeNone);
271
338
  } catch {}
272
339
  };
340
+ const onClose = () => {
341
+ if (timeout) clearTimeout(timeout);
342
+ finish(() => controller.close(), onResume, onResumeNone);
343
+ };
273
344
  agent.addEventListener("message", onMessage, { signal: streamController.signal });
345
+ agent.addEventListener("close", onClose, { signal: streamController.signal });
274
346
  try {
275
347
  agent.send(JSON.stringify({ type: "cf_agent_stream_resume_request" }));
276
348
  } catch {
@@ -278,7 +350,10 @@ var WebSocketChatTransport = class {
278
350
  }
279
351
  },
280
352
  cancel() {
281
- finish(() => {});
353
+ if (requestId && transport.cancelOnClientAbort) {
354
+ transport.sendCancelFrame(requestId);
355
+ finish(() => {}, onResumeRef, onResumeNoneRef, true);
356
+ } else finish(() => {}, onResumeRef, onResumeNoneRef);
282
357
  }
283
358
  });
284
359
  }
@@ -290,18 +365,30 @@ var WebSocketChatTransport = class {
290
365
  const agent = this.agent;
291
366
  const activeIds = this.activeRequestIds;
292
367
  const chunkController = new AbortController();
368
+ const abortError = /* @__PURE__ */ new Error("Aborted");
369
+ abortError.name = "AbortError";
293
370
  let completed = false;
294
- const finish = (action) => {
371
+ const finish = (action, keepId = false, clearServerTurn = true) => {
295
372
  if (completed) return;
296
373
  completed = true;
374
+ if (clearServerTurn) this.clearActiveServerTurn(requestId);
297
375
  try {
298
376
  action();
299
377
  } catch {}
300
- activeIds?.delete(requestId);
378
+ if (!keepId) activeIds?.delete(requestId);
301
379
  chunkController.abort();
302
380
  };
381
+ const cancelActiveRequest = () => {
382
+ if (completed) return false;
383
+ finish(() => streamController.error(abortError), true);
384
+ return true;
385
+ };
386
+ this.setActiveServerTurn(requestId, cancelActiveRequest);
387
+ let streamController;
388
+ const transport = this;
303
389
  return new ReadableStream({
304
390
  start(controller) {
391
+ streamController = controller;
305
392
  const onMessage = (event) => {
306
393
  try {
307
394
  const data = JSON.parse(event.data);
@@ -318,10 +405,17 @@ var WebSocketChatTransport = class {
318
405
  if (data.done) finish(() => controller.close());
319
406
  } catch {}
320
407
  };
408
+ const onClose = () => {
409
+ finish(() => controller.close(), false, false);
410
+ };
321
411
  agent.addEventListener("message", onMessage, { signal: chunkController.signal });
412
+ agent.addEventListener("close", onClose, { signal: chunkController.signal });
322
413
  },
323
414
  cancel() {
324
- finish(() => {});
415
+ if (transport.cancelOnClientAbort) {
416
+ transport.sendCancelFrame(requestId);
417
+ finish(() => {}, true);
418
+ } else finish(() => {}, false, false);
325
419
  }
326
420
  });
327
421
  }
@@ -482,6 +576,13 @@ function moveMessageToEnd(messages, messageId) {
482
576
  result.push(msg);
483
577
  return result;
484
578
  }
579
+ function prependMissingHydratedMessages(hydratedMessages, currentMessages) {
580
+ if (currentMessages.length === 0) return hydratedMessages;
581
+ const currentMessageIds = new Set(currentMessages.map((message) => message.id));
582
+ const missingHydratedMessages = hydratedMessages.filter((message) => !currentMessageIds.has(message.id));
583
+ if (missingHydratedMessages.length === 0) return currentMessages;
584
+ return [...missingHydratedMessages, ...currentMessages];
585
+ }
485
586
  /**
486
587
  * React hook for building AI chat interfaces using an Agent
487
588
  * @param options Chat options including the agent connection
@@ -501,7 +602,7 @@ function detectToolsRequiringConfirmation(tools) {
501
602
  return Object.entries(tools).filter(([_name, tool]) => !tool.execute).map(([name]) => name);
502
603
  }
503
604
  function useAgentChat(options) {
504
- const { agent, getInitialMessages, messages: optionsInitialMessages, onToolCall, onData, experimental_automaticToolResolution, tools, toolsRequiringConfirmation: manualToolsRequiringConfirmation, autoContinueAfterToolResult = true, autoSendAfterAllConfirmationsResolved = true, resume = true, body: bodyOption, prepareSendMessagesRequest, ...rest } = options;
605
+ const { agent, getInitialMessages, messages: optionsInitialMessages, onToolCall, onData, experimental_automaticToolResolution, tools, toolsRequiringConfirmation: manualToolsRequiringConfirmation, autoContinueAfterToolResult = true, autoSendAfterAllConfirmationsResolved = true, resume = true, cancelOnClientAbort = false, body: bodyOption, prepareSendMessagesRequest, ...rest } = options;
505
606
  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.");
506
607
  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.");
507
608
  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.");
@@ -528,7 +629,6 @@ function useAgentChat(options) {
528
629
  const agentPathChanged = Array.isArray(agent.path) && previousAgentAddressKeyRef.current !== null && previousAgentAddressKeyRef.current !== agentAddressKey;
529
630
  if (stableChatIdRef.current === null) stableChatIdRef.current = resolvedInitialMessagesCacheKey ?? fallbackChatId;
530
631
  else if (previousAgentRef.current !== agent || agentPathChanged) stableChatIdRef.current = resolvedInitialMessagesCacheKey ?? fallbackChatId;
531
- else if (resolvedInitialMessagesCacheKey && stableChatIdRef.current === fallbackChatId) stableChatIdRef.current = resolvedInitialMessagesCacheKey;
532
632
  previousAgentRef.current = agent;
533
633
  previousAgentAddressKeyRef.current = agentAddressKey;
534
634
  const agentRef = useRef(agent);
@@ -591,6 +691,7 @@ function useAgentChat(options) {
591
691
  if (customTransportRef.current === null) customTransportRef.current = new WebSocketChatTransport({
592
692
  agent: agentRef.current,
593
693
  activeRequestIds: localRequestIdsRef.current,
694
+ cancelOnClientAbort,
594
695
  prepareBody: async ({ messages: msgs, trigger, messageId }) => {
595
696
  let extraBody = {};
596
697
  const currentBody = bodyOptionRef.current;
@@ -612,6 +713,7 @@ function useAgentChat(options) {
612
713
  }
613
714
  });
614
715
  customTransportRef.current.agent = agentRef.current;
716
+ customTransportRef.current.setCancelOnClientAbort(cancelOnClientAbort);
615
717
  const customTransport = customTransportRef.current;
616
718
  const useChatHelpers = useChat({
617
719
  ...rest,
@@ -650,6 +752,7 @@ function useAgentChat(options) {
650
752
  ]);
651
753
  const stopWithToolContinuationAbort = useCallback(async () => {
652
754
  try {
755
+ customTransport.cancelActiveServerTurn();
653
756
  await stop();
654
757
  } finally {
655
758
  customTransport.abortActiveToolContinuation();
@@ -670,14 +773,9 @@ function useAgentChat(options) {
670
773
  useEffect(() => {
671
774
  if (!initialMessagesPromise) return;
672
775
  if (seededInitialMessagesKeyRef.current === initialMessagesCacheKey) return;
673
- if (chatMessages.length > 0) {
674
- markInitialMessagesSeeded();
675
- return;
676
- }
677
776
  markInitialMessagesSeeded();
678
- setMessages(initialMessagesRef.current);
777
+ setMessages((prevMessages) => prependMissingHydratedMessages(initialMessagesRef.current, prevMessages));
679
778
  }, [
680
- chatMessages.length,
681
779
  initialMessagesCacheKey,
682
780
  initialMessagesPromise,
683
781
  markInitialMessagesSeeded,
@@ -987,6 +1085,7 @@ function useAgentChat(options) {
987
1085
  streamId: data.id,
988
1086
  messageId: nanoid()
989
1087
  }).state;
1088
+ customTransport.observeServerTurn(data.id);
990
1089
  setIsServerStreaming(true);
991
1090
  agentRef.current.send(JSON.stringify({
992
1091
  type: "cf_agent_stream_resume_ack",
@@ -1007,6 +1106,11 @@ function useAgentChat(options) {
1007
1106
  } catch {}
1008
1107
  if (data.done || data.replayComplete) pendingReplayResumeRequestIdsRef.current.delete(data.id);
1009
1108
  if (data.done) {
1109
+ if (streamStateRef.current.status === "observing" && streamStateRef.current.streamId === data.id) {
1110
+ streamStateRef.current = { status: "idle" };
1111
+ setIsServerStreaming(false);
1112
+ }
1113
+ customTransport.handleServerTurnCompleted(data.id);
1010
1114
  restoreProtectedStreamingAssistant(localResponseIds.get(data.id));
1011
1115
  localResponseIds.delete(data.id);
1012
1116
  localRequestIdsRef.current.delete(data.id);
@@ -1026,6 +1130,7 @@ function useAgentChat(options) {
1026
1130
  console.warn("[useAgentChat] Failed to parse stream chunk:", parseError instanceof Error ? parseError.message : parseError, "body:", data.body?.slice(0, 100));
1027
1131
  }
1028
1132
  if (data.done || data.replayComplete) pendingReplayResumeRequestIdsRef.current.delete(data.id);
1133
+ if (data.done) customTransport.handleServerTurnCompleted(data.id);
1029
1134
  const result = broadcastTransition(streamStateRef.current, {
1030
1135
  type: "response",
1031
1136
  streamId: data.id,