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
feat(tray): list Antigravity provider cards instead of Auth Center accounts
Jason402d8ec39cfe
diff --git a/docs/agy-integration-zh.md b/docs/agy-integration-zh.mdindex 0842a20da..19e618d8c 100644--- a/docs/agy-integration-zh.md+++ b/docs/agy-integration-zh.md@@ -41,6 +41,7 @@ agy(CLI 和 Antigravity 桌面版)启动时读 `~/.gemini/config/config.json- 行的形状沿用旧版(`env.GEMINI_API_KEY`、`env.GOOGLE_GEMINI_BASE_URL`),网关独有的选项放在行的 `gateway` 对象(`wireProtocol`、`models`、`defaultModel`、`customHeaders`、`caCertPath`)。旧卡 `config.model.name` 里的显示名网关不认,不投影。- 当前卡指针存在设备级的 `current_provider_agy`;在用的卡删不掉。live 里已有网关时,首启导入成一张第三方卡(`category: custom`)。深链接 `enabled=true` 导入后直接切过去。- CLI 每次启动都读这个文件;**桌面版只在启动时读**,切换后要重启桌面版。已经运行的 agy 进程不会热切换。+- 托盘和 Gemini CLI 一样一行列供应商卡,点了直接切换;绑号的官方卡同时切 agy 登录,标题旁显示所绑账号,开了官方额度才查额度(只有 agy 现在登着的号会真的起 agy 查)。「打开终端」:diff --git a/src-tauri/src/services/agy_account/mod.rs b/src-tauri/src/services/agy_account/mod.rsindex 36d8bf126..c8cd90c35 100644--- a/src-tauri/src/services/agy_account/mod.rs+++ b/src-tauri/src/services/agy_account/mod.rs@@ -39,19 +39,6 @@ const STASH_FILENAME: &str = "agy-login-stash.json";/// 在 agy 里登录最多等这么久,过了就当放弃。const LOGIN_TIMEOUT: Duration = Duration::from_secs(10 * 60);-/// Antigravity 桌面端或 `agy` CLI 是否正在运行。-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]-pub struct AgyRunningState {- pub cli: bool,- pub desktop: bool,-}--impl AgyRunningState {- pub fn any(self) -> bool {- self.cli || self.desktop- }-}-/// 最近一次读到的账号表和 agy 当前登录,见 [`last_known_status`]。static LAST_KNOWN: std::sync::Mutex<Option<AgyAccountStatus>> = std::sync::Mutex::new(None);@@ -905,221 +892,5 @@ fn account_not_found(account_id: &str) -> AppError {AppError::Message(format!("找不到这个 Antigravity 账号: {account_id}"))}-/// Antigravity 桌面端或 `agy` CLI 有没有在跑。在跑的进程会继续用切换前的账号,续期时还可能把旧登录写回钥匙串。-pub fn agy_running_state() -> AgyRunningState {- #[cfg(target_os = "macos")]- {- let Ok(output) = std::process::Command::new("ps")- .args(["-axo", "comm="])- .stdin(std::process::Stdio::null())- .output()- else {- return AgyRunningState::default();- };- let text = String::from_utf8_lossy(&output.stdout);- classify_unix_process_lines(text.lines())- }- #[cfg(all(unix, not(target_os = "macos")))]- {- // Linux 的 `ps -axo comm=` 会把进程名截断到 15 字节(`language_server_linux_x64` 会变成 `language_server`),- // 改用 `args=` 保留完整可执行路径。- let Ok(output) = std::process::Command::new("ps")- .args(["-axo", "args="])- .stdin(std::process::Stdio::null())- .output()- else {- return AgyRunningState::default();- };- let text = String::from_utf8_lossy(&output.stdout);- classify_unix_process_lines(text.lines().map(unix_executable_token))- }- #[cfg(windows)]- {- use std::os::windows::process::CommandExt;- const CREATE_NO_WINDOW: u32 = 0x0800_0000;- let Ok(output) = std::process::Command::new("tasklist")- .args(["/FO", "CSV", "/NH"])- .creation_flags(CREATE_NO_WINDOW)- .stdin(std::process::Stdio::null())- .output()- else {- return AgyRunningState::default();- };- let text = String::from_utf8_lossy(&output.stdout);- classify_windows_processes(- parse_windows_tasklist_entries(&text),- windows_process_image_path,- )- }- #[cfg(not(any(unix, windows)))]- {- AgyRunningState::default()- }-}--pub fn agy_running() -> bool {- agy_running_state().any()-}--#[cfg_attr(not(any(unix, windows)), allow(dead_code))]-fn is_antigravity_ide_path(path: &str) -> bool {- let lower = path.to_ascii_lowercase();- lower.contains("antigravity-ide") || lower.contains("antigravity ide")-}--#[cfg_attr(not(any(unix, windows)), allow(dead_code))]-fn is_antigravity_desktop_language_server_path(path: &str) -> bool {- if is_antigravity_ide_path(path) {- return false;- }- path.to_ascii_lowercase()- .split(['\\', '/'])- .any(|segment| segment == "antigravity" || segment == "antigravity.app")-}--#[cfg(any(test, all(unix, not(target_os = "macos"))))]-fn unix_executable_token(line: &str) -> &str {- let trimmed = line.trim();- if let Some(app_idx) = trimmed.find(".app/") {- let after_app = &trimmed[app_idx + 5..];- let end_rel = after_app.find(" --").or_else(|| after_app.find(" -"));- return match end_rel {- Some(rel) => trimmed[..app_idx + 5 + rel].trim_end(),- None => trimmed,- };- }- trimmed.split_whitespace().next().unwrap_or(trimmed)-}--#[cfg_attr(not(unix), allow(dead_code))]-// 只接收可执行文件路径。macOS 的 ps comm= 已是完整路径,不能再按空格拆分。-fn classify_unix_process_lines<'a>(lines: impl Iterator<Item = &'a str>) -> AgyRunningState {- let mut state = AgyRunningState::default();- for raw in lines {- let trimmed = raw.trim();- if trimmed.is_empty() {- continue;- }- let exe = trimmed;- let path = std::path::Path::new(exe);- let file_name = path.file_name().and_then(|name| name.to_str());- if file_name == Some("agy") {- state.cli = true;- continue;- }- if is_antigravity_ide_path(exe) {- continue;- }- let in_desktop_bundle = path- .components()- .any(|part| part.as_os_str() == "Antigravity.app");- let is_antigravity_bin =- file_name.is_some_and(|name| name.eq_ignore_ascii_case("antigravity"));- let is_antigravity_ls = file_name- .is_some_and(|name| name == "language_server" || name.starts_with("language_server_"))- && is_antigravity_desktop_language_server_path(exe);- if in_desktop_bundle || is_antigravity_bin || is_antigravity_ls {- state.desktop = true;- }- }- state-}--#[cfg_attr(not(windows), allow(dead_code))]-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-enum WindowsProcessKind {- Cli,- Desktop,- LanguageServer,- Other,-}--#[cfg_attr(not(windows), allow(dead_code))]-fn classify_windows_image_name(image: &str) -> WindowsProcessKind {- if image.eq_ignore_ascii_case("agy.exe") {- WindowsProcessKind::Cli- } else if image.eq_ignore_ascii_case("Antigravity.exe") {- WindowsProcessKind::Desktop- } else {- let lower = image.to_ascii_lowercase();- if lower == "language_server.exe"- || (lower.starts_with("language_server_windows") && lower.ends_with(".exe"))- {- WindowsProcessKind::LanguageServer- } else {- WindowsProcessKind::Other- }- }-}--#[cfg_attr(not(windows), allow(dead_code))]-fn classify_windows_processes(- entries: impl IntoIterator<Item = (String, u32)>,- mut image_path: impl FnMut(u32) -> Option<String>,-) -> AgyRunningState {- let mut state = AgyRunningState::default();- let mut language_server_pids = Vec::new();- for (image, pid) in entries {- match classify_windows_image_name(&image) {- WindowsProcessKind::Cli => state.cli = true,- WindowsProcessKind::Desktop => {- // IDE 与 Desktop 都可能叫 Antigravity.exe,必须按实际路径区分。- // 无法读取路径时仍保留运行态保护,不能贸然覆盖登录。- state.desktop |= image_path(pid).is_none_or(|path| !is_antigravity_ide_path(&path));- }- WindowsProcessKind::LanguageServer => language_server_pids.push(pid),- WindowsProcessKind::Other => {}- }- }- if !state.desktop {- state.desktop = language_server_pids- .into_iter()- .filter_map(&mut image_path)- .any(|path| is_antigravity_desktop_language_server_path(&path));- }- state-}--#[cfg_attr(not(windows), allow(dead_code))]-fn parse_windows_tasklist_entries(output: &str) -> Vec<(String, u32)> {- output- .lines()- .filter_map(|line| {- let mut cols = line.split("\",\"").map(|col| col.trim_matches('"').trim());- let image = cols.next()?;- let pid = cols.next()?.parse::<u32>().ok()?;- if image.is_empty() {- None- } else {- Some((image.to_string(), pid))- }- })- .collect()-}--#[cfg(windows)]-fn windows_process_image_path(pid: u32) -> Option<String> {- use windows_sys::Win32::Foundation::CloseHandle;- use windows_sys::Win32::System::Threading::{- OpenProcess, QueryFullProcessImageNameW, PROCESS_QUERY_LIMITED_INFORMATION,- };-- // SAFETY: OpenProcess opens a handle with limited query rights; we always close it before returning.- let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };- if handle.is_null() {- return None;- }- let mut buf = vec![0u16; 1024];- let mut len = buf.len() as u32;- // SAFETY: buf is valid for len u16 elements and len receives the written character count.- let ok = unsafe { QueryFullProcessImageNameW(handle, 0, buf.as_mut_ptr(), &mut len) };- // SAFETY: handle is non-null and no longer needed.- unsafe { CloseHandle(handle) };- if ok == 0 || len == 0 {- return None;- }- Some(String::from_utf16_lossy(&buf[..len as usize]))-}-#[cfg(test)]mod tests;diff --git a/src-tauri/src/services/agy_account/tests.rs b/src-tauri/src/services/agy_account/tests.rsindex 32dc407f8..8ad107034 100644--- a/src-tauri/src/services/agy_account/tests.rs+++ b/src-tauri/src/services/agy_account/tests.rs@@ -1213,224 +1213,6 @@ mod running_guard_and_scope {reopened.switch_to("bob").await.unwrap();}- #[test]- fn macos_process_paths_with_spaces_are_not_split_into_arguments() {- for path in [- "/Users/Jane Doe/.local/bin/agy",- "/Volumes/Development Tools/agy",- ] {- assert!(- classify_unix_process_lines([path].into_iter()).cli,- "{path}"- );- }- for path in [- "/Users/Jane Doe/.gemini/antigravity/bin/language_server_macos_arm64",- "/Applications/Google Apps/Antigravity.app/Contents/Frameworks/Antigravity Helper.app/Contents/MacOS/Antigravity Helper",- ] {- assert!(classify_unix_process_lines([path].into_iter()).desktop, "{path}");- }- assert!(!classify_unix_process_lines(- [- "/Users/Jane Doe/Applications/Antigravity-IDE.app/Contents/MacOS/Antigravity",- "/Users/Jane Doe/.windsurf/bin/language_server_macos_arm64",- ]- .into_iter()- )- .any());- }-- #[test]- fn windows_process_paths_distinguish_ide_from_desktop() {- for path in [- r"C:\Program Files\Antigravity-IDE\Antigravity.exe",- r"C:\Users\Jane Doe\Antigravity IDE\Antigravity.exe",- r"C:\PROGRAM FILES\ANTIGRAVITY-IDE\antigravity.EXE",- ] {- let state =- classify_windows_processes([("Antigravity.exe".into(), 1)], |_| Some(path.into()));- assert!(!state.any(), "IDE must not block account switching: {path}");- }- let entries = [- ("Antigravity.exe".into(), 1),- ("Antigravity.exe".into(), 2),- ("agy.exe".into(), 3),- ("node.exe".into(), 4),- ];- let state = classify_windows_processes(entries, |pid| match pid {- 1 => Some(r"C:\Program Files\Antigravity-IDE\Antigravity.exe".into()),- 2 => Some(r"C:\Users\Jane Doe\Antigravity\Antigravity.exe".into()),- _ => panic!("only desktop candidates need a path lookup"),- });- assert_eq!(- state,- AgyRunningState {- cli: true,- desktop: true- }- );- assert!(- classify_windows_processes([("Antigravity.exe".into(), 1)], |_| None).desktop,- "an unreadable image path must not disable the running-process guard"- );- for (path, desktop) in [- (- r"C:\Program Files\Antigravity-IDE\language_server_windows_x64.exe",- false,- ),- (- r"C:\Program Files\Antigravity IDE\language_server_windows_x64.exe",- false,- ),- (- r"C:\Users\Jane Doe\Antigravity\language_server_windows_x64.exe",- true,- ),- (- r"C:\Program Files\Windsurf\language_server_windows_x64.exe",- false,- ),- ] {- let state =- classify_windows_processes([("language_server_windows_x64.exe".into(), 1)], |_| {- Some(path.into())- });- assert_eq!(state.desktop, desktop, "{path}");- }- }-- #[test]- fn process_classification_handles_windows_and_unix_processes() {- let tasklist = r#""System Idle Process","0","Services","0","8 K"-"agy.exe","1024","Console","1","45,000 K"-"Antigravity.exe","2048","Console","1","220,000 K"-"language_server_windows_x64.exe","4096","Console","1","180,000 K"-"language_server.exe","8192","Console","1","160,000 K"-"#;- let entries = parse_windows_tasklist_entries(tasklist);- assert_eq!(- entries,- vec![- ("System Idle Process".to_string(), 0),- ("agy.exe".to_string(), 1024),- ("Antigravity.exe".to_string(), 2048),- ("language_server_windows_x64.exe".to_string(), 4096),- ("language_server.exe".to_string(), 8192),- ]- );- assert_eq!(- classify_windows_image_name("agy.exe"),- WindowsProcessKind::Cli- );- assert_eq!(- classify_windows_image_name("antigravity.EXE"),- WindowsProcessKind::Desktop- );- assert_eq!(- classify_windows_image_name("language_server_windows_x64.exe"),- WindowsProcessKind::LanguageServer- );- assert_eq!(- classify_windows_image_name("language_server.exe"),- WindowsProcessKind::LanguageServer- );- assert_eq!(- classify_windows_image_name("node.exe"),- WindowsProcessKind::Other- );-- assert_eq!(- classify_unix_process_lines(- ["/Applications/Antigravity-IDE.app/Contents/MacOS/Antigravity"].into_iter()- ),- AgyRunningState {- cli: false,- desktop: false- }- );- assert_eq!(- classify_unix_process_lines(- ["/Applications/Antigravity.app/Contents/MacOS/Electron"].into_iter()- ),- AgyRunningState {- cli: false,- desktop: true- }- );- assert_eq!(- classify_unix_process_lines(- ["/Users/me/.windsurf/bin/language_server_macos_arm64"].into_iter()- ),- AgyRunningState {- cli: false,- desktop: false- }- );- assert_eq!(- classify_unix_process_lines(- [- "/usr/local/bin/agy",- "/Users/me/.gemini/antigravity/bin/language_server_macos_arm64"- ]- .into_iter()- ),- AgyRunningState {- cli: true,- desktop: true- }- );-- // Linux ps -axo args= lines with CLI flags and IDE paths.- assert_eq!(- classify_unix_process_lines(- [- "/usr/bin/agy --model gemini-3.1",- "/opt/antigravity/language_server_linux_x64 --port 1234"- ]- .into_iter()- .map(unix_executable_token)- ),- AgyRunningState {- cli: true,- desktop: true- }- );- assert_eq!(- classify_unix_process_lines(- [- "/home/u/.gemini/antigravity-ide/bin/language_server_linux_x64 --port 1",- "/Applications/Antigravity IDE.app/Contents/MacOS/Antigravity"- ]- .into_iter()- .map(unix_executable_token)- ),- AgyRunningState {- cli: false,- desktop: false- }- );-- // Windows Desktop executable path checks (legacy language_server_windows*.exe & new language_server.exe).- assert!(is_antigravity_desktop_language_server_path(- r"C:\Users\me\AppData\Local\Programs\Antigravity\resources\app\bin\language_server_windows_x64.exe"- ));- assert!(is_antigravity_desktop_language_server_path(- r"C:\Users\me\AppData\Local\Programs\Antigravity\resources\app\extensions\antigravity\bin\language_server.exe"- ));- assert!(!is_antigravity_desktop_language_server_path(- r"C:\Users\me\AppData\Local\Programs\Windsurf\language_server.exe"- ));- assert!(!is_antigravity_desktop_language_server_path(- r"C:\Users\me\AppData\Local\Programs\Windsurf\language_server_windows_x64.exe"- ));- assert!(!is_antigravity_desktop_language_server_path(- r"C:\Users\me\.gemini\antigravity-ide\bin\language_server_windows_x64.exe"- ));- assert!(!is_antigravity_desktop_language_server_path(- r"C:\Users\me\.gemini\antigravity-ide\bin\language_server.exe"- ));- }-#[test]fn saving_new_provider_binding_rolls_back_db_when_switch_fails() {use crate::app_config::AppType;diff --git a/src-tauri/src/services/provider/agy_direct.rs b/src-tauri/src/services/provider/agy_direct.rsindex be9db43dd..0dc401179 100644--- a/src-tauri/src/services/provider/agy_direct.rs+++ b/src-tauri/src/services/provider/agy_direct.rs@@ -42,7 +42,7 @@ pub(crate) fn is_official(provider: &Provider) -> bool {== Some("google-official")}-fn bound_account_id(provider: &Provider) -> Option<String> {+pub(crate) fn bound_account_id(provider: &Provider) -> Option<String> {if !is_official(provider) {return None;}diff --git a/src-tauri/src/tray.rs b/src-tauri/src/tray.rsindex 9018c8812..4a78dceef 100644--- a/src-tauri/src/tray.rs+++ b/src-tauri/src/tray.rs@@ -36,12 +36,13 @@ const COPILOT_UNIT_PREMIUM: &str = "requests";pub const TRAY_ID: &str = "cc-switch";/// 进托盘的应用,顺序和侧栏一致。累加式应用没有「当前供应商」,不进托盘。-pub const TRAY_APPS: [AppType; 5] = [+pub const TRAY_APPS: [AppType; 6] = [AppType::Claude,AppType::ClaudeDesktop,AppType::Codex,AppType::Gemini,AppType::GrokBuild,+ AppType::Agy,];/// 问题区最多几行,再多写「还有 N 个问题」。@@ -103,12 +104,6 @@ pub struct TrayTexts {pub feedback_stack_default: &'static str,/// 反馈行:应用项目pub feedback_profile: &'static str,- /// 反馈行:托盘里切了 Antigravity 账号、agy 正开着(开着的仍用原账号),`{app}` `{name}`- pub feedback_account_switched: &'static str,- /// 官方账号区(Antigravity)子菜单的标题- pub header_accounts: &'static str,- /// 官方账号区最下面:去授权中心- pub manage_accounts: &'static str,pub tier_five_hour: &'static str,pub tier_weekly: &'static str,pub tier_fable: &'static str,@@ -222,9 +217,6 @@ impl TrayTexts {feedback_stack_default:"{app}'s default provider is now {name}. Restart {app} to apply",feedback_profile: "Applied project \u{201c}{name}\u{201d} to {app}",- feedback_account_switched: "{app} signed in as {name}. Restart open {app} sessions to apply",- header_accounts: "Official accounts",- manage_accounts: "Manage accounts…",tier_five_hour: "5-hour",tier_weekly: "Weekly",tier_fable: "Fable",@@ -282,9 +274,6 @@ impl TrayTexts {feedback_switched: "{app}의 공급자가 {name}(으)로 전환되었습니다. 적용하려면 {app}을(를) 다시 시작하세요",feedback_stack_default: "{app}의 기본 공급자가 {name}(으)로 변경되었습니다. 적용하려면 {app}을(를) 다시 시작하세요",feedback_profile: "{app}에 {name} 프로젝트를 적용했습니다",- feedback_account_switched: "{app} 계정이 {name}(으)로 전환되었습니다. 열려 있는 {app}은(는) 다시 시작해야 적용됩니다",- header_accounts: "공식 계정",- manage_accounts: "계정 관리…",tier_five_hour: "5시간",tier_weekly: "주간",tier_fable: "Fable",@@ -344,9 +333,6 @@ impl TrayTexts {feedback_stack_default:"Standardanbieter von {app} ist jetzt {name}. {app} neu starten, um es zu übernehmen",feedback_profile: "Projekt \u{201e}{name}\u{201c} auf {app} angewendet",- feedback_account_switched: "{app} ist jetzt als {name} angemeldet. Laufende {app}-Sitzungen neu starten, um es zu übernehmen",- header_accounts: "Offizielle Konten",- manage_accounts: "Konten verwalten…",tier_five_hour: "5 Stunden",tier_weekly: "Woche",tier_fable: "Fable",@@ -404,9 +390,6 @@ impl TrayTexts {feedback_switched: "{app} переключён на {name}. Перезапустите {app}, чтобы применить",feedback_stack_default: "Провайдер по умолчанию для {app} теперь {name}. Перезапустите {app}, чтобы применить",feedback_profile: "Проект \u{00ab}{name}\u{00bb} применён к {app}",- feedback_account_switched: "{app} теперь использует аккаунт {name}. Перезапустите открытые сеансы {app}, чтобы применить",- header_accounts: "Официальные аккаунты",- manage_accounts: "Управление аккаунтами…",tier_five_hour: "5 часов",tier_weekly: "Неделя",tier_fable: "Fable",@@ -464,9 +447,6 @@ impl TrayTexts {feedback_switched: "{app}, {name} sağlayıcısına geçti. Uygulamak için {app} uygulamasını yeniden başlatın",feedback_stack_default: "{app} için varsayılan sağlayıcı artık {name}. Uygulamak için {app} uygulamasını yeniden başlatın",feedback_profile: "{name} projesi {app} uygulamasına uygulandı",- feedback_account_switched: "{app} artık {name} hesabını kullanıyor. Uygulamak için açık {app} oturumlarını yeniden başlatın",- header_accounts: "Resmî hesaplar",- manage_accounts: "Hesapları yönet…",tier_five_hour: "5 saatlik",tier_weekly: "Haftalık",tier_fable: "Fable",@@ -526,9 +506,6 @@ impl TrayTexts {"{app} を {name} に切り替えました。反映するには {app} を再起動してください",feedback_stack_default: "{app} のデフォルトのプロバイダーを {name} に変更しました。反映するには {app} を再起動してください",feedback_profile: "プロジェクト「{name}」を {app} に適用しました",- feedback_account_switched: "{app} のアカウントを {name} に切り替えました。開いている {app} は再起動すると反映されます",- header_accounts: "公式アカウント",- manage_accounts: "アカウントを管理…",tier_five_hour: "5時間",tier_weekly: "週間",tier_fable: "Fable",@@ -586,9 +563,6 @@ impl TrayTexts {feedback_switched: "{app} 已切換到 {name},重新啟動 {app} 後生效",feedback_stack_default: "{app} 的預設供應商改為 {name},重新啟動 {app} 後生效",feedback_profile: "已把專案「{name}」套用到 {app}",- feedback_account_switched: "{app} 已切換到帳號 {name},已開啟的 {app} 重新啟動後生效",- header_accounts: "官方帳號",- manage_accounts: "管理帳號…",tier_five_hour: "5 小時",tier_weekly: "每週",tier_fable: "Fable",@@ -646,9 +620,6 @@ impl TrayTexts {feedback_switched: "{app} 已切换到 {name},重启 {app} 后生效",feedback_stack_default: "{app} 的默认供应商改为 {name},重启 {app} 后生效",feedback_profile: "已把项目「{name}」用到 {app}",- feedback_account_switched: "{app} 已切换到账号 {name},已打开的 {app} 重启后生效",- header_accounts: "官方账号",- manage_accounts: "管理账号…",tier_five_hour: "5 小时",tier_weekly: "每周",tier_fable: "Fable",@@ -1184,6 +1155,8 @@ enum TrayUsageSource {ClaudeAccount(String),/// 授权中心的 xAI 账号(绑了账号的 Grok 官方卡、xAI OAuth 卡):按账号取,不读应用级订阅缓存。XaiAccount(String),+ /// 绑了授权中心账号的 Antigravity 官方卡:按账号取(同前端 `AgyAccountQuotaFooter`)。+ AgyAccount(String),/// 客户端自己登录的官方订阅:和供应商卡片读写同一份应用级订阅缓存。Subscription,Script,@@ -1191,6 +1164,14 @@ enum TrayUsageSource {/// Keep the tray's refresh and display paths on the same credentials and toggle.fn tray_usage_source(app_type: &AppType, provider: &Provider) -> Option<TrayUsageSource> {+ // Antigravity 绑号的官方卡和卡片一样:开了官方额度才查(`agy -p /usage` 要起 agy),+ // 不像别家绑号卡那样默认开着+ if *app_type == AppType::Agy {+ if let Some(account_id) = agy_bound_account_id(provider) {+ return provider_uses_official_subscription(provider)+ .then_some(TrayUsageSource::AgyAccount(account_id));+ }+ }// 绑了托管账号的卡(Codex、Claude 官方、Grok 官方、xAI OAuth)按账号取额度let bound = match app_type {// xAI OAuth 卡在哪个应用下都按 xAI 账号取(同卡片),聚合成员也一样(#9899)@@ -1278,6 +1259,12 @@ fn cached_usage_view(.with_xai_account(account_id, |quota| format_subscription_quota(texts, quota)).flatten();}+ if let Some(TrayUsageSource::AgyAccount(account_id)) = source {+ // 同上:这个号不是 agy 现在登着的号时,是切走前最后一次查到的+ return usage_cache+ .with_agy_account(account_id, |quota| format_subscription_quota(texts, quota))+ .flatten();+ }if source == Some(&TrayUsageSource::Subscription) {// 只读订阅缓存:卡片查到的和托盘悬停查到的都写在这里,两边不会各说各的。return usage_cache@@ -1496,6 +1483,8 @@ struct TrayAccountLabels {codex: ManagedAccountLabels,copilot: ManagedAccountLabels,xai: ManagedAccountLabels,+ /// 授权中心的 Antigravity 账号(内存里最后一次读到的账号表,不碰钥匙串)+ agy: HashMap<String, String>,}impl TrayAccountLabels {@@ -1511,10 +1500,26 @@ impl TrayAccountLabels {xai: ManagedAccountLabels::from_parts(crate::proxy::providers::xai_oauth_auth::labels_on_disk(data_dir),),+ agy: crate::services::agy_account::last_known_status()+ .map(|status| {+ status+ .accounts+ .iter()+ .map(|account| (account.id.clone(), account.label()))+ .collect()+ })+ .unwrap_or_default(),}}}+/// Antigravity 官方卡绑定的授权中心账号;不能切号的平台上没有(同前端 `canSwitchAgyAccount`)。+fn agy_bound_account_id(provider: &Provider) -> Option<String> {+ crate::services::provider::agy_direct::bound_account_id(provider)+ .map(|id| id.trim().to_string())+ .filter(|_| crate::services::agy_account::keychain::supported())+}+fn trimmed_managed_account_id(provider: &Provider, auth_provider: &str) -> Option<String> {provider.meta@@ -1572,6 +1577,12 @@ fn provider_account_label(return accounts.xai.resolve(Some(&id), false).map(str::to_string);}}+ if *app == AppType::Agy {+ // 只在绑了号时显示该号;没绑的跟随 agy 当前登录,不猜是哪个号+ if let Some(id) = agy_bound_account_id(provider) {+ return accounts.agy.get(&id).cloned();+ }+ }if is_copilot_proxy(app, provider) {let bound = trimmed_managed_account_id(provider, "github_copilot");return accounts@@ -1739,61 +1750,6 @@ fn collect_app_snapshot(Ok(snapshot)}-// ─── Antigravity 官方账号 ─────────────────────────────────────────────────────--/// Antigravity 在托盘里列的是授权中心的官方账号,不是供应商卡片(它的卡片只能「打开终端」):-/// 勾着的是 agy 现在登着的号,点一个号就把 agy 的全局登录切过去(和授权中心的切号同一个操作);-/// 每个号的额度用它自己的令牌查,不用先切号。没有收录账号时这一节不出现。-fn is_account_section(app: &AppType) -> bool {- *app == AppType::Agy-}--fn agy_quota_view(- usage_cache: &UsageCache,- texts: &TrayTexts,- account_id: &str,-) -> Option<QuotaView> {- usage_cache- .with_agy_account(account_id, |quota| format_subscription_quota(texts, quota))- .flatten()-}--/// 账号表 → 应用快照。`quota_of` 取某个号的额度(单测里不经缓存)。-fn agy_snapshot(- status: Option<crate::services::agy_account::AgyAccountStatus>,- quota_of: impl Fn(&str) -> Option<QuotaView>,-) -> Option<AppSnapshot> {- let status = status.filter(|status| status.supported && !status.accounts.is_empty())?;- let current_id = status- .current_account_id- .filter(|id| status.accounts.iter().any(|account| account.id == *id));- let providers = status- .accounts- .iter()- .map(|account| ProviderEntry {- id: account.id.clone(),- name: account.label(),- hint: None,- needs_routing: false,- official: true,- blocked_from_routing: false,- })- .collect();- let quota = current_id.as_deref().and_then("a_of);- Some(AppSnapshot {- app: AppType::Agy,- mode: TrayMode::Direct,- providers,- current_id,- queue: Vec::new(),- stack_members: Vec::new(),- quota,- service_down: false,- needs_attention: false,- profiles: None,- })-}-// ─── 问题区的状态 ─────────────────────────────────────────────────────────────/// 启动流程(接上路由、拉起 Desktop 映射服务)走完之前不报「路由服务没在跑」:那时它本来就还没起来。@@ -1926,14 +1882,12 @@ const FEEDBACK_TTL: std::time::Duration = std::time::Duration::from_secs(2 * 60)/// 存结构不存文字:语言改了照样按新语言写。#[derive(Debug, Clone, PartialEq)]enum TrayFeedback {- /// Codex / Gemini CLI / Grok Build 直连切换,或 Claude Desktop 切换。+ /// Codex / Gemini CLI / Grok Build / Antigravity 直连切换,或 Claude Desktop 切换。Switched { app: AppType, name: String },/// 聚合换默认:发布给客户端的模型列表跟着变。StackDefault { app: AppType, name: String },/// 应用项目:同时改了供应商、MCP、Skills、提示词。ProfileApplied { app: AppType, name: String },- /// 切了官方账号、客户端正开着:开着的还用原账号。- AccountSwitched { app: AppType, name: String },}struct FeedbackRecord {@@ -1957,7 +1911,10 @@ fn switch_feedback(app: &AppType, mode: TrayMode, name: String) -> Option<TrayFe})}TrayMode::Direct- if matches!(app, AppType::Codex | AppType::Gemini | AppType::GrokBuild) =>+ if matches!(+ app,+ AppType::Codex | AppType::Gemini | AppType::GrokBuild | AppType::Agy+ ) =>{Some(TrayFeedback::Switched {app: app.clone(),@@ -2017,7 +1974,6 @@ fn feedback_text(texts: &TrayTexts, feedback: &TrayFeedback) -> String {TrayFeedback::Switched { app, name } => (texts.feedback_switched, app, name),TrayFeedback::StackDefault { app, name } => (texts.feedback_stack_default, app, name),TrayFeedback::ProfileApplied { app, name } => (texts.feedback_profile, app, name),- TrayFeedback::AccountSwitched { app, name } => (texts.feedback_account_switched, app, name),};fill(template,@@ -2038,8 +1994,6 @@ struct MenuStatus {update_ready: Option<String>,/// 授权中心切号或代理令牌失效也会改变副标题,不能只比较路由状态。provider_hints: Vec<(AppType, String, Option<String>)>,- /// agy 现在登着的号:在授权中心或 agy 里换了号,勾要跟着挪。- agy_current: Option<String>,}// ─── 菜单模型(纯数据)────────────────────────────────────────────────────────@@ -2129,17 +2083,10 @@ fn problem_text(texts: &TrayTexts, problem: &TrayProblem) -> String {/// 托盘 / 面板里「重启并更新」的事件 id。const INSTALL_UPDATE_ID: &str = "app_update:install";-/// 打开授权中心(官方账号在那里添加、删除)。-const AUTH_PAGE_NAV_ID: &str = "nav:page:auth";-fn problem_id(problem: &TrayProblem) -> String {match problem {TrayProblem::ServiceDown { .. } => "nav:settings:routing".to_string(),TrayProblem::AttachFailed { app, .. } => format!("nav:app:{}:attach", app.as_str()),- // 账号区切号失败:原因(登录失效、钥匙串写不进去)要到授权中心处理- TrayProblem::SwitchFailed { app, .. } if is_account_section(app) => {- AUTH_PAGE_NAV_ID.to_string()- }TrayProblem::SwitchFailed { app, .. } => format!("nav:app:{}:failed", app.as_str()),}}@@ -2301,9 +2248,6 @@ fn app_children(let mut children = Vec::new();let header = match snapshot.mode {- TrayMode::Direct if is_account_section(&snapshot.app) => {- Some(texts.header_accounts.to_string())- }TrayMode::Direct => Some(texts.header_direct.to_string()),TrayMode::Route => Some(texts.header_route.to_string()),TrayMode::Failover => Some(texts.header_failover.to_string()),@@ -2353,15 +2297,10 @@ fn app_children(}children.push(TrayEntry::Separator);- if is_account_section(&snapshot.app) {- // 账号在授权中心添加、删除- children.push(TrayEntry::item(AUTH_PAGE_NAV_ID, texts.manage_accounts));- } else {- children.push(TrayEntry::item(- format!("nav:app:{app}"),- fill(texts.open_app_page, &[("app", snapshot.app.display_name())]),- ));- }+ children.push(TrayEntry::item(+ format!("nav:app:{app}"),+ fill(texts.open_app_page, &[("app", snapshot.app.display_name())]),+ ));children}@@ -2485,12 +2424,6 @@ fn collect_snapshots(app_state, texts, &settings, app, running, &profiles, &accounts,)?);}- if visible_apps.is_visible(&AppType::Agy) {- let status = crate::services::agy_account::last_known_status();- snapshots.extend(agy_snapshot(status, |id| {- agy_quota_view(&app_state.usage_cache, texts, id)- }));- }let port = snapshots.iter()@@ -2527,10 +2460,6 @@ fn collect_status(})}).collect(),- agy_current: snapshots- .iter()- .find(|snapshot| is_account_section(&snapshot.app))- .and_then(|snapshot| snapshot.current_id.clone()),};Ok((snapshots, status))}@@ -2692,6 +2621,7 @@ fn cached_reset_credits(TrayUsageSource::Subscription => usage_cache.with_subscription(app_type, count).flatten(),TrayUsageSource::ClaudeAccount(_)| TrayUsageSource::XaiAccount(_)+ | TrayUsageSource::AgyAccount(_)| TrayUsageSource::Script => None,}}@@ -2743,17 +2673,6 @@ fn panel_rows(return None;}let provider = row_provider_id(&id, app).and_then(|provider_id| {- if is_account_section(&snapshot.app) {- let account = snapshot.providers.iter().find(|p| p.id == provider_id)?;- return Some(PanelProvider {- name: account.name.clone(),- hint: None,- icon: Some("google".to_string()),- icon_color: None,- quota: agy_quota_view(usage_cache, texts, provider_id)- .map(|view| panel_quota(texts, &view, now, None)),- });- }let provider = rows.get(provider_id)?;let source = tray_usage_source(&snapshot.app, provider);Some(PanelProvider {@@ -2809,13 +2728,7 @@ pub(crate) fn collect_panel_model(app_state: &AppState) -> Result<PanelModel, Aplet mut apps = Vec::with_capacity(snapshots.len());for snapshot in &snapshots {let app = snapshot.app.as_str();- let accounts = is_account_section(&snapshot.app);- // 账号区的行是授权中心的账号,不读供应商表- let providers = if accounts {- indexmap::IndexMap::new()- } else {- app_state.db.get_provider_rows(&snapshot.app)?.readable- };+ let providers = app_state.db.get_provider_rows(&snapshot.app)?.readable;let (header, rows) = panel_rows(&app_state.usage_cache, &texts, snapshot, &providers, now);let credits = snapshot.current_id@@ -2834,7 +2747,6 @@ pub(crate) fn collect_panel_model(app_state: &AppState) -> Result<PanelModel, Apname: snapshot.app.display_name(),current: snapshot.current().map(|p| p.name.clone()),mode: match snapshot.mode {- TrayMode::Direct if accounts => texts.header_accounts,TrayMode::Direct => texts.header_direct,TrayMode::Route | TrayMode::Failover => texts.mode_route,TrayMode::Stack => texts.mode_stack,@@ -3297,14 +3209,11 @@ pub struct TrayNavigation {pub intent: Option<String>,#[serde(skip_serializing_if = "Option::is_none")]pub provider_id: Option<String>,- /// 全局页面(`auth`:授权中心)- #[serde(skip_serializing_if = "Option::is_none")]- pub page: Option<String>,}impl TrayNavigation {fn is_empty(&self) -> bool {- self.app.is_none() && self.section.is_none() && self.page.is_none()+ self.app.is_none() && self.section.is_none()}}@@ -3312,7 +3221,7 @@ impl TrayNavigation {static PENDING_NAVIGATION: Mutex<Option<TrayNavigation>> = Mutex::new(None);/// 解析 `nav:…` 菜单 id:`nav:main`、`nav:settings:<分组>`、`nav:app:<应用>[:…]`、-/// `nav:add:<应用>`、`nav:needs:<应用>:<供应商 id>`、`nav:page:auth`。+/// `nav:add:<应用>`、`nav:needs:<应用>:<供应商 id>`。fn parse_nav_id(id: &str) -> Option<TrayNavigation> {let rest = id.strip_prefix("nav:")?;let mut parts = rest.splitn(3, ':');@@ -3331,10 +3240,6 @@ fn parse_nav_id(id: &str) -> Option<TrayNavigation> {section: Some(target?.to_string()),..Default::default()},- "page" if target == Some("auth") => TrayNavigation {- page: Some("auth".to_string()),- ..Default::default()- },"app" => TrayNavigation {app: Some(app(target?)?),..Default::default()@@ -3369,10 +3274,6 @@ fn navigate(app: &tauri::AppHandle, navigation: TrayNavigation) {// 打开过对应页面,这个应用的问题行就算看过了。clear_app_problems(&app_type);}- if navigation.page.as_deref() == Some("auth") {- // 账号区切号失败的问题行指向授权中心- clear_app_problems(&AppType::Agy);- }let pending = !navigation.is_empty();if pending {*PENDING_NAVIGATION.lock_recover() = Some(navigation);@@ -3541,10 +3442,6 @@ pub fn handle_provider_tray_event(app: &tauri::AppHandle, event_id: &str) -> boolog::warn!("未知应用的供应商托盘事件: {event_id}");return true;};- if is_account_section(&app_type) {- handle_agy_account_click(app, provider_id.to_string());- return true;- }log::info!("托盘切换 {} 到 {provider_id}", app_type.display_name());let app_handle = app.clone();let provider_id = provider_id.to_string();@@ -3581,59 +3478,6 @@ pub fn handle_provider_tray_event(app: &tauri::AppHandle, event_id: &str) -> bootrue}-/// 点了一个 Antigravity 账号:把 agy 的全局登录切过去(和授权中心切号同一个操作)。-/// agy 正开着时说一句:开着的 agy 还用原账号,续期时还可能把原账号写回去。-fn handle_agy_account_click(app: &tauri::AppHandle, account_id: String) {- log::info!("托盘切换 Antigravity 账号到 {account_id}");- let app_handle = app.clone();- tauri::async_runtime::spawn(async move {- let Some(state) = app_handle.try_state::<crate::commands::AgyAccountState>() else {- return;- };- let manager = std::sync::Arc::clone(&state.0);- let before = crate::services::agy_account::last_known_status();- let was_current = before- .as_ref()- .and_then(|status| status.current_account_id.as_deref())- == Some(account_id.as_str());- let name = before- .as_ref()- .and_then(|status| {- status- .accounts- .iter()- .find(|account| account.id == account_id)- })- .map(|account| account.label())- .unwrap_or_else(|| account_id.clone());- match manager.switch_to(&account_id).await {- Ok(()) => {- clear_app_problems(&AppType::Agy);- let running = !was_current- && tokio::task::spawn_blocking(crate::services::agy_account::agy_running)- .await- .unwrap_or(false);- if running {- record_feedback(- &app_handle,- TrayFeedback::AccountSwitched {- app: AppType::Agy,- name,- },- );- }- }- Err(e) => {- log::error!("托盘切换 Antigravity 账号失败: {e}");- record_switch_failure(&AppType::Agy, e.to_string());- }- }- // 打勾项点了会自己翻转勾选:成功、没动、失败都要按实际状态重建。- let app = app_handle.clone();- let _ = tauri::async_runtime::spawn_blocking(move || refresh_tray_menu(&app)).await;- });-}-enum ClickOutcome {/// 切过去了;`mode` 是点击时的模式,决定要不要出反馈行。Switched { mode: TrayMode, name: String },@@ -3677,7 +3521,13 @@ fn handle_provider_click(if mode == TrayMode::Direct && provider_needs_routing(app_type, &provider) {return Ok(ClickOutcome::NeedsRoute);}- crate::services::ProviderService::switch(state, app_type.clone(), provider_id)?;+ if *app_type == AppType::Agy {+ // 绑了号的官方卡先把 agy 的登录切过去(同主界面切换)+ let accounts = app.state::<crate::commands::AgyAccountState>();+ crate::services::provider::agy_direct::switch_with_login(state, &accounts.0, provider_id)?;+ } else {+ crate::services::ProviderService::switch(state, app_type.clone(), provider_id)?;+ }Ok(ClickOutcome::Switched {mode,name: provider.name,@@ -3815,9 +3665,8 @@ pub fn schedule_tray_refresh(app: &tauri::AppHandle) {////// 刷新面与 `usage_view` 的展示面严格对齐 —— 每次悬停最多发/// `TRAY_APPS.len()` 个用量查询;按供应商用量开关查询,Codex 托管账号-/// 未保存开关时与卡片一致默认启用。Antigravity 账号区另算:在用的号在允许-/// 自动查询时按 `AGY_TRAY_QUOTA_REUSE` 问 agy,其余的号(以及关掉「自动查询-/// 额度」时的在用号)只读最后一次查到的(`refresh_agy_accounts`)。+/// 未保存开关时与卡片一致默认启用。Antigravity 绑号的官方卡按 `AGY_TRAY_QUOTA_REUSE`+/// 问 agy(只有 agy 现在登着的号会真的查,别的号读最后一次查到的)。pub(crate) async fn refresh_all_usage_in_tray(app: &tauri::AppHandle) {use crate::commands::CopilotAuthState;use futures::future::join_all;@@ -3916,6 +3765,28 @@ pub(crate) async fn refresh_all_usage_in_tray(app: &tauri::AppHandle) {.await.map(|_| ())}+ TrayUsageSource::AgyAccount(account_id) => {+ // 只有 agy 现在登着的号会真的起 agy 查;别的号读切走前最后一次的+ let accounts = app.state::<crate::commands::AgyAccountState>();+ match crate::commands::agy_quota(+ &accounts.0,+ Some(&account_id),+ AGY_TRAY_QUOTA_REUSE,+ )+ .await+ {+ Ok(quota) => {+ crate::commands::remember_account_quota(+ &app_clone,+ state.inner(),+ account_id,+ "a,+ );+ Ok(())+ }+ Err(e) => Err(e),+ }+ }TrayUsageSource::Subscription => {crate::commands::get_subscription_quota(app_clone, state, app_str).await@@ -3939,163 +3810,12 @@ pub(crate) async fn refresh_all_usage_in_tray(app: &tauri::AppHandle) {}}- let agy = async {- if visible_apps.is_visible(&AppType::Agy) {- refresh_agy_accounts(app, official_manual_only).await;- }- };- futures::join!(join_all(usage_futures), agy);+ join_all(usage_futures).await;}/// 托盘替 agy 当前登录的号查额度时,这么久内查过就不再起 agy(`/usage` 要启动 agy,七八秒)。const AGY_TRAY_QUOTA_REUSE: std::time::Duration = std::time::Duration::from_secs(5 * 60);-/// 托盘刷新单个 Antigravity 账号额度时要走哪一路。-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-enum AgyTrayQuotaAction {- /// 只读本地保存的最后一次额度(不拉起 agy,不发请求)。- CachedOnly,- /// 当前登着的号且允许自动查询:问 agy 的 `/usage`(按 `AGY_TRAY_QUOTA_REUSE` 复用)。- Live,-}--/// 决定托盘刷新某个 Antigravity 账号时的动作:-/// `requires_reauth` 的账号返回 `None` 跳过;「自动查询额度」关着或不是当前登录的号一律只读已保存快照。-fn agy_tray_quota_action(- account: &crate::services::agy_account::AgyAccount,- current_account_id: Option<&str>,- official_manual_only: bool,-) -> Option<AgyTrayQuotaAction> {- if account.requires_reauth {- return None;- }- let is_current = current_account_id == Some(account.id.as_str());- Some(if !official_manual_only && is_current {- AgyTrayQuotaAction::Live- } else {- AgyTrayQuotaAction::CachedOnly- })-}--/// 本地保存的 `last_quota` 要不要补进进程内的托盘缓存:-/// 只回填成功快照;缓存为空、只有无时间戳的占位失败(如 `NotFound`),或保存的快照更新时-/// 才写入,避免覆盖刚手动刷出的结果 / 失败状态,也避免每次悬停都触发无意义的托盘刷新。-fn should_hydrate_agy_cached_quota(- usage_cache: &UsageCache,- account_id: &str,- saved: &crate::services::subscription::SubscriptionQuota,-) -> bool {- if !saved.success {- return false;- }- usage_cache- .with_agy_account(account_id, |existing| {- saved.queried_at > existing.queried_at- || (existing.queried_at.is_none() && !existing.success)- })- .unwrap_or(true)-}--/// 按账号表刷新托盘的 Antigravity 额度缓存:-/// `requires_reauth` 的账号跳过;非当前登录或关掉「自动查询额度」时只读 `read_saved` 补进-/// `usage_cache`;允许自动查询的当前登录账号调 `query_live`。每条写入后立刻调 `on_updated`,-/// 避免慢速 `/usage` 拖慢其他账号本地快照的展示。-async fn refresh_agy_account_quotas<RS, RSFut, QL, QLFut>(- usage_cache: &UsageCache,- status: crate::services::agy_account::AgyAccountStatus,- official_manual_only: bool,- read_saved: RS,- query_live: QL,- on_updated: impl Fn(),-) where- RS: Fn(String) -> RSFut,- RSFut: std::future::Future<Output = Option<crate::services::subscription::SubscriptionQuota>>,- QL: Fn(String) -> QLFut,- QLFut: std::future::Future<- Output = Result<crate::services::subscription::SubscriptionQuota, String>,- >,-{- use futures::future::join_all;-- let current_account_id = status.current_account_id.as_deref();- let read_saved = &read_saved;- let query_live = &query_live;- let on_updated = &on_updated;- let queries = status.accounts.into_iter().filter_map(|account| {- let action = agy_tray_quota_action(&account, current_account_id, official_manual_only)?;- let account_id = account.id;- Some(async move {- match action {- AgyTrayQuotaAction::CachedOnly => {- if let Some(quota) = read_saved(account_id.clone()).await {- if should_hydrate_agy_cached_quota(usage_cache, &account_id, "a) {- usage_cache.put_agy_account(account_id, quota);- on_updated();- }- }- }- AgyTrayQuotaAction::Live => match query_live(account_id.clone()).await {- Ok(quota) => {- usage_cache.put_agy_account(account_id, quota);- on_updated();- }- Err(e) => {- log::debug!("[Tray] 刷新 Antigravity 账号 {account_id} 额度失败: {e}")- }- },- }- })- });- join_all(queries).await;-}--/// 托盘的 Antigravity 账号区:先读一次钥匙串(agy 现在登着哪个号、有没有收进新号),-/// 再取每个号的额度:在用的号在允许自动查询时问 agy 的 `/usage`,别的号以及关掉-/// 「自动查询额度」时只读本地保存的最后一次结果(不起 agy、不发请求),需要重新登录的号跳过。-/// 没收录过账号时什么都不做,不碰钥匙串。-async fn refresh_agy_accounts(app: &tauri::AppHandle, official_manual_only: bool) {- if !crate::services::agy_account::keychain::supported()- || crate::services::agy_account::last_known_status()- .is_none_or(|status| status.accounts.is_empty())- {- return;- }- let Some(state) = app.try_state::<crate::commands::AgyAccountState>() else {- return;- };- let manager = std::sync::Arc::clone(&state.0);- let status = match manager.status().await {- Ok(status) => status,- Err(e) => {- log::debug!("[Tray] 读取 Antigravity 账号失败: {e}");- return;- }- };- // 在 agy 里或授权中心换过号:勾跟着挪(状态没变就不重建)- schedule_tray_status_check(app);-- let Some(app_state) = app.try_state::<AppState>() else {- return;- };- refresh_agy_account_quotas(- &app_state.usage_cache,- status,- official_manual_only,- |account_id| {- let manager = std::sync::Arc::clone(&manager);- async move { manager.last_quota(&account_id).await }- },- |account_id| {- let manager = std::sync::Arc::clone(&manager);- async move {- crate::commands::agy_quota(&manager, Some(&account_id), AGY_TRAY_QUOTA_REUSE).await- }- },- || schedule_tray_refresh(app),- )- .await;-}-/// 这一路额度查询打的是不是官方账号的接口。托管 Codex、Claude 账号、客户端订阅都是;/// 脚本路径里 GitHub Copilot 卡(查 Copilot 账号用量)和官方订阅模板(xAI OAuth 查/// SuperGrok 账号额度)也是,其余脚本是第三方余额 / 套餐查询。diff --git a/src-tauri/src/tray/tests.rs b/src-tauri/src/tray/tests.rsindex 621ee2fd1..61e75da07 100644--- a/src-tauri/src/tray/tests.rs+++ b/src-tauri/src/tray/tests.rs@@ -136,7 +136,8 @@ fn tray_lists_switch_apps_in_sidebar_order_without_additive_apps() {"Claude Desktop","Codex","Gemini CLI",- "Grok Build"+ "Grok Build",+ "Antigravity"]);for app in TRAY_APPS {@@ -2410,113 +2411,95 @@ fn problems_drop_attach_failures_once_the_app_routes_again() {assert!(collect_problems(None, &rerouted).is_empty());}-// ─── Antigravity 官方账号区 ───+// ─── Antigravity ───-fn agy_account(id: &str, email: Option<&str>) -> crate::services::agy_account::AgyAccount {- crate::services::agy_account::AgyAccount {- id: id.to_string(),- email: email.map(str::to_string),- name: None,- picture: None,- authenticated_at: 0,- requires_reauth: false,- }-}--fn agy_status(- accounts: Vec<crate::services::agy_account::AgyAccount>,- current: Option<&str>,-) -> crate::services::agy_account::AgyAccountStatus {- crate::services::agy_account::AgyAccountStatus {- accounts,- current_account_id: current.map(str::to_string),- supported: true,- }+fn agy_official_provider(account_id: Option<&str>, enabled: Option<bool>) -> Provider {+ serde_json::from_value(serde_json::json!({+ "id": "agy-official",+ "name": "Google Official",+ "settingsConfig": {"env": {}, "config": {}},+ "category": "official",+ "websiteUrl": "https://antigravity.google",+ "meta": {+ "authBinding": account_id.map(|id| serde_json::json!({+ "source": "managed_account",+ "authProvider": "agy_oauth",+ "accountId": id+ })),+ "usage_script": enabled.map(|enabled| serde_json::json!({+ "enabled": enabled,+ "language": "javascript",+ "code": "",+ "templateType": "official_subscription"+ }))+ }+ }))+ .unwrap()}#[test]-fn agy_section_appears_only_with_accounts_on_a_platform_that_can_switch() {- assert!(agy_snapshot(None, |_| None).is_none());- assert!(agy_snapshot(Some(agy_status(vec![], None)), |_| None).is_none());- let mut unsupported = agy_status(vec![agy_account("1", Some("[email protected]"))], None);- unsupported.supported = false;- assert!(agy_snapshot(Some(unsupported), |_| None).is_none());+fn agy_official_card_hint_shows_only_its_bound_account() {+ let accounts = TrayAccountLabels {+ agy: HashMap::from([("acct-1".to_string(), "[email protected]".to_string())]),+ ..Default::default()+ };+ assert_eq!(+ provider_hint(+ &AppType::Agy,+ &agy_official_provider(Some("acct-1"), None),+ &accounts+ )+ .as_deref(),+ Some("[email protected]")+ );+ // 没绑号的跟随 agy 当前登录,绑的号不在本机:都退回官网域名+ for provider in [+ agy_official_provider(None, None),+ agy_official_provider(Some("gone"), None),+ ] {+ assert_eq!(+ provider_hint(&AppType::Agy, &provider, &accounts).as_deref(),+ Some("antigravity.google")+ );+ }}#[test]-fn agy_section_lists_accounts_and_only_the_signed_in_one_feeds_the_title_quota() {- let status = agy_status(- vec![- agy_account("111111111", Some("[email protected]")),- agy_account("222222222", None),- ],- Some("222222222"),+fn agy_bound_card_quota_is_opt_in_and_reads_that_account() {+ // 和卡片一样默认不查:`agy -p /usage` 要起 agy+ assert_eq!(+ tray_usage_source(&AppType::Agy, &agy_official_provider(Some("acct-1"), None)),+ None+ );+ assert_eq!(+ tray_usage_source(+ &AppType::Agy,+ &agy_official_provider(Some("acct-1"), Some(false))+ ),+ None+ );+ assert_eq!(+ tray_usage_source(+ &AppType::Agy,+ &agy_official_provider(Some("acct-1"), Some(true))+ ),+ Some(TrayUsageSource::AgyAccount("acct-1".to_string()))+ );+ // 没绑号的官方卡读 agy 当前登录的应用级订阅缓存+ assert_eq!(+ tray_usage_source(&AppType::Agy, &agy_official_provider(None, Some(true))),+ Some(TrayUsageSource::Subscription));- let asked = std::cell::RefCell::new(Vec::new());- let snapshot = agy_snapshot(Some(status), |id| {- asked.borrow_mut().push(id.to_string());- Some(QuotaView::Failed(QuotaFailure::Other))- })- .expect("section");- assert_eq!(snapshot.app, AppType::Agy);- let names: Vec<&str> = snapshot.providers.iter().map(|p| p.name.as_str()).collect();- assert_eq!(names, ["[email protected]", "Google (222222)"]);- assert_eq!(snapshot.current_id.as_deref(), Some("222222222"));- assert_eq!(*asked.borrow(), ["222222222"]);-- // 钥匙串里是没收录的号:不勾任何一个,标题也不写额度- let stray = agy_snapshot(- Some(agy_status(- vec![agy_account("1", Some("[email protected]"))],- Some("9"),- )),- |_| panic!("no current account, no quota"),- )- .expect("section");- assert_eq!(stray.current_id, None);- assert_eq!(stray.quota, None);}#[test]-fn agy_submenu_switches_accounts_and_sends_management_to_the_auth_center() {- let snapshot = agy_snapshot(- Some(agy_status(- vec![- agy_account("1", Some("[email protected]")),- agy_account("2", Some("[email protected]")),- ],- Some("2"),- )),- |_| None,- )- .expect("section");- let menu = model(&[], &[snapshot]);- assert!(texts_of(&menu).contains(&"Antigravity · [email protected]".to_string()));- let children = children_of(&menu, &AppType::Agy);- assert_eq!(- texts_of(&children),- ["官方账号", "[email protected]", "[email protected]", "---", "管理账号…"]- );- assert!(matches!(- &children[1],- TrayEntry::Check { id, checked: false, enabled: true, .. } if id == "prov:agy:1"- ));- assert!(matches!(- &children[2],- TrayEntry::Check { id, checked: true, .. } if id == "prov:agy:2"- ));- assert!(matches!(- &children[4],- TrayEntry::Item { id, .. } if id == AUTH_PAGE_NAV_ID- ));+fn agy_switch_feedback_says_the_desktop_app_needs_a_restart() {+ let feedback =+ switch_feedback(&AppType::Agy, TrayMode::Direct, "Relay".to_string()).expect("feedback");assert_eq!(- parse_nav_id(AUTH_PAGE_NAV_ID),- Some(TrayNavigation {- page: Some("auth".to_string()),- ..Default::default()- })+ feedback_text(&zh(), &feedback),+ "Antigravity 已切换到 Relay,重启 Antigravity 后生效");- assert_eq!(parse_nav_id("nav:page:nope"), None);}#[test]@@ -2540,223 +2523,3 @@ fn agy_quota_groups_gemini_claude_and_argon_by_their_lowest_left() {);assert!(almost_out);}--#[test]-fn agy_switch_failures_point_to_the_auth_center_and_feedback_names_the_account() {- let problem = TrayProblem::SwitchFailed {- app: AppType::Agy,- reason: "expired".to_string(),- };- assert_eq!(problem_id(&problem), AUTH_PAGE_NAV_ID);- let feedback = TrayFeedback::AccountSwitched {- app: AppType::Agy,- name: "[email protected]".to_string(),- };- assert_eq!(- feedback_text(&zh(), &feedback),- "Antigravity 已切换到账号 [email protected],已打开的 Antigravity 重启后生效"- );-}--fn agy_quota_at(ts: Option<i64>) -> SubscriptionQuota {- let mut q = make_quota("agy", true, vec![]);- q.queried_at = ts;- q-}--#[test]-fn agy_tray_refresh_respects_manual_only_and_skips_reauth_accounts() {- let active = agy_account("1", Some("[email protected]"));- let idle = agy_account("2", Some("[email protected]"));- let mut expired = agy_account("3", Some("[email protected]"));- expired.requires_reauth = true;-- let cases = [- (&active, Some("1"), false, Some(AgyTrayQuotaAction::Live)),- (- &idle,- Some("1"),- false,- Some(AgyTrayQuotaAction::CachedOnly),- ),- (&active, None, false, Some(AgyTrayQuotaAction::CachedOnly)),- (- &active,- Some("1"),- true,- Some(AgyTrayQuotaAction::CachedOnly),- ),- (&idle, Some("1"), true, Some(AgyTrayQuotaAction::CachedOnly)),- (&active, None, true, Some(AgyTrayQuotaAction::CachedOnly)),- (&expired, Some("3"), false, None),- (&expired, Some("3"), true, None),- (&expired, Some("1"), false, None),- (&expired, None, true, None),- ];- for (account, current, manual_only, expected) in cases {- assert_eq!(- agy_tray_quota_action(account, current, manual_only),- expected- );- }-}--#[test]-fn agy_cached_quota_hydrates_only_when_missing_or_newer() {- let cache = UsageCache::new();- let saved_1000 = agy_quota_at(Some(1000));- let saved_2000 = agy_quota_at(Some(2000));- let saved_no_ts = agy_quota_at(None);- let mut saved_failure =- SubscriptionQuota::error("agy", CredentialStatus::Valid, "bad disk".to_string());- saved_failure.queried_at = Some(9999);-- // 冷启动缓存为空时,成功快照(含无时间戳旧快照)补进去,失败快照绝不回填- assert!(should_hydrate_agy_cached_quota(&cache, "1", &saved_1000));- assert!(should_hydrate_agy_cached_quota(&cache, "1", &saved_no_ts));- assert!(!should_hydrate_agy_cached_quota(- &cache,- "1",- &saved_failure- ));-- // 已有缓存时同时间戳/无时间戳不重复写入,更新的本地快照才同步覆盖- cache.put_agy_account("1".to_string(), saved_1000.clone());- assert!(!should_hydrate_agy_cached_quota(&cache, "1", &saved_1000));- assert!(!should_hydrate_agy_cached_quota(&cache, "1", &saved_no_ts));- assert!(should_hydrate_agy_cached_quota(&cache, "1", &saved_2000));-- // 刚手动刷新出来的失败结果更新于本地旧快照:不能被旧快照盖掉- let mut newer_failure =- SubscriptionQuota::error("agy", CredentialStatus::Valid, "boom".to_string());- newer_failure.queried_at = Some(2000);- cache.put_agy_account("1".to_string(), newer_failure);- assert!(!should_hydrate_agy_cached_quota(&cache, "1", &saved_1000));-- // 缓存里只是 not_found(无时间戳):有保存过的快照就补上(含无时间戳旧快照)- cache.put_agy_account("1".to_string(), SubscriptionQuota::not_found("agy"));- assert!(should_hydrate_agy_cached_quota(&cache, "1", &saved_1000));- assert!(should_hydrate_agy_cached_quota(&cache, "1", &saved_no_ts));-- // 无时间戳成功快照补进缓存后幂等,但遇到带时间戳的新快照会更新- cache.put_agy_account("1".to_string(), saved_no_ts.clone());- assert!(!should_hydrate_agy_cached_quota(&cache, "1", &saved_no_ts));- assert!(should_hydrate_agy_cached_quota(&cache, "1", &saved_1000));-}--#[tokio::test]-async fn agy_tray_quota_refresh_respects_manual_only_skips_reauth_and_is_idempotent() {- use std::sync::atomic::{AtomicUsize, Ordering};-- async fn run(- cache: &UsageCache,- saved: &HashMap<String, SubscriptionQuota>,- status: crate::services::agy_account::AgyAccountStatus,- manual_only: bool,- live_result: Result<SubscriptionQuota, String>,- ) -> (Vec<String>, Vec<String>, usize) {- let saved_reads = std::sync::Mutex::new(Vec::new());- let live_calls = std::sync::Mutex::new(Vec::new());- let updates = AtomicUsize::new(0);- refresh_agy_account_quotas(- cache,- status,- manual_only,- |id| {- saved_reads.lock().unwrap().push(id.clone());- let q = saved.get(&id).cloned();- async move { q }- },- |id| {- live_calls.lock().unwrap().push(id);- let res = live_result.clone();- async move { res }- },- || {- updates.fetch_add(1, Ordering::Relaxed);- },- )- .await;- let mut reads = saved_reads.into_inner().unwrap();- reads.sort();- (- reads,- live_calls.into_inner().unwrap(),- updates.into_inner(),- )- }-- let mut expired = agy_account("3", Some("[email protected]"));- expired.requires_reauth = true;- let status = agy_status(- vec![- agy_account("1", Some("[email protected]")),- agy_account("2", Some("[email protected]")),- expired.clone(),- ],- Some("1"),- );- let saved = HashMap::from([- ("1".to_string(), agy_quota_at(Some(1000))),- ("2".to_string(), agy_quota_at(Some(1500))),- ("3".to_string(), agy_quota_at(Some(2000))),- ]);- let cache = UsageCache::new();- let ts_of = |id: &str| cache.with_agy_account(id, |q| q.queried_at);-- // 1. 关掉「自动查询额度」:当前号和空闲号只读本地快照,失效号跳过- let (reads, live, updates) = run(- &cache,- &saved,- status.clone(),- true,- Ok(agy_quota_at(Some(9999))),- )- .await;- assert_eq!(- (reads, live, updates),- (vec!["1".into(), "2".into()], vec![], 2)- );- assert_eq!(- (ts_of("1"), ts_of("2"), ts_of("3")),- (Some(Some(1000)), Some(Some(1500)), None)- );-- // 2. 再次悬停(快照没变):幂等,不触发托盘刷新- let (_, live, updates) = run(- &cache,- &saved,- status.clone(),- true,- Ok(agy_quota_at(Some(9999))),- )- .await;- assert_eq!((live, updates), (vec![], 0));-- // 3. 打开「自动查询额度」但实时查询超时:只问当前号,保留已有缓存- let (_, live, updates) =- run(&cache, &saved, status.clone(), false, Err("timeout".into())).await;- assert_eq!(- (live, updates, ts_of("1")),- (vec!["1".into()], 0, Some(Some(1000)))- );-- // 4. 打开「自动查询额度」且实时查询成功:只更新当前号,空闲号与失效号不动- let (_, live, updates) = run(&cache, &saved, status, false, Ok(agy_quota_at(Some(3000)))).await;- assert_eq!((live, updates), (vec!["1".into()], 1));- assert_eq!(- (ts_of("1"), ts_of("2"), ts_of("3")),- (Some(Some(3000)), Some(Some(1500)), None)- );-- // 5. 当前登录本身就是 requires_reauth 账号:即使开着自动查询也绝不调实时查询- let (_, live, updates) = run(- &cache,- &saved,- agy_status(vec![expired], Some("3")),- false,- Ok(agy_quota_at(Some(4000))),- )- .await;- assert_eq!((live, updates, ts_of("3")), (vec![], 0, None));-}diff --git a/src/App.tsx b/src/App.tsxindex 1913a96c3..76e1b621e 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -1003,10 +1003,6 @@ function App() {useTrayNavigation((navigation) => {const navigate = () => {- if (navigation.page) {- openPage(navigation.page);- return;- }if (navigation.section) {openSettings(navigation.section);return;diff --git a/src/hooks/useTrayNavigation.ts b/src/hooks/useTrayNavigation.tsindex cf5a77d5c..585879a70 100644--- a/src/hooks/useTrayNavigation.ts+++ b/src/hooks/useTrayNavigation.ts@@ -12,8 +12,6 @@ export interface TrayNavigation {/** `needsRoute`:弹「需要路由」对话框;`add`:开始添加供应商 */intent?: "needsRoute" | "add";providerId?: string;- /** 全局页面:`auth` 是授权中心(托盘的 Antigravity 账号区「管理账号…」) */- page?: "auth";}interface RawTrayNavigation {@@ -21,14 +19,12 @@ interface RawTrayNavigation {section?: string;intent?: string;providerId?: string;- page?: string;}export function parseTrayNavigation(raw: RawTrayNavigation | null | undefined,): TrayNavigation | null {if (!raw) return null;- if (raw.page === "auth") return { page: "auth" };const section = SETTINGS_SECTIONS.find((s) => s === raw.section);if (section) return { section };const app = APP_IDS.find((id) => id === raw.app);diff --git a/tests/config/backendConstants.json b/tests/config/backendConstants.jsonindex 3c51b818e..08a9eab4b 100644--- a/tests/config/backendConstants.json+++ b/tests/config/backendConstants.json@@ -168,7 +168,8 @@"claude-desktop": false,"codex": false,"gemini": false,- "grokbuild": false+ "grokbuild": false,+ "agy": false}},{@@ -186,7 +187,8 @@"claude-desktop": true,"codex": true,"gemini": false,- "grokbuild": true+ "grokbuild": true,+ "agy": false}},{@@ -204,7 +206,8 @@"claude-desktop": false,"codex": true,"gemini": false,- "grokbuild": true+ "grokbuild": true,+ "agy": false}},{@@ -222,7 +225,8 @@"claude-desktop": false,"codex": true,"gemini": false,- "grokbuild": true+ "grokbuild": true,+ "agy": false}},{@@ -240,7 +244,8 @@"claude-desktop": false,"codex": true,"gemini": false,- "grokbuild": true+ "grokbuild": true,+ "agy": false}},{@@ -261,7 +266,8 @@"claude-desktop": false,"codex": true,"gemini": false,- "grokbuild": true+ "grokbuild": true,+ "agy": false}},{@@ -282,7 +288,8 @@"claude-desktop": false,"codex": false,"gemini": false,- "grokbuild": false+ "grokbuild": false,+ "agy": false}},{@@ -300,7 +307,8 @@"claude-desktop": true,"codex": false,"gemini": false,- "grokbuild": false+ "grokbuild": false,+ "agy": false}},{@@ -319,7 +327,8 @@"claude-desktop": false,"codex": false,"gemini": false,- "grokbuild": false+ "grokbuild": false,+ "agy": false}}]diff --git a/tests/hooks/useTrayNavigation.test.tsx b/tests/hooks/useTrayNavigation.test.tsxindex e1bd589c5..eaacfdf0a 100644--- a/tests/hooks/useTrayNavigation.test.tsx+++ b/tests/hooks/useTrayNavigation.test.tsx@@ -43,14 +43,12 @@ describe("parseTrayNavigation", () => {expect(parseTrayNavigation({ section: "routing" })).toEqual({section: "routing",});- expect(parseTrayNavigation({ page: "auth" })).toEqual({ page: "auth" });});it("drops unknown targets and incomplete needs-route requests", () => {expect(parseTrayNavigation(null)).toBeNull();expect(parseTrayNavigation({ app: "nope" })).toBeNull();expect(parseTrayNavigation({ section: "nope" })).toBeNull();- expect(parseTrayNavigation({ page: "nope" })).toBeNull();expect(parseTrayNavigation({ app: "codex", intent: "needsRoute" })).toEqual({ app: "codex" },);