SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Agent cursor: bound the show per request; run engine.batch while shown (#2900)
SS-EN9c26f6dbc933
diff --git a/crates/ui-egui/src/agent_cursor.rs b/crates/ui-egui/src/agent_cursor.rsindex 676ab5e0a6..7844ad6b3e 100644--- a/crates/ui-egui/src/agent_cursor.rs+++ b/crates/ui-egui/src/agent_cursor.rs@@ -6,6 +6,12 @@//! waits for the animation, so an agent's timing stays honest. With "follow camera" on, a new//! sketch turns the view to face it and finishing the sketch turns back.//!+//! The show is bounded, whatever the request's size: besides the toolbar button the pointer+//! visits at most [`MAX_PICK_STOPS`] picks (a long point list is summarised by its first, middle+//! and last point on screen), and one request is acted out in at most [`TIME_BUDGET`] seconds+//! (the legs get shorter when there are many). An `engine.batch` is acted out the same way, as+//! one request: the toolbar buttons of a few of its commands, then the whole batch runs.+//!//! The pointer is drawn by the app, so screen recordings capture it. It is off by default (View//! settings on the navigation bar, or `ui.agent_cursor {show, speed, follow_camera}`); a call//! with `"animate": false` skips it.@@ -62,7 +68,7 @@ impl Speed {}}/// Seconds to glide to a stop, and to click there.- fn times(self) -> (f64, f64) {+ pub(crate) fn times(self) -> (f64, f64) {match self {Speed::Instant => (0.0, 0.0),Speed::Times(x) => {@@ -119,6 +125,9 @@ pub struct Job {params: Value,reply: Sender<ControlResponse>,stops: VecDeque<Pos2>,+ /// Seconds per glide and per click for this request (within [`TIME_BUDGET`] in all).+ glide: f64,+ click: f64,/// The leg under way: where it started and when.from: Pos2,started: f64,@@ -144,26 +153,75 @@ impl AgentCursor {}}+/// Most picks the pointer visits for one command, besides its toolbar button. More are+/// summarised by evenly spaced ones (the first, the middle and the last of three).+pub const MAX_PICK_STOPS: usize = 3;++/// Most toolbar buttons the pointer visits for one `engine.batch` (of its distinct commands,+/// evenly spaced).+pub const MAX_BATCH_STOPS: usize = 4;++/// Longest the pointer may take to act out one request (a command or a whole batch), in+/// seconds, whatever its size: the app answers no other control request meanwhile.+pub const TIME_BUDGET: f64 = 1.5;++/// At most `n` of `items`, evenly spaced, keeping the first and (for two or more) the last.+fn summarise<T: Copy>(items: &[T], n: usize) -> Vec<T> {+ if items.len() <= n {+ return items.to_vec();+ }+ if n <= 1 {+ return items.iter().take(n).copied().collect();+ }+ let last = items.len() - 1;+ (0..n).filter_map(|i| items.get(i * last / (n - 1)).copied()).collect()+}++/// Seconds per glide and per click for `stops` stops at `speed`: the speed's own, shortened so+/// the whole request takes at most [`TIME_BUDGET`].+pub fn leg_times(speed: Speed, stops: usize) -> (f64, f64) {+ let (glide, click) = speed.times();+ let total = stops as f64 * (glide + click);+ if total > TIME_BUDGET {+ let k = TIME_BUDGET / total;+ (glide * k, click * k)+ } else {+ (glide, click)+ }+}+/// Keys whose [x, y, z] values are directions or amounts, not places to point at.const NOT_PLACES: [&str; 14] =["translate", "dir1", "dir2", "axis", "direction", "normal", "pull", "color", "x_dir", "y_dir", "scale", "values", "limits", "size"];-/// Where the pointer goes for a command: its toolbar button (or its panel), then each pick.+/// A command's toolbar button, or its panel when the button sits in a drop-down.+fn button(command: &str) -> Option<Pos2> {+ let spec = solidcraft_engine::find_command(command)?;+ crate::scenario::handle_at(&format!("toolbar:{}", spec.id)).or_else(|| crate::scenario::handle_at(&format!("panel:{}:{}", spec.tab, spec.panel)))+}++/// Where the pointer goes for a command: its toolbar button (or its panel), then its picks on+/// screen, at most [`MAX_PICK_STOPS`] of them.pub fn stops(app: &SolveApp, command: &str, params: &Value) -> Vec<Pos2> {- let mut out = Vec::new();- if let Some(spec) = solidcraft_engine::find_command(command) {- let button = crate::scenario::handle_at(&format!("toolbar:{}", spec.id))- .or_else(|| crate::scenario::handle_at(&format!("panel:{}:{}", spec.tab, spec.panel)));- out.extend(button);- }+ let mut out: Vec<Pos2> = button(command).into_iter().collect();let Some(rect) = app.viewport.rect else { return out };let proj = crate::viewport::projection(app, rect);- for w in picks(app, command, params) {- if let Some(p) = proj.to_screen(w).filter(|p| rect.contains(*p)) {- out.push(p);+ let on_screen: Vec<Pos2> = picks(app, command, params).into_iter().filter_map(|w| proj.to_screen(w).filter(|p| rect.contains(*p))).collect();+ out.extend(summarise(&on_screen, MAX_PICK_STOPS));+ out+}++/// Where the pointer goes for an `engine.batch`: the toolbar buttons of its distinct commands, in+/// the order they first come, at most [`MAX_BATCH_STOPS`] of them.+pub fn batch_stops(steps: &[Value]) -> Vec<Pos2> {+ let mut seen: Vec<&str> = Vec::new();+ for c in steps.iter().filter_map(crate::control::batch_step_command) {+ if !seen.contains(&c) {+ seen.push(c);}}- out+ let buttons: Vec<Pos2> = seen.into_iter().filter_map(button).collect();+ summarise(&buttons, MAX_BATCH_STOPS)}/// The places a command's parameters pick, in the world: [x, y, z] points (faces, edges,@@ -230,15 +288,22 @@ fn walk<'a>(v: &'a Value, key: Option<&'a str>, f: &mut dyn FnMut(Option<&'a str/// back when it should simply run.pub fn intercept(app: &mut SolveApp, method: &str, params: &Value, reply: &Sender<ControlResponse>) -> bool {let s = app.ui.agent_cursor;- if !s.show || !matches!(method, "engine.execute" | "command") {+ if !s.show || params.get("animate").and_then(Value::as_bool) == Some(false) {return false;}- if params.get("animate").and_then(Value::as_bool) == Some(false) {- return false;- }- let Some(cmd) = params.get("command").or(params.get("id")).and_then(Value::as_str) else { return false };- let inner = params.get("params").cloned().unwrap_or(json!({}));- let stops: VecDeque<Pos2> = stops(app, cmd, &inner).into();+ let stops: VecDeque<Pos2> = match method {+ "engine.execute" | "command" => {+ let Some(cmd) = params.get("command").or(params.get("id")).and_then(Value::as_str) else { return false };+ let inner = params.get("params").cloned().unwrap_or(json!({}));+ stops(app, cmd, &inner).into()+ }+ // A batch is acted out as one request; one the app refuses is answered at once.+ "engine.batch" => match params.get("commands").and_then(Value::as_array) {+ Some(steps) if crate::control::batch_refusal(steps).is_none() => batch_stops(steps).into(),+ _ => return false,+ },+ _ => return false,+ };if s.speed == Speed::Instant {// No animation: the command runs now; the pointer jumps to where it acted.if let Some(last) = stops.back() {@@ -251,8 +316,18 @@ pub fn intercept(app: &mut SolveApp, method: &str, params: &Value, reply: &Sendereturn false;}let from = app.cursor_start();- app.agent.job =- Some(Job { method: method.to_string(), params: params.clone(), reply: reply.clone(), stops, from, started: app.now, clicked: false });+ let (glide, click) = leg_times(s.speed, stops.len());+ app.agent.job = Some(Job {+ method: method.to_string(),+ params: params.clone(),+ reply: reply.clone(),+ stops,+ glide,+ click,+ from,+ started: app.now,+ clicked: false,+ });true}@@ -275,8 +350,8 @@ pub fn step(app: &mut SolveApp, ctx: &egui::Context) {if !app.agent.ripples.is_empty() {ctx.request_repaint();}- let (glide, click) = app.ui.agent_cursor.speed.times();let Some(job) = app.agent.job.as_mut() else { return };+ let (glide, click) = (job.glide, job.click);ctx.request_repaint();let Some(&to) = job.stops.front() else {finish(app, ctx);@@ -391,6 +466,74 @@ mod tests {assert!(stops(&a, "solid.hole", &json!({"position": [1e6, 0, 0]})).iter().all(|p| rect.contains(*p)));}+ /// A ring of points around the box's top, `n` of them, in active-sketch coordinates.+ fn ring(n: usize) -> Vec<[f64; 2]> {+ (0..n)+ .map(|i| {+ let t = i as f64 / n as f64 * std::f64::consts::TAU;+ [20.0 + 12.0 * t.cos(), 15.0 + 12.0 * t.sin()]+ })+ .collect()+ }++ /// A 720-point line is not acted out point by point (that took minutes): the pointer visits+ /// at most a few representative points.+ #[test]+ fn long_point_lists_are_summarised() {+ let mut a = app();+ a.session.execute("sketch.create", &json!({"plane": "XY"})).unwrap();+ let p = json!({"points": ring(720), "closed": true});+ assert!(picks(&a, "sketch.line", &p).len() >= 700, "every point is still a pick");+ let s = stops(&a, "sketch.line", &p);+ assert!(s.len() >= MAX_PICK_STOPS && s.len() <= 1 + MAX_PICK_STOPS, "{s:?}");+ // Few points are all visited.+ assert_eq!(stops(&a, "sketch.line", &json!({"points": ring(2)})).iter().filter(|p| a.viewport.rect.unwrap().contains(**p)).count(), 2);+ assert_eq!(summarise(&[1, 2, 3, 4, 5, 6, 7], 3), vec![1, 4, 7]);+ assert_eq!(summarise(&[1, 2], 3), vec![1, 2]);+ assert_eq!(summarise(&[1, 2, 3], 1), vec![1]);+ assert!(summarise(&[1, 2, 3], 0).is_empty());+ }++ /// However many stops, one request is acted out within the time budget; a short one keeps+ /// the speed's own pace.+ #[test]+ fn one_request_is_acted_out_within_the_time_budget() {+ for speed in [Speed::Times(1.0), Speed::Times(2.5), Speed::Times(5.0), Speed::Instant] {+ for n in 0..=12 {+ let (g, c) = leg_times(speed, n);+ assert!(n as f64 * (g + c) <= TIME_BUDGET + 1e-9, "{speed:?} {n}: {g} {c}");+ assert!(g >= 0.0 && c >= 0.0);+ }+ }+ assert_eq!(leg_times(Speed::Times(1.0), 1), Speed::Times(1.0).times());+ assert_eq!(leg_times(Speed::Times(5.0), 4), Speed::Times(5.0).times());+ }++ /// End to end: with the cursor shown, a 720-point line and a batch are each answered within+ /// the time budget (in frames of 1/60 s), and the batch runs instead of being refused.+ #[test]+ fn big_requests_and_batches_are_acted_out_quickly() {+ let mut h = crate::scenario::Harness::new();+ assert_eq!(h.call("ui.agent_cursor", json!({"show": true, "speed": 1}))["ok"], true);+ assert_eq!(h.call("engine.execute", json!({"command": "sketch.create", "params": {"plane": "XY"}}))["ok"], true);+ let most = (TIME_BUDGET * 60.0) as usize + 2 * (2 + MAX_PICK_STOPS) + 8;+ let (r, frames) = h.call_queued("engine.execute", json!({"command": "sketch.line", "params": {"points": ring(720), "closed": true}}));+ assert_eq!(r["ok"], true, "{r}");+ assert!(frames <= most, "{frames} frames (at most {most})");+ assert_eq!(h.call("engine.execute", json!({"command": "sketch.finish"}))["ok"], true);+ let steps = json!([+ {"command": "solid.box", "params": {"length": 10, "width": 10, "height": 10, "corner": [60, 0, 0]}},+ {"command": "solid.sphere", "params": {"radius": 3, "center": [80, 0, 0]}},+ ]);+ let (r, frames) = h.call_queued("engine.batch", json!({"commands": steps}));+ assert_eq!((&r["ok"], &r["result"]["completed"]), (&json!(true), &json!(2)), "{r}");+ assert!(frames <= most, "{frames} frames (at most {most})");+ // A batch the app refuses is answered at once, without a show.+ let (r, frames) = h.call_queued("engine.batch", json!({"commands": [{"command": "doc.open", "params": {"path": "x.solidcraft"}}]}));+ assert!(r["error"].as_str().is_some_and(|e| e.starts_with("engine.batch unavailable")), "{r}");+ assert!(frames <= 3, "{frames}");+ }+#[test]fn speeds_read_old_and_new_settings() {// Saved settings from before #79: slow and normal are 1×, instant stays.diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rsindex a96f0c5c15..4720d5a7a1 100644--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@ -5,8 +5,9 @@//! - `engine.script {commands: [...]}`: run a command script//! - `engine.batch {commands: [...], rollback?}`: the steps in one request, each as//! `engine.execute` runs it; stops at the first failure and goes back to the checkpoint-//! (per-step results, `failed`, `undone`). Refused (`engine.batch unavailable: …`) while the-//! agent cursor is shown or when a step loads a file+//! (per-step results, `failed`, `undone`, `rolled_back`). Refused (`engine.batch unavailable: …`)+//! when a step loads a file; with the agent cursor shown, the pointer acts out a short summary+//! of it first//! - `engine.commands`: every command with tab, panel, params and enablement//! - `document.inspect {measure?}`: the design (parameters, timeline, bodies, sketches)//! - `ui.inspect`: UI state, viewport rect, camera, tool and dialog@@ -122,6 +123,18 @@ const MAX_BATCH: usize = 10_000;/// bypass.const LOADS_A_FILE: [&str; 3] = ["doc.open", "file.insert_step", "file.insert_mesh"];+/// Why `engine.batch` refuses these steps before running any: a step loads a file (send such+/// steps one by one).+pub(crate) fn batch_refusal(steps: &[Value]) -> Option<String> {+ let (i, c) = steps.iter().enumerate().find_map(|(i, step)| command(step).filter(|c| LOADS_A_FILE.contains(c)).map(|c| (i, c)))?;+ Some(format!("engine.batch unavailable: step {i} ({c}) loads a file"))+}++/// A batch step's command id (the agent cursor points at its toolbar button).+pub(crate) fn batch_step_command(step: &Value) -> Option<&str> {+ command(step)+}+/// `engine.batch {commands, rollback?, timings?, profile?}`: the steps in one request, so in one/// frame (#743). With `timings` the reply adds each step's time and `total_ms`, with `profile`/// each step's kernel share too (`solidcraft_engine::timing`, #1833). Each@@ -133,12 +146,10 @@ fn batch(app: &mut SolveApp, p: &Value) -> Outcome {let Some(steps) = p.get("commands").and_then(Value::as_array).filter(|s| s.len() <= MAX_BATCH) else {return err(format!("engine.batch: commands must be an array of at most {MAX_BATCH} steps"));};- // The agent cursor acts out each `engine.execute` on its own.- if app.ui.agent_cursor.show {- return err("engine.batch unavailable: the agent cursor is shown");- }- if let Some((i, c)) = steps.iter().enumerate().find_map(|(i, step)| command(step).filter(|c| LOADS_A_FILE.contains(c)).map(|c| (i, c))) {- return err(format!("engine.batch unavailable: step {i} ({c}) loads a file"));+ // (With the agent cursor shown, the pointer has already acted out a short summary of the+ // batch: `agent_cursor::intercept`.)+ if let Some(why) = batch_refusal(steps) {+ return err(why);}let rollback = p.get("rollback").and_then(Value::as_bool).unwrap_or(true);let profile = p.get("profile").and_then(Value::as_bool).unwrap_or(false);@@ -160,7 +171,9 @@ fn batch(app: &mut SolveApp, p: &Value) -> Outcome {Err(e) => {let restored = checkpoint.is_some_and(|id| app.run("edit.restore_checkpoint", json!({"checkpoint": id})).is_ok());let failed = json!({"index": i, "command": command(step), "error": e});- let reply = json!({"completed": i, "results": results, "failed": failed, "undone": if restored { i } else { 0 }});+ // `rolled_back`: the design really is back at its checkpoint.+ let reply =+ json!({"completed": i, "results": results, "failed": failed, "undone": if restored { i } else { 0 }, "rolled_back": restored});return ok(with_timings(reply, timed, rows, clock.ms()));}}@@ -1225,13 +1238,26 @@ mod tests {}#[test]- fn engine_batch_is_refused_while_the_agent_cursor_is_shown() {+ fn engine_batch_runs_while_the_agent_cursor_is_shown() {let mut h = crate::scenario::Harness::new();assert_eq!(h.call("ui.agent_cursor", json!({"show": true}))["ok"], true);let v = batch(&mut h, json!({"commands": [{"command": "solid.box", "params": {"length": 10, "width": 10, "height": 10}}]}));- assert_eq!(v["ok"], false, "{v}");- assert!(v["error"].as_str().is_some_and(|e| e.starts_with("engine.batch unavailable")), "{v}");- assert_eq!(inspect(&mut h)["bodies"].as_array().map(Vec::len), Some(0));+ assert_eq!(v["ok"], true, "{v}");+ assert_eq!(v["result"]["completed"], 1, "{v}");+ assert_eq!(inspect(&mut h)["bodies"].as_array().map(Vec::len), Some(1));+ }++ /// A failed batch says whether the design really went back (`rolled_back`), not just whether+ /// it was asked to.+ #[test]+ fn engine_batch_reports_whether_it_rolled_back() {+ let mut h = crate::scenario::Harness::new();+ let steps = json!([{"command": "solid.box", "params": {"length": 10, "width": 10, "height": 10}}, {"command": "NoSuchCommand"}]);+ let v = batch(&mut h, json!({"commands": steps.clone()}));+ assert_eq!((&v["result"]["rolled_back"], &v["result"]["undone"]), (&json!(true), &json!(1)), "{v}");+ let v = batch(&mut h, json!({"commands": steps, "rollback": false}));+ assert_eq!((&v["result"]["rolled_back"], &v["result"]["undone"]), (&json!(false), &json!(0)), "{v}");+ assert_eq!(inspect(&mut h)["bodies"].as_array().map(Vec::len), Some(1));}/// Every step of a batch from an MCP server stays inside the agent's folders (#205), as an