| 1 | #![cfg(unix)] |
| 2 | |
| 3 | use std::time::{Duration, Instant}; |
| 4 | |
| 5 | use agents::{Invocation, OutputFormat, RunEvent, RunPlan, RunStatus, RunUpdate, probe, run}; |
| 6 | use tokio::sync::{mpsc, oneshot}; |
| 7 | |
| 8 | fn plan(program: &str, args: &[&str], stdin: Option<&str>) -> RunPlan { |
| 9 | RunPlan { |
| 10 | run: Invocation { |
| 11 | program: program.to_string(), |
| 12 | args: args.iter().map(|arg| arg.to_string()).collect(), |
| 13 | cwd: Some("/".into()), |
| 14 | stdin: stdin.map(str::to_string), |
| 15 | }, |
| 16 | stop: None, |
| 17 | cleanup: Vec::new(), |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | #[tokio::test] |
| 22 | async fn completes_with_claude_final_text() { |
| 23 | let fixture = format!( |
| 24 | "{}/tests/fixtures/claude-stream.jsonl", |
| 25 | env!("CARGO_MANIFEST_DIR") |
| 26 | ); |
| 27 | let (sender, mut receiver) = mpsc::unbounded_channel(); |
| 28 | let (_keep_alive, stop) = oneshot::channel(); |
| 29 | let outcome = run( |
| 30 | plan("sh", &["-c", &format!("cat '{fixture}'")], Some("prompt")), |
| 31 | OutputFormat::ClaudeStreamJson, |
| 32 | sender, |
| 33 | stop, |
| 34 | ) |
| 35 | .await; |
| 36 | assert_eq!( |
| 37 | outcome.status, |
| 38 | RunStatus::Completed { |
| 39 | final_text: "The first word in `/etc/hostname` is `HOST01`.".to_string() |
| 40 | } |
| 41 | ); |
| 42 | assert_eq!(outcome.exit_code, Some(0)); |
| 43 | let mut saw_step = false; |
| 44 | while let Ok(update) = receiver.try_recv() { |
| 45 | if update == RunUpdate::Event(RunEvent::Step("Reading hostname".to_string())) { |
| 46 | saw_step = true; |
| 47 | } |
| 48 | } |
| 49 | assert!(saw_step); |
| 50 | } |
| 51 | |
| 52 | #[tokio::test] |
| 53 | async fn failing_command_reports_stderr() { |
| 54 | let (sender, mut receiver) = mpsc::unbounded_channel(); |
| 55 | let (_keep_alive, stop) = oneshot::channel(); |
| 56 | let outcome = run( |
| 57 | plan("sh", &["-c", "echo boom >&2; exit 3"], None), |
| 58 | OutputFormat::ClaudeStreamJson, |
| 59 | sender, |
| 60 | stop, |
| 61 | ) |
| 62 | .await; |
| 63 | assert_eq!(outcome.exit_code, Some(3)); |
| 64 | match outcome.status { |
| 65 | RunStatus::Failed { |
| 66 | message, |
| 67 | stderr_tail, |
| 68 | } => { |
| 69 | assert_eq!(message, "boom"); |
| 70 | assert_eq!(stderr_tail, vec!["boom".to_string()]); |
| 71 | } |
| 72 | other => panic!("unexpected status {other:?}"), |
| 73 | } |
| 74 | let updates: Vec<RunUpdate> = std::iter::from_fn(|| receiver.try_recv().ok()).collect(); |
| 75 | assert!(updates.contains(&RunUpdate::Stderr("boom".to_string()))); |
| 76 | } |
| 77 | |
| 78 | #[tokio::test] |
| 79 | async fn missing_program_fails_readably() { |
| 80 | let (sender, _receiver) = mpsc::unbounded_channel(); |
| 81 | let (_keep_alive, stop) = oneshot::channel(); |
| 82 | let outcome = run( |
| 83 | plan("definitely-not-a-real-program", &[], None), |
| 84 | OutputFormat::Text, |
| 85 | sender, |
| 86 | stop, |
| 87 | ) |
| 88 | .await; |
| 89 | assert!(matches!( |
| 90 | outcome.status, |
| 91 | RunStatus::Failed { message, .. } if message.contains("cannot start definitely-not-a-real-program") |
| 92 | )); |
| 93 | } |
| 94 | |
| 95 | #[tokio::test] |
| 96 | async fn stop_kills_the_process() { |
| 97 | let (sender, _receiver) = mpsc::unbounded_channel(); |
| 98 | let (stop_sender, stop) = oneshot::channel(); |
| 99 | let started = Instant::now(); |
| 100 | let handle = tokio::spawn(run( |
| 101 | plan("sh", &["-c", "sleep 30"], None), |
| 102 | OutputFormat::Text, |
| 103 | sender, |
| 104 | stop, |
| 105 | )); |
| 106 | tokio::time::sleep(Duration::from_millis(200)).await; |
| 107 | stop_sender.send(()).unwrap(); |
| 108 | let outcome = handle.await.unwrap(); |
| 109 | assert_eq!(outcome.status, RunStatus::Stopped); |
| 110 | assert!(started.elapsed() < Duration::from_secs(2)); |
| 111 | } |
| 112 | |
| 113 | #[tokio::test] |
| 114 | async fn probe_returns_the_first_output_line() { |
| 115 | let invocation = Invocation { |
| 116 | program: "sh".to_string(), |
| 117 | args: ["-c", "echo '2.1.290 (Claude Code)'; echo more"] |
| 118 | .map(String::from) |
| 119 | .to_vec(), |
| 120 | cwd: None, |
| 121 | stdin: None, |
| 122 | }; |
| 123 | assert_eq!( |
| 124 | probe(&invocation).await, |
| 125 | Ok("2.1.290 (Claude Code)".to_string()) |
| 126 | ); |
| 127 | } |
| 128 | |
| 129 | #[tokio::test] |
| 130 | async fn probe_reports_stderr_of_a_failing_command() { |
| 131 | let invocation = Invocation { |
| 132 | program: "sh".to_string(), |
| 133 | args: ["-c", "echo 'not logged in' >&2; exit 2"] |
| 134 | .map(String::from) |
| 135 | .to_vec(), |
| 136 | cwd: None, |
| 137 | stdin: None, |
| 138 | }; |
| 139 | assert_eq!(probe(&invocation).await, Err("not logged in".to_string())); |
| 140 | let missing = Invocation { |
| 141 | program: "definitely-not-a-program".to_string(), |
| 142 | args: Vec::new(), |
| 143 | cwd: None, |
| 144 | stdin: None, |
| 145 | }; |
| 146 | assert!( |
| 147 | probe(&missing) |
| 148 | .await |
| 149 | .unwrap_err() |
| 150 | .starts_with("cannot start") |
| 151 | ); |
| 152 | } |
| 153 | |
| 154 | #[tokio::test] |
| 155 | async fn cleanup_files_are_removed_when_the_run_ends() { |
| 156 | let directory = tempfile::tempdir().unwrap(); |
| 157 | let config = directory.path().join("mcp.json"); |
| 158 | std::fs::write(&config, "{}").unwrap(); |
| 159 | let mut finished_plan = plan("sh", &["-c", "exit 0"], None); |
| 160 | finished_plan.cleanup = vec![config.clone()]; |
| 161 | let (sender, _receiver) = mpsc::unbounded_channel(); |
| 162 | let (_keep_alive, stop) = oneshot::channel(); |
| 163 | run(finished_plan, OutputFormat::ClaudeStreamJson, sender, stop).await; |
| 164 | assert!(!config.exists()); |
| 165 | |
| 166 | std::fs::write(&config, "{}").unwrap(); |
| 167 | let mut stopped_plan = plan("sleep", &["30"], None); |
| 168 | stopped_plan.cleanup = vec![config.clone()]; |
| 169 | let (sender, _receiver) = mpsc::unbounded_channel(); |
| 170 | let (stop_sender, stop) = oneshot::channel(); |
| 171 | stop_sender.send(()).unwrap(); |
| 172 | run(stopped_plan, OutputFormat::ClaudeStreamJson, sender, stop).await; |
| 173 | assert!(!config.exists()); |
| 174 | } |
| 175 | |
| 176 | #[tokio::test] |
| 177 | async fn a_hanging_stop_command_is_killed_after_the_limit() { |
| 178 | let invocation = Invocation { |
| 179 | program: "sleep".to_string(), |
| 180 | args: vec!["30".to_string()], |
| 181 | cwd: None, |
| 182 | stdin: None, |
| 183 | }; |
| 184 | let started = std::time::Instant::now(); |
| 185 | agents::run_stop_invocation_within(&invocation, std::time::Duration::from_millis(200)).await; |
| 186 | assert!(started.elapsed() < std::time::Duration::from_secs(5)); |
| 187 | } |