Add T3 Connect onboarding flow

- Present an onboarding sheet after in-session sign-in
- Let users publish local environments and connect cloud environments
- Persist onboarding completion per account across mobile sessions
This commit is contained in:
Julius Marminge committed 2026-07-07 02:03:05 -07:00
1 parent d8e0ba3ea0
commit 53ab016efd
16 files changed
+1899 -706

No files matched your search

+15
View File
@@ -17,6 +17,8 @@ import { AppText as Text } from "./components/AppText";
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
import { ConnectOnboardingRouteScreen } from "./features/cloud/ConnectOnboardingRouteScreen";
import { useConnectOnboardingNavigation } from "./features/cloud/connectOnboarding";
import { ThreadFilesTreeScreen, ThreadFileScreen } from "./features/files/ThreadFilesRouteScreen";
import { AdaptiveWorkspaceLayout } from "./features/layout/AdaptiveWorkspaceLayout";
import { HardwareKeyboardCommandProvider } from "./features/keyboard/HardwareKeyboardCommandProvider";
@@ -220,6 +222,7 @@ const NewTaskSheetStack = createNativeStackNavigator({
// influence the adaptive workspace layout: opening Settings over Home should
// not flip the sidebar in or change the active thread.
const WORKSPACE_OVERLAY_ROUTES = new Set([
"ConnectOnboarding",
"Connections",
"ConnectionsNew",
"GitBranches",
@@ -251,6 +254,8 @@ function RootStackLayout(props: {
}) {
useAgentNotificationNavigation();
useThreadOutboxDrain();
// Presents the T3 Connect onboarding sheet after an in-session sign-in.
useConnectOnboardingNavigation();
// Full pathname (sheets included) for keyboard-command scoping; the
// workspace layout only reacts to the underlying non-overlay route.
const path = getPathFromState(props.state, navigationPathConfig);
@@ -412,6 +417,16 @@ export const RootStack = createNativeStackNavigator({
sheetGrabberVisible: true,
},
}),
ConnectOnboarding: createNativeStackScreen({
screen: ConnectOnboardingRouteScreen,
linking: "connect-onboarding",
options: {
gestureEnabled: true,
presentation: "formSheet",
sheetAllowedDetents: [0.75, 0.95],
sheetGrabberVisible: true,
},
}),
Connections: createNativeStackScreen({
screen: ConnectionsRouteScreen,
linking: "connections",
@@ -18,6 +18,7 @@ import {
setAgentAwarenessRelayTokenProvider,
unregisterAgentAwarenessDeviceForCurrentUser,
} from "../agent-awareness/remoteRegistration";
import { requestConnectOnboardingIfNeeded } from "./connectOnboarding";
import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig";
function resetManagedRelayTokenCache() {
@@ -67,6 +68,16 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
const nextAccount = isSignedIn && userId ? userId : null;
observedAccountRef.current = nextAccount;
// A sign-in that completed during this session (a cold start observes
// undefined → account and must not re-prompt) requests the T3 Connect
// onboarding sheet once per account.
if (previousObservedAccount === null && nextAccount !== null) {
void (async () => {
const result = await settlePromise(() => requestConnectOnboardingIfNeeded(nextAccount));
reportAtomCommandResult(result, { label: "connect onboarding request" });
})();
}
const queueAccountCleanup = (
previous: {
readonly userId: string;
@@ -0,0 +1,510 @@
import { useAuth } from "@clerk/expo";
import { useNavigation } from "@react-navigation/native";
import * as Effect from "effect/Effect";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import {
isAtomCommandInterrupted,
reportAtomCommandResult,
settleAsyncResult,
settlePromise,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { AppText as Text } from "../../components/AppText";
import type { SavedRemoteConnection } from "../../lib/connection";
import { cn } from "../../lib/cn";
import { runtime } from "../../lib/runtime";
import { useThemeColor } from "../../lib/useThemeColor";
import {
useRemoteConnections,
useSavedRemoteConnections,
} from "../../state/use-remote-environment-registry";
import { CloudEnvironmentRows } from "../connection/CloudEnvironmentRows";
import { splitEnvironmentSections } from "../connection/environmentSections";
import { SettingsSection } from "../settings/components/SettingsSection";
import { SettingsSwitchRow } from "../settings/components/SettingsSwitchRow";
import { markConnectOnboardingCompleted } from "./connectOnboarding";
import {
getEnvironmentConnectPublishState,
linkEnvironmentToCloud,
setEnvironmentPublishAgentActivity,
} from "./linkEnvironment";
import { refreshManagedRelayEnvironments } from "./managedRelayState";
import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig";
type PublishTargetPhase = "checking" | "ready" | "published" | "unauthorized" | "error";
interface PublishTarget {
readonly connection: SavedRemoteConnection;
readonly phase: PublishTargetPhase;
readonly linked: boolean;
readonly managedTunnelActive: boolean;
readonly publishAgentActivity: boolean;
readonly error: string | null;
}
function pendingPublishTarget(connection: SavedRemoteConnection): PublishTarget {
return {
connection,
phase: "checking",
linked: false,
managedTunnelActive: false,
publishAgentActivity: false,
error: null,
};
}
/**
* Post-sign-in onboarding sheet for T3 Connect. Offers to publish this
* device's locally paired environments (managed tunnel + agent activity, both
* defaulting on) when the paired session is authorized, then lists the
* account's T3 Connect environments so every device can be connected right
* away. Dismissing the sheet counts as completion — it never nags twice.
*/
export function ConnectOnboardingRouteScreen() {
return hasCloudPublicConfig() ? <ConfiguredConnectOnboardingRouteScreen /> : null;
}
function ConfiguredConnectOnboardingRouteScreen() {
const navigation = useNavigation();
const insets = useSafeAreaInsets();
const { getToken, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
const { isLoadingSavedConnection, savedConnectionsById } = useSavedRemoteConnections();
const { connectedEnvironments, onReconnectEnvironment } = useRemoteConnections();
const { connectedCloudEnvironments } = splitEnvironmentSections({
connectedEnvironments,
cloudEnvironments: null,
});
// Dismissing the sheet (swipe, Skip, or Done) counts as completion.
const completionPersistedRef = useRef(false);
const persistCompletion = useCallback(() => {
if (completionPersistedRef.current || !userId) {
return;
}
completionPersistedRef.current = true;
void (async () => {
const result = await settlePromise(() => markConnectOnboardingCompleted(userId));
reportAtomCommandResult(result, { label: "connect onboarding completion" });
})();
}, [userId]);
useEffect(
() => navigation.addListener("beforeRemove", persistCompletion),
[navigation, persistCompletion],
);
const handleDone = useCallback(() => {
persistCompletion();
navigation.goBack();
}, [navigation, persistCompletion]);
const bearerConnections = useMemo(
() =>
Object.values(savedConnectionsById).filter((connection) => connection.bearerToken !== null),
[savedConnectionsById],
);
const [targets, setTargets] = useState<ReadonlyArray<PublishTarget> | null>(null);
const [publishEnvironment, setPublishEnvironment] = useState(true);
const [publishAgentActivity, setPublishAgentActivity] = useState(true);
const [isApplying, setIsApplying] = useState(false);
const loadPublishTargets = useCallback(
async (connections: ReadonlyArray<SavedRemoteConnection>) => {
if (connections.length === 0) {
setTargets([]);
return;
}
setTargets(connections.map(pendingPublishTarget));
const result = await settleAsyncResult(() =>
runtime.runPromiseExit(
Effect.forEach(
connections,
(connection) =>
getEnvironmentConnectPublishState({ connection }).pipe(
Effect.match({
onFailure: (error): PublishTarget => ({
...pendingPublishTarget(connection),
phase: "error",
error: error.message,
}),
onSuccess: (state): PublishTarget => ({
connection,
phase:
state.canPublish === false
? "unauthorized"
: state.linked && state.managedTunnelActive && state.publishAgentActivity
? "published"
: "ready",
linked: state.linked,
managedTunnelActive: state.managedTunnelActive,
publishAgentActivity: state.publishAgentActivity,
error: null,
}),
}),
),
{ concurrency: "unbounded" },
),
),
);
if (result._tag === "Failure") {
if (isAtomCommandInterrupted(result)) {
return;
}
const error = squashAtomCommandFailure(result);
const message =
error instanceof Error ? error.message : "Could not check the environment link state.";
setTargets(
connections.map((connection) => ({
...pendingPublishTarget(connection),
phase: "error" as const,
error: message,
})),
);
return;
}
setTargets(result.value);
},
[],
);
// Check authorization + link state once the locally saved connections are
// ready. Loaded once per mount: reconnect churn in the registry must not
// flip the section back to "checking" mid-interaction.
const loadedRef = useRef(false);
useEffect(() => {
if (isLoadingSavedConnection || loadedRef.current) {
return;
}
loadedRef.current = true;
void loadPublishTargets(bearerConnections);
}, [bearerConnections, isLoadingSavedConnection, loadPublishTargets]);
const publishableTargets = useMemo(
() => (targets ?? []).filter((target) => target.phase === "ready"),
[targets],
);
const targetConnections = useMemo(
() => (targets ?? []).map((target) => target.connection),
[targets],
);
const handlePublish = useCallback(async () => {
const applicable = publishableTargets;
if (applicable.length === 0 || (!publishEnvironment && !publishAgentActivity)) {
return;
}
setIsApplying(true);
const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
const clerkToken = tokenResult._tag === "Success" ? tokenResult.value : null;
if (clerkToken === null) {
setIsApplying(false);
const error = tokenResult._tag === "Failure" ? squashAtomCommandFailure(tokenResult) : null;
Alert.alert(
"Publishing unavailable",
error instanceof Error ? error.message : "Sign in to publish environments over T3 Connect.",
);
return;
}
const failures: Array<string> = [];
await Promise.all(
applicable.map(async (target) => {
// Onboarding only ever enables: it links when something is missing and
// never tears down an existing link or clears a preference.
const needsLink = publishEnvironment
? !target.linked || !target.managedTunnelActive
: !target.linked && publishAgentActivity;
const applyEffect = Effect.gen(function* () {
if (needsLink) {
yield* linkEnvironmentToCloud({
connection: target.connection,
clerkToken,
mode: publishEnvironment ? "managed" : "publish_only",
});
}
if (publishAgentActivity && !target.publishAgentActivity) {
yield* setEnvironmentPublishAgentActivity({
connection: target.connection,
publishAgentActivity: true,
});
}
});
const result = await settleAsyncResult(() => runtime.runPromiseExit(applyEffect));
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
failures.push(
`${target.connection.environmentLabel}: ${
error instanceof Error ? error.message : "Publishing failed."
}`,
);
}
}),
);
refreshManagedRelayEnvironments();
await loadPublishTargets(targetConnections);
setIsApplying(false);
if (failures.length > 0) {
Alert.alert("Couldn't publish every environment", failures.join("\n\n"));
}
}, [
getToken,
loadPublishTargets,
publishAgentActivity,
publishEnvironment,
publishableTargets,
targetConnections,
]);
return (
<View collapsable={false} className="flex-1 bg-sheet">
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentContainerStyle={{
gap: 24,
paddingBottom: Math.max(insets.bottom, 18) + 18,
paddingHorizontal: 20,
paddingTop: 24,
}}
>
<View className="gap-1.5">
<View className="flex-row items-start justify-between gap-3">
<Text className="flex-1 text-2xl font-t3-bold text-foreground">Set up T3 Connect</Text>
<Pressable
accessibilityRole="button"
hitSlop={8}
onPress={handleDone}
className="rounded-full bg-subtle px-3.5 py-2 active:opacity-70"
>
<Text className="text-xs font-t3-bold uppercase text-foreground-muted">Skip</Text>
</Pressable>
</View>
<Text className="text-sm leading-normal text-foreground-muted">
{
"Mesh your devices together — publish this device's environments and connect the rest, all in one place."
}
</Text>
</View>
{isSignedIn ? (
<>
<PublishSection
targets={targets}
publishEnvironment={publishEnvironment}
publishAgentActivity={publishAgentActivity}
isApplying={isApplying}
onPublishEnvironmentChange={setPublishEnvironment}
onPublishAgentActivityChange={setPublishAgentActivity}
onPublish={() => void handlePublish()}
onRetry={() => void loadPublishTargets(targetConnections)}
/>
<View className="gap-2">
<Text className="px-2 text-sm font-t3-medium text-foreground-muted">
Connect your environments
</Text>
<Text className="px-2 text-sm leading-normal text-foreground-muted">
Environments published from your other devices are ready to connect here.
</Text>
<CloudEnvironmentRows
connectedCloudEnvironments={connectedCloudEnvironments}
onReconnectEnvironment={onReconnectEnvironment}
/>
</View>
</>
) : (
<View collapsable={false} className="rounded-[24px] bg-card p-5">
<Text className="text-sm leading-normal text-foreground-muted">
Sign in to your T3 account to set up T3 Connect.
</Text>
</View>
)}
<Pressable
accessibilityRole="button"
onPress={handleDone}
className="min-h-[48px] items-center justify-center rounded-[18px] bg-card active:opacity-70"
>
<Text className="text-base font-t3-bold text-foreground">Done</Text>
</Pressable>
</ScrollView>
</View>
);
}
function PublishSection(props: {
readonly targets: ReadonlyArray<PublishTarget> | null;
readonly publishEnvironment: boolean;
readonly publishAgentActivity: boolean;
readonly isApplying: boolean;
readonly onPublishEnvironmentChange: (enabled: boolean) => void;
readonly onPublishAgentActivityChange: (enabled: boolean) => void;
readonly onPublish: () => void;
readonly onRetry: () => void;
}) {
const iconColor = useThemeColor("--color-icon");
const primaryForeground = useThemeColor("--color-primary-foreground");
const targets = props.targets;
const isChecking = targets === null || targets.some((target) => target.phase === "checking");
const publishableTargets = (targets ?? []).filter((target) => target.phase === "ready");
const publishedTargets = (targets ?? []).filter((target) => target.phase === "published");
const hasRetryableErrors = (targets ?? []).some((target) => target.phase === "error");
const canPublish =
publishableTargets.length > 0 &&
(props.publishEnvironment || props.publishAgentActivity) &&
!props.isApplying;
if (targets !== null && targets.length === 0) {
return (
<View className="gap-2">
<Text className="px-2 text-sm font-t3-medium text-foreground-muted">
Publish this device
</Text>
<View collapsable={false} className="rounded-[24px] bg-card p-5">
<Text className="text-sm leading-normal text-foreground-muted">
{
"No locally paired environments on this device yet. Pair an environment first and it can be published to your other devices from Settings."
}
</Text>
</View>
</View>
);
}
if (isChecking) {
return (
<View className="gap-2">
<Text className="px-2 text-sm font-t3-medium text-foreground-muted">
Publish this device
</Text>
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">
<ActivityIndicator color={iconColor} />
<Text className="text-center text-sm leading-normal text-foreground-muted">
Checking which environments can publish.
</Text>
</View>
</View>
);
}
return (
<View className="gap-3">
<SettingsSection title="Publish this device">
{publishableTargets.length > 0 ? (
<>
<SettingsSwitchRow
icon="antenna.radiowaves.left.and.right"
label="Publish environment"
disabled={props.isApplying}
value={props.publishEnvironment}
onValueChange={props.onPublishEnvironmentChange}
/>
<SettingsSwitchRow
icon="bolt.circle"
label="Publish agent activity"
disabled={props.isApplying}
value={props.publishAgentActivity}
onValueChange={props.onPublishAgentActivityChange}
/>
</>
) : publishedTargets.length > 0 ? (
<View className="p-4">
<Text className="text-sm leading-normal text-foreground-muted">
{"This device's environments already publish over T3 Connect."}
</Text>
</View>
) : (
<View className="p-4">
<Text className="text-sm leading-normal text-foreground-muted">
{
"This device's paired sessions aren't authorized to publish. Pair again with an administrative link to enable publishing."
}
</Text>
</View>
)}
</SettingsSection>
{publishableTargets.length > 0 ? (
<Text className="px-2 text-sm leading-normal text-foreground-muted">
Make the environments paired with this device available to your other devices, and send
agent activity for notifications and Live Activities.
</Text>
) : null}
{targets.map((target) => (
<PublishTargetStatusRow key={target.connection.environmentId} target={target} />
))}
{publishableTargets.length > 0 ? (
<Pressable
accessibilityRole="button"
disabled={!canPublish}
onPress={props.onPublish}
className={cn(
"min-h-[48px] flex-row items-center justify-center gap-2 rounded-[18px] bg-primary px-5 active:opacity-70",
!canPublish && "opacity-50",
)}
>
{props.isApplying ? <ActivityIndicator color={primaryForeground} size="small" /> : null}
<Text className="text-base font-t3-bold text-primary-foreground">
{props.isApplying
? "Publishing..."
: `Publish ${publishableTargets.length === 1 ? "environment" : `${publishableTargets.length} environments`}`}
</Text>
</Pressable>
) : null}
{hasRetryableErrors ? (
<Pressable
accessibilityRole="button"
disabled={props.isApplying}
onPress={props.onRetry}
className="self-start rounded-full bg-subtle px-3.5 py-2 active:opacity-70 disabled:opacity-50"
>
<Text className="text-xs font-t3-bold text-foreground">Check again</Text>
</Pressable>
) : null}
</View>
);
}
function publishTargetStatusText(target: PublishTarget): string {
switch (target.phase) {
case "checking":
return "Checking...";
case "published":
return "Already publishing";
case "ready":
return target.linked ? "Partially published — ready to update" : "Ready to publish";
case "unauthorized":
return "This device's session is not authorized to publish";
case "error":
return target.error ?? "Could not check the environment";
}
}
function PublishTargetStatusRow(props: { readonly target: PublishTarget }) {
const isError = props.target.phase === "error";
return (
<View className="flex-row items-baseline gap-2 px-2">
<Text className="min-w-0 flex-shrink text-xs font-t3-bold text-foreground" numberOfLines={1}>
{props.target.connection.environmentLabel}
</Text>
<Text
className={cn(
"min-w-0 flex-1 text-xs",
isError ? "text-rose-500 dark:text-rose-400" : "text-foreground-muted",
)}
numberOfLines={3}
>
{publishTargetStatusText(props.target)}
</Text>
</View>
);
}
@@ -0,0 +1,68 @@
import { useAtomValue } from "@effect/atom-react";
import { useNavigation } from "@react-navigation/native";
import { Atom } from "effect/unstable/reactivity";
import { useEffect } from "react";
import { loadPreferences, savePreferencesPatch } from "../../lib/storage";
import { appAtomRegistry } from "../../state/atom-registry";
// Signals RootStackLayout (inside the navigation tree) that an in-session
// sign-in just completed for an account that has not seen the T3 Connect
// onboarding sheet yet. Holds the account id so a sign-out between the request
// and the navigation cannot present the sheet for the wrong account.
const connectOnboardingRequestAtom = Atom.make<string | null>(null).pipe(
Atom.keepAlive,
Atom.withLabel("mobile:connect-onboarding-request"),
);
/**
* Requests the onboarding sheet for the given account unless it already
* completed (or skipped) onboarding on this device.
*/
export async function requestConnectOnboardingIfNeeded(accountId: string): Promise<void> {
const preferences = await loadPreferences();
if (preferences.connectOnboardingCompletedAccounts?.includes(accountId)) {
return;
}
appAtomRegistry.set(connectOnboardingRequestAtom, accountId);
}
export function clearConnectOnboardingRequest(): void {
appAtomRegistry.set(connectOnboardingRequestAtom, null);
}
/** Persists that the account saw the sheet, so it never nags twice. */
export async function markConnectOnboardingCompleted(accountId: string): Promise<void> {
const preferences = await loadPreferences();
const completed = preferences.connectOnboardingCompletedAccounts ?? [];
if (completed.includes(accountId)) {
return;
}
await savePreferencesPatch({ connectOnboardingCompletedAccounts: [...completed, accountId] });
}
// Sign-in happens inside the Settings sheet; give its detent/session-state
// transitions a beat to settle before presenting another formSheet on top.
const PRESENT_ONBOARDING_DELAY_MS = 600;
/**
* Consumes the onboarding request inside the navigation tree (RootStackLayout)
* and presents the onboarding formSheet.
*/
export function useConnectOnboardingNavigation(): void {
const navigation = useNavigation();
const requestedAccountId = useAtomValue(connectOnboardingRequestAtom);
useEffect(() => {
if (requestedAccountId === null) {
return;
}
const timer = setTimeout(() => {
clearConnectOnboardingRequest();
navigation.navigate("ConnectOnboarding");
}, PRESENT_ONBOARDING_DELAY_MS);
return () => {
clearTimeout(timer);
};
}, [navigation, requestedAccountId]);
}
@@ -3,6 +3,7 @@ import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { HttpClient } from "effect/unstable/http";
import {
AuthRelayWriteScope,
EnvironmentCloudEndpointUnavailableError,
EnvironmentHttpBadRequestError,
EnvironmentHttpConflictError,
@@ -76,6 +77,13 @@ const isEnvironmentCloudApiError = Schema.is(
const MANAGED_ENDPOINT_PROVIDER_KIND =
"cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind;
// "publish_only" links the environment to the relay for agent-activity
// publishing alone: no managed tunnel is provisioned (mirrors the web client's
// CloudLinkMode).
export type CloudLinkMode = "managed" | "publish_only";
const PUBLISH_ONLY_PROVIDER_KIND = "manual" satisfies RelayManagedEndpointProviderKind;
function cloudEnvironmentLinkError(message: string) {
return (cause: unknown) => {
const environmentError = findEnvironmentCloudApiError(cause);
@@ -259,6 +267,7 @@ function ensureConnectEndpointMatchesEnvironment(input: {
export function linkEnvironmentToCloud(input: {
readonly connection: SavedRemoteConnection;
readonly clerkToken: string;
readonly mode?: CloudLinkMode;
}): Effect.Effect<
void,
CloudEnvironmentLinkError,
@@ -271,6 +280,10 @@ export function linkEnvironmentToCloud(input: {
});
}
const localBearerToken = input.connection.bearerToken;
const managedTunnelsEnabled = (input.mode ?? "managed") === "managed";
const providerKind = managedTunnelsEnabled
? MANAGED_ENDPOINT_PROVIDER_KIND
: PUBLISH_ONLY_PROVIDER_KIND;
const relayUrl = yield* requireRelayUrl();
const relayClient = yield* ManagedRelay.ManagedRelayClient;
const deviceId = yield* Effect.tryPromise({
@@ -288,7 +301,7 @@ export function linkEnvironmentToCloud(input: {
payload: {
notificationsEnabled: true,
liveActivitiesEnabled,
managedTunnelsEnabled: true,
managedTunnelsEnabled,
},
})
.pipe(
@@ -306,7 +319,7 @@ export function linkEnvironmentToCloud(input: {
endpoint: {
httpBaseUrl: input.connection.httpBaseUrl,
wsBaseUrl: input.connection.wsBaseUrl,
providerKind: MANAGED_ENDPOINT_PROVIDER_KIND,
providerKind,
},
origin: endpointOrigin(input.connection.httpBaseUrl),
},
@@ -320,7 +333,7 @@ export function linkEnvironmentToCloud(input: {
proof,
notificationsEnabled: true,
liveActivitiesEnabled,
managedTunnelsEnabled: true,
managedTunnelsEnabled,
},
})
.pipe(
@@ -328,7 +341,7 @@ export function linkEnvironmentToCloud(input: {
);
yield* ensureLinkedEnvironmentMatches({
expectedEnvironmentId: input.connection.environmentId,
expectedProviderKind: MANAGED_ENDPOINT_PROVIDER_KIND,
expectedProviderKind: providerKind,
link,
});
@@ -350,6 +363,91 @@ export function linkEnvironmentToCloud(input: {
});
}
function requireBearerToken(
connection: SavedRemoteConnection,
): Effect.Effect<string, CloudEnvironmentLinkError> {
return connection.bearerToken
? Effect.succeed(connection.bearerToken)
: Effect.fail(
new CloudEnvironmentLinkError({
message: "Only a locally paired bearer connection can publish over T3 Connect.",
}),
);
}
export interface EnvironmentConnectPublishState {
/**
* Whether the connection's session holds relay:write. `null` when the
* environment did not report session scopes (older servers) — callers should
* attempt publishing and surface the server's denial.
*/
readonly canPublish: boolean | null;
readonly linked: boolean;
readonly managedTunnelActive: boolean;
readonly publishAgentActivity: boolean;
}
/**
* Reads the environment-side publish authorization (session scopes) and relay
* link state for a locally paired bearer connection.
*/
export function getEnvironmentConnectPublishState(input: {
readonly connection: SavedRemoteConnection;
}): Effect.Effect<
EnvironmentConnectPublishState,
CloudEnvironmentLinkError,
HttpClient.HttpClient
> {
return Effect.gen(function* () {
const localBearerToken = yield* requireBearerToken(input.connection);
const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl);
const headers = { authorization: `Bearer ${localBearerToken}` };
const session = yield* environmentClient.auth
.session({ headers })
.pipe(Effect.mapError(cloudEnvironmentLinkError("Could not read the environment session.")));
const linkState = yield* environmentClient.connect
.linkState({ headers })
.pipe(
Effect.mapError(cloudEnvironmentLinkError("Could not read the environment link state.")),
);
return {
canPublish: !session.authenticated
? false
: session.scopes === undefined
? null
: session.scopes.includes(AuthRelayWriteScope),
linked: linkState.linked,
managedTunnelActive: linkState.managedTunnelActive ?? linkState.linked,
publishAgentActivity: linkState.publishAgentActivity,
};
});
}
/**
* Sets the environment-server-side "publish agent activity" preference. The
* link flow does not touch this secret, so clients opting into activity
* publishing must call it explicitly.
*/
export function setEnvironmentPublishAgentActivity(input: {
readonly connection: SavedRemoteConnection;
readonly publishAgentActivity: boolean;
}): Effect.Effect<void, CloudEnvironmentLinkError, HttpClient.HttpClient> {
return Effect.gen(function* () {
const localBearerToken = yield* requireBearerToken(input.connection);
const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl);
yield* environmentClient.connect
.preferences({
headers: { authorization: `Bearer ${localBearerToken}` },
payload: { publishAgentActivity: input.publishAgentActivity },
})
.pipe(
Effect.mapError(
cloudEnvironmentLinkError("Could not update the environment publish preference."),
),
);
});
}
export function listCloudEnvironments(input: {
readonly clerkToken: string;
}): Effect.Effect<
@@ -0,0 +1,351 @@
import { useAuth } from "@clerk/expo";
import { SymbolView } from "expo-symbols";
import {
connectionStatusText,
type EnvironmentConnectionPhase,
} from "@t3tools/client-runtime/connection";
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback, useState } from "react";
import {
ActivityIndicator,
Pressable,
Switch,
type NativeSyntheticEvent,
type TextLayoutEventData,
View,
} from "react-native";
import { AppText as Text } from "../../components/AppText";
import { cn } from "../../lib/cn";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { useThemeColor } from "../../lib/useThemeColor";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironmentPresentation";
import { ConnectionStatusDot } from "./ConnectionStatusDot";
import { type RelayEnvironmentView, useConnectionController } from "./useConnectionController";
/**
* "T3 Cloud" section: every environment published to the signed-in account,
* with connect switches, availability status, refresh, and loading/error
* states. Shared between the Settings environments screen and the T3 Connect
* onboarding sheet.
*/
export function CloudEnvironmentRows(props: {
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
}) {
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const controller = useConnectionController();
const iconColor = useThemeColor("--color-icon");
const availableCloudEnvironments = controller.availableRelayEnvironments;
const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
const hasCloudRows =
props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
const handleConnectCloudEnvironment = useCallback(
(entry: RelayEnvironmentView) => controller.connectRelayEnvironment(entry.environment),
[controller],
);
const handleDisconnectCloudEnvironment = useCallback(
(environmentId: EnvironmentId) => controller.removeEnvironment(environmentId),
[controller],
);
const handleToggleCloudError = useCallback((environmentId: string) => {
setExpandedErrorId((current) => (current === environmentId ? null : environmentId));
}, []);
if (!isSignedIn) return null;
return (
<View collapsable={false} className="mt-5 gap-3">
<View className="flex-row items-center justify-between px-1">
<Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Cloud</Text>
<Pressable
accessibilityRole="button"
disabled={controller.relayDiscovery.isRefreshing}
onPress={() => {
void controller.refreshRelayEnvironments();
}}
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
>
{controller.relayDiscovery.isRefreshing ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView name="arrow.clockwise" size={14} tintColor={iconColor} type="monochrome" />
)}
</Pressable>
</View>
{hasCloudRows ? (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{props.connectedCloudEnvironments.map((environment, index) => (
<ConnectedCloudEnvironmentRow
key={environment.environmentId}
environment={environment}
borderTop={index !== 0}
onConnect={() => props.onReconnectEnvironment(environment.environmentId)}
onDisconnect={() => handleDisconnectCloudEnvironment(environment.environmentId)}
errorExpanded={expandedErrorId === environment.environmentId}
onToggleError={() => handleToggleCloudError(environment.environmentId)}
/>
))}
{availableCloudEnvironments.map((environment, index) => (
<CloudEnvironmentRow
key={environment.environment.environmentId}
environment={environment}
borderTop={props.connectedCloudEnvironments.length > 0 || index !== 0}
onConnect={() => handleConnectCloudEnvironment(environment)}
errorExpanded={expandedErrorId === environment.environment.environmentId}
onToggleError={() => handleToggleCloudError(environment.environment.environmentId)}
/>
))}
</View>
) : controller.relayDiscovery.isRefreshing ? (
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">
<ActivityIndicator color={iconColor} />
<Text className="text-center text-sm leading-normal text-foreground-muted">
Loading linked cloud environments.
</Text>
</View>
) : controller.relayDiscovery.error ? (
<View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
<Text className="text-base font-t3-bold text-foreground">
Could not load T3 Cloud environments
</Text>
<Text className="text-sm text-foreground-muted">{controller.relayDiscovery.error}</Text>
{controller.relayDiscovery.errorTraceId ? (
<CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />
) : null}
</View>
) : (
<View collapsable={false} className="rounded-[24px] bg-card p-5">
<Text className="text-sm leading-normal text-foreground-muted">
No additional linked cloud environments.
</Text>
</View>
)}
</View>
);
}
function ConnectedCloudEnvironmentRow(props: {
readonly environment: ConnectedEnvironmentSummary;
readonly borderTop: boolean;
readonly errorExpanded: boolean;
readonly onConnect: () => void;
readonly onDisconnect: () => void;
readonly onToggleError: () => void;
}) {
return (
<CloudEnvironmentRowShell
borderTop={props.borderTop}
connectionError={props.environment.connectionError}
connectionErrorTraceId={props.environment.connectionErrorTraceId}
connectionState={props.environment.connectionState}
errorExpanded={props.errorExpanded}
label={props.environment.environmentLabel}
onValueChange={(enabled) => {
if (enabled) {
props.onConnect();
return;
}
props.onDisconnect();
}}
onToggleError={props.onToggleError}
value={props.environment.connectionState !== "available"}
/>
);
}
function CloudEnvironmentRow(props: {
readonly environment: RelayEnvironmentView;
readonly borderTop: boolean;
readonly errorExpanded: boolean;
readonly onConnect: () => void;
readonly onToggleError: () => void;
}) {
const presentation = availableCloudEnvironmentPresentation({
isStatusPending: props.environment.availability === "checking",
status: props.environment.status,
statusError: props.environment.error,
statusErrorTraceId: props.environment.traceId,
});
return (
<CloudEnvironmentRowShell
borderTop={props.borderTop}
connectionError={presentation.connectionError}
connectionErrorTraceId={presentation.connectionErrorTraceId}
connectionState={presentation.connectionState}
errorExpanded={props.errorExpanded}
label={props.environment.environment.label}
onValueChange={(enabled) => {
if (enabled) {
props.onConnect();
}
}}
onToggleError={props.onToggleError}
statusText={presentation.statusText}
value={false}
/>
);
}
function CloudEnvironmentRowShell(props: {
readonly borderTop: boolean;
readonly connectionError: string | null;
readonly connectionErrorTraceId: string | null;
readonly connectionState: EnvironmentConnectionPhase;
readonly disabled?: boolean;
readonly errorExpanded: boolean;
readonly label: string;
readonly onToggleError: () => void;
readonly onValueChange: (enabled: boolean) => void;
readonly statusText?: string;
readonly value: boolean;
}) {
const activeTrack = String(useThemeColor("--color-switch-active"));
const track = String(useThemeColor("--color-secondary-border"));
const chevron = useThemeColor("--color-chevron");
const isRetrying =
props.connectionState === "connecting" || props.connectionState === "reconnecting";
const shouldPulse = isRetrying;
const statusText =
props.statusText ??
connectionStatusText({
phase: props.connectionState,
error: props.connectionError,
traceId: props.connectionErrorTraceId,
});
const statusClassName = props.connectionError
? "text-rose-500 dark:text-rose-400"
: "text-foreground-muted";
const [errorMeasurement, setErrorMeasurement] = useState<{
readonly text: string;
readonly lineCount: number;
} | null>(null);
const errorTraceId = props.connectionErrorTraceId;
const measuredErrorText = errorTraceId ? `${statusText} Trace ID: ${errorTraceId}` : statusText;
const errorLineCount =
errorMeasurement?.text === measuredErrorText ? errorMeasurement.lineCount : 0;
const errorCanExpand = props.connectionError !== null && errorLineCount > 1;
const isErrorExpanded = errorCanExpand && props.errorExpanded;
const StatusContainer = errorCanExpand ? Pressable : View;
const onMeasuredErrorTextLayout = useCallback(
(event: NativeSyntheticEvent<TextLayoutEventData>) => {
if (!props.connectionError) {
return;
}
const nextLineCount = event.nativeEvent.lines.length;
setErrorMeasurement((currentMeasurement) =>
currentMeasurement?.text === measuredErrorText &&
currentMeasurement.lineCount === nextLineCount
? currentMeasurement
: { text: measuredErrorText, lineCount: nextLineCount },
);
},
[measuredErrorText, props.connectionError],
);
return (
<View
collapsable={false}
className={cn(
"flex-row items-center gap-3 bg-card px-4 py-3.5",
props.borderTop && "border-t border-border",
)}
>
<View className="min-w-0 flex-1 gap-0.5">
<View className="min-w-0 flex-row items-center gap-2">
<ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
<Text
className="min-w-0 flex-shrink text-base font-t3-bold leading-snug text-foreground"
numberOfLines={1}
>
{props.label}
</Text>
</View>
{props.connectionError ? (
<Text
aria-hidden
className={cn("absolute left-0 right-0 text-xs", statusClassName)}
onTextLayout={onMeasuredErrorTextLayout}
style={{ opacity: 0, zIndex: -1 }}
>
{measuredErrorText}
</Text>
) : null}
<StatusContainer
{...(errorCanExpand
? { accessibilityRole: "button" as const, onPress: props.onToggleError }
: {})}
className="min-w-0 flex-row items-start gap-1"
>
<Text
className={cn("min-w-0 flex-1 text-xs", statusClassName)}
numberOfLines={isErrorExpanded ? undefined : 1}
>
{statusText}
{errorTraceId ? (
<>
{" Trace ID: "}
<Text
accessibilityHint="Copies the trace ID"
accessibilityRole="button"
className={cn("text-xs underline", statusClassName)}
onLongPress={(event) => {
event.stopPropagation();
copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });
}}
onPress={(event) => {
event.stopPropagation();
}}
style={{ textDecorationStyle: "dotted" }}
>
{errorTraceId}
</Text>
</>
) : null}
</Text>
{errorCanExpand ? (
<SymbolView
name="chevron.down"
size={10}
tintColor={chevron}
type="monochrome"
style={{
marginTop: 3,
transform: [{ rotate: isErrorExpanded ? "180deg" : "0deg" }],
}}
/>
) : null}
</StatusContainer>
</View>
<Switch
disabled={props.disabled}
ios_backgroundColor={track}
onValueChange={props.onValueChange}
trackColor={{ false: track, true: activeTrack }}
value={props.value}
/>
</View>
);
}
function CopyTraceIdButton(props: { readonly traceId: string }) {
const iconColor = useThemeColor("--color-icon");
return (
<Pressable
accessibilityRole="button"
onPress={() => {
copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });
}}
className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
>
<SymbolView name="doc.on.doc" size={12} tintColor={iconColor} type="monochrome" />
<Text className="text-xs font-t3-bold text-foreground">Copy trace ID</Text>
</Pressable>
);
}
@@ -1,38 +1,18 @@
import { useAuth } from "@clerk/expo";
import { NativeHeaderToolbar } from "../../native/StackHeader";
import { useNavigation } from "@react-navigation/native";
import { SymbolView } from "expo-symbols";
import {
connectionStatusText,
type EnvironmentConnectionPhase,
} from "@t3tools/client-runtime/connection";
import type { EnvironmentId } from "@t3tools/contracts";
import { useCallback, useState } from "react";
import {
ActivityIndicator,
Pressable,
ScrollView,
Switch,
type NativeSyntheticEvent,
type TextLayoutEventData,
View,
} from "react-native";
import { ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import {
type RelayEnvironmentView,
useConnectionController,
} from "../connection/useConnectionController";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironmentPresentation";
import { CloudEnvironmentRows } from "../connection/CloudEnvironmentRows";
import { ConnectionEnvironmentRow } from "../connection/ConnectionEnvironmentRow";
import { ConnectionStatusDot } from "../connection/ConnectionStatusDot";
import { splitEnvironmentSections } from "../connection/environmentSections";
import { cn } from "../../lib/cn";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { useThemeColor } from "../../lib/useThemeColor";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
export function SettingsEnvironmentsRouteScreen() {
@@ -117,7 +97,7 @@ export function SettingsEnvironmentsRouteScreen() {
)}
{hasCloudPublicConfig() ? (
<ConfiguredCloudEnvironmentRows
<CloudEnvironmentRows
connectedCloudEnvironments={connectedCloudEnvironments}
onReconnectEnvironment={onReconnectEnvironment}
/>
@@ -126,323 +106,3 @@ export function SettingsEnvironmentsRouteScreen() {
</View>
);
}
function ConfiguredCloudEnvironmentRows(props: {
readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
}) {
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const controller = useConnectionController();
const iconColor = useThemeColor("--color-icon");
const availableCloudEnvironments = controller.availableRelayEnvironments;
const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
const hasCloudRows =
props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
const handleConnectCloudEnvironment = useCallback(
(entry: RelayEnvironmentView) => controller.connectRelayEnvironment(entry.environment),
[controller],
);
const handleDisconnectCloudEnvironment = useCallback(
(environmentId: EnvironmentId) => controller.removeEnvironment(environmentId),
[controller],
);
const handleToggleCloudError = useCallback((environmentId: string) => {
setExpandedErrorId((current) => (current === environmentId ? null : environmentId));
}, []);
if (!isSignedIn) return null;
return (
<View collapsable={false} className="mt-5 gap-3">
<View className="flex-row items-center justify-between px-1">
<Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Cloud</Text>
<Pressable
accessibilityRole="button"
disabled={controller.relayDiscovery.isRefreshing}
onPress={() => {
void controller.refreshRelayEnvironments();
}}
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
>
{controller.relayDiscovery.isRefreshing ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView name="arrow.clockwise" size={14} tintColor={iconColor} type="monochrome" />
)}
</Pressable>
</View>
{hasCloudRows ? (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{props.connectedCloudEnvironments.map((environment, index) => (
<ConnectedCloudEnvironmentRow
key={environment.environmentId}
environment={environment}
borderTop={index !== 0}
onConnect={() => props.onReconnectEnvironment(environment.environmentId)}
onDisconnect={() => handleDisconnectCloudEnvironment(environment.environmentId)}
errorExpanded={expandedErrorId === environment.environmentId}
onToggleError={() => handleToggleCloudError(environment.environmentId)}
/>
))}
{availableCloudEnvironments.map((environment, index) => (
<CloudEnvironmentRow
key={environment.environment.environmentId}
environment={environment}
borderTop={props.connectedCloudEnvironments.length > 0 || index !== 0}
onConnect={() => handleConnectCloudEnvironment(environment)}
errorExpanded={expandedErrorId === environment.environment.environmentId}
onToggleError={() => handleToggleCloudError(environment.environment.environmentId)}
/>
))}
</View>
) : controller.relayDiscovery.isRefreshing ? (
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">
<ActivityIndicator color={iconColor} />
<Text className="text-center text-sm leading-normal text-foreground-muted">
Loading linked cloud environments.
</Text>
</View>
) : controller.relayDiscovery.error ? (
<View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
<Text className="text-base font-t3-bold text-foreground">
Could not load T3 Cloud environments
</Text>
<Text className="text-sm text-foreground-muted">{controller.relayDiscovery.error}</Text>
{controller.relayDiscovery.errorTraceId ? (
<CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />
) : null}
</View>
) : (
<View collapsable={false} className="rounded-[24px] bg-card p-5">
<Text className="text-sm leading-normal text-foreground-muted">
No additional linked cloud environments.
</Text>
</View>
)}
</View>
);
}
function ConnectedCloudEnvironmentRow(props: {
readonly environment: ConnectedEnvironmentSummary;
readonly borderTop: boolean;
readonly errorExpanded: boolean;
readonly onConnect: () => void;
readonly onDisconnect: () => void;
readonly onToggleError: () => void;
}) {
return (
<CloudEnvironmentRowShell
borderTop={props.borderTop}
connectionError={props.environment.connectionError}
connectionErrorTraceId={props.environment.connectionErrorTraceId}
connectionState={props.environment.connectionState}
errorExpanded={props.errorExpanded}
label={props.environment.environmentLabel}
onValueChange={(enabled) => {
if (enabled) {
props.onConnect();
return;
}
props.onDisconnect();
}}
onToggleError={props.onToggleError}
value={props.environment.connectionState !== "available"}
/>
);
}
function CloudEnvironmentRow(props: {
readonly environment: RelayEnvironmentView;
readonly borderTop: boolean;
readonly errorExpanded: boolean;
readonly onConnect: () => void;
readonly onToggleError: () => void;
}) {
const presentation = availableCloudEnvironmentPresentation({
isStatusPending: props.environment.availability === "checking",
status: props.environment.status,
statusError: props.environment.error,
statusErrorTraceId: props.environment.traceId,
});
return (
<CloudEnvironmentRowShell
borderTop={props.borderTop}
connectionError={presentation.connectionError}
connectionErrorTraceId={presentation.connectionErrorTraceId}
connectionState={presentation.connectionState}
errorExpanded={props.errorExpanded}
label={props.environment.environment.label}
onValueChange={(enabled) => {
if (enabled) {
props.onConnect();
}
}}
onToggleError={props.onToggleError}
statusText={presentation.statusText}
value={false}
/>
);
}
function CloudEnvironmentRowShell(props: {
readonly borderTop: boolean;
readonly connectionError: string | null;
readonly connectionErrorTraceId: string | null;
readonly connectionState: EnvironmentConnectionPhase;
readonly disabled?: boolean;
readonly errorExpanded: boolean;
readonly label: string;
readonly onToggleError: () => void;
readonly onValueChange: (enabled: boolean) => void;
readonly statusText?: string;
readonly value: boolean;
}) {
const activeTrack = String(useThemeColor("--color-switch-active"));
const track = String(useThemeColor("--color-secondary-border"));
const chevron = useThemeColor("--color-chevron");
const isRetrying =
props.connectionState === "connecting" || props.connectionState === "reconnecting";
const shouldPulse = isRetrying;
const statusText =
props.statusText ??
connectionStatusText({
phase: props.connectionState,
error: props.connectionError,
traceId: props.connectionErrorTraceId,
});
const statusClassName = props.connectionError
? "text-rose-500 dark:text-rose-400"
: "text-foreground-muted";
const [errorMeasurement, setErrorMeasurement] = useState<{
readonly text: string;
readonly lineCount: number;
} | null>(null);
const errorTraceId = props.connectionErrorTraceId;
const measuredErrorText = errorTraceId ? `${statusText} Trace ID: ${errorTraceId}` : statusText;
const errorLineCount =
errorMeasurement?.text === measuredErrorText ? errorMeasurement.lineCount : 0;
const errorCanExpand = props.connectionError !== null && errorLineCount > 1;
const isErrorExpanded = errorCanExpand && props.errorExpanded;
const StatusContainer = errorCanExpand ? Pressable : View;
const onMeasuredErrorTextLayout = useCallback(
(event: NativeSyntheticEvent<TextLayoutEventData>) => {
if (!props.connectionError) {
return;
}
const nextLineCount = event.nativeEvent.lines.length;
setErrorMeasurement((currentMeasurement) =>
currentMeasurement?.text === measuredErrorText &&
currentMeasurement.lineCount === nextLineCount
? currentMeasurement
: { text: measuredErrorText, lineCount: nextLineCount },
);
},
[measuredErrorText, props.connectionError],
);
return (
<View
collapsable={false}
className={cn(
"flex-row items-center gap-3 bg-card px-4 py-3.5",
props.borderTop && "border-t border-border",
)}
>
<View className="min-w-0 flex-1 gap-0.5">
<View className="min-w-0 flex-row items-center gap-2">
<ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
<Text
className="min-w-0 flex-shrink text-base font-t3-bold leading-snug text-foreground"
numberOfLines={1}
>
{props.label}
</Text>
</View>
{props.connectionError ? (
<Text
aria-hidden
className={cn("absolute left-0 right-0 text-xs", statusClassName)}
onTextLayout={onMeasuredErrorTextLayout}
style={{ opacity: 0, zIndex: -1 }}
>
{measuredErrorText}
</Text>
) : null}
<StatusContainer
{...(errorCanExpand
? { accessibilityRole: "button" as const, onPress: props.onToggleError }
: {})}
className="min-w-0 flex-row items-start gap-1"
>
<Text
className={cn("min-w-0 flex-1 text-xs", statusClassName)}
numberOfLines={isErrorExpanded ? undefined : 1}
>
{statusText}
{errorTraceId ? (
<>
{" Trace ID: "}
<Text
accessibilityHint="Copies the trace ID"
accessibilityRole="button"
className={cn("text-xs underline", statusClassName)}
onLongPress={(event) => {
event.stopPropagation();
copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });
}}
onPress={(event) => {
event.stopPropagation();
}}
style={{ textDecorationStyle: "dotted" }}
>
{errorTraceId}
</Text>
</>
) : null}
</Text>
{errorCanExpand ? (
<SymbolView
name="chevron.down"
size={10}
tintColor={chevron}
type="monochrome"
style={{
marginTop: 3,
transform: [{ rotate: isErrorExpanded ? "180deg" : "0deg" }],
}}
/>
) : null}
</StatusContainer>
</View>
<Switch
disabled={props.disabled}
ios_backgroundColor={track}
onValueChange={props.onValueChange}
trackColor={{ false: track, true: activeTrack }}
value={props.value}
/>
</View>
);
}
function CopyTraceIdButton(props: { readonly traceId: string }) {
const iconColor = useThemeColor("--color-icon");
return (
<Pressable
accessibilityRole="button"
onPress={() => {
copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });
}}
className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
>
<SymbolView name="doc.on.doc" size={12} tintColor={iconColor} type="monochrome" />
<Text className="text-xs font-t3-bold text-foreground">Copy trace ID</Text>
</Pressable>
);
}
+9
View File
@@ -69,6 +69,8 @@ export interface Preferences {
/** Code/diff font size override; null/absent means derived from baseFontSize. */
readonly codeFontSize?: number | null;
readonly codeWordBreak?: boolean;
/** Cloud account ids that already saw the T3 Connect onboarding sheet. */
readonly connectOnboardingCompletedAccounts?: ReadonlyArray<string>;
}
async function readStorageItem(key: MobileStorageKeyValue): Promise<string | null> {
@@ -167,6 +169,7 @@ export async function loadPreferences(): Promise<Preferences> {
markdownFontSize?: number;
codeFontSize?: number | null;
codeWordBreak?: boolean;
connectOnboardingCompletedAccounts?: ReadonlyArray<string>;
} = {};
if (typeof parsed.liveActivitiesEnabled === "boolean") {
@@ -187,6 +190,12 @@ export async function loadPreferences(): Promise<Preferences> {
if (typeof parsed.codeWordBreak === "boolean") {
preferences.codeWordBreak = parsed.codeWordBreak;
}
if (Array.isArray(parsed.connectOnboardingCompletedAccounts)) {
preferences.connectOnboardingCompletedAccounts =
parsed.connectOnboardingCompletedAccounts.filter(
(account): account is string => typeof account === "string",
);
}
return preferences;
}
+18
View File
@@ -0,0 +1,18 @@
import * as Schema from "effect/Schema";
/**
* Tracks which T3 Connect accounts have completed (or dismissed) the
* post-sign-in onboarding wizard, so it is shown at most once per account per
* browser.
*/
export const CONNECT_ONBOARDING_STORAGE_KEY = "t3code:connect-onboarding:v1";
export const ConnectOnboardingStateSchema = Schema.Struct({
completedAccounts: Schema.Array(Schema.String),
});
export type ConnectOnboardingState = typeof ConnectOnboardingStateSchema.Type;
export const EMPTY_CONNECT_ONBOARDING_STATE: ConnectOnboardingState = {
completedAccounts: [],
};
@@ -0,0 +1,161 @@
import { useAuth } from "@clerk/react";
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import {
isAtomCommandInterrupted,
settlePromise,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { useState } from "react";
import { toastManager } from "../components/ui/toast";
import { relayEnvironmentDiscovery } from "../state/relay";
import { useAtomCommand } from "../state/use-atom-command";
import {
linkPrimaryEnvironment as linkPrimaryEnvironmentAtom,
unlinkPrimaryEnvironment as unlinkPrimaryEnvironmentAtom,
updatePrimaryEnvironmentPreferences as updatePrimaryEnvironmentPreferencesAtom,
} from "./linkEnvironmentAtoms";
import { usePrimaryCloudLinkState } from "./primaryCloudLinkState";
import { resolveRelayClerkTokenOptions } from "./publicConfig";
export interface CloudLinkDesiredState {
readonly managedTunnel: boolean;
readonly publish: boolean;
}
/**
* Drives the primary environment's T3 Connect link. T3 Connect (managed
* tunnel) and agent-activity publishing are independent capabilities backed by
* a single relay link, so consumers express the full desired state and
* `reconcileCloudState` applies it: unlink when neither is wanted, otherwise
* (re)link with the mode the managed-tunnel bit implies and set the publish
* preference. Re-linking only happens when the managed-tunnel mode actually
* changes, so flipping publish alone is cheap.
*/
export function useCloudLinkController() {
const { getToken, isSignedIn } = useAuth();
const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
reportFailure: false,
});
const linkPrimaryEnvironment = useAtomCommand(linkPrimaryEnvironmentAtom, {
reportFailure: false,
});
const unlinkPrimaryEnvironment = useAtomCommand(unlinkPrimaryEnvironmentAtom, {
reportFailure: false,
});
const updatePrimaryEnvironmentPreferences = useAtomCommand(
updatePrimaryEnvironmentPreferencesAtom,
{ reportFailure: false },
);
const primaryCloudLinkState = usePrimaryCloudLinkState();
const [operationError, setOperationError] = useState<string | null>(null);
const reportUpdateFailure = (cause: unknown) => {
const message = cause instanceof Error ? cause.message : "Could not update T3 Connect access.";
const traceId = findErrorTraceId(cause);
console.error("[t3-connect] Could not update T3 Connect", { message, traceId, cause });
setOperationError(traceId ? `${message} Trace ID: ${traceId}` : message);
toastManager.add({
type: "error",
title: "Could not update T3 Connect",
description: message,
data: traceId
? {
secondaryActionProps: {
children: "Copy trace ID",
onClick: () => void navigator.clipboard?.writeText(traceId),
},
}
: undefined,
});
};
// Older environment servers predate the managedTunnelActive field; for them a
// link always implies a managed tunnel, so fall back to `linked`.
const managedTunnelActive =
primaryCloudLinkState.data?.managedTunnelActive ?? primaryCloudLinkState.data?.linked ?? false;
const publishAgentActivity = primaryCloudLinkState.data?.publishAgentActivity ?? false;
const linked = primaryCloudLinkState.data?.linked ?? false;
const reconcileCloudState = async (desired: CloudLinkDesiredState): Promise<boolean> => {
setOperationError(null);
const target = primaryCloudLinkState.target;
if (!target) {
reportUpdateFailure(new Error("Local environment is not ready yet."));
return false;
}
const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
if (tokenResult._tag === "Failure") {
reportUpdateFailure(squashAtomCommandFailure(tokenResult));
return false;
}
const clerkToken = tokenResult.value;
const wantsLink = desired.managedTunnel || desired.publish;
// A failure after this point may follow a partially applied mutation (e.g.
// the link succeeded but the preference update did not), so every exit —
// success or failure — refreshes the rendered state to whatever the server
// actually holds now.
if (!wantsLink) {
const unlinkResult = await unlinkPrimaryEnvironment({
target,
clerkToken: clerkToken ?? null,
});
if (unlinkResult._tag === "Failure") {
if (!isAtomCommandInterrupted(unlinkResult)) {
reportUpdateFailure(squashAtomCommandFailure(unlinkResult));
}
primaryCloudLinkState.refresh();
return false;
}
} else {
if (!clerkToken) {
reportUpdateFailure(new Error("Sign in to T3 Connect before enabling this."));
return false;
}
if (!linked || managedTunnelActive !== desired.managedTunnel) {
const linkResult = await linkPrimaryEnvironment({
target,
clerkToken,
mode: desired.managedTunnel ? "managed" : "publish_only",
});
if (linkResult._tag === "Failure") {
if (!isAtomCommandInterrupted(linkResult)) {
reportUpdateFailure(squashAtomCommandFailure(linkResult));
}
primaryCloudLinkState.refresh();
return false;
}
}
const prefResult = await updatePrimaryEnvironmentPreferences({
target,
publishAgentActivity: desired.publish,
});
if (prefResult._tag === "Failure") {
if (!isAtomCommandInterrupted(prefResult)) {
reportUpdateFailure(squashAtomCommandFailure(prefResult));
}
primaryCloudLinkState.refresh();
return false;
}
}
primaryCloudLinkState.refresh();
const refreshResult = await refreshRelayEnvironments();
if (refreshResult._tag === "Failure" && !isAtomCommandInterrupted(refreshResult)) {
reportUpdateFailure(squashAtomCommandFailure(refreshResult));
return false;
}
return true;
};
return {
isSignedIn,
linkState: primaryCloudLinkState,
linked,
managedTunnelActive,
publishAgentActivity,
operationError,
reconcileCloudState,
};
}
@@ -0,0 +1,56 @@
import { cn } from "~/lib/utils";
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
type ConnectionStatusDotProps = {
tooltipText?: string | null;
dotClassName: string;
pingClassName?: string | null;
};
export function ConnectionStatusDot({
tooltipText,
dotClassName,
pingClassName,
}: ConnectionStatusDotProps) {
const dotContent = (
<>
{pingClassName ? (
<span
className={cn(
"absolute inline-flex h-full w-full animate-ping rounded-full",
pingClassName,
)}
/>
) : null}
<span className={cn("relative inline-flex size-2 rounded-full", dotClassName)} />
</>
);
if (!tooltipText) {
return (
<span className="relative flex size-3 shrink-0 items-center justify-center">
{dotContent}
</span>
);
}
const dot = (
<button
type="button"
title={tooltipText}
aria-label={tooltipText}
className="relative flex size-3 shrink-0 cursor-help items-center justify-center rounded-full outline-hidden"
>
{dotContent}
</button>
);
return (
<Tooltip>
<TooltipTrigger render={dot} />
<TooltipPopup side="top" className="max-w-80 whitespace-pre-wrap leading-tight">
{tooltipText}
</TooltipPopup>
</Tooltip>
);
}
@@ -0,0 +1,204 @@
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import {
RelayConnectionRegistration,
RelayConnectionTarget,
} from "@t3tools/client-runtime/connection";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
import * as Option from "effect/Option";
import { type ReactNode, useCallback, useEffect, useMemo, useState } from "react";
import { environmentCatalog } from "~/connection/catalog";
import { cn } from "~/lib/utils";
import { relayEnvironmentDiscovery } from "~/state/relay";
import { useRelayEnvironmentDiscovery } from "~/state/environments";
import { useAtomCommand } from "~/state/use-atom-command";
import { ConnectionStatusDot } from "../ConnectionStatusDot";
import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "../settings/itemRows";
import { Button } from "../ui/button";
import { Skeleton } from "../ui/skeleton";
import { toastManager } from "../ui/toast";
export function RemoteEnvironmentRowsSkeleton() {
return (
<div className={ITEM_ROW_CLASSNAME}>
<div className={ITEM_ROW_INNER_CLASSNAME}>
<div className="min-w-0 flex-1 space-y-2">
<Skeleton className="h-4 w-32 rounded-full" />
<Skeleton className="h-3 w-20 rounded-full" />
</div>
<Skeleton className="h-7 w-16 rounded-md" />
</div>
</div>
);
}
/**
* The user's T3 Connect environments from relay discovery, each with a
* Connect button. The primary environment is always excluded; already-saved
* environments are hidden unless `showSavedAsConnected` renders them as
* connected instead (used by onboarding, where the full device mesh should be
* visible).
*/
export function CloudEnvironmentConnectRows({
primaryEnvironmentId,
savedEnvironmentIds,
showSavedAsConnected = false,
empty = null,
}: {
readonly primaryEnvironmentId: EnvironmentId | null;
readonly savedEnvironmentIds: ReadonlyArray<EnvironmentId>;
readonly showSavedAsConnected?: boolean;
readonly empty?: ReactNode;
}) {
const environmentsState = useRelayEnvironmentDiscovery();
const registerEnvironment = useAtomCommand(environmentCatalog.register, {
reportFailure: false,
});
const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
reportFailure: false,
});
const connectRelayEnvironment = useCallback(
(environment: RelayClientEnvironmentRecord) =>
registerEnvironment(
new RelayConnectionRegistration({
target: new RelayConnectionTarget({
environmentId: environment.environmentId,
label: environment.label,
}),
}),
),
[registerEnvironment],
);
const [connectingEnvironmentId, setConnectingEnvironmentId] = useState<EnvironmentId | null>(
null,
);
const savedIds = useMemo(() => new Set(savedEnvironmentIds), [savedEnvironmentIds]);
useEffect(() => {
void refreshRelayEnvironments();
}, [refreshRelayEnvironments]);
const connectEnvironment = async (environment: RelayClientEnvironmentRecord) => {
setConnectingEnvironmentId(environment.environmentId);
const result = await connectRelayEnvironment(environment);
setConnectingEnvironmentId(null);
if (result._tag === "Success") {
toastManager.add({
type: "success",
title: "Environment connected",
description: `${environment.label} is available through T3 Connect.`,
});
return;
}
if (isAtomCommandInterrupted(result)) {
return;
}
const cause = squashAtomCommandFailure(result);
const message =
cause instanceof Error ? cause.message : "Could not connect the T3 Connect environment.";
const traceId = findErrorTraceId(cause);
console.error("[t3-connect] Could not connect environment", { message, traceId, cause });
toastManager.add({
type: "error",
title: "Could not connect environment",
description: message,
data: traceId
? {
secondaryActionProps: {
children: "Copy trace ID",
onClick: () => void navigator.clipboard?.writeText(traceId),
},
}
: undefined,
});
};
const visibleEnvironments = [...environmentsState.environments.values()].filter(
({ environment }) =>
environment.environmentId !== primaryEnvironmentId &&
(showSavedAsConnected || !savedIds.has(environment.environmentId)),
);
const standalone = showSavedAsConnected || savedEnvironmentIds.length === 0;
if (
standalone &&
visibleEnvironments.length === 0 &&
environmentsState.refreshing &&
environmentsState.environments.size === 0
) {
return <RemoteEnvironmentRowsSkeleton />;
}
if (standalone && visibleEnvironments.length === 0) {
return empty;
}
return visibleEnvironments.map(({ environment, availability, error }) => {
const alreadyConnected = savedIds.has(environment.environmentId);
return (
<div key={environment.environmentId} className={ITEM_ROW_CLASSNAME}>
<div className={ITEM_ROW_INNER_CLASSNAME}>
<div className="min-w-0">
<div className="flex items-center gap-2">
<ConnectionStatusDot
dotClassName={
availability === "online"
? "bg-success"
: availability === "error"
? "bg-destructive"
: availability === "checking"
? "bg-warning"
: "bg-muted-foreground/35"
}
pingClassName={availability === "checking" ? "bg-warning/60 duration-2000" : null}
tooltipText={
availability === "online"
? "Relay online"
: availability === "offline"
? "Relay offline"
: availability === "checking"
? "Checking relay status"
: (Option.getOrNull(error)?.message ?? "Relay status unavailable")
}
/>
<p className="truncate text-sm font-medium">{environment.label}</p>
</div>
<p
className={cn(
"mt-1 truncate text-xs",
availability === "error" ? "text-destructive" : "text-muted-foreground",
)}
>
{availability === "online"
? "Available · Relay online"
: availability === "offline"
? "Available · Relay offline"
: availability === "checking"
? "Available · Checking relay status…"
: (Option.getOrNull(error)?.message ?? "Available · Relay status unavailable")}
</p>
</div>
{alreadyConnected ? (
<Button size="sm" variant="outline" disabled>
Connected
</Button>
) : (
<Button
size="sm"
disabled={connectingEnvironmentId !== null}
onClick={() => void connectEnvironment(environment)}
>
{connectingEnvironmentId === environment.environmentId ? "Connecting…" : "Connect"}
</Button>
)}
</div>
</div>
);
});
}
@@ -0,0 +1,368 @@
import { useAuth } from "@clerk/react";
import { AuthAdministrativeScopes, AuthRelayWriteScope } from "@t3tools/contracts";
import { CheckIcon } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import {
CONNECT_ONBOARDING_STORAGE_KEY,
ConnectOnboardingStateSchema,
EMPTY_CONNECT_ONBOARDING_STATE,
} from "~/cloud/connectOnboarding";
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
import { useCloudLinkController } from "~/cloud/useCloudLinkController";
import { usePrimarySessionState } from "~/environments/primary";
import { useLocalStorage } from "~/hooks/useLocalStorage";
import { cn } from "~/lib/utils";
import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";
import { CloudEnvironmentConnectRows } from "./CloudEnvironmentConnectList";
import { Button } from "../ui/button";
import {
Dialog,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "../ui/dialog";
import { Switch } from "../ui/switch";
import { toastManager } from "../ui/toast";
/**
* Post-sign-in onboarding wizard for T3 Connect. Opens once per account (per
* browser) after the user is signed in: first prompts to publish this
* environment (managed tunnel + agent activity, both defaulting on) when the
* current session is authorized to manage the relay link, then lists the
* account's T3 Connect environments so every device can be connected right
* away. Dismissing the dialog counts as completion — it never nags twice.
*/
export function ConnectOnboardingDialog() {
if (!hasCloudPublicConfig()) return null;
return <ConfiguredConnectOnboardingDialog />;
}
type OnboardingStep = "publish" | "devices";
function ConfiguredConnectOnboardingDialog() {
const { isLoaded, isSignedIn, userId } = useAuth();
const [onboardingState, setOnboardingState] = useLocalStorage(
CONNECT_ONBOARDING_STORAGE_KEY,
EMPTY_CONNECT_ONBOARDING_STATE,
ConnectOnboardingStateSchema,
);
const desktopBridge = window.desktopBridge;
const primarySessionState = usePrimarySessionState();
const currentSessionScopes = desktopBridge
? AuthAdministrativeScopes
: primarySessionState.data?.authenticated
? (primarySessionState.data.scopes ?? null)
: null;
const canManageRelay = currentSessionScopes?.includes(AuthRelayWriteScope) ?? false;
// The publish step is only offered when we know the answer; opening the
// wizard before the session state resolves would let the step set change
// mid-flight. A failed session read still opens the wizard — it just means
// no publish step.
const sessionScopesKnown =
Boolean(desktopBridge) ||
primarySessionState.data !== null ||
primarySessionState.error !== null;
const controller = useCloudLinkController();
const showPublishStep = canManageRelay && controller.linkState.target !== null;
const steps: ReadonlyArray<OnboardingStep> = showPublishStep
? ["publish", "devices"]
: ["devices"];
const [openForAccount, setOpenForAccount] = useState<string | null>(null);
const [step, setStep] = useState<OnboardingStep>("devices");
const [exposeEnvironment, setExposeEnvironment] = useState(true);
const [publishAgentActivity, setPublishAgentActivity] = useState(true);
const [isApplying, setIsApplying] = useState(false);
const prefilledFromLinkStateRef = useRef(false);
const completedAccounts = onboardingState.completedAccounts;
useEffect(() => {
if (!isLoaded || !isSignedIn || !userId) return;
if (openForAccount !== null) return;
if (completedAccounts.includes(userId)) return;
if (!sessionScopesKnown) return;
prefilledFromLinkStateRef.current = false;
setExposeEnvironment(true);
setPublishAgentActivity(true);
setStep(canManageRelay && controller.linkState.target !== null ? "publish" : "devices");
setOpenForAccount(userId);
}, [
canManageRelay,
completedAccounts,
controller.linkState.target,
isLoaded,
isSignedIn,
openForAccount,
sessionScopesKnown,
userId,
]);
// Signing out (or switching accounts) mid-wizard invalidates everything the
// wizard would do — close it and let the sign-in trigger re-evaluate.
useEffect(() => {
if (openForAccount !== null && (!isSignedIn || userId !== openForAccount)) {
setOpenForAccount(null);
}
}, [isSignedIn, openForAccount, userId]);
// Toggles default on, but an environment that is already linked should show
// its actual configuration instead of silently proposing to rewrite it.
const linkStateData = controller.linkState.data;
useEffect(() => {
if (openForAccount === null || prefilledFromLinkStateRef.current || linkStateData === null) {
return;
}
prefilledFromLinkStateRef.current = true;
if (linkStateData.linked) {
setExposeEnvironment(linkStateData.managedTunnelActive ?? linkStateData.linked);
setPublishAgentActivity(linkStateData.publishAgentActivity);
}
}, [linkStateData, openForAccount]);
const complete = () => {
const account = openForAccount;
setOpenForAccount(null);
if (!account) return;
setOnboardingState((state) =>
state.completedAccounts.includes(account)
? state
: { completedAccounts: [...state.completedAccounts, account] },
);
};
const applyPublishSelection = async () => {
// The wizard only ever enables — with both toggles off there is nothing to
// apply, and an existing link must not be torn down from onboarding.
if (!exposeEnvironment && !publishAgentActivity) {
setStep("devices");
return;
}
setIsApplying(true);
const ok = await controller.reconcileCloudState({
managedTunnel: exposeEnvironment,
publish: publishAgentActivity,
});
setIsApplying(false);
if (!ok) return;
toastManager.add({
type: "success",
title: "T3 Connect enabled",
description: exposeEnvironment
? "This environment is available to your other devices through T3 Connect."
: "This environment publishes agent activity to your mobile clients.",
});
setStep("devices");
};
return (
<Dialog
open={openForAccount !== null}
onOpenChange={(open) => {
if (!open) complete();
}}
>
<DialogPopup className="max-w-xl">
<DialogHeader>
<DialogTitle>Set up T3 Connect</DialogTitle>
<DialogDescription>
Mesh your devices together — publish this environment and connect the rest, all in one
place.
</DialogDescription>
{steps.length > 1 ? (
<OnboardingStepper steps={steps} currentStep={step} onStepSelect={setStep} />
) : null}
</DialogHeader>
<DialogPanel>
{step === "publish" ? (
<PublishStep
exposeEnvironment={exposeEnvironment}
publishAgentActivity={publishAgentActivity}
disabled={isApplying}
operationError={controller.operationError}
onExposeEnvironmentChange={setExposeEnvironment}
onPublishAgentActivityChange={setPublishAgentActivity}
/>
) : (
<DevicesStep />
)}
</DialogPanel>
<DialogFooter variant="bare">
{step === "publish" ? (
<>
<Button variant="ghost" disabled={isApplying} onClick={() => setStep("devices")}>
Not now
</Button>
<Button
disabled={isApplying || (controller.linkState.isPending && linkStateData === null)}
onClick={() => void applyPublishSelection()}
>
{isApplying ? "Enabling…" : "Continue"}
</Button>
</>
) : (
<Button onClick={complete}>Done</Button>
)}
</DialogFooter>
</DialogPopup>
</Dialog>
);
}
const STEP_LABELS: Record<OnboardingStep, string> = {
publish: "Publish",
devices: "Connect devices",
};
function OnboardingStepper({
steps,
currentStep,
onStepSelect,
}: {
readonly steps: ReadonlyArray<OnboardingStep>;
readonly currentStep: OnboardingStep;
readonly onStepSelect: (step: OnboardingStep) => void;
}) {
const currentIndex = steps.indexOf(currentStep);
return (
<div className="grid grid-cols-2 gap-2">
{steps.map((step, index) => (
<button
key={step}
type="button"
className={cn(
"grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] gap-x-2 rounded-lg border px-3 py-2 text-left",
index === currentIndex
? "border-primary bg-primary/10 ring-1 ring-primary/25"
: index < currentIndex
? "border-border bg-background"
: "border-border bg-muted/40",
)}
onClick={() => onStepSelect(step)}
>
<span
className={cn(
"row-span-2 mt-0.5 grid size-4 place-items-center rounded-full border",
index < currentIndex
? "border-primary bg-primary text-primary-foreground"
: index === currentIndex
? "border-primary bg-background"
: "border-muted-foreground/35 bg-background",
)}
aria-hidden
>
{index < currentIndex ? <CheckIcon className="size-3" /> : null}
</span>
<span className="text-[10px] font-medium uppercase text-muted-foreground">
Step {index + 1}
</span>
<span className="truncate text-xs font-semibold text-foreground">
{STEP_LABELS[step]}
</span>
</button>
))}
</div>
);
}
function PublishStep({
exposeEnvironment,
publishAgentActivity,
disabled,
operationError,
onExposeEnvironmentChange,
onPublishAgentActivityChange,
}: {
readonly exposeEnvironment: boolean;
readonly publishAgentActivity: boolean;
readonly disabled: boolean;
readonly operationError: string | null;
readonly onExposeEnvironmentChange: (enabled: boolean) => void;
readonly onPublishAgentActivityChange: (enabled: boolean) => void;
}) {
return (
<div className="space-y-3">
<div className="rounded-lg border">
<OnboardingToggleRow
title="Publish this environment"
description="Make this environment available to your other devices through T3 Connect."
checked={exposeEnvironment}
disabled={disabled}
onCheckedChange={onExposeEnvironmentChange}
/>
<OnboardingToggleRow
title="Publish agent activity"
description="Send activity from this environment to your mobile clients for push notifications and Live Activities."
checked={publishAgentActivity}
disabled={disabled}
onCheckedChange={onPublishAgentActivityChange}
/>
</div>
{operationError ? <p className="text-xs text-destructive">{operationError}</p> : null}
</div>
);
}
function OnboardingToggleRow({
title,
description,
checked,
disabled,
onCheckedChange,
}: {
readonly title: string;
readonly description: string;
readonly checked: boolean;
readonly disabled: boolean;
readonly onCheckedChange: (enabled: boolean) => void;
}) {
return (
<div className="flex items-start justify-between gap-4 border-t border-border/60 px-4 py-3 first:border-t-0">
<div className="min-w-0">
<p className="text-sm font-medium">{title}</p>
<p className="mt-1 text-xs text-muted-foreground">{description}</p>
</div>
<Switch
aria-label={title}
checked={checked}
disabled={disabled}
onCheckedChange={onCheckedChange}
/>
</div>
);
}
function DevicesStep() {
const { environments } = useEnvironments();
const primaryEnvironment = usePrimaryEnvironment();
const savedEnvironmentIds = useMemo(
() =>
environments
.filter((environment) => environment.entry.target._tag !== "PrimaryConnectionTarget")
.map((environment) => environment.environmentId),
[environments],
);
return (
<div className="overflow-hidden rounded-lg border">
<CloudEnvironmentConnectRows
primaryEnvironmentId={primaryEnvironment?.environmentId ?? null}
savedEnvironmentIds={savedEnvironmentIds}
showSavedAsConnected
empty={
<p className="px-4 py-6 text-center text-sm text-muted-foreground">
No other environments are published to your account yet. Publish one from another device
and it will show up here.
</p>
}
/>
</div>
);
}
@@ -7,8 +7,7 @@ import {
TerminalIcon,
TriangleAlertIcon,
} from "lucide-react";
import { useAuth } from "@clerk/react";
import { type ReactNode, memo, useCallback, useEffect, useMemo, useState } from "react";
import { type ReactNode, memo, useCallback, useMemo, useState } from "react";
import {
AuthAccessReadScope,
AuthAccessWriteScope,
@@ -30,18 +29,11 @@ import {
type DesktopWslState,
type EnvironmentId,
} from "@t3tools/contracts";
import {
connectionStatusText,
RelayConnectionRegistration,
RelayConnectionTarget,
} from "@t3tools/client-runtime/connection";
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import { connectionStatusText } from "@t3tools/client-runtime/connection";
import {
isAtomCommandInterrupted,
settlePromise,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
import * as DateTime from "effect/DateTime";
import * as Option from "effect/Option";
@@ -50,7 +42,6 @@ import { cn } from "../../lib/utils";
import { formatElapsedDurationLabel, formatExpiresInLabel } from "../../timestampFormat";
import { resolveDesktopPairingUrl, resolveHostedPairingUrl } from "./pairingUrls";
import { applyWslEnableSelection } from "./ConnectionsSettings.logic";
import { resolveRelayClerkTokenOptions } from "../../cloud/publicConfig";
import {
SettingsPageContainer,
SettingsRow,
@@ -82,7 +73,6 @@ import {
} from "../ui/alert-dialog";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import { QRCodeSvg } from "../ui/qr-code";
import { Skeleton } from "../ui/skeleton";
import { Spinner } from "../ui/spinner";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { Switch } from "../ui/switch";
@@ -117,13 +107,8 @@ import {
import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
import { useUiStateStore } from "~/uiStateStore";
import { resolveServerConfigVersionMismatch } from "~/versionSkew";
import { usePrimaryCloudLinkState } from "~/cloud/primaryCloudLinkState";
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
import {
linkPrimaryEnvironment as linkPrimaryEnvironmentAtom,
unlinkPrimaryEnvironment as unlinkPrimaryEnvironmentAtom,
updatePrimaryEnvironmentPreferences as updatePrimaryEnvironmentPreferencesAtom,
} from "~/cloud/linkEnvironmentAtoms";
import { useCloudLinkController } from "~/cloud/useCloudLinkController";
import { authEnvironment } from "~/state/auth";
import { environmentCatalog } from "~/connection/catalog";
import {
@@ -141,10 +126,11 @@ import {
type EnvironmentPresentation,
useEnvironments,
usePrimaryEnvironment,
useRelayEnvironmentDiscovery,
} from "~/state/environments";
import { relayEnvironmentDiscovery } from "~/state/relay";
import { useAtomCommand } from "../../state/use-atom-command";
import { ConnectionStatusDot } from "../ConnectionStatusDot";
import { CloudEnvironmentConnectRows } from "../cloud/CloudEnvironmentConnectList";
import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
const DEFAULT_TAILSCALE_SERVE_PORT = 443;
const EMPTY_ADVERTISED_ENDPOINTS: ReadonlyArray<AdvertisedEndpoint> = [];
@@ -260,60 +246,6 @@ function AccessScopeSummary({
);
}
type ConnectionStatusDotProps = {
tooltipText?: string | null;
dotClassName: string;
pingClassName?: string | null;
};
function ConnectionStatusDot({
tooltipText,
dotClassName,
pingClassName,
}: ConnectionStatusDotProps) {
const dotContent = (
<>
{pingClassName ? (
<span
className={cn(
"absolute inline-flex h-full w-full animate-ping rounded-full",
pingClassName,
)}
/>
) : null}
<span className={cn("relative inline-flex size-2 rounded-full", dotClassName)} />
</>
);
if (!tooltipText) {
return (
<span className="relative flex size-3 shrink-0 items-center justify-center">
{dotContent}
</span>
);
}
const dot = (
<button
type="button"
title={tooltipText}
aria-label={tooltipText}
className="relative flex size-3 shrink-0 cursor-help items-center justify-center rounded-full outline-hidden"
>
{dotContent}
</button>
);
return (
<Tooltip>
<TooltipTrigger render={dot} />
<TooltipPopup side="top" className="max-w-80 whitespace-pre-wrap leading-tight">
{tooltipText}
</TooltipPopup>
</Tooltip>
);
}
function formatDesktopSshTarget(target: DesktopSshEnvironmentTarget): string {
const authority = target.username ? `${target.username}@${target.hostname}` : target.hostname;
return target.port ? `${authority}:${target.port}` : authority;
@@ -437,13 +369,8 @@ function formatDesktopSshConnectionError(error: unknown): string {
return withoutTaggedErrorPrefix.trim() || fallback;
}
/** Direct row in the card – same pattern as the Provider / ACP-agent list rows. */
const ITEM_ROW_CLASSNAME = "border-t border-border/60 px-4 py-4 first:border-t-0 sm:px-5";
const ENDPOINT_ROW_CLASSNAME = "border-t border-border/60 px-4 py-2.5 first:border-t-0 sm:px-5";
const ITEM_ROW_INNER_CLASSNAME =
"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between";
type AccessSectionPresentation = "current" | "endpoint-rail";
function accessRowClassName(_presentation: AccessSectionPresentation) {
@@ -1629,51 +1556,17 @@ function CloudLinkSwitch({
}
function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: boolean }) {
const { getToken, isSignedIn } = useAuth();
const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
reportFailure: false,
});
const linkPrimaryEnvironment = useAtomCommand(linkPrimaryEnvironmentAtom, {
reportFailure: false,
});
const unlinkPrimaryEnvironment = useAtomCommand(unlinkPrimaryEnvironmentAtom, {
reportFailure: false,
});
const updatePrimaryEnvironmentPreferences = useAtomCommand(
updatePrimaryEnvironmentPreferencesAtom,
{ reportFailure: false },
);
const primaryCloudLinkState = usePrimaryCloudLinkState();
const [operationError, setOperationError] = useState<string | null>(null);
const {
isSignedIn,
linkState: primaryCloudLinkState,
managedTunnelActive,
publishAgentActivity,
operationError,
reconcileCloudState,
} = useCloudLinkController();
const [isUpdating, setIsUpdating] = useState(false);
const [isUpdatingPreference, setIsUpdatingPreference] = useState(false);
const reportUpdateFailure = (cause: unknown) => {
const message = cause instanceof Error ? cause.message : "Could not update T3 Connect access.";
const traceId = findErrorTraceId(cause);
console.error("[t3-connect] Could not update T3 Connect", { message, traceId, cause });
setOperationError(traceId ? `${message} Trace ID: ${traceId}` : message);
toastManager.add({
type: "error",
title: "Could not update T3 Connect",
description: message,
data: traceId
? {
secondaryActionProps: {
children: "Copy trace ID",
onClick: () => void navigator.clipboard?.writeText(traceId),
},
}
: undefined,
});
};
// Older environment servers predate the managedTunnelActive field; for them a
// link always implies a managed tunnel, so fall back to `linked`.
const managedTunnelActive =
primaryCloudLinkState.data?.managedTunnelActive ?? primaryCloudLinkState.data?.linked ?? false;
const publishAgentActivity = primaryCloudLinkState.data?.publishAgentActivity ?? false;
const linked = primaryCloudLinkState.data?.linked ?? false;
const disabledReason = !isSignedIn
? "Sign in to T3 Connect to manage this environment."
: !canManageRelay
@@ -1681,86 +1574,6 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
: null;
const isBusy = isUpdating || isUpdatingPreference;
// T3 Connect (managed tunnel) and publishing are independent capabilities
// backed by a single relay link. Reconcile the whole desired state: unlink
// when neither is wanted, otherwise (re)link with the mode the managed-tunnel
// bit implies and set the publish preference. Re-linking only happens when the
// managed-tunnel mode actually changes, so flipping publish alone is cheap.
const reconcileCloudState = async (desired: {
readonly managedTunnel: boolean;
readonly publish: boolean;
}): Promise<boolean> => {
setOperationError(null);
const target = primaryCloudLinkState.target;
if (!target) {
reportUpdateFailure(new Error("Local environment is not ready yet."));
return false;
}
const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));
if (tokenResult._tag === "Failure") {
reportUpdateFailure(squashAtomCommandFailure(tokenResult));
return false;
}
const clerkToken = tokenResult.value;
const wantsLink = desired.managedTunnel || desired.publish;
// A failure after this point may follow a partially applied mutation (e.g.
// the link succeeded but the preference update did not), so every exit —
// success or failure — refreshes the rendered state to whatever the server
// actually holds now.
if (!wantsLink) {
const unlinkResult = await unlinkPrimaryEnvironment({
target,
clerkToken: clerkToken ?? null,
});
if (unlinkResult._tag === "Failure") {
if (!isAtomCommandInterrupted(unlinkResult)) {
reportUpdateFailure(squashAtomCommandFailure(unlinkResult));
}
primaryCloudLinkState.refresh();
return false;
}
} else {
if (!clerkToken) {
reportUpdateFailure(new Error("Sign in to T3 Connect before enabling this."));
return false;
}
if (!linked || managedTunnelActive !== desired.managedTunnel) {
const linkResult = await linkPrimaryEnvironment({
target,
clerkToken,
mode: desired.managedTunnel ? "managed" : "publish_only",
});
if (linkResult._tag === "Failure") {
if (!isAtomCommandInterrupted(linkResult)) {
reportUpdateFailure(squashAtomCommandFailure(linkResult));
}
primaryCloudLinkState.refresh();
return false;
}
}
const prefResult = await updatePrimaryEnvironmentPreferences({
target,
publishAgentActivity: desired.publish,
});
if (prefResult._tag === "Failure") {
if (!isAtomCommandInterrupted(prefResult)) {
reportUpdateFailure(squashAtomCommandFailure(prefResult));
}
primaryCloudLinkState.refresh();
return false;
}
}
primaryCloudLinkState.refresh();
const refreshResult = await refreshRelayEnvironments();
if (refreshResult._tag === "Failure" && !isAtomCommandInterrupted(refreshResult)) {
reportUpdateFailure(squashAtomCommandFailure(refreshResult));
return false;
}
return true;
};
const updateManagedTunnel = async (enabled: boolean) => {
setIsUpdating(true);
const ok = await reconcileCloudState({ managedTunnel: enabled, publish: publishAgentActivity });
@@ -1857,163 +1670,6 @@ function EmptyRemoteEnvironments({ cloudEnabled = true }: { readonly cloudEnable
);
}
function RemoteEnvironmentRowsSkeleton() {
return (
<div className={ITEM_ROW_CLASSNAME}>
<div className={ITEM_ROW_INNER_CLASSNAME}>
<div className="min-w-0 flex-1 space-y-2">
<Skeleton className="h-4 w-32 rounded-full" />
<Skeleton className="h-3 w-20 rounded-full" />
</div>
<Skeleton className="h-7 w-16 rounded-md" />
</div>
</div>
);
}
function ConfiguredCloudRemoteEnvironmentRows({
primaryEnvironmentId,
savedEnvironmentIds,
}: {
readonly primaryEnvironmentId: EnvironmentId | null;
readonly savedEnvironmentIds: ReadonlyArray<EnvironmentId>;
}) {
const environmentsState = useRelayEnvironmentDiscovery();
const registerEnvironment = useAtomCommand(environmentCatalog.register, {
reportFailure: false,
});
const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
reportFailure: false,
});
const connectRelayEnvironment = useCallback(
(environment: RelayClientEnvironmentRecord) =>
registerEnvironment(
new RelayConnectionRegistration({
target: new RelayConnectionTarget({
environmentId: environment.environmentId,
label: environment.label,
}),
}),
),
[registerEnvironment],
);
const [connectingEnvironmentId, setConnectingEnvironmentId] = useState<EnvironmentId | null>(
null,
);
const savedIds = useMemo(() => new Set(savedEnvironmentIds), [savedEnvironmentIds]);
useEffect(() => {
void refreshRelayEnvironments();
}, [refreshRelayEnvironments]);
const connectEnvironment = async (environment: RelayClientEnvironmentRecord) => {
setConnectingEnvironmentId(environment.environmentId);
const result = await connectRelayEnvironment(environment);
setConnectingEnvironmentId(null);
if (result._tag === "Success") {
toastManager.add({
type: "success",
title: "Environment connected",
description: `${environment.label} is available through T3 Connect.`,
});
return;
}
if (isAtomCommandInterrupted(result)) {
return;
}
const cause = squashAtomCommandFailure(result);
const message =
cause instanceof Error ? cause.message : "Could not connect the T3 Connect environment.";
const traceId = findErrorTraceId(cause);
console.error("[t3-connect] Could not connect environment", { message, traceId, cause });
toastManager.add({
type: "error",
title: "Could not connect environment",
description: message,
data: traceId
? {
secondaryActionProps: {
children: "Copy trace ID",
onClick: () => void navigator.clipboard?.writeText(traceId),
},
}
: undefined,
});
};
const connectableEnvironments = [...environmentsState.environments.values()].filter(
({ environment }) =>
environment.environmentId !== primaryEnvironmentId &&
!savedIds.has(environment.environmentId),
);
if (
savedEnvironmentIds.length === 0 &&
environmentsState.refreshing &&
environmentsState.environments.size === 0
) {
return <RemoteEnvironmentRowsSkeleton />;
}
if (savedEnvironmentIds.length === 0 && connectableEnvironments.length === 0) {
return <EmptyRemoteEnvironments />;
}
return connectableEnvironments.map(({ environment, availability, error }) => (
<div key={environment.environmentId} className={ITEM_ROW_CLASSNAME}>
<div className={ITEM_ROW_INNER_CLASSNAME}>
<div className="min-w-0">
<div className="flex items-center gap-2">
<ConnectionStatusDot
dotClassName={
availability === "online"
? "bg-success"
: availability === "error"
? "bg-destructive"
: availability === "checking"
? "bg-warning"
: "bg-muted-foreground/35"
}
pingClassName={availability === "checking" ? "bg-warning/60 duration-2000" : null}
tooltipText={
availability === "online"
? "Relay online"
: availability === "offline"
? "Relay offline"
: availability === "checking"
? "Checking relay status"
: (Option.getOrNull(error)?.message ?? "Relay status unavailable")
}
/>
<p className="truncate text-sm font-medium">{environment.label}</p>
</div>
<p
className={cn(
"mt-1 truncate text-xs",
availability === "error" ? "text-destructive" : "text-muted-foreground",
)}
>
{availability === "online"
? "Available · Relay online"
: availability === "offline"
? "Available · Relay offline"
: availability === "checking"
? "Available · Checking relay status…"
: (Option.getOrNull(error)?.message ?? "Available · Relay status unavailable")}
</p>
</div>
<Button
size="sm"
disabled={connectingEnvironmentId !== null}
onClick={() => void connectEnvironment(environment)}
>
{connectingEnvironmentId === environment.environmentId ? "Connecting…" : "Connect"}
</Button>
</div>
</div>
));
}
function CloudRemoteEnvironmentRows({
primaryEnvironmentId,
savedEnvironmentIds,
@@ -2022,9 +1678,10 @@ function CloudRemoteEnvironmentRows({
readonly savedEnvironmentIds: ReadonlyArray<EnvironmentId>;
}) {
return hasCloudPublicConfig() ? (
<ConfiguredCloudRemoteEnvironmentRows
<CloudEnvironmentConnectRows
primaryEnvironmentId={primaryEnvironmentId}
savedEnvironmentIds={savedEnvironmentIds}
empty={<EmptyRemoteEnvironments />}
/>
) : savedEnvironmentIds.length === 0 ? (
<EmptyRemoteEnvironments cloudEnabled={false} />
@@ -0,0 +1,5 @@
/** Direct row in the card – same pattern as the Provider / ACP-agent list rows. */
export const ITEM_ROW_CLASSNAME = "border-t border-border/60 px-4 py-4 first:border-t-0 sm:px-5";
export const ITEM_ROW_INNER_CLASSNAME =
"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between";
+2
View File
@@ -14,6 +14,7 @@ import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "../branding";
import { resolveServerBackedAppDisplayName } from "../branding.logic";
import { AppSidebarLayout } from "../components/AppSidebarLayout";
import { CommandPalette } from "../components/CommandPalette";
import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog";
import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog";
import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";
import { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";
@@ -128,6 +129,7 @@ function RootRouteView() {
<DocumentTitleSync />
{primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
<RelayClientInstallDialog />
<ConnectOnboardingDialog />
<SshPasswordPromptDialog />
<SlowRpcRequestToastCoordinator />
<HostedStaticEnvironmentBootstrap />