A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io
Rust ai-toolsclaude-codecodexdeepseek-harnessdesktop-appgrokgrokbuildhermeskimi-codemcpopen-sourceopencodepiprovider-managementrustskillsskills-managementtauriwsl-support
fix(agy): disable auto-updater, support forced quota retry, and preserve not_found/Io retry (#10101)
pablod1ccdfc47970
diff --git a/src-tauri/src/agy_config.rs b/src-tauri/src/agy_config.rsindex d844bbc2d..0722d53ba 100644--- a/src-tauri/src/agy_config.rs+++ b/src-tauri/src/agy_config.rs@@ -2273,4 +2273,47 @@ mod integration_tests {assert_eq!(login_shell_agy_in(&zsh.to_string_lossy()), Some(agy));assert_eq!(login_shell_agy_in(&sh.to_string_lossy()), None);}++ #[test]+ #[serial]+ fn background_command_disables_auto_update_and_injects_global_proxy() {+ use std::collections::HashMap;+ use std::ffi::OsString;++ struct ProxyGuard(Option<String>);+ impl Drop for ProxyGuard {+ fn drop(&mut self) {+ let _ = crate::proxy::http_client::apply_proxy(self.0.as_deref());+ }+ }++ let _guard = ProxyGuard(crate::proxy::http_client::get_current_proxy_url());+ let env_map = |cmd: &tokio::process::Command| -> HashMap<OsString, Option<OsString>> {+ cmd.as_std()+ .get_envs()+ .map(|(k, v)| (k.to_os_string(), v.map(|s| s.to_os_string())))+ .collect()+ };++ crate::proxy::http_client::apply_proxy(None).unwrap();+ let direct = env_map(&background_command(Path::new("agy")));+ assert_eq!(+ direct.get(std::ffi::OsStr::new("AGY_CLI_DISABLE_AUTO_UPDATE")),+ Some(&Some(OsString::from("true")))+ );+ assert!(!direct.contains_key(std::ffi::OsStr::new("HTTPS_PROXY")));++ crate::proxy::http_client::apply_proxy(Some("http://127.0.0.1:7890")).unwrap();+ let proxied = env_map(&background_command(Path::new("agy")));+ assert_eq!(+ proxied.get(std::ffi::OsStr::new("AGY_CLI_DISABLE_AUTO_UPDATE")),+ Some(&Some(OsString::from("true")))+ );+ for key in ["HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy"] {+ assert_eq!(+ proxied.get(std::ffi::OsStr::new(key)),+ Some(&Some(OsString::from("http://127.0.0.1:7890")))+ );+ }+ }}diff --git a/src-tauri/src/commands/agy_account.rs b/src-tauri/src/commands/agy_account.rsindex 25e4ac63e..c39a82da4 100644--- a/src-tauri/src/commands/agy_account.rs+++ b/src-tauri/src/commands/agy_account.rs@@ -71,9 +71,16 @@ pub async fn agy_account_quota(app: tauri::AppHandle,app_state: tauri::State<'_, crate::store::AppState>,account_id: String,+ force: Option<bool>,state: tauri::State<'_, AgyAccountState>,) -> Result<SubscriptionQuota, String> {- let quota = agy_quota(&state.0, Some(&account_id), QUOTA_REUSE_INTERACTIVE).await?;+ let quota = agy_quota(+ &state.0,+ Some(&account_id),+ QUOTA_REUSE_INTERACTIVE,+ force.unwrap_or(false),+ )+ .await?;remember_account_quota(&app, &app_state, account_id, "a);Ok(quota)}@@ -153,11 +160,13 @@ fn snapshot_only(gateway_in_use: bool, requested: Option<&str>, current: Option</// Antigravity 官方登录的额度,只问 agy 自己的 `/usage`(不用 agy 的身份发请求)。/// 不指定账号就是 agy 现在登着的号;指定的号不是 agy 当前登录、或者网关在用时,返回它最后-/// 一次查到的。`reuse` 内查过同一个号就不再起 agy。查成功的结果按账号记下。+/// 一次查到的。`force` 为 `false` 且 `reuse` 内查过同一个号就不再起 agy;`force` 为 `true` 时+/// 跳过短时缓存但仍持锁排队。查成功的结果按账号记下。pub(crate) async fn agy_quota(manager: &AgyAccountManager,account_id: Option<&str>,reuse: Duration,+ force: bool,) -> Result<SubscriptionQuota, String> {if !crate::services::agy_account::keychain::supported() {return crate::services::subscription_agy::get_agy_subscription_quota().await;@@ -177,6 +186,7 @@ pub(crate) async fn agy_quota(&LAST_LIVE_QUERY,current.as_deref(),reuse,+ force,crate::services::subscription_agy::get_agy_subscription_quota,|| async { manager.current_account_id().await == current },)@@ -208,6 +218,7 @@ async fn query_live_with_cache<F, Fut, C, CFut>(cache: &Mutex<Option<LiveQuery>>,current: Option<&str>,reuse: Duration,+ force: bool,fetch: F,is_still_current: C,) -> Result<LiveQueryResult, String>@@ -218,18 +229,20 @@ whereCFut: Future<Output = bool>,{let mut last = cache.lock().await;- if let Some(query) = last.as_ref() {- let effective_reuse = if query.result.as_ref().is_ok_and(|quota| quota.success) {- reuse- } else {- reuse.min(QUOTA_FAILURE_REUSE)- };- if query.account_id.as_deref() == current && query.at.elapsed() < effective_reuse {- return Ok(LiveQueryResult {- quota: query.result.clone()?,- should_record: false,- still_current: true,- });+ if !force {+ if let Some(query) = last.as_ref() {+ let effective_reuse = if query.result.as_ref().is_ok_and(|quota| quota.success) {+ reuse+ } else {+ reuse.min(QUOTA_FAILURE_REUSE)+ };+ if query.account_id.as_deref() == current && query.at.elapsed() < effective_reuse {+ return Ok(LiveQueryResult {+ quota: query.result.clone()?,+ should_record: false,+ still_current: true,+ });+ }}}// 超时也走失败缓存,避免排队中的请求立即再次拉起 agy。@@ -445,6 +458,7 @@ mod tests {&cache,Some("alice"),tray_reuse,+ false,|| async {calls.fetch_add(1, Ordering::SeqCst);Err(timeout.to_string())@@ -459,6 +473,7 @@ mod tests {&cache,Some("alice"),tray_reuse,+ false,|| async {calls.fetch_add(1, Ordering::SeqCst);Ok(ok_quota(50.0))@@ -475,6 +490,7 @@ mod tests {&cache,Some("alice"),tray_reuse,+ false,|| async {calls.fetch_add(1, Ordering::SeqCst);Ok(SubscriptionQuota::error(@@ -498,6 +514,7 @@ mod tests {&cache,Some("alice"),tray_reuse,+ false,|| async {calls.fetch_add(1, Ordering::SeqCst);Ok(ok_quota(12.0))@@ -527,6 +544,7 @@ mod tests {&cache,Some("alice"),tray_reuse,+ false,|| async {calls.fetch_add(1, Ordering::SeqCst);Ok(ok_quota(35.0))@@ -545,6 +563,7 @@ mod tests {&cache,Some("alice"),tray_reuse,+ false,|| async {calls.fetch_add(1, Ordering::SeqCst);Ok(ok_quota(99.0))@@ -559,6 +578,102 @@ mod tests {assert_eq!(calls.load(Ordering::SeqCst), 4);}+ #[tokio::test]+ async fn live_cache_force_bypasses_cached_failure_and_success_while_false_reuses() {+ let cache = Mutex::new(None);+ let calls = AtomicUsize::new(0);+ let reuse = Duration::from_secs(300);++ // 1. 写入失败缓存+ let fail = query_live_with_cache(+ &cache,+ Some("alice"),+ reuse,+ false,+ || async {+ calls.fetch_add(1, Ordering::SeqCst);+ Ok(SubscriptionQuota::not_found(TOOL))+ },+ || async { true },+ )+ .await+ .unwrap();+ assert!(!fail.quota.success);+ assert_eq!(calls.load(Ordering::SeqCst), 1);++ // force = false 在 20s 内仍复用失败+ let reused_fail = query_live_with_cache(+ &cache,+ Some("alice"),+ reuse,+ false,+ || async {+ calls.fetch_add(1, Ordering::SeqCst);+ Ok(ok_quota(10.0))+ },+ || async { true },+ )+ .await+ .unwrap();+ assert!(!reused_fail.quota.success);+ assert_eq!(calls.load(Ordering::SeqCst), 1);++ // force = true 跳过失败缓存并写回最新成功结果+ let forced_ok = query_live_with_cache(+ &cache,+ Some("alice"),+ reuse,+ true,+ || async {+ calls.fetch_add(1, Ordering::SeqCst);+ Ok(ok_quota(20.0))+ },+ || async { true },+ )+ .await+ .unwrap();+ assert!(forced_ok.quota.success);+ assert!(forced_ok.should_record);+ assert_eq!(forced_ok.quota.tiers[0].utilization, 20.0);+ assert_eq!(calls.load(Ordering::SeqCst), 2);++ // force = false 复用刚刚写回的成功缓存+ let reused_ok = query_live_with_cache(+ &cache,+ Some("alice"),+ reuse,+ false,+ || async {+ calls.fetch_add(1, Ordering::SeqCst);+ Ok(ok_quota(80.0))+ },+ || async { true },+ )+ .await+ .unwrap();+ assert_eq!(reused_ok.quota.tiers[0].utilization, 20.0);+ assert!(!reused_ok.should_record);+ assert_eq!(calls.load(Ordering::SeqCst), 2);++ // force = true 同样跳过成功缓存+ let forced_refresh = query_live_with_cache(+ &cache,+ Some("alice"),+ reuse,+ true,+ || async {+ calls.fetch_add(1, Ordering::SeqCst);+ Ok(ok_quota(45.0))+ },+ || async { true },+ )+ .await+ .unwrap();+ assert_eq!(forced_refresh.quota.tiers[0].utilization, 45.0);+ assert!(forced_refresh.should_record);+ assert_eq!(calls.load(Ordering::SeqCst), 3);+ }+#[test]fn login_command_escapes_special_chars() {assert_eq!(diff --git a/src-tauri/src/commands/subscription.rs b/src-tauri/src/commands/subscription.rsindex 8f38d672f..c71fd5249 100644--- a/src-tauri/src/commands/subscription.rs+++ b/src-tauri/src/commands/subscription.rs@@ -27,6 +27,7 @@ pub async fn get_subscription_quota(&agy.0,None,crate::commands::agy_account::QUOTA_REUSE_INTERACTIVE,+ false,).await}diff --git a/src-tauri/src/services/subscription_agy.rs b/src-tauri/src/services/subscription_agy.rsindex 2b22b2352..171c89362 100644--- a/src-tauri/src/services/subscription_agy.rs+++ b/src-tauri/src/services/subscription_agy.rs@@ -263,8 +263,8 @@ fn keychain_quota_failure(read: Result<Option<String>, AppError>) -> Option<Subs}/// 由 `subscription::get_subscription_quota("agy")` 分发。没装 agy、或网关在用(官方登录没在用)-/// 时按「没有凭据」处理(卡片不显示);超时、没登录或输出看不懂都写成查询失败,错误里不带-/// agy 的原始输出。+/// 时按「没有凭据」处理(卡片不显示);已找到可执行文件但启动失败、超时、没登录或输出看不懂+/// 都写成查询失败,错误里不带 agy 的原始输出。pub(crate) async fn get_agy_subscription_quota() -> Result<SubscriptionQuota, String> {if gateway_in_use().await {return Ok(SubscriptionQuota::not_found(TOOL));@@ -292,11 +292,22 @@ pub(crate) async fn get_agy_subscription_quota() -> Result<SubscriptionQuota, St// build_usage_command 带上设置里的全局代理并隔离后台子进程环境;进程树的清理// 和 Windows 隐藏窗口由 run_command_output 负责。let command = build_usage_command(&bin);- let output = match run_command_output(command, TIMEOUT).await {+ quota_from_command_result(run_command_output(command, TIMEOUT).await)+}++fn quota_from_command_result(+ result: Result<Output, CommandExecError>,+) -> Result<SubscriptionQuota, String> {+ let output = match result {Ok(output) => output,Err(CommandExecError::Io(error)) => {log::warn!("[AgyQuota] 启动或执行 agy 失败: {error}");- return Ok(SubscriptionQuota::not_found(TOOL));+ return Ok(SubscriptionQuota::error(+ TOOL,+ CredentialStatus::Valid,+ "Failed to run agy to query quota. Check your agy installation and try again."+ .to_string(),+ ));}Err(CommandExecError::Timeout) => {log::warn!("[AgyQuota] agy /usage 查询超时({}s)", TIMEOUT.as_secs());@@ -530,4 +541,19 @@ mod tests {assert_eq!(flags.0 .0, 0x0800_0000);assert!(wrapped.has_wrap::<process_wrap::tokio::JobObject>());}++ #[test]+ fn io_exec_error_maps_to_valid_credential_error_instead_of_not_found() {+ let quota = quota_from_command_result(Err(CommandExecError::Io(std::io::Error::new(+ std::io::ErrorKind::NotFound,+ "spawn failed",+ ))))+ .unwrap();+ assert!(!quota.success);+ assert!(matches!(quota.credential_status, CredentialStatus::Valid));+ assert_eq!(+ quota.error.as_deref(),+ Some("Failed to run agy to query quota. Check your agy installation and try again.")+ );+ }}diff --git a/src-tauri/src/tray.rs b/src-tauri/src/tray.rsindex 9758e4e21..0bb01f9e5 100644--- a/src-tauri/src/tray.rs+++ b/src-tauri/src/tray.rs@@ -3943,6 +3943,7 @@ pub(crate) async fn refresh_all_usage_in_tray(app: &tauri::AppHandle) {&accounts.0,Some(&account_id),AGY_TRAY_QUOTA_REUSE,+ false,).await{diff --git a/src/components/AgyAccountQuotaFooter.tsx b/src/components/AgyAccountQuotaFooter.tsxindex 19f3aa9df..d83756092 100644--- a/src/components/AgyAccountQuotaFooter.tsx+++ b/src/components/AgyAccountQuotaFooter.tsx@@ -1,8 +1,12 @@-import React from "react";-import { useQuery } from "@tanstack/react-query";+import React, { useEffect } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";import { useTranslation } from "react-i18next";-import { useAgyAccountQuota } from "@/lib/query/subscription";-import { authGetStatus, type ManagedAuthStatus } from "@/lib/api/auth";+import {+ agyAuthStatusQuery,+ syncAgyLoginOnWindowFocus,+ useAgyAccountQuota,+} from "@/lib/query/subscription";+import { subscribeWindowFocus } from "@/lib/windowActivity";import { toast } from "@/lib/toast";import { SubscriptionQuotaView } from "@/components/SubscriptionQuotaFooter";import { useQuotaDisplay } from "@/components/quota/useQuotaDisplay";@@ -28,12 +32,14 @@ const AgyAccountQuotaFooter: React.FC<AgyAccountQuotaFooterProps> = ({}) => {const { t } = useTranslation();const display = useQuotaDisplay();+ const queryClient = useQueryClient();// 和授权中心共用同一份账号状态缓存:default_account_id 就是 agy 现在登着的号- const { data: authStatus } = useQuery<ManagedAuthStatus>({- queryKey: ["managed-auth-status", "agy_oauth"],- queryFn: () => authGetStatus("agy_oauth"),- staleTime: 30000,- });+ const { data: authStatus } = useQuery(agyAuthStatusQuery);+ useEffect(+ () =>+ subscribeWindowFocus(() => void syncAgyLoginOnWindowFocus(queryClient)),+ [queryClient],+ );const notCurrent =authStatus != null && authStatus.default_account_id !== accountId;const {diff --git a/src/components/settings/auth/AccountQuota.tsx b/src/components/settings/auth/AccountQuota.tsxindex bc77a3523..233f4f246 100644--- a/src/components/settings/auth/AccountQuota.tsx+++ b/src/components/settings/auth/AccountQuota.tsx@@ -526,10 +526,22 @@ function CurrentAgyAccountQuota({refetch,manualIdle,} = useAgyAccountQuota(accountId, { enabled: true, autoQuery: false });+ // 当前账号拿到 not_found 时不能把额度列隐藏,否则 ↻ 重试按钮会一起消失(重试期间保持 loading 避免闪烁)+ const state: AccountQuotaState =+ quota?.credentialStatus === "not_found"+ ? loading+ ? { kind: "loading" }+ : {+ kind: "failed",+ reason: t("authCenter.agy.quotaNotFound", {+ defaultValue: "未检测到 agy 或登录状态已变化,请重试。",+ }),+ }+ : subscriptionQuotaState(t, quota, loading, i18n.language, display);return (<AccountQuotaColumnlogin={login}- state={subscriptionQuotaState(t, quota, loading, i18n.language, display)}+ state={state}queriedAt={quota?.queriedAt ?? null}loading={loading}onRefresh={() => void refetch()}diff --git a/src/components/settings/auth/RefreshAllQuotaButton.tsx b/src/components/settings/auth/RefreshAllQuotaButton.tsxindex 680a69995..8f89dcc2b 100644--- a/src/components/settings/auth/RefreshAllQuotaButton.tsx+++ b/src/components/settings/auth/RefreshAllQuotaButton.tsx@@ -16,6 +16,7 @@ import {} from "@/components/providers/workbuddyQuota";import {agyAuthStatusQuery,+ markAgyQuotaForceRefresh,markCodebuddyQuotaForceRefresh,} from "@/lib/query/subscription";@@ -86,6 +87,7 @@ export function RefreshAllQuotaButton() {size="regular"disabled={fetching}onClick={() => {+ markAgyQuotaForceRefresh();markCodebuddyQuotaForceRefresh();markWorkBuddyQuotaForceRefresh();void Promise.all(diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.jsonindex bd3083f1a..c90bd6935 100644--- a/src/i18n/locales/de.json+++ b/src/i18n/locales/de.json@@ -5365,7 +5365,8 @@"openDesktop": "Antigravity öffnen","quotaNotCurrent": "Wechsle zu diesem Konto, um sein Kontingent abzufragen","quotaRefreshNotCurrent": "agy kann nur das Kontingent des angemeldeten Kontos abfragen. Angezeigt wird der zuletzt vor dem Wechsel abgefragte Stand. Wechsle zu diesem Konto und aktualisiere dann.",- "quotaRefreshDisabledHint": "Wechsle zu diesem Konto, um das aktuelle Kontingent abzufragen"+ "quotaRefreshDisabledHint": "Wechsle zu diesem Konto, um das aktuelle Kontingent abzufragen",+ "quotaNotFound": "agy wurde nicht gefunden oder der Anmeldestatus hat sich geändert. Bitte erneut versuchen."},"codebuddy": {"mainland": "China",diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.jsonindex cd79a30ac..0781c30b3 100644--- a/src/i18n/locales/en.json+++ b/src/i18n/locales/en.json@@ -5365,7 +5365,8 @@"openDesktop": "Open Antigravity","quotaNotCurrent": "Switch to this account to check its quota","quotaRefreshNotCurrent": "agy can only check the quota of the account it's signed in with. This shows the last quota checked before you switched away. Switch to this account, then refresh.",- "quotaRefreshDisabledHint": "Switch to this account to check its latest quota"+ "quotaRefreshDisabledHint": "Switch to this account to check its latest quota",+ "quotaNotFound": "agy was not found or the sign-in state changed. Try again."},"codebuddy": {"mainland": "China",diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.jsonindex bcf896432..4b905480b 100644--- a/src/i18n/locales/ja.json+++ b/src/i18n/locales/ja.json@@ -5365,7 +5365,8 @@"openDesktop": "Antigravity を開く","quotaNotCurrent": "このアカウントに切り替えると残量を確認できます","quotaRefreshNotCurrent": "agy で確認できるのは、現在ログイン中のアカウントの残量だけです。ここには切り替える前に最後に確認した値が表示されています。このアカウントに切り替えてから更新してください。",- "quotaRefreshDisabledHint": "このアカウントに切り替えると最新の残量を確認できます"+ "quotaRefreshDisabledHint": "このアカウントに切り替えると最新の残量を確認できます",+ "quotaNotFound": "agy が見つからないか、ログイン状態が変化しました。再試行してください。"},"codebuddy": {"mainland": "国内版",diff --git a/src/i18n/locales/ko.json b/src/i18n/locales/ko.jsonindex 7aafb26f1..1da02503f 100644--- a/src/i18n/locales/ko.json+++ b/src/i18n/locales/ko.json@@ -5365,7 +5365,8 @@"openDesktop": "Antigravity 열기","quotaNotCurrent": "이 계정으로 전환해야 사용량을 조회할 수 있습니다","quotaRefreshNotCurrent": "agy는 현재 로그인된 계정의 사용량만 조회할 수 있습니다. 여기에는 전환하기 전에 마지막으로 조회한 값이 표시됩니다. 이 계정으로 전환한 뒤 새로고침하세요.",- "quotaRefreshDisabledHint": "이 계정으로 전환해야 최신 사용량을 조회할 수 있습니다"+ "quotaRefreshDisabledHint": "이 계정으로 전환해야 최신 사용량을 조회할 수 있습니다",+ "quotaNotFound": "agy를 찾을 수 없거나 로그인 상태가 변경되었습니다. 다시 시도하세요."},"codebuddy": {"mainland": "중국",diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.jsonindex 4fcb378af..375eb3fff 100644--- a/src/i18n/locales/ru.json+++ b/src/i18n/locales/ru.json@@ -5363,7 +5363,8 @@"openDesktop": "Открыть Antigravity","quotaNotCurrent": "Переключитесь на этот аккаунт, чтобы проверить квоту","quotaRefreshNotCurrent": "agy может проверить квоту только того аккаунта, в который сейчас выполнен вход. Здесь показана квота, полученная перед переключением. Переключитесь на этот аккаунт и обновите.",- "quotaRefreshDisabledHint": "Переключитесь на этот аккаунт, чтобы проверить актуальную квоту"+ "quotaRefreshDisabledHint": "Переключитесь на этот аккаунт, чтобы проверить актуальную квоту",+ "quotaNotFound": "agy не найден или статус входа изменился. Повторите попытку."},"codebuddy": {"mainland": "Китай",diff --git a/src/i18n/locales/tr.json b/src/i18n/locales/tr.jsonindex 487768488..7415acda7 100644--- a/src/i18n/locales/tr.json+++ b/src/i18n/locales/tr.json@@ -5294,7 +5294,8 @@"openDesktop": "Antigravity'yi aç","quotaNotCurrent": "Kotasını görmek için bu hesaba geçin","quotaRefreshNotCurrent": "agy yalnızca oturum açık olan hesabın kotasını sorgulayabilir. Burada, başka hesaba geçmeden önce en son sorgulanan değer gösterilir. Bu hesaba geçip ardından yenileyin.",- "quotaRefreshDisabledHint": "Güncel kotasını görmek için bu hesaba geçin"+ "quotaRefreshDisabledHint": "Güncel kotasını görmek için bu hesaba geçin",+ "quotaNotFound": "agy bulunamadı veya oturum durumu değişti. Yeniden deneyin."},"codebuddy": {"mainland": "Çin",diff --git a/src/i18n/locales/zh-TW.json b/src/i18n/locales/zh-TW.jsonindex c885809b5..103a1fbae 100644--- a/src/i18n/locales/zh-TW.json+++ b/src/i18n/locales/zh-TW.json@@ -5365,7 +5365,8 @@"openDesktop": "開啟 Antigravity","quotaNotCurrent": "切換到這個帳號後才能查詢額度","quotaRefreshNotCurrent": "agy 只能查詢目前登入帳號的額度,這裡顯示的是切走前最後一次查到的。切換到這個帳號後再重新整理。",- "quotaRefreshDisabledHint": "切換到這個帳號後才能查詢最新額度"+ "quotaRefreshDisabledHint": "切換到這個帳號後才能查詢最新額度",+ "quotaNotFound": "未偵測到 agy 或登入狀態已變更,請重試。"},"codebuddy": {"mainland": "國內版",diff --git a/src/i18n/locales/zh.json b/src/i18n/locales/zh.jsonindex d758239b4..d92d272c4 100644--- a/src/i18n/locales/zh.json+++ b/src/i18n/locales/zh.json@@ -5365,7 +5365,8 @@"openDesktop": "打开 Antigravity","quotaNotCurrent": "切到这个号后才能查额度","quotaRefreshNotCurrent": "agy 只能查当前登着的号的额度,这里显示的是切走前最后一次查到的。切到这个号后再刷新。",- "quotaRefreshDisabledHint": "切到这个号后才能查最新额度"+ "quotaRefreshDisabledHint": "切到这个号后才能查最新额度",+ "quotaNotFound": "未检测到 agy 或登录状态已变化,请重试。"},"codebuddy": {"mainland": "国内版",diff --git a/src/lib/api/subscription.ts b/src/lib/api/subscription.tsindex a867f2d72..ad60ccf92 100644--- a/src/lib/api/subscription.ts+++ b/src/lib/api/subscription.ts@@ -18,8 +18,14 @@ export const subscriptionApi = {/** Claude Code 默认登录的套餐(没绑账号的官方卡显示) */getClaudeDefaultPlan: (): Promise<ClaudeAccountPlan | null> =>invoke("get_claude_default_plan"),- getAgyAccountQuota: (accountId: string): Promise<SubscriptionQuota> =>- invoke("agy_account_quota", { accountId }),+ getAgyAccountQuota: (+ accountId: string,+ force = false,+ ): Promise<SubscriptionQuota> =>+ invoke(+ "agy_account_quota",+ force ? { accountId, force: true } : { accountId },+ ),/** 只读本地保存的 Antigravity 额度快照,不读钥匙串、不启动 `agy`。 */getAgyAccountLastQuota: (accountId: string,diff --git a/src/lib/query/subscription.ts b/src/lib/query/subscription.tsindex fe15dd233..7ad7af286 100644--- a/src/lib/query/subscription.ts+++ b/src/lib/query/subscription.ts@@ -468,6 +468,13 @@ export function useXaiOauthQuotaByAccountId(return useQuotaKeepLastGood(query, accountId ?? "default", policy);}+let agyForceRefreshEpoch = 0;++/** 授权中心「全部刷新」时调用:让下一次 Antigravity 额度重查跳过后端短时缓存。 */+export function markAgyQuotaForceRefresh() {+ agyForceRefreshEpoch += 1;+}+/*** Antigravity 账号的剩余额度(按账号 ID)。agy 当前登着的号问 agy 的 `/usage`,* 别的号返回切走前最后一次查到的(没有时为 not_found)。@@ -482,11 +489,19 @@ export function useAgyAccountQuota(autoQuery = false,autoQueryIntervalMinutes = 5,} = options;+ const force = useRef(false);+ const seenForceEpoch = useRef(agyForceRefreshEpoch);const policy = useQuotaPolicy();const autoAllowed = policy.autoAllowed;const query = useQuery({queryKey: ["agy_oauth", "quota", accountId],- queryFn: () => subscriptionApi.getAgyAccountQuota(accountId),+ queryFn: () => {+ const skipCache =+ force.current || seenForceEpoch.current !== agyForceRefreshEpoch;+ force.current = false;+ seenForceEpoch.current = agyForceRefreshEpoch;+ return subscriptionApi.getAgyAccountQuota(accountId, skipCache);+ },enabled: autoAllowed && enabled,...autoRefetch(autoAllowed && autoQuery, autoQueryIntervalMinutes),// 缓存里如果是之前作为非当前号拿到的 not_found,成为当前号重新挂载时立刻重查,不等 5 分钟。@@ -498,7 +513,16 @@ export function useAgyAccountQuota(retry: false,});- return useQuotaKeepLastGood(query, accountId, policy);+ const keepLastGood = useQuotaKeepLastGood(query, accountId, policy);+ const refetch: typeof query.refetch = (refetchOptions) => {+ force.current = true;+ return query.refetch(refetchOptions);+ };++ return {+ ...keepLastGood,+ refetch,+ };}/**diff --git a/tests/components/AgyAccountQuota.test.tsx b/tests/components/AgyAccountQuota.test.tsxindex e4408ed30..08bc6ab68 100644--- a/tests/components/AgyAccountQuota.test.tsx+++ b/tests/components/AgyAccountQuota.test.tsx@@ -13,6 +13,7 @@ import { createInstance } from "i18next";import { I18nextProvider, initReactI18next } from "react-i18next";import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { AgyAccountQuota } from "@/components/settings/auth/AccountQuota";+import AgyAccountQuotaFooter from "@/components/AgyAccountQuotaFooter";import { RefreshAllQuotaButton } from "@/components/settings/auth/RefreshAllQuotaButton";import {agyAuthStatusQuery,@@ -203,7 +204,7 @@ describe("AgyAccountQuota", () => {fireEvent.click(refreshButton);expect(await screen.findByText("剩余 90%")).toBeInTheDocument();- expect(mocks.getAgyAccountQuota).toHaveBeenCalledWith("a");+ expect(mocks.getAgyAccountQuota).toHaveBeenCalledWith("a", true);});it("recovers to manual-idle instead of hiding the column when a newly current account had cached not_found", async () => {@@ -321,7 +322,7 @@ describe("AgyAccountQuota", () => {await waitFor(() =>expect(mocks.getAgyAccountQuota).toHaveBeenCalledTimes(1),);- expect(mocks.getAgyAccountQuota).toHaveBeenCalledWith("b");+ expect(mocks.getAgyAccountQuota).toHaveBeenCalledWith("b", false);expect(screen.getByText("refetching-b")).toBeInTheDocument();expect(screen.getByText("c:empty")).toBeInTheDocument();@@ -432,7 +433,7 @@ describe("AgyAccountQuota", () => {expect(await screen.findByText("剩余 90%")).toBeInTheDocument();expect(mocks.getAgyAccountQuota).toHaveBeenCalledTimes(1);- expect(mocks.getAgyAccountQuota).toHaveBeenCalledWith("a");+ expect(mocks.getAgyAccountQuota).toHaveBeenCalledWith("a", false);mocks.getAgyAccountQuota.mockClear();@@ -442,7 +443,7 @@ describe("AgyAccountQuota", () => {expect(await screen.findByText("剩余 60%")).toBeInTheDocument();expect(mocks.getAgyAccountQuota).toHaveBeenCalledTimes(1);- expect(mocks.getAgyAccountQuota).toHaveBeenCalledWith("b");+ expect(mocks.getAgyAccountQuota).toHaveBeenCalledWith("b", false);});it("renders expired non-current snapshots truthfully without rewriting percentages or showing past countdowns", async () => {@@ -635,7 +636,7 @@ describe("AgyAccountQuota", () => {expect(await screen.findByText("剩余 60%")).toBeInTheDocument();expect(mocks.getAgyAccountQuota).toHaveBeenCalledTimes(1);- expect(mocks.getAgyAccountQuota).toHaveBeenCalledWith("a");+ expect(mocks.getAgyAccountQuota).toHaveBeenCalledWith("a", true);});it("also skips directly observed non-current agy_oauth quota queries during Refresh all", async () => {@@ -677,6 +678,129 @@ describe("AgyAccountQuota", () => {expect(await screen.findByText("a-loaded/b-idle")).toBeInTheDocument();expect(mocks.getAgyAccountQuota).toHaveBeenCalledTimes(1);- expect(mocks.getAgyAccountQuota).toHaveBeenCalledWith("a");+ expect(mocks.getAgyAccountQuota).toHaveBeenCalledWith("a", true);+ });++ it("shows failed state with retry button for current account not_found and recovers with force refresh", async () => {+ mocks.getSettings.mockResolvedValue({});+ let resolveRetry!: (quota: SubscriptionQuota) => void;+ mocks.getAgyAccountQuota+ .mockResolvedValueOnce(NOT_FOUND_QUOTA)+ .mockImplementationOnce(+ () =>+ new Promise<SubscriptionQuota>((resolve) => {+ resolveRetry = resolve;+ }),+ );++ render(<AgyAccountQuota accountId="a" login="[email protected]" isCurrent />, {+ wrapper: wrapperFor(newClient()),+ });++ expect(+ await screen.findByText(zh.authCenter.agy.quotaNotFound),+ ).toBeInTheDocument();+ expect(screen.getByText(zh.quota.failed)).toBeInTheDocument();+ expect(mocks.getAgyAccountQuota).toHaveBeenCalledWith("a", false);++ const refreshButton = screen.getByRole("button", {+ name: "刷新 [email protected] 的额度",+ });+ expect(refreshButton).toHaveAttribute("aria-disabled", "false");++ fireEvent.click(refreshButton);+ await waitFor(() =>+ expect(refreshButton).toHaveAttribute("aria-busy", "true"),+ );+ expect(screen.getByText(zh.authCenter.quota.loading)).toBeInTheDocument();+ expect(mocks.getAgyAccountQuota).toHaveBeenNthCalledWith(2, "a", true);++ resolveRetry(+ makeQuota({+ tiers: [+ { name: "agy_gemini_five_hour", utilization: 25, resetsAt: null },+ ],+ }),+ );+ expect(await screen.findByText("剩余 75%")).toBeInTheDocument();+ });++ it("passes force=false on automatic queries and force=true only on manual refetch", async () => {+ mocks.getSettings.mockResolvedValue({});+ mocks.getAgyAccountQuota.mockResolvedValue(makeQuota());++ let latestRefetch!: () => Promise<unknown>;+ function Observer() {+ const q = useAgyAccountQuota("a");+ latestRefetch = q.refetch;+ return <span>{q.data?.success ? "ok" : "idle"}</span>;+ }++ const client = newClient();+ render(<Observer />, { wrapper: wrapperFor(client) });++ expect(await screen.findByText("ok")).toBeInTheDocument();+ expect(mocks.getAgyAccountQuota).toHaveBeenNthCalledWith(1, "a", false);++ await act(async () => {+ await latestRefetch();+ });+ expect(mocks.getAgyAccountQuota).toHaveBeenNthCalledWith(2, "a", true);++ await act(async () => {+ await client.invalidateQueries({ queryKey: ["agy_oauth", "quota", "a"] });+ });+ await waitFor(() =>+ expect(mocks.getAgyAccountQuota).toHaveBeenCalledTimes(3),+ );+ expect(mocks.getAgyAccountQuota).toHaveBeenNthCalledWith(3, "a", false);+ });++ it("syncs AgyAccountQuotaFooter auth status and quota on window focus", async () => {+ mocks.getSettings.mockResolvedValue({});+ mocks.authGetStatus+ .mockResolvedValueOnce({+ provider: "agy_oauth",+ authenticated: true,+ default_account_id: "a",+ accounts: [],+ })+ .mockResolvedValueOnce({+ provider: "agy_oauth",+ authenticated: true,+ default_account_id: "b",+ accounts: [],+ });+ mocks.getAgyAccountQuota+ .mockResolvedValueOnce(NOT_FOUND_QUOTA)+ .mockResolvedValueOnce(+ makeQuota({+ tiers: [+ { name: "agy_gemini_five_hour", utilization: 20, resetsAt: null },+ ],+ }),+ );++ const client = newClient();+ render(<AgyAccountQuotaFooter accountId="b" isCurrent />, {+ wrapper: wrapperFor(client),+ });++ await waitFor(() =>+ expect(mocks.authGetStatus).toHaveBeenCalledWith("agy_oauth"),+ );+ await waitFor(() =>+ expect(mocks.getAgyAccountQuota).toHaveBeenCalledWith("b", false),+ );+ expect(screen.queryByText("剩余 80%")).not.toBeInTheDocument();++ act(() => {+ window.dispatchEvent(new Event("focus"));+ });++ expect(await screen.findByText("剩余 80%")).toBeInTheDocument();+ expect(mocks.authGetStatus).toHaveBeenCalledTimes(2);+ expect(mocks.getAgyAccountQuota).toHaveBeenCalledTimes(2);+ expect(mocks.getAgyAccountQuota).toHaveBeenLastCalledWith("b", false);});});