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

serverSettings.test.ts

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