Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

37.2 KB
Raw Blame
//! Antigravity 官方账号的状态与专用命令(加号、切号走授权中心的通用 `auth_*` 命令)。

use std::future::Future;
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;
use crate::error::AppError;
use crate::services::agy_account::AgyAccountManager;
use crate::services::subscription::SubscriptionQuota;

const TOOL: &str = "agy";

/// `login_surface` 的取值:ACP 应用内登录 / 终端里跑 agy / Antigravity 桌面端登录。
pub(crate) const LOGIN_SURFACE_ACP: &str = "acp";
pub(crate) const LOGIN_SURFACE_TERMINAL: &str = "terminal";
pub(crate) const LOGIN_SURFACE_DESKTOP: &str = "desktop";

/// 「添加账号」的登录入口:找到 agy 就在终端里跑(现有方式);没找到但装了 Antigravity
/// 桌面端就交给桌面端登录(桌面端 Sign in 与 CLI 共用同一把系统钥匙串,CC Switch 只观察
/// 收录,不用 agy 的 OAuth 客户端)。都没有时返回 `Missing`。
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum LoginSurface {
    /// agy 可执行文件的路径
    Terminal(PathBuf),
    /// 已安装 Antigravity 桌面端;`Some` 是能直接启动的入口(exe / `.app` / 二进制),
    /// `None` 表示只检测到安装痕迹(如用户数据目录),启动交给用户手动。
    Desktop(Option<PathBuf>),
    /// 既没有 agy 也没有桌面端
    Missing,
}

/// 探测「添加账号」的登录入口(文件系统探测,放阻塞线程里跑)。
/// 若登录 shell 缓存此前记录的是未命中(`None`),绕过 miss TTL 现场重探一次;
/// 已缓存的真实可执行文件仍直接复用,不额外起 shell。
pub(crate) async fn resolve_login_surface() -> LoginSurface {
    tokio::task::spawn_blocking(|| {
        resolve_login_surface_with(
            crate::agy_config::real_agy_bin_reprobe_miss,
            || crate::agy_config::desktop_status().installed,
            crate::agy_config::desktop_launch_target,
        )
    })
    .await
    .unwrap_or(LoginSurface::Missing)
}

fn resolve_login_surface_with<F, D, L>(
    find_bin: F,
    desktop_installed: D,
    desktop_target: L,
) -> LoginSurface
where
    F: FnOnce() -> Option<PathBuf>,
    D: FnOnce() -> bool,
    L: FnOnce() -> Option<PathBuf>,
{
    if let Some(bin) = find_bin() {
        return LoginSurface::Terminal(bin);
    }
    if !desktop_installed() {
        return LoginSurface::Missing;
    }
    LoginSurface::Desktop(desktop_target())
}

/// 界面上的额度查询在这么短的时间里重复时,直接用上一次 `/usage` 的结果,免得同时起好几个 agy。
pub(crate) const QUOTA_REUSE_INTERACTIVE: Duration = Duration::from_secs(20);
/// 失败或未检测到 agy 的结果仅做短时复用,避免并发或托盘悬停反复拉起 agy,又不至于把失败卡太久。
const QUOTA_FAILURE_REUSE: Duration = Duration::from_secs(20);

pub struct AgyAccountState(pub Arc<AgyAccountManager>);

/// 上一次 `/usage` 的结果:查的时候 agy 登着哪个号、什么时候查的。查询期间持锁,
/// 同时来的请求排队等这一次的结果,不另起 agy。
struct LiveQuery {
    account_id: Option<String>,
    at: Instant,
    result: Result<SubscriptionQuota, String>,
}

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")]
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<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, &result.quota);
    Ok(result)
}

/// 只读本地保存的上次额度快照,不读钥匙串、不启动 `agy`。
/// 授权中心展示非当前登录账号的历史额度时用。
#[tauri::command(rename_all = "camelCase")]
pub async fn agy_account_last_quota(
    account_id: String,
    state: tauri::State<'_, AgyAccountState>,
) -> Result<Option<SubscriptionQuota>, String> {
    Ok(state.0.last_quota(&account_id).await)
}

/// 收录 Antigravity 当前登录的账号(已收录的号就更新副本)。状态读取不自动收录没见过
/// 的号,在 agy 或桌面端登录后由用户在授权中心显式收录。
#[tauri::command]
pub async fn agy_account_import_current(
    state: tauri::State<'_, AgyAccountState>,
) -> Result<crate::commands::auth::ManagedAuthAccount, String> {
    let account = state.0.import_current().await.map_err(|e| e.to_string())?;
    Ok(map_agy_account(account.clone(), Some(&account.id)))
}

/// 「添加账号」等待中「重新打开终端」:只再开一个终端,不重置这次登录。新终端换一个退出码文件,
/// 旧终端之后退出不会把这次登录判成失败。
#[tauri::command]
pub async fn agy_account_open_login_terminal(
    state: tauri::State<'_, AgyAccountState>,
) -> Result<(), String> {
    let exit_file = state.0.renew_login_exit_file().await;
    open_agy_login_terminal(exit_file).await
}

/// 「添加账号」等待中「打开 Antigravity」:启动桌面端,不重置这次登录。
#[tauri::command]
pub async fn agy_account_open_desktop() -> Result<(), String> {
    open_agy_desktop().await
}

/// ACP 登录(`agy acp --login`):把用户粘贴的授权码或回调地址写进正在等待的子进程。
#[tauri::command(rename_all = "camelCase")]
pub async fn agy_account_submit_paste(
    flow_id: String,
    value: String,
    state: tauri::State<'_, AgyAccountState>,
) -> Result<(), String> {
    state
        .0
        .submit_paste(&flow_id, &value)
        .await
        .map_err(|error| error.to_string())
}

/// 按账号查到的额度写进托盘的缓存(托盘逐个账号显示)。不能切号的平台查的是 agy 自己的
/// `/usage`,不是这个账号的,不写。
pub(crate) fn remember_account_quota(
    app: &tauri::AppHandle,
    app_state: &crate::store::AppState,
    account_id: String,
    quota: &SubscriptionQuota,
) {
    if !crate::services::agy_account::keychain::supported() {
        return;
    }
    app_state
        .usage_cache
        .put_agy_account(account_id, quota.clone());
    crate::tray::schedule_tray_refresh(app);
}

/// 要不要只给快照、不起 agy:指定的号不是 agy 当前登录的,或者网关在用(钥匙串里的登录
/// 没在用)。只有 agy 正在用的那个登录才实时查。
fn snapshot_only(gateway_in_use: bool, requested: Option<&str>, current: Option<&str>) -> bool {
    gateway_in_use || requested.is_some_and(|requested| current != Some(requested))
}

/// Antigravity 官方登录的额度,只问 agy 自己的 `/usage`(不用 agy 的身份发请求)。
/// 不指定账号就是 agy 现在登着的号;指定的号不是 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> {
    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() {
        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;
    if snapshot_only(gateway, account_id, current.as_deref()) {
        let shown = account_id.or(current.as_deref());
        let last = match shown {
            Some(id) => manager.last_quota(id).await,
            None => None,
        };
        return Ok(AgyAccountQuota {
            quota: last.unwrap_or_else(|| SubscriptionQuota::not_found(TOOL)),
            gateway_in_use: gateway,
        });
    }

    let outcome = query_live_with_cache(
        &LAST_LIVE_QUERY,
        current.as_deref(),
        reuse,
        force,
        crate::services::subscription_agy::get_agy_subscription_quota,
        || async { manager.current_account_id().await == current },
    )
    .await?;
    if !outcome.still_current {
        // 查询期间已切到别的号:这份实时结果不能归到指定账号上,改回它已保存的上次快照
        if let Some(account_id) = account_id {
            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 {
        if let Some(account_id) = current.as_deref() {
            manager.record_quota(account_id, &outcome.quota).await;
        }
    }
    Ok(AgyAccountQuota {
        quota: outcome.quota,
        gateway_in_use: false,
    })
}

struct LiveQueryResult {
    quota: SubscriptionQuota,
    should_record: bool,
    still_current: bool,
}

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>
where
    F: FnOnce() -> Fut,
    Fut: Future<Output = Result<SubscriptionQuota, String>>,
    C: FnOnce() -> CFut,
    CFut: Future<Output = bool>,
{
    let mut last = cache.lock().await;
    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。
    let result = fetch().await;
    // 查询要七八秒:期间在别处换了号,这份结果就不知道是谁的,不记到任何账号上
    let still_current = is_still_current().await;
    let should_record = still_current && result.as_ref().is_ok_and(|quota| quota.success);
    if still_current {
        *last = Some(LiveQuery {
            account_id: current.map(str::to_string),
            at: Instant::now(),
            result: result.clone(),
        });
    }
    Ok(LiveQueryResult {
        quota: result?,
        should_record,
        still_current,
    })
}

/// Unix 终端里跑的登录命令:完整路径直呼刚探测到的 `agy`,没探测到时退回裸 `agy` 交给
/// 用户 shell 的 PATH 解析(探测失败时 shell 里大概率也没有,命令不存在诊断会留在窗口里)。
/// `env -u` 去掉可能残留的 Key,免得 agy 改走 Key 模式。
/// `proxy_vars` 是要带进终端的全局代理环境变量(见 [`login_proxy_vars`])。
#[cfg_attr(windows, allow(dead_code))]
fn format_unix_login_command(bin: Option<&Path>, proxy_vars: &[(&str, String)]) -> String {
    let invocation = match bin {
        Some(path) => {
            let escaped = path.to_string_lossy().replace('\'', "'\\''");
            format!("'{escaped}'")
        }
        None => TOOL.to_string(),
    };
    let mut parts = vec!["env -u GEMINI_API_KEY -u GOOGLE_GEMINI_BASE_URL".to_string()];
    for (key, value) in proxy_vars {
        let escaped = value.replace('\'', "'\\''");
        parts.push(format!("{key}='{escaped}'"));
    }
    parts.push(invocation);
    parts.join(" ")
}

/// Go 版 agy 不读系统代理:CC Switch 设了全局代理时,登录终端里也带上(含 SOCKS5)。
/// 用户环境里已经设了的变量不覆盖。
fn login_proxy_vars() -> Vec<(&'static str, String)> {
    crate::proxy::http_client::get_current_proxy_url()
        .map(|url| {
            crate::services::claude_account::login::global_proxy_env(&url, true, |key| {
                std::env::var_os(key).is_some()
            })
        })
        .unwrap_or_default()
}

/// 打开用户首选终端运行 `agy`,让用户在 agy 自己的界面里登录要添加的账号。
/// 「重新打开终端」也走这里:现场重新定位 agy(等待期间用户可能刚装好)。
pub(crate) async fn open_agy_login_terminal(exit_file: Option<PathBuf>) -> Result<(), String> {
    let bin = tokio::task::spawn_blocking(crate::agy_config::real_agy_bin_fresh)
        .await
        .map_err(|e| format!("launch task join error: {e}"))?;
    open_terminal_with_bin(bin, exit_file).await
}

/// 用已知路径打开终端运行 `agy`(`start_login` 已先收好原登录并暂时清掉钥匙串,新开的
/// `agy` 会直接进登录界面)。Windows 直接把 `agy.exe` 完整路径交给终端,不写临时 .bat:
/// .bat 里的命令要交给 cmd 按 PATH 解析,残留的启动器脚本(如被卸载 CLI 留下的
/// `agy.cmd`)会把客户端文件重新下载回来;没定位到 `agy.exe` 时直接报错,不开必死终端。
/// cmd 分支给路径多包一层双引号,用户名带 `&`、`(`、`)` 等字符(agy 安装目录随之带上)
/// 也能跑;同时经本地命名管道把 `agy.exe` 退出码或用户直接关窗写回 `exit_file`。
/// macOS/Linux 仍走启动脚本——探测只认真正的可执行文件,脚本只负责跑它;`exit_file`
/// 给了时脚本在 agy 退出后把退出码写进去,轮询看到就结束等待。两边都带上全局代理。
pub(crate) async fn open_terminal_with_bin(
    bin: Option<PathBuf>,
    exit_file: Option<PathBuf>,
) -> Result<(), String> {
    let proxy_vars = tokio::task::spawn_blocking(login_proxy_vars)
        .await
        .map_err(|e| format!("launch task join error: {e}"))?;
    #[cfg(target_os = "windows")]
    {
        let Some(bin) = bin else {
            return Err(AppError::localized(
                "agy.account.agy_not_found",
                "未找到 Antigravity CLI(agy)。请先安装它,再点「添加账号」。",
                "No Antigravity CLI (agy) was found. Install it first, then add the account again.",
            )
            .to_string());
        };
        if let Some(path) = exit_file.as_deref() {
            let _ = std::fs::remove_file(path);
        }
        // 清掉旧凭据环境变量,保证 agy 走自己的登录流程(等价于原 .bat 里的 `set "VAR="`)
        crate::commands::terminal_launch::launch_terminal_command_with_exit_file(
            bin,
            Vec::new(),
            proxy_vars,
            &["GEMINI_API_KEY", "GOOGLE_GEMINI_BASE_URL"],
            exit_file,
        )
        .await
    }
    #[cfg(not(target_os = "windows"))]
    {
        let command = format_unix_login_command(bin.as_deref(), &proxy_vars);
        tokio::task::spawn_blocking(move || {
            if let Some(path) = exit_file.as_deref() {
                let _ = std::fs::remove_file(path);
            }
            crate::commands::terminal_launch::launch_terminal_running_with_exit_file(
                &command,
                "agy_login",
                exit_file.as_deref(),
            )
        })
        .await
        .map_err(|e| format!("launch task join error: {e}"))?
    }
}

/// 打开 Antigravity 桌面端,让用户在里面登录要添加的账号(桌面端 Sign in 与 CLI 共用钥匙串)。
pub(crate) async fn open_agy_desktop() -> Result<(), String> {
    let target = tokio::task::spawn_blocking(crate::agy_config::desktop_launch_target)
        .await
        .map_err(|e| format!("launch task join error: {e}"))?;
    open_desktop_with_target(target).await
}

/// 用已知的启动入口打开桌面端;`None` 表示没探测到能直接启动的路径(macOS 试按名字打开,
/// 其它平台交给用户手动打开)。
pub(crate) async fn open_desktop_with_target(target: Option<PathBuf>) -> Result<(), String> {
    tokio::task::spawn_blocking(move || launch_desktop_app(target.as_deref()))
        .await
        .map_err(|e| format!("launch task join error: {e}"))?
}

fn launch_desktop_app(target: Option<&Path>) -> Result<(), String> {
    use std::process::{Command, Stdio};
    let spawn_detached = |mut command: Command| -> Result<(), String> {
        command
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null());
        command.spawn().map(|_| ()).map_err(|error| {
            AppError::localized(
                "agy.account.desktop_launch_failed",
                format!("启动 Antigravity 桌面端失败: {error}"),
                format!("Failed to launch the Antigravity desktop app: {error}"),
            )
            .to_string()
        })
    };
    if let Some(target) = target {
        if cfg!(target_os = "macos") {
            let mut command = Command::new("open");
            command.arg(target);
            return spawn_detached(command);
        }
        return spawn_detached(Command::new(target));
    }
    // 只检测到用户数据目录(装在非标准位置):macOS 还能按名字交给 LaunchServices,
    // 其它平台请用户手动打开(界面提示里有说明,登录流程继续)。
    if cfg!(target_os = "macos") {
        let mut command = Command::new("open");
        command.args(["-a", "Antigravity"]);
        return spawn_detached(command);
    }
    Err(AppError::localized(
        "agy.account.desktop_launch_unavailable",
        "未能自动启动 Antigravity 桌面端,请手动打开它并在其中登录要添加的账号。",
        "Could not launch the Antigravity desktop app automatically. Open it manually and sign in there with the account to add.",
    )
    .to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::services::subscription::{CredentialStatus, QuotaTier};
    use std::sync::atomic::{AtomicUsize, Ordering};

    fn ok_quota(utilization: f64) -> SubscriptionQuota {
        SubscriptionQuota {
            tool: TOOL.to_string(),
            credential_status: CredentialStatus::Valid,
            credential_message: None,
            success: true,
            tiers: vec![QuotaTier {
                name: "agy_gemini_five_hour".to_string(),
                utilization,
                resets_at: None,
                used_value_usd: None,
                max_value_usd: None,
            }],
            extra_usage: None,
            reset_credits: None,
            credits_balance: None,
            plan_name: None,
            error: None,
            queried_at: Some(1),
        }
    }

    #[tokio::test]
    async fn live_cache_uses_short_ttl_for_failures_and_skips_switched_results() {
        let cache = Mutex::new(None);
        let calls = AtomicUsize::new(0);
        let tray_reuse = Duration::from_secs(300);
        let timeout = "Antigravity quota query timed out";

        // 1. 失败在短 TTL(20s)内复用,防止并发/托盘反复拉起 agy
        let first = query_live_with_cache(
            &cache,
            Some("alice"),
            tray_reuse,
            false,
            || async {
                calls.fetch_add(1, Ordering::SeqCst);
                Err(timeout.to_string())
            },
            || async { true },
        )
        .await;
        assert_eq!(first.err().as_deref(), Some(timeout));
        assert_eq!(calls.load(Ordering::SeqCst), 1);

        let cached_fail = query_live_with_cache(
            &cache,
            Some("alice"),
            tray_reuse,
            false,
            || async {
                calls.fetch_add(1, Ordering::SeqCst);
                Ok(ok_quota(50.0))
            },
            || async { true },
        )
        .await;
        assert_eq!(cached_fail.err().as_deref(), Some(timeout));
        assert_eq!(calls.load(Ordering::SeqCst), 1);

        // 2. 超过 20s 后失败过期(即使 tray_reuse = 300s),重新触发查询
        cache.lock().await.as_mut().unwrap().at = Instant::now() - Duration::from_secs(25);
        let retried_fail = query_live_with_cache(
            &cache,
            Some("alice"),
            tray_reuse,
            false,
            || async {
                calls.fetch_add(1, Ordering::SeqCst);
                Ok(SubscriptionQuota::error(
                    TOOL,
                    CredentialStatus::Valid,
                    "failed".into(),
                ))
            },
            || async { true },
        )
        .await
        .unwrap();
        assert!(!retried_fail.quota.success);
        assert!(!retried_fail.should_record);
        assert!(retried_fail.still_current);
        assert_eq!(calls.load(Ordering::SeqCst), 2);

        // 3. 查询期间切号:不覆盖缓存、不记录,并标记 still_current = false 供调用方回退 last_quota
        cache.lock().await.as_mut().unwrap().at = Instant::now() - Duration::from_secs(25);
        let switched = query_live_with_cache(
            &cache,
            Some("alice"),
            tray_reuse,
            false,
            || async {
                calls.fetch_add(1, Ordering::SeqCst);
                Ok(ok_quota(12.0))
            },
            || async { false },
        )
        .await
        .unwrap();
        assert!(!switched.should_record);
        assert!(!switched.still_current);
        assert_eq!(calls.load(Ordering::SeqCst), 3);
        assert!(
            !cache
                .lock()
                .await
                .as_ref()
                .unwrap()
                .result
                .as_ref()
                .unwrap()
                .success
        );

        // 4. 同一账号查询成功写入缓存,25s 后在 300s 复用窗口内仍命中
        cache.lock().await.as_mut().unwrap().at = Instant::now() - Duration::from_secs(25);
        let ok = query_live_with_cache(
            &cache,
            Some("alice"),
            tray_reuse,
            false,
            || async {
                calls.fetch_add(1, Ordering::SeqCst);
                Ok(ok_quota(35.0))
            },
            || async { true },
        )
        .await
        .unwrap();
        assert!(ok.quota.success);
        assert!(ok.should_record);
        assert!(ok.still_current);
        assert_eq!(calls.load(Ordering::SeqCst), 4);

        cache.lock().await.as_mut().unwrap().at = Instant::now() - Duration::from_secs(25);
        let cached = query_live_with_cache(
            &cache,
            Some("alice"),
            tray_reuse,
            false,
            || async {
                calls.fetch_add(1, Ordering::SeqCst);
                Ok(ok_quota(99.0))
            },
            || async { true },
        )
        .await
        .unwrap();
        assert_eq!(cached.quota.tiers[0].utilization, 35.0);
        assert!(!cached.should_record);
        assert!(cached.still_current);
        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!(
            format_unix_login_command(None, &[]),
            "env -u GEMINI_API_KEY -u GOOGLE_GEMINI_BASE_URL agy"
        );
        assert_eq!(
            format_unix_login_command(Some(Path::new("/Users/o'neil/.local/bin/agy")), &[]),
            "env -u GEMINI_API_KEY -u GOOGLE_GEMINI_BASE_URL '/Users/o'\\''neil/.local/bin/agy'"
        );

        // 全局代理带进登录终端(Go 版 agy 不读系统代理),值按单引号转义
        let proxy = vec![
            ("HTTPS_PROXY", "socks5://u:p'[email protected]:1080".to_string()),
            ("NO_PROXY", "localhost,127.0.0.1".to_string()),
        ];
        assert_eq!(
            format_unix_login_command(None, &proxy),
            "env -u GEMINI_API_KEY -u GOOGLE_GEMINI_BASE_URL HTTPS_PROXY='socks5://u:p'\\''[email protected]:1080' NO_PROXY='localhost,127.0.0.1' agy"
        );
    }

    #[cfg(windows)]
    #[tokio::test]
    async fn windows_login_without_agy_fails_instead_of_a_dead_terminal() {
        // 没定位到 agy.exe(卸载后只剩残留启动器脚本也算没定位):不再开终端跑裸 `agy`,
        // 避免 PATH 里的启动器脚本把客户端文件重新下载回来
        let error = open_terminal_with_bin(None, None).await.unwrap_err();
        assert!(error.contains("未找到") && error.contains("agy"));
    }

    #[test]
    fn only_the_login_agy_is_using_is_queried_live() {
        // 没开网关:当前登录(不指定或指定的就是它)实时查,别的号给快照
        assert!(!snapshot_only(false, None, Some("a")));
        assert!(!snapshot_only(false, Some("a"), Some("a")));
        assert!(snapshot_only(false, Some("b"), Some("a")));
        // 网关在用:钥匙串里的登录没在用,谁都只给快照
        assert!(snapshot_only(true, None, Some("a")));
        assert!(snapshot_only(true, Some("a"), Some("a")));
        assert!(snapshot_only(true, None, None));
    }

    #[test]
    fn resolve_login_surface_bypasses_cached_miss_while_reusing_valid_hit() {
        use std::sync::Mutex as StdMutex;

        let tmp = tempfile::tempdir().unwrap();
        let agy = tmp.path().join("agy");
        std::fs::write(&agy, "#!/bin/sh\nexit 0\n").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&agy, std::fs::Permissions::from_mode(0o755)).unwrap();
        }
        let desktop = tmp.path().join("Antigravity.app");
        let cache: StdMutex<Option<crate::agy_config::LoginShellCacheEntry>> = StdMutex::new(None);
        let probes = AtomicUsize::new(0);
        let t0 = Instant::now();

        // 1. 后台查询未找到 agy,在 60s 内缓存 None miss;期间回退到桌面端或 Missing
        let bg_miss =
            crate::agy_config::cached_login_shell_agy_with(&cache, "/bin/zsh", t0, false, |_| {
                probes.fetch_add(1, Ordering::SeqCst);
                None
            });
        assert_eq!(bg_miss, None);
        assert_eq!(probes.load(Ordering::SeqCst), 1);

        let desktop_fallback = resolve_login_surface_with(
            || {
                crate::agy_config::cached_login_shell_agy_with(
                    &cache,
                    "/bin/zsh",
                    t0 + Duration::from_secs(5),
                    true,
                    |_| {
                        probes.fetch_add(1, Ordering::SeqCst);
                        None
                    },
                )
            },
            || true,
            || Some(desktop.clone()),
        );
        assert_eq!(desktop_fallback, LoginSurface::Desktop(Some(desktop)));
        assert_eq!(probes.load(Ordering::SeqCst), 2);

        let missing_fallback = resolve_login_surface_with(
            || {
                crate::agy_config::cached_login_shell_agy_with(
                    &cache,
                    "/bin/zsh",
                    t0 + Duration::from_secs(6),
                    true,
                    |_| {
                        probes.fetch_add(1, Ordering::SeqCst);
                        None
                    },
                )
            },
            || false,
            || None,
        );
        assert_eq!(missing_fallback, LoginSurface::Missing);
        assert_eq!(probes.load(Ordering::SeqCst), 3);

        // 2. 用户随后安装好 agy 并点击「添加账号」:即使仍在 60s miss TTL 内,仍绕过 miss 缓存重探并命中
        let added = resolve_login_surface_with(
            || {
                crate::agy_config::cached_login_shell_agy_with(
                    &cache,
                    "/bin/zsh",
                    t0 + Duration::from_secs(10),
                    true,
                    |_| {
                        probes.fetch_add(1, Ordering::SeqCst);
                        Some(agy.clone())
                    },
                )
            },
            || panic!("desktop status should not be checked once agy is found"),
            || panic!("desktop target should not be checked once agy is found"),
        );
        assert_eq!(added, LoginSurface::Terminal(agy.clone()));
        assert_eq!(probes.load(Ordering::SeqCst), 4);

        // 3. 已缓存有效路径时,再次点击「添加账号」直接零成本复用,不再触发 shell 探测
        let reused = resolve_login_surface_with(
            || {
                crate::agy_config::cached_login_shell_agy_with(
                    &cache,
                    "/bin/zsh",
                    t0 + Duration::from_secs(15),
                    true,
                    |_| {
                        probes.fetch_add(1, Ordering::SeqCst);
                        None
                    },
                )
            },
            || false,
            || None,
        );
        assert_eq!(reused, LoginSurface::Terminal(agy));
        assert_eq!(probes.load(Ordering::SeqCst), 4);
    }

    #[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);
    }
}