Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 54 additions & 4 deletions apps/web/src/cloud/managedRelayState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@ import {
createAtomCommandScheduler,
createRuntimeCommand,
} from "@t3tools/client-runtime/state/runtime";
import type {
RelayClientDeviceRecord,
RelayClientEnvironmentRecord,
RelayT3ChatLinkResponse,
import {
DEFAULT_MANAGED_TUNNEL_LIMIT,
T3CHAT_PLAN_TUNNEL_LIMITS,
type RelayClientDeviceRecord,
type RelayClientEnvironmentRecord,
type RelayT3ChatLinkResponse,
} from "@t3tools/contracts/relay";
import type { EnvironmentId } from "@t3tools/contracts";
import * as Context from "effect/Context";
Expand Down Expand Up @@ -144,3 +146,51 @@ export function useManagedRelayDevices() {
refresh,
};
}

/** How this account can raise its tunnel cap: link T3 Chat, or upgrade the linked plan. */
export type ManagedTunnelUpgrade = "link" | "pro" | "premier" | null;

// Mirrors the relay's cap without manual overrides, which the relay does not expose.
function managedTunnelCap(t3Chat: RelayT3ChatLinkResponse): {
readonly limit: number;
readonly upgrade: ManagedTunnelUpgrade;
} {
if (!t3Chat.available) return { limit: DEFAULT_MANAGED_TUNNEL_LIMIT, upgrade: null };
switch (t3Chat.link?.plan) {
case "premier":
return { limit: T3CHAT_PLAN_TUNNEL_LIMITS.premier, upgrade: null };
case "pro":
return { limit: T3CHAT_PLAN_TUNNEL_LIMITS.pro, upgrade: "premier" };
case "free":
return { limit: DEFAULT_MANAGED_TUNNEL_LIMIT, upgrade: "pro" };
case undefined:
return { limit: DEFAULT_MANAGED_TUNNEL_LIMIT, upgrade: "link" };
}
}

/** Refetches the account's environments and T3 Chat plan after a tunnel changes. */
export function refreshManagedTunnelUsage() {
const accountId = appAtomRegistry.get(managedRelaySessionAtom)?.accountId;
if (!accountId) return;
managedRelayQueryManager.refreshEnvironments(appAtomRegistry, accountId);
managedRelayQueryManager.refreshT3ChatLink(appAtomRegistry, accountId);
}

/** Managed tunnels on this account and its cap. Null fields are still loading or failed. */
export function useManagedTunnelUsage() {
const environments = useManagedRelayEnvironments();
const t3Chat = useManagedRelayT3ChatLink();
const used =
environments.accountId === null
? null
: (environments.data?.filter(
(environment) => environment.endpoint.providerKind === "cloudflare_tunnel",
).length ?? null);
const cap = t3Chat.accountId !== null && t3Chat.data ? managedTunnelCap(t3Chat.data) : null;
return {
used,
limit: cap?.limit ?? null,
upgrade: cap?.upgrade ?? null,
refresh: refreshManagedTunnelUsage,
};
}
42 changes: 38 additions & 4 deletions apps/web/src/cloud/useCloudLinkController.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@ import {
EnvironmentId,
type EnvironmentCloudLinkStateResult,
} from "@t3tools/contracts";
import type { RelayManagedEndpointProviderKind } from "@t3tools/contracts/relay";
import { ManagedRelay } from "@t3tools/client-runtime/relay";
import {
RelayEnvironmentLinkLimitExceededError,
type RelayManagedEndpointProviderKind,
} from "@t3tools/contracts/relay";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/reactivity";
import { useLayoutEffect } from "react";
import { describe, expect, it, vi } from "vite-plus/test";
Expand Down Expand Up @@ -88,6 +93,7 @@ vi.mock(import("./publicConfig"), async (original) => ({
resolveRelayClerkTokenOptions: () => ({}) as never,
}));

import { CloudEnvironmentLinkError } from "./linkEnvironment";
import { useCloudLinkController, type CloudLinkDesiredState } from "./useCloudLinkController";

const target = {
Expand Down Expand Up @@ -125,9 +131,8 @@ async function mountController() {
/>,
);
return Object.assign(screen, {
get controller() {
return controller;
},
// Object.assign would copy a getter's value once, so read the latest render through a function.
controller: () => controller,
async reconcile(desired: CloudLinkDesiredState) {
let succeeded = false;
await act(async () => {
Expand Down Expand Up @@ -225,4 +230,33 @@ describe("useCloudLinkController", () => {
expect(testState.link).not.toHaveBeenCalled();
expect(testState.preferences).not.toHaveBeenCalled();
});

it("reports a relay tunnel cap refusal as tunnelLimit instead of an error", async () => {
using _setup = setup();
testState.snapshot = { ...linkedState, linked: false, managedTunnelActive: false };
testState.link.mockResolvedValueOnce(
AsyncResult.failure(
Cause.fail(
new CloudEnvironmentLinkError({
message: "environment-links failed",
cause: new ManagedRelay.ManagedRelayRequestFailedError({
action: "link relay environment",
cause: null,
relayError: new RelayEnvironmentLinkLimitExceededError({
code: "environment_link_limit_exceeded",
maxTunnels: 3,
traceId: "trace-1",
}),
}),
}),
),
),
);
await using screen = await mountController();

expect(await screen.reconcile({ managedTunnel: true, publish: false })).toBe(false);
expect(screen.controller()?.tunnelLimit).toBe(3);
expect(screen.controller()?.operationError).toBeNull();
expect(testState.toast).not.toHaveBeenCalled();
});
});
28 changes: 27 additions & 1 deletion apps/web/src/cloud/useCloudLinkController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,22 @@ import {
AuthRelayWriteScope,
type EnvironmentCloudLinkStateResult,
} from "@t3tools/contracts";
import { ManagedRelay } from "@t3tools/client-runtime/relay";
import type { RelayManagedEndpointProviderKind } from "@t3tools/contracts/relay";
import {
isAtomCommandInterrupted,
settlePromise,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import * as Schema from "effect/Schema";
import { useState } from "react";

import { toastManager } from "../components/ui/toast";
import { relayEnvironmentDiscovery } from "../state/relay";
import { readEnvironmentScope } from "../state/session";
import { useAtomCommand } from "../state/use-atom-command";
import { CloudEnvironmentLinkError } from "./linkEnvironment";
import { refreshManagedTunnelUsage } from "./managedRelayState";
import {
linkPrimaryEnvironment as linkPrimaryEnvironmentAtom,
unlinkPrimaryEnvironment as unlinkPrimaryEnvironmentAtom,
Expand Down Expand Up @@ -46,6 +50,18 @@ function isManagedTunnelActive(
);
}

const isManagedRelayRequestFailedError = Schema.is(ManagedRelay.ManagedRelayRequestFailedError);

/** The account's tunnel cap when the relay refused a new tunnel for being at it. */
function tunnelLimitFromLinkFailure(cause: unknown): number | null {
if (!(cause instanceof CloudEnvironmentLinkError)) return null;
const relayCause = cause.cause;
if (!isManagedRelayRequestFailedError(relayCause)) return null;
return relayCause.relayError?._tag === "RelayEnvironmentLinkLimitExceededError"
? relayCause.relayError.maxTunnels
: null;
}

export function useCloudLinkController() {
const { getToken, isSignedIn } = useAuth();
const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
Expand All @@ -68,6 +84,7 @@ export function useCloudLinkController() {
? relayEnvironments.get(primaryEnvironmentId)?.environment.endpoint.providerKind
: undefined;
const [operationError, setOperationError] = useState<string | null>(null);
const [tunnelLimit, setTunnelLimit] = useState<number | null>(null);

const reportUpdateFailure = (cause: unknown) => {
const message = cause instanceof Error ? cause.message : "Could not update T3 Connect access.";
Expand Down Expand Up @@ -100,6 +117,7 @@ export function useCloudLinkController() {

const reconcileCloudState = async (desired: CloudLinkDesiredState): Promise<boolean> => {
setOperationError(null);
setTunnelLimit(null);
const target = primaryCloudLinkState.target;
if (!target) {
reportUpdateFailure(new Error("Local environment is not ready yet."));
Expand Down Expand Up @@ -138,6 +156,7 @@ export function useCloudLinkController() {
target,
clerkToken: tokenResult._tag === "Success" ? (tokenResult.value ?? null) : null,
});
refreshManagedTunnelUsage();
if (unlinkResult._tag === "Failure") {
if (!isAtomCommandInterrupted(unlinkResult)) {
reportUpdateFailure(squashAtomCommandFailure(unlinkResult));
Expand Down Expand Up @@ -168,9 +187,15 @@ export function useCloudLinkController() {
clerkToken,
mode: desired.managedTunnel ? "managed" : "publish_only",
});
// Any link attempt can change the account's tunnel count.
refreshManagedTunnelUsage();
if (linkResult._tag === "Failure") {
if (!isAtomCommandInterrupted(linkResult)) {
reportUpdateFailure(squashAtomCommandFailure(linkResult));
const cause = squashAtomCommandFailure(linkResult);
// The caller shows an upgrade prompt instead of an error.
const limit = tunnelLimitFromLinkFailure(cause);
if (limit === null) reportUpdateFailure(cause);
else setTunnelLimit(limit);
}
primaryCloudLinkState.refresh();
return false;
Expand Down Expand Up @@ -215,6 +240,7 @@ export function useCloudLinkController() {
publishAgentActivity,
holdWebhooksWhileOffline,
operationError,
tunnelLimit,
reconcileCloudState,
};
}
99 changes: 26 additions & 73 deletions apps/web/src/components/clerk/T3ChatUserProfilePage.tsx
Original file line number Diff line number Diff line change
@@ -1,95 +1,43 @@
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { T3CHAT_PLAN_TUNNEL_LIMITS, type RelayT3ChatLink } from "@t3tools/contracts/relay";
import { MessageSquareIcon } from "lucide-react";
import { useState } from "react";
import type { ReactNode } from "react";

import {
createManagedRelayT3ChatLinkRequestCommand,
unlinkManagedRelayT3ChatCommand,
useManagedRelayT3ChatLink,
} from "../../cloud/managedRelayState";
import { readLocalApi } from "../../localApi";
import { useAtomCommand } from "../../state/use-atom-command";
import { useManagedTunnelUsage } from "../../cloud/managedRelayState";
import { T3CHAT_SUBSCRIPTION_URL, TunnelUsageMeter } from "../cloud/TunnelUsage";
import { Button } from "../ui/button";
import { toastManager } from "../ui/toast";
import {
ClerkUserProfilePage,
ClerkUserProfileRefreshButton,
ClerkUserProfileRow,
} from "./ClerkUserProfilePage";
import { useT3ChatLink } from "./useT3ChatLink";

function planLabel(link: RelayT3ChatLink): string {
const upgradeLink = (
<a className="underline" href={T3CHAT_SUBSCRIPTION_URL} target="_blank" rel="noopener noreferrer">
Upgrade on T3 Chat
</a>
);

function planLabel(link: RelayT3ChatLink): ReactNode {
switch (link.plan) {
case "premier":
return `Premier · up to ${T3CHAT_PLAN_TUNNEL_LIMITS.premier} tunnels`;
case "pro":
return `Pro · up to ${T3CHAT_PLAN_TUNNEL_LIMITS.pro} tunnels, or ${T3CHAT_PLAN_TUNNEL_LIMITS.premier} with Premier`;
return (
<>
Pro · up to {T3CHAT_PLAN_TUNNEL_LIMITS.pro} tunnels. {upgradeLink} to Premier for{" "}
{T3CHAT_PLAN_TUNNEL_LIMITS.premier}.
</>
);
case "free":
return "Upgrade on T3 Chat for more tunnels";
return <>{upgradeLink} for more tunnels</>;
}
}

function reportFailure(title: string, cause: unknown) {
const traceId = findErrorTraceId(cause);
toastManager.add({
type: "error",
title,
description: cause instanceof Error ? cause.message : "Try again.",
data: traceId
? {
secondaryActionProps: {
children: "Copy trace ID",
onClick: () => void navigator.clipboard?.writeText(traceId),
},
}
: undefined,
});
}

/** Links a T3 Chat account so paid subscribers get more tunnels. */
export function T3ChatUserProfilePage() {
const linkState = useManagedRelayT3ChatLink();
const createLinkRequest = useAtomCommand(createManagedRelayT3ChatLinkRequestCommand, {
reportFailure: false,
});
const unlink = useAtomCommand(unlinkManagedRelayT3ChatCommand, { reportFailure: false });
const [pending, setPending] = useState<"link" | "unlink" | null>(null);
// Kept so a blocked popup still leaves the user a link to open.
const [linkUrl, setLinkUrl] = useState<string | null>(null);

const handleLink = async () => {
const accountId = linkState.accountId;
if (!accountId || pending) return;
setPending("link");
const result = await createLinkRequest({ accountId });
if (result._tag === "Success") {
setLinkUrl(result.value);
await readLocalApi()
?.shell.openExternal(result.value)
.catch(() => undefined);
} else if (!isAtomCommandInterrupted(result)) {
reportFailure("Could not start linking", squashAtomCommandFailure(result));
}
setPending(null);
};

const handleUnlink = async () => {
const accountId = linkState.accountId;
if (!accountId || pending) return;
setPending("unlink");
const result = await unlink({ accountId });
if (result._tag === "Success") {
setLinkUrl(null);
linkState.refresh();
} else if (!isAtomCommandInterrupted(result)) {
reportFailure("Could not unlink T3 Chat", squashAtomCommandFailure(result));
}
setPending(null);
};
const { linkState, pending, linkUrl, link: handleLink, unlink: handleUnlink } = useT3ChatLink();
const usage = useManagedTunnelUsage();

const data = linkState.data;
const link = data?.link ?? null;
Expand All @@ -102,7 +50,7 @@ export function T3ChatUserProfilePage() {
<ClerkUserProfileRefreshButton
disabled={pending !== null}
isPending={linkState.isPending}
onClick={linkState.refresh}
onClick={usage.refresh}
/>
}
>
Expand Down Expand Up @@ -160,6 +108,11 @@ export function T3ChatUserProfilePage() {
)}
</div>
</ClerkUserProfileRow>
{usage.used !== null && usage.limit !== null ? (
<li className="border-t py-4">
<TunnelUsageMeter used={usage.used} limit={usage.limit} />
</li>
) : null}
</ul>
)}
</ClerkUserProfilePage>
Expand Down
8 changes: 5 additions & 3 deletions apps/web/src/components/clerk/T3ConnectAccountPages.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,22 +28,24 @@ export const T3_CONNECT_ACCOUNT_PAGES = [
},
] as const;

export type T3ConnectAccountPageUrl = (typeof T3_CONNECT_ACCOUNT_PAGES)[number]["url"];

type PortalTargets = Readonly<Record<string, HTMLDivElement | undefined>>;

/** Keep portals rendered while the modal can open; Clerk owns the custom-page DOM nodes. */
export function useT3ConnectAccountPage(): {
readonly open: (() => void) | null;
readonly open: ((page?: T3ConnectAccountPageUrl) => void) | null;
readonly portals: ReactNode;
} {
const clerk = useClerk();
const { isSignedIn } = useAuth();
const [targets, setTargets] = useState<PortalTargets>({});

const open = () => {
const open = (page: T3ConnectAccountPageUrl = "t3-connect") => {
const setTarget = (key: string, element: HTMLDivElement | undefined) =>
setTargets((current) => ({ ...current, [key]: element }));
clerk.openUserProfile({
__experimental_startPath: "/t3-connect",
__experimental_startPath: `/${page}`,
customPages: T3_CONNECT_ACCOUNT_PAGES.map((page) => ({
label: page.label,
url: page.url,
Expand Down
Loading
Loading