Skip to content

Commit d32a9bd

Browse files
fix(relay): show the account's real tunnel cap in T3 Connect settings
The tunnel meter computed its cap from the T3 Chat plan on the client, so accounts with a manual override saw "4 of 3 tunnels in use". The T3 Chat link endpoint now returns the relay's enforced cap (override or plan), and the web client uses it, falling back to the plan default for older relays. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 5ef5685 commit d32a9bd

7 files changed

Lines changed: 90 additions & 32 deletions

File tree

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

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -150,21 +150,26 @@ export function useManagedRelayDevices() {
150150
/** How this account can raise its tunnel cap: link T3 Chat, or upgrade the linked plan. */
151151
export type ManagedTunnelUpgrade = "link" | "pro" | "premier" | null;
152152

153-
// Mirrors the relay's cap without manual overrides, which the relay does not expose.
153+
// Older relays omit `maxTunnels`, so fall back to the plan's default cap.
154154
function managedTunnelCap(t3Chat: RelayT3ChatLinkResponse): {
155155
readonly limit: number;
156156
readonly upgrade: ManagedTunnelUpgrade;
157157
} {
158-
if (!t3Chat.available) return { limit: DEFAULT_MANAGED_TUNNEL_LIMIT, upgrade: null };
158+
const cap = (planLimit: number, upgrade: ManagedTunnelUpgrade) => {
159+
const limit = t3Chat.maxTunnels ?? planLimit;
160+
// Every upgrade offers Premier, which a manual override may already exceed.
161+
return { limit, upgrade: limit < T3CHAT_PLAN_TUNNEL_LIMITS.premier ? upgrade : null };
162+
};
163+
if (!t3Chat.available) return cap(DEFAULT_MANAGED_TUNNEL_LIMIT, null);
159164
switch (t3Chat.link?.plan) {
160165
case "premier":
161-
return { limit: T3CHAT_PLAN_TUNNEL_LIMITS.premier, upgrade: null };
166+
return cap(T3CHAT_PLAN_TUNNEL_LIMITS.premier, null);
162167
case "pro":
163-
return { limit: T3CHAT_PLAN_TUNNEL_LIMITS.pro, upgrade: "premier" };
168+
return cap(T3CHAT_PLAN_TUNNEL_LIMITS.pro, "premier");
164169
case "free":
165-
return { limit: DEFAULT_MANAGED_TUNNEL_LIMIT, upgrade: "pro" };
170+
return cap(DEFAULT_MANAGED_TUNNEL_LIMIT, "pro");
166171
case undefined:
167-
return { limit: DEFAULT_MANAGED_TUNNEL_LIMIT, upgrade: "link" };
172+
return cap(DEFAULT_MANAGED_TUNNEL_LIMIT, "link");
168173
}
169174
}
170175

‎infra/relay/src/environments/ManagedEndpointProvider.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,7 @@ function makeTunnelLimits(
343343
}
344344
return yield* reserve;
345345
}),
346+
getLimit: () => Effect.die("unused"),
346347
});
347348
}
348349

‎infra/relay/src/environments/ManagedTunnelLimits.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,27 @@ const reserve = (
121121
),
122122
);
123123

124+
const getLimit = (input: { readonly override?: number; readonly plan: RelayT3ChatPlan | null }) =>
125+
Effect.gen(function* () {
126+
const limits = yield* ManagedTunnelLimits.ManagedTunnelLimits;
127+
return yield* limits.getLimit({ userId: "user-1", plan: input.plan });
128+
}).pipe(
129+
Effect.provide(
130+
ManagedTunnelLimits.layer.pipe(
131+
Layer.provide(
132+
Layer.succeed(
133+
RelayDb.RelayDb,
134+
makeFakeDb({
135+
otherSlots: () => 0,
136+
...(input.override === undefined ? {} : { override: input.override }),
137+
}),
138+
),
139+
),
140+
Layer.provide(t3ChatLayer("free")),
141+
),
142+
),
143+
);
144+
124145
describe("ManagedTunnelLimits", () => {
125146
it.effect("rejects concurrent reservations past the limit", () => {
126147
const reserved: Array<string> = [];
@@ -362,6 +383,7 @@ describe("ManagedTunnelLimits", () => {
362383
yield* reserve({ activeTunnels: limit - 1, plan });
363384
const error = yield* Effect.flip(reserve({ activeTunnels: limit, plan }));
364385
expect(error).toMatchObject({ _tag: "ManagedTunnelLimitExceeded", maxTunnels: limit });
386+
expect(yield* getLimit({ plan })).toBe(limit);
365387
}
366388
}),
367389
);
@@ -372,6 +394,8 @@ describe("ManagedTunnelLimits", () => {
372394
const error = yield* Effect.flip(reserve({ activeTunnels: 3, plan }));
373395
expect(error).toMatchObject({ _tag: "ManagedTunnelLimitExceeded", maxTunnels: 3 });
374396
}
397+
expect(yield* getLimit({ plan: "free" })).toBe(3);
398+
expect(yield* getLimit({ plan: null })).toBe(3);
375399
}),
376400
);
377401

@@ -383,6 +407,7 @@ describe("ManagedTunnelLimits", () => {
383407
reserve({ override, activeTunnels: override, plan: "premier", lookups }),
384408
);
385409
expect(error).toMatchObject({ _tag: "ManagedTunnelLimitExceeded", maxTunnels: override });
410+
expect(yield* getLimit({ override, plan: "premier" })).toBe(override);
386411
}
387412
expect(lookups).toEqual([]);
388413
}),

‎infra/relay/src/environments/ManagedTunnelLimits.ts‎

Lines changed: 36 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,11 @@ import * as Effect from "effect/Effect";
66
import * as Layer from "effect/Layer";
77
import * as Schema from "effect/Schema";
88
import * as SqlError from "effect/sql/SqlError";
9-
import { DEFAULT_MANAGED_TUNNEL_LIMIT, T3CHAT_PLAN_TUNNEL_LIMITS } from "@t3tools/contracts/relay";
9+
import {
10+
DEFAULT_MANAGED_TUNNEL_LIMIT,
11+
T3CHAT_PLAN_TUNNEL_LIMITS,
12+
type RelayT3ChatPlan,
13+
} from "@t3tools/contracts/relay";
1014

1115
import * as RelayDb from "../db.ts";
1216
import {
@@ -106,27 +110,52 @@ export class ManagedTunnelLimits extends Context.Service<
106110
input: { readonly userId: string; readonly environmentId: string },
107111
reserve: Effect.Effect<A, E, R>,
108112
) => Effect.Effect<A, E | ManagedTunnelLimitExceeded | ManagedTunnelLimitPersistenceError, R>;
113+
/** The cap `withCapacity` enforces for a user on the given T3 Chat plan. */
114+
readonly getLimit: (input: {
115+
readonly userId: string;
116+
readonly plan: RelayT3ChatPlan | null;
117+
}) => Effect.Effect<number, ManagedTunnelLimitPersistenceError>;
109118
}
110119
>()("t3code-relay/environments/ManagedTunnelLimits") {}
111120

112121
const make = Effect.gen(function* () {
113122
const db = yield* RelayDb.RelayDb;
114123
const t3Chat = yield* T3ChatAccounts.T3ChatAccounts;
115124

125+
const planTunnelLimit = (plan: RelayT3ChatPlan | null) =>
126+
plan && plan !== "free" ? T3CHAT_PLAN_TUNNEL_LIMITS[plan] : 0;
127+
116128
// Asked only at the cap, so most links never call T3 Chat. Any failure keeps the lower cap.
117129
const t3ChatTunnelLimit = (userId: string) =>
118130
t3Chat.getLink({ userId }).pipe(
119-
Effect.map((link) =>
120-
link && link.plan !== "free" ? T3CHAT_PLAN_TUNNEL_LIMITS[link.plan] : 0,
121-
),
131+
Effect.map((link) => planTunnelLimit(link?.plan ?? null)),
122132
Effect.catch((error) =>
123133
Effect.logWarning("T3 Chat plan check failed", { userId, error: error.message }).pipe(
124134
Effect.as(0),
125135
),
126136
),
127137
);
128138

139+
const loadOverride = (userId: string) =>
140+
db
141+
.select({ maxTunnels: relayManagedTunnelLimits.maxTunnels })
142+
.from(relayManagedTunnelLimits)
143+
.where(eq(relayManagedTunnelLimits.userId, userId))
144+
.limit(1)
145+
.pipe(
146+
Effect.map((rows) => rows[0]?.maxTunnels ?? null),
147+
Effect.mapError(
148+
(cause) =>
149+
new ManagedTunnelLimitPersistenceError({ operation: "load-limit", userId, cause }),
150+
),
151+
);
152+
129153
return ManagedTunnelLimits.of({
154+
getLimit: Effect.fn("relay.managed_tunnel_limits.get_limit")(function* (input) {
155+
// A manual override is the exact cap; a T3 Chat plan raises only the default.
156+
const override = yield* loadOverride(input.userId);
157+
return override ?? Math.max(DEFAULT_MANAGED_TUNNEL_LIMIT, planTunnelLimit(input.plan));
158+
}),
130159
withCapacity: Effect.fn("relay.managed_tunnel_limits.with_capacity")(function* <A, E, R>(
131160
input: { readonly userId: string; readonly environmentId: string },
132161
reserve: Effect.Effect<A, E, R>,
@@ -148,22 +177,8 @@ const make = Effect.gen(function* () {
148177
),
149178
);
150179

151-
const overrides = yield* db
152-
.select({ maxTunnels: relayManagedTunnelLimits.maxTunnels })
153-
.from(relayManagedTunnelLimits)
154-
.where(eq(relayManagedTunnelLimits.userId, input.userId))
155-
.limit(1)
156-
.pipe(
157-
Effect.mapError(
158-
(cause) =>
159-
new ManagedTunnelLimitPersistenceError({
160-
operation: "load-limit",
161-
userId: input.userId,
162-
cause,
163-
}),
164-
),
165-
);
166-
const baseMaxTunnels = overrides[0]?.maxTunnels ?? DEFAULT_MANAGED_TUNNEL_LIMIT;
180+
const override = yield* loadOverride(input.userId);
181+
const baseMaxTunnels = override ?? DEFAULT_MANAGED_TUNNEL_LIMIT;
167182

168183
const pendingCutoff = DateTime.formatIso(
169184
DateTime.subtract(yield* DateTime.now, {
@@ -196,7 +211,7 @@ const make = Effect.gen(function* () {
196211
// A manual override is the exact cap; a T3 Chat plan raises only the default.
197212
// Runs under the user lock, bounded by the T3 Chat request timeout.
198213
const maxTunnels =
199-
t3Chat.available && overrides.length === 0
214+
t3Chat.available && override === null
200215
? Math.max(baseMaxTunnels, yield* t3ChatTunnelLimit(input.userId))
201216
: baseMaxTunnels;
202217
if (activeTunnels >= maxTunnels) {

‎infra/relay/src/http/Api.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ import * as HookInbox from "../hooks/HookInbox.ts";
6464
import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";
6565
import * as ManagedEndpointAllocations from "../environments/ManagedEndpointAllocations.ts";
6666
import * as ManagedEndpointProvider from "../environments/ManagedEndpointProvider.ts";
67+
import * as ManagedTunnelLimits from "../environments/ManagedTunnelLimits.ts";
6768
import * as AgentActivityPublisher from "../agentActivity/AgentActivityPublisher.ts";
6869
import * as EnvironmentPublishSignatures from "../environments/EnvironmentPublishSignatures.ts";
6970
import * as T3ChatAccounts from "../t3chat/T3ChatAccounts.ts";
@@ -130,6 +131,7 @@ describe("managed endpoint provisioning errors", () => {
130131
Layer.mock(ManagedEndpointProvider.ManagedEndpointProvider, {}),
131132
Layer.mock(Devices.Devices, {}),
132133
Layer.mock(T3ChatAccounts.T3ChatAccounts, { available: false }),
134+
Layer.mock(ManagedTunnelLimits.ManagedTunnelLimits, {}),
133135
),
134136
),
135137
Layer.provideMerge(
@@ -241,6 +243,7 @@ describe("device listing compatibility", () => {
241243
},
242244
}),
243245
Layer.mock(T3ChatAccounts.T3ChatAccounts, { available: false }),
246+
Layer.mock(ManagedTunnelLimits.ManagedTunnelLimits, {}),
244247
),
245248
),
246249
Layer.provideMerge(
@@ -322,6 +325,7 @@ describe("Cloudflare rate-limit retry hint", () => {
322325
Layer.mock(ManagedEndpointProvider.ManagedEndpointProvider, {}),
323326
Layer.mock(Devices.Devices, {}),
324327
Layer.mock(T3ChatAccounts.T3ChatAccounts, { available: false }),
328+
Layer.mock(ManagedTunnelLimits.ManagedTunnelLimits, {}),
325329
),
326330
),
327331
Layer.provideMerge(

‎infra/relay/src/http/Api.ts‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ import * as AgentActivityPublisher from "../agentActivity/AgentActivityPublisher
7474
import * as EnvironmentConnector from "../environments/EnvironmentConnector.ts";
7575
import * as EnvironmentLinker from "../environments/EnvironmentLinker.ts";
7676
import * as ManagedEndpointProvider from "../environments/ManagedEndpointProvider.ts";
77+
import * as ManagedTunnelLimits from "../environments/ManagedTunnelLimits.ts";
7778
import * as ManagedEndpointAllocations from "../environments/ManagedEndpointAllocations.ts";
7879
import * as EnvironmentPublishSignatures from "../environments/EnvironmentPublishSignatures.ts";
7980
import * as MobileRegistrations from "../agentActivity/MobileRegistrations.ts";
@@ -825,6 +826,7 @@ export const layerClientApi = HttpApiBuilder.group(
825826
const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider;
826827
const devices = yield* Devices.Devices;
827828
const t3Chat = yield* T3ChatAccounts.T3ChatAccounts;
829+
const tunnelLimits = yield* ManagedTunnelLimits.ManagedTunnelLimits;
828830
return handlers
829831
.handle(
830832
"listEnvironments",
@@ -996,12 +998,16 @@ export const layerClientApi = HttpApiBuilder.group(
996998
"getT3ChatLink",
997999
Effect.fn("relay.api.client.getT3ChatLink")(function* () {
9981000
yield* appendRelayCredentialResponseHeaders;
999-
if (!t3Chat.available) return { available: false, link: null };
10001001
const { userId } = yield* RelayClientPrincipal;
1001-
const link = yield* t3Chat
1002-
.getLink({ userId })
1003-
.pipe(Effect.catch(() => relayInternalErrorResponse("upstream_unavailable")));
1004-
return { available: true, link };
1002+
const link = t3Chat.available
1003+
? yield* t3Chat
1004+
.getLink({ userId })
1005+
.pipe(Effect.catch(() => relayInternalErrorResponse("upstream_unavailable")))
1006+
: null;
1007+
const maxTunnels = yield* tunnelLimits
1008+
.getLimit({ userId, plan: link?.plan ?? null })
1009+
.pipe(Effect.catch(() => relayInternalErrorResponse("internal_error")));
1010+
return { available: t3Chat.available, link, maxTunnels };
10051011
}, mapRelayCommonApiErrors("not_authorized")),
10061012
)
10071013
.handle(

‎packages/contracts/src/relay.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -981,6 +981,8 @@ export const RelayT3ChatLinkResponse = Schema.Struct({
981981
// False when this relay has no T3 Chat secret, so clients hide the feature.
982982
available: Schema.Boolean,
983983
link: Schema.NullOr(RelayT3ChatLink),
984+
// The account's managed tunnel cap, including manual overrides. Absent from older relays.
985+
maxTunnels: Schema.optionalKey(Schema.Number),
984986
});
985987
export type RelayT3ChatLinkResponse = typeof RelayT3ChatLinkResponse.Type;
986988

0 commit comments

Comments
 (0)