Skip to content

Commit 95c630f

Browse files
committed
fix(usage): report limits per provider account
1 parent c531ae3 commit 95c630f

20 files changed

Lines changed: 874 additions & 226 deletions

‎apps/mobile/src/features/usage/UsageRouteScreen.tsx‎

Lines changed: 136 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
import { useNavigation } from "@react-navigation/native";
2+
import { useAtomValue } from "@effect/atom-react";
23
import type { DailyTotals, MergedUsage } from "@t3tools/shared/usageMerge";
4+
import {
5+
buildProviderRateLimitsView,
6+
type ProviderRateLimitsView,
7+
type RateLimitWindowView,
8+
} from "@t3tools/shared/providerRateLimits";
39
import {
410
enumerateDays,
511
enumerateHourStarts,
@@ -11,13 +17,14 @@ import {
1117
formatUsd,
1218
makeWindow,
1319
} from "@t3tools/shared/usageFormat";
14-
import { useMemo, useState } from "react";
20+
import { useEffect, useMemo, useState } from "react";
1521
import { Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";
1622
import { useSafeAreaInsets } from "react-native-safe-area-context";
1723

1824
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
1925
import { AppText as Text } from "../../components/AppText";
2026
import { NativeStackScreenOptions } from "../../native/StackHeader";
27+
import { environmentServerConfigsAtom } from "../../state/server";
2128
import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
2229
import { SettingsSection } from "../settings/components/SettingsSection";
2330
import { UsageDailyChart } from "./UsageDailyChart";
@@ -44,6 +51,36 @@ export function UsageRouteScreen() {
4451
const { days: windowDays, window } = windowSelection;
4552
const isPast24Hours = windowDays === 1;
4653
const { merged, environments, isPending, isPartial, refresh } = useUsage(window);
54+
const serverConfigs = useAtomValue(environmentServerConfigsAtom);
55+
const rateLimitEnvironments = useMemo(
56+
() =>
57+
environments.map((environment) => ({
58+
environmentId: environment.environmentId,
59+
label: environment.label,
60+
providers: serverConfigs.get(environment.environmentId)?.providers ?? [],
61+
})),
62+
[environments, serverConfigs],
63+
);
64+
const hasRateLimitSnapshots = rateLimitEnvironments.some((environment) =>
65+
environment.providers.some((provider) => (provider.rateLimits?.windows.length ?? 0) > 0),
66+
);
67+
const [rateLimitsNowMs, setRateLimitsNowMs] = useState(() => Date.now());
68+
useEffect(() => {
69+
if (!hasRateLimitSnapshots) {
70+
return;
71+
}
72+
setRateLimitsNowMs(Date.now());
73+
const intervalId = setInterval(() => setRateLimitsNowMs(Date.now()), 60_000);
74+
return () => clearInterval(intervalId);
75+
}, [hasRateLimitSnapshots]);
76+
const planLimits = useMemo(
77+
() =>
78+
buildProviderRateLimitsView({
79+
environments: rateLimitEnvironments,
80+
nowMs: rateLimitsNowMs,
81+
}),
82+
[rateLimitEnvironments, rateLimitsNowMs],
83+
);
4784

4885
const days = useMemo(
4986
() => enumerateDays(window.sinceDay, window.untilDay),
@@ -117,6 +154,8 @@ export function UsageRouteScreen() {
117154

118155
<UsageCoverageNotice environments={environments} merged={merged} isPartial={isPartial} />
119156

157+
<PlanLimitsSection view={planLimits} />
158+
120159
{isPending ? (
121160
<Text className="py-16 text-center text-base text-foreground-muted">
122161
Scanning provider transcripts…
@@ -148,6 +187,102 @@ export function UsageRouteScreen() {
148187
);
149188
}
150189

190+
function PlanLimitsSection(props: { readonly view: ProviderRateLimitsView }) {
191+
if (props.view.providers.length === 0) {
192+
return null;
193+
}
194+
195+
return (
196+
<SettingsSection title="Plan limits" card>
197+
{props.view.providers.map((provider, index) => (
198+
<View
199+
key={provider.key}
200+
className={index === 0 ? "gap-3 p-4" : "gap-3 border-t border-border-subtle p-4"}
201+
>
202+
<View className="flex-row items-baseline justify-between gap-3">
203+
<View className="min-w-0 flex-1">
204+
<Text className="text-base font-t3-medium text-foreground" numberOfLines={1}>
205+
{provider.displayName}
206+
{provider.planLabel ? ` · ${provider.planLabel}` : ""}
207+
</Text>
208+
{provider.environmentLabel ? (
209+
<Text className="text-xs text-foreground-tertiary" numberOfLines={1}>
210+
{provider.environmentLabel}
211+
</Text>
212+
) : null}
213+
</View>
214+
</View>
215+
216+
{provider.windows.map((window) => (
217+
<PlanLimitWindowRow
218+
key={window.id}
219+
accentColor={provider.accentColor}
220+
window={window}
221+
/>
222+
))}
223+
224+
{provider.notice ? (
225+
<Text className="text-sm text-danger-foreground">{provider.notice}</Text>
226+
) : null}
227+
</View>
228+
))}
229+
</SettingsSection>
230+
);
231+
}
232+
233+
function PlanLimitWindowRow(props: {
234+
readonly window: RateLimitWindowView;
235+
readonly accentColor: string | undefined;
236+
}) {
237+
const { window } = props;
238+
const percentLabel = window.isReset ? "reset" : `${Math.round(window.usedPercent)}%`;
239+
240+
return (
241+
<View className="gap-1.5">
242+
<View className="flex-row items-baseline justify-between gap-3">
243+
<Text className="text-sm text-foreground-muted">{window.label}</Text>
244+
<Text
245+
className={
246+
window.status === "exhausted"
247+
? "text-sm font-t3-medium tabular-nums text-danger-foreground"
248+
: "text-sm tabular-nums text-foreground-muted"
249+
}
250+
>
251+
{percentLabel}
252+
{!window.isReset && window.resetsInLabel ? ` · ${window.resetsInLabel} left` : ""}
253+
</Text>
254+
</View>
255+
<View
256+
accessibilityLabel={`${window.label} usage`}
257+
accessibilityRole="progressbar"
258+
accessibilityValue={{
259+
min: 0,
260+
max: 100,
261+
now: Math.round(window.usedPercent),
262+
}}
263+
className="h-1.5 overflow-hidden rounded-full bg-subtle-strong"
264+
>
265+
<View
266+
className={
267+
window.status === "exhausted"
268+
? "h-full rounded-full bg-danger-foreground"
269+
: "h-full rounded-full bg-foreground-muted"
270+
}
271+
style={{
272+
width: `${window.usedPercent}%`,
273+
...(props.accentColor && window.status === "ok"
274+
? { backgroundColor: props.accentColor }
275+
: {}),
276+
}}
277+
/>
278+
</View>
279+
{window.detail ? (
280+
<Text className="text-xs text-foreground-tertiary">{window.detail}</Text>
281+
) : null}
282+
</View>
283+
);
284+
}
285+
151286
function SegmentedControl<Value extends number | string>(props: {
152287
readonly options: readonly { readonly value: Value; readonly label: string }[];
153288
readonly selected: Value;

‎apps/server/src/orchestration/Layers/ProviderRateLimitsReactor.ts‎

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -41,18 +41,24 @@ export const make = Effect.gen(function* () {
4141
if (!snapshot || instanceId === undefined) {
4242
return Effect.void;
4343
}
44-
return providerRegistry.setProviderRateLimits({ instanceId, rateLimits: snapshot }).pipe(
45-
Effect.asVoid,
46-
Effect.catchCause((cause) =>
47-
Cause.hasInterruptsOnly(cause)
48-
? Effect.failCause(cause)
49-
: Effect.logWarning("failed to record provider rate limits", {
50-
instanceId,
51-
provider: event.provider,
52-
cause: Cause.pretty(cause),
53-
}),
54-
),
55-
);
44+
return providerRegistry
45+
.setProviderRateLimits({
46+
instanceId,
47+
rateLimits: snapshot,
48+
...(event.payload.updateMode ? { mode: event.payload.updateMode } : {}),
49+
})
50+
.pipe(
51+
Effect.asVoid,
52+
Effect.catchCause((cause) =>
53+
Cause.hasInterruptsOnly(cause)
54+
? Effect.failCause(cause)
55+
: Effect.logWarning("failed to record provider rate limits", {
56+
instanceId,
57+
provider: event.provider,
58+
cause: Cause.pretty(cause),
59+
}),
60+
),
61+
);
5662
};
5763

5864
const worker = yield* makeDrainableWorker(processEvent);

‎apps/server/src/provider/Layers/ClaudeAdapter.test.ts‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2720,6 +2720,95 @@ describe("ClaudeAdapterLive", () => {
27202720
);
27212721
});
27222722

2723+
it.effect("reads authoritative Claude plan limits when a turn completes", () => {
2724+
const harness = makeHarness();
2725+
Object.assign(harness.query, {
2726+
usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: async () => ({
2727+
subscription_type: "max",
2728+
rate_limits_available: true,
2729+
rate_limits: {
2730+
five_hour: {
2731+
utilization: 42,
2732+
resets_at: "2026-08-24T17:00:00.000Z",
2733+
},
2734+
seven_day: {
2735+
utilization: 18,
2736+
resets_at: "2026-08-28T12:00:00.000Z",
2737+
},
2738+
seven_day_opus: {
2739+
utilization: 64,
2740+
resets_at: null,
2741+
},
2742+
},
2743+
}),
2744+
});
2745+
2746+
return Effect.gen(function* () {
2747+
const adapter = yield* ClaudeAdapter;
2748+
2749+
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 8).pipe(
2750+
Stream.runCollect,
2751+
Effect.forkChild,
2752+
);
2753+
2754+
yield* adapter.startSession({
2755+
threadId: THREAD_ID,
2756+
provider: ProviderDriverKind.make("claudeAgent"),
2757+
runtimeMode: "full-access",
2758+
});
2759+
2760+
yield* adapter.sendTurn({
2761+
threadId: THREAD_ID,
2762+
input: "hello",
2763+
attachments: [],
2764+
});
2765+
2766+
harness.query.emit({
2767+
type: "result",
2768+
subtype: "success",
2769+
is_error: false,
2770+
duration_ms: 1234,
2771+
duration_api_ms: 1200,
2772+
num_turns: 1,
2773+
result: "done",
2774+
stop_reason: "end_turn",
2775+
session_id: "sdk-session-result-rate-limits",
2776+
usage: {
2777+
input_tokens: 4,
2778+
cache_creation_input_tokens: 0,
2779+
cache_read_input_tokens: 0,
2780+
output_tokens: 8,
2781+
},
2782+
modelUsage: {},
2783+
} as unknown as SDKMessage);
2784+
harness.query.finish();
2785+
2786+
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
2787+
const rateLimitsEvent = runtimeEvents.find(
2788+
(event) => event.type === "account.rate-limits.updated",
2789+
);
2790+
assert.equal(rateLimitsEvent?.type, "account.rate-limits.updated");
2791+
if (rateLimitsEvent?.type === "account.rate-limits.updated") {
2792+
assert.strictEqual(rateLimitsEvent.payload.updateMode, "replace");
2793+
assert.strictEqual(rateLimitsEvent.payload.snapshot?.planLabel, "Max");
2794+
assert.deepStrictEqual(
2795+
rateLimitsEvent.payload.snapshot?.windows.map((window) => [
2796+
window.id,
2797+
window.usedPercent,
2798+
]),
2799+
[
2800+
["five_hour", 42],
2801+
["seven_day", 18],
2802+
["seven_day_opus", 64],
2803+
],
2804+
);
2805+
}
2806+
}).pipe(
2807+
Effect.provideService(Random.Random, makeDeterministicRandomService()),
2808+
Effect.provide(harness.layer),
2809+
);
2810+
});
2811+
27232812
it.effect("clamps oversized Claude usage to the reported context window", () => {
27242813
const harness = makeHarness();
27252814
return Effect.gen(function* () {

0 commit comments

Comments
 (0)