Skip to content

Commit 5e7c618

Browse files
feat(web): the Limits view shows the last week of each account and its resets
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 1afd2b3 commit 5e7c618

7 files changed

Lines changed: 333 additions & 1 deletion

File tree

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
import { useAtomValue } from "@effect/atom-react";
2+
import type { EnvironmentId, ServerProvider } from "@t3tools/contracts";
3+
import * as Option from "effect/Option";
4+
import { AsyncResult } from "effect/reactivity";
5+
import { useMemo } from "react";
6+
7+
import { serverEnvironment } from "../../state/server";
8+
import { buildUsageLimitTrend } from "./usageLimitTrend";
9+
10+
const PERIOD_DAYS = 7;
11+
const DAY_MS = 24 * 60 * 60_000;
12+
13+
const resetTimeFormat = new Intl.DateTimeFormat(undefined, {
14+
weekday: "short",
15+
day: "numeric",
16+
month: "short",
17+
hour: "2-digit",
18+
minute: "2-digit",
19+
});
20+
21+
/**
22+
* How each account's allowance was used over the last week, and what every
23+
* reset left unused. Shows nothing until the environment has recorded a
24+
* reading, so an environment without the history costs no space.
25+
*/
26+
export function UsageLimitTrendSection({
27+
environmentId,
28+
providers,
29+
now,
30+
}: {
31+
readonly environmentId: EnvironmentId;
32+
readonly providers: ReadonlyArray<ServerProvider>;
33+
readonly now: number;
34+
}) {
35+
// Whole days, so the query key holds still between renders.
36+
const sinceMs = Math.floor(now / DAY_MS) * DAY_MS - (PERIOD_DAYS - 1) * DAY_MS;
37+
const input = useMemo(() => ({ since: new Date(sinceMs).toISOString() }), [sinceMs]);
38+
const result = useAtomValue(serverEnvironment.usageLimitHistory({ environmentId, input }));
39+
const history = Option.getOrNull(AsyncResult.value(result));
40+
if (history === null) return null;
41+
const accounts = buildUsageLimitTrend({ history, providers, sinceMs, nowMs: now });
42+
if (accounts.length === 0) return null;
43+
return (
44+
<section className="flex flex-col gap-3" data-testid="usage-limit-trend">
45+
<h2 className="text-sm font-medium text-foreground">
46+
Last {PERIOD_DAYS} days
47+
<span className="ml-2 font-normal text-muted-foreground">
48+
recorded since this environment started keeping history
49+
</span>
50+
</h2>
51+
<div className="grid gap-3 sm:grid-cols-2">
52+
{accounts.map((account) => (
53+
<div
54+
key={account.instanceId}
55+
className="flex flex-col gap-2 rounded-lg border border-border/60 p-3"
56+
>
57+
<h3 className="truncate text-sm font-medium text-foreground">{account.name}</h3>
58+
{account.lines.map((line) => (
59+
<div key={line.windowId} className="flex items-center gap-3">
60+
<span className="w-28 shrink-0 truncate text-xs text-muted-foreground">
61+
{line.label}
62+
</span>
63+
<svg
64+
viewBox="0 0 100 100"
65+
preserveAspectRatio="none"
66+
role="img"
67+
aria-label={`${line.label}: ${Math.round(line.remainingPercent)}% left`}
68+
className="h-8 min-w-0 flex-1 rounded-sm bg-muted/40 text-foreground/70"
69+
>
70+
<polyline
71+
points={line.path}
72+
fill="none"
73+
stroke="currentColor"
74+
strokeWidth="2"
75+
vectorEffect="non-scaling-stroke"
76+
/>
77+
</svg>
78+
<span className="w-16 shrink-0 text-right text-xs tabular-nums text-foreground">
79+
{Math.round(line.remainingPercent)}% left
80+
</span>
81+
</div>
82+
))}
83+
{account.resets.length > 0 ? (
84+
<ul className="flex flex-col gap-1 border-t border-border/60 pt-2 text-xs text-muted-foreground">
85+
{account.resets.map((reset) => (
86+
<li key={`${reset.windowId}:${reset.at}`} className="flex flex-wrap gap-x-2">
87+
<span className="tabular-nums">
88+
{resetTimeFormat.format(new Date(reset.at))}
89+
</span>
90+
<span>{reset.label} reset</span>
91+
<span className="text-foreground">
92+
{Math.round(reset.unusedPercentBefore)}% unused
93+
</span>
94+
{reset.ahead ? (
95+
<span>
96+
early
97+
{reset.expectedAt
98+
? `, was due ${resetTimeFormat.format(new Date(reset.expectedAt))}`
99+
: ""}
100+
</span>
101+
) : null}
102+
</li>
103+
))}
104+
</ul>
105+
) : null}
106+
</div>
107+
))}
108+
</div>
109+
</section>
110+
);
111+
}

‎apps/web/src/components/usage/UsageLimits.tsx‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import {
3838
import { Button } from "../ui/button";
3939
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
4040
import { UsageLimitsPooled } from "./UsageLimitsPooled";
41+
import { UsageLimitTrendSection } from "./UsageLimitTrendSection";
4142
import { PROVIDER_PRESENTATION } from "./usageProviders";
4243

4344
const PACE: Record<LimitPace, { readonly label: string; readonly icon: typeof GaugeIcon }> = {
@@ -382,5 +383,17 @@ export function UsageLimitsSection({
382383
];
383384
}),
384385
);
385-
return <UsageLimitsPooled presentations={selected} now={now} cursorPrompt={cursorPrompt} />;
386+
return (
387+
<div className="flex flex-col gap-8">
388+
<UsageLimitsPooled presentations={selected} now={now} cursorPrompt={cursorPrompt} />
389+
{[...selected].map(([id, presentation]) => (
390+
<UsageLimitTrendSection
391+
key={id}
392+
environmentId={id}
393+
providers={presentation.serverConfig?.providers ?? []}
394+
now={now}
395+
/>
396+
))}
397+
</div>
398+
);
386399
}

‎apps/web/src/components/usage/UsagePage.refresh.test.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ vi.mock("../WorkspacePageContainer", () => ({ WorkspacePageContainer: "main" }))
9090
vi.mock("../WorkspacePageHeader", () => ({ WorkspacePageHeader: "header" }));
9191
vi.mock("./UsageProviderChart", () => ({ UsageProviderChart: "div" }));
9292
vi.mock("./UsagePriceOverrides", () => ({ UsagePriceOverrides: () => null }));
93+
vi.mock("./UsageLimitTrendSection", () => ({ UsageLimitTrendSection: () => null }));
9394
vi.mock("../chat/ProviderInstanceIcon", () => ({ ProviderInstanceIcon: () => null }));
9495
vi.mock("../settings/RedactedSensitiveText", () => ({ RedactedSensitiveText: "span" }));
9596
vi.mock("../settings/providerDriverMeta", () => ({
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import { ProviderDriverKind, ProviderInstanceId, type UsageLimitHistory } from "@t3tools/contracts";
2+
import { describe, expect, it } from "vite-plus/test";
3+
4+
import { buildUsageLimitTrend } from "./usageLimitTrend";
5+
6+
const SINCE = Date.parse("2026-10-10T00:00:00.000Z");
7+
const NOW = Date.parse("2026-10-11T00:00:00.000Z");
8+
9+
const point = (instanceId: string, at: string, usedPercent: number) => ({
10+
at,
11+
instanceId: ProviderInstanceId.make(instanceId),
12+
windowId: "weekly",
13+
kind: "weekly" as const,
14+
label: "Weekly",
15+
usedPercent,
16+
});
17+
18+
const providers = [
19+
{
20+
instanceId: ProviderInstanceId.make("codex"),
21+
driver: ProviderDriverKind.make("codex"),
22+
displayName: "Work",
23+
},
24+
];
25+
26+
describe("buildUsageLimitTrend", () => {
27+
it("draws a stepped line that holds each reading until the next one", () => {
28+
const history: UsageLimitHistory = {
29+
points: [
30+
point("codex", "2026-10-10T06:00:00.000Z", 20),
31+
point("codex", "2026-10-10T18:00:00.000Z", 60),
32+
],
33+
resets: [],
34+
};
35+
const [account] = buildUsageLimitTrend({ history, providers, sinceMs: SINCE, nowMs: NOW });
36+
expect(account?.name).toBe("Work");
37+
expect(account?.lines).toEqual([
38+
{
39+
windowId: "weekly",
40+
label: "Weekly",
41+
remainingPercent: 40,
42+
path: "25,20 75,20 75,60 100,60",
43+
},
44+
]);
45+
});
46+
47+
it("keeps the history of an account the server no longer lists, after the known ones", () => {
48+
const history: UsageLimitHistory = {
49+
points: [
50+
point("codex_old", "2026-10-10T06:00:00.000Z", 5),
51+
point("codex", "2026-10-10T06:00:00.000Z", 20),
52+
],
53+
resets: [],
54+
};
55+
expect(
56+
buildUsageLimitTrend({ history, providers, sinceMs: SINCE, nowMs: NOW }).map(
57+
(account) => account.name,
58+
),
59+
).toEqual(["Work", "codex_old"]);
60+
});
61+
62+
it("lists an account's resets newest first", () => {
63+
const reset = (at: string, unusedPercentBefore: number) => ({
64+
at,
65+
instanceId: ProviderInstanceId.make("codex"),
66+
windowId: "weekly",
67+
kind: "weekly" as const,
68+
label: "Weekly",
69+
usedPercentBefore: 100 - unusedPercentBefore,
70+
unusedPercentBefore,
71+
usedPercentAfter: 0,
72+
lastSeenBeforeAt: at,
73+
ahead: true,
74+
});
75+
const history: UsageLimitHistory = {
76+
points: [point("codex", "2026-10-10T06:00:00.000Z", 20)],
77+
resets: [reset("2026-10-10T08:00:00.000Z", 38), reset("2026-10-10T20:00:00.000Z", 12)],
78+
};
79+
const [account] = buildUsageLimitTrend({ history, providers, sinceMs: SINCE, nowMs: NOW });
80+
expect(account?.resets.map((entry) => entry.unusedPercentBefore)).toEqual([12, 38]);
81+
});
82+
});
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
/**
2+
* Shapes the recorded usage-limit history for the Limits view: one burn-down
3+
* line per account window, and the resets that happened in the period.
4+
*
5+
* @module usageLimitTrend
6+
*/
7+
import type {
8+
ServerProvider,
9+
UsageLimitHistory,
10+
UsageLimitHistoryPoint,
11+
UsageLimitReset,
12+
} from "@t3tools/contracts";
13+
import { resolveProviderInstanceDisplayName } from "@t3tools/client-runtime/state/provider-instance-display";
14+
15+
export interface UsageLimitTrendLine {
16+
readonly windowId: string;
17+
readonly label: string;
18+
/** Remaining allowance now, by the last recorded reading. */
19+
readonly remainingPercent: number;
20+
/**
21+
* SVG polyline points in a 0..100 by 0..100 box: x is time across the
22+
* period, y is 0 at a full allowance and 100 at an empty one. Stepped,
23+
* because a reading holds until the next one.
24+
*/
25+
readonly path: string;
26+
}
27+
28+
export interface UsageLimitTrendAccount {
29+
readonly instanceId: string;
30+
readonly name: string;
31+
readonly lines: ReadonlyArray<UsageLimitTrendLine>;
32+
/** Newest first. */
33+
readonly resets: ReadonlyArray<UsageLimitReset>;
34+
}
35+
36+
const round = (value: number) => Math.round(value * 100) / 100;
37+
38+
function steppedPath(
39+
points: ReadonlyArray<UsageLimitHistoryPoint>,
40+
sinceMs: number,
41+
nowMs: number,
42+
): string {
43+
const span = Math.max(1, nowMs - sinceMs);
44+
const x = (atMs: number) =>
45+
round(((Math.min(Math.max(atMs, sinceMs), nowMs) - sinceMs) / span) * 100);
46+
const coordinates: string[] = [];
47+
let previousY: number | null = null;
48+
for (const point of points) {
49+
const px = x(Date.parse(point.at));
50+
const py = round(point.usedPercent);
51+
// Hold the previous reading up to this moment, then step to the new one.
52+
if (previousY !== null) coordinates.push(`${px},${previousY}`);
53+
coordinates.push(`${px},${py}`);
54+
previousY = py;
55+
}
56+
if (previousY !== null) coordinates.push(`100,${previousY}`);
57+
return coordinates.join(" ");
58+
}
59+
60+
/**
61+
* Accounts with at least one recorded reading, in the order the providers are
62+
* listed. An account the server no longer knows keeps its instance id as name,
63+
* so its history does not vanish with the account.
64+
*/
65+
export function buildUsageLimitTrend(input: {
66+
readonly history: UsageLimitHistory;
67+
readonly providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "driver" | "displayName">>;
68+
readonly sinceMs: number;
69+
readonly nowMs: number;
70+
}): ReadonlyArray<UsageLimitTrendAccount> {
71+
const byInstance = new Map<string, Map<string, UsageLimitHistoryPoint[]>>();
72+
for (const point of input.history.points) {
73+
const windows = byInstance.get(point.instanceId) ?? new Map<string, UsageLimitHistoryPoint[]>();
74+
byInstance.set(point.instanceId, windows);
75+
const points = windows.get(point.windowId) ?? [];
76+
windows.set(point.windowId, points);
77+
points.push(point);
78+
}
79+
const order = new Map(
80+
input.providers.map((provider, index) => [provider.instanceId as string, index]),
81+
);
82+
return [...byInstance.entries()]
83+
.sort(
84+
([left], [right]) =>
85+
(order.get(left) ?? Number.MAX_SAFE_INTEGER) -
86+
(order.get(right) ?? Number.MAX_SAFE_INTEGER) || left.localeCompare(right),
87+
)
88+
.map(([instanceId, windows]) => {
89+
const provider = input.providers.find((entry) => entry.instanceId === instanceId);
90+
return {
91+
instanceId,
92+
name: provider ? resolveProviderInstanceDisplayName(provider) : instanceId,
93+
lines: [...windows.entries()].map(([windowId, points]) => {
94+
const sorted = [...points].sort(
95+
(left, right) => Date.parse(left.at) - Date.parse(right.at),
96+
);
97+
const last = sorted.at(-1)!;
98+
return {
99+
windowId,
100+
label: last.label,
101+
remainingPercent: Math.max(0, 100 - last.usedPercent),
102+
path: steppedPath(sorted, input.sinceMs, input.nowMs),
103+
};
104+
}),
105+
resets: input.history.resets
106+
.filter((reset) => reset.instanceId === instanceId)
107+
.sort((left, right) => Date.parse(right.at) - Date.parse(left.at)),
108+
};
109+
});
110+
}

‎docs/user/usage.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,16 @@ or endpoint configurations do not report subscription limits.
117117
API-key accounts may not report subscription limits. This also applies to Claude connections
118118
using a proxy through `ANTHROPIC_AUTH_TOKEN`.
119119

120+
### See how limits were used over time
121+
122+
Below the bars, **Last 7 days** draws one line per account window: flat while nothing was used,
123+
falling as the allowance is spent. It starts with the first reading the environment recorded, so a
124+
fresh install shows a short line.
125+
126+
Each reset is listed under its account with how much of the allowance was still unused. A reset
127+
that came before the time the provider had announced is marked **early**, which is how you see
128+
what a provider-wide reset took away.
129+
120130
## Connect a CLIProxyAPI hub
121131

122132
To see pooled accounts, open **Settings → Providers → Usage providers → Add hub**. Choose the

‎packages/client-runtime/src/state/server.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1099,6 +1099,11 @@ export function createServerEnvironmentAtoms<R, E>(
10991099
label: "environment-data:server:scheduled-tasks:live",
11001100
tag: WS_METHODS.scheduledTasksSubscribe,
11011101
}),
1102+
usageLimitHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
1103+
label: "environment-data:server:usage-limit-history",
1104+
tag: WS_METHODS.serverGetUsageLimitHistory,
1105+
staleTimeMs: 60_000,
1106+
}),
11021107
// A cold transcript scan is measured in seconds, so keep the result around
11031108
// long enough that switching windows or re-rendering does not rescan.
11041109
// Slow sources answer from cache first: that summary stays on screen, with

0 commit comments

Comments
 (0)