forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-utils.ts
More file actions
407 lines (358 loc) · 10.8 KB
/
Copy pathtest-utils.ts
File metadata and controls
407 lines (358 loc) · 10.8 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
import { Message } from "@ag-ui/client";
import { vi } from "vitest";
import { DynamicSuggestionsConfig, FrontendTool } from "../types";
export interface MockAgentOptions {
messages?: Message[];
newMessages?: Message[];
error?: Error | string;
runAgentDelay?: number;
runAgentCallback?: (input: any) => void;
agentId?: string;
threadId?: string;
state?: Record<string, any>;
}
export class MockAgent {
public messages: Message[] = [];
public state: Record<string, any> = {};
public agentId?: string;
public threadId?: string;
public addMessages = vi.fn((messages: Message[]) => {
this.messages.push(...messages);
});
public addMessage = vi.fn((message: Message) => {
this.messages.push(message);
// Also track on parent if this is a clone
if (this._parentAgent) {
this._parentAgent.addMessage(message);
}
});
public abortRun = vi.fn();
public clone = vi.fn(() => this._cloneImpl());
private newMessages: Message[];
private error?: Error | string;
private runAgentDelay: number;
public runAgentCallback?: (input: any) => void;
public runAgentCalls: any[] = [];
private _parentAgent?: MockAgent;
constructor(options: MockAgentOptions = {}) {
this.messages = options.messages || [];
this.newMessages = options.newMessages || [];
this.error = options.error;
this.runAgentDelay = options.runAgentDelay || 0;
this.runAgentCallback = options.runAgentCallback;
this.agentId = options.agentId;
this.threadId = options.threadId;
this.state = options.state || {};
}
async runAgent(
input: any,
subscriber?: any,
): Promise<{ newMessages: Message[] }> {
this.runAgentCalls.push(input);
// Also track on parent if this is a clone
if (this._parentAgent) {
this._parentAgent.runAgentCalls.push(input);
}
if (this.runAgentCallback) {
this.runAgentCallback(input);
}
if (this.runAgentDelay > 0) {
await new Promise((resolve) => setTimeout(resolve, this.runAgentDelay));
}
if (this.error) {
throw this.error;
}
// If there's a subscriber with onMessagesChanged, call it with the messages
if (subscriber?.onMessagesChanged && this.newMessages.length > 0) {
// Trigger the subscriber callback with messages
subscriber.onMessagesChanged({
messages: [...this.messages, ...this.newMessages],
});
}
// Simulate real agent behavior: during runAgent, streamed messages are
// added to agent.messages before the promise resolves. This ensures
// processAgentResult can find parent messages via findIndex.
this.messages.push(...this.newMessages);
return { newMessages: this.newMessages };
}
private _cloneImpl(): MockAgent {
const cloned = new MockAgent({
messages: [...this.messages],
newMessages: [...this.newMessages],
error: this.error,
runAgentDelay: this.runAgentDelay,
runAgentCallback: this.runAgentCallback,
agentId: this.agentId,
threadId: this.threadId,
state: JSON.parse(JSON.stringify(this.state)),
});
// Link the clone back to the parent so calls are visible
cloned._parentAgent = this;
return cloned;
}
// Provide a no-op subscribe API so core can attach state listeners
// without errors during tests.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public subscribe(_subscriber?: any): { unsubscribe: () => void } {
return { unsubscribe: () => {} };
}
setNewMessages(messages: Message[]): void {
this.newMessages = messages;
}
}
export function createMessage(overrides: Partial<Message> = {}): Message {
return {
id: `msg-${Math.random().toString(36).substr(2, 9)}`,
role: "user",
content: "Test message",
...overrides,
} as Message;
}
export function createAssistantMessage(
overrides: Partial<Message> = {},
): Message {
return createMessage({
role: "assistant",
content: "Assistant message",
...overrides,
});
}
export function createToolCallMessage(
toolCallName: string,
args: any = {},
overrides: Partial<Message> = {},
): Message {
const toolCallId = `tool-call-${Math.random().toString(36).substr(2, 9)}`;
return createAssistantMessage({
content: "",
toolCalls: [
{
id: toolCallId,
type: "function",
function: {
name: toolCallName,
arguments: JSON.stringify(args),
},
},
],
...overrides,
});
}
export function createToolResultMessage(
toolCallId: string,
content: string,
overrides: Partial<Message> = {},
): Message {
return createMessage({
role: "tool",
content,
toolCallId,
...overrides,
});
}
export function createTool<T extends Record<string, unknown>>(
overrides: Partial<FrontendTool<T>> = {},
): FrontendTool<T> {
return {
name: `tool-${Math.random().toString(36).substr(2, 9)}`,
description: "Test tool",
handler: vi.fn(async () => "Tool result"),
followUp: false, // Default to false to avoid unexpected recursion in tests
...overrides,
};
}
export function createMultipleToolCallsMessage(
toolCalls: Array<{ name: string; args?: any }>,
overrides: Partial<Message> = {},
): Message {
return createAssistantMessage({
content: "",
toolCalls: toolCalls.map((tc) => ({
id: `tool-call-${Math.random().toString(36).substr(2, 9)}`,
type: "function",
function: {
name: tc.name,
arguments: JSON.stringify(tc.args || {}),
},
})),
...overrides,
});
}
export async function waitForCondition(
condition: () => boolean,
timeout: number = 1000,
interval: number = 10,
): Promise<void> {
const start = Date.now();
while (!condition()) {
if (Date.now() - start > timeout) {
throw new Error("Timeout waiting for condition");
}
await new Promise((resolve) => setTimeout(resolve, interval));
}
}
/**
* Helper to create a dynamic suggestions config
*/
export function createSuggestionsConfig(
overrides: Partial<DynamicSuggestionsConfig> = {},
): DynamicSuggestionsConfig {
return {
instructions: "Suggest helpful next actions",
minSuggestions: 1,
maxSuggestions: 3,
available: "always",
providerAgentId: "default",
consumerAgentId: "*",
...overrides,
};
}
/**
* Helper to create a tool call message for copilotkitSuggest
*/
export function createSuggestionToolCall(
suggestions: Array<{ title: string; message: string }>,
overrides: Partial<Message> = {},
): Message {
const toolCallId = `suggest-call-${Math.random().toString(36).substr(2, 9)}`;
return createAssistantMessage({
content: "",
toolCalls: [
{
id: toolCallId,
type: "function",
function: {
name: "copilotkitSuggest",
arguments: JSON.stringify({ suggestions }),
},
},
],
...overrides,
});
}
/**
* Helper to create streaming suggestion messages with partial JSON
* Returns an array of JSON chunks that can be assembled into complete suggestions
*/
export function createStreamingSuggestionChunks(): string[] {
return [
'{"suggestions":[',
'{"title":"First","message":"Do first thing"}',
',{"title":"Second",',
'"message":"Do second thing"}',
',{"title":"Third","message":"Do third thing"}',
"]}",
];
}
export class MockPush {
private callbacks = new Map<string, Function>();
receive(status: string, callback: Function): MockPush {
this.callbacks.set(status, callback);
return this;
}
trigger(status: string, response?: unknown): void {
this.callbacks.get(status)?.(response);
}
}
export class MockChannel {
public topic: string;
public params: Record<string, any>;
public joinPayload: Record<string, any> | null = null;
public pushLog: Array<{ event: string; payload: any; push: MockPush }> = [];
public left = false;
private handlers = new Map<
string,
Array<{ ref: number; callback: (payload: any) => void }>
>();
private joinPush = new MockPush();
private errorHandlers: Array<(reason?: any) => void> = [];
private nextRef = 1;
constructor(topic: string = "", params: Record<string, any> = {}) {
this.topic = topic;
this.params = params;
}
on(event: string, callback: (payload: any) => void): number {
if (!this.handlers.has(event)) {
this.handlers.set(event, []);
}
const ref = this.nextRef++;
this.handlers.get(event)!.push({ ref, callback });
return ref;
}
off(event: string, ref?: number): void {
if (!this.handlers.has(event)) return;
if (ref === undefined) {
this.handlers.delete(event);
} else {
const filtered = this.handlers.get(event)!.filter((h) => h.ref !== ref);
this.handlers.set(event, filtered);
}
}
onError(callback: (reason?: any) => void): void {
this.errorHandlers.push(callback);
}
join(payload?: Record<string, any>): MockPush {
this.joinPayload = payload ?? null;
return this.joinPush;
}
push(event: string, payload: any): MockPush {
const mockPush = new MockPush();
this.pushLog.push({ event, payload, push: mockPush });
return mockPush;
}
leave(): void {
this.left = true;
}
/** Test helper — simulate the server acknowledging, rejecting, or timing out the join. */
triggerJoin(status: "ok" | "error" | "timeout", response?: unknown): void {
this.joinPush.trigger(status, response);
}
/** Test helper — simulate the server pushing an event. */
serverPush(eventType: string, payload: any): void {
for (const { callback } of this.handlers.get(eventType) ?? []) {
callback(payload);
}
}
/** Test helper — simulate the channel crashing server-side. */
triggerError(reason?: string): void {
for (const handler of this.errorHandlers) handler(reason);
}
}
export class MockSocket {
public url: string;
public opts: Record<string, any>;
public connected = false;
public disconnected = false;
public channels: MockChannel[] = [];
private errorHandlers: Array<(error?: any) => void> = [];
private openHandlers: Array<() => void> = [];
constructor(url: string = "", opts: Record<string, any> = {}) {
this.url = url;
this.opts = opts;
}
connect(): void {
this.connected = true;
}
disconnect(): void {
this.disconnected = true;
}
onError(callback: (error?: any) => void): void {
this.errorHandlers.push(callback);
}
onOpen(callback: () => void): void {
this.openHandlers.push(callback);
}
channel(topic: string, params: Record<string, any> = {}): MockChannel {
const ch = new MockChannel(topic, params);
this.channels.push(ch);
return ch;
}
/** Test helper — simulate the WebSocket transport erroring. */
triggerError(error?: any): void {
for (const handler of this.errorHandlers) handler(error);
}
/** Test helper — simulate a successful (re)connection. */
triggerOpen(): void {
for (const handler of this.openHandlers) handler();
}
}