@copilotkit/react-native 1.57.1 → 1.57.3

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.
@@ -0,0 +1,558 @@
1
+ import React, { createRef } from "react";
2
+ import { render, fireEvent, act } from "@testing-library/react";
3
+ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
4
+
5
+ // ─── Mocks ────────────────────────────────────────────────────────────────────
6
+
7
+ // Track the agentId passed to useAgent across renders
8
+ let capturedAgentId: string | undefined;
9
+
10
+ const hoisted = vi.hoisted(() => {
11
+ const _React = require("react");
12
+ return {
13
+ RealContext: _React.createContext(null),
14
+ MockCoreConstructor: vi.fn(),
15
+ };
16
+ });
17
+
18
+ let unsubscribeMock: ReturnType<typeof vi.fn>;
19
+
20
+ function createMockCore() {
21
+ return {
22
+ subscribe: vi.fn((_subscriber: any) => ({
23
+ unsubscribe: unsubscribeMock,
24
+ })),
25
+ subscribeToAgentWithOptions: vi.fn((_agent: any, _handlers: any) => ({
26
+ unsubscribe: vi.fn(),
27
+ })),
28
+ setRuntimeUrl: vi.fn(),
29
+ setRuntimeTransport: vi.fn(),
30
+ setHeaders: vi.fn(),
31
+ setCredentials: vi.fn(),
32
+ setProperties: vi.fn(),
33
+ setDebug: vi.fn(),
34
+ setDefaultThrottleMs: vi.fn(),
35
+ getAgent: vi.fn(() => undefined),
36
+ runtimeUrl: "https://api.test",
37
+ runtimeTransport: "auto",
38
+ runtimeConnectionStatus: "Disconnected",
39
+ headers: {},
40
+ agents: {},
41
+ defaultThrottleMs: undefined,
42
+ addTool: vi.fn(),
43
+ removeTool: vi.fn(),
44
+ getTool: vi.fn(() => undefined),
45
+ addHookRenderToolCall: vi.fn(),
46
+ registerThreadStore: vi.fn(),
47
+ unregisterThreadStore: vi.fn(),
48
+ intelligence: undefined,
49
+ };
50
+ }
51
+
52
+ let mockCoreInstance: ReturnType<typeof createMockCore>;
53
+
54
+ vi.mock("@copilotkit/react-core/v2/headless", () => {
55
+ function CopilotKitCoreReact(this: any, ...args: any[]) {
56
+ hoisted.MockCoreConstructor(...args);
57
+ const instance = hoisted.MockCoreConstructor.mock.results.at(-1)?.value;
58
+ if (instance) Object.assign(this, instance);
59
+ }
60
+ return {
61
+ CopilotKitCoreReact,
62
+ useAgent: (props: any) => {
63
+ const ctx = require("react").useContext(hoisted.RealContext);
64
+ if (!ctx) {
65
+ throw new Error("useCopilotKit must be used within CopilotKitProvider");
66
+ }
67
+ capturedAgentId = props?.agentId;
68
+ return { agent: {} };
69
+ },
70
+ useFrontendTool: () => {},
71
+ useComponent: () => {},
72
+ useHumanInTheLoop: () => {},
73
+ useInterrupt: () => {},
74
+ useSuggestions: () => {},
75
+ useConfigureSuggestions: () => {},
76
+ useAgentContext: () => {},
77
+ useThreads: () => ({
78
+ threads: [],
79
+ isLoading: false,
80
+ error: null,
81
+ hasMoreThreads: false,
82
+ isFetchingMoreThreads: false,
83
+ fetchMoreThreads: () => {},
84
+ renameThread: async () => {},
85
+ archiveThread: async () => {},
86
+ deleteThread: async () => {},
87
+ }),
88
+ CopilotChatConfigurationProvider: ({ children }: any) => children,
89
+ useCopilotChatConfiguration: () => null,
90
+ CopilotChatDefaultLabels: {},
91
+ };
92
+ });
93
+
94
+ vi.mock("@copilotkit/react-core/v2/context", () => {
95
+ const _React = require("react");
96
+ return {
97
+ CopilotKitContext: hoisted.RealContext,
98
+ LicenseContext: _React.createContext({
99
+ status: null,
100
+ license: null,
101
+ checkFeature: () => true,
102
+ getLimit: () => null,
103
+ }),
104
+ useCopilotKit: () => {
105
+ const ctx = _React.useContext(hoisted.RealContext);
106
+ if (!ctx) {
107
+ throw new Error("useCopilotKit must be used within CopilotKitProvider");
108
+ }
109
+ return ctx;
110
+ },
111
+ useLicenseContext: () => ({
112
+ status: null,
113
+ license: null,
114
+ checkFeature: () => true,
115
+ getLimit: () => null,
116
+ }),
117
+ };
118
+ });
119
+
120
+ vi.mock("@copilotkit/shared", () => ({
121
+ DEFAULT_AGENT_ID: "default",
122
+ randomUUID: () => "test-uuid-" + Math.random().toString(36).slice(2, 8),
123
+ getModalityFromMimeType: (mimeType: string) => {
124
+ if (mimeType.startsWith("image/")) return "image";
125
+ if (mimeType.startsWith("audio/")) return "audio";
126
+ if (mimeType.startsWith("video/")) return "video";
127
+ return "document";
128
+ },
129
+ formatFileSize: (bytes: number) => `${bytes} B`,
130
+ createLicenseContextValue: () => ({
131
+ status: null,
132
+ license: null,
133
+ checkFeature: () => true,
134
+ getLimit: () => null,
135
+ }),
136
+ }));
137
+
138
+ vi.mock("expo-document-picker", () => ({
139
+ getDocumentAsync: vi.fn().mockResolvedValue({ canceled: true, assets: [] }),
140
+ }));
141
+ vi.mock("expo-file-system", () => ({
142
+ readAsStringAsync: vi.fn().mockResolvedValue("base64data"),
143
+ EncodingType: { Base64: "base64" },
144
+ }));
145
+
146
+ // Mock React Native components for jsdom environment
147
+ vi.mock("react-native", () => {
148
+ const _React = require("react");
149
+
150
+ // Simple mock components that render as divs with testIDs
151
+ const Modal = ({ children, visible, testID, onRequestClose }: any) => {
152
+ if (!visible) return null;
153
+ return _React.createElement(
154
+ "div",
155
+ { "data-testid": testID, "data-visible": visible },
156
+ children,
157
+ );
158
+ };
159
+
160
+ const View = ({ children, style, testID }: any) =>
161
+ _React.createElement("div", { "data-testid": testID, style }, children);
162
+
163
+ const Text = ({ children, style, testID }: any) =>
164
+ _React.createElement("span", { "data-testid": testID, style }, children);
165
+
166
+ const TouchableOpacity = ({
167
+ children,
168
+ onPress,
169
+ testID,
170
+ accessibilityLabel,
171
+ style,
172
+ }: any) =>
173
+ _React.createElement(
174
+ "button",
175
+ {
176
+ "data-testid": testID,
177
+ onClick: onPress,
178
+ "aria-label": accessibilityLabel,
179
+ style,
180
+ },
181
+ children,
182
+ );
183
+
184
+ const Pressable = ({ children, onPress, testID, style }: any) =>
185
+ _React.createElement(
186
+ "div",
187
+ { "data-testid": testID, onClick: onPress, style },
188
+ children,
189
+ );
190
+
191
+ const Animated = {
192
+ View,
193
+ Text,
194
+ createAnimatedComponent: (comp: any) => comp,
195
+ timing: () => ({ start: (cb?: any) => cb?.() }),
196
+ spring: () => ({ start: (cb?: any) => cb?.() }),
197
+ Value: class {
198
+ _value: number;
199
+ constructor(v: number) {
200
+ this._value = v;
201
+ }
202
+ setValue(v: number) {
203
+ this._value = v;
204
+ }
205
+ interpolate() {
206
+ return this;
207
+ }
208
+ },
209
+ };
210
+
211
+ const StyleSheet = {
212
+ create: (styles: any) => styles,
213
+ hairlineWidth: 1,
214
+ };
215
+
216
+ const useWindowDimensions = () => ({ width: 375, height: 812 });
217
+
218
+ return {
219
+ Modal,
220
+ View,
221
+ Text,
222
+ TouchableOpacity,
223
+ Pressable,
224
+ Animated,
225
+ StyleSheet,
226
+ useWindowDimensions,
227
+ Platform: { OS: "ios" },
228
+ };
229
+ });
230
+
231
+ // Import after mocks
232
+ import { CopilotKitProvider } from "../CopilotKitProvider";
233
+ import { CopilotPopup } from "../CopilotPopup";
234
+ import type { CopilotPopupHandle } from "../CopilotPopup";
235
+
236
+ // ─── Tests ────────────────────────────────────────────────────────────────────
237
+
238
+ describe("CopilotPopup", () => {
239
+ beforeEach(() => {
240
+ capturedAgentId = undefined;
241
+ unsubscribeMock = vi.fn();
242
+ mockCoreInstance = createMockCore();
243
+ hoisted.MockCoreConstructor.mockClear();
244
+ hoisted.MockCoreConstructor.mockReturnValue(mockCoreInstance);
245
+ });
246
+
247
+ afterEach(() => {
248
+ vi.clearAllMocks();
249
+ });
250
+
251
+ it("renders without crashing", () => {
252
+ const { container } = render(
253
+ <CopilotKitProvider runtimeUrl="https://api.test">
254
+ <CopilotPopup />
255
+ </CopilotKitProvider>,
256
+ );
257
+
258
+ expect(container).toBeTruthy();
259
+ });
260
+
261
+ it("shows FAB when closed and hides FAB when open", () => {
262
+ const { queryByTestId } = render(
263
+ <CopilotKitProvider runtimeUrl="https://api.test">
264
+ <CopilotPopup defaultOpen={false} />
265
+ </CopilotKitProvider>,
266
+ );
267
+
268
+ // FAB should be visible when popup is closed
269
+ expect(queryByTestId("copilot-popup-fab")).toBeTruthy();
270
+ // Modal should not be visible
271
+ expect(queryByTestId("copilot-popup-modal")).toBeNull();
272
+ });
273
+
274
+ describe("defaultOpen", () => {
275
+ it("starts closed by default", () => {
276
+ const { queryByTestId } = render(
277
+ <CopilotKitProvider runtimeUrl="https://api.test">
278
+ <CopilotPopup />
279
+ </CopilotKitProvider>,
280
+ );
281
+
282
+ // FAB visible = popup closed
283
+ expect(queryByTestId("copilot-popup-fab")).toBeTruthy();
284
+ expect(queryByTestId("copilot-popup-modal")).toBeNull();
285
+ });
286
+
287
+ it("starts open when defaultOpen=true", () => {
288
+ const { queryByTestId } = render(
289
+ <CopilotKitProvider runtimeUrl="https://api.test">
290
+ <CopilotPopup defaultOpen={true} />
291
+ </CopilotKitProvider>,
292
+ );
293
+
294
+ // Modal should be visible when defaultOpen is true
295
+ expect(queryByTestId("copilot-popup-modal")).toBeTruthy();
296
+ // FAB should be hidden when popup is open
297
+ expect(queryByTestId("copilot-popup-fab")).toBeNull();
298
+ });
299
+ });
300
+
301
+ describe("imperative handle", () => {
302
+ it("open() makes the popup visible", () => {
303
+ const ref = createRef<CopilotPopupHandle>();
304
+
305
+ const { queryByTestId } = render(
306
+ <CopilotKitProvider runtimeUrl="https://api.test">
307
+ <CopilotPopup ref={ref} defaultOpen={false} />
308
+ </CopilotKitProvider>,
309
+ );
310
+
311
+ // Initially closed
312
+ expect(queryByTestId("copilot-popup-modal")).toBeNull();
313
+
314
+ // Call open()
315
+ act(() => {
316
+ ref.current!.open();
317
+ });
318
+
319
+ expect(queryByTestId("copilot-popup-modal")).toBeTruthy();
320
+ });
321
+
322
+ it("close() hides the popup", () => {
323
+ const ref = createRef<CopilotPopupHandle>();
324
+
325
+ const { queryByTestId } = render(
326
+ <CopilotKitProvider runtimeUrl="https://api.test">
327
+ <CopilotPopup ref={ref} defaultOpen={true} />
328
+ </CopilotKitProvider>,
329
+ );
330
+
331
+ // Initially open
332
+ expect(queryByTestId("copilot-popup-modal")).toBeTruthy();
333
+
334
+ // Call close()
335
+ act(() => {
336
+ ref.current!.close();
337
+ });
338
+
339
+ expect(queryByTestId("copilot-popup-modal")).toBeNull();
340
+ });
341
+
342
+ it("toggle() switches the popup state", () => {
343
+ const ref = createRef<CopilotPopupHandle>();
344
+
345
+ const { queryByTestId } = render(
346
+ <CopilotKitProvider runtimeUrl="https://api.test">
347
+ <CopilotPopup ref={ref} defaultOpen={false} />
348
+ </CopilotKitProvider>,
349
+ );
350
+
351
+ // Initially closed
352
+ expect(queryByTestId("copilot-popup-modal")).toBeNull();
353
+
354
+ // Toggle open
355
+ act(() => {
356
+ ref.current!.toggle();
357
+ });
358
+ expect(queryByTestId("copilot-popup-modal")).toBeTruthy();
359
+
360
+ // Toggle closed
361
+ act(() => {
362
+ ref.current!.toggle();
363
+ });
364
+ expect(queryByTestId("copilot-popup-modal")).toBeNull();
365
+ });
366
+ });
367
+
368
+ describe("dismissOnBackdropPress", () => {
369
+ it("closes when backdrop is pressed (default behavior)", () => {
370
+ const ref = createRef<CopilotPopupHandle>();
371
+
372
+ const { queryByTestId, getByTestId } = render(
373
+ <CopilotKitProvider runtimeUrl="https://api.test">
374
+ <CopilotPopup ref={ref} defaultOpen={true} />
375
+ </CopilotKitProvider>,
376
+ );
377
+
378
+ expect(queryByTestId("copilot-popup-modal")).toBeTruthy();
379
+
380
+ // Click the backdrop
381
+ act(() => {
382
+ fireEvent.click(getByTestId("copilot-popup-backdrop"));
383
+ });
384
+
385
+ expect(queryByTestId("copilot-popup-modal")).toBeNull();
386
+ });
387
+
388
+ it("does NOT close when dismissOnBackdropPress=false", () => {
389
+ const ref = createRef<CopilotPopupHandle>();
390
+
391
+ const { queryByTestId, getByTestId } = render(
392
+ <CopilotKitProvider runtimeUrl="https://api.test">
393
+ <CopilotPopup
394
+ ref={ref}
395
+ defaultOpen={true}
396
+ dismissOnBackdropPress={false}
397
+ />
398
+ </CopilotKitProvider>,
399
+ );
400
+
401
+ expect(queryByTestId("copilot-popup-modal")).toBeTruthy();
402
+
403
+ // Click the backdrop — should NOT close
404
+ act(() => {
405
+ fireEvent.click(getByTestId("copilot-popup-backdrop"));
406
+ });
407
+
408
+ expect(queryByTestId("copilot-popup-modal")).toBeTruthy();
409
+ });
410
+ });
411
+
412
+ describe("agentId forwarding", () => {
413
+ it("forwards agentId to CopilotChat", () => {
414
+ render(
415
+ <CopilotKitProvider runtimeUrl="https://api.test">
416
+ <CopilotPopup agentId="popup-agent" defaultOpen={true} />
417
+ </CopilotKitProvider>,
418
+ );
419
+
420
+ expect(capturedAgentId).toBe("popup-agent");
421
+ });
422
+
423
+ it("forwards agentName to CopilotChat when agentId not set", () => {
424
+ render(
425
+ <CopilotKitProvider runtimeUrl="https://api.test">
426
+ <CopilotPopup agentName="legacy-popup" defaultOpen={true} />
427
+ </CopilotKitProvider>,
428
+ );
429
+
430
+ expect(capturedAgentId).toBe("legacy-popup");
431
+ });
432
+
433
+ it("agentId takes priority over agentName", () => {
434
+ render(
435
+ <CopilotKitProvider runtimeUrl="https://api.test">
436
+ <CopilotPopup
437
+ agentId="primary"
438
+ agentName="legacy"
439
+ defaultOpen={true}
440
+ />
441
+ </CopilotKitProvider>,
442
+ );
443
+
444
+ expect(capturedAgentId).toBe("primary");
445
+ });
446
+
447
+ it("uses default agent ID when neither provided", () => {
448
+ render(
449
+ <CopilotKitProvider runtimeUrl="https://api.test">
450
+ <CopilotPopup defaultOpen={true} />
451
+ </CopilotKitProvider>,
452
+ );
453
+
454
+ expect(capturedAgentId).toBe("default");
455
+ });
456
+ });
457
+
458
+ it("renders children inside the popup", () => {
459
+ const { getByText } = render(
460
+ <CopilotKitProvider runtimeUrl="https://api.test">
461
+ <CopilotPopup defaultOpen={true}>
462
+ <span>Custom Content</span>
463
+ </CopilotPopup>
464
+ </CopilotKitProvider>,
465
+ );
466
+
467
+ expect(getByText("Custom Content")).toBeTruthy();
468
+ });
469
+
470
+ it("displays custom header title", () => {
471
+ const { getByText } = render(
472
+ <CopilotKitProvider runtimeUrl="https://api.test">
473
+ <CopilotPopup defaultOpen={true} headerTitle="My Chat" />
474
+ </CopilotKitProvider>,
475
+ );
476
+
477
+ expect(getByText("My Chat")).toBeTruthy();
478
+ });
479
+
480
+ it("calls onOpen and onClose callbacks", () => {
481
+ const onOpen = vi.fn();
482
+ const onClose = vi.fn();
483
+ const ref = createRef<CopilotPopupHandle>();
484
+
485
+ render(
486
+ <CopilotKitProvider runtimeUrl="https://api.test">
487
+ <CopilotPopup ref={ref} onOpen={onOpen} onClose={onClose} />
488
+ </CopilotKitProvider>,
489
+ );
490
+
491
+ act(() => {
492
+ ref.current!.open();
493
+ });
494
+ expect(onOpen).toHaveBeenCalledTimes(1);
495
+
496
+ act(() => {
497
+ ref.current!.close();
498
+ });
499
+ expect(onClose).toHaveBeenCalledTimes(1);
500
+ });
501
+
502
+ it("hides FAB when showToggleButton=false", () => {
503
+ const { queryByTestId } = render(
504
+ <CopilotKitProvider runtimeUrl="https://api.test">
505
+ <CopilotPopup showToggleButton={false} defaultOpen={false} />
506
+ </CopilotKitProvider>,
507
+ );
508
+
509
+ expect(queryByTestId("copilot-popup-fab")).toBeNull();
510
+ });
511
+
512
+ it("FAB toggles the popup open", () => {
513
+ const { queryByTestId, getByTestId } = render(
514
+ <CopilotKitProvider runtimeUrl="https://api.test">
515
+ <CopilotPopup defaultOpen={false} />
516
+ </CopilotKitProvider>,
517
+ );
518
+
519
+ expect(queryByTestId("copilot-popup-modal")).toBeNull();
520
+
521
+ act(() => {
522
+ fireEvent.click(getByTestId("copilot-popup-fab"));
523
+ });
524
+
525
+ expect(queryByTestId("copilot-popup-modal")).toBeTruthy();
526
+ });
527
+
528
+ it("close button in header closes the popup", () => {
529
+ const { queryByTestId, getByTestId } = render(
530
+ <CopilotKitProvider runtimeUrl="https://api.test">
531
+ <CopilotPopup defaultOpen={true} />
532
+ </CopilotKitProvider>,
533
+ );
534
+
535
+ expect(queryByTestId("copilot-popup-modal")).toBeTruthy();
536
+
537
+ act(() => {
538
+ fireEvent.click(getByTestId("copilot-popup-close"));
539
+ });
540
+
541
+ expect(queryByTestId("copilot-popup-modal")).toBeNull();
542
+ });
543
+
544
+ describe("attachments prop forwarding", () => {
545
+ it("forwards attachments config to CopilotChat", () => {
546
+ expect(() => {
547
+ render(
548
+ <CopilotKitProvider runtimeUrl="https://api.test">
549
+ <CopilotPopup
550
+ defaultOpen={true}
551
+ attachments={{ enabled: true, accept: "image/*" }}
552
+ />
553
+ </CopilotKitProvider>,
554
+ );
555
+ }).not.toThrow();
556
+ });
557
+ });
558
+ });