@copilotkit/react-native 2.0.0-rc.3 → 2.0.0-rc.30

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.
Files changed (84) hide show
  1. package/dist/{CopilotKitProvider-CE4bc6CP.mjs → CopilotKitProvider-BXpkAl1Y.mjs} +55 -42
  2. package/dist/CopilotKitProvider-BXpkAl1Y.mjs.map +1 -0
  3. package/dist/{CopilotKitProvider-Byw3cqe2.cjs → CopilotKitProvider-DDPbJkHS.cjs} +53 -40
  4. package/dist/CopilotKitProvider-DDPbJkHS.cjs.map +1 -0
  5. package/dist/CopilotKitProvider-F7Pn5kp4.d.cts +65 -0
  6. package/dist/CopilotKitProvider-Khgz5dQo.d.mts +65 -0
  7. package/dist/{Markdown-C_9Re36O.cjs → Markdown-CaYHlD4j.cjs} +8 -8
  8. package/dist/Markdown-CaYHlD4j.cjs.map +1 -0
  9. package/dist/{Markdown-1ips7myr.d.cts → Markdown-DzjnSuu5.d.cts} +3 -3
  10. package/dist/{Markdown-C6AsLHmd.mjs → Markdown-SE9MfY2U.mjs} +4 -4
  11. package/dist/Markdown-SE9MfY2U.mjs.map +1 -0
  12. package/dist/{Markdown-JsYh7oSA.d.mts → Markdown-a-rdG22_.d.mts} +3 -3
  13. package/dist/{MarkdownRendererContext-CAnuohIS.mjs → MarkdownRendererContext-B_AKdPAN.mjs} +1 -1
  14. package/dist/{MarkdownRendererContext-CAnuohIS.mjs.map → MarkdownRendererContext-B_AKdPAN.mjs.map} +1 -1
  15. package/dist/components/index.cjs +73 -172
  16. package/dist/components/index.cjs.map +1 -1
  17. package/dist/components/index.d.cts +2 -2
  18. package/dist/components/index.d.mts +2 -2
  19. package/dist/components/index.mjs +75 -174
  20. package/dist/components/index.mjs.map +1 -1
  21. package/dist/headless.cjs +2 -1
  22. package/dist/headless.d.cts +2 -2
  23. package/dist/headless.d.mts +2 -2
  24. package/dist/headless.mjs +2 -1
  25. package/dist/index.cjs +126 -158
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.d.cts +35 -17
  28. package/dist/index.d.mts +36 -18
  29. package/dist/index.mjs +130 -161
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/polyfills/encoding.cjs +5 -5
  32. package/dist/polyfills/encoding.cjs.map +1 -1
  33. package/dist/polyfills/encoding.mjs +5 -4
  34. package/dist/polyfills/encoding.mjs.map +1 -1
  35. package/dist/polyfills.cjs +2 -1
  36. package/dist/polyfills.cjs.map +1 -1
  37. package/dist/polyfills.mjs +2 -1
  38. package/dist/polyfills.mjs.map +1 -1
  39. package/dist/{streaming-fetch-Dm1oN4f2.mjs → streaming-fetch-CLHG3Z1H.mjs} +1 -1
  40. package/dist/{streaming-fetch-Dm1oN4f2.mjs.map → streaming-fetch-CLHG3Z1H.mjs.map} +1 -1
  41. package/dist/{streaming-fetch-Bm91EsRc.cjs → streaming-fetch-DbDALGya.cjs} +1 -1
  42. package/dist/{streaming-fetch-Bm91EsRc.cjs.map → streaming-fetch-DbDALGya.cjs.map} +1 -1
  43. package/dist/utf8-BIN9t4Oy.mjs +113 -0
  44. package/dist/utf8-BIN9t4Oy.mjs.map +1 -0
  45. package/dist/utf8-Cf3Ssy33.cjs +125 -0
  46. package/dist/utf8-Cf3Ssy33.cjs.map +1 -0
  47. package/package.json +12 -21
  48. package/scripts/verify-polyfill-barrel.mjs +4 -6
  49. package/src/CopilotChat.tsx +114 -93
  50. package/src/CopilotKitProvider.tsx +87 -130
  51. package/src/CopilotPopup.tsx +2 -2
  52. package/src/CopilotSidebar.tsx +7 -5
  53. package/src/__mocks__/react-native.ts +31 -0
  54. package/src/__mocks__/test-copilotkit.tsx +9 -3
  55. package/src/__tests__/attachments-integration.test.tsx +15 -2
  56. package/src/__tests__/copilot-chat-agentid.test.tsx +15 -2
  57. package/src/__tests__/copilot-chat-attachments.test.tsx +15 -2
  58. package/src/__tests__/copilot-chat-configuration.test.tsx +82 -0
  59. package/src/__tests__/copilot-chat-threads.test.tsx +232 -0
  60. package/src/__tests__/copilot-popup.test.tsx +15 -2
  61. package/src/__tests__/copilot-sidebar.test.tsx +15 -2
  62. package/src/__tests__/copilotkit-provider.test.tsx +68 -73
  63. package/src/__tests__/headless-integration.test.tsx +11 -1
  64. package/src/__tests__/use-attachments.test.ts +27 -2
  65. package/src/components/CopilotChat.tsx +106 -233
  66. package/src/components/CopilotModal.tsx +1 -1
  67. package/src/components/Markdown.tsx +4 -4
  68. package/src/components/__tests__/CopilotChat-edge-cases.test.tsx +5 -1
  69. package/src/components/__tests__/CopilotChat.test.tsx +12 -4
  70. package/src/components/__tests__/CopilotChatInterrupt.test.tsx +208 -0
  71. package/src/components/__tests__/Markdown.code-alias.test.tsx +1 -1
  72. package/src/components/messages/AssistantMessage.tsx +3 -3
  73. package/src/components/messages/TypingIndicator.tsx +4 -4
  74. package/src/hooks/use-attachments.ts +95 -139
  75. package/src/polyfills/__tests__/utf8.test.ts +112 -0
  76. package/src/polyfills/encoding.ts +5 -4
  77. package/src/polyfills/utf8.ts +151 -0
  78. package/src/types.d.ts +0 -13
  79. package/dist/CopilotKitProvider-BWjzCdHN.d.mts +0 -121
  80. package/dist/CopilotKitProvider-Btm10msB.d.cts +0 -121
  81. package/dist/CopilotKitProvider-Byw3cqe2.cjs.map +0 -1
  82. package/dist/CopilotKitProvider-CE4bc6CP.mjs.map +0 -1
  83. package/dist/Markdown-C6AsLHmd.mjs.map +0 -1
  84. package/dist/Markdown-C_9Re36O.cjs.map +0 -1
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { i as defaultMarkdownStyles, n as CopilotMarkdownProps, r as MarkdownStyle, t as CopilotMarkdown } from "./Markdown-1ips7myr.cjs";
2
- import { a as NativeMarkdownRendererProps, i as NativeMarkdownRenderer, n as CopilotKitProvider, o as useMarkdownRenderer, r as MarkdownRendererProvider, t as CopilotKitNativeProviderProps } from "./CopilotKitProvider-Btm10msB.cjs";
1
+ import { i as defaultMarkdownStyles, n as CopilotMarkdownProps, r as MarkdownStyle, t as CopilotMarkdown } from "./Markdown-DzjnSuu5.cjs";
2
+ import { a as NativeMarkdownRendererProps, i as NativeMarkdownRenderer, n as CopilotKitProvider, o as useMarkdownRenderer, r as MarkdownRendererProvider, t as CopilotKitNativeProviderProps } from "./CopilotKitProvider-F7Pn5kp4.cjs";
3
3
  import { AbstractAgent, AgentCapabilities, AgentContextInput, AssistantMessageType, CopilotChatConfigurationValue, CopilotChatDefaultLabels, CopilotChatLabels, CopilotKitContext, CopilotKitContextValue, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, FrontendTool, FrontendToolRenderFunction, Interrupt, InterruptEvent, InterruptHandlerProps, InterruptRenderProps, JsonSerializable, Message, ReactFrontendTool, ReactHumanInTheLoop, ReactToolCallRenderer, RenderToolCompleteProps, RenderToolExecutingProps, RenderToolInProgressProps, RenderToolProps, ResumeEntry, ResumeStatus, Suggestion, Thread, ToolCall, ToolCallStatus, ToolMessage, UseAgentUpdate, UseInterruptConfig, UseThreadsInput, UseThreadsResult, defineToolCallRenderer, useAgent, useAgentContext, useCapabilities, useComponent, useConfigureSuggestions, useCopilotKit, useFrontendTool, useHumanInTheLoop, useInterrupt, useLicenseContext, useRenderTool, useRenderToolCall, useSuggestions, useThreads } from "./headless.cjs";
4
4
  import * as react_jsx_runtime0 from "react/jsx-runtime";
5
5
  import React, { ReactNode } from "react";
@@ -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
  }
@@ -105,7 +107,8 @@ interface CopilotChatBaseProps {
105
107
  * The agent ID to use for this chat session.
106
108
  * Matches the web SDK's CopilotChat `agentId` prop.
107
109
  *
108
- * Resolution order: `agentId` > `agentName` > `"default"`
110
+ * Resolution order: `agentId` > `agentName` > the agent of the chat (or
111
+ * `CopilotChatConfigurationProvider`) around this one > `"default"`
109
112
  */
110
113
  agentId?: string;
111
114
  /**
@@ -114,14 +117,16 @@ interface CopilotChatBaseProps {
114
117
  */
115
118
  agentName?: string;
116
119
  /**
117
- * Thread ID for this chat session. When provided, the chat will resume
118
- * 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.
119
124
  */
120
125
  threadId?: string;
121
126
  /**
122
127
  * Error handler scoped to this chat's agent. Fires in addition to the
123
- * provider-level onError (does not suppress it). Receives only errors
124
- * whose context.agentId matches this chat's agent.
128
+ * provider-level onError (does not suppress it). Receives errors whose
129
+ * context.agentId matches this chat's agent, and errors with no agentId.
125
130
  */
126
131
  onError?: (event: {
127
132
  error: Error;
@@ -160,6 +165,16 @@ interface CopilotChatProps extends CopilotChatBaseProps {
160
165
  *
161
166
  * Children can access chat state via `useCopilotChatContext()`.
162
167
  *
168
+ * Hooks inside the chat, such as `useAgent` and `useInterrupt`, use this
169
+ * chat's agent when they do not pass an `agentId`. When the chat has a
170
+ * `threadId`, `useAgent` inside the chat sets that thread on each agent it
171
+ * returns, also on an agent that the hook names with its own `agentId`. Only
172
+ * `useAgent({ agentId, runtimeAgentId, threadId })` keeps a different thread.
173
+ *
174
+ * A chat inside another chat uses the outer chat's agent when it has no
175
+ * `agentId`. When the outer chat has a `threadId` and the inner chat does not,
176
+ * the inner chat uses the outer thread. The web `CopilotChat` does the same.
177
+ *
163
178
  * ```tsx
164
179
  * import { CopilotChat, useCopilotChatContext } from "@copilotkit/react-native";
165
180
  *
@@ -251,7 +266,10 @@ interface CopilotSidebarProps extends Omit<CopilotChatBaseProps, "children"> {
251
266
  onClose?: () => void;
252
267
  /** Custom style applied to the drawer container. */
253
268
  style?: ViewStyle;
254
- /** Content rendered inside the drawer below the chat area. */
269
+ /**
270
+ * Your chat UI, rendered inside the drawer below the header. The inner
271
+ * CopilotChat is headless and draws no messages or input of its own.
272
+ */
255
273
  children?: ReactNode;
256
274
  }
257
275
  /**
@@ -318,8 +336,8 @@ interface CopilotPopupProps {
318
336
  */
319
337
  attachments?: NativeAttachmentsConfig;
320
338
  /**
321
- * Optional children rendered below the CopilotChat content
322
- * inside the popup card.
339
+ * Your chat UI, rendered inside the popup card below the header. The inner
340
+ * CopilotChat is headless and draws no messages or input of its own.
323
341
  */
324
342
  children?: ReactNode;
325
343
  /**
package/dist/index.d.mts CHANGED
@@ -1,10 +1,10 @@
1
- import { i as defaultMarkdownStyles, n as CopilotMarkdownProps, r as MarkdownStyle, t as CopilotMarkdown } from "./Markdown-JsYh7oSA.mjs";
2
- import { a as NativeMarkdownRendererProps, i as NativeMarkdownRenderer, n as CopilotKitProvider, o as useMarkdownRenderer, r as MarkdownRendererProvider, t as CopilotKitNativeProviderProps } from "./CopilotKitProvider-BWjzCdHN.mjs";
1
+ import { i as defaultMarkdownStyles, n as CopilotMarkdownProps, r as MarkdownStyle, t as CopilotMarkdown } from "./Markdown-a-rdG22_.mjs";
2
+ import { a as NativeMarkdownRendererProps, i as NativeMarkdownRenderer, n as CopilotKitProvider, o as useMarkdownRenderer, r as MarkdownRendererProvider, t as CopilotKitNativeProviderProps } from "./CopilotKitProvider-Khgz5dQo.mjs";
3
3
  import { AbstractAgent, AgentCapabilities, AgentContextInput, AssistantMessageType, CopilotChatConfigurationValue, CopilotChatDefaultLabels, CopilotChatLabels, CopilotKitContext, CopilotKitContextValue, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, FrontendTool, FrontendToolRenderFunction, Interrupt, InterruptEvent, InterruptHandlerProps, InterruptRenderProps, JsonSerializable, Message, ReactFrontendTool, ReactHumanInTheLoop, ReactToolCallRenderer, RenderToolCompleteProps, RenderToolExecutingProps, RenderToolInProgressProps, RenderToolProps, ResumeEntry, ResumeStatus, Suggestion, Thread, ToolCall, ToolCallStatus, ToolMessage, UseAgentUpdate, UseInterruptConfig, UseThreadsInput, UseThreadsResult, defineToolCallRenderer, useAgent, useAgentContext, useCapabilities, useComponent, useConfigureSuggestions, useCopilotKit, useFrontendTool, useHumanInTheLoop, useInterrupt, useLicenseContext, useRenderTool, useRenderToolCall, useSuggestions, useThreads } from "./headless.mjs";
4
4
  import React, { ReactNode } from "react";
5
+ import { CopilotKitCoreErrorCode as CopilotKitCoreErrorCode$1 } from "@copilotkit/core";
5
6
  import { Attachment, AttachmentUploadErrorReason, AttachmentUploadResult } from "@copilotkit/shared";
6
7
  import * as react_jsx_runtime0 from "react/jsx-runtime";
7
- import { CopilotKitCoreErrorCode as CopilotKitCoreErrorCode$1 } from "@copilotkit/core";
8
8
  import { ViewStyle } from "react-native";
9
9
 
10
10
  //#region src/hooks/use-attachments.d.ts
@@ -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
  }
@@ -105,7 +107,8 @@ interface CopilotChatBaseProps {
105
107
  * The agent ID to use for this chat session.
106
108
  * Matches the web SDK's CopilotChat `agentId` prop.
107
109
  *
108
- * Resolution order: `agentId` > `agentName` > `"default"`
110
+ * Resolution order: `agentId` > `agentName` > the agent of the chat (or
111
+ * `CopilotChatConfigurationProvider`) around this one > `"default"`
109
112
  */
110
113
  agentId?: string;
111
114
  /**
@@ -114,14 +117,16 @@ interface CopilotChatBaseProps {
114
117
  */
115
118
  agentName?: string;
116
119
  /**
117
- * Thread ID for this chat session. When provided, the chat will resume
118
- * 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.
119
124
  */
120
125
  threadId?: string;
121
126
  /**
122
127
  * Error handler scoped to this chat's agent. Fires in addition to the
123
- * provider-level onError (does not suppress it). Receives only errors
124
- * whose context.agentId matches this chat's agent.
128
+ * provider-level onError (does not suppress it). Receives errors whose
129
+ * context.agentId matches this chat's agent, and errors with no agentId.
125
130
  */
126
131
  onError?: (event: {
127
132
  error: Error;
@@ -160,6 +165,16 @@ interface CopilotChatProps extends CopilotChatBaseProps {
160
165
  *
161
166
  * Children can access chat state via `useCopilotChatContext()`.
162
167
  *
168
+ * Hooks inside the chat, such as `useAgent` and `useInterrupt`, use this
169
+ * chat's agent when they do not pass an `agentId`. When the chat has a
170
+ * `threadId`, `useAgent` inside the chat sets that thread on each agent it
171
+ * returns, also on an agent that the hook names with its own `agentId`. Only
172
+ * `useAgent({ agentId, runtimeAgentId, threadId })` keeps a different thread.
173
+ *
174
+ * A chat inside another chat uses the outer chat's agent when it has no
175
+ * `agentId`. When the outer chat has a `threadId` and the inner chat does not,
176
+ * the inner chat uses the outer thread. The web `CopilotChat` does the same.
177
+ *
163
178
  * ```tsx
164
179
  * import { CopilotChat, useCopilotChatContext } from "@copilotkit/react-native";
165
180
  *
@@ -251,7 +266,10 @@ interface CopilotSidebarProps extends Omit<CopilotChatBaseProps, "children"> {
251
266
  onClose?: () => void;
252
267
  /** Custom style applied to the drawer container. */
253
268
  style?: ViewStyle;
254
- /** Content rendered inside the drawer below the chat area. */
269
+ /**
270
+ * Your chat UI, rendered inside the drawer below the header. The inner
271
+ * CopilotChat is headless and draws no messages or input of its own.
272
+ */
255
273
  children?: ReactNode;
256
274
  }
257
275
  /**
@@ -318,8 +336,8 @@ interface CopilotPopupProps {
318
336
  */
319
337
  attachments?: NativeAttachmentsConfig;
320
338
  /**
321
- * Optional children rendered below the CopilotChat content
322
- * inside the popup card.
339
+ * Your chat UI, rendered inside the popup card below the header. The inner
340
+ * CopilotChat is headless and draws no messages or input of its own.
323
341
  */
324
342
  children?: ReactNode;
325
343
  /**
package/dist/index.mjs CHANGED
@@ -1,113 +1,83 @@
1
- import { r as useMarkdownRenderer, t as MarkdownRendererProvider } from "./MarkdownRendererContext-CAnuohIS.mjs";
2
- import { t as CopilotKitProvider } from "./CopilotKitProvider-CE4bc6CP.mjs";
1
+ import "./utf8-BIN9t4Oy.mjs";
2
+ import { r as useMarkdownRenderer, t as MarkdownRendererProvider } from "./MarkdownRendererContext-B_AKdPAN.mjs";
3
+ import { t as CopilotKitProvider } from "./CopilotKitProvider-BXpkAl1Y.mjs";
3
4
  import { AbstractAgent, CopilotChatDefaultLabels, CopilotKitContext, CopilotKitCoreErrorCode, CopilotKitCoreRuntimeConnectionStatus, ToolCallStatus, UseAgentUpdate, defineToolCallRenderer, useAgent, useAgentContext, useCapabilities, useComponent, useConfigureSuggestions, useCopilotKit, useFrontendTool, useHumanInTheLoop, useInterrupt, useLicenseContext, useRenderTool, useRenderToolCall, useSuggestions, useThreads } from "./headless.mjs";
4
- import { n as defaultMarkdownStyles, t as CopilotMarkdown } from "./Markdown-C6AsLHmd.mjs";
5
- import React, { createContext, forwardRef, useCallback, useContext, useEffect, useImperativeHandle, useRef, useState } from "react";
5
+ import { n as defaultMarkdownStyles, t as CopilotMarkdown } from "./Markdown-SE9MfY2U.mjs";
6
+ import React, { createContext, forwardRef, useCallback, useContext, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
6
7
  import { useCopilotKit as useCopilotKit$1 } from "@copilotkit/react-core/context";
7
- import { useAgent as useAgent$1 } from "@copilotkit/react-core/headless";
8
- import { DEFAULT_AGENT_ID, formatFileSize, getModalityFromMimeType, randomUUID } from "@copilotkit/shared";
8
+ import { CopilotChatConfigurationProvider, useAgent as useAgent$1, useCopilotChatConfiguration } from "@copilotkit/react-core/headless";
9
+ import { ɵAttachmentQueue, ɵChatConnection, ɵFreshThreadId, ɵcreateChatSubmitter, ɵsubscribeToAgentErrors } from "@copilotkit/core";
10
+ import { DEFAULT_AGENT_ID } from "@copilotkit/shared";
9
11
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
10
12
  import * as DocumentPicker from "expo-document-picker";
11
13
  import * as FileSystem from "expo-file-system";
12
14
  import { Animated, Modal, Pressable, StyleSheet, Text, TouchableOpacity, View, useWindowDimensions } from "react-native";
13
15
 
14
16
  //#region src/hooks/use-attachments.ts
15
- const DEFAULT_MAX_SIZE = 20 * 1024 * 1024;
17
+ const nativeFiles = /* @__PURE__ */ new WeakMap();
18
+ /**
19
+ * Wraps a native file for core's `ɵAttachmentQueue`, which is typed for the
20
+ * web `File`. The queue reads only `name`, `size` and `type`, because the
21
+ * config from {@link toQueueConfig} always uploads through `onUpload` and the
22
+ * queue never reads the bytes itself.
23
+ */
24
+ function toQueueFile(file) {
25
+ const queued = {
26
+ name: file.name,
27
+ size: file.size,
28
+ type: file.mimeType
29
+ };
30
+ nativeFiles.set(queued, file);
31
+ return queued;
32
+ }
33
+ function toNativeFile(file) {
34
+ const native = nativeFiles.get(file);
35
+ if (!native) throw new Error(`[CopilotKit] "${file.name}" was not picked natively`);
36
+ return native;
37
+ }
38
+ /** Reads a picked file as base64 with expo-file-system. */
39
+ async function readNativeFile(file) {
40
+ return {
41
+ type: "data",
42
+ value: await FileSystem.readAsStringAsync(file.uri, { encoding: FileSystem.EncodingType.Base64 }),
43
+ mimeType: file.mimeType
44
+ };
45
+ }
46
+ /**
47
+ * The RN config as core's queue takes it. Uploads go through the app's
48
+ * `onUpload`, or through expo-file-system when there is none.
49
+ */
50
+ function toQueueConfig(config) {
51
+ if (!config) return void 0;
52
+ const { onUpload, onUploadFailed, ...rest } = config;
53
+ return {
54
+ ...rest,
55
+ onUpload: (file) => {
56
+ const native = toNativeFile(file);
57
+ return onUpload ? onUpload(native) : readNativeFile(native);
58
+ },
59
+ onUploadFailed: onUploadFailed ? ({ file, ...error }) => onUploadFailed({
60
+ ...error,
61
+ file: toNativeFile(file)
62
+ }) : void 0
63
+ };
64
+ }
16
65
  /**
17
66
  * React Native hook that manages file attachment state -- picking, uploading,
18
- * and lifecycle. All returned callbacks are referentially stable via useCallback.
67
+ * and lifecycle. All returned callbacks are referentially stable.
19
68
  *
20
- * This is the RN counterpart of the web `useAttachments` hook from
21
- * `@copilotkit/react-core`. It replaces web APIs (FileReader, DragEvent,
22
- * HTMLInputElement) with Expo modules (expo-document-picker, expo-file-system).
69
+ * The queue itself (accept filter, size check, uploads, ready state) is
70
+ * `@copilotkit/core`'s `ɵAttachmentQueue`, shared with the web chats. This
71
+ * hook adds the native glue: expo-document-picker to pick files and
72
+ * expo-file-system to read them.
23
73
  */
24
74
  function useAttachments({ config }) {
25
75
  const enabled = config?.enabled ?? false;
26
- const [attachments, setAttachments] = useState([]);
27
76
  const configRef = useRef(config);
28
77
  configRef.current = config;
29
- const attachmentsRef = useRef([]);
30
- attachmentsRef.current = attachments;
31
- /**
32
- * Simple MIME accept filter for NativeFileInput.
33
- * Handles wildcards like "image/*" and exact types like "application/pdf".
34
- * Comma-separated lists are supported.
35
- */
36
- const matchesAccept = useCallback((file, accept) => {
37
- if (!accept || accept === "*/*") return true;
38
- return accept.split(",").map((f) => f.trim()).some((filter) => {
39
- if (filter.startsWith(".")) return file.name.toLowerCase().endsWith(filter.toLowerCase());
40
- if (filter.endsWith("/*")) {
41
- const prefix = filter.slice(0, -2);
42
- return file.mimeType.startsWith(prefix + "/");
43
- }
44
- return file.mimeType === filter;
45
- });
46
- }, []);
47
- const processFiles = useCallback(async (files) => {
48
- const cfg = configRef.current;
49
- const accept = cfg?.accept ?? "*/*";
50
- const maxSize = cfg?.maxSize ?? DEFAULT_MAX_SIZE;
51
- const rejectedFiles = files.filter((f) => !matchesAccept(f, accept));
52
- for (const file of rejectedFiles) cfg?.onUploadFailed?.({
53
- reason: "invalid-type",
54
- file,
55
- message: `File "${file.name}" is not accepted. Supported types: ${accept}`
56
- });
57
- const validFiles = files.filter((f) => matchesAccept(f, accept));
58
- for (const file of validFiles) {
59
- if (file.size > maxSize) {
60
- cfg?.onUploadFailed?.({
61
- reason: "file-too-large",
62
- file,
63
- message: `File "${file.name}" exceeds the maximum size of ${formatFileSize(maxSize)}`
64
- });
65
- continue;
66
- }
67
- const modality = getModalityFromMimeType(file.mimeType);
68
- const placeholderId = randomUUID();
69
- const placeholder = {
70
- id: placeholderId,
71
- type: modality,
72
- source: {
73
- type: "data",
74
- value: "",
75
- mimeType: file.mimeType
76
- },
77
- filename: file.name,
78
- size: file.size,
79
- status: "uploading"
80
- };
81
- setAttachments((prev) => [...prev, placeholder]);
82
- try {
83
- let source;
84
- let uploadMetadata;
85
- if (cfg?.onUpload) {
86
- const { metadata: meta, ...uploadSource } = await cfg.onUpload(file);
87
- source = uploadSource;
88
- uploadMetadata = meta;
89
- } else source = {
90
- type: "data",
91
- value: await FileSystem.readAsStringAsync(file.uri, { encoding: FileSystem.EncodingType.Base64 }),
92
- mimeType: file.mimeType
93
- };
94
- setAttachments((prev) => prev.map((att) => att.id === placeholderId ? {
95
- ...att,
96
- source,
97
- status: "ready",
98
- metadata: uploadMetadata
99
- } : att));
100
- } catch (error) {
101
- setAttachments((prev) => prev.filter((att) => att.id !== placeholderId));
102
- console.error(`[CopilotKit] Failed to upload "${file.name}":`, error);
103
- cfg?.onUploadFailed?.({
104
- reason: "upload-failed",
105
- file,
106
- message: error instanceof Error ? error.message : `Failed to upload "${file.name}"`
107
- });
108
- }
109
- }
110
- }, [matchesAccept]);
78
+ const [queue] = useState(() => new ɵAttachmentQueue(() => toQueueConfig(configRef.current)));
79
+ const attachments = useSyncExternalStore(useCallback((onChange) => queue.subscribe(onChange), [queue]), () => queue.getSnapshot(), () => queue.getSnapshot());
80
+ const processFiles = useCallback((files) => queue.processFiles(files.map(toQueueFile)), [queue]);
111
81
  return {
112
82
  attachments,
113
83
  enabled,
@@ -131,15 +101,8 @@ function useAttachments({ config }) {
131
101
  }
132
102
  }, [processFiles]),
133
103
  processFiles,
134
- removeAttachment: useCallback((id) => {
135
- setAttachments((prev) => prev.filter((a) => a.id !== id));
136
- }, []),
137
- consumeAttachments: useCallback(() => {
138
- const ready = attachmentsRef.current.filter((a) => a.status === "ready");
139
- if (ready.length === 0) return ready;
140
- setAttachments((prev) => prev.filter((a) => a.status !== "ready"));
141
- return ready;
142
- }, [])
104
+ removeAttachment: useCallback((id) => queue.remove(id), [queue]),
105
+ consumeAttachments: useCallback(() => queue.consumeReady(), [queue])
143
106
  };
144
107
  }
145
108
 
@@ -164,6 +127,16 @@ function useCopilotChatContext() {
164
127
  *
165
128
  * Children can access chat state via `useCopilotChatContext()`.
166
129
  *
130
+ * Hooks inside the chat, such as `useAgent` and `useInterrupt`, use this
131
+ * chat's agent when they do not pass an `agentId`. When the chat has a
132
+ * `threadId`, `useAgent` inside the chat sets that thread on each agent it
133
+ * returns, also on an agent that the hook names with its own `agentId`. Only
134
+ * `useAgent({ agentId, runtimeAgentId, threadId })` keeps a different thread.
135
+ *
136
+ * A chat inside another chat uses the outer chat's agent when it has no
137
+ * `agentId`. When the outer chat has a `threadId` and the inner chat does not,
138
+ * the inner chat uses the outer thread. The web `CopilotChat` does the same.
139
+ *
167
140
  * ```tsx
168
141
  * import { CopilotChat, useCopilotChatContext } from "@copilotkit/react-native";
169
142
  *
@@ -178,7 +151,8 @@ function useCopilotChatContext() {
178
151
  * ```
179
152
  */
180
153
  function CopilotChat({ agentId, agentName, threadId, onError, throttleMs, attachments: attachmentsConfig, children, ..._rest }) {
181
- const resolvedAgentId = agentId ?? agentName ?? DEFAULT_AGENT_ID;
154
+ const chatConfig = useCopilotChatConfiguration();
155
+ const resolvedAgentId = agentId ?? agentName ?? chatConfig?.agentId ?? DEFAULT_AGENT_ID;
182
156
  const warnedRef = useRef(false);
183
157
  useEffect(() => {
184
158
  if (agentName !== void 0 && agentId === void 0 && !warnedRef.current) {
@@ -186,72 +160,62 @@ function CopilotChat({ agentId, agentName, threadId, onError, throttleMs, attach
186
160
  if (typeof __DEV__ === "undefined" || __DEV__) console.warn("[CopilotKit] agentName is deprecated, use agentId instead");
187
161
  }
188
162
  }, [agentName, agentId]);
163
+ const providedThreadId = threadId ?? chatConfig?.threadId;
164
+ const [freshThreadId] = useState(() => new ɵFreshThreadId());
165
+ const resolvedThreadId = useMemo(() => freshThreadId.resolve(providedThreadId), [freshThreadId, providedThreadId]);
166
+ const hasExplicitThreadId = !!threadId || !!chatConfig?.hasExplicitThreadId;
189
167
  const { agent } = useAgent$1({
190
168
  agentId: resolvedAgentId,
191
169
  throttleMs
192
170
  });
193
- useEffect(() => {
194
- if (threadId) agent.threadId = threadId;
195
- }, [agent, threadId]);
196
171
  const { copilotkit } = useCopilotKit$1();
172
+ const [connection] = useState(() => new ɵChatConnection({ core: copilotkit }));
173
+ const { threads } = connection;
174
+ useEffect(() => {
175
+ const handle = connection.open({
176
+ agent,
177
+ threadId: resolvedThreadId,
178
+ explicit: hasExplicitThreadId
179
+ });
180
+ return () => handle.release();
181
+ }, [
182
+ connection,
183
+ agent,
184
+ resolvedThreadId,
185
+ hasExplicitThreadId
186
+ ]);
197
187
  const onErrorRef = useRef(onError);
198
188
  useEffect(() => {
199
189
  onErrorRef.current = onError;
200
190
  }, [onError]);
201
191
  useEffect(() => {
202
192
  if (!onErrorRef.current) return;
203
- const subscription = copilotkit.subscribe({ onError: (event) => {
204
- if (event.context?.agentId === resolvedAgentId || !event.context?.agentId) onErrorRef.current?.({
205
- error: event.error,
206
- code: event.code,
207
- context: event.context
208
- });
209
- } });
210
- return () => {
211
- subscription.unsubscribe();
212
- };
193
+ return ɵsubscribeToAgentErrors(copilotkit, resolvedAgentId, (event) => onErrorRef.current?.(event));
213
194
  }, [copilotkit, resolvedAgentId]);
214
195
  const { attachments: selectedAttachments, enabled: attachmentsEnabled, openPicker, removeAttachment, consumeAttachments } = useAttachments({ config: attachmentsConfig });
215
- const submitMessage = useCallback(async (value) => {
216
- if (selectedAttachments.some((a) => a.status === "uploading")) {
217
- console.error("[CopilotKit] Cannot send while attachments are uploading");
218
- return;
219
- }
220
- const readyAttachments = consumeAttachments();
221
- if (readyAttachments.length > 0) {
222
- const contentParts = [];
223
- if (value.trim()) contentParts.push({
224
- type: "text",
225
- text: value
226
- });
227
- for (const att of readyAttachments) contentParts.push({
228
- type: att.type,
229
- source: att.source,
230
- metadata: {
231
- ...att.filename ? { filename: att.filename } : {},
232
- ...att.metadata
233
- }
234
- });
235
- agent.addMessage({
236
- id: randomUUID(),
237
- role: "user",
238
- content: contentParts
239
- });
240
- } else agent.addMessage({
241
- id: randomUUID(),
242
- role: "user",
243
- content: value
244
- });
245
- try {
246
- await copilotkit.runAgent({ agent });
247
- } catch (error) {
248
- console.error("CopilotChat: runAgent failed", error);
249
- }
250
- }, [
251
- agent,
252
- selectedAttachments,
253
- consumeAttachments
254
- ]);
196
+ const attachmentsRef = useRef(selectedAttachments);
197
+ useLayoutEffect(() => {
198
+ attachmentsRef.current = selectedAttachments;
199
+ });
200
+ const agentRef = useRef(agent);
201
+ useLayoutEffect(() => {
202
+ agentRef.current = agent;
203
+ });
204
+ const [submitter] = useState(() => ɵcreateChatSubmitter({
205
+ core: copilotkit,
206
+ getAgent: () => agentRef.current,
207
+ input: {
208
+ get: () => "",
209
+ set: () => {}
210
+ },
211
+ attachments: {
212
+ isUploading: () => attachmentsRef.current.some((a) => a.status === "uploading"),
213
+ consumeReady: () => consumeAttachments()
214
+ },
215
+ threads
216
+ }));
217
+ useEffect(() => () => submitter.showNotice(null), [submitter]);
218
+ const submitMessage = useCallback((value) => submitter.submit(value), [submitter]);
255
219
  const contextValue = {
256
220
  agent,
257
221
  isRunning: agent.isRunning,
@@ -262,9 +226,14 @@ function CopilotChat({ agentId, agentName, threadId, onError, throttleMs, attach
262
226
  removeAttachment,
263
227
  submitMessage
264
228
  };
265
- return /* @__PURE__ */ jsx(CopilotChatCtx.Provider, {
266
- value: contextValue,
267
- children
229
+ return /* @__PURE__ */ jsx(CopilotChatConfigurationProvider, {
230
+ agentId: resolvedAgentId,
231
+ threadId: resolvedThreadId,
232
+ hasExplicitThreadId,
233
+ children: /* @__PURE__ */ jsx(CopilotChatCtx.Provider, {
234
+ value: contextValue,
235
+ children
236
+ })
268
237
  });
269
238
  }
270
239
 
@@ -323,7 +292,7 @@ const CopilotSidebar = forwardRef(function CopilotSidebar({ agentId, agentName,
323
292
  const { width: screenWidth } = useWindowDimensions();
324
293
  const drawerWidth = resolveWidth(widthProp, screenWidth);
325
294
  const [isOpen, setIsOpen] = useState(defaultOpen);
326
- const slideAnim = useRef(new Animated.Value(defaultOpen ? 0 : drawerWidth)).current;
295
+ const [slideAnim] = useState(() => new Animated.Value(defaultOpen ? 0 : drawerWidth));
327
296
  useEffect(() => {
328
297
  if (!isOpen) slideAnim.setValue(drawerWidth);
329
298
  }, [