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