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

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
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Thread restore and thread switching in the headless `<CopilotChat>`. Runs on
3
+ * a REAL `CopilotKitCoreReact` (via `TestCopilotKit`), so the connect, the
4
+ * reset on a switch to a fresh thread, and the send queue are core's
5
+ * `ɵThreadSwitchCoordinator` and `ɵChatSubmitter`, as in the web chats.
6
+ */
7
+ import React from "react";
8
+ import { act, render, screen, waitFor } from "@testing-library/react";
9
+ import { describe, expect, it, vi } from "vitest";
10
+ import type { Message, RunAgentResult } from "@ag-ui/client";
11
+ import { CopilotChat, useCopilotChatContext } from "../CopilotChat";
12
+ import { SeededAgent, TestCopilotKit } from "../__mocks__/test-copilotkit";
13
+ import type { CopilotChatContextValue } from "../CopilotChat";
14
+
15
+ const EMPTY_RESULT: RunAgentResult = { result: undefined, newMessages: [] };
16
+
17
+ const text = (id: string, content: string): Message => ({
18
+ id,
19
+ role: "assistant",
20
+ content,
21
+ });
22
+
23
+ /**
24
+ * An agent with stored threads. `connectAgent` restores the history of the
25
+ * thread the agent is on, as the runtime's `/connect` does. A test can hold
26
+ * the connect open with `holdConnect`.
27
+ */
28
+ class ThreadedAgent extends SeededAgent {
29
+ readonly connectedThreadIds: string[] = [];
30
+ readonly runs: { threadId: string; messages: string[] }[] = [];
31
+ private heldConnect: Promise<void> | undefined;
32
+ private heldRun: Promise<void> | undefined;
33
+
34
+ constructor(private readonly histories: Record<string, Message[]>) {
35
+ super();
36
+ }
37
+
38
+ holdConnect() {
39
+ let release!: () => void;
40
+ this.heldConnect = new Promise<void>((resolve) => {
41
+ release = resolve;
42
+ });
43
+ return release;
44
+ }
45
+
46
+ override async connectAgent(): Promise<RunAgentResult> {
47
+ const threadId = this.threadId;
48
+ this.connectedThreadIds.push(threadId);
49
+ await this.heldConnect;
50
+ this.setMessages(this.histories[threadId] ?? []);
51
+ return EMPTY_RESULT;
52
+ }
53
+
54
+ /** Holds the next run open; the returned function finishes it with a reply. */
55
+ holdRun() {
56
+ let release!: () => void;
57
+ this.heldRun = new Promise<void>((resolve) => {
58
+ release = resolve;
59
+ });
60
+ return release;
61
+ }
62
+
63
+ override async runAgent(): Promise<RunAgentResult> {
64
+ this.runs.push({
65
+ threadId: this.threadId,
66
+ messages: this.messages.map((m) => String(m.content)),
67
+ });
68
+ const held = this.heldRun;
69
+ if (held) {
70
+ this.heldRun = undefined;
71
+ await held;
72
+ this.addMessage(text("reply", "reply"));
73
+ }
74
+ return EMPTY_RESULT;
75
+ }
76
+ }
77
+
78
+ let chat: CopilotChatContextValue | null = null;
79
+
80
+ function Transcript() {
81
+ chat = useCopilotChatContext();
82
+ return (
83
+ <ul data-testid="transcript">
84
+ {chat.messages.map((m: Message) => (
85
+ <li key={m.id}>{String(m.content)}</li>
86
+ ))}
87
+ </ul>
88
+ );
89
+ }
90
+
91
+ function renderChat(agent: ThreadedAgent, threadId?: string) {
92
+ const agents = { x: agent };
93
+ const view = (id?: string) => (
94
+ <TestCopilotKit messages={[]} agents={agents}>
95
+ <CopilotChat agentId="x" threadId={id}>
96
+ <Transcript />
97
+ </CopilotChat>
98
+ </TestCopilotKit>
99
+ );
100
+ const result = render(view(threadId));
101
+ return {
102
+ switchTo: (id?: string) => result.rerender(view(id)),
103
+ unmount: result.unmount,
104
+ };
105
+ }
106
+
107
+ const transcript = () =>
108
+ Array.from(screen.getByTestId("transcript").children).map(
109
+ (li) => li.textContent,
110
+ );
111
+
112
+ describe("headless CopilotChat threads", () => {
113
+ it("restores the thread named by threadId", async () => {
114
+ const agent = new ThreadedAgent({ t1: [text("a", "from t1")] });
115
+
116
+ renderChat(agent, "t1");
117
+
118
+ await waitFor(() => expect(transcript()).toEqual(["from t1"]));
119
+ expect(agent.connectedThreadIds).toEqual(["t1"]);
120
+ expect(agent.threadId).toBe("t1");
121
+ });
122
+
123
+ it("restores the new thread when threadId changes", async () => {
124
+ const agent = new ThreadedAgent({
125
+ t1: [text("a", "from t1")],
126
+ t2: [text("b", "from t2")],
127
+ });
128
+ const { switchTo } = renderChat(agent, "t1");
129
+ await waitFor(() => expect(transcript()).toEqual(["from t1"]));
130
+
131
+ switchTo("t2");
132
+
133
+ await waitFor(() => expect(transcript()).toEqual(["from t2"]));
134
+ expect(agent.connectedThreadIds).toEqual(["t1", "t2"]);
135
+ expect(agent.threadId).toBe("t2");
136
+ });
137
+
138
+ it("does not connect a chat without threadId, and gives the agent a new thread", () => {
139
+ const agent = new ThreadedAgent({});
140
+ const before = agent.threadId;
141
+
142
+ renderChat(agent);
143
+
144
+ expect(agent.connectedThreadIds).toEqual([]);
145
+ expect(agent.threadId).toEqual(expect.any(String));
146
+ expect(agent.threadId).not.toBe(before);
147
+ });
148
+
149
+ it("empties the chat when threadId is removed", async () => {
150
+ const agent = new ThreadedAgent({ t1: [text("a", "from t1")] });
151
+ const { switchTo } = renderChat(agent, "t1");
152
+ await waitFor(() => expect(transcript()).toEqual(["from t1"]));
153
+
154
+ switchTo(undefined);
155
+
156
+ await waitFor(() => expect(transcript()).toEqual([]));
157
+ expect(agent.threadId).not.toBe("t1");
158
+ expect(agent.connectedThreadIds).toEqual(["t1"]);
159
+ });
160
+
161
+ it("sends a message only after the thread has been restored", async () => {
162
+ const agent = new ThreadedAgent({ t1: [text("a", "from t1")] });
163
+ const release = agent.holdConnect();
164
+ renderChat(agent, "t1");
165
+ await waitFor(() => expect(agent.connectedThreadIds).toEqual(["t1"]));
166
+
167
+ let sent: Promise<void> | undefined;
168
+ act(() => {
169
+ sent = chat!.submitMessage("hello");
170
+ });
171
+ // The connect is still loading, so the send waits for it.
172
+ await Promise.resolve();
173
+ expect(agent.runs).toEqual([]);
174
+
175
+ await act(async () => {
176
+ release();
177
+ await sent;
178
+ });
179
+
180
+ expect(agent.runs).toEqual([
181
+ { threadId: "t1", messages: ["from t1", "hello"] },
182
+ ]);
183
+ });
184
+ it("leaves the agent's run running when the chat unmounts after the thread loaded", async () => {
185
+ const agent = new ThreadedAgent({ t1: [text("a", "from t1")] });
186
+ const { unmount } = renderChat(agent, "t1");
187
+ await waitFor(() => expect(transcript()).toEqual(["from t1"]));
188
+ const finishRun = agent.holdRun();
189
+ let sent: Promise<void> | undefined;
190
+ act(() => {
191
+ sent = chat!.submitMessage("hello");
192
+ });
193
+ await waitFor(() => expect(agent.runs).toHaveLength(1));
194
+ // Core detaches the previous run itself before a connect or a run; count
195
+ // only what the chat's cleanup does.
196
+ const detach = vi.spyOn(agent, "detachActiveRun");
197
+
198
+ unmount();
199
+ await act(async () => {});
200
+
201
+ // The connect had settled, so the run in flight is not the connect's
202
+ // own: the reply the user asked for keeps streaming.
203
+ expect(detach).not.toHaveBeenCalled();
204
+ finishRun();
205
+ await sent;
206
+ expect(agent.messages.map((m) => String(m.content))).toEqual([
207
+ "from t1",
208
+ "hello",
209
+ "reply",
210
+ ]);
211
+ });
212
+
213
+ it("keeps the messages of an agent that cannot connect, and sends on its thread", async () => {
214
+ // An agent without connect: a connect would only empty it.
215
+ const agent = new (class extends SeededAgent {
216
+ readonly runs: string[] = [];
217
+ override async runAgent(): Promise<RunAgentResult> {
218
+ this.runs.push(this.threadId);
219
+ return EMPTY_RESULT;
220
+ }
221
+ })();
222
+ agent.setMessages([text("a", "kept")]);
223
+ renderChat(agent as unknown as ThreadedAgent, "t1");
224
+
225
+ await act(async () => {
226
+ await chat!.submitMessage("hello");
227
+ });
228
+
229
+ expect(transcript()).toEqual(["kept", "hello"]);
230
+ expect(agent.runs).toEqual(["t1"]);
231
+ });
232
+ });
@@ -33,6 +33,12 @@ function createMockCore() {
33
33
  setMessageFilter: vi.fn(),
34
34
  setDebug: vi.fn(),
35
35
  setDefaultThrottleMs: vi.fn(),
36
+ ɵupdateConfig: vi.fn(),
37
+ ɵruntimeInfo: { status: "disconnected" },
38
+ ɵsubscribeToRuntimeInfo: vi.fn(() => () => {}),
39
+ setErrorHandler: vi.fn(),
40
+ connect: vi.fn(),
41
+ dispose: vi.fn(),
36
42
  getAgent: vi.fn(() => undefined),
37
43
  runtimeUrl: "https://api.test",
38
44
  runtimeTransport: "auto",
@@ -52,13 +58,17 @@ function createMockCore() {
52
58
 
53
59
  let mockCoreInstance: ReturnType<typeof createMockCore>;
54
60
 
55
- vi.mock("@copilotkit/react-core/headless", () => {
61
+ vi.mock("@copilotkit/react-core/headless", async (importOriginal) => {
62
+ // The real entry, so the provider gets the real `ɵuseOwnedCore`.
63
+ const actual =
64
+ await importOriginal<typeof import("@copilotkit/react-core/headless")>();
56
65
  function CopilotKitCoreReact(this: any, ...args: any[]) {
57
66
  hoisted.MockCoreConstructor(...args);
58
67
  const instance = hoisted.MockCoreConstructor.mock.results.at(-1)?.value;
59
68
  if (instance) Object.assign(this, instance);
60
69
  }
61
70
  return {
71
+ ...actual,
62
72
  CopilotKitCoreReact,
63
73
  useAgent: (props: any) => {
64
74
  const ctx = require("react").useContext(hoisted.RealContext);
@@ -118,7 +128,10 @@ vi.mock("@copilotkit/react-core/context", () => {
118
128
  };
119
129
  });
120
130
 
121
- vi.mock("@copilotkit/shared", () => ({
131
+ vi.mock("@copilotkit/shared", async (importOriginal) => ({
132
+ // The real module first: the provider evaluates @copilotkit/core, which
133
+ // needs shared's value exports.
134
+ ...(await importOriginal<typeof import("@copilotkit/shared")>()),
122
135
  DEFAULT_AGENT_ID: "default",
123
136
  randomUUID: () => "test-uuid-" + Math.random().toString(36).slice(2, 8),
124
137
  getModalityFromMimeType: (mimeType: string) => {
@@ -33,6 +33,12 @@ function createMockCore() {
33
33
  setMessageFilter: vi.fn(),
34
34
  setDebug: vi.fn(),
35
35
  setDefaultThrottleMs: vi.fn(),
36
+ ɵupdateConfig: vi.fn(),
37
+ ɵruntimeInfo: { status: "disconnected" },
38
+ ɵsubscribeToRuntimeInfo: vi.fn(() => () => {}),
39
+ setErrorHandler: vi.fn(),
40
+ connect: vi.fn(),
41
+ dispose: vi.fn(),
36
42
  getAgent: vi.fn(() => undefined),
37
43
  runtimeUrl: "https://api.test",
38
44
  runtimeTransport: "auto",
@@ -52,13 +58,17 @@ function createMockCore() {
52
58
 
53
59
  let mockCoreInstance: ReturnType<typeof createMockCore>;
54
60
 
55
- vi.mock("@copilotkit/react-core/headless", () => {
61
+ vi.mock("@copilotkit/react-core/headless", async (importOriginal) => {
62
+ // The real entry, so the provider gets the real `ɵuseOwnedCore`.
63
+ const actual =
64
+ await importOriginal<typeof import("@copilotkit/react-core/headless")>();
56
65
  function CopilotKitCoreReact(this: any, ...args: any[]) {
57
66
  hoisted.MockCoreConstructor(...args);
58
67
  const instance = hoisted.MockCoreConstructor.mock.results.at(-1)?.value;
59
68
  if (instance) Object.assign(this, instance);
60
69
  }
61
70
  return {
71
+ ...actual,
62
72
  CopilotKitCoreReact,
63
73
  useAgent: (props: any) => {
64
74
  const ctx = require("react").useContext(hoisted.RealContext);
@@ -118,7 +128,10 @@ vi.mock("@copilotkit/react-core/context", () => {
118
128
  };
119
129
  });
120
130
 
121
- vi.mock("@copilotkit/shared", () => ({
131
+ vi.mock("@copilotkit/shared", async (importOriginal) => ({
132
+ // The real module first: the provider evaluates @copilotkit/core, which
133
+ // needs shared's value exports.
134
+ ...(await importOriginal<typeof import("@copilotkit/shared")>()),
122
135
  DEFAULT_AGENT_ID: "default",
123
136
  randomUUID: () => "test-uuid-" + Math.random().toString(36).slice(2, 8),
124
137
  getModalityFromMimeType: (mimeType: string) => {
@@ -23,17 +23,20 @@ function createMockCore() {
23
23
  capturedSubscriber = subscriber;
24
24
  return { unsubscribe: unsubscribeMock };
25
25
  }),
26
- setRuntimeUrl: vi.fn(),
27
- setRuntimeTransport: vi.fn(),
28
- setHeaders: vi.fn(),
29
- setCredentials: vi.fn(),
30
- setProperties: vi.fn(),
31
- setMessageFilter: vi.fn(),
32
- setDebug: vi.fn(),
33
- setDefaultThrottleMs: vi.fn(),
26
+ ɵupdateConfig: vi.fn(),
27
+ ɵruntimeInfo: { status: "disconnected" },
28
+ ɵsubscribeToRuntimeInfo: vi.fn(() => () => {}),
29
+ setErrorHandler: vi.fn(),
30
+ connect: vi.fn(),
31
+ dispose: vi.fn(),
34
32
  };
35
33
  }
36
34
 
35
+ /** The last config patch the provider pushed to the core. */
36
+ function lastPatch() {
37
+ return mockCoreInstance.ɵupdateConfig.mock.calls.at(-1)?.[0];
38
+ }
39
+
37
40
  let mockCoreInstance: ReturnType<typeof createMockCore>;
38
41
 
39
42
  /** Keeps the final turn only — the shape #1482 asks for. */
@@ -41,14 +44,16 @@ const keepLastTurn = (messages: any[]) => messages.slice(-1);
41
44
  /** A second, distinguishable filter, for asserting a swap took effect. */
42
45
  const keepLastTwo = (messages: any[]) => messages.slice(-2);
43
46
 
44
- vi.mock("@copilotkit/react-core/headless", () => {
47
+ vi.mock("@copilotkit/react-core/headless", async (importOriginal) => {
48
+ const actual =
49
+ await importOriginal<typeof import("@copilotkit/react-core/headless")>();
45
50
  // Regular function (not arrow) so it's new-able
46
51
  function CopilotKitCoreReact(this: any, ...args: any[]) {
47
52
  hoisted.MockCoreConstructor(...args);
48
53
  const instance = hoisted.MockCoreConstructor.mock.results.at(-1)?.value;
49
54
  if (instance) Object.assign(this, instance);
50
55
  }
51
- return { CopilotKitCoreReact };
56
+ return { ...actual, CopilotKitCoreReact };
52
57
  });
53
58
 
54
59
  vi.mock("@copilotkit/react-core/context", () => {
@@ -70,7 +75,8 @@ vi.mock("@copilotkit/react-core/context", () => {
70
75
  };
71
76
  });
72
77
 
73
- vi.mock("@copilotkit/shared", () => ({
78
+ vi.mock("@copilotkit/shared", async (importOriginal) => ({
79
+ ...(await importOriginal<typeof import("@copilotkit/shared")>()),
74
80
  createLicenseContextValue: () => ({
75
81
  status: null,
76
82
  license: null,
@@ -197,9 +203,7 @@ describe("CopilotKitProvider (React Native)", () => {
197
203
  </CopilotKitProvider>,
198
204
  );
199
205
 
200
- expect(mockCoreInstance.setRuntimeUrl).toHaveBeenCalledWith(
201
- "https://api.test/v2",
202
- );
206
+ expect(lastPatch()?.runtimeUrl).toBe("https://api.test/v2");
203
207
  });
204
208
 
205
209
  it("calls setHeaders when headers content changes", () => {
@@ -209,7 +213,7 @@ describe("CopilotKitProvider (React Native)", () => {
209
213
  </CopilotKitProvider>,
210
214
  );
211
215
 
212
- mockCoreInstance.setHeaders.mockClear();
216
+ mockCoreInstance.ɵupdateConfig.mockClear();
213
217
 
214
218
  rerender(
215
219
  <CopilotKitProvider runtimeUrl="https://api.test" headers={{ b: "2" }}>
@@ -217,7 +221,7 @@ describe("CopilotKitProvider (React Native)", () => {
217
221
  </CopilotKitProvider>,
218
222
  );
219
223
 
220
- expect(mockCoreInstance.setHeaders).toHaveBeenCalledWith({ b: "2" });
224
+ expect(lastPatch()?.headers).toEqual({ b: "2" });
221
225
  });
222
226
 
223
227
  it("does not re-fire setHeaders when content is identical (JSON-stabilized)", () => {
@@ -227,7 +231,7 @@ describe("CopilotKitProvider (React Native)", () => {
227
231
  </CopilotKitProvider>,
228
232
  );
229
233
 
230
- mockCoreInstance.setHeaders.mockClear();
234
+ mockCoreInstance.ɵupdateConfig.mockClear();
231
235
 
232
236
  // New object reference but same content
233
237
  rerender(
@@ -236,7 +240,7 @@ describe("CopilotKitProvider (React Native)", () => {
236
240
  </CopilotKitProvider>,
237
241
  );
238
242
 
239
- expect(mockCoreInstance.setHeaders).not.toHaveBeenCalled();
243
+ expect(mockCoreInstance.ɵupdateConfig).not.toHaveBeenCalled();
240
244
  });
241
245
 
242
246
  // #1482: parity with the React, Vue and Angular providers. The filter's own
@@ -267,7 +271,7 @@ describe("CopilotKitProvider (React Native)", () => {
267
271
  </CopilotKitProvider>,
268
272
  );
269
273
 
270
- mockCoreInstance.setMessageFilter.mockClear();
274
+ mockCoreInstance.ɵupdateConfig.mockClear();
271
275
 
272
276
  rerender(
273
277
  <CopilotKitProvider
@@ -278,9 +282,7 @@ describe("CopilotKitProvider (React Native)", () => {
278
282
  </CopilotKitProvider>,
279
283
  );
280
284
 
281
- expect(mockCoreInstance.setMessageFilter).toHaveBeenCalledWith(
282
- keepLastTwo,
283
- );
285
+ expect(lastPatch()?.messageFilter).toBe(keepLastTwo);
284
286
  });
285
287
 
286
288
  it("clears the filter when the prop goes away", () => {
@@ -293,7 +295,7 @@ describe("CopilotKitProvider (React Native)", () => {
293
295
  </CopilotKitProvider>,
294
296
  );
295
297
 
296
- mockCoreInstance.setMessageFilter.mockClear();
298
+ mockCoreInstance.ɵupdateConfig.mockClear();
297
299
 
298
300
  rerender(
299
301
  <CopilotKitProvider runtimeUrl="https://api.test">
@@ -301,7 +303,9 @@ describe("CopilotKitProvider (React Native)", () => {
301
303
  </CopilotKitProvider>,
302
304
  );
303
305
 
304
- expect(mockCoreInstance.setMessageFilter).toHaveBeenCalledWith(undefined);
306
+ const patch = lastPatch();
307
+ expect(patch && "messageFilter" in patch).toBe(true);
308
+ expect(patch?.messageFilter).toBeUndefined();
305
309
  });
306
310
  });
307
311
 
@@ -403,7 +407,9 @@ describe("CopilotKitProvider (React Native)", () => {
403
407
  // ── Error handling ────────────────────────────────────────────────────
404
408
 
405
409
  describe("error handling", () => {
406
- it("forwards errors to onError prop when provided", () => {
410
+ // Core calls the handler, and logs when there is none (core tests cover
411
+ // that). The provider's job is handing the handler over.
412
+ it("passes onError to the core at construction", () => {
407
413
  const onError = vi.fn();
408
414
  render(
409
415
  <CopilotKitProvider runtimeUrl="https://api.test" onError={onError}>
@@ -411,47 +417,12 @@ describe("CopilotKitProvider (React Native)", () => {
411
417
  </CopilotKitProvider>,
412
418
  );
413
419
 
414
- const testError = new Error("test error");
415
- act(() => {
416
- capturedSubscriber.onError({
417
- error: testError,
418
- code: "RUNTIME_ERROR",
419
- context: { detail: "info" },
420
- });
421
- });
422
-
423
- expect(onError).toHaveBeenCalledWith({
424
- error: testError,
425
- code: "RUNTIME_ERROR",
426
- context: { detail: "info" },
427
- });
428
- });
429
-
430
- it("logs to console.error when onError is not provided", () => {
431
- const spy = vi.spyOn(console, "error").mockImplementation(() => {});
432
- render(
433
- <CopilotKitProvider runtimeUrl="https://api.test">
434
- <div />
435
- </CopilotKitProvider>,
436
- );
437
-
438
- act(() => {
439
- capturedSubscriber.onError({
440
- error: new Error("fail"),
441
- code: "AGENT_ERROR",
442
- context: {},
443
- });
444
- });
445
-
446
- expect(spy).toHaveBeenCalledWith(
447
- expect.stringContaining("AGENT_ERROR"),
448
- expect.any(Error),
449
- expect.any(Object),
420
+ expect(hoisted.MockCoreConstructor).toHaveBeenCalledWith(
421
+ expect.objectContaining({ onError }),
450
422
  );
451
- spy.mockRestore();
452
423
  });
453
424
 
454
- it("picks up new onError callback without resubscribing (ref pattern)", () => {
425
+ it("hands a new onError to the core", () => {
455
426
  const onError1 = vi.fn();
456
427
  const onError2 = vi.fn();
457
428
 
@@ -467,16 +438,9 @@ describe("CopilotKitProvider (React Native)", () => {
467
438
  </CopilotKitProvider>,
468
439
  );
469
440
 
470
- act(() => {
471
- capturedSubscriber.onError({
472
- error: new Error("test"),
473
- code: "RUNTIME_ERROR",
474
- context: {},
475
- });
476
- });
477
-
478
- expect(onError1).not.toHaveBeenCalled();
479
- expect(onError2).toHaveBeenCalled();
441
+ expect(mockCoreInstance.setErrorHandler).toHaveBeenLastCalledWith(
442
+ onError2,
443
+ );
480
444
  });
481
445
  });
482
446
 
@@ -494,5 +458,36 @@ describe("CopilotKitProvider (React Native)", () => {
494
458
 
495
459
  expect(unsubscribeMock).toHaveBeenCalled();
496
460
  });
461
+
462
+ it("disposes the core after unmount", async () => {
463
+ const { unmount } = render(
464
+ <CopilotKitProvider runtimeUrl="https://api.test">
465
+ <div />
466
+ </CopilotKitProvider>,
467
+ );
468
+
469
+ unmount();
470
+
471
+ await vi.waitFor(() =>
472
+ expect(mockCoreInstance.dispose).toHaveBeenCalledTimes(1),
473
+ );
474
+ });
475
+ });
476
+
477
+ // ── Runtime connection ──────────────────────────────────────────────
478
+
479
+ describe("runtime connection", () => {
480
+ it("defers /info to an effect", () => {
481
+ render(
482
+ <CopilotKitProvider runtimeUrl="https://api.test">
483
+ <div />
484
+ </CopilotKitProvider>,
485
+ );
486
+
487
+ expect(hoisted.MockCoreConstructor).toHaveBeenCalledWith(
488
+ expect.objectContaining({ deferInitialConnection: true }),
489
+ );
490
+ expect(mockCoreInstance.connect).toHaveBeenCalled();
491
+ });
497
492
  });
498
493
  });
@@ -88,6 +88,12 @@ function createMockCore() {
88
88
  setMessageFilter: vi.fn(),
89
89
  setDebug: vi.fn(),
90
90
  setDefaultThrottleMs: vi.fn(),
91
+ ɵupdateConfig: vi.fn(),
92
+ ɵruntimeInfo: { status: "disconnected" },
93
+ ɵsubscribeToRuntimeInfo: vi.fn(() => () => {}),
94
+ setErrorHandler: vi.fn(),
95
+ connect: vi.fn(),
96
+ dispose: vi.fn(),
91
97
  getAgent: vi.fn(() => undefined),
92
98
  runtimeUrl: "https://api.test",
93
99
  runtimeTransport: "auto",
@@ -107,7 +113,10 @@ function createMockCore() {
107
113
 
108
114
  let mockCoreInstance: ReturnType<typeof createMockCore>;
109
115
 
110
- vi.mock("@copilotkit/react-core/headless", () => {
116
+ vi.mock("@copilotkit/react-core/headless", async (importOriginal) => {
117
+ // The real entry, so the provider gets the real `ɵuseOwnedCore`.
118
+ const actual =
119
+ await importOriginal<typeof import("@copilotkit/react-core/headless")>();
111
120
  // Regular function (not arrow) so it's new-able
112
121
  function CopilotKitCoreReact(this: any, ...args: any[]) {
113
122
  hoisted.MockCoreConstructor(...args);
@@ -115,6 +124,7 @@ vi.mock("@copilotkit/react-core/headless", () => {
115
124
  if (instance) Object.assign(this, instance);
116
125
  }
117
126
  return {
127
+ ...actual,
118
128
  CopilotKitCoreReact,
119
129
  useAgent: () => {
120
130
  const ctx = require("react").useContext(hoisted.RealContext);
@@ -17,8 +17,10 @@ vi.mock("expo-file-system", () => ({
17
17
  EncodingType: { Base64: "base64" },
18
18
  }));
19
19
 
20
- // Mock @copilotkit/shared -- only the utils we use
21
- vi.mock("@copilotkit/shared", () => ({
20
+ // Mock @copilotkit/shared over the real module: core's attachment queue
21
+ // needs its other exports.
22
+ vi.mock("@copilotkit/shared", async (importOriginal) => ({
23
+ ...(await importOriginal<typeof import("@copilotkit/shared")>()),
22
24
  getModalityFromMimeType: (mimeType: string) => {
23
25
  if (mimeType.startsWith("image/")) return "image";
24
26
  if (mimeType.startsWith("audio/")) return "audio";
@@ -157,6 +159,7 @@ describe("useAttachments (React Native)", () => {
157
159
  expect(onUploadFailed).toHaveBeenCalledWith(
158
160
  expect.objectContaining({
159
161
  reason: "file-too-large",
162
+ file,
160
163
  }),
161
164
  );
162
165
  });
@@ -189,6 +192,7 @@ describe("useAttachments (React Native)", () => {
189
192
  expect(onUploadFailed).toHaveBeenCalledWith(
190
193
  expect.objectContaining({
191
194
  reason: "invalid-type",
195
+ file,
192
196
  }),
193
197
  );
194
198
  });
@@ -219,10 +223,31 @@ describe("useAttachments (React Native)", () => {
219
223
  expect(onUploadFailed).toHaveBeenCalledWith(
220
224
  expect.objectContaining({
221
225
  reason: "upload-failed",
226
+ file,
222
227
  }),
223
228
  );
224
229
  });
225
230
 
231
+ it("ignores files while attachments are disabled", async () => {
232
+ const { result } = renderHook(() =>
233
+ useAttachments({ config: { enabled: false } }),
234
+ );
235
+
236
+ await act(async () => {
237
+ await result.current.processFiles([
238
+ {
239
+ uri: "file:///tmp/photo.jpg",
240
+ name: "photo.jpg",
241
+ size: 1024,
242
+ mimeType: "image/jpeg",
243
+ },
244
+ ]);
245
+ });
246
+
247
+ expect(result.current.attachments).toEqual([]);
248
+ expect(mockReadAsStringAsync).not.toHaveBeenCalled();
249
+ });
250
+
226
251
  it("calls custom onUpload instead of reading file directly", async () => {
227
252
  const customUpload = vi.fn().mockResolvedValue({
228
253
  type: "url",