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): deduplicate focus sync, hide gateway not_found, and avoid blocking switch (#10259)
pablo05d9386c1c0b
diff --git a/src-tauri/src/commands/agy_account.rs b/src-tauri/src/commands/agy_account.rsindex c39a82da4..8e250af98 100644--- a/src-tauri/src/commands/agy_account.rs+++ b/src-tauri/src/commands/agy_account.rs@@ -5,6 +5,7 @@ use std::path::{Path, PathBuf};use std::sync::{Arc, LazyLock};use std::time::{Duration, Instant};+use serde::Serialize;use tokio::sync::Mutex;use crate::commands::auth::map_agy_account;@@ -64,6 +65,17 @@ struct LiveQuery {static LAST_LIVE_QUERY: LazyLock<Mutex<Option<LiveQuery>>> = LazyLock::new(|| Mutex::new(None));+/// 授权中心 / 绑号卡的 Antigravity 账号额度:Enterprise Gateway 在用时附带 `gatewayInUse: true`,+/// 供界面区分「未检测到 agy」与「网关在用且无快照」,避免对网关在用状态给出无效重试提示。+#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct AgyAccountQuota {+ #[serde(flatten)]+ pub quota: SubscriptionQuota,+ #[serde(skip_serializing_if = "std::ops::Not::not")]+ pub gateway_in_use: bool,+}+/// 授权中心逐个账号、以及绑了账号的官方卡显示的剩余额度。agy 正登着这个号时问 agy 的/// `/usage`;别的号返回切走前最后一次查到的(没查到过时为「没有凭据」,界面不显示)。#[tauri::command(rename_all = "camelCase")]@@ -73,16 +85,16 @@ pub async fn agy_account_quota(account_id: String,force: Option<bool>,state: tauri::State<'_, AgyAccountState>,-) -> Result<SubscriptionQuota, String> {- let quota = agy_quota(+) -> Result<AgyAccountQuota, String> {+ let result = agy_quota_with_gateway(&state.0,Some(&account_id),QUOTA_REUSE_INTERACTIVE,force.unwrap_or(false),).await?;- remember_account_quota(&app, &app_state, account_id, "a);- Ok(quota)+ remember_account_quota(&app, &app_state, account_id, &result.quota);+ Ok(result)}/// 只读本地保存的上次额度快照,不读钥匙串、不启动 `agy`。@@ -168,8 +180,28 @@ pub(crate) async fn agy_quota(reuse: Duration,force: bool,) -> Result<SubscriptionQuota, String> {+ agy_quota_with_gateway(manager, account_id, reuse, force)+ .await+ .map(|result| result.quota)+}++async fn agy_quota_with_gateway(+ manager: &AgyAccountManager,+ account_id: Option<&str>,+ reuse: Duration,+ force: bool,+) -> Result<AgyAccountQuota, String> {if !crate::services::agy_account::keychain::supported() {- return crate::services::subscription_agy::get_agy_subscription_quota().await;+ let gateway = crate::services::subscription_agy::gateway_in_use().await;+ let quota = if gateway {+ SubscriptionQuota::not_found(TOOL)+ } else {+ crate::services::subscription_agy::get_agy_subscription_quota().await?+ };+ return Ok(AgyAccountQuota {+ quota,+ gateway_in_use: gateway,+ });}let current = manager.current_account_id().await;let gateway = crate::services::subscription_agy::gateway_in_use().await;@@ -179,7 +211,10 @@ pub(crate) async fn agy_quota(Some(id) => manager.last_quota(id).await,None => None,};- return Ok(last.unwrap_or_else(|| SubscriptionQuota::not_found(TOOL)));+ return Ok(AgyAccountQuota {+ quota: last.unwrap_or_else(|| SubscriptionQuota::not_found(TOOL)),+ gateway_in_use: gateway,+ });}let outcome = query_live_with_cache(@@ -194,10 +229,13 @@ pub(crate) async fn agy_quota(if !outcome.still_current {// 查询期间已切到别的号:这份实时结果不能归到指定账号上,改回它已保存的上次快照if let Some(account_id) = account_id {- return Ok(manager- .last_quota(account_id)- .await- .unwrap_or_else(|| SubscriptionQuota::not_found(TOOL)));+ return Ok(AgyAccountQuota {+ quota: manager+ .last_quota(account_id)+ .await+ .unwrap_or_else(|| SubscriptionQuota::not_found(TOOL)),+ gateway_in_use: false,+ });}}if outcome.should_record {@@ -205,7 +243,10 @@ pub(crate) async fn agy_quota(manager.record_quota(account_id, &outcome.quota).await;}}- Ok(outcome.quota)+ Ok(AgyAccountQuota {+ quota: outcome.quota,+ gateway_in_use: false,+ })}struct LiveQueryResult {@@ -716,4 +757,108 @@ mod tests {assert!(snapshot_only(true, Some("a"), Some("a")));assert!(snapshot_only(true, None, None));}++ #[test]+ fn agy_account_quota_serializes_gateway_in_use_only_when_true() {+ let without_gateway = serde_json::to_value(AgyAccountQuota {+ quota: SubscriptionQuota::not_found(TOOL),+ gateway_in_use: false,+ })+ .unwrap();+ assert_eq!(without_gateway["credentialStatus"], "not_found");+ assert!(without_gateway.get("gatewayInUse").is_none());++ let with_gateway = serde_json::to_value(AgyAccountQuota {+ quota: SubscriptionQuota::not_found(TOOL),+ gateway_in_use: true,+ })+ .unwrap();+ assert_eq!(with_gateway["credentialStatus"], "not_found");+ assert_eq!(with_gateway["gatewayInUse"], true);+ }++ #[tokio::test]+ #[serial_test::serial]+ async fn agy_quota_with_gateway_flags_gateway_in_use_when_enterprise_gateway_is_active() {+ use crate::services::agy_account::keychain::{encode, AgyLoginStore};+ use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};++ struct StubLogin(std::sync::Mutex<Option<String>>);+ impl AgyLoginStore for StubLogin {+ fn read(&self) -> Result<Option<String>, AppError> {+ Ok(self.0.lock().unwrap().clone())+ }+ fn write(&self, value: &str) -> Result<(), AppError> {+ *self.0.lock().unwrap() = Some(value.to_string());+ Ok(())+ }+ fn delete(&self) -> Result<(), AppError> {+ *self.0.lock().unwrap() = None;+ Ok(())+ }+ }++ let _home = crate::test_support::TestHome::new();+ let store_dir = tempfile::tempdir().unwrap();+ let payload = URL_SAFE_NO_PAD.encode(+ serde_json::to_vec(&serde_json::json!({"sub": "alice", "email": "[email protected]"}))+ .unwrap(),+ );+ let raw_cred = encode(&serde_json::json!({+ "token": {+ "access_token": "a1",+ "token_type": "Bearer",+ "refresh_token": "r1",+ "expiry": "2099-01-01T00:00:00Z",+ "expires_in": 3599+ },+ "auth_method": "consumer",+ "id_token": format!("e30.{payload}.sig")+ }))+ .unwrap();+ let login = Arc::new(StubLogin(std::sync::Mutex::new(Some(raw_cred))));+ let manager = AgyAccountManager::with_login_store(store_dir.path().to_path_buf(), login);+ manager.import_current().await.unwrap();++ let gateway_path = crate::agy_config::gateway_config_path();+ std::fs::create_dir_all(gateway_path.parent().unwrap()).unwrap();+ std::fs::write(+ &gateway_path,+ r#"{"gateway":{"enabled":true,"url":"https://relay.example","apiKey":"k"}}"#,+ )+ .unwrap();++ // 1. 网关在用且无本地快照:返回 not_found + gateway_in_use = true+ let no_snapshot =+ agy_quota_with_gateway(&manager, Some("alice"), QUOTA_REUSE_INTERACTIVE, false)+ .await+ .unwrap();+ assert!(matches!(+ no_snapshot.quota.credential_status,+ CredentialStatus::NotFound+ ));+ assert!(no_snapshot.gateway_in_use);++ // 2. 网关在用但有历史快照:照常返回快照且保留 gateway_in_use = true+ manager.record_quota("alice", &ok_quota(35.0)).await;+ let with_snapshot =+ agy_quota_with_gateway(&manager, Some("alice"), QUOTA_REUSE_INTERACTIVE, false)+ .await+ .unwrap();+ assert!(with_snapshot.quota.success);+ assert_eq!(with_snapshot.quota.tiers[0].utilization, 35.0);+ assert!(with_snapshot.gateway_in_use);++ // 3. 关闭网关后,非当前号缺快照不带 gateway_in_use+ std::fs::write(&gateway_path, r#"{"gateway":{"enabled":false}}"#).unwrap();+ let without_gateway =+ agy_quota_with_gateway(&manager, Some("bob"), QUOTA_REUSE_INTERACTIVE, false)+ .await+ .unwrap();+ assert!(matches!(+ without_gateway.quota.credential_status,+ CredentialStatus::NotFound+ ));+ assert!(!without_gateway.gateway_in_use);+ }}diff --git a/src/App.tsx b/src/App.tsxindex ed8b9e2b1..b5b70a77f 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -26,6 +26,7 @@ import { KNOWN_APP_TYPES, type AppTypeFilter } from "@/types/usage";import type { EnvConflict } from "@/types/env";import type { SubscriptionQuota } from "@/types/subscription";import {+ invalidateAgyLoginCaches,invalidateClaudeOfficialLoginCaches,invalidateGrokCliLoginCaches,} from "@/lib/query/subscription";@@ -558,6 +559,12 @@ function App() {// 托盘切卡、应用项目同样可能把默认登录收成新账号await invalidateClaudeOfficialLoginCaches(queryClient);}+ if (event.appType === "agy") {+ // 托盘切卡同样可能切换 Antigravity 网关或绑定账号;只等快速的登录状态,额度后台异步刷新+ await invalidateAgyLoginCaches(queryClient, {+ awaitQuota: false,+ });+ }if (event.appType === "grokbuild") {// 托盘切卡同样可能把 Grok CLI 原登录收成新账号、换成绑定的号await invalidateGrokCliLoginCaches(queryClient);diff --git a/src/components/settings/auth/AccountQuota.tsx b/src/components/settings/auth/AccountQuota.tsxindex 233f4f246..88f53dd18 100644--- a/src/components/settings/auth/AccountQuota.tsx+++ b/src/components/settings/auth/AccountQuota.tsx@@ -526,17 +526,20 @@ function CurrentAgyAccountQuota({refetch,manualIdle,} = useAgyAccountQuota(accountId, { enabled: true, autoQuery: false });- // 当前账号拿到 not_found 时不能把额度列隐藏,否则 ↻ 重试按钮会一起消失(重试期间保持 loading 避免闪烁)+ // 当前账号拿到 not_found 时不能把额度列隐藏,否则 ↻ 重试按钮会一起消失(重试期间保持 loading 避免闪烁);+ // 但 Enterprise Gateway 在用且无本地快照时,点重试也查不到,照旧隐藏整列。const state: AccountQuotaState =quota?.credentialStatus === "not_found"- ? loading- ? { kind: "loading" }- : {- kind: "failed",- reason: t("authCenter.agy.quotaNotFound", {- defaultValue: "未检测到 agy 或登录状态已变化,请重试。",- }),- }+ ? quota.gatewayInUse+ ? null+ : loading+ ? { kind: "loading" }+ : {+ kind: "failed",+ reason: t("authCenter.agy.quotaNotFound", {+ defaultValue: "未检测到 agy 或登录状态已变化,请重试。",+ }),+ }: subscriptionQuotaState(t, quota, loading, i18n.language, display);return (<AccountQuotaColumndiff --git a/src/lib/api/subscription.ts b/src/lib/api/subscription.tsindex ad60ccf92..1e1528827 100644--- a/src/lib/api/subscription.ts+++ b/src/lib/api/subscription.ts@@ -1,5 +1,6 @@import { invoke } from "@tauri-apps/api/core";import type {+ AgyAccountQuota,ClaudeAccountPlan,ClaudeAccountQuota,SubscriptionQuota,@@ -21,7 +22,7 @@ export const subscriptionApi = {getAgyAccountQuota: (accountId: string,force = false,- ): Promise<SubscriptionQuota> =>+ ): Promise<AgyAccountQuota> =>invoke("agy_account_quota",force ? { accountId, force: true } : { accountId },diff --git a/src/lib/query/mutations.ts b/src/lib/query/mutations.tsindex dcbf54c70..b2791d3ec 100644--- a/src/lib/query/mutations.ts+++ b/src/lib/query/mutations.ts@@ -476,6 +476,10 @@ export const useSwitchProviderMutation = (appId: AppId) => {if (appHas(appId, "piFamily")) {await invalidatePiProviderCaches(queryClient, appId);}+ if (appId === "agy") {+ // 切卡可能切换 Antigravity 网关或绑定账号;只等快速的登录状态,额度后台异步刷新,不阻塞切卡+ await invalidateAgyLoginCaches(queryClient, { awaitQuota: false });+ }if (appId === "grokbuild") {// 切到绑号的 Grok 官方卡时,后端可能把原 CLI 登录收成了新账号;// 切换失败前也可能已经收过,所以成功失败都重读授权中心和 CLI 额度diff --git a/src/lib/query/subscription.ts b/src/lib/query/subscription.tsindex 7ad7af286..8d68aeabb 100644--- a/src/lib/query/subscription.ts+++ b/src/lib/query/subscription.ts@@ -12,6 +12,7 @@ import { authApi } from "@/lib/api";import type { AppId } from "@/lib/api/types";import type { ProviderMeta } from "@/types";import type {+ AgyAccountQuota,ClaudeAccountPlan,SubscriptionQuota,} from "@/types/subscription";@@ -92,8 +93,14 @@ export async function invalidateAgyQuotaCaches(* Refresh the actual agy login and every Antigravity quota: only the account agy is* signed in with can be queried, so a switch changes which one shows live numbers.*/-export async function invalidateAgyLoginCaches(queryClient: QueryClient) {- await resetAgyNotFoundQuotas(queryClient);+export async function invalidateAgyLoginCaches(+ queryClient: QueryClient,+ options?: { awaitQuota?: boolean },+) {+ const awaitQuota = options?.awaitQuota ?? true;+ if (awaitQuota) {+ await resetAgyNotFoundQuotas(queryClient);+ }// 先刷新当前登录号,再按最新的当前号失效额度缓存。await queryClient.invalidateQueries({queryKey: agyAuthStatusQuery.queryKey,@@ -105,34 +112,64 @@ export async function invalidateAgyLoginCaches(queryClient: QueryClient) {statusState && !statusState.isInvalidated? (statusState.data?.default_account_id ?? null): undefined;- await invalidateAgyQuotaCaches(queryClient, currentAccountId);+ const quotaInvalidation = invalidateAgyQuotaCaches(+ queryClient,+ currentAccountId,+ );+ if (awaitQuota) {+ await quotaInvalidation;+ } else {+ void quotaInvalidation.catch(() => undefined);+ }}+const inFlightAgyFocusStatusSync = new WeakMap<QueryClient, Promise<void>>();+/**- * 窗口重新聚焦时同步 Antigravity 登录状态;若用户在外部终端换了号,- * 同步清理旧的 not_found 并失效额度缓存。+ * 窗口重新聚焦时同步 Antigravity 登录状态;同一 QueryClient 并发聚焦(如多张绑号卡各自订阅)+ * 共享本次状态检查并在检查完成后立即释放锁,避免卡在后续 7–30 秒额度重查期间而吞掉下一次聚焦切换。+ * 若用户在外部终端换了号,同步清理旧的 not_found 并失效额度缓存。*/export async function syncAgyLoginOnWindowFocus(queryClient: QueryClient) {- const previous = queryClient.getQueryData<ManagedAuthStatus>(- agyAuthStatusQuery.queryKey,- );- await queryClient.invalidateQueries({- queryKey: agyAuthStatusQuery.queryKey,- });- const nextState = queryClient.getQueryState<ManagedAuthStatus>(- agyAuthStatusQuery.queryKey,- );- if (- previous !== undefined &&- nextState &&- !nextState.isInvalidated &&- nextState.data !== undefined &&- previous.default_account_id !== nextState.data.default_account_id- ) {- await invalidateAgyQuotaCaches(- queryClient,- nextState.data.default_account_id ?? null,+ const inFlight = inFlightAgyFocusStatusSync.get(queryClient);+ if (inFlight) {+ await inFlight;+ return;+ }++ let shouldInvalidateQuotas = false;+ let nextAccountId: string | null = null;+ const statusSync = (async () => {+ const previous = queryClient.getQueryData<ManagedAuthStatus>(+ agyAuthStatusQuery.queryKey,+ );+ await queryClient.invalidateQueries({+ queryKey: agyAuthStatusQuery.queryKey,+ });+ const nextState = queryClient.getQueryState<ManagedAuthStatus>(+ agyAuthStatusQuery.queryKey,);+ if (+ previous !== undefined &&+ nextState &&+ !nextState.isInvalidated &&+ nextState.data !== undefined &&+ previous.default_account_id !== nextState.data.default_account_id+ ) {+ shouldInvalidateQuotas = true;+ nextAccountId = nextState.data.default_account_id ?? null;+ }+ })().finally(() => {+ if (inFlightAgyFocusStatusSync.get(queryClient) === statusSync) {+ inFlightAgyFocusStatusSync.delete(queryClient);+ }+ });++ inFlightAgyFocusStatusSync.set(queryClient, statusSync);+ await statusSync;++ if (shouldInvalidateQuotas) {+ await invalidateAgyQuotaCaches(queryClient, nextAccountId);}}@@ -286,14 +323,14 @@ const QUERY_REJECTED_PLACEHOLDER: SubscriptionQuota = {* `scopeKey` 标识查询身份(appId / 绑定的账号 id):身份变化时丢弃旧快照,* 避免用上一个账号的额度掩盖新账号的瞬时失败。*/-function useQuotaKeepLastGood(- query: UseQueryResult<SubscriptionQuota>,+function useQuotaKeepLastGood<T extends SubscriptionQuota>(+ query: UseQueryResult<T>,scopeKey: string,policy: QuotaPolicy,) {const lastGoodRef = useRef<{key: string;- snap: LastGoodSnapshot<SubscriptionQuota> | null;+ snap: LastGoodSnapshot<T> | null;}>({ key: scopeKey, snap: null });if (lastGoodRef.current.key !== scopeKey) {lastGoodRef.current = { key: scopeKey, snap: null };@@ -316,10 +353,10 @@ function useQuotaKeepLastGood(data:data ??(query.isError- ? {+ ? ({...QUERY_REJECTED_PLACEHOLDER,error: extractErrorMessage(query.error) || null,- }+ } as T): undefined),};}@@ -493,7 +530,7 @@ export function useAgyAccountQuota(const seenForceEpoch = useRef(agyForceRefreshEpoch);const policy = useQuotaPolicy();const autoAllowed = policy.autoAllowed;- const query = useQuery({+ const query = useQuery<AgyAccountQuota>({queryKey: ["agy_oauth", "quota", accountId],queryFn: () => {const skipCache =diff --git a/src/types/subscription.ts b/src/types/subscription.tsindex 5e70fce41..95d86c142 100644--- a/src/types/subscription.ts+++ b/src/types/subscription.ts@@ -55,3 +55,8 @@ export interface ClaudeAccountPlan {export interface ClaudeAccountQuota extends SubscriptionQuota {plan?: ClaudeAccountPlan | null;}++/** Antigravity 账号额度(Enterprise Gateway 在用时附带 `gatewayInUse: true`) */+export interface AgyAccountQuota extends SubscriptionQuota {+ gatewayInUse?: boolean;+}diff --git a/tests/components/AgyAccountQuota.test.tsx b/tests/components/AgyAccountQuota.test.tsxindex 08bc6ab68..a4972e600 100644--- a/tests/components/AgyAccountQuota.test.tsx+++ b/tests/components/AgyAccountQuota.test.tsx@@ -18,9 +18,13 @@ import { RefreshAllQuotaButton } from "@/components/settings/auth/RefreshAllQuotimport {agyAuthStatusQuery,invalidateAgyLoginCaches,+ syncAgyLoginOnWindowFocus,useAgyAccountQuota,} from "@/lib/query/subscription";-import type { SubscriptionQuota } from "@/types/subscription";+import type {+ AgyAccountQuota as AgyAccountQuotaResult,+ SubscriptionQuota,+} from "@/types/subscription";import zh from "@/i18n/locales/zh.json";const mocks = vi.hoisted(() => ({@@ -803,4 +807,244 @@ describe("AgyAccountQuota", () => {expect(mocks.getAgyAccountQuota).toHaveBeenCalledTimes(2);expect(mocks.getAgyAccountQuota).toHaveBeenLastCalledWith("b", false);});++ it("deduplicates concurrent window-focus sync across multiple AgyAccountQuotaFooter cards", 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: [],+ });++ let resolveQuotaB!: (quota: AgyAccountQuotaResult) => void;+ mocks.getAgyAccountQuota.mockImplementation((id: string) => {+ if (id === "a") {+ return Promise.resolve(+ makeQuota({+ tiers: [+ { name: "agy_gemini_five_hour", utilization: 10, resetsAt: null },+ ],+ }),+ );+ }+ return new Promise<AgyAccountQuotaResult>((resolve) => {+ resolveQuotaB = resolve;+ });+ });++ const client = newClient();+ // 目标账号 b 预先有非 not_found 快照,确保无去重时第二次 invalidateQueries 会触发 cancelRefetch 重发请求+ client.setQueryData(+ ["agy_oauth", "quota", "b"],+ makeQuota({+ tiers: [+ { name: "agy_gemini_five_hour", utilization: 50, resetsAt: null },+ ],+ }),+ );++ render(+ <>+ <AgyAccountQuotaFooter accountId="a" isCurrent />+ <AgyAccountQuotaFooter accountId="b" isCurrent={false} />+ </>,+ { wrapper: wrapperFor(client) },+ );++ expect(await screen.findByText("剩余 90%")).toBeInTheDocument();+ expect(screen.getByText("剩余 50%")).toBeInTheDocument();+ await waitFor(() => expect(mocks.authGetStatus).toHaveBeenCalledTimes(1));+ expect(mocks.getAgyAccountQuota).toHaveBeenCalledTimes(1);++ mocks.authGetStatus.mockClear();+ mocks.getAgyAccountQuota.mockClear();++ act(() => {+ window.dispatchEvent(new Event("focus"));+ });++ await waitFor(() =>+ expect(mocks.getAgyAccountQuota).toHaveBeenCalledTimes(1),+ );+ expect(mocks.authGetStatus).toHaveBeenCalledTimes(1);+ expect(mocks.getAgyAccountQuota).toHaveBeenCalledWith("b", false);++ // 等待一轮微任务后再校验,确保没有被 cancelRefetch 取消重发第二次查询+ await act(async () => {+ await Promise.resolve();+ });+ expect(mocks.getAgyAccountQuota).toHaveBeenCalledTimes(1);++ await act(async () => {+ resolveQuotaB(+ makeQuota({+ tiers: [+ { name: "agy_gemini_five_hour", utilization: 20, resetsAt: null },+ ],+ }),+ );+ });++ expect(await screen.findByText("剩余 80%")).toBeInTheDocument();+ expect(mocks.authGetStatus).toHaveBeenCalledTimes(1);+ expect(mocks.getAgyAccountQuota).toHaveBeenCalledTimes(1);+ });++ it("releases the focus-sync lock once auth_status completes so a later focus during a slow quota fetch is not swallowed", 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: [],+ })+ .mockResolvedValueOnce({+ provider: "agy_oauth",+ authenticated: true,+ default_account_id: "c",+ accounts: [],+ });++ let resolveQuotaB!: (quota: AgyAccountQuotaResult) => void;+ mocks.getAgyAccountQuota.mockImplementation((id: string) => {+ if (id === "b") {+ return new Promise<AgyAccountQuotaResult>((resolve) => {+ resolveQuotaB = resolve;+ });+ }+ return Promise.resolve(+ makeQuota({+ tiers: [+ { name: "agy_gemini_five_hour", utilization: 10, resetsAt: null },+ ],+ }),+ );+ });++ const client = newClient();+ client.setQueryData(+ ["agy_oauth", "quota", "b"],+ makeQuota({+ tiers: [+ { name: "agy_gemini_five_hour", utilization: 50, resetsAt: null },+ ],+ }),+ );+ client.setQueryData(+ ["agy_oauth", "quota", "c"],+ makeQuota({+ tiers: [+ { name: "agy_gemini_five_hour", utilization: 60, resetsAt: null },+ ],+ }),+ );++ function Observers() {+ useQuery(agyAuthStatusQuery);+ const b = useAgyAccountQuota("b");+ const c = useAgyAccountQuota("c");+ return (+ <span>+ {b.data?.tiers[0]?.utilization ?? "none"}/+ {c.data?.tiers[0]?.utilization ?? "none"}+ </span>+ );+ }++ render(<Observers />, { wrapper: wrapperFor(client) });+ expect(await screen.findByText("50/60")).toBeInTheDocument();+ await waitFor(() => expect(mocks.authGetStatus).toHaveBeenCalledTimes(1));+ mocks.authGetStatus.mockClear();++ let focusOneA!: Promise<void>;+ let focusOneB!: Promise<void>;+ act(() => {+ focusOneA = syncAgyLoginOnWindowFocus(client);+ focusOneB = syncAgyLoginOnWindowFocus(client);+ });++ await waitFor(() =>+ expect(mocks.getAgyAccountQuota).toHaveBeenCalledWith("b", false),+ );+ expect(mocks.authGetStatus).toHaveBeenCalledTimes(1);+ expect(mocks.getAgyAccountQuota).toHaveBeenCalledTimes(1);++ // 首次聚焦的 b 额度查询仍在挂起期间,再次聚焦(外部已切到 c)不能被吞掉+ await act(async () => {+ await syncAgyLoginOnWindowFocus(client);+ });++ expect(mocks.authGetStatus).toHaveBeenCalledTimes(2);+ expect(mocks.getAgyAccountQuota).toHaveBeenCalledTimes(2);+ expect(mocks.getAgyAccountQuota).toHaveBeenLastCalledWith("c", false);+ expect(await screen.findByText("50/10")).toBeInTheDocument();++ await act(async () => {+ resolveQuotaB(+ makeQuota({+ tiers: [+ { name: "agy_gemini_five_hour", utilization: 25, resetsAt: null },+ ],+ }),+ );+ await Promise.all([focusOneA, focusOneB]);+ });+ expect(await screen.findByText("25/10")).toBeInTheDocument();+ });++ it("hides current account quota column instead of showing not_found retry when Enterprise Gateway is in use without a snapshot", async () => {+ mocks.getSettings.mockResolvedValue({});+ mocks.getAgyAccountQuota.mockResolvedValue({+ ...NOT_FOUND_QUOTA,+ gatewayInUse: true,+ });++ const { container } = render(+ <AgyAccountQuota accountId="a" login="[email protected]" isCurrent />,+ { wrapper: wrapperFor(newClient()) },+ );++ await waitFor(() =>+ expect(mocks.getAgyAccountQuota).toHaveBeenCalledWith("a", false),+ );+ await waitFor(() => expect(container).toBeEmptyDOMElement());+ expect(+ screen.queryByText(zh.authCenter.agy.quotaNotFound),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "刷新 [email protected] 的额度" }),+ ).not.toBeInTheDocument();+ });++ it("still shows stored snapshot when Enterprise Gateway is in use", async () => {+ mocks.getSettings.mockResolvedValue({});+ mocks.getAgyAccountQuota.mockResolvedValue({+ ...makeQuota(),+ gatewayInUse: true,+ });++ render(<AgyAccountQuota accountId="a" login="[email protected]" isCurrent />, {+ wrapper: wrapperFor(newClient()),+ });++ expect(await screen.findByText("剩余 70%")).toBeInTheDocument();+ expect(+ screen.queryByText(zh.authCenter.agy.quotaNotFound),+ ).not.toBeInTheDocument();+ });});diff --git a/tests/hooks/useSwitchProviderResult.test.tsx b/tests/hooks/useSwitchProviderResult.test.tsxindex c1e12694a..e447ebbbf 100644--- a/tests/hooks/useSwitchProviderResult.test.tsx+++ b/tests/hooks/useSwitchProviderResult.test.tsx@@ -1,10 +1,15 @@import type { ReactNode } from "react";import { act, renderHook, waitFor } from "@testing-library/react";-import { QueryClientProvider } from "@tanstack/react-query";+import { QueryClientProvider, useQuery } from "@tanstack/react-query";import { http, HttpResponse } from "msw";-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";import { useSwitchProviderMutation } from "@/lib/query/mutations";-import { useSubscriptionQuota } from "@/lib/query/subscription";+import {+ agyAuthStatusQuery,+ subscriptionKeys,+ useAgyAccountQuota,+ useSubscriptionQuota,+} from "@/lib/query/subscription";import { server } from "../msw/server";import { createTestQueryClient } from "../utils/testQueryClient";@@ -166,4 +171,155 @@ describe("provider switch result transport", () => {expect(client.getQueryState(quotaKey)?.isInvalidated).toBe(true);client.clear();});++ it("does not block agy provider switch while active quota queries are hanging", async () => {+ let accountQuotaCalls = 0;+ let subscriptionQuotaCalls = 0;+ let authStatusCalls = 0;+ let trayCalls = 0;+ const validAgyQuota = {+ tool: "agy",+ credentialStatus: "valid",+ credentialMessage: null,+ success: true,+ tiers: [],+ extraUsage: null,+ error: null,+ queriedAt: 1,+ };+ server.use(+ http.post("http://tauri.local/get_settings", () =>+ HttpResponse.json({ officialQuotaManualOnly: false }),+ ),+ http.post("http://tauri.local/auth_get_status", async ({ request }) => {+ const body = (await request.json()) as { authProvider?: string };+ if (body.authProvider === "agy_oauth") {+ authStatusCalls += 1;+ return HttpResponse.json({+ provider: "agy_oauth",+ authenticated: true,+ default_account_id: authStatusCalls === 1 ? "a" : "b",+ accounts: [],+ });+ }+ return HttpResponse.json({+ provider: body.authProvider ?? "",+ authenticated: false,+ default_account_id: null,+ accounts: [],+ });+ }),+ http.post("http://tauri.local/agy_account_quota", () => {+ accountQuotaCalls += 1;+ if (accountQuotaCalls === 1) {+ return HttpResponse.json(validAgyQuota);+ }+ return new Promise(() => {});+ }),+ http.post("http://tauri.local/get_subscription_quota", () => {+ subscriptionQuotaCalls += 1;+ if (subscriptionQuotaCalls === 1) {+ return HttpResponse.json(validAgyQuota);+ }+ return new Promise(() => {});+ }),+ http.post("http://tauri.local/switch_provider", () =>+ HttpResponse.json({ warnings: [] }),+ ),+ http.post("http://tauri.local/update_tray_menu", () => {+ trayCalls += 1;+ return HttpResponse.json(true);+ }),+ );++ const client = createTestQueryClient();+ const lastQuotaKey = ["agy_oauth", "last_quota", "b"];+ const accountQuotaKey = ["agy_oauth", "quota", "b"];+ const subQuotaKey = subscriptionKeys.quota("agy");+ client.setQueryData(lastQuotaKey, null);++ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+ const { result } = renderHook(+ () => ({+ authStatus: useQuery(agyAuthStatusQuery),+ accountQuota: useAgyAccountQuota("b"),+ subQuota: useSubscriptionQuota("agy", true),+ switchMutation: useSwitchProviderMutation("agy"),+ }),+ { wrapper },+ );++ await waitFor(() => {+ expect(result.current.authStatus.isSuccess).toBe(true);+ expect(result.current.accountQuota.isSuccess).toBe(true);+ expect(result.current.subQuota.isSuccess).toBe(true);+ });++ await act(async () => {+ await result.current.switchMutation.mutateAsync("provider-b");+ });++ expect(trayCalls).toBe(1);+ expect(authStatusCalls).toBe(2);+ expect(+ client.getQueryData<{ default_account_id: string | null }>(+ agyAuthStatusQuery.queryKey,+ )?.default_account_id,+ ).toBe("b");+ await waitFor(() => {+ expect(accountQuotaCalls).toBe(2);+ expect(subscriptionQuotaCalls).toBe(2);+ });+ expect(client.getQueryState(lastQuotaKey)?.isInvalidated).toBe(true);+ expect(client.getQueryState(accountQuotaKey)?.isInvalidated).toBe(true);+ expect(client.getQueryState(subQuotaKey)?.isInvalidated).toBe(true);+ client.clear();+ });++ it("swallows background agy quota invalidation failures without unhandled rejections", async () => {+ server.use(+ http.post("http://tauri.local/auth_get_status", () =>+ HttpResponse.json({+ provider: "agy_oauth",+ authenticated: true,+ default_account_id: "b",+ accounts: [],+ }),+ ),+ http.post("http://tauri.local/switch_provider", () =>+ HttpResponse.json({ warnings: [] }),+ ),+ http.post("http://tauri.local/update_tray_menu", () =>+ HttpResponse.json(true),+ ),+ );++ const client = createTestQueryClient();+ client.setQueryData(agyAuthStatusQuery.queryKey, {+ provider: "agy_oauth",+ authenticated: true,+ default_account_id: "a",+ accounts: [],+ });+ const resetSpy = vi+ .spyOn(client, "resetQueries")+ .mockRejectedValueOnce(new Error("reset failed"));++ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+ const { result } = renderHook(() => useSwitchProviderMutation("agy"), {+ wrapper,+ });++ await act(async () => {+ await result.current.mutateAsync("provider-b");+ await Promise.resolve();+ });++ expect(resetSpy).toHaveBeenCalled();+ client.clear();+ });});diff --git a/tests/integration/App.test.tsx b/tests/integration/App.test.tsxindex d578d4fde..19149cb10 100644--- a/tests/integration/App.test.tsx+++ b/tests/integration/App.test.tsx@@ -426,6 +426,83 @@ describe("App integration with MSW", () => {});});+ // 托盘切到 Antigravity 供应商时只等快速的登录状态,不能被 7–30s 的额度查询卡住后续事件处理+ it("refreshes Antigravity auth status and fires quota invalidations without blocking on provider-switched", async () => {+ server.use(+ http.post("http://tauri.local/auth_get_status", async ({ request }) => {+ const body = (await request.json()) as { authProvider?: string };+ if (body.authProvider === "agy_oauth") {+ return HttpResponse.json({+ provider: "agy_oauth",+ authenticated: true,+ default_account_id: "b",+ accounts: [],+ });+ }+ return HttpResponse.json({+ provider: body.authProvider ?? "",+ authenticated: false,+ default_account_id: null,+ accounts: [],+ });+ }),+ );++ const { default: App } = await import("@/App");+ const { client } = renderApp(App);++ await waitFor(() =>+ expect(screen.getByTestId("provider-list").textContent).toContain(+ "claude-1",+ ),+ );++ client.setQueryData(["managed-auth-status", "agy_oauth"], {+ provider: "agy_oauth",+ authenticated: true,+ default_account_id: "a",+ accounts: [],+ });++ const originalInvalidate = client.invalidateQueries.bind(client);+ const invalidateSpy = vi+ .spyOn(client, "invalidateQueries")+ .mockImplementation((filters, options) => {+ const key = filters?.queryKey;+ if (+ Array.isArray(key) &&+ (key[0] === "subscription" || key[0] === "agy_oauth")+ ) {+ return new Promise<void>(() => {});+ }+ return originalInvalidate(filters, options);+ });++ emitTauriEvent("provider-switched", {+ appType: "agy",+ providerId: "agy-2",+ });++ await waitFor(() => {+ expect(invalidateSpy).toHaveBeenCalledWith({+ queryKey: ["managed-auth-status", "agy_oauth"],+ });+ expect(invalidateSpy).toHaveBeenCalledWith({+ queryKey: ["subscription", "quota", "agy"],+ });+ expect(invalidateSpy).toHaveBeenCalledWith({+ queryKey: ["agy_oauth", "last_quota"],+ });+ expect(invalidateSpy).toHaveBeenCalledWith({+ queryKey: ["agy_oauth", "quota"],+ });+ // 必须已越过 await invalidateAgyLoginCaches 继续跑到后面的 codex_oauth 失效,证明未被挂起的额度查询阻塞+ expect(invalidateSpy).toHaveBeenCalledWith(+ expect.objectContaining({ predicate: expect.any(Function) }),+ );+ });+ });+it("invalidates OpenCode membership and both OMO selections after a tray add", async () => {const { default: App } = await import("@/App");const { client } = renderApp(App);