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

fix(agy): harden terminal login launch and state handling (#10102)

pablo9d6692b1b8db
diff --git a/src-tauri/src/agy_config.rs b/src-tauri/src/agy_config.rs
index f3499f867..8695c8589 100644
--- a/src-tauri/src/agy_config.rs
+++ b/src-tauri/src/agy_config.rs
@@ -1135,11 +1135,27 @@ fn is_real_binary(path: &Path) -> bool {
}
/// 在登录 shell 里 `command -v agy`,限时 2 秒,避免用户的 rc 文件卡住界面。
+/// 只在 `.zshrc` / `.bashrc` 里加了 PATH 时,非交互登录 shell 看不到,仅对 zsh / bash 再试一次交互登录 shell。
fn login_shell_agy() -> Option<PathBuf> {
- use std::process::Stdio;
let shell = std::env::var("SHELL").ok().filter(|s| !s.is_empty())?;
+ login_shell_agy_in(&shell)
+}
+
+fn login_shell_agy_in(shell: &str) -> Option<PathBuf> {
+ if let Some(found) = probe_shell_agy(shell, &["-l", "-c", "command -v agy"]) {
+ return Some(found);
+ }
+ let base = Path::new(shell).file_name().and_then(|n| n.to_str());
+ if matches!(base, Some("zsh" | "bash")) {
+ return probe_shell_agy(shell, &["-l", "-i", "-c", "command -v agy"]);
+ }
+ None
+}
+
+fn probe_shell_agy(shell: &str, args: &[&str]) -> Option<PathBuf> {
+ use std::process::Stdio;
let mut child = Command::new(shell)
- .args(["-l", "-c", "command -v agy"])
+ .args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
@@ -1160,8 +1176,14 @@ fn login_shell_agy() -> Option<PathBuf> {
}
let output = child.wait_with_output().ok()?;
let text = String::from_utf8(output.stdout).ok()?;
- let path = PathBuf::from(text.lines().rev().find(|l| !l.trim().is_empty())?.trim());
- path.is_absolute().then_some(path)
+ text.lines()
+ .rev()
+ .map(str::trim)
+ .filter(|l| !l.is_empty())
+ .find_map(|line| {
+ let path = PathBuf::from(line);
+ path.is_absolute().then_some(path)
+ })
}
/// 撤掉 #8268 测试版装的启动器:`bin/agy` 包装脚本、带 Key 的 `env` 文件和各 shell
@@ -2122,4 +2144,22 @@ mod integration_tests {
let path = std::env::join_paths([&wrapper_dir, &plain, &real_dir]).unwrap();
assert_eq!(resolve_real_agy(&path, &home, &[], false), Some(real));
}
+
+ #[test]
+ fn login_shell_falls_back_to_interactive_for_zsh_and_bash_only() {
+ let tmp = tempfile::tempdir().unwrap();
+ let zsh = tmp.path().join("zsh");
+ let sh = tmp.path().join("sh");
+ let agy = fake_agy(&tmp.path().join("custom"));
+ let script = format!(
+ "#!/bin/sh\nif [ \"$1\" = \"-l\" ] && [ \"$2\" = \"-i\" ]; then\n echo 'welcome'\n printf '%s\\n' '{}'\n exit 0\nfi\nexit 1\n",
+ agy.display()
+ );
+ for bin in [&zsh, &sh] {
+ fs::write(bin, &script).unwrap();
+ fs::set_permissions(bin, fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ assert_eq!(login_shell_agy_in(&zsh.to_string_lossy()), Some(agy));
+ assert_eq!(login_shell_agy_in(&sh.to_string_lossy()), None);
+ }
}
diff --git a/src-tauri/src/commands/agy_account.rs b/src-tauri/src/commands/agy_account.rs
index 82ed3d0b5..f061a4997 100644
--- a/src-tauri/src/commands/agy_account.rs
+++ b/src-tauri/src/commands/agy_account.rs
@@ -86,10 +86,14 @@ pub async fn agy_account_last_quota(
Ok(state.0.last_quota(&account_id).await)
}
-/// 「添加账号」等待中「重新打开终端」:只再开一个终端,不重置这次登录。
+/// 「添加账号」等待中「重新打开终端」:只再开一个终端,不重置这次登录。新终端换一个退出码文件,
+/// 旧终端之后退出不会把这次登录判成失败。
#[tauri::command]
-pub async fn agy_account_open_login_terminal() -> Result<(), String> {
- open_agy_login_terminal().await
+pub async fn agy_account_open_login_terminal(
+ state: tauri::State<'_, AgyAccountState>,
+) -> Result<(), String> {
+ let exit_file = state.0.renew_login_exit_file().await;
+ open_agy_login_terminal(exit_file).await
}
/// 「添加账号」等待中「打开 Antigravity」:启动桌面端,不重置这次登录。
@@ -223,8 +227,9 @@ where
/// Unix 终端里跑的登录命令:完整路径直呼刚探测到的 `agy`,没探测到时退回裸 `agy` 交给
/// 用户 shell 的 PATH 解析(探测失败时 shell 里大概率也没有,命令不存在诊断会留在窗口里)。
/// `env -u` 去掉可能残留的 Key,免得 agy 改走 Key 模式。
+/// `proxy_vars` 是要带进终端的全局代理环境变量(见 [`login_proxy_vars`])。
#[cfg_attr(windows, allow(dead_code))]
-fn format_unix_login_command(bin: Option<&Path>) -> String {
+fn format_unix_login_command(bin: Option<&Path>, proxy_vars: &[(&str, String)]) -> String {
let invocation = match bin {
Some(path) => {
let escaped = path.to_string_lossy().replace('\'', "'\\''");
@@ -232,16 +237,34 @@ fn format_unix_login_command(bin: Option<&Path>) -> String {
}
None => TOOL.to_string(),
};
- format!("env -u GEMINI_API_KEY -u GOOGLE_GEMINI_BASE_URL {invocation}")
+ let mut parts = vec!["env -u GEMINI_API_KEY -u GOOGLE_GEMINI_BASE_URL".to_string()];
+ for (key, value) in proxy_vars {
+ let escaped = value.replace('\'', "'\\''");
+ parts.push(format!("{key}='{escaped}'"));
+ }
+ parts.push(invocation);
+ parts.join(" ")
+}
+
+/// Go 版 agy 不读系统代理:CC Switch 设了全局代理时,登录终端里也带上(含 SOCKS5)。
+/// 用户环境里已经设了的变量不覆盖。
+fn login_proxy_vars() -> Vec<(&'static str, String)> {
+ crate::proxy::http_client::get_current_proxy_url()
+ .map(|url| {
+ crate::services::claude_account::login::global_proxy_env(&url, true, |key| {
+ std::env::var_os(key).is_some()
+ })
+ })
+ .unwrap_or_default()
}
/// 打开用户首选终端运行 `agy`,让用户在 agy 自己的界面里登录要添加的账号。
/// 「重新打开终端」也走这里:现场重新定位 agy(等待期间用户可能刚装好)。
-pub(crate) async fn open_agy_login_terminal() -> Result<(), String> {
+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)
.await
.map_err(|e| format!("launch task join error: {e}"))?;
- open_terminal_with_bin(bin).await
+ open_terminal_with_bin(bin, exit_file).await
}
/// 用已知路径打开终端运行 `agy`(`start_login` 已先收好原登录并暂时清掉钥匙串,新开的
@@ -249,8 +272,16 @@ pub(crate) async fn open_agy_login_terminal() -> Result<(), String> {
/// .bat 里的命令要交给 cmd 按 PATH 解析,残留的启动器脚本(如被卸载 CLI 留下的
/// `agy.cmd`)会把客户端文件重新下载回来;没定位到 `agy.exe` 时直接报错,不开必死终端。
/// cmd 分支给路径多包一层双引号,用户名带 `&`、`(`、`)` 等字符(agy 安装目录随之带上)
-/// 也能跑。macOS/Linux 仍走启动脚本——探测只认真正的可执行文件,脚本只负责跑它。
-pub(crate) async fn open_terminal_with_bin(bin: Option<PathBuf>) -> Result<(), String> {
+/// 也能跑。macOS/Linux 仍走启动脚本——探测只认真正的可执行文件,脚本只负责跑它;`exit_file`
+/// 给了时脚本在 agy 退出后把退出码写进去,轮询看到就结束等待。Windows 不经脚本,拿不到
+/// 退出码,仍等登录或超时。两边都带上全局代理。
+pub(crate) async fn open_terminal_with_bin(
+ bin: Option<PathBuf>,
+ exit_file: Option<PathBuf>,
+) -> Result<(), String> {
+ let proxy_vars = tokio::task::spawn_blocking(login_proxy_vars)
+ .await
+ .map_err(|e| format!("launch task join error: {e}"))?;
#[cfg(target_os = "windows")]
{
let Some(bin) = bin else {
@@ -261,11 +292,18 @@ pub(crate) async fn open_terminal_with_bin(bin: Option<PathBuf>) -> Result<(), S
)
.to_string());
};
+ // Windows 不经脚本,没有地方写退出码
+ let _ = exit_file;
// 清掉旧凭据环境变量,保证 agy 走自己的登录流程(等价于原 .bat 里的 `set "VAR="`)
tokio::task::spawn_blocking(move || {
+ let envs: Vec<(&str, &str)> = proxy_vars
+ .iter()
+ .map(|(key, value)| (*key, value.as_str()))
+ .collect();
crate::commands::terminal_launch::launch_terminal_command(
&bin,
&[],
+ &envs,
&["GEMINI_API_KEY", "GOOGLE_GEMINI_BASE_URL"],
)
})
@@ -274,9 +312,16 @@ pub(crate) async fn open_terminal_with_bin(bin: Option<PathBuf>) -> Result<(), S
}
#[cfg(not(target_os = "windows"))]
{
- let command = format_unix_login_command(bin.as_deref());
+ let command = format_unix_login_command(bin.as_deref(), &proxy_vars);
tokio::task::spawn_blocking(move || {
- crate::commands::terminal_launch::launch_terminal_running(&command, "agy_login")
+ if let Some(path) = exit_file.as_deref() {
+ let _ = std::fs::remove_file(path);
+ }
+ crate::commands::terminal_launch::launch_terminal_running_with_exit_file(
+ &command,
+ "agy_login",
+ exit_file.as_deref(),
+ )
})
.await
.map_err(|e| format!("launch task join error: {e}"))?
@@ -490,13 +535,23 @@ mod tests {
#[test]
fn login_command_escapes_special_chars() {
assert_eq!(
- format_unix_login_command(None),
+ format_unix_login_command(None, &[]),
"env -u GEMINI_API_KEY -u GOOGLE_GEMINI_BASE_URL agy"
);
assert_eq!(
- format_unix_login_command(Some(Path::new("/Users/o'neil/.local/bin/agy"))),
+ format_unix_login_command(Some(Path::new("/Users/o'neil/.local/bin/agy")), &[]),
"env -u GEMINI_API_KEY -u GOOGLE_GEMINI_BASE_URL '/Users/o'\\''neil/.local/bin/agy'"
);
+
+ // 全局代理带进登录终端(Go 版 agy 不读系统代理),值按单引号转义
+ let proxy = vec![
+ ("HTTPS_PROXY", "socks5://u:p'[email protected]:1080".to_string()),
+ ("NO_PROXY", "localhost,127.0.0.1".to_string()),
+ ];
+ assert_eq!(
+ format_unix_login_command(None, &proxy),
+ "env -u GEMINI_API_KEY -u GOOGLE_GEMINI_BASE_URL HTTPS_PROXY='socks5://u:p'\\''[email protected]:1080' NO_PROXY='localhost,127.0.0.1' agy"
+ );
}
#[cfg(windows)]
@@ -504,7 +559,7 @@ mod tests {
async fn windows_login_without_agy_fails_instead_of_a_dead_terminal() {
// 没定位到 agy.exe(卸载后只剩残留启动器脚本也算没定位):不再开终端跑裸 `agy`,
// 避免 PATH 里的启动器脚本把客户端文件重新下载回来
- let error = open_terminal_with_bin(None).await.unwrap_err();
+ let error = open_terminal_with_bin(None, None).await.unwrap_err();
assert!(error.contains("未找到") && error.contains("agy"));
}
diff --git a/src-tauri/src/commands/auth.rs b/src-tauri/src/commands/auth.rs
index 0d559b541..eefa2b086 100644
--- a/src-tauri/src/commands/auth.rs
+++ b/src-tauri/src/commands/auth.rs
@@ -312,7 +312,11 @@ pub async fn auth_start_login(
LoginSurface::Terminal(bin) => {
let start = agy_state.0.start_login().await?;
if let Err(error) =
- crate::commands::agy_account::open_terminal_with_bin(Some(bin)).await
+ crate::commands::agy_account::open_terminal_with_bin(
+ Some(bin),
+ start.exit_status_file.clone(),
+ )
+ .await
{
agy_state.0.cancel_login(&start.flow_id).await;
return Err(error);
diff --git a/src-tauri/src/commands/terminal_launch.rs b/src-tauri/src/commands/terminal_launch.rs
index 126ee492b..38a32154a 100644
--- a/src-tauri/src/commands/terminal_launch.rs
+++ b/src-tauri/src/commands/terminal_launch.rs
@@ -861,6 +861,23 @@ fn unique_temp_path(stem: &str, ext: &str) -> PathBuf {
))
}
+/// 写只有本人能读、写、执行的启动脚本(0700):脚本里可能带代理的账号密码,Linux 的 `/tmp`
+/// 别的用户也能列出和读取。路径由 [`unique_temp_path`] 生成,`create_new` 不会跟随别人预先放好的文件。
+#[cfg(any(target_os = "macos", target_os = "linux"))]
+fn write_private_script(path: &Path, content: &str) -> Result<(), String> {
+ use std::io::Write;
+ use std::os::unix::fs::OpenOptionsExt;
+
+ let mut file = std::fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .mode(0o700)
+ .open(path)
+ .map_err(|e| format!("写入启动脚本失败: {e}"))?;
+ file.write_all(content.as_bytes())
+ .map_err(|e| format!("写入启动脚本失败: {e}"))
+}
+
/// 根据平台打开终端运行 `launch`。
fn launch_provider_terminal(launch: &ProviderLaunch, cwd: Option<&Path>) -> Result<(), String> {
#[cfg(any(target_os = "macos", target_os = "linux"))]
@@ -1336,6 +1353,7 @@ fn build_macos_ghostty_applescript(script_file: &std::path::Path) -> String {
set was_running to application "Ghostty" is running
if was_running then
tell application "Ghostty"
+ activate
new window with configuration {{command:launcher_command}}
end tell
else
@@ -1915,6 +1933,8 @@ fn wt_terminal_command(program_str: &str, args: &[&str]) -> std::process::Comman
/// 把完整路径作为 UTF-16 参数直接交给终端,也不经过代码页解码(#8034 只影响 .bat 的
/// 文件字节)。窗口用 `/K`、`-NoExit` 保持打开,命令退出后用户仍看得到输出。cmd 分支
/// 给路径多包一层双引号并经外层转义交给 `cmd /K`,用户名带 `&`、`(`、`)`、`%` 等字符时也能跑。
+/// `envs` 加给启动的终端(`start` 会继承;旧版 Windows Terminal 的新标签不一定继承),
+/// `env_removals` 从中删掉。
///
/// **Security**:`program` 与 `args` 会原样交给终端执行,调用方必须保证内容可信
/// (当前只由后端用已探测的二进制路径调用)。
@@ -1922,24 +1942,29 @@ fn wt_terminal_command(program_str: &str, args: &[&str]) -> std::process::Comman
pub(crate) fn launch_terminal_command(
program: &Path,
args: &[&str],
+ envs: &[(&str, &str)],
env_removals: &[&str],
) -> Result<(), String> {
let program_str = program.to_string_lossy().to_string();
let preferred = crate::settings::get_preferred_terminal();
let terminal = preferred.as_deref().unwrap_or("cmd");
+ let run = |mut command: std::process::Command, terminal_name: &str| {
+ command.envs(envs.iter().copied());
+ run_terminal_command(command, terminal_name, env_removals)
+ };
let result = match terminal {
"powershell" => {
let command = powershell_terminal_command(&program_str, args);
- run_terminal_command(command, "PowerShell", env_removals)
+ run(command, "PowerShell")
}
"wt" => {
let command = wt_terminal_command(&program_str, args);
- run_terminal_command(command, "Windows Terminal", env_removals)
+ run(command, "Windows Terminal")
}
_ => {
let command = cmd_terminal_command(&program_str, args);
- run_terminal_command(command, "cmd", env_removals)
+ run(command, "cmd")
}
};
@@ -1949,7 +1974,7 @@ pub(crate) fn launch_terminal_command(
result.as_ref().err()
);
let command = cmd_terminal_command(&program_str, args);
- return run_terminal_command(command, "cmd", env_removals);
+ return run(command, "cmd");
}
result
}
@@ -1971,6 +1996,47 @@ fn windows_powershell_program(path: &str) -> &'static str {
}
}
+#[cfg_attr(windows, allow(dead_code))]
+fn build_running_unix_script(
+ script_file: &Path,
+ command_line: &str,
+ label: &str,
+ exit_file: Option<&Path>,
+) -> String {
+ let cleanup = shell_single_quote(&format!(
+ "rm -f -- {}",
+ shell_single_quote(&script_file.to_string_lossy())
+ ));
+ let exit_record = exit_file
+ .map(|path| {
+ let exit_q = shell_single_quote(&path.to_string_lossy());
+ let tmp_q = shell_single_quote(&format!("{}.tmp", path.to_string_lossy()));
+ format!(
+ "_cc_switch_rc=$?\nprintf '%s\\n' \"$_cc_switch_rc\" > {tmp_q} && mv -f {tmp_q} {exit_q} || rm -f -- {tmp_q}\n"
+ )
+ })
+ .unwrap_or_default();
+ format!(
+ "#!/usr/bin/env sh\ntrap {cleanup} EXIT\ncd \"$HOME\" 2>/dev/null || true\necho \"[cc-switch] Starting: {label}\"\necho \"\"\n{command_line}\n{exit_record}echo \"\"\necho \"[cc-switch] Command exited. Press Enter to close.\"\nread -r _\n"
+ )
+}
+
+#[cfg_attr(not(windows), allow(dead_code))]
+fn build_running_windows_bat(command_line: &str, label: &str, exit_file: Option<&Path>) -> String {
+ let exit_record = exit_file
+ .map(|path| {
+ let escaped = path.to_string_lossy().replace('%', "%%");
+ let tmp = format!("{escaped}.tmp");
+ format!(
+ "set \"_CC_SWITCH_RC=%ERRORLEVEL%\"\r\n(echo %_CC_SWITCH_RC%)>\"{tmp}\"\r\nmove /y \"{tmp}\" \"{escaped}\" >nul 2>&1 || del \"{tmp}\" >nul 2>&1\r\n"
+ )
+ })
+ .unwrap_or_default();
+ format!(
+ "@echo off\r\ncd /d \"%USERPROFILE%\" 2>nul\r\necho [cc-switch] Starting: {label}\r\necho.\r\n{command_line}\r\n{exit_record}echo.\r\necho [cc-switch] Command exited. Press any key to close.\r\npause >nul\r\ndel \"%~f0\" >nul 2>&1\r\n"
+ )
+}
+
/// 打开用户首选终端并在其中执行一段可信命令脚本。脚本尾部 `read -r` / `pause`
/// 是刻意设计的——让命令退出后窗口不要瞬间关闭,用户才看得到 `command
/// not found` / `ModuleNotFoundError` 这类诊断信息。
@@ -1978,37 +2044,24 @@ fn windows_powershell_program(path: &str) -> &'static str {
/// **Security**:`command_line` 会被原样拼进 shell/batch 脚本,调用方必须
/// 保证它是可信字符串(当前只由后端硬编码调用)。
pub(crate) fn launch_terminal_running(command_line: &str, label: &str) -> Result<(), String> {
- let temp_dir = std::env::temp_dir();
- let pid = std::process::id();
+ launch_terminal_running_with_exit_file(command_line, label, None)
+}
+pub(crate) fn launch_terminal_running_with_exit_file(
+ command_line: &str,
+ label: &str,
+ exit_file: Option<&Path>,
+) -> Result<(), String> {
#[cfg(any(target_os = "macos", target_os = "linux"))]
let (script_file, script_content) = {
- let file = temp_dir.join(format!("cc_switch_{}_{}.sh", label, pid));
- let content = format!(
- r#"#!/usr/bin/env sh
-trap 'rm -f "{script_path}"' EXIT
-echo "[cc-switch] Starting: {label}"
-echo ""
-{cmd}
-echo ""
-echo "[cc-switch] Command exited. Press Enter to close."
-read -r _
-"#,
- script_path = file.display(),
- label = label,
- cmd = command_line,
- );
+ let file = unique_temp_path(&format!("cc_switch_{label}"), "sh");
+ let content = build_running_unix_script(&file, command_line, label, exit_file);
(file, content)
};
#[cfg(target_os = "macos")]
{
- use std::os::unix::fs::PermissionsExt;
-
- std::fs::write(&script_file, &script_content)
- .map_err(|e| format!("写入启动脚本失败: {e}"))?;
- std::fs::set_permissions(&script_file, std::fs::Permissions::from_mode(0o755))
- .map_err(|e| format!("设置脚本权限失败: {e}"))?;
+ write_private_script(&script_file, &script_content)?;
let preferred = crate::settings::get_preferred_terminal();
let terminal = preferred.as_deref().unwrap_or("terminal");
@@ -2025,26 +2078,27 @@ read -r _
_ => launch_macos_terminal_app(&script_file),
};
- if result.is_err() && terminal != "terminal" {
+ let final_result = if result.is_err() && terminal != "terminal" {
log::warn!(
"首选终端 {} 启动失败,回退到 Terminal.app: {:?}",
terminal,
result.as_ref().err()
);
- return launch_macos_terminal_app(&script_file);
+ launch_macos_terminal_app(&script_file)
+ } else {
+ result
+ };
+ if final_result.is_err() {
+ let _ = std::fs::remove_file(&script_file);
}
- result
+ final_result
}
#[cfg(target_os = "linux")]
{
- use std::os::unix::fs::PermissionsExt;
use std::process::Command;
- std::fs::write(&script_file, &script_content)
- .map_err(|e| format!("写入启动脚本失败: {e}"))?;
- std::fs::set_permissions(&script_file, std::fs::Permissions::from_mode(0o755))
- .map_err(|e| format!("设置脚本权限失败: {e}"))?;
+ write_private_script(&script_file, &script_content)?;
let preferred = crate::settings::get_preferred_terminal();
let terminals_to_try = linux_terminal_candidates(preferred.as_deref());
@@ -2081,12 +2135,8 @@ read -r _
let preferred = crate::settings::get_preferred_terminal();
let terminal = preferred.as_deref().unwrap_or("cmd");
- let bat_file = temp_dir.join(format!("cc_switch_{}_{}.bat", label, pid));
- let content = format!(
- "@echo off\r\necho [cc-switch] Starting: {label}\r\necho.\r\n{cmd}\r\necho.\r\necho [cc-switch] Command exited. Press any key to close.\r\npause >nul\r\ndel \"%~f0\" >nul 2>&1\r\n",
- label = label,
- cmd = command_line,
- );
+ let bat_file = unique_temp_path(&format!("cc_switch_{label}"), "bat");
+ let content = build_running_windows_bat(command_line, label, exit_file);
std::fs::write(&bat_file, &content).map_err(|e| format!("写入批处理文件失败: {e}"))?;
let bat_path = bat_file.to_string_lossy();
@@ -2128,7 +2178,7 @@ read -r _
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
{
- let _ = (temp_dir, pid, command_line, label);
+ let _ = (command_line, label, exit_file);
Err("不支持的操作系统".to_string())
}
}
@@ -2910,10 +2960,65 @@ mod tests {
let ghostty = build_macos_ghostty_applescript(p);
assert!(ghostty.contains(expected_sh));
- assert!(ghostty.contains("new window with configuration {command:launcher_command}"));
+ assert!(ghostty.contains(
+ "tell application \"Ghostty\"\n activate\n new window with configuration {command:launcher_command}"
+ ));
assert!(ghostty.contains("--initial-command="));
}
+ #[test]
+ fn running_scripts_set_home_cwd_quote_cleanup_and_record_exit_status() {
+ let script = Path::new("/tmp/it's dir/cc_switch_agy_login_1.sh");
+ let exit_file = Path::new("/tmp/it's dir/exit.status");
+ let unix = build_running_unix_script(script, "agy", "agy_login", Some(exit_file));
+ assert!(unix.contains("cd \"$HOME\" 2>/dev/null || true\n"));
+ assert!(unix.contains("trap 'rm -f -- '\"'\"'/tmp/it'\"'\"'\"'\"'\"'\"'\"'\"'s dir/cc_switch_agy_login_1.sh'\"'\"'' EXIT"));
+ let rc_pos = unix.find("_cc_switch_rc=$?").unwrap();
+ let prompt_pos = unix.find("Press Enter to close.").unwrap();
+ assert!(rc_pos < prompt_pos);
+ assert!(unix.contains("mv -f"));
+
+ let bat = build_running_windows_bat(
+ "agy",
+ "agy_login",
+ Some(Path::new(r"C:\Temp\exit%1.status")),
+ );
+ assert!(bat.contains("cd /d \"%USERPROFILE%\" 2>nul\r\n"));
+ let err_pos = bat.find("set \"_CC_SWITCH_RC=%ERRORLEVEL%\"").unwrap();
+ let bat_prompt_pos = bat.find("Press any key to close.").unwrap();
+ assert!(err_pos < bat_prompt_pos);
+ assert!(bat.contains(r#"move /y "C:\Temp\exit%%1.status.tmp" "C:\Temp\exit%%1.status""#));
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn running_unix_script_executes_cleanup_and_exit_file_recording() {
+ use std::io::Write;
+ use std::os::unix::fs::PermissionsExt;
+
+ let dir = tempfile::tempdir().unwrap();
+ let tricky = dir.path().join("it's dir");
+ std::fs::create_dir_all(&tricky).unwrap();
+ let script = tricky.join("run.sh");
+ let exit_file = tricky.join("exit.status");
+ let content =
+ build_running_unix_script(&script, "(exit 42)", "test_exit", Some(&exit_file));
+ std::fs::write(&script, content).unwrap();
+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
+
+ let mut child = std::process::Command::new("sh")
+ .arg(&script)
+ .stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ .unwrap();
+ child.stdin.take().unwrap().write_all(b"\n").unwrap();
+ assert!(child.wait().unwrap().success());
+ assert_eq!(std::fs::read_to_string(&exit_file).unwrap().trim(), "42");
+ assert!(!script.exists(), "EXIT trap should remove script");
+ }
+
#[test]
fn build_windows_cwd_command_str_handles_drive_unc_escaping_and_non_ascii() {
assert_eq!(
diff --git a/src-tauri/src/services/agy_account/mod.rs b/src-tauri/src/services/agy_account/mod.rs
index 088946252..19bed79a3 100644
--- a/src-tauri/src/services/agy_account/mod.rs
+++ b/src-tauri/src/services/agy_account/mod.rs
@@ -21,7 +21,7 @@ pub mod identity;
pub mod keychain;
use std::collections::{BTreeMap, HashMap};
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -158,6 +158,27 @@ pub struct LoginStart {
/// 桌面端模式:开始时钥匙串里就有一份没收录过的登录,第一次轮询会直接收录它,
/// 桌面端不需要再登录,也不用打开。
pub already_signed_in: bool,
+ /// 终端模式:终端里的 agy 退出后,启动脚本把退出码写到这里;轮询看到它就立刻结束这次登录,
+ /// 不用干等超时。桌面端模式不开终端,为 `None`。
+ pub exit_status_file: Option<PathBuf>,
+}
+
+/// 终端里 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);
+ }
}
/// 取消或超时且钥匙串仍为空时要写回的原登录。
@@ -173,6 +194,7 @@ struct PendingLogin {
baseline: Option<String>,
restore: Option<RestoreLogin>,
saw_logged_out: bool,
+ exit_status: Option<ExitStatusFile>,
deadline: Instant,
}
@@ -341,6 +363,8 @@ impl AgyAccountManager {
}
};
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(),
@@ -348,6 +372,7 @@ impl AgyAccountManager {
baseline,
restore,
saw_logged_out,
+ exit_status,
deadline: Instant::now() + LOGIN_TIMEOUT,
},
);
@@ -355,13 +380,27 @@ impl AgyAccountManager {
flow_id,
expires_in: LOGIN_TIMEOUT.as_secs(),
already_signed_in,
+ exit_status_file,
})
}
+ /// 「重新打开终端」:给进行中的终端登录换一个新的退出码文件并返回它。旧终端里的 agy 之后退出
+ /// 只会写旧文件,不会把这次登录判成失败。没有进行中的终端登录时返回 `None`。
+ pub async fn renew_login_exit_file(&self) -> Option<PathBuf> {
+ let mut pending = self.pending.lock().await;
+ let entry = pending
+ .values_mut()
+ .find(|entry| entry.exit_status.is_some() && Instant::now() < entry.deadline)?;
+ let file = ExitStatusFile::new();
+ let path = file.0.clone();
+ entry.exit_status = Some(file);
+ Some(path)
+ }
+
/// 钥匙串里还是开始时那份(或没登录)时返回 `Ok(None)`;换成认得出的登录(或观察到登出后
/// 重新登录同一账号,或开始时就有没收录过的登录)就收录、同步回退文件与 Desktop scope 并返回它。
pub async fn poll_login(&self, flow_id: &str) -> Result<Option<AgyAccount>, AppError> {
- let (baseline, saw_logged_out) = {
+ let (baseline, saw_logged_out, exit_status_file) = {
let mut pending = self.pending.lock().await;
let Some(entry) = pending.get(flow_id) else {
return Err(login_ended());
@@ -373,8 +412,36 @@ impl AgyAccountManager {
.await;
return Err(login_ended());
}
- (entry.baseline.clone(), entry.saw_logged_out)
+ (
+ entry.baseline.clone(),
+ entry.saw_logged_out,
+ entry.exit_status.as_ref().map(|file| file.0.clone()),
+ )
};
+ 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 {
@@ -493,7 +560,17 @@ impl AgyAccountManager {
}
/// 把 agy 的全局登录换成这个账号。已经是它且没有未完成的切换时什么都不写。
+ ///
+ /// 切成功后丢掉进行中的「添加账号」:钥匙串已经换成切过去的号,轮询会把它误当成新登录。
+ /// 开始加号时暂存的原登录已收进账号表(认不出的写进了 stash),钥匙串也不再是空的,丢掉不会
+ /// 弄丢登录。切换失败时不动,取消或超时仍能写回原登录。
pub async fn switch_to(&self, account_id: &str) -> Result<(), AppError> {
+ 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());
}
@@ -674,9 +751,13 @@ impl AgyAccountManager {
let Some(raw) = raw else {
return Ok((None, LiveLogin::None));
};
- let Some(credential) = keychain::decode(&raw)
- .ok()
- .filter(|credential| refresh_token_of(credential).is_some())
+ 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)));
};
@@ -832,6 +913,46 @@ fn refresh_token_of(credential: &Value) -> Option<&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
diff --git a/src-tauri/src/services/agy_account/tests.rs b/src-tauri/src/services/agy_account/tests.rs
index e133d2375..8948fc44a 100644
--- a/src-tauri/src/services/agy_account/tests.rs
+++ b/src-tauri/src/services/agy_account/tests.rs
@@ -718,6 +718,128 @@ mod switching {
assert!(status.accounts.is_empty());
}
+ #[tokio::test]
+ async fn read_live_treats_agy15_logged_out_metadata_as_none_without_stashing() {
+ let (dir, login, manager) = manager();
+ for metadata in [
+ json!({"writer_id": "w1", "auth_method": "consumer"}),
+ json!({"token": null, "writer_id": "w1"}),
+ json!({"token": {}, "id_token_email": "[email protected]"}),
+ ] {
+ set_live(&login, &metadata);
+ let status = manager.status().await.unwrap();
+ assert_eq!(status.current_account_id, None);
+ // 登出残留不算原登录:不暂存、不清钥匙串,取消也不写回
+ let start = manager.start_login().await.unwrap();
+ assert!(!dir.path().join(STASH_FILENAME).exists());
+ assert_eq!(*login.deletes.lock().unwrap(), 0);
+ assert!(manager.cancel_login(&start.flow_id).await);
+ assert_eq!(*login.writes.lock().unwrap(), 0);
+ }
+
+ // token 里带 access_token 但缺 refresh_token 仍视为认不出的格式并暂存
+ set_live(&login, &json!({"token": {"access_token": "only-access"}}));
+ let start = manager.start_login().await.unwrap();
+ assert!(dir.path().join(STASH_FILENAME).exists());
+ assert!(manager.cancel_login(&start.flow_id).await);
+ }
+
+ #[tokio::test]
+ async fn poll_login_ends_on_terminal_exit_and_restores_the_cleared_login() {
+ let (_dir, login, manager) = manager();
+ set_live(&login, &credential("alice", "a1"));
+
+ let start = manager.start_login().await.unwrap();
+ let exit_file = start
+ .exit_status_file
+ .clone()
+ .expect("终端模式带退出码文件");
+ assert!(manager.poll_login(&start.flow_id).await.unwrap().is_none());
+ // agy 异常退出:立刻结束,钥匙串还空着就写回原登录,文件随流程删掉
+ std::fs::write(&exit_file, "127\n").unwrap();
+ let err = manager.poll_login(&start.flow_id).await.unwrap_err();
+ assert!(matches!(
+ err,
+ AppError::Localized { key, .. } if key == "agy.account.login_command_failed"
+ ));
+ assert_eq!(live_sub(&login).as_deref(), Some("alice"));
+ assert!(!exit_file.exists());
+ assert!(manager.poll_login(&start.flow_id).await.is_err());
+
+ // 正常退出但没登录:同样立刻结束
+ let start = manager.start_login().await.unwrap();
+ let exit_file = start.exit_status_file.clone().unwrap();
+ std::fs::write(&exit_file, "0\n").unwrap();
+ let err = manager.poll_login(&start.flow_id).await.unwrap_err();
+ assert!(matches!(
+ err,
+ AppError::Localized { key, .. } if key == "agy.account.login_not_completed"
+ ));
+ assert!(!exit_file.exists());
+
+ // 登录完成后才退出:先看钥匙串,照常收录
+ let start = manager.start_login().await.unwrap();
+ let exit_file = start.exit_status_file.clone().unwrap();
+ set_live(&login, &credential("bob", "b1"));
+ std::fs::write(&exit_file, "0\n").unwrap();
+ let account = manager.poll_login(&start.flow_id).await.unwrap().unwrap();
+ assert_eq!(account.id, "bob");
+ assert!(!exit_file.exists());
+
+ // 取消也删文件
+ let start = manager.start_login().await.unwrap();
+ let exit_file = start.exit_status_file.clone().unwrap();
+ std::fs::write(&exit_file, "0\n").unwrap();
+ assert!(manager.cancel_login(&start.flow_id).await);
+ assert!(!exit_file.exists());
+ }
+
+ #[tokio::test]
+ async fn reopening_the_terminal_ignores_the_old_terminal_exit() {
+ let (_dir, login, manager) = manager();
+ set_live(&login, &credential("alice", "a1"));
+ let start = manager.start_login().await.unwrap();
+ let old = start.exit_status_file.clone().unwrap();
+
+ let renewed = manager.renew_login_exit_file().await.unwrap();
+ assert_ne!(renewed, old);
+ // 旧终端里的 agy 之后退出:只写旧文件,这次登录照常等待
+ std::fs::write(&old, "0\n").unwrap();
+ assert!(manager.poll_login(&start.flow_id).await.unwrap().is_none());
+ let _ = std::fs::remove_file(&old);
+ std::fs::write(&renewed, "1\n").unwrap();
+ assert!(manager.poll_login(&start.flow_id).await.is_err());
+ assert!(!renewed.exists());
+ }
+
+ #[tokio::test]
+ async fn desktop_login_has_no_exit_status_file() {
+ let (_dir, _login, manager) = manager();
+ let start = manager.start_login_desktop().await.unwrap();
+ assert!(start.exit_status_file.is_none());
+ assert!(manager.renew_login_exit_file().await.is_none());
+ }
+
+ #[tokio::test]
+ async fn switch_to_ends_the_pending_login_and_removes_its_exit_file() {
+ let (_dir, login, manager) = manager();
+ set_live(&login, &credential("alice", "a1"));
+ add(&manager, "bob").await;
+
+ let start = manager.start_login().await.unwrap();
+ let exit_file = start.exit_status_file.clone().unwrap();
+ std::fs::write(&exit_file, "0\n").unwrap();
+ // 等待中切号:钥匙串换成 bob,这次登录作废(否则轮询会把切过去的号当成新登录)
+ manager.switch_to("bob").await.unwrap();
+ assert_eq!(live_sub(&login).as_deref(), Some("bob"));
+ assert!(!exit_file.exists());
+ let err = manager.poll_login(&start.flow_id).await.unwrap_err();
+ assert!(matches!(
+ err,
+ AppError::Localized { key, .. } if key == "agy.account.login_expired"
+ ));
+ }
+
/// 真机钥匙串冒烟:读写一条测试专用的条目(不是 agy 那条),确认写入(macOS 经 `security -i`,
/// Windows 经凭据管理器)、原地更新、读回都正常。默认不跑:`cargo test agy_account -- --ignored`。
#[test]
diff --git a/src/components/providers/forms/hooks/useManagedAuth.ts b/src/components/providers/forms/hooks/useManagedAuth.ts
index e6f3d8bfb..e198e074e 100644
--- a/src/components/providers/forms/hooks/useManagedAuth.ts
+++ b/src/components/providers/forms/hooks/useManagedAuth.ts
@@ -370,6 +370,14 @@ export function useManagedAuth(
mutationFn: (accountId: string) =>
authApi.authRemoveAccount(authProvider, accountId),
onSuccess: async () => {
+ // 删号会结束进行中的登录:停掉轮询并通知后端取消,免得旧流程之后被当成完成
+ flowGenerationRef.current += 1;
+ const previousDeviceCode = activeDeviceCodeRef.current;
+ activeDeviceCodeRef.current = null;
+ stopPolling();
+ if (previousDeviceCode) {
+ void cancelBackendFlow(previousDeviceCode);
+ }
setPollingState("idle");
setDeviceCode(null);
setError(null);
diff --git a/src/components/settings/auth/ManagedAccountsGroup.tsx b/src/components/settings/auth/ManagedAccountsGroup.tsx
index a7faff563..45f281934 100644
--- a/src/components/settings/auth/ManagedAccountsGroup.tsx
+++ b/src/components/settings/auth/ManagedAccountsGroup.tsx
@@ -755,7 +755,7 @@ function AccountRow({
>
{canSetDefault && (
<DropdownMenuItem
- disabled={settingDefault}
+ disabled={settingDefault || busy}
onSelect={() => onSetDefault?.(account.id)}
className="h-[30px] rounded-control px-2.5 text-body"
>
diff --git a/tests/components/AgyOAuthSection.test.tsx b/tests/components/AgyOAuthSection.test.tsx
index 50eec0f95..012861a3d 100644
--- a/tests/components/AgyOAuthSection.test.tsx
+++ b/tests/components/AgyOAuthSection.test.tsx
@@ -414,4 +414,38 @@ describe("AgyOAuthSection", () => {
"已添加 Antigravity 账号。",
);
});
+
+ it("disables switching while a sign-in is in progress", async () => {
+ const auth = baseAuth();
+ auth.accounts = [
+ account("a", "[email protected]"),
+ account("b", "[email protected]"),
+ ];
+ auth.defaultAccountId = "a";
+ Object.assign(auth, {
+ isPolling: true,
+ isAddingAccount: true,
+ pollingState: "polling",
+ deviceCode: {
+ provider: "agy_oauth",
+ device_code: "flow",
+ user_code: "",
+ verification_uri: "",
+ expires_in: 600,
+ interval: 2,
+ },
+ });
+ mocks.useManagedAuth.mockReturnValue(auth);
+ renderSection();
+
+ // 等待登录时切号会改写钥匙串,被当成这次登录的结果:菜单项禁用
+ await userEvent.click(
+ screen.getByRole("button", { name: "[email protected] 的更多操作" }),
+ );
+ expect(
+ await screen.findByRole("menuitem", {
+ name: "切换 Antigravity 到这个账号",
+ }),
+ ).toHaveAttribute("aria-disabled", "true");
+ });
});
diff --git a/tests/hooks/useManagedAuth.test.tsx b/tests/hooks/useManagedAuth.test.tsx
index 9cf10da0c..882128313 100644
--- a/tests/hooks/useManagedAuth.test.tsx
+++ b/tests/hooks/useManagedAuth.test.tsx
@@ -480,6 +480,35 @@ describe("useManagedAuth", () => {
expect(result.current.pollingState).toBe("idle");
});
+ it("stops polling and cancels the backend flow when an account is removed mid-login", async () => {
+ apiMocks.authStartLogin.mockResolvedValue({
+ provider: "agy_oauth",
+ device_code: "flow-remove",
+ user_code: "",
+ verification_uri: "",
+ expires_in: 600,
+ interval: 2,
+ });
+ apiMocks.authPollForAccount.mockImplementation(() => new Promise(() => {}));
+ apiMocks.authRemoveAccount.mockResolvedValue(undefined);
+ apiMocks.authCancelLogin.mockResolvedValue(true);
+ const { result } = renderHook(() => useManagedAuth("agy_oauth"), {
+ wrapper: createWrapper(),
+ });
+ act(() => result.current.addAccount());
+ await waitFor(() => expect(result.current.isPolling).toBe(true));
+
+ act(() => result.current.removeAccount("a"));
+
+ await waitFor(() =>
+ expect(apiMocks.authCancelLogin).toHaveBeenCalledWith(
+ "agy_oauth",
+ "flow-remove",
+ ),
+ );
+ await waitFor(() => expect(result.current.isPolling).toBe(false));
+ });
+
it("refreshes status when login committed before cancellation", async () => {
let resolvePoll!: (account: object) => void;
let resolveCancel!: (cancelled: boolean) => void;