Open History to see the last commit
1import {
2 DEFAULT_SERVER_SETTINGS,
3 ProjectId,
4 ProviderDriverKind,
5 ProviderInstanceId,
6 SecretProviderId,
7 SecretProviderKind,
8 ServerSettings,
9 ServerSettingsPatch,
10 UsageLimitSourceId,
11 type ServerProvider,
12} from "@t3tools/contracts";
13import * as Duration from "effect/Duration";
14import * as Schema from "effect/Schema";
15import { describe, expect, it } from "vite-plus/test";
16import { resolveServerBackgroundActivitySettings } from "./backgroundActivitySettings.ts";
17import { createModelSelection } from "./model.ts";
18import { resolveProjectScripts } from "./projectScripts.ts";
19import {
20 applyServerSettingsPatch,
21 fallbackTextGenerationModelSelection,
22 modelPreferencesMigrationPatch,
23 resolveModelPreferences,
24 isModelSelectionProviderEnabled,
25 parsePersistedServerObservabilitySettings,
26 resolveSourceControlWriterModelSelection,
27} from "./serverSettings.ts";
28
29const decodeServerSettings = Schema.decodeUnknownSync(ServerSettings);
30const decodeServerSettingsPatch = Schema.decodeUnknownSync(ServerSettingsPatch);
31
32const FOLDED_SERVER_SETTINGS = { ...DEFAULT_SERVER_SETTINGS, projectSettingsFolded: true };
33
34describe("fallbackTextGenerationModelSelection", () => {
35 it("uses Big Pickle when only OpenCode is enabled", () => {
36 expect(
37 fallbackTextGenerationModelSelection({}, (instanceId) => instanceId === "opencode"),
38 ).toEqual({ instanceId: "opencode", model: "opencode/big-pickle" });
39 });
40
41 it("replaces and clears the fallback without carrying model options", () => {
42 const fallbackModelSelection = { instanceId: ProviderInstanceId.make("codex"), model: "new" };
43 const settings = applyServerSettingsPatch(
44 {
45 ...DEFAULT_SERVER_SETTINGS,
46 fallbackModelSelection: {
47 ...fallbackModelSelection,
48 model: "old",
49 options: [{ id: "effort", value: "high" }],
50 },
51 },
52 { fallbackModelSelection },
53 );
54 expect(settings.fallbackModelSelection).toEqual(fallbackModelSelection);
55 expect(
56 applyServerSettingsPatch(settings, { fallbackModelSelection: null }).fallbackModelSelection,
57 ).toBeNull();
58 });
59 it("ignores a configured non-default instance at machine scope, matching no fallback", () => {
60 const configured = ProviderInstanceId.make("codex_work");
61 const providerInstances = {
62 [configured]: { driver: ProviderDriverKind.make("codex"), config: {} },
63 };
64 const fallback = fallbackTextGenerationModelSelection(
65 providerInstances,
66 (instanceId) => instanceId === configured,
67 );
68 expect(fallback).toBeNull();
69 });
70
71 it("considers a configured non-default instance only when asked to", () => {
72 const configured = ProviderInstanceId.make("codex_work");
73 const providerInstances = {
74 [configured]: { driver: ProviderDriverKind.make("codex"), config: {} },
75 };
76 const fallback = fallbackTextGenerationModelSelection(
77 providerInstances,
78 (instanceId) => instanceId === configured,
79 { includeConfiguredInstances: true },
80 );
81 expect(fallback?.instanceId).toBe(configured);
82 });
83});
84
85describe("serverSettings helpers", () => {
86 it("translates a shipped client's idle compaction switch into a mode", () => {
87 const off = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, { idleCompaction: "off" });
88 expect([off.idleCompaction, off.compactIdleThreads]).toEqual(["off", false]);
89 // Turning the old switch off keeps "Never" instead of reverting to the default.
90 const stillOff = applyServerSettingsPatch(off, { compactIdleThreads: false });
91 expect(stillOff.idleCompaction).toBe("off");
92 const on = applyServerSettingsPatch(off, { compactIdleThreads: true });
93 expect([on.idleCompaction, on.compactIdleThreads]).toEqual(["beforeCacheExpires", true]);
94 });
95
96 it("changes a cleanup rule without replacing the machine's other rules", () => {
97 const enabled = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
98 storageCleanup: { worktreeAfterDays: 8, worktreeOnMerge: true, logsAfterDays: 30 },
99 });
100 expect(
101 applyServerSettingsPatch(enabled, {
102 storageCleanup: { worktreeAfterDays: null },
103 }).storageCleanup,
104 ).toEqual({
105 worktreeAfterDays: null,
106 worktreeSettledAfterDays: null,
107 worktreeOnMerge: true,
108 worktreeOnDelete: false,
109 worktreeUnchanged: false,
110 worktreeKeepWhen: "uncommitted-changes",
111 browserArtifactsAfterDays: null,
112 logsAfterDays: 30,
113 });
114 });
115 it("replaces a source control host's patched field so a cleared account pin does not survive", () => {
116 const pinned = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
117 sourceControlHosts: {
118 github: { hosts: { "github.com": { account: "work", enabled: true } }, tokens: {} },
119 },
120 });
121 const unpinned = applyServerSettingsPatch(pinned, {
122 sourceControlHosts: { github: { hosts: { "github.com": { enabled: false } } } },
123 });
124 expect(unpinned.sourceControlHosts.github).toEqual({
125 hosts: { "github.com": { enabled: false } },
126 tokens: {},
127 });
128 });
129
130 it("keeps a source control host's saved tokens when a patch sets another host's token", () => {
131 const reference = { provider: "vault", reference: "github/token" };
132 const saved = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
133 sourceControlHosts: { github: { tokens: { "github.com": reference } } },
134 });
135 const patched = applyServerSettingsPatch(saved, {
136 sourceControlHosts: { github: { tokens: { "ghe.example": "x" } } },
137 });
138 expect(patched.sourceControlHosts.github?.tokens).toEqual({
139 "github.com": reference,
140 "ghe.example": "x",
141 });
142 const recased = applyServerSettingsPatch(saved, {
143 sourceControlHosts: { github: { tokens: { " GitHub.com ": "ghp_new" } } },
144 });
145 expect(recased.sourceControlHosts.github?.tokens).toEqual({ "github.com": "ghp_new" });
146 });
147
148 it("inherits actions, preserves existing actions, and supports empty overrides and reset", () => {
149 const project = { id: ProjectId.make("project-actions"), scripts: [] };
150 const action = {
151 id: "check",
152 name: "Check",
153 command: "npm test",
154 icon: "play" as const,
155 runOnWorktreeCreate: false,
156 };
157 const existing = { ...project, scripts: [{ ...action, command: "npm run lint" }] };
158 const unfolded = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
159 defaultProjectScripts: [action],
160 });
161 expect(resolveProjectScripts(unfolded, existing)).toEqual(existing.scripts);
162 const defaults = applyServerSettingsPatch(FOLDED_SERVER_SETTINGS, {
163 defaultProjectScripts: [action],
164 });
165 expect(resolveProjectScripts(defaults, project)).toEqual([action]);
166 expect(resolveProjectScripts(defaults, existing)).toEqual([action]);
167 const disabled = applyServerSettingsPatch(defaults, {
168 projectScriptOverrides: { [project.id]: [] },
169 });
170 expect(resolveProjectScripts(disabled, project)).toEqual([]);
171 const changedDefault = applyServerSettingsPatch(disabled, {
172 defaultProjectScripts: [{ ...action, command: "npm run build" }],
173 });
174 expect(resolveProjectScripts(changedDefault, project)).toEqual([]);
175 const reset = applyServerSettingsPatch(changedDefault, {
176 projectScriptOverrides: { [project.id]: null },
177 });
178 expect(resolveProjectScripts(reset, existing)).toEqual(changedDefault.defaultProjectScripts);
179 expect(
180 resolveProjectScripts(
181 applyServerSettingsPatch(reset, { defaultProjectScripts: [] }),
182 existing,
183 ),
184 ).toEqual([]);
185 });
186
187 it("preserves other projects' actions when overriding, clearing, or resetting one project", () => {
188 const firstProject = { id: ProjectId.make("first-project"), scripts: [] };
189 const secondProject = { id: ProjectId.make("second-project"), scripts: [] };
190 const defaultAction = {
191 id: "check",
192 name: "Check",
193 command: "npm test",
194 icon: "play" as const,
195 runOnWorktreeCreate: false,
196 };
197 const firstAction = { ...defaultAction, command: "npm run lint" };
198 const secondAction = { ...defaultAction, command: "npm run build" };
199 const firstUpdate = applyServerSettingsPatch(FOLDED_SERVER_SETTINGS, {
200 defaultProjectScripts: [defaultAction],
201 projectScriptOverrides: { [firstProject.id]: [firstAction] },
202 });
203 const secondUpdate = applyServerSettingsPatch(firstUpdate, {
204 projectScriptOverrides: { [secondProject.id]: [secondAction] },
205 });
206 expect(resolveProjectScripts(secondUpdate, firstProject)).toEqual([firstAction]);
207 expect(resolveProjectScripts(secondUpdate, secondProject)).toEqual([secondAction]);
208
209 const cleared = applyServerSettingsPatch(secondUpdate, {
210 projectScriptOverrides: { [firstProject.id]: [] },
211 });
212 expect(resolveProjectScripts(cleared, firstProject)).toEqual([]);
213 expect(resolveProjectScripts(cleared, secondProject)).toEqual([secondAction]);
214
215 const reset = applyServerSettingsPatch(cleared, {
216 projectScriptOverrides: { [firstProject.id]: null },
217 });
218 expect(resolveProjectScripts(reset, { ...firstProject, scripts: [firstAction] })).toEqual([
219 defaultAction,
220 ]);
221 expect(resolveProjectScripts(reset, secondProject)).toEqual([secondAction]);
222 expect(resolveProjectScripts(secondUpdate, firstProject)).toEqual([firstAction]);
223 });
224
225 it("preserves other projects' boolean overrides across separate updates and resets", () => {
226 const firstProjectId = ProjectId.make("first-project");
227 const secondProjectId = ProjectId.make("second-project");
228 const firstUpdate = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
229 defaultAutoPull: true,
230 projectAutoPullOverrides: { [firstProjectId]: false },
231 projectAgentBrowserAccessOverrides: { [firstProjectId]: false },
232 });
233 const secondUpdate = applyServerSettingsPatch(firstUpdate, {
234 projectAutoPullOverrides: { [secondProjectId]: false },
235 projectAgentBrowserAccessOverrides: { [secondProjectId]: false },
236 });
237 expect(secondUpdate.projectAutoPullOverrides).toEqual({
238 [firstProjectId]: false,
239 [secondProjectId]: false,
240 });
241 expect(secondUpdate.projectAgentBrowserAccessOverrides).toEqual({
242 [firstProjectId]: false,
243 [secondProjectId]: false,
244 });
245
246 const reset = applyServerSettingsPatch(secondUpdate, {
247 projectAutoPullOverrides: { [firstProjectId]: null },
248 projectAgentBrowserAccessOverrides: { [firstProjectId]: null },
249 });
250 expect(reset.projectAutoPullOverrides[firstProjectId]).toBeUndefined();
251 expect(reset.projectAgentBrowserAccessOverrides[firstProjectId]).toBeUndefined();
252 expect(reset.projectAutoPullOverrides[secondProjectId]).toBe(false);
253 expect(reset.projectAgentBrowserAccessOverrides[secondProjectId]).toBe(false);
254 expect(secondUpdate.projectAutoPullOverrides[firstProjectId]).toBe(false);
255 expect(secondUpdate.projectAgentBrowserAccessOverrides[firstProjectId]).toBe(false);
256 });
257
258 it("parses lenient persisted settings JSON and trims observability URLs", () => {
259 expect(
260 parsePersistedServerObservabilitySettings(
261 JSON.stringify({
262 observability: {
263 otlpTracesUrl: " http://localhost:4318/v1/traces ",
264 otlpMetricsUrl: " http://localhost:4318/v1/metrics ",
265 otlpLogsUrl: " http://localhost:4318/v1/logs ",
266 },
267 }),
268 ),
269 ).toEqual({
270 otlpTracesUrl: "http://localhost:4318/v1/traces",
271 otlpMetricsUrl: "http://localhost:4318/v1/metrics",
272 otlpLogsUrl: "http://localhost:4318/v1/logs",
273 });
274 });
275
276 it("falls back cleanly when persisted settings are invalid", () => {
277 expect(parsePersistedServerObservabilitySettings("{")).toEqual({
278 otlpTracesUrl: undefined,
279 otlpMetricsUrl: undefined,
280 otlpLogsUrl: undefined,
281 });
282 });
283
284 it("still deep merges text generation selection when only options are provided", () => {
285 const current = {
286 ...DEFAULT_SERVER_SETTINGS,
287 textGenerationModelSelection: createModelSelection(
288 ProviderInstanceId.make("codex"),
289 "gpt-5.4-mini",
290 [
291 { id: "reasoningEffort", value: "high" },
292 { id: "fastMode", value: true },
293 ],
294 ),
295 };
296
297 expect(
298 applyServerSettingsPatch(current, {
299 textGenerationModelSelection: {
300 options: [{ id: "fastMode", value: false }],
301 },
302 }).textGenerationModelSelection,
303 ).toEqual({
304 instanceId: "codex",
305 model: "gpt-5.4-mini",
306 options: [
307 { id: "reasoningEffort", value: "high" },
308 { id: "fastMode", value: false },
309 ],
310 });
311 });
312
313 it("replaces text generation selection across providers without leaking stale options", () => {
314 const current = {
315 ...DEFAULT_SERVER_SETTINGS,
316 textGenerationModelSelection: createModelSelection(
317 ProviderInstanceId.make("codex"),
318 "gpt-5.4-mini",
319 [
320 { id: "reasoningEffort", value: "high" },
321 { id: "fastMode", value: true },
322 ],
323 ),
324 };
325
326 expect(
327 applyServerSettingsPatch(current, {
328 textGenerationModelSelection: {
329 instanceId: ProviderInstanceId.make("opencode"),
330 model: "openai/gpt-5",
331 },
332 }).textGenerationModelSelection,
333 ).toEqual({
334 instanceId: "opencode",
335 model: "openai/gpt-5",
336 });
337 });
338
339 it("falls back from a disabled source control writer provider without clearing its selection", () => {
340 const instanceId = ProviderInstanceId.make("codex_writer");
341 const sourceControlWriterModelSelection = createModelSelection(instanceId, "gpt-5.4-mini");
342 const settings = {
343 ...DEFAULT_SERVER_SETTINGS,
344 providerInstances: {
345 [instanceId]: {
346 driver: ProviderDriverKind.make("codex"),
347 enabled: false,
348 config: {},
349 },
350 },
351 sourceControlWriterModelSelection,
352 };
353
354 expect(isModelSelectionProviderEnabled(settings, sourceControlWriterModelSelection)).toBe(
355 false,
356 );
357 expect(resolveSourceControlWriterModelSelection(settings, undefined, null)).toBe(
358 settings.textGenerationModelSelection,
359 );
360 expect(settings.sourceControlWriterModelSelection).toBe(sourceControlWriterModelSelection);
361 });
362
363 it("falls back from a writer provider that cannot generate application text", () => {
364 const instanceId = ProviderInstanceId.make("acp_writer");
365 const sourceControlWriterModelSelection = createModelSelection(instanceId, "default");
366 const settings = {
367 ...DEFAULT_SERVER_SETTINGS,
368 providerInstances: {
369 [instanceId]: {
370 driver: ProviderDriverKind.make("acpRegistry"),
371 enabled: true,
372 config: {},
373 },
374 },
375 sourceControlWriterModelSelection,
376 };
377 const incapableProvider = {
378 instanceId,
379 driver: ProviderDriverKind.make("acpRegistry"),
380 supportsTextGeneration: false,
381 enabled: true,
382 installed: true,
383 version: null,
384 status: "ready",
385 auth: { status: "authenticated" },
386 checkedAt: "2026-07-27T00:00:00.000Z",
387 models: [],
388 slashCommands: [],
389 skills: [],
390 } satisfies ServerProvider;
391
392 expect(resolveSourceControlWriterModelSelection(settings, [incapableProvider], null)).toBe(
393 settings.textGenerationModelSelection,
394 );
395 expect(settings.sourceControlWriterModelSelection).toBe(sourceControlWriterModelSelection);
396 });
397
398 it("falls back from a writer provider a project turned off, keeping it for other projects", () => {
399 const instanceId = ProviderInstanceId.make("codex_writer");
400 const projectId = ProjectId.make("project-a");
401 const sourceControlWriterModelSelection = createModelSelection(instanceId, "gpt-5.4-mini");
402 const settings = {
403 ...DEFAULT_SERVER_SETTINGS,
404 providerInstances: {
405 [instanceId]: { driver: ProviderDriverKind.make("codex"), enabled: true, config: {} },
406 },
407 projectSettingsOverrides: {
408 [projectId]: { providerInstances: { [instanceId]: { enabled: false } } },
409 },
410 sourceControlWriterModelSelection,
411 };
412 const provider = {
413 instanceId,
414 driver: ProviderDriverKind.make("codex"),
415 enabled: true,
416 installed: true,
417 version: null,
418 status: "ready",
419 auth: { status: "authenticated" },
420 checkedAt: "2026-07-27T00:00:00.000Z",
421 availability: "available",
422 models: [],
423 slashCommands: [],
424 skills: [],
425 } satisfies ServerProvider;
426
427 expect(resolveSourceControlWriterModelSelection(settings, [provider], projectId)).toBe(
428 settings.textGenerationModelSelection,
429 );
430 expect(resolveSourceControlWriterModelSelection(settings, [provider], null)).toBe(
431 sourceControlWriterModelSelection,
432 );
433 });
434
435 it("keeps a writer on an instance the project turned on while the machine has it off", () => {
436 const instanceId = ProviderInstanceId.make("codex_writer");
437 const projectId = ProjectId.make("project-a");
438 const sourceControlWriterModelSelection = createModelSelection(instanceId, "gpt-5.4-mini");
439 const settings = {
440 ...DEFAULT_SERVER_SETTINGS,
441 providerInstances: {
442 [instanceId]: { driver: ProviderDriverKind.make("codex"), enabled: false, config: {} },
443 },
444 projectSettingsOverrides: {
445 [projectId]: { providerInstances: { [instanceId]: { enabled: true } } },
446 },
447 sourceControlWriterModelSelection,
448 };
449 const provider = {
450 instanceId,
451 driver: ProviderDriverKind.make("codex"),
452 enabled: true,
453 installed: true,
454 version: null,
455 status: "ready",
456 auth: { status: "authenticated" },
457 checkedAt: "2026-07-27T00:00:00.000Z",
458 availability: "available",
459 models: [],
460 slashCommands: [],
461 skills: [],
462 } satisfies ServerProvider;
463
464 expect(resolveSourceControlWriterModelSelection(settings, [provider], projectId)).toBe(
465 sourceControlWriterModelSelection,
466 );
467 expect(resolveSourceControlWriterModelSelection(settings, [provider], null)).toBe(
468 settings.textGenerationModelSelection,
469 );
470 });
471
472 it("replaces providerInstances maps so omitted instance fields are cleared", () => {
473 const codexId = ProviderInstanceId.make("codex");
474 const current = {
475 ...DEFAULT_SERVER_SETTINGS,
476 providerInstances: {
477 [codexId]: {
478 driver: ProviderDriverKind.make("codex"),
479 displayName: "Codex Work",
480 accentColor: "#7c3aed",
481 enabled: true,
482 config: { homePath: "~/.codex" },
483 },
484 },
485 };
486
487 expect(
488 applyServerSettingsPatch(current, {
489 providerInstances: {
490 [codexId]: {
491 driver: ProviderDriverKind.make("codex"),
492 displayName: "Codex Work",
493 enabled: true,
494 config: { homePath: "~/.codex" },
495 },
496 },
497 }).providerInstances[codexId],
498 ).toEqual({
499 driver: ProviderDriverKind.make("codex"),
500 displayName: "Codex Work",
501 enabled: true,
502 config: { homePath: "~/.codex" },
503 });
504 });
505
506 it("keeps a project's providerInstances override when a patch entry omits the key", () => {
507 const instanceId = ProviderInstanceId.make("codex_work");
508 const projectId = ProjectId.make("project-a");
509 const current = {
510 ...DEFAULT_SERVER_SETTINGS,
511 projectSettingsOverrides: {
512 [projectId]: {
513 newWorktreesStartFromOrigin: true,
514 providerInstances: { [instanceId]: { enabled: false } },
515 },
516 },
517 };
518
519 const patched = applyServerSettingsPatch(current, {
520 projectSettingsOverrides: {
521 [projectId]: { newWorktreesStartFromOrigin: false },
522 },
523 });
524
525 expect(patched.projectSettingsOverrides[projectId]).toEqual({
526 newWorktreesStartFromOrigin: false,
527 providerInstances: { [instanceId]: { enabled: false } },
528 });
529 });
530
531 // regression: #18334 a newer client must still see this server drop a key it does not know
532 it("drops an override key this server does not know from a patch and keeps one it stored", () => {
533 const projectId = ProjectId.make("project-a");
534 const current = decodeServerSettings({
535 projectSettingsFolded: true,
536 projectSettingsOverrides: {
537 [projectId]: { defaultAutoPull: true, addedByNewerServer: 3 },
538 },
539 });
540 const patch = decodeServerSettingsPatch({
541 projectSettingsOverrides: {
542 [projectId]: { defaultAutoPull: false, addedByNewerServer: 4, addedByNewerClient: "x" },
543 },
544 });
545
546 const updated = applyServerSettingsPatch(current, patch);
547 expect(updated.projectSettingsOverrides[projectId]).toEqual({
548 defaultAutoPull: false,
549 addedByNewerServer: 3,
550 });
551 const reset = applyServerSettingsPatch(updated, {
552 projectSettingsOverrides: { [projectId]: {} },
553 });
554 expect(reset.projectSettingsOverrides[projectId]).toEqual({ addedByNewerServer: 3 });
555 expect(
556 applyServerSettingsPatch(reset, {
557 projectSettingsOverrides: { [projectId]: null },
558 }).projectSettingsOverrides[projectId],
559 ).toBeUndefined();
560 });
561
562 it("clears a project's providerInstances override when a patch entry sends an empty map", () => {
563 const instanceId = ProviderInstanceId.make("codex_work");
564 const projectId = ProjectId.make("project-a");
565 const current = {
566 ...DEFAULT_SERVER_SETTINGS,
567 projectSettingsOverrides: {
568 [projectId]: {
569 newWorktreesStartFromOrigin: true,
570 providerInstances: { [instanceId]: { enabled: false } },
571 },
572 },
573 };
574
575 const patched = applyServerSettingsPatch(current, {
576 projectSettingsOverrides: {
577 [projectId]: { newWorktreesStartFromOrigin: true, providerInstances: {} },
578 },
579 });
580
581 expect(patched.projectSettingsOverrides[projectId]).toEqual({
582 newWorktreesStartFromOrigin: true,
583 providerInstances: {},
584 });
585 });
586
587 it("upserts and removes usageLimitSources per entry so concurrent edits cannot clobber", () => {
588 const hubA = UsageLimitSourceId.make("cliproxy-a");
589 const hubB = UsageLimitSourceId.make("cliproxy-b");
590 const source = (url: string) => ({
591 kind: "cliproxy" as const,
592 url,
593 managementKey: "secret",
594 enabled: true,
595 });
596 const current = {
597 ...DEFAULT_SERVER_SETTINGS,
598 usageLimitSources: { [hubA]: source("http://a:8318") },
599 };
600
601 const added = applyServerSettingsPatch(current, {
602 usageLimitSources: { [hubB]: source("http://b:8318") },
603 });
604 expect(Object.keys(added.usageLimitSources)).toEqual([hubA, hubB]);
605
606 const removed = applyServerSettingsPatch(added, { usageLimitSources: { [hubA]: null } });
607 expect(Object.keys(removed.usageLimitSources)).toEqual([hubB]);
608 });
609
610 it("upserts and removes secretProviders per entry so concurrent edits cannot clobber", () => {
611 const personal = SecretProviderId.make("personal");
612 const work = SecretProviderId.make("work");
613 const onePassword = (label: string, account: string) => ({
614 kind: SecretProviderKind.make("one_password"),
615 label,
616 config: { account },
617 });
618 const current = {
619 ...DEFAULT_SERVER_SETTINGS,
620 secretProviders: { [personal]: onePassword("Personal", "my.1password.com") },
621 };
622
623 const added = applyServerSettingsPatch(current, {
624 secretProviders: { [work]: onePassword("Work", "team.1password.com") },
625 });
626 expect(Object.keys(added.secretProviders)).toEqual([personal, work]);
627
628 const removed = applyServerSettingsPatch(added, { secretProviders: { [personal]: null } });
629 expect(Object.keys(removed.secretProviders)).toEqual([work]);
630 });
631
632 it("replaces and removes individual usage prices without clobbering other models", () => {
633 const prices = { inputCostPerMillionTokens: 2, outputCostPerMillionTokens: 8 };
634 const current = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
635 usagePriceOverrides: { "example-model": { ...prices, cacheReadCostPerMillionTokens: 0.5 } },
636 });
637 const added = applyServerSettingsPatch(current, {
638 usagePriceOverrides: { "other-model": prices },
639 });
640 const replaced = applyServerSettingsPatch(added, {
641 usagePriceOverrides: { "example-model": prices },
642 });
643 expect(replaced.usagePriceOverrides).toEqual({
644 "example-model": prices,
645 "other-model": prices,
646 });
647 const removed = applyServerSettingsPatch(replaced, {
648 usagePriceOverrides: { "example-model": null },
649 });
650 expect(removed.usagePriceOverrides).toEqual({ "other-model": prices });
651 expect(current.usagePriceOverrides["example-model"]?.cacheReadCostPerMillionTokens).toBe(0.5);
652 });
653
654 it("stores background activity profiles as a versioned object and syncs legacy aliases", () => {
655 const next = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
656 backgroundActivity: {
657 schemaVersion: 1,
658 profile: "battery-saver",
659 overrides: {},
660 },
661 });
662
663 expect(next.backgroundActivity).toEqual({
664 schemaVersion: 1,
665 profile: "battery-saver",
666 overrides: {},
667 });
668 expect(next.backgroundActivityProfile).toBe("battery-saver");
669 expect(Duration.toMillis(next.automaticGitFetchInterval)).toBe(0);
670 expect(Duration.toMillis(next.providerHealthRefreshInterval)).toBe(
671 Duration.toMillis(Duration.minutes(15)),
672 );
673 });
674
675 it("turns legacy interval patches into custom background activity overrides", () => {
676 const next = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
677 automaticGitFetchInterval: Duration.seconds(15),
678 });
679
680 expect(next.backgroundActivity).toEqual({
681 schemaVersion: 1,
682 profile: "custom",
683 baseProfile: "balanced",
684 overrides: {
685 automaticGitFetchInterval: Duration.seconds(15),
686 },
687 });
688 expect(resolveServerBackgroundActivitySettings(next).profile).toBe("balanced");
689 expect(
690 Duration.toMillis(resolveServerBackgroundActivitySettings(next).automaticGitFetchInterval),
691 ).toBe(15_000);
692 });
693
694 it("preserves legacy background activity settings when applying an unrelated patch", () => {
695 const current = {
696 ...DEFAULT_SERVER_SETTINGS,
697 backgroundActivityProfile: "performance" as const,
698 automaticGitFetchInterval: Duration.seconds(7),
699 providerHealthRefreshInterval: Duration.minutes(4),
700 };
701
702 const next = applyServerSettingsPatch(current, {
703 sourceControlWriterModelSelection: createModelSelection(
704 ProviderInstanceId.make("codex"),
705 "gpt-5.4-mini",
706 ),
707 });
708
709 expect(next.backgroundActivity).toEqual({
710 schemaVersion: 1,
711 profile: "custom",
712 baseProfile: "performance",
713 overrides: {
714 automaticGitFetchInterval: Duration.seconds(7),
715 providerHealthRefreshInterval: Duration.minutes(4),
716 },
717 });
718 expect(next.backgroundActivityProfile).toBe("performance");
719 expect(Duration.toMillis(next.automaticGitFetchInterval)).toBe(7_000);
720 expect(Duration.toMillis(next.providerHealthRefreshInterval)).toBe(240_000);
721 });
722
723 it("does not reactivate dormant overrides from a concrete profile", () => {
724 const current = {
725 ...DEFAULT_SERVER_SETTINGS,
726 backgroundActivity: {
727 schemaVersion: 1 as const,
728 profile: "battery-saver" as const,
729 overrides: {
730 providerHealthRefreshInterval: Duration.seconds(5),
731 },
732 },
733 };
734
735 const next = applyServerSettingsPatch(current, {
736 automaticGitFetchInterval: Duration.seconds(15),
737 });
738
739 expect(next.backgroundActivity).toEqual({
740 schemaVersion: 1,
741 profile: "custom",
742 baseProfile: "battery-saver",
743 overrides: {
744 automaticGitFetchInterval: Duration.seconds(15),
745 },
746 });
747 });
748
749 it("prefers structured background activity settings over legacy aliases", () => {
750 const next = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
751 backgroundActivity: {
752 schemaVersion: 1,
753 profile: "battery-saver",
754 overrides: {},
755 },
756 automaticGitFetchInterval: Duration.seconds(5),
757 backgroundActivityProfile: "performance",
758 });
759
760 expect(next.backgroundActivity).toEqual({
761 schemaVersion: 1,
762 profile: "battery-saver",
763 overrides: {},
764 });
765 expect(next.backgroundActivityProfile).toBe("battery-saver");
766 expect(Duration.toMillis(next.automaticGitFetchInterval)).toBe(0);
767 });
768
769 it("reconciles custom background activity back to a preset when overrides match the preset", () => {
770 const custom = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
771 automaticGitFetchInterval: Duration.seconds(15),
772 });
773 const next = applyServerSettingsPatch(custom, {
774 automaticGitFetchInterval: Duration.seconds(30),
775 });
776
777 expect(next.backgroundActivity).toEqual({
778 schemaVersion: 1,
779 profile: "balanced",
780 overrides: {},
781 });
782 expect(next.backgroundActivityProfile).toBe("balanced");
783 expect(Duration.toMillis(next.automaticGitFetchInterval)).toBe(30_000);
784 });
785
786 it("replaces the complete background override record", () => {
787 const current = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
788 backgroundActivity: {
789 schemaVersion: 1,
790 profile: "custom",
791 baseProfile: "balanced",
792 overrides: {
793 automaticGitFetchInterval: Duration.seconds(15),
794 providerHealthRefreshInterval: Duration.minutes(3),
795 },
796 },
797 });
798
799 const next = applyServerSettingsPatch(current, {
800 backgroundActivity: {
801 overrides: {
802 automaticGitFetchInterval: Duration.seconds(10),
803 },
804 },
805 });
806
807 expect(next.backgroundActivity).toEqual({
808 schemaVersion: 1,
809 profile: "custom",
810 baseProfile: "balanced",
811 overrides: {
812 automaticGitFetchInterval: Duration.seconds(10),
813 },
814 });
815 });
816
817 it("keeps interval overrides supplied with a profile patch", () => {
818 const next = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
819 backgroundActivityProfile: "performance",
820 automaticGitFetchInterval: Duration.seconds(0),
821 providerHealthRefreshInterval: Duration.minutes(4),
822 });
823
824 expect(next.backgroundActivity).toEqual({
825 schemaVersion: 1,
826 profile: "custom",
827 baseProfile: "performance",
828 overrides: {
829 automaticGitFetchInterval: Duration.seconds(0),
830 providerHealthRefreshInterval: Duration.minutes(4),
831 },
832 });
833 });
834});
835
836describe("worktreesDirectory", () => {
837 it("remembers previous custom locations so their worktrees stay managed", () => {
838 const first = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, { worktreesDirectory: "/a" });
839 expect(first.previousWorktreesDirectories).toEqual([]);
840 const second = applyServerSettingsPatch(first, { worktreesDirectory: "/b" });
841 expect(second.previousWorktreesDirectories).toEqual(["/a"]);
842 const reset = applyServerSettingsPatch(second, { worktreesDirectory: "" });
843 expect(reset.previousWorktreesDirectories).toEqual(["/a", "/b"]);
844 const back = applyServerSettingsPatch(reset, { worktreesDirectory: "/a" });
845 expect(back.previousWorktreesDirectories).toEqual(["/b"]);
846 });
847});
848
849describe("synchronized model preferences", () => {
850 it("supports provider identifiers that match inherited object keys", () => {
851 const provider = ProviderInstanceId.make("toString");
852 const next = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
853 setModelsHidden: [{ provider, model: "example", hidden: true }],
854 });
855 expect(next.providerModelPreferences?.[provider]?.hiddenModels).toEqual(["example"]);
856 });
857 const provider = ProviderInstanceId.make("codex_work");
858 const legacy = {
859 favorites: [{ provider, model: "sol" }],
860 providerModelPreferences: { [provider]: { hiddenModels: ["astra"], modelOrder: ["sol"] } },
861 };
862
863 it("keeps concurrent adds and removes of the same favorite idempotent", () => {
864 const add = { setModelFavorites: [{ provider, model: "sol", favorite: true }] };
865 const first = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, add);
866 expect(applyServerSettingsPatch(first, add).favorites).toEqual([{ provider, model: "sol" }]);
867 const remove = { setModelFavorites: [{ provider, model: "sol", favorite: false }] };
868 const removed = applyServerSettingsPatch(first, remove);
869 expect(applyServerSettingsPatch(removed, remove).favorites).toEqual([]);
870 expect(first.favorites).toEqual([{ provider, model: "sol" }]);
871 });
872
873 it("preserves unrelated models and providers during bulk visibility and order edits", () => {
874 const otherProvider = ProviderInstanceId.make("claude_work");
875 const initial = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
876 providerModelPreferences: {
877 ...legacy.providerModelPreferences,
878 [otherProvider]: { hiddenModels: ["opus"], modelOrder: ["sonnet", "opus"] },
879 },
880 });
881 const mobile = applyServerSettingsPatch(initial, {
882 setModelsHidden: [{ provider, model: "luna", hidden: true }],
883 });
884 const web = applyServerSettingsPatch(mobile, {
885 setModelsHidden: [
886 { provider, model: "astra", hidden: false },
887 { provider, model: "sol", hidden: true },
888 ],
889 setProviderModelOrder: { provider, modelOrder: ["sol", "luna", "astra"] },
890 });
891 expect(initial.providerModelPreferences?.[provider]).toEqual(
892 legacy.providerModelPreferences[provider],
893 );
894 expect(web.providerModelPreferences?.[provider]).toEqual({
895 hiddenModels: ["luna", "sol"],
896 modelOrder: ["sol", "luna", "astra"],
897 });
898 expect(web.providerModelPreferences?.[otherProvider]).toEqual(
899 initial.providerModelPreferences?.[otherProvider],
900 );
901 expect(
902 applyServerSettingsPatch(web, {
903 setProviderModelOrder: { provider, modelOrder: [] },
904 }).providerModelPreferences?.[provider],
905 ).toEqual({ hiddenModels: ["luna", "sol"], modelOrder: [] });
906 });
907
908 it("migrates saved lists independently without claiming empty legacy lists", () => {
909 expect(modelPreferencesMigrationPatch(DEFAULT_SERVER_SETTINGS, {})).toBeNull();
910 const patch = modelPreferencesMigrationPatch(DEFAULT_SERVER_SETTINGS, legacy)!;
911 const migrated = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, patch);
912 expect(resolveModelPreferences(migrated)).toEqual(legacy);
913 expect(modelPreferencesMigrationPatch(migrated, legacy)).toBeNull();
914 const favoritesOnly = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, { favorites: [] });
915 expect(modelPreferencesMigrationPatch(favoritesOnly, legacy)).toEqual({
916 migrateModelPreferences: { providerModelPreferences: legacy.providerModelPreferences },
917 });
918 });
919
920 it("keeps explicit clears when a delayed migration arrives from another device", () => {
921 const staleMigration = modelPreferencesMigrationPatch(DEFAULT_SERVER_SETTINGS, legacy)!;
922 const cleared = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
923 favorites: [],
924 providerModelPreferences: {},
925 });
926 expect(
927 resolveModelPreferences(applyServerSettingsPatch(cleared, staleMigration), legacy),
928 ).toEqual({
929 favorites: [],
930 providerModelPreferences: {},
931 });
932 });
933
934 it("replaces visibility records so showing every model clears removed entries", () => {
935 const migrated = applyServerSettingsPatch(
936 DEFAULT_SERVER_SETTINGS,
937 modelPreferencesMigrationPatch(DEFAULT_SERVER_SETTINGS, legacy)!,
938 );
939 const cleared = applyServerSettingsPatch(migrated, { providerModelPreferences: {} });
940 expect(cleared.providerModelPreferences).toEqual({});
941 expect(cleared.favorites).toEqual(legacy.favorites);
942 });
943
944 it("sets favorites without losing changes from other clients", () => {
945 const first = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
946 setModelFavorites: [{ provider, model: "sol", favorite: true }],
947 });
948 const second = applyServerSettingsPatch(first, {
949 setModelFavorites: [{ provider, model: "astra", favorite: true }],
950 migrateModelPreferences: { favorites: [] },
951 });
952 expect(second.favorites).toEqual([
953 { provider, model: "sol" },
954 { provider, model: "astra" },
955 ]);
956 const removed = applyServerSettingsPatch(second, {
957 setModelFavorites: [{ provider, model: "sol", favorite: false }],
958 });
959 expect(removed.favorites).toEqual([{ provider, model: "astra" }]);
960 expect(
961 applyServerSettingsPatch(removed, {
962 setModelFavorites: [{ provider, model: "astra", favorite: false }],
963 }).favorites,
964 ).toEqual([]);
965 });
966
967 it("keeps the same model on different provider instances as separate favorites", () => {
968 const otherProvider = ProviderInstanceId.make("codex_personal");
969 const first = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
970 setModelFavorites: [{ provider, model: "sol", favorite: true }],
971 });
972 const second = applyServerSettingsPatch(first, {
973 setModelFavorites: [{ provider: otherProvider, model: "sol", favorite: true }],
974 });
975 expect(second.favorites).toEqual([
976 { provider, model: "sol" },
977 { provider: otherProvider, model: "sol" },
978 ]);
979 expect(
980 applyServerSettingsPatch(second, {
981 setModelFavorites: [{ provider, model: "sol", favorite: false }],
982 }).favorites,
983 ).toEqual([{ provider: otherProvider, model: "sol" }]);
984 });
985});