@copilotkit/react-core 1.57.3 → 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 -336
  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,1412 +0,0 @@
1
- import React, {
2
- useState,
3
- useRef,
4
- KeyboardEvent,
5
- ChangeEvent,
6
- useEffect,
7
- useLayoutEffect,
8
- forwardRef,
9
- useImperativeHandle,
10
- useCallback,
11
- useMemo,
12
- } from "react";
13
- import { twMerge } from "tailwind-merge";
14
- import { Plus, Mic, ArrowUp, X, Check, Square, Loader2 } from "lucide-react";
15
-
16
- import {
17
- CopilotChatLabels,
18
- useCopilotChatConfiguration,
19
- CopilotChatDefaultLabels,
20
- } from "../../providers/CopilotChatConfigurationProvider";
21
- import { Button } from "../../components/ui/button";
22
- import {
23
- Tooltip,
24
- TooltipContent,
25
- TooltipTrigger,
26
- } from "../../components/ui/tooltip";
27
- import {
28
- DropdownMenu,
29
- DropdownMenuTrigger,
30
- DropdownMenuContent,
31
- DropdownMenuItem,
32
- DropdownMenuSub,
33
- DropdownMenuSubTrigger,
34
- DropdownMenuSubContent,
35
- DropdownMenuSeparator,
36
- } from "../../components/ui/dropdown-menu";
37
-
38
- import { CopilotChatAudioRecorder } from "./CopilotChatAudioRecorder";
39
- import { renderSlot, WithSlots } from "../../lib/slots";
40
- import { cn } from "../../lib/utils";
41
-
42
- export type CopilotChatInputMode = "input" | "transcribe" | "processing";
43
-
44
- export type ToolsMenuItem = {
45
- label: string;
46
- } & (
47
- | {
48
- action: () => void;
49
- items?: never;
50
- }
51
- | {
52
- action?: never;
53
- items: (ToolsMenuItem | "-")[];
54
- }
55
- );
56
-
57
- type CopilotChatInputSlots = {
58
- textArea: typeof CopilotChatInput.TextArea;
59
- sendButton: typeof CopilotChatInput.SendButton;
60
- startTranscribeButton: typeof CopilotChatInput.StartTranscribeButton;
61
- cancelTranscribeButton: typeof CopilotChatInput.CancelTranscribeButton;
62
- finishTranscribeButton: typeof CopilotChatInput.FinishTranscribeButton;
63
- addMenuButton: typeof CopilotChatInput.AddMenuButton;
64
- audioRecorder: typeof CopilotChatAudioRecorder;
65
- disclaimer: typeof CopilotChatInput.Disclaimer;
66
- };
67
-
68
- type CopilotChatInputRestProps = {
69
- mode?: CopilotChatInputMode;
70
- toolsMenu?: (ToolsMenuItem | "-")[];
71
- autoFocus?: boolean;
72
- onSubmitMessage?: (value: string) => void;
73
- onStop?: () => void;
74
- isRunning?: boolean;
75
- onStartTranscribe?: () => void;
76
- onCancelTranscribe?: () => void;
77
- onFinishTranscribe?: () => void;
78
- onFinishTranscribeWithAudio?: (audioBlob: Blob) => Promise<void>;
79
- onAddFile?: () => void;
80
- value?: string;
81
- onChange?: (value: string) => void;
82
- /** Positioning mode for the input container. Default: 'static' */
83
- positioning?: "static" | "absolute";
84
- /** Keyboard height in pixels for mobile keyboard handling */
85
- keyboardHeight?: number;
86
- /** Ref for the outer positioning container */
87
- containerRef?: React.Ref<HTMLDivElement>;
88
- /** Whether to show the disclaimer. Default: true for absolute positioning, false for static */
89
- showDisclaimer?: boolean;
90
- /**
91
- * Set to `true` when the input sits at the bottom of its container as a
92
- * flex-last-child (visible position is driven by layout, not CSS
93
- * positioning). Triggers reservation of bottom space for the fixed
94
- * CopilotKit license banner via the
95
- * `--copilotkit-license-banner-offset` CSS var so the two don't overlap.
96
- *
97
- * Not needed when `positioning === "absolute"`; that mode already pins the
98
- * input to the bottom and picks up the same reservation automatically.
99
- * Leave unset (default `false`) for inputs rendered mid-layout such as the
100
- * welcome screen, where the banner offset would push the input off-center.
101
- */
102
- bottomAnchored?: boolean;
103
- } & Omit<React.HTMLAttributes<HTMLDivElement>, "onChange">;
104
-
105
- type CopilotChatInputBaseProps = WithSlots<
106
- CopilotChatInputSlots,
107
- CopilotChatInputRestProps
108
- >;
109
-
110
- type CopilotChatInputChildrenArgs = CopilotChatInputBaseProps extends {
111
- children?: infer C;
112
- }
113
- ? C extends (props: infer P) => React.ReactNode
114
- ? P
115
- : never
116
- : never;
117
-
118
- export type CopilotChatInputProps = Omit<
119
- CopilotChatInputBaseProps,
120
- "children"
121
- > & {
122
- children?: (props: CopilotChatInputChildrenArgs) => React.ReactNode;
123
- };
124
-
125
- const SLASH_MENU_MAX_VISIBLE_ITEMS = 5;
126
- const SLASH_MENU_ITEM_HEIGHT_PX = 40;
127
-
128
- export function CopilotChatInput({
129
- mode = "input",
130
- onSubmitMessage,
131
- onStop,
132
- isRunning = false,
133
- onStartTranscribe,
134
- onCancelTranscribe,
135
- onFinishTranscribe,
136
- onFinishTranscribeWithAudio,
137
- onAddFile,
138
- onChange,
139
- value,
140
- toolsMenu,
141
- autoFocus = false,
142
- positioning = "static",
143
- keyboardHeight = 0,
144
- containerRef,
145
- showDisclaimer,
146
- bottomAnchored = false,
147
- textArea,
148
- sendButton,
149
- startTranscribeButton,
150
- cancelTranscribeButton,
151
- finishTranscribeButton,
152
- addMenuButton,
153
- audioRecorder,
154
- disclaimer,
155
- children,
156
- className,
157
- ...props
158
- }: CopilotChatInputProps) {
159
- const isControlled = value !== undefined;
160
- const [internalValue, setInternalValue] = useState<string>(() => value ?? "");
161
-
162
- useEffect(() => {
163
- if (!isControlled && value !== undefined) {
164
- setInternalValue(value);
165
- }
166
- }, [isControlled, value]);
167
-
168
- const resolvedValue = isControlled ? (value ?? "") : internalValue;
169
-
170
- const [layout, setLayout] = useState<"compact" | "expanded">("compact");
171
- const ignoreResizeRef = useRef(false);
172
- const resizeEvaluationRafRef = useRef<number | null>(null);
173
- const isExpanded = mode === "input" && layout === "expanded";
174
- const [commandQuery, setCommandQuery] = useState<string | null>(null);
175
- const [slashHighlightIndex, setSlashHighlightIndex] = useState(0);
176
-
177
- const inputRef = useRef<HTMLTextAreaElement>(null);
178
- const gridRef = useRef<HTMLDivElement>(null);
179
- const addButtonContainerRef = useRef<HTMLDivElement>(null);
180
- const actionsContainerRef = useRef<HTMLDivElement>(null);
181
- const audioRecorderRef =
182
- useRef<React.ElementRef<typeof CopilotChatAudioRecorder>>(null);
183
- const slashMenuRef = useRef<HTMLDivElement>(null);
184
- const config = useCopilotChatConfiguration();
185
- const labels = config?.labels ?? CopilotChatDefaultLabels;
186
-
187
- const previousModalStateRef = useRef<boolean | undefined>(undefined);
188
- const measurementCanvasRef = useRef<HTMLCanvasElement | null>(null);
189
- const measurementsRef = useRef({
190
- singleLineHeight: 0,
191
- maxHeight: 0,
192
- paddingLeft: 0,
193
- paddingRight: 0,
194
- });
195
-
196
- // Cached container dimensions — invalidated on resize, lazily repopulated on next layout pass.
197
- // Eliminates getComputedStyle(grid) + 2x getBoundingClientRect per compact-layout evaluation.
198
- const containerCacheRef = useRef<{
199
- compactWidth: number;
200
- } | null>(null);
201
-
202
- const commandItems = useMemo(() => {
203
- const entries: ToolsMenuItem[] = [];
204
- const seen = new Set<string>();
205
-
206
- const pushItem = (item: ToolsMenuItem | "-") => {
207
- if (item === "-") {
208
- return;
209
- }
210
-
211
- if (item.items && item.items.length > 0) {
212
- for (const nested of item.items) {
213
- pushItem(nested);
214
- }
215
- return;
216
- }
217
-
218
- if (!seen.has(item.label)) {
219
- seen.add(item.label);
220
- entries.push(item);
221
- }
222
- };
223
-
224
- if (onAddFile) {
225
- pushItem({
226
- label: labels.chatInputToolbarAddButtonLabel,
227
- action: onAddFile,
228
- });
229
- }
230
-
231
- if (toolsMenu && toolsMenu.length > 0) {
232
- for (const item of toolsMenu) {
233
- pushItem(item);
234
- }
235
- }
236
-
237
- return entries;
238
- }, [labels.chatInputToolbarAddButtonLabel, onAddFile, toolsMenu]);
239
-
240
- const filteredCommands = useMemo(() => {
241
- if (commandQuery === null) {
242
- return [] as ToolsMenuItem[];
243
- }
244
-
245
- if (commandItems.length === 0) {
246
- return [] as ToolsMenuItem[];
247
- }
248
-
249
- const query = commandQuery.trim().toLowerCase();
250
- if (query.length === 0) {
251
- return commandItems;
252
- }
253
-
254
- const startsWith: ToolsMenuItem[] = [];
255
- const contains: ToolsMenuItem[] = [];
256
- for (const item of commandItems) {
257
- const label = item.label.toLowerCase();
258
- if (label.startsWith(query)) {
259
- startsWith.push(item);
260
- } else if (label.includes(query)) {
261
- contains.push(item);
262
- }
263
- }
264
-
265
- return [...startsWith, ...contains];
266
- }, [commandItems, commandQuery]);
267
-
268
- useEffect(() => {
269
- if (!autoFocus) {
270
- previousModalStateRef.current = config?.isModalOpen;
271
- return;
272
- }
273
-
274
- if (config?.isModalOpen && !previousModalStateRef.current) {
275
- inputRef.current?.focus({ preventScroll: true });
276
- }
277
-
278
- previousModalStateRef.current = config?.isModalOpen;
279
- }, [config?.isModalOpen, autoFocus]);
280
-
281
- useEffect(() => {
282
- if (commandItems.length === 0 && commandQuery !== null) {
283
- setCommandQuery(null);
284
- }
285
- }, [commandItems.length, commandQuery]);
286
-
287
- const previousCommandQueryRef = useRef<string | null>(null);
288
-
289
- useEffect(() => {
290
- if (
291
- commandQuery !== null &&
292
- commandQuery !== previousCommandQueryRef.current &&
293
- filteredCommands.length > 0
294
- ) {
295
- setSlashHighlightIndex(0);
296
- }
297
-
298
- previousCommandQueryRef.current = commandQuery;
299
- }, [commandQuery, filteredCommands.length]);
300
-
301
- useEffect(() => {
302
- if (commandQuery === null) {
303
- setSlashHighlightIndex(0);
304
- return;
305
- }
306
-
307
- if (filteredCommands.length === 0) {
308
- setSlashHighlightIndex(-1);
309
- } else if (
310
- slashHighlightIndex < 0 ||
311
- slashHighlightIndex >= filteredCommands.length
312
- ) {
313
- setSlashHighlightIndex(0);
314
- }
315
- }, [commandQuery, filteredCommands, slashHighlightIndex]);
316
-
317
- // Handle recording based on mode changes
318
- useEffect(() => {
319
- const recorder = audioRecorderRef.current;
320
- if (!recorder) {
321
- return;
322
- }
323
-
324
- if (mode === "transcribe") {
325
- // Start recording when entering transcribe mode
326
- recorder.start().catch(console.error);
327
- } else {
328
- // Stop recording when leaving transcribe mode
329
- if (recorder.state === "recording") {
330
- recorder.stop().catch(console.error);
331
- }
332
- }
333
- }, [mode]);
334
-
335
- useEffect(() => {
336
- if (mode !== "input") {
337
- setLayout("compact");
338
- setCommandQuery(null);
339
- }
340
- }, [mode]);
341
-
342
- const updateSlashState = useCallback(
343
- (value: string) => {
344
- if (commandItems.length === 0) {
345
- setCommandQuery((prev) => (prev === null ? prev : null));
346
- return;
347
- }
348
-
349
- if (value.startsWith("/")) {
350
- const firstLine = value.split(/\r?\n/, 1)[0] ?? "";
351
- const query = firstLine.slice(1);
352
- setCommandQuery((prev) => (prev === query ? prev : query));
353
- } else {
354
- setCommandQuery((prev) => (prev === null ? prev : null));
355
- }
356
- },
357
- [commandItems.length],
358
- );
359
-
360
- useEffect(() => {
361
- updateSlashState(resolvedValue);
362
- }, [resolvedValue, updateSlashState]);
363
-
364
- // Handlers
365
- const handleChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
366
- const nextValue = e.target.value;
367
- if (!isControlled) {
368
- setInternalValue(nextValue);
369
- }
370
- onChange?.(nextValue);
371
- updateSlashState(nextValue);
372
- };
373
-
374
- const clearInputValue = useCallback(() => {
375
- if (!isControlled) {
376
- setInternalValue("");
377
- }
378
-
379
- if (onChange) {
380
- onChange("");
381
- }
382
- }, [isControlled, onChange]);
383
-
384
- const runCommand = useCallback(
385
- (item: ToolsMenuItem) => {
386
- clearInputValue();
387
-
388
- item.action?.();
389
-
390
- setCommandQuery(null);
391
- setSlashHighlightIndex(0);
392
-
393
- requestAnimationFrame(() => {
394
- inputRef.current?.focus();
395
- });
396
- },
397
- [clearInputValue],
398
- );
399
-
400
- const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
401
- // Skip key handling during IME composition (e.g. CJK input).
402
- // The compositionend event will fire separately when composition ends.
403
- if (e.nativeEvent.isComposing || e.keyCode === 229) {
404
- return;
405
- }
406
-
407
- if (commandQuery !== null && mode === "input") {
408
- if (e.key === "ArrowDown") {
409
- if (filteredCommands.length > 0) {
410
- e.preventDefault();
411
- setSlashHighlightIndex((prev) => {
412
- if (filteredCommands.length === 0) {
413
- return prev;
414
- }
415
- const next = prev === -1 ? 0 : (prev + 1) % filteredCommands.length;
416
- return next;
417
- });
418
- }
419
- return;
420
- }
421
-
422
- if (e.key === "ArrowUp") {
423
- if (filteredCommands.length > 0) {
424
- e.preventDefault();
425
- setSlashHighlightIndex((prev) => {
426
- if (filteredCommands.length === 0) {
427
- return prev;
428
- }
429
- if (prev === -1) {
430
- return filteredCommands.length - 1;
431
- }
432
- return prev <= 0 ? filteredCommands.length - 1 : prev - 1;
433
- });
434
- }
435
- return;
436
- }
437
-
438
- if (e.key === "Enter") {
439
- const selected =
440
- slashHighlightIndex >= 0
441
- ? filteredCommands[slashHighlightIndex]
442
- : undefined;
443
- if (selected) {
444
- e.preventDefault();
445
- runCommand(selected);
446
- return;
447
- }
448
- }
449
-
450
- if (e.key === "Escape") {
451
- e.preventDefault();
452
- setCommandQuery(null);
453
- return;
454
- }
455
- }
456
-
457
- if (e.key === "Enter" && !e.shiftKey) {
458
- e.preventDefault();
459
- if (isProcessing) {
460
- onStop?.();
461
- } else {
462
- send();
463
- }
464
- }
465
- };
466
-
467
- const send = () => {
468
- if (!onSubmitMessage) {
469
- return;
470
- }
471
- const trimmed = resolvedValue.trim();
472
- if (!trimmed) {
473
- return;
474
- }
475
-
476
- onSubmitMessage(trimmed);
477
-
478
- // Always clear the input after sending, including controlled mode.
479
- // In controlled mode, onChange("") notifies the parent to reset its state.
480
- if (!isControlled) {
481
- setInternalValue("");
482
- }
483
- onChange?.("");
484
-
485
- if (inputRef.current) {
486
- inputRef.current.focus();
487
- }
488
- };
489
-
490
- const BoundTextArea = renderSlot(textArea, CopilotChatInput.TextArea, {
491
- ref: inputRef,
492
- value: resolvedValue,
493
- onChange: handleChange,
494
- onKeyDown: handleKeyDown,
495
- onCompositionStart: () => {
496
- isComposingRef.current = true;
497
- },
498
- onCompositionEnd: () => {
499
- isComposingRef.current = false;
500
- },
501
- autoFocus: autoFocus,
502
- className: twMerge(
503
- "cpk:w-full cpk:py-3",
504
- isExpanded ? "cpk:px-5" : "cpk:pr-5",
505
- ),
506
- });
507
-
508
- const isProcessing = mode !== "transcribe" && isRunning;
509
- const canSend = resolvedValue.trim().length > 0 && !!onSubmitMessage;
510
- const canStop = !!onStop;
511
-
512
- const handleSendButtonClick = () => {
513
- if (isProcessing) {
514
- onStop?.();
515
- return;
516
- }
517
- send();
518
- };
519
-
520
- const BoundAudioRecorder = renderSlot(
521
- audioRecorder,
522
- CopilotChatAudioRecorder,
523
- {
524
- ref: audioRecorderRef,
525
- },
526
- );
527
-
528
- const BoundSendButton = renderSlot(sendButton, CopilotChatInput.SendButton, {
529
- onClick: handleSendButtonClick,
530
- disabled: isProcessing ? !canStop : !canSend,
531
- children:
532
- isProcessing && canStop ? (
533
- <Square className="cpk:size-[18px] cpk:fill-current" />
534
- ) : undefined,
535
- });
536
-
537
- const BoundStartTranscribeButton = renderSlot(
538
- startTranscribeButton,
539
- CopilotChatInput.StartTranscribeButton,
540
- {
541
- onClick: onStartTranscribe,
542
- },
543
- );
544
-
545
- const BoundCancelTranscribeButton = renderSlot(
546
- cancelTranscribeButton,
547
- CopilotChatInput.CancelTranscribeButton,
548
- {
549
- onClick: onCancelTranscribe,
550
- },
551
- );
552
-
553
- // Handler for finish button - stops recording and passes audio blob
554
- const handleFinishTranscribe = useCallback(async () => {
555
- const recorder = audioRecorderRef.current;
556
- if (recorder && recorder.state === "recording") {
557
- try {
558
- const audioBlob = await recorder.stop();
559
- if (onFinishTranscribeWithAudio) {
560
- await onFinishTranscribeWithAudio(audioBlob);
561
- }
562
- } catch (error) {
563
- console.error("Failed to stop recording:", error);
564
- }
565
- }
566
- // Always call the original handler to reset mode
567
- onFinishTranscribe?.();
568
- }, [onFinishTranscribe, onFinishTranscribeWithAudio]);
569
-
570
- const BoundFinishTranscribeButton = renderSlot(
571
- finishTranscribeButton,
572
- CopilotChatInput.FinishTranscribeButton,
573
- {
574
- onClick: handleFinishTranscribe,
575
- },
576
- );
577
-
578
- const BoundAddMenuButton = renderSlot(
579
- addMenuButton,
580
- CopilotChatInput.AddMenuButton,
581
- {
582
- disabled: mode === "transcribe",
583
- onAddFile,
584
- toolsMenu,
585
- },
586
- );
587
-
588
- const BoundDisclaimer = renderSlot(
589
- disclaimer,
590
- CopilotChatInput.Disclaimer,
591
- {},
592
- );
593
-
594
- // Determine whether to show disclaimer based on prop or positioning default
595
- const shouldShowDisclaimer = showDisclaimer ?? positioning === "absolute";
596
-
597
- if (children) {
598
- const childProps = {
599
- textArea: BoundTextArea,
600
- audioRecorder: BoundAudioRecorder,
601
- sendButton: BoundSendButton,
602
- startTranscribeButton: BoundStartTranscribeButton,
603
- cancelTranscribeButton: BoundCancelTranscribeButton,
604
- finishTranscribeButton: BoundFinishTranscribeButton,
605
- addMenuButton: BoundAddMenuButton,
606
- disclaimer: BoundDisclaimer,
607
- onSubmitMessage,
608
- onStop,
609
- isRunning,
610
- onStartTranscribe,
611
- onCancelTranscribe,
612
- onFinishTranscribe,
613
- onAddFile,
614
- mode,
615
- toolsMenu,
616
- autoFocus,
617
- positioning,
618
- keyboardHeight,
619
- showDisclaimer: shouldShowDisclaimer,
620
- containerRef,
621
- } as CopilotChatInputChildrenArgs;
622
-
623
- return (
624
- <div data-copilotkit style={{ display: "contents" }}>
625
- {children(childProps)}
626
- </div>
627
- );
628
- }
629
-
630
- const handleContainerClick = (e: React.MouseEvent<HTMLDivElement>) => {
631
- // Don't focus if clicking on buttons or other interactive elements
632
- const target = e.target as HTMLElement;
633
- if (
634
- target.tagName !== "BUTTON" &&
635
- !target.closest("button") &&
636
- inputRef.current &&
637
- mode === "input"
638
- ) {
639
- inputRef.current.focus();
640
- }
641
- };
642
-
643
- // Track whether an IME composition is active so we can avoid
644
- // resetting textarea.value during measurement (which would break
645
- // the composition session).
646
- const isComposingRef = useRef(false);
647
-
648
- const ensureMeasurements = useCallback(() => {
649
- const textarea = inputRef.current;
650
- if (!textarea || isComposingRef.current) {
651
- return;
652
- }
653
-
654
- const previousValue = textarea.value;
655
- const previousHeight = textarea.style.height;
656
-
657
- textarea.style.height = "auto";
658
-
659
- const computedStyle = window.getComputedStyle(textarea);
660
- const paddingLeft = parseFloat(computedStyle.paddingLeft) || 0;
661
- const paddingRight = parseFloat(computedStyle.paddingRight) || 0;
662
- const paddingTop = parseFloat(computedStyle.paddingTop) || 0;
663
- const paddingBottom = parseFloat(computedStyle.paddingBottom) || 0;
664
-
665
- textarea.value = "";
666
- const singleLineHeight = textarea.scrollHeight;
667
- textarea.value = previousValue;
668
-
669
- const contentHeight = singleLineHeight - paddingTop - paddingBottom;
670
- const maxHeight = contentHeight * 5 + paddingTop + paddingBottom;
671
-
672
- measurementsRef.current = {
673
- singleLineHeight,
674
- maxHeight,
675
- paddingLeft,
676
- paddingRight,
677
- };
678
-
679
- textarea.style.height = previousHeight;
680
- textarea.style.maxHeight = `${maxHeight}px`;
681
- }, []);
682
-
683
- const adjustTextareaHeight = useCallback(() => {
684
- const textarea = inputRef.current;
685
- if (!textarea) {
686
- return 0;
687
- }
688
-
689
- if (measurementsRef.current.singleLineHeight === 0) {
690
- ensureMeasurements();
691
- }
692
-
693
- const { maxHeight } = measurementsRef.current;
694
- if (maxHeight) {
695
- textarea.style.maxHeight = `${maxHeight}px`;
696
- }
697
-
698
- textarea.style.height = "auto";
699
- const scrollHeight = textarea.scrollHeight;
700
- if (maxHeight) {
701
- textarea.style.height = `${Math.min(scrollHeight, maxHeight)}px`;
702
- } else {
703
- textarea.style.height = `${scrollHeight}px`;
704
- }
705
-
706
- return scrollHeight;
707
- }, [ensureMeasurements]);
708
-
709
- const updateLayout = useCallback((nextLayout: "compact" | "expanded") => {
710
- setLayout((prev) => {
711
- if (prev === nextLayout) {
712
- return prev;
713
- }
714
- ignoreResizeRef.current = true;
715
- return nextLayout;
716
- });
717
- }, []);
718
-
719
- const updateContainerCache = useCallback((): {
720
- compactWidth: number;
721
- } | null => {
722
- const grid = gridRef.current;
723
- const addContainer = addButtonContainerRef.current;
724
- const actionsContainer = actionsContainerRef.current;
725
- if (!grid || !addContainer || !actionsContainer) return null;
726
-
727
- const gridStyles = window.getComputedStyle(grid);
728
- const paddingLeft = parseFloat(gridStyles.paddingLeft) || 0;
729
- const paddingRight = parseFloat(gridStyles.paddingRight) || 0;
730
- const columnGap = parseFloat(gridStyles.columnGap) || 0;
731
- const gridAvailableWidth = grid.clientWidth - paddingLeft - paddingRight;
732
-
733
- if (gridAvailableWidth <= 0) return null;
734
-
735
- const addWidth = addContainer.getBoundingClientRect().width;
736
- const actionsWidth = actionsContainer.getBoundingClientRect().width;
737
- const compactWidth = Math.max(
738
- gridAvailableWidth - addWidth - actionsWidth - columnGap * 2,
739
- 0,
740
- );
741
-
742
- if (compactWidth <= 0) return null;
743
-
744
- const result = { compactWidth };
745
- containerCacheRef.current = result;
746
- return result;
747
- }, []);
748
-
749
- const evaluateLayout = useCallback(() => {
750
- if (mode !== "input") {
751
- updateLayout("compact");
752
- return;
753
- }
754
-
755
- if (
756
- typeof window !== "undefined" &&
757
- typeof window.matchMedia === "function"
758
- ) {
759
- const isMobileViewport = window.matchMedia("(max-width: 767px)").matches;
760
- if (isMobileViewport) {
761
- ensureMeasurements();
762
- adjustTextareaHeight();
763
- updateLayout("expanded");
764
- return;
765
- }
766
- }
767
-
768
- const textarea = inputRef.current;
769
- const grid = gridRef.current;
770
- const addContainer = addButtonContainerRef.current;
771
- const actionsContainer = actionsContainerRef.current;
772
-
773
- if (!textarea || !grid || !addContainer || !actionsContainer) {
774
- return;
775
- }
776
-
777
- if (measurementsRef.current.singleLineHeight === 0) {
778
- ensureMeasurements();
779
- }
780
-
781
- const scrollHeight = adjustTextareaHeight();
782
- const baseline = measurementsRef.current.singleLineHeight;
783
- const hasExplicitBreak = resolvedValue.includes("\n");
784
- const renderedMultiline =
785
- baseline > 0 ? scrollHeight > baseline + 1 : false;
786
- let shouldExpand = hasExplicitBreak || renderedMultiline;
787
-
788
- if (!shouldExpand) {
789
- // Use cached container dimensions (lazily populated on first access, invalidated on resize).
790
- const cache = containerCacheRef.current ?? updateContainerCache();
791
-
792
- if (cache && cache.compactWidth > 0) {
793
- const compactInnerWidth = Math.max(
794
- cache.compactWidth -
795
- (measurementsRef.current.paddingLeft || 0) -
796
- (measurementsRef.current.paddingRight || 0),
797
- 0,
798
- );
799
-
800
- if (compactInnerWidth > 0) {
801
- // Read font fresh each evaluation — getComputedStyle for style-only
802
- // properties is cheap and avoids stale values after CSS/theme changes.
803
- const textareaStyles = window.getComputedStyle(textarea);
804
- let font = textareaStyles.font;
805
- if (!font) {
806
- const {
807
- fontStyle,
808
- fontVariant,
809
- fontWeight,
810
- fontSize,
811
- lineHeight,
812
- fontFamily,
813
- } = textareaStyles;
814
- if (fontSize && fontFamily) {
815
- font = `${fontStyle} ${fontVariant} ${fontWeight} ${fontSize}/${lineHeight} ${fontFamily}`;
816
- }
817
- }
818
-
819
- if (font?.trim()) {
820
- const canvas =
821
- measurementCanvasRef.current ?? document.createElement("canvas");
822
- if (!measurementCanvasRef.current) {
823
- measurementCanvasRef.current = canvas;
824
- }
825
-
826
- const context = canvas.getContext("2d");
827
- if (context) {
828
- context.font = font;
829
-
830
- const lines =
831
- resolvedValue.length > 0 ? resolvedValue.split("\n") : [""];
832
- let longestWidth = 0;
833
- for (const line of lines) {
834
- const metrics = context.measureText(line || " ");
835
- if (metrics.width > longestWidth) {
836
- longestWidth = metrics.width;
837
- }
838
- }
839
-
840
- if (longestWidth > compactInnerWidth) {
841
- shouldExpand = true;
842
- }
843
- } else if (process.env.NODE_ENV !== "production") {
844
- console.warn(
845
- "[CopilotChatInput] canvas.getContext('2d') returned null. " +
846
- "Text-width-based expansion will be unavailable.",
847
- );
848
- }
849
- } else if (process.env.NODE_ENV !== "production") {
850
- console.warn(
851
- "[CopilotChatInput] Could not resolve textarea font for layout measurement. " +
852
- "Text-width-based expansion will be skipped until the next evaluation.",
853
- );
854
- }
855
- }
856
- }
857
- }
858
-
859
- const nextLayout = shouldExpand ? "expanded" : "compact";
860
- updateLayout(nextLayout);
861
- }, [
862
- adjustTextareaHeight,
863
- ensureMeasurements,
864
- mode,
865
- resolvedValue,
866
- updateContainerCache,
867
- updateLayout,
868
- ]);
869
-
870
- useLayoutEffect(() => {
871
- evaluateLayout();
872
- }, [evaluateLayout]);
873
-
874
- useEffect(() => {
875
- if (typeof ResizeObserver === "undefined") {
876
- return;
877
- }
878
-
879
- const textarea = inputRef.current;
880
- const grid = gridRef.current;
881
- const addContainer = addButtonContainerRef.current;
882
- const actionsContainer = actionsContainerRef.current;
883
-
884
- if (!textarea || !grid || !addContainer || !actionsContainer) {
885
- return;
886
- }
887
-
888
- const containerTargets = new Set<Element>([
889
- grid,
890
- addContainer,
891
- actionsContainer,
892
- ]);
893
-
894
- const scheduleEvaluation = (invalidateCache: boolean) => {
895
- if (ignoreResizeRef.current) {
896
- ignoreResizeRef.current = false;
897
- // Self-inflicted resize from a layout toggle — container dimensions
898
- // are unchanged, so keep the cache warm.
899
- return;
900
- }
901
-
902
- if (invalidateCache) {
903
- containerCacheRef.current = null;
904
- }
905
-
906
- if (typeof window === "undefined") {
907
- evaluateLayout();
908
- return;
909
- }
910
-
911
- if (resizeEvaluationRafRef.current !== null) {
912
- cancelAnimationFrame(resizeEvaluationRafRef.current);
913
- }
914
-
915
- resizeEvaluationRafRef.current = window.requestAnimationFrame(() => {
916
- resizeEvaluationRafRef.current = null;
917
- evaluateLayout();
918
- });
919
- };
920
-
921
- // Single observer for all elements — inspect entry.target to decide
922
- // whether to invalidate the container dimension cache. Container
923
- // targets (grid, buttons) changing size means compactWidth may have
924
- // changed; textarea height changes (typing) do not affect it.
925
- const observer = new ResizeObserver((entries) => {
926
- let shouldInvalidate = false;
927
- for (const entry of entries) {
928
- if (containerTargets.has(entry.target)) {
929
- shouldInvalidate = true;
930
- break;
931
- }
932
- }
933
- scheduleEvaluation(shouldInvalidate);
934
- });
935
-
936
- observer.observe(grid);
937
- observer.observe(addContainer);
938
- observer.observe(actionsContainer);
939
- observer.observe(textarea);
940
-
941
- return () => {
942
- observer.disconnect();
943
- if (
944
- typeof window !== "undefined" &&
945
- resizeEvaluationRafRef.current !== null
946
- ) {
947
- cancelAnimationFrame(resizeEvaluationRafRef.current);
948
- resizeEvaluationRafRef.current = null;
949
- }
950
- };
951
- }, [evaluateLayout]);
952
-
953
- const slashMenuVisible = commandQuery !== null && commandItems.length > 0;
954
-
955
- useEffect(() => {
956
- if (!slashMenuVisible || slashHighlightIndex < 0) {
957
- return;
958
- }
959
-
960
- const active = slashMenuRef.current?.querySelector<HTMLElement>(
961
- `[data-slash-index="${slashHighlightIndex}"]`,
962
- );
963
- active?.scrollIntoView({ block: "nearest" });
964
- }, [slashMenuVisible, slashHighlightIndex]);
965
-
966
- const slashMenu = slashMenuVisible ? (
967
- <div
968
- data-testid="copilot-slash-menu"
969
- role="listbox"
970
- aria-label="Slash commands"
971
- ref={slashMenuRef}
972
- className="cpk:absolute cpk:bottom-full cpk:left-0 cpk:right-0 cpk:z-30 cpk:mb-2 cpk:max-h-64 cpk:overflow-y-auto cpk:rounded-lg cpk:border cpk:border-border cpk:bg-white cpk:shadow-lg cpk:dark:border-[#3a3a3a] cpk:dark:bg-[#1f1f1f]"
973
- style={{
974
- maxHeight: `${SLASH_MENU_MAX_VISIBLE_ITEMS * SLASH_MENU_ITEM_HEIGHT_PX}px`,
975
- }}
976
- >
977
- {filteredCommands.length === 0 ? (
978
- <div className="cpk:px-3 cpk:py-2 cpk:text-sm cpk:text-muted-foreground">
979
- No commands found
980
- </div>
981
- ) : (
982
- filteredCommands.map((item, index) => {
983
- const isActive = index === slashHighlightIndex;
984
- return (
985
- <button
986
- key={`${item.label}-${index}`}
987
- type="button"
988
- role="option"
989
- aria-selected={isActive}
990
- data-active={isActive ? "true" : undefined}
991
- data-slash-index={index}
992
- className={twMerge(
993
- "cpk:w-full cpk:px-3 cpk:py-2 cpk:text-left cpk:text-sm cpk:transition-colors",
994
- "cpk:hover:bg-muted cpk:dark:hover:bg-[#2f2f2f]",
995
- isActive
996
- ? "cpk:bg-muted cpk:dark:bg-[#2f2f2f]"
997
- : "cpk:bg-transparent",
998
- )}
999
- onMouseEnter={() => setSlashHighlightIndex(index)}
1000
- onMouseDown={(event) => {
1001
- event.preventDefault();
1002
- runCommand(item);
1003
- }}
1004
- >
1005
- {item.label}
1006
- </button>
1007
- );
1008
- })
1009
- )}
1010
- </div>
1011
- ) : null;
1012
-
1013
- // The input pill (inner component)
1014
- const inputPill = (
1015
- <div
1016
- data-testid="copilot-chat-input"
1017
- className={twMerge(
1018
- // V1 compatibility class for custom styling
1019
- "copilotKitInput",
1020
- // Layout
1021
- "cpk:flex cpk:w-full cpk:flex-col cpk:items-center cpk:justify-center",
1022
- // Interaction
1023
- "cpk:cursor-text",
1024
- // Overflow and clipping
1025
- "cpk:overflow-visible cpk:bg-clip-padding cpk:contain-inline-size",
1026
- // Background
1027
- "cpk:bg-white cpk:dark:bg-[#303030]",
1028
- // Visual effects
1029
- "cpk:shadow-[0_4px_4px_0_#0000000a,0_0_1px_0_#0000009e] cpk:rounded-[28px]",
1030
- )}
1031
- onClick={handleContainerClick}
1032
- data-layout={isExpanded ? "expanded" : "compact"}
1033
- >
1034
- <div
1035
- ref={gridRef}
1036
- className={twMerge(
1037
- "cpk:grid cpk:w-full cpk:gap-x-3 cpk:gap-y-3 cpk:px-3 cpk:py-2",
1038
- isExpanded
1039
- ? "cpk:grid-cols-[auto_minmax(0,1fr)_auto] cpk:grid-rows-[auto_auto]"
1040
- : "cpk:grid-cols-[auto_minmax(0,1fr)_auto] cpk:items-center",
1041
- )}
1042
- data-layout={isExpanded ? "expanded" : "compact"}
1043
- >
1044
- <div
1045
- ref={addButtonContainerRef}
1046
- className={twMerge(
1047
- "cpk:flex cpk:items-center",
1048
- isExpanded ? "cpk:row-start-2" : "cpk:row-start-1",
1049
- "cpk:col-start-1",
1050
- )}
1051
- >
1052
- {BoundAddMenuButton}
1053
- </div>
1054
- <div
1055
- className={twMerge(
1056
- "cpk:relative cpk:flex cpk:min-w-0 cpk:flex-col cpk:min-h-[50px] cpk:justify-center",
1057
- isExpanded
1058
- ? "cpk:col-span-3 cpk:row-start-1"
1059
- : "cpk:col-start-2 cpk:row-start-1",
1060
- )}
1061
- >
1062
- {mode === "transcribe" ? (
1063
- BoundAudioRecorder
1064
- ) : mode === "processing" ? (
1065
- <div className="cpk:flex cpk:w-full cpk:items-center cpk:justify-center cpk:py-3 cpk:px-5">
1066
- <Loader2 className="cpk:size-[26px] cpk:animate-spin cpk:text-muted-foreground" />
1067
- </div>
1068
- ) : (
1069
- <>
1070
- {BoundTextArea}
1071
- {slashMenu}
1072
- </>
1073
- )}
1074
- </div>
1075
- <div
1076
- ref={actionsContainerRef}
1077
- className={twMerge(
1078
- "cpk:flex cpk:items-center cpk:justify-end cpk:gap-2",
1079
- isExpanded
1080
- ? "cpk:col-start-3 cpk:row-start-2"
1081
- : "cpk:col-start-3 cpk:row-start-1",
1082
- )}
1083
- >
1084
- {mode === "transcribe" ? (
1085
- <>
1086
- {onCancelTranscribe && BoundCancelTranscribeButton}
1087
- {onFinishTranscribe && BoundFinishTranscribeButton}
1088
- </>
1089
- ) : (
1090
- <>
1091
- {onStartTranscribe && BoundStartTranscribeButton}
1092
- {BoundSendButton}
1093
- </>
1094
- )}
1095
- </div>
1096
- </div>
1097
- </div>
1098
- );
1099
-
1100
- return (
1101
- <div
1102
- data-copilotkit
1103
- ref={containerRef}
1104
- className={cn(
1105
- "cpk:pointer-events-none cpk:relative cpk:z-20",
1106
- positioning === "absolute" &&
1107
- "cpk:absolute cpk:bottom-0 cpk:left-0 cpk:right-0",
1108
- className,
1109
- )}
1110
- style={{
1111
- transform:
1112
- keyboardHeight > 0 ? `translateY(-${keyboardHeight}px)` : undefined,
1113
- transition: "transform 0.2s ease-out",
1114
- // Reserve room when the fixed license banner is visible so it doesn't
1115
- // overlap the input. Applied only for bottom-anchored inputs (either
1116
- // `positioning === "absolute"`, or an explicitly-flagged flex-last-child
1117
- // input in run state). The welcome-screen input sits mid-layout and
1118
- // must stay still when the banner is present.
1119
- ...(positioning === "absolute" || bottomAnchored
1120
- ? { paddingBottom: "var(--copilotkit-license-banner-offset, 0px)" }
1121
- : {}),
1122
- }}
1123
- {...props}
1124
- >
1125
- <div className="cpk:max-w-3xl cpk:mx-auto cpk:py-0 cpk:px-4 cpk:sm:px-0 cpk:[div[data-sidebar-chat]_&]:px-8 cpk:[div[data-popup-chat]_&]:px-4 cpk:pointer-events-auto">
1126
- {inputPill}
1127
- </div>
1128
- {shouldShowDisclaimer && BoundDisclaimer}
1129
- </div>
1130
- );
1131
- }
1132
-
1133
- // eslint-disable-next-line @typescript-eslint/no-namespace
1134
- export namespace CopilotChatInput {
1135
- export const SendButton: React.FC<
1136
- React.ButtonHTMLAttributes<HTMLButtonElement>
1137
- > = ({ className, children, ...props }) => (
1138
- <div className="cpk:mr-[10px]">
1139
- <Button
1140
- type="button"
1141
- data-testid="copilot-send-button"
1142
- variant="chatInputToolbarPrimary"
1143
- size="chatInputToolbarIcon"
1144
- className={className}
1145
- {...props}
1146
- >
1147
- {children ?? <ArrowUp className="cpk:size-[18px]" />}
1148
- </Button>
1149
- </div>
1150
- );
1151
-
1152
- export const ToolbarButton: React.FC<
1153
- React.ButtonHTMLAttributes<HTMLButtonElement> & {
1154
- icon: React.ReactNode;
1155
- labelKey: keyof CopilotChatLabels;
1156
- defaultClassName?: string;
1157
- }
1158
- > = ({ icon, labelKey, defaultClassName, className, ...props }) => {
1159
- const config = useCopilotChatConfiguration();
1160
- const labels = config?.labels ?? CopilotChatDefaultLabels;
1161
- return (
1162
- <Tooltip>
1163
- <TooltipTrigger asChild>
1164
- <Button
1165
- type="button"
1166
- variant="chatInputToolbarSecondary"
1167
- size="chatInputToolbarIcon"
1168
- className={twMerge(defaultClassName, className)}
1169
- {...props}
1170
- >
1171
- {icon}
1172
- </Button>
1173
- </TooltipTrigger>
1174
- <TooltipContent side="bottom">
1175
- <p>{labels[labelKey]}</p>
1176
- </TooltipContent>
1177
- </Tooltip>
1178
- );
1179
- };
1180
-
1181
- export const StartTranscribeButton: React.FC<
1182
- React.ButtonHTMLAttributes<HTMLButtonElement>
1183
- > = (props) => (
1184
- <ToolbarButton
1185
- data-testid="copilot-start-transcribe-button"
1186
- icon={<Mic className="cpk:size-[18px]" />}
1187
- labelKey="chatInputToolbarStartTranscribeButtonLabel"
1188
- defaultClassName="cpk:mr-2"
1189
- {...props}
1190
- />
1191
- );
1192
-
1193
- export const CancelTranscribeButton: React.FC<
1194
- React.ButtonHTMLAttributes<HTMLButtonElement>
1195
- > = (props) => (
1196
- <ToolbarButton
1197
- data-testid="copilot-cancel-transcribe-button"
1198
- icon={<X className="cpk:size-[18px]" />}
1199
- labelKey="chatInputToolbarCancelTranscribeButtonLabel"
1200
- defaultClassName="cpk:mr-2"
1201
- {...props}
1202
- />
1203
- );
1204
-
1205
- export const FinishTranscribeButton: React.FC<
1206
- React.ButtonHTMLAttributes<HTMLButtonElement>
1207
- > = (props) => (
1208
- <ToolbarButton
1209
- data-testid="copilot-finish-transcribe-button"
1210
- icon={<Check className="cpk:size-[18px]" />}
1211
- labelKey="chatInputToolbarFinishTranscribeButtonLabel"
1212
- defaultClassName="cpk:mr-[10px]"
1213
- {...props}
1214
- />
1215
- );
1216
-
1217
- export const AddMenuButton: React.FC<
1218
- React.ButtonHTMLAttributes<HTMLButtonElement> & {
1219
- toolsMenu?: (ToolsMenuItem | "-")[];
1220
- onAddFile?: () => void;
1221
- }
1222
- > = ({ className, toolsMenu, onAddFile, disabled, ...props }) => {
1223
- const config = useCopilotChatConfiguration();
1224
- const labels = config?.labels ?? CopilotChatDefaultLabels;
1225
-
1226
- // Defer Radix UI rendering until after hydration to avoid ID mismatches
1227
- const [mounted, setMounted] = useState(false);
1228
- useEffect(() => setMounted(true), []);
1229
-
1230
- const menuItems = useMemo<(ToolsMenuItem | "-")[]>(() => {
1231
- const items: (ToolsMenuItem | "-")[] = [];
1232
-
1233
- if (onAddFile) {
1234
- items.push({
1235
- label: labels.chatInputToolbarAddButtonLabel,
1236
- action: onAddFile,
1237
- });
1238
- }
1239
-
1240
- if (toolsMenu && toolsMenu.length > 0) {
1241
- if (items.length > 0) {
1242
- items.push("-");
1243
- }
1244
-
1245
- for (const item of toolsMenu) {
1246
- if (item === "-") {
1247
- if (items.length === 0 || items[items.length - 1] === "-") {
1248
- continue;
1249
- }
1250
- items.push(item);
1251
- } else {
1252
- items.push(item);
1253
- }
1254
- }
1255
-
1256
- while (items.length > 0 && items[items.length - 1] === "-") {
1257
- items.pop();
1258
- }
1259
- }
1260
-
1261
- return items;
1262
- }, [onAddFile, toolsMenu, labels.chatInputToolbarAddButtonLabel]);
1263
-
1264
- const renderMenuItems = useCallback(
1265
- (items: (ToolsMenuItem | "-")[]): React.ReactNode =>
1266
- items.map((item, index) => {
1267
- if (item === "-") {
1268
- return <DropdownMenuSeparator key={`separator-${index}`} />;
1269
- }
1270
-
1271
- if (item.items && item.items.length > 0) {
1272
- return (
1273
- <DropdownMenuSub key={`group-${index}`}>
1274
- <DropdownMenuSubTrigger>{item.label}</DropdownMenuSubTrigger>
1275
- <DropdownMenuSubContent>
1276
- {renderMenuItems(item.items)}
1277
- </DropdownMenuSubContent>
1278
- </DropdownMenuSub>
1279
- );
1280
- }
1281
-
1282
- return (
1283
- <DropdownMenuItem key={`item-${index}`} onClick={item.action}>
1284
- {item.label}
1285
- </DropdownMenuItem>
1286
- );
1287
- }),
1288
- [],
1289
- );
1290
-
1291
- const hasMenuItems = menuItems.length > 0;
1292
- const isDisabled = disabled || !hasMenuItems;
1293
-
1294
- const button = (
1295
- <Button
1296
- type="button"
1297
- data-testid="copilot-add-menu-button"
1298
- variant="chatInputToolbarSecondary"
1299
- size="chatInputToolbarIcon"
1300
- className={twMerge("cpk:ml-1", className)}
1301
- disabled={isDisabled}
1302
- {...props}
1303
- >
1304
- <Plus className="cpk:size-[20px]" />
1305
- </Button>
1306
- );
1307
-
1308
- // Render plain button during SSR; Radix wrappers only after hydration
1309
- if (!mounted) return button;
1310
-
1311
- return (
1312
- <DropdownMenu>
1313
- <Tooltip>
1314
- <TooltipTrigger asChild>
1315
- <DropdownMenuTrigger asChild>{button}</DropdownMenuTrigger>
1316
- </TooltipTrigger>
1317
- <TooltipContent side="bottom">
1318
- <p className="cpk:flex cpk:items-center cpk:gap-1 cpk:text-xs cpk:font-medium">
1319
- <span>Add attachments</span>
1320
- <code className="cpk:rounded cpk:bg-[#4a4a4a] cpk:px-1 cpk:py-[1px] cpk:font-mono cpk:text-[11px] cpk:text-white cpk:dark:bg-[#e0e0e0] cpk:dark:text-black">
1321
- /
1322
- </code>
1323
- </p>
1324
- </TooltipContent>
1325
- </Tooltip>
1326
- {hasMenuItems && (
1327
- <DropdownMenuContent side="top" align="start">
1328
- {renderMenuItems(menuItems)}
1329
- </DropdownMenuContent>
1330
- )}
1331
- </DropdownMenu>
1332
- );
1333
- };
1334
-
1335
- export type TextAreaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement>;
1336
-
1337
- export const TextArea = forwardRef<HTMLTextAreaElement, TextAreaProps>(
1338
- function TextArea(
1339
- { style, className, autoFocus, placeholder, ...props },
1340
- ref,
1341
- ) {
1342
- const internalTextareaRef = useRef<HTMLTextAreaElement>(null);
1343
- const config = useCopilotChatConfiguration();
1344
- const labels = config?.labels ?? CopilotChatDefaultLabels;
1345
-
1346
- useImperativeHandle(
1347
- ref,
1348
- () => internalTextareaRef.current as HTMLTextAreaElement,
1349
- );
1350
-
1351
- useEffect(() => {
1352
- if (autoFocus) {
1353
- internalTextareaRef.current?.focus({ preventScroll: true });
1354
- }
1355
- }, [autoFocus]);
1356
-
1357
- return (
1358
- <textarea
1359
- ref={internalTextareaRef}
1360
- data-testid="copilot-chat-textarea"
1361
- placeholder={placeholder ?? labels.chatInputPlaceholder}
1362
- className={twMerge(
1363
- "cpk:bg-transparent cpk:outline-none cpk:antialiased cpk:font-regular cpk:leading-relaxed cpk:text-[16px] cpk:placeholder:text-[#00000077] cpk:dark:placeholder:text-[#fffc]",
1364
- className,
1365
- )}
1366
- style={{
1367
- overflow: "auto",
1368
- resize: "none",
1369
- ...style,
1370
- }}
1371
- rows={1}
1372
- {...props}
1373
- />
1374
- );
1375
- },
1376
- );
1377
-
1378
- export const AudioRecorder = CopilotChatAudioRecorder;
1379
-
1380
- export const Disclaimer: React.FC<React.HTMLAttributes<HTMLDivElement>> = ({
1381
- className,
1382
- ...props
1383
- }) => {
1384
- const config = useCopilotChatConfiguration();
1385
- const labels = config?.labels ?? CopilotChatDefaultLabels;
1386
- return (
1387
- <div
1388
- className={cn(
1389
- "cpk:text-center cpk:text-xs cpk:text-muted-foreground cpk:py-3 cpk:px-4 cpk:max-w-3xl cpk:mx-auto",
1390
- className,
1391
- )}
1392
- {...props}
1393
- >
1394
- {labels.chatDisclaimerText}
1395
- </div>
1396
- );
1397
- };
1398
- }
1399
-
1400
- CopilotChatInput.TextArea.displayName = "CopilotChatInput.TextArea";
1401
- CopilotChatInput.SendButton.displayName = "CopilotChatInput.SendButton";
1402
- CopilotChatInput.ToolbarButton.displayName = "CopilotChatInput.ToolbarButton";
1403
- CopilotChatInput.StartTranscribeButton.displayName =
1404
- "CopilotChatInput.StartTranscribeButton";
1405
- CopilotChatInput.CancelTranscribeButton.displayName =
1406
- "CopilotChatInput.CancelTranscribeButton";
1407
- CopilotChatInput.FinishTranscribeButton.displayName =
1408
- "CopilotChatInput.FinishTranscribeButton";
1409
- CopilotChatInput.AddMenuButton.displayName = "CopilotChatInput.AddMenuButton";
1410
- CopilotChatInput.Disclaimer.displayName = "CopilotChatInput.Disclaimer";
1411
-
1412
- export default CopilotChatInput;