Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge bd8657af44 Avoid provider pill transition bookkeeping renders
Co-authored-by: Julius Marminge <[email protected]>
2026-07-08 16:16:12 +00:00
Cursor AgentandJulius Marminge f34cfbb7c4 Optimize provider update pill renders
Co-authored-by: Julius Marminge <[email protected]>
2026-07-08 16:15:10 +00:00
Rowan 0c66565854 fix(release): bump electron-builder so pnpm 11 deduped deps land in the asar (#3790) 2026-07-08 04:38:45 -07:00
Julius Marminge e775bc6228 Upgrade Clerk toolchain to latest versions (#3785) 2026-07-08 04:30:07 -07:00
Julius MarmingeandCursor Agent 03ac1f0cd9 fix(release): stage pnpm 11 allowBuilds for desktop installs (#3781)
Co-authored-by: Cursor Agent <[email protected]>
2026-07-07 15:55:18 -07:00
Julius MarmingeandCursor Agent 7778a1cea7 Use rounded depth logo for production splash screen (#3780)
Co-authored-by: Cursor Agent <[email protected]>
2026-07-07 22:49:50 +00:00
Julius MarmingeandClaude Fable 5 dad0889766 Revert "Revert "Add T3 Connect onboarding for mobile and web"" (#3777)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-07 14:17:18 -07:00
b9cc8d6ef1 Set up Cursor Cloud dev environment (web + Android toolchain) (#3755)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Theo Browne <[email protected]>
2026-07-07 13:18:58 -07:00
Julius MarmingeandClaude Fable 5 0e0040832c Expose Clerk Google sign-in env vars to Expo (#3772)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-07 12:45:40 -07:00
Julius Marminge cd8b9fc8b3 Revert "Add T3 Connect onboarding for mobile and web" (#3776) 2026-07-07 12:40:12 -07:00
Julius Marminge fa6073e2e1 Add T3 Connect onboarding for mobile and web (#3765) 2026-07-07 12:39:56 -07:00
Julius Marminge 4eb1b57933 Lead with the outcome when no agents are active in the Live Activity (#3768) 2026-07-07 09:12:52 -07:00
41 changed files with 2668 additions and 1468 deletions

No files matched your search

+72
View File
@@ -0,0 +1,72 @@
---
description: Cursor Cloud environment setup and run notes for T3 Code (Cursor-specific; not for other editors/CI)
alwaysApply: true
---
# Cursor Cloud specific instructions
These notes apply only to Cursor Cloud agents (kept out of the shared `AGENTS.md` since T3 Code is
developed in many places). They cover the pre-provisioned VM environment and non-obvious run caveats.
## Toolchain
Pre-installed and wired into login shells (`~/.bashrc`/`~/.profile`): Node 24 (via nvm), the global
`vp` (Vite+) CLI, and its bundled pnpm. `vp` is the package manager + task runner for this repo
(`vp i`, `vp check`, `vp run typecheck`, `vp test`, `vp run --filter <pkg> <script>`).
- Node gotcha: the base image also ships an older Node on `/exec-daemon` that wins on `PATH` in
non-login shells. Run commands in a login shell (`bash -lc '...'`) or prepend
`$HOME/.nvm/versions/node/v24.13.1/bin` so Node 24 (`engines.node: ^24.13.1`) is used.
- `vp check` also runs the formatter (not just lint); markdown edits must be formatter-clean. Run
`vp check --fix` before committing.
## Running the web app
- `npm run dev` (from repo root) starts contracts (watch), web (Vite, port 5733), and the server
(`node --watch`, port 13773) together, auto-wiring `VITE_HTTP_URL`/`VITE_WS_URL`. Use
`npm run dev:server` / `npm run dev:web` for one side. If base ports are taken it auto-offsets to
the next free pair, so read the actual ports from stdout. Avoid production `build`/`start` in dev.
- Auth/pairing: the server is unauthenticated by default and prints a pairing URL to stdout on startup
(e.g. `http://localhost:5733/pair#token=XXXX`). Open that URL in the browser to pair before the web
UI can talk to the server. Server state (SQLite, auth, projects) lives under `~/.t3`
(`T3CODE_HOME`); multiple `npm run dev` instances bind different ports but share that same DB.
- Agent providers are external CLIs (`codex`, `claude`, `cursor-agent`, `opencode`) probed on `PATH`.
Without one installed the UI loads but no agent can run. Claude Code
(`npm i -g @anthropic-ai/claude-code`) works headlessly using `ANTHROPIC_API_KEY` from the
environment (the server forwards `process.env` to the child; no interactive `claude auth login`
needed). Provider probing runs at startup and refreshes roughly every 5 minutes — restart the dev
server to pick up a newly installed provider CLI immediately.
## Android native builds (apps/mobile)
The Android toolchain is pre-installed and wired into login shells: OpenJDK 17
(`JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64`; the base image's default `java` is 21, so builds must
use `JAVA_HOME`), and the Android SDK at `$HOME/Android/Sdk` (`ANDROID_HOME`/`ANDROID_SDK_ROOT`) with
platform-tools, `platforms;android-36`, `build-tools;36.0.0`, `ndk;27.1.12297006`, and `cmake;3.22.1`.
Gradle auto-downloads any additional pinned SDK packages on demand.
- Generate the native project first: from `apps/mobile`,
`EXPO_NO_GIT_STATUS=1 APP_VARIANT=development npx expo prebuild --clean --platform android`
(the `android/` folder is generated, not committed). RN 0.85 defaults: compileSdk/targetSdk 36,
minSdk 24, NDK `27.1.12297006` (see `react-native/gradle/libs.versions.toml`).
- Build with Gradle from `apps/mobile/android`, e.g. `./gradlew :app:assembleDebug`. First build is
slow (Kotlin + C++/NDK codegen). Limit ABIs to speed things up, e.g.
`-PreactNativeArchitectures=arm64-v8a`. Verified working end-to-end on a native module:
`./gradlew :react-native-worklets:assembleDebug` compiles Kotlin + C++ and emits an AAR + `.so`s.
- No emulator: this VM has no `/dev/kvm` (nested virtualization), so a hardware-accelerated Android
emulator will not run. Use a physical device (`adb`) or EAS cloud builds (`vp run eas:android:*`) to
actually run the app. The full IDE GUI is unnecessary here — the SDK/NDK/Gradle toolchain that
Android Studio bundles is what is installed.
- Known blocker for the full-app `:app:assembleDebug` (pre-existing, app-level — not the environment):
`:react-native-screens:compileDebugKotlin` fails because `patches/[email protected]`
adds new codegen props (`subtitle`, `largeSubtitle`, `navigationItemStyle`,
`headerCenterBarButtonItems`, `headerToolbarItems`) to the JS spec + iOS native code but includes no
Android Kotlin setters, so the generated `ScreenStackHeaderConfigManagerInterface` is unimplemented.
The mobile README documents only iOS for local builds and routes Android through EAS. Fixing local
Android app builds requires an app/patch change (add the Android Kotlin setters), which is out of
scope for environment setup.
## Known flaky tests (unrelated to setup)
- `apps/server/src/git/GitManager.test.ts` (cross-repo PR metadata, can time out at 12s).
- `apps/server/src/provider/Layers/ProviderRegistry.test.ts` (codex binaryPath re-probe ordering).
+4 -1
View File
@@ -57,7 +57,10 @@ jobs:
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
packager: pnpm
# npm, not pnpm: this only installs eas-cli into the action's own
# tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
# ignored build script (no allowBuilds config outside the repo).
packager: npm
- name: Pull preview environment variables
if: steps.expo-token.outputs.present == 'true'
+4 -1
View File
@@ -80,7 +80,10 @@ jobs:
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
packager: pnpm
# npm, not pnpm: this only installs eas-cli into the action's own
# tool dir, and pnpm 11 hard-fails that install on dtrace-provider's
# ignored build script (no allowBuilds config outside the repo).
packager: npm
- name: Pull production environment variables
if: steps.expo-token.outputs.present == 'true'
+1 -1
View File
@@ -31,7 +31,7 @@
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"cross-env": "^10.1.0",
"electron-builder": "26.8.1",
"electron-builder": "26.15.6",
"tailwindcss": "^4.0.0",
"vite-plus": "catalog:"
},
+9
View File
@@ -196,6 +196,15 @@ const config: ExpoConfig = {
publishableKey: repoEnv.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null,
jwtTemplate: repoEnv.EXPO_PUBLIC_CLERK_JWT_TEMPLATE ?? null,
},
// Native Google sign-in credentials. @clerk/expo reads these from `extra`
// under their exact env-var names (not nested), and its config plugin reads
// the iOS URL scheme at prebuild to register it in Info.plist.
// Unset values must be omitted (not null): the public manifest serializes
// null to {}, which is truthy and would defeat Clerk's fallback checks.
EXPO_PUBLIC_CLERK_GOOGLE_WEB_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_WEB_CLIENT_ID,
EXPO_PUBLIC_CLERK_GOOGLE_IOS_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_IOS_CLIENT_ID,
EXPO_PUBLIC_CLERK_GOOGLE_ANDROID_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_ANDROID_CLIENT_ID,
EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME,
observability: {
tracesUrl: repoEnv.EXPO_PUBLIC_OTLP_TRACES_URL ?? "https://api.axiom.co/v1/traces",
tracesDataset: repoEnv.EXPO_PUBLIC_OTLP_TRACES_DATASET ?? null,
Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 302 KiB

+19
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/connectOnboardingNavigation";
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,20 @@ export const RootStack = createNativeStackNavigator({
sheetGrabberVisible: true,
},
}),
ConnectOnboarding: createNativeStackScreen({
screen: ConnectOnboardingRouteScreen,
linking: "connect-onboarding",
options: {
// Root screenOptions hide headers; formSheets that want the native
// title bar opt back in with the sheet header preset.
...SHEET_SOLID_HEADER_OPTIONS,
title: "Set up T3 Connect",
gestureEnabled: true,
presentation: "formSheet",
sheetAllowedDetents: [0.6, 0.95],
sheetGrabberVisible: true,
},
}),
Connections: createNativeStackScreen({
screen: ConnectionsRouteScreen,
linking: "connections",
+2 -2
View File
@@ -92,7 +92,7 @@ const capabilitiesLayer = Layer.succeedContext(
if (session === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "Sign in to T3 Cloud to connect this environment.",
detail: "Sign in to T3 Connect to connect this environment.",
});
}
const token = yield* session.readClerkToken().pipe(
@@ -107,7 +107,7 @@ const capabilitiesLayer = Layer.succeedContext(
if (token === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "The T3 Cloud session is unavailable.",
detail: "The T3 Connect session is unavailable.",
});
}
return token;
@@ -18,6 +18,7 @@ import {
setAgentAwarenessRelayTokenProvider,
unregisterAgentAwarenessDeviceForCurrentUser,
} from "../agent-awareness/remoteRegistration";
import { clearConnectOnboardingRequest, requestConnectOnboarding } from "./connectOnboarding";
import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig";
function resetManagedRelayTokenCache() {
@@ -67,6 +68,19 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
const nextAccount = isSignedIn && userId ? userId : null;
observedAccountRef.current = nextAccount;
// Every sign-in or account switch that completes during this session (a
// cold start observes undefined → account and must not re-prompt) requests
// the T3 Connect onboarding sheet — account transitions clear the
// connected environments, so each new session starts with no devices to
// reach. The request itself is issued after the cleanup transition inside
// activateSession, so the sheet never lists the previous account's
// environments; sign-out drops any not-yet-presented request instead.
const isAccountTransition =
previousObservedAccount !== undefined && previousObservedAccount !== nextAccount;
if (isAccountTransition && nextAccount === null) {
clearConnectOnboardingRequest();
}
const queueAccountCleanup = (
previous: {
readonly userId: string;
@@ -114,6 +128,9 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
}
previousTokenProviderRef.current = { userId, provider: tokenProvider };
activateCloudRelayAccount(userId, tokenProvider);
if (isAccountTransition) {
requestConnectOnboarding(userId);
}
};
const activateAfterTransition = (transition: Promise<void>) => {
void (async () => {
@@ -39,7 +39,7 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
You are on the waitlist
</Text>
<Text className="text-center font-sans text-base text-foreground-secondary">
We will email you when your T3 Cloud access is ready.
We will email you when your T3 Connect access is ready.
</Text>
<SignInAction onPress={props.onSignIn} />
</View>
@@ -0,0 +1,129 @@
import { NativeHeaderToolbar } from "../../native/StackHeader";
import { useAuth } from "@clerk/expo";
import { StackActions, useNavigation } from "@react-navigation/native";
import { useCallback, useEffect, useState } from "react";
import { Pressable, RefreshControl, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { reportAtomCommandResult, settlePromise } from "@t3tools/client-runtime/state/runtime";
import { AppText as Text } from "../../components/AppText";
import { useRemoteConnections } from "../../state/use-remote-environment-registry";
import { CloudEnvironmentRows } from "../connection/CloudEnvironmentRows";
import { splitEnvironmentSections } from "../connection/environmentSections";
import { useConnectionController } from "../connection/useConnectionController";
import { optOutOfConnectOnboarding } from "./connectOnboardingOptOut";
import { hasCloudPublicConfig } from "./publicConfig";
/**
* Post-sign-in onboarding sheet for T3 Connect. Mobile never publishes
* environments itself — it consumes ones published elsewhere — so this simply
* surfaces the account's T3 Connect environments right after sign-in so every
* device can be connected in one go. It shows on every sign-in: sign-out
* clears the connected environments, so each new session starts from zero.
*/
export function ConnectOnboardingRouteScreen() {
const navigation = useNavigation();
// The route is deep-linkable; without cloud config the sheet would present
// empty with no chrome to dismiss it, so bail back out instead.
useEffect(() => {
if (hasCloudPublicConfig()) {
return;
}
if (navigation.canGoBack()) {
navigation.goBack();
} else {
navigation.dispatch(StackActions.replace("Home"));
}
}, [navigation]);
return hasCloudPublicConfig() ? <ConfiguredConnectOnboardingRouteScreen /> : null;
}
function ConfiguredConnectOnboardingRouteScreen() {
const navigation = useNavigation();
const insets = useSafeAreaInsets();
const { isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
const { connectedEnvironments, onReconnectEnvironment } = useRemoteConnections();
const { refreshRelayEnvironments } = useConnectionController();
const { connectedCloudEnvironments } = splitEnvironmentSections({
connectedEnvironments,
cloudEnvironments: null,
});
// Pull-to-refresh tracks its own spinner instead of discovery's refreshing
// flag, so background refreshes (e.g. the sign-in one) don't yank the
// content down.
const [isPullRefreshing, setIsPullRefreshing] = useState(false);
const handlePullRefresh = useCallback(() => {
void (async () => {
setIsPullRefreshing(true);
await refreshRelayEnvironments();
setIsPullRefreshing(false);
})();
}, [refreshRelayEnvironments]);
const handleClose = useCallback(() => {
navigation.goBack();
}, [navigation]);
// Persist before dismissing so a quick sign-out/sign-in cannot race ahead
// of the preference write; the write is a local secure-store update.
const handleDontShowAgain = useCallback(() => {
void (async () => {
if (userId) {
const result = await settlePromise(() => optOutOfConnectOnboarding(userId));
reportAtomCommandResult(result, { label: "connect onboarding opt-out" });
}
navigation.goBack();
})();
}, [navigation, userId]);
return (
<View collapsable={false} className="flex-1 bg-sheet">
<NativeHeaderToolbar placement="right">
<NativeHeaderToolbar.Button icon="xmark" onPress={handleClose} separateBackground />
</NativeHeaderToolbar>
<ScrollView
alwaysBounceVertical
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
style={{ flex: 1 }}
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
gap: 16,
paddingHorizontal: 20,
paddingTop: 16,
}}
refreshControl={
<RefreshControl refreshing={isPullRefreshing} onRefresh={handlePullRefresh} />
}
>
{isSignedIn ? (
<CloudEnvironmentRows
connectedCloudEnvironments={connectedCloudEnvironments}
onReconnectEnvironment={onReconnectEnvironment}
showHeader={false}
/>
) : (
<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>
)}
{userId ? (
<Pressable
accessibilityRole="button"
hitSlop={8}
onPress={handleDontShowAgain}
className="items-center py-1 active:opacity-70"
>
<Text className="text-xs text-foreground-muted">{"Don't show this again"}</Text>
</Pressable>
) : null}
</ScrollView>
</View>
);
}
@@ -0,0 +1,24 @@
import { Atom } from "effect/unstable/reactivity";
import { appAtomRegistry } from "../../state/atom-registry";
// Signals RootStackLayout (inside the navigation tree) that an in-session
// sign-in just completed. Holds the account id so a sign-out between the
// request and the navigation cannot present the sheet for the wrong account.
export const connectOnboardingRequestAtom = Atom.make<string | null>(null).pipe(
Atom.keepAlive,
Atom.withLabel("mobile:connect-onboarding-request"),
);
/**
* Requests the onboarding sheet for the given account. Sign-out clears the
* connected environments, so onboarding runs on every in-session sign-in —
* each new session starts with no connected devices.
*/
export function requestConnectOnboarding(accountId: string): void {
appAtomRegistry.set(connectOnboardingRequestAtom, accountId);
}
export function clearConnectOnboardingRequest(): void {
appAtomRegistry.set(connectOnboardingRequestAtom, null);
}
@@ -0,0 +1,49 @@
import { useAtomValue } from "@effect/atom-react";
import { useNavigation } from "@react-navigation/native";
import { useEffect } from "react";
import { appAtomRegistry } from "../../state/atom-registry";
import { clearConnectOnboardingRequest, connectOnboardingRequestAtom } from "./connectOnboarding";
import { isConnectOnboardingOptedOut } from "./connectOnboardingOptOut";
// 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. Lives apart from connectOnboarding.ts
* so non-navigation consumers (CloudAuthProvider) do not pull
* @react-navigation into their module graph.
*/
export function useConnectOnboardingNavigation(): void {
const navigation = useNavigation();
const requestedAccountId = useAtomValue(connectOnboardingRequestAtom);
useEffect(() => {
if (requestedAccountId === null) {
return;
}
let cancelled = false;
const timer = setTimeout(() => {
void (async () => {
// A failed preference read prefers showing the sheet.
const optedOut = await isConnectOnboardingOptedOut(requestedAccountId).catch(() => false);
// The cancelled flag covers effect re-runs, but a sign-out can clear
// the request atom moments before this render commits — re-check the
// atom so a stale request never presents the sheet.
if (cancelled || appAtomRegistry.get(connectOnboardingRequestAtom) !== requestedAccountId) {
return;
}
clearConnectOnboardingRequest();
if (!optedOut) {
navigation.navigate("ConnectOnboarding");
}
})();
}, PRESENT_ONBOARDING_DELAY_MS);
return () => {
cancelled = true;
clearTimeout(timer);
};
}, [navigation, requestedAccountId]);
}
@@ -0,0 +1,21 @@
import { loadPreferences, updatePreferences } from "../../lib/storage";
// Lives apart from connectOnboarding.ts so CloudAuthProvider (which imports
// the request signal) never pulls lib/storage — expo-secure-store — into its
// module graph; that breaks CloudAuthProvider.test.ts suite loading.
/** Whether the account chose "Don't show this again". */
export async function isConnectOnboardingOptedOut(accountId: string): Promise<boolean> {
const preferences = await loadPreferences();
return preferences.connectOnboardingOptOutAccounts?.includes(accountId) ?? false;
}
/** Persists "Don't show this again" for the account. */
export async function optOutOfConnectOnboarding(accountId: string): Promise<void> {
await updatePreferences((current) => {
const optedOut = current.connectOnboardingOptOutAccounts ?? [];
return optedOut.includes(accountId)
? {}
: { connectOnboardingOptOutAccounts: [...optedOut, accountId] };
});
}
@@ -0,0 +1,379 @@
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 Connect" 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;
/**
* Hide the "T3 Connect" section title + refresh button for hosts that
* provide their own chrome (the onboarding sheet's native header and
* pull-to-refresh).
*/
readonly showHeader?: boolean;
}) {
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));
}, []);
const showHeader = props.showHeader ?? true;
if (!isSignedIn) return null;
return (
<View collapsable={false} className={cn("gap-3", showHeader && "mt-5")}>
{showHeader ? (
<View className="flex-row items-center justify-between px-1">
<Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Connect</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>
) : null}
{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 ? null : (
<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>
)}
{/* Rendered alongside any connected rows — a failed discovery must not
hide behind an otherwise-healthy list. */}
{controller.relayDiscovery.error && !controller.relayDiscovery.isRefreshing ? (
<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 Connect environments
</Text>
<Text className="text-sm text-foreground-muted">{controller.relayDiscovery.error}</Text>
{controller.relayDiscovery.errorTraceId ? (
<CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />
) : null}
<Pressable
accessibilityRole="button"
onPress={() => {
void controller.refreshRelayEnvironments();
}}
className="self-start rounded-full bg-subtle px-3.5 py-2 active:opacity-70"
>
<Text className="text-xs font-t3-bold text-foreground">Try again</Text>
</Pressable>
</View>
) : null}
</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>
);
}
@@ -135,7 +135,7 @@ export function ConnectionEnvironmentRow(props: {
>
{props.environment.isRelayManaged ? (
<Text className="text-sm text-foreground-muted">
Managed by T3 Cloud. Tunnel details update automatically.
Managed by T3 Connect. Tunnel details update automatically.
</Text>
) : (
<>
@@ -35,7 +35,7 @@ function cloudEnvironment(environmentId: string): RelayClientEnvironmentRecord {
}
describe("mobile environment settings sections", () => {
it("keeps saved relay-managed connections under T3 Cloud", () => {
it("keeps saved relay-managed connections under T3 Connect", () => {
const local = connectedEnvironment({
environmentId: "environment-local",
isRelayManaged: false,
@@ -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>
);
}
@@ -240,8 +240,8 @@ function ConfiguredSettingsRouteScreen() {
const promptSignIn = useCallback(() => {
Alert.alert(
"Request T3 Cloud access",
"Live Activity updates require approved T3 Cloud access so relay can deliver updates to this device.",
"Request T3 Connect access",
"Live Activity updates require approved T3 Connect access so relay can deliver updates to this device.",
[
{ text: "Cancel", style: "cancel" },
{
+29 -7
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 opted out of the T3 Connect onboarding sheet. */
readonly connectOnboardingOptOutAccounts?: 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;
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
} = {};
if (typeof parsed.liveActivitiesEnabled === "boolean") {
@@ -187,18 +190,37 @@ export async function loadPreferences(): Promise<Preferences> {
if (typeof parsed.codeWordBreak === "boolean") {
preferences.codeWordBreak = parsed.codeWordBreak;
}
if (Array.isArray(parsed.connectOnboardingOptOutAccounts)) {
preferences.connectOnboardingOptOutAccounts = parsed.connectOnboardingOptOutAccounts.filter(
(account): account is string => typeof account === "string",
);
}
return preferences;
}
// Preference writes are read-modify-write over one JSON blob; concurrent
// writers would drop each other's fields, so all writes are serialized here.
let preferencesWriteQueue: Promise<unknown> = Promise.resolve();
export async function updatePreferences(
update: (current: Preferences) => Partial<Preferences>,
): Promise<Preferences> {
const task = preferencesWriteQueue.then(async () => {
const current = await loadPreferences();
const next: Preferences = {
...current,
...update(current),
};
await writeJsonStorageItem(PREFERENCES_KEY, next);
return next;
});
preferencesWriteQueue = task.catch(() => undefined);
return task;
}
export async function savePreferencesPatch(patch: Partial<Preferences>): Promise<Preferences> {
const current = await loadPreferences();
const next: Preferences = {
...current,
...patch,
};
await writeJsonStorageItem(PREFERENCES_KEY, next);
return next;
return updatePreferences(() => patch);
}
export async function loadOrCreateAgentAwarenessDeviceId(): Promise<string> {
@@ -199,6 +199,70 @@ describe("AgentActivity widget layout", () => {
).not.toContain("widgetURL");
});
it("leads with the outcome instead of a zero count when nothing is active", () => {
const layout = AgentActivity(
{
...props,
subtitle: "Agent work completed",
activeCount: 0,
activities: [makeRow({ phase: "completed", status: "Done" })],
},
environment as never,
);
const banner = JSON.stringify(layout.banner);
expect(banner).toContain("Agent work completed");
expect(banner).not.toContain("0 active");
expect(banner).toContain("#6ee7b7"); // emerald-300 header tint
expect(JSON.stringify(layout.compactTrailing)).toContain("Done");
expect(JSON.stringify(layout.compactTrailing)).not.toContain("0 active");
expect(JSON.stringify(layout.expandedLeading)).toContain("Done");
expect(JSON.stringify(layout.minimal)).toContain("checkmark.circle.fill");
expect(JSON.stringify(layout.bannerSmall)).toContain("Done");
});
it("reads Failed when the finished work ended in failure", () => {
const layout = AgentActivity(
{
...props,
subtitle: "Agent work failed",
activeCount: 0,
activities: [makeRow({ phase: "failed", status: "Failed" })],
},
environment as never,
);
const banner = JSON.stringify(layout.banner);
expect(banner).toContain("Agent work failed");
expect(banner).toContain("#fca5a5"); // red-300 header tint
expect(JSON.stringify(layout.compactTrailing)).toContain("Failed");
expect(JSON.stringify(layout.expandedLeading)).toContain("Failed");
expect(JSON.stringify(layout.minimal)).toContain("xmark.octagon.fill");
});
it("lets a failure dominate mixed finished outcomes across every presentation", () => {
const layout = AgentActivity(
{
...props,
// The server subtitle keys off the newest terminal row (completed
// here); the layout must still read Failed everywhere so the header
// text never disagrees with the tint, count slots, or minimal glyph.
subtitle: "Agent work completed",
activeCount: 0,
activities: [
makeRow({ phase: "completed", status: "Done" }),
makeRow({ threadId: "thread-2", phase: "failed", status: "Failed" }),
],
},
environment as never,
);
const banner = JSON.stringify(layout.banner);
expect(banner).toContain("Agent work failed");
expect(banner).not.toContain("Agent work completed");
expect(banner).toContain("#fca5a5"); // red-300 header tint
expect(JSON.stringify(layout.compactTrailing)).toContain("Failed");
expect(JSON.stringify(layout.expandedLeading)).toContain("Failed");
expect(JSON.stringify(layout.minimal)).toContain("xmark.octagon.fill");
});
it("renders up to five rows in the banner", () => {
const layout = AgentActivity(
{
+21 -8
View File
@@ -123,16 +123,28 @@ export function AgentActivity(
? phaseTint(failedRow.phase)
: tint;
// With nothing active the aggregate only carries recently finished work, so
// "0 active agents" (and a lone "0" in the expanded island) read as broken.
// Lead with the outcome instead. The outcome is derived here from the rows
// rather than taken from the server subtitle (which keys off the newest
// terminal row): every presentation — header text, tint, count slots,
// minimal glyph — must agree, and a failure anywhere should dominate a
// newer success.
const allDone = props.activeCount === 0;
const doneLabel = failedRow ? "Failed" : "Done";
const outcomeLabel = failedRow ? "Agent work failed" : "Agent work completed";
// Header copy: "5 active agents" + (", 1 needs attention"). The banner renders
// the two parts in-line so the attention half can carry the accent color;
// `summary` is the short form for tight spots (expanded center, watch card).
const agentWord = props.activeCount === 1 ? "agent" : "agents";
const agentsLabel = `${props.activeCount} active ${agentWord}`;
const agentsLabel = allDone ? outcomeLabel : `${props.activeCount} active ${agentWord}`;
const attentionSuffix =
attentionRows.length > 0
? `${attentionRows.length} need${attentionRows.length === 1 ? "s" : ""} attention`
: "";
const summary = attentionSuffix || `${props.activeCount} active`;
const activeLabel = allDone ? doneLabel : `${props.activeCount} active`;
const summary = attentionSuffix || activeLabel;
// Any registered scheme variant routes back to this app; taps are delivered
// to the widget's containing app, so the prod scheme is safe for all builds.
@@ -142,8 +154,6 @@ export function AgentActivity(
? `t3code://${deepLinkRow.deepLink.slice(1)}`
: null;
const activeLabel = `${props.activeCount} active`;
// A scannable status glyph per phase — reads faster than colored words and
// ties the compact / expanded / banner / watch presentations together.
type SFName = NonNullable<ComponentProps<typeof Image>["systemName"]>;
@@ -245,7 +255,9 @@ export function AgentActivity(
<Text
modifiers={[
font({ weight: "semibold", size: 13 }),
foregroundStyle(primaryForeground),
// The all-done header carries the outcome tint (emerald /
// red) the way the Done/Failed status labels do.
foregroundStyle(allDone ? headerTint : primaryForeground),
lineLimit(1),
]}
>
@@ -322,16 +334,17 @@ export function AgentActivity(
</Text>
),
// The shared/minimal form is a ~22pt circle — a single signal reads there,
// the wordmark does not. Show the blocking phase glyph, else the mark.
// the wordmark does not. Show the blocking/outcome phase glyph, else the
// mark (all-done shows the hero row's checkmark/cross).
minimal:
attentionRow || failedRow
(attentionRow || failedRow || allDone) && heroRow
? renderGlyph(phaseSymbol(heroRow.phase), 13, phaseTint(heroRow.phase))
: renderLogo(11, tint),
expandedLeading: (
<HStack spacing={5} alignment="center" modifiers={[padding({ leading: 4, vertical: 4 })]}>
{renderLogo(15, tint)}
<Text modifiers={[font({ weight: "bold", size: 13 }), foregroundStyle(tint)]}>
{`${props.activeCount}`}
{allDone ? doneLabel : `${props.activeCount}`}
</Text>
</HStack>
),
+18
View File
@@ -0,0 +1,18 @@
import * as Schema from "effect/Schema";
/**
* Accounts that opted out of the post-sign-in T3 Connect onboarding wizard
* ("Don't show this again"). The wizard otherwise shows on every sign-in,
* since sign-out clears the connected environments.
*/
export const CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY = "t3code:connect-onboarding-opt-out:v1";
export const ConnectOnboardingOptOutSchema = Schema.Struct({
optOutAccounts: Schema.Array(Schema.String),
});
export type ConnectOnboardingOptOutState = typeof ConnectOnboardingOptOutSchema.Type;
export const EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE: ConnectOnboardingOptOutState = {
optOutAccounts: [],
};
@@ -0,0 +1,163 @@
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()));
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) {
// Unlink works without a relay token — a failed token read must not
// leave the user unable to turn T3 Connect off.
const unlinkResult = await unlinkPrimaryEnvironment({
target,
clerkToken: tokenResult._tag === "Success" ? (tokenResult.value ?? null) : null,
});
if (unlinkResult._tag === "Failure") {
if (!isAtomCommandInterrupted(unlinkResult)) {
reportUpdateFailure(squashAtomCommandFailure(unlinkResult));
}
primaryCloudLinkState.refresh();
return false;
}
} else {
if (tokenResult._tag === "Failure") {
reportUpdateFailure(squashAtomCommandFailure(tokenResult));
return false;
}
const clerkToken = tokenResult.value;
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,227 @@
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) {
// A failed or offline discovery is not "no environments" — misreporting it
// as empty would read as the user's devices having disappeared.
const discoveryProblem = environmentsState.offline
? "You appear to be offline."
: (Option.getOrNull(environmentsState.error)?.message ?? null);
if (discoveryProblem !== null && !environmentsState.refreshing) {
return (
<div className={ITEM_ROW_CLASSNAME}>
<p className="text-sm font-medium text-destructive">
Could not load T3 Connect environments
</p>
<p className="mt-1 text-xs text-muted-foreground">{discoveryProblem}</p>
<Button
size="sm"
variant="outline"
className="mt-3"
onClick={() => void refreshRelayEnvironments()}
>
Try again
</Button>
</div>
);
}
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,437 @@
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_OPT_OUT_STORAGE_KEY,
ConnectOnboardingOptOutSchema,
EMPTY_CONNECT_ONBOARDING_OPT_OUT_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 { Checkbox } from "../ui/checkbox";
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 on every in-session
* sign-in — sign-out removes the connected relay environments, so each new
* session starts with no devices to reach. It 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. A cold load with a restored session does not count as a sign-in.
*/
export function ConnectOnboardingDialog() {
if (!hasCloudPublicConfig()) return null;
return <ConfiguredConnectOnboardingDialog />;
}
type OnboardingStep = "publish" | "devices";
function ConfiguredConnectOnboardingDialog() {
// Mirrors ManagedRelayAuthProvider: a pending Clerk session must not read as
// signed-out, or its later activation would look like a fresh sign-in.
const { isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });
const [optOutState, setOptOutState] = useLocalStorage(
CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY,
EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE,
ConnectOnboardingOptOutSchema,
);
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 [requestedAccount, setRequestedAccount] = useState<string | null>(null);
const [openForAccount, setOpenForAccount] = useState<string | null>(null);
const [step, setStep] = useState<OnboardingStep>("devices");
const [exposeEnvironment, setExposeEnvironment] = useState(true);
const [publishAgentActivity, setPublishAgentActivity] = useState(true);
const [dontShowAgain, setDontShowAgain] = useState(false);
const [isApplying, setIsApplying] = useState(false);
const prefilledFromLinkStateRef = useRef(false);
const observedAccountRef = useRef<string | null | undefined>(undefined);
const optOutAccounts = optOutState.optOutAccounts;
// Every sign-in or account switch that completes during this session
// requests the wizard — account transitions clear the connected relay
// environments, so each new session starts with no devices to reach. A cold
// load observes undefined → account and must not re-prompt.
useEffect(() => {
if (!isLoaded) return;
// A loaded-but-incomplete snapshot (signed in, user id not yet populated)
// must not be recorded as signed-out — the next render would then look
// like a fresh sign-in on a cold load.
if (isSignedIn && !userId) return;
const previousAccount = observedAccountRef.current;
const nextAccount = isSignedIn && userId ? userId : null;
observedAccountRef.current = nextAccount;
if (previousAccount !== undefined && previousAccount !== nextAccount && nextAccount !== null) {
setRequestedAccount(nextAccount);
}
}, [isLoaded, isSignedIn, userId]);
// A manageable session implies a primary environment, so when the scopes
// allow publishing, wait for the connection target too — otherwise the
// wizard could open on the devices step moments before the publish step
// becomes available and freeze there.
const publishStepDecided = !canManageRelay || controller.linkState.target !== null;
// Open once the session scopes resolve so the step set is stable. Accounts
// that chose "Don't show this again" are skipped.
useEffect(() => {
if (requestedAccount === null || openForAccount !== null) return;
if (optOutAccounts.includes(requestedAccount)) {
setRequestedAccount(null);
return;
}
if (!sessionScopesKnown || !publishStepDecided) return;
setRequestedAccount(null);
prefilledFromLinkStateRef.current = false;
setExposeEnvironment(true);
setPublishAgentActivity(true);
setDontShowAgain(false);
setStep(canManageRelay && controller.linkState.target !== null ? "publish" : "devices");
setOpenForAccount(requestedAccount);
}, [
canManageRelay,
controller.linkState.target,
openForAccount,
optOutAccounts,
publishStepDecided,
requestedAccount,
sessionScopesKnown,
]);
// 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);
}
if (requestedAccount !== null && (!isSignedIn || userId !== requestedAccount)) {
setRequestedAccount(null);
}
}, [isSignedIn, openForAccount, requestedAccount, userId]);
// Toggles default on, but an environment that is already linked should show
// its actual configuration instead of silently proposing to rewrite it.
// Only when the link belongs to the account being onboarded, though — after
// an account switch the cached link state can still describe the previous
// account's setup.
const linkStateData = controller.linkState.data;
useEffect(() => {
if (openForAccount === null || prefilledFromLinkStateRef.current || linkStateData === null) {
return;
}
prefilledFromLinkStateRef.current = true;
if (linkStateData.linked && linkStateData.cloudUserId === openForAccount) {
setExposeEnvironment(linkStateData.managedTunnelActive ?? linkStateData.linked);
setPublishAgentActivity(linkStateData.publishAgentActivity);
}
}, [linkStateData, openForAccount]);
const complete = () => {
// Keep the wizard up while a link request is in flight so its outcome
// (and any failure) stays visible.
if (isApplying) return;
const account = openForAccount;
setOpenForAccount(null);
if (account !== null && dontShowAgain) {
setOptOutState((state) =>
state.optOutAccounts.includes(account)
? state
: { optOutAccounts: [...state.optOutAccounts, 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) => {
// Keep the dialog up while a link request is in flight so its outcome
// (and any failure) stays visible.
if (!open && !isApplying) 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}
disabled={isApplying}
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" className="sm:justify-between">
<label className="flex cursor-pointer items-center gap-2 self-start text-xs text-muted-foreground sm:self-center">
<Checkbox
checked={dontShowAgain}
onCheckedChange={(checked) => setDontShowAgain(checked === true)}
/>
Don&apos;t show this again
</label>
<div className="flex flex-col-reverse gap-2 sm:flex-row">
{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 disabled={isApplying} onClick={complete}>
Done
</Button>
)}
</div>
</DialogFooter>
</DialogPopup>
</Dialog>
);
}
const STEP_LABELS: Record<OnboardingStep, string> = {
publish: "Publish",
devices: "Connect devices",
};
function OnboardingStepper({
steps,
currentStep,
disabled,
onStepSelect,
}: {
readonly steps: ReadonlyArray<OnboardingStep>;
readonly currentStep: OnboardingStep;
readonly disabled: boolean;
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"
disabled={disabled}
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,7 +2,7 @@ import { useNavigate } from "@tanstack/react-router";
import { useAtomValue } from "@effect/atom-react";
import type { ServerProvider } from "@t3tools/contracts";
import { CircleCheckIcon, DownloadIcon, LoaderIcon, TriangleAlertIcon, XIcon } from "lucide-react";
import { useCallback, useEffect, useState, type CSSProperties } from "react";
import { useCallback, useEffect, useRef, useState, type CSSProperties } from "react";
import { primaryServerProvidersAtom } from "../../state/server";
import {
@@ -28,51 +28,19 @@ const PROVIDER_UPDATE_PILL_PROGRESS_STYLES = {
error: "bg-destructive/14",
} as const;
function providerUpdatePillProgressStyle(
tone: ProviderUpdateSidebarPillView["tone"],
): string | null {
return tone === "loading" ? null : PROVIDER_UPDATE_PILL_PROGRESS_STYLES[tone];
function useMountedIsoTimestamp(): string {
const [mountedIsoTimestamp] = useState(() => new Date().toISOString());
return mountedIsoTimestamp;
}
interface SidebarProviderUpdatePillContentProps {
providers: ReadonlyArray<ServerProvider>;
onOpenProviderSettings: () => void;
}
function useProviderUpdateSidebarVisibleAfterIso(): string {
const [visibleAfterIso] = useState(() => new Date().toISOString());
return visibleAfterIso;
}
function useSidebarProviderUpdatePillTransition(
view: ProviderUpdateSidebarPillView | null,
onDismissViewKey: (viewKey: string) => void,
) {
const [renderedView, setRenderedView] = useState<ProviderUpdateSidebarPillView | null>(view);
const [pendingView, setPendingView] = useState<ProviderUpdateSidebarPillView | null>(null);
const [exitingKey, setExitingKey] = useState<string | null>(null);
const [dismissAfterExitKey, setDismissAfterExitKey] = useState<string | null>(null);
const displayedView = renderedView ?? view;
const dismissAfterVisibleMs = displayedView?.dismissAfterVisibleMs;
const viewKey = displayedView?.key ?? null;
const dismissProgressStyle = displayedView
? providerUpdatePillProgressStyle(displayedView.tone)
: null;
const showDismissProgress =
dismissAfterVisibleMs !== undefined && dismissProgressStyle !== null && exitingKey !== viewKey;
const startExit = useCallback(
(key: string, nextView: ProviderUpdateSidebarPillView | null, dismissKey?: string) => {
if (exitingKey === key) {
return;
}
setPendingView(nextView);
setExitingKey(key);
setDismissAfterExitKey(dismissKey ?? null);
},
[exitingKey],
);
function useProviderUpdateRenderedViewSynchronization(input: {
readonly exitingKey: string | null;
readonly renderedView: ProviderUpdateSidebarPillView | null;
readonly setRenderedView: (view: ProviderUpdateSidebarPillView | null) => void;
readonly startExit: (key: string, nextView: ProviderUpdateSidebarPillView | null) => void;
readonly view: ProviderUpdateSidebarPillView | null;
}) {
const { exitingKey, renderedView, setRenderedView, startExit, view } = input;
useEffect(() => {
if (exitingKey !== null) {
return;
@@ -91,8 +59,20 @@ function useSidebarProviderUpdatePillTransition(
startExit(renderedView.key, view);
return;
}
}, [exitingKey, renderedView, startExit, view]);
}, [exitingKey, renderedView, setRenderedView, startExit, view]);
}
function useProviderUpdateAutoDismiss(input: {
readonly dismissAfterVisibleMs: number | undefined;
readonly exitingKey: string | null;
readonly startExit: (
key: string,
nextView: ProviderUpdateSidebarPillView | null,
dismissKey?: string,
) => void;
readonly viewKey: string | null;
}) {
const { dismissAfterVisibleMs, exitingKey, startExit, viewKey } = input;
useEffect(() => {
if (!dismissAfterVisibleMs || !viewKey) {
return;
@@ -106,53 +86,60 @@ function useSidebarProviderUpdatePillTransition(
return () => window.clearTimeout(timeoutId);
}, [dismissAfterVisibleMs, exitingKey, startExit, viewKey]);
const finishExit = useCallback(
(viewKey: string) => {
if (dismissAfterExitKey === viewKey) {
onDismissViewKey(viewKey);
}
setRenderedView(pendingView);
setPendingView(null);
setExitingKey(null);
setDismissAfterExitKey(null);
},
[dismissAfterExitKey, onDismissViewKey, pendingView],
);
return {
displayedView,
dismissAfterVisibleMs,
dismissProgressStyle,
exitingKey,
finishExit,
showDismissProgress,
startExit,
};
}
export function SidebarProviderUpdatePillContent({
providers,
onOpenProviderSettings,
}: SidebarProviderUpdatePillContentProps) {
export function SidebarProviderUpdatePill() {
const navigate = useNavigate();
const providers = useAtomValue(primaryServerProvidersAtom);
const [dismissedKeys, setDismissedKeys] = useState<ReadonlySet<string>>(() => new Set());
const visibleAfterIso = useProviderUpdateSidebarVisibleAfterIso();
const visibleAfterIso = useMountedIsoTimestamp();
const view = getProviderUpdateSidebarPillView(providers, {
visibleAfterIso,
dismissedKeys,
});
const dismissViewKey = useCallback((viewKey: string) => {
setDismissedKeys((previous) => new Set(previous).add(viewKey));
}, []);
const {
displayedView,
dismissAfterVisibleMs,
dismissProgressStyle,
const [renderedView, setRenderedView] = useState<ProviderUpdateSidebarPillView | null>(
() => view,
);
const pendingViewRef = useRef<ProviderUpdateSidebarPillView | null>(null);
const [exitingKey, setExitingKey] = useState<string | null>(null);
const dismissAfterExitKeyRef = useRef<string | null>(null);
const openProviderSettings = useCallback(() => {
void navigate({ to: "/settings/providers" });
}, [navigate]);
const displayedView = renderedView ?? view;
const dismissAfterVisibleMs = displayedView?.dismissAfterVisibleMs;
const viewKey = displayedView?.key ?? null;
const showDismissProgress =
dismissAfterVisibleMs !== undefined &&
displayedView?.tone !== "loading" &&
exitingKey !== viewKey;
const startExit = useCallback(
(key: string, nextView: ProviderUpdateSidebarPillView | null, dismissKey?: string) => {
if (exitingKey === key) {
return;
}
pendingViewRef.current = nextView;
dismissAfterExitKeyRef.current = dismissKey ?? null;
setExitingKey(key);
},
[exitingKey],
);
useProviderUpdateRenderedViewSynchronization({
exitingKey,
finishExit,
showDismissProgress,
renderedView,
setRenderedView,
startExit,
} = useSidebarProviderUpdatePillTransition(view, dismissViewKey);
view,
});
useProviderUpdateAutoDismiss({
dismissAfterVisibleMs,
exitingKey,
startExit,
viewKey,
});
if (!displayedView) {
return null;
@@ -174,15 +161,21 @@ export function SidebarProviderUpdatePillContent({
if (!displayedView || exitingKey !== displayedView.key) {
return;
}
finishExit(displayedView.key);
if (dismissAfterExitKeyRef.current === displayedView.key) {
setDismissedKeys((previous) => new Set(previous).add(displayedView.key));
}
setRenderedView(pendingViewRef.current);
pendingViewRef.current = null;
setExitingKey(null);
dismissAfterExitKeyRef.current = null;
}}
>
{showDismissProgress && dismissProgressStyle ? (
{showDismissProgress ? (
<div
key={displayedView.key}
aria-hidden="true"
className={`provider-update-pill-progress pointer-events-none absolute inset-y-0 left-0 w-full origin-left border-r border-current/15 shadow-[inset_0_1px_0_rgb(255_255_255_/_0.08)] ${
dismissProgressStyle
PROVIDER_UPDATE_PILL_PROGRESS_STYLES[displayedView.tone]
}`}
style={
{
@@ -199,7 +192,7 @@ export function SidebarProviderUpdatePillContent({
type="button"
aria-label={displayedView.description}
className="provider-update-main relative z-[1] flex h-full flex-1 items-center gap-2 px-2 text-left"
onClick={onOpenProviderSettings}
onClick={openProviderSettings}
>
{displayedView.tone === "loading" ? (
<LoaderIcon className="size-3.5 animate-spin" />
@@ -236,18 +229,3 @@ export function SidebarProviderUpdatePillContent({
</div>
);
}
export function SidebarProviderUpdatePill() {
const navigate = useNavigate();
const providers = useAtomValue(primaryServerProvidersAtom);
const openProviderSettings = useCallback(() => {
void navigate({ to: "/settings/providers" });
}, [navigate]);
return (
<SidebarProviderUpdatePillContent
providers={providers}
onOpenProviderSettings={openProviderSettings}
/>
);
}
+2 -2
View File
@@ -182,7 +182,7 @@ const capabilitiesLayer = Layer.effectContext(
if (session === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "Sign in to T3 Cloud to connect this environment.",
detail: "Sign in to T3 Connect to connect this environment.",
});
}
const token = yield* session.readClerkToken().pipe(
@@ -197,7 +197,7 @@ const capabilitiesLayer = Layer.effectContext(
if (token === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "The T3 Cloud session is unavailable.",
detail: "The T3 Connect session is unavailable.",
});
}
return token;
+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 />
+1 -1
View File
@@ -48,7 +48,7 @@
"engines": {
"node": "^24.13.1"
},
"packageManager": "pnpm@10.24.0",
"packageManager": "pnpm@11.10.0",
"msw": {
"workerDirectory": [
"apps/web/public"
@@ -342,6 +342,55 @@ describe("RelayEnvironmentDiscovery", () => {
}),
);
it.effect("refreshes proactively when credentials change before any manual refresh", () =>
Effect.gen(function* () {
const harness = yield* makeHarness();
yield* Effect.gen(function* () {
const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery;
const requests = yield* Ref.get(harness.statusRequests);
for (const environment of environments) {
yield* Deferred.succeed(
requests.get(environment.environmentId)!,
status(environment, "online"),
);
}
// Let the scoped wakeup subscription start before emitting, mirroring
// a real sign-in which always happens long after service start.
yield* Effect.yieldNow;
// Sign-in activates the session and emits credentials-changed; the
// list must populate without any screen having asked for a refresh.
yield* harness.wake("credentials-changed");
const populated = yield* SubscriptionRef.changes(discovery.state).pipe(
Stream.filter(
(state) => state.environments.size === environments.length && !state.refreshing,
),
Stream.runHead,
Effect.map(Option.getOrThrow),
);
expect(Option.isNone(populated.error)).toBe(true);
expect(yield* Ref.get(harness.listCalls)).toBe(1);
}).pipe(Effect.provide(harness.layer), Effect.scoped);
}),
);
it.effect("settles to a clean empty state when refreshed while signed out", () =>
Effect.gen(function* () {
const harness = yield* makeHarness();
yield* Effect.gen(function* () {
const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery;
yield* Ref.set(harness.clerkToken, null);
yield* discovery.refresh;
const state = yield* SubscriptionRef.get(discovery.state);
expect(state.environments.size).toBe(0);
expect(state.refreshing).toBe(false);
expect(Option.isNone(state.error)).toBe(true);
}).pipe(Effect.provide(harness.layer));
}),
);
it.effect("does not republish stale rows after sign-out invalidates an in-flight refresh", () =>
Effect.gen(function* () {
const harness = yield* makeHarness();
+26 -5
View File
@@ -222,7 +222,27 @@ export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () {
error: Option.none(),
});
const clerkToken = yield* session.clerkToken;
// Signed out is the idle state, not a failure: the proactive refresh on
// credentials-changed also runs on sign-out and must settle back to a
// clean empty list. Only the session-level "no credentials" error is
// benign — relay-side auth failures (expired/invalid tokens) happen
// after this point and must surface as errors.
const tokenResult = yield* Effect.result(session.clerkToken);
if (tokenResult._tag === "Failure") {
const failure = tokenResult.failure;
if (failure._tag === "ConnectionBlockedError" && failure.reason === "authentication") {
if ((yield* Ref.get(accountGeneration)) !== generation) {
return;
}
yield* SubscriptionRef.update(state, (current) => ({
...current,
refreshing: false,
}));
return;
}
return yield* Effect.fail(failure);
}
const clerkToken = tokenResult.success;
if ((yield* Ref.get(accountGeneration)) !== generation) {
return;
}
@@ -311,11 +331,12 @@ export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () {
yield* Ref.update(accountGeneration, (current) => current + 1);
yield* Ref.set(activeAccountId, Option.none());
yield* Ref.set(offlineReportFingerprints, new Map());
const shouldRefresh = yield* Ref.get(hasRefreshed);
yield* SubscriptionRef.set(state, EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE);
if (shouldRefresh) {
yield* refresh.pipe(Effect.forkScoped);
}
// Refresh proactively — this wakeup fires when a session activates
// (sign-in or cold start), and the list should be populated before
// any screen asks for it. A signed-out refresh settles back to the
// clean empty state.
yield* refresh.pipe(Effect.forkScoped);
})
: Effect.void,
),
@@ -123,7 +123,7 @@ export function createManagedRelaySession(input: ManagedRelaySessionInput): Mana
try: () => readCachedClerkToken(nowMillis),
catch: (cause) =>
new ManagedRelaySessionError({
message: "Could not obtain the T3 Cloud session token.",
message: "Could not obtain the T3 Connect session token.",
cause,
}),
});
@@ -181,7 +181,7 @@ function readSessionClerkToken(
? Effect.succeed(token)
: Effect.fail(
new ManagedRelaySessionError({
message: "The T3 Cloud session token is unavailable.",
message: "The T3 Connect session token is unavailable.",
}),
),
),
@@ -226,7 +226,7 @@ function requireClerkToken(
if (!session || session.accountId !== accountId) {
return Effect.fail(
new ManagedRelaySessionError({
message: "Sign in to T3 Cloud before loading relay data.",
message: "Sign in to T3 Connect before loading relay data.",
}),
);
}
@@ -296,7 +296,7 @@ export function readManagedRelaySnapshotState<A>(
let errorTraceId: string | null = null;
if (result._tag === "Failure") {
const cause = Cause.squash(result.cause);
error = cause instanceof Error ? cause.message : "Could not load T3 Cloud data.";
error = cause instanceof Error ? cause.message : "Could not load T3 Connect data.";
errorTraceId = findErrorTraceId(cause);
}
return {
+40 -1
View File
@@ -1,3 +1,42 @@
diff --git a/android/src/main/java/com/swmansion/rnscreens/ScreenStackHeaderConfigViewManager.kt b/android/src/main/java/com/swmansion/rnscreens/ScreenStackHeaderConfigViewManager.kt
index 03d8d9f3a5c403c93282d53cbacf1a339e877e85..54d5eabc6c8a408e711a5be97286fdbb8ab1c461 100644
--- a/android/src/main/java/com/swmansion/rnscreens/ScreenStackHeaderConfigViewManager.kt
+++ b/android/src/main/java/com/swmansion/rnscreens/ScreenStackHeaderConfigViewManager.kt
@@ -103,6 +103,34 @@ class ScreenStackHeaderConfigViewManager :
config.setTitle(title)
}
+ // The t3 patch adds these iOS glass-chrome props to the native spec; they have
+ // no Android implementation, but the codegen-generated interface requires the
+ // setters to exist. No-ops keep the Android build compiling.
+ override fun setSubtitle(
+ config: ScreenStackHeaderConfig,
+ subtitle: String?,
+ ) = Unit
+
+ override fun setLargeSubtitle(
+ config: ScreenStackHeaderConfig,
+ largeSubtitle: String?,
+ ) = Unit
+
+ override fun setNavigationItemStyle(
+ config: ScreenStackHeaderConfig,
+ navigationItemStyle: String?,
+ ) = Unit
+
+ override fun setHeaderCenterBarButtonItems(
+ config: ScreenStackHeaderConfig,
+ headerCenterBarButtonItems: ReadableArray?,
+ ) = Unit
+
+ override fun setHeaderToolbarItems(
+ config: ScreenStackHeaderConfig,
+ headerToolbarItems: ReadableArray?,
+ ) = Unit
+
override fun setTitleFontFamily(
config: ScreenStackHeaderConfig,
titleFontFamily: String?,
diff --git a/ios/RNSBarButtonItem.h b/ios/RNSBarButtonItem.h
index ea5325ea8d17b1ddfa790ff8dab48ce83142d4d3..acd2fd7ceb7162ed300abc4d3c9f0c24f4d63898 100644
--- a/ios/RNSBarButtonItem.h
@@ -1067,7 +1106,7 @@ index b7568ecfebd4f4420f2a8d3fec5184d7fc728dd1..41ca1f273f0175929e73105faa463978
onPressHeaderBarButtonMenuItem?: CT.DirectEventHandler<OnPressHeaderBarButtonMenuItemEvent> | undefined;
synchronousShadowStateUpdatesEnabled?: CT.WithDefault<boolean, false>;
diff --git a/lib/typescript/types.d.ts b/lib/typescript/types.d.ts
index 3b384e03891e38e936f370372a682d73440e7ec2..1e3a966806c8b8b312f75fb367f758efe49dde9d 100644
index 3b384e03891e38e936f370372a682d73440e7ec2..861ffed850e90f27916c427853b503dbe6ee9840 100644
--- a/lib/typescript/types.d.ts
+++ b/lib/typescript/types.d.ts
@@ -10,6 +10,7 @@ export type SearchBarCommands = {
+542 -564
View File
File diff suppressed because it is too large. Load diff
+30 -15
View File
@@ -5,14 +5,31 @@ packages:
- packages/*
- scripts
# Successor to onlyBuiltDependencies/ignoredBuiltDependencies (pnpm 11).
# true = allowed to run build scripts; false mirrors the pnpm 10 behavior
# where anything outside onlyBuiltDependencies was silently not built.
allowBuilds:
browser-tabs-lock: false
bufferutil: false
core-js: false
electron: true
electron-winstaller: false
esbuild: true
msgpackr-extract: true
msw: false
node-pty: true
sharp: true
utf-8-validate: false
workerd: false
catalog:
"@clerk/backend": 3.8.4
"@clerk/clerk-js": 6.22.0
"@clerk/electron": 0.0.5
"@clerk/backend": 3.11.1
"@clerk/clerk-js": 6.25.0
"@clerk/electron": 0.0.10
"@clerk/electron-passkeys": 0.0.3
"@clerk/expo": 3.6.2
"@clerk/react": 6.11.1
"@clerk/shared": 4.22.0
"@clerk/expo": 3.7.1
"@clerk/react": 6.12.0
"@clerk/shared": 4.25.0
"@effect/atom-react": 4.0.0-beta.78
"@effect/openapi-generator": 4.0.0-beta.78
"@effect/platform-bun": 4.0.0-beta.78
@@ -34,15 +51,13 @@ catalog:
vite-plus: 0.2.2
yaml: ^2.9.0
ignoredBuiltDependencies:
- msw
onlyBuiltDependencies:
- electron
- esbuild
- msgpackr-extract
- node-pty
- sharp
minimumReleaseAgeExclude:
- "@clerk/[email protected]"
- "@clerk/[email protected]"
- "@clerk/[email protected]"
- "@clerk/[email protected]"
- "@clerk/[email protected]"
- "@clerk/[email protected]"
overrides:
"@clerk/backend": "catalog:"
+68 -14
View File
@@ -11,7 +11,7 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import {
BuildCommandFailedError,
createStageWorkspaceConfig,
createStagePnpmConfig,
createStagePatchedDependencies,
createBuildConfig,
DESKTOP_ASAR_UNPACK,
InvalidMacPasskeyRpDomainError,
@@ -168,7 +168,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
it("carries only staged dependency patch metadata into staged desktop installs", () => {
assert.deepStrictEqual(
createStagePnpmConfig(
createStagePatchedDependencies(
{
"@expo/[email protected]": "patches/@expo%[email protected]",
"@ff-labs/[email protected]": "patches/@[email protected]",
@@ -183,28 +183,26 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
},
),
{
patchedDependencies: {
"@ff-labs/[email protected]": "patches/@[email protected].patch",
"@pierre/[email protected]": "patches/@pierre%[email protected].patch",
"[email protected]": "patches/[email protected]",
},
"@ff-labs/[email protected]": "patches/@[email protected]",
"@pierre/[email protected]": "patches/@pierre%[email protected].patch",
"[email protected]": "patches/[email protected].patch",
},
);
assert.equal(
createStagePnpmConfig(
assert.deepStrictEqual(
createStagePatchedDependencies(
{
"@expo/[email protected]": "patches/@expo%[email protected]",
},
{ effect: "4.0.0-beta.73" },
),
undefined,
{},
);
});
it("installs optional native dependencies for the target desktop architecture", () => {
assert.deepStrictEqual(STAGE_INSTALL_ARGS, ["install", "--prod"]);
assert.deepStrictEqual(createStageWorkspaceConfig("mac", "x64"), {
assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "mac", arch: "x64" }), {
supportedArchitectures: {
os: ["darwin"],
cpu: ["x64"],
@@ -212,21 +210,21 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
});
// Windows artifacts also bundle the same-architecture WSL (Linux, glibc) backend, so the
// staged install must fetch its native optional deps (e.g. ffi-rs) too.
assert.deepStrictEqual(createStageWorkspaceConfig("win", "x64"), {
assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "win", arch: "x64" }), {
supportedArchitectures: {
os: ["win32", "linux"],
cpu: ["x64"],
libc: ["glibc"],
},
});
assert.deepStrictEqual(createStageWorkspaceConfig("win", "arm64"), {
assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "win", arch: "arm64" }), {
supportedArchitectures: {
os: ["win32", "linux"],
cpu: ["arm64"],
libc: ["glibc"],
},
});
assert.deepStrictEqual(createStageWorkspaceConfig("mac", "universal"), {
assert.deepStrictEqual(createStageWorkspaceConfig({ platform: "mac", arch: "universal" }), {
supportedArchitectures: {
os: ["darwin"],
cpu: ["arm64", "x64"],
@@ -234,6 +232,62 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
});
});
it("stages pnpm 11 allowBuilds and patchedDependencies in the workspace yaml", () => {
assert.deepStrictEqual(
createStageWorkspaceConfig({
platform: "linux",
arch: "x64",
allowBuilds: {
electron: true,
"node-pty": true,
"browser-tabs-lock": false,
},
patchedDependencies: {
"[email protected]": "patches/[email protected]",
},
overrides: {
effect: "4.0.0-beta.73",
},
}),
{
supportedArchitectures: {
os: ["linux"],
cpu: ["x64"],
},
allowBuilds: {
electron: true,
"node-pty": true,
"browser-tabs-lock": false,
},
patchedDependencies: {
"[email protected]": "patches/[email protected]",
},
overrides: {
effect: "4.0.0-beta.73",
},
},
);
// Empty maps must not be written — pnpm would still require reviewed
// packages if allowBuilds is present but incomplete, and omitting empty
// patchedDependencies keeps the stage yaml minimal.
assert.deepStrictEqual(
createStageWorkspaceConfig({
platform: "mac",
arch: "arm64",
allowBuilds: {},
patchedDependencies: {},
overrides: {},
}),
{
supportedArchitectures: {
os: ["darwin"],
cpu: ["arm64"],
},
},
);
});
it("unpacks the fff shared library for filesystem and FFI access", () => {
assert.deepStrictEqual(DESKTOP_ASAR_UNPACK, ["node_modules/@ff-labs/fff-bin-*/**/*"]);
});
+50 -33
View File
@@ -40,6 +40,7 @@ const WorkspaceConfig = Schema.Struct({
catalog: Schema.optional(Schema.Record(Schema.String, Schema.String)),
overrides: Schema.optional(Schema.Record(Schema.String, Schema.String)),
patchedDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
allowBuilds: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)),
});
type WorkspaceConfig = typeof WorkspaceConfig.Type;
@@ -49,7 +50,14 @@ const StageWorkspaceConfig = Schema.Struct({
cpu: Schema.Array(Schema.String),
libc: Schema.optional(Schema.Array(Schema.String)),
}),
// pnpm 11 only reads these from pnpm-workspace.yaml (not package.json#pnpm).
// Without allowBuilds the staged `vp install --prod` fails with
// ERR_PNPM_IGNORED_BUILDS for packages that have lifecycle scripts.
allowBuilds: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)),
patchedDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
overrides: Schema.optional(Schema.Record(Schema.String, Schema.String)),
});
type StageWorkspaceConfig = typeof StageWorkspaceConfig.Type;
const RepoRoot = Effect.service(Path.Path).pipe(
Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),
@@ -563,10 +571,6 @@ interface StagePackageJson {
readonly devDependencies: {
readonly electron: string;
};
readonly overrides: Record<string, unknown>;
readonly pnpm?: {
readonly patchedDependencies?: Record<string, string>;
};
}
export const STAGE_INSTALL_ARGS = ["install", "--prod"] as const;
@@ -876,10 +880,14 @@ const stageClerkPasskeyNativeBinaries = Effect.fn("stageClerkPasskeyNativeBinari
}
});
export function createStageWorkspaceConfig(
platform: typeof BuildPlatform.Type,
arch: typeof BuildArch.Type,
): typeof StageWorkspaceConfig.Type {
export function createStageWorkspaceConfig(input: {
readonly platform: typeof BuildPlatform.Type;
readonly arch: typeof BuildArch.Type;
readonly allowBuilds?: Record<string, boolean>;
readonly patchedDependencies?: Record<string, string>;
readonly overrides?: Record<string, string>;
}): StageWorkspaceConfig {
const { platform, arch, allowBuilds, patchedDependencies, overrides } = input;
const hostOs = platform === "mac" ? "darwin" : platform === "win" ? "win32" : "linux";
const hostCpu = arch === "universal" ? ["arm64", "x64"] : [arch];
// Windows artifacts also bundle the same-architecture WSL Linux backend, which loads
@@ -887,36 +895,37 @@ export function createStageWorkspaceConfig(
// Pull the Linux (glibc) variants in addition to the host platform's so
// they ship in the asar; without them the WSL backend crash-loops on require
// ("Cannot find module '@yuuang/ffi-rs-linux-x64-gnu'").
if (platform === "win") {
return {
supportedArchitectures: {
os: Array.from(new Set([hostOs, "linux"])),
cpu: hostCpu,
libc: ["glibc"],
},
};
}
const supportedArchitectures =
platform === "win"
? {
os: Array.from(new Set([hostOs, "linux"])),
cpu: hostCpu,
libc: ["glibc"],
}
: {
os: [hostOs],
cpu: hostCpu,
};
return {
supportedArchitectures: {
os: [hostOs],
cpu: hostCpu,
},
supportedArchitectures,
...(allowBuilds && Object.keys(allowBuilds).length > 0 ? { allowBuilds } : {}),
...(patchedDependencies && Object.keys(patchedDependencies).length > 0
? { patchedDependencies }
: {}),
...(overrides && Object.keys(overrides).length > 0 ? { overrides } : {}),
};
}
export function createStagePnpmConfig(
export function createStagePatchedDependencies(
patchedDependencies: Record<string, string>,
dependencies: Record<string, unknown>,
): StagePackageJson["pnpm"] | undefined {
const stagePatchedDependencies = Object.fromEntries(
): Record<string, string> {
return Object.fromEntries(
Object.entries(patchedDependencies).filter(([patchKey]) =>
Object.hasOwn(dependencies, getPatchedDependencyPackageName(patchKey)),
),
);
return Object.keys(stagePatchedDependencies).length > 0
? { patchedDependencies: stagePatchedDependencies }
: undefined;
}
function getPatchedDependencyPackageName(patchKey: string): string {
@@ -1540,6 +1549,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
const workspaceCatalog = workspaceConfig.catalog ?? {};
const workspaceOverrides = workspaceConfig.overrides ?? {};
const workspacePatchedDependencies = workspaceConfig.patchedDependencies ?? {};
const workspaceAllowBuilds = workspaceConfig.allowBuilds ?? {};
const platformConfig = PLATFORM_CONFIG[options.platform];
if (!platformConfig) {
@@ -1709,7 +1719,10 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
)
: {}),
};
const stagePnpmConfig = createStagePnpmConfig(workspacePatchedDependencies, stageDependencies);
const stagePatchedDependencies = createStagePatchedDependencies(
workspacePatchedDependencies,
stageDependencies,
);
const stagePackageJson: StagePackageJson = {
name: "t3code",
version: appVersion,
@@ -1738,20 +1751,24 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
devDependencies: {
electron: electronVersion,
},
overrides: resolvedOverrides,
...(stagePnpmConfig ? { pnpm: stagePnpmConfig } : {}),
};
const stagePackageJsonString = yield* encodeJsonString(stagePackageJson);
yield* fs.writeFileString(path.join(stageAppDir, "package.json"), `${stagePackageJsonString}\n`);
const stageWorkspaceConfig = createStageWorkspaceConfig(options.platform, options.arch);
const stageWorkspaceConfig = createStageWorkspaceConfig({
platform: options.platform,
arch: options.arch,
allowBuilds: workspaceAllowBuilds,
patchedDependencies: stagePatchedDependencies,
overrides: resolvedOverrides,
});
const stageWorkspaceConfigString = yield* encodeStageWorkspaceConfig(stageWorkspaceConfig);
yield* fs.writeFileString(
path.join(stageAppDir, "pnpm-workspace.yaml"),
stageWorkspaceConfigString,
);
if (Object.keys(workspacePatchedDependencies).length > 0) {
if (Object.keys(stagePatchedDependencies).length > 0) {
yield* fs.copy(path.join(repoRoot, "patches"), path.join(stageAppDir, "patches"));
}