| 1 | use std::path::{Path, PathBuf}; |
| 2 | |
| 3 | use crate::action::AgentAction; |
| 4 | use crate::profile::{AgentProfile, Environment}; |
| 5 | use crate::template::{UnknownPlaceholder, Values, placeholders_in, render, split_command}; |
| 6 | |
| 7 | const WSL_PROGRAM: &str = "wsl.exe"; |
| 8 | const SESSION_FLAG: &str = "--session-id {session_id}"; |
| 9 | const RESUME_FLAG: &str = "--resume {session_id}"; |
| 10 | const WSL_SCRIPT: &str = r#"case "$1" in "~"*) dir="$HOME${1#\~}";; *) dir="$1";; esac; cd "$dir" && shift && exec "$@""#; |
| 11 | |
| 12 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 13 | pub struct Invocation { |
| 14 | pub program: String, |
| 15 | pub args: Vec<String>, |
| 16 | pub cwd: Option<PathBuf>, |
| 17 | pub stdin: Option<String>, |
| 18 | } |
| 19 | |
| 20 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 21 | pub struct McpEndpoint { |
| 22 | pub url: String, |
| 23 | pub token: String, |
| 24 | } |
| 25 | |
| 26 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 27 | pub struct RunPlan { |
| 28 | pub run: Invocation, |
| 29 | pub stop: Option<Invocation>, |
| 30 | pub cleanup: Vec<PathBuf>, |
| 31 | } |
| 32 | |
| 33 | #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] |
| 34 | pub enum InvocationError { |
| 35 | #[error("the command is empty")] |
| 36 | EmptyCommand, |
| 37 | #[error(transparent)] |
| 38 | UnknownPlaceholder(#[from] UnknownPlaceholder), |
| 39 | #[error("cannot write the MCP config: {0}")] |
| 40 | McpConfig(String), |
| 41 | #[error("the agent command has no \"{SESSION_FLAG}\" to resume with")] |
| 42 | CannotResume, |
| 43 | } |
| 44 | |
| 45 | fn expand_home(path: &str) -> String { |
| 46 | let remainder = match path.strip_prefix('~') { |
| 47 | Some(remainder) if remainder.is_empty() || remainder.starts_with(['/', '\\']) => remainder, |
| 48 | _ => return path.to_string(), |
| 49 | }; |
| 50 | match std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")) { |
| 51 | Ok(home) => format!("{home}{remainder}"), |
| 52 | Err(_) => path.to_string(), |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | fn mcp_config_json(endpoint: &McpEndpoint) -> String { |
| 57 | serde_json::json!({ |
| 58 | "mcpServers": { |
| 59 | "teams": { |
| 60 | "type": "http", |
| 61 | "url": endpoint.url, |
| 62 | "headers": {"Authorization": format!("Bearer {}", endpoint.token)}, |
| 63 | } |
| 64 | } |
| 65 | }) |
| 66 | .to_string() |
| 67 | } |
| 68 | |
| 69 | pub fn wsl_path(path: &str) -> String { |
| 70 | let mut characters = path.chars(); |
| 71 | match (characters.next(), characters.next(), characters.next()) { |
| 72 | (Some(drive), Some(':'), Some('/' | '\\')) if drive.is_ascii_alphabetic() => format!( |
| 73 | "/mnt/{}/{}", |
| 74 | drive.to_ascii_lowercase(), |
| 75 | path[3..].replace('\\', "/") |
| 76 | ), |
| 77 | _ => path.to_string(), |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | fn write_mcp_config( |
| 82 | directory: &Path, |
| 83 | session_id: &str, |
| 84 | endpoint: &McpEndpoint, |
| 85 | ) -> Result<PathBuf, InvocationError> { |
| 86 | let to_error = |error: std::io::Error| InvocationError::McpConfig(error.to_string()); |
| 87 | std::fs::create_dir_all(directory).map_err(to_error)?; |
| 88 | let path = directory.join(format!("mcp-{session_id}.json")); |
| 89 | let mut options = std::fs::OpenOptions::new(); |
| 90 | options.write(true).create(true).truncate(true); |
| 91 | #[cfg(unix)] |
| 92 | std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); |
| 93 | let mut file = options.open(&path).map_err(to_error)?; |
| 94 | std::io::Write::write_all(&mut file, mcp_config_json(endpoint).as_bytes()).map_err(to_error)?; |
| 95 | Ok(path) |
| 96 | } |
| 97 | |
| 98 | fn mcp_config_argument(flag: &str, path: &Path, environment: &Environment) -> String { |
| 99 | let text = path.to_string_lossy(); |
| 100 | let text = match environment { |
| 101 | Environment::Wsl { .. } if cfg!(windows) => wsl_path(&text), |
| 102 | _ => text.into_owned(), |
| 103 | }; |
| 104 | if flag.ends_with("additional-mcp-config") { |
| 105 | format!("@{text}") |
| 106 | } else { |
| 107 | text |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | fn wsl_prefix(environment: &Environment) -> Vec<String> { |
| 112 | match environment { |
| 113 | Environment::Wsl { |
| 114 | distro: Some(distro), |
| 115 | } => vec!["-d".to_string(), distro.clone()], |
| 116 | _ => Vec::new(), |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | fn working_directory(profile: &AgentProfile, action: &AgentAction) -> String { |
| 121 | match profile.environment { |
| 122 | Environment::Host => expand_home(&action.working_dir), |
| 123 | Environment::Wsl { .. } => action.working_dir.clone(), |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | pub fn build_invocation( |
| 128 | profile: &AgentProfile, |
| 129 | action: &AgentAction, |
| 130 | prompt: &str, |
| 131 | session_id: &str, |
| 132 | mcp: Option<&McpEndpoint>, |
| 133 | mcp_config_directory: Option<&Path>, |
| 134 | ) -> Result<RunPlan, InvocationError> { |
| 135 | let working_dir = working_directory(profile, action); |
| 136 | let values = Values { |
| 137 | session_id: session_id.to_string(), |
| 138 | agent: profile.id.clone(), |
| 139 | prompt: prompt.to_string(), |
| 140 | cwd: working_dir.clone(), |
| 141 | ..Values::default() |
| 142 | }; |
| 143 | let raw_tokens: Vec<String> = split_command(&profile.command) |
| 144 | .into_iter() |
| 145 | .chain(split_command(&action.extra_args)) |
| 146 | .collect(); |
| 147 | if raw_tokens.is_empty() { |
| 148 | return Err(InvocationError::EmptyCommand); |
| 149 | } |
| 150 | let uses_prompt_placeholder = raw_tokens |
| 151 | .iter() |
| 152 | .any(|token| placeholders_in(token).iter().any(|name| name == "prompt")); |
| 153 | let mut tokens = raw_tokens |
| 154 | .iter() |
| 155 | .map(|token| render(token, &values)) |
| 156 | .collect::<Result<Vec<_>, _>>()?; |
| 157 | let mut cleanup = Vec::new(); |
| 158 | if let Some(endpoint) = mcp |
| 159 | && let Some(directory) = mcp_config_directory |
| 160 | && !profile.mcp_config_flag.is_empty() |
| 161 | { |
| 162 | let path = write_mcp_config(directory, session_id, endpoint)?; |
| 163 | tokens.push(profile.mcp_config_flag.clone()); |
| 164 | tokens.push(mcp_config_argument( |
| 165 | &profile.mcp_config_flag, |
| 166 | &path, |
| 167 | &profile.environment, |
| 168 | )); |
| 169 | cleanup.push(path); |
| 170 | } |
| 171 | let stdin = (!uses_prompt_placeholder).then(|| prompt.to_string()); |
| 172 | |
| 173 | match &profile.environment { |
| 174 | Environment::Host => { |
| 175 | let mut tokens = tokens.into_iter(); |
| 176 | let program = tokens.next().ok_or(InvocationError::EmptyCommand)?; |
| 177 | Ok(RunPlan { |
| 178 | run: Invocation { |
| 179 | program, |
| 180 | args: tokens.collect(), |
| 181 | cwd: Some(PathBuf::from(working_dir)), |
| 182 | stdin, |
| 183 | }, |
| 184 | stop: None, |
| 185 | cleanup, |
| 186 | }) |
| 187 | } |
| 188 | Environment::Wsl { .. } => { |
| 189 | let mut args = wsl_prefix(&profile.environment); |
| 190 | let mut stop_args = args.clone(); |
| 191 | args.extend( |
| 192 | ["-e", "sh", "-lc", WSL_SCRIPT, "sh"] |
| 193 | .into_iter() |
| 194 | .map(String::from), |
| 195 | ); |
| 196 | args.push(working_dir); |
| 197 | args.extend(tokens); |
| 198 | stop_args.extend(["-e", "pkill", "-f", session_id].map(String::from)); |
| 199 | Ok(RunPlan { |
| 200 | run: Invocation { |
| 201 | program: WSL_PROGRAM.to_string(), |
| 202 | args, |
| 203 | cwd: None, |
| 204 | stdin, |
| 205 | }, |
| 206 | stop: Some(Invocation { |
| 207 | program: WSL_PROGRAM.to_string(), |
| 208 | args: stop_args, |
| 209 | cwd: None, |
| 210 | stdin: None, |
| 211 | }), |
| 212 | cleanup, |
| 213 | }) |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | fn is_plain_session_id(session_id: &str) -> bool { |
| 219 | !session_id.is_empty() |
| 220 | && session_id |
| 221 | .chars() |
| 222 | .all(|character| character.is_ascii_alphanumeric() || character == '-') |
| 223 | } |
| 224 | |
| 225 | pub fn kill_process_invocation(process_id: u32, session_id: &str) -> Option<Invocation> { |
| 226 | if !is_plain_session_id(session_id) { |
| 227 | return None; |
| 228 | } |
| 229 | if cfg!(windows) { |
| 230 | let script = format!( |
| 231 | "$p = Get-CimInstance Win32_Process -Filter 'ProcessId={process_id}'; if ($p -and $p.CommandLine -like '*{session_id}*') {{ taskkill /PID {process_id} /T /F }}" |
| 232 | ); |
| 233 | return Some(Invocation { |
| 234 | program: "powershell".to_string(), |
| 235 | args: ["-NoProfile", "-Command", &script] |
| 236 | .map(String::from) |
| 237 | .to_vec(), |
| 238 | cwd: None, |
| 239 | stdin: None, |
| 240 | }); |
| 241 | } |
| 242 | Some(Invocation { |
| 243 | program: "sh".to_string(), |
| 244 | args: [ |
| 245 | "-c", |
| 246 | r#"grep -qaF -- "$2" "/proc/$1/cmdline" && kill -9 "$1""#, |
| 247 | "sh", |
| 248 | &process_id.to_string(), |
| 249 | session_id, |
| 250 | ] |
| 251 | .map(String::from) |
| 252 | .to_vec(), |
| 253 | cwd: None, |
| 254 | stdin: None, |
| 255 | }) |
| 256 | } |
| 257 | |
| 258 | pub fn supports_resume(profile: &AgentProfile) -> bool { |
| 259 | profile.command.contains(SESSION_FLAG) |
| 260 | } |
| 261 | |
| 262 | pub fn resume_invocation( |
| 263 | profile: &AgentProfile, |
| 264 | action: &AgentAction, |
| 265 | prompt: &str, |
| 266 | session_id: &str, |
| 267 | mcp: Option<&McpEndpoint>, |
| 268 | mcp_config_directory: Option<&Path>, |
| 269 | ) -> Result<RunPlan, InvocationError> { |
| 270 | if !supports_resume(profile) { |
| 271 | return Err(InvocationError::CannotResume); |
| 272 | } |
| 273 | let resuming_profile = AgentProfile { |
| 274 | command: profile.command.replace(SESSION_FLAG, RESUME_FLAG), |
| 275 | ..profile.clone() |
| 276 | }; |
| 277 | build_invocation( |
| 278 | &resuming_profile, |
| 279 | action, |
| 280 | prompt, |
| 281 | session_id, |
| 282 | mcp, |
| 283 | mcp_config_directory, |
| 284 | ) |
| 285 | } |
| 286 | |
| 287 | pub fn open_session_invocation( |
| 288 | profile: &AgentProfile, |
| 289 | action: &AgentAction, |
| 290 | session_id: &str, |
| 291 | ) -> Result<Invocation, InvocationError> { |
| 292 | let values = Values { |
| 293 | session_id: session_id.to_string(), |
| 294 | agent: profile.id.clone(), |
| 295 | cwd: working_directory(profile, action), |
| 296 | ..Values::default() |
| 297 | }; |
| 298 | let mut tokens = split_command(&profile.open_session_command) |
| 299 | .iter() |
| 300 | .map(|token| render(token, &values)) |
| 301 | .collect::<Result<Vec<_>, _>>()? |
| 302 | .into_iter(); |
| 303 | let program = tokens.next().ok_or(InvocationError::EmptyCommand)?; |
| 304 | Ok(Invocation { |
| 305 | program, |
| 306 | args: tokens.collect(), |
| 307 | cwd: None, |
| 308 | stdin: None, |
| 309 | }) |
| 310 | } |
| 311 | |
| 312 | pub fn version_check_invocation(profile: &AgentProfile) -> Invocation { |
| 313 | let program = split_command(&profile.command) |
| 314 | .into_iter() |
| 315 | .next() |
| 316 | .unwrap_or_default(); |
| 317 | match &profile.environment { |
| 318 | Environment::Host => Invocation { |
| 319 | program, |
| 320 | args: vec!["--version".to_string()], |
| 321 | cwd: None, |
| 322 | stdin: None, |
| 323 | }, |
| 324 | Environment::Wsl { .. } => { |
| 325 | let mut args = wsl_prefix(&profile.environment); |
| 326 | args.extend( |
| 327 | ["-e", "sh", "-lc", WSL_SCRIPT, "sh", "~"] |
| 328 | .into_iter() |
| 329 | .map(String::from), |
| 330 | ); |
| 331 | args.push(program); |
| 332 | args.push("--version".to_string()); |
| 333 | Invocation { |
| 334 | program: WSL_PROGRAM.to_string(), |
| 335 | args, |
| 336 | cwd: None, |
| 337 | stdin: None, |
| 338 | } |
| 339 | } |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | #[cfg(test)] |
| 344 | mod tests { |
| 345 | use super::*; |
| 346 | |
| 347 | #[test] |
| 348 | fn wsl_invocation_has_exact_args() { |
| 349 | let mut profile = AgentProfile::claude_wsl(); |
| 350 | profile.environment = Environment::Wsl { |
| 351 | distro: Some("Ubuntu".to_string()), |
| 352 | }; |
| 353 | let action = AgentAction::answer_this("claude"); |
| 354 | let plan = build_invocation(&profile, &action, "hi there", "sid-1", None, None).unwrap(); |
| 355 | let expected_args: Vec<String> = [ |
| 356 | "-d", |
| 357 | "Ubuntu", |
| 358 | "-e", |
| 359 | "sh", |
| 360 | "-lc", |
| 361 | WSL_SCRIPT, |
| 362 | "sh", |
| 363 | "~", |
| 364 | "claude", |
| 365 | "-p", |
| 366 | "--output-format", |
| 367 | "stream-json", |
| 368 | "--verbose", |
| 369 | "--session-id", |
| 370 | "sid-1", |
| 371 | "--allowedTools", |
| 372 | "WebSearch,WebFetch,Read,Grep,Glob,mcp__teams", |
| 373 | ] |
| 374 | .map(String::from) |
| 375 | .to_vec(); |
| 376 | assert_eq!(plan.run.program, "wsl.exe"); |
| 377 | assert_eq!(plan.run.args, expected_args); |
| 378 | assert_eq!(plan.run.cwd, None); |
| 379 | assert_eq!(plan.run.stdin.as_deref(), Some("hi there")); |
| 380 | let stop = plan.stop.unwrap(); |
| 381 | assert_eq!(stop.program, "wsl.exe"); |
| 382 | assert_eq!( |
| 383 | stop.args, |
| 384 | ["-d", "Ubuntu", "-e", "pkill", "-f", "sid-1"].map(String::from) |
| 385 | ); |
| 386 | } |
| 387 | |
| 388 | #[test] |
| 389 | fn prompt_placeholder_goes_in_args_without_stdin() { |
| 390 | let profile = AgentProfile::copilot_wsl(); |
| 391 | let action = AgentAction::answer_this("copilot"); |
| 392 | let plan = build_invocation(&profile, &action, "a b\nc", "sid-2", None, None).unwrap(); |
| 393 | assert_eq!(plan.run.stdin, None); |
| 394 | assert_eq!(plan.run.args[..2], ["-e".to_string(), "sh".to_string()]); |
| 395 | let prompt_position = plan.run.args.iter().position(|arg| arg == "-p").unwrap() + 1; |
| 396 | assert_eq!(plan.run.args[prompt_position], "a b\nc"); |
| 397 | } |
| 398 | |
| 399 | #[test] |
| 400 | fn host_invocation_expands_home() { |
| 401 | let mut action = AgentAction::build_this("claude-host"); |
| 402 | action.working_dir = "~/work".to_string(); |
| 403 | let plan = build_invocation( |
| 404 | &AgentProfile::claude_host(), |
| 405 | &action, |
| 406 | "p", |
| 407 | "sid-3", |
| 408 | None, |
| 409 | None, |
| 410 | ) |
| 411 | .unwrap(); |
| 412 | let home = std::env::var("HOME") |
| 413 | .or_else(|_| std::env::var("USERPROFILE")) |
| 414 | .unwrap(); |
| 415 | assert_eq!(plan.run.program, "claude"); |
| 416 | assert_eq!(plan.run.cwd, Some(PathBuf::from(format!("{home}/work")))); |
| 417 | assert_eq!(plan.run.stdin.as_deref(), Some("p")); |
| 418 | assert!( |
| 419 | plan.run |
| 420 | .args |
| 421 | .ends_with(&["--permission-mode".to_string(), "auto".to_string()]) |
| 422 | ); |
| 423 | assert_eq!(plan.stop, None); |
| 424 | } |
| 425 | |
| 426 | fn endpoint() -> McpEndpoint { |
| 427 | McpEndpoint { |
| 428 | url: "http://127.0.0.1:9/mcp".to_string(), |
| 429 | token: "tok".to_string(), |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | #[test] |
| 434 | fn mcp_endpoint_writes_a_config_file_and_passes_its_path() { |
| 435 | let directory = tempfile::tempdir().unwrap(); |
| 436 | let action = AgentAction::answer_this("claude"); |
| 437 | let plan = build_invocation( |
| 438 | &AgentProfile::claude_host(), |
| 439 | &action, |
| 440 | "p", |
| 441 | "sid", |
| 442 | Some(&endpoint()), |
| 443 | Some(directory.path()), |
| 444 | ) |
| 445 | .unwrap(); |
| 446 | let flag_position = plan |
| 447 | .run |
| 448 | .args |
| 449 | .iter() |
| 450 | .position(|arg| arg == "--mcp-config") |
| 451 | .unwrap(); |
| 452 | let expected_path = directory.path().join("mcp-sid.json"); |
| 453 | assert_eq!( |
| 454 | plan.run.args[flag_position + 1], |
| 455 | expected_path.to_string_lossy() |
| 456 | ); |
| 457 | assert_eq!(plan.cleanup, vec![expected_path.clone()]); |
| 458 | assert!(!plan.run.args.iter().any(|arg| arg.contains("tok"))); |
| 459 | let json: serde_json::Value = |
| 460 | serde_json::from_str(&std::fs::read_to_string(&expected_path).unwrap()).unwrap(); |
| 461 | let server = &json["mcpServers"]["teams"]; |
| 462 | assert_eq!(server["type"], "http"); |
| 463 | assert_eq!(server["url"], "http://127.0.0.1:9/mcp"); |
| 464 | assert_eq!(server["headers"]["Authorization"], "Bearer tok"); |
| 465 | #[cfg(unix)] |
| 466 | assert_eq!( |
| 467 | std::os::unix::fs::PermissionsExt::mode( |
| 468 | &std::fs::metadata(&expected_path).unwrap().permissions() |
| 469 | ) & 0o777, |
| 470 | 0o600 |
| 471 | ); |
| 472 | } |
| 473 | |
| 474 | #[test] |
| 475 | fn mcp_flag_is_omitted_without_endpoint_or_directory() { |
| 476 | let directory = tempfile::tempdir().unwrap(); |
| 477 | let action = AgentAction::answer_this("claude"); |
| 478 | let profile = AgentProfile::claude_host(); |
| 479 | let without_endpoint = |
| 480 | build_invocation(&profile, &action, "p", "sid", None, Some(directory.path())).unwrap(); |
| 481 | assert!( |
| 482 | !without_endpoint |
| 483 | .run |
| 484 | .args |
| 485 | .iter() |
| 486 | .any(|arg| arg == "--mcp-config") |
| 487 | ); |
| 488 | let without_directory = |
| 489 | build_invocation(&profile, &action, "p", "sid", Some(&endpoint()), None).unwrap(); |
| 490 | assert!( |
| 491 | !without_directory |
| 492 | .run |
| 493 | .args |
| 494 | .iter() |
| 495 | .any(|arg| arg == "--mcp-config") |
| 496 | ); |
| 497 | assert!(without_directory.cleanup.is_empty()); |
| 498 | } |
| 499 | |
| 500 | #[test] |
| 501 | fn copilot_takes_the_config_path_with_an_at_prefix() { |
| 502 | let directory = tempfile::tempdir().unwrap(); |
| 503 | let action = AgentAction::answer_this("copilot"); |
| 504 | let plan = build_invocation( |
| 505 | &AgentProfile::copilot_wsl(), |
| 506 | &action, |
| 507 | "p", |
| 508 | "sid", |
| 509 | Some(&endpoint()), |
| 510 | Some(directory.path()), |
| 511 | ) |
| 512 | .unwrap(); |
| 513 | let flag_position = plan |
| 514 | .run |
| 515 | .args |
| 516 | .iter() |
| 517 | .position(|arg| arg == "--additional-mcp-config") |
| 518 | .unwrap(); |
| 519 | assert_eq!( |
| 520 | plan.run.args[flag_position + 1], |
| 521 | format!( |
| 522 | "@{}", |
| 523 | directory.path().join("mcp-sid.json").to_string_lossy() |
| 524 | ) |
| 525 | ); |
| 526 | } |
| 527 | |
| 528 | #[test] |
| 529 | fn windows_paths_translate_to_the_wsl_mount() { |
| 530 | assert_eq!( |
| 531 | wsl_path(r"C:\Users\x\AppData\mcp-1.json"), |
| 532 | "/mnt/c/Users/x/AppData/mcp-1.json" |
| 533 | ); |
| 534 | assert_eq!(wsl_path("D:/data/mcp.json"), "/mnt/d/data/mcp.json"); |
| 535 | assert_eq!(wsl_path("/tmp/mcp.json"), "/tmp/mcp.json"); |
| 536 | assert_eq!(wsl_path("relative/mcp.json"), "relative/mcp.json"); |
| 537 | } |
| 538 | |
| 539 | #[test] |
| 540 | fn agent_placeholder_renders_profile_id() { |
| 541 | let mut profile = AgentProfile::claude_host(); |
| 542 | profile.command = "tool --agent {agent}".to_string(); |
| 543 | let mut action = AgentAction::build_this("x"); |
| 544 | action.extra_args = String::new(); |
| 545 | let plan = build_invocation(&profile, &action, "p", "s", None, None).unwrap(); |
| 546 | assert_eq!(plan.run.args, ["--agent", "claude-host"].map(String::from)); |
| 547 | } |
| 548 | |
| 549 | #[test] |
| 550 | fn empty_command_is_an_error() { |
| 551 | let mut profile = AgentProfile::claude_host(); |
| 552 | profile.command = String::new(); |
| 553 | let mut action = AgentAction::build_this("x"); |
| 554 | action.extra_args = String::new(); |
| 555 | assert_eq!( |
| 556 | build_invocation(&profile, &action, "p", "s", None, None), |
| 557 | Err(InvocationError::EmptyCommand) |
| 558 | ); |
| 559 | } |
| 560 | |
| 561 | #[test] |
| 562 | fn open_session_renders_cwd_and_session() { |
| 563 | let action = AgentAction::build_this("claude"); |
| 564 | let invocation = |
| 565 | open_session_invocation(&AgentProfile::claude_wsl(), &action, "sid-4").unwrap(); |
| 566 | assert_eq!(invocation.program, "wt.exe"); |
| 567 | assert_eq!( |
| 568 | invocation.args, |
| 569 | [ |
| 570 | "wsl.exe", |
| 571 | "--cd", |
| 572 | "~", |
| 573 | "-e", |
| 574 | "sh", |
| 575 | "-lc", |
| 576 | "exec claude --resume sid-4" |
| 577 | ] |
| 578 | .map(String::from) |
| 579 | ); |
| 580 | } |
| 581 | |
| 582 | #[test] |
| 583 | fn version_check_runs_the_first_token_in_the_same_environment() { |
| 584 | let host = version_check_invocation(&AgentProfile::claude_host()); |
| 585 | assert_eq!(host.program, "claude"); |
| 586 | assert_eq!(host.args, ["--version"].map(String::from)); |
| 587 | let mut wsl_profile = AgentProfile::claude_wsl(); |
| 588 | wsl_profile.environment = Environment::Wsl { |
| 589 | distro: Some("Ubuntu".to_string()), |
| 590 | }; |
| 591 | let wsl = version_check_invocation(&wsl_profile); |
| 592 | assert_eq!(wsl.program, "wsl.exe"); |
| 593 | assert_eq!( |
| 594 | wsl.args, |
| 595 | [ |
| 596 | "-d", |
| 597 | "Ubuntu", |
| 598 | "-e", |
| 599 | "sh", |
| 600 | "-lc", |
| 601 | WSL_SCRIPT, |
| 602 | "sh", |
| 603 | "~", |
| 604 | "claude", |
| 605 | "--version" |
| 606 | ] |
| 607 | .map(String::from) |
| 608 | ); |
| 609 | } |
| 610 | |
| 611 | #[test] |
| 612 | fn resume_swaps_the_session_flag_and_keeps_the_extra_args() { |
| 613 | let mut profile = AgentProfile::claude_wsl(); |
| 614 | profile.environment = Environment::Wsl { |
| 615 | distro: Some("Ubuntu".to_string()), |
| 616 | }; |
| 617 | let action = AgentAction::answer_this("claude"); |
| 618 | let plan = resume_invocation(&profile, &action, "go on", "sid-9", None, None).unwrap(); |
| 619 | let expected_args: Vec<String> = [ |
| 620 | "-d", |
| 621 | "Ubuntu", |
| 622 | "-e", |
| 623 | "sh", |
| 624 | "-lc", |
| 625 | WSL_SCRIPT, |
| 626 | "sh", |
| 627 | "~", |
| 628 | "claude", |
| 629 | "-p", |
| 630 | "--output-format", |
| 631 | "stream-json", |
| 632 | "--verbose", |
| 633 | "--resume", |
| 634 | "sid-9", |
| 635 | "--allowedTools", |
| 636 | "WebSearch,WebFetch,Read,Grep,Glob,mcp__teams", |
| 637 | ] |
| 638 | .map(String::from) |
| 639 | .to_vec(); |
| 640 | assert_eq!(plan.run.args, expected_args); |
| 641 | assert_eq!(plan.run.stdin.as_deref(), Some("go on")); |
| 642 | assert_eq!( |
| 643 | plan.stop.unwrap().args, |
| 644 | ["-d", "Ubuntu", "-e", "pkill", "-f", "sid-9"].map(String::from) |
| 645 | ); |
| 646 | } |
| 647 | |
| 648 | #[test] |
| 649 | fn resume_on_the_host_keeps_the_permission_mode() { |
| 650 | let action = AgentAction::build_this("claude-host"); |
| 651 | let plan = resume_invocation( |
| 652 | &AgentProfile::claude_host(), |
| 653 | &action, |
| 654 | "go on", |
| 655 | "sid-8", |
| 656 | None, |
| 657 | None, |
| 658 | ) |
| 659 | .unwrap(); |
| 660 | assert_eq!(plan.run.program, "claude"); |
| 661 | assert!(!plan.run.args.contains(&"--session-id".to_string())); |
| 662 | assert!( |
| 663 | plan.run |
| 664 | .args |
| 665 | .windows(2) |
| 666 | .any(|pair| pair == ["--resume", "sid-8"]) |
| 667 | ); |
| 668 | assert!( |
| 669 | plan.run |
| 670 | .args |
| 671 | .ends_with(&["--permission-mode".to_string(), "auto".to_string()]) |
| 672 | ); |
| 673 | assert_eq!(plan.stop, None); |
| 674 | } |
| 675 | |
| 676 | #[test] |
| 677 | fn copilot_resumes_with_the_prompt_in_its_args() { |
| 678 | let action = AgentAction::answer_this("copilot"); |
| 679 | let plan = resume_invocation( |
| 680 | &AgentProfile::copilot_wsl(), |
| 681 | &action, |
| 682 | "go on", |
| 683 | "sid-7", |
| 684 | None, |
| 685 | None, |
| 686 | ) |
| 687 | .unwrap(); |
| 688 | assert_eq!(plan.run.stdin, None); |
| 689 | assert!( |
| 690 | plan.run |
| 691 | .args |
| 692 | .windows(2) |
| 693 | .any(|pair| pair == ["--resume", "sid-7"]) |
| 694 | ); |
| 695 | assert!(plan.run.args.contains(&"go on".to_string())); |
| 696 | } |
| 697 | |
| 698 | #[test] |
| 699 | fn kill_refuses_a_session_id_that_is_not_plain() { |
| 700 | assert_eq!(kill_process_invocation(1, ""), None); |
| 701 | assert_eq!(kill_process_invocation(1, "a'; rm -rf /; '"), None); |
| 702 | assert_eq!(kill_process_invocation(1, "a b"), None); |
| 703 | } |
| 704 | |
| 705 | #[cfg(windows)] |
| 706 | #[test] |
| 707 | fn kill_checks_the_command_line_before_taskkill() { |
| 708 | let invocation = kill_process_invocation(4242, "abc-123").unwrap(); |
| 709 | assert_eq!(invocation.program, "powershell"); |
| 710 | assert_eq!( |
| 711 | invocation.args[..2], |
| 712 | ["-NoProfile", "-Command"].map(String::from) |
| 713 | ); |
| 714 | let script = &invocation.args[2]; |
| 715 | assert!(script.contains("ProcessId=4242")); |
| 716 | assert!(script.contains("-like '*abc-123*'")); |
| 717 | assert!(script.contains("taskkill /PID 4242 /T /F")); |
| 718 | } |
| 719 | |
| 720 | #[cfg(unix)] |
| 721 | mod unix_kill { |
| 722 | use super::super::*; |
| 723 | |
| 724 | fn spawn_sleeper(label: &str) -> std::process::Child { |
| 725 | std::process::Command::new("sh") |
| 726 | .args(["-c", "sleep 30", label]) |
| 727 | .spawn() |
| 728 | .unwrap() |
| 729 | } |
| 730 | |
| 731 | fn run_kill(process_id: u32, session_id: &str) { |
| 732 | let invocation = kill_process_invocation(process_id, session_id).unwrap(); |
| 733 | std::process::Command::new(invocation.program) |
| 734 | .args(invocation.args) |
| 735 | .status() |
| 736 | .unwrap(); |
| 737 | } |
| 738 | |
| 739 | #[test] |
| 740 | fn kills_a_process_whose_command_line_has_the_session_id() { |
| 741 | let mut child = spawn_sleeper("fake-session-1"); |
| 742 | run_kill(child.id(), "fake-session-1"); |
| 743 | let status = child.wait().unwrap(); |
| 744 | assert!(!status.success()); |
| 745 | } |
| 746 | |
| 747 | #[test] |
| 748 | fn leaves_a_process_without_the_session_id_alone() { |
| 749 | let mut child = spawn_sleeper("other-session"); |
| 750 | run_kill(child.id(), "fake-session-2"); |
| 751 | assert!(child.try_wait().unwrap().is_none()); |
| 752 | child.kill().unwrap(); |
| 753 | child.wait().unwrap(); |
| 754 | } |
| 755 | } |
| 756 | |
| 757 | #[test] |
| 758 | fn a_command_without_the_session_flag_cannot_resume() { |
| 759 | let mut profile = AgentProfile::claude_host(); |
| 760 | profile.command = "tool -p".to_string(); |
| 761 | let action = AgentAction::build_this("claude-host"); |
| 762 | assert!(!supports_resume(&profile)); |
| 763 | assert_eq!( |
| 764 | resume_invocation(&profile, &action, "go on", "sid", None, None), |
| 765 | Err(InvocationError::CannotResume) |
| 766 | ); |
| 767 | } |
| 768 | } |