Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

serverSettings.test.ts

1,156 lines42.7 KB

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