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("refuses environment-wide keys and older servers at project scope", () => {
235 expect(
236 planScopedSettingsPatch(project, environments, { enableProviderUpdateChecks: false }),
237 ).toMatchObject({
238 serverWrites: [],
239 unavailableReason: "This setting is environment-wide and cannot be overridden by a project.",
240 });
241 const legacy = environment("Server", { projectOverrides: false });
242 expect(
243 planScopedSettingsPatch(checkout, [laptop, legacy], { defaultAutoPull: true }),
244 ).toMatchObject({ serverWrites: [], unavailableReason: expect.stringContaining("update") });
245 });
246
247 it("clears overrides per member and removes an emptied entry", () => {
248 const withOverrides = environment("Server", {
249 settings: {
250 projectSettingsOverrides: {
251 [projectId]: { defaultAutoPull: true, enableAgentBrowserAccess: false },
252 },
253 },
254 });
255 const plan = planScopedSettingsClear(checkout, [laptop, withOverrides], ["defaultAutoPull"]);
256 expect(plan.serverWrites).toEqual([
257 {
258 environmentId: server.environmentId,
259 label: server.label,
260 patch: { projectSettingsOverrides: { [projectId]: { enableAgentBrowserAccess: false } } },
261 },
262 ]);
263 expect(
264 planScopedSettingsClear(
265 checkout,
266 [laptop, withOverrides],
267 ["defaultAutoPull", "enableAgentBrowserAccess"],
268 ).serverWrites[0]?.patch,
269 ).toEqual({ projectSettingsOverrides: { [projectId]: null } });
270 });
271
272 it("never substitutes an environment-default write for an invalid scope", () => {
273 const scope = resolveSettingsScope({ machine: "removed" }, [group], environments);
274 const plan = planScopedSettingsPatch(scope, environments, { enableAgentBrowserAccess: false });
275 expect(plan.serverWrites).toEqual([]);
276 expect(plan.hasClientWrite).toBe(false);
277 expect(plan.unavailableReason).not.toBeNull();
278 });
279
280 it("waits for every target and identifies both RPC failures and rejected writes", async () => {
281 const third = environment("Third");
282 const fourth = environment("Fourth");
283 const selected = [...environments, third, fourth];
284 const scope = resolveSettingsScope({}, [], selected);
285 const persistServer = vi
286 .fn()
287 .mockResolvedValueOnce({ _tag: "Success" })
288 .mockResolvedValueOnce({ _tag: "Failure" })
289 .mockRejectedValueOnce(new Error("Disconnected during save"))
290 .mockResolvedValueOnce({ _tag: "Success" });
291 const result = await persistScopedSettingsPatch(
292 planScopedSettingsPatch(scope, selected, { enableAgentBrowserAccess: false }),
293 persistServer,
294 vi.fn(),
295 );
296 expect(result.savedEnvironmentCount).toBe(2);
297 expect(result.failedEnvironments.map(({ label }) => label)).toEqual([
298 server.label,
299 third.label,
300 ]);
301 expect(persistServer).toHaveBeenCalledTimes(4);
302 });
303});
304
305describe("scoped settings mixed values", () => {
306 it("compares only requested settings across connected targets", () => {
307 const changed = environment("Changed", { settings: { enableAgentBrowserAccess: false } });
308 const targets = resolveScopedSettingsTargets(all, [laptop, changed]);
309 expect(scopedSettingsAreMixed(targets, ["enableAgentBrowserAccess"])).toBe(true);
310 expect(scopedSettingsAreMixed(targets, ["enableProviderUpdateChecks"])).toBe(false);
311 expect(scopedSettingsAreMixed([], ["enableAgentBrowserAccess"])).toBe(false);
312 });
313
314 it("treats independently decoded equal nested settings as the same value", () => {
315 const style = {
316 ...DEFAULT_SERVER_SETTINGS.sourceControlWritingStyle,
317 mode: "custom" as const,
318 customInstructions: "Use plain language",
319 };
320 const first = environment("First", { settings: { sourceControlWritingStyle: { ...style } } });
321 const second = environment("Second", { settings: { sourceControlWritingStyle: { ...style } } });
322 const targets = resolveScopedSettingsTargets(all, [first, second]);
323 expect(scopedSettingsAreMixed(targets, ["sourceControlWritingStyle"])).toBe(false);
324 });
325});
326
327describe("project overrides at environment scope", () => {
328 const laptop = EnvironmentId.make("laptop");
329 const desk = EnvironmentId.make("desk");
330 const fleet = ProjectId.make("fleet");
331 const t3 = ProjectId.make("t3");
332 const environment = (
333 environmentId: EnvironmentId,
334 overrides: ServerSettings["projectSettingsOverrides"],
335 ) => ({
336 environmentId,
337 label: environmentId,
338 connection: { phase: "connected" as const },
339 serverConfig: {
340 settings: { ...DEFAULT_SERVER_SETTINGS, projectSettingsOverrides: overrides },
341 environment: { capabilities: { projectSettingsOverrides: true } },
342 },
343 });
344
345 it("lists only the projects that override the keys", () => {
346 const entries = listProjectOverrides(
347 [
348 environment(laptop, {
349 [fleet]: { defaultAutoPull: true, defaultThreadEnvMode: "local" },
350 [t3]: { defaultThreadEnvMode: "local" },
351 }),
352 environment(desk, { [fleet]: { defaultAutoPull: false } }),
353 ],
354 ["defaultAutoPull"],
355 );
356 expect(entries).toEqual([
357 { environmentId: laptop, projectId: fleet },
358 { environmentId: desk, projectId: fleet },
359 ]);
360 });
361
362 it("clears only those keys and drops entries that become empty", () => {
363 const plan = planProjectOverridesClear(
364 [
365 environment(laptop, {
366 [fleet]: { defaultAutoPull: true, defaultThreadEnvMode: "local" },
367 [t3]: { defaultAutoPull: true },
368 }),
369 ],
370 [
371 { environmentId: laptop, projectId: fleet },
372 { environmentId: laptop, projectId: t3 },
373 ],
374 ["defaultAutoPull"],
375 );
376 expect(plan.serverWrites).toEqual([
377 {
378 environmentId: laptop,
379 label: laptop,
380 patch: {
381 projectSettingsOverrides: { [fleet]: { defaultThreadEnvMode: "local" }, [t3]: null },
382 },
383 },
384 ]);
385 });
386});
387
388describe("partial object patches at project scope", () => {
389 it("completes a writing style field patch from the target's effective value", () => {
390 const environmentId = EnvironmentId.make("laptop");
391 const projectId = ProjectId.make("fleet");
392 const member = {
393 id: projectId,
394 environmentId,
395 physicalProjectKey: "laptop:/repo",
396 environmentLabel: "Laptop",
397 title: "fleet",
398 workspaceRoot: "/repo",
399 defaultModelSelection: null,
400 scripts: [],
401 createdAt: "2026-01-01T00:00:00.000Z",
402 updatedAt: "2026-01-01T00:00:00.000Z",
403 };
404 const settings = {
405 ...DEFAULT_SERVER_SETTINGS,
406 projectSettingsOverrides: {
407 [projectId]: {
408 sourceControlWritingStyle: {
409 mode: "custom" as const,
410 customInstructions: "Keep it short.",
411 followChangeRequestTemplates: false,
412 },
413 },
414 },
415 };
416 const plan = planScopedSettingsPatch(
417 {
418 kind: "project",
419 group: {} as never,
420 environmentId: null,
421 label: "fleet",
422 members: [member as never],
423 environmentIds: [environmentId],
424 },
425 [
426 {
427 environmentId,
428 label: "Laptop",
429 connection: { phase: "connected" },
430 serverConfig: {
431 settings,
432 environment: { capabilities: { projectSettingsOverrides: true } },
433 },
434 },
435 ],
436 { sourceControlWritingStyle: { customInstructions: "Be terse." } },
437 );
438 expect(plan.serverWrites[0]?.patch).toEqual({
439 projectSettingsOverrides: {
440 [projectId]: {
441 sourceControlWritingStyle: {
442 mode: "custom",
443 customInstructions: "Be terse.",
444 followChangeRequestTemplates: false,
445 },
446 },
447 },
448 });
449 });
450});