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