@devries-cameron20 / t3code-1 / commits / 9f33a1c836
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

feat(web): show T3 Connect tunnel usage and push full accounts to T3 Chat (#26369)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Oct 28, 2026 at 03:04 UTC 9f33a1c8361e18f553b387cbb5d3c2c62d56f8ba
14 files changed +506 -95
apps/web/src/cloud/managedRelayState.ts
+54 -4
@@ -12,10 +12,12 @@ import {
12 createAtomCommandScheduler,
13 createRuntimeCommand,
14 } from "@t3tools/client-runtime/state/runtime";
15 -import type {
16 - RelayClientDeviceRecord,
17 - RelayClientEnvironmentRecord,
18 - RelayT3ChatLinkResponse,
15 +import {
16 + DEFAULT_MANAGED_TUNNEL_LIMIT,
17 + T3CHAT_PLAN_TUNNEL_LIMITS,
18 + type RelayClientDeviceRecord,
19 + type RelayClientEnvironmentRecord,
20 + type RelayT3ChatLinkResponse,
21 } from "@t3tools/contracts/relay";
22 import type { EnvironmentId } from "@t3tools/contracts";
23 import * as Context from "effect/Context";
@@ -144,3 +146,51 @@ export function useManagedRelayDevices() {
146 refresh,
147 };
148 }
149 +
150 +/** How this account can raise its tunnel cap: link T3 Chat, or upgrade the linked plan. */
151 +export type ManagedTunnelUpgrade = "link" | "pro" | "premier" | null;
152 +
153 +// Mirrors the relay's cap without manual overrides, which the relay does not expose.
154 +function managedTunnelCap(t3Chat: RelayT3ChatLinkResponse): {
155 + readonly limit: number;
156 + readonly upgrade: ManagedTunnelUpgrade;
157 +} {
158 + if (!t3Chat.available) return { limit: DEFAULT_MANAGED_TUNNEL_LIMIT, upgrade: null };
159 + switch (t3Chat.link?.plan) {
160 + case "premier":
161 + return { limit: T3CHAT_PLAN_TUNNEL_LIMITS.premier, upgrade: null };
162 + case "pro":
163 + return { limit: T3CHAT_PLAN_TUNNEL_LIMITS.pro, upgrade: "premier" };
164 + case "free":
165 + return { limit: DEFAULT_MANAGED_TUNNEL_LIMIT, upgrade: "pro" };
166 + case undefined:
167 + return { limit: DEFAULT_MANAGED_TUNNEL_LIMIT, upgrade: "link" };
168 + }
169 +}
170 +
171 +/** Refetches the account's environments and T3 Chat plan after a tunnel changes. */
172 +export function refreshManagedTunnelUsage() {
173 + const accountId = appAtomRegistry.get(managedRelaySessionAtom)?.accountId;
174 + if (!accountId) return;
175 + managedRelayQueryManager.refreshEnvironments(appAtomRegistry, accountId);
176 + managedRelayQueryManager.refreshT3ChatLink(appAtomRegistry, accountId);
177 +}
178 +
179 +/** Managed tunnels on this account and its cap. Null fields are still loading or failed. */
180 +export function useManagedTunnelUsage() {
181 + const environments = useManagedRelayEnvironments();
182 + const t3Chat = useManagedRelayT3ChatLink();
183 + const used =
184 + environments.accountId === null
185 + ? null
186 + : (environments.data?.filter(
187 + (environment) => environment.endpoint.providerKind === "cloudflare_tunnel",
188 + ).length ?? null);
189 + const cap = t3Chat.accountId !== null && t3Chat.data ? managedTunnelCap(t3Chat.data) : null;
190 + return {
191 + used,
192 + limit: cap?.limit ?? null,
193 + upgrade: cap?.upgrade ?? null,
194 + refresh: refreshManagedTunnelUsage,
195 + };
196 +}
apps/web/src/cloud/useCloudLinkController.browser.test.tsx
+38 -4
@@ -4,7 +4,12 @@ import {
4 EnvironmentId,
5 type EnvironmentCloudLinkStateResult,
6 } from "@t3tools/contracts";
7 -import type { RelayManagedEndpointProviderKind } from "@t3tools/contracts/relay";
7 +import { ManagedRelay } from "@t3tools/client-runtime/relay";
8 +import {
9 + RelayEnvironmentLinkLimitExceededError,
10 + type RelayManagedEndpointProviderKind,
11 +} from "@t3tools/contracts/relay";
12 +import * as Cause from "effect/Cause";
13 import { AsyncResult } from "effect/reactivity";
14 import { useLayoutEffect } from "react";
15 import { describe, expect, it, vi } from "vite-plus/test";
@@ -88,6 +93,7 @@ vi.mock(import("./publicConfig"), async (original) => ({
93 resolveRelayClerkTokenOptions: () => ({}) as never,
94 }));
95
96 +import { CloudEnvironmentLinkError } from "./linkEnvironment";
97 import { useCloudLinkController, type CloudLinkDesiredState } from "./useCloudLinkController";
98
99 const target = {
@@ -125,9 +131,8 @@ async function mountController() {
131 />,
132 );
133 return Object.assign(screen, {
128 - get controller() {
129 - return controller;
130 - },
134 + // Object.assign would copy a getter's value once, so read the latest render through a function.
135 + controller: () => controller,
136 async reconcile(desired: CloudLinkDesiredState) {
137 let succeeded = false;
138 await act(async () => {
@@ -225,4 +230,33 @@ describe("useCloudLinkController", () => {
230 expect(testState.link).not.toHaveBeenCalled();
231 expect(testState.preferences).not.toHaveBeenCalled();
232 });
233 +
234 + it("reports a relay tunnel cap refusal as tunnelLimit instead of an error", async () => {
235 + using _setup = setup();
236 + testState.snapshot = { ...linkedState, linked: false, managedTunnelActive: false };
237 + testState.link.mockResolvedValueOnce(
238 + AsyncResult.failure(
239 + Cause.fail(
240 + new CloudEnvironmentLinkError({
241 + message: "environment-links failed",
242 + cause: new ManagedRelay.ManagedRelayRequestFailedError({
243 + action: "link relay environment",
244 + cause: null,
245 + relayError: new RelayEnvironmentLinkLimitExceededError({
246 + code: "environment_link_limit_exceeded",
247 + maxTunnels: 3,
248 + traceId: "trace-1",
249 + }),
250 + }),
251 + }),
252 + ),
253 + ),
254 + );
255 + await using screen = await mountController();
256 +
257 + expect(await screen.reconcile({ managedTunnel: true, publish: false })).toBe(false);
258 + expect(screen.controller()?.tunnelLimit).toBe(3);
259 + expect(screen.controller()?.operationError).toBeNull();
260 + expect(testState.toast).not.toHaveBeenCalled();
261 + });
262 });
apps/web/src/cloud/useCloudLinkController.ts
+27 -1
@@ -7,18 +7,22 @@ import {
7 AuthRelayWriteScope,
8 type EnvironmentCloudLinkStateResult,
9 } from "@t3tools/contracts";
10 +import { ManagedRelay } from "@t3tools/client-runtime/relay";
11 import type { RelayManagedEndpointProviderKind } from "@t3tools/contracts/relay";
12 import {
13 isAtomCommandInterrupted,
14 settlePromise,
15 squashAtomCommandFailure,
16 } from "@t3tools/client-runtime/state/runtime";
17 +import * as Schema from "effect/Schema";
18 import { useState } from "react";
19
20 import { toastManager } from "../components/ui/toast";
21 import { relayEnvironmentDiscovery } from "../state/relay";
22 import { readEnvironmentScope } from "../state/session";
23 import { useAtomCommand } from "../state/use-atom-command";
24 +import { CloudEnvironmentLinkError } from "./linkEnvironment";
25 +import { refreshManagedTunnelUsage } from "./managedRelayState";
26 import {
27 linkPrimaryEnvironment as linkPrimaryEnvironmentAtom,
28 unlinkPrimaryEnvironment as unlinkPrimaryEnvironmentAtom,
@@ -46,6 +50,18 @@ function isManagedTunnelActive(
50 );
51 }
52
53 +const isManagedRelayRequestFailedError = Schema.is(ManagedRelay.ManagedRelayRequestFailedError);
54 +
55 +/** The account's tunnel cap when the relay refused a new tunnel for being at it. */
56 +function tunnelLimitFromLinkFailure(cause: unknown): number | null {
57 + if (!(cause instanceof CloudEnvironmentLinkError)) return null;
58 + const relayCause = cause.cause;
59 + if (!isManagedRelayRequestFailedError(relayCause)) return null;
60 + return relayCause.relayError?._tag === "RelayEnvironmentLinkLimitExceededError"
61 + ? relayCause.relayError.maxTunnels
62 + : null;
63 +}
64 +
65 export function useCloudLinkController() {
66 const { getToken, isSignedIn } = useAuth();
67 const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
@@ -68,6 +84,7 @@ export function useCloudLinkController() {
84 ? relayEnvironments.get(primaryEnvironmentId)?.environment.endpoint.providerKind
85 : undefined;
86 const [operationError, setOperationError] = useState<string | null>(null);
87 + const [tunnelLimit, setTunnelLimit] = useState<number | null>(null);
88
89 const reportUpdateFailure = (cause: unknown) => {
90 const message = cause instanceof Error ? cause.message : "Could not update T3 Connect access.";
@@ -100,6 +117,7 @@ export function useCloudLinkController() {
117
118 const reconcileCloudState = async (desired: CloudLinkDesiredState): Promise<boolean> => {
119 setOperationError(null);
120 + setTunnelLimit(null);
121 const target = primaryCloudLinkState.target;
122 if (!target) {
123 reportUpdateFailure(new Error("Local environment is not ready yet."));
@@ -138,6 +156,7 @@ export function useCloudLinkController() {
156 target,
157 clerkToken: tokenResult._tag === "Success" ? (tokenResult.value ?? null) : null,
158 });
159 + refreshManagedTunnelUsage();
160 if (unlinkResult._tag === "Failure") {
161 if (!isAtomCommandInterrupted(unlinkResult)) {
162 reportUpdateFailure(squashAtomCommandFailure(unlinkResult));
@@ -168,9 +187,15 @@ export function useCloudLinkController() {
187 clerkToken,
188 mode: desired.managedTunnel ? "managed" : "publish_only",
189 });
190 + // Any link attempt can change the account's tunnel count.
191 + refreshManagedTunnelUsage();
192 if (linkResult._tag === "Failure") {
193 if (!isAtomCommandInterrupted(linkResult)) {
173 - reportUpdateFailure(squashAtomCommandFailure(linkResult));
194 + const cause = squashAtomCommandFailure(linkResult);
195 + // The caller shows an upgrade prompt instead of an error.
196 + const limit = tunnelLimitFromLinkFailure(cause);
197 + if (limit === null) reportUpdateFailure(cause);
198 + else setTunnelLimit(limit);
199 }
200 primaryCloudLinkState.refresh();
201 return false;
@@ -215,6 +240,7 @@ export function useCloudLinkController() {
240 publishAgentActivity,
241 holdWebhooksWhileOffline,
242 operationError,
243 + tunnelLimit,
244 reconcileCloudState,
245 };
246 }
apps/web/src/components/clerk/T3ChatUserProfilePage.tsx
+26 -73
@@ -1,95 +1,43 @@
1 -import { findErrorTraceId } from "@t3tools/client-runtime/errors";
2 -import {
3 - isAtomCommandInterrupted,
4 - squashAtomCommandFailure,
5 -} from "@t3tools/client-runtime/state/runtime";
1 import { T3CHAT_PLAN_TUNNEL_LIMITS, type RelayT3ChatLink } from "@t3tools/contracts/relay";
2 import { MessageSquareIcon } from "lucide-react";
8 -import { useState } from "react";
3 +import type { ReactNode } from "react";
4
10 -import {
11 - createManagedRelayT3ChatLinkRequestCommand,
12 - unlinkManagedRelayT3ChatCommand,
13 - useManagedRelayT3ChatLink,
14 -} from "../../cloud/managedRelayState";
15 -import { readLocalApi } from "../../localApi";
16 -import { useAtomCommand } from "../../state/use-atom-command";
5 +import { useManagedTunnelUsage } from "../../cloud/managedRelayState";
6 +import { T3CHAT_SUBSCRIPTION_URL, TunnelUsageMeter } from "../cloud/TunnelUsage";
7 import { Button } from "../ui/button";
18 -import { toastManager } from "../ui/toast";
8 import {
9 ClerkUserProfilePage,
10 ClerkUserProfileRefreshButton,
11 ClerkUserProfileRow,
12 } from "./ClerkUserProfilePage";
13 +import { useT3ChatLink } from "./useT3ChatLink";
14
25 -function planLabel(link: RelayT3ChatLink): string {
15 +const upgradeLink = (
16 + <a className="underline" href={T3CHAT_SUBSCRIPTION_URL} target="_blank" rel="noopener noreferrer">
17 + Upgrade on T3 Chat
18 + </a>
19 +);
20 +
21 +function planLabel(link: RelayT3ChatLink): ReactNode {
22 switch (link.plan) {
23 case "premier":
24 return `Premier · up to ${T3CHAT_PLAN_TUNNEL_LIMITS.premier} tunnels`;
25 case "pro":
30 - return `Pro · up to ${T3CHAT_PLAN_TUNNEL_LIMITS.pro} tunnels, or ${T3CHAT_PLAN_TUNNEL_LIMITS.premier} with Premier`;
26 + return (
27 + <>
28 + Pro · up to {T3CHAT_PLAN_TUNNEL_LIMITS.pro} tunnels. {upgradeLink} to Premier for{" "}
29 + {T3CHAT_PLAN_TUNNEL_LIMITS.premier}.
30 + </>
31 + );
32 case "free":
32 - return "Upgrade on T3 Chat for more tunnels";
33 + return <>{upgradeLink} for more tunnels</>;
34 }
35 }
36
36 -function reportFailure(title: string, cause: unknown) {
37 - const traceId = findErrorTraceId(cause);
38 - toastManager.add({
39 - type: "error",
40 - title,
41 - description: cause instanceof Error ? cause.message : "Try again.",
42 - data: traceId
43 - ? {
44 - secondaryActionProps: {
45 - children: "Copy trace ID",
46 - onClick: () => void navigator.clipboard?.writeText(traceId),
47 - },
48 - }
49 - : undefined,
50 - });
51 -}
52 -
37 /** Links a T3 Chat account so paid subscribers get more tunnels. */
38 export function T3ChatUserProfilePage() {
55 - const linkState = useManagedRelayT3ChatLink();
56 - const createLinkRequest = useAtomCommand(createManagedRelayT3ChatLinkRequestCommand, {
57 - reportFailure: false,
58 - });
59 - const unlink = useAtomCommand(unlinkManagedRelayT3ChatCommand, { reportFailure: false });
60 - const [pending, setPending] = useState<"link" | "unlink" | null>(null);
61 - // Kept so a blocked popup still leaves the user a link to open.
62 - const [linkUrl, setLinkUrl] = useState<string | null>(null);
63 -
64 - const handleLink = async () => {
65 - const accountId = linkState.accountId;
66 - if (!accountId || pending) return;
67 - setPending("link");
68 - const result = await createLinkRequest({ accountId });
69 - if (result._tag === "Success") {
70 - setLinkUrl(result.value);
71 - await readLocalApi()
72 - ?.shell.openExternal(result.value)
73 - .catch(() => undefined);
74 - } else if (!isAtomCommandInterrupted(result)) {
75 - reportFailure("Could not start linking", squashAtomCommandFailure(result));
76 - }
77 - setPending(null);
78 - };
79 -
80 - const handleUnlink = async () => {
81 - const accountId = linkState.accountId;
82 - if (!accountId || pending) return;
83 - setPending("unlink");
84 - const result = await unlink({ accountId });
85 - if (result._tag === "Success") {
86 - setLinkUrl(null);
87 - linkState.refresh();
88 - } else if (!isAtomCommandInterrupted(result)) {
89 - reportFailure("Could not unlink T3 Chat", squashAtomCommandFailure(result));
90 - }
91 - setPending(null);
92 - };
39 + const { linkState, pending, linkUrl, link: handleLink, unlink: handleUnlink } = useT3ChatLink();
40 + const usage = useManagedTunnelUsage();
41
42 const data = linkState.data;
43 const link = data?.link ?? null;
@@ -102,7 +50,7 @@ export function T3ChatUserProfilePage() {
50 <ClerkUserProfileRefreshButton
51 disabled={pending !== null}
52 isPending={linkState.isPending}
105 - onClick={linkState.refresh}
53 + onClick={usage.refresh}
54 />
55 }
56 >
@@ -160,6 +108,11 @@ export function T3ChatUserProfilePage() {
108 )}
109 </div>
110 </ClerkUserProfileRow>
111 + {usage.used !== null && usage.limit !== null ? (
112 + <li className="border-t py-4">
113 + <TunnelUsageMeter used={usage.used} limit={usage.limit} />
114 + </li>
115 + ) : null}
116 </ul>
117 )}
118 </ClerkUserProfilePage>
apps/web/src/components/clerk/T3ConnectAccountPages.tsx
+5 -3
@@ -28,22 +28,24 @@ export const T3_CONNECT_ACCOUNT_PAGES = [
28 },
29 ] as const;
30
31 +export type T3ConnectAccountPageUrl = (typeof T3_CONNECT_ACCOUNT_PAGES)[number]["url"];
32 +
33 type PortalTargets = Readonly<Record<string, HTMLDivElement | undefined>>;
34
35 /** Keep portals rendered while the modal can open; Clerk owns the custom-page DOM nodes. */
36 export function useT3ConnectAccountPage(): {
35 - readonly open: (() => void) | null;
37 + readonly open: ((page?: T3ConnectAccountPageUrl) => void) | null;
38 readonly portals: ReactNode;
39 } {
40 const clerk = useClerk();
41 const { isSignedIn } = useAuth();
42 const [targets, setTargets] = useState<PortalTargets>({});
43
42 - const open = () => {
44 + const open = (page: T3ConnectAccountPageUrl = "t3-connect") => {
45 const setTarget = (key: string, element: HTMLDivElement | undefined) =>
46 setTargets((current) => ({ ...current, [key]: element }));
47 clerk.openUserProfile({
46 - __experimental_startPath: "/t3-connect",
48 + __experimental_startPath: `/${page}`,
49 customPages: T3_CONNECT_ACCOUNT_PAGES.map((page) => ({
50 label: page.label,
51 url: page.url,
apps/web/src/components/clerk/T3ConnectUserProfilePage.tsx
+55 -2
@@ -11,9 +11,11 @@ import { useRef, useState } from "react";
11 import {
12 deregisterManagedRelayEnvironmentCommand,
13 useManagedRelayEnvironments,
14 + useManagedTunnelUsage,
15 } from "../../cloud/managedRelayState";
16 import { useAtomCommand } from "../../state/use-atom-command";
16 -import { Button } from "../ui/button";
17 +import { T3CHAT_SUBSCRIPTION_URL, TunnelUsageMeter, tunnelUpgradeCopy } from "../cloud/TunnelUsage";
18 +import { Button, InlineButton } from "../ui/button";
19 import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
20 import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";
21 import { toastManager } from "../ui/toast";
@@ -22,6 +24,7 @@ import {
24 ClerkUserProfileRefreshButton,
25 ClerkUserProfileRow,
26 } from "./ClerkUserProfilePage";
27 +import { useT3ChatLink } from "./useT3ChatLink";
28
29 const linkedAtFormatter = new Intl.DateTimeFormat(undefined, { dateStyle: "medium" });
30
@@ -110,6 +113,53 @@ function T3ConnectEnvironmentRow(props: {
113 );
114 }
115
116 +function T3ConnectTunnelUsage() {
117 + const usage = useManagedTunnelUsage();
118 + const t3Chat = useT3ChatLink();
119 + if (usage.used === null || usage.limit === null) return null;
120 + return (
121 + <div className="border-t py-4">
122 + <TunnelUsageMeter used={usage.used} limit={usage.limit} />
123 + {usage.upgrade ? (
124 + <p className="mt-2 text-xs leading-4.5 text-muted-foreground">
125 + {usage.upgrade === "link" && t3Chat.linkUrl ? (
126 + <>
127 + Confirm on{" "}
128 + <a
129 + className="underline"
130 + href={t3Chat.linkUrl}
131 + target="_blank"
132 + rel="noopener noreferrer"
133 + >
134 + t3.chat
135 + </a>
136 + , then select Refresh.
137 + </>
138 + ) : (
139 + <>
140 + {tunnelUpgradeCopy(usage.upgrade)}{" "}
141 + {usage.upgrade === "link" ? (
142 + <InlineButton disabled={t3Chat.pending !== null} onClick={() => void t3Chat.link()}>
143 + {t3Chat.pending === "link" ? "Opening…" : "Link T3 Chat"}
144 + </InlineButton>
145 + ) : (
146 + <a
147 + className="underline"
148 + href={T3CHAT_SUBSCRIPTION_URL}
149 + target="_blank"
150 + rel="noopener noreferrer"
151 + >
152 + Upgrade on T3 Chat
153 + </a>
154 + )}
155 + </>
156 + )}
157 + </p>
158 + ) : null}
159 + </div>
160 + );
161 +}
162 +
163 export function T3ConnectUserProfilePage() {
164 const environmentsState = useManagedRelayEnvironments();
165 const deregisterEnvironment = useAtomCommand(deregisterManagedRelayEnvironmentCommand, {
@@ -188,6 +238,8 @@ export function T3ConnectUserProfilePage() {
238 (environment) =>
239 removedEnvironmentLinkedAt.get(environment.environmentId) !== environment.linkedAt,
240 );
241 + const usage = useManagedTunnelUsage();
242 + const refreshAll = usage.refresh;
243 const isInitialLoad =
244 !environmentsState.accountId || (environmentsState.data === null && !environmentsState.error);
245
@@ -199,11 +251,12 @@ export function T3ConnectUserProfilePage() {
251 <ClerkUserProfileRefreshButton
252 disabled={deregisteringEnvironmentId !== null}
253 isPending={environmentsState.isPending}
202 - onClick={environmentsState.refresh}
254 + onClick={refreshAll}
255 />
256 }
257 >
258 <div>
259 + <T3ConnectTunnelUsage />
260 {environmentsState.error ? (
261 <div className="mb-4 border-t border-destructive/35 py-3 text-xs" role="alert">
262 <p className="font-medium text-destructive-foreground">
apps/web/src/components/clerk/useT3ChatLink.ts new
+76
@@ -0,0 +1,76 @@
1 +import { findErrorTraceId } from "@t3tools/client-runtime/errors";
2 +import {
3 + isAtomCommandInterrupted,
4 + squashAtomCommandFailure,
5 +} from "@t3tools/client-runtime/state/runtime";
6 +import { useState } from "react";
7 +
8 +import {
9 + createManagedRelayT3ChatLinkRequestCommand,
10 + unlinkManagedRelayT3ChatCommand,
11 + useManagedRelayT3ChatLink,
12 +} from "../../cloud/managedRelayState";
13 +import { readLocalApi } from "../../localApi";
14 +import { useAtomCommand } from "../../state/use-atom-command";
15 +import { toastManager } from "../ui/toast";
16 +
17 +function reportFailure(title: string, cause: unknown) {
18 + const traceId = findErrorTraceId(cause);
19 + toastManager.add({
20 + type: "error",
21 + title,
22 + description: cause instanceof Error ? cause.message : "Try again.",
23 + data: traceId
24 + ? {
25 + secondaryActionProps: {
26 + children: "Copy trace ID",
27 + onClick: () => void navigator.clipboard?.writeText(traceId),
28 + },
29 + }
30 + : undefined,
31 + });
32 +}
33 +
34 +/** Starts and removes the T3 Chat link that raises the T3 Connect tunnel cap. */
35 +export function useT3ChatLink() {
36 + const linkState = useManagedRelayT3ChatLink();
37 + const createLinkRequest = useAtomCommand(createManagedRelayT3ChatLinkRequestCommand, {
38 + reportFailure: false,
39 + });
40 + const unlinkCommand = useAtomCommand(unlinkManagedRelayT3ChatCommand, { reportFailure: false });
41 + const [pending, setPending] = useState<"link" | "unlink" | null>(null);
42 + // Kept so a blocked popup still leaves the user a link to open.
43 + const [linkUrl, setLinkUrl] = useState<string | null>(null);
44 +
45 + const link = async () => {
46 + const accountId = linkState.accountId;
47 + if (!accountId || pending) return;
48 + setPending("link");
49 + const result = await createLinkRequest({ accountId });
50 + if (result._tag === "Success") {
51 + setLinkUrl(result.value);
52 + await readLocalApi()
53 + ?.shell.openExternal(result.value)
54 + .catch(() => undefined);
55 + } else if (!isAtomCommandInterrupted(result)) {
56 + reportFailure("Could not start linking", squashAtomCommandFailure(result));
57 + }
58 + setPending(null);
59 + };
60 +
61 + const unlink = async () => {
62 + const accountId = linkState.accountId;
63 + if (!accountId || pending) return;
64 + setPending("unlink");
65 + const result = await unlinkCommand({ accountId });
66 + if (result._tag === "Success") {
67 + setLinkUrl(null);
68 + linkState.refresh();
69 + } else if (!isAtomCommandInterrupted(result)) {
70 + reportFailure("Could not unlink T3 Chat", squashAtomCommandFailure(result));
71 + }
72 + setPending(null);
73 + };
74 +
75 + return { linkState, pending, linkUrl, link, unlink };
76 +}
apps/web/src/components/cloud/ConnectOnboardingDialog.tsx
+42
@@ -9,6 +9,7 @@ import {
9 ConnectOnboardingOptOutSchema,
10 EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE,
11 } from "~/cloud/connectOnboarding";
12 +import { useManagedTunnelUsage } from "~/cloud/managedRelayState";
13 import { hasCloudPublicConfig } from "~/cloud/publicConfig";
14 import { useCloudLinkController } from "~/cloud/useCloudLinkController";
15 import { useLocalStorage } from "~/hooks/useLocalStorage";
@@ -19,7 +20,12 @@ import {
20 usePrimaryEnvironmentId,
21 } from "~/state/environments";
22 import { environmentSession, readEnvironmentScope, useEnvironmentScope } from "~/state/session";
23 +import {
24 + type T3ConnectAccountPageUrl,
25 + useT3ConnectAccountPage,
26 +} from "../clerk/T3ConnectAccountPages";
27 import { CloudEnvironmentConnectRows } from "./CloudEnvironmentConnectList";
28 +import { TunnelLimitAlert } from "./TunnelUsage";
29 import { Button } from "../ui/button";
30 import { Checkbox } from "../ui/checkbox";
31 import { Dialog } from "../ui/dialog";
@@ -63,6 +69,7 @@ function ConfiguredConnectOnboardingDialog() {
69 primaryEnvironmentId === null ? environmentsReady : primarySessionState._tag !== "Initial";
70
71 const controller = useCloudLinkController();
72 + const accountPage = useT3ConnectAccountPage();
73 const showPublishStep = canManageRelay && controller.linkState.target !== null;
74 const steps: ReadonlyArray<OnboardingStep> = showPublishStep
75 ? ["publish", "devices"]
@@ -180,6 +187,15 @@ function ConfiguredConnectOnboardingDialog() {
187 setStep("devices");
188 };
189
190 + const openAccountPage = accountPage.open;
191 + // The account page is a Clerk modal, so close this dialog before it opens.
192 + const leaveForAccountPage = openAccountPage
193 + ? (page: T3ConnectAccountPageUrl) => {
194 + complete();
195 + openAccountPage(page);
196 + }
197 + : null;
198 +
199 return (
200 <Dialog
201 open={openForAccount !== null}
@@ -223,6 +239,8 @@ function ConfiguredConnectOnboardingDialog() {
239 publishAgentActivity={publishAgentActivity}
240 disabled={isApplying || !canManageRelay || linkStateData === null}
241 operationError={controller.operationError ?? controller.linkState.error}
242 + tunnelLimit={controller.tunnelLimit}
243 + onOpenAccountPage={leaveForAccountPage}
244 onExposeEnvironmentChange={(enabled) => {
245 if (
246 primaryEnvironmentId !== null &&
@@ -274,6 +292,8 @@ function ConfiguredConnectOnboardingDialog() {
292 )}
293 </WizardFooter>
294 </WizardPopup>
295 + {/* Base UI renders Root children while closed, so this keeps the account page mounted. */}
296 + {accountPage.portals}
297 </Dialog>
298 );
299 }
@@ -288,6 +308,8 @@ function PublishStep({
308 publishAgentActivity,
309 disabled,
310 operationError,
311 + tunnelLimit,
312 + onOpenAccountPage,
313 onExposeEnvironmentChange,
314 onPublishAgentActivityChange,
315 }: {
@@ -295,6 +317,8 @@ function PublishStep({
317 readonly publishAgentActivity: boolean;
318 readonly disabled: boolean;
319 readonly operationError: string | null;
320 + readonly tunnelLimit: number | null;
321 + readonly onOpenAccountPage: ((page: T3ConnectAccountPageUrl) => void) | null;
322 readonly onExposeEnvironmentChange: (enabled: boolean) => void;
323 readonly onPublishAgentActivityChange: (enabled: boolean) => void;
324 }) {
@@ -317,10 +341,28 @@ function PublishStep({
341 />
342 </div>
343 {operationError ? <p className="text-xs text-destructive">{operationError}</p> : null}
344 + {tunnelLimit !== null ? (
345 + <OnboardingTunnelLimitAlert onOpenAccountPage={onOpenAccountPage} />
346 + ) : null}
347 </div>
348 );
349 }
350
351 +function OnboardingTunnelLimitAlert({
352 + onOpenAccountPage,
353 +}: {
354 + readonly onOpenAccountPage: ((page: T3ConnectAccountPageUrl) => void) | null;
355 +}) {
356 + const { upgrade } = useManagedTunnelUsage();
357 + return (
358 + <TunnelLimitAlert
359 + upgrade={upgrade}
360 + onLinkT3Chat={onOpenAccountPage ? () => onOpenAccountPage("t3-chat") : null}
361 + onManageTunnels={onOpenAccountPage ? () => onOpenAccountPage("t3-connect") : null}
362 + />
363 + );
364 +}
365 +
366 function OnboardingToggleRow({
367 title,
368 description,
apps/web/src/components/cloud/TunnelUsage.tsx new
+118
@@ -0,0 +1,118 @@
1 +import { T3CHAT_PLAN_TUNNEL_LIMITS } from "@t3tools/contracts/relay";
2 +import { TriangleAlertIcon } from "lucide-react";
3 +import type { ReactNode } from "react";
4 +
5 +import type { ManagedTunnelUpgrade } from "../../cloud/managedRelayState";
6 +import { cn } from "../../lib/utils";
7 +import { Alert, AlertAction, AlertDescription, AlertTitle } from "../ui/alert";
8 +import { Button } from "../ui/button";
9 +
10 +// Above this, one slot per tunnel is too thin to read, so the bar fills instead.
11 +const MAX_SEGMENTS = 10;
12 +
13 +export const T3CHAT_SUBSCRIPTION_URL = "https://t3.chat/settings/subscription";
14 +
15 +export function tunnelUpgradeCopy(upgrade: Exclude<ManagedTunnelUpgrade, null>): string {
16 + const { pro, premier } = T3CHAT_PLAN_TUNNEL_LIMITS;
17 + switch (upgrade) {
18 + case "link":
19 + return `Link T3 Chat Pro for up to ${pro} tunnels, or Premier for up to ${premier}.`;
20 + case "pro":
21 + return `Upgrade to T3 Chat Pro for up to ${pro} tunnels, or Premier for up to ${premier}.`;
22 + case "premier":
23 + return `Upgrade to T3 Chat Premier for up to ${premier} tunnels.`;
24 + }
25 +}
26 +
27 +/** "2 of 3 tunnels in use" with one bar slot per tunnel. */
28 +export function TunnelUsageMeter({
29 + used,
30 + limit,
31 + action,
32 + className,
33 +}: {
34 + readonly used: number;
35 + readonly limit: number;
36 + readonly action?: ReactNode;
37 + readonly className?: string;
38 +}) {
39 + const full = used >= limit;
40 + const fill = full ? "bg-warning" : "bg-foreground/72";
41 + return (
42 + <div className={cn("flex max-w-sm flex-col gap-1.5", className)}>
43 + <div className="flex items-baseline justify-between gap-3 text-xs">
44 + <span className={cn("tabular-nums", full ? "text-warning-foreground" : "text-foreground")}>
45 + {used} of {limit} tunnels in use
46 + </span>
47 + {action}
48 + </div>
49 + <div
50 + role="meter"
51 + aria-label="T3 Connect tunnels in use"
52 + aria-valuemin={0}
53 + aria-valuemax={limit}
54 + aria-valuenow={used}
55 + className="flex h-1.5 gap-1"
56 + >
57 + {limit <= MAX_SEGMENTS ? (
58 + Array.from({ length: limit }, (_, index) => (
59 + <span
60 + key={index}
61 + className={cn("flex-1 rounded-full", index < used ? fill : "bg-muted")}
62 + />
63 + ))
64 + ) : (
65 + <span className="flex-1 overflow-hidden rounded-full bg-muted">
66 + <span
67 + className={cn("block h-full rounded-full", fill)}
68 + style={{ width: `${Math.min(100, (used / limit) * 100)}%` }}
69 + />
70 + </span>
71 + )}
72 + </div>
73 + </div>
74 + );
75 +}
76 +
77 +/** Shown when the relay refuses a new tunnel because the account is at its cap. */
78 +export function TunnelLimitAlert({
79 + upgrade,
80 + onLinkT3Chat,
81 + onManageTunnels,
82 +}: {
83 + readonly upgrade: ManagedTunnelUpgrade;
84 + readonly onLinkT3Chat: (() => void) | null;
85 + readonly onManageTunnels: (() => void) | null;
86 +}) {
87 + const action =
88 + upgrade === "link" && onLinkT3Chat ? (
89 + <Button size="sm" onClick={onLinkT3Chat}>
90 + Link T3 Chat
91 + </Button>
92 + ) : upgrade === "pro" || upgrade === "premier" ? (
93 + <Button
94 + size="sm"
95 + render={<a href={T3CHAT_SUBSCRIPTION_URL} target="_blank" rel="noopener noreferrer" />}
96 + >
97 + Upgrade on T3 Chat
98 + </Button>
99 + ) : onManageTunnels ? (
100 + <Button size="sm" variant="outline" onClick={onManageTunnels}>
101 + Manage tunnels
102 + </Button>
103 + ) : null;
104 + return (
105 + <Alert variant="warning">
106 + <TriangleAlertIcon />
107 + <AlertTitle>You&apos;re out of tunnels (they cost us money).</AlertTitle>
108 + <AlertDescription>
109 + {upgrade === "link"
110 + ? "Switch to Tailscale or get more tunnels by linking your T3 Chat sub (sorry!)"
111 + : upgrade
112 + ? "Switch to Tailscale or get more tunnels by upgrading your T3 Chat sub (sorry!)"
113 + : "Switch to Tailscale or deregister an environment you no longer use (sorry!)"}
114 + </AlertDescription>
115 + {action ? <AlertAction>{action}</AlertAction> : null}
116 + </Alert>
117 + );
118 +}
apps/web/src/components/settings/SavedEnvironmentRows.tsx
+58 -2
@@ -39,7 +39,7 @@ import { Menu, MenuItem, MenuPopup, MenuSeparator, MenuTrigger } from "../ui/men
39 import { Switch } from "../ui/switch";
40 import { stackedThreadToast, toastManager } from "../ui/toast";
41 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
42 -import { Button } from "../ui/button";
42 +import { Button, InlineButton } from "../ui/button";
43 import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";
44 import {
45 resolveServerConfigVersionMismatch,
@@ -49,6 +49,9 @@ import {
49 import { hasCloudPublicConfig } from "~/cloud/publicConfig";
50 import { isElectron } from "~/env";
51 import { useCloudLinkController } from "~/cloud/useCloudLinkController";
52 +import { useManagedTunnelUsage } from "~/cloud/managedRelayState";
53 +import { useT3ConnectAccountPage } from "../clerk/T3ConnectAccountPages";
54 +import { TunnelLimitAlert, TunnelUsageMeter } from "../cloud/TunnelUsage";
55 import { environmentCatalog } from "~/connection/catalog";
56 import { readEnvironmentScope } from "~/state/session";
57 import {
@@ -463,6 +466,56 @@ function CloudLinkSwitch({
466 );
467 }
468
469 +/** Tunnel meter, plus the upgrade prompt after the relay refuses a tunnel at the cap. */
470 +function T3ConnectTunnelUsage({ tunnelLimit }: { readonly tunnelLimit: number | null }) {
471 + const usage = useManagedTunnelUsage();
472 + const accountPage = useT3ConnectAccountPage();
473 + const openAccountPage = accountPage.open;
474 + // Usage when the relay refused. The relay also counts tunnels still being set up, so only
475 + // a freed tunnel or a higher cap clears the alert, not a meter that merely shows room.
476 + const [usedAtRefusal, setUsedAtRefusal] = useState<number | null>(null);
477 + if (tunnelLimit === null) {
478 + if (usedAtRefusal !== null) setUsedAtRefusal(null);
479 + } else if (usedAtRefusal === null && usage.used !== null) {
480 + setUsedAtRefusal(usage.used);
481 + }
482 + const showLimitAlert =
483 + tunnelLimit !== null &&
484 + !(usedAtRefusal !== null && usage.used !== null && usage.used < usedAtRefusal) &&
485 + !(usage.limit !== null && usage.limit > tunnelLimit);
486 + const meter =
487 + usage.used !== null && usage.limit !== null ? (
488 + <TunnelUsageMeter
489 + used={usage.used}
490 + limit={usage.limit}
491 + action={
492 + // At the cap the alert below carries the same action.
493 + usage.upgrade && openAccountPage && !showLimitAlert ? (
494 + <InlineButton onClick={() => openAccountPage("t3-chat")}>Get more tunnels</InlineButton>
495 + ) : null
496 + }
497 + />
498 + ) : null;
499 + return (
500 + <>
501 + {meter || showLimitAlert ? (
502 + <div className="flex flex-col gap-3 pb-3">
503 + {meter}
504 + {showLimitAlert ? (
505 + <TunnelLimitAlert
506 + upgrade={usage.upgrade}
507 + onLinkT3Chat={openAccountPage ? () => openAccountPage("t3-chat") : null}
508 + onManageTunnels={openAccountPage ? () => openAccountPage("t3-connect") : null}
509 + />
510 + ) : null}
511 + </div>
512 + ) : null}
513 + {/* Kept outside the conditional so an open account page does not remount. */}
514 + {accountPage.portals}
515 + </>
516 + );
517 +}
518 +
519 function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: boolean }) {
520 const primaryEnvironmentId = usePrimaryEnvironmentId();
521 const {
@@ -474,6 +527,7 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
527 publishAgentActivity,
528 holdWebhooksWhileOffline,
529 operationError,
530 + tunnelLimit,
531 reconcileCloudState,
532 } = useCloudLinkController();
533 const { openAuthPrompt } = useT3ConnectAuthPrompt();
@@ -625,7 +679,9 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
679 />
680 )
681 }
628 - />
682 + >
683 + {signedOut ? null : <T3ConnectTunnelUsage tunnelLimit={tunnelLimit} />}
684 + </SettingsRow>
685 ) : linkRevoked ? (
686 <SettingsRow
687 title={searchableSetting("t3-connect").title}
apps/web/src/components/settings/settingsSearch.ts
+1 -1
@@ -1058,7 +1058,7 @@ export const SETTINGS_SEARCH_ITEMS = [
1058 title: "T3 Connect",
1059 to: "/settings/access",
1060 targetId: "connections-environment",
1061 - searchTerms: ["managed tunnel cloud other devices remote"],
1061 + searchTerms: ["managed tunnel cloud other devices remote tunnels limit t3 chat"],
1062 desktopOnly: true,
1063 cloudOnly: true,
1064 },
infra/relay/src/environments/ManagedTunnelLimits.test.ts
+3 -3
@@ -9,7 +9,7 @@ import { PGlite } from "@electric-sql/pglite";
9 import { drizzle } from "drizzle-orm/pglite";
10 import { ne } from "drizzle-orm";
11 import { PgDialect } from "drizzle-orm/pg-core";
12 -import type { RelayT3ChatPlan } from "@t3tools/contracts/relay";
12 +import { DEFAULT_MANAGED_TUNNEL_LIMIT, type RelayT3ChatPlan } from "@t3tools/contracts/relay";
13
14 import * as RelayDb from "../db.ts";
15 import { relayManagedEndpointAllocations } from "../persistence/schema.ts";
@@ -124,7 +124,7 @@ const reserve = (
124 describe("ManagedTunnelLimits", () => {
125 it.effect("rejects concurrent reservations past the limit", () => {
126 const reserved: Array<string> = [];
127 - const attempts = ManagedTunnelLimits.DEFAULT_MANAGED_TUNNEL_LIMIT + 2;
127 + const attempts = DEFAULT_MANAGED_TUNNEL_LIMIT + 2;
128
129 return Effect.gen(function* () {
130 const limits = yield* ManagedTunnelLimits.ManagedTunnelLimits;
@@ -140,7 +140,7 @@ describe("ManagedTunnelLimits", () => {
140 { concurrency: "unbounded" },
141 );
142
143 - expect(reserved).toHaveLength(ManagedTunnelLimits.DEFAULT_MANAGED_TUNNEL_LIMIT);
143 + expect(reserved).toHaveLength(DEFAULT_MANAGED_TUNNEL_LIMIT);
144 expect(
145 results.filter(
146 (result) =>
infra/relay/src/environments/ManagedTunnelLimits.ts
+1 -2
@@ -6,7 +6,7 @@ import * as Effect from "effect/Effect";
6 import * as Layer from "effect/Layer";
7 import * as Schema from "effect/Schema";
8 import * as SqlError from "effect/sql/SqlError";
9 -import { T3CHAT_PLAN_TUNNEL_LIMITS } from "@t3tools/contracts/relay";
9 +import { DEFAULT_MANAGED_TUNNEL_LIMIT, T3CHAT_PLAN_TUNNEL_LIMITS } from "@t3tools/contracts/relay";
10
11 import * as RelayDb from "../db.ts";
12 import {
@@ -16,7 +16,6 @@ import {
16 } from "../persistence/schema.ts";
17 import * as T3ChatAccounts from "../t3chat/T3ChatAccounts.ts";
18
19 -export const DEFAULT_MANAGED_TUNNEL_LIMIT = 3;
19 // Reserve-to-tunnel takes two Cloudflare calls capped at 8 seconds each; a reservation older than this was abandoned.
20 const MANAGED_TUNNEL_PENDING_WINDOW_MINUTES = 15;
21
packages/contracts/src/relay.ts
+2
@@ -966,6 +966,8 @@ export type RelayOkResponse = typeof RelayOkResponse.Type;
966 export const RelayT3ChatPlan = Schema.Literals(["free", "pro", "premier"]);
967 export type RelayT3ChatPlan = typeof RelayT3ChatPlan.Type;
968
969 +export const DEFAULT_MANAGED_TUNNEL_LIMIT = 3;
970 +
971 // A linked paid T3 Chat plan raises the default managed tunnel cap.
972 export const T3CHAT_PLAN_TUNNEL_LIMITS = { pro: 10, premier: 100 } as const;
973