Skip to content

Commit ccbfd69

Browse files
fix(mobile): the Add environment form shows only its own pairing errors
The pairing form read the app-wide pending connection error, so an error another feature reported (a failed composer send, a branch refresh) showed in red under the Address and Code fields, and closing the form wiped it. Five effects kept the form in sync: two reseeded the fields from the pairing URL atom and the route, one ended the spinner when the global error appeared, one cleared the global error on unmount, and one started dev auto-connect on mount. pairEnvironment now pairs and returns { ok, error }; the form keeps its own submit error in state. The route's pairing URL seeds the fields at mount and keys the form, so a new prefill link remounts it. Dev auto-connect (`autoConnect=1`) starts when the link is parsed, finds the form at any depth, and reports progress through devAutoConnectAttemptAtom, so a remount of the form never pairs twice. Effects: ConnectionsNewRouteScreen.tsx 5 -> 0. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 4cb29a5 commit ccbfd69

7 files changed

Lines changed: 351 additions & 98 deletions

File tree

‎apps/mobile/src/App.tsx‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ import { OverlayPortalHost } from "./components/ui/OverlayPortal";
5151
import { shouldHandleAppLink, restoreDraftLinkState } from "./lib/appLinking";
5252
import { hasCloudPublicConfig } from "./features/cloud/publicConfig";
5353
import { takeScheduledTaskNewLink } from "./features/settings/scheduled-task-editor-state";
54+
import { startDevAutoConnect } from "./features/connection/devAutoConnect";
5455
import {
5556
disposeOnFoundationReplace,
5657
type FoundationHotModule,
@@ -93,9 +94,11 @@ const linkingConfig = {
9394

9495
function getAppStateFromPath(path: string, options: Parameters<typeof getStateFromPath>[1]) {
9596
return takeScheduledTaskNewLink(
96-
restoreSettingsLinkState(
97-
restoreDraftLinkState(getStateFromPath(path, options), path),
98-
settingsLinkPage(),
97+
startDevAutoConnect(
98+
restoreSettingsLinkState(
99+
restoreDraftLinkState(getStateFromPath(path, options), path),
100+
settingsLinkPage(),
101+
),
99102
),
100103
);
101104
}
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
import type { ReactNode } from "react";
2+
import { act } from "react";
3+
import { createRoot } from "react-dom/client";
4+
import { expect, it, vi } from "vite-plus/test";
5+
6+
const { Children, harness } = vi.hoisted(() => ({
7+
Children: ({ children }: { children?: ReactNode }) => <>{children}</>,
8+
harness: {
9+
// The app-wide error slot other features (composer sends, branch refreshes) write to.
10+
pendingConnectionError: null as string | null,
11+
connectPress: vi.fn(),
12+
},
13+
}));
14+
15+
vi.mock("react-native", () => ({
16+
View: Children,
17+
Pressable: Children,
18+
Linking: { openSettings: vi.fn() },
19+
StyleSheet: { absoluteFill: {} },
20+
}));
21+
vi.mock("react-native-svg", () => ({
22+
default: Children,
23+
Defs: Children,
24+
RadialGradient: Children,
25+
Rect: () => null,
26+
Stop: () => null,
27+
}));
28+
vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ bottom: 0 }) }));
29+
vi.mock("@react-navigation/native", () => ({
30+
StackActions: { replace: vi.fn() },
31+
useIsFocused: () => true,
32+
useNavigation: () => ({ canGoBack: () => true, goBack: vi.fn(), dispatch: vi.fn() }),
33+
useRoute: () => ({ name: "ConnectionsNew" }),
34+
}));
35+
vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null }));
36+
vi.mock("@clerk/expo", () => ({ useAuth: () => ({ isLoaded: false, isSignedIn: false }) }));
37+
vi.mock("expo-camera", () => ({
38+
CameraView: () => null,
39+
useCameraPermissions: () => [null, vi.fn()],
40+
}));
41+
vi.mock("expo-haptics", () => ({
42+
notificationAsync: vi.fn(async () => {}),
43+
NotificationFeedbackType: { Success: "success", Error: "error" },
44+
}));
45+
vi.mock("../../components/ui/ListRow", () => ({ ListRow: () => null }));
46+
vi.mock("../../components/ui/Dialog", () => ({ alert: vi.fn() }));
47+
vi.mock("../../components/ui/ScreenScrollView", () => ({ ScreenScrollView: Children }));
48+
vi.mock("../../components/ui/AppText", () => ({
49+
AppText: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
50+
AppTextInput: () => null,
51+
}));
52+
vi.mock("../../components/ui/FrostedCutout", () => ({ FrostedCutout: () => null }));
53+
vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: () => null }));
54+
vi.mock("../../lib/useUniwindTheme", () => ({ useUniwindTheme: () => ({}) }));
55+
vi.mock("../settings/appearance/AppearancePreferencesProvider", () => ({
56+
useAppearancePreferences: () => ({ themeAppearance: "dark" }),
57+
}));
58+
vi.mock("../settings/components/SettingsScreen", () => ({ SettingsScreen: Children }));
59+
vi.mock("../settings/settings-navigation", () => ({
60+
leaveSettingsPage: vi.fn(),
61+
openSettings: vi.fn(),
62+
}));
63+
vi.mock("../workspace/workspace-selection-store", () => ({ workspaceHasColumns: () => false }));
64+
vi.mock("../cloud/publicConfig", () => ({ hasCloudPublicConfig: () => false }));
65+
vi.mock("./CloudEnvironmentRows", () => ({ CloudEnvironmentRows: () => null }));
66+
vi.mock("./environmentSections", () => ({
67+
splitEnvironmentSections: () => ({ connectedCloudEnvironments: [] }),
68+
}));
69+
vi.mock("./devAutoConnect", () => ({ devAutoConnectAttemptAtom: {} }));
70+
vi.mock("../../state/use-remote-environment-registry", () => ({
71+
setPendingConnectionError: (message: string | null) => {
72+
harness.pendingConnectionError = message;
73+
},
74+
useRemoteConnections: () => ({
75+
connectionPairingUrl: "",
76+
connectedEnvironments: [],
77+
pairingConnectionError: harness.pendingConnectionError,
78+
onChangeConnectionPairingUrl: vi.fn(),
79+
onConnectPress: harness.connectPress,
80+
onSetEnvironmentEnabled: vi.fn(),
81+
onRemoveEnvironmentPress: vi.fn(),
82+
}),
83+
}));
84+
85+
import { ConnectionsNewRouteScreen } from "./ConnectionsNewRouteScreen";
86+
87+
it("does not show another feature's error as a pairing failure", () => {
88+
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
89+
vi.stubGlobal("__DEV__", false);
90+
harness.pendingConnectionError = "Could not send the message.";
91+
const container = document.createElement("div");
92+
const root = createRoot(container);
93+
act(() => root.render(<ConnectionsNewRouteScreen route={{ params: undefined }} />));
94+
95+
expect(container.textContent).not.toContain("Could not send the message.");
96+
expect(container.textContent).toContain("For machines on your local network or tailnet.");
97+
98+
act(() => root.unmount());
99+
// Leaving the form must not wipe an error that belongs to another screen.
100+
expect(harness.pendingConnectionError).toBe("Could not send the message.");
101+
});

‎apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx‎

Lines changed: 58 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ import {
1212
type StaticScreenProps,
1313
} from "@react-navigation/native";
1414
import type { EnvironmentId } from "@t3tools/contracts";
15-
import { AsyncResult } from "effect/reactivity";
16-
import { useEffect, useRef, useState } from "react";
15+
import { useAtomValue } from "@effect/atom-react";
16+
import { useState } from "react";
1717
import { Linking, Pressable, StyleSheet, View } from "react-native";
1818
import Svg, { Defs, RadialGradient, Rect, Stop } from "react-native-svg";
1919
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -24,13 +24,11 @@ import { SettingsScreen } from "../settings/components/SettingsScreen";
2424
import { AppText as Text, AppTextInput, type AppTextInputProps } from "../../components/ui/AppText";
2525
import { FrostedCutout } from "../../components/ui/FrostedCutout";
2626
import { buildPairingUrl, extractPairingUrlFromQrPayload, parsePairingUrl } from "./pairing";
27-
import {
28-
setPendingConnectionError,
29-
useRemoteConnections,
30-
} from "../../state/use-remote-environment-registry";
27+
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
3128
import { SymbolView } from "../../components/ui/AppSymbol";
3229
import { hasCloudPublicConfig } from "../cloud/publicConfig";
3330
import { CloudEnvironmentRows } from "./CloudEnvironmentRows";
31+
import { devAutoConnectAttemptAtom } from "./devAutoConnect";
3432
import { splitEnvironmentSections } from "./environmentSections";
3533
import { leaveSettingsPage } from "../settings/settings-navigation";
3634
import { workspaceHasColumns } from "../workspace/workspace-selection-store";
@@ -45,73 +43,73 @@ type ConnectionsNewRouteParams = {
4543
export function ConnectionsNewRouteScreen({
4644
route,
4745
}: StaticScreenProps<ConnectionsNewRouteParams | undefined>) {
48-
const {
49-
connectionPairingUrl,
50-
onChangeConnectionPairingUrl,
51-
onConnectPress,
52-
pairingConnectionError,
53-
} = useRemoteConnections();
54-
const navigation = useNavigation();
55-
const routeName = useRoute().name;
5646
const params = route.params ?? {};
5747
// Dev-only prefill prevents production links from supplying an attacker-chosen host and token.
5848
const routePairingUrl = __DEV__ ? (params.pairingUrl?.trim() ?? "") : "";
59-
const shouldAutoConnect =
60-
__DEV__ &&
61-
routePairingUrl.length > 0 &&
62-
(params.autoConnect === "1" || params.autoConnect === "true");
49+
// A new prefill link replaces whatever the form held.
50+
return (
51+
<PairingForm
52+
key={routePairingUrl}
53+
routePairingUrl={routePairingUrl}
54+
routeFor={params.routeFor}
55+
/>
56+
);
57+
}
58+
59+
function PairingForm({
60+
routePairingUrl,
61+
routeFor,
62+
}: {
63+
readonly routePairingUrl: string;
64+
readonly routeFor: EnvironmentId | undefined;
65+
}) {
66+
const { connectionPairingUrl, onChangeConnectionPairingUrl, onConnectPress } =
67+
useRemoteConnections();
68+
const navigation = useNavigation();
69+
const routeName = useRoute().name;
6370
const insets = useSafeAreaInsets();
64-
const [hostInput, setHostInput] = useState("");
65-
const [codeInput, setCodeInput] = useState("");
71+
const [initialPairing] = useState(() => parsePairingUrl(routePairingUrl || connectionPairingUrl));
72+
const [hostInput, setHostInput] = useState(initialPairing.host);
73+
const [codeInput, setCodeInput] = useState(initialPairing.code);
6674
const [isSubmitting, setIsSubmitting] = useState(false);
75+
const [submitError, setSubmitError] = useState<string | null>(null);
76+
const autoConnectAttempt = useAtomValue(devAutoConnectAttemptAtom);
77+
const autoConnect =
78+
autoConnectAttempt !== null &&
79+
routePairingUrl.length > 0 &&
80+
autoConnectAttempt.pairingUrl === routePairingUrl
81+
? autoConnectAttempt
82+
: null;
83+
// The dev auto-connect report applies until the user starts their own attempt.
84+
const [ownAttempt, setOwnAttempt] = useState(false);
85+
const connecting = isSubmitting || (!ownAttempt && autoConnect?.status === "connecting");
86+
const pairingConnectionError =
87+
submitError ?? (!ownAttempt && autoConnect?.status === "failed" ? autoConnect.error : null);
6788
const [cameraPermission, requestCameraPermission] = useCameraPermissions();
6889
const screenFocused = useIsFocused();
6990
const [scannerLocked, setScannerLocked] = useState(false);
7091
// A good scan parks the camera so it can't re-read the code over later edits.
7192
const [scanComplete, setScanComplete] = useState(false);
72-
const attemptedAutoConnectRef = useRef<string | null>(null);
7393

7494
const headerIconColor = useUniwindTheme()["--color-icon"];
7595

76-
const connectDisabled = isSubmitting || hostInput.trim().length === 0;
77-
78-
useEffect(() => {
79-
const { host, code } = parsePairingUrl(connectionPairingUrl);
80-
// oxlint-disable-next-line react/set-state-in-effect -- A new pairing URL reseeds the editable host and code fields.
81-
setHostInput(host);
82-
setCodeInput(code);
83-
}, [connectionPairingUrl]);
96+
const connectDisabled = connecting || hostInput.trim().length === 0;
8497

85-
useEffect(() => {
86-
if (routePairingUrl.length === 0) {
87-
return;
88-
}
89-
90-
const { host, code } = parsePairingUrl(routePairingUrl);
91-
// oxlint-disable-next-line react/set-state-in-effect -- A pairing URL from the route reseeds the editable host and code fields.
92-
setHostInput(host);
93-
setCodeInput(code);
94-
}, [routePairingUrl]);
95-
96-
useEffect(() => {
97-
if (pairingConnectionError) {
98-
// oxlint-disable-next-line react/set-state-in-effect -- A pairing failure reported by the connection runtime ends the submit.
99-
setIsSubmitting(false);
100-
}
101-
}, [pairingConnectionError]);
98+
const clearError = () => {
99+
setSubmitError(null);
100+
setOwnAttempt(true);
101+
};
102102

103103
const handleHostChange = (value: string) => {
104104
setHostInput(value);
105-
setPendingConnectionError(null);
105+
clearError();
106106
};
107107

108108
const handleCodeChange = (value: string) => {
109109
setCodeInput(value);
110-
setPendingConnectionError(null);
110+
clearError();
111111
};
112112

113-
useEffect(() => () => setPendingConnectionError(null), []);
114-
115113
const handleScanPress = async () => {
116114
const permission = await requestCameraPermission();
117115
if (permission.granted) {
@@ -156,17 +154,21 @@ export function ConnectionsNewRouteScreen({
156154
}
157155
};
158156

159-
const connectAndClose = async (pairingUrl: string) => {
157+
const handleSubmit = async () => {
158+
const pairingUrl = buildPairingUrl(hostInput, codeInput);
159+
setOwnAttempt(true);
160+
setSubmitError(null);
160161
setIsSubmitting(true);
161162
onChangeConnectionPairingUrl(pairingUrl);
162-
const result = await onConnectPress(pairingUrl, params.routeFor);
163+
const outcome = await onConnectPress(pairingUrl, routeFor);
163164
setIsSubmitting(false);
165+
setSubmitError(outcome.error);
164166
void Haptics.notificationAsync(
165-
AsyncResult.isSuccess(result)
167+
outcome.ok
166168
? Haptics.NotificationFeedbackType.Success
167169
: Haptics.NotificationFeedbackType.Error,
168170
);
169-
if (AsyncResult.isSuccess(result)) {
171+
if (outcome.ok) {
170172
// Replacing with Home would nest it inside any sheet below; return to the opener.
171173
if (!navigation.canGoBack()) {
172174
navigation.dispatch(StackActions.replace("Home"));
@@ -177,27 +179,14 @@ export function ConnectionsNewRouteScreen({
177179
}
178180
};
179181

180-
const handleSubmit = async () => {
181-
await connectAndClose(buildPairingUrl(hostInput, codeInput));
182-
};
183-
184-
useEffect(() => {
185-
if (!shouldAutoConnect || attemptedAutoConnectRef.current === routePairingUrl) {
186-
return;
187-
}
188-
189-
attemptedAutoConnectRef.current = routePairingUrl;
190-
void connectAndClose(routePairingUrl);
191-
}, [connectAndClose, routePairingUrl, shouldAutoConnect]);
192-
193182
return (
194183
<SettingsScreen
195184
formSheet={routeName === "ConnectionsNew"}
196185
title="Add environment"
197186
actions={[
198187
{
199-
accessibilityLabel: isSubmitting ? "Connecting" : "Add environment",
200-
loading: isSubmitting,
188+
accessibilityLabel: connecting ? "Connecting" : "Add environment",
189+
loading: connecting,
201190
icon: "checkmark",
202191
tintColor: headerIconColor,
203192
disabled: connectDisabled,

0 commit comments

Comments
 (0)