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

serverSettings.test.ts

1,079 lines39.8 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 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 and broadcasts thread settlement settings", () =>
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 changes = yield* serverSettings.subscribeChanges;
282​
283 const next = yield* serverSettings.updateSettings({
284 sidebarAutoSettleAfterDays: null,
285 sidebarAutoSettleOnMerge: false,
286 });
287 const change = Option.getOrUndefined(yield* Stream.runHead(changes));
288 const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
289 // Inspect raw persisted JSON before schema decoding can apply defaults.
290 // @effect-diagnostics-next-line preferSchemaOverJson:off
291 const persisted = JSON.parse(raw) as Record<string, unknown>;
292​
293 assert.strictEqual(next.sidebarAutoSettleAfterDays, null);
294 assert.isFalse(next.sidebarAutoSettleOnMerge);
295 assert.strictEqual(change?.sidebarAutoSettleAfterDays, null);
296 assert.isFalse(change?.sidebarAutoSettleOnMerge);
297 assert.strictEqual(persisted.sidebarAutoSettleAfterDays, null);
298 assert.isFalse(persisted.sidebarAutoSettleOnMerge);
299 }),
300 ).pipe(Effect.provide(makeServerSettingsLayer())),
301 );
302​
303 it.effect("preserves model when switching providers via textGenerationModelSelection", () =>
304 Effect.gen(function* () {
305 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
306​
307 // Start with Claude text generation selection
308 yield* serverSettings.updateSettings({
309 textGenerationModelSelection: {
310 instanceId: ProviderInstanceId.make("claudeAgent"),
311 model: "claude-sonnet-4-6",
312 options: createModelSelection(
313 ProviderInstanceId.make("claudeAgent"),
314 "claude-sonnet-4-6",
315 [{ id: "effort", value: "high" }],
316 ).options!,
317 },
318 });
319​
320 // Switch to Codex — the stale Claude "effort" in options must not
321 // cause the update to lose the selected model.
322 const next = yield* serverSettings.updateSettings({
323 textGenerationModelSelection: {
324 instanceId: ProviderInstanceId.make("codex"),
325 model: "gpt-5.4",
326 options: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
327 { id: "reasoningEffort", value: "high" },
328 ]).options!,
329 },
330 });
331​
332 assert.deepEqual(
333 next.textGenerationModelSelection,
334 createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
335 { id: "reasoningEffort", value: "high" },
336 ]),
337 );
338 }).pipe(Effect.provide(makeServerSettingsLayer())),
339 );
340​
341 it.effect("preserves custom provider instance text generation selections", () =>
342 Effect.gen(function* () {
343 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
344​
345 const next = yield* serverSettings.updateSettings({
346 providerInstances: {
347 [ProviderInstanceId.make("claude_openrouter")]: {
348 driver: ProviderDriverKind.make("claudeAgent"),
349 enabled: true,
350 config: { customModels: ["openai/gpt-5.5"] },
351 },
352 },
353 textGenerationModelSelection: {
354 instanceId: ProviderInstanceId.make("claude_openrouter"),
355 model: "openai/gpt-5.5",
356 },
357 });
358​
359 assert.deepEqual(next.textGenerationModelSelection, {
360 instanceId: ProviderInstanceId.make("claude_openrouter"),
361 model: "openai/gpt-5.5",
362 });
363 }).pipe(Effect.provide(makeServerSettingsLayer())),
364 );
365​
366 it.effect(
367 "uses explicit provider instance enabled state over legacy provider enabled state",
368 () =>
369 Effect.gen(function* () {
370 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
371 const instanceId = ProviderInstanceId.make("claude_openrouter");
372​
373 const next = yield* serverSettings.updateSettings({
374 providers: {
375 claudeAgent: {
376 enabled: false,
377 },
378 },
379 providerInstances: {
380 [instanceId]: {
381 driver: ProviderDriverKind.make("claudeAgent"),
382 enabled: true,
383 config: { customModels: ["openai/gpt-5.5"] },
384 },
385 },
386 textGenerationModelSelection: {
387 instanceId,
388 model: "openai/gpt-5.5",
389 },
390 });
391​
392 assert.deepEqual(next.textGenerationModelSelection, {
393 instanceId,
394 model: "openai/gpt-5.5",
395 });
396 }).pipe(Effect.provide(makeServerSettingsLayer())),
397 );
398​
399 it.effect("preserves enabled text generation selections for non-built-in drivers", () =>
400 Effect.gen(function* () {
401 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
402 const instanceId = ProviderInstanceId.make("openrouter_text");
403​
404 const next = yield* serverSettings.updateSettings({
405 providerInstances: {
406 [instanceId]: {
407 driver: ProviderDriverKind.make("openrouter"),
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(
426 "preserves the source control writer selection when its provider instance is disabled",
427 () =>
428 Effect.gen(function* () {
429 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
430 const serverConfig = yield* ServerConfig.ServerConfig;
431 const fileSystem = yield* FileSystem.FileSystem;
432 const instanceId = ProviderInstanceId.make("codex_writer");
433 const sourceControlWriterModelSelection = {
434 instanceId,
435 model: "gpt-5.4-mini",
436 };
437​
438 yield* serverSettings.updateSettings({
439 providerInstances: {
440 [instanceId]: {
441 driver: ProviderDriverKind.make("codex"),
442 enabled: true,
443 config: {},
444 },
445 },
446 sourceControlWriterModelSelection,
447 });
448​
449 const next = yield* serverSettings.updateSettings({
450 providerInstances: {
451 [instanceId]: {
452 driver: ProviderDriverKind.make("codex"),
453 enabled: false,
454 config: {},
455 },
456 },
457 });
458​
459 assert.deepEqual(next.sourceControlWriterModelSelection, sourceControlWriterModelSelection);
460 assert.deepEqual(
461 ServerSettingsModule.resolveSourceControlWriterModelSelection(next),
462 next.textGenerationModelSelection,
463 );
464 assert.deepEqual(
465 (yield* serverSettings.getSettings).sourceControlWriterModelSelection,
466 sourceControlWriterModelSelection,
467 );
468​
469 const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
470 assert.deepEqual(
471 // @effect-diagnostics-next-line preferSchemaOverJson:off
472 JSON.parse(raw).sourceControlWriterModelSelection,
473 sourceControlWriterModelSelection,
474 );
475​
476 const restored = yield* serverSettings.updateSettings({
477 providerInstances: {
478 [instanceId]: {
479 driver: ProviderDriverKind.make("codex"),
480 enabled: true,
481 config: {},
482 },
483 },
484 });
485 assert.deepEqual(
486 ServerSettingsModule.resolveSourceControlWriterModelSelection(restored),
487 sourceControlWriterModelSelection,
488 );
489 }).pipe(Effect.provide(makeServerSettingsLayer())),
490 );
491​
492 it.effect("drops stale text generation options when resetting model selection", () =>
493 Effect.gen(function* () {
494 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
495​
496 yield* serverSettings.updateSettings({
497 textGenerationModelSelection: {
498 instanceId: ProviderInstanceId.make("codex"),
499 model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
500 options: createModelSelection(
501 ProviderInstanceId.make("codex"),
502 DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
503 [
504 { id: "reasoningEffort", value: "high" },
505 { id: "fastMode", value: true },
506 ],
507 ).options!,
508 },
509 });
510​
511 const next = yield* serverSettings.updateSettings({
512 textGenerationModelSelection: {
513 instanceId: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.instanceId,
514 model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
515 },
516 });
517​
518 assert.deepEqual(next.textGenerationModelSelection, {
519 instanceId: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.instanceId,
520 model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
521 });
522 }).pipe(Effect.provide(makeServerSettingsLayer())),
523 );
524​
525 it.effect("replaces provider instance maps when clearing optional fields", () =>
526 Effect.gen(function* () {
527 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
528 const codexId = ProviderInstanceId.make("codex");
529​
530 yield* serverSettings.updateSettings({
531 providerInstances: {
532 [codexId]: {
533 driver: ProviderDriverKind.make("codex"),
534 displayName: "Codex Work",
535 accentColor: "#7c3aed",
536 enabled: true,
537 config: { homePath: "~/.codex" },
538 },
539 },
540 });
541​
542 const next = yield* serverSettings.updateSettings({
543 providerInstances: {
544 [codexId]: {
545 driver: ProviderDriverKind.make("codex"),
546 displayName: "Codex Work",
547 enabled: true,
548 config: { homePath: "~/.codex" },
549 },
550 },
551 });
552​
553 assert.deepEqual(next.providerInstances[codexId], {
554 driver: ProviderDriverKind.make("codex"),
555 displayName: "Codex Work",
556 enabled: true,
557 config: { homePath: "~/.codex" },
558 });
559 }).pipe(Effect.provide(makeServerSettingsLayer())),
560 );
561​
562 it.effect("enables previously used providers from sparse settings files", () =>
563 Effect.gen(function* () {
564 const serverConfig = yield* ServerConfig.ServerConfig;
565 const fileSystem = yield* FileSystem.FileSystem;
566 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
567 yield* fileSystem.writeFileString(
568 serverConfig.settingsPath,
569 '{"providers":{"opencode":{"serverUrl":"http://127.0.0.1:4096"}}}',
570 );
571 yield* recordProviderUsage("opencode");
572​
573 const settings = yield* serverSettings.getSettings;
574​
575 assert.isFalse(settings.providers.grok.enabled);
576 assert.isTrue(settings.providers.opencode.enabled);
577 assert.isFalse(settings.providers.cursor.enabled);
578 assert.equal(settings.providers.opencode.serverUrl, "http://127.0.0.1:4096");
579 }).pipe(Effect.provide(makeServerSettingsLayer())),
580 );
581​
582 it.effect("preserves existing provider instances without explicit enabled flags", () =>
583 Effect.gen(function* () {
584 const serverConfig = yield* ServerConfig.ServerConfig;
585 const fileSystem = yield* FileSystem.FileSystem;
586 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
587 yield* fileSystem.writeFileString(
588 serverConfig.settingsPath,
589 '{"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":{}}}}',
590 );
591 yield* recordProviderUsage("cursor", "cursor_work");
592 yield* recordProviderUsage("grok", null);
593 yield* recordProviderUsage("opencode", "opencode_work");
594​
595 const settings = yield* serverSettings.getSettings;
596​
597 assert.isTrue(settings.providers.cursor.enabled);
598 assert.isTrue(settings.providerInstances[ProviderInstanceId.make("cursor_work")]?.enabled);
599 assert.isTrue(settings.providerInstances[ProviderInstanceId.make("grok")]?.enabled);
600 assert.isTrue(settings.providerInstances[ProviderInstanceId.make("opencode_work")]?.enabled);
601 const unused = settings.providerInstances[ProviderInstanceId.make("opencode_unused")];
602 assert.isDefined(unused);
603 assert.isFalse(resolveProviderInstanceEnabled(unused));
604 }).pipe(Effect.provide(makeServerSettingsLayer())),
605 );
606​
607 it.effect("preserves explicit provider disables in existing settings files", () =>
608 Effect.gen(function* () {
609 const serverConfig = yield* ServerConfig.ServerConfig;
610 const fileSystem = yield* FileSystem.FileSystem;
611 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
612 yield* fileSystem.writeFileString(
613 serverConfig.settingsPath,
614 '{"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":{}}}}',
615 );
616 yield* recordProviderUsage("grok");
617 yield* recordProviderUsage("opencode");
618 yield* recordProviderUsage("cursor");
619​
620 const settings = yield* serverSettings.getSettings;
621​
622 assert.isFalse(settings.providers.grok.enabled);
623 assert.isFalse(settings.providers.opencode.enabled);
624 assert.isFalse(settings.providers.cursor.enabled);
625 assert.isFalse(settings.providerInstances[ProviderInstanceId.make("grok")]?.enabled);
626 assert.isFalse(settings.providerInstances[ProviderInstanceId.make("opencode")]?.enabled);
627 assert.isFalse(settings.providerInstances[ProviderInstanceId.make("cursor")]?.enabled);
628 }).pipe(Effect.provide(makeServerSettingsLayer())),
629 );
630​
631 it.effect("keeps unused providers disabled in existing sparse settings files", () =>
632 Effect.gen(function* () {
633 const serverConfig = yield* ServerConfig.ServerConfig;
634 const fileSystem = yield* FileSystem.FileSystem;
635 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
636 yield* fileSystem.writeFileString(serverConfig.settingsPath, "{}");
637​
638 const settings = yield* serverSettings.getSettings;
639​
640 assert.isFalse(settings.providers.grok.enabled);
641 assert.isFalse(settings.providers.opencode.enabled);
642 assert.isFalse(settings.providers.cursor.enabled);
643 }).pipe(Effect.provide(makeServerSettingsLayer())),
644 );
645​
646 it.effect("preserves provider history when no settings file exists", () =>
647 Effect.gen(function* () {
648 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
649 yield* recordProviderUsage("grok");
650​
651 const settings = yield* serverSettings.getSettings;
652​
653 assert.isTrue(settings.providers.grok.enabled);
654 assert.isFalse(settings.providers.opencode.enabled);
655 assert.isFalse(settings.providers.cursor.enabled);
656 }).pipe(Effect.provide(makeServerSettingsLayer())),
657 );
658​
659 it.effect("preserves provider history when the settings file is invalid", () =>
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, "{invalid json");
665 yield* recordProviderUsage("cursor");
666​
667 const settings = yield* serverSettings.getSettings;
668​
669 assert.isTrue(settings.providers.cursor.enabled);
670 assert.isFalse(settings.providers.grok.enabled);
671 assert.isFalse(settings.providers.opencode.enabled);
672 }).pipe(Effect.provide(makeServerSettingsLayer())),
673 );
674​
675 it.effect("preserves valid provider flags when another settings field is invalid", () =>
676 Effect.gen(function* () {
677 const serverConfig = yield* ServerConfig.ServerConfig;
678 const fileSystem = yield* FileSystem.FileSystem;
679 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
680 yield* fileSystem.writeFileString(
681 serverConfig.settingsPath,
682 '{"addProjectBaseDirectory":42,"providers":{"cursor":{"enabled":false},"grok":{"enabled":true}}}',
683 );
684 yield* recordProviderUsage("cursor");
685​
686 const settings = yield* serverSettings.getSettings;
687​
688 assert.isFalse(settings.providers.cursor.enabled);
689 assert.isTrue(settings.providers.grok.enabled);
690 assert.isFalse(settings.providers.opencode.enabled);
691 }).pipe(Effect.provide(makeServerSettingsLayer())),
692 );
693​
694 it.effect("restores providers from persisted runtime sessions", () =>
695 Effect.gen(function* () {
696 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
697 const sql = yield* SqlClient.SqlClient;
698 yield* sql`
699 INSERT INTO provider_session_runtime (
700 thread_id,
701 provider_name,
702 provider_instance_id,
703 adapter_key,
704 status,
705 last_seen_at
706 )
707 VALUES (
708 ${"thread-opencode-runtime"},
709 ${"opencode"},
710 ${"opencode"},
711 ${"opencode"},
712 ${"ready"},
713 ${"2026-08-25T00:00:00.000Z"}
714 )
715 `;
716​
717 const settings = yield* serverSettings.getSettings;
718​
719 assert.isFalse(settings.providers.grok.enabled);
720 assert.isTrue(settings.providers.opencode.enabled);
721 assert.isFalse(settings.providers.cursor.enabled);
722 }).pipe(Effect.provide(makeServerSettingsLayer())),
723 );
724​
725 it.effect("persists explicit disables after a provider has been used", () =>
726 Effect.gen(function* () {
727 const serverConfig = yield* ServerConfig.ServerConfig;
728 const fileSystem = yield* FileSystem.FileSystem;
729 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
730 yield* recordProviderUsage("grok");
731​
732 assert.isTrue((yield* serverSettings.getSettings).providers.grok.enabled);
733​
734 const settings = yield* serverSettings.updateSettings({
735 providers: { grok: { enabled: false } },
736 });
737 assert.isFalse(settings.providers.grok.enabled);
738​
739 const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
740 // @effect-diagnostics-next-line preferSchemaOverJson:off
741 assert.isFalse(JSON.parse(raw).providers.grok.enabled);
742 }).pipe(Effect.provide(makeServerSettingsLayer())),
743 );
744​
745 it.effect("persists explicit provider enables before their first use", () =>
746 Effect.gen(function* () {
747 const serverConfig = yield* ServerConfig.ServerConfig;
748 const fileSystem = yield* FileSystem.FileSystem;
749 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
750​
751 yield* serverSettings.updateSettings({
752 providers: {
753 cursor: { enabled: true },
754 grok: { enabled: true },
755 opencode: { enabled: true },
756 },
757 });
758 yield* serverSettings.updateSettings({ addProjectBaseDirectory: "~/Development" });
759​
760 const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
761 // @effect-diagnostics-next-line preferSchemaOverJson:off
762 const persisted = JSON.parse(raw);
763 assert.isTrue(persisted.providers.cursor.enabled);
764 assert.isTrue(persisted.providers.grok.enabled);
765 assert.isTrue(persisted.providers.opencode.enabled);
766 }).pipe(Effect.provide(makeServerSettingsLayer())),
767 );
768​
769 it.effect("keeps optional providers disabled after a new installation writes settings", () =>
770 Effect.gen(function* () {
771 const serverConfig = yield* ServerConfig.ServerConfig;
772 const fileSystem = yield* FileSystem.FileSystem;
773 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
774​
775 const initial = yield* serverSettings.getSettings;
776 assert.isFalse(initial.providers.grok.enabled);
777 assert.isFalse(initial.providers.opencode.enabled);
778 assert.isFalse(initial.providers.cursor.enabled);
779​
780 const next = yield* serverSettings.updateSettings({
781 addProjectBaseDirectory: "~/Development",
782 providerInstances: {
783 [ProviderInstanceId.make("grok")]: {
784 driver: ProviderDriverKind.make("grok"),
785 config: {},
786 },
787 },
788 });
789​
790 assert.isFalse(next.providers.grok.enabled);
791 assert.isFalse(next.providers.opencode.enabled);
792 assert.isFalse(next.providers.cursor.enabled);
793 const grok = next.providerInstances[ProviderInstanceId.make("grok")];
794 assert.isDefined(grok);
795 assert.isFalse(resolveProviderInstanceEnabled(grok));
796​
797 const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
798 // @effect-diagnostics-next-line preferSchemaOverJson:off
799 const persisted = JSON.parse(raw);
800 assert.isFalse(persisted.providers.cursor.enabled);
801 assert.isFalse(persisted.providers.grok.enabled);
802 assert.isFalse(persisted.providers.opencode.enabled);
803 assert.isUndefined(persisted.providerInstances.grok.enabled);
804 }).pipe(Effect.provide(makeServerSettingsLayer())),
805 );
806​
807 it.effect("folds a legacy in-config enabled flag into the envelope on load", () =>
808 Effect.gen(function* () {
809 const serverConfig = yield* ServerConfig.ServerConfig;
810 const fileSystem = yield* FileSystem.FileSystem;
811 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
812 // Old settings files can carry both flags with conflicting values.
813 // The explicit false must win so a user's disable sticks.
814 yield* fileSystem.writeFileString(
815 serverConfig.settingsPath,
816 '{"providerInstances":{"grok":{"driver":"grok","enabled":true,"config":{"enabled":false}},"codex_work":{"driver":"codex","config":{"enabled":true,"homePath":"~/.codex"}},"cursor":{"driver":"cursor","config":{"enabled":"nope"}}}}',
817 );
818​
819 const settings = yield* serverSettings.getSettings;
820​
821 const grokId = ProviderInstanceId.make("grok");
822 const codexWorkId = ProviderInstanceId.make("codex_work");
823 assert.deepEqual(settings.providerInstances[grokId], {
824 driver: ProviderDriverKind.make("grok"),
825 enabled: false,
826 config: {},
827 });
828 // A lone in-config flag is lifted to the envelope and stripped.
829 assert.deepEqual(settings.providerInstances[codexWorkId], {
830 driver: ProviderDriverKind.make("codex"),
831 enabled: true,
832 config: { homePath: "~/.codex" },
833 });
834 // A malformed flag is left alone so driver schema validation can
835 // surface it instead of the fold silently repairing the config.
836 assert.deepEqual(settings.providerInstances[ProviderInstanceId.make("cursor")], {
837 driver: ProviderDriverKind.make("cursor"),
838 config: { enabled: "nope" },
839 });
840 }).pipe(Effect.provide(makeServerSettingsLayer())),
841 );
842​
843 it.effect("folds in-config enabled flags arriving through updates", () =>
844 Effect.gen(function* () {
845 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
846 const grokId = ProviderInstanceId.make("grok");
847​
848 const next = yield* serverSettings.updateSettings({
849 providerInstances: {
850 [grokId]: {
851 driver: ProviderDriverKind.make("grok"),
852 enabled: true,
853 config: { enabled: false, binaryPath: "/opt/grok" },
854 },
855 },
856 });
857​
858 assert.deepEqual(next.providerInstances[grokId], {
859 driver: ProviderDriverKind.make("grok"),
860 enabled: false,
861 config: { binaryPath: "/opt/grok" },
862 });
863 }).pipe(Effect.provide(makeServerSettingsLayer())),
864 );
865​
866 it.effect("trims provider path settings when updates are applied", () =>
867 Effect.gen(function* () {
868 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
869​
870 const next = yield* serverSettings.updateSettings({
871 providers: {
872 codex: {
873 binaryPath: " /opt/homebrew/bin/codex ",
874 homePath: " ",
875 },
876 claudeAgent: {
877 binaryPath: " /opt/homebrew/bin/claude ",
878 },
879 opencode: {
880 binaryPath: " /opt/homebrew/bin/opencode ",
881 serverUrl: " http://127.0.0.1:4096 ",
882 serverPassword: " secret-password ",
883 },
884 },
885 });
886​
887 assert.deepEqual(next.providers.codex, {
888 enabled: true,
889 binaryPath: "/opt/homebrew/bin/codex",
890 homePath: "",
891 shadowHomePath: "",
892 launchArgs: "",
893 customModels: [],
894 });
895 assert.deepEqual(next.providers.claudeAgent, {
896 enabled: true,
897 binaryPath: "/opt/homebrew/bin/claude",
898 homePath: "",
899 customModels: [],
900 launchArgs: "",
901 autoCompactWindow: "",
902 });
903 assert.deepEqual(next.providers.opencode, {
904 // OpenCode is disabled by default; this update only touches paths.
905 enabled: false,
906 binaryPath: "/opt/homebrew/bin/opencode",
907 serverUrl: "http://127.0.0.1:4096",
908 serverPassword: "secret-password",
909 customModels: [],
910 });
911 }).pipe(Effect.provide(makeServerSettingsLayer())),
912 );
913​
914 it.effect("trims observability settings when updates are applied", () =>
915 Effect.gen(function* () {
916 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
917​
918 const next = yield* serverSettings.updateSettings({
919 addProjectBaseDirectory: " ~/Development ",
920 observability: {
921 otlpTracesUrl: " http://localhost:4318/v1/traces ",
922 otlpMetricsUrl: " http://localhost:4318/v1/metrics ",
923 },
924 });
925​
926 assert.equal(next.addProjectBaseDirectory, "~/Development");
927 assert.deepEqual(next.observability, {
928 otlpTracesUrl: "http://localhost:4318/v1/traces",
929 otlpMetricsUrl: "http://localhost:4318/v1/metrics",
930 });
931 }).pipe(Effect.provide(makeServerSettingsLayer())),
932 );
933​
934 it.effect("defaults blank binary paths to provider executables", () =>
935 Effect.gen(function* () {
936 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
937​
938 const next = yield* serverSettings.updateSettings({
939 providers: {
940 codex: {
941 binaryPath: " ",
942 },
943 claudeAgent: {
944 binaryPath: "",
945 },
946 },
947 });
948​
949 assert.equal(next.providers.codex.binaryPath, "codex");
950 assert.equal(next.providers.claudeAgent.binaryPath, "claude");
951 }).pipe(Effect.provide(makeServerSettingsLayer())),
952 );
953​
954 it.effect("writes non-default settings and explicit optional provider defaults to disk", () =>
955 Effect.gen(function* () {
956 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
957 const serverConfig = yield* ServerConfig.ServerConfig;
958 const fileSystem = yield* FileSystem.FileSystem;
959 const next = yield* serverSettings.updateSettings({
960 addProjectBaseDirectory: "~/Development",
961 observability: {
962 otlpTracesUrl: "http://localhost:4318/v1/traces",
963 otlpMetricsUrl: "http://localhost:4318/v1/metrics",
964 },
965 providers: {
966 codex: {
967 binaryPath: "/opt/homebrew/bin/codex",
968 },
969 opencode: {
970 serverUrl: "http://127.0.0.1:4096",
971 serverPassword: "secret-password",
972 },
973 },
974 automaticGitFetchInterval: Duration.seconds(10),
975 });
976​
977 assert.equal(next.providers.codex.binaryPath, "/opt/homebrew/bin/codex");
978​
979 const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
980 // @effect-diagnostics-next-line preferSchemaOverJson:off
981 assert.deepEqual(JSON.parse(raw), {
982 addProjectBaseDirectory: "~/Development",
983 observability: {
984 otlpTracesUrl: "http://localhost:4318/v1/traces",
985 otlpMetricsUrl: "http://localhost:4318/v1/metrics",
986 },
987 providers: {
988 codex: {
989 binaryPath: "/opt/homebrew/bin/codex",
990 },
991 cursor: {
992 enabled: false,
993 },
994 grok: {
995 enabled: false,
996 },
997 opencode: {
998 enabled: false,
999 serverUrl: "http://127.0.0.1:4096",
1000 serverPassword: "secret-password",
1001 },
1002 },
1003 backgroundActivity: {
1004 schemaVersion: 1,
1005 profile: "custom",
1006 baseProfile: "balanced",
1007 overrides: {
1008 automaticGitFetchInterval: 10_000,
1009 },
1010 },
1011 automaticGitFetchInterval: 10_000,
1012 });
1013 }).pipe(Effect.provide(makeServerSettingsLayer())),
1014 );
1015​
1016 it.effect("stores sensitive provider instance environment values outside settings.json", () =>
1017 Effect.gen(function* () {
1018 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
1019 const serverConfig = yield* ServerConfig.ServerConfig;
1020 const fileSystem = yield* FileSystem.FileSystem;
1021 const instanceId = ProviderInstanceId.make("codex_personal");
1022​
1023 const next = yield* serverSettings.updateSettings({
1024 providerInstances: {
1025 [instanceId]: {
1026 driver: ProviderDriverKind.make("codex"),
1027 environment: [
1028 { name: "OPENROUTER_API_KEY", value: "sk-or-secret", sensitive: true },
1029 { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false },
1030 ],
1031 config: {},
1032 },
1033 },
1034 });
1035​
1036 assert.deepEqual(next.providerInstances[instanceId]?.environment, [
1038 name: "OPENROUTER_API_KEY",
1039 value: "sk-or-secret",
1040 sensitive: true,
1041 valueRedacted: true,
1042 },
1043 { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false },
1044 ]);
1045​
1046 const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
1047 assert.notInclude(raw, "sk-or-secret");
1048 // @effect-diagnostics-next-line preferSchemaOverJson:off
1049 assert.deepEqual(JSON.parse(raw).providerInstances.codex_personal.environment, [
1051 name: "OPENROUTER_API_KEY",
1052 value: "",
1053 sensitive: true,
1054 valueRedacted: true,
1055 },
1056 { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false },
1057 ]);
1058​
1059 const roundTripped = yield* serverSettings.updateSettings({
1060 providerInstances: {
1061 [instanceId]: {
1062 driver: ProviderDriverKind.make("codex"),
1063 displayName: "Codex Personal",
1064 environment: [
1065 { name: "OPENROUTER_API_KEY", value: "", sensitive: true, valueRedacted: true },
1066 { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false },
1067 ],
1068 config: {},
1069 },
1070 },
1071 });
1072​
1073 assert.equal(
1074 roundTripped.providerInstances[instanceId]?.environment?.[0]?.value,
1075 "sk-or-secret",
1076 );
1077 }).pipe(Effect.provide(makeServerSettingsLayer())),
1078 );
1079});