@copilotkit/react-core 1.57.2 → 1.57.4

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 (266) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +12 -13
  3. package/skills/react-core/SKILL.md +108 -0
  4. package/skills/react-core/references/agent-access.md +288 -0
  5. package/skills/react-core/references/attachments.md +291 -0
  6. package/skills/react-core/references/capabilities.md +138 -0
  7. package/skills/react-core/references/chat-components.md +221 -0
  8. package/skills/react-core/references/client-side-tools.md +358 -0
  9. package/skills/react-core/references/custom-message-renderers.md +226 -0
  10. package/skills/react-core/references/debug-mode.md +153 -0
  11. package/skills/react-core/references/human-in-the-loop.md +312 -0
  12. package/skills/react-core/references/provider-setup.md +326 -0
  13. package/skills/react-core/references/rendering-activity-messages.md +207 -0
  14. package/skills/react-core/references/rendering-tool-calls.md +319 -0
  15. package/skills/react-core/references/suggestions.md +211 -0
  16. package/skills/react-core/references/switching-agents-recipes.md +160 -0
  17. package/skills/react-core/references/switching-agents.md +231 -0
  18. package/skills/react-core/references/threads.md +226 -0
  19. package/.attw.json +0 -3
  20. package/CHANGELOG.md +0 -5043
  21. package/scripts/scope-preflight.mjs +0 -100
  22. package/src/components/CopilotListeners.tsx +0 -137
  23. package/src/components/__tests__/CopilotListeners.test.tsx +0 -38
  24. package/src/components/copilot-provider/__tests__/copilot-messages-key.test.tsx +0 -92
  25. package/src/components/copilot-provider/__tests__/copilotkit-error.test.tsx +0 -77
  26. package/src/components/copilot-provider/__tests__/error-visibility-prod.test.tsx +0 -70
  27. package/src/components/copilot-provider/__tests__/v1-explicit-threadid-bridge.test.tsx +0 -107
  28. package/src/components/copilot-provider/copilot-messages.tsx +0 -314
  29. package/src/components/copilot-provider/copilotkit-props.tsx +0 -214
  30. package/src/components/copilot-provider/copilotkit.tsx +0 -853
  31. package/src/components/copilot-provider/index.ts +0 -3
  32. package/src/components/dev-console/console-trigger.tsx +0 -283
  33. package/src/components/dev-console/developer-console-modal.tsx +0 -1016
  34. package/src/components/dev-console/icons.tsx +0 -106
  35. package/src/components/error-boundary/error-boundary.tsx +0 -99
  36. package/src/components/error-boundary/error-utils.tsx +0 -105
  37. package/src/components/index.ts +0 -1
  38. package/src/components/toast/exclamation-mark-icon.tsx +0 -27
  39. package/src/components/toast/toast-provider.tsx +0 -448
  40. package/src/components/usage-banner.tsx +0 -266
  41. package/src/context/__tests__/threads-context.test.tsx +0 -141
  42. package/src/context/coagent-state-renders-context.tsx +0 -89
  43. package/src/context/copilot-context.tsx +0 -365
  44. package/src/context/copilot-messages-context.tsx +0 -35
  45. package/src/context/index.ts +0 -22
  46. package/src/context/threads-context.tsx +0 -69
  47. package/src/hooks/__tests__/use-coagent-config.test.ts +0 -352
  48. package/src/hooks/__tests__/use-coagent-state-render-bridge.helpers.test.ts +0 -107
  49. package/src/hooks/__tests__/use-coagent-state-render.e2e.test.tsx +0 -1209
  50. package/src/hooks/__tests__/use-coagent-state-render.test.tsx +0 -356
  51. package/src/hooks/__tests__/use-copilot-chat-internal-connect.test.tsx +0 -241
  52. package/src/hooks/__tests__/use-frontend-tool-available.test.tsx +0 -72
  53. package/src/hooks/__tests__/use-frontend-tool-remount.e2e.test.tsx +0 -102
  54. package/src/hooks/index.ts +0 -33
  55. package/src/hooks/use-agent-nodename.ts +0 -33
  56. package/src/hooks/use-coagent-state-render-bridge.helpers.ts +0 -345
  57. package/src/hooks/use-coagent-state-render-bridge.tsx +0 -222
  58. package/src/hooks/use-coagent-state-render-registry.ts +0 -230
  59. package/src/hooks/use-coagent-state-render.ts +0 -163
  60. package/src/hooks/use-coagent.ts +0 -377
  61. package/src/hooks/use-configure-chat-suggestions.tsx +0 -96
  62. package/src/hooks/use-copilot-action.ts +0 -245
  63. package/src/hooks/use-copilot-additional-instructions.ts +0 -98
  64. package/src/hooks/use-copilot-authenticated-action.ts +0 -73
  65. package/src/hooks/use-copilot-chat-headless_c.ts +0 -264
  66. package/src/hooks/use-copilot-chat-suggestions.tsx +0 -134
  67. package/src/hooks/use-copilot-chat.ts +0 -132
  68. package/src/hooks/use-copilot-chat_internal.ts +0 -875
  69. package/src/hooks/use-copilot-readable.ts +0 -135
  70. package/src/hooks/use-copilot-runtime-client.ts +0 -178
  71. package/src/hooks/use-default-tool.ts +0 -13
  72. package/src/hooks/use-flat-category-store.ts +0 -109
  73. package/src/hooks/use-frontend-tool.ts +0 -113
  74. package/src/hooks/use-human-in-the-loop.ts +0 -138
  75. package/src/hooks/use-langgraph-interrupt.ts +0 -103
  76. package/src/hooks/use-lazy-tool-renderer.tsx +0 -30
  77. package/src/hooks/use-make-copilot-document-readable.ts +0 -30
  78. package/src/hooks/use-render-tool-call.ts +0 -89
  79. package/src/hooks/use-tree.ts +0 -222
  80. package/src/index.tsx +0 -7
  81. package/src/lib/copilot-task.ts +0 -215
  82. package/src/lib/index.ts +0 -1
  83. package/src/lib/status-checker.ts +0 -67
  84. package/src/setupTests.ts +0 -37
  85. package/src/test-helpers/copilot-context.ts +0 -91
  86. package/src/types/chat-suggestion-configuration.ts +0 -23
  87. package/src/types/coagent-action.ts +0 -35
  88. package/src/types/coagent-state.ts +0 -13
  89. package/src/types/crew.ts +0 -89
  90. package/src/types/document-pointer.ts +0 -7
  91. package/src/types/frontend-action.ts +0 -213
  92. package/src/types/index.ts +0 -17
  93. package/src/types/interrupt-action.ts +0 -58
  94. package/src/types/system-message.ts +0 -4
  95. package/src/utils/dev-console.ts +0 -19
  96. package/src/utils/index.ts +0 -2
  97. package/src/utils/suggestions-constants.ts +0 -8
  98. package/src/utils/utils.test.ts +0 -7
  99. package/src/utils/utils.ts +0 -6
  100. package/src/v2/__tests__/A2UIMessageRenderer.test.tsx +0 -240
  101. package/src/v2/__tests__/globalSetup.ts +0 -14
  102. package/src/v2/__tests__/setup.ts +0 -93
  103. package/src/v2/__tests__/utils/test-helpers.tsx +0 -570
  104. package/src/v2/a2ui/A2UICatalogContext.tsx +0 -79
  105. package/src/v2/a2ui/A2UIMessageRenderer.tsx +0 -294
  106. package/src/v2/a2ui/A2UIToolCallRenderer.tsx +0 -290
  107. package/src/v2/components/CopilotKitInspector.tsx +0 -52
  108. package/src/v2/components/MCPAppsActivityRenderer.tsx +0 -815
  109. package/src/v2/components/OpenGenerativeUIRenderer.tsx +0 -598
  110. package/src/v2/components/WildcardToolCallRender.tsx +0 -86
  111. package/src/v2/components/__tests__/OpenGenerativeUIRenderer.test.tsx +0 -665
  112. package/src/v2/components/chat/CopilotChat.tsx +0 -664
  113. package/src/v2/components/chat/CopilotChatAssistantMessage.tsx +0 -393
  114. package/src/v2/components/chat/CopilotChatAttachmentQueue.tsx +0 -374
  115. package/src/v2/components/chat/CopilotChatAttachmentRenderer.tsx +0 -159
  116. package/src/v2/components/chat/CopilotChatAudioRecorder.tsx +0 -350
  117. package/src/v2/components/chat/CopilotChatInput.tsx +0 -1412
  118. package/src/v2/components/chat/CopilotChatMessageView.tsx +0 -716
  119. package/src/v2/components/chat/CopilotChatReasoningMessage.tsx +0 -265
  120. package/src/v2/components/chat/CopilotChatSuggestionPill.tsx +0 -59
  121. package/src/v2/components/chat/CopilotChatSuggestionView.tsx +0 -134
  122. package/src/v2/components/chat/CopilotChatToggleButton.tsx +0 -171
  123. package/src/v2/components/chat/CopilotChatToolCallsView.tsx +0 -40
  124. package/src/v2/components/chat/CopilotChatUserMessage.tsx +0 -445
  125. package/src/v2/components/chat/CopilotChatView.tsx +0 -890
  126. package/src/v2/components/chat/CopilotModalHeader.tsx +0 -129
  127. package/src/v2/components/chat/CopilotPopup.tsx +0 -81
  128. package/src/v2/components/chat/CopilotPopupView.tsx +0 -317
  129. package/src/v2/components/chat/CopilotSidebar.tsx +0 -80
  130. package/src/v2/components/chat/CopilotSidebarView.tsx +0 -269
  131. package/src/v2/components/chat/Lightbox.tsx +0 -103
  132. package/src/v2/components/chat/__tests__/CopilotChat.absentThreadConnect.test.tsx +0 -66
  133. package/src/v2/components/chat/__tests__/CopilotChat.attachments.test.tsx +0 -168
  134. package/src/v2/components/chat/__tests__/CopilotChat.e2e.test.tsx +0 -1239
  135. package/src/v2/components/chat/__tests__/CopilotChat.onError.test.tsx +0 -73
  136. package/src/v2/components/chat/__tests__/CopilotChat.slots.e2e.test.tsx +0 -432
  137. package/src/v2/components/chat/__tests__/CopilotChat.suggestionsAlways.test.tsx +0 -183
  138. package/src/v2/components/chat/__tests__/CopilotChat.welcomeGate.test.tsx +0 -184
  139. package/src/v2/components/chat/__tests__/CopilotChatActivityRendering.e2e.test.tsx +0 -649
  140. package/src/v2/components/chat/__tests__/CopilotChatAssistantMessage.slots.e2e.test.tsx +0 -624
  141. package/src/v2/components/chat/__tests__/CopilotChatAssistantMessage.test.tsx +0 -702
  142. package/src/v2/components/chat/__tests__/CopilotChatAssistantMessage.thumbs.test.tsx +0 -72
  143. package/src/v2/components/chat/__tests__/CopilotChatCopyButton.clipboard.test.tsx +0 -241
  144. package/src/v2/components/chat/__tests__/CopilotChatCssClasses.test.tsx +0 -107
  145. package/src/v2/components/chat/__tests__/CopilotChatInput.slots.e2e.test.tsx +0 -929
  146. package/src/v2/components/chat/__tests__/CopilotChatInput.test.tsx +0 -1567
  147. package/src/v2/components/chat/__tests__/CopilotChatMessageView.slots.e2e.test.tsx +0 -1004
  148. package/src/v2/components/chat/__tests__/CopilotChatMessageView.test.tsx +0 -279
  149. package/src/v2/components/chat/__tests__/CopilotChatPerf.e2e.test.tsx +0 -296
  150. package/src/v2/components/chat/__tests__/CopilotChatPropsRerender.e2e.test.tsx +0 -249
  151. package/src/v2/components/chat/__tests__/CopilotChatSuggestionView.slots.e2e.test.tsx +0 -530
  152. package/src/v2/components/chat/__tests__/CopilotChatToolRendering.e2e.test.tsx +0 -785
  153. package/src/v2/components/chat/__tests__/CopilotChatToolRerenders.e2e.test.tsx +0 -2416
  154. package/src/v2/components/chat/__tests__/CopilotChatUserMessage.slots.e2e.test.tsx +0 -621
  155. package/src/v2/components/chat/__tests__/CopilotChatView.connectingGate.test.tsx +0 -56
  156. package/src/v2/components/chat/__tests__/CopilotChatView.inputOverlay.test.tsx +0 -264
  157. package/src/v2/components/chat/__tests__/CopilotChatView.onClick.e2e.test.tsx +0 -853
  158. package/src/v2/components/chat/__tests__/CopilotChatView.pinToSend.test.tsx +0 -94
  159. package/src/v2/components/chat/__tests__/CopilotChatView.slots.e2e.test.tsx +0 -1050
  160. package/src/v2/components/chat/__tests__/CopilotModalHeader.slots.e2e.test.tsx +0 -484
  161. package/src/v2/components/chat/__tests__/CopilotPopupView.slots.e2e.test.tsx +0 -612
  162. package/src/v2/components/chat/__tests__/CopilotSidebarView.position.test.tsx +0 -159
  163. package/src/v2/components/chat/__tests__/CopilotSidebarView.slots.e2e.test.tsx +0 -502
  164. package/src/v2/components/chat/__tests__/MCPAppsActivityRenderer.e2e.test.tsx +0 -1068
  165. package/src/v2/components/chat/__tests__/MCPAppsProxy.e2e.test.tsx +0 -589
  166. package/src/v2/components/chat/__tests__/MCPAppsUiMessage.e2e.test.tsx +0 -403
  167. package/src/v2/components/chat/__tests__/copilot-chat-throttle.test.tsx +0 -137
  168. package/src/v2/components/chat/__tests__/normalize-auto-scroll.test.ts +0 -37
  169. package/src/v2/components/chat/__tests__/setup.ts +0 -1
  170. package/src/v2/components/chat/index.ts +0 -90
  171. package/src/v2/components/chat/last-user-message-context.ts +0 -21
  172. package/src/v2/components/chat/normalize-auto-scroll.ts +0 -17
  173. package/src/v2/components/chat/scroll-element-context.ts +0 -13
  174. package/src/v2/components/index.ts +0 -8
  175. package/src/v2/components/intelligence-indicator/IntelligenceIndicator.tsx +0 -286
  176. package/src/v2/components/intelligence-indicator/__tests__/IntelligenceIndicator.e2e.test.tsx +0 -464
  177. package/src/v2/components/intelligence-indicator/index.ts +0 -2
  178. package/src/v2/components/license-warning-banner.tsx +0 -217
  179. package/src/v2/components/ui/button.tsx +0 -124
  180. package/src/v2/components/ui/dropdown-menu.tsx +0 -258
  181. package/src/v2/components/ui/tooltip.tsx +0 -60
  182. package/src/v2/context.ts +0 -62
  183. package/src/v2/headless.ts +0 -64
  184. package/src/v2/hooks/__tests__/standard-schema-types.test.tsx +0 -152
  185. package/src/v2/hooks/__tests__/standard-schema.test.tsx +0 -282
  186. package/src/v2/hooks/__tests__/use-agent-context-timing.e2e.test.tsx +0 -140
  187. package/src/v2/hooks/__tests__/use-agent-context.test.tsx +0 -401
  188. package/src/v2/hooks/__tests__/use-agent-error-state.test.tsx +0 -44
  189. package/src/v2/hooks/__tests__/use-agent-stability.test.tsx +0 -211
  190. package/src/v2/hooks/__tests__/use-agent-throttle.test.tsx +0 -1029
  191. package/src/v2/hooks/__tests__/use-agent.e2e.test.tsx +0 -159
  192. package/src/v2/hooks/__tests__/use-attachments.test.tsx +0 -169
  193. package/src/v2/hooks/__tests__/use-capabilities.test.tsx +0 -76
  194. package/src/v2/hooks/__tests__/use-component.test.tsx +0 -126
  195. package/src/v2/hooks/__tests__/use-configure-suggestions.e2e.test.tsx +0 -696
  196. package/src/v2/hooks/__tests__/use-default-render-tool.test.tsx +0 -153
  197. package/src/v2/hooks/__tests__/use-frontend-tool-available.test.tsx +0 -167
  198. package/src/v2/hooks/__tests__/use-frontend-tool.e2e.test.tsx +0 -2148
  199. package/src/v2/hooks/__tests__/use-human-in-the-loop.e2e.test.tsx +0 -1261
  200. package/src/v2/hooks/__tests__/use-interrupt.test.tsx +0 -397
  201. package/src/v2/hooks/__tests__/use-katex-styles.test.tsx +0 -56
  202. package/src/v2/hooks/__tests__/use-keyboard-height.test.tsx +0 -192
  203. package/src/v2/hooks/__tests__/use-pin-to-send.test.tsx +0 -219
  204. package/src/v2/hooks/__tests__/use-render-custom-messages.test.tsx +0 -55
  205. package/src/v2/hooks/__tests__/use-render-tool.test.tsx +0 -259
  206. package/src/v2/hooks/__tests__/use-suggestions.e2e.test.tsx +0 -524
  207. package/src/v2/hooks/__tests__/use-threads.test.tsx +0 -757
  208. package/src/v2/hooks/__tests__/zod-regression.test.tsx +0 -311
  209. package/src/v2/hooks/index.ts +0 -24
  210. package/src/v2/hooks/use-agent-context.tsx +0 -45
  211. package/src/v2/hooks/use-agent.tsx +0 -227
  212. package/src/v2/hooks/use-attachments.tsx +0 -269
  213. package/src/v2/hooks/use-capabilities.tsx +0 -25
  214. package/src/v2/hooks/use-component.tsx +0 -91
  215. package/src/v2/hooks/use-configure-suggestions.tsx +0 -236
  216. package/src/v2/hooks/use-default-render-tool.tsx +0 -271
  217. package/src/v2/hooks/use-frontend-tool.tsx +0 -46
  218. package/src/v2/hooks/use-human-in-the-loop.tsx +0 -81
  219. package/src/v2/hooks/use-interrupt.tsx +0 -305
  220. package/src/v2/hooks/use-keyboard-height.tsx +0 -67
  221. package/src/v2/hooks/use-pin-to-send.ts +0 -94
  222. package/src/v2/hooks/use-render-activity-message.tsx +0 -72
  223. package/src/v2/hooks/use-render-custom-messages.tsx +0 -93
  224. package/src/v2/hooks/use-render-tool-call.tsx +0 -208
  225. package/src/v2/hooks/use-render-tool.tsx +0 -184
  226. package/src/v2/hooks/use-suggestions.tsx +0 -91
  227. package/src/v2/hooks/use-threads.tsx +0 -325
  228. package/src/v2/hooks/useKatexStyles.ts +0 -27
  229. package/src/v2/index.css +0 -1
  230. package/src/v2/index.ts +0 -27
  231. package/src/v2/lib/__tests__/completePartialMarkdown.test.ts +0 -495
  232. package/src/v2/lib/__tests__/processPartialHtml.test.ts +0 -112
  233. package/src/v2/lib/__tests__/renderSlot.test.tsx +0 -588
  234. package/src/v2/lib/__tests__/slots.test.ts +0 -56
  235. package/src/v2/lib/processPartialHtml.ts +0 -45
  236. package/src/v2/lib/react-core.ts +0 -156
  237. package/src/v2/lib/slots.tsx +0 -184
  238. package/src/v2/lib/transcription-client.ts +0 -184
  239. package/src/v2/lib/utils.ts +0 -8
  240. package/src/v2/providers/CopilotChatConfigurationProvider.tsx +0 -196
  241. package/src/v2/providers/CopilotKitProvider.tsx +0 -800
  242. package/src/v2/providers/SandboxFunctionsContext.ts +0 -10
  243. package/src/v2/providers/__tests__/CopilotChatConfigurationProvider.test.tsx +0 -652
  244. package/src/v2/providers/__tests__/CopilotKitProvider.license.test.tsx +0 -101
  245. package/src/v2/providers/__tests__/CopilotKitProvider.onError.test.tsx +0 -69
  246. package/src/v2/providers/__tests__/CopilotKitProvider.renderCustomMessages.e2e.test.tsx +0 -881
  247. package/src/v2/providers/__tests__/CopilotKitProvider.sandboxFunctions.test.tsx +0 -198
  248. package/src/v2/providers/__tests__/CopilotKitProvider.stability.test.tsx +0 -740
  249. package/src/v2/providers/__tests__/CopilotKitProvider.test.tsx +0 -713
  250. package/src/v2/providers/__tests__/CopilotKitProvider.wildcard.test.tsx +0 -294
  251. package/src/v2/providers/index.ts +0 -21
  252. package/src/v2/styles/globals.css +0 -349
  253. package/src/v2/types/__tests__/defineToolCallRenderer.test.tsx +0 -525
  254. package/src/v2/types/defineToolCallRenderer.ts +0 -68
  255. package/src/v2/types/frontend-tool.ts +0 -8
  256. package/src/v2/types/human-in-the-loop.ts +0 -33
  257. package/src/v2/types/index.ts +0 -8
  258. package/src/v2/types/interrupt.ts +0 -15
  259. package/src/v2/types/react-activity-message-renderer.ts +0 -27
  260. package/src/v2/types/react-custom-message-renderer.ts +0 -17
  261. package/src/v2/types/react-tool-call-renderer.ts +0 -35
  262. package/src/v2/types/sandbox-function.ts +0 -11
  263. package/tsconfig.json +0 -8
  264. package/tsdown.config.ts +0 -193
  265. package/typedoc.json +0 -4
  266. package/vitest.config.mjs +0 -31
@@ -1,815 +0,0 @@
1
- "use client";
2
-
3
- import React, { useEffect, useRef, useState, useCallback } from "react";
4
- import { z } from "zod";
5
- import type { AbstractAgent, RunAgentResult } from "@ag-ui/client";
6
- import { useCopilotKit } from "../providers/CopilotKitProvider";
7
-
8
- // Protocol version supported
9
- const PROTOCOL_VERSION = "2025-06-18";
10
-
11
- // Build sandbox proxy HTML with optional extra CSP domains from resource metadata
12
- function buildSandboxHTML(extraCspDomains?: string[]): string {
13
- const baseScriptSrc =
14
- "'self' 'wasm-unsafe-eval' 'unsafe-inline' 'unsafe-eval' blob: data: http://localhost:* https://localhost:*";
15
- const baseFrameSrc = "* blob: data: http://localhost:* https://localhost:*";
16
- const extra = extraCspDomains?.length ? " " + extraCspDomains.join(" ") : "";
17
- const scriptSrc = baseScriptSrc + extra;
18
- const frameSrc = baseFrameSrc + extra;
19
-
20
- return `<!doctype html>
21
- <html>
22
- <head>
23
- <meta charset="utf-8" />
24
- <meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src * data: blob: 'unsafe-inline'; media-src * blob: data:; font-src * blob: data:; script-src ${scriptSrc}; style-src * blob: data: 'unsafe-inline'; connect-src *; frame-src ${frameSrc}; base-uri 'self';" />
25
- <style>html,body{margin:0;padding:0;height:100%;width:100%;overflow:hidden}*{box-sizing:border-box}iframe{background-color:transparent;border:none;padding:0;overflow:hidden;width:100%;height:100%}</style>
26
- </head>
27
- <body>
28
- <script>
29
- if(window.self===window.top){throw new Error("This file must be used in an iframe.")}
30
- const inner=document.createElement("iframe");
31
- inner.style="width:100%;height:100%;border:none;";
32
- inner.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms");
33
- document.body.appendChild(inner);
34
- window.addEventListener("message",async(event)=>{
35
- if(event.source===window.parent){
36
- if(event.data&&event.data.method==="ui/notifications/sandbox-resource-ready"){
37
- const{html,sandbox}=event.data.params;
38
- if(typeof sandbox==="string")inner.setAttribute("sandbox",sandbox);
39
- if(typeof html==="string")inner.srcdoc=html;
40
- }else if(inner&&inner.contentWindow){
41
- inner.contentWindow.postMessage(event.data,"*");
42
- }
43
- }else if(event.source===inner.contentWindow){
44
- window.parent.postMessage(event.data,"*");
45
- }
46
- });
47
- window.parent.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-proxy-ready",params:{}},"*");
48
- </script>
49
- </body>
50
- </html>`;
51
- }
52
-
53
- /**
54
- * Queue for serializing MCP app requests to an agent.
55
- * Ensures requests wait for the agent to stop running and are processed one at a time.
56
- */
57
- class MCPAppsRequestQueue {
58
- private queues = new Map<
59
- string,
60
- Array<{
61
- execute: () => Promise<RunAgentResult>;
62
- resolve: (result: RunAgentResult) => void;
63
- reject: (error: Error) => void;
64
- }>
65
- >();
66
- private processing = new Map<string, boolean>();
67
-
68
- /**
69
- * Add a request to the queue for a specific agent thread.
70
- * Returns a promise that resolves when the request completes.
71
- */
72
- async enqueue(
73
- agent: AbstractAgent,
74
- request: () => Promise<RunAgentResult>,
75
- ): Promise<RunAgentResult> {
76
- const threadId = agent.threadId || "default";
77
-
78
- return new Promise((resolve, reject) => {
79
- // Get or create queue for this thread
80
- let queue = this.queues.get(threadId);
81
- if (!queue) {
82
- queue = [];
83
- this.queues.set(threadId, queue);
84
- }
85
-
86
- // Add request to queue
87
- queue.push({ execute: request, resolve, reject });
88
-
89
- // Start processing if not already running
90
- this.processQueue(threadId, agent);
91
- });
92
- }
93
-
94
- private async processQueue(
95
- threadId: string,
96
- agent: AbstractAgent,
97
- ): Promise<void> {
98
- // If already processing this queue, return
99
- if (this.processing.get(threadId)) {
100
- return;
101
- }
102
-
103
- this.processing.set(threadId, true);
104
-
105
- try {
106
- const queue = this.queues.get(threadId);
107
- if (!queue) return;
108
-
109
- while (queue.length > 0) {
110
- const item = queue[0]!;
111
-
112
- try {
113
- // Wait for any active run to complete before processing
114
- await this.waitForAgentIdle(agent);
115
-
116
- // Execute the request
117
- const result = await item.execute();
118
- item.resolve(result);
119
- } catch (error) {
120
- item.reject(
121
- error instanceof Error ? error : new Error(String(error)),
122
- );
123
- }
124
-
125
- // Remove processed item
126
- queue.shift();
127
- }
128
- } finally {
129
- this.processing.set(threadId, false);
130
- }
131
- }
132
-
133
- private waitForAgentIdle(agent: AbstractAgent): Promise<void> {
134
- return new Promise((resolve) => {
135
- if (!agent.isRunning) {
136
- resolve();
137
- return;
138
- }
139
-
140
- let done = false;
141
- const finish = () => {
142
- if (done) return;
143
- done = true;
144
- clearInterval(checkInterval);
145
- sub.unsubscribe();
146
- resolve();
147
- };
148
-
149
- const sub = agent.subscribe({
150
- onRunFinalized: finish,
151
- onRunFailed: finish,
152
- });
153
-
154
- // Fallback for reconnect scenarios where events don't fire
155
- const checkInterval = setInterval(() => {
156
- if (!agent.isRunning) finish();
157
- }, 500);
158
- });
159
- }
160
- }
161
-
162
- // Global queue instance for all MCP app requests
163
- const mcpAppsRequestQueue = new MCPAppsRequestQueue();
164
-
165
- /**
166
- * Activity type for MCP Apps events - must match the middleware's MCPAppsActivityType
167
- */
168
- export const MCPAppsActivityType = "mcp-apps";
169
-
170
- // Zod schema for activity content validation (middleware 0.0.2 format)
171
- export const MCPAppsActivityContentSchema = z.object({
172
- result: z.object({
173
- content: z.array(z.any()).optional(),
174
- structuredContent: z.any().optional(),
175
- isError: z.boolean().optional(),
176
- }),
177
- // Resource URI to fetch (e.g., "ui://server/dashboard")
178
- resourceUri: z.string(),
179
- // MD5 hash of server config (renamed from serverId in 0.0.1)
180
- serverHash: z.string(),
181
- // Optional stable server ID from config (takes precedence over serverHash)
182
- serverId: z.string().optional(),
183
- // Original tool input arguments
184
- toolInput: z.record(z.unknown()).optional(),
185
- });
186
-
187
- export type MCPAppsActivityContent = z.infer<
188
- typeof MCPAppsActivityContentSchema
189
- >;
190
-
191
- // Type for the resource fetched from the server
192
- interface FetchedResource {
193
- uri: string;
194
- mimeType?: string;
195
- text?: string;
196
- blob?: string;
197
- _meta?: {
198
- ui?: {
199
- prefersBorder?: boolean;
200
- csp?: {
201
- connectDomains?: string[];
202
- resourceDomains?: string[];
203
- };
204
- };
205
- };
206
- }
207
-
208
- interface JSONRPCRequest {
209
- jsonrpc: "2.0";
210
- id: string | number;
211
- method: string;
212
- params?: Record<string, unknown>;
213
- }
214
-
215
- interface JSONRPCResponse {
216
- jsonrpc: "2.0";
217
- id: string | number;
218
- result?: unknown;
219
- error?: { code: number; message: string };
220
- }
221
-
222
- interface JSONRPCNotification {
223
- jsonrpc: "2.0";
224
- method: string;
225
- params?: Record<string, unknown>;
226
- }
227
-
228
- type JSONRPCMessage = JSONRPCRequest | JSONRPCResponse | JSONRPCNotification;
229
-
230
- function isRequest(msg: JSONRPCMessage): msg is JSONRPCRequest {
231
- return "id" in msg && "method" in msg;
232
- }
233
-
234
- function isNotification(msg: JSONRPCMessage): msg is JSONRPCNotification {
235
- return !("id" in msg) && "method" in msg;
236
- }
237
-
238
- /**
239
- * Props for the activity renderer component
240
- */
241
- interface MCPAppsActivityRendererProps {
242
- activityType: string;
243
- content: MCPAppsActivityContent;
244
- message: unknown; // ActivityMessage from @ag-ui/core
245
- agent: AbstractAgent | undefined;
246
- }
247
-
248
- /**
249
- * MCP Apps Extension Activity Renderer
250
- *
251
- * Renders MCP Apps UI in a sandboxed iframe with full protocol support.
252
- * Fetches resource content on-demand via proxied MCP requests.
253
- */
254
- export const MCPAppsActivityRenderer: React.FC<MCPAppsActivityRendererProps> =
255
- function MCPAppsActivityRenderer({ content, agent }) {
256
- const { copilotkit } = useCopilotKit();
257
- const containerRef = useRef<HTMLDivElement>(null);
258
- const iframeRef = useRef<HTMLIFrameElement | null>(null);
259
- const [iframeReady, setIframeReady] = useState(false);
260
- const [error, setError] = useState<Error | null>(null);
261
- const [isLoading, setIsLoading] = useState(true);
262
- const [iframeSize, setIframeSize] = useState<{
263
- width?: number;
264
- height?: number;
265
- }>({});
266
- const [fetchedResource, setFetchedResource] =
267
- useState<FetchedResource | null>(null);
268
-
269
- // Use refs for values that shouldn't trigger re-renders but need latest values
270
- const contentRef = useRef(content);
271
- contentRef.current = content;
272
-
273
- // Store agent in a ref for use in async handlers
274
- const agentRef = useRef(agent);
275
- agentRef.current = agent;
276
-
277
- // Ref to track fetch state - survives StrictMode remounts
278
- const fetchStateRef = useRef<{
279
- inProgress: boolean;
280
- promise: Promise<FetchedResource | null> | null;
281
- resourceUri: string | null;
282
- }>({ inProgress: false, promise: null, resourceUri: null });
283
-
284
- // Callback to send a message to the iframe
285
- const sendToIframe = useCallback((msg: JSONRPCMessage) => {
286
- if (iframeRef.current?.contentWindow) {
287
- console.log("[MCPAppsRenderer] Sending to iframe:", msg);
288
- iframeRef.current.contentWindow.postMessage(msg, "*");
289
- }
290
- }, []);
291
-
292
- // Callback to send a JSON-RPC response
293
- const sendResponse = useCallback(
294
- (id: string | number, result: unknown) => {
295
- sendToIframe({
296
- jsonrpc: "2.0",
297
- id,
298
- result,
299
- });
300
- },
301
- [sendToIframe],
302
- );
303
-
304
- // Callback to send a JSON-RPC error response
305
- const sendErrorResponse = useCallback(
306
- (id: string | number, code: number, message: string) => {
307
- sendToIframe({
308
- jsonrpc: "2.0",
309
- id,
310
- error: { code, message },
311
- });
312
- },
313
- [sendToIframe],
314
- );
315
-
316
- // Callback to send a notification
317
- const sendNotification = useCallback(
318
- (method: string, params?: Record<string, unknown>) => {
319
- sendToIframe({
320
- jsonrpc: "2.0",
321
- method,
322
- params: params || {},
323
- });
324
- },
325
- [sendToIframe],
326
- );
327
-
328
- // Effect 0: Fetch the resource content on mount
329
- // Uses ref-based deduplication to handle React StrictMode double-mounting
330
- useEffect(() => {
331
- const { resourceUri, serverHash, serverId } = content;
332
-
333
- // Check if we already have a fetch in progress for this resource
334
- // This handles StrictMode double-mounting - second mount reuses first mount's promise
335
- if (
336
- fetchStateRef.current.inProgress &&
337
- fetchStateRef.current.resourceUri === resourceUri
338
- ) {
339
- // Reuse the existing promise
340
- fetchStateRef.current.promise
341
- ?.then((resource) => {
342
- if (resource) {
343
- setFetchedResource(resource);
344
- setIsLoading(false);
345
- }
346
- })
347
- .catch((err) => {
348
- setError(err instanceof Error ? err : new Error(String(err)));
349
- setIsLoading(false);
350
- });
351
- return;
352
- }
353
-
354
- if (!agent) {
355
- setError(new Error("No agent available to fetch resource"));
356
- setIsLoading(false);
357
- return;
358
- }
359
-
360
- // Mark fetch as in progress
361
- fetchStateRef.current.inProgress = true;
362
- fetchStateRef.current.resourceUri = resourceUri;
363
-
364
- // Create the fetch promise using the queue to serialize requests
365
- const fetchPromise = (async (): Promise<FetchedResource | null> => {
366
- try {
367
- // Use queue to wait for agent to be idle and serialize requests
368
- const runResult = await mcpAppsRequestQueue.enqueue(agent, () =>
369
- agent.runAgent({
370
- forwardedProps: {
371
- __proxiedMCPRequest: {
372
- serverHash,
373
- serverId, // optional, takes precedence if provided
374
- method: "resources/read",
375
- params: { uri: resourceUri },
376
- },
377
- },
378
- }),
379
- );
380
-
381
- // Extract resource from result
382
- // The response format is: { contents: [{ uri, mimeType, text?, blob?, _meta? }] }
383
- const resultData = runResult.result as
384
- | { contents?: FetchedResource[] }
385
- | undefined;
386
- const resource = resultData?.contents?.[0];
387
-
388
- if (!resource) {
389
- throw new Error("No resource content in response");
390
- }
391
-
392
- return resource;
393
- } catch (err) {
394
- console.error("[MCPAppsRenderer] Failed to fetch resource:", err);
395
- throw err;
396
- } finally {
397
- // Mark fetch as complete
398
- fetchStateRef.current.inProgress = false;
399
- }
400
- })();
401
-
402
- // Store the promise for potential reuse
403
- fetchStateRef.current.promise = fetchPromise;
404
-
405
- // Handle the result
406
- fetchPromise
407
- .then((resource) => {
408
- if (resource) {
409
- setFetchedResource(resource);
410
- setIsLoading(false);
411
- }
412
- })
413
- .catch((err) => {
414
- setError(err instanceof Error ? err : new Error(String(err)));
415
- setIsLoading(false);
416
- });
417
-
418
- // No cleanup needed - we want the fetch to complete even if StrictMode unmounts
419
- }, [agent, content]);
420
-
421
- // Effect 1: Setup sandbox proxy iframe and communication (after resource is fetched)
422
- useEffect(() => {
423
- // Wait for resource to be fetched
424
- if (isLoading || !fetchedResource) {
425
- return;
426
- }
427
-
428
- // Capture container reference at effect start (refs are cleared during unmount)
429
- const container = containerRef.current;
430
- if (!container) {
431
- return;
432
- }
433
-
434
- let mounted = true;
435
- let messageHandler: ((event: MessageEvent) => void) | null = null;
436
- let initialListener: ((event: MessageEvent) => void) | null = null;
437
- let createdIframe: HTMLIFrameElement | null = null;
438
-
439
- const setup = async () => {
440
- try {
441
- // Create sandbox proxy iframe
442
- const iframe = document.createElement("iframe");
443
- createdIframe = iframe; // Track for cleanup
444
- iframe.style.width = "100%";
445
- iframe.style.height = "100px"; // Start small, will be resized by size-changed notification
446
- iframe.style.border = "none";
447
- iframe.style.backgroundColor = "transparent";
448
- iframe.style.display = "block";
449
- iframe.setAttribute(
450
- "sandbox",
451
- "allow-scripts allow-same-origin allow-forms",
452
- );
453
-
454
- // Wait for sandbox proxy to be ready
455
- const sandboxReady = new Promise<void>((resolve) => {
456
- initialListener = (event: MessageEvent) => {
457
- if (event.source === iframe.contentWindow) {
458
- if (
459
- event.data?.method === "ui/notifications/sandbox-proxy-ready"
460
- ) {
461
- if (initialListener) {
462
- window.removeEventListener("message", initialListener);
463
- initialListener = null;
464
- }
465
- resolve();
466
- }
467
- }
468
- };
469
- window.addEventListener("message", initialListener);
470
- });
471
-
472
- // Check mounted before adding to DOM (handles StrictMode double-mount)
473
- if (!mounted) {
474
- if (initialListener) {
475
- window.removeEventListener("message", initialListener);
476
- initialListener = null;
477
- }
478
- return;
479
- }
480
-
481
- // Build sandbox HTML with CSP domains from resource metadata
482
- const cspDomains = fetchedResource._meta?.ui?.csp?.resourceDomains;
483
- iframe.srcdoc = buildSandboxHTML(cspDomains);
484
- iframeRef.current = iframe;
485
- container.appendChild(iframe);
486
-
487
- // Wait for sandbox proxy to signal ready
488
- await sandboxReady;
489
- if (!mounted) return;
490
-
491
- console.log("[MCPAppsRenderer] Sandbox proxy ready");
492
-
493
- // Setup message handler for JSON-RPC messages from the inner iframe
494
- messageHandler = async (event: MessageEvent) => {
495
- if (event.source !== iframe.contentWindow) return;
496
-
497
- const msg = event.data as JSONRPCMessage;
498
- if (!msg || typeof msg !== "object" || msg.jsonrpc !== "2.0")
499
- return;
500
-
501
- console.log("[MCPAppsRenderer] Received from iframe:", msg);
502
-
503
- // Handle requests (need response)
504
- if (isRequest(msg)) {
505
- switch (msg.method) {
506
- case "ui/initialize": {
507
- // Respond with host capabilities
508
- sendResponse(msg.id, {
509
- protocolVersion: PROTOCOL_VERSION,
510
- hostInfo: {
511
- name: "CopilotKit MCP Apps Host",
512
- version: "1.0.0",
513
- },
514
- hostCapabilities: {
515
- openLinks: {},
516
- logging: {},
517
- },
518
- hostContext: {
519
- theme: "light",
520
- platform: "web",
521
- },
522
- });
523
- break;
524
- }
525
-
526
- case "ui/message": {
527
- // Add message to CopilotKit chat and optionally invoke agent
528
- const currentAgent = agentRef.current;
529
-
530
- if (!currentAgent) {
531
- console.warn(
532
- "[MCPAppsRenderer] ui/message: No agent available",
533
- );
534
- sendResponse(msg.id, { isError: false });
535
- break;
536
- }
537
-
538
- try {
539
- const params = msg.params as {
540
- role?: string;
541
- content?: Array<{ type: string; text?: string }>;
542
- followUp?: boolean;
543
- };
544
-
545
- const role =
546
- (params.role as "user" | "assistant") || "user";
547
-
548
- // Extract text content from the message
549
- const textContent =
550
- params.content
551
- ?.filter((c) => c.type === "text" && c.text)
552
- .map((c) => c.text)
553
- .join("\n") || "";
554
-
555
- if (textContent) {
556
- currentAgent.addMessage({
557
- id: crypto.randomUUID(),
558
- role,
559
- content: textContent,
560
- });
561
- }
562
-
563
- // Acknowledge the message immediately — don't block on agent run
564
- sendResponse(msg.id, { isError: false });
565
-
566
- // Determine whether to invoke the agent after adding message.
567
- // followUp: true → always invoke agent
568
- // followUp: false → display-only, skip agent
569
- // not specified → invoke for user messages, skip for assistant
570
- const shouldFollowUp = params.followUp ?? role === "user";
571
-
572
- if (shouldFollowUp && textContent) {
573
- // Use copilotkit.runAgent to go through RunHandler — provides
574
- // frontend tools, context, tool execution, and abort support.
575
- // Fire-and-forget: errors are handled by RunHandler's error emission.
576
- mcpAppsRequestQueue
577
- .enqueue(currentAgent, () =>
578
- copilotkit.runAgent({ agent: currentAgent }),
579
- )
580
- .catch((err) =>
581
- console.error(
582
- "[MCPAppsRenderer] ui/message agent run failed:",
583
- err,
584
- ),
585
- );
586
- }
587
- } catch (err) {
588
- console.error("[MCPAppsRenderer] ui/message error:", err);
589
- sendResponse(msg.id, { isError: true });
590
- }
591
- break;
592
- }
593
-
594
- case "ui/open-link": {
595
- // Open URL in new tab
596
- const url = msg.params?.url as string | undefined;
597
- if (url) {
598
- window.open(url, "_blank", "noopener,noreferrer");
599
- sendResponse(msg.id, { isError: false });
600
- } else {
601
- sendErrorResponse(msg.id, -32602, "Missing url parameter");
602
- }
603
- break;
604
- }
605
-
606
- case "tools/call": {
607
- // Proxy tool call to MCP server via agent.runAgent()
608
- const { serverHash, serverId } = contentRef.current;
609
- const currentAgent = agentRef.current;
610
-
611
- if (!serverHash) {
612
- sendErrorResponse(
613
- msg.id,
614
- -32603,
615
- "No server hash available for proxying",
616
- );
617
- break;
618
- }
619
-
620
- if (!currentAgent) {
621
- sendErrorResponse(
622
- msg.id,
623
- -32603,
624
- "No agent available for proxying",
625
- );
626
- break;
627
- }
628
-
629
- try {
630
- // Use queue to wait for agent to be idle and serialize requests
631
- const runResult = await mcpAppsRequestQueue.enqueue(
632
- currentAgent,
633
- () =>
634
- currentAgent.runAgent({
635
- forwardedProps: {
636
- __proxiedMCPRequest: {
637
- serverHash,
638
- serverId, // optional, takes precedence if provided
639
- method: "tools/call",
640
- params: msg.params,
641
- },
642
- },
643
- }),
644
- );
645
-
646
- // The result from runAgent contains the MCP response
647
- sendResponse(msg.id, runResult.result || {});
648
- } catch (err) {
649
- console.error("[MCPAppsRenderer] tools/call error:", err);
650
- sendErrorResponse(msg.id, -32603, String(err));
651
- }
652
- break;
653
- }
654
-
655
- default:
656
- sendErrorResponse(
657
- msg.id,
658
- -32601,
659
- `Method not found: ${msg.method}`,
660
- );
661
- }
662
- }
663
-
664
- // Handle notifications (no response needed)
665
- if (isNotification(msg)) {
666
- switch (msg.method) {
667
- case "ui/notifications/initialized": {
668
- console.log("[MCPAppsRenderer] Inner iframe initialized");
669
- if (mounted) {
670
- setIframeReady(true);
671
- }
672
- break;
673
- }
674
-
675
- case "ui/notifications/size-changed": {
676
- const { width, height } = msg.params || {};
677
- console.log("[MCPAppsRenderer] Size change:", {
678
- width,
679
- height,
680
- });
681
- if (mounted) {
682
- setIframeSize({
683
- width: typeof width === "number" ? width : undefined,
684
- height: typeof height === "number" ? height : undefined,
685
- });
686
- }
687
- break;
688
- }
689
-
690
- case "notifications/message": {
691
- // Logging notification from the app
692
- console.log("[MCPAppsRenderer] App log:", msg.params);
693
- break;
694
- }
695
- }
696
- }
697
- };
698
-
699
- window.addEventListener("message", messageHandler);
700
-
701
- // Extract HTML content from fetched resource
702
- let html: string;
703
- if (fetchedResource.text) {
704
- html = fetchedResource.text;
705
- } else if (fetchedResource.blob) {
706
- html = atob(fetchedResource.blob);
707
- } else {
708
- throw new Error("Resource has no text or blob content");
709
- }
710
-
711
- // Send the resource content to the sandbox proxy
712
- sendNotification("ui/notifications/sandbox-resource-ready", { html });
713
- } catch (err) {
714
- console.error("[MCPAppsRenderer] Setup error:", err);
715
- if (mounted) {
716
- setError(err instanceof Error ? err : new Error(String(err)));
717
- }
718
- }
719
- };
720
-
721
- setup();
722
-
723
- return () => {
724
- mounted = false;
725
- // Clean up initial listener if still active
726
- if (initialListener) {
727
- window.removeEventListener("message", initialListener);
728
- initialListener = null;
729
- }
730
- if (messageHandler) {
731
- window.removeEventListener("message", messageHandler);
732
- }
733
- // Remove the iframe we created (using tracked reference, not DOM query)
734
- // This works even if containerRef.current is null during unmount
735
- if (createdIframe) {
736
- createdIframe.remove();
737
- createdIframe = null;
738
- }
739
- iframeRef.current = null;
740
- };
741
- }, [
742
- isLoading,
743
- fetchedResource,
744
- sendNotification,
745
- sendResponse,
746
- sendErrorResponse,
747
- ]);
748
-
749
- // Effect 2: Update iframe size when it changes
750
- useEffect(() => {
751
- if (iframeRef.current) {
752
- if (iframeSize.width !== undefined) {
753
- // Use minWidth with min() to allow expansion but cap at 100%
754
- iframeRef.current.style.minWidth = `min(${iframeSize.width}px, 100%)`;
755
- iframeRef.current.style.width = "100%";
756
- }
757
- if (iframeSize.height !== undefined) {
758
- iframeRef.current.style.height = `${iframeSize.height}px`;
759
- }
760
- }
761
- }, [iframeSize]);
762
-
763
- // Effect 3: Send tool input when iframe ready
764
- useEffect(() => {
765
- if (iframeReady && content.toolInput) {
766
- console.log("[MCPAppsRenderer] Sending tool input:", content.toolInput);
767
- sendNotification("ui/notifications/tool-input", {
768
- arguments: content.toolInput,
769
- });
770
- }
771
- }, [iframeReady, content.toolInput, sendNotification]);
772
-
773
- // Effect 4: Send tool result when iframe ready
774
- useEffect(() => {
775
- if (iframeReady && content.result) {
776
- console.log("[MCPAppsRenderer] Sending tool result:", content.result);
777
- sendNotification("ui/notifications/tool-result", content.result);
778
- }
779
- }, [iframeReady, content.result, sendNotification]);
780
-
781
- // Determine border styling based on prefersBorder metadata from fetched resource
782
- // true = show border/background, false = none, undefined = host decides (we default to none)
783
- const prefersBorder = fetchedResource?._meta?.ui?.prefersBorder;
784
- const borderStyle =
785
- prefersBorder === true
786
- ? {
787
- borderRadius: "8px",
788
- backgroundColor: "#f9f9f9",
789
- border: "1px solid #e0e0e0",
790
- }
791
- : {};
792
-
793
- return (
794
- <div
795
- ref={containerRef}
796
- style={{
797
- width: "100%",
798
- height: iframeSize.height ? `${iframeSize.height}px` : "auto",
799
- minHeight: "100px",
800
- overflow: "hidden",
801
- position: "relative",
802
- ...borderStyle,
803
- }}
804
- >
805
- {isLoading && (
806
- <div style={{ padding: "1rem", color: "#666" }}>Loading...</div>
807
- )}
808
- {error && (
809
- <div style={{ color: "red", padding: "1rem" }}>
810
- Error: {error.message}
811
- </div>
812
- )}
813
- </div>
814
- );
815
- };