forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopilotKitProvider.tsx
More file actions
188 lines (176 loc) · 5.28 KB
/
Copy pathCopilotKitProvider.tsx
File metadata and controls
188 lines (176 loc) · 5.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import React, {
type ReactNode,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import {
CopilotKitContext,
type CopilotKitContextValue,
LicenseContext,
} from "@copilotkit/react-core/v2/context";
import { CopilotKitCoreReact } from "@copilotkit/react-core/v2/headless";
import type { CopilotKitCoreErrorCode } from "@copilotkit/core";
export interface CopilotKitNativeProviderProps {
children: ReactNode;
/** URL of the CopilotKit runtime endpoint */
runtimeUrl: string;
/** Custom headers sent with every request */
headers?: Record<string, string>;
/** Whether the runtime uses a single-route endpoint */
useSingleEndpoint?: boolean;
/** Custom properties forwarded to agents */
properties?: Record<string, unknown>;
/**
* Error handler called when CopilotKit encounters an error.
* Fires for all error types (runtime connection failures, agent errors, tool errors).
* If not provided, errors are logged to console.error.
*/
onError?: (event: {
error: Error;
code: CopilotKitCoreErrorCode;
context: Record<string, any>;
}) => void;
}
/**
* CopilotKit provider for React Native.
*
* A lightweight alternative to the web CopilotKitProvider that avoids
* web-only dependencies (DOM, CSS, Radix UI, Lit, etc).
*
* Usage:
* ```tsx
* import "@copilotkit/react-native/polyfills";
* import { CopilotKitProvider } from "@copilotkit/react-native";
*
* function App() {
* return (
* <CopilotKitProvider runtimeUrl="https://your-runtime/api/copilotkit">
* <ChatScreen />
* </CopilotKitProvider>
* );
* }
* ```
*/
export const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps> = ({
children,
runtimeUrl,
headers,
useSingleEndpoint,
properties,
onError,
}) => {
// Stabilize headers/properties references to avoid effect churn when callers
// pass inline object literals (e.g. headers={{}} or the undefined default).
// eslint-disable-next-line react-hooks/exhaustive-deps
const stableHeaders = useMemo(() => headers ?? {}, [JSON.stringify(headers)]);
// eslint-disable-next-line react-hooks/exhaustive-deps
const stableProperties = useMemo(
() => properties ?? {},
[JSON.stringify(properties)],
);
const copilotkitRef = useRef<CopilotKitCoreReact | null>(null);
if (copilotkitRef.current === null) {
copilotkitRef.current = new CopilotKitCoreReact({
runtimeUrl,
runtimeTransport:
useSingleEndpoint === true
? "single"
: useSingleEndpoint === false
? "rest"
: "auto",
headers: stableHeaders,
properties: stableProperties,
});
}
const copilotkit = copilotkitRef.current;
// Sync props to core instance
useEffect(() => {
copilotkit.setRuntimeUrl(runtimeUrl);
copilotkit.setRuntimeTransport(
useSingleEndpoint === true
? "single"
: useSingleEndpoint === false
? "rest"
: "auto",
);
copilotkit.setHeaders(stableHeaders);
copilotkit.setProperties(stableProperties);
}, [
runtimeUrl,
useSingleEndpoint,
stableHeaders,
stableProperties,
copilotkit,
]);
// Track executing tool call IDs at the provider level.
// Critical for HITL reconnection: onToolExecutionStart fires before child
// components mount, so we must capture the state here.
const [executingToolCallIds, setExecutingToolCallIds] = useState<
ReadonlySet<string>
>(() => new Set());
// Use ref to avoid subscription churn when onError changes
const onErrorRef = useRef(onError);
useEffect(() => {
onErrorRef.current = onError;
}, [onError]);
// Single subscription for tool execution tracking and error handling.
// Tool call IDs are tracked at the provider level because onToolExecutionStart
// fires before child components mount — critical for HITL reconnection.
useEffect(() => {
const subscription = copilotkit.subscribe({
onToolExecutionStart: ({ toolCallId }) => {
setExecutingToolCallIds((prev) => {
if (prev.has(toolCallId)) return prev;
const next = new Set(prev);
next.add(toolCallId);
return next;
});
},
onToolExecutionEnd: ({ toolCallId }) => {
setExecutingToolCallIds((prev) => {
if (!prev.has(toolCallId)) return prev;
const next = new Set(prev);
next.delete(toolCallId);
return next;
});
},
onError: (event) => {
if (onErrorRef.current) {
onErrorRef.current(event);
} else {
console.error(
`[CopilotKit] Error (${event.code}):`,
event.error,
event.context ?? {},
);
}
},
});
return () => subscription.unsubscribe();
}, [copilotkit]);
const contextValue: CopilotKitContextValue = useMemo(
() => ({
copilotkit,
executingToolCallIds,
}),
[copilotkit, executingToolCallIds],
);
const licenseContextValue = useMemo(
() => ({
status: null as null,
license: null as null,
checkFeature: () => true,
getLimit: () => null,
}),
[],
);
return (
<CopilotKitContext.Provider value={contextValue}>
<LicenseContext.Provider value={licenseContextValue}>
{children}
</LicenseContext.Provider>
</CopilotKitContext.Provider>
);
};