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