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

serverSettings.test.ts

994 lines37.0 KB

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