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

serverSettings.test.ts

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