-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain_test.go
More file actions
1286 lines (1143 loc) · 47.1 KB
/
main_test.go
File metadata and controls
1286 lines (1143 loc) · 47.1 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
package main
import (
"encoding/base64"
"encoding/json"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
)
func TestParseLaunchRequestReadsRestartFlag(t *testing.T) {
request := parseLaunchRequest([]string{"--launcher", "--debug-port", "9229", "--helper-port", "57321", "--restart"})
if !request.restart {
t.Fatal("restart flag should be true")
}
if request.debugPort != 9229 {
t.Fatalf("debug port mismatch: %d", request.debugPort)
}
if request.helperPort != 57321 {
t.Fatalf("helper port mismatch: %d", request.helperPort)
}
}
func TestBuildWatcherInstallPlanMatchesOriginalWindowsShape(t *testing.T) {
plan := buildWatcherInstallPlan(`C:\Tools\Codex++.exe`, 9229, `C:\Users\A\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\CodexPlusPlusWatcher.lnk`)
if plan.LauncherPath != `C:\Tools\Codex++.exe` {
t.Fatalf("launcher path mismatch: %q", plan.LauncherPath)
}
if plan.Arguments != "--debug-port 9229" {
t.Fatalf("arguments mismatch: %q", plan.Arguments)
}
if plan.RunValue != `"C:\Tools\Codex++.exe" --debug-port 9229` {
t.Fatalf("run value mismatch: %q", plan.RunValue)
}
if plan.ShortcutPath == "" {
t.Fatal("shortcut path should be preserved")
}
}
func TestParseWindowsUninstallRegistryValue(t *testing.T) {
output := `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall\CodexTools
DisplayName REG_SZ CodexTools
UninstallString REG_SZ "C:\Users\A\AppData\Local\CodexTools\Uninstall.exe"
`
value := parseWindowsRegQueryValue(output, "UninstallString")
if value != `"C:\Users\A\AppData\Local\CodexTools\Uninstall.exe"` {
t.Fatalf("uninstall registry value mismatch: %q", value)
}
}
func TestWindowsExecutableFromCommandParsesQuotedPath(t *testing.T) {
command := `"C:\Users\A\AppData\Local\CodexTools\Uninstall.exe" /S`
if got := windowsExecutableFromCommand(command); got != `C:\Users\A\AppData\Local\CodexTools\Uninstall.exe` {
t.Fatalf("quoted command path mismatch: %q", got)
}
}
func TestNormalizeSettingsLanguage(t *testing.T) {
settings := normalizeSettings(backendSettings{Language: "ja"})
if settings.Language != "ja-JP" {
t.Fatalf("language should normalize to ja-JP, got %q", settings.Language)
}
settings = normalizeSettings(backendSettings{Language: "unsupported"})
if settings.Language != defaultLanguage {
t.Fatalf("unsupported language should fall back to %q, got %q", defaultLanguage, settings.Language)
}
}
func TestChatGPTAuthStatusFromContentsReadsEmail(t *testing.T) {
status := chatGPTAuthStatusFromContents(fakeChatGPTAuthJSON(t, "alpha@example.com"), "test")
if !status.Authenticated {
t.Fatal("official auth should be authenticated")
}
if status.AccountLabel != "alpha@example.com" {
t.Fatalf("account label mismatch: %q", status.AccountLabel)
}
}
func TestLoadSettingsMigratesCurrentOfficialAuthToActiveProfile(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
settings := defaultSettings()
settings.RelayProfiles = []relayProfile{
{ID: "first", Name: "First", RelayMode: "official", Protocol: "responses"},
{ID: "second", Name: "Second", RelayMode: "official", Protocol: "responses"},
}
settings.ActiveRelayID = "second"
writeTestFile(t, filepath.Join(home, ".codex", "auth.json"), fakeChatGPTAuthJSON(t, "active@example.com"))
writeTestFile(t, filepath.Join(home, ".codex", "config.toml"), `model_provider = "openai"`+"\n")
if err := atomicWriteJSON(settingsPath(), settings); err != nil {
t.Fatalf("failed to write settings: %v", err)
}
loaded := loadSettings()
if loaded.RelayProfiles[0].OfficialAuthContents != "" {
t.Fatal("inactive profile should not receive migrated official auth")
}
active := activeRelayProfile(loaded)
if active.ID != "second" {
t.Fatalf("active profile mismatch: %q", active.ID)
}
if active.OfficialAccountLabel != "active@example.com" {
t.Fatalf("official account label mismatch: %q", active.OfficialAccountLabel)
}
if active.OfficialAuthContents == "" {
t.Fatal("official auth contents should be migrated")
}
if active.AuthContents == "" {
t.Fatal("auth contents should be migrated")
}
if active.ConfigContents == "" {
t.Fatal("config contents should be migrated for active profile")
}
}
func TestRelayStatusDetectsBoundOfficialAuthWithoutCurrentAuthFile(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
settings := defaultSettings()
settings.RelayProfiles = []relayProfile{{
ID: "official",
Name: "Official",
RelayMode: "official",
Protocol: "responses",
OfficialAuthContents: fakeChatGPTAuthJSON(t, "bound@example.com"),
OfficialAccountLabel: "bound@example.com",
}}
settings.ActiveRelayID = "official"
status := relayStatusFromHome(filepath.Join(home, ".codex"), settings)
if boolFromAny(status["currentAuthenticated"]) {
t.Fatal("current auth file should not be detected")
}
if !boolFromAny(status["boundOfficialAuthenticated"]) {
t.Fatalf("bound official auth should be detected: %#v", status)
}
if !boolFromAny(status["officialAuthenticated"]) {
t.Fatalf("overall official auth should be detected: %#v", status)
}
if got := stringFromAny(status["boundOfficialAccountLabel"]); got != "bound@example.com" {
t.Fatalf("bound account label mismatch: %q", got)
}
if got := stringFromAny(status["boundOfficialProfileId"]); got != "official" {
t.Fatalf("bound profile id mismatch: %q", got)
}
}
func TestInstallGuideConnectionDetectsBoundOfficialAuth(t *testing.T) {
settings := defaultSettings()
settings.RelayProfiles = []relayProfile{{
ID: "official",
Name: "Official",
RelayMode: "official",
Protocol: "responses",
OfficialAuthContents: fakeChatGPTAuthJSON(t, "bound@example.com"),
OfficialAccountLabel: "bound@example.com",
}}
settings.ActiveRelayID = "official"
relayStatus := relayStatusFromHome(filepath.Join(t.TempDir(), ".codex"), settings)
payload := installGuideConnectionPayload(settings, relayStatus)
if !boolFromAny(payload["ready"]) {
t.Fatalf("bound official auth should make guide connection ready: %#v", payload)
}
if !boolFromAny(payload["officialReady"]) {
t.Fatalf("official account should be ready: %#v", payload)
}
if got := stringFromAny(payload["profileId"]); got != "official" {
t.Fatalf("profile id mismatch: %q", got)
}
}
func TestInstallGuideConnectionRequiresMixedApiFields(t *testing.T) {
settings := defaultSettings()
settings.RelayProfiles = []relayProfile{{
ID: "mixed",
Name: "Mixed",
RelayMode: "mixedApi",
Protocol: "responses",
OfficialAuthContents: fakeChatGPTAuthJSON(t, "mixed@example.com"),
OfficialAccountLabel: "mixed@example.com",
}}
settings.ActiveRelayID = "mixed"
relayStatus := relayStatusFromHome(filepath.Join(t.TempDir(), ".codex"), settings)
payload := installGuideConnectionPayload(settings, relayStatus)
if boolFromAny(payload["ready"]) {
t.Fatalf("mixed API without base URL/key should not be ready: %#v", payload)
}
if !boolFromAny(payload["officialReady"]) || boolFromAny(payload["apiReady"]) {
t.Fatalf("mixed API readiness flags mismatch: %#v", payload)
}
}
func TestDefaultCCSDBPathPrefersExistingHomeDatabase(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
expected := filepath.Join(home, ".cc-switch", "cc-switch.db")
writeTestFile(t, expected, "sqlite")
if got := defaultCCSDBPath(); got != expected {
t.Fatalf("ccswitch database path mismatch: %q", got)
}
}
func TestPlatformAndArchDisplayNames(t *testing.T) {
if got := platformDisplayName("windows"); got != "Windows" {
t.Fatalf("windows platform label mismatch: %q", got)
}
if got := archDisplayName("amd64"); got != "x64" {
t.Fatalf("amd64 arch label mismatch: %q", got)
}
if got := archDisplayName("arm64"); got != "ARM64" {
t.Fatalf("arm64 arch label mismatch: %q", got)
}
}
func TestListCCSProvidersReadsSQLiteDatabase(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "cc-switch.db")
db, err := openSQLite(dbPath)
if err != nil {
t.Fatalf("failed to open sqlite db: %v", err)
}
defer db.Close()
if _, err := db.Exec(`CREATE TABLE providers (id TEXT, name TEXT, settings_config TEXT, app_type TEXT, sort_index INTEGER, created_at TEXT)`); err != nil {
t.Fatalf("failed to create providers table: %v", err)
}
config := `{"base_url":"https://relay.example.com/v1","api_key":"relay-key"}`
if _, err := db.Exec(`INSERT INTO providers (id, name, settings_config, app_type, sort_index, created_at) VALUES (?, ?, ?, ?, ?, ?)`, "provider-1", "Relay One", config, "codex", 1, "2026-05-27"); err != nil {
t.Fatalf("failed to insert provider: %v", err)
}
providers, err := listCCSProviders(dbPath)
if err != nil {
t.Fatalf("failed to list providers: %v", err)
}
if len(providers) != 1 {
t.Fatalf("provider count mismatch: %d", len(providers))
}
if providers[0].SourceID != "provider-1" || providers[0].BaseURL != "https://relay.example.com/v1" || providers[0].APIKey != "relay-key" {
t.Fatalf("provider mismatch: %#v", providers[0])
}
}
func TestListCCSProvidersReadsSettingsConfigVariants(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "cc-switch.db")
db, err := openSQLite(dbPath)
if err != nil {
t.Fatalf("failed to open sqlite db: %v", err)
}
defer db.Close()
if _, err := db.Exec(`CREATE TABLE providers (providerId TEXT, displayName TEXT, settingsConfig TEXT)`); err != nil {
t.Fatalf("failed to create providers table: %v", err)
}
configText := strings.Join([]string{
`model_provider = "CodexPlusPlus"`,
`[model_providers.CodexPlusPlus]`,
`wire_api = "chat"`,
`base_url = "https://relay.example.com/v1/"`,
`experimental_bearer_token = "toml-key"`,
}, "\n")
settingsConfig, _ := json.Marshal(map[string]any{
"config": configText,
"auth": `{"tokens":{"id_token":"official-token"}}`,
})
if _, err := db.Exec(`INSERT INTO providers (providerId, displayName, settingsConfig) VALUES (?, ?, ?)`, "provider-2", "Relay Two", string(settingsConfig)); err != nil {
t.Fatalf("failed to insert provider: %v", err)
}
providers, err := listCCSProviders(dbPath)
if err != nil {
t.Fatalf("failed to list providers: %v", err)
}
if len(providers) != 1 {
t.Fatalf("provider count mismatch: %d", len(providers))
}
provider := providers[0]
if provider.SourceID != "provider-2" || provider.Name != "Relay Two" {
t.Fatalf("provider identity mismatch: %#v", provider)
}
if provider.BaseURL != "https://relay.example.com/v1" || provider.APIKey != "toml-key" || provider.Protocol != "chatCompletions" {
t.Fatalf("provider settings mismatch: %#v", provider)
}
if provider.ConfigContents != configText {
t.Fatalf("config contents mismatch:\n%s", provider.ConfigContents)
}
if provider.AuthContents != `{"tokens":{"id_token":"official-token"}}` {
t.Fatalf("auth contents mismatch: %q", provider.AuthContents)
}
}
func TestListCCSProvidersReadsRawTomlConfigColumn(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "cc-switch.db")
db, err := openSQLite(dbPath)
if err != nil {
t.Fatalf("failed to open sqlite db: %v", err)
}
defer db.Close()
if _, err := db.Exec(`CREATE TABLE providers (id TEXT, name TEXT, config TEXT, app_type TEXT)`); err != nil {
t.Fatalf("failed to create providers table: %v", err)
}
configText := strings.Join([]string{
`model_provider = "CodexPlusPlus"`,
`[model_providers.CodexPlusPlus]`,
`base_url = "https://relay.example.com/v1"`,
`experimental_bearer_token = "raw-key"`,
}, "\n")
if _, err := db.Exec(`INSERT INTO providers (id, name, config, app_type) VALUES (?, ?, ?, ?)`, "provider-3", "Relay Three", configText, "codex"); err != nil {
t.Fatalf("failed to insert provider: %v", err)
}
if _, err := db.Exec(`INSERT INTO providers (id, name, config, app_type) VALUES (?, ?, ?, ?)`, "provider-4", "Other", configText, "claude"); err != nil {
t.Fatalf("failed to insert non-codex provider: %v", err)
}
providers, err := listCCSProviders(dbPath)
if err != nil {
t.Fatalf("failed to list providers: %v", err)
}
if len(providers) != 1 {
t.Fatalf("provider count mismatch: %d", len(providers))
}
if providers[0].SourceID != "provider-3" || providers[0].APIKey != "raw-key" || providers[0].ConfigContents != configText {
t.Fatalf("provider mismatch: %#v", providers[0])
}
}
func TestListCCSProvidersReadsMetaAPIFormatAndFillsBearerToken(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "cc-switch.db")
db, err := openSQLite(dbPath)
if err != nil {
t.Fatalf("failed to open sqlite db: %v", err)
}
defer db.Close()
if _, err := db.Exec(`CREATE TABLE providers (id TEXT, name TEXT, settings_config TEXT, meta TEXT, app_type TEXT)`); err != nil {
t.Fatalf("failed to create providers table: %v", err)
}
configText := strings.Join([]string{
`model_provider = "custom"`,
`[model_providers.custom]`,
`name = "Custom"`,
`wire_api = "responses"`,
`base_url = "https://relay.example.com/v1"`,
}, "\n")
settingsConfig, _ := json.Marshal(map[string]any{
"config": configText,
"auth": map[string]any{"OPENAI_API_KEY": "auth-key"},
})
meta, _ := json.Marshal(map[string]any{"apiFormat": "openai_chat"})
if _, err := db.Exec(`INSERT INTO providers (id, name, settings_config, meta, app_type) VALUES (?, ?, ?, ?, ?)`, "provider-5", "Relay Five", string(settingsConfig), string(meta), "codex"); err != nil {
t.Fatalf("failed to insert provider: %v", err)
}
providers, err := listCCSProviders(dbPath)
if err != nil {
t.Fatalf("failed to list providers: %v", err)
}
if len(providers) != 1 {
t.Fatalf("provider count mismatch: %d", len(providers))
}
provider := providers[0]
if provider.Protocol != "chatCompletions" || provider.APIKey != "auth-key" {
t.Fatalf("provider metadata mismatch: %#v", provider)
}
if !strings.Contains(provider.ConfigContents, `experimental_bearer_token = "auth-key"`) {
t.Fatalf("config should be filled with bearer token:\n%s", provider.ConfigContents)
}
}
func TestOfficialModeRequiresBoundOfficialAuth(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
settings := defaultSettings()
settings.RelayProfiles = []relayProfile{{ID: "official", Name: "Official", RelayMode: "official", Protocol: "responses"}}
settings.ActiveRelayID = "official"
if err := saveSettings(settings); err != nil {
t.Fatalf("failed to save settings: %v", err)
}
result := (&server{}).clearRelayInjection()
if result["status"] != "failed" {
t.Fatalf("official switch without bound auth should fail: %#v", result)
}
}
func TestOfficialModeWritesBoundOfficialAuth(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
officialAuth := fakeChatGPTAuthJSON(t, "official@example.com")
settings := defaultSettings()
settings.RelayProfiles = []relayProfile{{
ID: "official",
Name: "Official",
RelayMode: "official",
Protocol: "responses",
OfficialAuthContents: officialAuth,
OfficialAccountLabel: "official@example.com",
}}
settings.ActiveRelayID = "official"
if err := saveSettings(settings); err != nil {
t.Fatalf("failed to save settings: %v", err)
}
writeTestFile(t, filepath.Join(home, ".codex", "config.toml"), `model_provider = "CodexPlusPlus"`+"\n\n[model_providers.CodexPlusPlus]\nbase_url = \"https://api.example.com\"\n")
result := (&server{}).clearRelayInjection()
if result["status"] != "ok" {
t.Fatalf("official switch should succeed: %#v", result)
}
status := chatGPTAuthStatus(filepath.Join(home, ".codex"))
if !status.Authenticated || status.AccountLabel != "official@example.com" {
t.Fatalf("bound official auth was not written: %#v", status)
}
config, _ := os.ReadFile(filepath.Join(home, ".codex", "config.toml"))
if strings.Contains(string(config), "CodexPlusPlus") {
t.Fatalf("official mode should clear relay provider config:\n%s", string(config))
}
}
func TestActivateOfficialAuthWritesBoundOfficialAuth(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
officialAuth := fakeChatGPTAuthJSON(t, "bound@example.com")
currentAuth := fakeChatGPTAuthJSON(t, "current@example.com")
writeTestFile(t, filepath.Join(home, ".codex", "auth.json"), currentAuth)
settings := defaultSettings()
settings.RelayProfiles = []relayProfile{{
ID: "official",
Name: "Official",
RelayMode: "official",
Protocol: "responses",
OfficialAuthContents: officialAuth,
OfficialAccountLabel: "bound@example.com",
}}
settings.ActiveRelayID = "official"
if err := saveSettings(settings); err != nil {
t.Fatalf("failed to save settings: %v", err)
}
result := (&server{}).activateOfficialAuth(map[string]any{
"request": map[string]any{"profileId": "official"},
})
if result["status"] != "ok" {
t.Fatalf("activate official auth should succeed: %#v", result)
}
status := chatGPTAuthStatus(filepath.Join(home, ".codex"))
if !status.Authenticated || status.AccountLabel != "bound@example.com" {
t.Fatalf("bound official auth was not activated: %#v", status)
}
}
func TestImportCurrentRelayFilesUpdatesTargetProfileSnapshot(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
writeTestFile(t, filepath.Join(home, ".codex", "config.toml"), "model_provider = \"openai\"\n")
writeTestFile(t, filepath.Join(home, ".codex", "auth.json"), fakeChatGPTAuthJSON(t, "import@example.com"))
settings := defaultSettings()
settings.RelayProfiles = []relayProfile{{ID: "one", Name: "One", RelayMode: "official", Protocol: "responses"}}
settings.ActiveRelayID = "one"
if err := saveSettings(settings); err != nil {
t.Fatalf("failed to save settings: %v", err)
}
result := (&server{}).importCurrentRelayFiles(map[string]any{
"request": map[string]any{"profileId": "one"},
})
if result["status"] != "ok" {
t.Fatalf("import current relay files should succeed: %#v", result)
}
loaded := loadSettings()
profile := activeRelayProfile(loaded)
if !strings.Contains(profile.ConfigContents, `model_provider = "openai"`) {
t.Fatalf("config snapshot mismatch:\n%s", profile.ConfigContents)
}
if profile.AuthContents == "" || profile.OfficialAuthContents == "" {
t.Fatalf("auth snapshot should be imported: %#v", profile)
}
if profile.OfficialAccountLabel != "import@example.com" {
t.Fatalf("official account label mismatch: %q", profile.OfficialAccountLabel)
}
}
func TestClearRelayInjectionFallsBackToLegacyOfficialAuthContents(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
officialAuth := fakeChatGPTAuthJSON(t, "legacy@example.com")
settings := defaultSettings()
settings.RelayProfiles = []relayProfile{{
ID: "legacy",
Name: "Legacy",
RelayMode: "official",
Protocol: "responses",
OfficialAuthContents: officialAuth,
OfficialAccountLabel: "legacy@example.com",
AuthContents: "",
ConfigContents: "",
}}
settings.ActiveRelayID = "legacy"
if err := saveSettings(settings); err != nil {
t.Fatalf("failed to save settings: %v", err)
}
writeTestFile(t, filepath.Join(home, ".codex", "config.toml"), `model_provider = "CodexPlusPlus"`+"\n")
result := (&server{}).clearRelayInjection()
if result["status"] != "ok" {
t.Fatalf("official switch should succeed with legacy auth fallback: %#v", result)
}
auth, _ := os.ReadFile(filepath.Join(home, ".codex", "auth.json"))
if chatGPTAuthStatusFromContents(string(auth), "auth").AccountLabel != "legacy@example.com" {
t.Fatalf("legacy official auth should be written to live auth.json, got:\n%s", string(auth))
}
}
func TestMixedModeWritesBoundOfficialAuthAndRelayConfig(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
officialAuth := fakeChatGPTAuthJSON(t, "mixed@example.com")
settings := defaultSettings()
settings.RelayProfiles = []relayProfile{{
ID: "mixed",
Name: "Mixed",
BaseURL: "https://api.example.com",
APIKey: "relay-key",
RelayMode: "mixedApi",
Protocol: "responses",
OfficialAuthContents: officialAuth,
OfficialAccountLabel: "mixed@example.com",
}}
settings.ActiveRelayID = "mixed"
if err := saveSettings(settings); err != nil {
t.Fatalf("failed to save settings: %v", err)
}
result := (&server{}).applyRelayInjection(false)
if result["status"] != "ok" {
t.Fatalf("mixed switch should succeed: %#v", result)
}
status := chatGPTAuthStatus(filepath.Join(home, ".codex"))
if !status.Authenticated || status.AccountLabel != "mixed@example.com" {
t.Fatalf("bound mixed official auth was not written: %#v", status)
}
config, _ := os.ReadFile(filepath.Join(home, ".codex", "config.toml"))
if !strings.Contains(string(config), `experimental_bearer_token = "relay-key"`) {
t.Fatalf("mixed relay config missing bearer token:\n%s", string(config))
}
auth, _ := os.ReadFile(filepath.Join(home, ".codex", "auth.json"))
if chatGPTAuthStatusFromContents(string(auth), "auth").AccountLabel != "mixed@example.com" {
t.Fatalf("mixed relay should use profile auth snapshot, got:\n%s", string(auth))
}
}
func TestPureAPIModeKeepsCurrentAuthWhenProfileSnapshotMissing(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
officialAuth := fakeChatGPTAuthJSON(t, "stored@example.com")
currentAuth := fakeChatGPTAuthJSON(t, "current@example.com")
writeTestFile(t, filepath.Join(home, ".codex", "auth.json"), currentAuth)
settings := defaultSettings()
settings.RelayProfiles = []relayProfile{{
ID: "pure",
Name: "Pure",
BaseURL: "https://api.example.com",
APIKey: "pure-key",
RelayMode: "pureApi",
Protocol: "responses",
OfficialAuthContents: officialAuth,
OfficialAccountLabel: "stored@example.com",
}}
settings.ActiveRelayID = "pure"
if err := saveSettings(settings); err != nil {
t.Fatalf("failed to save settings: %v", err)
}
result := (&server{}).applyRelayInjection(true)
if result["status"] != "ok" {
t.Fatalf("pure API switch should succeed: %#v", result)
}
auth, _ := os.ReadFile(filepath.Join(home, ".codex", "auth.json"))
if chatGPTAuthStatusFromContents(string(auth), "auth").AccountLabel != "current@example.com" {
t.Fatalf("pure API mode should preserve auth.json, got:\n%s", string(auth))
}
config, _ := os.ReadFile(filepath.Join(home, ".codex", "config.toml"))
if !strings.Contains(string(config), `experimental_bearer_token = "pure-key"`) {
t.Fatalf("pure API config should carry provider bearer token:\n%s", string(config))
}
loaded := loadSettings()
if activeRelayProfile(loaded).OfficialAccountLabel != "stored@example.com" {
t.Fatal("pure API mode should not remove stored official binding")
}
}
func TestPureAPIModeWritesProfileAuthSnapshotWhenPresent(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
currentAuth := fakeChatGPTAuthJSON(t, "current@example.com")
profileAuth := fakeChatGPTAuthJSON(t, "profile@example.com")
writeTestFile(t, filepath.Join(home, ".codex", "auth.json"), currentAuth)
settings := defaultSettings()
settings.RelayProfiles = []relayProfile{{
ID: "pure",
Name: "Pure",
BaseURL: "https://api.example.com",
APIKey: "pure-key",
RelayMode: "pureApi",
Protocol: "responses",
ConfigContents: buildTestRelayConfig("https://api.example.com", "pure-key"),
AuthContents: profileAuth,
}}
settings.ActiveRelayID = "pure"
if err := saveSettings(settings); err != nil {
t.Fatalf("failed to save settings: %v", err)
}
result := (&server{}).applyRelayInjection(true)
if result["status"] != "ok" {
t.Fatalf("pure API switch should succeed: %#v", result)
}
auth, _ := os.ReadFile(filepath.Join(home, ".codex", "auth.json"))
if chatGPTAuthStatusFromContents(string(auth), "auth").AccountLabel != "profile@example.com" {
t.Fatalf("pure API should restore saved auth snapshot, got:\n%s", string(auth))
}
}
func TestPureAPIModeWritesImportedConfigWithoutAuthOverwrite(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
currentAuth := fakeChatGPTAuthJSON(t, "current@example.com")
writeTestFile(t, filepath.Join(home, ".codex", "auth.json"), currentAuth)
importedConfig := strings.Join([]string{
`model_provider = "custom"`,
`[model_providers.custom]`,
`name = "Custom"`,
`wire_api = "responses"`,
`base_url = "https://imported.example.com/v1"`,
}, "\n")
settings := defaultSettings()
settings.RelayProfiles = []relayProfile{{
ID: "pure-imported",
Name: "Pure Imported",
BaseURL: "https://fallback.example.com",
APIKey: "imported-key",
RelayMode: "pureApi",
Protocol: "responses",
ConfigContents: importedConfig,
}}
settings.ActiveRelayID = "pure-imported"
if err := saveSettings(settings); err != nil {
t.Fatalf("failed to save settings: %v", err)
}
result := (&server{}).applyRelayInjection(true)
if result["status"] != "ok" {
t.Fatalf("pure API switch should succeed: %#v", result)
}
auth, _ := os.ReadFile(filepath.Join(home, ".codex", "auth.json"))
if chatGPTAuthStatusFromContents(string(auth), "auth").AccountLabel != "current@example.com" {
t.Fatalf("pure API mode should preserve auth.json, got:\n%s", string(auth))
}
config, _ := os.ReadFile(filepath.Join(home, ".codex", "config.toml"))
configText := string(config)
if !strings.Contains(configText, `base_url = "https://imported.example.com/v1"`) {
t.Fatalf("pure API should write imported config.toml:\n%s", configText)
}
if strings.Contains(configText, "fallback.example.com") {
t.Fatalf("pure API should not regenerate over imported config:\n%s", configText)
}
if !strings.Contains(configText, `experimental_bearer_token = "imported-key"`) {
t.Fatalf("pure API should ensure bearer token in imported config:\n%s", configText)
}
}
func TestRepairCodexGoalsConfigEnablesGoalsFeature(t *testing.T) {
contents := strings.Join([]string{
`model_provider = "CodexPlusPlus"`,
"",
"[features]",
"remote_connections = true",
"",
}, "\n")
updated := repairCodexGoalsConfig(contents)
if !strings.Contains(updated, "[features]\nremote_connections = true\ngoals = true") {
t.Fatalf("goals feature was not added to features table:\n%s", updated)
}
if strings.Count(updated, "goals = true") != 1 {
t.Fatalf("goals feature should be written exactly once:\n%s", updated)
}
}
func TestRepairCodexPluginConfigRestoresCachedPluginTables(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
writeTestFile(t, filepath.Join(home, ".tmp", "plugins", ".agents", "plugins", "marketplace.json"), `{"name":"openai-curated"}`)
writeTestFile(t, filepath.Join(home, "plugins", "cache", "openai-curated", "github", "6188456f", ".codex-plugin", "plugin.json"), `{"name":"github"}`)
writeTestFile(t, filepath.Join(home, "plugins", "cache", "openai-bundled", "browser", "26.519.41501", ".codex-plugin", "plugin.json"), `{"name":"browser"}`)
updated, pluginCount, marketplaceCount, _ := repairCodexPluginConfig(home, `model_provider = "CodexPlusPlus"`+"\n")
if pluginCount != 2 {
t.Fatalf("plugin count mismatch: %d", pluginCount)
}
if marketplaceCount != 1 {
t.Fatalf("marketplace count mismatch: %d", marketplaceCount)
}
for _, expected := range []string{
`[marketplaces.openai-curated]`,
`source = "` + filepath.Join(home, ".tmp", "plugins") + `"`,
`[plugins."browser@openai-bundled"]`,
`[plugins."github@openai-curated"]`,
`enabled = true`,
} {
if !strings.Contains(updated, expected) {
t.Fatalf("updated config missing %q:\n%s", expected, updated)
}
}
}
func writeTestFile(t *testing.T, path, contents string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatalf("failed to create test dir: %v", err)
}
if err := os.WriteFile(path, []byte(contents), 0o644); err != nil {
t.Fatalf("failed to write test file: %v", err)
}
}
func buildTestRelayConfig(baseURL, apiKey string) string {
return strings.Join([]string{
`model_provider = "CodexPlusPlus"`,
``,
`[model_providers.CodexPlusPlus]`,
`name = "CodexPlusPlus"`,
`wire_api = "responses"`,
`requires_openai_auth = true`,
`base_url = "` + baseURL + `"`,
`experimental_bearer_token = "` + apiKey + `"`,
``,
}, "\n")
}
func fakeChatGPTAuthJSON(t *testing.T, email string) string {
t.Helper()
payload, err := json.Marshal(map[string]string{"email": email})
if err != nil {
t.Fatalf("failed to marshal token payload: %v", err)
}
token := "header." + base64.RawURLEncoding.EncodeToString(payload) + ".signature"
data, err := json.MarshalIndent(map[string]any{
"auth_mode": "chatgpt",
"tokens": map[string]string{
"id_token": token,
"refresh_token": "refresh-token",
},
}, "", " ")
if err != nil {
t.Fatalf("failed to marshal auth json: %v", err)
}
return string(data) + "\n"
}
func TestSelectCodexMirrorAssetPrefersWindowsInstaller(t *testing.T) {
asset, ok := selectCodexMirrorAsset([]codexAppMirrorAsset{
{Name: "release-manifest.json", BrowserDownloadURL: "https://example.com/release-manifest.json"},
{Name: "SHA256SUMS-windows.txt", BrowserDownloadURL: "https://example.com/SHA256SUMS-windows.txt"},
{Name: "OpenAI.Codex_26.519.5221.0_x64__2p2nqsd0c76g0.Msix", BrowserDownloadURL: "https://example.com/OpenAI.Codex_26.519.5221.0_x64__2p2nqsd0c76g0.Msix"},
}, "windows", "amd64")
if !ok {
t.Fatal("expected a windows asset")
}
if asset.Name != "OpenAI.Codex_26.519.5221.0_x64__2p2nqsd0c76g0.Msix" {
t.Fatalf("selected wrong asset: %q", asset.Name)
}
}
func TestSelectCodexMirrorAssetPrefersMacArchitecture(t *testing.T) {
asset, ok := selectCodexMirrorAsset([]codexAppMirrorAsset{
{Name: "Codex-mac-x64.dmg", BrowserDownloadURL: "https://example.com/Codex-mac-x64.dmg"},
{Name: "Codex-mac-arm64.dmg", BrowserDownloadURL: "https://example.com/Codex-mac-arm64.dmg"},
}, "darwin", "arm64")
if !ok {
t.Fatal("expected a macOS asset")
}
if asset.Name != "Codex-mac-arm64.dmg" {
t.Fatalf("selected wrong asset: %q", asset.Name)
}
}
func TestNormalizeCodexAppPathAcceptsWindowsExecutableAndAppDir(t *testing.T) {
root := t.TempDir()
appDir := filepath.Join(root, "OpenAI.Codex_1.2.3.0_x64__test", "app")
if err := os.MkdirAll(appDir, 0o755); err != nil {
t.Fatalf("failed to create app dir: %v", err)
}
exe := filepath.Join(appDir, "Codex.exe")
writeTestFile(t, exe, "binary")
if got := normalizeCodexAppPath(exe); got != appDir {
t.Fatalf("executable should normalize to app dir: %q", got)
}
if got := normalizeCodexAppPath(filepath.Dir(appDir)); got != appDir {
t.Fatalf("package root should normalize to nested app dir: %q", got)
}
if got := normalizeCodexAppPath(appDir); got != appDir {
t.Fatalf("app dir should stay app dir: %q", got)
}
}
func TestPackagedWindowsAppUserModelIDMatchesOriginalLauncherShape(t *testing.T) {
path := `C:\Program Files\WindowsApps\OpenAI.Codex_26.519.11010.0_x64__2p2nqsd0c76g0\app`
if got := packagedWindowsAppUserModelID(path); got != "OpenAI.Codex_2p2nqsd0c76g0!App" {
t.Fatalf("app user model id mismatch: %q", got)
}
}
func TestPackagedWindowsAppUserModelIDIsCaseInsensitive(t *testing.T) {
path := `C:\Program Files\WindowsApps\OpenAI.Codex_26.519.11010.0_x64__2p2nqsd0c76g0\app`
mistypedCase := strings.Replace(path, "OpenAI.Codex_", "OpenAl.Codex_", 1)
if got := packagedWindowsAppUserModelID(strings.ToLower(path)); got != "OpenAI.Codex_2p2nqsd0c76g0!App" {
t.Fatalf("lowercase package path should still resolve app id: %q", got)
}
if got := packagedWindowsAppUserModelID(mistypedCase); got != "" {
t.Fatalf("non Codex package identity should not resolve app id: %q", got)
}
}
func TestWindowsPackagePathNormalizesToAppDirOnWindows(t *testing.T) {
path := `C:\Program Files\WindowsApps\OpenAI.Codex_26.519.11010.0_x64__2p2nqsd0c76g0\app\Codex.exe`
if runtime.GOOS != "windows" {
if got := normalizeCodexAppPath(path); got != "" {
t.Fatalf("Windows package paths should not normalize outside Windows: %q", got)
}
return
}
want := `C:\Program Files\WindowsApps\OpenAI.Codex_26.519.11010.0_x64__2p2nqsd0c76g0\app`
if got := normalizeCodexAppPath(path); got != want {
t.Fatalf("Windows package path should normalize to app dir: %q", got)
}
}
func TestWindowsPackageShapeNormalizesWithoutReadableExecutable(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("Windows package normalization only applies on Windows")
}
path := `C:\Program Files\WindowsApps\OpenAI.Codex_26.519.11010.0_x64__2p2nqsd0c76g0`
want := `C:\Program Files\WindowsApps\OpenAI.Codex_26.519.11010.0_x64__2p2nqsd0c76g0\app`
if got := normalizeCodexAppPath(path); got != want {
t.Fatalf("package shape should normalize without file access: %q", got)
}
}
func TestMissingWindowsExecutionAliasDoesNotNormalize(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("execution alias guard only applies on Windows")
}
path := filepath.Join(t.TempDir(), "Microsoft", "WindowsApps", "Codex.exe")
if got := normalizeCodexAppPath(path); got != "" {
t.Fatalf("missing Windows execution alias should not normalize: %q", got)
}
}
func TestWindowsPlainDirectoryWithoutCodexExecutableDoesNotNormalize(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("Windows directory normalization only applies on Windows")
}
dir := filepath.Join(t.TempDir(), "Codex")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatalf("failed to create plain directory: %v", err)
}
if got := normalizeCodexAppPath(dir); got != "" {
t.Fatalf("plain directory without Codex.exe should not normalize: %q", got)
}
}
func TestBuildCodexExecutableRejectsWindowsPlainDirectory(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("Windows executable lookup only applies on Windows")
}
dir := filepath.Join(t.TempDir(), "Codex")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatalf("failed to create plain directory: %v", err)
}
if got := buildCodexExecutable(dir); got != "" {
t.Fatalf("plain directory should not be treated as executable: %q", got)
}
}
func TestBuildWindowsPackagedActivationArguments(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("packaged activation is only built on Windows")
}
path := `C:\Program Files\WindowsApps\OpenAI.Codex_26.519.11010.0_x64__2p2nqsd0c76g0\app`
activation := buildWindowsPackagedActivation(path, 9229, []string{"--force_high_performance_gpu"})
if activation == nil {
t.Fatal("activation should be built")
}
if activation.appUserModelID != "OpenAI.Codex_2p2nqsd0c76g0!App" {
t.Fatalf("app user model id mismatch: %q", activation.appUserModelID)
}
if activation.arguments != "--remote-debugging-port=9229 --remote-allow-origins=http://127.0.0.1:9229 --force_high_performance_gpu" {
t.Fatalf("activation arguments mismatch: %q", activation.arguments)
}
}
func TestCodexLaunchPayloadPrefersDirectExecutableWhenReadable(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("Windows executable preference only applies on Windows")
}
appDir := filepath.Join(t.TempDir(), "OpenAI.Codex_26.519.11010.0_x64__2p2nqsd0c76g0", "app")
exe := filepath.Join(appDir, "Codex.exe")
writeTestFile(t, exe, "binary")
payload := codexLaunchPayload(appDir)
if got := stringFromAny(payload["method"]); got != "executable" {
t.Fatalf("readable MSIX app dir should prefer direct executable launch: %#v", payload)
}
if got := stringFromAny(payload["executable"]); got != exe {
t.Fatalf("executable mismatch: %q", got)
}
}
func TestWindowsPackagedExplorerCommandShape(t *testing.T) {
command := windowsPackagedExplorerCommand("OpenAI.Codex_abc!App", []string{"--remote-debugging-port=9229"})
if len(command) != 3 {
t.Fatalf("command length mismatch: %#v", command)
}
if command[0] != "explorer.exe" || command[1] != `shell:AppsFolder\OpenAI.Codex_abc!App` || command[2] != "--remote-debugging-port=9229" {
t.Fatalf("command shape mismatch: %#v", command)
}
}
func TestCodexLaunchPayloadUsesPackagedActivationShape(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("packaged activation is only used on Windows")
}
path := `C:\Program Files\WindowsApps\OpenAI.Codex_26.519.11010.0_x64__2p2nqsd0c76g0\app`
payload := codexLaunchPayload(path)
if !boolFromAny(payload["ready"]) {
t.Fatalf("packaged app should be launch-ready: %#v", payload)
}
if got := stringFromAny(payload["method"]); got != "packaged_activation" {
t.Fatalf("launch method mismatch: %q", got)
}
if got := stringFromAny(payload["appUserModelId"]); got != "OpenAI.Codex_2p2nqsd0c76g0!App" {
t.Fatalf("app user model id mismatch: %q", got)
}
}
func TestFindLatestWindowsCodexAppDirPrefersHighestVersion(t *testing.T) {
root := t.TempDir()
oldApp := filepath.Join(root, "OpenAI.Codex_1.2.3.0_x64__abc", "app")
newApp := filepath.Join(root, "OpenAI.Codex_26.519.11010.0_x64__abc", "app")
if err := os.MkdirAll(oldApp, 0o755); err != nil {
t.Fatalf("failed to create old app dir: %v", err)
}
if err := os.MkdirAll(newApp, 0o755); err != nil {
t.Fatalf("failed to create new app dir: %v", err)
}
if err := os.MkdirAll(filepath.Join(root, "OpenAI.Codex_not-a-version_x64__abc"), 0o755); err != nil {
t.Fatalf("failed to create invalid app dir: %v", err)
}
if got := findLatestWindowsCodexAppDir(root); got != newApp {
t.Fatalf("latest app dir mismatch: %q", got)
}
}