Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Control channel: each step of engine.script gets the window's follow-up, like engine.batch (#12629) (#12630)

CamWight970eb715f367
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 9507faf68c..a4ab21616a 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -2321,16 +2321,7 @@ impl Session {
}
fn run_script_with(&mut self, script: &Value, profile: Option<bool>, each: &mut dyn FnMut(usize, &Value)) -> Result<(Vec<Value>, Option<Value>)> {
- let list = match script {
- Value::Array(a) => a.clone(),
- Value::Object(o) => {
- o.get("commands").and_then(Value::as_array).cloned().ok_or_else(|| EngineError::Other("script: missing `commands` array".into()))?
- }
- _ => return Err(EngineError::Other("script must be a JSON array or {\"commands\": [...]}".into())),
- };
- if list.len() > 100_000 {
- return Err(EngineError::Other("script too long".into()));
- }
+ let list = script_steps(script)?;
let mut out = Vec::new();
let mut steps = Vec::new();
let clock = timing::Clock::start();
@@ -2358,6 +2349,21 @@ impl Session {
}
}
+/// A script's steps: the JSON array itself, or the `commands` array of an object; at most 100 000.
+pub fn script_steps(script: &Value) -> Result<&Vec<Value>> {
+ let list = match script {
+ Value::Array(a) => a,
+ Value::Object(o) => {
+ o.get("commands").and_then(Value::as_array).ok_or_else(|| EngineError::Other("script: missing `commands` array".into()))?
+ }
+ _ => return Err(EngineError::Other("script must be a JSON array or {\"commands\": [...]}".into())),
+ };
+ if list.len() > 100_000 {
+ return Err(EngineError::Other("script too long".into()));
+ }
+ Ok(list)
+}
+
#[cfg(test)]
mod boolean_regression_tests;
#[cfg(test)]
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index ad44937944..c388e194ce 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -357,6 +357,11 @@ fn command(step: &Value) -> Option<&str> {
step.get("command").or_else(|| step.get("id")).and_then(Value::as_str)
}
+/// A batch step's parameters: missing or null is no parameters.
+fn step_params(step: &Value) -> Value {
+ step.get("params").cloned().filter(|p| !p.is_null()).unwrap_or(json!({}))
+}
+
/// Most steps in one `engine.batch` (as in the MCP `batch` tool).
const MAX_BATCH: usize = 10_000;
@@ -427,9 +432,7 @@ fn batch(app: &mut SolveApp, p: &Value) -> Outcome {
// checkpoint; previous application changes are truthfully retained.
let mut results = Vec::new();
for (i, step) in steps.iter().enumerate() {
- let result = command(step)
- .ok_or_else(|| "missing command".to_string())
- .and_then(|id| execute(app, id, step.get("params").cloned().filter(|p| !p.is_null()).unwrap_or(json!({}))));
+ let result = command(step).ok_or_else(|| "missing command".to_string()).and_then(|id| execute(app, id, step_params(step)));
match result {
Ok(result) => results.push(result),
Err(error) => return ok(solidcraft_engine::panels::commands::sequential_failure(i, command(step), error, results)),
@@ -476,7 +479,7 @@ fn batch(app: &mut SolveApp, p: &Value) -> Outcome {
for i in singles {
let Some(step) = steps.get(i) else { continue };
let (r, took) = timing::time(profile, || match command(step) {
- Some(id) => execute(app, id, step.get("params").cloned().filter(|v| !v.is_null()).unwrap_or(json!({}))),
+ Some(id) => execute(app, id, step_params(step)),
None => Err("missing `command`".to_string()),
});
if timed {
@@ -500,6 +503,43 @@ fn batch(app: &mut SolveApp, p: &Value) -> Outcome {
ok(with_timings(json!({"completed": results.len(), "results": results, "undone": 0}), timed, rows, clock.ms()))
}
+/// `engine.script {commands}` (or the bare array): each step runs as `engine.execute` runs it, so
+/// the window follows it as it follows a batch step (#12629). The first failure stops the script,
+/// and the steps before it stay. Its words are the engine script's, or the panel error when a step
+/// is a panel command.
+fn script(app: &mut SolveApp, p: &Value) -> Outcome {
+ let steps = match solidcraft_engine::script_steps(p) {
+ Ok(steps) => steps,
+ Err(e) => return err(e),
+ };
+ if let Some(c) = steps.iter().find_map(switches_design) {
+ return err(format!("engine.script unavailable: {c} switches to another design (send it on its own)"));
+ }
+ let panels = steps.iter().any(|step| command(step).is_some_and(solidcraft_engine::panels::commands::is_command));
+ let mut results = Vec::with_capacity(steps.len());
+ for (i, step) in steps.iter().enumerate() {
+ let Some(id) = command(step) else {
+ return if panels {
+ Outcome::Done(json!({"ok": false, "error": "missing command", "step": i + 1}))
+ } else {
+ err(format!("script step {}: missing `command`", i + 1))
+ };
+ };
+ match execute(app, id, step_params(step)) {
+ Ok(result) => results.push(result),
+ Err(error) if panels => {
+ let mut reply = json!({"ok": false, "error": error, "step": i + 1});
+ if let Some(reason) = solidcraft_engine::panels::commands::structured_error(&error) {
+ reply["panel_error"] = reason;
+ }
+ return Outcome::Done(reply);
+ }
+ Err(error) => return err(format!("step {} ({id}): {error}", i + 1)),
+ }
+ }
+ ok(json!(results))
+}
+
/// A batch reply with `timings` and `total_ms` when they were asked for.
fn with_timings(mut reply: Value, timed: bool, rows: Vec<Value>, total_ms: f64) -> Value {
if timed && let Some(o) = reply.as_object_mut() {
@@ -791,7 +831,7 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) ->
}
"engine.execute" | "command" => {
let Some(id) = s("command").or(s("id")) else { return err("missing `command`") };
- wrap(execute(app, id, p.get("params").cloned().filter(|v| !v.is_null()).unwrap_or(json!({}))))
+ wrap(execute(app, id, step_params(p)))
}
"engine.batch" => batch(app, p),
"ui.agent_cursor" => {
@@ -810,52 +850,7 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) ->
}
ok(json!(app.ui.agent_cursor))
}
- "engine.script" => {
- let steps = p.as_array().or_else(|| p.get("commands").and_then(Value::as_array));
- if let Some(c) = steps.and_then(|steps| steps.iter().find_map(switches_design)) {
- return err(format!("engine.script unavailable: {c} switches to another design (send it on its own)"));
- }
- if let Some(steps) =
- steps.filter(|steps| steps.iter().any(|step| command(step).is_some_and(solidcraft_engine::panels::commands::is_command)))
- {
- if steps.len() > 100_000 {
- return err("script too long");
- }
- let mut results = Vec::new();
- for (i, step) in steps.iter().enumerate() {
- let result = command(step)
- .ok_or_else(|| "missing command".to_string())
- .and_then(|id| execute(app, id, step.get("params").cloned().filter(|p| !p.is_null()).unwrap_or(json!({}))));
- match result {
- Ok(result) => results.push(result),
- Err(error) => {
- let mut reply = json!({"ok":false,"error":error,"step":i + 1});
- if let Some(reason) = solidcraft_engine::panels::commands::structured_error(&error) {
- reply["panel_error"] = reason;
- }
- return Outcome::Done(reply);
- }
- }
- }
- return ok(json!(results));
- }
- let mut replaced = false;
- let r = app
- .session
- .run_script_each(p, &mut |i, _| {
- let id = steps.and_then(|steps| steps.get(i)).and_then(command).and_then(solidcraft_engine::find_command).map(|spec| spec.id);
- replaced |= matches!(id, Some("file.new" | "doc.open" | "doc.recover"));
- })
- .map(|v| json!(v))
- .map_err(|e| e.to_string());
- // A successful replacement still happened if a later script step failed.
- if replaced {
- crate::documents::reset_chat(app);
- app.edit_in_place.active = None;
- }
- app.follow_view_request(false);
- wrap(r)
- }
+ "engine.script" => script(app, p),
"engine.commands" => wrap(execute(app, "engine.commands", json!({}))),
"document.inspect" => wrap(app.session.execute("document.inspect", p).map_err(|e| e.to_string())),
"document.revision" => wrap(app.session.execute("document.revision", p).map_err(|e| e.to_string())),
@@ -2685,6 +2680,82 @@ mod tests {
assert_eq!(inspect(&mut h)["sketches"].as_array().map(Vec::len), Some(40));
}
+ /// #12629: each step of `engine.script` gets what the window does after the command, as the
+ /// same step of `engine.batch` gets it: the grid, the tool, the spin, a preference, the echo.
+ #[test]
+ fn a_script_step_gets_the_windows_follow_up_like_a_batch_step() {
+ let steps = json!([
+ {"command": "view.grid", "params": {"on": false}},
+ {"command": "view.tool", "params": {"tool": "pan"}},
+ {"command": "view.spin", "params": {"on": true}},
+ {"command": "view.angle_readout", "params": {"enabled": true}},
+ {"command": "sketch.create", "params": {"plane": "XY"}},
+ {"command": "sketch.finish", "params": {}},
+ ]);
+ let window = |method: &str| {
+ let mut h = crate::scenario::Harness::new();
+ // No checkpoint, so the batch runs exactly the script's steps.
+ let v = h.call(method, json!({"commands": steps, "rollback": false}));
+ assert_eq!(v["ok"], true, "{method}: {v}");
+ let app = &h.app;
+ (app.ui.show_grid, app.viewport.nav, app.viewport.spin, app.preferences.show_view_angles, app.session.log.clone())
+ };
+ let batch = window("engine.batch");
+ assert_eq!((batch.0, batch.1, batch.2, batch.3), (false, Some(crate::viewport::NavMode::Pan), true, true));
+ assert_eq!(window("engine.script"), batch);
+ }
+
+ /// The first failing step stops a script, and the steps before it stay with what the window
+ /// did after them: a preference set by step 1 is kept when step 3 fails.
+ #[test]
+ fn a_script_stops_at_its_failing_step_and_keeps_the_ones_before() {
+ let mut h = crate::scenario::Harness::new();
+ assert!(!h.app.preferences.show_view_angles && h.app.ui.show_grid);
+ let v = h.call(
+ "engine.script",
+ json!({"commands": [
+ {"command": "view.angle_readout", "params": {"enabled": true}},
+ {"command": "solid.box", "params": {"length": 10, "width": 10, "height": 10}},
+ {"command": "no.such_command"},
+ {"command": "view.grid", "params": {"on": false}},
+ ]}),
+ );
+ assert_eq!(v["ok"], false, "{v}");
+ assert!(v["error"].as_str().is_some_and(|e| e.starts_with("step 3 (no.such_command): ")), "{v}");
+ assert!(h.app.preferences.show_view_angles, "step 1's preference stays");
+ assert_eq!(inspect(&mut h)["bodies"].as_array().map(Vec::len), Some(1), "step 2's box stays");
+ assert!(h.app.ui.show_grid, "nothing after the failing step ran");
+ let v = h.call("engine.script", json!([{"params": {}}]));
+ assert_eq!(v["error"], "script step 1: missing `command`", "{v}");
+ }
+
+ /// A panel command among a script's steps no longer changes how the other steps run.
+ #[test]
+ fn a_script_with_and_without_a_panel_step_leaves_the_window_alike() {
+ let window = |panel: bool| {
+ let mut app = panel_command_app();
+ let mut steps = vec![
+ json!({"command": "view.grid", "params": {"on": false}}),
+ json!({"command": "view.tool", "params": {"tool": "pan"}}),
+ json!({"command": "view.angle_readout", "params": {"enabled": true}}),
+ ];
+ if panel {
+ steps.push(json!({"command": "layout.get"}));
+ }
+ let v = panel_control(&mut app, "engine.script", json!({"commands": steps}));
+ assert_eq!(v["ok"], true, "{v}");
+ (app.ui.show_grid, app.viewport.nav, app.preferences.show_view_angles)
+ };
+ assert_eq!(window(false), window(true));
+ assert_eq!(window(false), (false, Some(crate::viewport::NavMode::Pan), true));
+ // A failing step of such a script is named by its number, with the panel's own reason.
+ let mut app = panel_command_app();
+ let steps = json!([{"command": "view.grid", "params": {"on": false}}, {"command": "panel.list", "params": {"unknown": true}}]);
+ let v = panel_control(&mut app, "engine.script", json!({"commands": steps}));
+ assert_eq!((&v["ok"], &v["step"], &v["panel_error"]["rule"]), (&json!(false), &json!(2), &json!("schema")), "{v}");
+ assert!(!app.ui.show_grid, "the step before it stays");
+ }
+
/// #5822: `engine.batch {coalesce_parameters}` sets a run of parameter edits together, one
/// rebuild, and answers each step; a refused edit is named by its own step and the batch goes
/// back. Unasked, each edit runs on its own as before.
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 0f03f1c5d0..a7e4ec3f97 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -595,7 +595,7 @@ reply without `param_check` as unchecked. The bridged MCP server asks once per c
| Method | Params | Result |
|---|---|---|
| `engine.execute` | `command`: command id, `params`: JSON object | the command's result |
-| `engine.script` | `commands`: `[{command, params}, …]` | results, stops at the first error |
+| `engine.script` | `commands`: `[{command, params}, …]` | results. Each step runs as `engine.execute` runs it, so the window follows it as it does a batch step. The first error stops the script, and the steps before it stay |
| `engine.batch` | `commands`: `[{command, params}, …]` (at most 10 000), `rollback?`: bool (default true), `timings?`, `profile?`, `coalesce_parameters?`: 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`, when a step loads a file (`doc.open`, `file.insert_step`, `file.insert_mesh`, `pointcloud.insert`, `pointcloud.reload`) or when it goes to another design's tab (`component.edit_in_place`, `component.finish_edit`, which `engine.script` refuses too). Send such steps one by one. A step the batch would certainly refuse at its turn is found before the first step runs (#5853): a step without a command, an unknown command id (with the closest ids) or, with strict parameter checking, a call that breaks its command's contract. The reply is then that step's failure with `completed: 0`, `undone: 0`, `not_run` listing every step and a `note`; nothing has run. With `coalesce_parameters`, each run of consecutive plain parameter edits (`parameters.change` with only a name and an expression, or with `changes`) is set as one `parameters.change {changes}`, so the design rebuilds once for the run. Every step still gets its own result (with `coalesced`: the run's length), and the run is one undo step. The run skips the states between its edits: an edit that would be refused on its own, but not once the run's later edits are in, goes through. A run whose combined edit is refused (a new parameter, a bad expression) runs step by step, so the refused step is named. Answered when done, for up to 3600 s |
| `engine.commands` | — | every command: id, label, tab, panel, icon, shortcut (the user's current first key, or null when cleared), params doc, enabled |
| `document.revision` | — | `{document_id, revision}`: the active design's id and a number that moves whenever the design changes, for programs that follow it ([Following the design](#following-the-design)) |