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