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