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