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