SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Control: a whole-design measure reads a copy off the window thread (#4604) (#4614)
dudedagger422586b09f5a17
diff --git a/crates/ui-egui/src/control_job.rs b/crates/ui-egui/src/control_job.rsindex 0c2f1361bf..1089791a3b 100644--- a/crates/ui-egui/src/control_job.rs+++ b/crates/ui-egui/src/control_job.rs@@ -68,7 +68,13 @@ const NAMES_A_FILE: [&str; 8] = ["path", "paths", "file", "files", "dir", "folde/// Commands that change nothing in the design and write a file: they run on a copy.const ANSWERED_ON_A_COPY: [&str; 2] = ["file.export", "file.save_mesh"];-/// Exports computing at once; more run here.+/// Commands that only read the design, which can take long on a large one (a measure of every+/// body, an inspection that measures them, #4604; a clearance or interference check of every pair+/// of bodies, minutes on an assembly of 150): they run on a copy too, whatever the preference,+/// since an answer from the design as it was when asked has no order to keep.+const READ_ON_A_COPY: [&str; 4] = ["inspect.measure", "document.inspect", "inspect.clearance", "inspect.interference"];++/// Exports and readings computing at once; more run here.const MAX_ANSWERING: usize = 4;/// How often a design change is computed again because the design changed under it before it@@ -100,6 +106,20 @@ fn executed(params: &Value) -> Option<(&str, Value)> {Some((command, params.get("params").cloned().filter(|v| !v.is_null()).unwrap_or(json!({}))))}+/// A request that only reads the design and can take long ([`READ_ON_A_COPY`]): an+/// `engine.execute` of such a command, or the `document.inspect` method. The command and its+/// parameters.+fn reading(req: &ControlRequest) -> Option<(&'static str, Value)> {+ match req.method.as_str() {+ "document.inspect" => Some(("document.inspect", req.params.clone())),+ "engine.execute" | "command" => {+ let (command, params) = executed(&req.params)?;+ spec_id(command).filter(|id| READ_ON_A_COPY.contains(id)).map(|id| (id, params))+ }+ _ => None,+ }+}+/// Requests that change the design: they wait while one computes.pub(crate) fn changes_the_design(method: &str) -> bool {matches!(method, "engine.execute" | "command" | "engine.script" | "engine.batch")@@ -293,7 +313,18 @@ impl SolveApp {/// Take a control request off the window thread when it computes long (see the module/// notes). Returns it when it should simply run here now.pub(crate) fn offload_control(&mut self, ctx: &egui::Context, req: ControlRequest) -> Option<ControlRequest> {- if self.apply_off_thread.is_none() || !self.preferences.agent_off_thread || self.file_load.busy() || self.file_picker.is_some() {+ if self.apply_off_thread.is_none() || self.file_load.busy() || self.file_picker.is_some() {+ return Some(req);+ }+ // Reading the design (a measure, an inspection that measures): on a copy, answered from+ // there, preference or not. On a large assembly it took a minute on the window thread,+ // and the window, answering nothing meanwhile, was closed as not responding (#4604).+ if self.control_answering.len() < MAX_ANSWERING+ && let Some((id, params)) = reading(&req)+ {+ return self.answer_on_a_copy(req, id, params);+ }+ if !self.preferences.agent_off_thread {return Some(req);}// An export: on a copy, answered from there.@@ -302,21 +333,7 @@ impl SolveApp {&& let Some((command, params)) = executed(&req.params)&& let Some(id) = spec_id(command).filter(|id| ANSWERED_ON_A_COPY.contains(id)){- let Ok(scope) = crate::control::request_scope(self, &req.params) else { return Some(req) };- let mut copy = self.session.scratch();- let rx = spawn(scope, move || {- Some(match copy.execute(id, ¶ms) {- Ok(v) => json!({"ok": true, "result": v}),- Err(e) => json!({"ok": false, "error": e.to_string()}),- })- });- let Some(rx) = rx else { return Some(req) };- let job = ControlJob { label: label(self, id), req, work: Work::Answer, done: rx, started: crate::now_ms() };- match within_wait(self, &job.done) {- Some(reply) => self.answered(job, reply),- None => self.control_answering.push(job),- }- return None;+ return self.answer_on_a_copy(req, id, params);}let commands = ahead_commands(&req.method, &req.params);let Some(first) = commands.first().map(|(c, _)| c.clone()) else { return Some(req) };@@ -332,10 +349,33 @@ impl SolveApp {None}- /// An export's reply, from its copy, with the echo the command leaves when it runs here.+ /// Run command `id` on a copy of the session, off the window thread, and answer `req` from+ /// there: at once when it is done within the app's wait, otherwise once it is in. `None`: it+ /// is taken care of; `Some`: it runs here (no threads).+ fn answer_on_a_copy(&mut self, req: ControlRequest, id: &'static str, params: Value) -> Option<ControlRequest> {+ let Ok(scope) = crate::control::request_scope(self, &req.params) else { return Some(req) };+ let mut copy = self.session.scratch();+ let rx = spawn(scope, move || {+ Some(match copy.execute(id, ¶ms) {+ Ok(v) => json!({"ok": true, "result": v}),+ Err(e) => json!({"ok": false, "error": e.to_string()}),+ })+ });+ let Some(rx) = rx else { return Some(req) };+ let job = ControlJob { label: label(self, id), req, work: Work::Answer, done: rx, started: crate::now_ms() };+ match within_wait(self, &job.done) {+ Some(reply) => self.answered(job, reply),+ None => self.control_answering.push(job),+ }+ None+ }++ /// An export's or a reading's reply, from its copy, with the echo an export leaves when it+ /// runs here.fn answered(&mut self, job: ControlJob, reply: Option<Value>) {let reply = reply.unwrap_or_else(|| json!({"ok": false, "error": format!("`{}` ended without a reply", job.label)}));- if reply["ok"] == true {+ let export = executed(&job.req.params).and_then(|(command, _)| spec_id(command)).is_some_and(|id| ANSWERED_ON_A_COPY.contains(&id));+ if reply["ok"] == true && export {let language = crate::i18n::Locale::for_language(&self.preferences.language);self.session.echo(language.format("ui.command_done", &[("command", job.label.as_str())]));}diff --git a/crates/ui-egui/src/history_off_thread_tests.rs b/crates/ui-egui/src/history_off_thread_tests.rsindex 968d72158a..80356746be 100644--- a/crates/ui-egui/src/history_off_thread_tests.rs+++ b/crates/ui-egui/src/history_off_thread_tests.rs@@ -177,10 +177,11 @@ fn an_agent_design_change_computes_off_the_window_thread() {h.frames(1);assert!(h.app.agent_computing().is_some_and(|(_, label)| !label.is_empty()), "the window says the agent's command computes");assert!(view.try_recv().is_ok_and(|v| v["ok"] == true), "ui.* answered while it computes");- let seen = inspect.try_recv().expect("inspection answered while it computes");- assert_eq!(seen["result"]["timeline"].as_array().map(Vec::len), Some(features), "the design as it was: {seen}");assert!(boss.try_recv().is_err(), "the next design change waits its turn");assert_eq!(h.app.session.doc.features.len(), features, "nothing applied yet");+ // The inspection reads a copy of the design as it was when asked, off the window thread.+ let seen = reply_to(&mut h, &inspect);+ assert_eq!(seen["result"]["timeline"].as_array().map(Vec::len), Some(features), "the design as it was: {seen}");let r = reply_to(&mut h, &hole);assert_eq!(r["ok"], true, "{r}");let r = reply_to(&mut h, &boss);@@ -283,6 +284,63 @@ fn an_agent_export_runs_on_a_copy() {let _ = std::fs::remove_dir_all(&dir);}+/// #4604: measuring the whole design (an inspection measures every body) reads a copy off the+/// window thread, preference or not: on a large assembly it took a minute, the window answered+/// nothing meanwhile and was closed as not responding. The window answers `ui.*` while it+/// measures, and the measure comes back as when it runs here.+#[test]+fn a_measure_reads_a_copy_off_the_window_thread_preference_or_not() {+ let (mut h, tx) = agent_harness();+ h.app.preferences.agent_off_thread = false;+ let here = h.app.run("inspect.measure", json!({})).unwrap();+ let log = h.app.session.log.len();+ let measure = ask(&tx, "engine.execute", json!({"command": "inspect.measure", "params": {}}));+ let inspect = ask(&tx, "document.inspect", json!({"measure": true}));+ let command = ask(&tx, "command", json!({"command": "document.inspect", "params": {"measure": true}}));+ let view = ask(&tx, "ui.inspect", json!({}));+ h.frames(1);+ assert!(view.try_recv().is_ok_and(|v| v["ok"] == true), "ui.* answered meanwhile");+ assert_eq!(h.app.control_answering.len(), 3, "all three read a copy");+ let r = reply_to(&mut h, &measure);+ assert_eq!(r["result"]["total"], here["total"], "{r}");+ for reply in [inspect, command] {+ let r = reply_to(&mut h, &reply);+ assert_eq!(r["ok"], true, "{r}");+ assert!(r["result"]["timeline"].is_array(), "{r}");+ }+ assert!(h.app.control_answering.is_empty());+ assert_eq!(h.app.session.log.len(), log, "a reading leaves no echo: {:?}", h.app.session.log);+}++/// A clearance or interference check of every pair of bodies reads a copy off the window thread+/// too: on an assembly of 150 bodies it computed for minutes with the window not responding. The+/// answers are the ones running it here gives.+#[test]+fn a_clearance_check_reads_a_copy_off_the_window_thread() {+ let (mut h, tx) = agent_harness();+ h.app.preferences.agent_off_thread = false;+ // The answers but their timing.+ let untimed = |mut v: serde_json::Value| {+ if let Some(o) = v.as_object_mut() {+ o.remove("ms");+ }+ v+ };+ let clearance_here = untimed(h.app.run("inspect.clearance", json!({})).unwrap());+ let interference_here = untimed(h.app.run("inspect.interference", json!({})).unwrap());+ let clearance = ask(&tx, "engine.execute", json!({"command": "inspect.clearance", "params": {}}));+ let interference = ask(&tx, "engine.execute", json!({"command": "inspect.interference", "params": {}}));+ let view = ask(&tx, "ui.inspect", json!({}));+ h.frames(1);+ assert!(view.try_recv().is_ok_and(|v| v["ok"] == true), "ui.* answered meanwhile");+ assert_eq!(h.app.control_answering.len(), 2, "both read a copy");+ let r = reply_to(&mut h, &clearance);+ assert_eq!(untimed(r["result"].clone()), clearance_here, "{r}");+ let r = reply_to(&mut h, &interference);+ assert_eq!(untimed(r["result"].clone()), interference_here, "{r}");+ assert!(h.app.control_answering.is_empty());+}+/// With the preference off (Preferences > AI, the default) an agent's design change runs on the/// window thread, as before: answered in the frame it arrives.#[test]@@ -320,9 +378,9 @@ fn the_window_answers_while_the_agent_cursor_acts_out_a_design_change() {h.frames(1);assert!(h.app.agent.busy());assert!(view.try_recv().is_ok_and(|v| v["ok"] == true), "ui.* answered while the pointer acts out the command");- assert!(inspect.try_recv().is_ok_and(|v| v["ok"] == true), "inspection answered too");assert!(boss.try_recv().is_err(), "the next design change waits its turn");assert_eq!(h.app.session.doc.features.len(), features, "nothing applied yet");+ assert!(reply_to(&mut h, &inspect)["ok"] == true, "inspection answered too, from a copy");let r = reply_to(&mut h, &hole);assert_eq!(r["ok"], true, "{r}");let r = reply_to(&mut h, &boss);