@devries-cameron20 / t3code Mirror · read-only / commits / a8edf13f99
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 14:30 UTC

fix(mobile): the Add environment form shows only its own pairing errors (#25859)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 27, 2026 at 05:39 UTC a8edf13f9998192073ad6184c916d879c5d4120a
7 files changed +500 -100
apps/mobile/src/App.tsx
+8 -5
@@ -51,6 +51,7 @@ import { OverlayPortalHost } from "./components/ui/OverlayPortal";
51 import { shouldHandleAppLink, restoreDraftLinkState } from "./lib/appLinking";
52 import { hasCloudPublicConfig } from "./features/cloud/publicConfig";
53 import { takeScheduledTaskNewLink } from "./features/settings/scheduled-task-editor-state";
54 +import { startDevAutoConnect } from "./features/connection/devAutoConnect";
55 import {
56 resolvePendingNewTaskPromptLink,
57 takeNewTaskPromptLink,
@@ -103,11 +104,13 @@ const linkingConfig = {
104
105 function getAppStateFromPath(path: string, options: Parameters<typeof getStateFromPath>[1]) {
106 return takeScheduledTaskNewLink(
106 - takeNewTaskPromptLink(
107 - takeThreadPromptLink(
108 - restoreSettingsLinkState(
109 - restoreDraftLinkState(getStateFromPath(path, options), path),
110 - settingsLinkPage(),
107 + startDevAutoConnect(
108 + takeNewTaskPromptLink(
109 + takeThreadPromptLink(
110 + restoreSettingsLinkState(
111 + restoreDraftLinkState(getStateFromPath(path, options), path),
112 + settingsLinkPage(),
113 + ),
114 ),
115 ),
116 ),
apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx new
+104
@@ -0,0 +1,104 @@
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", () => ({
70 + autoConnectReport: () => ({ connecting: false, error: null }),
71 + devAutoConnectAttemptAtom: {},
72 +}));
73 +vi.mock("../../state/use-remote-environment-registry", () => ({
74 + setPendingConnectionError: (message: string | null) => {
75 + harness.pendingConnectionError = message;
76 + },
77 + useRemoteConnections: () => ({
78 + connectionPairingUrl: "",
79 + connectedEnvironments: [],
80 + pairingConnectionError: harness.pendingConnectionError,
81 + onChangeConnectionPairingUrl: vi.fn(),
82 + onConnectPress: harness.connectPress,
83 + onSetEnvironmentEnabled: vi.fn(),
84 + onRemoveEnvironmentPress: vi.fn(),
85 + }),
86 +}));
87 +
88 +import { ConnectionsNewRouteScreen } from "./ConnectionsNewRouteScreen";
89 +
90 +it("does not show another feature's error as a pairing failure", () => {
91 + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
92 + vi.stubGlobal("__DEV__", false);
93 + harness.pendingConnectionError = "Could not send the message.";
94 + const container = document.createElement("div");
95 + const root = createRoot(container);
96 + act(() => root.render(<ConnectionsNewRouteScreen route={{ params: undefined }} />));
97 +
98 + expect(container.textContent).not.toContain("Could not send the message.");
99 + expect(container.textContent).toContain("For machines on your local network or tailnet.");
100 +
101 + act(() => root.unmount());
102 + // Leaving the form must not wipe an error that belongs to another screen.
103 + expect(harness.pendingConnectionError).toBe("Could not send the message.");
104 +});
apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx
+55 -69
@@ -12,8 +12,8 @@ import {
12 type StaticScreenProps,
13 } from "@react-navigation/native";
14 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";
17 import { Linking, Pressable, StyleSheet, View } from "react-native";
18 import Svg, { Defs, RadialGradient, Rect, Stop } from "react-native-svg";
19 import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -24,13 +24,11 @@ import { SettingsScreen } from "../settings/components/SettingsScreen";
24 import { AppText as Text, AppTextInput, type AppTextInputProps } from "../../components/ui/AppText";
25 import { FrostedCutout } from "../../components/ui/FrostedCutout";
26 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";
28 import { SymbolView } from "../../components/ui/AppSymbol";
29 import { hasCloudPublicConfig } from "../cloud/publicConfig";
30 import { CloudEnvironmentRows } from "./CloudEnvironmentRows";
31 +import { autoConnectReport, devAutoConnectAttemptAtom } from "./devAutoConnect";
32 import { splitEnvironmentSections } from "./environmentSections";
33 import { leaveSettingsPage } from "../settings/settings-navigation";
34 import { workspaceHasColumns } from "../workspace/workspace-selection-store";
@@ -45,73 +43,70 @@ type ConnectionsNewRouteParams = {
43 export function ConnectionsNewRouteScreen({
44 route,
45 }: StaticScreenProps<ConnectionsNewRouteParams | undefined>) {
48 - const {
49 - connectionPairingUrl,
50 - onChangeConnectionPairingUrl,
51 - onConnectPress,
52 - pairingConnectionError,
53 - } = useRemoteConnections();
54 - const navigation = useNavigation();
55 - const routeName = useRoute().name;
46 const params = route.params ?? {};
47 // Dev-only prefill prevents production links from supplying an attacker-chosen host and token.
48 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;
70 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);
74 const [isSubmitting, setIsSubmitting] = useState(false);
75 + const [submitError, setSubmitError] = useState<string | null>(null);
76 + // The user's own edit or submit dismisses the dev auto-connect report.
77 + const [ownAttempt, setOwnAttempt] = useState(false);
78 + const autoConnect = autoConnectReport(
79 + useAtomValue(devAutoConnectAttemptAtom),
80 + routePairingUrl,
81 + ownAttempt,
82 + );
83 + const connecting = isSubmitting || autoConnect.connecting;
84 + const pairingConnectionError = submitError ?? autoConnect.error;
85 const [cameraPermission, requestCameraPermission] = useCameraPermissions();
86 const screenFocused = useIsFocused();
87 const [scannerLocked, setScannerLocked] = useState(false);
88 // A good scan parks the camera so it can't re-read the code over later edits.
89 const [scanComplete, setScanComplete] = useState(false);
72 - const attemptedAutoConnectRef = useRef<string | null>(null);
90
91 const headerIconColor = useUniwindTheme()["--color-icon"];
92
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]);
84 -
85 - useEffect(() => {
86 - if (routePairingUrl.length === 0) {
87 - return;
88 - }
93 + const connectDisabled = connecting || hostInput.trim().length === 0;
94
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]);
95 + const clearError = () => {
96 + setSubmitError(null);
97 + setOwnAttempt(true);
98 + };
99
100 const handleHostChange = (value: string) => {
101 setHostInput(value);
105 - setPendingConnectionError(null);
102 + clearError();
103 };
104
105 const handleCodeChange = (value: string) => {
106 setCodeInput(value);
110 - setPendingConnectionError(null);
107 + clearError();
108 };
109
113 - useEffect(() => () => setPendingConnectionError(null), []);
114 -
110 const handleScanPress = async () => {
111 const permission = await requestCameraPermission();
112 if (permission.granted) {
@@ -156,17 +151,21 @@ export function ConnectionsNewRouteScreen({
151 }
152 };
153
159 - const connectAndClose = async (pairingUrl: string) => {
154 + const handleSubmit = async () => {
155 + const pairingUrl = buildPairingUrl(hostInput, codeInput);
156 + setOwnAttempt(true);
157 + setSubmitError(null);
158 setIsSubmitting(true);
159 onChangeConnectionPairingUrl(pairingUrl);
162 - const result = await onConnectPress(pairingUrl, params.routeFor);
160 + const outcome = await onConnectPress(pairingUrl, routeFor);
161 setIsSubmitting(false);
162 + setSubmitError(outcome.error);
163 void Haptics.notificationAsync(
165 - AsyncResult.isSuccess(result)
164 + outcome.ok
165 ? Haptics.NotificationFeedbackType.Success
166 : Haptics.NotificationFeedbackType.Error,
167 );
169 - if (AsyncResult.isSuccess(result)) {
168 + if (outcome.ok) {
169 // Replacing with Home would nest it inside any sheet below; return to the opener.
170 if (!navigation.canGoBack()) {
171 navigation.dispatch(StackActions.replace("Home"));
@@ -177,27 +176,14 @@ export function ConnectionsNewRouteScreen({
176 }
177 };
178
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 -
179 return (
180 <SettingsScreen
181 formSheet={routeName === "ConnectionsNew"}
182 title="Add environment"
183 actions={[
184 {
199 - accessibilityLabel: isSubmitting ? "Connecting" : "Add environment",
200 - loading: isSubmitting,
185 + accessibilityLabel: connecting ? "Connecting" : "Add environment",
186 + loading: connecting,
187 icon: "checkmark",
188 tintColor: headerIconColor,
189 disabled: connectDisabled,
apps/mobile/src/features/connection/devAutoConnect.test.ts new
+193
@@ -0,0 +1,193 @@
1 +import type { NavigationState, PartialState } from "@react-navigation/native";
2 +import { expect, it, vi } from "vite-plus/test";
3 +
4 +const harness = vi.hoisted(() => ({
5 + pair: vi.fn(),
6 + goBack: vi.fn(),
7 + dispatch: vi.fn(),
8 + columns: false,
9 + // The root stack the form sits on when pairing succeeds.
10 + rootState: {
11 + key: "root",
12 + index: 2,
13 + routes: [
14 + { key: "home", name: "Home" },
15 + { key: "settings", name: "Settings" },
16 + { key: "new", name: "SettingsEnvironmentNew" },
17 + ],
18 + },
19 + // Navigation that is not ready yet holds callbacks here until the test flushes them.
20 + deferred: null as Array<() => void> | null,
21 +}));
22 +
23 +vi.mock("@react-navigation/native", () => ({ StackActions: { replace: vi.fn() } }));
24 +vi.mock("../../state/use-remote-environment-registry", () => ({
25 + pairEnvironment: harness.pair,
26 +}));
27 +vi.mock("../workspace/workspace-selection-store", () => ({
28 + workspaceHasColumns: () => harness.columns,
29 +}));
30 +vi.mock("../../lib/rootNavigation", () => ({
31 + rootNavigationRef: {
32 + getCurrentRoute: () => harness.rootState.routes[harness.rootState.index],
33 + getRootState: () => harness.rootState,
34 + getState: () => harness.rootState,
35 + getParent: () => undefined,
36 + canGoBack: () => true,
37 + goBack: harness.goBack,
38 + dispatch: harness.dispatch,
39 + },
40 + whenRootNavigationReady: (navigate: () => void) => {
41 + if (harness.deferred) harness.deferred.push(navigate);
42 + else navigate();
43 + },
44 +}));
45 +
46 +import { appAtomRegistry } from "../../state/atom-registry";
47 +import {
48 + autoConnectReport,
49 + devAutoConnectAttemptAtom,
50 + startDevAutoConnect,
51 +} from "./devAutoConnect";
52 +
53 +const PAIRING_URL = "http://192.168.1.10:3773/pair#token=abc";
54 +
55 +function settingsLink(params: object): PartialState<NavigationState> {
56 + return {
57 + routes: [
58 + { name: "Home" },
59 + { name: "Settings", state: { routes: [{ name: "SettingsEnvironmentNew", params }] } },
60 + ],
61 + };
62 +}
63 +
64 +it("pairs from a nested settings link once, reports failure, and closes the form on success", async () => {
65 + vi.stubGlobal("__DEV__", true);
66 + const failed = Promise.withResolvers<{ ok: boolean; error: string | null }>();
67 + harness.pair.mockReturnValueOnce(failed.promise);
68 +
69 + const state = settingsLink({ pairingUrl: ` ${PAIRING_URL} `, autoConnect: "1" });
70 + expect(startDevAutoConnect(state)).toBe(state);
71 + expect(harness.pair).toHaveBeenCalledExactlyOnceWith(PAIRING_URL, undefined);
72 + expect(appAtomRegistry.get(devAutoConnectAttemptAtom)).toEqual({
73 + pairingUrl: PAIRING_URL,
74 + status: "connecting",
75 + });
76 +
77 + failed.resolve({ ok: false, error: "Pairing code expired." });
78 + await failed.promise;
79 + await Promise.resolve();
80 + expect(appAtomRegistry.get(devAutoConnectAttemptAtom)).toEqual({
81 + pairingUrl: PAIRING_URL,
82 + status: "failed",
83 + error: "Pairing code expired.",
84 + });
85 + expect(harness.goBack).not.toHaveBeenCalled();
86 +
87 + const succeeded = Promise.withResolvers<{ ok: boolean; error: string | null }>();
88 + harness.pair.mockReturnValueOnce(succeeded.promise);
89 + startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL, autoConnect: "true" }));
90 + succeeded.resolve({ ok: true, error: null });
91 + await succeeded.promise;
92 + await Promise.resolve();
93 + expect(appAtomRegistry.get(devAutoConnectAttemptAtom)).toBeNull();
94 + expect(harness.goBack).toHaveBeenCalledOnce();
95 +});
96 +
97 +it("only prefills without the flag, and ignores the flag in production builds", () => {
98 + harness.pair.mockClear();
99 + vi.stubGlobal("__DEV__", true);
100 + startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL }));
101 + vi.stubGlobal("__DEV__", false);
102 + startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL, autoConnect: "1" }));
103 + expect(harness.pair).not.toHaveBeenCalled();
104 +});
105 +
106 +it("forgets a failed auto-connect once the form is opened again without the flag", async () => {
107 + vi.stubGlobal("__DEV__", true);
108 + const failed = Promise.withResolvers<{ ok: boolean; error: string | null }>();
109 + harness.pair.mockReturnValueOnce(failed.promise);
110 + startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL, autoConnect: "1" }));
111 + failed.resolve({ ok: false, error: "Pairing code expired." });
112 + await failed.promise;
113 + await Promise.resolve();
114 + expect(appAtomRegistry.get(devAutoConnectAttemptAtom)).toMatchObject({ status: "failed" });
115 +
116 + startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL }));
117 + expect(appAtomRegistry.get(devAutoConnectAttemptAtom)).toBeNull();
118 +});
119 +
120 +it("drops the result of a pairing that a later link superseded", async () => {
121 + vi.stubGlobal("__DEV__", true);
122 + const stale = Promise.withResolvers<{ ok: boolean; error: string | null }>();
123 + harness.pair.mockReturnValueOnce(stale.promise);
124 + startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL, autoConnect: "1" }));
125 + startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL }));
126 +
127 + stale.resolve({ ok: false, error: "Pairing code expired." });
128 + await stale.promise;
129 + await Promise.resolve();
130 + expect(appAtomRegistry.get(devAutoConnectAttemptAtom)).toBeNull();
131 +});
132 +
133 +it("keeps Connect busy while the auto-connect runs, even after the user edits the form", () => {
134 + const connecting = { pairingUrl: PAIRING_URL, status: "connecting" } as const;
135 + expect(autoConnectReport(connecting, PAIRING_URL, true)).toEqual({
136 + connecting: true,
137 + error: null,
138 + });
139 + const failed = { pairingUrl: PAIRING_URL, status: "failed", error: "Expired." } as const;
140 + expect(autoConnectReport(failed, PAIRING_URL, false)).toEqual({
141 + connecting: false,
142 + error: "Expired.",
143 + });
144 + expect(autoConnectReport(failed, PAIRING_URL, true).error).toBeNull();
145 + expect(autoConnectReport(connecting, "http://other/pair#token=x", false).connecting).toBe(false);
146 +});
147 +
148 +async function pairSuccessfully(link: PartialState<NavigationState>) {
149 + const succeeded = Promise.withResolvers<{ ok: boolean; error: string | null }>();
150 + harness.pair.mockReturnValueOnce(succeeded.promise);
151 + startDevAutoConnect(link);
152 + succeeded.resolve({ ok: true, error: null });
153 + await succeeded.promise;
154 + await Promise.resolve();
155 +}
156 +
157 +it("on columns, a successful settings link shows Environments instead of an empty detail", async () => {
158 + vi.stubGlobal("__DEV__", true);
159 + harness.goBack.mockClear();
160 + harness.dispatch.mockClear();
161 + harness.columns = true;
162 + await pairSuccessfully(settingsLink({ pairingUrl: PAIRING_URL, autoConnect: "1" }));
163 + harness.columns = false;
164 +
165 + expect(harness.goBack).not.toHaveBeenCalled();
166 + expect(harness.dispatch).toHaveBeenCalledExactlyOnceWith({
167 + type: "RESET",
168 + target: "root",
169 + payload: expect.objectContaining({
170 + index: 2,
171 + routes: [
172 + { key: "home", name: "Home" },
173 + { key: "settings", name: "Settings" },
174 + { name: "SettingsEnvironments", params: undefined },
175 + ],
176 + }),
177 + });
178 +});
179 +
180 +it("a success that waited for navigation leaves a newer link's form open", async () => {
181 + vi.stubGlobal("__DEV__", true);
182 + harness.goBack.mockClear();
183 + harness.dispatch.mockClear();
184 + harness.deferred = [];
185 + await pairSuccessfully(settingsLink({ pairingUrl: PAIRING_URL, autoConnect: "1" }));
186 + startDevAutoConnect(settingsLink({ pairingUrl: "http://192.168.1.11:3773/pair#token=def" }));
187 +
188 + const deferred = harness.deferred;
189 + harness.deferred = null;
190 + for (const navigate of deferred) navigate();
191 + expect(harness.goBack).not.toHaveBeenCalled();
192 + expect(harness.dispatch).not.toHaveBeenCalled();
193 +});
apps/mobile/src/features/connection/devAutoConnect.ts new
+99
@@ -0,0 +1,99 @@
1 +import type { NavigationState, PartialState } from "@react-navigation/native";
2 +import { StackActions } from "@react-navigation/native";
3 +import type { EnvironmentId } from "@t3tools/contracts";
4 +import { Atom } from "effect/reactivity";
5 +
6 +import { findLinkedRoute } from "../../lib/appLinking";
7 +import { rootNavigationRef, whenRootNavigationReady } from "../../lib/rootNavigation";
8 +import { appAtomRegistry } from "../../state/atom-registry";
9 +import { leaveSettingsPage } from "../settings/settings-navigation";
10 +import { workspaceHasColumns } from "../workspace/workspace-selection-store";
11 +import { pairEnvironment } from "../../state/use-remote-environment-registry";
12 +
13 +export type DevAutoConnectAttempt =
14 + | { readonly pairingUrl: string; readonly status: "connecting" }
15 + | { readonly pairingUrl: string; readonly status: "failed"; readonly error: string | null };
16 +
17 +/** The pairing the dev deep link started, so the form it opens can show its progress. */
18 +export const devAutoConnectAttemptAtom = Atom.make<DevAutoConnectAttempt | null>(null).pipe(
19 + Atom.keepAlive,
20 + Atom.withLabel("mobile:dev-auto-connect-attempt"),
21 +);
22 +
23 +/**
24 + * What the form opened by `routePairingUrl` shows of the dev auto-connect. Editing or submitting
25 + * (`dismissed`) hides a failure, but a pairing still running keeps Connect busy, so the user
26 + * cannot start a second pairing beside it.
27 + */
28 +export function autoConnectReport(
29 + attempt: DevAutoConnectAttempt | null,
30 + routePairingUrl: string,
31 + dismissed: boolean,
32 +): { readonly connecting: boolean; readonly error: string | null } {
33 + if (attempt === null || routePairingUrl.length === 0 || attempt.pairingUrl !== routePairingUrl) {
34 + return { connecting: false, error: null };
35 + }
36 + if (attempt.status === "connecting") return { connecting: true, error: null };
37 + return { connecting: false, error: dismissed ? null : attempt.error };
38 +}
39 +
40 +// The pairing form is mounted both as a root sheet and inside the settings sheet.
41 +const PAIRING_FORM_ROUTES = ["ConnectionsNew", "SettingsEnvironmentNew"];
42 +
43 +function isAutoConnectFlag(value: unknown): boolean {
44 + return value === "1" || value === "true";
45 +}
46 +
47 +async function connect(pairingUrl: string, expectedEnvironmentId: EnvironmentId | undefined) {
48 + const attempt: DevAutoConnectAttempt = { pairingUrl, status: "connecting" };
49 + appAtomRegistry.set(devAutoConnectAttemptAtom, attempt);
50 + const outcome = await pairEnvironment(pairingUrl, expectedEnvironmentId);
51 + // A later link replaced or cleared this attempt; its result belongs to no open form.
52 + if (appAtomRegistry.get(devAutoConnectAttemptAtom) !== attempt) return;
53 + if (!outcome.ok) {
54 + appAtomRegistry.set(devAutoConnectAttemptAtom, {
55 + pairingUrl,
56 + status: "failed",
57 + error: outcome.error,
58 + });
59 + return;
60 + }
61 + whenRootNavigationReady(() => {
62 + // A newer link (with or without the flag) owns the form now.
63 + if (appAtomRegistry.get(devAutoConnectAttemptAtom) !== attempt) return;
64 + appAtomRegistry.set(devAutoConnectAttemptAtom, null);
65 + const current = rootNavigationRef.getCurrentRoute()?.name;
66 + if (current === undefined || !PAIRING_FORM_ROUTES.includes(current)) return;
67 + // Same exit as the form's own Connect: return to the opener, and on columns show the
68 + // new environment on Environments instead of an empty detail.
69 + if (!rootNavigationRef.canGoBack()) rootNavigationRef.dispatch(StackActions.replace("Home"));
70 + else leaveSettingsPage(rootNavigationRef, workspaceHasColumns(), "SettingsEnvironments");
71 + });
72 +}
73 +
74 +/**
75 + * `connections/new?pairingUrl=…&autoConnect=1` (or `settings/environment-new?…`) pairs from the
76 + * link itself, so a remount of the form never pairs twice. Production builds ignore the flag so
77 + * a link can never pair with an attacker-chosen host.
78 + */
79 +export function startDevAutoConnect(
80 + state: PartialState<NavigationState> | undefined,
81 +): PartialState<NavigationState> | undefined {
82 + if (!__DEV__) return state;
83 + const route = findLinkedRoute(state, PAIRING_FORM_ROUTES);
84 + if (route === undefined) return state;
85 + const params = (route.params ?? {}) as {
86 + readonly autoConnect?: unknown;
87 + readonly pairingUrl?: unknown;
88 + readonly routeFor?: EnvironmentId;
89 + };
90 + const pairingUrl = typeof params.pairingUrl === "string" ? params.pairingUrl.trim() : "";
91 + if (isAutoConnectFlag(params.autoConnect) && pairingUrl.length > 0) {
92 + void connect(pairingUrl, params.routeFor);
93 + } else {
94 + // Only links put a pairing URL on the form, so a form opened by any other link starts
95 + // clean instead of showing an earlier auto-connect's failure for the same URL.
96 + appAtomRegistry.set(devAutoConnectAttemptAtom, null);
97 + }
98 + return state;
99 +}
apps/mobile/src/state/use-remote-environment-registry.ts
+40 -26
@@ -5,6 +5,7 @@ import type { EnvironmentId } from "@t3tools/contracts";
5 import * as Cause from "effect/Cause";
6 import { AsyncResult, Atom } from "effect/reactivity";
7 import { useCallback } from "react";
8 +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
9
10 import { hasCloudPublicConfig } from "../features/cloud/publicConfig";
11 import { useConnectionController } from "../features/connection/useConnectionController";
@@ -17,6 +18,7 @@ import { environmentSession } from "./session";
18 import { environmentCatalog } from "../connection/catalog";
19 import { createRemoteEnvironmentProjectionAtoms } from "./remote-environment-projections";
20 import { serverEnvironment } from "./server";
21 +import { connectPairingUrl as connectPairingUrlCommand } from "../connection/onboarding";
22
23 const connectionPairingUrlAtom = Atom.make("").pipe(
24 Atom.keepAlive,
@@ -32,6 +34,41 @@ export function setPendingConnectionError(message: string | null): void {
34 appAtomRegistry.set(pendingConnectionErrorAtom, message);
35 }
36
37 +export interface PairingOutcome {
38 + readonly ok: boolean;
39 + /** Shown beside the pairing form; null when the failure got its own dialog. */
40 + readonly error: string | null;
41 +}
42 +
43 +/** Pairs with the environment behind a pairing link and saves it. */
44 +export async function pairEnvironment(
45 + pairingUrl: string,
46 + expectedEnvironmentId?: EnvironmentId,
47 +): Promise<PairingOutcome> {
48 + const result = await runAtomCommand(
49 + appAtomRegistry,
50 + connectPairingUrlCommand,
51 + { pairingUrl, ...(expectedEnvironmentId === undefined ? {} : { expectedEnvironmentId }) },
52 + { reportFailure: false },
53 + );
54 + if (AsyncResult.isSuccess(result)) {
55 + appAtomRegistry.set(connectionPairingUrlAtom, "");
56 + return { ok: true, error: null };
57 + }
58 + const error = Cause.squash(result.cause);
59 + const message = error instanceof Error ? error.message : "Failed to pair with the environment.";
60 + if (
61 + error !== null &&
62 + typeof error === "object" &&
63 + "reason" in error &&
64 + error.reason === "unsupported"
65 + ) {
66 + Dialog.alert("Client not supported", message);
67 + return { ok: false, error: null };
68 + }
69 + return { ok: false, error: message };
70 +}
71 +
72 const remoteEnvironmentProjections = createRemoteEnvironmentProjectionAtoms({
73 presentationAtom: environmentPresentations.presentationAtom,
74 preparedConnectionAtom: environmentSession.preparedConnectionValueAtom,
@@ -111,7 +148,6 @@ export function useRemoteConnections() {
148 const controller = useConnectionController();
149 const navigation = useNavigation();
150 const connectionPairingUrl = useAtomValue(connectionPairingUrlAtom);
114 - const pendingConnectionError = useAtomValue(pendingConnectionErrorAtom);
151 const { connectedEnvironments, connectionError, connectionState } = useRemoteConnectionStatus();
152
153 const onChangeConnectionPairingUrl = useCallback((pairingUrl: string) => {
@@ -119,30 +155,9 @@ export function useRemoteConnections() {
155 }, []);
156
157 const onConnectPress = useCallback(
122 - async (pairingUrl?: string, expectedEnvironmentId?: EnvironmentId) => {
123 - const nextPairingUrl = pairingUrl ?? connectionPairingUrl;
124 - setPendingConnectionError(null);
125 - const result = await controller.connectPairingUrl(nextPairingUrl, expectedEnvironmentId);
126 - if (AsyncResult.isFailure(result)) {
127 - const error = Cause.squash(result.cause);
128 - const message =
129 - error instanceof Error ? error.message : "Failed to pair with the environment.";
130 - if (
131 - error !== null &&
132 - typeof error === "object" &&
133 - "reason" in error &&
134 - error.reason === "unsupported"
135 - ) {
136 - Dialog.alert("Client not supported", message);
137 - } else {
138 - setPendingConnectionError(message);
139 - }
140 - } else {
141 - appAtomRegistry.set(connectionPairingUrlAtom, "");
142 - }
143 - return result;
144 - },
145 - [connectionPairingUrl, controller],
158 + (pairingUrl?: string, expectedEnvironmentId?: EnvironmentId) =>
159 + pairEnvironment(pairingUrl ?? connectionPairingUrl, expectedEnvironmentId),
160 + [connectionPairingUrl],
161 );
162
163 const onReconnectEnvironment = useCallback(
@@ -210,7 +225,6 @@ export function useRemoteConnections() {
225 connectionPairingUrl,
226 connectionState,
227 connectionError,
213 - pairingConnectionError: pendingConnectionError,
228 connectedEnvironments,
229 connectedEnvironmentCount: connectedEnvironments.length,
230 onChangeConnectionPairingUrl,
apps/mobile/vite.config.ts
+1
@@ -27,6 +27,7 @@ const reactTests = [
27 "src/features/terminal/useTerminalExitNavigation.test.tsx",
28 "src/features/threads/use-thread-list-now.test.tsx",
29 "src/features/home/home-list-options.test.tsx",
30 + "src/features/connection/ConnectionsNewRouteScreen.test.tsx",
31 ];
32
33 const sourceRoot = `${normalizePath(NodeURL.fileURLToPath(new URL("./src", import.meta.url)))}/`;