diff --git a/docs/automation/guides/plugin-panels.md b/docs/automation/guides/plugin-panels.md new file mode 100644 index 0000000000..933f3f8c99 --- /dev/null +++ b/docs/automation/guides/plugin-panels.md @@ -0,0 +1,155 @@ +# Plugin panel surfaces + +Plugin panels can publish three kinds of declarative SURFACE that the host renders with native widgets (api v29): a bounded declarative **scene** (vector snapshot on the canvas), a semantic **widget** tree/list (rows with lazy paging and optional BUTTON rows), and a **typed table** (scalar cells the user can edit; the plugin stays the data authority). `ocs_panels` reads them; `ocs_panel_action` acts on them exactly like the user's gesture. Both ride the same facade as every other intent tool: pass `ocs_session_id` when several sessions are open. + +## Discover what is published + +Without arguments you get one bounded line per surface — owner and per-tier revision plus counts, never content: + +``` +ocs_panels → {"ok":true,"panels":[ + {"panel_id":"acme:tree","owner":"acme.widgetpack", + "tiers":{"widgets":{"revision":3,"rows":1042}}}, + {"panel_id":"acme:plot","owner":"acme.plotsmith", + "tiers":{"scene":{"revision":7,"elements":214}}} +]} +``` + +## Read one surface, page by page + +Pass `panel_id` for detail. The scene tier answers with COUNTS only (the plugin owns the geometry; use `ocs_render`/`ocs_capture` for pixels): + +``` +ocs_panels {"panel_id":"acme:plot"} → + {"tier":"scene","revision":7,"elements":214, + "by_type":{"group":4,"rect":120,"path":80,"text":10}} +``` + +Widget and table rows come back as keyed pages: at most `rows` entries (default 50, cap 200), starting strictly after the `after` cursor, with `next.after` set when more remain. Walk the cursor until `next` is null — every row appears exactly once, in a stable order: + +``` +ocs_panels {"panel_id":"acme:tree","tier":"widgets","rows":200} +ocs_panels {"panel_id":"acme:tree","tier":"widgets","rows":200,"after":1042} +``` + +Widget rows read `{"id","label","children","action"}`; `children` is `leaf`, `unloaded` (ask the plugin by activating the row — see below), or a list of child ids; `action` is set on BUTTON rows. Table pages list `columns` first and rows in the surface's own order with typed cells (`"text"`, `1.5`, `true`). + +## Act: activate an element + +`ocs_panel_action` is the semantic click. On a widget row it is exactly the event the user pressing the row (button or tree node) produces: + +``` +ocs_panel_action {"panel_id":"acme:tree","element":1042} + → {"ok":true,"panel_id":"acme:tree","element":1042, + "kind":"node_activated","sequence":17, + "delivery":"best_effort_owner_targeted"} +``` + +On a scene element pass `"kind":"element_clicked"`. `kind` defaults by tier (widget rows activate as nodes, scene elements click). The element must exist in that surface — a typo refuses and burns no sequence number. + +## What the plugin sees (and what you should expect) + +The activation is delivered to the OWNING plugin only, as the same `PanelSurfaceEvent` a GUI gesture produces, with the surface's monotonic `sequence` as its explicit identity: two identical-looking activations are DISTINCT events. Delivery is best-effort — a dead owner's event drops silently, and a plugin that wants to know about lazy children answers an `Unloaded` expansion by pushing its own page. The plugin stays the data authority: after any action, re-read the surface (the revision advances when the plugin publishes anew) instead of assuming a result. None of this touches records, geometry, or undo. + +--- + +## For plugin authors: constructing the surfaces + +Everything below is the plugin side of the same v29 story — the plugin declares data, the host renders it with native widgets, and the plugin is notified when the user acts. All three tiers can coexist on one panel (independent revision spaces). + +### A widget tree/list with a BUTTON row + +```rust +use ocs_plugin_api::scene::StableId; +use ocs_plugin_api::widget::{WidgetChildren, WidgetRevision, WidgetRow, WidgetSurface}; + +let mut surface = WidgetSurface::new(WidgetRevision(1)); + +// A leaf row that ACTS as a button (buttons are leaf-only by validation). +surface.rows.insert(StableId(1), WidgetRow { + label: "Recalculate".into(), + children: WidgetChildren::Leaf, + action: Some("recalc".into()), // arrives back as NodeActivated +}); +// A node with children the host will page in ONLY when expanded. +surface.rows.insert(StableId(2), WidgetRow { + label: "Layers".into(), + children: WidgetChildren::Unloaded, + action: None, +}); +surface.roots = vec![StableId(1), StableId(2)]; +host.panel_widget_publish("acme:tree", surface)?; +``` + +When the user expands the `Unloaded` row the plugin receives `SurfaceEvent::NodeExpanded` and answers with a keyed page — installing a page NEVER replaces the surface: + +```rust +let page = WidgetPage { + base_revision: WidgetRevision(2), // must match the stored head + parent: Some(StableId(2)), // children of "Layers" + after: None, // insert at the front; position with `after` + rows: (0..50).map(|i| (StableId(100 + i), WidgetRow { + label: format!("Layer {i}"), + children: WidgetChildren::Leaf, + action: None, + })).collect(), + next: Some(StableId(150)), // cursor for the NEXT page (or None) +}; +host.panel_surface_page("acme:tree", page)?; +``` + +### A typed, editable table + +```rust +use ocs_plugin_api::tables::{CellValue, TableColumn, TableRevision, TableSurface}; +use ocs_plugin_api::scene::StableId; + +let columns = vec![ + TableColumn { id: StableId(10), label: "Name".into(), .. }, + TableColumn { id: StableId(11), label: "Length".into(), .. }, +]; +let mut table = TableSurface::new(TableRevision(1), columns); +table.order = vec![StableId(100)]; +table.rows.insert(StableId(100), vec![ + CellValue::Text("Wall A".into()), + CellValue::Number(4.25), +]); +host.panel_table_publish("acme:schedule", table)?; +``` + +The user edits cells in the host's native grid (host-local drafts until a typed commit). Each commit arrives as `SurfaceEvent::CellEdited { row, column, value }`; the plugin canonicalizes by pushing its own atomic patch (all-or-nothing, revision-checked — `SetCell` touches exactly one cell): + +```rust +let patch = TablePatch { + base_revision: TableRevision(2), + ops: vec![TableOp::SetCell { + row: StableId(100), column: StableId(11), value: CellValue::Number(4.5), + }], +}; +host.panel_surface_table_patch("acme:schedule", patch)?; +``` + +### A scene surface + +```rust +let scene = PanelScene { revision: SceneRevision(1), elements: vec![ /* Rect/Path/Text/Group */ ] }; +host.panel_surface_publish("acme:plot", PanelSurface::Scene(scene))?; +``` + +### Menus: reuse the v15 quad panels — no new path + +Plugin menus are the EXISTING v15 declarative quad panels (`QuadPanelDef`, registered once per session via `register_quad_panels`); they are not part of the surface tiers and this stage adds no second menu vocabulary: + +```rust +let menu = QuadPanelDef::new("align_tools", "Align") + .with_applies_to(vec!["LWPOLYLINE".into()]); +// items: QuadItemDef { control_id, label, icon: OwnedIconKind::Svg(..), +// action: QuadActionDef::Command("ALIGN".into()) } +host.register_quad_panels(plugin_id, &[menu])?; +// A pick arrives as HostNotification::QuadAction (or runs the command). +``` + +### The contract in one line + +Publish data at a revision; the host renders and owns the interaction; you receive only the semantic events that need your authority (activation, expansion of `Unloaded` rows, committed cell edits) — owner-targeted, sequence-identified, best-effort. A working example plugin lives in the train repository's `example_plugin_panel/`. + diff --git a/src/app/automation.rs b/src/app/automation.rs index 93a965d16d..f346f545d4 100644 --- a/src/app/automation.rs +++ b/src/app/automation.rs @@ -20,18 +20,18 @@ //! bounds and counts (read) #[cfg(not(target_arch = "wasm32"))] -use crate::io::line_read::{lines_capped, MAX_LINE_BYTES}; +use crate::io::line_read::{MAX_LINE_BYTES, lines_capped}; use std::collections::{BTreeMap, HashSet}; #[cfg(not(target_arch = "wasm32"))] use std::io::Write; use std::path::PathBuf; -use serde_json::{json, Value}; +use serde_json::{Value, json}; #[cfg(not(target_arch = "wasm32"))] use sha2::{Digest, Sha256}; -use super::control::{layout_listing, page_setup_read}; use super::OpenCADStudio; +use super::control::{layout_listing, page_setup_read}; /// Run the headless JSON server. Default transport is stdin/stdout; with /// `--port ` it instead listens on `127.0.0.1:` and serves one client at @@ -281,6 +281,16 @@ fn err(msg: impl std::fmt::Display) -> Value { json!({ "ok": false, "error": msg.to_string() }) } +/// One typed table cell, as the automation facade's `plugin_panels` read +/// exposes it (api v29, S08): the scalar itself, typed by JSON kind. +fn cell_value_json(value: &ocs_plugin_api::tables::CellValue) -> Value { + match value { + ocs_plugin_api::tables::CellValue::Text(text) => json!(text), + ocs_plugin_api::tables::CellValue::Number(number) => json!(number), + ocs_plugin_api::tables::CellValue::Bool(flag) => json!(flag), + } +} + /// The constraints that reference `entity`, as the entity read exposes them: /// the kind, every distinct participating handle, and whether the solver is /// still honouring it. Built from the live constraint sets — the structure a @@ -348,7 +358,7 @@ pub(crate) fn entity_type_matches(entity: &document::EntityType, requested: &str } } // The node library's object names ("Construction Line", "2D Solid"). - use crate::ui::node_graph::{ObjectKind, OBJECTS}; + use crate::ui::node_graph::{OBJECTS, ObjectKind}; OBJECTS.iter().any(|kind| { *kind != ObjectKind::Object && kind.name().eq_ignore_ascii_case(requested) @@ -409,19 +419,23 @@ pub(crate) fn entity_json( map.insert("knots".into(), json!(spline.knots)); map.insert( "control_points".into(), - json!(spline - .control_points - .iter() - .map(|point| v3(*point)) - .collect::>()), + json!( + spline + .control_points + .iter() + .map(|point| v3(*point)) + .collect::>() + ), ); map.insert( "fit_points".into(), - json!(spline - .fit_points - .iter() - .map(|point| v3(*point)) - .collect::>()), + json!( + spline + .fit_points + .iter() + .map(|point| v3(*point)) + .collect::>() + ), ); map.insert("weights".into(), json!(spline.weights)); } @@ -520,7 +534,9 @@ pub(crate) fn entity_json( if !text.is_empty() { map.insert( "text".into(), - json!(crate::entities::text_support::resolve_dxf_special_chars(text)), + json!(crate::entities::text_support::resolve_dxf_special_chars( + text + )), ); } } @@ -535,13 +551,13 @@ pub(crate) fn entity_json( .edges .iter() .filter_map(|edge| match edge { - document::entities::BoundaryEdge::Polyline(polyline) => { - Some(json!(polyline + document::entities::BoundaryEdge::Polyline(polyline) => Some(json!( + polyline .vertices .iter() .map(|v| [v.x, v.y]) - .collect::>())) - } + .collect::>() + )), _ => None, }) .collect(); @@ -681,7 +697,7 @@ pub(super) fn requested_save_target( Some(value) => { return Err(format!( "unsupported target format {value:?}; use dwg or dxf" - )) + )); } None => None, }; @@ -1147,18 +1163,14 @@ impl OpenCADStudio { "entities" => self.entity_summary(), "audit" => self.document_audit(&req), "query" => self.entity_query(self.active_tab, &req), - "civil_station_offset" => { - crate::app::civil_query::civil_station_offset( - &self.tabs[self.active_tab].scene.document, - &req, - ) - } - "civil_surface_stats" => { - crate::app::civil_query::civil_surface_stats( - &self.tabs[self.active_tab].scene.document, - &req, - ) - } + "civil_station_offset" => crate::app::civil_query::civil_station_offset( + &self.tabs[self.active_tab].scene.document, + &req, + ), + "civil_surface_stats" => crate::app::civil_query::civil_surface_stats( + &self.tabs[self.active_tab].scene.document, + &req, + ), "text_search" => self.automation_text_search(&req), "text_audit" => self.automation_text_audit(&req), "text_replace" => self.automation_text_replace(&req), @@ -1442,11 +1454,329 @@ impl OpenCADStudio { Err(e) => err(format!("save: {e}")), } } + "plugin_panels" => self.plugin_panels_read(&req), + "plugin_panel_action" => self.plugin_panel_action(&req), "" => err("missing \"op\""), other => err(format!("unknown op: {other}")), } } + /// Bounded reads of the plugin panel surfaces (api v29, S08): the + /// automation facade's `plugin_panels`. Without panel_id: one summary + /// line per surface (owner + per-tier revision and counts). With + /// panel_id: one tier's detail — scene counts only, widget/table rows + /// as keyed pages (`after` cursor + `next` continuation) that never + /// materialize more than the page. + pub(super) fn plugin_panels_read(&self, req: &Value) -> Value { + let Some(panel_id) = req["panel_id"].as_str() else { + let panels: Vec = self + .panel_surfaces + .surface_summaries() + .into_iter() + .map(|s| { + let mut entry = json!({ + "panel_id": s.panel_id, + "owner": s.owner, + }); + if let Some((revision, elements)) = s.scene { + entry["tiers"]["scene"] = + json!({"revision": revision, "elements": elements}); + } + if let Some((revision, rows)) = s.widgets { + entry["tiers"]["widgets"] = json!({"revision": revision, "rows": rows}); + } + if let Some((revision, rows, columns)) = s.tables { + entry["tiers"]["tables"] = + json!({"revision": revision, "rows": rows, "columns": columns}); + } + entry + }) + .collect(); + return json!({ + "ok": true, + "panels": panels, + "next": "Pass panel_id for one surface's bounded detail; plugin_panel_action activates an element.", + }); + }; + self.plugin_panels_detail(panel_id, req) + } + + /// One panel's tier detail (see `plugin_panels_read`). + fn plugin_panels_detail(&self, panel_id: &str, req: &Value) -> Value { + let tier = req["tier"].as_str().map(|tier| tier.to_ascii_lowercase()); + let tier = tier.as_deref().or({ + // Default to the panel's first published tier. + if self.panel_surfaces.scene_any_owner(panel_id).is_some() { + Some("scene") + } else if self.panel_surfaces.widget_any_owner(panel_id).is_some() { + Some("widgets") + } else if self.panel_surfaces.table_any_owner(panel_id).is_some() { + Some("tables") + } else { + None + } + }); + let Some(tier) = tier else { + return err(format!("plugin_panels: no surface for panel {panel_id}")); + }; + let rows_limit = req["rows"].as_u64().unwrap_or(50).min(200) as usize; + let after = req["after"].as_u64().map(ocs_plugin_api::scene::StableId); + match tier { + "scene" => { + let Some(scene) = self.panel_surfaces.scene_any_owner(panel_id) else { + return err(format!( + "plugin_panels: panel {panel_id} has no scene surface" + )); + }; + let mut by_type = json!({"group": 0, "rect": 0, "path": 0, "text": 0}); + fn count(element: &ocs_plugin_api::scene::SceneElement, by_type: &mut Value) { + match element { + ocs_plugin_api::scene::SceneElement::Group { children, .. } => { + by_type["group"] = json!(by_type["group"].as_u64().unwrap_or(0) + 1); + for child in children { + count(child, by_type); + } + } + ocs_plugin_api::scene::SceneElement::Rect { .. } => { + by_type["rect"] = json!(by_type["rect"].as_u64().unwrap_or(0) + 1); + } + ocs_plugin_api::scene::SceneElement::Path { .. } => { + by_type["path"] = json!(by_type["path"].as_u64().unwrap_or(0) + 1); + } + ocs_plugin_api::scene::SceneElement::Text { .. } => { + by_type["text"] = json!(by_type["text"].as_u64().unwrap_or(0) + 1); + } + } + } + for element in &scene.elements { + count(element, &mut by_type); + } + json!({ + "ok": true, + "panel_id": panel_id, + "tier": "scene", + "revision": scene.revision.0, + "elements": scene.elements.len(), + "by_type": by_type, + "note": "Scene surfaces expose counts; activate an element with plugin_panel_action.", + }) + } + "widgets" => { + let Some(surface) = self.panel_surfaces.widget_any_owner(panel_id) else { + return err(format!( + "plugin_panels: panel {panel_id} has no widget surface" + )); + }; + // Keyed page over the row map in StableId order (the same + // order the keyed page installs read back in): never more + // than the page, cursor-continuable. + let start: std::ops::Bound = match after { + Some(id) => std::ops::Bound::Excluded(id), + None => std::ops::Bound::Unbounded, + }; + let mut rows_json = Vec::with_capacity(rows_limit.min(surface.rows.len())); + let mut last: Option = None; + let mut more = false; + for (id, row) in surface.rows.range::(( + start, + std::ops::Bound::Unbounded, + )) { + if rows_json.len() >= rows_limit { + more = true; + break; + } + let children = match &row.children { + ocs_plugin_api::widget::WidgetChildren::Leaf => json!("leaf"), + ocs_plugin_api::widget::WidgetChildren::Unloaded => json!("unloaded"), + ocs_plugin_api::widget::WidgetChildren::Loaded(children) => { + json!(children.iter().map(|c| c.0).collect::>()) + } + }; + rows_json.push(json!({ + "id": id.0, + "label": row.label, + "children": children, + "action": row.action, + })); + last = Some(*id); + } + json!({ + "ok": true, + "panel_id": panel_id, + "tier": "widgets", + "revision": surface.revision.0, + "total_rows": surface.rows.len(), + "rows": rows_json, + "next": last.filter(|_| more).map(|id| json!({ + "after": id.0, + "note": "Pass as `after` with the same rows page size." + })).unwrap_or(json!(null)), + }) + } + "tables" => { + let Some(surface) = self.panel_surfaces.table_any_owner(panel_id) else { + return err(format!( + "plugin_panels: panel {panel_id} has no table surface" + )); + }; + let columns: Vec = surface + .columns + .iter() + .map(|column| json!({"id": column.id.0, "label": column.label})) + .collect(); + // Paged rows in the surface's own `order` (positioned + // semantics), cursor = the last returned row id. + let start_index = match after { + Some(id) => surface + .order + .iter() + .position(|row_id| *row_id == id) + .map_or(surface.order.len(), |index| index + 1), + None => 0, + }; + let page: Vec<&ocs_plugin_api::scene::StableId> = surface + .order + .get(start_index..) + .unwrap_or(&[]) + .iter() + .take(rows_limit) + .collect(); + let mut rows_json = Vec::with_capacity(page.len()); + for row_id in &page { + let cells = surface + .rows + .get(*row_id) + .map(|cells| cells.iter().map(cell_value_json).collect::>()) + .unwrap_or_default(); + rows_json.push(json!({"id": row_id.0, "cells": cells})); + } + let remaining = surface.order.len().saturating_sub(start_index); + let more = remaining > page.len(); + let next = page.last().filter(|_| more).map(|id| { + json!({ + "after": id.0, + "note": "Pass as `after` with the same rows page size." + }) + }); + json!({ + "ok": true, + "panel_id": panel_id, + "tier": "tables", + "revision": surface.revision.0, + "total_rows": surface.rows.len(), + "columns": columns, + "rows": rows_json, + "next": next.unwrap_or(json!(null)), + }) + } + other => err(format!( + "plugin_panels: unknown tier {other} (scene | widgets | tables)" + )), + } + } + + /// Activate one element of a plugin panel surface (api v29, S08): the + /// automation facade's `plugin_panel_action`. Routes through the SAME + /// [`PanelEventRouter`](crate::app::panel_events::PanelEventRouter) + /// constructors the GUI gestures use, then delivers owner-targeted via + /// the same `publish_surface_event_to_plugin` — so an MCP-triggered + /// activation is the GUI-triggered event, by construction (and by the + /// recorded-dispatch equivalence test). + pub(super) fn plugin_panel_action(&mut self, req: &Value) -> Value { + let Some(panel_id) = req["panel_id"].as_str() else { + return err("plugin_panel_action: missing panel_id"); + }; + let Some(raw_element) = req["element"].as_u64() else { + return err("plugin_panel_action: missing element (stable id)"); + }; + let element = ocs_plugin_api::scene::StableId(raw_element); + let Some(registered) = self.plugin_panels.get(panel_id) else { + return err(format!( + "plugin_panel_action: unknown panel {panel_id} (not registered)" + )); + }; + let Some(owner) = registered.owner_plugin_id.as_deref() else { + return err(format!( + "plugin_panel_action: panel {panel_id} has no owning plugin" + )); + }; + // The element must exist in the surface the kind addresses, so a + // typo activates nothing (and no sequence number burns). + let in_widgets = self + .panel_surfaces + .widget_any_owner(panel_id) + .is_some_and(|surface| surface.rows.contains_key(&element)); + let in_scene = self + .panel_surfaces + .scene_any_owner(panel_id) + .is_some_and(|scene| { + scene + .elements + .iter() + .any(|node| node.stable_id() == element) + }); + let requested = req["kind"].as_str().map(|kind| kind.to_ascii_lowercase()); + let requested = requested.as_deref(); + let kind = match requested { + Some("node_activated") => { + if !in_widgets { + return err(format!( + "plugin_panel_action: panel {panel_id} has no widget row {raw_element}" + )); + } + "node_activated" + } + Some("element_clicked") => { + if !in_scene { + return err(format!( + "plugin_panel_action: panel {panel_id} has no scene element {raw_element}" + )); + } + "element_clicked" + } + Some(other) => { + return err(format!( + "plugin_panel_action: unknown kind {other} (node_activated | element_clicked)" + )); + } + None => { + if in_widgets { + "node_activated" + } else if in_scene { + "element_clicked" + } else { + return err(format!( + "plugin_panel_action: panel {panel_id} has no surface element {raw_element}" + )); + } + } + }; + let routed = if kind == "node_activated" { + self.panel_event_router.on_node_activated(panel_id, element) + } else { + self.panel_event_router + .on_element_clicked(panel_id, element) + }; + let sequence = routed.sequence; + #[cfg(not(target_arch = "wasm32"))] + crate::plugin::v4_support::publish_surface_event_to_plugin( + owner, + routed.panel_id, + routed.sequence, + routed.event, + ); + #[cfg(target_arch = "wasm32")] + let _ = (owner, routed); + json!({ + "ok": true, + "panel_id": panel_id, + "element": raw_element, + "kind": kind, + "sequence": sequence, + "delivery": "best_effort_owner_targeted", + }) + } + /// Run a command line headlessly. Thin wrapper over the shared /// [`OpenCADStudio::run_one_command_line`] (see `cmd_result.rs`), which the /// GUI command line shares so both process `UCS Z 90` / `LINE 0,0 10,10` / @@ -2220,8 +2550,8 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] #[test] fn plugin_edit_publication_is_not_repeated_at_message_boundary() { - use document::entities::Point; use document::EntityType; + use document::entities::Point; let mut app = super::OpenCADStudio::new_for_test(); app.automation_op(r#"{"op":"new"}"#); @@ -2247,11 +2577,223 @@ mod tests { crate::plugin::v4_support::take_test_dispatch_log() } + // ── Plugin-panel surface facade (api v29, S08) ─────────────────────── + // + // The MCP facade must produce the SAME event the GUI gesture produces: + // both routes run through the one PanelEventRouter and the one + // owner-targeted delivery, and the recorded dispatch log proves it. + + fn register_widget_panel(app: &mut super::OpenCADStudio, panel_id: &str) { + // The reaper keeps surfaces only for VISIBLE owners; an in-process + // test sink makes "acme.widgetpack" visible without a process. + crate::plugin::grip_points::install_in_process_sink("acme.widgetpack", |_host, _event| { + ocs_plugin_api::host::CustomGripResponse::default() + }); + let panel = ocs_plugin_api::dialog::PanelDef::new(panel_id, "Tree"); + let mut state = crate::ui::window::plugin_panel::PluginPanelState::from_def(panel); + state.owner_plugin_id = Some("acme.widgetpack".into()); + app.plugin_panels.insert(panel_id.to_string(), state); + let mut surface = + ocs_plugin_api::widget::WidgetSurface::new(ocs_plugin_api::widget::WidgetRevision(1)); + surface.rows.insert( + ocs_plugin_api::scene::StableId(7), + ocs_plugin_api::widget::WidgetRow { + label: "Run".to_owned(), + children: ocs_plugin_api::widget::WidgetChildren::Leaf, + action: Some("run".to_owned()), + }, + ); + surface.roots = vec![ocs_plugin_api::scene::StableId(7)]; + app.panel_surfaces + .publish_widget("acme.widgetpack", panel_id, surface) + .expect("widget surface publishes"); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn mcp_panel_action_routes_the_same_event_as_the_gui_gesture() { + let mut app = super::OpenCADStudio::new_for_test(); + app.automation_op(r#"{"op":"new"}"#); + register_widget_panel(&mut app, "acme:tree"); + + // GUI path: the message the native widget renderer sends on + // activation (button row = the user pressed the button). Drain the + // log first: setup dispatches (new drawing etc.) must not count. + let _ = plugin_dispatch_log(); + let _ = app.update(crate::app::Message::PanelWidgetNodeActivated { + owner: "acme.widgetpack".into(), + panel: "acme:tree".into(), + node: ocs_plugin_api::scene::StableId(7), + }); + let gui_log = plugin_dispatch_log(); + assert_eq!( + gui_log.len(), + 1, + "GUI activation dispatches exactly one event" + ); + + // MCP path: the SAME activation through the facade. + let result = app.automation_op( + r#"{"op":"plugin_panel_action","panel_id":"acme:tree","element":7,"kind":"node_activated"}"#, + ); + assert_eq!(result["ok"], true, "facade result: {result}"); + let mcp_log = plugin_dispatch_log(); + assert_eq!( + mcp_log.len(), + 1, + "facade activation dispatches exactly one event" + ); + + // Equivalence: same panel + same event; the per-surface sequence + // advanced by exactly one (identity is the sequence, not content). + let gui = gui_log[0].clone(); + let mcp = mcp_log[0].clone(); + assert!( + gui.starts_with("PanelSurfaceEvent(acme:tree, seq 1, "), + "gui: {gui}" + ); + assert!( + mcp.starts_with("PanelSurfaceEvent(acme:tree, seq 2, "), + "mcp: {mcp}" + ); + let event_part = |entry: &str| { + let (_seq, event) = entry + .split_once(", seq ") + .map(|(head, rest)| rest.split_once(", ").map_or((rest, ""), |parts| parts)) + .expect("seq split"); + event.to_string() + }; + assert_eq!( + event_part(&mcp), + event_part(&gui), + "identical event payloads" + ); + assert_eq!(result["sequence"], 2); + assert_eq!(result["kind"], "node_activated"); + } + + #[test] + fn plugin_panels_overview_and_paged_rows_stay_bounded() { + let mut app = super::OpenCADStudio::new_for_test(); + app.automation_op(r#"{"op":"new"}"#); + register_widget_panel(&mut app, "acme:tree"); + + let overview = app.automation_op(r#"{"op":"plugin_panels"}"#); + assert_eq!(overview["ok"], true); + assert_eq!(overview["panels"][0]["panel_id"], "acme:tree"); + assert_eq!(overview["panels"][0]["owner"], "acme.widgetpack"); + assert_eq!(overview["panels"][0]["tiers"]["widgets"]["rows"], 1); + + let detail = + app.automation_op(r#"{"op":"plugin_panels","panel_id":"acme:tree","tier":"widgets"}"#); + assert_eq!(detail["ok"], true); + assert_eq!(detail["rows"][0]["id"], 7); + assert_eq!(detail["rows"][0]["action"], "run"); + assert_eq!(detail["rows"][0]["children"], "leaf"); + assert!(detail["next"].is_null(), "single row has no next cursor"); + + // Unknown elements/panels refuse without dispatching any SURFACE + // event (the automation wrapper's post-op document notifications + // are the ordinary broadcast law, not the surface tier). + let surface_events = |log: &[String]| { + log.iter() + .filter(|e| e.starts_with("PanelSurfaceEvent")) + .count() + }; + let before = surface_events(&plugin_dispatch_log()); + let missing = app + .automation_op(r#"{"op":"plugin_panel_action","panel_id":"acme:tree","element":99}"#); + assert_eq!(missing["ok"], false); + let unknown = app + .automation_op(r#"{"op":"plugin_panel_action","panel_id":"nobody:here","element":7}"#); + assert_eq!(unknown["ok"], false); + assert_eq!( + surface_events(&plugin_dispatch_log()), + before, + "refusals dispatch no surface events" + ); + } + + #[test] + fn plugin_panels_pages_a_10k_row_surface_without_materializing_it() { + let mut app = super::OpenCADStudio::new_for_test(); + app.automation_op(r#"{"op":"new"}"#); + // Same visibility law as the helper: an in-process test sink keeps + // the owner's surface alive across the pump's reaper sweep. + crate::plugin::grip_points::install_in_process_sink("acme.widgetpack", |_host, _event| { + ocs_plugin_api::host::CustomGripResponse::default() + }); + let panel = ocs_plugin_api::dialog::PanelDef::new("acme:big", "Big"); + let mut state = crate::ui::window::plugin_panel::PluginPanelState::from_def(panel); + state.owner_plugin_id = Some("acme.widgetpack".into()); + app.plugin_panels.insert("acme:big".into(), state); + let mut surface = + ocs_plugin_api::widget::WidgetSurface::new(ocs_plugin_api::widget::WidgetRevision(1)); + for id in 1..=10_000u64 { + surface.rows.insert( + ocs_plugin_api::scene::StableId(id), + ocs_plugin_api::widget::WidgetRow { + label: format!("row {id}"), + children: ocs_plugin_api::widget::WidgetChildren::Leaf, + action: None, + }, + ); + } + surface.roots = (1..=10_000u64) + .map(ocs_plugin_api::scene::StableId) + .collect(); + app.panel_surfaces + .publish_widget("acme.widgetpack", "acme:big", surface) + .expect("10k-row surface publishes (at the budget cap)"); + + let detail = app.automation_op( + r#"{"op":"plugin_panels","panel_id":"acme:big","tier":"widgets","rows":200}"#, + ); + assert_eq!(detail["total_rows"], 10_000); + assert_eq!(detail["rows"].as_array().map(Vec::len), Some(200)); + + // Walk the cursor to the end: 50 pages of 200, ids strictly + // increasing, every row seen exactly once. + let mut seen = Vec::new(); + let mut after: Option = None; + for _ in 0..1_000 { + let mut request = json!({ + "op":"plugin_panels", + "panel_id":"acme:big", + "tier":"widgets", + "rows":200, + }); + if let Some(after) = after { + request["after"] = json!(after); + } + let page = app.automation_op(&request.to_string()); + assert_eq!(page["ok"], true); + let rows = page["rows"].as_array().cloned().unwrap_or_default(); + let empty = rows.is_empty(); + for row in &rows { + seen.push(row["id"].as_u64().expect("row id")); + } + match page["next"]["after"].as_u64() { + Some(next) => after = Some(next), + None => break, + } + if empty { + panic!("empty page with a next cursor"); + } + } + assert_eq!(seen.len(), 10_000, "every row paged exactly once"); + let mut sorted = seen.clone(); + sorted.sort_unstable(); + assert_eq!(sorted, seen, "pages are strictly increasing"); + assert_eq!(seen.first(), Some(&1)); + assert_eq!(seen.last(), Some(&10_000)); + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn an_edit_dispatches_document_changed_once_per_epoch() { - use document::entities::Point; use document::EntityType; + use document::entities::Point; let mut app = super::OpenCADStudio::new_for_test(); app.automation_op(r#"{"op":"new"}"#); @@ -2406,8 +2948,8 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] #[test] fn idempotent_designation_remarks_cannot_loop_the_dispatch() { - use document::entities::Point; use document::EntityType; + use document::entities::Point; // Models the consumer plugin's re-mark handler: on DocumentChanged it // re-marks its entities through the plugin host API. The write goes @@ -2450,8 +2992,8 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] #[test] fn history_replay_emits_no_plugin_notifications_itself() { - use document::entities::Point; use document::EntityType; + use document::entities::Point; // Undo/redo replay never publishes: the notification boundary is the // only channel, so replaying history steps in isolation is silent. @@ -2517,7 +3059,7 @@ mod tests { ); } use crate::app::{Message, OpenCADStudio}; - use serde_json::{json, Value}; + use serde_json::{Value, json}; #[test] fn audit_rejects_an_undeclared_entity_layer() { @@ -2693,10 +3235,12 @@ mod tests { let ordinary = app.automation_op(&serde_json::json!({"op":"save", "path":path}).to_string()); assert_eq!(ordinary["ok"], true, "{ordinary}"); - assert!(!ordinary["error"] - .as_str() - .unwrap_or_default() - .contains("changed outside")); + assert!( + !ordinary["error"] + .as_str() + .unwrap_or_default() + .contains("changed outside") + ); let _ = std::fs::remove_file(path); } @@ -4626,8 +5170,14 @@ DEAD .scene .replay_since(geometry_before) .expect("targeted block invalidation"); - assert!(changes.contains(&(line, crate::scene::ChangeKind::Modified)), "{changes:?}"); - assert!(changes.contains(&(insert, crate::scene::ChangeKind::Modified)), "{changes:?}"); + assert!( + changes.contains(&(line, crate::scene::ChangeKind::Modified)), + "{changes:?}" + ); + assert!( + changes.contains(&(insert, crate::scene::ChangeKind::Modified)), + "{changes:?}" + ); app.undo_active_tab(); assert_eq!( app.tabs[i] @@ -4856,7 +5406,14 @@ DEAD let q = app.automation_op(r#"{"op":"query","type":"Line","detail":"summary"}"#); let handle = q["entities"][0]["handle"].as_str().unwrap().to_owned(); let tab = app.active_tab; - app.tabs[tab].scene.document.layers.get_mut("0").unwrap().flags.locked = true; + app.tabs[tab] + .scene + .document + .layers + .get_mut("0") + .unwrap() + .flags + .locked = true; app.tabs[tab].dirty = false; // On a locked layer the line stays; listed twice, it is one object. @@ -4875,7 +5432,14 @@ DEAD assert_eq!(count_type(&mut app, "Line"), 1); assert!(!app.tabs[tab].dirty, "nothing was erased"); - app.tabs[tab].scene.document.layers.get_mut("0").unwrap().flags.locked = false; + app.tabs[tab] + .scene + .document + .layers + .get_mut("0") + .unwrap() + .flags + .locked = false; let r = mutate( &mut app, &format!( @@ -4892,11 +5456,12 @@ DEAD let mut app = OpenCADStudio::new_for_test(); app.automation_op(r#"{"op":"new"}"#); app.automation_op(r#"{"op":"run","cmd":"LINE 0,0 10,0"}"#); - let handle = app.automation_op(r#"{"op":"query","type":"Line","detail":"summary"}"#) - ["entities"][0]["handle"] - .as_str() - .unwrap() - .to_owned(); + let handle = + app.automation_op(r#"{"op":"query","type":"Line","detail":"summary"}"#)["entities"][0] + ["handle"] + .as_str() + .unwrap() + .to_owned(); let r = mutate( &mut app, @@ -4959,11 +5524,12 @@ DEAD r#"{{"protocol":1,"op":"block_define","request_id":"rb1","document_id":{doc},"name":"READBOX","base":[0,0,0],"handles":[{joined}]}}"# )); assert_eq!(defined["ok"], true, "{defined}"); - let insert = app.automation_op(r#"{"op":"query","type":"Insert","detail":"summary"}"#) - ["entities"][0]["handle"] - .as_str() - .unwrap() - .to_owned(); + let insert = + app.automation_op(r#"{"op":"query","type":"Insert","detail":"summary"}"#)["entities"] + [0]["handle"] + .as_str() + .unwrap() + .to_owned(); let scaled = mutate( &mut app, @@ -5002,11 +5568,12 @@ DEAD let mut app = OpenCADStudio::new_for_test(); app.automation_op(r#"{"op":"new"}"#); app.automation_op(r#"{"op":"run","cmd":"LINE 10,0 20,0"}"#); - let handle = app.automation_op(r#"{"op":"query","type":"Line","detail":"summary"}"#) - ["entities"][0]["handle"] - .as_str() - .unwrap() - .to_owned(); + let handle = + app.automation_op(r#"{"op":"query","type":"Line","detail":"summary"}"#)["entities"][0] + ["handle"] + .as_str() + .unwrap() + .to_owned(); let close = |a: f64, b: f64| (a - b).abs() < 1e-6; // Rotate 90° CCW about the origin: (10,0)→(0,10), (20,0)→(0,20). @@ -5066,11 +5633,12 @@ DEAD let mut app = OpenCADStudio::new_for_test(); app.automation_op(r#"{"op":"new"}"#); app.automation_op(r#"{"op":"run","cmd":"CIRCLE 0,0 1"}"#); - let handle = app.automation_op(r#"{"op":"query","type":"Circle","detail":"summary"}"#) - ["entities"][0]["handle"] - .as_str() - .unwrap() - .to_owned(); + let handle = + app.automation_op(r#"{"op":"query","type":"Circle","detail":"summary"}"#)["entities"] + [0]["handle"] + .as_str() + .unwrap() + .to_owned(); let r = mutate( &mut app, &format!( @@ -5101,11 +5669,12 @@ DEAD let mut app = OpenCADStudio::new_for_test(); app.automation_op(r#"{"op":"new"}"#); app.automation_op(r#"{"op":"run","cmd":"CIRCLE 5,5 2"}"#); - let handle = app.automation_op(r#"{"op":"query","type":"Circle","detail":"summary"}"#) - ["entities"][0]["handle"] - .as_str() - .unwrap() - .to_owned(); + let handle = + app.automation_op(r#"{"op":"query","type":"Circle","detail":"summary"}"#)["entities"] + [0]["handle"] + .as_str() + .unwrap() + .to_owned(); let r = mutate( &mut app, @@ -5477,11 +6046,12 @@ DEAD let mut app = OpenCADStudio::new_for_test(); app.automation_op(r#"{"op":"new"}"#); app.automation_op(r#"{"op":"run","cmd":"CIRCLE 5,5 2"}"#); - let handle = app.automation_op(r#"{"op":"query","type":"Circle","detail":"summary"}"#) - ["entities"][0]["handle"] - .as_str() - .unwrap() - .to_owned(); + let handle = + app.automation_op(r#"{"op":"query","type":"Circle","detail":"summary"}"#)["entities"] + [0]["handle"] + .as_str() + .unwrap() + .to_owned(); let r = mutate( &mut app, &format!( @@ -5870,7 +6440,7 @@ DEAD #[test] fn matchprop_uses_single_preselected_source_for_successive_destinations() { use crate::command::StepInput; - use document::{entities::Line, types::Vector3, EntityType}; + use document::{EntityType, entities::Line, types::Vector3}; for command in ["MA", "MATCHPROP"] { let mut app = OpenCADStudio::new_for_test(); @@ -5976,7 +6546,7 @@ DEAD #[test] fn matchprop_requests_source_without_a_single_preselected_object() { use crate::command::StepInput; - use document::{entities::Line, EntityType}; + use document::{EntityType, entities::Line}; for preselect in [false, true] { let mut app = OpenCADStudio::new_for_test(); @@ -6092,7 +6662,7 @@ DEAD #[test] fn matchprop_source_glow_survives_preview_refresh_and_destination_apply() { use crate::command::StepInput; - use document::{entities::Line, types::Vector3, EntityType}; + use document::{EntityType, entities::Line, types::Vector3}; let mut app = OpenCADStudio::new_for_test(); app.automation_op(r#"{"op":"new"}"#); @@ -6614,12 +7184,14 @@ DEAD Some("LINE") ); assert_eq!(app.tabs[0].active_cmd.as_ref().unwrap().prompt(), prompt); - assert!(app.tabs[0] - .active_cmd - .as_ref() - .unwrap() - .resolved_anchor() - .is_none()); + assert!( + app.tabs[0] + .active_cmd + .as_ref() + .unwrap() + .resolved_anchor() + .is_none() + ); assert_eq!(app.last_point, previous); assert!(app.tabs[0].suspended_cmd.is_none()); assert!(app.tabs[0].scene.document.entities().next().is_none()); @@ -6801,10 +7373,11 @@ DEAD // Snapper is now forced on with only Midpoint enabled assert!(app.snapper.snap_enabled); assert_eq!(app.snapper.enabled.len(), 1); - assert!(app - .snapper - .enabled - .contains(&crate::snap::SnapType::Midpoint)); + assert!( + app.snapper + .enabled + .contains(&crate::snap::SnapType::Midpoint) + ); // Submit first point (0,0) let _ = app.update(Message::CommandInput("0,0".to_string())); @@ -6817,10 +7390,11 @@ DEAD let _ = app.update(Message::CommandInput("END".to_string())); let _ = app.update(Message::CommandSubmit); assert!(app.snapper.snap_enabled); - assert!(app - .snapper - .enabled - .contains(&crate::snap::SnapType::Endpoint)); + assert!( + app.snapper + .enabled + .contains(&crate::snap::SnapType::Endpoint) + ); // Escape cancels LINE and clears unconsumed snap override let _ = app.update(Message::CommandEscape); @@ -6857,8 +7431,8 @@ DEAD fn serve_socket_drops_a_client_streaming_an_oversize_line() { use std::io::{BufRead, BufReader, Write}; use std::net::TcpStream; - use std::sync::atomic::{AtomicU16, Ordering}; use std::sync::Arc; + use std::sync::atomic::{AtomicU16, Ordering}; let bound = Arc::new(AtomicU16::new(0)); let listen_bound = bound.clone(); @@ -6924,8 +7498,8 @@ DEAD fn serve_socket_drops_an_idle_client_and_keeps_serving() { use std::io::{BufRead, BufReader}; use std::net::TcpStream; - use std::sync::atomic::{AtomicU16, Ordering}; use std::sync::Arc; + use std::sync::atomic::{AtomicU16, Ordering}; use std::time::Duration; let bound = Arc::new(AtomicU16::new(0)); diff --git a/src/app/panel_events.rs b/src/app/panel_events.rs index 27e5608ae1..3cc18f0137 100644 --- a/src/app/panel_events.rs +++ b/src/app/panel_events.rs @@ -259,6 +259,25 @@ impl PanelEventRouter { } } + /// Automation-triggered activation of a SCENE element (api v29, S08): + /// the agent's `plugin_panel_action` routes here, mirroring + /// `on_node_activated`. The explicit identity is the per-surface + /// sequence, as everywhere; `pos` is pointer-derived payload, NOT + /// identity — the automation path anchors it at the element's stored + /// origin (no pointer exists), so equivalence with a GUI click is + /// asserted on (panel, sequence, kind, element), never on pos. + pub fn on_element_clicked(&mut self, panel_id: &str, element: StableId) -> RoutedEvent { + let sequence = self.next_sequence(panel_id); + RoutedEvent { + panel_id: panel_id.to_owned(), + sequence, + event: SurfaceEvent::ElementClicked { + element, + pos: ocs_plugin_api::scene::Vec2([0.0, 0.0]), + }, + } + } + /// Settle the active drag (whatever panel owns it): a `DragSettled` /// at the latest known position when started, or a silent drop when /// the drag never began. The single-pointer law: a new press steals diff --git a/src/app/panel_surfaces.rs b/src/app/panel_surfaces.rs index 3ee87fe8b1..fb68debedb 100644 --- a/src/app/panel_surfaces.rs +++ b/src/app/panel_surfaces.rs @@ -392,6 +392,91 @@ impl PanelSurfaceStore { .filter(|record| record.owner_plugin_id == plugin_id) .map(|record| &record.surface) } + + /// Owner-agnostic store read for the host's OWN automation interface + /// (api v29, S08: the MCP facade reads what the operator's app owns — + /// plugin-to-plugin isolation is untouched: `scene`/`widget`/`table` + /// keep their owner checks). One bounded summary line per surface. + pub fn surface_summaries(&self) -> Vec { + let mut out = Vec::new(); + for (panel_id, record) in &self.scenes { + out.push(SurfaceSummary { + panel_id: panel_id.clone(), + owner: record.owner_plugin_id.clone(), + scene: Some((record.scene.revision.0, record.scene.elements.len())), + widgets: None, + tables: None, + }); + } + for (panel_id, record) in &self.widgets { + match out.iter_mut().find(|s| &s.panel_id == panel_id) { + Some(entry) => { + entry.widgets = Some((record.surface.revision.0, record.surface.rows.len())) + } + None => out.push(SurfaceSummary { + panel_id: panel_id.clone(), + owner: record.owner_plugin_id.clone(), + scene: None, + widgets: Some((record.surface.revision.0, record.surface.rows.len())), + tables: None, + }), + } + } + for (panel_id, record) in &self.tables { + match out.iter_mut().find(|s| &s.panel_id == panel_id) { + Some(entry) => { + entry.tables = Some(( + record.surface.revision.0, + record.surface.rows.len(), + record.surface.columns.len(), + )) + } + None => out.push(SurfaceSummary { + panel_id: panel_id.clone(), + owner: record.owner_plugin_id.clone(), + scene: None, + widgets: None, + tables: Some(( + record.surface.revision.0, + record.surface.rows.len(), + record.surface.columns.len(), + )), + }), + } + } + out + } + + /// Owner-agnostic tier read for the automation facade (same law as + /// `surface_summaries`). + pub fn scene_any_owner(&self, panel_id: &str) -> Option<&PanelScene> { + self.scenes.get(panel_id).map(|record| &record.scene) + } + + /// Owner-agnostic widget-tier read (see `scene_any_owner`). + pub fn widget_any_owner( + &self, + panel_id: &str, + ) -> Option<&ocs_plugin_api::widget::WidgetSurface> { + self.widgets.get(panel_id).map(|record| &record.surface) + } + + /// Owner-agnostic table-tier read (see `scene_any_owner`). + pub fn table_any_owner(&self, panel_id: &str) -> Option<&ocs_plugin_api::tables::TableSurface> { + self.tables.get(panel_id).map(|record| &record.surface) + } +} + +/// One panel's surface inventory for the automation facade (S08): owner, +/// plus per-tier `(revision, count)` presence. Counts are bounded by the +/// tier budgets; nothing here materializes rows. +#[derive(Debug, Clone, PartialEq)] +pub struct SurfaceSummary { + pub panel_id: String, + pub owner: String, + pub scene: Option<(u64, usize)>, + pub widgets: Option<(u64, usize)>, + pub tables: Option<(u64, usize, usize)>, } #[cfg(test)] diff --git a/src/mcp.rs b/src/mcp.rs index 23ef62ec0e..2b54e120e3 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -4,9 +4,9 @@ //! to the authenticated GUI control bridge; this module contains no geometry. use crate::mcp_ops::{batch_bindings, validate_execute_request}; -use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _}; +use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64}; use serde::Deserialize; -use serde_json::{json, Map, Value}; +use serde_json::{Map, Value, json}; use sha2::{Digest, Sha256}; #[cfg(any(windows, target_os = "macos"))] use std::collections::HashSet; @@ -66,7 +66,7 @@ const MODERN_PROTOCOL_VERSION: &str = "2026-07-28"; /// `save` describes its `target_version` as the DWG version. /// `ocs_capture` / `ocs_render` gained `layout`, `aspect_fit`, and `renderer` (`document_id` on `ocs_capture`) for headless off-screen capture. #[cfg(test)] -const TOOL_SCHEMA_DIGEST: &str = "586df5bc8dbab0ae7b9d7959dc227dbf46e9baeedf9a8c6dec423d389a04eb5a"; +const TOOL_SCHEMA_DIGEST: &str = "b6f40c032594c2626b6eeb04d4eb0c1532c3722a3d2dca3368ee5b73983ec3cc"; const MAX_REQUEST: usize = 1_048_576; const MAX_RESPONSE: u64 = 16 * 1024 * 1024; const CACHE_TTL_MS: u64 = 3_600_000; @@ -74,7 +74,7 @@ const CACHE_TTL_MS: u64 = 3_600_000; /// land. Tools and discovery are static by comparison, so they keep the hour. const RESOURCE_TTL_MS: u64 = 60_000; const TASK_TTL_MS: u64 = 3_600_000; -pub(crate) const INSTRUCTIONS: &str = "Prefer intent tools: ocs_inspect, ocs_query, ocs_run, ocs_new/open/save, ocs_render. Use ocs_read/ocs_execute for advanced work and explicit envelopes. ocs_session_id is optional with one session. Intent calls need no request_id, but reuse one to retry a mutation; after an uncertain outcome query the operation, and never replay a mutation with a new id. Read capabilities and record_schema before unfamiliar ops; use entity_schema for creation, validate for preflight. Preserve document_id and revision from state. running/waiting_input are not completion: follow state.command.accepts, options, input_example. Let the geometry kernel do the math. Before delivery audit the target format/version, then save_verified or ocs_save_verified to an absolute path. Announce the bridge build on connection and change. For batches use response_detail: summary; bindings reuse earlier results. Read guides via cad://guides/{name} or ocs_read op: guide, parameters.name: workflow, architecture, capture, batch-bindings. Read architecture before floorplan vectorization; capture before visual verification."; +pub(crate) const INSTRUCTIONS: &str = "Prefer intent tools: ocs_inspect, ocs_query, ocs_run, ocs_new/open/save, ocs_render. Inspect and drive plugin panel surfaces with ocs_panels and ocs_panel_action. Use ocs_read/ocs_execute for advanced work and explicit envelopes. ocs_session_id is optional with one session. Intent calls need no request_id, but reuse one to retry a mutation; after an uncertain outcome query the operation, and never replay a mutation with a new id. Read capabilities and record_schema before unfamiliar ops; use entity_schema for creation, validate for preflight. Preserve document_id and revision from state. running/waiting_input are not completion: follow state.command.accepts, options, input_example. Let the geometry kernel do the math. Before delivery audit the target format/version, then save_verified or ocs_save_verified to an absolute path. Announce the bridge build on connection and change. For batches use response_detail: summary; bindings reuse earlier results. Read guides via cad://guides/{name} or ocs_read op: guide, parameters.name: workflow, architecture, capture, plugin-panels, batch-bindings. Read architecture before floorplan vectorization; capture before visual verification."; const READ_OPS: &[&str] = &[ "state", "hello", @@ -111,6 +111,7 @@ const READ_OPS: &[&str] = &[ "keytips", "plugins", "capture", + "plugin_panels", ]; const EXECUTE_OPS: &[&str] = &[ "new", @@ -132,6 +133,7 @@ const EXECUTE_OPS: &[&str] = &[ "panel_input", "panel_button", "panel_action", + "plugin_panel_action", "action", "embed_image", "dgn_import", @@ -633,13 +635,7 @@ impl ResourceStore { self.insert_tile_entry(session_id, uri, hash, data_base64, bytes_len, metadata) } - fn tile_uri_for( - session_id: &str, - layout: Option<&str>, - level: u32, - x: u32, - y: u32, - ) -> String { + fn tile_uri_for(session_id: &str, layout: Option<&str>, level: u32, x: u32, y: u32) -> String { match layout.map(str::trim).filter(|s| !s.is_empty()) { Some(lay) => { let enc = encode_uri_segment(lay); @@ -705,8 +701,10 @@ impl ResourceStore { )), ); } - self.layout_manifests - .insert((session_id.to_string(), layout.to_ascii_lowercase()), manifest); + self.layout_manifests.insert( + (session_id.to_string(), layout.to_ascii_lowercase()), + manifest, + ); uri } @@ -1961,6 +1959,11 @@ const GUIDES: &[(&str, &str, &str)] = &[ "Captures and visual verification", include_str!("../docs/automation/guides/capture.md"), ), + ( + "plugin-panels", + "Plugin panel surfaces", + include_str!("../docs/automation/guides/plugin-panels.md"), + ), ( "batch-bindings", "Dependent batch steps", @@ -2043,7 +2046,13 @@ fn serve_tile_resource( })?), None => resources.pyramid_manifests.get(session_id), }; - let manifest_layout = layout_opt.or_else(|| manifest.and_then(|m| m.get("layout")).and_then(Value::as_str)).map(str::to_string); + let manifest_layout = layout_opt + .or_else(|| { + manifest + .and_then(|m| m.get("layout")) + .and_then(Value::as_str) + }) + .map(str::to_string); let manifest_renderer = manifest .and_then(|m| m.get("renderer")) .and_then(Value::as_str) @@ -2057,11 +2066,12 @@ fn serve_tile_resource( None => [-100.0, -100.0, 100.0, 100.0], }; - let tile_bounds = - crate::app::control::vision::compute_tile_bounds(base_bounds, level, x, y)?; + let tile_bounds = crate::app::control::vision::compute_tile_bounds(base_bounds, level, x, y)?; let path = std::env::temp_dir().join(format!( "ocs-tile-{session_id}-{}-{level}-{x}-{y}.png", - layout_opt.map(encode_uri_segment).unwrap_or_else(|| "active".to_string()) + layout_opt + .map(encode_uri_segment) + .unwrap_or_else(|| "active".to_string()) )); let mut req = json!({ "op": "capture", @@ -2285,16 +2295,7 @@ fn read_resource( } else if let Some(trimmed) = subpath.strip_prefix("tile/") { if let Some((level, x, y, is_json)) = parse_tile_subpath(trimmed) { return serve_tile_resource( - uri, - session_id, - None, - level, - x, - y, - is_json, - clients, - resources, - pump, + uri, session_id, None, level, x, y, is_json, clients, resources, pump, mcp_id, ); } @@ -2689,9 +2690,7 @@ fn call_tool( let manifest_for_meta = if let Some(eff_lay) = tile_layout { if !targets_other_doc { resources.insert_layout_manifest(session_id, eff_lay, manifest_val); - resources - .get_layout_manifest(session_id, eff_lay) - .cloned() + resources.get_layout_manifest(session_id, eff_lay).cloned() } else { let enc = encode_uri_segment(eff_lay); if let Some(obj) = manifest_val.as_object_mut() { @@ -2854,7 +2853,7 @@ pub(crate) fn tool_definitions() -> Value { }, { "name":"ocs_read", - "description":"Use entity_schema with parameters.type for creation fields/examples; omit type to list. Use validate with parameters.request to check an execute request without running it (no live document checks). Use guide with parameters.name to read workflow, architecture, capture or batch-bindings guidance (omit name to list). Discover capabilities and record schemas, or read state, complete database records, command manifests, entities, blocks (semantic block instances with attributes, definition tags and dynamic properties), properties, kernel measurements and spatial relationships, history, events or operation status from a live OCS session. Use batch_result with parameters.request_id to retrieve retained batch details without executing steps; available only in the originating MCP connection, for up to 64 retained batches per session.", + "description":"Use entity_schema with parameters.type for creation fields/examples; omit type to list. Use validate with parameters.request to check an execute request without running it (no live document checks). Use guide with parameters.name to read workflow, architecture, capture, plugin-panels or batch-bindings guidance (omit name to list). Discover capabilities and record schemas, or read state, complete database records, command manifests, entities, blocks (semantic block instances with attributes, definition tags and dynamic properties), properties, kernel measurements and spatial relationships, history, events or operation status from a live OCS session. Use batch_result with parameters.request_id to retrieve retained batch details without executing steps; available only in the originating MCP connection, for up to 64 retained batches per session.", "inputSchema":{"type":"object","properties":{"ocs_session_id":{"type":"string","minLength":1,"description":"Value of session_id returned by ocs_sessions."},"op":{"type":"string","enum":READ_OPS,"default":"state"},"parameters":{"type":"object","description":"Operation-specific filters.","properties":{"layout":{"type":"string","minLength":1,"description":"Layout name for op: page_setup_get."},"request":{"type":"object","description":"Execute request to preflight without dispatch. request_id may be omitted. Batch bindings are checked structurally; result-dependent values require execution."},"name":{"type":"string","description":"Command name, block name/glob, or record name."},"names":{"type":"array","items":{"type":"string"},"description":"Block name or wildcard glob filters (e.g. ['*'], ['DOOR*']) for op: blocks."},"extract_attributes":{"type":"boolean","default":true,"description":"Extract ATTRIB values, ATTDEF defaults, and visible definition text tags (e.g. TAG, DIMS) for op: blocks."},"extract_dynamic_properties":{"type":"boolean","default":true,"description":"Extract dynamic block parameters, visibility states, and lookup values for op: blocks."},"include_anonymous":{"type":"boolean","default":false,"description":"Include unlinked internal anonymous blocks (*U..., *D..., *T...) in op: blocks."},"search":{"type":"string","description":"Case-insensitive command or record-type search."},"find":{"type":"string","description":"Text query string for text_search."},"match_case":{"type":"boolean","default":false,"description":"Case-sensitive text search."},"whole_word":{"type":"boolean","default":false,"description":"Match only whole words."},"ignore_accents":{"type":"boolean","description":"Ignore accents/diacritics in text (defaults to true when match_case is false)."},"scope":{"type":"string","enum":["all","active_space","blocks"],"default":"all","description":"Text search scope."},"system_spellcheck":{"type":"boolean","default":false,"description":"Use native OS spell-checker (Windows, macOS, Linux)."},"language":{"type":"string","description":"Language tag for spell-checker (e.g. 'fr-FR', 'en-US', 'de-DE', 'es-ES')."},"suggest":{"type":"boolean","default":true,"description":"Include suggested corrections for misspelled words."},"check_terms":{"type":"array","items":{"type":"string"},"description":"List of terms or suspect misspellings to flag in text_audit."},"dictionary":{"type":"array","items":{"type":"string"},"description":"Known valid words for text_audit dictionary check."},"pairs":{"type":"array","description":"Find/replace pairs for dry-run simulation in text_audit.","items":{"type":"object","properties":{"find":{"type":"string"},"replace":{"type":"string"}},"required":["find","replace"]}},"dry_run_pairs":{"type":"array","description":"Alias for pairs in text_audit.","items":{"type":"object","properties":{"find":{"type":"string"},"replace":{"type":"string"}},"required":["find","replace"]}},"document_id":{"type":"integer","minimum":0},"path":{"type":"string","description":"Optional intended output path for audit; extension determines target format."},"target_format":{"type":"string","enum":["dwg","dxf"],"description":"Intended output format for audit."},"target_version":{"type":"string","enum":["R14","2000","2004","2007","2010","2013","2018","AC1014","AC1015","AC1018","AC1021","AC1024","AC1027","AC1032"],"description":"Intended CAD output version for audit."},"collection":{"type":"string","description":"Record collection, all for records, or omit to discover collections and schema types."},"handle":{"type":"string"},"handles":{"type":"array","items":{"type":"string"},"description":"Exact entity or record handles."},"type":{"type":"string","description":"Entity or record type filter; for record_schema, returns its complete type graph and writable field paths."},"layer":{"type":"string","description":"Layer name filter for query; * and ? are wildcards."},"xdata_app":{"type":"string","description":"Only entities carrying XDATA of this application (query)."},"detail":{"type":"string","enum":["summary","geometry","full"],"default":"geometry","description":"Entity detail returned by query."},"fields":{"type":"array","items":{"type":"string"},"description":"Return only these entity fields plus handle."},"paths":{"type":"array","items":{"type":"string"},"description":"Project RFC 6901 JSON Pointer paths relative to record.properties."},"where":{"type":"array","description":"All property filters must match.","items":{"type":"object","properties":{"path":{"type":"string"},"op":{"type":"string","enum":["eq","ne","lt","lte","gt","gte","contains","starts_with","ends_with","in","exists","not_exists"],"default":"eq"},"value":{}},"required":["path"],"additionalProperties":false}},"near":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":3,"description":"Rank planar curves by exact kernel distance to this world XY point."},"point":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":3,"description":"World point whose object snap the snap op reports."},"from":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":3,"description":"Base point for perpendicular and tangent snaps (snap op)."},"contains_point":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":3,"description":"Return closed planar curves containing this world XY point."},"bounds":{"type":"array","items":{"type":"number"},"minItems":4,"maxItems":4,"description":"Filter entities whose world XY bounds overlap [min_x,min_y,max_x,max_y]."},"intersections":{"type":"array","items":{"type":"string"},"minItems":2,"maxItems":2,"description":"Return exact kernel intersections between two planar curve handles."},"after":{"type":"integer","minimum":0,"description":"Event cursor."},"request_id":{"type":"string","description":"Operation id to query."},"offset":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":10000},"station":{"type":"number","description":"Alignment station for op: civil_station_offset."},"offset_distance":{"type":"number","description":"Signed perpendicular distance from the alignment, positive right of travel, for op: civil_station_offset."},"handle":{"type":"string"},"handles":{"type":"array","items":{"type":"string"},"description":"Exact entity or record handles."}},"additionalProperties":false}},"anyOf":[{"required":["ocs_session_id"]},{"required":["op"],"properties":{"op":{"enum":["guide","entity_schema","validate"]}}}],"additionalProperties":false}, "outputSchema":read_output_schema(), "title":"Read OCS state","annotations":{"readOnlyHint":true,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false} @@ -3716,7 +3715,7 @@ mod tests { &names[..4], ["ocs_sessions", "ocs_read", "ocs_execute", "ocs_capture"] ); - assert_eq!(names.len(), 20); + assert_eq!(names.len(), 22); // The build announcement must live in the entry-point tool // description: global instructions don't reliably reach agents. assert!( @@ -3728,15 +3727,19 @@ mod tests { ); assert_eq!(tools[0]["annotations"]["readOnlyHint"], false); for tool in [&tools[1], &tools[2], &tools[3]] { - assert!(tool["inputSchema"]["properties"] - .get("session_id") - .is_none()); + assert!( + tool["inputSchema"]["properties"] + .get("session_id") + .is_none() + ); } for tool in [&tools[2], &tools[3]] { - assert!(tool["inputSchema"]["required"] - .as_array() - .unwrap() - .contains(&json!("ocs_session_id"))); + assert!( + tool["inputSchema"]["required"] + .as_array() + .unwrap() + .contains(&json!("ocs_session_id")) + ); } let read_schema = &tools[1]["inputSchema"]; for op in ["guide", "entity_schema", "validate"] { @@ -3798,8 +3801,8 @@ mod tests { let save_var = find_variant("save_verified"); assert_eq!(save_var["properties"]["target_version"]["enum"][0], "R14"); assert_eq!( - tools[1]["inputSchema"]["properties"]["parameters"]["properties"]["where"]["items"] - ["properties"]["op"]["enum"], + tools[1]["inputSchema"]["properties"]["parameters"]["properties"]["where"]["items"]["properties"] + ["op"]["enum"], json!([ "eq", "ne", @@ -3841,10 +3844,12 @@ mod tests { initialized["result"]["capabilities"]["resources"]["subscribe"], false ); - assert!(initialized["result"]["instructions"] - .as_str() - .unwrap() - .contains("geometry kernel")); + assert!( + initialized["result"]["instructions"] + .as_str() + .unwrap() + .contains("geometry kernel") + ); let listed = handle_message( json!({"jsonrpc":"2.0","id":2,"method":"tools/list"}), @@ -3854,7 +3859,7 @@ mod tests { &mut detached_pump(), ) .unwrap(); - assert_eq!(listed["result"]["tools"].as_array().unwrap().len(), 20); + assert_eq!(listed["result"]["tools"].as_array().unwrap().len(), 22); // SEP-2549: freshness hints ship on every protocol version; only // the modern envelope stays negotiated (see // legacy_list_results_carry_sep2549_ttl). @@ -3879,9 +3884,10 @@ mod tests { assert_eq!(discovered["result"]["cacheScope"], "public"); assert_eq!(discovered["result"]["supportedVersions"][0], "2026-07-28"); assert!(discovered["result"]["capabilities"]["resources"].is_object()); - assert!(discovered["result"]["capabilities"]["extensions"] - ["io.modelcontextprotocol/tasks"] - .is_object()); + assert!( + discovered["result"]["capabilities"]["extensions"]["io.modelcontextprotocol/tasks"] + .is_object() + ); assert_eq!( discovered["result"]["_meta"]["io.modelcontextprotocol/serverInfo"]["name"], "OpenCADStudio" @@ -4334,12 +4340,16 @@ mod tests { ) .unwrap(); let templates = listed["result"]["resourceTemplates"].as_array().unwrap(); - assert!(templates - .iter() - .any(|t| t["uriTemplate"].as_str().unwrap().contains("{level}"))); - assert!(templates - .iter() - .any(|t| t["uriTemplate"].as_str().unwrap().contains("{hash}"))); + assert!( + templates + .iter() + .any(|t| t["uriTemplate"].as_str().unwrap().contains("{level}")) + ); + assert!( + templates + .iter() + .any(|t| t["uriTemplate"].as_str().unwrap().contains("{hash}")) + ); assert_eq!(listed["result"]["ttlMs"], RESOURCE_TTL_MS); assert_eq!(listed["result"]["cacheScope"], "public"); } @@ -4495,10 +4505,12 @@ mod tests { .unwrap(); let prop = &capture["inputSchema"]["properties"]["request_id"]; assert_eq!(prop["type"], "string"); - assert!(!capture["inputSchema"]["required"] - .as_array() - .unwrap() - .contains(&json!("request_id"))); + assert!( + !capture["inputSchema"]["required"] + .as_array() + .unwrap() + .contains(&json!("request_id")) + ); } #[test] @@ -4595,10 +4607,12 @@ mod tests { .unwrap(); assert_eq!(called["result"]["isError"], true); assert!(called["result"].get("structuredContent").is_none()); - assert!(called["result"]["content"][0]["text"] - .as_str() - .unwrap() - .contains("request_id")); + assert!( + called["result"]["content"][0]["text"] + .as_str() + .unwrap() + .contains("request_id") + ); } #[test] @@ -4647,9 +4661,11 @@ mod tests { .unwrap(); let res_arr = listed["result"]["resources"].as_array().unwrap(); assert!(res_arr.iter().any(|r| r["uri"] == uri)); - assert!(res_arr - .iter() - .any(|r| r["uri"] == "cad://session/sess1/snapshot/latest.png")); + assert!( + res_arr + .iter() + .any(|r| r["uri"] == "cad://session/sess1/snapshot/latest.png") + ); // Test resources/read with png let read_png = handle_message( @@ -4734,10 +4750,12 @@ mod tests { ); let content = res_res["content"].as_array().unwrap(); assert_eq!(content[0]["type"], "text"); - assert!(content[0]["text"] - .as_str() - .unwrap() - .contains("cad://session/s1/snapshot/hash123.png")); + assert!( + content[0]["text"] + .as_str() + .unwrap() + .contains("cad://session/s1/snapshot/hash123.png") + ); assert_eq!(content[1]["type"], "resource_link"); assert_eq!(content[1]["name"], "Captured viewport"); assert_eq!(content[1]["mimeType"], "image/png"); @@ -4842,7 +4860,9 @@ mod tests { resolve_tile_base_bounds(&json!({}), &resources, "s1", Some("sheet 1")).unwrap(), [0.0, 0.0, 297.0, 210.0] ); - assert!(resolve_tile_base_bounds(&json!({}), &resources, "s1", Some("Uncaptured")).is_err()); + assert!( + resolve_tile_base_bounds(&json!({}), &resources, "s1", Some("Uncaptured")).is_err() + ); assert_eq!( resolve_tile_base_bounds( &json!({"bounds": [0.0, 0.0, 420.0, 297.0]}), @@ -4887,7 +4907,9 @@ mod tests { &mut detached_pump(), ) .unwrap(); - let s_man_txt = read_s_man["result"]["contents"][0]["text"].as_str().unwrap(); + let s_man_txt = read_s_man["result"]["contents"][0]["text"] + .as_str() + .unwrap(); assert!(s_man_txt.contains("cad://session/s1/layout/Sheet%201/tile/{level}/{x}/{y}.png")); let read_m_tile = handle_message( @@ -4908,10 +4930,12 @@ mod tests { &mut detached_pump(), ) .unwrap(); - assert!(read_s_tile_json["result"]["contents"][0]["text"] - .as_str() - .unwrap() - .contains("sheet-tile")); + assert!( + read_s_tile_json["result"]["contents"][0]["text"] + .as_str() + .unwrap() + .contains("sheet-tile") + ); let untagged = json!({"world_bounds": [0.0, 0.0, 10.0, 10.0]}); let model = json!({"layout": "Model", "world_bounds": [0.0, 0.0, 10.0, 10.0]}); @@ -4934,11 +4958,13 @@ mod tests { })); assert_eq!(result["isError"], false); assert_eq!(result["structuredContent"], metadata); - assert!(result["content"] - .as_array() - .unwrap() - .iter() - .any(|block| block["type"] == "image" && block["data"] == "capture-png")); + assert!( + result["content"] + .as_array() + .unwrap() + .iter() + .any(|block| block["type"] == "image" && block["data"] == "capture-png") + ); } } @@ -5019,10 +5045,12 @@ mod tests { .unwrap(); let man_contents = read_man["result"]["contents"].as_array().unwrap(); assert_eq!(man_contents[0]["mimeType"], "application/json"); - assert!(man_contents[0]["text"] - .as_str() - .unwrap() - .contains("cad://session/sess1/tile/{level}/{x}/{y}.png")); + assert!( + man_contents[0]["text"] + .as_str() + .unwrap() + .contains("cad://session/sess1/tile/{level}/{x}/{y}.png") + ); // 5. Test resources/read with tile png let read_tile = handle_message( @@ -5082,9 +5110,11 @@ mod tests { "request_id":"draw", "steps":[{"op":"run","request_id":"nested","cmd":"LINE 0,0 10,0"}] }); - assert!(validate_execute_request(&invalid, "batch") - .unwrap_err() - .contains("omit request_id")); + assert!( + validate_execute_request(&invalid, "batch") + .unwrap_err() + .contains("omit request_id") + ); let compact = compact_state(&json!({ "session_id":"s","document_id":3,"revision":4,"geometry_revision":5, @@ -5192,10 +5222,12 @@ mod tests { })); assert_eq!(result["isError"], true); assert!(result.get("structuredContent").is_none()); - assert!(result["content"][0]["text"] - .as_str() - .unwrap() - .contains("stale_state")); + assert!( + result["content"][0]["text"] + .as_str() + .unwrap() + .contains("stale_state") + ); } #[test] @@ -5252,8 +5284,10 @@ mod tests { }); let batch_res = validate_execute_request(&batch, "batch").expect("batch passes"); assert_eq!(batch_res.warnings.len(), 1); - assert!(batch_res.warnings[0] - .contains("batch step 0: unknown parameter 'stray' ignored for op 'run'")); + assert!( + batch_res.warnings[0] + .contains("batch step 0: unknown parameter 'stray' ignored for op 'run'") + ); } #[test] @@ -5407,15 +5441,19 @@ mod tests { // Reconstruct the old duplicated layout using the same operation // definitions, so the size comparison stays meaningful as ops evolve. let mut old = standalone.clone(); - old["anyOf"] = json!(crate::mcp_ops::OPS - .iter() - .map(|op| crate::mcp_ops::op_schema(op)) - .collect::>()); - old["$defs"]["batch_step"]["anyOf"] = json!(crate::mcp_ops::OPS - .iter() - .filter(|op| op.batchable) - .map(|op| crate::mcp_ops::op_schema(op)) - .collect::>()); + old["anyOf"] = json!( + crate::mcp_ops::OPS + .iter() + .map(|op| crate::mcp_ops::op_schema(op)) + .collect::>() + ); + old["$defs"]["batch_step"]["anyOf"] = json!( + crate::mcp_ops::OPS + .iter() + .filter(|op| op.batchable) + .map(|op| crate::mcp_ops::op_schema(op)) + .collect::>() + ); old["$defs"] .as_object_mut() .unwrap() @@ -5460,10 +5498,12 @@ mod tests { json!({"request":{"op":"entities_create","entities":[{"type":"Circle","center":["bad",0],"radius":2}]}}), ); assert_eq!(invalid["valid"], false); - assert!(invalid["error"] - .as_str() - .unwrap() - .contains("/entities/0/center/0")); + assert!( + invalid["error"] + .as_str() + .unwrap() + .contains("/entities/0/center/0") + ); assert!(clients.is_empty()); assert!(resources.latest.is_empty()); let rejected = call_tool( @@ -5504,7 +5544,7 @@ mod tests { #[test] fn guides_are_discoverable_without_a_gui_session() { - assert!(INSTRUCTIONS.len() < 1100); + assert!(INSTRUCTIONS.len() < 1200); assert!(INSTRUCTIONS.contains("state.command.accepts")); assert!(INSTRUCTIONS.contains("never replay a mutation")); let mut clients = HashMap::new(); @@ -5529,11 +5569,13 @@ mod tests { assert_eq!(tool_list["guides"].as_array().unwrap().len(), GUIDES.len()); for (name, _, text) in GUIDES { let uri = format!("cad://guides/{name}"); - assert!(listed["result"]["resources"] - .as_array() - .unwrap() - .iter() - .any(|r| r["uri"] == uri)); + assert!( + listed["result"]["resources"] + .as_array() + .unwrap() + .iter() + .any(|r| r["uri"] == uri) + ); let resource = read_resource( &uri, &mut clients, @@ -5556,14 +5598,16 @@ mod tests { assert_eq!(tool["ok"], true); assert_eq!(tool_list["ok"], true); } - assert!(read_resource( - "cad://guides/missing", - &mut clients, - &mut resources, - &mut detached_pump(), - None - ) - .is_err()); + assert!( + read_resource( + "cad://guides/missing", + &mut clients, + &mut resources, + &mut detached_pump(), + None + ) + .is_err() + ); assert!(clients.is_empty()); } @@ -5571,20 +5615,24 @@ mod tests { fn batch_bindings_validate_and_preserve_types() { let step = json!({"op":"group_create","name":"walls","bindings":{"handles":{"step":0,"path":"/result/a~1b~0c"}}}); let request = json!({"op":"batch","steps":[{"op":"run","cmd":"LINE 0,0 1,1"},step]}); - assert!(validate_execute_request(&request, "batch") - .unwrap() - .warnings - .is_empty()); + assert!( + validate_execute_request(&request, "batch") + .unwrap() + .warnings + .is_empty() + ); let results = vec![json!({"ok":true,"status":"completed","result":{"a/b~c":["A","B"]}})]; let resolved = resolve_batch_step(&step, 1, &results).unwrap(); assert_eq!(resolved["handles"], json!(["A", "B"])); assert!(resolved.get("bindings").is_none()); - assert!(resolve_batch_step( - &step, - 1, - &[json!({"status":"completed","result":{"a/b~c":42}})] - ) - .is_err()); + assert!( + resolve_batch_step( + &step, + 1, + &[json!({"status":"completed","result":{"a/b~c":42}})] + ) + .is_err() + ); assert!(resolve_batch_step(&step, 1, &[json!({"status":"running"})]).is_err()); assert!(resolve_batch_step(&step, 1, &[json!({"status":"completed"})]).is_err()); for binding in [ @@ -5849,9 +5897,11 @@ mod tests { assert!(schema["$defs"]["window"].is_object()); assert!(schema["$defs"]["batch_step"].is_object()); let json_str = schema.to_string(); - // Generates cleanly without exponential blowup: compact ~15KB to 45KB + // Generates cleanly without exponential blowup: compact ~15KB to 48KB + // (the catalogue's 13th execute op, plugin_panel_action, sits inside + // the deliberate 2026-11 budget revisit) assert!( - json_str.len() < 45_000, + json_str.len() < 48_000, "schema size is {} bytes", json_str.len() ); diff --git a/src/mcp_intent.rs b/src/mcp_intent.rs index 145c720cf6..5631727fd9 100644 --- a/src/mcp_intent.rs +++ b/src/mcp_intent.rs @@ -1,7 +1,7 @@ //! Transport-neutral descriptors and generated schemas for curated MCP intent tools. use crate::mcp_ops::{self, OpDef}; -use serde_json::{json, Value}; +use serde_json::{Value, json}; #[derive(Clone, Copy, PartialEq, Eq)] pub enum IntentKind { @@ -64,6 +64,11 @@ pub static DESCRIPTORS: &[IntentDescriptor] = &[ read("ocs_audit", "Audit OCS document", &mcp_ops::AUDIT), read("ocs_commands", "List OCS commands", &mcp_ops::COMMANDS), read("ocs_measure", "Measure OCS entities", &mcp_ops::MEASURE), + read( + "ocs_panels", + "Inspect OCS plugin panels", + &mcp_ops::PLUGIN_PANELS, + ), IntentDescriptor { name: "ocs_render", title: "Render OCS viewport", @@ -96,6 +101,13 @@ pub static DESCRIPTORS: &[IntentDescriptor] = &[ &[], false, ), + execute( + "ocs_panel_action", + "Activate OCS panel element", + &mcp_ops::PLUGIN_PANEL_ACTION, + &[], + false, + ), execute( "ocs_cancel", "Cancel OCS command", @@ -233,11 +245,13 @@ fn operation_schema(descriptor: &IntentDescriptor) -> Value { .filter(|name| name != "op") .map(|name| { let name = name.as_str().expect("string required parameter"); - json!(descriptor - .aliases - .iter() - .find(|alias| alias.backing == name) - .map_or(name, |alias| alias.public)) + json!( + descriptor + .aliases + .iter() + .find(|alias| alias.backing == name) + .map_or(name, |alias| alias.public) + ) }) .collect(); required.dedup(); @@ -306,8 +320,8 @@ pub fn tool_definitions() -> Vec { #[cfg(test)] mod tests { - use super::{facade_arguments, find_descriptor, tool_definitions, IntentKind, DESCRIPTORS}; - use serde_json::{json, Value}; + use super::{DESCRIPTORS, IntentKind, facade_arguments, find_descriptor, tool_definitions}; + use serde_json::{Value, json}; use std::collections::HashSet; const NAMES: &[&str] = &[ @@ -317,6 +331,7 @@ mod tests { "ocs_audit", "ocs_commands", "ocs_measure", + "ocs_panels", "ocs_render", "ocs_run", "ocs_new", @@ -324,6 +339,7 @@ mod tests { "ocs_save", "ocs_save_verified", "ocs_select", + "ocs_panel_action", "ocs_cancel", "ocs_undo", "ocs_redo", @@ -457,12 +473,14 @@ mod tests { ); let schema = &generated("ocs_render")["inputSchema"]; - assert!(crate::schema_validation::validate_shape( - schema, - &json!({"layout":"Sheet1","aspect_fit":true,"renderer":"gpu"}), - "" - ) - .is_ok()); + assert!( + crate::schema_validation::validate_shape( + schema, + &json!({"layout":"Sheet1","aspect_fit":true,"renderer":"gpu"}), + "" + ) + .is_ok() + ); assert!( crate::schema_validation::validate_shape(schema, &json!({"layout":42}), "").is_err() ); @@ -487,7 +505,7 @@ mod tests { .map(|descriptor| descriptor.name) .collect(); assert_eq!(names, NAMES); - assert_eq!(names.iter().copied().collect::>().len(), 16); + assert_eq!(names.iter().copied().collect::>().len(), 18); for name in NAMES { let descriptor = find_descriptor(name).expect("descriptor lookup succeeds"); assert_eq!(descriptor.name, *name); @@ -531,7 +549,7 @@ mod tests { #[test] fn generated_schemas_expose_public_arguments_without_required_envelopes() { let tools = tool_definitions(); - assert_eq!(tools.len(), 16); + assert_eq!(tools.len(), 18); for tool in &tools { let schema = &tool["inputSchema"]; assert_eq!(schema["type"], "object"); @@ -592,18 +610,22 @@ mod tests { match descriptor.kind { IntentKind::Execute => { assert_eq!(schema["properties"]["request_id"]["type"], "string"); - assert!(schema["required"] - .as_array() - .is_none_or(|required| { !required.contains(&json!("request_id")) })); + assert!( + schema["required"] + .as_array() + .is_none_or(|required| { !required.contains(&json!("request_id")) }) + ); } IntentKind::Read | IntentKind::Capture => { assert!(schema["properties"].get("request_id").is_none()); - assert!(crate::schema_validation::validate_shape( - &schema, - &json!({"request_id":"not-an-execute-intent"}), - "" - ) - .is_err()); + assert!( + crate::schema_validation::validate_shape( + &schema, + &json!({"request_id":"not-an-execute-intent"}), + "" + ) + .is_err() + ); } } } @@ -764,10 +786,12 @@ mod tests { let properties = tool["inputSchema"]["properties"].as_object().unwrap(); assert!(properties.contains_key("name")); assert!(!properties.contains_key("search")); - assert!(tool["description"] - .as_str() - .unwrap() - .contains(r#"{"name":"LINE"}"#)); + assert!( + tool["description"] + .as_str() + .unwrap() + .contains(r#"{"name":"LINE"}"#) + ); } #[test] @@ -793,7 +817,10 @@ mod tests { assert!(render_properties.contains_key(name), "render lacks {name}"); } assert!(render_properties.contains_key("layout")); - assert_eq!(schema["properties"]["layout"], facade["properties"]["layout"]); + assert_eq!( + schema["properties"]["layout"], + facade["properties"]["layout"] + ); for (name, default) in [ ("scope", json!("viewport")), ("max_dimension", json!(1600)), @@ -812,9 +839,11 @@ mod tests { assert_eq!(facade["properties"]["view"]["default"], "current"); assert_eq!(schema["properties"]["view"]["default"], "extents"); assert_eq!(schema["additionalProperties"], false); - assert!(schema["required"] - .as_array() - .is_none_or(|required| required.is_empty())); + assert!( + schema["required"] + .as_array() + .is_none_or(|required| required.is_empty()) + ); assert_eq!(render["annotations"]["readOnlyHint"], false); assert_eq!(render["annotations"]["destructiveHint"], false); } @@ -882,10 +911,10 @@ mod tests { } #[test] - fn all_tools_keep_facades_first_and_append_sixteen_intents() { + fn all_tools_keep_facades_first_and_append_eighteen_intents() { let tools = crate::mcp::tool_definitions(); let tools = tools.as_array().unwrap(); - assert_eq!(tools.len(), 20); + assert_eq!(tools.len(), 22); let names: Vec<_> = tools .iter() .map(|tool| tool["name"].as_str().unwrap()) diff --git a/src/mcp_ops.rs b/src/mcp_ops.rs index b64ae34c92..059dae97a2 100644 --- a/src/mcp_ops.rs +++ b/src/mcp_ops.rs @@ -1,7 +1,7 @@ //! Declarative description of every MCP op. Single source of truth for the //! advertised JSON Schema, the pre-dispatch validator, and test examples. -use serde_json::{json, Map, Value}; +use serde_json::{Map, Value, json}; pub const TARGET_VERSIONS: &[&str] = &[ "R14", "2000", "2004", "2007", "2010", "2013", "2018", "AC1014", "AC1015", "AC1018", "AC1021", @@ -153,8 +153,7 @@ pub static SWITCH_DOCUMENT: OpDef = OpDef { pub static RUN: OpDef = OpDef { name: "run", - doc: - "Execute a command string with prompt answers separated by spaces (e.g. 'LINE 0,0 10,10').", + doc: "Execute a command string with prompt answers separated by spaces (e.g. 'LINE 0,0 10,10').", batchable: true, params: &[req("cmd", Ty::Str, "Command name and arguments.")], rules: &[], @@ -270,10 +269,28 @@ pub static SELECT: OpDef = OpDef { opt("handles", Ty::Handles, "Explicit entity handles to select."), opt("type", Ty::Str, "Entity type filter."), opt("layer", Ty::Str, "Layer name filter."), - opt("window", Ty::Raw(r#"{"type":"array","items":{"type":"number"},"minItems":4,"maxItems":4}"#), "World XY box [x1, y1, x2, y2]: selects what lies inside it, as a viewport window does."), - opt("crossing", Ty::Bool, "With window: also select what the box crosses."), - opt("clear", Ty::Bool, "Clear existing selection before applying."), - opt("where", Ty::ArrayOf(&Ty::Raw(r#"{"type":"object","properties":{"path":{"type":"string"},"op":{"type":"string"},"value":{}},"required":["path"]}"#)), "Property filter predicates."), + opt( + "window", + Ty::Raw(r#"{"type":"array","items":{"type":"number"},"minItems":4,"maxItems":4}"#), + "World XY box [x1, y1, x2, y2]: selects what lies inside it, as a viewport window does.", + ), + opt( + "crossing", + Ty::Bool, + "With window: also select what the box crosses.", + ), + opt( + "clear", + Ty::Bool, + "Clear existing selection before applying.", + ), + opt( + "where", + Ty::ArrayOf(&Ty::Raw( + r#"{"type":"object","properties":{"path":{"type":"string"},"op":{"type":"string"},"value":{}},"required":["path"]}"#, + )), + "Property filter predicates.", + ), ], rules: &[], example: r#"{"op":"select","clear":true}"#, @@ -300,10 +317,26 @@ pub static GRIP_DRAG: OpDef = OpDef { doc: "Drag one grip to a world point the way a grip pick-and-place in the viewport does. Built-ins: supply handle (read grips for the ids); object snaps, ortho and polar are off for the move. Plugin-declared custom grips (API v11): supply plugin (the owner id from the grips read's plugin_grips) instead of a handle — the drag routes to the owning plugin (begin, move, settle), whose settle writes are its own single undo step.", batchable: true, params: &[ - opt("handle", Ty::Handle, "Entity whose grip moves (built-in grips)."), - req("grip_id", Ty::Int, "Grip id from the grips read (entity grip id, or the plugin grip's id for custom grips)."), - req("point", Ty::Point, "World point [x, y, z] the grip moves to."), - opt("plugin", Ty::Str, "Owner plugin id when dragging a plugin-declared custom grip (from the grips read's plugin_grips); omit for built-in entity grips."), + opt( + "handle", + Ty::Handle, + "Entity whose grip moves (built-in grips).", + ), + req( + "grip_id", + Ty::Int, + "Grip id from the grips read (entity grip id, or the plugin grip's id for custom grips).", + ), + req( + "point", + Ty::Point, + "World point [x, y, z] the grip moves to.", + ), + opt( + "plugin", + Ty::Str, + "Owner plugin id when dragging a plugin-declared custom grip (from the grips read's plugin_grips); omit for built-in entity grips.", + ), ], rules: &[], example: r#"{"op":"grip_drag","plugin":"opencad.civil_ifc","grip_id":7,"point":[10,0,0]}"#, @@ -315,7 +348,11 @@ pub static CLICK: OpDef = OpDef { batchable: true, params: &[ req("point", Ty::Point, "World point [x, y, z] to click on."), - opt("modifiers", Ty::Str, "Keys held during the click: \"ctrl\", \"shift\" or \"ctrl+shift\"."), + opt( + "modifiers", + Ty::Str, + "Keys held during the click: \"ctrl\", \"shift\" or \"ctrl+shift\".", + ), ], rules: &[], example: r#"{"op":"click","point":[10,0,0],"modifiers":"ctrl"}"#, @@ -328,10 +365,16 @@ pub static POINTER: OpDef = OpDef { params: &[ req( "events", - Ty::ArrayOf(&Ty::Raw(r#"{"type":"object","properties":{"move":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":2},"move_world":{"type":"array","items":{"type":"number"},"minItems":3,"maxItems":3},"press":{"type":"string","enum":["left","right","middle"]},"release":{"type":"string","enum":["left","right","middle"]},"wheel":{"type":"number"}}}"#)), + Ty::ArrayOf(&Ty::Raw( + r#"{"type":"object","properties":{"move":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":2},"move_world":{"type":"array","items":{"type":"number"},"minItems":3,"maxItems":3},"press":{"type":"string","enum":["left","right","middle"]},"release":{"type":"string","enum":["left","right","middle"]},"wheel":{"type":"number"}}}"#, + )), "Events in order; each holds one of move, move_world, press, release, wheel (lines, positive zooms in) or leave (true: the pointer leaves the canvas).", ), - opt("modifiers", Ty::Str, "Keys held throughout: \"ctrl\", \"shift\" or \"ctrl+shift\"."), + opt( + "modifiers", + Ty::Str, + "Keys held throughout: \"ctrl\", \"shift\" or \"ctrl+shift\".", + ), ], rules: &[], example: r#"{"op":"pointer","events":[{"move_world":[10,0,0]},{"press":"left"},{"release":"left"},{"move_world":[12,3,0]},{"press":"left"},{"release":"left"}]}"#, @@ -361,6 +404,61 @@ pub static SET_PROPERTIES: OpDef = OpDef { example: r#"{"op":"set_properties","collection":"layers","name":"Walls","updates":[{"path":"/color","value":3}]}"#, }; +pub static PLUGIN_PANELS: OpDef = OpDef { + name: "plugin_panels", + doc: "Inspect the plugin panel SURFACES (api v29): the declarative scene, native widget tree/list, and typed-table tiers the host renders. Without panel_id: a bounded overview (per panel: owner and per-tier revision + element/row counts). With panel_id: one tier's detail — scene tier returns counts only; widget rows and table rows return as keyed pages (after-cursor + next continuation), never materializing more than the page.", + batchable: false, + params: &[ + opt( + "panel_id", + Ty::Str, + "One panel's surface detail instead of the overview.", + ), + opt( + "tier", + Ty::EnumCi(&["scene", "widgets", "tables"]), + "Which surface tier to read for panel_id (defaults to the panel's first published tier).", + ), + opt( + "rows", + Ty::Int, + "Page size for widget/table row pages (default 50, capped at 200).", + ), + opt( + "after", + Ty::Int, + "Keyed-page cursor: the last row id of the previous page; the next page starts strictly after it.", + ), + ], + rules: &[], + example: r#"{"op":"plugin_panels"}"#, +}; + +pub static PLUGIN_PANEL_ACTION: OpDef = OpDef { + name: "plugin_panel_action", + doc: "Activate one element of a plugin panel SURFACE (api v29) — the semantic action an agent can drive exactly like the user's gesture: `node_activated` for a widget row (a button row carries its action name to the plugin), `element_clicked` for a scene element. Delivers the owner-targeted, sequence-identified surface event the GUI path delivers; records, geometry and undo stay untouched.", + batchable: false, + params: &[ + req( + "panel_id", + Ty::Str, + "Panel id the surface is published under.", + ), + req( + "element", + Ty::Int, + "The element's stable id (StableId) as shown by the plugin_panels read.", + ), + opt( + "kind", + Ty::EnumCi(&["node_activated", "element_clicked"]), + "Defaults to node_activated when the panel has a widget surface, element_clicked otherwise.", + ), + ], + rules: &[], + example: r#"{"op":"plugin_panel_action","panel_id":"acme:tree","element":7,"kind":"node_activated"}"#, +}; + pub static PANEL_INPUT: OpDef = OpDef { name: "panel_input", doc: "Edit one native dock-panel field. Changes only the UI draft; records and geometry are not written.", @@ -368,7 +466,11 @@ pub static PANEL_INPUT: OpDef = OpDef { params: &[ req("panel_id", Ty::Str, "Registered native panel id."), req("control_id", Ty::Str, "Field id declared by that panel."), - opt("text", Ty::Str, "Exact draft text (preferred for Number fields)."), + opt( + "text", + Ty::Str, + "Exact draft text (preferred for Number fields).", + ), opt("value", Ty::Num, "Finite numeric draft converted to text."), ], rules: &[], @@ -381,7 +483,11 @@ pub static PANEL_BUTTON: OpDef = OpDef { batchable: false, params: &[ req("panel_id", Ty::Str, "Registered native panel id."), - req("control_id", Ty::Str, "Button id declared by that panel, or reset."), + req( + "control_id", + Ty::Str, + "Button id declared by that panel, or reset.", + ), ], rules: &[], example: r#"{"op":"panel_button","panel_id":"cvifc.ifc_h_properties","control_id":"apply"}"#, @@ -401,7 +507,9 @@ pub static PANEL_ACTION: OpDef = OpDef { ), opt( "value", - Ty::Raw(r#"{"oneOf":[{"type":"boolean"},{"type":"number"},{"type":"string"},{"type":"object","properties":{"index":{"type":"integer","minimum":0},"text":{"type":"string"}},"required":["index"]}]}"#), + Ty::Raw( + r#"{"oneOf":[{"type":"boolean"},{"type":"number"},{"type":"string"},{"type":"object","properties":{"index":{"type":"integer","minimum":0},"text":{"type":"string"}},"required":["index"]}]}"#, + ), "Typed draft for change: booleans, numbers, strings, or {index, text} choices. Choice text defaults to options[index] when omitted.", ), ], @@ -430,12 +538,38 @@ pub static EMBED_IMAGE: OpDef = OpDef { req("path", Ty::Str, "Path to the image file."), opt("at", Ty::Point, "Lower-left corner [x, y] or [x, y, z]."), opt("width", Ty::Num, "World width of the image."), - opt("linked", Ty::Bool, "Store as path-linked RasterImage instead of embedded OLE2FRAME."), - opt("calibrate", Ty::Raw(r#"{"type":"object","description":"Automatic 2-point reference calibration: {point_a:[px1,py1], point_b:[px2,py2], distance:650.0, align_to:[0,0]}"}"#), "Automatic 2-point reference calibration: {point_a:[px1,py1], point_b:[px2,py2], distance:650.0, align_to:[0,0]}."), - opt("layer", Ty::Str, "Layer name to place the image on (auto-created if missing, e.g. '_XREF')."), - opt("lock_layer", Ty::Bool, "Lock the target layer after attaching."), - opt("source_points", Ty::ArrayOf(&Ty::Point), "Pixel points in image [[px1,py1],[px2,py2]] for 2-point alignment."), - opt("target_points", Ty::ArrayOf(&Ty::Point), "CAD world points [[x1,y1],[x2,y2]] for 2-point alignment."), + opt( + "linked", + Ty::Bool, + "Store as path-linked RasterImage instead of embedded OLE2FRAME.", + ), + opt( + "calibrate", + Ty::Raw( + r#"{"type":"object","description":"Automatic 2-point reference calibration: {point_a:[px1,py1], point_b:[px2,py2], distance:650.0, align_to:[0,0]}"}"#, + ), + "Automatic 2-point reference calibration: {point_a:[px1,py1], point_b:[px2,py2], distance:650.0, align_to:[0,0]}.", + ), + opt( + "layer", + Ty::Str, + "Layer name to place the image on (auto-created if missing, e.g. '_XREF').", + ), + opt( + "lock_layer", + Ty::Bool, + "Lock the target layer after attaching.", + ), + opt( + "source_points", + Ty::ArrayOf(&Ty::Point), + "Pixel points in image [[px1,py1],[px2,py2]] for 2-point alignment.", + ), + opt( + "target_points", + Ty::ArrayOf(&Ty::Point), + "CAD world points [[x1,y1],[x2,y2]] for 2-point alignment.", + ), ], rules: &[], example: r#"{"op":"embed_image","path":"plan.png","linked":true,"calibrate":{"point_a":[52,910],"point_b":[450,910],"distance":6500},"layer":"_XREF","lock_layer":true}"#, @@ -447,10 +581,26 @@ pub static DGN_IMPORT: OpDef = OpDef { batchable: true, params: &[ req("path", Ty::Str, "DGN source file path."), - opt("model", Ty::Str, "Design model name (case-insensitive; omitted uses the first)."), - opt("units", Ty::EnumCi(&["Master", "Sub"]), "DGN unit conversion (Master or Sub)."), - opt("mapping", Ty::Str, "Conversion mapping; Standard, optionally with ;codepage=N."), - opt("codepage", Ty::Int, "V7 text code page; 0/1252 select the default; explicit value overrides mapping suffix."), + opt( + "model", + Ty::Str, + "Design model name (case-insensitive; omitted uses the first).", + ), + opt( + "units", + Ty::EnumCi(&["Master", "Sub"]), + "DGN unit conversion (Master or Sub).", + ), + opt( + "mapping", + Ty::Str, + "Conversion mapping; Standard, optionally with ;codepage=N.", + ), + opt( + "codepage", + Ty::Int, + "V7 text code page; 0/1252 select the default; explicit value overrides mapping suffix.", + ), ], rules: &[], example: r#"{"op":"dgn_import","path":"cadastral.dgn","model":"Default","units":"Master","mapping":"Standard","codepage":1250}"#, @@ -484,33 +634,109 @@ pub static PLOT: OpDef = OpDef { doc: "Plot layouts to a PDF or SVG file. scale (e.g. \"1:100\") overrides fit; fit defaults to true when scale is omitted.", batchable: true, params: &[ - req("path", Ty::Str, "Output PDF or SVG file path (selected by extension)."), - opt("layout", Ty::Str, "Target layout name or 'all' (defaults to 'Model')."), - opt("area", Ty::EnumCi(&["extents", "display", "limits", "layout", "window"]), "Plot area (defaults to extents)."), - opt("window", Ty::Window, "World [x0, y0, x1, y1] rectangle; required when area=window."), - opt("paper", Ty::Str, "Canonical paper size name from paper catalog."), - opt("orientation", Ty::EnumCi(&["Portrait", "Landscape"]), "Sheet orientation."), - opt("shade", Ty::EnumCi(crate::io::plot::SHADE_PLOT_MODES), "Shaded viewport plot mode."), - opt("fit", Ty::Bool, "Fit drawing to sheet (defaults to true if scale omitted)."), - opt("scale", Ty::Str, "Plot scale as paper:drawing ratio (e.g. \"1:100\")."), - opt("center", Ty::Bool, "Center plot on sheet (defaults to true)."), + req( + "path", + Ty::Str, + "Output PDF or SVG file path (selected by extension).", + ), + opt( + "layout", + Ty::Str, + "Target layout name or 'all' (defaults to 'Model').", + ), + opt( + "area", + Ty::EnumCi(&["extents", "display", "limits", "layout", "window"]), + "Plot area (defaults to extents).", + ), + opt( + "window", + Ty::Window, + "World [x0, y0, x1, y1] rectangle; required when area=window.", + ), + opt( + "paper", + Ty::Str, + "Canonical paper size name from paper catalog.", + ), + opt( + "orientation", + Ty::EnumCi(&["Portrait", "Landscape"]), + "Sheet orientation.", + ), + opt( + "shade", + Ty::EnumCi(crate::io::plot::SHADE_PLOT_MODES), + "Shaded viewport plot mode.", + ), + opt( + "fit", + Ty::Bool, + "Fit drawing to sheet (defaults to true if scale omitted).", + ), + opt( + "scale", + Ty::Str, + "Plot scale as paper:drawing ratio (e.g. \"1:100\").", + ), + opt( + "center", + Ty::Bool, + "Center plot on sheet (defaults to true).", + ), opt("offset_x", Ty::Num, "Plot offset X in mm."), opt("offset_y", Ty::Num, "Plot offset Y in mm."), opt("upside_down", Ty::Bool, "Rotate content 180 degrees."), - opt("plot_style", Ty::Str, "CTB file path or named plot style table."), + opt( + "plot_style", + Ty::Str, + "CTB file path or named plot style table.", + ), opt("transparency", Ty::Bool, "Honor transparency settings."), opt("lineweights", Ty::Bool, "Honor lineweight settings."), - opt("scale_lineweights", Ty::Bool, "Scale lineweights with a non-fit plot scale."), - opt("paperspace_last", Ty::Bool, "Plot model-space objects before paper-space objects."), - opt("apply_plot_styles", Ty::Bool, "Enable/disable the selected or requested plot style; explicit false wins."), + opt( + "scale_lineweights", + Ty::Bool, + "Scale lineweights with a non-fit plot scale.", + ), + opt( + "paperspace_last", + Ty::Bool, + "Plot model-space objects before paper-space objects.", + ), + opt( + "apply_plot_styles", + Ty::Bool, + "Enable/disable the selected or requested plot style; explicit false wins.", + ), opt("merge_lines", Ty::Bool, "Merge overlapping lines."), - opt("text_as_outlines", Ty::Bool, "SVG only: emit font-independent glyph paths instead of text elements."), - opt("layer_attributes", Ty::Bool, "SVG only: tag each drawn item with its drawing layer as data-layer groups the consumer can toggle."), - opt("non_scaling_stroke", Ty::Bool, "SVG only: keep stroke widths constant under downstream SVG transforms (web maps)."), + opt( + "text_as_outlines", + Ty::Bool, + "SVG only: emit font-independent glyph paths instead of text elements.", + ), + opt( + "layer_attributes", + Ty::Bool, + "SVG only: tag each drawn item with its drawing layer as data-layer groups the consumer can toggle.", + ), + opt( + "non_scaling_stroke", + Ty::Bool, + "SVG only: keep stroke widths constant under downstream SVG transforms (web maps).", + ), opt("stamp", Ty::Bool, "Print plot stamp."), - opt("per_page", Ty::Bool, "When layout='all', write one output file per layout as -.."), + opt( + "per_page", + Ty::Bool, + "When layout='all', write one output file per layout as -..", + ), ], - rules: &[Rule::RequiredWhen { key: "area", equals: "window", then: &["window"] }], + rules: &[Rule::RequiredWhen { + key: "area", + equals: "window", + then: &["window"], + }], example: r#"{"op":"plot","path":"out.pdf","area":"extents","scale":"1:100"}"#, }; @@ -532,12 +758,32 @@ pub static ENTITIES_SET: OpDef = OpDef { doc: "Atomically apply shared common-property writes to any number of entity handles in one undo step.", batchable: true, params: &[ - req("handles", Ty::Handles, "Non-empty unique entity handle list."), - opt("layer", Ty::Str, "Existing target layer name; omitted leaves layers unchanged."), - opt("color", Ty::Raw(COLOR_SCHEMA), "ByLayer/ByBlock, ACI 0..256, {Index:N}, {Rgb:{r,g,b}}, or {rgb:[r,g,b]}."), - opt("linetype", Ty::Str, "Existing linetype name, ByLayer, or ByBlock."), + req( + "handles", + Ty::Handles, + "Non-empty unique entity handle list.", + ), + opt( + "layer", + Ty::Str, + "Existing target layer name; omitted leaves layers unchanged.", + ), + opt( + "color", + Ty::Raw(COLOR_SCHEMA), + "ByLayer/ByBlock, ACI 0..256, {Index:N}, {Rgb:{r,g,b}}, or {rgb:[r,g,b]}.", + ), + opt( + "linetype", + Ty::Str, + "Existing linetype name, ByLayer, or ByBlock.", + ), opt("linetype_scale", Ty::Num, "Finite positive linetype scale."), - opt("invisible", Ty::Bool, "Exact visibility state (false = visible)."), + opt( + "invisible", + Ty::Bool, + "Exact visibility state (false = visible).", + ), opt("label", Ty::Str, "Optional non-empty undo-history label."), ], rules: &[ @@ -619,20 +865,48 @@ pub static TEXT_REPLACE: OpDef = OpDef { batchable: true, params: &[ opt("find", Ty::Str, "Text to find."), - opt("replace", Ty::Str, "Replacement text. Defaults to empty string (deletes the match)."), - opt("pairs", Ty::ArrayOf(&Ty::Raw( - r#"{"type":"object","properties":{"find":{"type":"string"},"replace":{"type":"string"}},"required":["find"]}"# - )), "Several find/replace pairs applied in order."), + opt( + "replace", + Ty::Str, + "Replacement text. Defaults to empty string (deletes the match).", + ), + opt( + "pairs", + Ty::ArrayOf(&Ty::Raw( + r#"{"type":"object","properties":{"find":{"type":"string"},"replace":{"type":"string"}},"required":["find"]}"#, + )), + "Several find/replace pairs applied in order.", + ), opt("match_case", Ty::Bool, "Case-sensitive search."), opt("whole_word", Ty::Bool, "Match only whole words."), - opt("ignore_accents", Ty::Bool, "Ignore accents/diacritics (defaults to true when match_case is false)."), - opt("dry_run", Ty::Bool, "Report matches without changing anything."), - opt("replace_all", Ty::Bool, "Replace all occurrences within matching entities (defaults to true)."), - opt("scope", Ty::Enum(&["all", "active_space", "model_space", "blocks"]), "Search scope."), + opt( + "ignore_accents", + Ty::Bool, + "Ignore accents/diacritics (defaults to true when match_case is false).", + ), + opt( + "dry_run", + Ty::Bool, + "Report matches without changing anything.", + ), + opt( + "replace_all", + Ty::Bool, + "Replace all occurrences within matching entities (defaults to true).", + ), + opt( + "scope", + Ty::Enum(&["all", "active_space", "model_space", "blocks"]), + "Search scope.", + ), opt("layer", Ty::Str, "Optional layer name filter."), opt("handles", Ty::Handles, "Optional handles filter."), opt("type", Ty::Str, "Optional entity type filter."), - opt("bounds", Ty::Window, "Optional bounding box filter [min_x, min_y, max_x, max_y]."), + opt( + "bounds", + Ty::Window, + "Optional bounding box filter [min_x, min_y, max_x, max_y].", + ), ], rules: &[Rule::AnyOf(&["find", "pairs"])], example: r#"{"op":"text_replace","find":"OLD","replace":"NEW"}"#, @@ -705,7 +979,9 @@ pub static PLUGIN_CALL: OpDef = OpDef { req("tool", Ty::Str, "Tool name within that plugin."), opt( "arguments", - Ty::Raw(r#"{"type":"object","description":"Tool arguments matching its input_schema"}"#), + Ty::Raw( + r#"{"type":"object","description":"Tool arguments matching its input_schema"}"#, + ), "Arguments object, checked against the tool's input_schema.", ), ], @@ -967,8 +1243,7 @@ pub static XREF_UNLOAD: OpDef = OpDef { pub static XREF_DETACH: OpDef = OpDef { name: "xref_detach", - doc: - "Detach one direct reference, its insertion, and owned dependent records in one undo step.", + doc: "Detach one direct reference, its insertion, and owned dependent records in one undo step.", batchable: true, params: &[req("id", Ty::Handle, "Direct reference id from xrefs.")], rules: &[Rule::RejectUnknown], @@ -1107,9 +1382,11 @@ pub static BATCH: OpDef = OpDef { name: "batch", doc: "Execute sequential operations with fresh state and step idempotency keys. Stops on first error.", batchable: false, - params: &[ - req("steps", Ty::BatchSteps, "List of batch steps to execute."), - ], + params: &[req( + "steps", + Ty::BatchSteps, + "List of batch steps to execute.", + )], rules: &[], example: r#"{"op":"batch","steps":[{"op":"run","cmd":"LINE 0,0 10,0"}]}"#, }; @@ -1273,12 +1550,28 @@ pub static NODE_GRAPH: OpDef = OpDef { opt( "action", Ty::EnumCi(&[ - "library", "state", "show", "hide", "add", "remove", "connect", "disconnect", - "set", "toggle", "clear", "run", "save", "load", + "library", + "state", + "show", + "hide", + "add", + "remove", + "connect", + "disconnect", + "set", + "toggle", + "clear", + "run", + "save", + "load", ]), "What to do; defaults to state.", ), - opt("type", Ty::Str, "Node type to add, as listed by action library (e.g. Line, Point, Move, Selected Objects)."), + opt( + "type", + Ty::Str, + "Node type to add, as listed by action library (e.g. Line, Point, Move, Selected Objects).", + ), opt( "kind", Ty::EnumCi(&["object", "operation"]), @@ -1290,21 +1583,71 @@ pub static NODE_GRAPH: OpDef = OpDef { Ty::Str, "Port field for set and toggle: a row (start_x), a coordinate group (start_x|start_y|start_z, value a point) or a section port (section:color, value an object of fields). toggle also takes a section title.", ), - opt("value", Ty::Raw(r#"{"description":"Any JSON value: number, text, boolean, point {x,y,z}, object {handle} or list"}"#), "Value for set."), - opt("from", Ty::Raw(r#"{"type":"object","properties":{"node":{"type":"integer","minimum":1},"field":{"type":"string"}},"required":["node","field"],"additionalProperties":false}"#), "Output port {node, field} for connect."), - opt("to", Ty::Raw(r#"{"type":"object","properties":{"node":{"type":"integer","minimum":1},"field":{"type":"string"}},"required":["node","field"],"additionalProperties":false}"#), "Input port {node, field} for connect and disconnect."), + opt( + "value", + Ty::Raw( + r#"{"description":"Any JSON value: number, text, boolean, point {x,y,z}, object {handle} or list"}"#, + ), + "Value for set.", + ), + opt( + "from", + Ty::Raw( + r#"{"type":"object","properties":{"node":{"type":"integer","minimum":1},"field":{"type":"string"}},"required":["node","field"],"additionalProperties":false}"#, + ), + "Output port {node, field} for connect.", + ), + opt( + "to", + Ty::Raw( + r#"{"type":"object","properties":{"node":{"type":"integer","minimum":1},"field":{"type":"string"}},"required":["node","field"],"additionalProperties":false}"#, + ), + "Input port {node, field} for connect and disconnect.", + ), opt("position", Ty::Point, "Canvas position of an added node."), opt("path", Ty::Str, "Absolute .ocg path for save and load."), ], rules: &[ - Rule::RequiredWhen { key: "action", equals: "add", then: &["type"] }, - Rule::RequiredWhen { key: "action", equals: "remove", then: &["node"] }, - Rule::RequiredWhen { key: "action", equals: "connect", then: &["from", "to"] }, - Rule::RequiredWhen { key: "action", equals: "disconnect", then: &["to"] }, - Rule::RequiredWhen { key: "action", equals: "set", then: &["node", "field", "value"] }, - Rule::RequiredWhen { key: "action", equals: "toggle", then: &["node", "field"] }, - Rule::RequiredWhen { key: "action", equals: "save", then: &["path"] }, - Rule::RequiredWhen { key: "action", equals: "load", then: &["path"] }, + Rule::RequiredWhen { + key: "action", + equals: "add", + then: &["type"], + }, + Rule::RequiredWhen { + key: "action", + equals: "remove", + then: &["node"], + }, + Rule::RequiredWhen { + key: "action", + equals: "connect", + then: &["from", "to"], + }, + Rule::RequiredWhen { + key: "action", + equals: "disconnect", + then: &["to"], + }, + Rule::RequiredWhen { + key: "action", + equals: "set", + then: &["node", "field", "value"], + }, + Rule::RequiredWhen { + key: "action", + equals: "toggle", + then: &["node", "field"], + }, + Rule::RequiredWhen { + key: "action", + equals: "save", + then: &["path"], + }, + Rule::RequiredWhen { + key: "action", + equals: "load", + then: &["path"], + }, ], example: r#"{"op":"node_graph","action":"add","type":"Line"}"#, }; @@ -1329,6 +1672,7 @@ pub static OPS: &[&OpDef] = &[ &PANEL_INPUT, &PANEL_BUTTON, &PANEL_ACTION, + &PLUGIN_PANEL_ACTION, &ACTION, &EMBED_IMAGE, &DGN_IMPORT, diff --git a/src/plugin/v4_support.rs b/src/plugin/v4_support.rs index 0dbbf55a04..01efafea4d 100644 --- a/src/plugin/v4_support.rs +++ b/src/plugin/v4_support.rs @@ -520,6 +520,13 @@ fn record_test_dispatch(notification: &HostNotification) { "" } ), + // API v29 (S08 equivalence): one entry per owner-targeted surface + // event; identity is the per-surface sequence, so the log keeps it. + HostNotification::PanelSurfaceEvent { + panel_id, + sequence, + event, + } => format!("PanelSurfaceEvent({panel_id}, seq {sequence}, {event:?})"), _ => "Other".to_string(), }; TEST_DISPATCH_LOG.with(|log| log.borrow_mut().push(kind));