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