Skip to content

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

Agents and scripts: Delete describes its exact parameters and reply (#12610) (#12635)

PeppaWutz9ecf28834f30
diff --git a/crates/engine/src/cmd/delete.rs b/crates/engine/src/cmd/delete.rs
index f435cd52f4..8c27d4c686 100644
--- a/crates/engine/src/cmd/delete.rs
+++ b/crates/engine/src/cmd/delete.rs
@@ -10,11 +10,19 @@ use solidcraft_doc::FeatureKind;
use super::{CommandSpec, sketch_store};
use crate::params::{bad, bool_};
+use crate::schema::delete::{SelectionDeleteParams, SelectionDeleteResult};
+use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Sel, Session};
-pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("selection.delete", "Delete", delete).icon("delete").params(
- "items?: [selection items]; components?, occurrences?, canvases?, point_clouds?, joints?: [ids or names]; dry_run?: bool → deleted, deleted_joints, would_fail, skipped (one undo step)",
-)];
+const DELETE_CONTRACT: TypedContract<SelectionDeleteParams> = TypedContract::new();
+
+pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("selection.delete", "Delete", crate::checked!("selection.delete", delete))
+ .icon("delete")
+ .contract(&DELETE_CONTRACT)
+ .output(output_schema_for::<SelectionDeleteResult>)
+ .params(
+ "items?: [selection items]; components?, occurrences?, canvases?, point_clouds?, joints?: [ids or names]; dry_run?: bool → deleted, deleted_joints, would_fail, skipped (one undo step)",
+ )];
/// Run another command's body inside this one (so the whole delete is one undo step).
fn sub(s: &mut Session, id: &str, p: Value) -> Result<Value> {
@@ -227,11 +235,12 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, skipped.first().cloned().unwrap_or_else(|| "nothing to delete".into())));
}
s.refresh();
- let deleted: Vec<&String> = features_before.iter().filter(|(id, _)| s.doc.feature(*id).is_none()).map(|(_, n)| n).collect();
+ let deleted: Vec<String> = features_before.iter().filter(|(id, _)| s.doc.feature(*id).is_none()).map(|(_, n)| n.clone()).collect();
// Features after a rolled-back marker count too (#3471).
let would_fail: Vec<String> =
super::edit::newly_broken_in_history(&before_doc, &before, &s.doc, &s.model).into_iter().map(|(name, _)| name).collect();
- Ok(json!({ "deleted": deleted, "deleted_joints": joints, "bodies": bodies, "would_fail": would_fail, "skipped": skipped }))
+ let reply = SelectionDeleteResult { deleted, deleted_joints: joints, bodies, would_fail, skipped, param_warnings: Vec::new() };
+ serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
}
#[cfg(test)]
diff --git a/crates/engine/src/schema/delete.rs b/crates/engine/src/schema/delete.rs
new file mode 100644
index 0000000000..97463af8f4
--- /dev/null
+++ b/crates/engine/src/schema/delete.rs
@@ -0,0 +1,215 @@
+//! Contracts and result types for the command in `cmd/delete.rs`: `selection.delete`.
+//!
+//! The handler reads its parameters from the raw JSON, so each key here reads as the handler
+//! reads it and fails with the handler's message: `items` and `joints` with their own words, the
+//! four lists of ids or names (`components`, `occurrences`, `canvases`, `point_clouds`) are read
+//! as the handler reads them: what it ignores is ignored, never refused. Whether an item, a joint, an occurrence or a component exists stays 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 in its own order).
+
+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, json};
+
+use super::check::whole;
+use crate::Sel;
+
+/// The most items or ids a list takes (the handler's limit).
+const MAX_LIST: usize = 10_000;
+
+/// Delete what is selected, in one undo step: sketch entities (while sketching), timeline features
+/// and sketches (with the features that depend on them), construction planes and axes, bodies (a
+/// Remove feature from here on in the timeline), occurrences and components, canvases, point
+/// clouds and joints. `dry_run` reports what would go and what would fail without changing
+/// anything. Give something to delete in `items` or one of the lists; otherwise the call is
+/// refused.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct SelectionDeleteParams {
+ /// What to delete, as selection items: `{"type": "feature", "id": 3}`, `{"type": "body",
+ /// "name": "Body1"}`, `{"type": "sketch_curve", "id": "c1"}` and so on. At most 10000. Items
+ /// that can't be deleted (an origin plane, an edge or vertex, a profile outside the sketch
+ /// being edited) are named in `skipped`.
+ #[serde(default)]
+ pub items: Option<SelectionItems>,
+ /// Components to delete, by id or name (not the design itself). Only the first 10000 are
+ /// read.
+ #[serde(default)]
+ pub components: Option<IdList>,
+ /// Occurrences to delete, by id or name. One goes alone while its component has others; the
+ /// last one takes the component. Only the first 10000 are read.
+ #[serde(default)]
+ pub occurrences: Option<IdList>,
+ /// Canvases and decals to delete, by id or name. Only the first 10000 are read.
+ #[serde(default)]
+ pub canvases: Option<IdList>,
+ /// Point clouds to delete, by id or name. Only the first 10000 are read.
+ #[serde(default)]
+ pub point_clouds: Option<IdList>,
+ /// Joints to delete, by id or name (at most 10000).
+ #[serde(default)]
+ pub joints: Option<JointList>,
+ /// Only report what would be deleted and what would fail, and change nothing. Default:
+ /// false.
+ #[serde(default)]
+ pub dry_run: Option<bool>,
+}
+
+/// `items`, as the handler reads it: a list of at most 10000 selection items, each as [`Sel`]
+/// reads it. Kept as parsed, for the handler to read again.
+#[derive(Clone, Debug, PartialEq)]
+pub struct SelectionItems(pub Vec<Sel>);
+
+impl<'de> Deserialize<'de> for SelectionItems {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ Value::Array(a) if a.len() <= MAX_LIST => a
+ .into_iter()
+ .map(|v| serde_json::from_value(v.clone()).map_err(|e| D::Error::custom(whole(format!("bad item {v}: {e}")))))
+ .collect::<Result<_, _>>()
+ .map(SelectionItems),
+ _ => Err(D::Error::custom(whole("`items` must be a list of selection items"))),
+ }
+ }
+}
+
+impl JsonSchema for SelectionItems {
+ fn schema_name() -> Cow<'static, str> {
+ "SelectionItems".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ let point = json!({"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3});
+ let text = json!({"type": "string"});
+ let count = json!({"type": "integer", "minimum": 0});
+ // One object per kind of item: `type` and the keys it needs.
+ let item = |kind: &str, keys: &[(&str, &Value)], optional: &[(&str, &Value)]| {
+ let mut properties = serde_json::Map::new();
+ properties.insert("type".into(), json!({"type": "string", "enum": [kind]}));
+ let mut required = vec![json!("type")];
+ for (key, schema) in keys {
+ properties.insert((*key).into(), (*schema).clone());
+ required.push(json!(key));
+ }
+ for (key, schema) in optional {
+ properties.insert((*key).into(), (*schema).clone());
+ }
+ json!({"type": "object", "properties": properties, "required": required})
+ };
+ let path = json!({"type": "array", "items": {"type": "integer", "minimum": 0}});
+ json_schema!({
+ "description": "Selection items: objects with a `type` and the keys that type needs.",
+ "type": "array",
+ "maxItems": MAX_LIST,
+ "items": {"anyOf": [
+ item("occurrence", &[("path", &path)], &[]),
+ item("body", &[("name", &text)], &[]),
+ item("edge", &[("body", &text), ("index", &count), ("point", &point)], &[]),
+ item("face", &[("body", &text), ("index", &count), ("point", &point)], &[]),
+ item("feature", &[("id", &count)], &[]),
+ item("sketch_curve", &[("id", &text)], &[("sketch", &count)]),
+ item("sketch_point", &[("id", &text)], &[]),
+ item("sketch_midpoint", &[("id", &text)], &[]),
+ item("external_sketch_curve", &[("sketch", &count), ("id", &text)], &[]),
+ item("external_sketch_point", &[("sketch", &count), ("id", &text)], &[]),
+ item("sketch_constraint", &[("id", &text)], &[]),
+ item("profile", &[("sketch", &count), ("index", &count)], &[]),
+ item("plane", &[("name", &text)], &[]),
+ item("construction_point", &[("name", &text)], &[]),
+ item("axis", &[("name", &text)], &[]),
+ item("vertex", &[("body", &text), ("point", &point)], &[])
+ ]}
+ })
+ }
+}
+
+/// An id (a number from 0 up) or a name, as the handler's list reader takes one.
+fn id_or_name<E: serde::de::Error>(v: Value, message: &str) -> Result<String, E> {
+ match v {
+ Value::Number(n) if n.is_u64() => Ok(n.to_string()),
+ Value::String(s) => Ok(s),
+ _ => Err(E::custom(message.to_string())),
+ }
+}
+
+fn id_or_name_schema() -> Value {
+ json!({"anyOf": [{"type": "string"}, {"type": "integer", "minimum": 0}]})
+}
+
+/// A list of ids or names, read as the handler's `keys()` reads `components`, `occurrences`,
+/// `canvases` and `point_clouds`: anything but a list is left out, so are items that are neither a
+/// name nor an id, and only the first 10000 count. Nothing is refused, as the handler refuses
+/// nothing here.
+#[derive(Clone, Debug, PartialEq)]
+pub struct IdList(pub Vec<String>);
+
+impl<'de> Deserialize<'de> for IdList {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let Value::Array(a) = Value::deserialize(d)? else {
+ return Ok(IdList(Vec::new()));
+ };
+ Ok(IdList(a.into_iter().take(MAX_LIST).filter_map(|v| id_or_name::<D::Error>(v, "").ok()).collect()))
+ }
+}
+
+impl JsonSchema for IdList {
+ fn schema_name() -> Cow<'static, str> {
+ "IdList".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "Ids (numbers) or names. Anything else is ignored.", "type": "array", "items": id_or_name_schema()})
+ }
+}
+
+/// `joints`, as the handler reads it: a list of at most 10000 ids or names.
+#[derive(Clone, Debug, PartialEq)]
+pub struct JointList(pub Vec<String>);
+
+impl<'de> Deserialize<'de> for JointList {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let Value::Array(a) = Value::deserialize(d)? else {
+ return Err(D::Error::custom(whole("`joints` must be a list of ids or names")));
+ };
+ let message = whole("`joints` must contain at most 10000 ids or names");
+ if a.len() > MAX_LIST {
+ return Err(D::Error::custom(message));
+ }
+ a.into_iter().map(|v| id_or_name(v, &message)).collect::<Result<_, _>>().map(JointList)
+ }
+}
+
+impl JsonSchema for JointList {
+ fn schema_name() -> Cow<'static, str> {
+ "JointList".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "Joint ids (numbers) or names.", "type": "array", "items": id_or_name_schema(), "maxItems": MAX_LIST})
+ }
+}
+
+/// What `selection.delete` returns. With `dry_run` it says what would happen.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct SelectionDeleteResult {
+ /// The names of the timeline features that went (or would go), the selected ones and those
+ /// that depended on them.
+ pub deleted: Vec<String>,
+ /// The ids of the joints that went (or would go): the ones asked for, and those on an
+ /// occurrence deleted.
+ pub deleted_joints: Vec<u64>,
+ /// The bodies still there that got a Remove feature, by name.
+ pub bodies: Vec<String>,
+ /// The names of the features that would fail (or now fail) to rebuild without what went,
+ /// also those after a rolled-back marker.
+ pub would_fail: Vec<String>,
+ /// Why some items were not deleted (an origin plane, an edge or vertex, …), each reason once.
+ pub skipped: Vec<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 = "delete_tests.rs"]
+mod tests;
diff --git a/crates/engine/src/schema/delete_tests.rs b/crates/engine/src/schema/delete_tests.rs
new file mode 100644
index 0000000000..780973a247
--- /dev/null
+++ b/crates/engine/src/schema/delete_tests.rs
@@ -0,0 +1,273 @@
+use serde_json::{Value, json};
+
+use super::{IdList, JointList, SelectionDeleteParams, SelectionDeleteResult, SelectionItems};
+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};
+
+fn run(s: &mut Session, id: &str, p: Value) -> Value {
+ s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
+}
+
+fn matches(schema: schemars::Schema, r: &Value) {
+ let schema = schema.as_value();
+ assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");
+}
+
+#[test]
+fn schemas_and_the_key_check_agree() {
+ assert_keys(
+ input_schema_for::<SelectionDeleteParams>(),
+ &["canvases", "components", "dry_run", "items", "joints", "occurrences", "point_clouds"],
+ );
+}
+
+/// Strict gives the handler's messages for the calls it refuses for a key.
+#[test]
+fn strict_keeps_todays_errors() {
+ assert_strict_keeps_todays_errors(&[
+ ("selection.delete", json!({})),
+ ("selection.delete", json!({"items": null})),
+ ("selection.delete", json!({"items": "all"})),
+ ("selection.delete", json!({"items": {"type": "body", "name": "Body1"}})),
+ ("selection.delete", json!({"items": [{"type": "body"}]})),
+ ("selection.delete", json!({"items": [{"type": "nothing"}]})),
+ ("selection.delete", json!({"items": [5]})),
+ ("selection.delete", json!({"items": [{"type": "feature", "id": -1}]})),
+ ("selection.delete", json!({"items": [{"type": "face", "body": "B", "index": 0, "point": [1, 2]}]})),
+ ("selection.delete", json!({"items": vec![json!({"type": "body", "name": "B"}); 10_001]})),
+ ("selection.delete", json!({"joints": "J1"})),
+ ("selection.delete", json!({"joints": [true]})),
+ ("selection.delete", json!({"joints": [1.5]})),
+ ("selection.delete", json!({"joints": [-1]})),
+ ("selection.delete", json!({"joints": vec![json!(1); 10_001]})),
+ ("selection.delete", json!({"joints": ["Nope"]})),
+ ("selection.delete", json!({"joints": [99]})),
+ ("selection.delete", json!({"components": ["Nope"]})),
+ ("selection.delete", json!({"components": [0]})),
+ ("selection.delete", json!({"occurrences": ["Nope"]})),
+ ("selection.delete", json!({"canvases": ["Nope"]})),
+ ("selection.delete", json!({"point_clouds": ["Nope"]})),
+ ("selection.delete", json!({"items": [{"type": "feature", "id": 99999}]})),
+ ("selection.delete", json!({"items": [{"type": "plane", "name": "XY"}]})),
+ ]);
+}
+
+/// The types read each key as the handler does: what it takes they take, what it refuses (with
+/// its message) they refuse.
+#[test]
+fn the_types_read_like_the_handler() {
+ let items = |v: Value| serde_json::from_value::<SelectionItems>(v).map_err(|e| e.to_string());
+ assert_eq!(items(json!([])).map(|i| i.0.len()), Ok(0));
+ assert_eq!(items(json!([{"type": "feature", "id": 3}, {"type": "body", "name": "B"}])).map(|i| i.0.len()), Ok(2));
+ assert_eq!(items(json!([{"type": "feature", "id": 3}])).map(|i| i.0), Ok(vec![Sel::Feature { id: 3 }]));
+ assert!(items(json!("x")).is_err_and(|e| e.contains("`items` must be a list of selection items")));
+ assert!(items(json!(null)).is_err());
+ assert!(items(json!([{"type": "nothing"}])).is_err_and(|e| e.contains("bad item {\"type\":\"nothing\"}: ")));
+ assert!(items(json!(vec![json!({"type": "body", "name": "B"}); 10_001])).is_err());
+ assert!(items(json!(vec![json!({"type": "body", "name": "B"}); 10_000])).is_ok());
+
+ let ids = |v: Value| serde_json::from_value::<IdList>(v).map(|l| l.0).ok();
+ assert_eq!(ids(json!(["Plate", 3])), Some(vec!["Plate".to_string(), "3".to_string()]));
+ assert_eq!(ids(json!([])), Some(vec![]));
+ // What the handler ignores is ignored, not refused: a call that runs today is not warned about.
+ assert_eq!(ids(json!("Plate")), Some(vec![]));
+ assert_eq!(ids(json!(["a", true, -1, 1.5, null, 2])), Some(vec!["a".to_string(), "2".to_string()]));
+ assert_eq!(ids(json!(vec![json!(1); 10_001])).map(|l| l.len()), Some(10_000));
+
+ let joints = |v: Value| serde_json::from_value::<JointList>(v).map_err(|e| e.to_string());
+ assert_eq!(joints(json!(["J1", 2])).map(|l| l.0), Ok(vec!["J1".to_string(), "2".to_string()]));
+ assert!(joints(json!("J1")).is_err_and(|e| e.contains("`joints` must be a list of ids or names")));
+ for bad in [json!([true]), json!([1.5]), json!([-1]), json!(vec![json!(1); 10_001])] {
+ assert!(joints(bad).is_err_and(|e| e.contains("`joints` must contain at most 10000 ids or names")));
+ }
+
+ // Nothing is needed, and a `null` is a key left out (the handler says "nothing to delete").
+ let params = |v: Value| serde_json::from_value::<SelectionDeleteParams>(v).is_ok();
+ assert!(params(json!({})));
+ assert!(params(
+ json!({"items": null, "components": null, "occurrences": null, "canvases": null, "point_clouds": null, "joints": null, "dry_run": null})
+ ));
+ assert!(params(json!({"dry_run": true})));
+ assert!(!params(json!({"dry_run": "yes"})));
+}
+
+/// The schema takes every kind of item the handler can read, and refuses what it can't.
+#[test]
+fn the_schema_takes_every_selection_item() {
+ let schema = input_schema_for::<SelectionDeleteParams>();
+ let schema = schema.as_value();
+ let point = solidcore_record::Vec3::new(1.0, 2.0, 3.0);
+ let all = [
+ Sel::Occurrence { path: vec![1, 2] },
+ Sel::Body { name: "B".into() },
+ Sel::Edge { body: "B".into(), index: 0, point },
+ Sel::Face { body: "B".into(), index: 1, point },
+ Sel::Feature { id: 4 },
+ Sel::SketchCurve { id: "c1".into(), sketch: None },
+ Sel::SketchCurve { id: "c1".into(), sketch: Some(2) },
+ Sel::SketchPoint { id: "p1".into() },
+ Sel::SketchMidpoint { id: "c1".into() },
+ Sel::ExternalSketchCurve { sketch: 2, id: "c1".into() },
+ Sel::ExternalSketchPoint { sketch: 2, id: "p1".into() },
+ Sel::SketchConstraint { id: "k1".into() },
+ Sel::Profile { sketch: 2, index: 0 },
+ Sel::Plane { name: "XY".into() },
+ Sel::ConstructionPoint { name: "P".into() },
+ Sel::Axis { name: "X".into() },
+ Sel::Vertex { body: "B".into(), point },
+ ];
+ for item in all {
+ let item = serde_json::to_value(&item).unwrap();
+ assert!(conforms(schema, schema, &json!({"items": [item]})), "{item}");
+ assert!(serde_json::from_value::<SelectionItems>(json!([item])).is_ok(), "{item}");
+ }
+ let takes = |p: Value, takes: bool| assert_eq!(conforms(schema, schema, &p), takes, "{p}");
+ takes(json!({}), true);
+ takes(
+ json!({"items": [], "components": ["A", 2], "occurrences": [1], "canvases": ["C"], "point_clouds": [3], "joints": ["J", 4], "dry_run": true}),
+ true,
+ );
+ takes(json!({"items": [{"type": "nothing"}]}), false);
+ takes(json!({"items": [{"type": "body"}]}), false);
+ takes(json!({"items": "all"}), false);
+ takes(json!({"joints": [true]}), false);
+ takes(json!({"dry_run": "yes"}), false);
+ takes(json!({"colour": 1}), false);
+}
+
+/// Calls that run today with a list the handler ignores get no warning and no refusal, in warn
+/// and in strict.
+#[test]
+fn lists_the_handler_ignores_are_not_warned_about() {
+ let mut s = part();
+ let sketch = s.doc.features.first().map(|f| f.id).unwrap();
+ for level in [ParamCheck::Warn, ParamCheck::Strict] {
+ s.param_check = level;
+ let p = json!({"items": [{"type": "feature", "id": sketch}], "dry_run": true, "components": "A", "canvases": [true, -1], "point_clouds": 5});
+ let r = s.execute("selection.delete", &p).unwrap_or_else(|e| panic!("{e}"));
+ assert!(r.get("param_warnings").is_none(), "{r}");
+ }
+}
+
+/// A design with a sketch extruded into a body, a second box and an offset plane.
+fn part() -> Session {
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ run(&mut s, "sketch.create", json!({"plane": "XY"}));
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 20]}));
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "solid.extrude", json!({"distance": 5}));
+ run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [50, 0, 0]}));
+ run(&mut s, "construct.plane.offset", json!({"base": "XY", "offset": 10}));
+ s
+}
+
+/// Three components, A grounded, with a joint from A to each of the others.
+fn joint_assembly() -> Session {
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ for (name, x) in [("A", 0), ("B", 30), ("C", 60)] {
+ run(&mut s, "component.activate", json!({"component": "root"}));
+ run(&mut s, "component.create", json!({"name": name}));
+ run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 10, "corner": [x, 0, 0]}));
+ }
+ run(&mut s, "component.activate", json!({"component": "root"}));
+ run(&mut s, "occurrence.ground", json!({"occurrence": "A:1", "grounded": true}));
+ for (name, other, face) in [("Hinge", "B:1", [40, 10, 0]), ("Glue", "C:1", [70, 10, 0])] {
+ let ends = json!({"a": {"occurrence": "A:1", "face": [10, 10, 10]}, "b": {"occurrence": other, "face": face}});
+ let mut p = json!({"type": "revolute", "name": name});
+ p.as_object_mut().unwrap().extend(ends.as_object().unwrap().clone());
+ run(&mut s, "joint.create", p);
+ }
+ s
+}
+
+fn png() -> String {
+ let mut b = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec();
+ b.extend(400u32.to_be_bytes());
+ b.extend(200u32.to_be_bytes());
+ b.extend([8, 6, 0, 0, 0, 0, 0, 0, 0]);
+ solidcraft_doc::canvas::base64_encode(&b)
+}
+
+/// Every form of the command, in warn without warnings: the reply matches the output schema and
+/// has the keys it had before (and no `param_warnings`).
+#[test]
+fn replies_match_the_output_schema() {
+ let keys = |r: &Value| r.as_object().map(|o| o.keys().cloned().collect::<std::collections::BTreeSet<_>>()).unwrap_or_default();
+ let expected: std::collections::BTreeSet<String> =
+ ["bodies", "deleted", "deleted_joints", "skipped", "would_fail"].into_iter().map(String::from).collect();
+ let check = |r: &Value| {
+ matches(output_schema_for::<SelectionDeleteResult>(), r);
+ assert_eq!(keys(r), expected, "{r}");
+ };
+ let mut s = part();
+ let sketch = s.doc.features.first().map(|f| f.id).unwrap();
+ // A dry run, then the real thing.
+ let n = s.doc.features.len();
+ let r = run(&mut s, "selection.delete", json!({"items": [{"type": "feature", "id": sketch}], "dry_run": true}));
+ check(&r);
+ assert_eq!(s.doc.features.len(), n);
+ assert!(r["deleted"].as_array().is_some_and(|d| d.len() >= 2), "{r}");
+ let done = run(&mut s, "selection.delete", json!({"items": [{"type": "feature", "id": sketch}]}));
+ check(&done);
+ assert_eq!(done, r, "the dry run says what the delete did");
+ assert_eq!((&done["deleted_joints"], &done["skipped"]), (&json!([]), &json!([])), "{done}");
+ // A body (a Remove feature), and an item that can't go, with its reason once.
+ let body = s.model.state().bodies[0].name.clone();
+ let plane = json!({"type": "plane", "name": "XY"});
+ let r = run(&mut s, "selection.delete", json!({"items": [{"type": "body", "name": body}, plane, plane]}));
+ check(&r);
+ assert_eq!(r["bodies"], json!([body]), "{r}");
+ assert_eq!(r["skipped"], json!(["the origin planes can't be deleted"]), "{r}");
+ // A canvas by id, with the other keys `null`.
+ run(&mut s, "canvas.insert", json!({"data": png()}));
+ let canvas = s.doc.canvases[0].id;
+ let r = run(&mut s, "selection.delete", json!({"canvases": [canvas], "items": null, "components": null, "joints": null, "dry_run": false}));
+ check(&r);
+ assert!(s.doc.canvases.is_empty());
+ // A point cloud, by id.
+ let dir = std::env::temp_dir().join(format!("solidcraft-delete-schema-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("two.xyz");
+ std::fs::write(&path, "0 0 0\n1 0 0\n").unwrap();
+ let cloud = run(&mut s, "pointcloud.insert", json!({"path": path}))["cloud"].clone();
+ let r = run(&mut s, "selection.delete", json!({"point_clouds": [cloud]}));
+ check(&r);
+ let _ = std::fs::remove_dir_all(dir);
+
+ // Joints, an occurrence of a component with others, and a component.
+ let mut s = joint_assembly();
+ let hinge = s.doc.assembly.joints[0].id;
+ let r = run(&mut s, "selection.delete", json!({"joints": [hinge, "Glue"], "dry_run": true}));
+ check(&r);
+ assert_eq!(r["deleted_joints"].as_array().map(Vec::len), Some(2), "{r}");
+ let r = run(&mut s, "selection.delete", json!({"joints": [hinge, "Glue"]}));
+ check(&r);
+ assert!(s.doc.assembly.joints.is_empty());
+ let b2 = run(&mut s, "occurrence.copy", json!({"occurrence": "B:1", "translate": [0, 40, 0]}))["occurrence"].as_u64().unwrap();
+ let r = run(&mut s, "selection.delete", json!({"occurrences": ["B:1"]}));
+ check(&r);
+ assert!(s.doc.occurrences.iter().any(|o| o.id == b2));
+ let r = run(&mut s, "selection.delete", json!({"components": ["C"], "items": []}));
+ check(&r);
+ assert!(s.doc.components.iter().all(|c| c.name != "C"));
+ // A selected occurrence, by its exact path.
+ let o = s.doc.occurrences.iter().find(|o| o.name == "A:1").unwrap().id;
+ let r = run(&mut s, "selection.delete", json!({"items": [{"type": "occurrence", "path": [o]}], "dry_run": true}));
+ check(&r);
+}
+
+/// A misspelt key runs in warn and says so, the reply still matches the schema; strict refuses it.
+#[test]
+fn a_misspelt_key_is_reported_in_warn_and_refused_in_strict() {
+ let mut s = part();
+ let sketch = s.doc.features.first().map(|f| f.id).unwrap();
+ let p = json!({"items": [{"type": "feature", "id": sketch}], "dryrun": true});
+ let r = s.execute("selection.delete", &p).unwrap();
+ assert!(r["param_warnings"].as_array().is_some_and(|w| w.iter().any(|w| w.as_str().is_some_and(|w| w.contains("`dryrun`")))), "{r}");
+ matches(output_schema_for::<SelectionDeleteResult>(), &r);
+ assert!(s.doc.feature(sketch).is_none(), "the call still ran");
+ s.param_check = ParamCheck::Strict;
+ let error = s.execute("selection.delete", &json!({"items": [], "dryrun": true})).err().map(|e| e.to_string()).unwrap_or_default();
+ assert!(error.contains("`dryrun`"), "{error}");
+}
diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs
index 818c6e875e..86dbd2985c 100644
--- a/crates/engine/src/schema/mod.rs
+++ b/crates/engine/src/schema/mod.rs
@@ -64,6 +64,7 @@ pub mod component;
pub mod component_link;
pub mod config;
pub mod construct;
+pub mod delete;
pub mod diagnostics;
pub mod edit;
pub mod features;
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index c9300b512b..e08d44814b 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -106,7 +106,6 @@ render.start
render.status
select.clear
select.set
-selection.delete
sheet.export_bend_table
sheet.export_dxf
sheet.flat_pattern