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