Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

scopedSettings.test.ts

622 lines21.3 KB

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