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