edith
Clone
https://git.tahinli.com/Tahinli/edith.git
0 watching·0 forks·Rust·18.3 MiB·ff99ad6·Tahinli·6 days ago·1055 commits
| 1 | use serde_json::{Value, json}; |
| 2 | |
| 3 | use crate::help; |
| 4 | use crate::server::{Server, Tool}; |
| 5 | |
| 6 | const VERSIONS: [&str; 3] = ["2025-06-18", "2025-03-26", "2024-11-05"]; |
| 7 | const LATEST: &str = "2025-06-18"; |
| 8 | |
| 9 | /// Longest path an argument may carry, in bytes. Past it the OS refuses the name anyway. |
| 10 | const PATH_MAX: usize = 4096; |
| 11 | |
| 12 | pub fn handle(server: &mut Server, msg: Value) -> Option<Value> { |
| 13 | // MCP 2025-06-18 dropped JSON-RPC batching: an array is refused whole, empty or not. |
| 14 | if msg.is_array() { |
| 15 | return Some(error(Value::Null, -32600, "batches are not supported")); |
| 16 | } |
| 17 | if !msg.is_object() { |
| 18 | return Some(error(Value::Null, -32600, "invalid request: expected a JSON object")); |
| 19 | } |
| 20 | // No id means a notification: it gets no reply, whatever it asks for. |
| 21 | let id = msg.get("id")?.clone(); |
| 22 | // A request id is a string, a number or null (JSON-RPC 2.0); anything else cannot be echoed back. |
| 23 | if !matches!(id, Value::Null | Value::String(_) | Value::Number(_)) { |
| 24 | return Some(error(Value::Null, -32600, "invalid request: id must be a string, a number or null")); |
| 25 | } |
| 26 | let params = msg.get("params").cloned().unwrap_or(Value::Null); |
| 27 | let result = match msg.get("method").and_then(Value::as_str) { |
| 28 | Some("initialize") => Ok(initialize(¶ms)), |
| 29 | Some("ping") => Ok(json!({})), |
| 30 | Some("tools/list") => Ok(tools_list()), |
| 31 | Some("tools/call") => Ok(tools_call(server, ¶ms)), |
| 32 | Some("resources/list") => Ok(resources_list()), |
| 33 | Some("resources/read") => resources_read(server, ¶ms), |
| 34 | Some(m) => Err((-32601, format!("method not found: {m}"))), |
| 35 | None => Err((-32600, "invalid request: no method".to_owned())), |
| 36 | }; |
| 37 | Some(match result { |
| 38 | Ok(r) => json!({"jsonrpc": "2.0", "id": id, "result": r}), |
| 39 | Err((code, message)) => error(id, code, &message), |
| 40 | }) |
| 41 | } |
| 42 | |
| 43 | pub fn error(id: Value, code: i64, message: &str) -> Value { |
| 44 | json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}}) |
| 45 | } |
| 46 | |
| 47 | /// Every tool the server answers, `help` included. |
| 48 | fn all_tools() -> Vec<Tool> { |
| 49 | help::catalogue() |
| 50 | } |
| 51 | |
| 52 | fn initialize(params: &Value) -> Value { |
| 53 | let asked = params.get("protocolVersion").and_then(Value::as_str).unwrap_or(""); |
| 54 | let version = if VERSIONS.contains(&asked) { asked } else { LATEST }; |
| 55 | json!({ |
| 56 | "protocolVersion": version, |
| 57 | "capabilities": {"tools": {"listChanged": false}, "resources": {}}, |
| 58 | "serverInfo": {"name": "edith", "version": env!("CARGO_PKG_VERSION")}, |
| 59 | "instructions": help::short(&all_tools()), |
| 60 | }) |
| 61 | } |
| 62 | |
| 63 | fn tools_list() -> Value { |
| 64 | let tools: Vec<Value> = all_tools() |
| 65 | .iter() |
| 66 | .map(|t| json!({"name": t.name, "description": t.description, "inputSchema": (t.schema)()})) |
| 67 | .collect(); |
| 68 | json!({"tools": tools}) |
| 69 | } |
| 70 | |
| 71 | fn resources_list() -> Value { |
| 72 | json!({"resources": [ |
| 73 | { |
| 74 | "uri": "edith://help", |
| 75 | "name": "help", |
| 76 | "title": "edith cheat sheet", |
| 77 | "description": "Addresses, times, undo, the tool list, edit ops and recipes.", |
| 78 | "mimeType": "text/markdown" |
| 79 | }, |
| 80 | { |
| 81 | "uri": "edith://project", |
| 82 | "name": "project", |
| 83 | "title": "project status", |
| 84 | "description": "The project_status text: path, duration, lanes, sources, undo depth.", |
| 85 | "mimeType": "text/plain" |
| 86 | }, |
| 87 | { |
| 88 | "uri": "edith://timeline", |
| 89 | "name": "timeline", |
| 90 | "title": "timeline", |
| 91 | "description": "The timeline text: every lane's clips at their addresses.", |
| 92 | "mimeType": "text/plain" |
| 93 | } |
| 94 | ]}) |
| 95 | } |
| 96 | |
| 97 | fn resources_read(server: &mut Server, params: &Value) -> Result<Value, (i64, String)> { |
| 98 | let uri = params |
| 99 | .get("uri") |
| 100 | .and_then(Value::as_str) |
| 101 | .ok_or((-32602, "resources/read needs a `uri`".to_owned()))?; |
| 102 | let (mime, text) = match uri { |
| 103 | "edith://help" => ("text/markdown", help::sheet(&all_tools())), |
| 104 | "edith://project" => ("text/plain", run_named(server, "project_status")), |
| 105 | "edith://timeline" => ("text/plain", run_named(server, "timeline")), |
| 106 | other => return Err((-32002, format!("resource not found: {other}"))), |
| 107 | }; |
| 108 | Ok(json!({"contents": [{"uri": uri, "mimeType": mime, "text": text}]})) |
| 109 | } |
| 110 | |
| 111 | /// Runs a tool with no arguments and returns its text, which is the error text when it refuses. |
| 112 | fn run_named(server: &mut Server, name: &str) -> String { |
| 113 | let tools = all_tools(); |
| 114 | match tools.iter().find(|t| t.name == name) { |
| 115 | Some(tool) => (tool.run)(server, &json!({})).text, |
| 116 | None => format!("tool `{name}` is not registered"), |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | fn tools_call(server: &mut Server, params: &Value) -> Value { |
| 121 | let name = params.get("name").and_then(Value::as_str).unwrap_or(""); |
| 122 | let args = match params.get("arguments") { |
| 123 | None | Some(Value::Null) => json!({}), |
| 124 | Some(v) => v.clone(), |
| 125 | }; |
| 126 | let tools = all_tools(); |
| 127 | let Some(tool) = tools.iter().find(|t| t.name == name) else { |
| 128 | return refusal(help::unknown_tool(&tools, name)); |
| 129 | }; |
| 130 | if let Err(text) = check_args(tool, &args) { |
| 131 | return refusal(text); |
| 132 | } |
| 133 | // One tool call is one undo step: every engine edit it makes shares a single snapshot. |
| 134 | let mark = server.session.as_mut().map(|s| s.step_mark()); |
| 135 | if let Some(s) = server.session.as_mut() { |
| 136 | s.begin_batch(); |
| 137 | } |
| 138 | // `sequence` points a call at another sequence: a read goes back to the active one after. |
| 139 | let targeted = tool.name != "sequence"; |
| 140 | let reply = match if targeted { crate::tools::sequence::enter(server, &args, tool.name != "edit") } else { Ok(None) } { |
| 141 | Ok(back) => { |
| 142 | let reply = (tool.run)(server, &args); |
| 143 | crate::tools::sequence::leave(server, back); |
| 144 | reply |
| 145 | } |
| 146 | Err(refused) => refused, |
| 147 | }; |
| 148 | if let Some(s) = server.session.as_mut() { |
| 149 | s.end_batch(); |
| 150 | // An edit's step names its ops, so the GUI's Undo says what the call did. |
| 151 | if let (Some(mark), Some(label)) = (mark, edit_step_label(tool.name, &args)) { |
| 152 | s.name_step(mark, &label); |
| 153 | } |
| 154 | } |
| 155 | let mut content = vec![json!({"type": "text", "text": reply.text})]; |
| 156 | for (mime, data) in &reply.images { |
| 157 | content.push(json!({"type": "image", "data": data, "mimeType": mime})); |
| 158 | } |
| 159 | let mut out = json!({"content": content, "isError": reply.is_error}); |
| 160 | if let Some(s) = reply.structured { |
| 161 | out["structuredContent"] = *s; |
| 162 | } |
| 163 | out |
| 164 | } |
| 165 | |
| 166 | /// The name an edit call's step carries: its ops in order, each named once, as far as |
| 167 | /// the menu row has room for. `None` for any other tool, and for an edit with no ops. |
| 168 | fn edit_step_label(tool: &str, args: &Value) -> Option<String> { |
| 169 | if tool != "edit" { |
| 170 | return None; |
| 171 | } |
| 172 | let mut names: Vec<String> = Vec::new(); |
| 173 | for op in args.get("ops").and_then(Value::as_array)? { |
| 174 | let Some(name) = op.get("op").and_then(Value::as_str) else { |
| 175 | continue; |
| 176 | }; |
| 177 | let name = name.replace('_', " "); |
| 178 | if !names.contains(&name) { |
| 179 | names.push(name); |
| 180 | } |
| 181 | } |
| 182 | let mut label = String::new(); |
| 183 | for name in names { |
| 184 | let next = match label.is_empty() { |
| 185 | true => name, |
| 186 | false => format!("{label}, {name}"), |
| 187 | }; |
| 188 | if next.chars().count() >= 30 { |
| 189 | break; |
| 190 | } |
| 191 | label = next; |
| 192 | } |
| 193 | let mut chars = label.chars(); |
| 194 | let first = chars.next()?; |
| 195 | Some(first.to_uppercase().chain(chars).collect()) |
| 196 | } |
| 197 | |
| 198 | fn refusal(text: String) -> Value { |
| 199 | json!({"content": [{"type": "text", "text": text}], "isError": true}) |
| 200 | } |
| 201 | |
| 202 | /// Refuses a call whose top-level arguments do not fit the tool's `inputSchema`: |
| 203 | /// a key the schema does not list, a `required` key that is missing, or a value |
| 204 | /// whose JSON type differs from a single `type` the schema states. A null value |
| 205 | /// counts as absent, as the tools read it. Nested values (the ops of `edit`) are |
| 206 | /// left to the tool that reads them. |
| 207 | pub fn check_args(tool: &Tool, args: &Value) -> Result<(), String> { |
| 208 | let Some(given) = args.as_object() else { |
| 209 | return Err(format!("arguments for {} must be a JSON object", tool.name)); |
| 210 | }; |
| 211 | let schema = (tool.schema)(); |
| 212 | let empty = serde_json::Map::new(); |
| 213 | let props = schema.get("properties").and_then(Value::as_object).unwrap_or(&empty); |
| 214 | |
| 215 | for key in given.keys() { |
| 216 | if !props.contains_key(key) { |
| 217 | let accepted: Vec<&str> = props.keys().map(String::as_str).collect(); |
| 218 | let accepted = if accepted.is_empty() { "none".to_owned() } else { accepted.join(", ") }; |
| 219 | return Err(format!("unknown argument `{key}` for {}; accepted: {accepted}", tool.name)); |
| 220 | } |
| 221 | } |
| 222 | let required = schema.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str); |
| 223 | for key in required { |
| 224 | if given.get(key).is_none_or(Value::is_null) { |
| 225 | let hint = prop_sentence(props.get(key)).map(|d| format!(": {d}")).unwrap_or_default(); |
| 226 | return Err(format!("missing required argument `{key}` for {}{hint}", tool.name)); |
| 227 | } |
| 228 | } |
| 229 | for (key, value) in given { |
| 230 | if value.is_null() { |
| 231 | continue; |
| 232 | } |
| 233 | if is_path_key(key) { |
| 234 | let longest = match value { |
| 235 | Value::String(s) => s.len(), |
| 236 | Value::Array(items) => items.iter().filter_map(Value::as_str).map(str::len).max().unwrap_or(0), |
| 237 | _ => 0, |
| 238 | }; |
| 239 | if longest > PATH_MAX { |
| 240 | return Err(format!( |
| 241 | "argument `{key}` for {} has a path of {longest} bytes; a path is at most {PATH_MAX} bytes", |
| 242 | tool.name |
| 243 | )); |
| 244 | } |
| 245 | } |
| 246 | if let (Some(max), Some(text)) = ( |
| 247 | props.get(key).and_then(|p| p.get("maxLength")).and_then(Value::as_u64), |
| 248 | value.as_str(), |
| 249 | ) { |
| 250 | let n = text.chars().count(); |
| 251 | if n as u64 > max { |
| 252 | return Err(format!( |
| 253 | "argument `{key}` for {} must be at most {max} characters, got {n}", |
| 254 | tool.name |
| 255 | )); |
| 256 | } |
| 257 | } |
| 258 | let Some(prop) = props.get(key) else { |
| 259 | continue; |
| 260 | }; |
| 261 | let types = declared_types(prop); |
| 262 | if types.is_empty() || types.iter().any(|ty| type_matches(ty, value)) { |
| 263 | continue; |
| 264 | } |
| 265 | // A number that fails an integer type is named by its value, so `1.5` reads as |
| 266 | // `got 1.5` rather than `got number`. |
| 267 | let got = match value { |
| 268 | Value::Number(n) if types.iter().any(|ty| ty == "integer") => n.to_string(), |
| 269 | _ => json_type(value).to_owned(), |
| 270 | }; |
| 271 | let hint = prop_sentence(Some(prop)).map(|d| format!(": {d}")).unwrap_or_default(); |
| 272 | return Err(format!( |
| 273 | "argument `{key}` for {} must be {}, got {got}; for example {}{hint}", |
| 274 | tool.name, |
| 275 | describe_any(&types), |
| 276 | help::example(key, prop) |
| 277 | )); |
| 278 | } |
| 279 | Ok(()) |
| 280 | } |
| 281 | |
| 282 | /// The first sentence of a property's `description`, so a refusal can say what the argument means. |
| 283 | /// A period ends a sentence unless it follows an abbreviation (`e.g.`, `i.e.`). |
| 284 | fn prop_sentence(prop: Option<&Value>) -> Option<String> { |
| 285 | let text = prop?.get("description")?.as_str()?.trim(); |
| 286 | let mut end = text.len(); |
| 287 | for (i, _) in text.match_indices(". ") { |
| 288 | let before = text[..i].to_ascii_lowercase(); |
| 289 | if !(before.ends_with("e.g") || before.ends_with("i.e")) { |
| 290 | end = i + 1; |
| 291 | break; |
| 292 | } |
| 293 | } |
| 294 | let sentence = text[..end].trim(); |
| 295 | (!sentence.is_empty()).then(|| sentence.to_owned()) |
| 296 | } |
| 297 | |
| 298 | /// The JSON type names a schema property states: its `type`, one name or a list of them. |
| 299 | fn declared_types(prop: &Value) -> Vec<String> { |
| 300 | match prop.get("type") { |
| 301 | Some(Value::String(t)) => vec![t.clone()], |
| 302 | Some(Value::Array(ts)) => ts.iter().filter_map(Value::as_str).map(str::to_owned).collect(), |
| 303 | _ => Vec::new(), |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | /// Whether an argument named `key` holds a filesystem path, or a list of them. |
| 308 | fn is_path_key(key: &str) -> bool { |
| 309 | key.contains("path") || key.contains("file") || key == "out" || key.starts_with("out_") || key == "glob" || key == "dir" || key == "folder" |
| 310 | } |
| 311 | |
| 312 | fn type_matches(ty: &str, v: &Value) -> bool { |
| 313 | match ty { |
| 314 | "string" => v.is_string(), |
| 315 | "number" => v.is_number(), |
| 316 | // An integral float such as `1000000000.0` is a whole number too; the tool then |
| 317 | // says whether it is in range. |
| 318 | "integer" => v.is_i64() || v.is_u64() || v.as_f64().is_some_and(|f| f.is_finite() && f.fract() == 0.0), |
| 319 | "boolean" => v.is_boolean(), |
| 320 | "array" => v.is_array(), |
| 321 | "object" => v.is_object(), |
| 322 | "null" => v.is_null(), |
| 323 | _ => true, |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | /// The types a refusal names: `an array or a string` for `["array", "string"]`. |
| 328 | fn describe_any(types: &[String]) -> String { |
| 329 | types.iter().map(|ty| describe(ty)).collect::<Vec<_>>().join(" or ") |
| 330 | } |
| 331 | |
| 332 | fn describe(ty: &str) -> String { |
| 333 | match ty { |
| 334 | "integer" => "an integer".to_owned(), |
| 335 | "array" => "an array".to_owned(), |
| 336 | "object" => "an object".to_owned(), |
| 337 | other => format!("a {other}"), |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | fn json_type(v: &Value) -> &'static str { |
| 342 | match v { |
| 343 | Value::Null => "null", |
| 344 | Value::Bool(_) => "boolean", |
| 345 | Value::Number(_) => "number", |
| 346 | Value::String(_) => "string", |
| 347 | Value::Array(_) => "array", |
| 348 | Value::Object(_) => "object", |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | #[cfg(test)] |
| 353 | mod tests { |
| 354 | use super::*; |
| 355 | use crate::testutil::TestDir; |
| 356 | |
| 357 | /// An edit call names its step by the ops it made, once each and in order, and any |
| 358 | /// other tool names nothing. |
| 359 | #[test] |
| 360 | fn an_edit_step_is_named_by_its_ops() { |
| 361 | let args = json!({"ops": [ |
| 362 | {"op": "split", "at": "110f"}, |
| 363 | {"op": "trim_in", "at": "5f"}, |
| 364 | {"op": "split", "at": "115f"}, |
| 365 | ]}); |
| 366 | assert_eq!(edit_step_label("edit", &args).as_deref(), Some("Split, trim in")); |
| 367 | assert_eq!(edit_step_label("undo", &args), None, "only an edit call names its step"); |
| 368 | assert_eq!(edit_step_label("edit", &json!({"ops": []})), None); |
| 369 | let many = json!({"ops": [ |
| 370 | {"op": "remove_silence"}, {"op": "add_marker"}, {"op": "change_speed"}, |
| 371 | ]}); |
| 372 | let label = edit_step_label("edit", &many).expect("a label"); |
| 373 | assert!(label.chars().count() < 30, "{label:?} is too long for a menu row"); |
| 374 | assert!(label.starts_with("Remove silence"), "{label:?}"); |
| 375 | } |
| 376 | |
| 377 | fn request(server: &mut Server, method: &str, params: Value) -> Value { |
| 378 | handle(server, json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params})).expect("a reply") |
| 379 | } |
| 380 | |
| 381 | fn call(server: &mut Server, name: &str, args: Value) -> Value { |
| 382 | request(server, "tools/call", json!({"name": name, "arguments": args}))["result"].clone() |
| 383 | } |
| 384 | |
| 385 | fn text_of(result: &Value) -> &str { |
| 386 | result["content"][0]["text"].as_str().unwrap_or("") |
| 387 | } |
| 388 | |
| 389 | /// A project path inside a folder that the returned guard removes when the test ends. |
| 390 | fn scratch_project(test: &str) -> (TestDir, String) { |
| 391 | let dir = TestDir::new(&format!("rpc-{test}")); |
| 392 | let path = dir.join("rpc.edith").display().to_string(); |
| 393 | (dir, path) |
| 394 | } |
| 395 | |
| 396 | #[test] |
| 397 | fn initialize_advertises_resources() { |
| 398 | let mut s = Server::new(); |
| 399 | let reply = request(&mut s, "initialize", json!({})); |
| 400 | assert_eq!(reply["result"]["capabilities"]["resources"], json!({})); |
| 401 | assert!(reply["result"]["instructions"].as_str().unwrap_or("").contains("V1@")); |
| 402 | } |
| 403 | |
| 404 | #[test] |
| 405 | fn resources_list_has_three() { |
| 406 | let mut s = Server::new(); |
| 407 | let reply = request(&mut s, "resources/list", json!({})); |
| 408 | let uris: Vec<&str> = reply["result"]["resources"] |
| 409 | .as_array() |
| 410 | .expect("array") |
| 411 | .iter() |
| 412 | .filter_map(|r| r["uri"].as_str()) |
| 413 | .collect(); |
| 414 | assert_eq!(uris, ["edith://help", "edith://project", "edith://timeline"]); |
| 415 | } |
| 416 | |
| 417 | #[test] |
| 418 | fn resources_read_help_mentions_addresses_and_keep() { |
| 419 | let mut s = Server::new(); |
| 420 | let reply = request(&mut s, "resources/read", json!({"uri": "edith://help"})); |
| 421 | let content = &reply["result"]["contents"][0]; |
| 422 | assert_eq!(content["mimeType"], "text/markdown"); |
| 423 | let text = content["text"].as_str().unwrap_or(""); |
| 424 | assert!(text.contains("V1@")); |
| 425 | assert!(text.contains("keep")); |
| 426 | } |
| 427 | |
| 428 | #[test] |
| 429 | fn resources_read_project_without_a_project_gives_the_error_text() { |
| 430 | let mut s = Server::new(); |
| 431 | let reply = request(&mut s, "resources/read", json!({"uri": "edith://project"})); |
| 432 | let text = reply["result"]["contents"][0]["text"].as_str().unwrap_or(""); |
| 433 | assert!(text.contains("no project open"), "{text}"); |
| 434 | } |
| 435 | |
| 436 | #[test] |
| 437 | fn resources_read_refuses_an_unknown_uri() { |
| 438 | let mut s = Server::new(); |
| 439 | let reply = request(&mut s, "resources/read", json!({"uri": "edith://nope"})); |
| 440 | assert_eq!(reply["error"]["code"], -32002); |
| 441 | } |
| 442 | |
| 443 | #[test] |
| 444 | fn unknown_argument_is_refused_before_the_tool_runs() { |
| 445 | let mut s = Server::new(); |
| 446 | let (_dir, path) = scratch_project("bogus"); |
| 447 | let result = call(&mut s, "project_new", json!({"path": path, "bogus": 1})); |
| 448 | assert_eq!(result["isError"], true); |
| 449 | let text = text_of(&result); |
| 450 | assert!(text.starts_with("unknown argument `bogus` for project_new; accepted: "), "{text}"); |
| 451 | assert!(text.contains("path") && text.contains("discard"), "{text}"); |
| 452 | assert!(s.session.is_none(), "the tool must not have run"); |
| 453 | } |
| 454 | |
| 455 | #[test] |
| 456 | fn missing_required_is_refused() { |
| 457 | let mut s = Server::new(); |
| 458 | let result = call(&mut s, "project_new", json!({"fps": 30})); |
| 459 | assert_eq!(result["isError"], true); |
| 460 | assert_eq!(text_of(&result), "missing required argument `path` for project_new: Where the .edith file will be saved."); |
| 461 | } |
| 462 | |
| 463 | #[test] |
| 464 | fn wrong_type_is_refused() { |
| 465 | let mut s = Server::new(); |
| 466 | let (_dir, path) = scratch_project("fps-string"); |
| 467 | let result = call(&mut s, "project_new", json!({"path": path, "fps": "30"})); |
| 468 | assert_eq!(result["isError"], true); |
| 469 | assert_eq!(text_of(&result), "argument `fps` for project_new must be a number, got string; for example 1: Frame rate of the timeline."); |
| 470 | } |
| 471 | |
| 472 | #[test] |
| 473 | fn a_list_type_accepts_either_listed_type() { |
| 474 | let media = all_tools().into_iter().find(|t| t.name == "media_import").expect("media_import"); |
| 475 | assert!(check_args(&media, &json!({"paths": "x.mp4"})).is_ok()); |
| 476 | assert!(check_args(&media, &json!({"paths": ["a.mp4", "b.mp4"]})).is_ok()); |
| 477 | } |
| 478 | |
| 479 | #[test] |
| 480 | fn a_list_type_refuses_a_value_matching_none_of_its_types() { |
| 481 | let media = all_tools().into_iter().find(|t| t.name == "media_import").expect("media_import"); |
| 482 | let err = check_args(&media, &json!({"paths": 5})).expect_err("refused"); |
| 483 | assert_eq!( |
| 484 | err, |
| 485 | "argument `paths` for media_import must be an array or a string, got number; for example [\"clip.mp4\"]: Media file paths to import into the open project: a list, or one path as a string." |
| 486 | ); |
| 487 | } |
| 488 | |
| 489 | #[test] |
| 490 | fn a_refusal_names_the_example_from_the_schema() { |
| 491 | let levels = all_tools().into_iter().find(|t| t.name == "levels").expect("levels"); |
| 492 | let err = check_args(&levels, &json!({"target": "A1", "per_sec": true})).expect_err("refused"); |
| 493 | assert_eq!(err, "argument `per_sec` for levels must be a number, got boolean; for example 10: Buckets per second: a number, how many values each second of sound gets (e.g. 10 for ten per second)."); |
| 494 | } |
| 495 | |
| 496 | /// A refusal carries the property's first sentence; an abbreviation such as `e.g.` does not end it. |
| 497 | #[test] |
| 498 | fn a_refusal_or_missing_argument_says_what_the_argument_means() { |
| 499 | let levels = all_tools().into_iter().find(|t| t.name == "levels").expect("levels"); |
| 500 | let err = check_args(&levels, &json!({})).expect_err("target is required"); |
| 501 | assert_eq!(err, "missing required argument `target` for levels: A clip address (A1@0), a lane (A1), src:N for a whole source file, or \"mix\" for the timeline as exported."); |
| 502 | assert_eq!(prop_sentence(Some(&json!({"description": "A list: one (e.g. 3). Then more."}))).as_deref(), Some("A list: one (e.g. 3).")); |
| 503 | assert_eq!(prop_sentence(Some(&json!({"description": "No period here"}))).as_deref(), Some("No period here")); |
| 504 | assert_eq!(prop_sentence(Some(&json!({}))), None); |
| 505 | assert_eq!(prop_sentence(None), None); |
| 506 | } |
| 507 | |
| 508 | #[test] |
| 509 | fn valid_call_passes() { |
| 510 | let mut s = Server::new(); |
| 511 | let (_dir, path) = scratch_project("fps-number"); |
| 512 | let result = call(&mut s, "project_new", json!({"path": path, "fps": 30})); |
| 513 | assert_eq!(result["isError"], false, "{}", text_of(&result)); |
| 514 | } |
| 515 | |
| 516 | #[test] |
| 517 | fn nested_edit_ops_are_left_to_the_ops() { |
| 518 | let edit = all_tools().into_iter().find(|t| t.name == "edit").expect("edit is registered"); |
| 519 | let args = json!({"ops": [{"op": "place", "not_an_arg": 1}]}); |
| 520 | assert!(check_args(&edit, &args).is_ok()); |
| 521 | } |
| 522 | |
| 523 | #[test] |
| 524 | fn unknown_tool_gets_an_edit_op_hint_or_near_names() { |
| 525 | let mut s = Server::new(); |
| 526 | let op = call(&mut s, "lane_add", json!({})); |
| 527 | assert_eq!(op["isError"], true); |
| 528 | assert_eq!( |
| 529 | text_of(&op), |
| 530 | "lane_add is an edit op: edit {ops:[{op:\"lane_add\", …}]} — help {topic:\"lane_add\"}" |
| 531 | ); |
| 532 | let near = call(&mut s, "project_sav", json!({})); |
| 533 | assert!(text_of(&near).contains("project_save"), "{}", text_of(&near)); |
| 534 | let far = call(&mut s, "zzzzzzzzzz", json!({})); |
| 535 | assert!(text_of(&far).starts_with("unknown tool `zzzzzzzzzz`"), "{}", text_of(&far)); |
| 536 | } |
| 537 | |
| 538 | #[test] |
| 539 | fn a_batch_array_is_refused_whole_with_a_null_id() { |
| 540 | let mut s = Server::new(); |
| 541 | for batch in [json!([]), json!([{"jsonrpc": "2.0", "id": 1, "method": "ping"}])] { |
| 542 | let reply = handle(&mut s, batch).expect("a batch gets a reply"); |
| 543 | assert_eq!(reply["error"]["code"], -32600); |
| 544 | assert_eq!(reply["error"]["message"], "batches are not supported"); |
| 545 | assert!(reply["id"].is_null()); |
| 546 | } |
| 547 | } |
| 548 | |
| 549 | #[test] |
| 550 | fn an_id_that_is_not_a_string_number_or_null_is_refused() { |
| 551 | let mut s = Server::new(); |
| 552 | let reply = handle(&mut s, json!({"jsonrpc": "2.0", "id": {"a": 1}, "method": "ping"})).expect("a reply"); |
| 553 | assert_eq!(reply["error"]["code"], -32600); |
| 554 | assert!(reply["id"].is_null()); |
| 555 | let ok = handle(&mut s, json!({"jsonrpc": "2.0", "id": "x", "method": "ping"})).expect("a reply"); |
| 556 | assert_eq!(ok["id"], "x"); |
| 557 | assert!(ok.get("result").is_some()); |
| 558 | } |
| 559 | |
| 560 | #[test] |
| 561 | fn a_non_object_message_is_an_invalid_request() { |
| 562 | let mut s = Server::new(); |
| 563 | let reply = handle(&mut s, json!(42)).expect("a reply"); |
| 564 | assert_eq!(reply["error"]["code"], -32600); |
| 565 | } |
| 566 | |
| 567 | #[test] |
| 568 | fn a_label_past_its_max_length_is_refused_before_the_tool_runs() { |
| 569 | let mut s = Server::new(); |
| 570 | let long = "x".repeat(61); |
| 571 | let result = call(&mut s, "edit", json!({"ops": [{"op": "split", "at": "1f"}], "label": long})); |
| 572 | assert_eq!(result["isError"], true); |
| 573 | assert_eq!(text_of(&result), "argument `label` for edit must be at most 60 characters, got 61"); |
| 574 | let ok = call(&mut s, "edit", json!({"ops": [{"op": "split", "at": "1f"}], "label": "x".repeat(60)})); |
| 575 | assert!(!text_of(&ok).contains("must be at most"), "{}", text_of(&ok)); |
| 576 | } |
| 577 | |
| 578 | #[test] |
| 579 | fn a_path_past_4096_bytes_is_refused_up_front() { |
| 580 | let mut s = Server::new(); |
| 581 | let path = format!("/{}", "a".repeat(4096)); |
| 582 | let result = call(&mut s, "project_new", json!({"path": path})); |
| 583 | assert_eq!(result["isError"], true); |
| 584 | assert_eq!( |
| 585 | text_of(&result), |
| 586 | "argument `path` for project_new has a path of 4097 bytes; a path is at most 4096 bytes" |
| 587 | ); |
| 588 | assert!(s.session.is_none(), "the tool must not have run"); |
| 589 | } |
| 590 | |
| 591 | /// A tool call that makes more engine edits than the 100-step cap is one undo step, and |
| 592 | /// it is undoable whole: the ledger does not drop it the moment it lands. |
| 593 | #[test] |
| 594 | fn a_tool_call_past_the_cap_is_one_undo_step() { |
| 595 | let mut s = Server::new(); |
| 596 | let src = format!("{}/../../assets/test_av.mp4", env!("CARGO_MANIFEST_DIR")); |
| 597 | s.session = Some(engine::PlaybackSession::open(&src).expect("open assets/test_av.mp4")); |
| 598 | let ops: Vec<Value> = (1..=110).map(|f| json!({"op": "split", "at": format!("{f}f")})).collect(); |
| 599 | let edited = call(&mut s, "edit", json!({"ops": ops})); |
| 600 | assert_eq!(edited["isError"], false, "{}", text_of(&edited)); |
| 601 | assert_eq!(s.ledger.len(), 1, "one call, one step"); |
| 602 | assert_eq!(s.session.as_ref().unwrap().undo_depth(), 1, "the engine holds one snapshot for it"); |
| 603 | assert!(!s.history_capped); |
| 604 | |
| 605 | let undone = call(&mut s, "undo", json!({})); |
| 606 | assert_eq!(undone["isError"], false, "{}", text_of(&undone)); |
| 607 | assert!(text_of(&undone).starts_with("undid: split"), "{}", text_of(&undone)); |
| 608 | assert!(s.ledger.is_empty()); |
| 609 | assert_eq!(s.session.as_ref().unwrap().undo_depth(), 0); |
| 610 | } |
| 611 | |
| 612 | #[test] |
| 613 | fn help_tool_is_listed_and_schema_checked() { |
| 614 | let mut s = Server::new(); |
| 615 | let listed = request(&mut s, "tools/list", json!({})); |
| 616 | let names: Vec<&str> = listed["result"]["tools"] |
| 617 | .as_array() |
| 618 | .expect("array") |
| 619 | .iter() |
| 620 | .filter_map(|t| t["name"].as_str()) |
| 621 | .collect(); |
| 622 | assert!(names.contains(&"help")); |
| 623 | let result = call(&mut s, "help", json!({"topic": "nope"})); |
| 624 | assert_eq!(result["isError"], true); |
| 625 | } |
| 626 | |
| 627 | #[test] |
| 628 | fn integral_float_passes_the_integer_check() { |
| 629 | let frame = crate::server::tools().into_iter().find(|t| t.name == "frame").expect("frame tool"); |
| 630 | assert!(check_args(&frame, &json!({"at": "0f", "width": 1000000000.0})).is_ok()); |
| 631 | assert!(check_args(&frame, &json!({"at": "0f", "width": 1000000000})).is_ok()); |
| 632 | assert!(check_args(&frame, &json!({"at": "0f", "width": 1e30})).is_ok()); |
| 633 | } |
| 634 | |
| 635 | #[test] |
| 636 | fn fractional_number_still_fails_the_integer_check() { |
| 637 | let frame = crate::server::tools().into_iter().find(|t| t.name == "frame").expect("frame tool"); |
| 638 | let err = check_args(&frame, &json!({"at": "0f", "width": 1.5})).expect_err("refused"); |
| 639 | assert_eq!(err, "argument `width` for frame must be an integer, got 1.5; for example 1: Width of the image in pixels; the height follows the aspect."); |
| 640 | } |
| 641 | } |