Open History to see the last commit
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 listProjectOverrides,
17 persistScopedSettingsPatch,
18 planProjectOverridesClear,
19 planScopedSettingsClear,
20 planScopedSettingsPatch,
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 projectOverrides?: boolean;
35 } = {},
36) {
37 return {
38 environmentId: EnvironmentId.make(id),
39 label: id,
40 connection: {
41 phase: options.connected === false ? ("offline" as const) : ("connected" as const),
42 },
43 serverConfig:
44 options.loaded === false
45 ? null
46 : {
47 settings: { ...DEFAULT_SERVER_SETTINGS, ...options.settings },
48 environment: {
49 capabilities: { projectSettingsOverrides: options.projectOverrides !== false },
50 },
51 },
52 };
53}
54
55const laptop = environment("Laptop");
56const server = environment("Server");
57const offline = environment("Offline", { connected: false });
58const loading = environment("Loading", { loaded: false });
59const environments = [laptop, server, offline, loading];
60const all = resolveSettingsScope({}, [], environments);
61const named = resolveSettingsScope({ machine: server.environmentId }, [], environments);
62
63const projectId = ProjectId.make("project");
64const laptopProjectId = ProjectId.make("laptop-project");
65const member = {
66 id: projectId,
67 environmentId: server.environmentId,
68 title: "Project",
69 workspaceRoot: "/repo",
70 physicalProjectKey: `${server.environmentId}:/repo`,
71 environmentLabel: server.label,
72 defaultModelSelection: null,
73 scripts: [],
74 createdAt: "2026-09-07T00:00:00.000Z",
75 updatedAt: "2026-09-07T00:00:00.000Z",
76};
77const laptopMember = {
78 ...member,
79 id: laptopProjectId,
80 environmentId: laptop.environmentId,
81 physicalProjectKey: `${laptop.environmentId}:/repo`,
82 environmentLabel: laptop.label,
83};
84const group: SidebarProjectSnapshot = {
85 ...member,
86 projectKey: "project-group",
87 displayName: "Project",
88 memberProjects: [member, laptopMember],
89 memberProjectRefs: [
90 { environmentId: server.environmentId, projectId },
91 { environmentId: laptop.environmentId, projectId: laptopProjectId },
92 ],
93 groupedProjectCount: 2,
94 environmentPresence: "remote-only",
95 allRemoteMembersAreDesktopLocal: false,
96 allRemoteMembersAreWsl: false,
97 remoteEnvironmentLabels: [server.label, laptop.label],
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("prefers the selected primary as the aggregate representative without including disconnected targets", () => {
128 const selected = selectScopedSettingsEnvironments(all, environments, server.environmentId);
129 expect(selected.environment).toBe(server);
130 expect(selected.environments).toEqual(environments);
131 expect(selected.connectedEnvironments).toEqual([laptop, server]);
132 });
133
134 it("resolves each member's effective settings and source at project scope", () => {
135 const overridden = environment("Server", {
136 settings: {
137 defaultAutoPull: false,
138 projectSettingsOverrides: { [projectId]: { defaultAutoPull: true } },
139 },
140 });
141 const targets = resolveScopedSettingsTargets(project, [laptop, overridden]);
142 expect(targets.map((target) => [target.projectId, target.settings.defaultAutoPull])).toEqual([
143 [projectId, true],
144 [laptopProjectId, false],
145 ]);
146 expect(scopedSettingsSource(targets, ["defaultAutoPull"])).toBe("mixed");
147 expect(scopedSettingsSource([targets[0]!], ["defaultAutoPull"])).toBe("project");
148 expect(scopedSettingsSource(targets, ["enableProviderUpdateChecks"])).toBe("environment");
149 expect(scopedSettingsAreMixed(targets, ["defaultAutoPull"])).toBe(true);
150 });
151});
152
153describe("scoped settings writes", () => {
154 it("edits the effective machine policy without changing other machines' rules", () => {
155 const custom = environment("Laptop", {
156 settings: {
157 worktreeCleanup: {
158 mode: "custom",
159 rules: {
160 worktreeAfterDays: 12,
161 worktreeOnDelete: true,
162 worktreeOnMerge: true,
163 worktreeUnchanged: false,
164 worktreeKeepWhen: "uncommitted-changes",
165 },
166 },
167 },
168 });
169 const disabled = environment("Server", {
170 settings: { worktreeCleanup: { mode: "off" } },
171 });
172 const targets = [custom, disabled];
173 const plan = planScopedSettingsPatch(all, targets, {
174 storageCleanup: { worktreeOnDelete: false },
175 });
176 const policies = plan.serverWrites.map((write, index) =>
177 resolveWorktreeCleanup(
178 applyServerSettingsPatch(targets[index]!.serverConfig!.settings, write.patch),
179 null,
180 ),
181 );
182 expect(policies).toEqual([
183 {
184 worktreeAfterDays: 12,
185 worktreeOnDelete: false,
186 worktreeOnMerge: true,
187 worktreeUnchanged: false,
188 worktreeKeepWhen: "uncommitted-changes",
189 },
190 {
191 worktreeAfterDays: null,
192 worktreeOnDelete: false,
193 worktreeOnMerge: false,
194 worktreeUnchanged: false,
195 worktreeKeepWhen: "uncommitted-changes",
196 },
197 ]);
198 });
199 it("isolates a formerly shared server preference to the named environment", async () => {
200 const persistServer = vi.fn().mockResolvedValue({ _tag: "Success" });
201 const persistClient = vi.fn();
202 await persistScopedSettingsPatch(
203 planScopedSettingsPatch(named, environments, { sidebarAutoSettleOnMerge: false }),
204 persistServer,
205 persistClient,
206 );
207 expect(persistServer.mock.calls).toEqual([
208 [
209 {
210 environmentId: server.environmentId,
211 input: { patch: { sidebarAutoSettleOnMerge: false } },
212 },
213 ],
214 ]);
215 expect(persistClient).not.toHaveBeenCalled();
216 });
217
218 it("writes an aggregate preference only to connected environments with loaded configuration", async () => {
219 const persistServer = vi.fn().mockResolvedValue({ _tag: "Success" });
220 const persistClient = vi.fn();
221 await persistScopedSettingsPatch(
222 planScopedSettingsPatch(all, environments, { enableProviderUpdateChecks: false }),
223 persistServer,
224 persistClient,
225 );
226 expect(persistServer.mock.calls.map(([input]) => input.environmentId)).toEqual([
227 laptop.environmentId,
228 server.environmentId,
229 ]);
230 expect(persistClient).not.toHaveBeenCalled();
231 });
232
233 it("persists client keys locally at any scope alongside server keys", async () => {
234 const persistServer = vi.fn().mockResolvedValue({ _tag: "Success" });
235 const persistClient = vi.fn();
236 await persistScopedSettingsPatch(
237 planScopedSettingsPatch(named, environments, {
238 diffIgnoreWhitespace: false,
239 enableProviderUpdateChecks: false,
240 }),
241 persistServer,
242 persistClient,
243 );
244 expect(persistClient).toHaveBeenCalledExactlyOnceWith({ diffIgnoreWhitespace: false });
245 expect(persistServer).toHaveBeenCalledExactlyOnceWith({
246 environmentId: server.environmentId,
247 input: { patch: { enableProviderUpdateChecks: false } },
248 });
249 });
250
251 it("writes project overrides into each member's entry on its environment", () => {
252 const withExisting = environment("Server", {
253 settings: {
254 projectSettingsOverrides: { [projectId]: { enableAgentBrowserAccess: false } },
255 },
256 });
257 const plan = planScopedSettingsPatch(project, [laptop, withExisting], {
258 defaultAutoPull: true,
259 });
260 expect(plan.unavailableReason).toBeNull();
261 expect(plan.serverWrites).toEqual([
262 {
263 environmentId: server.environmentId,
264 label: server.label,
265 patch: {
266 projectSettingsOverrides: {
267 [projectId]: { enableAgentBrowserAccess: false, defaultAutoPull: true },
268 },
269 },
270 },
271 {
272 environmentId: laptop.environmentId,
273 label: laptop.label,
274 patch: { projectSettingsOverrides: { [laptopProjectId]: { defaultAutoPull: true } } },
275 },
276 ]);
277 expect(
278 planScopedSettingsPatch(checkout, [laptop, server], { defaultAutoPull: true }),
279 ).toMatchObject({
280 serverWrites: [{ environmentId: server.environmentId }],
281 });
282 });
283
284 it("keeps each project's other cleanup rules when changing one rule across machines", () => {
285 const machine = environment("Laptop", {
286 settings: {
287 storageCleanup: { ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeAfterDays: 30 },
288 },
289 });
290 const customized = environment("Server", {
291 settings: {
292 projectSettingsOverrides: {
293 [projectId]: {
294 defaultAutoPull: true,
295 worktreeCleanup: {
296 mode: "custom",
297 rules: {
298 worktreeAfterDays: 8,
299 worktreeOnDelete: false,
300 worktreeOnMerge: true,
301 worktreeUnchanged: false,
302 worktreeKeepWhen: "uncommitted-changes",
303 },
304 },
305 },
306 },
307 },
308 });
309 const plan = planScopedSettingsPatch(project, [machine, customized], {
310 worktreeCleanup: { mode: "custom", rules: { worktreeOnDelete: true } },
311 });
312 expect(plan.serverWrites.map((write) => write.patch.projectSettingsOverrides)).toEqual([
313 {
314 [projectId]: {
315 defaultAutoPull: true,
316 worktreeCleanup: {
317 mode: "custom",
318 rules: {
319 worktreeAfterDays: 8,
320 worktreeOnDelete: true,
321 worktreeOnMerge: true,
322 worktreeUnchanged: false,
323 worktreeKeepWhen: "uncommitted-changes",
324 },
325 },
326 },
327 },
328 {
329 [laptopProjectId]: {
330 worktreeCleanup: {
331 mode: "custom",
332 rules: {
333 worktreeAfterDays: 30,
334 worktreeOnDelete: true,
335 worktreeOnMerge: false,
336 worktreeUnchanged: false,
337 worktreeKeepWhen: "uncommitted-changes",
338 },
339 },
340 },
341 },
342 ]);
343 expect(
344 planScopedSettingsClear(checkout, [customized], ["worktreeCleanup"]).serverWrites[0]?.patch,
345 ).toEqual({
346 projectSettingsOverrides: { [projectId]: { defaultAutoPull: true } },
347 });
348 expect(
349 planScopedSettingsPatch(project, [machine, customized], {
350 storageCleanup: { browserArtifactsAfterDays: 8 },
351 }).serverWrites,
352 ).toEqual([]);
353 });
354
355 it("scopes agent device access to projects while keeping hub and hosts environment-wide", () => {
356 const plan = planScopedSettingsPatch(project, [laptop, server], {
357 enableAgentDeviceAccess: true,
358 });
359 expect(plan.serverWrites.map((write) => write.patch)).toEqual([
360 { projectSettingsOverrides: { [projectId]: { enableAgentDeviceAccess: true } } },
361 { projectSettingsOverrides: { [laptopProjectId]: { enableAgentDeviceAccess: true } } },
362 ]);
363 for (const patch of [{ enableDeviceSupport: true }, { deviceHosts: [] }]) {
364 expect(planScopedSettingsPatch(project, environments, patch).serverWrites).toEqual([]);
365 }
366 });
367
368 it("refuses environment-wide keys and older servers at project scope", () => {
369 expect(
370 planScopedSettingsPatch(project, environments, { enableProviderUpdateChecks: false }),
371 ).toMatchObject({
372 serverWrites: [],
373 unavailableReason: "This setting is environment-wide and cannot be overridden by a project.",
374 });
375 const legacy = environment("Server", { projectOverrides: false });
376 expect(
377 planScopedSettingsPatch(checkout, [laptop, legacy], { defaultAutoPull: true }),
378 ).toMatchObject({ serverWrites: [], unavailableReason: expect.stringContaining("update") });
379 });
380
381 it("clears overrides per member and removes an emptied entry", () => {
382 const withOverrides = environment("Server", {
383 settings: {
384 projectSettingsOverrides: {
385 [projectId]: { defaultAutoPull: true, enableAgentBrowserAccess: false },
386 },
387 },
388 });
389 const plan = planScopedSettingsClear(checkout, [laptop, withOverrides], ["defaultAutoPull"]);
390 expect(plan.serverWrites).toEqual([
391 {
392 environmentId: server.environmentId,
393 label: server.label,
394 patch: { projectSettingsOverrides: { [projectId]: { enableAgentBrowserAccess: false } } },
395 },
396 ]);
397 expect(
398 planScopedSettingsClear(
399 checkout,
400 [laptop, withOverrides],
401 ["defaultAutoPull", "enableAgentBrowserAccess"],
402 ).serverWrites[0]?.patch,
403 ).toEqual({ projectSettingsOverrides: { [projectId]: null } });
404 });
405
406 it("never substitutes an environment-default write for an invalid scope", () => {
407 const scope = resolveSettingsScope({ machine: "removed" }, [group], environments);
408 const plan = planScopedSettingsPatch(scope, environments, { enableAgentBrowserAccess: false });
409 expect(plan.serverWrites).toEqual([]);
410 expect(plan.hasClientWrite).toBe(false);
411 expect(plan.unavailableReason).not.toBeNull();
412 });
413
414 it("waits for every target and identifies both RPC failures and rejected writes", async () => {
415 const third = environment("Third");
416 const fourth = environment("Fourth");
417 const selected = [...environments, third, fourth];
418 const scope = resolveSettingsScope({}, [], selected);
419 const persistServer = vi
420 .fn()
421 .mockResolvedValueOnce({ _tag: "Success" })
422 .mockResolvedValueOnce({
423 _tag: "Failure",
424 cause: Cause.fail(
425 new EnvironmentAuthorizationError({
426 requiredScope: "settings:write",
427 message: "This connection lacks permission to change settings.",
428 }),
429 ),
430 })
431 .mockRejectedValueOnce(new Error("Disconnected during save"))
432 .mockResolvedValueOnce({ _tag: "Success" });
433 const result = await persistScopedSettingsPatch(
434 planScopedSettingsPatch(scope, selected, { enableAgentBrowserAccess: false }),
435 persistServer,
436 vi.fn(),
437 );
438 expect(result.savedEnvironmentCount).toBe(2);
439 expect(result.savedEnvironments.map(({ label }) => label)).toEqual([
440 laptop.label,
441 fourth.label,
442 ]);
443 expect(result.failedEnvironments.map(({ message }) => message)).toEqual([
444 "This connection lacks permission to change settings.",
445 "Disconnected during save",
446 ]);
447 expect(result.failedEnvironments.map(({ label }) => label)).toEqual([
448 server.label,
449 third.label,
450 ]);
451 expect(persistServer).toHaveBeenCalledTimes(4);
452 });
453});
454
455describe("scoped settings mixed values", () => {
456 it("compares only requested settings across connected targets", () => {
457 const changed = environment("Changed", { settings: { enableAgentBrowserAccess: false } });
458 const targets = resolveScopedSettingsTargets(all, [laptop, changed]);
459 expect(scopedSettingsAreMixed(targets, ["enableAgentBrowserAccess"])).toBe(true);
460 expect(scopedSettingsAreMixed(targets, ["enableProviderUpdateChecks"])).toBe(false);
461 expect(scopedSettingsAreMixed([], ["enableAgentBrowserAccess"])).toBe(false);
462 });
463
464 it("treats independently decoded equal nested settings as the same value", () => {
465 const style = {
466 ...DEFAULT_SERVER_SETTINGS.sourceControlWritingStyle,
467 mode: "custom" as const,
468 customInstructions: "Use plain language",
469 };
470 const first = environment("First", { settings: { sourceControlWritingStyle: { ...style } } });
471 const second = environment("Second", { settings: { sourceControlWritingStyle: { ...style } } });
472 const targets = resolveScopedSettingsTargets(all, [first, second]);
473 expect(scopedSettingsAreMixed(targets, ["sourceControlWritingStyle"])).toBe(false);
474 });
475});
476
477describe("project overrides at environment scope", () => {
478 const laptop = EnvironmentId.make("laptop");
479 const desk = EnvironmentId.make("desk");
480 const fleet = ProjectId.make("fleet");
481 const t3 = ProjectId.make("t3");
482 const environment = (
483 environmentId: EnvironmentId,
484 overrides: ServerSettings["projectSettingsOverrides"],
485 ) => ({
486 environmentId,
487 label: environmentId,
488 connection: { phase: "connected" as const },
489 serverConfig: {
490 settings: { ...DEFAULT_SERVER_SETTINGS, projectSettingsOverrides: overrides },
491 environment: { capabilities: { projectSettingsOverrides: true } },
492 },
493 });
494
495 it("lists only the projects that override the keys", () => {
496 const entries = listProjectOverrides(
497 [
498 environment(laptop, {
499 [fleet]: { defaultAutoPull: true, defaultThreadEnvMode: "local" },
500 [t3]: { defaultThreadEnvMode: "local" },
501 }),
502 environment(desk, { [fleet]: { defaultAutoPull: false } }),
503 ],
504 ["defaultAutoPull"],
505 );
506 expect(entries).toEqual([
507 { environmentId: laptop, projectId: fleet },
508 { environmentId: desk, projectId: fleet },
509 ]);
510 });
511
512 it("clears only those keys and drops entries that become empty", () => {
513 const plan = planProjectOverridesClear(
514 [
515 environment(laptop, {
516 [fleet]: { defaultAutoPull: true, defaultThreadEnvMode: "local" },
517 [t3]: { defaultAutoPull: true },
518 }),
519 ],
520 [
521 { environmentId: laptop, projectId: fleet },
522 { environmentId: laptop, projectId: t3 },
523 ],
524 ["defaultAutoPull"],
525 );
526 expect(plan.serverWrites).toEqual([
527 {
528 environmentId: laptop,
529 label: laptop,
530 patch: {
531 projectSettingsOverrides: { [fleet]: { defaultThreadEnvMode: "local" }, [t3]: null },
532 },
533 },
534 ]);
535 });
536});
537
538describe("null patches at project scope", () => {
539 it("removes the override for keys that cannot store null and keeps it for keys that can", () => {
540 const environmentId = EnvironmentId.make("laptop");
541 const projectId = ProjectId.make("fleet");
542 const scope = {
543 kind: "project" as const,
544 group: {} as never,
545 environmentId: null,
546 label: "fleet",
547 members: [{ id: projectId, environmentId } as never],
548 environmentIds: [environmentId],
549 };
550 const environments = [
551 {
552 environmentId,
553 label: "Laptop",
554 connection: { phase: "connected" as const },
555 serverConfig: {
556 settings: {
557 ...DEFAULT_SERVER_SETTINGS,
558 projectSettingsOverrides: {
559 [projectId]: { defaultThreadEnvMode: "worktree" as const, defaultAutoPull: true },
560 },
561 },
562 environment: { capabilities: { projectSettingsOverrides: true } },
563 },
564 },
565 ];
566 expect(
567 planScopedSettingsPatch(scope, environments, { defaultThreadEnvMode: null }).serverWrites[0]
568 ?.patch,
569 ).toEqual({ projectSettingsOverrides: { [projectId]: { defaultAutoPull: true } } });
570 expect(
571 planScopedSettingsPatch(scope, environments, { defaultModelSelection: null }).serverWrites[0]
572 ?.patch,
573 ).toEqual({
574 projectSettingsOverrides: {
575 [projectId]: {
576 defaultThreadEnvMode: "worktree",
577 defaultAutoPull: true,
578 defaultModelSelection: null,
579 },
580 },
581 });
582 });
583});
584
585describe("partial object patches at project scope", () => {
586 it("completes a writing style field patch from the target's effective value", () => {
587 const environmentId = EnvironmentId.make("laptop");
588 const projectId = ProjectId.make("fleet");
589 const member = {
590 id: projectId,
591 environmentId,
592 physicalProjectKey: "laptop:/repo",
593 environmentLabel: "Laptop",
594 title: "fleet",
595 workspaceRoot: "/repo",
596 defaultModelSelection: null,
597 scripts: [],
598 createdAt: "2026-01-01T00:00:00.000Z",
599 updatedAt: "2026-01-01T00:00:00.000Z",
600 };
601 const settings = {
602 ...DEFAULT_SERVER_SETTINGS,
603 projectSettingsOverrides: {
604 [projectId]: {
605 sourceControlWritingStyle: {
606 mode: "custom" as const,
607 customInstructions: "Keep it short.",
608 followChangeRequestTemplates: false,
609 },
610 },
611 },
612 };
613 const plan = planScopedSettingsPatch(
614 {
615 kind: "project",
616 group: {} as never,
617 environmentId: null,
618 label: "fleet",
619 members: [member as never],
620 environmentIds: [environmentId],
621 },
622 [
623 {
624 environmentId,
625 label: "Laptop",
626 connection: { phase: "connected" },
627 serverConfig: {
628 settings,
629 environment: { capabilities: { projectSettingsOverrides: true } },
630 },
631 },
632 ],
633 { sourceControlWritingStyle: { customInstructions: "Be terse." } },
634 );
635 expect(plan.serverWrites[0]?.patch).toEqual({
636 projectSettingsOverrides: {
637 [projectId]: {
638 sourceControlWritingStyle: {
639 mode: "custom",
640 customInstructions: "Be terse.",
641 followChangeRequestTemplates: false,
642 },
643 },
644 },
645 });
646 });
647});
648
649it("routes legacy model preference keys exclusively to the selected environment", () => {
650 const patch = {
651 favorites: [{ provider: ProviderInstanceId.make("codex"), model: "sol" }],
652 providerModelPreferences: {},
653 };
654 const plan = planScopedSettingsPatch(named, environments, patch);
655 expect(plan.clientPatch).toEqual({});
656 expect(plan.hasClientWrite).toBe(false);
657 expect(plan.serverWrites).toEqual([
658 { environmentId: server.environmentId, label: server.label, patch },
659 ]);
660});