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

scopedSettings.test.ts

811 lines28.4 KB

1import {
2 DEFAULT_SERVER_SETTINGS,
3 EnvironmentAuthorizationError,
4 EnvironmentId,
5 ProjectId,
6 ProviderInstanceId,
7 type ServerSettings,
8} from "@t3tools/contracts";
9import { describe, expect, it, vi } from "vite-plus/test";
10import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
11import * as Cause from "effect/Cause";
12import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
13​
14import type { SidebarProjectSnapshot } from "../../sidebarProjectGrouping";
15import {
16 persistScopedSettingsPatch,
17 planProjectOverridesClear,
18 planScopedSettingsClear,
19 planScopedSettingsPatch,
20 scopedIdleCompaction,
21 resolveScopedSettingsTargets,
22 scopedSettingsAreMixed,
23 scopedSettingsSource,
24 selectScopedSettingsEnvironments,
25} from "./scopedSettings";
26import { resolveSettingsScope } from "./settingsScope";
27​
28function environment(
29 id: string,
30 options: {
31 connected?: boolean;
32 loaded?: boolean;
33 settings?: Partial<ServerSettings>;
34 } = {},
35) {
36 return {
37 environmentId: EnvironmentId.make(id),
38 label: id,
39 connection: {
40 phase: options.connected === false ? ("offline" as const) : ("connected" as const),
41 },
42 serverConfig:
43 options.loaded === false
44 ? null
45 : {
46 settings: { ...DEFAULT_SERVER_SETTINGS, ...options.settings },
47 },
48 };
50​
51const laptop = environment("Laptop");
52const server = environment("Server");
53const offline = environment("Offline", { connected: false });
54const loading = environment("Loading", { loaded: false });
55const environments = [laptop, server, offline, loading];
56const all = resolveSettingsScope({}, [], environments);
57const named = resolveSettingsScope({ machine: server.environmentId }, [], environments);
58​
59const projectId = ProjectId.make("project");
60const laptopProjectId = ProjectId.make("laptop-project");
61const member = {
62 id: projectId,
63 environmentId: server.environmentId,
64 title: "Project",
65 workspaceRoot: "/repo",
66 physicalProjectKey: `${server.environmentId}:/repo`,
67 environmentLabel: server.label,
68 defaultModelSelection: null,
69 scripts: [],
70 createdAt: "2026-09-07T00:00:00.000Z",
71 updatedAt: "2026-09-07T00:00:00.000Z",
72};
73const laptopMember = {
74 ...member,
75 id: laptopProjectId,
76 environmentId: laptop.environmentId,
77 physicalProjectKey: `${laptop.environmentId}:/repo`,
78 environmentLabel: laptop.label,
79};
80const group: SidebarProjectSnapshot = {
81 ...member,
82 projectKey: "project-group",
83 displayName: "Project",
84 memberProjects: [member, laptopMember],
85 memberProjectRefs: [
86 { environmentId: server.environmentId, projectId },
87 { environmentId: laptop.environmentId, projectId: laptopProjectId },
88 ],
89 groupedProjectCount: 2,
90 environmentPresence: "remote-only",
91 allRemoteMembersAreDesktopLocal: false,
92 allRemoteMembersAreWsl: false,
93 remoteEnvironmentLabels: [server.label, laptop.label],
94 pinned: false,
95 archived: false,
96};
97const project = resolveSettingsScope({ project: group.projectKey }, [group], environments);
98const checkout = resolveSettingsScope(
99 { project: group.projectKey, machine: server.environmentId, checkout: member.physicalProjectKey },
100 [group],
101 environments,
102);
103​
104describe("scoped settings targets", () => {
105 it("uses the named environment even when a different primary is available", () => {
106 const selected = selectScopedSettingsEnvironments(named, environments, laptop.environmentId);
107 expect(selected.environments).toEqual([server]);
108 expect(selected.environment).toBe(server);
109 });
110​
111 it("keeps an offline named environment selected without falling back to primary", () => {
112 const scope = resolveSettingsScope({ machine: offline.environmentId }, [], environments);
113 const selected = selectScopedSettingsEnvironments(scope, environments, laptop.environmentId);
114 expect(selected.environments).toEqual([offline]);
115 expect(selected.connectedEnvironments).toEqual([]);
116 expect(selected.environment).toBeNull();
117 expect(
118 planScopedSettingsPatch(scope, environments, { enableProviderUpdateChecks: false }),
119 ).toMatchObject({
120 serverWrites: [],
121 unavailableReason: "Connect Offline to save this setting.",
122 });
123 });
124​
125 it("resolves each member's effective settings and source at project scope", () => {
126 const overridden = environment("Server", {
127 settings: {
128 defaultAutoPull: false,
129 projectSettingsOverrides: { [projectId]: { defaultAutoPull: true } },
130 },
131 });
132 const targets = resolveScopedSettingsTargets(project, [laptop, overridden]);
133 expect(targets.map((target) => [target.projectId, target.settings.defaultAutoPull])).toEqual([
134 [projectId, true],
135 [laptopProjectId, false],
136 ]);
137 expect(scopedSettingsSource(targets, ["defaultAutoPull"])).toBe("mixed");
138 expect(scopedSettingsSource([targets[0]!], ["defaultAutoPull"])).toBe("project");
139 expect(scopedSettingsSource(targets, ["enableProviderUpdateChecks"])).toBe("environment");
140 expect(scopedSettingsAreMixed(targets, ["defaultAutoPull"])).toBe(true);
141 });
142});
143​
144describe("scoped settings writes", () => {
145 it("edits the effective machine policy without changing other machines' rules", () => {
146 const custom = environment("Laptop", {
147 settings: {
148 worktreeCleanup: {
149 mode: "custom",
150 rules: {
151 worktreeAfterDays: 12,
152 worktreeSettledAfterDays: null,
153 worktreeOnDelete: true,
154 worktreeOnMerge: true,
155 worktreeUnchanged: false,
156 worktreeKeepWhen: "uncommitted-changes",
157 },
158 },
159 },
160 });
161 const disabled = environment("Server", {
162 settings: { worktreeCleanup: { mode: "off" } },
163 });
164 const targets = [custom, disabled];
165 const plan = planScopedSettingsPatch(all, targets, {
166 storageCleanup: { worktreeOnDelete: false },
167 });
168 const policies = plan.serverWrites.map((write, index) =>
169 resolveWorktreeCleanup(
170 applyServerSettingsPatch(targets[index]!.serverConfig!.settings, write.patch),
171 null,
172 ),
173 );
174 expect(policies).toEqual([
175 {
176 worktreeAfterDays: 12,
177 worktreeSettledAfterDays: null,
178 worktreeOnDelete: false,
179 worktreeOnMerge: true,
180 worktreeUnchanged: false,
181 worktreeKeepWhen: "uncommitted-changes",
182 },
183 {
184 worktreeAfterDays: null,
185 worktreeSettledAfterDays: null,
186 worktreeOnDelete: false,
187 worktreeOnMerge: false,
188 worktreeUnchanged: false,
189 worktreeKeepWhen: "uncommitted-changes",
190 },
191 ]);
192 });
193​
194 it("compares idle compaction by mode, and offers Never only where every server stores it", () => {
195 const fixed = {
196 settings: {
197 ...DEFAULT_SERVER_SETTINGS,
198 compactIdleThreads: false,
199 idleCompaction: "onReturn" as const,
200 },
201 };
202 const modes = {
203 settings: { ...DEFAULT_SERVER_SETTINGS, compactIdleThreads: "onReturn" as const },
204 };
205 const legacy = { settings: { ...DEFAULT_SERVER_SETTINGS, compactIdleThreads: false } };
206 expect(scopedIdleCompaction([fixed, modes])).toEqual({ mixed: false, neverAvailable: true });
207 expect(scopedIdleCompaction([fixed, legacy])).toEqual({ mixed: false, neverAvailable: false });
208 expect(
209 scopedIdleCompaction([fixed, { settings: { ...fixed.settings, idleCompaction: "off" } }])
210 .mixed,
211 ).toBe(true);
212 });
213​
214 it("sends an idle compaction mode in the form each environment's server reads", () => {
215 const targets = [
216 environment("Fixed", { settings: { compactIdleThreads: false, idleCompaction: "onReturn" } }),
217 environment("Modes", { settings: { compactIdleThreads: "onReturn" } }),
218 environment("Switch", { settings: { compactIdleThreads: false } }),
219 ];
220 const plan = planScopedSettingsPatch(resolveSettingsScope({}, [], targets), targets, {
221 idleCompaction: "beforeCacheExpires",
222 });
223 expect(plan.serverWrites.map((write) => write.patch)).toEqual([
224 { idleCompaction: "beforeCacheExpires" },
225 { compactIdleThreads: "beforeCacheExpires" },
226 { compactIdleThreads: true },
227 ]);
228 });
229​
230 it("writes an aggregate preference only to connected environments with loaded configuration", async () => {
231 const persistServer = vi.fn().mockResolvedValue({ _tag: "Success" });
232 const persistClient = vi.fn();
233 await persistScopedSettingsPatch(
234 planScopedSettingsPatch(all, environments, { enableProviderUpdateChecks: false }),
235 persistServer,
236 persistClient,
237 );
238 expect(persistServer.mock.calls.map(([input]) => input.environmentId)).toEqual([
239 laptop.environmentId,
240 server.environmentId,
241 ]);
242 expect(persistClient).not.toHaveBeenCalled();
243 });
244​
245 describe("an environment that saves but drops keys it does not know", () => {
246 const upgradedLaptop = (saved: Partial<ServerSettings>) =>
247 vi.fn(async ({ environmentId }: { environmentId: EnvironmentId }) => ({
248 _tag: "Success" as const,
249 value: {
250 ...DEFAULT_SERVER_SETTINGS,
251 ...(environmentId === laptop.environmentId ? saved : {}),
252 },
253 }));
254 const outcome = async (
255 plan: ReturnType<typeof planScopedSettingsPatch>,
256 persistServer: ReturnType<typeof upgradedLaptop>,
257 ) => {
258 const result = await persistScopedSettingsPatch(plan, persistServer, vi.fn());
259 return {
260 saved: result.savedEnvironments.map(({ label }) => label),
261 failed: result.failedEnvironments.map(({ label, message }) => ({ label, message })),
262 };
263 };
264 const unsupported = [
265 {
266 label: server.label,
267 message: "This environment does not support this setting. Update T3 Code on it.",
268 },
269 ];
270​
271 it("reports a dropped toggle", async () => {
272 expect(
273 await outcome(
274 planScopedSettingsPatch(all, environments, { reviewGuidesEnabled: true }),
275 upgradedLaptop({ reviewGuidesEnabled: true }),
276 ),
277 ).toEqual({ saved: [laptop.label], failed: unsupported });
278 });
279​
280 it("reports dropped text but accepts the server trimming it", async () => {
281 expect(
282 await outcome(
283 planScopedSettingsPatch(all, environments, { reviewGuideInstructions: " Read tests " }),
284 upgradedLaptop({ reviewGuideInstructions: "Read tests" }),
285 ),
286 ).toEqual({ saved: [laptop.label], failed: unsupported });
287 });
288​
289 // regression: #18334 an environment silently dropped a setting with no warning
290 it("reports a dropped key inside a project override", async () => {
291 expect(
292 await outcome(
293 planScopedSettingsPatch(project, environments, { defaultAutoPull: true }),
294 upgradedLaptop({
295 projectSettingsOverrides: { [laptopProjectId]: { defaultAutoPull: true } },
296 }),
297 ),
298 ).toEqual({ saved: [laptop.label], failed: unsupported });
299 });
300​
301 it("accepts a write that matches what the environment already had", async () => {
302 expect(
303 await outcome(
304 planScopedSettingsPatch(all, environments, { reviewGuidesEnabled: false }),
305 upgradedLaptop({}),
306 ),
307 ).toEqual({ saved: [laptop.label, server.label], failed: [] });
308 });
309 });
310​
311 it("persists client keys locally at any scope alongside server keys", async () => {
312 const persistServer = vi.fn().mockResolvedValue({ _tag: "Success" });
313 const persistClient = vi.fn();
314 await persistScopedSettingsPatch(
315 planScopedSettingsPatch(named, environments, {
316 diffIgnoreWhitespace: false,
317 enableProviderUpdateChecks: false,
318 }),
319 persistServer,
320 persistClient,
321 );
322 expect(persistClient).toHaveBeenCalledExactlyOnceWith({ diffIgnoreWhitespace: false });
323 expect(persistServer).toHaveBeenCalledExactlyOnceWith({
324 environmentId: server.environmentId,
325 input: { patch: { enableProviderUpdateChecks: false } },
326 });
327 });
328​
329 it("writes project overrides into each member's entry on its environment", () => {
330 const withExisting = environment("Server", {
331 settings: {
332 projectSettingsOverrides: { [projectId]: { enableAgentBrowserAccess: false } },
333 },
334 });
335 const plan = planScopedSettingsPatch(project, [laptop, withExisting], {
336 defaultAutoPull: true,
337 });
338 expect(plan.unavailableReason).toBeNull();
339 expect(plan.serverWrites).toEqual([
340 {
341 environmentId: server.environmentId,
342 label: server.label,
343 previous: expect.anything(),
344 patch: {
345 projectSettingsOverrides: {
346 [projectId]: { enableAgentBrowserAccess: false, defaultAutoPull: true },
347 },
348 },
349 },
350 {
351 environmentId: laptop.environmentId,
352 label: laptop.label,
353 previous: expect.anything(),
354 patch: { projectSettingsOverrides: { [laptopProjectId]: { defaultAutoPull: true } } },
355 },
356 ]);
357 expect(
358 planScopedSettingsPatch(checkout, [laptop, server], { defaultAutoPull: true }),
359 ).toMatchObject({
360 serverWrites: [{ environmentId: server.environmentId }],
361 });
362 });
363​
364 it("keeps each project's other cleanup rules when changing one rule across machines", () => {
365 const machine = environment("Laptop", {
366 settings: {
367 storageCleanup: { ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeAfterDays: 30 },
368 },
369 });
370 const customized = environment("Server", {
371 settings: {
372 projectSettingsOverrides: {
373 [projectId]: {
374 defaultAutoPull: true,
375 worktreeCleanup: {
376 mode: "custom",
377 rules: {
378 worktreeAfterDays: 8,
379 worktreeSettledAfterDays: null,
380 worktreeOnDelete: false,
381 worktreeOnMerge: true,
382 worktreeUnchanged: false,
383 worktreeKeepWhen: "uncommitted-changes",
384 },
385 },
386 },
387 },
388 },
389 });
390 const plan = planScopedSettingsPatch(project, [machine, customized], {
391 worktreeCleanup: { mode: "custom", rules: { worktreeOnDelete: true } },
392 });
393 const settledPlan = planScopedSettingsPatch(project, [machine, customized], {
394 worktreeCleanup: { mode: "custom", rules: { worktreeSettledAfterDays: 0 } },
395 });
396 expect(
397 settledPlan.serverWrites.map((write) => write.patch.projectSettingsOverrides),
398 ).toMatchObject([
399 { [projectId]: { worktreeCleanup: { rules: { worktreeSettledAfterDays: 0 } } } },
400 { [laptopProjectId]: { worktreeCleanup: { rules: { worktreeSettledAfterDays: 0 } } } },
401 ]);
402 expect(plan.serverWrites.map((write) => write.patch.projectSettingsOverrides)).toEqual([
403 {
404 [projectId]: {
405 defaultAutoPull: true,
406 worktreeCleanup: {
407 mode: "custom",
408 rules: {
409 worktreeAfterDays: 8,
410 worktreeSettledAfterDays: null,
411 worktreeOnDelete: true,
412 worktreeOnMerge: true,
413 worktreeUnchanged: false,
414 worktreeKeepWhen: "uncommitted-changes",
415 },
416 },
417 },
418 },
419 {
420 [laptopProjectId]: {
421 worktreeCleanup: {
422 mode: "custom",
423 rules: {
424 worktreeAfterDays: 30,
425 worktreeSettledAfterDays: null,
426 worktreeOnDelete: true,
427 worktreeOnMerge: false,
428 worktreeUnchanged: false,
429 worktreeKeepWhen: "uncommitted-changes",
430 },
431 },
432 },
433 },
434 ]);
435 expect(
436 planScopedSettingsClear(checkout, [customized], ["worktreeCleanup"]).serverWrites[0]?.patch,
437 ).toEqual({
438 projectSettingsOverrides: { [projectId]: { defaultAutoPull: true } },
439 });
440 expect(
441 planScopedSettingsPatch(project, [machine, customized], {
442 storageCleanup: { browserArtifactsAfterDays: 8 },
443 }).serverWrites,
444 ).toEqual([]);
445 });
446​
447 // regression: #11541 device settings were written to the wrong scope
448 it("scopes agent device access to projects while keeping hub and hosts environment-wide", () => {
449 const plan = planScopedSettingsPatch(project, [laptop, server], {
450 enableAgentDeviceAccess: true,
451 });
452 expect(plan.serverWrites.map((write) => write.patch)).toEqual([
453 { projectSettingsOverrides: { [projectId]: { enableAgentDeviceAccess: true } } },
454 { projectSettingsOverrides: { [laptopProjectId]: { enableAgentDeviceAccess: true } } },
455 ]);
456 for (const patch of [{ enableDeviceSupport: true }, { deviceHosts: [] }]) {
457 expect(planScopedSettingsPatch(project, environments, patch).serverWrites).toEqual([]);
458 }
459 });
460​
461 it("refuses environment-wide keys at project scope", () => {
462 expect(
463 planScopedSettingsPatch(project, environments, { enableProviderUpdateChecks: false }),
464 ).toMatchObject({
465 serverWrites: [],
466 unavailableReason: "This setting is environment-wide and cannot be overridden by a project.",
467 });
468 });
469​
470 // regression: #35093 client settings saved in project scope overwrote the global default
471 it("refuses client-only keys at project scope", () => {
472 for (const scope of [project, checkout]) {
473 expect(
474 planScopedSettingsPatch(scope, environments, {
475 browserDefaultViewport: { _tag: "freeform", width: 1440, height: 900 },
476 }),
477 ).toMatchObject({
478 clientPatch: {},
479 hasClientWrite: false,
480 serverWrites: [],
481 unavailableReason:
482 "This setting is environment-wide and cannot be overridden by a project.",
483 });
484 expect(
485 planScopedSettingsPatch(
486 scope,
487 environments,
488 { fontSizeInterface: 15 },
489 { deviceOnly: true },
490 ),
491 ).toMatchObject({ clientPatch: { fontSizeInterface: 15 }, unavailableReason: null });
492 }
493 });
494​
495 it("clears overrides per member and removes an emptied entry", () => {
496 const withOverrides = environment("Server", {
497 settings: {
498 projectSettingsOverrides: {
499 [projectId]: { defaultAutoPull: true, enableAgentBrowserAccess: false },
500 },
501 },
502 });
503 const plan = planScopedSettingsClear(checkout, [laptop, withOverrides], ["defaultAutoPull"]);
504 expect(plan.serverWrites).toEqual([
505 {
506 environmentId: server.environmentId,
507 label: server.label,
508 previous: expect.anything(),
509 patch: { projectSettingsOverrides: { [projectId]: { enableAgentBrowserAccess: false } } },
510 },
511 ]);
512 expect(
513 planScopedSettingsClear(
514 checkout,
515 [laptop, withOverrides],
516 ["defaultAutoPull", "enableAgentBrowserAccess"],
517 ).serverWrites[0]?.patch,
518 ).toEqual({ projectSettingsOverrides: { [projectId]: null } });
519 });
520​
521 it("never substitutes an environment-default write for an invalid scope", () => {
522 const scope = resolveSettingsScope({ machine: "removed" }, [group], environments);
523 const plan = planScopedSettingsPatch(scope, environments, { enableAgentBrowserAccess: false });
524 expect(plan.serverWrites).toEqual([]);
525 expect(plan.hasClientWrite).toBe(false);
526 expect(plan.unavailableReason).not.toBeNull();
527 });
528​
529 it("waits for every target and identifies both RPC failures and rejected writes", async () => {
530 const third = environment("Third");
531 const fourth = environment("Fourth");
532 const selected = [...environments, third, fourth];
533 const scope = resolveSettingsScope({}, [], selected);
534 const persistServer = vi
535 .fn()
536 .mockResolvedValueOnce({ _tag: "Success" })
537 .mockResolvedValueOnce({
538 _tag: "Failure",
539 cause: Cause.fail(
540 new EnvironmentAuthorizationError({
541 requiredScope: "settings:write",
542 message: "This connection lacks permission to change settings.",
543 }),
544 ),
545 })
546 .mockRejectedValueOnce(new Error("Disconnected during save"))
547 .mockResolvedValueOnce({ _tag: "Success" });
548 const result = await persistScopedSettingsPatch(
549 planScopedSettingsPatch(scope, selected, { enableAgentBrowserAccess: false }),
550 persistServer,
551 vi.fn(),
552 );
553 expect(result.savedEnvironmentCount).toBe(2);
554 expect(result.savedEnvironments.map(({ label }) => label)).toEqual([
555 laptop.label,
556 fourth.label,
557 ]);
558 expect(result.failedEnvironments.map(({ message }) => message)).toEqual([
559 "This connection lacks permission to change settings.",
560 "Disconnected during save",
561 ]);
562 expect(result.failedEnvironments.map(({ label }) => label)).toEqual([
563 server.label,
564 third.label,
565 ]);
566 expect(persistServer).toHaveBeenCalledTimes(4);
567 });
568});
569​
570describe("scoped settings mixed values", () => {
571 it("treats independently decoded equal nested settings as the same value", () => {
572 const style = {
573 ...DEFAULT_SERVER_SETTINGS.sourceControlWritingStyle,
574 mode: "custom" as const,
575 customInstructions: "Use plain language",
576 };
577 const first = environment("First", { settings: { sourceControlWritingStyle: { ...style } } });
578 const second = environment("Second", { settings: { sourceControlWritingStyle: { ...style } } });
579 const targets = resolveScopedSettingsTargets(all, [first, second]);
580 expect(scopedSettingsAreMixed(targets, ["sourceControlWritingStyle"])).toBe(false);
581 });
582});
583​
584describe("project overrides at environment scope", () => {
585 const laptop = EnvironmentId.make("laptop");
586 const fleet = ProjectId.make("fleet");
587 const t3 = ProjectId.make("t3");
588 const environment = (
589 environmentId: EnvironmentId,
590 overrides: ServerSettings["projectSettingsOverrides"],
591 ) => ({
592 environmentId,
593 label: environmentId,
594 connection: { phase: "connected" as const },
595 serverConfig: {
596 settings: { ...DEFAULT_SERVER_SETTINGS, projectSettingsOverrides: overrides },
597 environment: { capabilities: { projectSettingsOverrides: true } },
598 },
599 });
600​
601 it("clears only those keys and drops entries that become empty", () => {
602 const plan = planProjectOverridesClear(
603 [
604 environment(laptop, {
605 [fleet]: { defaultAutoPull: true, defaultThreadEnvMode: "local" },
606 [t3]: { defaultAutoPull: true },
607 }),
608 ],
609 [
610 { environmentId: laptop, projectId: fleet },
611 { environmentId: laptop, projectId: t3 },
612 ],
613 ["defaultAutoPull"],
614 );
615 expect(plan.serverWrites).toEqual([
616 {
617 environmentId: laptop,
618 label: laptop,
619 previous: expect.anything(),
620 patch: {
621 projectSettingsOverrides: { [fleet]: { defaultThreadEnvMode: "local" }, [t3]: null },
622 },
623 },
624 ]);
625 });
626});
627​
628describe("null patches at project scope", () => {
629 it("removes the override for keys that cannot store null and keeps it for keys that can", () => {
630 const environmentId = EnvironmentId.make("laptop");
631 const projectId = ProjectId.make("fleet");
632 const scope = {
633 kind: "project" as const,
634 group: {} as never,
635 environmentId: null,
636 label: "fleet",
637 members: [{ id: projectId, environmentId } as never],
638 environmentIds: [environmentId],
639 };
640 const environments = [
641 {
642 environmentId,
643 label: "Laptop",
644 connection: { phase: "connected" as const },
645 serverConfig: {
646 settings: {
647 ...DEFAULT_SERVER_SETTINGS,
648 projectSettingsOverrides: {
649 [projectId]: { defaultThreadEnvMode: "worktree" as const, defaultAutoPull: true },
650 },
651 },
652 environment: { capabilities: { projectSettingsOverrides: true } },
653 },
654 },
655 ];
656 expect(
657 planScopedSettingsPatch(scope, environments, { defaultThreadEnvMode: null }).serverWrites[0]
658 ?.patch,
659 ).toEqual({ projectSettingsOverrides: { [projectId]: { defaultAutoPull: true } } });
660 expect(
661 planScopedSettingsPatch(scope, environments, { defaultModelSelection: null }).serverWrites[0]
662 ?.patch,
663 ).toEqual({
664 projectSettingsOverrides: {
665 [projectId]: {
666 defaultThreadEnvMode: "worktree",
667 defaultAutoPull: true,
668 defaultModelSelection: null,
669 },
670 },
671 });
672 });
673});
674​
675describe("partial object patches at project scope", () => {
676 it("completes a writing style field patch from the target's effective value", () => {
677 const environmentId = EnvironmentId.make("laptop");
678 const projectId = ProjectId.make("fleet");
679 const member = {
680 id: projectId,
681 environmentId,
682 physicalProjectKey: "laptop:/repo",
683 environmentLabel: "Laptop",
684 title: "fleet",
685 workspaceRoot: "/repo",
686 defaultModelSelection: null,
687 scripts: [],
688 createdAt: "2026-01-01T00:00:00.000Z",
689 updatedAt: "2026-01-01T00:00:00.000Z",
690 };
691 const settings = {
692 ...DEFAULT_SERVER_SETTINGS,
693 projectSettingsOverrides: {
694 [projectId]: {
695 sourceControlWritingStyle: {
696 mode: "custom" as const,
697 customInstructions: "Keep it short.",
698 followChangeRequestTemplates: false,
699 },
700 },
701 },
702 };
703 const plan = planScopedSettingsPatch(
704 {
705 kind: "project",
706 group: {} as never,
707 environmentId: null,
708 label: "fleet",
709 members: [member as never],
710 environmentIds: [environmentId],
711 },
712 [
713 {
714 environmentId,
715 label: "Laptop",
716 connection: { phase: "connected" },
717 serverConfig: {
718 settings,
719 },
720 },
721 ],
722 { sourceControlWritingStyle: { customInstructions: "Be terse." } },
723 );
724 expect(plan.serverWrites[0]?.patch).toEqual({
725 projectSettingsOverrides: {
726 [projectId]: {
727 sourceControlWritingStyle: {
728 mode: "custom",
729 customInstructions: "Be terse.",
730 followChangeRequestTemplates: false,
731 },
732 },
733 },
734 });
735 });
736});
737​
738it("routes legacy model preference keys exclusively to the selected environment", () => {
739 const patch = {
740 favorites: [{ provider: ProviderInstanceId.make("codex"), model: "sol" }],
741 providerModelPreferences: {},
742 };
743 const plan = planScopedSettingsPatch(named, environments, patch);
744 expect(plan.clientPatch).toEqual({});
745 expect(plan.hasClientWrite).toBe(false);
746 expect(plan.serverWrites).toEqual([
747 {
748 environmentId: server.environmentId,
749 label: server.label,
750 previous: expect.anything(),
751 patch,
752 },
753 ]);
754});
755​
756describe("model selection patches at project scope", () => {
757 const codex = ProviderInstanceId.make("codex");
758 const claude = ProviderInstanceId.make("claudeAgent");
759 const saved = {
760 instanceId: codex,
761 model: "gpt-5.6",
762 options: [{ id: "reasoningEffort", value: "high" }],
763 };
764 const customized = environment("Server", {
765 settings: {
766 projectSettingsOverrides: {
767 [projectId]: {
768 defaultModelSelection: saved,
769 sourceControlWriterModelSelection: saved,
770 reviewGuideModelSelection: saved,
771 textGenerationModelSelection: saved,
772 },
773 },
774 },
775 });
776​
777 // regression: #16581 changing a project's model kept the old model's options
778 it("replaces old options when changing model selections", () => {
779 const plan = planScopedSettingsPatch(checkout, [customized], {
780 defaultModelSelection: { instanceId: claude, model: "claude-opus-4-8" },
781 sourceControlWriterModelSelection: { instanceId: codex, model: "gpt-5.6-mini" },
782 reviewGuideModelSelection: { instanceId: codex, model: "gpt-5.6-mini" },
783 textGenerationModelSelection: { instanceId: claude, model: "claude-sonnet-4-6" },
784 });
785 expect(plan.serverWrites[0]?.patch.projectSettingsOverrides?.[projectId]).toEqual({
786 defaultModelSelection: { instanceId: claude, model: "claude-opus-4-8" },
787 sourceControlWriterModelSelection: { instanceId: codex, model: "gpt-5.6-mini" },
788 reviewGuideModelSelection: { instanceId: codex, model: "gpt-5.6-mini" },
789 textGenerationModelSelection: { instanceId: claude, model: "claude-sonnet-4-6" },
790 });
791 });
792​
793 it("completes partial text-generation selections without retaining old options", () => {
794 const modelPlan = planScopedSettingsPatch(checkout, [customized], {
795 textGenerationModelSelection: { model: "gpt-5.6-mini" },
796 });
797 expect(
798 modelPlan.serverWrites[0]?.patch.projectSettingsOverrides?.[projectId]
799 ?.textGenerationModelSelection,
800 ).toEqual({ instanceId: codex, model: "gpt-5.6-mini" });
801​
802 const options = [{ id: "reasoningEffort", value: "low" }];
803 const optionsPlan = planScopedSettingsPatch(checkout, [customized], {
804 textGenerationModelSelection: { options },
805 });
806 expect(
807 optionsPlan.serverWrites[0]?.patch.projectSettingsOverrides?.[projectId]
808 ?.textGenerationModelSelection,
809 ).toEqual({ ...saved, options });
810 });
811});