From d895fef35407ed38a0f6d5ff32a6d38325de19f3 Mon Sep 17 00:00:00 2001 From: Mateusz Sych <151755914+SychPL@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:10:03 +0000 Subject: [PATCH] Control channel: a pushed design.changed event for clients that subscribe (#6985) (#6986) * claim: #6646 * Control channel: document.revision, a design revision and a document id (#6646) A program that follows the open design asks document.revision and exports only when the answer moves: document_id names the open design (kept through edits, saves and renames, another for each design started or opened, never shared between two tabs or two runs) and revision moves whenever the design, what is hidden or an uncaptured component position changes. It stays put on reads, selections and view changes, unlike the session's view revision. The revision is read lazily: the session remembers the design it last reported (held weakly, so Arc::make_mut can never change it in place and its address can't be reused) and takes a new number from one counter for the whole run when the design is another one. The control method answers at once, also while a slow command computes; engine.execute reaches the same command for scripts and MCP. * document.revision: hash the run's id prefix with the process's random keys A clock set before 1970 gave every run the prefix 0, so a restarted app could answer a new design with the id and revision of the old one. The docs no longer promise an answer at once: a screenshot waiting for an opened design to be meshed still holds the requests behind it. * document.revision: its label in the complete catalogs (ja, zh) * claim: #6985 * Control channel: control.subscribe and design.changed events (#6985) A connection that sends control.subscribe gets the active design's id and revision in the reply (as document.revision answers), then a {"event":"design.changed","params":{document_id, revision}} line whenever either changes, so a live link need not poll. The window publishes the design at the end of each frame's logic and drawing while a connection is subscribed (one atomic load otherwise). Each subscribed connection waits on that from a thread of its own and writes the latest after a 100 ms gap, so a burst of changes is one line. Replies and events share one lock per connection, each written whole (#6390). * control.subscribe: the reply before any event, a second one refused The events thread started before the subscribe reply was written, so a change right after the window's answer could reach the client before the reply that named the older revision. The subscription now starts holding the connection's line lock and writes the reply under it. A second control.subscribe on a subscribed connection is refused on the connection itself: its answer could arrive behind a newer event. When no thread or socket is left for the events, the reply says it did not subscribe instead of ok. * control.subscribe: a second one does not lose a finished late reply The already-subscribed answer came before the busy check, so a request that timed out and had finished since lost its reply: control.pending then said the app ended it without one. It now comes after the busy check and drops a finished late reply as every other request does. * control_server: declare the subscribe guard at the top of the loop Clear of the lines #6643 changes (its token check moves to where the declaration was). * control_server: the subscription's items beside serve Away from the lines next to send, where #6643 adds token_of. * control test: New on a blank design reuses its tab, so redo the box first --------- Co-authored-by: MateuszSychXpl <151755914+MateuszSychXpl@users.noreply.github.com> --- apps/solidcraft/src/control_server.rs | 214 +++++++++++++++++- assets/locales/pending/document-revision.json | 17 ++ crates/engine/src/cmd/inspect.rs | 63 ++++++ crates/engine/src/cmd/mod.rs | 2 +- crates/engine/src/control_pending.rs | 3 + crates/engine/src/lib.rs | 9 + crates/ui-egui/src/control.rs | 181 +++++++++++++++ crates/ui-egui/src/lib.rs | 2 + docs/control-protocol.md | 60 ++++- docs/mcp.md | 5 + 10 files changed, 548 insertions(+), 8 deletions(-) create mode 100644 assets/locales/pending/document-revision.json diff --git a/apps/solidcraft/src/control_server.rs b/apps/solidcraft/src/control_server.rs index d66178578..f5185b356 100644 --- a/apps/solidcraft/src/control_server.rs +++ b/apps/solidcraft/src/control_server.rs @@ -13,11 +13,15 @@ use solidcraft_engine::MAX_LINE; use solidcraft_engine::control_auth; use solidcraft_engine::control_pending; use solidcraft_ui_egui::ControlRequest; +use solidcraft_ui_egui::control::{DESIGN_WATCH, DesignWatch, Subscriber}; /// Connections served at once, so a flood must not be able to spawn threads without end. const MAX_CONNECTIONS: usize = 16; /// Lines that are not JSON before the connection is closed, so garbage cannot loop forever. const MAX_BAD_LINES: usize = 8; +/// How long a subscribed connection waits after a `design.changed` line before the next: what +/// changes meanwhile (a parameter dragged) goes out as one line, the latest (#6985). +const EVENT_GAP: Duration = Duration::from_millis(100); static OPEN: AtomicUsize = AtomicUsize::new(0); /// The token files this launch wrote (its control port, the agent chat's endpoint), removed @@ -365,10 +369,91 @@ fn busy_message(p: &Pending, method: &str) -> String { ) } -fn serve(stream: TcpStream, token: &str, tx: Sender, ctx: egui::Context, patient: bool) { - serve_with(stream, token, tx, ctx, patient, WAITS, &RUNNING); +/// A subscribed connection's socket, for its replies and its events: each line is written whole +/// and alone, so an event never lands inside a reply (#6985). +struct Lines { + socket: TcpStream, + turn: Mutex<()>, } +impl Lines { + fn send(&self, line: &Value) -> std::io::Result<()> { + let _turn = self.turn.lock().unwrap_or_else(PoisonError::into_inner); + send(&mut &self.socket, line) + } +} + +/// A connection's `control.subscribe` (#6985): its `design.changed` lines, sent from a thread of +/// their own until the connection ends. +struct Subscription { + lines: Arc, + stop: Arc, + _counted: Subscriber, +} + +impl Subscription { + /// Write `reply`, the window's answer to `control.subscribe` naming the design `seen`, on + /// `out`, then send `design`'s changes after it: the reply goes out before any event. `None`, + /// with nothing written, when no thread or socket was left for the events. + fn start( + design: &'static DesignWatch, + counted: Subscriber, + out: &TcpStream, + seen: (String, u64), + reply: &Value, + ) -> Option<(Self, std::io::Result<()>)> { + let lines = Arc::new(Lines { socket: out.try_clone().ok()?, turn: Mutex::new(()) }); + let stop = Arc::new(AtomicBool::new(false)); + let first = lines.turn.lock().unwrap_or_else(PoisonError::into_inner); + let (l, s) = (lines.clone(), stop.clone()); + std::thread::Builder::new().stack_size(64 * 1024).spawn(move || send_events(design, &l, &s, seen)).ok()?; + let sent = send(&mut &lines.socket, reply); + drop(first); + Some((Subscription { lines, stop, _counted: counted }, sent)) + } +} + +/// The design a `control.subscribe` reply names. +fn design_of(reply: &Value) -> Option<(String, u64)> { + let result = reply.get("result")?; + Some((result.get("document_id")?.as_str()?.to_string(), result.get("revision")?.as_u64()?)) +} + +impl Drop for Subscription { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + // The socket closes now, not when the thread next looks; a line blocked on a client that + // stopped reading ends too. + let _ = self.lines.socket.shutdown(std::net::Shutdown::Both); + } +} + +/// The `design.changed` lines of a subscribed connection, each time the design differs from the +/// last one it was told of (`seen`), until `stop`. +fn send_events(design: &DesignWatch, lines: &Lines, stop: &AtomicBool, mut seen: (String, u64)) { + while !stop.load(Ordering::Relaxed) { + let Some(now) = design.wait(&seen, stop, Duration::from_secs(1)).filter(|now| *now != seen) else { continue }; + if lines.send(&json!({"event": "design.changed", "params": {"document_id": now.0, "revision": now.1}})).is_err() { + break; + } + seen = now; + std::thread::sleep(EVENT_GAP); + } +} + +/// Write `reply` on the connection: through its subscription once it has one. +fn answer(out: &mut TcpStream, events: Option<&Subscription>, reply: &Value) -> std::io::Result<()> { + match events { + Some(e) => e.lines.send(reply), + None => send(out, reply), + } +} + +fn serve(stream: TcpStream, token: &str, tx: Sender, ctx: egui::Context, patient: bool) { + serve_with(stream, token, tx, ctx, patient, WAITS, &RUNNING, &DESIGN_WATCH); +} + +#[allow(clippy::too_many_arguments)] fn serve_with( stream: TcpStream, token: &str, @@ -377,6 +462,7 @@ fn serve_with( patient: bool, waits: Waits, running: &'static Running, + design: &'static DesignWatch, ) { let connection = running.connections.fetch_add(1, Ordering::Relaxed) + 1; let Ok(read) = stream.try_clone() else { return }; @@ -385,12 +471,15 @@ fn serve_with( let mut bad = 0usize; let mut authenticated = false; let mut pending: Option = None; + let mut events: Option = None; loop { + // A first `control.subscribe` on its way to the window (#6985). + let mut joining = None; let line = match read_line(&mut reader, MAX_LINE) { Ok(Some(l)) => String::from_utf8_lossy(&l).into_owned(), Ok(None) => break, Err(e) => { - let _ = send(&mut out, &json!({"ok": false, "error": e.to_string()})); + let _ = answer(&mut out, events.as_ref(), &json!({"ok": false, "error": e.to_string()})); break; } }; @@ -434,6 +523,14 @@ fn serve_with( } else if let Some(p) = pending.as_ref().filter(|_| late.is_none()) { // Nothing more is queued behind it, to run unseen when it ends. json!({"ok": false, "busy": true, "error": busy_message(p, &method)}) + } else if method == "control.subscribe" && events.is_some() { + if late.is_some() { + // As below: finished, and the client moved on without asking. + pending = None; + } + // Its events already say how the design moves; a second answer could only + // arrive behind a newer one. + json!({"ok": false, "error": "already subscribed: this connection is sent design.changed lines; ask document.revision for the design now"}) } else { if late.is_some() { // Finished, and the client moved on without asking: it is dropped. @@ -443,6 +540,9 @@ fn serve_with( let wait = if patient || method == "engine.batch" { waits.long } else { waits.short }; let what = control_pending::describe(&method, ¶ms); let effect = control_pending::effect(&method, ¶ms); + // Counted before the window answers, so it publishes every change from its + // answer on. + joining = (method == "control.subscribe").then(|| design.join()); let (req, rrx) = ControlRequest::new(method.clone(), params); let ticket = running.add(connection, &id, &req); if tx.send(req).is_err() { @@ -472,7 +572,20 @@ fn serve_with( json!({"ok": false, "error": format!("bad JSON: {e}")}) } }; - if send(&mut out, &reply).is_err() { + // Subscribed once the window named the design (not when it refused or timed out). + let sent = match joining.and_then(|counted| design_of(&reply).map(|seen| (counted, seen))) { + Some((counted, seen)) => match Subscription::start(design, counted, &out, seen, &reply) { + Some((subscription, sent)) => { + events = Some(subscription); + sent + } + None => { + send(&mut out, &json!({"id": reply.get("id"), "ok": false, "error": "not subscribed: no thread or socket left for the events"})) + } + }, + None => answer(&mut out, events.as_ref(), &reply), + }; + if sent.is_err() { break; } if bad >= MAX_BAD_LINES { @@ -512,7 +625,7 @@ mod tests { static RUNNING: Running = Running::new(); std::thread::spawn(move || { if let Some(stream) = listener.incoming().flatten().next() { - serve_with(stream, token, tx, egui::Context::default(), false, waits, &RUNNING); + serve_with(stream, token, tx, egui::Context::default(), false, waits, &RUNNING, &DESIGN_WATCH); } }); let s = TcpStream::connect(addr).unwrap(); @@ -578,7 +691,7 @@ mod tests { std::thread::spawn(move || { for stream in listener.incoming().flatten() { let tx = tx.clone(); - std::thread::spawn(move || serve_with(stream, token, tx, egui::Context::default(), false, waits, &RUNNING)); + std::thread::spawn(move || serve_with(stream, token, tx, egui::Context::default(), false, waits, &RUNNING, &DESIGN_WATCH)); } }); let open = || { @@ -648,6 +761,95 @@ mod tests { assert_eq!((&r["result"]["pending"], &r["result"]["done"]), (&json!(7), &json!(true)), "{r}"); } + /// #6985: a connection that sends `control.subscribe` gets the design in the reply, then a + /// `design.changed` line each time the window publishes another: never before the reply, + /// none for the same design, the latest after a burst, each line whole between its replies. + /// A second subscribe is refused without reaching the window. A connection that did not + /// subscribe gets no events, and one that closed is no longer counted. + #[test] + fn subscribed_connections_are_told_of_design_changes() { + static RUNNING: Running = Running::new(); + static WATCH: DesignWatch = DesignWatch::new(); + let token = "0123456789abcdef0123456789abcdef"; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + // The window: it answers `control.subscribe` as the app does, publishing the design first; + // then the design changes at once, before the reply may have been written. + std::thread::spawn(move || { + for req in rx { + if req.method == "control.subscribe" { + WATCH.publish("d-1", 3); + let _ = req.reply.send(json!({"ok": true, "result": {"document_id": "d-1", "revision": 3}})); + WATCH.publish("d-1", 4); + } else { + let _ = req.reply.send(json!({"ok": true, "result": req.method})); + } + } + }); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let tx = tx.clone(); + std::thread::spawn(move || serve_with(stream, token, tx, egui::Context::default(), false, WAITS, &RUNNING, &WATCH)); + } + }); + let open = || { + let s = TcpStream::connect(addr).unwrap(); + s.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + (s.try_clone().unwrap(), BufReader::new(s)) + }; + let next = |lines: &mut BufReader| -> Value { + let mut l = String::new(); + lines.read_line(&mut l).unwrap(); + serde_json::from_str(&l).unwrap() + }; + let changed = |id: &str, revision: u64| json!({"event": "design.changed", "params": {"document_id": id, "revision": revision}}); + + let (mut quiet_out, mut quiet) = open(); + writeln!(quiet_out, "{}", json!({"id": 1, "method": "ui.view", "token": token})).unwrap(); + assert_eq!(next(&mut quiet)["id"], 1); + + let (mut out, mut lines) = open(); + writeln!(out, "{}", json!({"id": 1, "method": "control.subscribe", "token": token})).unwrap(); + assert_eq!(next(&mut lines), json!({"id": 1, "ok": true, "result": {"document_id": "d-1", "revision": 3}})); + assert_eq!(next(&mut lines), changed("d-1", 4), "the change after the window's answer comes after the reply"); + assert!(WATCH.subscribed()); + // The design it was told of is no news; another revision is. + WATCH.publish("d-1", 4); + WATCH.publish("d-1", 5); + assert_eq!(next(&mut lines), changed("d-1", 5)); + // A burst ends with its latest. + for revision in 6..=10 { + WATCH.publish("d-1", revision); + } + let mut last = 5; + while last < 10 { + let e = next(&mut lines); + let revision = e["params"]["revision"].as_u64().unwrap(); + assert!(e["event"] == "design.changed" && revision > last, "{e} after {last}"); + last = revision; + } + // Another tab: another id, whatever its revision. + WATCH.publish("d-2", 2); + assert_eq!(next(&mut lines), changed("d-2", 2)); + // Subscribed already: refused here (the window would have published d-1 again). + writeln!(out, "{}", json!({"id": 2, "method": "control.subscribe"})).unwrap(); + let r = next(&mut lines); + assert!(r["id"] == 2 && r["ok"] == false && r["error"].as_str().is_some_and(|e| e.starts_with("already subscribed")), "{r}"); + // Replies still come, whole, and nothing else was sent meanwhile. + writeln!(out, "{}", json!({"id": 3, "method": "ui.view"})).unwrap(); + assert_eq!(next(&mut lines), json!({"id": 3, "ok": true, "result": "ui.view"})); + writeln!(quiet_out, "{}", json!({"id": 2, "method": "ui.view"})).unwrap(); + assert_eq!(next(&mut quiet), json!({"id": 2, "ok": true, "result": "ui.view"}), "no events without subscribing"); + // Closed, it is no longer counted. + drop((out, lines)); + let deadline = Instant::now() + Duration::from_secs(10); + while WATCH.subscribed() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + assert!(!WATCH.subscribed()); + } + /// A timed-out request that only reads is not said to "still apply", nor is one that only /// writes a file (an export, #1989); a change is, by name. #[test] diff --git a/assets/locales/pending/document-revision.json b/assets/locales/pending/document-revision.json new file mode 100644 index 000000000..2fdf50ce2 --- /dev/null +++ b/assets/locales/pending/document-revision.json @@ -0,0 +1,17 @@ +{ + "en": { + "cmd.document_revision": "Design Revision" + }, + "de": { + "cmd.document_revision": "Konstruktionsrevision" + }, + "ja": { + "cmd.document_revision": "デザイン リビジョン" + }, + "pl": { + "cmd.document_revision": "Wersja projektu" + }, + "zh": { + "cmd.document_revision": "设计版本号" + } +} diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs index 94c4e4f02..f5c0fb415 100644 --- a/crates/engine/src/cmd/inspect.rs +++ b/crates/engine/src/cmd/inspect.rs @@ -1,5 +1,10 @@ //! Inspection: measure bodies, describe the document, sketches and model topology. +use std::collections::BTreeMap; +use std::hash::{BuildHasher, RandomState}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, OnceLock, Weak}; + use serde_json::{Value, json}; use solidcraft_sketch::CurveKind; @@ -18,6 +23,11 @@ pub static COMMANDS: &[CommandSpec] = &[ .noundo() .params("bodies?: [names] (default all) → closed per body; volume_mm3, center_of_mass, density_g_cm3 and mass_g only for closed, consistently oriented bodies; area, bbox and counts for all; total.open_bodies_skipped counts bodies excluded from volume/mass totals; or items: [1-2 selections] (face/edge: type, body, point; index optional) → length/area/volume; diameter, radius, circumference or arc_length/angle_deg of circles, arcs and cylinders; slot sizes; min (distance_mm, from, to), max, center_distance (centre to centre, or from an axis) and angle"), CommandSpec::new("document.inspect", "Inspect Design", inspect).icon("inspect").noundo().params("measure?: bool (include body measurements)"), + CommandSpec::new("document.revision", "Design Revision", revision).icon("inspect").noundo().params( + "→ document_id (this open design's id: kept while it stays open, another for each design started or opened), \ + revision (moves whenever the design, what is hidden or a component's uncaptured position changes, \ + never on a selection or a view; from one counter for the whole run, so it never repeats). Read-only", + ), CommandSpec::new("sketch.inspect", "Inspect Sketch", sketch_inspect).icon("inspect").noundo().params("sketch?: id|name (default active)"), CommandSpec::new("model.edges", "List Edges", model_edges).icon("inspect").noundo().params("body: name"), CommandSpec::new("model.faces", "List Faces", model_faces).icon("inspect").noundo().params( @@ -241,6 +251,59 @@ fn sketch_inspect(s: &mut Session, p: &Value) -> Result { sketch_json(s, id).ok_or_else(|| EngineError::Other("that sketch is not evaluated (rolled back or not a sketch)".into())) } +/// Revisions of every design of this run (#6646). +static NEXT_REVISION: AtomicU64 = AtomicU64::new(1); + +/// The design as `document.revision` last saw it, which its revision names. +pub(crate) struct Followed { + /// Held weakly: a design something holds weakly is never changed in place (`Arc::make_mut` + /// moves it), and its address can't go to another design meanwhile. + doc: Weak, + visibility: crate::Visibility, + pending_moves: BTreeMap, + revision: u64, +} + +/// A new design's id: one for this run, then a number, so no two designs of one run, or of two +/// runs, have the same. +pub(crate) fn new_document_id() -> String { + static RUN: OnceLock = OnceLock::new(); + static NEXT: AtomicU64 = AtomicU64::new(1); + let run = RUN.get_or_init(|| { + let started = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); + // Hashed with this process's random keys (where the system has them), so two runs differ + // even with the clock set back. + RandomState::new().hash_one(started) + }); + format!("{run:016x}-{}", NEXT.fetch_add(1, Ordering::Relaxed)) +} + +impl Session { + /// The revision of what the design holds now (`document.revision`), a new one when it changed + /// since last asked. Changes between two asks that end where they began (an edit undone) need + /// no new one: the design is the one that revision named. + pub fn design_revision(&mut self) -> u64 { + let seen = |f: &Followed| { + std::ptr::eq(f.doc.as_ptr(), Arc::as_ptr(&self.doc)) && f.visibility == self.visibility && f.pending_moves == self.pending_moves + }; + match self.followed.as_ref().filter(|f| seen(f)) { + Some(f) => f.revision, + None => { + let revision = NEXT_REVISION.fetch_add(1, Ordering::Relaxed); + let (doc, visibility, pending_moves) = (Arc::downgrade(&self.doc), self.visibility.clone(), self.pending_moves.clone()); + self.followed = Some(Followed { doc, visibility, pending_moves, revision }); + revision + } + } + } +} + +/// `document.revision`: the design's id and [`Session::design_revision`]. +fn revision(s: &mut Session, _p: &Value) -> Result { + let revision = s.design_revision(); + Ok(json!({"document_id": s.document_id, "revision": revision})) +} + fn inspect(s: &mut Session, p: &Value) -> Result { let st = s.model.state(); let (vals, perr) = s.doc.param_values(); diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 1293c9818..8aaa9f32b 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -48,7 +48,7 @@ pub use component_link::resolve_design_links; mod config; mod file; mod frame; -mod inspect; +pub(crate) mod inspect; mod interference; pub(crate) mod joints; mod libraries; diff --git a/crates/engine/src/control_pending.rs b/crates/engine/src/control_pending.rs index 72511bd5a..86dcfa4b2 100644 --- a/crates/engine/src/control_pending.rs +++ b/crates/engine/src/control_pending.rs @@ -32,7 +32,9 @@ impl Effect { /// (`ui.screenshot` with a `path`, and `ui.render`, write a file: see [`effect`].) const READ_METHODS: &[&str] = &[ "control.pending", + "control.subscribe", "document.inspect", + "document.revision", "engine.commands", "ui.at", "ui.handles", @@ -54,6 +56,7 @@ pub fn command_reads_only(id: &str) -> bool { || id.starts_with("model.") || id.ends_with(".inspect") || id.ends_with(".list") + || id == "document.revision" || matches!(id, "document.inspect" | "engine.commands" | "render.status" | "render.backends" | "render.settings.get" | "file.slicers") } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 405e0f6dd..a65f9829d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -292,6 +292,11 @@ pub struct Session { pub log: Vec, /// Increments on every document change (views use it to refresh). pub revision: u64, + /// This open design's id for programs that follow it (`document.revision`, #6646): kept + /// while it stays open, through saves and renames; another for each design started or opened. + pub document_id: String, + /// The design as `document.revision` last saw it, and the revision it gave it. + pub(crate) followed: Option, /// Project a face's edges into a sketch created on it (the default; `sketch.auto_project`). pub auto_project: bool, /// How calls that break a command's parameter contract are treated (off by default). It @@ -482,6 +487,8 @@ impl Session { open_preview: None, log: Vec::new(), revision: 1, + document_id: cmd::inspect::new_document_id(), + followed: None, auto_project: true, param_check: schema::ParamCheck::Off, live_links: None, @@ -1141,6 +1148,8 @@ impl Session { saved: self.saved.clone(), log: Vec::new(), revision: self.revision, + document_id: self.document_id.clone(), + followed: None, auto_project: self.auto_project, param_check: self.param_check, live_links: None, diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index c84395d2e..5eca34b60 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -41,7 +41,10 @@ //! and replies once the command has run (`"animate": false` skips that one call) //! - `ui.resize {width, height}`, `app.quit` +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::Sender; +use std::sync::{Condvar, Mutex, MutexGuard, PoisonError}; +use std::time::Duration; use serde_json::{Value, json}; use solidcraft_engine::io::vfs; @@ -87,6 +90,81 @@ pub(crate) fn cancelled_chat_response() -> Value { json!({"ok": false, "error": "not run: the agent chat turn ended or its document tab was left"}) } +/// The active design's id and revision for control connections that sent `control.subscribe` +/// (#6985): the window publishes them each frame while one is subscribed, and each such +/// connection waits for them to move, then sends a `design.changed` line. +#[derive(Default)] +pub struct DesignWatch { + subscribers: AtomicUsize, + now: Mutex>, + moved: Condvar, +} + +/// The app's [`DesignWatch`]. +pub static DESIGN_WATCH: DesignWatch = DesignWatch::new(); + +impl DesignWatch { + pub const fn new() -> Self { + DesignWatch { subscribers: AtomicUsize::new(0), now: Mutex::new(None), moved: Condvar::new() } + } + + fn now(&self) -> MutexGuard<'_, Option<(String, u64)>> { + self.now.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// The design as it is now; waiters wake only when it moved. Only the latest is kept, so + /// changes made faster than a connection sends them go out as one. + pub fn publish(&self, document_id: &str, revision: u64) { + let mut now = self.now(); + if now.as_ref().is_some_and(|(id, r)| id == document_id && *r == revision) { + return; + } + *now = Some((document_id.to_string(), revision)); + self.moved.notify_all(); + } + + /// Whether a connection is subscribed: the window publishes only then. + pub fn subscribed(&self) -> bool { + self.subscribers.load(Ordering::Relaxed) > 0 + } + + /// Count a subscribed connection until the returned guard is dropped. + pub fn join(&'static self) -> Subscriber { + self.subscribers.fetch_add(1, Ordering::Relaxed); + Subscriber(self) + } + + /// Wait up to `wait` for the design to differ from `seen`, or for `stop`; the design then + /// (`None` before anything was published). + pub fn wait(&self, seen: &(String, u64), stop: &AtomicBool, wait: Duration) -> Option<(String, u64)> { + let unmoved = |now: &mut Option<(String, u64)>| now.as_ref() == Some(seen) && !stop.load(Ordering::Relaxed); + let (now, _) = self.moved.wait_timeout_while(self.now(), wait, unmoved).unwrap_or_else(PoisonError::into_inner); + now.clone() + } +} + +/// A subscribed connection, counted by its [`DesignWatch`] while this lives. +pub struct Subscriber(&'static DesignWatch); + +impl Drop for Subscriber { + fn drop(&mut self) { + self.0.subscribers.fetch_sub(1, Ordering::Relaxed); + // Under the lock, so a connection about to wait sees its `stop` set before it does. + let _now = self.0.now(); + self.0.moved.notify_all(); + } +} + +/// Publish the active design for subscribed connections ([`DesignWatch`]). Called at the end of +/// each frame's logic (which runs while the window is hidden too) and of its drawing, so a +/// change made in either goes out in that frame. +pub(crate) fn publish_design(app: &mut SolveApp, watch: &DesignWatch) { + if watch.subscribed() { + let revision = app.session.design_revision(); + watch.publish(&app.session.document_id, revision); + } +} + pub enum Outcome { Done(Value), Screenshot { path: Option }, @@ -392,6 +470,14 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> } "engine.commands" => wrap(app.session.execute("engine.commands", &json!({})).map_err(|e| e.to_string())), "document.inspect" => wrap(app.session.execute("document.inspect", p).map_err(|e| e.to_string())), + "document.revision" => wrap(app.session.execute("document.revision", p).map_err(|e| e.to_string())), + // The connection already counts as subscribed (`DesignWatch::join`), and its events start + // from this answer: published first, so no event repeats it and none older follows. + "control.subscribe" => { + let revision = app.session.design_revision(); + DESIGN_WATCH.publish(&app.session.document_id, revision); + ok(json!({"document_id": app.session.document_id, "revision": revision})) + } "ui.messages" => ok(crate::messages::control(app, p)), "ui.inspect" => ok(json!({ "render": crate::render_workspace::inspect_state(app), @@ -1159,6 +1245,101 @@ mod tests { assert!(app.synthetic.is_empty()); } + /// #6646: `document.revision` names the active design and what it holds. The revision moves on + /// an edit, a parameter, a hide, an undo and a redo, never on a read or a selection, and never + /// comes back; the id stays through edits and is another for another tab of the same name. + #[test] + fn document_revision_follows_the_design_and_tells_tabs_apart() { + fn now(h: &mut crate::scenario::Harness) -> (String, u64) { + let r = h.call("document.revision", json!({})); + assert_eq!(r["ok"], true, "{r}"); + (r["result"]["document_id"].as_str().unwrap_or_default().to_string(), r["result"]["revision"].as_u64().unwrap_or_default()) + } + fn run(h: &mut crate::scenario::Harness, command: &str, params: Value) { + let r = h.call("engine.execute", json!({"command": command, "params": params})); + assert_eq!(r["ok"], true, "{command}: {r}"); + } + let mut h = crate::scenario::Harness::new(); + let (id, mut last) = now(&mut h); + assert!(!id.is_empty() && last > 0, "{id} {last}"); + // Reads and a selection leave it as it is (the view's own revision moves on a selection). + let view = h.app.session.revision; + h.call("document.inspect", json!({})); + h.call("ui.inspect", json!({})); + run(&mut h, "select.clear", json!({})); + assert!(h.app.session.revision > view); + assert_eq!(now(&mut h), (id.clone(), last)); + for (command, params) in [ + ("solid.box", json!({"length": 10, "width": 10, "height": 10})), + ("parameters.add", json!({"name": "w", "expression": "12 mm"})), + ("browser.visibility", json!({"folder": "bodies", "visible": false})), + ("edit.undo", json!({})), + ("edit.redo", json!({})), + ] { + run(&mut h, command, params); + let (same, revision) = now(&mut h); + assert_eq!(same, id, "{command} keeps the id"); + assert!(revision > last, "{command}: {revision} after {last}"); + assert_eq!(now(&mut h).1, revision, "asking again after {command}"); + last = revision; + } + // Another tab with the same name is another design; back on the first, its revision is + // the one it had. + h.call("ui.documents", json!({"action": "new"})); + let tabs = h.call("ui.documents", json!({}))["result"]["documents"].clone(); + assert_eq!(tabs[0]["name"], tabs[1]["name"], "{tabs}"); + let (other, other_revision) = now(&mut h); + assert_ne!(other, id); + assert!(other_revision > last, "{other_revision} after {last}"); + h.call("ui.documents", json!({"action": "switch", "index": 0})); + assert_eq!(now(&mut h), (id.clone(), last)); + // A design started in its place is another one too, and its revision is new. + run(&mut h, "file.new", json!({})); + let (fresh, revision) = now(&mut h); + assert!(fresh != id && fresh != other, "{fresh}"); + assert!(revision > other_revision, "{revision} after {other_revision}"); + } + + /// #6985: while a connection is subscribed, a frame publishes the active design as + /// `document.revision` names it: the same after a selection, a new revision after an edit, + /// another id on another tab; nothing while none is. `control.subscribe` answers what + /// `document.revision` does, and a connection that waited through several changes is told + /// only of the latest. + #[test] + fn subscribed_frames_publish_the_design() { + static WATCH: DesignWatch = DesignWatch::new(); + let now = || WATCH.now().clone(); + let mut h = crate::scenario::Harness::new(); + publish_design(&mut h.app, &WATCH); + assert_eq!(now(), None, "nobody subscribed"); + let counted = WATCH.join(); + let subscribed = h.call("control.subscribe", json!({})); + assert_eq!(subscribed["result"], h.call("document.revision", json!({}))["result"], "{subscribed}"); + publish_design(&mut h.app, &WATCH); + let (id, first) = now().unwrap(); + assert_eq!(json!({"document_id": id, "revision": first}), subscribed["result"]); + h.call("engine.execute", json!({"command": "select.clear", "params": {}})); + publish_design(&mut h.app, &WATCH); + assert_eq!(now(), Some((id.clone(), first)), "a selection is no change"); + h.call("engine.execute", json!({"command": "solid.box", "params": {"length": 10, "width": 10, "height": 10}})); + publish_design(&mut h.app, &WATCH); + let (same, second) = now().unwrap(); + assert!(same == id && second > first, "{same} {second} after {first}"); + h.call("engine.execute", json!({"command": "edit.undo", "params": {}})); + publish_design(&mut h.app, &WATCH); + let third = now().unwrap().1; + assert!(third > second, "{third} after {second}"); + let stop = AtomicBool::new(false); + assert_eq!(WATCH.wait(&(id.clone(), first), &stop, Duration::ZERO), Some((id.clone(), third))); + // New on a blank design reuses its tab: the box comes back first. + h.call("engine.execute", json!({"command": "edit.redo", "params": {}})); + h.call("ui.documents", json!({"action": "new"})); + publish_design(&mut h.app, &WATCH); + assert!(now().is_some_and(|(other, _)| other != id), "{:?}", now()); + drop(counted); + assert!(!WATCH.subscribed()); + } + fn render(app: &mut SolveApp, path: &std::path::Path) -> Vec { let (req, _rx) = ControlRequest::new("ui.render", json!({"path": path.to_string_lossy(), "width": 200, "height": 140})); match handle(app, &crate::fonts::test_context(), &req) { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 64f31a8bb..daa233a31 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1806,6 +1806,7 @@ impl SolveApp { } } } + control::publish_design(self, &control::DESIGN_WATCH); } /// Inject synthetic events (one pointer event per frame). @@ -1888,6 +1889,7 @@ impl SolveApp { if self.file_picker_busy() { ui.ctx().request_repaint_after(std::time::Duration::from_millis(50)); } + control::publish_design(self, &control::DESIGN_WATCH); self.frame_ms = now_ms() - t0; frame_watch::end(self); } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 1c18a4d3d..ef103931e 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -28,7 +28,9 @@ the one found; use `--connect` for another. Requests are one line `{"id": …, "method": "…", "params": {…}}`; replies are described below. Each request is one line `{"id": …, "method": "…", "params": {…}}`; each reply is one line `{"id": …, "ok": true, "result": …}` or `{"id": …, "ok": false, "error": "…"}`. Requests are handled on the UI thread between frames; pointer and keyboard input is injected as real egui -events, one pointer event per frame. +events, one pointer event per frame. A connection that sent `control.subscribe` is also sent +event lines `{"event": "…", "params": {…}}`, which have no `id` +([Following the design](#following-the-design)). ### Token @@ -134,10 +136,66 @@ MCP server sends its folders this way on every request ([mcp.md](mcp.md)). Witho | `engine.script` | `commands`: `[{command, params}, …]` | results, stops at the first error | | `engine.batch` | `commands`: `[{command, params}, …]` (at most 10 000), `rollback?`: bool (default true), `timings?`, `profile?`, `coalesce_parameters?`: bool (default false) | `{completed, results, undone}`, plus `failed: {index, command, error}` when a step fails, and with `timings` `timings: [{index, command, ms}]` (the failing step included) and `total_ms`; `profile` adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`. Runs the steps in one request, so within one frame, each as `engine.execute` runs it. The first failure stops the batch, and with `rollback` the design goes back to how it was before it (`undone`: the steps taken back, `rolled_back`: whether the design is back as it was, `false` only when the checkpoint could not restore it). Refused before anything runs, with an error starting `engine.batch unavailable`, while the agent cursor is shown or when a step loads a file (`doc.open`, `file.insert_step`, `file.insert_mesh`). Send such steps one by one. With `coalesce_parameters`, each run of consecutive plain parameter edits (`parameters.change` with only a name and an expression, or with `changes`) is set as one `parameters.change {changes}`, so the design rebuilds once for the run. Every step still gets its own result (with `coalesced`: the run's length), and the run is one undo step. The run skips the states between its edits: an edit that would be refused on its own, but not once the run's later edits are in, goes through. A run whose combined edit is refused (a new parameter, a bad expression) runs step by step, so the refused step is named. Answered when done, for up to 3600 s | | `engine.commands` | — | every command: id, label, tab, panel, icon, shortcut, params doc, enabled | +| `document.revision` | — | `{document_id, revision}`: the active design's id and a number that moves whenever the design changes, for programs that follow it ([Following the design](#following-the-design)) | +| `control.subscribe` | — | `{document_id, revision}`, as `document.revision`; the connection is then sent a `design.changed` line whenever they change ([Following the design](#following-the-design)) | | `document.inspect` | `measure?`: bool | parameters, timeline (errors, timings), bodies, sketches, selection (assembly joints: `engine.execute` `joint.inspect {joint?}`, which reads only: each joint's two origins with the occurrence, the snap as saved, the feature, face, edge or sketch curve its names refer to, and whether it resolves or why not; kind, offset, angle, flip, values, limits, expressions and motion links) | Commands never open dialogs when run this way. `solidcraft-cli commands` prints the same registry. +### Following the design + +A program that follows the open design (a renderer kept in step, a live link) asks +`document.revision`, which only reads and does not wait behind design changes (a slow command +computing, a file loading, the agent cursor acting one out), and exports only when the answer +changes (#6646): + +```text +{"id":1,"method":"document.revision","token":"…"} +→ {"id":1,"ok":true,"result":{"document_id":"18f3a0c2d4e5b6a7-1","revision":3}} +``` + +- `document_id` names the active design (its tab) while it stays open, through edits, saves and + renames. Two open designs have different ids even with the same name, and each design started + or opened gets a new one, also one opened or started in the same tab. Ids of one run never + match those of another. Treat it as an opaque string. +- `revision` moves whenever the design changes: an edit, a parameter, undo or redo, a design + opened or started, what is hidden or shown (saved with the design), a component moved and not + captured yet. It stays the same for reads, a selection, a camera move, a section or an analysis + view. Revisions come from one counter for the whole run, so a revision never names two + states, and it never goes back: changes undone before the next ask that end where the design + was need no new one (its revision still names that design). + +Switching tabs changes `document_id`; back on a tab its revision is the one it had, if nothing +changed it meanwhile. Compare both values, and export when either differs from the last +answer. The same answer comes from `engine.execute` `document.revision` (and so from scripts and +MCP `execute`), which waits its turn behind design changes like any command. + +A client need not ask again and again: after `control.subscribe` on its connection, the app +sends it a line whenever the active design changes (#6985): + +```text +{"id":1,"method":"control.subscribe","token":"…"} +→ {"id":1,"ok":true,"result":{"document_id":"18f3a0c2d4e5b6a7-1","revision":3}} +{"event":"design.changed","params":{"document_id":"18f3a0c2d4e5b6a7-1","revision":4}} +{"event":"design.changed","params":{"document_id":"18f3a0c2d4e5b6a7-2","revision":5}} +``` + +- The reply is what `document.revision` answers then (and, like it, does not wait behind design + changes); no event comes before it. From there on, each `design.changed` line carries what + `document.revision` would answer, sent when its `document_id` or `revision` differs from the + last one this connection was told: an edit, undo or redo, a design opened or started, a tab + switched. +- Lines are coalesced, not sent per frame: at most about ten a second, and changes made faster + (a parameter dragged) are followed by one line with the latest. Once the design stops + changing, the last line names it as it is. +- An event has `event` and `params` and no `id`; every reply still has its request's `id`. Each + event is a whole line of its own, between replies, never inside one. Ignore events you don't + know. +- Only connections that subscribed get events, until they close (or shut their sending side). A + second `control.subscribe` on a subscribed connection is refused with `already subscribed`; + ask `document.revision` for the design now. A `control.subscribe` that timed out or failed did + not subscribe the connection: send it again. + ### Slow commands and the window (#1989) With the preference **Preferences > AI > Keep the window responsive while agents run commands** diff --git a/docs/mcp.md b/docs/mcp.md index bc4d1f52c..1b2c124c2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -300,6 +300,11 @@ To change a feature after it is made, read its definition with `execute` `timeli `{"extent": {"distance": "30"}}`). The fields per feature type are listed in the book's *Solid features* chapter. +To tell whether the design changed since a call, without reading all of it again, `execute` +`document.revision` answers `{document_id, revision}`: `revision` moves only when the design +changes, and `document_id` names the open design (another one after `new_design` or `open`). +See [control-protocol.md](control-protocol.md#following-the-design). + Resources: `solidcraft://design` (inspect JSON with measurements) and `solidcraft://commands` (the catalog).