@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,254 @@
1
+ import React, { useState } from "react";
2
+ import { useRenderTool } from "./use-render-tool";
3
+
4
+ type DefaultRenderProps = {
5
+ /** The name of the tool being called. */
6
+ name: string;
7
+ /** The parsed parameters passed to the tool call. */
8
+ parameters: unknown;
9
+ /** Current execution status of the tool call. */
10
+ status: "inProgress" | "executing" | "complete";
11
+ /** The tool call result string, available only when `status` is `"complete"`. */
12
+ result: string | undefined;
13
+ };
14
+
15
+ /**
16
+ * Registers a wildcard (`"*"`) tool-call renderer via `useRenderTool`.
17
+ *
18
+ * - Call with no config to use CopilotKit's built-in default tool-call card.
19
+ * - Pass `config.render` to replace the default UI with your own fallback renderer.
20
+ *
21
+ * This is useful when you want a generic renderer for tools that do not have a
22
+ * dedicated `useRenderTool({ name: "..." })` registration.
23
+ *
24
+ * @param config - Optional custom wildcard render function.
25
+ * @param deps - Optional dependencies to refresh registration.
26
+ *
27
+ * @example
28
+ * ```tsx
29
+ * useDefaultRenderTool();
30
+ * ```
31
+ *
32
+ * @example
33
+ * ```tsx
34
+ * useDefaultRenderTool({
35
+ * render: ({ name, status }) => <div>{name}: {status}</div>,
36
+ * });
37
+ * ```
38
+ *
39
+ * @example
40
+ * ```tsx
41
+ * useDefaultRenderTool(
42
+ * {
43
+ * render: ({ name, result }) => (
44
+ * <ToolEventRow title={name} payload={result} compact={compactMode} />
45
+ * ),
46
+ * },
47
+ * [compactMode],
48
+ * );
49
+ * ```
50
+ */
51
+ export function useDefaultRenderTool(
52
+ config?: {
53
+ render?: (props: DefaultRenderProps) => React.ReactElement;
54
+ },
55
+ deps?: ReadonlyArray<unknown>,
56
+ ): void {
57
+ useRenderTool(
58
+ {
59
+ name: "*",
60
+ render: config?.render ?? DefaultToolCallRenderer,
61
+ },
62
+ deps,
63
+ );
64
+ }
65
+
66
+ function DefaultToolCallRenderer({
67
+ name,
68
+ parameters,
69
+ status,
70
+ result,
71
+ }: DefaultRenderProps): React.ReactElement {
72
+ const [isExpanded, setIsExpanded] = useState(false);
73
+
74
+ const statusString = String(status) as
75
+ | "inProgress"
76
+ | "executing"
77
+ | "complete";
78
+ const isActive =
79
+ statusString === "inProgress" || statusString === "executing";
80
+ const isComplete = statusString === "complete";
81
+
82
+ const statusLabel = isActive ? "Running" : isComplete ? "Done" : status;
83
+ const dotColor = isActive ? "#f59e0b" : isComplete ? "#10b981" : "#a1a1aa";
84
+ const badgeBg = isActive ? "#fef3c7" : isComplete ? "#d1fae5" : "#f4f4f5";
85
+ const badgeColor = isActive ? "#92400e" : isComplete ? "#065f46" : "#3f3f46";
86
+
87
+ return (
88
+ <div
89
+ style={{
90
+ marginTop: "8px",
91
+ paddingBottom: "8px",
92
+ }}
93
+ >
94
+ <div
95
+ style={{
96
+ borderRadius: "12px",
97
+ border: "1px solid #e4e4e7",
98
+ backgroundColor: "#fafafa",
99
+ padding: "14px 16px",
100
+ }}
101
+ >
102
+ {/* Header row — always visible */}
103
+ <div
104
+ onClick={() => setIsExpanded(!isExpanded)}
105
+ style={{
106
+ display: "flex",
107
+ alignItems: "center",
108
+ justifyContent: "space-between",
109
+ gap: "10px",
110
+ cursor: "pointer",
111
+ userSelect: "none",
112
+ }}
113
+ >
114
+ <div
115
+ style={{
116
+ display: "flex",
117
+ alignItems: "center",
118
+ gap: "8px",
119
+ minWidth: 0,
120
+ }}
121
+ >
122
+ <svg
123
+ style={{
124
+ height: "14px",
125
+ width: "14px",
126
+ color: "#71717a",
127
+ transition: "transform 0.15s",
128
+ transform: isExpanded ? "rotate(90deg)" : "rotate(0deg)",
129
+ flexShrink: 0,
130
+ }}
131
+ fill="none"
132
+ viewBox="0 0 24 24"
133
+ strokeWidth={2}
134
+ stroke="currentColor"
135
+ >
136
+ <path
137
+ strokeLinecap="round"
138
+ strokeLinejoin="round"
139
+ d="M8.25 4.5l7.5 7.5-7.5 7.5"
140
+ />
141
+ </svg>
142
+ <span
143
+ style={{
144
+ display: "inline-block",
145
+ height: "8px",
146
+ width: "8px",
147
+ borderRadius: "50%",
148
+ backgroundColor: dotColor,
149
+ flexShrink: 0,
150
+ }}
151
+ />
152
+ <span
153
+ style={{
154
+ fontSize: "13px",
155
+ fontWeight: 600,
156
+ color: "#18181b",
157
+ overflow: "hidden",
158
+ textOverflow: "ellipsis",
159
+ whiteSpace: "nowrap",
160
+ }}
161
+ >
162
+ {name}
163
+ </span>
164
+ </div>
165
+
166
+ <span
167
+ style={{
168
+ display: "inline-flex",
169
+ alignItems: "center",
170
+ borderRadius: "9999px",
171
+ padding: "2px 8px",
172
+ fontSize: "11px",
173
+ fontWeight: 500,
174
+ backgroundColor: badgeBg,
175
+ color: badgeColor,
176
+ flexShrink: 0,
177
+ }}
178
+ >
179
+ {statusLabel}
180
+ </span>
181
+ </div>
182
+
183
+ {/* Expandable details */}
184
+ {isExpanded && (
185
+ <div style={{ marginTop: "12px", display: "grid", gap: "12px" }}>
186
+ <div>
187
+ <div
188
+ style={{
189
+ fontSize: "10px",
190
+ textTransform: "uppercase",
191
+ letterSpacing: "0.05em",
192
+ color: "#71717a",
193
+ }}
194
+ >
195
+ Arguments
196
+ </div>
197
+ <pre
198
+ style={{
199
+ marginTop: "6px",
200
+ maxHeight: "200px",
201
+ overflow: "auto",
202
+ borderRadius: "6px",
203
+ backgroundColor: "#f4f4f5",
204
+ padding: "10px",
205
+ fontSize: "11px",
206
+ lineHeight: 1.6,
207
+ color: "#27272a",
208
+ whiteSpace: "pre-wrap",
209
+ wordBreak: "break-word",
210
+ }}
211
+ >
212
+ {JSON.stringify(parameters ?? {}, null, 2)}
213
+ </pre>
214
+ </div>
215
+
216
+ {result !== undefined && (
217
+ <div>
218
+ <div
219
+ style={{
220
+ fontSize: "10px",
221
+ textTransform: "uppercase",
222
+ letterSpacing: "0.05em",
223
+ color: "#71717a",
224
+ }}
225
+ >
226
+ Result
227
+ </div>
228
+ <pre
229
+ style={{
230
+ marginTop: "6px",
231
+ maxHeight: "200px",
232
+ overflow: "auto",
233
+ borderRadius: "6px",
234
+ backgroundColor: "#f4f4f5",
235
+ padding: "10px",
236
+ fontSize: "11px",
237
+ lineHeight: 1.6,
238
+ color: "#27272a",
239
+ whiteSpace: "pre-wrap",
240
+ wordBreak: "break-word",
241
+ }}
242
+ >
243
+ {typeof result === "string"
244
+ ? result
245
+ : JSON.stringify(result, null, 2)}
246
+ </pre>
247
+ </div>
248
+ )}
249
+ </div>
250
+ )}
251
+ </div>
252
+ </div>
253
+ );
254
+ }
@@ -0,0 +1,43 @@
1
+ import { useEffect } from "react";
2
+ import { useCopilotKit } from "../providers/CopilotKitProvider";
3
+ import type { ReactFrontendTool } from "../types/frontend-tool";
4
+
5
+ const EMPTY_DEPS: ReadonlyArray<unknown> = [];
6
+
7
+ export function useFrontendTool<
8
+ T extends Record<string, unknown> = Record<string, unknown>,
9
+ >(tool: ReactFrontendTool<T>, deps?: ReadonlyArray<unknown>) {
10
+ const { copilotkit } = useCopilotKit();
11
+ const extraDeps = deps ?? EMPTY_DEPS;
12
+
13
+ useEffect(() => {
14
+ const name = tool.name;
15
+
16
+ // Always register/override the tool for this name on mount
17
+ if (copilotkit.getTool({ toolName: name, agentId: tool.agentId })) {
18
+ console.warn(
19
+ `Tool '${name}' already exists for agent '${tool.agentId || "global"}'. Overriding with latest registration.`,
20
+ );
21
+ copilotkit.removeTool(name, tool.agentId);
22
+ }
23
+ copilotkit.addTool(tool);
24
+
25
+ // Register/override renderer by name and agentId through core
26
+ if (tool.render && tool.parameters) {
27
+ copilotkit.addHookRenderToolCall({
28
+ name,
29
+ args: tool.parameters,
30
+ agentId: tool.agentId,
31
+ render: tool.render,
32
+ });
33
+ }
34
+
35
+ return () => {
36
+ copilotkit.removeTool(name, tool.agentId);
37
+ // we are intentionally not removing the render here so that the tools can still render in the chat history
38
+ };
39
+ // Depend on stable keys by default and allow callers to opt into
40
+ // additional dependencies for dynamic tool configuration.
41
+ // tool.available is included so toggling availability re-registers the tool.
42
+ }, [tool.name, tool.available, copilotkit, extraDeps.length, ...extraDeps]);
43
+ }
@@ -0,0 +1,81 @@
1
+ import { useCopilotKit } from "../providers/CopilotKitProvider";
2
+ import type { ReactFrontendTool } from "../types/frontend-tool";
3
+ import type { ReactHumanInTheLoop } from "../types/human-in-the-loop";
4
+ import type { ReactToolCallRenderer } from "../types/react-tool-call-renderer";
5
+ import { useCallback, useEffect, useRef } from "react";
6
+ import React from "react";
7
+ import { useFrontendTool } from "./use-frontend-tool";
8
+
9
+ export function useHumanInTheLoop<
10
+ T extends Record<string, unknown> = Record<string, unknown>,
11
+ >(tool: ReactHumanInTheLoop<T>, deps?: ReadonlyArray<unknown>) {
12
+ const { copilotkit } = useCopilotKit();
13
+ const resolvePromiseRef = useRef<((result: unknown) => void) | null>(null);
14
+
15
+ const respond = useCallback(async (result: unknown) => {
16
+ if (resolvePromiseRef.current) {
17
+ resolvePromiseRef.current(result);
18
+ resolvePromiseRef.current = null;
19
+ }
20
+ }, []);
21
+
22
+ const handler = useCallback(async () => {
23
+ return new Promise((resolve) => {
24
+ resolvePromiseRef.current = resolve;
25
+ });
26
+ }, []);
27
+
28
+ const RenderComponent: ReactToolCallRenderer<T>["render"] = useCallback(
29
+ (props) => {
30
+ const ToolComponent = tool.render;
31
+
32
+ // Enhance props based on current status
33
+ if (props.status === "inProgress") {
34
+ const enhancedProps = {
35
+ ...props,
36
+ name: tool.name,
37
+ description: tool.description || "",
38
+ respond: undefined,
39
+ };
40
+ return React.createElement(ToolComponent, enhancedProps);
41
+ } else if (props.status === "executing") {
42
+ const enhancedProps = {
43
+ ...props,
44
+ name: tool.name,
45
+ description: tool.description || "",
46
+ respond,
47
+ };
48
+ return React.createElement(ToolComponent, enhancedProps);
49
+ } else if (props.status === "complete") {
50
+ const enhancedProps = {
51
+ ...props,
52
+ name: tool.name,
53
+ description: tool.description || "",
54
+ respond: undefined,
55
+ };
56
+ return React.createElement(ToolComponent, enhancedProps);
57
+ }
58
+
59
+ // Fallback - just render with original props
60
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
61
+ return React.createElement(ToolComponent, props as any);
62
+ },
63
+ [tool.render, tool.name, tool.description, respond],
64
+ );
65
+
66
+ const frontendTool: ReactFrontendTool<T> = {
67
+ ...tool,
68
+ handler,
69
+ render: RenderComponent,
70
+ };
71
+
72
+ useFrontendTool(frontendTool, deps);
73
+
74
+ // Human-in-the-loop tools should remove their renderer on unmount
75
+ // since they can't respond to user interactions anymore
76
+ useEffect(() => {
77
+ return () => {
78
+ copilotkit.removeHookRenderToolCall(tool.name, tool.agentId);
79
+ };
80
+ }, [copilotkit, tool.name, tool.agentId]);
81
+ }
@@ -0,0 +1,305 @@
1
+ import React, {
2
+ useState,
3
+ useEffect,
4
+ useCallback,
5
+ useMemo,
6
+ useRef,
7
+ } from "react";
8
+ import { useCopilotKit } from "../providers/CopilotKitProvider";
9
+ import { useAgent } from "./use-agent";
10
+ import type {
11
+ InterruptEvent,
12
+ InterruptRenderProps,
13
+ InterruptHandlerProps,
14
+ } from "../types/interrupt";
15
+
16
+ export type { InterruptEvent, InterruptRenderProps, InterruptHandlerProps };
17
+
18
+ const INTERRUPT_EVENT_NAME = "on_interrupt";
19
+
20
+ type InterruptHandlerFn<TValue, TResult> = (
21
+ props: InterruptHandlerProps<TValue>,
22
+ ) => TResult | PromiseLike<TResult>;
23
+
24
+ type InterruptResultFromHandler<THandler> = THandler extends (
25
+ ...args: never[]
26
+ ) => infer TResult
27
+ ? TResult extends PromiseLike<infer TResolved>
28
+ ? TResolved | null
29
+ : TResult | null
30
+ : null;
31
+
32
+ type InterruptResult<TValue, TResult> = InterruptResultFromHandler<
33
+ InterruptHandlerFn<TValue, TResult>
34
+ >;
35
+
36
+ type InterruptRenderInChat = boolean | undefined;
37
+
38
+ type UseInterruptReturn<TRenderInChat extends InterruptRenderInChat> =
39
+ TRenderInChat extends false
40
+ ? React.ReactElement | null
41
+ : TRenderInChat extends true | undefined
42
+ ? void
43
+ : React.ReactElement | null | void;
44
+
45
+ export function isPromiseLike<TValue>(
46
+ value: TValue | PromiseLike<TValue>,
47
+ ): value is PromiseLike<TValue> {
48
+ return (
49
+ (typeof value === "object" || typeof value === "function") &&
50
+ value !== null &&
51
+ typeof Reflect.get(value, "then") === "function"
52
+ );
53
+ }
54
+
55
+ /**
56
+ * Configuration options for `useInterrupt`.
57
+ */
58
+ interface UseInterruptConfigBase<TValue = unknown, TResult = never> {
59
+ /**
60
+ * Render function for the interrupt UI.
61
+ *
62
+ * This is called once an interrupt is finalized and accepted by `enabled` (if provided).
63
+ * Use `resolve` from render props to resume the agent run with user input.
64
+ */
65
+ render: (
66
+ props: InterruptRenderProps<TValue, InterruptResult<TValue, TResult>>,
67
+ ) => React.ReactElement;
68
+ /**
69
+ * Optional pre-render handler invoked when an interrupt is received.
70
+ *
71
+ * Return either a sync value or an async value to pass into `render` as `result`.
72
+ * Rejecting/throwing falls back to `result = null`.
73
+ */
74
+ handler?: InterruptHandlerFn<TValue, TResult>;
75
+ /**
76
+ * Optional predicate to filter which interrupts should be handled by this hook.
77
+ * Return `false` to ignore an interrupt.
78
+ */
79
+ enabled?: (event: InterruptEvent<TValue>) => boolean;
80
+ /** Optional agent id. Defaults to the current configured chat agent. */
81
+ agentId?: string;
82
+ }
83
+
84
+ export interface UseInterruptInChatConfig<
85
+ TValue = unknown,
86
+ TResult = never,
87
+ > extends UseInterruptConfigBase<TValue, TResult> {
88
+ /** When true (default), the interrupt UI renders inside `<CopilotChat>` automatically. Set to false to render it yourself. */
89
+ renderInChat?: true;
90
+ }
91
+
92
+ export interface UseInterruptExternalConfig<
93
+ TValue = unknown,
94
+ TResult = never,
95
+ > extends UseInterruptConfigBase<TValue, TResult> {
96
+ /** When true (default), the interrupt UI renders inside `<CopilotChat>` automatically. Set to false to render it yourself. */
97
+ renderInChat: false;
98
+ }
99
+
100
+ export interface UseInterruptDynamicConfig<
101
+ TValue = unknown,
102
+ TResult = never,
103
+ > extends UseInterruptConfigBase<TValue, TResult> {
104
+ /** Dynamic boolean mode. When non-literal, return type is a union. */
105
+ renderInChat: boolean;
106
+ }
107
+
108
+ export type UseInterruptConfig<
109
+ TValue = unknown,
110
+ TResult = never,
111
+ TRenderInChat extends InterruptRenderInChat = undefined,
112
+ > = UseInterruptConfigBase<TValue, TResult> & {
113
+ /** When true (default), the interrupt UI renders inside `<CopilotChat>` automatically. Set to false to render it yourself. */
114
+ renderInChat?: TRenderInChat;
115
+ };
116
+
117
+ /**
118
+ * Handles agent interrupts (`on_interrupt`) with optional filtering, preprocessing, and resume behavior.
119
+ *
120
+ * The hook listens to custom events on the active agent, stores interrupt payloads per run,
121
+ * and surfaces a render callback once the run finalizes. Call `resolve` from your UI to resume
122
+ * execution with user-provided data.
123
+ *
124
+ * - `renderInChat: true` (default): the element is published into `<CopilotChat>` and this hook returns `void`.
125
+ * - `renderInChat: false`: the hook returns the interrupt element so you can place it anywhere in your component tree.
126
+ *
127
+ * `event.value` is typed as `any` since the interrupt payload shape depends on your agent.
128
+ * Type-narrow it in your callbacks (e.g. `handler`, `enabled`, `render`) as needed.
129
+ *
130
+ * @typeParam TResult - Inferred from `handler` return type. Exposed as `result` in `render`.
131
+ * @param config - Interrupt configuration (renderer, optional handler/filter, and render mode).
132
+ * @returns When `renderInChat` is `false`, returns the interrupt element (or `null` when idle).
133
+ * Otherwise returns `void` and publishes the element into chat. In `render`, `result` is always
134
+ * either the handler's resolved return value or `null` (including when no handler is provided,
135
+ * when filtering skips the interrupt, or when handler execution fails).
136
+ *
137
+ * @example
138
+ * ```tsx
139
+ * import { useInterrupt } from "@copilotkit/react-core/v2";
140
+ *
141
+ * function InterruptUI() {
142
+ * useInterrupt({
143
+ * render: ({ event, resolve }) => (
144
+ * <div>
145
+ * <p>{event.value.question}</p>
146
+ * <button onClick={() => resolve({ approved: true })}>Approve</button>
147
+ * <button onClick={() => resolve({ approved: false })}>Reject</button>
148
+ * </div>
149
+ * ),
150
+ * });
151
+ *
152
+ * return null;
153
+ * }
154
+ * ```
155
+ *
156
+ * @example
157
+ * ```tsx
158
+ * import { useInterrupt } from "@copilotkit/react-core/v2";
159
+ *
160
+ * function CustomPanel() {
161
+ * const interruptElement = useInterrupt({
162
+ * renderInChat: false,
163
+ * enabled: (event) => event.value.startsWith("approval:"),
164
+ * handler: async ({ event }) => ({ label: event.value.toUpperCase() }),
165
+ * render: ({ event, result, resolve }) => (
166
+ * <aside>
167
+ * <strong>{result?.label ?? ""}</strong>
168
+ * <button onClick={() => resolve({ value: event.value })}>Continue</button>
169
+ * </aside>
170
+ * ),
171
+ * });
172
+ *
173
+ * return <>{interruptElement}</>;
174
+ * }
175
+ * ```
176
+ */
177
+ /* eslint-disable @typescript-eslint/no-explicit-any */
178
+ export function useInterrupt<
179
+ TResult = never,
180
+ TRenderInChat extends InterruptRenderInChat = undefined,
181
+ >(
182
+ config: UseInterruptConfig<any, TResult, TRenderInChat>,
183
+ ): UseInterruptReturn<TRenderInChat> {
184
+ /* eslint-enable @typescript-eslint/no-explicit-any */
185
+ const { copilotkit } = useCopilotKit();
186
+ const { agent } = useAgent({ agentId: config.agentId });
187
+ const [pendingEvent, setPendingEvent] = useState<InterruptEvent | null>(null);
188
+ const pendingEventRef = useRef(pendingEvent);
189
+ pendingEventRef.current = pendingEvent;
190
+ const [handlerResult, setHandlerResult] =
191
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
192
+ useState<InterruptResult<any, TResult>>(null);
193
+
194
+ useEffect(() => {
195
+ let localInterrupt: InterruptEvent | null = null;
196
+
197
+ const subscription = agent.subscribe({
198
+ onCustomEvent: ({ event }) => {
199
+ if (event.name === INTERRUPT_EVENT_NAME) {
200
+ localInterrupt = { name: event.name, value: event.value };
201
+ }
202
+ },
203
+ onRunStartedEvent: () => {
204
+ localInterrupt = null;
205
+ setPendingEvent(null);
206
+ },
207
+ onRunFinalized: () => {
208
+ if (localInterrupt) {
209
+ setPendingEvent(localInterrupt);
210
+ localInterrupt = null;
211
+ }
212
+ },
213
+ onRunFailed: () => {
214
+ localInterrupt = null;
215
+ },
216
+ });
217
+
218
+ return () => subscription.unsubscribe();
219
+ }, [agent]);
220
+
221
+ const resolve = useCallback(
222
+ (response: unknown) => {
223
+ setPendingEvent(null);
224
+ copilotkit.runAgent({
225
+ agent,
226
+ forwardedProps: {
227
+ command: {
228
+ resume: response,
229
+ interruptEvent: pendingEventRef.current?.value,
230
+ },
231
+ },
232
+ });
233
+ },
234
+ [agent, copilotkit],
235
+ );
236
+
237
+ useEffect(() => {
238
+ // No interrupt to process — reset any stale handler result from a previous interrupt
239
+ if (!pendingEvent) {
240
+ setHandlerResult(null);
241
+ return;
242
+ }
243
+ // Interrupt exists but the consumer's filter rejects it — treat as no-op
244
+ if (config.enabled && !config.enabled(pendingEvent)) {
245
+ setHandlerResult(null);
246
+ return;
247
+ }
248
+ const handler = config.handler;
249
+ // No handler provided — skip straight to rendering with a null result
250
+ if (!handler) {
251
+ setHandlerResult(null);
252
+ return;
253
+ }
254
+
255
+ let cancelled = false;
256
+ const maybePromise = handler({
257
+ event: pendingEvent,
258
+ resolve,
259
+ });
260
+
261
+ // If the handler returns a promise/thenable, wait for resolution before setting result.
262
+ if (isPromiseLike(maybePromise)) {
263
+ Promise.resolve(maybePromise)
264
+ .then((resolved) => {
265
+ if (!cancelled) setHandlerResult(resolved);
266
+ })
267
+ .catch(() => {
268
+ if (!cancelled) setHandlerResult(null);
269
+ });
270
+ } else {
271
+ setHandlerResult(maybePromise);
272
+ }
273
+
274
+ return () => {
275
+ cancelled = true;
276
+ };
277
+ // eslint-disable-next-line react-hooks/exhaustive-deps
278
+ }, [pendingEvent, config.enabled, config.handler, resolve]);
279
+
280
+ const element = useMemo(() => {
281
+ if (!pendingEvent) return null;
282
+ if (config.enabled && !config.enabled(pendingEvent)) return null;
283
+
284
+ return config.render({
285
+ event: pendingEvent,
286
+ result: handlerResult,
287
+ resolve,
288
+ });
289
+ // eslint-disable-next-line react-hooks/exhaustive-deps
290
+ }, [pendingEvent, handlerResult, config.enabled, config.render, resolve]);
291
+
292
+ // Publish to core for in-chat rendering
293
+ useEffect(() => {
294
+ if (config.renderInChat === false) return;
295
+ copilotkit.setInterruptElement(element);
296
+ return () => copilotkit.setInterruptElement(null);
297
+ }, [element, config.renderInChat, copilotkit]);
298
+
299
+ // Only return element when rendering outside chat
300
+ if (config.renderInChat === false) {
301
+ return element as UseInterruptReturn<TRenderInChat>;
302
+ }
303
+
304
+ return undefined as UseInterruptReturn<TRenderInChat>;
305
+ }