Open History to see the last commit
1import { describe, expect, it } from "vite-plus/test";
2import * as Schema from "effect/Schema";
3
4import { type CommandId, ProjectId } from "./baseSchemas.ts";
5import {
6 ProviderDriverKind,
7 ProviderInstanceEnvironment,
8 ProviderInstanceId,
9} from "./providerInstance.ts";
10import {
11 ClientSettingsSchema,
12 ClientSettingsPatch,
13 ClientServerSettingsPatch,
14 ClaudeSettings,
15 DEFAULT_SERVER_SETTINGS,
16 globalIdleCompaction,
17 idleCompactionPatch,
18 PROJECT_SCOPED_SERVER_SETTING_KEYS,
19 requiredScopesForProjectMutation,
20 resolveIdleCompaction,
21 resolveProjectProviderInstanceEnabled,
22 resolveProviderInstanceEnabled,
23 ServerSettings,
24 ServerSettingsPatch,
25 withIdleCompaction,
26} from "./settings.ts";
27
28const decodeClientSettings = Schema.decodeUnknownSync(ClientSettingsSchema);
29const decodeClientSettingsPatch = Schema.decodeUnknownSync(ClientSettingsPatch);
30const encodeClientSettings = Schema.encodeSync(ClientSettingsSchema);
31const decodeServerSettings = Schema.decodeUnknownSync(ServerSettings);
32const encodeProviderInstanceEnvironment = Schema.encodeSync(ProviderInstanceEnvironment);
33const decodeProviderInstanceEnvironment = Schema.decodeSync(ProviderInstanceEnvironment);
34// The environment variable shape builds released before secret references decode.
35const decodeStringOnlyEnvironment = Schema.decodeUnknownSync(
36 Schema.Array(
37 Schema.Struct({ name: Schema.String, value: Schema.String, sensitive: Schema.Boolean }),
38 ),
39);
40const decodeServerSettingsPatch = Schema.decodeUnknownSync(ServerSettingsPatch);
41const decodeClientServerSettingsPatch = Schema.decodeUnknownSync(ClientServerSettingsPatch);
42const encodeServerSettings = Schema.encodeSync(ServerSettings);
43const encodeServerSettingsPatch = Schema.encodeSync(ServerSettingsPatch);
44const decodeClaudeSettings = Schema.decodeUnknownSync(ClaudeSettings);
45
46it("drops theme defaults from a client's settings patch", () => {
47 expect(
48 decodeClientServerSettingsPatch({
49 newWorktreesStartFromOrigin: false,
50 defaultTheme: "grove",
51 defaultThemeSetAt: "2026-11-13T00:00:00.000Z",
52 defaultAppearance: "dark",
53 defaultAppearanceSetAt: "2026-11-13T00:00:00.000Z",
54 }),
55 ).toEqual({ newWorktreesStartFromOrigin: false });
56});
57
58describe("storage cleanup settings", () => {
59 it("keeps cleanup disabled for existing installations", () => {
60 expect(decodeServerSettings({}).worktreeCleanup).toBeNull();
61 expect(decodeServerSettings({}).storageCleanup).toEqual({
62 worktreeAfterDays: null,
63 worktreeSettledAfterDays: null,
64 worktreeOnMerge: false,
65 worktreeOnDelete: false,
66 worktreeUnchanged: false,
67 worktreeKeepWhen: "uncommitted-changes",
68 browserArtifactsAfterDays: null,
69 logsAfterDays: null,
70 });
71 });
72
73 it("accepts partial custom patches but requires complete stored project rules", () => {
74 expect(
75 decodeServerSettingsPatch({
76 worktreeCleanup: { mode: "custom", rules: { worktreeAfterDays: 8 } },
77 }),
78 ).toEqual({ worktreeCleanup: { mode: "custom", rules: { worktreeAfterDays: 8 } } });
79 expect(() =>
80 decodeServerSettings({
81 projectSettingsOverrides: {
82 project: { worktreeCleanup: { mode: "custom", rules: { worktreeAfterDays: 8 } } },
83 },
84 }),
85 ).toThrow();
86 expect(
87 decodeServerSettings({
88 projectSettingsOverrides: {
89 project: {
90 worktreeCleanup: {
91 mode: "custom",
92 rules: {
93 worktreeAfterDays: null,
94 worktreeOnMerge: false,
95 worktreeOnDelete: false,
96 worktreeUnchanged: false,
97 },
98 },
99 },
100 },
101 }).projectSettingsOverrides[ProjectId.make("project")]?.worktreeCleanup,
102 ).toMatchObject({
103 mode: "custom",
104 rules: { worktreeSettledAfterDays: null, worktreeKeepWhen: "uncommitted-changes" },
105 });
106 });
107
108 it("decodes older custom rules with the default local-file policy", () => {
109 const settings = decodeServerSettings({
110 worktreeCleanup: {
111 mode: "custom",
112 rules: {
113 worktreeAfterDays: 8,
114 worktreeOnMerge: false,
115 worktreeOnDelete: false,
116 worktreeUnchanged: false,
117 },
118 },
119 });
120 expect(settings.worktreeCleanup).toMatchObject({
121 rules: { worktreeKeepWhen: "uncommitted-changes" },
122 });
123 expect(
124 decodeServerSettingsPatch({ storageCleanup: { worktreeKeepWhen: "tracked-changes" } }),
125 ).toEqual({ storageCleanup: { worktreeKeepWhen: "tracked-changes" } });
126 expect(() =>
127 decodeServerSettingsPatch({ storageCleanup: { worktreeKeepWhen: "unknown" } }),
128 ).toThrow();
129 });
130});
131
132describe("ClientSettings terminal close confirmation", () => {
133 it("keeps confirmation enabled for settings without a saved preference", () => {
134 expect(decodeClientSettings({}).confirmTerminalClose).toBe(true);
135 });
136});
137
138describe("ServerSettings usage price overrides", () => {
139 const prices = { inputCostPerMillionTokens: 2, outputCostPerMillionTokens: 8 };
140
141 it("rejects empty model IDs and incomplete input/output pricing", () => {
142 for (const usagePriceOverrides of [
143 { " ": prices },
144 { "example-model": { inputCostPerMillionTokens: 2 } },
145 { "example-model": { outputCostPerMillionTokens: 8 } },
146 ]) {
147 expect(() => decodeServerSettingsPatch({ usagePriceOverrides })).toThrow();
148 }
149 });
150
151 it("ignores an invalid model filter without dropping the other settings", () => {
152 const valid = { include: [{ provider: "newer-provider", model: "orbit-1" }] };
153 expect(decodeServerSettings({ usageModelFilter: valid }).usageModelFilter).toEqual(valid);
154 const settings = decodeServerSettings({
155 usageModelFilter: { exclude: [{ model: "" }] },
156 usageModelAliases: { "drift-9": "orbit-1" },
157 });
158 expect(settings.usageModelFilter).toBeUndefined();
159 expect(settings.usageModelAliases).toEqual({ "drift-9": "orbit-1" });
160 });
161});
162
163it("drops a hand-edited non-string hidden tag and keeps the rest of the settings", () => {
164 const settings = decodeServerSettings({
165 hiddenThreadTags: ["private", 123],
166 hideTaggedThreads: true,
167 });
168 expect(settings.hiddenThreadTags).toEqual(["private"]);
169 expect(settings.hideTaggedThreads).toBe(true);
170});
171
172describe("ServerSettings secret providers", () => {
173 const onePassword = (account: string) => ({
174 kind: "one_password",
175 label: "Personal",
176 config: { account },
177 });
178
179 it("keeps an unknown kind or a longer label from invalidating the rest of the settings", () => {
180 const openbao = { kind: "openbao", label: "V".repeat(65), config: { address: "https://x" } };
181 const decoded = decodeServerSettings({
182 worktreesDirectory: "/work",
183 secretProviders: { vault: openbao, personal: onePassword("my.1password.com") },
184 });
185 expect(decoded.worktreesDirectory).toBe("/work");
186 expect(encodeServerSettings(decoded).secretProviders).toEqual({
187 vault: openbao,
188 personal: onePassword("my.1password.com"),
189 });
190 });
191
192 it("accepts slug ids and null removals but no id that is not a slug", () => {
193 expect(
194 decodeServerSettingsPatch({
195 secretProviders: { "1password": onePassword("my.1password.com"), work: null },
196 }).secretProviders,
197 ).toEqual({ "1password": onePassword("my.1password.com"), work: null });
198 for (const id of ["", "My Vault", "a/b", "-vault"]) {
199 expect(() =>
200 decodeServerSettingsPatch({ secretProviders: { [id]: onePassword("my.1password.com") } }),
201 ).toThrow();
202 }
203 expect(() =>
204 decodeServerSettingsPatch({
205 secretProviders: { work: { ...onePassword("my.1password.com"), label: "V".repeat(65) } },
206 }),
207 ).toThrow();
208 });
209
210 it("stores a provider environment secret reference in a layout older builds still decode", () => {
211 const providerInstances = (secret: unknown) => ({
212 codex: {
213 driver: "codex",
214 environment: [
215 { name: "OPENAI_API_KEY", sensitive: true, value: "", secret },
216 { name: "BASE_URL", value: "https://example.test" },
217 ],
218 },
219 });
220 const secret = { provider: "personal", reference: "op://Private/OpenAI/credential" };
221 const environment = decodeServerSettings({ providerInstances: providerInstances(secret) })
222 .providerInstances[ProviderInstanceId.make("codex")]?.environment;
223 expect(environment).toEqual([
224 { name: "OPENAI_API_KEY", value: secret, sensitive: true },
225 { name: "BASE_URL", value: "https://example.test", sensitive: false },
226 ]);
227
228 const encoded = encodeProviderInstanceEnvironment(environment ?? []);
229 expect(encoded).toEqual([
230 { name: "OPENAI_API_KEY", value: "", sensitive: true, secret },
231 { name: "BASE_URL", value: "https://example.test", sensitive: false },
232 ]);
233 expect(decodeProviderInstanceEnvironment(encoded)).toEqual(environment);
234 expect(decodeStringOnlyEnvironment(encoded)).toEqual([
235 { name: "OPENAI_API_KEY", value: "", sensitive: true },
236 { name: "BASE_URL", value: "https://example.test", sensitive: false },
237 ]);
238
239 for (const invalid of [
240 { provider: "My Vault", reference: "op://a/b/c" },
241 { provider: "personal", reference: " " },
242 { provider: "personal", reference: "op://Private/OpenAI\n/credential" },
243 { provider: "personal", reference: "x".repeat(1025) },
244 ]) {
245 expect(() =>
246 decodeServerSettings({ providerInstances: providerInstances(invalid) }),
247 ).toThrow();
248 }
249 });
250});
251
252describe("custom model settings", () => {
253 const capabilities = {
254 optionDescriptors: [
255 {
256 id: "effort",
257 label: "Reasoning",
258 type: "select",
259 options: [{ id: "high", label: "High", isDefault: true }],
260 },
261 ],
262 };
263
264 it("accepts legacy bare slugs alongside full entries", () => {
265 const decoded = decodeClaudeSettings({
266 customModels: ["bare-slug", { slug: "named", name: "Named", capabilities }],
267 });
268 expect(decoded.customModels).toEqual([
269 "bare-slug",
270 { slug: "named", name: "Named", capabilities },
271 ]);
272 });
273});
274
275describe("resolveIdleCompaction", () => {
276 it("lets a Claude instance override the global default", () => {
277 const settings = decodeServerSettings({
278 idleCompaction: "off",
279 providerInstances: {
280 claude_work: { driver: "claudeAgent", config: { idleCompaction: "onReturn" } },
281 claude_personal: { driver: "claudeAgent" },
282 },
283 });
284 expect(resolveIdleCompaction(settings, ProviderInstanceId.make("claude_work"))).toBe(
285 "onReturn",
286 );
287 expect(resolveIdleCompaction(settings, ProviderInstanceId.make("claude_personal"))).toBe("off");
288 expect(resolveIdleCompaction(settings, ProviderInstanceId.make("claudeAgent"))).toBe("off");
289 });
290
291 it("reads the mode from the legacy switch, in either form servers saved it", () => {
292 expect(globalIdleCompaction(decodeServerSettings({ compactIdleThreads: true }))).toBe(
293 "beforeCacheExpires",
294 );
295 expect(globalIdleCompaction(decodeServerSettings({ compactIdleThreads: "off" }))).toBe("off");
296 expect(globalIdleCompaction(decodeServerSettings({}))).toBe("onReturn");
297 });
298
299 it("keeps the legacy switch a boolean, as shipped clients decode it", () => {
300 const encode = Schema.encodeSync(Schema.toCodecJson(ServerSettings));
301 for (const mode of ["onReturn", "beforeCacheExpires", "off"] as const) {
302 const encoded = encode(withIdleCompaction(DEFAULT_SERVER_SETTINGS, mode)) as {
303 readonly compactIdleThreads: unknown;
304 readonly idleCompaction: unknown;
305 };
306 expect(encoded.compactIdleThreads).toBe(mode === "beforeCacheExpires");
307 expect(encoded.idleCompaction).toBe(mode);
308 }
309 });
310
311 it("patches the field the server reads", () => {
312 expect(
313 idleCompactionPatch({ compactIdleThreads: false, idleCompaction: "onReturn" }, "off"),
314 ).toEqual({
315 idleCompaction: "off",
316 });
317 expect(idleCompactionPatch({ compactIdleThreads: "onReturn" }, "off")).toEqual({
318 compactIdleThreads: "off",
319 });
320 expect(idleCompactionPatch({ compactIdleThreads: false }, "beforeCacheExpires")).toEqual({
321 compactIdleThreads: true,
322 });
323 });
324});
325
326describe("ClientSettings notifications", () => {
327 it("requires opt-in when existing settings omit notification preferences", () => {
328 expect(decodeClientSettings({}).notificationMode).toBe("off");
329 expect(decodeClientSettings({}).inAppNotificationsEnabled).toBe(false);
330 expect(decodeClientSettingsPatch({})).not.toHaveProperty("inAppNotificationsEnabled");
331 expect(decodeClientSettingsPatch({})).not.toHaveProperty("notificationMode");
332 });
333});
334
335describe("ClientSettings quit confirmation", () => {
336 it.each([
337 [true, "hold"],
338 [false, "direct"],
339 ] as const)("migrates the legacy %s value to %s", (legacyValue, mode) => {
340 const settings = decodeClientSettings({ confirmQuit: legacyValue });
341
342 expect(settings.confirmQuit).toBe(mode);
343 expect(encodeClientSettings(settings).confirmQuit).toBe(mode);
344 });
345});
346
347describe("provider enabled defaults", () => {
348 it("resolves instance enabled state with explicit false winning", () => {
349 const cursor = ProviderDriverKind.make("cursor");
350 const codex = ProviderDriverKind.make("codex");
351 expect(resolveProviderInstanceEnabled({ driver: cursor, config: {} })).toBe(false);
352 expect(resolveProviderInstanceEnabled({ driver: codex, config: {} })).toBe(true);
353 expect(
354 resolveProviderInstanceEnabled({ driver: ProviderDriverKind.make("ollama"), config: {} }),
355 ).toBe(true);
356 expect(resolveProviderInstanceEnabled({ driver: cursor, enabled: true, config: {} })).toBe(
357 true,
358 );
359 expect(resolveProviderInstanceEnabled({ driver: codex, enabled: false, config: {} })).toBe(
360 false,
361 );
362 expect(resolveProviderInstanceEnabled({ driver: cursor, config: { enabled: true } })).toBe(
363 true,
364 );
365 expect(
366 resolveProviderInstanceEnabled({ driver: cursor, enabled: true, config: { enabled: false } }),
367 ).toBe(false);
368 expect(
369 resolveProviderInstanceEnabled({ driver: codex, enabled: false, config: { enabled: true } }),
370 ).toBe(false);
371 });
372
373 it("keeps the retired Grok ACP driver disabled even when explicitly enabled", () => {
374 expect(
375 resolveProviderInstanceEnabled({
376 driver: ProviderDriverKind.make("grok"),
377 enabled: true,
378 config: { enabled: true },
379 }),
380 ).toBe(false);
381 });
382});
383
384describe("ServerSettings worktree defaults", () => {
385 it("defaults the thread env mode to inherit and keeps stored values", () => {
386 expect(decodeServerSettings({}).defaultThreadEnvMode).toBeNull();
387 expect(decodeServerSettings({ defaultThreadEnvMode: "worktree" }).defaultThreadEnvMode).toBe(
388 "worktree",
389 );
390 expect(
391 decodeServerSettings({ defaultThreadEnvMode: "remote" }).defaultThreadEnvMode,
392 ).toBeNull();
393 expect(
394 decodeServerSettingsPatch({ defaultThreadEnvMode: null }).defaultThreadEnvMode,
395 ).toBeNull();
396 });
397
398 it("keeps an inherited thread env mode off the wire for older clients", () => {
399 const encode = Schema.encodeSync(ServerSettings);
400 expect("defaultThreadEnvMode" in encode(decodeServerSettings({}))).toBe(false);
401 expect(
402 encode(decodeServerSettings({ defaultThreadEnvMode: "worktree" })).defaultThreadEnvMode,
403 ).toBe("worktree");
404 });
405});
406
407describe("ServerSettings.sourceControlWritingStyle", () => {
408 it.each([
409 { legacy: "", mode: "repo_conventions", customInstructions: "" },
410 { legacy: " \t\n ", mode: "repo_conventions", customInstructions: "" },
411 {
412 legacy: " Prefer concise wording.\nKeep issue references. ",
413 mode: "custom",
414 customInstructions: "Prefer concise wording.\nKeep issue references.",
415 },
416 ])("normalizes legacy writing style $legacy in snapshots only", ({ legacy, ...expected }) => {
417 const style = { ...expected, followChangeRequestTemplates: true };
418 for (const [input, normalized] of [
419 [{ sourceControlWritingStyle: legacy }, { sourceControlWritingStyle: style }],
420 [
421 { projectSettingsOverrides: { project: { sourceControlWritingStyle: legacy } } },
422 { projectSettingsOverrides: { project: { sourceControlWritingStyle: style } } },
423 ],
424 ] as const) {
425 const settings = decodeServerSettings(input);
426 expect(settings).toMatchObject(normalized);
427 expect(encodeServerSettings(settings)).toMatchObject(normalized);
428 expect(() => decodeServerSettingsPatch(input)).toThrow();
429 }
430 });
431});
432
433describe("ServerSettings environment icon", () => {
434 it("decodes a kind from a newer server as null instead of failing the snapshot", () => {
435 expect(decodeServerSettings({ environmentIcon: "toaster" }).environmentIcon).toBeNull();
436 });
437});
438
439const decodeDeviceHostSettings = Schema.decodeSync(ServerSettings);
440
441// `deviceHosts` as it was decoded before Expo hosts existed: an SSH host needs a target.
442const decodeOlderDeviceHostSettings = Schema.decodeUnknownSync(
443 Schema.Struct({
444 deviceHosts: Schema.Array(Schema.Struct({ id: Schema.String, target: Schema.String })),
445 }),
446);
447
448it("keeps Expo hosts out of the SSH host list servers and clients before Expo hosts decode", () => {
449 const settings = decodeDeviceHostSettings({
450 deviceHosts: [{ id: "mini", label: "Mac mini", target: "user@mini" }],
451 easDeviceHosts: [{ kind: "eas", id: "eas", label: "Expo Simulators" }],
452 });
453 const wire = encodeServerSettings(settings);
454 expect(decodeOlderDeviceHostSettings(wire).deviceHosts).toEqual([
455 { id: "mini", target: "user@mini" },
456 ]);
457 expect(settings.easDeviceHosts.map((host) => host.id)).toEqual(["eas"]);
458});
459
460it("validates remote device hosts and rejects ambiguous host ids", () => {
461 const host = { id: "mini", label: "Mac mini", target: "user@mini", port: 2222 };
462 // Hosts saved before Expo hosts existed have no `kind`; they are SSH hosts.
463 expect(decodeDeviceHostSettings({ deviceHosts: [host] }).deviceHosts).toEqual([
464 { kind: "ssh", ...host },
465 ]);
466 expect(() => decodeDeviceHostSettings({ deviceHosts: [host, host] })).toThrow();
467 expect(() => decodeDeviceHostSettings({ deviceHosts: [{ ...host, id: "local" }] })).toThrow();
468 expect(() =>
469 decodeDeviceHostSettings({ deviceHosts: [{ ...host, target: "-oProxyCommand=bad" }] }),
470 ).toThrow();
471 expect(() => decodeDeviceHostSettings({ deviceHosts: [{ ...host, port: 0 }] })).toThrow();
472});
473
474describe("ServerSettings project overrides across versions", () => {
475 it("sends back an override key from a newer server when an older client edits the entry", () => {
476 const projectId = ProjectId.make("project-a");
477 // As an older client reads a newer server's settings, with one key it does not know.
478 const entry = decodeServerSettings({
479 projectSettingsOverrides: {
480 [projectId]: { defaultAutoPull: true, addedByNewerServer: { mode: "kept" } },
481 },
482 }).projectSettingsOverrides[projectId];
483
484 const sent = encodeServerSettingsPatch({
485 projectSettingsOverrides: { [projectId]: { ...entry, defaultAutoPull: false } },
486 });
487
488 expect(decodeServerSettingsPatch(sent).projectSettingsOverrides?.[projectId]).toEqual({
489 defaultAutoPull: false,
490 addedByNewerServer: { mode: "kept" },
491 });
492 });
493});
494
495describe("resolveProjectProviderInstanceEnabled", () => {
496 const projectId = "project-a" as ProjectId;
497 const instanceId = ProviderInstanceId.make("codex_work");
498
499 it("lets a project disable an instance the machine enabled", () => {
500 const settings: ServerSettings = {
501 ...DEFAULT_SERVER_SETTINGS,
502 providerInstances: {
503 [instanceId]: { driver: ProviderDriverKind.make("codex"), enabled: true },
504 },
505 projectSettingsOverrides: {
506 [projectId]: { providerInstances: { [instanceId]: { enabled: false } } },
507 },
508 };
509 expect(resolveProjectProviderInstanceEnabled(settings, projectId, instanceId)).toBe(false);
510 });
511});
512
513describe("requiredScopesForProjectMutation", () => {
514 it("adds the settings scope only when a mutation carries scripts", () => {
515 const projectId = "project-1" as ProjectId;
516 const commandId = "command-1" as CommandId;
517 expect(
518 requiredScopesForProjectMutation({ type: "project.update", commandId, projectId }),
519 ).toEqual(["orchestration:operate"]);
520 expect(
521 requiredScopesForProjectMutation({
522 type: "project.update",
523 commandId,
524 projectId,
525 scripts: [],
526 }),
527 ).toEqual(["orchestration:operate", "settings:write"]);
528 });
529});
530
531describe("voice settings", () => {
532 it("does not import voice consent from ordinary device preferences", () => {
533 const imported = {
534 voiceTranscriptionEnvironmentId: "env-1",
535 voiceTranscriptionDestination: { kind: "environment", environmentId: "env-1" },
536 speechPostProcessingEnabled: true,
537 };
538 expect(decodeClientSettings({}).speechSilenceFiltering).toBe(true);
539 expect(decodeClientSettings({}).speechStreaming).toBe(true);
540 expect(decodeClientSettings({ speechStreaming: false }).speechStreaming).toBe(false);
541 expect(decodeClientSettingsPatch({ speechStreaming: false })).toEqual({
542 speechStreaming: false,
543 });
544 expect(decodeClientSettingsPatch({ speechSilenceFiltering: false })).toEqual({
545 speechSilenceFiltering: false,
546 });
547 for (const key of Object.keys(imported)) {
548 expect(decodeClientSettings(imported)).not.toHaveProperty(key);
549 expect(decodeClientSettingsPatch(imported)).not.toHaveProperty(key);
550 }
551 });
552
553 it("keeps the correction cue personal and project vocabulary on the environment", () => {
554 expect(decodeClientSettings({}).speechCorrectionWord).toBe("");
555 expect(() => decodeClientSettingsPatch({ speechCorrectionWord: "x".repeat(51) })).toThrow();
556 expect(DEFAULT_SERVER_SETTINGS.speechProjectCustomWords).toEqual([]);
557 expect(PROJECT_SCOPED_SERVER_SETTING_KEYS).toContain("speechProjectCustomWords");
558 });
559});
560
561describe("server model preferences", () => {
562 it("distinguishes unmigrated lists from deliberately cleared lists", () => {
563 expect(decodeServerSettings({})).toMatchObject({
564 favorites: null,
565 providerModelPreferences: null,
566 });
567 const input = { favorites: [], providerModelPreferences: {} };
568 expect(encodeServerSettings(decodeServerSettings(input))).toMatchObject(input);
569 expect(decodeServerSettingsPatch(input)).toEqual(input);
570 });
571});