-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathacp-test-utils.ts
More file actions
353 lines (312 loc) · 13.4 KB
/
Copy pathacp-test-utils.ts
File metadata and controls
353 lines (312 loc) · 13.4 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
import {CodexAcpClient} from '../CodexAcpClient';
import {type CodexConnectionEvent, CodexAppServerClient} from '../CodexAppServerClient';
import {startCodexConnection} from "../CodexJsonRpcConnection";
import {CodexAcpServer, type SessionState} from "../CodexAcpServer";
import type {AgentSideConnection, RequestPermissionResponse} from "@agentclientprotocol/sdk";
import type {ServerNotification} from "../app-server";
import type {MessageConnection} from "vscode-jsonrpc/node";
import path from "node:path";
import fs from "node:fs";
import os from "node:os";
import {AgentMode} from "../AgentMode";
import {expect, vi} from "vitest";
export type MethodCallEvent = { method: string; args: any[] };
export interface SmartMockConfig {
returnValues?: Map<string, () => any>;
}
export function createSmartMock<T extends object>(
onCall: (event: MethodCallEvent) => void,
config?: SmartMockConfig
) {
return new Proxy({} as T, {
get(_, prop) {
return (...args: any[]) => {
onCall({ method: String(prop), args });
const returnValueFn = config?.returnValues?.get(String(prop));
if (returnValueFn) {
return returnValueFn();
}
return { mock: "Mocked return" };
};
}
});
}
export interface TestFixture {
getCodexAppServerClient(): CodexAppServerClient,
getCodexAcpClient(): CodexAcpClient,
getCodexAcpAgent(): CodexAcpServer,
onCodexConnectionEvent(handler: (event: CodexConnectionEvent) => void): void,
getCodexConnectionEvents(ignoredFields: string[], options?: CodexConnectionDumpOptions): CodexConnectionEvent[],
getCodexConnectionDump(ignoredFields: string[], options?: CodexConnectionDumpOptions): string,
clearCodexConnectionDump(): void,
onAcpConnectionEvent(handler: (event: MethodCallEvent) => void): void,
getAcpConnectionEvents(ignoredFields: string[]): MethodCallEvent[],
getAcpConnectionDump(ignoredFields: string[]): string,
clearAcpConnectionDump(): void,
}
export interface CodexConnectionDumpOptions {
placeholderResponseMethods?: string[];
}
export interface AcpConnectionConfig {
connection: AgentSideConnection;
events: MethodCallEvent[];
eventHandlers: ((event: MethodCallEvent) => void)[];
}
export interface ConnectionConfig {
connection: MessageConnection;
getExitCode: () => number | null;
acpConnection?: AcpConnectionConfig;
}
export function createBaseTestFixture(config: ConnectionConfig): TestFixture {
const acpConnectionEvents = config.acpConnection?.events ?? [];
const acpEventHandlers = config.acpConnection?.eventHandlers ?? [];
const acpConnection = config.acpConnection?.connection ?? createSmartMock<AgentSideConnection>((event) => {
acpConnectionEvents.push(event);
acpEventHandlers.forEach(handler => handler(event));
});
const codexAppServerClient = new CodexAppServerClient(config.connection);
const codexAcpClient = new CodexAcpClient(codexAppServerClient);
const codexAcpAgent = new CodexAcpServer(acpConnection, codexAcpClient, undefined, config.getExitCode);
const transportEvents: CodexConnectionEvent[] = [];
const codexEventHandlers: ((event: CodexConnectionEvent) => void)[] = [];
codexAppServerClient.onClientTransportEvent((event) => {
transportEvents.push(event);
codexEventHandlers.forEach(handler => handler(event));
});
return {
getCodexAcpAgent(): CodexAcpServer {
return codexAcpAgent;
},
getCodexAcpClient(): CodexAcpClient {
return codexAcpClient;
},
getCodexConnectionEvents(ignoredFields: string[], options?: CodexConnectionDumpOptions): CodexConnectionEvent[] {
const placeholderResponseMethods = new Set(options?.placeholderResponseMethods ?? []);
const pendingRequestMethods: string[] = [];
return transportEvents.flatMap((event) => {
switch (event.eventType) {
case "request":
pendingRequestMethods.push(event.method);
break;
case "response":
const requestMethod = pendingRequestMethods.shift();
if (requestMethod && placeholderResponseMethods.has(requestMethod)) {
return [{
eventType: "response" as const,
placeholder: requestMethod,
} as CodexConnectionEvent];
}
break;
}
return [anonymizeValue(event, [], new Set(ignoredFields)) as CodexConnectionEvent];
});
},
getCodexConnectionDump(ignoredFields: string[], options?: CodexConnectionDumpOptions): string {
const filteredEvents = this.getCodexConnectionEvents(ignoredFields, options);
return createArrayDump(filteredEvents, []);
},
onCodexConnectionEvent(handler: (event: CodexConnectionEvent) => void): void {
codexEventHandlers.push(handler);
},
getCodexAppServerClient(): CodexAppServerClient {
return codexAppServerClient;
},
clearCodexConnectionDump(): void {
transportEvents.splice(0, transportEvents.length);
},
onAcpConnectionEvent(handler: (event: MethodCallEvent) => void): void {
acpEventHandlers.push(handler);
},
getAcpConnectionEvents(ignoredFields: string[]): MethodCallEvent[] {
return acpConnectionEvents.map(event => anonymizeValue(event, [], new Set(ignoredFields)) as MethodCallEvent);
},
getAcpConnectionDump(ignoredFields: string[]): string {
return createArrayDump(this.getAcpConnectionEvents(ignoredFields), []);
},
clearAcpConnectionDump() {
acpConnectionEvents.splice(0, acpConnectionEvents.length);
}
};
}
/**
* Creates a test fixture with a real Codex connection.
* Use for integration tests that need to interact with the actual Codex binary.
*/
export function createTestFixture(): TestFixture {
const pathToCodex = path.resolve(process.cwd(), "node_modules", ".bin", process.platform === 'win32' ? "codex.cmd" : "codex");
if (!fs.existsSync(pathToCodex)) {
throw new Error(`Codex binary not found at ${pathToCodex}. Did you run 'npm install'?`);
}
const codexHome = createTestCodexHome();
const codexConnection = startCodexConnection(pathToCodex, {
...process.env,
CODEX_HOME: codexHome,
});
codexConnection.process.on("exit", () => {
removeDirectoryWithRetry(codexHome);
});
return createBaseTestFixture({
connection: codexConnection.connection,
getExitCode: () => codexConnection.process.exitCode
});
}
function createTestCodexHome(): string {
const codexHome = fs.mkdtempSync(path.join(os.tmpdir(), "codex-acp-codex-home-"));
fs.writeFileSync(path.join(codexHome, "config.toml"), 'cli_auth_credentials_store = "file"\n', "utf8");
return codexHome;
}
export function removeDirectoryWithRetry(directory: string): void {
for (let attempt = 0; attempt < 5; attempt += 1) {
try {
fs.rmSync(directory, { recursive: true, force: true });
return;
} catch (error) {
const err = error as NodeJS.ErrnoException;
if (err.code !== "ENOTEMPTY" && err.code !== "EBUSY") {
return;
}
}
}
}
export interface CodexMockTestFixture extends TestFixture {
sendServerNotification(notification: ServerNotification | Record<string, unknown>): void,
sendServerRequest<T>(method: string, params: unknown): Promise<T>,
setPermissionResponse(response: RequestPermissionResponse): void,
}
/**
* Creates a test fixture with a mock Codex connection.
* Use for unit tests that don't need a real Codex binary.
* Provides `sendServerNotification()` to simulate server notifications.
* Provides `sendServerRequest()` to simulate server-initiated requests (e.g., approval requests).
* Provides `setPermissionResponse()` to control ACP permission dialog responses.
*/
export function createCodexMockTestFixture(): CodexMockTestFixture {
let unhandledNotificationHandler: ((notification: any) => void) | null = null;
const requestHandlers = new Map<string, (params: unknown) => Promise<unknown>>();
// State for controlling permission responses
const permissionState: { response: RequestPermissionResponse } = {
response: { outcome: { outcome: 'cancelled' } }
};
const mockCodexConnection = {
sendRequest: () => Promise.resolve(undefined),
onUnhandledNotification: (handler: (notification: any) => void) => {
unhandledNotificationHandler = handler;
},
onNotification: () => {},
onRequest: (type: { method: string }, handler: (params: unknown) => Promise<unknown>) => {
requestHandlers.set(type.method, handler);
},
end: () => {},
} as unknown as MessageConnection;
// Create ACP connection with configurable permission response
const acpConnectionEvents: MethodCallEvent[] = [];
const acpEventHandlers: ((event: MethodCallEvent) => void)[] = [];
const returnValues = new Map<string, () => any>();
returnValues.set('requestPermission', () => permissionState.response);
const acpConnection = createSmartMock<AgentSideConnection>((event) => {
acpConnectionEvents.push(event);
acpEventHandlers.forEach(handler => handler(event));
}, { returnValues });
const baseFixture = createBaseTestFixture({
connection: mockCodexConnection,
getExitCode: () => null,
acpConnection: {
connection: acpConnection,
events: acpConnectionEvents,
eventHandlers: acpEventHandlers,
}
});
return {
...baseFixture,
sendServerNotification(notification: ServerNotification | Record<string, unknown>): void {
if (unhandledNotificationHandler) {
unhandledNotificationHandler(notification);
}
},
async sendServerRequest<T>(method: string, params: unknown): Promise<T> {
const handler = requestHandlers.get(method);
if (!handler) {
throw new Error(`No handler registered for ${method}`);
}
return await handler(params) as T;
},
setPermissionResponse(response: RequestPermissionResponse): void {
permissionState.response = response;
},
};
}
export function createObjectDump(obj: any, anonymizedFields: string[] = []) {
return JSON.stringify(anonymizeValue(obj, [], new Set(anonymizedFields)), null, 2);
}
export function createArrayDump(objects: any[], anonymizedFields: string[]): string {
return objects.map(event => createObjectDump(event, anonymizedFields)).join("\n");
}
function anonymizeValue(value: any, path: string[], fieldsToAnonymize: Set<string>): any {
if (value === null || typeof value !== "object") {
return value;
}
if (Array.isArray(value)) {
return value.map((item, index) => anonymizeValue(item, [...path, String(index)], fieldsToAnonymize));
}
return Object.fromEntries(
Object.entries(value).map(([key, val]) => {
const nextPath = [...path, key];
const pathKey = nextPath.join(".");
if (fieldsToAnonymize.has(key) || fieldsToAnonymize.has(pathKey)) {
return [key, key];
}
return [key, anonymizeValue(val, nextPath, fieldsToAnonymize)];
})
);
}
/**
* Creates a default SessionState for use in tests.
* Override specific fields as needed.
*/
export function createTestSessionState(overrides?: Partial<SessionState>): SessionState {
return {
currentTurnId: null,
lastTokenUsage: null,
totalTokenUsage: null,
modelContextWindow: null,
rateLimits: null,
account: null,
cwd: "/test/cwd",
sessionId: "session-id",
currentModelId: "model-id[effort]",
supportedReasoningEfforts: [],
supportedInputModalities: ["text", "image"],
agentMode: AgentMode.DEFAULT_AGENT_MODE,
...overrides,
};
}
export async function setupPromptAndSendNotifications(
fixture: CodexMockTestFixture,
sessionId: string,
sessionState: SessionState,
notifications: ServerNotification[]
): Promise<void> {
const codexAcpAgent = fixture.getCodexAcpAgent();
const codexAppServerClient = fixture.getCodexAppServerClient();
const turn = { id: "turn-id", items: [], status: "inProgress" as const, error: null };
codexAppServerClient.turnStart = vi.fn().mockResolvedValue({
turn,
});
codexAppServerClient.awaitTurnCompleted = vi.fn().mockResolvedValue({
threadId: sessionId,
turn: { ...turn, status: "completed" },
});
vi.spyOn(codexAcpAgent, "getSessionState").mockReturnValue(sessionState);
await codexAcpAgent.prompt({
sessionId,
prompt: [{ type: "text", text: "test prompt" }],
});
fixture.clearAcpConnectionDump();
for (const notification of notifications) {
fixture.sendServerNotification(notification);
}
await vi.waitFor(() => {
const dump = fixture.getAcpConnectionDump([]);
expect(dump.length).toBeGreaterThan(0);
});
}