SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
MCP batch: rollback restores the original document (#3242) (#3288)
Dahak Builds2b1cb2c4e1ea
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 3eae93671d..6c587973be 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -431,16 +431,24 @@ impl Session {/// Become `fresh` (another design opened, recovered or started), keeping the settings that/// are the user's rather than the design's: `auto_project` is a preference (#680).+ /// Checkpoints survive too: a batch that failed after `file.new` or `doc.open` goes back+ /// from the checkpoint it took before its first step, and that checkpoint belongs to the+ /// design before the batch, which is what the batch promised (#3242). The design is what a+ /// checkpoint keeps, not the replaced session's file path (docs/mcp.md).pub fn replace_design(&mut self, fresh: Session) {let auto_project = self.auto_project;let param_check = self.param_check;let render_viewport = self.render_viewport.clone();let render_jobs = self.render_jobs.scratch();+ let checkpoints = std::mem::take(&mut self.checkpoints);+ let next_checkpoint = self.next_checkpoint;*self = fresh;self.auto_project = auto_project;self.param_check = param_check;self.render_viewport = render_viewport;self.render_jobs = render_jobs;+ self.checkpoints = checkpoints;+ self.next_checkpoint = next_checkpoint;}/// The design has changes not in its file: in the document, or in what is hidden.diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex 42d9f57fe8..5a3380b6e1 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -1785,6 +1785,23 @@ fn checkpoint_restores_with_a_full_undo_history() {assert!(s.execute("edit.restore_checkpoint", &json!({"checkpoint": id})).is_err());}+/// Regression (#3242): `file.new` replaced the session and its checkpoints with it, so a+/// batch that failed after `file.new` could not go back to the design it began in.+#[test]+fn a_checkpoint_survives_file_new() {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 1.0, "width": 1.0, "height": 1.0}));+ let id = run(&mut s, "edit.checkpoint", json!({}))["checkpoint"].as_u64().unwrap();+ run(&mut s, "file.new", json!({"name": "Replacement"}));+ run(&mut s, "solid.box", json!({"length": 2.0, "width": 2.0, "height": 2.0}));+ assert_eq!(run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64(), Some(8.0));+ run(&mut s, "edit.restore_checkpoint", json!({"checkpoint": id}));+ assert_eq!(run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64(), Some(1.0));+ // The undo history is the restored design's own: one step back is the empty design.+ run(&mut s, "edit.undo", json!({}));+ assert_eq!(run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64(), Some(0.0));+}+#[test]fn components_occurrences_and_world_placement() {let mut s = Session::default();diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rsindex 8ac811edd2..71cdb9513d 100644--- a/crates/mcp/src/tests.rs+++ b/crates/mcp/src/tests.rs@@ -421,6 +421,35 @@ fn batch_rolls_back_with_a_full_undo_history() {assert_eq!(d["undo"], undo);}+/// Regression (#3242): a failed batch containing `file.new` reported `rolled_back: true` and+/// kept the replacement design. The checkpoint survives the new document, so the design the+/// batch started in — the 1 mm cube — is back when the batch fails.+#[test]+fn a_failed_batch_with_file_new_restores_the_original_design() {+ let mut s = server();+ tool(&mut s, "batch", json!({"commands": [{"command": "solid.box", "params": {"length": 1, "width": 1, "height": 1, "body_name": "Original"}}]}));+ let name = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false}))["name"].clone();+ let r = raw_tool(+ &mut s,+ "batch",+ json!({"rollback": true, "commands": [+ {"command": "file.new", "params": {"name": "Replacement"}},+ {"command": "solid.box", "params": {"length": 2, "width": 2, "height": 2}},+ {"command": "not.a.command"},+ ]}),+ );+ assert_eq!(r["result"]["isError"], true, "{r}");+ let body: Value = serde_json::from_str(r["result"]["content"][0]["text"].as_str().unwrap()).unwrap();+ assert_eq!(body["failed"]["index"], 2, "{body}");+ assert_eq!(body["rolled_back"], true, "{body}");+ assert_eq!(body["undone"], 2, "{body}");+ // The original 1 mm cube is back; the replacement design is gone.+ assert_eq!(tool(&mut s, "measure", json!({}))["body_count"], 1);+ assert!(rel(volume(&mut s), 1.0) < 1e-9, "{}", volume(&mut s));+ let d = tool(&mut s, "inspect_design", json!({"measure": false, "sketches": false}));+ assert_eq!(d["name"], name, "{d}");+}+#[test]fn helper_sketches_can_be_hidden() {let mut s = server();@@ -1346,6 +1375,27 @@ fn batch_reports_a_failed_engine_batch_like_before() {);}+/// `rolled_back` tells whether the design went back, not whether a rollback was asked for+/// (#3242): the app's `rolled_back`, or, for an app that predates that field, none of the+/// completed steps undone means the design did not go back.+#[test]+fn a_batch_the_app_could_not_roll_back_reports_it() {+ let failed = |reply: Value| {+ let (_, body, is_error) = recorded_batch(Ok(reply), json!({"commands": [{"command": "a.one"}, {"command": "a.two"}]}));+ assert!(is_error);+ body+ };+ let body = failed(+ json!({"completed": 1, "results": [{"x": 1}], "failed": {"index": 1, "command": "a.two", "error": "boom"}, "rolled_back": false, "undone": 0}),+ );+ assert_eq!(body["rolled_back"], false, "{body}");+ let body = failed(json!({"completed": 1, "results": [{"x": 1}], "failed": {"index": 1, "command": "a.two", "error": "boom"}, "undone": 0}));+ assert_eq!(body["rolled_back"], false, "{body}");+ // A first step that failed left nothing to take back.+ let body = failed(json!({"completed": 0, "results": [], "failed": {"index": 0, "command": "a.one", "error": "boom"}, "undone": 0}));+ assert_eq!(body["rolled_back"], true, "{body}");+}+#[test]fn batch_falls_back_when_the_app_lacks_engine_batch() {let (b, body, is_error) =diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rsindex ef720a0e16..2139a6a6bb 100644--- a/crates/mcp/src/tools.rs+++ b/crates/mcp/src/tools.rs@@ -500,12 +500,13 @@ impl Undo {}}- /// Go back; the number of steps undone.- fn rollback(self, b: &mut dyn Backend, steps: usize) -> u64 {+ /// Go back; (whether the design is back as it was, the number of steps undone). A failed+ /// rollback says so rather than reporting the flag the caller asked for (#3242).+ fn rollback(self, b: &mut dyn Backend, steps: usize) -> (bool, u64) {match self {Undo::Checkpoint(id) => match exec(b, "edit.restore_checkpoint", json!({"checkpoint": id})) {- Ok(_) => steps as u64,- Err(_) => 0,+ Ok(_) => (true, steps as u64),+ Err(_) => (false, 0),},Undo::Depth(before) => {let after = undo_depth(b).unwrap_or(before);@@ -516,9 +517,10 @@ impl Undo {}undone += 1;}- undone+ (undone == steps as u64, undone)}- Undo::None => 0,+ // Nothing remembered the design; only a first step that failed left nothing behind.+ Undo::None => (steps == 0, 0),}}@@ -583,12 +585,12 @@ fn batch(b: &mut dyn Backend, a: &Map<String, Value>) -> Value {match r {Ok(v) => results.push(if verbose { v } else { compact(v) }),Err(e) => {- let undone = start.rollback(b, i);+ let (rolled_back, undone) = start.rollback(b, i);let reply = json!({"ok": false,"completed": i,"failed": {"index": i, "command": command, "error": e},- "rolled_back": rollback,+ "rolled_back": rolled_back,"undone": undone,"results": results,});@@ -616,17 +618,24 @@ fn batch_reply(r: &Value, rollback: bool, verbose: bool) -> Value {r["results"].as_array().cloned().unwrap_or_default().into_iter().map(|v| if verbose { v } else { compact(v) }).collect();let (mut reply, error) = match r.get("failed").filter(|f| !f.is_null()) {None => (json!({"ok": true, "completed": results.len(), "results": results}), false),- Some(failed) => (- json!({- "ok": false,- "completed": r["completed"],- "failed": failed,- "rolled_back": rollback,- "undone": r["undone"],- "results": results,- }),- true,- ),+ Some(failed) => {+ // `rolled_back` tells whether the design went back, not whether a rollback was+ // asked for (#3242): the app answers with its own `rolled_back`; an app that+ // predates that field and undid none of the steps it had completed did not go back.+ let undone = r["undone"].as_u64().unwrap_or(0);+ let went_back = r.get("rolled_back").and_then(Value::as_bool).unwrap_or(undone > 0 || r["completed"].as_u64() == Some(0));+ (+ json!({+ "ok": false,+ "completed": r["completed"],+ "failed": failed,+ "rolled_back": rollback && went_back,+ "undone": r["undone"],+ "results": results,+ }),+ true,+ )+ }};// The app timed the steps where they ran.if let Some(o) = reply.as_object_mut() {diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex 92a1d9bc60..9cf50862c4 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -74,7 +74,7 @@ MCP server sends its folders this way on every request ([mcp.md](mcp.md)). Witho|---|---|---|| `engine.execute` | `command`: command id, `params`: JSON object | the command's result || `engine.script` | `commands`: `[{command, params}, …]` | results, stops at the first error |-| `engine.batch` | `commands`: `[{command, params}, …]` (at most 10 000), `rollback?`: bool (default true), `timings?`, `profile?`: bool (default false) | `{completed, results, undone}`, plus `failed: {index, command, error}` when a step fails, and with `timings` `timings: [{index, command, ms}]` (the failing step included) and `total_ms`; `profile` adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`. Runs the steps in one request, so within one frame, each as `engine.execute` runs it. The first failure stops the batch, and with `rollback` the design goes back to how it was before it (`undone`: the steps taken back). Refused before anything runs, with an error starting `engine.batch unavailable`, while the agent cursor is shown or when a step loads a file (`doc.open`, `file.insert_step`, `file.insert_mesh`). Send such steps one by one. Answered when done, for up to 3600 s |+| `engine.batch` | `commands`: `[{command, params}, …]` (at most 10 000), `rollback?`: bool (default true), `timings?`, `profile?`: bool (default false) | `{completed, results, undone}`, plus `failed: {index, command, error}` when a step fails, and with `timings` `timings: [{index, command, ms}]` (the failing step included) and `total_ms`; `profile` adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`. Runs the steps in one request, so within one frame, each as `engine.execute` runs it. The first failure stops the batch, and with `rollback` the design goes back to how it was before it (`undone`: the steps taken back, `rolled_back`: whether the design is back as it was, `false` only when the checkpoint could not restore it). Refused before anything runs, with an error starting `engine.batch unavailable`, while the agent cursor is shown or when a step loads a file (`doc.open`, `file.insert_step`, `file.insert_mesh`). Send such steps one by one. Answered when done, for up to 3600 s || `engine.commands` | — | every command: id, label, tab, panel, icon, shortcut, params doc, enabled || `document.inspect` | `measure?`: bool | parameters, timeline (errors, timings), bodies, sketches, selection (assembly joints: `engine.execute` `joint.inspect {joint?}`, which reads only: each joint's two origins with the occurrence, the snap as saved, the feature, face, edge or sketch curve its names refer to, and whether it resolves or why not; kind, offset, angle, flip, values, limits, expressions and motion links) |