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

57.7 KB
Raw Blame
//! Antigravity CLI 的官方账号:在 CC Switch 里加号、切号。
//!
//! agy 只有一份全局登录,存在系统钥匙串里(见 `keychain`)。CC Switch 自己存每个账号的整份
//! 登录数据(`agy_accounts.json`,0600,不随云同步),切换就是把目标账号那份写进钥匙串,
//! agy 下次启动就是这个号。账号按 id_token 的 `sub` 区分(邮箱可能相同前缀,名字可改);
//! agy 1.5 起钥匙串里没有 id_token,按 refresh token / 邮箱对回已收录的号(见 `read_live`)。
//!
//! 几条规矩:
//! - 加号、切号前先把钥匙串里现在那份收回来:是已收录的号就更新它(agy 续期后写回的新
//!   access token);没收录的号(没见过的、用户删过的、认不出格式的)整条暂存到
//!   `agy-login-stash.json`,不收进账号表——用户没点「收录」就不进授权中心,切走也不会丢。
//! - 查看状态、查额度只刷新已收录的号:钥匙串里没收录过的登录不自动收进账号表(不会
//!   自己冒出来,与其他应用默认不读取一致),由用户在授权中心点「收录当前账号」显式
//!   收进来(`import_current`)。
//! - 从 CC Switch 删账号只删自己的副本,永远不动钥匙串(不替 agy 登出)。
//! - 不自动换号:额度用完、请求出错都不切,切换只由用户触发。
//! - 不发任何网络请求,不用 agy 的身份:不用 agy 的 OAuth 客户端登录或续期,也不拿 agy 的令牌
//!   去问 Google。加号是在 agy 里登录(`start_login` 打开终端运行 agy,钥匙串变了就收录);
//!   认账号只解本地的 id_token / 邮箱;令牌由 agy 自己续期(Google 不轮换 refresh token,
//!   副本里过期的 access token 切过去后 agy 会自己换新)。
//! - 额度只问 agy 自己的 `/usage`,所以只查得到 agy 当前登着的号;查到的按账号记下
//!   (`last_quota`),切走的号显示切走前最后一次查到的。

pub mod acp_login;
pub mod identity;
pub mod keychain;
mod stash;

use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};

use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio::sync::Mutex;

use crate::error::AppError;
use crate::services::subscription::SubscriptionQuota;
use crate::sync_utils::MutexExt;
use keychain::AgyLoginStore;

const STORE_FILENAME: &str = "agy_accounts.json";
const STASH_FILENAME: &str = "agy-login-stash.json";
/// 在 agy 里登录最多等这么久,过了就当放弃。
const LOGIN_TIMEOUT: Duration = Duration::from_secs(10 * 60);

/// 最近一次读到的账号表和 agy 当前登录,见 [`last_known_status`]。
static LAST_KNOWN: std::sync::Mutex<Option<AgyAccountStatus>> = std::sync::Mutex::new(None);

/// 最近一次读到的账号表和 agy 当前登录。托盘建菜单是同步的,也不该每次都起子进程读钥匙串,
/// 就读这份:账号表每次存盘后更新,当前登录在查看状态、切号、查额度读过钥匙串后更新。
/// 还没读过钥匙串时 `current_account_id` 为 `None`。
pub fn last_known_status() -> Option<AgyAccountStatus> {
    LAST_KNOWN.lock_recover().clone()
}

/// 记下账号表;`current` 为 `Some` 时连同刚从钥匙串读到的当前登录一起记,`None` 沿用上次的。
fn remember(store: &StoreFile, current: Option<Option<String>>) {
    let mut last = LAST_KNOWN.lock_recover();
    let current = match current {
        Some(current) => current,
        None => last
            .as_ref()
            .and_then(|status| status.current_account_id.clone()),
    }
    .filter(|id| store.accounts.contains_key(id));
    *last = Some(AgyAccountStatus {
        accounts: sorted_accounts(store),
        current_account_id: current,
        supported: keychain::supported(),
        uncollected_login: None,
    });
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct AccountData {
    sub: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    email: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    name: Option<String>,
    /// agy 钥匙串里那份 JSON 原样保存(以后 agy 新增的字段也跟着走)
    credential: Value,
    authenticated_at: i64,
    #[serde(default)]
    requires_reauth: bool,
    /// agy 登着这个号时最后一次查到的额度(`/usage`),切走后照样显示
    #[serde(default, skip_serializing_if = "Option::is_none")]
    last_quota: Option<SubscriptionQuota>,
}

#[derive(Debug, Default, Serialize, Deserialize)]
struct StoreFile {
    #[serde(default)]
    version: u32,
    #[serde(default)]
    accounts: BTreeMap<String, AccountData>,
    /// 用户在 CC Switch 里删掉、但 agy 还登着的号:查看状态时不再自动收回来。
    /// 切走它时照样收录(切换绝不弄丢登录),收录后就从这里去掉。
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    dismissed: Vec<String>,
    /// 已删账号的 `sub -> email`(不含令牌):agy 1.5 钥匙串里不再带 `id_token`,
    /// 只有 `id_token_email`;留着邮箱才能在不发网的情况下认出钥匙串里还是这个被删掉的号,
    /// 切走时也能按原 `sub` 收回。
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    dismissed_emails: BTreeMap<String, String>,
    /// 写钥匙串前落盘;只有核验、回退文件同步和桌面缓存清理都完成后才清除。
    /// 失败后即使钥匙串已是目标账号,重试(含重启后)也不能直接当成成功。
    #[serde(default)]
    switch_incomplete: bool,
}

#[derive(Debug, Clone, Serialize)]
pub struct AgyAccount {
    pub id: String,
    pub email: Option<String>,
    pub name: Option<String>,
    pub authenticated_at: i64,
    pub requires_reauth: bool,
}

impl AgyAccount {
    /// 界面上显示的名字:邮箱 > 名字 > `Google (<sub 前 6 位>)`。
    pub fn label(&self) -> String {
        self.email
            .clone()
            .or_else(|| self.name.clone())
            .unwrap_or_else(|| {
                let short: String = self.id.chars().take(6).collect();
                format!("Google ({short})")
            })
    }
}

impl From<&AccountData> for AgyAccount {
    fn from(data: &AccountData) -> Self {
        Self {
            id: data.sub.clone(),
            email: data.email.clone(),
            name: data.name.clone(),
            authenticated_at: data.authenticated_at,
            requires_reauth: data.requires_reauth,
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct AgyAccountStatus {
    pub accounts: Vec<AgyAccount>,
    /// agy 当前登录的是哪个已收录的号;没登录、读不到钥匙串、或钥匙串里的登录没收录时为 `None`
    pub current_account_id: Option<String>,
    /// 这个平台能不能切号(macOS、Windows 和 Linux)。
    pub supported: bool,
    /// 钥匙串里现在的登录没收录进账号表时给出它的显示名。状态读取不自动收录(不认识的
    /// 号不会自己冒出来),界面凭它提示用户点「收录当前账号」。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uncollected_login: Option<String>,
}

#[derive(Debug)]
pub struct LoginStart {
    pub flow_id: String,
    pub expires_in: u64,
    /// 桌面端模式:开始时钥匙串里就有一份没收录过的登录,第一次轮询会直接收录它,
    /// 桌面端不需要再登录,也不用打开。
    pub already_signed_in: bool,
    /// 终端模式:终端里的 agy 退出后,启动脚本把退出码写到这里;轮询看到它就立刻结束这次登录,
    /// 不用干等超时。桌面端与 ACP 模式不开终端,为 `None`。
    pub exit_status_file: Option<PathBuf>,
    /// ACP 模式(`agy acp --login`)返回的 Google OAuth 链接;终端/桌面端模式为 `None`。
    pub auth_url: Option<String>,
}

/// 终端里 agy 的退出码文件。登录流程结束(完成、取消、超时、被丢弃)时随之删掉。
struct ExitStatusFile(PathBuf);

impl ExitStatusFile {
    fn new() -> Self {
        Self(std::env::temp_dir().join(format!(
            "cc_switch_agy_exit_{}.status",
            uuid::Uuid::new_v4()
        )))
    }
}

impl Drop for ExitStatusFile {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.0);
    }
}

/// 取消或超时且钥匙串仍为空时要写回的原登录。
struct RestoreLogin {
    raw: String,
    account_id: Option<String>,
}

enum PendingLoginKind {
    /// 终端 / 桌面端登录:监听钥匙串变化(终端模式同时带退出码文件)。
    Keychain {
        baseline: Option<String>,
        saw_logged_out: bool,
        exit_status: Option<ExitStatusFile>,
    },
    /// ACP 登录:后台跑 `agy acp --login`,等用户粘贴回调后子进程写回钥匙串并退出。
    Acp(acp_login::RunningAcpLogin),
}

/// 一次「添加账号」:终端模式开始时先把原登录存下来并暂时清掉钥匙串,让新开的 `agy` 直接进
/// 登录流程;桌面端模式不动钥匙串(只观察);ACP 模式在后台跑 `agy acp --login` 并等粘贴。
struct PendingLogin {
    restore: Option<RestoreLogin>,
    deadline: Instant,
    kind: PendingLoginKind,
}

impl PendingLogin {
    async fn cancel_and_wait(&self) {
        if let PendingLoginKind::Acp(acp) = &self.kind {
            acp.cancel_and_wait().await;
        }
    }
}

/// 钥匙串里当前那份登录,解出来认得是谁时带上身份。
enum LiveLogin {
    None,
    Known {
        credential: Value,
        claims: identity::IdentityClaims,
    },
    /// 读得到但解不开或认不出账号
    Unrecognized(String),
}

impl LiveLogin {
    /// 用来判断钥匙串里的登录换没换:认得出的按 refresh token,认不出的按原文。
    fn fingerprint(&self) -> Option<String> {
        match self {
            Self::None => None,
            Self::Known { credential, .. } => refresh_token_of(credential).map(str::to_string),
            Self::Unrecognized(raw) => Some(raw.clone()),
        }
    }
}

pub struct AgyAccountManager {
    data_dir: PathBuf,
    login: Arc<dyn AgyLoginStore>,
    desktop_user_data_dir: Option<PathBuf>,
    /// 账号表;同时充当所有改动(含写钥匙串)的互斥锁
    store: Mutex<StoreFile>,
    pending: Mutex<HashMap<String, PendingLogin>>,
    /// 串行化登录启动、收尾与切号,覆盖 ACP 等待链接但尚未登记 pending 的阶段。
    login_transition: Mutex<()>,
}

impl AgyAccountManager {
    pub fn new(data_dir: PathBuf) -> Self {
        let standalone_token = crate::config::get_home_dir()
            .join(".gemini")
            .join(keychain::STANDALONE_TOKEN_FILENAME);
        Self::with_parts(
            data_dir,
            Arc::new(keychain::AgyLogin::new(standalone_token)),
            keychain::default_desktop_user_data_dir(),
        )
    }

    pub fn with_login_store(data_dir: PathBuf, login: Arc<dyn AgyLoginStore>) -> Self {
        Self::with_parts(data_dir, login, None)
    }

    #[cfg(test)]
    pub(crate) fn with_test_env(
        data_dir: PathBuf,
        login: Arc<dyn AgyLoginStore>,
        desktop_user_data_dir: Option<PathBuf>,
    ) -> Self {
        Self::with_parts(data_dir, login, desktop_user_data_dir)
    }

    fn with_parts(
        data_dir: PathBuf,
        login: Arc<dyn AgyLoginStore>,
        desktop_user_data_dir: Option<PathBuf>,
    ) -> Self {
        let path = data_dir.join(STORE_FILENAME);
        let store = crate::config::load_json_or_set_aside(&path, "AgyAccount");
        remember(&store, None);
        Self {
            data_dir,
            login,
            desktop_user_data_dir,
            store: Mutex::new(store),
            pending: Mutex::new(HashMap::new()),
            login_transition: Mutex::new(()),
        }
    }

    #[cfg(test)]
    pub async fn has_pending_login(&self) -> bool {
        let now = Instant::now();
        let mut pending = self.pending.lock().await;
        pending.retain(|_, entry| now < entry.deadline);
        !pending.is_empty()
    }

    // ---------- 在 agy 里登录 ----------

    /// 开始「添加账号」(终端模式):先把 agy 现在登着的号收回来(已收录的更新副本,没收录的
    /// 暂存、不进账号表),再暂时清除钥匙串,让新打开的 `agy` 直接进入登录界面。取消、打开终端失败或超时且
    /// 钥匙串仍为空时自动写回原登录。
    pub async fn start_login(&self) -> Result<LoginStart, AppError> {
        self.start_login_inner(true).await
    }

    /// 开始「添加账号」(桌面端模式):没找到 agy 但装了 Antigravity 桌面端时,登录由桌面端
    /// 自己完成——桌面端 Sign in 与 CLI 共用同一把系统钥匙串,这里只读钥匙串等它变化。
    /// 不暂存、不清除、也不写回:原来的登录一直有效。钥匙串里已经是没收录过的登录时,
    /// 第一次轮询就直接收录它(桌面端已有登录不用重新登,见 `already_signed_in`);
    /// 同一个收录过的号重登(refresh token 没变)不会结束,先在桌面端退出再登录才行。
    pub async fn start_login_desktop(&self) -> Result<LoginStart, AppError> {
        self.start_login_inner(false).await
    }

    async fn drain_pending(&self) -> Option<RestoreLogin> {
        let entries: Vec<_> = self
            .pending
            .lock()
            .await
            .drain()
            .map(|(_, entry)| entry)
            .collect();
        let mut carried = None;
        for entry in entries {
            entry.cancel_and_wait().await;
            if carried.is_none() {
                carried = entry.restore;
            }
        }
        carried
    }

    async fn start_login_inner(&self, clear_keychain: bool) -> Result<LoginStart, AppError> {
        let _transition = self.login_transition.lock().await;
        if !keychain::supported() {
            return Err(keychain::unsupported_error());
        }
        let carried_restore = self.drain_pending().await;
        let (baseline, restore, saw_logged_out, already_signed_in) = {
            let mut store = self.store.lock().await;
            let (raw, live) = self.read_live_with_raw(&store, true).await?;
            if let Some(raw_value) = raw {
                let baseline = live.fingerprint();
                // 桌面端模式:钥匙串里已有的登录还没收录过时(用户删过的号也算没收录——
                // 点「添加账号」就是要收录这份登录,被删过的也收回来),这次「添加账号」
                // 要的就是它——baseline 置空,第一次轮询就直接收录,不用再登录;只有
                // 已收录的号才等新登录。
                let fresh_desktop_login = match &live {
                    LiveLogin::Known { credential, .. } => {
                        !clear_keychain && !is_managed_login(&store, credential)
                    }
                    _ => false,
                };
                let (current, changed) = if clear_keychain {
                    // 钥匙串里的登录马上要删掉:没收录的号暂存起来免得弄丢,但不收进账号表
                    self.refresh_or_stash(&mut store, live, &raw_value)?
                } else {
                    // 桌面端模式:登录留在钥匙串里,不用暂存;被用户删过的号也不因此复活
                    absorb(&mut store, live, true, false)
                };
                if changed {
                    self.persist(&store)?;
                }
                if clear_keychain {
                    let login = Arc::clone(&self.login);
                    run_blocking(move || login.delete()).await?;
                    remember(&store, Some(None));
                    (
                        baseline,
                        Some(RestoreLogin {
                            raw: raw_value,
                            account_id: current,
                        }),
                        true,
                        false,
                    )
                } else {
                    remember(&store, Some(current.clone()));
                    (
                        if fresh_desktop_login { None } else { baseline },
                        carried_restore,
                        false,
                        fresh_desktop_login,
                    )
                }
            } else {
                let has_restore = carried_restore.is_some();
                (None, carried_restore, has_restore, false)
            }
        };
        let flow_id = uuid::Uuid::new_v4().to_string();
        let exit_status = clear_keychain.then(ExitStatusFile::new);
        let exit_status_file = exit_status.as_ref().map(|file| file.0.clone());
        let mut pending = self.pending.lock().await;
        pending.insert(
            flow_id.clone(),
            PendingLogin {
                restore,
                deadline: Instant::now() + LOGIN_TIMEOUT,
                kind: PendingLoginKind::Keychain {
                    baseline,
                    saw_logged_out,
                    exit_status,
                },
            },
        );
        Ok(LoginStart {
            flow_id,
            expires_in: LOGIN_TIMEOUT.as_secs(),
            already_signed_in,
            exit_status_file,
            auth_url: None,
        })
    }

    fn stash_live_before_acp_login(
        &self,
        store: &mut StoreFile,
        raw: Option<String>,
        live: LiveLogin,
    ) -> Result<(), AppError> {
        if let Some(raw_value) = raw {
            // 钥匙串里的登录不要因为开始 ACP 登录而自动收录进账号表:未收录或已删的号先暂存,
            // 避免用户没点「收录」就自己冒出来,后续被新登录覆盖也不会丢。
            let (current, changed) = self.refresh_or_stash(store, live, &raw_value)?;
            if changed {
                self.persist(store)?;
            }
            remember(store, Some(current));
        }
        Ok(())
    }

    /// 开始「添加账号」(ACP 应用内模式):启动 `agy acp --login` 返回 Google 授权链接,
    /// 不清空钥匙串(仅先把当前未删除/不认识的登录收好,避免后续写入钥匙串丢登录);
    /// 失败或取消若导致钥匙串为空且携带了此前未恢复的原登录,仍按约定写回。
    pub async fn start_login_acp(&self, bin: &Path) -> Result<LoginStart, AppError> {
        let _transition = self.login_transition.lock().await;
        if !keychain::supported() {
            return Err(keychain::unsupported_error());
        }
        let carried_restore = self.drain_pending().await;
        {
            let mut store = self.store.lock().await;
            let (raw, live) = self.read_live_with_raw(&store, true).await?;
            self.stash_live_before_acp_login(&mut store, raw, live)?;
        }
        let acp = match acp_login::RunningAcpLogin::start(bin, &self.data_dir, LOGIN_TIMEOUT).await
        {
            Ok(acp) => acp,
            Err(error) => {
                self.restore_if_empty(carried_restore).await;
                return Err(error);
            }
        };
        let auth_url = acp.auth_url.authorization_url.clone();
        let flow_id = uuid::Uuid::new_v4().to_string();
        self.pending.lock().await.insert(
            flow_id.clone(),
            PendingLogin {
                restore: carried_restore,
                deadline: Instant::now() + LOGIN_TIMEOUT,
                kind: PendingLoginKind::Acp(acp),
            },
        );
        Ok(LoginStart {
            flow_id,
            expires_in: LOGIN_TIMEOUT.as_secs(),
            already_signed_in: false,
            exit_status_file: None,
            auth_url: Some(auth_url),
        })
    }

    /// ACP 登录(`agy acp --login`):把用户粘贴的授权码或回调 URL 写入子进程 stdin。
    pub async fn submit_paste(&self, flow_id: &str, input: &str) -> Result<(), AppError> {
        let paste_target = {
            let _transition = self.login_transition.lock().await;
            let mut pending = self.pending.lock().await;
            let Some(entry) = pending.get(flow_id) else {
                return Err(login_ended());
            };
            if Instant::now() >= entry.deadline {
                let expired = pending.remove(flow_id);
                drop(pending);
                if let Some(entry) = expired {
                    entry.cancel_and_wait().await;
                    self.restore_if_empty(entry.restore).await;
                }
                return Err(login_ended());
            }
            let PendingLoginKind::Acp(acp) = &entry.kind else {
                return Err(login_ended());
            };
            acp.paste_target()
        };
        paste_target.submit(input).await
    }

    /// 「重新打开终端」:给进行中的终端登录换一个新的退出码文件并返回它。旧终端里的 agy 之后退出
    /// 只会写旧文件,不会把这次登录判成失败。没有进行中的终端登录时返回 `None`。
    pub async fn renew_login_exit_file(&self) -> Option<PathBuf> {
        let mut pending = self.pending.lock().await;
        let now = Instant::now();
        pending.values_mut().find_map(|entry| {
            if now >= entry.deadline {
                return None;
            }
            match &mut entry.kind {
                PendingLoginKind::Keychain {
                    exit_status: slot @ Some(_),
                    ..
                } => {
                    let file = ExitStatusFile::new();
                    let path = file.0.clone();
                    *slot = Some(file);
                    Some(path)
                }
                _ => None,
            }
        })
    }

    /// 将认得出的实时登录收录、同步回退凭据与 Desktop scope 并完成收尾。
    async fn finalize_live_login(
        &self,
        store: &mut StoreFile,
        live: LiveLogin,
    ) -> Result<Option<AgyAccount>, AppError> {
        let (id, _) = absorb(store, live, true, true);
        let Some(id) = id else {
            return Ok(None);
        };
        self.forget_stashed(&id);
        let data = store
            .accounts
            .get(&id)
            .cloned()
            .ok_or_else(|| account_not_found(&id))?;
        // 登录确认也会更新 Desktop 的凭据与缓存;失败后允许切换当前号补齐。
        store.switch_incomplete = true;
        self.persist(store)?;
        let login = Arc::clone(&self.login);
        let credential = data.credential.clone();
        run_blocking(move || login.sync_fallback(&credential)).await?;
        self.finish_switch(store, &id)?;
        Ok(Some(AgyAccount::from(&data)))
    }

    /// 钥匙串里还是开始时那份(或没登录)时返回 `Ok(None)`;换成认得出的登录(或观察到登出后
    /// 重新登录同一账号,或开始时就有没收录过的登录)就收录、同步回退文件与 Desktop scope 并返回它。
    /// ACP 流程则等待 `agy acp --login` 完成退出后再校验钥匙串、收录并同步 Desktop scope。
    pub async fn poll_login(&self, flow_id: &str) -> Result<Option<AgyAccount>, AppError> {
        let _transition = self.login_transition.lock().await;
        enum PollAction {
            Keychain {
                baseline: Option<String>,
                saw_logged_out: bool,
                exit_status_file: Option<PathBuf>,
            },
            AcpPending,
            AcpClosed(Option<RestoreLogin>),
            AcpDone(acp_login::AcpLoginExit, Option<RestoreLogin>),
            Expired(Option<RestoreLogin>),
        }

        let action = {
            let mut pending = self.pending.lock().await;
            let Some(entry) = pending.get_mut(flow_id) else {
                return Err(login_ended());
            };
            if Instant::now() >= entry.deadline {
                let expired = pending.remove(flow_id);
                if let Some(entry) = expired {
                    entry.cancel_and_wait().await;
                    PollAction::Expired(entry.restore)
                } else {
                    PollAction::Expired(None)
                }
            } else {
                match &mut entry.kind {
                    PendingLoginKind::Keychain {
                        baseline,
                        saw_logged_out,
                        exit_status,
                    } => PollAction::Keychain {
                        baseline: baseline.clone(),
                        saw_logged_out: *saw_logged_out,
                        exit_status_file: exit_status.as_ref().map(|file| file.0.clone()),
                    },
                    PendingLoginKind::Acp(acp) => match acp.done.try_recv() {
                        Err(tokio::sync::oneshot::error::TryRecvError::Empty) => {
                            PollAction::AcpPending
                        }
                        Err(tokio::sync::oneshot::error::TryRecvError::Closed) => {
                            let removed = pending.remove(flow_id);
                            PollAction::AcpClosed(removed.and_then(|entry| entry.restore))
                        }
                        Ok(exit) => {
                            let removed = pending.remove(flow_id);
                            PollAction::AcpDone(exit, removed.and_then(|entry| entry.restore))
                        }
                    },
                }
            }
        };

        match action {
            PollAction::AcpPending => Ok(None),
            PollAction::Expired(restore) => {
                self.restore_if_empty(restore).await;
                Err(login_ended())
            }
            PollAction::AcpClosed(restore) => {
                self.restore_if_empty(restore).await;
                Err(AppError::localized(
                    "agy.account.acp_interrupted",
                    "Antigravity 登录被中断,请重试",
                    "Antigravity sign-in was interrupted. Please try again.",
                ))
            }
            PollAction::AcpDone(exit, restore) => {
                if !exit.success {
                    self.restore_if_empty(restore).await;
                    return Err(AppError::Message(exit.message));
                }
                let result = {
                    let mut store = self.store.lock().await;
                    match self.read_live(&store, true).await {
                        Ok(live) if matches!(live, LiveLogin::Known { .. }) => {
                            match self.finalize_live_login(&mut store, live).await? {
                                Some(account) => Ok(Some(account)),
                                None => Err(acp_keyring_missing()),
                            }
                        }
                        Ok(_) => Err(acp_keyring_missing()),
                        Err(error) => Err(error),
                    }
                };
                if result.is_err() {
                    self.restore_if_empty(restore).await;
                }
                result
            }
            PollAction::Keychain {
                baseline,
                saw_logged_out,
                exit_status_file,
            } => {
                if let Some(account) = self
                    .poll_live_login(flow_id, baseline, saw_logged_out)
                    .await?
                {
                    return Ok(Some(account));
                }
                // 先看钥匙串再看退出码:agy 登完马上退出时,上面已经收录,不会误报。
                if let Some(error) = exit_status_file.as_deref().and_then(read_exit_status_error) {
                    let ended = self.pending.lock().await.remove(flow_id);
                    // 和取消一样:钥匙串还空着就写回开始时暂存的原登录
                    self.restore_if_empty(ended.and_then(|entry| entry.restore))
                        .await;
                    return Err(error);
                }
                Ok(None)
            }
        }
    }

    /// 看钥匙串里有没有这次要的新登录;有就收录、结束这次登录并返回它。
    async fn poll_live_login(
        &self,
        flow_id: &str,
        baseline: Option<String>,
        saw_logged_out: bool,
    ) -> Result<Option<AgyAccount>, AppError> {
        let result = {
            let mut store = self.store.lock().await;
            let live = match self.read_live(&store, false).await {
                Ok(live) => live,
                Err(error) => {
                    log::debug!("[AgyAccount] 等待登录时读取钥匙串失败: {error}");
                    return Ok(None);
                }
            };
            if matches!(live, LiveLogin::None) {
                drop(store);
                let mut pending = self.pending.lock().await;
                if let Some(entry) = pending.get_mut(flow_id) {
                    if let PendingLoginKind::Keychain {
                        saw_logged_out: logged_out,
                        ..
                    } = &mut entry.kind
                    {
                        *logged_out = true;
                    }
                }
                return Ok(None);
            }
            if !matches!(live, LiveLogin::Known { .. })
                || (!saw_logged_out && live.fingerprint() == baseline)
            {
                return Ok(None);
            }
            self.finalize_live_login(&mut store, live).await?
        };
        self.pending.lock().await.remove(flow_id);
        Ok(result)
    }

    pub async fn cancel_login(&self, flow_id: &str) -> bool {
        let _transition = self.login_transition.lock().await;
        let removed = self.pending.lock().await.remove(flow_id);
        let Some(entry) = removed else {
            return false;
        };
        entry.cancel_and_wait().await;
        self.restore_if_empty(entry.restore).await;
        true
    }

    /// 退出 CC Switch 前调用:「添加账号」还没登完时钥匙串是被临时清空的,写回原登录的记录只在
    /// 内存里,这里按取消处理(钥匙串仍为空才写回),免得退出后 agy 和桌面版变成未登录。
    pub async fn abandon_pending_logins(&self) {
        let _transition = self.login_transition.lock().await;
        let entries: Vec<PendingLogin> = self
            .pending
            .lock()
            .await
            .drain()
            .map(|(_, entry)| entry)
            .collect();
        for entry in entries {
            entry.cancel_and_wait().await;
            self.restore_if_empty(entry.restore).await;
        }
    }

    async fn restore_if_empty(&self, restore: Option<RestoreLogin>) {
        let Some(restore) = restore else {
            return;
        };
        let store = self.store.lock().await;
        let login = Arc::clone(&self.login);
        match run_blocking(move || login.read()).await {
            Ok(None) => {
                let login = Arc::clone(&self.login);
                let raw = restore.raw;
                if let Err(error) = run_blocking(move || login.write(&raw)).await {
                    log::warn!("[AgyAccount] 恢复取消前的 Antigravity 登录失败: {error}");
                    return;
                }
                remember(&store, Some(restore.account_id));
            }
            Ok(Some(_)) => {}
            Err(error) => {
                log::warn!("[AgyAccount] 恢复前检查 Antigravity 钥匙串失败: {error}");
            }
        }
    }

    // ---------- 状态与切换 ----------

    /// 列出账号,并顺手把钥匙串里的最新登录收回来(agy 续期后的 access token、还没收录的号)。
    /// 查看账号。只刷新已收录的号:钥匙串里没收录过的登录不自动收进账号表(与其他应用
    /// 默认不读取一致),只报出它的名字,由用户点「收录当前账号」显式收进来。
    pub async fn status(&self) -> Result<AgyAccountStatus, AppError> {
        let mut store = self.store.lock().await;
        let mut current = None;
        let mut uncollected = None;
        if keychain::supported() {
            match self.read_live(&store, false).await {
                Ok(live) => {
                    uncollected = uncollected_label(&store, &live);
                    let (id, changed) = absorb(&mut store, live, false, false);
                    current = id;
                    if changed {
                        self.persist(&store)?;
                    }
                }
                Err(error) => log::warn!("[AgyAccount] 读取 agy 当前登录失败: {error}"),
            }
            remember(&store, Some(current.clone()));
        }
        Ok(AgyAccountStatus {
            accounts: sorted_accounts(&store),
            current_account_id: current,
            supported: keychain::supported(),
            uncollected_login: uncollected,
        })
    }

    /// 收录钥匙串里当前的登录(已收录的号就更新副本)。状态读取不自动收录没见过的号,
    /// 在 agy 或桌面端登录后由用户在这里显式收录;被删过的号也收回来(显式收录即用户要求)。
    pub async fn import_current(&self) -> Result<AgyAccount, AppError> {
        if !keychain::supported() {
            return Err(keychain::unsupported_error());
        }
        let mut store = self.store.lock().await;
        let live = self.read_live(&store, false).await?;
        match &live {
            LiveLogin::None => return Err(not_logged_in()),
            LiveLogin::Unrecognized(raw) => {
                self.stash_unrecognized(raw)?;
                return Err(unrecognized_format());
            }
            LiveLogin::Known { .. } => {}
        }
        let (id, changed) = absorb(&mut store, live, true, true);
        if changed {
            self.persist(&store)?;
        }
        let id = id.ok_or_else(not_logged_in)?;
        self.forget_stashed(&id);
        remember(&store, Some(Some(id.clone())));
        let data = store
            .accounts
            .get(&id)
            .cloned()
            .ok_or_else(|| account_not_found(&id))?;
        Ok(AgyAccount::from(&data))
    }

    /// 把 agy 的全局登录换成这个账号。已经是它且没有未完成的切换时什么都不写。
    ///
    /// 切成功后丢掉进行中的「添加账号」:钥匙串已经换成切过去的号,轮询会把它误当成新登录。
    /// 开始加号时的原登录已收回(已收录的更新了副本,没收录的写进了 stash),钥匙串也不再是
    /// 空的,丢掉不会弄丢登录。ACP 必须在写入前停止;切换失败时保留 pending 的恢复记录,
    /// 取消或超时仍能写回原登录。
    pub async fn switch_to(&self, account_id: &str) -> Result<(), AppError> {
        let _transition = self.login_transition.lock().await;
        self.switch_to_inner(account_id).await?;
        self.pending.lock().await.clear();
        Ok(())
    }

    async fn switch_to_inner(&self, account_id: &str) -> Result<(), AppError> {
        if !keychain::supported() {
            return Err(keychain::unsupported_error());
        }
        let mut store = self.store.lock().await;
        let target = store
            .accounts
            .get(account_id)
            .cloned()
            .ok_or_else(|| account_not_found(account_id))?;
        if target.requires_reauth {
            return Err(AppError::localized(
                "agy.account.requires_reauth",
                "这个账号的登录已失效,请重新添加",
                "This account's sign-in has expired. Add it again.",
            ));
        }

        // 先校验目标,再等旧 ACP 完全退出,避免它在写入/核验/同步期间覆盖目标凭据。
        // 失败时仍保留终端登录的 restore;不能提前 drain 丢掉恢复原登录的机会。
        for entry in self.pending.lock().await.values() {
            entry.cancel_and_wait().await;
        }

        // 切走前先收回钥匙串里那份:已收录的号更新副本,没收录的(含用户删过的)只暂存,
        // 不收进账号表,也不会弄丢
        let (current, changed) = match self.read_live_with_raw(&store, true).await? {
            (Some(raw), live) => self.refresh_or_stash(&mut store, live, &raw)?,
            (None, _) => (None, false),
        };
        if changed {
            self.persist(&store)?;
        }
        let already_current = current.as_deref() == Some(account_id);
        if already_current && !store.switch_incomplete {
            remember(&store, Some(current));
            return Ok(());
        }

        if already_current {
            // read_live/absorb 已拿到当前凭据,重试时不能拿切换前的副本覆盖它。
            let credential = store.accounts[account_id].credential.clone();
            let login = Arc::clone(&self.login);
            run_blocking(move || login.sync_fallback(&credential)).await?;
            return self.finish_switch(&mut store, account_id);
        }

        store.switch_incomplete = true;
        self.persist(&store)?;
        let credential = target.credential;
        let expected = refresh_token_of(&credential).map(str::to_string);
        let login = Arc::clone(&self.login);
        let credential_for_write = credential.clone();
        run_blocking(move || login.write_credential(&credential_for_write)).await?;

        // 核验失败时只重读,避免再次覆盖 agy 可能已经更新过的登录。
        for _ in 0..2 {
            if let Ok(LiveLogin::Known { credential, .. }) = self.read_live(&store, false).await {
                let written = refresh_token_of(&credential);
                if written.is_some() && written == expected.as_deref() {
                    let login = Arc::clone(&self.login);
                    run_blocking(move || login.sync_fallback(&credential)).await?;
                    self.finish_switch(&mut store, account_id)?;
                    log::info!("[AgyAccount] 已切换 Antigravity 登录");
                    return Ok(());
                }
            }
        }
        Err(AppError::localized(
            "agy.account.write_verify_failed",
            "已写入钥匙串,但无法确认 agy 当前登录的账号。请先在授权中心检查当前登录,再重试。",
            "The keychain write completed, but agy's current account could not be verified. Check the current sign-in in Auth Center before retrying.",
        ))
    }

    /// 只删 CC Switch 里的副本。删的是 agy 正登着的号时记下来,免得查看状态时又被收回来。
    pub async fn remove(&self, account_id: &str) -> Result<(), AppError> {
        let mut store = self.store.lock().await;
        let Some(removed) = store.accounts.remove(account_id) else {
            return Err(account_not_found(account_id));
        };
        if !store.dismissed.iter().any(|id| id == account_id) {
            store.dismissed.push(account_id.to_string());
        }
        if let Some(email) = removed.email.filter(|email| !email.is_empty()) {
            store.dismissed_emails.insert(account_id.to_string(), email);
        }
        self.persist(&store)
    }

    pub async fn remove_all(&self) -> Result<Vec<String>, AppError> {
        let mut store = self.store.lock().await;
        let removed: Vec<String> = store.accounts.keys().cloned().collect();
        for (id, account) in std::mem::take(&mut store.accounts) {
            if !store.dismissed.contains(&id) {
                store.dismissed.push(id.clone());
            }
            if let Some(email) = account.email.filter(|email| !email.is_empty()) {
                store.dismissed_emails.insert(id, email);
            }
        }
        self.persist(&store)?;
        Ok(removed)
    }

    pub async fn list(&self) -> Vec<AgyAccount> {
        sorted_accounts(&*self.store.lock().await)
    }

    // ---------- 额度 ----------

    /// agy 现在登着哪个已收录的号。只刷新已收录的号,不自动收录没见过的登录(不认识的
    /// 号不会自己冒出来)。没登录、读不到、格式不认识、没收录、或用户在 CC Switch 里
    /// 删过这个号时为 `None`。
    pub async fn current_account_id(&self) -> Option<String> {
        if !keychain::supported() {
            return None;
        }
        let mut store = self.store.lock().await;
        let live = match self.read_live(&store, false).await {
            Ok(live) => live,
            Err(error) => {
                log::warn!("[AgyAccount] 读取 agy 当前登录失败: {error}");
                return None;
            }
        };
        let (id, changed) = absorb(&mut store, live, false, false);
        if changed {
            if let Err(error) = self.persist(&store) {
                log::warn!("[AgyAccount] 保存账号文件失败: {error}");
            }
        }
        remember(&store, Some(id.clone()));
        id
    }

    /// 记下 agy 登着这个号时查到的额度。
    pub async fn record_quota(&self, account_id: &str, quota: &SubscriptionQuota) {
        let mut store = self.store.lock().await;
        let Some(account) = store.accounts.get_mut(account_id) else {
            return;
        };
        account.last_quota = Some(quota.clone());
        if let Err(error) = self.persist(&store) {
            log::warn!("[AgyAccount] 保存账号文件失败: {error}");
        }
    }

    /// 这个号最后一次查到的额度(可能是很久以前的,看 `queried_at`)。
    pub async fn last_quota(&self, account_id: &str) -> Option<SubscriptionQuota> {
        self.store
            .lock()
            .await
            .accounts
            .get(account_id)?
            .last_quota
            .clone()
    }

    // ---------- 内部 ----------

    /// 读钥匙串里 agy 当前的登录并认出是谁(只看本地数据,见 [`identify`])。
    async fn read_live(
        &self,
        store: &StoreFile,
        allow_unlock: bool,
    ) -> Result<LiveLogin, AppError> {
        self.read_live_with_raw(store, allow_unlock)
            .await
            .map(|(_, live)| live)
    }

    async fn read_live_with_raw(
        &self,
        store: &StoreFile,
        allow_unlock: bool,
    ) -> Result<(Option<String>, LiveLogin), AppError> {
        let login = Arc::clone(&self.login);
        let raw = run_blocking(move || {
            if allow_unlock {
                login.read_for_switch()
            } else {
                login.read()
            }
        })
        .await?;
        let Some(raw) = raw else {
            return Ok((None, LiveLogin::None));
        };
        let decoded = keychain::decode(&raw).ok();
        // agy 1.5 `/logout` 后条目里只剩元信息(writer_id、auth_method),按未登录处理:
        // 不暂存进 stash,「添加账号」也不把它当原登录暂存、写回。
        if decoded.as_ref().is_some_and(is_logged_out_metadata) {
            return Ok((None, LiveLogin::None));
        }
        let Some(credential) = decoded.filter(|credential| refresh_token_of(credential).is_some())
        else {
            return Ok((Some(raw.clone()), LiveLogin::Unrecognized(raw)));
        };
        let live = match identify(store, &credential) {
            Some(claims) => LiveLogin::Known { credential, claims },
            None => LiveLogin::Unrecognized(raw.clone()),
        };
        Ok((Some(raw), live))
    }

    fn stash_unrecognized(&self, raw: &str) -> Result<(), AppError> {
        stash::put(
            &self.data_dir.join(STASH_FILENAME),
            stash::UNRECOGNIZED_KEY,
            raw,
        )
    }

    /// 钥匙串里的登录要被覆盖(切号、终端「添加账号」)前收回它:已收录的号更新副本;没收录的
    /// (没见过的、用户删过的、认不出格式的)原文写进暂存,不收进账号表。返回同 [`absorb`]。
    /// 暂存写不进去(文件坏了)时报错,调用方不能接着覆盖钥匙串。
    fn refresh_or_stash(
        &self,
        store: &mut StoreFile,
        live: LiveLogin,
        raw: &str,
    ) -> Result<(Option<String>, bool), AppError> {
        match &live {
            LiveLogin::Known { claims, .. } => {
                let key = claims.sub.as_deref().unwrap_or(stash::UNRECOGNIZED_KEY);
                if !store.accounts.contains_key(key) {
                    stash::put(&self.data_dir.join(STASH_FILENAME), key, raw)?;
                }
            }
            LiveLogin::Unrecognized(raw) => self.stash_unrecognized(raw)?,
            LiveLogin::None => {}
        }
        // 只刷新已收录的号;删过的号顺手补记邮箱(见 absorb)
        Ok(absorb(store, live, false, false))
    }

    /// 这个号正式收录了:暂存里它的那份登录用不上了。暂存读不出时只记日志,不挡收录。
    fn forget_stashed(&self, account_id: &str) {
        if let Err(error) = stash::forget(&self.data_dir.join(STASH_FILENAME), account_id) {
            log::warn!("[AgyAccount] 清理已收录账号的登录暂存失败: {error}");
        }
    }

    fn persist(&self, store: &StoreFile) -> Result<(), AppError> {
        let snapshot = StoreFile {
            version: 1,
            accounts: store.accounts.clone(),
            dismissed: store.dismissed.clone(),
            dismissed_emails: store.dismissed_emails.clone(),
            switch_incomplete: store.switch_incomplete,
        };
        let content = serde_json::to_vec_pretty(&snapshot)
            .map_err(|source| AppError::JsonSerialize { source })?;
        crate::config::atomic_write_private(&self.data_dir.join(STORE_FILENAME), &content)?;
        remember(store, None);
        Ok(())
    }

    fn finish_switch(&self, store: &mut StoreFile, account_id: &str) -> Result<(), AppError> {
        self.clear_desktop_credential_scope()?;
        store.switch_incomplete = false;
        if let Err(error) = self.persist(store) {
            store.switch_incomplete = true;
            return Err(error);
        }
        remember(store, Some(Some(account_id.to_string())));
        Ok(())
    }

    fn clear_desktop_credential_scope(&self) -> Result<(), AppError> {
        if let Some(dir) = &self.desktop_user_data_dir {
            keychain::clear_desktop_user_scope_in(dir)?;
        }
        Ok(())
    }
}

/// 把钥匙串里的登录并进账号表,返回它对应的账号 id 和表有没有变。
/// `import_unknown`:没收录的号也收进来,只在用户亲手要收这份登录时传 `true`(加号后轮询到的
/// 新登录、桌面端加号、手动收录);查看状态、切号只传 `false`,只刷新已收录的号,没收录的
/// 不会自己冒出来(切号时由 [`AgyAccountManager::refresh_or_stash`] 暂存)。
/// `import_dismissed`:被用户删过的号也收回来(同样只在用户亲手收录时)。
fn absorb(
    store: &mut StoreFile,
    live: LiveLogin,
    import_unknown: bool,
    import_dismissed: bool,
) -> (Option<String>, bool) {
    let LiveLogin::Known { credential, claims } = live else {
        return (None, false);
    };
    let sub = claims.sub.clone().unwrap_or_default();
    if let Some(existing) = store.accounts.get_mut(&sub) {
        let mut changed = false;
        if existing.credential != credential {
            existing.credential = credential;
            existing.requires_reauth = false;
            changed = true;
        }
        // 续期后的 id_token 不带名字,有新值才更新
        changed |= fill(&mut existing.email, claims.email);
        changed |= fill(&mut existing.name, claims.name);
        return (Some(sub), changed);
    }
    let dismissed = store.dismissed.contains(&sub);
    if dismissed && !import_dismissed {
        // 旧版删过的号只有 `dismissed` 里的 sub、没有邮箱:经 id_token 认出后顺手把邮箱
        // 补进 `dismissed_emails`,agy 换成只存邮箱的格式后也能靠 `match_stored` 认出来。
        let changed = claims
            .email
            .or_else(|| live_email(&credential))
            .filter(|email| !email.is_empty())
            .is_some_and(|email| {
                if store.dismissed_emails.get(&sub) == Some(&email) {
                    false
                } else {
                    store.dismissed_emails.insert(sub, email);
                    true
                }
            });
        return (None, changed);
    }
    if !import_unknown {
        // 没收录的号:查看状态不自动收录,只报名字让用户点「收录」
        return (None, false);
    }
    store.dismissed.retain(|id| *id != sub);
    store.dismissed_emails.remove(&sub);
    upsert(store, credential, &claims);
    (Some(sub), true)
}

/// 钥匙串里没收录过的登录的显示名(查看状态时带给界面,提示用户点「收录」)。
/// 已收录的号、没登录或认不出的返回 `None`。名字同 [`AgyAccount::label`]:邮箱 > 名字 >
/// `Google (<sub 前 6 位>)`。
fn uncollected_label(store: &StoreFile, live: &LiveLogin) -> Option<String> {
    let LiveLogin::Known { claims, .. } = live else {
        return None;
    };
    let sub = claims.sub.clone().unwrap_or_default();
    if store.accounts.contains_key(&sub) {
        return None;
    }
    let label = claims
        .email
        .clone()
        .or_else(|| claims.name.clone())
        .filter(|label| !label.is_empty())
        .unwrap_or_else(|| {
            let short: String = sub.chars().take(6).collect();
            format!("Google ({short})")
        });
    Some(label)
}

fn fill(slot: &mut Option<String>, value: Option<String>) -> bool {
    match value.filter(|v| !v.is_empty()) {
        Some(value) if slot.as_deref() != Some(value.as_str()) => {
            *slot = Some(value);
            true
        }
        _ => false,
    }
}

fn upsert(
    store: &mut StoreFile,
    credential: Value,
    claims: &identity::IdentityClaims,
) -> AgyAccount {
    let sub = claims.sub.clone().unwrap_or_default();
    store.dismissed.retain(|id| *id != sub);
    store.dismissed_emails.remove(&sub);
    let now = chrono::Utc::now().timestamp();
    let entry = store
        .accounts
        .entry(sub.clone())
        .or_insert_with(|| AccountData {
            sub: sub.clone(),
            email: None,
            name: None,
            credential: Value::Null,
            authenticated_at: now,
            requires_reauth: false,
            last_quota: None,
        });
    entry.credential = credential;
    entry.requires_reauth = false;
    entry.authenticated_at = now;
    fill(&mut entry.email, claims.email.clone());
    fill(&mut entry.name, claims.name.clone());
    AgyAccount::from(&*entry)
}

fn sorted_accounts(store: &StoreFile) -> Vec<AgyAccount> {
    let mut accounts: Vec<AgyAccount> = store.accounts.values().map(AgyAccount::from).collect();
    accounts.sort_by_key(|account| account.authenticated_at);
    accounts
}

pub(super) fn refresh_token_of(credential: &Value) -> Option<&str> {
    credential
        .pointer("/token/refresh_token")
        .and_then(Value::as_str)
        .filter(|token| !token.is_empty())
}

/// agy 1.5 `/logout` 后钥匙串可能留下不带令牌的元信息 JSON(如 writer_id / auth_method)。
/// 带 refresh token 或 access token 的都不算;`token` 是别的形状的仍按认不出的格式暂存。
fn is_logged_out_metadata(credential: &Value) -> bool {
    if !credential.is_object() {
        return false;
    }
    if refresh_token_of(credential).is_some()
        || credential
            .pointer("/token/access_token")
            .and_then(Value::as_str)
            .is_some_and(|token| !token.is_empty())
    {
        return false;
    }
    match credential.get("token") {
        None | Some(Value::Null) => true,
        Some(Value::Object(map)) => map.is_empty(),
        _ => false,
    }
}

/// 终端里的 agy 退出后写下的退出码:读到就说明终端已经结束、这次登录不会完成了。
fn read_exit_status_error(path: &Path) -> Option<AppError> {
    let raw = std::fs::read_to_string(path).ok()?;
    match raw.trim().parse::<i32>() {
        Ok(0) | Err(_) => Some(AppError::localized(
            "agy.account.login_not_completed",
            "终端里的 agy 已退出,但还没有完成登录",
            "agy in the terminal exited before sign-in completed.",
        )),
        Ok(code) => Some(AppError::localized(
            "agy.account.login_command_failed",
            format!("终端里的 agy 异常退出(退出码 {code}),请查看终端窗口里的提示后重试"),
            format!(
                "agy in the terminal exited with code {code}. Check the terminal window and try again."
            ),
        )),
    }
}

/// agy 1.5 起写进钥匙串的邮箱(替代了 id_token);没有 `id_token_email` 时兜底从 `id_token` 解出 `email`。
fn live_email(credential: &Value) -> Option<String> {
    credential
        .get("id_token_email")
        .and_then(Value::as_str)
        .map(str::trim)
        .filter(|email| !email.is_empty())
        .map(str::to_string)
        .or_else(|| {
            credential["id_token"]
                .as_str()
                .and_then(identity::identity)
                .and_then(|claims| claims.email)
                .map(|email| email.trim().to_string())
                .filter(|email| !email.is_empty())
        })
}

/// 这份登录对应哪个已收录(或已删但仍在钥匙串里)的号:同一个 refresh token 优先,
/// 其次邮箱相同(在 agy 里重新登录过同一个号,或刚在 CC Switch 里删掉的号)。
fn match_stored(store: &StoreFile, credential: &Value) -> Option<identity::IdentityClaims> {
    let refresh_token = refresh_token_of(credential)?;
    let email = live_email(credential);
    if let Some(account) = store
        .accounts
        .values()
        .find(|account| refresh_token_of(&account.credential) == Some(refresh_token))
        .or_else(|| {
            let email = email.as_deref()?;
            store.accounts.values().find(|account| {
                account
                    .email
                    .as_deref()
                    .is_some_and(|stored| stored.eq_ignore_ascii_case(email))
            })
        })
    {
        return Some(identity::IdentityClaims {
            sub: Some(account.sub.clone()),
            email: email.or_else(|| account.email.clone()),
            name: None,
        });
    }
    let email = email?;
    let (sub, stored_email) = store
        .dismissed_emails
        .iter()
        .find(|(_, stored)| stored.eq_ignore_ascii_case(&email))?;
    Some(identity::IdentityClaims {
        sub: Some(sub.clone()),
        email: Some(stored_email.clone()),
        name: None,
    })
}

/// 钥匙串里这份登录是谁:新凭据自带 `id_token.sub` 且仓库已有(或已删)对应 `sub` 键时优先精确匹配,
/// 消除 `sub` 与 `email:` 混用产生的重复账号;否则再按已收录(或已删)的 refresh token / 邮箱对回,
/// 再没有就用 `id_token` 或 `id_token_email` 当 id。都没有的认不出。
fn identify(store: &StoreFile, credential: &Value) -> Option<identity::IdentityClaims> {
    let token_claims = credential["id_token"].as_str().and_then(identity::identity);
    if let Some(claims) = token_claims.as_ref() {
        if let Some(sub) = claims.sub.as_deref() {
            if store.accounts.contains_key(sub) || store.dismissed.iter().any(|id| id == sub) {
                return Some(claims.clone());
            }
        }
    }
    match (match_stored(store, credential), token_claims) {
        (Some(stored), Some(mut claims)) => {
            claims.sub = stored.sub;
            claims.email = claims.email.or(stored.email);
            Some(claims)
        }
        (Some(stored), None) => Some(stored),
        (None, Some(claims)) => Some(claims),
        (None, None) => live_email(credential).map(|email| identity::IdentityClaims {
            sub: Some(identity::email_account_id(&email)),
            email: Some(email),
            name: None,
        }),
    }
}

/// 钥匙串里这份登录是不是已收录的号(用户删过的不算:dismissed 只防 status 的静默复活,
/// 点「添加账号」是显式要收录这份登录,被删过的也收回)。已收录的号才等新的登录。
fn is_managed_login(store: &StoreFile, credential: &Value) -> bool {
    let Some(claims) = identify(store, credential) else {
        return false;
    };
    let Some(sub) = claims.sub.as_deref() else {
        return false;
    };
    store.accounts.contains_key(sub)
}

fn not_logged_in() -> AppError {
    AppError::localized(
        "agy.account.not_logged_in",
        "Antigravity 当前没有登录",
        "Antigravity is not signed in.",
    )
}

fn unrecognized_format() -> AppError {
    AppError::localized(
        "agy.account.unrecognized",
        "Antigravity 的登录格式认不出,已原样暂存,没有改动它",
        "Antigravity's sign-in is in a format CC Switch does not recognize. It was backed up as-is and left untouched.",
    )
}

fn login_ended() -> AppError {
    AppError::localized(
        "agy.account.login_expired",
        "这次登录已结束,请重新添加账号",
        "This sign-in has ended. Add the account again.",
    )
}

fn acp_keyring_missing() -> AppError {
    AppError::localized(
        "agy.account.acp_keyring_missing",
        "Antigravity 登录已完成,但未在系统钥匙串中检测到有效账号,请重试",
        "Antigravity sign-in completed, but no valid account was found in the system keychain. Please try again.",
    )
}

async fn run_blocking<T: Send + 'static>(
    job: impl FnOnce() -> Result<T, AppError> + Send + 'static,
) -> Result<T, AppError> {
    tokio::task::spawn_blocking(job)
        .await
        .map_err(|error| AppError::Message(format!("钥匙串操作中断: {error}")))?
}

fn account_not_found(account_id: &str) -> AppError {
    AppError::Message(format!("找不到这个 Antigravity 账号: {account_id}"))
}

#[cfg(test)]
mod tests;