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): report Windows terminal exit and window close via named pipe (#10167)

funkpopo64c9fb44ada6
diff --git a/src-tauri/src/commands/agy_account.rs b/src-tauri/src/commands/agy_account.rs
index d7a1fc9db..81e512527 100644
--- a/src-tauri/src/commands/agy_account.rs
+++ b/src-tauri/src/commands/agy_account.rs
@@ -283,9 +283,9 @@ pub(crate) async fn open_agy_login_terminal(exit_file: Option<PathBuf>) -> Resul
/// .bat 里的命令要交给 cmd 按 PATH 解析,残留的启动器脚本(如被卸载 CLI 留下的
/// `agy.cmd`)会把客户端文件重新下载回来;没定位到 `agy.exe` 时直接报错,不开必死终端。
/// cmd 分支给路径多包一层双引号,用户名带 `&`、`(`、`)` 等字符(agy 安装目录随之带上)
-/// 也能跑。macOS/Linux 仍走启动脚本——探测只认真正的可执行文件,脚本只负责跑它;`exit_file`
-/// 给了时脚本在 agy 退出后把退出码写进去,轮询看到就结束等待。Windows 不经脚本,拿不到
-/// 退出码,仍等登录或超时。两边都带上全局代理。
+/// 也能跑;同时经本地命名管道把 `agy.exe` 退出码或用户直接关窗写回 `exit_file`。
+/// macOS/Linux 仍走启动脚本——探测只认真正的可执行文件,脚本只负责跑它;`exit_file`
+/// 给了时脚本在 agy 退出后把退出码写进去,轮询看到就结束等待。两边都带上全局代理。
pub(crate) async fn open_terminal_with_bin(
bin: Option<PathBuf>,
exit_file: Option<PathBuf>,
@@ -303,23 +303,18 @@ pub(crate) async fn open_terminal_with_bin(
)
.to_string());
};
- // Windows 不经脚本,没有地方写退出码
- let _ = exit_file;
+ if let Some(path) = exit_file.as_deref() {
+ let _ = std::fs::remove_file(path);
+ }
// 清掉旧凭据环境变量,保证 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"],
- )
- })
+ crate::commands::terminal_launch::launch_terminal_command_with_exit_file(
+ bin,
+ Vec::new(),
+ proxy_vars,
+ &["GEMINI_API_KEY", "GOOGLE_GEMINI_BASE_URL"],
+ exit_file,
+ )
.await
- .map_err(|e| format!("launch task join error: {e}"))?
}
#[cfg(not(target_os = "windows"))]
{
diff --git a/src-tauri/src/commands/terminal_launch.rs b/src-tauri/src/commands/terminal_launch.rs
index ab7c21418..aded1773d 100644
--- a/src-tauri/src/commands/terminal_launch.rs
+++ b/src-tauri/src/commands/terminal_launch.rs
@@ -1904,6 +1904,125 @@ fn run_terminal_command(
#[cfg(target_os = "windows")]
const CMD_TERMINAL_PROGRAM_VAR: &str = "CC_SWITCH_TERMINAL_PROGRAM";
+#[cfg(target_os = "windows")]
+const WINDOWS_EXIT_PIPE_PREFIX: &str = "cc-switch-terminal-exit-";
+#[cfg(target_os = "windows")]
+const WINDOWS_EXIT_PIPE_CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
+/// 略长于 `agy_account::LOGIN_TIMEOUT`(10 分钟),避免超时后才关窗留下迟到的退出码文件。
+#[cfg(target_os = "windows")]
+const WINDOWS_EXIT_PIPE_WATCH_TIMEOUT: std::time::Duration =
+ std::time::Duration::from_secs(11 * 60);
+
+#[cfg(target_os = "windows")]
+struct WindowsExitPipe {
+ pipe_name: String,
+ server: tokio::net::windows::named_pipe::NamedPipeServer,
+ exit_file: PathBuf,
+}
+
+#[cfg(target_os = "windows")]
+impl WindowsExitPipe {
+ fn bind(exit_file: PathBuf) -> std::io::Result<Self> {
+ let pipe_name = format!("{WINDOWS_EXIT_PIPE_PREFIX}{}", uuid::Uuid::new_v4());
+ let pipe_path = format!(r"\\.\pipe\{pipe_name}");
+ let server = tokio::net::windows::named_pipe::ServerOptions::new()
+ .first_pipe_instance(true)
+ .max_instances(1)
+ .access_inbound(true)
+ .access_outbound(false)
+ .reject_remote_clients(true)
+ .create(&pipe_path)?;
+ Ok(Self {
+ pipe_name,
+ server,
+ exit_file,
+ })
+ }
+
+ fn pipe_name(&self) -> &str {
+ &self.pipe_name
+ }
+
+ fn spawn_watcher(self) {
+ tokio::spawn(watch_windows_exit_pipe(
+ self.server,
+ self.exit_file,
+ WINDOWS_EXIT_PIPE_CONNECT_TIMEOUT,
+ WINDOWS_EXIT_PIPE_WATCH_TIMEOUT,
+ ));
+ }
+}
+
+#[cfg(target_os = "windows")]
+async fn watch_windows_exit_pipe(
+ server: tokio::net::windows::named_pipe::NamedPipeServer,
+ exit_file: PathBuf,
+ connect_timeout: std::time::Duration,
+ watch_timeout: std::time::Duration,
+) {
+ match tokio::time::timeout(connect_timeout, server.connect()).await {
+ Ok(Ok(())) => {}
+ Ok(Err(err)) => {
+ log::debug!("[TerminalLaunch] 退出码管道等待连接失败: {err}");
+ return;
+ }
+ Err(_) => {
+ log::debug!("[TerminalLaunch] 退出码管道等待连接超时,放弃本次监听");
+ return;
+ }
+ }
+ let status = match tokio::time::timeout(watch_timeout, read_pipe_exit_line(&server)).await {
+ Ok(Some(code)) => format!("{code}\n"),
+ Ok(None) => "closed\n".to_string(),
+ Err(_) => return,
+ };
+ let _ = tokio::task::spawn_blocking(move || write_exit_status_file(&exit_file, &status)).await;
+}
+
+#[cfg(target_os = "windows")]
+async fn read_pipe_exit_line(
+ server: &tokio::net::windows::named_pipe::NamedPipeServer,
+) -> Option<String> {
+ let mut buf = Vec::new();
+ let mut chunk = [0u8; 64];
+ loop {
+ if server.readable().await.is_err() {
+ break;
+ }
+ match server.try_read(&mut chunk) {
+ Ok(0) => break,
+ Ok(n) => {
+ buf.extend_from_slice(&chunk[..n]);
+ if buf.contains(&b'\n') || buf.len() >= 128 {
+ break;
+ }
+ }
+ Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => continue,
+ Err(_) => break,
+ }
+ }
+ let text = String::from_utf8_lossy(&buf);
+ let first = text.lines().next().map(str::trim).unwrap_or("");
+ if first.is_empty() {
+ None
+ } else {
+ Some(first.to_string())
+ }
+}
+
+#[cfg(target_os = "windows")]
+fn write_exit_status_file(path: &Path, status: &str) {
+ let tmp = PathBuf::from(format!("{}.tmp", path.to_string_lossy()));
+ if std::fs::write(&tmp, status).is_ok() {
+ if std::fs::rename(&tmp, path).is_err() {
+ let _ = std::fs::remove_file(&tmp);
+ let _ = std::fs::write(path, status);
+ }
+ } else {
+ let _ = std::fs::write(path, status);
+ }
+}
+
/// 把要经外层 `cmd /C start ...` 透传给内层命令的文本做 `^` 转义,避免外层 `cmd`
/// 提前展开 `%...%`、切开 `& | < > ( )` 或把 `""` 拆成空引号串。
#[cfg(target_os = "windows")]
@@ -1928,30 +2047,41 @@ fn escape_outer_cmd_raw_arg(s: &str) -> String {
/// 剥掉首尾各一个引号、保留中间的。所以把 `"%VAR%" [args...]` 再包一层双引号,
/// 内层 `cmd /K` 剥完外层双引号后剩下的正是带引号的 `%VAR%` 与参数;内层展开
/// `%VAR%` 后不会再按 `& | ( ) ^ %` 解析。
+///
+/// 传了 `exit_pipe_name` 时在整组命令外挂 `9>\\.\pipe\<name>`,程序退出后经
+/// `(call echo ^%ERRORLEVEL^%)>&9` 把退出码送回监听线程(括起 `call echo ...` 避免
+/// 单个数字的退出码如 `1` 与 `>&9` 相邻被 `cmd` 解析成句柄重定向),用户直接关窗
+/// 则由命名管道 EOF 通知。
#[cfg(target_os = "windows")]
-fn format_cmd_k_raw_arg(args: &[&str]) -> String {
- let mut inner = format!("\"%{CMD_TERMINAL_PROGRAM_VAR}%\"");
+fn format_cmd_k_raw_arg(args: &[&str], exit_pipe_name: Option<&str>) -> String {
+ let mut invoke = format!("\"%{CMD_TERMINAL_PROGRAM_VAR}%\"");
for arg in args {
- inner.push(' ');
+ invoke.push(' ');
if arg.is_empty()
|| arg.chars().any(|c| {
c.is_whitespace()
|| matches!(c, '"' | '&' | '|' | '<' | '>' | '(' | ')' | '^' | '%')
})
{
- inner.push('"');
+ invoke.push('"');
for ch in arg.chars() {
if ch == '"' {
- inner.push_str("\\\"");
+ invoke.push_str("\\\"");
} else {
- inner.push(ch);
+ invoke.push(ch);
}
}
- inner.push('"');
+ invoke.push('"');
} else {
- inner.push_str(arg);
+ invoke.push_str(arg);
}
}
+ let inner = match exit_pipe_name {
+ Some(pipe_name) => {
+ format!("({invoke} & (call echo ^%ERRORLEVEL^%)>&9) 9>\\\\.\\pipe\\{pipe_name}")
+ }
+ None => invoke,
+ };
escape_outer_cmd_raw_arg(&format!("\"{inner}\""))
}
@@ -1962,19 +2092,24 @@ fn format_cmd_k_raw_arg(args: &[&str]) -> String {
/// **Security**:`program_str` 与 `args` 会原样交给终端执行,调用方必须保证内容可信
/// (当前只由后端用已探测的二进制路径调用)。
#[cfg(target_os = "windows")]
-fn cmd_terminal_command(program_str: &str, args: &[&str]) -> std::process::Command {
+fn cmd_terminal_command(
+ program_str: &str,
+ args: &[&str],
+ exit_pipe_name: Option<&str>,
+) -> std::process::Command {
let mut command = windows_start_command(&["cmd", "/K"], &[], &effective_path_string());
command
- .raw_arg(format_cmd_k_raw_arg(args))
+ .raw_arg(format_cmd_k_raw_arg(args, exit_pipe_name))
.env(CMD_TERMINAL_PROGRAM_VAR, program_str);
command
}
#[cfg(target_os = "windows")]
-fn powershell_terminal_command(program_str: &str, args: &[&str]) -> std::process::Command {
+fn format_powershell_terminal_command(args: &[&str], exit_pipe_name: Option<&str>) -> String {
// 路径经环境变量传入,避免外层 `cmd /C start` 提前展开路径里的 `%...%`;
// PowerShell 直接执行 `& $env:CC_SWITCH_TERMINAL_PROGRAM`,空格与特殊字符都安全。
- let ps_cmd = if args.is_empty() {
+ // 命令串内不能出现双引号或 `%`,否则经 `cmd /C start` 透传会被截断或展开。
+ let invoke = if args.is_empty() {
format!("& $env:{CMD_TERMINAL_PROGRAM_VAR}")
} else {
let ps_args: Vec<String> = args
@@ -1983,6 +2118,25 @@ fn powershell_terminal_command(program_str: &str, args: &[&str]) -> std::process
.collect();
format!("& $env:{CMD_TERMINAL_PROGRAM_VAR} {}", ps_args.join(" "))
};
+ match exit_pipe_name {
+ Some(pipe_name) => format!(
+ "$__p = [System.IO.Pipes.NamedPipeClientStream]::new('.', '{pipe_name}', [System.IO.Pipes.PipeDirection]::Out); \
+ try {{ $__p.Connect(5000); $__w = [System.IO.StreamWriter]::new($__p) }} catch {{ $__w = $null }}; \
+ $__rc = 1; \
+ try {{ $global:LASTEXITCODE = $null; {invoke}; $__rc = if ($null -ne $LASTEXITCODE) {{ $LASTEXITCODE }} elseif ($?) {{ 0 }} else {{ 1 }} }} \
+ finally {{ if ($__w) {{ try {{ $__w.WriteLine($__rc); $__w.Flush() }} catch {{}}; $__w.Dispose() }}; $__p.Dispose() }}"
+ ),
+ None => invoke,
+ }
+}
+
+#[cfg(target_os = "windows")]
+fn powershell_terminal_command(
+ program_str: &str,
+ args: &[&str],
+ exit_pipe_name: Option<&str>,
+) -> std::process::Command {
+ let ps_cmd = format_powershell_terminal_command(args, exit_pipe_name);
windows_start_command(
&[
windows_powershell_program(&effective_path_string()),
@@ -1996,15 +2150,37 @@ fn powershell_terminal_command(program_str: &str, args: &[&str]) -> std::process
}
#[cfg(target_os = "windows")]
-fn wt_terminal_command(program_str: &str, args: &[&str]) -> std::process::Command {
+fn wt_terminal_command(
+ program_str: &str,
+ args: &[&str],
+ exit_pipe_name: Option<&str>,
+) -> std::process::Command {
// 旧版 Windows Terminal 不一定继承自定义环境变量,路径仍经命令行传入:
- // 前置 `call` 避免 `cmd /K` 剥掉引号;有空白时 wt 会自动给参数加引号,无空白时
- // wt 不加引号,因此先给内层 `cmd` 的特殊字符加 `^` 转义,再整体转义给外层 `cmd`。
+ // 前置 `call`(无退出管道时)或在括号内直接执行(有退出管道时)避免 `cmd /K` 剥掉引号;
+ // 有空白时 wt 会自动给参数加引号,无空白时 wt 不加引号,因此先给内层 `cmd` 的特殊字符
+ // 加 `^` 转义,再整体转义给外层 `cmd`。
let inner_arg = if program_str.chars().any(char::is_whitespace) {
format!("\"{program_str}\"")
} else {
escape_outer_cmd_raw_arg(program_str)
};
+ if let Some(pipe_name) = exit_pipe_name {
+ let mut command =
+ windows_start_command(&["wt", "cmd", "/K"], &[], &effective_path_string());
+ command
+ .raw_arg(escape_outer_cmd_raw_arg("("))
+ .raw_arg(escape_outer_cmd_raw_arg(&inner_arg))
+ .args(args.iter().copied())
+ .raw_arg(escape_outer_cmd_raw_arg("&"))
+ .raw_arg(escape_outer_cmd_raw_arg("(call"))
+ .arg("echo")
+ .raw_arg(escape_outer_cmd_raw_arg("^%ERRORLEVEL^%)>&9"))
+ .raw_arg(escape_outer_cmd_raw_arg(")"))
+ .raw_arg(escape_outer_cmd_raw_arg(&format!(
+ "9>\\\\.\\pipe\\{pipe_name}"
+ )));
+ return command;
+ }
let mut command =
windows_start_command(&["wt", "cmd", "/K", "call"], &[], &effective_path_string());
command
@@ -2024,11 +2200,12 @@ fn wt_terminal_command(program_str: &str, args: &[&str]) -> std::process::Comman
/// **Security**:`program` 与 `args` 会原样交给终端执行,调用方必须保证内容可信
/// (当前只由后端用已探测的二进制路径调用)。
#[cfg(target_os = "windows")]
-pub(crate) fn launch_terminal_command(
+fn launch_windows_terminal_command(
program: &Path,
args: &[&str],
envs: &[(&str, &str)],
env_removals: &[&str],
+ exit_pipe_name: Option<&str>,
) -> Result<(), String> {
let program_str = program.to_string_lossy().to_string();
let preferred = crate::settings::get_preferred_terminal();
@@ -2040,15 +2217,15 @@ pub(crate) fn launch_terminal_command(
let result = match terminal {
"powershell" => {
- let command = powershell_terminal_command(&program_str, args);
+ let command = powershell_terminal_command(&program_str, args, exit_pipe_name);
run(command, "PowerShell")
}
"wt" => {
- let command = wt_terminal_command(&program_str, args);
+ let command = wt_terminal_command(&program_str, args, exit_pipe_name);
run(command, "Windows Terminal")
}
_ => {
- let command = cmd_terminal_command(&program_str, args);
+ let command = cmd_terminal_command(&program_str, args, exit_pipe_name);
run(command, "cmd")
}
};
@@ -2058,12 +2235,53 @@ pub(crate) fn launch_terminal_command(
"首选终端 {terminal} 启动失败,回退到 cmd: {:?}",
result.as_ref().err()
);
- let command = cmd_terminal_command(&program_str, args);
+ let command = cmd_terminal_command(&program_str, args, exit_pipe_name);
return run(command, "cmd");
}
result
}
+/// 在 Windows 首选终端里直接执行程序,并经本地命名管道监听程序退出码或终端关闭,
+/// 结果写回 `exit_file`(不落临时 `.bat`)。
+#[cfg(target_os = "windows")]
+pub(crate) async fn launch_terminal_command_with_exit_file(
+ program: PathBuf,
+ args: Vec<String>,
+ envs: Vec<(&'static str, String)>,
+ env_removals: &'static [&'static str],
+ exit_file: Option<PathBuf>,
+) -> Result<(), String> {
+ let pipe = exit_file.and_then(|path| match WindowsExitPipe::bind(path) {
+ Ok(pipe) => Some(pipe),
+ Err(err) => {
+ log::warn!("[TerminalLaunch] 创建退出码命名管道失败,改为仅等待登录完成: {err}");
+ None
+ }
+ });
+ let pipe_name = pipe.as_ref().map(|p| p.pipe_name().to_string());
+
+ let result = tokio::task::spawn_blocking(move || {
+ let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
+ let env_refs: Vec<(&str, &str)> = envs.iter().map(|(k, v)| (*k, v.as_str())).collect();
+ launch_windows_terminal_command(
+ &program,
+ &arg_refs,
+ &env_refs,
+ env_removals,
+ pipe_name.as_deref(),
+ )
+ })
+ .await
+ .map_err(|e| format!("launch task join error: {e}"))?;
+
+ if result.is_ok() {
+ if let Some(pipe) = pipe {
+ pipe.spawn_watcher();
+ }
+ }
+ result
+}
+
/// 首选终端为 PowerShell 时启动哪个程序。`powershell` 永远是系统自带的 Windows
/// PowerShell 5.1;装了 PowerShell 7+ 的用户默认用的是 `pwsh`,所以补全后的 PATH 里
/// 有 `pwsh.exe` 就用它,没有才退回 `powershell`。Microsoft Store 版的 `pwsh.exe` 是
@@ -2153,7 +2371,7 @@ pub(crate) fn launch_terminal_running(command_line: &str, label: &str) -> Result
launch_terminal_with_script(command_line, label, None, &proxy_env)
}
-/// 只有 agy 登录在用,且 Windows 下 agy 不经脚本启动(见 `agy_account.rs`),所以只在非 Windows 编译。
+/// 只有非 Windows 平台的 agy 登录在用;Windows 下 agy 不经脚本启动,走 [`launch_terminal_command_with_exit_file`]。
#[cfg(not(target_os = "windows"))]
pub(crate) fn launch_terminal_running_with_exit_file(
command_line: &str,
@@ -2376,13 +2594,13 @@ mod tests {
// 被 cmd 剥引号切开(#10067 的同类问题)。路径必须多包一层双引号、经 `^` 转义后由
// raw_arg 原样拼进命令行,并经环境变量传给终端,外层与内层 `cmd` 都不会提前展开 `%`。
let program = r"C:\Users\Name With (Space) & 100% ^caret!\agy.exe";
- let command = cmd_terminal_command(program, &["--model", "a & b"]);
+ let command = cmd_terminal_command(program, &["--model", "a & b"], None);
let args: Vec<String> = command
.get_args()
.map(|a| a.to_string_lossy().to_string())
.collect();
- let expected_raw = format_cmd_k_raw_arg(&["--model", "a & b"]);
+ let expected_raw = format_cmd_k_raw_arg(&["--model", "a & b"], None);
let placeholder_index = args
.iter()
.position(|a| a == &expected_raw)
@@ -2429,7 +2647,7 @@ mod tests {
cmd.args([
"/D", "/V:OFF", "/C", "start", "/B", "/WAIT", "cmd", "/D", "/V:OFF", "/C",
])
- .raw_arg(format_cmd_k_raw_arg(extra_args))
+ .raw_arg(format_cmd_k_raw_arg(extra_args, None))
.env(CMD_TERMINAL_PROGRAM_VAR, &script)
.current_dir(std::env::var_os("SystemRoot").unwrap());
let output = cmd.output().unwrap();
@@ -2449,7 +2667,7 @@ mod tests {
#[test]
fn powershell_terminal_command_runs_programs_under_special_char_paths() {
let program = r"C:\Users\Name (With) & %PATH% 'quote' ^caret!\agy.exe";
- let command = powershell_terminal_command(program, &["--arg", "a'b"]);
+ let command = powershell_terminal_command(program, &["--arg", "a'b"], None);
let args: Vec<String> = command
.get_args()
.map(|a| a.to_string_lossy().to_string())
@@ -2503,7 +2721,7 @@ mod tests {
#[test]
fn wt_terminal_command_escapes_special_char_paths() {
let with_space = r"C:\Users\Name (With) & 100% ^caret!\agy.exe";
- let cmd_space = wt_terminal_command(with_space, &[]);
+ let cmd_space = wt_terminal_command(with_space, &[], None);
let args_space: Vec<String> = cmd_space
.get_args()
.map(|a| a.to_string_lossy().to_string())
@@ -2522,7 +2740,7 @@ mod tests {
);
let no_space = r"C:\Users\a&b(c)%d@^!\agy.exe";
- let cmd_nospace = wt_terminal_command(no_space, &[]);
+ let cmd_nospace = wt_terminal_command(no_space, &[], None);
let args_nospace: Vec<String> = cmd_nospace
.get_args()
.map(|a| a.to_string_lossy().to_string())
@@ -2541,6 +2759,199 @@ mod tests {
);
}
+ #[cfg(target_os = "windows")]
+ #[tokio::test]
+ async fn windows_exit_pipe_captures_cmd_exit_codes_under_special_char_paths() {
+ let root = tempfile::tempdir().unwrap();
+ let dir = root.path().join("张三 (With) & 100% %PATH% ^caret @ !");
+ std::fs::create_dir_all(&dir).unwrap();
+ let hostname_exe = PathBuf::from(std::env::var_os("SystemRoot").unwrap())
+ .join("System32")
+ .join("hostname.exe");
+ let target_exe = dir.join("agy_like.exe");
+ std::fs::copy(&hostname_exe, &target_exe).unwrap();
+ let system_cmd = PathBuf::from(std::env::var_os("SystemRoot").unwrap())
+ .join("System32")
+ .join("cmd.exe");
+
+ let cases: Vec<(PathBuf, Vec<&str>, &str)> = vec![
+ (target_exe, Vec::new(), "0"),
+ // 单数字退出码 `1`:防止 `(call echo ...)` 外层缺少括号时 `1>&9` 被 cmd 误解析成句柄重定向
+ (system_cmd.clone(), vec!["/c", "exit", "1"], "1"),
+ (system_cmd, vec!["/c", "exit", "42"], "42"),
+ ];
+
+ for (index, (program, args, expected_code)) in cases.into_iter().enumerate() {
+ let exit_file = dir.join(format!("exit_{index}.status"));
+ let pipe = WindowsExitPipe::bind(exit_file.clone()).unwrap();
+ let raw_arg = format_cmd_k_raw_arg(&args, Some(pipe.pipe_name()));
+ let handle = tokio::spawn(watch_windows_exit_pipe(
+ pipe.server,
+ pipe.exit_file,
+ std::time::Duration::from_secs(10),
+ std::time::Duration::from_secs(10),
+ ));
+
+ let output = tokio::task::spawn_blocking(move || {
+ std::process::Command::new("cmd")
+ .args([
+ "/D", "/V:OFF", "/C", "start", "/B", "/WAIT", "cmd", "/D", "/V:OFF", "/C",
+ ])
+ .raw_arg(raw_arg)
+ .env(CMD_TERMINAL_PROGRAM_VAR, &program)
+ .current_dir(std::env::var_os("SystemRoot").unwrap())
+ .output()
+ .unwrap()
+ })
+ .await
+ .unwrap();
+ assert!(output.status.success(), "case={index}: {output:?}");
+
+ handle.await.unwrap();
+ assert_eq!(
+ std::fs::read_to_string(&exit_file).unwrap().trim(),
+ expected_code,
+ "case={index}"
+ );
+ }
+ }
+
+ #[cfg(target_os = "windows")]
+ #[tokio::test]
+ async fn windows_exit_pipe_captures_powershell_exit_code() {
+ let root = tempfile::tempdir().unwrap();
+ let exit_file = root.path().join("ps_exit.status");
+ let pipe = WindowsExitPipe::bind(exit_file.clone()).unwrap();
+ let ps_cmd = format_powershell_terminal_command(&["/c", "exit 42"], Some(pipe.pipe_name()));
+ assert!(!ps_cmd.contains('"') && !ps_cmd.contains('%'));
+
+ let handle = tokio::spawn(watch_windows_exit_pipe(
+ pipe.server,
+ pipe.exit_file,
+ std::time::Duration::from_secs(10),
+ std::time::Duration::from_secs(10),
+ ));
+
+ let system_cmd = PathBuf::from(std::env::var_os("SystemRoot").unwrap())
+ .join("System32")
+ .join("cmd.exe");
+ let ps_program = windows_powershell_program(&effective_path_string());
+ let output = tokio::task::spawn_blocking(move || {
+ std::process::Command::new("cmd")
+ .args([
+ "/D",
+ "/V:OFF",
+ "/C",
+ "start",
+ "/B",
+ "/WAIT",
+ ps_program,
+ "-NoProfile",
+ "-Command",
+ &ps_cmd,
+ ])
+ .env(CMD_TERMINAL_PROGRAM_VAR, &system_cmd)
+ .output()
+ .unwrap()
+ })
+ .await
+ .unwrap();
+ assert!(output.status.success(), "{output:?}");
+
+ handle.await.unwrap();
+ assert_eq!(std::fs::read_to_string(&exit_file).unwrap().trim(), "42");
+ }
+
+ #[cfg(target_os = "windows")]
+ #[tokio::test]
+ async fn windows_exit_pipe_writes_closed_on_eof_and_ignores_connect_timeout() {
+ let root = tempfile::tempdir().unwrap();
+
+ // A. 终端窗口被直接关掉(管道连上后未写退出码即 EOF)-> 写入 `closed`
+ let closed_exit_file = root.path().join("closed.status");
+ let pipe = WindowsExitPipe::bind(closed_exit_file.clone()).unwrap();
+ let pipe_path = format!(r"\\.\pipe\{}", pipe.pipe_name());
+ let handle = tokio::spawn(watch_windows_exit_pipe(
+ pipe.server,
+ pipe.exit_file,
+ std::time::Duration::from_secs(5),
+ std::time::Duration::from_secs(5),
+ ));
+ let client = tokio::net::windows::named_pipe::ClientOptions::new()
+ .read(false)
+ .write(true)
+ .open(&pipe_path)
+ .unwrap();
+ drop(client);
+ handle.await.unwrap();
+ assert_eq!(
+ std::fs::read_to_string(&closed_exit_file).unwrap().trim(),
+ "closed"
+ );
+
+ // B. 管道一直无人连接直至超时 -> 绝不误写 exit_file(免得误杀正在进行的登录)
+ let timeout_exit_file = root.path().join("timeout.status");
+ let timeout_pipe = WindowsExitPipe::bind(timeout_exit_file.clone()).unwrap();
+ watch_windows_exit_pipe(
+ timeout_pipe.server,
+ timeout_pipe.exit_file,
+ std::time::Duration::from_millis(50),
+ std::time::Duration::from_secs(1),
+ )
+ .await;
+ assert!(!timeout_exit_file.exists());
+ }
+
+ #[cfg(target_os = "windows")]
+ #[test]
+ fn wt_terminal_command_with_exit_pipe_escapes_special_char_paths() {
+ let pipe_name = "cc-switch-test";
+ let expected_tail = vec![
+ escape_outer_cmd_raw_arg("&"),
+ escape_outer_cmd_raw_arg("(call"),
+ "echo".to_string(),
+ escape_outer_cmd_raw_arg("^%ERRORLEVEL^%)>&9"),
+ escape_outer_cmd_raw_arg(")"),
+ escape_outer_cmd_raw_arg(&format!("9>\\\\.\\pipe\\{pipe_name}")),
+ ];
+
+ let with_space = r"C:\Users\Name (With) & 100% ^caret!\agy.exe";
+ let cmd_space = wt_terminal_command(with_space, &[], Some(pipe_name));
+ let args_space: Vec<String> = cmd_space
+ .get_args()
+ .map(|a| a.to_string_lossy().to_string())
+ .collect();
+ let mut expected_space = vec![
+ "/C".to_string(),
+ "start".to_string(),
+ "wt".to_string(),
+ "cmd".to_string(),
+ "/K".to_string(),
+ escape_outer_cmd_raw_arg("("),
+ escape_outer_cmd_raw_arg(&format!("\"{with_space}\"")),
+ ];
+ expected_space.extend(expected_tail.clone());
+ assert_eq!(args_space, expected_space);
+
+ let no_space = r"C:\Users\a&b(c)%d@^!\agy.exe";
+ let cmd_nospace = wt_terminal_command(no_space, &[], Some(pipe_name));
+ let args_nospace: Vec<String> = cmd_nospace
+ .get_args()
+ .map(|a| a.to_string_lossy().to_string())
+ .collect();
+ let mut expected_nospace = vec![
+ "/C".to_string(),
+ "start".to_string(),
+ "wt".to_string(),
+ "cmd".to_string(),
+ "/K".to_string(),
+ escape_outer_cmd_raw_arg("("),
+ escape_outer_cmd_raw_arg(&escape_outer_cmd_raw_arg(no_space)),
+ ];
+ expected_nospace.extend(expected_tail);
+ assert_eq!(args_nospace, expected_nospace);
+ }
+
#[test]
fn unix_shell_command_and_exec_builders() {
let claude = format!(
diff --git a/src-tauri/src/services/agy_account/tests.rs b/src-tauri/src/services/agy_account/tests.rs
index 393acc0f3..50bf8124d 100644
--- a/src-tauri/src/services/agy_account/tests.rs
+++ b/src-tauri/src/services/agy_account/tests.rs
@@ -858,6 +858,19 @@ mod switching {
err,
AppError::Localized { key, .. } if key == "agy.account.login_not_completed"
));
+ assert_eq!(live_sub(&login).as_deref(), Some("alice"));
+ assert!(!exit_file.exists());
+
+ // Windows 终端直接点 X 关闭(管道 EOF 写入 `closed`):同样立刻结束并恢复原登录
+ let start = manager.start_login().await.unwrap();
+ let exit_file = start.exit_status_file.clone().unwrap();
+ std::fs::write(&exit_file, "closed\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_eq!(live_sub(&login).as_deref(), Some("alice"));
assert!(!exit_file.exists());
// 登录完成后才退出:先看钥匙串,照常收录