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