@cloudflare/ai-chat 0.5.4 → 0.6.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
@@ -225,6 +225,10 @@ type UseAgentChatOptions<
225
225
  /** Agent connection from useAgent (accepts both typed and untyped agents) */ agent: AgentConnection & {
226
226
  agent: string;
227
227
  name: string;
228
+ path?: ReadonlyArray<{
229
+ agent: string;
230
+ name: string;
231
+ }>;
228
232
  getHttpUrl: () => string;
229
233
  };
230
234
  getInitialMessages?:
package/dist/react.js CHANGED
@@ -165,11 +165,12 @@ var WebSocketChatTransport = class {
165
165
  this._resumeResolver = (data) => {
166
166
  const requestId = data.id;
167
167
  activeIds?.add(requestId);
168
+ const stream = this._createResumeStream(requestId);
168
169
  this.agent.send(JSON.stringify({
169
170
  type: "cf_agent_stream_resume_ack",
170
171
  id: requestId
171
172
  }));
172
- done(this._createResumeStream(requestId));
173
+ done(stream);
173
174
  };
174
175
  try {
175
176
  this.agent.send(JSON.stringify({ type: "cf_agent_stream_resume_request" }));
@@ -517,16 +518,19 @@ function useAgentChat(options) {
517
518
  const agentUrl = rawHttpUrl ? new URL(rawHttpUrl) : null;
518
519
  if (agentUrl) agentUrl.searchParams.delete("_pk");
519
520
  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;
521
+ const agentAddressKey = Array.isArray(agent.path) ? JSON.stringify(agent.path.map((step) => [step.agent, step.name])) : JSON.stringify([[agent.agent ?? "", agent.name ?? ""]]);
522
+ const resolvedInitialMessagesCacheKey = agentUrl ? `${agentUrl.origin}${agentUrl.pathname}|${agentAddressKey}` : null;
523
+ const initialMessagesCacheKey = agentAddressKey;
523
524
  const stableChatIdRef = useRef(null);
524
525
  const previousAgentRef = useRef(null);
525
- const fallbackChatId = agentIdentityKey;
526
+ const previousAgentAddressKeyRef = useRef(null);
527
+ const fallbackChatId = agentAddressKey;
528
+ const agentPathChanged = Array.isArray(agent.path) && previousAgentAddressKeyRef.current !== null && previousAgentAddressKeyRef.current !== agentAddressKey;
526
529
  if (stableChatIdRef.current === null) stableChatIdRef.current = resolvedInitialMessagesCacheKey ?? fallbackChatId;
527
- else if (previousAgentRef.current !== agent) stableChatIdRef.current = resolvedInitialMessagesCacheKey ?? fallbackChatId;
530
+ else if (previousAgentRef.current !== agent || agentPathChanged) stableChatIdRef.current = resolvedInitialMessagesCacheKey ?? fallbackChatId;
528
531
  else if (resolvedInitialMessagesCacheKey && stableChatIdRef.current === fallbackChatId) stableChatIdRef.current = resolvedInitialMessagesCacheKey;
529
532
  previousAgentRef.current = agent;
533
+ previousAgentAddressKeyRef.current = agentAddressKey;
530
534
  const agentRef = useRef(agent);
531
535
  agentRef.current = agent;
532
536
  async function defaultGetInitialMessagesFetch({ url }) {
@@ -581,6 +585,8 @@ function useAgentChat(options) {
581
585
  * Used by onAgentMessage to skip messages already handled by the transport.
582
586
  */
583
587
  const localRequestIdsRef = useRef(/* @__PURE__ */ new Set());
588
+ const pendingReplayResumeRequestIdsRef = useRef(/* @__PURE__ */ new Set());
589
+ const replayHydratedAssistantMessageIdsRef = useRef(/* @__PURE__ */ new Set());
584
590
  const customTransportRef = useRef(null);
585
591
  if (customTransportRef.current === null) customTransportRef.current = new WebSocketChatTransport({
586
592
  agent: agentRef.current,
@@ -718,6 +724,53 @@ function useAgentChat(options) {
718
724
  return result;
719
725
  });
720
726
  }, [setMessages]);
727
+ const resetMatchingHydratedAssistantForReplay = useCallback((messageId) => {
728
+ setMessages((prevMessages) => {
729
+ const lastMessage = prevMessages[prevMessages.length - 1];
730
+ if (!lastMessage || lastMessage.role !== "assistant" || lastMessage.id !== messageId) return prevMessages;
731
+ replayHydratedAssistantMessageIdsRef.current.add(messageId);
732
+ const next = [...prevMessages];
733
+ next[next.length - 1] = {
734
+ ...lastMessage,
735
+ parts: []
736
+ };
737
+ return next;
738
+ });
739
+ }, [setMessages]);
740
+ const collapseHydratedReplayTextParts = useCallback((message) => {
741
+ const parts = message.parts;
742
+ const nextParts = parts.filter((part, index) => {
743
+ if (part.type !== "text" || !("text" in part) || !part.text) return true;
744
+ return !parts.some((candidate, candidateIndex) => {
745
+ if (candidateIndex <= index) return false;
746
+ if (candidate.type !== "text" || !("text" in candidate) || !candidate.text) return false;
747
+ return candidate.text.startsWith(part.text);
748
+ });
749
+ });
750
+ return nextParts.length === parts.length ? message : {
751
+ ...message,
752
+ parts: nextParts
753
+ };
754
+ }, []);
755
+ useEffect(() => {
756
+ if (replayHydratedAssistantMessageIdsRef.current.size === 0) return;
757
+ const idsToCollapse = new Set(chatMessages.filter((message) => replayHydratedAssistantMessageIdsRef.current.has(message.id) && message.role === "assistant" && collapseHydratedReplayTextParts(message) !== message).map((message) => message.id));
758
+ if (idsToCollapse.size === 0) return;
759
+ setMessages((prevMessages) => {
760
+ let changed = false;
761
+ const nextMessages = prevMessages.map((message) => {
762
+ if (!idsToCollapse.has(message.id)) return message;
763
+ const nextMessage = collapseHydratedReplayTextParts(message);
764
+ if (nextMessage !== message) changed = true;
765
+ return nextMessage;
766
+ });
767
+ return changed ? nextMessages : prevMessages;
768
+ });
769
+ }, [
770
+ chatMessages,
771
+ collapseHydratedReplayTextParts,
772
+ setMessages
773
+ ]);
721
774
  const resetLocalChatState = useCallback(() => {
722
775
  markInitialMessagesSeeded();
723
776
  setMessages([]);
@@ -725,6 +778,8 @@ function useAgentChat(options) {
725
778
  resetToolContinuation();
726
779
  processedToolCalls.current.clear();
727
780
  localResponseMessageIdsRef.current.clear();
781
+ pendingReplayResumeRequestIdsRef.current.clear();
782
+ replayHydratedAssistantMessageIdsRef.current.clear();
728
783
  protectedStreamingAssistantRef.current = null;
729
784
  }, [
730
785
  markInitialMessagesSeeded,
@@ -924,6 +979,7 @@ function useAgentChat(options) {
924
979
  break;
925
980
  case "cf_agent_stream_resuming":
926
981
  if (!resume && !customTransport.isAwaitingResume()) return;
982
+ if (!resumingToolContinuationRef.current) pendingReplayResumeRequestIdsRef.current.add(data.id);
927
983
  if (customTransport.handleStreamResuming(data)) return;
928
984
  if (localRequestIdsRef.current.has(data.id)) return;
929
985
  streamStateRef.current = broadcastTransition(streamStateRef.current, {
@@ -941,8 +997,15 @@ function useAgentChat(options) {
941
997
  if (localRequestIdsRef.current.has(data.id)) {
942
998
  if (data.body?.trim()) try {
943
999
  const chunkData = JSON.parse(data.body);
944
- if (chunkData.type === "start" && typeof chunkData.messageId === "string") localResponseIds.set(data.id, chunkData.messageId);
1000
+ if (chunkData.type === "start" && typeof chunkData.messageId === "string") {
1001
+ localResponseIds.set(data.id, chunkData.messageId);
1002
+ if (data.replay && pendingReplayResumeRequestIdsRef.current.has(data.id)) {
1003
+ pendingReplayResumeRequestIdsRef.current.delete(data.id);
1004
+ resetMatchingHydratedAssistantForReplay(chunkData.messageId);
1005
+ }
1006
+ }
945
1007
  } catch {}
1008
+ if (data.done || data.replayComplete) pendingReplayResumeRequestIdsRef.current.delete(data.id);
946
1009
  if (data.done) {
947
1010
  restoreProtectedStreamingAssistant(localResponseIds.get(data.id));
948
1011
  localResponseIds.delete(data.id);
@@ -951,12 +1014,18 @@ function useAgentChat(options) {
951
1014
  return;
952
1015
  }
953
1016
  let chunkData;
1017
+ if (data.replay && streamStateRef.current.status !== "observing" && !pendingReplayResumeRequestIdsRef.current.has(data.id)) return;
954
1018
  if (data.body?.trim()) try {
955
1019
  chunkData = JSON.parse(data.body);
1020
+ if (data.replay && pendingReplayResumeRequestIdsRef.current.has(data.id) && typeof chunkData.messageId === "string" && chunkData.type === "start") {
1021
+ pendingReplayResumeRequestIdsRef.current.delete(data.id);
1022
+ resetMatchingHydratedAssistantForReplay(chunkData.messageId);
1023
+ }
956
1024
  if (typeof chunkData.type === "string" && chunkData.type.startsWith("data-") && onDataRef.current) onDataRef.current(chunkData);
957
1025
  } catch (parseError) {
958
1026
  console.warn("[useAgentChat] Failed to parse stream chunk:", parseError instanceof Error ? parseError.message : parseError, "body:", data.body?.slice(0, 100));
959
1027
  }
1028
+ if (data.done || data.replayComplete) pendingReplayResumeRequestIdsRef.current.delete(data.id);
960
1029
  const result = broadcastTransition(streamStateRef.current, {
961
1030
  type: "response",
962
1031
  streamId: data.id,
@@ -990,6 +1059,7 @@ function useAgentChat(options) {
990
1059
  resume,
991
1060
  customTransport,
992
1061
  preserveProtectedStreamingAssistant,
1062
+ resetMatchingHydratedAssistantForReplay,
993
1063
  restoreProtectedStreamingAssistant,
994
1064
  resetLocalChatState
995
1065
  ]);