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