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

settings.test.ts

486 lines18.7 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​
131describe("ServerSettings secret providers", () => {
132 const onePassword = (account: string) => ({
133 kind: "one_password",
134 label: "Personal",
135 config: { account },
136 });
137​
138 it("keeps an unknown kind or a longer label from invalidating the rest of the settings", () => {
139 const openbao = { kind: "openbao", label: "V".repeat(65), config: { address: "https://x" } };
140 const decoded = decodeServerSettings({
141 worktreesDirectory: "/work",
142 secretProviders: { vault: openbao, personal: onePassword("my.1password.com") },
143 });
144 expect(decoded.worktreesDirectory).toBe("/work");
145 expect(encodeServerSettings(decoded).secretProviders).toEqual({
146 vault: openbao,
147 personal: onePassword("my.1password.com"),
148 });
149 });
150​
151 it("accepts slug ids and null removals but no id that is not a slug", () => {
152 expect(
153 decodeServerSettingsPatch({
154 secretProviders: { "1password": onePassword("my.1password.com"), work: null },
155 }).secretProviders,
156 ).toEqual({ "1password": onePassword("my.1password.com"), work: null });
157 for (const id of ["", "My Vault", "a/b", "-vault"]) {
158 expect(() =>
159 decodeServerSettingsPatch({ secretProviders: { [id]: onePassword("my.1password.com") } }),
160 ).toThrow();
161 }
162 expect(() =>
163 decodeServerSettingsPatch({
164 secretProviders: { work: { ...onePassword("my.1password.com"), label: "V".repeat(65) } },
165 }),
166 ).toThrow();
167 });
168​
169 it("stores a provider environment secret reference in a layout older builds still decode", () => {
170 const providerInstances = (secret: unknown) => ({
171 codex: {
172 driver: "codex",
173 environment: [
174 { name: "OPENAI_API_KEY", sensitive: true, value: "", secret },
175 { name: "BASE_URL", value: "https://example.test" },
176 ],
177 },
178 });
179 const secret = { provider: "personal", reference: "op://Private/OpenAI/credential" };
180 const environment = decodeServerSettings({ providerInstances: providerInstances(secret) })
181 .providerInstances[ProviderInstanceId.make("codex")]?.environment;
182 expect(environment).toEqual([
183 { name: "OPENAI_API_KEY", value: secret, sensitive: true },
184 { name: "BASE_URL", value: "https://example.test", sensitive: false },
185 ]);
186​
187 const encoded = encodeProviderInstanceEnvironment(environment ?? []);
188 expect(encoded).toEqual([
189 { name: "OPENAI_API_KEY", value: "", sensitive: true, secret },
190 { name: "BASE_URL", value: "https://example.test", sensitive: false },
191 ]);
192 expect(decodeProviderInstanceEnvironment(encoded)).toEqual(environment);
193 expect(decodeStringOnlyEnvironment(encoded)).toEqual([
194 { name: "OPENAI_API_KEY", value: "", sensitive: true },
195 { name: "BASE_URL", value: "https://example.test", sensitive: false },
196 ]);
197​
198 for (const invalid of [
199 { provider: "My Vault", reference: "op://a/b/c" },
200 { provider: "personal", reference: " " },
201 { provider: "personal", reference: "op://Private/OpenAI\n/credential" },
202 { provider: "personal", reference: "x".repeat(1025) },
203 ]) {
204 expect(() =>
205 decodeServerSettings({ providerInstances: providerInstances(invalid) }),
206 ).toThrow();
207 }
208 });
209});
210​
211describe("custom model settings", () => {
212 const capabilities = {
213 optionDescriptors: [
214 {
215 id: "effort",
216 label: "Reasoning",
217 type: "select",
218 options: [{ id: "high", label: "High", isDefault: true }],
219 },
220 ],
221 };
222​
223 it("accepts legacy bare slugs alongside full entries", () => {
224 const decoded = decodeClaudeSettings({
225 customModels: ["bare-slug", { slug: "named", name: "Named", capabilities }],
226 });
227 expect(decoded.customModels).toEqual([
228 "bare-slug",
229 { slug: "named", name: "Named", capabilities },
230 ]);
231 });
232});
233​
234describe("resolveIdleCompaction", () => {
235 it("lets a Claude instance override the global default", () => {
236 const settings = decodeServerSettings({
237 idleCompaction: "off",
238 providerInstances: {
239 claude_work: { driver: "claudeAgent", config: { idleCompaction: "onReturn" } },
240 claude_personal: { driver: "claudeAgent" },
241 },
242 });
243 expect(resolveIdleCompaction(settings, ProviderInstanceId.make("claude_work"))).toBe(
244 "onReturn",
245 );
246 expect(resolveIdleCompaction(settings, ProviderInstanceId.make("claude_personal"))).toBe("off");
247 expect(resolveIdleCompaction(settings, ProviderInstanceId.make("claudeAgent"))).toBe("off");
248 });
249​
250 it("reads the mode from the legacy switch, in either form servers saved it", () => {
251 expect(globalIdleCompaction(decodeServerSettings({ compactIdleThreads: true }))).toBe(
252 "beforeCacheExpires",
253 );
254 expect(globalIdleCompaction(decodeServerSettings({ compactIdleThreads: "off" }))).toBe("off");
255 expect(globalIdleCompaction(decodeServerSettings({}))).toBe("onReturn");
256 });
257​
258 it("keeps the legacy switch a boolean, as shipped clients decode it", () => {
259 const encode = Schema.encodeSync(Schema.toCodecJson(ServerSettings));
260 for (const mode of ["onReturn", "beforeCacheExpires", "off"] as const) {
261 const encoded = encode(withIdleCompaction(DEFAULT_SERVER_SETTINGS, mode)) as {
262 readonly compactIdleThreads: unknown;
263 readonly idleCompaction: unknown;
264 };
265 expect(encoded.compactIdleThreads).toBe(mode === "beforeCacheExpires");
266 expect(encoded.idleCompaction).toBe(mode);
267 }
268 });
269​
270 it("patches the field the server reads", () => {
271 expect(
272 idleCompactionPatch({ compactIdleThreads: false, idleCompaction: "onReturn" }, "off"),
273 ).toEqual({
274 idleCompaction: "off",
275 });
276 expect(idleCompactionPatch({ compactIdleThreads: "onReturn" }, "off")).toEqual({
277 compactIdleThreads: "off",
278 });
279 expect(idleCompactionPatch({ compactIdleThreads: false }, "beforeCacheExpires")).toEqual({
280 compactIdleThreads: true,
281 });
282 });
283});
284​
285describe("ClientSettings notifications", () => {
286 it("requires opt-in when existing settings omit notification preferences", () => {
287 expect(decodeClientSettings({}).notificationMode).toBe("off");
288 expect(decodeClientSettings({}).inAppNotificationsEnabled).toBe(false);
289 expect(decodeClientSettingsPatch({})).not.toHaveProperty("inAppNotificationsEnabled");
290 expect(decodeClientSettingsPatch({})).not.toHaveProperty("notificationMode");
291 });
292});
293​
294describe("ClientSettings quit confirmation", () => {
295 it.each([
296 [true, "hold"],
297 [false, "direct"],
298 ] as const)("migrates the legacy %s value to %s", (legacyValue, mode) => {
299 const settings = decodeClientSettings({ confirmQuit: legacyValue });
300​
301 expect(settings.confirmQuit).toBe(mode);
302 expect(encodeClientSettings(settings).confirmQuit).toBe(mode);
303 });
304});
305​
306describe("provider enabled defaults", () => {
307 it("resolves instance enabled state with explicit false winning", () => {
308 const grok = ProviderDriverKind.make("grok");
309 const codex = ProviderDriverKind.make("codex");
310 expect(resolveProviderInstanceEnabled({ driver: grok, config: {} })).toBe(false);
311 expect(resolveProviderInstanceEnabled({ driver: codex, config: {} })).toBe(true);
312 expect(
313 resolveProviderInstanceEnabled({ driver: ProviderDriverKind.make("ollama"), config: {} }),
314 ).toBe(true);
315 expect(resolveProviderInstanceEnabled({ driver: grok, enabled: true, config: {} })).toBe(true);
316 expect(resolveProviderInstanceEnabled({ driver: codex, enabled: false, config: {} })).toBe(
317 false,
318 );
319 expect(resolveProviderInstanceEnabled({ driver: grok, config: { enabled: true } })).toBe(true);
320 expect(
321 resolveProviderInstanceEnabled({ driver: grok, enabled: true, config: { enabled: false } }),
322 ).toBe(false);
323 expect(
324 resolveProviderInstanceEnabled({ driver: codex, enabled: false, config: { enabled: true } }),
325 ).toBe(false);
326 });
327});
328​
329describe("ServerSettings worktree defaults", () => {
330 it("defaults the thread env mode to inherit and keeps stored values", () => {
331 expect(decodeServerSettings({}).defaultThreadEnvMode).toBeNull();
332 expect(decodeServerSettings({ defaultThreadEnvMode: "worktree" }).defaultThreadEnvMode).toBe(
333 "worktree",
334 );
335 expect(
336 decodeServerSettings({ defaultThreadEnvMode: "remote" }).defaultThreadEnvMode,
337 ).toBeNull();
338 expect(
339 decodeServerSettingsPatch({ defaultThreadEnvMode: null }).defaultThreadEnvMode,
340 ).toBeNull();
341 });
342​
343 it("keeps an inherited thread env mode off the wire for older clients", () => {
344 const encode = Schema.encodeSync(ServerSettings);
345 expect("defaultThreadEnvMode" in encode(decodeServerSettings({}))).toBe(false);
346 expect(
347 encode(decodeServerSettings({ defaultThreadEnvMode: "worktree" })).defaultThreadEnvMode,
348 ).toBe("worktree");
349 });
350});
351​
352describe("ServerSettings.sourceControlWritingStyle", () => {
353 it.each([
354 { legacy: "", mode: "repo_conventions", customInstructions: "" },
355 { legacy: " \t\n ", mode: "repo_conventions", customInstructions: "" },
356 {
357 legacy: " Prefer concise wording.\nKeep issue references. ",
358 mode: "custom",
359 customInstructions: "Prefer concise wording.\nKeep issue references.",
360 },
361 ])("normalizes legacy writing style $legacy in snapshots only", ({ legacy, ...expected }) => {
362 const style = { ...expected, followChangeRequestTemplates: true };
363 for (const [input, normalized] of [
364 [{ sourceControlWritingStyle: legacy }, { sourceControlWritingStyle: style }],
365 [
366 { projectSettingsOverrides: { project: { sourceControlWritingStyle: legacy } } },
367 { projectSettingsOverrides: { project: { sourceControlWritingStyle: style } } },
368 ],
369 ] as const) {
370 const settings = decodeServerSettings(input);
371 expect(settings).toMatchObject(normalized);
372 expect(encodeServerSettings(settings)).toMatchObject(normalized);
373 expect(() => decodeServerSettingsPatch(input)).toThrow();
374 }
375 });
376});
377​
378describe("ServerSettings environment icon", () => {
379 it("decodes a kind from a newer server as null instead of failing the snapshot", () => {
380 expect(decodeServerSettings({ environmentIcon: "toaster" }).environmentIcon).toBeNull();
381 });
382});
383​
384const decodeDeviceHostSettings = Schema.decodeSync(ServerSettings);
385​
386// `deviceHosts` as it was decoded before EAS hosts existed: an SSH host needs a target.
387const decodeOlderDeviceHostSettings = Schema.decodeUnknownSync(
388 Schema.Struct({
389 deviceHosts: Schema.Array(Schema.Struct({ id: Schema.String, target: Schema.String })),
390 }),
391);
392​
393it("keeps EAS hosts out of the SSH host list servers and clients before EAS hosts decode", () => {
394 const settings = decodeDeviceHostSettings({
395 deviceHosts: [{ id: "mini", label: "Mac mini", target: "user@mini" }],
396 easDeviceHosts: [{ kind: "eas", id: "eas", label: "EAS Simulator" }],
397 });
398 const wire = encodeServerSettings(settings);
399 expect(decodeOlderDeviceHostSettings(wire).deviceHosts).toEqual([
400 { id: "mini", target: "user@mini" },
401 ]);
402 expect(settings.easDeviceHosts.map((host) => host.id)).toEqual(["eas"]);
403});
404​
405it("validates remote device hosts and rejects ambiguous host ids", () => {
406 const host = { id: "mini", label: "Mac mini", target: "user@mini", port: 2222 };
407 // Hosts saved before EAS hosts existed have no `kind`; they are SSH hosts.
408 expect(decodeDeviceHostSettings({ deviceHosts: [host] }).deviceHosts).toEqual([
409 { kind: "ssh", ...host },
410 ]);
411 expect(() => decodeDeviceHostSettings({ deviceHosts: [host, host] })).toThrow();
412 expect(() => decodeDeviceHostSettings({ deviceHosts: [{ ...host, id: "local" }] })).toThrow();
413 expect(() =>
414 decodeDeviceHostSettings({ deviceHosts: [{ ...host, target: "-oProxyCommand=bad" }] }),
415 ).toThrow();
416 expect(() => decodeDeviceHostSettings({ deviceHosts: [{ ...host, port: 0 }] })).toThrow();
417});
418​
419describe("ServerSettings project overrides across versions", () => {
420 it("sends back an override key from a newer server when an older client edits the entry", () => {
421 const projectId = ProjectId.make("project-a");
422 // As an older client reads a newer server's settings, with one key it does not know.
423 const entry = decodeServerSettings({
424 projectSettingsOverrides: {
425 [projectId]: { defaultAutoPull: true, addedByNewerServer: { mode: "kept" } },
426 },
427 }).projectSettingsOverrides[projectId];
428​
429 const sent = encodeServerSettingsPatch({
430 projectSettingsOverrides: { [projectId]: { ...entry, defaultAutoPull: false } },
431 });
432​
433 expect(decodeServerSettingsPatch(sent).projectSettingsOverrides?.[projectId]).toEqual({
434 defaultAutoPull: false,
435 addedByNewerServer: { mode: "kept" },
436 });
437 });
438});
439​
440describe("resolveProjectProviderInstanceEnabled", () => {
441 const projectId = "project-a" as ProjectId;
442 const instanceId = ProviderInstanceId.make("codex_work");
443​
444 it("lets a project disable an instance the machine enabled", () => {
445 const settings: ServerSettings = {
446 ...DEFAULT_SERVER_SETTINGS,
447 providerInstances: {
448 [instanceId]: { driver: ProviderDriverKind.make("codex"), enabled: true },
449 },
450 projectSettingsOverrides: {
451 [projectId]: { providerInstances: { [instanceId]: { enabled: false } } },
452 },
453 };
454 expect(resolveProjectProviderInstanceEnabled(settings, projectId, instanceId)).toBe(false);
455 });
456});
457​
458describe("requiredScopesForProjectMutation", () => {
459 it("adds the settings scope only when a mutation carries scripts", () => {
460 const projectId = "project-1" as ProjectId;
461 const commandId = "command-1" as CommandId;
462 expect(
463 requiredScopesForProjectMutation({ type: "project.update", commandId, projectId }),
464 ).toEqual(["orchestration:operate"]);
465 expect(
466 requiredScopesForProjectMutation({
467 type: "project.update",
468 commandId,
469 projectId,
470 scripts: [],
471 }),
472 ).toEqual(["orchestration:operate", "settings:write"]);
473 });
474});
475​
476describe("server model preferences", () => {
477 it("distinguishes unmigrated lists from deliberately cleared lists", () => {
478 expect(decodeServerSettings({})).toMatchObject({
479 favorites: null,
480 providerModelPreferences: null,
481 });
482 const input = { favorites: [], providerModelPreferences: {} };
483 expect(encodeServerSettings(decodeServerSettings(input))).toMatchObject(input);
484 expect(decodeServerSettingsPatch(input)).toEqual(input);
485 });
486});