@copilotkit/react-core 1.57.0 → 1.57.1-canary.1778272612

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 (86) hide show
  1. package/dist/{copilotkit-CPe2-340.mjs → copilotkit-3XTEoVQO.mjs} +1367 -1200
  2. package/dist/copilotkit-3XTEoVQO.mjs.map +1 -0
  3. package/dist/{copilotkit-DFaI4j2r.d.mts → copilotkit-BCJ2yvV6.d.mts} +68 -8
  4. package/dist/copilotkit-BCJ2yvV6.d.mts.map +1 -0
  5. package/dist/{copilotkit-Dg4r4Gi_.d.cts → copilotkit-CBbSvze0.d.cts} +68 -8
  6. package/dist/copilotkit-CBbSvze0.d.cts.map +1 -0
  7. package/dist/{copilotkit-DGbvw8n2.cjs → copilotkit-Dnj9pi4m.cjs} +1369 -1196
  8. package/dist/copilotkit-Dnj9pi4m.cjs.map +1 -0
  9. package/dist/index.cjs +2 -5
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.cts +1 -1
  12. package/dist/index.d.mts +1 -1
  13. package/dist/index.mjs +2 -5
  14. package/dist/index.mjs.map +1 -1
  15. package/dist/index.umd.js +733 -610
  16. package/dist/index.umd.js.map +1 -1
  17. package/dist/v2/context.cjs +135 -0
  18. package/dist/v2/context.cjs.map +1 -0
  19. package/dist/v2/context.d.cts +148 -0
  20. package/dist/v2/context.d.cts.map +1 -0
  21. package/dist/v2/context.d.mts +148 -0
  22. package/dist/v2/context.d.mts.map +1 -0
  23. package/dist/v2/context.mjs +129 -0
  24. package/dist/v2/context.mjs.map +1 -0
  25. package/dist/v2/headless.cjs +1043 -0
  26. package/dist/v2/headless.cjs.map +1 -0
  27. package/dist/v2/headless.d.cts +605 -0
  28. package/dist/v2/headless.d.cts.map +1 -0
  29. package/dist/v2/headless.d.mts +512 -0
  30. package/dist/v2/headless.d.mts.map +1 -0
  31. package/dist/v2/headless.mjs +997 -0
  32. package/dist/v2/headless.mjs.map +1 -0
  33. package/dist/v2/index.cjs +2 -1
  34. package/dist/v2/index.css +1 -1
  35. package/dist/v2/index.d.cts +2 -2
  36. package/dist/v2/index.d.mts +2 -2
  37. package/dist/v2/index.mjs +2 -2
  38. package/dist/v2/index.umd.js +1385 -1204
  39. package/dist/v2/index.umd.js.map +1 -1
  40. package/package.json +14 -6
  41. package/src/hooks/__tests__/use-copilot-chat-internal-connect.test.tsx +5 -6
  42. package/src/hooks/use-copilot-chat_internal.ts +0 -1
  43. package/src/v2/components/chat/CopilotChat.tsx +2 -1
  44. package/src/v2/components/chat/CopilotChatMessageView.tsx +24 -9
  45. package/src/v2/components/chat/CopilotChatView.tsx +2 -2
  46. package/src/v2/components/chat/CopilotSidebar.tsx +5 -1
  47. package/src/v2/components/chat/CopilotSidebarView.tsx +24 -10
  48. package/src/v2/components/chat/__tests__/CopilotChat.welcomeGate.test.tsx +1 -3
  49. package/src/v2/components/chat/__tests__/CopilotChatActivityRendering.e2e.test.tsx +29 -25
  50. package/src/v2/components/chat/__tests__/CopilotSidebarView.position.test.tsx +159 -0
  51. package/src/v2/components/chat/__tests__/MCPAppsUiMessage.e2e.test.tsx +5 -60
  52. package/src/v2/components/index.ts +1 -0
  53. package/src/v2/components/intelligence-indicator/IntelligenceIndicator.tsx +286 -0
  54. package/src/v2/components/intelligence-indicator/__tests__/IntelligenceIndicator.e2e.test.tsx +464 -0
  55. package/src/v2/components/intelligence-indicator/index.ts +2 -0
  56. package/src/v2/context.ts +62 -0
  57. package/src/v2/headless.ts +42 -0
  58. package/src/v2/hooks/__tests__/standard-schema.test.tsx +2 -2
  59. package/src/v2/hooks/__tests__/use-agent-context.test.tsx +3 -3
  60. package/src/v2/hooks/__tests__/use-agent-stability.test.tsx +3 -3
  61. package/src/v2/hooks/__tests__/use-agent-throttle.test.tsx +85 -85
  62. package/src/v2/hooks/__tests__/use-interrupt.test.tsx +2 -2
  63. package/src/v2/hooks/__tests__/use-render-tool.test.tsx +2 -2
  64. package/src/v2/hooks/__tests__/use-threads.test.tsx +2 -2
  65. package/src/v2/hooks/__tests__/zod-regression.test.tsx +2 -2
  66. package/src/v2/hooks/use-agent-context.tsx +1 -1
  67. package/src/v2/hooks/use-agent.tsx +9 -118
  68. package/src/v2/hooks/use-configure-suggestions.tsx +1 -1
  69. package/src/v2/hooks/use-default-render-tool.tsx +18 -1
  70. package/src/v2/hooks/use-frontend-tool.tsx +2 -2
  71. package/src/v2/hooks/use-human-in-the-loop.tsx +1 -1
  72. package/src/v2/hooks/use-interrupt.tsx +1 -1
  73. package/src/v2/hooks/use-render-activity-message.tsx +3 -11
  74. package/src/v2/hooks/use-render-custom-messages.tsx +1 -6
  75. package/src/v2/hooks/use-render-tool-call.tsx +36 -6
  76. package/src/v2/hooks/use-render-tool.tsx +2 -2
  77. package/src/v2/hooks/use-suggestions.tsx +1 -1
  78. package/src/v2/hooks/use-threads.tsx +1 -1
  79. package/src/v2/providers/CopilotKitProvider.tsx +19 -59
  80. package/src/v2/styles/globals.css +118 -0
  81. package/tsdown.config.ts +75 -0
  82. package/dist/copilotkit-CPe2-340.mjs.map +0 -1
  83. package/dist/copilotkit-DFaI4j2r.d.mts.map +0 -1
  84. package/dist/copilotkit-DGbvw8n2.cjs.map +0 -1
  85. package/dist/copilotkit-Dg4r4Gi_.d.cts.map +0 -1
  86. package/src/v2/hooks/__tests__/use-agent-thread-isolation.test.tsx +0 -333
@@ -49,6 +49,11 @@ class MockMCPProxyAgent extends AbstractAgent {
49
49
  this.runAgentResponses.set(method, response);
50
50
  }
51
51
 
52
+ addMessage(msg: Parameters<AbstractAgent["addMessage"]>[0]) {
53
+ this.addMessageCalls.push(msg as any);
54
+ return super.addMessage(msg);
55
+ }
56
+
52
57
  emit(event: BaseEvent) {
53
58
  if (event.type === EventType.RUN_STARTED) {
54
59
  this.isRunning = true;
@@ -70,66 +75,6 @@ class MockMCPProxyAgent extends AbstractAgent {
70
75
  });
71
76
  }
72
77
 
73
- clone(): MockMCPProxyAgent {
74
- const cloned = new MockMCPProxyAgent();
75
- cloned.agentId = this.agentId;
76
- type Internal = {
77
- subject: Subject<BaseEvent>;
78
- runAgentCalls: Array<{ input: Partial<RunAgentInput> }>;
79
- addMessageCalls: Array<{ id: string; role: string; content: string }>;
80
- runAgentResponses: Map<string, unknown>;
81
- };
82
- (cloned as unknown as Internal).subject = (
83
- this as unknown as Internal
84
- ).subject;
85
- (cloned as unknown as Internal).runAgentCalls = (
86
- this as unknown as Internal
87
- ).runAgentCalls;
88
- (cloned as unknown as Internal).addMessageCalls = (
89
- this as unknown as Internal
90
- ).addMessageCalls;
91
- (cloned as unknown as Internal).runAgentResponses = (
92
- this as unknown as Internal
93
- ).runAgentResponses;
94
-
95
- const registry = this;
96
- Object.defineProperty(cloned, "isRunning", {
97
- get() {
98
- return registry.isRunning;
99
- },
100
- set(v: boolean) {
101
- registry.isRunning = v;
102
- },
103
- configurable: true,
104
- enumerable: true,
105
- });
106
-
107
- const proto = MockMCPProxyAgent.prototype;
108
- cloned.runAgent = async function (
109
- input?: Partial<RunAgentInput>,
110
- ): Promise<RunAgentResult> {
111
- const proxiedRequest = input?.forwardedProps?.__proxiedMCPRequest;
112
- if (proxiedRequest) {
113
- return registry.runAgent(input);
114
- }
115
- return proto.runAgent.call(cloned, input);
116
- };
117
-
118
- // Track addMessage calls on the clone (the component uses the clone)
119
- const origAddMessage = cloned.addMessage.bind(cloned);
120
- cloned.addMessage = function (msg: Parameters<typeof origAddMessage>[0]) {
121
- registry.addMessageCalls.push(msg as any);
122
- return origAddMessage(msg);
123
- };
124
-
125
- // Proxy run() calls so spies on the registry's run() see clone invocations
126
- cloned.run = function (input: RunAgentInput): Observable<BaseEvent> {
127
- return registry.run(input);
128
- };
129
-
130
- return cloned;
131
- }
132
-
133
78
  async detachActiveRun(): Promise<void> {}
134
79
 
135
80
  run(_input: RunAgentInput): Observable<BaseEvent> {
@@ -5,3 +5,4 @@ export * from "./chat";
5
5
  export * from "./WildcardToolCallRender";
6
6
  export * from "./CopilotKitInspector";
7
7
  export * from "./MCPAppsActivityRenderer";
8
+ export * from "./intelligence-indicator";
@@ -0,0 +1,286 @@
1
+ import React, { useEffect, useMemo, useState } from "react";
2
+ import type { Message } from "@ag-ui/core";
3
+ import { useCopilotKit } from "../../providers/CopilotKitProvider";
4
+ import { useCopilotChatConfiguration } from "../../providers/CopilotChatConfigurationProvider";
5
+ import { useAgent, UseAgentUpdate } from "../../hooks/use-agent";
6
+
7
+ /**
8
+ * Grace window before showing the spinner. A matching tool call must
9
+ * remain unresolved (no `tool`-role result message in `agent.messages`)
10
+ * for at least this long before the pill appears. This filters out
11
+ * history-replay flashes — during `connectAgent` replay, tool calls and
12
+ * their results arrive back-to-back in sub-millisecond bursts, so the
13
+ * timer is cancelled before it fires. Live runs cross the threshold
14
+ * easily because the tool actually has to execute.
15
+ */
16
+ const PENDING_THRESHOLD_MS = 100;
17
+
18
+ /** Hold the checkmark briefly before fading out. */
19
+ const CHECK_HOLD_MS = 800;
20
+
21
+ /**
22
+ * Duration of the fade-out animation. Must match
23
+ * `cpk-intelligence-pill-fade-out` keyframes in `v2/styles/globals.css`.
24
+ */
25
+ const FADE_OUT_ANIMATION_MS = 480;
26
+
27
+ /**
28
+ * Tool-name regex patterns that trigger the indicator. Currently
29
+ * hardcoded to the Intelligence MCP server's canonical tool name. If
30
+ * we add per-instance customization later (e.g. a `CopilotKitProvider`
31
+ * prop or a runtime-info field), this constant becomes the fallback.
32
+ */
33
+ const DEFAULT_TOOL_PATTERNS: readonly RegExp[] = [
34
+ /^copilotkit_knowledge_base_shell$/,
35
+ ];
36
+
37
+ type Phase = "idle" | "spinner" | "check" | "fading" | "hidden";
38
+
39
+ export interface IntelligenceIndicatorProps {
40
+ /** The message this indicator is attached to. */
41
+ message: Message;
42
+ /**
43
+ * Agent id whose run state the indicator tracks. Pass through from
44
+ * the surrounding chat configuration; mounting from
45
+ * `CopilotChatMessageView` resolves this automatically.
46
+ */
47
+ agentId: string;
48
+ /**
49
+ * Optional override for the visible label. Defaults to "Using
50
+ * CopilotKit Intelligence".
51
+ */
52
+ label?: string;
53
+ }
54
+
55
+ const isMatchingToolCallName = (name: unknown): boolean =>
56
+ typeof name === "string" && DEFAULT_TOOL_PATTERNS.some((p) => p.test(name));
57
+
58
+ /**
59
+ * "Tool-call-like" messages do NOT count as a real follow-up: tool
60
+ * result messages, assistant messages that carry tool calls, and
61
+ * empty-content assistant messages (which some providers emit as a
62
+ * standalone wrapper around a batch of tool calls). A real follow-up
63
+ * is anything else — most importantly an assistant message with prose
64
+ * content, or a fresh user message.
65
+ */
66
+ const isToolCallLikeMessage = (m: Message): boolean => {
67
+ if (m.role === "tool") return true;
68
+ if (m.role === "assistant") {
69
+ const tcs = Array.isArray(m.toolCalls) ? m.toolCalls : [];
70
+ if (tcs.length > 0) return true;
71
+ const content = m.content;
72
+ return typeof content !== "string" || content.trim().length === 0;
73
+ }
74
+ return false;
75
+ };
76
+
77
+ /**
78
+ * The "Using CopilotKit Intelligence" pill. Auto-mounted by
79
+ * `CopilotChatMessageView` for every message slot when
80
+ * `copilotkit.intelligence` is configured — callers do not register
81
+ * this themselves. Self-gates so only the canonical message renders a
82
+ * pill.
83
+ *
84
+ * Render gates (all must hold):
85
+ * 1. `copilotkit.intelligence !== undefined`
86
+ * 2. The message is an assistant message with at least one tool call
87
+ * whose name matches {@link DEFAULT_TOOL_PATTERNS}
88
+ * 3. The message is the *latest* such matching-assistant message in
89
+ * `agent.messages` — tool-result messages and prose-only assistant
90
+ * messages don't invalidate the slot, so the pill stays
91
+ * continuously through a multi-step tool chain.
92
+ * 4. The phase machine is past `idle` (the pending-grace timer fired)
93
+ * and not yet `hidden`.
94
+ *
95
+ * Phase machine (per-instance, all timers local):
96
+ * - Starts in `idle` — nothing rendered.
97
+ * - `idle → spinner` once a matching tool call has been pending
98
+ * (no `tool`-role result with a matching `toolCallId`) for
99
+ * {@link PENDING_THRESHOLD_MS}. Replay flashes (tool call + result
100
+ * in the same tick) never cross this threshold.
101
+ * - `spinner → check` as soon as EITHER `agent.isRunning` flips
102
+ * false OR a non-tool-call-like message appears later in
103
+ * `agent.messages` (i.e. the agent has produced a "real"
104
+ * follow-up — prose answer or a new user turn).
105
+ * - `check → fading` after {@link CHECK_HOLD_MS}.
106
+ * - `fading → hidden` after {@link FADE_OUT_ANIMATION_MS}.
107
+ *
108
+ * Once `hidden`, the phase is sticky — a finished pill never re-spawns
109
+ * on the same message. New runs mount fresh indicator instances on
110
+ * their own assistant messages.
111
+ *
112
+ * The "exactly one pill at a time" guarantee is structural: only one
113
+ * message satisfies the latest-matching-assistant gate at any moment.
114
+ */
115
+ export function IntelligenceIndicator(
116
+ props: IntelligenceIndicatorProps,
117
+ ): React.ReactElement | null {
118
+ const { message, agentId, label = "Using CopilotKit Intelligence" } = props;
119
+
120
+ const { copilotkit } = useCopilotKit();
121
+ const config = useCopilotChatConfiguration();
122
+ const { agent } = useAgent({
123
+ agentId,
124
+ updates: [
125
+ UseAgentUpdate.OnRunStatusChanged,
126
+ UseAgentUpdate.OnMessagesChanged,
127
+ ],
128
+ });
129
+
130
+ // IDs of matching tool calls on this message.
131
+ const matchingToolCallIds = useMemo<readonly string[]>(() => {
132
+ if (message.role !== "assistant") return [];
133
+ const tcs = Array.isArray(message.toolCalls) ? message.toolCalls : [];
134
+ const ids: string[] = [];
135
+ for (const tc of tcs) {
136
+ if (isMatchingToolCallName(tc?.function?.name) && tc?.id) {
137
+ ids.push(tc.id);
138
+ }
139
+ }
140
+ return ids;
141
+ }, [message]);
142
+
143
+ // Pending = at least one matching tool call has no corresponding
144
+ // `tool`-role result message in `agent.messages`.
145
+ const hasPending = useMemo(() => {
146
+ if (matchingToolCallIds.length === 0) return false;
147
+ const resolved = new Set<string>();
148
+ for (const m of agent.messages) {
149
+ if (m.role === "tool" && m.toolCallId) resolved.add(m.toolCallId);
150
+ }
151
+ return matchingToolCallIds.some((id) => !resolved.has(id));
152
+ }, [matchingToolCallIds, agent.messages]);
153
+
154
+ // True once the agent has produced a "real" message *after* this
155
+ // assistant message — prose, a new user turn, etc. Tool-call-like
156
+ // messages do not count (they're part of the same tool flow).
157
+ const sawRealFollowup = useMemo(() => {
158
+ const idx = agent.messages.findIndex((m) => m.id === message.id);
159
+ if (idx < 0) return false;
160
+ for (let i = idx + 1; i < agent.messages.length; i += 1) {
161
+ if (!isToolCallLikeMessage(agent.messages[i]!)) return true;
162
+ }
163
+ return false;
164
+ }, [agent.messages, message.id]);
165
+
166
+ const [phase, setPhase] = useState<Phase>("idle");
167
+
168
+ // idle → spinner: pending tool call hasn't been resolved within the
169
+ // grace window. Cleared if the result arrives first (replay) or if
170
+ // there's nothing to wait on.
171
+ useEffect(() => {
172
+ if (phase !== "idle") return undefined;
173
+ if (!hasPending) return undefined;
174
+ const t = setTimeout(() => setPhase("spinner"), PENDING_THRESHOLD_MS);
175
+ return () => clearTimeout(t);
176
+ }, [phase, hasPending]);
177
+
178
+ // spinner → check: agent stopped running OR a real follow-up
179
+ // message arrived. Both are independent signals; whichever fires
180
+ // first wins.
181
+ useEffect(() => {
182
+ if (phase !== "spinner") return undefined;
183
+ if (!agent.isRunning || sawRealFollowup) {
184
+ setPhase("check");
185
+ }
186
+ return undefined;
187
+ }, [phase, agent.isRunning, sawRealFollowup]);
188
+
189
+ // check → fading after the hold.
190
+ useEffect(() => {
191
+ if (phase !== "check") return undefined;
192
+ const t = setTimeout(() => setPhase("fading"), CHECK_HOLD_MS);
193
+ return () => clearTimeout(t);
194
+ }, [phase]);
195
+
196
+ // fading → hidden after the fade animation.
197
+ useEffect(() => {
198
+ if (phase !== "fading") return undefined;
199
+ const t = setTimeout(() => setPhase("hidden"), FADE_OUT_ANIMATION_MS);
200
+ return () => clearTimeout(t);
201
+ }, [phase]);
202
+
203
+ // ─── Render gates ────────────────────────────────────────────────────
204
+ // Hooks above MUST run unconditionally; bail with `null` only after.
205
+
206
+ if (copilotkit.intelligence === undefined) return null;
207
+ if (!config) return null;
208
+ if (phase === "idle" || phase === "hidden") return null;
209
+
210
+ if (message.role !== "assistant") return null;
211
+ // Defensive: a malformed `toolCalls` (non-array, missing nested
212
+ // `function.name`) would otherwise throw inside `.some(...)` and take
213
+ // down the chat tree. Treat as "no match" instead.
214
+ const toolCalls = Array.isArray(message.toolCalls) ? message.toolCalls : [];
215
+ const hasMatch = toolCalls.some((tc) =>
216
+ isMatchingToolCallName(tc?.function?.name),
217
+ );
218
+ if (!hasMatch) return null;
219
+
220
+ // Walk `agent.messages` from the end and find the latest assistant
221
+ // message that itself has a matching tool call. If that's not us,
222
+ // we're not the canonical slot — return `null`.
223
+ let latestMatchingAssistantId: string | undefined;
224
+ for (let i = agent.messages.length - 1; i >= 0; i -= 1) {
225
+ const m = agent.messages[i]!;
226
+ if (m.role !== "assistant") continue;
227
+ const tcs = Array.isArray(m.toolCalls) ? m.toolCalls : [];
228
+ if (tcs.some((tc) => isMatchingToolCallName(tc?.function?.name))) {
229
+ latestMatchingAssistantId = m.id;
230
+ break;
231
+ }
232
+ }
233
+ if (latestMatchingAssistantId !== message.id) return null;
234
+
235
+ // ─── Visual ──────────────────────────────────────────────────────────
236
+
237
+ const showSpinner = phase === "spinner";
238
+ const isFading = phase === "fading";
239
+
240
+ return (
241
+ <span
242
+ className={
243
+ "cpk-intelligence-pill" +
244
+ (isFading ? " cpk-intelligence-pill--fading" : "")
245
+ }
246
+ role="status"
247
+ aria-live="polite"
248
+ aria-hidden={isFading || undefined}
249
+ data-testid={`cpk-intelligence-pill-${message.id}`}
250
+ title={label}
251
+ >
252
+ <svg
253
+ className="cpk-intelligence-pill__icon"
254
+ viewBox="0 0 24 24"
255
+ width="14"
256
+ height="14"
257
+ aria-hidden="true"
258
+ >
259
+ <circle
260
+ cx="12"
261
+ cy="12"
262
+ r="9"
263
+ fill="none"
264
+ strokeWidth="2.5"
265
+ strokeLinecap="round"
266
+ className={
267
+ "cpk-intelligence-pill__ring" +
268
+ (showSpinner ? "" : " cpk-intelligence-pill__ring--done")
269
+ }
270
+ />
271
+ <path
272
+ d="M8 12.5l3 3 5-6"
273
+ fill="none"
274
+ strokeWidth="2.5"
275
+ strokeLinecap="round"
276
+ strokeLinejoin="round"
277
+ className={
278
+ "cpk-intelligence-pill__check" +
279
+ (showSpinner ? "" : " cpk-intelligence-pill__check--shown")
280
+ }
281
+ />
282
+ </svg>
283
+ <span>{label}</span>
284
+ </span>
285
+ );
286
+ }