SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Agents and scripts: Motion Study, List and Delete describe their exact parameters and reply (#12155) (#12156)
austin62jake146a43f38e13
diff --git a/crates/engine/src/cmd/motion.rs b/crates/engine/src/cmd/motion.rsindex 6f6927634c..93a7d29824 100644--- a/crates/engine/src/cmd/motion.rs+++ b/crates/engine/src/cmd/motion.rs@@ -16,7 +16,8 @@ use super::joints::{cannot_move, effective_values, joint_id, occurrence_id, placuse crate::params::{bad, bool_, str_, vec3};use crate::schema::motion::{ContactCheck, ContactCollision, ContactCreateParams, ContactEditParams, ContactEnableParams, ContactNoParams, ContactSetChange,- ContactSetCreated, ContactSetEdited, ContactSetInfo, ContactSets, ContactSwitch, FindLimitsParams, FindLimitsResult,+ ContactSetCreated, ContactSetEdited, ContactSetInfo, ContactSets, ContactSwitch, FindLimitsParams, FindLimitsResult, MotionListParams,+ MotionStudies, MotionStudyDeleteParams, MotionStudyDeleted, MotionStudyInfo, MotionStudyKeyInfo, MotionStudyParams, MotionStudySaved,};use crate::schema::{TypedContract, output_schema_for};use crate::{EngineError, Result, Session};@@ -46,6 +47,9 @@ const CONTACT_ENABLE_CONTRACT: TypedContract<ContactEnableParams> = TypedContracconst CONTACT_NONE_CONTRACT: TypedContract<ContactNoParams> = TypedContract::new();const CONTACT_CREATE_CONTRACT: TypedContract<ContactCreateParams> = TypedContract::new();const CONTACT_EDIT_CONTRACT: TypedContract<ContactEditParams> = TypedContract::new();+const STUDY_CONTRACT: TypedContract<MotionStudyParams> = TypedContract::new();+const STUDY_DELETE_CONTRACT: TypedContract<MotionStudyDeleteParams> = TypedContract::new();+const STUDY_LIST_CONTRACT: TypedContract<MotionListParams> = TypedContract::new();pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("contact.enable_sets", "Enable Contact Sets", crate::checked!("contact.enable_sets", enable_sets))@@ -92,10 +96,15 @@ pub static COMMANDS: &[CommandSpec] = &[.contract(&CONTACT_NONE_CONTRACT).output(output_schema_for::<ContactCheck>).params("→ pairs in contact sets that pass through each other now"),- CommandSpec::new("motion.study", "Motion Study", study).at("SOLID", "ASSEMBLE").icon("play").params(- "name?; study? (edit an existing one); steps? (timeline length, default 100); keys: [{joint, index?, points: [[step, value], …]}] \+ CommandSpec::new("motion.study", "Motion Study", crate::checked!("motion.study", study))+ .at("SOLID", "ASSEMBLE")+ .icon("play")+ .contract(&STUDY_CONTRACT)+ .output(output_schema_for::<MotionStudySaved>)+ .params(+ "name?; study? (edit an existing one); steps? (timeline length, default 100); keys: [{joint, index?, points: [[step, value], …]}] \(values: degrees for angles, mm for distances, or expressions)",- ),+ ),CommandSpec::new("motion.play", "Play Motion Study", play).icon("play").params("study: id|name; step (0…steps) — sets the joints to the study's values there (contact sets stop them); quiet?: bool \(positions of only the occurrences that moved) → values: [{joint, values: [{name, value, unit}]}], positions, moved: whether \@@ -145,8 +154,16 @@ pub static COMMANDS: &[CommandSpec] = &[.contract(&FIND_LIMITS_CONTRACT).output(output_schema_for::<FindLimitsResult>).params(sweep::FIND_LIMITS_DOC),- CommandSpec::new("motion.list", "List Motion Studies", list_studies).icon("list").noundo(),- CommandSpec::new("motion.delete", "Delete Motion Study", delete_study).icon("delete").params("study"),+ CommandSpec::new("motion.list", "List Motion Studies", crate::checked!("motion.list", list_studies))+ .icon("list")+ .noundo()+ .contract(&STUDY_LIST_CONTRACT)+ .output(output_schema_for::<MotionStudies>),+ CommandSpec::new("motion.delete", "Delete Motion Study", crate::checked!("motion.delete", delete_study))+ .icon("delete")+ .contract(&STUDY_DELETE_CONTRACT)+ .output(output_schema_for::<MotionStudyDeleted>)+ .params("study"),CommandSpec::new("explode.create", "Exploded View", explode_create).at("SOLID", "ASSEMBLE").icon("explode").enabled(has_parts_to_explode).params("name?; scale? (automatic: each occurrence pushed away from the assembly's centre by scale × its offset, default 1); \moves?: [{occurrence, translate: [x,y,z]}] (instead of automatic)",@@ -557,30 +574,30 @@ pub fn drive_joint_index(s: &mut Session, id: u64, q: Vec<f64>, index: usize) ->Ok(drive_with_contact(s, &[(id, q)], &[(id, index)].into_iter().collect())?.0)}-/// A contact command's reply as JSON: they build their replies from the types their output-/// schemas describe, so the two can't drift apart.-fn contact_reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {+/// A command's reply as JSON: the contact and motion study commands build their replies from the+/// types their output schemas describe, so the two can't drift apart.+fn typed_reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))}fn enable_sets(s: &mut Session, p: &Value) -> Result<Value> {let enabled = bool_(p, "enabled").unwrap_or(true);s.doc_mut().assembly.contact_enabled = enabled;- contact_reply("contact.enable_sets", ContactSwitch { enabled, all: None, param_warnings: Vec::new() })+ typed_reply("contact.enable_sets", ContactSwitch { enabled, all: None, param_warnings: Vec::new() })}fn enable_all(s: &mut Session, _p: &Value) -> Result<Value> {let a = &mut s.doc_mut().assembly;a.contact_enabled = true;a.contact_all = true;- contact_reply("contact.enable_all", ContactSwitch { enabled: true, all: Some(true), param_warnings: Vec::new() })+ typed_reply("contact.enable_all", ContactSwitch { enabled: true, all: Some(true), param_warnings: Vec::new() })}fn disable_all(s: &mut Session, _p: &Value) -> Result<Value> {let a = &mut s.doc_mut().assembly;a.contact_enabled = false;a.contact_all = false;- contact_reply("contact.disable_all", ContactSwitch { enabled: false, all: None, param_warnings: Vec::new() })+ typed_reply("contact.disable_all", ContactSwitch { enabled: false, all: None, param_warnings: Vec::new() })}fn new_set(s: &mut Session, p: &Value) -> Result<Value> {@@ -598,7 +615,7 @@ fn new_set(s: &mut Session, p: &Value) -> Result<Value> {let a = &mut s.doc_mut().assembly;a.contact_sets.push(ContactSet { id, name: name.clone(), occurrences: occ, suppressed: false });a.contact_enabled = true;- contact_reply(cmd, ContactSetCreated { set: id, name, param_warnings: Vec::new() })+ typed_reply(cmd, ContactSetCreated { set: id, name, param_warnings: Vec::new() })}fn set_index(s: &Session, p: &Value, cmd: &str) -> Result<usize> {@@ -620,7 +637,7 @@ fn edit_set(s: &mut Session, p: &Value) -> Result<Value> {let i = set_index(s, p, cmd)?;if bool_(p, "delete").unwrap_or(false) {s.doc_mut().assembly.contact_sets.remove(i);- return contact_reply(cmd, ContactSetEdited { change: ContactSetChange::Deleted { deleted: true }, param_warnings: Vec::new() });+ return typed_reply(cmd, ContactSetEdited { change: ContactSetChange::Deleted { deleted: true }, param_warnings: Vec::new() });}let occ = if p.get("occurrences").is_some() { Some(occurrences(s, p, cmd)?) } else { None };if occ.as_ref().is_some_and(|o| o.len() < 2) {@@ -637,18 +654,18 @@ fn edit_set(s: &mut Session, p: &Value) -> Result<Value> {c.suppressed = x;}let set = c.id;- contact_reply(cmd, ContactSetEdited { change: ContactSetChange::Changed { set }, param_warnings: Vec::new() })+ typed_reply(cmd, ContactSetEdited { change: ContactSetChange::Changed { set }, param_warnings: Vec::new() })}fn list_sets(s: &mut Session, _p: &Value) -> Result<Value> {let a = &s.doc.assembly;let sets = a.contact_sets.iter().map(ContactSetInfo::from).collect();- contact_reply("contact.list", ContactSets { enabled: a.contact_enabled, all: a.contact_all, sets, param_warnings: Vec::new() })+ typed_reply("contact.list", ContactSets { enabled: a.contact_enabled, all: a.contact_all, sets, param_warnings: Vec::new() })}fn check(s: &mut Session, _p: &Value) -> Result<Value> {let collisions = collisions(s).into_iter().map(|(a, b, depth_mm)| ContactCollision { a, b, depth_mm }).collect();- contact_reply("contact.check", ContactCheck { collisions, param_warnings: Vec::new() })+ typed_reply("contact.check", ContactCheck { collisions, param_warnings: Vec::new() })}// ---- Motion studies ----@@ -737,7 +754,7 @@ fn study(s: &mut Session, p: &Value) -> Result<Value> {m}};- Ok(json!({"study": out.id, "name": out.name, "steps": out.steps, "keys": out.keys.len()}))+ typed_reply(cmd, MotionStudySaved { study: out.id, name: out.name, steps: out.steps, keys: out.keys.len(), param_warnings: Vec::new() })}/// Joint values of a study at a step: (joint, full value vector).@@ -1079,36 +1096,37 @@ fn keep_sampled_trace(}fn list_studies(s: &mut Session, _p: &Value) -> Result<Value> {- let studies: Vec<Value> = s.doc.assembly.studies.iter().map(|m| study_json(s, m)).collect();- Ok(json!({"studies": studies, "traces": associative::list(s)}))+ let studies = s.doc.assembly.studies.iter().map(|m| study_info(s, m)).collect();+ typed_reply("motion.list", MotionStudies { studies, traces: associative::list(s), param_warnings: Vec::new() })}/// A study as `motion.list` gives it: key values in the units `motion.study` takes — degrees/// for angles, mm for distances, like `joint.list`'s values — each key with its joint's name,/// so a listed study can be fed back to `motion.study` unchanged.-fn study_json(s: &Session, m: &MotionStudy) -> Value {- let keys: Vec<Value> = m+fn study_info(s: &Session, m: &MotionStudy) -> MotionStudyInfo {+ let keys = m.keys.iter().map(|k| {let joint = s.doc.assembly.joints.iter().find(|j| j.id == k.joint);let angle = joint.is_some_and(|j| j.kind.is_angle(k.index));- json!({- "joint": k.joint,- "joint_name": joint.map(|j| j.name.clone()).unwrap_or_else(|| k.joint.to_string()),- "index": k.index,- "unit": if angle { "deg" } else { "mm" },- "points": k.points.iter().map(|(step, v)| json!([step, if angle { v.to_degrees() } else { *v }])).collect::<Vec<_>>(),- })+ MotionStudyKeyInfo {+ joint: k.joint,+ joint_name: joint.map(|j| j.name.clone()).unwrap_or_else(|| k.joint.to_string()),+ index: k.index,+ unit: if angle { "deg" } else { "mm" }.into(),+ points: k.points.iter().map(|(step, v)| [*step, if angle { v.to_degrees() } else { *v }]).collect(),+ }}).collect();- json!({"id": m.id, "name": m.name, "steps": m.steps, "keys": keys})+ MotionStudyInfo { id: m.id, name: m.name.clone(), steps: m.steps, keys }}fn delete_study(s: &mut Session, p: &Value) -> Result<Value> {- let i = study_index(s, p, "motion.delete")?;+ let cmd = "motion.delete";+ let i = study_index(s, p, cmd)?;let m = s.doc_mut().assembly.studies.remove(i);- Ok(json!({"deleted": m.name}))+ typed_reply(cmd, MotionStudyDeleted { deleted: m.name, param_warnings: Vec::new() })}// ---- Exploded views ----diff --git a/crates/engine/src/cmd/motion_tests.rs b/crates/engine/src/cmd/motion_tests.rsindex eca7cc1aeb..e2fd641d05 100644--- a/crates/engine/src/cmd/motion_tests.rs+++ b/crates/engine/src/cmd/motion_tests.rs@@ -16,6 +16,13 @@ fn occ(s: &Session, component: &str) -> u64 {s.doc.occurrence_of(c).map(|o| o.id).unwrap_or(0)}+/// The call that deletes item `id` with `delete`: Edit Contact Set deletes with `delete: true`;+/// Delete Motion Study and Delete Exploded View take only the item, and strict refuses any other+/// key (#12155).+fn deletion(delete: &str, key: &str, id: u64) -> Value {+ if delete == "contact.edit" { json!({key: id, "delete": true}) } else { json!({key: id}) }+}+#[test]fn deleted_motion_item_ids_are_not_reused_after_reopening() {for (create, delete, key, params) in [@@ -29,13 +36,13 @@ fn deleted_motion_item_ids_are_not_reused_after_reopening() {run(&mut s, "component.create", json!({"name": name}));}let first = run(&mut s, create, params.clone())[key].as_u64().unwrap();- let deletion = json!({key: first, "delete": true});- run(&mut s, delete, deletion.clone());+ let deleting = deletion(delete, key, first);+ run(&mut s, delete, deleting.clone());let doc = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap();*s.doc_mut() = doc;let second = run(&mut s, create, params)[key].as_u64().unwrap();assert!(second > first, "{create}: deleted item {first} was reused as {second}");- assert!(s.execute(delete, &deletion).is_err());+ assert!(s.execute(delete, &deleting).is_err());}}@@ -60,7 +67,7 @@ fn default_names_skip_names_in_use() {let (first, one) = made(&mut s);let (_, two) = made(&mut s);assert_eq!([one, two], [format!("{prefix}1"), format!("{prefix}2")]);- run(&mut s, delete, json!({key: first, "delete": true}));+ run(&mut s, delete, deletion(delete, key, first));assert_eq!(made(&mut s).1, format!("{prefix}1"), "{create}: the free name, not {prefix}2 again");}// Placements: with the first deleted, a copy takes a name none has.diff --git a/crates/engine/src/schema/motion.rs b/crates/engine/src/schema/motion.rsindex f65e042ebb..d4ab868a56 100644--- a/crates/engine/src/schema/motion.rs+++ b/crates/engine/src/schema/motion.rs@@ -5,7 +5,7 @@ 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 serde_json::{Value, json};use super::check::whole;@@ -401,6 +401,230 @@ pub struct ContactCollision {pub depth_mm: f64,}+// ---- Motion studies (#12155) ----+//+// `motion.study` reads its parameters from the raw JSON, so each key here reads as the handler+// reads it and fails with its message. Whether the study and each key's joint exist, whether the+// joint has that value, and whether an expression evaluates stay the handler's to check.++/// The most keys a motion study takes, and the most points one key takes.+const MAX_STUDY_KEYS: usize = 1000;+const MAX_KEY_POINTS: usize = 10_000;+/// A point's step, and a value given as a number, are read only while smaller than this in size.+const MAX_POINT_MAGNITUDE: f64 = 1e9;++/// Make a motion study, which drives joints along a timeline of steps: each key gives one value of+/// one joint at some steps, linear in between and held before the first and after the last. With+/// `study`, change that study instead. One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct MotionStudyParams {+ /// A study to change, by id (a number) or name; left out, a new one is made.+ #[serde(default, deserialize_with = "some_study", skip_serializing_if = "Option::is_none")]+ #[schemars(schema_with = "study_ref_schema")]+ pub study: Option<Value>,+ /// The study's name; blank text keeps it. Default for a new one: "Motion Study" and the first+ /// number no study's name has.+ #[serde(default)]+ pub name: Option<String>,+ /// How many steps the timeline has: 1 to 100 000 (a fraction rounds). Default for a new one: 100.+ #[serde(default, deserialize_with = "study_steps", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "f64", range(min = 1, max = 100_000))]+ pub steps: Option<f64>,+ #[serde(default, deserialize_with = "study_keys", skip_serializing_if = "Option::is_none")]+ #[schemars(schema_with = "study_keys_schema")]+ pub keys: Option<Vec<Value>>,+}++/// List the design's motion studies, each with its keys in the units `motion.study` takes, and its+/// associative traces. Nothing is changed.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct MotionListParams {}++/// Delete a motion study. One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = study_required)]+pub struct MotionStudyDeleteParams {+ // Required in the schema (`study_required`), optional in the type: left out, the handler+ // refuses it with its own message, not the check's "is required".+ #[serde(default, deserialize_with = "some_study", skip_serializing_if = "Option::is_none")]+ #[schemars(schema_with = "study_ref_schema")]+ pub study: Option<Value>,+}++/// `study`: an id or a name, with the handler's message for anything else, `null` included.+fn some_study<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Value>, D::Error> {+ match Value::deserialize(d)? {+ v @ (Value::Number(_) | Value::String(_)) => Ok(Some(v)),+ _ => Err(D::Error::custom(whole("`study` must be an id or a name"))),+ }+}++fn study_ref_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "The motion study, by id (a number) or name. A number is looked up as an id first, text as a name first.",+ "type": ["number", "string"]+ })+}++fn study_required(schema: &mut Schema) {+ require(schema, "study");+}++/// `steps`: a number from 1 to 100 000, with the handler's message for anything else, `null`+/// included.+fn study_steps<'de, D: Deserializer<'de>>(d: D) -> Result<Option<f64>, D::Error> {+ Value::deserialize(d)?+ .as_f64()+ .filter(|n| n.is_finite() && (1.0..=100_000.0).contains(n))+ .map(Some)+ .ok_or_else(|| D::Error::custom(whole("`steps` must be 1…100000")))+}++/// Why the handler refuses `key`'s shape before looking at the design: its joint, value index,+/// points and values, with the handler's messages.+fn study_key_problem(key: &Value) -> Option<String> {+ if !matches!(key.get("joint"), Some(Value::Number(_) | Value::String(_))) {+ return Some("`joint` must be an id or a name".into());+ }+ // The handler reads an index that isn't a whole number as 0; the contract refuses it.+ if key.get("index").is_some_and(|i| i.as_u64().is_none()) {+ return Some("a key's `index` must be a whole number of 0 or more".into());+ }+ let Some(points) = key.get("points").and_then(Value::as_array) else {+ return Some("each key needs `points`: [[step, value], …]".into());+ };+ if points.is_empty() || points.len() > MAX_KEY_POINTS {+ return Some("a key needs 1…10000 points".into());+ }+ for point in points {+ let step = point.get(0).and_then(Value::as_f64).filter(|x| x.is_finite() && x.abs() < MAX_POINT_MAGNITUDE);+ let Some(value) = point.get(1).filter(|_| step.is_some()) else {+ return Some("points are [step, value]".into());+ };+ let readable = match value {+ Value::Number(n) => n.as_f64().is_some_and(|x| x.is_finite() && x.abs() < MAX_POINT_MAGNITUDE),+ Value::String(_) => true,+ _ => false,+ };+ if !readable {+ return Some(format!("a joint value {}", crate::params::expr_problem(Some(value))));+ }+ }+ None+}++/// `keys`: a list of at most 1000 keys, each checked as [`study_key_problem`] says. Given, `null`+/// included, it must be a list, as the handler reads it.+fn study_keys<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<Value>>, D::Error> {+ let Value::Array(keys) = Value::deserialize(d)? else {+ return Err(D::Error::custom(whole("`keys` must be a list")));+ };+ if keys.len() > MAX_STUDY_KEYS {+ return Err(D::Error::custom(whole("too many keys")));+ }+ if let Some(problem) = keys.iter().find_map(study_key_problem) {+ return Err(D::Error::custom(whole(problem)));+ }+ Ok(Some(keys))+}++/// The schema of `motion.study`'s `keys`. A point's two elements are typed apart+/// (`prefixItems`): the step must be a number, while the value may be a number or an+/// expression. Elements after those two are ignored by the handler, so they are left free.+fn study_keys_schema(_: &mut SchemaGenerator) -> Schema {+ let number = json!({"type": "number", "exclusiveMinimum": -MAX_POINT_MAGNITUDE, "exclusiveMaximum": MAX_POINT_MAGNITUDE});+ json_schema!({+ "description": "The study's keys, replacing any it has (at most 1000). Each drives one value of one joint: `joint` by id or name, `index` the value (0 for a revolute's angle; default 0), and `points` as [step, value] pairs (1 to 10 000), a value being degrees for an angle and mm for a distance, or an expression.",+ "type": "array",+ "maxItems": MAX_STUDY_KEYS,+ "items": {+ "type": "object",+ "required": ["joint", "points"],+ "properties": {+ "joint": {"type": ["number", "string"]},+ "index": {"type": "integer", "minimum": 0},+ "points": {+ "type": "array",+ "minItems": 1,+ "maxItems": MAX_KEY_POINTS,+ "items": {+ "type": "array",+ "minItems": 2,+ "prefixItems": [+ number.clone(),+ {"anyOf": [number, {"type": "string"}]}+ ]+ }+ }+ }+ }+ })+}++/// What `motion.study` returns: the study made or changed.+#[derive(Debug, Serialize, JsonSchema)]+pub struct MotionStudySaved {+ /// The study's id.+ pub study: u64,+ pub name: String,+ pub steps: u32,+ /// How many keys it has.+ pub keys: 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>,+}++/// What `motion.list` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct MotionStudies {+ pub studies: Vec<MotionStudyInfo>,+ /// The design's associative traces, each `{sketch, motion, samples, error}`: the sketch+ /// (by id) the trace draws into, the motion it follows (a joint's range or a study), how many+ /// samples it takes (`null`: automatic), and why it last failed (`null` when it didn't).+ #[schemars(with = "Vec<serde_json::Map<String, Value>>")]+ pub traces: Vec<Value>,+ /// 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>,+}++/// A motion study, in the form `motion.study` takes it back unchanged.+#[derive(Debug, Serialize, JsonSchema)]+pub struct MotionStudyInfo {+ pub id: u64,+ pub name: String,+ pub steps: u32,+ pub keys: Vec<MotionStudyKeyInfo>,+}++/// One key of a study.+#[derive(Debug, Serialize, JsonSchema)]+pub struct MotionStudyKeyInfo {+ /// The joint's id.+ pub joint: u64,+ /// Its name; its id, as text, when the joint is gone.+ pub joint_name: String,+ /// Which of its values.+ pub index: usize,+ /// `deg` for an angle, `mm` for a distance: the unit of the points' values.+ pub unit: String,+ /// [step, value] pairs.+ pub points: Vec<[f64; 2]>,+}++/// What `motion.delete` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct MotionStudyDeleted {+ /// The deleted study's name.+ pub deleted: String,+ /// 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 = "motion_tests.rs"]mod tests;diff --git a/crates/engine/src/schema/motion_tests.rs b/crates/engine/src/schema/motion_tests.rsindex 6f773263d2..1546b0a0f6 100644--- a/crates/engine/src/schema/motion_tests.rs+++ b/crates/engine/src/schema/motion_tests.rs@@ -2,7 +2,8 @@ use serde_json::{Value, json};use super::{ContactCheck, ContactCreateParams, ContactEditParams, ContactEnableParams, ContactNoParams, ContactSetCreated, ContactSetEdited, ContactSets,- ContactSwitch, FindLimitsParams, FindLimitsResult,+ ContactSwitch, FindLimitsParams, FindLimitsResult, MotionListParams, MotionStudies, MotionStudyDeleteParams, MotionStudyDeleted,+ MotionStudyParams, MotionStudySaved,};use crate::Session;use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};@@ -15,6 +16,9 @@ fn schemas_and_the_key_check_agree() {assert_keys(input_schema_for::<ContactNoParams>(), &[]);assert_keys(input_schema_for::<ContactCreateParams>(), &["name", "occurrences"]);assert_keys(input_schema_for::<ContactEditParams>(), &["delete", "name", "occurrences", "set", "suppressed"]);+ assert_keys(input_schema_for::<MotionStudyParams>(), &["keys", "name", "steps", "study"]);+ assert_keys(input_schema_for::<MotionListParams>(), &[]);+ assert_keys(input_schema_for::<MotionStudyDeleteParams>(), &["study"]);}#[test]@@ -148,3 +152,110 @@ fn replies_match_the_output_schema() {let required: Vec<&str> = schema.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect();assert!(!required.contains(&"param_warnings"));}++/// A key driving the door's hinge from 0 to `to` degrees over the steps.+fn hinge_key(to: Value) -> Value {+ json!({"joint": "Hinge", "points": [[0, 0], [100, to]]})+}++/// #12155: the motion study commands refuse, in strict, what they refuse today, with the same+/// message. They need the door's joints, so the shared helper doesn't fit.+#[test]+fn strict_keeps_the_motion_studys_errors() {+ let many_keys = vec![hinge_key(json!(10)); 1001];+ let many_points: Vec<Value> = (0..10_001).map(|i| json!([i, 0])).collect();+ for (id, p) in [+ ("motion.study", json!({"study": true})),+ ("motion.study", json!({"study": null})),+ ("motion.study", json!({"study": "Nope"})),+ ("motion.study", json!({"steps": 0})),+ ("motion.study", json!({"steps": "100"})),+ ("motion.study", json!({"steps": null})),+ ("motion.study", json!({"keys": {"joint": "Hinge"}})),+ ("motion.study", json!({"keys": null})),+ ("motion.study", json!({"keys": many_keys})),+ ("motion.study", json!({"keys": [{"points": [[0, 0]]}]})),+ ("motion.study", json!({"keys": [{"joint": "Nope", "points": [[0, 0]]}]})),+ ("motion.study", json!({"keys": [{"joint": "Hinge", "index": 3, "points": [[0, 0]]}]})),+ ("motion.study", json!({"keys": [{"joint": "Hinge"}]})),+ ("motion.study", json!({"keys": [{"joint": "Hinge", "points": []}]})),+ ("motion.study", json!({"keys": [{"joint": "Hinge", "points": many_points}]})),+ ("motion.study", json!({"keys": [{"joint": "Hinge", "points": [[0]]}]})),+ ("motion.study", json!({"keys": [{"joint": "Hinge", "points": [["a", 0]]}]})),+ ("motion.study", json!({"keys": [hinge_key(json!(true))]})),+ ("motion.study", json!({"keys": [hinge_key(json!("nope + 1"))]})),+ ("motion.delete", json!({})),+ ("motion.delete", json!({"study": [1]})),+ ("motion.delete", json!({"study": "Nope"})),+ ] {+ let error = |level: ParamCheck| {+ let mut s = door();+ s.param_check = level;+ s.execute(id, &p).err().map(|e| e.to_string())+ };+ let off = error(ParamCheck::Off);+ assert!(off.is_some(), "{id} {p} should fail today");+ assert_eq!(error(ParamCheck::Strict), off, "{id} {p}");+ }+}++/// #12155: a key's points, in `motion.study`'s schema, take what the handler reads: a step that+/// is a number (not text), and a value that is a number or an expression, each smaller than 1e9+/// in size; elements after those two are ignored. Each case is checked against the contract's+/// own key check too, so the schema and the handler can't drift apart.+#[test]+fn a_studys_points_schema_takes_what_the_handler_reads() {+ let study = input_schema_for::<MotionStudyParams>();+ let study = study.as_value();+ for (point, takes) in [+ (json!([0, 20]), true),+ (json!([12.5, "10 mm"]), true),+ (json!([0, 20, "ignored"]), true),+ (json!(["0", 20]), false),+ (json!([null, 20]), false),+ (json!([2e9, 20]), false),+ (json!([0, 2e9]), false),+ (json!([0, true]), false),+ (json!([0]), false),+ ] {+ let key = json!({"joint": "Hinge", "points": [point]});+ assert_eq!(conforms(study, study, &json!({"keys": [key]})), takes, "schema: {point}");+ assert_eq!(super::study_key_problem(&key).is_none(), takes, "key check: {point}");+ }+}++/// #12155: making, changing, listing and deleting motion studies reply as the output schemas+/// say, in Warn without warnings; a listed study's keys go back into `motion.study` unchanged.+/// A misspelt key gets `param_warnings` in Warn, since the handlers ignore unknown keys, and+/// strict refuses it.+#[test]+fn motion_studies_reply_with_their_schemas() {+ let mut s = door();+ s.param_check = ParamCheck::Warn;+ let mut run = |id: &str, p: Value, schema: schemars::Schema| {+ let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));+ let schema = schema.as_value();+ assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");+ assert!(r.get("param_warnings").is_none(), "{r}");+ r+ };+ let r = run("motion.study", json!({"name": "Swing", "steps": 50, "keys": [hinge_key(json!(30))]}), output_schema_for::<MotionStudySaved>());+ assert_eq!((r["name"].as_str(), r["steps"].as_u64(), r["keys"].as_u64()), (Some("Swing"), Some(50), Some(1)), "{r}");+ let slide = json!({"joint": "Rail", "index": 0, "points": [[0, 0], [50, "10 mm"]]});+ run("motion.study", json!({"study": "Swing", "keys": [hinge_key(json!(20)), slide]}), output_schema_for::<MotionStudySaved>());+ run("motion.study", json!({}), output_schema_for::<MotionStudySaved>());+ let list = run("motion.list", json!({}), output_schema_for::<MotionStudies>());+ let swing = &list["studies"][0];+ assert_eq!((swing["keys"][0]["unit"].as_str(), swing["keys"][1]["unit"].as_str()), (Some("deg"), Some("mm")), "{list}");+ assert_eq!(swing["keys"][0]["points"], json!([[0.0, 0.0], [100.0, 20.0]]), "degrees, as given");+ // The listed keys go back in as they are.+ run("motion.study", json!({"study": swing["id"], "keys": swing["keys"]}), output_schema_for::<MotionStudySaved>());+ let r = run("motion.delete", json!({"study": "Swing"}), output_schema_for::<MotionStudyDeleted>());+ assert_eq!(r["deleted"], "Swing", "{r}");+ let p = json!({"name": "Again", "step": 10});+ let r = s.execute("motion.study", &p).unwrap_or_else(|e| panic!("{p}: {e}"));+ assert!(r["param_warnings"].to_string().contains("step"), "{r}");+ s.param_check = ParamCheck::Strict;+ let error = s.execute("motion.study", &p).err().map(|e| e.to_string()).unwrap_or_default();+ assert!(error.contains("`step`"), "{error}");+}diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txtindex 3dbb76424f..9a0d24bec9 100644--- a/crates/engine/src/schema/unconverted.txt+++ b/crates/engine/src/schema/unconverted.txt@@ -78,14 +78,11 @@ joint.sweepmaterial.assignmaterial.listmesh.convert-motion.deletemotion.exportmotion.export_animationmotion.interference-motion.listmotion.playmotion.plot-motion.studymotion.tracemotion.trace.editmotion.trace.keep