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