Skip to content

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

Timeline/MCP API: suppress lists, dotted edit keys, set_parameter expression (#2899)

SS-ENfb82ccb27356
diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs
index 67d682d035..fc8e4b45aa 100644
--- a/crates/engine/src/cmd/edit.rs
+++ b/crates/engine/src/cmd/edit.rs
@@ -25,7 +25,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.at("SOLID", "MODIFY")
.icon("delete")
.key("Delete")
- .params("features: [id or name] (a sketch takes its dependent features with it) → deleted: [ids]; failing?: [{feature, error}] (later features that worked and now fail)"),
+ .params("feature: id|name | features: [id|name] (one undo step; a sketch takes its dependent features with it) → deleted: [ids]; failing?: [{feature, error}] (later features that worked and now fail)"),
CommandSpec::new("timeline.rename", "Rename", rename).icon("rename").params("feature: id|name, name (references to it follow)"),
CommandSpec::new("timeline.group", "New Feature Folder", group)
.icon("folder")
@@ -54,11 +54,15 @@ pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("timeline.dependents", "Feature Dependents", dependents).icon("graph")
.noundo()
.params("feature: id|name → features deleted with it, and features that would fail without it"),
- CommandSpec::new("timeline.suppress", "Suppress Feature", suppress).icon("suppress").params("feature: id|name, suppressed?: bool (default toggles)"),
+ CommandSpec::new("timeline.suppress", "Suppress Feature", suppress).icon("suppress").params(
+ "feature: id|name | features: [id|name] (one undo step), suppressed?: bool (default toggles: several features are all \
+ suppressed unless all of them already are, then all are unsuppressed) → feature: id (or features: [ids]), suppressed",
+ ),
CommandSpec::new("timeline.edit", "Edit Feature", edit_feature).icon("edit").params(
"feature: id|name, set: {fields to change, merged into the feature's definition as timeline.inspect returns it, \
e.g. {\"extent\": {\"distance\": \"30\"}} (extrude), {\"angle\": \"90 deg\"} (revolve); \
- expressions are text} → recomputed: features rebuilt, restored: features whose earlier result for the same inputs was reused",
+ a dotted key names a nested field ({\"plane.distance\": \"8 mm\"} = {\"plane\": {\"distance\": \"8 mm\"}}); \
+ expressions are text, or a number in mm or degrees} → recomputed: features rebuilt, restored: features whose earlier result for the same inputs was reused",
),
CommandSpec::new("timeline.inspect", "Inspect Feature", inspect_feature).icon("inspect").noundo().params(
"feature: id|name → type, definition (the fields timeline.edit's set changes, with their current values), \
@@ -529,12 +533,52 @@ fn rollback(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"marker": s.doc.marker.unwrap_or(n), "features": n}))
}
+/// The features named by `feature: id|name` and/or `features: [id|name]` (or one id|name), in
+/// the order given and without repeats. Each must exist.
+fn feature_ids(s: &Session, p: &Value, cmd: &str) -> Result<Vec<u64>> {
+ let mut given: Vec<&Value> = Vec::new();
+ if let Some(f) = p.get("feature").filter(|v| !v.is_null()) {
+ given.push(f);
+ }
+ match p.get("features") {
+ None | Some(Value::Null) => {}
+ Some(Value::Array(a)) if a.len() <= 10_000 => given.extend(a),
+ Some(Value::Array(_)) => return Err(bad(cmd, "too many features")),
+ Some(one @ (Value::Number(_) | Value::String(_))) => given.push(one),
+ Some(_) => return Err(bad(cmd, "`features` must be a list of feature ids or names")),
+ }
+ if given.is_empty() {
+ return Err(bad(cmd, "`feature` (id or name) or `features` (a list of them) must name a feature"));
+ }
+ let mut ids = Vec::new();
+ for v in given {
+ let id = feature_id(s, Some(v), cmd)?;
+ if !ids.contains(&id) {
+ ids.push(id);
+ }
+ }
+ Ok(ids)
+}
+
fn suppress(s: &mut Session, p: &Value) -> Result<Value> {
- let id = feature_id(s, p.get("feature"), "timeline.suppress")?;
- let want = bool_(p, "suppressed");
- let f = s.doc_mut().feature_mut(id).ok_or_else(|| EngineError::Other("feature".into()))?;
- f.suppressed = want.unwrap_or(!f.suppressed);
- Ok(json!({"feature": id, "suppressed": f.suppressed}))
+ let cmd = "timeline.suppress";
+ let ids = feature_ids(s, p, cmd)?;
+ let want = match bool_(p, "suppressed") {
+ Some(b) => b,
+ None if p.get("suppressed").is_some_and(|v| !v.is_null()) => return Err(bad(cmd, "`suppressed` must be true or false")),
+ // Toggle: one feature flips; several are all suppressed unless all already are.
+ None => !ids.iter().all(|id| s.doc.feature(*id).is_some_and(|f| f.suppressed)),
+ };
+ // One command, so one undo step however many features it changes.
+ let doc = s.doc_mut();
+ for id in &ids {
+ let f = doc.feature_mut(*id).ok_or_else(|| bad(cmd, format!("no feature {id}")))?;
+ f.suppressed = want;
+ }
+ match ids.as_slice() {
+ [id] if p.get("features").is_none_or(Value::is_null) => Ok(json!({"feature": id, "suppressed": want})),
+ _ => Ok(json!({"features": ids, "suppressed": want})),
+ }
}
fn merge(dst: &mut Value, src: &Value, depth: usize) {
@@ -643,17 +687,20 @@ fn unknown_field(
}
/// "unknown field `offset`; ConstructionPlane has `plane.base.name`, `plane.distance`…": the
-/// editable fields where it was given, as paths.
-fn unknown_field_message(field: &[Step], def: &Value, type_name: &str) -> String {
- fn leaves(v: &Value, prefix: &str, top: bool, depth: usize, out: &mut Vec<String>) {
+/// editable fields where it was given, as paths (each one timeline.edit's `set` takes as a key).
+fn unknown_field_message(field: &[Step], def: &Value, kind: &FeatureKind) -> String {
+ let type_name = kind.type_name();
+ let heavy = heavy_fields(kind);
+ let skip = |k: &str| NOT_EDITABLE.contains(&k) || heavy.iter().any(|(h, _)| *h == k);
+ fn leaves(v: &Value, prefix: &str, skip: Option<&dyn Fn(&str) -> bool>, depth: usize, out: &mut Vec<String>) {
match v {
Value::Object(o) if depth < 4 && !o.is_empty() => {
for (k, x) in o {
- if top && NOT_EDITABLE.contains(&k.as_str()) {
+ if skip.is_some_and(|skip| skip(k)) {
continue;
}
let at = if prefix.is_empty() { k.clone() } else { format!("{prefix}.{k}") };
- leaves(x, &at, false, depth + 1, out);
+ leaves(x, &at, None, depth + 1, out);
}
}
_ if !prefix.is_empty() => out.push(format!("`{prefix}`")),
@@ -663,7 +710,8 @@ fn unknown_field_message(field: &[Step], def: &Value, type_name: &str) -> String
let parent = field.split_last().map(|(_, p)| p).unwrap_or_default();
let mut known = Vec::new();
if let Some(at) = at_path(def, parent) {
- leaves(at, &path_text(parent), parent.is_empty(), 0, &mut known);
+ let top: Option<&dyn Fn(&str) -> bool> = if parent.is_empty() { Some(&skip) } else { None };
+ leaves(at, &path_text(parent), top, 0, &mut known);
}
const SHOWN: usize = 40;
let more = known.len().saturating_sub(SHOWN);
@@ -679,6 +727,140 @@ fn unknown_field_message(field: &[Step], def: &Value, type_name: &str) -> String
format!("unknown field `{field}`; {type_name} has {list} (timeline.inspect shows them with their values)")
}
+/// `set` with dotted keys (`"plane.distance"`, as timeline.edit's unknown-field message lists the
+/// fields) expanded into the nested form (`{"plane": {"distance": …}}`), merged with any nested
+/// form given next to them. A key the definition itself has at that level stays as it is. A field
+/// given twice (`plane.distance` and `plane: {distance}`) is refused.
+fn expand_dotted(set: &Value, def: Option<&Value>, cmd: &str, depth: usize) -> Result<Value> {
+ if depth > 16 {
+ return Ok(set.clone());
+ }
+ match set {
+ Value::Object(o) => {
+ let mut nested = serde_json::Map::new();
+ for (k, v) in o {
+ let parts: Vec<&str> = k.split('.').collect();
+ let literal = parts.len() == 1 || parts.len() > 16 || parts.iter().any(|x| x.is_empty()) || def.and_then(|d| d.get(k)).is_some();
+ let parts = if literal { vec![k.as_str()] } else { parts };
+ insert_field(&mut nested, &parts, v.clone(), k, cmd)?;
+ }
+ let mut out = serde_json::Map::new();
+ for (k, v) in nested {
+ let d = def.and_then(|d| d.get(&k));
+ out.insert(k, expand_dotted(&v, d, cmd, depth + 1)?);
+ }
+ Ok(Value::Object(out))
+ }
+ Value::Array(a) => a
+ .iter()
+ .enumerate()
+ .map(|(i, v)| expand_dotted(v, def.and_then(|d| d.get(i)), cmd, depth + 1))
+ .collect::<Result<Vec<_>>>()
+ .map(Value::Array),
+ _ => Ok(set.clone()),
+ }
+}
+
+/// Put `v` at `parts` in `out`, creating the objects on the way; `key` is the field as given.
+fn insert_field(out: &mut serde_json::Map<String, Value>, parts: &[&str], v: Value, key: &str, cmd: &str) -> Result<()> {
+ let twice = || bad(cmd, format!("`{key}` is given twice (as a dotted key and in the nested form)"));
+ let Some((last, parents)) = parts.split_last() else { return Ok(()) };
+ let mut at = out;
+ for part in parents {
+ let slot = at.entry(part.to_string()).or_insert_with(|| Value::Object(serde_json::Map::new()));
+ at = slot.as_object_mut().ok_or_else(twice)?;
+ }
+ match (at.get_mut(*last), v) {
+ (None, v) => {
+ at.insert(last.to_string(), v);
+ }
+ (Some(Value::Object(slot)), Value::Object(more)) => {
+ for (k, x) in more {
+ insert_field(slot, &[k.as_str()], x, key, cmd)?;
+ }
+ }
+ (Some(_), _) => return Err(twice()),
+ }
+ Ok(())
+}
+
+fn at_path_mut<'a>(v: &'a mut Value, path: &[Step]) -> Option<&'a mut Value> {
+ path.iter().try_fold(v, |v, s| match s {
+ Step::Key(k) => v.get_mut(k),
+ Step::Index(i) => v.get_mut(*i),
+ })
+}
+
+/// Paths of the finite numbers in `set` where the definition (`before`) has no number.
+fn number_leaves(set: &Value, before: &Value, path: &mut Vec<Step>, out: &mut Vec<Vec<Step>>, depth: usize) {
+ if depth > 16 || out.len() >= 1_000 {
+ return;
+ }
+ match set {
+ Value::Object(o) => {
+ for (k, v) in o {
+ path.push(Step::Key(k.clone()));
+ number_leaves(v, before, path, out, depth + 1);
+ path.pop();
+ }
+ }
+ Value::Array(a) => {
+ for (i, v) in a.iter().enumerate().take(10_000) {
+ path.push(Step::Index(i));
+ number_leaves(v, before, path, out, depth + 1);
+ path.pop();
+ }
+ }
+ Value::Number(n) if crate::params::number_text(n).is_some() && !matches!(at_path(before, path), Some(Value::Number(_))) => {
+ out.push(path.clone());
+ }
+ _ => {}
+ }
+}
+
+/// Finite numbers given for expression fields become the expression's text (`8` → `"8"`, mm or
+/// degrees by context), as the feature commands take them (`params::expr`). Which fields are
+/// expressions is what the feature's own walk says: each number is put in as a marker text, and
+/// the markers the feature then shows among its expressions are expression fields. Numbers
+/// anywhere else stay numbers.
+fn numbers_as_expressions(mut set: Value, before: &Value) -> Value {
+ let mut found = Vec::new();
+ number_leaves(&set, before, &mut Vec::new(), &mut found, 0);
+ if found.is_empty() {
+ return set;
+ }
+ let marker = |i: usize| format!("\u{1}number {i}");
+ // The markers among the feature's expressions with the numbers at `which` marked, or None
+ // when the feature doesn't read that way.
+ let expressions = |which: &[usize]| -> Option<std::collections::BTreeSet<String>> {
+ let mut marked = set.clone();
+ for &i in which {
+ if let Some(slot) = found.get(i).and_then(|path| at_path_mut(&mut marked, path)) {
+ *slot = Value::String(marker(i));
+ }
+ }
+ let mut v = before.clone();
+ merge(&mut v, &marked, 0);
+ let f: Feature = serde_json::from_value(v).ok()?;
+ Some(f.kind.expressions().into_iter().filter(|e| e.starts_with('\u{1}')).map(str::to_string).collect())
+ };
+ let all: Vec<usize> = (0..found.len()).collect();
+ let hits: Vec<usize> = match expressions(&all) {
+ Some(e) => all.into_iter().filter(|i| e.contains(&marker(*i))).collect(),
+ // Some of them are numbers after all: one at a time.
+ None => all.into_iter().take(64).filter(|i| expressions(&[*i]).is_some_and(|e| e.contains(&marker(*i)))).collect(),
+ };
+ for i in hits {
+ if let Some(slot) = found.get(i).and_then(|path| at_path_mut(&mut set, path))
+ && let Value::Number(n) = slot
+ && let Some(text) = crate::params::number_text(n)
+ {
+ *slot = Value::String(text);
+ }
+ }
+ set
+}
+
/// `profiles` (also a loft section's) given as the feature commands take it (`"all"`,
/// `[index]`, `[{curves}]`, `[{point}]`...) becomes the stored form; the stored form passes.
fn command_profiles(set: &Value, cmd: &str) -> Result<Value> {
@@ -706,6 +888,17 @@ fn command_profiles(set: &Value, cmd: &str) -> Result<Value> {
/// the name and suppression, which timeline.rename and timeline.suppress change.
const NOT_EDITABLE: &[&str] = &["id", "type", "name", "suppressed", "param_names", "edge_refs", "edge_names", "face_names"];
+/// Large payloads that timeline.edit cannot change, left out of a feature's definition: (field,
+/// what it holds).
+fn heavy_fields(kind: &FeatureKind) -> &'static [(&'static str, &'static str)] {
+ match kind {
+ FeatureKind::Sketch { .. } => &[("sketch", "the sketch geometry (sketch.inspect; edit it with the sketch commands)")],
+ FeatureKind::Import { .. } => &[("step", "the imported STEP text"), ("components", "the imported product tree")],
+ FeatureKind::MeshImport { .. } => &[("meshes", "the imported meshes")],
+ _ => &[],
+ }
+}
+
fn inspect_feature(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "timeline.inspect";
let id = feature_id(s, p.get("feature"), cmd)?;
@@ -716,14 +909,7 @@ fn inspect_feature(s: &mut Session, p: &Value) -> Result<Value> {
for k in NOT_EDITABLE {
o.remove(*k);
}
- // Large payloads that timeline.edit cannot change.
- let heavy: &[(&str, &str)] = match &f.kind {
- FeatureKind::Sketch { .. } => &[("sketch", "the sketch geometry (sketch.inspect; edit it with the sketch commands)")],
- FeatureKind::Import { .. } => &[("step", "the imported STEP text"), ("components", "the imported product tree")],
- FeatureKind::MeshImport { .. } => &[("meshes", "the imported meshes")],
- _ => &[],
- };
- for (k, why) in heavy {
+ for (k, why) in heavy_fields(&f.kind) {
if o.remove(*k).is_some() {
omitted.push(json!({"field": k, "what": why}));
}
@@ -754,8 +940,10 @@ fn edit_feature(s: &mut Session, p: &Value) -> Result<Value> {
let id = feature_id(s, p.get("feature"), cmd)?;
let set = p.get("set").filter(|v| v.is_object()).ok_or_else(|| bad(cmd, "`set` must be an object of fields"))?;
let f = s.doc.feature(id).cloned().ok_or_else(|| bad(cmd, "feature"))?;
- let mut v = serde_json::to_value(&f).map_err(|e| EngineError::Other(e.to_string()))?;
- let set = &command_profiles(set, cmd)?;
+ let before = serde_json::to_value(&f).map_err(|e| EngineError::Other(e.to_string()))?;
+ let set = expand_dotted(set, Some(&before), cmd, 0)?;
+ let set = &numbers_as_expressions(command_profiles(&set, cmd)?, &before);
+ let mut v = before.clone();
merge(&mut v, set, 0);
let mut nf: Feature = serde_json::from_value(v.clone()).map_err(|e| bad(cmd, format!("invalid feature: {e}")))?;
nf.id = f.id;
@@ -772,9 +960,8 @@ fn edit_feature(s: &mut Session, p: &Value) -> Result<Value> {
// serde drops fields the definition doesn't have without a word: refuse them, or a typo
// would report success and change nothing.
let after = serde_json::to_value(&nf).map_err(|e| EngineError::Other(e.to_string()))?;
- let before = serde_json::to_value(&f).map_err(|e| EngineError::Other(e.to_string()))?;
if let Some(field) = unknown_field(set, Some(&before), Some(&after), &v, &mut Vec::new(), 0) {
- return Err(bad(cmd, unknown_field_message(&field, &before, f.kind.type_name())));
+ return Err(bad(cmd, unknown_field_message(&field, &before, &f.kind)));
}
if let FeatureKind::BodyTransfer { bodies, from, to, transform } = &nf.kind {
solidcraft_doc::validate_body_transfer(&s.doc, &solidcraft_doc::plain(bodies), *from, *to, transform)?;
diff --git a/crates/engine/src/cmd/edit_tests.rs b/crates/engine/src/cmd/edit_tests.rs
index a5381f3271..9e78e2a140 100644
--- a/crates/engine/src/cmd/edit_tests.rs
+++ b/crates/engine/src/cmd/edit_tests.rs
@@ -544,3 +544,133 @@ fn edit_refuses_unknown_fields() {
let def = run(&mut s, "timeline.inspect", json!({"feature": "Twin"}))["definition"].clone();
assert_eq!(def["combine"], json!(true), "{def}");
}
+
+fn suppressed(s: &Session, name: &str) -> bool {
+ s.doc.find_feature(name).unwrap().suppressed
+}
+
+/// timeline.suppress takes `features: [..]` as timeline.delete does, as one undo step; it used to
+/// refuse it ("`feature` must be an id or name").
+#[test]
+fn suppress_takes_a_list_of_features_as_one_undo_step() {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "name": "A"}));
+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0], "name": "B"}));
+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [40, 0, 0], "name": "C"}));
+ let id = |s: &Session, name: &str| s.doc.find_feature(name).unwrap().id;
+ let undo = s.undo.len();
+ let a = id(&s, "A");
+ let r = run(&mut s, "timeline.suppress", json!({"features": [a, "B"], "suppressed": true}));
+ assert_eq!(r, json!({"features": [id(&s, "A"), id(&s, "B")], "suppressed": true}));
+ assert!(suppressed(&s, "A") && suppressed(&s, "B") && !suppressed(&s, "C"));
+ assert_eq!(s.undo.len(), undo + 1, "one undo step");
+ assert_eq!(s.model.state().bodies.len(), 1);
+ run(&mut s, "edit.undo", json!({}));
+ assert!(!suppressed(&s, "A") && !suppressed(&s, "B"));
+ assert_eq!(s.model.state().bodies.len(), 3);
+
+ // Toggling several: all suppressed unless all already are, then all unsuppressed.
+ run(&mut s, "timeline.suppress", json!({"feature": "A"}));
+ run(&mut s, "timeline.suppress", json!({"features": ["A", "B", "C"]}));
+ assert!(suppressed(&s, "A") && suppressed(&s, "B") && suppressed(&s, "C"));
+ run(&mut s, "timeline.suppress", json!({"features": ["A", "B", "C"]}));
+ assert!(!suppressed(&s, "A") && !suppressed(&s, "B") && !suppressed(&s, "C"));
+ // `feature` and `features` together; a repeat counts once.
+ let r = run(&mut s, "timeline.suppress", json!({"feature": "C", "features": ["C", "B"], "suppressed": true}));
+ assert_eq!(r["features"], json!([id(&s, "C"), id(&s, "B")]), "{r}");
+ assert!(!suppressed(&s, "A") && suppressed(&s, "B") && suppressed(&s, "C"));
+ // A single `feature` replies as before.
+ let r = run(&mut s, "timeline.suppress", json!({"feature": "C", "suppressed": false}));
+ assert_eq!(r, json!({"feature": id(&s, "C"), "suppressed": false}));
+
+ // An unknown feature in the list refuses the whole command, as do no features at all.
+ let before = (*s.doc).clone();
+ let undo = s.undo.len();
+ for bad in [
+ json!({"features": ["A", "Nope"], "suppressed": true}),
+ json!({"features": []}),
+ json!({}),
+ json!({"features": [{}]}),
+ json!({"features": ["A"], "suppressed": "yes"}),
+ ] {
+ assert!(s.execute("timeline.suppress", &bad).is_err(), "{bad}");
+ }
+ assert_eq!(*s.doc, before);
+ assert_eq!(s.undo.len(), undo);
+ // timeline.delete takes either.
+ run(&mut s, "timeline.delete", json!({"feature": "C"}));
+ run(&mut s, "timeline.delete", json!({"features": ["B"]}));
+ assert!(s.doc.find_feature("B").is_none() && s.doc.find_feature("C").is_none());
+}
+
+/// The value at a dotted path of a definition.
+fn dotted<'a>(def: &'a Value, path: &str) -> &'a Value {
+ path.split('.').fold(def, |v, k| &v[k])
+}
+
+/// The lowest Z of the design's first body.
+fn low_z(s: &mut Session) -> f64 {
+ let m = run(s, "inspect.measure", json!({}));
+ let min = &m["bodies"][0]["bbox"]["min"];
+ min[2].as_f64().or_else(|| min["z"].as_f64()).unwrap_or_else(|| panic!("{m}"))
+}
+
+/// timeline.edit takes the dotted keys its unknown-field message lists (`plane.distance`), and
+/// numbers for expressions, as the feature commands do; both used to be refused.
+#[test]
+fn edit_takes_dotted_keys_and_numbers_for_expressions() {
+ let mut s = Session::default();
+ run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 5, "name": "S"}));
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]}));
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "solid.extrude", json!({"distance": 5, "name": "Pad"}));
+ let def = |s: &mut Session, f: &str| run(s, "timeline.inspect", json!({"feature": f}))["definition"].clone();
+
+ run(&mut s, "timeline.edit", json!({"feature": "S", "set": {"plane.distance": "8 mm"}}));
+ assert_eq!(def(&mut s, "S")["plane"]["distance"], json!("8 mm"));
+ assert!((low_z(&mut s) - 8.0).abs() < 1e-9);
+ // A bare number is mm, as in sketch.create's `offset`.
+ run(&mut s, "timeline.edit", json!({"feature": "S", "set": {"plane.distance": 12}}));
+ assert_eq!(def(&mut s, "S")["plane"]["distance"], json!("12"));
+ assert!((low_z(&mut s) - 12.0).abs() < 1e-9);
+ run(&mut s, "timeline.edit", json!({"feature": "S", "set": {"plane": {"distance": 3.5}}}));
+ assert_eq!(def(&mut s, "S")["plane"]["distance"], json!("3.5"));
+ // The nested form works as before.
+ run(&mut s, "timeline.edit", json!({"feature": "S", "set": {"plane": {"distance": "4"}}}));
+ assert!((low_z(&mut s) - 4.0).abs() < 1e-9);
+
+ // Every field the unknown-field message lists is accepted as it is written there.
+ let e = s.execute("timeline.edit", &json!({"feature": "S", "set": {"plane.dist": "1"}})).unwrap_err().to_string();
+ assert!(e.contains("unknown field `plane.dist`") && e.contains("`plane.distance`"), "{e}");
+ let e = s.execute("timeline.edit", &json!({"feature": "S", "set": {"nope": "1"}})).unwrap_err().to_string();
+ let listed: Vec<&str> = e.split('`').skip(3).step_by(2).collect();
+ assert!(listed.contains(&"plane.distance") && listed.contains(&"plane.type"), "{e}");
+ // Not the sketch geometry, which timeline.inspect leaves out and the sketch commands edit.
+ assert!(!listed.iter().any(|k| k.starts_with("sketch")), "{e}");
+ let now = def(&mut s, "S");
+ for key in listed {
+ let value = dotted(&now, key).clone();
+ run(&mut s, "timeline.edit", json!({"feature": "S", "set": {key: value}}));
+ }
+ assert_eq!(def(&mut s, "S"), now);
+
+ // Numbers on an extrude, also for an expression the definition leaves out.
+ run(&mut s, "timeline.edit", json!({"feature": "Pad", "set": {"extent.distance": 20, "extent": {"taper": 0}}}));
+ let d = def(&mut s, "Pad");
+ assert_eq!((&d["extent"]["distance"], &d["extent"]["taper"]), (&json!("20"), &json!("0")), "{d}");
+ let volume = run(&mut s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap();
+ assert!((volume - 2000.0).abs() < 1e-6, "{volume}");
+
+ // Still refused: a field given twice, unknown dotted fields, a number for a name.
+ let before = (*s.doc).clone();
+ for (set, says) in [
+ (json!({"plane.distance": "1", "plane": {"distance": "2"}}), "given twice"),
+ (json!({"plane.wobble": "1"}), "unknown field `plane.wobble`"),
+ (json!({"plane.distance.x": "1"}), "invalid feature"),
+ (json!({"plane.base.name": 5}), "invalid feature"),
+ ] {
+ let e = s.execute("timeline.edit", &json!({"feature": "S", "set": set})).unwrap_err().to_string();
+ assert!(e.contains(says), "{set}: {e}");
+ }
+ assert_eq!(*s.doc, before);
+}
diff --git a/crates/engine/src/params.rs b/crates/engine/src/params.rs
index b05f70a0ec..54a50f353a 100644
--- a/crates/engine/src/params.rs
+++ b/crates/engine/src/params.rs
@@ -58,10 +58,16 @@ pub fn vec2_list(cmd: &str, p: &Value, k: &str, max: usize) -> Result<Vec<Vec2>>
a.iter().map(|v| vec2(v).ok_or_else(|| bad(cmd, format!("`{k}` must contain [x, y] points")))).collect()
}
+/// A finite number given for an expression, as the expression's text (`8` → `"8"`, which reads
+/// as mm or degrees by context).
+pub fn number_text(n: &serde_json::Number) -> Option<String> {
+ n.as_f64().and_then(finite).map(|v| format!("{v}"))
+}
+
/// An expression parameter: a number (mm or degrees by context) or an expression string.
pub fn expr(p: &Value, k: &str) -> Option<Expr> {
match p.get(k)? {
- Value::Number(n) => n.as_f64().and_then(finite).map(|v| Expr::new(format!("{v}"))),
+ Value::Number(n) => number_text(n).map(Expr::new),
Value::String(s) if !s.trim().is_empty() && s.len() <= 4096 => Some(Expr::new(s.trim())),
_ => None,
}
diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs
index 38d637aa54..e60ef2aaef 100644
--- a/crates/mcp/src/tests.rs
+++ b/crates/mcp/src/tests.rs
@@ -293,6 +293,33 @@ fn parameters_drive_the_design() {
assert!(d["params"].as_array().unwrap().iter().any(|p| p["name"] == "len" && p["value"] == 50.0), "{d}");
}
+/// `set_parameter` takes the new value as `value` or as `expression` (the name parameters.change
+/// uses), which it used to refuse instead of forwarding.
+#[test]
+fn set_parameter_takes_value_or_expression() {
+ let mut s = server();
+ let def = tool_definitions().into_iter().find(|d| d["name"] == "set_parameter").unwrap();
+ assert_eq!(def["inputSchema"]["required"], json!(["name"]), "{def}");
+ assert!(def["inputSchema"]["properties"]["expression"].is_object(), "{def}");
+ tool(&mut s, "set_parameter", json!({"name": "len", "expression": "40 mm"}));
+ tool(&mut s, "execute", json!({"command": "solid.box", "params": {"length": "len", "width": 10, "height": 10, "corner": [0, 0, 0]}}));
+ assert!(rel(volume(&mut s), 4000.0) < 1e-9);
+ let r = tool(&mut s, "set_parameter", json!({"name": "len", "expression": 50}));
+ assert_eq!(r["value"], 50.0, "{r}");
+ assert!(rel(volume(&mut s), 5000.0) < 1e-9);
+ // Both, when they agree.
+ let r = tool(&mut s, "set_parameter", json!({"name": "len", "value": 60, "expression": "60"}));
+ assert_eq!(r["value"], 60.0, "{r}");
+ // Both disagreeing, or neither, is an error that changes nothing.
+ for args in [json!({"name": "len", "value": 70, "expression": "80"}), json!({"name": "len"}), json!({"name": "len", "value": null})] {
+ let r = raw_tool(&mut s, "set_parameter", args.clone());
+ assert_eq!(r["result"]["isError"], json!(true), "{args}: {r}");
+ let text = r["result"]["content"][0]["text"].as_str().unwrap_or_default();
+ assert!(text.contains("`value`") && text.contains("`expression`"), "{args}: {text}");
+ }
+ assert!(rel(volume(&mut s), 6000.0) < 1e-9);
+}
+
/// Design properties (#1015) are set through `execute` and come back in `inspect_design`.
#[test]
fn design_properties_show_in_inspect_design() {
diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs
index 7d97daaa7a..8f0c457bc1 100644
--- a/crates/mcp/src/tools.rs
+++ b/crates/mcp/src/tools.rs
@@ -164,16 +164,19 @@ pub fn tool_definitions() -> Vec<Value> {
"set_parameter",
"Set a parameter",
"Create or change a user parameter and re-evaluate the timeline. `value` is a number (mm) or an expression \
- (\"40 mm\", \"width * 2\", \"30 deg\"). Returns the new value, the features recomputed (`recomputed`), the features whose earlier \
- result for the same inputs was reused instead (`restored`, e.g. after setting a value back) and any features that now fail.",
+ (\"40 mm\", \"width * 2\", \"30 deg\"); `expression` is the same thing under the name the parameters.change command \
+ uses. Give one of the two (both only when they agree). Returns the new value, the features recomputed (`recomputed`), the \
+ features whose earlier result for the same inputs was reused instead (`restored`, e.g. after setting a value back) and any \
+ features that now fail.",
obj(
json!({
"name": string("Parameter name"),
- "value": {"type": ["number", "string"], "description": "Number or expression"},
+ "value": {"type": ["number", "string"], "description": "Number or expression (or give it as `expression`)"},
+ "expression": {"type": ["number", "string"], "description": "Same as `value` (the parameters.change name); give one of the two"},
"unit": string("mm, deg or \"\" (unitless); default from the expression"),
"comment": string("Comment shown in the parameters table"),
}),
- &["name", "value"],
+ &["name"],
),
Effect::Edits,
),
@@ -419,7 +422,7 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Map<String, Value>) -> Result<V
}
"set_parameter" => {
let mut p = pick(a, &["name", "unit", "comment"]);
- p["expression"] = a.get("value").cloned().unwrap_or(Value::Null);
+ p["expression"] = parameter_value(a)?;
exec(b, "parameters.change", p)
}
"export" => exec(b, "file.export", pick(a, &["path", "format", "bodies", "mesh_prefix", "effort", "velocity"])),
@@ -436,6 +439,21 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Map<String, Value>) -> Result<V
}
}
+/// `set_parameter`'s new value: `value` or `expression` (the parameters.change name), one of
+/// them, or both when they agree (`50` and `"50"` do).
+fn parameter_value(a: &Map<String, Value>) -> Result<Value, String> {
+ let text = |v: &Value| match v {
+ Value::String(s) => s.trim().to_string(),
+ v => v.to_string(),
+ };
+ match (a.get("value").filter(|v| !v.is_null()), a.get("expression").filter(|v| !v.is_null())) {
+ (Some(v), None) | (None, Some(v)) => Ok(v.clone()),
+ (Some(v), Some(e)) if text(v) == text(e) => Ok(v.clone()),
+ (Some(_), Some(_)) => Err("set_parameter: `value` and `expression` disagree; give one of them".into()),
+ (None, None) => Err("set_parameter: give the new value as `value` (or `expression`): a number (mm) or an expression".into()),
+ }
+}
+
fn undo_depth(b: &mut dyn Backend) -> Option<u64> {
b.call("document.inspect", json!({})).ok().and_then(|d| d["undo"].as_u64())
}
diff --git a/docs/mcp.md b/docs/mcp.md
index 1ddc2063d5..7b15492b28 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -148,7 +148,7 @@ They cover the workflow, the command shapes, how to verify with `measure`, and t
| `inspect_design` | `measure?` (default true), `sketches?` (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), 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: 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`). |
-| `set_parameter` | `name`, `value` (number or expression), `unit?`, `comment?` | Create or change a user parameter and recompute; reports `recomputed` (features rebuilt), `restored` (features whose earlier result for the same inputs was reused, e.g. a value set back) and features that now fail. |
+| `set_parameter` | `name`, `value` or `expression` (number or expression), `unit?`, `comment?` | Create or change a user parameter and recompute. `expression` is another name for `value` (the one `parameters.change` uses): give one of them, or both only when they agree; neither, or two that differ, is an error. Reports `recomputed` (features rebuilt), `restored` (features whose earlier result for the same inputs was reused, e.g. a value set back) and features that now fail. |
| `screenshot` | `view?` (iso, top, front, back, bottom, left, right, home, fit, or a named view saved with `view.save`), `camera?` (`{target, yaw, pitch, distance, fov?}`, as `view.apply`), `path?`, `width?`, `height?`, `source?` (window, model), `grid?`, `axes?` | A PNG image content block. Headless: a render with the viewport's pipelines on a headless GPU device (see `solidcraft-cli gpu`; with no adapter, the CPU rasterizer, without analysis colours), fitted to the model, or from the named view or camera; the reply's `renderer` says which (`gpu`, `gpu-software`, `cpu`, with a `warning` for `cpu`). Bridged: the app window (default) or a model render with the app's camera; a named view or camera moves the app's viewport there first (`execute` `view.apply` does the same without a screenshot). `grid: false` and `axes: false` leave the ground grid (it lies on Z 0 and cuts through a part that straddles it) and the origin's axes out of a model render; axes hidden with `browser.visibility` stay out whatever `axes` says. Bridged, a screenshot that gives `grid` or `axes` is a model render, which follows the app's Grid and Origin switches for what it does not give; `source: "window"` with either is an error. A window that is minimised or on another macOS Space presents no frame: with no `source` the reply is a model render and says so (`fallback`); `source: "window"` is an error saying why, at once. Agents that don't need the app's chrome can ask for `source: "model"`. |
| `export` | `path`, `format?` (step, 3mf, 3mf-tagged, stl, stla, obj, urdf), `bodies?`, `mesh_prefix?`, `effort?`, `velocity?` | STEP, 3MF or mesh export; URDF writes the whole assembly with its meshes next to it (`docs/urdf.md`). |
| `undo`, `redo` | — | Undo / redo one change. |