Skip to content

Commit f7a2cf0

Browse files
t3dotggclaude
andcommitted
feat(relay): link a T3 Chat Premier account for up to 100 tunnels
Experimental. T3 Connect users can link their T3 Chat account from the T3 Connect account dialog. When an account reaches its tunnel cap, the relay asks T3 Chat for the linked plan and allows up to 100 tunnels for Premier. The relay signs the link request with a secret shared with T3 Chat; T3 Chat stores the link. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 7873f53 commit f7a2cf0

23 files changed

Lines changed: 895 additions & 13 deletions

File tree

‎.github/workflows/deploy-relay.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ jobs:
8181
CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }}
8282
APNS_PRIVATE_KEY: ${{ secrets.APNS_PRIVATE_KEY }}
8383
FCM_SERVICE_ACCOUNT: ${{ secrets.FCM_SERVICE_ACCOUNT }}
84+
T3CHAT_LINK_SECRET: ${{ secrets.T3CHAT_LINK_SECRET }}
8485

8586
- name: Publish relay deploy commit status
8687
uses: actions/github-script@v8

‎apps/web/src/cloud/managedRelayState.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
import { useAtomValue } from "@effect/atom-react";
22
import {
33
createManagedRelayQueryManager,
4+
createManagedRelayT3ChatLinkRequest,
45
deregisterManagedRelayEnvironment,
56
ManagedRelay,
67
managedRelaySessionAtom,
78
readManagedRelaySnapshotState,
9+
unlinkManagedRelayT3Chat,
810
} from "@t3tools/client-runtime/relay";
911
import {
1012
createAtomCommandScheduler,
@@ -13,6 +15,7 @@ import {
1315
import type {
1416
RelayClientDeviceRecord,
1517
RelayClientEnvironmentRecord,
18+
RelayT3ChatLinkResponse,
1619
} from "@t3tools/contracts/relay";
1720
import type { EnvironmentId } from "@t3tools/contracts";
1821
import * as Context from "effect/Context";
@@ -50,6 +53,50 @@ export const deregisterManagedRelayEnvironmentCommand = createRuntimeCommand(
5053
},
5154
);
5255

56+
const accountSerial = {
57+
mode: "serial",
58+
key: (input: { readonly accountId: string }) => input.accountId,
59+
} as const;
60+
61+
export const createManagedRelayT3ChatLinkRequestCommand = createRuntimeCommand(
62+
managedRelayAtomRuntime,
63+
{
64+
label: "web:managed-relay:create-t3chat-link-request",
65+
scheduler: managedRelayMutationScheduler,
66+
concurrency: accountSerial,
67+
execute: (input: { readonly accountId: string }, registry) =>
68+
createManagedRelayT3ChatLinkRequest(registry, input),
69+
},
70+
);
71+
72+
export const unlinkManagedRelayT3ChatCommand = createRuntimeCommand(managedRelayAtomRuntime, {
73+
label: "web:managed-relay:unlink-t3chat",
74+
scheduler: managedRelayMutationScheduler,
75+
concurrency: accountSerial,
76+
execute: (input: { readonly accountId: string }, registry) =>
77+
unlinkManagedRelayT3Chat(registry, input),
78+
});
79+
80+
const EMPTY_T3CHAT_LINK_ATOM = Atom.make(
81+
AsyncResult.success<RelayT3ChatLinkResponse>({ available: false, link: null }),
82+
).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:web:t3chat-link:null"));
83+
84+
export function useManagedRelayT3ChatLink() {
85+
const session = useAtomValue(managedRelaySessionAtom);
86+
const accountId = session?.accountId ?? null;
87+
const atom = accountId
88+
? managedRelayQueryManager.t3ChatLinkAtom(accountId)
89+
: EMPTY_T3CHAT_LINK_ATOM;
90+
const snapshot = readManagedRelaySnapshotState(useAtomValue(atom));
91+
const refresh = () => {
92+
if (accountId) {
93+
managedRelayQueryManager.refreshT3ChatLink(appAtomRegistry, accountId);
94+
}
95+
};
96+
97+
return { ...snapshot, accountId, refresh };
98+
}
99+
53100
const EMPTY_ENVIRONMENTS_ATOM = Atom.make(
54101
AsyncResult.success<ReadonlyArray<RelayClientEnvironmentRecord>>([]),
55102
).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:web:environments:null"));
Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
import { findErrorTraceId } from "@t3tools/client-runtime/errors";
2+
import {
3+
isAtomCommandInterrupted,
4+
squashAtomCommandFailure,
5+
} from "@t3tools/client-runtime/state/runtime";
6+
import { T3CHAT_PREMIER_TUNNEL_LIMIT, type RelayT3ChatLink } from "@t3tools/contracts/relay";
7+
import { MessageSquareIcon } from "lucide-react";
8+
import { useState } from "react";
9+
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";
17+
import { Button } from "../ui/button";
18+
import { toastManager } from "../ui/toast";
19+
import {
20+
ClerkUserProfilePage,
21+
ClerkUserProfileRefreshButton,
22+
ClerkUserProfileRow,
23+
} from "./ClerkUserProfilePage";
24+
25+
function planLabel(link: RelayT3ChatLink): string {
26+
return link.plan === "premier"
27+
? `Premier · up to ${T3CHAT_PREMIER_TUNNEL_LIMIT} tunnels`
28+
: "Upgrade to Premier on T3 Chat for more tunnels";
29+
}
30+
31+
function reportFailure(title: string, cause: unknown) {
32+
const traceId = findErrorTraceId(cause);
33+
toastManager.add({
34+
type: "error",
35+
title,
36+
description: cause instanceof Error ? cause.message : "Try again.",
37+
data: traceId
38+
? {
39+
secondaryActionProps: {
40+
children: "Copy trace ID",
41+
onClick: () => void navigator.clipboard?.writeText(traceId),
42+
},
43+
}
44+
: undefined,
45+
});
46+
}
47+
48+
/** Experimental: links a T3 Chat account so Premier subscribers get more tunnels. */
49+
export function T3ChatUserProfilePage() {
50+
const linkState = useManagedRelayT3ChatLink();
51+
const createLinkRequest = useAtomCommand(createManagedRelayT3ChatLinkRequestCommand, {
52+
reportFailure: false,
53+
});
54+
const unlink = useAtomCommand(unlinkManagedRelayT3ChatCommand, { reportFailure: false });
55+
const [pending, setPending] = useState<"link" | "unlink" | null>(null);
56+
// Kept so a blocked popup still leaves the user a link to open.
57+
const [linkUrl, setLinkUrl] = useState<string | null>(null);
58+
59+
const handleLink = async () => {
60+
const accountId = linkState.accountId;
61+
if (!accountId || pending) return;
62+
setPending("link");
63+
const result = await createLinkRequest({ accountId });
64+
if (result._tag === "Success") {
65+
setLinkUrl(result.value);
66+
await readLocalApi()
67+
?.shell.openExternal(result.value)
68+
.catch(() => undefined);
69+
} else if (!isAtomCommandInterrupted(result)) {
70+
reportFailure("Could not start linking", squashAtomCommandFailure(result));
71+
}
72+
setPending(null);
73+
};
74+
75+
const handleUnlink = async () => {
76+
const accountId = linkState.accountId;
77+
if (!accountId || pending) return;
78+
setPending("unlink");
79+
const result = await unlink({ accountId });
80+
if (result._tag === "Success") {
81+
setLinkUrl(null);
82+
linkState.refresh();
83+
} else if (!isAtomCommandInterrupted(result)) {
84+
reportFailure("Could not unlink T3 Chat", squashAtomCommandFailure(result));
85+
}
86+
setPending(null);
87+
};
88+
89+
const data = linkState.data;
90+
const link = data?.link ?? null;
91+
92+
return (
93+
<ClerkUserProfilePage
94+
title="T3 Chat"
95+
description={`Experimental. Link a T3 Chat Premier account to use up to ${T3CHAT_PREMIER_TUNNEL_LIMIT} T3 Connect tunnels.`}
96+
action={
97+
<ClerkUserProfileRefreshButton
98+
disabled={pending !== null}
99+
isPending={linkState.isPending}
100+
onClick={linkState.refresh}
101+
/>
102+
}
103+
>
104+
{linkState.error ? (
105+
<div className="border-t py-3 text-xs" role="alert">
106+
<p className="font-medium text-destructive-foreground">Could not load T3 Chat link</p>
107+
<p className="mt-0.5 text-muted-foreground">{linkState.error}</p>
108+
</div>
109+
) : data === null ? null : !data.available ? (
110+
<p className="border-t py-4 text-xs text-muted-foreground">
111+
This T3 Connect server does not support T3 Chat linking.
112+
</p>
113+
) : (
114+
<ul className="border-t">
115+
<ClerkUserProfileRow icon={<MessageSquareIcon className="size-4" />}>
116+
<div className="flex items-start gap-4">
117+
<div className="min-w-0 flex-1">
118+
<h3 className="truncate text-sm leading-4.5 font-medium text-foreground">
119+
{link ? link.email : "Not linked"}
120+
</h3>
121+
<p className="mt-1 text-xs leading-4.5 text-muted-foreground">
122+
{link ? (
123+
planLabel(link)
124+
) : linkUrl ? (
125+
<>
126+
Confirm on{" "}
127+
<a
128+
className="underline"
129+
href={linkUrl}
130+
target="_blank"
131+
rel="noopener noreferrer"
132+
>
133+
t3.chat
134+
</a>
135+
, then select Refresh.
136+
</>
137+
) : (
138+
"You confirm the link on t3.chat."
139+
)}
140+
</p>
141+
</div>
142+
{link ? (
143+
<Button
144+
size="sm"
145+
variant="destructive-outline"
146+
disabled={pending !== null}
147+
onClick={() => void handleUnlink()}
148+
>
149+
{pending === "unlink" ? "Unlinking…" : "Unlink"}
150+
</Button>
151+
) : (
152+
<Button size="sm" disabled={pending !== null} onClick={() => void handleLink()}>
153+
{pending === "link" ? "Opening…" : "Link T3 Chat"}
154+
</Button>
155+
)}
156+
</div>
157+
</ClerkUserProfileRow>
158+
</ul>
159+
)}
160+
</ClerkUserProfilePage>
161+
);
162+
}

‎apps/web/src/components/clerk/T3ConnectAccountPages.tsx‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import { useAuth, useClerk } from "@clerk/react";
2-
import { ServerIcon, SmartphoneIcon } from "lucide-react";
2+
import { MessageSquareIcon, ServerIcon, SmartphoneIcon } from "lucide-react";
33
import { type ReactNode, useState } from "react";
44
import { createPortal } from "react-dom";
55

66
import { MobileClientsUserProfilePage } from "./MobileClientsUserProfilePage";
7+
import { T3ChatUserProfilePage } from "./T3ChatUserProfilePage";
78
import { T3ConnectUserProfilePage } from "./T3ConnectUserProfilePage";
89

910
export const T3_CONNECT_ACCOUNT_PAGES = [
@@ -19,6 +20,12 @@ export const T3_CONNECT_ACCOUNT_PAGES = [
1920
icon: <ServerIcon className="size-4" />,
2021
content: <T3ConnectUserProfilePage />,
2122
},
23+
{
24+
label: "T3 Chat",
25+
url: "t3-chat",
26+
icon: <MessageSquareIcon className="size-4" />,
27+
content: <T3ChatUserProfilePage />,
28+
},
2229
] as const;
2330

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

‎docs/internals/t3-connect.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,18 @@ and clients keep their bindings. Every mutation on an allocation bumps its
131131
`generation`, and deletion locks the row at the generation it claimed, so a
132132
host that reconnects mid-sweep wins.
133133

134+
## T3 Chat Premier raises the tunnel cap (experimental)
135+
136+
T3 Chat uses WorkOS, not Clerk, so the two accounts are linked by consent
137+
rather than by a shared identity. The relay and T3 Chat share one secret
138+
(`T3CHAT_LINK_SECRET` here, `T3CODE_LINK_SECRET` there). The relay signs a
139+
short-lived token naming the Clerk user and email; the user confirms it while
140+
signed in to T3 Chat, and T3 Chat stores the link. T3 Chat owns the link and the
141+
plan, so the relay keeps no copy. It asks T3 Chat only when an account reaches
142+
its normal cap, and any failure keeps the normal cap. Downgrading does not
143+
remove tunnels that already exist
144+
([limits](../../infra/relay/src/environments/ManagedTunnelLimits.ts)).
145+
134146
## The relay client follows the server's pin
135147

136148
The host runs `cloudflared` pinned by `CLOUDFLARED_VERSION` in

‎docs/operations/release.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,11 @@ Required `production` environment secrets:
147147
- `CLERK_SECRET_KEY`
148148
- `APNS_PRIVATE_KEY`
149149

150+
Optional `production` environment secrets:
151+
152+
- `T3CHAT_LINK_SECRET` for the experimental T3 Chat account link. It must match
153+
`T3CODE_LINK_SECRET` on T3 Chat.
154+
150155
After changing a variable or secret, run the **Deploy T3 Connect relay** workflow manually from
151156
`main` with **force** unchecked. Alchemy compares the values the Worker reads and redeploys it when
152157
one changed. Check **force** only to redeploy resources with no detected change: a forced run also

‎infra/relay/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,8 @@ The `production` GitHub environment must define these Actions secrets:
160160
- `CLERK_SECRET_KEY`
161161
- `APNS_PRIVATE_KEY`
162162
- `FCM_SERVICE_ACCOUNT` when Android push is enabled
163+
- `T3CHAT_LINK_SECRET`, optional, shared with T3 Chat's `T3CODE_LINK_SECRET`. Without it the
164+
experimental T3 Chat account link is off. `T3CHAT_URL` overrides the default `https://t3.chat`.
163165

164166
The account-scoped repository credentials are consumed by Alchemy while provisioning relay stages; they
165167
are not bound into the relay Worker. The production deployment uses an Axiom personal access token,

‎infra/relay/src/Config.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,12 @@ export interface ApnsCredentials {
4848
readonly environment: ApnsEnvironment;
4949
}
5050

51+
export interface T3ChatSettings {
52+
readonly baseUrl: string;
53+
// Shared with T3 Chat: signs link tokens and authenticates relay calls.
54+
readonly linkSecret: Redacted.Redacted<string>;
55+
}
56+
5157
export class RelayConfiguration extends Context.Service<
5258
RelayConfiguration,
5359
{
@@ -65,6 +71,7 @@ export class RelayConfiguration extends Context.Service<
6571
readonly managedEndpointCleanupMode?: ManagedEndpointCleanupMode;
6672
readonly legacyManagedEndpointCleanupMode?: ManagedEndpointCleanupMode;
6773
readonly legacyTunnelGraceMinutes?: number;
74+
readonly t3Chat?: T3ChatSettings;
6875
}
6976
>()("t3code-relay/Config/RelayConfiguration") {}
7077

0 commit comments

Comments
 (0)