Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

serverSettings.test.ts

1,142 lines42.5 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import {
3 DEFAULT_SERVER_SETTINGS,
4 ProviderDriverKind,
5 ProviderInstanceId,
6 resolveProviderInstanceEnabled,
7 ServerSettings,
8 ServerSettingsPatch,
9} from "@t3tools/contracts";
10import { createModelSelection } from "@t3tools/shared/model";
11import { assert, it } from "@effect/vitest";
12import * as Effect from "effect/Effect";
13import * as Duration from "effect/Duration";
14import * as FileSystem from "effect/FileSystem";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as Path from "effect/Path";
18import * as PlatformError from "effect/PlatformError";
19import * as Schema from "effect/Schema";
20import * as Stream from "effect/Stream";
21import * as SqlClient from "effect/unstable/sql/SqlClient";
22import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
23import * as ServerConfig from "./config.ts";
24import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts";
25import * as ServerSettingsModule from "./serverSettings.ts";
26import { resolveProviderInstanceTerminalEnvironment } from "./terminal/Manager.ts";
27​
28const decodeSettingsPatch = Schema.decodeUnknownEffect(ServerSettingsPatch);
29const decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings);
30​
31const makeServerSettingsLayer = () =>
32 ServerSettingsModule.layer.pipe(
33 Layer.provide(ServerSecretStore.layer),
34 Layer.provideMerge(Layer.fresh(SqlitePersistenceMemory)),
35 Layer.provideMerge(
36 Layer.fresh(
37 ServerConfig.layerTest(process.cwd(), {
38 prefix: "t3code-server-settings-test-",
39 }),
40 ),
41 ),
42 );
43​
44const makeFailingSecretStoreLayer = (cause: ServerSecretStore.SecretStoreError) =>
45 Layer.succeed(
46 ServerSecretStore.ServerSecretStore,
47 ServerSecretStore.ServerSecretStore.of({
48 get: () => Effect.fail(cause),
49 set: () => Effect.void,
50 create: () => Effect.void,
51 getOrCreateRandom: () => Effect.succeed(new Uint8Array()),
52 remove: () => Effect.void,
53 }),
54 );
55​
56const recordProviderUsage = (provider: string, instanceId: string | null = provider) =>
57 Effect.gen(function* () {
58 const sql = yield* SqlClient.SqlClient;
59 yield* sql`
60 INSERT INTO projection_thread_sessions (
61 thread_id,
62 status,
63 provider_name,
64 provider_instance_id,
65 updated_at
66 )
67 VALUES (
68 ${`thread-${instanceId ?? provider}`},
69 ${"ready"},
70 ${provider},
71 ${instanceId},
72 ${"2026-08-25T00:00:00.000Z"}
73 )
74 `;
75 });
76​
77it.layer(NodeServices.layer)("server settings", (it) => {
78 it.effect("preserves context when reading a provider environment secret fails", () => {
79 const platformCause = PlatformError.systemError({
80 _tag: "PermissionDenied",
81 module: "FileSystem",
82 method: "readFile",
83 pathOrDescriptor: "provider environment secret",
84 description: "Secret backend unavailable.",
85 });
86 const cause = new ServerSecretStore.SecretStoreReadError({
87 resource: "provider environment secret",
88 cause: platformCause,
89 });
90 const configLayer = Layer.fresh(
91 ServerConfig.layerTest(process.cwd(), {
92 prefix: "t3code-server-settings-secret-failure-test-",
93 }),
94 );
95 const settingsLayer = ServerSettingsModule.layer.pipe(
96 Layer.provide(makeFailingSecretStoreLayer(cause)),
97 Layer.provideMerge(Layer.fresh(SqlitePersistenceMemory)),
98 Layer.provideMerge(configLayer),
99 );
100​
101 return Effect.gen(function* () {
102 const serverConfig = yield* ServerConfig.ServerConfig;
103 const fileSystem = yield* FileSystem.FileSystem;
104 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
105 yield* fileSystem.writeFileString(
106 serverConfig.settingsPath,
107 '{"providerInstances":{"codex_personal":{"driver":"codex","environment":[{"name":"OPENROUTER_API_KEY","value":"","sensitive":true,"valueRedacted":true}],"config":{}}}}',
108 );
109​
110 const error = yield* Effect.flip(serverSettings.getSettings);
111​
112 assert.deepInclude(error, {
113 _tag: "ServerSettingsError",
114 operation: "read-secret",
115 providerInstanceId: "codex_personal",
116 environmentVariable: "OPENROUTER_API_KEY",
117 });
118 assert.strictEqual(error.cause, cause);
119 assert.notInclude(error.message, cause.message);
120 }).pipe(Effect.provide(settingsLayer));
121 });
122​
123 it.effect("identifies provider history query failures", () =>
124 Effect.gen(function* () {
125 const serverConfig = yield* ServerConfig.ServerConfig;
126 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
127 const sql = yield* SqlClient.SqlClient;
128 yield* sql`DROP TABLE projection_thread_sessions`;
129​
130 const error = yield* Effect.flip(serverSettings.getSettings);
131​
132 assert.deepInclude(error, {
133 _tag: "ServerSettingsError",
134 operation: "read-provider-history",
135 settingsPath: serverConfig.settingsPath,
136 });
137 }).pipe(Effect.provide(makeServerSettingsLayer())),
138 );
139​
140 it.effect("decodes nested settings patches", () =>
141 Effect.gen(function* () {
142 assert.deepEqual(
143 yield* decodeSettingsPatch({ providers: { codex: { binaryPath: "/tmp/codex" } } }),
144 {
145 providers: { codex: { binaryPath: "/tmp/codex" } },
146 },
147 );
148​
149 assert.deepEqual(
150 yield* decodeSettingsPatch({
151 textGenerationModelSelection: {
152 options: [{ id: "fastMode", value: false }],
153 },
154 }),
155 {
156 textGenerationModelSelection: {
157 options: [{ id: "fastMode", value: false }],
158 },
159 },
160 );
161 }),
162 );
163​
164 it.effect(
165 "decodes legacy object-shaped textGenerationModelSelection.options from settings.json",
166 () =>
167 Effect.gen(function* () {
168 const decoded = yield* decodeServerSettings({
169 textGenerationModelSelection: {
170 provider: ProviderDriverKind.make("codex"),
171 model: "gpt-5.4-mini",
172 options: { reasoningEffort: "low" },
173 },
174 });
175​
176 assert.deepEqual(decoded.textGenerationModelSelection, {
177 instanceId: ProviderInstanceId.make("codex"),
178 model: "gpt-5.4-mini",
179 options: [{ id: "reasoningEffort", value: "low" }],
180 });
181 }),
182 );
183​
184 it.effect("deep merges nested settings updates without dropping siblings", () =>
185 Effect.gen(function* () {
186 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
187​
188 yield* serverSettings.updateSettings({
189 providers: {
190 codex: {
191 binaryPath: "/usr/local/bin/codex",
192 homePath: "/Users/julius/.codex",
193 },
194 claudeAgent: {
195 binaryPath: "/usr/local/bin/claude",
196 customModels: ["claude-custom"],
197 },
198 },
199 textGenerationModelSelection: {
200 instanceId: ProviderInstanceId.make("codex"),
201 model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
202 options: createModelSelection(
203 ProviderInstanceId.make("codex"),
204 DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
205 [
206 { id: "reasoningEffort", value: "high" },
207 { id: "fastMode", value: true },
208 ],
209 ).options!,
210 },
211 });
212​
213 const next = yield* serverSettings.updateSettings({
214 providers: {
215 codex: {
216 binaryPath: "/opt/homebrew/bin/codex",
217 },
218 },
219 textGenerationModelSelection: {
220 options: [{ id: "fastMode", value: false }],
221 },
222 });
223​
224 assert.deepEqual(next.providers.codex, {
225 enabled: true,
226 binaryPath: "/opt/homebrew/bin/codex",
227 homePath: "/Users/julius/.codex",
228 shadowHomePath: "",
229 launchArgs: "",
230 customModels: [],
231 });
232 assert.deepEqual(next.providers.claudeAgent, {
233 enabled: true,
234 binaryPath: "/usr/local/bin/claude",
235 homePath: "",
236 customModels: ["claude-custom"],
237 launchArgs: "",
238 autoCompactWindow: "",
239 });
240 assert.deepEqual(
241 next.textGenerationModelSelection,
242 createModelSelection(
243 ProviderInstanceId.make("codex"),
244 DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
245 [
246 { id: "reasoningEffort", value: "high" },
247 { id: "fastMode", value: false },
248 ],
249 ),
250 );
251 }).pipe(Effect.provide(makeServerSettingsLayer())),
252 );
253​
254 it.effect("buffers changes after a subscription is acquired but before it is consumed", () =>
255 Effect.scoped(
256 Effect.gen(function* () {
257 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
258 const changes = yield* serverSettings.subscribeChanges;
259​
260 yield* serverSettings.updateSettings({
261 providers: {
262 codex: {
263 binaryPath: "/usr/local/bin/codex-next",
264 },
265 },
266 });
267​
268 const firstChange = yield* changes.pipe(Stream.runHead, Effect.timeout("1 second"));
269 assert.equal(
270 Option.getOrUndefined(firstChange)?.providers.codex.binaryPath,
271 "/usr/local/bin/codex-next",
272 );
273 }),
274 ).pipe(Effect.provide(makeServerSettingsLayer())),
275 );
276​
277 it.effect("persists custom usage prices and removes them from the settings file", () =>
278 Effect.scoped(
279 Effect.gen(function* () {
280 const serverConfig = yield* ServerConfig.ServerConfig;
281 const fileSystem = yield* FileSystem.FileSystem;
282 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
283 const prices = {
284 inputCostPerMillionTokens: 2,
285 outputCostPerMillionTokens: 8,
286 cacheReadCostPerMillionTokens: 0,
287 };
288 const readPersisted = fileSystem
289 .readFileString(serverConfig.settingsPath)
290 .pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(ServerSettings))));
291​
292 yield* serverSettings.updateSettings({ usagePriceOverrides: { "example-model": prices } });
293 const persisted = yield* readPersisted;
294 assert.deepStrictEqual(persisted.usagePriceOverrides, { "example-model": prices });
295​
296 yield* serverSettings.updateSettings({ usagePriceOverrides: { "example-model": null } });
297 const restored = yield* readPersisted;
298 assert.deepStrictEqual(restored.usagePriceOverrides, {});
299 }),
300 ).pipe(Effect.provide(makeServerSettingsLayer())),
301 );
302​
303 it.effect("persists and broadcasts thread settlement settings", () =>
304 Effect.scoped(
305 Effect.gen(function* () {
306 const serverConfig = yield* ServerConfig.ServerConfig;
307 const fileSystem = yield* FileSystem.FileSystem;
308 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
309 const changes = yield* serverSettings.subscribeChanges;
310​
311 const next = yield* serverSettings.updateSettings({
312 sidebarAutoSettleAfterDays: null,
313 sidebarAutoSettleOnMerge: false,
314 });
315 const change = Option.getOrUndefined(yield* Stream.runHead(changes));
316 const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
317 // Inspect raw persisted JSON before schema decoding can apply defaults.
318 // @effect-diagnostics-next-line preferSchemaOverJson:off
319 const persisted = JSON.parse(raw) as Record<string, unknown>;
320​
321 assert.strictEqual(next.sidebarAutoSettleAfterDays, null);
322 assert.isFalse(next.sidebarAutoSettleOnMerge);
323 assert.strictEqual(change?.sidebarAutoSettleAfterDays, null);
324 assert.isFalse(change?.sidebarAutoSettleOnMerge);
325 assert.strictEqual(persisted.sidebarAutoSettleAfterDays, null);
326 assert.isFalse(persisted.sidebarAutoSettleOnMerge);
327 }),
328 ).pipe(Effect.provide(makeServerSettingsLayer())),
329 );
330​
331 it.effect("preserves model when switching providers via textGenerationModelSelection", () =>
332 Effect.gen(function* () {
333 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
334​
335 // Start with Claude text generation selection
336 yield* serverSettings.updateSettings({
337 textGenerationModelSelection: {
338 instanceId: ProviderInstanceId.make("claudeAgent"),
339 model: "claude-sonnet-4-6",
340 options: createModelSelection(
341 ProviderInstanceId.make("claudeAgent"),
342 "claude-sonnet-4-6",
343 [{ id: "effort", value: "high" }],
344 ).options!,
345 },
346 });
347​
348 // Switch to Codex — the stale Claude "effort" in options must not
349 // cause the update to lose the selected model.
350 const next = yield* serverSettings.updateSettings({
351 textGenerationModelSelection: {
352 instanceId: ProviderInstanceId.make("codex"),
353 model: "gpt-5.4",
354 options: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
355 { id: "reasoningEffort", value: "high" },
356 ]).options!,
357 },
358 });
359​
360 assert.deepEqual(
361 next.textGenerationModelSelection,
362 createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
363 { id: "reasoningEffort", value: "high" },
364 ]),
365 );
366 }).pipe(Effect.provide(makeServerSettingsLayer())),
367 );
368​
369 it.effect("preserves custom provider instance text generation selections", () =>
370 Effect.gen(function* () {
371 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
372​
373 const next = yield* serverSettings.updateSettings({
374 providerInstances: {
375 [ProviderInstanceId.make("claude_openrouter")]: {
376 driver: ProviderDriverKind.make("claudeAgent"),
377 enabled: true,
378 config: { customModels: ["openai/gpt-5.5"] },
379 },
380 },
381 textGenerationModelSelection: {
382 instanceId: ProviderInstanceId.make("claude_openrouter"),
383 model: "openai/gpt-5.5",
384 },
385 });
386​
387 assert.deepEqual(next.textGenerationModelSelection, {
388 instanceId: ProviderInstanceId.make("claude_openrouter"),
389 model: "openai/gpt-5.5",
390 });
391 }).pipe(Effect.provide(makeServerSettingsLayer())),
392 );
393​
394 it.effect(
395 "uses explicit provider instance enabled state over legacy provider enabled state",
396 () =>
397 Effect.gen(function* () {
398 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
399 const instanceId = ProviderInstanceId.make("claude_openrouter");
400​
401 const next = yield* serverSettings.updateSettings({
402 providers: {
403 claudeAgent: {
404 enabled: false,
405 },
406 },
407 providerInstances: {
408 [instanceId]: {
409 driver: ProviderDriverKind.make("claudeAgent"),
410 enabled: true,
411 config: { customModels: ["openai/gpt-5.5"] },
412 },
413 },
414 textGenerationModelSelection: {
415 instanceId,
416 model: "openai/gpt-5.5",
417 },
418 });
419​
420 assert.deepEqual(next.textGenerationModelSelection, {
421 instanceId,
422 model: "openai/gpt-5.5",
423 });
424 }).pipe(Effect.provide(makeServerSettingsLayer())),
425 );
426​
427 it.effect("preserves enabled text generation selections for non-built-in drivers", () =>
428 Effect.gen(function* () {
429 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
430 const instanceId = ProviderInstanceId.make("openrouter_text");
431​
432 const next = yield* serverSettings.updateSettings({
433 providerInstances: {
434 [instanceId]: {
435 driver: ProviderDriverKind.make("openrouter"),
436 enabled: true,
437 config: { customModels: ["openai/gpt-5.5"] },
438 },
439 },
440 textGenerationModelSelection: {
441 instanceId,
442 model: "openai/gpt-5.5",
443 },
444 });
445​
446 assert.deepEqual(next.textGenerationModelSelection, {
447 instanceId,
448 model: "openai/gpt-5.5",
449 });
450 }).pipe(Effect.provide(makeServerSettingsLayer())),
451 );
452​
453 it.effect(
454 "preserves the source control writer selection when its provider instance is disabled",
455 () =>
456 Effect.gen(function* () {
457 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
458 const serverConfig = yield* ServerConfig.ServerConfig;
459 const fileSystem = yield* FileSystem.FileSystem;
460 const instanceId = ProviderInstanceId.make("codex_writer");
461 const sourceControlWriterModelSelection = {
462 instanceId,
463 model: "gpt-5.4-mini",
464 };
465​
466 yield* serverSettings.updateSettings({
467 providerInstances: {
468 [instanceId]: {
469 driver: ProviderDriverKind.make("codex"),
470 enabled: true,
471 config: {},
472 },
473 },
474 sourceControlWriterModelSelection,
475 });
476​
477 const next = yield* serverSettings.updateSettings({
478 providerInstances: {
479 [instanceId]: {
480 driver: ProviderDriverKind.make("codex"),
481 enabled: false,
482 config: {},
483 },
484 },
485 });
486​
487 assert.deepEqual(next.sourceControlWriterModelSelection, sourceControlWriterModelSelection);
488 assert.deepEqual(
489 ServerSettingsModule.resolveSourceControlWriterModelSelection(next),
490 next.textGenerationModelSelection,
491 );
492 assert.deepEqual(
493 (yield* serverSettings.getSettings).sourceControlWriterModelSelection,
494 sourceControlWriterModelSelection,
495 );
496​
497 const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
498 assert.deepEqual(
499 // @effect-diagnostics-next-line preferSchemaOverJson:off
500 JSON.parse(raw).sourceControlWriterModelSelection,
501 sourceControlWriterModelSelection,
502 );
503​
504 const restored = yield* serverSettings.updateSettings({
505 providerInstances: {
506 [instanceId]: {
507 driver: ProviderDriverKind.make("codex"),
508 enabled: true,
509 config: {},
510 },
511 },
512 });
513 assert.deepEqual(
514 ServerSettingsModule.resolveSourceControlWriterModelSelection(restored),
515 sourceControlWriterModelSelection,
516 );
517 }).pipe(Effect.provide(makeServerSettingsLayer())),
518 );
519​
520 it.effect("drops stale text generation options when resetting model selection", () =>
521 Effect.gen(function* () {
522 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
523​
524 yield* serverSettings.updateSettings({
525 textGenerationModelSelection: {
526 instanceId: ProviderInstanceId.make("codex"),
527 model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
528 options: createModelSelection(
529 ProviderInstanceId.make("codex"),
530 DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
531 [
532 { id: "reasoningEffort", value: "high" },
533 { id: "fastMode", value: true },
534 ],
535 ).options!,
536 },
537 });
538​
539 const next = yield* serverSettings.updateSettings({
540 textGenerationModelSelection: {
541 instanceId: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.instanceId,
542 model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
543 },
544 });
545​
546 assert.deepEqual(next.textGenerationModelSelection, {
547 instanceId: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.instanceId,
548 model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
549 });
550 }).pipe(Effect.provide(makeServerSettingsLayer())),
551 );
552​
553 it.effect("replaces provider instance maps when clearing optional fields", () =>
554 Effect.gen(function* () {
555 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
556 const codexId = ProviderInstanceId.make("codex");
557​
558 yield* serverSettings.updateSettings({
559 providerInstances: {
560 [codexId]: {
561 driver: ProviderDriverKind.make("codex"),
562 displayName: "Codex Work",
563 accentColor: "#7c3aed",
564 enabled: true,
565 config: { homePath: "~/.codex" },
566 },
567 },
568 });
569​
570 const next = yield* serverSettings.updateSettings({
571 providerInstances: {
572 [codexId]: {
573 driver: ProviderDriverKind.make("codex"),
574 displayName: "Codex Work",
575 enabled: true,
576 config: { homePath: "~/.codex" },
577 },
578 },
579 });
580​
581 assert.deepEqual(next.providerInstances[codexId], {
582 driver: ProviderDriverKind.make("codex"),
583 displayName: "Codex Work",
584 enabled: true,
585 config: { homePath: "~/.codex" },
586 });
587 }).pipe(Effect.provide(makeServerSettingsLayer())),
588 );
589​
590 it.effect("enables previously used providers from sparse settings files", () =>
591 Effect.gen(function* () {
592 const serverConfig = yield* ServerConfig.ServerConfig;
593 const fileSystem = yield* FileSystem.FileSystem;
594 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
595 yield* fileSystem.writeFileString(
596 serverConfig.settingsPath,
597 '{"providers":{"opencode":{"serverUrl":"http://127.0.0.1:4096"}}}',
598 );
599 yield* recordProviderUsage("opencode");
600​
601 const settings = yield* serverSettings.getSettings;
602​
603 assert.isFalse(settings.providers.grok.enabled);
604 assert.isTrue(settings.providers.opencode.enabled);
605 assert.isFalse(settings.providers.cursor.enabled);
606 assert.equal(settings.providers.opencode.serverUrl, "http://127.0.0.1:4096");
607 }).pipe(Effect.provide(makeServerSettingsLayer())),
608 );
609​
610 it.effect("preserves existing provider instances without explicit enabled flags", () =>
611 Effect.gen(function* () {
612 const serverConfig = yield* ServerConfig.ServerConfig;
613 const fileSystem = yield* FileSystem.FileSystem;
614 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
615 yield* fileSystem.writeFileString(
616 serverConfig.settingsPath,
617 '{"providerInstances":{"cursor_work":{"driver":"cursor","config":{}},"grok":{"driver":"grok","config":{}},"opencode_work":{"driver":"opencode","config":{"serverUrl":"http://127.0.0.1:4096"}},"opencode_unused":{"driver":"opencode","config":{}}}}',
618 );
619 yield* recordProviderUsage("cursor", "cursor_work");
620 yield* recordProviderUsage("grok", null);
621 yield* recordProviderUsage("opencode", "opencode_work");
622​
623 const settings = yield* serverSettings.getSettings;
624​
625 assert.isTrue(settings.providers.cursor.enabled);
626 assert.isTrue(settings.providerInstances[ProviderInstanceId.make("cursor_work")]?.enabled);
627 assert.isTrue(settings.providerInstances[ProviderInstanceId.make("grok")]?.enabled);
628 assert.isTrue(settings.providerInstances[ProviderInstanceId.make("opencode_work")]?.enabled);
629 const unused = settings.providerInstances[ProviderInstanceId.make("opencode_unused")];
630 assert.isDefined(unused);
631 assert.isFalse(resolveProviderInstanceEnabled(unused));
632 }).pipe(Effect.provide(makeServerSettingsLayer())),
633 );
634​
635 it.effect("preserves explicit provider disables in existing settings files", () =>
636 Effect.gen(function* () {
637 const serverConfig = yield* ServerConfig.ServerConfig;
638 const fileSystem = yield* FileSystem.FileSystem;
639 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
640 yield* fileSystem.writeFileString(
641 serverConfig.settingsPath,
642 '{"providers":{"grok":{"enabled":false},"opencode":{"enabled":false},"cursor":{"enabled":false}},"providerInstances":{"grok":{"driver":"grok","enabled":false,"config":{}},"opencode":{"driver":"opencode","config":{"enabled":false}},"cursor":{"driver":"cursor","enabled":false,"config":{}}}}',
643 );
644 yield* recordProviderUsage("grok");
645 yield* recordProviderUsage("opencode");
646 yield* recordProviderUsage("cursor");
647​
648 const settings = yield* serverSettings.getSettings;
649​
650 assert.isFalse(settings.providers.grok.enabled);
651 assert.isFalse(settings.providers.opencode.enabled);
652 assert.isFalse(settings.providers.cursor.enabled);
653 assert.isFalse(settings.providerInstances[ProviderInstanceId.make("grok")]?.enabled);
654 assert.isFalse(settings.providerInstances[ProviderInstanceId.make("opencode")]?.enabled);
655 assert.isFalse(settings.providerInstances[ProviderInstanceId.make("cursor")]?.enabled);
656 }).pipe(Effect.provide(makeServerSettingsLayer())),
657 );
658​
659 it.effect("keeps unused providers disabled in existing sparse settings files", () =>
660 Effect.gen(function* () {
661 const serverConfig = yield* ServerConfig.ServerConfig;
662 const fileSystem = yield* FileSystem.FileSystem;
663 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
664 yield* fileSystem.writeFileString(serverConfig.settingsPath, "{}");
665​
666 const settings = yield* serverSettings.getSettings;
667​
668 assert.isFalse(settings.providers.grok.enabled);
669 assert.isFalse(settings.providers.opencode.enabled);
670 assert.isFalse(settings.providers.cursor.enabled);
671 }).pipe(Effect.provide(makeServerSettingsLayer())),
672 );
673​
674 it.effect("preserves provider history when no settings file exists", () =>
675 Effect.gen(function* () {
676 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
677 yield* recordProviderUsage("grok");
678​
679 const settings = yield* serverSettings.getSettings;
680​
681 assert.isTrue(settings.providers.grok.enabled);
682 assert.isFalse(settings.providers.opencode.enabled);
683 assert.isFalse(settings.providers.cursor.enabled);
684 }).pipe(Effect.provide(makeServerSettingsLayer())),
685 );
686​
687 it.effect("preserves provider history when the settings file is invalid", () =>
688 Effect.gen(function* () {
689 const serverConfig = yield* ServerConfig.ServerConfig;
690 const fileSystem = yield* FileSystem.FileSystem;
691 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
692 yield* fileSystem.writeFileString(serverConfig.settingsPath, "{invalid json");
693 yield* recordProviderUsage("cursor");
694​
695 const settings = yield* serverSettings.getSettings;
696​
697 assert.isTrue(settings.providers.cursor.enabled);
698 assert.isFalse(settings.providers.grok.enabled);
699 assert.isFalse(settings.providers.opencode.enabled);
700 }).pipe(Effect.provide(makeServerSettingsLayer())),
701 );
702​
703 it.effect("preserves valid provider flags when another settings field is invalid", () =>
704 Effect.gen(function* () {
705 const serverConfig = yield* ServerConfig.ServerConfig;
706 const fileSystem = yield* FileSystem.FileSystem;
707 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
708 yield* fileSystem.writeFileString(
709 serverConfig.settingsPath,
710 '{"addProjectBaseDirectory":42,"providers":{"cursor":{"enabled":false},"grok":{"enabled":true}}}',
711 );
712 yield* recordProviderUsage("cursor");
713​
714 const settings = yield* serverSettings.getSettings;
715​
716 assert.isFalse(settings.providers.cursor.enabled);
717 assert.isTrue(settings.providers.grok.enabled);
718 assert.isFalse(settings.providers.opencode.enabled);
719 }).pipe(Effect.provide(makeServerSettingsLayer())),
720 );
721​
722 it.effect("restores providers from persisted runtime sessions", () =>
723 Effect.gen(function* () {
724 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
725 const sql = yield* SqlClient.SqlClient;
726 yield* sql`
727 INSERT INTO provider_session_runtime (
728 thread_id,
729 provider_name,
730 provider_instance_id,
731 adapter_key,
732 status,
733 last_seen_at
734 )
735 VALUES (
736 ${"thread-opencode-runtime"},
737 ${"opencode"},
738 ${"opencode"},
739 ${"opencode"},
740 ${"ready"},
741 ${"2026-08-25T00:00:00.000Z"}
742 )
743 `;
744​
745 const settings = yield* serverSettings.getSettings;
746​
747 assert.isFalse(settings.providers.grok.enabled);
748 assert.isTrue(settings.providers.opencode.enabled);
749 assert.isFalse(settings.providers.cursor.enabled);
750 }).pipe(Effect.provide(makeServerSettingsLayer())),
751 );
752​
753 it.effect("persists explicit disables after a provider has been used", () =>
754 Effect.gen(function* () {
755 const serverConfig = yield* ServerConfig.ServerConfig;
756 const fileSystem = yield* FileSystem.FileSystem;
757 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
758 yield* recordProviderUsage("grok");
759​
760 assert.isTrue((yield* serverSettings.getSettings).providers.grok.enabled);
761​
762 const settings = yield* serverSettings.updateSettings({
763 providers: { grok: { enabled: false } },
764 });
765 assert.isFalse(settings.providers.grok.enabled);
766​
767 const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
768 // @effect-diagnostics-next-line preferSchemaOverJson:off
769 assert.isFalse(JSON.parse(raw).providers.grok.enabled);
770 }).pipe(Effect.provide(makeServerSettingsLayer())),
771 );
772​
773 it.effect("persists explicit provider enables before their first use", () =>
774 Effect.gen(function* () {
775 const serverConfig = yield* ServerConfig.ServerConfig;
776 const fileSystem = yield* FileSystem.FileSystem;
777 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
778​
779 yield* serverSettings.updateSettings({
780 providers: {
781 cursor: { enabled: true },
782 grok: { enabled: true },
783 opencode: { enabled: true },
784 },
785 });
786 yield* serverSettings.updateSettings({ addProjectBaseDirectory: "~/Development" });
787​
788 const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
789 // @effect-diagnostics-next-line preferSchemaOverJson:off
790 const persisted = JSON.parse(raw);
791 assert.isTrue(persisted.providers.cursor.enabled);
792 assert.isTrue(persisted.providers.grok.enabled);
793 assert.isTrue(persisted.providers.opencode.enabled);
794 }).pipe(Effect.provide(makeServerSettingsLayer())),
795 );
796​
797 it.effect("keeps optional providers disabled after a new installation writes settings", () =>
798 Effect.gen(function* () {
799 const serverConfig = yield* ServerConfig.ServerConfig;
800 const fileSystem = yield* FileSystem.FileSystem;
801 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
802​
803 const initial = yield* serverSettings.getSettings;
804 assert.isFalse(initial.providers.grok.enabled);
805 assert.isFalse(initial.providers.opencode.enabled);
806 assert.isFalse(initial.providers.cursor.enabled);
807​
808 const next = yield* serverSettings.updateSettings({
809 addProjectBaseDirectory: "~/Development",
810 providerInstances: {
811 [ProviderInstanceId.make("grok")]: {
812 driver: ProviderDriverKind.make("grok"),
813 config: {},
814 },
815 },
816 });
817​
818 assert.isFalse(next.providers.grok.enabled);
819 assert.isFalse(next.providers.opencode.enabled);
820 assert.isFalse(next.providers.cursor.enabled);
821 const grok = next.providerInstances[ProviderInstanceId.make("grok")];
822 assert.isDefined(grok);
823 assert.isFalse(resolveProviderInstanceEnabled(grok));
824​
825 const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
826 // @effect-diagnostics-next-line preferSchemaOverJson:off
827 const persisted = JSON.parse(raw);
828 assert.isFalse(persisted.providers.cursor.enabled);
829 assert.isFalse(persisted.providers.grok.enabled);
830 assert.isFalse(persisted.providers.opencode.enabled);
831 assert.isUndefined(persisted.providerInstances.grok.enabled);
832 }).pipe(Effect.provide(makeServerSettingsLayer())),
833 );
834​
835 it.effect("folds a legacy in-config enabled flag into the envelope on load", () =>
836 Effect.gen(function* () {
837 const serverConfig = yield* ServerConfig.ServerConfig;
838 const fileSystem = yield* FileSystem.FileSystem;
839 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
840 // Old settings files can carry both flags with conflicting values.
841 // The explicit false must win so a user's disable sticks.
842 yield* fileSystem.writeFileString(
843 serverConfig.settingsPath,
844 '{"providerInstances":{"grok":{"driver":"grok","enabled":true,"config":{"enabled":false}},"codex_work":{"driver":"codex","config":{"enabled":true,"homePath":"~/.codex"}},"cursor":{"driver":"cursor","config":{"enabled":"nope"}}}}',
845 );
846​
847 const settings = yield* serverSettings.getSettings;
848​
849 const grokId = ProviderInstanceId.make("grok");
850 const codexWorkId = ProviderInstanceId.make("codex_work");
851 assert.deepEqual(settings.providerInstances[grokId], {
852 driver: ProviderDriverKind.make("grok"),
853 enabled: false,
854 config: {},
855 });
856 // A lone in-config flag is lifted to the envelope and stripped.
857 assert.deepEqual(settings.providerInstances[codexWorkId], {
858 driver: ProviderDriverKind.make("codex"),
859 enabled: true,
860 config: { homePath: "~/.codex" },
861 });
862 // A malformed flag is left alone so driver schema validation can
863 // surface it instead of the fold silently repairing the config.
864 assert.deepEqual(settings.providerInstances[ProviderInstanceId.make("cursor")], {
865 driver: ProviderDriverKind.make("cursor"),
866 config: { enabled: "nope" },
867 });
868 }).pipe(Effect.provide(makeServerSettingsLayer())),
869 );
870​
871 it.effect("folds in-config enabled flags arriving through updates", () =>
872 Effect.gen(function* () {
873 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
874 const grokId = ProviderInstanceId.make("grok");
875​
876 const next = yield* serverSettings.updateSettings({
877 providerInstances: {
878 [grokId]: {
879 driver: ProviderDriverKind.make("grok"),
880 enabled: true,
881 config: { enabled: false, binaryPath: "/opt/grok" },
882 },
883 },
884 });
885​
886 assert.deepEqual(next.providerInstances[grokId], {
887 driver: ProviderDriverKind.make("grok"),
888 enabled: false,
889 config: { binaryPath: "/opt/grok" },
890 });
891 }).pipe(Effect.provide(makeServerSettingsLayer())),
892 );
893​
894 it.effect("trims provider path settings when updates are applied", () =>
895 Effect.gen(function* () {
896 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
897​
898 const next = yield* serverSettings.updateSettings({
899 providers: {
900 codex: {
901 binaryPath: " /opt/homebrew/bin/codex ",
902 homePath: " ",
903 },
904 claudeAgent: {
905 binaryPath: " /opt/homebrew/bin/claude ",
906 },
907 opencode: {
908 binaryPath: " /opt/homebrew/bin/opencode ",
909 serverUrl: " http://127.0.0.1:4096 ",
910 serverPassword: " secret-password ",
911 },
912 },
913 });
914​
915 assert.deepEqual(next.providers.codex, {
916 enabled: true,
917 binaryPath: "/opt/homebrew/bin/codex",
918 homePath: "",
919 shadowHomePath: "",
920 launchArgs: "",
921 customModels: [],
922 });
923 assert.deepEqual(next.providers.claudeAgent, {
924 enabled: true,
925 binaryPath: "/opt/homebrew/bin/claude",
926 homePath: "",
927 customModels: [],
928 launchArgs: "",
929 autoCompactWindow: "",
930 });
931 assert.deepEqual(next.providers.opencode, {
932 // OpenCode is disabled by default; this update only touches paths.
933 enabled: false,
934 binaryPath: "/opt/homebrew/bin/opencode",
935 serverUrl: "http://127.0.0.1:4096",
936 serverPassword: "secret-password",
937 customModels: [],
938 });
939 }).pipe(Effect.provide(makeServerSettingsLayer())),
940 );
941​
942 it.effect("trims observability settings when updates are applied", () =>
943 Effect.gen(function* () {
944 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
945​
946 const next = yield* serverSettings.updateSettings({
947 addProjectBaseDirectory: " ~/Development ",
948 observability: {
949 otlpTracesUrl: " http://localhost:4318/v1/traces ",
950 otlpMetricsUrl: " http://localhost:4318/v1/metrics ",
951 },
952 });
953​
954 assert.equal(next.addProjectBaseDirectory, "~/Development");
955 assert.deepEqual(next.observability, {
956 otlpTracesUrl: "http://localhost:4318/v1/traces",
957 otlpMetricsUrl: "http://localhost:4318/v1/metrics",
958 });
959 }).pipe(Effect.provide(makeServerSettingsLayer())),
960 );
961​
962 it.effect("defaults blank binary paths to provider executables", () =>
963 Effect.gen(function* () {
964 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
965​
966 const next = yield* serverSettings.updateSettings({
967 providers: {
968 codex: {
969 binaryPath: " ",
970 },
971 claudeAgent: {
972 binaryPath: "",
973 },
974 },
975 });
976​
977 assert.equal(next.providers.codex.binaryPath, "codex");
978 assert.equal(next.providers.claudeAgent.binaryPath, "claude");
979 }).pipe(Effect.provide(makeServerSettingsLayer())),
980 );
981​
982 it.effect("writes non-default settings and explicit optional provider defaults to disk", () =>
983 Effect.gen(function* () {
984 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
985 const serverConfig = yield* ServerConfig.ServerConfig;
986 const fileSystem = yield* FileSystem.FileSystem;
987 const next = yield* serverSettings.updateSettings({
988 addProjectBaseDirectory: "~/Development",
989 observability: {
990 otlpTracesUrl: "http://localhost:4318/v1/traces",
991 otlpMetricsUrl: "http://localhost:4318/v1/metrics",
992 },
993 providers: {
994 codex: {
995 binaryPath: "/opt/homebrew/bin/codex",
996 },
997 opencode: {
998 serverUrl: "http://127.0.0.1:4096",
999 serverPassword: "secret-password",
1000 },
1001 },
1002 automaticGitFetchInterval: Duration.seconds(10),
1003 });
1004​
1005 assert.equal(next.providers.codex.binaryPath, "/opt/homebrew/bin/codex");
1006​
1007 const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
1008 // @effect-diagnostics-next-line preferSchemaOverJson:off
1009 assert.deepEqual(JSON.parse(raw), {
1010 addProjectBaseDirectory: "~/Development",
1011 observability: {
1012 otlpTracesUrl: "http://localhost:4318/v1/traces",
1013 otlpMetricsUrl: "http://localhost:4318/v1/metrics",
1014 },
1015 providers: {
1016 codex: {
1017 binaryPath: "/opt/homebrew/bin/codex",
1018 },
1019 cursor: {
1020 enabled: false,
1021 },
1022 grok: {
1023 enabled: false,
1024 },
1025 opencode: {
1026 enabled: false,
1027 serverUrl: "http://127.0.0.1:4096",
1028 serverPassword: "secret-password",
1029 },
1030 },
1031 backgroundActivity: {
1032 schemaVersion: 1,
1033 profile: "custom",
1034 baseProfile: "balanced",
1035 overrides: {
1036 automaticGitFetchInterval: 10_000,
1037 },
1038 },
1039 automaticGitFetchInterval: 10_000,
1040 });
1041 }).pipe(Effect.provide(makeServerSettingsLayer())),
1042 );
1043​
1044 it.effect("stores sensitive provider instance environment values outside settings.json", () =>
1045 Effect.gen(function* () {
1046 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
1047 const serverConfig = yield* ServerConfig.ServerConfig;
1048 const fileSystem = yield* FileSystem.FileSystem;
1049 const instanceId = ProviderInstanceId.make("codex_personal");
1050​
1051 const next = yield* serverSettings.updateSettings({
1052 providerInstances: {
1053 [instanceId]: {
1054 driver: ProviderDriverKind.make("codex"),
1055 environment: [
1056 { name: "OPENROUTER_API_KEY", value: "sk-or-secret", sensitive: true },
1057 { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false },
1058 ],
1059 config: {},
1060 },
1061 },
1062 });
1063​
1064 assert.deepEqual(next.providerInstances[instanceId]?.environment, [
1066 name: "OPENROUTER_API_KEY",
1067 value: "sk-or-secret",
1068 sensitive: true,
1069 valueRedacted: true,
1070 },
1071 { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false },
1072 ]);
1073​
1074 const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
1075 assert.notInclude(raw, "sk-or-secret");
1076 // @effect-diagnostics-next-line preferSchemaOverJson:off
1077 assert.deepEqual(JSON.parse(raw).providerInstances.codex_personal.environment, [
1079 name: "OPENROUTER_API_KEY",
1080 value: "",
1081 sensitive: true,
1082 valueRedacted: true,
1083 },
1084 { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false },
1085 ]);
1086​
1087 const roundTripped = yield* serverSettings.updateSettings({
1088 providerInstances: {
1089 [instanceId]: {
1090 driver: ProviderDriverKind.make("codex"),
1091 displayName: "Codex Personal",
1092 environment: [
1093 { name: "OPENROUTER_API_KEY", value: "", sensitive: true, valueRedacted: true },
1094 { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false },
1095 ],
1096 config: {},
1097 },
1098 },
1099 });
1100​
1101 assert.equal(
1102 roundTripped.providerInstances[instanceId]?.environment?.[0]?.value,
1103 "sk-or-secret",
1104 );
1105 }).pipe(Effect.provide(makeServerSettingsLayer())),
1106 );
1107​
1108 it.effect("materializes provider secrets for terminal environment resolution", () =>
1109 Effect.gen(function* () {
1110 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
1111 const serverConfig = yield* ServerConfig.ServerConfig;
1112 const fileSystem = yield* FileSystem.FileSystem;
1113 const path = yield* Path.Path;
1114 const instanceId = ProviderInstanceId.make("codex_terminal");
1115​
1116 yield* serverSettings.updateSettings({
1117 providerInstances: {
1118 [instanceId]: {
1119 driver: ProviderDriverKind.make("codex"),
1120 environment: [
1121 { name: "OPENROUTER_API_KEY", value: "sk-terminal-secret", sensitive: true },
1122 ],
1123 config: { homePath: "~/.codex-terminal" },
1124 },
1125 },
1126 });
1127​
1128 const environment = yield* resolveProviderInstanceTerminalEnvironment({
1129 serverSettings,
1130 path,
1131 rawProviderInstanceId: instanceId,
1132 env: undefined,
1133 });
1134 const persisted = yield* fileSystem.readFileString(serverConfig.settingsPath);
1135​
1136 assert.equal(environment.OPENROUTER_API_KEY, "sk-terminal-secret");
1137 assert.match(environment.CODEX_HOME ?? "", /[\\/][.]codex-terminal$/);
1138 assert.notInclude(persisted, "sk-terminal-secret");
1139 assert.include(persisted, '"valueRedacted": true');
1140 }).pipe(Effect.provide(makeServerSettingsLayer())),
1141 );
1142});