@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/README.md +11 -1
- package/dist/index.cjs +752 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +394 -6
- package/dist/index.d.mts +394 -6
- package/dist/index.mjs +725 -14
- package/dist/index.mjs.map +1 -1
- package/dist/polyfills.cjs +86 -73
- package/dist/polyfills.cjs.map +1 -1
- package/dist/polyfills.mjs +86 -73
- package/dist/polyfills.mjs.map +1 -1
- package/package.json +21 -5
- package/src/CopilotChat.tsx +293 -0
- package/src/CopilotKitProvider.tsx +55 -13
- package/src/CopilotModal.tsx +32 -0
- package/src/CopilotPopup.tsx +359 -0
- package/src/CopilotSidebar.tsx +357 -0
- package/src/__tests__/__mocks__/expo-document-picker.ts +13 -0
- package/src/__tests__/__mocks__/expo-file-system.ts +12 -0
- package/src/__tests__/attachments-integration.test.tsx +336 -0
- package/src/__tests__/copilot-chat-agentid.test.tsx +305 -0
- package/src/__tests__/copilot-chat-attachments.test.tsx +259 -0
- package/src/__tests__/copilot-popup.test.tsx +558 -0
- package/src/__tests__/copilot-sidebar.test.tsx +500 -0
- package/src/__tests__/copilotkit-provider.test.tsx +3 -0
- package/src/__tests__/headless-integration.test.tsx +55 -1
- package/src/__tests__/streaming-fetch.test.ts +84 -44
- package/src/__tests__/use-attachments.test.ts +410 -0
- package/src/hooks/use-attachments.ts +274 -0
- package/src/index.ts +77 -3
- package/src/polyfills.ts +3 -2
- package/src/streaming-fetch.ts +135 -104
- package/tsdown.config.ts +1 -0
- package/vitest.config.mjs +19 -0
package/dist/polyfills.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"polyfills.mjs","names":[],"sources":["../src/streaming-fetch.ts","../src/polyfills.ts"],"sourcesContent":["/**\n * Streaming fetch implementation for React Native.\n *\n * React Native's built-in fetch doesn't support response.body.getReader()\n * (ReadableStream). This replaces global.fetch with an XHR-based\n * implementation that streams chunks via ReadableStream, enabling\n * CopilotKit's SSE-based agent communication.\n *\n * If native fetch already supports ReadableStream bodies (newer RN / Hermes),\n * the replacement is skipped entirely.\n *\n * Call `installStreamingFetch()` once at app startup after polyfills.\n */\n\ndeclare const global: typeof globalThis;\n\n/** Subset of the Response interface implemented by the streaming fetch polyfill. */\ninterface StreamingFetchResponse {\n readonly ok: boolean;\n readonly status: number;\n readonly statusText: string;\n readonly url: string;\n readonly type: string;\n readonly redirected: boolean;\n readonly bodyUsed: boolean;\n readonly headers: Headers;\n readonly body: ReadableStream<Uint8Array>;\n json(): Promise<unknown>;\n text(): Promise<string>;\n arrayBuffer(): Promise<ArrayBuffer>;\n blob(): Promise<Blob>;\n clone(): never;\n formData(): Promise<never>;\n}\n\nfunction createAbortError(): DOMException {\n return new (global as any).DOMException(\n \"The operation was aborted.\",\n \"AbortError\",\n );\n}\n\nexport function installStreamingFetch(): void {\n // Skip if native fetch already supports ReadableStream body.\n // Newer React Native versions (Hermes) may support this natively.\n try {\n const testResponse = new Response(\"\");\n if (\n testResponse.body != null &&\n typeof testResponse.body.getReader === \"function\"\n ) {\n return;\n }\n } catch (e) {\n // Response constructor unavailable — expected in older RN environments.\n if (\n __DEV__ &&\n e instanceof Error &&\n !(e instanceof ReferenceError) &&\n !(e instanceof TypeError)\n ) {\n console.warn(\n \"[CopilotKit] Unexpected error during streaming fetch feature detection, \" +\n \"installing XHR-based polyfill:\",\n e,\n );\n }\n }\n\n const originalFetch = global.fetch;\n const TextEncoder = global.TextEncoder;\n\n const streamingFetch = function streamingFetch(\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> {\n // Extract defaults from Request object when input is a Request\n const request =\n typeof input !== \"string\" && !(input instanceof URL) ? input : null;\n let url: string;\n if (typeof input === \"string\") {\n url = input;\n } else if (input instanceof URL) {\n url = input.href;\n } else {\n url = (input as Request).url;\n }\n const method = init?.method || request?.method || \"GET\";\n const headers = init?.headers || (request ? request.headers : {});\n const body = (init?.body ?? request?.body) as string | null | undefined;\n const signal = init?.signal || request?.signal;\n\n return new Promise((resolve, reject) => {\n // Reject immediately if signal is already aborted (per fetch spec)\n if (signal?.aborted) {\n reject(createAbortError());\n return;\n }\n\n const xhr = new XMLHttpRequest();\n xhr.open(method, url);\n\n // Default 60s timeout to prevent hanging on stalled mobile connections\n // (WiFi→cellular transitions, tunnels, serverless cold starts).\n // Callers can still use AbortSignal.timeout() for finer control.\n xhr.timeout = 60_000;\n\n let headerEntries: [string, string][];\n if (headers instanceof Headers) {\n headerEntries = Array.from(headers.entries());\n } else if (Array.isArray(headers)) {\n headerEntries = headers as [string, string][];\n } else {\n headerEntries = Object.entries(headers as Record<string, string>);\n }\n for (const [key, value] of headerEntries) {\n xhr.setRequestHeader(key, value as string);\n }\n\n xhr.responseType = \"text\";\n\n let streamController: ReadableStreamDefaultController<Uint8Array> | null =\n null;\n let lastIndex = 0;\n let streamClosed = false;\n let settled = false;\n const encoder = new TextEncoder();\n\n // Promise that resolves/rejects when XHR completes or fails\n let resolveFullText: (text: string) => void;\n let rejectFullText: (error: Error) => void;\n const fullTextPromise = new Promise<string>((res, rej) => {\n resolveFullText = res;\n rejectFullText = rej;\n });\n // Prevent unhandled rejection when error occurs but .text()/.json() is never called\n fullTextPromise.catch(() => {});\n\n function closeStream() {\n if (streamController && !streamClosed) {\n streamClosed = true;\n streamController.close();\n }\n }\n\n function errorStream(err: Error) {\n if (streamController && !streamClosed) {\n streamClosed = true;\n streamController.error(err);\n }\n }\n\n function flushChunks() {\n if (\n streamController &&\n !streamClosed &&\n xhr.responseText.length > lastIndex\n ) {\n const newData = xhr.responseText.slice(lastIndex);\n lastIndex = xhr.responseText.length;\n streamController.enqueue(encoder.encode(newData));\n }\n }\n\n /** Centralized error handler — errors the stream, rejects fullTextPromise,\n * and rejects the outer fetch promise if not yet settled. */\n function fail(err: Error) {\n cleanupAbortListener();\n errorStream(err);\n rejectFullText(err);\n if (!settled) {\n settled = true;\n reject(err);\n }\n }\n\n const onAbort = () => {\n fail(createAbortError());\n xhr.abort();\n };\n\n if (signal) {\n signal.addEventListener(\"abort\", onAbort);\n }\n\n function cleanupAbortListener() {\n if (signal) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n }\n\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n streamController = controller;\n },\n cancel() {\n xhr.abort();\n rejectFullText(createAbortError());\n },\n });\n\n xhr.onprogress = function () {\n try {\n flushChunks();\n } catch (err) {\n fail(err instanceof Error ? err : new Error(String(err)));\n xhr.abort();\n }\n };\n\n xhr.onload = function () {\n cleanupAbortListener();\n try {\n flushChunks();\n } catch (err) {\n fail(err instanceof Error ? err : new Error(String(err)));\n return;\n }\n closeStream();\n resolveFullText(xhr.responseText);\n };\n\n xhr.onerror = function () {\n fail(new TypeError(\"Network request failed\"));\n };\n\n xhr.ontimeout = function () {\n fail(new TypeError(\"Network request timed out\"));\n };\n\n // Resolve with Response once headers arrive.\n // Guard against status === 0 which XHR produces for CORS failures,\n // DNS errors, and mixed-content blocks — let onerror handle those.\n let resp: StreamingFetchResponse | null = null;\n xhr.onreadystatechange = function () {\n // Safety net: if XHR completed but we never resolved/rejected, fail explicitly.\n // This can happen when status === 0 and onerror doesn't fire (some RN networking impls).\n if (xhr.readyState === 4 && !settled && !resp) {\n fail(\n new TypeError(\n `Network request to ${url} completed with status ${xhr.status} but no response was produced. ` +\n `This may indicate a CORS failure, DNS error, or React Native networking issue.`,\n ),\n );\n return;\n }\n\n if (xhr.readyState >= 2 && !resp && xhr.status !== 0) {\n const respHeaders: Record<string, string> = {};\n const rawHeaders = xhr.getAllResponseHeaders() || \"\";\n for (const line of rawHeaders.trim().split(\"\\r\\n\")) {\n const idx = line.indexOf(\": \");\n if (idx > 0) {\n respHeaders[line.slice(0, idx).toLowerCase()] = line.slice(\n idx + 2,\n );\n }\n }\n\n const responseHeaders = new Headers(respHeaders);\n\n let bodyUsed = false;\n\n resp = {\n // Duck-typed Response object (not a native Response instance)\n ok: xhr.status >= 200 && xhr.status < 300,\n status: xhr.status,\n statusText: xhr.statusText,\n url: url,\n type: \"basic\",\n redirected: false,\n get bodyUsed() {\n return bodyUsed;\n },\n headers: responseHeaders,\n body: stream,\n json: async () => {\n bodyUsed = true;\n const text = await fullTextPromise;\n try {\n return JSON.parse(text);\n } catch (e) {\n throw new TypeError(\n `Failed to parse JSON from ${method} ${url} (status ${xhr.status}): ${\n text.length > 200 ? text.slice(0, 200) + \"...\" : text\n }`,\n );\n }\n },\n text: async () => {\n bodyUsed = true;\n return fullTextPromise;\n },\n arrayBuffer: async () => {\n bodyUsed = true;\n return encoder.encode(await fullTextPromise).buffer;\n },\n blob: async () => {\n bodyUsed = true;\n const buf = encoder.encode(await fullTextPromise);\n if (typeof Blob !== \"undefined\") {\n return new Blob([buf], {\n type: responseHeaders.get(\"content-type\") || \"\",\n });\n }\n throw new Error(\n \"Blob is not available in this React Native environment.\",\n );\n },\n clone: () => {\n throw new Error(\n \"Response.clone() is not supported by the React Native streaming fetch polyfill.\",\n );\n },\n formData: async () => {\n throw new Error(\n \"Response.formData() is not supported by the React Native streaming fetch polyfill.\",\n );\n },\n };\n settled = true;\n // NOTE: abort listener is NOT removed here — the signal must remain\n // wired to xhr.abort() for mid-stream cancellation. Cleanup happens\n // in terminal handlers (onload, onerror, ontimeout) or onAbort itself.\n resolve(resp as unknown as Response);\n }\n };\n\n xhr.send(body ?? null);\n });\n };\n\n // Expose original fetch for opt-out (e.g., third-party libs that need native behavior)\n (streamingFetch as any).__originalFetch = originalFetch;\n global.fetch = streamingFetch;\n}\n","/**\n * All polyfills required for CopilotKit to work in React Native.\n *\n * Import this BEFORE any CopilotKit code in your app entry point:\n * import \"@copilotkit/react-native/polyfills\";\n *\n * For granular control, import individual polyfills instead:\n * import \"@copilotkit/react-native/polyfills/streams\";\n * import \"@copilotkit/react-native/polyfills/encoding\";\n * import \"@copilotkit/react-native/polyfills/crypto\";\n * import \"@copilotkit/react-native/polyfills/dom\";\n * import \"@copilotkit/react-native/polyfills/location\";\n */\n\nimport \"./polyfills/streams\";\nimport \"./polyfills/encoding\";\nimport \"./polyfills/crypto\";\nimport \"./polyfills/dom\";\nimport \"./polyfills/location\";\n\nimport { installStreamingFetch } from \"./streaming-fetch\";\ninstallStreamingFetch();\n"],"mappings":";AAmCA,SAAS,mBAAiC;AACxC,QAAO,IAAK,OAAe,aACzB,8BACA,aACD;;AAGH,SAAgB,wBAA8B;AAG5C,KAAI;EACF,MAAM,eAAe,IAAI,SAAS,GAAG;AACrC,MACE,aAAa,QAAQ,QACrB,OAAO,aAAa,KAAK,cAAc,WAEvC;UAEK,GAAG;AAEV,MACE,WACA,aAAa,SACb,EAAE,aAAa,mBACf,EAAE,aAAa,WAEf,SAAQ,KACN,0GAEA,EACD;;CAIL,MAAM,gBAAgB,OAAO;CAC7B,MAAM,cAAc,OAAO;CAE3B,MAAM,iBAAiB,SAAS,eAC9B,OACA,MACmB;EAEnB,MAAM,UACJ,OAAO,UAAU,YAAY,EAAE,iBAAiB,OAAO,QAAQ;EACjE,IAAI;AACJ,MAAI,OAAO,UAAU,SACnB,OAAM;WACG,iBAAiB,IAC1B,OAAM,MAAM;MAEZ,OAAO,MAAkB;EAE3B,MAAM,SAAS,MAAM,UAAU,SAAS,UAAU;EAClD,MAAM,UAAU,MAAM,YAAY,UAAU,QAAQ,UAAU,EAAE;EAChE,MAAM,OAAQ,MAAM,QAAQ,SAAS;EACrC,MAAM,SAAS,MAAM,UAAU,SAAS;AAExC,SAAO,IAAI,SAAS,SAAS,WAAW;AAEtC,OAAI,QAAQ,SAAS;AACnB,WAAO,kBAAkB,CAAC;AAC1B;;GAGF,MAAM,MAAM,IAAI,gBAAgB;AAChC,OAAI,KAAK,QAAQ,IAAI;AAKrB,OAAI,UAAU;GAEd,IAAI;AACJ,OAAI,mBAAmB,QACrB,iBAAgB,MAAM,KAAK,QAAQ,SAAS,CAAC;YACpC,MAAM,QAAQ,QAAQ,CA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AAI;AACF,eAAO,KAAK,MAAM,KAAK;gBAChB,GAAG;AACV,cAAM,IAAI,UACR,6BAA6B,OAAO,GAAG,IAAI,WAAW,IAAI,OAAO,KAC/D,KAAK,SAAS,MAAM,KAAK,MAAM,GAAG,IAAI,GAAG,QAAQ,OAEpD;;;MAGL,MAAM,YAAY;AAChB,kBAAW;AACX,cAAO;;MAET,aAAa,YAAY;AACvB,kBAAW;AACX,cAAO,QAAQ,OAAO,MAAM,gBAAgB,CAAC;;MAE/C,MAAM,YAAY;AAChB,kBAAW;OACX,MAAM,MAAM,QAAQ,OAAO,MAAM,gBAAgB;AACjD,WAAI,OAAO,SAAS,YAClB,QAAO,IAAI,KAAK,CAAC,IAAI,EAAE,EACrB,MAAM,gBAAgB,IAAI,eAAe,IAAI,IAC9C,CAAC;AAEJ,aAAM,IAAI,MACR,0DACD;;MAEH,aAAa;AACX,aAAM,IAAI,MACR,kFACD;;MAEH,UAAU,YAAY;AACpB,aAAM,IAAI,MACR,qFACD;;MAEJ;AACD,eAAU;AAIV,aAAQ,KAA4B;;;AAIxC,OAAI,KAAK,QAAQ,KAAK;IACtB;;AAIJ,CAAC,eAAuB,kBAAkB;AAC1C,QAAO,QAAQ;;;;;ACzTjB,uBAAuB"}
|
|
1
|
+
{"version":3,"file":"polyfills.mjs","names":[],"sources":["../src/streaming-fetch.ts","../src/polyfills.ts"],"sourcesContent":["/**\n * Streaming fetch implementation for React Native.\n *\n * React Native's built-in fetch doesn't support response.body.getReader()\n * (ReadableStream). This replaces global.fetch with an XHR-based\n * implementation that streams chunks via ReadableStream, enabling\n * CopilotKit's SSE-based agent communication.\n *\n * If native fetch already supports ReadableStream bodies (newer RN / Hermes),\n * the replacement is skipped entirely.\n *\n * THREADING NOTE: In React Native, XHR callbacks (onprogress, onload, etc.)\n * may fire on a native networking thread. Pushing data into the ReadableStream\n * from that thread can trigger downstream React setState calls on the wrong\n * thread, causing iOS to kill the process with \"deleted thread with uncommitted\n * CATransaction\". All stream-mutating operations are therefore deferred via\n * setTimeout(fn, 0) to bounce back to the JS thread (main thread in Hermes).\n *\n * Call `installStreamingFetch()` once at app startup after polyfills.\n */\n\ndeclare const global: typeof globalThis;\n\n/** Subset of the Response interface implemented by the streaming fetch polyfill. */\ninterface StreamingFetchResponse {\n readonly ok: boolean;\n readonly status: number;\n readonly statusText: string;\n readonly url: string;\n readonly type: string;\n readonly redirected: boolean;\n readonly bodyUsed: boolean;\n readonly headers: Headers;\n readonly body: ReadableStream<Uint8Array>;\n json(): Promise<unknown>;\n text(): Promise<string>;\n arrayBuffer(): Promise<ArrayBuffer>;\n blob(): Promise<Blob>;\n clone(): never;\n formData(): Promise<never>;\n}\n\nfunction createAbortError(): DOMException {\n return new (global as any).DOMException(\n \"The operation was aborted.\",\n \"AbortError\",\n );\n}\n\nexport function installStreamingFetch(): void {\n // Skip if native fetch already supports ReadableStream body.\n // Newer React Native versions (Hermes) may support this natively.\n try {\n const testResponse = new Response(\"\");\n if (\n testResponse.body != null &&\n typeof testResponse.body.getReader === \"function\"\n ) {\n return;\n }\n } catch (e) {\n // Response constructor unavailable — expected in older RN environments.\n if (\n __DEV__ &&\n e instanceof Error &&\n !(e instanceof ReferenceError) &&\n !(e instanceof TypeError)\n ) {\n console.warn(\n \"[CopilotKit] Unexpected error during streaming fetch feature detection, \" +\n \"installing XHR-based polyfill:\",\n e,\n );\n }\n }\n\n const originalFetch = global.fetch;\n const TextEncoder = global.TextEncoder;\n\n const streamingFetch = function streamingFetch(\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> {\n // Extract defaults from Request object when input is a Request\n const request =\n typeof input !== \"string\" && !(input instanceof URL) ? input : null;\n let url: string;\n if (typeof input === \"string\") {\n url = input;\n } else if (input instanceof URL) {\n url = input.href;\n } else {\n url = (input as Request).url;\n }\n const method = init?.method || request?.method || \"GET\";\n const headers = init?.headers || (request ? request.headers : {});\n const body = (init?.body ?? request?.body) as string | null | undefined;\n const signal = init?.signal || request?.signal;\n\n return new Promise((resolve, reject) => {\n // Reject immediately if signal is already aborted (per fetch spec)\n if (signal?.aborted) {\n reject(createAbortError());\n return;\n }\n\n const xhr = new XMLHttpRequest();\n xhr.open(method, url);\n\n // Default 60s timeout to prevent hanging on stalled mobile connections\n // (WiFi→cellular transitions, tunnels, serverless cold starts).\n // Callers can still use AbortSignal.timeout() for finer control.\n xhr.timeout = 60_000;\n\n let headerEntries: [string, string][];\n if (headers instanceof Headers) {\n headerEntries = Array.from(headers.entries());\n } else if (Array.isArray(headers)) {\n headerEntries = headers as [string, string][];\n } else {\n headerEntries = Object.entries(headers as Record<string, string>);\n }\n for (const [key, value] of headerEntries) {\n xhr.setRequestHeader(key, value as string);\n }\n\n xhr.responseType = \"text\";\n\n let streamController: ReadableStreamDefaultController<Uint8Array> | null =\n null;\n let lastIndex = 0;\n let streamClosed = false;\n let settled = false;\n const encoder = new TextEncoder();\n\n // Promise that resolves/rejects when XHR completes or fails\n let resolveFullText: (text: string) => void;\n let rejectFullText: (error: Error) => void;\n const fullTextPromise = new Promise<string>((res, rej) => {\n resolveFullText = res;\n rejectFullText = rej;\n });\n // Prevent unhandled rejection when error occurs but .text()/.json() is never called\n fullTextPromise.catch(() => {});\n\n function closeStream() {\n if (streamController && !streamClosed) {\n streamClosed = true;\n streamController.close();\n }\n }\n\n function errorStream(err: Error) {\n if (streamController && !streamClosed) {\n streamClosed = true;\n streamController.error(err);\n }\n }\n\n function flushChunks() {\n if (\n streamController &&\n !streamClosed &&\n xhr.responseText.length > lastIndex\n ) {\n const newData = xhr.responseText.slice(lastIndex);\n lastIndex = xhr.responseText.length;\n streamController.enqueue(encoder.encode(newData));\n }\n }\n\n /** Centralized error handler — errors the stream, rejects fullTextPromise,\n * and rejects the outer fetch promise if not yet settled. */\n function fail(err: Error) {\n cleanupAbortListener();\n errorStream(err);\n rejectFullText(err);\n if (!settled) {\n settled = true;\n reject(err);\n }\n }\n\n const onAbort = () => {\n fail(createAbortError());\n xhr.abort();\n };\n\n if (signal) {\n signal.addEventListener(\"abort\", onAbort);\n }\n\n function cleanupAbortListener() {\n if (signal) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n }\n\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n streamController = controller;\n },\n cancel() {\n xhr.abort();\n rejectFullText(createAbortError());\n },\n });\n\n // All XHR callbacks are wrapped with setTimeout(fn, 0) to ensure they\n // run on the JS thread. In React Native, XHR callbacks may fire on a\n // native networking thread; calling streamController.enqueue() there\n // triggers downstream React setState on the wrong thread, which causes\n // iOS to kill the process (\"deleted thread with uncommitted CATransaction\").\n // setTimeout(fn, 0) defers execution to the JS event loop (main thread\n // in Hermes) with negligible latency — streaming still feels real-time.\n\n xhr.onprogress = function () {\n setTimeout(() => {\n try {\n flushChunks();\n } catch (err) {\n fail(err instanceof Error ? err : new Error(String(err)));\n xhr.abort();\n }\n }, 0);\n };\n\n xhr.onload = function () {\n setTimeout(() => {\n cleanupAbortListener();\n try {\n flushChunks();\n } catch (err) {\n fail(err instanceof Error ? err : new Error(String(err)));\n return;\n }\n closeStream();\n resolveFullText(xhr.responseText);\n }, 0);\n };\n\n xhr.onerror = function () {\n setTimeout(() => {\n fail(new TypeError(\"Network request failed\"));\n }, 0);\n };\n\n xhr.ontimeout = function () {\n setTimeout(() => {\n fail(new TypeError(\"Network request timed out\"));\n }, 0);\n };\n\n // Resolve with Response once headers arrive.\n // Guard against status === 0 which XHR produces for CORS failures,\n // DNS errors, and mixed-content blocks — let onerror handle those.\n let resp: StreamingFetchResponse | null = null;\n xhr.onreadystatechange = function () {\n // Capture XHR state synchronously before deferring — XHR properties\n // may change between now and when setTimeout fires.\n const readyState = xhr.readyState;\n const xhrStatus = xhr.status;\n const xhrStatusText = xhr.statusText;\n const rawHeaders = xhr.getAllResponseHeaders() || \"\";\n\n setTimeout(() => {\n // Safety net: if XHR completed but we never resolved/rejected, fail explicitly.\n // This can happen when status === 0 and onerror doesn't fire (some RN networking impls).\n if (readyState === 4 && !settled && !resp) {\n fail(\n new TypeError(\n `Network request to ${url} completed with status ${xhrStatus} but no response was produced. ` +\n `This may indicate a CORS failure, DNS error, or React Native networking issue.`,\n ),\n );\n return;\n }\n\n if (readyState >= 2 && !resp && xhrStatus !== 0) {\n const respHeaders: Record<string, string> = {};\n for (const line of rawHeaders.trim().split(\"\\r\\n\")) {\n const idx = line.indexOf(\": \");\n if (idx > 0) {\n respHeaders[line.slice(0, idx).toLowerCase()] = line.slice(\n idx + 2,\n );\n }\n }\n\n const responseHeaders = new Headers(respHeaders);\n\n let bodyUsed = false;\n\n resp = {\n // Duck-typed Response object (not a native Response instance)\n ok: xhrStatus >= 200 && xhrStatus < 300,\n status: xhrStatus,\n statusText: xhrStatusText,\n url: url,\n type: \"basic\",\n redirected: false,\n get bodyUsed() {\n return bodyUsed;\n },\n headers: responseHeaders,\n body: stream,\n json: async () => {\n bodyUsed = true;\n const text = await fullTextPromise;\n try {\n return JSON.parse(text);\n } catch (e) {\n throw new TypeError(\n `Failed to parse JSON from ${method} ${url} (status ${xhrStatus}): ${\n text.length > 200 ? text.slice(0, 200) + \"...\" : text\n }`,\n );\n }\n },\n text: async () => {\n bodyUsed = true;\n return fullTextPromise;\n },\n arrayBuffer: async () => {\n bodyUsed = true;\n return encoder.encode(await fullTextPromise).buffer;\n },\n blob: async () => {\n bodyUsed = true;\n const buf = encoder.encode(await fullTextPromise);\n if (typeof Blob !== \"undefined\") {\n return new Blob([buf], {\n type: responseHeaders.get(\"content-type\") || \"\",\n });\n }\n throw new Error(\n \"Blob is not available in this React Native environment.\",\n );\n },\n clone: () => {\n throw new Error(\n \"Response.clone() is not supported by the React Native streaming fetch polyfill.\",\n );\n },\n formData: async () => {\n throw new Error(\n \"Response.formData() is not supported by the React Native streaming fetch polyfill.\",\n );\n },\n };\n settled = true;\n // NOTE: abort listener is NOT removed here — the signal must remain\n // wired to xhr.abort() for mid-stream cancellation. Cleanup happens\n // in terminal handlers (onload, onerror, ontimeout) or onAbort itself.\n resolve(resp as unknown as Response);\n }\n }, 0);\n };\n\n xhr.send(body ?? null);\n });\n };\n\n // Expose original fetch for opt-out (e.g., third-party libs that need native behavior)\n (streamingFetch as any).__originalFetch = originalFetch;\n global.fetch = streamingFetch;\n}\n","/**\n * All polyfills required for CopilotKit to work in React Native.\n *\n * These are auto-imported when `@copilotkit/react-native` is loaded.\n * A manual `import \"@copilotkit/react-native/polyfills\"` is no longer\n * required but still works for advanced / selective bootstrap scenarios.\n *\n * For granular control, import individual polyfills instead:\n * import \"@copilotkit/react-native/polyfills/streams\";\n * import \"@copilotkit/react-native/polyfills/encoding\";\n * import \"@copilotkit/react-native/polyfills/crypto\";\n * import \"@copilotkit/react-native/polyfills/dom\";\n * import \"@copilotkit/react-native/polyfills/location\";\n */\n\nimport \"./polyfills/streams\";\nimport \"./polyfills/encoding\";\nimport \"./polyfills/crypto\";\nimport \"./polyfills/dom\";\nimport \"./polyfills/location\";\n\nimport { installStreamingFetch } from \"./streaming-fetch\";\ninstallStreamingFetch();\n"],"mappings":";AA0CA,SAAS,mBAAiC;AACxC,QAAO,IAAK,OAAe,aACzB,8BACA,aACD;;AAGH,SAAgB,wBAA8B;AAG5C,KAAI;EACF,MAAM,eAAe,IAAI,SAAS,GAAG;AACrC,MACE,aAAa,QAAQ,QACrB,OAAO,aAAa,KAAK,cAAc,WAEvC;UAEK,GAAG;AAEV,MACE,WACA,aAAa,SACb,EAAE,aAAa,mBACf,EAAE,aAAa,WAEf,SAAQ,KACN,0GAEA,EACD;;CAIL,MAAM,gBAAgB,OAAO;CAC7B,MAAM,cAAc,OAAO;CAE3B,MAAM,iBAAiB,SAAS,eAC9B,OACA,MACmB;EAEnB,MAAM,UACJ,OAAO,UAAU,YAAY,EAAE,iBAAiB,OAAO,QAAQ;EACjE,IAAI;AACJ,MAAI,OAAO,UAAU,SACnB,OAAM;WACG,iBAAiB,IAC1B,OAAM,MAAM;MAEZ,OAAO,MAAkB;EAE3B,MAAM,SAAS,MAAM,UAAU,SAAS,UAAU;EAClD,MAAM,UA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QAAQ,KAAK;IACtB;;AAIJ,CAAC,eAAuB,kBAAkB;AAC1C,QAAO,QAAQ;;;;;ACvVjB,uBAAuB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@copilotkit/react-native",
|
|
3
|
-
"version": "1.57.
|
|
3
|
+
"version": "1.57.2",
|
|
4
4
|
"private": false,
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
},
|
|
19
19
|
"type": "module",
|
|
20
20
|
"sideEffects": [
|
|
21
|
+
"./dist/index.*",
|
|
21
22
|
"./dist/polyfills.*",
|
|
22
23
|
"./dist/polyfills/**/*"
|
|
23
24
|
],
|
|
@@ -59,11 +60,12 @@
|
|
|
59
60
|
"access": "public"
|
|
60
61
|
},
|
|
61
62
|
"dependencies": {
|
|
63
|
+
"@ag-ui/client": "0.0.53",
|
|
62
64
|
"text-encoding": "^0.7.0",
|
|
63
65
|
"web-streams-polyfill": "^4.2.0",
|
|
64
|
-
"@copilotkit/core": "1.57.
|
|
65
|
-
"@copilotkit/
|
|
66
|
-
"@copilotkit/
|
|
66
|
+
"@copilotkit/core": "1.57.2",
|
|
67
|
+
"@copilotkit/react-core": "1.57.2",
|
|
68
|
+
"@copilotkit/shared": "1.57.2"
|
|
67
69
|
},
|
|
68
70
|
"devDependencies": {
|
|
69
71
|
"@testing-library/react": "^16.3.0",
|
|
@@ -76,8 +78,22 @@
|
|
|
76
78
|
"vitest": "^3.2.4"
|
|
77
79
|
},
|
|
78
80
|
"peerDependencies": {
|
|
81
|
+
"expo-document-picker": ">=12.0.0",
|
|
82
|
+
"expo-file-system": ">=17.0.0",
|
|
79
83
|
"react": "^18 || ^19",
|
|
80
|
-
"react-native": ">=0.70"
|
|
84
|
+
"react-native": ">=0.70",
|
|
85
|
+
"zod": ">=3.0.0"
|
|
86
|
+
},
|
|
87
|
+
"peerDependenciesMeta": {
|
|
88
|
+
"expo-document-picker": {
|
|
89
|
+
"optional": true
|
|
90
|
+
},
|
|
91
|
+
"expo-file-system": {
|
|
92
|
+
"optional": true
|
|
93
|
+
},
|
|
94
|
+
"zod": {
|
|
95
|
+
"optional": true
|
|
96
|
+
}
|
|
81
97
|
},
|
|
82
98
|
"scripts": {
|
|
83
99
|
"build": "tsdown",
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import React, {
|
|
2
|
+
createContext,
|
|
3
|
+
useCallback,
|
|
4
|
+
useContext,
|
|
5
|
+
useEffect,
|
|
6
|
+
useRef,
|
|
7
|
+
} from "react";
|
|
8
|
+
import type { ReactNode } from "react";
|
|
9
|
+
import { useAgent } from "@copilotkit/react-core/v2/headless";
|
|
10
|
+
import { useCopilotKit } from "@copilotkit/react-core/v2/context";
|
|
11
|
+
import { DEFAULT_AGENT_ID, randomUUID } from "@copilotkit/shared";
|
|
12
|
+
import type { InputContent } from "@copilotkit/shared";
|
|
13
|
+
import type { CopilotKitCoreErrorCode } from "@copilotkit/core";
|
|
14
|
+
import { useAttachments } from "./hooks/use-attachments";
|
|
15
|
+
import type { NativeAttachmentsConfig } from "./hooks/use-attachments";
|
|
16
|
+
import type { Attachment } from "@copilotkit/shared";
|
|
17
|
+
|
|
18
|
+
// ---------------------------------------------------------------------------
|
|
19
|
+
// Context
|
|
20
|
+
// ---------------------------------------------------------------------------
|
|
21
|
+
|
|
22
|
+
export interface CopilotChatContextValue {
|
|
23
|
+
/** The resolved agent instance. */
|
|
24
|
+
agent: any;
|
|
25
|
+
/** Whether the agent is currently running. */
|
|
26
|
+
isRunning: boolean;
|
|
27
|
+
/** Current messages in the conversation. */
|
|
28
|
+
messages: any[];
|
|
29
|
+
/** Currently selected attachments (uploading + ready). */
|
|
30
|
+
attachments: Attachment[];
|
|
31
|
+
/** Whether attachments are enabled. */
|
|
32
|
+
attachmentsEnabled: boolean;
|
|
33
|
+
/** Open the native document picker to add files. */
|
|
34
|
+
openPicker: () => Promise<void>;
|
|
35
|
+
/** Remove an attachment by ID. */
|
|
36
|
+
removeAttachment: (id: string) => void;
|
|
37
|
+
/**
|
|
38
|
+
* Submit a message with optional attachments.
|
|
39
|
+
* Handles consuming ready attachments, building InputContent[],
|
|
40
|
+
* calling agent.addMessage, and running the agent.
|
|
41
|
+
*/
|
|
42
|
+
submitMessage: (text: string) => Promise<void>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const CopilotChatCtx = createContext<CopilotChatContextValue | null>(null);
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Hook to access the CopilotChat context from child components.
|
|
49
|
+
* Must be called inside a `<CopilotChat>` component tree.
|
|
50
|
+
*/
|
|
51
|
+
export function useCopilotChatContext(): CopilotChatContextValue {
|
|
52
|
+
const ctx = useContext(CopilotChatCtx);
|
|
53
|
+
if (!ctx) {
|
|
54
|
+
throw new Error(
|
|
55
|
+
"useCopilotChatContext must be used within a <CopilotChat> component",
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
return ctx;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// ---------------------------------------------------------------------------
|
|
62
|
+
// Props
|
|
63
|
+
// ---------------------------------------------------------------------------
|
|
64
|
+
|
|
65
|
+
export interface CopilotChatProps {
|
|
66
|
+
/**
|
|
67
|
+
* The agent ID to use for this chat session.
|
|
68
|
+
* Matches the web SDK's CopilotChat `agentId` prop.
|
|
69
|
+
*
|
|
70
|
+
* Resolution order: `agentId` > `agentName` > `"default"`
|
|
71
|
+
*/
|
|
72
|
+
agentId?: string;
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* @deprecated Use `agentId` instead. `agentName` is kept for backwards
|
|
76
|
+
* compatibility and will be removed in a future release.
|
|
77
|
+
*/
|
|
78
|
+
agentName?: string;
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Thread ID for this chat session. When provided, the chat will resume
|
|
82
|
+
* the specified thread. Matches the web SDK's CopilotChat `threadId` prop.
|
|
83
|
+
*/
|
|
84
|
+
threadId?: string;
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Error handler scoped to this chat's agent. Fires in addition to the
|
|
88
|
+
* provider-level onError (does not suppress it). Receives only errors
|
|
89
|
+
* whose context.agentId matches this chat's agent.
|
|
90
|
+
*/
|
|
91
|
+
onError?: (event: {
|
|
92
|
+
error: Error;
|
|
93
|
+
code: CopilotKitCoreErrorCode;
|
|
94
|
+
context: Record<string, any>;
|
|
95
|
+
}) => void | Promise<void>;
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Throttle interval (in milliseconds) for re-renders triggered by message
|
|
99
|
+
* change notifications. Overrides the provider-level `defaultThrottleMs`
|
|
100
|
+
* for this chat instance. Forwarded to the internal `useAgent()` hook.
|
|
101
|
+
*
|
|
102
|
+
* @default undefined -- inherits from provider `defaultThrottleMs`;
|
|
103
|
+
* if that is also unset, re-renders are unthrottled.
|
|
104
|
+
*/
|
|
105
|
+
throttleMs?: number;
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Enable multimodal file attachments (images, audio, video, documents).
|
|
109
|
+
* Pass a NativeAttachmentsConfig object to configure file picking behavior.
|
|
110
|
+
*/
|
|
111
|
+
attachments?: NativeAttachmentsConfig;
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Optional children rendered inside the chat context.
|
|
115
|
+
*/
|
|
116
|
+
children?: ReactNode;
|
|
117
|
+
|
|
118
|
+
/** Passthrough props are forwarded to consumers via the agent context. */
|
|
119
|
+
[key: string]: unknown;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Headless CopilotChat component for React Native.
|
|
124
|
+
*
|
|
125
|
+
* Wires up the `useAgent` hook with `agentId` resolution and renders children.
|
|
126
|
+
* Unlike the web SDK's CopilotChat, this component does not render any UI
|
|
127
|
+
* elements -- consumers provide their own React Native views.
|
|
128
|
+
*
|
|
129
|
+
* Children can access chat state via `useCopilotChatContext()`.
|
|
130
|
+
*
|
|
131
|
+
* ```tsx
|
|
132
|
+
* import { CopilotChat, useCopilotChatContext } from "@copilotkit/react-native";
|
|
133
|
+
*
|
|
134
|
+
* function MyChatUI() {
|
|
135
|
+
* const { messages, submitMessage, attachments, openPicker } = useCopilotChatContext();
|
|
136
|
+
* // ... render your UI
|
|
137
|
+
* }
|
|
138
|
+
*
|
|
139
|
+
* <CopilotChat agentId="my-agent" attachments={{ enabled: true }}>
|
|
140
|
+
* <MyChatUI />
|
|
141
|
+
* </CopilotChat>
|
|
142
|
+
* ```
|
|
143
|
+
*/
|
|
144
|
+
export function CopilotChat({
|
|
145
|
+
agentId,
|
|
146
|
+
agentName,
|
|
147
|
+
threadId,
|
|
148
|
+
onError,
|
|
149
|
+
throttleMs,
|
|
150
|
+
attachments: attachmentsConfig,
|
|
151
|
+
children,
|
|
152
|
+
..._rest
|
|
153
|
+
}: CopilotChatProps) {
|
|
154
|
+
const resolvedAgentId = agentId ?? agentName ?? DEFAULT_AGENT_ID;
|
|
155
|
+
|
|
156
|
+
// Deprecation warning (dev only, fires once per mount)
|
|
157
|
+
const warnedRef = useRef(false);
|
|
158
|
+
useEffect(() => {
|
|
159
|
+
if (
|
|
160
|
+
agentName !== undefined &&
|
|
161
|
+
agentId === undefined &&
|
|
162
|
+
!warnedRef.current
|
|
163
|
+
) {
|
|
164
|
+
warnedRef.current = true;
|
|
165
|
+
if (typeof __DEV__ === "undefined" || __DEV__) {
|
|
166
|
+
console.warn(
|
|
167
|
+
"[CopilotKit] agentName is deprecated, use agentId instead",
|
|
168
|
+
);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}, [agentName, agentId]);
|
|
172
|
+
|
|
173
|
+
const { agent } = useAgent({ agentId: resolvedAgentId, throttleMs });
|
|
174
|
+
|
|
175
|
+
// Set threadId on the agent when provided
|
|
176
|
+
useEffect(() => {
|
|
177
|
+
if (threadId) {
|
|
178
|
+
agent.threadId = threadId;
|
|
179
|
+
}
|
|
180
|
+
}, [agent, threadId]);
|
|
181
|
+
|
|
182
|
+
// onError subscription -- forward core errors scoped to this chat's agent
|
|
183
|
+
const { copilotkit } = useCopilotKit();
|
|
184
|
+
const onErrorRef = useRef(onError);
|
|
185
|
+
useEffect(() => {
|
|
186
|
+
onErrorRef.current = onError;
|
|
187
|
+
}, [onError]);
|
|
188
|
+
|
|
189
|
+
useEffect(() => {
|
|
190
|
+
if (!onErrorRef.current) return;
|
|
191
|
+
|
|
192
|
+
const subscription = copilotkit.subscribe({
|
|
193
|
+
onError: (event) => {
|
|
194
|
+
// Only forward errors that match this chat's agent
|
|
195
|
+
if (
|
|
196
|
+
event.context?.agentId === resolvedAgentId ||
|
|
197
|
+
!event.context?.agentId
|
|
198
|
+
) {
|
|
199
|
+
onErrorRef.current?.({
|
|
200
|
+
error: event.error,
|
|
201
|
+
code: event.code,
|
|
202
|
+
context: event.context,
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
},
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
return () => {
|
|
209
|
+
subscription.unsubscribe();
|
|
210
|
+
};
|
|
211
|
+
}, [copilotkit, resolvedAgentId]);
|
|
212
|
+
|
|
213
|
+
// Attachments
|
|
214
|
+
const {
|
|
215
|
+
attachments: selectedAttachments,
|
|
216
|
+
enabled: attachmentsEnabled,
|
|
217
|
+
openPicker,
|
|
218
|
+
removeAttachment,
|
|
219
|
+
consumeAttachments,
|
|
220
|
+
} = useAttachments({ config: attachmentsConfig });
|
|
221
|
+
|
|
222
|
+
// Submit handler -- mirrors web CopilotChat.tsx lines 234-288
|
|
223
|
+
const submitMessage = useCallback(
|
|
224
|
+
async (value: string) => {
|
|
225
|
+
// Block if uploads in progress
|
|
226
|
+
const hasUploading = selectedAttachments.some(
|
|
227
|
+
(a) => a.status === "uploading",
|
|
228
|
+
);
|
|
229
|
+
if (hasUploading) {
|
|
230
|
+
console.error(
|
|
231
|
+
"[CopilotKit] Cannot send while attachments are uploading",
|
|
232
|
+
);
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const readyAttachments = consumeAttachments();
|
|
237
|
+
|
|
238
|
+
if (readyAttachments.length > 0) {
|
|
239
|
+
const contentParts: InputContent[] = [];
|
|
240
|
+
if (value.trim()) {
|
|
241
|
+
contentParts.push({ type: "text", text: value });
|
|
242
|
+
}
|
|
243
|
+
for (const att of readyAttachments) {
|
|
244
|
+
contentParts.push({
|
|
245
|
+
type: att.type,
|
|
246
|
+
source: att.source,
|
|
247
|
+
metadata: {
|
|
248
|
+
...(att.filename ? { filename: att.filename } : {}),
|
|
249
|
+
...att.metadata,
|
|
250
|
+
},
|
|
251
|
+
} as InputContent);
|
|
252
|
+
}
|
|
253
|
+
agent.addMessage({
|
|
254
|
+
id: randomUUID(),
|
|
255
|
+
role: "user",
|
|
256
|
+
content: contentParts,
|
|
257
|
+
});
|
|
258
|
+
} else {
|
|
259
|
+
agent.addMessage({
|
|
260
|
+
id: randomUUID(),
|
|
261
|
+
role: "user",
|
|
262
|
+
content: value,
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
try {
|
|
267
|
+
await copilotkit.runAgent({ agent });
|
|
268
|
+
} catch (error) {
|
|
269
|
+
console.error("CopilotChat: runAgent failed", error);
|
|
270
|
+
}
|
|
271
|
+
},
|
|
272
|
+
// copilotkit is intentionally excluded -- it is a stable ref that never changes.
|
|
273
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
274
|
+
[agent, selectedAttachments, consumeAttachments],
|
|
275
|
+
);
|
|
276
|
+
|
|
277
|
+
const contextValue: CopilotChatContextValue = {
|
|
278
|
+
agent,
|
|
279
|
+
isRunning: agent.isRunning,
|
|
280
|
+
messages: agent.messages,
|
|
281
|
+
attachments: selectedAttachments,
|
|
282
|
+
attachmentsEnabled,
|
|
283
|
+
openPicker,
|
|
284
|
+
removeAttachment,
|
|
285
|
+
submitMessage,
|
|
286
|
+
};
|
|
287
|
+
|
|
288
|
+
return (
|
|
289
|
+
<CopilotChatCtx.Provider value={contextValue}>
|
|
290
|
+
{children}
|
|
291
|
+
</CopilotChatCtx.Provider>
|
|
292
|
+
);
|
|
293
|
+
}
|
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
import React, {
|
|
2
|
-
|
|
3
|
-
useEffect,
|
|
4
|
-
useMemo,
|
|
5
|
-
useRef,
|
|
6
|
-
useState,
|
|
7
|
-
} from "react";
|
|
1
|
+
import React, { useEffect, useMemo, useRef, useState } from "react";
|
|
2
|
+
import type { ReactNode } from "react";
|
|
8
3
|
import {
|
|
9
4
|
CopilotKitContext,
|
|
10
|
-
type CopilotKitContextValue,
|
|
11
5
|
LicenseContext,
|
|
12
6
|
} from "@copilotkit/react-core/v2/context";
|
|
7
|
+
import type { CopilotKitContextValue } from "@copilotkit/react-core/v2/context";
|
|
13
8
|
import { CopilotKitCoreReact } from "@copilotkit/react-core/v2/headless";
|
|
14
9
|
import type { CopilotKitCoreErrorCode } from "@copilotkit/core";
|
|
10
|
+
import type { DebugConfig } from "@copilotkit/shared";
|
|
15
11
|
|
|
16
12
|
export interface CopilotKitNativeProviderProps {
|
|
17
13
|
children: ReactNode;
|
|
18
14
|
/** URL of the CopilotKit runtime endpoint */
|
|
19
15
|
runtimeUrl: string;
|
|
20
16
|
/** Custom headers sent with every request */
|
|
21
|
-
headers?: Record<string, string
|
|
17
|
+
headers?: Record<string, string> | (() => Record<string, string>);
|
|
18
|
+
/**
|
|
19
|
+
* Credentials mode for fetch requests (e.g., "include" for HTTP-only cookies in cross-origin requests).
|
|
20
|
+
*/
|
|
21
|
+
credentials?: RequestCredentials;
|
|
22
22
|
/** Whether the runtime uses a single-route endpoint */
|
|
23
23
|
useSingleEndpoint?: boolean;
|
|
24
24
|
/** Custom properties forwarded to agents */
|
|
@@ -32,7 +32,18 @@ export interface CopilotKitNativeProviderProps {
|
|
|
32
32
|
error: Error;
|
|
33
33
|
code: CopilotKitCoreErrorCode;
|
|
34
34
|
context: Record<string, any>;
|
|
35
|
-
}) => void
|
|
35
|
+
}) => void | Promise<void>;
|
|
36
|
+
/**
|
|
37
|
+
* Enable debug logging for the client-side event pipeline.
|
|
38
|
+
* When `true`, enables verbose logging from the core instance.
|
|
39
|
+
*/
|
|
40
|
+
debug?: DebugConfig;
|
|
41
|
+
/**
|
|
42
|
+
* Default throttle interval (ms) for `onMessagesChanged` / `onStateChanged`
|
|
43
|
+
* subscriptions. Individual subscriptions can override with their own `throttleMs`.
|
|
44
|
+
*/
|
|
45
|
+
defaultThrottleMs?: number;
|
|
46
|
+
// Cloud features (publicApiKey, licenseToken) — not yet supported on React Native
|
|
36
47
|
}
|
|
37
48
|
|
|
38
49
|
/**
|
|
@@ -41,9 +52,12 @@ export interface CopilotKitNativeProviderProps {
|
|
|
41
52
|
* A lightweight alternative to the web CopilotKitProvider that avoids
|
|
42
53
|
* web-only dependencies (DOM, CSS, Radix UI, Lit, etc).
|
|
43
54
|
*
|
|
55
|
+
* Polyfills are auto-imported when `@copilotkit/react-native` is loaded,
|
|
56
|
+
* so a separate `import "@copilotkit/react-native/polyfills"` is no longer
|
|
57
|
+
* required (though it remains available for advanced use).
|
|
58
|
+
*
|
|
44
59
|
* Usage:
|
|
45
60
|
* ```tsx
|
|
46
|
-
* import "@copilotkit/react-native/polyfills";
|
|
47
61
|
* import { CopilotKitProvider } from "@copilotkit/react-native";
|
|
48
62
|
*
|
|
49
63
|
* function App() {
|
|
@@ -58,15 +72,25 @@ export interface CopilotKitNativeProviderProps {
|
|
|
58
72
|
export const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps> = ({
|
|
59
73
|
children,
|
|
60
74
|
runtimeUrl,
|
|
61
|
-
headers,
|
|
75
|
+
headers: headersProp,
|
|
76
|
+
credentials,
|
|
62
77
|
useSingleEndpoint,
|
|
63
78
|
properties,
|
|
64
79
|
onError,
|
|
80
|
+
debug,
|
|
81
|
+
defaultThrottleMs,
|
|
65
82
|
}) => {
|
|
83
|
+
// Resolve headers from function or static object (matches web provider pattern)
|
|
84
|
+
const resolvedHeaders =
|
|
85
|
+
typeof headersProp === "function" ? headersProp() : headersProp;
|
|
86
|
+
|
|
66
87
|
// Stabilize headers/properties references to avoid effect churn when callers
|
|
67
88
|
// pass inline object literals (e.g. headers={{}} or the undefined default).
|
|
68
89
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
69
|
-
const stableHeaders = useMemo(
|
|
90
|
+
const stableHeaders = useMemo(
|
|
91
|
+
() => resolvedHeaders ?? {},
|
|
92
|
+
[JSON.stringify(resolvedHeaders)],
|
|
93
|
+
);
|
|
70
94
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
71
95
|
const stableProperties = useMemo(
|
|
72
96
|
() => properties ?? {},
|
|
@@ -85,8 +109,15 @@ export const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps> = ({
|
|
|
85
109
|
? "rest"
|
|
86
110
|
: "auto",
|
|
87
111
|
headers: stableHeaders,
|
|
112
|
+
credentials,
|
|
88
113
|
properties: stableProperties,
|
|
114
|
+
debug,
|
|
89
115
|
});
|
|
116
|
+
// Set initial defaultThrottleMs synchronously so child hooks see the
|
|
117
|
+
// correct value on their first render (before useEffect fires).
|
|
118
|
+
if (defaultThrottleMs !== undefined) {
|
|
119
|
+
copilotkitRef.current.setDefaultThrottleMs(defaultThrottleMs);
|
|
120
|
+
}
|
|
90
121
|
}
|
|
91
122
|
|
|
92
123
|
const copilotkit = copilotkitRef.current;
|
|
@@ -102,15 +133,26 @@ export const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps> = ({
|
|
|
102
133
|
: "auto",
|
|
103
134
|
);
|
|
104
135
|
copilotkit.setHeaders(stableHeaders);
|
|
136
|
+
copilotkit.setCredentials(credentials);
|
|
105
137
|
copilotkit.setProperties(stableProperties);
|
|
138
|
+
copilotkit.setDebug(debug);
|
|
106
139
|
}, [
|
|
107
140
|
runtimeUrl,
|
|
108
141
|
useSingleEndpoint,
|
|
109
142
|
stableHeaders,
|
|
143
|
+
credentials,
|
|
110
144
|
stableProperties,
|
|
145
|
+
debug,
|
|
111
146
|
copilotkit,
|
|
112
147
|
]);
|
|
113
148
|
|
|
149
|
+
// Sync defaultThrottleMs to the core instance on prop changes.
|
|
150
|
+
// Initial value is set synchronously during instance creation (inside the
|
|
151
|
+
// ref guard above), so this only handles subsequent updates.
|
|
152
|
+
useEffect(() => {
|
|
153
|
+
copilotkit.setDefaultThrottleMs(defaultThrottleMs);
|
|
154
|
+
}, [copilotkit, defaultThrottleMs]);
|
|
155
|
+
|
|
114
156
|
// Track executing tool call IDs at the provider level.
|
|
115
157
|
// Critical for HITL reconnection: onToolExecutionStart fires before child
|
|
116
158
|
// components mount, so we must capture the state here.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import React, { type ReactNode } from "react";
|
|
2
|
+
import { CopilotChat, type CopilotChatProps } from "./CopilotChat";
|
|
3
|
+
|
|
4
|
+
export interface CopilotModalProps extends CopilotChatProps {
|
|
5
|
+
/**
|
|
6
|
+
* Optional children rendered inside the modal context.
|
|
7
|
+
*/
|
|
8
|
+
children?: ReactNode;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Headless CopilotModal component for React Native.
|
|
13
|
+
*
|
|
14
|
+
* A thin wrapper around CopilotChat that mirrors the web SDK's CopilotModal
|
|
15
|
+
* API surface. On React Native, modal presentation is handled by the consumer
|
|
16
|
+
* (e.g. React Native's `Modal` component) -- this component only provides
|
|
17
|
+
* the agent wiring and prop resolution.
|
|
18
|
+
*
|
|
19
|
+
* ```tsx
|
|
20
|
+
* import { CopilotModal } from "@copilotkit/react-native";
|
|
21
|
+
* import { Modal } from "react-native";
|
|
22
|
+
*
|
|
23
|
+
* <Modal visible={isOpen}>
|
|
24
|
+
* <CopilotModal agentId="my-agent">
|
|
25
|
+
* <MyChatUI />
|
|
26
|
+
* </CopilotModal>
|
|
27
|
+
* </Modal>
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
export function CopilotModal({ children, ...props }: CopilotModalProps) {
|
|
31
|
+
return <CopilotChat {...props}>{children}</CopilotChat>;
|
|
32
|
+
}
|