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

main
ts 557 lines 21.7 KB
Raw
1 import { describe, expect, it } from "vite-plus/test";
2 import * as Schema from "effect/Schema";
3
4 import { type CommandId, ProjectId } from "./baseSchemas.ts";
5 import {
6 ProviderDriverKind,
7 ProviderInstanceEnvironment,
8 ProviderInstanceId,
9 } from "./providerInstance.ts";
10 import {
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
28 const decodeClientSettings = Schema.decodeUnknownSync(ClientSettingsSchema);
29 const decodeClientSettingsPatch = Schema.decodeUnknownSync(ClientSettingsPatch);
30 const encodeClientSettings = Schema.encodeSync(ClientSettingsSchema);
31 const decodeServerSettings = Schema.decodeUnknownSync(ServerSettings);
32 const encodeProviderInstanceEnvironment = Schema.encodeSync(ProviderInstanceEnvironment);
33 const decodeProviderInstanceEnvironment = Schema.decodeSync(ProviderInstanceEnvironment);
34 // The environment variable shape builds released before secret references decode.
35 const decodeStringOnlyEnvironment = Schema.decodeUnknownSync(
36 Schema.Array(
37 Schema.Struct({ name: Schema.String, value: Schema.String, sensitive: Schema.Boolean }),
38 ),
39 );
40 const decodeServerSettingsPatch = Schema.decodeUnknownSync(ServerSettingsPatch);
41 const decodeClientServerSettingsPatch = Schema.decodeUnknownSync(ClientServerSettingsPatch);
42 const encodeServerSettings = Schema.encodeSync(ServerSettings);
43 const encodeServerSettingsPatch = Schema.encodeSync(ServerSettingsPatch);
44 const decodeClaudeSettings = Schema.decodeUnknownSync(ClaudeSettings);
45
46 it("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
58 describe("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
132 describe("ClientSettings terminal close confirmation", () => {
133 it("keeps confirmation enabled for settings without a saved preference", () => {
134 expect(decodeClientSettings({}).confirmTerminalClose).toBe(true);
135 });
136 });
137
138 describe("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
163 it("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
172 describe("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
252 describe("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
275 describe("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
326 describe("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
335 describe("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
347 describe("provider enabled defaults", () => {
348 it("resolves instance enabled state with explicit false winning", () => {
349 const grok = ProviderDriverKind.make("grok");
350 const codex = ProviderDriverKind.make("codex");
351 expect(resolveProviderInstanceEnabled({ driver: grok, 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: grok, enabled: true, config: {} })).toBe(true);
357 expect(resolveProviderInstanceEnabled({ driver: codex, enabled: false, config: {} })).toBe(
358 false,
359 );
360 expect(resolveProviderInstanceEnabled({ driver: grok, config: { enabled: true } })).toBe(true);
361 expect(
362 resolveProviderInstanceEnabled({ driver: grok, enabled: true, config: { enabled: false } }),
363 ).toBe(false);
364 expect(
365 resolveProviderInstanceEnabled({ driver: codex, enabled: false, config: { enabled: true } }),
366 ).toBe(false);
367 });
368 });
369
370 describe("ServerSettings worktree defaults", () => {
371 it("defaults the thread env mode to inherit and keeps stored values", () => {
372 expect(decodeServerSettings({}).defaultThreadEnvMode).toBeNull();
373 expect(decodeServerSettings({ defaultThreadEnvMode: "worktree" }).defaultThreadEnvMode).toBe(
374 "worktree",
375 );
376 expect(
377 decodeServerSettings({ defaultThreadEnvMode: "remote" }).defaultThreadEnvMode,
378 ).toBeNull();
379 expect(
380 decodeServerSettingsPatch({ defaultThreadEnvMode: null }).defaultThreadEnvMode,
381 ).toBeNull();
382 });
383
384 it("keeps an inherited thread env mode off the wire for older clients", () => {
385 const encode = Schema.encodeSync(ServerSettings);
386 expect("defaultThreadEnvMode" in encode(decodeServerSettings({}))).toBe(false);
387 expect(
388 encode(decodeServerSettings({ defaultThreadEnvMode: "worktree" })).defaultThreadEnvMode,
389 ).toBe("worktree");
390 });
391 });
392
393 describe("ServerSettings.sourceControlWritingStyle", () => {
394 it.each([
395 { legacy: "", mode: "repo_conventions", customInstructions: "" },
396 { legacy: " \t\n ", mode: "repo_conventions", customInstructions: "" },
397 {
398 legacy: " Prefer concise wording.\nKeep issue references. ",
399 mode: "custom",
400 customInstructions: "Prefer concise wording.\nKeep issue references.",
401 },
402 ])("normalizes legacy writing style $legacy in snapshots only", ({ legacy, ...expected }) => {
403 const style = { ...expected, followChangeRequestTemplates: true };
404 for (const [input, normalized] of [
405 [{ sourceControlWritingStyle: legacy }, { sourceControlWritingStyle: style }],
406 [
407 { projectSettingsOverrides: { project: { sourceControlWritingStyle: legacy } } },
408 { projectSettingsOverrides: { project: { sourceControlWritingStyle: style } } },
409 ],
410 ] as const) {
411 const settings = decodeServerSettings(input);
412 expect(settings).toMatchObject(normalized);
413 expect(encodeServerSettings(settings)).toMatchObject(normalized);
414 expect(() => decodeServerSettingsPatch(input)).toThrow();
415 }
416 });
417 });
418
419 describe("ServerSettings environment icon", () => {
420 it("decodes a kind from a newer server as null instead of failing the snapshot", () => {
421 expect(decodeServerSettings({ environmentIcon: "toaster" }).environmentIcon).toBeNull();
422 });
423 });
424
425 const decodeDeviceHostSettings = Schema.decodeSync(ServerSettings);
426
427 // `deviceHosts` as it was decoded before Expo hosts existed: an SSH host needs a target.
428 const decodeOlderDeviceHostSettings = Schema.decodeUnknownSync(
429 Schema.Struct({
430 deviceHosts: Schema.Array(Schema.Struct({ id: Schema.String, target: Schema.String })),
431 }),
432 );
433
434 it("keeps Expo hosts out of the SSH host list servers and clients before Expo hosts decode", () => {
435 const settings = decodeDeviceHostSettings({
436 deviceHosts: [{ id: "mini", label: "Mac mini", target: "user@mini" }],
437 easDeviceHosts: [{ kind: "eas", id: "eas", label: "Expo Simulators" }],
438 });
439 const wire = encodeServerSettings(settings);
440 expect(decodeOlderDeviceHostSettings(wire).deviceHosts).toEqual([
441 { id: "mini", target: "user@mini" },
442 ]);
443 expect(settings.easDeviceHosts.map((host) => host.id)).toEqual(["eas"]);
444 });
445
446 it("validates remote device hosts and rejects ambiguous host ids", () => {
447 const host = { id: "mini", label: "Mac mini", target: "user@mini", port: 2222 };
448 // Hosts saved before Expo hosts existed have no `kind`; they are SSH hosts.
449 expect(decodeDeviceHostSettings({ deviceHosts: [host] }).deviceHosts).toEqual([
450 { kind: "ssh", ...host },
451 ]);
452 expect(() => decodeDeviceHostSettings({ deviceHosts: [host, host] })).toThrow();
453 expect(() => decodeDeviceHostSettings({ deviceHosts: [{ ...host, id: "local" }] })).toThrow();
454 expect(() =>
455 decodeDeviceHostSettings({ deviceHosts: [{ ...host, target: "-oProxyCommand=bad" }] }),
456 ).toThrow();
457 expect(() => decodeDeviceHostSettings({ deviceHosts: [{ ...host, port: 0 }] })).toThrow();
458 });
459
460 describe("ServerSettings project overrides across versions", () => {
461 it("sends back an override key from a newer server when an older client edits the entry", () => {
462 const projectId = ProjectId.make("project-a");
463 // As an older client reads a newer server's settings, with one key it does not know.
464 const entry = decodeServerSettings({
465 projectSettingsOverrides: {
466 [projectId]: { defaultAutoPull: true, addedByNewerServer: { mode: "kept" } },
467 },
468 }).projectSettingsOverrides[projectId];
469
470 const sent = encodeServerSettingsPatch({
471 projectSettingsOverrides: { [projectId]: { ...entry, defaultAutoPull: false } },
472 });
473
474 expect(decodeServerSettingsPatch(sent).projectSettingsOverrides?.[projectId]).toEqual({
475 defaultAutoPull: false,
476 addedByNewerServer: { mode: "kept" },
477 });
478 });
479 });
480
481 describe("resolveProjectProviderInstanceEnabled", () => {
482 const projectId = "project-a" as ProjectId;
483 const instanceId = ProviderInstanceId.make("codex_work");
484
485 it("lets a project disable an instance the machine enabled", () => {
486 const settings: ServerSettings = {
487 ...DEFAULT_SERVER_SETTINGS,
488 providerInstances: {
489 [instanceId]: { driver: ProviderDriverKind.make("codex"), enabled: true },
490 },
491 projectSettingsOverrides: {
492 [projectId]: { providerInstances: { [instanceId]: { enabled: false } } },
493 },
494 };
495 expect(resolveProjectProviderInstanceEnabled(settings, projectId, instanceId)).toBe(false);
496 });
497 });
498
499 describe("requiredScopesForProjectMutation", () => {
500 it("adds the settings scope only when a mutation carries scripts", () => {
501 const projectId = "project-1" as ProjectId;
502 const commandId = "command-1" as CommandId;
503 expect(
504 requiredScopesForProjectMutation({ type: "project.update", commandId, projectId }),
505 ).toEqual(["orchestration:operate"]);
506 expect(
507 requiredScopesForProjectMutation({
508 type: "project.update",
509 commandId,
510 projectId,
511 scripts: [],
512 }),
513 ).toEqual(["orchestration:operate", "settings:write"]);
514 });
515 });
516
517 describe("voice settings", () => {
518 it("does not import voice consent from ordinary device preferences", () => {
519 const imported = {
520 voiceTranscriptionEnvironmentId: "env-1",
521 voiceTranscriptionDestination: { kind: "environment", environmentId: "env-1" },
522 speechPostProcessingEnabled: true,
523 };
524 expect(decodeClientSettings({}).speechSilenceFiltering).toBe(true);
525 expect(decodeClientSettings({}).speechStreaming).toBe(true);
526 expect(decodeClientSettings({ speechStreaming: false }).speechStreaming).toBe(false);
527 expect(decodeClientSettingsPatch({ speechStreaming: false })).toEqual({
528 speechStreaming: false,
529 });
530 expect(decodeClientSettingsPatch({ speechSilenceFiltering: false })).toEqual({
531 speechSilenceFiltering: false,
532 });
533 for (const key of Object.keys(imported)) {
534 expect(decodeClientSettings(imported)).not.toHaveProperty(key);
535 expect(decodeClientSettingsPatch(imported)).not.toHaveProperty(key);
536 }
537 });
538
539 it("keeps the correction cue personal and project vocabulary on the environment", () => {
540 expect(decodeClientSettings({}).speechCorrectionWord).toBe("");
541 expect(() => decodeClientSettingsPatch({ speechCorrectionWord: "x".repeat(51) })).toThrow();
542 expect(DEFAULT_SERVER_SETTINGS.speechProjectCustomWords).toEqual([]);
543 expect(PROJECT_SCOPED_SERVER_SETTING_KEYS).toContain("speechProjectCustomWords");
544 });
545 });
546
547 describe("server model preferences", () => {
548 it("distinguishes unmigrated lists from deliberately cleared lists", () => {
549 expect(decodeServerSettings({})).toMatchObject({
550 favorites: null,
551 providerModelPreferences: null,
552 });
553 const input = { favorites: [], providerModelPreferences: {} };
554 expect(encodeServerSettings(decodeServerSettings(input))).toMatchObject(input);
555 expect(decodeServerSettingsPatch(input)).toEqual(input);
556 });
557 });