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
fix(codex): address PR review feedback for quota policy flow
rexname155588363342
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/page.tsx b/src/app/(dashboard)/dashboard/providers/[id]/page.tsxindex a25668823d..80a7b27273 100644--- a/src/app/(dashboard)/dashboard/providers/[id]/page.tsx+++ b/src/app/(dashboard)/dashboard/providers/[id]/page.tsx@@ -32,6 +32,17 @@ import {import { getModelsByProviderId } from "@/shared/constants/models";import { useCopyToClipboard } from "@/shared/hooks/useCopyToClipboard";+function normalizeCodexLimitPolicy(policy: unknown): { use5h: boolean; useWeekly: boolean } {+ const record =+ policy && typeof policy === "object" && !Array.isArray(policy)+ ? (policy as Record<string, unknown>)+ : {};+ return {+ use5h: typeof record.use5h === "boolean" ? record.use5h : true,+ useWeekly: typeof record.useWeekly === "boolean" ? record.useWeekly : true,+ };+}+export default function ProviderDetailPage() {const params = useParams();const router = useRouter();@@ -49,6 +60,7 @@ export default function ProviderDetailPage() {const [headerImgError, setHeaderImgError] = useState(false);const { copied, copy } = useCopyToClipboard();const t = useTranslations("providers");+ const notify = useNotificationStore();const hasAutoOpened = useRef(false);const userDismissed = useRef(false);const [proxyTarget, setProxyTarget] = useState(null);@@ -327,8 +339,7 @@ export default function ProviderDetailPage() {: {};const nextPolicy = {- use5h: typeof existingPolicy.use5h === "boolean" ? existingPolicy.use5h : true,- useWeekly: typeof existingPolicy.useWeekly === "boolean" ? existingPolicy.useWeekly : true,+ ...normalizeCodexLimitPolicy(existingPolicy),[field]: enabled,};@@ -343,23 +354,29 @@ export default function ProviderDetailPage() {}),});- if (res.ok) {- setConnections((prev) =>- prev.map((connection) =>- connection.id === connectionId- ? {- ...connection,- providerSpecificData: {- ...(connection.providerSpecificData || {}),- codexLimitPolicy: nextPolicy,- },- }- : connection- )- );+ if (!res.ok) {+ const data = await res.json().catch(() => ({}));+ notify.error(data.error || "Failed to update Codex limit policy");+ return;}++ setConnections((prev) =>+ prev.map((connection) =>+ connection.id === connectionId+ ? {+ ...connection,+ providerSpecificData: {+ ...(connection.providerSpecificData || {}),+ codexLimitPolicy: nextPolicy,+ },+ }+ : connection+ )+ );+ notify.success("Codex limit policy updated");} catch (error) {console.error("Error toggling Codex quota policy:", error);+ notify.error("Failed to update Codex limit policy");}};@@ -383,7 +400,6 @@ export default function ProviderDetailPage() {// T12: Manual token refreshconst [refreshingId, setRefreshingId] = useState<string | null>(null);- const notify = useNotificationStore();const handleRefreshToken = async (connectionId: string) => {if (refreshingId) return;setRefreshingId(connectionId);@@ -2309,9 +2325,9 @@ function ConnectionRow({typeof connection.providerSpecificData.codexLimitPolicy === "object"? connection.providerSpecificData.codexLimitPolicy: {};- const codex5hEnabled = typeof codexPolicy.use5h === "boolean" ? codexPolicy.use5h : true;- const codexWeeklyEnabled =- typeof codexPolicy.useWeekly === "boolean" ? codexPolicy.useWeekly : true;+ const normalizedCodexPolicy = normalizeCodexLimitPolicy(codexPolicy);+ const codex5hEnabled = normalizedCodexPolicy.use5h;+ const codexWeeklyEnabled = normalizedCodexPolicy.useWeekly;return (<divdiff --git a/src/domain/quotaCache.ts b/src/domain/quotaCache.tsindex 30df9c8852..a0b0e2caad 100644--- a/src/domain/quotaCache.ts+++ b/src/domain/quotaCache.ts@@ -200,10 +200,6 @@ export function getQuotaWindowStatus(if (!entry) return null;const now = Date.now();- const advanced = advancedWindowResetAt(entry, now);- if (advanced) {- entry.exhausted = false;- }const window = entry.quotas[windowName];if (!window) return null;@@ -212,10 +208,12 @@ export function getQuotaWindowStatus(const usedPercentage = clampPercent(100 - remainingPercentage);let resetAt = window.resetAt || null;+ let windowExpired = false;if (resetAt) {const resetMs = parseDate(resetAt);if (resetMs !== null && resetMs <= now) {resetAt = null;+ windowExpired = true;}}@@ -223,7 +221,8 @@ export function getQuotaWindowStatus(remainingPercentage,usedPercentage,resetAt,- reachedThreshold: usedPercentage >= thresholdPercent,+ // If reset time has already passed, avoid stale cached percentages blocking selection.+ reachedThreshold: windowExpired ? false : usedPercentage >= thresholdPercent,};}diff --git a/src/sse/services/auth.ts b/src/sse/services/auth.tsindex c431c2952e..d1d834714d 100644--- a/src/sse/services/auth.ts+++ b/src/sse/services/auth.ts@@ -38,6 +38,8 @@ interface ProviderConnectionView {backoffLevel: number;}+const CODEX_QUOTA_THRESHOLD_PERCENT = 90;+function asRecord(value: unknown): JsonRecord {return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};}@@ -101,6 +103,18 @@ function parseFutureDateMs(value: string | null): number | null {return ms;}+function getEarliestFutureDate(candidates: Array<string | null>): string | null {+ return (+ candidates+ .map((candidate) => ({+ raw: candidate,+ ms: parseFutureDateMs(candidate),+ }))+ .filter((entry) => entry.ms !== null)+ .sort((a, b) => (a.ms as number) - (b.ms as number))[0]?.raw || null+ );+}+// Mutex to prevent race conditions during account selectionlet selectionMutex = Promise.resolve();@@ -231,10 +245,10 @@ export async function getProviderCredentials(policyEligibleConnections = availableConnections.filter((connection) => {const policy = getCodexLimitPolicy(connection.providerSpecificData);const sessionStatus = policy.use5h- ? getQuotaWindowStatus(connection.id, "session", 90)+ ? getQuotaWindowStatus(connection.id, "session", CODEX_QUOTA_THRESHOLD_PERCENT): null;const weeklyStatus = policy.useWeekly- ? getQuotaWindowStatus(connection.id, "weekly", 90)+ ? getQuotaWindowStatus(connection.id, "weekly", CODEX_QUOTA_THRESHOLD_PERCENT): null;const reasons: string[] = [];@@ -251,14 +265,7 @@ export async function getProviderCredentials(}if (reasons.length > 0) {- const nextResetAt =- resetCandidates- .map((candidate) => ({- raw: candidate,- ms: parseFutureDateMs(candidate),- }))- .filter((entry) => entry.ms !== null)- .sort((a, b) => (a.ms as number) - (b.ms as number))[0]?.raw || null;+ const nextResetAt = getEarliestFutureDate(resetCandidates);blockedByPolicy.push({id: connection.id,@@ -281,10 +288,10 @@ export async function getProviderCredentials(}if (policyEligibleConnections.length === 0 && availableConnections.length > 0) {- const earliestResetMs = blockedByPolicy- .map((entry) => parseFutureDateMs(entry.resetAt))- .filter((ms): ms is number => ms !== null)- .sort((a, b) => a - b)[0];+ const earliestResetAt = getEarliestFutureDate(+ blockedByPolicy.map((entry) => entry.resetAt)+ );+ const earliestResetMs = parseFutureDateMs(earliestResetAt);const retryAfter = earliestResetMs? new Date(earliestResetMs).toISOString()