Spaces:
Paused
Paused
icebear icebear0828 commited on
feat: auto-refresh quota with tiered warnings (#92) (#93)
Browse filesBackground quota refresher fetches official usage every 5min (configurable),
caches on AccountEntry for instant dashboard reads, and marks exhausted
accounts as rate_limited. Tiered warning thresholds (default 80%/90%) trigger
visual banners in the dashboard. Frontend auto-polls every 30s.
Co-authored-by: icebear0828 <icebear0828@users.noreply.github.com>
Files changed (19)
- CHANGELOG.md+1
- config/default.yaml+6
- package.json+3
- shared/hooks/use-accounts.ts+10-3
- shared/i18n/translations.ts+4
- shared/types.ts+19-6
- src/auth/__tests__/account-pool-quota.test.tsAdded+181
- src/auth/__tests__/config-quota.test.tsAdded+71
- src/auth/__tests__/quota-utils.test.tsAdded+100
- src/auth/__tests__/quota-warnings.test.tsAdded+117
- src/auth/account-pool.ts+47-1
- src/auth/quota-utils.tsAdded+39
- src/auth/quota-warnings.tsAdded+73
- src/auth/types.ts+5
- src/auth/usage-refresher.tsAdded+161
- src/config.ts+8
- src/index.ts+5
- src/routes/accounts.ts+74-76
- web/src/components/AccountList.tsx+38-2
7 unmodified lines89101112137 unmodified lines### Added- Docker 镜像自动发布:push master 自动构建多架构(amd64/arm64)镜像到 GHCR(`ghcr.io/icebear0828/codex-proxy`),docker-compose.yml 切换为预构建镜像,支持 Watchtower 自动更新- 双窗口配额显示:Dashboard 账号卡片同时展示主窗口(小时限制)和次窗口(周限制)的用量百分比、进度条和重置时间,后端 `secondary_window` 不再被忽略- 更新弹窗 + 自动重启:点击"有可用更新"弹出 Modal 显示 changelog,一键更新后服务器自动重启、前端自动刷新,零人工干预(git 模式 spawn 新进程、Docker/Electron 显示对应操作指引)7 unmodified lines8910111213147 unmodified lines### Added- 额度自动刷新 + 分层预警:后台每 5 分钟(可配置)定时拉取所有账号的官方额度,缓存到 AccountEntry 供 Dashboard 即时读取;额度达到阈值(默认 80%/90%,可自定义)时显示 warning/critical 横幅;额度耗尽的账号自动标记为 rate_limited 跳过分配,到期自动恢复 (#92)- Docker 镜像自动发布:push master 自动构建多架构(amd64/arm64)镜像到 GHCR(`ghcr.io/icebear0828/codex-proxy`),docker-compose.yml 切换为预构建镜像,支持 Watchtower 自动更新- 双窗口配额显示:Dashboard 账号卡片同时展示主窗口(小时限制)和次窗口(周限制)的用量百分比、进度条和重置时间,后端 `secondary_window` 不再被忽略- 更新弹窗 + 自动重启:点击"有可用更新"弹出 Modal 显示 changelog,一键更新后服务器自动重启、前端自动刷新,零人工干预(git 模式 spawn 新进程、Docker/Electron 显示对应操作指引)
34 unmodified lines35363734 unmodified linesimpersonate_profile: chrome144proxy_url: nullforce_http11: true34 unmodified lines35363738394041424334 unmodified linesimpersonate_profile: chrome144proxy_url: nullforce_http11: truequota:refresh_interval_minutes: 5warning_thresholds:primary: [80, 90]secondary: [80, 90]skip_exhausted: true
1 unmodified line2345671 unmodified line"name": "codex-proxy","version": "1.0.55","description": "Reverse proxy that exposes Codex Desktop Responses API as OpenAI-compatible /v1/chat/completions","type": "module","scripts": {"test": "vitest run",1 unmodified line23456789101 unmodified line"name": "codex-proxy","version": "1.0.55","description": "Reverse proxy that exposes Codex Desktop Responses API as OpenAI-compatible /v1/chat/completions","contributors": [{ "name": "Huangcoolbo", "url": "https://github.com/Huangcoolbo" }],"type": "module","scripts": {"test": "vitest run",
9 unmodified lines101112131415161718199 unmodified lines293031323334183 unmodified lines2182192202212222232249 unmodified linesconst [addInfo, setAddInfo] = useState("");const [addError, setAddError] = useState("");const loadAccounts = useCallback(async () => {setRefreshing(true);try {const resp = await fetch("/auth/accounts?quota=true");const data = await resp.json();setList(data.accounts || []);setLastUpdated(new Date());9 unmodified linesloadAccounts();}, [loadAccounts]);// Listen for OAuth callback successuseEffect(() => {const handler = async (event: MessageEvent) => {183 unmodified linesaddVisible,addInfo,addError,refresh: loadAccounts,patchLocal,startAdd,submitRelay,9 unmodified lines10111213141516171819209 unmodified lines303132333435363738394041183 unmodified lines2252262272282292302319 unmodified linesconst [addInfo, setAddInfo] = useState("");const [addError, setAddError] = useState("");const loadAccounts = useCallback(async (fresh = false) => {setRefreshing(true);try {const url = fresh ? "/auth/accounts?quota=fresh" : "/auth/accounts?quota=true";const resp = await fetch(url);const data = await resp.json();setList(data.accounts || []);setLastUpdated(new Date());9 unmodified linesloadAccounts();}, [loadAccounts]);// Auto-poll cached quota every 30suseEffect(() => {const timer = setInterval(() => loadAccounts(), 30_000);return () => clearInterval(timer);}, [loadAccounts]);// Listen for OAuth callback successuseEffect(() => {const handler = async (event: MessageEvent) => {183 unmodified linesaddVisible,addInfo,addError,refresh: useCallback(() => loadAccounts(true), [loadAccounts]),patchLocal,startAdd,submitRelay,
178 unmodified lines179180181182183184178 unmodified lines363364365366367368178 unmodified linesstatusPass: "Pass",statusFail: "Fail",statusSkip: "Skip",},zh: {serverOnline: "\u670d\u52a1\u8fd0\u884c\u4e2d",178 unmodified linesstatusPass: "\u901a\u8fc7",statusFail: "\u5931\u8d25",statusSkip: "\u8df3\u8fc7",},} as const;178 unmodified lines179180181182183184185186178 unmodified lines365366367368369370371372178 unmodified linesstatusPass: "Pass",statusFail: "Fail",statusSkip: "Skip",quotaCriticalWarning: "{count} account(s) approaching quota limit",quotaWarning: "{count} account(s) quota usage elevated",},zh: {serverOnline: "\u670d\u52a1\u8fd0\u884c\u4e2d",178 unmodified linesstatusPass: "\u901a\u8fc7",statusFail: "\u5931\u8d25",statusSkip: "\u8df3\u8fc7",quotaCriticalWarning: "{count} \u4e2a\u8d26\u53f7\u989d\u5ea6\u5373\u5c06\u8017\u5c3d",quotaWarning: "{count} \u4e2a\u8d26\u53f7\u989d\u5ea6\u7528\u91cf\u8f83\u9ad8",},} as const;
1234567891010 unmodified lines212223242526export interface AccountQuota {rate_limit?: {used_percent?: number | null;limit_reached?: boolean;reset_at?: number | null;limit_window_seconds?: number | null;};}export interface Account {10 unmodified lineswindow_output_tokens?: number;};quota?: AccountQuota;proxyId?: string;proxyName?: string;}1234567891011121314151617181920212210 unmodified lines33343536373839export interface AccountQuotaWindow {used_percent?: number | null;limit_reached?: boolean;reset_at?: number | null;limit_window_seconds?: number | null;}export interface AccountQuota {rate_limit?: AccountQuotaWindow;secondary_rate_limit?: AccountQuotaWindow | null;}export interface QuotaWarning {accountId: string;email: string | null;window: "primary" | "secondary";level: "warning" | "critical";usedPercent: number;resetAt: number | null;}export interface Account {10 unmodified lineswindow_output_tokens?: number;};quota?: AccountQuota;quotaFetchedAt?: string | null;proxyId?: string;proxyName?: string;}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181/** * Tests for AccountPool quota-related methods: * - updateCachedQuota() * - markQuotaExhausted() * - toInfo() populating cached quota * - loadPersisted() backfill */
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("fs", () => ({ readFileSync: vi.fn(() => { throw new Error("ENOENT"); }), writeFileSync: vi.fn(), renameSync: vi.fn(), existsSync: vi.fn(() => false), mkdirSync: vi.fn(),}));
vi.mock("../../paths.js", () => ({ getDataDir: vi.fn(() => "/tmp/test-data"), getConfigDir: vi.fn(() => "/tmp/test-config"),}));
vi.mock("../../config.js", () => ({ getConfig: vi.fn(() => ({ auth: { jwt_token: null, rotation_strategy: "least_used", rate_limit_backoff_seconds: 60, }, server: { proxy_api_key: null }, quota: { refresh_interval_minutes: 5, warning_thresholds: { primary: [80, 90], secondary: [80, 90] }, skip_exhausted: true, }, })),}));
// Use a counter to generate unique accountIdslet _idCounter = 0;vi.mock("../../auth/jwt-utils.js", () => ({ decodeJwtPayload: vi.fn(() => ({ exp: Math.floor(Date.now() / 1000) + 3600 })), extractChatGptAccountId: vi.fn(() => `acct-${++_idCounter}`), extractUserProfile: vi.fn(() => ({ email: `user${_idCounter}@test.com`, chatgpt_plan_type: "plus", })), isTokenExpired: vi.fn(() => false),}));
vi.mock("../../utils/jitter.js", () => ({ jitter: vi.fn((val: number) => val),}));
vi.mock("../../models/model-store.js", () => ({ getModelPlanTypes: vi.fn(() => []),}));
import { AccountPool } from "../account-pool.js";import type { CodexQuota } from "../types.js";
function makeQuota(overrides?: Partial<CodexQuota>): CodexQuota { return { plan_type: "plus", rate_limit: { allowed: true, limit_reached: false, used_percent: 42, reset_at: Math.floor(Date.now() / 1000) + 3600, limit_window_seconds: 3600, }, secondary_rate_limit: null, code_review_rate_limit: null, ...overrides, };}
describe("AccountPool quota methods", () => { let pool: AccountPool;
beforeEach(() => { pool = new AccountPool(); });
describe("updateCachedQuota", () => { it("stores quota and timestamp on account", () => { const id = pool.addAccount("eyJhbGciOiJIUzI1NiJ9.test-token-aaa"); const quota = makeQuota();
pool.updateCachedQuota(id, quota);
const entry = pool.getEntry(id); expect(entry?.cachedQuota).toEqual(quota); expect(entry?.quotaFetchedAt).toBeTruthy(); });
it("no-ops for unknown entry", () => { // Should not throw pool.updateCachedQuota("nonexistent", makeQuota()); }); });
describe("markQuotaExhausted", () => { it("sets status to rate_limited with reset time", () => { const id = pool.addAccount("eyJhbGciOiJIUzI1NiJ9.test-token-bbb"); const resetAt = Math.floor(Date.now() / 1000) + 7200;
pool.markQuotaExhausted(id, resetAt);
const entry = pool.getEntry(id); expect(entry?.status).toBe("rate_limited"); expect(entry?.usage.rate_limit_until).toBeTruthy(); });
it("uses fallback when resetAt is null", () => { const id = pool.addAccount("eyJhbGciOiJIUzI1NiJ9.test-token-ccc");
pool.markQuotaExhausted(id, null);
const entry = pool.getEntry(id); expect(entry?.status).toBe("rate_limited"); expect(entry?.usage.rate_limit_until).toBeTruthy(); });
it("does not override non-active status", () => { const id = pool.addAccount("eyJhbGciOiJIUzI1NiJ9.test-token-ddd"); pool.markStatus(id, "disabled");
pool.markQuotaExhausted(id, Math.floor(Date.now() / 1000) + 3600);
const entry = pool.getEntry(id); expect(entry?.status).toBe("disabled"); // unchanged }); });
describe("toInfo with cached quota", () => { it("populates quota field from cachedQuota", () => { const id = pool.addAccount("eyJhbGciOiJIUzI1NiJ9.test-token-eee"); const quota = makeQuota({ plan_type: "team" });
pool.updateCachedQuota(id, quota);
const accounts = pool.getAccounts(); const acct = accounts.find((a) => a.id === id); expect(acct?.quota).toEqual(quota); expect(acct?.quotaFetchedAt).toBeTruthy(); });
it("does not include quota when cachedQuota is null", () => { const id = pool.addAccount("eyJhbGciOiJIUzI1NiJ9.test-token-fff");
const accounts = pool.getAccounts(); const acct = accounts.find((a) => a.id === id); expect(acct?.quota).toBeUndefined(); }); });
describe("acquire skips exhausted accounts", () => { it("skips rate_limited (quota exhausted) account", () => { const id1 = pool.addAccount("eyJhbGciOiJIUzI1NiJ9.test-token-ggg"); const id2 = pool.addAccount("eyJhbGciOiJIUzI1NiJ9.test-token-hhh");
// Exhaust first account pool.markQuotaExhausted(id1, Math.floor(Date.now() / 1000) + 7200);
const acquired = pool.acquire(); expect(acquired).not.toBeNull(); expect(acquired!.entryId).toBe(id2); pool.release(acquired!.entryId); });
it("returns null when all accounts exhausted", () => { const id1 = pool.addAccount("eyJhbGciOiJIUzI1NiJ9.test-token-iii"); pool.markQuotaExhausted(id1, Math.floor(Date.now() / 1000) + 7200);
const acquired = pool.acquire(); expect(acquired).toBeNull(); }); });});1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071/** * Tests for quota config section parsing. */
import { describe, it, expect, vi, beforeEach } from "vitest";
// Mock dependencies before importing configvi.mock("../../models/model-store.js", () => ({ loadStaticModels: vi.fn(),}));vi.mock("../../models/model-fetcher.js", () => ({ triggerImmediateRefresh: vi.fn(),}));
import { z } from "zod";
// Replicate the quota schema to test independentlyconst QuotaSchema = z.object({ refresh_interval_minutes: z.number().min(1).default(5), warning_thresholds: z.object({ primary: z.array(z.number().min(1).max(100)).default([80, 90]), secondary: z.array(z.number().min(1).max(100)).default([80, 90]), }).default({}), skip_exhausted: z.boolean().default(true),}).default({});
describe("quota config schema", () => { it("uses defaults when empty", () => { const result = QuotaSchema.parse({}); expect(result.refresh_interval_minutes).toBe(5); expect(result.warning_thresholds.primary).toEqual([80, 90]); expect(result.warning_thresholds.secondary).toEqual([80, 90]); expect(result.skip_exhausted).toBe(true); });
it("uses defaults when undefined", () => { const result = QuotaSchema.parse(undefined); expect(result.refresh_interval_minutes).toBe(5); });
it("accepts custom thresholds", () => { const result = QuotaSchema.parse({ refresh_interval_minutes: 10, warning_thresholds: { primary: [70, 85, 95], secondary: [60], }, skip_exhausted: false, }); expect(result.refresh_interval_minutes).toBe(10); expect(result.warning_thresholds.primary).toEqual([70, 85, 95]); expect(result.warning_thresholds.secondary).toEqual([60]); expect(result.skip_exhausted).toBe(false); });
it("rejects refresh_interval_minutes < 1", () => { expect(() => QuotaSchema.parse({ refresh_interval_minutes: 0 })).toThrow(); });
it("rejects threshold > 100", () => { expect(() => QuotaSchema.parse({ warning_thresholds: { primary: [101] }, })).toThrow(); });
it("rejects threshold < 1", () => { expect(() => QuotaSchema.parse({ warning_thresholds: { primary: [0] }, })).toThrow(); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100import { describe, it, expect } from "vitest";import { toQuota } from "../quota-utils.js";import type { CodexUsageResponse } from "../../proxy/codex-api.js";
function makeUsageResponse(overrides?: Partial<CodexUsageResponse>): CodexUsageResponse { return { plan_type: "plus", rate_limit: { allowed: true, limit_reached: false, primary_window: { used_percent: 42, reset_at: 1700000000, limit_window_seconds: 3600, reset_after_seconds: 1800, }, secondary_window: null, }, code_review_rate_limit: null, credits: null, promo: null, ...overrides, };}
describe("toQuota", () => { it("converts primary window correctly", () => { const quota = toQuota(makeUsageResponse()); expect(quota.plan_type).toBe("plus"); expect(quota.rate_limit.used_percent).toBe(42); expect(quota.rate_limit.reset_at).toBe(1700000000); expect(quota.rate_limit.limit_window_seconds).toBe(3600); expect(quota.rate_limit.limit_reached).toBe(false); expect(quota.rate_limit.allowed).toBe(true); expect(quota.secondary_rate_limit).toBeNull(); expect(quota.code_review_rate_limit).toBeNull(); });
it("converts secondary window when present", () => { const quota = toQuota(makeUsageResponse({ rate_limit: { allowed: true, limit_reached: false, primary_window: { used_percent: 10, reset_at: 1700000000, limit_window_seconds: 3600, reset_after_seconds: 3000, }, secondary_window: { used_percent: 75, reset_at: 1700500000, limit_window_seconds: 604800, reset_after_seconds: 300000, }, }, }));
expect(quota.secondary_rate_limit).not.toBeNull(); expect(quota.secondary_rate_limit!.used_percent).toBe(75); expect(quota.secondary_rate_limit!.reset_at).toBe(1700500000); expect(quota.secondary_rate_limit!.limit_window_seconds).toBe(604800); });
it("converts code review rate limit when present", () => { const quota = toQuota(makeUsageResponse({ code_review_rate_limit: { allowed: true, limit_reached: true, primary_window: { used_percent: 100, reset_at: 1700001000, limit_window_seconds: 3600, reset_after_seconds: 0, }, secondary_window: null, }, }));
expect(quota.code_review_rate_limit).not.toBeNull(); expect(quota.code_review_rate_limit!.allowed).toBe(true); expect(quota.code_review_rate_limit!.limit_reached).toBe(true); expect(quota.code_review_rate_limit!.used_percent).toBe(100); });
it("handles null primary window gracefully", () => { const quota = toQuota(makeUsageResponse({ rate_limit: { allowed: true, limit_reached: false, primary_window: null, secondary_window: null, }, }));
expect(quota.rate_limit.used_percent).toBeNull(); expect(quota.rate_limit.reset_at).toBeNull(); expect(quota.rate_limit.limit_window_seconds).toBeNull(); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117import { describe, it, expect, beforeEach } from "vitest";import { evaluateThresholds, updateWarnings, clearWarnings, getActiveWarnings, getWarningsLastUpdated,} from "../quota-warnings.js";
describe("evaluateThresholds", () => { it("returns null when usedPercent is null", () => { const result = evaluateThresholds("a1", "a@test.com", null, null, "primary", [80, 90]); expect(result).toBeNull(); });
it("returns null when below all thresholds", () => { const result = evaluateThresholds("a1", "a@test.com", 50, 1700000000, "primary", [80, 90]); expect(result).toBeNull(); });
it("returns warning when between thresholds", () => { const result = evaluateThresholds("a1", "a@test.com", 85, 1700000000, "primary", [80, 90]); expect(result).not.toBeNull(); expect(result!.level).toBe("warning"); expect(result!.usedPercent).toBe(85); expect(result!.window).toBe("primary"); });
it("returns critical when at or above highest threshold", () => { const result = evaluateThresholds("a1", "a@test.com", 95, 1700000000, "primary", [80, 90]); expect(result).not.toBeNull(); expect(result!.level).toBe("critical"); expect(result!.usedPercent).toBe(95); });
it("returns critical when exactly at highest threshold", () => { const result = evaluateThresholds("a1", null, 90, null, "secondary", [80, 90]); expect(result).not.toBeNull(); expect(result!.level).toBe("critical"); expect(result!.email).toBeNull(); });
it("handles single threshold (always critical)", () => { const result = evaluateThresholds("a1", "a@test.com", 80, null, "primary", [80]); expect(result).not.toBeNull(); expect(result!.level).toBe("critical"); });
it("handles unsorted thresholds", () => { const result = evaluateThresholds("a1", "a@test.com", 85, null, "primary", [90, 80]); expect(result).not.toBeNull(); expect(result!.level).toBe("warning"); // 85 >= 80 but < 90 });
it("handles three thresholds", () => { // [60, 80, 90]: 75 should be warning (between 60 and 80) const result = evaluateThresholds("a1", null, 75, null, "primary", [60, 80, 90]); expect(result).not.toBeNull(); expect(result!.level).toBe("warning"); });});
describe("warning store", () => { beforeEach(() => { // Clear all warnings for (const w of getActiveWarnings()) { clearWarnings(w.accountId); } });
it("starts empty", () => { expect(getActiveWarnings()).toEqual([]); });
it("stores and retrieves warnings", () => { updateWarnings("a1", [ { accountId: "a1", email: "a@test.com", window: "primary", level: "warning", usedPercent: 85, resetAt: null }, ]); const all = getActiveWarnings(); expect(all).toHaveLength(1); expect(all[0].accountId).toBe("a1"); expect(getWarningsLastUpdated()).not.toBeNull(); });
it("replaces warnings for same account", () => { updateWarnings("a1", [ { accountId: "a1", email: null, window: "primary", level: "warning", usedPercent: 85, resetAt: null }, ]); updateWarnings("a1", [ { accountId: "a1", email: null, window: "primary", level: "critical", usedPercent: 95, resetAt: null }, ]); const all = getActiveWarnings(); expect(all).toHaveLength(1); expect(all[0].level).toBe("critical"); });
it("clears warnings for account", () => { updateWarnings("a1", [ { accountId: "a1", email: null, window: "primary", level: "warning", usedPercent: 85, resetAt: null }, ]); updateWarnings("a2", [ { accountId: "a2", email: null, window: "secondary", level: "critical", usedPercent: 95, resetAt: null }, ]); clearWarnings("a1"); const all = getActiveWarnings(); expect(all).toHaveLength(1); expect(all[0].accountId).toBe("a2"); });
it("removes warnings when updated with empty array", () => { updateWarnings("a1", [ { accountId: "a1", email: null, window: "primary", level: "warning", usedPercent: 85, resetAt: null }, ]); updateWarnings("a1", []); expect(getActiveWarnings()).toHaveLength(0); });});27 unmodified lines282930313233270 unmodified lines30430530630730830911 unmodified lines321322323324325326218 unmodified lines5455465475485495505516 unmodified lines55855956056156256365 unmodified lines62963063163263363445 unmodified lines68068168268368468527 unmodified linesAccountUsage,AcquiredAccount,AccountsFile,} from "./types.js";function getAccountsFile(): string {270 unmodified lineslimit_window_seconds: null,},addedAt: new Date().toISOString(),};this.accounts.set(id, entry);11 unmodified linesthis.schedulePersist();}removeAccount(id: string): boolean {this.acquireLocks.delete(id);const deleted = this.accounts.delete(id);218 unmodified linesprivate toInfo(entry: AccountEntry): AccountInfo {const payload = decodeJwtPayload(entry.token);const exp = payload?.exp;return {id: entry.id,email: entry.email,accountId: entry.accountId,6 unmodified lines? new Date(exp * 1000).toISOString(): null,};}// ── Persistence ─────────────────────────────────────────────────65 unmodified linesentry.usage.limit_window_seconds = null;needsPersist = true;}this.accounts.set(entry.id, entry);}}45 unmodified lineslimit_window_seconds: null,},addedAt: new Date().toISOString(),};this.accounts.set(id, entry);27 unmodified lines28293031323334270 unmodified lines30530630730830931031131211 unmodified lines324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359218 unmodified lines5785795805815825835846 unmodified lines59159259359459559659759859960060165 unmodified lines66766866967067167267367467567667767845 unmodified lines72472572672772872973073127 unmodified linesAccountUsage,AcquiredAccount,AccountsFile,CodexQuota,} from "./types.js";function getAccountsFile(): string {270 unmodified lineslimit_window_seconds: null,},addedAt: new Date().toISOString(),cachedQuota: null,quotaFetchedAt: null,};this.accounts.set(id, entry);11 unmodified linesthis.schedulePersist();}/*** Update cached quota for an account (called by background quota refresher).*/updateCachedQuota(entryId: string, quota: CodexQuota): void {const entry = this.accounts.get(entryId);if (!entry) return;entry.cachedQuota = quota;entry.quotaFetchedAt = new Date().toISOString();this.schedulePersist();}/*** Mark an account as quota-exhausted by setting it rate_limited until resetAt.* Reuses the rate_limited mechanism so acquire() skips it and refreshStatus() auto-recovers.*/markQuotaExhausted(entryId: string, resetAtUnix: number | null): void {const entry = this.accounts.get(entryId);if (!entry) return;// Only mark if currently active — don't override other statesif (entry.status !== "active") return;const until = resetAtUnix? new Date(resetAtUnix * 1000).toISOString(): new Date(Date.now() + 300_000).toISOString(); // fallback 5 minentry.status = "rate_limited";entry.usage.rate_limit_until = until;this.acquireLocks.delete(entryId);this.schedulePersist();}removeAccount(id: string): boolean {this.acquireLocks.delete(id);const deleted = this.accounts.delete(id);218 unmodified linesprivate toInfo(entry: AccountEntry): AccountInfo {const payload = decodeJwtPayload(entry.token);const exp = payload?.exp;const info: AccountInfo = {id: entry.id,email: entry.email,accountId: entry.accountId,6 unmodified lines? new Date(exp * 1000).toISOString(): null,};if (entry.cachedQuota) {info.quota = entry.cachedQuota;info.quotaFetchedAt = entry.quotaFetchedAt;}return info;}// ── Persistence ─────────────────────────────────────────────────65 unmodified linesentry.usage.limit_window_seconds = null;needsPersist = true;}// Backfill cachedQuota fields for old entriesif (entry.cachedQuota === undefined) {entry.cachedQuota = null;entry.quotaFetchedAt = null;needsPersist = true;}this.accounts.set(entry.id, entry);}}45 unmodified lineslimit_window_seconds: null,},addedAt: new Date().toISOString(),cachedQuota: null,quotaFetchedAt: null,};this.accounts.set(id, entry);
123456789101112131415161718192021222324252627282930313233343536373839/** * Shared quota conversion utility. * Converts CodexUsageResponse (raw backend) → CodexQuota (normalized). */
import type { CodexQuota } from "./types.js";import type { CodexUsageResponse } from "../proxy/codex-api.js";
export function toQuota(usage: CodexUsageResponse): CodexQuota { const sw = usage.rate_limit.secondary_window; return { plan_type: usage.plan_type, rate_limit: { allowed: usage.rate_limit.allowed, limit_reached: usage.rate_limit.limit_reached, used_percent: usage.rate_limit.primary_window?.used_percent ?? null, reset_at: usage.rate_limit.primary_window?.reset_at ?? null, limit_window_seconds: usage.rate_limit.primary_window?.limit_window_seconds ?? null, }, secondary_rate_limit: sw ? { limit_reached: usage.rate_limit.limit_reached, used_percent: sw.used_percent ?? null, reset_at: sw.reset_at ?? null, limit_window_seconds: sw.limit_window_seconds ?? null, } : null, code_review_rate_limit: usage.code_review_rate_limit ? { allowed: usage.code_review_rate_limit.allowed, limit_reached: usage.code_review_rate_limit.limit_reached, used_percent: usage.code_review_rate_limit.primary_window?.used_percent ?? null, reset_at: usage.code_review_rate_limit.primary_window?.reset_at ?? null, } : null, };}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273/** * Quota warning state store. * Tracks accounts approaching or exceeding quota limits. */
export interface QuotaWarning { accountId: string; email: string | null; window: "primary" | "secondary"; level: "warning" | "critical"; usedPercent: number; resetAt: number | null;}
const _warnings = new Map<string, QuotaWarning[]>();let _lastUpdated: string | null = null;
/** * Evaluate quota thresholds and return warnings for a single account. * Thresholds are sorted ascending; highest matched threshold determines level. */export function evaluateThresholds( accountId: string, email: string | null, usedPercent: number | null, resetAt: number | null, window: "primary" | "secondary", thresholds: number[],): QuotaWarning | null { if (usedPercent == null) return null; // Sort ascending const sorted = [...thresholds].sort((a, b) => a - b); // Find highest matched threshold let matchedIdx = -1; for (let i = sorted.length - 1; i >= 0; i--) { if (usedPercent >= sorted[i]) { matchedIdx = i; break; } } if (matchedIdx < 0) return null;
// Highest threshold = critical, others = warning const level: "warning" | "critical" = matchedIdx === sorted.length - 1 ? "critical" : "warning";
return { accountId, email, window, level, usedPercent, resetAt };}
export function updateWarnings(accountId: string, warnings: QuotaWarning[]): void { if (warnings.length === 0) { _warnings.delete(accountId); } else { _warnings.set(accountId, warnings); } _lastUpdated = new Date().toISOString();}
export function clearWarnings(accountId: string): void { _warnings.delete(accountId);}
export function getActiveWarnings(): QuotaWarning[] { const all: QuotaWarning[] = []; for (const list of _warnings.values()) { all.push(...list); } return all;}
export function getWarningsLastUpdated(): string | null { return _lastUpdated;}40 unmodified lines4142434445467 unmodified lines54555657585940 unmodified linesstatus: AccountStatus;usage: AccountUsage;addedAt: string;}/** Public info (no token) */7 unmodified linesaddedAt: string;expiresAt: string | null;quota?: CodexQuota;}/** A single rate limit window (primary or secondary). */40 unmodified lines414243444546474849507 unmodified lines5859606162636440 unmodified linesstatus: AccountStatus;usage: AccountUsage;addedAt: string;/** Cached official quota from background refresh. Null until first fetch. */cachedQuota: CodexQuota | null;/** ISO timestamp of when cachedQuota was last updated. */quotaFetchedAt: string | null;}/** Public info (no token) */7 unmodified linesaddedAt: string;expiresAt: string | null;quota?: CodexQuota;quotaFetchedAt?: string | null;}/** A single rate limit window (primary or secondary). */
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161/** * Usage Refresher — background quota refresh for all accounts. * * - Periodically fetches official quota from Codex backend * - Caches quota on AccountEntry for fast dashboard reads * - Marks quota-exhausted accounts as rate_limited * - Evaluates warning thresholds and updates warning store * - Non-fatal: all errors log warnings but never crash the server */
import { CodexApi } from "../proxy/codex-api.js";import { getConfig } from "../config.js";import { jitter } from "../utils/jitter.js";import { toQuota } from "./quota-utils.js";import { evaluateThresholds, updateWarnings, type QuotaWarning,} from "./quota-warnings.js";import type { AccountPool } from "./account-pool.js";import type { CookieJar } from "../proxy/cookie-jar.js";import type { ProxyPool } from "../proxy/proxy-pool.js";
const INITIAL_DELAY_MS = 3_000; // 3s after startup
let _refreshTimer: ReturnType<typeof setTimeout> | null = null;let _accountPool: AccountPool | null = null;let _cookieJar: CookieJar | null = null;let _proxyPool: ProxyPool | null = null;
async function fetchQuotaForAllAccounts( pool: AccountPool, cookieJar: CookieJar, proxyPool: ProxyPool | null,): Promise<void> { if (!pool.isAuthenticated()) return;
const entries = pool.getAllEntries().filter((e) => e.status === "active"); if (entries.length === 0) return;
const config = getConfig(); const thresholds = config.quota.warning_thresholds;
console.log(`[QuotaRefresh] Refreshing quota for ${entries.length} active account(s)`);
const results = await Promise.allSettled( entries.map(async (entry) => { const proxyUrl = proxyPool?.resolveProxyUrl(entry.id); const api = new CodexApi(entry.token, entry.accountId, cookieJar, entry.id, proxyUrl); const usage = await api.getUsage(); const quota = toQuota(usage);
// Cache quota on the account pool.updateCachedQuota(entry.id, quota);
// Sync rate limit window const resetAt = usage.rate_limit.primary_window?.reset_at ?? null; const windowSec = usage.rate_limit.primary_window?.limit_window_seconds ?? null; pool.syncRateLimitWindow(entry.id, resetAt, windowSec);
// Mark exhausted if limit reached (primary or secondary) if (config.quota.skip_exhausted) { const primaryExhausted = quota.rate_limit.limit_reached; const secondaryExhausted = quota.secondary_rate_limit?.limit_reached ?? false; if (primaryExhausted || secondaryExhausted) { const exhaustResetAt = primaryExhausted ? quota.rate_limit.reset_at : quota.secondary_rate_limit?.reset_at ?? null; pool.markQuotaExhausted(entry.id, exhaustResetAt); console.log(`[QuotaRefresh] Account ${entry.id} (${entry.email ?? "?"}) quota exhausted — marked rate_limited`); } }
// Evaluate warning thresholds const warnings: QuotaWarning[] = []; const pw = evaluateThresholds( entry.id, entry.email, quota.rate_limit.used_percent, quota.rate_limit.reset_at, "primary", thresholds.primary, ); if (pw) warnings.push(pw);
const sw = evaluateThresholds( entry.id, entry.email, quota.secondary_rate_limit?.used_percent ?? null, quota.secondary_rate_limit?.reset_at ?? null, "secondary", thresholds.secondary, ); if (sw) warnings.push(sw);
updateWarnings(entry.id, warnings); }), );
let succeeded = 0; for (const r of results) { if (r.status === "fulfilled") { succeeded++; } else { const msg = r.reason instanceof Error ? r.reason.message : String(r.reason); console.warn(`[QuotaRefresh] Account quota fetch failed: ${msg}`); } }
console.log(`[QuotaRefresh] Done: ${succeeded}/${entries.length} succeeded`);}
function scheduleNext( pool: AccountPool, cookieJar: CookieJar,): void { const config = getConfig(); const intervalMs = jitter(config.quota.refresh_interval_minutes * 60 * 1000, 0.15); _refreshTimer = setTimeout(async () => { try { await fetchQuotaForAllAccounts(pool, cookieJar, _proxyPool); } finally { scheduleNext(pool, cookieJar); } }, intervalMs);}
/** * Start the background quota refresh loop. */export function startQuotaRefresh( accountPool: AccountPool, cookieJar: CookieJar, proxyPool?: ProxyPool,): void { _accountPool = accountPool; _cookieJar = cookieJar; _proxyPool = proxyPool ?? null;
_refreshTimer = setTimeout(async () => { try { await fetchQuotaForAllAccounts(accountPool, cookieJar, _proxyPool); } finally { scheduleNext(accountPool, cookieJar); } }, INITIAL_DELAY_MS);
const config = getConfig(); console.log(`[QuotaRefresh] Scheduled initial quota refresh in 3s (interval: ${config.quota.refresh_interval_minutes}min)`);}
/** * Stop the background refresh timer. */export function stopQuotaRefresh(): void { if (_refreshTimer) { clearTimeout(_refreshTimer); _refreshTimer = null; console.log("[QuotaRefresh] Stopped quota refresh"); }}50 unmodified lines51525354555650 unmodified linestransport: z.enum(["auto", "curl-cli", "libcurl-ffi"]).default("auto"),force_http11: z.boolean().default(false),}).default({}),});export type AppConfig = z.infer<typeof ConfigSchema>;50 unmodified lines515253545556575859606162636450 unmodified linestransport: z.enum(["auto", "curl-cli", "libcurl-ffi"]).default("auto"),force_http11: z.boolean().default(false),}).default({}),quota: z.object({refresh_interval_minutes: z.number().min(1).default(5),warning_thresholds: z.object({primary: z.array(z.number().min(1).max(100)).default([80, 90]),secondary: z.array(z.number().min(1).max(100)).default([80, 90]),}).default({}),skip_exhausted: z.boolean().default(true),}).default({}),});export type AppConfig = z.infer<typeof ConfigSchema>;
23 unmodified lines24252627282996 unmodified lines12612712812913013113 unmodified lines14514614714814915023 unmodified linesimport { initTransport } from "./tls/transport.js";import { loadStaticModels } from "./models/model-store.js";import { startModelRefresh, stopModelRefresh } from "./models/model-fetcher.js";export interface ServerHandle {close: () => Promise<void>;96 unmodified lines// Start background model refresh (requires auth to be ready)startModelRefresh(accountPool, cookieJar, proxyPool);// Start proxy health check timer (if proxies exist)proxyPool.startHealthCheckTimer();13 unmodified linesstopUpdateChecker();stopProxyUpdateChecker();stopModelRefresh();refreshScheduler.destroy();proxyPool.destroy();cookieJar.destroy();23 unmodified lines2425262728293096 unmodified lines12712812913013113213313413513 unmodified lines14915015115215315415523 unmodified linesimport { initTransport } from "./tls/transport.js";import { loadStaticModels } from "./models/model-store.js";import { startModelRefresh, stopModelRefresh } from "./models/model-fetcher.js";import { startQuotaRefresh, stopQuotaRefresh } from "./auth/usage-refresher.js";export interface ServerHandle {close: () => Promise<void>;96 unmodified lines// Start background model refresh (requires auth to be ready)startModelRefresh(accountPool, cookieJar, proxyPool);// Start background quota refreshstartQuotaRefresh(accountPool, cookieJar, proxyPool);// Start proxy health check timer (if proxies exist)proxyPool.startHealthCheckTimer();13 unmodified linesstopUpdateChecker();stopProxyUpdateChecker();stopModelRefresh();stopQuotaRefresh();refreshScheduler.destroy();proxyPool.destroy();cookieJar.destroy();
24 unmodified lines2526272829302 unmodified lines333435363738394041424344454647484950515253545556575859606162636465666768697072 unmodified lines143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195138 unmodified lines33433533633733824 unmodified linesimport type { CodexQuota, AccountInfo } from "../auth/types.js";import type { CookieJar } from "../proxy/cookie-jar.js";import type { ProxyPool } from "../proxy/proxy-pool.js";const BulkImportSchema = z.object({accounts: z.array(z.object({2 unmodified lines})).min(1),});function toQuota(usage: CodexUsageResponse): CodexQuota {const sw = usage.rate_limit.secondary_window;return {plan_type: usage.plan_type,rate_limit: {allowed: usage.rate_limit.allowed,limit_reached: usage.rate_limit.limit_reached,used_percent: usage.rate_limit.primary_window?.used_percent ?? null,reset_at: usage.rate_limit.primary_window?.reset_at ?? null,limit_window_seconds: usage.rate_limit.primary_window?.limit_window_seconds ?? null,},secondary_rate_limit: sw? {limit_reached: usage.rate_limit.limit_reached,used_percent: sw.used_percent ?? null,reset_at: sw.reset_at ?? null,limit_window_seconds: sw.limit_window_seconds ?? null,}: null,code_review_rate_limit: usage.code_review_rate_limit? {allowed: usage.code_review_rate_limit.allowed,limit_reached: usage.code_review_rate_limit.limit_reached,used_percent:usage.code_review_rate_limit.primary_window?.used_percent ?? null,reset_at:usage.code_review_rate_limit.primary_window?.reset_at ?? null,}: null,};}export function createAccountRoutes(pool: AccountPool,scheduler: RefreshScheduler,72 unmodified linesreturn c.json({ success: true, added, updated, failed, errors });});// List all accounts (with optional ?quota=true)app.get("/auth/accounts", async (c) => {const accounts = pool.getAccounts();const wantQuota = c.req.query("quota") === "true";if (!wantQuota) {const enrichedBasic = accounts.map((acct) => ({...acct,proxyId: proxyPool?.getAssignment(acct.id) ?? "global",proxyName: proxyPool?.getAssignmentDisplayName(acct.id) ?? "Global Default",}));return c.json({ accounts: enrichedBasic });}// Fetch quota for every active account in parallelconst enriched: AccountInfo[] = await Promise.all(accounts.map(async (acct) => {if (acct.status !== "active") return acct;const entry = pool.getEntry(acct.id);if (!entry) return acct;try {const api = makeApi(acct.id, entry.token, entry.accountId);const usage = await api.getUsage();// Sync rate limit window — auto-reset local counters on window rolloverconst resetAt = usage.rate_limit.primary_window?.reset_at ?? null;const windowSec = usage.rate_limit.primary_window?.limit_window_seconds ?? null;pool.syncRateLimitWindow(acct.id, resetAt, windowSec);// Re-read usage after potential resetconst freshAcct = pool.getAccounts().find((a) => a.id === acct.id) ?? acct;return {...freshAcct,quota: toQuota(usage),proxyId: proxyPool?.getAssignment(acct.id) ?? "global",proxyName: proxyPool?.getAssignmentDisplayName(acct.id) ?? "Global Default",};} catch {return {...acct,proxyId: proxyPool?.getAssignment(acct.id) ?? "global",proxyName: proxyPool?.getAssignmentDisplayName(acct.id) ?? "Global Default",};}}),);return c.json({ accounts: enriched });});138 unmodified linesreturn c.json({ success: true });});return app;}24 unmodified lines25262728293031322 unmodified lines35363738394072 unmodified lines113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184138 unmodified lines32332432532632732832933033133233333433533624 unmodified linesimport type { CodexQuota, AccountInfo } from "../auth/types.js";import type { CookieJar } from "../proxy/cookie-jar.js";import type { ProxyPool } from "../proxy/proxy-pool.js";import { toQuota } from "../auth/quota-utils.js";import { getActiveWarnings, getWarningsLastUpdated } from "../auth/quota-warnings.js";const BulkImportSchema = z.object({accounts: z.array(z.object({2 unmodified lines})).min(1),});export function createAccountRoutes(pool: AccountPool,scheduler: RefreshScheduler,72 unmodified linesreturn c.json({ success: true, added, updated, failed, errors });});// List all accounts// ?quota=true → return cached quota (fast, from background refresh)// ?quota=fresh → force live fetch from upstream (manual refresh button)app.get("/auth/accounts", async (c) => {const quotaParam = c.req.query("quota");const wantFresh = quotaParam === "fresh";if (wantFresh) {// Live fetch quota for every active account in parallelconst accounts = pool.getAccounts();const enriched: AccountInfo[] = await Promise.all(accounts.map(async (acct) => {if (acct.status !== "active") {return {...acct,proxyId: proxyPool?.getAssignment(acct.id) ?? "global",proxyName: proxyPool?.getAssignmentDisplayName(acct.id) ?? "Global Default",};}const entry = pool.getEntry(acct.id);if (!entry) {return {...acct,proxyId: proxyPool?.getAssignment(acct.id) ?? "global",proxyName: proxyPool?.getAssignmentDisplayName(acct.id) ?? "Global Default",};}try {const api = makeApi(acct.id, entry.token, entry.accountId);const usage = await api.getUsage();const quota = toQuota(usage);// Cache the fresh quotapool.updateCachedQuota(acct.id, quota);// Sync rate limit window — auto-reset local counters on window rolloverconst resetAt = usage.rate_limit.primary_window?.reset_at ?? null;const windowSec = usage.rate_limit.primary_window?.limit_window_seconds ?? null;pool.syncRateLimitWindow(acct.id, resetAt, windowSec);// Re-read usage after potential resetconst freshAcct = pool.getAccounts().find((a) => a.id === acct.id) ?? acct;return {...freshAcct,quota,proxyId: proxyPool?.getAssignment(acct.id) ?? "global",proxyName: proxyPool?.getAssignmentDisplayName(acct.id) ?? "Global Default",};} catch {return {...acct,proxyId: proxyPool?.getAssignment(acct.id) ?? "global",proxyName: proxyPool?.getAssignmentDisplayName(acct.id) ?? "Global Default",};}}),);return c.json({ accounts: enriched });}// Default: return accounts with cached quota (populated by toInfo())const accounts = pool.getAccounts();const enriched = accounts.map((acct) => ({...acct,proxyId: proxyPool?.getAssignment(acct.id) ?? "global",proxyName: proxyPool?.getAssignmentDisplayName(acct.id) ?? "Global Default",}));return c.json({ accounts: enriched });});138 unmodified linesreturn c.json({ success: true });});// ── Quota warnings ──────────────────────────────────────────────app.get("/auth/quota/warnings", (c) => {return c.json({warnings: getActiveWarnings(),updatedAt: getWarningsLastUpdated(),});});return app;}
1234567812 unmodified lines21222324252664 unmodified lines919293949596import { useState, useCallback } from "preact/hooks";import { useI18n, useT } from "../../../shared/i18n/context";import { AccountCard } from "./AccountCard";import { AccountImportExport } from "./AccountImportExport";import type { Account, ProxyEntry } from "../../../shared/types";interface AccountListProps {accounts: Account[];12 unmodified linesconst t = useT();const { lang } = useI18n();const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());const toggleSelect = useCallback((id: string) => {setSelectedIds((prev) => {64 unmodified lines</button></div></div><div class="grid grid-cols-1 md:grid-cols-2 gap-4">{loading ? (<div class="md:col-span-2 text-center py-8 text-slate-400 dark:text-text-dim text-sm bg-white dark:bg-card-dark border border-gray-200 dark:border-border-dark rounded-xl transition-colors">1234567812 unmodified lines21222324252627282930313233343536373839404164 unmodified lines106107108109110111112113114115116117118119120121122123124125126127128129130131132import { useState, useCallback, useEffect } from "preact/hooks";import { useI18n, useT } from "../../../shared/i18n/context";import { AccountCard } from "./AccountCard";import { AccountImportExport } from "./AccountImportExport";import type { Account, ProxyEntry, QuotaWarning } from "../../../shared/types";interface AccountListProps {accounts: Account[];12 unmodified linesconst t = useT();const { lang } = useI18n();const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());const [warnings, setWarnings] = useState<QuotaWarning[]>([]);// Poll quota warningsuseEffect(() => {const fetchWarnings = async () => {try {const resp = await fetch("/auth/quota/warnings");const data = await resp.json();setWarnings(data.warnings || []);} catch { /* ignore */ }};fetchWarnings();const timer = setInterval(fetchWarnings, 30_000);return () => clearInterval(timer);}, []);const toggleSelect = useCallback((id: string) => {setSelectedIds((prev) => {64 unmodified lines</button></div></div>{/* Quota warning banners */}{warnings.filter((w) => w.level === "critical").length > 0 && (<div class="px-4 py-2.5 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800/30 text-red-700 dark:text-red-400 text-sm flex items-center gap-2"><svg class="size-4 shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z" /></svg><span>{t("quotaCriticalWarning").replace("{count}", String(warnings.filter((w) => w.level === "critical").length))}</span></div>)}{warnings.filter((w) => w.level === "warning").length > 0 && warnings.filter((w) => w.level === "critical").length === 0 && (<div class="px-4 py-2.5 rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800/30 text-amber-700 dark:text-amber-400 text-sm flex items-center gap-2"><svg class="size-4 shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z" /></svg><span>{t("quotaWarning").replace("{count}", String(warnings.filter((w) => w.level === "warning").length))}</span></div>)}<div class="grid grid-cols-1 md:grid-cols-2 gap-4">{loading ? (<div class="md:col-span-2 text-center py-8 text-slate-400 dark:text-text-dim text-sm bg-white dark:bg-card-dark border border-gray-200 dark:border-border-dark rounded-xl transition-colors">
CHANGELOG.md+1
config/default.yaml+6
package.json+3
shared/hooks/use-accounts.ts+10-3
shared/i18n/translations.ts+4
shared/types.ts+19-6
src/auth/__tests__/account-pool-quota.test.tsAdded+181
src/auth/__tests__/config-quota.test.tsAdded+71
src/auth/__tests__/quota-utils.test.tsAdded+100
src/auth/__tests__/quota-warnings.test.tsAdded+117
src/auth/account-pool.ts+47-1
src/auth/quota-utils.tsAdded+39
src/auth/quota-warnings.tsAdded+73
src/auth/types.ts+5
src/auth/usage-refresher.tsAdded+161
src/config.ts+8
src/index.ts+5
src/routes/accounts.ts+74-76
web/src/components/AccountList.tsx+38-2