@copilotkit/react-core 0.0.0-main-20260220223427 → 0.0.0-main-20260403195251
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +540 -71
- package/dist/copilotkit-BK_zLoVm.mjs +7661 -0
- package/dist/copilotkit-BK_zLoVm.mjs.map +1 -0
- package/dist/copilotkit-BYNyIuE7.d.cts +2208 -0
- package/dist/copilotkit-BYNyIuE7.d.cts.map +1 -0
- package/dist/copilotkit-BYNyIuE7.d.ts +2208 -0
- package/dist/copilotkit-BYNyIuE7.d.ts.map +1 -0
- package/dist/copilotkit-CDZGGOIB.cjs +8074 -0
- package/dist/copilotkit-CDZGGOIB.cjs.map +1 -0
- package/dist/copilotkit-rBCfdqIo.d.mts +2208 -0
- package/dist/copilotkit-rBCfdqIo.d.mts.map +1 -0
- package/dist/index.cjs +166 -2200
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +14 -674
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +14 -674
- package/dist/index.d.mts.map +1 -1
- package/dist/index.d.ts +667 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.mjs +119 -2124
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +2252 -230
- package/dist/index.umd.js.map +1 -1
- package/dist/v2/index.cjs +78 -6
- package/dist/v2/index.css +1 -2
- package/dist/v2/index.d.cts +6 -2
- package/dist/v2/index.d.mts +6 -2
- package/dist/v2/index.d.ts +6 -0
- package/dist/v2/index.mjs +8 -3
- package/dist/v2/index.umd.js +7786 -12
- package/dist/v2/index.umd.js.map +1 -0
- package/package.json +66 -39
- package/scripts/scope-preflight.mjs +100 -0
- package/src/components/CopilotListeners.tsx +2 -6
- package/src/components/copilot-provider/__tests__/copilot-messages-key.test.tsx +92 -0
- package/src/components/copilot-provider/copilot-messages.tsx +1 -1
- package/src/components/copilot-provider/copilotkit-props.tsx +1 -1
- package/src/components/copilot-provider/copilotkit.tsx +120 -68
- package/src/context/copilot-messages-context.tsx +1 -1
- package/src/hooks/__tests__/use-coagent-config.test.ts +2 -2
- package/src/hooks/__tests__/use-coagent-state-render.e2e.test.tsx +5 -6
- package/src/hooks/__tests__/use-copilot-chat-internal-connect.test.tsx +242 -0
- package/src/hooks/__tests__/use-frontend-tool-available.test.tsx +1 -1
- package/src/hooks/__tests__/use-frontend-tool-remount.e2e.test.tsx +4 -4
- package/src/hooks/index.ts +0 -1
- package/src/hooks/use-agent-nodename.ts +1 -1
- package/src/hooks/use-coagent-state-render-bridge.tsx +1 -4
- package/src/hooks/use-coagent.ts +1 -1
- package/src/hooks/use-configure-chat-suggestions.tsx +2 -2
- package/src/hooks/use-copilot-chat-suggestions.tsx +2 -2
- package/src/hooks/use-copilot-chat_internal.ts +73 -13
- package/src/hooks/use-copilot-readable.ts +1 -1
- package/src/hooks/use-frontend-tool.ts +2 -2
- package/src/hooks/use-human-in-the-loop.ts +2 -2
- package/src/hooks/use-langgraph-interrupt.ts +95 -38
- package/src/hooks/use-lazy-tool-renderer.tsx +1 -1
- package/src/hooks/use-render-tool-call.ts +1 -1
- package/src/lib/copilot-task.ts +1 -1
- package/src/setupTests.ts +18 -14
- package/src/types/interrupt-action.ts +5 -0
- package/src/v2/__tests__/A2UIMessageRenderer.test.tsx +176 -0
- package/src/v2/__tests__/globalSetup.ts +14 -0
- package/src/v2/__tests__/setup.ts +93 -0
- package/src/v2/__tests__/utils/test-helpers.tsx +503 -0
- package/src/v2/a2ui/A2UIMessageRenderer.tsx +206 -0
- package/src/v2/components/CopilotKitInspector.tsx +50 -0
- package/src/v2/components/MCPAppsActivityRenderer.tsx +785 -0
- package/src/v2/components/WildcardToolCallRender.tsx +86 -0
- package/src/v2/components/__tests__/license-warning-banner.test.tsx +46 -0
- package/src/v2/components/chat/CopilotChat.tsx +433 -0
- package/src/v2/components/chat/CopilotChatAssistantMessage.tsx +375 -0
- package/src/v2/components/chat/CopilotChatAudioRecorder.tsx +350 -0
- package/src/v2/components/chat/CopilotChatInput.tsx +1302 -0
- package/src/v2/components/chat/CopilotChatMessageView.tsx +561 -0
- package/src/v2/components/chat/CopilotChatReasoningMessage.tsx +252 -0
- package/src/v2/components/chat/CopilotChatSuggestionPill.tsx +59 -0
- package/src/v2/components/chat/CopilotChatSuggestionView.tsx +133 -0
- package/src/v2/components/chat/CopilotChatToggleButton.tsx +171 -0
- package/src/v2/components/chat/CopilotChatToolCallsView.tsx +40 -0
- package/src/v2/components/chat/CopilotChatUserMessage.tsx +388 -0
- package/src/v2/components/chat/CopilotChatView.tsx +598 -0
- package/src/v2/components/chat/CopilotModalHeader.tsx +129 -0
- package/src/v2/components/chat/CopilotPopup.tsx +81 -0
- package/src/v2/components/chat/CopilotPopupView.tsx +317 -0
- package/src/v2/components/chat/CopilotSidebar.tsx +76 -0
- package/src/v2/components/chat/CopilotSidebarView.tsx +255 -0
- package/src/v2/components/chat/__tests__/CopilotChat.e2e.test.tsx +1113 -0
- package/src/v2/components/chat/__tests__/CopilotChat.onError.test.tsx +73 -0
- package/src/v2/components/chat/__tests__/CopilotChat.slots.e2e.test.tsx +432 -0
- package/src/v2/components/chat/__tests__/CopilotChatActivityRendering.e2e.test.tsx +150 -0
- package/src/v2/components/chat/__tests__/CopilotChatAssistantMessage.slots.e2e.test.tsx +624 -0
- package/src/v2/components/chat/__tests__/CopilotChatAssistantMessage.test.tsx +702 -0
- package/src/v2/components/chat/__tests__/CopilotChatCssClasses.test.tsx +107 -0
- package/src/v2/components/chat/__tests__/CopilotChatInput.slots.e2e.test.tsx +929 -0
- package/src/v2/components/chat/__tests__/CopilotChatInput.test.tsx +986 -0
- package/src/v2/components/chat/__tests__/CopilotChatMessageView.slots.e2e.test.tsx +1004 -0
- package/src/v2/components/chat/__tests__/CopilotChatMessageView.test.tsx +169 -0
- package/src/v2/components/chat/__tests__/CopilotChatSuggestionView.slots.e2e.test.tsx +530 -0
- package/src/v2/components/chat/__tests__/CopilotChatToolRendering.e2e.test.tsx +785 -0
- package/src/v2/components/chat/__tests__/CopilotChatToolRerenders.e2e.test.tsx +2416 -0
- package/src/v2/components/chat/__tests__/CopilotChatUserMessage.slots.e2e.test.tsx +621 -0
- package/src/v2/components/chat/__tests__/CopilotChatView.onClick.e2e.test.tsx +853 -0
- package/src/v2/components/chat/__tests__/CopilotChatView.slots.e2e.test.tsx +1050 -0
- package/src/v2/components/chat/__tests__/CopilotModalHeader.slots.e2e.test.tsx +484 -0
- package/src/v2/components/chat/__tests__/CopilotPopupView.slots.e2e.test.tsx +612 -0
- package/src/v2/components/chat/__tests__/CopilotSidebarView.slots.e2e.test.tsx +502 -0
- package/src/v2/components/chat/__tests__/MCPAppsActivityRenderer.e2e.test.tsx +1027 -0
- package/src/v2/components/chat/__tests__/setup.ts +1 -0
- package/src/v2/components/chat/index.ts +79 -0
- package/src/v2/components/index.ts +7 -0
- package/src/v2/components/license-warning-banner.tsx +198 -0
- package/src/v2/components/ui/button.tsx +123 -0
- package/src/v2/components/ui/dropdown-menu.tsx +258 -0
- package/src/v2/components/ui/tooltip.tsx +60 -0
- package/src/v2/hooks/__tests__/standard-schema-types.test.tsx +152 -0
- package/src/v2/hooks/__tests__/standard-schema.test.tsx +282 -0
- package/src/v2/hooks/__tests__/use-agent-context-timing.e2e.test.tsx +140 -0
- package/src/v2/hooks/__tests__/use-agent-context.test.tsx +401 -0
- package/src/v2/hooks/__tests__/use-agent-error-state.test.tsx +44 -0
- package/src/v2/hooks/__tests__/use-agent-stability.test.tsx +205 -0
- package/src/v2/hooks/__tests__/use-agent-thread-isolation.test.tsx +327 -0
- package/src/v2/hooks/__tests__/use-agent-throttle.test.tsx +728 -0
- package/src/v2/hooks/__tests__/use-agent.e2e.test.tsx +159 -0
- package/src/v2/hooks/__tests__/use-component.test.tsx +123 -0
- package/src/v2/hooks/__tests__/use-configure-suggestions.e2e.test.tsx +696 -0
- package/src/v2/hooks/__tests__/use-default-render-tool.test.tsx +153 -0
- package/src/v2/hooks/__tests__/use-frontend-tool-available.test.tsx +167 -0
- package/src/v2/hooks/__tests__/use-frontend-tool.e2e.test.tsx +2148 -0
- package/src/v2/hooks/__tests__/use-human-in-the-loop.e2e.test.tsx +1261 -0
- package/src/v2/hooks/__tests__/use-interrupt.test.tsx +397 -0
- package/src/v2/hooks/__tests__/use-katex-styles.test.tsx +56 -0
- package/src/v2/hooks/__tests__/use-keyboard-height.test.tsx +192 -0
- package/src/v2/hooks/__tests__/use-render-tool.test.tsx +259 -0
- package/src/v2/hooks/__tests__/use-suggestions.e2e.test.tsx +524 -0
- package/src/v2/hooks/__tests__/use-threads.test.tsx +433 -0
- package/src/v2/hooks/__tests__/zod-regression.test.tsx +311 -0
- package/src/v2/hooks/index.ts +18 -0
- package/src/v2/hooks/use-agent-context.tsx +45 -0
- package/src/v2/hooks/use-agent.tsx +358 -0
- package/src/v2/hooks/use-component.tsx +89 -0
- package/src/v2/hooks/use-configure-suggestions.tsx +187 -0
- package/src/v2/hooks/use-default-render-tool.tsx +254 -0
- package/src/v2/hooks/use-frontend-tool.tsx +43 -0
- package/src/v2/hooks/use-human-in-the-loop.tsx +81 -0
- package/src/v2/hooks/use-interrupt.tsx +305 -0
- package/src/v2/hooks/use-keyboard-height.tsx +67 -0
- package/src/v2/hooks/use-render-activity-message.tsx +73 -0
- package/src/v2/hooks/use-render-custom-messages.tsx +98 -0
- package/src/v2/hooks/use-render-tool-call.tsx +175 -0
- package/src/v2/hooks/use-render-tool.tsx +181 -0
- package/src/v2/hooks/use-suggestions.tsx +91 -0
- package/src/v2/hooks/use-threads.tsx +256 -0
- package/src/v2/hooks/useKatexStyles.ts +27 -0
- package/src/v2/index.css +1 -1
- package/src/v2/index.ts +21 -2
- package/src/v2/lib/__tests__/completePartialMarkdown.test.ts +495 -0
- package/src/v2/lib/__tests__/renderSlot.test.tsx +588 -0
- package/src/v2/lib/react-core.ts +156 -0
- package/src/v2/lib/slots.tsx +143 -0
- package/src/v2/lib/transcription-client.ts +184 -0
- package/src/v2/lib/utils.ts +8 -0
- package/src/v2/providers/CopilotChatConfigurationProvider.tsx +162 -0
- package/src/v2/providers/CopilotKitProvider.tsx +600 -0
- package/src/v2/providers/__tests__/CopilotChatConfigurationProvider.test.tsx +546 -0
- package/src/v2/providers/__tests__/CopilotKitProvider.license.test.tsx +101 -0
- package/src/v2/providers/__tests__/CopilotKitProvider.onError.test.tsx +69 -0
- package/src/v2/providers/__tests__/CopilotKitProvider.renderCustomMessages.e2e.test.tsx +881 -0
- package/src/v2/providers/__tests__/CopilotKitProvider.stability.test.tsx +740 -0
- package/src/v2/providers/__tests__/CopilotKitProvider.test.tsx +642 -0
- package/src/v2/providers/__tests__/CopilotKitProvider.wildcard.test.tsx +294 -0
- package/src/v2/providers/index.ts +14 -0
- package/src/v2/styles/globals.css +231 -0
- package/src/v2/types/__tests__/defineToolCallRenderer.test.tsx +525 -0
- package/src/v2/types/defineToolCallRenderer.ts +65 -0
- package/src/v2/types/frontend-tool.ts +8 -0
- package/src/v2/types/human-in-the-loop.ts +33 -0
- package/src/v2/types/index.ts +7 -0
- package/src/v2/types/interrupt.ts +15 -0
- package/src/v2/types/react-activity-message-renderer.ts +27 -0
- package/src/v2/types/react-custom-message-renderer.ts +17 -0
- package/src/v2/types/react-tool-call-renderer.ts +32 -0
- package/tsdown.config.ts +34 -10
- package/vitest.config.mjs +4 -3
- package/LICENSE +0 -21
- package/dist/v2/index.css.map +0 -1
- package/src/hooks/use-langgraph-interrupt-render.ts +0 -147
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
import { useCopilotKit } from "../providers/CopilotKitProvider";
|
|
2
|
+
import { useCopilotChatConfiguration } from "../providers/CopilotChatConfigurationProvider";
|
|
3
|
+
import { useMemo, useEffect, useReducer, useRef } from "react";
|
|
4
|
+
import { DEFAULT_AGENT_ID } from "@copilotkit/shared";
|
|
5
|
+
import { AbstractAgent, HttpAgent } from "@ag-ui/client";
|
|
6
|
+
import {
|
|
7
|
+
ProxiedCopilotRuntimeAgent,
|
|
8
|
+
CopilotKitCoreRuntimeConnectionStatus,
|
|
9
|
+
} from "@copilotkit/core";
|
|
10
|
+
|
|
11
|
+
export enum UseAgentUpdate {
|
|
12
|
+
OnMessagesChanged = "OnMessagesChanged",
|
|
13
|
+
OnStateChanged = "OnStateChanged",
|
|
14
|
+
OnRunStatusChanged = "OnRunStatusChanged",
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const ALL_UPDATES: UseAgentUpdate[] = [
|
|
18
|
+
UseAgentUpdate.OnMessagesChanged,
|
|
19
|
+
UseAgentUpdate.OnStateChanged,
|
|
20
|
+
UseAgentUpdate.OnRunStatusChanged,
|
|
21
|
+
];
|
|
22
|
+
|
|
23
|
+
export interface UseAgentProps {
|
|
24
|
+
agentId?: string;
|
|
25
|
+
threadId?: string;
|
|
26
|
+
updates?: UseAgentUpdate[];
|
|
27
|
+
/**
|
|
28
|
+
* Throttle interval (in milliseconds) for React re-renders triggered by
|
|
29
|
+
* `OnMessagesChanged` notifications. Useful to reduce re-render frequency
|
|
30
|
+
* during high-frequency message updates such as streaming.
|
|
31
|
+
*
|
|
32
|
+
* Uses leading+trailing: first update fires immediately, subsequent updates
|
|
33
|
+
* within the window are coalesced, and a trailing timer ensures the most
|
|
34
|
+
* recent update fires after the window expires. The trailing edge restarts
|
|
35
|
+
* the throttle window, so no two renders occur within `throttleMs` of each
|
|
36
|
+
* other. Cleanup on unmount cancels any pending trailing timer.
|
|
37
|
+
*
|
|
38
|
+
* Must be a non-negative finite number. Negative or non-finite values fall
|
|
39
|
+
* back to unthrottled behavior with a `console.error`. Only affects
|
|
40
|
+
* `OnMessagesChanged` updates — `OnStateChanged` and `OnRunStatusChanged`
|
|
41
|
+
* always fire immediately. If `updates` does not include
|
|
42
|
+
* `OnMessagesChanged`, this property has no effect.
|
|
43
|
+
*
|
|
44
|
+
* This throttle is independent of and additive with any
|
|
45
|
+
* `notificationThrottle` configured on the `AbstractAgent` instance.
|
|
46
|
+
*
|
|
47
|
+
* Default: `0` (no throttle).
|
|
48
|
+
*/
|
|
49
|
+
throttleMs?: number;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Clone a registry agent for per-thread isolation.
|
|
54
|
+
* Copies agent configuration (transport, headers, etc.) but resets conversation
|
|
55
|
+
* state (messages, threadId, state) so each thread starts fresh.
|
|
56
|
+
*/
|
|
57
|
+
function cloneForThread(
|
|
58
|
+
source: AbstractAgent,
|
|
59
|
+
threadId: string,
|
|
60
|
+
headers: Record<string, string>,
|
|
61
|
+
): AbstractAgent {
|
|
62
|
+
const clone = source.clone();
|
|
63
|
+
if (clone === source) {
|
|
64
|
+
throw new Error(
|
|
65
|
+
`useAgent: ${source.constructor.name}.clone() returned the same instance. ` +
|
|
66
|
+
`clone() must return a new, independent object.`,
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
clone.threadId = threadId;
|
|
70
|
+
clone.setMessages([]);
|
|
71
|
+
clone.setState({});
|
|
72
|
+
if (clone instanceof HttpAgent) {
|
|
73
|
+
clone.headers = { ...headers };
|
|
74
|
+
}
|
|
75
|
+
return clone;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Module-level WeakMap: registryAgent → (threadId → clone).
|
|
80
|
+
* Shared across all useAgent() calls so that every component using the same
|
|
81
|
+
* (agentId, threadId) pair receives the same agent instance. Using WeakMap
|
|
82
|
+
* ensures the clone map is garbage-collected when the registry agent is
|
|
83
|
+
* replaced (e.g. after reconnect or hot-reload).
|
|
84
|
+
*/
|
|
85
|
+
export const globalThreadCloneMap = new WeakMap<
|
|
86
|
+
AbstractAgent,
|
|
87
|
+
Map<string, AbstractAgent>
|
|
88
|
+
>();
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Look up an existing per-thread clone without creating one.
|
|
92
|
+
* Returns undefined when no clone has been created yet for this pair.
|
|
93
|
+
*/
|
|
94
|
+
export function getThreadClone(
|
|
95
|
+
registryAgent: AbstractAgent | undefined | null,
|
|
96
|
+
threadId: string | undefined | null,
|
|
97
|
+
): AbstractAgent | undefined {
|
|
98
|
+
if (!registryAgent || !threadId) return undefined;
|
|
99
|
+
return globalThreadCloneMap.get(registryAgent)?.get(threadId);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function getOrCreateThreadClone(
|
|
103
|
+
existing: AbstractAgent,
|
|
104
|
+
threadId: string,
|
|
105
|
+
headers: Record<string, string>,
|
|
106
|
+
): AbstractAgent {
|
|
107
|
+
let byThread = globalThreadCloneMap.get(existing);
|
|
108
|
+
if (!byThread) {
|
|
109
|
+
byThread = new Map();
|
|
110
|
+
globalThreadCloneMap.set(existing, byThread);
|
|
111
|
+
}
|
|
112
|
+
const cached = byThread.get(threadId);
|
|
113
|
+
if (cached) return cached;
|
|
114
|
+
|
|
115
|
+
const clone = cloneForThread(existing, threadId, headers);
|
|
116
|
+
byThread.set(threadId, clone);
|
|
117
|
+
return clone;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function useAgent({
|
|
121
|
+
agentId,
|
|
122
|
+
threadId,
|
|
123
|
+
updates,
|
|
124
|
+
throttleMs,
|
|
125
|
+
}: UseAgentProps = {}) {
|
|
126
|
+
agentId ??= DEFAULT_AGENT_ID;
|
|
127
|
+
|
|
128
|
+
const { copilotkit } = useCopilotKit();
|
|
129
|
+
// Fall back to the enclosing CopilotChatConfigurationProvider's threadId so
|
|
130
|
+
// that useAgent() called without explicit threadId (e.g. inside a custom
|
|
131
|
+
// message renderer) automatically uses the same per-thread clone as the
|
|
132
|
+
// CopilotChat component it lives within.
|
|
133
|
+
const chatConfig = useCopilotChatConfiguration();
|
|
134
|
+
threadId ??= chatConfig?.threadId;
|
|
135
|
+
|
|
136
|
+
const effectiveThrottleMs = useMemo(() => {
|
|
137
|
+
if (
|
|
138
|
+
throttleMs !== undefined &&
|
|
139
|
+
(!Number.isFinite(throttleMs) || throttleMs < 0)
|
|
140
|
+
) {
|
|
141
|
+
console.error(
|
|
142
|
+
`useAgent: throttleMs must be a non-negative finite number, got ${throttleMs}. Falling back to unthrottled.`,
|
|
143
|
+
);
|
|
144
|
+
return 0;
|
|
145
|
+
}
|
|
146
|
+
return throttleMs ?? 0;
|
|
147
|
+
}, [throttleMs]);
|
|
148
|
+
|
|
149
|
+
const [, forceUpdate] = useReducer((x) => x + 1, 0);
|
|
150
|
+
|
|
151
|
+
const updateFlags = useMemo(
|
|
152
|
+
() => updates ?? ALL_UPDATES,
|
|
153
|
+
[JSON.stringify(updates)],
|
|
154
|
+
);
|
|
155
|
+
|
|
156
|
+
// Cache provisional agents to avoid creating new references on every render
|
|
157
|
+
// while the runtime is still connecting. A new reference would cascade into
|
|
158
|
+
// CopilotChat's connectAgent effect, causing unnecessary HTTP calls.
|
|
159
|
+
const provisionalAgentCache = useRef<Map<string, ProxiedCopilotRuntimeAgent>>(
|
|
160
|
+
new Map(),
|
|
161
|
+
);
|
|
162
|
+
|
|
163
|
+
const agent: AbstractAgent = useMemo(() => {
|
|
164
|
+
// Use a composite key when threadId is provided so that different threads
|
|
165
|
+
// for the same agent get independent instances.
|
|
166
|
+
const cacheKey = threadId ? `${agentId}:${threadId}` : agentId;
|
|
167
|
+
|
|
168
|
+
const existing = copilotkit.getAgent(agentId);
|
|
169
|
+
if (existing) {
|
|
170
|
+
// Real agent found — clear any cached provisionals for this key and the
|
|
171
|
+
// bare agentId key (handles the case where a provisional was created
|
|
172
|
+
// before threadId was available, then the component re-renders with one).
|
|
173
|
+
provisionalAgentCache.current.delete(cacheKey);
|
|
174
|
+
provisionalAgentCache.current.delete(agentId);
|
|
175
|
+
|
|
176
|
+
if (!threadId) {
|
|
177
|
+
// No threadId — return the shared registry agent (original behavior)
|
|
178
|
+
return existing;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// threadId provided — return the shared per-thread clone.
|
|
182
|
+
// The global WeakMap ensures all components using the same
|
|
183
|
+
// (registryAgent, threadId) pair receive the same instance, so state
|
|
184
|
+
// mutations (addMessage, setState) are visible everywhere. The WeakMap
|
|
185
|
+
// entry is GC-collected automatically when the registry agent is replaced.
|
|
186
|
+
return getOrCreateThreadClone(existing, threadId, copilotkit.headers);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const isRuntimeConfigured = copilotkit.runtimeUrl !== undefined;
|
|
190
|
+
const status = copilotkit.runtimeConnectionStatus;
|
|
191
|
+
|
|
192
|
+
// While runtime is not yet synced, return a provisional runtime agent
|
|
193
|
+
if (
|
|
194
|
+
isRuntimeConfigured &&
|
|
195
|
+
(status === CopilotKitCoreRuntimeConnectionStatus.Disconnected ||
|
|
196
|
+
status === CopilotKitCoreRuntimeConnectionStatus.Connecting)
|
|
197
|
+
) {
|
|
198
|
+
// Return cached provisional if available (keeps reference stable)
|
|
199
|
+
const cached = provisionalAgentCache.current.get(cacheKey);
|
|
200
|
+
if (cached) {
|
|
201
|
+
// Update headers on the cached agent in case they changed
|
|
202
|
+
cached.headers = { ...copilotkit.headers };
|
|
203
|
+
return cached;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const provisional = new ProxiedCopilotRuntimeAgent({
|
|
207
|
+
runtimeUrl: copilotkit.runtimeUrl,
|
|
208
|
+
agentId,
|
|
209
|
+
transport: copilotkit.runtimeTransport,
|
|
210
|
+
runtimeMode: "pending",
|
|
211
|
+
});
|
|
212
|
+
// Apply current headers so runs/connects inherit them
|
|
213
|
+
provisional.headers = { ...copilotkit.headers };
|
|
214
|
+
if (threadId) {
|
|
215
|
+
provisional.threadId = threadId;
|
|
216
|
+
}
|
|
217
|
+
provisionalAgentCache.current.set(cacheKey, provisional);
|
|
218
|
+
return provisional;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Runtime is in Error state — return a provisional agent instead of throwing.
|
|
222
|
+
// The error has already been emitted through the subscriber system
|
|
223
|
+
// (RUNTIME_INFO_FETCH_FAILED). Throwing here would crash the React tree;
|
|
224
|
+
// returning a provisional agent lets onError handlers fire while keeping
|
|
225
|
+
// the app alive.
|
|
226
|
+
if (
|
|
227
|
+
isRuntimeConfigured &&
|
|
228
|
+
status === CopilotKitCoreRuntimeConnectionStatus.Error
|
|
229
|
+
) {
|
|
230
|
+
// Cache the provisional so that dep changes while in Error state (e.g.
|
|
231
|
+
// headers update) return the same agent reference, matching the
|
|
232
|
+
// Disconnected/Connecting path and preventing spurious re-subscriptions.
|
|
233
|
+
const cached = provisionalAgentCache.current.get(cacheKey);
|
|
234
|
+
if (cached) {
|
|
235
|
+
cached.headers = { ...copilotkit.headers };
|
|
236
|
+
return cached;
|
|
237
|
+
}
|
|
238
|
+
const provisional = new ProxiedCopilotRuntimeAgent({
|
|
239
|
+
runtimeUrl: copilotkit.runtimeUrl,
|
|
240
|
+
agentId,
|
|
241
|
+
transport: copilotkit.runtimeTransport,
|
|
242
|
+
runtimeMode: "pending",
|
|
243
|
+
});
|
|
244
|
+
provisional.headers = { ...copilotkit.headers };
|
|
245
|
+
if (threadId) {
|
|
246
|
+
provisional.threadId = threadId;
|
|
247
|
+
}
|
|
248
|
+
provisionalAgentCache.current.set(cacheKey, provisional);
|
|
249
|
+
return provisional;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// No runtime configured and agent doesn't exist — this is a configuration error.
|
|
253
|
+
const knownAgents = Object.keys(copilotkit.agents ?? {});
|
|
254
|
+
const runtimePart = isRuntimeConfigured
|
|
255
|
+
? `runtimeUrl=${copilotkit.runtimeUrl}`
|
|
256
|
+
: "no runtimeUrl";
|
|
257
|
+
throw new Error(
|
|
258
|
+
`useAgent: Agent '${agentId}' not found after runtime sync (${runtimePart}). ` +
|
|
259
|
+
(knownAgents.length
|
|
260
|
+
? `Known agents: [${knownAgents.join(", ")}]`
|
|
261
|
+
: "No agents registered.") +
|
|
262
|
+
" Verify your runtime /info and/or agents__unsafe_dev_only.",
|
|
263
|
+
);
|
|
264
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
265
|
+
}, [
|
|
266
|
+
agentId,
|
|
267
|
+
threadId,
|
|
268
|
+
copilotkit.agents,
|
|
269
|
+
copilotkit.runtimeConnectionStatus,
|
|
270
|
+
copilotkit.runtimeUrl,
|
|
271
|
+
copilotkit.runtimeTransport,
|
|
272
|
+
JSON.stringify(copilotkit.headers),
|
|
273
|
+
]);
|
|
274
|
+
|
|
275
|
+
useEffect(() => {
|
|
276
|
+
if (updateFlags.length === 0) return;
|
|
277
|
+
|
|
278
|
+
const handlers: Parameters<AbstractAgent["subscribe"]>[0] = {};
|
|
279
|
+
let timerId: ReturnType<typeof setTimeout> | null = null;
|
|
280
|
+
let active = true;
|
|
281
|
+
|
|
282
|
+
if (updateFlags.includes(UseAgentUpdate.OnMessagesChanged)) {
|
|
283
|
+
const ms = effectiveThrottleMs;
|
|
284
|
+
if (ms > 0) {
|
|
285
|
+
// Throttled onMessagesChanged: leading+trailing pattern.
|
|
286
|
+
// First notification fires immediately, subsequent ones within the
|
|
287
|
+
// window are coalesced. Trailing timer fires after the window to
|
|
288
|
+
// ensure the final state is rendered.
|
|
289
|
+
let throttleActive = false;
|
|
290
|
+
// Tracks whether a notification arrived during the throttle window,
|
|
291
|
+
// so the trailing timer knows whether a re-render is needed.
|
|
292
|
+
let pending = false;
|
|
293
|
+
|
|
294
|
+
const throttledNotify = () => {
|
|
295
|
+
if (!active) return;
|
|
296
|
+
if (!throttleActive) {
|
|
297
|
+
// Leading edge — fire immediately and start the throttle window
|
|
298
|
+
throttleActive = true;
|
|
299
|
+
pending = false;
|
|
300
|
+
forceUpdate();
|
|
301
|
+
timerId = setTimeout(function trailingEdge() {
|
|
302
|
+
timerId = null;
|
|
303
|
+
if (active && pending) {
|
|
304
|
+
// Trailing edge — fire and restart the window
|
|
305
|
+
pending = false;
|
|
306
|
+
forceUpdate();
|
|
307
|
+
timerId = setTimeout(trailingEdge, ms);
|
|
308
|
+
} else {
|
|
309
|
+
// No pending notifications — end the window
|
|
310
|
+
throttleActive = false;
|
|
311
|
+
}
|
|
312
|
+
}, ms);
|
|
313
|
+
} else {
|
|
314
|
+
pending = true;
|
|
315
|
+
}
|
|
316
|
+
};
|
|
317
|
+
|
|
318
|
+
handlers.onMessagesChanged = throttledNotify;
|
|
319
|
+
} else {
|
|
320
|
+
handlers.onMessagesChanged = forceUpdate;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
if (updateFlags.includes(UseAgentUpdate.OnStateChanged)) {
|
|
325
|
+
handlers.onStateChanged = forceUpdate;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
if (updateFlags.includes(UseAgentUpdate.OnRunStatusChanged)) {
|
|
329
|
+
handlers.onRunInitialized = forceUpdate;
|
|
330
|
+
handlers.onRunFinalized = forceUpdate;
|
|
331
|
+
handlers.onRunFailed = forceUpdate;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const subscription = agent.subscribe(handlers);
|
|
335
|
+
return () => {
|
|
336
|
+
active = false;
|
|
337
|
+
if (timerId !== null) {
|
|
338
|
+
clearTimeout(timerId);
|
|
339
|
+
}
|
|
340
|
+
subscription.unsubscribe();
|
|
341
|
+
};
|
|
342
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
343
|
+
}, [agent, forceUpdate, effectiveThrottleMs, updateFlags]);
|
|
344
|
+
|
|
345
|
+
// Keep HttpAgent headers fresh without mutating inside useMemo, which is
|
|
346
|
+
// unsafe in concurrent mode (React may invoke useMemo multiple times and
|
|
347
|
+
// discard intermediate results, but mutations always land).
|
|
348
|
+
useEffect(() => {
|
|
349
|
+
if (agent instanceof HttpAgent) {
|
|
350
|
+
agent.headers = { ...copilotkit.headers };
|
|
351
|
+
}
|
|
352
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
353
|
+
}, [agent, JSON.stringify(copilotkit.headers)]);
|
|
354
|
+
|
|
355
|
+
return {
|
|
356
|
+
agent,
|
|
357
|
+
};
|
|
358
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import type { StandardSchemaV1, InferSchemaOutput } from "@copilotkit/shared";
|
|
2
|
+
import type { ComponentType } from "react";
|
|
3
|
+
import { useFrontendTool } from "./use-frontend-tool";
|
|
4
|
+
|
|
5
|
+
type InferRenderProps<T> = T extends StandardSchemaV1
|
|
6
|
+
? InferSchemaOutput<T>
|
|
7
|
+
: any;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Registers a React component as a frontend tool renderer in chat.
|
|
11
|
+
*
|
|
12
|
+
* This hook is a convenience wrapper around `useFrontendTool` that:
|
|
13
|
+
* - builds a model-facing tool description,
|
|
14
|
+
* - forwards optional schema parameters (any Standard Schema V1 compatible library),
|
|
15
|
+
* - renders your component with tool call parameters.
|
|
16
|
+
*
|
|
17
|
+
* Use this when you want to display a typed visual component for a tool call
|
|
18
|
+
* without manually wiring a full frontend tool object.
|
|
19
|
+
*
|
|
20
|
+
* When `parameters` is provided, render props are inferred from the schema.
|
|
21
|
+
* When omitted, the render component may accept any props.
|
|
22
|
+
*
|
|
23
|
+
* @typeParam TSchema - Schema describing tool parameters, or `undefined` when no schema is given.
|
|
24
|
+
* @param config - Tool registration config.
|
|
25
|
+
* @param deps - Optional dependencies to refresh registration (same semantics as `useEffect`).
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```tsx
|
|
29
|
+
* // Without parameters — render accepts any props
|
|
30
|
+
* useComponent({
|
|
31
|
+
* name: "showGreeting",
|
|
32
|
+
* render: ({ message }: { message: string }) => <div>{message}</div>,
|
|
33
|
+
* });
|
|
34
|
+
* ```
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```tsx
|
|
38
|
+
* // With parameters — render props inferred from schema
|
|
39
|
+
* useComponent({
|
|
40
|
+
* name: "showWeatherCard",
|
|
41
|
+
* parameters: z.object({ city: z.string() }),
|
|
42
|
+
* render: ({ city }) => <div>{city}</div>,
|
|
43
|
+
* });
|
|
44
|
+
* ```
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* ```tsx
|
|
48
|
+
* useComponent(
|
|
49
|
+
* {
|
|
50
|
+
* name: "renderProfile",
|
|
51
|
+
* parameters: z.object({ userId: z.string() }),
|
|
52
|
+
* render: ProfileCard,
|
|
53
|
+
* agentId: "support-agent",
|
|
54
|
+
* },
|
|
55
|
+
* [selectedAgentId],
|
|
56
|
+
* );
|
|
57
|
+
* ```
|
|
58
|
+
*/
|
|
59
|
+
export function useComponent<
|
|
60
|
+
TSchema extends StandardSchemaV1 | undefined = undefined,
|
|
61
|
+
>(
|
|
62
|
+
config: {
|
|
63
|
+
name: string;
|
|
64
|
+
description?: string;
|
|
65
|
+
parameters?: TSchema;
|
|
66
|
+
render: ComponentType<NoInfer<InferRenderProps<TSchema>>>;
|
|
67
|
+
agentId?: string;
|
|
68
|
+
},
|
|
69
|
+
deps?: ReadonlyArray<unknown>,
|
|
70
|
+
): void {
|
|
71
|
+
const prefix = `Use this tool to display the "${config.name}" component in the chat. This tool renders a visual UI component for the user.`;
|
|
72
|
+
const fullDescription = config.description
|
|
73
|
+
? `${prefix}\n\n${config.description}`
|
|
74
|
+
: prefix;
|
|
75
|
+
|
|
76
|
+
useFrontendTool(
|
|
77
|
+
{
|
|
78
|
+
name: config.name,
|
|
79
|
+
description: fullDescription,
|
|
80
|
+
parameters: config.parameters,
|
|
81
|
+
render: ({ args }: { args: unknown }) => {
|
|
82
|
+
const Component = config.render;
|
|
83
|
+
return <Component {...(args as InferRenderProps<TSchema>)} />;
|
|
84
|
+
},
|
|
85
|
+
agentId: config.agentId,
|
|
86
|
+
},
|
|
87
|
+
deps,
|
|
88
|
+
);
|
|
89
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { useCallback, useEffect, useMemo, useRef } from "react";
|
|
2
|
+
import { useCopilotKit } from "../providers/CopilotKitProvider";
|
|
3
|
+
import { useCopilotChatConfiguration } from "../providers/CopilotChatConfigurationProvider";
|
|
4
|
+
import { DEFAULT_AGENT_ID } from "@copilotkit/shared";
|
|
5
|
+
import {
|
|
6
|
+
DynamicSuggestionsConfig,
|
|
7
|
+
StaticSuggestionsConfig,
|
|
8
|
+
SuggestionsConfig,
|
|
9
|
+
Suggestion,
|
|
10
|
+
} from "@copilotkit/core";
|
|
11
|
+
|
|
12
|
+
type StaticSuggestionInput = Omit<Suggestion, "isLoading"> &
|
|
13
|
+
Partial<Pick<Suggestion, "isLoading">>;
|
|
14
|
+
|
|
15
|
+
type StaticSuggestionsConfigInput = Omit<
|
|
16
|
+
StaticSuggestionsConfig,
|
|
17
|
+
"suggestions"
|
|
18
|
+
> & {
|
|
19
|
+
suggestions: StaticSuggestionInput[];
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
type SuggestionsConfigInput =
|
|
23
|
+
| DynamicSuggestionsConfig
|
|
24
|
+
| StaticSuggestionsConfigInput;
|
|
25
|
+
|
|
26
|
+
export function useConfigureSuggestions(
|
|
27
|
+
config: SuggestionsConfigInput | null | undefined,
|
|
28
|
+
deps?: ReadonlyArray<unknown>,
|
|
29
|
+
): void {
|
|
30
|
+
const { copilotkit } = useCopilotKit();
|
|
31
|
+
const chatConfig = useCopilotChatConfiguration();
|
|
32
|
+
const extraDeps = deps ?? [];
|
|
33
|
+
|
|
34
|
+
const resolvedConsumerAgentId = useMemo(
|
|
35
|
+
() => chatConfig?.agentId ?? DEFAULT_AGENT_ID,
|
|
36
|
+
[chatConfig?.agentId],
|
|
37
|
+
);
|
|
38
|
+
|
|
39
|
+
const rawConsumerAgentId = useMemo(
|
|
40
|
+
() =>
|
|
41
|
+
config ? (config as SuggestionsConfigInput).consumerAgentId : undefined,
|
|
42
|
+
[config],
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
const normalizationCacheRef = useRef<{
|
|
46
|
+
serialized: string | null;
|
|
47
|
+
config: SuggestionsConfig | null;
|
|
48
|
+
}>({
|
|
49
|
+
serialized: null,
|
|
50
|
+
config: null,
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
const { normalizedConfig, serializedConfig } = useMemo(() => {
|
|
54
|
+
if (!config) {
|
|
55
|
+
normalizationCacheRef.current = { serialized: null, config: null };
|
|
56
|
+
return { normalizedConfig: null, serializedConfig: null };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (config.available === "disabled") {
|
|
60
|
+
normalizationCacheRef.current = { serialized: null, config: null };
|
|
61
|
+
return { normalizedConfig: null, serializedConfig: null };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
let built: SuggestionsConfig;
|
|
65
|
+
if (isDynamicConfig(config)) {
|
|
66
|
+
built = {
|
|
67
|
+
...config,
|
|
68
|
+
} satisfies DynamicSuggestionsConfig;
|
|
69
|
+
} else {
|
|
70
|
+
const normalizedSuggestions = normalizeStaticSuggestions(
|
|
71
|
+
config.suggestions,
|
|
72
|
+
);
|
|
73
|
+
const baseConfig: StaticSuggestionsConfig = {
|
|
74
|
+
...config,
|
|
75
|
+
suggestions: normalizedSuggestions,
|
|
76
|
+
};
|
|
77
|
+
built = baseConfig;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const serialized = JSON.stringify(built);
|
|
81
|
+
const cache = normalizationCacheRef.current;
|
|
82
|
+
if (cache.serialized === serialized && cache.config) {
|
|
83
|
+
return { normalizedConfig: cache.config, serializedConfig: serialized };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
normalizationCacheRef.current = { serialized, config: built };
|
|
87
|
+
return { normalizedConfig: built, serializedConfig: serialized };
|
|
88
|
+
}, [config, resolvedConsumerAgentId, ...extraDeps]);
|
|
89
|
+
const latestConfigRef = useRef<SuggestionsConfig | null>(null);
|
|
90
|
+
latestConfigRef.current = normalizedConfig;
|
|
91
|
+
const previousSerializedConfigRef = useRef<string | null>(null);
|
|
92
|
+
|
|
93
|
+
const targetAgentId = useMemo(() => {
|
|
94
|
+
if (!normalizedConfig) {
|
|
95
|
+
return resolvedConsumerAgentId;
|
|
96
|
+
}
|
|
97
|
+
const consumer = (
|
|
98
|
+
normalizedConfig as StaticSuggestionsConfig | DynamicSuggestionsConfig
|
|
99
|
+
).consumerAgentId;
|
|
100
|
+
if (!consumer || consumer === "*") {
|
|
101
|
+
return resolvedConsumerAgentId;
|
|
102
|
+
}
|
|
103
|
+
return consumer;
|
|
104
|
+
}, [normalizedConfig, resolvedConsumerAgentId]);
|
|
105
|
+
|
|
106
|
+
const isGlobalConfig =
|
|
107
|
+
rawConsumerAgentId === undefined || rawConsumerAgentId === "*";
|
|
108
|
+
|
|
109
|
+
const requestReload = useCallback(() => {
|
|
110
|
+
if (!normalizedConfig) {
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (isGlobalConfig) {
|
|
115
|
+
const agents = Object.values(copilotkit.agents ?? {});
|
|
116
|
+
for (const entry of agents) {
|
|
117
|
+
const agentId = entry.agentId;
|
|
118
|
+
if (!agentId) {
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (!entry.isRunning) {
|
|
122
|
+
copilotkit.reloadSuggestions(agentId);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (!targetAgentId) {
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
copilotkit.reloadSuggestions(targetAgentId);
|
|
133
|
+
}, [copilotkit, isGlobalConfig, normalizedConfig, targetAgentId]);
|
|
134
|
+
|
|
135
|
+
useEffect(() => {
|
|
136
|
+
if (!serializedConfig || !latestConfigRef.current) {
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const id = copilotkit.addSuggestionsConfig(latestConfigRef.current);
|
|
141
|
+
|
|
142
|
+
requestReload();
|
|
143
|
+
|
|
144
|
+
return () => {
|
|
145
|
+
copilotkit.removeSuggestionsConfig(id);
|
|
146
|
+
};
|
|
147
|
+
}, [copilotkit, serializedConfig, requestReload]);
|
|
148
|
+
|
|
149
|
+
useEffect(() => {
|
|
150
|
+
if (!normalizedConfig) {
|
|
151
|
+
previousSerializedConfigRef.current = null;
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
if (
|
|
155
|
+
serializedConfig &&
|
|
156
|
+
previousSerializedConfigRef.current === serializedConfig
|
|
157
|
+
) {
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
if (serializedConfig) {
|
|
161
|
+
previousSerializedConfigRef.current = serializedConfig;
|
|
162
|
+
}
|
|
163
|
+
requestReload();
|
|
164
|
+
}, [normalizedConfig, requestReload, serializedConfig]);
|
|
165
|
+
|
|
166
|
+
useEffect(() => {
|
|
167
|
+
if (!normalizedConfig || extraDeps.length === 0) {
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
requestReload();
|
|
171
|
+
}, [extraDeps.length, normalizedConfig, requestReload, ...extraDeps]);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function isDynamicConfig(
|
|
175
|
+
config: SuggestionsConfigInput,
|
|
176
|
+
): config is DynamicSuggestionsConfig {
|
|
177
|
+
return "instructions" in config;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function normalizeStaticSuggestions(
|
|
181
|
+
suggestions: StaticSuggestionInput[],
|
|
182
|
+
): Suggestion[] {
|
|
183
|
+
return suggestions.map((suggestion) => ({
|
|
184
|
+
...suggestion,
|
|
185
|
+
isLoading: suggestion.isLoading ?? false,
|
|
186
|
+
}));
|
|
187
|
+
}
|