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