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