Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

settings.test.ts

506 lines19.5 KB

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