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
perf(agy): cache login/interactive shell fallback when locating agy (#10138)
pablofb94deddf461
diff --git a/src-tauri/src/agy_config.rs b/src-tauri/src/agy_config.rsindex 0722d53ba..ce7b42789 100644--- a/src-tauri/src/agy_config.rs+++ b/src-tauri/src/agy_config.rs@@ -18,6 +18,8 @@use std::fs;use std::path::{Path, PathBuf};use std::process::Command;+use std::sync::{LazyLock, Mutex};+use std::time::{Duration, Instant};use serde::Serialize;use serde_json::{json, Value};@@ -28,6 +30,7 @@ use crate::config::{use crate::error::AppError;use crate::live::patch::json::JsonPatch;use crate::live::patch::{KeyPath, LivePatch};+use crate::sync_utils::MutexExt;/// `~/.gemini/antigravity-cli`pub fn agy_dir() -> PathBuf {@@ -1126,20 +1129,37 @@ pub(crate) fn apply_neutral_current_dir(command: &mut tokio::process::Command) {/// 从 Dock / Finder 启动时 PATH 只有系统目录,所以后两步不可省。/// 旧版测试装的包装脚本永远不会被返回。pub(crate) fn real_agy_bin() -> Option<PathBuf> {+ real_agy_bin_with_miss_bypass(false)+}++/// 定位真实的 `agy`:命中真实可执行文件时继续复用登录 shell 缓存;+/// 若缓存里记录的是未命中(`None`),绕过 miss TTL 现场重探一次(供「添加账号」显式触发)。+pub(crate) fn real_agy_bin_reprobe_miss() -> Option<PathBuf> {+ real_agy_bin_with_miss_bypass(true)+}++fn real_agy_bin_with_miss_bypass(bypass_miss: bool) -> Option<PathBuf> {let path_var = std::env::var_os("PATH").unwrap_or_default();let system_dirs: Vec<PathBuf> = if cfg!(windows) {windows_agy_dirs(dirs::data_local_dir(), &get_home_dir())} else {unix_agy_dirs(&get_home_dir())};- resolve_real_agy(+ resolve_real_agy_with_miss_bypass(&path_var,&get_home_dir(),&system_dirs,!cfg!(test) && cfg!(unix),+ bypass_miss,)}+/// 清空登录 shell 回退缓存后重新定位 `agy`(用户等待期间刚装好 CLI 时用,如「重新打开终端」)。+pub(crate) fn real_agy_bin_fresh() -> Option<PathBuf> {+ *LOGIN_SHELL_CACHE.lock_recover() = None;+ real_agy_bin()+}+/// Windows 上不在 PATH 里的安装位置(GUI 进程的 PATH 常缺用户级条目):/// install.ps1 装到 `%LOCALAPPDATA%\agy\bin`;只装了桌面版时 `agy.exe` 在/// `%USERPROFILE%\.gemini\bin`,安装器不把它加进 PATH(#10105)。@@ -1162,11 +1182,22 @@ fn unix_agy_dirs(home: &Path) -> Vec<PathBuf> {]}+#[cfg(test)]fn resolve_real_agy(path_var: &std::ffi::OsStr,home: &Path,system_dirs: &[PathBuf],probe_login_shell: bool,+) -> Option<PathBuf> {+ resolve_real_agy_with_miss_bypass(path_var, home, system_dirs, probe_login_shell, false)+}++fn resolve_real_agy_with_miss_bypass(+ path_var: &std::ffi::OsStr,+ home: &Path,+ system_dirs: &[PathBuf],+ probe_login_shell: bool,+ bypass_miss: bool,) -> Option<PathBuf> {let mut dirs: Vec<PathBuf> = std::env::split_paths(path_var).filter(|dir| !dir.as_os_str().is_empty())@@ -1189,7 +1220,7 @@ fn resolve_real_agy(}}if probe_login_shell {- return login_shell_agy().filter(|found| is_real_binary(found));+ return login_shell_agy(bypass_miss);}None}@@ -1211,11 +1242,66 @@ fn is_real_binary(path: &Path) -> bool {}}+const LOGIN_SHELL_MISS_TTL: Duration = Duration::from_secs(60);++pub(crate) struct LoginShellCacheEntry {+ shell: String,+ found: Option<PathBuf>,+ probed_at: Instant,+}++static LOGIN_SHELL_CACHE: LazyLock<Mutex<Option<LoginShellCacheEntry>>> =+ LazyLock::new(|| Mutex::new(None));++/// 缓存登录/交互 shell 的探测结果:命中真实可执行文件时长期复用(文件消失或失去可执行权限即失效),+/// 未找到时按短 TTL(60s)缓存,避免没装 agy 或只在 rc 里配 PATH 的用户每次查额度/拉模型列表都起一次交互 shell。+/// `bypass_miss = true` 时仅跳过已缓存的 `None` 现场重探一次,已缓存的真实路径仍直接复用。+/// 持锁执行探测,并发冷启动时只跑一次 shell。+pub(crate) fn cached_login_shell_agy_with<F>(+ cache: &Mutex<Option<LoginShellCacheEntry>>,+ shell: &str,+ now: Instant,+ bypass_miss: bool,+ probe: F,+) -> Option<PathBuf>+where+ F: FnOnce(&str) -> Option<PathBuf>,+{+ let mut guard = cache.lock_recover();+ if let Some(entry) = guard.as_ref() {+ if entry.shell == shell {+ match entry.found.as_ref() {+ Some(path) if is_real_binary(path) => return Some(path.clone()),+ Some(_) => {}+ None if !bypass_miss+ && now.saturating_duration_since(entry.probed_at) < LOGIN_SHELL_MISS_TTL =>+ {+ return None;+ }+ None => {}+ }+ }+ }+ let found = probe(shell).filter(|path| is_real_binary(path));+ *guard = Some(LoginShellCacheEntry {+ shell: shell.to_string(),+ found: found.clone(),+ probed_at: now,+ });+ found+}+/// 在登录 shell 里 `command -v agy`,限时 2 秒,避免用户的 rc 文件卡住界面。/// 只在 `.zshrc` / `.bashrc` 里加了 PATH 时,非交互登录 shell 看不到,仅对 zsh / bash 再试一次交互登录 shell。-fn login_shell_agy() -> Option<PathBuf> {+fn login_shell_agy(bypass_miss: bool) -> Option<PathBuf> {let shell = std::env::var("SHELL").ok().filter(|s| !s.is_empty())?;- login_shell_agy_in(&shell)+ cached_login_shell_agy_with(+ &LOGIN_SHELL_CACHE,+ &shell,+ Instant::now(),+ bypass_miss,+ login_shell_agy_in,+ )}fn login_shell_agy_in(shell: &str) -> Option<PathBuf> {@@ -2316,4 +2402,261 @@ mod integration_tests {);}}++ #[test]+ fn login_shell_cache_reuses_hits_and_expires_misses_and_deleted_binaries() {+ use std::sync::atomic::{AtomicUsize, Ordering};++ let tmp = tempfile::tempdir().unwrap();+ let agy = fake_agy(&tmp.path().join("bin"));+ let agy2 = fake_agy(&tmp.path().join("bin2"));+ let cache: Mutex<Option<LoginShellCacheEntry>> = Mutex::new(None);+ let probes = AtomicUsize::new(0);+ let t0 = Instant::now();++ // 1. 首次命中被缓存,即使超过 MISS_TTL 且二进制仍存在也不会重跑探测+ let hit1 = cached_login_shell_agy_with(&cache, "/bin/zsh", t0, false, |_| {+ probes.fetch_add(1, Ordering::SeqCst);+ Some(agy.clone())+ });+ assert_eq!(hit1, Some(agy.clone()));+ assert_eq!(probes.load(Ordering::SeqCst), 1);++ let hit2 = cached_login_shell_agy_with(+ &cache,+ "/bin/zsh",+ t0 + LOGIN_SHELL_MISS_TTL + Duration::from_secs(300),+ false,+ |_| {+ probes.fetch_add(1, Ordering::SeqCst);+ None+ },+ );+ assert_eq!(hit2, Some(agy.clone()));+ assert_eq!(probes.load(Ordering::SeqCst), 1);++ // 2. 二进制失去可执行权限或被删除时立刻失效,重新探测新路径+ fs::set_permissions(&agy, fs::Permissions::from_mode(0o644)).unwrap();+ let after_chmod = cached_login_shell_agy_with(&cache, "/bin/zsh", t0, false, |_| {+ probes.fetch_add(1, Ordering::SeqCst);+ Some(agy2.clone())+ });+ assert_eq!(after_chmod, Some(agy2.clone()));+ assert_eq!(probes.load(Ordering::SeqCst), 2);++ fs::remove_file(&agy2).unwrap();+ let miss1 = cached_login_shell_agy_with(+ &cache,+ "/bin/zsh",+ t0 + Duration::from_secs(10),+ false,+ |_| {+ probes.fetch_add(1, Ordering::SeqCst);+ None+ },+ );+ assert_eq!(miss1, None);+ assert_eq!(probes.load(Ordering::SeqCst), 3);++ // 3. 未命中在 MISS_TTL 内直接复用,过期后重新探测+ let miss2 = cached_login_shell_agy_with(+ &cache,+ "/bin/zsh",+ t0 + Duration::from_secs(10) + LOGIN_SHELL_MISS_TTL - Duration::from_secs(1),+ false,+ |_| {+ probes.fetch_add(1, Ordering::SeqCst);+ Some(fake_agy(&tmp.path().join("should-not-run-yet")))+ },+ );+ assert_eq!(miss2, None);+ assert_eq!(probes.load(Ordering::SeqCst), 3);++ let newly_installed = fake_agy(&tmp.path().join("bin3"));+ let after_ttl = cached_login_shell_agy_with(+ &cache,+ "/bin/zsh",+ t0 + Duration::from_secs(10) + LOGIN_SHELL_MISS_TTL,+ false,+ |_| {+ probes.fetch_add(1, Ordering::SeqCst);+ Some(newly_installed.clone())+ },+ );+ assert_eq!(after_ttl, Some(newly_installed.clone()));+ assert_eq!(probes.load(Ordering::SeqCst), 4);++ // 4. 切换 SHELL 会重新探测;probe 返回旧版包装脚本时规范化为 None 并缓存 miss+ let wrapper_dir = tmp.path().join("wrapper");+ fs::create_dir_all(&wrapper_dir).unwrap();+ let wrapper = wrapper_dir.join("agy");+ fs::write(&wrapper, format!("#!/bin/sh\n# {}\n", legacy::WRAPPER_MARK)).unwrap();+ fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o755)).unwrap();++ let wrapper_miss = cached_login_shell_agy_with(+ &cache,+ "/bin/bash",+ t0 + Duration::from_secs(100),+ false,+ |_| {+ probes.fetch_add(1, Ordering::SeqCst);+ Some(wrapper.clone())+ },+ );+ assert_eq!(wrapper_miss, None);+ assert_eq!(probes.load(Ordering::SeqCst), 5);++ let cached_wrapper_miss = cached_login_shell_agy_with(+ &cache,+ "/bin/bash",+ t0 + Duration::from_secs(105),+ false,+ |_| {+ probes.fetch_add(1, Ordering::SeqCst);+ Some(newly_installed.clone())+ },+ );+ assert_eq!(cached_wrapper_miss, None);+ assert_eq!(probes.load(Ordering::SeqCst), 5);+ }++ #[test]+ fn login_shell_cache_runs_interactive_probe_script_only_once_for_hit_and_miss() {+ let tmp = tempfile::tempdir().unwrap();+ let hit_zsh = tmp.path().join("hit-dir").join("zsh");+ let miss_zsh = tmp.path().join("miss-dir").join("zsh");+ fs::create_dir_all(hit_zsh.parent().unwrap()).unwrap();+ fs::create_dir_all(miss_zsh.parent().unwrap()).unwrap();++ let hit_count = tmp.path().join("hit.count");+ let miss_count = tmp.path().join("miss.count");+ let agy = fake_agy(&tmp.path().join("custom"));++ fs::write(+ &hit_zsh,+ format!(+ "#!/bin/sh\nif [ \"$1\" = \"-l\" ] && [ \"$2\" = \"-i\" ]; then\n printf 'x' >> '{}'\n printf '%s\\n' '{}'\n exit 0\nfi\nexit 1\n",+ hit_count.display(),+ agy.display()+ ),+ )+ .unwrap();+ fs::write(+ &miss_zsh,+ format!(+ "#!/bin/sh\nif [ \"$1\" = \"-l\" ] && [ \"$2\" = \"-i\" ]; then\n printf 'x' >> '{}'\nfi\nexit 1\n",+ miss_count.display()+ ),+ )+ .unwrap();+ fs::set_permissions(&hit_zsh, fs::Permissions::from_mode(0o755)).unwrap();+ fs::set_permissions(&miss_zsh, fs::Permissions::from_mode(0o755)).unwrap();++ let cache: Mutex<Option<LoginShellCacheEntry>> = Mutex::new(None);+ let t0 = Instant::now();+ for _ in 0..3 {+ assert_eq!(+ cached_login_shell_agy_with(+ &cache,+ &hit_zsh.to_string_lossy(),+ t0,+ false,+ login_shell_agy_in,+ ),+ Some(agy.clone())+ );+ }+ assert_eq!(fs::read_to_string(&hit_count).unwrap().len(), 1);++ for i in 0..3 {+ assert_eq!(+ cached_login_shell_agy_with(+ &cache,+ &miss_zsh.to_string_lossy(),+ t0 + Duration::from_secs(i),+ false,+ login_shell_agy_in,+ ),+ None+ );+ }+ assert_eq!(fs::read_to_string(&miss_count).unwrap().len(), 1);+ }++ #[test]+ fn login_shell_cache_miss_bypass_reprobes_only_misses_and_reuses_valid_hits() {+ use std::sync::atomic::{AtomicUsize, Ordering};++ let tmp = tempfile::tempdir().unwrap();+ let agy = fake_agy(&tmp.path().join("bin"));+ let cache: Mutex<Option<LoginShellCacheEntry>> = Mutex::new(None);+ let probes = AtomicUsize::new(0);+ let t0 = Instant::now();++ // 1. 冷启动时 bypass_miss = true 只探测一次(不会重复拉起两次 shell)+ let cold_miss = cached_login_shell_agy_with(&cache, "/bin/zsh", t0, true, |_| {+ probes.fetch_add(1, Ordering::SeqCst);+ None+ });+ assert_eq!(cold_miss, None);+ assert_eq!(probes.load(Ordering::SeqCst), 1);++ // 2. 普通路径在 60s TTL 内复用 miss;bypass_miss = true 跳过 miss 缓存重新探测+ let cached_miss = cached_login_shell_agy_with(+ &cache,+ "/bin/zsh",+ t0 + Duration::from_secs(5),+ false,+ |_| {+ probes.fetch_add(1, Ordering::SeqCst);+ Some(agy.clone())+ },+ );+ assert_eq!(cached_miss, None);+ assert_eq!(probes.load(Ordering::SeqCst), 1);++ let reprobed = cached_login_shell_agy_with(+ &cache,+ "/bin/zsh",+ t0 + Duration::from_secs(10),+ true,+ |_| {+ probes.fetch_add(1, Ordering::SeqCst);+ Some(agy.clone())+ },+ );+ assert_eq!(reprobed, Some(agy.clone()));+ assert_eq!(probes.load(Ordering::SeqCst), 2);++ // 3. 命中真实可执行文件后,即使 bypass_miss = true 也直接复用缓存、不重复探测+ let hit_reused = cached_login_shell_agy_with(+ &cache,+ "/bin/zsh",+ t0 + Duration::from_secs(15),+ true,+ |_| {+ probes.fetch_add(1, Ordering::SeqCst);+ None+ },+ );+ assert_eq!(hit_reused, Some(agy));+ assert_eq!(probes.load(Ordering::SeqCst), 2);+ }++ #[test]+ #[serial]+ fn real_agy_bin_fresh_clears_login_shell_cache() {+ let tmp = tempfile::tempdir().unwrap();+ let agy = fake_agy(&tmp.path().join("fresh-bin"));+ *LOGIN_SHELL_CACHE.lock_recover() = Some(LoginShellCacheEntry {+ shell: "/bin/zsh".to_string(),+ found: Some(agy),+ probed_at: Instant::now(),+ });+ assert!(LOGIN_SHELL_CACHE.lock_recover().is_some());++ let _home = HomeGuard::new();+ let _ = real_agy_bin_fresh();+ assert!(LOGIN_SHELL_CACHE.lock_recover().is_none());+ }}diff --git a/src-tauri/src/commands/agy_account.rs b/src-tauri/src/commands/agy_account.rsindex 8e250af98..17be2c247 100644--- a/src-tauri/src/commands/agy_account.rs+++ b/src-tauri/src/commands/agy_account.rs@@ -23,6 +23,7 @@ pub(crate) const LOGIN_SURFACE_DESKTOP: &str = "desktop";/// 「添加账号」的登录入口:找到 agy 就在终端里跑(现有方式);没找到但装了 Antigravity/// 桌面端就交给桌面端登录(桌面端 Sign in 与 CLI 共用同一把系统钥匙串,CC Switch 只观察/// 收录,不用 agy 的 OAuth 客户端)。都没有时返回 `Missing`。+#[derive(Debug, PartialEq, Eq)]pub(crate) enum LoginSurface {/// agy 可执行文件的路径Terminal(PathBuf),@@ -34,20 +35,39 @@ pub(crate) enum LoginSurface {}/// 探测「添加账号」的登录入口(文件系统探测,放阻塞线程里跑)。+/// 若登录 shell 缓存此前记录的是未命中(`None`),绕过 miss TTL 现场重探一次;+/// 已缓存的真实可执行文件仍直接复用,不额外起 shell。pub(crate) async fn resolve_login_surface() -> LoginSurface {tokio::task::spawn_blocking(|| {- if let Some(bin) = crate::agy_config::real_agy_bin() {- return LoginSurface::Terminal(bin);- }- if !crate::agy_config::desktop_status().installed {- return LoginSurface::Missing;- }- LoginSurface::Desktop(crate::agy_config::desktop_launch_target())+ resolve_login_surface_with(+ crate::agy_config::real_agy_bin_reprobe_miss,+ || crate::agy_config::desktop_status().installed,+ crate::agy_config::desktop_launch_target,+ )}).await.unwrap_or(LoginSurface::Missing)}+fn resolve_login_surface_with<F, D, L>(+ find_bin: F,+ desktop_installed: D,+ desktop_target: L,+) -> LoginSurface+where+ F: FnOnce() -> Option<PathBuf>,+ D: FnOnce() -> bool,+ L: FnOnce() -> Option<PathBuf>,+{+ if let Some(bin) = find_bin() {+ return LoginSurface::Terminal(bin);+ }+ if !desktop_installed() {+ return LoginSurface::Missing;+ }+ LoginSurface::Desktop(desktop_target())+}+/// 界面上的额度查询在这么短的时间里重复时,直接用上一次 `/usage` 的结果,免得同时起好几个 agy。pub(crate) const QUOTA_REUSE_INTERACTIVE: Duration = Duration::from_secs(20);/// 失败或未检测到 agy 的结果仅做短时复用,避免并发或托盘悬停反复拉起 agy,又不至于把失败卡太久。@@ -342,7 +362,7 @@ fn login_proxy_vars() -> Vec<(&'static str, String)> {/// 打开用户首选终端运行 `agy`,让用户在 agy 自己的界面里登录要添加的账号。/// 「重新打开终端」也走这里:现场重新定位 agy(等待期间用户可能刚装好)。pub(crate) async fn open_agy_login_terminal(exit_file: Option<PathBuf>) -> Result<(), String> {- let bin = tokio::task::spawn_blocking(crate::agy_config::real_agy_bin)+ let bin = tokio::task::spawn_blocking(crate::agy_config::real_agy_bin_fresh).await.map_err(|e| format!("launch task join error: {e}"))?;open_terminal_with_bin(bin, exit_file).await@@ -758,6 +778,111 @@ mod tests {assert!(snapshot_only(true, None, None));}+ #[test]+ fn resolve_login_surface_bypasses_cached_miss_while_reusing_valid_hit() {+ use std::sync::Mutex as StdMutex;++ let tmp = tempfile::tempdir().unwrap();+ let agy = tmp.path().join("agy");+ std::fs::write(&agy, "#!/bin/sh\nexit 0\n").unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&agy, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ let desktop = tmp.path().join("Antigravity.app");+ let cache: StdMutex<Option<crate::agy_config::LoginShellCacheEntry>> = StdMutex::new(None);+ let probes = AtomicUsize::new(0);+ let t0 = Instant::now();++ // 1. 后台查询未找到 agy,在 60s 内缓存 None miss;期间回退到桌面端或 Missing+ let bg_miss =+ crate::agy_config::cached_login_shell_agy_with(&cache, "/bin/zsh", t0, false, |_| {+ probes.fetch_add(1, Ordering::SeqCst);+ None+ });+ assert_eq!(bg_miss, None);+ assert_eq!(probes.load(Ordering::SeqCst), 1);++ let desktop_fallback = resolve_login_surface_with(+ || {+ crate::agy_config::cached_login_shell_agy_with(+ &cache,+ "/bin/zsh",+ t0 + Duration::from_secs(5),+ true,+ |_| {+ probes.fetch_add(1, Ordering::SeqCst);+ None+ },+ )+ },+ || true,+ || Some(desktop.clone()),+ );+ assert_eq!(desktop_fallback, LoginSurface::Desktop(Some(desktop)));+ assert_eq!(probes.load(Ordering::SeqCst), 2);++ let missing_fallback = resolve_login_surface_with(+ || {+ crate::agy_config::cached_login_shell_agy_with(+ &cache,+ "/bin/zsh",+ t0 + Duration::from_secs(6),+ true,+ |_| {+ probes.fetch_add(1, Ordering::SeqCst);+ None+ },+ )+ },+ || false,+ || None,+ );+ assert_eq!(missing_fallback, LoginSurface::Missing);+ assert_eq!(probes.load(Ordering::SeqCst), 3);++ // 2. 用户随后安装好 agy 并点击「添加账号」:即使仍在 60s miss TTL 内,仍绕过 miss 缓存重探并命中+ let added = resolve_login_surface_with(+ || {+ crate::agy_config::cached_login_shell_agy_with(+ &cache,+ "/bin/zsh",+ t0 + Duration::from_secs(10),+ true,+ |_| {+ probes.fetch_add(1, Ordering::SeqCst);+ Some(agy.clone())+ },+ )+ },+ || panic!("desktop status should not be checked once agy is found"),+ || panic!("desktop target should not be checked once agy is found"),+ );+ assert_eq!(added, LoginSurface::Terminal(agy.clone()));+ assert_eq!(probes.load(Ordering::SeqCst), 4);++ // 3. 已缓存有效路径时,再次点击「添加账号」直接零成本复用,不再触发 shell 探测+ let reused = resolve_login_surface_with(+ || {+ crate::agy_config::cached_login_shell_agy_with(+ &cache,+ "/bin/zsh",+ t0 + Duration::from_secs(15),+ true,+ |_| {+ probes.fetch_add(1, Ordering::SeqCst);+ None+ },+ )+ },+ || false,+ || None,+ );+ assert_eq!(reused, LoginSurface::Terminal(agy));+ assert_eq!(probes.load(Ordering::SeqCst), 4);+ }+#[test]fn agy_account_quota_serializes_gateway_in_use_only_when_true() {let without_gateway = serde_json::to_value(AgyAccountQuota {