Skip to content
TypeScript

fix(connect): the remove dialog says whether a T3 Connect environment is still on the account (#21706)

Rodrigo Brechardebd1265ccf9e
diff --git a/apps/mobile/src/features/cloud/T3ConnectProfilePage.tsx b/apps/mobile/src/features/cloud/T3ConnectProfilePage.tsx
index 842d58c9aa3..03b6daaa4e7 100644
--- a/apps/mobile/src/features/cloud/T3ConnectProfilePage.tsx
+++ b/apps/mobile/src/features/cloud/T3ConnectProfilePage.tsx
@@ -14,6 +14,7 @@ import { SymbolView } from "../../components/ui/AppSymbol";
import * as Dialog from "../../components/ui/Dialog";
import { Menu } from "../../components/ui/Menu";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
+import { relayEnvironmentDiscovery } from "../../state/relay";
import { useAtomCommand } from "../../state/use-atom-command";
import {
deregisterManagedRelayEnvironmentCommand,
@@ -46,6 +47,9 @@ export function T3ConnectProfilePage() {
const deregisterEnvironment = useAtomCommand(deregisterManagedRelayEnvironmentCommand, {
reportFailure: false,
});
+ const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refreshAfterMutation, {
+ reportFailure: false,
+ });
const [deregisteringEnvironmentId, setDeregisteringEnvironmentId] =
useState<EnvironmentId | null>(null);
const mutationPendingRef = useRef(false);
@@ -75,6 +79,7 @@ export function T3ConnectProfilePage() {
return { accountId, linkedAtById };
});
environmentsState.refresh();
+ void refreshRelayEnvironments();
return;
}
if (isAtomCommandInterrupted(result)) return;
diff --git a/apps/mobile/src/state/use-remote-environment-registry.ts b/apps/mobile/src/state/use-remote-environment-registry.ts
index 8a8003a6e27..c75456461bf 100644
--- a/apps/mobile/src/state/use-remote-environment-registry.ts
+++ b/apps/mobile/src/state/use-remote-environment-registry.ts
@@ -1,6 +1,7 @@
import * as Dialog from "../components/ui/Dialog";
import { useAtomValue } from "@effect/atom-react";
import { useNavigation } from "@react-navigation/native";
+import { Discovery } from "@t3tools/client-runtime/relay";
import type { EnvironmentId } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult, Atom } from "effect/reactivity";
@@ -17,8 +18,17 @@ import { environmentSession } from "./session";
import { environmentCatalog } from "../connection/catalog";
import { createRemoteEnvironmentProjectionAtoms } from "./remote-environment-projections";
import { serverEnvironment } from "./server";
+import { relayEnvironmentDiscovery } from "./relay";
import { connectPairingUrl as connectPairingUrlCommand } from "../connection/onboarding";
+const RELAY_REMOVAL_ACCOUNT_NOTE: Record<Discovery.RelayEnvironmentRegistration, string> = {
+ registered:
+ "It stays on your T3 Connect account and keeps its host space. Deregister it under T3 Account → T3 Connect to free it.",
+ unregistered: "It's no longer on your T3 Connect account.",
+ unknown:
+ "This doesn't change your T3 Connect account. To deregister it there, use T3 Account → T3 Connect.",
+};
+
const connectionPairingUrlAtom = Atom.make("").pipe(
Atom.keepAlive,
Atom.withLabel("mobile:connection-pairing-url"),
@@ -180,22 +190,20 @@ export function useRemoteConnections() {
},
} as const;
if (environment.isRelayManaged) {
+ const registration = Discovery.relayEnvironmentRegistration(
+ appAtomRegistry.get(relayEnvironmentDiscovery.stateValueAtom),
+ environmentId,
+ );
+ const openAccount = {
+ text: "Open T3 Account",
+ onPress: () => navigation.navigate("SettingsAuth"),
+ };
Dialog.alert(
"Remove from this device?",
- `Forget ${environment.environmentLabel} and its cached threads on this device.\n\nIt stays on your T3 Connect account and keeps its host space. Deregister it under T3 Account → T3 Connect to free it.`,
- [
- { text: "Cancel", style: "cancel" },
- // SettingsAuth renders nothing in builds without cloud config.
- ...(hasCloudPublicConfig()
- ? [
- {
- text: "Open T3 Account",
- onPress: () => navigation.navigate("SettingsAuth"),
- },
- ]
- : []),
- remove,
- ],
+ `Forget ${environment.environmentLabel} and its cached threads on this device.\n\n${RELAY_REMOVAL_ACCOUNT_NOTE[registration]}`,
+ registration === "unregistered" || !hasCloudPublicConfig()
+ ? [{ text: "Cancel", style: "cancel" }, remove]
+ : [{ text: "Cancel", style: "cancel" }, openAccount, remove],
);
return;
}
diff --git a/apps/web/src/components/clerk/RemoveT3ConnectEnvironmentDialog.tsx b/apps/web/src/components/clerk/RemoveT3ConnectEnvironmentDialog.tsx
index efe6d5785d8..ff398e3a398 100644
--- a/apps/web/src/components/clerk/RemoveT3ConnectEnvironmentDialog.tsx
+++ b/apps/web/src/components/clerk/RemoveT3ConnectEnvironmentDialog.tsx
@@ -1,5 +1,8 @@
+import { Discovery } from "@t3tools/client-runtime/relay";
+import type { EnvironmentId } from "@t3tools/contracts";
import { useState } from "react";
+import { useRelayEnvironmentDiscovery } from "../../state/environments";
import {
AlertDialog,
AlertDialogClose,
@@ -14,17 +17,40 @@ import { useT3ConnectAccountPage } from "./T3ConnectAccountPages";
export function RemoveT3ConnectEnvironmentDialog({
environmentLabel,
+ environmentId,
onCancel,
onConfirm,
}: {
readonly environmentLabel: string | null;
+ readonly environmentId: EnvironmentId | null;
readonly onCancel: () => void;
readonly onConfirm: () => void;
}) {
const accountPage = useT3ConnectAccountPage();
- const [shownLabel, setShownLabel] = useState(environmentLabel);
- if (environmentLabel !== null && environmentLabel !== shownLabel) setShownLabel(environmentLabel);
+ const discovery = useRelayEnvironmentDiscovery();
+ const registration = environmentId
+ ? Discovery.relayEnvironmentRegistration(discovery, environmentId)
+ : "unknown";
+ const [shown, setShown] = useState({ label: environmentLabel, registration });
+ if (
+ environmentLabel !== null &&
+ (environmentLabel !== shown.label || registration !== shown.registration)
+ ) {
+ setShown({ label: environmentLabel, registration });
+ }
const openAccountPage = accountPage.open;
+ const accountPageLink = openAccountPage ? (
+ <InlineButton
+ onClick={() => {
+ onCancel();
+ openAccountPage();
+ }}
+ >
+ T3 Connect settings
+ </InlineButton>
+ ) : (
+ "T3 Connect settings"
+ );
return (
<>
@@ -36,25 +62,24 @@ export function RemoveT3ConnectEnvironmentDialog({
>
<AlertDialogPopup>
<AlertDialogHeader>
- <AlertDialogTitle>Remove {shownLabel} from this device?</AlertDialogTitle>
+ <AlertDialogTitle>Remove {shown.label} from this device?</AlertDialogTitle>
<AlertDialogDescription>
This forgets its pairing, credentials, and cached threads here.
</AlertDialogDescription>
<AlertDialogDescription>
- It stays on your T3 Connect account and keeps its host space. Deregister it in{" "}
- {openAccountPage ? (
- <InlineButton
- onClick={() => {
- onCancel();
- openAccountPage();
- }}
- >
- T3 Connect settings
- </InlineButton>
+ {shown.registration === "registered" ? (
+ <>
+ It stays on your T3 Connect account and keeps its host space. Deregister it in{" "}
+ {accountPageLink} to free it.
+ </>
+ ) : shown.registration === "unregistered" ? (
+ "It's no longer on your T3 Connect account."
) : (
- "T3 Connect settings"
- )}{" "}
- to free it.
+ <>
+ This doesn't change your T3 Connect account. To deregister it there, use{" "}
+ {accountPageLink}.
+ </>
+ )}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
diff --git a/apps/web/src/components/clerk/T3ConnectUserProfilePage.tsx b/apps/web/src/components/clerk/T3ConnectUserProfilePage.tsx
index be59127723c..e02186af9e6 100644
--- a/apps/web/src/components/clerk/T3ConnectUserProfilePage.tsx
+++ b/apps/web/src/components/clerk/T3ConnectUserProfilePage.tsx
@@ -13,6 +13,7 @@ import {
useManagedRelayEnvironments,
useManagedTunnelUsage,
} from "../../cloud/managedRelayState";
+import { relayEnvironmentDiscovery } from "../../state/relay";
import { useAtomCommand } from "../../state/use-atom-command";
import { T3CHAT_SUBSCRIPTION_URL, TunnelUsageMeter, tunnelUpgradeCopy } from "../cloud/TunnelUsage";
import { Button, InlineButton } from "../ui/button";
@@ -165,6 +166,9 @@ export function T3ConnectUserProfilePage() {
const deregisterEnvironment = useAtomCommand(deregisterManagedRelayEnvironmentCommand, {
reportFailure: false,
});
+ const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refreshAfterMutation, {
+ reportFailure: false,
+ });
const [deregisteringEnvironmentId, setDeregisteringEnvironmentId] =
useState<EnvironmentId | null>(null);
const [confirmingEnvironmentId, setConfirmingEnvironmentId] = useState<EnvironmentId | null>(
@@ -197,6 +201,7 @@ export function T3ConnectUserProfilePage() {
return { accountId, linkedAtById };
});
environmentsState.refresh();
+ void refreshRelayEnvironments();
toastManager.add({
type: "success",
title: "Server deregistered",
diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx
index 502dc8c6a6e..16bb4a4375d 100644
--- a/apps/web/src/components/settings/ConnectionsSettings.tsx
+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx
@@ -1518,6 +1518,7 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
{hasCloudPublicConfig() ? (
<RemoveT3ConnectEnvironmentDialog
environmentLabel={pendingT3ConnectRemoval?.label ?? null}
+ environmentId={pendingT3ConnectRemoval?.environmentId ?? null}
onCancel={() => setPendingT3ConnectRemoval(null)}
onConfirm={() => {
if (!pendingT3ConnectRemoval) return;
diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md
index eca8907e87e..a01febe9188 100644
--- a/docs/user/remote-access.md
+++ b/docs/user/remote-access.md
@@ -374,7 +374,8 @@ shows that it was removed from T3 Connect. To link it again, turn on
command-line host that released its tunnel when it last stopped may link itself
again on its next start; run `t3 connect unlink` on that host to keep it off.
Removing an environment from a device's connection settings only forgets it on
-that device; it stays registered to your account.
+that device and doesn't change your T3 Connect account. A device keeps a saved
+environment after it's deregistered until you remove it from that device.
When idle tunnel cleanup is enabled, T3 Connect removes a linked environment's
tunnel after it stays offline for several minutes. The environment stays linked
diff --git a/packages/client-runtime/src/relay/discovery.test.ts b/packages/client-runtime/src/relay/discovery.test.ts
index 2e15b5448c2..9332652df39 100644
--- a/packages/client-runtime/src/relay/discovery.test.ts
+++ b/packages/client-runtime/src/relay/discovery.test.ts
@@ -12,6 +12,7 @@ import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
+import { Atom, AtomRegistry } from "effect/reactivity";
import * as ManagedRelay from "./managedRelay.ts";
import * as ClientCapabilities from "../platform/capabilities.ts";
@@ -20,6 +21,7 @@ import { ConnectionBlockedError, type NetworkStatus } from "../connection/model.
import * as ConnectionWakeups from "../connection/wakeups.ts";
import * as RelayEnvironmentDiscovery from "./discovery.ts";
import { NETWORK_BLOCKING_HINT } from "../errors/network.ts";
+import { createRelayEnvironmentDiscoveryAtoms } from "../state/relayDiscovery.ts";
const environments = [
{
@@ -59,6 +61,8 @@ function status(
const makeHarness = Effect.fn("RelayDiscoveryTest.makeHarness")(function* () {
const networkStatus = yield* SubscriptionRef.make<NetworkStatus>("online");
const listCalls = yield* Ref.make(0);
+ const listedEnvironments =
+ yield* Ref.make<ReadonlyArray<RelayClientEnvironmentRecord>>(environments);
const listFailure = yield* Ref.make<ManagedRelay.ManagedRelayClientError | null>(null);
const secondListCall = yield* Deferred.make<void>();
const clerkToken = yield* Ref.make<string | null>("clerk-token");
@@ -100,7 +104,7 @@ const makeHarness = Effect.fn("RelayDiscoveryTest.makeHarness")(function* () {
if (failure) {
return yield* failure;
}
- return environments;
+ return yield* Ref.get(listedEnvironments);
}),
getEnvironmentStatus: ({ environmentId }) =>
Ref.get(statusRequests).pipe(
@@ -165,6 +169,7 @@ const makeHarness = Effect.fn("RelayDiscoveryTest.makeHarness")(function* () {
return {
layer,
listCalls,
+ listedEnvironments,
listFailure,
clerkToken,
networkStatus,
@@ -179,6 +184,51 @@ const makeHarness = Effect.fn("RelayDiscoveryTest.makeHarness")(function* () {
});
describe("RelayEnvironmentDiscovery", () => {
+ it.effect("fetches a fresh list after removal while an older refresh is checking statuses", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const harness = yield* makeHarness();
+ yield* Effect.gen(function* () {
+ const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery;
+ const atoms = createRelayEnvironmentDiscoveryAtoms(
+ Atom.runtime(
+ Layer.succeed(RelayEnvironmentDiscovery.RelayEnvironmentDiscovery, discovery),
+ ),
+ );
+ const registry = AtomRegistry.make();
+ yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
+
+ const refresh = atoms.refresh.run(registry, undefined);
+ yield* SubscriptionRef.changes(discovery.state).pipe(
+ Stream.filter((state) => state.environments.size === environments.length),
+ Stream.runHead,
+ );
+ const coalescedRefresh = atoms.refresh.run(registry, undefined);
+ yield* Ref.set(harness.listedEnvironments, [environments[1]!]);
+ const mutationRefresh = atoms.refreshAfterMutation.run(registry, undefined);
+
+ const requests = yield* Ref.get(harness.statusRequests);
+ for (const environment of environments) {
+ yield* Deferred.succeed(
+ requests.get(environment.environmentId)!,
+ status(environment, "online"),
+ );
+ }
+ const results = yield* Effect.promise(() =>
+ Promise.all([refresh, coalescedRefresh, mutationRefresh]),
+ );
+ for (const result of results) {
+ expect(result._tag).toBe("Success");
+ }
+ expect(yield* Ref.get(harness.listCalls)).toBe(2);
+ const complete = yield* SubscriptionRef.get(discovery.state);
+ expect([...complete.environments.keys()]).toEqual([environments[1]!.environmentId]);
+ expect(complete.refreshing).toBe(false);
+ }).pipe(Effect.provide(harness.layer));
+ }),
+ ),
+ );
+
it.effect("publishes each environment status as soon as that lookup completes", () =>
Effect.gen(function* () {
const harness = yield* makeHarness();
@@ -228,6 +278,38 @@ describe("RelayEnvironmentDiscovery", () => {
}),
);
+ it.effect("reports an environment as unregistered only once the relay list has loaded", () =>
+ Effect.gen(function* () {
+ const harness = yield* makeHarness();
+ yield* Effect.gen(function* () {
+ const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery;
+ const listed = environments[0]!.environmentId;
+ const deregistered = "deregistered-environment";
+ const before = yield* SubscriptionRef.get(discovery.state);
+ expect(RelayEnvironmentDiscovery.relayEnvironmentRegistration(before, deregistered)).toBe(
+ "unknown",
+ );
+
+ const requests = yield* Ref.get(harness.statusRequests);
+ for (const environment of environments) {
+ yield* Deferred.succeed(
+ requests.get(environment.environmentId)!,
+ status(environment, "online"),
+ );
+ }
+ yield* discovery.refresh;
+
+ const after = yield* SubscriptionRef.get(discovery.state);
+ expect(RelayEnvironmentDiscovery.relayEnvironmentRegistration(after, listed)).toBe(
+ "registered",
+ );
+ expect(RelayEnvironmentDiscovery.relayEnvironmentRegistration(after, deregistered)).toBe(
+ "unregistered",
+ );
+ }).pipe(Effect.provide(harness.layer));
+ }),
+ );
+
it.effect(
"preserves discovered rows while offline and refreshes after connectivity returns",
() =>
@@ -350,6 +432,12 @@ describe("RelayEnvironmentDiscovery", () => {
const failed = yield* SubscriptionRef.get(discovery.state);
expect(failed.environments.size).toBe(0);
expect(Option.isSome(failed.error)).toBe(true);
+ expect(
+ RelayEnvironmentDiscovery.relayEnvironmentRegistration(
+ failed,
+ environments[0]!.environmentId,
+ ),
+ ).toBe("unknown");
}).pipe(Effect.provide(harness.layer));
}),
);
@@ -397,6 +485,12 @@ describe("RelayEnvironmentDiscovery", () => {
expect(state.environments.size).toBe(0);
expect(state.refreshing).toBe(false);
expect(Option.isNone(state.error)).toBe(true);
+ expect(
+ RelayEnvironmentDiscovery.relayEnvironmentRegistration(
+ state,
+ environments[0]!.environmentId,
+ ),
+ ).toBe("unknown");
}).pipe(Effect.provide(harness.layer));
}),
);
@@ -429,7 +523,14 @@ describe("RelayEnvironmentDiscovery", () => {
yield* Fiber.join(refreshFiber);
yield* Effect.yieldNow;
- expect((yield* SubscriptionRef.get(discovery.state)).environments.size).toBe(0);
+ const signedOut = yield* SubscriptionRef.get(discovery.state);
+ expect(signedOut.environments.size).toBe(0);
+ expect(
+ RelayEnvironmentDiscovery.relayEnvironmentRegistration(
+ signedOut,
+ environments[0]!.environmentId,
+ ),
+ ).toBe("unknown");
}).pipe(Effect.provide(harness.layer), Effect.scoped);
}),
);
diff --git a/packages/client-runtime/src/relay/discovery.ts b/packages/client-runtime/src/relay/discovery.ts
index 25ac154c3d7..ce5e708829d 100644
--- a/packages/client-runtime/src/relay/discovery.ts
+++ b/packages/client-runtime/src/relay/discovery.ts
@@ -34,6 +34,8 @@ export interface RelayDiscoveredEnvironment {
export interface RelayEnvironmentDiscoveryState {
readonly environments: ReadonlyMap<string, RelayDiscoveredEnvironment>;
+ // Only a loaded account list distinguishes a missing registration from an unknown one.
+ readonly listed: boolean;
readonly refreshing: boolean;
readonly offline: boolean;
readonly error: Option.Option<ConnectionAttemptError>;
@@ -49,11 +51,22 @@ export class RelayEnvironmentDiscovery extends Context.Service<
export const EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE: RelayEnvironmentDiscoveryState = {
environments: new Map(),
+ listed: false,
refreshing: false,
offline: false,
error: Option.none(),
};
+export type RelayEnvironmentRegistration = "registered" | "unregistered" | "unknown";
+
+export function relayEnvironmentRegistration(
+ state: RelayEnvironmentDiscoveryState,
+ environmentId: string,
+): RelayEnvironmentRegistration {
+ if (state.environments.has(environmentId)) return "registered";
+ return state.listed ? "unregistered" : "unknown";
+}
+
function validateStatus(
environment: RelayClientEnvironmentRecord,
status: RelayEnvironmentStatusResponse,
@@ -218,6 +231,7 @@ export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () {
yield* Ref.set(refreshGeneration, generation);
yield* SubscriptionRef.set(state, {
environments: new Map(),
+ listed: false,
refreshing: true,
offline: false,
error: Option.none(),
@@ -273,6 +287,7 @@ export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () {
yield* SubscriptionRef.update(state, (current) => ({
...current,
environments: next,
+ listed: true,
}));
yield* Effect.forEach(
diff --git a/packages/client-runtime/src/state/relayDiscovery.ts b/packages/client-runtime/src/state/relayDiscovery.ts
index b31dd67ca9d..47d92621b4c 100644
--- a/packages/client-runtime/src/state/relayDiscovery.ts
+++ b/packages/client-runtime/src/state/relayDiscovery.ts
@@ -32,9 +32,19 @@ export function createRelayEnvironmentDiscoveryAtoms<R, E>(
),
});
+ const refreshAfterMutation = createRuntimeCommand(runtime, {
+ label: "relay-environment-discovery:refresh-after-mutation",
+ concurrency: { mode: "serial", key: () => "refresh-after-mutation" },
+ execute: (_input: void) =>
+ RelayEnvironmentDiscovery.RelayEnvironmentDiscovery.pipe(
+ Effect.flatMap((discovery) => discovery.refresh),
+ ),
+ });
+
return {
stateAtom,
stateValueAtom,
refresh,
+ refreshAfterMutation,
};
}