Skip to content
Open
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
7 changes: 6 additions & 1 deletion apps/web/src/components/chat/ThreadDetailsUsage.logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
type UsageLimitSourceSnapshots,
} from "@t3tools/contracts";
import {
accountUsageLimits,
antigravityWindowLimitsModel,
collectLimitAccounts,
collectLimitPools,
Expand All @@ -30,6 +31,7 @@ export function resolveThreadDetailsLimits(
providers: readonly ServerProvider[],
sources: UsageLimitSourceSnapshots,
now: number,
peers: Iterable<ServerProvider> = [],
): ThreadDetailsLimits | null {
const provider = providers.find((entry) => entry.instanceId === providerInstanceId);
if (!provider) return null;
Expand All @@ -41,7 +43,10 @@ export function resolveThreadDetailsLimits(
provider.usageLimits;
if (!own) return null;
const hubs = instanceHubs(provider, sources);
if (limitsNotice(own) === null || hubs.length === 0) return { kind: "instance", limits: own };
// Linked environments can hold a fresher reading of the same account; a hub-routed instance never takes theirs.
if (limitsNotice(own) === null || hubs.length === 0) {
return { kind: "instance", limits: accountUsageLimits(provider, own, peers) };
}
// An instance sent to a hub reads no limits of its own; its hub pools the accounts it spends.
return hubPool(provider.driver, model, providers, hubs, now) ?? { kind: "instance", limits: own };
}
Expand Down
15 changes: 14 additions & 1 deletion apps/web/src/components/chat/ThreadDetailsUsage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@ import {
remainingPercent,
} from "@t3tools/shared/usageLimits";
import { formatDuration, limitsNotice } from "@t3tools/shared/usageLimitsCopy";
import { useAtomValue } from "@effect/atom-react";
import { Link } from "@tanstack/react-router";
import { msg, useGT, useLocale, useMessages } from "gt-react";
import type { ReactNode } from "react";

import { usePrimarySettings } from "../../hooks/useSettings";
import { useNowMinute } from "../../hooks/useNowMinute";
import { environmentPresentations } from "../../state/presentation";
import type { ContextWindowSnapshot } from "@t3tools/client-runtime/state/context-window";
import { formatContextWindowTokens } from "../../lib/contextWindow";
import { cn } from "../../lib/utils";
Expand Down Expand Up @@ -60,7 +62,18 @@ export function ThreadDetailsUsage({
const gt = useGT();
const nowMinute = useNowMinute();
const now = Date.parse(`${nowMinute}:00Z`);
const resolved = resolveThreadDetailsLimits(providerInstanceId, model, providers, sources, now);
const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom);
const peers = [...presentations.values()].flatMap(
(presentation) => presentation.serverConfig?.providers ?? [],
);
const resolved = resolveThreadDetailsLimits(
providerInstanceId,
model,
providers,
sources,
now,
peers,
);
if (!resolved) return null;

return (
Expand Down
145 changes: 145 additions & 0 deletions packages/shared/src/usageLimits.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
type LimitAccount,
displayLimitWindows,
cursorUsageWindowDetails,
accountUsageLimits,
collectProviderUsageLimits,
sameUsageLimitCommandCoverage,
withUsageLimitsCommands,
Expand Down Expand Up @@ -2011,3 +2012,147 @@ describe("ChatGPT sharing presentation", () => {
).toBe(false);
});
});

describe("accountUsageLimits", () => {
const older = "2026-09-03T11:00:00.000Z";
const newer = "2026-09-03T11:30:00.000Z";
const readings = (usedPercent: number, at: string, credentialFingerprint = "fp-1") => ({
checkedAt: at,
credentialFingerprint,
windows: [{ ...window, usedPercent }],
});
const failed = (at: string) => ({
checkedAt: at,
windows: [],
unavailable: { reason: "probeFailed" as const },
});
const login = (overrides: Partial<ServerProvider> = {}) =>
provider({ instanceId: ProviderInstanceId.make("login"), ...overrides });

it("takes a fresher reading that shares a credential fingerprint", () => {
const own = login({ usageLimits: readings(80, older) });
const peer = login({ usageLimits: readings(20, newer) });
expect(accountUsageLimits(own, own.usageLimits!, [peer])).toBe(peer.usageLimits);
});

it("takes a fresher reading that shares an email and workspace", () => {
const auth = { status: "authenticated" as const, email: "Dev@Example.com", workspaceId: "w1" };
const own = login({ auth, usageLimits: readings(80, older, "fp-own") });
const peer = login({
auth: { ...auth, email: "dev@example.com" },
usageLimits: readings(20, newer, "fp-peer"),
});
expect(accountUsageLimits(own, own.usageLimits!, [peer])).toBe(peer.usageLimits);
});

it("prefers a readable peer over a failed local reading of the same account", () => {
const own = login({ usageLimits: { ...failed(newer), credentialFingerprint: "fp-1" } });
const peer = login({ usageLimits: readings(20, older) });
expect(accountUsageLimits(own, own.usageLimits!, [peer])).toBe(peer.usageLimits);
});

it.each([
["newer own reading", readings(20, newer), readings(80, older), {}],
["tied own reading", readings(20, newer), readings(80, newer), {}],
[
"other driver",
readings(80, older),
readings(20, newer),
{ driver: ProviderDriverKind.make("claudeAgent") },
],
["disabled peer", readings(80, older), readings(20, newer), { enabled: false }],
["uninstalled peer", readings(80, older), readings(20, newer), { installed: false }],
[
"unavailable peer",
readings(80, older),
readings(20, newer),
{ availability: "unavailable" as const },
],
["failed peer", readings(80, older), failed(newer), {}],
[
"hub-routed peer",
readings(80, older),
readings(20, newer),
{
auth: {
status: "authenticated" as const,
email: "a@x.io",
workspaceId: "w1",
endpoint: "http://127.0.0.1:8317",
},
},
],
[
"other workspace",
readings(80, older),
readings(20, newer),
{ auth: { status: "authenticated" as const, email: "a@x.io", workspaceId: "w2" } },
],
[
"other account",
readings(80, older),
readings(20, newer),
{ auth: { status: "authenticated" as const, email: "b@x.io", workspaceId: "w1" } },
],
])("keeps its own reading against a %s", (_name, ownLimits, peerLimits, peerOverrides) => {
const own = login({
auth: { status: "authenticated", email: "a@x.io", workspaceId: "w1" },
usageLimits: ownLimits,
});
const peer = login({
auth: { status: "authenticated", email: "a@x.io", workspaceId: "w1" },
usageLimits: peerLimits,
...peerOverrides,
});
expect(accountUsageLimits(own, ownLimits, [peer])).toBe(ownLimits);
});

it("keeps a hub-routed login's own reading instead of a direct peer's", () => {
const ownLimits = failed(older);
const own = login({
auth: { status: "authenticated", email: "a@x.io", endpoint: "http://127.0.0.1:8317" },
usageLimits: ownLimits,
});
const peer = login({
auth: { status: "authenticated", email: "a@x.io" },
usageLimits: readings(20, newer),
});
expect(accountUsageLimits(own, ownLimits, [peer])).toBe(ownLimits);
});

it("keeps its own reading when multiple workspaces make the account ambiguous", () => {
const ownLimits = readings(80, older);
const own = login({
auth: { status: "authenticated", email: "a@x.io" },
usageLimits: ownLimits,
});
const peerA = login({
auth: { status: "authenticated", email: "a@x.io", workspaceId: "w1" },
usageLimits: readings(20, newer),
});
const peerB = login({
auth: { status: "authenticated", email: "a@x.io", workspaceId: "w2" },
usageLimits: readings(10, newer),
});
expect(accountUsageLimits(own, ownLimits, [peerA, peerB])).toBe(ownLimits);
});

it("keeps an unsupported own reading", () => {
const unsupported = {
checkedAt: older,
credentialFingerprint: "fp-1",
windows: [],
unavailable: { reason: "unsupported" as const },
};
const own = login({ usageLimits: unsupported });
const peer = login({ usageLimits: readings(20, newer) });
expect(accountUsageLimits(own, unsupported, [peer])).toBe(unsupported);
});

it("keeps its own reading when the account has no email or credential fingerprint", () => {
const ownLimits = { checkedAt: older, windows: [{ ...window, usedPercent: 80 }] };
const own = login({ usageLimits: ownLimits });
const peer = login({ usageLimits: { checkedAt: newer, windows: [window] } });
expect(accountUsageLimits(own, ownLimits, [peer])).toBe(ownLimits);
});
});
44 changes: 37 additions & 7 deletions packages/shared/src/usageLimits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -944,6 +944,42 @@ export function hubRoutes(
account.models ? listed(account) : serving.has(account.driver) || account.driver === driver;
}

function fresherLimits(next: ServerProviderUsageLimits, previous: ServerProviderUsageLimits) {
const previousUsable = limitsNotice(previous) === null;
const usable = limitsNotice(next) === null;
return (
(usable && !previousUsable) ||
(usable === previousUsable && Date.parse(next.checkedAt) > Date.parse(previous.checkedAt))
);
}

/** The freshest readable limits any enabled login of this provider's account reports across environments. */
export function accountUsageLimits(
provider: ServerProvider,
own: ServerProviderUsageLimits,
peers: Iterable<ServerProvider>,
): ServerProviderUsageLimits {
if (
!provider.enabled ||
provider.auth.endpoint !== undefined ||
own.unavailable?.reason === "unsupported"
) {
return own;
}
const enabledPeers = [...peers].filter((peer) => peer.enabled);
const resolveKey = accountKeyResolver([provider, ...enabledPeers].map(nativeReport));
const key = resolveKey(nativeReport(provider));
if (key === null) return own;
let best = own;
for (const peer of providersWithLimits(enabledPeers)) {
if (peer.driver !== provider.driver || !peer.usageLimits) continue;
if (peer.auth.endpoint !== undefined || limitsNotice(peer.usageLimits) !== null) continue;
if (resolveKey(nativeReport(peer)) !== key) continue;
if (fresherLimits(peer.usageLimits, best)) best = peer.usageLimits;
}
return best;
}

export function collectProviderUsageLimits(
instanceId: ProviderInstanceId,
providers: readonly ServerProvider[],
Expand Down Expand Up @@ -988,13 +1024,7 @@ export function collectProviderUsageLimits(
const snapshot = { provider, limits: provider.usageLimits };
const key = accountKey ?? `instance:${provider.instanceId}`;
const previous = nativeByAccount.get(key);
const previousUsable = previous ? limitsNotice(previous.usage.limits) === null : false;
const usable = limitsNotice(snapshot.limits) === null;
const providerWins =
!previous ||
(usable && !previousUsable) ||
(usable === previousUsable &&
Date.parse(snapshot.limits.checkedAt) > Date.parse(previous.usage.limits.checkedAt));
const providerWins = !previous || fresherLimits(snapshot.limits, previous.usage.limits);
const previousCredit = previous?.credits;
const credits =
snapshot.limits.resetCredits &&
Expand Down
Loading