SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Agents and scripts: Select and Clear Selection describe their exact parameters and reply (#13132) (#13174)
PeppaWutze69dfe126c20
diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rsindex 2859c82621..f8ccde82d3 100644--- a/crates/engine/src/cmd/edit.rs+++ b/crates/engine/src/cmd/edit.rs@@ -17,6 +17,7 @@ use crate::schema::edit::{TimelineReordered, TimelineReorderedMany, TimelineRollToParams, TimelineRollbackParams, TimelineSuppressParams, TimelineSuppressResult,TimelineUngroupParams, TimelineUngrouped,};+use crate::schema::select::{PartialPick, SelectClearParams, SelectClearResult, SelectItem, SelectSetParams, SelectSetResult, read_item};use crate::schema::{TypedContract, output_schema_for};use crate::{EngineError, Result, Sel, Session, Snapshot};@@ -182,16 +183,24 @@ pub static COMMANDS: &[CommandSpec] = &["group: folder id → group, name, parent, features, joints; or feature: id|name → type, definition (the fields timeline.edit's set changes, with their current values), \inputs: [{label, param, expression, unit}] (named inputs parameters.change can also set), error, warning",),- CommandSpec::new("select.set", "Select", select_set).icon("select")+ CommandSpec::new("select.set", "Select", crate::checked!("select.set", select_set)).icon("select").noundo()+ .contract(&SELECT_SET_CONTRACT)+ .output(output_schema_for::<SelectSetResult>).params("items: [{type: body|edge|face|feature|sketch_curve|sketch_point|profile, …}], add?: bool; face/edge: body plus point [x,y,z] in world mm or index (both also accepted); a point uses Measure's pick tolerance, an index supplies a point on the item; invalid partial picks leave the selection unchanged"),CommandSpec::new("select.filter", "Selection filter", select_filter).icon("select").noundo().doc_only().params("mode: body|face|component → validated UI pick granularity; headless echo only, no document edits or undo"),- CommandSpec::new("select.clear", "Clear Selection", select_clear).icon("select").noundo(),+ CommandSpec::new("select.clear", "Clear Selection", crate::checked!("select.clear", select_clear))+ .icon("select")+ .noundo()+ .contract(&SELECT_CLEAR_CONTRACT)+ .output(output_schema_for::<SelectClearResult>),CommandSpec::new("select.same_look", "Select Same Look", select_same_look).icon("select").noundo().doc_only().params("body?: world body name, face?: face index; defaults to the current body/face selection → selects objects using the resolved appearance"),];+const SELECT_SET_CONTRACT: TypedContract<SelectSetParams> = TypedContract::new();+const SELECT_CLEAR_CONTRACT: TypedContract<SelectClearParams> = TypedContract::new();const COMPUTE_ALL_CONTRACT: TypedContract<TimelineComputeAllParams> = TypedContract::new();const DELETE_CONTRACT: TypedContract<TimelineDeleteParams> = TypedContract::new();const RENAME_CONTRACT: TypedContract<TimelineRenameParams> = TypedContract::new();@@ -1446,20 +1455,10 @@ fn edit_feature(s: &mut Session, p: &Value) -> Result<Value> {/// an existing index-and-point pair. Unlike Measure, selection keeps the exact face/edge index:/// it must not merge a cylinder's patches or a circular rim's arcs into a different item.fn selection_item(s: &Session, value: Value) -> Result<Sel> {- use solidcore_record::Vec3;-- let kind = value.get("type").and_then(Value::as_str);- if !matches!(kind, Some("face" | "edge")) || (value.get("index").is_some() && value.get("point").is_some()) {- return serde_json::from_value(value).map_err(|e| bad("select.set", e.to_string()));- }- let face = kind == Some("face");- #[derive(serde::Deserialize)]- struct Pick {- body: String,- index: Option<usize>,- point: Option<Vec3>,- }- let Pick { body, index, point } = serde_json::from_value(value).map_err(|e| bad("select.set", e.to_string()))?;+ let (face, PartialPick { body, index, point }) = match read_item(value).map_err(|e| bad("select.set", e))? {+ SelectItem::Exact(sel) => return Ok(sel),+ SelectItem::Pick { face, pick } => (face, pick),+ };let state = s.world_state()?;let b = state.body(&body).ok_or_else(|| bad("select.set", format!("no body `{body}`")))?;let missing = || bad("select.set", format!("no {} of `{body}` at the given index or point", if face { "face" } else { "edge" }));@@ -1534,7 +1533,7 @@ fn select_set(s: &mut Session, p: &Value) -> Result<Value> {}}s.refresh_display();- Ok(json!({"selected": s.selection.len()}))+ reply("select.set", SelectSetResult { selected: s.selection.len(), param_warnings: Vec::new() })}fn select_filter(_s: &mut Session, p: &Value) -> Result<Value> {@@ -1591,7 +1590,7 @@ fn select_same_look(s: &mut Session, p: &Value) -> Result<Value> {fn select_clear(s: &mut Session, _p: &Value) -> Result<Value> {s.selection.clear();s.refresh_display();- Ok(json!({"selected": 0}))+ reply("select.clear", SelectClearResult { selected: 0, param_warnings: Vec::new() })}/// Features that worked in `before` and fail in `after`: (name, error).diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rsindex 8bfce59734..f207ac17d1 100644--- a/crates/engine/src/schema/mod.rs+++ b/crates/engine/src/schema/mod.rs@@ -101,6 +101,7 @@ pub mod render_stage;pub mod render_surface_resources;pub mod render_ui;pub mod section;+pub mod select;pub mod sheet;pub mod silhouette;pub mod sketch;diff --git a/crates/engine/src/schema/select.rs b/crates/engine/src/schema/select.rsnew file mode 100644index 0000000000..82d2784bf3--- /dev/null+++ b/crates/engine/src/schema/select.rs@@ -0,0 +1,151 @@+//! Contracts and result types for the selection commands in `cmd/edit.rs`: `select.set` and+//! `select.clear`.+//!+//! `select.set` reads `items` and `add` from the raw JSON. Each item reads as the handler reads+//! it ([`read_item`] is the handler's own first step, so a call the handler takes is a call the+//! contract takes): a face or edge with an `index` or a `point` (not both) is read as a partial+//! pick, which the handler completes against the design, and anything else is read as a+//! [`Sel`]. Whether a body, face or edge is there, and how many items are too many, stay the+//! handler's to check. A call with several problems may get a different one first in strict than+//! with the check off (the check goes key by key, the handler item by item against the design).++use std::borrow::Cow;++use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};+use serde::de::Error as _;+use serde::{Deserialize, Deserializer, Serialize};+use serde_json::Value;+use solidcore_record::Vec3;++use super::check::whole;+use crate::Sel;++/// A face or edge picked by an index or a point only, which the handler completes.+#[derive(Debug, Deserialize)]+pub struct PartialPick {+ pub body: String,+ pub index: Option<usize>,+ pub point: Option<Vec3>,+}++/// One item of `select.set`, as the handler first reads it.+#[derive(Debug)]+pub enum SelectItem {+ /// A complete selection item.+ Exact(Sel),+ /// A face (`face` true) or edge given by its body and one of an index or a point.+ Pick { face: bool, pick: PartialPick },+}++/// Read one item of `select.set`; the error is the handler's message. A face or edge that has+/// both `index` and `point` (even `null`) is read as a [`Sel`], so is any other type; a face or+/// edge with at most one of them is read as a [`PartialPick`], which reads only `body`, `index`+/// and `point`.+pub(crate) fn read_item(value: Value) -> Result<SelectItem, String> {+ let kind = value.get("type").and_then(Value::as_str);+ if !matches!(kind, Some("face" | "edge")) || (value.get("index").is_some() && value.get("point").is_some()) {+ return serde_json::from_value(value).map(SelectItem::Exact).map_err(|e| e.to_string());+ }+ let face = kind == Some("face");+ serde_json::from_value(value).map(|pick| SelectItem::Pick { face, pick }).map_err(|e| e.to_string())+}++impl<'de> Deserialize<'de> for SelectItem {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ read_item(Value::deserialize(d)?).map_err(|e| D::Error::custom(whole(e)))+ }+}++/// A point in world mm.+fn point() -> Value {+ serde_json::json!({"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3})+}++impl JsonSchema for SelectItem {+ fn schema_name() -> Cow<'static, str> {+ "SelectItem".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ let text = || serde_json::json!({"type": "string"});+ let count = || serde_json::json!({"type": "integer", "minimum": 0});+ let variant = |kind: &str, what: &str, properties: Value, required: &[&str]| {+ let required: Vec<&str> = std::iter::once("type").chain(required.iter().copied()).collect();+ let mut all = serde_json::json!({"type": {"const": kind}});+ if let (Some(all), Some(properties)) = (all.as_object_mut(), properties.as_object()) {+ all.extend(properties.clone());+ }+ serde_json::json!({"description": what, "type": "object", "properties": all, "required": required})+ };+ let pick = |kind: &str, what: &str| {+ let mut v = variant(kind, what, serde_json::json!({"body": text(), "index": count(), "point": point()}), &["body"]);+ v["anyOf"] = serde_json::json!([{"required": ["index"]}, {"required": ["point"]}]);+ v+ };+ json_schema!({+ "description": "What to select, by `type`. Keys a type doesn't read are ignored. A face or edge needs `body` and an `index` or a `point` (both are accepted); the engine finds the other.",+ "anyOf": [+ variant("body", "A body, by name.", serde_json::json!({"name": text()}), &["name"]),+ pick("face", "A face of a body, by index or by a point on it (world mm, within Measure's pick tolerance)."),+ pick("edge", "An edge of a body, by index or by a point on it (world mm, within Measure's pick tolerance)."),+ variant("vertex", "A vertex of a body, at a point.", serde_json::json!({"body": text(), "point": point()}), &["body", "point"]),+ variant("occurrence", "A placed component, by its path of occurrence ids.", serde_json::json!({"path": {"type": "array", "items": count()}}), &["path"]),+ variant("feature", "A timeline feature, by id.", serde_json::json!({"id": count()}), &["id"]),+ variant("sketch_curve", "A curve of the active sketch, by id; `sketch` names the sketch it is in.", serde_json::json!({"id": text(), "sketch": {"type": ["integer", "null"], "minimum": 0}}), &["id"]),+ variant("sketch_point", "A point of the active sketch, by id.", serde_json::json!({"id": text()}), &["id"]),+ variant("sketch_midpoint", "The midpoint of a line of the active sketch, by id.", serde_json::json!({"id": text()}), &["id"]),+ variant("external_sketch_curve", "A curve of another sketch.", serde_json::json!({"sketch": count(), "id": text()}), &["sketch", "id"]),+ variant("external_sketch_point", "A point of another sketch.", serde_json::json!({"sketch": count(), "id": text()}), &["sketch", "id"]),+ variant("sketch_constraint", "A constraint or dimension of the active sketch, by id.", serde_json::json!({"id": text()}), &["id"]),+ variant("profile", "A closed profile of a sketch, by sketch id and index.", serde_json::json!({"sketch": count(), "index": count()}), &["sketch", "index"]),+ variant("plane", "An origin plane (XY, XZ, YZ) or a construction plane, by name.", serde_json::json!({"name": text()}), &["name"]),+ variant("construction_point", "A construction point, by feature name.", serde_json::json!({"name": text()}), &["name"]),+ variant("axis", "An origin axis (X, Y, Z) or a construction axis, by name.", serde_json::json!({"name": text()}), &["name"])+ ]+ })+ }+}++/// Make what is selected the given items, or add them to it. Nothing changes when an item is+/// refused. A body, face or edge must exist in the design; a body or occurrence that isn't there+/// is refused. At most 10,000 items. Not an undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct SelectSetParams {+ /// What to select. Default: none (the selection is cleared, or left as it is with `add`).+ /// A face or edge may give just an `index` or just a `point`; the engine fills in the other.+ #[serde(default)]+ pub items: Option<Vec<SelectItem>>,+ /// Add to the current selection instead of replacing it. Items already selected are not+ /// added twice. Default: false.+ #[serde(default)]+ pub add: Option<bool>,+}++/// What `select.set` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct SelectSetResult {+ /// How many items are selected now.+ pub selected: usize,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub param_warnings: Vec<String>,+}++/// `select.clear` takes no parameters: it deselects everything. Not an undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct SelectClearParams {}++/// What `select.clear` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct SelectClearResult {+ /// How many items are selected now: always 0.+ pub selected: usize,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub param_warnings: Vec<String>,+}++#[cfg(test)]+#[path = "select_tests.rs"]+mod tests;diff --git a/crates/engine/src/schema/select_tests.rs b/crates/engine/src/schema/select_tests.rsnew file mode 100644index 0000000000..9e3c93e791--- /dev/null+++ b/crates/engine/src/schema/select_tests.rs@@ -0,0 +1,223 @@+use serde_json::{Value, json};++use super::{SelectClearParams, SelectClearResult, SelectItem, SelectSetParams, SelectSetResult, read_item};+use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};+use crate::schema::{ParamCheck, input_schema_for, output_schema_for};+use crate::{Sel, Session};++#[test]+fn schemas_and_the_key_check_agree() {+ assert_keys(input_schema_for::<SelectSetParams>(), &["add", "items"]);+ assert_keys(input_schema_for::<SelectClearParams>(), &[]);+}++/// Strict gives the handler's message for the items it refuses on their own.+#[test]+fn strict_keeps_todays_errors() {+ assert_strict_keeps_todays_errors(&[+ ("select.set", json!({"items": [{"type": "bogus"}]})),+ ("select.set", json!({"items": [{}]})),+ ("select.set", json!({"items": [7]})),+ ("select.set", json!({"items": [{"type": "body"}]})),+ ("select.set", json!({"items": [{"type": "body", "name": 5}]})),+ ("select.set", json!({"items": [{"type": "feature", "id": -1}]})),+ ("select.set", json!({"items": [{"type": "occurrence", "path": "1"}]})),+ ("select.set", json!({"items": [{"type": "face"}]})),+ ("select.set", json!({"items": [{"type": "face", "body": "Box1"}]})),+ ("select.set", json!({"items": [{"type": "face", "index": 0}]})),+ ("select.set", json!({"items": [{"type": "edge", "body": "Box1", "index": -1}]})),+ ("select.set", json!({"items": [{"type": "edge", "body": "Box1", "point": [1, 2]}]})),+ ("select.set", json!({"items": [{"type": "edge", "body": "Box1", "index": 0, "point": null}]})),+ ("select.set", json!({"items": [{"type": "face", "body": "Box1", "index": null, "point": [1, 2, 3]}]})),+ ("select.set", json!({"items": [{"type": "body", "name": "Missing"}]})),+ ("select.set", json!({"items": [{"type": "face", "body": "Missing", "point": [1, 2, 3]}]})),+ ]);+}++/// The item type reads each item as the handler does: face and edge items with one of `index`+/// and `point` are partial picks, everything else a `Sel`.+#[test]+fn the_item_type_reads_like_the_handler() {+ let item = |v: Value| serde_json::from_value::<SelectItem>(v);+ assert!(matches!(item(json!({"type": "body", "name": "A", "colour": 1})), Ok(SelectItem::Exact(_))));+ assert!(matches!(item(json!({"type": "face", "body": "A", "index": 2})), Ok(SelectItem::Pick { face: true, .. })));+ assert!(matches!(item(json!({"type": "edge", "body": "A", "point": [1, 2, 3], "extra": 1})), Ok(SelectItem::Pick { face: false, .. })));+ assert!(matches!(item(json!({"type": "edge", "body": "A", "point": null})), Ok(SelectItem::Pick { .. })));+ // Neither: the handler refuses it against the design, after it has looked up the body.+ assert!(matches!(item(json!({"type": "face", "body": "A"})), Ok(SelectItem::Pick { .. })));+ assert!(matches!(item(json!({"type": "face", "body": "A", "index": 2, "point": [1, 2, 3]})), Ok(SelectItem::Exact(_))));+ assert!(matches!(item(json!({"type": "sketch_curve", "id": "c1"})), Ok(SelectItem::Exact(_))));+ assert!(matches!(item(json!({"type": "profile", "sketch": 3, "index": 0})), Ok(SelectItem::Exact(_))));+ // Both given: read whole, as a Sel, so a null refuses.+ assert!(item(json!({"type": "face", "body": "A", "index": 2, "point": null})).is_err());+ assert!(item(json!({"type": "face", "index": 2})).is_err());+ assert!(item(json!({"type": "face", "body": "A", "index": "2"})).is_err());+ assert!(item(json!({"type": "nothing"})).is_err() && item(json!(null)).is_err() && item(json!("body")).is_err());+ // The messages are the handler's (what serde says), whole.+ for bad in [json!({"type": "nothing"}), json!({"type": "face"}), json!({"type": "body"}), json!(3)] {+ let handler = read_item(bad.clone()).err().unwrap_or_default();+ let typed = item(bad.clone()).err().map(|e| e.to_string()).unwrap_or_default();+ assert!(typed.ends_with(&handler), "{bad}: {typed} / {handler}");+ }+}++/// The schema takes what the type takes, and the keys the params type reads.+#[test]+fn the_schemas_take_what_the_handler_reads() {+ let check = |schema: schemars::Schema, cases: &[(Value, bool)]| {+ let schema = schema.as_value().clone();+ for (p, takes) in cases {+ assert_eq!(conforms(&schema, &schema, p), *takes, "{p}");+ }+ };+ let cases = [+ (json!({}), true),+ (json!({"items": []}), true),+ (json!({"items": null, "add": null}), true),+ (json!({"items": [{"type": "body", "name": "A"}], "add": true}), true),+ (json!({"items": [{"type": "face", "body": "A", "index": 1}, {"type": "edge", "body": "A", "point": [1, 2, 3]}]}), true),+ (json!({"items": [{"type": "face", "body": "A", "index": 1, "point": [1, 2, 3]}]}), true),+ (json!({"items": [{"type": "plane", "name": "XY"}, {"type": "occurrence", "path": [1, 2]}, {"type": "feature", "id": 4}]}), true),+ (json!({"items": [{"type": "sketch_curve", "id": "c1", "sketch": 2}, {"type": "profile", "sketch": 2, "index": 0}]}), true),+ (json!({"items": [{"type": "face", "body": "A"}]}), false),+ (json!({"items": [{"type": "bogus"}]}), false),+ (json!({"items": [{"type": "body"}]}), false),+ (json!({"items": "A"}), false),+ (json!({"add": "yes"}), false),+ (json!({"item": []}), false),+ ];+ check(input_schema_for::<SelectSetParams>(), &cases);+ check(input_schema_for::<SelectClearParams>(), &[(json!({}), true), (json!({"add": true}), false)]);+ // The schema differs from the type in two cases: a face or edge with neither `index` nor+ // `point`, which the type leaves to the handler (its message depends on the design), and an+ // unknown key, which the key check reports, not the type.+ let apart = [json!({"items": [{"type": "face", "body": "A"}]}), json!({"item": []})];+ for (p, takes) in cases.iter().filter(|(p, _)| !apart.contains(p)) {+ assert_eq!(serde_json::from_value::<SelectSetParams>(p.clone()).is_ok(), *takes, "{p}");+ }+}++/// Real calls of both commands in Warn: no warnings, and the replies match the output schemas+/// and are what the handlers have always returned. A misspelt key gets its warning and the+/// reply still matches; strict refuses it.+#[test]+fn replies_match_the_output_schema() {+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };+ s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10, "body_name": "Box1"})).unwrap();+ s.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "corner": [30, 0, 0], "body_name": "Box2"})).unwrap();+ let matches = |schema: schemars::Schema, r: &Value| {+ let schema = schema.as_value();+ assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");+ };+ let run = |s: &mut Session, id: &str, p: Value| {+ let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));+ assert!(r.get("param_warnings").is_none(), "{id} {p}: {r}");+ r+ };+ let set = |s: &mut Session, p: Value| {+ let r = run(s, "select.set", p);+ matches(output_schema_for::<SelectSetResult>(), &r);+ r+ };+ assert_eq!(set(&mut s, json!({})), json!({"selected": 0}));+ assert_eq!(set(&mut s, json!({"items": [{"type": "body", "name": "Box1"}]})), json!({"selected": 1}));+ assert_eq!(set(&mut s, json!({"items": [{"type": "body", "name": "Box2"}], "add": true})), json!({"selected": 2}));+ assert_eq!(set(&mut s, json!({"items": [{"type": "body", "name": "Box2"}], "add": true})), json!({"selected": 2}));+ assert_eq!(set(&mut s, json!({"items": null})), json!({"selected": 0}));+ assert_eq!(set(&mut s, json!({"items": [{"type": "face", "body": "Box1", "index": 0}], "add": null})), json!({"selected": 1}));+ assert_eq!(+ set(&mut s, json!({"items": [{"type": "face", "body": "Box1", "point": [5, 5, 10]}, {"type": "edge", "body": "Box1", "index": 0}]})),+ json!({"selected": 2})+ );+ let complete = s.selection[0].clone();+ assert_eq!(set(&mut s, json!({"items": [complete, {"type": "plane", "name": "XY", "colour": "red"}], "add": true})), json!({"selected": 3}));+ let r = run(&mut s, "select.clear", json!({}));+ matches(output_schema_for::<SelectClearResult>(), &r);+ assert_eq!(r, json!({"selected": 0}));+ assert!(s.selection.is_empty());+ // A misspelt key runs in warn and says so; the reply still matches.+ let p = json!({"items": [{"type": "body", "name": "Box1"}], "ad": true});+ let r = s.execute("select.set", &p).unwrap();+ assert!(r["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{r}");+ assert_eq!(r["selected"], 1);+ matches(output_schema_for::<SelectSetResult>(), &r);+ let r = s.execute("select.clear", &json!({"all": true})).unwrap();+ assert!(r["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{r}");+ matches(output_schema_for::<SelectClearResult>(), &r);+ s.param_check = ParamCheck::Strict;+ let error = s.execute("select.set", &p).err().map(|e| e.to_string()).unwrap_or_default();+ assert!(error.contains("`ad`"), "{error}");+ let error = s.execute("select.clear", &json!({"all": true})).err().map(|e| e.to_string()).unwrap_or_default();+ assert!(error.contains("`all`"), "{error}");+}++/// One item of every `Sel` variant, as `Sel` serializes it (and the forms it also reads): each is+/// a `Sel`, is read by the item type, matches the item schema, and is accepted in strict.+#[test]+fn every_selection_kind_is_taken() {+ let items = [+ json!({"type": "occurrence", "path": [1, 2]}),+ json!({"type": "body", "name": "A"}),+ json!({"type": "edge", "body": "A", "index": 1, "point": [1, 2, 3]}),+ json!({"type": "face", "body": "A", "index": 1, "point": [1, 2, 3]}),+ json!({"type": "feature", "id": 4}),+ json!({"type": "sketch_curve", "id": "c1"}),+ json!({"type": "sketch_curve", "id": "c1", "sketch": 2}),+ json!({"type": "sketch_curve", "id": "c1", "sketch": null}),+ json!({"type": "sketch_point", "id": "p1"}),+ json!({"type": "sketch_midpoint", "id": "l1"}),+ json!({"type": "external_sketch_curve", "sketch": 2, "id": "c1"}),+ json!({"type": "external_sketch_point", "sketch": 2, "id": "p1"}),+ json!({"type": "sketch_constraint", "id": "k1"}),+ json!({"type": "profile", "sketch": 2, "index": 0}),+ json!({"type": "plane", "name": "XY"}),+ json!({"type": "construction_point", "name": "P"}),+ json!({"type": "axis", "name": "X"}),+ json!({"type": "vertex", "body": "A", "point": [0, 0, 0]}),+ ];+ let schema = input_schema_for::<SelectSetParams>();+ let schema = schema.as_value();+ // `conforms` doesn't check `const`, so each item is also matched to the branch of its `type`.+ let branches = schema["$defs"]["SelectItem"]["anyOf"].as_array().cloned().unwrap_or_default();+ assert!(!branches.is_empty(), "no SelectItem branches in {schema}");+ // Every branch is one of the kinds listed here.+ for b in &branches {+ assert!(items.iter().any(|i| i["type"] == b["properties"]["type"]["const"]), "{b} isn't tried");+ }+ for item in items {+ assert!(serde_json::from_value::<Sel>(item.clone()).is_ok(), "{item} isn't a Sel");+ assert!(serde_json::from_value::<SelectItem>(item.clone()).is_ok(), "{item}");+ let kind = item["type"].as_str().unwrap_or_default();+ let branch = branches.iter().find(|b| b["properties"]["type"]["const"] == kind);+ assert!(branch.is_some_and(|b| conforms(schema, b, &item)), "no `{kind}` branch takes {item}");+ let p = json!({"items": [item]});+ assert!(conforms(schema, schema, &p), "{p} doesn't match {schema}");+ }+}++/// Valid calls are not refused in Strict, and a wrong-typed `items` or `add`, which the handler+/// reads as if left out, is reported in Warn and refused in Strict.+#[test]+fn strict_takes_valid_calls_and_warn_reports_wrong_types() {+ let mut s = Session { param_check: ParamCheck::Strict, ..Session::default() };+ s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10, "body_name": "Box1"})).unwrap();+ for p in [+ json!({}),+ json!({"items": null, "add": null}),+ json!({"items": [{"type": "body", "name": "Box1"}], "add": true}),+ json!({"items": [{"type": "face", "body": "Box1", "index": 0}]}),+ json!({"items": [{"type": "edge", "body": "Box1", "point": [0, 0, 0]}], "add": true}),+ json!({"items": [{"type": "plane", "name": "XY", "colour": "red"}]}),+ ] {+ let r = s.execute("select.set", &p).unwrap_or_else(|e| panic!("{p}: {e}"));+ assert!(r.get("param_warnings").is_none(), "{p}: {r}");+ }+ assert_eq!(s.execute("select.clear", &json!({})).unwrap(), json!({"selected": 0}));+ for p in [json!({"items": "Box1"}), json!({"add": "yes"})] {+ s.param_check = ParamCheck::Warn;+ let r = s.execute("select.set", &p).unwrap();+ assert!(r["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{p}: {r}");+ s.param_check = ParamCheck::Strict;+ assert!(s.execute("select.set", &p).is_err(), "{p}");+ }+}diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txtindex 5b0995e3e0..68ef83d206 100644--- a/crates/engine/src/schema/unconverted.txt+++ b/crates/engine/src/schema/unconverted.txt@@ -34,8 +34,6 @@ render.result.regraderender.scenerender.startrender.status-select.clear-select.setsheet.export_bend_tablesheet.export_dxfsheet.flat_pattern