The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 239 lines 8.07 KB
Raw
1 import { DEFAULT_SERVER_SETTINGS, type ServerSettingsPatch } from "@t3tools/contracts";
2 import { AsyncResult } from "effect/reactivity";
3 import type { ReactNode } from "react";
4 import { act } from "react";
5 import { createRoot, type Root } from "react-dom/client";
6 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
7
8 const { 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
20 vi.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 }));
39 vi.mock("@effect/atom-react", () => ({
40 useAtomValue: () => AsyncResult.success({}),
41 useAtomSet: () => () => {},
42 }));
43 vi.mock("../../state/preferences", () => ({
44 mobilePreferencesAtom: {},
45 saveMobilePreferences: {},
46 }));
47 vi.mock("./components/AutoSettleDaysField", () => ({ AutoSettleDaysField: () => null }));
48 vi.mock("./components/IssueTrackerSection", () => ({ IssueTrackerSection: () => null }));
49 vi.mock("./components/SourceControlProvidersSection", () => ({
50 SourceControlProvidersSection: () => null,
51 }));
52 vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ bottom: 0 }) }));
53 vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({}) }));
54 vi.mock("../../state/session", () => ({
55 readEnvironmentScope: () => true,
56 useEnvironmentsWithScope: () =>
57 new Set(
58 mocks.targets
59 .map((target) => target.environmentId)
60 .filter((environmentId) => !mocks.readOnly.has(environmentId)),
61 ),
62 }));
63 vi.mock("../../state/server", () => ({ serverEnvironment: { updateSettings: {} } }));
64 vi.mock("../../state/environments", () => ({ useEnvironments: () => ({ environments: [] }) }));
65 vi.mock("../../state/use-atom-command", () => ({
66 useAtomCommand: () => mocks.updateSettings,
67 }));
68 vi.mock("../threads/thread-settings-options", () => ({
69 RUNTIME_MODE_CHOICES: [],
70 withManagedRuntimeModeLimits: (choices: readonly unknown[]) => choices,
71 }));
72 vi.mock("../../components/ui/ScreenScrollView", () => ({ ScreenScrollView: Children }));
73 vi.mock("../../components/ui/AppText", () => ({ AppText: Children }));
74 vi.mock("../../components/ui/Button", () => ({
75 Button: ({
76 label,
77 disabled,
78 onPress,
79 }: {
80 label: string;
81 disabled?: boolean;
82 onPress: () => void;
83 }) => (
84 <button disabled={disabled} onClick={onPress}>
85 {label}
86 </button>
87 ),
88 }));
89 vi.mock("./components/SettingsScreen", () => ({ SettingsScreen: Children }));
90 vi.mock("./components/SettingsEnvironmentFilterHeader", () => ({
91 useSettingsEnvironmentMenu: () => ({
92 title: "Filter",
93 icon: "line.3.horizontal.decrease.circle",
94 items: [],
95 }),
96 }));
97 vi.mock("./components/DatabaseStorageNotice", () => ({ DatabaseStorageNotice: () => null }));
98 vi.mock("./components/SettingsSection", () => ({ SettingsSection: Children }));
99 vi.mock("../../components/ui/ListChoiceRow", () => ({ ListChoiceRow: () => null }));
100 vi.mock("./components/SettingsSwitchRow", () => ({
101 SettingsSwitchRow: ({
102 label,
103 value,
104 disabled,
105 onValueChange,
106 }: {
107 label: string;
108 value: boolean | null;
109 disabled?: boolean;
110 onValueChange: (value: boolean) => void;
111 }) => (
112 <button
113 role="switch"
114 aria-checked={value ?? "mixed"}
115 disabled={disabled}
116 onClick={() => onValueChange(!value)}
117 >
118 {label}
119 </button>
120 ),
121 }));
122 vi.mock("./components/SettingsRow", () => ({ SettingsRow: () => null }));
123 vi.mock("./components/BranchNamingSettings", () => ({
124 BranchNamingSettings: (props: { onChange: (patch: ServerSettingsPatch) => void }) => {
125 mocks.branchNaming.onChange = props.onChange;
126 return null;
127 },
128 }));
129 vi.mock("./settings-environment-filter", () => ({
130 useSettingsEnvironmentFilter: () => ({
131 selectedTargets: mocks.targets,
132 projectGroups: [
133 {
134 key: "project",
135 label: "Project",
136 members: mocks.targets.map((target) => ({
137 project: { environmentId: target.environmentId, id: "project" },
138 })),
139 },
140 ],
141 selectedProjectKey: mocks.projectSelected ? "project" : null,
142 }),
143 }));
144
145 import {
146 SettingsThreadsRouteScreen,
147 SettingsWorktreesRouteScreen,
148 } from "./SettingsServerControlsRouteScreen";
149
150 function environment(environmentId: string, label: string) {
151 return {
152 environmentId,
153 label,
154 connection: { phase: "connected" },
155 serverConfig: {
156 settings: {
157 ...DEFAULT_SERVER_SETTINGS,
158 defaultAutoPull: false,
159 sidebarAutoSettleOnMerge: false,
160 },
161 environment: {
162 capabilities: { projectSettingsOverrides: true, threadAutoSettlement: true },
163 },
164 },
165 };
166 }
167
168 let root: Root;
169 let container: HTMLDivElement;
170
171 beforeEach(() => {
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.readOnly = new Set();
178 mocks.alert.mockReset();
179 mocks.updateSettings.mockReset();
180 mocks.updateSettings.mockResolvedValue(AsyncResult.success(undefined));
181 });
182
183 afterEach(() => {
184 act(() => root.unmount());
185 });
186
187 describe("SettingsServerControlsRouteScreen", () => {
188 it("sends a draft saved during a pending write once that write settles", async () => {
189 const pending = Promise.withResolvers<AsyncResult.Success<void>>();
190 mocks.updateSettings.mockReturnValueOnce(pending.promise);
191 act(() => root.render(<SettingsWorktreesRouteScreen />));
192
193 act(() => mocks.branchNaming.onChange({ branchNamingMode: "custom" }));
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 it("holds auto-settle changes until a pending project override write settles", async () => {
209 mocks.projectSelected = true;
210 const pending = Promise.withResolvers<AsyncResult.Success<void>>();
211 mocks.updateSettings.mockReturnValueOnce(pending.promise);
212 act(() => root.render(<SettingsThreadsRouteScreen />));
213 const toggle = (label: string) =>
214 [...container.querySelectorAll<HTMLButtonElement>('[role="switch"]')].find(
215 (button) => button.textContent === label,
216 )!;
217
218 act(() => toggle("Agent browser access").click());
219 act(() => toggle("Auto-settle merged threads").click());
220
221 // Both rewrite the whole project override, so a second write planned now would drop the first.
222 expect(mocks.updateSettings).toHaveBeenCalledOnce();
223 await act(async () => pending.resolve(AsyncResult.success(undefined)));
224 });
225
226 it("disables auto-settle when a selected environment cannot save settings", () => {
227 const remote = environment("remote", "Remote");
228 // Auto-settle rows skip a server without auto-settlement, but the page still saves to it.
229 remote.serverConfig.environment.capabilities.threadAutoSettlement = false;
230 mocks.targets = [environment("local", "Local"), remote];
231 mocks.readOnly = new Set(["remote"]);
232 act(() => root.render(<SettingsThreadsRouteScreen />));
233
234 const autoSettle = [...container.querySelectorAll<HTMLButtonElement>('[role="switch"]')].find(
235 (button) => button.textContent === "Auto-settle merged threads",
236 )!;
237 expect(autoSettle.disabled).toBe(true);
238 });
239 });