From 2fb7a174f51695df5682036fc84999a8fcb26b5f Mon Sep 17 00:00:00 2001 From: margrop <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:34:11 +0800 Subject: [PATCH] feat: provider quotas, Claude OAuth via CLIProxyAPI, agy rotation and dashboard themes Sync the reviewed development snapshot from the private Gitea repository, excluding private CI/CD infrastructure (.gitea workflows, Gitea runner and Portainer receiver configuration). - Google AI: current model catalog (Argon/Gemini) with per-model quota rows - Claude OAuth through CLIProxyAPI management API (no token storage) - Kimi/MiniMax/Qianwen header repair flows and quota windows - agy account rotation helper with identity-hash gating - read-only /api/summary for Home Assistant dashboards - concurrent refresh with NDJSON streaming and 5-minute auto-refresh - responsive card layout and dashboard themes Co-authored-by: margrop <41898282+github-actions[bot]@users.noreply.github.com> --- AGENTS.md | 16 + CHANGELOG.md | 7 + README.md | 395 +++++++++- docker-compose.yml | 3 + index.html | 310 +++++++- parser.js | 217 +++++- scripts/agy-quota-rotation.example.json | 8 + scripts/agy_quota_rotate.py | 399 ++++++++++ server.py | 998 ++++++++++++++++++++++-- tests/parser.test.js | 731 ++++++++++++++++- tests/test_agy_quota.py | 831 ++++++++++++++++++++ tests/test_claude.py | 201 +++++ tests/test_qianwen.py | 199 +++++ tests/test_refresh_stream.py | 92 +++ tests/test_server.py | 257 ++++++ 15 files changed, 4510 insertions(+), 154 deletions(-) create mode 100644 scripts/agy-quota-rotation.example.json create mode 100644 scripts/agy_quota_rotate.py create mode 100644 tests/test_agy_quota.py create mode 100644 tests/test_claude.py create mode 100644 tests/test_qianwen.py create mode 100644 tests/test_refresh_stream.py diff --git a/AGENTS.md b/AGENTS.md index d70129c..820c8c1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,6 +25,20 @@ - Check command exit codes, stderr and expected output. Treat any `fatal:` output as failure even if an outer command exits successfully. - GitHub requires the `Parser (Node)` and `Server (Python)` checks. Preserve branch protection and wait for both before updating `main`. +## Live Verification + +- Runtime data under the deployment `data/` directory is user state, not test + fixture. Never write defaults, empty arrays or synthetic ids into `/api/order`, + `/api/hidden`, `/api/requests` or `/api/snapshot` on a live deployment. +- Before any state-changing verification, read the current value and keep it. Restore + that exact saved value afterwards; do not reset it to empty because the test finished. +- Report the before and after values of every mutated field so a change is visible. +- Prefer an isolated local server with fixture data, or a dedicated throwaway account id + that is appended to the saved list and removed by id. +- Never reuse a real account id as a test subject for deletion or mutation checks. +- Treat an unconfirmed restore as an incident: state the risk and the recovery path + instead of describing the run as clean. + ## Repository Synchronization - The Gitea development repository retains its complete history. Publish each requested GitHub synchronization as one reviewed commit based on the current GitHub `main`. @@ -42,6 +56,8 @@ - Keep persistent runtime data under `/docker/coding_plan_quota_dashboard/data/`. - Verify `http://:8080/` returns HTTP 200 after deployment; substitute the actual host privately, never commit it. - Verify the affected UI or provider flow as well; HTTP 200 alone does not prove the feature works. +- Follow the Live Verification rules when testing against a deployed instance; a + verification run must leave every user state file with its original values and order. - Quote remote SSH command strings to prevent local expansion of remote variables or command substitutions; prefer a remote script for complex commands. - For remote background jobs, check process state for zombies as well as completion logs and artifacts; `kill -0` alone is insufficient. diff --git a/CHANGELOG.md b/CHANGELOG.md index acc4d15..addcada 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,14 @@ adheres to [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Fixed +- Google AI quota lookups continue to the next host when a proxy or Google + host drops the connection, instead of failing the account outright. +- Codex new-api business errors now show the provider's `message`. + ### Added +- Read-only `GET /api/summary` with each visible account's headline quota and + status for Home Assistant and other home dashboards. - Initial public release. - Single-page dashboard for Codex, MiniMax, Volcengine AgentPlan / CodingPlan, Kimi Code, LongCat, Qianwen AI and Google AI (Gemini 3.5 Flash). diff --git a/README.md b/README.md index e593577..95168b5 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,15 @@ [![CI](https://github.com/margrop/coding-plan-dashboard/actions/workflows/test.yml/badge.svg)](./.github/workflows/test.yml) A single-page dashboard that aggregates the coding-plan quotas of multiple AI providers -(Codex, MiniMax, Volcengine AgentPlan / CodingPlan, Kimi Code, LongCat, Qianwen AI, -Zhipu AI CodingPlan and Google AI Gemini Models) into one self-hosted UI. Each provider supports multiple +(Codex, Claude OAuth, MiniMax, Volcengine AgentPlan / CodingPlan, Kimi Code, LongCat, Qianwen AI, +Zhipu AI CodingPlan and Google AI model quotas) into one self-hosted UI. Each provider supports multiple accounts with independent labels. -一个部署在局域网中的 Coding Plan 配额看板,支持 Codex、MiniMax、火山方舟 CodingPlan / -AgentPlan、Kimi Code、LongCat、千问 AI、智谱 AI CodingPlan 和 Google AI Gemini Models。支持同一平台 -多账号,每个账号可添加备注。Google AI 显示 Gemini Models 的 5 小时和周额度。 +一个部署在局域网中的 Coding Plan 配额看板,支持 Codex、Claude OAuth、MiniMax、火山方舟 CodingPlan / +AgentPlan、Kimi Code、LongCat、千问 AI、智谱 AI CodingPlan 和 Google AI 模型额度。支持同一平台 +多账号,每个账号可添加备注。Google AI 仅显示接口实际返回的额度:Gemini Models 的 5 小时和周额度; +支持 Argon 的账号将 Argon 周额度置于首位,并同时显示返回的 Argon 5 小时额度、Gemini 窗口和 +当前可用模型(包括 Gemini、Claude、GPT)的独立用量,名称随接口返回更新。 ## Features / 功能 @@ -18,15 +20,51 @@ AgentPlan、Kimi Code、LongCat、千问 AI、智谱 AI CodingPlan 和 Google AI needed. / 根据原始 `curl` URL 自动识别数据来源,不需要手工选择产品。 - The server re-executes saved requests on page open, manual refresh, or auto refresh; results are persisted as JSON on the host so they survive container restarts. + An open page auto-refreshes every 5 minutes and stops after 99 automatic refreshes; + reload the page to start counting again. / 页面打开、刷新或点击刷新按钮时由服务器重新执行已保存的请求;配额结果保存到服务器端 - JSON 文件,容器重启后自动恢复。 + JSON 文件,容器重启后自动恢复。页面保持打开时每 5 分钟自动刷新一次,最多自动刷新 + 99 次,重新打开页面后重新计数。 - First paint shows the cached snapshot then silently refreshes to the latest data; - successful refreshes do not pop up any dialog. + successful refreshes do not pop up any dialog. Accounts are queried concurrently + (up to 8 at a time) and each card updates as soon as its own result returns. + / 各账号并发查询(最多 8 个同时进行),哪个账号先返回就先更新哪张卡片。 - Five built-in visual themes (Aurora, Ocean, Forest, Sunset and Paper), each with Light / Dark modes. The selected theme and mode are saved in browser local storage; the appearance controls are available after unlocking the page. - Multi-account support: each imported curl is stored as a separate account with its own ID, label, edit, delete (with double confirm), and reorder controls. + After unlocking, **▲ / ▼** swaps a card with the adjacent visible card, skipping + hidden accounts and credit entries merged into another card. Their positions in + the complete saved order are retained. Boundary buttons and buttons awaiting a + save are disabled; failed saves restore the previous order and show an error. + Successful changes are persisted on the server and survive page reloads. + / 解锁后点击 **▲ / ▼** 与相邻可见卡片交换位置,跳过隐藏账号及已合并的重置卡条目;完整 + 顺序仍保留这些条目的位置。边界或保存期间按钮禁用,保存失败会恢复原顺序并提示,成功后 + 刷新页面仍保留顺序。 +- Any quota card can be hidden from the dashboard via its **隐藏** button. Hidden + accounts are listed in the **已隐藏账号** panel, sorted by provider channel so that all + accounts of the same channel (for example 火山方舟 CodingPlan / AgentPlan, or the Codex + sources) stay together; channels follow the card order and accounts inside a channel + keep their card order. Each row also shows the longest quota period as text (e.g. + 周已用 / 月已用 / 订阅已用 + 百分比 + 剩余时间, using the same calculation as the + card summary) with a mini progress bar in the same bar style as the cards next to the + percentage; labels, percentage with bar and countdown share one line in fixed-width + columns and line up vertically across rows without increasing row height. Plan labels + use compact names such as Code, Gemini, Argon and OAuth; model fallback rows show 模型已用. + Hover over either label to see its full plan or quota/model name. Accounts can + be restored through the full account list + or the per-row **恢复显示** button. The hidden list is persisted in `/data/hidden.json` + (separate from the display order) and is cleaned up automatically when an account is + deleted; hidden cards are still refreshed by the server. + / 每张卡片可点击 **隐藏** 从面板中收起。**已隐藏账号** 面板按渠道分组排序,同一渠道的多个 + 账号相邻展示(渠道顺序跟随卡片顺序,渠道内保持卡片顺序);每行以文字显示该账号最长周期的 + 额度已使用百分比与剩余时间(区分周额度 / 月额度 / 订阅额度等,口径与卡片汇总一致),百分比 + 旁附带与卡片同风格的迷你进度条;周期名、百分比+进度条、剩余时间同一行分三列固定宽度、上下 + 对齐,且不增加行高。列表中使用「Code」「Gemini」「订阅已用」「模型已用」等短标签,悬停可查看 + 完整方案、周期或模型名称。可通过全量账号列表或行内 **恢复显示** 按钮恢复。 + 隐藏列表独立持久化到服务器 `/data/hidden.json`,删除账号时自动清理,且被隐藏的账号仍会正常 + 刷新数据。 - Existing Kimi accounts can update request verification headers from a fresh `GetSubscriptionStats` curl without replacing the saved URL, body, or account. - Existing Kimi accounts can save a complete `RefreshToken` directly; every quota @@ -34,8 +72,36 @@ AgentPlan、Kimi Code、LongCat、千问 AI、智谱 AI CodingPlan 和 Google AI persists rotated access / refresh tokens plus response cookies when provided. - Existing MiniMax accounts can update verification headers from a fresh `token_plan/remains_percent` curl while preserving the account and request body. + Both `www.minimaxi.com` and `www.minimax.cn` are supported, including header + updates copied from the other domain for the same endpoint; the saved URL stays unchanged. + A MiniMax weekly window is treated as unavailable when the provider reports no + positive weekly total or a non-active weekly status (e.g. plans without a weekly + cap); quota summaries — including the hidden-account list — then fall back to the + five-hour window instead of showing an empty 周额度. + / MiniMax 账号在接口未返回有效周限额(周总量缺失/为 0 或周状态非生效)时视为无周限额, + 额度汇总(含已隐藏账号列表)回退显示 5 小时窗口,而不是虚假的“周额度已使用 0%”。 +- Qianwen AI TokenPlan displays only the quota windows the endpoint actually returns + (`per5HourPercentage`, `per1WeekPercentage`, `per1MonthPercentage`). The provider dropped + the weekly cap and kept a single monthly one, so such accounts now show 月额度 instead of + an empty 周额度; the monthly window is the longest period and drives the card and + hidden-account summary. Legacy responses that still carry a weekly window keep showing it. + / 千问 AI TokenPlan 仅展示接口实际返回的额度窗口(5 小时 / 周 / 月)。官方已取消周限额、 + 仅保留月限额,此类账号现显示“月额度”,不再出现空的“周额度”;月额度同时作为最长周期用于 + 卡片与已隐藏账号汇总。仍返回周限额的旧接口数据保持原样显示。 +- Existing Qianwen accounts can renew their browser login through **更新 Token / Cookie**. + Paste a fresh complete usage curl to update Cookie / verification headers and the + form's `sec_token`, preserving the account ID, label, URL and other request data. + Only that account is refreshed after saving; failed refreshes retain its last successful cache. + / 千问账号支持原地更新登录凭据;`BailianGateway.Login.NotLogined` 会显示登录失效提示和修复指引。 - Refresh failures, including supported provider business errors returned with HTTP 200, keep the last successful cached result visible with an error notice. +- Claude OAuth accounts are synchronized from an operator-configured CLIProxyAPI + server. Cards show five-hour, weekly and any returned model-specific weekly + utilization, remaining percentages and reset countdowns. Missing windows and + reset times stay unavailable. OAuth credentials remain in CLIProxyAPI; the + dashboard stores only a hashed account reference and quota data. + / 支持从 CLIProxyAPI 同步 Claude OAuth 账号,显示 5 小时、周额度以及接口实际返回的 + 模型专属周额度;管理密钥仅配置在服务端,不向浏览器返回或复制 OAuth Token。 - Per-account Volcengine AK/SK configuration (no curl required); uses HMAC-SHA256 V4 signing against `GetCodingPlanUsage` / `GetAgentPlanAFPUsage`. - Codex supports both the official `/usage` + `/rate-limit-reset-credits` endpoints @@ -48,6 +114,21 @@ AgentPlan、Kimi Code、LongCat、千问 AI、智谱 AI CodingPlan 和 Google AI as **已过期**; authentication failures are reported separately. - Self-contained single-file browser UI (`index.html`) with a custom SVG logo and no external favicon dependency. +- Responsive layout: below 1100px each hidden-account row stacks into a name/plan row + plus a quota row, keeping the full period label (周额度 / 月额度 …) readable instead of + ellipsised, and the countdown wraps when it does not fit. Desktop keeps the aligned + single-line columns. Long inline `` paths wrap rather than forcing horizontal + page scroll on narrow phones. + / 响应式布局:窄于 1100px 时,隐藏账号行堆叠为“账号/套餐”一行加“额度”一行,完整保留 + 周额度 / 月额度等周期名(不再被省略号截断),剩余时间在放不下时自动换行;桌面端维持单行 + 对齐列。长 `` 路径可换行,避免手机上出现横向滚动。 +- In the hidden-account list, Google AI accounts with Argon show the ordinary + **Gemini weekly** usage and its reset time as **周额度已用**. If that weekly bucket + is missing, the row shows unavailable data. Google accounts without Argon appear + only in the restore dropdown, where they can still be restored normally. + / 已隐藏的 Google AI 账号中,支持 Argon 的账号显示 Gemini 通用模型的“周额度已用” + 及对应重置时间;缺少该周额度时显示暂无数据。不支持 Argon 的 Google 账号仅保留在 + 恢复显示的下拉列表中。 ## File Layout @@ -56,6 +137,8 @@ index.html Single-file frontend server.py Static file serving + JSON persistence + restricted curl execution parser.js Parser implementation used by Node tests docker-compose.yml Container deployment configuration +.github/workflows/ GitHub Actions validation (parser and server checks) +scripts/ Local helper scripts (no credentials) tests/ Parser and server unit tests AGENTS.md Coding-agent instructions for this repository ``` @@ -111,6 +194,14 @@ cd /docker/coding_plan_quota_dashboard sudo docker compose up -d --force-recreate ``` +### Continuous Integration + +[`.github/workflows/test.yml`](.github/workflows/test.yml) runs the parser tests +(`Parser (Node)`) and the server test suite plus a compile check (`Server (Python)`) +on pushes and pull requests targeting `main` / `master`, using Node.js 22 and +Python 3.13. Both checks are required before `main` is updated. + + ## Persistent Data & Backups ```text @@ -119,6 +210,7 @@ sudo docker compose up -d --force-recreate /docker/coding_plan_quota_dashboard/data/snapshot.json # latest quota snapshot /docker/coding_plan_quota_dashboard/data/results.json # per-account cached API responses /docker/coding_plan_quota_dashboard/data/order.json # account display order +/docker/coding_plan_quota_dashboard/data/hidden.json # account ids hidden from the dashboard ``` Backup: @@ -150,7 +242,7 @@ auto-classifies by URL: - `chatgpt.com/backend-api/wham/rate-limit-reset-credits` → Codex reset credits - `/api/channel/{channelId}/codex/usage` → NewAPI Codex usage - `/api/channel/{channelId}/codex/usage/reset-credits` → NewAPI Codex reset credits -- `www.minimaxi.com` → MiniMax +- `www.minimaxi.com` / `www.minimax.cn` → MiniMax - `GetCodingPlanUsage` → Volcengine CodingPlan - `GetAgentPlanAFPUsage` → Volcengine AgentPlan (current endpoint) - `GetAgentPlanUsageDetails` → Volcengine AgentPlan (legacy endpoint, still supported) @@ -161,10 +253,223 @@ auto-classifies by URL: Google AI uses the dedicated account form, not curl auto-detection. Unlock the page, add an OAuth Refresh Token and an optional proxy, and configure `GOOGLE_AI_CLIENTS` -on the server (see Security Notes). The server tries `retrieveUserQuotaSummary`, -`retrieveUserQuota` and `loadCodeAssist` across its configured Google endpoints. -The dashboard displays Gemini Models 5-hour and weekly buckets when the response -contains the supported quota structure; it cannot display absent bucket data. +on the server (see Security Notes). The server first checks `fetchAvailableModels` +across its configured Google endpoints, then combines the available model catalog +with `retrieveUserQuotaSummary` quota groups. + +Google filters these responses using client metadata. The default request profile +matches Antigravity CLI 1.4.6, including its released build (`cl=1000353293`) and +consumer authentication marker. Older client identifiers can return a legacy model +catalog that omits Argon and its weekly quota even for an eligible account. Set the +optional server-side `GOOGLE_AI_USER_AGENT` environment variable to override this +profile after a future client-protocol change; an empty value keeps the default. +Compose reads it from the shell / `.env`; an existing Portainer Stack can set it in +its environment without changing any saved account credentials. + +The official upstream spelling is **Argon**, with IDs such as +`gemini-4-argon-high`, `gemini-4-argon-medium` and `gemini-4-argon-low`. +The older `Agron` spelling is still accepted for compatibility. If an enabled, +available model's ID, display name or model enum identifies Argon, that account uses +**Argon** as its primary quota and compact plan/Code-column label. +The **GEMINI 4 ARGON** weekly bucket is shown first in the account details and supplies +the main percentage and countdown, even if another window's usage is higher. +Any explicitly returned Argon 5-hour window and ordinary **Gemini 5-hour and weekly** +windows are displayed alongside it, with independent percentages and reset times. +The current model quotas are listed separately below these windows and never supply +the Argon reading. The server checks the remaining summary +hosts when one response has Argon quota but omits the Gemini windows, and combines +the explicitly returned windows. Duplicate readings retain the lower remaining quota. +Other models' quota and Claude/GPT weekly buckets cannot supply an Argon reading. An Argon summary +alone does not establish availability: the account must also list Argon in `models`. +Disabled or explicitly unavailable Argon entries do not trigger the switch. + +If the Argon weekly bucket is missing, its primary reading uses the explicit Argon +5-hour or per-model quota that Google returns; never invent a weekly limit or reset time. +Per-model data is labelled as a model quota with an unknown period. If no usable Argon quota exists, +the refresh fails and preserves the previous successful cache. + +Google AI details show only quota that the API returned. A missing or invalid +**Gemini · 5小时** or **Gemini · 周额度** window has no row, and no placeholder +percentage or countdown is shown. A Claude/GPT window or a model quota whose period +is unknown cannot fill these windows. + +Accounts without Argon keep the Gemini Models summary behavior. If that group is +unavailable, per-model data comes from `models[id].quotaInfo` or +`retrieveUserQuota` (`buckets[].modelId`), retaining `loadCodeAssist` as a legacy fallback. +The fallback prefers the newest available Gemini version in the returned model IDs, +comparing version components numerically (for example, 3.10 follows 3.9). Within a +version, unqualified IDs precede `-tiered` and `-high` / `-medium` / `-low` variants, +with model-ID order breaking ties. Disabled, unavailable and internal models are +excluded. The choice does not depend on which model has the most quota remaining. + +Every successful Google AI refresh also rebuilds **当前模型用量** from the current +catalog and any per-model buckets. It includes public, enabled Gemini, Claude, GPT +and other named models with a valid quota, using the returned `displayName` when +present and the actual model ID otherwise. Models are grouped by family and sorted +by numeric version, newest first. Each row shows that model's own used/remaining +percentage and reported reset time; matching names do not imply a shared quota pool. +Repeated readings for the same model ID retain the lower remaining quota. Internal +chat/tab entries and models without a valid `remainingFraction` have no row. A new +refresh removes models that are no longer returned. These detail rows do not replace +the primary Gemini/Argon summary or supply missing 5-hour/weekly windows. + +The model fallback displays the actual selected model ID, its remaining/used +percentage and the reset time reported by Google. It does not label an unknown +period as 5-hour or weekly, infer shared quota pools, or invent missing reset +times. Zero remaining is valid. Missing or invalid Gemini quota is a refresh +failure that preserves the last successful cache; it is never displayed as 100% +remaining. Summaries containing only Claude/GPT buckets are not Gemini quota. + +### Claude OAuth through CLIProxyAPI + +Set `CLIPROXYAPI_BASE_URL` (for example `http://cliproxy.example.lan:8317`) +and `CLIPROXYAPI_MANAGEMENT_KEY` in the deployment environment. The base URL must +be an HTTP(S) origin without a path or embedded credentials. The Compose file +reads both variables from the shell / `.env`; Portainer deployments can supply +them as Stack environment variables. Keep the real values outside the repository. +The dashboard host must be able to reach that management endpoint, and CLIProxyAPI +must already contain an enabled Claude OAuth account. + +Unlock the dashboard and click **同步 Claude 账号并刷新**. `POST /api/claude/accounts` +adds enabled Claude OAuth accounts without duplicating existing entries, changing +their labels or removing other accounts. Repeated syncs preserve order and hidden +state. Editing a Claude label also preserves its account binding. Claude cards and +account lists display only the first five characters of the label; the full label +remains saved on the server. New accounts +are appended; they do not replace existing provider accounts. + +The backend reads `/v0/management/auth-files`, resolves each saved account to its +current `auth_index`, then calls `/v0/management/api-call` with a fixed +`GET https://api.anthropic.com/api/oauth/usage` request and the `Bearer $TOKEN$` +placeholder. CLIProxyAPI supplies the OAuth token; access and refresh tokens are +never downloaded or stored by this integration. If authentication expires, +reauthenticate in CLIProxyAPI and sync again. Both the management HTTP status and +the nested upstream `status_code` are checked. Provider errors or missing quota +windows retain the last successful cache. A 100% utilization reading is valid +exhausted quota, not proof of expired authentication. + +Claude `utilization` is already a percentage, so `2` means 2% used / 98% remaining. +Only returned five-hour, overall weekly, Opus / Sonnet / OAuth-app / Cowork weekly +windows with valid utilization are displayed. Null windows and missing reset times +are not fabricated. Response headers, unrelated billing data and disabled extra +usage are not cached or displayed. + +服务端配置 CLIProxyAPI 地址及管理密钥后,解锁页面并同步 Claude 账号即可,无需抓取或粘贴 +OAuth Token。同步只追加新账号,保留已有账号、备注、排序和隐藏状态;刷新失败继续展示成功缓存。 +请保护管理端口及密钥,使用 HTTPS 或受信任的内网连接。此集成不扩大导入 cURL 的域名白名单。 + +### Read-only summary for home dashboards + +`GET /api/summary` returns the headline quota of each visible account, ordered like +the page and computed with the same rules as the card headline (longest available +period, status thresholds 90% / 100%). Hidden accounts and `codexNewApiCredits` +are skipped; the Codex reset-card count is merged into its NewAPI account. + +```json +{"total": 1, "ok": 1, "warn": 0, "bad": 0, "updatedAt": "2026-01-01T00:00:00+00:00", + "accounts": [{"id": "acc_alpha", "name": "Kimi", "provider": "Kimi", "source": "kimi", + "usedPercent": 40.0, "remainingPercent": 60.0, "period": "周额度", + "resetAt": "2026-01-05T00:00:00+00:00", "resetCards": null, "status": "已同步", + "level": "ok", "refreshOk": true, "updatedAt": "2026-01-01T00:00:00+00:00"}]} +``` + +The response contains no curl text, tokens or raw provider responses, so it is the +endpoint to poll from Home Assistant `rest` sensors. It reads the cached snapshot: +quotas are re-parsed only while a dashboard page is open (manual or automatic +refresh), so check `updatedAt` for staleness. + +只读汇总接口 `GET /api/summary` 按页面顺序返回可见账号的主额度、状态与重置时间, +不含 cURL、Token 或原始响应,可供 Home Assistant 等家庭面板轮询。数据来自最近一次页面刷新的快照。 + +### agy account rotation + +`POST /api/agy/quotas` queries the current Google AI quota for the supplied +`accountIds` (1–20 IDs). It returns `{"ok": true, "accounts": {"acc_alpha": +{"ok": true, "status": 200, "updatedAt": "...", "fiveHour": +{"remainingPercent": 80, "resetAt": null}, "weekly": null}}}`. The top-level +`ok` means at least one requested account succeeded; always check each account's +`ok` field. Only Gemini Models buckets are included. Missing 5-hour data is a +query failure; absent weekly quota or reset times remain `null`. Exhausted quota +is valid data and does not imply expired authentication. Failures return a +generic error without provider bodies or credentials. + +Some accounts are not granted the Gemini Models group and only expose a +per-model quota. Those still report `ok: false` because they have no explicit +5-hour/weekly window, but the response now carries the model value so callers +can use it explicitly: + +```json +{"ok": false, "fiveHour": null, "weekly": null, + "fallback": {"modelId": "gemini-3.8-flash-tiered", + "remainingPercent": 99.9, + "resetAt": "2026-11-14T03:12:29Z"}} +``` + +`fallback` is `null` when no usable model quota exists. It reports a different +and narrower unit than the group windows, so it is never mixed into the same +comparison as `fiveHour`/`weekly`. + +This endpoint queries only the requested Google AI accounts concurrently (up to +five workers, with a 45-second query budget per account). It does not refresh +other providers or write requests, cached results, snapshots, ordering, or hidden +accounts. It uses the existing server-side Google OAuth clients and proxy. +Like the other dashboard APIs, it requires trusted-network access or external +authentication; the UI lock does not protect it. + +[scripts/agy_quota_rotate.py](scripts/agy_quota_rotate.py) integrates with an +existing local `~/bin/agy-switch` installation. Copy it to the script path used +by your existing rotation LaunchAgent. Copy +[the example configuration](scripts/agy-quota-rotation.example.json) to +`~/.gemini/agy-switch/quota-rotation.json` (mode `0600`), set `dashboardUrl`, and +map every local profile alias to its verified dashboard Google AI account ID. +Verify the actual OAuth identity when creating the mapping; display labels can +differ from aliases. Aliases for the same account should use the same ID. Keep +the real URL, account IDs, and credentials out of the repository. +An optional `identityHashes` object maps aliases to SHA-256 hashes of the verified +Google OAuth `sub` claim. A profile whose current identity differs is skipped +until its saved login is updated, so a pending login change cannot select the +wrong identity using another account's quota. This gate also applies to fallback: +if the hourly target has a different identity, the run fails without switching. + +Set the rotation LaunchAgent's `StartCalendarInterval` to six minute entries: +`0`, `10`, `20`, `30`, `40`, `50`. The script scores each account using +`min(fiveHour.remainingPercent, weekly.remainingPercent)` and selects the highest +score. + +Accounts without the Gemini Models group fall back to the model value the +dashboard reports (`fallback.remainingPercent`). The fallback is applied per +account: an account the dashboard reports as successful still has to supply both +explicit windows, so a missing or stale window stays a failure for that account. +The per-model value describes that account's own pool, so all accounts remain +comparable and rotation can move to the account with the most headroom. Set +`modelFallback: false` in the configuration to ignore model-only accounts. + +When fewer than two accounts are usable, or the dashboard query fails, the script +records a streak in `~/.local/state/agy-rotation-alert.json`. Logs show +`DEGRADED runs=N/threshold` until `alertAfterRuns` (default `3`) consecutive runs +are unhealthy, then emit `ALERT` at most once per hour. Any healthy run clears +the streak. Equal scores prefer the account whose next reported reset occurs soonest, +using the earlier of its 5-hour and weekly reset times. If reset times also tie, +the current profile is retained. Missing or invalid reset times stay unknown and +sort after known times; an elapsed reported reset is due (zero seconds), but does +not cause the script to assume the quota has replenished. +Both Gemini windows constrain usage: +an account with 90% left over 5 hours but only 5% left this week scores 5%, while +one with 30% left over 5 hours and 80% left this week scores 30%. This matches the +dashboard's headline remaining percentage. Either missing window makes that +account unavailable for selection; no full quota is assumed. A successful zero +reading does not trigger fallback. Individual failed queries are skipped if other +accounts succeed. If the dashboard request fails or no valid fresh quota for both +windows is returned, the original selection `profiles[current_hour % len(profiles)]` +is used; the target remains the same throughout that hour. + +Responses older than two minutes or more than 30 seconds in the future are +rejected. Invalid local configuration fails without changing the account. +The script shares `agy-switch`'s account lock, skips a busy lock, preserves +interrupted keepalive recovery, verifies Keychain and the token file, and probes +`agy models` before reporting success. Switching or probe failures do not trigger +hourly fallback. Existing account guards and keepalive tasks should retain the +same lock; schedule keepalive a few minutes away from the rotation triggers. For Zhipu AI CodingPlan, the two `TOKENS_LIMIT` entries are distinguished by their window metadata and displayed separately as 5-hour Token and weekly quota; their @@ -189,11 +494,37 @@ The legacy full RefreshToken cURL API remains accepted for existing configuratio To update MiniMax authentication, unlock the page, click **更新验证头** on its card, and paste a fresh browser-copied `token_plan/remains_percent` curl. Cookie and other verification headers are merged into the saved request; the URL, body and account -ID are preserved. HTTP 200 with a nonzero `base_resp.status_code` is treated as a +ID are preserved. Requests copied from either `www.minimaxi.com` or `www.minimax.cn` +can update an account on the other domain when the scheme, port and path match. +HTTP 200 with a nonzero `base_resp.status_code` is treated as a failed refresh. A 100% usage reading alone does not prove authentication has expired. MiniMax 验证信息失效时,可在账号卡片中点击 **更新验证头**,粘贴浏览器新复制的完整 -cURL,再保存并刷新。刷新失败时保留上次成功的数据,并显示错误提示。 +cURL,再保存并刷新。支持旧域名 `www.minimaxi.com` 和新域名 `www.minimax.cn`; +同一接口可跨这两个域名更新验证头,保留原 URL、请求体和账号 ID。 +刷新失败时保留上次成功的数据,并显示错误提示。 + +To repair Qianwen `BailianGateway.Login.NotLogined`, sign in to the Qianwen +console again and open the Token Plan usage page. In the browser's Network panel, +find the `data/api.json` request whose `api` query parameter contains `tokenplan` +and ends in `/usage`, and choose **Copy as cURL (bash)**. Unlock the dashboard, +click **更新 Token / Cookie** on the existing Qianwen card, paste the complete curl, +and click **保存并刷新**. This console endpoint uses a browser login Cookie and a +form `sec_token`; a model API Key does not replace them. This feature updates an +existing session manually; it does not provide automatic OAuth / RefreshToken renewal. +The backend validates the same host, port, path and `product` / `action` / `api` +routing parameters, merges request headers and updates only `sec_token` in the +saved form body. Other request data, labels, account ordering, hidden state and +other accounts are preserved. When the saved form contains `sec_token`, a new +curl without it is rejected to avoid keeping a stale token alongside fresh cookies. + +千问提示未登录时,请重新登录控制台,打开 Token Plan 用量页,从 Network 复制完整的 +用量查询 cURL(bash 格式),再在原账号卡片中更新。不要重新添加账号,也不要只填 API Key。 +保存后仅刷新当前千问账号。`POST /api/refresh` 可选传入 +`{"accountIds":["acc_example"]}`(1–20 个已保存账号 ID)进行定向刷新;不传时仍刷新全部账号。 +传入 `"stream":true` 时以 NDJSON 逐行返回 `{"id":...,"ok":...}`,每个账号完成即输出一行; +不传时返回包含全部账号结果的 JSON 对象。 +HTTP 200 中的登录业务错误仍视为失败并保留上次成功缓存,额度耗尽本身不代表登录失效。 Codex official and NewAPI endpoints can coexist; the server merges them into one card. `curl -sS`, `--proxy` and `--insecure` flags are translated into Python HTTPS @@ -206,7 +537,7 @@ and shows "接口未返回" instead of fabricating usage. - The server does not shell out; imported curl is parsed and re-issued via Python `urllib`-style HTTPS requests. -- The host allowlist defaults to `chatgpt.com`, `www.minimaxi.com`, +- The host allowlist defaults to `chatgpt.com`, `www.minimaxi.com`, `www.minimax.cn`, `console.volcengine.com`, `www.kimi.com`, `auth.kimi.com`, `longcat.chat`, `cs-data.qianwenai.com`, and `www.bigmodel.cn`; additional NewAPI hosts can be enabled via the `NEWAPI_HOSTS` (comma-separated) environment variable and are accepted only for @@ -216,6 +547,11 @@ and shows "接口未返回" instead of fabricating usage. When unset, the server boots with three `REDACTED_*` placeholders and the Google AI refresh call will fail until you provide real values; this keeps credentials out of source code. +- Claude uses `CLIPROXYAPI_BASE_URL` and `CLIPROXYAPI_MANAGEMENT_KEY` only on the + server. Management redirects are rejected, and the configured LAN endpoint + bypasses process proxy variables. The browser receives no management key, + OAuth tokens or CLIProxyAPI auth-file contents; management errors are sanitized. + Account labels and filtered quota responses remain private dashboard data. - NewAPI is reached over plain HTTP because it is a LAN service — do **not** extend this rule to arbitrary external HTTP endpoints. - When a `codexNewApi` request is saved the refresh automatically skips the official @@ -227,6 +563,8 @@ and shows "接口未返回" instead of fabricating usage. - `/api/requests` removes separate Kimi refresh fields and proxy settings and masks the `sk` and Google `refreshToken` fields. It still returns saved curl text, which can contain Authorization headers and cookies; this endpoint is sensitive. +- `/api/summary` exposes only account display names, headline percentages, status + and timestamps; it is intended for LAN dashboards such as Home Assistant. - The page lock prevents accidental edits in the UI; it is not authentication or API access control. Protect the service with network restrictions or an authenticated reverse proxy before granting access beyond a trusted environment. @@ -240,10 +578,35 @@ PYTHONPATH=. python3 -m unittest discover -s tests -p 'test_*.py' python3 -m py_compile server.py ``` -CI runs the same commands on pushes to `main` / `master` and pull requests targeting +GitHub CI runs the same commands on pushes to `main` / `master` and pull requests targeting those branches; see [`.github/workflows/test.yml`](./.github/workflows/test.yml). +## Live Verification / 线上验证 + +A deployed instance holds real user state, so verification runs must be +non-destructive: + +- The JSON files under the deployment `data/` directory are user state, not test + fixtures. Never write defaults, empty arrays or synthetic ids into `/api/order`, + `/api/hidden`, `/api/requests` or `/api/snapshot` while testing a live instance. +- Read the current value of every field before changing it and keep that snapshot. + After the run, restore the exact saved value — do not clear a list because the test + has finished. +- Report the before and after value of each mutated field, so an unintended change is + visible instead of being described as a clean run. +- Prefer an isolated local server with fixture data. When a live check is unavoidable, + append a dedicated throwaway account id to the saved list and remove it by id. +- Never use an existing account as the subject of a delete or overwrite test. +- `hidden.json` and `order.json` have no automatic per-write backup; the periodic data + archive is the only recovery path, which is why live writes must be additive and + reversible. + +/ 部署实例上的 `data/` 文件属于用户真实状态,不是测试夹具。线上验证前必须先读取并保留原值, +验证后按原值精确还原,禁止把显示顺序、隐藏列表等重置为空来“收尾”;并在结果中报告每个被修改 +字段的变更前后值。优先使用本地隔离服务与夹具数据;必须线上验证时只追加重命名可丢弃的测试 +账号 id,并按 id 精确移除。不得用现有账号验证删除或覆盖逻辑。 + ## Repository Synchronization / 仓库同步 The development repository on Gitea retains the complete commit history. GitHub diff --git a/docker-compose.yml b/docker-compose.yml index 9bf507e..f7afd2f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -6,6 +6,9 @@ services: environment: PORT: "8080" APP_REVISION: "2026-07-14-codex-agentplan-fix" + GOOGLE_AI_USER_AGENT: "${GOOGLE_AI_USER_AGENT:-}" + CLIPROXYAPI_BASE_URL: "${CLIPROXYAPI_BASE_URL:-}" + CLIPROXYAPI_MANAGEMENT_KEY: "${CLIPROXYAPI_MANAGEMENT_KEY:-}" command: ["python", "/srv/server.py"] volumes: - /docker/coding_plan_quota_dashboard/index.html:/srv/index.html:ro diff --git a/index.html b/index.html index 32485c2..011b37a 100644 --- a/index.html +++ b/index.html @@ -10,9 +10,15 @@ @@ -57,11 +64,50 @@ .card-actions button:not(.primary),.reorder-btns button,.label-edit button:not(.save),.creds-edit .actions button:not(.primary){background:var(--panel2);border-color:var(--line);color:var(--muted)} .card-actions button:not(.primary):hover,.reorder-btns button:hover,.label-edit button:not(.save):hover,.creds-edit .actions button:not(.primary):hover{color:var(--text);border-color:var(--accent)} .card-actions button.danger,.card-actions button.danger:hover{color:var(--bad)} +.hidden-panel h3{margin-bottom:6px} +.select-wide{width:100%;background:var(--panel);border:1px solid var(--line);border-radius:9px;color:var(--text);padding:8px 10px;font-size:13px} +.hidden-list{margin-top:14px;display:flex;flex-direction:column;gap:8px} +.hidden-restore{display:flex;align-items:center;gap:8px;margin-top:4px} +.hidden-restore label{font-size:12px;color:var(--muted);flex:0 0 auto} +.hidden-restore .select-wide{flex:1 1 auto;min-width:0;width:auto;padding:6px 10px;font-size:12px;border-radius:7px} +.hidden-row{display:flex;align-items:center;gap:10px;padding:9px 12px;border:1px solid var(--line);border-radius:11px;background:var(--panel2)} +.hidden-row .name{color:var(--text);flex:0 0 15rem;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.hidden-row .sub{color:var(--muted);font-size:12px;flex:0 0 5rem;max-width:5rem;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.hidden-row .longest{display:inline-grid;grid-template-columns:6rem 8rem 9rem;align-items:center;gap:8px;color:var(--muted);font-size:12px;flex:0 0 auto} +.hidden-row .lp-value{display:flex;align-items:center;gap:6px;justify-content:flex-end} +.hidden-row .lp-pct{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap;flex:0 0 4.2rem} +.hidden-row .lp-bar{flex:1 1 auto;min-width:0;height:6px;border-radius:99px;background:color-mix(in srgb,var(--bg) 82%,#000000);overflow:hidden} +.hidden-row .lp-bar .fill{display:block;height:100%;border-radius:inherit;background:linear-gradient(90deg,var(--accent),#b678ff);transition:width .3s} +.hidden-row .lp-bar .fill.good{background:linear-gradient(90deg,var(--good),color-mix(in srgb,var(--good) 55%,#ffffff))} +.hidden-row .lp-reset{white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.hidden-row .lp-name{white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.hidden-row .spacer{flex:1 1 auto} +.hidden-row button,.hidden-restore button{padding:4px 10px;font-size:12px;border-radius:7px;border:1px solid var(--line);background:var(--panel);color:var(--muted);flex:0 0 auto} +.hidden-row button:hover,.hidden-restore button:hover{color:var(--text);border-color:var(--accent)} +body.locked .hidden-panel .hidden-restore,body.locked .hidden-row button{display:none!important} .label-edit button.save{color:#fff} .label-edit input,.creds-edit input,#volcSource{background:var(--panel)!important;border-color:var(--line)!important;color:var(--text)!important} .appearance-controls{display:flex;gap:7px;align-items:center;flex-wrap:wrap}.appearance-controls select{background:var(--panel2);border:1px solid var(--line);border-radius:9px;color:var(--text);padding:8px 10px;font-size:12px}.appearance-controls label{color:var(--muted);font-size:11px} +.logo.claude{background:#573c30;color:#f4cfb6} body.locked .appearance-controls{display:none!important} @media(max-width:800px){.appearance-controls{justify-content:flex-start;margin-top:8px}} +@media(max-width:1100px){ +.shell{padding:24px 14px 46px} +.card{padding:15px} +.hidden-restore{flex-wrap:wrap} +.hidden-restore .select-wide{flex:1 1 11rem} +.hidden-row{display:grid;grid-template-columns:minmax(0,1fr) auto auto;grid-template-areas:"name sub btn" "long long long";column-gap:8px;row-gap:7px;align-items:center;padding:11px 12px} +.hidden-row .name{grid-area:name;flex:none} +.hidden-row .sub{grid-area:sub;flex:none} +.hidden-row button{grid-area:btn} +.hidden-row .spacer{display:none} +.hidden-row .longest{grid-area:long;display:flex;flex-wrap:wrap;align-items:center;gap:4px 8px;width:100%;flex:none} +.hidden-row .lp-name{flex:0 0 auto;white-space:nowrap;overflow:visible;text-overflow:clip} +.hidden-row .lp-value{flex:1 1 8rem;min-width:7rem} +.hidden-row .lp-pct{flex:0 0 auto} +.hidden-row .lp-bar{min-width:2rem} +.hidden-row .lp-reset{flex:0 0 auto;text-align:left} +} @@ -73,6 +119,11 @@
+

数据采集

导入原始 curl:系统会根据接口 URL 自动识别平台类型。每个 curl 保存为独立账号,可添加备注区分。请求会保存到服务器 JSON 文件,页面每次打开或点击刷新时由服务器重新执行。注意:原始 curl 可能包含 Token/Cookie,会以明文保存在服务器。

@@ -96,7 +147,7 @@

新增火山方舟账号

无需抓包,直接填写 Acc

更新已有火山方舟账号的 AK/SK

在对应 CodingPlan / AgentPlan 卡片上点击「设置 AK/SK」即可为该账号配置 OpenAPI 凭据。配置后该账号将通过 OpenAPI 签名鉴权获取用量,无需 curl 中的 Cookie。

-

新增 Google AI 账号

填写 Antigravity / Gemini CLI 的 OAuth refresh token 创建 Google AI 账号,显示 Gemini Models 的 5 小时和周额度。refresh token 可在 ~/.gemini/antigravity-cli/antigravity-oauth-token(字段 token.refresh_token)或 ~/.gemini/oauth_creds.json 中找到。代理默认使用服务器环境变量 GOOGLE_AI_PROXY,可在此覆盖;不填则直接对外网请求。

+

新增 Google AI 账号

填写 Antigravity / Gemini CLI 的 OAuth refresh token 创建 Google AI 账号,支持 Argon(兼容 Agron 标识)的账号优先显示 GEMINI 4 ARGON 周限额,并同时展示接口返回的 Argon 5 小时额度、普通 Gemini 5 小时/周额度和 Gemini 3.8 Flash 模型额度。仅显示接口实际返回的额度,未返回的窗口不显示;普通账号在分组不可用时优先使用 Gemini 3.8 Flash 模型额度。refresh token 可在 ~/.gemini/antigravity-cli/antigravity-oauth-token(字段 token.refresh_token)或 ~/.gemini/oauth_creds.json 中找到。代理默认使用服务器环境变量 GOOGLE_AI_PROXY,可在此覆盖;不填则直接对外网请求。

@@ -104,6 +155,10 @@

新增 Google AI 账号

填写 Antigravity / Gemini CLI

+
+

Claude OAuth 账号

从已连接的 CLIProxyAPI 同步 Claude OAuth 账号,显示 5 小时和周额度的使用比例、剩余比例及重置倒计时。登录凭据由 CLIProxyAPI 管理,无需复制 Token。重复同步会保留已有账号和备注;认证失效时请在 CLIProxyAPI 中重新登录,再同步账号。

+
+
diff --git a/parser.js b/parser.js index 45a8287..e006f58 100644 --- a/parser.js +++ b/parser.js @@ -22,23 +22,30 @@ function percent(value) { } function normalizeWindows(value) { - return Array.isArray(value.model_remains) ? value.model_remains.map(item => ({ - modelName: item.model_name || 'Plan', - interval: { - usedPercent: percent(item.current_interval_used_percent), - totalPercent: percent(item.current_interval_total_percent) || 100, - remainingPercent: Math.max(0, 100 - percent(item.current_interval_used_percent)), - startAt: item.start_time || null, - resetAt: item.end_time || null - }, - weekly: { - usedPercent: percent(item.current_weekly_used_percent), - totalPercent: percent(item.current_weekly_total_percent) || 100, - remainingPercent: Math.max(0, 100 - percent(item.current_weekly_used_percent)), - startAt: item.weekly_start_time || null, - resetAt: item.weekly_end_time || null - } - })) : []; + return Array.isArray(value.model_remains) ? value.model_remains.map(item => { + const weeklyTotalRaw = item.current_weekly_total_percent ?? item.current_weekly_total ?? item.weekly_total_percent; + const weeklyTotal = percent(weeklyTotalRaw); + const weeklyStatus = Number(item.current_weekly_status ?? item.weekly_status); + const weeklyAvailable = !!weeklyTotalRaw && weeklyTotal > 0 && !(Number.isFinite(weeklyStatus) && weeklyStatus !== 1); + return { + modelName: item.model_name || 'Plan', + interval: { + usedPercent: percent(item.current_interval_used_percent), + totalPercent: percent(item.current_interval_total_percent) || 100, + remainingPercent: Math.max(0, 100 - percent(item.current_interval_used_percent)), + startAt: item.start_time || null, + resetAt: item.end_time || null + }, + weekly: { + available: weeklyAvailable, + usedPercent: percent(item.current_weekly_used_percent), + totalPercent: weeklyTotal || 100, + remainingPercent: Math.max(0, 100 - percent(item.current_weekly_used_percent)), + startAt: item.weekly_start_time || null, + resetAt: item.weekly_end_time || null + } + }; + }) : []; } function unwrap(value) { @@ -134,11 +141,15 @@ function normalizeQianwen(payload) { if (value && typeof value[key] === 'object') value = value[key]; } const periods = []; - if (value.per5HourPercentage !== undefined) { - periods.push({ name: '5h', usedPercent: ratioToPercent(value.per5HourPercentage), remainingPercent: Math.max(0, 100 - ratioToPercent(value.per5HourPercentage)), resetAt: firstNumber(value, ['per5HourResetTime']) }); - } - if (value.per1WeekPercentage !== undefined) { - periods.push({ name: '1w', usedPercent: ratioToPercent(value.per1WeekPercentage), remainingPercent: Math.max(0, 100 - ratioToPercent(value.per1WeekPercentage)), resetAt: firstNumber(value, ['per1WeekResetTime']) }); + const quotaWindows = [ + ['5h', 'per5HourPercentage', 'per5HourResetTime'], + ['1w', 'per1WeekPercentage', 'per1WeekResetTime'], + ['monthly', 'per1MonthPercentage', 'per1MonthResetTime'] + ]; + for (const [name, percentKey, resetKey] of quotaWindows) { + if (value[percentKey] === undefined || value[percentKey] === null) continue; + const usedPercent = ratioToPercent(value[percentKey]); + periods.push({ name, usedPercent, remainingPercent: Math.max(0, 100 - usedPercent), resetAt: firstNumber(value, [resetKey]) }); } const used = periods.length ? Math.max(...periods.map(period => period.usedPercent)) : 0; return { limit: 100, used, remaining: Math.max(0, 100 - used), unit: '%', periods, updatedAt: Date.now() }; @@ -258,23 +269,153 @@ function normalizeVolcengine(payload) { }; } +function normalizeClaude(payload) { + const value = payload && typeof payload === 'object' ? payload : {}; + const labels = [['five_hour', '5h'], ['seven_day', 'weekly'], + ['seven_day_opus', 'Opus周额度'], ['seven_day_sonnet', 'Sonnet周额度'], + ['seven_day_oauth_apps', 'OAuth应用周额度'], ['seven_day_cowork', 'Cowork周额度']]; + const periods = []; + for (const [key, name] of labels) { + const bucket = value[key]; + const utilization = bucket && typeof bucket === 'object' ? firstNumber(bucket, ['utilization']) : null; + if (utilization === null || utilization === undefined || utilization < 0) continue; + const usedPercent = Math.max(0, Math.min(100, utilization)); + periods.push({ name, usedPercent, remainingPercent: 100 - usedPercent, + resetAt: typeof bucket.resets_at === 'string' && Number.isFinite(Date.parse(bucket.resets_at)) ? bucket.resets_at : null }); + } + const used = periods.length ? Math.max(...periods.map(period => period.usedPercent)) : 0; + return { limit: periods.length ? 100 : null, used: periods.length ? used : null, + remaining: periods.length ? 100 - used : null, unit: '%', periods, updatedAt: Date.now() }; +} + function normalizeGoogleAi(payload) { const value = unwrap(payload); - const groups = Array.isArray(value.groups) ? value.groups : []; - const group = groups.find(item => String(item?.displayName || '').toLowerCase() === 'gemini models') - || groups.find(item => String(item?.displayName || '').toLowerCase().includes('gemini')); - if (!group || !Array.isArray(group.buckets)) return { limit: 100, used: 0, remaining: 100, unit: '%', periods: [], updatedAt: Date.now() }; - const labels = { '5h': '5h', weekly: 'weekly' }; - const periods = group.buckets - .filter(bucket => bucket && labels[bucket.window] && Number.isFinite(Number(bucket.remainingFraction))) - .map(bucket => { - const remaining = Math.max(0, Math.min(1, Number(bucket.remainingFraction))); - const usedPercent = Math.max(0, Math.min(100, (1 - remaining) * 100)); - return { name: labels[bucket.window], usedPercent, remainingPercent: Math.max(0, 100 - usedPercent), resetAt: bucket.resetTime || bucket.reset_at || null }; - }) - .sort((left, right) => ({ '5h': 0, weekly: 1 }[left.name] ?? 9) - ({ '5h': 0, weekly: 1 }[right.name] ?? 9)); - const used = periods.length ? Math.max(...periods.map(period => period.usedPercent)) : 0; - return { limit: 100, used, remaining: Math.max(0, 100 - used), unit: '%', periods, updatedAt: Date.now() }; + const empty = { limit: null, used: null, remaining: null, unit: '%', periods: [], updatedAt: Date.now() }; + if (payload?.error || payload?.success === false || value.error || value.success === false) return empty; + const fraction = bucket => { + const raw = bucket.remainingFraction ?? bucket.remaining_fraction; + if (!['number', 'string'].includes(typeof raw) || (typeof raw === 'string' && !raw.trim())) return null; + const number = Number(raw); + return Number.isFinite(number) && number >= 0 && number <= 1 ? number : null; + }; + const period = (name, bucket, remaining) => ({ name, usedPercent: (1 - remaining) * 100, + remainingPercent: remaining * 100, + resetAt: typeof (bucket.resetTime || bucket.reset_at) === 'string' + && Number.isFinite(Date.parse(bucket.resetTime || bucket.reset_at)) ? (bucket.resetTime || bucket.reset_at) : null }); + const catalog = value.models && typeof value.models === 'object' && !Array.isArray(value.models) ? value.models : {}; + const available = model => model && typeof model === 'object' && !Array.isArray(model) + && model.disabled !== true && model.available !== false && model.isInternal !== true; + const version = text => (String(text).match(/\d+(?:[.-]\d+)*/)?.[0] || '0').split(/[.-]/).map(Number); + const compareVersion = (left, right) => { + for (let index = 0; index < Math.max(left.length, right.length); index++) { + const difference = (right[index] || 0) - (left[index] || 0); + if (difference) return difference; + } + return 0; + }; + const compareId = (left, right) => left < right ? -1 : left > right ? 1 : 0; + const geminiVersion = id => { + const match = id.match(/^gemini-(\d+)(?:\.(\d+))?(?:\.(\d+))?/); + return [1, 2, 3].map(index => Number(match?.[index] || 0)); + }; + const isArgon = text => /argon|agron/i.test(text); + const agronPriority = id => id.toLowerCase() === 'gemini-4-argon' ? -4 + : id.toLowerCase().startsWith('gemini-4-argon-') ? -3 : id.toLowerCase() === 'gemini-4-agron' ? -2 : -1; + const agronModels = Object.entries(catalog).filter(([id, model]) => /^[A-Za-z0-9._-]+$/.test(id) + && available(model) + && isArgon(`${id} ${model.displayName || ''} ${model.model || ''}`)) + .sort(([left], [right]) => agronPriority(left) - agronPriority(right) + || (left < right ? -1 : left > right ? 1 : 0)); + const supportsAgron = agronModels.length > 0; + const agronIds = new Set(agronModels.map(([id]) => id)); + const groups = (Array.isArray(value.groups) ? value.groups : []).filter(item => item && typeof item === 'object'); + const selectGroup = agron => { + const available = groups.filter(item => isArgon(String(item.displayName || '')) === agron); + const preferred = agron ? ['gemini4argon', 'gemini4agron'] : ['geminimodels']; + return preferred.map(name => available.find(item => String(item.displayName || '').toLowerCase().replace(/[^a-z0-9]/g, '') === name)).find(Boolean) + || available.find(item => agron || String(item.displayName || '').toLowerCase().includes('gemini')); + }; + const group = selectGroup(supportsAgron); + const modelName = /argon/i.test(`${group?.displayName || ''} ${agronModels.map(([id, model]) => `${id} ${model.displayName || ''} ${model.model || ''}`).join(' ')}`) + ? 'GEMINI 4 ARGON' : 'GEMINI 4 AGRON'; + const readWindows = selectedGroup => { + const windows = new Map(); + for (const bucket of Array.isArray(selectedGroup?.buckets) ? selectedGroup.buckets : []) { + if (!bucket) continue; + const name = String(bucket.window || '').toLowerCase(); + if (!['5h', 'weekly'].includes(name)) continue; + const remaining = fraction(bucket); + if (remaining === null) continue; + if (!windows.has(name) || remaining * 100 < windows.get(name).remainingPercent) + windows.set(name, period(name, bucket, remaining)); + } + return windows; + }; + const candidates = (Array.isArray(value.buckets) ? value.buckets : []) + .filter(bucket => bucket && typeof bucket === 'object') + .map(bucket => [bucket.modelId ?? bucket.model_id, bucket]); + for (const [id, model] of Object.entries(catalog)) + if (available(model)) candidates.push([id, model.quotaInfo ?? model.quota_info]); + const compareModel = (left, right, agron) => agron + ? agronPriority(left) - agronPriority(right) || compareId(left, right) + : compareVersion(geminiVersion(left), geminiVersion(right)) + || (/-tiered$/.test(left) ? 1 : /-(high|medium|low)$/.test(left) ? 2 : 0) + - (/-tiered$/.test(right) ? 1 : /-(high|medium|low)$/.test(right) ? 2 : 0) + || compareId(left, right); + const allModels = new Map(); + for (const [id, bucket] of candidates) { + if (typeof id !== 'string' || !/^[A-Za-z0-9._-]+$/.test(id) || !bucket || typeof bucket !== 'object') continue; + const metadata = catalog[id]; + if (metadata && !available(metadata)) continue; + if (!/^(gemini|claude|gpt)-/i.test(id) && !metadata?.displayName && !agronIds.has(id)) continue; + const remaining = fraction(bucket); + if (remaining === null) continue; + if (!allModels.has(id) || remaining * 100 < allModels.get(id).remainingPercent) { + const { name, ...quota } = period(id, bucket, remaining); + allModels.set(id, { modelId: id, modelName: typeof metadata?.displayName === 'string' + && metadata.displayName.trim() ? metadata.displayName.trim() : id, ...quota }); + } + } + const family = id => /^gemini-/i.test(id) ? 0 : /^claude-/i.test(id) ? 1 : /^gpt-/i.test(id) ? 2 : 3; + const displayModels = [...allModels.values()].sort((left, right) => family(left.modelId) - family(right.modelId) + || compareVersion(version(left.modelName), version(right.modelName)) || compareId(left.modelId, right.modelId)); + const modelDetails = displayModels.length ? { modelQuotas: displayModels } : {}; + const modelQuotas = agron => candidates.filter(([id, bucket]) => typeof id === 'string' + && (agron ? agronIds.has(id) : /^gemini-[a-z0-9._-]+$/.test(id) && !isArgon(id)) + && (!catalog[id] || available(catalog[id])) + && bucket && typeof bucket === 'object' && fraction(bucket) !== null) + .map(([id, bucket]) => ({ ...period(id, bucket, fraction(bucket)), modelId: id })) + .sort((left, right) => compareModel(left.modelId, right.modelId, agron) + || left.remainingPercent - right.remainingPercent); + const windows = readWindows(group); + const geminiWindows = supportsAgron ? readWindows(selectGroup(false)) : new Map(); + const geminiPeriods = ['5h', 'weekly'].filter(name => geminiWindows.has(name)) + .map(name => ({ ...geminiWindows.get(name), name: `gemini-${name}`, + label: `Gemini · ${name === '5h' ? '5小时' : '周额度'}` })); + // Argon accounts can also return an ordinary Gemini model quota without a window. + const geminiModel = supportsAgron ? modelQuotas(false)[0] : null; + if (geminiModel) { + const { modelId, ...quota } = geminiModel; + geminiPeriods.push({ ...quota, name: 'gemini-model', label: `${modelId} · 模型额度` }); + } + const periods = (supportsAgron ? ['weekly', '5h'] : ['5h', 'weekly']) + .filter(name => windows.has(name)).map(name => windows.get(name)); + if (periods.length) { + const used = supportsAgron ? periods[0].usedPercent : Math.max(...periods.map(item => item.usedPercent)); + if (supportsAgron) for (const item of periods) + item.label = `${modelName} · ${item.name === 'weekly' ? '周限额' : '5小时限额'}`; + return { limit: 100, used, remaining: 100 - used, unit: '%', periods: [...periods, ...geminiPeriods], ...modelDetails, + ...(supportsAgron ? { modelId: agronModels[0][0], modelName, planLabel: 'Agron', + quotaSource: 'agron', primaryPeriodName: periods[0].name } : {}), updatedAt: Date.now() }; + } + const models = modelQuotas(supportsAgron); + if (!models.length) return empty; + const { modelId, ...selected } = models[0]; + if (supportsAgron) selected.label = `${modelName} · 模型额度`; + return { limit: 100, used: selected.usedPercent, remaining: selected.remainingPercent, + unit: '%', periods: [selected, ...geminiPeriods], ...modelDetails, modelId, quotaSource: 'model', + ...(supportsAgron ? { modelName, planLabel: 'Agron', primaryPeriodName: selected.name } : {}), + updatedAt: Date.now() }; } -module.exports = { normalizeCodex, normalizeCodexCredits, normalizeCodexNewApi, normalizeCodexUsage, normalizeMiniMax, normalizeKimi, normalizeQianwen, normalizeZhipu, normalizeLongCat, normalizeVolcengine, normalizeGoogleAi }; +module.exports = { normalizeCodex, normalizeCodexCredits, normalizeCodexNewApi, normalizeCodexUsage, normalizeMiniMax, normalizeKimi, normalizeQianwen, normalizeZhipu, normalizeLongCat, normalizeVolcengine, normalizeGoogleAi, normalizeClaude }; diff --git a/scripts/agy-quota-rotation.example.json b/scripts/agy-quota-rotation.example.json new file mode 100644 index 0000000..8289b6a --- /dev/null +++ b/scripts/agy-quota-rotation.example.json @@ -0,0 +1,8 @@ +{ + "dashboardUrl": "http://localhost:8080", + "timeoutSeconds": 65, + "accountIds": { + "alpha": "acc_alpha", + "beta": "acc_beta" + } +} diff --git a/scripts/agy_quota_rotate.py b/scripts/agy_quota_rotate.py new file mode 100644 index 0000000..28b871f --- /dev/null +++ b/scripts/agy_quota_rotate.py @@ -0,0 +1,399 @@ +#!/usr/bin/env python3 +"""Select an agy profile using both quota windows, with hourly fallback.""" + +from contextlib import redirect_stdout +from datetime import datetime, timezone +from pathlib import Path +from urllib.parse import urlparse +from urllib.request import ProxyHandler, Request, build_opener +import io +import hashlib +import json +import math +import os +import re +import runpy +import signal +import subprocess +import sys + + +CONFIG_PATH = Path(os.environ.get( + 'AGY_QUOTA_ROTATION_CONFIG', + str(Path.home() / '.gemini/agy-switch/quota-rotation.json'), +)) + + +ALERT_PATH = Path(os.environ.get( + 'AGY_ROTATION_ALERT_STATE', + str(Path.home() / '.local/state/agy-rotation-alert.json'), +)) + + +class ConfigurationError(RuntimeError): + pass + + +def alert_sequence(condition, config, now=None, usable=None): + """Track consecutive unhealthy runs; log ALERT once per hour at the threshold.""" + if not condition: + try: + ALERT_PATH.unlink() + except FileNotFoundError: + pass + return + threshold = config.get('alertAfterRuns', 3) + if isinstance(threshold, bool) or not isinstance(threshold, int) or threshold < 1: + threshold = 3 + now = now or datetime.now(timezone.utc) + state = {} + try: + loaded = json.loads(ALERT_PATH.read_text()) + if isinstance(loaded, dict): + state = loaded + except (OSError, ValueError): + state = {} + runs = int(state.get('runs') or 0) + 1 + last_alert = state.get('lastAlertAt') or '' + try: + since = (now - datetime.fromisoformat(last_alert)).total_seconds() + except (ValueError, TypeError): + since = math.inf + if runs < threshold: + log(f'DEGRADED runs={runs}/{threshold} usable_accounts={usable if usable is not None else state.get("usable", "unknown")}') + elif since >= 3600: + log(f'ALERT runs={runs} 轮换已连续多轮无法按 dashboard 额度充分选择账号,请检查账号与 dashboard。') + last_alert = now.isoformat() + try: + ALERT_PATH.parent.mkdir(parents=True, exist_ok=True) + ALERT_PATH.write_text(json.dumps({'runs': runs, 'lastAlertAt': last_alert, 'usable': usable}, ensure_ascii=False)) + except OSError: + pass + + + +def log(message): + print(f'{datetime.now().isoformat(timespec="seconds")} {message}', flush=True) + + +def target_profile(profiles, hour): + """Preserve the original hour-of-day selection, including its wraparound.""" + aliases = list(profiles) + if not aliases: + raise RuntimeError('没有可轮换的 agy 账号。') + index = (hour + 1) % len(aliases) or len(aliases) + return aliases[index - 1], index + + +def redact(text): + text = re.sub(r'(?:sk-[A-Za-z0-9_-]+|ya29\.[A-Za-z0-9_.-]+|1//[A-Za-z0-9_-]+|go-keyring-base64:[A-Za-z0-9+/=]+)', '[REDACTED]', text) + text = re.sub(r'eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+', '[REDACTED]', text) + return re.sub(r'[A-Za-z0-9_.+%-]+@[A-Za-z0-9.-]+', '[REDACTED_EMAIL]', text) + + +def query_dashboard(config, account_ids): + base = config.get('dashboardUrl', '').rstrip('/') + parsed = urlparse(base) + if parsed.scheme not in ('http', 'https') or not parsed.netloc or parsed.username or parsed.password or parsed.query or parsed.fragment: + raise ConfigurationError('dashboardUrl 必须是无凭据的 HTTP(S) 地址。') + timeout = config.get('timeoutSeconds', 65) + if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not 1 <= timeout <= 120: + raise ConfigurationError('timeoutSeconds 必须在 1 到 120 秒之间。') + request = Request( + base + '/api/agy/quotas', method='POST', + headers={'Content-Type': 'application/json', 'Accept': 'application/json'}, + data=json.dumps({'accountIds': account_ids}).encode(), + ) + # The configured dashboard is normally on the LAN, outside the agy proxy. + with build_opener(ProxyHandler({})).open(request, timeout=timeout) as response: + body = response.read(262145) + if len(body) > 262144: + raise RuntimeError('dashboard 响应过大。') + return json.loads(body) + + +def remaining_percent(period): + value = period.get('remainingPercent') if isinstance(period, dict) else None + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not 0 <= value <= 100: + return None + return value + + +def reset_seconds(period, now): + """Keep absent/invalid reset times unknown; a reported elapsed time is due.""" + value = period.get('resetAt') if isinstance(period, dict) else None + if not isinstance(value, str) or not value: + return None + try: + reset = datetime.fromisoformat(value.replace('Z', '+00:00')) + if reset.tzinfo is None: + return None + return max(0, (reset - now).total_seconds()) + except (ValueError, OverflowError): + return None + + +def format_seconds(value): + return 'unknown' if value is None else f'{value:.0f}' + + +LAST_SELECTION = {} + + +def fallback_percent(row): + """Return a per-model remaining percentage when no explicit window exists.""" + fallback = row.get('fallback') + if not isinstance(fallback, dict): + return None + value = fallback.get('remainingPercent') + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not 0 <= value <= 100: + return None + return value + + +def freshness(row, now): + """Age of the dashboard row in seconds; infinite when unusable.""" + try: + updated = datetime.fromisoformat(str(row.get('updatedAt', '')).replace('Z', '+00:00')) + if updated.tzinfo is None: + return math.inf + return (now - updated).total_seconds() + except (ValueError, TypeError, AttributeError): + return math.inf + + +def group_usable(row, now): + """Score an account by both explicit windows; None when either is missing.""" + remaining = remaining_percent(row.get('fiveHour')) + weekly = remaining_percent(row.get('weekly')) + if remaining is None or weekly is None: + return None + if not -30 <= freshness(row, now) <= 120: + return None + resets = [value for value in (reset_seconds(row.get('fiveHour'), now), reset_seconds(row.get('weekly'), now)) + if value is not None] + return min(remaining, weekly), (min(resets) if resets else math.inf) + + +def model_usable(row, now): + """Score an account by its per-model quota alone.""" + usable = fallback_percent(row) + if usable is None: + return None + reset = reset_seconds(row.get('fallback'), now) + return usable, (math.inf if reset is None else reset) + + +def account_usable(row, now, allow_model): + """Score one account, falling back per account rather than per run. + + An account the dashboard reports as successful must supply both explicit + windows (missing ones stay failures). Accounts without the Gemini Models + group report ok=false; their per-model quota describes the same underlying + pool, so it is used for those accounts only. That keeps every account + comparable without weakening the explicit-window contract. + """ + if row.get('ok') is True: + remaining = remaining_percent(row.get('fiveHour')) + weekly = remaining_percent(row.get('weekly')) + if remaining is None or weekly is None: + return None + if not -30 <= freshness(row, now) <= 120: + return None + resets = [value for value in ( + reset_seconds(row.get('fiveHour'), now), + reset_seconds(row.get('weekly'), now), + ) if value is not None] + return min(remaining, weekly), (min(resets) if resets else math.inf) + return model_usable(row, now) if allow_model else None + + +def select_dashboard_profile(profiles, current, config, now=None): + mapping = config.get('accountIds') + if not isinstance(mapping, dict) or any( + not isinstance(mapping.get(alias), str) or not mapping[alias].strip() + for alias in profiles + ): + raise RuntimeError('每个本地 agy 别名都必须配置 dashboard 账号 ID。') + allow_model = config.get('modelFallback', True) is not False + account_ids = list(dict.fromkeys(mapping[alias] for alias in profiles)) + response = query_dashboard(config, account_ids) + # The dashboard sets a top-level ok only when an account has explicit + # windows. Model-level answers are per-account, so validate the mapping + # instead of rejecting an otherwise usable response. + if not isinstance(response, dict) or not isinstance(response.get('accounts'), dict): + raise RuntimeError('dashboard 未返回成功的额度查询。') + now = now or datetime.now(timezone.utc) + now = now.astimezone(timezone.utc) + + candidates = {} + for alias in profiles: + identity_hash = config.get('identityHashes', {}).get(alias) + if identity_hash: + subject = profiles[alias].get('info', {}).get('sub', '') + if not subject or hashlib.sha256(subject.encode()).hexdigest() != identity_hash: + log(f'PROFILE-NOT-READY target={alias} reason=identity-mismatch') + continue + row = response['accounts'].get(mapping[alias]) + if not isinstance(row, dict): + log(f'QUOTA-UNAVAILABLE target={alias}') + continue + if row.get('ok') is not True and not allow_model: + log(f'QUOTA-UNAVAILABLE target={alias}') + continue + scored = account_usable(row, now, allow_model) + if scored is None: + log(f'QUOTA-UNAVAILABLE target={alias}') + continue + usable, next_reset = scored + candidates[alias] = (usable, next_reset) + five_hour = remaining_percent(row.get('fiveHour')) if row.get('ok') is True else None + weekly = remaining_percent(row.get('weekly')) if row.get('ok') is True else None + model = fallback_percent(row) + log(f'QUOTA target={alias} usable={usable:.6f}% 5h={format_seconds(five_hour)} ' + f'weekly={format_seconds(weekly)} model={format_seconds(model)} ' + f'reset_seconds={format_seconds(next_reset)}') + + if not candidates: + raise RuntimeError('dashboard 未返回有效且新鲜的 Gemini 5 小时和周额度,也没有可用的模型级额度。') + LAST_SELECTION['usable'] = len(candidates) + maximum = max(score for score, _ in candidates.values()) + shortest_reset = min(reset for score, reset in candidates.values() if score == maximum) + tied = [alias for alias, value in candidates.items() if value == (maximum, shortest_reset)] + target = current if current in tied else tied[0] + return target, maximum + + +def probe_models(): + proc = subprocess.Popen( + ['/bin/zsh', '-ic', + 'whence proxy_on >/dev/null 2>&1 || exit 127; eval proxy_on || exit $?; agy models'], + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True, start_new_session=True, + env={**os.environ, 'AGY_SWITCH_MANAGED_SESSION': '1'}, + ) + try: + output, _ = proc.communicate(timeout=120) + return proc.returncode, output + except subprocess.TimeoutExpired: + return 124, 'proxy_on + agy models 超过 120 秒未返回。' + finally: + if proc.poll() is None: + os.killpg(proc.pid, signal.SIGTERM) + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + os.killpg(proc.pid, signal.SIGKILL) + proc.wait() + + +def run_locked(manager, now=None): + recovery = manager['SWITCH_DIR'] / 'scheduled-hi-recovery.json' + if recovery.exists(): + saved = manager['read_token_data'](recovery) + if not saved or not saved.get('original'): + raise RuntimeError('保活任务恢复文件无效,拒绝覆盖登录状态。') + manager['install_live_token'](saved['original']) + recovery.unlink() + log('RECOVERED 上次中断的保活任务已恢复原凭据。') + + manager['auto_init']() + manager['sync_live_token']() + profiles = manager['list_profiles']() + if not profiles: + raise RuntimeError('没有可轮换的 agy 账号。') + hour = (now or datetime.now()).hour + config = json.loads(CONFIG_PATH.read_text()) + if not isinstance(config, dict): + raise RuntimeError('额度轮换配置必须是对象。') + mapping = config.get('accountIds', {}) + if not isinstance(mapping, dict) or any(not isinstance(mapping.get(a), str) or not mapping[a].strip() for a in profiles): + raise RuntimeError('每个本地 agy 别名都必须配置 dashboard 账号 ID。') + identity_hashes = config.get('identityHashes', {}) + if not isinstance(identity_hashes, dict) or any( + not isinstance(value, str) or not re.fullmatch(r'[a-f0-9]{64}', value) + for value in identity_hashes.values() + ): + raise ConfigurationError('identityHashes 必须包含 Google OAuth subject 的 SHA-256。') + source = 'dashboard' + LAST_SELECTION.clear() + try: + target, score = select_dashboard_profile( + profiles, manager['get_config']().get('desired_active') or manager['get_config']().get('active'), config, now, + ) + log(f'SELECT source=dashboard target={target} score={score:.6f}% ' + f'usable_accounts={LAST_SELECTION.get("usable", 0)} model_only={LAST_SELECTION.get("modelOnly", 0)}') + # Fewer than two usable accounts means rotation can no longer trade off + # quota between accounts; warn after repeated runs. + alert_sequence(LAST_SELECTION.get('usable', 0) < 2, config, now, LAST_SELECTION.get('usable', 0)) + except ConfigurationError: + raise + except (OSError, ValueError, RuntimeError, TimeoutError) as exc: + source = 'hourly-fallback' + target, index = target_profile(profiles, hour) + # Do not log raw HTTP error bodies, URLs or Google credential text. + log(f'FALLBACK reason={type(exc).__name__} H={hour} index={index} target={target}') + alert_sequence(True, config, now) + identity_hash = identity_hashes.get(target) + subject = profiles[target].get('info', {}).get('sub', '') + if identity_hash and (not subject or hashlib.sha256(subject.encode()).hexdigest() != identity_hash): + raise RuntimeError(f'目标账号 {target} 正在等待指定 Google 身份的登录信息更新。') + expected = manager['read_token_data'](profiles[target]['token_path']) + log(f'BEGIN H={hour} n={len(profiles)} source={source} target={target}') + active = manager['get_config']() + unchanged = active.get('active') == target and active.get('desired_active') == target + if unchanged: + try: + manager['verify_live_token'](expected) + except RuntimeError: + unchanged = False + if not unchanged: + # agy-switch's interactive output includes personal email addresses. + with redirect_stdout(io.StringIO()): + manager['cmd_switch'](target) + manager['verify_live_token'](expected) + if manager['get_config']().get('active') != target: + raise RuntimeError('活动账号配置与轮换目标不一致。') + log(f'SWITCH-VERIFIED target={target} keychain=true token_file=true unchanged={str(unchanged).lower()}') + + code, output = probe_models() + if code != 0 or not re.search(r'gemini-[\w.-]+', output): + log(f'PROBE-FAIL target={target} exit={code}') + for line in output.splitlines()[-10:]: + log(redact(line)) + return 1 + manager['verify_live_token'](expected) + if manager['get_config']().get('active') != target: + raise RuntimeError('agy 探测期间活动账号被其他进程改变。') + manager['sync_live_token']() + log(f'PROBE-OK target={target} agy_models=true') + log(f'OK H={hour} n={len(profiles)} source={source} target={target} verified=true') + return 0 + + +def run_hourly(manager, now=None): + """Keep the existing entry point and shared lock used by local automation.""" + try: + with manager['account_lock'](blocking=False): + return run_locked(manager, now) + except BlockingIOError: + log('SKIP 其他账号任务正在持锁,下个 10 分钟周期重试。') + return 0 + + +def stop(signum, frame): + raise InterruptedError(f'signal={signum}') + + +if __name__ == '__main__': + for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP): + signal.signal(sig, stop) + try: + sys.exit(run_hourly(runpy.run_path(str(Path.home() / 'bin/agy-switch')))) + except InterruptedError: + log('FAIL 轮换任务被中断。') + sys.exit(130) + except Exception as exc: + detail = str(exc) if isinstance(exc, RuntimeError) else type(exc).__name__ + log(f'FAIL {redact(detail)}') + sys.exit(1) diff --git a/server.py b/server.py index 2707415..a2fc08c 100644 --- a/server.py +++ b/server.py @@ -1,17 +1,22 @@ import hashlib import hmac import json +import math import os import re import shlex import uuid import base64 +import threading +import time +from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime, timezone +from http.client import HTTPException from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path -from urllib.parse import quote, urlencode, urlparse +from urllib.parse import parse_qs, quote, quote_plus, unquote_plus, urlencode, urlparse from urllib.error import HTTPError, URLError -from urllib.request import ProxyHandler, Request, build_opener, urlopen +from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener, urlopen def now_iso(): @@ -113,13 +118,20 @@ def execute_volcengine_openapi(credentials, action): GOOGLE_OAUTH_URL = "https://oauth2.googleapis.com/token" -GOOGLE_UA = "antigravity-tools/1.1.5" +# Google gates the current model catalog and quota buckets on the CLI build. +DEFAULT_GOOGLE_UA = ( + "antigravity-cli/1.4.6 (aidev_client; os_type=linux; arch=amd64; " + "cl=1000353293; auth_method=consumer)" +) +GOOGLE_UA = os.environ.get("GOOGLE_AI_USER_AGENT", DEFAULT_GOOGLE_UA).strip() or DEFAULT_GOOGLE_UA +# Production first: the daily environment can omit the Gemini quota group. GOOGLE_BASES = [ - "https://daily-cloudcode-pa.googleapis.com", "https://cloudcode-pa.googleapis.com", + "https://daily-cloudcode-pa.googleapis.com", "https://daily-cloudcode-pa.sandbox.googleapis.com", ] GOOGLE_QUOTA_ENDPOINTS = [ + "fetchAvailableModels", "retrieveUserQuotaSummary", "retrieveUserQuota", "loadCodeAssist", @@ -162,7 +174,127 @@ def _load_google_clients(): GOOGLE_CLIENTS = _load_google_clients() -CREDENTIAL_SOURCES = set(VOLC_ACTIONS) | {"googleAi"} +CREDENTIAL_SOURCES = set(VOLC_ACTIONS) | {"googleAi", "claude"} + +CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage" +CLAUDE_WINDOWS = ("five_hour", "seven_day", "seven_day_opus", "seven_day_sonnet", "seven_day_oauth_apps", "seven_day_cowork") + + +class _NoManagementRedirect(HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + + +def cliproxy_configured(): + return bool(os.environ.get("CLIPROXYAPI_BASE_URL", "").strip() + and os.environ.get("CLIPROXYAPI_MANAGEMENT_KEY", "").strip()) + + +def _cliproxy_management(path, payload=None): + """Use only the operator-configured management server; never expose its response on failure.""" + if not cliproxy_configured(): + raise ValueError("Claude requires CLIPROXYAPI_BASE_URL and CLIPROXYAPI_MANAGEMENT_KEY on the server") + base = os.environ["CLIPROXYAPI_BASE_URL"].strip().rstrip("/") + parsed = urlparse(base) + if (parsed.scheme not in {"http", "https"} or not parsed.hostname + or parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path): + raise ValueError("CLIPROXYAPI_BASE_URL must be an HTTP(S) origin without credentials or a path") + data = None if payload is None else json.dumps(payload).encode("utf-8") + request = Request(base + "/v0/management/" + path, data=data, + headers={"Authorization": "Bearer " + os.environ["CLIPROXYAPI_MANAGEMENT_KEY"].strip(), + "Content-Type": "application/json"}, + method="GET" if payload is None else "POST") + opener = build_opener(ProxyHandler({}), _NoManagementRedirect()) + try: + with opener.open(request, timeout=35) as response: + if response.status != 200: + raise ValueError("CLIProxyAPI management returned an unsuccessful HTTP status") + raw = response.read(2097153) + if len(raw) > 2097152: + raise ValueError("CLIProxyAPI management response is too large") + value = json.loads(raw) + if not isinstance(value, dict): + raise ValueError("CLIProxyAPI management returned an invalid response") + return value + except HTTPError as error: + raise ValueError(f"CLIProxyAPI management request failed (HTTP {error.code})") from None + except (URLError, OSError, TimeoutError): + raise ValueError("CLIProxyAPI management server is unreachable or timed out") from None + except (json.JSONDecodeError, UnicodeDecodeError): + raise ValueError("CLIProxyAPI management returned invalid JSON") from None + + +def list_claude_oauth_accounts(): + files = _cliproxy_management("auth-files").get("files") + if not isinstance(files, list): + raise ValueError("CLIProxyAPI did not return an OAuth account list") + accounts = {} + for item in files: + if not isinstance(item, dict) or item.get("provider", item.get("type")) != "claude": + continue + if item.get("account_type") != "oauth": + continue + identity = item.get("id") or item.get("name") + if not isinstance(identity, str) or not identity or not item.get("auth_index"): + continue + # Resolve the current auth_index on every refresh; it can change after reauthentication. + reference = hashlib.sha256(("claude\0" + identity).encode("utf-8")).hexdigest() + accounts[reference] = {"authIndex": str(item["auth_index"]), + "label": str(item.get("label") or item.get("email") or "Claude OAuth"), + "disabled": bool(item.get("disabled"))} + return accounts + + +def _claude_usage_valid(payload): + if not isinstance(payload, dict) or payload.get("error") or payload.get("type") == "error": + return False + for name in CLAUDE_WINDOWS: + window = payload.get(name) + value = window.get("utilization") if isinstance(window, dict) else None + if isinstance(value, bool) or value is None or (isinstance(value, str) and not value.strip()): + continue + try: + if math.isfinite(float(value)) and float(value) >= 0: + return True + except (ValueError, TypeError): + continue + return False + + +def execute_claude_usage(definition, accounts=None): + """Query through CLIProxyAPI's token substitution; OAuth secrets never enter dashboard state.""" + try: + accounts = list_claude_oauth_accounts() if accounts is None else accounts + account = accounts.get(definition.get("claudeAccountId", "")) + if not account: + return 404, "", "Claude OAuth account is missing; reauthenticate in CLIProxyAPI and sync accounts" + if account["disabled"]: + return 403, "", "Claude OAuth account is disabled in CLIProxyAPI" + response = _cliproxy_management("api-call", { + "authIndex": account["authIndex"], "method": "GET", "url": CLAUDE_USAGE_URL, + "header": {"Authorization": "Bearer $TOKEN$", "anthropic-beta": "oauth-2025-04-20", + "User-Agent": "claude-code/2.1.0"}, + }) + status = response.get("status_code") + if type(status) is not int or not 100 <= status <= 599: + return 502, "", "CLIProxyAPI returned an invalid upstream status" + if status != 200: + message = ("Claude OAuth authentication failed; reauthenticate in CLIProxyAPI" if status in {401, 403} + else "Claude usage query failed") + return status, "", message + try: + body = response.get("body") + payload = json.loads(body) if isinstance(body, str) else body + except (ValueError, TypeError): + payload = None + if not _claude_usage_valid(payload): + return 502, "", "Claude returned no valid quota windows" + # Do not cache response headers, account metadata, spend details or unrelated fields. + filtered = {name: {key: payload[name][key] for key in ("utilization", "resets_at") if key in payload[name]} + for name in CLAUDE_WINDOWS if isinstance(payload.get(name), dict)} + return 200, json.dumps(filtered, ensure_ascii=False), "" + except ValueError as error: + return 502, "", str(error) def _google_opener(proxy): @@ -171,13 +303,22 @@ def _google_opener(proxy): return None -def execute_google_ai(credentials): +def execute_google_ai(credentials, timeout=35, deadline=None): refresh_token = credentials.get("refreshToken", "") proxy = credentials.get("proxy") or os.environ.get("GOOGLE_AI_PROXY", "") if not refresh_token: raise ValueError("missing google ai refresh token") access_token = None last_error = None + + def request_timeout(): + if deadline is None: + return timeout + remaining = deadline - time.monotonic() + if remaining <= 0: + raise TimeoutError("Google AI quota query timed out") + return min(timeout, remaining) + for client_id, client_secret in GOOGLE_CLIENTS: data = urlencode({ "client_id": client_id, @@ -188,7 +329,8 @@ def execute_google_ai(credentials): request = Request(GOOGLE_OAUTH_URL, data=data, method="POST") try: opener = _google_opener(proxy) - context = opener.open(request, timeout=35) if opener else urlopen(request, timeout=35) + wait = request_timeout() + context = opener.open(request, timeout=wait) if opener else urlopen(request, timeout=wait) with context as response: access_token = json.loads(response.read().decode("utf-8", errors="replace")).get("access_token") if access_token: @@ -197,10 +339,18 @@ def execute_google_ai(credentials): last_error = f"HTTP {error.code}: {error.read().decode('utf-8', errors='replace')[:120]}" except URLError as error: last_error = str(error.reason) + except (ConnectionError, HTTPException) as error: + # A proxy or Google host dropping the connection should not skip the next client. + last_error = str(error) or type(error).__name__ if not access_token: return 1, "", f"oauth refresh failed: {last_error}" body = b"{}" last_error = None + fallback = None + catalog = None + summary_fallback = None + agron_summary = None + quota_groups = [] for endpoint in GOOGLE_QUOTA_ENDPOINTS: for base in GOOGLE_BASES: @@ -212,19 +362,281 @@ def execute_google_ai(credentials): ) try: opener = _google_opener(proxy) - context = opener.open(request, timeout=35) if opener else urlopen(request, timeout=35) + wait = request_timeout() + context = opener.open(request, timeout=wait) if opener else urlopen(request, timeout=wait) with context as response: response_body = response.read().decode("utf-8", errors="replace") - if "remainingFraction" in response_body or "remaining_fraction" in response_body: - return response.status, response_body, "" - last_error = f"HTTP {response.status} no quota data @ {base}/{endpoint}" + try: + payload = json.loads(response_body) + except ValueError: + payload = None + value = _google_quota_value(payload) + if endpoint == "fetchAvailableModels": + if isinstance(value.get("models"), dict): + candidate = google_ai_model_quota(value) + has_agron = bool(_google_agron_models(value)) + if (catalog is None or has_agron or (candidate and ( + fallback is None or _google_model_priority(candidate["modelId"], candidate.get("planLabel") == "Agron") < fallback[0]))): + catalog = value + if has_agron: + fallback = None + combined = dict(value) + if catalog is not None: + combined["models"] = catalog["models"] + quota_groups = _google_merge_quota_groups(quota_groups, value.get("groups")) + if quota_groups: + combined["groups"] = quota_groups + packed = (response.status, json.dumps(combined), "") + supports_agron = bool(_google_agron_models(combined)) + gemini_periods = _google_group_periods(combined) + complete_gemini = {"5h", "weekly"}.issubset(gemini_periods) + if supports_agron: + periods = _google_group_periods(combined, agron=True) + if "weekly" in periods and complete_gemini: + return packed + if periods: + agron_summary = packed + elif gemini_periods: + summary_fallback = packed + if endpoint != "fetchAvailableModels" and complete_gemini: + return packed + model = google_ai_model_quota(combined) + if model: + priority = _google_model_priority(model["modelId"], model.get("planLabel") == "Agron") + if fallback is None or priority <= fallback[0]: + fallback = (priority, packed) + if endpoint not in {"fetchAvailableModels", "retrieveUserQuotaSummary"} and fallback[0][0] <= 1: + return fallback[1] + if endpoint == "fetchAvailableModels" and supports_agron: + break + last_error = f"HTTP {response.status} no preferred Google AI quota @ {base}/{endpoint}" except HTTPError as error: last_error = f"HTTP {error.code} {error.reason} @ {base}/{endpoint}" + error.close() except URLError as error: last_error = f"{error.reason} @ {base}/{endpoint}" + except (ConnectionError, HTTPException) as error: + # One dropped connection must not abort the remaining hosts and endpoints. + last_error = f"{error or type(error).__name__} @ {base}/{endpoint}" + except TimeoutError: + if agron_summary: + return agron_summary + if summary_fallback and not _google_agron_models(catalog): + return summary_fallback + if fallback: + return fallback[1] + raise + if endpoint == "retrieveUserQuotaSummary": + if agron_summary: + return agron_summary + if not _google_agron_models(catalog) and summary_fallback: + return summary_fallback + if fallback and fallback[0][0] <= 1: + return fallback[1] + if fallback: + return fallback[1] return 1, "", f"quota endpoints failed: {last_error}" +def _google_quota_value(payload): + if not isinstance(payload, dict) or payload.get("error") or payload.get("success") is False: + return {} + value = payload.get("data") if isinstance(payload.get("data"), dict) else payload + return {} if value.get("error") or value.get("success") is False else value + + +def _google_merge_quota_groups(current, incoming): + """Keep real windows returned by different hosts, without inflating quota.""" + groups = {} + for group in current + (incoming if isinstance(incoming, list) else []): + if not isinstance(group, dict) or not isinstance(group.get("displayName"), str): + continue + key = re.sub(r"[^a-z0-9]", "", group["displayName"].lower()) + previous = groups.get(key, {}) + buckets = {} + for bucket in previous.get("buckets", []) + (group.get("buckets") if isinstance(group.get("buckets"), list) else []): + if not isinstance(bucket, dict): + continue + bucket_key = str(bucket.get("bucketId") or bucket.get("window", "")).lower() + old_fraction = _google_quota_fraction(buckets.get(bucket_key, {})) + fraction = _google_quota_fraction(bucket) + if bucket_key not in buckets or (fraction is not None and (old_fraction is None or fraction <= old_fraction)): + buckets[bucket_key] = bucket + groups[key] = {**previous, **group, "buckets": list(buckets.values())} + return list(groups.values()) + + +def _google_quota_fraction(bucket): + fraction = bucket.get("remainingFraction") + if fraction is None: + fraction = bucket.get("remaining_fraction") + if isinstance(fraction, bool) or fraction is None or not isinstance(fraction, (int, float, str)): + return None + try: + fraction = float(fraction) + except (TypeError, ValueError, OverflowError): + return None + return fraction if math.isfinite(fraction) and 0 <= fraction <= 1 else None + + +def _google_agron_models(payload): + models = _google_quota_value(payload).get("models") + if not isinstance(models, dict): + return {} + return {model_id: model for model_id, model in models.items() + if isinstance(model_id, str) and re.fullmatch(r"[A-Za-z0-9._-]+", model_id) + and isinstance(model, dict) and model.get("disabled") is not True + and model.get("available") is not False and model.get("isInternal") is not True + and any(marker in " ".join(str(v) for v in (model_id, model.get("displayName", ""), model.get("model", ""))).lower() + for marker in ("argon", "agron"))} + + +def _google_group_periods(payload, agron=False): + value = _google_quota_value(payload) + groups = value.get("groups") + if not isinstance(groups, list): + return {} + groups = [group for group in groups if isinstance(group, dict)] + if agron: + groups = [g for g in groups if any(m in str(g.get("displayName", "")).lower() for m in ("argon", "agron"))] + else: + groups = [g for g in groups if not any(m in str(g.get("displayName", "")).lower() for m in ("argon", "agron"))] + preferred = ("gemini4argon", "gemini4agron") if agron else ("geminimodels",) + group = next((g for name in preferred for g in groups + if re.sub(r"[^a-z0-9]", "", str(g.get("displayName", "")).lower()) == name), None) + if group is None: + group = next((g for g in groups if agron or "gemini" in str(g.get("displayName", "")).lower()), {}) + buckets = group.get("buckets") + if not isinstance(buckets, list): + return {} + periods = {} + for bucket in buckets: + if not isinstance(bucket, dict): + continue + name = str(bucket.get("window", "")).lower() + if name not in {"5h", "weekly"}: + continue + fraction = _google_quota_fraction(bucket) + if fraction is None: + continue + # A duplicate bucket must not inflate the account's usable quota. + if name not in periods or fraction * 100 < periods[name]["remainingPercent"]: + reset_at = bucket.get("resetTime") or bucket.get("reset_at") + periods[name] = {"remainingPercent": fraction * 100, + "resetAt": reset_at if isinstance(reset_at, str) else None} + return periods + + +def _google_model_priority(model_id, agron=False): + if agron: + if model_id.lower() == "gemini-4-argon": + return (-4, model_id) + if model_id.lower().startswith("gemini-4-argon-"): + return (-3, model_id) + return (-2 if model_id.lower() == "gemini-4-agron" else -1, model_id) + version = re.match(r"^gemini-(\d+)(?:\.(\d+))?(?:\.(\d+))?", model_id) + numbers = tuple(-int(part or 0) for part in version.groups()) if version else (0, 0, 0) + variant = 1 if model_id.endswith("-tiered") else 2 if re.search(r"-(high|medium|low)$", model_id) else 0 + return (0 if version else 1, *numbers, variant, model_id) + + +def google_ai_model_quota(payload): + """Choose a real Gemini model quota without assigning an unknown period.""" + value = _google_quota_value(payload) + agron_models = _google_agron_models(payload) + buckets = value.get("buckets") + candidates = [(b.get("modelId") if b.get("modelId") is not None else b.get("model_id"), b) + for b in buckets if isinstance(b, dict)] if isinstance(buckets, list) else [] + models = value.get("models") + if isinstance(models, dict): + candidates.extend((model_id, model.get("quotaInfo") if model.get("quotaInfo") is not None else model.get("quota_info")) + for model_id, model in models.items() if isinstance(model, dict)) + quotas = [] + for model_id, bucket in candidates: + if not isinstance(model_id, str) or not isinstance(bucket, dict): + continue + metadata = models.get(model_id) if isinstance(models, dict) else None + if isinstance(metadata, dict) and (metadata.get("disabled") is True + or metadata.get("available") is False or metadata.get("isInternal") is True): + continue + if agron_models: + if model_id not in agron_models: + continue + elif not re.fullmatch(r"gemini-[a-z0-9._-]+", model_id) or any(m in model_id for m in ("argon", "agron")): + continue + fraction = _google_quota_fraction(bucket) + if fraction is None: + continue + reset_at = bucket.get("resetTime") or bucket.get("reset_at") + quotas.append({"modelId": model_id, "remainingPercent": fraction * 100, + "resetAt": reset_at if isinstance(reset_at, str) else None}) + if agron_models: + metadata = agron_models[model_id] + name = " ".join(str(v) for v in (model_id, metadata.get("displayName", ""), metadata.get("model", ""))).lower() + quotas[-1].update(planLabel="Agron", modelName="GEMINI 4 ARGON" if "argon" in name else "GEMINI 4 AGRON") + return min(quotas, key=lambda q: (_google_model_priority(q["modelId"], bool(agron_models)), q["remainingPercent"])) if quotas else None + + +def google_ai_quota_periods(payload): + """Extract explicit Gemini windows for rotation; model quotas have no period.""" + periods = _google_group_periods(payload) + if "5h" not in periods: + raise ValueError("Google AI did not return a valid Gemini 5-hour quota") + return {"fiveHour": periods["5h"], "weekly": periods.get("weekly")} + + +def query_agy_quotas(accounts, credentials, account_ids): + """Query only the requested Google accounts; never change persisted state.""" + def query(account_id): + definition = accounts.get(account_id, {}) + result = {"ok": False, "status": None, "updatedAt": None, + "fiveHour": None, "weekly": None, "fallback": None} + if not isinstance(definition, dict) or definition.get("source") != "googleAi": + result["error"] = "account is not a configured Google AI account" + return result + refresh_token = definition.get("refreshToken") or credentials.get("googleAi", {}).get("refreshToken", "") + if not refresh_token: + result["error"] = "Google AI refresh token is not configured" + return result + try: + code, body, _ = execute_google_ai( + {"refreshToken": refresh_token, + "proxy": definition.get("proxy") or os.environ.get("GOOGLE_AI_PROXY", "")}, + timeout=10, deadline=time.monotonic() + 45, + ) + result["status"] = code + if not is_success_status(code): + result["error"] = "Google AI quota query failed" + return result + payload = json.loads(body) + try: + result.update(google_ai_quota_periods(payload)) + except ValueError: + # Accounts without the Gemini Models group only expose a per-model + # quota. That has no explicit 5-hour/weekly window, so it stays a + # non-successful query for this API, but the value is reported for + # callers that can use a model-level fallback. + model = google_ai_model_quota(payload) + if model is None: + raise + result["fallback"] = { + "modelId": model["modelId"], + "remainingPercent": model["remainingPercent"], + "resetAt": model.get("resetAt"), + } + result["error"] = "Google AI returned no explicit 5-hour window; only a per-model quota is available" + else: + result.update(ok=True, updatedAt=now_iso()) + except (ValueError, OSError, TimeoutError, TypeError): + # Provider responses and exception text may contain credentials. + result["error"] = "Google AI quota query failed or returned invalid 5-hour data" + return result + + with ThreadPoolExecutor(max_workers=min(5, len(account_ids))) as pool: + results = dict(zip(account_ids, pool.map(query, account_ids))) + return {"ok": any(result["ok"] for result in results.values()), "accounts": results} + + def mask_secret(secret): if not secret: return "" @@ -254,6 +666,196 @@ def save_order(path, order): save_snapshot(path, {"order": list(order)}) +def load_hidden(path): + value = load_snapshot(path) + if not isinstance(value, dict): + return [] + hidden = value.get("hidden") + return [str(item) for item in hidden if isinstance(item, (str, int))] if isinstance(hidden, list) else [] + + +def save_hidden(path, hidden): + save_snapshot(path, {"hidden": list(hidden)}) + + +# Read-only quota summary for home dashboards (e.g. Home Assistant). It mirrors the +# card headline logic in index.html (pct, quotaCandidates, longestPeriodInfo, status) +# and never includes curl text, tokens or raw provider responses. +SOURCE_NAMES = { + "codexUsage": "Codex", "codexCredits": "Codex", "codexNewApi": "Codex", "codexNewApiCredits": "Codex", + "minimax": "MiniMax", "volcCoding": "火山方舟", "volcAgent": "火山方舟", "kimi": "Kimi", "claude": "Claude", + "longcat": "LongCat", "qianwen": "千问AI", "zhipuCoding": "智谱AI", "googleAi": "Google AI", +} +PERIOD_LABELS = { + "5h": "5小时额度", "session": "当前窗口额度", "当前窗口": "当前窗口额度", "今日用量": "今日额度", "weekly": "周额度", + "7d": "7天额度", "1w": "周额度", "周额度": "周额度", "本周用量": "本周额度", "monthly": "月额度", "月额度": "月额度", + "本月用量": "本月额度", "time": "MCP月额度", "订阅": "订阅额度", "订阅额度": "订阅额度", "免费额度": "免费额度", + "付费额度": "付费额度", "当前额度": "当前额度", "其他额度": "其他额度", +} + + +def _finite(value): + if isinstance(value, bool) or value is None or value == "": + return None + try: + number = float(value) + except (TypeError, ValueError): + return None + return number if math.isfinite(number) else None + + +def _clamp_percent(value): + return max(0.0, min(100.0, value)) + + +def period_rank(name): + key = str(name or "").lower() + if key in ("5h", "session", "当前窗口", "今日用量"): + return 1 + if key in ("weekly", "7d", "1w", "周额度", "本周用量") or key.endswith("周额度"): + return 2 + if key in ("monthly", "月额度", "本月用量"): + return 3 + if key in ("订阅", "订阅额度", "免费额度", "付费额度", "当前额度", "其他额度"): + return 4 + return 0 + + +def period_display_name(name): + key = str(name if name is not None else "").strip() + return PERIOD_LABELS.get(key) or PERIOD_LABELS.get(key.lower()) or key + + +def quota_candidates(item): + candidates = [] + for period in item.get("periods") or []: + used = _finite(period.get("usedPercent")) + if used is not None and period.get("available") is not False: + candidates.append({"rank": period_rank(period.get("name")), "name": period.get("name"), "used": _clamp_percent(used), + "resetAt": period.get("resetAt") or period.get("expireTime") or None}) + for window in item.get("windows") or []: + if window.get("available") is False: + continue + interval = window.get("interval") + if isinstance(interval, dict) and _finite(interval.get("usedPercent")) is not None: + candidates.append({"rank": 1, "name": window.get("name") or "5h", "used": _clamp_percent(_finite(interval["usedPercent"])), + "resetAt": interval.get("resetAt") or None}) + weekly = window.get("weekly") + if isinstance(weekly, dict) and weekly.get("available") is not False and _finite(weekly.get("usedPercent")) is not None: + candidates.append({"rank": 2, "name": "weekly", "used": _clamp_percent(_finite(weekly["usedPercent"])), + "resetAt": weekly.get("resetAt") or None}) + if _finite(window.get("usedPercent")) is not None: + candidates.append({"rank": period_rank(window.get("name")), "name": window.get("name"), + "used": _clamp_percent(_finite(window["usedPercent"])), "resetAt": window.get("resetAt") or None}) + return candidates + + +def longest_period_info(item): + candidates = quota_candidates(item) + if not candidates: + return None + if item.get("planLabel") == "Agron": + primary = next((c for c in candidates if c["name"] == item.get("primaryPeriodName")), None) + if primary: + return {"used": primary["used"], "label": period_display_name(primary["name"]), "resetAt": primary["resetAt"]} + rank = max(c["rank"] for c in candidates) + selected = [c for c in candidates if c["rank"] == rank] + used = max(c["used"] for c in selected) + source = next((c for c in selected if c["used"] == used), selected[0]) + return {"used": used, "label": period_display_name(source["name"]), "resetAt": source["resetAt"]} + + +def quota_pct(item): + if item.get("planLabel") == "Agron" and _finite(item.get("used")) is not None: + return _finite(item["used"]) + values = [v for v in (_finite(p.get("usedPercent")) for p in (item.get("periods") or [])) if v is not None] + values += [v for v in (_finite(w.get("usedPercent")) for w in (item.get("windows") or [])) if v is not None] + if _finite(item.get("usedPercent")) is not None: + values.append(_finite(item["usedPercent"])) + if values: + return max(values) + used, limit = _finite(item.get("used")), _finite(item.get("limit")) + if used is not None and limit is not None and limit > 0: + return used / limit * 100 + return 0.0 + + +def quota_status(item): + if not item: + return "未加载", "warn" + if item.get("limit") == 0: + return "已过期", "bad" + display = round(quota_pct(item) * 10) / 10 + if display >= 100: + return "无法使用", "bad" + if display >= 90: + return "接近上限", "warn" + return "已同步", "ok" + + +def _iso_time(value): + number = _finite(value) + if number is not None: + return datetime.fromtimestamp(number / 1000, timezone.utc).isoformat() + if isinstance(value, str) and value: + try: + return datetime.fromisoformat(value.replace("Z", "+00:00")).isoformat() + except ValueError: + return None + return None + + +def build_summary(accounts, snapshot, results, order, hidden): + state = {key: value for key, value in snapshot.items() if isinstance(value, dict)} if isinstance(snapshot, dict) else {} + credits_id = next((aid for aid, acc in accounts.items() if acc.get("source") == "codexNewApiCredits"), None) + new_api_id = next((aid for aid, acc in accounts.items() if acc.get("source") == "codexNewApi"), None) + if credits_id and new_api_id and credits_id in state: + credits, target = state[credits_id], state.get(new_api_id) or {"windows": []} + state[new_api_id] = {**target, "resetCards": credits.get("resetCards", target.get("resetCards")), + "updatedAt": target.get("updatedAt") or credits.get("updatedAt")} + ordered = [aid for aid in order if aid in accounts] + [aid for aid in accounts if aid not in order] + hidden_ids = set(hidden) + items = [] + for aid in dict.fromkeys(ordered): + acc = accounts[aid] + source = acc.get("source", "") + if source == "codexNewApiCredits" or aid in hidden_ids: + continue + label = str(acc.get("label") or "") + if source == "claude": + label = label[:5] + provider = SOURCE_NAMES.get(source, source) + data = state.get(aid) + info = longest_period_info(data) if data else None + text, level = quota_status(data) + result = results.get(aid) if isinstance(results.get(aid), dict) else {} + items.append({ + "id": aid, + "name": f"{provider} · {label}" if label else provider, + "provider": provider, + "source": source, + "usedPercent": round(info["used"], 2) if info else None, + "remainingPercent": round(100 - info["used"], 2) if info else None, + "period": info["label"] if info else None, + "resetAt": _iso_time(info["resetAt"]) if info else None, + "resetCards": data.get("resetCards") if data else None, + "status": text, + "level": level, + "refreshOk": result.get("ok") if "ok" in result else None, + "updatedAt": _iso_time((data or {}).get("updatedAt")), + }) + levels = [item["level"] for item in items] + times = [item["updatedAt"] for item in items if item["updatedAt"]] + return { + "total": len(items), + "ok": levels.count("ok"), + "warn": levels.count("warn"), + "bad": levels.count("bad"), + "updatedAt": max(times) if times else None, + "accounts": items, + } + + def is_success_status(status): return status == 200 @@ -287,6 +889,19 @@ def provider_response_ok(source, code, body): """Treat HTTP 200 business-error responses as failed provider calls.""" if not is_success_status(code): return False + if source == "claude": + try: + return _claude_usage_valid(json.loads(body)) + except (TypeError, ValueError): + return False + if source == "googleAi": + try: + payload = json.loads(body) + if _google_agron_models(payload): + return bool(_google_group_periods(payload, agron=True) or google_ai_model_quota(payload)) + return bool(_google_group_periods(payload) or google_ai_model_quota(payload)) + except (TypeError, ValueError): + return False if source not in {NEWAPI_CODEX_USAGE_PATH, NEWAPI_CODEX_CREDITS_PATH, "qianwen", "zhipuCoding", "minimax"}: return True try: @@ -308,12 +923,18 @@ def provider_response_ok(source, code, body): def provider_response_error(source, body): - if source not in {"qianwen", "zhipuCoding", "minimax"}: + if source == "googleAi": + return "Google AI did not return usable Gemini quota data" + if source not in {NEWAPI_CODEX_USAGE_PATH, NEWAPI_CODEX_CREDITS_PATH, "qianwen", "zhipuCoding", "minimax"}: return "" try: payload = json.loads(body) except (TypeError, ValueError): return "" + if not isinstance(payload, dict): + return "" + if source in {NEWAPI_CODEX_USAGE_PATH, NEWAPI_CODEX_CREDITS_PATH}: + return str(payload.get("message") or "").strip()[:200] if source == "zhipuCoding": return str(payload.get("message") or payload.get("msg") or payload.get("error") or "").strip() if source == "minimax": @@ -327,9 +948,11 @@ def provider_response_error(source, body): return str(data.get("errorMsg") or data.get("errorCode") or "").strip() +MINIMAX_HOSTS = {"www.minimaxi.com", "www.minimax.cn"} + ALLOWED_HOSTS = { "chatgpt.com", - "www.minimaxi.com", + *MINIMAX_HOSTS, "console.volcengine.com", "www.kimi.com", "auth.kimi.com", @@ -440,7 +1063,7 @@ def infer_source(command): return "qianwen" if parsed.hostname == "www.bigmodel.cn" and path.rstrip("/") == "/api/monitor/usage/quota/limit": return "zhipuCoding" - if parsed.hostname == "www.minimaxi.com": + if parsed.hostname in MINIMAX_HOSTS: return "minimax" if parsed.hostname == "console.volcengine.com" and path.endswith("GetCodingPlanUsage"): return "volcCoding" @@ -744,7 +1367,7 @@ def refresh_kimi_access_token(definition): return status, updated, "" -def merge_verification_curl(existing_curl, verification_curl, ignored_headers, required_prefixes, source_name): +def merge_verification_curl(existing_curl, verification_curl, ignored_headers, required_prefixes, source_name, equivalent_hosts=()): """Merge verification headers from a new cURL into an existing one. Args: @@ -753,6 +1376,7 @@ def merge_verification_curl(existing_curl, verification_curl, ignored_headers, r ignored_headers: Set of header names to skip (e.g. connection, content-length). required_prefixes: Tuple of header name prefixes that must be present (e.g. ("authorization", "cookie", "x-msh-")). source_name: Human-readable source name for error messages. + equivalent_hosts: Provider aliases accepted for the same endpoint; the saved URL stays unchanged. """ existing_url, existing_args = parse_curl(existing_curl) verification_url, verification_args = parse_curl(verification_curl) @@ -760,9 +1384,13 @@ def merge_verification_curl(existing_curl, verification_curl, ignored_headers, r raise ValueError(f"both requests must target the same {source_name} endpoint") existing_endpoint = urlparse(existing_url) verification_endpoint = urlparse(verification_url) - if (existing_endpoint.scheme, existing_endpoint.hostname, existing_endpoint.port, existing_endpoint.path) != ( + existing_host = existing_endpoint.hostname + verification_host = verification_endpoint.hostname + if existing_host in equivalent_hosts and verification_host in equivalent_hosts: + verification_host = existing_host + if (existing_endpoint.scheme, existing_host, existing_endpoint.port, existing_endpoint.path) != ( verification_endpoint.scheme, - verification_endpoint.hostname, + verification_host, verification_endpoint.port, verification_endpoint.path, ): @@ -839,9 +1467,90 @@ def merge_minimax_verification_curl(existing_curl, verification_curl): {"connection", "content-length", "host"}, ("cookie", "authorization", "x-"), "MiniMax", + equivalent_hosts=MINIMAX_HOSTS, ) +def merge_qianwen_verification_curl(existing_curl, verification_curl): + """Renew browser session headers and the form's sec_token, keeping query parameters and business data.""" + existing_url, existing_args = parse_curl(existing_curl) + verification_url, verification_args = parse_curl(verification_curl) + if any(infer_source(command) != "qianwen" for command in (existing_curl, verification_curl)): + raise ValueError("both requests must target the Qianwen usage endpoint") + existing_route = parse_qs(urlparse(existing_url).query, keep_blank_values=True) + verification_route = parse_qs(urlparse(verification_url).query, keep_blank_values=True) + for key in ("product", "action", "api"): + if (len(existing_route.get(key, [])) != 1 + or existing_route[key] != verification_route.get(key)): + raise ValueError("new Qianwen request must target the existing usage API") + if not existing_route["api"][0].endswith("/usage"): + raise ValueError("Qianwen verification updates require a usage API request") + verification_request, _ = build_http_request(verification_args) + if not verification_request.get_header("Cookie", "").strip(): + raise ValueError("new Qianwen request must include the complete login Cookie") + + def form_body(args): + bodies = [] + index = 1 + while index < len(args) - 1: + option = args[index] + if option in {"-G", "--get"}: + raise ValueError("Qianwen verification updates require a form POST request") + if option in {"-d", "--data", "--data-raw", "--data-binary"}: + bodies.append(args[index + 1]) + index += 2 if option in ALLOWED_OPTIONS_WITH_VALUE else 1 + if len(bodies) > 1: + raise ValueError("Qianwen request must contain a single form body") + return bodies[0] if bodies else "" + + existing_body = form_body(existing_args) + verification_body = form_body(verification_args) + existing_form = parse_qs(existing_body, keep_blank_values=True) + verification_form = parse_qs(verification_body, keep_blank_values=True) + tokens = verification_form.get("sec_token", []) + if "sec_token" in existing_form or tokens: + if len(tokens) != 1 or not tokens[0].strip(): + raise ValueError("new Qianwen request must include a fresh sec_token; copy the complete usage cURL") + existing_request, _ = build_http_request(existing_args) + for request in (existing_request, verification_request): + if (not request.data or request.get_method() != "POST" + or request.get_header("Content-type", "").split(";", 1)[0].strip().lower() != "application/x-www-form-urlencoded"): + raise ValueError("Qianwen sec_token updates require a URL-encoded form body") + if len(existing_form.get("sec_token", [])) > 1: + raise ValueError("saved Qianwen request contains duplicate sec_token fields") + + ignored_headers = {"connection", "content-length", "host", "content-type"} + merged = merge_verification_curl( + existing_curl, verification_curl, ignored_headers, ("cookie",), "Qianwen", + ) + _, merged_args = parse_curl(merged) + updated = [merged_args[0]] + index = 1 + while index < len(merged_args) - 1: + option = merged_args[index] + if option in {"-H", "--header"} and _normalize_curl_header_name(merged_args[index + 1]) in {"connection", "content-length", "host"}: + index += 2 + continue + if option in {"-d", "--data", "--data-raw", "--data-binary"} and tokens: + parts = existing_body.split("&") + parts = [part.split("=", 1)[0] + "=" + quote_plus(tokens[0]) + if unquote_plus(part.split("=", 1)[0]) == "sec_token" else part + for part in parts] + if "sec_token" not in existing_form: + parts.append("sec_token=" + quote_plus(tokens[0])) + updated.extend([option, "&".join(parts)]) + index += 2 + continue + if option in ALLOWED_OPTIONS_WITH_VALUE: + updated.extend([option, merged_args[index + 1]]) + index += 2 + continue + updated.append(option) + index += 1 + updated.append(existing_url) + return " ".join(shlex.quote(arg) for arg in updated) + + def load_requests(path): value = load_snapshot(path) if not isinstance(value, dict): @@ -934,12 +1643,81 @@ def execute_curl(command): return 1, "", str(error.reason) +REFRESH_WORKERS = 8 +REFRESH_STATE_LOCK = threading.Lock() + + +class ClaudeCatalog: + """Resolve the CLIProxyAPI Claude catalog at most once per refresh request.""" + + def __init__(self): + self._lock = threading.Lock() + self._loaded = False + self._catalog = None + self._error = "" + + def get(self): + with self._lock: + if not self._loaded: + try: + self._catalog = list_claude_oauth_accounts() + except ValueError as error: + self._error = str(error) + self._loaded = True + return self._catalog, self._error + + +def refresh_account(definition, credentials, claude_catalog): + """Query one saved account; return its result and any rotated definition to persist.""" + source = definition.get("source", "") + refreshed_definition = None + try: + if source in VOLC_ACTIONS: + ak = definition.get("ak") or credentials.get("volc", {}).get("accessKeyId", "") + sk = definition.get("sk") or credentials.get("volc", {}).get("secretAccessKey", "") + if ak and sk: + code, stdout, stderr = execute_volcengine_openapi({"accessKeyId": ak, "secretAccessKey": sk}, VOLC_ACTIONS[source]) + else: + code, stdout, stderr = execute_curl(definition.get("curl", "")) + elif source == "claude": + catalog, catalog_error = claude_catalog.get() + if catalog_error: + code, stdout, stderr = 502, "", catalog_error + else: + code, stdout, stderr = execute_claude_usage(definition, catalog) + elif source == "googleAi": + refresh_token = definition.get("refreshToken") or credentials.get("googleAi", {}).get("refreshToken", "") + proxy = definition.get("proxy") or os.environ.get("GOOGLE_AI_PROXY", "") + if refresh_token: + code, stdout, stderr = execute_google_ai({"refreshToken": refresh_token, "proxy": proxy}) + else: + code, stdout, stderr = execute_curl(definition.get("curl", "")) + elif source == "kimi" and definition.get("kimiRefreshToken"): + code, refreshed_definition, stderr = refresh_kimi_access_token(definition) + if refreshed_definition: + code, stdout, stderr = execute_curl(refreshed_definition.get("curl", "")) + else: + stdout = "" + if code == 200: + code = 502 + else: + code, stdout, stderr = execute_curl(definition.get("curl", "")) + provider_ok = provider_response_ok(source, code, stdout) + if not provider_ok and is_success_status(code): + stderr = stderr or provider_response_error(source, stdout) or "provider returned an unsuccessful business response" + updated_at = now_iso() if provider_ok else None + return {"ok": provider_ok, "status": code, "body": stdout, "error": stderr, "updatedAt": updated_at}, refreshed_definition + except (ValueError, OSError, TimeoutError) as error: + return {"ok": False, "status": None, "body": "", "error": str(error)}, refreshed_definition + + class DashboardHandler(SimpleHTTPRequestHandler): snapshot_path = Path(os.environ.get("SNAPSHOT_PATH", "/data/snapshot.json")) requests_path = Path(os.environ.get("REQUESTS_PATH", "/data/requests.json")) results_path = Path(os.environ.get("RESULTS_PATH", "/data/results.json")) credentials_path = Path(os.environ.get("CREDENTIALS_PATH", "/data/credentials.json")) order_path = Path(os.environ.get("ORDER_PATH", "/data/order.json")) + hidden_path = Path(os.environ.get("HIDDEN_PATH", "/data/hidden.json")) def do_GET(self): if self.path == "/api/snapshot": @@ -968,9 +1746,17 @@ def do_GET(self): if self.path == "/api/results": self.send_json(load_results(self.results_path)) return + if self.path == "/api/summary": + self.send_json(build_summary(load_requests(self.requests_path), load_snapshot(self.snapshot_path), + load_results(self.results_path), load_order(self.order_path), + load_hidden(self.hidden_path))) + return if self.path == "/api/order": self.send_json({"order": load_order(self.order_path)}) return + if self.path == "/api/hidden": + self.send_json({"hidden": load_hidden(self.hidden_path)}) + return if self.path == "/api/credentials": creds = load_credentials(self.credentials_path) masked = {} @@ -993,7 +1779,7 @@ def do_GET(self): super().do_GET() def do_POST(self): - if self.path not in {"/api/snapshot", "/api/requests", "/api/refresh", "/api/credentials", "/api/order"}: + if self.path not in {"/api/snapshot", "/api/requests", "/api/refresh", "/api/credentials", "/api/order", "/api/hidden", "/api/agy/quotas", "/api/claude/accounts"}: self.send_error(404) return try: @@ -1003,6 +1789,39 @@ def do_POST(self): payload = json.loads(self.rfile.read(length).decode("utf-8")) if not isinstance(payload, dict): raise ValueError("snapshot must be an object") + if self.path == "/api/claude/accounts": + oauth_accounts = list_claude_oauth_accounts() + requests = load_requests(self.requests_path) + existing = {item.get("claudeAccountId"): aid for aid, item in requests.items() + if item.get("source") == "claude"} + account_ids = [] + added = 0 + for reference, account in oauth_accounts.items(): + if account["disabled"]: + continue + account_id = existing.get(reference) + if not account_id: + account_id = f"acc_{uuid.uuid4().hex[:12]}" + requests[account_id] = {"source": "claude", "label": account["label"], "curl": "", + "claudeAccountId": reference, "updatedAt": now_iso()} + added += 1 + account_ids.append(account_id) + if added: + save_requests(self.requests_path, requests) + self.send_json({"ok": True, "accountIds": account_ids, "added": added}) + return + if self.path == "/api/agy/quotas": + account_ids = payload.get("accountIds") + if (not isinstance(account_ids, list) or not 1 <= len(account_ids) <= 20 + or any(not isinstance(aid, str) or not aid.strip() for aid in account_ids)): + raise ValueError("accountIds must contain 1 to 20 non-empty account IDs") + account_ids = list(dict.fromkeys(account_ids)) + # Avoid load_requests' legacy migration: this API is read-only. + accounts = load_snapshot(self.requests_path) + if not isinstance(accounts, dict): + accounts = {} + self.send_json(query_agy_quotas(accounts, load_credentials(self.credentials_path), account_ids)) + return if self.path == "/api/snapshot": save_snapshot(self.snapshot_path, payload) self.send_json({"ok": True}) @@ -1084,6 +1903,21 @@ def do_POST(self): save_requests(self.requests_path, requests) self.send_json({"ok": True, "id": account_id, "source": "minimax", "updatedAt": updated["updatedAt"]}) return + if "qianwenVerificationCurl" in payload: + if not account_id: + raise ValueError("id is required for Qianwen verification updates") + if existing.get("source") != "qianwen": + raise ValueError("account is not a Qianwen account") + verification_curl = str(payload.get("qianwenVerificationCurl", "")).strip() + if not verification_curl: + raise ValueError("qianwenVerificationCurl is required") + updated = dict(existing) + updated["curl"] = merge_qianwen_verification_curl(existing.get("curl", ""), verification_curl) + updated["updatedAt"] = now_iso() + requests[account_id] = updated + save_requests(self.requests_path, requests) + self.send_json({"ok": True, "id": account_id, "source": "qianwen", "updatedAt": updated["updatedAt"]}) + return if not curl and existing: curl = existing.get("curl", "") if curl: @@ -1092,6 +1926,8 @@ def do_POST(self): account_id = find_matching_newapi_account(curl, requests) or "" elif explicit_source in CREDENTIAL_SOURCES and not existing: source = explicit_source + if source == "claude": + raise ValueError("use /api/claude/accounts to sync Claude OAuth accounts") if source in VOLC_ACTIONS and not (ak and sk_input): raise ValueError("ak and sk are required for volcengine accounts") if source == "googleAi" and not refresh_token: @@ -1110,6 +1946,8 @@ def do_POST(self): if source == "googleAi": definition["refreshToken"] = refresh_token or existing.get("refreshToken", "") definition["proxy"] = proxy_input or existing.get("proxy", "") + if source == "claude": + definition["claudeAccountId"] = existing.get("claudeAccountId", "") if source == "kimi" and existing.get("source") == "kimi": definition["kimiRefreshToken"] = existing.get("kimiRefreshToken", "") definition["kimiRefreshHeaders"] = existing.get("kimiRefreshHeaders", {}) @@ -1137,57 +1975,41 @@ def do_POST(self): save_order(self.order_path, cleaned) self.send_json({"ok": True, "order": cleaned}) return - results = {} - cached_results = load_results(self.results_path) + if self.path == "/api/hidden": + hidden = payload.get("hidden") + if not isinstance(hidden, list): + raise ValueError("hidden must be an array") + cleaned = [] + for item in hidden: + value = str(item).strip() + if isinstance(item, (str, int)) and value and value not in cleaned: + cleaned.append(value) + save_hidden(self.hidden_path, cleaned) + self.send_json({"ok": True, "hidden": cleaned}) + return credentials = load_credentials(self.credentials_path) accounts = load_requests(self.requests_path) - requests_changed = False - for account_id, definition in accounts.items(): - source = definition.get("source", "") - if should_skip_source(source, accounts): - continue - try: - if source in VOLC_ACTIONS: - ak = definition.get("ak") or credentials.get("volc", {}).get("accessKeyId", "") - sk = definition.get("sk") or credentials.get("volc", {}).get("secretAccessKey", "") - if ak and sk: - code, stdout, stderr = execute_volcengine_openapi({"accessKeyId": ak, "secretAccessKey": sk}, VOLC_ACTIONS[source]) - else: - code, stdout, stderr = execute_curl(definition.get("curl", "")) - elif source == "googleAi": - refresh_token = definition.get("refreshToken") or credentials.get("googleAi", {}).get("refreshToken", "") - proxy = definition.get("proxy") or os.environ.get("GOOGLE_AI_PROXY", "") - if refresh_token: - code, stdout, stderr = execute_google_ai({"refreshToken": refresh_token, "proxy": proxy}) - else: - code, stdout, stderr = execute_curl(definition.get("curl", "")) - elif source == "kimi" and definition.get("kimiRefreshToken"): - code, refreshed_definition, stderr = refresh_kimi_access_token(definition) - if refreshed_definition: - accounts[account_id] = refreshed_definition - requests_changed = True - definition = refreshed_definition - code, stdout, curl_error = execute_curl(definition.get("curl", "")) - stderr = curl_error - else: - stdout = "" - if code == 200: - code = 502 - else: - code, stdout, stderr = execute_curl(definition.get("curl", "")) - provider_ok = provider_response_ok(source, code, stdout) - if not provider_ok and is_success_status(code): - stderr = stderr or provider_response_error(source, stdout) or "provider returned an unsuccessful business response" - updated_at = now_iso() if provider_ok else None - result = {"ok": provider_ok, "status": code, "body": stdout, "error": stderr, "updatedAt": updated_at} - results[account_id] = result - if provider_ok: - cached_results[account_id] = result - except (ValueError, OSError, TimeoutError) as error: - results[account_id] = {"ok": False, "status": None, "body": "", "error": str(error)} - if requests_changed: - save_requests(self.requests_path, accounts) - save_results(self.results_path, cached_results) + account_ids = payload.get("accountIds") + if "accountIds" in payload: + if (not isinstance(account_ids, list) or not 1 <= len(account_ids) <= 20 + or any(not isinstance(aid, str) or aid not in accounts for aid in account_ids)): + raise ValueError("accountIds must contain 1 to 20 saved account IDs") + targets = [(account_id, definition) for account_id, definition in accounts.items() + if (account_ids is None or account_id in account_ids) + and not should_skip_source(definition.get("source", ""), accounts)] + claude_catalog = ClaudeCatalog() + + def run(target): + account_id, definition = target + result, refreshed_definition = refresh_account(definition, credentials, claude_catalog) + self.persist_refresh(account_id, result, refreshed_definition) + return account_id, result + + if payload.get("stream") is True: + self.stream_refresh(run, targets) + return + with ThreadPoolExecutor(max_workers=max(1, min(REFRESH_WORKERS, len(targets)))) as pool: + results = dict(pool.map(run, targets)) self.send_json(results) except (ValueError, UnicodeDecodeError, json.JSONDecodeError) as error: self.send_error(400, str(error)) @@ -1210,10 +2032,52 @@ def do_DELETE(self): results = load_results(self.results_path) results.pop(account_id, None) save_results(self.results_path, results) + order = [item for item in load_order(self.order_path) if item != account_id] + save_order(self.order_path, order) + hidden = [item for item in load_hidden(self.hidden_path) if item != account_id] + save_hidden(self.hidden_path, hidden) self.send_json({"ok": True, "id": account_id}) except (ValueError, UnicodeDecodeError, json.JSONDecodeError) as error: self.send_error(400, str(error)) + def persist_refresh(self, account_id, result, refreshed_definition): + """Persist one finished account; reload under the lock so concurrent refreshes merge.""" + if not refreshed_definition and not result["ok"]: + return + with REFRESH_STATE_LOCK: + if refreshed_definition: + accounts = load_requests(self.requests_path) + if account_id in accounts: + accounts[account_id] = refreshed_definition + save_requests(self.requests_path, accounts) + if result["ok"]: + cached_results = load_results(self.results_path) + cached_results[account_id] = result + save_results(self.results_path, cached_results) + + def stream_refresh(self, run, targets): + """Send each account result as one NDJSON line as soon as it finishes.""" + self.send_response(200) + self.send_header("Content-Type", "application/x-ndjson; charset=utf-8") + self.send_header("Cache-Control", "no-store") + self.send_header("X-Accel-Buffering", "no") + self.send_header("Connection", "close") + self.end_headers() + self.close_connection = True + connected = True + with ThreadPoolExecutor(max_workers=max(1, min(REFRESH_WORKERS, len(targets)))) as pool: + for future in as_completed([pool.submit(run, target) for target in targets]): + account_id, result = future.result() + if not connected: + continue + line = json.dumps({"id": account_id, **result}, ensure_ascii=False) + "\n" + try: + self.wfile.write(line.encode("utf-8")) + self.wfile.flush() + except OSError: + # The browser left; keep persisting the remaining results. + connected = False + def send_json(self, payload): body = json.dumps(payload, ensure_ascii=False).encode("utf-8") self.send_response(200) diff --git a/tests/parser.test.js b/tests/parser.test.js index 2dc0844..e1be45d 100644 --- a/tests/parser.test.js +++ b/tests/parser.test.js @@ -1,5 +1,7 @@ const test = require('node:test'); const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); const { normalizeCodex, normalizeCodexCredits, @@ -7,12 +9,75 @@ const { normalizeCodexUsage, normalizeMiniMax, normalizeKimi, + normalizeGoogleAi, + normalizeClaude, normalizeLongCat, normalizeQianwen, normalizeVolcengine, normalizeZhipu } = require('../parser.js'); +test('normalizes Claude percentages directly and preserves actual reset times', () => { + const result = normalizeClaude({ + five_hour: { utilization: 2, resets_at: '2026-10-17T12:00:00+00:00' }, + seven_day: { utilization: 0, resets_at: '2026-10-22T00:00:00Z' }, + seven_day_opus: null, + extra_usage: { is_enabled: false, utilization: null } + }); + assert.deepEqual(result.periods, [ + { name: '5h', usedPercent: 2, remainingPercent: 98, resetAt: '2026-10-17T12:00:00+00:00' }, + { name: 'weekly', usedPercent: 0, remainingPercent: 100, resetAt: '2026-10-22T00:00:00Z' } + ]); + assert.equal(result.used, 2); + assert.equal(result.remaining, 98); +}); + +test('Claude exhausted quota remains a valid window and optional model windows are independent', () => { + const result = normalizeClaude({ + five_hour: { utilization: 100 }, + seven_day_opus: { utilization: 12.5 }, + seven_day_sonnet: { utilization: '30.25', resets_at: 'invalid' } + }); + assert.equal(result.limit, 100); + assert.equal(result.remaining, 0); + assert.deepEqual(result.periods.map(p => [p.name, p.usedPercent, p.resetAt]), [ + ['5h', 100, null], ['Opus周额度', 12.5, null], ['Sonnet周额度', 30.25, null] + ]); +}); + +test('Claude missing or malformed quota does not fabricate unused quota or resets', () => { + for (const payload of [null, {}, { five_hour: null }, { five_hour: false }, + { five_hour: { utilization: null } }, { five_hour: { utilization: '' } }, + { five_hour: { utilization: false } }, { five_hour: { utilization: -1 } }, + { seven_day: { utilization: 'invalid' } }]) { + const result = normalizeClaude(payload); + assert.deepEqual(result.periods, []); + assert.equal(result.limit, null); + assert.equal(result.used, null); + assert.equal(result.remaining, null); + } +}); + +test('browser Claude normalization matches parser and model weekly windows have weekly rank', () => { + const html = fs.readFileSync(require.resolve('../index.html'), 'utf8'); + const firstNumberCode = html.match(/^function firstNumber\(value,keys\).*$/m)[0]; + const claudeCode = html.match(/^function normalizeClaude\(payload\).*$/m)[0]; + const rankCode = html.match(/^function periodRank\(name\).*$/m)[0]; + const context = vm.createContext({ now: () => 'fixture' }); + vm.runInContext(firstNumberCode + '\n' + claudeCode + '\n' + rankCode, context); + for (const payload of [{}, { five_hour: { utilization: 2 }, seven_day: { utilization: 10 } }, + { five_hour: null, seven_day_sonnet: { utilization: '5', resets_at: '2026-10-22T00:00:00Z' } }, + { five_hour: { utilization: true }, seven_day: { utilization: 100 } }]) { + const expected = normalizeClaude(payload); + const actual = JSON.parse(JSON.stringify(context.normalizeClaude(payload))); + delete expected.updatedAt; + delete actual.updatedAt; + assert.deepEqual(actual, expected); + } + assert.equal(context.periodRank('Opus周额度'), 2); + assert.equal(context.periodRank('OAuth应用周额度'), 2); +}); + test('normalizes Codex reset credit count', () => { const result = normalizeCodexCredits({ available_count: 4, @@ -109,6 +174,41 @@ test('normalizes MiniMax interval and weekly quota windows', () => { assert.equal(result.windows[0].interval.usedPercent, 44); assert.equal(result.windows[0].interval.remainingPercent, 56); assert.equal(result.windows[0].weekly.resetAt, 1784476800000); + assert.equal(result.windows[0].weekly.available, true); +}); + +test('marks MiniMax weekly window unavailable when the provider reports no active weekly cap', () => { + const result = normalizeMiniMax({ model_remains: [{ + model_name: 'general', + current_interval_used_percent: '0%', + current_interval_total_percent: '100%', + current_interval_status: 1, + start_time: 1789851600000, + end_time: 1789869600000, + weekly_start_time: 1789315200000, + weekly_end_time: 1789920000000, + current_weekly_used_percent: '0%', + current_weekly_total_percent: '100%', + current_weekly_status: 3 + }] }); + assert.equal(result.windows[0].weekly.available, false); + assert.equal(result.windows[0].interval.usedPercent, 0); +}); + +test('marks MiniMax weekly window unavailable when the weekly total is missing or zero', () => { + const missing = normalizeMiniMax({ model_remains: [{ + model_name: 'general', + current_interval_used_percent: '12%', + current_interval_total_percent: '100%' + }] }); + assert.equal(missing.windows[0].weekly.available, false); + const zero = normalizeMiniMax({ model_remains: [{ + model_name: 'general', + current_interval_used_percent: '12%', + current_weekly_used_percent: '5%', + current_weekly_total_percent: '0%' + }] }); + assert.equal(zero.windows[0].weekly.available, false); }); test('uses MiniMax five-hour window for the headline usage when available', () => { @@ -251,6 +351,47 @@ test('normalizes Qianwen AI TokenPlan usage periods', () => { assert.equal(result.unit, '%'); }); +test('normalizes Qianwen AI monthly-only usage without a weekly limit', () => { + const result = normalizeQianwen({ + code: '200', + data: { + DataV2: { + ret: ['SUCCESS::接口调用成功'], + data: { + msg: 'Success.', + code: 'SUCCESS', + data: { + per1MonthPercentage: 0.012131574086956523, + per1MonthResetTime: 1792080000000 + }, + requestId: '5b3d52fb', + success: true + } + }, + success: true, + httpStatus: 200 + }, + httpStatusCode: '200', + successResponse: true + }); + assert.deepEqual(result.periods.map(period => period.name), ['monthly']); + assert.ok(Math.abs(result.periods[0].usedPercent - 1.2131574086956523) < 0.000001); + assert.ok(Math.abs(result.periods[0].remainingPercent - 98.78684259130435) < 0.000001); + assert.equal(result.periods[0].resetAt, 1792080000000); + assert.ok(Math.abs(result.used - 1.2131574086956523) < 0.000001); +}); + +test('normalizes an empty Qianwen AI response without inventing periods', () => { + const empty = normalizeQianwen({ code: '200', data: { DataV2: { data: { data: {} } } } }); + assert.deepEqual(empty.periods, []); + assert.equal(empty.used, 0); + const nullish = normalizeQianwen({ + data: { DataV2: { data: { data: { per5HourPercentage: null, per1WeekPercentage: null, per1MonthPercentage: 0.5, per1MonthResetTime: null } } } } + }); + assert.deepEqual(nullish.periods.map(period => period.name), ['monthly']); + assert.equal(nullish.periods[0].resetAt, null); +}); + test('normalizes Zhipu CodingPlan token and time limits', () => { const result = normalizeZhipu({ data: { @@ -320,5 +461,593 @@ test('normalizes Google AI without Gemini Models group as empty periods', () => const { normalizeGoogleAi } = require('../parser.js'); const result = normalizeGoogleAi({ groups: [{ displayName: 'Claude and GPT models', buckets: [] }] }); assert.equal(result.periods.length, 0); - assert.equal(result.used, 0); + assert.equal(result.used, null); + assert.equal(result.limit, null); + assert.equal(result.remaining, null); +}); + +test('Google AI summary takes precedence over per-model quota', () => { + const result = normalizeGoogleAi({ + groups: [{ displayName: 'Gemini Models', buckets: [ + { window: 'weekly', remainingFraction: 0.4 }, + { window: '5h', remainingFraction: 0.8 }, + { window: '5h', remainingFraction: 0.9 } + ] }], + models: { 'gemini-3.8-flash': { quotaInfo: { remainingFraction: 0.99 } } } + }); + assert.deepEqual(result.periods.map(p => [p.name, p.remainingPercent]), [['5h', 80], ['weekly', 40]]); + assert.equal(result.remaining, 40); + assert.equal(result.modelId, undefined); +}); + +test('Google AI model fallback prefers exact 3.8 Flash rather than the largest quota', () => { + const result = normalizeGoogleAi({ groups: [{ displayName: 'Claude and GPT models', buckets: [] }], buckets: [ + { modelId: 'gemini-2.5-pro', remainingFraction: 1 }, + { modelId: 'gemini-3.8-flash-tiered', remainingFraction: 0.99 }, + { modelId: 'claude-sonnet-4-6', remainingFraction: 1 }, + { modelId: 'gemini-3.8-flash', remainingFraction: 0.2, resetTime: '2026-10-23T01:00:00Z' } + ] }); + assert.equal(result.modelId, 'gemini-3.8-flash'); + assert.equal(result.quotaSource, 'model'); + assert.equal(result.remaining, 20); + assert.equal(result.used, 80); + assert.deepEqual(result.periods, [{ name: 'gemini-3.8-flash', usedPercent: 80, + remainingPercent: 20, resetAt: '2026-10-23T01:00:00Z' }]); +}); + +test('Google AI accepts the tiered alias from quotaInfo without inventing a period', () => { + const result = normalizeGoogleAi({ data: { models: { + 'gemini-3.8-flash-high': { quotaInfo: { remainingFraction: 1 } }, + 'gemini-3.8-flash-tiered': { quotaInfo: { remainingFraction: 0.9899333 } }, + 'gemini-2.5-pro': { quotaInfo: { remainingFraction: 1 } } + } } }); + assert.equal(result.modelId, 'gemini-3.8-flash-tiered'); + assert.ok(Math.abs(result.remaining - 98.99333) < 1e-8); + assert.equal(result.periods[0].resetAt, null); + assert.equal(result.periods.some(p => ['5h', 'weekly'].includes(p.name)), false); +}); + +test('Google AI model fallback prefers a newer Gemini version even when its quota is exhausted', () => { + const result = normalizeGoogleAi({ buckets: [ + { model_id: 'gemini-3-flash', remaining_fraction: 0 }, + { model_id: 'gemini-2.5-pro', remaining_fraction: 1 }, + { model_id: 'gemini-3.8-flash', remaining_fraction: null } + ] }); + assert.equal(result.modelId, 'gemini-3-flash'); + assert.equal(result.remaining, 0); + assert.equal(result.used, 100); +}); + +function currentGoogleModels() { + return { models: { + 'gemini-3.8-flash-tiered': { quotaInfo: { remainingFraction: 0.25 } }, + 'gemini-3.10-pro': { displayName: 'Gemini 3.10 Pro', quotaInfo: { remainingFraction: 0.4 } }, + 'claude-sonnet-5-5-medium': { displayName: 'Claude Sonnet 5.5 (Medium)', + quotaInfo: { remainingFraction: 0.75, resetTime: '2026-12-01T05:00:00Z' } }, + 'claude-opus-5-5-high': { displayName: 'Claude Opus 5.5 (High)', quotaInfo: { remainingFraction: 0 } }, + 'claude-sonnet-4-6': { displayName: 'Claude Sonnet 4.6', quotaInfo: { remainingFraction: 0.5 } }, + 'gpt-oss-120b-medium': { displayName: 'GPT-OSS 120B (Medium)', quotaInfo: { remainingFraction: 1 } }, + 'preview-fixture': { displayName: 'New Model Preview', quotaInfo: { remainingFraction: 0.6 } }, + 'gemini-9-pro': { disabled: true, quotaInfo: { remainingFraction: 1 } }, + 'gemini-8-pro': { available: false, quotaInfo: { remainingFraction: 1 } }, + 'claude-internal': { isInternal: true, quotaInfo: { remainingFraction: 1 } }, + chat_fixture: { isInternal: true, quotaInfo: { remainingFraction: 1 } }, + tab_flash_lite_preview: { quotaInfo: { remainingFraction: 1 } }, + 'gemini-no-quota': { quotaInfo: { resetTime: '2026-12-01T05:00:00Z' } } + }, groups: [{ displayName: 'Gemini Models', buckets: [ + { window: '5h', remainingFraction: 0.9 }, { window: 'weekly', remainingFraction: 0.8 } + ] }] }; +} + +test('Google AI lists current public models with their real names, independent usage and resets', () => { + const result = normalizeGoogleAi(currentGoogleModels()); + assert.equal(result.modelQuotas.length, 7); + const byId = new Map(result.modelQuotas.map(model => [model.modelId, model])); + assert.deepEqual(byId.get('claude-sonnet-5-5-medium'), { + modelId: 'claude-sonnet-5-5-medium', modelName: 'Claude Sonnet 5.5 (Medium)', + usedPercent: 25, remainingPercent: 75, resetAt: '2026-12-01T05:00:00Z' + }); + assert.equal(byId.get('claude-opus-5-5-high').usedPercent, 100); + assert.equal(byId.get('gpt-oss-120b-medium').usedPercent, 0); + assert.equal(byId.get('preview-fixture').modelName, 'New Model Preview'); + assert.equal(byId.get('gemini-3.8-flash-tiered').modelName, 'gemini-3.8-flash-tiered'); + assert.equal(byId.get('claude-opus-5-5-high').resetAt, null); + assert.ok(result.modelQuotas.findIndex(m => m.modelId === 'claude-sonnet-5-5-medium') + < result.modelQuotas.findIndex(m => m.modelId === 'claude-sonnet-4-6')); + // Independent per-model exhaustion must not replace the Gemini summary. + assert.ok(Math.abs(result.used - 20) < 1e-8); + assert.deepEqual(result.periods.map(p => p.name), ['5h', 'weekly']); +}); + +test('Google AI selects newer numeric Gemini versions and drops models removed by the next refresh', () => { + const payload = currentGoogleModels(); + delete payload.groups; + const result = normalizeGoogleAi(payload); + assert.equal(result.modelId, 'gemini-3.10-pro'); + assert.equal(result.remaining, 40); + delete payload.models['claude-sonnet-5-5-medium']; + assert.ok(!normalizeGoogleAi(payload).modelQuotas.some(m => m.modelId === 'claude-sonnet-5-5-medium')); + assert.ok(result.modelQuotas.some(m => m.modelId === 'claude-sonnet-5-5-medium')); +}); + +test('Google AI deduplicates model readings conservatively and omits malformed quota or reset data', () => { + const payload = currentGoogleModels(); + payload.buckets = [ + { modelId: 'gemini-3.10-pro', remainingFraction: 0.1 }, + { modelId: 'gemini-3.10-pro', remainingFraction: 0.9 }, + { modelId: 'gemini-9-pro', remainingFraction: 1 } + ]; + payload.models['claude-invalid'] = { displayName: 'Claude Fixture', quotaInfo: { remainingFraction: true } }; + payload.models['claude-sonnet-5-5-medium'].quotaInfo.resetTime = 'invalid'; + const result = normalizeGoogleAi(payload); + assert.equal(result.modelQuotas.length, 7); + assert.equal(result.modelQuotas.find(m => m.modelId === 'gemini-3.10-pro').remainingPercent, 10); + assert.equal(result.modelQuotas.find(m => m.modelId === 'claude-sonnet-5-5-medium').resetAt, null); +}); + +test('Google AI invalid quota and business errors never imply full remaining', () => { + for (const remainingFraction of [null, true, false, '', ' ', 'invalid', NaN, Infinity, -0.1, 1.1]) { + const result = normalizeGoogleAi({ buckets: [{ modelId: 'gemini-3.8-flash', remainingFraction }] }); + assert.equal(result.remaining, null); + assert.deepEqual(result.periods, []); + } + for (const payload of [null, {}, { error: { message: 'fixture failure' }, buckets: [ + { modelId: 'gemini-3.8-flash', remainingFraction: 1 } + ] }, { data: { success: false, models: { 'gemini-3.8-flash': { quotaInfo: { remainingFraction: 1 } } } } }]) + assert.equal(normalizeGoogleAi(payload).remaining, null); +}); + +function agronQuota(weekly = 0.6, fiveHour = 0.2, modelRemaining = 0.9) { + return { + models: { + 'gemini-4-agron': { displayName: 'GEMINI 4 AGRON', quotaInfo: { remainingFraction: modelRemaining } }, + 'gemini-3.8-flash-tiered': { quotaInfo: { remainingFraction: 1 } } + }, + groups: [ + { displayName: 'Gemini Models', buckets: [{ window: 'weekly', remainingFraction: 0.05 }] }, + { displayName: 'GEMINI 4 AGRON', buckets: [ + { window: '5h', remainingFraction: fiveHour }, + { window: 'weekly', remainingFraction: weekly, resetTime: '2026-11-01T00:00:00Z' } + ] } + ] + }; +} + +function argonQuota() { + return { models: Object.fromEntries(['high', 'medium', 'low'].map(effort => [ + `gemini-4-argon-${effort}`, { displayName: `Gemini 4 Argon (${effort})`, + quotaInfo: { remainingFraction: 0.9, resetTime: '2026-11-01T00:00:00Z' } } + ])), groups: [{ displayName: 'Gemini 4 Argon', buckets: [{ + bucketId: 'gemini-argon-wtu-weekly', displayName: 'Gemini 4 Argon Weekly Limit', + window: 'weekly', remainingFraction: 0.65, resetTime: '2026-11-01T00:00:00Z' + }] }] }; +} + +test('canonical Argon response selects its independent weekly quota and official display name', () => { + const result = normalizeGoogleAi(argonQuota()); + assert.equal(result.modelId, 'gemini-4-argon-high'); + assert.equal(result.modelName, 'GEMINI 4 ARGON'); + assert.equal(result.planLabel, 'Agron'); + assert.equal(result.primaryPeriodName, 'weekly'); + assert.equal(result.remaining, 65); + assert.equal(result.periods.length, 1); + assert.equal(result.periods[0].label, 'GEMINI 4 ARGON · 周限额'); + assert.equal(result.periods[0].resetAt, '2026-11-01T00:00:00Z'); +}); + +test('canonical Argon models and group are preferred to the Agron compatibility spelling', () => { + const payload = agronQuota(); + Object.assign(payload.models, argonQuota().models); + payload.groups.push(...argonQuota().groups); + const result = normalizeGoogleAi(payload); + assert.equal(result.modelId, 'gemini-4-argon-high'); + assert.equal(result.modelName, 'GEMINI 4 ARGON'); + assert.equal(result.remaining, 65); +}); + +test('Argon compact Code label uses the upstream spelling', () => { + const html = fs.readFileSync(require.resolve('../index.html'), 'utf8'); + const code = html.split('\n').find(line => line.startsWith('function compactSourceSubtitle(')); + const context = vm.createContext({ SOURCES: {} }); + vm.runInContext(code, context); + assert.equal(context.compactSourceSubtitle('googleAi', normalizeGoogleAi(argonQuota())), 'Argon'); + assert.equal(context.compactSourceSubtitle('googleAi', normalizeGoogleAi(agronQuota())), 'Agron'); +}); + +test('Agron availability makes its weekly quota primary and puts it first in details', () => { + const result = normalizeGoogleAi(agronQuota()); + assert.equal(result.planLabel, 'Agron'); + assert.equal(result.modelId, 'gemini-4-agron'); + assert.equal(result.modelName, 'GEMINI 4 AGRON'); + assert.equal(result.primaryPeriodName, 'weekly'); + assert.equal(result.quotaSource, 'agron'); + assert.equal(result.used, 40); + assert.equal(result.remaining, 60); + assert.deepEqual(result.periods.map(p => [p.name, p.remainingPercent]), [['weekly', 60], ['5h', 20], ['gemini-weekly', 5], ['gemini-model', 100]]); + assert.equal(result.periods[0].label, 'GEMINI 4 AGRON · 周限额'); + assert.equal(result.periods[0].resetAt, '2026-11-01T00:00:00Z'); +}); + +test('Agron can be identified by model display name or enum and zero remaining is valid', () => { + for (const metadata of [{ displayName: 'GEMINI 4 AGRON' }, { model: 'MODEL_GEMINI_4_AGRON' }]) { + const result = normalizeGoogleAi({ data: { models: { + 'MODEL_FIXTURE': { ...metadata, quotaInfo: { remainingFraction: 0 } }, + 'gemini-3.8-flash': { quotaInfo: { remainingFraction: 1 } } + } } }); + assert.equal(result.modelId, 'MODEL_FIXTURE'); + assert.equal(result.planLabel, 'Agron'); + assert.equal(result.remaining, 0); + assert.equal(result.used, 100); + assert.equal(result.periods[0].name, 'MODEL_FIXTURE'); + assert.equal(result.periods[0].resetAt, null); + assert.equal(result.quotaSource, 'model'); + } +}); + +test('disabled Agron or an Agron quota without a model catalog keeps legacy Gemini selection', () => { + for (const unavailable of [{ disabled: true }, { available: false }]) { + const payload = agronQuota(); + Object.assign(payload.models['gemini-4-agron'], unavailable); + const result = normalizeGoogleAi(payload); + assert.equal(result.planLabel, undefined); + assert.equal(result.remaining, 5); + assert.equal(result.periods[0].name, 'weekly'); + } + const payload = agronQuota(); + delete payload.models['gemini-4-agron']; + assert.equal(normalizeGoogleAi(payload).planLabel, undefined); + delete payload.groups[0]; + const legacy = normalizeGoogleAi(payload); + assert.equal(legacy.modelId, 'gemini-3.8-flash-tiered'); + assert.equal(legacy.remaining, 100); +}); + +test('Agron model data never invents weekly quota or borrows Flash quota', () => { + const result = normalizeGoogleAi(agronQuota(null, null, 0.25)); + assert.equal(result.planLabel, 'Agron'); + assert.equal(result.remaining, 25); + assert.equal(result.quotaSource, 'model'); + assert.equal(result.periods.length, 3); + assert.equal(result.periods[0].name, 'gemini-4-agron'); + assert.equal(result.periods[0].label, 'GEMINI 4 AGRON · 模型额度'); + assert.equal(result.periods[2].label, 'gemini-3.8-flash-tiered · 模型额度'); + assert.equal(normalizeGoogleAi(agronQuota(null, null, null)).remaining, null); + assert.equal(normalizeGoogleAi(agronQuota(null, 0.2, null)).primaryPeriodName, '5h'); +}); + +test('Agron summary can supply missing model quota and duplicate weekly buckets stay conservative', () => { + const payload = agronQuota(0.6, 0.1, null); + payload.groups[1].buckets.push({ window: 'WEEKLY', remainingFraction: 0.4 }); + const result = normalizeGoogleAi(payload); + assert.equal(result.used, 60); + assert.equal(result.remaining, 40); + assert.equal(result.periods.length, 4); + assert.equal(result.periods[0].name, 'weekly'); + assert.equal(result.periods[3].name, 'gemini-model'); + assert.equal(result.periods[0].resetAt, null); +}); + +test('Agron cards keep their primary quota while hidden summaries show the ordinary Gemini weekly quota', () => { + const html = fs.readFileSync(require.resolve('../index.html'), 'utf8'); + const context = vm.createContext({ SOURCES: { googleAi: { sub: 'Gemini' } }, + progressPeriod: label => label, waitText: () => 'fixture countdown', state: {}, + requestDefinitions: { acc_fixture: { source: 'googleAi' } } }); + const names = ['pct', 'periodRank', 'quotaCandidates', 'periodDisplayName', 'longestPeriodInfo', + 'compactSourceSubtitle', 'googleAiRows', 'escapeHtml', 'longestPeriodText']; + const code = names.map(name => html.split('\n').find(line => line.startsWith('function ' + name + '('))).join('\n'); + const labels = html.split('\n').find(line => line.startsWith('const PERIOD_LABELS=')); + vm.runInContext(labels + '\n' + code, context); + const result = normalizeGoogleAi(agronQuota(0.6, 0.1)); + context.state.acc_fixture = result; + assert.equal(context.pct(result), 40); + assert.equal(context.longestPeriodInfo(result).used, 40); + assert.equal(context.compactSourceSubtitle('googleAi', result), 'Agron'); + assert.equal(context.compactSourceSubtitle('googleAi', {}), 'Gemini'); + assert.ok(context.googleAiRows(result).startsWith('GEMINI 4 AGRON · 周限额')); + assert.ok(context.longestPeriodText('acc_fixture').includes('周额度已用')); + assert.ok(context.longestPeriodText('acc_fixture').includes('95.00%')); + assert.ok(context.longestPeriodText('acc_fixture').includes('Gemini 通用模型')); +}); + +test('browser Google AI normalization matches parser for both response shapes', () => { + const html = fs.readFileSync(require.resolve('../index.html'), 'utf8'); + const googleCode = html.slice(html.indexOf('function normalizeGoogleAi('), html.indexOf('\nfunction normalizeClaude(')); + const unwrapCode = html.match(/^function unwrap\(value\).*$/m)[0]; + const context = vm.createContext({ now: () => 'fixture' }); + vm.runInContext(unwrapCode + '\n' + googleCode, context); + for (const payload of [{}, { groups: [{ displayName: 'Gemini Models', buckets: [ + { window: '5h', remainingFraction: 0.3 }, { window: 'weekly', remainingFraction: 0.8 } + ] }] }, { buckets: [ + { modelId: 'gemini-3.8-flash-tiered', remainingFraction: 0.9899333 }, + { modelId: 'gemini-3.8-flash', remainingFraction: 0.1 } + ] }, { data: { models: { 'gemini-3.8-flash-tiered': { quotaInfo: { remainingFraction: 0, resetTime: '2026-10-23T01:00:00Z' } } } } }, + { buckets: [{ modelId: 'gemini-3.8-flash', remainingFraction: true }] }, + agronQuota(), agronQuota(null, null, 0), agronQuota(null, null, null), + { data: agronQuota(0.4, null, null) }, argonQuota(), { data: argonQuota() }, + { ...argonQuota(), models: { ...argonQuota().models, + 'gemini-3.8-flash-tiered': { quotaInfo: { remainingFraction: 0.5 } } } }, + currentGoogleModels(), { data: currentGoogleModels() }, + { ...argonQuota(), groups: [...argonQuota().groups, { displayName: 'Gemini Models', buckets: [ + { window: '5h', remainingFraction: 0.2 }, { window: 'weekly', remainingFraction: 0.8 } + ] }] }]) { + const expected = normalizeGoogleAi(payload); + const actual = JSON.parse(JSON.stringify(context.normalizeGoogleAi(payload))); + delete expected.updatedAt; + delete actual.updatedAt; + assert.deepEqual(actual, expected); + } +}); + +function browserFunctions(names) { + const html = fs.readFileSync(require.resolve('../index.html'), 'utf8'); + const declarations = [...html.matchAll(/^(?:async )?function (\w+)\(/gm)]; + return names.map(name => { + const index = declarations.findIndex(match => match[1] === name); + assert.notEqual(index, -1, `missing browser function ${name}`); + return html.slice(declarations[index].index, declarations[index + 1]?.index); + }).join('\n'); +} + +function hiddenPanelContext(requestDefinitions, state) { + const nodes = new Map(); + const node = selector => { + if (!nodes.has(selector)) nodes.set(selector, { innerHTML: '', value: '', + classList: { add() {}, remove() {} } }); + return nodes.get(selector); + }; + const writes = []; + const hiddenIds = new Set(Object.keys(requestDefinitions)); + const context = vm.createContext({ requestDefinitions, state, hiddenIds, locked: false, + SOURCES: { googleAi: { name: 'Google AI', sub: 'Gemini' }, kimi: { name: 'Kimi', sub: 'Code' } }, + $: node, waitText: reset => reset || '暂无重置时间', + saveHidden: () => writes.push([...hiddenIds]) }); + const names = ['accountLabel', 'accountDisplayName', 'compactSourceSubtitle', 'longestPeriodText', + 'longestPeriodInfo', 'quotaCandidates', 'periodRank', 'periodDisplayName', 'escapeHtml', + 'groupHiddenByChannel', 'showAccount']; + const html = fs.readFileSync(require.resolve('../index.html'), 'utf8'); + const panel = html.match(/^function renderHiddenPanel\([\s\S]*?^\}/m)[0]; + vm.runInContext(browserFunctions(names) + '\n' + panel, context); + context.render = () => { + const all = Object.entries(requestDefinitions); + context.renderHiddenPanel(all, all.filter(([id]) => hiddenIds.has(id))); + }; + context.render(); + return { context, node, writes }; +} + +test('hidden Google Argon rows use Gemini weekly quota and other Google accounts remain restorable', () => { + const payload = argonQuota(); + payload.groups[0].buckets[0].remainingFraction = 0; + payload.groups.push({ displayName: 'Gemini Models', buckets: [ + { window: 'weekly', remainingFraction: 0.75, resetTime: '2026-12-03T00:00:00Z' } + ] }); + const accounts = { + acc_plain: { source: 'googleAi', label: '普通示例' }, + acc_argon: { source: 'googleAi', label: 'Argon 示例' }, + acc_other: { source: 'kimi', label: '其他平台示例' } + }; + const state = { acc_plain: normalizeGoogleAi(currentGoogleModels()), + acc_argon: normalizeGoogleAi(payload), + acc_other: { periods: [{ name: 'weekly', usedPercent: 42 }] } }; + const before = JSON.stringify({ accounts, state }); + const { context, node, writes } = hiddenPanelContext(accounts, state); + const rows = node('#hiddenList').innerHTML; + assert.equal((rows.match(/class="hidden-row"/g) || []).length, 2); + assert.ok(rows.includes('周额度已用')); + assert.ok(rows.includes('25.00%')); + assert.ok(rows.includes('data-reset-wait="2026-12-03T00:00:00Z"')); + assert.ok(rows.includes('Gemini 通用模型 · 周额度已使用')); + assert.ok(!rows.includes('100.00%')); + assert.ok(rows.includes('42.00%')); + assert.ok(!rows.includes('普通示例')); + assert.ok(node('#hiddenSelect').innerHTML.includes('value="acc_plain">Google AI · 普通示例(已隐藏)')); + assert.equal(JSON.stringify({ accounts, state }), before); + assert.equal(state.acc_argon.used, 100); + assert.deepEqual(writes, []); + + node('#hiddenSelect').value = 'acc_plain'; + context.showAccount(node('#hiddenSelect').value); + assert.deepEqual(writes, [['acc_argon', 'acc_other']]); + assert.ok(node('#hiddenSelect').innerHTML.includes('value="acc_plain">Google AI · 普通示例')); + assert.equal(JSON.stringify({ accounts, state }), before); +}); + +test('hidden Google accounts without Argon need no usage rows and retain the restore dropdown', () => { + const accounts = { acc_plain: { source: 'googleAi', label: '普通示例' } }; + for (const state of [{}, { acc_plain: normalizeGoogleAi(currentGoogleModels()) }]) { + const { node, context, writes } = hiddenPanelContext(accounts, state); + assert.ok(node('#hiddenList').innerHTML.includes('下拉列表恢复')); + assert.ok(!node('#hiddenList').innerHTML.includes('hidden-row')); + assert.ok(!node('#hiddenList').innerHTML.includes('当前没有被隐藏的账号')); + assert.ok(node('#hiddenSelect').innerHTML.includes('acc_plain')); + context.showAccount('acc_plain'); + assert.deepEqual(writes, [[]]); + assert.ok(node('#hiddenList').innerHTML.includes('当前没有被隐藏的账号')); + } +}); + +test('hidden Argon quota never borrows Argon or model usage when the Gemini weekly bucket is absent', () => { + const accounts = { acc_argon: { source: 'googleAi', label: 'Argon 示例' } }; + for (const invalid of [null, { name: 'gemini-weekly', usedPercent: null }, + { name: 'gemini-weekly', usedPercent: NaN }, + { name: 'gemini-weekly', usedPercent: 10, available: false }]) { + const data = normalizeGoogleAi(argonQuota()); + if (invalid) data.periods.push(invalid); + const { node } = hiddenPanelContext(accounts, { acc_argon: data }); + const rows = node('#hiddenList').innerHTML; + assert.ok(rows.includes('暂无周额度数据')); + assert.ok(rows.includes('data-reset-wait=""')); + assert.ok(!rows.includes('%')); + } + const payload = argonQuota(); + payload.groups.push({ displayName: 'Gemini Models', buckets: [ + { window: 'weekly', remainingFraction: 0 } + ] }); + const { node } = hiddenPanelContext(accounts, { acc_argon: normalizeGoogleAi(payload) }); + assert.ok(node('#hiddenList').innerHTML.includes('100.00%')); + assert.ok(node('#hiddenList').innerHTML.includes('暂无重置时间')); +}); + +test('Argon details retain independent Gemini five-hour and weekly windows', () => { + const payload = argonQuota(); + payload.groups.push({ displayName: 'Gemini Models', buckets: [ + { window: '5h', remainingFraction: 0.1, resetTime: '2026-11-01T05:00:00Z' }, + { window: 'weekly', remainingFraction: 0, resetTime: '2026-11-06T00:00:00Z' } + ] }); + const result = normalizeGoogleAi(payload); + assert.deepEqual(result.periods.map(p => [p.name, p.remainingPercent]), [ + ['weekly', 65], ['gemini-5h', 10], ['gemini-weekly', 0] + ]); + assert.equal(result.used, 35); + assert.equal(result.primaryPeriodName, 'weekly'); + assert.equal(result.periods[1].resetAt, '2026-11-01T05:00:00Z'); + assert.equal(result.periods[2].resetAt, '2026-11-06T00:00:00Z'); + const context = vm.createContext({ progressPeriod: label => `${label}\n` }); + vm.runInContext(browserFunctions(['googleAiRows', 'escapeHtml']), context); + const rows = context.googleAiRows(result); + assert.ok(rows.startsWith('GEMINI 4 ARGON · 周限额')); + assert.ok(rows.includes('Gemini · 5小时')); + assert.ok(rows.includes('Gemini · 周额度')); + assert.ok(!rows.includes('接口未返回')); +}); + +test('Google AI rows show only returned quota without placeholder windows', () => { + const context = vm.createContext({ progressPeriod: label => `${label}\n` }); + vm.runInContext(browserFunctions(['googleAiRows', 'escapeHtml']), context); + const model = normalizeGoogleAi({ models: { + 'gemini-3.8-flash': { quotaInfo: { remainingFraction: 0.75 } } + } }); + const rows = context.googleAiRows(model); + assert.ok(!rows.includes('接口未返回')); + assert.ok(!rows.includes('Gemini · 5小时')); + assert.ok(!rows.includes('Gemini · 周额度')); + assert.ok(rows.includes('gemini-3.8-flash')); + assert.ok(rows.includes('模型额度 · 周期未提供')); + const argonRows = context.googleAiRows(normalizeGoogleAi(argonQuota())); + assert.ok(argonRows.startsWith('GEMINI 4 ARGON · 周限额\n')); + assert.ok(argonRows.includes('当前模型用量(3)')); + const regularRows = context.googleAiRows(normalizeGoogleAi({ groups: [{ + displayName: 'Gemini Models', buckets: [ + { window: '5h', remainingFraction: 0.25 }, { window: 'weekly', remainingFraction: 0.5 } + ] + }] })); + assert.equal(regularRows, 'Gemini · 5小时\nGemini · 周额度\n'); +}); + +test('Argon accounts also show returned Gemini 3.8 Flash model quota and Argon windows', () => { + const payload = argonQuota(); + payload.models['gemini-3.8-flash-tiered'] = { quotaInfo: { remainingFraction: 0.97958344, + resetTime: '2026-10-24T04:38:06Z' } }; + payload.groups[0].buckets.push({ window: '5h', remainingFraction: 0.5, resetTime: '2026-10-24T05:00:00Z' }); + payload.groups.push({ displayName: 'Claude and GPT models', buckets: [{ window: '5h', remainingFraction: 1 }] }); + const result = normalizeGoogleAi(payload); + assert.equal(result.used, 35); + assert.equal(result.primaryPeriodName, 'weekly'); + assert.deepEqual(result.periods.map(p => [p.name, p.label, Number(p.remainingPercent.toFixed(4))]), [ + ['weekly', 'GEMINI 4 ARGON · 周限额', 65], + ['5h', 'GEMINI 4 ARGON · 5小时限额', 50], + ['gemini-model', 'gemini-3.8-flash-tiered · 模型额度', 97.9583] + ]); + assert.equal(result.periods[2].resetAt, '2026-10-24T04:38:06Z'); + const context = vm.createContext({ progressPeriod: label => `${label}\n` }); + vm.runInContext(browserFunctions(['googleAiRows', 'escapeHtml']), context); + const rows = context.googleAiRows(result); + assert.ok(rows.startsWith('GEMINI 4 ARGON · 周限额\nGEMINI 4 ARGON · 5小时限额\n')); + assert.ok(rows.includes('当前模型用量(4)')); + assert.equal((rows.match(/title="gemini-3.8-flash-tiered"/g) || []).length, 1); + assert.ok(rows.includes('模型额度 · 周期未提供')); +}); + +test('Google AI renders the current model names, usages and resets while escaping provider labels', () => { + const payload = currentGoogleModels(); + payload.models['preview-fixture'].displayName = ''; + const rendered = []; + const context = vm.createContext({ progressPeriod: (label, used, reset, remaining) => { + rendered.push({ label, used, reset, remaining }); + return label; + } }); + vm.runInContext(browserFunctions(['googleAiRows', 'escapeHtml']), context); + const rows = context.googleAiRows(normalizeGoogleAi(payload)); + assert.ok(rows.includes('当前模型用量(7)')); + assert.ok(rows.includes('Claude Sonnet 5.5 (Medium)')); + assert.ok(rows.includes('GPT-OSS 120B (Medium)')); + assert.ok(!rows.includes(' r.label === 'Claude Sonnet 5.5 (Medium)'), { + label: 'Claude Sonnet 5.5 (Medium)', used: 25, reset: '2026-12-01T05:00:00Z', remaining: 75 + }); +}); + +function orderingContext(fetch) { + const writes = [], alerts = []; + const context = vm.createContext({ + locked: false, orderSaving: false, + accountOrder: ['visible_a', 'hidden_a', 'credits_a', 'visible_b', 'hidden_b', 'visible_c'], + hiddenIds: new Set(['hidden_a', 'hidden_b']), + requestDefinitions: { + visible_a: { source: 'googleAi' }, hidden_a: { source: 'kimi' }, + credits_a: { source: 'codexNewApiCredits' }, visible_b: { source: 'claude' }, + hidden_b: { source: 'googleAi' }, visible_c: { source: 'codexNewApi' } + }, render() {}, alert: message => alerts.push(message), + fetch: async (url, options) => { + assert.equal(url, '/api/order'); + const body = JSON.parse(options.body); + writes.push(body.order); + return fetch ? fetch() : { ok: true, json: async () => ({ ok: true, order: body.order }) }; + } + }); + vm.runInContext(browserFunctions(['getOrderedAccounts', 'getVisibleAccounts', 'moveAccount', 'saveOrder']), context); + return { context, writes, alerts, ids: () => Array.from(context.getVisibleAccounts(), ([id]) => id) }; +} + +test('one move skips hidden and merged-credit accounts and persists their positions', async () => { + const { context, writes, ids } = orderingContext(); + await context.moveAccount('visible_a', 1); + assert.deepEqual(ids(), ['visible_b', 'visible_a', 'visible_c']); + assert.deepEqual(writes, [['visible_b', 'hidden_a', 'credits_a', 'visible_a', 'hidden_b', 'visible_c']]); + context.accountOrder = writes[0]; // A page reload reads the persisted complete order. + assert.deepEqual(ids(), ['visible_b', 'visible_a', 'visible_c']); + await context.moveAccount('visible_a', -1); + assert.deepEqual(ids(), ['visible_a', 'visible_b', 'visible_c']); + assert.equal(context.orderSaving, false); +}); + +test('ordering boundaries, locked editing and invisible subjects do not save', async () => { + const { context, writes } = orderingContext(); + for (const [id, direction] of [['visible_a', -1], ['visible_c', 1], ['hidden_a', 1], + ['credits_a', 1], ['missing', 1], ['visible_b', 0], ['visible_b', 2]]) + await context.moveAccount(id, direction); + context.locked = true; + await context.moveAccount('visible_a', 1); + assert.deepEqual(writes, []); +}); + +test('ordering blocks overlapping saves so fast clicks cannot overwrite a newer order', async () => { + let finish; + const { context, writes, ids } = orderingContext(() => new Promise(resolve => { finish = resolve; })); + const pending = context.moveAccount('visible_a', 1); + assert.equal(context.orderSaving, true); + await context.moveAccount('visible_a', 1); + assert.equal(writes.length, 1); + finish({ ok: true, json: async () => ({ ok: true }) }); + await pending; + assert.equal(context.orderSaving, false); + assert.deepEqual(ids(), ['visible_b', 'visible_a', 'visible_c']); +}); + +test('failed ordering saves restore the previous order and report the failure', async () => { + for (const fetch of [ + async () => { throw new Error('offline'); }, + async () => ({ ok: false, status: 500 }), + async () => ({ ok: true, json: async () => ({ ok: false }) }) + ]) { + const { context, alerts, ids } = orderingContext(fetch); + const original = Array.from(context.accountOrder); + await context.moveAccount('visible_a', 1); + assert.deepEqual(Array.from(context.accountOrder), original); + assert.deepEqual(ids(), ['visible_a', 'visible_b', 'visible_c']); + assert.equal(context.orderSaving, false); + assert.equal(alerts.length, 1); + assert.match(alerts[0], /保存显示顺序失败/); + } }); diff --git a/tests/test_agy_quota.py b/tests/test_agy_quota.py new file mode 100644 index 0000000..c91ec7a --- /dev/null +++ b/tests/test_agy_quota.py @@ -0,0 +1,831 @@ +from contextlib import redirect_stdout +from datetime import datetime, timedelta, timezone +from http.server import ThreadingHTTPServer +from io import BytesIO, StringIO +import json +import hashlib +from pathlib import Path +import runpy +import tempfile +import threading +import unittest +from unittest import mock +from urllib.error import HTTPError +from urllib.request import Request, urlopen + +from server import (DashboardHandler, GOOGLE_UA, execute_google_ai, google_ai_model_quota, + google_ai_quota_periods, provider_response_ok, query_agy_quotas) + + +def quota(five_hour=0.8, weekly=0.4): + return {'groups': [ + {'displayName': 'Claude and GPT models', 'buckets': [ + {'window': '5h', 'remainingFraction': 1}, + ]}, + {'displayName': 'Gemini Models', 'buckets': [ + {'window': 'weekly', 'remainingFraction': weekly}, + {'window': '5h', 'remainingFraction': five_hour}, + ]}, + ]} + + +def model_quota(model_id='gemini-3.8-flash-tiered', remaining=0.9899333): + return {'models': {model_id: {'quotaInfo': {'remainingFraction': remaining}}}} + + +def agron_quota(weekly=0.6, five_hour=0.2, model_remaining=0.9): + payload = model_quota('gemini-4-agron', model_remaining) + payload['models']['gemini-4-agron']['displayName'] = 'GEMINI 4 AGRON' + payload['models']['gemini-3.8-flash-tiered'] = {'quotaInfo': {'remainingFraction': 1}} + payload['groups'] = [{'displayName': 'GEMINI 4 AGRON', 'buckets': [ + {'window': '5h', 'remainingFraction': five_hour}, + {'window': 'weekly', 'remainingFraction': weekly, 'resetTime': '2026-11-01T00:00:00Z'}, + ]}] + return payload + + +def argon_quota(): + return {'models': {f'gemini-4-argon-{effort}': { + 'displayName': f'Gemini 4 Argon ({effort.title()})', + 'quotaInfo': {'remainingFraction': 0.9}, + } for effort in ['high', 'medium', 'low']}, 'groups': [{ + 'displayName': 'Gemini 4 Argon', 'buckets': [{ + 'bucketId': 'gemini-argon-wtu-weekly', 'window': 'weekly', + 'remainingFraction': 0.65, 'resetTime': '2026-11-01T00:00:00Z', + }], + }]} + + +class QuotaApiTests(unittest.TestCase): + def test_gemini_five_hour_is_separate_from_weekly_and_third_party(self): + result = google_ai_quota_periods(quota()) + self.assertEqual(result['fiveHour'], {'remainingPercent': 80, 'resetAt': None}) + self.assertEqual(result['weekly'], {'remainingPercent': 40, 'resetAt': None}) + + def test_missing_or_invalid_five_hour_is_never_assumed_unused(self): + for fraction in (None, True, '', 'invalid', float('nan'), float('inf'), -0.1, 1.1): + with self.subTest(fraction=fraction), self.assertRaises(ValueError): + google_ai_quota_periods(quota(fraction)) + with self.assertRaises(ValueError): + google_ai_quota_periods({'groups': []}) + + def test_zero_remaining_is_a_valid_quota_and_missing_weekly_stays_absent(self): + self.assertEqual(google_ai_quota_periods(quota(0, None)), { + 'fiveHour': {'remainingPercent': 0, 'resetAt': None}, 'weekly': None, + }) + + def test_preserves_reported_reset_without_inventing_missing_reset(self): + payload = quota() + payload['groups'][1]['buckets'][1]['resetTime'] = '2026-01-01T05:00:00Z' + self.assertEqual(google_ai_quota_periods(payload)['fiveHour']['resetAt'], '2026-01-01T05:00:00Z') + + def test_business_error_cannot_supply_successful_quota(self): + payload = quota() + payload['error'] = {'message': 'fixture business failure'} + with self.assertRaises(ValueError): + google_ai_quota_periods(payload) + + def test_queries_only_requested_google_accounts_and_redacts_failures(self): + accounts = { + 'acc_alpha': {'source': 'googleAi', 'refreshToken': 'REDACTED_ALPHA'}, + 'acc_beta': {'source': 'googleAi', 'refreshToken': 'REDACTED_BETA'}, + 'acc_other': {'source': 'kimi', 'curl': 'REDACTED_CURL'}, + } + + def execute(credentials, **kwargs): + if credentials['refreshToken'] == 'REDACTED_ALPHA': + return 200, json.dumps(quota()), '' + return 401, 'REDACTED_PROVIDER_BODY', 'REDACTED_PROVIDER_ERROR' + + with mock.patch('server.execute_google_ai', side_effect=execute) as call: + response = query_agy_quotas(accounts, {}, ['acc_alpha', 'acc_beta', 'acc_other', 'acc_missing']) + self.assertTrue(response['ok']) + self.assertEqual(call.call_count, 2) + self.assertTrue(response['accounts']['acc_alpha']['ok']) + self.assertIsNotNone(response['accounts']['acc_alpha']['updatedAt']) + self.assertFalse(response['accounts']['acc_beta']['ok']) + self.assertIsNone(response['accounts']['acc_beta']['updatedAt']) + self.assertNotIn('REDACTED_', json.dumps(response)) + + def test_http_200_with_unusable_body_is_a_query_failure(self): + with mock.patch('server.execute_google_ai', return_value=(200, '{"groups":[]}', '')): + response = query_agy_quotas({'acc_alpha': {'source': 'googleAi', 'refreshToken': 'REDACTED'}}, {}, ['acc_alpha']) + self.assertFalse(response['ok']) + self.assertIsNone(response['accounts']['acc_alpha']['fiveHour']) + + def test_model_only_quota_reports_a_fallback_without_becoming_successful(self): + body = json.dumps(model_quota(remaining=0.9899333)) + with mock.patch('server.execute_google_ai', return_value=(200, body, '')): + response = query_agy_quotas({'acc_alpha': {'source': 'googleAi', 'refreshToken': 'REDACTED'}}, {}, ['acc_alpha']) + account = response['accounts']['acc_alpha'] + # The contract is unchanged: no explicit 5-hour window is a failed query. + self.assertFalse(account['ok']) + self.assertIsNone(account['fiveHour']) + self.assertEqual(account['fallback'], { + 'modelId': 'gemini-3.8-flash-tiered', + 'remainingPercent': 98.99333, + 'resetAt': None, + }) + self.assertNotIn('REDACTED', json.dumps(response)) + + def _fake_google(self, bodies): + seen = [] + + class Response(BytesIO): + status = 200 + def __enter__(self): + return self + def __exit__(self, *args): + return False + + def fake_urlopen(request, timeout=None): + url = request.full_url + seen.append(url) + if 'oauth2' in url: + return Response(b'{"access_token": "REDACTED"}') + if url in bodies: + return Response(json.dumps(bodies[url]).encode()) + for host, body in bodies.items(): + if url.startswith(host + '/'): + return Response(json.dumps(body).encode()) + raise HTTPError(url, 404, 'Not Found', {}, BytesIO()) + return seen, fake_urlopen + + def test_skips_quota_host_without_gemini_group(self): + third_party = {'groups': [{'displayName': 'Claude and GPT models', 'buckets': [{'window': '5h', 'remainingFraction': 1}]}]} + seen, fake = self._fake_google({ + 'https://cloudcode-pa.googleapis.com': third_party, + 'https://daily-cloudcode-pa.googleapis.com': quota(), + }) + with mock.patch('server._google_opener', return_value=None), mock.patch('server.urlopen', side_effect=fake): + code, body, error = execute_google_ai({'refreshToken': 'REDACTED'}) + self.assertEqual((code, error), (200, '')) + self.assertEqual(google_ai_quota_periods(json.loads(body))['fiveHour']['remainingPercent'], 80) + quota_urls = [url for url in seen if 'oauth2' not in url] + self.assertEqual(quota_urls[0], 'https://cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels') + + def test_dropped_connection_on_one_host_falls_through_to_next_host(self): + from http.client import RemoteDisconnected + seen, fake = self._fake_google({'https://daily-cloudcode-pa.googleapis.com': quota()}) + + def flaky(request, timeout=None): + if request.full_url.startswith('https://cloudcode-pa.googleapis.com/'): + seen.append(request.full_url) + raise RemoteDisconnected('Remote end closed connection without response') + return fake(request, timeout) + with mock.patch('server._google_opener', return_value=None), mock.patch('server.urlopen', side_effect=flaky): + code, body, error = execute_google_ai({'refreshToken': 'REDACTED'}) + self.assertEqual((code, error), (200, '')) + self.assertEqual(google_ai_quota_periods(json.loads(body))['fiveHour']['remainingPercent'], 80) + self.assertIn('https://daily-cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels', seen) + + def test_dropped_connection_everywhere_is_reported_without_raising(self): + from http.client import RemoteDisconnected + + def dropped(request, timeout=None): + if 'oauth2' in request.full_url: + return self._fake_google({})[1](request, timeout) + raise RemoteDisconnected('Remote end closed connection without response') + with mock.patch('server._google_opener', return_value=None), mock.patch('server.urlopen', side_effect=dropped): + code, body, error = execute_google_ai({'refreshToken': 'REDACTED'}) + self.assertEqual((code, body), (1, '')) + self.assertIn('Remote end closed connection without response', error) + + def test_third_party_only_response_is_not_successful_gemini_quota(self): + third_party = {'groups': [{'displayName': 'Claude and GPT models', 'buckets': [{'window': '5h', 'remainingFraction': 1}]}]} + _, fake = self._fake_google({'https://cloudcode-pa.googleapis.com': third_party}) + with mock.patch('server._google_opener', return_value=None), mock.patch('server.urlopen', side_effect=fake): + code, body, error = execute_google_ai({'refreshToken': 'REDACTED'}) + self.assertEqual(code, 1) + self.assertEqual(body, '') + self.assertIn('quota endpoints failed', error) + self.assertFalse(provider_response_ok('googleAi', 200, json.dumps(third_party))) + + def test_fallback_reads_preferred_model_after_all_summary_hosts(self): + bodies = {base + '/v1internal:retrieveUserQuotaSummary': {'groups': []} for base in ( + 'https://cloudcode-pa.googleapis.com', 'https://daily-cloudcode-pa.googleapis.com', + 'https://daily-cloudcode-pa.sandbox.googleapis.com', + )} + bodies['https://cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels'] = model_quota() + seen, fake = self._fake_google(bodies) + with mock.patch('server._google_opener', return_value=None), mock.patch('server.urlopen', side_effect=fake): + code, body, error = execute_google_ai({'refreshToken': 'REDACTED'}) + self.assertEqual((code, error), (200, '')) + self.assertEqual(google_ai_model_quota(json.loads(body))['modelId'], 'gemini-3.8-flash-tiered') + self.assertEqual(len([url for url in seen if url.endswith(':retrieveUserQuotaSummary')]), 3) + self.assertTrue(seen[-1].endswith(':retrieveUserQuotaSummary')) + + def test_agron_catalog_is_joined_to_its_weekly_summary_before_returning(self): + catalog = {'models': agron_quota()['models']} + summary = {'groups': quota()['groups'] + agron_quota()['groups']} + seen, fake = self._fake_google({ + 'https://cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels': catalog, + 'https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary': summary, + }) + with mock.patch('server._google_opener', return_value=None), mock.patch('server.urlopen', side_effect=fake): + code, body, error = execute_google_ai({'refreshToken': 'REDACTED'}) + payload = json.loads(body) + self.assertEqual((code, error), (200, '')) + self.assertEqual(payload['models'], catalog['models']) + self.assertEqual(payload['groups'], summary['groups']) + self.assertEqual(google_ai_model_quota(payload)['modelId'], 'gemini-4-agron') + self.assertTrue(provider_response_ok('googleAi', 200, body)) + self.assertEqual(seen[-1], 'https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary') + + def test_consumer_build_metadata_reveals_canonical_argon_catalog_and_weekly_quota(self): + catalog = argon_quota() + _, modern = self._fake_google({ + 'https://cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels': {'models': catalog['models']}, + 'https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary': {'groups': catalog['groups']}, + }) + _, legacy = self._fake_google({'https://cloudcode-pa.googleapis.com': model_quota()}) + agents = [] + + def upstream(request, timeout=None): + if 'oauth2' in request.full_url: + return modern(request, timeout) + agent = request.get_header('User-agent') or '' + agents.append(agent) + native_profile = all(marker in agent for marker in ( + 'antigravity-cli/', 'cl=1000353293', 'auth_method=consumer', + )) + return (modern if native_profile else legacy)(request, timeout) + + with mock.patch('server._google_opener', return_value=None), mock.patch('server.urlopen', side_effect=upstream): + code, body, error = execute_google_ai({'refreshToken': 'REDACTED'}) + payload = json.loads(body) + self.assertEqual((code, error), (200, '')) + self.assertEqual(payload['groups'], catalog['groups']) + self.assertEqual(google_ai_model_quota(payload)['modelName'], 'GEMINI 4 ARGON') + self.assertTrue(provider_response_ok('googleAi', 200, body)) + self.assertTrue(all(agent == GOOGLE_UA for agent in agents)) + with mock.patch('server.GOOGLE_UA', 'antigravity-tools/1.1.5'), mock.patch('server._google_opener', return_value=None), mock.patch('server.urlopen', side_effect=upstream): + code, body, _ = execute_google_ai({'refreshToken': 'REDACTED'}) + self.assertEqual(code, 200) + self.assertEqual(google_ai_model_quota(json.loads(body))['modelId'], 'gemini-3.8-flash-tiered') + + def test_canonical_argon_ids_win_over_legacy_agron_aliases(self): + payload = agron_quota() + payload['models'].update(argon_quota()['models']) + selected = google_ai_model_quota(payload) + self.assertEqual(selected['modelId'], 'gemini-4-argon-high') + self.assertEqual(selected['modelName'], 'GEMINI 4 ARGON') + + def test_later_model_host_can_enable_agron_before_accepting_legacy_summary(self): + _, fake = self._fake_google({ + 'https://cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels': model_quota(), + 'https://daily-cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels': {'models': agron_quota()['models']}, + 'https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary': {'groups': agron_quota()['groups']}, + }) + with mock.patch('server._google_opener', return_value=None), mock.patch('server.urlopen', side_effect=fake): + code, body, error = execute_google_ai({'refreshToken': 'REDACTED'}) + self.assertEqual((code, error), (200, '')) + self.assertEqual(google_ai_model_quota(json.loads(body))['planLabel'], 'Agron') + + def test_agron_weekly_is_sought_before_returning_a_five_hour_only_summary(self): + five_hour = agron_quota(weekly=None) + weekly = agron_quota() + _, fake = self._fake_google({ + 'https://cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels': {'models': weekly['models']}, + 'https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary': {'groups': five_hour['groups']}, + 'https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary': {'groups': weekly['groups']}, + }) + with mock.patch('server._google_opener', return_value=None), mock.patch('server.urlopen', side_effect=fake): + code, body, error = execute_google_ai({'refreshToken': 'REDACTED'}) + self.assertEqual((code, error), (200, '')) + self.assertEqual(json.loads(body)['groups'], weekly['groups']) + + def test_argon_weekly_does_not_stop_lookup_before_regular_gemini_windows(self): + catalog = argon_quota() + seen, fake = self._fake_google({ + 'https://cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels': {'models': catalog['models']}, + 'https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary': {'groups': catalog['groups']}, + 'https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary': quota(), + }) + with mock.patch('server._google_opener', return_value=None), mock.patch('server.urlopen', side_effect=fake): + code, body, error = execute_google_ai({'refreshToken': 'REDACTED'}) + payload = json.loads(body) + self.assertEqual((code, error), (200, '')) + self.assertEqual(payload['models'], catalog['models']) + self.assertEqual(payload['groups'][0], catalog['groups'][0]) + self.assertEqual(google_ai_quota_periods(payload), { + 'fiveHour': {'remainingPercent': 80, 'resetAt': None}, + 'weekly': {'remainingPercent': 40, 'resetAt': None}, + }) + self.assertTrue(provider_response_ok('googleAi', code, body)) + self.assertTrue(seen[-1].startswith('https://daily-cloudcode-pa.googleapis.com/')) + + def test_regular_gemini_windows_are_combined_across_summary_hosts(self): + _, fake = self._fake_google({ + 'https://cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels': model_quota(), + 'https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary': quota(five_hour=0.2, weekly=None), + 'https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary': quota(five_hour=0.8, weekly=0.4), + }) + with mock.patch('server._google_opener', return_value=None), mock.patch('server.urlopen', side_effect=fake): + code, body, error = execute_google_ai({'refreshToken': 'REDACTED'}) + self.assertEqual((code, error), (200, '')) + self.assertEqual(google_ai_quota_periods(json.loads(body)), { + 'fiveHour': {'remainingPercent': 20, 'resetAt': None}, + 'weekly': {'remainingPercent': 40, 'resetAt': None}, + }) + + def test_argon_only_summary_does_not_relabel_third_party_windows_as_gemini(self): + catalog = argon_quota() + third_party = quota()['groups'][0] + _, fake = self._fake_google({ + 'https://cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels': {'models': catalog['models']}, + 'https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary': {'groups': catalog['groups'] + [third_party]}, + }) + with mock.patch('server._google_opener', return_value=None), mock.patch('server.urlopen', side_effect=fake): + code, body, error = execute_google_ai({'refreshToken': 'REDACTED'}) + self.assertEqual((code, error), (200, '')) + self.assertTrue(provider_response_ok('googleAi', code, body)) + with self.assertRaises(ValueError): + google_ai_quota_periods(json.loads(body)) + + def test_agron_capability_accepts_display_name_and_enum_but_not_disabled_models(self): + for metadata in [{'displayName': 'GEMINI 4 AGRON'}, {'model': 'MODEL_GEMINI_4_AGRON'}]: + payload = {'models': {'MODEL_FIXTURE': {**metadata, 'quotaInfo': {'remainingFraction': 0}}}} + result = google_ai_model_quota(payload) + self.assertEqual(result['planLabel'], 'Agron') + self.assertEqual(result['remainingPercent'], 0) + self.assertTrue(provider_response_ok('googleAi', 200, json.dumps(payload))) + for unavailable in [{'disabled': True}, {'available': False}]: + variant = {'models': {'MODEL_FIXTURE': {**payload['models']['MODEL_FIXTURE'], **unavailable}}} + self.assertIsNone(google_ai_model_quota(variant)) + + def test_agron_presence_without_any_agron_quota_rejects_flash_and_other_group_quota(self): + payload = agron_quota(weekly=None, five_hour=None, model_remaining=None) + payload['groups'] += quota()['groups'] + self.assertIsNone(google_ai_model_quota(payload)) + self.assertFalse(provider_response_ok('googleAi', 200, json.dumps(payload))) + _, fake = self._fake_google({'https://cloudcode-pa.googleapis.com': payload}) + with mock.patch('server._google_opener', return_value=None), mock.patch('server.urlopen', side_effect=fake): + code, body, error = execute_google_ai({'refreshToken': 'REDACTED'}) + self.assertEqual(code, 1) + self.assertEqual(body, '') + + def test_agron_summary_is_usable_even_if_model_level_fraction_is_missing(self): + payload = agron_quota(model_remaining=None) + self.assertIsNone(google_ai_model_quota(payload)) + self.assertTrue(provider_response_ok('googleAi', 200, json.dumps(payload))) + + def test_agron_group_or_raw_bucket_alone_does_not_establish_model_availability(self): + payload = {'groups': agron_quota()['groups'], 'buckets': [ + {'modelId': 'gemini-4-agron', 'remainingFraction': 0.5}, + ]} + self.assertFalse(provider_response_ok('googleAi', 200, json.dumps(payload))) + self.assertIsNone(google_ai_model_quota(payload)) + with self.assertRaises(ValueError): + google_ai_quota_periods(payload) + + def test_legacy_per_model_buckets_are_a_valid_fallback_when_models_endpoint_is_unavailable(self): + buckets = {'buckets': [ + {'modelId': 'gemini-2.5-pro', 'remainingFraction': 1}, + {'modelId': 'gemini-3.8-flash', 'remainingFraction': 0.25}, + ]} + _, fake = self._fake_google({'https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota': buckets}) + with mock.patch('server._google_opener', return_value=None), mock.patch('server.urlopen', side_effect=fake): + code, body, error = execute_google_ai({'refreshToken': 'REDACTED'}) + self.assertEqual((code, error), (200, '')) + self.assertEqual(google_ai_model_quota(json.loads(body))['remainingPercent'], 25) + + def test_model_selection_prefers_exact_id_then_alias_not_highest_remaining(self): + payload = model_quota(remaining=0.7) + payload['models'].update({ + 'gemini-3.8-flash-high': {'quotaInfo': {'remainingFraction': 1}}, + 'gemini-3.8-flash': {'quotaInfo': {'remainingFraction': 0.2}}, + 'gemini-2.5-pro': {'quotaInfo': {'remainingFraction': 1}}, + 'claude-sonnet-4-6': {'quotaInfo': {'remainingFraction': 1}}, + }) + self.assertEqual(google_ai_model_quota(payload), { + 'modelId': 'gemini-3.8-flash', 'remainingPercent': 20, 'resetAt': None, + }) + del payload['models']['gemini-3.8-flash'] + self.assertEqual(google_ai_model_quota(payload)['modelId'], 'gemini-3.8-flash-tiered') + del payload['models']['gemini-3.8-flash-tiered'] + self.assertEqual(google_ai_model_quota(payload)['modelId'], 'gemini-3.8-flash-high') + + def test_latest_available_gemini_version_wins_over_fixed_flash_and_larger_remaining(self): + payload = model_quota(remaining=1) + payload['models'].update({ + 'gemini-3.9-pro': {'quotaInfo': {'remainingFraction': 1}}, + 'gemini-3.10-pro': {'quotaInfo': {'remainingFraction': 0}}, + 'gemini-9-pro': {'disabled': True, 'quotaInfo': {'remainingFraction': 1}}, + 'gemini-8-pro': {'available': False, 'quotaInfo': {'remainingFraction': 1}}, + 'gemini-7-pro': {'isInternal': True, 'quotaInfo': {'remainingFraction': 1}}, + }) + payload['buckets'] = [{'modelId': 'gemini-9-pro', 'remainingFraction': 1}] + self.assertEqual(google_ai_model_quota(payload), { + 'modelId': 'gemini-3.10-pro', 'remainingPercent': 0, 'resetAt': None, + }) + self.assertTrue(provider_response_ok('googleAi', 200, json.dumps(payload))) + + def test_refresh_preserves_current_public_model_catalog_with_new_gemini_and_claude(self): + catalog = model_quota('gemini-3.10-pro', 0.2) + catalog['models']['claude-sonnet-5-5-medium'] = { + 'displayName': 'Claude Sonnet 5.5 (Medium)', + 'quotaInfo': {'remainingFraction': 0.75, 'resetTime': '2026-12-01T05:00:00Z'}, + } + _, fake = self._fake_google({ + 'https://cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels': catalog, + 'https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary': quota(), + }) + with mock.patch('server._google_opener', return_value=None), mock.patch('server.urlopen', side_effect=fake): + code, body, error = execute_google_ai({'refreshToken': 'REDACTED'}) + self.assertEqual((code, error), (200, '')) + self.assertEqual(json.loads(body)['models'], catalog['models']) + self.assertEqual(google_ai_quota_periods(json.loads(body))['weekly']['remainingPercent'], 40) + self.assertEqual(google_ai_model_quota(json.loads(body))['modelId'], 'gemini-3.10-pro') + + def test_invalid_summary_does_not_hide_valid_model_fallback(self): + payload = model_quota() + payload.update(quota(five_hour=None, weekly=None)) + _, fake = self._fake_google({'https://cloudcode-pa.googleapis.com': payload}) + with mock.patch('server._google_opener', return_value=None), mock.patch('server.urlopen', side_effect=fake): + code, body, error = execute_google_ai({'refreshToken': 'REDACTED'}) + self.assertEqual((code, error), (200, '')) + self.assertIsNotNone(google_ai_model_quota(json.loads(body))) + + def test_model_zero_quota_is_valid_but_invalid_values_and_errors_are_not(self): + self.assertEqual(google_ai_model_quota(model_quota(remaining=0)), { + 'modelId': 'gemini-3.8-flash-tiered', 'remainingPercent': 0, 'resetAt': None, + }) + self.assertTrue(provider_response_ok('googleAi', 200, json.dumps(model_quota(remaining=0)))) + for value in (None, True, False, '', ' ', 'invalid', float('nan'), float('inf'), -0.1, 1.1): + with self.subTest(value=value): + payload = model_quota(remaining=value) + self.assertIsNone(google_ai_model_quota(payload)) + self.assertFalse(provider_response_ok('googleAi', 200, json.dumps(payload))) + for payload in [dict(model_quota(), error={'message': 'fixture failure'}), + {'data': dict(model_quota(), success=False)}]: + self.assertFalse(provider_response_ok('googleAi', 200, json.dumps(payload))) + + def test_model_fallback_never_invents_rotation_windows(self): + with self.assertRaises(ValueError): + google_ai_quota_periods(model_quota()) + with mock.patch('server.execute_google_ai', return_value=(200, json.dumps(model_quota()), '')): + result = query_agy_quotas({'acc_fixture': {'source': 'googleAi', 'refreshToken': 'REDACTED'}}, {}, ['acc_fixture']) + self.assertFalse(result['ok']) + self.assertIsNone(result['accounts']['acc_fixture']['fiveHour']) + self.assertIsNone(result['accounts']['acc_fixture']['weekly']) + + def test_failed_google_refresh_keeps_last_successful_agron_cache(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + accounts = {'acc_fixture': {'source': 'googleAi', 'refreshToken': 'REDACTED'}} + cached = {'acc_fixture': {'ok': True, 'status': 200, 'body': json.dumps(agron_quota()), + 'error': '', 'updatedAt': '2026-10-22T00:00:00Z'}} + (root / 'requests.json').write_text(json.dumps(accounts)) + (root / 'results.json').write_text(json.dumps(cached)) + + class Handler(DashboardHandler): + def log_message(self, *_): + pass + + for name in ('requests', 'results', 'snapshot', 'credentials', 'order', 'hidden'): + setattr(Handler, name + '_path', root / (name + '.json')) + httpd = ThreadingHTTPServer(('127.0.0.1', 0), Handler) + thread = threading.Thread(target=httpd.serve_forever, daemon=True) + thread.start() + try: + request = Request(f'http://127.0.0.1:{httpd.server_port}/api/refresh', data=b'{}', + headers={'Content-Type': 'application/json'}) + body = json.dumps(agron_quota(weekly=None, five_hour=None, model_remaining=None)) + with mock.patch('server.execute_google_ai', return_value=(200, body, '')): + with urlopen(request, timeout=5) as response: + result = json.load(response) + self.assertFalse(result['acc_fixture']['ok']) + self.assertEqual(json.loads((root / 'results.json').read_text()), cached) + self.assertEqual(json.loads((root / 'requests.json').read_text()), accounts) + finally: + httpd.shutdown() + httpd.server_close() + thread.join(timeout=5) + + def test_deadline_expires_before_network_request(self): + with mock.patch('server.time.monotonic', return_value=50), mock.patch('server.urlopen') as call: + with self.assertRaises(TimeoutError): + execute_google_ai({'refreshToken': 'REDACTED'}, deadline=49) + call.assert_not_called() + + def test_endpoint_preserves_all_state_bytes_and_rejects_invalid_selection(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + paths = {name: root / (name + '.json') for name in ( + 'requests', 'credentials', 'results', 'snapshot', 'order', 'hidden', + )} + for name, path in paths.items(): + value = {'acc_alpha': {'source': 'googleAi', 'refreshToken': 'REDACTED'}} if name == 'requests' else {'fixture': name} + path.write_text(json.dumps(value) + '\n') + before = {name: path.read_bytes() for name, path in paths.items()} + + class Handler(DashboardHandler): + def log_message(self, *_): + pass + + for name, path in paths.items(): + setattr(Handler, name + '_path', path) + httpd = ThreadingHTTPServer(('127.0.0.1', 0), Handler) + thread = threading.Thread(target=httpd.serve_forever, daemon=True) + thread.start() + try: + url = f'http://127.0.0.1:{httpd.server_port}/api/agy/quotas' + body = json.dumps({'accountIds': ['acc_alpha', 'acc_alpha']}).encode() + with mock.patch('server.execute_google_ai', return_value=(200, json.dumps(quota()), '')) as call: + with urlopen(Request(url, data=body, headers={'Content-Type': 'application/json'}), timeout=5) as response: + output = json.load(response) + self.assertEqual(call.call_count, 1) + self.assertEqual(list(output['accounts']), ['acc_alpha']) + self.assertEqual({name: path.read_bytes() for name, path in paths.items()}, before) + for ids in ([], 'acc_alpha', [None], [''], ['acc_alpha'] * 21): + with self.subTest(ids=ids), self.assertRaises(HTTPError) as caught: + urlopen(Request(url, data=json.dumps({'accountIds': ids}).encode()), timeout=5) + self.assertEqual(caught.exception.code, 400) + caught.exception.close() + finally: + httpd.shutdown() + httpd.server_close() + thread.join(timeout=5) + + +class RotationTests(unittest.TestCase): + def setUp(self): + self.rotation = runpy.run_path(str(Path(__file__).resolve().parents[1] / 'scripts/agy_quota_rotate.py'))['select_dashboard_profile'].__globals__ + self.profiles = dict.fromkeys(['alpha', 'beta', 'beta_alias']) + self.config = {'dashboardUrl': 'http://localhost:8080', 'accountIds': { + 'alpha': 'acc_alpha', 'beta': 'acc_beta', 'beta_alias': 'acc_beta', + }} + self.now = datetime(2026, 1, 1, tzinfo=timezone.utc) + + def response(self, alpha, beta, beta_weekly=100, alpha_weekly=100): + def row(value, weekly=None): + return {'ok': True, 'updatedAt': self.now.isoformat(), + 'fiveHour': {'remainingPercent': value}, + 'weekly': None if weekly is None else {'remainingPercent': weekly}} + return {'ok': True, 'accounts': {'acc_alpha': row(alpha, alpha_weekly), 'acc_beta': row(beta, beta_weekly)}} + + def select(self, response, current='alpha'): + self.rotation['query_dashboard'] = mock.Mock(return_value=response) + with redirect_stdout(StringIO()): + result = self.rotation['select_dashboard_profile'](self.profiles, current, self.config, self.now) + self.rotation['query_dashboard'].assert_called_once_with(self.config, ['acc_alpha', 'acc_beta']) + return result + + def model_row(self, remaining, reset_minutes=None, model_id='gemini-3.8-flash-tiered'): + fallback = {'modelId': model_id, 'remainingPercent': remaining} + if reset_minutes is not None: + fallback['resetAt'] = (self.now + timedelta(minutes=reset_minutes)).isoformat() + return {'ok': False, 'updatedAt': None, 'fiveHour': None, 'weekly': None, + 'fallback': fallback, + 'error': 'Google AI returned no explicit 5-hour window; only a per-model quota is available'} + + def test_model_only_quota_is_usable_when_no_window_account_exists(self): + response = {'ok': True, 'accounts': { + 'acc_alpha': self.model_row(40, 5), + 'acc_beta': self.model_row(90, 30), + }} + # Selection now depends on per-model values instead of falling back to + # the fixed hourly order. + self.assertEqual(self.select(response), ('beta', 90)) + + def test_model_quota_only_account_can_beat_a_depleted_window_account(self): + response = self.response(20, 90, 30, 10) + response['accounts']['acc_beta']['ok'] = False + response['accounts']['acc_beta']['fiveHour'] = None + response['accounts']['acc_beta']['weekly'] = None + response['accounts']['acc_beta']['fallback'] = {'modelId': 'gemini-3.8-flash-tiered', 'remainingPercent': 99} + # acc_alpha is window-limited by weekly (10%), while acc_beta only reports + # its per-model pool (99%). Rotation must pick the account with more + # headroom instead of being stuck on the window-limited one. + self.assertEqual(self.select(response), ('beta', 99)) + + def test_model_fallback_can_be_disabled(self): + self.config['modelFallback'] = False + response = {'ok': True, 'accounts': { + 'acc_alpha': self.model_row(40, 5), + 'acc_beta': self.model_row(90, 30), + }} + with self.assertRaises(RuntimeError): + self.select(response) + + def test_model_only_accounts_still_tie_break_on_reset(self): + response = {'ok': True, 'accounts': { + 'acc_alpha': self.model_row(80, 60), + 'acc_beta': self.model_row(80, 10), + }} + self.assertEqual(self.select(response, current='alpha'), ('beta', 80)) + + def test_selection_is_limited_by_the_more_depleted_quota_window(self): + self.assertEqual(self.select(self.response(20, 90, 5)), ('alpha', 20)) + self.assertEqual(self.select(self.response(90, 30, 95, 10)), ('beta', 30)) + + def test_equal_combined_scores_keep_current_despite_different_window_values(self): + self.assertEqual(self.select(self.response(20, 90, 20, 95), current='beta_alias'), ('beta_alias', 20)) + + def test_missing_weekly_is_skipped_without_assuming_full_quota(self): + self.assertEqual(self.select(self.response(100, 70, 50, None)), ('beta', 50)) + with self.assertRaises(RuntimeError): + self.select(self.response(100, 70, None, None)) + + def test_equal_quota_prefers_five_hour_reset_soonest_over_current_account(self): + response = self.response(80, 80) + for aid, minutes in (('acc_alpha', 120), ('acc_beta', 10)): + response['accounts'][aid]['fiveHour']['resetAt'] = (self.now + timedelta(minutes=minutes)).isoformat() + response['accounts'][aid]['weekly']['resetAt'] = (self.now + timedelta(days=5)).isoformat() + self.assertEqual(self.select(response, current='alpha'), ('beta', 80)) + + def test_weekly_reset_also_participates_in_tie_breaking(self): + response = self.response(80, 80) + for row in response['accounts'].values(): + row['fiveHour']['resetAt'] = (self.now + timedelta(hours=4)).isoformat() + response['accounts']['acc_alpha']['weekly']['resetAt'] = (self.now + timedelta(minutes=5)).isoformat() + response['accounts']['acc_beta']['weekly']['resetAt'] = (self.now + timedelta(days=2)).isoformat() + self.assertEqual(self.select(response, current='beta'), ('alpha', 80)) + + def test_equal_quota_and_reset_time_preserve_current_alias(self): + response = self.response(80, 80) + for row in response['accounts'].values(): + row['fiveHour']['resetAt'] = (self.now + timedelta(hours=2)).isoformat() + self.assertEqual(self.select(response, current='beta_alias'), ('beta_alias', 80)) + + def test_unknown_reset_time_is_not_fabricated_as_zero(self): + response = self.response(80, 80) + response['accounts']['acc_alpha']['fiveHour']['resetAt'] = 'invalid' + response['accounts']['acc_beta']['fiveHour']['resetAt'] = (self.now + timedelta(minutes=30)).isoformat() + self.assertEqual(self.select(response, current='alpha'), ('beta', 80)) + self.assertIsNone(self.rotation['reset_seconds']({'resetAt': None}, self.now)) + + def test_higher_quota_precedes_earlier_reset_and_due_reset_does_not_restore_quota(self): + response = self.response(90, 80) + response['accounts']['acc_alpha']['fiveHour']['resetAt'] = (self.now + timedelta(hours=5)).isoformat() + response['accounts']['acc_beta']['fiveHour']['resetAt'] = (self.now - timedelta(minutes=1)).isoformat() + self.assertEqual(self.select(response, current='beta'), ('alpha', 90)) + self.assertEqual(self.rotation['reset_seconds'](response['accounts']['acc_beta']['fiveHour'], self.now), 0) + + def test_duplicate_alias_and_equal_quota_keep_current_account(self): + self.assertEqual(self.select(self.response(90, 90), current='beta_alias'), ('beta_alias', 90)) + + def test_known_exhausted_weekly_account_is_not_usable(self): + self.assertEqual(self.select(self.response(20, 90, 0)), ('alpha', 20)) + + def test_all_zero_quotas_remain_valid_and_keep_current(self): + self.assertEqual(self.select(self.response(0, 0), current='beta'), ('beta', 0)) + + def test_partial_failure_uses_successful_account(self): + response = self.response(30, 100) + response['accounts']['acc_beta'] = {'ok': False} + self.assertEqual(self.select(response), ('alpha', 30)) + + def test_pending_login_identity_is_skipped_then_automatically_becomes_ready(self): + self.config['identityHashes'] = {'alpha': hashlib.sha256(b'new-subject').hexdigest()} + self.profiles = {alias: {'info': {'sub': 'old-subject'}} for alias in self.profiles} + self.assertEqual(self.select(self.response(100, 20)), ('beta', 20)) + self.profiles['alpha']['info']['sub'] = 'new-subject' + self.assertEqual(self.select(self.response(100, 20)), ('alpha', 100)) + + def test_stale_invalid_and_unsuccessful_responses_are_failures(self): + for change in ('stale', 'future', 'invalid', 'failed', 'missing'): + response = self.response(30, 100) + for row in response['accounts'].values(): + if change == 'stale': row['updatedAt'] = (self.now - timedelta(minutes=3)).isoformat() + if change == 'future': row['updatedAt'] = (self.now + timedelta(minutes=2)).isoformat() + if change == 'invalid': row['fiveHour']['remainingPercent'] = None + if change == 'failed': row['ok'] = False + if change == 'missing': row.pop('fiveHour') + with self.subTest(change=change), self.assertRaises(RuntimeError): + self.select(response) + + def test_hourly_fallback_keeps_the_original_wraparound(self): + for hour in range(24): + self.assertEqual(self.rotation['target_profile'](self.profiles, hour)[0], list(self.profiles)[hour % 3]) + + def test_busy_account_lock_skips_without_querying_or_switching(self): + manager = {'account_lock': mock.Mock(side_effect=BlockingIOError)} + self.rotation['run_locked'] = mock.Mock() + with redirect_stdout(StringIO()): + self.assertEqual(self.rotation['run_hourly'](manager), 0) + self.rotation['run_locked'].assert_not_called() + + def run_with_fixture_manager(self, query, hour=1, identity_hashes=None, switch_error=None): + """Exercise the real decision, switch and verification sequence in isolation.""" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + config = {**self.config, 'identityHashes': identity_hashes or {}} + path = root / 'rotation.json' + path.write_text(json.dumps(config)) + self.rotation['CONFIG_PATH'] = path + self.rotation['query_dashboard'] = query + self.rotation['probe_models'] = mock.Mock(return_value=(0, 'gemini-fixture-model')) + active = {'active': 'alpha', 'desired_active': 'alpha'} + profiles = {alias: {'token_path': alias, 'info': {'sub': 'old-subject'}} for alias in self.profiles} + installed = ['alpha'] + + def switch(alias): + if switch_error: + raise switch_error + installed[0] = alias + active.update(active=alias, desired_active=alias) + + def verify(expected): + if installed[0] != expected: + raise RuntimeError('fixture identity mismatch') + + manager = {'SWITCH_DIR': root, 'auto_init': mock.Mock(), 'sync_live_token': mock.Mock(), + 'list_profiles': lambda: profiles, 'get_config': lambda: active, + 'read_token_data': lambda path: path, 'cmd_switch': mock.Mock(side_effect=switch), + 'verify_live_token': mock.Mock(side_effect=verify)} + captured = StringIO() + with redirect_stdout(captured): + try: + result = self.rotation['run_locked'](manager, self.now.replace(hour=hour)) + except RuntimeError as error: + result = error + return result, dict(active), manager['cmd_switch'], captured.getvalue() + + def test_real_dashboard_decision_installs_and_verifies_the_maximum(self): + query = mock.Mock(return_value=self.response(20, 90)) + code, active, switch, output = self.run_with_fixture_manager(query, hour=0) + self.assertEqual(code, 0) + self.assertEqual(active, {'active': 'beta', 'desired_active': 'beta'}) + switch.assert_called_once_with('beta') + self.assertIn('source=dashboard target=beta verified=true', output) + + def test_transport_failure_runs_the_original_hourly_switch(self): + query = mock.Mock(side_effect=OSError('fixture unreachable')) + code, active, switch, output = self.run_with_fixture_manager(query) + self.assertEqual(code, 0) + self.assertEqual(active['active'], 'beta') + switch.assert_called_once_with('beta') + self.assertIn('FALLBACK', output) + self.assertIn('source=hourly-fallback target=beta verified=true', output) + + def test_pending_identity_cannot_be_selected_by_hourly_fallback(self): + query = mock.Mock(side_effect=OSError('fixture unreachable')) + result, active, switch, _ = self.run_with_fixture_manager( + query, identity_hashes={'beta': hashlib.sha256(b'new-subject').hexdigest()}, + ) + self.assertIsInstance(result, RuntimeError) + self.assertEqual(active['active'], 'alpha') + switch.assert_not_called() + self.rotation['probe_models'].assert_not_called() + + def test_switch_failure_does_not_fall_back_after_a_successful_query(self): + query = mock.Mock(return_value=self.response(20, 90)) + result, active, switch, output = self.run_with_fixture_manager(query, hour=0, switch_error=RuntimeError('fixture Keychain failure')) + self.assertIsInstance(result, RuntimeError) + self.assertEqual(active['active'], 'alpha') + switch.assert_called_once_with('beta') + self.assertNotIn('FALLBACK', output) + + +class AlertTests(unittest.TestCase): + def setUp(self): + self.rotation = runpy.run_path(str(Path(__file__).resolve().parents[1] / 'scripts/agy_quota_rotate.py'))['select_dashboard_profile'].__globals__ + self.directory = tempfile.TemporaryDirectory() + self.path = Path(self.directory.name) / 'alert.json' + self.rotation['ALERT_PATH'] = self.path + self.now = datetime(2026, 1, 1, tzinfo=timezone.utc) + + def tearDown(self): + self.directory.cleanup() + + def run_once(self, condition, now=None, config=None): + output = StringIO() + with redirect_stdout(output): + self.rotation['alert_sequence'](condition, config or {}, now or self.now, 1) + return output.getvalue() + + def test_healthy_run_clears_the_streak_file(self): + self.path.write_text(json.dumps({'runs': 5})) + self.assertEqual(self.run_once(False), '') + self.assertFalse(self.path.exists()) + + def test_degraded_runs_stay_quiet_until_the_threshold(self): + self.path.unlink(missing_ok=True) + first = self.run_once(True, config={'alertAfterRuns': 3}) + second = self.run_once(True, config={'alertAfterRuns': 3}) + self.assertNotIn('ALERT ', first + second) + self.assertIn('DEGRADED runs=2/3', second) + + def test_threshold_run_emits_one_alert_per_hour(self): + config = {'alertAfterRuns': 2} + self.run_once(True, config=config) + third = self.run_once(True, config=config) + self.assertIn('ALERT runs=2', third) + # A second unhealthy run within the hour must not repeat the alert. + later = self.run_once(True, now=self.now + timedelta(minutes=10), config=config) + self.assertNotIn('ALERT ', later) + # After an hour it may alert again. + self.assertIn('ALERT runs=4', self.run_once(True, now=self.now + timedelta(hours=2), config=config)) + + def test_invalid_threshold_falls_back_to_three(self): + for value in (0, -1, True, 'x', None): + self.path.unlink(missing_ok=True) + self.assertNotIn('ALERT ', self.run_once(True, config={'alertAfterRuns': value})) + self.path.unlink(missing_ok=True) + self.assertIn('DEGRADED runs=1/3', self.run_once(True, config={'alertAfterRuns': 'x'})) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_claude.py b/tests/test_claude.py new file mode 100644 index 0000000..598d8b6 --- /dev/null +++ b/tests/test_claude.py @@ -0,0 +1,201 @@ +import hashlib +import json +import tempfile +import unittest +from io import BytesIO +from pathlib import Path +from unittest.mock import patch +from urllib.error import HTTPError, URLError + +from server import ( + CLAUDE_USAGE_URL, DashboardHandler, _NoManagementRedirect, _cliproxy_management, + execute_claude_usage, list_claude_oauth_accounts, load_snapshot, + provider_response_ok, save_snapshot, +) + + +AUTH_FILE = {"id": "claude-fixture.json", "name": "claude-fixture.json", "provider": "claude", + "account_type": "oauth", "auth_index": "fixture-current-index", "label": "Fixture Claude", + "email": "fixture@example.com", "disabled": False} +REFERENCE = hashlib.sha256(b"claude\0claude-fixture.json").hexdigest() +QUOTA = {"five_hour": {"utilization": 2, "resets_at": "2026-10-17T12:00:00Z"}, + "seven_day": {"utilization": 0, "resets_at": None}, "seven_day_opus": None} +CATALOG = {REFERENCE: {"authIndex": "fixture-current-index", "label": "Fixture Claude", "disabled": False}} + + +class ClaudeTransportTest(unittest.TestCase): + def test_requires_server_configuration_and_restricts_base_to_an_origin(self): + with patch.dict("os.environ", {"CLIPROXYAPI_BASE_URL": "", "CLIPROXYAPI_MANAGEMENT_KEY": ""}): + with self.assertRaisesRegex(ValueError, "requires CLIPROXYAPI"): + _cliproxy_management("auth-files") + for base in ("file:///tmp/test", "http://user:REDACTED@example.com", "https://example.com/path", "https://example.com?key=REDACTED"): + with self.subTest(base=base), patch.dict("os.environ", {"CLIPROXYAPI_BASE_URL": base, "CLIPROXYAPI_MANAGEMENT_KEY": "REDACTED_MANAGEMENT"}), self.assertRaises(ValueError): + _cliproxy_management("auth-files") + + def test_management_uses_server_key_and_no_redirect_or_proxy_environment(self): + class Response: + status = 200 + def __enter__(self): return self + def __exit__(self, *args): pass + def read(self, size): return b'{"files":[]}' + + with patch.dict("os.environ", {"CLIPROXYAPI_BASE_URL": "http://cliproxy.example.lan:8317/", "CLIPROXYAPI_MANAGEMENT_KEY": "REDACTED_MANAGEMENT"}), patch("server.build_opener") as build: + build.return_value.open.return_value = Response() + self.assertEqual(_cliproxy_management("auth-files"), {"files": []}) + request = build.return_value.open.call_args.args[0] + self.assertEqual(request.full_url, "http://cliproxy.example.lan:8317/v0/management/auth-files") + self.assertEqual(request.get_header("Authorization"), "Bearer REDACTED_MANAGEMENT") + self.assertEqual(build.call_args.args[0].proxies, {}) + self.assertIsInstance(build.call_args.args[1], _NoManagementRedirect) + self.assertIsNone(build.call_args.args[1].redirect_request(None, None, 302, "", {}, "http://other.example")) + + def test_management_errors_do_not_leak_provider_bodies_or_credentials(self): + errors = [HTTPError("http://example.com", 401, "REDACTED_SECRET", {}, BytesIO(b'REDACTED_SECRET')), + URLError("REDACTED_SECRET"), TimeoutError("REDACTED_SECRET")] + for error in errors: + with self.subTest(error=type(error).__name__), patch.dict("os.environ", {"CLIPROXYAPI_BASE_URL": "https://cliproxy.example.com", "CLIPROXYAPI_MANAGEMENT_KEY": "REDACTED_MANAGEMENT"}), patch("server.build_opener") as build: + build.return_value.open.side_effect = error + with self.assertRaises(ValueError) as raised: + _cliproxy_management("auth-files") + self.assertNotIn("REDACTED_SECRET", str(raised.exception)) + + def test_discovers_only_claude_oauth_and_uses_stable_identity_not_transient_index(self): + files = [AUTH_FILE, dict(AUTH_FILE, provider="codex"), dict(AUTH_FILE, account_type="api_key"), None] + with patch("server._cliproxy_management", return_value={"files": files}): + self.assertEqual(list_claude_oauth_accounts(), CATALOG) + with patch("server._cliproxy_management", return_value={"files": [dict(AUTH_FILE, auth_index="fixture-rotated-index")]}): + updated = list_claude_oauth_accounts() + self.assertEqual(list(updated), [REFERENCE]) + self.assertEqual(updated[REFERENCE]["authIndex"], "fixture-rotated-index") + + def test_queries_fixed_usage_endpoint_with_token_placeholder_and_filters_cached_body(self): + payload = dict(QUOTA, spend={"private": "REDACTED_SECRET"}) + with patch("server._cliproxy_management", return_value={"status_code": 200, "header": {"set-cookie": "REDACTED_SECRET"}, "body": json.dumps(payload)}) as management: + status, body, error = execute_claude_usage({"claudeAccountId": REFERENCE}, CATALOG) + self.assertEqual(status, 200) + self.assertEqual(error, "") + self.assertNotIn("REDACTED_SECRET", body) + call = management.call_args.args[1] + self.assertEqual(call["authIndex"], "fixture-current-index") + self.assertEqual(call["url"], CLAUDE_USAGE_URL) + self.assertEqual(call["method"], "GET") + self.assertEqual(call["header"]["Authorization"], "Bearer $TOKEN$") + self.assertTrue(provider_response_ok("claude", status, body)) + + def test_nested_http_failure_and_malformed_quota_are_failures_with_sanitized_errors(self): + responses = [ + {"status_code": 401, "body": "REDACTED_SECRET"}, + {"status_code": 429, "body": "REDACTED_SECRET"}, + {"status_code": 200, "body": '{"type":"error","error":{"message":"REDACTED_SECRET"}}'}, + {"status_code": 200, "body": "not JSON REDACTED_SECRET"}, + {"status_code": 200, "body": '{"five_hour":{"utilization":null}}'}, + {"status_code": 200, "body": '{"five_hour":{"utilization":false}}'}, + {"status_code": False, "body": "REDACTED_SECRET"}, + ] + for response in responses: + with self.subTest(response=response), patch("server._cliproxy_management", return_value=response): + status, body, error = execute_claude_usage({"claudeAccountId": REFERENCE}, CATALOG) + self.assertNotEqual(status, 200) + self.assertEqual(body, "") + self.assertNotIn("REDACTED_SECRET", error) + + def test_disabled_or_removed_account_does_not_call_upstream(self): + for catalog in ({}, {REFERENCE: dict(CATALOG[REFERENCE], disabled=True)}): + with patch("server._cliproxy_management") as management: + status, _, _ = execute_claude_usage({"claudeAccountId": REFERENCE}, catalog) + self.assertIn(status, (403, 404)) + management.assert_not_called() + + def test_hundred_percent_quota_is_success_and_empty_data_is_not(self): + self.assertTrue(provider_response_ok("claude", 200, '{"five_hour":{"utilization":100}}')) + for body in ('{}', '[]', 'null', '{"five_hour":{"utilization":null}}', '{"error":"unauthorized"}'): + self.assertFalse(provider_response_ok("claude", 200, body)) + + +class ClaudeApiTest(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.paths = {name + "_path": Path(temp.name) / (name + ".json") + for name in ("requests", "results", "snapshot", "order", "hidden", "credentials")} + self.existing = {"acc_fixture_other": {"source": "kimi", "label": "Keep", "curl": "REDACTED_OTHER"}} + for name, path in self.paths.items(): + value = self.existing if name == "requests_path" else {"fixture": name} + save_snapshot(path, value) + self.before = {name: path.read_bytes() for name, path in self.paths.items()} + + def post(self, route, payload): + handler = DashboardHandler.__new__(DashboardHandler) + handler.path = route + body = json.dumps(payload).encode() + handler.headers = {"Content-Length": str(len(body))} + handler.rfile = BytesIO(body) + handler.send_json = lambda value: setattr(handler, "captured", value) + handler.send_error = lambda code, message=None: setattr(handler, "error", (code, message)) + with patch.multiple(DashboardHandler, **self.paths): + DashboardHandler.do_POST(handler) + return handler + + def assert_untouched(self, except_names=()): + for name, path in self.paths.items(): + if name not in except_names: + self.assertEqual(path.read_bytes(), self.before[name], name) + + def test_sync_is_additive_idempotent_and_preserves_existing_labels_and_user_state(self): + with patch("server.list_claude_oauth_accounts", return_value=CATALOG): + first = self.post("/api/claude/accounts", {}) + self.assertEqual(first.captured["added"], 1) + account_id = first.captured["accountIds"][0] + accounts = load_snapshot(self.paths["requests_path"]) + self.assertEqual(accounts["acc_fixture_other"], self.existing["acc_fixture_other"]) + self.assertEqual(list(accounts), ["acc_fixture_other", account_id]) + self.assertEqual(accounts[account_id]["claudeAccountId"], REFERENCE) + self.assertNotIn("authIndex", accounts[account_id]) + self.assert_untouched(("requests_path",)) + self.post("/api/requests", {"id": account_id, "label": "Custom label", "curl": ""}) + updated = self.paths["requests_path"].read_bytes() + with patch("server.list_claude_oauth_accounts", return_value=CATALOG): + second = self.post("/api/claude/accounts", {}) + self.assertEqual(second.captured["added"], 0) + self.assertEqual(second.captured["accountIds"], [account_id]) + self.assertEqual(self.paths["requests_path"].read_bytes(), updated) + self.assertEqual(load_snapshot(self.paths["requests_path"])[account_id]["claudeAccountId"], REFERENCE) + + def test_sync_skips_disabled_accounts_and_failure_does_not_write(self): + with patch("server.list_claude_oauth_accounts", return_value={REFERENCE: dict(CATALOG[REFERENCE], disabled=True)}): + result = self.post("/api/claude/accounts", {}) + self.assertEqual(result.captured["accountIds"], []) + self.assert_untouched() + with patch("server.list_claude_oauth_accounts", side_effect=ValueError("CLIProxyAPI is unavailable")): + result = self.post("/api/claude/accounts", {}) + self.assertEqual(result.error[0], 400) + self.assert_untouched() + + def test_refresh_failure_preserves_success_cache_and_other_accounts(self): + accounts = dict(self.existing, acc_fixture_claude={"source": "claude", "claudeAccountId": REFERENCE, "curl": ""}) + save_snapshot(self.paths["requests_path"], accounts) + cache = {"acc_fixture_claude": {"ok": True, "body": json.dumps(QUOTA), "status": 200, "updatedAt": "2026-01-01"}} + save_snapshot(self.paths["results_path"], cache) + saved = {name: path.read_bytes() for name, path in self.paths.items()} + with patch("server.list_claude_oauth_accounts", return_value=CATALOG), patch("server._cliproxy_management", return_value={"status_code": 401, "body": "REDACTED_SECRET"}), patch("server.execute_curl") as curl: + result = self.post("/api/refresh", {"accountIds": ["acc_fixture_claude"]}) + curl.assert_not_called() + self.assertFalse(result.captured["acc_fixture_claude"]["ok"]) + self.assertEqual(result.captured["acc_fixture_claude"]["status"], 401) + self.assertNotIn("REDACTED_SECRET", json.dumps(result.captured)) + for name, path in self.paths.items(): + self.assertEqual(path.read_bytes(), saved[name], name) + + def test_multiple_claude_accounts_resolve_catalog_once_and_retain_other_cache(self): + accounts = dict(self.existing, acc_fixture_a={"source": "claude", "claudeAccountId": REFERENCE}, acc_fixture_b={"source": "claude", "claudeAccountId": REFERENCE}) + save_snapshot(self.paths["requests_path"], accounts) + with patch("server.list_claude_oauth_accounts", return_value=CATALOG) as catalog, patch("server._cliproxy_management", return_value={"status_code": 200, "body": json.dumps(QUOTA)}), patch("server.execute_curl") as curl: + result = self.post("/api/refresh", {"accountIds": ["acc_fixture_a", "acc_fixture_b"]}) + catalog.assert_called_once() + curl.assert_not_called() + self.assertTrue(all(v["ok"] for v in result.captured.values())) + self.assertEqual(load_snapshot(self.paths["results_path"])["fixture"], "results_path") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_qianwen.py b/tests/test_qianwen.py new file mode 100644 index 0000000..dceb776 --- /dev/null +++ b/tests/test_qianwen.py @@ -0,0 +1,199 @@ +import json +import shlex +import tempfile +import unittest +from io import BytesIO +from pathlib import Path +from unittest.mock import patch +from urllib.parse import parse_qs + +from server import ( + DashboardHandler, + build_http_request, + load_snapshot, + merge_qianwen_verification_curl, + parse_curl, + save_snapshot, +) + + +USAGE_URL = ( + "https://cs-data.qianwenai.com/data/api.json?product=sfm_bailian" + "&action=BroadScopeAspnGateway" + "&api=zeldaHttp.apikeyMgr.%2Ftokenplan%2Fpersonal%2Fapi%2Fv2%2Fusage" +) +SAVED_BODY = 'product=sfm_bailian¶ms=%7B%22Data%22%3A%7B%22scope%22%3A%22saved%22%7D%7D&sec_token=REDACTED_OLD®ion=cn-beijing&blank=' +NEW_BODY = 'params=%7B%22Data%22%3A%7B%22scope%22%3A%22different%22%7D%7D&sec_token=REDACTED_NEW%2B%2F%3D' + + +def usage_curl(cookie="login_qianwenai_ticket=REDACTED_NEW", body=NEW_BODY, url=USAGE_URL, content_type="application/x-www-form-urlencoded"): + args = ["curl", "--url", url, "-H", "content-type: " + content_type, "-b", cookie] + if body is not None: + args.extend(["--data-raw", body]) + return shlex.join(args) + + +class QianwenVerificationTest(unittest.TestCase): + def setUp(self): + self.saved_curl = usage_curl("login_qianwenai_ticket=REDACTED_OLD", SAVED_BODY) + + def test_renews_cookie_and_sec_token_preserving_original_request_data(self): + existing_url = USAGE_URL + "&saved=value" + existing = usage_curl("login_qianwenai_ticket=REDACTED_OLD", SAVED_BODY, existing_url) + existing += " -H 'content-length: 99999' -H 'host: cs-data.qianwenai.com' -H 'connection: keep-alive'" + fresh = usage_curl() + " -H 'x-csrf-token: REDACTED_CSRF' -H 'content-length: 1'" + merged = merge_qianwen_verification_curl(existing, fresh) + url, args = parse_curl(merged) + request, _ = build_http_request(args) + self.assertEqual(url, existing_url) + self.assertEqual(request.get_method(), "POST") + self.assertEqual(request.get_header("Cookie"), "login_qianwenai_ticket=REDACTED_NEW") + self.assertEqual(request.get_header("X-csrf-token"), "REDACTED_CSRF") + self.assertEqual(request.data.decode(), SAVED_BODY.replace("sec_token=REDACTED_OLD", "sec_token=REDACTED_NEW%2B%2F%3D")) + for name in ("Content-length", "Host", "Connection"): + self.assertIsNone(request.get_header(name)) + self.assertNotIn("REDACTED_OLD", merged) + + def test_accepts_cookie_as_header_and_preserves_body_without_sec_token(self): + saved = usage_curl(body="product=sfm_bailian¶ms=%7B%7D") + fresh = shlex.join(["curl", USAGE_URL, "-H", "Cookie: login_qianwenai_ticket=REDACTED_HEADER"]) + request, _ = build_http_request(parse_curl(merge_qianwen_verification_curl(saved, fresh))[1]) + self.assertEqual(request.data, b"product=sfm_bailian¶ms=%7B%7D") + self.assertEqual(request.get_header("Cookie"), "login_qianwenai_ticket=REDACTED_HEADER") + + def test_adds_new_sec_token_when_saved_form_did_not_include_it(self): + saved = usage_curl(body="params=%7B%7D") + request, _ = build_http_request(parse_curl(merge_qianwen_verification_curl(saved, usage_curl()))[1]) + self.assertEqual(parse_qs(request.data.decode())["sec_token"], ["REDACTED_NEW+/="]) + self.assertEqual(parse_qs(request.data.decode())["params"], ["{}"]) + + def test_rejects_missing_cookie_or_missing_empty_or_duplicate_sec_token(self): + for fresh in ( + usage_curl(cookie=""), + shlex.join(["curl", USAGE_URL, "-H", "authorization: Bearer REDACTED"]), + usage_curl(body=None), + usage_curl(body="sec_token="), + usage_curl(body="sec_token=REDACTED_ONE&sec_token=REDACTED_TWO"), + ): + with self.subTest(fresh=fresh), self.assertRaises(ValueError): + merge_qianwen_verification_curl(self.saved_curl, fresh) + + def test_rejects_mismatched_endpoint_and_gateway_routing(self): + for url in ( + USAGE_URL.replace("sfm_bailian", "different"), + USAGE_URL.replace("BroadScopeAspnGateway", "different"), + USAGE_URL.replace("%2Fusage", "%2Fother"), + USAGE_URL + "&api=duplicate", + USAGE_URL.replace("/data/api.json", "/other/data/api.json"), + USAGE_URL.replace("qianwenai.com/", "qianwenai.com:8443/"), + USAGE_URL.replace("https://", "http://"), + "https://www.minimax.cn/backend/account/token_plan/remains_percent", + ): + with self.subTest(url=url), self.assertRaises(ValueError): + merge_qianwen_verification_curl(self.saved_curl, usage_curl(url=url)) + + def test_rejects_non_form_get_and_ambiguous_body_instead_of_losing_parameters(self): + for fresh in ( + usage_curl(content_type="application/json"), + usage_curl() + " -G", + usage_curl() + " -X GET", + usage_curl() + " --data 'sec_token=REDACTED_OTHER'", + ): + with self.subTest(fresh=fresh), self.assertRaises(ValueError): + merge_qianwen_verification_curl(self.saved_curl, fresh) + + +class QianwenApiTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.paths = {name + "_path": Path(self.temp.name) / (name + ".json") + for name in ("requests", "results", "snapshot", "order", "hidden", "credentials")} + self.accounts = { + "acc_fixture_qw": {"source": "qianwen", "label": "Fixture", "curl": usage_curl("login_qianwenai_ticket=REDACTED_OLD", SAVED_BODY), "updatedAt": "2026-01-01"}, + "acc_fixture_other": {"source": "kimi", "curl": "REDACTED_OTHER", "kimiRefreshToken": "REDACTED_REFRESH"}, + } + self.cache = {"acc_fixture_qw": {"ok": True, "status": 200, "body": '{"data":{"success":true,"DataV2":{"data":{"data":{"per1MonthPercentage":0.25}}}}}', "updatedAt": "2026-01-01"}} + save_snapshot(self.paths["requests_path"], self.accounts) + save_snapshot(self.paths["results_path"], self.cache) + save_snapshot(self.paths["order_path"], list(self.accounts)) + save_snapshot(self.paths["hidden_path"], ["acc_fixture_other"]) + for name in ("snapshot", "credentials"): + save_snapshot(self.paths[name + "_path"], {"fixture": name}) + self.before = {name: path.read_bytes() for name, path in self.paths.items()} + + def post(self, route, payload): + handler = DashboardHandler.__new__(DashboardHandler) + handler.path = route + body = json.dumps(payload).encode() + handler.headers = {"Content-Length": str(len(body))} + handler.rfile = BytesIO(body) + handler.send_json = lambda value: setattr(handler, "captured", value) + handler.send_error = lambda code, message=None: setattr(handler, "error", (code, message)) + with patch.multiple(DashboardHandler, **self.paths): + DashboardHandler.do_POST(handler) + return handler + + def assert_unchanged(self, except_paths=()): + for name, path in self.paths.items(): + if name not in except_paths: + self.assertEqual(path.read_bytes(), self.before[name], name) + + def test_updates_existing_account_without_touching_cached_or_other_user_state(self): + handler = self.post("/api/requests", {"id": "acc_fixture_qw", "qianwenVerificationCurl": usage_curl()}) + self.assertFalse(hasattr(handler, "error")) + self.assertEqual(handler.captured["id"], "acc_fixture_qw") + self.assertEqual(handler.captured["source"], "qianwen") + self.assertNotIn("REDACTED", json.dumps(handler.captured)) + saved = load_snapshot(self.paths["requests_path"]) + self.assertEqual(list(saved), list(self.accounts)) + self.assertEqual(saved["acc_fixture_other"], self.accounts["acc_fixture_other"]) + self.assertEqual(saved["acc_fixture_qw"]["label"], "Fixture") + request, _ = build_http_request(parse_curl(saved["acc_fixture_qw"]["curl"])[1]) + self.assertEqual(parse_qs(request.data.decode())["sec_token"], ["REDACTED_NEW+/="]) + self.assert_unchanged(except_paths=("requests_path",)) + + def test_rejects_wrong_missing_or_unknown_account_and_incomplete_credentials_without_writes(self): + for payload in ( + {"qianwenVerificationCurl": usage_curl()}, + {"id": "acc_fixture_unknown", "qianwenVerificationCurl": usage_curl()}, + {"id": "acc_fixture_other", "qianwenVerificationCurl": usage_curl()}, + {"id": "acc_fixture_qw", "qianwenVerificationCurl": ""}, + {"id": "acc_fixture_qw", "qianwenVerificationCurl": usage_curl(body=None)}, + ): + with self.subTest(payload=payload): + handler = self.post("/api/requests", payload) + self.assertEqual(handler.error[0], 400) + self.assert_unchanged() + + def test_targeted_login_failure_preserves_cache_and_does_not_refresh_other_accounts(self): + body = '{"code":"200","data":{"success":false,"errorCode":"BailianGateway.Login.NotLogined","errorMsg":"BailianGateway.Login.NotLogined"}}' + with patch("server.execute_curl", return_value=(200, body, "")) as execute, patch("server.refresh_kimi_access_token") as kimi: + handler = self.post("/api/refresh", {"accountIds": ["acc_fixture_qw"]}) + self.assertEqual(execute.call_count, 1) + kimi.assert_not_called() + self.assertEqual(list(handler.captured), ["acc_fixture_qw"]) + self.assertFalse(handler.captured["acc_fixture_qw"]["ok"]) + self.assertEqual(handler.captured["acc_fixture_qw"]["error"], "BailianGateway.Login.NotLogined") + self.assert_unchanged() + + def test_targeted_success_updates_only_selected_cache(self): + body = self.cache["acc_fixture_qw"]["body"] + with patch("server.execute_curl", return_value=(200, body, "")), patch("server.refresh_kimi_access_token") as kimi: + handler = self.post("/api/refresh", {"accountIds": ["acc_fixture_qw"]}) + kimi.assert_not_called() + self.assertTrue(handler.captured["acc_fixture_qw"]["ok"]) + self.assertEqual(load_snapshot(self.paths["results_path"])["acc_fixture_qw"]["body"], body) + self.assert_unchanged(except_paths=("results_path",)) + + def test_invalid_refresh_selection_is_rejected_before_provider_calls_or_writes(self): + for ids in (None, [], "acc_fixture_qw", ["acc_fixture_unknown"], [False], ["acc_fixture_qw"] * 21): + with self.subTest(ids=ids), patch("server.execute_curl") as execute: + handler = self.post("/api/refresh", {"accountIds": ids}) + self.assertEqual(handler.error[0], 400) + execute.assert_not_called() + self.assert_unchanged() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_refresh_stream.py b/tests/test_refresh_stream.py new file mode 100644 index 0000000..ed98808 --- /dev/null +++ b/tests/test_refresh_stream.py @@ -0,0 +1,92 @@ +import json +import tempfile +import threading +import unittest +from http.server import ThreadingHTTPServer +from pathlib import Path +from unittest import mock +from urllib.request import Request, urlopen + +from server import DashboardHandler + + +class RefreshStreamTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + self.accounts = { + "acc_slow": {"source": "codexUsage", "curl": "slow"}, + "acc_fast": {"source": "codexUsage", "curl": "fast"}, + "acc_fail": {"source": "codexUsage", "curl": "fail"}, + } + self.cached = {"acc_fail": {"ok": True, "status": 200, "body": "{}", "error": "", "updatedAt": "2026-01-01T00:00:00Z"}} + (self.root / "requests.json").write_text(json.dumps(self.accounts)) + (self.root / "results.json").write_text(json.dumps(self.cached)) + + class Handler(DashboardHandler): + def log_message(self, *_): + pass + + for name in ("requests", "results", "snapshot", "credentials", "order", "hidden"): + setattr(Handler, name + "_path", self.root / (name + ".json")) + self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self.thread = threading.Thread(target=self.httpd.serve_forever, daemon=True) + self.thread.start() + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + self.thread.join(timeout=5) + self.tmp.cleanup() + + def post(self, payload): + return Request(f"http://127.0.0.1:{self.httpd.server_port}/api/refresh", + data=json.dumps(payload).encode(), headers={"Content-Type": "application/json"}) + + def test_streams_each_result_as_soon_as_it_finishes(self): + fast_sent = threading.Event() + + def curl(command): + if command == "slow": + # The slow account only finishes after the fast line reached the client. + self.assertTrue(fast_sent.wait(5)) + return 200, '{"slow":true}', "" + if command == "fail": + return 500, "", "upstream failed" + return 200, '{"fast":true}', "" + + with mock.patch("server.execute_curl", side_effect=curl): + with urlopen(self.post({"stream": True}), timeout=10) as response: + self.assertTrue(response.headers["Content-Type"].startswith("application/x-ndjson")) + lines = [] + for raw in response: + item = json.loads(raw) + lines.append(item) + if item["id"] == "acc_fast": + fast_sent.set() + + order = [item["id"] for item in lines] + self.assertEqual(sorted(order), ["acc_fail", "acc_fast", "acc_slow"]) + self.assertLess(order.index("acc_fast"), order.index("acc_slow")) + cached = json.loads((self.root / "results.json").read_text()) + self.assertEqual(json.loads(cached["acc_fast"]["body"]), {"fast": True}) + self.assertEqual(json.loads(cached["acc_slow"]["body"]), {"slow": True}) + # A failed refresh keeps the last successful cache. + self.assertEqual(cached["acc_fail"], self.cached["acc_fail"]) + + def test_queries_accounts_concurrently_without_stream(self): + barrier = threading.Barrier(3, timeout=5) + + def curl(command): + barrier.wait() + return 200, json.dumps({"account": command}), "" + + with mock.patch("server.execute_curl", side_effect=curl): + with urlopen(self.post({}), timeout=10) as response: + results = json.load(response) + self.assertEqual(sorted(results), ["acc_fail", "acc_fast", "acc_slow"]) + self.assertTrue(all(result["ok"] for result in results.values())) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_server.py b/tests/test_server.py index a719b22..ca79539 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -14,6 +14,7 @@ load_results, load_order, load_snapshot, + load_hidden, kimi_refresh_headers_for_token, merge_kimi_verification_curl, merge_minimax_verification_curl, @@ -23,6 +24,7 @@ refresh_kimi_access_token, save_credentials, save_order, + save_hidden, save_requests, save_results, save_snapshot, @@ -345,6 +347,113 @@ def test_minimax_business_error_is_not_provider_success(self): self.assertTrue(provider_response_ok("minimax", 200, '{"base_resp":{"status_code":0,"status_msg":"success"}}')) self.assertTrue(provider_response_ok("minimax", 200, '{"model_remains":[]}')) + def test_newapi_codex_business_error_reports_message(self): + from server import provider_response_ok, provider_response_error + body = '{"success":false,"message":"upstream request failed"}' + for source in ("codexNewApi", "codexNewApiCredits"): + self.assertFalse(provider_response_ok(source, 200, body)) + self.assertEqual(provider_response_error(source, body), "upstream request failed") + self.assertEqual(provider_response_error("codexNewApi", "[]"), "") + + def test_merges_minimax_headers_across_domain_aliases(self): + for old_host, new_host in ( + ("www.minimaxi.com", "www.minimax.cn"), + ("www.minimax.cn", "www.minimaxi.com"), + ): + with self.subTest(old_host=old_host, new_host=new_host): + existing_url = f"https://{old_host}/backend/account/token_plan/remains_percent?scope=saved" + existing = f"curl '{existing_url}' -H 'cookie: _token=REDACTED_OLD' --data-raw '{{\"scope\":\"saved\"}}'" + verification = f"curl --url 'https://{new_host}/backend/account/token_plan/remains_percent' -b '_token=REDACTED_NEW; minimax_group_id_v2=REDACTED_GROUP' -H 'origin: https://platform.minimax.cn' -H 'x-group-id: REDACTED_GROUP'" + + merged = merge_minimax_verification_curl(existing, verification) + url, args = parse_curl(merged) + request, _ = build_http_request(args) + + self.assertEqual(url, existing_url) + self.assertEqual(request.method, "POST") + self.assertEqual(request.data, b'{"scope":"saved"}') + self.assertEqual(request.get_header("Cookie"), "_token=REDACTED_NEW; minimax_group_id_v2=REDACTED_GROUP") + self.assertEqual(request.get_header("Origin"), "https://platform.minimax.cn") + self.assertEqual(request.get_header("X-group-id"), "REDACTED_GROUP") + self.assertNotIn("REDACTED_OLD", merged) + + def test_minimax_alias_update_still_restricts_endpoint(self): + existing = "curl 'https://www.minimaxi.com/backend/account/token_plan/remains_percent' -b '_token=REDACTED_OLD'" + for url in ( + "https://www.minimax.cn/backend/account/other", + "https://www.minimax.cn:8443/backend/account/token_plan/remains_percent", + "http://www.minimax.cn/backend/account/token_plan/remains_percent", + "https://www.minimax.cn.example.com/backend/account/token_plan/remains_percent", + "https://www.kimi.com/apiv2/kimi.gateway.membership.v2.MembershipService/GetSubscriptionStats", + ): + with self.subTest(url=url), self.assertRaises(ValueError): + merge_minimax_verification_curl(existing, f"curl '{url}' -b '_token=REDACTED_NEW'") + + def test_updates_existing_minimax_from_new_domain_without_changing_other_state(self): + from io import BytesIO + from server import DashboardHandler + from unittest.mock import patch + + existing_url = "https://www.minimaxi.com/backend/account/token_plan/remains_percent" + existing = f"curl '{existing_url}' -b '_token=REDACTED_OLD' --data-raw '{{}}'" + verification = "curl --url 'https://www.minimax.cn/backend/account/token_plan/remains_percent' -b '_token=REDACTED_NEW'" + with tempfile.TemporaryDirectory() as tmp: + paths = {name + "_path": Path(tmp) / (name + ".json") for name in ("requests", "results", "snapshot", "order", "hidden", "credentials")} + accounts = {"acc_fixture_mm": {"source": "minimax", "label": "Fixture", "curl": existing, "updatedAt": "2026-01-01"}, "acc_fixture_other": {"source": "kimi", "curl": "REDACTED_OTHER"}} + save_requests(paths["requests_path"], accounts) + for name in ("results", "snapshot", "order", "hidden", "credentials"): + save_snapshot(paths[name + "_path"], {"fixture": name}) + before = {name: path.read_bytes() for name, path in paths.items()} + body = json.dumps({"id": "acc_fixture_mm", "minimaxVerificationCurl": verification}).encode() + handler = DashboardHandler.__new__(DashboardHandler) + handler.path = "/api/requests" + handler.headers = {"Content-Length": str(len(body))} + handler.rfile = BytesIO(body) + handler.send_json = lambda payload: setattr(handler, "captured", payload) + handler.send_error = lambda code, message=None: self.fail(f"HTTP {code}: {message}") + + with patch.multiple(DashboardHandler, **paths): + DashboardHandler.do_POST(handler) + + self.assertEqual(handler.captured["id"], "acc_fixture_mm") + self.assertEqual(handler.captured["source"], "minimax") + saved = load_requests(paths["requests_path"]) + self.assertEqual(list(saved), list(accounts)) + self.assertEqual(saved["acc_fixture_other"], accounts["acc_fixture_other"]) + self.assertEqual(saved["acc_fixture_mm"]["label"], "Fixture") + url, args = parse_curl(saved["acc_fixture_mm"]["curl"]) + request, _ = build_http_request(args) + self.assertEqual(url, existing_url) + self.assertEqual(request.data, b'{}') + self.assertEqual(request.get_header("Cookie"), "_token=REDACTED_NEW") + for name, path in paths.items(): + if name != "requests_path": + self.assertEqual(path.read_bytes(), before[name]) + + def test_minimax_failed_refresh_preserves_last_successful_cache(self): + from io import BytesIO + from server import DashboardHandler + from unittest.mock import patch + + with tempfile.TemporaryDirectory() as tmp: + paths = {name + "_path": Path(tmp) / (name + ".json") for name in ("requests", "results", "credentials")} + save_requests(paths["requests_path"], {"acc_fixture_mm": {"source": "minimax", "curl": "curl 'https://www.minimax.cn/backend/account/token_plan/remains_percent'"}}) + cached = {"acc_fixture_mm": {"ok": True, "status": 200, "body": '{"model_remains":[]}', "updatedAt": "2026-01-01"}} + save_results(paths["results_path"], cached) + handler = DashboardHandler.__new__(DashboardHandler) + handler.path = "/api/refresh" + handler.headers = {"Content-Length": "2"} + handler.rfile = BytesIO(b'{}') + handler.send_json = lambda payload: setattr(handler, "captured", payload) + error_body = '{"base_resp":{"status_code":1016,"status_msg":"invalid api key"}}' + + with patch.multiple(DashboardHandler, **paths), patch("server.execute_curl", return_value=(200, error_body, "")): + DashboardHandler.do_POST(handler) + + self.assertFalse(handler.captured["acc_fixture_mm"]["ok"]) + self.assertEqual(handler.captured["acc_fixture_mm"]["error"], "invalid api key") + self.assertEqual(load_results(paths["results_path"]), cached) + def test_only_http_200_is_a_successful_provider_result(self): self.assertTrue(is_success_status(200)) self.assertFalse(is_success_status(0)) @@ -380,6 +489,7 @@ def test_infers_source_from_endpoint(self): self.assertEqual(infer_source("curl https://chatgpt.com/backend-api/wham/rate-limit-reset-credits"), "codexCredits") self.assertEqual(infer_source("curl https://chatgpt.com/backend-api/wham/usage"), "codexUsage") self.assertEqual(infer_source("curl https://www.minimaxi.com/backend/account/token_plan/remains_percent"), "minimax") + self.assertEqual(infer_source("curl --url 'https://www.minimax.cn/backend/account/token_plan/remains_percent' -b '_token=REDACTED_TOKEN'"), "minimax") self.assertEqual(infer_source("curl https://console.volcengine.com/api/top/ark/cn-beijing/2024-01-01/GetCodingPlanUsage?"), "volcCoding") self.assertEqual(infer_source("curl https://console.volcengine.com/api/top/ark/cn-beijing/2024-01-01/GetAgentPlanUsageDetails?"), "volcAgent") self.assertEqual(infer_source("curl https://console.volcengine.com/api/top/ark/cn-beijing/2024-01-01/GetAgentPlanAFPUsage?"), "volcAgent") @@ -891,3 +1001,150 @@ def test_create_volc_account_without_ak_sk_rejected(self): self.assertEqual(errors["code"], 400) self.assertIn("ak and sk are required", errors["msg"]) + + +class HiddenAccountsTest(unittest.TestCase): + def test_load_hidden_returns_empty_when_missing(self): + with tempfile.TemporaryDirectory() as tmp: + self.assertEqual(load_hidden(Path(tmp) / "hidden.json"), []) + + def test_save_and_load_hidden_round_trips(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "hidden.json" + save_hidden(path, ["acc_1", "acc_2"]) + self.assertEqual(load_hidden(path), ["acc_1", "acc_2"]) + + def test_load_hidden_returns_empty_when_malformed(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "hidden.json" + save_snapshot(path, {"hidden": "not-a-list"}) + self.assertEqual(load_hidden(path), []) + + def test_post_hidden_persists_and_deduplicates(self): + from server import DashboardHandler + from io import BytesIO + import json as _json + + with tempfile.TemporaryDirectory() as tmp: + hidden_path = Path(tmp) / "hidden.json" + DashboardHandler.requests_path = Path(tmp) / "requests.json" + DashboardHandler.snapshot_path = Path(tmp) / "snapshot.json" + DashboardHandler.results_path = Path(tmp) / "results.json" + DashboardHandler.credentials_path = Path(tmp) / "credentials.json" + DashboardHandler.order_path = Path(tmp) / "order.json" + DashboardHandler.hidden_path = hidden_path + + body = _json.dumps({"hidden": ["acc_1", " acc_2 ", "acc_1", "", None]}).encode() + handler = DashboardHandler.__new__(DashboardHandler) + handler.path = "/api/hidden" + handler.headers = {"Content-Length": str(len(body))} + handler.rfile = BytesIO(body) + captured = {} + handler.send_json = lambda payload: captured.update({"payload": payload}) + handler.wfile = BytesIO() + + DashboardHandler.do_POST(handler) + + self.assertEqual(captured["payload"]["ok"], True) + self.assertEqual(captured["payload"]["hidden"], ["acc_1", "acc_2"]) + self.assertEqual(load_hidden(hidden_path), ["acc_1", "acc_2"]) + + def test_post_hidden_rejects_non_list(self): + from server import DashboardHandler + from io import BytesIO + import json as _json + + with tempfile.TemporaryDirectory() as tmp: + DashboardHandler.requests_path = Path(tmp) / "requests.json" + DashboardHandler.snapshot_path = Path(tmp) / "snapshot.json" + DashboardHandler.results_path = Path(tmp) / "results.json" + DashboardHandler.credentials_path = Path(tmp) / "credentials.json" + DashboardHandler.order_path = Path(tmp) / "order.json" + DashboardHandler.hidden_path = Path(tmp) / "hidden.json" + + body = _json.dumps({"hidden": "acc_1"}).encode() + handler = DashboardHandler.__new__(DashboardHandler) + handler.path = "/api/hidden" + handler.headers = {"Content-Length": str(len(body))} + handler.rfile = BytesIO(body) + errors = {} + handler.send_error = lambda code, msg=None: errors.update({"code": code, "msg": msg}) + handler.wfile = BytesIO() + + DashboardHandler.do_POST(handler) + + self.assertEqual(errors["code"], 400) + self.assertIn("hidden must be an array", errors["msg"]) + + def test_delete_account_clears_order_and_hidden_entries(self): + from server import DashboardHandler + from io import BytesIO + import json as _json + + with tempfile.TemporaryDirectory() as tmp: + req_path = Path(tmp) / "requests.json" + order_path = Path(tmp) / "order.json" + hidden_path = Path(tmp) / "hidden.json" + save_requests(req_path, { + "acc_keep": {"source": "codexUsage", "label": "", "curl": "", "updatedAt": None}, + "acc_gone": {"source": "codexUsage", "label": "", "curl": "", "updatedAt": None}, + }) + save_order(order_path, ["acc_keep", "acc_gone"]) + save_hidden(hidden_path, ["acc_gone"]) + + DashboardHandler.requests_path = req_path + DashboardHandler.snapshot_path = Path(tmp) / "snapshot.json" + DashboardHandler.results_path = Path(tmp) / "results.json" + DashboardHandler.credentials_path = Path(tmp) / "credentials.json" + DashboardHandler.order_path = order_path + DashboardHandler.hidden_path = hidden_path + + body = _json.dumps({"id": "acc_gone"}).encode() + handler = DashboardHandler.__new__(DashboardHandler) + handler.path = "/api/requests" + handler.headers = {"Content-Length": str(len(body))} + handler.rfile = BytesIO(body) + captured = {} + handler.send_json = lambda payload: captured.update({"payload": payload}) + handler.wfile = BytesIO() + + DashboardHandler.do_DELETE(handler) + + self.assertEqual(captured["payload"]["ok"], True) + self.assertEqual(list(load_requests(req_path)), ["acc_keep"]) + self.assertEqual(load_order(order_path), ["acc_keep"]) + self.assertEqual(load_hidden(hidden_path), []) + + +class SummaryTest(unittest.TestCase): + def test_summary_mirrors_card_headline_and_skips_hidden_and_credits(self): + from server import build_summary + accounts = { + "acc_kimi": {"source": "kimi", "label": "", "curl": "curl secret"}, + "acc_codex": {"source": "codexNewApi", "label": "main", "curl": "curl secret"}, + "acc_credits": {"source": "codexNewApiCredits", "label": "", "curl": "curl secret"}, + "acc_hidden": {"source": "googleAi", "label": "x", "refreshToken": "secret"}, + "acc_empty": {"source": "zhipuCoding", "label": ""}, + } + snapshot = { + "acc_kimi": {"limit": 100, "used": 95, "periods": [ + {"name": "5h", "usedPercent": 10, "resetAt": 1767225600000}, + {"name": "weekly", "usedPercent": 95, "resetAt": "2026-01-05T00:00:00Z"}], + "updatedAt": "2026-01-01T00:00:00+00:00"}, + "acc_codex": {"windows": [{"name": "5h", "available": True, "usedPercent": 100, "resetAt": None}], + "updatedAt": "2026-01-01T01:00:00+00:00"}, + "acc_credits": {"windows": [], "resetCards": 3}, + "acc_hidden": {"periods": [{"name": "5h", "usedPercent": 1}]}, + } + results = {"acc_kimi": {"ok": True, "body": "raw secret"}, "acc_codex": {"ok": False}} + summary = build_summary(accounts, snapshot, results, ["acc_codex"], ["acc_hidden"]) + self.assertEqual([item["id"] for item in summary["accounts"]], ["acc_codex", "acc_kimi", "acc_empty"]) + codex, kimi, empty = summary["accounts"] + self.assertEqual((codex["name"], codex["usedPercent"], codex["period"], codex["level"], codex["resetCards"], + codex["refreshOk"]), ("Codex · main", 100.0, "5小时额度", "bad", 3, False)) + self.assertEqual((kimi["remainingPercent"], kimi["period"], kimi["status"], kimi["resetAt"]), + (5.0, "周额度", "接近上限", "2026-01-05T00:00:00+00:00")) + self.assertEqual((empty["usedPercent"], empty["status"], empty["updatedAt"]), (None, "未加载", None)) + self.assertEqual((summary["total"], summary["ok"], summary["warn"], summary["bad"]), (3, 0, 2, 1)) + self.assertEqual(summary["updatedAt"], "2026-01-01T01:00:00+00:00") + self.assertNotIn("secret", json.dumps(summary))