@copilotkit/react-native 1.57.1-canary.1778272612 → 1.57.2

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/src/index.ts CHANGED
@@ -4,16 +4,51 @@
4
4
  * React Native bindings for CopilotKit. Provides a lightweight provider
5
5
  * and re-exports platform-agnostic hooks from @copilotkit/react-core.
6
6
  *
7
+ * Polyfills (DOMException, ReadableStream, TextEncoder, etc.) are
8
+ * auto-imported when this module loads -- no manual
9
+ * `import "@copilotkit/react-native/polyfills"` needed.
10
+ *
7
11
  * Quick start:
8
12
  * ```tsx
9
13
  * import { CopilotKitProvider, useAgent, useCopilotKit } from "@copilotkit/react-native";
10
14
  * ```
11
15
  */
12
16
 
17
+ // Auto-install polyfills so consumers don't need a manual import.
18
+ // Must run before any CopilotKit code that relies on ReadableStream / fetch streaming.
19
+ import "./polyfills";
20
+
13
21
  // React Native provider (no web dependencies)
14
22
  export { CopilotKitProvider } from "./CopilotKitProvider";
15
23
  export type { CopilotKitNativeProviderProps } from "./CopilotKitProvider";
16
24
 
25
+ // Provider props alias (mirrors web's CopilotKitProviderProps)
26
+ export type { CopilotKitNativeProviderProps as CopilotKitProviderProps } from "./CopilotKitProvider";
27
+
28
+ // Headless chat components (no DOM, consumer provides UI)
29
+ export { CopilotChat, useCopilotChatContext } from "./CopilotChat";
30
+ export type { CopilotChatProps, CopilotChatContextValue } from "./CopilotChat";
31
+ export { CopilotModal } from "./CopilotModal";
32
+ export type { CopilotModalProps } from "./CopilotModal";
33
+
34
+ // Native attachments hook and types
35
+ export { useAttachments } from "./hooks/use-attachments";
36
+ export type {
37
+ NativeAttachmentsConfig,
38
+ NativeFileInput,
39
+ UseNativeAttachmentsProps,
40
+ UseNativeAttachmentsReturn,
41
+ } from "./hooks/use-attachments";
42
+
43
+ // Pre-built UI components
44
+ export { CopilotSidebar } from "./CopilotSidebar";
45
+ export type {
46
+ CopilotSidebarProps,
47
+ CopilotSidebarHandle,
48
+ } from "./CopilotSidebar";
49
+ export { CopilotPopup } from "./CopilotPopup";
50
+ export type { CopilotPopupProps, CopilotPopupHandle } from "./CopilotPopup";
51
+
17
52
  // Re-export context and hooks from react-core (platform-agnostic)
18
53
  export {
19
54
  useCopilotKit,
@@ -34,11 +69,50 @@ export {
34
69
  useConfigureSuggestions,
35
70
  useAgentContext,
36
71
  useThreads,
72
+ useRenderTool,
73
+ useCapabilities,
74
+ defineToolCallRenderer,
75
+ CopilotChatDefaultLabels,
37
76
  type UseAgentUpdate,
77
+ type UseInterruptConfig,
78
+ type AgentContextInput,
79
+ type JsonSerializable,
80
+ type Thread,
81
+ type UseThreadsInput,
82
+ type UseThreadsResult,
83
+ type CopilotChatLabels,
84
+ type CopilotChatConfigurationValue,
85
+ type InterruptEvent,
86
+ type InterruptHandlerProps,
87
+ type InterruptRenderProps,
88
+ type ReactFrontendTool,
89
+ type ReactHumanInTheLoop,
90
+ type RenderToolProps,
91
+ type RenderToolInProgressProps,
92
+ type RenderToolExecutingProps,
93
+ type RenderToolCompleteProps,
38
94
  } from "@copilotkit/react-core/v2/headless";
39
95
 
96
+ // useRenderToolCall — web-specific (depends on DOM elements via DefaultToolCallRenderer)
97
+ // useRenderCustomMessages — web-specific (tightly coupled to web chat UI rendering pipeline)
98
+ // useRenderActivityMessage — web-specific (tightly coupled to web chat UI rendering pipeline)
99
+ // useDefaultRenderTool — web-specific (DefaultToolCallRenderer uses <div>, <svg>, etc.)
100
+
40
101
  // Re-export core types commonly needed
41
- export {
42
- type CopilotKitCoreRuntimeConnectionStatus,
43
- type CopilotKitCoreErrorCode,
102
+ export type {
103
+ CopilotKitCoreRuntimeConnectionStatus,
104
+ CopilotKitCoreErrorCode,
105
+ Suggestion,
106
+ FrontendTool,
107
+ ToolCallStatus,
44
108
  } from "@copilotkit/core";
109
+
110
+ // Re-export AG-UI types for consumer convenience (matches web SDK surface)
111
+ export type {
112
+ Message,
113
+ AssistantMessage,
114
+ ToolCall,
115
+ ToolMessage,
116
+ AbstractAgent,
117
+ AgentCapabilities,
118
+ } from "@ag-ui/client";
package/src/polyfills.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * All polyfills required for CopilotKit to work in React Native.
3
3
  *
4
- * Import this BEFORE any CopilotKit code in your app entry point:
5
- * import "@copilotkit/react-native/polyfills";
4
+ * These are auto-imported when `@copilotkit/react-native` is loaded.
5
+ * A manual `import "@copilotkit/react-native/polyfills"` is no longer
6
+ * required but still works for advanced / selective bootstrap scenarios.
6
7
  *
7
8
  * For granular control, import individual polyfills instead:
8
9
  * import "@copilotkit/react-native/polyfills/streams";
@@ -9,6 +9,13 @@
9
9
  * If native fetch already supports ReadableStream bodies (newer RN / Hermes),
10
10
  * the replacement is skipped entirely.
11
11
  *
12
+ * THREADING NOTE: In React Native, XHR callbacks (onprogress, onload, etc.)
13
+ * may fire on a native networking thread. Pushing data into the ReadableStream
14
+ * from that thread can trigger downstream React setState calls on the wrong
15
+ * thread, causing iOS to kill the process with "deleted thread with uncommitted
16
+ * CATransaction". All stream-mutating operations are therefore deferred via
17
+ * setTimeout(fn, 0) to bounce back to the JS thread (main thread in Hermes).
18
+ *
12
19
  * Call `installStreamingFetch()` once at app startup after polyfills.
13
20
  */
14
21
 
@@ -199,33 +206,49 @@ export function installStreamingFetch(): void {
199
206
  },
200
207
  });
201
208
 
209
+ // All XHR callbacks are wrapped with setTimeout(fn, 0) to ensure they
210
+ // run on the JS thread. In React Native, XHR callbacks may fire on a
211
+ // native networking thread; calling streamController.enqueue() there
212
+ // triggers downstream React setState on the wrong thread, which causes
213
+ // iOS to kill the process ("deleted thread with uncommitted CATransaction").
214
+ // setTimeout(fn, 0) defers execution to the JS event loop (main thread
215
+ // in Hermes) with negligible latency — streaming still feels real-time.
216
+
202
217
  xhr.onprogress = function () {
203
- try {
204
- flushChunks();
205
- } catch (err) {
206
- fail(err instanceof Error ? err : new Error(String(err)));
207
- xhr.abort();
208
- }
218
+ setTimeout(() => {
219
+ try {
220
+ flushChunks();
221
+ } catch (err) {
222
+ fail(err instanceof Error ? err : new Error(String(err)));
223
+ xhr.abort();
224
+ }
225
+ }, 0);
209
226
  };
210
227
 
211
228
  xhr.onload = function () {
212
- cleanupAbortListener();
213
- try {
214
- flushChunks();
215
- } catch (err) {
216
- fail(err instanceof Error ? err : new Error(String(err)));
217
- return;
218
- }
219
- closeStream();
220
- resolveFullText(xhr.responseText);
229
+ setTimeout(() => {
230
+ cleanupAbortListener();
231
+ try {
232
+ flushChunks();
233
+ } catch (err) {
234
+ fail(err instanceof Error ? err : new Error(String(err)));
235
+ return;
236
+ }
237
+ closeStream();
238
+ resolveFullText(xhr.responseText);
239
+ }, 0);
221
240
  };
222
241
 
223
242
  xhr.onerror = function () {
224
- fail(new TypeError("Network request failed"));
243
+ setTimeout(() => {
244
+ fail(new TypeError("Network request failed"));
245
+ }, 0);
225
246
  };
226
247
 
227
248
  xhr.ontimeout = function () {
228
- fail(new TypeError("Network request timed out"));
249
+ setTimeout(() => {
250
+ fail(new TypeError("Network request timed out"));
251
+ }, 0);
229
252
  };
230
253
 
231
254
  // Resolve with Response once headers arrive.
@@ -233,97 +256,105 @@ export function installStreamingFetch(): void {
233
256
  // DNS errors, and mixed-content blocks — let onerror handle those.
234
257
  let resp: StreamingFetchResponse | null = null;
235
258
  xhr.onreadystatechange = function () {
236
- // Safety net: if XHR completed but we never resolved/rejected, fail explicitly.
237
- // This can happen when status === 0 and onerror doesn't fire (some RN networking impls).
238
- if (xhr.readyState === 4 && !settled && !resp) {
239
- fail(
240
- new TypeError(
241
- `Network request to ${url} completed with status ${xhr.status} but no response was produced. ` +
242
- `This may indicate a CORS failure, DNS error, or React Native networking issue.`,
243
- ),
244
- );
245
- return;
246
- }
247
-
248
- if (xhr.readyState >= 2 && !resp && xhr.status !== 0) {
249
- const respHeaders: Record<string, string> = {};
250
- const rawHeaders = xhr.getAllResponseHeaders() || "";
251
- for (const line of rawHeaders.trim().split("\r\n")) {
252
- const idx = line.indexOf(": ");
253
- if (idx > 0) {
254
- respHeaders[line.slice(0, idx).toLowerCase()] = line.slice(
255
- idx + 2,
256
- );
257
- }
259
+ // Capture XHR state synchronously before deferring — XHR properties
260
+ // may change between now and when setTimeout fires.
261
+ const readyState = xhr.readyState;
262
+ const xhrStatus = xhr.status;
263
+ const xhrStatusText = xhr.statusText;
264
+ const rawHeaders = xhr.getAllResponseHeaders() || "";
265
+
266
+ setTimeout(() => {
267
+ // Safety net: if XHR completed but we never resolved/rejected, fail explicitly.
268
+ // This can happen when status === 0 and onerror doesn't fire (some RN networking impls).
269
+ if (readyState === 4 && !settled && !resp) {
270
+ fail(
271
+ new TypeError(
272
+ `Network request to ${url} completed with status ${xhrStatus} but no response was produced. ` +
273
+ `This may indicate a CORS failure, DNS error, or React Native networking issue.`,
274
+ ),
275
+ );
276
+ return;
258
277
  }
259
278
 
260
- const responseHeaders = new Headers(respHeaders);
261
-
262
- let bodyUsed = false;
263
-
264
- resp = {
265
- // Duck-typed Response object (not a native Response instance)
266
- ok: xhr.status >= 200 && xhr.status < 300,
267
- status: xhr.status,
268
- statusText: xhr.statusText,
269
- url: url,
270
- type: "basic",
271
- redirected: false,
272
- get bodyUsed() {
273
- return bodyUsed;
274
- },
275
- headers: responseHeaders,
276
- body: stream,
277
- json: async () => {
278
- bodyUsed = true;
279
- const text = await fullTextPromise;
280
- try {
281
- return JSON.parse(text);
282
- } catch (e) {
283
- throw new TypeError(
284
- `Failed to parse JSON from ${method} ${url} (status ${xhr.status}): ${
285
- text.length > 200 ? text.slice(0, 200) + "..." : text
286
- }`,
279
+ if (readyState >= 2 && !resp && xhrStatus !== 0) {
280
+ const respHeaders: Record<string, string> = {};
281
+ for (const line of rawHeaders.trim().split("\r\n")) {
282
+ const idx = line.indexOf(": ");
283
+ if (idx > 0) {
284
+ respHeaders[line.slice(0, idx).toLowerCase()] = line.slice(
285
+ idx + 2,
287
286
  );
288
287
  }
289
- },
290
- text: async () => {
291
- bodyUsed = true;
292
- return fullTextPromise;
293
- },
294
- arrayBuffer: async () => {
295
- bodyUsed = true;
296
- return encoder.encode(await fullTextPromise).buffer;
297
- },
298
- blob: async () => {
299
- bodyUsed = true;
300
- const buf = encoder.encode(await fullTextPromise);
301
- if (typeof Blob !== "undefined") {
302
- return new Blob([buf], {
303
- type: responseHeaders.get("content-type") || "",
304
- });
305
- }
306
- throw new Error(
307
- "Blob is not available in this React Native environment.",
308
- );
309
- },
310
- clone: () => {
311
- throw new Error(
312
- "Response.clone() is not supported by the React Native streaming fetch polyfill.",
313
- );
314
- },
315
- formData: async () => {
316
- throw new Error(
317
- "Response.formData() is not supported by the React Native streaming fetch polyfill.",
318
- );
319
- },
320
- };
321
- settled = true;
322
- // NOTE: abort listener is NOT removed here — the signal must remain
323
- // wired to xhr.abort() for mid-stream cancellation. Cleanup happens
324
- // in terminal handlers (onload, onerror, ontimeout) or onAbort itself.
325
- resolve(resp as unknown as Response);
326
- }
288
+ }
289
+
290
+ const responseHeaders = new Headers(respHeaders);
291
+
292
+ let bodyUsed = false;
293
+
294
+ resp = {
295
+ // Duck-typed Response object (not a native Response instance)
296
+ ok: xhrStatus >= 200 && xhrStatus < 300,
297
+ status: xhrStatus,
298
+ statusText: xhrStatusText,
299
+ url: url,
300
+ type: "basic",
301
+ redirected: false,
302
+ get bodyUsed() {
303
+ return bodyUsed;
304
+ },
305
+ headers: responseHeaders,
306
+ body: stream,
307
+ json: async () => {
308
+ bodyUsed = true;
309
+ const text = await fullTextPromise;
310
+ try {
311
+ return JSON.parse(text);
312
+ } catch (e) {
313
+ throw new TypeError(
314
+ `Failed to parse JSON from ${method} ${url} (status ${xhrStatus}): ${
315
+ text.length > 200 ? text.slice(0, 200) + "..." : text
316
+ }`,
317
+ );
318
+ }
319
+ },
320
+ text: async () => {
321
+ bodyUsed = true;
322
+ return fullTextPromise;
323
+ },
324
+ arrayBuffer: async () => {
325
+ bodyUsed = true;
326
+ return encoder.encode(await fullTextPromise).buffer;
327
+ },
328
+ blob: async () => {
329
+ bodyUsed = true;
330
+ const buf = encoder.encode(await fullTextPromise);
331
+ if (typeof Blob !== "undefined") {
332
+ return new Blob([buf], {
333
+ type: responseHeaders.get("content-type") || "",
334
+ });
335
+ }
336
+ throw new Error(
337
+ "Blob is not available in this React Native environment.",
338
+ );
339
+ },
340
+ clone: () => {
341
+ throw new Error(
342
+ "Response.clone() is not supported by the React Native streaming fetch polyfill.",
343
+ );
344
+ },
345
+ formData: async () => {
346
+ throw new Error(
347
+ "Response.formData() is not supported by the React Native streaming fetch polyfill.",
348
+ );
349
+ },
350
+ };
351
+ settled = true;
352
+ // NOTE: abort listener is NOT removed here — the signal must remain
353
+ // wired to xhr.abort() for mid-stream cancellation. Cleanup happens
354
+ // in terminal handlers (onload, onerror, ontimeout) or onAbort itself.
355
+ resolve(resp as unknown as Response);
356
+ }
357
+ }, 0);
327
358
  };
328
359
 
329
360
  xhr.send(body ?? null);
package/tsdown.config.ts CHANGED
@@ -18,6 +18,7 @@ export default defineConfig({
18
18
  external: [
19
19
  "react",
20
20
  "react-native",
21
+ "@ag-ui/client",
21
22
  "@copilotkit/react-core",
22
23
  "@copilotkit/core",
23
24
  "@copilotkit/shared",
package/vitest.config.mjs CHANGED
@@ -1,6 +1,22 @@
1
1
  import { defineConfig } from "vitest/config";
2
+ import path from "node:path";
2
3
 
3
4
  export default defineConfig({
5
+ resolve: {
6
+ alias: {
7
+ // Expo modules are not installed in the monorepo (they live in the
8
+ // user's RN app). Point them at lightweight stubs so Vite's import
9
+ // analysis doesn't fail. Tests override these via vi.mock().
10
+ "expo-document-picker": path.resolve(
11
+ __dirname,
12
+ "src/__tests__/__mocks__/expo-document-picker.ts",
13
+ ),
14
+ "expo-file-system": path.resolve(
15
+ __dirname,
16
+ "src/__tests__/__mocks__/expo-file-system.ts",
17
+ ),
18
+ },
19
+ },
4
20
  test: {
5
21
  environment: "jsdom",
6
22
  globals: true,
@@ -11,6 +27,9 @@ export default defineConfig({
11
27
  server: {
12
28
  deps: {
13
29
  inline: [/@copilotkit/],
30
+ // react-native uses Flow syntax that Vitest/Rollup can't parse outside
31
+ // of Metro. Exclude it so the test runner doesn't attempt to bundle it.
32
+ external: ["react-native"],
14
33
  },
15
34
  },
16
35
  },