Skip to content
TypeScript

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

Julius Marmingea8edf13f9998
diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx
index f63b210a11c..c1a43dcde4a 100644
--- a/apps/mobile/src/App.tsx
+++ b/apps/mobile/src/App.tsx
@@ -51,6 +51,7 @@ import { OverlayPortalHost } from "./components/ui/OverlayPortal";
import { shouldHandleAppLink, restoreDraftLinkState } from "./lib/appLinking";
import { hasCloudPublicConfig } from "./features/cloud/publicConfig";
import { takeScheduledTaskNewLink } from "./features/settings/scheduled-task-editor-state";
+import { startDevAutoConnect } from "./features/connection/devAutoConnect";
import {
resolvePendingNewTaskPromptLink,
takeNewTaskPromptLink,
@@ -103,11 +104,13 @@ const linkingConfig = {
function getAppStateFromPath(path: string, options: Parameters<typeof getStateFromPath>[1]) {
return takeScheduledTaskNewLink(
- takeNewTaskPromptLink(
- takeThreadPromptLink(
- restoreSettingsLinkState(
- restoreDraftLinkState(getStateFromPath(path, options), path),
- settingsLinkPage(),
+ startDevAutoConnect(
+ takeNewTaskPromptLink(
+ takeThreadPromptLink(
+ restoreSettingsLinkState(
+ restoreDraftLinkState(getStateFromPath(path, options), path),
+ settingsLinkPage(),
+ ),
),
),
),
diff --git a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx
new file mode 100644
index 00000000000..e96d73766c1
--- /dev/null
+++ b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.test.tsx
@@ -0,0 +1,104 @@
+import type { ReactNode } from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { expect, it, vi } from "vite-plus/test";
+
+const { Children, harness } = vi.hoisted(() => ({
+ Children: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ harness: {
+ // The app-wide error slot other features (composer sends, branch refreshes) write to.
+ pendingConnectionError: null as string | null,
+ connectPress: vi.fn(),
+ },
+}));
+
+vi.mock("react-native", () => ({
+ View: Children,
+ Pressable: Children,
+ Linking: { openSettings: vi.fn() },
+ StyleSheet: { absoluteFill: {} },
+}));
+vi.mock("react-native-svg", () => ({
+ default: Children,
+ Defs: Children,
+ RadialGradient: Children,
+ Rect: () => null,
+ Stop: () => null,
+}));
+vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ bottom: 0 }) }));
+vi.mock("@react-navigation/native", () => ({
+ StackActions: { replace: vi.fn() },
+ useIsFocused: () => true,
+ useNavigation: () => ({ canGoBack: () => true, goBack: vi.fn(), dispatch: vi.fn() }),
+ useRoute: () => ({ name: "ConnectionsNew" }),
+}));
+vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null }));
+vi.mock("@clerk/expo", () => ({ useAuth: () => ({ isLoaded: false, isSignedIn: false }) }));
+vi.mock("expo-camera", () => ({
+ CameraView: () => null,
+ useCameraPermissions: () => [null, vi.fn()],
+}));
+vi.mock("expo-haptics", () => ({
+ notificationAsync: vi.fn(async () => {}),
+ NotificationFeedbackType: { Success: "success", Error: "error" },
+}));
+vi.mock("../../components/ui/ListRow", () => ({ ListRow: () => null }));
+vi.mock("../../components/ui/Dialog", () => ({ alert: vi.fn() }));
+vi.mock("../../components/ui/ScreenScrollView", () => ({ ScreenScrollView: Children }));
+vi.mock("../../components/ui/AppText", () => ({
+ AppText: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
+ AppTextInput: () => null,
+}));
+vi.mock("../../components/ui/FrostedCutout", () => ({ FrostedCutout: () => null }));
+vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: () => null }));
+vi.mock("../../lib/useUniwindTheme", () => ({ useUniwindTheme: () => ({}) }));
+vi.mock("../settings/appearance/AppearancePreferencesProvider", () => ({
+ useAppearancePreferences: () => ({ themeAppearance: "dark" }),
+}));
+vi.mock("../settings/components/SettingsScreen", () => ({ SettingsScreen: Children }));
+vi.mock("../settings/settings-navigation", () => ({
+ leaveSettingsPage: vi.fn(),
+ openSettings: vi.fn(),
+}));
+vi.mock("../workspace/workspace-selection-store", () => ({ workspaceHasColumns: () => false }));
+vi.mock("../cloud/publicConfig", () => ({ hasCloudPublicConfig: () => false }));
+vi.mock("./CloudEnvironmentRows", () => ({ CloudEnvironmentRows: () => null }));
+vi.mock("./environmentSections", () => ({
+ splitEnvironmentSections: () => ({ connectedCloudEnvironments: [] }),
+}));
+vi.mock("./devAutoConnect", () => ({
+ autoConnectReport: () => ({ connecting: false, error: null }),
+ devAutoConnectAttemptAtom: {},
+}));
+vi.mock("../../state/use-remote-environment-registry", () => ({
+ setPendingConnectionError: (message: string | null) => {
+ harness.pendingConnectionError = message;
+ },
+ useRemoteConnections: () => ({
+ connectionPairingUrl: "",
+ connectedEnvironments: [],
+ pairingConnectionError: harness.pendingConnectionError,
+ onChangeConnectionPairingUrl: vi.fn(),
+ onConnectPress: harness.connectPress,
+ onSetEnvironmentEnabled: vi.fn(),
+ onRemoveEnvironmentPress: vi.fn(),
+ }),
+}));
+
+import { ConnectionsNewRouteScreen } from "./ConnectionsNewRouteScreen";
+
+it("does not show another feature's error as a pairing failure", () => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ vi.stubGlobal("__DEV__", false);
+ harness.pendingConnectionError = "Could not send the message.";
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ act(() => root.render(<ConnectionsNewRouteScreen route={{ params: undefined }} />));
+
+ expect(container.textContent).not.toContain("Could not send the message.");
+ expect(container.textContent).toContain("For machines on your local network or tailnet.");
+
+ act(() => root.unmount());
+ // Leaving the form must not wipe an error that belongs to another screen.
+ expect(harness.pendingConnectionError).toBe("Could not send the message.");
+});
diff --git a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx
index 2ea5efc780d..6f4e85d1d0d 100644
--- a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx
+++ b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx
@@ -12,8 +12,8 @@ import {
type StaticScreenProps,
} from "@react-navigation/native";
import type { EnvironmentId } from "@t3tools/contracts";
-import { AsyncResult } from "effect/reactivity";
-import { useEffect, useRef, useState } from "react";
+import { useAtomValue } from "@effect/atom-react";
+import { useState } from "react";
import { Linking, Pressable, StyleSheet, View } from "react-native";
import Svg, { Defs, RadialGradient, Rect, Stop } from "react-native-svg";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -24,13 +24,11 @@ import { SettingsScreen } from "../settings/components/SettingsScreen";
import { AppText as Text, AppTextInput, type AppTextInputProps } from "../../components/ui/AppText";
import { FrostedCutout } from "../../components/ui/FrostedCutout";
import { buildPairingUrl, extractPairingUrlFromQrPayload, parsePairingUrl } from "./pairing";
-import {
- setPendingConnectionError,
- useRemoteConnections,
-} from "../../state/use-remote-environment-registry";
+import { useRemoteConnections } from "../../state/use-remote-environment-registry";
import { SymbolView } from "../../components/ui/AppSymbol";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
import { CloudEnvironmentRows } from "./CloudEnvironmentRows";
+import { autoConnectReport, devAutoConnectAttemptAtom } from "./devAutoConnect";
import { splitEnvironmentSections } from "./environmentSections";
import { leaveSettingsPage } from "../settings/settings-navigation";
import { workspaceHasColumns } from "../workspace/workspace-selection-store";
@@ -45,73 +43,70 @@ type ConnectionsNewRouteParams = {
export function ConnectionsNewRouteScreen({
route,
}: StaticScreenProps<ConnectionsNewRouteParams | undefined>) {
- const {
- connectionPairingUrl,
- onChangeConnectionPairingUrl,
- onConnectPress,
- pairingConnectionError,
- } = useRemoteConnections();
- const navigation = useNavigation();
- const routeName = useRoute().name;
const params = route.params ?? {};
// Dev-only prefill prevents production links from supplying an attacker-chosen host and token.
const routePairingUrl = __DEV__ ? (params.pairingUrl?.trim() ?? "") : "";
- const shouldAutoConnect =
- __DEV__ &&
- routePairingUrl.length > 0 &&
- (params.autoConnect === "1" || params.autoConnect === "true");
+ // A new prefill link replaces whatever the form held.
+ return (
+ <PairingForm
+ key={routePairingUrl}
+ routePairingUrl={routePairingUrl}
+ routeFor={params.routeFor}
+ />
+ );
+}
+
+function PairingForm({
+ routePairingUrl,
+ routeFor,
+}: {
+ readonly routePairingUrl: string;
+ readonly routeFor: EnvironmentId | undefined;
+}) {
+ const { connectionPairingUrl, onChangeConnectionPairingUrl, onConnectPress } =
+ useRemoteConnections();
+ const navigation = useNavigation();
+ const routeName = useRoute().name;
const insets = useSafeAreaInsets();
- const [hostInput, setHostInput] = useState("");
- const [codeInput, setCodeInput] = useState("");
+ const [initialPairing] = useState(() => parsePairingUrl(routePairingUrl || connectionPairingUrl));
+ const [hostInput, setHostInput] = useState(initialPairing.host);
+ const [codeInput, setCodeInput] = useState(initialPairing.code);
const [isSubmitting, setIsSubmitting] = useState(false);
+ const [submitError, setSubmitError] = useState<string | null>(null);
+ // The user's own edit or submit dismisses the dev auto-connect report.
+ const [ownAttempt, setOwnAttempt] = useState(false);
+ const autoConnect = autoConnectReport(
+ useAtomValue(devAutoConnectAttemptAtom),
+ routePairingUrl,
+ ownAttempt,
+ );
+ const connecting = isSubmitting || autoConnect.connecting;
+ const pairingConnectionError = submitError ?? autoConnect.error;
const [cameraPermission, requestCameraPermission] = useCameraPermissions();
const screenFocused = useIsFocused();
const [scannerLocked, setScannerLocked] = useState(false);
// A good scan parks the camera so it can't re-read the code over later edits.
const [scanComplete, setScanComplete] = useState(false);
- const attemptedAutoConnectRef = useRef<string | null>(null);
const headerIconColor = useUniwindTheme()["--color-icon"];
- const connectDisabled = isSubmitting || hostInput.trim().length === 0;
-
- useEffect(() => {
- const { host, code } = parsePairingUrl(connectionPairingUrl);
- // oxlint-disable-next-line react/set-state-in-effect -- A new pairing URL reseeds the editable host and code fields.
- setHostInput(host);
- setCodeInput(code);
- }, [connectionPairingUrl]);
-
- useEffect(() => {
- if (routePairingUrl.length === 0) {
- return;
- }
+ const connectDisabled = connecting || hostInput.trim().length === 0;
- const { host, code } = parsePairingUrl(routePairingUrl);
- // oxlint-disable-next-line react/set-state-in-effect -- A pairing URL from the route reseeds the editable host and code fields.
- setHostInput(host);
- setCodeInput(code);
- }, [routePairingUrl]);
-
- useEffect(() => {
- if (pairingConnectionError) {
- // oxlint-disable-next-line react/set-state-in-effect -- A pairing failure reported by the connection runtime ends the submit.
- setIsSubmitting(false);
- }
- }, [pairingConnectionError]);
+ const clearError = () => {
+ setSubmitError(null);
+ setOwnAttempt(true);
+ };
const handleHostChange = (value: string) => {
setHostInput(value);
- setPendingConnectionError(null);
+ clearError();
};
const handleCodeChange = (value: string) => {
setCodeInput(value);
- setPendingConnectionError(null);
+ clearError();
};
- useEffect(() => () => setPendingConnectionError(null), []);
-
const handleScanPress = async () => {
const permission = await requestCameraPermission();
if (permission.granted) {
@@ -156,17 +151,21 @@ export function ConnectionsNewRouteScreen({
}
};
- const connectAndClose = async (pairingUrl: string) => {
+ const handleSubmit = async () => {
+ const pairingUrl = buildPairingUrl(hostInput, codeInput);
+ setOwnAttempt(true);
+ setSubmitError(null);
setIsSubmitting(true);
onChangeConnectionPairingUrl(pairingUrl);
- const result = await onConnectPress(pairingUrl, params.routeFor);
+ const outcome = await onConnectPress(pairingUrl, routeFor);
setIsSubmitting(false);
+ setSubmitError(outcome.error);
void Haptics.notificationAsync(
- AsyncResult.isSuccess(result)
+ outcome.ok
? Haptics.NotificationFeedbackType.Success
: Haptics.NotificationFeedbackType.Error,
);
- if (AsyncResult.isSuccess(result)) {
+ if (outcome.ok) {
// Replacing with Home would nest it inside any sheet below; return to the opener.
if (!navigation.canGoBack()) {
navigation.dispatch(StackActions.replace("Home"));
@@ -177,27 +176,14 @@ export function ConnectionsNewRouteScreen({
}
};
- const handleSubmit = async () => {
- await connectAndClose(buildPairingUrl(hostInput, codeInput));
- };
-
- useEffect(() => {
- if (!shouldAutoConnect || attemptedAutoConnectRef.current === routePairingUrl) {
- return;
- }
-
- attemptedAutoConnectRef.current = routePairingUrl;
- void connectAndClose(routePairingUrl);
- }, [connectAndClose, routePairingUrl, shouldAutoConnect]);
-
return (
<SettingsScreen
formSheet={routeName === "ConnectionsNew"}
title="Add environment"
actions={[
{
- accessibilityLabel: isSubmitting ? "Connecting" : "Add environment",
- loading: isSubmitting,
+ accessibilityLabel: connecting ? "Connecting" : "Add environment",
+ loading: connecting,
icon: "checkmark",
tintColor: headerIconColor,
disabled: connectDisabled,
diff --git a/apps/mobile/src/features/connection/devAutoConnect.test.ts b/apps/mobile/src/features/connection/devAutoConnect.test.ts
new file mode 100644
index 00000000000..af0e779ec93
--- /dev/null
+++ b/apps/mobile/src/features/connection/devAutoConnect.test.ts
@@ -0,0 +1,193 @@
+import type { NavigationState, PartialState } from "@react-navigation/native";
+import { expect, it, vi } from "vite-plus/test";
+
+const harness = vi.hoisted(() => ({
+ pair: vi.fn(),
+ goBack: vi.fn(),
+ dispatch: vi.fn(),
+ columns: false,
+ // The root stack the form sits on when pairing succeeds.
+ rootState: {
+ key: "root",
+ index: 2,
+ routes: [
+ { key: "home", name: "Home" },
+ { key: "settings", name: "Settings" },
+ { key: "new", name: "SettingsEnvironmentNew" },
+ ],
+ },
+ // Navigation that is not ready yet holds callbacks here until the test flushes them.
+ deferred: null as Array<() => void> | null,
+}));
+
+vi.mock("@react-navigation/native", () => ({ StackActions: { replace: vi.fn() } }));
+vi.mock("../../state/use-remote-environment-registry", () => ({
+ pairEnvironment: harness.pair,
+}));
+vi.mock("../workspace/workspace-selection-store", () => ({
+ workspaceHasColumns: () => harness.columns,
+}));
+vi.mock("../../lib/rootNavigation", () => ({
+ rootNavigationRef: {
+ getCurrentRoute: () => harness.rootState.routes[harness.rootState.index],
+ getRootState: () => harness.rootState,
+ getState: () => harness.rootState,
+ getParent: () => undefined,
+ canGoBack: () => true,
+ goBack: harness.goBack,
+ dispatch: harness.dispatch,
+ },
+ whenRootNavigationReady: (navigate: () => void) => {
+ if (harness.deferred) harness.deferred.push(navigate);
+ else navigate();
+ },
+}));
+
+import { appAtomRegistry } from "../../state/atom-registry";
+import {
+ autoConnectReport,
+ devAutoConnectAttemptAtom,
+ startDevAutoConnect,
+} from "./devAutoConnect";
+
+const PAIRING_URL = "http://192.168.1.10:3773/pair#token=abc";
+
+function settingsLink(params: object): PartialState<NavigationState> {
+ return {
+ routes: [
+ { name: "Home" },
+ { name: "Settings", state: { routes: [{ name: "SettingsEnvironmentNew", params }] } },
+ ],
+ };
+}
+
+it("pairs from a nested settings link once, reports failure, and closes the form on success", async () => {
+ vi.stubGlobal("__DEV__", true);
+ const failed = Promise.withResolvers<{ ok: boolean; error: string | null }>();
+ harness.pair.mockReturnValueOnce(failed.promise);
+
+ const state = settingsLink({ pairingUrl: ` ${PAIRING_URL} `, autoConnect: "1" });
+ expect(startDevAutoConnect(state)).toBe(state);
+ expect(harness.pair).toHaveBeenCalledExactlyOnceWith(PAIRING_URL, undefined);
+ expect(appAtomRegistry.get(devAutoConnectAttemptAtom)).toEqual({
+ pairingUrl: PAIRING_URL,
+ status: "connecting",
+ });
+
+ failed.resolve({ ok: false, error: "Pairing code expired." });
+ await failed.promise;
+ await Promise.resolve();
+ expect(appAtomRegistry.get(devAutoConnectAttemptAtom)).toEqual({
+ pairingUrl: PAIRING_URL,
+ status: "failed",
+ error: "Pairing code expired.",
+ });
+ expect(harness.goBack).not.toHaveBeenCalled();
+
+ const succeeded = Promise.withResolvers<{ ok: boolean; error: string | null }>();
+ harness.pair.mockReturnValueOnce(succeeded.promise);
+ startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL, autoConnect: "true" }));
+ succeeded.resolve({ ok: true, error: null });
+ await succeeded.promise;
+ await Promise.resolve();
+ expect(appAtomRegistry.get(devAutoConnectAttemptAtom)).toBeNull();
+ expect(harness.goBack).toHaveBeenCalledOnce();
+});
+
+it("only prefills without the flag, and ignores the flag in production builds", () => {
+ harness.pair.mockClear();
+ vi.stubGlobal("__DEV__", true);
+ startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL }));
+ vi.stubGlobal("__DEV__", false);
+ startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL, autoConnect: "1" }));
+ expect(harness.pair).not.toHaveBeenCalled();
+});
+
+it("forgets a failed auto-connect once the form is opened again without the flag", async () => {
+ vi.stubGlobal("__DEV__", true);
+ const failed = Promise.withResolvers<{ ok: boolean; error: string | null }>();
+ harness.pair.mockReturnValueOnce(failed.promise);
+ startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL, autoConnect: "1" }));
+ failed.resolve({ ok: false, error: "Pairing code expired." });
+ await failed.promise;
+ await Promise.resolve();
+ expect(appAtomRegistry.get(devAutoConnectAttemptAtom)).toMatchObject({ status: "failed" });
+
+ startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL }));
+ expect(appAtomRegistry.get(devAutoConnectAttemptAtom)).toBeNull();
+});
+
+it("drops the result of a pairing that a later link superseded", async () => {
+ vi.stubGlobal("__DEV__", true);
+ const stale = Promise.withResolvers<{ ok: boolean; error: string | null }>();
+ harness.pair.mockReturnValueOnce(stale.promise);
+ startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL, autoConnect: "1" }));
+ startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL }));
+
+ stale.resolve({ ok: false, error: "Pairing code expired." });
+ await stale.promise;
+ await Promise.resolve();
+ expect(appAtomRegistry.get(devAutoConnectAttemptAtom)).toBeNull();
+});
+
+it("keeps Connect busy while the auto-connect runs, even after the user edits the form", () => {
+ const connecting = { pairingUrl: PAIRING_URL, status: "connecting" } as const;
+ expect(autoConnectReport(connecting, PAIRING_URL, true)).toEqual({
+ connecting: true,
+ error: null,
+ });
+ const failed = { pairingUrl: PAIRING_URL, status: "failed", error: "Expired." } as const;
+ expect(autoConnectReport(failed, PAIRING_URL, false)).toEqual({
+ connecting: false,
+ error: "Expired.",
+ });
+ expect(autoConnectReport(failed, PAIRING_URL, true).error).toBeNull();
+ expect(autoConnectReport(connecting, "http://other/pair#token=x", false).connecting).toBe(false);
+});
+
+async function pairSuccessfully(link: PartialState<NavigationState>) {
+ const succeeded = Promise.withResolvers<{ ok: boolean; error: string | null }>();
+ harness.pair.mockReturnValueOnce(succeeded.promise);
+ startDevAutoConnect(link);
+ succeeded.resolve({ ok: true, error: null });
+ await succeeded.promise;
+ await Promise.resolve();
+}
+
+it("on columns, a successful settings link shows Environments instead of an empty detail", async () => {
+ vi.stubGlobal("__DEV__", true);
+ harness.goBack.mockClear();
+ harness.dispatch.mockClear();
+ harness.columns = true;
+ await pairSuccessfully(settingsLink({ pairingUrl: PAIRING_URL, autoConnect: "1" }));
+ harness.columns = false;
+
+ expect(harness.goBack).not.toHaveBeenCalled();
+ expect(harness.dispatch).toHaveBeenCalledExactlyOnceWith({
+ type: "RESET",
+ target: "root",
+ payload: expect.objectContaining({
+ index: 2,
+ routes: [
+ { key: "home", name: "Home" },
+ { key: "settings", name: "Settings" },
+ { name: "SettingsEnvironments", params: undefined },
+ ],
+ }),
+ });
+});
+
+it("a success that waited for navigation leaves a newer link's form open", async () => {
+ vi.stubGlobal("__DEV__", true);
+ harness.goBack.mockClear();
+ harness.dispatch.mockClear();
+ harness.deferred = [];
+ await pairSuccessfully(settingsLink({ pairingUrl: PAIRING_URL, autoConnect: "1" }));
+ startDevAutoConnect(settingsLink({ pairingUrl: "http://192.168.1.11:3773/pair#token=def" }));
+
+ const deferred = harness.deferred;
+ harness.deferred = null;
+ for (const navigate of deferred) navigate();
+ expect(harness.goBack).not.toHaveBeenCalled();
+ expect(harness.dispatch).not.toHaveBeenCalled();
+});
diff --git a/apps/mobile/src/features/connection/devAutoConnect.ts b/apps/mobile/src/features/connection/devAutoConnect.ts
new file mode 100644
index 00000000000..4c4d8de57b6
--- /dev/null
+++ b/apps/mobile/src/features/connection/devAutoConnect.ts
@@ -0,0 +1,99 @@
+import type { NavigationState, PartialState } from "@react-navigation/native";
+import { StackActions } from "@react-navigation/native";
+import type { EnvironmentId } from "@t3tools/contracts";
+import { Atom } from "effect/reactivity";
+
+import { findLinkedRoute } from "../../lib/appLinking";
+import { rootNavigationRef, whenRootNavigationReady } from "../../lib/rootNavigation";
+import { appAtomRegistry } from "../../state/atom-registry";
+import { leaveSettingsPage } from "../settings/settings-navigation";
+import { workspaceHasColumns } from "../workspace/workspace-selection-store";
+import { pairEnvironment } from "../../state/use-remote-environment-registry";
+
+export type DevAutoConnectAttempt =
+ | { readonly pairingUrl: string; readonly status: "connecting" }
+ | { readonly pairingUrl: string; readonly status: "failed"; readonly error: string | null };
+
+/** The pairing the dev deep link started, so the form it opens can show its progress. */
+export const devAutoConnectAttemptAtom = Atom.make<DevAutoConnectAttempt | null>(null).pipe(
+ Atom.keepAlive,
+ Atom.withLabel("mobile:dev-auto-connect-attempt"),
+);
+
+/**
+ * What the form opened by `routePairingUrl` shows of the dev auto-connect. Editing or submitting
+ * (`dismissed`) hides a failure, but a pairing still running keeps Connect busy, so the user
+ * cannot start a second pairing beside it.
+ */
+export function autoConnectReport(
+ attempt: DevAutoConnectAttempt | null,
+ routePairingUrl: string,
+ dismissed: boolean,
+): { readonly connecting: boolean; readonly error: string | null } {
+ if (attempt === null || routePairingUrl.length === 0 || attempt.pairingUrl !== routePairingUrl) {
+ return { connecting: false, error: null };
+ }
+ if (attempt.status === "connecting") return { connecting: true, error: null };
+ return { connecting: false, error: dismissed ? null : attempt.error };
+}
+
+// The pairing form is mounted both as a root sheet and inside the settings sheet.
+const PAIRING_FORM_ROUTES = ["ConnectionsNew", "SettingsEnvironmentNew"];
+
+function isAutoConnectFlag(value: unknown): boolean {
+ return value === "1" || value === "true";
+}
+
+async function connect(pairingUrl: string, expectedEnvironmentId: EnvironmentId | undefined) {
+ const attempt: DevAutoConnectAttempt = { pairingUrl, status: "connecting" };
+ appAtomRegistry.set(devAutoConnectAttemptAtom, attempt);
+ const outcome = await pairEnvironment(pairingUrl, expectedEnvironmentId);
+ // A later link replaced or cleared this attempt; its result belongs to no open form.
+ if (appAtomRegistry.get(devAutoConnectAttemptAtom) !== attempt) return;
+ if (!outcome.ok) {
+ appAtomRegistry.set(devAutoConnectAttemptAtom, {
+ pairingUrl,
+ status: "failed",
+ error: outcome.error,
+ });
+ return;
+ }
+ whenRootNavigationReady(() => {
+ // A newer link (with or without the flag) owns the form now.
+ if (appAtomRegistry.get(devAutoConnectAttemptAtom) !== attempt) return;
+ appAtomRegistry.set(devAutoConnectAttemptAtom, null);
+ const current = rootNavigationRef.getCurrentRoute()?.name;
+ if (current === undefined || !PAIRING_FORM_ROUTES.includes(current)) return;
+ // Same exit as the form's own Connect: return to the opener, and on columns show the
+ // new environment on Environments instead of an empty detail.
+ if (!rootNavigationRef.canGoBack()) rootNavigationRef.dispatch(StackActions.replace("Home"));
+ else leaveSettingsPage(rootNavigationRef, workspaceHasColumns(), "SettingsEnvironments");
+ });
+}
+
+/**
+ * `connections/new?pairingUrl=…&autoConnect=1` (or `settings/environment-new?…`) pairs from the
+ * link itself, so a remount of the form never pairs twice. Production builds ignore the flag so
+ * a link can never pair with an attacker-chosen host.
+ */
+export function startDevAutoConnect(
+ state: PartialState<NavigationState> | undefined,
+): PartialState<NavigationState> | undefined {
+ if (!__DEV__) return state;
+ const route = findLinkedRoute(state, PAIRING_FORM_ROUTES);
+ if (route === undefined) return state;
+ const params = (route.params ?? {}) as {
+ readonly autoConnect?: unknown;
+ readonly pairingUrl?: unknown;
+ readonly routeFor?: EnvironmentId;
+ };
+ const pairingUrl = typeof params.pairingUrl === "string" ? params.pairingUrl.trim() : "";
+ if (isAutoConnectFlag(params.autoConnect) && pairingUrl.length > 0) {
+ void connect(pairingUrl, params.routeFor);
+ } else {
+ // Only links put a pairing URL on the form, so a form opened by any other link starts
+ // clean instead of showing an earlier auto-connect's failure for the same URL.
+ appAtomRegistry.set(devAutoConnectAttemptAtom, null);
+ }
+ return state;
+}
diff --git a/apps/mobile/src/state/use-remote-environment-registry.ts b/apps/mobile/src/state/use-remote-environment-registry.ts
index 70a232bb9d0..4ed71500229 100644
--- a/apps/mobile/src/state/use-remote-environment-registry.ts
+++ b/apps/mobile/src/state/use-remote-environment-registry.ts
@@ -5,6 +5,7 @@ import type { EnvironmentId } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult, Atom } from "effect/reactivity";
import { useCallback } from "react";
+import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
import { hasCloudPublicConfig } from "../features/cloud/publicConfig";
import { useConnectionController } from "../features/connection/useConnectionController";
@@ -17,6 +18,7 @@ import { environmentSession } from "./session";
import { environmentCatalog } from "../connection/catalog";
import { createRemoteEnvironmentProjectionAtoms } from "./remote-environment-projections";
import { serverEnvironment } from "./server";
+import { connectPairingUrl as connectPairingUrlCommand } from "../connection/onboarding";
const connectionPairingUrlAtom = Atom.make("").pipe(
Atom.keepAlive,
@@ -32,6 +34,41 @@ export function setPendingConnectionError(message: string | null): void {
appAtomRegistry.set(pendingConnectionErrorAtom, message);
}
+export interface PairingOutcome {
+ readonly ok: boolean;
+ /** Shown beside the pairing form; null when the failure got its own dialog. */
+ readonly error: string | null;
+}
+
+/** Pairs with the environment behind a pairing link and saves it. */
+export async function pairEnvironment(
+ pairingUrl: string,
+ expectedEnvironmentId?: EnvironmentId,
+): Promise<PairingOutcome> {
+ const result = await runAtomCommand(
+ appAtomRegistry,
+ connectPairingUrlCommand,
+ { pairingUrl, ...(expectedEnvironmentId === undefined ? {} : { expectedEnvironmentId }) },
+ { reportFailure: false },
+ );
+ if (AsyncResult.isSuccess(result)) {
+ appAtomRegistry.set(connectionPairingUrlAtom, "");
+ return { ok: true, error: null };
+ }
+ const error = Cause.squash(result.cause);
+ const message = error instanceof Error ? error.message : "Failed to pair with the environment.";
+ if (
+ error !== null &&
+ typeof error === "object" &&
+ "reason" in error &&
+ error.reason === "unsupported"
+ ) {
+ Dialog.alert("Client not supported", message);
+ return { ok: false, error: null };
+ }
+ return { ok: false, error: message };
+}
+
const remoteEnvironmentProjections = createRemoteEnvironmentProjectionAtoms({
presentationAtom: environmentPresentations.presentationAtom,
preparedConnectionAtom: environmentSession.preparedConnectionValueAtom,
@@ -111,7 +148,6 @@ export function useRemoteConnections() {
const controller = useConnectionController();
const navigation = useNavigation();
const connectionPairingUrl = useAtomValue(connectionPairingUrlAtom);
- const pendingConnectionError = useAtomValue(pendingConnectionErrorAtom);
const { connectedEnvironments, connectionError, connectionState } = useRemoteConnectionStatus();
const onChangeConnectionPairingUrl = useCallback((pairingUrl: string) => {
@@ -119,30 +155,9 @@ export function useRemoteConnections() {
}, []);
const onConnectPress = useCallback(
- async (pairingUrl?: string, expectedEnvironmentId?: EnvironmentId) => {
- const nextPairingUrl = pairingUrl ?? connectionPairingUrl;
- setPendingConnectionError(null);
- const result = await controller.connectPairingUrl(nextPairingUrl, expectedEnvironmentId);
- if (AsyncResult.isFailure(result)) {
- const error = Cause.squash(result.cause);
- const message =
- error instanceof Error ? error.message : "Failed to pair with the environment.";
- if (
- error !== null &&
- typeof error === "object" &&
- "reason" in error &&
- error.reason === "unsupported"
- ) {
- Dialog.alert("Client not supported", message);
- } else {
- setPendingConnectionError(message);
- }
- } else {
- appAtomRegistry.set(connectionPairingUrlAtom, "");
- }
- return result;
- },
- [connectionPairingUrl, controller],
+ (pairingUrl?: string, expectedEnvironmentId?: EnvironmentId) =>
+ pairEnvironment(pairingUrl ?? connectionPairingUrl, expectedEnvironmentId),
+ [connectionPairingUrl],
);
const onReconnectEnvironment = useCallback(
@@ -210,7 +225,6 @@ export function useRemoteConnections() {
connectionPairingUrl,
connectionState,
connectionError,
- pairingConnectionError: pendingConnectionError,
connectedEnvironments,
connectedEnvironmentCount: connectedEnvironments.length,
onChangeConnectionPairingUrl,
diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts
index 3e37faf60d0..816b1439b4e 100644
--- a/apps/mobile/vite.config.ts
+++ b/apps/mobile/vite.config.ts
@@ -27,6 +27,7 @@ const reactTests = [
"src/features/terminal/useTerminalExitNavigation.test.tsx",
"src/features/threads/use-thread-list-now.test.tsx",
"src/features/home/home-list-options.test.tsx",
+ "src/features/connection/ConnectionsNewRouteScreen.test.tsx",
];
const sourceRoot = `${normalizePath(NodeURL.fileURLToPath(new URL("./src", import.meta.url)))}/`;