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