SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Agent chip: the batch step and its command, centred above the navigation bar (#5748)
SS-EN4ab6d9295291
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 1c4c2133f7..8a78e7660f 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -214,7 +214,13 @@ impl Ahead {/// [`Session::prime`], so running them for real evaluates nothing again: the shared cache/// drops results past its budget, and a large design's states are past it.pub fn evaluate(self, commands: &[(String, Value)]) -> Result<Evaluated> {- let (after, _) = self.0.preview_in_place(commands)?;+ self.evaluate_counting(commands, &std::sync::atomic::AtomicUsize::new(0))+ }++ /// [`Ahead::evaluate`], setting `step` to the number of the command running (from 1), so a+ /// front end can say how far a batch has got.+ pub fn evaluate_counting(self, commands: &[(String, Value)], step: &std::sync::atomic::AtomicUsize) -> Result<Evaluated> {+ let (after, _) = self.0.preview_in_place(commands, Some(step))?;after.world_state().warm_display();Ok(Evaluated(after.model))}@@ -1281,12 +1287,20 @@ impl Session {/// A `timeline.redefine` is shown even while the timeline is rolled back to the feature/// being edited.pub fn preview(&self, commands: &[(String, Value)]) -> Result<Preview> {- self.scratch().preview_in_place(commands).map(|(after, replies)| Preview { before: self.model.state(), after: after.model.state(), replies })+ self.scratch().preview_in_place(commands, None).map(|(after, replies)| Preview {+ before: self.model.state(),+ after: after.model.state(),+ replies,+ })}/// The same evaluated preview in occurrence coordinates, including uncaptured moves.pub fn preview_world(&self, commands: &[(String, Value)]) -> Result<Preview> {- self.scratch().preview_in_place(commands).map(|(after, replies)| Preview { before: self.world_state(), after: after.world_state(), replies })+ self.scratch().preview_in_place(commands, None).map(|(after, replies)| Preview {+ before: self.world_state(),+ after: after.world_state(),+ replies,+ })}/// World preview with each session's visibility applied, including new body placements.@@ -1297,7 +1311,7 @@ impl Session {shown.bodies.retain(|body| session.body_visible(&body.name));Arc::new(shown)};- self.scratch().preview_in_place(commands).map(|(after, replies)| Preview { before: visible(self), after: visible(&after), replies })+ self.scratch().preview_in_place(commands, None).map(|(after, replies)| Preview { before: visible(self), after: visible(&after), replies })}/// Run `commands` on a [`Session::scratch`] copy that keeps the undo and redo stacks: what@@ -1312,12 +1326,15 @@ impl Session {Ahead(copy)}- fn preview_in_place(mut self, commands: &[(String, Value)]) -> Result<(Self, Vec<Value>)> {+ fn preview_in_place(mut self, commands: &[(String, Value)], step: Option<&std::sync::atomic::AtomicUsize>) -> Result<(Self, Vec<Value>)> {if commands.is_empty() {return Err(EngineError::Other("nothing to preview".into()));}let mut replies = Vec::with_capacity(commands.len());- for (id, params) in commands {+ for (i, (id, params)) in commands.iter().enumerate() {+ if let Some(step) = step {+ step.store(i + 1, std::sync::atomic::Ordering::Relaxed);+ }let r = self.execute(id, params)?;replies.push(r.clone());if id == "timeline.redefine"diff --git a/crates/ui-egui/src/agent_cursor.rs b/crates/ui-egui/src/agent_cursor.rsindex 1012ad2c88..9236e3ada8 100644--- a/crates/ui-egui/src/agent_cursor.rs+++ b/crates/ui-egui/src/agent_cursor.rs@@ -167,8 +167,8 @@ impl AgentCursor {/// Since when the pointer has waited at its last stop for its command to compute (ms), and/// the command.- pub fn computing(&self) -> Option<(f64, &str)> {- self.job.as_ref().filter(|j| j.stops.is_empty()).and_then(|j| j.ahead.as_ref()).map(|a| (a.started, a.label.as_str()))+ pub fn computing(&self) -> Option<(f64, String)> {+ self.job.as_ref().filter(|j| j.stops.is_empty()).and_then(|j| j.ahead.as_ref()).map(|a| (a.started, a.steps.shown()))}/// Follow the pointer input an agent sends itself (`ui.move`, `ui.click`, `ui.drag`,diff --git a/crates/ui-egui/src/control_job.rs b/crates/ui-egui/src/control_job.rsindex 2e7f6de851..38d70bd185 100644--- a/crates/ui-egui/src/control_job.rs+++ b/crates/ui-egui/src/control_job.rs@@ -26,6 +26,7 @@//! `agent_off_thread`, off by default).use std::sync::Arc;+use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::mpsc::{Receiver, TryRecvError};use serde_json::{Value, json};@@ -144,6 +145,8 @@ pub struct ControlJob {pub(crate) started: f64,/// The command, as the toolbar names it.pub(crate) label: String,+ /// How far it has got (evaluated ahead).+ steps: Option<Arc<Steps>>,}impl ControlJob {@@ -178,23 +181,58 @@ fn spawn(Some(rx)}+/// How far a request evaluating ahead has got: the step running (from 1) of how many, and+/// each step's command as the toolbar names it.+pub(crate) struct Steps {+ now: AtomicUsize,+ labels: Vec<String>,+ total: usize,+}++impl Steps {+ fn new(app: &SolveApp, request: &Value, commands: &[(String, Value)]) -> Arc<Steps> {+ // A batch counts all its steps, also those after the ones computed ahead.+ let total = request.get("commands").and_then(Value::as_array).map_or(commands.len(), Vec::len).max(commands.len());+ Arc::new(Steps { now: AtomicUsize::new(0), labels: commands.iter().map(|(c, _)| label(app, c)).collect(), total })+ }++ /// What the chip says: the command running, and in a batch which step it is+ /// (`3/21 · Extrude`).+ pub(crate) fn shown(&self) -> String {+ let now = self.now.load(Ordering::Relaxed).max(1);+ let label = self.labels.get(now - 1).or(self.labels.last()).cloned().unwrap_or_default();+ if self.total > 1 { format!("{now}/{} · {label}", self.total) } else { label }+ }+}+/// Evaluate `commands` ahead on a copy of the session, on a worker (with the folder scope/// `request` names). What it computes is kept for the run here.-fn evaluate_ahead(app: &SolveApp, request: &Value, commands: Vec<(String, Value)>) -> Option<(Receiver<Option<Value>>, Arc<KeptResults>)> {+fn evaluate_ahead(+ app: &SolveApp,+ request: &Value,+ commands: Vec<(String, Value)>,+) -> Option<(Receiver<Option<Value>>, Arc<KeptResults>, Arc<Steps>)> {let scope = crate::control::request_scope(app, request).ok()?;let ahead = app.session.ahead();let kept = ahead.kept();+ let steps = Steps::new(app, request, &commands);+ let counting = steps.clone();let rx = spawn(scope, move || {- let _ = ahead.evaluate(&commands);+ let _ = ahead.evaluate_counting(&commands, &counting.now);None})?;- Some((rx, kept))+ Some((rx, kept, steps))}/// Start computing a design change ahead, for the design as it is now.-fn begin_ahead(app: &SolveApp, req: &ControlRequest, commands: Vec<(String, Value)>, tries: u8) -> Option<(Work, Receiver<Option<Value>>)> {- let (rx, kept) = evaluate_ahead(app, &req.params, commands.clone())?;- Some((Work::Ahead { commands, doc: app.session.doc.clone(), revision: app.session.revision, tries, kept }, rx))+fn begin_ahead(+ app: &SolveApp,+ req: &ControlRequest,+ commands: Vec<(String, Value)>,+ tries: u8,+) -> Option<(Work, Receiver<Option<Value>>, Arc<Steps>)> {+ let (rx, kept, steps) = evaluate_ahead(app, &req.params, commands.clone())?;+ Some((Work::Ahead { commands, doc: app.session.doc.clone(), revision: app.session.revision, tries, kept }, rx, steps))}impl SolveApp {@@ -222,6 +260,8 @@ pub struct Ahead {pub(crate) started: f64,/// The command, as the toolbar names it.pub(crate) label: String,+ /// How far it has got.+ pub(crate) steps: Arc<Steps>,}impl Ahead {@@ -235,8 +275,8 @@ impl Ahead {}let commands = ahead_commands(method, request);let label = label(app, &commands.first()?.0);- let (done, kept) = evaluate_ahead(app, request, commands)?;- Some(Ahead { done, kept, started: crate::now_ms(), label })+ let (done, kept, steps) = evaluate_ahead(app, request, commands)?;+ Some(Ahead { done, kept, started: crate::now_ms(), label, steps })}/// The evaluation is in (or its worker ended).@@ -298,8 +338,11 @@ fn within_wait(app: &SolveApp, rx: &Receiver<Option<Value>>) -> Option<Option<Vaimpl SolveApp {/// Since when an agent's design change has been computing off the window thread (ms), and/// its command.- pub fn agent_computing(&self) -> Option<(f64, &str)> {- self.control_job.as_ref().map(|j| (j.started, j.label.as_str())).or_else(|| self.agent.computing())+ pub fn agent_computing(&self) -> Option<(f64, String)> {+ self.control_job+ .as_ref()+ .map(|j| (j.started, j.steps.as_ref().map_or_else(|| j.label.clone(), |s| s.shown())))+ .or_else(|| self.agent.computing())}/// Stop waiting for the agent's design change that is computing: it is answered as stopped@@ -346,8 +389,8 @@ impl SolveApp {}let commands = ahead_commands(&req.method, &req.params);let Some(first) = commands.first().map(|(c, _)| c.clone()) else { return Some(req) };- let Some((work, rx)) = begin_ahead(self, &req, commands, 0) else { return Some(req) };- let job = ControlJob { label: label(self, &first), req, work, done: rx, started: crate::now_ms() };+ let Some((work, rx, steps)) = begin_ahead(self, &req, commands, 0) else { return Some(req) };+ let job = ControlJob { label: label(self, &first), req, work, done: rx, started: crate::now_ms(), steps: Some(steps) };if within_wait(self, &job.done).is_some() {// Computed within the wait: it runs now, as before, finding what was computed.let Work::Ahead { kept, .. } = job.work else { return Some(job.req) };@@ -371,7 +414,7 @@ impl SolveApp {})});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() };+ let job = ControlJob { label: label(self, id), req, work: Work::Answer, done: rx, started: crate::now_ms(), steps: None };match within_wait(self, &job.done) {Some(reply) => self.answered(job, reply),None => self.control_answering.push(job),@@ -442,8 +485,8 @@ impl SolveApp {}if (!same || s.revision != revision) && tries < MAX_TRIES {// A person's edit went first: computed again for the design as it is now.- if let Some((work, rx)) = begin_ahead(self, &job.req, commands, tries + 1) {- self.control_job = Some(ControlJob { work, done: rx, ..job });+ if let Some((work, rx, steps)) = begin_ahead(self, &job.req, commands, tries + 1) {+ self.control_job = Some(ControlJob { work, done: rx, steps: Some(steps), ..job });return;}}diff --git a/crates/ui-egui/src/history_off_thread_tests.rs b/crates/ui-egui/src/history_off_thread_tests.rsindex 30d2ae041e..534dbd8928 100644--- a/crates/ui-egui/src/history_off_thread_tests.rs+++ b/crates/ui-egui/src/history_off_thread_tests.rs@@ -252,6 +252,34 @@ fn second_hole() -> serde_json::Value {json!({"command": "solid.cylinder", "params": {"base": [50, 10, -1], "axis": [0, 0, 1], "radius": 3, "height": 20, "operation": "cut"}})}+/// While an agent's batch computes, the chip says which step it is on, of how many, and that+/// step's command (`2/3 · Cylinder`); a single command shows just its name.+#[test]+fn a_computing_batch_says_its_step() {+ let (mut h, tx) = agent_harness();+ let hole = |x: f64| json!({"command": "solid.cylinder", "params": {"base": [x, 10, -1], "axis": [0, 0, 1], "radius": 3, "height": 20, "operation": "cut"}});+ let batch = ask(&tx, "engine.batch", json!({"commands": [hole(50.0), hole(30.0), hole(70.0)]}));+ h.frames(1);+ let (_, label) = h.app.agent_computing().expect("the batch computes");+ let (step, command) = label.split_once(" · ").expect(&label);+ assert!(["1/3", "2/3", "3/3"].contains(&step), "{label}");+ assert!(!command.is_empty() && !command.contains('.'), "the toolbar's name, not the id: {label}");+ // Centred on the navigation bar and above it, clear of the window's own toasts.+ let chip = crate::scenario::rect_of("agent:chip").expect("the chip is drawn");+ let nav = h.app.viewport.layout.as_ref().expect("laid out").navigation;+ assert!((chip.center().x - nav.center().x).abs() < 1.0 && chip.bottom() < nav.top(), "{chip:?} not centred above {nav:?}");+ for toast in ["toast", "toast:computing"].into_iter().filter_map(crate::scenario::rect_of) {+ assert!(!chip.intersects(toast), "{chip:?} over {toast:?}");+ }+ assert_eq!(reply_to(&mut h, &batch)["ok"], true);+ let single = ask(&tx, "engine.execute", second_hole());+ h.frames(1);+ if let Some((_, label)) = h.app.agent_computing() {+ assert!(!label.contains('/'), "{label}");+ }+ assert_eq!(reply_to(&mut h, &single)["ok"], true);+}+/// #1989: an agent's design change computes off the window thread. The window keeps answering/// (`ui.*`, inspection) while it computes and shows which command it is; the agent's next/// design change waits its turn; each lands as its own undo step with its usual reply.diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rsindex f2505a3655..7f4ef46347 100644--- a/crates/ui-egui/src/viewport.rs+++ b/crates/ui-egui/src/viewport.rs@@ -3953,8 +3953,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {crate::select_other::show(app, ui.ctx());axis_view(app, ui, rect);nav_bar(app, ui, rect);- agent_chip(app, ui, overlay_rect);- // The notices first, so the 3D mouse picture can keep clear of them.+ // The notices and the agent chip first, so the 3D mouse picture can keep clear of them.let toasts = transient_messages(app, ui, rect);if app.preferences.space_mouse_in_view&& app.space_mouse.calibrating.is_none()@@ -3963,11 +3962,8 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {use crate::prefs::SpaceMouseGhost;let calibration = app.preferences.space_mouse_calibrations.get(device);let position = app.preferences.space_mouse_ghost_position;- // The agent chip (an agent command computing off the window thread) sits at the lower left- // too: the picture stays clear of it.- let chip = app.agent_computing().map(|_| Rect::from_min_size(agent_chip_anchor(app, overlay_rect), vec2(400.0, 34.0)));let navigation = app.viewport.layout.as_ref().map(|layout| layout.navigation);- let obstacles = [navigation, chip].into_iter().flatten().chain(toasts).collect::<Vec<_>>();+ let obstacles = navigation.into_iter().chain(toasts).collect::<Vec<_>>();// The Viewport positions sit in the content area (right of the browser), Left Window in the// corner of the whole window; both stay above the floating History card, like the legend.let area = if position == SpaceMouseGhost::LeftWindow { rect } else { crate::shell::content_rect(app, rect) };@@ -4006,25 +4002,31 @@ fn paint_box_selection(painter: &egui::Painter, bx: BoxSel, sketch: bool) {}}-/// Where the agent chip's top left is: above the History bar, and above the computing notice when-/// that is up too.-fn agent_chip_anchor(app: &SolveApp, rect: Rect) -> Pos2 {- let above = if app.computing_since().is_some() { 106.0 } else { 76.0 };- pos2(rect.left() + 12.0, rect.bottom() - above)-}-/// An agent's command computing off the window thread (#1989): which one, in the agent cursor's-/// colour, and a button that stops waiting for it.-fn agent_chip(app: &mut SolveApp, ui: &egui::Ui, rect: Rect) {+/// colour, and a button that stops waiting for it. Centred on the navigation bar, just above it,+/// and moved up past anything it would cover (`taken`: the toasts and other controls).+fn agent_chip(app: &mut SolveApp, ui: &egui::Ui, view: Rect, taken: &[Rect]) -> Option<Rect> {let t = Tokens::get();let painter = ui.painter().clone();- if let Some((since, label)) = app.agent_computing().map(|(since, label)| (since, label.to_string())) {+ if let Some((since, label)) = app.agent_computing() {let seconds = ((crate::now_ms() - since) / 1000.0).floor().max(0.0);let computing = crate::i18n::format("dialog.computing", &[("seconds", &format!("{seconds:.0}"))]);- let pos = agent_chip_anchor(app, rect);let galley = painter.layout_no_wrap(format!("{label} · {computing}"), FontId::proportional(t.font_label), t.text);let stop = painter.layout_no_wrap(crate::i18n::tr("ui.agent_chat_stop").to_string(), FontId::proportional(t.font_label), t.text);- let r = Rect::from_min_size(pos, vec2(galley.size().x + stop.size().x + 54.0, galley.size().y.max(stop.size().y) + 8.0));+ let size = vec2(galley.size().x + stop.size().x + 54.0, galley.size().y.max(stop.size().y) + 8.0);+ let nav = app.viewport.layout.as_ref().map(|l| l.navigation).filter(|n| n.is_positive() && n.is_finite());+ let (x, bottom) = nav.map_or((view.center().x, view.bottom() - t.space_8), |n| (n.center().x, n.top() - t.space_8));+ let x = x.clamp(view.left() + size.x * 0.5, (view.right() - size.x * 0.5).max(view.left() + size.x * 0.5));+ let mut r = Rect::from_min_size(pos2(x - size.x * 0.5, bottom - size.y), size);+ // Each step clears one rectangle, so this ends after at most `taken.len()` moves.+ for _ in 0..=taken.len() {+ match taken.iter().filter(|o| o.expand(t.space_4).intersects(r)).map(|o| o.top()).reduce(f32::min) {+ Some(top) => r = r.translate(vec2(0.0, top - t.space_8 - r.bottom())),+ None => break,+ }+ }+ let pos = r.min;+ crate::scenario::publish_rect("agent:chip", r);painter.rect_filled(r, t.radius_sm, t.overlay);painter.rect_stroke(r, t.radius_sm, Stroke::new(1.0, crate::icons::pointer::agent()), egui::StrokeKind::Inside);egui::Spinner::new()@@ -4041,7 +4043,9 @@ fn agent_chip(app: &mut SolveApp, ui: &egui::Ui, rect: Rect) {app.stop_agent_command();}ui.ctx().request_repaint_after(std::time::Duration::from_millis(100));+ return Some(r);}+ None}/// How long a status message stays in the view (milliseconds).@@ -4052,7 +4056,11 @@ const STATUS_TOAST_MS: f64 = 6000.0;fn transient_messages(app: &mut SolveApp, ui: &egui::Ui, viewport: Rect) -> Vec<Rect> {// Nothing to show or time: an idle window skips the layout. The offer is checked too, as its clock// runs from the frames `due` sees.- if app.status.is_none() && app.computing_since().is_none() && crate::space_mouse_offer::offerable(app).is_none() {+ if app.status.is_none()+ && app.computing_since().is_none()+ && app.agent_computing().is_none()+ && crate::space_mouse_offer::offerable(app).is_none()+ {return Vec::new();}let t = Tokens::get();@@ -4061,13 +4069,15 @@ fn transient_messages(app: &mut SolveApp, ui: &egui::Ui, viewport: Rect) -> Vec<if let Some(layout) = &app.viewport.layout {obstacles.extend([layout.navigation, layout.axis_view]);}- let mut free = crate::viewport_layout::free_rect(crate::shell::content_rect(app, viewport), &obstacles).shrink(t.space_8);+ let view = crate::shell::content_rect(app, viewport);+ let mut free = crate::viewport_layout::free_rect(view, &obstacles).shrink(t.space_8);// The 3D mouse calibration offer: text and actions from its module, drawn by the shared toast.if let Some(offer) = crate::space_mouse_offer::due(app, ui.ctx()) {let labels: Vec<String> = offer.actions.iter().map(|action| crate::i18n::tr(action.label()).to_string()).collect();let labels: Vec<(&str, ToastKind)> = labels.iter().map(String::as_str).zip(offer.actions.iter().map(|action| action.kind())).collect();if let Some((r, clicked)) = paint_toast_with(ui, free, crate::i18n::tr("ui.3d_mouse_offer").to_string(), ToastLead::Dot(false), &labels) {crate::scenario::publish_rect("toast:space_mouse_offer", r);+ obstacles.push(r);free.max.y = r.top() - t.space_8;shown.push(r);crate::space_mouse_offer::keep(app, ui.ctx(), r);@@ -4081,6 +4091,7 @@ fn transient_messages(app: &mut SolveApp, ui: &egui::Ui, viewport: Rect) -> Vec<let shown_ms = crate::now_ms() - at;if shown_ms < STATUS_TOAST_MS {if let Some(r) = paint_toast(ui, free, msg, error, false) {+ obstacles.push(r);crate::scenario::publish_rect("toast", r);free.max.y = r.top() - t.space_8;shown.push(r);@@ -4108,6 +4119,7 @@ fn transient_messages(app: &mut SolveApp, ui: &egui::Ui, viewport: Rect) -> Vec<let seconds = ((crate::now_ms() - since) / 1000.0).floor().max(0.0);let text = crate::i18n::format("dialog.computing", &[("seconds", &format!("{seconds:.0}"))]);if let Some(r) = paint_toast(ui, free, text, false, true) {+ obstacles.push(r);crate::scenario::publish_rect("toast:computing", r);if app.status.is_none() {crate::scenario::publish_rect("toast", r);@@ -4116,6 +4128,10 @@ fn transient_messages(app: &mut SolveApp, ui: &egui::Ui, viewport: Rect) -> Vec<}ui.ctx().request_repaint_after(std::time::Duration::from_millis(100));}+ // The navigation bar is the chip's anchor, so it doesn't count as something to move past.+ let nav = app.viewport.layout.as_ref().map(|l| l.navigation);+ obstacles.retain(|o| Some(*o) != nav);+ shown.extend(agent_chip(app, ui, view, &obstacles));shown}