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

SettingsServerControlsRouteScreen.test.tsx

329 lines11.2 KB

1import { DEFAULT_SERVER_SETTINGS, type ServerSettingsPatch } from "@t3tools/contracts";
2import * as Cause from "effect/Cause";
3import { AsyncResult } from "effect/reactivity";
4import type { ReactNode } from "react";
5import { act } from "react";
6import { createRoot, type Root } from "react-dom/client";
7import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
8​
9const { Children, mocks } = vi.hoisted(() => ({
10 Children: ({ children }: { children?: ReactNode }) => children,
11 mocks: {
12 branchNaming: { onChange: (_patch: ServerSettingsPatch) => {} },
13 updateSettings: vi.fn(),
14 alert: vi.fn(),
15 targets: [] as ReturnType<typeof environment>[],
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: () => new Set(mocks.targets.map((target) => target.environmentId)),
53}));
54vi.mock("../../state/server", () => ({ serverEnvironment: { updateSettings: {} } }));
55vi.mock("../../state/use-atom-command", () => ({
56 useAtomCommand: () => mocks.updateSettings,
57}));
58vi.mock("../threads/thread-settings-options", () => ({ RUNTIME_MODE_CHOICES: [] }));
59vi.mock("../../components/ui/ScreenScrollView", () => ({ ScreenScrollView: Children }));
60vi.mock("../../components/ui/AppText", () => ({ AppText: Children }));
61vi.mock("../../components/ui/Button", () => ({
62 Button: ({
63 label,
64 disabled,
65 onPress,
66 }: {
67 label: string;
68 disabled?: boolean;
69 onPress: () => void;
70 }) => (
71 <button disabled={disabled} onClick={onPress}>
72 {label}
73 </button>
74 ),
75}));
76vi.mock("./components/SettingsScreen", () => ({ SettingsScreen: Children }));
77vi.mock("./components/SettingsEnvironmentFilterHeader", () => ({
78 AndroidSettingsEnvironmentFilter: () => null,
79 SettingsEnvironmentFilterHeader: () => null,
80}));
81vi.mock("./components/DatabaseStorageNotice", () => ({ DatabaseStorageNotice: () => null }));
82vi.mock("./components/SettingsSection", () => ({ SettingsSection: Children }));
83vi.mock("./components/SettingsChoiceRow", () => ({ SettingsChoiceRow: () => null }));
84vi.mock("./components/SettingsSwitchRow", () => ({
85 SettingsSwitchRow: ({
86 label,
87 value,
88 disabled,
89 onValueChange,
90 }: {
91 label: string;
92 value: boolean | null;
93 disabled?: boolean;
94 onValueChange: (value: boolean) => void;
95 }) => (
96 <button
97 role="switch"
98 aria-checked={value ?? "mixed"}
99 disabled={disabled}
100 onClick={() => onValueChange(!value)}
101 >
102 {label}
103 </button>
104 ),
105}));
106vi.mock("./components/SettingsRow", () => ({ SettingsRow: () => null }));
107vi.mock("./components/BranchNamingSettings", () => ({
108 BranchNamingSettings: (props: { onChange: (patch: ServerSettingsPatch) => void }) => {
109 mocks.branchNaming.onChange = props.onChange;
110 return null;
111 },
112}));
113vi.mock("./settings-environment-filter", () => ({
114 useSettingsEnvironmentFilter: () => ({
115 selectedTargets: mocks.targets,
116 projectGroups: [
117 {
118 key: "project",
119 label: "Project",
120 members: mocks.targets.map((target) => ({
121 project: { environmentId: target.environmentId, id: "project" },
122 })),
123 },
124 ],
125 selectedProjectKey: mocks.projectSelected ? "project" : null,
126 }),
127}));
128​
129import { SettingsEnvironmentSourceControlRouteScreen } from "./SettingsServerControlsRouteScreen";
130import { SettingsThreadsRouteScreen } from "./SettingsThreadsRouteScreen";
131​
132function environment(environmentId: string, label: string) {
133 return {
134 environmentId,
135 label,
136 connection: { phase: "connected" },
137 serverConfig: {
138 settings: {
139 ...DEFAULT_SERVER_SETTINGS,
140 defaultAutoPull: false,
141 sidebarAutoSettleOnMerge: false,
142 },
143 environment: {
144 capabilities: { projectSettingsOverrides: true, threadAutoSettlement: true },
145 },
146 },
147 };
149​
150function button(label: string) {
151 const result = Array.from(container.querySelectorAll("button")).find(
152 (element) => element.textContent === label || element.getAttribute("aria-label") === label,
153 );
154 if (!result) throw new Error(`Missing button: ${label}`);
155 return result;
157​
158function expectFailures() {
159 const messages = mocks.alert.mock.calls
160 .map(([title, message]) => `${title}\n${message}`)
161 .join("\n");
162 expect.soft(messages).toMatch(/Alpha(?:(?!Beta)[\s\S])*Permission denied/);
163 expect.soft(messages).toMatch(/Beta(?:(?!Alpha)[\s\S])*Disk full/);
164 expect.soft(messages).not.toContain("Healthy");
166​
167function failTwoEnvironments() {
168 mocks.targets = [
169 environment("healthy", "Healthy"),
170 environment("alpha", "Alpha"),
171 environment("beta", "Beta"),
172 ];
173 mocks.updateSettings.mockImplementation(async ({ environmentId }: { environmentId: string }) =>
174 environmentId === "healthy"
175 ? AsyncResult.success(undefined)
176 : AsyncResult.failure(
177 Cause.fail(new Error(environmentId === "alpha" ? "Permission denied" : "Disk full")),
178 ),
179 );
181​
182let root: Root;
183let container: HTMLDivElement;
184​
185beforeEach(() => {
186 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
187 container = document.createElement("div");
188 root = createRoot(container);
189 mocks.targets = [environment("local", "Local")];
190 mocks.projectSelected = false;
191 mocks.alert.mockReset();
192 mocks.updateSettings.mockReset();
193 mocks.updateSettings.mockResolvedValue(AsyncResult.success(undefined));
194});
195​
196afterEach(() => {
197 act(() => root.unmount());
198});
199​
200describe("SettingsServerControlsRouteScreen", () => {
201 it("sends a draft saved during a pending write once that write settles", async () => {
202 const pending = Promise.withResolvers<AsyncResult.Success<void>>();
203 mocks.updateSettings.mockReturnValueOnce(pending.promise);
204 act(() => root.render(<SettingsEnvironmentSourceControlRouteScreen />));
205​
206 act(() => mocks.branchNaming.onChange({ branchNamingMode: "custom" }));
207 // The branch naming view closes with a draft while the mode write is pending.
208 act(() => mocks.branchNaming.onChange({ branchNameInstructions: "Use issue IDs." }));
209 expect(mocks.updateSettings).toHaveBeenCalledOnce();
210​
211 await act(async () => pending.resolve(AsyncResult.success(undefined)));
212​
213 expect(mocks.updateSettings).toHaveBeenCalledTimes(2);
214 expect(mocks.updateSettings).toHaveBeenLastCalledWith({
215 environmentId: "local",
216 input: {
217 patch: { branchNamingMode: "custom", branchNameInstructions: "Use issue IDs." },
218 },
219 });
220 });
221});
222​
223describe.each([
224 {
225 name: "source control",
226 Screen: SettingsEnvironmentSourceControlRouteScreen,
227 label: "Automatically pull",
228 key: "defaultAutoPull",
229 },
230 {
231 name: "thread behavior",
232 Screen: SettingsThreadsRouteScreen,
233 label: "Auto-settle merged threads",
234 key: "sidebarAutoSettleOnMerge",
235 },
236] as const)("$name shared settings", ({ Screen, label, key }) => {
237 it("identifies each failed environment and reason, then allows a subscription-driven retry", async () => {
238 failTwoEnvironments();
239 const pending = Promise.withResolvers<AsyncResult.Success<void>>();
240 mocks.updateSettings.mockReturnValueOnce(pending.promise);
241 act(() => root.render(<Screen />));
242​
243 act(() => button(label).click());
244 expect(button(label).disabled).toBe(true);
245 await act(async () => pending.resolve(AsyncResult.success(undefined)));
246​
247 expectFailures();
248 expect(mocks.updateSettings.mock.calls.map(([input]) => input.environmentId)).toEqual([
249 "healthy",
250 "alpha",
251 "beta",
252 ]);
253 expect(button(label).disabled).toBe(false);
254 expect(button(label).getAttribute("aria-checked")).toBe("false");
255​
256 mocks.alert.mockClear();
257 mocks.updateSettings.mockResolvedValue(AsyncResult.success(undefined));
258 await act(async () => button(label).click());
259 expect(mocks.updateSettings).toHaveBeenCalledTimes(6);
260 expect(mocks.alert).not.toHaveBeenCalled();
261 expect(button(label).getAttribute("aria-checked")).toBe("false");
262​
263 mocks.targets = mocks.targets.map((target) => ({
264 ...target,
265 serverConfig: {
266 ...target.serverConfig,
267 settings: { ...target.serverConfig.settings, [key]: true },
268 },
269 }));
270 act(() => root.render(<Screen />));
271 expect(button(label).getAttribute("aria-checked")).toBe("true");
272 });
273​
274 it("reports failed project resets and keeps overrides visible until a successful retry is received", async () => {
275 failTwoEnvironments();
276 mocks.projectSelected = true;
277 mocks.targets = mocks.targets.map((target) => ({
278 ...target,
279 serverConfig: {
280 ...target.serverConfig,
281 settings: {
282 ...target.serverConfig.settings,
283 projectSettingsOverrides: { project: { [key]: true } },
284 },
285 },
286 }));
287 act(() => root.render(<Screen />));
288​
289 await act(async () => button("Use defaults").click());
290​
291 expectFailures();
292 expect(button(label).getAttribute("aria-checked")).toBe("true");
293 expect(button("Use defaults").disabled).toBe(false);
294​
295 mocks.alert.mockClear();
296 mocks.updateSettings.mockResolvedValue(AsyncResult.success(undefined));
297 await act(async () => button("Use defaults").click());
298 expect(mocks.updateSettings).toHaveBeenCalledTimes(6);
299 expect(mocks.alert).not.toHaveBeenCalled();
300 expect(button(label).getAttribute("aria-checked")).toBe("true");
301​
302 mocks.targets = mocks.targets.map((target) => ({
303 ...target,
304 serverConfig: {
305 ...target.serverConfig,
306 settings: { ...target.serverConfig.settings, projectSettingsOverrides: {} },
307 },
308 }));
309 act(() => root.render(<Screen />));
310 expect(button(label).getAttribute("aria-checked")).toBe("false");
311 expect(container.textContent).not.toContain("Use defaults");
312 });
313​
314 it("does not alert for an interrupted write and releases the controls for retry", async () => {
315 const pending = Promise.withResolvers<AsyncResult.Failure<void>>();
316 mocks.updateSettings.mockReturnValueOnce(pending.promise);
317 act(() => root.render(<Screen />));
318​
319 act(() => button(label).click());
320 expect(button(label).disabled).toBe(true);
321 await act(async () => pending.resolve(AsyncResult.failure(Cause.interrupt(1))));
322​
323 expect(mocks.alert).not.toHaveBeenCalled();
324 expect(button(label).disabled).toBe(false);
325 await act(async () => button(label).click());
326 expect(mocks.updateSettings).toHaveBeenCalledTimes(2);
327 expect(mocks.alert).not.toHaveBeenCalled();
328 });
329});