Skip to content

Commit 44ebb2f

Browse files
StiensWoutmaria-rcksjuliusmarminge
authored
feat(usage): show Muse Code limits, and xAI and Antigravity accounts from a CLIProxyAPI hub (#33800)
Co-authored-by: maria-rcks <[email protected]> Co-authored-by: Julius Marminge <[email protected]>
1 parent 78201b0 commit 44ebb2f

21 files changed

Lines changed: 1201 additions & 217 deletions

File tree

‎apps/mobile/src/features/threads/ComposerUsageLimits.tsx‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
1+
import { providerClients } from "@t3tools/client-runtime/provider-clients";
12
import type { EnvironmentId, UsageLimitsReport } from "@t3tools/contracts";
23
import { Pressable, ScrollView, View } from "react-native";
34

45
import { SymbolView } from "../../components/ui/AppSymbol";
56
import { AppText as Text } from "../../components/ui/AppText";
67
import { AccountLimits, ResetCredits } from "../usage/UsageLimitsSection";
78

8-
const DRIVER_LABEL: Partial<Record<string, string>> = { codex: "Codex", claudeAgent: "Claude" };
9-
109
export function ComposerUsageLimits({
1110
report,
1211
environmentId,
@@ -37,7 +36,7 @@ export function ComposerUsageLimits({
3736
const resetCreditInput =
3837
account.resetCreditInput ??
3938
(account.instanceId ? { instanceId: account.instanceId } : undefined);
40-
const driverLabel = DRIVER_LABEL[account.driver] ?? String(account.driver);
39+
const driverLabel = providerClients.get(account.driver)?.label ?? account.driver;
4140
return (
4241
<AccountLimits
4342
key={account.id}

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

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { useAtomValue } from "@effect/atom-react";
22
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
33
import { EnvironmentId } from "@t3tools/contracts";
4+
import { providerClients } from "@t3tools/client-runtime/provider-clients";
45
import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display";
56
import {
67
collectLimitAccounts,
@@ -29,17 +30,11 @@ import { environmentPresentations } from "../../state/presentation";
2930
import { ResetCredits } from "./UsageLimitsSection";
3031
import { usageProviderKind, useProviderColors } from "./usageProviders";
3132

32-
const DRIVER_LABEL: Partial<Record<string, string>> = {
33-
codex: "Codex",
34-
claudeAgent: "Claude",
35-
grok: "Grok",
36-
antigravity: "Antigravity",
37-
};
3833
const PACE_LABEL = { ahead: "Ahead of pace", on: "On pace", under: "Under pace" } as const;
3934

4035
function accountName(account: LimitAccount) {
4136
if (account.displayName) return account.displayName;
42-
if (!account.email) return DRIVER_LABEL[account.driver] ?? String(account.driver);
37+
if (!account.email) return providerClients.get(account.driver)?.label ?? account.driver;
4338
return emailInitials(account.email) || "Account";
4439
}
4540

@@ -444,7 +439,7 @@ export function UsageLimitsSection({
444439
<View className="flex-row items-center gap-2 px-1">
445440
<ProviderIcon provider={pool.driver} size={18} />
446441
<Text className="text-base font-t3-medium text-foreground">
447-
{DRIVER_LABEL[pool.driver] ?? pool.driver}
442+
{providerClients.get(pool.driver)?.label ?? pool.driver}
448443
</Text>
449444
</View>
450445
{windows.map((window) => {
@@ -559,7 +554,9 @@ export function UsageLimitAccountScreen({ route }: AccountScreenProps) {
559554
<View className="flex-row items-center gap-2">
560555
<ProviderIcon provider={account.driver} size={24} />
561556
<Text className="flex-1 text-xl font-t3-bold text-foreground">
562-
{account.displayName ?? DRIVER_LABEL[account.driver] ?? account.driver}
557+
{account.displayName ??
558+
providerClients.get(account.driver)?.label ??
559+
account.driver}
563560
</Text>
564561
</View>
565562
{account.email ? (

‎apps/server/src/provider/antigravityUsageLimits.ts‎

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ import {
1515
makeUsageLimits,
1616
} from "@t3tools/provider-core/server/usageLimits";
1717

18+
export function antigravityUserAgent(platform: NodeJS.Platform, architecture: NodeJS.Architecture) {
19+
return `antigravity/hub/2.24.0 (aidev_client; os_type=${platform}; arch=${architecture}; cl=963137146)`;
20+
}
21+
1822
const DAILY_ENDPOINT = "https://daily-cloudcode-pa.googleapis.com";
1923
const PROD_ENDPOINT = "https://cloudcode-pa.googleapis.com";
2024
// The ACP runtime meters consumer tiers on the daily host and GCP-terms tiers on prod.
@@ -120,6 +124,22 @@ function summaryResetTime(
120124
return untouched ? undefined : bucket.resetTime;
121125
}
122126

127+
const sha256 = Effect.fnUntraced(function* (text: string) {
128+
const digest = yield* (yield* Digest.Digest).digest(
129+
Digest.sha256,
130+
new TextEncoder().encode(text),
131+
);
132+
return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
133+
});
134+
135+
/** Keys an account by its Google ID, which matches across machines and hubs; refresh tokens do not. */
136+
export const antigravityAccountFingerprint = (userInfo: unknown) =>
137+
decodeUserInfo(userInfo).pipe(Effect.flatMap((info) => sha256(`google-account\0${info.id}`)));
138+
139+
/** Windows from a `retrieveUserQuotaSummary` answer requested at `requestedAt`. */
140+
export const antigravitySummaryWindows = (response: unknown, requestedAt: number) =>
141+
decodeSummary(response).pipe(Effect.map((summary) => summaryWindows(summary, requestedAt)));
142+
123143
function summaryWindows(summary: typeof Summary.Type, requestedAt: number) {
124144
const windows = new Map<string, ServerProviderUsageWindow>();
125145
const groups = summary.groups?.some((group) => group.buckets?.length)
@@ -203,15 +223,6 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(
203223
| undefined;
204224
let generation = 0;
205225

206-
const sha256 = (text: string) =>
207-
crypto
208-
.digest(Digest.sha256, new TextEncoder().encode(text))
209-
.pipe(
210-
Effect.map((digest) =>
211-
Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join(""),
212-
),
213-
);
214-
215226
const request = (request: HttpClientRequest.HttpClientRequest) =>
216227
client.execute(request).pipe(
217228
Effect.provideService(FetchHttpClient.RequestInit, MANUAL_REDIRECT),
@@ -259,8 +270,7 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(
259270
HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }),
260271
),
261272
).pipe(
262-
Effect.flatMap(decodeUserInfo),
263-
Effect.flatMap((info) => sha256(`google-account\0${info.id}`)),
273+
Effect.flatMap(antigravityAccountFingerprint),
264274
Effect.orElseSucceed(() => fingerprint),
265275
);
266276
if (generation === startedGeneration) {
@@ -294,7 +304,7 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(
294304
HttpClientRequest.post(`${endpoint}/v1internal:${operation}`).pipe(
295305
HttpClientRequest.setHeaders({
296306
Authorization: `Bearer ${accessToken}`,
297-
"User-Agent": `antigravity/hub/2.24.0 (aidev_client; os_type=${platform}; arch=${architecture}; cl=963137146)`,
307+
"User-Agent": antigravityUserAgent(platform, architecture),
298308
}),
299309
HttpClientRequest.bodyJsonUnsafe(
300310
token.project_id ? { project: token.project_id } : {},
@@ -313,9 +323,7 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(
313323
}
314324
return [...windows.values()];
315325
});
316-
const summary = yield* fetchWindows("retrieveUserQuotaSummary", (response, requestedAt) =>
317-
decodeSummary(response).pipe(Effect.map((summary) => summaryWindows(summary, requestedAt))),
318-
);
326+
const summary = yield* fetchWindows("retrieveUserQuotaSummary", antigravitySummaryWindows);
319327
const windows = summary.length
320328
? summary
321329
: yield* fetchWindows("fetchAvailableModels", (response) =>
@@ -331,6 +339,7 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(
331339
return { ...makeUsageLimits({ checkedAt, windows }), credentialFingerprint: account };
332340
});
333341
const probe = read.pipe(
342+
Effect.provideService(Digest.Digest, crypto),
334343
Effect.timeout("30 seconds"),
335344
Effect.catch(() =>
336345
Effect.gen(function* () {

‎apps/server/src/usage/cliproxyApi.test.ts‎

Lines changed: 192 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2+
import * as HostProcess from "@t3tools/shared/HostProcess";
23
import { describe, expect, it } from "@effect/vitest";
34
import * as Effect from "effect/Effect";
45
import * as Schema from "effect/Schema";
@@ -48,12 +49,15 @@ const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
4849

4950
function fixture(
5051
options: {
51-
accounts?: Array<
52-
(typeof accounts)[number] & {
53-
disabled?: boolean;
54-
id_token: { chatgpt_account_id: string; plan_type?: string; chatgpt_plan_type?: string };
55-
}
56-
>;
52+
accounts?: Array<{
53+
id: string;
54+
auth_index: string;
55+
provider: string;
56+
email?: string;
57+
disabled?: boolean;
58+
project_id?: string;
59+
id_token?: { chatgpt_account_id: string; plan_type?: string; chatgpt_plan_type?: string };
60+
}>;
5761
upstream?: (request: RequestBody) => { status: number; body: unknown };
5862
cooldownStatus?: number;
5963
} = {},
@@ -433,6 +437,188 @@ describe("CLIProxyAPI built-in management API", () => {
433437
}),
434438
);
435439

440+
const antigravitySummary = {
441+
buckets: [
442+
{
443+
bucketId: "gemini-weekly",
444+
window: "weekly",
445+
remainingFraction: 0.75,
446+
resetTime: "2099-01-01T00:00:00Z",
447+
},
448+
],
449+
};
450+
451+
it.effect("reads an xAI account as Grok with Grok CLI headers", () =>
452+
Effect.gen(function* () {
453+
const test = fixture({
454+
accounts: [{ id: "xai.json", auth_index: "x", provider: "xai", email: "[email protected]" }],
455+
upstream: () => ({
456+
status: 200,
457+
body: {
458+
config: {
459+
creditUsagePercent: 40,
460+
currentPeriod: { type: "USAGE_PERIOD_TYPE_WEEKLY", end: "2099-01-01T00:00:00Z" },
461+
},
462+
},
463+
}),
464+
});
465+
const [account] = yield* (yield* test.api).readAccounts(config);
466+
expect(account).toMatchObject({ driver: "grok", email: "[email protected]" });
467+
expect(account?.usageLimits.windows).toMatchObject([
468+
{ id: "subscription", kind: "weekly", usedPercent: 40 },
469+
]);
470+
const call = test.requests.find((request) => request.body?.url)?.body;
471+
expect(call?.method).toBe("GET");
472+
expect(call?.url).toBe("https://cli-chat-proxy.grok.com/v1/billing?format=credits");
473+
expect(call?.header).toMatchObject({
474+
"x-xai-token-auth": "xai-grok-cli",
475+
"x-grok-client-version": expect.any(String),
476+
"User-Agent": expect.stringMatching(/^grok-cli\//),
477+
});
478+
}),
479+
);
480+
481+
it.effect("reads an Antigravity summary and keys the account by its Google ID", () =>
482+
Effect.gen(function* () {
483+
const test = fixture({
484+
accounts: [
485+
{
486+
487+
auth_index: "g",
488+
provider: "antigravity",
489+
490+
project_id: "project-7",
491+
},
492+
],
493+
upstream: (request) => ({
494+
status: 200,
495+
body: request.url?.endsWith("/userinfo") ? { id: "google-42" } : antigravitySummary,
496+
}),
497+
});
498+
const [account] = yield* (yield* test.api).readAccounts(config);
499+
expect(account?.driver).toBe("antigravity");
500+
expect(account?.email).toBeUndefined();
501+
expect(account?.usageLimits.credentialFingerprint).toBe(
502+
// sha256("google-account\0google-42"), as a local Antigravity probe reports it.
503+
"136d4952771fd67a3600053f37492cbd05828712e0b1c89ebab03d4c22ab6554",
504+
);
505+
expect(account?.usageLimits.windows).toMatchObject([
506+
{ id: "gemini-weekly", kind: "weekly", usedPercent: 25 },
507+
]);
508+
const summary = test.requests.find((request) => request.body?.method === "POST")?.body;
509+
expect(summary?.url).toBe(
510+
"https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary",
511+
);
512+
expect(summary?.data).toBe(encodeJson({ project: "project-7" }));
513+
expect(summary).toMatchObject({
514+
auth_index: "g",
515+
method: "POST",
516+
header: {
517+
Authorization: "Bearer $TOKEN$",
518+
"Content-Type": "application/json",
519+
"User-Agent":
520+
"antigravity/hub/2.24.0 (aidev_client; os_type=linux; arch=x64; cl=963137146)",
521+
},
522+
});
523+
const identityCalls = test.requests.filter((request) =>
524+
request.body?.url?.endsWith("/userinfo"),
525+
);
526+
expect(identityCalls).toHaveLength(1);
527+
expect(identityCalls[0]?.body).toMatchObject({
528+
method: "GET",
529+
url: "https://www.googleapis.com/oauth2/v2/userinfo",
530+
header: { Authorization: "Bearer $TOKEN$" },
531+
});
532+
}).pipe(
533+
Effect.provideService(HostProcess.Platform, "linux"),
534+
Effect.provideService(HostProcess.Architecture, "x64"),
535+
),
536+
);
537+
538+
it.effect("keeps Antigravity limits and listing email when its identity read fails", () =>
539+
Effect.gen(function* () {
540+
const test = fixture({
541+
accounts: [
542+
{
543+
id: "antigravity.json",
544+
auth_index: "g",
545+
provider: "antigravity",
546+
547+
project_id: "project-7",
548+
},
549+
],
550+
upstream: (request) =>
551+
request.url?.endsWith("/userinfo")
552+
? { status: 403, body: { error: "denied" } }
553+
: {
554+
status: 200,
555+
body: antigravitySummary,
556+
},
557+
});
558+
const result = yield* (yield* test.api).readAccounts(config);
559+
expect(result).toHaveLength(1);
560+
const [account] = result;
561+
expect(account).toMatchObject({ driver: "antigravity", email: "[email protected]" });
562+
expect(account?.usageLimits.credentialFingerprint).toBeUndefined();
563+
expect(account?.usageLimits.unavailable).toBeUndefined();
564+
expect(account?.usageLimits.windows).toMatchObject([
565+
{ id: "gemini-weekly", kind: "weekly", usedPercent: 25 },
566+
]);
567+
}),
568+
);
569+
570+
it.effect.each([
571+
{ name: "a refused xAI call", provider: "xai", status: 403, body: { error: "denied" } },
572+
{ name: "a malformed xAI answer", provider: "xai", status: 200, body: { config: "x" } },
573+
{ name: "a refused Antigravity call", provider: "antigravity", status: 401, body: {} },
574+
{ name: "a malformed Antigravity answer", provider: "antigravity", status: 200, body: [] },
575+
{ name: "an empty Antigravity summary", provider: "antigravity", status: 200, body: {} },
576+
])("reports $name as unreadable", ({ provider, status, body }) =>
577+
Effect.gen(function* () {
578+
const test = fixture({
579+
accounts: [{ id: `${provider}.json`, auth_index: "a", provider, project_id: "project-7" }],
580+
upstream: () => ({ status, body }),
581+
});
582+
const [account] = yield* (yield* test.api).readAccounts(config);
583+
expect(account?.usageLimits.unavailable?.reason).toBe("probeFailed");
584+
}),
585+
);
586+
587+
it.effect.each([undefined, "", " "])(
588+
"rejects a missing or blank Antigravity project (%s) before upstream calls",
589+
(project_id) =>
590+
Effect.gen(function* () {
591+
const test = fixture({
592+
accounts: [
593+
{
594+
id: "antigravity.json",
595+
auth_index: "a",
596+
provider: "antigravity",
597+
...(project_id === undefined ? {} : { project_id }),
598+
},
599+
],
600+
});
601+
const [account] = yield* (yield* test.api).readAccounts(config);
602+
expect(account?.usageLimits.unavailable?.reason).toBe("probeFailed");
603+
expect(test.requests.map((request) => request.path)).toEqual(["/v0/management/auth-files"]);
604+
}),
605+
);
606+
607+
it.effect("skips accounts of providers the hub table does not know", () =>
608+
Effect.gen(function* () {
609+
const test = fixture({
610+
accounts: [
611+
{ id: "kiro.json", auth_index: "k", provider: "kiro", email: "[email protected]" },
612+
{ ...accounts[0]!, provider: "claude" },
613+
],
614+
upstream: () => ({ status: 200, body: { five_hour: { utilization: 1, resets_at: null } } }),
615+
});
616+
const result = yield* (yield* test.api).readAccounts(config);
617+
expect(result.map((account) => account.driver)).toEqual(["claudeAgent"]);
618+
expect(test.requests.map((request) => request.body?.auth_index)).not.toContain("k");
619+
}),
620+
);
621+
436622
it.effect("pins redemption to the displayed credit and clears only that account's cooldown", () =>
437623
Effect.gen(function* () {
438624
const test = fixture();

0 commit comments

Comments
 (0)