@cloudflare/ai-chat 0.4.6 → 0.5.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
@@ -157,7 +157,7 @@ declare function getAgentMessages<M extends UIMessage = UIMessage>(
157
157
  type GetInitialMessagesOptions = {
158
158
  agent: string;
159
159
  name: string;
160
- url: string;
160
+ url?: string;
161
161
  };
162
162
  type UseChatParams<M extends UIMessage = UIMessage> = ChatInit<M> &
163
163
  UseChatOptions<M>;
@@ -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
@@ -513,13 +513,23 @@ function useAgentChat(options) {
513
513
  onToolCallRef.current = onToolCall;
514
514
  const onDataRef = useRef(onData);
515
515
  onDataRef.current = onData;
516
- const agentUrl = new URL(agent.getHttpUrl());
517
- agentUrl.searchParams.delete("_pk");
518
- const agentUrlString = agentUrl.toString();
519
- const initialMessagesCacheKey = `${agentUrl.origin}${agentUrl.pathname}|${agent.agent ?? ""}|${agent.name ?? ""}`;
516
+ const rawHttpUrl = agent.getHttpUrl();
517
+ const agentUrl = rawHttpUrl ? new URL(rawHttpUrl) : null;
518
+ if (agentUrl) agentUrl.searchParams.delete("_pk");
519
+ const agentUrlString = agentUrl?.toString() ?? null;
520
+ const agentIdentityKey = `${agent.agent ?? ""}|${agent.name ?? ""}`;
521
+ const resolvedInitialMessagesCacheKey = agentUrl ? `${agentUrl.origin}${agentUrl.pathname}|${agentIdentityKey}` : null;
522
+ const initialMessagesCacheKey = agentIdentityKey;
523
+ const stableChatIdRef = useRef(null);
524
+ const previousChatIdentityKeyRef = useRef(null);
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;
520
529
  const agentRef = useRef(agent);
521
530
  agentRef.current = agent;
522
531
  async function defaultGetInitialMessagesFetch({ url }) {
532
+ if (!url) return [];
523
533
  const getMessagesUrl = new URL(url);
524
534
  getMessagesUrl.pathname += "/get-messages";
525
535
  const response = await fetch(getMessagesUrl.toString(), {
@@ -546,10 +556,10 @@ function useAgentChat(options) {
546
556
  requestCache.set(cacheKey, promise);
547
557
  return promise;
548
558
  }
549
- const initialMessagesPromise = getInitialMessages === null ? null : doGetInitialMessages({
559
+ const initialMessagesPromise = !(getInitialMessages === null ? false : getInitialMessages ? true : !!agentUrlString) ? null : doGetInitialMessages({
550
560
  agent: agent.agent,
551
561
  name: agent.name,
552
- url: agentUrlString
562
+ url: agentUrlString ?? void 0
553
563
  }, initialMessagesCacheKey);
554
564
  const initialMessages = initialMessagesPromise ? use(initialMessagesPromise) : optionsInitialMessages ?? [];
555
565
  useEffect(() => {
@@ -601,19 +611,30 @@ function useAgentChat(options) {
601
611
  onData,
602
612
  messages: initialMessages,
603
613
  transport: customTransport,
604
- id: initialMessagesCacheKey,
614
+ id: stableChatIdRef.current,
605
615
  resume
606
616
  });
607
617
  const { messages: chatMessages, setMessages, addToolResult, addToolApprovalResponse, sendMessage, resumeStream, status, stop } = useChatHelpers;
608
618
  const statusRef = useRef(status);
609
619
  statusRef.current = status;
610
620
  const resumingToolContinuationRef = useRef(false);
621
+ const continuationGenerationRef = useRef(0);
622
+ const [isToolContinuation, setIsToolContinuation] = useState(false);
623
+ const resetToolContinuation = useCallback(() => {
624
+ continuationGenerationRef.current++;
625
+ resumingToolContinuationRef.current = false;
626
+ setIsToolContinuation(false);
627
+ }, []);
611
628
  const startToolContinuation = useCallback(() => {
612
629
  if (!autoContinueAfterToolResult || resumingToolContinuationRef.current) return;
630
+ const myGeneration = ++continuationGenerationRef.current;
613
631
  resumingToolContinuationRef.current = true;
632
+ setIsToolContinuation(true);
614
633
  customTransport.expectToolContinuation();
615
634
  resumeStream().finally(() => {
635
+ if (continuationGenerationRef.current !== myGeneration) return;
616
636
  resumingToolContinuationRef.current = false;
637
+ setIsToolContinuation(false);
617
638
  });
618
639
  }, [
619
640
  autoContinueAfterToolResult,
@@ -633,13 +654,35 @@ function useAgentChat(options) {
633
654
  const [clientToolResults, setClientToolResults] = useState(/* @__PURE__ */ new Map());
634
655
  const messagesRef = useRef(chatMessages);
635
656
  messagesRef.current = chatMessages;
657
+ const initialMessagesRef = useRef(initialMessages);
658
+ initialMessagesRef.current = initialMessages;
659
+ const seededInitialMessagesKeyRef = useRef(null);
660
+ const markInitialMessagesSeeded = useCallback(() => {
661
+ seededInitialMessagesKeyRef.current = initialMessagesCacheKey;
662
+ }, [initialMessagesCacheKey]);
663
+ useEffect(() => {
664
+ if (!initialMessagesPromise) return;
665
+ if (seededInitialMessagesKeyRef.current === initialMessagesCacheKey) return;
666
+ if (chatMessages.length > 0) {
667
+ markInitialMessagesSeeded();
668
+ return;
669
+ }
670
+ markInitialMessagesSeeded();
671
+ setMessages(initialMessagesRef.current);
672
+ }, [
673
+ chatMessages.length,
674
+ initialMessagesCacheKey,
675
+ initialMessagesPromise,
676
+ markInitialMessagesSeeded,
677
+ setMessages
678
+ ]);
636
679
  const localResponseMessageIdsRef = useRef(/* @__PURE__ */ new Map());
637
680
  const protectedStreamingAssistantRef = useRef(null);
638
681
  const preserveProtectedStreamingAssistant = useCallback((messages) => {
639
682
  const protection = protectedStreamingAssistantRef.current;
640
- if (!protection) return messages;
683
+ if (!protection) return [...messages];
641
684
  const protectedAssistant = messagesRef.current.find((message) => message.id === protection.assistantId) ?? messages.find((message) => message.id === protection.assistantId);
642
- if (!protectedAssistant) return messages;
685
+ if (!protectedAssistant) return [...messages];
643
686
  return [...messages.filter((message) => message.id !== protection.assistantId), protectedAssistant];
644
687
  }, []);
645
688
  const protectStreamingAssistantTail = useCallback(() => {
@@ -674,6 +717,19 @@ function useAgentChat(options) {
674
717
  return result;
675
718
  });
676
719
  }, [setMessages]);
720
+ const resetLocalChatState = useCallback(() => {
721
+ markInitialMessagesSeeded();
722
+ setMessages([]);
723
+ setClientToolResults(/* @__PURE__ */ new Map());
724
+ resetToolContinuation();
725
+ processedToolCalls.current.clear();
726
+ localResponseMessageIdsRef.current.clear();
727
+ protectedStreamingAssistantRef.current = null;
728
+ }, [
729
+ markInitialMessagesSeeded,
730
+ setMessages,
731
+ resetToolContinuation
732
+ ]);
677
733
  const sendMessageWithStreamingProtection = useCallback(async (message, options) => {
678
734
  const request = sendMessage(message, options);
679
735
  if (message !== void 0 && !(typeof message === "object" && message !== null && "messageId" in message && message.messageId != null)) protectStreamingAssistantTail();
@@ -836,11 +892,9 @@ function useAgentChat(options) {
836
892
  }
837
893
  switch (data.type) {
838
894
  case "cf_agent_chat_clear":
839
- localResponseIds.clear();
840
- protectedStreamingAssistantRef.current = null;
841
895
  streamStateRef.current = broadcastTransition(streamStateRef.current, { type: "clear" }).state;
842
896
  setIsServerStreaming(false);
843
- setMessages([]);
897
+ resetLocalChatState();
844
898
  break;
845
899
  case "cf_agent_chat_messages":
846
900
  setMessages(preserveProtectedStreamingAssistant(data.messages));
@@ -935,7 +989,8 @@ function useAgentChat(options) {
935
989
  resume,
936
990
  customTransport,
937
991
  preserveProtectedStreamingAssistant,
938
- restoreProtectedStreamingAssistant
992
+ restoreProtectedStreamingAssistant,
993
+ resetLocalChatState
939
994
  ]);
940
995
  const addToolResultAndSendMessage = async (args) => {
941
996
  const { toolCallId } = args;
@@ -1021,30 +1076,42 @@ function useAgentChat(options) {
1021
1076
  output: opts.state === "output-error" ? opts.errorText ?? "Tool execution denied by user" : opts.output
1022
1077
  });
1023
1078
  }, [sendToolOutputToServer, addToolResult]);
1024
- const isStreaming = status === "streaming" || isServerStreaming;
1079
+ const lastAssistantMessage = messagesWithToolResults[messagesWithToolResults.length - 1];
1080
+ const hasPendingClientToolCalls = (() => {
1081
+ const hasOnToolCall = !!onToolCall;
1082
+ if (!hasOnToolCall && !tools) return false;
1083
+ if (!lastAssistantMessage || lastAssistantMessage.role !== "assistant") return false;
1084
+ for (const part of lastAssistantMessage.parts) {
1085
+ if (!isToolUIPart(part)) continue;
1086
+ if (part.state !== "input-available") continue;
1087
+ const toolName = getToolName(part);
1088
+ if (toolsRequiringConfirmation.includes(toolName)) continue;
1089
+ if (hasOnToolCall || tools?.[toolName]?.execute) return true;
1090
+ }
1091
+ return false;
1092
+ })();
1093
+ const effectiveIsServerStreaming = isServerStreaming || hasPendingClientToolCalls;
1094
+ const isStreaming = status === "streaming" || effectiveIsServerStreaming;
1025
1095
  return {
1026
1096
  ...useChatHelpers,
1027
1097
  messages: messagesWithToolResults,
1028
- isServerStreaming,
1098
+ isServerStreaming: effectiveIsServerStreaming,
1029
1099
  isStreaming,
1100
+ isToolContinuation,
1030
1101
  sendMessage: sendMessageWithStreamingProtection,
1031
1102
  stop: stopWithToolContinuationAbort,
1032
1103
  addToolOutput,
1033
1104
  addToolResult: addToolResultAndSendMessage,
1034
1105
  addToolApprovalResponse: addToolApprovalResponseAndNotifyServer,
1035
1106
  clearHistory: () => {
1036
- setMessages([]);
1037
- setClientToolResults(/* @__PURE__ */ new Map());
1038
- resumingToolContinuationRef.current = false;
1039
- processedToolCalls.current.clear();
1040
- localResponseMessageIdsRef.current.clear();
1041
- protectedStreamingAssistantRef.current = null;
1107
+ resetLocalChatState();
1042
1108
  agent.send(JSON.stringify({ type: "cf_agent_chat_clear" }));
1043
1109
  },
1044
1110
  setMessages: (messagesOrUpdater) => {
1045
1111
  let resolvedMessages;
1046
1112
  if (typeof messagesOrUpdater === "function") resolvedMessages = messagesOrUpdater(messagesRef.current);
1047
1113
  else resolvedMessages = messagesOrUpdater;
1114
+ if (resolvedMessages.length === 0) markInitialMessagesSeeded();
1048
1115
  setMessages(resolvedMessages);
1049
1116
  agent.send(JSON.stringify({
1050
1117
  messages: resolvedMessages,