@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 3,296 lines 134 KB
Raw
1 import { deriveProviderInstanceConfigMap } from "./provider/ProviderInstanceRegistryHydration.ts";
2 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 import {
5 DEFAULT_SERVER_SETTINGS,
6 globalIdleCompaction,
7 type ManagedPolicyDocument,
8 ModelSelection,
9 ProjectId,
10 ProjectScript,
11 ProviderDriverKind,
12 type ProviderInstanceEnvironment,
13 ProviderInstanceId,
14 resolveProviderInstanceEnabled,
15 SecretProviderId,
16 ServerSettings,
17 ServerSettingsPatch,
18 UsageLimitSourceId,
19 type SimlockDeviceHostConfig,
20 } from "@t3tools/contracts";
21 import { createModelSelection } from "@t3tools/shared/model";
22 import { assert, it } from "@effect/vitest";
23 import * as Deferred from "effect/Deferred";
24 import * as Effect from "effect/Effect";
25 import * as FileSystem from "effect/FileSystem";
26 import * as Fiber from "effect/Fiber";
27 import * as Layer from "effect/Layer";
28 import * as Option from "effect/Option";
29 import * as Path from "effect/Path";
30 import * as PlatformError from "effect/PlatformError";
31 import * as Schema from "effect/Schema";
32 import * as Stream from "effect/Stream";
33 import * as SchemaAST from "effect/SchemaAST";
34 import * as SqlClient from "effect/sql/SqlClient";
35 import * as TestClock from "effect/testing/TestClock";
36 import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
37 import { sourceControlHostSecretName } from "./sourceControl/sourceControlHostSecrets.ts";
38 import * as ServerConfig from "./config.ts";
39 import * as SqlitePersistence from "./persistence/Sqlite.ts";
40 import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
41 import * as ServerSettingsModule from "./serverSettings.ts";
42 import { SECRET_REDACTED } from "./settingsSecrets.ts";
43 import * as ManagedPolicy from "./policy/ManagedPolicy.ts";
44 import { resolveProviderInstanceTerminalEnvironment } from "./terminal/Manager.ts";
45
46 const decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings);
47 const decodeServerSettingsJson = Schema.decodeUnknownEffect(Schema.fromJsonString(ServerSettings));
48 const decodeServerSettingsPatch = Schema.decodeUnknownEffect(ServerSettingsPatch);
49
50 const layerServerSettings = (policy?: ManagedPolicyDocument) =>
51 ServerSettingsModule.layer.pipe(
52 Layer.provide(ServerSecretStore.layer),
53 Layer.provide(ManagedPolicy.layerTest(policy)),
54 Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
55 Layer.provideMerge(
56 Layer.fresh(
57 ServerConfig.layerTest(process.cwd(), {
58 prefix: "t3code-server-settings-test-",
59 }),
60 ),
61 ),
62 );
63
64 const layerServerSettingsWithSecrets = () =>
65 ServerSettingsModule.layer.pipe(
66 Layer.provideMerge(ServerSecretStore.layer),
67 Layer.provide(ManagedPolicy.layerTest()),
68 Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
69 Layer.provideMerge(
70 Layer.fresh(
71 ServerConfig.layerTest(process.cwd(), {
72 prefix: "t3code-server-settings-test-",
73 }),
74 ),
75 ),
76 );
77
78 const layerFailingSecretStore = (cause: ServerSecretStore.SecretStoreError) =>
79 Layer.succeed(
80 ServerSecretStore.ServerSecretStore,
81 ServerSecretStore.ServerSecretStore.of({
82 get: () => Effect.fail(cause),
83 set: () => Effect.void,
84 create: () => Effect.void,
85 getOrCreateRandom: () => Effect.succeed(new Uint8Array()),
86 remove: () => Effect.void,
87 }),
88 );
89
90 const recordProviderUsage = (provider: string, instanceId: string | null = provider) =>
91 Effect.gen(function* () {
92 const sql = yield* SqlClient.SqlClient;
93 yield* sql`
94 INSERT INTO projection_thread_sessions (
95 thread_id,
96 status,
97 provider_name,
98 provider_instance_id,
99 updated_at
100 )
101 VALUES (
102 ${`thread-${instanceId ?? provider}`},
103 ${"ready"},
104 ${provider},
105 ${instanceId},
106 ${"2026-08-25T00:00:00.000Z"}
107 )
108 `;
109 });
110
111 /** Paths of fields typed `SettingsSecretValue` that clients decode with the settings schema itself. */
112 function strictSecretReferencePaths(
113 ast: SchemaAST.AST,
114 path = "",
115 seen = new Set<SchemaAST.AST>(),
116 ): ReadonlyArray<string> {
117 if (seen.has(ast)) return [];
118 seen.add(ast);
119 const walk = (type: SchemaAST.AST, at: string): ReadonlyArray<string> =>
120 type.context?.annotations?.settingsSecretReference === true
121 ? [at]
122 : strictSecretReferencePaths(type, `${at}.`, seen);
123 if (SchemaAST.isObjects(ast)) {
124 return [
125 ...ast.propertySignatures.flatMap((property) =>
126 walk(property.type, `${path}${String(property.name)}`),
127 ),
128 ...ast.indexSignatures.flatMap((signature) => walk(signature.type, `${path}*`)),
129 ];
130 }
131 if (SchemaAST.isArrays(ast)) {
132 return [...ast.elements, ...ast.rest].flatMap((element) => walk(element, `${path}[]`));
133 }
134 if (SchemaAST.isUnion(ast)) {
135 return ast.types.flatMap((member) => strictSecretReferencePaths(member, path, seen));
136 }
137 if (SchemaAST.isSuspend(ast)) return strictSecretReferencePaths(ast.thunk(), path, seen);
138 return [];
139 }
140
141 it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings", (it) => {
142 it.effect("serializes concurrent model preference edits without cancelling duplicate adds", () =>
143 Effect.gen(function* () {
144 const service = yield* ServerSettingsModule.ServerSettingsService;
145 const provider = ProviderInstanceId.make("codex_work");
146 yield* Effect.all(
147 [
148 service.updateSettings({
149 setModelFavorites: [{ provider, model: "sol", favorite: true }],
150 }),
151 service.updateSettings({
152 setModelFavorites: [{ provider, model: "sol", favorite: true }],
153 }),
154 service.updateSettings({
155 setModelFavorites: [{ provider, model: "luna", favorite: true }],
156 }),
157 service.updateSettings({ setModelsHidden: [{ provider, model: "astra", hidden: true }] }),
158 service.updateSettings({ setModelsHidden: [{ provider, model: "luna", hidden: true }] }),
159 service.updateSettings({
160 setProviderModelOrder: { provider, modelOrder: ["luna", "sol"] },
161 }),
162 ],
163 { concurrency: "unbounded" },
164 );
165 const settings = yield* service.getSettings;
166 assert.deepEqual(settings.favorites?.map((entry) => entry.model).sort(), ["luna", "sol"]);
167 assert.deepEqual(settings.providerModelPreferences?.[provider]?.hiddenModels.toSorted(), [
168 "astra",
169 "luna",
170 ]);
171 assert.deepEqual(settings.providerModelPreferences?.[provider]?.modelOrder, ["luna", "sol"]);
172 }).pipe(Effect.provide(layerServerSettings())),
173 );
174 it.effect("persists and broadcasts model preferences to other connected clients", () =>
175 Effect.scoped(
176 Effect.gen(function* () {
177 const service = yield* ServerSettingsModule.ServerSettingsService;
178 const config = yield* ServerConfig.ServerConfig;
179 const fs = yield* FileSystem.FileSystem;
180 const provider = ProviderInstanceId.make("codex_work");
181 const patch = {
182 favorites: [{ provider, model: "sol" }],
183 providerModelPreferences: {
184 [provider]: { hiddenModels: ["astra"], modelOrder: ["sol"] },
185 },
186 };
187 const changes = yield* service.subscribeChanges;
188 yield* service.updateSettings(patch);
189 const received = Option.getOrThrow(yield* Stream.runHead(changes));
190 assert.deepEqual(received.favorites, patch.favorites);
191 assert.deepEqual(received.providerModelPreferences, patch.providerModelPreferences);
192 const saved = yield* decodeServerSettingsJson(
193 yield* fs.readFileString(config.settingsPath),
194 );
195 assert.deepEqual(saved.favorites, patch.favorites);
196 assert.deepEqual(saved.providerModelPreferences, patch.providerModelPreferences);
197 const hidden = yield* service.updateSettings({
198 setModelsHidden: [{ provider, model: "sol", hidden: true }],
199 });
200 assert.deepEqual(hidden.providerModelPreferences?.[provider], {
201 hiddenModels: ["astra", "sol"],
202 modelOrder: ["sol"],
203 });
204 const shown = yield* service.updateSettings({
205 setModelsHidden: [{ provider, model: "astra", hidden: false }],
206 });
207 assert.deepEqual(shown.providerModelPreferences?.[provider], {
208 hiddenModels: ["sol"],
209 modelOrder: ["sol"],
210 });
211 assert.deepEqual(
212 (yield* decodeServerSettingsJson(yield* fs.readFileString(config.settingsPath)))
213 .providerModelPreferences,
214 shown.providerModelPreferences,
215 );
216 yield* service.updateSettings({ favorites: [], providerModelPreferences: {} });
217
218 const migrated = yield* service.updateSettings({ migrateModelPreferences: patch });
219 assert.deepEqual(migrated.favorites, []);
220 assert.deepEqual(migrated.providerModelPreferences, {});
221 }),
222 ).pipe(Effect.provide(layerServerSettings())),
223 );
224 it.effect("migrates saved token delivery to paragraph buffering without resetting settings", () =>
225 Effect.gen(function* () {
226 const config = yield* ServerConfig.ServerConfig;
227 const fs = yield* FileSystem.FileSystem;
228 const service = yield* ServerSettingsModule.ServerSettingsService;
229 yield* fs.writeFileString(
230 config.settingsPath,
231 `{
232 "responseStreamingMode": "token",
233 "enableAgentBrowserAccess": false,
234 "projectSettingsOverrides": {
235 "legacy": { "responseStreamingMode": "token", "defaultAutoPull": true },
236 "buffered": { "responseStreamingMode": "turn" },
237 "inherited": { "defaultAutoPull": false }
238 }
239 }`,
240 );
241
242 const settings = yield* service.getSettings;
243 assert.equal(settings.responseStreamingMode, "paragraph");
244 assert.isFalse(settings.enableAgentBrowserAccess);
245 assert.deepEqual(settings.projectSettingsOverrides, {
246 [ProjectId.make("legacy")]: { responseStreamingMode: "paragraph", defaultAutoPull: true },
247 [ProjectId.make("buffered")]: { responseStreamingMode: "turn" },
248 [ProjectId.make("inherited")]: { defaultAutoPull: false },
249 });
250
251 yield* service.updateSettings({ responseStreamingMode: "turn" });
252 const persisted = yield* decodeServerSettingsJson(
253 yield* fs.readFileString(config.settingsPath),
254 );
255 assert.equal(persisted.responseStreamingMode, "turn");
256 assert.deepEqual(persisted.projectSettingsOverrides, settings.projectSettingsOverrides);
257 }).pipe(Effect.provide(layerServerSettings())),
258 );
259
260 it.effect("keeps an override key a newer server saved when a project setting is edited", () =>
261 Effect.gen(function* () {
262 const config = yield* ServerConfig.ServerConfig;
263 const fs = yield* FileSystem.FileSystem;
264 const service = yield* ServerSettingsModule.ServerSettingsService;
265 const projectId = ProjectId.make("project-a");
266 yield* fs.writeFileString(
267 config.settingsPath,
268 `{ "projectSettingsOverrides": { "project-a": { "defaultAutoPull": true, "addedByNewerServer": 3 } } }`,
269 );
270 const loaded = yield* service.getSettings;
271
272 yield* service.updateSettings({
273 projectSettingsOverrides: {
274 [projectId]: { ...loaded.projectSettingsOverrides[projectId], defaultAutoPull: false },
275 },
276 });
277
278 const persisted = JSON.parse(yield* fs.readFileString(config.settingsPath));
279 assert.deepEqual(persisted.projectSettingsOverrides, {
280 [projectId]: { defaultAutoPull: false, addedByNewerServer: 3 },
281 });
282 }).pipe(Effect.provide(layerServerSettings())),
283 );
284
285 it.effect("moves an idle compaction mode saved in the legacy switch to its own field", () =>
286 Effect.gen(function* () {
287 const config = yield* ServerConfig.ServerConfig;
288 const fs = yield* FileSystem.FileSystem;
289 const service = yield* ServerSettingsModule.ServerSettingsService;
290 yield* fs.writeFileString(config.settingsPath, `{ "compactIdleThreads": "off" }`);
291
292 const settings = yield* service.getSettings;
293 // Shipped clients decode the switch as a boolean and drop the config otherwise.
294 assert.strictEqual(settings.compactIdleThreads, false);
295 assert.equal(settings.idleCompaction, "off");
296 }).pipe(Effect.provide(layerServerSettings())),
297 );
298
299 it.effect("tells clients it reads idle compaction modes before any settings are saved", () =>
300 Effect.gen(function* () {
301 const service = yield* ServerSettingsModule.ServerSettingsService;
302 const settings = yield* service.getSettings;
303 assert.equal(settings.idleCompaction, "onReturn");
304 assert.strictEqual(settings.compactIdleThreads, false);
305 }).pipe(Effect.provide(layerServerSettings())),
306 );
307
308 it.effect("sends clients a known secret provider's config but never an unknown kind's", () =>
309 Effect.gen(function* () {
310 const settings = yield* decodeServerSettings({
311 secretProviders: {
312 personal: { kind: "one_password", label: "Personal", config: { account: "my" } },
313 vault: { kind: "openbao", label: "Vault", config: { token: "bao-token" } },
314 },
315 });
316 assert.deepStrictEqual<unknown>(
317 ServerSettingsModule.redactServerSettingsForClient(settings, { secretReferences: true })
318 .secretProviders,
319 {
320 personal: { kind: "one_password", label: "Personal", config: { account: "my" } },
321 vault: { kind: "openbao", label: "Vault" },
322 },
323 );
324 }),
325 );
326
327 it.effect("stores no secret provider of an unloaded kind or with a config its kind rejects", () =>
328 Effect.gen(function* () {
329 const service = yield* ServerSettingsModule.ServerSettingsService;
330 const write = (entry: unknown) =>
331 decodeServerSettingsPatch({ secretProviders: { personal: entry } }).pipe(
332 Effect.flatMap(service.updateSettings),
333 Effect.flip,
334 );
335 for (const entry of [
336 { kind: "one_password", label: "Personal", config: { account: "--help" } },
337 { kind: "one_password", label: "Personal" },
338 { kind: "openbao", label: "Vault", config: { address: "https://x" } },
339 ]) {
340 assert.deepInclude(yield* write(entry), { operation: "write-secret-provider" });
341 }
342 assert.deepStrictEqual((yield* service.getSettings).secretProviders, {});
343 }).pipe(Effect.provide(layerServerSettings())),
344 );
345
346 it.effect("saves through a symlinked settings file without replacing the link", () =>
347 Effect.gen(function* () {
348 const config = yield* ServerConfig.ServerConfig;
349 const fs = yield* FileSystem.FileSystem;
350 const path = yield* Path.Path;
351 const service = yield* ServerSettingsModule.ServerSettingsService;
352 const dotfiles = yield* fs.makeTempDirectoryScoped({ prefix: "t3-settings-dotfiles-" });
353 const linkedSettingsPath = path.join(dotfiles, "settings.json");
354 yield* fs.writeFileString(linkedSettingsPath, `{ "responseStreamingMode": "turn" }`);
355 yield* fs.remove(config.settingsPath, { force: true });
356 yield* fs.symlink(linkedSettingsPath, config.settingsPath);
357
358 yield* service.updateSettings({ responseStreamingMode: "paragraph" });
359
360 assert.equal(yield* fs.readLink(config.settingsPath), linkedSettingsPath);
361 const persisted = yield* decodeServerSettingsJson(
362 yield* fs.readFileString(linkedSettingsPath),
363 );
364 assert.equal(persisted.responseStreamingMode, "paragraph");
365 }).pipe(Effect.provide(layerServerSettings())),
366 );
367
368 it.effect("retries a failed settings read instead of keeping the failure", () =>
369 Effect.gen(function* () {
370 const serverConfig = yield* ServerConfig.ServerConfig;
371 const fileSystem = yield* FileSystem.FileSystem;
372 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
373
374 yield* fileSystem.makeDirectory(serverConfig.settingsPath);
375
376 const error = yield* Effect.flip(serverSettings.getSettings);
377 assert.deepInclude(error, { _tag: "ServerSettingsError", operation: "read-file" });
378
379 yield* fileSystem.remove(serverConfig.settingsPath, { recursive: true });
380 yield* fileSystem.writeFileString(
381 serverConfig.settingsPath,
382 `{ "responseStreamingMode": "turn" }`,
383 );
384
385 const settings = yield* serverSettings.getSettings;
386 assert.equal(settings.responseStreamingMode, "turn");
387 }).pipe(Effect.provide(layerServerSettings())),
388 );
389
390 it.effect(
391 "decodes legacy object-shaped textGenerationModelSelection.options from settings.json",
392 () =>
393 Effect.gen(function* () {
394 const decoded = yield* decodeServerSettings({
395 textGenerationModelSelection: {
396 provider: ProviderDriverKind.make("codex"),
397 model: "gpt-5.4-mini",
398 options: { reasoningEffort: "low" },
399 },
400 });
401
402 assert.deepEqual(decoded.textGenerationModelSelection, {
403 instanceId: ProviderInstanceId.make("codex"),
404 model: "gpt-5.4-mini",
405 options: [{ id: "reasoningEffort", value: "low" }],
406 });
407 }),
408 );
409
410 it.effect("deep merges nested settings updates without dropping siblings", () =>
411 Effect.gen(function* () {
412 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
413
414 yield* serverSettings.updateSettings({
415 observability: { otlpTracesUrl: "http://localhost:4318/v1/traces" },
416 textGenerationModelSelection: {
417 instanceId: ProviderInstanceId.make("codex"),
418 model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
419 options: createModelSelection(
420 ProviderInstanceId.make("codex"),
421 DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
422 [
423 { id: "reasoningEffort", value: "high" },
424 { id: "fastMode", value: true },
425 ],
426 ).options!,
427 },
428 });
429
430 const next = yield* serverSettings.updateSettings({
431 observability: { otlpMetricsUrl: "http://localhost:4318/v1/metrics" },
432 textGenerationModelSelection: {
433 options: [{ id: "fastMode", value: false }],
434 },
435 });
436
437 assert.equal(next.observability.otlpTracesUrl, "http://localhost:4318/v1/traces");
438 assert.equal(next.observability.otlpMetricsUrl, "http://localhost:4318/v1/metrics");
439 assert.deepEqual(
440 next.textGenerationModelSelection,
441 createModelSelection(
442 ProviderInstanceId.make("codex"),
443 DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
444 [
445 { id: "reasoningEffort", value: "high" },
446 { id: "fastMode", value: false },
447 ],
448 ),
449 );
450 }).pipe(Effect.provide(layerServerSettings())),
451 );
452
453 it.effect("keeps an external settings edit that the watcher has not reloaded yet", () =>
454 Effect.gen(function* () {
455 const config = yield* ServerConfig.ServerConfig;
456 const fs = yield* FileSystem.FileSystem;
457 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
458 yield* serverSettings.getSettings;
459
460 yield* writeFileStringAtomically({
461 filePath: config.settingsPath,
462 contents: `{ "responseStreamingMode": "turn" }`,
463 });
464 yield* serverSettings.updateSettings({
465 observability: { otlpTracesUrl: "http://localhost:4318/v1/traces" },
466 });
467
468 const saved = yield* decodeServerSettingsJson(yield* fs.readFileString(config.settingsPath));
469 assert.equal(saved.responseStreamingMode, "turn");
470 assert.equal(saved.observability.otlpTracesUrl, "http://localhost:4318/v1/traces");
471
472 yield* writeFileStringAtomically({
473 filePath: config.settingsPath,
474 contents: `{ "responseStreamingMode": "paragraph" }`,
475 });
476 const instanceId = ProviderInstanceId.make("acpRegistry_kilo");
477 yield* serverSettings.updateProviderInstance({
478 operation: "upsert",
479 instanceId,
480 instance: {
481 driver: ProviderDriverKind.make("acpRegistry"),
482 displayName: "Kilo",
483 config: { agentId: "kilo", distribution: "auto" },
484 },
485 });
486
487 const afterProviderSave = yield* decodeServerSettingsJson(
488 yield* fs.readFileString(config.settingsPath),
489 );
490 assert.equal(afterProviderSave.responseStreamingMode, "paragraph");
491 assert.equal(afterProviderSave.providerInstances[instanceId]?.displayName, "Kilo");
492 }).pipe(Effect.provide(layerServerSettings())),
493 );
494
495 it.effect("refuses to save over a settings file it cannot parse", () =>
496 Effect.gen(function* () {
497 const config = yield* ServerConfig.ServerConfig;
498 const fs = yield* FileSystem.FileSystem;
499 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
500 yield* serverSettings.getSettings;
501 const raw = `{ "responseStreamingMode": "turn", `;
502 yield* fs.writeFileString(config.settingsPath, raw);
503
504 const error = yield* Effect.flip(
505 serverSettings.updateSettings({
506 observability: { otlpTracesUrl: "http://localhost:4318/v1/traces" },
507 }),
508 );
509
510 assert.equal(error.operation, "read-file");
511 assert.equal(error.settingsPath, config.settingsPath);
512 assert.instanceOf(error.cause, Error);
513 assert.equal(yield* fs.readFileString(config.settingsPath), raw);
514 }).pipe(Effect.provide(layerServerSettings())),
515 );
516
517 it.effect("creates provider instances atomically without overwriting a concurrent add", () =>
518 Effect.gen(function* () {
519 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
520 const instanceId = ProviderInstanceId.make("acpRegistry_shared");
521 const results = yield* Effect.forEach(
522 ["First", "Second"],
523 (displayName) =>
524 serverSettings
525 .updateProviderInstance({
526 operation: "create",
527 instanceId,
528 instance: {
529 driver: ProviderDriverKind.make("acpRegistry"),
530 displayName,
531 config: { agentId: "shared", distribution: "auto" },
532 },
533 })
534 .pipe(Effect.result),
535 { concurrency: "unbounded" },
536 );
537
538 assert.equal(results.filter((result) => result._tag === "Success").length, 1);
539 assert.equal(results.filter((result) => result._tag === "Failure").length, 1);
540 assert.isTrue(
541 ["First", "Second"].includes(
542 (yield* serverSettings.getSettings).providerInstances[instanceId]?.displayName ?? "",
543 ),
544 );
545
546 // An inherited Object.prototype member is not an instance that already exists.
547 for (const name of ["constructor", "toString", "valueOf"]) {
548 const prototypeNamedId = ProviderInstanceId.make(name);
549 const created = yield* serverSettings.updateProviderInstance({
550 operation: "create",
551 instanceId: prototypeNamedId,
552 instance: { driver: ProviderDriverKind.make("codex") },
553 });
554 assert.isTrue(Object.hasOwn(created.providerInstances, prototypeNamedId));
555 }
556 }).pipe(Effect.provide(layerServerSettings())),
557 );
558
559 it.effect("pauses provider-instance mutations while a settings snapshot is in use", () =>
560 Effect.gen(function* () {
561 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
562 const snapshotEntered = yield* Deferred.make<void>();
563 const releaseSnapshot = yield* Deferred.make<void>();
564 const mutationCompleted = yield* Deferred.make<void>();
565 const instanceId = ProviderInstanceId.make("acpRegistry_kilo");
566
567 const snapshotFiber = yield* serverSettings
568 .withSettingsSnapshot(() =>
569 Deferred.succeed(snapshotEntered, undefined).pipe(
570 Effect.andThen(Deferred.await(releaseSnapshot)),
571 ),
572 )
573 .pipe(Effect.forkChild({ startImmediately: true }));
574 yield* Deferred.await(snapshotEntered);
575
576 const mutationFiber = yield* serverSettings
577 .updateProviderInstance({
578 operation: "upsert",
579 instanceId,
580 instance: {
581 driver: ProviderDriverKind.make("acpRegistry"),
582 displayName: "Kilo",
583 config: { agentId: "kilo", distribution: "auto" },
584 },
585 })
586 .pipe(
587 Effect.tap(() => Deferred.succeed(mutationCompleted, undefined)),
588 Effect.forkChild({ startImmediately: true }),
589 );
590 yield* Effect.yieldNow;
591
592 assert.isTrue(Option.isNone(yield* Deferred.poll(mutationCompleted)));
593 yield* Deferred.succeed(releaseSnapshot, undefined);
594 yield* Fiber.join(snapshotFiber);
595 yield* Fiber.join(mutationFiber);
596 assert.equal(
597 (yield* serverSettings.getSettings).providerInstances[instanceId]?.displayName,
598 "Kilo",
599 );
600 }).pipe(Effect.provide(layerServerSettings())),
601 );
602
603 it.effect("buffers changes after a subscription is acquired but before it is consumed", () =>
604 Effect.scoped(
605 Effect.gen(function* () {
606 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
607 const changes = yield* serverSettings.subscribeChanges;
608
609 yield* serverSettings.updateSettings({
610 addProjectBaseDirectory: "~/next",
611 });
612
613 const firstChange = yield* changes.pipe(Stream.runHead, Effect.timeout("1 second"));
614 assert.equal(Option.getOrUndefined(firstChange)?.addProjectBaseDirectory, "~/next");
615 }),
616 ).pipe(Effect.provide(layerServerSettings())),
617 );
618
619 it.effect("preserves saved usage settings during cleanup edits and removes custom prices", () =>
620 Effect.scoped(
621 Effect.gen(function* () {
622 const serverConfig = yield* ServerConfig.ServerConfig;
623 const fileSystem = yield* FileSystem.FileSystem;
624 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
625 const prices = {
626 inputCostPerMillionTokens: 2,
627 outputCostPerMillionTokens: 8,
628 cacheReadCostPerMillionTokens: 0,
629 };
630 const readPersisted = fileSystem
631 .readFileString(serverConfig.settingsPath)
632 .pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(ServerSettings))));
633
634 yield* serverSettings.updateSettings({ usagePriceOverrides: { "example-model": prices } });
635 const usageModelAliases = { "example-preview": "example-model" };
636 const sourceId = UsageLimitSourceId.make("hub");
637 const usageLimitSources = {
638 [sourceId]: {
639 kind: "cliproxy" as const,
640 url: "https://hub.example.test",
641 managementKey: "",
642 enabled: true,
643 },
644 };
645 const saved = yield* serverSettings.updateSettings({
646 usageModelAliases,
647 usageLimitSources,
648 });
649 const updated = yield* serverSettings.updateSettings({
650 storageCleanup: { worktreeSettledAfterDays: 0, worktreeKeepWhen: "any-local-files" },
651 });
652 assert.deepStrictEqual(updated.usageLimitSources, saved.usageLimitSources);
653 const persisted = yield* readPersisted;
654 assert.deepStrictEqual(persisted.usagePriceOverrides, { "example-model": prices });
655 assert.deepStrictEqual(persisted.usageModelAliases, usageModelAliases);
656 assert.deepStrictEqual(persisted.usageLimitSources, usageLimitSources);
657 assert.equal(persisted.storageCleanup.worktreeSettledAfterDays, 0);
658 assert.equal(persisted.storageCleanup.worktreeKeepWhen, "any-local-files");
659
660 yield* serverSettings.updateSettings({ usagePriceOverrides: { "example-model": null } });
661 const restored = yield* readPersisted;
662 assert.deepStrictEqual(restored.usagePriceOverrides, {});
663 }),
664 ).pipe(Effect.provide(layerServerSettings())),
665 );
666
667 it.effect("preserves model when switching providers via textGenerationModelSelection", () =>
668 Effect.gen(function* () {
669 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
670
671 yield* serverSettings.updateSettings({
672 textGenerationModelSelection: {
673 instanceId: ProviderInstanceId.make("claudeAgent"),
674 model: "claude-sonnet-4-6",
675 options: createModelSelection(
676 ProviderInstanceId.make("claudeAgent"),
677 "claude-sonnet-4-6",
678 [{ id: "effort", value: "high" }],
679 ).options!,
680 },
681 });
682
683 const next = yield* serverSettings.updateSettings({
684 textGenerationModelSelection: {
685 instanceId: ProviderInstanceId.make("codex"),
686 model: "gpt-5.4",
687 options: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
688 { id: "reasoningEffort", value: "high" },
689 ]).options!,
690 },
691 });
692
693 assert.deepEqual(
694 next.textGenerationModelSelection,
695 createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
696 { id: "reasoningEffort", value: "high" },
697 ]),
698 );
699 }).pipe(Effect.provide(layerServerSettings())),
700 );
701
702 it.effect(
703 "keeps a custom instance's selection when the driver's default instance is disabled",
704 () =>
705 Effect.gen(function* () {
706 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
707 const instanceId = ProviderInstanceId.make("claude_openrouter");
708
709 const next = yield* serverSettings.updateSettings({
710 providerInstances: {
711 [ProviderInstanceId.make("claudeAgent")]: {
712 driver: ProviderDriverKind.make("claudeAgent"),
713 enabled: false,
714 },
715 [instanceId]: {
716 driver: ProviderDriverKind.make("claudeAgent"),
717 enabled: true,
718 config: { customModels: ["openai/gpt-5.5"] },
719 },
720 },
721 textGenerationModelSelection: {
722 instanceId,
723 model: "openai/gpt-5.5",
724 },
725 });
726
727 assert.deepEqual(next.textGenerationModelSelection, {
728 instanceId,
729 model: "openai/gpt-5.5",
730 });
731 }).pipe(Effect.provide(layerServerSettings())),
732 );
733
734 it.effect.each(["codex"])(
735 "falls back to enabled instance %s after disabling the selection",
736 (fallbackId) =>
737 Effect.scoped(
738 Effect.gen(function* () {
739 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
740 const serverConfig = yield* ServerConfig.ServerConfig;
741 const fileSystem = yield* FileSystem.FileSystem;
742 const writerId = ProviderInstanceId.make("writer");
743 const fallbackInstanceId = ProviderInstanceId.make(fallbackId);
744 const selection = { instanceId: writerId, model: "claude-sonnet-4-6" };
745 const providerInstances = {
746 [ProviderInstanceId.make("claudeAgent")]: {
747 driver: ProviderDriverKind.make("claudeAgent"),
748 enabled: false,
749 },
750 [fallbackInstanceId]: {
751 driver: ProviderDriverKind.make("codex"),
752 enabled: true,
753 config: {},
754 },
755 [writerId]: {
756 driver: ProviderDriverKind.make("claudeAgent"),
757 enabled: true,
758 config: {},
759 },
760 };
761
762 yield* serverSettings.updateSettings({
763 providerInstances,
764 textGenerationModelSelection: selection,
765 });
766 const changes = yield* serverSettings.subscribeChanges;
767
768 const next = yield* serverSettings.updateSettings({
769 providerInstances: {
770 ...providerInstances,
771 [writerId]: { ...providerInstances[writerId]!, enabled: false },
772 },
773 });
774 const fallbackSelection = {
775 instanceId: fallbackInstanceId,
776 model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
777 };
778 assert.deepEqual(next.textGenerationModelSelection, fallbackSelection);
779 assert.deepEqual(
780 (yield* serverSettings.getSettings).textGenerationModelSelection,
781 fallbackSelection,
782 );
783 const change = Option.getOrUndefined(yield* Stream.runHead(changes));
784 assert.deepEqual(change?.textGenerationModelSelection, fallbackSelection);
785
786 const persisted = yield* fileSystem
787 .readFileString(serverConfig.settingsPath)
788 .pipe(
789 Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(ServerSettings))),
790 );
791 assert.deepEqual(persisted.textGenerationModelSelection, selection);
792
793 const restored = yield* serverSettings.updateSettings({ providerInstances });
794 assert.deepEqual(restored.textGenerationModelSelection, selection);
795 }),
796 ).pipe(Effect.provide(layerServerSettings())),
797 );
798
799 it.effect("skips explicitly disabled default instances when choosing a fallback", () =>
800 Effect.gen(function* () {
801 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
802 const next = yield* serverSettings.updateSettings({
803 providerInstances: {
804 [ProviderInstanceId.make("codex")]: {
805 driver: ProviderDriverKind.make("codex"),
806 enabled: false,
807 config: {},
808 },
809 },
810 });
811
812 assert.equal(next.textGenerationModelSelection.instanceId, "claudeAgent");
813 assert.equal(next.textGenerationModelSelection.model, "claude-haiku-5-5");
814 }).pipe(Effect.provide(layerServerSettings())),
815 );
816
817 // A backend behind a custom model may refuse the built-in default.
818 it.effect("falls back to the thread default when it is a custom model on that instance", () =>
819 Effect.gen(function* () {
820 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
821 const claude = ProviderInstanceId.make("claudeAgent");
822 const providerInstances = {
823 [ProviderInstanceId.make("codex")]: {
824 driver: ProviderDriverKind.make("codex"),
825 enabled: false,
826 config: {},
827 },
828 [claude]: {
829 driver: ProviderDriverKind.make("claudeAgent"),
830 config: { customModels: ["z-ai/glm-5.3-flash"] },
831 },
832 };
833
834 const custom = yield* serverSettings.updateSettings({
835 providerInstances,
836 defaultModelSelection: {
837 instanceId: claude,
838 model: "z-ai/glm-5.3-flash",
839 options: [{ id: "thinking", value: false }],
840 },
841 });
842 assert.deepEqual(custom.textGenerationModelSelection, {
843 instanceId: claude,
844 model: "z-ai/glm-5.3-flash",
845 options: [{ id: "thinking", value: false }],
846 });
847
848 const builtIn = yield* serverSettings.updateSettings({
849 defaultModelSelection: { instanceId: claude, model: "claude-fable-5-1" },
850 });
851 assert.equal(builtIn.textGenerationModelSelection.model, "claude-haiku-5-5");
852 }).pipe(Effect.provide(layerServerSettings())),
853 );
854
855 it.effect(
856 "preserves the source control writer selection when its provider instance is disabled",
857 () =>
858 Effect.gen(function* () {
859 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
860 const serverConfig = yield* ServerConfig.ServerConfig;
861 const fileSystem = yield* FileSystem.FileSystem;
862 const instanceId = ProviderInstanceId.make("codex_writer");
863 const sourceControlWriterModelSelection = {
864 instanceId,
865 model: "gpt-5.4-mini",
866 };
867
868 yield* serverSettings.updateSettings({
869 providerInstances: {
870 [instanceId]: {
871 driver: ProviderDriverKind.make("codex"),
872 enabled: true,
873 config: {},
874 },
875 },
876 sourceControlWriterModelSelection,
877 });
878
879 const next = yield* serverSettings.updateSettings({
880 providerInstances: {
881 [instanceId]: {
882 driver: ProviderDriverKind.make("codex"),
883 enabled: false,
884 config: {},
885 },
886 },
887 });
888
889 assert.deepEqual(next.sourceControlWriterModelSelection, sourceControlWriterModelSelection);
890 assert.deepEqual(
891 ServerSettingsModule.resolveSourceControlWriterModelSelection(next, undefined, null),
892 next.textGenerationModelSelection,
893 );
894 assert.deepEqual(
895 (yield* serverSettings.getSettings).sourceControlWriterModelSelection,
896 sourceControlWriterModelSelection,
897 );
898
899 const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
900 assert.deepEqual(
901 JSON.parse(raw).sourceControlWriterModelSelection,
902 sourceControlWriterModelSelection,
903 );
904
905 const restored = yield* serverSettings.updateSettings({
906 providerInstances: {
907 [instanceId]: {
908 driver: ProviderDriverKind.make("codex"),
909 enabled: true,
910 config: {},
911 },
912 },
913 });
914 assert.deepEqual(
915 ServerSettingsModule.resolveSourceControlWriterModelSelection(restored, undefined, null),
916 sourceControlWriterModelSelection,
917 );
918 }).pipe(Effect.provide(layerServerSettings())),
919 );
920
921 it.effect("moves customized legacy provider settings into default instances on load", () =>
922 Effect.gen(function* () {
923 const serverConfig = yield* ServerConfig.ServerConfig;
924 const fileSystem = yield* FileSystem.FileSystem;
925 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
926 yield* fileSystem.writeFileString(
927 serverConfig.settingsPath,
928 JSON.stringify({
929 addProjectBaseDirectory: "~/Development",
930 providers: {
931 codex: { binaryPath: "/opt/guard/bin/codex" },
932 claudeAgent: { enabled: false },
933 cursor: { enabled: false },
934 grok: { enabled: false },
935 opencode: { enabled: false },
936 },
937 }),
938 );
939
940 const settings = yield* serverSettings.getSettings;
941
942 assert.deepEqual(settings.providerInstances, {
943 [ProviderInstanceId.make("codex")]: {
944 driver: ProviderDriverKind.make("codex"),
945 config: { binaryPath: "/opt/guard/bin/codex" },
946 },
947 [ProviderInstanceId.make("claudeAgent")]: {
948 driver: ProviderDriverKind.make("claudeAgent"),
949 enabled: false,
950 config: {},
951 },
952 });
953
954 const persisted = JSON.parse(yield* fileSystem.readFileString(serverConfig.settingsPath));
955 assert.isUndefined(persisted.providers);
956 assert.equal(persisted.addProjectBaseDirectory, "~/Development");
957 assert.deepEqual(persisted.providerInstances.codex, {
958 driver: "codex",
959 config: { binaryPath: "/opt/guard/bin/codex" },
960 });
961 }).pipe(Effect.provide(layerServerSettings())),
962 );
963
964 it.effect("keeps an explicit default instance over the legacy blob for its driver", () =>
965 Effect.gen(function* () {
966 const serverConfig = yield* ServerConfig.ServerConfig;
967 const fileSystem = yield* FileSystem.FileSystem;
968 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
969 yield* fileSystem.writeFileString(
970 serverConfig.settingsPath,
971 JSON.stringify({
972 providers: { codex: { binaryPath: "/legacy/codex" } },
973 providerInstances: {
974 codex: { driver: "codex", enabled: true, config: { binaryPath: "/explicit/codex" } },
975 },
976 }),
977 );
978
979 const settings = yield* serverSettings.getSettings;
980
981 assert.deepEqual(settings.providerInstances[ProviderInstanceId.make("codex")], {
982 driver: ProviderDriverKind.make("codex"),
983 enabled: true,
984 config: { binaryPath: "/explicit/codex" },
985 });
986 }).pipe(Effect.provide(layerServerSettings())),
987 );
988
989 it.effect("enables previously used optional providers while migrating legacy settings", () =>
990 Effect.gen(function* () {
991 const serverConfig = yield* ServerConfig.ServerConfig;
992 const fileSystem = yield* FileSystem.FileSystem;
993 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
994 yield* fileSystem.writeFileString(
995 serverConfig.settingsPath,
996 JSON.stringify({
997 providers: { opencode: { serverUrl: "http://127.0.0.1:4096" }, cursor: {} },
998 providerInstances: {
999 cursor_work: { driver: "cursor", config: {} },
1000 opencode_unused: { driver: "opencode", config: {} },
1001 },
1002 }),
1003 );
1004 yield* recordProviderUsage("opencode");
1005 yield* recordProviderUsage("grok", null);
1006 yield* recordProviderUsage("cursor", "cursor_work");
1007
1008 const settings = yield* serverSettings.getSettings;
1009
1010 assert.deepEqual(settings.providerInstances[ProviderInstanceId.make("opencode")], {
1011 driver: ProviderDriverKind.make("opencode"),
1012 enabled: true,
1013 config: { serverUrl: "http://127.0.0.1:4096" },
1014 });
1015
1016 assert.isTrue(settings.providerInstances[ProviderInstanceId.make("grok")]?.enabled);
1017 assert.isTrue(settings.providerInstances[ProviderInstanceId.make("cursor_work")]?.enabled);
1018
1019 assert.isTrue(settings.providerInstances[ProviderInstanceId.make("cursor")]?.enabled);
1020 const unused = settings.providerInstances[ProviderInstanceId.make("opencode_unused")];
1021 assert.isDefined(unused);
1022 assert.isFalse(resolveProviderInstanceEnabled(unused));
1023 }).pipe(Effect.provide(layerServerSettings())),
1024 );
1025
1026 it.effect("keeps explicit legacy disables even when provider history shows use", () =>
1027 Effect.gen(function* () {
1028 const serverConfig = yield* ServerConfig.ServerConfig;
1029 const fileSystem = yield* FileSystem.FileSystem;
1030 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
1031 yield* fileSystem.writeFileString(
1032 serverConfig.settingsPath,
1033 JSON.stringify({ providers: { grok: { enabled: false, binaryPath: "/opt/grok" } } }),
1034 );
1035 yield* recordProviderUsage("grok");
1036
1037 const settings = yield* serverSettings.getSettings;
1038
1039 assert.deepEqual(settings.providerInstances[ProviderInstanceId.make("grok")], {
1040 driver: ProviderDriverKind.make("grok"),
1041 enabled: false,
1042 config: { binaryPath: "/opt/grok" },
1043 });
1044 }).pipe(Effect.provide(layerServerSettings())),
1045 );
1046
1047 it.effect("migrates legacy providers from an invalid file without rewriting it", () =>
1048 Effect.gen(function* () {
1049 const serverConfig = yield* ServerConfig.ServerConfig;
1050 const fileSystem = yield* FileSystem.FileSystem;
1051 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
1052 const raw =
1053 '{"addProjectBaseDirectory":42,"continueThreadsAfterServerUpdate":"false","providers":{"codex":{"binaryPath":"/x"}}}';
1054 yield* fileSystem.writeFileString(serverConfig.settingsPath, raw);
1055
1056 const settings = yield* serverSettings.getSettings;
1057
1058 assert.deepEqual(settings.providerInstances[ProviderInstanceId.make("codex")], {
1059 driver: ProviderDriverKind.make("codex"),
1060 config: { binaryPath: "/x" },
1061 });
1062
1063 assert.isFalse(settings.continueThreadsAfterServerUpdate);
1064 assert.equal(yield* fileSystem.readFileString(serverConfig.settingsPath), raw);
1065 }).pipe(Effect.provide(layerServerSettings())),
1066 );
1067
1068 it.effect("keeps a default-off provider's new instance disabled and sparse on disk", () =>
1069 Effect.gen(function* () {
1070 const serverConfig = yield* ServerConfig.ServerConfig;
1071 const fileSystem = yield* FileSystem.FileSystem;
1072 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
1073
1074 const next = yield* serverSettings.updateSettings({
1075 providerInstances: {
1076 [ProviderInstanceId.make("grok")]: {
1077 driver: ProviderDriverKind.make("grok"),
1078 config: {},
1079 },
1080 },
1081 });
1082
1083 const grok = next.providerInstances[ProviderInstanceId.make("grok")];
1084 assert.isDefined(grok);
1085 assert.isFalse(resolveProviderInstanceEnabled(grok));
1086 const persisted = JSON.parse(yield* fileSystem.readFileString(serverConfig.settingsPath));
1087 assert.isUndefined(persisted.providers);
1088 assert.isUndefined(persisted.providerInstances.grok.enabled);
1089 }).pipe(Effect.provide(layerServerSettings())),
1090 );
1091
1092 it.effect("folds a legacy in-config enabled flag into the envelope on load", () =>
1093 Effect.gen(function* () {
1094 const serverConfig = yield* ServerConfig.ServerConfig;
1095 const fileSystem = yield* FileSystem.FileSystem;
1096 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
1097
1098 yield* fileSystem.writeFileString(
1099 serverConfig.settingsPath,
1100 '{"providerInstances":{"grok":{"driver":"grok","enabled":true,"config":{"enabled":false}},"codex_work":{"driver":"codex","config":{"enabled":true,"homePath":"~/.codex"}},"cursor":{"driver":"cursor","config":{"enabled":"nope"}}}}',
1101 );
1102
1103 const settings = yield* serverSettings.getSettings;
1104
1105 const grokId = ProviderInstanceId.make("grok");
1106 const codexWorkId = ProviderInstanceId.make("codex_work");
1107 assert.deepEqual(settings.providerInstances[grokId], {
1108 driver: ProviderDriverKind.make("grok"),
1109 enabled: false,
1110 config: {},
1111 });
1112
1113 assert.deepEqual(settings.providerInstances[codexWorkId], {
1114 driver: ProviderDriverKind.make("codex"),
1115 enabled: true,
1116 config: { homePath: "~/.codex" },
1117 });
1118
1119 assert.deepEqual(settings.providerInstances[ProviderInstanceId.make("cursor")], {
1120 driver: ProviderDriverKind.make("cursor"),
1121 config: { enabled: "nope" },
1122 });
1123 }).pipe(Effect.provide(layerServerSettings())),
1124 );
1125
1126 it.effect("reads settings secrets once per settings change", () => {
1127 let reads = 0;
1128 const layerSecret = Layer.effect(
1129 ServerSecretStore.ServerSecretStore,
1130 Effect.map(ServerSecretStore.ServerSecretStore, (store) => ({
1131 ...store,
1132 get: (name: string) =>
1133 Effect.suspend(() => {
1134 reads++;
1135 return store.get(name);
1136 }),
1137 })),
1138 ).pipe(Layer.provide(ServerSecretStore.layer));
1139 const layerSettings = ServerSettingsModule.layer.pipe(
1140 Layer.provide(layerSecret),
1141 Layer.provide(ManagedPolicy.layerTest()),
1142 Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
1143 Layer.provideMerge(
1144 Layer.fresh(
1145 ServerConfig.layerTest(process.cwd(), { prefix: "t3code-settings-secret-cache-test-" }),
1146 ),
1147 ),
1148 );
1149 return Effect.gen(function* () {
1150 const instanceId = ProviderInstanceId.make("codex_cached");
1151 const service = yield* ServerSettingsModule.ServerSettingsService;
1152 const save = (value: string) =>
1153 service.updateSettings({
1154 providerInstances: {
1155 [instanceId]: {
1156 driver: ProviderDriverKind.make("codex"),
1157 environment: [{ name: "API_TOKEN", value, sensitive: true }],
1158 config: {},
1159 },
1160 },
1161 });
1162 const token = service.getSettings.pipe(
1163 Effect.map((settings) => settings.providerInstances[instanceId]?.environment?.[0]?.value),
1164 );
1165 yield* save("sk-first");
1166 reads = 0;
1167 assert.equal(yield* token, "sk-first");
1168 assert.equal(yield* token, "sk-first");
1169 assert.equal(reads, 0);
1170 yield* save("sk-second");
1171 assert.equal(yield* token, "sk-second");
1172 }).pipe(Effect.provide(layerSettings));
1173 });
1174
1175 it.effect("keeps the inline value on disk when secret migration fails", () => {
1176 const cause = new ServerSecretStore.SecretStorePersistError({
1177 resource: "provider environment secret",
1178 cause: new Error("Secret storage unavailable"),
1179 });
1180 const layerSecret = Layer.effect(
1181 ServerSecretStore.ServerSecretStore,
1182 Effect.map(ServerSecretStore.ServerSecretStore, (store) => ({
1183 ...store,
1184 set: () => Effect.fail(cause),
1185 })),
1186 ).pipe(Layer.provide(ServerSecretStore.layer));
1187 const layerSettings = ServerSettingsModule.layer.pipe(
1188 Layer.provide(ManagedPolicy.layerTest()),
1189 Layer.provide(layerSecret),
1190 Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
1191 Layer.provideMerge(
1192 Layer.fresh(
1193 ServerConfig.layerTest(process.cwd(), {
1194 prefix: "t3code-inline-secret-failure-test-",
1195 }),
1196 ),
1197 ),
1198 );
1199 return Effect.gen(function* () {
1200 const instanceId = ProviderInstanceId.make("codex_personal");
1201 const service = yield* ServerSettingsModule.ServerSettingsService;
1202 const config = yield* ServerConfig.ServerConfig;
1203 const fs = yield* FileSystem.FileSystem;
1204 const original =
1205 '{"providerInstances":{"codex_personal":{"driver":"codex","environment":[{"name":"API_TOKEN","value":"inline-test-token","sensitive":true}],"config":{}}}}';
1206 yield* fs.writeFileString(config.settingsPath, original);
1207 const error = yield* Effect.flip(
1208 service.updateSettings({
1209 providerInstances: {
1210 [instanceId]: {
1211 driver: ProviderDriverKind.make("codex"),
1212 environment: [{ name: "API_TOKEN", value: "", sensitive: true, valueRedacted: true }],
1213 config: {},
1214 },
1215 },
1216 }),
1217 );
1218 assert.equal(error.operation, "write-secret");
1219 assert.strictEqual(error.cause, cause);
1220 assert.equal(yield* fs.readFileString(config.settingsPath), original);
1221 const settings = yield* service.getSettings;
1222 assert.equal(
1223 settings.providerInstances[instanceId]?.environment?.[0]?.value,
1224 "inline-test-token",
1225 );
1226 }).pipe(Effect.provide(layerSettings));
1227 });
1228
1229 it.effect.each(
1230 [
1231 {
1232 label: "preserves an inline secret on a redacted settings save",
1233 variable: { name: "API_TOKEN", value: "", sensitive: true, valueRedacted: true },
1234 expected: "inline-test-token",
1235 },
1236 {
1237 label: "preserves the effective last inline secret when names are duplicated",
1238 variable: { name: "API_TOKEN", value: "", sensitive: true, valueRedacted: true },
1239 expected: "last-inline-test-token",
1240 duplicate: true,
1241 },
1242 {
1243 label: "replaces an inline secret with an explicit value",
1244 variable: { name: "API_TOKEN", value: "replacement-test-token", sensitive: true },
1245 expected: "replacement-test-token",
1246 },
1247 {
1248 label: "clears an inline secret with an explicit empty value",
1249 variable: { name: "API_TOKEN", value: "", sensitive: true },
1250 expected: "",
1251 },
1252 ].map((testCase) => [testCase.label, testCase] as const),
1253 )("%s", ([, { variable, expected, duplicate }]) =>
1254 Effect.gen(function* () {
1255 const instanceId = ProviderInstanceId.make("codex_personal");
1256 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
1257 const serverConfig = yield* ServerConfig.ServerConfig;
1258 const fileSystem = yield* FileSystem.FileSystem;
1259 yield* fileSystem.writeFileString(
1260 serverConfig.settingsPath,
1261 duplicate
1262 ? '{"providerInstances":{"codex_personal":{"driver":"codex","environment":[{"name":"API_TOKEN","value":"inline-test-token","sensitive":true},{"name":"API_TOKEN","value":"last-inline-test-token","sensitive":true}],"config":{}}}}'
1263 : '{"providerInstances":{"codex_personal":{"driver":"codex","environment":[{"name":"API_TOKEN","value":"inline-test-token","sensitive":true}],"config":{}}}}',
1264 );
1265 const initial = yield* serverSettings.getSettings;
1266 assert.equal(
1267 initial.providerInstances[instanceId]?.environment?.[0]?.value,
1268 "inline-test-token",
1269 );
1270
1271 const next = yield* serverSettings.updateSettings({
1272 providerInstances: {
1273 [instanceId]: {
1274 driver: ProviderDriverKind.make("codex"),
1275 displayName: "Renamed provider",
1276 environment: duplicate ? [variable, variable] : [variable],
1277 config: {},
1278 },
1279 },
1280 });
1281 assert.equal(next.providerInstances[instanceId]?.environment?.[0]?.value, expected);
1282 const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
1283 assert.notInclude(raw, "inline-test-token");
1284 assert.notInclude(raw, "replacement-test-token");
1285
1286 const reloaded = yield* Effect.gen(function* () {
1287 const fresh = yield* ServerSettingsModule.ServerSettingsService;
1288 return yield* fresh.getSettings;
1289 }).pipe(
1290 Effect.provide(
1291 Layer.fresh(ServerSettingsModule.layer).pipe(
1292 Layer.provide(Layer.merge(ServerSecretStore.layer, ManagedPolicy.layerTest())),
1293 ),
1294 ),
1295 );
1296 assert.equal(reloaded.providerInstances[instanceId]?.environment?.[0]?.value, expected);
1297 }).pipe(Effect.provide(layerServerSettings())),
1298 );
1299
1300 it.effect.each(
1301 [
1302 { label: "redacted then empty sensitive", duplicate: { value: "", sensitive: true } },
1303 {
1304 label: "empty sensitive then redacted",
1305 duplicate: { value: "", sensitive: true },
1306 redactedLast: true,
1307 },
1308 { label: "redacted then plain", duplicate: { value: "plain-foo", sensitive: false } },
1309 {
1310 label: "plain then redacted",
1311 duplicate: { value: "plain-foo", sensitive: false },
1312 redactedLast: true,
1313 },
1314 {
1315 label: "secret reference then redacted",
1316 duplicate: {
1317 value: { provider: SecretProviderId.make("personal"), reference: "op://Private/FOO" },
1318 sensitive: true,
1319 },
1320 redactedLast: true,
1321 },
1322 {
1323 label: "inline seed, redacted then empty sensitive",
1324 duplicate: { value: "", sensitive: true },
1325 inline: '[{"name":"FOO","value":"stored-foo","sensitive":true}]',
1326 },
1327 {
1328 label: "inline seed with an empty duplicate, redacted then empty sensitive",
1329 duplicate: { value: "", sensitive: true },
1330 inline:
1331 '[{"name":"FOO","value":"stored-foo","sensitive":true},{"name":"FOO","value":"","sensitive":true}]',
1332 },
1333 {
1334 label: "inline seed with an empty duplicate, new value then redacted",
1335 duplicate: { value: "new-foo", sensitive: true },
1336 redactedLast: true,
1337 inline:
1338 '[{"name":"FOO","value":"stored-foo","sensitive":true},{"name":"FOO","value":"","sensitive":true}]',
1339 expected: "new-foo",
1340 },
1341 ].map((testCase) => [testCase.label, testCase] as const),
1342 )(
1343 "keeps a stored secret a redacted row still claims when a duplicate name is saved (%s)",
1344 ([, { duplicate, redactedLast, inline, expected = "stored-foo" }]) =>
1345 Effect.gen(function* () {
1346 const service = yield* ServerSettingsModule.ServerSettingsService;
1347 const instanceId = ProviderInstanceId.make("codex_personal");
1348 const save = (environment: ProviderInstanceEnvironment) =>
1349 service.updateSettings({
1350 providerInstances: {
1351 [instanceId]: { driver: ProviderDriverKind.make("codex"), environment, config: {} },
1352 },
1353 });
1354 if (inline) {
1355 const config = yield* ServerConfig.ServerConfig;
1356 const fs = yield* FileSystem.FileSystem;
1357 yield* fs.writeFileString(
1358 config.settingsPath,
1359 `{"providerInstances":{"codex_personal":{"driver":"codex","environment":${inline},"config":{}}}}`,
1360 );
1361 yield* service.getSettings;
1362 } else {
1363 yield* save([{ name: "FOO", value: "stored-foo", sensitive: true }]);
1364 }
1365 const redacted = { name: "FOO", value: "", sensitive: true, valueRedacted: true };
1366 const copy = { name: "FOO", ...duplicate };
1367 yield* save(redactedLast ? [copy, redacted] : [redacted, copy]);
1368
1369 const reloaded = yield* Effect.gen(function* () {
1370 const fresh = yield* ServerSettingsModule.ServerSettingsService;
1371 return yield* fresh.getSettings;
1372 }).pipe(
1373 Effect.provide(
1374 Layer.fresh(ServerSettingsModule.layer).pipe(
1375 Layer.provide(Layer.merge(ServerSecretStore.layer, ManagedPolicy.layerTest())),
1376 ),
1377 ),
1378 );
1379 assert.equal(
1380 reloaded.providerInstances[instanceId]?.environment?.[redactedLast ? 1 : 0]?.value,
1381 expected,
1382 );
1383 }).pipe(Effect.provide(layerServerSettings())),
1384 );
1385
1386 it.effect("removes a kept secret once every row with its name is deleted", () =>
1387 Effect.gen(function* () {
1388 const service = yield* ServerSettingsModule.ServerSettingsService;
1389 const store = yield* ServerSecretStore.ServerSecretStore;
1390 const instanceId = ProviderInstanceId.make("codex_personal");
1391 const save = (environment: ProviderInstanceEnvironment) =>
1392 service.updateSettings({
1393 providerInstances: {
1394 [instanceId]: { driver: ProviderDriverKind.make("codex"), environment, config: {} },
1395 },
1396 });
1397 yield* save([{ name: "FOO", value: "stored-foo", sensitive: true }]);
1398 yield* save([
1399 { name: "FOO", value: "", sensitive: true, valueRedacted: true },
1400 { name: "FOO", value: "plain-foo", sensitive: false },
1401 ]);
1402 const secretName = "provider-env-Y29kZXhfcGVyc29uYWw-Rk9P";
1403 assert.isTrue(Option.isSome(yield* store.get(secretName)));
1404 yield* save([]);
1405 assert.isTrue(Option.isNone(yield* store.get(secretName)));
1406 }).pipe(Effect.provide(layerServerSettingsWithSecrets())),
1407 );
1408
1409 it.effect.each([true, false])(
1410 "preserves duplicate secret operation order (sensitive last: %s)",
1411 (sensitiveLast) =>
1412 Effect.gen(function* () {
1413 const service = yield* ServerSettingsModule.ServerSettingsService;
1414 const instanceId = ProviderInstanceId.make("codex_duplicate");
1415 const secret = { name: "API_TOKEN", value: "secret-last", sensitive: true };
1416 const plain = { name: "API_TOKEN", value: "plain-last", sensitive: false };
1417 const next = yield* service.updateSettings({
1418 providerInstances: {
1419 [instanceId]: {
1420 driver: ProviderDriverKind.make("codex"),
1421 environment: sensitiveLast ? [plain, secret] : [secret, plain],
1422 config: {},
1423 },
1424 },
1425 });
1426 assert.equal(
1427 next.providerInstances[instanceId]?.environment?.at(-1)?.value,
1428 sensitiveLast ? "secret-last" : "plain-last",
1429 );
1430 assert.equal(
1431 next.providerInstances[instanceId]?.environment?.find((v) => v.sensitive)?.value,
1432 sensitiveLast ? "secret-last" : "",
1433 );
1434 }).pipe(Effect.provide(layerServerSettings())),
1435 );
1436
1437 it.effect(
1438 "uses the same secret lifecycle for provider config, environment, host tokens, and quota keys",
1439 () =>
1440 Effect.gen(function* () {
1441 const service = yield* ServerSettingsModule.ServerSettingsService;
1442 const config = yield* ServerConfig.ServerConfig;
1443 const fs = yield* FileSystem.FileSystem;
1444 const store = yield* ServerSecretStore.ServerSecretStore;
1445 const instanceId = ProviderInstanceId.make("antigravity_secrets");
1446 const saved = yield* service.updateSettings({
1447 providerInstances: {
1448 [instanceId]: {
1449 driver: ProviderDriverKind.make("antigravity"),
1450 config: { apiKey: "config-secret" },
1451 environment: [
1452 { name: "API_TOKEN", value: "env-secret", sensitive: true },
1453 { name: "BASE_URL", value: "https://example.test", sensitive: false },
1454 ],
1455 },
1456 },
1457 sourceControlHosts: {
1458 github: { tokens: { "github.com": "github-secret" } },
1459 bitbucket: { email: "me@example.test", accessToken: "bitbucket-secret" },
1460 gitcafe: { token: "gitcafe-secret" },
1461 },
1462 usageLimitSources: {
1463 [UsageLimitSourceId.make("hub")]: {
1464 kind: "cliproxy",
1465 url: "https://hub.example.test",
1466 managementKey: "quota-secret",
1467 enabled: true,
1468 },
1469 },
1470 easDeviceHosts: [
1471 {
1472 kind: "eas",
1473 id: "eas",
1474 label: "Expo Simulators",
1475 accessToken: "expo-secret",
1476 maxSessionMinutes: 30,
1477 idleMinutes: 10,
1478 maxConcurrentSessions: 2,
1479 },
1480 ],
1481 });
1482 const values = [
1483 "config-secret",
1484 "env-secret",
1485 "github-secret",
1486 "bitbucket-secret",
1487 "gitcafe-secret",
1488 "quota-secret",
1489 "expo-secret",
1490 ];
1491 const client = ServerSettingsModule.redactServerSettingsForClient(saved, {
1492 secretReferences: true,
1493 });
1494 const disk = yield* fs.readFileString(config.settingsPath);
1495 for (const value of values) {
1496 assert.include(JSON.stringify(saved), value);
1497 assert.notInclude(JSON.stringify(client), value);
1498 assert.notInclude(disk, value);
1499 }
1500 assert.include(JSON.stringify(client), "https://example.test");
1501 assert.include(JSON.stringify(client), "me@example.test");
1502 const echoed = yield* service.updateSettings({
1503 providerInstances: client.providerInstances,
1504 sourceControlHosts: client.sourceControlHosts,
1505 usageLimitSources: client.usageLimitSources,
1506 easDeviceHosts: client.easDeviceHosts,
1507 });
1508 for (const value of values) assert.include(JSON.stringify(echoed), value);
1509 const renamed = yield* service.updateProviderInstance({
1510 operation: "upsert",
1511 instanceId,
1512 instance: { ...client.providerInstances[instanceId]!, displayName: "Renamed" },
1513 });
1514 assert.propertyVal(
1515 renamed.providerInstances[instanceId]?.config,
1516 "apiKey",
1517 "config-secret",
1518 );
1519
1520 for (const apiKey of ["replacement-secret", ""]) {
1521 const changed = yield* service.updateProviderInstance({
1522 operation: "upsert",
1523 instanceId,
1524 instance: { ...client.providerInstances[instanceId]!, config: { apiKey } },
1525 });
1526 assert.propertyVal(changed.providerInstances[instanceId]?.config, "apiKey", apiKey);
1527 const redacted = ServerSettingsModule.redactServerSettingsForClient(changed, {
1528 secretReferences: true,
1529 });
1530 assert.propertyVal(
1531 redacted.providerInstances[instanceId]?.config,
1532 "apiKey",
1533 apiKey ? "••••••" : "",
1534 );
1535 }
1536
1537 yield* service.updateProviderInstance({
1538 operation: "upsert",
1539 instanceId,
1540 instance: saved.providerInstances[instanceId]!,
1541 });
1542
1543 const secretNames = [
1544 "provider-config-YW50aWdyYXZpdHlfc2VjcmV0cw-YW50aWdyYXZpdHk-YXBpS2V5",
1545 "provider-env-YW50aWdyYXZpdHlfc2VjcmV0cw-QVBJX1RPS0VO",
1546 sourceControlHostSecretName({
1547 kind: "github",
1548 field: "tokens",
1549 serverHost: "github.com",
1550 }),
1551 sourceControlHostSecretName({
1552 kind: "bitbucket",
1553 field: "accessToken",
1554 serverHost: null,
1555 }),
1556 sourceControlHostSecretName({ kind: "gitcafe", field: "token", serverHost: null }),
1557 "usage-limit-source-aHVi",
1558 ];
1559 for (const name of secretNames) {
1560 assert.isTrue(Option.isSome(yield* store.get(name)), name);
1561 }
1562 const secret = {
1563 provider: SecretProviderId.make("personal"),
1564 reference: "op://Private/Antigravity/token",
1565 };
1566 const referenced = yield* service.updateProviderInstance({
1567 operation: "upsert",
1568 instanceId,
1569 instance: {
1570 ...client.providerInstances[instanceId]!,
1571 environment: [
1572 { name: "API_TOKEN", value: secret, sensitive: true, valueRedacted: true },
1573 ],
1574 },
1575 });
1576 assert.isTrue(Option.isNone(yield* store.get(secretNames[1]!)));
1577 assert.deepEqual(
1578 ServerSettingsModule.redactServerSettingsForClient(referenced, { secretReferences: true })
1579 .providerInstances[instanceId]?.environment,
1580 [{ name: "API_TOKEN", value: secret, sensitive: true }],
1581 );
1582 yield* service.updateSettings({
1583 providerInstances: {},
1584 sourceControlHosts: {
1585 github: { tokens: {} },
1586 bitbucket: { accessToken: "" },
1587 gitcafe: { token: "" },
1588 },
1589 usageLimitSources: { [UsageLimitSourceId.make("hub")]: null },
1590 });
1591 for (const name of secretNames) {
1592 assert.isTrue(Option.isNone(yield* store.get(name)));
1593 }
1594 }).pipe(Effect.provide(layerServerSettingsWithSecrets())),
1595 );
1596
1597 it.effect("moves saved provider credentials to the secret store when settings load", () =>
1598 Effect.gen(function* () {
1599 const service = yield* ServerSettingsModule.ServerSettingsService;
1600 const config = yield* ServerConfig.ServerConfig;
1601 const fs = yield* FileSystem.FileSystem;
1602 yield* fs.writeFileString(
1603 config.settingsPath,
1604 JSON.stringify({
1605 providerInstances: {
1606 antigravity: { driver: "antigravity", config: { apiKey: "legacy-api-key" } },
1607 opencode: {
1608 driver: "opencode",
1609 config: { serverUrl: "http://127.0.0.1:4096", serverPassword: "legacy-password" },
1610 },
1611 },
1612 }),
1613 );
1614 const saved = yield* service.getSettings;
1615 const opencode = ProviderInstanceId.make("opencode");
1616 assert.propertyVal(
1617 saved.providerInstances[ProviderInstanceId.make("antigravity")]?.config,
1618 "apiKey",
1619 "legacy-api-key",
1620 );
1621 assert.propertyVal(
1622 saved.providerInstances[opencode]?.config,
1623 "serverPassword",
1624 "legacy-password",
1625 );
1626 const client = ServerSettingsModule.redactServerSettingsForClient(saved, {
1627 secretReferences: true,
1628 });
1629 for (const value of ["legacy-api-key", "legacy-password"]) {
1630 assert.notInclude(yield* fs.readFileString(config.settingsPath), value);
1631 assert.notInclude(JSON.stringify(client), value);
1632 }
1633 const clientConfig = client.providerInstances[opencode]?.config as Record<string, unknown>;
1634 const edited = yield* service.updateProviderInstance({
1635 operation: "upsert",
1636 instanceId: opencode,
1637 instance: {
1638 ...client.providerInstances[opencode]!,
1639 config: { ...clientConfig, serverUrl: "http://127.0.0.1:4097" },
1640 },
1641 });
1642 assert.deepInclude(edited.providerInstances[opencode]?.config, {
1643 serverUrl: "http://127.0.0.1:4097",
1644 serverPassword: "legacy-password",
1645 });
1646 }).pipe(Effect.provide(layerServerSettings())),
1647 );
1648
1649 it.effect(
1650 "keeps source control host secrets in the secret store and tells clients only that one is set",
1651 () =>
1652 Effect.gen(function* () {
1653 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
1654 const secrets = yield* ServerSecretStore.ServerSecretStore;
1655 const serverConfig = yield* ServerConfig.ServerConfig;
1656 const fileSystem = yield* FileSystem.FileSystem;
1657
1658 const saved = yield* serverSettings.updateSettings({
1659 sourceControlHosts: {
1660 bitbucket: { email: "me@example.com", accessToken: "bb-access" },
1661 github: { tokens: { "github.com": "ghp_dotcom", "ghe.acme.test": "ghp_ghe" } },
1662 },
1663 });
1664 assert.deepEqual(saved.sourceControlHosts.bitbucket, {
1665 email: "me@example.com",
1666 accessToken: "bb-access",
1667 });
1668 const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
1669 for (const secret of ["bb-access", "ghp_dotcom", "ghp_ghe"]) assert.notInclude(raw, secret);
1670 assert.include(raw, "me@example.com");
1671
1672 const forClient = ServerSettingsModule.redactServerSettingsForClient(saved, {
1673 secretReferences: true,
1674 }).sourceControlHosts;
1675 assert.equal(forClient.bitbucket?.email, "me@example.com");
1676 assert.notInclude(String(forClient.bitbucket?.accessToken), "bb-access");
1677 assert.isAbove(String(forClient.bitbucket?.accessToken).length, 0);
1678
1679 yield* serverSettings.updateSettings({ sourceControlHosts: forClient });
1680 yield* serverSettings.updateSettings({
1681 sourceControlHosts: { bitbucket: { email: "other@example.com" } },
1682 });
1683 const kept = (yield* serverSettings.getSettings).sourceControlHosts;
1684 assert.deepEqual(kept.bitbucket, { email: "other@example.com", accessToken: "bb-access" });
1685 assert.deepEqual(kept.github?.tokens, {
1686 "github.com": "ghp_dotcom",
1687 "ghe.acme.test": "ghp_ghe",
1688 });
1689
1690 const cleared = yield* serverSettings.updateSettings({
1691 sourceControlHosts: {
1692 bitbucket: { accessToken: "" },
1693 github: {
1694 tokens: {
1695 "github.com": "",
1696 "ghe.acme.test": (forClient.github!.tokens as Record<string, string>)[
1697 "ghe.acme.test"
1698 ],
1699 },
1700 },
1701 },
1702 });
1703 assert.equal(cleared.sourceControlHosts.bitbucket?.accessToken, "");
1704 const stored = (kind: string, field: string, serverHost: string | null) =>
1705 secrets.get(sourceControlHostSecretName({ kind, field, serverHost }));
1706 assert.isTrue(Option.isNone(yield* stored("bitbucket", "accessToken", null)));
1707 assert.isTrue(Option.isNone(yield* stored("github", "tokens", "github.com")));
1708 assert.isTrue(Option.isSome(yield* stored("github", "tokens", "ghe.acme.test")));
1709
1710 const reference = {
1711 provider: SecretProviderId.make("personal"),
1712 reference: "op://Private/Bitbucket/token",
1713 };
1714 const gitHubReference = {
1715 provider: SecretProviderId.make("personal"),
1716 reference: "op://Private/GitHub/token",
1717 };
1718 yield* serverSettings.updateSettings({
1719 sourceControlHosts: {
1720 bitbucket: { accessToken: "bb-access" },
1721 github: { tokens: { "github.com": "ghp_dotcom", "ghe.acme.test": "ghp_ghe" } },
1722 },
1723 });
1724 assert.isTrue(Option.isSome(yield* stored("bitbucket", "accessToken", null)));
1725 assert.isTrue(Option.isSome(yield* stored("github", "tokens", "github.com")));
1726 const referenced = yield* serverSettings.updateSettings({
1727 sourceControlHosts: {
1728 bitbucket: { accessToken: reference },
1729 github: { tokens: { "github.com": gitHubReference, "ghe.acme.test": "ghp_ghe" } },
1730 },
1731 });
1732 assert.deepEqual(referenced.sourceControlHosts.bitbucket?.accessToken, reference);
1733 assert.isTrue(Option.isNone(yield* stored("bitbucket", "accessToken", null)));
1734 assert.isTrue(Option.isNone(yield* stored("github", "tokens", "github.com")));
1735 assert.isTrue(Option.isSome(yield* stored("github", "tokens", "ghe.acme.test")));
1736 const redacted = ServerSettingsModule.redactServerSettingsForClient(referenced, {
1737 secretReferences: true,
1738 }).sourceControlHosts;
1739 assert.deepEqual(redacted.bitbucket?.accessToken, reference);
1740 const tokens = redacted.github?.tokens as Record<string, unknown>;
1741 assert.deepEqual(tokens["github.com"], gitHubReference);
1742 assert.notEqual(tokens["ghe.acme.test"], "ghp_ghe");
1743
1744 // A client that cannot decode references sees saved secrets and can send them back.
1745 const usageReference = {
1746 provider: SecretProviderId.make("personal"),
1747 reference: "op://Private/Hub/key",
1748 };
1749 const easReference = {
1750 provider: SecretProviderId.make("personal"),
1751 reference: "op://Private/Expo/token",
1752 };
1753 const simlockReference = {
1754 provider: SecretProviderId.make("personal"),
1755 reference: "op://Private/Simlock/token",
1756 };
1757 const antigravityReference = {
1758 provider: SecretProviderId.make("personal"),
1759 reference: "op://Private/Gemini/key",
1760 };
1761 const openCodeReference = {
1762 provider: SecretProviderId.make("personal"),
1763 reference: "op://Private/OpenCode/password",
1764 };
1765 const antigravity = ProviderInstanceId.make("antigravity");
1766 const openCode = ProviderInstanceId.make("opencode");
1767 const hub = UsageLimitSourceId.make("hub");
1768 const router = ProviderInstanceId.make("openrouter");
1769 const withUsage = yield* serverSettings.updateSettings({
1770 cloudSpeechCredentials: { openai: usageReference, xai: "literal-fixture" },
1771 textGenerators: {
1772 [router]: {
1773 kind: "openaiCompatible",
1774 baseUrl: "https://openrouter.ai/api/v1",
1775 apiKey: usageReference,
1776 enabled: true,
1777 },
1778 },
1779 usageLimitSources: {
1780 [hub]: {
1781 kind: "cliproxy",
1782 url: "https://hub.test",
1783 managementKey: usageReference,
1784 enabled: true,
1785 },
1786 },
1787 easDeviceHosts: [
1788 {
1789 kind: "eas",
1790 id: "eas",
1791 label: "Expo Simulators",
1792 accessToken: easReference,
1793 maxSessionMinutes: 30,
1794 idleMinutes: 10,
1795 maxConcurrentSessions: 2,
1796 },
1797 ],
1798 simlockDeviceHosts: [
1799 {
1800 kind: "simlock",
1801 id: "pool",
1802 label: "Device pool",
1803 gatewayUrl: "https://simlock.test:4700",
1804 agentToken: simlockReference,
1805 maxLeases: 2,
1806 maxLeaseMinutes: 60,
1807 },
1808 ],
1809 providerInstances: {
1810 [antigravity]: {
1811 driver: ProviderDriverKind.make("antigravity"),
1812 config: { authMethod: "gemini-api-key", apiKey: antigravityReference },
1813 },
1814 [openCode]: {
1815 driver: ProviderDriverKind.make("opencode"),
1816 config: { serverUrl: "http://127.0.0.1:4096", serverPassword: openCodeReference },
1817 },
1818 },
1819 });
1820 const legacy = ServerSettingsModule.redactServerSettingsForClient(withUsage, {
1821 secretReferences: false,
1822 });
1823 assert.notInclude(JSON.stringify(legacy), "op://");
1824 assert.deepEqual(legacy.cloudSpeechCredentials, {
1825 openai: SECRET_REDACTED,
1826 xai: SECRET_REDACTED,
1827 openrouter: "",
1828 });
1829 assert.equal(legacy.sourceControlHosts.bitbucket?.accessToken, SECRET_REDACTED);
1830 assert.equal(legacy.usageLimitSources[hub]?.managementKey, SECRET_REDACTED);
1831 assert.equal(legacy.textGenerators[router]?.apiKey, SECRET_REDACTED);
1832 assert.equal(legacy.easDeviceHosts[0]?.accessToken, SECRET_REDACTED);
1833 assert.equal(legacy.simlockDeviceHosts[0]?.agentToken, SECRET_REDACTED);
1834 const configOf = (settings: ServerSettings, id: ProviderInstanceId) =>
1835 settings.providerInstances[id]?.config as Record<string, unknown> | undefined;
1836 assert.equal(configOf(legacy, antigravity)?.apiKey, SECRET_REDACTED);
1837 assert.equal(configOf(legacy, openCode)?.serverPassword, SECRET_REDACTED);
1838 const echoed = yield* serverSettings.updateSettings({
1839 cloudSpeechCredentials: legacy.cloudSpeechCredentials,
1840 sourceControlHosts: legacy.sourceControlHosts,
1841 usageLimitSources: legacy.usageLimitSources,
1842 textGenerators: legacy.textGenerators,
1843 easDeviceHosts: legacy.easDeviceHosts,
1844 simlockDeviceHosts: legacy.simlockDeviceHosts,
1845 providerInstances: legacy.providerInstances,
1846 });
1847 assert.deepEqual(echoed.sourceControlHosts.bitbucket?.accessToken, reference);
1848 assert.deepEqual(echoed.sourceControlHosts.github?.tokens, {
1849 "github.com": gitHubReference,
1850 "ghe.acme.test": "ghp_ghe",
1851 });
1852 assert.deepEqual(echoed.usageLimitSources[hub]?.managementKey, usageReference);
1853 assert.deepEqual(echoed.textGenerators[router]?.apiKey, usageReference);
1854 assert.deepEqual(echoed.cloudSpeechCredentials, {
1855 openai: usageReference,
1856 xai: "literal-fixture",
1857 openrouter: "",
1858 });
1859 assert.deepEqual(echoed.easDeviceHosts[0]?.accessToken, easReference);
1860 assert.deepEqual(echoed.simlockDeviceHosts[0]?.agentToken, simlockReference);
1861 assert.deepEqual(configOf(echoed, antigravity)?.apiKey, antigravityReference);
1862 assert.deepEqual(configOf(echoed, openCode)?.serverPassword, openCodeReference);
1863 assert.isTrue(Option.isSome(yield* stored("github", "tokens", "ghe.acme.test")));
1864 // A saved token goes only to the gateway it was saved for, however it is echoed.
1865 const moved = (agentToken: SimlockDeviceHostConfig["agentToken"]) =>
1866 serverSettings.updateSettings({
1867 simlockDeviceHosts: [
1868 {
1869 ...echoed.simlockDeviceHosts[0]!,
1870 gatewayUrl: "https://elsewhere.test",
1871 agentToken,
1872 },
1873 ],
1874 });
1875 assert.equal((yield* moved(SECRET_REDACTED)).simlockDeviceHosts[0]?.agentToken, "");
1876 yield* serverSettings.updateSettings({ simlockDeviceHosts: echoed.simlockDeviceHosts });
1877 assert.equal((yield* moved(simlockReference)).simlockDeviceHosts[0]?.agentToken, "");
1878 assert.equal(
1879 (yield* moved("typed-token")).simlockDeviceHosts[0]?.agentToken,
1880 "typed-token",
1881 );
1882 }).pipe(Effect.provide(layerServerSettingsWithSecrets())),
1883 );
1884
1885 it.effect("removing a secret provider unsets every field that read from it", () =>
1886 Effect.gen(function* () {
1887 const service = yield* ServerSettingsModule.ServerSettingsService;
1888 const personal = (reference: string) => ({
1889 provider: SecretProviderId.make("personal"),
1890 reference: `op://Private/${reference}`,
1891 });
1892 const work = { provider: SecretProviderId.make("work"), reference: "op://Work/token" };
1893 const instanceId = ProviderInstanceId.make("antigravity_refs");
1894 const hub = UsageLimitSourceId.make("hub");
1895 yield* decodeServerSettingsPatch({
1896 secretProviders: {
1897 personal: { kind: "one_password", label: "Personal", config: { account: "my" } },
1898 work: { kind: "one_password", label: "Work", config: { account: "work" } },
1899 },
1900 }).pipe(Effect.flatMap(service.updateSettings));
1901 yield* service.updateSettings({
1902 providerInstances: {
1903 [instanceId]: {
1904 driver: ProviderDriverKind.make("antigravity"),
1905 environment: [
1906 { name: "API_TOKEN", value: personal("Antigravity/env"), sensitive: true },
1907 { name: "WORK_TOKEN", value: work, sensitive: true },
1908 { name: "PLAIN", value: "kept", sensitive: false },
1909 ],
1910 },
1911 },
1912 sourceControlHosts: {
1913 bitbucket: { accessToken: personal("Bitbucket/token") },
1914 github: { tokens: { "github.com": personal("GitHub/token"), "ghe.acme.test": work } },
1915 },
1916 cloudSpeechCredentials: { openai: personal("Voice/key"), xai: work },
1917 usageLimitSources: {
1918 [hub]: {
1919 kind: "cliproxy",
1920 url: "https://hub.test",
1921 managementKey: personal("Hub/key"),
1922 enabled: true,
1923 },
1924 },
1925 easDeviceHosts: [
1926 {
1927 kind: "eas",
1928 id: "eas",
1929 label: "Expo Simulators",
1930 accessToken: personal("Expo/token"),
1931 maxSessionMinutes: 30,
1932 idleMinutes: 10,
1933 maxConcurrentSessions: 2,
1934 },
1935 ],
1936 });
1937
1938 // An older client's save echoes a reference it cannot decode as the redacted marker.
1939 const removed = yield* service.updateSettings({
1940 secretProviders: { [SecretProviderId.make("personal")]: null },
1941 usageLimitSources: {
1942 [hub]: {
1943 kind: "cliproxy",
1944 url: "https://hub.test",
1945 managementKey: SECRET_REDACTED,
1946 enabled: true,
1947 },
1948 },
1949 });
1950 assert.notInclude(JSON.stringify(removed), "op://Private");
1951 assert.deepEqual(removed.providerInstances[instanceId]?.environment, [
1952 { name: "WORK_TOKEN", value: work, sensitive: true },
1953 { name: "PLAIN", value: "kept", sensitive: false },
1954 ]);
1955 assert.equal(removed.sourceControlHosts.bitbucket?.accessToken, "");
1956 assert.deepEqual(removed.sourceControlHosts.github?.tokens, {
1957 "github.com": "",
1958 "ghe.acme.test": work,
1959 });
1960 assert.equal(removed.usageLimitSources[hub]?.managementKey, "");
1961 assert.deepEqual(removed.cloudSpeechCredentials, { openai: "", xai: work, openrouter: "" });
1962 assert.equal(removed.easDeviceHosts[0]?.accessToken, "");
1963 assert.deepEqual(Object.keys(removed.secretProviders), ["work"]);
1964 }).pipe(Effect.provide(layerServerSettingsWithSecrets())),
1965 );
1966
1967 it.effect("knows every strictly decoded field that can hold a secret reference", () =>
1968 Effect.sync(() => {
1969 // Shipped clients decode these as strings. Each must be covered by the older-client case above.
1970 assert.deepEqual(strictSecretReferencePaths(ServerSettings.ast), [
1971 "cloudSpeechCredentials.openai",
1972 "cloudSpeechCredentials.xai",
1973 "cloudSpeechCredentials.openrouter",
1974 "easDeviceHosts.[].accessToken",
1975 "simlockDeviceHosts.[].agentToken",
1976 "usageLimitSources.*.managementKey",
1977 "textGenerators.*.apiKey",
1978 ]);
1979 }),
1980 );
1981
1982 it.effect("keeps the retired keys for another load when a token cannot be copied", () => {
1983 const cause = new ServerSecretStore.SecretStoreReadError({
1984 resource: "bitbucket-access-token",
1985 cause: PlatformError.systemError({
1986 _tag: "PermissionDenied",
1987 module: "FileSystem",
1988 method: "readFile",
1989 pathOrDescriptor: "bitbucket-access-token",
1990 description: "Secret backend unavailable.",
1991 }),
1992 });
1993 const layerSettings = ServerSettingsModule.layer.pipe(
1994 Layer.provide(ManagedPolicy.layerTest()),
1995 Layer.provide(layerFailingSecretStore(cause)),
1996 Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
1997 Layer.provideMerge(
1998 Layer.fresh(
1999 ServerConfig.layerTest(process.cwd(), {
2000 prefix: "t3code-server-settings-legacy-failure-test-",
2001 }),
2002 ),
2003 ),
2004 );
2005 return Effect.gen(function* () {
2006 const serverConfig = yield* ServerConfig.ServerConfig;
2007 const fileSystem = yield* FileSystem.FileSystem;
2008 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
2009 const legacy = JSON.stringify({
2010 bitbucket: { email: "me@example.com", accessToken: "\u2022\u2022\u2022\u2022\u2022\u2022" },
2011 });
2012 yield* fileSystem.writeFileString(serverConfig.settingsPath, legacy);
2013
2014 yield* Effect.exit(serverSettings.getSettings);
2015
2016 assert.equal(yield* fileSystem.readFileString(serverConfig.settingsPath), legacy);
2017 }).pipe(Effect.provide(layerSettings));
2018 });
2019
2020 it.effect("moves the retired bitbucket and github keys and their secrets on load", () =>
2021 Effect.gen(function* () {
2022 const serverConfig = yield* ServerConfig.ServerConfig;
2023 const fileSystem = yield* FileSystem.FileSystem;
2024 const secrets = yield* ServerSecretStore.ServerSecretStore;
2025 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
2026 const marker = "\u2022\u2022\u2022\u2022\u2022\u2022";
2027 yield* secrets.set("bitbucket-access-token", new TextEncoder().encode("bb-saved"));
2028 yield* secrets.set(
2029 `github-token-${Buffer.from("github.com", "utf8").toString("base64url")}`,
2030 new TextEncoder().encode("ghp_saved"),
2031 );
2032 yield* fileSystem.writeFileString(
2033 serverConfig.settingsPath,
2034 JSON.stringify({
2035 bitbucket: { email: "me@example.com", accessToken: marker },
2036 github: {
2037 hosts: { "github.com": { account: "work" } },
2038 tokens: { "github.com": marker },
2039 },
2040 }),
2041 );
2042
2043 const loaded = (yield* serverSettings.getSettings).sourceControlHosts;
2044
2045 assert.deepEqual(loaded.bitbucket, { email: "me@example.com", accessToken: "bb-saved" });
2046 assert.deepEqual(loaded.github?.tokens, { "github.com": "ghp_saved" });
2047 assert.deepEqual(loaded.github?.hosts, { "github.com": { account: "work" } });
2048 const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
2049 assert.notInclude(raw, '"bitbucket":{"email"');
2050 assert.include(raw, "sourceControlHosts");
2051 assert.isTrue(Option.isNone(yield* secrets.get("bitbucket-access-token")));
2052 }).pipe(Effect.provide(layerServerSettingsWithSecrets())),
2053 );
2054
2055 it.effect(
2056 "moves a hand-edited source control token into the secret store when settings load",
2057 () =>
2058 Effect.gen(function* () {
2059 const serverConfig = yield* ServerConfig.ServerConfig;
2060 const fileSystem = yield* FileSystem.FileSystem;
2061 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
2062 yield* fileSystem.writeFileString(
2063 serverConfig.settingsPath,
2064 '{"sourceControlHosts":{"bitbucket":{"accessToken":"hand-edited-token"}}}',
2065 );
2066
2067 const loaded = yield* serverSettings.getSettings;
2068
2069 assert.equal(loaded.sourceControlHosts.bitbucket?.accessToken, "hand-edited-token");
2070 assert.notInclude(
2071 yield* fileSystem.readFileString(serverConfig.settingsPath),
2072 "hand-edited-token",
2073 );
2074 }).pipe(Effect.provide(layerServerSettingsWithSecrets())),
2075 );
2076
2077 it.effect("materializes provider secrets for terminal environment resolution", () =>
2078 Effect.gen(function* () {
2079 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
2080 const serverConfig = yield* ServerConfig.ServerConfig;
2081 const fileSystem = yield* FileSystem.FileSystem;
2082 const path = yield* Path.Path;
2083 const instanceId = ProviderInstanceId.make("codex_terminal");
2084
2085 yield* serverSettings.updateSettings({
2086 providerInstances: {
2087 [instanceId]: {
2088 driver: ProviderDriverKind.make("codex"),
2089 environment: [
2090 { name: "OPENROUTER_API_KEY", value: "sk-terminal-secret", sensitive: true },
2091 ],
2092 config: { homePath: "~/.codex-terminal" },
2093 },
2094 },
2095 });
2096
2097 const environment = yield* resolveProviderInstanceTerminalEnvironment({
2098 deriveProviderInstanceConfigMap,
2099 serverSettings,
2100 path,
2101 rawProviderInstanceId: instanceId,
2102 env: undefined,
2103 });
2104 const persisted = yield* fileSystem.readFileString(serverConfig.settingsPath);
2105
2106 assert.equal(environment.OPENROUTER_API_KEY, "sk-terminal-secret");
2107 assert.match(environment.CODEX_HOME ?? "", /[\\/][.]codex-terminal$/);
2108 assert.notInclude(persisted, "sk-terminal-secret");
2109 assert.include(persisted, '"valueRedacted": true');
2110 }).pipe(Effect.provide(layerServerSettings())),
2111 );
2112 it.effect("rolls back provider secret changes when the settings file commit fails", () =>
2113 Effect.gen(function* () {
2114 const fileSystem = yield* FileSystem.FileSystem;
2115 let failRename = false;
2116 let settingsPathToFail: string | undefined;
2117 let readDuringWrite: Effect.Effect<void> = Effect.void;
2118 const writeFailure = PlatformError.systemError({
2119 _tag: "PermissionDenied",
2120 module: "FileSystem",
2121 method: "rename",
2122 description: "Forced settings write failure.",
2123 });
2124 const failingFileSystem = FileSystem.FileSystem.of({
2125 ...fileSystem,
2126 rename: (fromPath, toPath) =>
2127 failRename && toPath === settingsPathToFail
2128 ? readDuringWrite.pipe(Effect.andThen(Effect.fail(writeFailure)))
2129 : fileSystem.rename(fromPath, toPath),
2130 });
2131 const instanceId = ProviderInstanceId.make("antigravity_write_failure");
2132 const layerSettings = layerServerSettings().pipe(
2133 Layer.provideMerge(Layer.succeed(FileSystem.FileSystem, failingFileSystem)),
2134 );
2135
2136 yield* Effect.gen(function* () {
2137 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
2138 settingsPathToFail = (yield* ServerConfig.ServerConfig).settingsPath;
2139 yield* serverSettings.updateProviderInstance({
2140 operation: "upsert",
2141 instanceId,
2142 instance: {
2143 driver: ProviderDriverKind.make("antigravity"),
2144 environment: [{ name: "OPENROUTER_API_KEY", value: "sk-kept", sensitive: true }],
2145 config: { apiKey: "config-kept" },
2146 },
2147 });
2148
2149 failRename = true;
2150 readDuringWrite = Effect.ignore(serverSettings.getSettings);
2151 const failedUpdate = yield* serverSettings
2152 .updateProviderInstance({
2153 operation: "upsert",
2154 instanceId,
2155 instance: {
2156 driver: ProviderDriverKind.make("antigravity"),
2157 environment: [{ name: "OPENROUTER_API_KEY", value: "sk-new", sensitive: true }],
2158 config: { apiKey: "config-new" },
2159 },
2160 })
2161 .pipe(Effect.result);
2162 assert.equal(failedUpdate._tag, "Failure");
2163 assert.equal(
2164 (yield* serverSettings.getSettings).providerInstances[instanceId]?.environment?.[0]
2165 ?.value,
2166 "sk-kept",
2167 );
2168 assert.propertyVal(
2169 (yield* serverSettings.getSettings).providerInstances[instanceId]?.config,
2170 "apiKey",
2171 "config-kept",
2172 );
2173
2174 const failed = yield* serverSettings
2175 .updateProviderInstance({ operation: "remove", instanceId })
2176 .pipe(Effect.result);
2177 assert.equal(failed._tag, "Failure");
2178 assert.equal(
2179 (yield* serverSettings.getSettings).providerInstances[instanceId]?.environment?.[0]
2180 ?.value,
2181 "sk-kept",
2182 );
2183 assert.propertyVal(
2184 (yield* serverSettings.getSettings).providerInstances[instanceId]?.config,
2185 "apiKey",
2186 "config-kept",
2187 );
2188 }).pipe(Effect.provide(layerSettings));
2189 }),
2190 );
2191
2192 it.effect.each(["response materialization", "partially committed write"] as const)(
2193 "rolls back provider secret changes after %s fails",
2194 (failure) => {
2195 const textDecoder = new TextDecoder();
2196 const secrets = new Map<string, Uint8Array>();
2197 let rejectNewSecret = false;
2198 const layerSecretStore = Layer.succeed(
2199 ServerSecretStore.ServerSecretStore,
2200 ServerSecretStore.ServerSecretStore.of({
2201 get: (name) =>
2202 Effect.suspend(() => {
2203 const value = secrets.get(name);
2204 if (
2205 failure === "response materialization" &&
2206 rejectNewSecret &&
2207 value !== undefined &&
2208 textDecoder.decode(value) === "sk-new"
2209 ) {
2210 return Effect.fail(
2211 new ServerSecretStore.SecretStoreReadError({
2212 resource: `secret ${name}`,
2213 cause: "Forced response materialization failure.",
2214 }),
2215 );
2216 }
2217 return Effect.succeed(
2218 value === undefined ? Option.none() : Option.some(Uint8Array.from(value)),
2219 );
2220 }),
2221 set: (name, value) =>
2222 Effect.suspend(() => {
2223 secrets.set(name, Uint8Array.from(value));
2224 return failure === "partially committed write" &&
2225 rejectNewSecret &&
2226 textDecoder.decode(value) === "sk-new"
2227 ? Effect.fail(
2228 new ServerSecretStore.SecretStorePersistError({
2229 resource: `secret ${name}`,
2230 cause: "chmod failed after rename",
2231 }),
2232 )
2233 : Effect.void;
2234 }),
2235 create: (name, value) =>
2236 Effect.sync(() => {
2237 secrets.set(name, Uint8Array.from(value));
2238 }),
2239 getOrCreateRandom: (name, bytes) =>
2240 Effect.sync(() => {
2241 const value = secrets.get(name) ?? new Uint8Array(bytes);
2242 secrets.set(name, value);
2243 return Uint8Array.from(value);
2244 }),
2245 remove: (name) =>
2246 Effect.sync(() => {
2247 secrets.delete(name);
2248 }),
2249 }),
2250 );
2251 const layerSettings = ServerSettingsModule.layer.pipe(
2252 Layer.provide(ManagedPolicy.layerTest()),
2253 Layer.provide(ManagedPolicy.layerTest()),
2254 Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
2255 Layer.provide(layerSecretStore),
2256 Layer.provideMerge(
2257 Layer.fresh(
2258 ServerConfig.layerTest(process.cwd(), {
2259 prefix: "t3code-server-settings-materialization-failure-test-",
2260 }),
2261 ),
2262 ),
2263 );
2264 const instanceId = ProviderInstanceId.make("codex_materialization_failure");
2265
2266 return Effect.gen(function* () {
2267 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
2268 yield* serverSettings.updateSettings({
2269 providerInstances: {
2270 [instanceId]: {
2271 driver: ProviderDriverKind.make("antigravity"),
2272 environment: [{ name: "OPENROUTER_API_KEY", value: "sk-kept", sensitive: true }],
2273 config: { apiKey: "config-kept" },
2274 },
2275 },
2276 });
2277
2278 rejectNewSecret = true;
2279 const failedUpdate = yield* serverSettings
2280 .updateSettings({
2281 providerInstances: {
2282 [instanceId]: {
2283 driver: ProviderDriverKind.make("antigravity"),
2284 environment: [{ name: "OPENROUTER_API_KEY", value: "sk-new", sensitive: true }],
2285 config: { apiKey: "config-new" },
2286 },
2287 },
2288 })
2289 .pipe(Effect.result);
2290
2291 assert.equal(failedUpdate._tag, "Failure");
2292 rejectNewSecret = false;
2293 assert.equal(
2294 (yield* serverSettings.getSettings).providerInstances[instanceId]?.environment?.[0]
2295 ?.value,
2296 "sk-kept",
2297 );
2298 assert.propertyVal(
2299 (yield* serverSettings.getSettings).providerInstances[instanceId]?.config,
2300 "apiKey",
2301 "config-kept",
2302 );
2303 }).pipe(Effect.provide(layerSettings));
2304 },
2305 );
2306
2307 it.effect("folds legacy project overrides into projectSettingsOverrides once", () =>
2308 Effect.gen(function* () {
2309 const serverConfig = yield* ServerConfig.ServerConfig;
2310 const fileSystem = yield* FileSystem.FileSystem;
2311 const sql = yield* SqlClient.SqlClient;
2312 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
2313 const legacyProject = ProjectId.make("project-legacy");
2314 const scriptedProject = ProjectId.make("project-scripted");
2315 const script: ProjectScript = {
2316 id: "check",
2317 name: "Check",
2318 command: "npm test",
2319 icon: "play",
2320 runOnWorktreeCreate: false,
2321 };
2322 const model = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.5");
2323 const encodeModelSelection = Schema.encodeEffect(Schema.fromJsonString(ModelSelection));
2324
2325 const modelJson = yield* encodeModelSelection(model);
2326 const encodeProjectScripts = Schema.encodeEffect(
2327 Schema.fromJsonString(Schema.Array(ProjectScript)),
2328 );
2329
2330 const scriptsJson = yield* encodeProjectScripts([script]);
2331 for (const [projectId, modelColumn, envMode, autoPull, scripts] of [
2332 [legacyProject, modelJson, "worktree", 1, scriptsJson],
2333 [scriptedProject, null, null, 0, scriptsJson],
2334 ] as const) {
2335 yield* sql`
2336 INSERT INTO projection_projects (
2337 project_id, title, workspace_root, default_model_selection_json,
2338 default_thread_env_mode, auto_pull, scripts_json, created_at, updated_at
2339 )
2340 VALUES (
2341 ${projectId}, ${"Project"}, ${`/tmp/${projectId}`}, ${modelColumn},
2342 ${envMode}, ${autoPull}, ${scripts},
2343 ${"2026-08-25T00:00:00.000Z"}, ${"2026-08-25T00:00:00.000Z"}
2344 )
2345 `;
2346 }
2347 yield* fileSystem.writeFileString(
2348 serverConfig.settingsPath,
2349 `{"projectAgentBrowserAccessOverrides":{"${legacyProject}":false},"projectAutoPullOverrides":{"${scriptedProject}":true},"projectScriptOverrides":{"${legacyProject}":null}}`,
2350 );
2351
2352 const settings = yield* serverSettings.getSettings;
2353 assert.isTrue(settings.projectSettingsFolded);
2354 assert.deepEqual<ServerSettings["projectSettingsOverrides"]>(
2355 settings.projectSettingsOverrides,
2356 {
2357 [legacyProject]: {
2358 enableAgentBrowserAccess: false,
2359 defaultModelSelection: model,
2360 defaultThreadEnvMode: "worktree",
2361 defaultAutoPull: true,
2362 },
2363 [scriptedProject]: { defaultAutoPull: true, defaultProjectScripts: [script] },
2364 },
2365 );
2366
2367 assert.deepEqual<ServerSettings["projectAutoPullOverrides"]>(
2368 settings.projectAutoPullOverrides,
2369 {
2370 [legacyProject]: true,
2371 [scriptedProject]: true,
2372 },
2373 );
2374 assert.deepEqual<ServerSettings["projectScriptOverrides"]>(settings.projectScriptOverrides, {
2375 [scriptedProject]: [script],
2376 });
2377
2378 yield* serverSettings.updateSettings({
2379 projectSettingsOverrides: { [legacyProject]: null },
2380 });
2381 const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
2382 const persisted = yield* decodeServerSettings(JSON.parse(raw));
2383 assert.isTrue(persisted.projectSettingsFolded);
2384 assert.isUndefined(persisted.projectSettingsOverrides[legacyProject]);
2385 }).pipe(Effect.provide(layerServerSettings())),
2386 );
2387
2388 it.effect.each([
2389 { label: "malformed JSON", broken: '{"defaultAutoPull": tru' },
2390 { label: "invalid retention", broken: '{"usageHistoryRetentionDays": 0}' },
2391 ])("leaves settings.json with $label untouched and disables destructive defaults", ({ broken }) =>
2392 Effect.gen(function* () {
2393 const serverConfig = yield* ServerConfig.ServerConfig;
2394 const fileSystem = yield* FileSystem.FileSystem;
2395 const sql = yield* SqlClient.SqlClient;
2396 const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
2397 yield* sql`
2398 INSERT INTO projection_projects (
2399 project_id, title, workspace_root, auto_pull, scripts_json, created_at, updated_at
2400 )
2401 VALUES (
2402 ${"project-broken"}, ${"Project"}, ${"/tmp/project-broken"}, ${1}, ${"[]"},
2403 ${"2026-08-25T00:00:00.000Z"}, ${"2026-08-25T00:00:00.000Z"}
2404 )
2405 `;
2406 yield* fileSystem.writeFileString(serverConfig.settingsPath, broken);
2407
2408 const settings = yield* serverSettings.getSettings;
2409 assert.isFalse(settings.projectSettingsFolded);
2410 assert.isFalse(settings.continueThreadsAfterServerUpdate);
2411 assert.equal(settings.usageHistoryRetentionDays, "unlimited");
2412 assert.deepEqual(settings.projectSettingsOverrides, {});
2413
2414 assert.equal(yield* fileSystem.readFileString(serverConfig.settingsPath), broken);
2415 }).pipe(Effect.provide(layerServerSettings())),
2416 );
2417 });
2418
2419 it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))(
2420 "server settings under a managed policy",
2421 (it) => {
2422 const policy: ManagedPolicyDocument = {
2423 schemaVersion: 1,
2424 organization: "Example Corp",
2425 settings: {
2426 defaultRuntimeMode: { value: "approval-required", locked: false },
2427 enableAgentDeviceAccess: { value: false, locked: true },
2428 },
2429 };
2430
2431 it.effect("uses policy defaults until the user picks something else", () =>
2432 Effect.gen(function* () {
2433 const service = yield* ServerSettingsModule.ServerSettingsService;
2434 const config = yield* ServerConfig.ServerConfig;
2435 const fs = yield* FileSystem.FileSystem;
2436
2437 assert.equal((yield* service.getSettings).defaultRuntimeMode, "approval-required");
2438
2439 // The built-in default differs from the policy's, so choosing it must persist.
2440 yield* service.updateSettings({ defaultRuntimeMode: "full-access" });
2441 assert.equal((yield* service.getSettings).defaultRuntimeMode, "full-access");
2442 assert.include(yield* fs.readFileString(config.settingsPath), '"full-access"');
2443
2444 // Choosing the policy's value leaves nothing in the file to outlive the policy.
2445 yield* service.updateSettings({ defaultRuntimeMode: "approval-required" });
2446 assert.notInclude(yield* fs.readFileString(config.settingsPath), "defaultRuntimeMode");
2447 }).pipe(Effect.provide(layerServerSettings(policy))),
2448 );
2449
2450 it.effect("keeps a stored value that equals a policy default through unrelated writes", () =>
2451 Effect.gen(function* () {
2452 const service = yield* ServerSettingsModule.ServerSettingsService;
2453 const config = yield* ServerConfig.ServerConfig;
2454 const fs = yield* FileSystem.FileSystem;
2455 yield* fs.writeFileString(
2456 config.settingsPath,
2457 JSON.stringify({ defaultRuntimeMode: "approval-required" }),
2458 );
2459
2460 yield* service.updateSettings({ defaultAutoPull: true });
2461 assert.include(yield* fs.readFileString(config.settingsPath), '"approval-required"');
2462 }).pipe(Effect.provide(layerServerSettings(policy))),
2463 );
2464
2465 it.effect("keeps stored values under whole-object policy defaults, and only the user's", () =>
2466 Effect.gen(function* () {
2467 const service = yield* ServerSettingsModule.ServerSettingsService;
2468 const config = yield* ServerConfig.ServerConfig;
2469 const fs = yield* FileSystem.FileSystem;
2470 const selection = {
2471 ...DEFAULT_SERVER_SETTINGS.textGenerationModelSelection,
2472 model: "managed",
2473 };
2474 const chosenModel = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-mini" };
2475 yield* fs.writeFileString(
2476 config.settingsPath,
2477 JSON.stringify({
2478 storageCleanup: { logsAfterDays: 30, browserArtifactsAfterDays: 7 },
2479 textGenerationModelSelection: selection,
2480 }),
2481 );
2482
2483 // Picking another model on the policy's instance differs from the policy in one field only.
2484 yield* service.updateSettings({
2485 defaultAutoPull: true,
2486 defaultModelSelection: chosenModel,
2487 });
2488 const stored = JSON.parse(yield* fs.readFileString(config.settingsPath));
2489 assert.deepEqual(stored.storageCleanup, {
2490 logsAfterDays: 30,
2491 browserArtifactsAfterDays: 7,
2492 });
2493 // Model selections are saved whole, never as the fields that differ from the policy's.
2494 assert.deepEqual(stored.textGenerationModelSelection, selection);
2495 assert.deepEqual(stored.defaultModelSelection, chosenModel);
2496 // The switch the server derives from the policy's idle compaction stays out of the file.
2497 assert.notProperty(stored, "compactIdleThreads");
2498 }).pipe(
2499 Effect.provide(
2500 layerServerSettings({
2501 schemaVersion: 1,
2502 organization: "Example Corp",
2503 settings: {
2504 storageCleanup: {
2505 value: { ...DEFAULT_SERVER_SETTINGS.storageCleanup, logsAfterDays: 30 },
2506 locked: false,
2507 },
2508 "textGenerationModelSelection.model": { value: "managed", locked: false },
2509 defaultModelSelection: {
2510 value: { instanceId: "codex", model: "gpt-managed" },
2511 locked: false,
2512 },
2513 idleCompaction: { value: "beforeCacheExpires", locked: false },
2514 },
2515 }),
2516 ),
2517 ),
2518 );
2519
2520 it.effect(
2521 "keeps an idle compaction choice saved before idleCompaction over a policy default",
2522 () =>
2523 // The file holds only the legacy switch: off differs from the policy's default, on matches it.
2524 Effect.forEach([false, true], (compactIdleThreads) =>
2525 Effect.gen(function* () {
2526 const service = yield* ServerSettingsModule.ServerSettingsService;
2527 const config = yield* ServerConfig.ServerConfig;
2528 const fs = yield* FileSystem.FileSystem;
2529 const chosen = compactIdleThreads ? "beforeCacheExpires" : "onReturn";
2530 yield* fs.writeFileString(config.settingsPath, JSON.stringify({ compactIdleThreads }));
2531
2532 assert.equal((yield* service.getSettings).idleCompaction, chosen);
2533 yield* service.updateSettings({ defaultAutoPull: true });
2534 // What applies once the policy is gone is still the user's choice.
2535 const stored = JSON.parse(yield* fs.readFileString(config.settingsPath));
2536 assert.equal(globalIdleCompaction(stored), chosen);
2537 }).pipe(
2538 Effect.provide(
2539 layerServerSettings({
2540 schemaVersion: 1,
2541 organization: "Example Corp",
2542 settings: { idleCompaction: { value: "beforeCacheExpires", locked: false } },
2543 }),
2544 ),
2545 ),
2546 ),
2547 );
2548
2549 it.effect("lays locks over the user's own and per-project values without persisting them", () =>
2550 Effect.gen(function* () {
2551 const service = yield* ServerSettingsModule.ServerSettingsService;
2552 const config = yield* ServerConfig.ServerConfig;
2553 const fs = yield* FileSystem.FileSystem;
2554 const projectId = ProjectId.make("project-locked");
2555 yield* fs.writeFileString(
2556 config.settingsPath,
2557 JSON.stringify({
2558 enableAgentDeviceAccess: true,
2559 projectSettingsOverrides: { [projectId]: { enableAgentDeviceAccess: true } },
2560 }),
2561 );
2562
2563 const settings = yield* service.getSettings;
2564 assert.isFalse(settings.enableAgentDeviceAccess);
2565 assert.isFalse(settings.projectSettingsOverrides[projectId]?.enableAgentDeviceAccess);
2566 assert.deepEqual(service.managedPolicy, {
2567 organization: "Example Corp",
2568 lockedSettings: ["enableAgentDeviceAccess"],
2569 });
2570
2571 const rejected = yield* service
2572 .updateSettings({ enableAgentDeviceAccess: true, defaultAutoPull: true })
2573 .pipe(Effect.flip);
2574 assert.equal(rejected.operation, "write-managed-setting");
2575 assert.equal(rejected.managedSetting, "enableAgentDeviceAccess");
2576 assert.equal(
2577 rejected.message,
2578 "enableAgentDeviceAccess is managed by Example Corp and cannot be changed.",
2579 );
2580 assert.isFalse((yield* service.getSettings).defaultAutoPull);
2581
2582 const projectRejected = yield* service
2583 .updateSettings({
2584 projectSettingsOverrides: { [projectId]: { enableAgentDeviceAccess: true } },
2585 })
2586 .pipe(Effect.flip);
2587 assert.equal(projectRejected.managedSetting, "enableAgentDeviceAccess");
2588
2589 // Unrelated writes, and writes that keep the locked value, go through.
2590 yield* service.updateSettings({ enableAgentDeviceAccess: false, defaultAutoPull: true });
2591 assert.isTrue((yield* service.getSettings).defaultAutoPull);
2592
2593 // The user's own value stays on disk, ready for when the policy is removed.
2594 const stored = JSON.parse(yield* fs.readFileString(config.settingsPath));
2595 assert.isTrue(stored.enableAgentDeviceAccess);
2596 }).pipe(Effect.provide(layerServerSettings(policy))),
2597 );
2598 it.effect("accepts a project override that brings the locked value inside a new setting", () =>
2599 Effect.gen(function* () {
2600 const service = yield* ServerSettingsModule.ServerSettingsService;
2601 const projectId = ProjectId.make("project-text-generation");
2602 const selection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-locked" };
2603
2604 yield* service.updateSettings({
2605 projectSettingsOverrides: { [projectId]: { textGenerationModelSelection: selection } },
2606 });
2607
2608 const project = (yield* service.getSettings).projectSettingsOverrides[projectId];
2609 assert.equal(project?.textGenerationModelSelection?.model, "gpt-locked");
2610 }).pipe(
2611 Effect.provide(
2612 layerServerSettings({
2613 schemaVersion: 1,
2614 organization: "Example Corp",
2615 settings: {
2616 "textGenerationModelSelection.model": { value: "gpt-locked", locked: true },
2617 },
2618 }),
2619 ),
2620 ),
2621 );
2622
2623 it.effect(
2624 "compares a project's partial override with a locked entry by the keys it holds",
2625 () =>
2626 Effect.gen(function* () {
2627 const service = yield* ServerSettingsModule.ServerSettingsService;
2628 const codexId = ProviderInstanceId.make("codex");
2629 const projectWith = (enabled: boolean) => ({
2630 projectSettingsOverrides: {
2631 [ProjectId.make("project-codex")]: { providerInstances: { [codexId]: { enabled } } },
2632 },
2633 });
2634
2635 yield* service.updateSettings(projectWith(true));
2636 const refused = yield* service.updateSettings(projectWith(false)).pipe(Effect.flip);
2637 assert.equal(refused.managedSetting, "providerInstances.codex");
2638 }).pipe(
2639 Effect.provide(
2640 layerServerSettings({
2641 schemaVersion: 1,
2642 organization: "Example Corp",
2643 settings: {
2644 "providerInstances.codex": {
2645 value: { driver: "codex", enabled: true },
2646 locked: true,
2647 },
2648 },
2649 }),
2650 ),
2651 ),
2652 );
2653
2654 it.effect("lowers default runtime modes above the ceiling without rewriting them", () =>
2655 Effect.gen(function* () {
2656 const service = yield* ServerSettingsModule.ServerSettingsService;
2657 const config = yield* ServerConfig.ServerConfig;
2658 const fs = yield* FileSystem.FileSystem;
2659 const raised = ProjectId.make("project-raised");
2660 const supervised = ProjectId.make("project-supervised");
2661 yield* fs.writeFileString(
2662 config.settingsPath,
2663 JSON.stringify({
2664 defaultRuntimeMode: "auto",
2665 projectSettingsOverrides: {
2666 [raised]: { defaultRuntimeMode: "full-access" },
2667 [supervised]: { defaultRuntimeMode: "approval-required" },
2668 },
2669 }),
2670 );
2671
2672 const settings = yield* service.getSettings;
2673 assert.equal(settings.defaultRuntimeMode, "auto-accept-edits");
2674 assert.equal(
2675 settings.projectSettingsOverrides[raised]?.defaultRuntimeMode,
2676 "auto-accept-edits",
2677 );
2678 assert.equal(
2679 settings.projectSettingsOverrides[supervised]?.defaultRuntimeMode,
2680 "approval-required",
2681 );
2682
2683 yield* service.updateSettings({ defaultAutoPull: true });
2684 const stored = JSON.parse(yield* fs.readFileString(config.settingsPath));
2685 assert.equal(stored.defaultRuntimeMode, "auto");
2686 assert.equal(stored.projectSettingsOverrides[raised].defaultRuntimeMode, "full-access");
2687 }).pipe(
2688 Effect.provide(
2689 layerServerSettings({
2690 schemaVersion: 1,
2691 organization: "Example Corp",
2692 limits: { maxRuntimeMode: "auto-accept-edits" },
2693 }),
2694 ),
2695 ),
2696 );
2697 },
2698 );
2699
2700 it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))(
2701 "server settings under a provider policy",
2702 (it) => {
2703 const claude = ProviderDriverKind.make("claudeAgent");
2704 const codex = ProviderDriverKind.make("codex");
2705 const cursor = ProviderDriverKind.make("cursor");
2706 const bedrock = { name: "CLAUDE_CODE_USE_BEDROCK", value: "1", sensitive: false };
2707 const policy: ManagedPolicyDocument = {
2708 schemaVersion: 1,
2709 organization: "Example Corp",
2710 limits: {
2711 providers: {
2712 allowedDrivers: [claude, codex],
2713 instances: {
2714 [claude]: {
2715 locked: true,
2716 environment: [{ name: bedrock.name, value: bedrock.value }],
2717 binaryPath: "/opt/claude/bin/claude",
2718 },
2719 [codex]: { locked: false, launchArgs: "-c model_provider=gateway" },
2720 },
2721 },
2722 },
2723 };
2724
2725 it.effect("refuses enabling a driver the policy leaves out, and keeps existing ones", () =>
2726 Effect.gen(function* () {
2727 const service = yield* ServerSettingsModule.ServerSettingsService;
2728 const config = yield* ServerConfig.ServerConfig;
2729 const fs = yield* FileSystem.FileSystem;
2730 const cursorId = ProviderInstanceId.make("cursor_work");
2731 yield* fs.writeFileString(
2732 config.settingsPath,
2733 JSON.stringify({
2734 providerInstances: {
2735 [cursorId]: { driver: cursor, enabled: true },
2736 // A default instance id is no proof of its driver.
2737 codex: { driver: cursor, enabled: true },
2738 },
2739 textGenerationModelSelection: { instanceId: cursorId, model: "auto" },
2740 }),
2741 );
2742
2743 const settings = yield* service.getSettings;
2744 // Never deleted: the instance stays for its threads, and the registry shows it unavailable.
2745 assert.equal(settings.providerInstances[cursorId]?.driver, cursor);
2746 // Built-in text generation does not fall back onto a disallowed driver either.
2747 assert.equal(settings.textGenerationModelSelection.instanceId, "claudeAgent");
2748
2749 const rejected = yield* service
2750 .updateProviderInstance({
2751 operation: "create",
2752 instanceId: ProviderInstanceId.make("cursor_new"),
2753 instance: { driver: cursor, enabled: true },
2754 })
2755 .pipe(Effect.flip);
2756 assert.equal(rejected.operation, "use-disallowed-provider");
2757 assert.equal(rejected.message, "Example Corp's policy does not allow the Cursor provider.");
2758 // Switching it on for one project is enabling it too.
2759 const perProject = yield* service
2760 .updateSettings({
2761 projectSettingsOverrides: {
2762 [ProjectId.make("project-a")]: {
2763 providerInstances: { [cursorId]: { enabled: true } },
2764 },
2765 },
2766 })
2767 .pipe(Effect.flip);
2768 assert.equal(perProject.operation, "use-disallowed-provider");
2769
2770 // The client echoes a default instance that was running before it was configured.
2771 yield* service.updateProviderInstance({
2772 operation: "upsert",
2773 instanceId: ProviderInstanceId.make("cursor"),
2774 instance: { driver: cursor, enabled: true },
2775 });
2776
2777 // Turning it off, or removing it, is still the user's call.
2778 yield* service.updateProviderInstance({
2779 operation: "upsert",
2780 instanceId: cursorId,
2781 instance: { driver: cursor, enabled: false },
2782 });
2783 yield* service.updateProviderInstance({ operation: "remove", instanceId: cursorId });
2784 assert.isUndefined((yield* service.getSettings).providerInstances[cursorId]);
2785 }).pipe(Effect.provide(layerServerSettings(policy))),
2786 );
2787
2788 it.effect("keeps a locked Codex pin from being bypassed by managed setup", () =>
2789 Effect.gen(function* () {
2790 const service = yield* ServerSettingsModule.ServerSettingsService;
2791 const config = yield* ServerConfig.ServerConfig;
2792 const fs = yield* FileSystem.FileSystem;
2793 const codexId = ProviderInstanceId.make("codex_chatgpt");
2794 yield* fs.writeFileString(
2795 config.settingsPath,
2796 JSON.stringify({
2797 providerInstances: { [codexId]: { driver: codex, config: { setupMode: "managed" } } },
2798 }),
2799 );
2800
2801 const effective = (yield* service.getSettings).providerInstances[codexId];
2802 assert.deepEqual(effective?.config, { binaryPath: "/opt/gateway/codex" });
2803 // A stored value stays for when the policy is gone; a new one is refused.
2804 const refused = yield* service
2805 .updateProviderInstance({
2806 operation: "upsert",
2807 instanceId: ProviderInstanceId.make("codex_new"),
2808 instance: { driver: codex, config: { setupMode: "managed" } },
2809 })
2810 .pipe(Effect.flip);
2811 assert.equal(refused.managedSetting, "providerInstances.codex_new.config.setupMode");
2812 // Adding a Codex instance sends the default setup, which leaves the pin in charge.
2813 yield* service.updateProviderInstance({
2814 operation: "upsert",
2815 instanceId: ProviderInstanceId.make("codex_cli"),
2816 instance: { driver: codex, config: { setupMode: "existing" } },
2817 });
2818 }).pipe(
2819 Effect.provide(
2820 layerServerSettings({
2821 schemaVersion: 1,
2822 organization: "Example Corp",
2823 limits: {
2824 providers: {
2825 instances: { [codex]: { locked: true, binaryPath: "/opt/gateway/codex" } },
2826 },
2827 },
2828 }),
2829 ),
2830 ),
2831 );
2832
2833 it.effect("pins instance fields at read time and refuses edits to locked ones", () =>
2834 Effect.gen(function* () {
2835 const service = yield* ServerSettingsModule.ServerSettingsService;
2836 const config = yield* ServerConfig.ServerConfig;
2837 const fs = yield* FileSystem.FileSystem;
2838 const claudeId = ProviderInstanceId.make("claudeAgent");
2839 const codexId = ProviderInstanceId.make("codex");
2840 const userVariable = { name: "MY_FLAG", value: "on", sensitive: false };
2841 yield* fs.writeFileString(
2842 config.settingsPath,
2843 JSON.stringify({
2844 providerInstances: {
2845 [claudeId]: {
2846 driver: claude,
2847 environment: [{ ...bedrock, value: "0" }, userVariable, { ...bedrock, value: "2" }],
2848 config: { binaryPath: "/usr/local/bin/claude" },
2849 },
2850 },
2851 }),
2852 );
2853
2854 const effective = yield* service.getSettings;
2855 const claudeInstance = effective.providerInstances[claudeId];
2856 assert.deepEqual(claudeInstance?.environment, [bedrock, userVariable]);
2857 assert.deepEqual(claudeInstance?.config, { binaryPath: "/opt/claude/bin/claude" });
2858 // The implicit default Codex instance gets the unlocked default too.
2859 assert.deepEqual(effective.providerInstances[codexId]?.config, {
2860 launchArgs: "-c model_provider=gateway",
2861 });
2862
2863 const lockedBinary = yield* service
2864 .updateProviderInstance({
2865 operation: "upsert",
2866 instanceId: claudeId,
2867 instance: { ...claudeInstance!, config: { binaryPath: "/tmp/claude" } },
2868 })
2869 .pipe(Effect.flip);
2870 assert.equal(lockedBinary.operation, "write-managed-setting");
2871 assert.equal(
2872 lockedBinary.managedSetting,
2873 "providerInstances.claudeAgent.config.binaryPath",
2874 );
2875 const lockedVariable = yield* service
2876 .updateProviderInstance({
2877 operation: "upsert",
2878 instanceId: claudeId,
2879 instance: { ...claudeInstance!, environment: [userVariable] },
2880 })
2881 .pipe(Effect.flip);
2882 assert.equal(
2883 lockedVariable.managedSetting,
2884 "providerInstances.claudeAgent.environment.CLAUDE_CODE_USE_BEDROCK",
2885 );
2886
2887 // Saving what the client was shown, plus an unrelated edit, goes through without baking
2888 // the policy into the file: the user's own values come back once the policy is removed.
2889 yield* service.updateProviderInstance({
2890 operation: "upsert",
2891 instanceId: claudeId,
2892 instance: { ...claudeInstance!, displayName: "Claude (work)" },
2893 });
2894 yield* service.updateProviderInstance({
2895 operation: "upsert",
2896 instanceId: codexId,
2897 instance: effective.providerInstances[codexId]!,
2898 });
2899 const stored = JSON.parse(yield* fs.readFileString(config.settingsPath));
2900 assert.deepEqual(stored.providerInstances[claudeId], {
2901 driver: claude,
2902 displayName: "Claude (work)",
2903 environment: [{ ...bedrock, value: "0" }, { ...bedrock, value: "2" }, userVariable],
2904 config: { binaryPath: "/usr/local/bin/claude" },
2905 });
2906 assert.isUndefined(stored.providerInstances[codexId]);
2907
2908 // Unlocked fields are the user's to override.
2909 yield* service.updateProviderInstance({
2910 operation: "upsert",
2911 instanceId: codexId,
2912 instance: { driver: codex, config: { launchArgs: "--mine" } },
2913 });
2914 assert.deepEqual((yield* service.getSettings).providerInstances[codexId]?.config, {
2915 launchArgs: "--mine",
2916 });
2917 }).pipe(Effect.provide(layerServerSettings(policy))),
2918 );
2919 },
2920 );
2921
2922 it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))(
2923 "server settings under a runtime mode ceiling",
2924 (it) => {
2925 const claude = ProviderDriverKind.make("claudeAgent");
2926 const acpRegistry = ProviderDriverKind.make("acpRegistry");
2927 const policy: ManagedPolicyDocument = {
2928 schemaVersion: 1,
2929 organization: "Example Corp",
2930 limits: {
2931 maxRuntimeMode: "auto-accept-edits",
2932 providers: {
2933 instances: {
2934 [claude]: {
2935 locked: false,
2936 environment: [{ name: "CLAUDE_CODE_USE_BEDROCK", value: "1" }],
2937 binaryPath: "/opt/claude/bin/claude",
2938 },
2939 },
2940 },
2941 },
2942 };
2943
2944 it.effect("keeps the secret of a variable it hides when the instance is saved", () => {
2945 const shared = ServerSecretStore.layer.pipe(
2946 Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
2947 Layer.provideMerge(
2948 Layer.fresh(ServerConfig.layerTest(process.cwd(), { prefix: "t3code-hidden-secret-" })),
2949 ),
2950 );
2951 const withPolicy = <A, E>(
2952 document: ManagedPolicyDocument | undefined,
2953 use: (
2954 service: ServerSettingsModule.ServerSettingsService["Service"],
2955 ) => Effect.Effect<A, E>,
2956 ) =>
2957 ServerSettingsModule.ServerSettingsService.pipe(
2958 Effect.flatMap(use),
2959 Effect.provide(
2960 ServerSettingsModule.layer.pipe(Layer.provide(ManagedPolicy.layerTest(document))),
2961 ),
2962 );
2963 const claudeId = ProviderInstanceId.make("claudeAgent");
2964 const token = { name: "ANTHROPIC_API_KEY", value: "sk-kept", sensitive: true };
2965 return Effect.gen(function* () {
2966 yield* withPolicy(undefined, (service) =>
2967 service.updateProviderInstance({
2968 operation: "upsert",
2969 instanceId: claudeId,
2970 instance: { driver: claude, environment: [token] },
2971 }),
2972 );
2973 // The ceiling shows only pinned variables, so the client saves without the token.
2974 yield* withPolicy(policy, (service) =>
2975 service.getSettings.pipe(
2976 Effect.flatMap((settings) =>
2977 service.updateProviderInstance({
2978 operation: "upsert",
2979 instanceId: claudeId,
2980 instance: {
2981 ...settings.providerInstances[claudeId]!,
2982 displayName: "Claude (work)",
2983 },
2984 }),
2985 ),
2986 ),
2987 );
2988 const restored = yield* withPolicy(undefined, (service) => service.getSettings);
2989 assert.equal(restored.providerInstances[claudeId]?.environment?.[0]?.value, token.value);
2990
2991 // Removing a secret provider still clears a hidden variable that read from it.
2992 const reference = {
2993 provider: SecretProviderId.make("personal"),
2994 reference: "op://Private/Anthropic/key",
2995 };
2996 yield* withPolicy(undefined, (service) =>
2997 decodeServerSettingsPatch({
2998 secretProviders: {
2999 personal: { kind: "one_password", label: "Personal", config: { account: "my" } },
3000 },
3001 }).pipe(
3002 Effect.flatMap(service.updateSettings),
3003 Effect.andThen(
3004 service.updateProviderInstance({
3005 operation: "upsert",
3006 instanceId: claudeId,
3007 instance: {
3008 driver: claude,
3009 environment: [{ name: token.name, value: reference, sensitive: true }],
3010 },
3011 }),
3012 ),
3013 ),
3014 );
3015 yield* withPolicy(policy, (service) =>
3016 service.updateSettings({ secretProviders: { [reference.provider]: null } }),
3017 );
3018 const cleared = yield* withPolicy(undefined, (service) => service.getSettings);
3019 assert.notInclude(JSON.stringify(cleared), "op://Private");
3020 }).pipe(Effect.provide(shared));
3021 });
3022
3023 it.effect("ignores stored launch configuration and refuses new values", () =>
3024 Effect.gen(function* () {
3025 const service = yield* ServerSettingsModule.ServerSettingsService;
3026 const config = yield* ServerConfig.ServerConfig;
3027 const fs = yield* FileSystem.FileSystem;
3028 const claudeId = ProviderInstanceId.make("claudeAgent");
3029 const registryId = ProviderInstanceId.make("acp_devin");
3030 const userVariable = {
3031 name: "CLAUDE_CONFIG_DIR",
3032 value: "/tmp/allow-all",
3033 sensitive: false,
3034 };
3035 const storedClaude = {
3036 driver: claude,
3037 environment: [userVariable, { ...userVariable, value: "/tmp/later-wins" }],
3038 config: {
3039 binaryPath: "/tmp/wrapper",
3040 launchArgs: "--dangerously-skip-permissions",
3041 homePath: "/tmp/allow-all",
3042 autoCompactWindow: "300000",
3043 },
3044 };
3045 yield* fs.writeFileString(
3046 config.settingsPath,
3047 JSON.stringify({
3048 providerInstances: {
3049 [claudeId]: storedClaude,
3050 [registryId]: {
3051 driver: acpRegistry,
3052 config: { agentId: "devin", commandPath: "/tmp/agent", commandArgs: ["--yolo"] },
3053 },
3054 },
3055 }),
3056 );
3057
3058 // Even an unlocked pin wins, and the user's launch values and variables are not used.
3059 const effective = yield* service.getSettings;
3060 const claudeInstance = effective.providerInstances[claudeId]!;
3061 assert.deepEqual(claudeInstance.config, {
3062 binaryPath: "/opt/claude/bin/claude",
3063 autoCompactWindow: "300000",
3064 });
3065 assert.deepEqual(claudeInstance.environment, [
3066 { name: "CLAUDE_CODE_USE_BEDROCK", value: "1", sensitive: false },
3067 ]);
3068 assert.deepEqual(effective.providerInstances[registryId]?.config, { agentId: "devin" });
3069
3070 const refused = (instance: typeof claudeInstance) =>
3071 service
3072 .updateProviderInstance({ operation: "upsert", instanceId: claudeId, instance })
3073 .pipe(Effect.flip);
3074 const launchArgs = yield* refused({
3075 ...claudeInstance,
3076 config: { ...claudeInstance.config!, launchArgs: "--permission-mode bypassPermissions" },
3077 });
3078 assert.equal(launchArgs.operation, "write-managed-setting");
3079 assert.equal(launchArgs.managedSetting, "providerInstances.claudeAgent.config.launchArgs");
3080 const binary = yield* refused({
3081 ...claudeInstance,
3082 config: { ...claudeInstance.config!, binaryPath: "/tmp/other-wrapper" },
3083 });
3084 assert.equal(binary.managedSetting, "providerInstances.claudeAgent.config.binaryPath");
3085 const environment = yield* refused({
3086 ...claudeInstance,
3087 environment: [{ name: "NODE_OPTIONS", value: "--require /tmp/x.js", sensitive: false }],
3088 });
3089 assert.equal(environment.managedSetting, "providerInstances.claudeAgent.environment");
3090 const commandArgs = yield* service
3091 .updateProviderInstance({
3092 operation: "upsert",
3093 instanceId: registryId,
3094 instance: {
3095 driver: acpRegistry,
3096 config: { agentId: "devin", commandArgs: ["--dangerously-skip-permissions"] },
3097 },
3098 })
3099 .pipe(Effect.flip);
3100 assert.equal(commandArgs.managedSetting, "providerInstances.acp_devin.config.commandArgs");
3101
3102 // Unrelated writes carry the stored instance through unchanged, duplicates included.
3103 yield* service.updateSettings({ defaultAutoPull: true });
3104
3105 // What the client was shown saves, with user-owned edits, and the stored values survive.
3106 yield* service.updateProviderInstance({
3107 operation: "upsert",
3108 instanceId: claudeId,
3109 instance: {
3110 ...claudeInstance,
3111 displayName: "Claude (work)",
3112 config: { ...claudeInstance.config!, autoCompactWindow: "400000" },
3113 },
3114 });
3115 const stored = JSON.parse(yield* fs.readFileString(config.settingsPath));
3116 assert.deepEqual(stored.providerInstances[claudeId], {
3117 ...storedClaude,
3118 displayName: "Claude (work)",
3119 config: { ...storedClaude.config, autoCompactWindow: "400000" },
3120 });
3121 }).pipe(Effect.provide(layerServerSettings(policy))),
3122 );
3123 },
3124 );
3125
3126 it.live("reloads a symlinked settings file after its target directory is replaced", () =>
3127 Effect.gen(function* () {
3128 const config = yield* ServerConfig.ServerConfig;
3129 const fs = yield* FileSystem.FileSystem;
3130 const path = yield* Path.Path;
3131 const service = yield* ServerSettingsModule.ServerSettingsService;
3132 const dotfiles = yield* fs.makeTempDirectoryScoped({ prefix: "t3-settings-dotfiles-" });
3133 const active = path.join(dotfiles, "active");
3134 const restored = path.join(dotfiles, "restored");
3135 yield* fs.makeDirectory(active);
3136 yield* fs.makeDirectory(restored);
3137 yield* fs.writeFileString(
3138 path.join(active, "settings.json"),
3139 `{ "responseStreamingMode": "turn" }`,
3140 );
3141 yield* fs.writeFileString(
3142 path.join(restored, "settings.json"),
3143 `{ "responseStreamingMode": "turn" }`,
3144 );
3145 yield* fs.remove(config.settingsPath, { force: true });
3146 yield* fs.symlink(path.join(active, "settings.json"), config.settingsPath);
3147 yield* service.start;
3148 const changes = yield* service.subscribeChanges;
3149
3150 yield* fs.writeFileString(
3151 path.join(restored, "settings.json"),
3152 `{ "responseStreamingMode": "turn", "defaultAutoPull": true }`,
3153 );
3154 yield* fs.rename(active, path.join(dotfiles, "previous"));
3155 yield* fs.rename(restored, active);
3156
3157 const restoredSettings = yield* changes.pipe(
3158 Stream.filter((settings) => settings.defaultAutoPull),
3159 Stream.runHead,
3160 );
3161 assert.isTrue(Option.isSome(restoredSettings));
3162
3163 yield* fs.writeFileString(
3164 path.join(active, "settings.json"),
3165 `{ "responseStreamingMode": "paragraph" }`,
3166 );
3167
3168 const reloaded = yield* changes.pipe(
3169 Stream.filter((settings) => settings.responseStreamingMode === "paragraph"),
3170 Stream.runHead,
3171 );
3172 assert.isTrue(Option.isSome(reloaded));
3173 }).pipe(
3174 Effect.scoped,
3175 // @effect-diagnostics-next-line multipleEffectProvide:off -- the settings layer reads the Node services provided below.
3176 Effect.provide(layerServerSettings()),
3177 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
3178 ),
3179 );
3180
3181 it.effect("starts with symlinked settings when the settings directory watch fails", () =>
3182 Effect.gen(function* () {
3183 const fs = yield* FileSystem.FileSystem;
3184 const path = yield* Path.Path;
3185 let settingsDirectory: string | undefined;
3186 const watchFailure = PlatformError.systemError({
3187 _tag: "Unknown",
3188 module: "FileSystem",
3189 method: "watch",
3190 description: "No file watches available.",
3191 });
3192 const failingFileSystem = FileSystem.FileSystem.of({
3193 ...fs,
3194 watch: (directory, options) =>
3195 directory === settingsDirectory ? Stream.fail(watchFailure) : fs.watch(directory, options),
3196 });
3197 const settingsLayer = layerServerSettings().pipe(
3198 Layer.provide(Layer.succeed(FileSystem.FileSystem, failingFileSystem)),
3199 );
3200
3201 yield* Effect.gen(function* () {
3202 const config = yield* ServerConfig.ServerConfig;
3203 const service = yield* ServerSettingsModule.ServerSettingsService;
3204 settingsDirectory = path.dirname(config.settingsPath);
3205 const dotfiles = yield* fs.makeTempDirectoryScoped({ prefix: "t3-settings-dotfiles-" });
3206 const target = path.join(dotfiles, "settings.json");
3207 yield* fs.writeFileString(target, `{ "responseStreamingMode": "paragraph" }`);
3208 yield* fs.remove(config.settingsPath, { force: true });
3209 yield* fs.symlink(target, config.settingsPath);
3210
3211 yield* service.start;
3212
3213 const settings = yield* service.getSettings;
3214 assert.equal(settings.responseStreamingMode, "paragraph");
3215 }).pipe(Effect.provide(settingsLayer));
3216 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
3217 );
3218
3219 it.effect("publishes edits made before the restored settings watch is registered", () =>
3220 Effect.gen(function* () {
3221 const fs = yield* FileSystem.FileSystem;
3222 const path = yield* Path.Path;
3223 const dotfiles = yield* fs.makeTempDirectoryScoped({ prefix: "t3-settings-dotfiles-" });
3224 const active = path.join(dotfiles, "active");
3225 const restored = path.join(dotfiles, "restored");
3226 const target = path.join(active, "settings.json");
3227 yield* fs.makeDirectory(active);
3228 yield* fs.makeDirectory(restored);
3229 yield* fs.writeFileString(target, `{ "responseStreamingMode": "turn" }`);
3230 yield* fs.writeFileString(
3231 path.join(restored, "settings.json"),
3232 `{ "responseStreamingMode": "turn" }`,
3233 );
3234
3235 const replaced = yield* Deferred.make<void>();
3236 const registering = yield* Deferred.make<void>();
3237 const allowRegistration = yield* Deferred.make<void>();
3238 const settingsLayer = layerServerSettings().pipe(
3239 Layer.provide(
3240 Layer.succeed(
3241 FileSystem.FileSystem,
3242 FileSystem.FileSystem.of({
3243 ...fs,
3244 watch: (directory, options) =>
3245 Stream.unwrap(
3246 Effect.gen(function* () {
3247 if (directory === dotfiles) {
3248 options?.onReady?.();
3249 return Stream.fromEffect(Deferred.await(replaced)).pipe(
3250 Stream.as({ _tag: "Create", path: "active" } as const),
3251 Stream.concat(Stream.never),
3252 );
3253 }
3254 if (directory !== active) return fs.watch(directory, options);
3255 if (yield* Deferred.isDone(replaced)) {
3256 yield* Deferred.succeed(registering, undefined);
3257 yield* Deferred.await(allowRegistration);
3258 }
3259 options?.onReady?.();
3260 return Stream.never;
3261 }),
3262 ),
3263 }),
3264 ),
3265 ),
3266 );
3267
3268 yield* Effect.gen(function* () {
3269 const config = yield* ServerConfig.ServerConfig;
3270 const service = yield* ServerSettingsModule.ServerSettingsService;
3271 yield* fs.symlink(target, config.settingsPath);
3272 yield* service.start;
3273 const changes = yield* service.subscribeChanges;
3274
3275 yield* fs.rename(active, path.join(dotfiles, "previous"));
3276 yield* fs.rename(restored, active);
3277 // Deliver the event on the test clock so it drains the watcher and any eager debounce.
3278 yield* Deferred.succeed(replaced, undefined).pipe(
3279 Effect.delay(1),
3280 Effect.forkScoped({ startImmediately: true }),
3281 );
3282 yield* TestClock.adjust("1 second");
3283 yield* Deferred.await(registering);
3284 yield* service.withSettingsSnapshot(() => Effect.void);
3285 yield* fs.writeFileString(target, `{ "responseStreamingMode": "paragraph" }`);
3286 yield* Deferred.succeed(allowRegistration, undefined).pipe(
3287 Effect.delay(1),
3288 Effect.forkScoped({ startImmediately: true }),
3289 );
3290 yield* TestClock.adjust("1 second");
3291
3292 const published = yield* changes.pipe(Stream.runHead);
3293 assert.equal(Option.getOrThrow(published).responseStreamingMode, "paragraph");
3294 }).pipe(Effect.provide(settingsLayer));
3295 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
3296 );