SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Typed schemas for Undo, Redo and the checkpoints (part of #2829) (#10945)
semmelrinde6602ab823f31
diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rsindex cbbd433f10..7d16e861c5 100644--- a/crates/engine/src/cmd/edit.rs+++ b/crates/engine/src/cmd/edit.rs@@ -18,8 +18,20 @@ pub static COMMANDS: &[CommandSpec] = &[.contract(&ASSISTANT_CONTRACT).output(crate::schema::output_schema_for::<crate::schema::edit::AssistantResult>).params("Show or hide Assistant in the app. Headless calls are refused without changing the design"),- CommandSpec::new("edit.undo", "Undo", undo).icon("undo").key("Ctrl+Z").noundo().doc_only(),- CommandSpec::new("edit.redo", "Redo", redo).icon("redo").key("Ctrl+Y").noundo().doc_only(),+ CommandSpec::new("edit.undo", "Undo", crate::checked!("edit.undo", undo))+ .icon("undo")+ .key("Ctrl+Z")+ .noundo()+ .doc_only()+ .contract(&UNDO_CONTRACT)+ .output(crate::schema::output_schema_for::<crate::schema::edit::UndoResult>),+ CommandSpec::new("edit.redo", "Redo", crate::checked!("edit.redo", redo))+ .icon("redo")+ .key("Ctrl+Y")+ .noundo()+ .doc_only()+ .contract(&REDO_CONTRACT)+ .output(crate::schema::output_schema_for::<crate::schema::edit::RedoResult>),CommandSpec::new("edit.repeat", "Repeat Last Command", crate::checked!("edit.repeat", repeat)).icon("redo").key("Shift+R")@@ -28,13 +40,17 @@ pub static COMMANDS: &[CommandSpec] = &[.contract(&REPEAT_CONTRACT).output(crate::schema::output_schema_for::<crate::schema::edit::RepeatResult>).params("Starts the last tool or dialog started in the app again, with its defaults (a toolbar click, not a replay of its values). Only the app has a tool to start: called here it is refused, and changes nothing"),- CommandSpec::new("edit.checkpoint", "Checkpoint", checkpoint).icon("checkpoint")+ CommandSpec::new("edit.checkpoint", "Checkpoint", crate::checked!("edit.checkpoint", checkpoint)).icon("checkpoint").noundo().doc_only()+ .contract(&CHECKPOINT_CONTRACT)+ .output(crate::schema::output_schema_for::<crate::schema::edit::CheckpointResult>).params("→ {checkpoint: id}: remember the design, active sketch and undo history (restore with edit.restore_checkpoint; the last 16 are kept, the oldest dropped first)"),- CommandSpec::new("edit.restore_checkpoint", "Restore Checkpoint", restore_checkpoint).icon("restore")+ CommandSpec::new("edit.restore_checkpoint", "Restore Checkpoint", crate::checked!("edit.restore_checkpoint", restore_checkpoint)).icon("restore").noundo().doc_only()+ .contract(&RESTORE_CHECKPOINT_CONTRACT)+ .output(crate::schema::output_schema_for::<crate::schema::edit::CheckpointResult>).params("checkpoint: id; forget?: bool (true = drop it without going back). Goes back to it, undo history included. Restoring or forgetting uses it and every later checkpoint up: take a new one to go back again"),CommandSpec::new("timeline.compute_all", "Compute All", compute_all).at("SOLID", "MODIFY").icon("compute").noundo(),CommandSpec::new("timeline.play", "Play History", crate::checked!("timeline.play", play))@@ -111,12 +127,22 @@ fn play(_s: &mut Session, p: &Value) -> Result<Value> {serde_json::to_value(crate::schema::edit::TimelinePlayResult { action: request.action }).map_err(|e| EngineError::Other(e.to_string()))}+const UNDO_CONTRACT: crate::schema::TypedContract<crate::schema::edit::UndoParams> = crate::schema::TypedContract::new();+const REDO_CONTRACT: crate::schema::TypedContract<crate::schema::edit::RedoParams> = crate::schema::TypedContract::new();+const CHECKPOINT_CONTRACT: crate::schema::TypedContract<crate::schema::edit::CheckpointParams> = crate::schema::TypedContract::new();+const RESTORE_CHECKPOINT_CONTRACT: crate::schema::TypedContract<crate::schema::edit::RestoreCheckpointParams> = crate::schema::TypedContract::new();++/// A reply built from its schema's type, so the two can't drift apart.+fn reply(cmd: &str, r: impl serde::Serialize) -> Result<Value> {+ serde_json::to_value(r).map_err(|e| bad(cmd, e.to_string()))+}+fn undo(s: &mut Session, _p: &Value) -> Result<Value> {let Some(prev) = s.undo.pop() else { return Err(EngineError::Other("nothing to undo".into())) };let now = go_to(s, prev);let label = now.label.clone();s.redo.push(now);- Ok(json!({"undone": label}))+ reply("edit.undo", crate::schema::edit::UndoResult { undone: label, param_warnings: Vec::new() })}fn redo(s: &mut Session, _p: &Value) -> Result<Value> {@@ -124,7 +150,7 @@ fn redo(s: &mut Session, _p: &Value) -> Result<Value> {let now = go_to(s, next);let label = now.label.clone();s.undo.push(now);- Ok(json!({"redone": label}))+ reply("edit.redo", crate::schema::edit::RedoResult { redone: label, param_warnings: Vec::new() })}const ASSISTANT_CONTRACT: crate::schema::TypedContract<crate::schema::edit::AssistantParams> = crate::schema::TypedContract::new();@@ -172,18 +198,21 @@ fn go_to(s: &mut Session, snap: Snapshot) -> Snapshot {}fn checkpoint(s: &mut Session, _p: &Value) -> Result<Value> {- Ok(json!({"checkpoint": s.checkpoint()}))+ let checkpoint = s.checkpoint();+ reply("edit.checkpoint", crate::schema::edit::CheckpointResult { checkpoint, restored: None, param_warnings: Vec::new() })}fn restore_checkpoint(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "edit.restore_checkpoint";let id = p.get("checkpoint").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "`checkpoint` must be an id from edit.checkpoint"))?;+ let done =+ |restored: bool| reply(cmd, crate::schema::edit::CheckpointResult { checkpoint: id, restored: Some(restored), param_warnings: Vec::new() });if bool_(p, "forget") == Some(true) {s.drop_checkpoint(id);- return Ok(json!({"checkpoint": id, "restored": false}));+ return done(false);}s.restore_checkpoint(id)?;- Ok(json!({"checkpoint": id, "restored": true}))+ done(true)}fn compute_all(s: &mut Session, _p: &Value) -> Result<Value> {diff --git a/crates/engine/src/schema/edit.rs b/crates/engine/src/schema/edit.rsindex c84cf96742..cffdbac66f 100644--- a/crates/engine/src/schema/edit.rs+++ b/crates/engine/src/schema/edit.rs@@ -1,7 +1,11 @@//! Contracts and result types for the commands in `cmd/edit.rs`.-use schemars::JsonSchema;-use serde::{Deserialize, Serialize};+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;/// Assistant visibility is UI-owned and takes no parameters.#[derive(Debug, Deserialize, JsonSchema)]@@ -46,15 +50,139 @@ pub struct TimelinePlayResult {pub action: PlaybackAction,}+/// `edit.undo` takes no parameters: it takes back the last step of the undo history.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct UndoParams {}++/// What `edit.undo` returns. With nothing to undo it is refused.+#[derive(Debug, Serialize, JsonSchema)]+pub struct UndoResult {+ /// The name of the step taken back, as the undo history labels it.+ pub undone: 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>,+}++/// `edit.redo` takes no parameters: it does again the last step undone.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct RedoParams {}++/// What `edit.redo` returns. With nothing to redo it is refused.+#[derive(Debug, Serialize, JsonSchema)]+pub struct RedoResult {+ /// The name of the step done again, as the undo history labels it.+ pub redone: 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>,+}++/// `edit.checkpoint` takes no parameters: it remembers the design, the active sketch and the+/// undo history, to go back to with `edit.restore_checkpoint`. The last 16 are kept, the oldest+/// dropped first.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct CheckpointParams {}++/// What `edit.checkpoint` and `edit.restore_checkpoint` return.+#[derive(Debug, Serialize, JsonSchema)]+pub struct CheckpointResult {+ /// The checkpoint's id.+ pub checkpoint: u64,+ /// `edit.restore_checkpoint` only: true when the design went back to it, false when it was+ /// dropped (`forget`).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub restored: Option<bool>,+ /// 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 checkpoint's id, as `edit.checkpoint` returns it: a whole number of at least 0.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct CheckpointId(pub u64);++impl<'de> Deserialize<'de> for CheckpointId {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ Value::deserialize(d)?.as_u64().map(CheckpointId).ok_or_else(|| D::Error::custom("must be an id from edit.checkpoint"))+ }+}++impl JsonSchema for CheckpointId {+ fn schema_name() -> Cow<'static, str> {+ "CheckpointId".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({"description": "A checkpoint's id, from edit.checkpoint.", "type": "integer", "minimum": 0})+ }+}++/// Go back to a checkpoint, undo history included; or, with `forget`, drop it without going+/// back. Either uses it up and every later checkpoint with it: take a new one to go back again.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct RestoreCheckpointParams {+ /// The checkpoint, by the id `edit.checkpoint` returned.+ pub checkpoint: CheckpointId,+ /// True to drop the checkpoint (and every later one) without going back. Default: false.+ #[serde(default)]+ pub forget: Option<bool>,+}+#[cfg(test)]mod tests {- use super::{AssistantParams, RepeatParams};- use crate::schema::input_schema_for;- use crate::schema::tests::assert_keys;+ use serde_json::{Value, json};++ use super::{+ AssistantParams, CheckpointParams, CheckpointResult, RedoParams, RedoResult, RepeatParams, RestoreCheckpointParams, UndoParams, UndoResult,+ };+ use crate::Session;+ use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};+ use crate::schema::{ParamCheck, input_schema_for, output_schema_for};#[test]fn schemas_and_the_key_check_agree() {assert_keys(input_schema_for::<RepeatParams>(), &[]);assert_keys(input_schema_for::<AssistantParams>(), &[]);+ assert_keys(input_schema_for::<UndoParams>(), &[]);+ assert_keys(input_schema_for::<RedoParams>(), &[]);+ assert_keys(input_schema_for::<CheckpointParams>(), &[]);+ assert_keys(input_schema_for::<RestoreCheckpointParams>(), &["checkpoint", "forget"]);+ }++ #[test]+ fn strict_keeps_todays_errors() {+ assert_strict_keeps_todays_errors(&[+ ("edit.restore_checkpoint", json!({"checkpoint": "first"})),+ ("edit.restore_checkpoint", json!({"checkpoint": -1})),+ ]);+ }++ /// Undo, redo, a checkpoint, going back to it and forgetting one, in Warn: each reply matches+ /// its output schema and carries no warning.+ #[test]+ fn replies_match_the_output_schema() {+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };+ let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));+ let matches = |schema: schemars::Schema, id: &str, reply: &Value| {+ let schema = schema.as_value();+ assert!(reply.get("param_warnings").is_none() && conforms(schema, schema, reply), "{id}: {reply} doesn't match {schema}");+ };+ run("solid.box", json!({"length": 10, "width": 10, "height": 10}));+ matches(output_schema_for::<UndoResult>(), "edit.undo", &run("edit.undo", json!({})));+ matches(output_schema_for::<RedoResult>(), "edit.redo", &run("edit.redo", json!({})));+ let taken = run("edit.checkpoint", json!({}));+ matches(output_schema_for::<CheckpointResult>(), "edit.checkpoint", &taken);+ run("solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [20, 0, 0]}));+ let back = run("edit.restore_checkpoint", json!({"checkpoint": taken["checkpoint"]}));+ assert_eq!(back["restored"], true, "{back}");+ matches(output_schema_for::<CheckpointResult>(), "edit.restore_checkpoint", &back);+ let again = run("edit.checkpoint", json!({}));+ let dropped = run("edit.restore_checkpoint", json!({"checkpoint": again["checkpoint"], "forget": true}));+ assert_eq!(dropped["restored"], false, "{dropped}");+ matches(output_schema_for::<CheckpointResult>(), "edit.restore_checkpoint", &dropped);}}diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txtindex 80ecc747fd..8f1b9eaf48 100644--- a/crates/engine/src/schema/unconverted.txt+++ b/crates/engine/src/schema/unconverted.txt@@ -66,10 +66,6 @@ document.metadatadocument.metadata.removedocument.metadata.setdocument.units-edit.checkpoint-edit.redo-edit.restore_checkpoint-edit.undoengine.commandsexplode.createexplode.delete