@cloudflare/ai-chat 0.7.2 → 0.8.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
@@ -401,6 +401,16 @@ declare function useAgentChat<
401
401
  * Use this for showing a universal streaming indicator.
402
402
  */
403
403
  isStreaming: boolean;
404
+ /**
405
+ * `true` while a durable chat turn is being recovered (interrupted by a
406
+ * deploy/eviction or a stream-stall watchdog abort and now resuming, #1620).
407
+ * Distinct from `isStreaming` — a recovering turn isn't producing tokens yet,
408
+ * so a client can show a "recovering…" hint instead of looking frozen. Most
409
+ * UIs treat `isStreaming || isRecovering` as "busy". Driven by the server's
410
+ * `CF_AGENT_CHAT_RECOVERING` frames (also replayed on connect for
411
+ * `@cloudflare/think`); cleared automatically on the next stream or terminal.
412
+ */
413
+ isRecovering: boolean;
404
414
  /**
405
415
  * `true` when the current `status`/`isServerStreaming` activity is
406
416
  * driven by a server-pushed tool continuation (i.e. the server is
package/dist/react.js CHANGED
@@ -727,28 +727,57 @@ function useAgentChat(options) {
727
727
  const statusRef = useRef(status);
728
728
  statusRef.current = status;
729
729
  const resumingToolContinuationRef = useRef(false);
730
+ const pendingToolContinuationRef = useRef(false);
731
+ const observedToolContinuationRequestIdRef = useRef(null);
732
+ const continuationLaunchTimerRef = useRef(null);
730
733
  const continuationGenerationRef = useRef(0);
731
734
  const [isToolContinuation, setIsToolContinuation] = useState(false);
732
735
  const resetToolContinuation = useCallback(() => {
733
736
  continuationGenerationRef.current++;
737
+ pendingToolContinuationRef.current = false;
734
738
  resumingToolContinuationRef.current = false;
739
+ observedToolContinuationRequestIdRef.current = null;
740
+ if (continuationLaunchTimerRef.current) {
741
+ clearTimeout(continuationLaunchTimerRef.current);
742
+ continuationLaunchTimerRef.current = null;
743
+ }
735
744
  setIsToolContinuation(false);
736
745
  }, []);
746
+ const scheduleToolContinuationLaunch = useCallback(() => {
747
+ if (!pendingToolContinuationRef.current || statusRef.current !== "ready" || continuationLaunchTimerRef.current) return;
748
+ continuationLaunchTimerRef.current = setTimeout(() => {
749
+ continuationLaunchTimerRef.current = null;
750
+ if (!pendingToolContinuationRef.current || statusRef.current !== "ready") return;
751
+ pendingToolContinuationRef.current = false;
752
+ const myGeneration = continuationGenerationRef.current;
753
+ customTransport.expectToolContinuation();
754
+ resumeStream().catch((error) => {
755
+ console.error("[useAgentChat] Tool continuation resume failed:", error);
756
+ }).finally(() => {
757
+ if (continuationGenerationRef.current !== myGeneration) return;
758
+ resumingToolContinuationRef.current = false;
759
+ setIsToolContinuation(false);
760
+ });
761
+ }, 0);
762
+ }, [customTransport, resumeStream]);
737
763
  const startToolContinuation = useCallback(() => {
738
764
  if (!autoContinueAfterToolResult || resumingToolContinuationRef.current) return;
739
- const myGeneration = ++continuationGenerationRef.current;
765
+ ++continuationGenerationRef.current;
740
766
  resumingToolContinuationRef.current = true;
767
+ pendingToolContinuationRef.current = true;
741
768
  setIsToolContinuation(true);
742
- customTransport.expectToolContinuation();
743
- resumeStream().finally(() => {
744
- if (continuationGenerationRef.current !== myGeneration) return;
745
- resumingToolContinuationRef.current = false;
746
- setIsToolContinuation(false);
747
- });
769
+ scheduleToolContinuationLaunch();
770
+ }, [autoContinueAfterToolResult, scheduleToolContinuationLaunch]);
771
+ useEffect(() => {
772
+ if (status === "error" && pendingToolContinuationRef.current) {
773
+ resetToolContinuation();
774
+ return;
775
+ }
776
+ scheduleToolContinuationLaunch();
748
777
  }, [
749
- autoContinueAfterToolResult,
750
- customTransport,
751
- resumeStream
778
+ resetToolContinuation,
779
+ scheduleToolContinuationLaunch,
780
+ status
752
781
  ]);
753
782
  const stopWithToolContinuationAbort = useCallback(async () => {
754
783
  try {
@@ -873,6 +902,7 @@ function useAgentChat(options) {
873
902
  markInitialMessagesSeeded();
874
903
  setMessages([]);
875
904
  setClientToolResults(/* @__PURE__ */ new Map());
905
+ setPendingOnToolCallIds(/* @__PURE__ */ new Set());
876
906
  resetToolContinuation();
877
907
  processedToolCalls.current.clear();
878
908
  localResponseMessageIdsRef.current.clear();
@@ -904,6 +934,15 @@ function useAgentChat(options) {
904
934
  })();
905
935
  const pendingConfirmationsRef = useRef(pendingConfirmations);
906
936
  pendingConfirmationsRef.current = pendingConfirmations;
937
+ const [pendingOnToolCallIds, setPendingOnToolCallIds] = useState(() => /* @__PURE__ */ new Set());
938
+ const finishOnToolCall = useCallback((toolCallId) => {
939
+ setPendingOnToolCallIds((prev) => {
940
+ if (!prev.has(toolCallId)) return prev;
941
+ const next = new Set(prev);
942
+ next.delete(toolCallId);
943
+ return next;
944
+ });
945
+ }, []);
907
946
  useEffect(() => {
908
947
  if (!experimental_automaticToolResolution) return;
909
948
  if (isResolvingToolsRef.current) return;
@@ -1006,6 +1045,12 @@ function useAgentChat(options) {
1006
1045
  const toolCallId = part.toolCallId;
1007
1046
  const toolName = getToolName(part);
1008
1047
  processedToolCalls.current.add(toolCallId);
1048
+ setPendingOnToolCallIds((prev) => {
1049
+ if (prev.has(toolCallId)) return prev;
1050
+ const next = new Set(prev);
1051
+ next.add(toolCallId);
1052
+ return next;
1053
+ });
1009
1054
  const addToolOutput = (opts) => {
1010
1055
  sendToolOutputToServer(opts.toolCallId, toolName, opts.output, opts.state, opts.errorText);
1011
1056
  addToolResult({
@@ -1014,22 +1059,33 @@ function useAgentChat(options) {
1014
1059
  output: opts.state === "output-error" ? opts.errorText ?? "Tool execution denied by user" : opts.output
1015
1060
  });
1016
1061
  };
1017
- currentOnToolCall({
1018
- toolCall: {
1019
- toolCallId,
1020
- toolName,
1021
- input: part.input
1022
- },
1023
- addToolOutput
1062
+ let result;
1063
+ try {
1064
+ result = currentOnToolCall({
1065
+ toolCall: {
1066
+ toolCallId,
1067
+ toolName,
1068
+ input: part.input
1069
+ },
1070
+ addToolOutput
1071
+ });
1072
+ } catch (error) {
1073
+ finishOnToolCall(toolCallId);
1074
+ throw error;
1075
+ }
1076
+ Promise.resolve(result).finally(() => {
1077
+ finishOnToolCall(toolCallId);
1024
1078
  });
1025
1079
  }
1026
1080
  }, [
1027
1081
  chatMessages,
1028
1082
  sendToolOutputToServer,
1029
- addToolResult
1083
+ addToolResult,
1084
+ finishOnToolCall
1030
1085
  ]);
1031
1086
  const streamStateRef = useRef({ status: "idle" });
1032
1087
  const [isServerStreaming, setIsServerStreaming] = useState(false);
1088
+ const [isRecovering, setIsRecovering] = useState(false);
1033
1089
  useEffect(() => {
1034
1090
  const localResponseIds = localResponseMessageIdsRef.current;
1035
1091
  /**
@@ -1048,8 +1104,12 @@ function useAgentChat(options) {
1048
1104
  case "cf_agent_chat_clear":
1049
1105
  streamStateRef.current = broadcastTransition(streamStateRef.current, { type: "clear" }).state;
1050
1106
  setIsServerStreaming(false);
1107
+ setIsRecovering(false);
1051
1108
  resetLocalChatState();
1052
1109
  break;
1110
+ case "cf_agent_chat_recovering":
1111
+ setIsRecovering(Boolean(data.recovering));
1112
+ break;
1053
1113
  case "cf_agent_chat_messages":
1054
1114
  setMessages(preserveProtectedStreamingAssistant(data.messages));
1055
1115
  break;
@@ -1075,11 +1135,22 @@ function useAgentChat(options) {
1075
1135
  case "cf_agent_stream_resume_none":
1076
1136
  customTransport.handleStreamResumeNone();
1077
1137
  break;
1078
- case "cf_agent_stream_resuming":
1079
- if (!resume && !customTransport.isAwaitingResume()) return;
1138
+ case "cf_agent_stream_resuming": {
1139
+ const isEarlyToolContinuation = resumingToolContinuationRef.current && !customTransport.isAwaitingResume();
1140
+ if (!resume && !customTransport.isAwaitingResume()) {
1141
+ if (!isEarlyToolContinuation) return;
1142
+ }
1080
1143
  if (!resumingToolContinuationRef.current) pendingReplayResumeRequestIdsRef.current.add(data.id);
1081
1144
  if (customTransport.handleStreamResuming(data)) return;
1082
1145
  if (localRequestIdsRef.current.has(data.id)) return;
1146
+ if (isEarlyToolContinuation) {
1147
+ pendingToolContinuationRef.current = false;
1148
+ observedToolContinuationRequestIdRef.current = data.id;
1149
+ if (continuationLaunchTimerRef.current) {
1150
+ clearTimeout(continuationLaunchTimerRef.current);
1151
+ continuationLaunchTimerRef.current = null;
1152
+ }
1153
+ }
1083
1154
  streamStateRef.current = broadcastTransition(streamStateRef.current, {
1084
1155
  type: "resume-fallback",
1085
1156
  streamId: data.id,
@@ -1087,11 +1158,13 @@ function useAgentChat(options) {
1087
1158
  }).state;
1088
1159
  customTransport.observeServerTurn(data.id);
1089
1160
  setIsServerStreaming(true);
1161
+ setIsRecovering(false);
1090
1162
  agentRef.current.send(JSON.stringify({
1091
1163
  type: "cf_agent_stream_resume_ack",
1092
1164
  id: data.id
1093
1165
  }));
1094
1166
  break;
1167
+ }
1095
1168
  case "cf_agent_use_chat_response": {
1096
1169
  if (localRequestIdsRef.current.has(data.id)) {
1097
1170
  if (data.body?.trim()) try {
@@ -1130,7 +1203,11 @@ function useAgentChat(options) {
1130
1203
  console.warn("[useAgentChat] Failed to parse stream chunk:", parseError instanceof Error ? parseError.message : parseError, "body:", data.body?.slice(0, 100));
1131
1204
  }
1132
1205
  if (data.done || data.replayComplete) pendingReplayResumeRequestIdsRef.current.delete(data.id);
1133
- if (data.done) customTransport.handleServerTurnCompleted(data.id);
1206
+ if (data.done) {
1207
+ customTransport.handleServerTurnCompleted(data.id);
1208
+ setIsRecovering(false);
1209
+ }
1210
+ const completedObservedToolContinuation = data.done && observedToolContinuationRequestIdRef.current === data.id;
1134
1211
  const result = broadcastTransition(streamStateRef.current, {
1135
1212
  type: "response",
1136
1213
  streamId: data.id,
@@ -1146,6 +1223,7 @@ function useAgentChat(options) {
1146
1223
  streamStateRef.current = result.state;
1147
1224
  if (result.messagesUpdate) setMessages(result.messagesUpdate);
1148
1225
  setIsServerStreaming(result.isStreaming);
1226
+ if (completedObservedToolContinuation) resetToolContinuation();
1149
1227
  break;
1150
1228
  }
1151
1229
  }
@@ -1155,6 +1233,7 @@ function useAgentChat(options) {
1155
1233
  agent.removeEventListener("message", onAgentMessage);
1156
1234
  streamStateRef.current = { status: "idle" };
1157
1235
  setIsServerStreaming(false);
1236
+ setIsRecovering(false);
1158
1237
  protectedStreamingAssistantRef.current = null;
1159
1238
  localResponseIds.clear();
1160
1239
  };
@@ -1164,6 +1243,7 @@ function useAgentChat(options) {
1164
1243
  resume,
1165
1244
  customTransport,
1166
1245
  preserveProtectedStreamingAssistant,
1246
+ resetToolContinuation,
1167
1247
  resetMatchingHydratedAssistantForReplay,
1168
1248
  restoreProtectedStreamingAssistant,
1169
1249
  resetLocalChatState
@@ -1254,15 +1334,15 @@ function useAgentChat(options) {
1254
1334
  }, [sendToolOutputToServer, addToolResult]);
1255
1335
  const lastAssistantMessage = messagesWithToolResults[messagesWithToolResults.length - 1];
1256
1336
  const hasPendingClientToolCalls = (() => {
1257
- const hasOnToolCall = !!onToolCall;
1258
- if (!hasOnToolCall && !tools) return false;
1337
+ if (pendingOnToolCallIds.size === 0 && !tools) return false;
1259
1338
  if (!lastAssistantMessage || lastAssistantMessage.role !== "assistant") return false;
1260
1339
  for (const part of lastAssistantMessage.parts) {
1261
1340
  if (!isToolUIPart(part)) continue;
1262
1341
  if (part.state !== "input-available") continue;
1263
1342
  const toolName = getToolName(part);
1264
1343
  if (toolsRequiringConfirmation.includes(toolName)) continue;
1265
- if (hasOnToolCall || tools?.[toolName]?.execute) return true;
1344
+ if (pendingOnToolCallIds.has(part.toolCallId)) return true;
1345
+ if (tools?.[toolName]?.execute) return true;
1266
1346
  }
1267
1347
  return false;
1268
1348
  })();
@@ -1273,6 +1353,14 @@ function useAgentChat(options) {
1273
1353
  messages: messagesWithToolResults,
1274
1354
  isServerStreaming: effectiveIsServerStreaming,
1275
1355
  isStreaming,
1356
+ /**
1357
+ * True while a durable chat turn is being recovered (interrupted by a
1358
+ * deploy/eviction or a stream-stall watchdog abort and now resuming, #1620).
1359
+ * Distinct from `isStreaming` — a recovering turn isn't producing tokens
1360
+ * yet. Render a "recovering…" hint; most UIs treat `isStreaming ||
1361
+ * isRecovering` as "busy". Cleared automatically on the next stream/terminal.
1362
+ */
1363
+ isRecovering,
1276
1364
  isToolContinuation,
1277
1365
  sendMessage: sendMessageWithStreamingProtection,
1278
1366
  stop: stopWithToolContinuationAbort,