diff --git a/crates/engine/src/batch_params.rs b/crates/engine/src/batch_params.rs new file mode 100644 index 000000000..5763013a7 --- /dev/null +++ b/crates/engine/src/batch_params.rs @@ -0,0 +1,191 @@ +//! Parameter edits in a batch, rebuilt once (#5822). +//! +//! An agent often sends a batch of `parameters.change` steps, one parameter each. Every step +//! evaluates the design again, and an edit early in the timeline rebuilds nearly all of it: a +//! batch of 21 such edits ran for minutes. `parameters.change {changes}` sets several parameters +//! with one rebuild. With `coalesce_parameters`, a batch runner sends each run of consecutive +//! plain edits (a name and an expression, or `changes`) as one such step. When that combined +//! step is refused (a step makes a new parameter, which `changes` can't; an expression is +//! wrong), the runner runs the run's steps one by one as before, so a refused edit is still +//! named by its own step. Any other step (a sketch, an extrude, a rename) ends a run, so it sees +//! the design up to date. A run skips the states between its edits: an edit refused on its own +//! can go through together with the run's later edits. + +use serde_json::{Map, Value, json}; + +/// How a batch's steps run. +#[derive(Clone, Debug, PartialEq)] +pub enum BatchRun { + /// One step as it is (its index). + Step(usize), + /// Consecutive plain parameter edits (their indices, at least two) as one + /// `parameters.change {changes}`: the parameters and expressions they set, the later of two + /// for one parameter. + Params { steps: Vec, changes: Map }, +} + +/// A step's command id (`command`, or `id` as the control channel also takes). +fn command(step: &Value) -> Option<&str> { + step.get("command").or_else(|| step.get("id")).and_then(Value::as_str) +} + +/// The parameters a plain `parameters.change` step sets, with their expressions: `{name, +/// expression}` (or `value`), or `{changes}`. `None` for any other step or form (a rename, a +/// unit, a comment, a deletion), which then runs as it is. +fn plain_edit(step: &Value) -> Option> { + if command(step)? != "parameters.change" { + return None; + } + let p = step.get("params")?.as_object()?; + let expression = |v: &Value| matches!(v, Value::Number(_) | Value::String(_)); + if let Some(changes) = p.get("changes") { + let changes = changes.as_object().filter(|c| !c.is_empty() && c.values().all(expression))?; + return (p.len() == 1).then(|| changes.clone()); + } + let name = p.get("name")?.as_str()?.trim(); + let e = p.get("expression").or_else(|| p.get("value")).filter(|e| expression(e))?; + let plain = p.keys().all(|k| matches!(k.as_str(), "name" | "expression" | "value")) && !name.is_empty(); + plain.then(|| Map::from_iter([(name.to_string(), e.clone())])) +} + +/// How `steps` run: each on its own, or with `coalesce` each run of two or more consecutive +/// plain parameter edits as one. +pub fn plan(steps: &[Value], coalesce: bool) -> Vec { + let mut out = Vec::new(); + let mut run: Vec<(usize, Map)> = Vec::new(); + let flush = |run: &mut Vec<(usize, Map)>, out: &mut Vec| match run.len() { + 0 => {} + 1 => out.extend(run.drain(..).map(|(i, _)| BatchRun::Step(i))), + _ => { + let mut changes = Map::new(); + let mut indices = Vec::with_capacity(run.len()); + for (i, edit) in run.drain(..) { + indices.push(i); + // A later edit of a parameter replaces an earlier one, as it would have. + for (name, e) in edit { + changes.remove(&name); + changes.insert(name, e); + } + } + out.push(BatchRun::Params { steps: indices, changes }); + } + }; + for (i, step) in steps.iter().enumerate() { + match plain_edit(step).filter(|_| coalesce) { + Some(edit) => run.push((i, edit)), + None => { + flush(&mut run, &mut out); + out.push(BatchRun::Step(i)); + } + } + } + flush(&mut run, &mut out); + out +} + +/// The combined step: `parameters.change {changes}`. +pub fn combined_params(changes: &Map) -> Value { + json!({"changes": changes}) +} + +/// Each step's result from the combined step's `result`: what it set, the value now, and what +/// the one rebuild did (`coalesced`: how many steps it took). In the steps' order. +pub fn step_results(steps: &[Value], indices: &[usize], result: &Value) -> Vec { + let changed = result.get("changed").and_then(Value::as_object); + indices + .iter() + .map(|i| { + let set = steps.get(*i).and_then(plain_edit).unwrap_or_default(); + let values: Map = + set.keys().map(|n| (n.clone(), changed.and_then(|c| c.get(n)).cloned().unwrap_or(Value::Null))).collect(); + let mut r = json!({ + "changed": values, + "coalesced": indices.len(), + "recomputed": result.get("recomputed").cloned().unwrap_or(Value::Null), + "restored": result.get("restored").cloned().unwrap_or(Value::Null), + "errors": result.get("errors").cloned().unwrap_or(Value::Null), + }); + // A one-parameter step answers as `parameters.change {name, expression}` does. + if let (Some((name, e)), 1) = (set.iter().next(), set.len()) + && let Some(o) = r.as_object_mut() + { + o.insert("name".into(), json!(name)); + o.insert("expression".into(), e.clone()); + o.insert("value".into(), values.get(name).cloned().unwrap_or(Value::Null)); + } + r + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn edit(name: &str, e: Value) -> Value { + json!({"command": "parameters.change", "params": {"name": name, "expression": e}}) + } + + #[test] + fn runs_of_plain_edits_join_and_anything_else_ends_them() { + let steps = vec![ + edit("a", json!("2 mm")), + edit("b", json!(3)), + json!({"command": "solid.box", "params": {"length": 1, "width": 1, "height": 1}}), + edit("c", json!("4")), + json!({"id": "parameters.change", "params": {"changes": {"d": "5", "a": "6 mm"}}}), + edit("a", json!("7 mm")), + json!({"command": "parameters.change", "params": {"name": "e", "new_name": "f"}}), + edit("g", json!("1")), + ]; + let got = plan(&steps, true); + let mut changes = Map::new(); + changes.insert("c".into(), json!("4")); + changes.insert("d".into(), json!("5")); + changes.insert("a".into(), json!("7 mm")); + let mut first = Map::new(); + first.insert("a".into(), json!("2 mm")); + first.insert("b".into(), json!(3)); + assert_eq!( + got, + vec![ + BatchRun::Params { steps: vec![0, 1], changes: first }, + BatchRun::Step(2), + BatchRun::Params { steps: vec![3, 4, 5], changes }, + BatchRun::Step(6), + BatchRun::Step(7), + ] + ); + // Off (the default): every step on its own. + assert_eq!(plan(&steps, false), (0..steps.len()).map(BatchRun::Step).collect::>()); + } + + #[test] + fn edits_with_more_than_a_name_and_an_expression_run_as_they_are() { + for params in [ + json!({"name": "a", "expression": "1", "unit": "mm"}), + json!({"name": "a", "expression": "1", "comment": "x"}), + json!({"name": "a", "expression": [1]}), + json!({"delete": "a"}), + json!({"changes": {}}), + json!({"changes": {"a": "1"}, "unit": "mm"}), + json!({"name": " ", "expression": "1"}), + ] { + let steps = vec![edit("b", json!("1")), json!({"command": "parameters.change", "params": params}), edit("c", json!("1"))]; + assert_eq!(plan(&steps, true), vec![BatchRun::Step(0), BatchRun::Step(1), BatchRun::Step(2)], "{params}"); + } + } + + #[test] + fn each_step_gets_its_own_result() { + let steps = vec![edit("a", json!("2 mm")), json!({"command": "parameters.change", "params": {"changes": {"b": "3", "c": "4"}}})]; + let result = json!({"changed": {"a": 2.0, "b": 3.0, "c": 4.0}, "recomputed": 5, "restored": 0, "errors": []}); + let rows = step_results(&steps, &[0, 1], &result); + assert_eq!(rows[0]["name"], "a"); + assert_eq!(rows[0]["value"], 2.0); + assert_eq!(rows[0]["coalesced"], 2); + assert_eq!(rows[1]["changed"], json!({"b": 3.0, "c": 4.0})); + assert_eq!(rows[1]["recomputed"], 5); + assert!(rows[1].get("name").is_none()); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 56ec782c8..9fe13e714 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -7,6 +7,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] +pub mod batch_params; pub mod capture; pub mod cmd; pub mod control_auth; diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 3d82bfc11..b391ae4ec 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -497,6 +497,73 @@ fn batch_stops_at_first_error_and_rolls_back() { assert_eq!(tool(&mut s, "measure", json!({}))["body_count"], 2); } +/// #5822: with `coalesce_parameters` a batch of parameter edits, one per step, rebuilds the +/// design once for the run, and every step still has its own result. A run with an edit +/// `changes` can't make (a new parameter) goes step by step, and a refused edit is still named +/// by its own step. +#[test] +fn batch_coalesces_parameter_edits() { + let mut s = server(); + let mut build = vec![json!({"command": "solid.box", "params": {"length": 100, "width": 100, "height": 5, "body_name": "Plate"}})]; + for i in 0..5 { + build.push(json!({"command": "parameters.add", "params": {"name": format!("h{i}"), "expression": "5 mm"}})); + build.push(json!({"command": "solid.cylinder", "params": {"radius": 3, "height": format!("h{i}"), "base": [i * 15 - 30, 0, 5], "operation": "join"}})); + } + tool(&mut s, "batch", json!({"commands": build})); + let edits: Vec = (0..5) + .map(|i| json!({"command": "parameters.change", "params": {"name": format!("h{i}"), "expression": format!("{} mm", 10 + i)}})) + .collect(); + let r = tool(&mut s, "batch", json!({"commands": edits, "coalesce_parameters": true})); + let results = r["results"].as_array().unwrap(); + assert_eq!(results.len(), 5, "{r}"); + for (i, row) in results.iter().enumerate() { + assert_eq!(row["name"], format!("h{i}"), "{row}"); + assert_eq!(row["coalesced"], 5, "{row}"); + assert_eq!(row["value"], json!(10.0 + i as f64), "{row}"); + } + // The plate and five pins, as tall as the new parameters make them. + let pins: f64 = (0..5).map(|i| std::f64::consts::PI * 9.0 * (10.0 + f64::from(i))).sum(); + let v = tool(&mut s, "measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap(); + assert!((v - (100.0 * 100.0 * 5.0 + pins)).abs() < 1e-3 * v, "{v}"); + // The same edits step by step on a second design end in the same design and values. + let mut t = server(); + tool(&mut t, "batch", json!({"commands": build})); + let one_by_one = tool(&mut t, "batch", json!({"commands": edits})); + for (a, b) in results.iter().zip(one_by_one["results"].as_array().unwrap()) { + assert_eq!((&a["name"], &a["value"]), (&b["name"], &b["value"]), "{a} vs {b}"); + } + let w = tool(&mut t, "measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap(); + assert!((v - w).abs() < 1e-9 * w, "coalesced {v}, step by step {w}"); + let list = |s: &mut Server| tool(s, "execute", json!({"command": "parameters.list", "params": {"filter": "user"}})); + assert_eq!(list(&mut s), list(&mut t)); + // A new parameter in the run: the run goes step by step and still sets everything. + let r = tool( + &mut s, + "batch", + json!({"coalesce_parameters": true, "commands": [ + {"command": "parameters.change", "params": {"name": "h0", "expression": "6 mm"}}, + {"command": "parameters.change", "params": {"name": "spare", "expression": "2 mm"}}, + ]}), + ); + assert_eq!(r["results"].as_array().map(Vec::len), Some(2), "{r}"); + assert!(r["results"][0].get("coalesced").is_none(), "{r}"); + // A refused edit is named by its own step, and the batch goes back. + let r = raw_tool( + &mut s, + "batch", + json!({"coalesce_parameters": true, "commands": [ + {"command": "parameters.change", "params": {"name": "h1", "expression": "7 mm"}}, + {"command": "parameters.change", "params": {"name": "h2", "expression": "1 +"}}, + ]}), + ); + let body: Value = serde_json::from_str(r["result"]["content"][0]["text"].as_str().unwrap()).unwrap(); + assert_eq!(body["failed"]["index"], 1, "{body}"); + assert_eq!(body["rolled_back"], true, "{body}"); + let rows = tool(&mut s, "execute", json!({"command": "parameters.list", "params": {"filter": "user"}})); + let h1 = rows.to_string(); + assert!(h1.contains("11 mm"), "h1 kept its value after the refused batch: {h1}"); +} + /// Regression: with a full undo history a failed batch reported `undone: 0` and left its /// sketches behind (an empty "Sketch1", two sketches named "TapHole"). #[test] diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 8104a29fc..6157ccded 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -126,6 +126,7 @@ pub fn tool_definitions() -> Vec { "items": {"type": "object", "properties": {"command": {"type": "string"}, "params": {"type": "object"}}, "required": ["command"]}, }, "rollback": {"type": "boolean", "description": "Undo completed steps when one fails (default true)"}, + "coalesce_parameters": {"type": "boolean", "description": "Set each run of consecutive plain parameter edits (parameters.change or set_parameter with a name and a value, or changes) together, rebuilding the design once for the run instead of once per edit; a run that is refused goes step by step, naming the refused step. Other steps still see the design up to date. Each step keeps its own result; the run is one undo step (default false)"}, "timings": {"type": "boolean", "description": "Add `timings`: [{index, command, ms}] for every step run (the failing one included) and `total_ms` (default false)"}, "profile": {"type": "boolean", "description": "Like timings, and each step's `profile`: {boolean_ms, tessellate_ms, other_ms}, its time in kernel booleans, in tessellation and the rest (default false)"}, "verbose": {"type": "boolean", "description": "false: a compact reply. Feature steps leave out the full body list (created_bodies, changed_bodies and removed_bodies stay), sketch steps the ids they repeat outside `created` (default true)"}, @@ -797,7 +798,11 @@ fn batch(b: &mut dyn Backend, a: &Map) -> Value { // An app that runs batches itself answers the whole batch in one request, so one frame // (#743). One too long for a control line goes step by step: the app would refuse it unrun. // The margin covers the envelope and the `allow_paths` the backend adds. + let coalesce = a.get("coalesce_parameters").and_then(Value::as_bool).unwrap_or(false); let mut params = json!({"commands": steps, "rollback": rollback}); + if coalesce && let Some(o) = params.as_object_mut() { + o.insert("coalesce_parameters".into(), Value::Bool(true)); + } if timed && let Some(o) = params.as_object_mut() { o.insert("timings".into(), Value::Bool(true)); o.insert("profile".into(), Value::Bool(profile)); @@ -835,46 +840,68 @@ fn batch(b: &mut dyn Backend, a: &Map) -> Value { let clock = timing::Clock::start(); // The kernel's share can only be measured where the commands run: in this process. let profile = profile && b.in_process(); - for (i, step) in steps.iter().enumerate() { - let command = step.get("command").or_else(|| step.get("id")).and_then(Value::as_str); - let (r, took) = timing::time(profile, || match command { - Some(id) => exec(b, id, step.get("params").cloned().filter(|p| !p.is_null()).unwrap_or(json!({}))), - None => Err("missing `command`".to_string()), - }); - if timed { - rows.push(took.to_json(i, command.unwrap_or_default())); - } - match r { - Ok(v) => { - let v = narrow(i, v); - results.push(if verbose { v } else { compact(v) }) + // With `coalesce_parameters`, each run of plain parameter edits as one edit (#5822); a run + // whose combined edit is refused goes step by step. + for run in solidcraft_engine::batch_params::plan(steps, coalesce) { + let singles = match run { + solidcraft_engine::batch_params::BatchRun::Step(i) => vec![i], + solidcraft_engine::batch_params::BatchRun::Params { steps: indices, changes } => { + let (r, took) = timing::time(profile, || exec(b, "parameters.change", solidcraft_engine::batch_params::combined_params(&changes))); + match r { + Ok(v) => { + if timed { + rows.push(took.to_json(indices.first().copied().unwrap_or(0), "parameters.change")); + } + let rows = solidcraft_engine::batch_params::step_results(steps, &indices, &v); + results.extend(rows.into_iter().map(|v| if verbose { v } else { compact(v) })); + continue; + } + Err(_) => indices, + } } - Err(e) => { - // A step still running in the app was not cancelled: the rollback first waits for - // it (the backend does), so a restored checkpoint takes it back too. - let running = e.starts_with(STILL_RUNNING); - let (went_back, undone) = start.rollback(b, i); - // Only a rollback asked for is reported as one. - let rolled_back = rollback && went_back; - let mut failed = json!({"index": i, "command": command, "error": e}); - // Applied: the steps before it, unless rolled back; and the step itself while it - // still runs, as it will apply when it finishes. - let mut applied: Vec = if rolled_back { Vec::new() } else { (0..i).collect() }; - if running && !rolled_back { - failed["still_running"] = json!(true); - applied.push(i); + }; + for i in singles { + let Some(step) = steps.get(i) else { continue }; + let command = step.get("command").or_else(|| step.get("id")).and_then(Value::as_str); + let (r, took) = timing::time(profile, || match command { + Some(id) => exec(b, id, step.get("params").cloned().filter(|p| !p.is_null()).unwrap_or(json!({}))), + None => Err("missing `command`".to_string()), + }); + if timed { + rows.push(took.to_json(i, command.unwrap_or_default())); + } + match r { + Ok(v) => { + let v = narrow(i, v); + results.push(if verbose { v } else { compact(v) }) + } + Err(e) => { + // A step still running in the app was not cancelled: the rollback first waits for + // it (the backend does), so a restored checkpoint takes it back too. + let running = e.starts_with(STILL_RUNNING); + let (went_back, undone) = start.rollback(b, i); + // Only a rollback asked for is reported as one. + let rolled_back = rollback && went_back; + let mut failed = json!({"index": i, "command": command, "error": e}); + // Applied: the steps before it, unless rolled back; and the step itself while it + // still runs, as it will apply when it finishes. + let mut applied: Vec = if rolled_back { Vec::new() } else { (0..i).collect() }; + if running && !rolled_back { + failed["still_running"] = json!(true); + applied.push(i); + } + let reply = json!({ + "ok": false, + "completed": i, + "failed": failed, + "rolled_back": rolled_back, + "undone": undone, + "applied": applied, + "not_run": (i + 1..steps.len()).collect::>(), + "results": results, + }); + return text_result(&with_timings(reply, timed, rows, clock.ms()), true); } - let reply = json!({ - "ok": false, - "completed": i, - "failed": failed, - "rolled_back": rolled_back, - "undone": undone, - "applied": applied, - "not_run": (i + 1..steps.len()).collect::>(), - "results": results, - }); - return text_result(&with_timings(reply, timed, rows, clock.ms()), true); } } } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 9685ec85c..0cd7098b4 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -46,7 +46,7 @@ use std::sync::mpsc::Sender; use serde_json::{Value, json}; use solidcraft_engine::io::vfs; use solidcraft_engine::render::StandardView; -use solidcraft_engine::timing; +use solidcraft_engine::{batch_params, timing}; use crate::SolveApp; @@ -195,23 +195,44 @@ fn batch(app: &mut SolveApp, p: &Value) -> Outcome { let clock = timing::Clock::start(); let checkpoint = if rollback { app.run("edit.checkpoint", json!({})).ok().and_then(|v| v["checkpoint"].as_u64()) } else { None }; let mut results = Vec::with_capacity(steps.len()); - for (i, step) in steps.iter().enumerate() { - 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!({}))), - None => Err("missing `command`".to_string()), - }); - if timed { - rows.push(took.to_json(i, command(step).unwrap_or_default())); - } - match r { - Ok(v) => results.push(v), - Err(e) => { - let restored = checkpoint.is_some_and(|id| app.run("edit.restore_checkpoint", json!({"checkpoint": id})).is_ok()); - let failed = json!({"index": i, "command": command(step), "error": e}); - // `rolled_back`: the design really is back at its checkpoint. - let reply = - json!({"completed": i, "results": results, "failed": failed, "undone": if restored { i } else { 0 }, "rolled_back": restored}); - return ok(with_timings(reply, timed, rows, clock.ms())); + // With `coalesce_parameters`, each run of plain parameter edits rebuilds once (#5822); a run + // whose combined edit is refused goes step by step, so a refused edit is named by its step. + let coalesce = p.get("coalesce_parameters").and_then(Value::as_bool).unwrap_or(false); + for run in batch_params::plan(steps, coalesce) { + let singles = match run { + batch_params::BatchRun::Step(i) => vec![i], + batch_params::BatchRun::Params { steps: indices, changes } => { + let (r, took) = timing::time(profile, || execute(app, "parameters.change", batch_params::combined_params(&changes))); + match r { + Ok(v) => { + if timed { + rows.push(took.to_json(indices.first().copied().unwrap_or(0), "parameters.change")); + } + results.extend(batch_params::step_results(steps, &indices, &v)); + continue; + } + Err(_) => indices, + } + } + }; + 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!({}))), + None => Err("missing `command`".to_string()), + }); + if timed { + rows.push(took.to_json(i, command(step).unwrap_or_default())); + } + match r { + Ok(v) => results.push(v), + Err(e) => { + let restored = checkpoint.is_some_and(|id| app.run("edit.restore_checkpoint", json!({"checkpoint": id})).is_ok()); + let failed = json!({"index": i, "command": command(step), "error": e}); + // `rolled_back`: the design really is back at its checkpoint. + let reply = json!({"completed": i, "results": results, "failed": failed, "undone": if restored { i } else { 0 }, "rolled_back": restored}); + return ok(with_timings(reply, timed, rows, clock.ms())); + } } } } @@ -1257,6 +1278,44 @@ mod tests { assert_eq!(inspect(&mut h)["sketches"].as_array().map(Vec::len), Some(40)); } + /// #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. + #[test] + fn engine_batch_coalesces_parameter_edits_when_asked() { + let mut h = crate::scenario::Harness::new(); + let build = json!([ + {"command": "parameters.add", "params": {"name": "w", "expression": "10 mm"}}, + {"command": "parameters.add", "params": {"name": "d", "expression": "10 mm"}}, + {"command": "solid.box", "params": {"length": "w", "width": "d", "height": 10}}, + ]); + assert_eq!(batch(&mut h, json!({"commands": build}))["ok"], true); + let edits = json!([ + {"command": "parameters.change", "params": {"name": "w", "expression": "20 mm"}}, + {"command": "parameters.change", "params": {"name": "d", "expression": "30 mm"}}, + ]); + let v = batch(&mut h, json!({"commands": edits, "coalesce_parameters": true})); + let results = v["result"]["results"].as_array().unwrap(); + assert_eq!(results.len(), 2, "{v}"); + assert!(results.iter().all(|r| r["coalesced"] == 2), "{v}"); + assert_eq!(results[1]["value"], 30.0, "{v}"); + let volume = |h: &mut crate::scenario::Harness| { + h.call("engine.execute", json!({"command": "inspect.measure", "params": {}}))["result"]["total"]["volume_mm3"].as_f64() + }; + assert!(volume(&mut h).is_some_and(|v| (v - 6000.0).abs() < 1e-6)); + let bad = json!([ + {"command": "parameters.change", "params": {"name": "w", "expression": "5 mm"}}, + {"command": "parameters.change", "params": {"name": "d", "expression": "1 +"}}, + ]); + let v = batch(&mut h, json!({"commands": bad, "coalesce_parameters": true})); + assert_eq!(v["result"]["failed"]["index"], 1, "{v}"); + assert_eq!(v["result"]["rolled_back"], true, "{v}"); + assert!(volume(&mut h).is_some_and(|v| (v - 6000.0).abs() < 1e-6), "the batch went back"); + // Unasked: one result per edit, none coalesced. + let v = batch(&mut h, json!({"commands": edits})); + assert!(v["result"]["results"].as_array().unwrap().iter().all(|r| r.get("coalesced").is_none()), "{v}"); + } + /// #1833: `engine.batch` times its steps where they run, the failing one included, with the /// kernel's share when `profile` asks; unasked, the reply is as before. #[test] diff --git a/crates/ui-egui/src/control_job.rs b/crates/ui-egui/src/control_job.rs index 1089791a3..3268e0afb 100644 --- a/crates/ui-egui/src/control_job.rs +++ b/crates/ui-egui/src/control_job.rs @@ -260,13 +260,22 @@ fn ahead_commands(method: &str, p: &Value) -> Vec<(String, Value)> { return Vec::new(); } let Some(steps) = p.get("commands").and_then(Value::as_array) else { return Vec::new() }; - steps - .iter() - .map_while(|step| { - let command = step.get("command").or_else(|| step.get("id")).and_then(Value::as_str)?; - let params = step.get("params").cloned().filter(|v| !v.is_null()).unwrap_or(json!({})); - computes_ahead(command, ¶ms).then(|| (command.to_string(), params)) + // As the batch will run them: with `coalesce_parameters`, a run of parameter edits + // as one edit (#5822). + let coalesce = p.get("coalesce_parameters").and_then(Value::as_bool).unwrap_or(false); + solidcraft_engine::batch_params::plan(steps, coalesce) + .into_iter() + .map(|run| match run { + solidcraft_engine::batch_params::BatchRun::Step(i) => { + let step = steps.get(i)?; + let command = step.get("command").or_else(|| step.get("id")).and_then(Value::as_str)?; + Some((command.to_string(), step.get("params").cloned().filter(|v| !v.is_null()).unwrap_or(json!({})))) + } + solidcraft_engine::batch_params::BatchRun::Params { changes, .. } => { + Some(("parameters.change".to_string(), solidcraft_engine::batch_params::combined_params(&changes))) + } }) + .map_while(|c| c.filter(|(command, params)| computes_ahead(command, params))) .collect() } _ => Vec::new(), diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 2e789cd51..b0d8daf00 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -132,7 +132,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, `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.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`, 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. 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, 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) | diff --git a/docs/mcp.md b/docs/mcp.md index a21dfd55c..fd0c76471 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -207,7 +207,7 @@ The `skill_reference` tool returns these documents from the copies built into So | `list_commands` | `filter?` | The command catalog: id, label, tab/panel, shortcut, parameter docs, enabled now. `filter` matches id, label, tab and panel. | | `describe_command` | `id` | One command's parameter docs (`params`) and, for commands with a typed contract (`solid.box`, `solid.extrude` and `engine.describe` so far), the JSON Schemas (2020-12) of its parameters (`input`) and of a successful result (`output`); `null` for the others. The same as `execute` `engine.describe {command}`. | | `execute` | `command`, `params?`, `verbose?` (default true) | Run any command with JSON parameters (`list_commands` shows them). Failures leave the design unchanged. A feature command replies with the feature (`feature`, `name`), every body (`bodies`) and the bodies it created, changed and removed (`created_bodies`, `changed_bodies`, `removed_bodies`). `verbose: false` uses the same compact reply as `batch`. | -| `batch` | `commands: [{command, params}]`, `rollback?` (default true), `verbose?` (default true), `timings?`, `profile?` (default false) | Run steps in order, stop at the first error and undo the completed steps. The reply names the failing step (`failed.index`, `failed.command`, `failed.error`), every result before it, `rolled_back` (true only when the design really went back to where the batch started), `undone`, `applied` (the indices of the steps whose changes are in the design) and `not_run` (the steps never sent). A step may name a tool instead of a command, with that tool's arguments as `params`: `set_parameter` (runs `parameters.change`; `value` or `expression`), `list_commands` (`engine.commands`, filtered by `filter` as the tool filters it), `describe_command` (`engine.describe`), `execute` (`{command, params}`), `measure`, `inspect_design` (`document.inspect`: each sketch as its counts, not its full contents, and no joints), `undo`, `redo`, `export`, `save`, `open`, `new_design` and `crash_reports`. `screenshot`, `body_topology` (use `model.edges` and `model.faces`), `batch`, `pending`, `running` and `skill_reference` can't be steps: such a batch fails before anything is sent. `verbose: false` keeps the reply small in large designs: feature steps leave out the full body list (`created_bodies`, `changed_bodies`, `removed_bodies` stay) and sketch steps the ids they repeat outside `created`. Bridged to an app that has `engine.batch`, the whole batch is one control request (one frame of the app). Older apps, and apps showing the agent cursor, get the steps one by one. `timings: true` adds `timings: [{index, command, ms}]` for every step run, the failing one included, and `total_ms`. `profile: true` also adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`, its time in kernel booleans, in tessellation and the rest. Steps are timed where they run: in the app when bridged. An app without `engine.batch` is timed step by step, without `profile`. | +| `batch` | `commands: [{command, params}]`, `rollback?` (default true), `verbose?` (default true), `timings?`, `profile?`, `coalesce_parameters?` (default false) | Run steps in order, stop at the first error and undo the completed steps. The reply names the failing step (`failed.index`, `failed.command`, `failed.error`), every result before it, `rolled_back` (true only when the design really went back to where the batch started), `undone`, `applied` (the indices of the steps whose changes are in the design) and `not_run` (the steps never sent). A step may name a tool instead of a command, with that tool's arguments as `params`: `set_parameter` (runs `parameters.change`; `value` or `expression`), `list_commands` (`engine.commands`, filtered by `filter` as the tool filters it), `describe_command` (`engine.describe`), `execute` (`{command, params}`), `measure`, `inspect_design` (`document.inspect`: each sketch as its counts, not its full contents, and no joints), `undo`, `redo`, `export`, `save`, `open`, `new_design` and `crash_reports`. `screenshot`, `body_topology` (use `model.edges` and `model.faces`), `batch`, `pending`, `running` and `skill_reference` can't be steps: such a batch fails before anything is sent. `verbose: false` keeps the reply small in large designs: feature steps leave out the full body list (`created_bodies`, `changed_bodies`, `removed_bodies` stay) and sketch steps the ids they repeat outside `created`. Bridged to an app that has `engine.batch`, the whole batch is one control request (one frame of the app). Older apps, and apps showing the agent cursor, get the steps one by one. `timings: true` adds `timings: [{index, command, ms}]` for every step run, the failing one included, and `total_ms`. `profile: true` also adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`, its time in kernel booleans, in tessellation and the rest. Steps are timed where they run: in the app when bridged. An app without `engine.batch` is timed step by step, without `profile`. `coalesce_parameters: true` sets each run of consecutive plain parameter edits (`parameters.change` or `set_parameter` with a name and a value, or `changes`) together, so the design rebuilds once per run instead of once per edit. Steps between runs see the design up to date. Each step keeps its own result (`coalesced`: the run's length), and the run is one undo step. The run skips the states between its edits, so an edit refused on its own can go through with the run's later ones. A refused run goes step by step, naming the refused step. | | `inspect_design` | `measure?` (default true), `sketches?` (default true), `joints?` (default true) | Design properties (`metadata`: project, author… and other tools' keys; set them with `execute` `document.metadata.set`), parameters, timeline (type, suppressed, rolled back, error, warning, timing), bodies (volume, area, centre of mass, bbox, face/edge/vertex counts, visible; `removed_later: true` while a sketch is being edited on a rolled-back timeline and a later feature deletes the body, which is then not shown), sketches (curves, points, constraints, profiles, DOF, solve status, visible), joints when the design has any (as `joint.inspect` gives them: each origin's occurrence, component and path, the snap as saved, the feature, face, edge or sketch curve (`sketch: {id, name, curve}`) its persistent names refer to, `resolves` and the `error` when it is lost; kind, offset, angle, flip, values, limits, expressions, motion links; `execute` `joint.inspect {joint}` gives one joint), selection, undo depth. Hide helper sketches, bodies or construction planes with `execute` `browser.visibility` (`{items, visible}` or `{folder, visible}`), and joint glyphs with `{joints: [id or name], visible}` or `{folder: "joints", visible}` (a hidden joint still constrains and drives; `joint.list` reports each joint's `visible`). | | `measure` | `body?` or `items?` | Volume (mm³), area (mm²), centre of mass, bbox and topology counts per body, with totals. With `items` (one or two selections as `execute` takes them: `face`, `edge`, `vertex`, `sketch_curve`, `profile`), the picked geometry instead: faces and edges need only `type`, `body` and `point`; `index` is optional. See below. | | `body_topology` | `body` | Edges (index, midpoint, length, ends) and faces (index, name, area, centroid, normal, `point`, and for a cylindrical face its `cylinder`: `origin`, `axis`, `radius`). An edge midpoint is the `[x,y,z]` that picks that edge for fillet and chamfer. A face's `point` lies on it and picks it (its centroid may not: that of a face with a hole is in the hole); a face's `name` picks it for the commands that take faces (`face.delete`, `solid.shell`, `solid.draft`, `solid.offset_face`, `solid.split_face`, `solid.replace_face`, and `face` of `sheet.convert`). |