@copilotkit/react-native 2.0.0-rc.26 → 2.0.0-rc.27

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/dist/index.cjs CHANGED
@@ -8,6 +8,7 @@ let react = require("react");
8
8
  react = require_MarkdownRendererContext.__toESM(react);
9
9
  let _copilotkit_react_core_context = require("@copilotkit/react-core/context");
10
10
  let _copilotkit_react_core_headless = require("@copilotkit/react-core/headless");
11
+ let _copilotkit_core = require("@copilotkit/core");
11
12
  let _copilotkit_shared = require("@copilotkit/shared");
12
13
  let react_jsx_runtime = require("react/jsx-runtime");
13
14
  let expo_document_picker = require("expo-document-picker");
@@ -16,105 +17,72 @@ let expo_file_system = require("expo-file-system");
16
17
  expo_file_system = require_MarkdownRendererContext.__toESM(expo_file_system);
17
18
  let react_native = require("react-native");
18
19
  let _ag_ui_client = require("@ag-ui/client");
19
- let _copilotkit_core = require("@copilotkit/core");
20
20
 
21
21
  //#region src/hooks/use-attachments.ts
22
- const DEFAULT_MAX_SIZE = 20 * 1024 * 1024;
22
+ const nativeFiles = /* @__PURE__ */ new WeakMap();
23
+ /**
24
+ * Wraps a native file for core's `ɵAttachmentQueue`, which is typed for the
25
+ * web `File`. The queue reads only `name`, `size` and `type`, because the
26
+ * config from {@link toQueueConfig} always uploads through `onUpload` and the
27
+ * queue never reads the bytes itself.
28
+ */
29
+ function toQueueFile(file) {
30
+ const queued = {
31
+ name: file.name,
32
+ size: file.size,
33
+ type: file.mimeType
34
+ };
35
+ nativeFiles.set(queued, file);
36
+ return queued;
37
+ }
38
+ function toNativeFile(file) {
39
+ const native = nativeFiles.get(file);
40
+ if (!native) throw new Error(`[CopilotKit] "${file.name}" was not picked natively`);
41
+ return native;
42
+ }
43
+ /** Reads a picked file as base64 with expo-file-system. */
44
+ async function readNativeFile(file) {
45
+ return {
46
+ type: "data",
47
+ value: await expo_file_system.readAsStringAsync(file.uri, { encoding: expo_file_system.EncodingType.Base64 }),
48
+ mimeType: file.mimeType
49
+ };
50
+ }
51
+ /**
52
+ * The RN config as core's queue takes it. Uploads go through the app's
53
+ * `onUpload`, or through expo-file-system when there is none.
54
+ */
55
+ function toQueueConfig(config) {
56
+ if (!config) return void 0;
57
+ const { onUpload, onUploadFailed, ...rest } = config;
58
+ return {
59
+ ...rest,
60
+ onUpload: (file) => {
61
+ const native = toNativeFile(file);
62
+ return onUpload ? onUpload(native) : readNativeFile(native);
63
+ },
64
+ onUploadFailed: onUploadFailed ? ({ file, ...error }) => onUploadFailed({
65
+ ...error,
66
+ file: toNativeFile(file)
67
+ }) : void 0
68
+ };
69
+ }
23
70
  /**
24
71
  * React Native hook that manages file attachment state -- picking, uploading,
25
- * and lifecycle. All returned callbacks are referentially stable via useCallback.
72
+ * and lifecycle. All returned callbacks are referentially stable.
26
73
  *
27
- * This is the RN counterpart of the web `useAttachments` hook from
28
- * `@copilotkit/react-core`. It replaces web APIs (FileReader, DragEvent,
29
- * HTMLInputElement) with Expo modules (expo-document-picker, expo-file-system).
74
+ * The queue itself (accept filter, size check, uploads, ready state) is
75
+ * `@copilotkit/core`'s `ɵAttachmentQueue`, shared with the web chats. This
76
+ * hook adds the native glue: expo-document-picker to pick files and
77
+ * expo-file-system to read them.
30
78
  */
31
79
  function useAttachments({ config }) {
32
80
  const enabled = config?.enabled ?? false;
33
- const [attachments, setAttachments] = (0, react.useState)([]);
34
81
  const configRef = (0, react.useRef)(config);
35
82
  configRef.current = config;
36
- const attachmentsRef = (0, react.useRef)([]);
37
- attachmentsRef.current = attachments;
38
- /**
39
- * Simple MIME accept filter for NativeFileInput.
40
- * Handles wildcards like "image/*" and exact types like "application/pdf".
41
- * Comma-separated lists are supported.
42
- */
43
- const matchesAccept = (0, react.useCallback)((file, accept) => {
44
- if (!accept || accept === "*/*") return true;
45
- return accept.split(",").map((f) => f.trim()).some((filter) => {
46
- if (filter.startsWith(".")) return file.name.toLowerCase().endsWith(filter.toLowerCase());
47
- if (filter.endsWith("/*")) {
48
- const prefix = filter.slice(0, -2);
49
- return file.mimeType.startsWith(prefix + "/");
50
- }
51
- return file.mimeType === filter;
52
- });
53
- }, []);
54
- const processFiles = (0, react.useCallback)(async (files) => {
55
- const cfg = configRef.current;
56
- const accept = cfg?.accept ?? "*/*";
57
- const maxSize = cfg?.maxSize ?? DEFAULT_MAX_SIZE;
58
- const rejectedFiles = files.filter((f) => !matchesAccept(f, accept));
59
- for (const file of rejectedFiles) cfg?.onUploadFailed?.({
60
- reason: "invalid-type",
61
- file,
62
- message: `File "${file.name}" is not accepted. Supported types: ${accept}`
63
- });
64
- const validFiles = files.filter((f) => matchesAccept(f, accept));
65
- for (const file of validFiles) {
66
- if (file.size > maxSize) {
67
- cfg?.onUploadFailed?.({
68
- reason: "file-too-large",
69
- file,
70
- message: `File "${file.name}" exceeds the maximum size of ${(0, _copilotkit_shared.formatFileSize)(maxSize)}`
71
- });
72
- continue;
73
- }
74
- const modality = (0, _copilotkit_shared.getModalityFromMimeType)(file.mimeType);
75
- const placeholderId = (0, _copilotkit_shared.randomUUID)();
76
- const placeholder = {
77
- id: placeholderId,
78
- type: modality,
79
- source: {
80
- type: "data",
81
- value: "",
82
- mimeType: file.mimeType
83
- },
84
- filename: file.name,
85
- size: file.size,
86
- status: "uploading"
87
- };
88
- setAttachments((prev) => [...prev, placeholder]);
89
- try {
90
- let source;
91
- let uploadMetadata;
92
- if (cfg?.onUpload) {
93
- const { metadata: meta, ...uploadSource } = await cfg.onUpload(file);
94
- source = uploadSource;
95
- uploadMetadata = meta;
96
- } else source = {
97
- type: "data",
98
- value: await expo_file_system.readAsStringAsync(file.uri, { encoding: expo_file_system.EncodingType.Base64 }),
99
- mimeType: file.mimeType
100
- };
101
- setAttachments((prev) => prev.map((att) => att.id === placeholderId ? {
102
- ...att,
103
- source,
104
- status: "ready",
105
- metadata: uploadMetadata
106
- } : att));
107
- } catch (error) {
108
- setAttachments((prev) => prev.filter((att) => att.id !== placeholderId));
109
- console.error(`[CopilotKit] Failed to upload "${file.name}":`, error);
110
- cfg?.onUploadFailed?.({
111
- reason: "upload-failed",
112
- file,
113
- message: error instanceof Error ? error.message : `Failed to upload "${file.name}"`
114
- });
115
- }
116
- }
117
- }, [matchesAccept]);
83
+ const [queue] = (0, react.useState)(() => new _copilotkit_core.ɵAttachmentQueue(() => toQueueConfig(configRef.current)));
84
+ const attachments = (0, react.useSyncExternalStore)((0, react.useCallback)((onChange) => queue.subscribe(onChange), [queue]), () => queue.getSnapshot(), () => queue.getSnapshot());
85
+ const processFiles = (0, react.useCallback)((files) => queue.processFiles(files.map(toQueueFile)), [queue]);
118
86
  return {
119
87
  attachments,
120
88
  enabled,
@@ -138,15 +106,8 @@ function useAttachments({ config }) {
138
106
  }
139
107
  }, [processFiles]),
140
108
  processFiles,
141
- removeAttachment: (0, react.useCallback)((id) => {
142
- setAttachments((prev) => prev.filter((a) => a.id !== id));
143
- }, []),
144
- consumeAttachments: (0, react.useCallback)(() => {
145
- const ready = attachmentsRef.current.filter((a) => a.status === "ready");
146
- if (ready.length === 0) return ready;
147
- setAttachments((prev) => prev.filter((a) => a.status !== "ready"));
148
- return ready;
149
- }, [])
109
+ removeAttachment: (0, react.useCallback)((id) => queue.remove(id), [queue]),
110
+ consumeAttachments: (0, react.useCallback)(() => queue.consumeReady(), [queue])
150
111
  };
151
112
  }
152
113
 
@@ -204,72 +165,62 @@ function CopilotChat({ agentId, agentName, threadId, onError, throttleMs, attach
204
165
  if (typeof __DEV__ === "undefined" || __DEV__) console.warn("[CopilotKit] agentName is deprecated, use agentId instead");
205
166
  }
206
167
  }, [agentName, agentId]);
168
+ const providedThreadId = threadId ?? chatConfig?.threadId;
169
+ const [freshThreadId] = (0, react.useState)(() => new _copilotkit_core.ɵFreshThreadId());
170
+ const resolvedThreadId = (0, react.useMemo)(() => freshThreadId.resolve(providedThreadId), [freshThreadId, providedThreadId]);
171
+ const hasExplicitThreadId = !!threadId || !!chatConfig?.hasExplicitThreadId;
207
172
  const { agent } = (0, _copilotkit_react_core_headless.useAgent)({
208
173
  agentId: resolvedAgentId,
209
174
  throttleMs
210
175
  });
211
- (0, react.useEffect)(() => {
212
- if (threadId) agent.threadId = threadId;
213
- }, [agent, threadId]);
214
176
  const { copilotkit } = (0, _copilotkit_react_core_context.useCopilotKit)();
177
+ const [connection] = (0, react.useState)(() => new _copilotkit_core.ɵChatConnection({ core: copilotkit }));
178
+ const { threads } = connection;
179
+ (0, react.useEffect)(() => {
180
+ const handle = connection.open({
181
+ agent,
182
+ threadId: resolvedThreadId,
183
+ explicit: hasExplicitThreadId
184
+ });
185
+ return () => handle.release();
186
+ }, [
187
+ connection,
188
+ agent,
189
+ resolvedThreadId,
190
+ hasExplicitThreadId
191
+ ]);
215
192
  const onErrorRef = (0, react.useRef)(onError);
216
193
  (0, react.useEffect)(() => {
217
194
  onErrorRef.current = onError;
218
195
  }, [onError]);
219
196
  (0, react.useEffect)(() => {
220
197
  if (!onErrorRef.current) return;
221
- const subscription = copilotkit.subscribe({ onError: (event) => {
222
- if (event.context?.agentId === resolvedAgentId || !event.context?.agentId) onErrorRef.current?.({
223
- error: event.error,
224
- code: event.code,
225
- context: event.context
226
- });
227
- } });
228
- return () => {
229
- subscription.unsubscribe();
230
- };
198
+ return (0, _copilotkit_core.ɵsubscribeToAgentErrors)(copilotkit, resolvedAgentId, (event) => onErrorRef.current?.(event));
231
199
  }, [copilotkit, resolvedAgentId]);
232
200
  const { attachments: selectedAttachments, enabled: attachmentsEnabled, openPicker, removeAttachment, consumeAttachments } = useAttachments({ config: attachmentsConfig });
233
- const submitMessage = (0, react.useCallback)(async (value) => {
234
- if (selectedAttachments.some((a) => a.status === "uploading")) {
235
- console.error("[CopilotKit] Cannot send while attachments are uploading");
236
- return;
237
- }
238
- const readyAttachments = consumeAttachments();
239
- if (readyAttachments.length > 0) {
240
- const contentParts = [];
241
- if (value.trim()) contentParts.push({
242
- type: "text",
243
- text: value
244
- });
245
- for (const att of readyAttachments) contentParts.push({
246
- type: att.type,
247
- source: att.source,
248
- metadata: {
249
- ...att.filename ? { filename: att.filename } : {},
250
- ...att.metadata
251
- }
252
- });
253
- agent.addMessage({
254
- id: (0, _copilotkit_shared.randomUUID)(),
255
- role: "user",
256
- content: contentParts
257
- });
258
- } else agent.addMessage({
259
- id: (0, _copilotkit_shared.randomUUID)(),
260
- role: "user",
261
- content: value
262
- });
263
- try {
264
- await copilotkit.runAgent({ agent });
265
- } catch (error) {
266
- console.error("CopilotChat: runAgent failed", error);
267
- }
268
- }, [
269
- agent,
270
- selectedAttachments,
271
- consumeAttachments
272
- ]);
201
+ const attachmentsRef = (0, react.useRef)(selectedAttachments);
202
+ (0, react.useLayoutEffect)(() => {
203
+ attachmentsRef.current = selectedAttachments;
204
+ });
205
+ const agentRef = (0, react.useRef)(agent);
206
+ (0, react.useLayoutEffect)(() => {
207
+ agentRef.current = agent;
208
+ });
209
+ const [submitter] = (0, react.useState)(() => (0, _copilotkit_core.ɵcreateChatSubmitter)({
210
+ core: copilotkit,
211
+ getAgent: () => agentRef.current,
212
+ input: {
213
+ get: () => "",
214
+ set: () => {}
215
+ },
216
+ attachments: {
217
+ isUploading: () => attachmentsRef.current.some((a) => a.status === "uploading"),
218
+ consumeReady: () => consumeAttachments()
219
+ },
220
+ threads
221
+ }));
222
+ (0, react.useEffect)(() => () => submitter.showNotice(null), [submitter]);
223
+ const submitMessage = (0, react.useCallback)((value) => submitter.submit(value), [submitter]);
273
224
  const contextValue = {
274
225
  agent,
275
226
  isRunning: agent.isRunning,
@@ -282,7 +233,8 @@ function CopilotChat({ agentId, agentName, threadId, onError, throttleMs, attach
282
233
  };
283
234
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_copilotkit_react_core_headless.CopilotChatConfigurationProvider, {
284
235
  agentId: resolvedAgentId,
285
- threadId,
236
+ threadId: resolvedThreadId,
237
+ hasExplicitThreadId,
286
238
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotChatCtx.Provider, {
287
239
  value: contextValue,
288
240
  children
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["FileSystem","DocumentPicker","DEFAULT_AGENT_ID","CopilotChatConfigurationProvider","Animated","Pressable","styles","View","Text","StyleSheet","TouchableOpacity","Text","Modal","Pressable","View","StyleSheet"],"sources":["../src/hooks/use-attachments.ts","../src/CopilotChat.tsx","../src/CopilotModal.tsx","../src/CopilotSidebar.tsx","../src/CopilotPopup.tsx"],"sourcesContent":["// packages/react-native/src/hooks/use-attachments.ts\nimport { useCallback, useRef, useState } from \"react\";\nimport {\n randomUUID,\n getModalityFromMimeType,\n formatFileSize,\n} from \"@copilotkit/shared\";\nimport type {\n Attachment,\n AttachmentUploadResult,\n AttachmentUploadErrorReason,\n} from \"@copilotkit/shared\";\nimport * as DocumentPicker from \"expo-document-picker\";\nimport * as FileSystem from \"expo-file-system\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Platform-neutral file descriptor for React Native.\n * Replaces the web `File` object in all attachment APIs.\n */\nexport interface NativeFileInput {\n /** Local file URI (e.g. `file:///path/to/file`). */\n uri: string;\n /** Filename with extension. */\n name: string;\n /** File size in bytes. */\n size: number;\n /** MIME type (e.g. `\"image/jpeg\"`). */\n mimeType: string;\n}\n\n/**\n * React Native variant of AttachmentsConfig.\n * Identical to the shared AttachmentsConfig except `onUpload` receives\n * a `NativeFileInput` instead of a web `File`.\n */\nexport interface NativeAttachmentsConfig {\n /** Enable file attachments in the chat input. */\n enabled: boolean;\n /** MIME type filter for the file picker, default all files. */\n accept?: string;\n /** Maximum file size in bytes, default 20MB (20 * 1024 * 1024). */\n maxSize?: number;\n /** Custom upload handler. Receives the native file descriptor. */\n onUpload?: (\n file: NativeFileInput,\n ) => AttachmentUploadResult | Promise<AttachmentUploadResult>;\n /** Called when an attachment fails validation or upload. */\n onUploadFailed?: (error: {\n reason: AttachmentUploadErrorReason;\n file: NativeFileInput;\n message: string;\n }) => void;\n}\n\nexport interface UseNativeAttachmentsProps {\n config?: NativeAttachmentsConfig;\n}\n\nexport interface UseNativeAttachmentsReturn {\n /** Currently selected attachments (uploading + ready). */\n attachments: Attachment[];\n /** Whether attachments are enabled. */\n enabled: boolean;\n /** Open the native document picker. */\n openPicker: () => Promise<void>;\n /** Process an array of NativeFileInput objects (validate, read, add to state). */\n processFiles: (files: NativeFileInput[]) => Promise<void>;\n /** Remove an attachment by ID. */\n removeAttachment: (id: string) => void;\n /** Consume ready attachments and clear the queue. Returns the consumed attachments. */\n consumeAttachments: () => Attachment[];\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_MAX_SIZE = 20 * 1024 * 1024; // 20 MB\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\n/**\n * React Native hook that manages file attachment state -- picking, uploading,\n * and lifecycle. All returned callbacks are referentially stable via useCallback.\n *\n * This is the RN counterpart of the web `useAttachments` hook from\n * `@copilotkit/react-core`. It replaces web APIs (FileReader, DragEvent,\n * HTMLInputElement) with Expo modules (expo-document-picker, expo-file-system).\n */\nexport function useAttachments({\n config,\n}: UseNativeAttachmentsProps): UseNativeAttachmentsReturn {\n const enabled = config?.enabled ?? false;\n\n const [attachments, setAttachments] = useState<Attachment[]>([]);\n\n // Refs for stable callbacks to read latest values\n const configRef = useRef(config);\n configRef.current = config;\n const attachmentsRef = useRef<Attachment[]>([]);\n attachmentsRef.current = attachments;\n\n /**\n * Simple MIME accept filter for NativeFileInput.\n * Handles wildcards like \"image/*\" and exact types like \"application/pdf\".\n * Comma-separated lists are supported.\n */\n const matchesAccept = useCallback(\n (file: NativeFileInput, accept: string): boolean => {\n if (!accept || accept === \"*/*\") return true;\n const filters = accept.split(\",\").map((f) => f.trim());\n return filters.some((filter) => {\n if (filter.startsWith(\".\")) {\n return file.name.toLowerCase().endsWith(filter.toLowerCase());\n }\n if (filter.endsWith(\"/*\")) {\n const prefix = filter.slice(0, -2);\n return file.mimeType.startsWith(prefix + \"/\");\n }\n return file.mimeType === filter;\n });\n },\n [],\n );\n\n const processFiles = useCallback(\n async (files: NativeFileInput[]) => {\n const cfg = configRef.current;\n const accept = cfg?.accept ?? \"*/*\";\n const maxSize = cfg?.maxSize ?? DEFAULT_MAX_SIZE;\n\n // Filter by accept type\n const rejectedFiles = files.filter((f) => !matchesAccept(f, accept));\n for (const file of rejectedFiles) {\n cfg?.onUploadFailed?.({\n reason: \"invalid-type\",\n file,\n message: `File \"${file.name}\" is not accepted. Supported types: ${accept}`,\n });\n }\n\n const validFiles = files.filter((f) => matchesAccept(f, accept));\n\n for (const file of validFiles) {\n // Size check\n if (file.size > maxSize) {\n cfg?.onUploadFailed?.({\n reason: \"file-too-large\",\n file,\n message: `File \"${file.name}\" exceeds the maximum size of ${formatFileSize(maxSize)}`,\n });\n continue;\n }\n\n const modality = getModalityFromMimeType(file.mimeType);\n const placeholderId = randomUUID();\n const placeholder: Attachment = {\n id: placeholderId,\n type: modality,\n source: { type: \"data\", value: \"\", mimeType: file.mimeType },\n filename: file.name,\n size: file.size,\n status: \"uploading\",\n };\n\n setAttachments((prev) => [...prev, placeholder]);\n\n try {\n let source: Attachment[\"source\"];\n let uploadMetadata: Record<string, unknown> | undefined;\n\n if (cfg?.onUpload) {\n const { metadata: meta, ...uploadSource } =\n await cfg.onUpload(file);\n source = uploadSource;\n uploadMetadata = meta;\n } else {\n // Default: read file as base64 via expo-file-system\n const base64 = await FileSystem.readAsStringAsync(file.uri, {\n encoding: FileSystem.EncodingType.Base64,\n });\n source = { type: \"data\", value: base64, mimeType: file.mimeType };\n }\n\n setAttachments((prev) =>\n prev.map((att) =>\n att.id === placeholderId\n ? {\n ...att,\n source,\n status: \"ready\" as const,\n metadata: uploadMetadata,\n }\n : att,\n ),\n );\n } catch (error) {\n // Remove placeholder on failure\n setAttachments((prev) =>\n prev.filter((att) => att.id !== placeholderId),\n );\n console.error(`[CopilotKit] Failed to upload \"${file.name}\":`, error);\n cfg?.onUploadFailed?.({\n reason: \"upload-failed\",\n file,\n message:\n error instanceof Error\n ? error.message\n : `Failed to upload \"${file.name}\"`,\n });\n }\n }\n },\n [matchesAccept],\n );\n\n const openPicker = useCallback(async () => {\n const cfg = configRef.current;\n const accept = cfg?.accept ?? \"*/*\";\n\n // Convert accept string to array for DocumentPicker\n const typeArray = accept\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean);\n\n try {\n const result = await DocumentPicker.getDocumentAsync({\n type: typeArray.length > 0 ? typeArray : [\"*/*\"],\n copyToCacheDirectory: true,\n multiple: true,\n });\n\n if (result.canceled || !result.assets?.length) return;\n\n const nativeFiles: NativeFileInput[] = result.assets.map((asset) => ({\n uri: asset.uri,\n name: asset.name ?? \"unknown\",\n size: asset.size ?? 0,\n mimeType: asset.mimeType ?? \"application/octet-stream\",\n }));\n\n await processFiles(nativeFiles);\n } catch (error) {\n console.error(\"[CopilotKit] Document picker error:\", error);\n }\n }, [processFiles]);\n\n const removeAttachment = useCallback((id: string) => {\n setAttachments((prev) => prev.filter((a) => a.id !== id));\n }, []);\n\n const consumeAttachments = useCallback(() => {\n const ready = attachmentsRef.current.filter((a) => a.status === \"ready\");\n if (ready.length === 0) return ready;\n setAttachments((prev) => prev.filter((a) => a.status !== \"ready\"));\n return ready;\n }, []);\n\n return {\n attachments,\n enabled,\n openPicker,\n processFiles,\n removeAttachment,\n consumeAttachments,\n };\n}\n","import React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useRef,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n CopilotChatConfigurationProvider,\n useAgent,\n useCopilotChatConfiguration,\n} from \"@copilotkit/react-core/headless\";\nimport { useCopilotKit } from \"@copilotkit/react-core/context\";\nimport { DEFAULT_AGENT_ID, randomUUID } from \"@copilotkit/shared\";\nimport type { InputContent } from \"@copilotkit/shared\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\nimport { useAttachments } from \"./hooks/use-attachments\";\nimport type { NativeAttachmentsConfig } from \"./hooks/use-attachments\";\nimport type { Attachment } from \"@copilotkit/shared\";\n\n// ---------------------------------------------------------------------------\n// Context\n// ---------------------------------------------------------------------------\n\nexport interface CopilotChatContextValue {\n /** The resolved agent instance. */\n agent: any;\n /** Whether the agent is currently running. */\n isRunning: boolean;\n /** Current messages in the conversation. */\n messages: any[];\n /** Currently selected attachments (uploading + ready). */\n attachments: Attachment[];\n /** Whether attachments are enabled. */\n attachmentsEnabled: boolean;\n /** Open the native document picker to add files. */\n openPicker: () => Promise<void>;\n /** Remove an attachment by ID. */\n removeAttachment: (id: string) => void;\n /**\n * Submit a message with optional attachments.\n * Handles consuming ready attachments, building InputContent[],\n * calling agent.addMessage, and running the agent.\n */\n submitMessage: (text: string) => Promise<void>;\n}\n\nconst CopilotChatCtx = createContext<CopilotChatContextValue | null>(null);\n\n/**\n * Hook to access the CopilotChat context from child components.\n * Must be called inside a `<CopilotChat>` component tree.\n */\nexport function useCopilotChatContext(): CopilotChatContextValue {\n const ctx = useContext(CopilotChatCtx);\n if (!ctx) {\n throw new Error(\n \"useCopilotChatContext must be used within a <CopilotChat> component\",\n );\n }\n return ctx;\n}\n\n// ---------------------------------------------------------------------------\n// Props\n// ---------------------------------------------------------------------------\n\nexport interface CopilotChatBaseProps {\n /**\n * The agent ID to use for this chat session.\n * Matches the web SDK's CopilotChat `agentId` prop.\n *\n * Resolution order: `agentId` > `agentName` > the agent of the chat (or\n * `CopilotChatConfigurationProvider`) around this one > `\"default\"`\n */\n agentId?: string;\n\n /**\n * @deprecated Use `agentId` instead. `agentName` is kept for backwards\n * compatibility and will be removed in a future release.\n */\n agentName?: string;\n\n /**\n * Thread ID for this chat session. When provided, the chat will resume\n * the specified thread. Matches the web SDK's CopilotChat `threadId` prop.\n */\n threadId?: string;\n\n /**\n * Error handler scoped to this chat's agent. Fires in addition to the\n * provider-level onError (does not suppress it). Receives errors whose\n * context.agentId matches this chat's agent, and errors with no agentId.\n */\n onError?: (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n\n /**\n * Throttle interval (in milliseconds) for re-renders triggered by message\n * change notifications. Overrides the provider-level `defaultThrottleMs`\n * for this chat instance. Forwarded to the internal `useAgent()` hook.\n *\n * @default undefined -- inherits from provider `defaultThrottleMs`;\n * if that is also unset, re-renders are unthrottled.\n */\n throttleMs?: number;\n\n /**\n * Enable multimodal file attachments (images, audio, video, documents).\n * Pass a NativeAttachmentsConfig object to configure file picking behavior.\n */\n attachments?: NativeAttachmentsConfig;\n\n /**\n * Optional children rendered inside the chat context.\n */\n children?: ReactNode;\n}\n\nexport interface CopilotChatProps extends CopilotChatBaseProps {\n /** Passthrough props are forwarded to consumers via the agent context. */\n [key: string]: unknown;\n}\n\n/**\n * Headless CopilotChat component for React Native.\n *\n * Wires up the `useAgent` hook with `agentId` resolution and renders children.\n * Unlike the web SDK's CopilotChat, this component does not render any UI\n * elements -- consumers provide their own React Native views.\n *\n * Children can access chat state via `useCopilotChatContext()`.\n *\n * Hooks inside the chat, such as `useAgent` and `useInterrupt`, use this\n * chat's agent when they do not pass an `agentId`. When the chat has a\n * `threadId`, `useAgent` inside the chat sets that thread on each agent it\n * returns, also on an agent that the hook names with its own `agentId`. Only\n * `useAgent({ agentId, runtimeAgentId, threadId })` keeps a different thread.\n *\n * A chat inside another chat uses the outer chat's agent when it has no\n * `agentId`. When the outer chat has a `threadId` and the inner chat does not,\n * the inner chat uses the outer thread. The web `CopilotChat` does the same.\n *\n * ```tsx\n * import { CopilotChat, useCopilotChatContext } from \"@copilotkit/react-native\";\n *\n * function MyChatUI() {\n * const { messages, submitMessage, attachments, openPicker } = useCopilotChatContext();\n * // ... render your UI\n * }\n *\n * <CopilotChat agentId=\"my-agent\" attachments={{ enabled: true }}>\n * <MyChatUI />\n * </CopilotChat>\n * ```\n */\nexport function CopilotChat({\n agentId,\n agentName,\n threadId,\n onError,\n throttleMs,\n attachments: attachmentsConfig,\n children,\n ..._rest\n}: CopilotChatProps) {\n // Same precedence as the web CopilotChat: a chat that names no agent takes\n // the agent of the chat configuration around it before \"default\".\n const chatConfig = useCopilotChatConfiguration();\n const resolvedAgentId =\n agentId ?? agentName ?? chatConfig?.agentId ?? DEFAULT_AGENT_ID;\n\n // Deprecation warning (dev only, fires once per mount)\n const warnedRef = useRef(false);\n useEffect(() => {\n if (\n agentName !== undefined &&\n agentId === undefined &&\n !warnedRef.current\n ) {\n warnedRef.current = true;\n if (typeof __DEV__ === \"undefined\" || __DEV__) {\n console.warn(\n \"[CopilotKit] agentName is deprecated, use agentId instead\",\n );\n }\n }\n }, [agentName, agentId]);\n\n const { agent } = useAgent({ agentId: resolvedAgentId, throttleMs });\n\n // Set threadId on the agent when provided\n useEffect(() => {\n if (threadId) {\n agent.threadId = threadId;\n }\n }, [agent, threadId]);\n\n // onError subscription -- forward core errors scoped to this chat's agent\n const { copilotkit } = useCopilotKit();\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n useEffect(() => {\n if (!onErrorRef.current) return;\n\n const subscription = copilotkit.subscribe({\n onError: (event) => {\n // Only forward errors that match this chat's agent\n if (\n event.context?.agentId === resolvedAgentId ||\n !event.context?.agentId\n ) {\n void onErrorRef.current?.({\n error: event.error,\n code: event.code,\n context: event.context,\n });\n }\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit, resolvedAgentId]);\n\n // Attachments\n const {\n attachments: selectedAttachments,\n enabled: attachmentsEnabled,\n openPicker,\n removeAttachment,\n consumeAttachments,\n } = useAttachments({ config: attachmentsConfig });\n\n // Submit handler -- mirrors web CopilotChat.tsx lines 234-288\n const submitMessage = useCallback(\n async (value: string) => {\n // Block if uploads in progress\n const hasUploading = selectedAttachments.some(\n (a) => a.status === \"uploading\",\n );\n if (hasUploading) {\n console.error(\n \"[CopilotKit] Cannot send while attachments are uploading\",\n );\n return;\n }\n\n const readyAttachments = consumeAttachments();\n\n if (readyAttachments.length > 0) {\n const contentParts: InputContent[] = [];\n if (value.trim()) {\n contentParts.push({ type: \"text\", text: value });\n }\n for (const att of readyAttachments) {\n contentParts.push({\n type: att.type,\n source: att.source,\n metadata: {\n ...(att.filename ? { filename: att.filename } : {}),\n ...att.metadata,\n },\n } as InputContent);\n }\n agent.addMessage({\n id: randomUUID(),\n role: \"user\",\n content: contentParts,\n });\n } else {\n agent.addMessage({\n id: randomUUID(),\n role: \"user\",\n content: value,\n });\n }\n\n try {\n await copilotkit.runAgent({ agent });\n } catch (error) {\n console.error(\"CopilotChat: runAgent failed\", error);\n }\n },\n // copilotkit is intentionally excluded -- it is a stable ref that never changes.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [agent, selectedAttachments, consumeAttachments],\n );\n\n const contextValue: CopilotChatContextValue = {\n agent,\n isRunning: agent.isRunning,\n messages: agent.messages,\n attachments: selectedAttachments,\n attachmentsEnabled,\n openPicker,\n removeAttachment,\n submitMessage,\n };\n\n // Publish this chat's agent and thread to the subtree, as the web\n // CopilotChat does. Hooks inside it that name no agent use this chat's\n // agent, which is the outer chat's agent when this chat names none.\n return (\n <CopilotChatConfigurationProvider\n agentId={resolvedAgentId}\n threadId={threadId}\n >\n <CopilotChatCtx.Provider value={contextValue}>\n {children}\n </CopilotChatCtx.Provider>\n </CopilotChatConfigurationProvider>\n );\n}\n","import React, { type ReactNode } from \"react\";\nimport { CopilotChat, type CopilotChatProps } from \"./CopilotChat\";\n\nexport interface CopilotModalProps extends CopilotChatProps {\n /**\n * Optional children rendered inside the modal context.\n */\n children?: ReactNode;\n}\n\n/**\n * Headless CopilotModal component for React Native.\n *\n * A thin wrapper around CopilotChat that mirrors the web SDK's CopilotModal\n * API surface. On React Native, modal presentation is handled by the consumer\n * (e.g. React Native's `Modal` component) -- this component only provides\n * the agent wiring and prop resolution.\n *\n * ```tsx\n * import { CopilotModal } from \"@copilotkit/react-native\";\n * import { Modal } from \"react-native\";\n *\n * <Modal visible={isOpen}>\n * <CopilotModal agentId=\"my-agent\">\n * <MyChatUI />\n * </CopilotModal>\n * </Modal>\n * ```\n */\nexport function CopilotModal({ children, ...props }: CopilotModalProps) {\n return <CopilotChat {...props}>{children}</CopilotChat>;\n}\n","import React, {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n Animated,\n Pressable,\n StyleSheet,\n Text,\n useWindowDimensions,\n View,\n} from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { CopilotChatBaseProps } from \"./CopilotChat\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface CopilotSidebarHandle {\n /** Slide the drawer open. */\n open(): void;\n /** Slide the drawer closed. */\n close(): void;\n /** Toggle the drawer open/closed. */\n toggle(): void;\n}\n\nexport interface CopilotSidebarProps extends Omit<\n CopilotChatBaseProps,\n \"children\"\n> {\n /**\n * Start the drawer in the open position.\n * @default false\n */\n defaultOpen?: boolean;\n\n /**\n * Width of the drawer panel. Accepts a number (points) or a percentage\n * string (e.g. `\"85%\"`). Defaults to 85% of the screen width.\n */\n width?: number | string;\n\n /**\n * Title displayed in the drawer header bar.\n * @default \"Copilot\"\n */\n headerTitle?: string;\n\n /**\n * Show a floating action button to toggle the drawer.\n * @default true\n */\n showToggleButton?: boolean;\n\n /** Called after the drawer finishes opening. */\n onOpen?: () => void;\n\n /** Called after the drawer finishes closing. */\n onClose?: () => void;\n\n /** Custom style applied to the drawer container. */\n style?: ViewStyle;\n\n /**\n * Your chat UI, rendered inside the drawer below the header. The inner\n * CopilotChat is headless and draws no messages or input of its own.\n */\n children?: ReactNode;\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst ANIMATION_DURATION_MS = 300;\nconst DEFAULT_HEADER_TITLE = \"Copilot\";\nconst BACKDROP_OPACITY = 0.4;\nconst FAB_SIZE = 56;\n\n// ---------------------------------------------------------------------------\n// Component\n// ---------------------------------------------------------------------------\n\n/**\n * CopilotSidebar -- a slide-in drawer from the right edge of the screen\n * that wraps CopilotChat for React Native.\n *\n * ```tsx\n * import { CopilotSidebar } from \"@copilotkit/react-native\";\n *\n * const ref = useRef<CopilotSidebarHandle>(null);\n *\n * <CopilotSidebar\n * ref={ref}\n * agentId=\"my-agent\"\n * headerTitle=\"Assistant\"\n * defaultOpen={false}\n * />\n * ```\n */\nexport const CopilotSidebar = forwardRef<\n CopilotSidebarHandle,\n CopilotSidebarProps\n>(function CopilotSidebar(\n {\n agentId,\n agentName,\n threadId,\n onError,\n throttleMs,\n defaultOpen = false,\n width: widthProp,\n headerTitle = DEFAULT_HEADER_TITLE,\n showToggleButton = true,\n onOpen,\n onClose,\n style,\n children,\n ...rest\n },\n ref,\n) {\n const { width: screenWidth } = useWindowDimensions();\n\n // Resolve drawer width ---------------------------------------------------\n const drawerWidth = resolveWidth(widthProp, screenWidth);\n\n // Animation & open state -------------------------------------------------\n const [isOpen, setIsOpen] = useState(defaultOpen);\n const [slideAnim] = useState(\n () => new Animated.Value(defaultOpen ? 0 : drawerWidth),\n );\n\n // Keep the animated value in sync when drawerWidth changes while closed\n useEffect(() => {\n if (!isOpen) {\n slideAnim.setValue(drawerWidth);\n }\n }, [drawerWidth, isOpen, slideAnim]);\n\n const animateTo = useCallback(\n (toValue: number, cb?: () => void) => {\n Animated.timing(slideAnim, {\n toValue,\n duration: ANIMATION_DURATION_MS,\n useNativeDriver: true,\n }).start(({ finished }) => {\n if (finished) cb?.();\n });\n },\n [slideAnim],\n );\n\n const open = useCallback(() => {\n setIsOpen(true);\n animateTo(0, onOpen);\n }, [animateTo, onOpen]);\n\n const close = useCallback(() => {\n animateTo(drawerWidth, () => {\n setIsOpen(false);\n onClose?.();\n });\n }, [animateTo, drawerWidth, onClose]);\n\n const toggle = useCallback(() => {\n if (isOpen) {\n close();\n } else {\n open();\n }\n }, [isOpen, open, close]);\n\n useImperativeHandle(ref, () => ({ open, close, toggle }), [\n open,\n close,\n toggle,\n ]);\n\n // Callbacks stored in refs for stable animation closures -----------------\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n useEffect(() => {\n onOpenRef.current = onOpen;\n }, [onOpen]);\n useEffect(() => {\n onCloseRef.current = onClose;\n }, [onClose]);\n\n // -----------------------------------------------------------------------\n // Render\n // -----------------------------------------------------------------------\n return (\n <>\n {/* Backdrop */}\n {isOpen && (\n <Pressable\n style={styles.backdrop}\n onPress={close}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Close sidebar\"\n testID=\"copilot-sidebar-backdrop\"\n />\n )}\n\n {/* Drawer */}\n {isOpen && (\n <Animated.View\n style={[\n styles.drawer,\n { width: drawerWidth, transform: [{ translateX: slideAnim }] },\n style,\n ]}\n testID=\"copilot-sidebar-drawer\"\n >\n {/* Header */}\n <View style={styles.header}>\n <Text style={styles.headerTitle}>{headerTitle}</Text>\n <Pressable\n onPress={close}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Close\"\n hitSlop={8}\n testID=\"copilot-sidebar-close\"\n >\n <Text style={styles.closeButton}>{\"✕\"}</Text>\n </Pressable>\n </View>\n\n {/* Chat area */}\n <View style={styles.chatContainer}>\n <CopilotChat\n agentId={agentId}\n agentName={agentName}\n threadId={threadId}\n onError={onError}\n throttleMs={throttleMs}\n {...rest}\n >\n {children}\n </CopilotChat>\n </View>\n </Animated.View>\n )}\n\n {/* Floating action button */}\n {showToggleButton && !isOpen && (\n <Pressable\n style={styles.fab}\n onPress={open}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Open sidebar\"\n testID=\"copilot-sidebar-fab\"\n >\n <Text style={styles.fabIcon}>{\"💬\"}</Text>\n </Pressable>\n )}\n </>\n );\n});\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction resolveWidth(\n widthProp: number | string | undefined,\n screenWidth: number,\n): number {\n if (widthProp === undefined) {\n return Math.round(screenWidth * 0.85);\n }\n if (typeof widthProp === \"number\") {\n return widthProp;\n }\n // Percentage string, e.g. \"85%\"\n const pctMatch = String(widthProp).match(/^(\\d+(?:\\.\\d+)?)%$/);\n if (pctMatch) {\n return Math.round(screenWidth * (parseFloat(pctMatch[1]) / 100));\n }\n // Fallback: try parsing as number\n const parsed = parseFloat(widthProp);\n return isNaN(parsed) ? Math.round(screenWidth * 0.85) : parsed;\n}\n\n// ---------------------------------------------------------------------------\n// Styles\n// ---------------------------------------------------------------------------\n\nconst styles = StyleSheet.create({\n backdrop: {\n ...StyleSheet.absoluteFill,\n backgroundColor: `rgba(0, 0, 0, ${BACKDROP_OPACITY})`,\n zIndex: 999,\n },\n drawer: {\n position: \"absolute\",\n top: 0,\n right: 0,\n bottom: 0,\n backgroundColor: \"#ffffff\",\n zIndex: 1000,\n shadowColor: \"#000\",\n shadowOffset: { width: -2, height: 0 },\n shadowOpacity: 0.25,\n shadowRadius: 8,\n elevation: 16,\n },\n header: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n paddingHorizontal: 16,\n paddingVertical: 12,\n borderBottomWidth: StyleSheet.hairlineWidth,\n borderBottomColor: \"#e0e0e0\",\n },\n headerTitle: {\n fontSize: 18,\n fontWeight: \"600\",\n color: \"#1a1a1a\",\n },\n closeButton: {\n fontSize: 20,\n color: \"#666\",\n padding: 4,\n },\n chatContainer: {\n flex: 1,\n },\n fab: {\n position: \"absolute\",\n bottom: 24,\n right: 24,\n width: FAB_SIZE,\n height: FAB_SIZE,\n borderRadius: FAB_SIZE / 2,\n backgroundColor: \"#007AFF\",\n alignItems: \"center\",\n justifyContent: \"center\",\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: 2 },\n shadowOpacity: 0.3,\n shadowRadius: 4,\n elevation: 8,\n zIndex: 998,\n },\n fabIcon: {\n fontSize: 24,\n },\n});\n","// NOTE: This component needs to be exported from index.ts\n// e.g. export { CopilotPopup } from \"./CopilotPopup\";\n// export type { CopilotPopupProps, CopilotPopupHandle } from \"./CopilotPopup\";\n\nimport React, {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n Modal,\n Pressable,\n StyleSheet,\n Text,\n TouchableOpacity,\n View,\n useWindowDimensions,\n} from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { NativeAttachmentsConfig } from \"./hooks/use-attachments\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\n\nexport interface CopilotPopupProps {\n /**\n * The agent ID to use for this chat session.\n * Passed through to CopilotChat.\n */\n agentId?: string;\n\n /**\n * @deprecated Use `agentId` instead.\n */\n agentName?: string;\n\n /**\n * Thread ID for this chat session.\n */\n threadId?: string;\n\n /**\n * Throttle interval (ms) for re-renders.\n */\n throttleMs?: number;\n\n /**\n * Whether the popup starts in the open state.\n * @default false\n */\n defaultOpen?: boolean;\n\n /**\n * Height of the popup card. Accepts a number (points) or a percentage\n * string (e.g. \"60%\") relative to the screen height.\n * @default \"60%\"\n */\n height?: number | string;\n\n /**\n * Error handler scoped to this popup's chat agent.\n */\n onError?: (error: Error) => void;\n\n /**\n * Title displayed in the popup header bar.\n * @default \"CopilotKit\"\n */\n headerTitle?: string;\n\n /**\n * Enable multimodal file attachments. Forwarded to the internal CopilotChat.\n * Children access attachment state via `useCopilotChatContext()`.\n */\n attachments?: NativeAttachmentsConfig;\n\n /**\n * Your chat UI, rendered inside the popup card below the header. The inner\n * CopilotChat is headless and draws no messages or input of its own.\n */\n children?: ReactNode;\n\n /**\n * Callback fired when the popup opens.\n */\n onOpen?: () => void;\n\n /**\n * Callback fired when the popup closes.\n */\n onClose?: () => void;\n\n /**\n * Whether tapping the semi-transparent backdrop dismisses the popup.\n * Equivalent to web SDK's `clickOutsideToClose`.\n * @default true\n */\n dismissOnBackdropPress?: boolean;\n\n /**\n * Whether to show the floating action button (FAB) that toggles the popup.\n * @default true\n */\n showToggleButton?: boolean;\n\n /**\n * Custom styles applied to the popup card container.\n */\n style?: ViewStyle;\n}\n\n/**\n * Imperative handle exposed via ref for controlling the popup programmatically.\n */\nexport interface CopilotPopupHandle {\n open: () => void;\n close: () => void;\n toggle: () => void;\n}\n\n/**\n * CopilotPopup for React Native.\n *\n * A floating action button (FAB) that opens a modal chat overlay.\n * The popup appears as a card floating above content with rounded corners,\n * a shadow, and a semi-transparent backdrop.\n *\n * ```tsx\n * import { CopilotPopup } from \"@copilotkit/react-native\";\n *\n * const popupRef = useRef<CopilotPopupHandle>(null);\n *\n * <CopilotPopup\n * ref={popupRef}\n * agentId=\"my-agent\"\n * headerTitle=\"Chat\"\n * defaultOpen={false}\n * />\n * ```\n */\nexport const CopilotPopup = forwardRef<CopilotPopupHandle, CopilotPopupProps>(\n function CopilotPopup(\n {\n agentId,\n agentName,\n threadId,\n throttleMs,\n defaultOpen = false,\n height = \"60%\",\n onError,\n headerTitle = \"CopilotKit\",\n attachments: attachmentsConfig,\n children,\n onOpen,\n onClose,\n dismissOnBackdropPress = true,\n showToggleButton = true,\n style,\n }: CopilotPopupProps,\n ref: React.Ref<CopilotPopupHandle>,\n ) {\n const [visible, setVisible] = useState(defaultOpen);\n const { height: screenHeight } = useWindowDimensions();\n\n // Stable refs for callbacks to avoid effect churn\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n useEffect(() => {\n onOpenRef.current = onOpen;\n }, [onOpen]);\n useEffect(() => {\n onCloseRef.current = onClose;\n }, [onClose]);\n\n const handleOpen = useCallback(() => {\n setVisible(true);\n onOpenRef.current?.();\n }, []);\n\n const handleClose = useCallback(() => {\n setVisible(false);\n onCloseRef.current?.();\n }, []);\n\n const handleToggle = useCallback(() => {\n setVisible((prev) => {\n const next = !prev;\n if (next) {\n onOpenRef.current?.();\n } else {\n onCloseRef.current?.();\n }\n return next;\n });\n }, []);\n\n // Expose imperative methods\n useImperativeHandle(\n ref,\n () => ({\n open: handleOpen,\n close: handleClose,\n toggle: handleToggle,\n }),\n [handleOpen, handleClose, handleToggle],\n );\n\n // Resolve popup height\n const resolvedHeight =\n typeof height === \"string\" && height.endsWith(\"%\")\n ? (parseFloat(height) / 100) * screenHeight\n : typeof height === \"number\"\n ? height\n : 0.6 * screenHeight;\n\n // Wrap onError to match CopilotChat's expected signature\n const chatOnError = onError\n ? (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => onError(event.error)\n : undefined;\n\n return (\n <>\n {/* Floating Action Button */}\n {showToggleButton && !visible && (\n <TouchableOpacity\n testID=\"copilot-popup-fab\"\n style={styles.fab}\n onPress={handleToggle}\n activeOpacity={0.8}\n accessibilityLabel=\"Open chat\"\n accessibilityRole=\"button\"\n >\n <Text style={styles.fabIcon}>💬</Text>\n </TouchableOpacity>\n )}\n\n {/* Modal Overlay */}\n <Modal\n testID=\"copilot-popup-modal\"\n visible={visible}\n transparent\n animationType=\"slide\"\n onRequestClose={handleClose}\n >\n {/* Backdrop */}\n <Pressable\n testID=\"copilot-popup-backdrop\"\n style={styles.backdrop}\n onPress={dismissOnBackdropPress ? handleClose : undefined}\n >\n {/* Card — stop propagation so tapping the card doesn't dismiss */}\n <Pressable\n testID=\"copilot-popup-card\"\n style={[styles.card, { height: resolvedHeight }, style]}\n onPress={() => {\n // Prevent backdrop press from firing\n }}\n >\n {/* Header */}\n <View style={styles.header}>\n <Text style={styles.headerTitle}>{headerTitle}</Text>\n <TouchableOpacity\n testID=\"copilot-popup-close\"\n onPress={handleClose}\n hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}\n accessibilityLabel=\"Close chat\"\n accessibilityRole=\"button\"\n >\n <Text style={styles.closeButton}>✕</Text>\n </TouchableOpacity>\n </View>\n\n {/* Chat Content */}\n <View style={styles.chatContainer}>\n <CopilotChat\n agentId={agentId}\n agentName={agentName}\n threadId={threadId}\n throttleMs={throttleMs}\n onError={chatOnError}\n attachments={attachmentsConfig}\n >\n {children}\n </CopilotChat>\n </View>\n </Pressable>\n </Pressable>\n </Modal>\n </>\n );\n },\n);\n\nconst styles = StyleSheet.create({\n fab: {\n position: \"absolute\",\n bottom: 24,\n right: 24,\n width: 56,\n height: 56,\n borderRadius: 28,\n backgroundColor: \"#6366f1\",\n alignItems: \"center\",\n justifyContent: \"center\",\n elevation: 6,\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: 3 },\n shadowOpacity: 0.27,\n shadowRadius: 4.65,\n },\n fabIcon: {\n fontSize: 24,\n },\n backdrop: {\n flex: 1,\n backgroundColor: \"rgba(0, 0, 0, 0.4)\",\n justifyContent: \"flex-end\",\n },\n card: {\n backgroundColor: \"#ffffff\",\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n overflow: \"hidden\",\n elevation: 10,\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: -3 },\n shadowOpacity: 0.25,\n shadowRadius: 8,\n },\n header: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n paddingHorizontal: 16,\n paddingVertical: 12,\n borderBottomWidth: StyleSheet.hairlineWidth,\n borderBottomColor: \"#e5e7eb\",\n },\n headerTitle: {\n fontSize: 17,\n fontWeight: \"600\",\n color: \"#111827\",\n },\n closeButton: {\n fontSize: 18,\n color: \"#6b7280\",\n fontWeight: \"500\",\n },\n chatContainer: {\n flex: 1,\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiFA,MAAM,mBAAmB,KAAK,OAAO;;;;;;;;;AAcrC,SAAgB,eAAe,EAC7B,UACwD;CACxD,MAAM,UAAU,QAAQ,WAAW;CAEnC,MAAM,CAAC,aAAa,sCAAyC,EAAE,CAAC;CAGhE,MAAM,8BAAmB,OAAO;AAChC,WAAU,UAAU;CACpB,MAAM,mCAAsC,EAAE,CAAC;AAC/C,gBAAe,UAAU;;;;;;CAOzB,MAAM,wCACH,MAAuB,WAA4B;AAClD,MAAI,CAAC,UAAU,WAAW,MAAO,QAAO;AAExC,SADgB,OAAO,MAAM,IAAI,CAAC,KAAK,MAAM,E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R,cAAc;EACd,iBAAiB;EACjB,YAAY;EACZ,gBAAgB;EAChB,WAAW;EACX,aAAa;EACb,cAAc;GAAE,OAAO;GAAG,QAAQ;GAAG;EACrC,eAAe;EACf,cAAc;EACf;CACD,SAAS,EACP,UAAU,IACX;CACD,UAAU;EACR,MAAM;EACN,iBAAiB;EACjB,gBAAgB;EACjB;CACD,MAAM;EACJ,iBAAiB;EACjB,qBAAqB;EACrB,sBAAsB;EACtB,UAAU;EACV,WAAW;EACX,aAAa;EACb,cAAc;GAAE,OAAO;GAAG,QAAQ;GAAI;EACtC,eAAe;EACf,cAAc;EACf;CACD,QAAQ;EACN,eAAe;EACf,YAAY;EACZ,gBAAgB;EAChB,mBAAmB;EACnB,iBAAiB;EACjB,mBAAmBA,wBAAW;EAC9B,mBAAmB;EACpB;CACD,aAAa;EACX,UAAU;EACV,YAAY;EACZ,OAAO;EACR;CACD,aAAa;EACX,UAAU;EACV,OAAO;EACP,YAAY;EACb;CACD,eAAe,EACb,MAAM,GACP;CACF,CAAC"}
1
+ {"version":3,"file":"index.cjs","names":["FileSystem","ɵAttachmentQueue","DocumentPicker","DEFAULT_AGENT_ID","ɵFreshThreadId","ɵChatConnection","CopilotChatConfigurationProvider","Animated","Pressable","styles","View","Text","StyleSheet","TouchableOpacity","Text","Modal","Pressable","View","StyleSheet"],"sources":["../src/hooks/use-attachments.ts","../src/CopilotChat.tsx","../src/CopilotModal.tsx","../src/CopilotSidebar.tsx","../src/CopilotPopup.tsx"],"sourcesContent":["// packages/react-native/src/hooks/use-attachments.ts\nimport { useCallback, useRef, useState, useSyncExternalStore } from \"react\";\nimport { ɵAttachmentQueue } from \"@copilotkit/core\";\nimport type {\n Attachment,\n AttachmentsConfig,\n AttachmentUploadResult,\n AttachmentUploadErrorReason,\n} from \"@copilotkit/shared\";\nimport * as DocumentPicker from \"expo-document-picker\";\nimport * as FileSystem from \"expo-file-system\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Platform-neutral file descriptor for React Native.\n * Replaces the web `File` object in all attachment APIs.\n */\nexport interface NativeFileInput {\n /** Local file URI (e.g. `file:///path/to/file`). */\n uri: string;\n /** Filename with extension. */\n name: string;\n /** File size in bytes. */\n size: number;\n /** MIME type (e.g. `\"image/jpeg\"`). */\n mimeType: string;\n}\n\n/**\n * React Native variant of AttachmentsConfig.\n * Identical to the shared AttachmentsConfig except `onUpload` receives\n * a `NativeFileInput` instead of a web `File`.\n */\nexport interface NativeAttachmentsConfig {\n /** Enable file attachments in the chat input. */\n enabled: boolean;\n /** MIME type filter for the file picker, default all files. */\n accept?: string;\n /** Maximum file size in bytes, default 20MB (20 * 1024 * 1024). */\n maxSize?: number;\n /** Custom upload handler. Receives the native file descriptor. */\n onUpload?: (\n file: NativeFileInput,\n ) => AttachmentUploadResult | Promise<AttachmentUploadResult>;\n /** Called when an attachment fails validation or upload. */\n onUploadFailed?: (error: {\n reason: AttachmentUploadErrorReason;\n file: NativeFileInput;\n message: string;\n }) => void;\n}\n\nexport interface UseNativeAttachmentsProps {\n config?: NativeAttachmentsConfig;\n}\n\nexport interface UseNativeAttachmentsReturn {\n /** Currently selected attachments (uploading + ready). */\n attachments: Attachment[];\n /** Whether attachments are enabled. */\n enabled: boolean;\n /** Open the native document picker. */\n openPicker: () => Promise<void>;\n /** Process an array of NativeFileInput objects (validate, read, add to state). */\n processFiles: (files: NativeFileInput[]) => Promise<void>;\n /** Remove an attachment by ID. */\n removeAttachment: (id: string) => void;\n /** Consume ready attachments and clear the queue. Returns the consumed attachments. */\n consumeAttachments: () => Attachment[];\n}\n\n// ---------------------------------------------------------------------------\n// Queue adapter\n// ---------------------------------------------------------------------------\n\n/**\n * The queue's view of a picked file: the `name`, `size` and `type` it reads to\n * validate the file and to draw its placeholder.\n */\ninterface QueuedNativeFile {\n name: string;\n size: number;\n type: string;\n}\n\n// The native descriptor behind each file the queue holds, so the app's\n// callbacks get the `NativeFileInput` they were typed for.\nconst nativeFiles = new WeakMap<object, NativeFileInput>();\n\n/**\n * Wraps a native file for core's `ɵAttachmentQueue`, which is typed for the\n * web `File`. The queue reads only `name`, `size` and `type`, because the\n * config from {@link toQueueConfig} always uploads through `onUpload` and the\n * queue never reads the bytes itself.\n */\nfunction toQueueFile(file: NativeFileInput) {\n const queued: QueuedNativeFile = {\n name: file.name,\n size: file.size,\n type: file.mimeType,\n };\n nativeFiles.set(queued, file);\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the queue is typed for the web File; it only reads name, size and type, and uploads go through onUpload with the native file\n return queued as unknown as File;\n}\n\nfunction toNativeFile(file: File) {\n const native = nativeFiles.get(file);\n if (!native) {\n throw new Error(`[CopilotKit] \"${file.name}\" was not picked natively`);\n }\n return native;\n}\n\n/** Reads a picked file as base64 with expo-file-system. */\nasync function readNativeFile(file: NativeFileInput) {\n const value = await FileSystem.readAsStringAsync(file.uri, {\n encoding: FileSystem.EncodingType.Base64,\n });\n return { type: \"data\" as const, value, mimeType: file.mimeType };\n}\n\n/**\n * The RN config as core's queue takes it. Uploads go through the app's\n * `onUpload`, or through expo-file-system when there is none.\n */\nfunction toQueueConfig(\n config: NativeAttachmentsConfig | undefined,\n): AttachmentsConfig | undefined {\n if (!config) return undefined;\n const { onUpload, onUploadFailed, ...rest } = config;\n return {\n ...rest,\n onUpload: (file) => {\n const native = toNativeFile(file);\n return onUpload ? onUpload(native) : readNativeFile(native);\n },\n onUploadFailed: onUploadFailed\n ? ({ file, ...error }) =>\n onUploadFailed({ ...error, file: toNativeFile(file) })\n : undefined,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\n/**\n * React Native hook that manages file attachment state -- picking, uploading,\n * and lifecycle. All returned callbacks are referentially stable.\n *\n * The queue itself (accept filter, size check, uploads, ready state) is\n * `@copilotkit/core`'s `ɵAttachmentQueue`, shared with the web chats. This\n * hook adds the native glue: expo-document-picker to pick files and\n * expo-file-system to read them.\n */\nexport function useAttachments({\n config,\n}: UseNativeAttachmentsProps): UseNativeAttachmentsReturn {\n const enabled = config?.enabled ?? false;\n\n // The queue reads the latest config on every action.\n const configRef = useRef(config);\n configRef.current = config;\n\n const [queue] = useState(\n () => new ɵAttachmentQueue(() => toQueueConfig(configRef.current)),\n );\n const attachments = useSyncExternalStore(\n useCallback((onChange) => queue.subscribe(onChange), [queue]),\n () => queue.getSnapshot(),\n () => queue.getSnapshot(),\n );\n\n const processFiles = useCallback(\n (files: NativeFileInput[]) => queue.processFiles(files.map(toQueueFile)),\n [queue],\n );\n\n const openPicker = useCallback(async () => {\n const accept = configRef.current?.accept ?? \"*/*\";\n\n // Convert accept string to array for DocumentPicker\n const typeArray = accept\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean);\n\n try {\n const result = await DocumentPicker.getDocumentAsync({\n type: typeArray.length > 0 ? typeArray : [\"*/*\"],\n copyToCacheDirectory: true,\n multiple: true,\n });\n\n if (result.canceled || !result.assets?.length) return;\n\n const pickedFiles: NativeFileInput[] = result.assets.map((asset) => ({\n uri: asset.uri,\n name: asset.name ?? \"unknown\",\n size: asset.size ?? 0,\n mimeType: asset.mimeType ?? \"application/octet-stream\",\n }));\n\n await processFiles(pickedFiles);\n } catch (error) {\n console.error(\"[CopilotKit] Document picker error:\", error);\n }\n }, [processFiles]);\n\n const removeAttachment = useCallback(\n (id: string) => queue.remove(id),\n [queue],\n );\n\n const consumeAttachments = useCallback(() => queue.consumeReady(), [queue]);\n\n return {\n attachments,\n enabled,\n openPicker,\n processFiles,\n removeAttachment,\n consumeAttachments,\n };\n}\n","import React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n CopilotChatConfigurationProvider,\n useAgent,\n useCopilotChatConfiguration,\n} from \"@copilotkit/react-core/headless\";\nimport { useCopilotKit } from \"@copilotkit/react-core/context\";\nimport { DEFAULT_AGENT_ID } from \"@copilotkit/shared\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\nimport {\n ɵChatConnection,\n ɵFreshThreadId,\n ɵcreateChatSubmitter,\n ɵsubscribeToAgentErrors,\n} from \"@copilotkit/core\";\nimport { useAttachments } from \"./hooks/use-attachments\";\nimport type { NativeAttachmentsConfig } from \"./hooks/use-attachments\";\nimport type { Attachment } from \"@copilotkit/shared\";\n\n// ---------------------------------------------------------------------------\n// Context\n// ---------------------------------------------------------------------------\n\nexport interface CopilotChatContextValue {\n /** The resolved agent instance. */\n agent: any;\n /** Whether the agent is currently running. */\n isRunning: boolean;\n /** Current messages in the conversation. */\n messages: any[];\n /** Currently selected attachments (uploading + ready). */\n attachments: Attachment[];\n /** Whether attachments are enabled. */\n attachmentsEnabled: boolean;\n /** Open the native document picker to add files. */\n openPicker: () => Promise<void>;\n /** Remove an attachment by ID. */\n removeAttachment: (id: string) => void;\n /**\n * Submit a message with the ready attachments and run the agent. Waits\n * for the thread's connection and for the run in flight. Blank text, and a\n * send while an attachment uploads, are ignored. Resolves once the run has\n * settled.\n */\n submitMessage: (text: string) => Promise<void>;\n}\n\nconst CopilotChatCtx = createContext<CopilotChatContextValue | null>(null);\n\n/**\n * Hook to access the CopilotChat context from child components.\n * Must be called inside a `<CopilotChat>` component tree.\n */\nexport function useCopilotChatContext(): CopilotChatContextValue {\n const ctx = useContext(CopilotChatCtx);\n if (!ctx) {\n throw new Error(\n \"useCopilotChatContext must be used within a <CopilotChat> component\",\n );\n }\n return ctx;\n}\n\n// ---------------------------------------------------------------------------\n// Props\n// ---------------------------------------------------------------------------\n\nexport interface CopilotChatBaseProps {\n /**\n * The agent ID to use for this chat session.\n * Matches the web SDK's CopilotChat `agentId` prop.\n *\n * Resolution order: `agentId` > `agentName` > the agent of the chat (or\n * `CopilotChatConfigurationProvider`) around this one > `\"default\"`\n */\n agentId?: string;\n\n /**\n * @deprecated Use `agentId` instead. `agentName` is kept for backwards\n * compatibility and will be removed in a future release.\n */\n agentName?: string;\n\n /**\n * Thread ID for this chat session. When provided, the chat restores the\n * thread from the backend and reconnects to a run in progress. Without it,\n * the chat uses the thread of the chat around it, or a new thread. Matches\n * the web SDK's CopilotChat `threadId` prop.\n */\n threadId?: string;\n\n /**\n * Error handler scoped to this chat's agent. Fires in addition to the\n * provider-level onError (does not suppress it). Receives errors whose\n * context.agentId matches this chat's agent, and errors with no agentId.\n */\n onError?: (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n\n /**\n * Throttle interval (in milliseconds) for re-renders triggered by message\n * change notifications. Overrides the provider-level `defaultThrottleMs`\n * for this chat instance. Forwarded to the internal `useAgent()` hook.\n *\n * @default undefined -- inherits from provider `defaultThrottleMs`;\n * if that is also unset, re-renders are unthrottled.\n */\n throttleMs?: number;\n\n /**\n * Enable multimodal file attachments (images, audio, video, documents).\n * Pass a NativeAttachmentsConfig object to configure file picking behavior.\n */\n attachments?: NativeAttachmentsConfig;\n\n /**\n * Optional children rendered inside the chat context.\n */\n children?: ReactNode;\n}\n\nexport interface CopilotChatProps extends CopilotChatBaseProps {\n /** Passthrough props are forwarded to consumers via the agent context. */\n [key: string]: unknown;\n}\n\n/**\n * Headless CopilotChat component for React Native.\n *\n * Wires up the `useAgent` hook with `agentId` resolution and renders children.\n * Unlike the web SDK's CopilotChat, this component does not render any UI\n * elements -- consumers provide their own React Native views.\n *\n * Children can access chat state via `useCopilotChatContext()`.\n *\n * Hooks inside the chat, such as `useAgent` and `useInterrupt`, use this\n * chat's agent when they do not pass an `agentId`. When the chat has a\n * `threadId`, `useAgent` inside the chat sets that thread on each agent it\n * returns, also on an agent that the hook names with its own `agentId`. Only\n * `useAgent({ agentId, runtimeAgentId, threadId })` keeps a different thread.\n *\n * A chat inside another chat uses the outer chat's agent when it has no\n * `agentId`. When the outer chat has a `threadId` and the inner chat does not,\n * the inner chat uses the outer thread. The web `CopilotChat` does the same.\n *\n * ```tsx\n * import { CopilotChat, useCopilotChatContext } from \"@copilotkit/react-native\";\n *\n * function MyChatUI() {\n * const { messages, submitMessage, attachments, openPicker } = useCopilotChatContext();\n * // ... render your UI\n * }\n *\n * <CopilotChat agentId=\"my-agent\" attachments={{ enabled: true }}>\n * <MyChatUI />\n * </CopilotChat>\n * ```\n */\nexport function CopilotChat({\n agentId,\n agentName,\n threadId,\n onError,\n throttleMs,\n attachments: attachmentsConfig,\n children,\n ..._rest\n}: CopilotChatProps) {\n // Same precedence as the web CopilotChat: a chat that names no agent takes\n // the agent of the chat configuration around it before \"default\".\n const chatConfig = useCopilotChatConfiguration();\n const resolvedAgentId =\n agentId ?? agentName ?? chatConfig?.agentId ?? DEFAULT_AGENT_ID;\n\n // Deprecation warning (dev only, fires once per mount)\n const warnedRef = useRef(false);\n useEffect(() => {\n if (\n agentName !== undefined &&\n agentId === undefined &&\n !warnedRef.current\n ) {\n warnedRef.current = true;\n if (typeof __DEV__ === \"undefined\" || __DEV__) {\n console.warn(\n \"[CopilotKit] agentName is deprecated, use agentId instead\",\n );\n }\n }\n }, [agentName, agentId]);\n\n // Same thread rules as the web CopilotChat: the `threadId` prop, else the\n // thread of the chat around this one, else a UUID minted for this chat.\n // Only a thread a caller picked is \"explicit\" and restored from the backend.\n const providedThreadId = threadId ?? chatConfig?.threadId;\n const [freshThreadId] = useState(() => new ɵFreshThreadId());\n const resolvedThreadId = useMemo(\n () => freshThreadId.resolve(providedThreadId),\n [freshThreadId, providedThreadId],\n );\n const hasExplicitThreadId = !!threadId || !!chatConfig?.hasExplicitThreadId;\n\n const { agent } = useAgent({ agentId: resolvedAgentId, throttleMs });\n const { copilotkit } = useCopilotKit();\n\n // Keeps the agent on the thread this chat shows, restores a picked thread\n // with a connect, and empties the agent on a switch to a fresh thread. Core\n // owns the connect's abort and detach, as in the web chats.\n const [connection] = useState(\n () => new ɵChatConnection({ core: copilotkit }),\n );\n const { threads } = connection;\n useEffect(() => {\n const handle = connection.open({\n agent,\n threadId: resolvedThreadId,\n explicit: hasExplicitThreadId,\n });\n return () => handle.release();\n }, [connection, agent, resolvedThreadId, hasExplicitThreadId]);\n\n // onError subscription -- forward core errors scoped to this chat's agent\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n useEffect(() => {\n if (!onErrorRef.current) return;\n return ɵsubscribeToAgentErrors(copilotkit, resolvedAgentId, (event) =>\n onErrorRef.current?.(event),\n );\n }, [copilotkit, resolvedAgentId]);\n\n // Attachments\n const {\n attachments: selectedAttachments,\n enabled: attachmentsEnabled,\n openPicker,\n removeAttachment,\n consumeAttachments,\n } = useAttachments({ config: attachmentsConfig });\n // A send waits for the run in flight, so the submitter re-checks the\n // upload guard against the latest attachments, not this render's.\n const attachmentsRef = useRef(selectedAttachments);\n useLayoutEffect(() => {\n attachmentsRef.current = selectedAttachments;\n });\n\n // The send side lives in core: the upload guard, the message content, and\n // waiting for the thread's connection and the run in flight.\n const agentRef = useRef(agent);\n useLayoutEffect(() => {\n agentRef.current = agent;\n });\n const [submitter] = useState(() =>\n ɵcreateChatSubmitter({\n core: copilotkit,\n getAgent: () => agentRef.current,\n // This chat renders no input box, so there is no text to clear or put\n // back.\n input: { get: () => \"\", set: () => {} },\n attachments: {\n isUploading: () =>\n attachmentsRef.current.some((a) => a.status === \"uploading\"),\n consumeReady: () => consumeAttachments(),\n },\n threads,\n }),\n );\n // Clears the notice timer of a blocked send on unmount.\n useEffect(() => () => submitter.showNotice(null), [submitter]);\n const submitMessage = useCallback(\n (value: string) => submitter.submit(value),\n [submitter],\n );\n\n const contextValue: CopilotChatContextValue = {\n agent,\n isRunning: agent.isRunning,\n messages: agent.messages,\n attachments: selectedAttachments,\n attachmentsEnabled,\n openPicker,\n removeAttachment,\n submitMessage,\n };\n\n // Publish this chat's agent and thread to the subtree, as the web\n // CopilotChat does. Hooks inside it that name no agent use this chat's\n // agent, which is the outer chat's agent when this chat names none.\n return (\n <CopilotChatConfigurationProvider\n agentId={resolvedAgentId}\n threadId={resolvedThreadId}\n hasExplicitThreadId={hasExplicitThreadId}\n >\n <CopilotChatCtx.Provider value={contextValue}>\n {children}\n </CopilotChatCtx.Provider>\n </CopilotChatConfigurationProvider>\n );\n}\n","import React, { type ReactNode } from \"react\";\nimport { CopilotChat, type CopilotChatProps } from \"./CopilotChat\";\n\nexport interface CopilotModalProps extends CopilotChatProps {\n /**\n * Optional children rendered inside the modal context.\n */\n children?: ReactNode;\n}\n\n/**\n * Headless CopilotModal component for React Native.\n *\n * A thin wrapper around CopilotChat that mirrors the web SDK's CopilotModal\n * API surface. On React Native, modal presentation is handled by the consumer\n * (e.g. React Native's `Modal` component) -- this component only provides\n * the agent wiring and prop resolution.\n *\n * ```tsx\n * import { CopilotModal } from \"@copilotkit/react-native\";\n * import { Modal } from \"react-native\";\n *\n * <Modal visible={isOpen}>\n * <CopilotModal agentId=\"my-agent\">\n * <MyChatUI />\n * </CopilotModal>\n * </Modal>\n * ```\n */\nexport function CopilotModal({ children, ...props }: CopilotModalProps) {\n return <CopilotChat {...props}>{children}</CopilotChat>;\n}\n","import React, {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n Animated,\n Pressable,\n StyleSheet,\n Text,\n useWindowDimensions,\n View,\n} from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { CopilotChatBaseProps } from \"./CopilotChat\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface CopilotSidebarHandle {\n /** Slide the drawer open. */\n open(): void;\n /** Slide the drawer closed. */\n close(): void;\n /** Toggle the drawer open/closed. */\n toggle(): void;\n}\n\nexport interface CopilotSidebarProps extends Omit<\n CopilotChatBaseProps,\n \"children\"\n> {\n /**\n * Start the drawer in the open position.\n * @default false\n */\n defaultOpen?: boolean;\n\n /**\n * Width of the drawer panel. Accepts a number (points) or a percentage\n * string (e.g. `\"85%\"`). Defaults to 85% of the screen width.\n */\n width?: number | string;\n\n /**\n * Title displayed in the drawer header bar.\n * @default \"Copilot\"\n */\n headerTitle?: string;\n\n /**\n * Show a floating action button to toggle the drawer.\n * @default true\n */\n showToggleButton?: boolean;\n\n /** Called after the drawer finishes opening. */\n onOpen?: () => void;\n\n /** Called after the drawer finishes closing. */\n onClose?: () => void;\n\n /** Custom style applied to the drawer container. */\n style?: ViewStyle;\n\n /**\n * Your chat UI, rendered inside the drawer below the header. The inner\n * CopilotChat is headless and draws no messages or input of its own.\n */\n children?: ReactNode;\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst ANIMATION_DURATION_MS = 300;\nconst DEFAULT_HEADER_TITLE = \"Copilot\";\nconst BACKDROP_OPACITY = 0.4;\nconst FAB_SIZE = 56;\n\n// ---------------------------------------------------------------------------\n// Component\n// ---------------------------------------------------------------------------\n\n/**\n * CopilotSidebar -- a slide-in drawer from the right edge of the screen\n * that wraps CopilotChat for React Native.\n *\n * ```tsx\n * import { CopilotSidebar } from \"@copilotkit/react-native\";\n *\n * const ref = useRef<CopilotSidebarHandle>(null);\n *\n * <CopilotSidebar\n * ref={ref}\n * agentId=\"my-agent\"\n * headerTitle=\"Assistant\"\n * defaultOpen={false}\n * />\n * ```\n */\nexport const CopilotSidebar = forwardRef<\n CopilotSidebarHandle,\n CopilotSidebarProps\n>(function CopilotSidebar(\n {\n agentId,\n agentName,\n threadId,\n onError,\n throttleMs,\n defaultOpen = false,\n width: widthProp,\n headerTitle = DEFAULT_HEADER_TITLE,\n showToggleButton = true,\n onOpen,\n onClose,\n style,\n children,\n ...rest\n },\n ref,\n) {\n const { width: screenWidth } = useWindowDimensions();\n\n // Resolve drawer width ---------------------------------------------------\n const drawerWidth = resolveWidth(widthProp, screenWidth);\n\n // Animation & open state -------------------------------------------------\n const [isOpen, setIsOpen] = useState(defaultOpen);\n const [slideAnim] = useState(\n () => new Animated.Value(defaultOpen ? 0 : drawerWidth),\n );\n\n // Keep the animated value in sync when drawerWidth changes while closed\n useEffect(() => {\n if (!isOpen) {\n slideAnim.setValue(drawerWidth);\n }\n }, [drawerWidth, isOpen, slideAnim]);\n\n const animateTo = useCallback(\n (toValue: number, cb?: () => void) => {\n Animated.timing(slideAnim, {\n toValue,\n duration: ANIMATION_DURATION_MS,\n useNativeDriver: true,\n }).start(({ finished }) => {\n if (finished) cb?.();\n });\n },\n [slideAnim],\n );\n\n const open = useCallback(() => {\n setIsOpen(true);\n animateTo(0, onOpen);\n }, [animateTo, onOpen]);\n\n const close = useCallback(() => {\n animateTo(drawerWidth, () => {\n setIsOpen(false);\n onClose?.();\n });\n }, [animateTo, drawerWidth, onClose]);\n\n const toggle = useCallback(() => {\n if (isOpen) {\n close();\n } else {\n open();\n }\n }, [isOpen, open, close]);\n\n useImperativeHandle(ref, () => ({ open, close, toggle }), [\n open,\n close,\n toggle,\n ]);\n\n // Callbacks stored in refs for stable animation closures -----------------\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n useEffect(() => {\n onOpenRef.current = onOpen;\n }, [onOpen]);\n useEffect(() => {\n onCloseRef.current = onClose;\n }, [onClose]);\n\n // -----------------------------------------------------------------------\n // Render\n // -----------------------------------------------------------------------\n return (\n <>\n {/* Backdrop */}\n {isOpen && (\n <Pressable\n style={styles.backdrop}\n onPress={close}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Close sidebar\"\n testID=\"copilot-sidebar-backdrop\"\n />\n )}\n\n {/* Drawer */}\n {isOpen && (\n <Animated.View\n style={[\n styles.drawer,\n { width: drawerWidth, transform: [{ translateX: slideAnim }] },\n style,\n ]}\n testID=\"copilot-sidebar-drawer\"\n >\n {/* Header */}\n <View style={styles.header}>\n <Text style={styles.headerTitle}>{headerTitle}</Text>\n <Pressable\n onPress={close}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Close\"\n hitSlop={8}\n testID=\"copilot-sidebar-close\"\n >\n <Text style={styles.closeButton}>{\"✕\"}</Text>\n </Pressable>\n </View>\n\n {/* Chat area */}\n <View style={styles.chatContainer}>\n <CopilotChat\n agentId={agentId}\n agentName={agentName}\n threadId={threadId}\n onError={onError}\n throttleMs={throttleMs}\n {...rest}\n >\n {children}\n </CopilotChat>\n </View>\n </Animated.View>\n )}\n\n {/* Floating action button */}\n {showToggleButton && !isOpen && (\n <Pressable\n style={styles.fab}\n onPress={open}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Open sidebar\"\n testID=\"copilot-sidebar-fab\"\n >\n <Text style={styles.fabIcon}>{\"💬\"}</Text>\n </Pressable>\n )}\n </>\n );\n});\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction resolveWidth(\n widthProp: number | string | undefined,\n screenWidth: number,\n): number {\n if (widthProp === undefined) {\n return Math.round(screenWidth * 0.85);\n }\n if (typeof widthProp === \"number\") {\n return widthProp;\n }\n // Percentage string, e.g. \"85%\"\n const pctMatch = String(widthProp).match(/^(\\d+(?:\\.\\d+)?)%$/);\n if (pctMatch) {\n return Math.round(screenWidth * (parseFloat(pctMatch[1]) / 100));\n }\n // Fallback: try parsing as number\n const parsed = parseFloat(widthProp);\n return isNaN(parsed) ? Math.round(screenWidth * 0.85) : parsed;\n}\n\n// ---------------------------------------------------------------------------\n// Styles\n// ---------------------------------------------------------------------------\n\nconst styles = StyleSheet.create({\n backdrop: {\n ...StyleSheet.absoluteFill,\n backgroundColor: `rgba(0, 0, 0, ${BACKDROP_OPACITY})`,\n zIndex: 999,\n },\n drawer: {\n position: \"absolute\",\n top: 0,\n right: 0,\n bottom: 0,\n backgroundColor: \"#ffffff\",\n zIndex: 1000,\n shadowColor: \"#000\",\n shadowOffset: { width: -2, height: 0 },\n shadowOpacity: 0.25,\n shadowRadius: 8,\n elevation: 16,\n },\n header: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n paddingHorizontal: 16,\n paddingVertical: 12,\n borderBottomWidth: StyleSheet.hairlineWidth,\n borderBottomColor: \"#e0e0e0\",\n },\n headerTitle: {\n fontSize: 18,\n fontWeight: \"600\",\n color: \"#1a1a1a\",\n },\n closeButton: {\n fontSize: 20,\n color: \"#666\",\n padding: 4,\n },\n chatContainer: {\n flex: 1,\n },\n fab: {\n position: \"absolute\",\n bottom: 24,\n right: 24,\n width: FAB_SIZE,\n height: FAB_SIZE,\n borderRadius: FAB_SIZE / 2,\n backgroundColor: \"#007AFF\",\n alignItems: \"center\",\n justifyContent: \"center\",\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: 2 },\n shadowOpacity: 0.3,\n shadowRadius: 4,\n elevation: 8,\n zIndex: 998,\n },\n fabIcon: {\n fontSize: 24,\n },\n});\n","// NOTE: This component needs to be exported from index.ts\n// e.g. export { CopilotPopup } from \"./CopilotPopup\";\n// export type { CopilotPopupProps, CopilotPopupHandle } from \"./CopilotPopup\";\n\nimport React, {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n Modal,\n Pressable,\n StyleSheet,\n Text,\n TouchableOpacity,\n View,\n useWindowDimensions,\n} from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { NativeAttachmentsConfig } from \"./hooks/use-attachments\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\n\nexport interface CopilotPopupProps {\n /**\n * The agent ID to use for this chat session.\n * Passed through to CopilotChat.\n */\n agentId?: string;\n\n /**\n * @deprecated Use `agentId` instead.\n */\n agentName?: string;\n\n /**\n * Thread ID for this chat session.\n */\n threadId?: string;\n\n /**\n * Throttle interval (ms) for re-renders.\n */\n throttleMs?: number;\n\n /**\n * Whether the popup starts in the open state.\n * @default false\n */\n defaultOpen?: boolean;\n\n /**\n * Height of the popup card. Accepts a number (points) or a percentage\n * string (e.g. \"60%\") relative to the screen height.\n * @default \"60%\"\n */\n height?: number | string;\n\n /**\n * Error handler scoped to this popup's chat agent.\n */\n onError?: (error: Error) => void;\n\n /**\n * Title displayed in the popup header bar.\n * @default \"CopilotKit\"\n */\n headerTitle?: string;\n\n /**\n * Enable multimodal file attachments. Forwarded to the internal CopilotChat.\n * Children access attachment state via `useCopilotChatContext()`.\n */\n attachments?: NativeAttachmentsConfig;\n\n /**\n * Your chat UI, rendered inside the popup card below the header. The inner\n * CopilotChat is headless and draws no messages or input of its own.\n */\n children?: ReactNode;\n\n /**\n * Callback fired when the popup opens.\n */\n onOpen?: () => void;\n\n /**\n * Callback fired when the popup closes.\n */\n onClose?: () => void;\n\n /**\n * Whether tapping the semi-transparent backdrop dismisses the popup.\n * Equivalent to web SDK's `clickOutsideToClose`.\n * @default true\n */\n dismissOnBackdropPress?: boolean;\n\n /**\n * Whether to show the floating action button (FAB) that toggles the popup.\n * @default true\n */\n showToggleButton?: boolean;\n\n /**\n * Custom styles applied to the popup card container.\n */\n style?: ViewStyle;\n}\n\n/**\n * Imperative handle exposed via ref for controlling the popup programmatically.\n */\nexport interface CopilotPopupHandle {\n open: () => void;\n close: () => void;\n toggle: () => void;\n}\n\n/**\n * CopilotPopup for React Native.\n *\n * A floating action button (FAB) that opens a modal chat overlay.\n * The popup appears as a card floating above content with rounded corners,\n * a shadow, and a semi-transparent backdrop.\n *\n * ```tsx\n * import { CopilotPopup } from \"@copilotkit/react-native\";\n *\n * const popupRef = useRef<CopilotPopupHandle>(null);\n *\n * <CopilotPopup\n * ref={popupRef}\n * agentId=\"my-agent\"\n * headerTitle=\"Chat\"\n * defaultOpen={false}\n * />\n * ```\n */\nexport const CopilotPopup = forwardRef<CopilotPopupHandle, CopilotPopupProps>(\n function CopilotPopup(\n {\n agentId,\n agentName,\n threadId,\n throttleMs,\n defaultOpen = false,\n height = \"60%\",\n onError,\n headerTitle = \"CopilotKit\",\n attachments: attachmentsConfig,\n children,\n onOpen,\n onClose,\n dismissOnBackdropPress = true,\n showToggleButton = true,\n style,\n }: CopilotPopupProps,\n ref: React.Ref<CopilotPopupHandle>,\n ) {\n const [visible, setVisible] = useState(defaultOpen);\n const { height: screenHeight } = useWindowDimensions();\n\n // Stable refs for callbacks to avoid effect churn\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n useEffect(() => {\n onOpenRef.current = onOpen;\n }, [onOpen]);\n useEffect(() => {\n onCloseRef.current = onClose;\n }, [onClose]);\n\n const handleOpen = useCallback(() => {\n setVisible(true);\n onOpenRef.current?.();\n }, []);\n\n const handleClose = useCallback(() => {\n setVisible(false);\n onCloseRef.current?.();\n }, []);\n\n const handleToggle = useCallback(() => {\n setVisible((prev) => {\n const next = !prev;\n if (next) {\n onOpenRef.current?.();\n } else {\n onCloseRef.current?.();\n }\n return next;\n });\n }, []);\n\n // Expose imperative methods\n useImperativeHandle(\n ref,\n () => ({\n open: handleOpen,\n close: handleClose,\n toggle: handleToggle,\n }),\n [handleOpen, handleClose, handleToggle],\n );\n\n // Resolve popup height\n const resolvedHeight =\n typeof height === \"string\" && height.endsWith(\"%\")\n ? (parseFloat(height) / 100) * screenHeight\n : typeof height === \"number\"\n ? height\n : 0.6 * screenHeight;\n\n // Wrap onError to match CopilotChat's expected signature\n const chatOnError = onError\n ? (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => onError(event.error)\n : undefined;\n\n return (\n <>\n {/* Floating Action Button */}\n {showToggleButton && !visible && (\n <TouchableOpacity\n testID=\"copilot-popup-fab\"\n style={styles.fab}\n onPress={handleToggle}\n activeOpacity={0.8}\n accessibilityLabel=\"Open chat\"\n accessibilityRole=\"button\"\n >\n <Text style={styles.fabIcon}>💬</Text>\n </TouchableOpacity>\n )}\n\n {/* Modal Overlay */}\n <Modal\n testID=\"copilot-popup-modal\"\n visible={visible}\n transparent\n animationType=\"slide\"\n onRequestClose={handleClose}\n >\n {/* Backdrop */}\n <Pressable\n testID=\"copilot-popup-backdrop\"\n style={styles.backdrop}\n onPress={dismissOnBackdropPress ? handleClose : undefined}\n >\n {/* Card — stop propagation so tapping the card doesn't dismiss */}\n <Pressable\n testID=\"copilot-popup-card\"\n style={[styles.card, { height: resolvedHeight }, style]}\n onPress={() => {\n // Prevent backdrop press from firing\n }}\n >\n {/* Header */}\n <View style={styles.header}>\n <Text style={styles.headerTitle}>{headerTitle}</Text>\n <TouchableOpacity\n testID=\"copilot-popup-close\"\n onPress={handleClose}\n hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}\n accessibilityLabel=\"Close chat\"\n accessibilityRole=\"button\"\n >\n <Text style={styles.closeButton}>✕</Text>\n </TouchableOpacity>\n </View>\n\n {/* Chat Content */}\n <View style={styles.chatContainer}>\n <CopilotChat\n agentId={agentId}\n agentName={agentName}\n threadId={threadId}\n throttleMs={throttleMs}\n onError={chatOnError}\n attachments={attachmentsConfig}\n >\n {children}\n </CopilotChat>\n </View>\n </Pressable>\n </Pressable>\n </Modal>\n </>\n );\n },\n);\n\nconst styles = StyleSheet.create({\n fab: {\n position: \"absolute\",\n bottom: 24,\n right: 24,\n width: 56,\n height: 56,\n borderRadius: 28,\n backgroundColor: \"#6366f1\",\n alignItems: \"center\",\n justifyContent: \"center\",\n elevation: 6,\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: 3 },\n shadowOpacity: 0.27,\n shadowRadius: 4.65,\n },\n fabIcon: {\n fontSize: 24,\n },\n backdrop: {\n flex: 1,\n backgroundColor: \"rgba(0, 0, 0, 0.4)\",\n justifyContent: \"flex-end\",\n },\n card: {\n backgroundColor: \"#ffffff\",\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n overflow: \"hidden\",\n elevation: 10,\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: -3 },\n shadowOpacity: 0.25,\n shadowRadius: 8,\n },\n header: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n paddingHorizontal: 16,\n paddingVertical: 12,\n borderBottomWidth: StyleSheet.hairlineWidth,\n borderBottomColor: \"#e5e7eb\",\n },\n headerTitle: {\n fontSize: 17,\n fontWeight: \"600\",\n color: \"#111827\",\n },\n closeButton: {\n fontSize: 18,\n color: \"#6b7280\",\n fontWeight: \"500\",\n },\n chatContainer: {\n flex: 1,\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA0FA,MAAM,8BAAc,IAAI,SAAkC;;;;;;;AAQ1D,SAAS,YAAY,MAAuB;CAC1C,MAAM,SAA2B;EAC/B,MAAM,KAAK;EACX,MAAM,KAAK;EACX,MAAM,KAAK;EACZ;AACD,aAAY,IAAI,QAAQ,KAAK;AAE7B,QAAO;;AAGT,SAAS,aAAa,MAAY;CAChC,MAAM,SAAS,YAAY,IAAI,KAAK;AACpC,KAAI,CAAC,OACH,OAAM,IAAI,MAAM,iBAAiB,KAAK,KAAK,2BAA2B;AAExE,QAAO;;;AAIT,eAAe,eAAe,MAAuB;AAInD,QAAO;EAAE,MAAM;EAAiB,OAHlB,MAAMA,iBAAW,kBAAkB,KAAK,KAAK,EACzD,UAAUA,iBAAW,aAAa,QACnC,CAAC;EACqC,UAAU,KAAK;EAAU;;;;;;AAOlE,SAAS,cACP,QAC+B;AAC/B,KAAI,CAAC,OAAQ,QAAO;CACpB,MAAM,EAAE,UAAU,gBAAgB,GAAG,SAAS;AAC9C,QAAO;EACL,GAAG;EACH,WAAW,SAAS;GAClB,MAAM,SAAS,aAAa,KAAK;AACjC,UAAO,WAAW,SAAS,OAAO,GAAG,eAAe,OAAO;;EAE7D,gBAAgB,kBACX,EAAE,MAAM,GAAG,YACV,eAAe;GAAE,GAAG;GAAO,MAAM,aAAa,KAAK;GAAE,CAAC,GACxD;EACL;;;;;;;;;;;AAgBH,SAAgB,eAAe,EAC7B,UACwD;CACxD,MAAM,UAAU,QAAQ,WAAW;CAGnC,MAAM,8BAAmB,OAAO;AAChC,WAAU,UAAU;CAEpB,MAAM,CAAC,mCACC,IAAIC,wCAAuB,cAAc,UAAU,QAAQ,CAAC,CACnE;CACD,MAAM,sEACS,aAAa,MAAM,UAAU,SAAS,EA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F,CAAC"}
package/dist/index.d.cts CHANGED
@@ -62,11 +62,12 @@ interface UseNativeAttachmentsReturn {
62
62
  }
63
63
  /**
64
64
  * React Native hook that manages file attachment state -- picking, uploading,
65
- * and lifecycle. All returned callbacks are referentially stable via useCallback.
65
+ * and lifecycle. All returned callbacks are referentially stable.
66
66
  *
67
- * This is the RN counterpart of the web `useAttachments` hook from
68
- * `@copilotkit/react-core`. It replaces web APIs (FileReader, DragEvent,
69
- * HTMLInputElement) with Expo modules (expo-document-picker, expo-file-system).
67
+ * The queue itself (accept filter, size check, uploads, ready state) is
68
+ * `@copilotkit/core`'s `ɵAttachmentQueue`, shared with the web chats. This
69
+ * hook adds the native glue: expo-document-picker to pick files and
70
+ * expo-file-system to read them.
70
71
  */
71
72
  declare function useAttachments({
72
73
  config
@@ -89,9 +90,10 @@ interface CopilotChatContextValue {
89
90
  /** Remove an attachment by ID. */
90
91
  removeAttachment: (id: string) => void;
91
92
  /**
92
- * Submit a message with optional attachments.
93
- * Handles consuming ready attachments, building InputContent[],
94
- * calling agent.addMessage, and running the agent.
93
+ * Submit a message with the ready attachments and run the agent. Waits
94
+ * for the thread's connection and for the run in flight. Blank text, and a
95
+ * send while an attachment uploads, are ignored. Resolves once the run has
96
+ * settled.
95
97
  */
96
98
  submitMessage: (text: string) => Promise<void>;
97
99
  }
@@ -115,8 +117,10 @@ interface CopilotChatBaseProps {
115
117
  */
116
118
  agentName?: string;
117
119
  /**
118
- * Thread ID for this chat session. When provided, the chat will resume
119
- * the specified thread. Matches the web SDK's CopilotChat `threadId` prop.
120
+ * Thread ID for this chat session. When provided, the chat restores the
121
+ * thread from the backend and reconnects to a run in progress. Without it,
122
+ * the chat uses the thread of the chat around it, or a new thread. Matches
123
+ * the web SDK's CopilotChat `threadId` prop.
120
124
  */
121
125
  threadId?: string;
122
126
  /**