@copilotkit/react-core 0.0.0-main-20260220223427 → 0.0.0-main-20260403195251

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.
Files changed (186) hide show
  1. package/CHANGELOG.md +540 -71
  2. package/dist/copilotkit-BK_zLoVm.mjs +7661 -0
  3. package/dist/copilotkit-BK_zLoVm.mjs.map +1 -0
  4. package/dist/copilotkit-BYNyIuE7.d.cts +2208 -0
  5. package/dist/copilotkit-BYNyIuE7.d.cts.map +1 -0
  6. package/dist/copilotkit-BYNyIuE7.d.ts +2208 -0
  7. package/dist/copilotkit-BYNyIuE7.d.ts.map +1 -0
  8. package/dist/copilotkit-CDZGGOIB.cjs +8074 -0
  9. package/dist/copilotkit-CDZGGOIB.cjs.map +1 -0
  10. package/dist/copilotkit-rBCfdqIo.d.mts +2208 -0
  11. package/dist/copilotkit-rBCfdqIo.d.mts.map +1 -0
  12. package/dist/index.cjs +166 -2200
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.d.cts +14 -674
  15. package/dist/index.d.cts.map +1 -1
  16. package/dist/index.d.mts +14 -674
  17. package/dist/index.d.mts.map +1 -1
  18. package/dist/index.d.ts +667 -0
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.mjs +119 -2124
  21. package/dist/index.mjs.map +1 -1
  22. package/dist/index.umd.js +2252 -230
  23. package/dist/index.umd.js.map +1 -1
  24. package/dist/v2/index.cjs +78 -6
  25. package/dist/v2/index.css +1 -2
  26. package/dist/v2/index.d.cts +6 -2
  27. package/dist/v2/index.d.mts +6 -2
  28. package/dist/v2/index.d.ts +6 -0
  29. package/dist/v2/index.mjs +8 -3
  30. package/dist/v2/index.umd.js +7786 -12
  31. package/dist/v2/index.umd.js.map +1 -0
  32. package/package.json +66 -39
  33. package/scripts/scope-preflight.mjs +100 -0
  34. package/src/components/CopilotListeners.tsx +2 -6
  35. package/src/components/copilot-provider/__tests__/copilot-messages-key.test.tsx +92 -0
  36. package/src/components/copilot-provider/copilot-messages.tsx +1 -1
  37. package/src/components/copilot-provider/copilotkit-props.tsx +1 -1
  38. package/src/components/copilot-provider/copilotkit.tsx +120 -68
  39. package/src/context/copilot-messages-context.tsx +1 -1
  40. package/src/hooks/__tests__/use-coagent-config.test.ts +2 -2
  41. package/src/hooks/__tests__/use-coagent-state-render.e2e.test.tsx +5 -6
  42. package/src/hooks/__tests__/use-copilot-chat-internal-connect.test.tsx +242 -0
  43. package/src/hooks/__tests__/use-frontend-tool-available.test.tsx +1 -1
  44. package/src/hooks/__tests__/use-frontend-tool-remount.e2e.test.tsx +4 -4
  45. package/src/hooks/index.ts +0 -1
  46. package/src/hooks/use-agent-nodename.ts +1 -1
  47. package/src/hooks/use-coagent-state-render-bridge.tsx +1 -4
  48. package/src/hooks/use-coagent.ts +1 -1
  49. package/src/hooks/use-configure-chat-suggestions.tsx +2 -2
  50. package/src/hooks/use-copilot-chat-suggestions.tsx +2 -2
  51. package/src/hooks/use-copilot-chat_internal.ts +73 -13
  52. package/src/hooks/use-copilot-readable.ts +1 -1
  53. package/src/hooks/use-frontend-tool.ts +2 -2
  54. package/src/hooks/use-human-in-the-loop.ts +2 -2
  55. package/src/hooks/use-langgraph-interrupt.ts +95 -38
  56. package/src/hooks/use-lazy-tool-renderer.tsx +1 -1
  57. package/src/hooks/use-render-tool-call.ts +1 -1
  58. package/src/lib/copilot-task.ts +1 -1
  59. package/src/setupTests.ts +18 -14
  60. package/src/types/interrupt-action.ts +5 -0
  61. package/src/v2/__tests__/A2UIMessageRenderer.test.tsx +176 -0
  62. package/src/v2/__tests__/globalSetup.ts +14 -0
  63. package/src/v2/__tests__/setup.ts +93 -0
  64. package/src/v2/__tests__/utils/test-helpers.tsx +503 -0
  65. package/src/v2/a2ui/A2UIMessageRenderer.tsx +206 -0
  66. package/src/v2/components/CopilotKitInspector.tsx +50 -0
  67. package/src/v2/components/MCPAppsActivityRenderer.tsx +785 -0
  68. package/src/v2/components/WildcardToolCallRender.tsx +86 -0
  69. package/src/v2/components/__tests__/license-warning-banner.test.tsx +46 -0
  70. package/src/v2/components/chat/CopilotChat.tsx +433 -0
  71. package/src/v2/components/chat/CopilotChatAssistantMessage.tsx +375 -0
  72. package/src/v2/components/chat/CopilotChatAudioRecorder.tsx +350 -0
  73. package/src/v2/components/chat/CopilotChatInput.tsx +1302 -0
  74. package/src/v2/components/chat/CopilotChatMessageView.tsx +561 -0
  75. package/src/v2/components/chat/CopilotChatReasoningMessage.tsx +252 -0
  76. package/src/v2/components/chat/CopilotChatSuggestionPill.tsx +59 -0
  77. package/src/v2/components/chat/CopilotChatSuggestionView.tsx +133 -0
  78. package/src/v2/components/chat/CopilotChatToggleButton.tsx +171 -0
  79. package/src/v2/components/chat/CopilotChatToolCallsView.tsx +40 -0
  80. package/src/v2/components/chat/CopilotChatUserMessage.tsx +388 -0
  81. package/src/v2/components/chat/CopilotChatView.tsx +598 -0
  82. package/src/v2/components/chat/CopilotModalHeader.tsx +129 -0
  83. package/src/v2/components/chat/CopilotPopup.tsx +81 -0
  84. package/src/v2/components/chat/CopilotPopupView.tsx +317 -0
  85. package/src/v2/components/chat/CopilotSidebar.tsx +76 -0
  86. package/src/v2/components/chat/CopilotSidebarView.tsx +255 -0
  87. package/src/v2/components/chat/__tests__/CopilotChat.e2e.test.tsx +1113 -0
  88. package/src/v2/components/chat/__tests__/CopilotChat.onError.test.tsx +73 -0
  89. package/src/v2/components/chat/__tests__/CopilotChat.slots.e2e.test.tsx +432 -0
  90. package/src/v2/components/chat/__tests__/CopilotChatActivityRendering.e2e.test.tsx +150 -0
  91. package/src/v2/components/chat/__tests__/CopilotChatAssistantMessage.slots.e2e.test.tsx +624 -0
  92. package/src/v2/components/chat/__tests__/CopilotChatAssistantMessage.test.tsx +702 -0
  93. package/src/v2/components/chat/__tests__/CopilotChatCssClasses.test.tsx +107 -0
  94. package/src/v2/components/chat/__tests__/CopilotChatInput.slots.e2e.test.tsx +929 -0
  95. package/src/v2/components/chat/__tests__/CopilotChatInput.test.tsx +986 -0
  96. package/src/v2/components/chat/__tests__/CopilotChatMessageView.slots.e2e.test.tsx +1004 -0
  97. package/src/v2/components/chat/__tests__/CopilotChatMessageView.test.tsx +169 -0
  98. package/src/v2/components/chat/__tests__/CopilotChatSuggestionView.slots.e2e.test.tsx +530 -0
  99. package/src/v2/components/chat/__tests__/CopilotChatToolRendering.e2e.test.tsx +785 -0
  100. package/src/v2/components/chat/__tests__/CopilotChatToolRerenders.e2e.test.tsx +2416 -0
  101. package/src/v2/components/chat/__tests__/CopilotChatUserMessage.slots.e2e.test.tsx +621 -0
  102. package/src/v2/components/chat/__tests__/CopilotChatView.onClick.e2e.test.tsx +853 -0
  103. package/src/v2/components/chat/__tests__/CopilotChatView.slots.e2e.test.tsx +1050 -0
  104. package/src/v2/components/chat/__tests__/CopilotModalHeader.slots.e2e.test.tsx +484 -0
  105. package/src/v2/components/chat/__tests__/CopilotPopupView.slots.e2e.test.tsx +612 -0
  106. package/src/v2/components/chat/__tests__/CopilotSidebarView.slots.e2e.test.tsx +502 -0
  107. package/src/v2/components/chat/__tests__/MCPAppsActivityRenderer.e2e.test.tsx +1027 -0
  108. package/src/v2/components/chat/__tests__/setup.ts +1 -0
  109. package/src/v2/components/chat/index.ts +79 -0
  110. package/src/v2/components/index.ts +7 -0
  111. package/src/v2/components/license-warning-banner.tsx +198 -0
  112. package/src/v2/components/ui/button.tsx +123 -0
  113. package/src/v2/components/ui/dropdown-menu.tsx +258 -0
  114. package/src/v2/components/ui/tooltip.tsx +60 -0
  115. package/src/v2/hooks/__tests__/standard-schema-types.test.tsx +152 -0
  116. package/src/v2/hooks/__tests__/standard-schema.test.tsx +282 -0
  117. package/src/v2/hooks/__tests__/use-agent-context-timing.e2e.test.tsx +140 -0
  118. package/src/v2/hooks/__tests__/use-agent-context.test.tsx +401 -0
  119. package/src/v2/hooks/__tests__/use-agent-error-state.test.tsx +44 -0
  120. package/src/v2/hooks/__tests__/use-agent-stability.test.tsx +205 -0
  121. package/src/v2/hooks/__tests__/use-agent-thread-isolation.test.tsx +327 -0
  122. package/src/v2/hooks/__tests__/use-agent-throttle.test.tsx +728 -0
  123. package/src/v2/hooks/__tests__/use-agent.e2e.test.tsx +159 -0
  124. package/src/v2/hooks/__tests__/use-component.test.tsx +123 -0
  125. package/src/v2/hooks/__tests__/use-configure-suggestions.e2e.test.tsx +696 -0
  126. package/src/v2/hooks/__tests__/use-default-render-tool.test.tsx +153 -0
  127. package/src/v2/hooks/__tests__/use-frontend-tool-available.test.tsx +167 -0
  128. package/src/v2/hooks/__tests__/use-frontend-tool.e2e.test.tsx +2148 -0
  129. package/src/v2/hooks/__tests__/use-human-in-the-loop.e2e.test.tsx +1261 -0
  130. package/src/v2/hooks/__tests__/use-interrupt.test.tsx +397 -0
  131. package/src/v2/hooks/__tests__/use-katex-styles.test.tsx +56 -0
  132. package/src/v2/hooks/__tests__/use-keyboard-height.test.tsx +192 -0
  133. package/src/v2/hooks/__tests__/use-render-tool.test.tsx +259 -0
  134. package/src/v2/hooks/__tests__/use-suggestions.e2e.test.tsx +524 -0
  135. package/src/v2/hooks/__tests__/use-threads.test.tsx +433 -0
  136. package/src/v2/hooks/__tests__/zod-regression.test.tsx +311 -0
  137. package/src/v2/hooks/index.ts +18 -0
  138. package/src/v2/hooks/use-agent-context.tsx +45 -0
  139. package/src/v2/hooks/use-agent.tsx +358 -0
  140. package/src/v2/hooks/use-component.tsx +89 -0
  141. package/src/v2/hooks/use-configure-suggestions.tsx +187 -0
  142. package/src/v2/hooks/use-default-render-tool.tsx +254 -0
  143. package/src/v2/hooks/use-frontend-tool.tsx +43 -0
  144. package/src/v2/hooks/use-human-in-the-loop.tsx +81 -0
  145. package/src/v2/hooks/use-interrupt.tsx +305 -0
  146. package/src/v2/hooks/use-keyboard-height.tsx +67 -0
  147. package/src/v2/hooks/use-render-activity-message.tsx +73 -0
  148. package/src/v2/hooks/use-render-custom-messages.tsx +98 -0
  149. package/src/v2/hooks/use-render-tool-call.tsx +175 -0
  150. package/src/v2/hooks/use-render-tool.tsx +181 -0
  151. package/src/v2/hooks/use-suggestions.tsx +91 -0
  152. package/src/v2/hooks/use-threads.tsx +256 -0
  153. package/src/v2/hooks/useKatexStyles.ts +27 -0
  154. package/src/v2/index.css +1 -1
  155. package/src/v2/index.ts +21 -2
  156. package/src/v2/lib/__tests__/completePartialMarkdown.test.ts +495 -0
  157. package/src/v2/lib/__tests__/renderSlot.test.tsx +588 -0
  158. package/src/v2/lib/react-core.ts +156 -0
  159. package/src/v2/lib/slots.tsx +143 -0
  160. package/src/v2/lib/transcription-client.ts +184 -0
  161. package/src/v2/lib/utils.ts +8 -0
  162. package/src/v2/providers/CopilotChatConfigurationProvider.tsx +162 -0
  163. package/src/v2/providers/CopilotKitProvider.tsx +600 -0
  164. package/src/v2/providers/__tests__/CopilotChatConfigurationProvider.test.tsx +546 -0
  165. package/src/v2/providers/__tests__/CopilotKitProvider.license.test.tsx +101 -0
  166. package/src/v2/providers/__tests__/CopilotKitProvider.onError.test.tsx +69 -0
  167. package/src/v2/providers/__tests__/CopilotKitProvider.renderCustomMessages.e2e.test.tsx +881 -0
  168. package/src/v2/providers/__tests__/CopilotKitProvider.stability.test.tsx +740 -0
  169. package/src/v2/providers/__tests__/CopilotKitProvider.test.tsx +642 -0
  170. package/src/v2/providers/__tests__/CopilotKitProvider.wildcard.test.tsx +294 -0
  171. package/src/v2/providers/index.ts +14 -0
  172. package/src/v2/styles/globals.css +231 -0
  173. package/src/v2/types/__tests__/defineToolCallRenderer.test.tsx +525 -0
  174. package/src/v2/types/defineToolCallRenderer.ts +65 -0
  175. package/src/v2/types/frontend-tool.ts +8 -0
  176. package/src/v2/types/human-in-the-loop.ts +33 -0
  177. package/src/v2/types/index.ts +7 -0
  178. package/src/v2/types/interrupt.ts +15 -0
  179. package/src/v2/types/react-activity-message-renderer.ts +27 -0
  180. package/src/v2/types/react-custom-message-renderer.ts +17 -0
  181. package/src/v2/types/react-tool-call-renderer.ts +32 -0
  182. package/tsdown.config.ts +34 -10
  183. package/vitest.config.mjs +4 -3
  184. package/LICENSE +0 -21
  185. package/dist/v2/index.css.map +0 -1
  186. package/src/hooks/use-langgraph-interrupt-render.ts +0 -147
@@ -0,0 +1,67 @@
1
+ import { useState, useEffect } from "react";
2
+
3
+ export interface KeyboardState {
4
+ isKeyboardOpen: boolean;
5
+ keyboardHeight: number;
6
+ availableHeight: number;
7
+ viewportHeight: number;
8
+ }
9
+
10
+ /**
11
+ * Hook to detect mobile keyboard appearance and calculate available viewport height.
12
+ * Uses the Visual Viewport API to track keyboard state on mobile devices.
13
+ *
14
+ * @returns KeyboardState object with keyboard information
15
+ */
16
+ export function useKeyboardHeight(): KeyboardState {
17
+ const [keyboardState, setKeyboardState] = useState<KeyboardState>({
18
+ isKeyboardOpen: false,
19
+ keyboardHeight: 0,
20
+ availableHeight: typeof window !== "undefined" ? window.innerHeight : 0,
21
+ viewportHeight: typeof window !== "undefined" ? window.innerHeight : 0,
22
+ });
23
+
24
+ useEffect(() => {
25
+ if (typeof window === "undefined") {
26
+ return;
27
+ }
28
+
29
+ // Check if Visual Viewport API is available
30
+ const visualViewport = window.visualViewport;
31
+ if (!visualViewport) {
32
+ return;
33
+ }
34
+
35
+ const updateKeyboardState = () => {
36
+ const layoutHeight = window.innerHeight;
37
+ const visualHeight = visualViewport.height;
38
+
39
+ // Calculate keyboard height (difference between layout and visual viewport)
40
+ const keyboardHeight = Math.max(0, layoutHeight - visualHeight);
41
+
42
+ // Keyboard is considered open if the height difference is significant (> 150px)
43
+ const isKeyboardOpen = keyboardHeight > 150;
44
+
45
+ setKeyboardState({
46
+ isKeyboardOpen,
47
+ keyboardHeight,
48
+ availableHeight: visualHeight,
49
+ viewportHeight: layoutHeight,
50
+ });
51
+ };
52
+
53
+ // Initial state
54
+ updateKeyboardState();
55
+
56
+ // Listen for viewport changes
57
+ visualViewport.addEventListener("resize", updateKeyboardState);
58
+ visualViewport.addEventListener("scroll", updateKeyboardState);
59
+
60
+ return () => {
61
+ visualViewport.removeEventListener("resize", updateKeyboardState);
62
+ visualViewport.removeEventListener("scroll", updateKeyboardState);
63
+ };
64
+ }, []);
65
+
66
+ return keyboardState;
67
+ }
@@ -0,0 +1,73 @@
1
+ import { ActivityMessage } from "@ag-ui/core";
2
+ import { DEFAULT_AGENT_ID } from "@copilotkit/shared";
3
+ import { useCopilotKit, useCopilotChatConfiguration } from "../providers";
4
+ import { useCallback, useMemo } from "react";
5
+ import { ReactActivityMessageRenderer } from "../types";
6
+
7
+ export function useRenderActivityMessage() {
8
+ const { copilotkit } = useCopilotKit();
9
+ const config = useCopilotChatConfiguration();
10
+ const agentId = config?.agentId ?? DEFAULT_AGENT_ID;
11
+
12
+ const renderers = copilotkit.renderActivityMessages;
13
+
14
+ // Find the renderer for a given activity type
15
+ const findRenderer = useCallback(
16
+ (activityType: string): ReactActivityMessageRenderer<unknown> | null => {
17
+ if (!renderers.length) {
18
+ return null;
19
+ }
20
+
21
+ const matches = renderers.filter(
22
+ (renderer) => renderer.activityType === activityType,
23
+ );
24
+
25
+ return (
26
+ matches.find((candidate) => candidate.agentId === agentId) ??
27
+ matches.find((candidate) => candidate.agentId === undefined) ??
28
+ renderers.find((candidate) => candidate.activityType === "*") ??
29
+ null
30
+ );
31
+ },
32
+ [agentId, renderers],
33
+ );
34
+
35
+ const renderActivityMessage = useCallback(
36
+ (message: ActivityMessage): React.ReactElement | null => {
37
+ const renderer = findRenderer(message.activityType);
38
+
39
+ if (!renderer) {
40
+ return null;
41
+ }
42
+
43
+ const parseResult = renderer.content.safeParse(message.content);
44
+
45
+ if (!parseResult.success) {
46
+ console.warn(
47
+ `Failed to parse content for activity message '${message.activityType}':`,
48
+ parseResult.error,
49
+ );
50
+ return null;
51
+ }
52
+
53
+ const Component = renderer.render;
54
+ const agent = copilotkit.getAgent(agentId);
55
+
56
+ return (
57
+ <Component
58
+ key={message.id}
59
+ activityType={message.activityType}
60
+ content={parseResult.data}
61
+ message={message}
62
+ agent={agent}
63
+ />
64
+ );
65
+ },
66
+ [agentId, copilotkit, findRenderer],
67
+ );
68
+
69
+ return useMemo(
70
+ () => ({ renderActivityMessage, findRenderer }),
71
+ [renderActivityMessage, findRenderer],
72
+ );
73
+ }
@@ -0,0 +1,98 @@
1
+ import { useCopilotChatConfiguration, useCopilotKit } from "../providers";
2
+ import { getThreadClone } from "./use-agent";
3
+ import { ReactCustomMessageRendererPosition } from "../types/react-custom-message-renderer";
4
+ import { Message } from "@ag-ui/core";
5
+
6
+ interface UseRenderCustomMessagesParams {
7
+ message: Message;
8
+ position: ReactCustomMessageRendererPosition;
9
+ }
10
+
11
+ export function useRenderCustomMessages() {
12
+ const { copilotkit } = useCopilotKit();
13
+ const config = useCopilotChatConfiguration();
14
+
15
+ if (!config) {
16
+ return null;
17
+ }
18
+
19
+ const { agentId, threadId } = config;
20
+
21
+ const customMessageRenderers = copilotkit.renderCustomMessages
22
+ .filter(
23
+ (renderer) =>
24
+ renderer.agentId === undefined || renderer.agentId === agentId,
25
+ )
26
+ .sort((a, b) => {
27
+ const aHasAgent = a.agentId !== undefined;
28
+ const bHasAgent = b.agentId !== undefined;
29
+ if (aHasAgent === bHasAgent) return 0;
30
+ return aHasAgent ? -1 : 1;
31
+ });
32
+
33
+ return function (params: UseRenderCustomMessagesParams) {
34
+ if (!customMessageRenderers.length) {
35
+ return null;
36
+ }
37
+ const { message, position } = params;
38
+ const resolvedRunId =
39
+ copilotkit.getRunIdForMessage(agentId, threadId, message.id) ??
40
+ copilotkit.getRunIdsForThread(agentId, threadId).slice(-1)[0];
41
+ const runId = resolvedRunId ?? `missing-run-id:${message.id}`;
42
+ // Prefer the per-thread clone so that agent.messages reflects the actual
43
+ // conversation state (messages live on the clone, not the registry agent).
44
+ // Fall back to the registry agent when no clone exists (no threadId).
45
+ const registryAgent = copilotkit.getAgent(agentId);
46
+ const agent = getThreadClone(registryAgent, threadId) ?? registryAgent;
47
+ if (!agent) {
48
+ throw new Error("Agent not found");
49
+ }
50
+
51
+ const messagesIdsInRun = resolvedRunId
52
+ ? agent.messages
53
+ .filter(
54
+ (msg) =>
55
+ copilotkit.getRunIdForMessage(agentId, threadId, msg.id) ===
56
+ resolvedRunId,
57
+ )
58
+ .map((msg) => msg.id)
59
+ : [message.id];
60
+
61
+ const rawMessageIndex = agent.messages.findIndex(
62
+ (msg) => msg.id === message.id,
63
+ );
64
+ const messageIndex = rawMessageIndex >= 0 ? rawMessageIndex : 0;
65
+ const messageIndexInRun = resolvedRunId
66
+ ? Math.max(messagesIdsInRun.indexOf(message.id), 0)
67
+ : 0;
68
+ const numberOfMessagesInRun = resolvedRunId ? messagesIdsInRun.length : 1;
69
+ const stateSnapshot = resolvedRunId
70
+ ? copilotkit.getStateByRun(agentId, threadId, resolvedRunId)
71
+ : undefined;
72
+
73
+ let result = null;
74
+ for (const renderer of customMessageRenderers) {
75
+ if (!renderer.render) {
76
+ continue;
77
+ }
78
+ const Component = renderer.render;
79
+ result = (
80
+ <Component
81
+ key={`${runId}-${message.id}-${position}`}
82
+ message={message}
83
+ position={position}
84
+ runId={runId}
85
+ messageIndex={messageIndex}
86
+ messageIndexInRun={messageIndexInRun}
87
+ numberOfMessagesInRun={numberOfMessagesInRun}
88
+ agentId={agentId}
89
+ stateSnapshot={stateSnapshot}
90
+ />
91
+ );
92
+ if (result) {
93
+ break;
94
+ }
95
+ }
96
+ return result;
97
+ };
98
+ }
@@ -0,0 +1,175 @@
1
+ import React, { useCallback, useMemo, useSyncExternalStore } from "react";
2
+ import { ToolCall, ToolMessage } from "@ag-ui/core";
3
+ import { ToolCallStatus } from "@copilotkit/core";
4
+ import { useCopilotKit } from "../providers/CopilotKitProvider";
5
+ import { useCopilotChatConfiguration } from "../providers/CopilotChatConfigurationProvider";
6
+ import { DEFAULT_AGENT_ID } from "@copilotkit/shared";
7
+ import { partialJSONParse } from "@copilotkit/shared";
8
+ import { ReactToolCallRenderer } from "../types/react-tool-call-renderer";
9
+
10
+ export interface UseRenderToolCallProps {
11
+ toolCall: ToolCall;
12
+ toolMessage?: ToolMessage;
13
+ }
14
+
15
+ /**
16
+ * Props for the memoized ToolCallRenderer component
17
+ */
18
+ interface ToolCallRendererProps {
19
+ toolCall: ToolCall;
20
+ toolMessage?: ToolMessage;
21
+ RenderComponent: ReactToolCallRenderer<unknown>["render"];
22
+ isExecuting: boolean;
23
+ }
24
+
25
+ /**
26
+ * Memoized component that renders a single tool call.
27
+ * This prevents unnecessary re-renders when parent components update
28
+ * but the tool call data hasn't changed.
29
+ */
30
+ const ToolCallRenderer = React.memo(
31
+ function ToolCallRenderer({
32
+ toolCall,
33
+ toolMessage,
34
+ RenderComponent,
35
+ isExecuting,
36
+ }: ToolCallRendererProps) {
37
+ // Memoize args based on the arguments string to maintain stable reference
38
+ const args = useMemo(
39
+ () => partialJSONParse(toolCall.function.arguments),
40
+ [toolCall.function.arguments],
41
+ );
42
+
43
+ const toolName = toolCall.function.name;
44
+
45
+ // Render based on status to preserve discriminated union type inference
46
+ if (toolMessage) {
47
+ return (
48
+ <RenderComponent
49
+ name={toolName}
50
+ args={args}
51
+ status={ToolCallStatus.Complete}
52
+ result={toolMessage.content}
53
+ />
54
+ );
55
+ } else if (isExecuting) {
56
+ return (
57
+ <RenderComponent
58
+ name={toolName}
59
+ args={args}
60
+ status={ToolCallStatus.Executing}
61
+ result={undefined}
62
+ />
63
+ );
64
+ } else {
65
+ return (
66
+ <RenderComponent
67
+ name={toolName}
68
+ args={args}
69
+ status={ToolCallStatus.InProgress}
70
+ result={undefined}
71
+ />
72
+ );
73
+ }
74
+ },
75
+ // Custom comparison function to prevent re-renders when tool call data hasn't changed
76
+ (prevProps, nextProps) => {
77
+ // Compare tool call identity and content
78
+ if (prevProps.toolCall.id !== nextProps.toolCall.id) return false;
79
+ if (prevProps.toolCall.function.name !== nextProps.toolCall.function.name)
80
+ return false;
81
+ if (
82
+ prevProps.toolCall.function.arguments !==
83
+ nextProps.toolCall.function.arguments
84
+ )
85
+ return false;
86
+
87
+ // Compare tool message (result)
88
+ const prevResult = prevProps.toolMessage?.content;
89
+ const nextResult = nextProps.toolMessage?.content;
90
+ if (prevResult !== nextResult) return false;
91
+
92
+ // Compare executing state
93
+ if (prevProps.isExecuting !== nextProps.isExecuting) return false;
94
+
95
+ // Compare render component reference
96
+ if (prevProps.RenderComponent !== nextProps.RenderComponent) return false;
97
+
98
+ return true;
99
+ },
100
+ );
101
+
102
+ /**
103
+ * Hook that returns a function to render tool calls based on the render functions
104
+ * defined in CopilotKitProvider.
105
+ *
106
+ * @returns A function that takes a tool call and optional tool message and returns the rendered component
107
+ */
108
+ export function useRenderToolCall() {
109
+ const { copilotkit, executingToolCallIds } = useCopilotKit();
110
+ const config = useCopilotChatConfiguration();
111
+ const agentId = config?.agentId ?? DEFAULT_AGENT_ID;
112
+
113
+ // Subscribe to render tool calls changes using useSyncExternalStore
114
+ // This ensures we always have the latest value, even if subscriptions run in any order
115
+ const renderToolCalls = useSyncExternalStore(
116
+ (callback) => {
117
+ return copilotkit.subscribe({
118
+ onRenderToolCallsChanged: callback,
119
+ }).unsubscribe;
120
+ },
121
+ () => copilotkit.renderToolCalls,
122
+ () => copilotkit.renderToolCalls,
123
+ );
124
+
125
+ // Note: executingToolCallIds is now provided by CopilotKitProvider context.
126
+ // This is critical for HITL reconnection: when connecting to a thread with
127
+ // pending tool calls, the onToolExecutionStart event fires before child components
128
+ // mount. By tracking at the provider level, the executing state is already
129
+ // available when this hook first runs.
130
+
131
+ const renderToolCall = useCallback(
132
+ ({
133
+ toolCall,
134
+ toolMessage,
135
+ }: UseRenderToolCallProps): React.ReactElement | null => {
136
+ // Find the render config for this tool call by name
137
+ // For rendering, we show all tool calls regardless of agentId
138
+ // The agentId scoping only affects handler execution (in core)
139
+ // Priority order:
140
+ // 1. Exact match by name (prefer agent-specific if multiple exist)
141
+ // 2. Wildcard (*) renderer
142
+ const exactMatches = renderToolCalls.filter(
143
+ (rc) => rc.name === toolCall.function.name,
144
+ );
145
+
146
+ // If multiple renderers with same name exist, prefer the one matching our agentId
147
+ const renderConfig =
148
+ exactMatches.find((rc) => rc.agentId === agentId) ||
149
+ exactMatches.find((rc) => !rc.agentId) ||
150
+ exactMatches[0] ||
151
+ renderToolCalls.find((rc) => rc.name === "*");
152
+
153
+ if (!renderConfig) {
154
+ return null;
155
+ }
156
+
157
+ const RenderComponent = renderConfig.render;
158
+ const isExecuting = executingToolCallIds.has(toolCall.id);
159
+
160
+ // Use the memoized ToolCallRenderer component to prevent unnecessary re-renders
161
+ return (
162
+ <ToolCallRenderer
163
+ key={toolCall.id}
164
+ toolCall={toolCall}
165
+ toolMessage={toolMessage}
166
+ RenderComponent={RenderComponent}
167
+ isExecuting={isExecuting}
168
+ />
169
+ );
170
+ },
171
+ [renderToolCalls, executingToolCallIds, agentId],
172
+ );
173
+
174
+ return renderToolCall;
175
+ }
@@ -0,0 +1,181 @@
1
+ import { useEffect } from "react";
2
+ import type { StandardSchemaV1, InferSchemaOutput } from "@copilotkit/shared";
3
+ import { useCopilotKit } from "../providers/CopilotKitProvider";
4
+ import { defineToolCallRenderer } from "../types/defineToolCallRenderer";
5
+
6
+ const EMPTY_DEPS: ReadonlyArray<unknown> = [];
7
+
8
+ export interface RenderToolInProgressProps<S extends StandardSchemaV1> {
9
+ name: string;
10
+ parameters: Partial<InferSchemaOutput<S>>;
11
+ status: "inProgress";
12
+ result: undefined;
13
+ }
14
+
15
+ export interface RenderToolExecutingProps<S extends StandardSchemaV1> {
16
+ name: string;
17
+ parameters: InferSchemaOutput<S>;
18
+ status: "executing";
19
+ result: undefined;
20
+ }
21
+
22
+ export interface RenderToolCompleteProps<S extends StandardSchemaV1> {
23
+ name: string;
24
+ parameters: InferSchemaOutput<S>;
25
+ status: "complete";
26
+ result: string;
27
+ }
28
+
29
+ export type RenderToolProps<S extends StandardSchemaV1> =
30
+ | RenderToolInProgressProps<S>
31
+ | RenderToolExecutingProps<S>
32
+ | RenderToolCompleteProps<S>;
33
+
34
+ type RenderToolConfig<S extends StandardSchemaV1> = {
35
+ name: string;
36
+ parameters?: S;
37
+ render: (props: RenderToolProps<S>) => React.ReactElement;
38
+ agentId?: string;
39
+ };
40
+
41
+ /**
42
+ * Registers a wildcard (`"*"`) renderer for tool calls.
43
+ *
44
+ * The wildcard renderer is used as a fallback when no exact name-matched
45
+ * renderer is registered for a tool call.
46
+ *
47
+ * @param config - Wildcard renderer configuration.
48
+ * @param deps - Optional dependencies to refresh registration.
49
+ *
50
+ * @example
51
+ * ```tsx
52
+ * useRenderTool(
53
+ * {
54
+ * name: "*",
55
+ * render: ({ name, status }) => (
56
+ * <div>
57
+ * {status === "complete" ? "✓" : "⏳"} {name}
58
+ * </div>
59
+ * ),
60
+ * },
61
+ * [],
62
+ * );
63
+ * ```
64
+ */
65
+ export function useRenderTool(
66
+ config: {
67
+ name: "*";
68
+ render: (props: any) => React.ReactElement;
69
+ agentId?: string;
70
+ },
71
+ deps?: ReadonlyArray<unknown>,
72
+ ): void;
73
+
74
+ /**
75
+ * Registers a name-scoped renderer for tool calls.
76
+ *
77
+ * The provided `parameters` schema defines the typed shape of `props.parameters`
78
+ * in `render` for `executing` and `complete` states. Accepts any Standard Schema V1
79
+ * compatible library (Zod, Valibot, ArkType, etc.).
80
+ *
81
+ * @typeParam S - Schema type describing tool call parameters.
82
+ * @param config - Named renderer configuration.
83
+ * @param deps - Optional dependencies to refresh registration.
84
+ *
85
+ * @example
86
+ * ```tsx
87
+ * useRenderTool(
88
+ * {
89
+ * name: "searchDocs",
90
+ * parameters: z.object({ query: z.string() }),
91
+ * render: ({ status, parameters, result }) => {
92
+ * if (status === "inProgress") return <div>Preparing...</div>;
93
+ * if (status === "executing") return <div>Searching {parameters.query}</div>;
94
+ * return <div>{result}</div>;
95
+ * },
96
+ * },
97
+ * [],
98
+ * );
99
+ * ```
100
+ */
101
+ export function useRenderTool<S extends StandardSchemaV1>(
102
+ config: {
103
+ name: string;
104
+ parameters: S;
105
+ render: (props: RenderToolProps<S>) => React.ReactElement;
106
+ agentId?: string;
107
+ },
108
+ deps?: ReadonlyArray<unknown>,
109
+ ): void;
110
+
111
+ /**
112
+ * Registers a renderer entry in CopilotKit's `renderToolCalls` registry.
113
+ *
114
+ * Key behavior:
115
+ * - deduplicates by `agentId:name` (latest registration wins),
116
+ * - keeps renderer entries on cleanup so historical chat tool calls can still render,
117
+ * - refreshes registration when `deps` change.
118
+ *
119
+ * @typeParam S - Schema type describing tool call parameters.
120
+ * @param config - Renderer config for wildcard or named tools.
121
+ * @param deps - Optional dependencies to refresh registration.
122
+ *
123
+ * @example
124
+ * ```tsx
125
+ * useRenderTool(
126
+ * {
127
+ * name: "searchDocs",
128
+ * parameters: z.object({ query: z.string() }),
129
+ * render: ({ status, parameters, result }) => {
130
+ * if (status === "executing") return <div>Searching {parameters.query}</div>;
131
+ * if (status === "complete") return <div>{result}</div>;
132
+ * return <div>Preparing...</div>;
133
+ * },
134
+ * },
135
+ * [],
136
+ * );
137
+ * ```
138
+ *
139
+ * @example
140
+ * ```tsx
141
+ * useRenderTool(
142
+ * {
143
+ * name: "summarize",
144
+ * parameters: z.object({ text: z.string() }),
145
+ * agentId: "research-agent",
146
+ * render: ({ name, status }) => <div>{name}: {status}</div>,
147
+ * },
148
+ * [selectedAgentId],
149
+ * );
150
+ * ```
151
+ */
152
+ export function useRenderTool<S extends StandardSchemaV1>(
153
+ config: RenderToolConfig<S>,
154
+ deps?: ReadonlyArray<unknown>,
155
+ ): void {
156
+ const { copilotkit } = useCopilotKit();
157
+ const extraDeps = deps ?? EMPTY_DEPS;
158
+
159
+ useEffect(() => {
160
+ // Build the ReactToolCallRenderer via defineToolCallRenderer
161
+ const renderer =
162
+ config.name === "*" && !config.parameters
163
+ ? defineToolCallRenderer({
164
+ name: "*",
165
+ render: (props) =>
166
+ config.render({ ...props, parameters: props.args }),
167
+ ...(config.agentId ? { agentId: config.agentId } : {}),
168
+ })
169
+ : defineToolCallRenderer({
170
+ name: config.name,
171
+ args: config.parameters!,
172
+ render: (props) =>
173
+ config.render({ ...props, parameters: props.args }),
174
+ ...(config.agentId ? { agentId: config.agentId } : {}),
175
+ });
176
+
177
+ copilotkit.addHookRenderToolCall(renderer);
178
+
179
+ // No cleanup removal — keeps renderer for chat history, same as useFrontendTool
180
+ }, [config.name, copilotkit, extraDeps.length, ...extraDeps]);
181
+ }
@@ -0,0 +1,91 @@
1
+ import { useCallback, useEffect, useMemo, useState } from "react";
2
+ import { Suggestion } from "@copilotkit/core";
3
+ import { useCopilotKit } from "../providers/CopilotKitProvider";
4
+ import { useCopilotChatConfiguration } from "../providers/CopilotChatConfigurationProvider";
5
+ import { DEFAULT_AGENT_ID } from "@copilotkit/shared";
6
+
7
+ export interface UseSuggestionsOptions {
8
+ agentId?: string;
9
+ }
10
+
11
+ export interface UseSuggestionsResult {
12
+ suggestions: Suggestion[];
13
+ reloadSuggestions: () => void;
14
+ clearSuggestions: () => void;
15
+ isLoading: boolean;
16
+ }
17
+
18
+ export function useSuggestions({
19
+ agentId,
20
+ }: UseSuggestionsOptions = {}): UseSuggestionsResult {
21
+ const { copilotkit } = useCopilotKit();
22
+ const config = useCopilotChatConfiguration();
23
+ const resolvedAgentId = useMemo(
24
+ () => agentId ?? config?.agentId ?? DEFAULT_AGENT_ID,
25
+ [agentId, config?.agentId],
26
+ );
27
+
28
+ const [suggestions, setSuggestions] = useState<Suggestion[]>(() => {
29
+ const result = copilotkit.getSuggestions(resolvedAgentId);
30
+ return result.suggestions;
31
+ });
32
+ const [isLoading, setIsLoading] = useState(() => {
33
+ const result = copilotkit.getSuggestions(resolvedAgentId);
34
+ return result.isLoading;
35
+ });
36
+
37
+ useEffect(() => {
38
+ const result = copilotkit.getSuggestions(resolvedAgentId);
39
+ setSuggestions(result.suggestions);
40
+ setIsLoading(result.isLoading);
41
+ }, [copilotkit, resolvedAgentId]);
42
+
43
+ useEffect(() => {
44
+ const subscription = copilotkit.subscribe({
45
+ onSuggestionsChanged: ({ agentId: changedAgentId, suggestions }) => {
46
+ if (changedAgentId !== resolvedAgentId) {
47
+ return;
48
+ }
49
+ setSuggestions(suggestions);
50
+ },
51
+ onSuggestionsStartedLoading: ({ agentId: changedAgentId }) => {
52
+ if (changedAgentId !== resolvedAgentId) {
53
+ return;
54
+ }
55
+ setIsLoading(true);
56
+ },
57
+ onSuggestionsFinishedLoading: ({ agentId: changedAgentId }) => {
58
+ if (changedAgentId !== resolvedAgentId) {
59
+ return;
60
+ }
61
+ setIsLoading(false);
62
+ },
63
+ onSuggestionsConfigChanged: () => {
64
+ const result = copilotkit.getSuggestions(resolvedAgentId);
65
+ setSuggestions(result.suggestions);
66
+ setIsLoading(result.isLoading);
67
+ },
68
+ });
69
+
70
+ return () => {
71
+ subscription.unsubscribe();
72
+ };
73
+ }, [copilotkit, resolvedAgentId]);
74
+
75
+ const reloadSuggestions = useCallback(() => {
76
+ copilotkit.reloadSuggestions(resolvedAgentId);
77
+ // Loading state is handled by onSuggestionsStartedLoading event
78
+ }, [copilotkit, resolvedAgentId]);
79
+
80
+ const clearSuggestions = useCallback(() => {
81
+ copilotkit.clearSuggestions(resolvedAgentId);
82
+ // State updates are handled by onSuggestionsChanged event
83
+ }, [copilotkit, resolvedAgentId]);
84
+
85
+ return {
86
+ suggestions,
87
+ reloadSuggestions,
88
+ clearSuggestions,
89
+ isLoading,
90
+ };
91
+ }