feat(usage): show Codex and Claude subscription limits on a Limits tab #9507
Mergedjuliusmarmingemerged 7 commits into
main fromrefs/pull/9507/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/web/src/components/usage/AddUsageLimitSourceDialog.tsx line 94OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +74,21 @@74+ onOpenChange(false);75+ };76+77+ return (78+ <Dialog79+ open={open}80+ onOpenChange={(next) => {81+ if (!next) reset();82+ onOpenChange(next);83+ }}84+ >85+ <DialogPopup className="max-w-md">86+ <DialogHeader>87+ <DialogTitle>Add a CLIProxyAPI hub</DialogTitle>88+ <DialogDescription>89+ Show the quota of every account the hub pools, next to the providers on this machine.90+ The key stays on the server.91+ </DialogDescription>92+ </DialogHeader>93+ <form94+ className="grid gap-4 px-6 py-5"
- apps/server/src/serverSettings.ts line 695Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -632,0 +675,21 @@675+ for (const [sourceId, source] of Object.entries(next.usageLimitSources)) {676+ const secretName = usageLimitSourceSecretName(sourceId);677+ if (source.managementKey === USAGE_LIMIT_SOURCE_KEY_REDACTED) {678+ // Unchanged from the client's point of view; the store already has it.679+ usageLimitSources[sourceId] = source;680+ continue;681+ }682+ if (source.managementKey.length === 0) {683+ yield* secretStore684+ .remove(secretName)685+ .pipe(686+ Effect.mapError(687+ (cause) =>688+ new ServerSettingsError({ settingsPath, operation: "remove-secret", cause }),689+ ),690+ );691+ usageLimitSources[sourceId] = source;692+ continue;693+ }694+ yield* secretStore695+ .set(secretName, textEncoder.encode(source.managementKey))apps/server/src/usage/UsageLimitSources.ts line 154Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +101,21 @@101+ const publish = (next: ReadonlyArray<UsageLimitSourceSnapshot>) =>102+ Effect.gen(function* () {103+ const changed = yield* Ref.modify(stateRef, (previous) =>104+ Equal.equals(previous, next) ? [false, previous] : [true, next],105+ );106+ if (changed) yield* PubSub.publish(changes, next);107+ });108+109+ const refresh = Effect.gen(function* () {110+ const settings = yield* settingsService.getSettings.pipe(111+ Effect.orElseSucceed((): ServerSettings | null => null),112+ );113+ const entries = Object.entries(settings?.usageLimitSources ?? {}).filter(114+ ([, config]) => config.enabled,115+ );116+ const snapshots = yield* Effect.forEach(117+ entries,118+ ([id, config]) => readSource(id as UsageLimitSourceId, config),119+ { concurrency: 4 },120+ );121+ yield* publish(snapshots);apps/web/src/components/usage/UsageLimits.tsx line 432OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +412,21 @@412+ <Button size="xs" variant="outline" onClick={() => setAdding(true)}>413+ <PlusIcon className="size-3" aria-hidden />414+ Add CLIProxyAPI hub415+ </Button>416+ ) : null;417+418+ return (419+ <div className="flex flex-col gap-8">420+ {groups.length === 0 && sources.length === 0 ? (421+ <p className="text-sm text-muted-foreground">422+ No provider on a connected environment reports subscription limits.423+ </p>424+ ) : null}425+ {sources.map((source) => (426+ <SourceLimits427+ key={source.key}428+ source={source}429+ now={now}430+ // Only the primary environment's own sources can be edited from here.431+ onRemove={432+ canEditSources && source.id in configuredSources ? () => removeSource(source.id) : nullapps/server/src/ws.ts lines 1682 to 1682OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1674,3 +1676,7 @@16741676 observeRpcEffect(16751677 WS_METHODS.serverRefreshProviders,16761678 Effect.gen(function* () {1679+ // An untargeted refresh is "re-read everything's status", which1680+ // includes quota from configured usage-limit sources.1681+ if (input.instanceId === undefined) {1682+ yield* usageLimitSources.refresh.pipe(Effect.forkScoped);apps/server/src/provider/makeManagedServerProvider.ts line 160Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -141,13 +153,8 @@141- const nextSnapshot = yield* input.checkProvider;142- const nextGeneration = yield* Ref.modify(snapshotStateRef, (state) => {143- const generation = input.enrichSnapshot144- ? state.enrichmentGeneration + 1145- : state.enrichmentGeneration;146- return [147- generation,148- {149- snapshot: nextSnapshot,150- enrichmentGeneration: generation,151- },152- ] as const;153- });153+ const probedSnapshot = yield* input.checkProvider;154+ const { snapshot: nextSnapshot, generation: nextGeneration } = yield* Ref.modify(155+ snapshotStateRef,156+ (state) => {157+ const generation = input.enrichSnapshot158+ ? state.enrichmentGeneration + 1159+ : state.enrichmentGeneration;160+ const snapshot = withUsageLimits(apps/server/src/provider/Layers/ClaudeAdapter.ts line 3609Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3595,9 +3598,12 @@35953598 }3596359935973600 if (message.type === "rate_limit_event") {3601+ const names = options?.scopedLimitNames3602+ ? yield* Ref.get(options.scopedLimitNames)3603+ : { overageIncluded: undefined };3604+ const limits = claudeRateLimitEventToUpdate(message.rate_limit_info, names);3605+ if (!limits) return;35983606 yield* offerRuntimeEvent({35993607 ...base,36003608 type: "account.rate-limits.updated",3601- payload: {3602- rateLimits: message,3603- },3609+ payload: { limits },apps/web/src/components/usage/AddUsageLimitSourceDialog.tsx line 34Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +8,21 @@8+ DialogDescription,9+ DialogFooter,10+ DialogHeader,11+ DialogPopup,12+ DialogTitle,13+} from "../ui/dialog";14+import { Input } from "../ui/input";15+import { Label } from "../ui/label";16+17+function sourceIdFromUrl(url: string): UsageLimitSourceId {18+ let host = url;19+ try {20+ host = new URL(url).host;21+ } catch {22+ // Keep the raw text; the server validates the URL when it polls.23+ }24+ const slug = host25+ .toLowerCase()26+ .replace(/[^a-z0-9]+/g, "-")27+ .replace(/^-+|-+$/g, "");28+ return UsageLimitSourceId.make(`cliproxy-${slug || "hub"}`);apps/server/src/usage/UsageLimitSources.ts lines 84 to 84OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +64,21 @@64+65+export const make = Effect.gen(function* () {66+ const httpClient = yield* HttpClient.HttpClient;67+ const settingsService = yield* ServerSettingsService;68+ const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;69+ const stateRef = yield* Ref.make<ReadonlyArray<UsageLimitSourceSnapshot>>([]);70+ const changes = yield* Effect.acquireRelease(71+ PubSub.unbounded<ReadonlyArray<UsageLimitSourceSnapshot>>(),72+ PubSub.shutdown,73+ );74+75+ const readSource = Effect.fn("UsageLimitSources.readSource")(function* (76+ id: UsageLimitSourceId,77+ config: UsageLimitSourceConfig,78+ ) {79+ const checkedAt = DateTime.formatIso(yield* DateTime.now);80+ const base = { id, kind: config.kind, label: sourceLabel(id, config), checkedAt } as const;81+ if (config.managementKey.length === 0) {82+ return { ...base, accounts: [], error: "No management key configured." };83+ }84+ const url = new URL(QUOTA_STATUS_PATH, config.url).toString();apps/server/src/provider/Layers/claudeUsageLimits.ts line 185OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +165,21 @@165+ names: { overageIncluded: undefined },166+ };167+ }168+ const windows: ServerProviderUsageWindow[] = [];169+ for (const id of Object.keys(WINDOWS)) {170+ const window = response.rate_limits[id as "five_hour" | "seven_day"];171+ if (!window || typeof window.utilization !== "number") continue;172+ windows.push(makeWindow(id, window.utilization, isoFromString(window.resets_at)));173+ }174+ // The CLI filters `model_scoped` to the overage-included allowlist, which175+ // today holds one model; the first entry is the one the event refers to.176+ const scoped = readModelScoped(response.rate_limits);177+ for (const entry of scoped) {178+ if (typeof entry.utilization !== "number") continue;179+ windows.push(180+ scopedWindow(entry.display_name, entry.utilization, isoFromString(entry.resets_at)),181+ );182+ }183+ return {184+ limits: makeUsageLimits({ checkedAt, windows }),185+ names: { overageIncluded: scoped[0]?.display_name },apps/server/src/usage/cliproxyUsageLimits.ts lines 102 to 102OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +82,21 @@82+ kind: "weekly",83+ label: "Weekly · Fable",84+ windowDurationMins: WEEK_MINS,85+ },86+];87+88+const DRIVER_BY_HUB_PROVIDER: Readonly<Record<string, ProviderDriverKind>> = {89+ claude: ProviderDriverKind.make("claudeAgent"),90+ codex: ProviderDriverKind.make("codex"),91+};92+93+function isoFromHub(value: string | undefined): string | undefined {94+ if (!value) return undefined;95+ const dt = DateTime.make(value);96+ return Option.isSome(dt) ? DateTime.formatIso(dt.value) : undefined;97+}98+99+/** `claude-julius@ping.gg.json` → `julius@ping.gg`; `codex-<hash>-x@y-pro.json` → `x@y`. */100+export function accountEmailFromAuthFile(fileName: string): string | undefined {101+ const stem = fileName.replace(/\.json$/i, "");102+ return stem.match(/[^\s/-]+@[^\s/]+?(?=(?:-[a-z0-9]+)?$)/i)?.[0];
- apps/web/src/components/usage/AddUsageLimitSourceDialog.tsx lines 134 to 134OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +114,21 @@114+ <Input115+ id="usage-source-key"116+ type="password"117+ autoComplete="off"118+ value={managementKey}119+ onChange={(event) => setManagementKey(event.target.value)}120+ />121+ </div>122+ <div className="grid gap-1.5">123+ <Label htmlFor="usage-source-label">Label (optional)</Label>124+ <Input125+ id="usage-source-label"126+ placeholder="Defaults to the hub's host name"127+ value={label}128+ onChange={(event) => setLabel(event.target.value)}129+ />130+ </div>131+ </form>132+ </DialogPanel>133+ <DialogFooter variant="bare">134+ <Button variant="outline" onClick={() => onOpenChange(false)}>
- apps/server/src/usage/UsageLimitSources.ts line 84OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +64,21 @@64+65+export const make = Effect.gen(function* () {66+ const httpClient = yield* HttpClient.HttpClient;67+ const settingsService = yield* ServerSettingsService;68+ const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;69+ const stateRef = yield* Ref.make<ReadonlyArray<UsageLimitSourceSnapshot>>([]);70+ const changes = yield* Effect.acquireRelease(71+ PubSub.unbounded<ReadonlyArray<UsageLimitSourceSnapshot>>(),72+ PubSub.shutdown,73+ );74+75+ const readSource = Effect.fn("UsageLimitSources.readSource")(function* (76+ id: UsageLimitSourceId,77+ config: UsageLimitSourceConfig,78+ ) {79+ const checkedAt = DateTime.formatIso(yield* DateTime.now);80+ const base = { id, kind: config.kind, label: sourceLabel(id, config), checkedAt } as const;81+ if (config.managementKey.length === 0) {82+ return { ...base, accounts: [], error: "No management key configured." };83+ }84+ const url = new URL(QUOTA_STATUS_PATH, config.url).toString();apps/server/src/usage/UsageLimitSources.ts line 122OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +102,21 @@102+ Effect.gen(function* () {103+ const changed = yield* Ref.modify(stateRef, (previous) =>104+ Equal.equals(previous, next) ? [false, previous] : [true, next],105+ );106+ if (changed) yield* PubSub.publish(changes, next);107+ });108+109+ const refresh = Effect.gen(function* () {110+ const settings = yield* settingsService.getSettings.pipe(111+ Effect.orElseSucceed((): ServerSettings | null => null),112+ );113+ const entries = Object.entries(settings?.usageLimitSources ?? {}).filter(114+ ([, config]) => config.enabled,115+ );116+ const snapshots = yield* Effect.forEach(117+ entries,118+ ([id, config]) => readSource(id as UsageLimitSourceId, config),119+ { concurrency: 4 },120+ );121+ yield* publish(snapshots);122+ }).pipe(Effect.ignoreCause({ log: true }));
- apps/server/src/provider/Layers/codexUsageLimits.ts lines 106 to 106OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +86,21 @@86+ readonly checkedAt: string;87+}): ServerProviderUsageLimits {88+ return makeUsageLimits({89+ checkedAt: input.checkedAt,90+ windows: codexRateLimitsToWindows(input.snapshot),91+ });92+}93+94+export function codexRateLimitsToUpdate(95+ snapshot: CodexRateLimitSnapshot,96+): ProviderUsageLimitsUpdate | undefined {97+ const windows = codexRateLimitsToWindows(snapshot);98+ return windows.length > 0 ? { windows } : undefined;99+}100+101+/**102+ * Codex's rate-limit errors arrive as a generic JSON-RPC failure whose message103+ * already says what went wrong (the upstream status, and for a lapsed login104+ * the `token_revoked` body). Keep it, labelled with where it came from.105+ */106+export function codexRateLimitsFailureMessage(error: unknown): string {apps/server/src/usage/UsageLimitSources.ts lines 54 to 54Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +31,21 @@31+import * as Stream from "effect/Stream";32+import { HttpClient, HttpClientResponse } from "effect/unstable/http";33+34+import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";35+import { ServerSettingsService } from "../serverSettings.ts";36+import { cliproxyStatusToAccounts, decodeCliproxyQuotaStatus } from "./cliproxyUsageLimits.ts";37+38+const FETCH_TIMEOUT = "10 seconds";39+const QUOTA_STATUS_PATH = "/v0/management/quota-scheduler/status";40+41+export class UsageLimitSources extends Context.Service<42+ UsageLimitSources,43+ {44+ readonly current: Effect.Effect<ReadonlyArray<UsageLimitSourceSnapshot>>;45+ /** The current set followed by every change, with repeats dropped. */46+ readonly streamChanges: Stream.Stream<ReadonlyArray<UsageLimitSourceSnapshot>>;47+ /** Re-read every source now. Never fails; failures land on the snapshot. */48+ readonly refresh: Effect.Effect<void>;49+ }50+>()("t3/usage/UsageLimitSources") {}51+@@ -1674,3 +1676,7 @@16741676 observeRpcEffect(16751677 WS_METHODS.serverRefreshProviders,16761678 Effect.gen(function* () {1679+ // An untargeted refresh is "re-read everything's status", which1680+ // includes quota from configured usage-limit sources. Awaited,1681+ // not forked: the RPC scope closes on return and would1682+ // interrupt a fork before the hub answered.
- apps/web/src/components/usage/UsageLimits.tsx line 407OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +387,21 @@387+}388+389+/**390+ * Subscription quota windows from every connected environment's providers.391+ * Countdowns anchor to render time rather than ticking: a live clock would392+ * repaint the page every minute for no decision-changing gain.393+ */394+export function UsageLimitsSection() {395+ const presentations = useAtomValue(environmentPresentations.presentationsAtom);396+ const groups = collectLimitsGroups(presentations);397+ const sources = collectLimitSources(presentations);398+ const configuredSources = usePrimarySettings((settings) => settings.usageLimitSources);399+ const canEditSources = usePrimarySettingsAvailable();400+ const primaryEnvironmentId = usePrimaryEnvironmentId();401+ const updateSettings = useUpdatePrimarySettings();402+ const [adding, setAdding] = useState(false);403+ // Anchored once per mount on purpose: countdowns must not tick (see below).404+ const [now] = useState(() => Date.now());405+406+ const removeSource = (id: UsageLimitSourceId) => {407+ const rest = Object.fromEntries(
- apps/server/src/usage/UsageLimitSources.ts line 98Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +76,21 @@76+ readonly _tag = "InvalidUrl";77+}78+79+function sourceLabel(id: string, config: UsageLimitSourceConfig): string {80+ if (config.label) return config.label;81+ try {82+ return new URL(config.url).host;83+ } catch {84+ return id;85+ }86+}87+88+export const make = Effect.gen(function* () {89+ const httpClient = yield* HttpClient.HttpClient;90+ const settingsService = yield* ServerSettingsService;91+ const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;92+ const stateRef = yield* Ref.make<ReadonlyArray<UsageLimitSourceSnapshot>>([]);93+ const changes = yield* Effect.acquireRelease(94+ PubSub.unbounded<ReadonlyArray<UsageLimitSourceSnapshot>>(),95+ PubSub.shutdown,96+ );
- apps/web/src/components/usage/AddUsageLimitSourceDialog.tsx line 68OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +48,21 @@48+ readonly open: boolean;49+ readonly onOpenChange: (open: boolean) => void;50+}) {51+ const updateSettings = useUpdatePrimarySettings();52+ const [label, setLabel] = useState("");53+ const [url, setUrl] = useState("");54+ const [managementKey, setManagementKey] = useState("");55+ const trimmedUrl = url.trim();56+ const canSave = trimmedUrl.length > 0 && managementKey.trim().length > 0;57+58+ const reset = () => {59+ setLabel("");60+ setUrl("");61+ setManagementKey("");62+ };63+64+ const save = () => {65+ if (!canSave) return;66+ const id = sourceIdFromUrl(trimmedUrl);67+ // Same reason as removal: merge into the map as it is now, not as rendered.68+ const current = appAtomRegistry.get(primaryServerSettingsAtom).usageLimitSources;
- apps/server/src/usage/UsageLimitSources.ts lines 75 to 77OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +57,21 @@57+ */58+function readFailureMessage(59+ error: HttpClientError.HttpClientError | Schema.SchemaError | Cause.TimeoutError | InvalidUrl,60+): string {61+ switch (error._tag) {62+ case "InvalidUrl":63+ return "The hub URL is not valid.";64+ case "TimeoutError":65+ return "The hub did not answer in time.";66+ case "SchemaError":67+ return "The hub answered with an unexpected shape.";68+ case "HttpClientError":69+ return error.reason._tag === "StatusCodeError"70+ ? `The hub refused the request (HTTP ${error.reason.response.status}).`71+ : "The hub could not be reached.";72+ }73+}74+75+class InvalidUrl {76+ readonly _tag = "InvalidUrl";77+}
juliusmarminge merged this19d8ab2
juliusmarminge closed this
Sign in to join this conversation.






macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed