| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | use std::fs; |
| 10 | use std::io::{BufRead, BufReader, Write}; |
| 11 | use std::path::{Path, PathBuf}; |
| 12 | use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; |
| 13 | use std::thread::sleep; |
| 14 | use std::time::{Duration, Instant}; |
| 15 | |
| 16 | use serde_json::{json, Value}; |
| 17 | |
| 18 | struct Client { |
| 19 | child: Child, |
| 20 | stdin: Option<ChildStdin>, |
| 21 | stdout: BufReader<ChildStdout>, |
| 22 | next_id: u64, |
| 23 | } |
| 24 | |
| 25 | impl Client { |
| 26 | fn spawn() -> Self { |
| 27 | Self::spawn_with_stderr(Stdio::inherit()) |
| 28 | } |
| 29 | |
| 30 | fn spawn_with_stderr(stderr: Stdio) -> Self { |
| 31 | let mut child = Command::new(env!("CARGO_BIN_EXE_edith_mcp")) |
| 32 | |
| 33 | .env("XDG_DATA_HOME", std::env::temp_dir().join(format!("edith_mcp-xdg-{}", std::process::id()))) |
| 34 | .stdin(Stdio::piped()) |
| 35 | .stdout(Stdio::piped()) |
| 36 | .stderr(stderr) |
| 37 | .spawn() |
| 38 | .expect("spawn edith_mcp"); |
| 39 | let stdin = child.stdin.take().expect("server stdin"); |
| 40 | let stdout = BufReader::new(child.stdout.take().expect("server stdout")); |
| 41 | Self { child, stdin: Some(stdin), stdout, next_id: 1 } |
| 42 | } |
| 43 | |
| 44 | fn send(&mut self, msg: &Value) { |
| 45 | let mut line = msg.to_string(); |
| 46 | line.push('\n'); |
| 47 | let stdin = self.stdin.as_mut().expect("stdin still open"); |
| 48 | stdin.write_all(line.as_bytes()).expect("write request"); |
| 49 | stdin.flush().expect("flush request"); |
| 50 | } |
| 51 | |
| 52 | |
| 53 | fn call(&mut self, method: &str, params: Value) -> Value { |
| 54 | let id = self.next_id; |
| 55 | self.next_id += 1; |
| 56 | self.send(&json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})); |
| 57 | let mut line = String::new(); |
| 58 | let n = self.stdout.read_line(&mut line).expect("read response"); |
| 59 | assert!(n > 0, "server closed stdout during {method}"); |
| 60 | let v: Value = serde_json::from_str(&line) |
| 61 | .unwrap_or_else(|e| panic!("stdout line during {method} is not JSON: {e}: {line:?}")); |
| 62 | assert_eq!(v["id"], json!(id), "response id mismatch for {method}"); |
| 63 | v |
| 64 | } |
| 65 | |
| 66 | fn notify(&mut self, method: &str, params: Value) { |
| 67 | self.send(&json!({"jsonrpc": "2.0", "method": method, "params": params})); |
| 68 | } |
| 69 | |
| 70 | |
| 71 | fn tool(&mut self, name: &str, args: Value) -> (String, bool) { |
| 72 | let r = self.call("tools/call", json!({"name": name, "arguments": args})); |
| 73 | let result = r.get("result").unwrap_or_else(|| panic!("tools/call {name} gave no result: {r}")); |
| 74 | let text = result["content"][0]["text"].as_str().unwrap_or("").to_owned(); |
| 75 | let is_error = result["isError"].as_bool().unwrap_or(false); |
| 76 | (text, is_error) |
| 77 | } |
| 78 | |
| 79 | |
| 80 | fn drain_and_check(&mut self) { |
| 81 | self.stdin = None; |
| 82 | for line in (&mut self.stdout).lines() { |
| 83 | let line = line.expect("read stdout"); |
| 84 | if line.trim().is_empty() { |
| 85 | continue; |
| 86 | } |
| 87 | serde_json::from_str::<Value>(&line) |
| 88 | .unwrap_or_else(|e| panic!("trailing stdout line is not JSON: {e}: {line:?}")); |
| 89 | } |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | impl Drop for Client { |
| 94 | fn drop(&mut self) { |
| 95 | let _ = self.child.kill(); |
| 96 | let _ = self.child.wait(); |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | struct Scratch(PathBuf); |
| 101 | |
| 102 | impl Drop for Scratch { |
| 103 | fn drop(&mut self) { |
| 104 | let _ = fs::remove_dir_all(&self.0); |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | #[test] |
| 109 | fn stdout_is_only_json_rpc() { |
| 110 | let assets = Path::new(env!("CARGO_MANIFEST_DIR")) |
| 111 | .join("../../assets") |
| 112 | .canonicalize() |
| 113 | .expect("assets directory exists"); |
| 114 | let dir = std::env::temp_dir().join(format!("edith_mcp-stdout-{}", std::process::id())); |
| 115 | let _ = fs::remove_dir_all(&dir); |
| 116 | fs::create_dir_all(&dir).expect("create scratch dir"); |
| 117 | let scratch = Scratch(dir); |
| 118 | let dir = scratch.0.clone(); |
| 119 | let mut c = Client::spawn(); |
| 120 | |
| 121 | let init = c.call( |
| 122 | "initialize", |
| 123 | json!({"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "stdout_clean", "version": "0"}}), |
| 124 | ); |
| 125 | assert!(init["result"]["protocolVersion"].is_string(), "initialize: {init}"); |
| 126 | c.notify("notifications/initialized", json!({})); |
| 127 | |
| 128 | let project = dir.join("p.edith"); |
| 129 | let (t, e) = c.tool("project_new", json!({"path": project.display().to_string()})); |
| 130 | assert!(!e, "project_new: {t}"); |
| 131 | |
| 132 | let source = assets.join("test_av.mp4").display().to_string(); |
| 133 | let (t, e) = c.tool("media_import", json!({"paths": [source]})); |
| 134 | assert!(!e, "media_import: {t}"); |
| 135 | |
| 136 | let (t, e) = c.tool("edit", json!({"ops": [{"op": "keep", "source": "src:0", "ranges": [["0s", "2s"]], "lane": "V1"}]})); |
| 137 | assert!(!e, "edit: {t}"); |
| 138 | |
| 139 | let (t, e) = c.tool("frame", json!({"at": "15f"})); |
| 140 | assert!(!e, "frame: {t}"); |
| 141 | |
| 142 | let out = dir.join("short.mkv"); |
| 143 | let (t, e) = c.tool( |
| 144 | "export_start", |
| 145 | json!({"out": out.display().to_string(), "range": {"from": 0, "to": "1s"}}), |
| 146 | ); |
| 147 | assert!(!e && t.contains("job:1"), "export_start: {t}"); |
| 148 | |
| 149 | let deadline = Instant::now() + Duration::from_secs(300); |
| 150 | loop { |
| 151 | let (t, e) = c.tool("export_status", json!({"job": 1})); |
| 152 | assert!(!e, "export failed: {t}"); |
| 153 | if t.contains("done") { |
| 154 | break; |
| 155 | } |
| 156 | assert!(Instant::now() < deadline, "export did not finish: {t}"); |
| 157 | sleep(Duration::from_millis(250)); |
| 158 | } |
| 159 | assert!(fs::metadata(&out).map(|m| m.len() > 0).unwrap_or(false), "exported file exists"); |
| 160 | |
| 161 | c.drain_and_check(); |
| 162 | } |
| 163 | |
| 164 | |
| 165 | |
| 166 | fn log_stderr(c: &mut Client) -> std::thread::JoinHandle<String> { |
| 167 | let mut stderr = c.child.stderr.take().expect("server stderr"); |
| 168 | std::thread::spawn(move || { |
| 169 | let mut log = String::new(); |
| 170 | let _ = std::io::Read::read_to_string(&mut stderr, &mut log); |
| 171 | log |
| 172 | }) |
| 173 | } |
| 174 | |
| 175 | |
| 176 | |
| 177 | |
| 178 | #[test] |
| 179 | fn autosave_notices_stay_off_stdout() { |
| 180 | let assets = Path::new(env!("CARGO_MANIFEST_DIR")) |
| 181 | .join("../../assets") |
| 182 | .canonicalize() |
| 183 | .expect("assets directory exists"); |
| 184 | let dir = std::env::temp_dir().join(format!("edith_mcp-autosave-stdout-{}", std::process::id())); |
| 185 | let _ = fs::remove_dir_all(&dir); |
| 186 | fs::create_dir_all(&dir).expect("create scratch dir"); |
| 187 | let scratch = Scratch(dir); |
| 188 | let dir = scratch.0.clone(); |
| 189 | let project = dir.join("p.edith"); |
| 190 | let source = assets.join("test_av.mp4").display().to_string(); |
| 191 | let keep = json!({"ops": [{"op": "keep", "source": "src:0", "ranges": [["0s", "2s"]], "lane": "V1"}]}); |
| 192 | |
| 193 | |
| 194 | let mut first = Client::spawn_with_stderr(Stdio::piped()); |
| 195 | let log_first = log_stderr(&mut first); |
| 196 | let init = first.call( |
| 197 | "initialize", |
| 198 | json!({"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "stdout_clean", "version": "0"}}), |
| 199 | ); |
| 200 | assert!(init["result"]["protocolVersion"].is_string(), "initialize: {init}"); |
| 201 | first.notify("notifications/initialized", json!({})); |
| 202 | let (t, e) = first.tool("project_new", json!({"path": project.display().to_string()})); |
| 203 | assert!(!e, "project_new: {t}"); |
| 204 | let (t, e) = first.tool("media_import", json!({"paths": [source.clone()]})); |
| 205 | assert!(!e, "media_import: {t}"); |
| 206 | let (t, e) = first.tool("edit", keep.clone()); |
| 207 | assert!(!e, "edit: {t}"); |
| 208 | first.drain_and_check(); |
| 209 | let _ = first.child.wait(); |
| 210 | let log_one = log_first.join().expect("stderr reader"); |
| 211 | assert!(log_one.contains("autosave: unsaved changes written to"), "session one autosave notice: {log_one}"); |
| 212 | |
| 213 | |
| 214 | |
| 215 | |
| 216 | let mut second = Client::spawn_with_stderr(Stdio::piped()); |
| 217 | let log_second = log_stderr(&mut second); |
| 218 | let init = second.call( |
| 219 | "initialize", |
| 220 | json!({"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "stdout_clean", "version": "0"}}), |
| 221 | ); |
| 222 | assert!(init["result"]["protocolVersion"].is_string(), "initialize: {init}"); |
| 223 | second.notify("notifications/initialized", json!({})); |
| 224 | let (t, e) = second.tool("project_open", json!({"path": project.display().to_string(), "recover": true})); |
| 225 | assert!(!e, "project_open: {t}"); |
| 226 | let (t, e) = second.tool("edit", keep); |
| 227 | assert!(!e, "edit: {t}"); |
| 228 | second.drain_and_check(); |
| 229 | let _ = second.child.wait(); |
| 230 | let log_two = log_second.join().expect("stderr reader"); |
| 231 | assert!(log_two.contains("autosave:"), "session two autosave notice: {log_two}"); |
| 232 | } |