Open History to see the last commit
1import {
2 DEFAULT_SERVER_SETTINGS,
3 EnvironmentId,
4 ProjectId,
5 type ServerSettings,
6} from "@t3tools/contracts";
7import { describe, expect, it, vi } from "vite-plus/test";
8
9import type { SidebarProjectSnapshot } from "../../sidebarProjectGrouping";
10import {
11 listProjectOverrides,
12 persistScopedSettingsPatch,
13 planProjectOverridesClear,
14 planScopedSettingsClear,
15 planScopedSettingsPatch,
16 resolveScopedSettingsTargets,
17 scopedSettingsAreMixed,
18 scopedSettingsSource,
19 selectScopedSettingsEnvironments,
20} from "./scopedSettings";
21import { resolveSettingsScope } from "./settingsScope";
22
23function environment(
24 id: string,
25 options: {
26 connected?: boolean;
27 loaded?: boolean;
28 settings?: Partial<ServerSettings>;
29 projectOverrides?: boolean;
30 } = {},
31) {
32 return {
33 environmentId: EnvironmentId.make(id),
34 label: id,
35 connection: {
36 phase: options.connected === false ? ("offline" as const) : ("connected" as const),
37 },
38 serverConfig:
39 options.loaded === false
40 ? null
41 : {
42 settings: { ...DEFAULT_SERVER_SETTINGS, ...options.settings },
43 environment: {
44 capabilities: { projectSettingsOverrides: options.projectOverrides !== false },
45 },
46 },
47 };
48}
49
50const laptop = environment("Laptop");
51const server = environment("Server");
52const offline = environment("Offline", { connected: false });
53const loading = environment("Loading", { loaded: false });
54const environments = [laptop, server, offline, loading];
55const all = resolveSettingsScope({}, [], environments);
56const named = resolveSettingsScope({ machine: server.environmentId }, [], environments);
57
58const projectId = ProjectId.make("project");
59const laptopProjectId = ProjectId.make("laptop-project");
60const member = {
61 id: projectId,
62 environmentId: server.environmentId,
63 title: "Project",
64 workspaceRoot: "/repo",
65 physicalProjectKey: `${server.environmentId}:/repo`,
66 environmentLabel: server.label,
67 defaultModelSelection: null,
68 scripts: [],
69 createdAt: "2026-09-07T00:00:00.000Z",
70 updatedAt: "2026-09-07T00:00:00.000Z",
71};
72const laptopMember = {
73 ...member,
74 id: laptopProjectId,
75 environmentId: laptop.environmentId,
76 physicalProjectKey: `${laptop.environmentId}:/repo`,
77 environmentLabel: laptop.label,
78};
79const group: SidebarProjectSnapshot = {
80 ...member,
81 projectKey: "project-group",
82 displayName: "Project",
83 memberProjects: [member, laptopMember],
84 memberProjectRefs: [
85 { environmentId: server.environmentId, projectId },
86 { environmentId: laptop.environmentId, projectId: laptopProjectId },
87 ],
88 groupedProjectCount: 2,
89 environmentPresence: "remote-only",
90 allRemoteMembersAreDesktopLocal: false,
91 allRemoteMembersAreWsl: false,
92 remoteEnvironmentLabels: [server.label, laptop.label],
93};
94const project = resolveSettingsScope({ project: group.projectKey }, [group], environments);
95const checkout = resolveSettingsScope(
96 { project: group.projectKey, machine: server.environmentId, checkout: member.physicalProjectKey },
97 [group],
98 environments,
99);
100
101describe("scoped settings targets", () => {
102 it("uses the named environment even when a different primary is available", () => {
103 const selected = selectScopedSettingsEnvironments(named, environments, laptop.environmentId);
104 expect(selected.environments).toEqual([server]);
105 expect(selected.environment).toBe(server);
106 });
107
108 it("keeps an offline named environment selected without falling back to primary", () => {
109 const scope = resolveSettingsScope({ machine: offline.environmentId }, [], environments);
110 const selected = selectScopedSettingsEnvironments(scope, environments, laptop.environmentId);
111 expect(selected.environments).toEqual([offline]);
112 expect(selected.connectedEnvironments).toEqual([]);
113 expect(selected.environment).toBeNull();
114 expect(
115 planScopedSettingsPatch(scope, environments, { enableProviderUpdateChecks: false }),
116 ).toMatchObject({
117 serverWrites: [],
118 unavailableReason: "Connect Offline to save this setting.",
119 });
120 });
121
122 it("prefers the selected primary as the aggregate representative without including disconnected targets", () => {
123 const selected = selectScopedSettingsEnvironments(all, environments, server.environmentId);
124 expect(selected.environment).toBe(server);
125 expect(selected.environments).toEqual(environments);
126 expect(selected.connectedEnvironments).toEqual([laptop, server]);
127 });
128
129 it("resolves each member's effective settings and source at project scope", () => {
130 const overridden = environment("Server", {
131 settings: {
132 defaultAutoPull: false,
133 projectSettingsOverrides: { [projectId]: { defaultAutoPull: true } },
134 },
135 });
136 const targets = resolveScopedSettingsTargets(project, [laptop, overridden]);
137 expect(targets.map((target) => [target.projectId, target.settings.defaultAutoPull])).toEqual([
138 [projectId, true],
139 [laptopProjectId, false],
140 ]);
141 expect(scopedSettingsSource(targets, ["defaultAutoPull"])).toBe("mixed");
142 expect(scopedSettingsSource([targets[0]!], ["defaultAutoPull"])).toBe("project");
143 expect(scopedSettingsSource(targets, ["enableProviderUpdateChecks"])).toBe("environment");
144 expect(scopedSettingsAreMixed(targets, ["defaultAutoPull"])).toBe(true);
145 });
146});
147
148describe("scoped settings writes", () => {
149 it("isolates a formerly shared server preference to the named environment", async () => {
150 const persistServer = vi.fn().mockResolvedValue({ _tag: "Success" });
151 const persistClient = vi.fn();
152 await persistScopedSettingsPatch(
153 planScopedSettingsPatch(named, environments, { sidebarAutoSettleOnMerge: false }),
154 persistServer,
155 persistClient,
156 );
157 expect(persistServer.mock.calls).toEqual([
158 [
159 {
160 environmentId: server.environmentId,
161 input: { patch: { sidebarAutoSettleOnMerge: false } },
162 },
163 ],
164 ]);
165 expect(persistClient).not.toHaveBeenCalled();
166 });
167
168 it("writes an aggregate preference only to connected environments with loaded configuration", async () => {
169 const persistServer = vi.fn().mockResolvedValue({ _tag: "Success" });
170 const persistClient = vi.fn();
171 await persistScopedSettingsPatch(
172 planScopedSettingsPatch(all, environments, { enableProviderUpdateChecks: false }),
173 persistServer,
174 persistClient,
175 );
176 expect(persistServer.mock.calls.map(([input]) => input.environmentId)).toEqual([
177 laptop.environmentId,
178 server.environmentId,
179 ]);
180 expect(persistClient).not.toHaveBeenCalled();
181 });
182
183 it("persists client keys locally at any scope alongside server keys", async () => {
184 const persistServer = vi.fn().mockResolvedValue({ _tag: "Success" });
185 const persistClient = vi.fn();
186 await persistScopedSettingsPatch(
187 planScopedSettingsPatch(named, environments, {
188 diffIgnoreWhitespace: false,
189 enableProviderUpdateChecks: false,
190 }),
191 persistServer,
192 persistClient,
193 );
194 expect(persistClient).toHaveBeenCalledExactlyOnceWith({ diffIgnoreWhitespace: false });
195 expect(persistServer).toHaveBeenCalledExactlyOnceWith({
196 environmentId: server.environmentId,
197 input: { patch: { enableProviderUpdateChecks: false } },
198 });
199 });
200
201 it("writes project overrides into each member's entry on its environment", () => {
202 const withExisting = environment("Server", {
203 settings: {
204 projectSettingsOverrides: { [projectId]: { enableAgentBrowserAccess: false } },
205 },
206 });
207 const plan = planScopedSettingsPatch(project, [laptop, withExisting], {
208 defaultAutoPull: true,
209 });
210 expect(plan.unavailableReason).toBeNull();
211 expect(plan.serverWrites).toEqual([
212 {
213 environmentId: server.environmentId,
214 label: server.label,
215 patch: {
216 projectSettingsOverrides: {
217 [projectId]: { enableAgentBrowserAccess: false, defaultAutoPull: true },
218 },
219 },
220 },
221 {
222 environmentId: laptop.environmentId,
223 label: laptop.label,
224 patch: { projectSettingsOverrides: { [laptopProjectId]: { defaultAutoPull: true } } },
225 },
226 ]);
227 expect(
228 planScopedSettingsPatch(checkout, [laptop, server], { defaultAutoPull: true }),
229 ).toMatchObject({
230 serverWrites: [{ environmentId: server.environmentId }],
231 });
232 });
233
234 it("scopes agent device access to projects while keeping hub and hosts environment-wide", () => {
235 const plan = planScopedSettingsPatch(project, [laptop, server], {
236 enableAgentDeviceAccess: true,
237 });
238 expect(plan.serverWrites.map((write) => write.patch)).toEqual([
239 { projectSettingsOverrides: { [projectId]: { enableAgentDeviceAccess: true } } },
240 { projectSettingsOverrides: { [laptopProjectId]: { enableAgentDeviceAccess: true } } },
241 ]);
242 for (const patch of [{ enableDeviceSupport: true }, { deviceHosts: [] }]) {
243 expect(planScopedSettingsPatch(project, environments, patch).serverWrites).toEqual([]);
244 }
245 });
246
247 it("refuses environment-wide keys and older servers at project scope", () => {
248 expect(
249 planScopedSettingsPatch(project, environments, { enableProviderUpdateChecks: false }),
250 ).toMatchObject({
251 serverWrites: [],
252 unavailableReason: "This setting is environment-wide and cannot be overridden by a project.",
253 });
254 const legacy = environment("Server", { projectOverrides: false });
255 expect(
256 planScopedSettingsPatch(checkout, [laptop, legacy], { defaultAutoPull: true }),
257 ).toMatchObject({ serverWrites: [], unavailableReason: expect.stringContaining("update") });
258 });
259
260 it("clears overrides per member and removes an emptied entry", () => {
261 const withOverrides = environment("Server", {
262 settings: {
263 projectSettingsOverrides: {
264 [projectId]: { defaultAutoPull: true, enableAgentBrowserAccess: false },
265 },
266 },
267 });
268 const plan = planScopedSettingsClear(checkout, [laptop, withOverrides], ["defaultAutoPull"]);
269 expect(plan.serverWrites).toEqual([
270 {
271 environmentId: server.environmentId,
272 label: server.label,
273 patch: { projectSettingsOverrides: { [projectId]: { enableAgentBrowserAccess: false } } },
274 },
275 ]);
276 expect(
277 planScopedSettingsClear(
278 checkout,
279 [laptop, withOverrides],
280 ["defaultAutoPull", "enableAgentBrowserAccess"],
281 ).serverWrites[0]?.patch,
282 ).toEqual({ projectSettingsOverrides: { [projectId]: null } });
283 });
284
285 it("never substitutes an environment-default write for an invalid scope", () => {
286 const scope = resolveSettingsScope({ machine: "removed" }, [group], environments);
287 const plan = planScopedSettingsPatch(scope, environments, { enableAgentBrowserAccess: false });
288 expect(plan.serverWrites).toEqual([]);
289 expect(plan.hasClientWrite).toBe(false);
290 expect(plan.unavailableReason).not.toBeNull();
291 });
292
293 it("waits for every target and identifies both RPC failures and rejected writes", async () => {
294 const third = environment("Third");
295 const fourth = environment("Fourth");
296 const selected = [...environments, third, fourth];
297 const scope = resolveSettingsScope({}, [], selected);
298 const persistServer = vi
299 .fn()
300 .mockResolvedValueOnce({ _tag: "Success" })
301 .mockResolvedValueOnce({ _tag: "Failure" })
302 .mockRejectedValueOnce(new Error("Disconnected during save"))
303 .mockResolvedValueOnce({ _tag: "Success" });
304 const result = await persistScopedSettingsPatch(
305 planScopedSettingsPatch(scope, selected, { enableAgentBrowserAccess: false }),
306 persistServer,
307 vi.fn(),
308 );
309 expect(result.savedEnvironmentCount).toBe(2);
310 expect(result.failedEnvironments.map(({ label }) => label)).toEqual([
311 server.label,
312 third.label,
313 ]);
314 expect(persistServer).toHaveBeenCalledTimes(4);
315 });
316});
317
318describe("scoped settings mixed values", () => {
319 it("compares only requested settings across connected targets", () => {
320 const changed = environment("Changed", { settings: { enableAgentBrowserAccess: false } });
321 const targets = resolveScopedSettingsTargets(all, [laptop, changed]);
322 expect(scopedSettingsAreMixed(targets, ["enableAgentBrowserAccess"])).toBe(true);
323 expect(scopedSettingsAreMixed(targets, ["enableProviderUpdateChecks"])).toBe(false);
324 expect(scopedSettingsAreMixed([], ["enableAgentBrowserAccess"])).toBe(false);
325 });
326
327 it("treats independently decoded equal nested settings as the same value", () => {
328 const style = {
329 ...DEFAULT_SERVER_SETTINGS.sourceControlWritingStyle,
330 mode: "custom" as const,
331 customInstructions: "Use plain language",
332 };
333 const first = environment("First", { settings: { sourceControlWritingStyle: { ...style } } });
334 const second = environment("Second", { settings: { sourceControlWritingStyle: { ...style } } });
335 const targets = resolveScopedSettingsTargets(all, [first, second]);
336 expect(scopedSettingsAreMixed(targets, ["sourceControlWritingStyle"])).toBe(false);
337 });
338});
339
340describe("project overrides at environment scope", () => {
341 const laptop = EnvironmentId.make("laptop");
342 const desk = EnvironmentId.make("desk");
343 const fleet = ProjectId.make("fleet");
344 const t3 = ProjectId.make("t3");
345 const environment = (
346 environmentId: EnvironmentId,
347 overrides: ServerSettings["projectSettingsOverrides"],
348 ) => ({
349 environmentId,
350 label: environmentId,
351 connection: { phase: "connected" as const },
352 serverConfig: {
353 settings: { ...DEFAULT_SERVER_SETTINGS, projectSettingsOverrides: overrides },
354 environment: { capabilities: { projectSettingsOverrides: true } },
355 },
356 });
357
358 it("lists only the projects that override the keys", () => {
359 const entries = listProjectOverrides(
360 [
361 environment(laptop, {
362 [fleet]: { defaultAutoPull: true, defaultThreadEnvMode: "local" },
363 [t3]: { defaultThreadEnvMode: "local" },
364 }),
365 environment(desk, { [fleet]: { defaultAutoPull: false } }),
366 ],
367 ["defaultAutoPull"],
368 );
369 expect(entries).toEqual([
370 { environmentId: laptop, projectId: fleet },
371 { environmentId: desk, projectId: fleet },
372 ]);
373 });
374
375 it("clears only those keys and drops entries that become empty", () => {
376 const plan = planProjectOverridesClear(
377 [
378 environment(laptop, {
379 [fleet]: { defaultAutoPull: true, defaultThreadEnvMode: "local" },
380 [t3]: { defaultAutoPull: true },
381 }),
382 ],
383 [
384 { environmentId: laptop, projectId: fleet },
385 { environmentId: laptop, projectId: t3 },
386 ],
387 ["defaultAutoPull"],
388 );
389 expect(plan.serverWrites).toEqual([
390 {
391 environmentId: laptop,
392 label: laptop,
393 patch: {
394 projectSettingsOverrides: { [fleet]: { defaultThreadEnvMode: "local" }, [t3]: null },
395 },
396 },
397 ]);
398 });
399});
400
401describe("partial object patches at project scope", () => {
402 it("completes a writing style field patch from the target's effective value", () => {
403 const environmentId = EnvironmentId.make("laptop");
404 const projectId = ProjectId.make("fleet");
405 const member = {
406 id: projectId,
407 environmentId,
408 physicalProjectKey: "laptop:/repo",
409 environmentLabel: "Laptop",
410 title: "fleet",
411 workspaceRoot: "/repo",
412 defaultModelSelection: null,
413 scripts: [],
414 createdAt: "2026-01-01T00:00:00.000Z",
415 updatedAt: "2026-01-01T00:00:00.000Z",
416 };
417 const settings = {
418 ...DEFAULT_SERVER_SETTINGS,
419 projectSettingsOverrides: {
420 [projectId]: {
421 sourceControlWritingStyle: {
422 mode: "custom" as const,
423 customInstructions: "Keep it short.",
424 followChangeRequestTemplates: false,
425 },
426 },
427 },
428 };
429 const plan = planScopedSettingsPatch(
430 {
431 kind: "project",
432 group: {} as never,
433 environmentId: null,
434 label: "fleet",
435 members: [member as never],
436 environmentIds: [environmentId],
437 },
438 [
439 {
440 environmentId,
441 label: "Laptop",
442 connection: { phase: "connected" },
443 serverConfig: {
444 settings,
445 environment: { capabilities: { projectSettingsOverrides: true } },
446 },
447 },
448 ],
449 { sourceControlWritingStyle: { customInstructions: "Be terse." } },
450 );
451 expect(plan.serverWrites[0]?.patch).toEqual({
452 projectSettingsOverrides: {
453 [projectId]: {
454 sourceControlWritingStyle: {
455 mode: "custom",
456 customInstructions: "Be terse.",
457 followChangeRequestTemplates: false,
458 },
459 },
460 },
461 });
462 });
463});