Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
feat(quota): show per-account upstream quota in the pool card
diegosouzapw18b615f5f065
diff --git a/src/app/(dashboard)/dashboard/costs/quota-share/QuotaSharePageClient.tsx b/src/app/(dashboard)/dashboard/costs/quota-share/QuotaSharePageClient.tsxindex fb0e483de1..b0def14f31 100644--- a/src/app/(dashboard)/dashboard/costs/quota-share/QuotaSharePageClient.tsx+++ b/src/app/(dashboard)/dashboard/costs/quota-share/QuotaSharePageClient.tsx@@ -83,6 +83,7 @@ function PoolCardWithUsage({connectionLabel,provider,providers,+ connectionIds,onEdit,onRemove,}: {@@ -91,6 +92,7 @@ function PoolCardWithUsage({connectionLabel: string;provider: string;providers?: string[];+ connectionIds?: string[];onEdit: () => void;onRemove: () => void;}) {@@ -103,6 +105,7 @@ function PoolCardWithUsage({connectionLabel={connectionLabel}provider={provider}providers={providers}+ connectionIds={connectionIds}onEdit={onEdit}onRemove={onRemove}/>@@ -291,6 +294,7 @@ export default function QuotaSharePageClient() {connectionLabel={connLabel(pool.connectionId)}provider={connProvider(pool.connectionId)}providers={[...new Set((pool.connectionIds ?? [pool.connectionId]).map(connProvider))]}+ connectionIds={pool.connectionIds ?? [pool.connectionId]}onEdit={() => setEditing(pool)}onRemove={() => void handleRemovePool(pool.id)}/>diff --git a/src/app/(dashboard)/dashboard/costs/quota-share/components/AccountQuotaRow.tsx b/src/app/(dashboard)/dashboard/costs/quota-share/components/AccountQuotaRow.tsxnew file mode 100644index 0000000000..87b93bb2b8--- /dev/null+++ b/src/app/(dashboard)/dashboard/costs/quota-share/components/AccountQuotaRow.tsx@@ -0,0 +1,184 @@+"use client";++import { useTranslations } from "next-intl";+import { useState, useEffect } from "react";+import ProviderIcon from "@/shared/components/ProviderIcon";+import {+ parseQuotaData,+ calculatePercentage,+ formatCountdown,+} from "@/app/(dashboard)/dashboard/usage/components/ProviderLimits/utils";++interface AccountQuotaRowProps {+ /** Primary provider identifier (used as fallback when providers is absent) */+ provider: string;+ /** Optional list of all provider identifiers — one per connection in the pool */+ providers?: string[];+ /** Optional list of connection IDs — used to look up cached quota data */+ connectionIds?: string[];+}++interface QuotaSummary {+ pct: number;+ resetAt: string | null;+}++/** Aggregate the worst-remaining quota across all quotas for a connection. */+function summarizeQuotas(provider: string, raw: unknown): QuotaSummary | null {+ if (!raw || typeof raw !== "object") return null;+ const parsed = parseQuotaData(provider, raw);+ if (!Array.isArray(parsed) || parsed.length === 0) return null;++ let worst: number | null = null;+ let closestResetAt: string | null = null;+ let closestResetMs = Number.POSITIVE_INFINITY;+ const now = Date.now();++ for (const q of parsed) {+ if (!q || q.unlimited) continue;+ const pct =+ q.remainingPercentage !== undefined+ ? Number(q.remainingPercentage)+ : calculatePercentage(q.used, q.total);+ if (!Number.isFinite(pct)) continue;+ if (worst === null || pct < worst) worst = pct;++ if (q.resetAt) {+ const ts = new Date(q.resetAt).getTime();+ if (Number.isFinite(ts) && ts > now && ts < closestResetMs) {+ closestResetMs = ts;+ closestResetAt = typeof q.resetAt === "string" ? q.resetAt : new Date(ts).toISOString();+ }+ }+ }++ if (worst === null) return null;+ return { pct: Math.round(worst), resetAt: closestResetAt };+}++function PctDot({ pct }: { pct: number }) {+ const color =+ pct <= 20 ? "bg-red-500" : pct <= 50 ? "bg-yellow-500" : "bg-emerald-500";+ const textColor =+ pct <= 20 ? "text-red-500" : pct <= 50 ? "text-yellow-500" : "text-emerald-500";+ return (+ <span className={`inline-flex items-center gap-1 tabular-nums text-[11px] ${textColor}`}>+ <span className={`w-1.5 h-1.5 rounded-full shrink-0 ${color}`} aria-hidden />+ {pct}%+ </span>+ );+}++/**+ * AccountQuotaRow — read-only compact section showing each pool connection's+ * upstream account quota, sourced from GET /api/usage/provider-limits (bulk+ * cached endpoint, same as ProviderLimits.tsx uses).+ *+ * Fail-soft: on error / loading / no data → renders a muted "—" line.+ * Never throws; never crashes the parent PoolCard.+ */+export default function AccountQuotaRow({+ provider,+ providers,+ connectionIds,+}: AccountQuotaRowProps) {+ const t = useTranslations("quotaShare");++ // Keyed by connectionId+ const [caches, setCaches] = useState<Record<string, unknown> | null>(null);+ const [error, setError] = useState(false);++ useEffect(() => {+ let alive = true;+ fetch("/api/usage/provider-limits")+ .then((r) => (r.ok ? r.json() : null))+ .then((data) => {+ if (!alive) return;+ const map = data?.caches;+ setCaches(map && typeof map === "object" ? (map as Record<string, unknown>) : {});+ })+ .catch(() => {+ if (alive) setError(true);+ });+ return () => {+ alive = false;+ };+ }, []);++ // Resolve the effective connection list to display+ const ids: string[] = Array.isArray(connectionIds) && connectionIds.length > 0+ ? connectionIds+ : [];++ // Resolve provider for each connection (providers[i] matches connectionIds[i])+ const providerFor = (index: number): string =>+ Array.isArray(providers) && providers[index] != null+ ? (providers[index] as string)+ : provider;++ const renderFallback = () => (+ <span className="text-[11px] text-text-muted tabular-nums">+ {t("accountQuotaNone")}+ </span>+ );++ if (error || caches === null) {+ return (+ <div className="mt-2 pt-2 border-t border-border/30">+ <span className="text-[10px] uppercase tracking-wide font-bold text-text-muted block mb-1">+ {t("accountQuotaTitle")}+ </span>+ {renderFallback()}+ </div>+ );+ }++ // If no connectionIds, nothing to display+ if (ids.length === 0) {+ return (+ <div className="mt-2 pt-2 border-t border-border/30">+ <span className="text-[10px] uppercase tracking-wide font-bold text-text-muted block mb-1">+ {t("accountQuotaTitle")}+ </span>+ {renderFallback()}+ </div>+ );+ }++ return (+ <div className="mt-2 pt-2 border-t border-border/30">+ <span className="text-[10px] uppercase tracking-wide font-bold text-text-muted block mb-1.5">+ {t("accountQuotaTitle")}+ </span>+ <div className="flex flex-col gap-1">+ {ids.map((connId, idx) => {+ const raw = caches?.[connId];+ const prov = providerFor(idx);+ const summary = summarizeQuotas(prov, raw);+ const reset = summary?.resetAt ? formatCountdown(summary.resetAt) : null;++ return (+ <div key={connId} className="flex items-center gap-1.5 text-[11px]">+ <span className="shrink-0">+ <ProviderIcon providerId={prov} size={14} />+ </span>+ <span className="text-text-muted truncate max-w-[90px]" title={connId}>+ {connId.slice(0, 8)}…+ </span>+ {summary ? (+ <>+ <PctDot pct={summary.pct} />+ {reset ? (+ <span className="text-text-muted">· {reset}</span>+ ) : null}+ </>+ ) : (+ <span className="text-text-muted">{t("accountQuotaNone")}</span>+ )}+ </div>+ );+ })}+ </div>+ </div>+ );+}diff --git a/src/app/(dashboard)/dashboard/costs/quota-share/components/PoolCard.tsx b/src/app/(dashboard)/dashboard/costs/quota-share/components/PoolCard.tsxindex 657d505294..ba8acdb9f4 100644--- a/src/app/(dashboard)/dashboard/costs/quota-share/components/PoolCard.tsx+++ b/src/app/(dashboard)/dashboard/costs/quota-share/components/PoolCard.tsx@@ -9,6 +9,7 @@ import DimensionBar from "./DimensionBar";import AllocationTable from "./AllocationTable";import BurnRateChart from "./BurnRateChart";import StackedAllocationBar from "./StackedAllocationBar";+import AccountQuotaRow from "./AccountQuotaRow";export interface PoolCardProps {pool: QuotaPool;@@ -21,6 +22,8 @@ export interface PoolCardProps {provider: string;/** Optional list of all provider identifiers when pool has multiple connections */providers?: string[];+ /** Optional list of all connection IDs in this pool — passed to AccountQuotaRow */+ connectionIds?: string[];onEdit: () => void;onRemove: () => void;}@@ -50,6 +53,7 @@ export default function PoolCard({connectionLabel,provider,providers,+ connectionIds,onEdit,onRemove,}: PoolCardProps) {@@ -162,6 +166,13 @@ export default function PoolCard({/></div>+ {/* Account quota row — read-only upstream quota per connection */}+ <AccountQuotaRow+ provider={provider}+ providers={providers}+ connectionIds={connectionIds}+ />+{/* Burn rate chart */}{usage && (<div className="pt-2 border-t border-border/30">diff --git a/src/i18n/messages/en.json b/src/i18n/messages/en.jsonindex 6fc61a18ba..8ed99aa60c 100644--- a/src/i18n/messages/en.json+++ b/src/i18n/messages/en.json@@ -7894,7 +7894,9 @@"wizardPrimaryBadge": "primary","wizardAdditionalConnectionsNote": "Additional connections use their catalog default limits (editable later).","wizardSingleProviderNote": "A pool uses a single provider",- "wizardPreviewMoreModels": "+{count} more"+ "wizardPreviewMoreModels": "+{count} more",+ "accountQuotaTitle": "Account quota",+ "accountQuotaNone": "—"},"plugins": {"title": "Plugins",diff --git a/src/i18n/messages/pt-BR.json b/src/i18n/messages/pt-BR.jsonindex b07742e6cf..e914c9f982 100644--- a/src/i18n/messages/pt-BR.json+++ b/src/i18n/messages/pt-BR.json@@ -5404,7 +5404,9 @@"wizardPrimaryBadge": "principal","wizardAdditionalConnectionsNote": "Conexões adicionais usam os limites padrão do catálogo (editáveis posteriormente).","wizardSingleProviderNote": "Um pool usa um provedor só",- "wizardPreviewMoreModels": "+{count} mais"+ "wizardPreviewMoreModels": "+{count} mais",+ "accountQuotaTitle": "Cota da conta",+ "accountQuotaNone": "—"},"requestLogger": {"recording": "Recording",diff --git a/tests/unit/quota-account-quota-row.test.ts b/tests/unit/quota-account-quota-row.test.tsnew file mode 100644index 0000000000..668ec0e258--- /dev/null+++ b/tests/unit/quota-account-quota-row.test.ts@@ -0,0 +1,154 @@+/**+ * Task 6 — AccountQuotaRow structural tests+ *+ * These tests use source-level assertions (readFileSync) so they work with the+ * Node.js native test runner without a DOM / React rendering setup.+ */+import test from "node:test";+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import { join, dirname } from "node:path";+import { fileURLToPath } from "node:url";++const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..", "..");++const ACCOUNT_QUOTA_ROW_PATH = join(+ ROOT,+ "src/app/(dashboard)/dashboard/costs/quota-share/components/AccountQuotaRow.tsx"+);++const POOL_CARD_PATH = join(+ ROOT,+ "src/app/(dashboard)/dashboard/costs/quota-share/components/PoolCard.tsx"+);++const EN_PATH = join(ROOT, "src/i18n/messages/en.json");+const PT_PATH = join(ROOT, "src/i18n/messages/pt-BR.json");++// ── Load sources ─────────────────────────────────────────────────────────────++const accountQuotaSrc = readFileSync(ACCOUNT_QUOTA_ROW_PATH, "utf8");+const poolCardSrc = readFileSync(POOL_CARD_PATH, "utf8");++// ── i18n parity ──────────────────────────────────────────────────────────────++const NEW_KEYS = ["accountQuotaTitle", "accountQuotaNone"] as const;++test("i18n: new keys present in en.json", () => {+ const en = JSON.parse(readFileSync(EN_PATH, "utf8")) as Record<string, Record<string, string>>;+ for (const k of NEW_KEYS) {+ assert.equal(+ typeof en["quotaShare"]?.[k],+ "string",+ `en.json missing quotaShare.${k}`+ );+ }+});++test("i18n: new keys present in pt-BR.json", () => {+ const pt = JSON.parse(readFileSync(PT_PATH, "utf8")) as Record<string, Record<string, string>>;+ for (const k of NEW_KEYS) {+ assert.equal(+ typeof pt["quotaShare"]?.[k],+ "string",+ `pt-BR.json missing quotaShare.${k}`+ );+ }+});++test("i18n: parity between en and pt-BR for new keys", () => {+ const en = JSON.parse(readFileSync(EN_PATH, "utf8")) as Record<string, Record<string, string>>;+ const pt = JSON.parse(readFileSync(PT_PATH, "utf8")) as Record<string, Record<string, string>>;+ for (const k of NEW_KEYS) {+ assert.ok(+ k in (en["quotaShare"] ?? {}),+ `en.json missing quotaShare.${k}`+ );+ assert.ok(+ k in (pt["quotaShare"] ?? {}),+ `pt-BR.json missing quotaShare.${k}`+ );+ }+});++// ── AccountQuotaRow structural assertions ────────────────────────────────────++test("AccountQuotaRow: fetches /api/usage/provider-limits endpoint", () => {+ assert.ok(+ accountQuotaSrc.includes("/api/usage/provider-limits"),+ "AccountQuotaRow must fetch the /api/usage/provider-limits endpoint"+ );+});++test("AccountQuotaRow: guards caches with optional chaining (no unguarded dereference)", () => {+ // Must use ?. when accessing caches map+ assert.ok(+ accountQuotaSrc.includes("caches?.["),+ "AccountQuotaRow must use optional chaining when accessing caches (caches?.[connId])"+ );+});++test("AccountQuotaRow: uses Array.isArray guard before relying on connectionIds", () => {+ assert.ok(+ accountQuotaSrc.includes("Array.isArray(connectionIds)"),+ "AccountQuotaRow must guard connectionIds with Array.isArray"+ );+});++test("AccountQuotaRow: uses Array.isArray guard before iterating parsed quotas", () => {+ assert.ok(+ accountQuotaSrc.includes("Array.isArray(parsed)"),+ "AccountQuotaRow must guard parsed result with Array.isArray"+ );+});++test("AccountQuotaRow: fail-soft — renders accountQuotaNone when empty", () => {+ assert.ok(+ accountQuotaSrc.includes("accountQuotaNone"),+ "AccountQuotaRow must render the accountQuotaNone fallback string"+ );+});++test("AccountQuotaRow: uses ProviderIcon from shared components", () => {+ assert.ok(+ accountQuotaSrc.includes("ProviderIcon"),+ "AccountQuotaRow must render a ProviderIcon per connection"+ );+});++test("AccountQuotaRow: cleans up fetch with alive flag to prevent state-after-unmount", () => {+ assert.ok(+ accountQuotaSrc.includes("alive = false"),+ "AccountQuotaRow must set alive = false in useEffect cleanup"+ );+});++// ── PoolCard mounts AccountQuotaRow ──────────────────────────────────────────++test("PoolCard: imports AccountQuotaRow", () => {+ assert.ok(+ poolCardSrc.includes("AccountQuotaRow"),+ "PoolCard.tsx must import and render AccountQuotaRow"+ );+});++test("PoolCard: mounts <AccountQuotaRow in JSX", () => {+ assert.ok(+ poolCardSrc.includes("<AccountQuotaRow"),+ "PoolCard.tsx must render <AccountQuotaRow .../>"+ );+});++test("PoolCard: passes connectionIds prop to AccountQuotaRow", () => {+ assert.ok(+ poolCardSrc.includes("connectionIds={connectionIds}"),+ "PoolCard.tsx must pass connectionIds to AccountQuotaRow"+ );+});++test("PoolCard: declares connectionIds in PoolCardProps interface", () => {+ assert.ok(+ poolCardSrc.includes("connectionIds?:"),+ "PoolCardProps must declare optional connectionIds field"+ );+});