@copilotkit/react-core 1.54.1 → 1.55.0-next.7

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 (183) hide show
  1. package/CHANGELOG.md +117 -116
  2. package/dist/copilotkit-B3Mb1yVE.cjs +7975 -0
  3. package/dist/copilotkit-B3Mb1yVE.cjs.map +1 -0
  4. package/dist/copilotkit-DBzgOMby.d.cts +2182 -0
  5. package/dist/copilotkit-DBzgOMby.d.cts.map +1 -0
  6. package/dist/copilotkit-DNYSFuz5.mjs +7562 -0
  7. package/dist/copilotkit-DNYSFuz5.mjs.map +1 -0
  8. package/dist/copilotkit-Dy5w3qEV.d.mts +2182 -0
  9. package/dist/copilotkit-Dy5w3qEV.d.mts.map +1 -0
  10. package/dist/index.cjs +27 -28
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +3 -3
  13. package/dist/index.d.cts.map +1 -1
  14. package/dist/index.d.mts +3 -3
  15. package/dist/index.d.mts.map +1 -1
  16. package/dist/index.mjs +4 -5
  17. package/dist/index.mjs.map +1 -1
  18. package/dist/index.umd.js +1941 -35
  19. package/dist/index.umd.js.map +1 -1
  20. package/dist/v2/index.cjs +77 -7
  21. package/dist/v2/index.css +1 -2
  22. package/dist/v2/index.d.cts +6 -4
  23. package/dist/v2/index.d.mts +6 -4
  24. package/dist/v2/index.mjs +7 -4
  25. package/dist/v2/index.umd.js +5725 -24
  26. package/dist/v2/index.umd.js.map +1 -1
  27. package/package.json +37 -9
  28. package/scripts/scope-preflight.mjs +101 -0
  29. package/src/components/CopilotListeners.tsx +2 -6
  30. package/src/components/copilot-provider/copilot-messages.tsx +1 -1
  31. package/src/components/copilot-provider/copilotkit-props.tsx +1 -1
  32. package/src/components/copilot-provider/copilotkit.tsx +4 -4
  33. package/src/context/copilot-messages-context.tsx +1 -1
  34. package/src/hooks/__tests__/use-coagent-config.test.ts +2 -2
  35. package/src/hooks/__tests__/use-coagent-state-render.e2e.test.tsx +2 -2
  36. package/src/hooks/__tests__/use-copilot-chat-internal-connect.test.tsx +3 -7
  37. package/src/hooks/__tests__/use-frontend-tool-available.test.tsx +1 -1
  38. package/src/hooks/__tests__/use-frontend-tool-remount.e2e.test.tsx +4 -4
  39. package/src/hooks/use-agent-nodename.ts +1 -1
  40. package/src/hooks/use-coagent-state-render-bridge.tsx +1 -4
  41. package/src/hooks/use-coagent.ts +1 -1
  42. package/src/hooks/use-configure-chat-suggestions.tsx +2 -2
  43. package/src/hooks/use-copilot-chat-suggestions.tsx +2 -2
  44. package/src/hooks/use-copilot-chat_internal.ts +2 -2
  45. package/src/hooks/use-copilot-readable.ts +1 -1
  46. package/src/hooks/use-frontend-tool.ts +2 -2
  47. package/src/hooks/use-human-in-the-loop.ts +2 -2
  48. package/src/hooks/use-langgraph-interrupt.ts +2 -5
  49. package/src/hooks/use-lazy-tool-renderer.tsx +1 -1
  50. package/src/hooks/use-render-tool-call.ts +1 -1
  51. package/src/lib/copilot-task.ts +1 -1
  52. package/src/setupTests.ts +18 -14
  53. package/src/v2/__tests__/A2UIMessageRenderer.test.tsx +176 -0
  54. package/src/v2/__tests__/globalSetup.ts +14 -0
  55. package/src/v2/__tests__/setup.ts +93 -0
  56. package/src/v2/__tests__/utils/test-helpers.tsx +470 -0
  57. package/src/v2/a2ui/A2UIMessageRenderer.tsx +206 -0
  58. package/src/v2/components/CopilotKitInspector.tsx +50 -0
  59. package/src/v2/components/MCPAppsActivityRenderer.tsx +785 -0
  60. package/src/v2/components/WildcardToolCallRender.tsx +86 -0
  61. package/src/v2/components/__tests__/license-warning-banner.test.tsx +46 -0
  62. package/src/v2/components/chat/CopilotChat.tsx +431 -0
  63. package/src/v2/components/chat/CopilotChatAssistantMessage.tsx +375 -0
  64. package/src/v2/components/chat/CopilotChatAudioRecorder.tsx +350 -0
  65. package/src/v2/components/chat/CopilotChatInput.tsx +1302 -0
  66. package/src/v2/components/chat/CopilotChatMessageView.tsx +556 -0
  67. package/src/v2/components/chat/CopilotChatReasoningMessage.tsx +252 -0
  68. package/src/v2/components/chat/CopilotChatSuggestionPill.tsx +59 -0
  69. package/src/v2/components/chat/CopilotChatSuggestionView.tsx +133 -0
  70. package/src/v2/components/chat/CopilotChatToggleButton.tsx +171 -0
  71. package/src/v2/components/chat/CopilotChatToolCallsView.tsx +40 -0
  72. package/src/v2/components/chat/CopilotChatUserMessage.tsx +388 -0
  73. package/src/v2/components/chat/CopilotChatView.tsx +598 -0
  74. package/src/v2/components/chat/CopilotModalHeader.tsx +129 -0
  75. package/src/v2/components/chat/CopilotPopup.tsx +81 -0
  76. package/src/v2/components/chat/CopilotPopupView.tsx +317 -0
  77. package/src/v2/components/chat/CopilotSidebar.tsx +76 -0
  78. package/src/v2/components/chat/CopilotSidebarView.tsx +255 -0
  79. package/src/v2/components/chat/__tests__/CopilotChat.e2e.test.tsx +1113 -0
  80. package/src/v2/components/chat/__tests__/CopilotChat.onError.test.tsx +73 -0
  81. package/src/v2/components/chat/__tests__/CopilotChat.slots.e2e.test.tsx +432 -0
  82. package/src/v2/components/chat/__tests__/CopilotChatActivityRendering.e2e.test.tsx +150 -0
  83. package/src/v2/components/chat/__tests__/CopilotChatAssistantMessage.slots.e2e.test.tsx +624 -0
  84. package/src/v2/components/chat/__tests__/CopilotChatAssistantMessage.test.tsx +702 -0
  85. package/src/v2/components/chat/__tests__/CopilotChatCssClasses.test.tsx +107 -0
  86. package/src/v2/components/chat/__tests__/CopilotChatInput.slots.e2e.test.tsx +929 -0
  87. package/src/v2/components/chat/__tests__/CopilotChatInput.test.tsx +986 -0
  88. package/src/v2/components/chat/__tests__/CopilotChatMessageView.slots.e2e.test.tsx +1004 -0
  89. package/src/v2/components/chat/__tests__/CopilotChatMessageView.test.tsx +169 -0
  90. package/src/v2/components/chat/__tests__/CopilotChatSuggestionView.slots.e2e.test.tsx +530 -0
  91. package/src/v2/components/chat/__tests__/CopilotChatToolRendering.e2e.test.tsx +782 -0
  92. package/src/v2/components/chat/__tests__/CopilotChatToolRerenders.e2e.test.tsx +2413 -0
  93. package/src/v2/components/chat/__tests__/CopilotChatUserMessage.slots.e2e.test.tsx +621 -0
  94. package/src/v2/components/chat/__tests__/CopilotChatView.onClick.e2e.test.tsx +853 -0
  95. package/src/v2/components/chat/__tests__/CopilotChatView.slots.e2e.test.tsx +1050 -0
  96. package/src/v2/components/chat/__tests__/CopilotModalHeader.slots.e2e.test.tsx +484 -0
  97. package/src/v2/components/chat/__tests__/CopilotPopupView.slots.e2e.test.tsx +612 -0
  98. package/src/v2/components/chat/__tests__/CopilotSidebarView.slots.e2e.test.tsx +502 -0
  99. package/src/v2/components/chat/__tests__/MCPAppsActivityRenderer.e2e.test.tsx +1011 -0
  100. package/src/v2/components/chat/__tests__/setup.ts +1 -0
  101. package/src/v2/components/chat/index.ts +79 -0
  102. package/src/v2/components/index.ts +7 -0
  103. package/src/v2/components/license-warning-banner.tsx +198 -0
  104. package/src/v2/components/ui/button.tsx +123 -0
  105. package/src/v2/components/ui/dropdown-menu.tsx +258 -0
  106. package/src/v2/components/ui/tooltip.tsx +60 -0
  107. package/src/v2/hooks/__tests__/standard-schema-types.test.tsx +152 -0
  108. package/src/v2/hooks/__tests__/standard-schema.test.tsx +282 -0
  109. package/src/v2/hooks/__tests__/use-agent-context-timing.e2e.test.tsx +132 -0
  110. package/src/v2/hooks/__tests__/use-agent-context.test.tsx +401 -0
  111. package/src/v2/hooks/__tests__/use-agent-error-state.test.tsx +44 -0
  112. package/src/v2/hooks/__tests__/use-agent-stability.test.tsx +205 -0
  113. package/src/v2/hooks/__tests__/use-agent.e2e.test.tsx +148 -0
  114. package/src/v2/hooks/__tests__/use-component.test.tsx +123 -0
  115. package/src/v2/hooks/__tests__/use-configure-suggestions.e2e.test.tsx +696 -0
  116. package/src/v2/hooks/__tests__/use-default-render-tool.test.tsx +153 -0
  117. package/src/v2/hooks/__tests__/use-frontend-tool-available.test.tsx +167 -0
  118. package/src/v2/hooks/__tests__/use-frontend-tool.e2e.test.tsx +2129 -0
  119. package/src/v2/hooks/__tests__/use-human-in-the-loop.e2e.test.tsx +1261 -0
  120. package/src/v2/hooks/__tests__/use-interrupt.test.tsx +397 -0
  121. package/src/v2/hooks/__tests__/use-katex-styles.test.tsx +56 -0
  122. package/src/v2/hooks/__tests__/use-keyboard-height.test.tsx +192 -0
  123. package/src/v2/hooks/__tests__/use-render-tool.test.tsx +259 -0
  124. package/src/v2/hooks/__tests__/use-suggestions.e2e.test.tsx +524 -0
  125. package/src/v2/hooks/__tests__/use-threads.test.tsx +433 -0
  126. package/src/v2/hooks/__tests__/zod-regression.test.tsx +311 -0
  127. package/src/v2/hooks/index.ts +18 -0
  128. package/src/v2/hooks/use-agent-context.tsx +45 -0
  129. package/src/v2/hooks/use-agent.tsx +155 -0
  130. package/src/v2/hooks/use-component.tsx +89 -0
  131. package/src/v2/hooks/use-configure-suggestions.tsx +187 -0
  132. package/src/v2/hooks/use-default-render-tool.tsx +254 -0
  133. package/src/v2/hooks/use-frontend-tool.tsx +43 -0
  134. package/src/v2/hooks/use-human-in-the-loop.tsx +81 -0
  135. package/src/v2/hooks/use-interrupt.tsx +305 -0
  136. package/src/v2/hooks/use-keyboard-height.tsx +67 -0
  137. package/src/v2/hooks/use-render-activity-message.tsx +73 -0
  138. package/src/v2/hooks/use-render-custom-messages.tsx +93 -0
  139. package/src/v2/hooks/use-render-tool-call.tsx +175 -0
  140. package/src/v2/hooks/use-render-tool.tsx +181 -0
  141. package/src/v2/hooks/use-suggestions.tsx +91 -0
  142. package/src/v2/hooks/use-threads.tsx +256 -0
  143. package/src/v2/hooks/useKatexStyles.ts +27 -0
  144. package/src/v2/index.css +1 -1
  145. package/src/v2/index.ts +18 -2
  146. package/src/v2/lib/__tests__/completePartialMarkdown.test.ts +495 -0
  147. package/src/v2/lib/__tests__/renderSlot.test.tsx +588 -0
  148. package/src/v2/lib/react-core.ts +156 -0
  149. package/src/v2/lib/slots.tsx +143 -0
  150. package/src/v2/lib/transcription-client.ts +184 -0
  151. package/src/v2/lib/utils.ts +8 -0
  152. package/src/v2/providers/CopilotChatConfigurationProvider.tsx +162 -0
  153. package/src/v2/providers/CopilotKitProvider.tsx +600 -0
  154. package/src/v2/providers/__tests__/CopilotChatConfigurationProvider.test.tsx +546 -0
  155. package/src/v2/providers/__tests__/CopilotKitProvider.license.test.tsx +101 -0
  156. package/src/v2/providers/__tests__/CopilotKitProvider.onError.test.tsx +69 -0
  157. package/src/v2/providers/__tests__/CopilotKitProvider.renderCustomMessages.e2e.test.tsx +881 -0
  158. package/src/v2/providers/__tests__/CopilotKitProvider.stability.test.tsx +740 -0
  159. package/src/v2/providers/__tests__/CopilotKitProvider.test.tsx +642 -0
  160. package/src/v2/providers/__tests__/CopilotKitProvider.wildcard.test.tsx +294 -0
  161. package/src/v2/providers/index.ts +14 -0
  162. package/src/v2/styles/globals.css +230 -0
  163. package/src/v2/types/__tests__/defineToolCallRenderer.test.tsx +525 -0
  164. package/src/v2/types/defineToolCallRenderer.ts +65 -0
  165. package/src/v2/types/frontend-tool.ts +8 -0
  166. package/src/v2/types/human-in-the-loop.ts +33 -0
  167. package/src/v2/types/index.ts +7 -0
  168. package/src/v2/types/interrupt.ts +15 -0
  169. package/src/v2/types/react-activity-message-renderer.ts +27 -0
  170. package/src/v2/types/react-custom-message-renderer.ts +17 -0
  171. package/src/v2/types/react-tool-call-renderer.ts +32 -0
  172. package/tsdown.config.ts +34 -10
  173. package/vitest.config.mjs +4 -3
  174. package/LICENSE +0 -21
  175. package/dist/copilotkit-BRPQ2sqS.d.cts +0 -670
  176. package/dist/copilotkit-BRPQ2sqS.d.cts.map +0 -1
  177. package/dist/copilotkit-C94ayZbs.cjs +0 -2161
  178. package/dist/copilotkit-C94ayZbs.cjs.map +0 -1
  179. package/dist/copilotkit-CwZMFmSK.d.mts +0 -670
  180. package/dist/copilotkit-CwZMFmSK.d.mts.map +0 -1
  181. package/dist/copilotkit-Yh_Ld_FX.mjs +0 -2031
  182. package/dist/copilotkit-Yh_Ld_FX.mjs.map +0 -1
  183. package/dist/v2/index.css.map +0 -1
@@ -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
+ }
@@ -0,0 +1,256 @@
1
+ import { useCopilotKit } from "../providers/CopilotKitProvider";
2
+ import {
3
+ ɵcreateThreadStore,
4
+ ɵselectThreads,
5
+ ɵselectThreadsError,
6
+ ɵselectThreadsIsLoading,
7
+ ɵselectHasNextPage,
8
+ ɵselectIsFetchingNextPage,
9
+ type ɵThread as CoreThread,
10
+ type ɵThreadRuntimeContext,
11
+ type ɵThreadStore,
12
+ } from "@copilotkit/core";
13
+ import {
14
+ useCallback,
15
+ useEffect,
16
+ useMemo,
17
+ useState,
18
+ useSyncExternalStore,
19
+ } from "react";
20
+
21
+ /**
22
+ * A conversation thread managed by the Intelligence platform.
23
+ *
24
+ * Each thread has a unique `id`, an optional human-readable `name`, and
25
+ * timestamp fields tracking creation and update times.
26
+ */
27
+ export interface Thread extends CoreThread {}
28
+
29
+ /**
30
+ * Configuration for the {@link useThreads} hook.
31
+ *
32
+ * Thread operations are scoped to the runtime-authenticated user and the
33
+ * provided agent on the Intelligence platform.
34
+ */
35
+ export interface UseThreadsInput {
36
+ /** The ID of the agent whose threads to list and manage. */
37
+ agentId: string;
38
+ /** When `true`, archived threads are included in the list. Defaults to `false`. */
39
+ includeArchived?: boolean;
40
+ /** Maximum number of threads to fetch per page. When set, enables cursor-based pagination. */
41
+ limit?: number;
42
+ }
43
+
44
+ /**
45
+ * Return value of the {@link useThreads} hook.
46
+ *
47
+ * The `threads` array is kept in sync with the platform via a realtime
48
+ * WebSocket subscription (when available) and is sorted most-recently-updated
49
+ * first. Mutations reject with an `Error` if the platform request fails.
50
+ */
51
+ export interface UseThreadsResult {
52
+ /**
53
+ * Threads for the current user/agent pair, sorted by most recently
54
+ * updated first. Updated in realtime when the platform pushes metadata
55
+ * events. Includes archived threads only when `includeArchived` is set.
56
+ */
57
+ threads: Thread[];
58
+ /**
59
+ * `true` while the initial thread list is being fetched from the platform.
60
+ * Subsequent realtime updates do not re-enter the loading state.
61
+ */
62
+ isLoading: boolean;
63
+ /**
64
+ * The most recent error from fetching threads or executing a mutation,
65
+ * or `null` when there is no error. Reset to `null` on the next
66
+ * successful fetch.
67
+ */
68
+ error: Error | null;
69
+ /**
70
+ * `true` when there are more threads available to fetch via
71
+ * {@link fetchNextPage}. Only meaningful when `limit` is set.
72
+ */
73
+ hasNextPage: boolean;
74
+ /**
75
+ * `true` while a subsequent page of threads is being fetched.
76
+ */
77
+ isFetchingNextPage: boolean;
78
+ /**
79
+ * Fetch the next page of threads. No-op when {@link hasNextPage} is
80
+ * `false` or a page fetch is already in progress.
81
+ */
82
+ fetchNextPage: () => void;
83
+ /**
84
+ * Rename a thread on the platform.
85
+ * Resolves when the server confirms the update; rejects on failure.
86
+ */
87
+ renameThread: (threadId: string, name: string) => Promise<void>;
88
+ /**
89
+ * Archive a thread on the platform.
90
+ * Archived threads are excluded from subsequent list results.
91
+ * Resolves when the server confirms the update; rejects on failure.
92
+ */
93
+ archiveThread: (threadId: string) => Promise<void>;
94
+ /**
95
+ * Permanently delete a thread from the platform.
96
+ * This is irreversible. Resolves when the server confirms deletion;
97
+ * rejects on failure.
98
+ */
99
+ deleteThread: (threadId: string) => Promise<void>;
100
+ }
101
+
102
+ function useThreadStoreSelector<T>(
103
+ store: ɵThreadStore,
104
+ selector: (state: ReturnType<ɵThreadStore["getState"]>) => T,
105
+ ): T {
106
+ return useSyncExternalStore(
107
+ useCallback(
108
+ (onStoreChange) => {
109
+ const subscription = store.select(selector).subscribe(onStoreChange);
110
+ return () => subscription.unsubscribe();
111
+ },
112
+ [store, selector],
113
+ ),
114
+ () => selector(store.getState()),
115
+ );
116
+ }
117
+
118
+ /**
119
+ * React hook for listing and managing Intelligence platform threads.
120
+ *
121
+ * On mount the hook fetches the thread list for the runtime-authenticated user
122
+ * and the given `agentId`. When the Intelligence platform exposes a WebSocket
123
+ * URL, it also opens a realtime subscription so the `threads` array stays
124
+ * current without polling — thread creates, renames, archives, and deletes
125
+ * from any client are reflected immediately.
126
+ *
127
+ * Mutation methods (`renameThread`, `archiveThread`, `deleteThread`) return
128
+ * promises that resolve once the platform confirms the operation and reject
129
+ * with an `Error` on failure.
130
+ *
131
+ * @param input - Agent identifier and optional list controls.
132
+ * @returns Thread list state and stable mutation callbacks.
133
+ *
134
+ * @example
135
+ * ```tsx
136
+ * import { useThreads } from "@copilotkit/react-core";
137
+ *
138
+ * function ThreadList() {
139
+ * const { threads, isLoading, renameThread, deleteThread } = useThreads({
140
+ * agentId: "agent-1",
141
+ * });
142
+ *
143
+ * if (isLoading) return <p>Loading…</p>;
144
+ *
145
+ * return (
146
+ * <ul>
147
+ * {threads.map((t) => (
148
+ * <li key={t.id}>
149
+ * {t.name ?? "Untitled"}
150
+ * <button onClick={() => renameThread(t.id, "New name")}>Rename</button>
151
+ * <button onClick={() => deleteThread(t.id)}>Delete</button>
152
+ * </li>
153
+ * ))}
154
+ * </ul>
155
+ * );
156
+ * }
157
+ * ```
158
+ */
159
+ export function useThreads({
160
+ agentId,
161
+ includeArchived,
162
+ limit,
163
+ }: UseThreadsInput): UseThreadsResult {
164
+ const { copilotkit } = useCopilotKit();
165
+
166
+ const [store] = useState(() =>
167
+ ɵcreateThreadStore({
168
+ fetch: globalThis.fetch,
169
+ }),
170
+ );
171
+
172
+ const threads = useThreadStoreSelector(store, ɵselectThreads);
173
+ const storeIsLoading = useThreadStoreSelector(store, ɵselectThreadsIsLoading);
174
+ const storeError = useThreadStoreSelector(store, ɵselectThreadsError);
175
+ const hasNextPage = useThreadStoreSelector(store, ɵselectHasNextPage);
176
+ const isFetchingNextPage = useThreadStoreSelector(
177
+ store,
178
+ ɵselectIsFetchingNextPage,
179
+ );
180
+ const headersKey = useMemo(() => {
181
+ return JSON.stringify(
182
+ Object.entries(copilotkit.headers ?? {}).sort(([left], [right]) =>
183
+ left.localeCompare(right),
184
+ ),
185
+ );
186
+ }, [copilotkit.headers]);
187
+ const runtimeError = useMemo(() => {
188
+ if (copilotkit.runtimeUrl) {
189
+ return null;
190
+ }
191
+
192
+ return new Error("Runtime URL is not configured");
193
+ }, [copilotkit.runtimeUrl]);
194
+ const isLoading = runtimeError ? false : storeIsLoading;
195
+ const error = runtimeError ?? storeError;
196
+
197
+ useEffect(() => {
198
+ store.start();
199
+ return () => {
200
+ store.stop();
201
+ };
202
+ }, [store]);
203
+
204
+ useEffect(() => {
205
+ const context: ɵThreadRuntimeContext | null = copilotkit.runtimeUrl
206
+ ? {
207
+ runtimeUrl: copilotkit.runtimeUrl,
208
+ headers: { ...copilotkit.headers },
209
+ wsUrl: copilotkit.intelligence?.wsUrl,
210
+ agentId,
211
+ includeArchived,
212
+ limit,
213
+ }
214
+ : null;
215
+
216
+ store.setContext(context);
217
+ }, [
218
+ store,
219
+ copilotkit.runtimeUrl,
220
+ headersKey,
221
+ copilotkit.intelligence?.wsUrl,
222
+ agentId,
223
+ copilotkit.headers,
224
+ includeArchived,
225
+ limit,
226
+ ]);
227
+
228
+ const renameThread = useCallback(
229
+ (threadId: string, name: string) => store.renameThread(threadId, name),
230
+ [store],
231
+ );
232
+
233
+ const archiveThread = useCallback(
234
+ (threadId: string) => store.archiveThread(threadId),
235
+ [store],
236
+ );
237
+
238
+ const deleteThread = useCallback(
239
+ (threadId: string) => store.deleteThread(threadId),
240
+ [store],
241
+ );
242
+
243
+ const fetchNextPage = useCallback(() => store.fetchNextPage(), [store]);
244
+
245
+ return {
246
+ threads,
247
+ isLoading,
248
+ error,
249
+ hasNextPage,
250
+ isFetchingNextPage,
251
+ fetchNextPage,
252
+ renameThread,
253
+ archiveThread,
254
+ deleteThread,
255
+ };
256
+ }