-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsettings.test.ts
More file actions
1038 lines (948 loc) · 36.5 KB
/
Copy pathsettings.test.ts
File metadata and controls
1038 lines (948 loc) · 36.5 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
import { describe, test, expect } from "bun:test";
import { chmod, mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { OPENCODE_GO_BASE_URL } from "../packages/opencode-go/src/index.js";
import {
isLocalSettings,
isSettings,
healOpenCodeGoProviders,
loadLocalSettings,
loadLocalSettingsWriteBase,
loadSettings,
normalizeOpenAICompatibleBaseURL,
resolveProvider,
saveGlobalSettings,
saveLocalSettings,
type Settings,
DEFAULT_SUBAGENT_MAX_TURNS,
MAX_SUBAGENT_MAX_TURNS_CAP,
resolveDefaultSubAgentMaxTurns,
resolveSubAgentMaxTurns,
clampSubAgentMaxTurns,
validateTaskMaxTurns,
toolWatchdogFromSettings,
loadGlobalSettingsWriteBase,
markLastChangelogVersion,
pushRecentModel,
toggleFavoriteModel,
listRecentModels,
listFavoriteModels,
} from "./config/settings.js";
const firepass: Settings = {
defaultProvider: "firepass",
providers: {
firepass: {
baseURL: "https://firepass.example/v1",
apiKey: "fp-key",
models: ["fp-large", "fp-small"],
defaultModel: "fp-large",
},
},
};
const twoProviders: Settings = {
defaultProvider: "a",
providers: {
a: { baseURL: "https://a/v1", apiKey: "a-key", models: ["a-model"] },
b: { baseURL: "https://b/v1", apiKey: "b-key", models: ["b-model"], defaultModel: "b-model" },
},
};
describe("normalizeOpenAICompatibleBaseURL", () => {
test("preserves a plain base URL", () => {
expect(normalizeOpenAICompatibleBaseURL("https://provider.example.com/v1")).toBe(
"https://provider.example.com/v1",
);
});
test("removes a trailing slash from a base URL", () => {
expect(normalizeOpenAICompatibleBaseURL("https://provider.example.com/v1/")).toBe(
"https://provider.example.com/v1",
);
});
test("normalizes a full chat completions endpoint to its base URL", () => {
expect(
normalizeOpenAICompatibleBaseURL("https://provider.example.com/v1/chat/completions"),
).toBe("https://provider.example.com/v1");
});
test("normalizes a full chat completions endpoint with trailing slash", () => {
expect(
normalizeOpenAICompatibleBaseURL("https://provider.example.com/v1/chat/completions/"),
).toBe("https://provider.example.com/v1");
});
test("trims whitespace around pasted URLs", () => {
expect(normalizeOpenAICompatibleBaseURL(" https://provider.example.com/v1 ")).toBe(
"https://provider.example.com/v1",
);
});
test("accepts localhost http URLs", () => {
expect(normalizeOpenAICompatibleBaseURL("http://localhost:11434/v1/")).toBe(
"http://localhost:11434/v1",
);
});
test("strips query and hash from pasted endpoint URLs", () => {
expect(
normalizeOpenAICompatibleBaseURL("https://provider.example.com/v1/chat/completions?x=1#frag"),
).toBe("https://provider.example.com/v1");
});
test("rejects malformed URL input with an actionable error", () => {
expect(() => normalizeOpenAICompatibleBaseURL("provider.example.com/v1")).toThrow(
/expected an absolute URL/,
);
});
test("rejects non-http URL schemes", () => {
expect(() => normalizeOpenAICompatibleBaseURL("file:///tmp/provider")).toThrow(
/expected http or https/,
);
});
});
describe("resolveProvider", () => {
test("file mode uses defaultProvider and defaultModel", () => {
const r = resolveProvider({ settings: firepass, local: null, cli: {} });
expect(r).toEqual({
providerName: "firepass",
baseURL: "https://firepass.example/v1",
apiKey: "fp-key",
model: "fp-large",
});
});
test("file mode normalizes configured provider baseURL", () => {
const settings: Settings = {
providers: {
only: {
baseURL: "https://o/v1/chat/completions/",
apiKey: "o-key",
models: ["m"],
},
},
};
const r = resolveProvider({ settings, local: null, cli: {} });
expect(r.baseURL).toBe("https://o/v1");
});
test("falls back to the first model when no defaultModel", () => {
const settings: Settings = {
providers: { only: { baseURL: "https://o/v1", apiKey: "o-key", models: ["first", "second"] } },
};
const r = resolveProvider({ settings, local: null, cli: {} });
expect(r.model).toBe("first");
expect(r.providerName).toBe("only");
});
test("a sole provider is used without a defaultProvider", () => {
const settings: Settings = {
providers: { solo: { baseURL: "https://s/v1", apiKey: "s-key", models: ["s-model"] } },
};
const r = resolveProvider({ settings, local: null, cli: {} });
expect(r.providerName).toBe("solo");
});
test("local selection overrides defaultProvider", () => {
const r = resolveProvider({ settings: twoProviders, local: { provider: "b" }, cli: {} });
expect(r.providerName).toBe("b");
expect(r.apiKey).toBe("b-key");
expect(r.model).toBe("b-model");
});
test("cli provider overrides local selection", () => {
const r = resolveProvider({
settings: twoProviders,
local: { provider: "a" },
cli: { provider: "b" },
});
expect(r.providerName).toBe("b");
});
test("model precedence: cli > local > defaultModel", () => {
const cli = resolveProvider({
settings: firepass,
local: { model: "fp-small" },
cli: { model: "cli-model" },
});
expect(cli.model).toBe("cli-model");
const local = resolveProvider({
settings: firepass,
local: { model: "fp-small" },
cli: {},
});
expect(local.model).toBe("fp-small");
});
test("throws when cli provider is not configured", () => {
expect(() =>
resolveProvider({ settings: twoProviders, local: null, cli: { provider: "c" } }),
).toThrow(/not found/);
});
test("names the offending provider when a local selection is not configured", () => {
expect(() =>
resolveProvider({ settings: twoProviders, local: { provider: "zzz" }, cli: {} }),
).toThrow(/Selected provider "zzz" is not configured/);
});
test("names the offending provider when defaultProvider is a typo", () => {
const settings: Settings = {
defaultProvider: "typo",
providers: { solo: { baseURL: "https://s/v1", apiKey: "s-key", models: ["s-model"] } },
};
expect(() => resolveProvider({ settings, local: null, cli: {} })).toThrow(
/Selected provider "typo" is not configured/,
);
});
test("throws listing every missing field", () => {
expect(() => resolveProvider({ settings: null, local: null, cli: {} })).toThrow(
/missing: provider, baseURL, apiKey, model/,
);
});
});
describe("validators", () => {
test("isSettings rejects a provider missing baseURL", () => {
expect(isSettings({ providers: { x: { apiKey: "k", models: ["m"] } } })).toBe(false);
});
test("isSettings accepts a valid shape", () => {
expect(isSettings(firepass)).toBe(true);
});
test("isSettings accepts bifrostVirtualKey and agentModelFallback", () => {
expect(
isSettings({
providers: {
bf: {
baseURL: "http://b:8080/v1",
apiKey: "sk-bf-k",
models: ["m"],
bifrostVirtualKey: true,
},
},
agentModelFallback: "none",
}),
).toBe(true);
});
test("isSettings accepts recentModels and favoriteModels", () => {
expect(
isSettings({
providers: firepass.providers,
recentModels: [{ provider: "firepass", model: "fp-large" }],
favoriteModels: [{ provider: "firepass", model: "fp-small" }],
}),
).toBe(true);
});
test("isSettings rejects malformed recentModels entries", () => {
expect(
isSettings({
providers: firepass.providers,
recentModels: [{ provider: "firepass" }],
}),
).toBe(false);
});
test("isSettings accepts showPromptCost", () => {
expect(isSettings({ providers: firepass.providers, showPromptCost: true })).toBe(true);
});
test("isLocalSettings rejects credentials", () => {
expect(isLocalSettings({ provider: "a", apiKey: "leak" })).toBe(false);
});
test("isLocalSettings accepts selection only", () => {
expect(isLocalSettings({ provider: "a", model: "m" })).toBe(true);
expect(isLocalSettings({})).toBe(true);
});
test("isLocalSettings accepts a valid reasoningEffort", () => {
expect(isLocalSettings({ model: "m", reasoningEffort: "high" })).toBe(true);
// "none" is OpenAI's explicit disable-reasoning value, a real level.
expect(isLocalSettings({ reasoningEffort: "none" })).toBe(true);
});
test("isLocalSettings rejects an invalid reasoningEffort", () => {
expect(isLocalSettings({ reasoningEffort: "legendary" })).toBe(false);
expect(isLocalSettings({ reasoningEffort: 5 })).toBe(false);
});
test("isLocalSettings accepts a valid env map", () => {
expect(isLocalSettings({ env: { FOO: "bar", BAZ: "qux" } })).toBe(true);
expect(isLocalSettings({ env: {} })).toBe(true);
});
test("isLocalSettings rejects a malformed env map", () => {
expect(isLocalSettings({ env: { FOO: 5 } })).toBe(false);
expect(isLocalSettings({ env: "not-an-object" })).toBe(false);
expect(isLocalSettings({ env: { FOO: { nested: true } } })).toBe(false);
});
});
describe("healOpenCodeGoProviders", () => {
test("pins flag and canonical baseURL for custom name with Go URL", () => {
const settings: Settings = {
providers: {
"go/personal": {
baseURL: "https://opencode.ai/zen/go/v1",
apiKey: "sk-go",
models: ["kimi-k2.7-code"],
},
},
};
expect(healOpenCodeGoProviders(settings)).toEqual(["go/personal"]);
expect(settings.providers["go/personal"]?.opencodeGo).toBe(true);
expect(settings.providers["go/personal"]?.baseURL).toBe(OPENCODE_GO_BASE_URL);
});
test("leaves bare Zen providers alone", () => {
const settings: Settings = {
providers: {
zen: {
baseURL: "https://opencode.ai/zen/v1",
apiKey: "sk-zen",
models: ["claude-sonnet-4-5"],
},
},
};
expect(healOpenCodeGoProviders(settings)).toEqual([]);
expect(settings.providers.zen?.opencodeGo).toBeUndefined();
expect(settings.providers.zen?.baseURL).toBe("https://opencode.ai/zen/v1");
});
test("is a no-op when already pinned", () => {
const settings: Settings = {
providers: {
"opencode-go": {
baseURL: OPENCODE_GO_BASE_URL,
apiKey: "sk-go",
models: ["kimi-k2.7-code"],
opencodeGo: true,
},
},
};
expect(healOpenCodeGoProviders(settings)).toEqual([]);
});
test("does not heal host spoofs or /zen/goodies paths", () => {
const settings: Settings = {
providers: {
spoof: {
baseURL: "https://not-opencode.ai/zen/go/v1",
apiKey: "sk",
models: ["kimi-k2.7-code"],
},
goodies: {
baseURL: "https://opencode.ai/zen/goodies",
apiKey: "sk",
models: ["kimi-k2.7-code"],
},
},
};
expect(healOpenCodeGoProviders(settings)).toEqual([]);
expect(settings.providers.spoof?.opencodeGo).toBeUndefined();
expect(settings.providers.goodies?.opencodeGo).toBeUndefined();
});
test("private gateway host is not healed by URL alone (needs flag or known name)", () => {
// Intentional FN: product URL matcher is public-host only (opencode.ai).
// Private reverse proxies must set opencodeGo or use the known provider id.
const settings: Settings = {
providers: {
"go-proxy": {
baseURL: "https://go.internal.example/zen/go/v1",
apiKey: "sk-go",
models: ["kimi-k2.7-code"],
},
},
};
expect(healOpenCodeGoProviders(settings)).toEqual([]);
expect(settings.providers["go-proxy"]?.opencodeGo).toBeUndefined();
expect(settings.providers["go-proxy"]?.baseURL).toBe(
"https://go.internal.example/zen/go/v1",
);
});
});
describe("loaders", () => {
test("loadSettings heals Go-by-URL providers onto disk", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, "settings.json");
await writeFile(
path,
JSON.stringify({
providers: {
"go/personal": {
baseURL: "https://opencode.ai/zen/go",
apiKey: "sk-go",
models: ["kimi-k2.7-code"],
},
},
}),
);
const loaded = await loadSettings(path);
expect(loaded?.providers["go/personal"]?.opencodeGo).toBe(true);
expect(loaded?.providers["go/personal"]?.baseURL).toBe(OPENCODE_GO_BASE_URL);
// Hard cutover: rewritten on disk, not only in memory.
const reloaded = await loadSettings(path);
expect(reloaded?.providers["go/personal"]?.opencodeGo).toBe(true);
expect(reloaded?.providers["go/personal"]?.baseURL).toBe(OPENCODE_GO_BASE_URL);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("loadSettings does not rewrite disk when heal is a no-op", async () => {
const { readFile, stat } = await import("node:fs/promises");
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, "settings.json");
const alreadyPinned = {
providers: {
"opencode-go": {
baseURL: OPENCODE_GO_BASE_URL,
apiKey: "sk-go",
models: ["kimi-k2.7-code"],
opencodeGo: true,
},
},
};
await writeFile(path, JSON.stringify(alreadyPinned));
const before = await readFile(path, "utf8");
const beforeStat = await stat(path);
// Ensure mtime resolution has room to move if a write sneaks in.
await Bun.sleep(20);
const loaded = await loadSettings(path);
expect(loaded?.providers["opencode-go"]?.opencodeGo).toBe(true);
const after = await readFile(path, "utf8");
const afterStat = await stat(path);
expect(after).toBe(before);
expect(afterStat.mtimeMs).toBe(beforeStat.mtimeMs);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("loadSettings logs healed provider ids when heal mutates", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
const writes: string[] = [];
const originalWrite = process.stderr.write.bind(process.stderr);
process.stderr.write = ((chunk: string | Uint8Array, ...rest: unknown[]) => {
writes.push(typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8"));
return (originalWrite as (c: string | Uint8Array, ...r: unknown[]) => boolean)(
chunk,
...rest,
);
}) as typeof process.stderr.write;
try {
const path = join(dir, "settings.json");
await writeFile(
path,
JSON.stringify({
providers: {
"go/personal": {
baseURL: "https://opencode.ai/zen/go",
apiKey: "sk-go",
models: ["kimi-k2.7-code"],
},
zen: {
baseURL: "https://opencode.ai/zen/v1",
apiKey: "sk-zen",
models: ["claude-sonnet-4-5"],
},
},
}),
);
await loadSettings(path);
const notice = writes.find((w) => w.includes("healed OpenCode Go providers"));
expect(notice).toBeDefined();
expect(notice).toContain("go/personal");
expect(notice).not.toContain("zen");
} finally {
process.stderr.write = originalWrite;
await rm(dir, { recursive: true, force: true });
}
});
test("loadSettings stays quiet on heal no-op", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
const writes: string[] = [];
const originalWrite = process.stderr.write.bind(process.stderr);
process.stderr.write = ((chunk: string | Uint8Array, ...rest: unknown[]) => {
writes.push(typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8"));
return (originalWrite as (c: string | Uint8Array, ...r: unknown[]) => boolean)(
chunk,
...rest,
);
}) as typeof process.stderr.write;
try {
const path = join(dir, "settings.json");
await writeFile(
path,
JSON.stringify({
providers: {
"opencode-go": {
baseURL: OPENCODE_GO_BASE_URL,
apiKey: "sk-go",
models: ["kimi-k2.7-code"],
opencodeGo: true,
},
},
}),
);
await loadSettings(path);
expect(writes.some((w) => w.includes("healed OpenCode Go providers"))).toBe(false);
} finally {
process.stderr.write = originalWrite;
await rm(dir, { recursive: true, force: true });
}
});
test("loadSettings keeps in-memory heal when disk save fails", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, "settings.json");
await writeFile(
path,
JSON.stringify({
providers: {
"go/personal": {
baseURL: "https://opencode.ai/zen/go",
apiKey: "sk-go",
models: ["kimi-k2.7-code"],
},
},
}),
);
// Read-only dir: heal save (temp write + rename) fails; load must not throw.
await chmod(dir, 0o555);
const loaded = await loadSettings(path);
expect(loaded?.providers["go/personal"]?.opencodeGo).toBe(true);
expect(loaded?.providers["go/personal"]?.baseURL).toBe(OPENCODE_GO_BASE_URL);
} finally {
await chmod(dir, 0o755).catch(() => {});
await rm(dir, { recursive: true, force: true });
}
});
test("loadSettings returns null for a missing file", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
expect(await loadSettings(join(dir, "nope.json"))).toBeNull();
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("loadSettings throws on an invalid schema", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, "settings.json");
await writeFile(path, JSON.stringify({ providers: { x: { models: [] } } }));
await expect(loadSettings(path)).rejects.toThrow(/Invalid settings schema/);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("loadSettings preserves bifrostVirtualKey and agentModelFallback", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, "settings.json");
await writeFile(
path,
JSON.stringify({
providers: {
bf: {
baseURL: "http://b:8080/v1",
apiKey: "k",
models: ["m"],
bifrostVirtualKey: true,
},
},
agentModelFallback: "active",
}),
);
const loaded = await loadSettings(path);
expect(loaded?.providers.bf?.bifrostVirtualKey).toBe(true);
expect(loaded?.agentModelFallback).toBe("active");
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("loadSettings preserves plugin and web-provider fields through a round trip", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, "settings.json");
await writeFile(
path,
JSON.stringify({
providers: { a: { baseURL: "https://a/v1", apiKey: "k", models: ["m"] } },
workflowProfiles: { fast: { implement: "m" } },
web: "exa",
plugins: { exa: { enabled: true, credentials: { apiKey: "exa-key" } } },
pluginPaths: ["/abs/plugins/exa", "./local-plugin"],
discoverClaudePlugins: true,
}),
);
const loaded = await loadSettings(path);
expect(loaded?.workflowProfiles).toEqual({ fast: { implement: "m" } });
expect(loaded?.web).toBe("exa");
expect(loaded?.plugins).toEqual({ exa: { enabled: true, credentials: { apiKey: "exa-key" } } });
expect(loaded?.pluginPaths).toEqual(["/abs/plugins/exa", "./local-plugin"]);
expect(loaded?.discoverClaudePlugins).toBe(true);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("loadLocalSettings fails open on credentials and unknown keys", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
await mkdir(join(dir, ".corbits"), { recursive: true });
const path = join(dir, ".corbits", "settings.json");
await writeFile(
path,
JSON.stringify({ provider: "a", model: "m1", apiKey: "leak", providers: {}, weird: true }),
);
// Must not throw — app starts with known keys applied.
const loaded = await loadLocalSettings(path);
expect(loaded).toEqual({ provider: "a", model: "m1" });
// Credentials never load.
expect(loaded).not.toHaveProperty("apiKey");
const { loadLocalSettingsResult } = await import("./config/settings.js");
const result = await loadLocalSettingsResult(path);
expect(result.settings).toEqual({ provider: "a", model: "m1" });
expect(result.diagnostics.length).toBeGreaterThan(0);
expect(result.diagnostics.some((d) => /credential|apiKey|unknown/i.test(d.message))).toBe(true);
expect(result.diagnostics.every((d) => d.fix.length > 0)).toBe(true);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("loadLocalSettings fails open on invalid JSON with diagnostics", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, "settings.json");
await writeFile(path, "{ not json");
expect(await loadLocalSettings(path)).toBeNull();
const { loadLocalSettingsResult } = await import("./config/settings.js");
const result = await loadLocalSettingsResult(path);
expect(result.settings).toBeNull();
expect(result.diagnostics.some((d) => /Invalid JSON/i.test(d.message))).toBe(true);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("loadLocalSettingsWriteBase distinguishes absent, cleaned, and unusable", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, "settings.json");
// Absent: empty base is safe to create.
expect(await loadLocalSettingsWriteBase(path)).toEqual({});
// Partial fail-open: cleaned known fields are the base.
await writeFile(
path,
JSON.stringify({ provider: "a", model: "m1", apiKey: "leak", weird: true }),
);
expect(await loadLocalSettingsWriteBase(path)).toEqual({ provider: "a", model: "m1" });
// Invalid JSON: skip write — do not collapse to {}.
await writeFile(path, "{ not json");
expect(await loadLocalSettingsWriteBase(path)).toBeNull();
// Non-object: skip write.
await writeFile(path, JSON.stringify(["not", "object"]));
expect(await loadLocalSettingsWriteBase(path)).toBeNull();
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("loadSettings preserves tools block through a round trip", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, ".corbits", "settings.json");
const withTools: Settings = {
...firepass,
tools: { timeoutMs: 120_000, maxTimeoutMs: 600_000, waitForApproval: false },
};
await saveGlobalSettings(path, withTools);
const loaded = await loadSettings(path);
expect(loaded?.tools).toEqual({
timeoutMs: 120_000,
maxTimeoutMs: 600_000,
waitForApproval: false,
});
expect(loaded).toEqual(withTools);
expect(toolWatchdogFromSettings(loaded)).toEqual({
defaultMs: 120_000,
maxMs: 600_000,
waitForApproval: false,
});
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("loadGlobalSettingsWriteBase distinguishes absent from unreadable", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, "settings.json");
// Absent file: a fresh minimal base is a safe write target.
expect(await loadGlobalSettingsWriteBase(path)).toEqual({ providers: {} });
// Readable file: its contents are the base.
await saveGlobalSettings(path, firepass);
expect(await loadGlobalSettingsWriteBase(path)).toEqual(firepass);
// Unreadable file: null so the caller skips the write instead of
// overwriting the whole settings file with a minimal base.
await writeFile(path, "{ not json");
expect(await loadGlobalSettingsWriteBase(path)).toBeNull();
await writeFile(path, JSON.stringify({ providers: "wrong-shape" }));
expect(await loadGlobalSettingsWriteBase(path)).toBeNull();
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("toolWatchdogFromSettings maps waitForApproval alone", () => {
expect(toolWatchdogFromSettings({ providers: {}, tools: { waitForApproval: true } })).toEqual({
waitForApproval: true,
});
expect(toolWatchdogFromSettings({ providers: {} })).toBeUndefined();
});
});
describe("sessionMode", () => {
test("loadSettings round-trips sessionMode", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, ".corbits", "settings.json");
await saveGlobalSettings(path, { ...firepass, sessionMode: "single" });
expect(await loadSettings(path)).toEqual({ ...firepass, sessionMode: "single" });
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("loadLocalSettings round-trips sessionMode", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-local-"));
try {
const path = join(dir, ".corbits", "settings.json");
await saveLocalSettings(path, { provider: "a", sessionMode: "orchestrator" });
expect(await loadLocalSettings(path)).toEqual({ provider: "a", sessionMode: "orchestrator" });
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("rejects invalid sessionMode", () => {
expect(isSettings({ providers: firepass.providers, sessionMode: "fleet" })).toBe(false);
expect(isLocalSettings({ provider: "a", sessionMode: 1 })).toBe(false);
});
});
test("loadSettings round-trips showPromptCost", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, ".corbits", "settings.json");
await saveGlobalSettings(path, { ...firepass, showPromptCost: true });
expect(await loadSettings(path)).toEqual({ ...firepass, showPromptCost: true });
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("loadSettings tolerates a legacy maxConcurrentSubAgents key", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, ".corbits", "settings.json");
await mkdir(join(dir, ".corbits"), { recursive: true });
await writeFile(
path,
JSON.stringify({ ...firepass, maxConcurrentSubAgents: 6 }, null, 2),
"utf8",
);
expect(await loadSettings(path)).toEqual(firepass);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
describe("lastChangelogVersion", () => {
test("isSettings accepts a version string", () => {
expect(
isSettings({
providers: firepass.providers,
lastChangelogVersion: "0.2.86",
}),
).toBe(true);
});
test("loadSettings round-trips lastChangelogVersion", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, ".corbits", "settings.json");
await saveGlobalSettings(path, { ...firepass, lastChangelogVersion: "0.2.85" });
expect(await loadSettings(path)).toEqual({ ...firepass, lastChangelogVersion: "0.2.85" });
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("markLastChangelogVersion stamps without clobbering other fields", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, ".corbits", "settings.json");
await saveGlobalSettings(path, { ...firepass, onboarded: true });
await markLastChangelogVersion(path, "0.2.86");
const loaded = await loadSettings(path);
expect(loaded?.lastChangelogVersion).toBe("0.2.86");
expect(loaded?.onboarded).toBe(true);
expect(loaded?.defaultProvider).toBe("firepass");
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("markLastChangelogVersion ignores empty versions", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, ".corbits", "settings.json");
await saveGlobalSettings(path, firepass);
await markLastChangelogVersion(path, " ");
expect(await loadSettings(path)).toEqual(firepass);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
});
describe("subagentMaxTurns", () => {
test("defaults to 30 when unset", () => {
expect(resolveDefaultSubAgentMaxTurns(null)).toBe(DEFAULT_SUBAGENT_MAX_TURNS);
expect(resolveDefaultSubAgentMaxTurns({ providers: {} })).toBe(30);
});
test("resolveSubAgentMaxTurns precedence", () => {
const settings = { providers: {}, subagentMaxTurns: 40 };
expect(resolveSubAgentMaxTurns({ settings })).toBe(40);
expect(resolveSubAgentMaxTurns({ settings, profileMaxTurns: 55 })).toBe(55);
expect(
resolveSubAgentMaxTurns({ settings, profileMaxTurns: 55, taskMaxTurns: 70 }),
).toBe(70);
});
test("clampSubAgentMaxTurns enforces floor and cap", () => {
expect(clampSubAgentMaxTurns(0)).toBe(1);
expect(clampSubAgentMaxTurns(150)).toBe(MAX_SUBAGENT_MAX_TURNS_CAP);
});
test("validateTaskMaxTurns rejects out of range", () => {
expect(validateTaskMaxTurns(101).ok).toBe(false);
expect(validateTaskMaxTurns(0).ok).toBe(false);
expect(validateTaskMaxTurns(50).ok).toBe(true);
});
test("loadSettings round-trips subagentMaxTurns", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, ".corbits", "settings.json");
await saveGlobalSettings(path, { ...firepass, subagentMaxTurns: 42 });
expect(await loadSettings(path)).toEqual({ ...firepass, subagentMaxTurns: 42 });
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("rejects invalid subagentMaxTurns in settings", () => {
expect(
isSettings({
providers: firepass.providers,
subagentMaxTurns: 0,
}),
).toBe(false);
expect(
isSettings({
providers: firepass.providers,
subagentMaxTurns: 101,
}),
).toBe(false);
});
});
describe("saveGlobalSettings", () => {
test("round-trips a settings object through loadSettings", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, ".corbits", "settings.json");
await saveGlobalSettings(path, firepass);
expect(await loadSettings(path)).toEqual(firepass);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("creates the .corbits directory when missing", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, "nested", ".corbits", "settings.json");
await saveGlobalSettings(path, firepass);
const loaded = await loadSettings(path);
expect(loaded?.defaultProvider).toBe("firepass");
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("refuses to write invalid settings", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, ".corbits", "settings.json");
const invalid = { providers: { x: { models: [] } } } as unknown as Settings;
await expect(saveGlobalSettings(path, invalid)).rejects.toThrow(/invalid global settings/);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
});
describe("saveLocalSettings", () => {
test("round-trips a selection through loadLocalSettings", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, ".corbits", "settings.json");
await saveLocalSettings(path, { provider: "firepass", model: "fp-small" });
expect(await loadLocalSettings(path)).toEqual({ provider: "firepass", model: "fp-small" });
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("round-trips a reasoningEffort through loadLocalSettings", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, ".corbits", "settings.json");
await saveLocalSettings(path, { provider: "firepass", model: "fp-small", reasoningEffort: "high" });
expect(await loadLocalSettings(path)).toEqual({
provider: "firepass",
model: "fp-small",
reasoningEffort: "high",
});
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("loadLocalSettings fails open on invalid reasoningEffort", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
await mkdir(join(dir, ".corbits"), { recursive: true });
const path = join(dir, ".corbits", "settings.json");
await writeFile(path, JSON.stringify({ model: "m", reasoningEffort: "legendary" }));
// Fail open: keep model, drop invalid effort, surface diagnostic.
expect(await loadLocalSettings(path)).toEqual({ model: "m" });
const { loadLocalSettingsResult } = await import("./config/settings.js");
const result = await loadLocalSettingsResult(path);
expect(result.settings).toEqual({ model: "m" });
expect(result.diagnostics.some((d) => /reasoningEffort/i.test(d.message))).toBe(true);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("creates the .corbits directory when missing", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, "nested", ".corbits", "settings.json");
await saveLocalSettings(path, { provider: "a" });
expect(await loadLocalSettings(path)).toEqual({ provider: "a" });
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test("refuses to write credentials", async () => {
const dir = await mkdtemp(join(tmpdir(), "ic-settings-"));
try {
const path = join(dir, ".corbits", "settings.json");
// Force an invalid shape past the type system to prove the guard holds.
const leaky = { provider: "a", apiKey: "leak" } as unknown as { provider?: string };
await expect(saveLocalSettings(path, leaky)).rejects.toThrow(/allowed/);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
});
describe("recent and favorite model helpers", () => {
test("pushRecentModel prepends, dedupes, and caps", () => {
let s: Settings = { providers: firepass.providers };
s = pushRecentModel(s, { provider: "a", model: "m1" });