forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheadless-integration.test.tsx
More file actions
448 lines (398 loc) · 13.6 KB
/
Copy pathheadless-integration.test.tsx
File metadata and controls
448 lines (398 loc) · 13.6 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
import React from "react";
import { render } from "@testing-library/react";
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
// ─── Mocks ────────────────────────────────────────────────────────────────────
// react-native uses Flow syntax that Vitest/Rollup can't parse outside of
// Metro. Mock it so barrel imports from ../index don't trigger a parse error.
vi.mock("react-native", () => {
const _React = require("react");
const View = ({ children, style, testID }: any) =>
_React.createElement("div", { "data-testid": testID, style }, children);
const Text = ({ children, style, testID }: any) =>
_React.createElement("span", { "data-testid": testID, style }, children);
const Pressable = ({ children, onPress, testID, style }: any) =>
_React.createElement(
"div",
{ "data-testid": testID, onClick: onPress, style },
children,
);
const TouchableOpacity = ({ children, onPress, testID, style }: any) =>
_React.createElement(
"button",
{ "data-testid": testID, onClick: onPress, style },
children,
);
const Modal = ({ children, visible, testID }: any) => {
if (!visible) return null;
return _React.createElement("div", { "data-testid": testID }, children);
};
return {
View,
Text,
Pressable,
TouchableOpacity,
Modal,
Animated: {
View,
Text,
createAnimatedComponent: (comp: any) => comp,
timing: () => ({ start: (cb?: any) => cb?.() }),
Value: class {
_value: number;
constructor(v: number) {
this._value = v;
}
setValue(v: number) {
this._value = v;
}
},
},
Dimensions: { get: () => ({ width: 375, height: 812 }) },
StyleSheet: { create: (styles: any) => styles, hairlineWidth: 1 },
useWindowDimensions: () => ({ width: 375, height: 812 }),
Platform: { OS: "ios" },
};
});
// vi.hoisted runs before vi.mock factories, making these available to both
const hoisted = vi.hoisted(() => {
const _React = require("react");
return {
RealContext: _React.createContext(null),
MockCoreConstructor: vi.fn(),
};
});
let _capturedSubscriber: Record<string, (...args: any[]) => void>;
let unsubscribeMock: ReturnType<typeof vi.fn>;
function createMockCore() {
return {
subscribe: vi.fn((subscriber: any) => {
_capturedSubscriber = subscriber;
return { 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", () => {
// Regular function (not arrow) so it's new-able
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: () => {
const ctx = require("react").useContext(hoisted.RealContext);
if (!ctx) {
throw new Error("useCopilotKit must be used within CopilotKitProvider");
}
return { agent: {} };
},
useFrontendTool: (_tool: any) => {
const ctx = require("react").useContext(hoisted.RealContext);
if (!ctx) {
throw new Error("useCopilotKit must be used within CopilotKitProvider");
}
},
useComponent: () => {
const ctx = require("react").useContext(hoisted.RealContext);
if (!ctx) {
throw new Error("useCopilotKit must be used within CopilotKitProvider");
}
},
useHumanInTheLoop: () => {
const ctx = require("react").useContext(hoisted.RealContext);
if (!ctx) {
throw new Error("useCopilotKit must be used within CopilotKitProvider");
}
},
useInterrupt: () => {
const ctx = require("react").useContext(hoisted.RealContext);
if (!ctx) {
throw new Error("useCopilotKit must be used within CopilotKitProvider");
}
},
useSuggestions: () => {
const ctx = require("react").useContext(hoisted.RealContext);
if (!ctx) {
throw new Error("useCopilotKit must be used within CopilotKitProvider");
}
},
useConfigureSuggestions: () => {
const ctx = require("react").useContext(hoisted.RealContext);
if (!ctx) {
throw new Error("useCopilotKit must be used within CopilotKitProvider");
}
},
useAgentContext: () => {
const ctx = require("react").useContext(hoisted.RealContext);
if (!ctx) {
throw new Error("useCopilotKit must be used within CopilotKitProvider");
}
},
useThreads: (_input: any) => {
const ctx = require("react").useContext(hoisted.RealContext);
if (!ctx) {
throw new Error("useCopilotKit must be used within CopilotKitProvider");
}
return {
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,
}),
};
});
// Mock @gorhom/bottom-sheet to prevent its CommonJS require("react-native")
// from bypassing the vite alias and loading the Flow-syntax react-native.
vi.mock("@gorhom/bottom-sheet", () => {
const React = require("react");
return {
__esModule: true,
default: React.forwardRef((props: any, ref: any) =>
React.createElement("mock-bottom-sheet", { ref }, props.children),
),
BottomSheetBackdrop: () => null,
BottomSheetFlatList: "FlatList",
BottomSheetView: (props: any) =>
React.createElement("div", null, props.children),
};
});
vi.mock("@copilotkit/shared", () => ({
createLicenseContextValue: () => ({
status: null,
license: null,
checkFeature: () => true,
getLimit: () => null,
}),
}));
// Import after mocks
import { CopilotKitProvider } from "../CopilotKitProvider";
import {
useAgent,
useFrontendTool,
useHumanInTheLoop,
useInterrupt,
useThreads,
} from "../index";
// ─── Tests ────────────────────────────────────────────────────────────────────
describe("Headless integration", () => {
beforeEach(() => {
unsubscribeMock = vi.fn();
mockCoreInstance = createMockCore();
hoisted.MockCoreConstructor.mockClear();
hoisted.MockCoreConstructor.mockReturnValue(mockCoreInstance);
});
afterEach(() => {
vi.clearAllMocks();
});
// ── Provider + hooks integration ──────────────────────────────────────
describe("provider + hooks integration", () => {
it("useAgent returns expected shape when called inside provider", () => {
let result: any = null;
function TestComponent() {
result = useAgent();
return null;
}
render(
<CopilotKitProvider runtimeUrl="https://api.test">
<TestComponent />
</CopilotKitProvider>,
);
expect(result).not.toBeNull();
expect(result).toHaveProperty("agent");
expect(typeof result.agent).toBe("object");
});
it("useFrontendTool can register a tool without error", () => {
function TestComponent() {
useFrontendTool({
name: "test-tool",
description: "A test tool",
parameters: {},
handler: async () => "done",
});
return null;
}
// Should not throw
expect(() => {
render(
<CopilotKitProvider runtimeUrl="https://api.test">
<TestComponent />
</CopilotKitProvider>,
);
}).not.toThrow();
});
it("useThreads returns thread state when called inside provider", () => {
let result: any = null;
function TestComponent() {
result = useThreads({ agentId: "test-agent" });
return null;
}
render(
<CopilotKitProvider runtimeUrl="https://api.test">
<TestComponent />
</CopilotKitProvider>,
);
expect(result).not.toBeNull();
expect(result).toHaveProperty("threads");
expect(result).toHaveProperty("isLoading");
expect(result).toHaveProperty("error");
expect(result).toHaveProperty("renameThread");
expect(result).toHaveProperty("archiveThread");
expect(result).toHaveProperty("deleteThread");
expect(result).toHaveProperty("hasMoreThreads");
expect(result).toHaveProperty("isFetchingMoreThreads");
expect(result).toHaveProperty("fetchMoreThreads");
expect(Array.isArray(result.threads)).toBe(true);
expect(typeof result.renameThread).toBe("function");
expect(typeof result.archiveThread).toBe("function");
expect(typeof result.deleteThread).toBe("function");
});
it("multiple hooks can coexist in the same provider tree", () => {
let agentResult: any = null;
let threadsResult: any = null;
function TestComponent() {
agentResult = useAgent();
threadsResult = useThreads({ agentId: "test-agent" });
useFrontendTool({
name: "multi-tool",
description: "Another tool",
parameters: {},
handler: async () => "ok",
});
return null;
}
expect(() => {
render(
<CopilotKitProvider runtimeUrl="https://api.test">
<TestComponent />
</CopilotKitProvider>,
);
}).not.toThrow();
expect(agentResult).toHaveProperty("agent");
expect(threadsResult).toHaveProperty("threads");
});
});
// ── Provider error boundary ───────────────────────────────────────────
describe("provider error boundary", () => {
it("useAgent throws when called outside CopilotKitProvider", () => {
function TestComponent() {
useAgent();
return null;
}
// Suppress React error boundary console output
const spy = vi.spyOn(console, "error").mockImplementation(() => {});
expect(() => {
render(<TestComponent />);
}).toThrow("useCopilotKit must be used within CopilotKitProvider");
spy.mockRestore();
});
it("useFrontendTool throws when called outside CopilotKitProvider", () => {
function TestComponent() {
useFrontendTool({
name: "orphan-tool",
description: "No provider",
parameters: {},
handler: async () => "fail",
});
return null;
}
const spy = vi.spyOn(console, "error").mockImplementation(() => {});
expect(() => {
render(<TestComponent />);
}).toThrow("useCopilotKit must be used within CopilotKitProvider");
spy.mockRestore();
});
it("useThreads throws when called outside CopilotKitProvider", () => {
function TestComponent() {
useThreads({ agentId: "test-agent" });
return null;
}
const spy = vi.spyOn(console, "error").mockImplementation(() => {});
expect(() => {
render(<TestComponent />);
}).toThrow("useCopilotKit must be used within CopilotKitProvider");
spy.mockRestore();
});
it("useHumanInTheLoop throws when called outside CopilotKitProvider", () => {
function TestComponent() {
useHumanInTheLoop();
return null;
}
const spy = vi.spyOn(console, "error").mockImplementation(() => {});
expect(() => {
render(<TestComponent />);
}).toThrow("useCopilotKit must be used within CopilotKitProvider");
spy.mockRestore();
});
it("useInterrupt throws when called outside CopilotKitProvider", () => {
function TestComponent() {
useInterrupt();
return null;
}
const spy = vi.spyOn(console, "error").mockImplementation(() => {});
expect(() => {
render(<TestComponent />);
}).toThrow("useCopilotKit must be used within CopilotKitProvider");
spy.mockRestore();
});
});
});