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