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

SettingsServerControlsRouteScreen.test.tsx

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