-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathCodexAcpClient.test.ts
More file actions
3422 lines (2983 loc) · 135 KB
/
Copy pathCodexAcpClient.test.ts
File metadata and controls
3422 lines (2983 loc) · 135 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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// noinspection ES6RedundantAwait
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {CODEX_API_KEY_ENV_VAR, OPENAI_API_KEY_ENV_VAR, type CodexAuthRequest} from "../../CodexAuthMethod";
import type * as acp from "@agentclientprotocol/sdk";
import {
createCodexMockTestFixture,
createTestFixture,
createTestModel,
createTestSessionState,
type TestFixture
} from "../acp-test-utils";
import type {ServerNotification} from "../../app-server";
import type {JsonObject} from "../../CodexAcpClient";
import type {SessionState} from "../../CodexAcpServer";
import {AgentMode} from "../../AgentMode";
import type {Model, ReviewStartResponse, ThreadGoal, TurnCompletedNotification, TurnStartParams} from "../../app-server/v2";
import type {RateLimitsMap} from "../../RateLimitsMap";
import {ModelId} from "../../ModelId";
describe('ACP server test', { timeout: 40_000 }, () => {
let fixture: TestFixture;
beforeEach(() => {
fixture = createTestFixture();
vi.clearAllMocks();
});
afterEach(() => {
vi.unstubAllEnvs();
});
const ignoredFields = ["thread", "cwd", "id", "createdAt", "path", "threadId", "userAgent", "sandbox", "conversationId", "origins", "supportedReasoningEfforts", "reasoningEffort", "model", "readOnlyAccess", "approvalsReviewer"];
it('should throw error without authentication', async () => {
const authFixture = createTestFixture();
const codexAcpAgent = authFixture.getCodexAcpAgent();
await codexAcpAgent.initialize({protocolVersion: 1});
await authFixture.getCodexAcpClient().logout();
authFixture.clearCodexConnectionDump();
await expect(
codexAcpAgent.newSession({cwd: "", mcpServers: []})
).rejects.toThrow("Authentication required");
const transportDump = authFixture.getCodexConnectionDump(ignoredFields);
await expect(transportDump).toMatchFileSnapshot("data/auth-failed.json");
});
it('should authenticate with key', async () => {
const keyFixture = createTestFixture();
const codexAcpAgent = keyFixture.getCodexAcpAgent();
await codexAcpAgent.initialize({protocolVersion: 1});
await keyFixture.getCodexAcpClient().logout();
const unauthenticatedResponse = await keyFixture.getCodexAcpAgent().extMethod("authentication/status", {});
expect(unauthenticatedResponse).toEqual({type: "unauthenticated"});
keyFixture.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 transportEvents = keyFixture.getCodexConnectionEvents([...ignoredFields, "upgrade"]);
const transportMethods = transportEvents.flatMap(event => "method" in event ? [event.method] : []);
const loginRequest = transportEvents.find(event =>
event.eventType === "request" &&
"method" in event &&
event.method === "account/login/start"
);
const loginResponse = transportEvents.find(event =>
event.eventType === "response" &&
"type" in event &&
event.type === "apiKey"
);
const threadStartResponse = transportEvents.find(event =>
event.eventType === "response" &&
"modelProvider" in event &&
"approvalPolicy" in event
);
expect(transportMethods).toEqual([
"account/login/start",
"account/read",
"account/updated",
"thread/start",
"model/list",
"thread/started",
"account/read",
"skills/list",
]);
expect(loginRequest).toEqual({
eventType: "request",
method: "account/login/start",
params: {
type: "apiKey",
apiKey: "TOKEN",
}
});
expect(loginResponse).toEqual({
eventType: "response",
type: "apiKey",
});
expect(threadStartResponse).toMatchObject({
eventType: "response",
modelProvider: "openai",
approvalPolicy: "on-request",
approvalsReviewer: "approvalsReviewer",
});
const authenticatedResponse = await keyFixture.getCodexAcpAgent().extMethod("authentication/status", {});
expect(authenticatedResponse).toEqual({type: "api-key"});
await keyFixture.getCodexAcpAgent().logout({});
const logoutResponse = await keyFixture.getCodexAcpAgent().extMethod("authentication/status", {});
expect(logoutResponse).toEqual({type: "unauthenticated"});
});
it('should authenticate with CODEX_API_KEY from the environment', async () => {
const envFixture = createTestFixture();
const codexAcpAgent = envFixture.getCodexAcpAgent();
vi.stubEnv(CODEX_API_KEY_ENV_VAR, "CODEX_ENV_TOKEN");
vi.stubEnv(OPENAI_API_KEY_ENV_VAR, "OPENAI_ENV_TOKEN");
await codexAcpAgent.initialize({protocolVersion: 1});
await envFixture.getCodexAcpClient().logout();
envFixture.clearCodexConnectionDump();
await codexAcpAgent.authenticate({methodId: "api-key"});
const transportEvents = envFixture.getCodexConnectionEvents([]);
const loginRequest = transportEvents.find(event =>
event.eventType === "request" &&
"method" in event &&
event.method === "account/login/start"
);
expect(loginRequest).toEqual({
eventType: "request",
method: "account/login/start",
params: {
type: "apiKey",
apiKey: "CODEX_ENV_TOKEN",
}
});
await expect(codexAcpAgent.extMethod("authentication/status", {})).resolves.toEqual({type: "api-key"});
});
it('should fall back to OPENAI_API_KEY from the environment', async () => {
const envFixture = createTestFixture();
const codexAcpAgent = envFixture.getCodexAcpAgent();
vi.stubEnv(CODEX_API_KEY_ENV_VAR, "");
vi.stubEnv(OPENAI_API_KEY_ENV_VAR, "OPENAI_ENV_TOKEN");
await codexAcpAgent.initialize({protocolVersion: 1});
await envFixture.getCodexAcpClient().logout();
envFixture.clearCodexConnectionDump();
await codexAcpAgent.authenticate({methodId: "api-key"});
const transportEvents = envFixture.getCodexConnectionEvents([]);
const loginRequest = transportEvents.find(event =>
event.eventType === "request" &&
"method" in event &&
event.method === "account/login/start"
);
expect(loginRequest).toEqual({
eventType: "request",
method: "account/login/start",
params: {
type: "apiKey",
apiKey: "OPENAI_ENV_TOKEN",
}
});
await expect(codexAcpAgent.extMethod("authentication/status", {})).resolves.toEqual({type: "api-key"});
});
it('should report a clear error when the selected API key env var is missing', async () => {
const envFixture = createTestFixture();
const codexAcpAgent = envFixture.getCodexAcpAgent();
vi.stubEnv(CODEX_API_KEY_ENV_VAR, "");
vi.stubEnv(OPENAI_API_KEY_ENV_VAR, "");
await expect(codexAcpAgent.authenticate({methodId: "api-key"}))
.rejects.toThrow(`${CODEX_API_KEY_ENV_VAR} or ${OPENAI_API_KEY_ENV_VAR} is not set`);
});
it('should not start ChatGPT login when already authenticated', async () => {
const chatGptFixture = createCodexMockTestFixture();
const codexAppServerClient = chatGptFixture.getCodexAppServerClient();
const accountReadSpy = vi.spyOn(codexAppServerClient, "accountRead").mockResolvedValue({
account: { type: "chatgpt", email: "test@example.com", planType: "pro" },
requiresOpenaiAuth: false,
});
const accountLoginSpy = vi.spyOn(codexAppServerClient, "accountLogin");
await expect(chatGptFixture.getCodexAcpAgent().authenticate({methodId: "chat-gpt"}))
.resolves.toEqual({});
expect(accountReadSpy).toHaveBeenCalledWith({refreshToken: true});
expect(accountLoginSpy).not.toHaveBeenCalled();
});
it('should authenticate with a gateway', async () => {
const gatewayFixture = createTestFixture();
const codexAcpAgent = gatewayFixture.getCodexAcpAgent();
await codexAcpAgent.initialize({
protocolVersion: 1,
clientCapabilities: {
auth: {
_meta: {
gateway: true,
}
}
}
});
await gatewayFixture.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 gatewayFixture.getCodexAcpClient().authRequired()).toBe(false);
const authenticatedResponse = await gatewayFixture.getCodexAcpAgent().extMethod("authentication/status", {});
expect(authenticatedResponse).toEqual({type: "gateway", name: "custom-gateway"});
const newSessionResponse = await codexAcpAgent.newSession({cwd: "", mcpServers: []});
expect(newSessionResponse.sessionId).toBeDefined();
});
it('should show account in /status for api key auth and hide it for gateway auth', async () => {
const authFixture = createTestFixture();
const codexAcpAgent = authFixture.getCodexAcpAgent();
await codexAcpAgent.initialize({
protocolVersion: 1,
clientCapabilities: {
auth: {
_meta: {
gateway: true,
}
}
}
});
await authFixture.getCodexAcpClient().logout();
await codexAcpAgent.authenticate({
methodId: "api-key",
_meta: { "api-key": { apiKey: "TOKEN" } }
});
const apiKeySession = await codexAcpAgent.newSession({cwd: "", mcpServers: []});
authFixture.clearAcpConnectionDump();
await codexAcpAgent.prompt({
sessionId: apiKeySession.sessionId,
prompt: [{ type: "text", text: "/status" }]
});
const apiKeyStatusDump = authFixture.getAcpConnectionDump([]);
expect(apiKeyStatusDump).toContain("**Account:** API key configured");
await codexAcpAgent.authenticate({
methodId: "gateway",
_meta: {
"gateway": {
baseUrl: "https://www.example.com",
headers: {
"Custom-Auth-Header": "TOKEN"
}
}
}
});
const gatewaySession = await codexAcpAgent.newSession({cwd: "", mcpServers: []});
authFixture.clearAcpConnectionDump();
await codexAcpAgent.prompt({
sessionId: gatewaySession.sessionId,
prompt: [{ type: "text", text: "/status" }]
});
const gatewayStatusDump = authFixture.getAcpConnectionDump([]);
expect(gatewayStatusDump).toContain("**Account:** not logged in");
});
it('supports legacy authentication/logout ext method', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpAgent = mockFixture.getCodexAcpAgent();
const logoutSpy = vi.spyOn(codexAcpAgent, "logout").mockResolvedValue();
await expect(codexAcpAgent.extMethod("authentication/logout", {})).resolves.toEqual({});
expect(logoutSpy).toHaveBeenCalledWith({});
});
it('prefetches session additional skill roots before thread start', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpClient = mockFixture.getCodexAcpClient();
const codexAppServerClient = mockFixture.getCodexAppServerClient();
const listSkillsSpy = vi.spyOn(codexAppServerClient, "listSkills").mockResolvedValue({ data: [] });
const threadStartSpy = vi.spyOn(codexAppServerClient, "threadStart").mockResolvedValue({
thread: { id: "thread-id" } as any,
model: "gpt-5",
modelProvider: "openai",
cwd: "/workspace",
approvalPolicy: "on-request",
sandbox: "workspace-write",
reasoningEffort: "medium",
} as any);
vi.spyOn(codexAppServerClient, "listModels").mockResolvedValue({
data: [{
id: "gpt-5",
model: "gpt-5",
upgrade: null,
upgradeInfo: null,
availabilityNux: null,
displayName: "gpt-5",
description: "test model",
hidden: false,
supportedReasoningEfforts: [{ reasoningEffort: "medium", description: "balanced" }],
defaultReasoningEffort: "medium",
inputModalities: ["text"],
supportsPersonality: false,
additionalSpeedTiers: [],
serviceTiers: [],
defaultServiceTier: null,
isDefault: true
}],
nextCursor: null
});
await codexAcpClient.newSession({
cwd: "/workspace",
mcpServers: [],
_meta: {
additionalRoots: ["/skills/one", " /skills/two ", 7]
}
});
expect(listSkillsSpy).toHaveBeenCalledWith({
cwds: ["/workspace", "/skills/one", "/skills/two"],
forceReload: true,
});
expect(listSkillsSpy.mock.invocationCallOrder[0]!).toBeLessThan(threadStartSpy.mock.invocationCallOrder[0]!);
});
it('prefers ACP additional directories over legacy meta roots for new session skill discovery', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpClient = mockFixture.getCodexAcpClient();
const codexAppServerClient = mockFixture.getCodexAppServerClient();
const extraRootsSetSpy = vi.spyOn(codexAppServerClient, "skillsExtraRootsSet").mockResolvedValue(undefined);
const listSkillsSpy = vi.spyOn(codexAppServerClient, "listSkills").mockResolvedValue({data: []});
const threadStartSpy = vi.spyOn(codexAppServerClient, "threadStart").mockResolvedValue({
thread: {id: "thread-id"} as any,
model: "gpt-5",
reasoningEffort: "medium",
serviceTier: null,
} as any);
vi.spyOn(codexAppServerClient, "listModels").mockResolvedValue({
data: [createTestModel({id: "gpt-5"})],
nextCursor: null,
});
const session = await codexAcpClient.newSession({
cwd: "/workspace",
additionalDirectories: ["/workspace/extra", "/workspace", "/workspace/extra"],
mcpServers: [],
_meta: {
additionalRoots: ["/skills/one", "/workspace/extra", "/workspace"],
},
});
expect(session.additionalDirectories).toEqual(["/workspace/extra"]);
expect(extraRootsSetSpy).toHaveBeenCalledWith({
extraRoots: ["/workspace/extra/.agents/skills"],
});
expect(listSkillsSpy).toHaveBeenCalledWith({
cwds: ["/workspace", "/workspace/extra"],
forceReload: true,
});
expect(extraRootsSetSpy.mock.invocationCallOrder[0]!).toBeLessThan(threadStartSpy.mock.invocationCallOrder[0]!);
expect(listSkillsSpy.mock.invocationCallOrder[0]!).toBeLessThan(threadStartSpy.mock.invocationCallOrder[0]!);
const threadStartRequest = threadStartSpy.mock.calls[0]![0];
expect(threadStartRequest.config?.["projects"]).toEqual({
"/workspace": {trust_level: "trusted"},
"/workspace/extra": {trust_level: "trusted"},
});
expect(threadStartRequest.config?.["sandbox_workspace_write"]).toEqual({
writable_roots: ["/workspace/extra"],
});
});
it('applies ACP additional directories to resumed and loaded sessions explicitly', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpClient = mockFixture.getCodexAcpClient();
const codexAppServerClient = mockFixture.getCodexAppServerClient();
vi.spyOn(codexAppServerClient, "skillsExtraRootsSet").mockResolvedValue(undefined);
vi.spyOn(codexAppServerClient, "listSkills").mockResolvedValue({data: []});
const threadResumeSpy = vi.spyOn(codexAppServerClient, "threadResume").mockResolvedValue({
thread: {id: "thread-id"} as any,
model: "gpt-5",
reasoningEffort: "medium",
serviceTier: null,
} as any);
const threadReadSpy = vi.spyOn(codexAppServerClient, "threadRead").mockResolvedValue({
thread: {id: "thread-id"} as any,
});
vi.spyOn(codexAppServerClient, "listModels").mockResolvedValue({
data: [createTestModel({id: "gpt-5"})],
nextCursor: null,
});
const resumed = await codexAcpClient.resumeSession({
sessionId: "resume-id",
cwd: "/workspace",
additionalDirectories: ["/workspace/resume-extra"],
});
const loaded = await codexAcpClient.loadSession({
sessionId: "load-id",
cwd: "/workspace",
additionalDirectories: ["/workspace/load-extra"],
mcpServers: [],
});
expect(resumed.additionalDirectories).toEqual(["/workspace/resume-extra"]);
expect(loaded.additionalDirectories).toEqual(["/workspace/load-extra"]);
expect(threadResumeSpy.mock.calls[0]![0].config?.["projects"]).toEqual({
"/workspace": {trust_level: "trusted"},
"/workspace/resume-extra": {trust_level: "trusted"},
});
expect(threadResumeSpy.mock.calls[1]![0].config?.["projects"]).toEqual({
"/workspace": {trust_level: "trusted"},
"/workspace/load-extra": {trust_level: "trusted"},
});
expect(threadReadSpy).toHaveBeenCalledWith({
threadId: "thread-id",
includeTurns: true,
});
});
it('uses configured model provider when resuming sessions without an explicit provider', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpClient = mockFixture.getCodexAcpClient();
const codexAppServerClient = mockFixture.getCodexAppServerClient();
vi.spyOn(codexAppServerClient, "skillsExtraRootsSet").mockResolvedValue(undefined);
vi.spyOn(codexAppServerClient, "listSkills").mockResolvedValue({data: []});
vi.spyOn(codexAppServerClient, "configRead").mockResolvedValue({
config: {
model_provider: "azure",
},
} as any);
const threadResumeSpy = vi.spyOn(codexAppServerClient, "threadResume").mockResolvedValue({
thread: {id: "thread-id"} as any,
model: "gpt-5",
reasoningEffort: "medium",
serviceTier: null,
} as any);
vi.spyOn(codexAppServerClient, "threadRead").mockResolvedValue({
thread: {id: "thread-id"} as any,
});
vi.spyOn(codexAppServerClient, "listModels").mockResolvedValue({
data: [createTestModel({id: "gpt-5"})],
nextCursor: null,
});
await codexAcpClient.resumeSession({
sessionId: "resume-id",
cwd: "/workspace",
});
await codexAcpClient.loadSession({
sessionId: "load-id",
cwd: "/workspace",
mcpServers: [],
});
expect(threadResumeSpy.mock.calls[0]![0].modelProvider).toBe("azure");
expect(threadResumeSpy.mock.calls[1]![0].modelProvider).toBe("azure");
});
it('tracks configured model provider auth state for resumed and loaded sessions', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpAgent = mockFixture.getCodexAcpAgent();
const codexAcpClient = mockFixture.getCodexAcpClient();
const codexAppServerClient = mockFixture.getCodexAppServerClient();
vi.spyOn(codexAcpClient, "authRequired").mockResolvedValue(false);
const getAccountSpy = vi.spyOn(codexAcpClient, "getAccount").mockResolvedValue({
account: null,
requiresOpenaiAuth: true,
});
vi.spyOn(codexAppServerClient, "skillsExtraRootsSet").mockResolvedValue(undefined);
vi.spyOn(codexAppServerClient, "listSkills").mockResolvedValue({data: []});
vi.spyOn(codexAppServerClient, "configRead").mockResolvedValue({
config: {
model_provider: "azure",
},
} as any);
const threadResumeSpy = vi.spyOn(codexAppServerClient, "threadResume").mockResolvedValue({
thread: {id: "thread-id"} as any,
model: "gpt-5",
modelProvider: "azure",
reasoningEffort: "medium",
serviceTier: null,
} as any);
vi.spyOn(codexAppServerClient, "threadRead").mockResolvedValue({
thread: {id: "thread-id", turns: []} as any,
});
vi.spyOn(codexAppServerClient, "listModels").mockResolvedValue({
data: [createTestModel({id: "gpt-5"})],
nextCursor: null,
});
await codexAcpAgent.resumeSession({
sessionId: "resume-id",
cwd: "/workspace",
});
await codexAcpAgent.loadSession({
sessionId: "load-id",
cwd: "/workspace",
mcpServers: [],
});
expect(threadResumeSpy.mock.calls[0]![0].modelProvider).toBe("azure");
expect(threadResumeSpy.mock.calls[1]![0].modelProvider).toBe("azure");
expect(getAccountSpy).not.toHaveBeenCalled();
expect(codexAcpAgent.getSessionState("resume-id")).toMatchObject({
account: null,
authConfigured: true,
authProvider: "azure",
});
expect(codexAcpAgent.getSessionState("load-id")).toMatchObject({
account: null,
authConfigured: true,
authProvider: "azure",
});
});
it('rejects malformed ACP additional directories', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpClient = mockFixture.getCodexAcpClient();
await expect(codexAcpClient.newSession({
cwd: "/workspace",
additionalDirectories: ["relative"],
mcpServers: [],
})).rejects.toThrow("additionalDirectories entries must be absolute paths");
await expect(codexAcpClient.newSession({
cwd: "/workspace",
additionalDirectories: [""],
mcpServers: [],
})).rejects.toThrow("additionalDirectories entries must not be empty");
await expect(codexAcpClient.newSession({
cwd: "/workspace",
additionalDirectories: [null],
mcpServers: [],
} as unknown as acp.NewSessionRequest)).rejects.toThrow("additionalDirectories entries must be strings");
});
it('sanitizes whitespace in ACP MCP server names before adding them to Codex config', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpClient = mockFixture.getCodexAcpClient();
const codexAppServerClient = mockFixture.getCodexAppServerClient();
vi.spyOn(codexAppServerClient, "listSkills").mockResolvedValue({data: []});
vi.spyOn(codexAppServerClient, "configRead").mockResolvedValue({
config: {
mcp_servers: {
shared_mcp: {
url: "https://example.com/mcp",
},
},
},
} as any);
const threadStartSpy = vi.spyOn(codexAppServerClient, "threadStart").mockResolvedValue({
thread: {id: "thread-id"} as any,
model: "gpt-5",
reasoningEffort: "medium",
serviceTier: null,
} as any);
vi.spyOn(codexAppServerClient, "listModels").mockResolvedValue({
data: [createTestModel({id: "gpt-5"})],
nextCursor: null,
});
await codexAcpClient.newSession({
cwd: "/workspace",
mcpServers: [{
name: "shared mcp",
command: "npx",
args: ["shared"],
env: [],
}, {
name: "stdio server\tone",
command: "npx",
args: ["stdio"],
env: [{name: "EXAMPLE", value: "1"}],
}, {
type: "http",
name: "http\nserver\u00a0two",
url: "https://example.com/http",
headers: [{name: "Authorization", value: "Bearer token"}],
}],
});
const threadStartRequest = threadStartSpy.mock.calls[0]![0];
expect(threadStartRequest.config?.["mcp_servers"]).toEqual({
stdio_server_one: {
command: "npx",
args: ["stdio"],
env: {EXAMPLE: "1"},
},
http_server_two: {
url: "https://example.com/http",
http_headers: {Authorization: "Bearer token"},
},
});
});
it('waits for typed mcp startup status updates and returns terminal states', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpClient = mockFixture.getCodexAcpClient();
const codexAppServerClient = mockFixture.getCodexAppServerClient();
const startupPromise = codexAcpClient.awaitMcpServerStartup(
["alpha", "beta"],
codexAppServerClient.getMcpServerStartupVersion()
);
mockFixture.sendServerNotification({
method: "mcpServer/startupStatus/updated",
params: { threadId: "thread-id", name: "alpha", status: "starting", error: null }
});
mockFixture.sendServerNotification({
method: "mcpServer/startupStatus/updated",
params: { threadId: "thread-id", name: "beta", status: "starting", error: null }
});
mockFixture.sendServerNotification({
method: "mcpServer/startupStatus/updated",
params: { threadId: "thread-id", name: "alpha", status: "ready", error: null }
});
mockFixture.sendServerNotification({
method: "mcpServer/startupStatus/updated",
params: { threadId: "thread-id", name: "beta", status: "ready", error: null }
});
const startup = await startupPromise;
expect(startup).toEqual({
ready: ["alpha", "beta"],
failed: [],
cancelled: [],
});
});
it('forwards failed MCP startup as failed tool call updates after new session', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpAgent = mockFixture.getCodexAcpAgent();
const codexAppServerClient = mockFixture.getCodexAppServerClient();
vi.spyOn(codexAcpAgent, "checkAuthorization").mockResolvedValue(undefined);
vi.spyOn(codexAppServerClient, "threadStart").mockResolvedValue({
thread: { id: "thread-id" } as any,
model: "gpt-5",
reasoningEffort: "medium",
} as any);
vi.spyOn(codexAppServerClient, "listModels").mockResolvedValue({
data: [{
id: "gpt-5",
name: "GPT-5",
inputModalities: ["text"],
supportedReasoningEfforts: [],
}],
hasMore: false,
} as any);
vi.spyOn(codexAppServerClient, "accountRead").mockResolvedValue({
requiresOpenaiAuth: false,
account: null,
} as any);
vi.spyOn(codexAppServerClient, "listSkills").mockResolvedValue({ data: [] });
const mcpServer = {
name: "broken-mcp",
command: "npx",
args: ["broken"],
env: [],
} as unknown as acp.McpServerStdio;
const session = await codexAcpAgent.newSession({
cwd: "/workspace",
mcpServers: [mcpServer]
});
mockFixture.sendServerNotification({
method: "mcpServer/startupStatus/updated",
params: { threadId: "thread-id", name: "broken-mcp", status: "failed", error: "boom" }
});
await vi.waitFor(() => {
const dump = mockFixture.getAcpConnectionDump([]);
expect(dump).toContain('"sessionId": "thread-id"');
expect(dump).toContain('"sessionUpdate": "tool_call"');
expect(dump).toContain('"toolCallId": "mcp_startup.broken-mcp"');
expect(dump).toContain('MCP server `broken-mcp` failed to start: boom');
});
expect(session.sessionId).toBe("thread-id");
});
it('prefetches skills before turn start', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpAgent = mockFixture.getCodexAcpAgent();
const codexAppServerClient = mockFixture.getCodexAppServerClient();
const listSkillsSpy = vi.spyOn(codexAppServerClient, "listSkills").mockResolvedValue({ data: [] });
const turnStartSpy = vi.spyOn(codexAppServerClient, "turnStart").mockResolvedValue({
turn: { id: "turn-id", items: [], status: "inProgress", error: null }
} as any);
vi.spyOn(codexAppServerClient, "awaitTurnCompleted").mockResolvedValue({
threadId: "session-id",
turn: { id: "turn-id", items: [], status: "completed", error: null }
} as any);
vi.spyOn(codexAcpAgent, "getSessionState").mockReturnValue(createTestSessionState({
sessionId: "session-id",
cwd: "/workspace"
}));
const promptRequest: acp.PromptRequest = {
sessionId: "session-id",
prompt: [{ type: "text", text: "Hello" }],
};
await codexAcpAgent.prompt(promptRequest);
expect(listSkillsSpy).toHaveBeenCalledWith({
cwds: ["/workspace"],
forceReload: true,
});
expect(listSkillsSpy.mock.invocationCallOrder[0]!).toBeLessThan(turnStartSpy.mock.invocationCallOrder[0]!);
});
it('applies ACP additional directories to turn skill discovery and sandbox policy', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpAgent = mockFixture.getCodexAcpAgent();
const codexAppServerClient = mockFixture.getCodexAppServerClient();
const extraRootsSetSpy = vi.spyOn(codexAppServerClient, "skillsExtraRootsSet").mockResolvedValue(undefined);
const listSkillsSpy = vi.spyOn(codexAppServerClient, "listSkills").mockResolvedValue({data: []});
const turnStartSpy = vi.spyOn(codexAppServerClient, "turnStart").mockResolvedValue({
turn: { id: "turn-id", items: [], status: "inProgress", error: null }
} as any);
vi.spyOn(codexAppServerClient, "awaitTurnCompleted").mockResolvedValue({
threadId: "session-id",
turn: { id: "turn-id", items: [], status: "completed", error: null }
} as any);
vi.spyOn(codexAcpAgent, "getSessionState").mockReturnValue(createTestSessionState({
sessionId: "session-id",
cwd: "/workspace",
additionalDirectories: ["/workspace/extra"],
}));
await codexAcpAgent.prompt({
sessionId: "session-id",
prompt: [{ type: "text", text: "Hello" }],
});
expect(extraRootsSetSpy).toHaveBeenCalledWith({
extraRoots: ["/workspace/extra/.agents/skills"],
});
expect(listSkillsSpy).toHaveBeenCalledWith({
cwds: ["/workspace", "/workspace/extra"],
forceReload: true,
});
expect(turnStartSpy.mock.calls[0]![0].sandboxPolicy).toMatchObject({
type: "workspaceWrite",
writableRoots: ["/workspace/extra"],
});
});
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;
}
function createTurn(id: string, status: "inProgress" | "completed" | "interrupted") {
return {
id,
items: [],
itemsView: "notLoaded" as const,
status,
error: null,
startedAt: null,
completedAt: null,
durationMs: null,
};
}
function createTurnCompletedNotification(threadId: string, turnId: string): ServerNotification {
return {
method: "turn/completed",
params: {
threadId,
turn: createTurn(turnId, "completed"),
},
};
}
async function flushAsyncWork(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 0));
}
function deferred<T>(): {promise: Promise<T>, resolve: (value: T) => void} {
let resolve: (value: T) => void = () => {};
const promise = new Promise<T>((innerResolve) => {
resolve = innerResolve;
});
return {promise, resolve};
}
it('should map events from dump', async () => {
fixture.getCodexAppServerClient().onServerNotification = loadNotifications();
const codexAcpAgent = fixture.getCodexAcpAgent();
fixture.getCodexAppServerClient().listSkills = vi.fn().mockResolvedValue({ data: [] });
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: "id", turnId: "string", itemId: "string", delta: "He", }},
{ method: "item/agentMessage/delta", params: { threadId: "id", turnId: "string", itemId: "string", delta: "ll", }},
{ method: "item/agentMessage/delta", params: { threadId: "id", 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 }
});
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;
});
// awaitTurnCompleted is per-turn; resolve the matching thread and turn.
mockFixture.getCodexAppServerClient().awaitTurnCompleted = vi.fn().mockImplementation((threadId: string, turnId: string) => Promise.resolve({
threadId,
turn: createTurn(turnId, "completed")
}));
// 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();
// Each notification carries the threadId of the session it belongs to,
// and must only be dispatched to that session.
const serverNotifications: ServerNotification[] = [
{ method: "item/agentMessage/delta", params: { threadId: "session-1", turnId: "string", itemId: "string", delta: "Hello-1", }},
{ method: "item/agentMessage/delta", params: { threadId: "session-2", turnId: "string", itemId: "string", delta: "Hello-2", }},
];
for (const notification of serverNotifications) {
mockFixture.sendServerNotification(notification);
}
// Wait for async handlers to complete
await vi.waitFor(() => {
const dump = mockFixture.getAcpConnectionDump([]);
expect(dump.length).toBeGreaterThanOrEqual(2);
});
// Should have exactly 2 events - the session-1 delta only on session-1, and
// the session-2 delta only on session-2 (no cross-session pollution).
await expect(mockFixture.getAcpConnectionDump([])).toMatchFileSnapshot("data/multiple-sessions.json");
});
it('should complete concurrent prompts by matching thread and turn id', async () => {
const mockFixture = createCodexMockTestFixture();
const codexAcpAgent = mockFixture.getCodexAcpAgent();
const turnIds = new Map([
["session-1", "turn-1"],
["session-2", "turn-2"],
]);
const turnStart = vi.fn().mockImplementation((params: TurnStartParams) => Promise.resolve({
turn: createTurn(turnIds.get(params.threadId) ?? "unknown-turn", "inProgress"),
}));
mockFixture.getCodexAppServerClient().turnStart = turnStart;
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;
});