@cloudflare/ai-chat 0.5.0 → 0.5.2

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
@@ -373,9 +373,13 @@ declare function useAgentChat<
373
373
  addToolOutput: (opts: AddToolOutputOptions) => void;
374
374
  /**
375
375
  * Whether a server-initiated stream (e.g. from `saveMessages`,
376
- * auto-continuation, or another tab) is currently active.
377
- * This is independent of the AI SDK's `status` which only tracks
378
- * client-initiated request/response cycles.
376
+ * auto-continuation, or another tab) is currently active, OR a
377
+ * client-side tool call is awaiting resolution via `onToolCall`.
378
+ * Covers the full "turn-in-progress" window from the consumer's
379
+ * perspective, including the gap between the model emitting a
380
+ * client-tool call and the server pushing a continuation after
381
+ * `addToolOutput`. This is independent of the AI SDK's `status`
382
+ * which only tracks client-initiated request/response cycles.
379
383
  */
380
384
  isServerStreaming: boolean;
381
385
  /**
@@ -384,6 +388,23 @@ declare function useAgentChat<
384
388
  * Use this for showing a universal streaming indicator.
385
389
  */
386
390
  isStreaming: boolean;
391
+ /**
392
+ * `true` when the current `status`/`isServerStreaming` activity is
393
+ * driven by a server-pushed tool continuation (i.e. the server is
394
+ * auto-continuing the conversation after `addToolOutput` or
395
+ * `addToolApprovalResponse`) rather than a fresh user submission.
396
+ *
397
+ * Use this to disambiguate "user just sent a new message, awaiting
398
+ * first token" from "mid-turn tool round-trip" — e.g. when you want
399
+ * a typing indicator only for the former:
400
+ *
401
+ * ```tsx
402
+ * const showTypingIndicator = status === "submitted" && !isToolContinuation;
403
+ * ```
404
+ *
405
+ * See issue #1365.
406
+ */
407
+ isToolContinuation: boolean;
387
408
  };
388
409
  //#endregion
389
410
  export {
package/dist/react.js CHANGED
@@ -521,11 +521,12 @@ function useAgentChat(options) {
521
521
  const resolvedInitialMessagesCacheKey = agentUrl ? `${agentUrl.origin}${agentUrl.pathname}|${agentIdentityKey}` : null;
522
522
  const initialMessagesCacheKey = agentIdentityKey;
523
523
  const stableChatIdRef = useRef(null);
524
- const previousChatIdentityKeyRef = useRef(null);
524
+ const previousAgentRef = useRef(null);
525
525
  const fallbackChatId = agentIdentityKey;
526
- if (stableChatIdRef.current === null || previousChatIdentityKeyRef.current !== agentIdentityKey) stableChatIdRef.current = resolvedInitialMessagesCacheKey ?? fallbackChatId;
527
- else if (resolvedInitialMessagesCacheKey && stableChatIdRef.current !== fallbackChatId && stableChatIdRef.current !== resolvedInitialMessagesCacheKey) stableChatIdRef.current = resolvedInitialMessagesCacheKey;
528
- previousChatIdentityKeyRef.current = agentIdentityKey;
526
+ if (stableChatIdRef.current === null) stableChatIdRef.current = resolvedInitialMessagesCacheKey ?? fallbackChatId;
527
+ else if (previousAgentRef.current !== agent) stableChatIdRef.current = resolvedInitialMessagesCacheKey ?? fallbackChatId;
528
+ else if (resolvedInitialMessagesCacheKey && stableChatIdRef.current === fallbackChatId) stableChatIdRef.current = resolvedInitialMessagesCacheKey;
529
+ previousAgentRef.current = agent;
529
530
  const agentRef = useRef(agent);
530
531
  agentRef.current = agent;
531
532
  async function defaultGetInitialMessagesFetch({ url }) {
@@ -618,12 +619,23 @@ function useAgentChat(options) {
618
619
  const statusRef = useRef(status);
619
620
  statusRef.current = status;
620
621
  const resumingToolContinuationRef = useRef(false);
622
+ const continuationGenerationRef = useRef(0);
623
+ const [isToolContinuation, setIsToolContinuation] = useState(false);
624
+ const resetToolContinuation = useCallback(() => {
625
+ continuationGenerationRef.current++;
626
+ resumingToolContinuationRef.current = false;
627
+ setIsToolContinuation(false);
628
+ }, []);
621
629
  const startToolContinuation = useCallback(() => {
622
630
  if (!autoContinueAfterToolResult || resumingToolContinuationRef.current) return;
631
+ const myGeneration = ++continuationGenerationRef.current;
623
632
  resumingToolContinuationRef.current = true;
633
+ setIsToolContinuation(true);
624
634
  customTransport.expectToolContinuation();
625
635
  resumeStream().finally(() => {
636
+ if (continuationGenerationRef.current !== myGeneration) return;
626
637
  resumingToolContinuationRef.current = false;
638
+ setIsToolContinuation(false);
627
639
  });
628
640
  }, [
629
641
  autoContinueAfterToolResult,
@@ -706,6 +718,19 @@ function useAgentChat(options) {
706
718
  return result;
707
719
  });
708
720
  }, [setMessages]);
721
+ const resetLocalChatState = useCallback(() => {
722
+ markInitialMessagesSeeded();
723
+ setMessages([]);
724
+ setClientToolResults(/* @__PURE__ */ new Map());
725
+ resetToolContinuation();
726
+ processedToolCalls.current.clear();
727
+ localResponseMessageIdsRef.current.clear();
728
+ protectedStreamingAssistantRef.current = null;
729
+ }, [
730
+ markInitialMessagesSeeded,
731
+ setMessages,
732
+ resetToolContinuation
733
+ ]);
709
734
  const sendMessageWithStreamingProtection = useCallback(async (message, options) => {
710
735
  const request = sendMessage(message, options);
711
736
  if (message !== void 0 && !(typeof message === "object" && message !== null && "messageId" in message && message.messageId != null)) protectStreamingAssistantTail();
@@ -868,12 +893,9 @@ function useAgentChat(options) {
868
893
  }
869
894
  switch (data.type) {
870
895
  case "cf_agent_chat_clear":
871
- localResponseIds.clear();
872
- protectedStreamingAssistantRef.current = null;
873
896
  streamStateRef.current = broadcastTransition(streamStateRef.current, { type: "clear" }).state;
874
897
  setIsServerStreaming(false);
875
- markInitialMessagesSeeded();
876
- setMessages([]);
898
+ resetLocalChatState();
877
899
  break;
878
900
  case "cf_agent_chat_messages":
879
901
  setMessages(preserveProtectedStreamingAssistant(data.messages));
@@ -967,9 +989,9 @@ function useAgentChat(options) {
967
989
  setMessages,
968
990
  resume,
969
991
  customTransport,
970
- markInitialMessagesSeeded,
971
992
  preserveProtectedStreamingAssistant,
972
- restoreProtectedStreamingAssistant
993
+ restoreProtectedStreamingAssistant,
994
+ resetLocalChatState
973
995
  ]);
974
996
  const addToolResultAndSendMessage = async (args) => {
975
997
  const { toolCallId } = args;
@@ -1055,25 +1077,47 @@ function useAgentChat(options) {
1055
1077
  output: opts.state === "output-error" ? opts.errorText ?? "Tool execution denied by user" : opts.output
1056
1078
  });
1057
1079
  }, [sendToolOutputToServer, addToolResult]);
1058
- const isStreaming = status === "streaming" || isServerStreaming;
1080
+ const lastAssistantMessage = messagesWithToolResults[messagesWithToolResults.length - 1];
1081
+ const hasPendingClientToolCalls = (() => {
1082
+ const hasOnToolCall = !!onToolCall;
1083
+ if (!hasOnToolCall && !tools) return false;
1084
+ if (!lastAssistantMessage || lastAssistantMessage.role !== "assistant") return false;
1085
+ for (const part of lastAssistantMessage.parts) {
1086
+ if (!isToolUIPart(part)) continue;
1087
+ if (part.state !== "input-available") continue;
1088
+ const toolName = getToolName(part);
1089
+ if (toolsRequiringConfirmation.includes(toolName)) continue;
1090
+ if (hasOnToolCall || tools?.[toolName]?.execute) return true;
1091
+ }
1092
+ return false;
1093
+ })();
1094
+ const effectiveIsServerStreaming = isServerStreaming || hasPendingClientToolCalls;
1095
+ const isStreaming = status === "streaming" || effectiveIsServerStreaming;
1059
1096
  return {
1060
1097
  ...useChatHelpers,
1061
1098
  messages: messagesWithToolResults,
1062
- isServerStreaming,
1099
+ isServerStreaming: effectiveIsServerStreaming,
1063
1100
  isStreaming,
1101
+ isToolContinuation,
1064
1102
  sendMessage: sendMessageWithStreamingProtection,
1065
1103
  stop: stopWithToolContinuationAbort,
1104
+ /**
1105
+ * Provide output for a tool call. Use this for tools that require user interaction
1106
+ * or client-side execution.
1107
+ */
1066
1108
  addToolOutput,
1109
+ /**
1110
+ * @deprecated Use `addToolOutput` instead.
1111
+ */
1067
1112
  addToolResult: addToolResultAndSendMessage,
1113
+ /**
1114
+ * Respond to a tool approval request. Use this for tools with `needsApproval`.
1115
+ * This wrapper notifies the server before updating local state, preventing
1116
+ * duplicate messages when sendMessage() is called afterward.
1117
+ */
1068
1118
  addToolApprovalResponse: addToolApprovalResponseAndNotifyServer,
1069
1119
  clearHistory: () => {
1070
- markInitialMessagesSeeded();
1071
- setMessages([]);
1072
- setClientToolResults(/* @__PURE__ */ new Map());
1073
- resumingToolContinuationRef.current = false;
1074
- processedToolCalls.current.clear();
1075
- localResponseMessageIdsRef.current.clear();
1076
- protectedStreamingAssistantRef.current = null;
1120
+ resetLocalChatState();
1077
1121
  agent.send(JSON.stringify({ type: "cf_agent_chat_clear" }));
1078
1122
  },
1079
1123
  setMessages: (messagesOrUpdater) => {