@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,2416 +0,0 @@
1
- import React, { useRef, useState } from "react";
2
- import {
3
- render,
4
- screen,
5
- fireEvent,
6
- waitFor,
7
- act,
8
- } from "@testing-library/react";
9
- import { z } from "zod";
10
- import { CopilotKitProvider } from "../../../providers/CopilotKitProvider";
11
- import { CopilotChat } from "../CopilotChat";
12
- import {
13
- AbstractAgent,
14
- EventType,
15
- type BaseEvent,
16
- type RunAgentInput,
17
- } from "@ag-ui/client";
18
- import { Observable, Subject } from "rxjs";
19
- import { defineToolCallRenderer, ReactToolCallRenderer } from "../../../types";
20
- import { ToolCallStatus } from "@copilotkit/core";
21
- import { CopilotChatMessageView } from "../CopilotChatMessageView";
22
- import { CopilotChatView, CopilotChatViewProps } from "../CopilotChatView";
23
- import { CopilotChatConfigurationProvider } from "../../../providers/CopilotChatConfigurationProvider";
24
- import { ActivityMessage, AssistantMessage, Message } from "@ag-ui/core";
25
- import {
26
- ReactActivityMessageRenderer,
27
- ReactCustomMessageRenderer,
28
- } from "../../../types";
29
- import CopilotChatInput, { CopilotChatInputProps } from "../CopilotChatInput";
30
- import { CopilotChatSuggestionView } from "../CopilotChatSuggestionView";
31
- import { CopilotChatAssistantMessage } from "../CopilotChatAssistantMessage";
32
-
33
- // A controllable streaming agent to step through events deterministically
34
- class MockStepwiseAgent extends AbstractAgent {
35
- private subject = new Subject<BaseEvent>();
36
-
37
- emit(event: BaseEvent) {
38
- if (event.type === EventType.RUN_STARTED) {
39
- this.isRunning = true;
40
- } else if (
41
- event.type === EventType.RUN_FINISHED ||
42
- event.type === EventType.RUN_ERROR
43
- ) {
44
- this.isRunning = false;
45
- }
46
- this.subject.next(event);
47
- }
48
-
49
- complete() {
50
- this.isRunning = false;
51
- this.subject.complete();
52
- }
53
-
54
- clone(): MockStepwiseAgent {
55
- const cloned = new MockStepwiseAgent();
56
- cloned.agentId = this.agentId;
57
- (cloned as unknown as { subject: Subject<BaseEvent> }).subject =
58
- this.subject;
59
- return cloned;
60
- }
61
-
62
- async detachActiveRun(): Promise<void> {}
63
-
64
- run(_input: RunAgentInput): Observable<BaseEvent> {
65
- return this.subject.asObservable();
66
- }
67
- }
68
-
69
- describe("Tool Call Re-render Prevention", () => {
70
- it("should not re-render a completed tool call when subsequent text is streamed", async () => {
71
- const agent = new MockStepwiseAgent();
72
-
73
- // Track render counts for the tool renderer
74
- let toolRenderCount = 0;
75
- let lastRenderStatus: string | null = null;
76
- let lastRenderArgs: Record<string, unknown> | null = null;
77
-
78
- const renderToolCalls = [
79
- defineToolCallRenderer({
80
- name: "getWeather",
81
- args: z.object({
82
- location: z.string(),
83
- }),
84
- render: ({ status, args, result }) => {
85
- toolRenderCount++;
86
- lastRenderStatus = status;
87
- lastRenderArgs = args as Record<string, unknown>;
88
-
89
- return (
90
- <div data-testid="weather-tool">
91
- <span data-testid="render-count">{toolRenderCount}</span>
92
- <span data-testid="status">{status}</span>
93
- <span data-testid="location">{args.location}</span>
94
- <span data-testid="result">
95
- {result ? String(result) : "pending"}
96
- </span>
97
- </div>
98
- );
99
- },
100
- }),
101
- ] as unknown as ReactToolCallRenderer<unknown>[];
102
-
103
- render(
104
- <CopilotKitProvider
105
- agents__unsafe_dev_only={{ default: agent }}
106
- renderToolCalls={renderToolCalls}
107
- >
108
- <div style={{ height: 400 }}>
109
- <CopilotChat />
110
- </div>
111
- </CopilotKitProvider>,
112
- );
113
-
114
- // Submit a user message to trigger runAgent
115
- const input = await screen.findByRole("textbox");
116
- fireEvent.change(input, { target: { value: "What's the weather?" } });
117
- fireEvent.keyDown(input, { key: "Enter", code: "Enter" });
118
-
119
- await waitFor(() => {
120
- expect(screen.getByText("What's the weather?")).toBeDefined();
121
- });
122
-
123
- const messageId = "m_rerender_test";
124
- const toolCallId = "tc_rerender_test";
125
-
126
- // Start the run
127
- agent.emit({ type: EventType.RUN_STARTED } as BaseEvent);
128
-
129
- // Stream the tool call with complete args
130
- agent.emit({
131
- type: EventType.TOOL_CALL_CHUNK,
132
- toolCallId,
133
- toolCallName: "getWeather",
134
- parentMessageId: messageId,
135
- delta: '{"location":"Paris"}',
136
- } as BaseEvent);
137
-
138
- // Wait for tool to render with InProgress status
139
- await waitFor(() => {
140
- const statusEl = screen.getByTestId("status");
141
- expect(statusEl.textContent).toBe("inProgress");
142
- expect(screen.getByTestId("location").textContent).toBe("Paris");
143
- });
144
-
145
- const renderCountAfterToolCall = toolRenderCount;
146
-
147
- // Send the tool result to complete the tool call
148
- agent.emit({
149
- type: EventType.TOOL_CALL_RESULT,
150
- toolCallId,
151
- messageId: `${messageId}_result`,
152
- content: JSON.stringify({ temperature: 22, condition: "sunny" }),
153
- } as BaseEvent);
154
-
155
- // Wait for tool to show Complete status
156
- await waitFor(() => {
157
- const statusEl = screen.getByTestId("status");
158
- expect(statusEl.textContent).toBe("complete");
159
- });
160
-
161
- const renderCountAfterComplete = toolRenderCount;
162
-
163
- // Sanity check: it should have re-rendered at least once to show complete status
164
- expect(renderCountAfterComplete).toBeGreaterThan(renderCountAfterToolCall);
165
-
166
- // Now stream additional text AFTER the tool call is complete
167
- // This should NOT cause the tool call renderer to re-render
168
- agent.emit({
169
- type: EventType.TEXT_MESSAGE_CHUNK,
170
- messageId: "m_followup",
171
- delta: "The weather in Paris is ",
172
- } as BaseEvent);
173
-
174
- // Wait a moment for React to process
175
- await waitFor(() => {
176
- expect(screen.getByText(/The weather in Paris is/)).toBeDefined();
177
- });
178
-
179
- const renderCountAfterFirstTextChunk = toolRenderCount;
180
-
181
- // Stream more text chunks
182
- agent.emit({
183
- type: EventType.TEXT_MESSAGE_CHUNK,
184
- messageId: "m_followup",
185
- delta: "currently sunny ",
186
- } as BaseEvent);
187
-
188
- await waitFor(() => {
189
- expect(screen.getByText(/currently sunny/)).toBeDefined();
190
- });
191
-
192
- agent.emit({
193
- type: EventType.TEXT_MESSAGE_CHUNK,
194
- messageId: "m_followup",
195
- delta: "with a temperature of 22°C.",
196
- } as BaseEvent);
197
-
198
- await waitFor(() => {
199
- expect(screen.getByText(/22°C/)).toBeDefined();
200
- });
201
-
202
- const renderCountAfterAllText = toolRenderCount;
203
-
204
- // THE KEY ASSERTION: The tool should NOT have re-rendered after it was complete
205
- // and we started streaming text
206
- expect(renderCountAfterAllText).toBe(renderCountAfterComplete);
207
-
208
- // Verify the tool still shows the correct completed state
209
- expect(screen.getByTestId("status").textContent).toBe("complete");
210
- expect(screen.getByTestId("location").textContent).toBe("Paris");
211
- expect(screen.getByTestId("result").textContent).toContain("temperature");
212
-
213
- agent.emit({ type: EventType.RUN_FINISHED } as BaseEvent);
214
- agent.complete();
215
- });
216
-
217
- it("should not re-render a tool call when its arguments have not changed during streaming", async () => {
218
- const agent = new MockStepwiseAgent();
219
-
220
- // Track render counts
221
- let toolRenderCount = 0;
222
-
223
- const renderToolCalls = [
224
- defineToolCallRenderer({
225
- name: "search",
226
- args: z.object({
227
- query: z.string(),
228
- }),
229
- render: ({ status, args }) => {
230
- toolRenderCount++;
231
-
232
- return (
233
- <div data-testid="search-tool">
234
- <span data-testid="search-render-count">{toolRenderCount}</span>
235
- <span data-testid="search-status">{status}</span>
236
- <span data-testid="search-query">{args.query}</span>
237
- </div>
238
- );
239
- },
240
- }),
241
- ] as unknown as ReactToolCallRenderer<unknown>[];
242
-
243
- render(
244
- <CopilotKitProvider
245
- agents__unsafe_dev_only={{ default: agent }}
246
- renderToolCalls={renderToolCalls}
247
- >
248
- <div style={{ height: 400 }}>
249
- <CopilotChat />
250
- </div>
251
- </CopilotKitProvider>,
252
- );
253
-
254
- const input = await screen.findByRole("textbox");
255
- fireEvent.change(input, { target: { value: "Search for something" } });
256
- fireEvent.keyDown(input, { key: "Enter", code: "Enter" });
257
-
258
- await waitFor(() => {
259
- expect(screen.getByText("Search for something")).toBeDefined();
260
- });
261
-
262
- const messageId = "m_search";
263
- const toolCallId = "tc_search";
264
-
265
- agent.emit({ type: EventType.RUN_STARTED } as BaseEvent);
266
-
267
- // Stream complete tool call args
268
- agent.emit({
269
- type: EventType.TOOL_CALL_CHUNK,
270
- toolCallId,
271
- toolCallName: "search",
272
- parentMessageId: messageId,
273
- delta: '{"query":"React hooks"}',
274
- } as BaseEvent);
275
-
276
- await waitFor(() => {
277
- expect(screen.getByTestId("search-query").textContent).toBe(
278
- "React hooks",
279
- );
280
- });
281
-
282
- const renderCountAfterToolCall = toolRenderCount;
283
-
284
- // Stream text in the same message (before tool result)
285
- // This simulates the agent adding explanation text while tool is in progress
286
- agent.emit({
287
- type: EventType.TEXT_MESSAGE_CHUNK,
288
- messageId,
289
- delta: "Let me search for that...",
290
- } as BaseEvent);
291
-
292
- await waitFor(() => {
293
- expect(screen.getByText(/Let me search for that/)).toBeDefined();
294
- });
295
-
296
- const renderCountAfterText = toolRenderCount;
297
-
298
- // The tool call should NOT re-render just because text was added to the message
299
- // since its arguments haven't changed
300
- expect(renderCountAfterText).toBe(renderCountAfterToolCall);
301
-
302
- agent.emit({ type: EventType.RUN_FINISHED } as BaseEvent);
303
- agent.complete();
304
- });
305
-
306
- it("should re-render a tool call when its arguments change during streaming", async () => {
307
- const agent = new MockStepwiseAgent();
308
-
309
- // Track render counts and captured args
310
- let toolRenderCount = 0;
311
- const capturedArgs: string[] = [];
312
-
313
- const renderToolCalls = [
314
- defineToolCallRenderer({
315
- name: "search",
316
- args: z.object({
317
- query: z.string(),
318
- }),
319
- render: ({ args }) => {
320
- toolRenderCount++;
321
- capturedArgs.push(args.query!);
322
-
323
- return (
324
- <div data-testid="search-tool">
325
- <span data-testid="search-render-count">{toolRenderCount}</span>
326
- <span data-testid="search-query">{args.query}</span>
327
- </div>
328
- );
329
- },
330
- }),
331
- ] as unknown as ReactToolCallRenderer<unknown>[];
332
-
333
- render(
334
- <CopilotKitProvider
335
- agents__unsafe_dev_only={{ default: agent }}
336
- renderToolCalls={renderToolCalls}
337
- >
338
- <div style={{ height: 400 }}>
339
- <CopilotChat />
340
- </div>
341
- </CopilotKitProvider>,
342
- );
343
-
344
- const input = await screen.findByRole("textbox");
345
- fireEvent.change(input, { target: { value: "Search for something" } });
346
- fireEvent.keyDown(input, { key: "Enter", code: "Enter" });
347
-
348
- await waitFor(() => {
349
- expect(screen.getByText("Search for something")).toBeDefined();
350
- });
351
-
352
- const messageId = "m_search_update";
353
- const toolCallId = "tc_search_update";
354
-
355
- agent.emit({ type: EventType.RUN_STARTED } as BaseEvent);
356
-
357
- // Stream partial args first
358
- agent.emit({
359
- type: EventType.TOOL_CALL_CHUNK,
360
- toolCallId,
361
- toolCallName: "search",
362
- parentMessageId: messageId,
363
- delta: '{"query":"Rea',
364
- } as BaseEvent);
365
-
366
- await waitFor(() => {
367
- expect(screen.getByTestId("search-query").textContent).toBe("Rea");
368
- });
369
-
370
- const renderCountAfterFirstChunk = toolRenderCount;
371
-
372
- // Stream more args
373
- agent.emit({
374
- type: EventType.TOOL_CALL_CHUNK,
375
- toolCallId,
376
- toolCallName: "search",
377
- parentMessageId: messageId,
378
- delta: 'ct hooks"}',
379
- } as BaseEvent);
380
-
381
- await waitFor(() => {
382
- expect(screen.getByTestId("search-query").textContent).toBe(
383
- "React hooks",
384
- );
385
- });
386
-
387
- const renderCountAfterSecondChunk = toolRenderCount;
388
-
389
- // THE KEY ASSERTION: Tool should re-render when arguments change
390
- expect(renderCountAfterSecondChunk).toBeGreaterThan(
391
- renderCountAfterFirstChunk,
392
- );
393
- expect(capturedArgs).toContain("Rea");
394
- expect(capturedArgs).toContain("React hooks");
395
-
396
- agent.emit({ type: EventType.RUN_FINISHED } as BaseEvent);
397
- agent.complete();
398
- });
399
-
400
- it("should re-render a tool call when status changes to complete", async () => {
401
- const agent = new MockStepwiseAgent();
402
-
403
- let toolRenderCount = 0;
404
- const capturedStatuses: string[] = [];
405
-
406
- const renderToolCalls = [
407
- defineToolCallRenderer({
408
- name: "getData",
409
- args: z.object({ id: z.string() }),
410
- render: ({ status, result }) => {
411
- toolRenderCount++;
412
- capturedStatuses.push(status);
413
-
414
- return (
415
- <div data-testid="data-tool">
416
- <span data-testid="data-status">{status}</span>
417
- <span data-testid="data-result">
418
- {result ? String(result) : "none"}
419
- </span>
420
- </div>
421
- );
422
- },
423
- }),
424
- ] as unknown as ReactToolCallRenderer<unknown>[];
425
-
426
- render(
427
- <CopilotKitProvider
428
- agents__unsafe_dev_only={{ default: agent }}
429
- renderToolCalls={renderToolCalls}
430
- >
431
- <div style={{ height: 400 }}>
432
- <CopilotChat />
433
- </div>
434
- </CopilotKitProvider>,
435
- );
436
-
437
- const input = await screen.findByRole("textbox");
438
- fireEvent.change(input, { target: { value: "Get data" } });
439
- fireEvent.keyDown(input, { key: "Enter", code: "Enter" });
440
-
441
- await waitFor(() => {
442
- expect(screen.getByText("Get data")).toBeDefined();
443
- });
444
-
445
- const messageId = "m_data";
446
- const toolCallId = "tc_data";
447
-
448
- agent.emit({ type: EventType.RUN_STARTED } as BaseEvent);
449
-
450
- // Send tool call
451
- agent.emit({
452
- type: EventType.TOOL_CALL_CHUNK,
453
- toolCallId,
454
- toolCallName: "getData",
455
- parentMessageId: messageId,
456
- delta: '{"id":"123"}',
457
- } as BaseEvent);
458
-
459
- await waitFor(() => {
460
- expect(screen.getByTestId("data-status").textContent).toBe("inProgress");
461
- });
462
-
463
- const renderCountBeforeResult = toolRenderCount;
464
-
465
- // Send tool result
466
- agent.emit({
467
- type: EventType.TOOL_CALL_RESULT,
468
- toolCallId,
469
- messageId: `${messageId}_result`,
470
- content: JSON.stringify({ data: "found" }),
471
- } as BaseEvent);
472
-
473
- await waitFor(() => {
474
- expect(screen.getByTestId("data-status").textContent).toBe("complete");
475
- });
476
-
477
- const renderCountAfterResult = toolRenderCount;
478
-
479
- // THE KEY ASSERTION: Tool should re-render when status changes
480
- expect(renderCountAfterResult).toBeGreaterThan(renderCountBeforeResult);
481
- expect(capturedStatuses).toContain("inProgress");
482
- expect(capturedStatuses).toContain("complete");
483
-
484
- agent.emit({ type: EventType.RUN_FINISHED } as BaseEvent);
485
- agent.complete();
486
- });
487
- });
488
-
489
- describe("Text Message Re-render Prevention", () => {
490
- it("should not re-render a previous assistant message when a new message streams in", async () => {
491
- // Track render counts per message ID
492
- const renderCounts: Record<string, number> = {};
493
-
494
- // Custom assistant message component that tracks renders
495
- const TrackedAssistantMessage: React.FC<{
496
- message: AssistantMessage;
497
- messages?: Message[];
498
- isRunning?: boolean;
499
- }> = ({ message }) => {
500
- // Increment render count for this message
501
- renderCounts[message.id] = (renderCounts[message.id] || 0) + 1;
502
-
503
- return (
504
- <div data-testid={`assistant-message-${message.id}`}>
505
- <span data-testid={`content-${message.id}`}>{message.content}</span>
506
- <span data-testid={`render-count-${message.id}`}>
507
- {renderCounts[message.id]}
508
- </span>
509
- </div>
510
- );
511
- };
512
-
513
- // Initial messages - one complete assistant message
514
- const initialMessages: Message[] = [
515
- {
516
- id: "msg-1",
517
- role: "assistant",
518
- content: "Hello! How can I help you today?",
519
- } as AssistantMessage,
520
- ];
521
-
522
- const { rerender } = render(
523
- <CopilotKitProvider>
524
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
525
- <CopilotChatMessageView
526
- messages={initialMessages}
527
- isRunning={false}
528
- assistantMessage={TrackedAssistantMessage as any}
529
- />
530
- </CopilotChatConfigurationProvider>
531
- </CopilotKitProvider>,
532
- );
533
-
534
- // Verify first message rendered
535
- await waitFor(() => {
536
- expect(screen.getByTestId("assistant-message-msg-1")).toBeDefined();
537
- });
538
-
539
- const firstMessageRenderCountAfterInitial = renderCounts["msg-1"];
540
- expect(firstMessageRenderCountAfterInitial).toBe(1);
541
-
542
- // Simulate streaming a second message - first chunk
543
- const messagesWithSecondPartial: Message[] = [
544
- ...initialMessages,
545
- {
546
- id: "msg-2",
547
- role: "assistant",
548
- content: "Let me help",
549
- } as AssistantMessage,
550
- ];
551
-
552
- rerender(
553
- <CopilotKitProvider>
554
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
555
- <CopilotChatMessageView
556
- messages={messagesWithSecondPartial}
557
- isRunning={true}
558
- assistantMessage={TrackedAssistantMessage as any}
559
- />
560
- </CopilotChatConfigurationProvider>
561
- </CopilotKitProvider>,
562
- );
563
-
564
- await waitFor(() => {
565
- expect(screen.getByTestId("assistant-message-msg-2")).toBeDefined();
566
- });
567
-
568
- const firstMessageRenderCountAfterSecondMessage = renderCounts["msg-1"];
569
-
570
- // Continue streaming the second message
571
- const messagesWithMoreContent: Message[] = [
572
- ...initialMessages,
573
- {
574
- id: "msg-2",
575
- role: "assistant",
576
- content: "Let me help you with that task.",
577
- } as AssistantMessage,
578
- ];
579
-
580
- rerender(
581
- <CopilotKitProvider>
582
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
583
- <CopilotChatMessageView
584
- messages={messagesWithMoreContent}
585
- isRunning={true}
586
- assistantMessage={TrackedAssistantMessage as any}
587
- />
588
- </CopilotChatConfigurationProvider>
589
- </CopilotKitProvider>,
590
- );
591
-
592
- await waitFor(() => {
593
- expect(screen.getByTestId("content-msg-2").textContent).toBe(
594
- "Let me help you with that task.",
595
- );
596
- });
597
-
598
- // Stream even more content
599
- const messagesWithEvenMoreContent: Message[] = [
600
- ...initialMessages,
601
- {
602
- id: "msg-2",
603
- role: "assistant",
604
- content: "Let me help you with that task. Here's what I found:",
605
- } as AssistantMessage,
606
- ];
607
-
608
- rerender(
609
- <CopilotKitProvider>
610
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
611
- <CopilotChatMessageView
612
- messages={messagesWithEvenMoreContent}
613
- isRunning={true}
614
- assistantMessage={TrackedAssistantMessage as any}
615
- />
616
- </CopilotChatConfigurationProvider>
617
- </CopilotKitProvider>,
618
- );
619
-
620
- await waitFor(() => {
621
- expect(screen.getByTestId("content-msg-2").textContent).toContain(
622
- "Here's what I found",
623
- );
624
- });
625
-
626
- const firstMessageRenderCountAfterAllStreaming = renderCounts["msg-1"];
627
-
628
- // THE KEY ASSERTION: The first message should NOT have re-rendered
629
- // when the second message was streaming
630
- expect(firstMessageRenderCountAfterAllStreaming).toBe(
631
- firstMessageRenderCountAfterInitial,
632
- );
633
-
634
- // Verify the second message did update (it should have rendered multiple times)
635
- expect(renderCounts["msg-2"]).toBeGreaterThan(1);
636
- });
637
-
638
- it("should not re-render a user message when assistant message streams", async () => {
639
- const renderCounts: Record<string, number> = {};
640
-
641
- const TrackedAssistantMessage: React.FC<{
642
- message: AssistantMessage;
643
- messages?: Message[];
644
- isRunning?: boolean;
645
- }> = ({ message }) => {
646
- renderCounts[message.id] = (renderCounts[message.id] || 0) + 1;
647
- return (
648
- <div data-testid={`assistant-message-${message.id}`}>
649
- <span data-testid={`content-${message.id}`}>{message.content}</span>
650
- </div>
651
- );
652
- };
653
-
654
- const TrackedUserMessage: React.FC<{
655
- message: Message;
656
- }> = ({ message }) => {
657
- renderCounts[message.id] = (renderCounts[message.id] || 0) + 1;
658
- return (
659
- <div data-testid={`user-message-${message.id}`}>
660
- <span data-testid={`user-content-${message.id}`}>
661
- {typeof message.content === "string" ? message.content : ""}
662
- </span>
663
- <span data-testid={`user-render-count-${message.id}`}>
664
- {renderCounts[message.id]}
665
- </span>
666
- </div>
667
- );
668
- };
669
-
670
- const initialMessages: Message[] = [
671
- {
672
- id: "user-1",
673
- role: "user",
674
- content: "Hello!",
675
- },
676
- ];
677
-
678
- const { rerender } = render(
679
- <CopilotKitProvider>
680
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
681
- <CopilotChatMessageView
682
- messages={initialMessages}
683
- isRunning={false}
684
- assistantMessage={TrackedAssistantMessage as any}
685
- userMessage={TrackedUserMessage as any}
686
- />
687
- </CopilotChatConfigurationProvider>
688
- </CopilotKitProvider>,
689
- );
690
-
691
- await waitFor(() => {
692
- expect(screen.getByTestId("user-message-user-1")).toBeDefined();
693
- });
694
-
695
- const userMessageRenderCountInitial = renderCounts["user-1"];
696
- expect(userMessageRenderCountInitial).toBe(1);
697
-
698
- // Add assistant response and stream it
699
- const messagesWithAssistant: Message[] = [
700
- ...initialMessages,
701
- {
702
- id: "assistant-1",
703
- role: "assistant",
704
- content: "Hi there!",
705
- } as AssistantMessage,
706
- ];
707
-
708
- rerender(
709
- <CopilotKitProvider>
710
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
711
- <CopilotChatMessageView
712
- messages={messagesWithAssistant}
713
- isRunning={true}
714
- assistantMessage={TrackedAssistantMessage as any}
715
- userMessage={TrackedUserMessage as any}
716
- />
717
- </CopilotChatConfigurationProvider>
718
- </CopilotKitProvider>,
719
- );
720
-
721
- // Stream more content
722
- const messagesWithMoreAssistant: Message[] = [
723
- ...initialMessages,
724
- {
725
- id: "assistant-1",
726
- role: "assistant",
727
- content: "Hi there! How can I assist you today?",
728
- } as AssistantMessage,
729
- ];
730
-
731
- rerender(
732
- <CopilotKitProvider>
733
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
734
- <CopilotChatMessageView
735
- messages={messagesWithMoreAssistant}
736
- isRunning={true}
737
- assistantMessage={TrackedAssistantMessage as any}
738
- userMessage={TrackedUserMessage as any}
739
- />
740
- </CopilotChatConfigurationProvider>
741
- </CopilotKitProvider>,
742
- );
743
-
744
- await waitFor(() => {
745
- expect(screen.getByTestId("content-assistant-1").textContent).toContain(
746
- "How can I assist",
747
- );
748
- });
749
-
750
- const userMessageRenderCountAfterStreaming = renderCounts["user-1"];
751
-
752
- // THE KEY ASSERTION: User message should not re-render when assistant streams
753
- expect(userMessageRenderCountAfterStreaming).toBe(
754
- userMessageRenderCountInitial,
755
- );
756
- });
757
-
758
- it("should re-render an assistant message when its content changes", async () => {
759
- const renderCounts: Record<string, number> = {};
760
- const capturedContent: string[] = [];
761
-
762
- const TrackedAssistantMessage: React.FC<{
763
- message: AssistantMessage;
764
- messages?: Message[];
765
- isRunning?: boolean;
766
- }> = ({ message }) => {
767
- renderCounts[message.id] = (renderCounts[message.id] || 0) + 1;
768
- capturedContent.push(message.content ?? "");
769
- return (
770
- <div data-testid={`assistant-message-${message.id}`}>
771
- <span data-testid={`content-${message.id}`}>{message.content}</span>
772
- </div>
773
- );
774
- };
775
-
776
- const initialMessages: Message[] = [
777
- {
778
- id: "msg-1",
779
- role: "assistant",
780
- content: "Hello",
781
- } as AssistantMessage,
782
- ];
783
-
784
- const { rerender } = render(
785
- <CopilotKitProvider>
786
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
787
- <CopilotChatMessageView
788
- messages={initialMessages}
789
- isRunning={true}
790
- assistantMessage={TrackedAssistantMessage as any}
791
- />
792
- </CopilotChatConfigurationProvider>
793
- </CopilotKitProvider>,
794
- );
795
-
796
- await waitFor(() => {
797
- expect(screen.getByTestId("assistant-message-msg-1")).toBeDefined();
798
- });
799
-
800
- const renderCountAfterInitial = renderCounts["msg-1"]!;
801
- expect(renderCountAfterInitial).toBe(1);
802
-
803
- // Update message content (streaming)
804
- const updatedMessages: Message[] = [
805
- {
806
- id: "msg-1",
807
- role: "assistant",
808
- content: "Hello! How can I help",
809
- } as AssistantMessage,
810
- ];
811
-
812
- rerender(
813
- <CopilotKitProvider>
814
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
815
- <CopilotChatMessageView
816
- messages={updatedMessages}
817
- isRunning={true}
818
- assistantMessage={TrackedAssistantMessage as any}
819
- />
820
- </CopilotChatConfigurationProvider>
821
- </CopilotKitProvider>,
822
- );
823
-
824
- await waitFor(() => {
825
- expect(screen.getByTestId("content-msg-1").textContent).toBe(
826
- "Hello! How can I help",
827
- );
828
- });
829
-
830
- const renderCountAfterUpdate = renderCounts["msg-1"]!;
831
-
832
- // THE KEY ASSERTION: Message should re-render when content changes
833
- expect(renderCountAfterUpdate).toBeGreaterThan(renderCountAfterInitial);
834
- expect(capturedContent).toContain("Hello");
835
- expect(capturedContent).toContain("Hello! How can I help");
836
- });
837
-
838
- it("should re-render a user message when its content changes", async () => {
839
- const renderCounts: Record<string, number> = {};
840
- const capturedContent: string[] = [];
841
-
842
- const TrackedUserMessage: React.FC<{
843
- message: Message;
844
- }> = ({ message }) => {
845
- renderCounts[message.id] = (renderCounts[message.id] || 0) + 1;
846
- const content =
847
- typeof message.content === "string" ? message.content : "";
848
- capturedContent.push(content);
849
- return (
850
- <div data-testid={`user-message-${message.id}`}>
851
- <span data-testid={`user-content-${message.id}`}>{content}</span>
852
- </div>
853
- );
854
- };
855
-
856
- const initialMessages: Message[] = [
857
- {
858
- id: "user-1",
859
- role: "user",
860
- content: "Initial message",
861
- },
862
- ];
863
-
864
- const { rerender } = render(
865
- <CopilotKitProvider>
866
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
867
- <CopilotChatMessageView
868
- messages={initialMessages}
869
- isRunning={false}
870
- userMessage={TrackedUserMessage as any}
871
- />
872
- </CopilotChatConfigurationProvider>
873
- </CopilotKitProvider>,
874
- );
875
-
876
- await waitFor(() => {
877
- expect(screen.getByTestId("user-message-user-1")).toBeDefined();
878
- });
879
-
880
- const renderCountAfterInitial = renderCounts["user-1"]!;
881
- expect(renderCountAfterInitial).toBe(1);
882
-
883
- // Update user message content (e.g., editing)
884
- const updatedMessages: Message[] = [
885
- {
886
- id: "user-1",
887
- role: "user",
888
- content: "Updated message",
889
- },
890
- ];
891
-
892
- rerender(
893
- <CopilotKitProvider>
894
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
895
- <CopilotChatMessageView
896
- messages={updatedMessages}
897
- isRunning={false}
898
- userMessage={TrackedUserMessage as any}
899
- />
900
- </CopilotChatConfigurationProvider>
901
- </CopilotKitProvider>,
902
- );
903
-
904
- await waitFor(() => {
905
- expect(screen.getByTestId("user-content-user-1").textContent).toBe(
906
- "Updated message",
907
- );
908
- });
909
-
910
- const renderCountAfterUpdate = renderCounts["user-1"]!;
911
-
912
- // THE KEY ASSERTION: User message should re-render when content changes
913
- expect(renderCountAfterUpdate).toBeGreaterThan(renderCountAfterInitial);
914
- expect(capturedContent).toContain("Initial message");
915
- expect(capturedContent).toContain("Updated message");
916
- });
917
- });
918
-
919
- describe("Activity Message Re-render Prevention", () => {
920
- it("should not re-render a previous activity message when a new message streams in", async () => {
921
- // Track render counts per message ID
922
- const renderCounts: Record<string, number> = {};
923
-
924
- // Custom activity renderer that tracks renders
925
- const activityRenderer: ReactActivityMessageRenderer<{
926
- status: string;
927
- percent: number;
928
- }> = {
929
- activityType: "search-progress",
930
- content: z.object({ status: z.string(), percent: z.number() }),
931
- render: ({ content, message }) => {
932
- renderCounts[message.id] = (renderCounts[message.id] || 0) + 1;
933
- return (
934
- <div data-testid={`activity-${message.id}`}>
935
- <span data-testid={`activity-content-${message.id}`}>
936
- {content.status} - {content.percent}%
937
- </span>
938
- <span data-testid={`activity-render-count-${message.id}`}>
939
- {renderCounts[message.id]}
940
- </span>
941
- </div>
942
- );
943
- },
944
- };
945
-
946
- // Initial messages - one activity message
947
- const initialMessages: Message[] = [
948
- {
949
- id: "activity-1",
950
- role: "activity",
951
- activityType: "search-progress",
952
- content: { status: "Searching", percent: 50 },
953
- } as ActivityMessage,
954
- ];
955
-
956
- const { rerender } = render(
957
- <CopilotKitProvider renderActivityMessages={[activityRenderer]}>
958
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
959
- <CopilotChatMessageView messages={initialMessages} isRunning={true} />
960
- </CopilotChatConfigurationProvider>
961
- </CopilotKitProvider>,
962
- );
963
-
964
- // Verify first activity rendered
965
- await waitFor(() => {
966
- expect(screen.getByTestId("activity-activity-1")).toBeDefined();
967
- });
968
-
969
- const firstActivityRenderCountAfterInitial = renderCounts["activity-1"];
970
- expect(firstActivityRenderCountAfterInitial).toBe(1);
971
-
972
- // Add a second activity message
973
- const messagesWithSecondActivity: Message[] = [
974
- ...initialMessages,
975
- {
976
- id: "activity-2",
977
- role: "activity",
978
- activityType: "search-progress",
979
- content: { status: "Processing", percent: 75 },
980
- } as ActivityMessage,
981
- ];
982
-
983
- rerender(
984
- <CopilotKitProvider renderActivityMessages={[activityRenderer]}>
985
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
986
- <CopilotChatMessageView
987
- messages={messagesWithSecondActivity}
988
- isRunning={true}
989
- />
990
- </CopilotChatConfigurationProvider>
991
- </CopilotKitProvider>,
992
- );
993
-
994
- await waitFor(() => {
995
- expect(screen.getByTestId("activity-activity-2")).toBeDefined();
996
- });
997
-
998
- // Update the second activity message
999
- const messagesWithUpdatedSecondActivity: Message[] = [
1000
- initialMessages[0]!,
1001
- {
1002
- id: "activity-2",
1003
- role: "activity",
1004
- activityType: "search-progress",
1005
- content: { status: "Almost done", percent: 90 },
1006
- } as ActivityMessage,
1007
- ];
1008
-
1009
- rerender(
1010
- <CopilotKitProvider renderActivityMessages={[activityRenderer]}>
1011
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1012
- <CopilotChatMessageView
1013
- messages={messagesWithUpdatedSecondActivity}
1014
- isRunning={true}
1015
- />
1016
- </CopilotChatConfigurationProvider>
1017
- </CopilotKitProvider>,
1018
- );
1019
-
1020
- await waitFor(() => {
1021
- expect(
1022
- screen.getByTestId("activity-content-activity-2").textContent,
1023
- ).toContain("Almost done");
1024
- });
1025
-
1026
- const firstActivityRenderCountAfterAllUpdates = renderCounts["activity-1"];
1027
-
1028
- // THE KEY ASSERTION: The first activity should NOT have re-rendered
1029
- // when the second activity was added or updated
1030
- expect(firstActivityRenderCountAfterAllUpdates).toBe(
1031
- firstActivityRenderCountAfterInitial,
1032
- );
1033
-
1034
- // Verify the second activity did update (it should have rendered multiple times)
1035
- expect(renderCounts["activity-2"]).toBeGreaterThan(1);
1036
- });
1037
-
1038
- it("should not re-render an activity message when an assistant message streams", async () => {
1039
- const renderCounts: Record<string, number> = {};
1040
-
1041
- const activityRenderer: ReactActivityMessageRenderer<{ status: string }> = {
1042
- activityType: "progress",
1043
- content: z.object({ status: z.string() }),
1044
- render: ({ content, message }) => {
1045
- renderCounts[message.id] = (renderCounts[message.id] || 0) + 1;
1046
- return (
1047
- <div data-testid={`activity-${message.id}`}>{content.status}</div>
1048
- );
1049
- },
1050
- };
1051
-
1052
- const TrackedAssistantMessage: React.FC<{
1053
- message: AssistantMessage;
1054
- messages?: Message[];
1055
- isRunning?: boolean;
1056
- }> = ({ message }) => {
1057
- renderCounts[message.id] = (renderCounts[message.id] || 0) + 1;
1058
- return (
1059
- <div data-testid={`assistant-${message.id}`}>{message.content}</div>
1060
- );
1061
- };
1062
-
1063
- const initialMessages: Message[] = [
1064
- {
1065
- id: "activity-1",
1066
- role: "activity",
1067
- activityType: "progress",
1068
- content: { status: "Loading..." },
1069
- } as ActivityMessage,
1070
- ];
1071
-
1072
- const { rerender } = render(
1073
- <CopilotKitProvider renderActivityMessages={[activityRenderer]}>
1074
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1075
- <CopilotChatMessageView
1076
- messages={initialMessages}
1077
- isRunning={true}
1078
- assistantMessage={TrackedAssistantMessage as any}
1079
- />
1080
- </CopilotChatConfigurationProvider>
1081
- </CopilotKitProvider>,
1082
- );
1083
-
1084
- await waitFor(() => {
1085
- expect(screen.getByTestId("activity-activity-1")).toBeDefined();
1086
- });
1087
-
1088
- const activityRenderCountInitial = renderCounts["activity-1"];
1089
- expect(activityRenderCountInitial).toBe(1);
1090
-
1091
- // Add an assistant message and stream it
1092
- const messagesWithAssistant: Message[] = [
1093
- ...initialMessages,
1094
- {
1095
- id: "assistant-1",
1096
- role: "assistant",
1097
- content: "Here's what I found...",
1098
- } as AssistantMessage,
1099
- ];
1100
-
1101
- rerender(
1102
- <CopilotKitProvider renderActivityMessages={[activityRenderer]}>
1103
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1104
- <CopilotChatMessageView
1105
- messages={messagesWithAssistant}
1106
- isRunning={true}
1107
- assistantMessage={TrackedAssistantMessage as any}
1108
- />
1109
- </CopilotChatConfigurationProvider>
1110
- </CopilotKitProvider>,
1111
- );
1112
-
1113
- // Stream more content
1114
- const messagesWithMoreAssistant: Message[] = [
1115
- initialMessages[0]!,
1116
- {
1117
- id: "assistant-1",
1118
- role: "assistant",
1119
- content: "Here's what I found... The results show that...",
1120
- } as AssistantMessage,
1121
- ];
1122
-
1123
- rerender(
1124
- <CopilotKitProvider renderActivityMessages={[activityRenderer]}>
1125
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1126
- <CopilotChatMessageView
1127
- messages={messagesWithMoreAssistant}
1128
- isRunning={true}
1129
- assistantMessage={TrackedAssistantMessage as any}
1130
- />
1131
- </CopilotChatConfigurationProvider>
1132
- </CopilotKitProvider>,
1133
- );
1134
-
1135
- await waitFor(() => {
1136
- expect(screen.getByTestId("assistant-assistant-1").textContent).toContain(
1137
- "The results show",
1138
- );
1139
- });
1140
-
1141
- const activityRenderCountAfterStreaming = renderCounts["activity-1"];
1142
-
1143
- // THE KEY ASSERTION: Activity message should not re-render when assistant streams
1144
- expect(activityRenderCountAfterStreaming).toBe(activityRenderCountInitial);
1145
- });
1146
-
1147
- it("should re-render an activity message when its content changes", async () => {
1148
- const renderCounts: Record<string, number> = {};
1149
- const capturedContent: { status: string; percent: number }[] = [];
1150
-
1151
- const activityRenderer: ReactActivityMessageRenderer<{
1152
- status: string;
1153
- percent: number;
1154
- }> = {
1155
- activityType: "progress",
1156
- content: z.object({ status: z.string(), percent: z.number() }),
1157
- render: ({ content, message }) => {
1158
- renderCounts[message.id] = (renderCounts[message.id] || 0) + 1;
1159
- capturedContent.push({ ...content });
1160
- return (
1161
- <div data-testid={`activity-${message.id}`}>
1162
- <span data-testid={`activity-status-${message.id}`}>
1163
- {content.status}
1164
- </span>
1165
- <span data-testid={`activity-percent-${message.id}`}>
1166
- {content.percent}
1167
- </span>
1168
- </div>
1169
- );
1170
- },
1171
- };
1172
-
1173
- const initialMessages: Message[] = [
1174
- {
1175
- id: "activity-1",
1176
- role: "activity",
1177
- activityType: "progress",
1178
- content: { status: "Starting", percent: 0 },
1179
- } as ActivityMessage,
1180
- ];
1181
-
1182
- const { rerender } = render(
1183
- <CopilotKitProvider renderActivityMessages={[activityRenderer]}>
1184
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1185
- <CopilotChatMessageView messages={initialMessages} isRunning={true} />
1186
- </CopilotChatConfigurationProvider>
1187
- </CopilotKitProvider>,
1188
- );
1189
-
1190
- await waitFor(() => {
1191
- expect(screen.getByTestId("activity-activity-1")).toBeDefined();
1192
- });
1193
-
1194
- const renderCountAfterInitial = renderCounts["activity-1"]!;
1195
- expect(renderCountAfterInitial).toBe(1);
1196
-
1197
- // Update activity content (progress update)
1198
- const updatedMessages: Message[] = [
1199
- {
1200
- id: "activity-1",
1201
- role: "activity",
1202
- activityType: "progress",
1203
- content: { status: "Processing", percent: 50 },
1204
- } as ActivityMessage,
1205
- ];
1206
-
1207
- rerender(
1208
- <CopilotKitProvider renderActivityMessages={[activityRenderer]}>
1209
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1210
- <CopilotChatMessageView messages={updatedMessages} isRunning={true} />
1211
- </CopilotChatConfigurationProvider>
1212
- </CopilotKitProvider>,
1213
- );
1214
-
1215
- await waitFor(() => {
1216
- expect(screen.getByTestId("activity-status-activity-1").textContent).toBe(
1217
- "Processing",
1218
- );
1219
- expect(
1220
- screen.getByTestId("activity-percent-activity-1").textContent,
1221
- ).toBe("50");
1222
- });
1223
-
1224
- const renderCountAfterUpdate = renderCounts["activity-1"]!;
1225
-
1226
- // THE KEY ASSERTION: Activity should re-render when content changes
1227
- expect(renderCountAfterUpdate).toBeGreaterThan(renderCountAfterInitial);
1228
- expect(capturedContent).toContainEqual({ status: "Starting", percent: 0 });
1229
- expect(capturedContent).toContainEqual({
1230
- status: "Processing",
1231
- percent: 50,
1232
- });
1233
- });
1234
-
1235
- it("should re-render an activity message when its activityType changes", async () => {
1236
- const renderCounts: Record<string, number> = {};
1237
-
1238
- const progressRenderer: ReactActivityMessageRenderer<{ status: string }> = {
1239
- activityType: "progress",
1240
- content: z.object({ status: z.string() }),
1241
- render: ({ content, message }) => {
1242
- renderCounts[message.id] = (renderCounts[message.id] || 0) + 1;
1243
- return (
1244
- <div data-testid={`activity-${message.id}`}>
1245
- <span data-testid={`activity-type-${message.id}`}>progress</span>
1246
- <span data-testid={`activity-status-${message.id}`}>
1247
- {content.status}
1248
- </span>
1249
- </div>
1250
- );
1251
- },
1252
- };
1253
-
1254
- const completedRenderer: ReactActivityMessageRenderer<{ result: string }> =
1255
- {
1256
- activityType: "completed",
1257
- content: z.object({ result: z.string() }),
1258
- render: ({ content, message }) => {
1259
- renderCounts[message.id] = (renderCounts[message.id] || 0) + 1;
1260
- return (
1261
- <div data-testid={`activity-${message.id}`}>
1262
- <span data-testid={`activity-type-${message.id}`}>completed</span>
1263
- <span data-testid={`activity-result-${message.id}`}>
1264
- {content.result}
1265
- </span>
1266
- </div>
1267
- );
1268
- },
1269
- };
1270
-
1271
- const initialMessages: Message[] = [
1272
- {
1273
- id: "activity-1",
1274
- role: "activity",
1275
- activityType: "progress",
1276
- content: { status: "Loading..." },
1277
- } as ActivityMessage,
1278
- ];
1279
-
1280
- const { rerender } = render(
1281
- <CopilotKitProvider
1282
- renderActivityMessages={[progressRenderer, completedRenderer]}
1283
- >
1284
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1285
- <CopilotChatMessageView messages={initialMessages} isRunning={true} />
1286
- </CopilotChatConfigurationProvider>
1287
- </CopilotKitProvider>,
1288
- );
1289
-
1290
- await waitFor(() => {
1291
- expect(screen.getByTestId("activity-type-activity-1").textContent).toBe(
1292
- "progress",
1293
- );
1294
- });
1295
-
1296
- const renderCountAfterInitial = renderCounts["activity-1"]!;
1297
- expect(renderCountAfterInitial).toBe(1);
1298
-
1299
- // Change activity type
1300
- const updatedMessages: Message[] = [
1301
- {
1302
- id: "activity-1",
1303
- role: "activity",
1304
- activityType: "completed",
1305
- content: { result: "Done!" },
1306
- } as ActivityMessage,
1307
- ];
1308
-
1309
- rerender(
1310
- <CopilotKitProvider
1311
- renderActivityMessages={[progressRenderer, completedRenderer]}
1312
- >
1313
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1314
- <CopilotChatMessageView
1315
- messages={updatedMessages}
1316
- isRunning={false}
1317
- />
1318
- </CopilotChatConfigurationProvider>
1319
- </CopilotKitProvider>,
1320
- );
1321
-
1322
- await waitFor(() => {
1323
- expect(screen.getByTestId("activity-type-activity-1").textContent).toBe(
1324
- "completed",
1325
- );
1326
- });
1327
-
1328
- const renderCountAfterTypeChange = renderCounts["activity-1"]!;
1329
-
1330
- // THE KEY ASSERTION: Activity should re-render when activityType changes
1331
- expect(renderCountAfterTypeChange).toBeGreaterThan(renderCountAfterInitial);
1332
- });
1333
- });
1334
-
1335
- describe("Custom Message Re-render Prevention", () => {
1336
- it("should not re-render a custom message for a previous message when a new message streams in", async () => {
1337
- const agent = new MockStepwiseAgent();
1338
-
1339
- // Track render counts by message ID and position
1340
- const renderCounts: Record<string, number> = {};
1341
-
1342
- // Custom message renderer that tracks renders
1343
- const customRenderer: ReactCustomMessageRenderer = {
1344
- render: ({ message, position }) => {
1345
- // Only render for assistant messages in "after" position
1346
- if (message.role !== "assistant" || position !== "after") {
1347
- return null;
1348
- }
1349
-
1350
- const key = `${message.id}-${position}`;
1351
- renderCounts[key] = (renderCounts[key] || 0) + 1;
1352
-
1353
- return (
1354
- <div data-testid={`custom-${message.id}`}>
1355
- <span data-testid={`custom-content-${message.id}`}>
1356
- Custom content for {message.id}
1357
- </span>
1358
- <span data-testid={`custom-render-count-${message.id}`}>
1359
- {renderCounts[key]}
1360
- </span>
1361
- </div>
1362
- );
1363
- },
1364
- };
1365
-
1366
- // Initial messages - one assistant message
1367
- const initialMessages: Message[] = [
1368
- {
1369
- id: "assistant-1",
1370
- role: "assistant",
1371
- content: "Hello! How can I help you?",
1372
- } as AssistantMessage,
1373
- ];
1374
-
1375
- const { rerender } = render(
1376
- <CopilotKitProvider
1377
- agents__unsafe_dev_only={{ default: agent }}
1378
- renderCustomMessages={[customRenderer]}
1379
- >
1380
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1381
- <CopilotChatMessageView
1382
- messages={initialMessages}
1383
- isRunning={false}
1384
- />
1385
- </CopilotChatConfigurationProvider>
1386
- </CopilotKitProvider>,
1387
- );
1388
-
1389
- // Verify first custom message rendered
1390
- await waitFor(() => {
1391
- expect(screen.getByTestId("custom-assistant-1")).toBeDefined();
1392
- });
1393
-
1394
- const firstCustomRenderCountAfterInitial =
1395
- renderCounts["assistant-1-after"];
1396
- expect(firstCustomRenderCountAfterInitial).toBe(1);
1397
-
1398
- // Add a second assistant message
1399
- const messagesWithSecond: Message[] = [
1400
- ...initialMessages,
1401
- {
1402
- id: "assistant-2",
1403
- role: "assistant",
1404
- content: "Here's some more info...",
1405
- } as AssistantMessage,
1406
- ];
1407
-
1408
- rerender(
1409
- <CopilotKitProvider
1410
- agents__unsafe_dev_only={{ default: agent }}
1411
- renderCustomMessages={[customRenderer]}
1412
- >
1413
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1414
- <CopilotChatMessageView
1415
- messages={messagesWithSecond}
1416
- isRunning={true}
1417
- />
1418
- </CopilotChatConfigurationProvider>
1419
- </CopilotKitProvider>,
1420
- );
1421
-
1422
- await waitFor(() => {
1423
- expect(screen.getByTestId("custom-assistant-2")).toBeDefined();
1424
- });
1425
-
1426
- // Update the second message (streaming more content)
1427
- const messagesWithUpdatedSecond: Message[] = [
1428
- initialMessages[0]!,
1429
- {
1430
- id: "assistant-2",
1431
- role: "assistant",
1432
- content: "Here's some more info... Let me explain in detail.",
1433
- } as AssistantMessage,
1434
- ];
1435
-
1436
- rerender(
1437
- <CopilotKitProvider
1438
- agents__unsafe_dev_only={{ default: agent }}
1439
- renderCustomMessages={[customRenderer]}
1440
- >
1441
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1442
- <CopilotChatMessageView
1443
- messages={messagesWithUpdatedSecond}
1444
- isRunning={true}
1445
- />
1446
- </CopilotChatConfigurationProvider>
1447
- </CopilotKitProvider>,
1448
- );
1449
-
1450
- // Stream even more content
1451
- const messagesWithMoreContent: Message[] = [
1452
- initialMessages[0]!,
1453
- {
1454
- id: "assistant-2",
1455
- role: "assistant",
1456
- content:
1457
- "Here's some more info... Let me explain in detail. This is comprehensive.",
1458
- } as AssistantMessage,
1459
- ];
1460
-
1461
- rerender(
1462
- <CopilotKitProvider
1463
- agents__unsafe_dev_only={{ default: agent }}
1464
- renderCustomMessages={[customRenderer]}
1465
- >
1466
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1467
- <CopilotChatMessageView
1468
- messages={messagesWithMoreContent}
1469
- isRunning={false}
1470
- />
1471
- </CopilotChatConfigurationProvider>
1472
- </CopilotKitProvider>,
1473
- );
1474
-
1475
- const firstCustomRenderCountAfterAllUpdates =
1476
- renderCounts["assistant-1-after"];
1477
-
1478
- // THE KEY ASSERTION: The first custom message should NOT have re-rendered
1479
- // when the second message was streaming
1480
- expect(firstCustomRenderCountAfterAllUpdates).toBe(
1481
- firstCustomRenderCountAfterInitial,
1482
- );
1483
-
1484
- // Verify the second custom message did update
1485
- expect(renderCounts["assistant-2-after"]).toBeGreaterThan(1);
1486
- });
1487
-
1488
- it("should not re-render custom messages when isRunning changes but message content is the same", async () => {
1489
- const agent = new MockStepwiseAgent();
1490
- const renderCounts: Record<string, number> = {};
1491
-
1492
- const customRenderer: ReactCustomMessageRenderer = {
1493
- render: ({ message, position }) => {
1494
- if (message.role !== "assistant" || position !== "after") {
1495
- return null;
1496
- }
1497
-
1498
- const key = `${message.id}-${position}`;
1499
- renderCounts[key] = (renderCounts[key] || 0) + 1;
1500
-
1501
- return (
1502
- <div data-testid={`custom-${message.id}`}>
1503
- Render count: {renderCounts[key]}
1504
- </div>
1505
- );
1506
- },
1507
- };
1508
-
1509
- const messages: Message[] = [
1510
- {
1511
- id: "assistant-1",
1512
- role: "assistant",
1513
- content: "Complete message",
1514
- } as AssistantMessage,
1515
- ];
1516
-
1517
- const { rerender } = render(
1518
- <CopilotKitProvider
1519
- agents__unsafe_dev_only={{ default: agent }}
1520
- renderCustomMessages={[customRenderer]}
1521
- >
1522
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1523
- <CopilotChatMessageView messages={messages} isRunning={true} />
1524
- </CopilotChatConfigurationProvider>
1525
- </CopilotKitProvider>,
1526
- );
1527
-
1528
- await waitFor(() => {
1529
- expect(screen.getByTestId("custom-assistant-1")).toBeDefined();
1530
- });
1531
-
1532
- const renderCountWhileRunning = renderCounts["assistant-1-after"]!;
1533
- expect(renderCountWhileRunning).toBe(1);
1534
-
1535
- // Change isRunning to false (but same messages)
1536
- rerender(
1537
- <CopilotKitProvider
1538
- agents__unsafe_dev_only={{ default: agent }}
1539
- renderCustomMessages={[customRenderer]}
1540
- >
1541
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1542
- <CopilotChatMessageView messages={messages} isRunning={false} />
1543
- </CopilotChatConfigurationProvider>
1544
- </CopilotKitProvider>,
1545
- );
1546
-
1547
- const renderCountAfterRunningChanged = renderCounts["assistant-1-after"]!;
1548
-
1549
- // THE KEY ASSERTION: Custom message should not re-render just because isRunning changed
1550
- expect(renderCountAfterRunningChanged).toBe(renderCountWhileRunning);
1551
- });
1552
-
1553
- it("should re-render a custom message when its message content changes", async () => {
1554
- const agent = new MockStepwiseAgent();
1555
- const renderCounts: Record<string, number> = {};
1556
- const capturedContent: string[] = [];
1557
-
1558
- const customRenderer: ReactCustomMessageRenderer = {
1559
- render: ({ message, position }) => {
1560
- if (message.role !== "assistant" || position !== "after") {
1561
- return null;
1562
- }
1563
-
1564
- const key = `${message.id}-${position}`;
1565
- renderCounts[key] = (renderCounts[key] || 0) + 1;
1566
- const content =
1567
- typeof message.content === "string" ? message.content : "";
1568
- capturedContent.push(content);
1569
-
1570
- return (
1571
- <div data-testid={`custom-${message.id}`}>
1572
- <span data-testid={`custom-content-${message.id}`}>{content}</span>
1573
- <span data-testid={`custom-render-count-${message.id}`}>
1574
- {renderCounts[key]}
1575
- </span>
1576
- </div>
1577
- );
1578
- },
1579
- };
1580
-
1581
- const initialMessages: Message[] = [
1582
- {
1583
- id: "assistant-1",
1584
- role: "assistant",
1585
- content: "Hello",
1586
- } as AssistantMessage,
1587
- ];
1588
-
1589
- const { rerender } = render(
1590
- <CopilotKitProvider
1591
- agents__unsafe_dev_only={{ default: agent }}
1592
- renderCustomMessages={[customRenderer]}
1593
- >
1594
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1595
- <CopilotChatMessageView messages={initialMessages} isRunning={true} />
1596
- </CopilotChatConfigurationProvider>
1597
- </CopilotKitProvider>,
1598
- );
1599
-
1600
- await waitFor(() => {
1601
- expect(screen.getByTestId("custom-assistant-1")).toBeDefined();
1602
- });
1603
-
1604
- const renderCountAfterInitial = renderCounts["assistant-1-after"]!;
1605
- expect(renderCountAfterInitial).toBe(1);
1606
-
1607
- // Update message content (streaming)
1608
- const updatedMessages: Message[] = [
1609
- {
1610
- id: "assistant-1",
1611
- role: "assistant",
1612
- content: "Hello! How can I help you today?",
1613
- } as AssistantMessage,
1614
- ];
1615
-
1616
- rerender(
1617
- <CopilotKitProvider
1618
- agents__unsafe_dev_only={{ default: agent }}
1619
- renderCustomMessages={[customRenderer]}
1620
- >
1621
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1622
- <CopilotChatMessageView messages={updatedMessages} isRunning={true} />
1623
- </CopilotChatConfigurationProvider>
1624
- </CopilotKitProvider>,
1625
- );
1626
-
1627
- await waitFor(() => {
1628
- expect(screen.getByTestId("custom-content-assistant-1").textContent).toBe(
1629
- "Hello! How can I help you today?",
1630
- );
1631
- });
1632
-
1633
- const renderCountAfterUpdate = renderCounts["assistant-1-after"]!;
1634
-
1635
- // THE KEY ASSERTION: Custom message should re-render when content changes
1636
- expect(renderCountAfterUpdate).toBeGreaterThan(renderCountAfterInitial);
1637
- expect(capturedContent).toContain("Hello");
1638
- expect(capturedContent).toContain("Hello! How can I help you today?");
1639
- });
1640
-
1641
- it("should re-render a custom message when its message role changes", async () => {
1642
- const agent = new MockStepwiseAgent();
1643
- const renderCounts: Record<string, number> = {};
1644
-
1645
- const customRenderer: ReactCustomMessageRenderer = {
1646
- render: ({ message, position }) => {
1647
- if (position !== "after") {
1648
- return null;
1649
- }
1650
-
1651
- const key = `${message.id}-${position}`;
1652
- renderCounts[key] = (renderCounts[key] || 0) + 1;
1653
-
1654
- return (
1655
- <div data-testid={`custom-${message.id}`}>
1656
- <span data-testid={`custom-role-${message.id}`}>
1657
- {message.role}
1658
- </span>
1659
- <span data-testid={`custom-render-count-${message.id}`}>
1660
- {renderCounts[key]}
1661
- </span>
1662
- </div>
1663
- );
1664
- },
1665
- };
1666
-
1667
- const initialMessages: Message[] = [
1668
- {
1669
- id: "msg-1",
1670
- role: "user",
1671
- content: "Hello",
1672
- },
1673
- ];
1674
-
1675
- const { rerender } = render(
1676
- <CopilotKitProvider
1677
- agents__unsafe_dev_only={{ default: agent }}
1678
- renderCustomMessages={[customRenderer]}
1679
- >
1680
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1681
- <CopilotChatMessageView
1682
- messages={initialMessages}
1683
- isRunning={false}
1684
- />
1685
- </CopilotChatConfigurationProvider>
1686
- </CopilotKitProvider>,
1687
- );
1688
-
1689
- await waitFor(() => {
1690
- expect(screen.getByTestId("custom-role-msg-1").textContent).toBe("user");
1691
- });
1692
-
1693
- const renderCountAfterInitial = renderCounts["msg-1-after"]!;
1694
- expect(renderCountAfterInitial).toBe(1);
1695
-
1696
- // Change message role (unusual but possible)
1697
- const updatedMessages: Message[] = [
1698
- {
1699
- id: "msg-1",
1700
- role: "assistant",
1701
- content: "Hello",
1702
- } as AssistantMessage,
1703
- ];
1704
-
1705
- rerender(
1706
- <CopilotKitProvider
1707
- agents__unsafe_dev_only={{ default: agent }}
1708
- renderCustomMessages={[customRenderer]}
1709
- >
1710
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1711
- <CopilotChatMessageView
1712
- messages={updatedMessages}
1713
- isRunning={false}
1714
- />
1715
- </CopilotChatConfigurationProvider>
1716
- </CopilotKitProvider>,
1717
- );
1718
-
1719
- await waitFor(() => {
1720
- expect(screen.getByTestId("custom-role-msg-1").textContent).toBe(
1721
- "assistant",
1722
- );
1723
- });
1724
-
1725
- const renderCountAfterRoleChange = renderCounts["msg-1-after"]!;
1726
-
1727
- // THE KEY ASSERTION: Custom message should re-render when role changes
1728
- expect(renderCountAfterRoleChange).toBeGreaterThan(renderCountAfterInitial);
1729
- });
1730
- });
1731
-
1732
- describe("Input Component Re-render Prevention", () => {
1733
- it("should not re-render the input component when messages stream in", async () => {
1734
- let inputRenderCount = 0;
1735
-
1736
- // Custom input component that tracks renders
1737
- const TrackedInput: React.FC<CopilotChatInputProps> = (props) => {
1738
- inputRenderCount++;
1739
- return (
1740
- <div data-testid="tracked-input">
1741
- <span data-testid="input-render-count">{inputRenderCount}</span>
1742
- <CopilotChatInput {...props} />
1743
- </div>
1744
- );
1745
- };
1746
-
1747
- // Use a stable callback reference to properly test memoization
1748
- const stableOnSubmit = () => {};
1749
-
1750
- const initialMessages: Message[] = [
1751
- {
1752
- id: "msg-1",
1753
- role: "assistant",
1754
- content: "Hello!",
1755
- } as AssistantMessage,
1756
- ];
1757
-
1758
- const { rerender } = render(
1759
- <CopilotKitProvider>
1760
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1761
- <CopilotChatView
1762
- messages={initialMessages}
1763
- isRunning={false}
1764
- input={TrackedInput as any}
1765
- onSubmitMessage={stableOnSubmit}
1766
- />
1767
- </CopilotChatConfigurationProvider>
1768
- </CopilotKitProvider>,
1769
- );
1770
-
1771
- await waitFor(() => {
1772
- expect(screen.getByTestId("tracked-input")).toBeDefined();
1773
- });
1774
-
1775
- const renderCountAfterInitial = inputRenderCount;
1776
- expect(renderCountAfterInitial).toBe(1);
1777
-
1778
- // Stream a new message (add more content)
1779
- const updatedMessages: Message[] = [
1780
- ...initialMessages,
1781
- {
1782
- id: "msg-2",
1783
- role: "assistant",
1784
- content: "How can I help?",
1785
- } as AssistantMessage,
1786
- ];
1787
-
1788
- rerender(
1789
- <CopilotKitProvider>
1790
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1791
- <CopilotChatView
1792
- messages={updatedMessages}
1793
- isRunning={false}
1794
- input={TrackedInput as any}
1795
- onSubmitMessage={stableOnSubmit}
1796
- />
1797
- </CopilotChatConfigurationProvider>
1798
- </CopilotKitProvider>,
1799
- );
1800
-
1801
- // Continue streaming
1802
- const moreMessages: Message[] = [
1803
- ...initialMessages,
1804
- {
1805
- id: "msg-2",
1806
- role: "assistant",
1807
- content: "How can I help you today?",
1808
- } as AssistantMessage,
1809
- ];
1810
-
1811
- rerender(
1812
- <CopilotKitProvider>
1813
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1814
- <CopilotChatView
1815
- messages={moreMessages}
1816
- isRunning={false}
1817
- input={TrackedInput as any}
1818
- onSubmitMessage={stableOnSubmit}
1819
- />
1820
- </CopilotChatConfigurationProvider>
1821
- </CopilotKitProvider>,
1822
- );
1823
-
1824
- // Even more streaming
1825
- const evenMoreMessages: Message[] = [
1826
- ...initialMessages,
1827
- {
1828
- id: "msg-2",
1829
- role: "assistant",
1830
- content: "How can I help you today? I'm here to assist.",
1831
- } as AssistantMessage,
1832
- ];
1833
-
1834
- rerender(
1835
- <CopilotKitProvider>
1836
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1837
- <CopilotChatView
1838
- messages={evenMoreMessages}
1839
- isRunning={false}
1840
- input={TrackedInput as any}
1841
- onSubmitMessage={stableOnSubmit}
1842
- />
1843
- </CopilotChatConfigurationProvider>
1844
- </CopilotKitProvider>,
1845
- );
1846
-
1847
- const renderCountAfterStreaming = inputRenderCount;
1848
-
1849
- // THE KEY ASSERTION: Input should NOT re-render when messages change
1850
- // (since input props haven't changed)
1851
- expect(renderCountAfterStreaming).toBe(renderCountAfterInitial);
1852
- });
1853
-
1854
- it("should re-render a replaced input component when its internal state changes", async () => {
1855
- let externalRenderCount = 0;
1856
-
1857
- // Custom input with internal state - uses useState to track clicks
1858
- const InputWithInternalState: React.FC<CopilotChatInputProps> = (props) => {
1859
- const [clickCount, setClickCount] = useState(0);
1860
- externalRenderCount++;
1861
-
1862
- return (
1863
- <div data-testid="stateful-input">
1864
- <span data-testid="external-render-count">{externalRenderCount}</span>
1865
- <span data-testid="click-count">{clickCount}</span>
1866
- <button
1867
- data-testid="increment-button"
1868
- onClick={() => setClickCount((c) => c + 1)}
1869
- >
1870
- Increment
1871
- </button>
1872
- <CopilotChatInput {...props} />
1873
- </div>
1874
- );
1875
- };
1876
-
1877
- const messages: Message[] = [
1878
- {
1879
- id: "msg-1",
1880
- role: "assistant",
1881
- content: "Hello!",
1882
- } as AssistantMessage,
1883
- ];
1884
-
1885
- render(
1886
- <CopilotKitProvider>
1887
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1888
- <CopilotChatView
1889
- messages={messages}
1890
- isRunning={false}
1891
- input={InputWithInternalState as any}
1892
- />
1893
- </CopilotChatConfigurationProvider>
1894
- </CopilotKitProvider>,
1895
- );
1896
-
1897
- await waitFor(() => {
1898
- expect(screen.getByTestId("stateful-input")).toBeDefined();
1899
- });
1900
-
1901
- // Initial state
1902
- expect(screen.getByTestId("click-count").textContent).toBe("0");
1903
- const initialExternalRenderCount = externalRenderCount;
1904
- expect(initialExternalRenderCount).toBe(1);
1905
-
1906
- // Click the button to trigger internal state change
1907
- const incrementButton = screen.getByTestId("increment-button");
1908
- fireEvent.click(incrementButton);
1909
-
1910
- // THE KEY ASSERTION: Internal state changes SHOULD cause re-render
1911
- await waitFor(() => {
1912
- expect(screen.getByTestId("click-count").textContent).toBe("1");
1913
- });
1914
-
1915
- // Verify the component actually re-rendered (not just DOM updated)
1916
- expect(externalRenderCount).toBe(2);
1917
-
1918
- // Click again to confirm consistent behavior
1919
- fireEvent.click(incrementButton);
1920
-
1921
- await waitFor(() => {
1922
- expect(screen.getByTestId("click-count").textContent).toBe("2");
1923
- });
1924
-
1925
- expect(externalRenderCount).toBe(3);
1926
- });
1927
-
1928
- it("should re-render the input component when its props change", async () => {
1929
- let inputRenderCount = 0;
1930
- const capturedModes: string[] = [];
1931
-
1932
- const TrackedInput: React.FC<CopilotChatInputProps> = (props) => {
1933
- inputRenderCount++;
1934
- capturedModes.push(props.mode || "default");
1935
- return (
1936
- <div data-testid="tracked-input">
1937
- <span data-testid="input-mode">{props.mode}</span>
1938
- <CopilotChatInput {...props} />
1939
- </div>
1940
- );
1941
- };
1942
-
1943
- const messages: Message[] = [
1944
- {
1945
- id: "msg-1",
1946
- role: "assistant",
1947
- content: "Hello!",
1948
- } as AssistantMessage,
1949
- ];
1950
-
1951
- const { rerender } = render(
1952
- <CopilotKitProvider>
1953
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1954
- <CopilotChatView
1955
- messages={messages}
1956
- isRunning={false}
1957
- input={TrackedInput as any}
1958
- onSubmitMessage={() => {}}
1959
- inputMode="input"
1960
- />
1961
- </CopilotChatConfigurationProvider>
1962
- </CopilotKitProvider>,
1963
- );
1964
-
1965
- await waitFor(() => {
1966
- expect(screen.getByTestId("tracked-input")).toBeDefined();
1967
- });
1968
-
1969
- const renderCountAfterInitial = inputRenderCount;
1970
- expect(renderCountAfterInitial).toBe(1);
1971
-
1972
- // Change the mode prop
1973
- rerender(
1974
- <CopilotKitProvider>
1975
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
1976
- <CopilotChatView
1977
- messages={messages}
1978
- isRunning={true}
1979
- input={TrackedInput as any}
1980
- onSubmitMessage={() => {}}
1981
- inputMode="processing"
1982
- />
1983
- </CopilotChatConfigurationProvider>
1984
- </CopilotKitProvider>,
1985
- );
1986
-
1987
- await waitFor(() => {
1988
- expect(screen.getByTestId("input-mode").textContent).toBe("processing");
1989
- });
1990
-
1991
- const renderCountAfterModeChange = inputRenderCount;
1992
-
1993
- // THE KEY ASSERTION: Input SHOULD re-render when its props change
1994
- expect(renderCountAfterModeChange).toBeGreaterThan(renderCountAfterInitial);
1995
- expect(capturedModes).toContain("input");
1996
- expect(capturedModes).toContain("processing");
1997
- });
1998
- });
1999
-
2000
- describe("Suggestion View Re-render Prevention", () => {
2001
- it("should re-render a suggestion when its loading state changes", async () => {
2002
- const suggestionRenderCounts: Record<string, number> = {};
2003
-
2004
- const TrackedSuggestionPill: React.FC<{
2005
- children: React.ReactNode;
2006
- isLoading?: boolean;
2007
- onClick?: () => void;
2008
- }> = ({ children, isLoading, onClick }) => {
2009
- const title = String(children);
2010
- suggestionRenderCounts[title] = (suggestionRenderCounts[title] || 0) + 1;
2011
- return (
2012
- <button
2013
- data-testid={`suggestion-${title}`}
2014
- onClick={onClick}
2015
- disabled={isLoading}
2016
- >
2017
- {title}
2018
- <span data-testid={`suggestion-loading-${title}`}>
2019
- {isLoading ? "loading" : "ready"}
2020
- </span>
2021
- </button>
2022
- );
2023
- };
2024
-
2025
- const suggestions = [
2026
- { title: "Tell me a joke", message: "Tell me a joke", isLoading: false },
2027
- {
2028
- title: "What's the weather?",
2029
- message: "What's the weather?",
2030
- isLoading: false,
2031
- },
2032
- ];
2033
-
2034
- const { rerender } = render(
2035
- <CopilotKitProvider>
2036
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
2037
- <CopilotChatSuggestionView
2038
- suggestions={suggestions}
2039
- suggestion={TrackedSuggestionPill as any}
2040
- />
2041
- </CopilotChatConfigurationProvider>
2042
- </CopilotKitProvider>,
2043
- );
2044
-
2045
- await waitFor(() => {
2046
- expect(
2047
- screen.getByTestId("suggestion-loading-Tell me a joke").textContent,
2048
- ).toBe("ready");
2049
- });
2050
-
2051
- const initialRenderCount = suggestionRenderCounts["Tell me a joke"]!;
2052
-
2053
- // Set first suggestion to loading
2054
- rerender(
2055
- <CopilotKitProvider>
2056
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
2057
- <CopilotChatSuggestionView
2058
- suggestions={suggestions}
2059
- loadingIndexes={[0]}
2060
- suggestion={TrackedSuggestionPill as any}
2061
- />
2062
- </CopilotChatConfigurationProvider>
2063
- </CopilotKitProvider>,
2064
- );
2065
-
2066
- await waitFor(() => {
2067
- expect(
2068
- screen.getByTestId("suggestion-loading-Tell me a joke").textContent,
2069
- ).toBe("loading");
2070
- });
2071
-
2072
- // THE KEY ASSERTION: Suggestion SHOULD re-render when loading state changes
2073
- expect(suggestionRenderCounts["Tell me a joke"]).toBeGreaterThan(
2074
- initialRenderCount,
2075
- );
2076
- });
2077
- });
2078
-
2079
- describe("Markdown Renderer Re-render Prevention", () => {
2080
- it("should not re-render markdown when other messages change", async () => {
2081
- const markdownRenderCounts: Record<string, number> = {};
2082
-
2083
- const TrackedMarkdownRenderer: React.FC<{
2084
- content: string;
2085
- }> = ({ content }) => {
2086
- markdownRenderCounts[content] = (markdownRenderCounts[content] || 0) + 1;
2087
- return (
2088
- <div data-testid={`markdown-${content.slice(0, 20)}`}>
2089
- <span data-testid={`markdown-content-${content.slice(0, 20)}`}>
2090
- {content}
2091
- </span>
2092
- <span data-testid={`markdown-render-count-${content.slice(0, 20)}`}>
2093
- {markdownRenderCounts[content]}
2094
- </span>
2095
- </div>
2096
- );
2097
- };
2098
-
2099
- const TrackedAssistantMessage: React.FC<{
2100
- message: AssistantMessage;
2101
- messages?: Message[];
2102
- isRunning?: boolean;
2103
- }> = ({ message, messages, isRunning }) => {
2104
- return (
2105
- <CopilotChatAssistantMessage
2106
- message={message}
2107
- messages={messages}
2108
- isRunning={isRunning}
2109
- markdownRenderer={TrackedMarkdownRenderer as any}
2110
- />
2111
- );
2112
- };
2113
-
2114
- const initialMessages: Message[] = [
2115
- {
2116
- id: "msg-1",
2117
- role: "assistant",
2118
- content: "Hello! How can I help?",
2119
- } as AssistantMessage,
2120
- ];
2121
-
2122
- const { rerender } = render(
2123
- <CopilotKitProvider>
2124
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
2125
- <CopilotChatMessageView
2126
- messages={initialMessages}
2127
- isRunning={false}
2128
- assistantMessage={TrackedAssistantMessage as any}
2129
- />
2130
- </CopilotChatConfigurationProvider>
2131
- </CopilotKitProvider>,
2132
- );
2133
-
2134
- await waitFor(() => {
2135
- expect(screen.getByTestId("markdown-Hello! How can I hel")).toBeDefined();
2136
- });
2137
-
2138
- const initialRenderCount = markdownRenderCounts["Hello! How can I help?"]!;
2139
-
2140
- // Add a new message (simulating streaming)
2141
- const messagesWithSecond: Message[] = [
2142
- ...initialMessages,
2143
- {
2144
- id: "msg-2",
2145
- role: "assistant",
2146
- content: "Let me help you with",
2147
- } as AssistantMessage,
2148
- ];
2149
-
2150
- rerender(
2151
- <CopilotKitProvider>
2152
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
2153
- <CopilotChatMessageView
2154
- messages={messagesWithSecond}
2155
- isRunning={true}
2156
- assistantMessage={TrackedAssistantMessage as any}
2157
- />
2158
- </CopilotChatConfigurationProvider>
2159
- </CopilotKitProvider>,
2160
- );
2161
-
2162
- await waitFor(() => {
2163
- expect(screen.getByTestId("markdown-Let me help you with")).toBeDefined();
2164
- });
2165
-
2166
- // THE KEY ASSERTION: First message's markdown should NOT re-render
2167
- expect(markdownRenderCounts["Hello! How can I help?"]).toBe(
2168
- initialRenderCount,
2169
- );
2170
- });
2171
-
2172
- it("should re-render markdown when its content changes", async () => {
2173
- const markdownRenderCounts: Record<string, number> = {};
2174
- const capturedContent: string[] = [];
2175
-
2176
- const TrackedMarkdownRenderer: React.FC<{
2177
- content: string;
2178
- }> = ({ content }) => {
2179
- markdownRenderCounts[content] = (markdownRenderCounts[content] || 0) + 1;
2180
- capturedContent.push(content);
2181
- return (
2182
- <div data-testid="markdown">
2183
- <span data-testid="markdown-content">{content}</span>
2184
- </div>
2185
- );
2186
- };
2187
-
2188
- const TrackedAssistantMessage: React.FC<{
2189
- message: AssistantMessage;
2190
- messages?: Message[];
2191
- isRunning?: boolean;
2192
- }> = ({ message, messages, isRunning }) => {
2193
- return (
2194
- <CopilotChatAssistantMessage
2195
- message={message}
2196
- messages={messages}
2197
- isRunning={isRunning}
2198
- markdownRenderer={TrackedMarkdownRenderer as any}
2199
- />
2200
- );
2201
- };
2202
-
2203
- const initialMessages: Message[] = [
2204
- {
2205
- id: "msg-1",
2206
- role: "assistant",
2207
- content: "Hello",
2208
- } as AssistantMessage,
2209
- ];
2210
-
2211
- const { rerender } = render(
2212
- <CopilotKitProvider>
2213
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
2214
- <CopilotChatMessageView
2215
- messages={initialMessages}
2216
- isRunning={true}
2217
- assistantMessage={TrackedAssistantMessage as any}
2218
- />
2219
- </CopilotChatConfigurationProvider>
2220
- </CopilotKitProvider>,
2221
- );
2222
-
2223
- await waitFor(() => {
2224
- expect(screen.getByTestId("markdown-content").textContent).toBe("Hello");
2225
- });
2226
-
2227
- // Stream more content
2228
- const messagesWithMoreContent: Message[] = [
2229
- {
2230
- id: "msg-1",
2231
- role: "assistant",
2232
- content: "Hello! How are you today?",
2233
- } as AssistantMessage,
2234
- ];
2235
-
2236
- rerender(
2237
- <CopilotKitProvider>
2238
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
2239
- <CopilotChatMessageView
2240
- messages={messagesWithMoreContent}
2241
- isRunning={true}
2242
- assistantMessage={TrackedAssistantMessage as any}
2243
- />
2244
- </CopilotChatConfigurationProvider>
2245
- </CopilotKitProvider>,
2246
- );
2247
-
2248
- await waitFor(() => {
2249
- expect(screen.getByTestId("markdown-content").textContent).toBe(
2250
- "Hello! How are you today?",
2251
- );
2252
- });
2253
-
2254
- // THE KEY ASSERTION: Markdown SHOULD re-render when content changes
2255
- expect(capturedContent).toContain("Hello");
2256
- expect(capturedContent).toContain("Hello! How are you today?");
2257
- });
2258
- });
2259
-
2260
- describe("Copy Button Re-render Prevention", () => {
2261
- it("should not re-render copy button when a new message is added", async () => {
2262
- let copyButtonRenderCount = 0;
2263
-
2264
- const TrackedCopyButton: React.FC<{
2265
- onClick?: () => void;
2266
- }> = ({ onClick }) => {
2267
- copyButtonRenderCount++;
2268
- return (
2269
- <button data-testid="copy-button" onClick={onClick}>
2270
- Copy
2271
- <span data-testid="copy-render-count">{copyButtonRenderCount}</span>
2272
- </button>
2273
- );
2274
- };
2275
-
2276
- const TrackedAssistantMessage: React.FC<{
2277
- message: AssistantMessage;
2278
- messages?: Message[];
2279
- isRunning?: boolean;
2280
- }> = ({ message, messages, isRunning }) => {
2281
- return (
2282
- <CopilotChatAssistantMessage
2283
- message={message}
2284
- messages={messages}
2285
- isRunning={isRunning}
2286
- copyButton={TrackedCopyButton as any}
2287
- />
2288
- );
2289
- };
2290
-
2291
- // Start with a completed message (isRunning=false so toolbar shows)
2292
- const initialMessages: Message[] = [
2293
- {
2294
- id: "msg-1",
2295
- role: "assistant",
2296
- content: "Hello! First message here.",
2297
- } as AssistantMessage,
2298
- ];
2299
-
2300
- const { rerender } = render(
2301
- <CopilotKitProvider>
2302
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
2303
- <CopilotChatMessageView
2304
- messages={initialMessages}
2305
- isRunning={false}
2306
- assistantMessage={TrackedAssistantMessage as any}
2307
- />
2308
- </CopilotChatConfigurationProvider>
2309
- </CopilotKitProvider>,
2310
- );
2311
-
2312
- await waitFor(() => {
2313
- expect(screen.getByTestId("copy-button")).toBeDefined();
2314
- });
2315
-
2316
- const initialRenderCount = copyButtonRenderCount;
2317
-
2318
- // Add a second message - the first message's copy button should NOT re-render
2319
- const messagesWithSecond: Message[] = [
2320
- ...initialMessages,
2321
- {
2322
- id: "msg-2",
2323
- role: "assistant",
2324
- content: "Second message here.",
2325
- } as AssistantMessage,
2326
- ];
2327
-
2328
- rerender(
2329
- <CopilotKitProvider>
2330
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
2331
- <CopilotChatMessageView
2332
- messages={messagesWithSecond}
2333
- isRunning={false}
2334
- assistantMessage={TrackedAssistantMessage as any}
2335
- />
2336
- </CopilotChatConfigurationProvider>
2337
- </CopilotKitProvider>,
2338
- );
2339
-
2340
- // Wait for second message to render
2341
- await waitFor(() => {
2342
- expect(screen.getAllByTestId("copy-button").length).toBe(2);
2343
- });
2344
-
2345
- // THE KEY ASSERTION: First message's copy button should NOT re-render when second message is added
2346
- // We check that the total render count is 2 (one for each message), not 3 (which would mean first re-rendered)
2347
- expect(copyButtonRenderCount).toBe(2);
2348
- });
2349
-
2350
- it("should re-render copy button when its onClick handler changes", async () => {
2351
- let copyButtonRenderCount = 0;
2352
-
2353
- const TrackedCopyButton: React.FC<{
2354
- onClick?: () => void;
2355
- }> = ({ onClick }) => {
2356
- copyButtonRenderCount++;
2357
- return (
2358
- <button data-testid="copy-button" onClick={onClick}>
2359
- Copy
2360
- </button>
2361
- );
2362
- };
2363
-
2364
- // First render with one message (isRunning=false so toolbar shows)
2365
- const message1: AssistantMessage = {
2366
- id: "msg-1",
2367
- role: "assistant",
2368
- content: "First message",
2369
- };
2370
-
2371
- const { rerender } = render(
2372
- <CopilotKitProvider>
2373
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
2374
- <CopilotChatAssistantMessage
2375
- message={message1}
2376
- isRunning={false}
2377
- copyButton={TrackedCopyButton as any}
2378
- />
2379
- </CopilotChatConfigurationProvider>
2380
- </CopilotKitProvider>,
2381
- );
2382
-
2383
- await waitFor(() => {
2384
- expect(screen.getByTestId("copy-button")).toBeDefined();
2385
- });
2386
-
2387
- const initialRenderCount = copyButtonRenderCount;
2388
-
2389
- // Re-render with a completely different message (different ID = different onClick)
2390
- const message2: AssistantMessage = {
2391
- id: "msg-2",
2392
- role: "assistant",
2393
- content: "Second message",
2394
- };
2395
-
2396
- rerender(
2397
- <CopilotKitProvider>
2398
- <CopilotChatConfigurationProvider agentId="default" threadId="test">
2399
- <CopilotChatAssistantMessage
2400
- message={message2}
2401
- isRunning={false}
2402
- copyButton={TrackedCopyButton as any}
2403
- />
2404
- </CopilotChatConfigurationProvider>
2405
- </CopilotKitProvider>,
2406
- );
2407
-
2408
- await waitFor(() => {
2409
- expect(screen.getByTestId("copy-button")).toBeDefined();
2410
- });
2411
-
2412
- // THE KEY ASSERTION: Copy button SHOULD re-render when the message changes
2413
- // because the onClick handler needs to reference the new message content
2414
- expect(copyButtonRenderCount).toBeGreaterThan(initialRenderCount);
2415
- });
2416
- });