-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathCodexAcpClient.test.ts
More file actions
498 lines (403 loc) · 22 KB
/
Copy pathCodexAcpClient.test.ts
File metadata and controls
498 lines (403 loc) · 22 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
// noinspection ES6RedundantAwait
import {describe, expect, it, vi, beforeEach} from 'vitest';
import type {CodexAuthRequest} from "../../CodexAuthMethod";
import type * as acp from "@agentclientprotocol/sdk";
import {createTestFixture, createCodexMockTestFixture, createTestSessionState, type TestFixture} from "../acp-test-utils";
import type {ServerNotification} from "../../app-server";
import type {SessionState} from "../../CodexAcpServer";
import {AgentMode} from "../../AgentMode";
import type {ListMcpServerStatusResponse, Model, SkillsListResponse} from "../../app-server/v2";
import {ModelId} from "../../ModelId";
describe('ACP server test', { timeout: 40_000 }, () => {
let fixture: TestFixture;
beforeEach(() => {
fixture = createTestFixture();
vi.clearAllMocks();
});
const ignoredFields = ["thread", "cwd", "id", "createdAt", "path", "threadId", "userAgent", "sandbox", "conversationId", "origins", "supportedReasoningEfforts", "reasoningEffort", "model"];
it.skip('should start conversation', async () => {
const codexAcpAgent = fixture.getCodexAcpAgent();
await codexAcpAgent.initialize({protocolVersion: 1});
fixture.getCodexAcpClient().authRequired = vi.fn().mockResolvedValue(false);
const newSessionResponse = await codexAcpAgent.newSession({cwd: "", mcpServers: []});
// noinspection ES6MissingAwait - we're only check initialization
codexAcpAgent.prompt({sessionId: newSessionResponse.sessionId, prompt: [{type: "text", text: "Hi!"}]});
const transportDump = fixture.getCodexConnectionDump(ignoredFields);
await expect(transportDump).toMatchFileSnapshot("data/start-conversation.json");
});
it('should throw error without authentication', async () => {
const codexAcpAgent = fixture.getCodexAcpAgent();
await codexAcpAgent.initialize({protocolVersion: 1});
await fixture.getCodexAcpClient().logout();
fixture.clearCodexConnectionDump();
await expect(
codexAcpAgent.newSession({cwd: "", mcpServers: []})
).rejects.toThrow("Authentication required");
const transportDump = fixture.getCodexConnectionDump(ignoredFields);
await expect(transportDump).toMatchFileSnapshot("data/auth-failed.json");
});
it('should authenticate with key', async () => {
const codexAcpAgent = fixture.getCodexAcpAgent();
await codexAcpAgent.initialize({protocolVersion: 1});
await fixture.getCodexAcpClient().logout();
fixture.clearCodexConnectionDump();
const authRequest: CodexAuthRequest = { methodId: "api-key", _meta: { "api-key": { apiKey: "TOKEN" }}}
await codexAcpAgent.authenticate(authRequest);
const newSessionResponse = await codexAcpAgent.newSession({cwd: "", mcpServers: []});
expect(newSessionResponse.sessionId).toBeDefined()
const transportDump = fixture.getCodexConnectionDump([...ignoredFields, "upgrade"]);
await expect(transportDump).toMatchFileSnapshot("data/auth-with-key.json");
});
it('should authenticate with a gateway', async () => {
const codexAcpAgent = fixture.getCodexAcpAgent();
await codexAcpAgent.initialize({protocolVersion: 1});
await fixture.getCodexAcpClient().logout();
const authRequest: CodexAuthRequest = {
methodId: "gateway",
_meta: {
"gateway": {
baseUrl: "https://www.example.com",
headers: {
"Custom-Auth-Header": "TOKEN"
}
}
}
};
await codexAcpAgent.authenticate(authRequest);
expect(await fixture.getCodexAcpClient().authRequired()).toBe(false);
const newSessionResponse = await codexAcpAgent.newSession({cwd: "", mcpServers: []});
expect(newSessionResponse.sessionId).toBeDefined()
})
function loadNotifications(){
//TODO collect logs form dev run and then load them from file to speedup
const serverNotifications: ServerNotification[] = [
{ method: "item/agentMessage/delta", params: { threadId: "string", turnId: "string", itemId: "string", delta: "He", }},
{ method: "item/agentMessage/delta", params: { threadId: "string", turnId: "string", itemId: "string", delta: "ll", }},
{ method: "item/agentMessage/delta", params: { threadId: "string", turnId: "string", itemId: "string", delta: "o!", }},
];
function onServerNotification(_sessionId: string, callback: (event: ServerNotification) => void){
for (const notification of serverNotifications) {
callback(notification);
}
}
return onServerNotification;
}
it('should map events from dump', async () => {
fixture.getCodexAppServerClient().onServerNotification = loadNotifications();
const codexAcpAgent = fixture.getCodexAcpAgent();
fixture.getCodexAppServerClient().turnStart = vi.fn().mockResolvedValue({
turn: { id: "turn-id", items: [], status: "inProgress", error: null }
});
fixture.getCodexAppServerClient().awaitTurnCompleted = vi.fn().mockResolvedValue({
threadId: "id",
turn: { id: "turn-id", items: [], status: "completed", error: null }
});
const sessionState: SessionState = createTestSessionState({
sessionId: "id",
currentModelId: "model-id[effort]",
agentMode: AgentMode.DEFAULT_AGENT_MODE
});
vi.spyOn(codexAcpAgent, "getSessionState").mockReturnValue(sessionState);
await codexAcpAgent.prompt({ sessionId: "id", prompt: [{type: "text", text: ""}] });
await expect(fixture.getAcpConnectionDump([])).toMatchFileSnapshot("data/output-acp-events.json");
});
it('should not duplicate messages on follow-up prompts', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpAgent = mockFixture.getCodexAcpAgent();
mockFixture.getCodexAppServerClient().turnStart = vi.fn().mockResolvedValue({
turn: { id: "turn-id", items: [], status: "inProgress", error: null }
});
mockFixture.getCodexAppServerClient().awaitTurnCompleted = vi.fn().mockResolvedValue({
threadId: "id",
turn: { id: "turn-id", items: [], status: "completed", error: null }
});
const sessionState: SessionState = createTestSessionState({
sessionId: "id",
currentModelId: "model-id[effort]",
agentMode: AgentMode.DEFAULT_AGENT_MODE
});
vi.spyOn(codexAcpAgent, "getSessionState").mockReturnValue(sessionState);
// First prompt - registers first notification handler
await codexAcpAgent.prompt({ sessionId: "id", prompt: [{type: "text", text: "First message"}] });
// Follow-up prompt - should NOT accumulate handlers
await codexAcpAgent.prompt({ sessionId: "id", prompt: [{type: "text", text: "Follow-up message"}] });
mockFixture.clearAcpConnectionDump();
// Trigger notifications after both prompts - should produce only 3 events, not 6
const serverNotifications: ServerNotification[] = [
{ method: "item/agentMessage/delta", params: { threadId: "string", turnId: "string", itemId: "string", delta: "He", }},
{ method: "item/agentMessage/delta", params: { threadId: "string", turnId: "string", itemId: "string", delta: "ll", }},
{ method: "item/agentMessage/delta", params: { threadId: "string", turnId: "string", itemId: "string", delta: "o!", }},
];
for (const notification of serverNotifications) {
mockFixture.sendServerNotification(notification);
}
// Wait for async handlers to complete
await vi.waitFor(() => {
const dump = mockFixture.getAcpConnectionDump([]);
expect(dump.length).toBeGreaterThan(0);
});
await expect(mockFixture.getAcpConnectionDump([])).toMatchFileSnapshot("data/follow-up-no-duplicates.json");
});
it('should handle multiple sessions independently', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpAgent = mockFixture.getCodexAcpAgent();
mockFixture.getCodexAppServerClient().turnStart = vi.fn().mockResolvedValue({
turn: { id: "turn-id", items: [], status: "inProgress", error: null }
});
mockFixture.getCodexAppServerClient().awaitTurnCompleted = vi.fn().mockResolvedValue({
threadId: "id",
turn: { id: "turn-id", items: [], status: "completed", error: null }
});
const sessionState1: SessionState = createTestSessionState({
sessionId: "session-1",
currentModelId: "model-id[effort]",
agentMode: AgentMode.DEFAULT_AGENT_MODE
});
const sessionState2: SessionState = createTestSessionState({
sessionId: "session-2",
currentModelId: "model-id[effort]",
agentMode: AgentMode.DEFAULT_AGENT_MODE
});
vi.spyOn(codexAcpAgent, "getSessionState").mockImplementation((sessionId: string) => {
return sessionId === "session-1" ? sessionState1 : sessionState2;
});
// Start prompts for two different sessions
await codexAcpAgent.prompt({ sessionId: "session-1", prompt: [{type: "text", text: "Message to session 1"}] });
await codexAcpAgent.prompt({ sessionId: "session-2", prompt: [{type: "text", text: "Message to session 2"}] });
mockFixture.clearAcpConnectionDump();
// Trigger notifications - both session handlers should receive them
const serverNotifications: ServerNotification[] = [
{ method: "item/agentMessage/delta", params: { threadId: "string", turnId: "string", itemId: "string", delta: "Hello", }},
];
for (const notification of serverNotifications) {
mockFixture.sendServerNotification(notification);
}
// Wait for async handlers to complete
await vi.waitFor(() => {
const dump = mockFixture.getAcpConnectionDump([]);
expect(dump.length).toBeGreaterThan(0);
});
// Should have 2 events - one for each session's handler
await expect(mockFixture.getAcpConnectionDump([])).toMatchFileSnapshot("data/multiple-sessions.json");
});
it('should send attachments as prompt items', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpAgent = mockFixture.getCodexAcpAgent();
const codexAppServerClient = mockFixture.getCodexAppServerClient();
vi.spyOn(codexAppServerClient, "awaitTurnCompleted").mockResolvedValue({
threadId: "session-id",
turn: { id: "turn-id", items: [], status: "completed", error: null }
});
const sessionState: SessionState = createTestSessionState();
vi.spyOn(codexAcpAgent, "getSessionState").mockReturnValue(sessionState);
const prompt: acp.ContentBlock[] = [
{ type: "text", text: "Hello" },
{ type: "image", mimeType: "image/png", data: "abc123", uri: "https://example.com/image.png" },
{ type: "resource_link", name: "report.txt", uri: "file:///tmp/report.txt" },
{ type: "resource", resource: { uri: "file:///tmp/notes.txt", text: "Notes body" } as acp.EmbeddedResourceResource },
];
await codexAcpAgent.prompt({ sessionId: "session-id", prompt });
await expect(mockFixture.getCodexConnectionDump(ignoredFields)).toMatchFileSnapshot("data/send-attachments-turn-start.json");
});
async function createSessionInSeparateInstance(): Promise<string> {
const initFixture = createTestFixture();
initFixture.getCodexAcpClient().authRequired = vi.fn().mockResolvedValue(false);
await initFixture.getCodexAcpAgent().initialize({protocolVersion: 1});
const newSessionResponse = await initFixture.getCodexAcpAgent().newSession({
cwd: "",
mcpServers: []
});
return newSessionResponse.sessionId;
}
it('should resume session', async () => {
const sessionId = await createSessionInSeparateInstance();
await fixture.getCodexAcpAgent().initialize({protocolVersion: 1});
fixture.getCodexAcpClient().authRequired = vi.fn().mockResolvedValue(false);
fixture.clearCodexConnectionDump();
await fixture.getCodexAcpAgent().unstable_resumeSession({
cwd: "",
sessionId: sessionId
});
await expect(fixture.getCodexConnectionDump(ignoredFields.concat("data", "model"))).toMatchFileSnapshot("data/thread-resume.json");
const promptResult: Promise<acp.PromptResponse> = fixture.getCodexAcpAgent().prompt({
sessionId: sessionId,
prompt: []
});
expect(promptResult).toBeDefined();
});
it('should fail on wrong sessionId', async () => {
const sessionId = "not-existing-session";
await fixture.getCodexAcpAgent().initialize({protocolVersion: 1});
fixture.getCodexAcpClient().authRequired = vi.fn().mockResolvedValue(false);
fixture.clearCodexConnectionDump();
await expect(
fixture.getCodexAcpAgent().unstable_resumeSession({cwd: "", sessionId: sessionId})
).rejects.toThrow("invalid thread id");
});
it('should return available builtin commands', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpAgent = mockFixture.getCodexAcpAgent();
vi.spyOn(mockFixture.getCodexAcpClient(), "listSkills").mockResolvedValue({ data: [] });
// @ts-expect-error - exercising private helper
await codexAcpAgent.availableCommands.publish("session-id");
await expect(mockFixture.getAcpConnectionDump([])).toMatchFileSnapshot("data/available-commands-build-in.json");
});
it('should return available commands from skills list', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpAgent = mockFixture.getCodexAcpAgent();
vi.spyOn(mockFixture.getCodexAcpClient(), "listSkills").mockResolvedValue({
data: [{
cwd: "/workspace",
skills: [{
name: "build",
description: "Build the project",
shortDescription: "Build",
path: "/workspace",
scope: "user",
enabled: true
}],
errors: []
}]
});
// @ts-expect-error - exercising private helper
await codexAcpAgent.availableCommands.publish("session-id");
await expect(mockFixture.getAcpConnectionDump([])).toMatchFileSnapshot("data/available-commands-skills.json");
});
it('handles builtin slash command locally', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpAgent = mockFixture.getCodexAcpAgent();
const sessionState: SessionState = createTestSessionState();
vi.spyOn(codexAcpAgent, "getSessionState").mockReturnValue(sessionState);
await codexAcpAgent.prompt({ sessionId: "session-id", prompt: [{ type: "text", text: "/status" }] });
await expect(mockFixture.getAcpConnectionDump([])).toMatchFileSnapshot("data/command-status.json");
});
it('handles logout command', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpAgent = mockFixture.getCodexAcpAgent();
const sessionState: SessionState = createTestSessionState();
const logoutSpy = vi.spyOn(mockFixture.getCodexAcpClient(), "logout").mockResolvedValue(undefined);
// @ts-expect-error - exercising private helper
const handled = await codexAcpAgent.availableCommands.handleCommand({ name: "logout", input: null }, sessionState);
expect(handled).toBe(true);
expect(logoutSpy).toHaveBeenCalledTimes(1);
await expect(mockFixture.getAcpConnectionDump([])).toMatchFileSnapshot("data/command-logout.json");
});
it('handles skills command', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpAgent = mockFixture.getCodexAcpAgent();
const sessionState: SessionState = createTestSessionState();
const skillsResponse: SkillsListResponse = {
data: [{
cwd: "/workspace",
skills: [
{ name: "build", description: "Build the project", shortDescription: "Build", path: "/workspace/build", scope: "user", enabled: true },
{ name: "deploy", description: "Deploy the service", path: "/workspace/deploy", scope: "repo", enabled: true }
],
errors: []
}]
};
const skillsSpy = vi.spyOn(mockFixture.getCodexAcpClient(), "listSkills").mockResolvedValue(skillsResponse);
// @ts-expect-error - exercising private helper
const handled = await codexAcpAgent.availableCommands.handleCommand({ name: "skills", input: null }, sessionState);
expect(handled).toBe(true);
expect(skillsSpy).toHaveBeenCalledTimes(1);
await expect(mockFixture.getAcpConnectionDump([])).toMatchFileSnapshot("data/command-skills.json");
});
it('handles mcp command', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpAgent = mockFixture.getCodexAcpAgent();
const sessionState: SessionState = createTestSessionState();
const mcpResponse: ListMcpServerStatusResponse = {
data: [
{
name: "fs",
tools: { listFiles: { name: "listFiles", inputSchema: { type: "object" } } },
resources: [{ name: "workspace", uri: "file:///workspace" }],
resourceTemplates: [],
authStatus: "bearerToken"
},
{
name: "browser",
tools: {},
resources: [],
resourceTemplates: [],
authStatus: "notLoggedIn"
}
],
nextCursor: null
};
const mcpSpy = vi.spyOn(mockFixture.getCodexAcpClient(), "listMcpServers").mockResolvedValue(mcpResponse);
// @ts-expect-error - exercising private helper
const handled = await codexAcpAgent.availableCommands.handleCommand({ name: "mcp", input: null }, sessionState);
expect(handled).toBe(true);
expect(mcpSpy).toHaveBeenCalledTimes(1);
await expect(mockFixture.getAcpConnectionDump([])).toMatchFileSnapshot("data/command-mcp.json");
});
const mockModels: Model[] = [
{
id: '5.2-codex',
model: '5.2-codex',
displayName: 'Codex 5.2',
description: 'Coding model',
supportedReasoningEfforts: [
{ reasoningEffort: 'high', description: 'Deep' },
{ reasoningEffort: 'medium', description: 'Balanced' }
],
defaultReasoningEffort: 'medium',
supportsPersonality: false,
isDefault: false,
upgrade: null,
inputModalities: []
},
{
id: '5.1',
model: '5.1',
displayName: 'Standard 5.1',
description: 'Standard model',
supportedReasoningEfforts: [
{ reasoningEffort: 'low', description: 'Fast' }
],
defaultReasoningEffort: 'low',
supportsPersonality: false,
isDefault: true,
upgrade: null,
inputModalities: []
}
];
it('should fallback to the default model when modelId is null', () => {
const result = fixture.getCodexAcpClient().createModelId(mockModels, null, 'low');
expect(result).toEqual(ModelId.create('5.1', 'low'));
});
it('should fallback to the model-specific effort when reasoningEffort is null', () => {
const result = fixture.getCodexAcpClient().createModelId(mockModels, '5.2-codex', null);
expect(result).toEqual(ModelId.create('5.2-codex', 'medium'));
});
it ('should disable resasoning.summary if key authorization is used', async () => {
const mockFixture = createCodexMockTestFixture();
const turnStartSpy = vi.spyOn(mockFixture.getCodexAppServerClient(), "turnStart").mockResolvedValue({
turn: { id: "turn-id", items: [], status: "inProgress", error: null }
});
vi.spyOn(mockFixture.getCodexAppServerClient(), "awaitTurnCompleted").mockResolvedValue({
threadId: "id", turn: { id: "turn-id", items: [], status: "completed", error: null }
});
vi.spyOn(mockFixture.getCodexAcpAgent(), "getSessionState").mockReturnValue(
createTestSessionState({ account: { type: "apiKey" } })
);
await mockFixture.getCodexAcpAgent().prompt({ sessionId: "id", prompt: [{ type: "text", text: "test" }] });
expect(turnStartSpy).toHaveBeenCalledWith(expect.objectContaining({ summary: "none" }));
});
it ('should not disable resasoning.summary by default', async () => {
const mockFixture = createCodexMockTestFixture();
const turnStartSpy = vi.spyOn(mockFixture.getCodexAppServerClient(), "turnStart").mockResolvedValue({
turn: { id: "turn-id", items: [], status: "inProgress", error: null }
});
vi.spyOn(mockFixture.getCodexAppServerClient(), "awaitTurnCompleted").mockResolvedValue({
threadId: "id", turn: { id: "turn-id", items: [], status: "completed", error: null }
});
vi.spyOn(mockFixture.getCodexAcpAgent(), "getSessionState").mockReturnValue(
createTestSessionState({ account: { type: "chatgpt", email: "test@example.com", planType: "pro" } })
);
await mockFixture.getCodexAcpAgent().prompt({ sessionId: "id", prompt: [{ type: "text", text: "test" }] });
expect(turnStartSpy).toHaveBeenCalledWith(expect.objectContaining({ summary: null }));
});
});