TypeScript
feat(mobile): add a T3 Connect page to the Clerk profile (#11765)
Julius Marminge0f21fcbb6dba
diff --git a/apps/mobile/global.css b/apps/mobile/global.cssindex 2f686e3a1fa..7a401fd7289 100644--- a/apps/mobile/global.css+++ b/apps/mobile/global.css@@ -233,6 +233,31 @@}}+/* ─── Clerk native profile ──────────────────────────────────────────── */+/* Fixed palette for custom pages inside Clerk's native user profile. Mirrors+ clerk-theme.json, which themes the SDK's own screens, so ours match them.+ Kept out of the runtime palette above on purpose: custom themes must not+ restyle Clerk's chrome. Keep in sync with clerk-theme.json. */+@layer theme {+ :root {+ @variant light {+ --color-clerk-page: #f2f2f7;+ --color-clerk-foreground: #262626;+ --color-clerk-foreground-muted: #737373;+ --color-clerk-border: rgba(229, 229, 234, 0.06);+ --color-clerk-danger: #dc2626;+ }++ @variant dark {+ --color-clerk-page: #0e0e0e;+ --color-clerk-foreground: #f5f5f5;+ --color-clerk-foreground-muted: #a3a3a3;+ --color-clerk-border: rgba(42, 42, 42, 0.06);+ --color-clerk-danger: #fca5a5;+ }+ }+}+/* ─── Typography ────────────────────────────────────────────────────── */@theme {/* Keep these native family names aligned with app.config.ts. */diff --git a/apps/mobile/src/features/cloud/T3ConnectProfilePage.tsx b/apps/mobile/src/features/cloud/T3ConnectProfilePage.tsxnew file mode 100644index 00000000000..702aa5f5e8e--- /dev/null+++ b/apps/mobile/src/features/cloud/T3ConnectProfilePage.tsx@@ -0,0 +1,273 @@+import { findErrorTraceId } from "@t3tools/client-runtime/errors";+import {+ isAtomCommandInterrupted,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";+import type { MenuAction } from "@react-native-menu/menu";+import type { EnvironmentId } from "@t3tools/contracts";+import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";+import { type ReactNode, useRef, useState } from "react";+import {+ ActivityIndicator,+ Alert,+ Pressable,+ RefreshControl,+ ScrollView,+ Text,+ View,+} from "react-native";++import { SymbolView } from "../../components/AppSymbol";+import { showConfirmDialog } from "../../components/ConfirmDialogHost";+import { ControlPillMenu } from "../../components/ControlPill";+import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";+import { useAtomCommand } from "../../state/use-atom-command";+import {+ deregisterManagedRelayEnvironmentCommand,+ useManagedRelayEnvironments,+} from "./managedRelayState";++const linkedAtFormatter = new Intl.DateTimeFormat(undefined, { dateStyle: "medium" });++function linkedAtLabel(value: string): string {+ const linkedAt = new Date(value);+ return Number.isNaN(linkedAt.getTime())+ ? "Link date unavailable"+ : `Linked ${linkedAtFormatter.format(linkedAt)}`;+}++function endpointLabel(environment: RelayClientEnvironmentRecord): string {+ return environment.endpoint.providerKind === "cloudflare_tunnel"+ ? "Managed tunnel"+ : "Activity publishing only";+}++function confirmDeregister(environment: RelayClientEnvironmentRecord, onConfirm: () => void) {+ const title = "Deregister server?";+ const message = `“${environment.label}” will be removed from this account. T3 Connect access will be revoked, any managed tunnel will be removed, and a host space will become available. Local connections on your devices are not changed.`;+ if (process.env.EXPO_OS === "ios") {+ Alert.alert(title, message, [+ { text: "Cancel", style: "cancel" },+ { text: "Deregister", style: "destructive", onPress: onConfirm },+ ]);+ return;+ }+ showConfirmDialog({ title, message, confirmText: "Deregister", destructive: true, onConfirm });+}++/**+ * The "T3 Connect" custom page inside Clerk's native user profile: every+ * environment registered to the signed-in account, with account-level+ * deregistration. Mirrors the web UserButton page; connections on this device+ * are managed in Settings instead.+ */+export function T3ConnectProfilePage() {+ const environmentsState = useManagedRelayEnvironments();+ const deregisterEnvironment = useAtomCommand(deregisterManagedRelayEnvironmentCommand, {+ reportFailure: false,+ });+ const [deregisteringEnvironmentId, setDeregisteringEnvironmentId] =+ useState<EnvironmentId | null>(null);+ const mutationPendingRef = useRef(false);+ // Deregistered rows stay in the cached list until the refresh lands, so hide+ // them by the linkedAt they had. A re-link produces a new linkedAt and shows again.+ const [removedEnvironments, setRemovedEnvironments] = useState<{+ readonly accountId: string | null;+ readonly linkedAtById: ReadonlyMap<EnvironmentId, string>;+ }>({ accountId: null, linkedAtById: new Map() });++ const handleDeregister = async (environment: RelayClientEnvironmentRecord) => {+ const accountId = environmentsState.accountId;+ if (!accountId || mutationPendingRef.current) return;++ mutationPendingRef.current = true;+ setDeregisteringEnvironmentId(environment.environmentId);+ const result = await deregisterEnvironment({+ accountId,+ environmentId: environment.environmentId,+ });+ mutationPendingRef.current = false;+ setDeregisteringEnvironmentId(null);++ if (result._tag === "Success") {+ setRemovedEnvironments((current) => {+ const linkedAtById = new Map(current.accountId === accountId ? current.linkedAtById : []);+ linkedAtById.set(environment.environmentId, environment.linkedAt);+ return { accountId, linkedAtById };+ });+ environmentsState.refresh();+ return;+ }+ if (isAtomCommandInterrupted(result)) return;++ const cause = squashAtomCommandFailure(result);+ const message = cause instanceof Error ? cause.message : "Could not deregister the server.";+ const traceId = findErrorTraceId(cause);+ console.error("[t3-connect] Could not deregister environment", {+ environmentId: environment.environmentId,+ message,+ traceId,+ cause,+ });+ Alert.alert(+ "Could not deregister server",+ traceId ? `${message}\n\nTrace ID: ${traceId}` : message,+ traceId+ ? [+ {+ text: "Copy trace ID",+ onPress: () => copyTextWithHaptic(traceId, { target: "connection-trace-id" }),+ },+ { text: "OK", style: "cancel" },+ ]+ : undefined,+ );+ };++ const removedEnvironmentLinkedAt =+ removedEnvironments.accountId === environmentsState.accountId+ ? removedEnvironments.linkedAtById+ : new Map<EnvironmentId, string>();+ const environments = (environmentsState.data ?? []).filter(+ (environment) =>+ removedEnvironmentLinkedAt.get(environment.environmentId) !== environment.linkedAt,+ );+ const isInitialLoad =+ !environmentsState.accountId || (environmentsState.data === null && !environmentsState.error);+ const errorTraceId = environmentsState.errorTraceId;++ return (+ <ScrollView+ className="flex-1 bg-clerk-page"+ contentContainerClassName="pb-8"+ contentInsetAdjustmentBehavior="automatic"+ refreshControl={+ <RefreshControl+ refreshing={environmentsState.isPending && environmentsState.data !== null}+ onRefresh={environmentsState.refresh}+ />+ }+ >+ <ClerkSectionHeader>Registered servers</ClerkSectionHeader>++ {environmentsState.error ? (+ <>+ <ClerkRow+ title="Could not load T3 Connect environments"+ subtitle={environmentsState.error}+ />+ {errorTraceId ? (+ <ClerkButtonRow+ label="Copy trace ID"+ onPress={() => {+ copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });+ }}+ />+ ) : null}+ </>+ ) : isInitialLoad ? (+ <View className="flex-row items-center gap-3 px-6 py-4">+ <ActivityIndicator colorClassName={"accent-clerk-foreground-muted"} size="small" />+ <Text className="text-base text-clerk-foreground-muted">Loading environments</Text>+ </View>+ ) : environments.length > 0 ? (+ environments.map((environment) => (+ <ClerkRow+ key={environment.environmentId}+ title={environment.label}+ subtitle={`${linkedAtLabel(environment.linkedAt)} · ${endpointLabel(environment)}`}+ accessory={+ deregisteringEnvironmentId === environment.environmentId ? (+ <ActivityIndicator colorClassName={"accent-clerk-foreground-muted"} size="small" />+ ) : (+ <ControlPillMenu+ actions={ENVIRONMENT_MENU_ACTIONS}+ isAnchoredToRight+ onPressAction={() =>+ confirmDeregister(environment, () => void handleDeregister(environment))+ }+ >+ <Pressable+ accessibilityLabel={`Actions for ${environment.label}`}+ accessibilityRole="button"+ disabled={deregisteringEnvironmentId !== null}+ className="size-[30px] items-center justify-center active:opacity-60 disabled:opacity-50"+ >+ <View className="rotate-90">+ <SymbolView+ name="ellipsis"+ size={18}+ tintColorClassName={"accent-clerk-foreground-muted"}+ type="monochrome"+ />+ </View>+ </Pressable>+ </ControlPillMenu>+ )+ }+ />+ ))+ ) : (+ <ClerkRow+ title="No servers registered"+ subtitle="Link a server from its local Settings to reach it through T3 Connect."+ />+ )}++ <Text className="px-6 pt-6 text-xs leading-normal text-clerk-foreground-muted">+ Connections on this device are managed in Settings.+ </Text>+ </ScrollView>+ );+}++const ENVIRONMENT_MENU_ACTIONS = [+ { id: "deregister", title: "Deregister", image: "trash", attributes: { destructive: true } },+] satisfies MenuAction[];++// Layout primitives that mirror clerk-ios ClerkKitUI's profile rows so a custom+// page reads as one of Clerk's own screens. System font on purpose: Clerk's+// native views do not use the app's DM Sans.++function ClerkSectionHeader(props: { readonly children: string }) {+ return (+ <Text className="min-h-4 border-b border-clerk-border px-6 pt-8 pb-4 text-xs font-medium tracking-[0.3px] text-clerk-foreground-muted uppercase">+ {props.children}+ </Text>+ );+}++function ClerkRow(props: {+ readonly title: string;+ readonly subtitle: string;+ readonly accessory?: ReactNode;+}) {+ return (+ <View+ collapsable={false}+ className="flex-row items-center gap-3 border-b border-clerk-border px-6 py-4"+ >+ <View className="min-w-0 flex-1 gap-0.5">+ <Text className="min-h-[22px] text-base text-clerk-foreground" numberOfLines={1}>+ {props.title}+ </Text>+ <Text className="min-h-5 text-sm text-clerk-foreground-muted" numberOfLines={2}>+ {props.subtitle}+ </Text>+ </View>+ {props.accessory}+ </View>+ );+}++function ClerkButtonRow(props: { readonly label: string; readonly onPress: () => void }) {+ return (+ <Pressable+ accessibilityRole="button"+ onPress={props.onPress}+ className="border-b border-clerk-border px-6 py-4 active:opacity-60"+ >+ <Text className="text-base font-semibold text-clerk-foreground">{props.label}</Text>+ </Pressable>+ );+}diff --git a/apps/mobile/src/features/cloud/managedRelayState.ts b/apps/mobile/src/features/cloud/managedRelayState.tsindex 8c41d74841e..375bda715e1 100644--- a/apps/mobile/src/features/cloud/managedRelayState.ts+++ b/apps/mobile/src/features/cloud/managedRelayState.ts@@ -1,9 +1,15 @@import { useAtomValue } from "@effect/atom-react";import {createManagedRelayQueryManager,+ deregisterManagedRelayEnvironment,managedRelaySessionAtom,readManagedRelaySnapshotState,} from "@t3tools/client-runtime/relay";+import {+ createAtomCommandScheduler,+ createRuntimeCommand,+} from "@t3tools/client-runtime/state/runtime";+import type { EnvironmentId } from "@t3tools/contracts";import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";import { AsyncResult, Atom } from "effect/unstable/reactivity";import { useCallback, useEffect } from "react";@@ -19,6 +25,22 @@ export const managedRelayQueryManager = createManagedRelayQueryManager(managedRecloudDebugLog(`query:${event.operation}:${event.stage}:${event.phase}`, { ...event }),});+const managedRelayMutationScheduler = createAtomCommandScheduler();++export const deregisterManagedRelayEnvironmentCommand = createRuntimeCommand(+ managedRelayAtomRuntime,+ {+ label: "mobile:managed-relay:deregister-environment",+ scheduler: managedRelayMutationScheduler,+ concurrency: {+ mode: "serial",+ key: (input: { readonly accountId: string; readonly environmentId: EnvironmentId }) =>+ input.accountId,+ },+ execute: (input, registry) => deregisterManagedRelayEnvironment(registry, input),+ },+);+const EMPTY_ENVIRONMENTS_ATOM = Atom.make(AsyncResult.success<ReadonlyArray<RelayClientEnvironmentRecord>>([]),).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:mobile:environments:null"));diff --git a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsxindex 96d612f8c68..e6e23fd78be 100644--- a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx+++ b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx@@ -1,10 +1,21 @@import { useAuth } from "@clerk/expo";-import { AuthView, UserProfileView } from "@clerk/expo/native";+import { AuthView, type UserProfileCustomPage, UserProfileView } from "@clerk/expo/native";import { StackActions, useNavigation } from "@react-navigation/native";import { useCallback, useEffect, useLayoutEffect, useRef } from "react";import { View } from "react-native";import { hasCloudPublicConfig } from "../cloud/publicConfig";+import { T3ConnectProfilePage } from "../cloud/T3ConnectProfilePage";++// Custom rows in Clerk's native profile. Mirrors the web UserButton pages.+const USER_PROFILE_CUSTOM_PAGES = [+ {+ path: "t3-connect",+ label: "T3 Connect",+ icon: "globe",+ content: <T3ConnectProfilePage />,+ },+] satisfies UserProfileCustomPage[];export function SettingsAuthRouteScreen() {const navigation = useNavigation();@@ -40,7 +51,11 @@ function ConfiguredSettingsAuthRouteScreen() {<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">{isLoaded ? (hasBeenSignedIn.current ? (- <UserProfileView isDismissible={false} onHostBack={handleHostBack} />+ <UserProfileView+ customPages={USER_PROFILE_CUSTOM_PAGES}+ isDismissible={false}+ onHostBack={handleHostBack}+ />) : (<AuthView isDismissible={false} onHostBack={handleHostBack} />)diff --git a/patches/@[email protected] b/patches/@[email protected]index 2d4a9287c11..e9bd5bfe07d 100644--- a/patches/@[email protected]+++ b/patches/@[email protected]@@ -1,8 +1,8 @@diff --git a/ios/ClerkAuthNativeView.swift b/ios/ClerkAuthNativeView.swift-index e76a8be1b1c8faa64ec6dfa83764764094133aff..17b36ad1319765e2b6db0551d32e07d7140e482f 100644+index 5f8d2ba66d5b232890af75c22b173c86d2ef546b..b170304cbf2fbaae8032db8dd6f89b6a59c6e3fe 100644--- a/ios/ClerkAuthNativeView.swift+++ b/ios/ClerkAuthNativeView.swift-@@ -108,7 +108,12 @@ public class ClerkAuthNativeView: ClerkNativeViewHost {+@@ -111,7 +111,12 @@ public class ClerkAuthNativeView: ClerkNativeViewHost {override func makeHostedController() -> UIViewController? {let hostBackAction: (() -> Void)? = currentHostBackButton@@ -16,8 +16,35 @@ index e76a8be1b1c8faa64ec6dfa83764764094133aff..17b36ad1319765e2b6db0551d32e07d7: nilreturn ClerkNativeBridge.shared.makeAuthViewController(+diff --git a/ios/ClerkNativeBridge.swift b/ios/ClerkNativeBridge.swift+index c90ad2ef1162cc2ac025c8b0b4aa135e8913dc21..ce8cb68764b1a3d3537672fc83e4e3077fceb97a 100644+--- a/ios/ClerkNativeBridge.swift++++ b/ios/ClerkNativeBridge.swift+@@ -1470,6 +1470,8 @@ private struct ClerkReactEmbeddedUserProfileCustomPage: View {+ }++ private struct ClerkReactUserProfileCustomPageContent: View {++ @Environment(\.clerkTheme) private var theme+++ let path: String+ let rows: [ClerkUserProfileCustomRowConfig]+ let state: ClerkUserProfileCustomPageState+@@ -1483,8 +1485,13 @@ private struct ClerkReactUserProfileCustomPageContent: View {+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)++ // Match Clerk's own profile pages so the navigation bar and page share++ // the theme's page background instead of a bare hosting container.++ .background(theme.colors.muted)+ .navigationTitle(userProfileCustomPageLabel(for: path, rows: rows))+ .navigationBarTitleDisplayMode(.inline)++ .preGlassSolidNavBar()++ .background(theme.colors.background)+ }+ }+diff --git a/ios/ClerkNativeViewHost.swift b/ios/ClerkNativeViewHost.swift-index 0d91f0e749f121595c17bc803663df6ac90e4163..8f8a89df97a54168b8b45d0e9c197ca3953b7028 100644+index 4e6540aceeaaab56ddf327bb3f16e120438f066f..cc16c94ca7a6eb91a97e76d5de02dc586f02a766 100644--- a/ios/ClerkNativeViewHost.swift+++ b/ios/ClerkNativeViewHost.swift@@ -5,6 +5,7 @@ public class ClerkNativeViewHost: ExpoView {@@ -60,10 +87,10 @@ index 0d91f0e749f121595c17bc803663df6ac90e4163..8f8a89df97a54168b8b45d0e9c197ca3guard configuredObserver == nil else { return }diff --git a/ios/ClerkUserProfileNativeView.swift b/ios/ClerkUserProfileNativeView.swift-index 12d6248b1dc4b4779b252c9954c2f89145907310..d838283b7adcf49fec2a63bff53251b9bee31bf8 100644+index f2ca604d41f50d05de8ac334879126cdc0414f84..46f406d5361b9a560a7c4ce855e344cbddd1d0b6 100644--- a/ios/ClerkUserProfileNativeView.swift+++ b/ios/ClerkUserProfileNativeView.swift-@@ -44,7 +44,12 @@ public class ClerkUserProfileNativeView: ClerkNativeViewHost {+@@ -47,7 +47,12 @@ public class ClerkUserProfileNativeView: ClerkUserProfileCustomPageHost {override func makeHostedController() -> UIViewController? {let hostBackAction: (() -> Void)? = currentHostBackButtondiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1f1b7b0c221..47f1ae85ea2 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -85,7 +85,7 @@ overrides:packageExtensionsChecksum: sha256-k/dT9NFDl5hihRPaoFKeY11hzyutMFs5psfZLFiKJic=patchedDependencies:- '@clerk/[email protected]': 72e426f44fc1cde16fc2cbba3d1e96cdca7c6d957faa73d0fe6b43948608a6c1+ '@clerk/[email protected]': a82bb41039ee88a290a87d4ab58be7be4c49fa338603b17ea646e1ec140a1cfb'@effect/[email protected]': a16b1e870d8c29e4a98b17cc4c638a4ff471753d8ca3487f78a22b759caf951b'@expo/[email protected]': 96f1a75347e6ea02dc4b7034ace815d8ee39e18b8166ebfb573d9e58328f0dc2'@ff-labs/[email protected]': c4e3cc2420ceb9dc650f9d189e9c24baf7e83f342998bacda5f459a4ce7927a8@@ -231,7 +231,7 @@ importers:dependencies:'@clerk/expo':specifier: 4.6.6- version: 4.6.6(patch_hash=72e426f44fc1cde16fc2cbba3d1e96cdca7c6d957faa73d0fe6b43948608a6c1)(dbc31631339ce74330e188d5d7a88158)+ version: 4.6.6(patch_hash=a82bb41039ee88a290a87d4ab58be7be4c49fa338603b17ea646e1ec140a1cfb)(dbc31631339ce74330e188d5d7a88158)'@effect/atom-react':specifier: 4.0.0-rc.112version: 4.0.0-rc.112([email protected](patch_hash=8bef799f35729cf3465eb428196f617b434a7c9f658d56acb2874d74b21b98b2))([email protected])([email protected])@@ -774,7 +774,7 @@ importers:version: link:../../packages/sharedalchemy:specifier: 2.0.0-beta.76- version: 2.0.0-beta.76(b3825b36417e56a486ccb5f22a7f3d7e)+ version: 2.0.0-beta.76(197b68e0d20fdf20cf352009eca17c9f)drizzle-orm:specifier: 1.0.0-rc.5-ab785fcversion: 1.0.0-rc.5-ab785fc(8ab70e2706da13c78d64d8a92fef1884)@@ -12437,7 +12437,7 @@ snapshots:electron-store: 8.2.0react-dom: 19.2.6([email protected])- '@clerk/[email protected](patch_hash=72e426f44fc1cde16fc2cbba3d1e96cdca7c6d957faa73d0fe6b43948608a6c1)(dbc31631339ce74330e188d5d7a88158)':+ '@clerk/[email protected](patch_hash=a82bb41039ee88a290a87d4ab58be7be4c49fa338603b17ea646e1ec140a1cfb)(dbc31631339ce74330e188d5d7a88158)':dependencies:@@ -16445,7 +16445,7 @@ snapshots:json-schema-traverse: 1.0.0require-from-string: 2.0.2- [email protected](b3825b36417e56a486ccb5f22a7f3d7e):+ [email protected](197b68e0d20fdf20cf352009eca17c9f):dependencies:'@alchemy.run/cloudflare-runtime': 2.0.0-beta.76(@distilled.cloud/[email protected]([email protected](patch_hash=8bef799f35729cf3465eb428196f617b434a7c9f658d56acb2874d74b21b98b2)))(@effect/[email protected]([email protected])([email protected](patch_hash=8bef799f35729cf3465eb428196f617b434a7c9f658d56acb2874d74b21b98b2))([email protected]))(@effect/[email protected]([email protected])([email protected](patch_hash=8bef799f35729cf3465eb428196f617b434a7c9f658d56acb2874d74b21b98b2))([email protected])([email protected]))(@types/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](patch_hash=8bef799f35729cf3465eb428196f617b434a7c9f658d56acb2874d74b21b98b2))([email protected])([email protected])'@alchemy.run/floci': 2.0.0-beta.76([email protected](patch_hash=8bef799f35729cf3465eb428196f617b434a7c9f658d56acb2874d74b21b98b2))