| 1 | #![cfg(unix)] |
| 2 | |
| 3 | use std::io::{Read, Write}; |
| 4 | use std::process::{Command, Stdio}; |
| 5 | use std::time::{Duration, Instant}; |
| 6 | |
| 7 | use serde_json::{Value, json}; |
| 8 | use tempfile::TempDir; |
| 9 | use wait_timeout::ChildExt; |
| 10 | use wiremock::matchers::{method, path}; |
| 11 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 12 | |
| 13 | const TEST_MODEL: &str = "prompt-input-model"; |
| 14 | const RUN_TIMEOUT: Duration = Duration::from_secs(60); |
| 15 | |
| 16 | enum Stdin { |
| 17 | Inherit, |
| 18 | Bytes(&'static str), |
| 19 | OpenPipe, |
| 20 | } |
| 21 | |
| 22 | struct Outcome { |
| 23 | success: bool, |
| 24 | stdout: String, |
| 25 | stderr: String, |
| 26 | elapsed: Duration, |
| 27 | dispatched: String, |
| 28 | } |
| 29 | |
| 30 | fn answer_sse() -> String { |
| 31 | let chunk = |value: Value| format!("data: {}\n\n", value); |
| 32 | [ |
| 33 | chunk(json!({ |
| 34 | "id": "c1", "object": "chat.completion.chunk", "model": TEST_MODEL, |
| 35 | "choices": [{"index": 0, "delta": {"content": "ok"}, "finish_reason": null}] |
| 36 | })), |
| 37 | chunk(json!({ |
| 38 | "id": "c1", "object": "chat.completion.chunk", "model": TEST_MODEL, |
| 39 | "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}] |
| 40 | })), |
| 41 | "data: [DONE]\n\n".to_string(), |
| 42 | ] |
| 43 | .join("") |
| 44 | } |
| 45 | |
| 46 | async fn start_mock_llm() -> MockServer { |
| 47 | let server = MockServer::start().await; |
| 48 | Mock::given(method("GET")) |
| 49 | .and(path("/v1/models")) |
| 50 | .respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 51 | "object": "list", |
| 52 | "data": [{ "id": TEST_MODEL, "object": "model" }] |
| 53 | }))) |
| 54 | .mount(&server) |
| 55 | .await; |
| 56 | Mock::given(method("POST")) |
| 57 | .and(path("/v1/chat/completions")) |
| 58 | .respond_with( |
| 59 | ResponseTemplate::new(200) |
| 60 | .insert_header("content-type", "text/event-stream") |
| 61 | .set_body_string(answer_sse()), |
| 62 | ) |
| 63 | .mount(&server) |
| 64 | .await; |
| 65 | server |
| 66 | } |
| 67 | |
| 68 | fn drain<R: Read + Send + 'static>(mut reader: R) -> std::thread::JoinHandle<Vec<u8>> { |
| 69 | std::thread::spawn(move || { |
| 70 | let mut out = Vec::new(); |
| 71 | let _ = reader.read_to_end(&mut out); |
| 72 | out |
| 73 | }) |
| 74 | } |
| 75 | |
| 76 | async fn run_exec(server: &MockServer, exec_args: &[&str], stdin: Stdin) -> Outcome { |
| 77 | let workspace = TempDir::new().expect("workspace"); |
| 78 | let home = TempDir::new().expect("home"); |
| 79 | std::fs::create_dir_all(home.path().join(".codewhale")).expect("config dir"); |
| 80 | |
| 81 | let mut command = Command::new(crate::binary::codewhale()); |
| 82 | command.env_clear(); |
| 83 | for key in ["PATH", "TMPDIR", "TERM", "LANG", "LC_ALL"] { |
| 84 | if let Some(value) = std::env::var_os(key) { |
| 85 | command.env(key, value); |
| 86 | } |
| 87 | } |
| 88 | command |
| 89 | .current_dir(workspace.path()) |
| 90 | .arg("--workspace") |
| 91 | .arg(workspace.path()) |
| 92 | .arg("--no-project-config") |
| 93 | .arg("exec") |
| 94 | .args(exec_args) |
| 95 | .env("HOME", home.path()) |
| 96 | .env("XDG_CONFIG_HOME", home.path().join(".config")) |
| 97 | .env( |
| 98 | "CODEWHALE_CONFIG_PATH", |
| 99 | home.path().join(".codewhale").join("config.toml"), |
| 100 | ) |
| 101 | .env("DEEPSEEK_API_KEY", "ci-test-key-not-real") |
| 102 | .env("DEEPSEEK_BASE_URL", server.uri()) |
| 103 | .env("CODEWHALE_BASE_URL", server.uri()) |
| 104 | .env("DEEPSEEK_MODEL", TEST_MODEL) |
| 105 | .env("CODEWHALE_MODEL", TEST_MODEL) |
| 106 | .env("RUST_LOG", "warn") |
| 107 | .stdout(Stdio::piped()) |
| 108 | .stderr(Stdio::piped()); |
| 109 | match stdin { |
| 110 | Stdin::Inherit => { |
| 111 | command.stdin(Stdio::null()); |
| 112 | } |
| 113 | Stdin::Bytes(_) | Stdin::OpenPipe => { |
| 114 | command.stdin(Stdio::piped()); |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | let started = Instant::now(); |
| 119 | let mut child = command.spawn().expect("spawn codewhale exec"); |
| 120 | let mut held_open = None; |
| 121 | match stdin { |
| 122 | Stdin::Bytes(text) => { |
| 123 | let mut pipe = child.stdin.take().expect("stdin pipe"); |
| 124 | let _ = pipe.write_all(text.as_bytes()); |
| 125 | } |
| 126 | Stdin::OpenPipe => held_open = child.stdin.take(), |
| 127 | Stdin::Inherit => {} |
| 128 | } |
| 129 | let stdout = drain(child.stdout.take().expect("stdout")); |
| 130 | let stderr = drain(child.stderr.take().expect("stderr")); |
| 131 | let status = match child.wait_timeout(RUN_TIMEOUT).expect("wait") { |
| 132 | Some(status) => status, |
| 133 | None => { |
| 134 | let _ = child.kill(); |
| 135 | let _ = child.wait(); |
| 136 | panic!( |
| 137 | "codewhale exec did not exit within {RUN_TIMEOUT:?}\nstderr:\n{}", |
| 138 | String::from_utf8_lossy(&stderr.join().unwrap_or_default()) |
| 139 | ); |
| 140 | } |
| 141 | }; |
| 142 | let elapsed = started.elapsed(); |
| 143 | drop(held_open); |
| 144 | let dispatched = server |
| 145 | .received_requests() |
| 146 | .await |
| 147 | .unwrap_or_default() |
| 148 | .iter() |
| 149 | .filter(|request| request.url.path() == "/v1/chat/completions") |
| 150 | .map(|request| String::from_utf8_lossy(&request.body).into_owned()) |
| 151 | .collect::<Vec<_>>() |
| 152 | .join("\n"); |
| 153 | Outcome { |
| 154 | success: status.success(), |
| 155 | stdout: String::from_utf8_lossy(&stdout.join().unwrap_or_default()).into_owned(), |
| 156 | stderr: String::from_utf8_lossy(&stderr.join().unwrap_or_default()).into_owned(), |
| 157 | elapsed, |
| 158 | dispatched, |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | fn assert_rejected_before_dispatch(outcome: &Outcome, flag: &str) { |
| 163 | assert!( |
| 164 | !outcome.success, |
| 165 | "a flag after the prompt must fail\nstdout:\n{}\nstderr:\n{}", |
| 166 | outcome.stdout, outcome.stderr |
| 167 | ); |
| 168 | assert!( |
| 169 | outcome.stderr.contains(flag), |
| 170 | "stderr must name {flag}\nstderr:\n{}", |
| 171 | outcome.stderr |
| 172 | ); |
| 173 | assert!( |
| 174 | outcome.dispatched.is_empty(), |
| 175 | "nothing may reach the provider: {}", |
| 176 | outcome.dispatched |
| 177 | ); |
| 178 | } |
| 179 | |
| 180 | #[tokio::test(flavor = "multi_thread")] |
| 181 | async fn flags_after_the_prompt_are_rejected_not_sent_as_text() { |
| 182 | let server = start_mock_llm().await; |
| 183 | for args in [ |
| 184 | vec!["fix tests", "--auto"], |
| 185 | vec!["fix", "tests", "--auto", "now"], |
| 186 | vec!["fix tests", "--auto=true"], |
| 187 | ] { |
| 188 | let outcome = run_exec(&server, &args, Stdin::Inherit).await; |
| 189 | assert_rejected_before_dispatch(&outcome, "--auto"); |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | #[tokio::test(flavor = "multi_thread")] |
| 194 | async fn full_width_and_typographic_flags_after_the_prompt_are_rejected() { |
| 195 | let server = start_mock_llm().await; |
| 196 | for (word, shown) in [ |
| 197 | ("\u{FF0D}\u{FF0D}auto", "--auto"), |
| 198 | ("\u{2014}auto", "--auto"), |
| 199 | ("\u{2013}\u{2013}auto", "--auto"), |
| 200 | ("--\u{FF41}\u{FF55}\u{FF54}\u{FF4F}", "--auto"), |
| 201 | ] { |
| 202 | let outcome = run_exec(&server, &["fix tests", word], Stdin::Inherit).await; |
| 203 | assert_rejected_before_dispatch(&outcome, shown); |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | #[tokio::test(flavor = "multi_thread")] |
| 208 | async fn separator_keeps_a_literal_flag_in_the_prompt() { |
| 209 | let server = start_mock_llm().await; |
| 210 | let outcome = run_exec(&server, &["--", "explain", "--auto"], Stdin::Inherit).await; |
| 211 | assert!(outcome.success, "stderr:\n{}", outcome.stderr); |
| 212 | assert!( |
| 213 | outcome.dispatched.contains("explain --auto"), |
| 214 | "dispatched: {}", |
| 215 | outcome.dispatched |
| 216 | ); |
| 217 | } |
| 218 | |
| 219 | #[tokio::test(flavor = "multi_thread")] |
| 220 | async fn an_unrelated_open_pipe_does_not_hang_an_explicit_prompt() { |
| 221 | let server = start_mock_llm().await; |
| 222 | let outcome = run_exec(&server, &["say hello"], Stdin::OpenPipe).await; |
| 223 | assert!( |
| 224 | outcome.success, |
| 225 | "stdout:\n{}\nstderr:\n{}", |
| 226 | outcome.stdout, outcome.stderr |
| 227 | ); |
| 228 | assert!(outcome.dispatched.contains("say hello")); |
| 229 | assert!( |
| 230 | outcome.stderr.contains("stdin produced no data"), |
| 231 | "the ignored stdin must be reported\nstderr:\n{}", |
| 232 | outcome.stderr |
| 233 | ); |
| 234 | assert!( |
| 235 | outcome.elapsed < Duration::from_secs(30), |
| 236 | "elapsed {:?}", |
| 237 | outcome.elapsed |
| 238 | ); |
| 239 | } |
| 240 | |
| 241 | #[tokio::test(flavor = "multi_thread")] |
| 242 | async fn piped_stdin_is_appended_to_the_prompt_and_is_the_prompt_alone() { |
| 243 | let server = start_mock_llm().await; |
| 244 | let appended = run_exec( |
| 245 | &server, |
| 246 | &["review this"], |
| 247 | Stdin::Bytes("diff --git a/x b/x\n"), |
| 248 | ) |
| 249 | .await; |
| 250 | assert!(appended.success, "stderr:\n{}", appended.stderr); |
| 251 | assert!(appended.dispatched.contains("review this")); |
| 252 | assert!(appended.dispatched.contains("diff --git a/x b/x")); |
| 253 | |
| 254 | let alone = run_exec(&server, &[], Stdin::Bytes("summarize the pipe prompt\n")).await; |
| 255 | assert!(alone.success, "stderr:\n{}", alone.stderr); |
| 256 | assert!(alone.dispatched.contains("summarize the pipe prompt")); |
| 257 | } |
| 258 |