Open History to see the last commit
1import {
2 DEFAULT_SERVER_SETTINGS,
3 EnvironmentAuthorizationError,
4 EnvironmentId,
5 ProjectId,
6 ProviderInstanceId,
7 type ServerSettings,
8 type ServerSettingsPatch,
9} from "@t3tools/contracts";
10import { describe, expect, it, vi } from "vite-plus/test";
11import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
12import * as Cause from "effect/Cause";
13import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
14
15import type { SidebarProjectSnapshot } from "../../sidebarProjectGrouping";
16import {
17 applyPendingScopedWrites,
18 createScopedSettingsWriter,
19 persistScopedSettingsPatch,
20 planProjectOverridesClear,
21 planScopedSettingsClear,
22 planScopedSettingsPatch,
23 scopedIdleCompaction,
24 resolveScopedSettingsTargets,
25 scopedSettingsAreMixed,
26 scopedSettingsSource,
27 scopedSettingsTargetMember,
28 selectScopedSettingsEnvironments,
29 settlePendingScopedWrites,
30 type PendingScopedWrite,
31} from "./scopedSettings";
32import { resolveSettingsScope } from "./settingsScope";
33
34function environment(
35 id: string,
36 options: {
37 connected?: boolean;
38 loaded?: boolean;
39 settings?: Partial<ServerSettings>;
40 } = {},
41) {
42 return {
43 environmentId: EnvironmentId.make(id),
44 label: id,
45 connection: {
46 phase: options.connected === false ? ("offline" as const) : ("connected" as const),
47 },
48 serverConfig:
49 options.loaded === false
50 ? null
51 : {
52 settings: { ...DEFAULT_SERVER_SETTINGS, ...options.settings },
53 },
54 };
55}
56
57const laptop = environment("Laptop");
58const server = environment("Server");
59const offline = environment("Offline", { connected: false });
60const loading = environment("Loading", { loaded: false });
61const environments = [laptop, server, offline, loading];
62const all = resolveSettingsScope({}, [], environments);
63const named = resolveSettingsScope({ machine: server.environmentId }, [], environments);
64
65const projectId = ProjectId.make("project");
66const laptopProjectId = ProjectId.make("laptop-project");
67const member = {
68 id: projectId,
69 environmentId: server.environmentId,
70 title: "Project",
71 workspaceRoot: "/repo",
72 physicalProjectKey: `${server.environmentId}:/repo`,
73 environmentLabel: server.label,
74 defaultModelSelection: null,
75 scripts: [],
76 createdAt: "2026-09-07T00:00:00.000Z",
77 updatedAt: "2026-09-07T00:00:00.000Z",
78};
79const laptopMember = {
80 ...member,
81 id: laptopProjectId,
82 environmentId: laptop.environmentId,
83 physicalProjectKey: `${laptop.environmentId}:/repo`,
84 environmentLabel: laptop.label,
85};
86const group: SidebarProjectSnapshot = {
87 ...member,
88 projectKey: "project-group",
89 displayName: "Project",
90 memberProjects: [member, laptopMember],
91 memberProjectRefs: [
92 { environmentId: server.environmentId, projectId },
93 { environmentId: laptop.environmentId, projectId: laptopProjectId },
94 ],
95 groupedProjectCount: 2,
96 environmentPresence: "remote-only",
97 allRemoteMembersAreDesktopLocal: false,
98 allRemoteMembersAreWsl: false,
99 remoteEnvironmentLabels: [server.label, laptop.label],
100 pinned: false,
101 archived: false,
102};
103const project = resolveSettingsScope({ project: group.projectKey }, [group], environments);
104const checkout = resolveSettingsScope(
105 { project: group.projectKey, machine: server.environmentId, checkout: member.physicalProjectKey },
106 [group],
107 environments,
108);
109
110describe("scoped settings targets", () => {
111 it("uses the named environment even when a different primary is available", () => {
112 const selected = selectScopedSettingsEnvironments(named, environments, laptop.environmentId);
113 expect(selected.environments).toEqual([server]);
114 expect(selected.environment).toBe(server);
115 });
116
117 it("keeps an offline named environment selected without falling back to primary", () => {
118 const scope = resolveSettingsScope({ machine: offline.environmentId }, [], environments);
119 const selected = selectScopedSettingsEnvironments(scope, environments, laptop.environmentId);
120 expect(selected.environments).toEqual([offline]);
121 expect(selected.connectedEnvironments).toEqual([]);
122 expect(selected.environment).toBeNull();
123 expect(
124 planScopedSettingsPatch(scope, environments, { enableProviderUpdateChecks: false }),
125 ).toMatchObject({
126 serverWrites: [],
127 unavailableReason: "Connect Offline to save this setting.",
128 });
129 });
130
131 it("resolves each member's effective settings and source at project scope", () => {
132 const overridden = environment("Server", {
133 settings: {
134 defaultAutoPull: false,
135 projectSettingsOverrides: { [projectId]: { defaultAutoPull: true } },
136 },
137 });
138 const targets = resolveScopedSettingsTargets(project, [laptop, overridden]);
139 expect(targets.map((target) => [target.projectId, target.settings.defaultAutoPull])).toEqual([
140 [projectId, true],
141 [laptopProjectId, false],
142 ]);
143 expect(scopedSettingsSource(targets, ["defaultAutoPull"])).toBe("mixed");
144 expect(scopedSettingsSource([targets[0]!], ["defaultAutoPull"])).toBe("project");
145 expect(scopedSettingsSource(targets, ["enableProviderUpdateChecks"])).toBe("environment");
146 expect(scopedSettingsAreMixed(targets, ["defaultAutoPull"])).toBe(true);
147 });
148
149 it("pairs each target with its own environment's member when project IDs match", () => {
150 const sharedId = ProjectId.make("shared");
151 const memberA = {
152 ...laptopMember,
153 id: sharedId,
154 workspaceRoot: "/A/repo",
155 physicalProjectKey: `${laptop.environmentId}:/A/repo`,
156 };
157 const memberB = {
158 ...member,
159 id: sharedId,
160 workspaceRoot: "/B/repo",
161 physicalProjectKey: `${server.environmentId}:/B/repo`,
162 };
163 const shared = resolveSettingsScope(
164 { project: "shared-group" },
165 [
166 {
167 ...group,
168 ...memberA,
169 projectKey: "shared-group",
170 memberProjects: [memberA, memberB],
171 memberProjectRefs: [
172 { environmentId: laptop.environmentId, projectId: sharedId },
173 { environmentId: server.environmentId, projectId: sharedId },
174 ],
175 },
176 ],
177 environments,
178 );
179 const targets = resolveScopedSettingsTargets(shared, [laptop, server]);
180 expect(targets.map((target) => scopedSettingsTargetMember(shared, target))).toEqual([
181 memberA,
182 memberB,
183 ]);
184 });
185});
186
187describe("scoped settings writes", () => {
188 it("edits the effective machine policy without changing other machines' rules", () => {
189 const custom = environment("Laptop", {
190 settings: {
191 worktreeCleanup: {
192 mode: "custom",
193 rules: {
194 worktreeAfterDays: 12,
195 worktreeSettledAfterDays: null,
196 worktreeOnDelete: true,
197 worktreeOnMerge: true,
198 worktreeUnchanged: false,
199 worktreeKeepWhen: "uncommitted-changes",
200 },
201 },
202 },
203 });
204 const disabled = environment("Server", {
205 settings: { worktreeCleanup: { mode: "off" } },
206 });
207 const targets = [custom, disabled];
208 const plan = planScopedSettingsPatch(all, targets, {
209 storageCleanup: { worktreeOnDelete: false },
210 });
211 const policies = plan.serverWrites.map((write, index) =>
212 resolveWorktreeCleanup(
213 applyServerSettingsPatch(targets[index]!.serverConfig!.settings, write.patch),
214 null,
215 ),
216 );
217 expect(policies).toEqual([
218 {
219 worktreeAfterDays: 12,
220 worktreeSettledAfterDays: null,
221 worktreeOnDelete: false,
222 worktreeOnMerge: true,
223 worktreeUnchanged: false,
224 worktreeKeepWhen: "uncommitted-changes",
225 },
226 {
227 worktreeAfterDays: null,
228 worktreeSettledAfterDays: null,
229 worktreeOnDelete: false,
230 worktreeOnMerge: false,
231 worktreeUnchanged: false,
232 worktreeKeepWhen: "uncommitted-changes",
233 },
234 ]);
235 });
236
237 it("compares idle compaction by mode, and offers Never only where every server stores it", () => {
238 const fixed = {
239 settings: {
240 ...DEFAULT_SERVER_SETTINGS,
241 compactIdleThreads: false,
242 idleCompaction: "onReturn" as const,
243 },
244 };
245 const modes = {
246 settings: { ...DEFAULT_SERVER_SETTINGS, compactIdleThreads: "onReturn" as const },
247 };
248 const legacy = { settings: { ...DEFAULT_SERVER_SETTINGS, compactIdleThreads: false } };
249 expect(scopedIdleCompaction([fixed, modes])).toEqual({ mixed: false, neverAvailable: true });
250 expect(scopedIdleCompaction([fixed, legacy])).toEqual({ mixed: false, neverAvailable: false });
251 const legacyEnvironment = environment("Legacy", { settings: legacy.settings });
252 const projected = applyPendingScopedWrites(
253 [legacyEnvironment],
254 [
255 {
256 save: {},
257 environmentId: legacyEnvironment.environmentId,
258 patch: { defaultRuntimeMode: "auto" },
259 },
260 ],
261 );
262 expect(scopedIdleCompaction(resolveScopedSettingsTargets(all, projected)).neverAvailable).toBe(
263 false,
264 );
265 expect(
266 scopedIdleCompaction([fixed, { settings: { ...fixed.settings, idleCompaction: "off" } }])
267 .mixed,
268 ).toBe(true);
269 });
270
271 it("sends an idle compaction mode in the form each environment's server reads", () => {
272 const targets = [
273 environment("Fixed", { settings: { compactIdleThreads: false, idleCompaction: "onReturn" } }),
274 environment("Modes", { settings: { compactIdleThreads: "onReturn" } }),
275 environment("Switch", { settings: { compactIdleThreads: false } }),
276 ];
277 const plan = planScopedSettingsPatch(resolveSettingsScope({}, [], targets), targets, {
278 idleCompaction: "beforeCacheExpires",
279 });
280 expect(plan.serverWrites.map((write) => write.patch)).toEqual([
281 { idleCompaction: "beforeCacheExpires" },
282 { compactIdleThreads: "beforeCacheExpires" },
283 { compactIdleThreads: true },
284 ]);
285 });
286
287 it("writes an aggregate preference only to connected environments with loaded configuration", async () => {
288 const persistServer = vi.fn().mockResolvedValue({ _tag: "Success" });
289 const persistClient = vi.fn();
290 await persistScopedSettingsPatch(
291 planScopedSettingsPatch(all, environments, { enableProviderUpdateChecks: false }),
292 persistServer,
293 persistClient,
294 );
295 expect(persistServer.mock.calls.map(([input]) => input.environmentId)).toEqual([
296 laptop.environmentId,
297 server.environmentId,
298 ]);
299 expect(persistClient).not.toHaveBeenCalled();
300 });
301
302 describe("an environment that saves but drops keys it does not know", () => {
303 const upgradedLaptop = (saved: Partial<ServerSettings>) =>
304 vi.fn(async ({ environmentId }: { environmentId: EnvironmentId }) => ({
305 _tag: "Success" as const,
306 value: {
307 ...DEFAULT_SERVER_SETTINGS,
308 ...(environmentId === laptop.environmentId ? saved : {}),
309 },
310 }));
311 const outcome = async (
312 plan: ReturnType<typeof planScopedSettingsPatch>,
313 persistServer: ReturnType<typeof upgradedLaptop>,
314 ) => {
315 const result = await persistScopedSettingsPatch(plan, persistServer, vi.fn());
316 return {
317 saved: result.savedEnvironments.map(({ label }) => label),
318 failed: result.failedEnvironments.map(({ label, message }) => ({ label, message })),
319 };
320 };
321 const unsupported = [
322 {
323 label: server.label,
324 message: "This environment does not support this setting. Update T3 Code on it.",
325 },
326 ];
327
328 it("reports a dropped toggle", async () => {
329 expect(
330 await outcome(
331 planScopedSettingsPatch(all, environments, { reviewGuidesEnabled: true }),
332 upgradedLaptop({ reviewGuidesEnabled: true }),
333 ),
334 ).toEqual({ saved: [laptop.label], failed: unsupported });
335 });
336
337 it("reports dropped text but accepts the server trimming it", async () => {
338 expect(
339 await outcome(
340 planScopedSettingsPatch(all, environments, { reviewGuideInstructions: " Read tests " }),
341 upgradedLaptop({ reviewGuideInstructions: "Read tests" }),
342 ),
343 ).toEqual({ saved: [laptop.label], failed: unsupported });
344 });
345
346 // regression: #18334 an environment silently dropped a setting with no warning
347 it("reports a dropped key inside a project override", async () => {
348 expect(
349 await outcome(
350 planScopedSettingsPatch(project, environments, { defaultAutoPull: true }),
351 upgradedLaptop({
352 projectSettingsOverrides: { [laptopProjectId]: { defaultAutoPull: true } },
353 }),
354 ),
355 ).toEqual({ saved: [laptop.label], failed: unsupported });
356 });
357
358 it("accepts a write that matches what the environment already had", async () => {
359 expect(
360 await outcome(
361 planScopedSettingsPatch(all, environments, { reviewGuidesEnabled: false }),
362 upgradedLaptop({}),
363 ),
364 ).toEqual({ saved: [laptop.label, server.label], failed: [] });
365 });
366 });
367
368 it("persists client keys locally at any scope alongside server keys", async () => {
369 const persistServer = vi.fn().mockResolvedValue({ _tag: "Success" });
370 const persistClient = vi.fn();
371 await persistScopedSettingsPatch(
372 planScopedSettingsPatch(named, environments, {
373 diffIgnoreWhitespace: false,
374 enableProviderUpdateChecks: false,
375 }),
376 persistServer,
377 persistClient,
378 );
379 expect(persistClient).toHaveBeenCalledExactlyOnceWith({ diffIgnoreWhitespace: false });
380 expect(persistServer).toHaveBeenCalledExactlyOnceWith({
381 environmentId: server.environmentId,
382 input: { patch: { enableProviderUpdateChecks: false } },
383 });
384 });
385
386 it("writes project overrides into each member's entry on its environment", () => {
387 const withExisting = environment("Server", {
388 settings: {
389 projectSettingsOverrides: { [projectId]: { enableAgentBrowserAccess: false } },
390 },
391 });
392 const plan = planScopedSettingsPatch(project, [laptop, withExisting], {
393 defaultAutoPull: true,
394 });
395 expect(plan.unavailableReason).toBeNull();
396 expect(plan.serverWrites).toEqual([
397 {
398 environmentId: server.environmentId,
399 label: server.label,
400 previous: expect.anything(),
401 patch: {
402 projectSettingsOverrides: {
403 [projectId]: { enableAgentBrowserAccess: false, defaultAutoPull: true },
404 },
405 },
406 },
407 {
408 environmentId: laptop.environmentId,
409 label: laptop.label,
410 previous: expect.anything(),
411 patch: { projectSettingsOverrides: { [laptopProjectId]: { defaultAutoPull: true } } },
412 },
413 ]);
414 expect(
415 planScopedSettingsPatch(checkout, [laptop, server], { defaultAutoPull: true }),
416 ).toMatchObject({
417 serverWrites: [{ environmentId: server.environmentId }],
418 });
419 });
420
421 it("keeps each project's other cleanup rules when changing one rule across machines", () => {
422 const machine = environment("Laptop", {
423 settings: {
424 storageCleanup: { ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeAfterDays: 30 },
425 },
426 });
427 const customized = environment("Server", {
428 settings: {
429 projectSettingsOverrides: {
430 [projectId]: {
431 defaultAutoPull: true,
432 worktreeCleanup: {
433 mode: "custom",
434 rules: {
435 worktreeAfterDays: 8,
436 worktreeSettledAfterDays: null,
437 worktreeOnDelete: false,
438 worktreeOnMerge: true,
439 worktreeUnchanged: false,
440 worktreeKeepWhen: "uncommitted-changes",
441 },
442 },
443 },
444 },
445 },
446 });
447 const plan = planScopedSettingsPatch(project, [machine, customized], {
448 worktreeCleanup: { mode: "custom", rules: { worktreeOnDelete: true } },
449 });
450 const settledPlan = planScopedSettingsPatch(project, [machine, customized], {
451 worktreeCleanup: { mode: "custom", rules: { worktreeSettledAfterDays: 0 } },
452 });
453 expect(
454 settledPlan.serverWrites.map((write) => write.patch.projectSettingsOverrides),
455 ).toMatchObject([
456 { [projectId]: { worktreeCleanup: { rules: { worktreeSettledAfterDays: 0 } } } },
457 { [laptopProjectId]: { worktreeCleanup: { rules: { worktreeSettledAfterDays: 0 } } } },
458 ]);
459 expect(plan.serverWrites.map((write) => write.patch.projectSettingsOverrides)).toEqual([
460 {
461 [projectId]: {
462 defaultAutoPull: true,
463 worktreeCleanup: {
464 mode: "custom",
465 rules: {
466 worktreeAfterDays: 8,
467 worktreeSettledAfterDays: null,
468 worktreeOnDelete: true,
469 worktreeOnMerge: true,
470 worktreeUnchanged: false,
471 worktreeKeepWhen: "uncommitted-changes",
472 },
473 },
474 },
475 },
476 {
477 [laptopProjectId]: {
478 worktreeCleanup: {
479 mode: "custom",
480 rules: {
481 worktreeAfterDays: 30,
482 worktreeSettledAfterDays: null,
483 worktreeOnDelete: true,
484 worktreeOnMerge: false,
485 worktreeUnchanged: false,
486 worktreeKeepWhen: "uncommitted-changes",
487 },
488 },
489 },
490 },
491 ]);
492 expect(
493 planScopedSettingsClear(checkout, [customized], ["worktreeCleanup"]).serverWrites[0]?.patch,
494 ).toEqual({
495 projectSettingsOverrides: { [projectId]: { defaultAutoPull: true } },
496 });
497 expect(
498 planScopedSettingsPatch(project, [machine, customized], {
499 storageCleanup: { browserArtifactsAfterDays: 8 },
500 }).serverWrites,
501 ).toEqual([]);
502 });
503
504 it("turns off project worktree cleanup without inheriting custom rules from the environment", () => {
505 const customEnvironment = environment("Server", {
506 settings: {
507 worktreeCleanup: {
508 mode: "custom",
509 rules: {
510 worktreeKeepWhen: "uncommitted-changes",
511 worktreeAfterDays: 7,
512 worktreeSettledAfterDays: 3,
513 worktreeOnMerge: true,
514 worktreeOnDelete: true,
515 worktreeUnchanged: true,
516 },
517 },
518 projectSettingsOverrides: {},
519 },
520 });
521 const plan = planScopedSettingsPatch(project, [customEnvironment], {
522 worktreeCleanup: { mode: "off" },
523 });
524 expect(plan.serverWrites).toHaveLength(1);
525 expect(plan.serverWrites[0]?.patch).toEqual({
526 projectSettingsOverrides: { [projectId]: { worktreeCleanup: { mode: "off" } } },
527 });
528 });
529
530 // regression: #11541 device settings were written to the wrong scope
531 it("scopes agent device access to projects while keeping hub and hosts environment-wide", () => {
532 const plan = planScopedSettingsPatch(project, [laptop, server], {
533 enableAgentDeviceAccess: true,
534 });
535 expect(plan.serverWrites.map((write) => write.patch)).toEqual([
536 { projectSettingsOverrides: { [projectId]: { enableAgentDeviceAccess: true } } },
537 { projectSettingsOverrides: { [laptopProjectId]: { enableAgentDeviceAccess: true } } },
538 ]);
539 for (const patch of [{ enableDeviceSupport: true }, { deviceHosts: [] }]) {
540 expect(planScopedSettingsPatch(project, environments, patch).serverWrites).toEqual([]);
541 }
542 });
543
544 it("refuses environment-wide keys at project scope", () => {
545 expect(
546 planScopedSettingsPatch(project, environments, { enableProviderUpdateChecks: false }),
547 ).toMatchObject({
548 serverWrites: [],
549 unavailableReason: "This setting is environment-wide and cannot be overridden by a project.",
550 });
551 });
552
553 // regression: #35093 client settings saved in project scope overwrote the global default
554 it("refuses client-only keys at project scope", () => {
555 for (const scope of [project, checkout]) {
556 expect(
557 planScopedSettingsPatch(scope, environments, {
558 browserDefaultViewport: { _tag: "freeform", width: 1440, height: 900 },
559 }),
560 ).toMatchObject({
561 clientPatch: {},
562 hasClientWrite: false,
563 serverWrites: [],
564 unavailableReason:
565 "This setting is environment-wide and cannot be overridden by a project.",
566 });
567 expect(
568 planScopedSettingsPatch(
569 scope,
570 environments,
571 { fontSizeInterface: 15 },
572 { deviceOnly: true },
573 ),
574 ).toMatchObject({ clientPatch: { fontSizeInterface: 15 }, unavailableReason: null });
575 }
576 });
577
578 it("clears overrides per member and removes an emptied entry", () => {
579 const withOverrides = environment("Server", {
580 settings: {
581 projectSettingsOverrides: {
582 [projectId]: { defaultAutoPull: true, enableAgentBrowserAccess: false },
583 },
584 },
585 });
586 const plan = planScopedSettingsClear(checkout, [laptop, withOverrides], ["defaultAutoPull"]);
587 expect(plan.serverWrites).toEqual([
588 {
589 environmentId: server.environmentId,
590 label: server.label,
591 previous: expect.anything(),
592 patch: { projectSettingsOverrides: { [projectId]: { enableAgentBrowserAccess: false } } },
593 },
594 ]);
595 expect(
596 planScopedSettingsClear(
597 checkout,
598 [laptop, withOverrides],
599 ["defaultAutoPull", "enableAgentBrowserAccess"],
600 ).serverWrites[0]?.patch,
601 ).toEqual({ projectSettingsOverrides: { [projectId]: null } });
602 });
603
604 it("never substitutes an environment-default write for an invalid scope", () => {
605 const scope = resolveSettingsScope({ machine: "removed" }, [group], environments);
606 const plan = planScopedSettingsPatch(scope, environments, { enableAgentBrowserAccess: false });
607 expect(plan.serverWrites).toEqual([]);
608 expect(plan.hasClientWrite).toBe(false);
609 expect(plan.unavailableReason).not.toBeNull();
610 });
611
612 it("waits for every target and identifies both RPC failures and rejected writes", async () => {
613 const third = environment("Third");
614 const fourth = environment("Fourth");
615 const selected = [...environments, third, fourth];
616 const scope = resolveSettingsScope({}, [], selected);
617 const persistServer = vi
618 .fn()
619 .mockResolvedValueOnce({ _tag: "Success" })
620 .mockResolvedValueOnce({
621 _tag: "Failure",
622 cause: Cause.fail(
623 new EnvironmentAuthorizationError({
624 requiredScope: "settings:write",
625 message: "This connection lacks permission to change settings.",
626 }),
627 ),
628 })
629 .mockRejectedValueOnce(new Error("Disconnected during save"))
630 .mockResolvedValueOnce({ _tag: "Success" });
631 const result = await persistScopedSettingsPatch(
632 planScopedSettingsPatch(scope, selected, { enableAgentBrowserAccess: false }),
633 persistServer,
634 vi.fn(),
635 );
636 expect(result.savedEnvironmentCount).toBe(2);
637 expect(result.savedEnvironments.map(({ label }) => label)).toEqual([
638 laptop.label,
639 fourth.label,
640 ]);
641 expect(result.failedEnvironments.map(({ message }) => message)).toEqual([
642 "This connection lacks permission to change settings.",
643 "Disconnected during save",
644 ]);
645 expect(result.failedEnvironments.map(({ label }) => label)).toEqual([
646 server.label,
647 third.label,
648 ]);
649 expect(persistServer).toHaveBeenCalledTimes(4);
650 });
651
652 describe("rapid project saves on one environment", () => {
653 const saving = (initial: ServerSettings) => {
654 let stored = initial;
655 const persistServer = vi.fn(async ({ input }: { input: { patch: ServerSettingsPatch } }) => {
656 stored = applyServerSettingsPatch(stored, input.patch);
657 return { _tag: "Success" as const, value: stored };
658 });
659 return { persistServer, stored: () => stored };
660 };
661
662 // regression: #18426 rapid project saves rebuilt overrides from a copy that trailed them
663 it("keeps every edit and reset while the client's copy trails its saves", async () => {
664 let copy: ServerSettings = {
665 ...DEFAULT_SERVER_SETTINGS,
666 projectSettingsOverrides: { [projectId]: { enableAgentBrowserAccess: false } },
667 };
668 const host = saving(copy);
669 // No config push arrives, so the client's copy stays as it was before the first save.
670 const write = createScopedSettingsWriter(() => copy);
671 const save = (plan: Parameters<typeof write>[1]) =>
672 write([environment("Server", { settings: copy })], plan, host.persistServer, vi.fn());
673 await Promise.all([
674 save((current) => planScopedSettingsPatch(checkout, current, { defaultAutoPull: true })),
675 save((current) => planScopedSettingsClear(checkout, current, ["enableAgentBrowserAccess"])),
676 save((current) =>
677 planScopedSettingsPatch(checkout, current, { removeAgentCreditsOnMerge: true }),
678 ),
679 ]);
680 expect(host.stored().projectSettingsOverrides[projectId]).toEqual({
681 defaultAutoPull: true,
682 removeAgentCreditsOnMerge: true,
683 });
684 // The first save's push arrives late, after the newer saves have finished.
685 copy = (await host.persistServer.mock.results[0]!.value).value;
686 await save((current) =>
687 planScopedSettingsPatch(checkout, current, { defaultThreadEnvMode: "worktree" }),
688 );
689 expect(host.stored().projectSettingsOverrides[projectId]).toEqual({
690 defaultAutoPull: true,
691 removeAgentCreditsOnMerge: true,
692 defaultThreadEnvMode: "worktree",
693 });
694 });
695
696 it.each(["remote", "previous save"] as const)(
697 "keeps the current base when a %s push arrives during a save",
698 async (push) => {
699 let copy: ServerSettings = DEFAULT_SERVER_SETTINGS;
700 const host = saving(copy);
701 const write = createScopedSettingsWriter(() => copy);
702 const edit = (patch: ServerSettingsPatch) =>
703 write(
704 [environment("Server", { settings: copy })],
705 (current) => planScopedSettingsPatch(checkout, current, patch),
706 host.persistServer,
707 vi.fn(),
708 );
709 await edit({ defaultAutoPull: true });
710 const previous = host.stored();
711 const persist = host.persistServer.getMockImplementation()!;
712 host.persistServer.mockImplementationOnce(async (request) => {
713 const response = await persist(request);
714 if (push === "remote") {
715 await persist({
716 input: {
717 patch: {
718 projectSettingsOverrides: {
719 [projectId]: { enableAgentBrowserAccess: false },
720 },
721 },
722 },
723 });
724 copy = host.stored();
725 } else {
726 copy = { ...previous };
727 }
728 return response;
729 });
730 await edit({ removeAgentCreditsOnMerge: true });
731 await edit({ defaultThreadEnvMode: "worktree" });
732 expect(host.stored().projectSettingsOverrides[projectId]).toEqual(
733 push === "remote"
734 ? { enableAgentBrowserAccess: false, defaultThreadEnvMode: "worktree" }
735 : {
736 defaultAutoPull: true,
737 removeAgentCreditsOnMerge: true,
738 defaultThreadEnvMode: "worktree",
739 },
740 );
741 },
742 );
743
744 it("plans from a copy that changed after the last save, and saves again after a failure", async () => {
745 let copy: ServerSettings = DEFAULT_SERVER_SETTINGS;
746 const host = saving(copy);
747 const write = createScopedSettingsWriter(() => copy);
748 const edit = (patch: ServerSettingsPatch) =>
749 write(
750 [environment("Server", { settings: copy })],
751 (current) => planScopedSettingsPatch(checkout, current, patch),
752 host.persistServer,
753 vi.fn(),
754 );
755 host.persistServer.mockRejectedValueOnce(new Error("Disconnected"));
756 expect((await edit({ defaultAutoPull: true })).failedEnvironments).toMatchObject([
757 { message: "Disconnected" },
758 ]);
759 expect((await edit({ defaultAutoPull: true })).savedEnvironmentCount).toBe(1);
760 // Another client replaces the override, and its push reaches this client.
761 await host.persistServer({
762 input: {
763 patch: { projectSettingsOverrides: { [projectId]: { enableAgentBrowserAccess: false } } },
764 },
765 });
766 copy = host.stored();
767 await edit({ removeAgentCreditsOnMerge: true });
768 expect(host.stored().projectSettingsOverrides[projectId]).toEqual({
769 enableAgentBrowserAccess: false,
770 removeAgentCreditsOnMerge: true,
771 });
772 });
773 });
774});
775
776describe("scoped settings mixed values", () => {
777 it("treats independently decoded equal nested settings as the same value", () => {
778 const style = {
779 ...DEFAULT_SERVER_SETTINGS.sourceControlWritingStyle,
780 mode: "custom" as const,
781 customInstructions: "Use plain language",
782 };
783 const first = environment("First", { settings: { sourceControlWritingStyle: { ...style } } });
784 const second = environment("Second", { settings: { sourceControlWritingStyle: { ...style } } });
785 const targets = resolveScopedSettingsTargets(all, [first, second]);
786 expect(scopedSettingsAreMixed(targets, ["sourceControlWritingStyle"])).toBe(false);
787 });
788
789 it("agrees while a save is in flight and follows the environment once it reports back", () => {
790 const patch = { defaultRuntimeMode: "auto" as const };
791 const saved = environment("Laptop", { settings: patch });
792 let waiting = environment("Server");
793 const save = {};
794 let writes: readonly PendingScopedWrite[] = [saved, waiting].map(({ environmentId }) => ({
795 save,
796 environmentId,
797 patch,
798 }));
799 const mixed = () =>
800 scopedSettingsAreMixed(
801 resolveScopedSettingsTargets(all, applyPendingScopedWrites([saved, waiting], writes)),
802 ["defaultRuntimeMode"],
803 );
804 const settle = (environmentId: EnvironmentId, result?: ServerSettings) => {
805 writes = settlePendingScopedWrites(
806 writes,
807 { save, environmentId },
808 (id) => [saved, waiting].find((env) => env.environmentId === id)?.serverConfig?.settings,
809 result,
810 );
811 };
812 expect(mixed()).toBe(false);
813
814 // Laptop already pushed its result; Server answers before its push arrives.
815 settle(saved.environmentId, saved.serverConfig!.settings);
816 settle(waiting.environmentId, applyServerSettingsPatch(waiting.serverConfig!.settings, patch));
817 expect(writes.map(({ environmentId }) => environmentId)).toEqual([waiting.environmentId]);
818 expect(mixed()).toBe(false);
819
820 waiting = environment("Server", { settings: { defaultRuntimeMode: "approval-required" } });
821 expect(mixed()).toBe(true);
822
823 writes = [{ save, environmentId: waiting.environmentId, patch }];
824 settle(waiting.environmentId);
825 expect(writes).toEqual([]);
826 });
827});
828
829describe("project overrides at environment scope", () => {
830 const laptop = EnvironmentId.make("laptop");
831 const fleet = ProjectId.make("fleet");
832 const t3 = ProjectId.make("t3");
833 const environment = (
834 environmentId: EnvironmentId,
835 overrides: ServerSettings["projectSettingsOverrides"],
836 ) => ({
837 environmentId,
838 label: environmentId,
839 connection: { phase: "connected" as const },
840 serverConfig: {
841 settings: { ...DEFAULT_SERVER_SETTINGS, projectSettingsOverrides: overrides },
842 environment: { capabilities: { projectSettingsOverrides: true } },
843 },
844 });
845
846 it("clears only those keys and drops entries that become empty", () => {
847 const plan = planProjectOverridesClear(
848 [
849 environment(laptop, {
850 [fleet]: { defaultAutoPull: true, defaultThreadEnvMode: "local" },
851 [t3]: { defaultAutoPull: true },
852 }),
853 ],
854 [
855 { environmentId: laptop, projectId: fleet },
856 { environmentId: laptop, projectId: t3 },
857 ],
858 ["defaultAutoPull"],
859 );
860 expect(plan.serverWrites).toEqual([
861 {
862 environmentId: laptop,
863 label: laptop,
864 previous: expect.anything(),
865 patch: {
866 projectSettingsOverrides: { [fleet]: { defaultThreadEnvMode: "local" }, [t3]: null },
867 },
868 },
869 ]);
870 });
871});
872
873describe("null patches at project scope", () => {
874 it("removes the override for keys that cannot store null and keeps it for keys that can", () => {
875 const environmentId = EnvironmentId.make("laptop");
876 const projectId = ProjectId.make("fleet");
877 const scope = {
878 kind: "project" as const,
879 group: {} as never,
880 environmentId: null,
881 label: "fleet",
882 members: [{ id: projectId, environmentId } as never],
883 environmentIds: [environmentId],
884 };
885 const environments = [
886 {
887 environmentId,
888 label: "Laptop",
889 connection: { phase: "connected" as const },
890 serverConfig: {
891 settings: {
892 ...DEFAULT_SERVER_SETTINGS,
893 projectSettingsOverrides: {
894 [projectId]: { defaultThreadEnvMode: "worktree" as const, defaultAutoPull: true },
895 },
896 },
897 environment: { capabilities: { projectSettingsOverrides: true } },
898 },
899 },
900 ];
901 expect(
902 planScopedSettingsPatch(scope, environments, { defaultThreadEnvMode: null }).serverWrites[0]
903 ?.patch,
904 ).toEqual({ projectSettingsOverrides: { [projectId]: { defaultAutoPull: true } } });
905 expect(
906 planScopedSettingsPatch(scope, environments, { defaultModelSelection: null }).serverWrites[0]
907 ?.patch,
908 ).toEqual({
909 projectSettingsOverrides: {
910 [projectId]: {
911 defaultThreadEnvMode: "worktree",
912 defaultAutoPull: true,
913 defaultModelSelection: null,
914 },
915 },
916 });
917 });
918});
919
920describe("partial object patches at project scope", () => {
921 it("completes a writing style field patch from the target's effective value", () => {
922 const environmentId = EnvironmentId.make("laptop");
923 const projectId = ProjectId.make("fleet");
924 const member = {
925 id: projectId,
926 environmentId,
927 physicalProjectKey: "laptop:/repo",
928 environmentLabel: "Laptop",
929 title: "fleet",
930 workspaceRoot: "/repo",
931 defaultModelSelection: null,
932 scripts: [],
933 createdAt: "2026-01-01T00:00:00.000Z",
934 updatedAt: "2026-01-01T00:00:00.000Z",
935 };
936 const settings = {
937 ...DEFAULT_SERVER_SETTINGS,
938 projectSettingsOverrides: {
939 [projectId]: {
940 sourceControlWritingStyle: {
941 mode: "custom" as const,
942 customInstructions: "Keep it short.",
943 followChangeRequestTemplates: false,
944 },
945 },
946 },
947 };
948 const plan = planScopedSettingsPatch(
949 {
950 kind: "project",
951 group: {} as never,
952 environmentId: null,
953 label: "fleet",
954 members: [member as never],
955 environmentIds: [environmentId],
956 },
957 [
958 {
959 environmentId,
960 label: "Laptop",
961 connection: { phase: "connected" },
962 serverConfig: {
963 settings,
964 },
965 },
966 ],
967 { sourceControlWritingStyle: { customInstructions: "Be terse." } },
968 );
969 expect(plan.serverWrites[0]?.patch).toEqual({
970 projectSettingsOverrides: {
971 [projectId]: {
972 sourceControlWritingStyle: {
973 mode: "custom",
974 customInstructions: "Be terse.",
975 followChangeRequestTemplates: false,
976 },
977 },
978 },
979 });
980 });
981});
982
983it("routes legacy model preference keys exclusively to the selected environment", () => {
984 const patch = {
985 favorites: [{ provider: ProviderInstanceId.make("codex"), model: "sol" }],
986 providerModelPreferences: {},
987 };
988 const plan = planScopedSettingsPatch(named, environments, patch);
989 expect(plan.clientPatch).toEqual({});
990 expect(plan.hasClientWrite).toBe(false);
991 expect(plan.serverWrites).toEqual([
992 {
993 environmentId: server.environmentId,
994 label: server.label,
995 previous: expect.anything(),
996 patch,
997 },
998 ]);
999});
1000
1001describe("model selection patches at project scope", () => {
1002 const codex = ProviderInstanceId.make("codex");
1003 const claude = ProviderInstanceId.make("claudeAgent");
1004 const saved = {
1005 instanceId: codex,
1006 model: "gpt-5.6",
1007 options: [{ id: "reasoningEffort", value: "high" }],
1008 };
1009 const customized = environment("Server", {
1010 settings: {
1011 projectSettingsOverrides: {
1012 [projectId]: {
1013 defaultModelSelection: saved,
1014 sourceControlWriterModelSelection: saved,
1015 reviewGuideModelSelection: saved,
1016 textGenerationModelSelection: saved,
1017 },
1018 },
1019 },
1020 });
1021
1022 // regression: #16581 changing a project's model kept the old model's options
1023 it("replaces old options when changing model selections", () => {
1024 const plan = planScopedSettingsPatch(checkout, [customized], {
1025 defaultModelSelection: { instanceId: claude, model: "claude-opus-4-8" },
1026 sourceControlWriterModelSelection: { instanceId: codex, model: "gpt-5.6-mini" },
1027 reviewGuideModelSelection: { instanceId: codex, model: "gpt-5.6-mini" },
1028 textGenerationModelSelection: { instanceId: claude, model: "claude-sonnet-4-6" },
1029 });
1030 expect(plan.serverWrites[0]?.patch.projectSettingsOverrides?.[projectId]).toEqual({
1031 defaultModelSelection: { instanceId: claude, model: "claude-opus-4-8" },
1032 sourceControlWriterModelSelection: { instanceId: codex, model: "gpt-5.6-mini" },
1033 reviewGuideModelSelection: { instanceId: codex, model: "gpt-5.6-mini" },
1034 textGenerationModelSelection: { instanceId: claude, model: "claude-sonnet-4-6" },
1035 });
1036 });
1037
1038 it("completes partial text-generation selections without retaining old options", () => {
1039 const modelPlan = planScopedSettingsPatch(checkout, [customized], {
1040 textGenerationModelSelection: { model: "gpt-5.6-mini" },
1041 });
1042 expect(
1043 modelPlan.serverWrites[0]?.patch.projectSettingsOverrides?.[projectId]
1044 ?.textGenerationModelSelection,
1045 ).toEqual({ instanceId: codex, model: "gpt-5.6-mini" });
1046
1047 const options = [{ id: "reasoningEffort", value: "low" }];
1048 const optionsPlan = planScopedSettingsPatch(checkout, [customized], {
1049 textGenerationModelSelection: { options },
1050 });
1051 expect(
1052 optionsPlan.serverWrites[0]?.patch.projectSettingsOverrides?.[projectId]
1053 ?.textGenerationModelSelection,
1054 ).toEqual({ ...saved, options });
1055 });
1056});