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

SettingsServerControlsRouteScreen.test.tsx

228 lines7.7 KB

1import { DEFAULT_SERVER_SETTINGS, type ServerSettingsPatch } from "@t3tools/contracts";
2import { AsyncResult } from "effect/reactivity";
3import type { ReactNode } from "react";
4import { act } from "react";
5import { createRoot, type Root } from "react-dom/client";
6import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
7​
8const { Children, mocks } = vi.hoisted(() => ({
9 Children: ({ children }: { children?: ReactNode }) => children,
10 mocks: {
11 branchNaming: { onChange: (_patch: ServerSettingsPatch) => {} },
12 updateSettings: vi.fn(),
13 alert: vi.fn(),
14 targets: [] as ReturnType<typeof environment>[],
15 readOnly: new Set<string>(),
16 projectSelected: false,
17 },
18}));
19​
20vi.mock("react-native", () => ({
21 View: Children,
22 Alert: { alert: mocks.alert },
23 Pressable: ({
24 children,
25 disabled,
26 onPress,
27 accessibilityLabel,
28 }: {
29 children?: ReactNode;
30 disabled?: boolean;
31 onPress: () => void;
32 accessibilityLabel?: string;
33 }) => (
34 <button disabled={disabled} onClick={onPress} aria-label={accessibilityLabel}>
35 {children}
36 </button>
37 ),
38}));
39vi.mock("@effect/atom-react", () => ({
40 useAtomValue: () => AsyncResult.success({}),
41 useAtomSet: () => () => {},
42}));
43vi.mock("../../state/preferences", () => ({
44 mobilePreferencesAtom: {},
45 updateMobilePreferencesAtom: {},
46}));
47vi.mock("./components/AutoSettleDaysField", () => ({ AutoSettleDaysField: () => null }));
48vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ bottom: 0 }) }));
49vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({}) }));
50vi.mock("../../state/session", () => ({
51 readEnvironmentScope: () => true,
52 useEnvironmentsWithScope: () =>
53 new Set(
54 mocks.targets
55 .map((target) => target.environmentId)
56 .filter((environmentId) => !mocks.readOnly.has(environmentId)),
57 ),
58}));
59vi.mock("../../state/server", () => ({ serverEnvironment: { updateSettings: {} } }));
60vi.mock("../../state/use-atom-command", () => ({
61 useAtomCommand: () => mocks.updateSettings,
62}));
63vi.mock("../threads/thread-settings-options", () => ({ RUNTIME_MODE_CHOICES: [] }));
64vi.mock("../../components/ui/ScreenScrollView", () => ({ ScreenScrollView: Children }));
65vi.mock("../../components/ui/AppText", () => ({ AppText: Children }));
66vi.mock("../../components/ui/Button", () => ({
67 Button: ({
68 label,
69 disabled,
70 onPress,
71 }: {
72 label: string;
73 disabled?: boolean;
74 onPress: () => void;
75 }) => (
76 <button disabled={disabled} onClick={onPress}>
77 {label}
78 </button>
79 ),
80}));
81vi.mock("./components/SettingsScreen", () => ({ SettingsScreen: Children }));
82vi.mock("./components/SettingsEnvironmentFilterHeader", () => ({
83 AndroidSettingsEnvironmentFilter: () => null,
84 SettingsEnvironmentFilterHeader: () => null,
85}));
86vi.mock("./components/DatabaseStorageNotice", () => ({ DatabaseStorageNotice: () => null }));
87vi.mock("./components/SettingsSection", () => ({ SettingsSection: Children }));
88vi.mock("./components/SettingsChoiceRow", () => ({ SettingsChoiceRow: () => null }));
89vi.mock("./components/SettingsSwitchRow", () => ({
90 SettingsSwitchRow: ({
91 label,
92 value,
93 disabled,
94 onValueChange,
95 }: {
96 label: string;
97 value: boolean | null;
98 disabled?: boolean;
99 onValueChange: (value: boolean) => void;
100 }) => (
101 <button
102 role="switch"
103 aria-checked={value ?? "mixed"}
104 disabled={disabled}
105 onClick={() => onValueChange(!value)}
106 >
107 {label}
108 </button>
109 ),
110}));
111vi.mock("./components/SettingsRow", () => ({ SettingsRow: () => null }));
112vi.mock("./components/BranchNamingSettings", () => ({
113 BranchNamingSettings: (props: { onChange: (patch: ServerSettingsPatch) => void }) => {
114 mocks.branchNaming.onChange = props.onChange;
115 return null;
116 },
117}));
118vi.mock("./settings-environment-filter", () => ({
119 useSettingsEnvironmentFilter: () => ({
120 selectedTargets: mocks.targets,
121 projectGroups: [
122 {
123 key: "project",
124 label: "Project",
125 members: mocks.targets.map((target) => ({
126 project: { environmentId: target.environmentId, id: "project" },
127 })),
128 },
129 ],
130 selectedProjectKey: mocks.projectSelected ? "project" : null,
131 }),
132}));
133​
134import {
135 SettingsThreadsRouteScreen,
136 SettingsWorktreesRouteScreen,
137} from "./SettingsServerControlsRouteScreen";
138​
139function environment(environmentId: string, label: string) {
140 return {
141 environmentId,
142 label,
143 connection: { phase: "connected" },
144 serverConfig: {
145 settings: {
146 ...DEFAULT_SERVER_SETTINGS,
147 defaultAutoPull: false,
148 sidebarAutoSettleOnMerge: false,
149 },
150 environment: {
151 capabilities: { projectSettingsOverrides: true, threadAutoSettlement: true },
152 },
153 },
154 };
156​
157let root: Root;
158let container: HTMLDivElement;
159​
160beforeEach(() => {
161 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
162 container = document.createElement("div");
163 root = createRoot(container);
164 mocks.targets = [environment("local", "Local")];
165 mocks.projectSelected = false;
166 mocks.readOnly = new Set();
167 mocks.alert.mockReset();
168 mocks.updateSettings.mockReset();
169 mocks.updateSettings.mockResolvedValue(AsyncResult.success(undefined));
170});
171​
172afterEach(() => {
173 act(() => root.unmount());
174});
175​
176describe("SettingsServerControlsRouteScreen", () => {
177 it("sends a draft saved during a pending write once that write settles", async () => {
178 const pending = Promise.withResolvers<AsyncResult.Success<void>>();
179 mocks.updateSettings.mockReturnValueOnce(pending.promise);
180 act(() => root.render(<SettingsWorktreesRouteScreen />));
181​
182 act(() => mocks.branchNaming.onChange({ branchNamingMode: "custom" }));
183 act(() => mocks.branchNaming.onChange({ branchNameInstructions: "Use issue IDs." }));
184 expect(mocks.updateSettings).toHaveBeenCalledOnce();
185​
186 await act(async () => pending.resolve(AsyncResult.success(undefined)));
187​
188 expect(mocks.updateSettings).toHaveBeenCalledTimes(2);
189 expect(mocks.updateSettings).toHaveBeenLastCalledWith({
190 environmentId: "local",
191 input: {
192 patch: { branchNamingMode: "custom", branchNameInstructions: "Use issue IDs." },
193 },
194 });
195 });
196​
197 it("holds auto-settle changes until a pending project override write settles", async () => {
198 mocks.projectSelected = true;
199 const pending = Promise.withResolvers<AsyncResult.Success<void>>();
200 mocks.updateSettings.mockReturnValueOnce(pending.promise);
201 act(() => root.render(<SettingsThreadsRouteScreen />));
202 const toggle = (label: string) =>
203 [...container.querySelectorAll<HTMLButtonElement>('[role="switch"]')].find(
204 (button) => button.textContent === label,
205 )!;
206​
207 act(() => toggle("Agent browser access").click());
208 act(() => toggle("Auto-settle merged threads").click());
209​
210 // Both rewrite the whole project override, so a second write planned now would drop the first.
211 expect(mocks.updateSettings).toHaveBeenCalledOnce();
212 await act(async () => pending.resolve(AsyncResult.success(undefined)));
213 });
214​
215 it("disables auto-settle when a selected environment cannot save settings", () => {
216 const remote = environment("remote", "Remote");
217 // Auto-settle rows skip a server without auto-settlement, but the page still saves to it.
218 remote.serverConfig.environment.capabilities.threadAutoSettlement = false;
219 mocks.targets = [environment("local", "Local"), remote];
220 mocks.readOnly = new Set(["remote"]);
221 act(() => root.render(<SettingsThreadsRouteScreen />));
222​
223 const autoSettle = [...container.querySelectorAll<HTMLButtonElement>('[role="switch"]')].find(
224 (button) => button.textContent === "Auto-settle merged threads",
225 )!;
226 expect(autoSettle.disabled).toBe(true);
227 });
228});