Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
chore(cua-driver): establish deterministic rustfmt baseline (#2327)
Francesco Bonacciccf301304e38
diff --git a/.github/workflows/ci-rust-format.yml b/.github/workflows/ci-rust-format.ymlnew file mode 100644index 0000000000..987485ca66--- /dev/null+++ b/.github/workflows/ci-rust-format.yml@@ -0,0 +1,39 @@+name: "CI: Rust format"++on:+ pull_request:+ paths:+ - "libs/cua-driver/rust/**"+ - ".github/workflows/ci-rust-format.yml"+ push:+ branches: [main]+ paths:+ - "libs/cua-driver/rust/**"+ - ".github/workflows/ci-rust-format.yml"+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: ci-rust-format-${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: true++jobs:+ format:+ name: Rustfmt (${{ matrix.os }})+ strategy:+ fail-fast: false+ matrix:+ os: [ubuntu-latest, macos-latest, windows-latest]+ runs-on: ${{ matrix.os }}+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4+ - name: Install pinned Rust toolchain+ uses: dtolnay/[email protected]+ with:+ components: rustfmt+ - name: Check Rust formatting+ working-directory: libs/cua-driver/rust+ run: cargo fmt --all -- --checkdiff --git a/libs/cua-driver/rust/README.md b/libs/cua-driver/rust/README.mdindex 8cb4f69444..be6cf795f0 100644--- a/libs/cua-driver/rust/README.md+++ b/libs/cua-driver/rust/README.md@@ -31,6 +31,22 @@ The Python wrapper and install scripts expect the built binary at`target/<profile>/cua-driver` (or `cua-driver.exe` on Windows), unless`CUA_DRIVER_BINARY` is set.+## Formatting++The supported Rust toolchain and `rustfmt` component are pinned in+`rust-toolchain.toml`. Install [rustup](https://rustup.rs/) and run the+canonical formatting check from this directory:++```bash+cargo fmt --all -- --check+```++To apply formatting, omit `--check`:++```bash+cargo fmt --all+```+## TestsDefault tests should be headless and safe for CI:diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/capture_scope.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/capture_scope.rsindex 860eb0523f..e6e05d0061 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/capture_scope.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/capture_scope.rs@@ -263,8 +263,7 @@ fn tool_scope(tool_name: &str, args: &Value) -> ToolScope {| "screenshot_compat"| "zoom"| "page"- )- || tool_name == "get_browser_state"+ ) || tool_name == "get_browser_state"|| (tool_name.starts_with("browser_")&& !matches!(tool_name, "browser_prepare" | "browser_download")){diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/cdp.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/cdp.rsindex 269438e224..e0f724d688 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/cdp.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/cdp.rs@@ -28,11 +28,7 @@ fn legacy_pool() -> &'static CdpPool {/// Returns the formatted result (or `exception: ...` if the evaluated code/// raised). Caller is responsible for prefixing the human-readable label/// (e.g. `"cdp.runtime.evaluate.user_gesture: ..."`).-pub async fn evaluate(- port: u16,- expression: &str,- await_promise: bool,-) -> anyhow::Result<String> {+pub async fn evaluate(port: u16, expression: &str, await_promise: bool) -> anyhow::Result<String> {evaluate_targeted(port, expression, await_promise, None).await}@@ -59,20 +55,16 @@ async fn cdp_evaluate() -> anyhow::Result<Value> {// A listener can be reachable before Chromium publishes its first page// target. Bound both that readiness interval and the HTTP roundtrip.- let pages = tokio::time::timeout(- std::time::Duration::from_secs(10),- cdp_wait_for_page(port),- )- .await- .map_err(|_| anyhow::anyhow!("CDP /json discovery on port {port} timed out after 10 s"))??;-- let page = pick_page(&pages, target_url_contains)- .ok_or_else(|| match target_url_contains {- Some(hint) => anyhow::anyhow!(- "No unique CDP page URL contains {hint:?} on port {port}"- ),- None => anyhow::anyhow!("No CDP page tabs found on port {port}"),- })?;+ let pages = tokio::time::timeout(std::time::Duration::from_secs(10), cdp_wait_for_page(port))+ .await+ .map_err(|_| {+ anyhow::anyhow!("CDP /json discovery on port {port} timed out after 10 s")+ })??;++ let page = pick_page(&pages, target_url_contains).ok_or_else(|| match target_url_contains {+ Some(hint) => anyhow::anyhow!("No unique CDP page URL contains {hint:?} on port {port}"),+ None => anyhow::anyhow!("No CDP page tabs found on port {port}"),+ })?;let ws_url = page.get("webSocketDebuggerUrl").and_then(|u| u.as_str())@@ -166,9 +158,7 @@ async fn cdp_list_pages(port: u16) -> anyhow::Result<Vec<Value>> {// forever. Parse Content-Length / Transfer-Encoding: chunked from the// response headers and read exactly that many body bytes, leaving the// socket open (it's torn down when we drop the stream).- let req = format!(- "GET /json HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n"- );+ let req = format!("GET /json HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n");stream.write_all(req.as_bytes()).await?;let mut reader = BufReader::new(stream);@@ -178,8 +168,12 @@ async fn cdp_list_pages(port: u16) -> anyhow::Result<Vec<Value>> {loop {header_line.clear();let n = reader.read_line(&mut header_line).await?;- if n == 0 { anyhow::bail!("CDP /json: EOF in headers"); }- if header_line == "\r\n" { break; }+ if n == 0 {+ anyhow::bail!("CDP /json: EOF in headers");+ }+ if header_line == "\r\n" {+ break;+ }let lower = header_line.to_ascii_lowercase();if let Some(v) = lower.strip_prefix("content-length:") {content_length = v.trim().parse::<usize>().ok();@@ -200,7 +194,9 @@ async fn cdp_list_pages(port: u16) -> anyhow::Result<Vec<Value>> {reader.read_line(&mut size_line).await?;let size = usize::from_str_radix(size_line.trim_end(), 16).map_err(|_| anyhow::anyhow!("CDP /json: bad chunk size {size_line:?}"))?;- if size == 0 { break; }+ if size == 0 {+ break;+ }let mut chunk = vec![0u8; size];reader.read_exact(&mut chunk).await?;out.extend_from_slice(&chunk);@@ -220,8 +216,8 @@ async fn cdp_list_pages(port: u16) -> anyhow::Result<Vec<Value>> {let body = std::str::from_utf8(&body_bytes).map_err(|_| anyhow::anyhow!("CDP /json response is not valid UTF-8"))?;- let all: Value = serde_json::from_str(body)- .map_err(|e| anyhow::anyhow!("CDP /json parse error: {e}"))?;+ let all: Value =+ serde_json::from_str(body).map_err(|e| anyhow::anyhow!("CDP /json parse error: {e}"))?;let pages = all.as_array()@@ -270,8 +266,7 @@ mod tests {fn omitted_page_hint_preserves_first_page_behavior() {let pages = pages();assert_eq!(- pick_page(&pages, None)- .and_then(|page| page["webSocketDebuggerUrl"].as_str()),+ pick_page(&pages, None).and_then(|page| page["webSocketDebuggerUrl"].as_str()),Some("ws://a"));}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/cursor_sampler.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/cursor_sampler.rsindex 19cc4c2534..8e3001d218 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/cursor_sampler.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/cursor_sampler.rs@@ -52,9 +52,11 @@ impl CursorSampler {// Write one JSON object per line. We hand-format// the trivial shape rather than pulling serde_json// into the hot loop — keeps wakeup-cost bounded.- let _ = writeln!(writer,+ let _ = writeln!(+ writer,"{{\"t_ms\":{:.3},\"x\":{:.2},\"y\":{:.2}}}",- t_ms, x, y);+ t_ms, x, y+ );count += 1;}std::thread::sleep(interval);@@ -73,12 +75,12 @@ impl CursorSampler {/// Stop the sampler. Returns the number of samples written.pub fn stop(mut self) -> usize {self.stop_flag.store(true, Ordering::Relaxed);- self.handle.take()- .and_then(|h| h.join().ok())- .unwrap_or(0)+ self.handle.take().and_then(|h| h.join().ok()).unwrap_or(0)}- pub fn output_path(&self) -> &std::path::Path { &self.output_path }+ pub fn output_path(&self) -> &std::path::Path {+ &self.output_path+ }}impl Drop for CursorSampler {@@ -119,11 +121,16 @@ fn sample_cursor() -> Option<(f64, f64)> {}#[repr(C)]#[derive(Copy, Clone)]- struct CGPoint { x: f64, y: f64 }+ struct CGPoint {+ x: f64,+ y: f64,+ }unsafe {let event = CGEventCreate(std::ptr::null_mut());- if event.is_null() { return None; }+ if event.is_null() {+ return None;+ }let p = CGEventGetLocation(event);CFRelease(event);Some((p.x, p.y))@@ -144,4 +151,6 @@ fn sample_cursor() -> Option<(f64, f64)> {}#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]-fn sample_cursor() -> Option<(f64, f64)> { None }+fn sample_cursor() -> Option<(f64, f64)> {+ None+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/element_cache.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/element_cache.rsindex 4b557227fd..ce8b6c9805 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/element_cache.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/element_cache.rs@@ -49,7 +49,9 @@ pub struct ElementCacheCore<K: Eq + Hash, S> {impl<K: Eq + Hash, S> ElementCacheCore<K, S> {pub fn new() -> Self {- Self { inner: Mutex::new(HashMap::new()) }+ Self {+ inner: Mutex::new(HashMap::new()),+ }}/// Replace the snapshot for `key`. If an entry already existed@@ -99,8 +101,16 @@ mod tests {#[test]fn insert_then_get_returns_projection() {let cache: ElementCacheCore<TestKey, TestSnapshot> = ElementCacheCore::new();- let key = TestKey { pid: 42, window_id: 7 };- cache.insert(key, TestSnapshot { elements: vec![10, 20, 30] });+ let key = TestKey {+ pid: 42,+ window_id: 7,+ };+ cache.insert(+ key,+ TestSnapshot {+ elements: vec![10, 20, 30],+ },+ );let third = cache.with_snapshot(&key, |s| s.elements.get(2).copied());assert_eq!(third, Some(Some(30)));@@ -109,7 +119,10 @@ mod tests {#[test]fn miss_returns_none() {let cache: ElementCacheCore<TestKey, TestSnapshot> = ElementCacheCore::new();- let key = TestKey { pid: 1, window_id: 1 };+ let key = TestKey {+ pid: 1,+ window_id: 1,+ };let v = cache.with_snapshot(&key, |s| s.elements.len());assert_eq!(v, None);}@@ -117,12 +130,20 @@ mod tests {#[test]fn count_via_with_snapshot() {let cache: ElementCacheCore<TestKey, TestSnapshot> = ElementCacheCore::new();- let key = TestKey { pid: 9, window_id: 99 };+ let key = TestKey {+ pid: 9,+ window_id: 99,+ };// Before insert: None.assert_eq!(cache.with_snapshot(&key, |s| s.elements.len()), None);- cache.insert(key, TestSnapshot { elements: vec![1, 2, 3, 4, 5] });+ cache.insert(+ key,+ TestSnapshot {+ elements: vec![1, 2, 3, 4, 5],+ },+ );assert_eq!(cache.with_snapshot(&key, |s| s.elements.len()), Some(5));}@@ -147,14 +168,32 @@ mod tests {let drops = Arc::new(AtomicUsize::new(0));let cache: ElementCacheCore<u32, DropCounter> = ElementCacheCore::new();- cache.insert(1, DropCounter { counter: drops.clone() });+ cache.insert(+ 1,+ DropCounter {+ counter: drops.clone(),+ },+ );assert_eq!(drops.load(Ordering::SeqCst), 0);- cache.insert(1, DropCounter { counter: drops.clone() });- assert_eq!(drops.load(Ordering::SeqCst), 1, "replacement should drop the prior snapshot");+ cache.insert(+ 1,+ DropCounter {+ counter: drops.clone(),+ },+ );+ assert_eq!(+ drops.load(Ordering::SeqCst),+ 1,+ "replacement should drop the prior snapshot"+ );cache.remove(&1);- assert_eq!(drops.load(Ordering::SeqCst), 2, "remove should drop the snapshot");+ assert_eq!(+ drops.load(Ordering::SeqCst),+ 2,+ "remove should drop the snapshot"+ );}#[test]diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/element_token.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/element_token.rsindex f22223f951..062caff68f 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/element_token.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/element_token.rs@@ -51,9 +51,9 @@//! it won't in practice — u32 wraps after 4 billion calls).use std::collections::HashMap;+use std::sync::atomic::{AtomicU32, Ordering};use std::sync::Mutex;use std::sync::OnceLock;-use std::sync::atomic::{AtomicU32, Ordering};/// LRU cap of valid snapshots retained per pid. Past this point the/// oldest entry for the pid is evicted and its tokens go stale.@@ -98,7 +98,9 @@ pub struct TokenRegistry {impl TokenRegistry {fn new() -> Self {- Self { by_pid: Mutex::new(HashMap::new()) }+ Self {+ by_pid: Mutex::new(HashMap::new()),+ }}/// Record a fresh snapshot for `pid` / `window_id`. Returns the@@ -113,12 +115,7 @@ impl TokenRegistry {/// Side effect: if this pid already has [`LRU_CAP_PER_PID`] snapshots/// in its lane, the oldest is evicted and any token that referenced/// it becomes stale — that's the contract.- pub fn register_snapshot(- &self,- pid: i32,- window_id: u32,- element_count: usize,- ) -> u32 {+ pub fn register_snapshot(&self, pid: i32, window_id: u32, element_count: usize) -> u32 {// Truncate to the 16-bit space the token format actually// surfaces. The full u32 still increments monotonically — we// just don't widen the on-the-wire token namespace beyond what@@ -153,10 +150,11 @@ impl TokenRegistry {/// - `"element_token element_index out of range"` — the index in/// the token is past the max recorded for the snapshot.pub fn resolve(&self, pid: i32, token: &str) -> Result<(u32, usize), String> {- let (sid, idx) = parse_token(token)- .ok_or_else(|| "element_token has invalid format".to_string())?;+ let (sid, idx) =+ parse_token(token).ok_or_else(|| "element_token has invalid format".to_string())?;let by_pid = self.by_pid.lock().unwrap();- let lane = by_pid.get(&pid)+ let lane = by_pid+ .get(&pid).ok_or_else(|| STALE_TOKEN_ERROR.to_string())?;let entry = lane.iter()@@ -183,7 +181,12 @@ impl TokenRegistry {/// unit test to assert the cap was honoured.#[cfg(test)]fn snapshot_count(&self, pid: i32) -> usize {- self.by_pid.lock().unwrap().get(&pid).map(|v| v.len()).unwrap_or(0)+ self.by_pid+ .lock()+ .unwrap()+ .get(&pid)+ .map(|v| v.len())+ .unwrap_or(0)}/// Test-only: clear all state. Lets parallel unit tests start clean@@ -454,7 +457,9 @@ mod tests {let s1 = reg.register_snapshot(pid, 1, 5);let s2 = reg.register_snapshot(pid, 1, 5);// Both should still resolve.- let _ = reg.resolve(pid, &format_token(s1, 0)).expect("s1 still in LRU");+ let _ = reg+ .resolve(pid, &format_token(s1, 0))+ .expect("s1 still in LRU");let _ = reg.resolve(pid, &format_token(s2, 0)).expect("s2 fresh");}@@ -552,10 +557,17 @@ mod tests {).expect("element_index-only must succeed");match resolved {- ResolvedElement::Element { window_id, element_index, via_token } => {+ ResolvedElement::Element {+ window_id,+ element_index,+ via_token,+ } => {assert_eq!(window_id, Some(99));assert_eq!(element_index, 7);- assert!(!via_token, "element_index-only path must NOT report via_token");+ assert!(+ !via_token,+ "element_index-only path must NOT report via_token"+ );}_ => panic!("expected Element, got {resolved:?}"),}@@ -581,7 +593,11 @@ mod tests {).expect("token-only must succeed");match resolved {- ResolvedElement::Element { window_id, element_index, via_token } => {+ ResolvedElement::Element {+ window_id,+ element_index,+ via_token,+ } => {assert_eq!(window_id, Some(555), "window_id comes from the snapshot");assert_eq!(element_index, 2);assert!(via_token, "token path must report via_token=true");@@ -609,7 +625,11 @@ mod tests {).expect("disagreement still resolves; token wins");match resolved {- ResolvedElement::Element { window_id, element_index, via_token } => {+ ResolvedElement::Element {+ window_id,+ element_index,+ via_token,+ } => {assert_eq!(window_id, Some(777));assert_eq!(element_index, 3, "token's idx wins over the integer arg");assert!(via_token);@@ -625,14 +645,7 @@ mod tests {let pid = 0x7fff_0003_i32;// Token references a snapshot that was never registered → stale.let token = format_token(0xdead, 0);- let err = resolve_element_args(- pid,- Some(0),- Some(&token),- Some(1),- "click",- )- .unwrap_err();+ let err = resolve_element_args(pid, Some(0), Some(&token), Some(1), "click").unwrap_err();// ToolResult::error wraps the message in a Content::Text — the// assertion uses the protocol-level error_text accessor.assert!(diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/ffmpeg_install.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/ffmpeg_install.rsindex c02646973b..b1431fdb5c 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/ffmpeg_install.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/ffmpeg_install.rs@@ -57,7 +57,10 @@ pub fn install_plan() -> Option<InstallPlan> {("apt-get", &["apt-get", "install", "-y", "ffmpeg"]),("dnf", &["dnf", "install", "-y", "ffmpeg"]),("yum", &["yum", "install", "-y", "ffmpeg"]),- ("zypper", &["zypper", "--non-interactive", "install", "ffmpeg"]),+ (+ "zypper",+ &["zypper", "--non-interactive", "install", "ffmpeg"],+ ),("pacman", &["pacman", "-S", "--noconfirm", "ffmpeg"]),("apk", &["apk", "add", "ffmpeg"]),("snap", &["snap", "install", "ffmpeg"]),@@ -98,8 +101,13 @@ pub fn install_plan() -> Option<InstallPlan> {return Some(InstallPlan {manager: "winget".into(),argv: [- "winget", "install", "-e", "--id", "Gyan.FFmpeg",- "--accept-package-agreements", "--accept-source-agreements",+ "winget",+ "install",+ "-e",+ "--id",+ "Gyan.FFmpeg",+ "--accept-package-agreements",+ "--accept-source-agreements",].iter().map(|s| (*s).to_string())diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/health_report.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/health_report.rsindex 634248a35e..761bc1ad1d 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/health_report.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/health_report.rs@@ -58,7 +58,11 @@ pub const NAME_SCREEN_CAPTURE_CAPABILITY: &str = "screen_capture_capability";/// apply on a platform simply isn't present in that platform's `names`/// vector, so the overall rollup ignores it.pub fn core_check_names() -> &'static [&'static str] {- &[NAME_BINARY_VERSION, NAME_PLATFORM_SUPPORTED, NAME_SESSION_ACTIVE]+ &[+ NAME_BINARY_VERSION,+ NAME_PLATFORM_SUPPORTED,+ NAME_SESSION_ACTIVE,+ ]}// ── Output model ─────────────────────────────────────────────────────────────diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/image_utils.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/image_utils.rsindex 3d141ae90f..d50ce437a5 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/image_utils.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/image_utils.rs@@ -106,8 +106,11 @@ pub fn write_crosshair_png(png_bytes: &[u8], cx: f64, cy: f64, path: &str) -> Relet path = if let Some(rest) = path.strip_prefix('~') {let home = std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE"))- .map_err(|_| anyhow::anyhow!(- "Cannot expand `~` in path {path:?}: neither HOME nor USERPROFILE is set"))?;+ .map_err(|_| {+ anyhow::anyhow!(+ "Cannot expand `~` in path {path:?}: neither HOME nor USERPROFILE is set"+ )+ })?;if home.is_empty() {anyhow::bail!("Cannot expand `~` in path {path:?}: HOME/USERPROFILE is empty");}@@ -246,11 +249,11 @@ pub fn encode_rgba_to_png(rgba: &[u8], w: u32, h: u32) -> Result<Vec<u8>> {rgba.len());}- let buf: ImageBuffer<image::Rgba<u8>, Vec<u8>> =- ImageBuffer::from_raw(w, h, rgba.to_vec())- .ok_or_else(|| anyhow!("invalid RGBA buffer for w={w} h={h}"))?;+ let buf: ImageBuffer<image::Rgba<u8>, Vec<u8>> = ImageBuffer::from_raw(w, h, rgba.to_vec())+ .ok_or_else(|| anyhow!("invalid RGBA buffer for w={w} h={h}"))?;let mut out = Vec::new();- DynamicImage::ImageRgba8(buf).write_to(&mut std::io::Cursor::new(&mut out), ImageFormat::Png)?;+ DynamicImage::ImageRgba8(buf)+ .write_to(&mut std::io::Cursor::new(&mut out), ImageFormat::Png)?;Ok(out)}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rsindex e28bc9888e..95e6c544a6 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs@@ -36,6 +36,7 @@ pub mod browser;pub mod capture_mode;pub mod capture_scope;pub mod cdp;+pub mod cursor_sampler;pub mod element_cache;pub mod element_token;pub mod ffmpeg_install;@@ -45,7 +46,6 @@ pub mod page;pub mod pip_hook;pub mod policy;pub mod protocol;-pub mod cursor_sampler;pub mod recording;pub mod recording_loader;pub mod recording_render;@@ -57,8 +57,8 @@ pub mod session_tools;pub mod socket_io;pub mod text_sanitize;pub mod tool;-pub mod tool_schema;pub mod tool_args;+pub mod tool_schema;pub mod video;pub mod video_ffmpeg;diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/page.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/page.rsindex 9944b40aa9..f9fdd0c498 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/page.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/page.rs@@ -401,17 +401,10 @@ impl Tool for PageTool {Ok(value) => value,Err(error) => return ToolResult::error(error),};- let target_url_contains =- args.get("target_url_contains").and_then(|v| v.as_str());+ let target_url_contains = args.get("target_url_contains").and_then(|v| v.as_str());match self.backend- .execute_javascript_targeted(- pid,- window_id,- &js,- cdp_port,- target_url_contains,- )+ .execute_javascript_targeted(pid, window_id, &js, cdp_port, target_url_contains).await{Ok(result) => ToolResult::text(result),@@ -429,16 +422,13 @@ impl Tool for PageTool {// fail fast at the input boundary rather than blowing up// inside the backend's JS payload (`querySelector(" ")`// returns null and the error there is much less specific).- let selector = match args- .get("selector")- .and_then(|v| v.as_str())- .map(str::trim)- {- Some(s) if !s.is_empty() => s.to_owned(),- _ => return ToolResult::error(- "Missing required parameter: selector (CSS selector for click_element)"- ),- };+ let selector =+ match args.get("selector").and_then(|v| v.as_str()).map(str::trim) {+ Some(s) if !s.is_empty() => s.to_owned(),+ _ => return ToolResult::error(+ "Missing required parameter: selector (CSS selector for click_element)",+ ),+ };match self.backend.click_element(pid, window_id, &selector).await {Ok(res) => {let structured = serde_json::json!({@@ -464,7 +454,11 @@ impl Tool for PageTool {Err(error) => return ToolResult::error(error),};let target_url_contains = args.get("target_url_contains").and_then(|v| v.as_str());- match self.backend.insert_text(pid, window_id, &text, cdp_port, target_url_contains).await {+ match self+ .backend+ .insert_text(pid, window_id, &text, cdp_port, target_url_contains)+ .await+ {Ok(msg) => ToolResult::text(msg),Err(e) => ToolResult::error(format!("insert_text failed: {e}")),}@@ -480,7 +474,11 @@ impl Tool for PageTool {Err(error) => return ToolResult::error(error),};let target_url_contains = args.get("target_url_contains").and_then(|v| v.as_str());- match self.backend.type_keystrokes(pid, window_id, &text, cdp_port, target_url_contains).await {+ match self+ .backend+ .type_keystrokes(pid, window_id, &text, cdp_port, target_url_contains)+ .await+ {Ok(msg) => ToolResult::text(msg),Err(e) => ToolResult::error(format!("type_keystrokes failed: {e}")),}@@ -520,9 +518,9 @@ fn optional_cdp_port(args: &Value) -> Result<Option<u16>, String> {let Some(value) = args.get("cdp_port") else {return Ok(None);};- let raw = value- .as_u64()- .ok_or_else(|| "Invalid parameter: cdp_port must be an integer from 1 to 65535".to_owned())?;+ let raw = value.as_u64().ok_or_else(|| {+ "Invalid parameter: cdp_port must be an integer from 1 to 65535".to_owned()+ })?;let port = u16::try_from(raw).ok().filter(|port| *port > 0)diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rsindex 773dbb3677..4badd6ecab 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rs@@ -22,7 +22,10 @@ impl Request {}pub fn tool_call(&self) -> anyhow::Result<ToolCall> {- let params = self.params.as_ref().ok_or_else(|| anyhow::anyhow!("missing params"))?;+ let params = self+ .params+ .as_ref()+ .ok_or_else(|| anyhow::anyhow!("missing params"))?;let name = params.get("name").and_then(|v| v.as_str())@@ -167,11 +170,7 @@ fn capability_declared(capabilities: Option<&Value>, name: &str) -> bool {.is_some_and(|caps| caps.contains_key(name))}-fn nested_capability_declared(- capabilities: Option<&Value>,- parent: &str,- child: &str,-) -> bool {+fn nested_capability_declared(capabilities: Option<&Value>, parent: &str, child: &str) -> bool {capabilities.and_then(|v| v.get(parent)).and_then(Value::as_object)@@ -208,14 +207,23 @@ pub struct RpcError {impl Response {pub fn ok(id: Value, result: Value) -> Self {- Self { jsonrpc: "2.0", id, body: ResponseBody::Result { result } }+ Self {+ jsonrpc: "2.0",+ id,+ body: ResponseBody::Result { result },+ }}pub fn error(id: Value, code: i64, message: impl Into<String>) -> Self {Self {jsonrpc: "2.0",id,- body: ResponseBody::Error { error: RpcError { code, message: message.into() } },+ body: ResponseBody::Error {+ error: RpcError {+ code,+ message: message.into(),+ },+ },}}@@ -240,7 +248,7 @@ pub enum Content {annotations: Option<Value>,},Image {- data: String, // base64-encoded PNG+ data: String, // base64-encoded PNG#[serde(rename = "mimeType")]mime_type: String,#[serde(skip_serializing_if = "Option::is_none")]@@ -250,15 +258,26 @@ pub enum Content {impl Content {pub fn text(text: impl Into<String>) -> Self {- Content::Text { text: text.into(), annotations: None }+ Content::Text {+ text: text.into(),+ annotations: None,+ }}pub fn image_png(data_base64: String) -> Self {- Content::Image { data: data_base64, mime_type: "image/png".into(), annotations: None }+ Content::Image {+ data: data_base64,+ mime_type: "image/png".into(),+ annotations: None,+ }}pub fn image_jpeg(data_base64: String) -> Self {- Content::Image { data: data_base64, mime_type: "image/jpeg".into(), annotations: None }+ Content::Image {+ data: data_base64,+ mime_type: "image/jpeg".into(),+ annotations: None,+ }}}@@ -274,11 +293,18 @@ pub struct ToolResult {impl ToolResult {pub fn text(msg: impl Into<String>) -> Self {- Self { content: vec![Content::text(msg)], ..Default::default() }+ Self {+ content: vec![Content::text(msg)],+ ..Default::default()+ }}pub fn error(msg: impl Into<String>) -> Self {- Self { content: vec![Content::text(msg)], is_error: Some(true), ..Default::default() }+ Self {+ content: vec![Content::text(msg)],+ is_error: Some(true),+ ..Default::default()+ }}pub fn with_structured(mut self, v: Value) -> Self {@@ -359,7 +385,10 @@ mod image_mime_type_tests {let c = Content::image_png("ZmFrZQ==".into());let v = serde_json::to_value(&c).expect("serialize");assert_eq!(v.get("type").and_then(|t| t.as_str()), Some("image"));- assert_eq!(v.get("mimeType").and_then(|t| t.as_str()), Some("image/png"));+ assert_eq!(+ v.get("mimeType").and_then(|t| t.as_str()),+ Some("image/png")+ );assert_eq!(v.get("data").and_then(|t| t.as_str()), Some("ZmFrZQ=="));}@@ -368,7 +397,10 @@ mod image_mime_type_tests {let c = Content::image_jpeg("ZmFrZQ==".into());let v = serde_json::to_value(&c).expect("serialize");assert_eq!(v.get("type").and_then(|t| t.as_str()), Some("image"));- assert_eq!(v.get("mimeType").and_then(|t| t.as_str()), Some("image/jpeg"));+ assert_eq!(+ v.get("mimeType").and_then(|t| t.as_str()),+ Some("image/jpeg")+ );}/// Text parts must not grow a mimeType field — the field belongs to@@ -379,7 +411,10 @@ mod image_mime_type_tests {let c = Content::text("hi");let v = serde_json::to_value(&c).expect("serialize");assert_eq!(v.get("type").and_then(|t| t.as_str()), Some("text"));- assert!(v.get("mimeType").is_none(), "text content must not carry mimeType");+ assert!(+ v.get("mimeType").is_none(),+ "text content must not carry mimeType"+ );}}@@ -443,7 +478,10 @@ mod initialize_metadata_tests {let debug = format!("{metadata:?}");for forbidden in ["secret", "prompt", "task", "arbitrary", "payload"] {- assert!(!debug.contains(forbidden), "metadata leaked {forbidden}: {debug}");+ assert!(+ !debug.contains(forbidden),+ "metadata leaked {forbidden}: {debug}"+ );}}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/recording_loader.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/recording_loader.rsindex 59ada94f73..75dbefaf33 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/recording_loader.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/recording_loader.rs@@ -69,7 +69,12 @@ pub fn load(dir: &Path) -> Result<LoadedTrajectory, LoadError> {let clicks = load_clicks(dir);let action_spans = load_action_spans(dir);- Ok(LoadedTrajectory { metadata, clicks, cursor_samples, action_spans })+ Ok(LoadedTrajectory {+ metadata,+ clicks,+ cursor_samples,+ action_spans,+ })}// ── session.json ─────────────────────────────────────────────────────────────@@ -101,12 +106,14 @@ fn load_session_metadata(}}- let cursor_sample_count = v.get("cursor")+ let cursor_sample_count = v+ .get("cursor").and_then(|c| c.get("sample_count")).and_then(|x| x.as_u64()).unwrap_or(0) as usize;- let display_scale_factor = v.get("display_scale_factor")+ let display_scale_factor = v+ .get("display_scale_factor").and_then(|x| x.as_f64()).unwrap_or(1.0);@@ -127,14 +134,22 @@ fn probe_video_dimensions(video_path: &Path) -> Option<(u32, u32)> {use std::process::Command;let ffprobe = crate::video_ffmpeg::find_ffprobe()?;let out = Command::new(ffprobe)- .args(["-v", "error",- "-select_streams", "v:0",- "-show_entries", "stream=width,height",- "-of", "csv=p=0:s=x"])+ .args([+ "-v",+ "error",+ "-select_streams",+ "v:0",+ "-show_entries",+ "stream=width,height",+ "-of",+ "csv=p=0:s=x",+ ]).arg(video_path).output().ok()?;- if !out.status.success() { return None; }+ if !out.status.success() {+ return None;+ }let s = String::from_utf8_lossy(&out.stdout);let trimmed = s.trim();let mut parts = trimmed.split('x');@@ -146,7 +161,9 @@ fn probe_video_dimensions(video_path: &Path) -> Option<(u32, u32)> {// ── cursor.jsonl ─────────────────────────────────────────────────────────────fn load_cursor_samples(path: &Path) -> Vec<CursorSample> {- if !path.exists() { return Vec::new(); }+ if !path.exists() {+ return Vec::new();+ }let text = match std::fs::read_to_string(path) {Ok(t) => t,Err(_) => return Vec::new(),@@ -154,14 +171,29 @@ fn load_cursor_samples(path: &Path) -> Vec<CursorSample> {let mut out: Vec<CursorSample> = Vec::with_capacity(text.len() / 48);for line in text.lines() {let line = line.trim();- if line.is_empty() { continue; }- let v: Value = match serde_json::from_str(line) { Ok(v) => v, Err(_) => continue };+ if line.is_empty() {+ continue;+ }+ let v: Value = match serde_json::from_str(line) {+ Ok(v) => v,+ Err(_) => continue,+ };let t_ms = double_value(v.get("t_ms")).unwrap_or(0.0);- let x = match double_value(v.get("x")) { Some(x) => x, None => continue };- let y = match double_value(v.get("y")) { Some(y) => y, None => continue };+ let x = match double_value(v.get("x")) {+ Some(x) => x,+ None => continue,+ };+ let y = match double_value(v.get("y")) {+ Some(y) => y,+ None => continue,+ };out.push(CursorSample { t_ms, x, y });}- out.sort_by(|a, b| a.t_ms.partial_cmp(&b.t_ms).unwrap_or(std::cmp::Ordering::Equal));+ out.sort_by(|a, b| {+ a.t_ms+ .partial_cmp(&b.t_ms)+ .unwrap_or(std::cmp::Ordering::Equal)+ });out}@@ -169,19 +201,30 @@ fn load_cursor_samples(path: &Path) -> Vec<CursorSample> {fn load_clicks(dir: &Path) -> Vec<ClickEvent> {let mut out = Vec::new();- let entries = match std::fs::read_dir(dir) { Ok(e) => e, Err(_) => return out };+ let entries = match std::fs::read_dir(dir) {+ Ok(e) => e,+ Err(_) => return out,+ };for entry in entries.flatten() {let name = entry.file_name();let name_s = name.to_string_lossy();- if !name_s.starts_with("turn-") { continue; }+ if !name_s.starts_with("turn-") {+ continue;+ }let path = entry.path();- if !path.is_dir() { continue; }+ if !path.is_dir() {+ continue;+ }let action_path = path.join("action.json");if let Some(c) = parse_click_turn(&action_path) {out.push(c);}}- out.sort_by(|a, b| a.t_ms.partial_cmp(&b.t_ms).unwrap_or(std::cmp::Ordering::Equal));+ out.sort_by(|a, b| {+ a.t_ms+ .partial_cmp(&b.t_ms)+ .unwrap_or(std::cmp::Ordering::Equal)+ });out}@@ -189,7 +232,9 @@ fn parse_click_turn(action_path: &Path) -> Option<ClickEvent> {let text = std::fs::read_to_string(action_path).ok()?;let v: Value = serde_json::from_str(&text).ok()?;let tool = v.get("tool")?.as_str()?;- if !is_click_class_tool(tool) { return None; }+ if !is_click_class_tool(tool) {+ return None;+ }// Coordinate recovery, in priority order:// 1. `arguments.{x,y}` — pixel-addressed clicks pass coords directly.@@ -208,7 +253,9 @@ fn parse_click_turn(action_path: &Path) -> Option<ClickEvent> {} else if let Some(cp) = v.get("click_point") {(double_value(cp.get("x"))?, double_value(cp.get("y"))?)} else if let Some(screen) = parse_screen_from_summary(- v.get("result_summary").and_then(|s| s.as_str()).unwrap_or("")+ v.get("result_summary")+ .and_then(|s| s.as_str())+ .unwrap_or(""),) {screen} else {@@ -246,25 +293,39 @@ fn is_click_class_tool(name: &str) -> bool {}fn is_click_or_type_class_tool(name: &str) -> bool {- matches!(name, "click" | "double_click" | "right_click" | "type_text" | "type_text_chars")+ matches!(+ name,+ "click" | "double_click" | "right_click" | "type_text" | "type_text_chars"+ )}// ── turn-*/action.json → action spans ────────────────────────────────────────fn load_action_spans(dir: &Path) -> Vec<ActionSpan> {let mut spans = Vec::new();- let entries = match std::fs::read_dir(dir) { Ok(e) => e, Err(_) => return spans };+ let entries = match std::fs::read_dir(dir) {+ Ok(e) => e,+ Err(_) => return spans,+ };for entry in entries.flatten() {let name = entry.file_name();let name_s = name.to_string_lossy();- if !name_s.starts_with("turn-") { continue; }+ if !name_s.starts_with("turn-") {+ continue;+ }let path = entry.path();- if !path.is_dir() { continue; }+ if !path.is_dir() {+ continue;+ }if let Some(s) = parse_action_span(&path.join("action.json")) {spans.push(s);}}- spans.sort_by(|a, b| a.start_ms.partial_cmp(&b.start_ms).unwrap_or(std::cmp::Ordering::Equal));+ spans.sort_by(|a, b| {+ a.start_ms+ .partial_cmp(&b.start_ms)+ .unwrap_or(std::cmp::Ordering::Equal)+ });spans}@@ -272,7 +333,9 @@ fn parse_action_span(action_path: &Path) -> Option<ActionSpan> {let text = std::fs::read_to_string(action_path).ok()?;let v: Value = serde_json::from_str(&text).ok()?;let tool = v.get("tool")?.as_str()?;- if !is_click_or_type_class_tool(tool) { return None; }+ if !is_click_or_type_class_tool(tool) {+ return None;+ }let end_ms = double_value(v.get("t_ms_from_session_start"))?;let start_ms = double_value(v.get("t_start_ms_from_session_start")).unwrap_or(end_ms);@@ -283,8 +346,15 @@ fn parse_action_span(action_path: &Path) -> Option<ActionSpan> {let width = double_value(wb.get("width"))?;let height = double_value(wb.get("height"))?;if width > 0.0 && height > 0.0 {- Some(WindowBounds { x, y, width, height })- } else { None }+ Some(WindowBounds {+ x,+ y,+ width,+ height,+ })+ } else {+ None+ }});let click_point = v.get("click_point").and_then(|cp| {@@ -306,9 +376,17 @@ fn parse_action_span(action_path: &Path) -> Option<ActionSpan> {fn double_value(v: Option<&Value>) -> Option<f64> {let v = v?;- if let Some(d) = v.as_f64() { return Some(d); }- if let Some(i) = v.as_i64() { return Some(i as f64); }- if let Some(u) = v.as_u64() { return Some(u as f64); }- if let Some(s) = v.as_str() { return s.parse().ok(); }+ if let Some(d) = v.as_f64() {+ return Some(d);+ }+ if let Some(i) = v.as_i64() {+ return Some(i as f64);+ }+ if let Some(u) = v.as_u64() {+ return Some(u as f64);+ }+ if let Some(s) = v.as_str() {+ return s.parse().ok();+ }None}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/recording_render.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/recording_render.rsindex f0165449a5..733be1922a 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/recording_render.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/recording_render.rs@@ -53,7 +53,10 @@ pub struct RenderOptions {impl Default for RenderOptions {fn default() -> Self {- Self { no_zoom: false, default_scale: DEFAULT_ZOOM_SCALE }+ Self {+ no_zoom: false,+ default_scale: DEFAULT_ZOOM_SCALE,+ }}}@@ -71,14 +74,16 @@ pub fn render(output_path: &Path,opts: &RenderOptions,) -> anyhow::Result<RenderResult> {- let traj = load(input_dir)- .map_err(|e: LoadError| anyhow::anyhow!("load {input_dir:?}: {e}"))?;- let ffmpeg = find_ffmpeg()- .ok_or_else(|| anyhow::anyhow!(+ let traj =+ load(input_dir).map_err(|e: LoadError| anyhow::anyhow!("load {input_dir:?}: {e}"))?;+ let ffmpeg = find_ffmpeg().ok_or_else(|| {+ anyhow::anyhow!("ffmpeg not found on PATH. Install with: \winget install Gyan.FFmpeg (Windows), \brew install ffmpeg (macOS), \- or apt install ffmpeg (Linux)."))?;+ or apt install ffmpeg (Linux)."+ )+ })?;let in_dur = probe_duration_ms(&traj.metadata.video_path).unwrap_or(0.0);@@ -130,7 +135,9 @@ pub fn render(format!("zoompan=z='{z}':x='{x}':y='{y}':d=1:s={w}x{h}:fps=30,\pad=ceil(iw/2)*2:ceil(ih/2)*2,format=yuv420p",- z = zoom_expr, x = x_expr, y = y_expr,+ z = zoom_expr,+ x = x_expr,+ y = y_expr,w = traj.metadata.video_width,h = traj.metadata.video_height,)@@ -139,18 +146,26 @@ pub fn render(// Build ffmpeg command.let mut cmd = Command::new(&ffmpeg);cmd.arg("-y")- .arg("-loglevel").arg("error")- .arg("-i").arg(&traj.metadata.video_path)- .arg("-vf").arg(&filter_chain)- .arg("-c:v").arg("libx264")- .arg("-preset").arg("medium") // medium is fine for off-line render- .arg("-pix_fmt").arg("yuv420p")- .arg("-movflags").arg("+faststart")+ .arg("-loglevel")+ .arg("error")+ .arg("-i")+ .arg(&traj.metadata.video_path)+ .arg("-vf")+ .arg(&filter_chain)+ .arg("-c:v")+ .arg("libx264")+ .arg("-preset")+ .arg("medium") // medium is fine for off-line render+ .arg("-pix_fmt")+ .arg("yuv420p")+ .arg("-movflags")+ .arg("+faststart").arg(output_path).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::piped());- let out = cmd.output()+ let out = cmd+ .output().map_err(|e| anyhow::anyhow!("spawn ffmpeg: {e}"))?;if !out.status.success() {let stderr = String::from_utf8_lossy(&out.stderr);@@ -216,17 +231,16 @@ fn build_zoompan_expressions(let peak_scale = region.scale;// Phase + ease + scale_at_t expressed in zoompan's `time` var.- let in_t = format!("max(0,min(1,(time-{start_s})/{zoom_in_s}))");+ let in_t = format!("max(0,min(1,(time-{start_s})/{zoom_in_s}))");let out_t = format!("max(0,min(1,({end_s}-time)/{zoom_out_s}))");- let phase = format!(- "if(lt(time,{in_end_s}),{in_t},if(gt(time,{out_start_s}),{out_t},1))");+ let phase = format!("if(lt(time,{in_end_s}),{in_t},if(gt(time,{out_start_s}),{out_t},1))");let ease = format!("(1-pow(1-({phase}),5))");let region_z = format!("(1+{ease}*({peak_scale}-1))");// x = clip(focus - iw/(2*z), 0, iw - iw/z)- let region_x = format!(- "max(0,min({video_w}-{video_w}/{region_z},{fx_px}-{video_w}/(2*{region_z})))");- let region_y = format!(- "max(0,min({video_h}-{video_h}/{region_z},{fy_px}-{video_h}/(2*{region_z})))");+ let region_x =+ format!("max(0,min({video_w}-{video_w}/{region_z},{fx_px}-{video_w}/(2*{region_z})))");+ let region_y =+ format!("max(0,min({video_h}-{video_h}/{region_z},{fy_px}-{video_h}/(2*{region_z})))");z_expr = format!("if(between(time,{start_s},{end_s}),{region_z},{z_expr})");x_expr = format!("if(between(time,{start_s},{end_s}),{region_x},{x_expr})");@@ -242,12 +256,20 @@ fn build_zoompan_expressions(fn probe_duration_ms(video_path: &Path) -> Option<f64> {let ffprobe = find_ffprobe()?;let out = Command::new(ffprobe)- .args(["-v", "error",- "-show_entries", "format=duration",- "-of", "default=noprint_wrappers=1:nokey=1"])+ .args([+ "-v",+ "error",+ "-show_entries",+ "format=duration",+ "-of",+ "default=noprint_wrappers=1:nokey=1",+ ]).arg(video_path)- .output().ok()?;- if !out.status.success() { return None; }+ .output()+ .ok()?;+ if !out.status.success() {+ return None;+ }let s = String::from_utf8_lossy(&out.stdout);let secs: f64 = s.trim().parse().ok()?;Some(secs * 1000.0)diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rsindex 48896552c6..1add10b4e0 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs@@ -46,7 +46,9 @@ pub struct StartRecordingTool {}impl StartRecordingTool {- pub fn new(session: Arc<RecordingSession>) -> Self { Self { session } }+ pub fn new(session: Arc<RecordingSession>) -> Self {+ Self { session }+ }}static START_REC_DEF: OnceLock<ToolDef> = OnceLock::new();@@ -89,7 +91,8 @@ impl Tool for StartRecordingTool {carries the diagnostic.\n\n\State persists for the life of the daemon / MCP session; a restart \resets to disabled with no on-disk state. Call `stop_recording` to \- disable + finalize the mp4.".into(),+ disable + finalize the mp4."+ .into(),input_schema: json!({"type": "object","required": ["output_dir"],@@ -130,7 +133,11 @@ impl Tool for StartRecordingTool {// (session_end) only stops the recording its own session started.let owner = args.opt_str("_session_id");- match self.session.start(output_dir.as_deref().unwrap(), record_video, owner.as_deref()) {+ match self.session.start(+ output_dir.as_deref().unwrap(),+ record_video,+ owner.as_deref(),+ ) {Ok(()) => {let state = self.session.current_state();// When the caller asked for video and it failed (e.g. macOS@@ -149,10 +156,14 @@ impl Tool for StartRecordingTool {""};format!("\n\n⚠️ Video capture failed (per-turn JSON+screenshot still running):\n{err}{hint}")- } else { String::new() };- let msg = format!("✅ Recording started -> {}{}",+ } else {+ String::new()+ };+ let msg = format!(+ "✅ Recording started -> {}{}",state.output_dir.as_deref().unwrap_or("?"),- video_note);+ video_note+ );ToolResult::text(msg).with_structured(recording_state_json(&state))}Err(e) => ToolResult::error(format!("Failed to start recording: {e}")),@@ -167,7 +178,9 @@ pub struct StopRecordingTool {}impl StopRecordingTool {- pub fn new(session: Arc<RecordingSession>) -> Self { Self { session } }+ pub fn new(session: Arc<RecordingSession>) -> Self {+ Self { session }+ }}static STOP_REC_DEF: OnceLock<ToolDef> = OnceLock::new();@@ -186,7 +199,8 @@ impl Tool for StopRecordingTool {recording is active regardless of which session started it. \Ownership-scoped teardown (so one MCP client disconnecting can't stop a \recording a later client started) is handled by the daemon's \- `session_end` lifecycle signal, not by this tool.".into(),+ `session_end` lifecycle signal, not by this tool."+ .into(),input_schema: json!({"type": "object","properties": {},@@ -206,7 +220,9 @@ impl Tool for StopRecordingTool {match self.session.stop_owner(None) {Ok(()) => {let state = self.session.current_state();- let video_note = state.last_video_path.as_deref()+ let video_note = state+ .last_video_path+ .as_deref().map(|p| format!(" (video → {p})")).unwrap_or_default();ToolResult::text(format!("✅ Recording stopped.{video_note}"))@@ -224,7 +240,9 @@ pub struct GetRecordingStateTool {}impl GetRecordingStateTool {- pub fn new(session: Arc<RecordingSession>) -> Self { Self { session } }+ pub fn new(session: Arc<RecordingSession>) -> Self {+ Self { session }+ }}static GET_REC_DEF: OnceLock<ToolDef> = OnceLock::new();@@ -331,12 +349,19 @@ impl Tool for ReplayTrajectoryTool {if let Some(relative) = dir_str.strip_prefix("~/") {if let Ok(home) = std::env::var("HOME") {std::path::PathBuf::from(home).join(relative)- } else { p }- } else { p }+ } else {+ p+ }+ } else {+ p+ }};if !dir.exists() {- return ToolResult::error(format!("Trajectory directory does not exist: {}", dir.display()));+ return ToolResult::error(format!(+ "Trajectory directory does not exist: {}",+ dir.display()+ ));}// Collect and sort turn-NNNNN directories.@@ -344,22 +369,30 @@ impl Tool for ReplayTrajectoryTool {.map(|rd| {rd.filter_map(|e| e.ok()).map(|e| e.path())- .filter(|p| p.is_dir() && p.file_name()- .and_then(|n| n.to_str())- .map(|n| n.starts_with("turn-"))- .unwrap_or(false))+ .filter(|p| {+ p.is_dir()+ && p.file_name()+ .and_then(|n| n.to_str())+ .map(|n| n.starts_with("turn-"))+ .unwrap_or(false)+ }).collect::<Vec<_>>()}).unwrap_or_default();turn_dirs.sort();if turn_dirs.is_empty() {- return ToolResult::error(format!("No turn-NNNNN folders found under {}", dir.display()));+ return ToolResult::error(format!(+ "No turn-NNNNN folders found under {}",+ dir.display()+ ));}let registry = match get_replay_registry() {Some(r) => r,- None => return ToolResult::error("Replay not available: registry not initialised yet."),+ None => {+ return ToolResult::error("Replay not available: registry not initialised yet.")+ }};let mut attempted = 0u32;@@ -369,7 +402,8 @@ impl Tool for ReplayTrajectoryTool {let mut first_failure: Option<(String, String, String)> = None;for turn_dir in &turn_dirs {- let turn_name = turn_dir.file_name()+ let turn_name = turn_dir+ .file_name().and_then(|n| n.to_str()).unwrap_or("?").to_owned();@@ -380,14 +414,17 @@ impl Tool for ReplayTrajectoryTool {Err(e) => {failed += 1;if first_failure.is_none() {- first_failure = Some((turn_name.clone(), "action.json".into(), e.to_string()));+ first_failure =+ Some((turn_name.clone(), "action.json".into(), e.to_string()));}turns_json.push(json!({"turn": turn_name,"ok": false,"parse_error": e.to_string()}));- if stop_on_error { break; }+ if stop_on_error {+ break;+ }continue;}};@@ -395,11 +432,15 @@ impl Tool for ReplayTrajectoryTool {attempted += 1;let result = registry.invoke(&tool_name, tool_args).await;let is_err = result.is_error.unwrap_or(false);- let summary = result.content.iter()+ let summary = result+ .content+ .iter().find_map(|c| {if let crate::protocol::Content::Text { text, .. } = c {Some(text.as_str())- } else { None }+ } else {+ None+ }}).unwrap_or("").to_owned();@@ -416,7 +457,9 @@ impl Tool for ReplayTrajectoryTool {if first_failure.is_none() {first_failure = Some((turn_name.clone(), tool_name.clone(), summary));}- if stop_on_error { break; }+ if stop_on_error {+ break;+ }} else {succeeded += 1;}@@ -426,9 +469,7 @@ impl Tool for ReplayTrajectoryTool {}}- let dir_name = dir.file_name()- .and_then(|n| n.to_str())- .unwrap_or("?");+ let dir_name = dir.file_name().and_then(|n| n.to_str()).unwrap_or("?");let mut summary_text = format!("replay {dir_name}: attempted={attempted} succeeded={succeeded} failed={failed}");@@ -448,8 +489,7 @@ impl Tool for ReplayTrajectoryTool {structured["first_failure"] = json!({ "turn": turn, "tool": tool, "error": error });}- ToolResult::text(summary_text)- .with_structured(structured)+ ToolResult::text(summary_text).with_structured(structured)}}@@ -479,11 +519,15 @@ fn parse_action_json(path: &std::path::Path) -> anyhow::Result<(String, Value)>}let text = std::fs::read_to_string(path)?;let obj: Value = serde_json::from_str(&text)?;- let tool = obj.get("tool")+ let tool = obj+ .get("tool").and_then(|v| v.as_str()).ok_or_else(|| anyhow::anyhow!("action.json missing 'tool' string field"))?.to_owned();- let tool_args = obj.get("arguments").cloned().unwrap_or(Value::Object(Default::default()));+ let tool_args = obj+ .get("arguments")+ .cloned()+ .unwrap_or(Value::Object(Default::default()));Ok((tool, tool_args))}@@ -556,7 +600,8 @@ impl Tool for InstallFfmpegTool {}let display = plan.display();- let result = tokio::task::spawn_blocking(move || crate::ffmpeg_install::run_install(&plan)).await;+ let result =+ tokio::task::spawn_blocking(move || crate::ffmpeg_install::run_install(&plan)).await;match result {Ok(Ok((cmd_ok, output))) => match crate::video_ffmpeg::find_ffmpeg() {Some(path) => ToolResult::text(format!("✅ ffmpeg installed via `{display}`."))@@ -569,7 +614,9 @@ impl Tool for InstallFfmpegTool {Command: {display}\ncommand_succeeded={cmd_ok}\nOutput tail:\n{output}")),},- Ok(Err(e)) => ToolResult::error(format!("ffmpeg install failed: {e}\nCommand: {display}")),+ Ok(Err(e)) => {+ ToolResult::error(format!("ffmpeg install failed: {e}\nCommand: {display}"))+ }Err(e) => ToolResult::error(format!("install task error: {e}")),}}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/recording_zoom.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/recording_zoom.rsindex 50ef6f3c4e..5de5d4a9ef 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/recording_zoom.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/recording_zoom.rs@@ -13,7 +13,13 @@ use serde::{Deserialize, Serialize};#[inline]pub fn clamp01(v: f64) -> f64 {- if v < 0.0 { 0.0 } else if v > 1.0 { 1.0 } else { v }+ if v < 0.0 {+ 0.0+ } else if v > 1.0 {+ 1.0+ } else {+ v+ }}#[inline]@@ -42,8 +48,12 @@ pub fn cubic_bezier(x1: f64, y1: f64, x2: f64, y2: f64, t: f64) -> f64 {for _ in 0..8 {let residual = sample_bezier_1d(x1, x2, s) - target_x;let slope = sample_bezier_1d_derivative(x1, x2, s);- if residual.abs() < 1e-6 { break; }- if slope.abs() < 1e-6 { break; }+ if residual.abs() < 1e-6 {+ break;+ }+ if slope.abs() < 1e-6 {+ break;+ }s -= residual / slope;}// Binary-search cleanup@@ -52,8 +62,14 @@ pub fn cubic_bezier(x1: f64, y1: f64, x2: f64, y2: f64, t: f64) -> f64 {let mut upper = 1.0;for _ in 0..10 {let x = sample_bezier_1d(x1, x2, s);- if (x - target_x).abs() < 1e-6 { break; }- if x < target_x { lower = s; } else { upper = s; }+ if (x - target_x).abs() < 1e-6 {+ break;+ }+ if x < target_x {+ lower = s;+ } else {+ upper = s;+ }s = (lower + upper) / 2.0;}sample_bezier_1d(y1, y2, s)@@ -149,21 +165,27 @@ pub struct ActionSpan {// ── ZoomRegion generation ────────────────────────────────────────────────────-pub fn generate_zoom_regions(- clicks: &[ClickEvent],- default_scale: f64,-) -> Vec<ZoomRegion> {+pub fn generate_zoom_regions(clicks: &[ClickEvent], default_scale: f64) -> Vec<ZoomRegion> {let mut sorted: Vec<&ClickEvent> = clicks.iter().collect();- sorted.sort_by(|a, b| a.t_ms.partial_cmp(&b.t_ms).unwrap_or(std::cmp::Ordering::Equal));+ sorted.sort_by(|a, b| {+ a.t_ms+ .partial_cmp(&b.t_ms)+ .unwrap_or(std::cmp::Ordering::Equal)+ });let mut out: Vec<ZoomRegion> = Vec::with_capacity(sorted.len());for click in &sorted {let seed_start = click.t_ms - defaults::PRE_CLICK_LEAD_IN_MS;let seed_end = click.t_ms + defaults::POST_CLICK_HOLD_MS;- let seed_waypoint = FocusWaypoint { t_ms: click.t_ms, x: click.x, y: click.y };+ let seed_waypoint = FocusWaypoint {+ t_ms: click.t_ms,+ x: click.x,+ y: click.y,+ };// Merge with the previous region if the gap is small enough.- let should_merge = out.last()+ let should_merge = out+ .last().map(|last| seed_start - last.end_ms < defaults::CHAINED_ZOOM_PAN_GAP_MS).unwrap_or(false);@@ -215,9 +237,13 @@ pub fn sample_curve(}};- let region = regions.iter()+ let region = regions+ .iter().find(|r| t_ms >= r.start_ms && t_ms <= r.end_ms);- let region = match region { Some(r) => r, None => return resting() };+ let region = match region {+ Some(r) => r,+ None => return resting(),+ };let (zoom_in, zoom_out) = region.effective_durations();let in_end = region.start_ms + zoom_in;@@ -226,7 +252,13 @@ pub fn sample_curve(// Phase progress with cubic-bezier(0.16, 1, 0.3, 1) easing.let phase_progress = if t_ms < in_end {let span = zoom_in.max(1e-6);- cubic_bezier(0.16, 1.0, 0.3, 1.0, clamp01((t_ms - region.start_ms) / span))+ cubic_bezier(+ 0.16,+ 1.0,+ 0.3,+ 1.0,+ clamp01((t_ms - region.start_ms) / span),+ )} else if t_ms > out_start {let span = zoom_out.max(1e-6);let tail = clamp01((region.end_ms - t_ms) / span);@@ -260,7 +292,9 @@ fn resolve_focus(t_ms: f64, region: &ZoomRegion) -> (f64, f64) {for i in 0..waypoints.len().saturating_sub(1) {let a = &waypoints[i];let b = &waypoints[i + 1];- if t_ms < a.t_ms || t_ms > b.t_ms { continue; }+ if t_ms < a.t_ms || t_ms > b.t_ms {+ continue;+ }let span = (b.t_ms - a.t_ms).max(1e-6);let local_t = clamp01((t_ms - a.t_ms) / span);// easeConnectedPan: cubic-bezier(0.1, 0, 0.2, 1)@@ -277,19 +311,31 @@ fn resolve_focus(t_ms: f64, region: &ZoomRegion) -> (f64, f64) {pub fn position_at(t_ms: f64, samples: &[CursorSample]) -> Option<(f64, f64)> {let first = samples.first()?;let last = samples.last()?;- if t_ms <= first.t_ms { return Some((first.x, first.y)); }- if t_ms >= last.t_ms { return Some((last.x, last.y)); }+ if t_ms <= first.t_ms {+ return Some((first.x, first.y));+ }+ if t_ms >= last.t_ms {+ return Some((last.x, last.y));+ }let mut lo = 0usize;let mut hi = samples.len() - 1;while hi - lo > 1 {let mid = (lo + hi) / 2;- if samples[mid].t_ms <= t_ms { lo = mid; } else { hi = mid; }+ if samples[mid].t_ms <= t_ms {+ lo = mid;+ } else {+ hi = mid;+ }}let before = &samples[lo];let after = &samples[hi];let span = after.t_ms - before.t_ms;- let u = if span > 0.0 { (t_ms - before.t_ms) / span } else { 0.0 };+ let u = if span > 0.0 {+ (t_ms - before.t_ms) / span+ } else {+ 0.0+ };Some((lerp(before.x, after.x, u), lerp(before.y, after.y, u)))}@@ -298,18 +344,26 @@ pub fn position_at(t_ms: f64, samples: &[CursorSample]) -> Option<(f64, f64)> {/// Pad raw action spans by ±`ACTION_PAD_MS` and merge overlapping spans./// Merged spans accumulate per-action focus waypoints for smooth pan.pub fn generate_action_spans(raw: &[ActionSpan]) -> Vec<ActionSpan> {- let mut padded: Vec<ActionSpan> = raw.iter().map(|s| ActionSpan {- start_ms: (s.start_ms - defaults::ACTION_PAD_MS).max(0.0),- end_ms: s.end_ms + defaults::ACTION_PAD_MS,- window_bounds: s.window_bounds,- click_point: s.click_point,- focus_waypoints: None,- }).collect();- padded.sort_by(|a, b| a.start_ms.partial_cmp(&b.start_ms).unwrap_or(std::cmp::Ordering::Equal));+ let mut padded: Vec<ActionSpan> = raw+ .iter()+ .map(|s| ActionSpan {+ start_ms: (s.start_ms - defaults::ACTION_PAD_MS).max(0.0),+ end_ms: s.end_ms + defaults::ACTION_PAD_MS,+ window_bounds: s.window_bounds,+ click_point: s.click_point,+ focus_waypoints: None,+ })+ .collect();+ padded.sort_by(|a, b| {+ a.start_ms+ .partial_cmp(&b.start_ms)+ .unwrap_or(std::cmp::Ordering::Equal)+ });let mut result: Vec<ActionSpan> = Vec::new();for span in padded {- let should_merge = result.last()+ let should_merge = result+ .last().map(|last| span.start_ms <= last.end_ms + defaults::ACTION_MERGE_GAP_MS).unwrap_or(false);@@ -321,16 +375,32 @@ pub fn generate_action_spans(raw: &[ActionSpan]) -> Vec<ActionSpan> {let mut waypoints = last.focus_waypoints.clone().unwrap_or_default();if waypoints.is_empty() {if let Some((lx, ly)) = focus_for_span(last) {- waypoints.push(FocusWaypoint { t_ms: last_mid, x: lx, y: ly });+ waypoints.push(FocusWaypoint {+ t_ms: last_mid,+ x: lx,+ y: ly,+ });}}if let Some((sx, sy)) = focus_for_span(&span) {- waypoints.push(FocusWaypoint { t_ms: span_mid, x: sx, y: sy });+ waypoints.push(FocusWaypoint {+ t_ms: span_mid,+ x: sx,+ y: sy,+ });}last.end_ms = last.end_ms.max(span.end_ms);- if last.window_bounds.is_none() { last.window_bounds = span.window_bounds; }- if last.click_point.is_none() { last.click_point = span.click_point; }- last.focus_waypoints = if waypoints.is_empty() { None } else { Some(waypoints) };+ if last.window_bounds.is_none() {+ last.window_bounds = span.window_bounds;+ }+ if last.click_point.is_none() {+ last.click_point = span.click_point;+ }+ last.focus_waypoints = if waypoints.is_empty() {+ None+ } else {+ Some(waypoints)+ };} else {result.push(span);}@@ -339,7 +409,9 @@ pub fn generate_action_spans(raw: &[ActionSpan]) -> Vec<ActionSpan> {}fn focus_for_span(span: &ActionSpan) -> Option<(f64, f64)> {- if let Some(cp) = span.click_point { return Some(cp); }+ if let Some(cp) = span.click_point {+ return Some(cp);+ }if let Some(wb) = span.window_bounds {return Some((wb.x + wb.width / 2.0, wb.y + wb.height / 2.0));}@@ -355,12 +427,18 @@ pub fn map_pts(input_ms: f64, spans: &[ActionSpan]) -> f64 {if span.start_ms > prev_end {let seg_end = span.start_ms.min(input_ms);out_ms += (seg_end - prev_end) / defaults::ACTION_FAST_SPEED;- if input_ms <= span.start_ms { return out_ms; }+ if input_ms <= span.start_ms {+ return out_ms;+ }}let start = span.start_ms.max(prev_end);let end = span.end_ms.min(input_ms);- if end > start { out_ms += end - start; }- if input_ms <= span.end_ms { return out_ms; }+ if end > start {+ out_ms += end - start;+ }+ if input_ms <= span.end_ms {+ return out_ms;+ }prev_end = span.end_ms;}if input_ms > prev_end {@@ -391,9 +469,14 @@ mod tests {#[test]fn click_becomes_a_region() {- let regions = generate_zoom_regions(&[- ClickEvent { t_ms: 5000.0, x: 100.0, y: 200.0 },- ], 2.0);+ let regions = generate_zoom_regions(+ &[ClickEvent {+ t_ms: 5000.0,+ x: 100.0,+ y: 200.0,+ }],+ 2.0,+ );assert_eq!(regions.len(), 1);let r = ®ions[0];assert_eq!(r.focus_x, 100.0);@@ -405,10 +488,21 @@ mod tests {#[test]fn close_clicks_merge_into_chained_region() {- let regions = generate_zoom_regions(&[- ClickEvent { t_ms: 1000.0, x: 100.0, y: 100.0 },- ClickEvent { t_ms: 2000.0, x: 200.0, y: 200.0 },- ], 2.0);+ let regions = generate_zoom_regions(+ &[+ ClickEvent {+ t_ms: 1000.0,+ x: 100.0,+ y: 100.0,+ },+ ClickEvent {+ t_ms: 2000.0,+ x: 200.0,+ y: 200.0,+ },+ ],+ 2.0,+ );assert_eq!(regions.len(), 1, "close clicks should merge");let waypoints = regions[0].waypoints.as_ref().unwrap();assert_eq!(waypoints.len(), 2);@@ -416,30 +510,54 @@ mod tests {#[test]fn far_apart_clicks_dont_merge() {- let regions = generate_zoom_regions(&[- ClickEvent { t_ms: 1000.0, x: 100.0, y: 100.0 },- ClickEvent { t_ms: 10000.0, x: 200.0, y: 200.0 },- ], 2.0);+ let regions = generate_zoom_regions(+ &[+ ClickEvent {+ t_ms: 1000.0,+ x: 100.0,+ y: 100.0,+ },+ ClickEvent {+ t_ms: 10000.0,+ x: 200.0,+ y: 200.0,+ },+ ],+ 2.0,+ );assert_eq!(regions.len(), 2);}#[test]fn sample_curve_inside_region_zooms() {- let regions = generate_zoom_regions(&[- ClickEvent { t_ms: 5000.0, x: 100.0, y: 200.0 },- ], 2.0);+ let regions = generate_zoom_regions(+ &[ClickEvent {+ t_ms: 5000.0,+ x: 100.0,+ y: 200.0,+ }],+ 2.0,+ );// At the click moment, should be near peak zoom.let (scale, fx, fy) = sample_curve(5000.0, ®ions, &[]);- assert!(scale > 1.5, "expected near-peak zoom at click time, got {scale}");+ assert!(+ scale > 1.5,+ "expected near-peak zoom at click time, got {scale}"+ );assert!((fx - 100.0).abs() < 0.5);assert!((fy - 200.0).abs() < 0.5);}#[test]fn sample_curve_outside_region_is_unity() {- let regions = generate_zoom_regions(&[- ClickEvent { t_ms: 5000.0, x: 100.0, y: 200.0 },- ], 2.0);+ let regions = generate_zoom_regions(+ &[ClickEvent {+ t_ms: 5000.0,+ x: 100.0,+ y: 200.0,+ }],+ 2.0,+ );// Far before any zoom region.let (scale, _, _) = sample_curve(0.0, ®ions, &[]);assert!((scale - 1.0).abs() < 1e-6);@@ -448,8 +566,16 @@ mod tests {#[test]fn cursor_position_at_clamps_to_endpoints() {let samples = vec![- CursorSample { t_ms: 0.0, x: 0.0, y: 0.0 },- CursorSample { t_ms: 1000.0, x: 100.0, y: 100.0 },+ CursorSample {+ t_ms: 0.0,+ x: 0.0,+ y: 0.0,+ },+ CursorSample {+ t_ms: 1000.0,+ x: 100.0,+ y: 100.0,+ },];assert_eq!(position_at(-100.0, &samples), Some((0.0, 0.0)));assert_eq!(position_at(2000.0, &samples), Some((100.0, 100.0)));@@ -462,8 +588,11 @@ mod tests {#[test]fn map_pts_is_monotonic_and_speeds_outside_spans() {let spans = vec![ActionSpan {- start_ms: 1000.0, end_ms: 2000.0,- window_bounds: None, click_point: None, focus_waypoints: None,+ start_ms: 1000.0,+ end_ms: 2000.0,+ window_bounds: None,+ click_point: None,+ focus_waypoints: None,}];// Before span: fast-forwardlet before = map_pts(500.0, &spans);diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/session.rsindex 5ae762837e..754dfa558e 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs@@ -98,9 +98,7 @@ pub fn bounded_cursor_outcome(} else {match icon.map(str::trim).filter(|value| !value.is_empty()) {None => CursorStyleCategory::Default,- Some(value) if value.eq_ignore_ascii_case("arrow") => {- CursorStyleCategory::BuiltinArrow- }+ Some(value) if value.eq_ignore_ascii_case("arrow") => CursorStyleCategory::BuiltinArrow,Some(value) if value.eq_ignore_ascii_case("teardrop") => {CursorStyleCategory::BuiltinTeardrop}@@ -416,7 +414,10 @@ mod tests {impl SessionObserver for ProbeObserver {fn on_session_started(&self, id: &str, observation: SessionStartObservation) {- self.starts.lock().unwrap().push((id.to_owned(), observation));+ self.starts+ .lock()+ .unwrap()+ .push((id.to_owned(), observation));}fn on_tool_completed(&self,@@ -522,10 +523,15 @@ mod tests {let sid = "test-ttl-session-DDEEFF";touch_session(sid);// A huge TTL leaves it alone (just touched).- assert!(evict_idle(Duration::from_secs(3600)).iter().all(|s| s != sid));+ assert!(evict_idle(Duration::from_secs(3600))+ .iter()+ .all(|s| s != sid));// A zero TTL treats any prior activity as idle → evicts it.let evicted = evict_idle(Duration::ZERO);- assert!(evicted.iter().any(|s| s == sid), "zero-TTL must evict a touched session");+ assert!(+ evicted.iter().any(|s| s == sid),+ "zero-TTL must evict a touched session"+ );assert!(is_session_ended(sid), "evicted session is ended");}@@ -556,7 +562,10 @@ mod tests {assert_eq!(custom.active_cursor_count, 7);let debug = format!("{custom:?}");for forbidden in ["/private/customer", "private-brand", "private agent"] {- assert!(!debug.contains(forbidden), "cursor outcome leaked {forbidden}: {debug}");+ assert!(+ !debug.contains(forbidden),+ "cursor outcome leaked {forbidden}: {debug}"+ );}let unknown = bounded_cursor_outcome(@@ -730,20 +739,23 @@ mod tests {&& observation.declaration == SessionDeclaration::ImplicitFirstAction&& observation.transport == SessionTransport::McpHttp}));- assert!(starts.iter().any(|(id, observation)| id == revived && observation.revived));+ assert!(starts+ .iter()+ .any(|(id, observation)| id == revived && observation.revived));drop(starts);let ends = probe.ends.lock().unwrap();assert!(ends.iter().any(|(id, reason, cursor)| {- id == explicit && *reason == SessionEndReason::Explicit+ id == explicit+ && *reason == SessionEndReason::Explicit&& cursor.is_some_and(|value| {value.style == CursorStyleCategory::BuiltinArrow&& value.active_cursor_count == 2})}));- assert!(ends.iter().any(|(id, reason, _)| {- id == idle && *reason == SessionEndReason::IdleTimeout- }));+ assert!(ends+ .iter()+ .any(|(id, reason, _)| { id == idle && *reason == SessionEndReason::IdleTimeout }));assert!(!ends.iter().any(|(id, _, _)| id == control));}}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/session_tools.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/session_tools.rsindex ac7c559d9a..def290844b 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/session_tools.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/session_tools.rs@@ -74,7 +74,7 @@ impl Tool for StartSessionTool {with the same id just refreshes its idle-TTL. End it with `end_session` \(or let the idle-TTL reclaim it). Concurrent runs/subagents each pass \their own `session` to get their own cursor."- .into(),+ .into(),input_schema: json!({"type": "object","required": ["session"],@@ -355,11 +355,7 @@ mod tests {use super::*;fn result_code(result: &ToolResult) -> Option<&str> {- result- .structured_content- .as_ref()?- .get("code")?- .as_str()+ result.structured_content.as_ref()?.get("code")?.as_str()}#[test]diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/socket_io.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/socket_io.rsindex 41ca0dd409..0122897875 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/socket_io.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/socket_io.rs@@ -90,7 +90,10 @@ mod tests {#[test]fn retries_through_transient_eagain() {- let mut w = FlakyWriter { eagain_left: 3, written: vec![] };+ let mut w = FlakyWriter {+ eagain_left: 3,+ written: vec![],+ };let deadline = Instant::now() + Duration::from_secs(5);write_all_with_retry(&mut w, b"hello\n", deadline).expect("transient EAGAIN should be retried, not fatal");@@ -99,7 +102,10 @@ mod tests {#[test]fn times_out_when_daemon_never_drains() {- let mut w = FlakyWriter { eagain_left: usize::MAX, written: vec![] };+ let mut w = FlakyWriter {+ eagain_left: usize::MAX,+ written: vec![],+ };let deadline = Instant::now() + Duration::from_millis(30);let err = write_all_with_retry(&mut w, b"hello\n", deadline).expect_err("a never-draining daemon must eventually surface an error");diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/text_sanitize.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/text_sanitize.rsindex 8bca1ebd19..29c985183c 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/text_sanitize.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/text_sanitize.rs@@ -93,7 +93,10 @@ pub fn strip_trailing_agent_protocol_tags(text: &str) -> Cow<'_, str> {if inner.is_empty() || inner.chars().any(char::is_whitespace) {break;}- if !PROTOCOL_TAG_NAMES.iter().any(|name| inner.eq_ignore_ascii_case(name)) {+ if !PROTOCOL_TAG_NAMES+ .iter()+ .any(|name| inner.eq_ignore_ascii_case(name))+ {break;}// Balance check: is there an opening `<NAME` (case-insensitive,@@ -159,8 +162,6 @@ fn has_matching_opener(prelude: &str, name: &str) -> bool {false}--#[cfg(test)]mod tests {use super::*;diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool_schema.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool_schema.rsindex 1ad03b0688..7501e83350 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool_schema.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool_schema.rs@@ -185,7 +185,11 @@ pub fn shared_schema_violations(tool_name: &str, input_schema: &Value) -> Vec<Stlet got: Vec<String> = input_schema.get("required").and_then(|r| r.as_array())- .map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect())+ .map(|a| {+ a.iter()+ .filter_map(|v| v.as_str().map(str::to_owned))+ .collect()+ }).unwrap_or_default();let mut got_sorted = got.clone();got_sorted.sort();diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/video_ffmpeg.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/video_ffmpeg.rsindex aedd5e3a79..ed48f7b6d0 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/video_ffmpeg.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/video_ffmpeg.rs@@ -61,8 +61,7 @@ impl FfmpegVideoBackend {}let mut cmd = Command::new(&ffmpeg);- cmd.arg("-y")- .arg("-loglevel").arg("error");+ cmd.arg("-y").arg("-loglevel").arg("error");platform_input_args(&mut cmd);@@ -70,20 +69,25 @@ impl FfmpegVideoBackend {// display stays in frame on odd resolutions (e.g. 1512×949 Win11).cmd.arg("-vf").arg("pad=ceil(iw/2)*2:ceil(ih/2)*2");- cmd.arg("-c:v").arg("libx264")- .arg("-preset").arg("ultrafast")- .arg("-pix_fmt").arg("yuv420p")- .arg("-movflags").arg("+faststart")- .arg("-g").arg("30")+ cmd.arg("-c:v")+ .arg("libx264")+ .arg("-preset")+ .arg("ultrafast")+ .arg("-pix_fmt")+ .arg("yuv420p")+ .arg("-movflags")+ .arg("+faststart")+ .arg("-g")+ .arg("30").arg(&output_path);cmd.stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::piped());- let mut child = cmd.spawn().map_err(|e| {- anyhow::anyhow!("Failed to spawn ffmpeg ({}): {e}", ffmpeg.display())- })?;+ let mut child = cmd+ .spawn()+ .map_err(|e| anyhow::anyhow!("Failed to spawn ffmpeg ({}): {e}", ffmpeg.display()))?;let stderr_thread = child.stderr.take().map(|mut stderr| {std::thread::spawn(move || -> Vec<u8> {@@ -110,9 +114,7 @@ impl FfmpegVideoBackend {.unwrap_or_default();let tail_str = String::from_utf8_lossy(&tail);let _ = child.kill();- anyhow::bail!(- "ffmpeg exited immediately ({status}). stderr tail:\n{tail_str}"- );+ anyhow::bail!("ffmpeg exited immediately ({status}). stderr tail:\n{tail_str}");}Ok(None) => {if Instant::now() >= probe_deadline {@@ -190,18 +192,34 @@ impl VideoBackend for FfmpegVideoBackend {/// distro I've seen.pub fn find_ffprobe() -> Option<PathBuf> {let ffmpeg = find_ffmpeg()?;- if ffmpeg.parent().map(|p| p.as_os_str().is_empty()).unwrap_or(true) {+ if ffmpeg+ .parent()+ .map(|p| p.as_os_str().is_empty())+ .unwrap_or(true)+ {return Some(PathBuf::from("ffprobe"));}let mut p = ffmpeg.clone();- p.set_file_name(if cfg!(target_os = "windows") { "ffprobe.exe" } else { "ffprobe" });- if p.exists() { Some(p) } else { None }+ p.set_file_name(if cfg!(target_os = "windows") {+ "ffprobe.exe"+ } else {+ "ffprobe"+ });+ if p.exists() {+ Some(p)+ } else {+ None+ }}pub(crate) fn find_ffmpeg() -> Option<PathBuf> {- if Command::new("ffmpeg").arg("-version")- .stdout(Stdio::null()).stderr(Stdio::null())- .status().map(|s| s.success()).unwrap_or(false)+ if Command::new("ffmpeg")+ .arg("-version")+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .status()+ .map(|s| s.success())+ .unwrap_or(false){return Some(PathBuf::from("ffmpeg"));}@@ -209,8 +227,7 @@ pub(crate) fn find_ffmpeg() -> Option<PathBuf> {#[cfg(target_os = "windows")]{if let Ok(local_appdata) = std::env::var("LOCALAPPDATA") {- let pkg_root = PathBuf::from(local_appdata)- .join("Microsoft/WinGet/Packages");+ let pkg_root = PathBuf::from(local_appdata).join("Microsoft/WinGet/Packages");if let Ok(entries) = std::fs::read_dir(&pkg_root) {for e in entries.flatten() {let name = e.file_name();@@ -232,7 +249,9 @@ pub(crate) fn find_ffmpeg() -> Option<PathBuf> {"C:/tools/ffmpeg/bin/ffmpeg.exe",] {let pb = PathBuf::from(p);- if pb.exists() { return Some(pb); }+ if pb.exists() {+ return Some(pb);+ }}}@@ -244,7 +263,9 @@ pub(crate) fn find_ffmpeg() -> Option<PathBuf> {"/snap/bin/ffmpeg",] {let pb = PathBuf::from(p);- if pb.exists() { return Some(pb); }+ if pb.exists() {+ return Some(pb);+ }}}@@ -259,7 +280,9 @@ pub(crate) fn find_ffmpeg() -> Option<PathBuf> {"/usr/bin/ffmpeg",] {let pb = PathBuf::from(p);- if pb.exists() { return Some(pb); }+ if pb.exists() {+ return Some(pb);+ }}}@@ -271,10 +294,14 @@ fn platform_input_args(cmd: &mut Command) {#[cfg(target_os = "windows")]{- cmd.arg("-f").arg("gdigrab")- .arg("-framerate").arg(framerate)- .arg("-draw_mouse").arg("1")- .arg("-i").arg("desktop");+ cmd.arg("-f")+ .arg("gdigrab")+ .arg("-framerate")+ .arg(framerate)+ .arg("-draw_mouse")+ .arg("1")+ .arg("-i")+ .arg("desktop");}#[cfg(target_os = "linux")]@@ -288,10 +315,14 @@ fn platform_input_args(cmd: &mut Command) {Ok("0") => "0",_ => "1",};- cmd.arg("-f").arg("x11grab")- .arg("-framerate").arg(framerate)- .arg("-draw_mouse").arg(draw_mouse)- .arg("-i").arg(display);+ cmd.arg("-f")+ .arg("x11grab")+ .arg("-framerate")+ .arg(framerate)+ .arg("-draw_mouse")+ .arg(draw_mouse)+ .arg("-i")+ .arg(display);}// macOS not wired here — the macOS factory is `SckitVideoBackendFactory`diff --git a/libs/cua-driver/rust/crates/cua-driver-core/tests/session_lifecycle.rs b/libs/cua-driver/rust/crates/cua-driver-core/tests/session_lifecycle.rsindex ad20c91d5e..caf5712314 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/tests/session_lifecycle.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/tests/session_lifecycle.rs@@ -26,8 +26,8 @@//! both paths, which is the cross-platform half of the contract.use cua_driver_core::session::{- active_session_count, end_session, evict_idle, is_session_ended,- register_session_end_hook, revive_session, touch_session,+ active_session_count, end_session, evict_idle, is_session_ended, register_session_end_hook,+ revive_session, touch_session,};use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::{Arc, Mutex, MutexGuard, OnceLock};@@ -85,7 +85,11 @@ impl Disposal {});}- Disposal { cursor_removed, config_cleared, recording_stopped }+ Disposal {+ cursor_removed,+ config_cleared,+ recording_stopped,+ }}fn counts(&self) -> (usize, usize, usize) {@@ -128,14 +132,23 @@ fn end_session_disposes_then_id_reuse_starts_fresh() {// cursor present" (the CursorRegistry is platform-macos, daemon-level only).revive_session(&sid);touch_session(&sid);- assert!(!is_session_ended(&sid), "freshly started session must be live");- assert!(active_session_count() >= 1, "session must be counted as active");+ assert!(+ !is_session_ended(&sid),+ "freshly started session must be live"+ );+ assert!(+ active_session_count() >= 1,+ "session must be counted as active"+ );disposal.assert_not_disposed("just started");// 2. After activity, the session is alive and NOT evicted under a long TTL.touch_session(&sid);let evicted = evict_idle(Duration::from_secs(3600));- assert!(!evicted.contains(&sid), "long-TTL sweep must not evict a just-touched session");+ assert!(+ !evicted.contains(&sid),+ "long-TTL sweep must not evict a just-touched session"+ );assert!(!is_session_ended(&sid), "still live after a long-TTL sweep");disposal.assert_not_disposed("after long-TTL no-op sweep");@@ -146,14 +159,26 @@ fn end_session_disposes_then_id_reuse_starts_fresh() {disposal.assert_fully_disposed_once("end_session");// The idle-TTL entry is gone, so a later sweep won't re-fire for it// (fire_session_end is idempotent regardless).- assert!(!evict_idle(Duration::ZERO).contains(&sid), "no leftover TTL entry");+ assert!(+ !evict_idle(Duration::ZERO).contains(&sid),+ "no leftover TTL entry"+ );disposal.assert_fully_disposed_once("end_session is idempotent (no double-dispose)");// 4. Reuse the same id: it must start FRESH, not a leaked/poisoned remnant.- assert!(revive_session(&sid), "re-declaring a recycled id revives it");+ assert!(+ revive_session(&sid),+ "re-declaring a recycled id revives it"+ );touch_session(&sid);- assert!(!is_session_ended(&sid), "revived id is live again, actions no longer rejected");- assert!(active_session_count() >= 1, "recycled id is counted active again");+ assert!(+ !is_session_ended(&sid),+ "revived id is live again, actions no longer rejected"+ );+ assert!(+ active_session_count() >= 1,+ "recycled id is counted active again"+ );// Clean up so we don't leak the TTL entry past the test.end_session(&sid);@@ -176,7 +201,10 @@ fn idle_ttl_eviction_disposes_like_end_session() {let evicted = evict_idle(Duration::from_millis(5));// (a) the id left the activity map (the shallow signal)...- assert!(evicted.contains(&sid), "idle session past the short TTL is evicted");+ assert!(+ evicted.contains(&sid),+ "idle session past the short TTL is evicted"+ );// (b) ...AND it was disposed exactly like end_session: tombstoned + every// cleanup hook fired once. This is the side-effect assertion, not just// map membership.@@ -208,7 +236,10 @@ fn fresh_session_survives_short_ttl_that_evicts_idle_sibling() {assert!(evicted.contains(&idle), "idle sibling evicted");idle_disposal.assert_fully_disposed_once("idle sibling disposed");- assert!(!evicted.contains(&fresh), "freshly-touched session must survive the sweep");+ assert!(+ !evicted.contains(&fresh),+ "freshly-touched session must survive the sweep"+ );assert!(!is_session_ended(&fresh), "fresh session not tombstoned");fresh_disposal.assert_not_disposed("fresh session not disposed by the sweep");diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/cli.rsindex f608966565..37a920c4ae 100644--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/cli.rs+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/cli.rs@@ -21,7 +21,9 @@ pub struct CliDriver {impl CliDriver {pub fn new() -> Self {- CliDriver { bin: driver_binary() }+ CliDriver {+ bin: driver_binary(),+ }}/// Whether the driver binary exists (caller should skip the test if not).diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/lib.rsindex fa1d415e71..9e33605ba4 100644--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/lib.rs+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/lib.rs@@ -35,11 +35,11 @@pub mod ax;mod browser_fixture;+mod cli;mod driver;pub mod e2e;mod journal;mod mcp;-mod cli;pub mod observer;mod paths;mod raw;@@ -48,13 +48,13 @@ mod response;pub mod sentinel;mod windows_setup;-pub use driver::{BehaviorRecording, Driver};pub use browser_fixture::BrowserFixtureServer;+pub use cli::CliDriver;+pub use driver::{BehaviorRecording, Driver};pub use journal::FixtureJournal;pub use mcp::McpDriver;-pub use raw::RawDriver;-pub use cli::CliDriver;pub use paths::{driver_binary, harness_app, workspace_root};+pub use raw::RawDriver;pub use reaper::{spawn_in_job, ChildReaper};pub use response::ToolResponse;diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rsindex 0a779a16cd..c9ea0c8a6e 100644--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs@@ -400,7 +400,10 @@ fn update_behavior_video_status(output_dir: &std::path::Path, status: &str) {if let Some(field) = timestamp_field {manifest["behavior_video"][field] = Value::from(unix_ms());}- let _ = std::fs::write(path, serde_json::to_vec_pretty(&manifest).unwrap_or_default());+ let _ = std::fs::write(+ path,+ serde_json::to_vec_pretty(&manifest).unwrap_or_default(),+ );}fn mark_behavior_video_baseline_ready(output_dir: &std::path::Path) {@@ -412,7 +415,10 @@ fn mark_behavior_video_baseline_ready(output_dir: &std::path::Path) {return;};manifest["behavior_video"]["baseline_ready_at_unix_ms"] = Value::from(unix_ms());- let _ = std::fs::write(path, serde_json::to_vec_pretty(&manifest).unwrap_or_default());+ let _ = std::fs::write(+ path,+ serde_json::to_vec_pretty(&manifest).unwrap_or_default(),+ );}fn unix_ms() -> u64 {diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer.rsindex 778f333822..dd920f6d54 100644--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer.rs+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer.rs@@ -705,12 +705,7 @@ pub mod macos {}}- fn row_occludes_target(- cover: Bounds,- target: Bounds,- display: Bounds,- tolerance: f64,- ) -> bool {+ fn row_occludes_target(cover: Bounds, target: Bounds, display: Bounds, tolerance: f64) -> bool {if cover.fully_contains(target, tolerance) {return true;}diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rsindex 7943a3e9c9..9e37fe0f87 100644--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs@@ -42,7 +42,11 @@ impl RawDriver {.ok()?;let stdin = child.stdin.take().unwrap();let stdout = BufReader::new(child.stdout.take().unwrap());- Some(RawDriver { child, stdin, stdout })+ Some(RawDriver {+ child,+ stdin,+ stdout,+ })}/// Write one JSON-RPC frame (newline-delimited) and flush.@@ -55,7 +59,9 @@ impl RawDriver {/// (a malformed or missing response is a protocol-test failure).pub fn recv(&mut self) -> Value {let mut line = String::new();- self.stdout.read_line(&mut line).expect("read response line");+ self.stdout+ .read_line(&mut line)+ .expect("read response line");serde_json::from_str(line.trim()).expect("parse JSON response")}}diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/windows_setup.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/windows_setup.rsindex 3425190602..cf70395351 100644--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/windows_setup.rs+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/windows_setup.rs@@ -14,8 +14,8 @@ fn is_hosted_runner_console(title: &str, class_name: &str) -> bool {"runner.worker","github actions runner",]- .iter()- .any(|marker| title.contains(marker))+ .iter()+ .any(|marker| title.contains(marker))}#[cfg(target_os = "windows")]diff --git a/libs/cua-driver/rust/crates/cua-driver-uia/src/main.rs b/libs/cua-driver/rust/crates/cua-driver-uia/src/main.rsindex bd3ea9608c..95e758ba19 100644--- a/libs/cua-driver/rust/crates/cua-driver-uia/src/main.rs+++ b/libs/cua-driver/rust/crates/cua-driver-uia/src/main.rs@@ -49,10 +49,20 @@ struct PipeResponse {#[cfg(target_os = "windows")]impl PipeResponse {fn ok(result: serde_json::Value) -> Self {- Self { ok: true, result: Some(result), error: None, exit_code: None }+ Self {+ ok: true,+ result: Some(result),+ error: None,+ exit_code: None,+ }}fn err(msg: impl Into<String>, code: i32) -> Self {- Self { ok: false, result: None, error: Some(msg.into()), exit_code: Some(code) }+ Self {+ ok: false,+ result: None,+ error: Some(msg.into()),+ exit_code: Some(code),+ }}}@@ -90,7 +100,9 @@ async fn async_main() -> anyhow::Result<()> {.create(PIPE_PATH).map_err(|e| anyhow::anyhow!("create named pipe {PIPE_PATH}: {e}"))?;- server.connect().await+ server+ .connect()+ .await.map_err(|e| anyhow::anyhow!("named pipe connect: {e}"))?;let reg = registry.clone();@@ -105,9 +117,12 @@ async fn async_main() -> anyhow::Result<()> {let _ = writer.write_all((serde_json::to_string(&PipeResponse::err(- format!("JSON parse error: {e}"), 65,- )).unwrap() + "\n")- .as_bytes(),+ format!("JSON parse error: {e}"),+ 65,+ ))+ .unwrap()+ + "\n")+ .as_bytes(),).await;continue;@@ -130,16 +145,19 @@ async fn handle_request() -> PipeResponse {match req.method.as_str() {"list" => {- let tools: Vec<serde_json::Value> = reg.iter_defs()- .map(|(name, def)| serde_json::json!({- "name": name,- "description": def.description,- "input_schema": def.input_schema,- "read_only": def.read_only,- "destructive": def.destructive,- "idempotent": def.idempotent,- "open_world": def.open_world,- }))+ let tools: Vec<serde_json::Value> = reg+ .iter_defs()+ .map(|(name, def)| {+ serde_json::json!({+ "name": name,+ "description": def.description,+ "input_schema": def.input_schema,+ "read_only": def.read_only,+ "destructive": def.destructive,+ "idempotent": def.idempotent,+ "open_world": def.open_world,+ })+ }).collect();PipeResponse::ok(serde_json::json!({ "tools": tools }))}@@ -156,29 +174,48 @@ async fn handle_request(}"call" => {let raw = req.name.as_deref().unwrap_or("").to_owned();- let tool_name = if raw == "type_text_chars" { "type_text".to_owned() } else { raw };- let args = req.args.unwrap_or(serde_json::Value::Object(serde_json::Map::new()));+ let tool_name = if raw == "type_text_chars" {+ "type_text".to_owned()+ } else {+ raw+ };+ let args = req+ .args+ .unwrap_or(serde_json::Value::Object(serde_json::Map::new()));if reg.get_def(&tool_name).is_none() {return PipeResponse::err(format!("Unknown tool: {tool_name}"), 64);}let result = reg.invoke(&tool_name, args).await;let is_err = result.is_error.unwrap_or(false);- let content: Vec<serde_json::Value> = result.content.iter().map(|c| match c {- cua_driver_core::protocol::Content::Text { text, .. } =>- serde_json::json!({"type":"text","text":text}),- cua_driver_core::protocol::Content::Image { data, mime_type, .. } =>- serde_json::json!({"type":"image","data":data,"mimeType":mime_type}),- }).collect();+ let content: Vec<serde_json::Value> = result+ .content+ .iter()+ .map(|c| match c {+ cua_driver_core::protocol::Content::Text { text, .. } => {+ serde_json::json!({"type":"text","text":text})+ }+ cua_driver_core::protocol::Content::Image {+ data, mime_type, ..+ } => serde_json::json!({"type":"image","data":data,"mimeType":mime_type}),+ })+ .collect();let mut result_obj = serde_json::json!({"content": content, "isError": is_err});if let Some(sc) = result.structured_content {result_obj["structuredContent"] = sc;}if is_err {- let msg = result.content.iter()- .filter_map(|c| if let cua_driver_core::protocol::Content::Text { text, .. } = c {- Some(text.as_str())- } else { None })- .collect::<Vec<_>>().join("\n");+ let msg = result+ .content+ .iter()+ .filter_map(|c| {+ if let cua_driver_core::protocol::Content::Text { text, .. } = c {+ Some(text.as_str())+ } else {+ None+ }+ })+ .collect::<Vec<_>>()+ .join("\n");PipeResponse::err(msg, 1)} else {PipeResponse::ok(result_obj)@@ -188,7 +225,9 @@ async fn handle_request(// Worker shutdown is unsupported in the prototype — restarting requires// ShellExecute which the main daemon doesn't have a clean path to. Treat// as a no-op for now; the supervising launcher can taskkill the process.- PipeResponse::ok(serde_json::json!({"shutdown": false, "reason": "uia worker ignores shutdown"}))+ PipeResponse::ok(+ serde_json::json!({"shutdown": false, "reason": "uia worker ignores shutdown"}),+ )}other => PipeResponse::err(format!("Unknown method: {other}"), 65),}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/autostart.rs b/libs/cua-driver/rust/crates/cua-driver/src/autostart.rsindex 1d96d736f5..5698ee7e43 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/autostart.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/autostart.rs@@ -240,10 +240,7 @@ Register-ScheduledTask -TaskName 'cua-driver-serve' -Action $action -Trigger $tr// happens INSIDE the elevated process (where it'll succeed on// the first attempt and not re-enter this branch). -Wait so we// can capture the child's exit code.- let inner = format!(- "& \"{}\" autostart enable",- exe.replace('"', "`\"")- );+ let inner = format!("& \"{}\" autostart enable", exe.replace('"', "`\""));let outer = format!("$p = Start-Process -FilePath '{}' -ArgumentList @('-NoProfile','-NonInteractive','-Command',{}) -Verb RunAs -Wait -PassThru; exit $p.ExitCode","powershell.exe",@@ -353,8 +350,7 @@ Register-ScheduledTask -TaskName 'cua-driver-serve' -Action $action -Trigger $trmod platform {use super::*;- const NOT_YET: &str =- "cua-driver autostart is currently Windows-only. macOS users: see \+ const NOT_YET: &str = "cua-driver autostart is currently Windows-only. macOS users: see \libs/cua-driver/scripts/install-local.sh --autostart for the \LaunchAgent recipe. Linux users: same script registers a systemd \--user unit. A cross-platform impl is tracked as a follow-up.";@@ -380,13 +376,17 @@ mod platform {/// (main) doesn't need to plumb back an exit code for every subcommand.pub fn run_autostart_cmd(subcommand: &str) {let (verb_result, success_text): (Result<()>, String) = match subcommand {- "enable" => (enable(), format!(- "Registered autostart entry '{TASK_NAME}'.\n \+ "enable" => (+ enable(),+ format!(+ "Registered autostart entry '{TASK_NAME}'.\n \cua-driver serve will start at every interactive logon."- )),- "disable" => (disable(), format!(- "Removed autostart entry '{TASK_NAME}' (no-op if it was already absent)."- )),+ ),+ ),+ "disable" => (+ disable(),+ format!("Removed autostart entry '{TASK_NAME}' (no-op if it was already absent)."),+ ),"status" => match status() {Ok(s) => {println!("{}", s.tag());@@ -397,9 +397,10 @@ pub fn run_autostart_cmd(subcommand: &str) {std::process::exit(1);}},- "kick" => (kick(), format!(- "Started autostart entry '{TASK_NAME}' for the current session."- )),+ "kick" => (+ kick(),+ format!("Started autostart entry '{TASK_NAME}' for the current session."),+ ),other => {eprintln!("Unknown autostart subcommand: {other:?}");eprintln!("Usage: cua-driver autostart {{enable|disable|status|kick}}");diff --git a/libs/cua-driver/rust/crates/cua-driver/src/check_update_tool.rs b/libs/cua-driver/rust/crates/cua-driver/src/check_update_tool.rsindex 3cd682b05a..6914744268 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/check_update_tool.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/check_update_tool.rs@@ -30,12 +30,11 @@ static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();fn def() -> &'static ToolDef {DEF.get_or_init(|| ToolDef {name: "check_for_update".into(),- description:- "Check whether a newer cua-driver-rs release is available on GitHub. \+ description: "Check whether a newer cua-driver-rs release is available on GitHub. \Returns the current and latest versions, an `update_available` boolean, \the install one-liner, and the release notes URL. Read-only — never \installs. Mirror of `cua-driver check-update --json`."- .into(),+ .into(),input_schema: serde_json::json!({"type": "object","properties": {},@@ -61,11 +60,9 @@ impl Tool for CheckForUpdateTool {// The fetch hits the network with a 4s timeout — run on a// blocking pool so the MCP server's tokio runtime keeps// multiplexing other tool calls during the round-trip.- let state = tokio::task::spawn_blocking(|| {- crate::version_check::check_update_state(false)- })- .await- .expect("version_check::check_update_state never panics");+ let state = tokio::task::spawn_blocking(|| crate::version_check::check_update_state(false))+ .await+ .expect("version_check::check_update_state never panics");let summary = if let Some(err) = &state.error {format!("Update check failed: {err}")@@ -79,8 +76,7 @@ impl Tool for CheckForUpdateTool {format!("Up to date (cua-driver {}).", state.current_version)};- let structured = serde_json::to_value(&state)- .unwrap_or_else(|_| serde_json::json!({}));+ let structured = serde_json::to_value(&state).unwrap_or_else(|_| serde_json::json!({}));ToolResult::text(summary).with_structured(structured)}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver/src/cli.rsindex a6225f7653..0011faf3c8 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs@@ -233,7 +233,10 @@ fn positional_args(args: &[String]) -> Vec<&str> {}fn finite_command_name_from_args(args: &[String]) -> Option<&'static str> {- if args.iter().any(|arg| matches!(arg.as_str(), "--help" | "-h" | "--version" | "-V")) {+ if args+ .iter()+ .any(|arg| matches!(arg.as_str(), "--help" | "-h" | "--version" | "-V"))+ {return None;}let positionals = positional_args(args);@@ -864,7 +867,9 @@ pub fn run_browser_approve(eprintln!(" browser pid: {pid}");eprintln!(" native window id: {window_id}");eprintln!(" caller session: {session}");- eprintln!("This grant stays in daemon memory, expires, and never authorizes arbitrary dialogs.");+ eprintln!(+ "This grant stays in daemon memory, expires, and never authorizes arbitrary dialogs."+ );eprint!("Type APPROVE to continue: ");let _ = std::io::stderr().flush();let mut confirmation = String::new();@@ -3669,22 +3674,52 @@ mod tests {#[test]fn finite_operations_are_closed_and_ignore_values() {- assert_eq!(finite_operation_from_args(&args(&["recording", "start", "/private/path"])), "start");- assert_eq!(finite_operation_from_args(&args(&["config", "set", "private.key", "private-value"])), "set");+ assert_eq!(+ finite_operation_from_args(&args(&["recording", "start", "/private/path"])),+ "start"+ );+ assert_eq!(+ finite_operation_from_args(&args(&["config", "set", "private.key", "private-value"])),+ "set"+ );assert_eq!(finite_operation_from_args(&args(&["skills"])), "status");- assert_eq!(finite_operation_from_args(&args(&["update", "--apply"])), "apply");+ assert_eq!(+ finite_operation_from_args(&args(&["update", "--apply"])),+ "apply"+ );assert_eq!(finite_operation_from_args(&args(&["update"])), "check_only");- assert_eq!(finite_operation_from_args(&args(&["doctor", "private-value"])), "not_applicable");- assert_eq!(finite_operation_from_args(&args(&["recording", "private-value"])), "other");+ assert_eq!(+ finite_operation_from_args(&args(&["doctor", "private-value"])),+ "not_applicable"+ );+ assert_eq!(+ finite_operation_from_args(&args(&["recording", "private-value"])),+ "other"+ );}#[test]fn finite_mcp_config_clients_are_closed_before_worker_handoff() {- assert_eq!(finite_client_kind_from_args(&args(&["mcp-config"])), "generic");- assert_eq!(finite_client_kind_from_args(&args(&["mcp-config", "--client", "claude-code"])), "claude_code");- assert_eq!(finite_client_kind_from_args(&args(&["mcp-config", "--client", "antigravity"])), "antigravity");- assert_eq!(finite_client_kind_from_args(&args(&["mcp-config", "--client", "/private/client"])), "other");- assert_eq!(finite_client_kind_from_args(&args(&["doctor", "--client", "claude"])), "not_applicable");+ assert_eq!(+ finite_client_kind_from_args(&args(&["mcp-config"])),+ "generic"+ );+ assert_eq!(+ finite_client_kind_from_args(&args(&["mcp-config", "--client", "claude-code"])),+ "claude_code"+ );+ assert_eq!(+ finite_client_kind_from_args(&args(&["mcp-config", "--client", "antigravity"])),+ "antigravity"+ );+ assert_eq!(+ finite_client_kind_from_args(&args(&["mcp-config", "--client", "/private/client"])),+ "other"+ );+ assert_eq!(+ finite_client_kind_from_args(&args(&["doctor", "--client", "claude"])),+ "not_applicable"+ );}#[test]diff --git a/libs/cua-driver/rust/crates/cua-driver/src/doctor.rs b/libs/cua-driver/rust/crates/cua-driver/src/doctor.rsindex e1ef4e9bfe..5c714d3752 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/doctor.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/doctor.rs@@ -58,13 +58,28 @@ pub struct Probe {impl Probe {pub fn ok(label: impl Into<String>, message: impl Into<String>) -> Self {- Self { label: label.into(), status: Status::Ok, message: message.into(), detail: None }+ Self {+ label: label.into(),+ status: Status::Ok,+ message: message.into(),+ detail: None,+ }}pub fn warn(label: impl Into<String>, message: impl Into<String>) -> Self {- Self { label: label.into(), status: Status::Warn, message: message.into(), detail: None }+ Self {+ label: label.into(),+ status: Status::Warn,+ message: message.into(),+ detail: None,+ }}pub fn err(label: impl Into<String>, message: impl Into<String>) -> Self {- Self { label: label.into(), status: Status::Err, message: message.into(), detail: None }+ Self {+ label: label.into(),+ status: Status::Err,+ message: message.into(),+ detail: None,+ }}pub fn with_detail(mut self, detail: impl Into<String>) -> Self {self.detail = Some(detail.into());@@ -120,8 +135,14 @@ impl Report {.map(|p| {let mut obj = serde_json::Map::new();obj.insert("label".into(), serde_json::Value::String(p.label.clone()));- obj.insert("status".into(), serde_json::Value::String(p.status.tag().into()));- obj.insert("message".into(), serde_json::Value::String(p.message.clone()));+ obj.insert(+ "status".into(),+ serde_json::Value::String(p.status.tag().into()),+ );+ obj.insert(+ "message".into(),+ serde_json::Value::String(p.message.clone()),+ );if let Some(d) = &p.detail {obj.insert("detail".into(), serde_json::Value::String(d.clone()));}@@ -160,8 +181,7 @@ fn probe_install_layout() -> Probe {match exe {Err(e) => Probe::err("install dir", format!("could not resolve current_exe: {e}")),Ok(path) => {- let canonical = std::fs::canonicalize(&path)- .unwrap_or_else(|_| path.clone());+ let canonical = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());let mut detail = String::new();if path != canonical {detail.push_str(&format!("argv exe: {}\n", path.display()));@@ -187,7 +207,10 @@ fn probe_home_dir() -> Probe {if !cua_home.exists() {return Probe::warn("home dir",- format!("{} does not exist yet (created on first run)", cua_home.display()),+ format!(+ "{} does not exist yet (created on first run)",+ cua_home.display()+ ),);}let releases = cua_home.join("packages").join("releases");@@ -216,10 +239,20 @@ fn probe_home_dir() -> Probe {fn probe_telemetry() -> Probe {let status = crate::telemetry::status();if status.enabled {- let identity = if status.installation_id_present { "install-id present" } else { "install-id not yet generated" };- Probe::ok("telemetry", format!("enabled via {} ({identity})", status.source))+ let identity = if status.installation_id_present {+ "install-id present"+ } else {+ "install-id not yet generated"+ };+ Probe::ok(+ "telemetry",+ format!("enabled via {} ({identity})", status.source),+ )} else {- Probe::ok("telemetry", format!("disabled via {} (installation ID retained)", status.source))+ Probe::ok(+ "telemetry",+ format!("disabled via {} (installation ID retained)", status.source),+ )}}@@ -387,7 +420,9 @@ fn append_platform_probes(report: &mut Report) {// (XWayland leaves DISPLAY pointing at the X server XWayland exposes,// but the actual session is still Wayland).let display = std::env::var("DISPLAY").ok().filter(|v| !v.is_empty());- let wayland = std::env::var("WAYLAND_DISPLAY").ok().filter(|v| !v.is_empty());+ let wayland = std::env::var("WAYLAND_DISPLAY")+ .ok()+ .filter(|v| !v.is_empty());match (display.as_deref(), wayland.as_deref()) {(None, None) => report.push(Probe::warn(@@ -422,15 +457,17 @@ fn append_platform_probes(report: &mut Report) {// open — `list_windows` doesn't distinguish the two — so the warning// hedges instead of asserting a connection failure.match platform_linux::x11::list_windows(None) {- v if v.is_empty() => report.push(- Probe::warn(- "X11 connection",- "no top-level windows returned (possible disconnected or inaccessible X11 display)",- ),- ),+ v if v.is_empty() => report.push(Probe::warn(+ "X11 connection",+ "no top-level windows returned (possible disconnected or inaccessible X11 display)",+ )),v => report.push(Probe::ok("X11 connection",- format!("connected, {} visible top-level window{}", v.len(), if v.len() == 1 { "" } else { "s" }),+ format!(+ "connected, {} visible top-level window{}",+ v.len(),+ if v.len() == 1 { "" } else { "s" }+ ),)),}@@ -440,7 +477,10 @@ fn append_platform_probes(report: &mut Report) {// org.a11y.Bus name.let at_spi_env = std::env::var("AT_SPI_BUS").ok().filter(|v| !v.is_empty());match at_spi_env {- Some(addr) => report.push(Probe::ok("AT-SPI", format!("bus address present (AT_SPI_BUS={addr})"))),+ Some(addr) => report.push(Probe::ok(+ "AT-SPI",+ format!("bus address present (AT_SPI_BUS={addr})"),+ )),None => {// Bounded wait — a hung session bus daemon would otherwise// block `doctor` indefinitely. 3s is enough for a healthy@@ -449,7 +489,10 @@ fn append_platform_probes(report: &mut Report) {// as a warning instead of looking like the binary froze.let bus_ok = probe_at_spi_bus_via_gdbus(std::time::Duration::from_secs(3));if bus_ok {- report.push(Probe::ok("AT-SPI", "org.a11y.Bus reachable via session bus"));+ report.push(Probe::ok(+ "AT-SPI",+ "org.a11y.Bus reachable via session bus",+ ));} else {report.push(Probe::warn("AT-SPI", "accessibility bus not reachable")@@ -516,7 +559,10 @@ fn append_platform_probes(report: &mut Report) {fn append_platform_probes(report: &mut Report) {report.push(Probe::warn("platform",- format!("no platform-specific probes implemented for {}", std::env::consts::OS),+ format!(+ "no platform-specific probes implemented for {}",+ std::env::consts::OS+ ),));}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/main.rs b/libs/cua-driver/rust/crates/cua-driver/src/main.rsindex 443247603d..ee0b0d1145 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/main.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/main.rs@@ -311,9 +311,8 @@ fn main() {claude_code_compat,} => {responsibility::reexec_disclaimed_if_needed();- let gate_opts = platform_macos::permissions::GateOpts::from_env_and_flag(- no_permissions_gate,- );+ let gate_opts =+ platform_macos::permissions::GateOpts::from_env_and_flag(no_permissions_gate);if let Some((progress, context)) =platform_macos::permissions::gate::prepare_telemetry_context(gate_opts.opt_out){@@ -605,16 +604,16 @@ fn main() {// attribution and forwards stdio MCP through its socket.// Issue #1525 / mirror of Swift PR #1479.if cli::should_use_daemon_proxy(no_daemon_relaunch) {- if let Err(e) = cli::run_mcp_via_daemon_proxy(- socket,- claude_code_compat,- |daemon, success| telemetry::capture_mcp_startup_completed(- "daemon_proxy",- daemon.telemetry_value(),- success,- startup_started.elapsed(),- ),- ) {+ if let Err(e) =+ cli::run_mcp_via_daemon_proxy(socket, claude_code_compat, |daemon, success| {+ telemetry::capture_mcp_startup_completed(+ "daemon_proxy",+ daemon.telemetry_value(),+ success,+ startup_started.elapsed(),+ )+ })+ {eprintln!("cua-driver-rs: {e}");telemetry::flush_pending(std::time::Duration::from_millis(750));std::process::exit(1);@@ -937,16 +936,16 @@ fn main() -> anyhow::Result<()> {// Code over SSH lands in Session 0 and every desktop// tool returns empty. See `cli::should_use_daemon_proxy`.if cli::should_use_daemon_proxy(no_daemon_relaunch) {- if let Err(e) = cli::run_mcp_via_daemon_proxy(- socket,- claude_code_compat,- |daemon, success| telemetry::capture_mcp_startup_completed(- "daemon_proxy",- daemon.telemetry_value(),- success,- startup_started.elapsed(),- ),- ) {+ if let Err(e) =+ cli::run_mcp_via_daemon_proxy(socket, claude_code_compat, |daemon, success| {+ telemetry::capture_mcp_startup_completed(+ "daemon_proxy",+ daemon.telemetry_value(),+ success,+ startup_started.elapsed(),+ )+ })+ {eprintln!("cua-driver-rs: {e}");telemetry::flush_pending(std::time::Duration::from_millis(750));std::process::exit(1);diff --git a/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs b/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rsindex 8b49d049b2..4075598eae 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs@@ -163,8 +163,12 @@ fn serialize(resp: &Response) -> String {/// (so it already works); this keeps config + recording session-scoping/// consistent across transports.fn apply_session_identity(req: &mut Request) {- let Some(params) = req.params.as_mut() else { return };- let Some(args) = params.get_mut("arguments").and_then(|a| a.as_object_mut()) else { return };+ let Some(params) = req.params.as_mut() else {+ return;+ };+ let Some(args) = params.get_mut("arguments").and_then(|a| a.as_object_mut()) else {+ return;+ };let session = args.get("session").and_then(|v| v.as_str())@@ -236,7 +240,12 @@ async fn read_http_request(stream: &mut TcpStream) -> anyhow::Result<Option<Httpif content_length > 0 {stream.read_exact(&mut body).await?;}- Ok(Some(HttpRequest { method, path, body, keep_alive }))+ Ok(Some(HttpRequest {+ method,+ path,+ body,+ keep_alive,+ }))}async fn write_http(diff --git a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rsindex 0573100283..3a48ace21c 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs@@ -34,9 +34,7 @@ use cua_driver_core::server::{use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};use tracing::{debug, error, warn};-use crate::serve::{- is_daemon_listening, send_request, DaemonRequest, ToolObservationOrigin,-};+use crate::serve::{is_daemon_listening, send_request, DaemonRequest, ToolObservationOrigin};/// Run the MCP stdio proxy. Reads JSON-RPC lines from stdin, forwards/// the body of each `tools/list` / `tools/call` to the daemon at@@ -601,8 +599,7 @@ async fn forward_tool_call(name: Some(name.clone()),args: Some(args),session_id: Some(session_id.to_owned()),- observation_origin: daemon_observes_tool_calls- .then_some(ToolObservationOrigin::McpProxy),+ observation_origin: daemon_observes_tool_calls.then_some(ToolObservationOrigin::McpProxy),};// The daemon client is sync, so jump to a blocking thread to keepdiff --git a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs b/libs/cua-driver/rust/crates/cua-driver/src/serve.rsindex 90064a9b53..ab79140ab0 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs@@ -31,11 +31,7 @@ fn is_active_proxy_session(session: Option<&str>) -> bool {session.is_some_and(|session| active_proxy_sessions().lock().unwrap().contains(session))}-fn inject_browser_approvals(- tool_name: &str,- args: &mut serde_json::Value,- session: Option<&str>,-) {+fn inject_browser_approvals(tool_name: &str, args: &mut serde_json::Value, session: Option<&str>) {if tool_name == "browser_prepare" && is_active_proxy_session(session) {if let Some(arguments) = args.as_object_mut() {arguments.insert(@@ -86,10 +82,7 @@ fn now_unix_secs() -> u64 {/// Also refreshes the idle-TTL clock for an explicit session (the minted/// fallback is reaped by EOF, not TTL). Returns the effective `_session_id` for/// the resurrection guard.-fn apply_session_identity(- args: &mut serde_json::Value,- minted: &Option<String>,-) -> Option<String> {+fn apply_session_identity(args: &mut serde_json::Value, minted: &Option<String>) -> Option<String> {let explicit = args.as_object().and_then(|o| o.get("session"))@@ -159,9 +152,8 @@ fn spawn_recording_idle_backstop(loop {tick.tick().await;if registry.recording.current_state().enabled {- let idle = now_unix_secs().saturating_sub(- last_activity.load(std::sync::atomic::Ordering::Relaxed),- );+ let idle = now_unix_secs()+ .saturating_sub(last_activity.load(std::sync::atomic::Ordering::Relaxed));if idle >= ttl {tracing::warn!("recording idle {idle}s ≥ {ttl}s TTL; auto-stopping \@@ -178,10 +170,8 @@ fn spawn_recording_idle_backstop(// (SCStream::stop_capture blocks on disk I/O), so run it on a// blocking thread to keep the reactor free (see the EOF reaper).let reg2 = registry.clone();- let _ = tokio::task::spawn_blocking(move || {- reg2.recording.stop_owner(None)- })- .await;+ let _ =+ tokio::task::spawn_blocking(move || reg2.recording.stop_owner(None)).await;}}}@@ -219,7 +209,10 @@ fn spawn_session_idle_sweep() {tick.tick().await;let ended = cua_driver_core::session::evict_idle(ttl);if !ended.is_empty() {- tracing::info!(count = ended.len(), "idle-TTL reclaimed sessions: {ended:?}");+ tracing::info!(+ count = ended.len(),+ "idle-TTL reclaimed sessions: {ended:?}"+ );}}});@@ -355,10 +348,20 @@ pub struct DaemonResponse {impl DaemonResponse {pub fn ok(result: serde_json::Value) -> Self {- Self { ok: true, result: Some(result), error: None, exit_code: None }+ Self {+ ok: true,+ result: Some(result),+ error: None,+ exit_code: None,+ }}pub fn err(msg: impl Into<String>, code: i32) -> Self {- Self { ok: false, result: None, error: Some(msg.into()), exit_code: Some(code) }+ Self {+ ok: false,+ result: None,+ error: Some(msg.into()),+ exit_code: Some(code),+ }}}@@ -392,7 +395,9 @@ fn observe_daemon_result(crate::telemetry::capture_tool_completed(outcome, transport);match response.body {cua_driver_core::protocol::ResponseBody::Result { result } => result,- cua_driver_core::protocol::ResponseBody::Error { .. } => unreachable!("constructed ok response"),+ cua_driver_core::protocol::ResponseBody::Error { .. } => {+ unreachable!("constructed ok response")+ }}}@@ -424,7 +429,9 @@ async fn invoke_daemon_tool(let observation_transport = daemon_observation_transport(&req);let raw_name = req.name.as_deref().unwrap_or("").to_owned();let tool_name = if raw_name == "type_text_chars" {- eprintln!("[cua-driver-rs] deprecated tool name 'type_text_chars' — use 'type_text' instead.");+ eprintln!(+ "[cua-driver-rs] deprecated tool name 'type_text_chars' — use 'type_text' instead."+ );"type_text".to_owned()} else {raw_name@@ -450,8 +457,7 @@ async fn invoke_daemon_tool(});if let Some(sid) = &effective_session {- if !is_session_lifecycle_tool(&tool_name)- && cua_driver_core::session::is_session_ended(sid)+ if !is_session_lifecycle_tool(&tool_name) && cua_driver_core::session::is_session_ended(sid){observe_daemon_error(observation, 1);return DaemonResponse::err(@@ -500,9 +506,7 @@ async fn invoke_daemon_tool(crate::telemetry::Transport::McpHttp => {cua_driver_core::session::SessionTransport::McpHttp}- crate::telemetry::Transport::Cli => {- cua_driver_core::session::SessionTransport::Cli- }+ crate::telemetry::Transport::Cli => cua_driver_core::session::SessionTransport::Cli,crate::telemetry::Transport::Daemon => {cua_driver_core::session::SessionTransport::Daemon}@@ -531,7 +535,11 @@ async fn invoke_daemon_tool(if let Some(structured) = result.structured_content {result_value["structuredContent"] = structured;}- DaemonResponse::ok(observe_daemon_result(observation, session_context, result_value))+ DaemonResponse::ok(observe_daemon_result(+ observation,+ session_context,+ result_value,+ ))}// ── Client ────────────────────────────────────────────────────────────────────@@ -738,8 +746,8 @@ pub async fn run_serve(// Remove stale socket file (from a crashed previous daemon).let _ = std::fs::remove_file(socket_path);- let listener = UnixListener::bind(socket_path)- .map_err(|e| anyhow::anyhow!("bind {socket_path}: {e}"))?;+ let listener =+ UnixListener::bind(socket_path).map_err(|e| anyhow::anyhow!("bind {socket_path}: {e}"))?;eprintln!("Cua Driver daemon listening on {socket_path}");@@ -1085,9 +1093,8 @@ fn maybe_spawn_uia_worker() {return;}let uia_str = uia.display().to_string();- let cmd = format!(- "(New-Object -ComObject Shell.Application).ShellExecute('{uia_str}','','','',0)"- );+ let cmd =+ format!("(New-Object -ComObject Shell.Application).ShellExecute('{uia_str}','','','',0)");match std::process::Command::new("powershell.exe").args(["-NoProfile", "-WindowStyle", "Hidden", "-Command", &cmd]).spawn()@@ -1149,8 +1156,7 @@ fn is_self_at_high_il() -> bool {/// pointer (which the caller must keep alive for the lifetime of the/// pipe-server, then free via `LocalFree`).#[cfg(target_os = "windows")]-unsafe fn build_open_pipe_security_attrs()- -> Option<(SecurityAttributesRaw, *mut std::ffi::c_void)>+unsafe fn build_open_pipe_security_attrs() -> Option<(SecurityAttributesRaw, *mut std::ffi::c_void)>{#[link(name = "advapi32")]extern "system" {@@ -1483,7 +1489,8 @@ pub fn run_serve_cmd(// Fail fast if another daemon is already running.if is_daemon_listening(&socket_path) {- let pid_hint = pid_file_path.as_deref()+ let pid_hint = pid_file_path+ .as_deref().and_then(|p| read_pid_file(p)).map(|pid| format!(" (pid {pid})")).unwrap_or_default();@@ -1502,10 +1509,7 @@ pub fn run_serve_cmd(// hours of debugging tools that are working as designed.#[cfg(target_os = "windows")]{- if matches!(- platform_windows::diagnostics::current_session_id(),- Some(0),- ) {+ if matches!(platform_windows::diagnostics::current_session_id(), Some(0),) {eprintln!("WARNING: cua-driver serve is starting in Session 0 (services). \Window-driving tools — click, type_text, screenshot, \@@ -1524,11 +1528,7 @@ pub fn run_serve_cmd(.build().expect("tokio runtime");- if let Err(e) = rt.block_on(run_serve(- registry,- &socket_path,- pid_file_path.as_deref(),- )) {+ if let Err(e) = rt.block_on(run_serve(registry, &socket_path, pid_file_path.as_deref())) {eprintln!("cua-driver serve error: {e}");std::process::exit(1);}@@ -1700,10 +1700,11 @@ mod gate_tests {// 1. LIVE session call → tool runs.let socket1 = socket.clone();let s1 = sid.to_owned();- let resp = tokio::task::spawn_blocking(move || send_request(&socket1, &call_req(Some(&s1))))- .await- .unwrap()- .expect("live call response");+ let resp =+ tokio::task::spawn_blocking(move || send_request(&socket1, &call_req(Some(&s1))))+ .await+ .unwrap()+ .expect("live call response");assert!(resp.ok, "live-session call should succeed");assert_eq!(PROBE_INVOCATIONS.load(Ordering::SeqCst),@@ -1731,11 +1732,15 @@ mod gate_tests {// success that silently does nothing).let socket3 = socket.clone();let s3 = sid.to_owned();- let resp = tokio::task::spawn_blocking(move || send_request(&socket3, &call_req(Some(&s3))))- .await- .unwrap()- .expect("ended call response");- assert!(!resp.ok, "ended-session call must be rejected loudly (not ok)");+ let resp =+ tokio::task::spawn_blocking(move || send_request(&socket3, &call_req(Some(&s3))))+ .await+ .unwrap()+ .expect("ended call response");+ assert!(+ !resp.ok,+ "ended-session call must be rejected loudly (not ok)"+ );assert!(resp.error.as_deref().unwrap_or("").contains("has ended"),"rejection must explain the session ended; got {:?}",@@ -1763,15 +1768,19 @@ mod gate_tests {.await.unwrap().expect("start_session response");- assert!(resp.ok, "start_session must run even for an ended id (lifecycle-exempt)");+ assert!(+ resp.ok,+ "start_session must run even for an ended id (lifecycle-exempt)"+ );// 3c. A call on the revived id now RUNS again.let socket3c = socket.clone();let s3c = sid.to_owned();- let resp = tokio::task::spawn_blocking(move || send_request(&socket3c, &call_req(Some(&s3c))))- .await- .unwrap()- .expect("revived call response");+ let resp =+ tokio::task::spawn_blocking(move || send_request(&socket3c, &call_req(Some(&s3c))))+ .await+ .unwrap()+ .expect("revived call response");assert!(resp.ok, "call on a revived session should succeed");assert_eq!(PROBE_INVOCATIONS.load(Ordering::SeqCst),@@ -1845,8 +1854,7 @@ mod telemetry_routing_tests {.unwrap();assert_eq!(legacy.observation_origin, None);- let current = serde_json::to_value(request(Some(ToolObservationOrigin::McpProxy)))- .unwrap();+ let current = serde_json::to_value(request(Some(ToolObservationOrigin::McpProxy))).unwrap();assert_eq!(current["observation_origin"], "mcp_proxy");}}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/skills.rs b/libs/cua-driver/rust/crates/cua-driver/src/skills.rsindex e777c187ea..68b8f900a2 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/skills.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/skills.rs@@ -100,13 +100,21 @@ fn excluded_platform_docs(all_platforms: bool) -> &'static [&'static str] {return &[];}#[cfg(target_os = "windows")]- { &["LINUX.md", "MACOS.md"] }+ {+ &["LINUX.md", "MACOS.md"]+ }#[cfg(target_os = "linux")]- { &["WINDOWS.md", "MACOS.md"] }+ {+ &["WINDOWS.md", "MACOS.md"]+ }#[cfg(target_os = "macos")]- { &["WINDOWS.md", "LINUX.md"] }+ {+ &["WINDOWS.md", "LINUX.md"]+ }#[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]- { &[] }+ {+ &[]+ }}/// True when the basename matches one of the excluded platform docs.@@ -139,14 +147,13 @@ fn home_dir() -> Result<PathBuf> {}#[cfg(windows)]{- let userprofile = std::env::var("USERPROFILE")- .map_err(|_| anyhow!("USERPROFILE not set"))?;+ let userprofile =+ std::env::var("USERPROFILE").map_err(|_| anyhow!("USERPROFILE not set"))?;return Ok(PathBuf::from(userprofile).join(HOME_SUBDIRECTORY));}#[cfg(not(windows))]{- let home = std::env::var("HOME")- .map_err(|_| anyhow!("HOME not set"))?;+ let home = std::env::var("HOME").map_err(|_| anyhow!("HOME not set"))?;return Ok(PathBuf::from(home).join(HOME_SUBDIRECTORY));}}@@ -194,17 +201,35 @@ enum AgentParent {}const AGENTS: &[Agent] = &[- Agent { label: "Claude Code", parent: AgentParent::Home(".claude/skills") },- Agent { label: "Codex", parent: AgentParent::Home(".agents/skills") },- Agent { label: "OpenClaw", parent: AgentParent::Home(".openclaw/skills") },+ Agent {+ label: "Claude Code",+ parent: AgentParent::Home(".claude/skills"),+ },+ Agent {+ label: "Codex",+ parent: AgentParent::Home(".agents/skills"),+ },+ Agent {+ label: "OpenClaw",+ parent: AgentParent::Home(".openclaw/skills"),+ },#[cfg(windows)]- Agent { label: "OpenCode", parent: AgentParent::AppData("opencode/skills") },+ Agent {+ label: "OpenCode",+ parent: AgentParent::AppData("opencode/skills"),+ },#[cfg(not(windows))]- Agent { label: "OpenCode", parent: AgentParent::Home(".config/opencode/skills") },+ Agent {+ label: "OpenCode",+ parent: AgentParent::Home(".config/opencode/skills"),+ },// Antigravity CLI + Antigravity IDE share the `.gemini/skills/` dir// (the same path Gemini CLI used pre-May-2026). Registering the// single shared path means both surfaces pick up the same symlink.- Agent { label: "Antigravity", parent: AgentParent::Home(".gemini/skills") },+ Agent {+ label: "Antigravity",+ parent: AgentParent::Home(".gemini/skills"),+ },// Hermes (NousResearch/hermes-agent) resolves user skills from// `~/.hermes/skills/` at agent load time — the same directory its// `/skills install …` slash command and `hermes skills install`@@ -213,7 +238,10 @@ const AGENTS: &[Agent] = &[// cua-driver pack symlinked here adds the platform-specific deep// dives (MACOS.md / WINDOWS.md / LINUX.md / RECORDING.md /// BROWSER.md) that Hermes deliberately doesn't clone.- Agent { label: "Hermes", parent: AgentParent::Home(".hermes/skills") },+ Agent {+ label: "Hermes",+ parent: AgentParent::Home(".hermes/skills"),+ },];impl Agent {@@ -221,20 +249,17 @@ impl Agent {match self.parent {AgentParent::Home(seg) => {#[cfg(windows)]- let base = std::env::var("USERPROFILE")- .map_err(|_| anyhow!("USERPROFILE not set"))?;+ let base =+ std::env::var("USERPROFILE").map_err(|_| anyhow!("USERPROFILE not set"))?;#[cfg(not(windows))]- let base = std::env::var("HOME")- .map_err(|_| anyhow!("HOME not set"))?;+ let base = std::env::var("HOME").map_err(|_| anyhow!("HOME not set"))?;Ok(PathBuf::from(base).join(seg.replace('/', std::path::MAIN_SEPARATOR_STR)))}AgentParent::AppData(seg) => {#[cfg(windows)]- let base = std::env::var("APPDATA")- .map_err(|_| anyhow!("APPDATA not set"))?;+ let base = std::env::var("APPDATA").map_err(|_| anyhow!("APPDATA not set"))?;#[cfg(not(windows))]- let base = std::env::var("HOME")- .map_err(|_| anyhow!("HOME not set"))?;+ let base = std::env::var("HOME").map_err(|_| anyhow!("HOME not set"))?;Ok(PathBuf::from(base).join(seg.replace('/', std::path::MAIN_SEPARATOR_STR)))}}@@ -249,10 +274,10 @@ impl Agent {pub fn run(subcommand: &str, flags: &[String]) {let result = match subcommand {"install" => install(flags, false),- "update" => install(flags, true),+ "update" => install(flags, true),"uninstall" => uninstall(flags),- "status" => status(),- "path" => print_path(),+ "status" => status(),+ "path" => print_path(),other => {eprintln!("Unknown skills subcommand: {other:?}");eprintln!("Usage: cua-driver skills {{install|update|uninstall|status|path}}");@@ -273,7 +298,10 @@ pub fn run(subcommand: &str, flags: &[String]) {fn install(flags: &[String], force: bool) -> Result<()> {let from_main = flags.iter().any(|f| f == "--from=main")|| (flags.iter().any(|f| f == "--from")- && flags.iter().zip(flags.iter().skip(1)).any(|(a, b)| a == "--from" && b == "main"));+ && flags+ .iter()+ .zip(flags.iter().skip(1))+ .any(|(a, b)| a == "--from" && b == "main"));let force = force || flags.iter().any(|f| f == "--force");// `--all-platforms` opts INTO keeping LINUX.md / MACOS.md / WINDOWS.md// for every host. Default is host-only — only the matching platform's@@ -294,7 +322,10 @@ fn install(flags: &[String], force: bool) -> Result<()> {.with_context(|| format!("failed to fetch skill pack to {}", local.display()))?;println!("✅ Skill pack at {}", local.display());} else {- println!("✅ Skill pack already at {} (use `cua-driver skills update` to refresh)", local.display());+ println!(+ "✅ Skill pack already at {} (use `cua-driver skills update` to refresh)",+ local.display()+ );}let mut linked_any = false;@@ -335,10 +366,15 @@ fn sweep_legacy_skill_pack() {let legacy_local = home.join("skills").join(LEGACY_SKILL_PACK_NAME);if legacy_local.exists() {if let Err(e) = fs::remove_dir_all(&legacy_local) {- eprintln!(" warning: could not remove legacy local pack at {}: {e}",- legacy_local.display());+ eprintln!(+ " warning: could not remove legacy local pack at {}: {e}",+ legacy_local.display()+ );} else {- println!(" cleaned up legacy local pack at {}", legacy_local.display());+ println!(+ " cleaned up legacy local pack at {}",+ legacy_local.display()+ );}}}@@ -350,8 +386,10 @@ fn sweep_legacy_skill_pack() {let dir = legacy_skills_dir.join(name);if dir.exists() {if let Err(e) = fs::remove_dir_all(&dir) {- eprintln!(" warning: could not remove legacy pack at {}: {e}",- dir.display());+ eprintln!(+ " warning: could not remove legacy pack at {}: {e}",+ dir.display()+ );} else {println!(" cleaned up legacy local pack at {}", dir.display());}@@ -379,10 +417,17 @@ fn sweep_legacy_skill_pack() {continue;}if let Err(e) = remove_link(&legacy_link) {- eprintln!(" warning: could not remove legacy {} link at {}: {e}",- agent.label, legacy_link.display());+ eprintln!(+ " warning: could not remove legacy {} link at {}: {e}",+ agent.label,+ legacy_link.display()+ );} else {- println!(" cleaned up legacy {} link at {}", agent.label, legacy_link.display());+ println!(+ " cleaned up legacy {} link at {}",+ agent.label,+ legacy_link.display()+ );}}}@@ -406,9 +451,13 @@ fn link_agent(agent: Agent, local_skill_dir: &Path) -> Result<bool> {// the signature of case 3. We then check `is_symlink_or_junction`// before deleting, so we never touch a real user directory.let has_metadata = link.symlink_metadata().is_ok();- let resolves = link.exists();+ let resolves = link.exists();if has_metadata && resolves {- println!(" {} skill link already exists at {} (skipping)", agent.label, link.display());+ println!(+ " {} skill link already exists at {} (skipping)",+ agent.label,+ link.display()+ );return Ok(false);}if has_metadata && !resolves && is_symlink_or_junction(&link) {@@ -416,14 +465,26 @@ fn link_agent(agent: Agent, local_skill_dir: &Path) -> Result<bool> {// sweep_legacy_skill_pack cleaned a pre-rename pack out from// under it). Remove + recreate pointing at the new target.if let Err(e) = remove_link(&link) {- eprintln!(" warning: could not remove stale {} link at {}: {e}",- agent.label, link.display());+ eprintln!(+ " warning: could not remove stale {} link at {}: {e}",+ agent.label,+ link.display()+ );return Ok(false);}- println!(" cleaned up stale {} link at {}", agent.label, link.display());- }- make_dir_symlink(local_skill_dir, &link)- .with_context(|| format!("symlink {} -> {}", link.display(), local_skill_dir.display()))?;+ println!(+ " cleaned up stale {} link at {}",+ agent.label,+ link.display()+ );+ }+ make_dir_symlink(local_skill_dir, &link).with_context(|| {+ format!(+ "symlink {} -> {}",+ link.display(),+ local_skill_dir.display()+ )+ })?;println!(" ✅ linked {} skill at {}", agent.label, link.display());Ok(true)}@@ -472,8 +533,7 @@ fn fetch_into(dest: &Path, from_main: bool, all_platforms: bool) -> Result<()> {continue;}let url = format!("{base}/{f}");- let body = http_get_text(&url)- .with_context(|| format!("GET {url}"))?;+ let body = http_get_text(&url).with_context(|| format!("GET {url}"))?;fs::write(dest.join(f), body)?;}return Ok(());@@ -484,14 +544,14 @@ fn fetch_into(dest: &Path, from_main: bool, all_platforms: bool) -> Result<()> {let url = format!("https://github.com/trycua/cua/releases/download/cua-driver-rs-v{version}/cua-driver-rs-v{version}-skills.tar.gz");- let bytes = http_get_bytes(&url)- .with_context(|| format!("GET {url}"))?;+ let bytes = http_get_bytes(&url).with_context(|| format!("GET {url}"))?;extract_tar_gz(&bytes, dest, all_platforms)?;Ok(())}fn http_get_text(url: &str) -> Result<String> {- let resp = ureq::get(url).call()+ let resp = ureq::get(url)+ .call().map_err(|e| anyhow!("HTTP error fetching {url}: {e}"))?;if resp.status() != 200 {bail!("HTTP {} fetching {url}", resp.status());@@ -500,7 +560,8 @@ fn http_get_text(url: &str) -> Result<String> {}fn http_get_bytes(url: &str) -> Result<Vec<u8>> {- let resp = ureq::get(url).call()+ let resp = ureq::get(url)+ .call().map_err(|e| anyhow!("HTTP error fetching {url}: {e}"))?;if resp.status() != 200 {bail!("HTTP {} fetching {url}", resp.status());@@ -584,7 +645,11 @@ fn uninstall(flags: &[String]) -> Result<()> {println!(" ✅ removed {} link at {}", agent.label, link.display());removed_any = true;} else {- println!(" {} link at {} is not a symlink/junction; leaving alone", agent.label, link.display());+ println!(+ " {} link at {} is not a symlink/junction; leaving alone",+ agent.label,+ link.display()+ );}}}@@ -611,7 +676,10 @@ fn uninstall(flags: &[String]) -> Result<()> {let local = legacy_skills_dir.join(name);if local.exists() {fs::remove_dir_all(&local)?;- println!(" ✅ removed legacy local skill pack at {}", local.display());+ println!(+ " ✅ removed legacy local skill pack at {}",+ local.display()+ );}}let _ = fs::remove_dir(&legacy_skills_dir);@@ -637,7 +705,9 @@ fn is_symlink_or_junction(p: &Path) -> bool {#[cfg(not(windows))]fn is_symlink_or_junction(p: &Path) -> bool {- p.symlink_metadata().map(|md| md.file_type().is_symlink()).unwrap_or(false)+ p.symlink_metadata()+ .map(|md| md.file_type().is_symlink())+ .unwrap_or(false)}#[cfg(windows)]@@ -672,7 +742,11 @@ fn status() -> Result<()> {let link = parent.join(SKILL_PACK_NAME);let parent_exists = parent.exists();if !parent_exists {- println!(" {} — agent dir not present ({})", agent.label, parent.display());+ println!(+ " {} — agent dir not present ({})",+ agent.label,+ parent.display()+ );continue;}if !link.exists() && link.symlink_metadata().is_err() {@@ -680,11 +754,20 @@ fn status() -> Result<()> {} else if is_symlink_or_junction(&link) {let target = fs::read_link(&link).ok();match target {- Some(t) => println!(" {} — ✅ linked: {} → {}", agent.label, link.display(), t.display()),- None => println!(" {} — ✅ linked: {}", agent.label, link.display()),+ Some(t) => println!(+ " {} — ✅ linked: {} → {}",+ agent.label,+ link.display(),+ t.display()+ ),+ None => println!(" {} — ✅ linked: {}", agent.label, link.display()),}} else {- println!(" {} — non-symlink path at {} (left alone)", agent.label, link.display());+ println!(+ " {} — non-symlink path at {} (left alone)",+ agent.label,+ link.display()+ );}}Ok(())@@ -723,8 +806,7 @@ mod tests {#[test]fn from_main_manifest_matches_canonical_markdown_files() {- let skill_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))- .join("../../Skills/cua-driver");+ let skill_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../Skills/cua-driver");let mut canonical = std::fs::read_dir(&skill_dir).unwrap_or_else(|error| panic!("failed to read {}: {error}", skill_dir.display())).map(|entry| entry.unwrap().path())@@ -733,13 +815,16 @@ mod tests {.collect::<Vec<_>>();canonical.sort();- let mut manifest = SKILL_FILES.iter()+ let mut manifest = SKILL_FILES+ .iter().map(|file| (*file).to_owned()).collect::<Vec<_>>();manifest.sort();- assert_eq!(manifest, canonical,- "SKILL_FILES must include every canonical Markdown file");+ assert_eq!(+ manifest, canonical,+ "SKILL_FILES must include every canonical Markdown file"+ );}#[test]@@ -748,7 +833,7 @@ mod tests {// cua-driver-rs-v0.2.20-skills/SKILL.md// cua-driver-rs-v0.2.20-skills/WINDOWS.mdlet bytes = build_tarball(&[- ("cua-driver-rs-v0.2.20-skills/SKILL.md", b"flat-skill"),+ ("cua-driver-rs-v0.2.20-skills/SKILL.md", b"flat-skill"),("cua-driver-rs-v0.2.20-skills/WINDOWS.md", b"flat-win"),]);let dest = tempdir().unwrap();@@ -770,8 +855,14 @@ mod tests {// Both wrappers must be stripped or the user ends up with a// nested cua-driver-rs/ dir (the bug this fixes).let bytes = build_tarball(&[- ("cua-driver-rs-v0.2.18-skills/cua-driver-rs/SKILL.md", b"legacy-skill"),- ("cua-driver-rs-v0.2.18-skills/cua-driver-rs/WINDOWS.md", b"legacy-win"),+ (+ "cua-driver-rs-v0.2.18-skills/cua-driver-rs/SKILL.md",+ b"legacy-skill",+ ),+ (+ "cua-driver-rs-v0.2.18-skills/cua-driver-rs/WINDOWS.md",+ b"legacy-win",+ ),]);let dest = tempdir().unwrap();extract_tar_gz(&bytes, dest.path(), true).unwrap();@@ -780,16 +871,19 @@ mod tests {assert_eq!(s, "legacy-skill");let w = std::fs::read_to_string(dest.path().join("WINDOWS.md")).unwrap();assert_eq!(w, "legacy-win");- assert!(!dest.path().join("cua-driver-rs").exists(),- "nested cua-driver-rs/ dir should have been stripped");+ assert!(+ !dest.path().join("cua-driver-rs").exists(),+ "nested cua-driver-rs/ dir should have been stripped"+ );}#[test]fn extract_double_wrap_new_name_also_strips() {// Interim shape (v0.2.19, briefly): inner dir is `cua-driver/`.- let bytes = build_tarball(&[- ("cua-driver-rs-v0.2.19-skills/cua-driver/SKILL.md", b"interim-skill"),- ]);+ let bytes = build_tarball(&[(+ "cua-driver-rs-v0.2.19-skills/cua-driver/SKILL.md",+ b"interim-skill",+ )]);let dest = tempdir().unwrap();extract_tar_gz(&bytes, dest.path(), true).unwrap();let s = std::fs::read_to_string(dest.path().join("SKILL.md")).unwrap();@@ -802,9 +896,7 @@ mod tests {// If a future skill pack adds a real subdir (e.g. `examples/`),// it must NOT be stripped — only the unambiguous pack-name// wrappers are.- let bytes = build_tarball(&[- ("cua-driver-rs-v0.2.20-skills/examples/click.md", b"sample"),- ]);+ let bytes = build_tarball(&[("cua-driver-rs-v0.2.20-skills/examples/click.md", b"sample")]);let dest = tempdir().unwrap();extract_tar_gz(&bytes, dest.path(), true).unwrap();let s = std::fs::read_to_string(dest.path().join("examples/click.md")).unwrap();@@ -818,21 +910,29 @@ mod tests {// platform docs get skipped during extraction. README + SKILL +// platform-agnostic docs are always kept.let bytes = build_tarball(&[- ("cua-driver-rs-v0.2.20-skills/README.md", b"r"),- ("cua-driver-rs-v0.2.20-skills/SKILL.md", b"s"),- ("cua-driver-rs-v0.2.20-skills/WINDOWS.md", b"w"),- ("cua-driver-rs-v0.2.20-skills/MACOS.md", b"m"),- ("cua-driver-rs-v0.2.20-skills/LINUX.md", b"l"),- ("cua-driver-rs-v0.2.20-skills/RECORDING.md",b"R"),- ("cua-driver-rs-v0.2.20-skills/BROWSER.md", b"B"),- ("cua-driver-rs-v0.2.20-skills/EMBEDDING.md",b"E"),+ ("cua-driver-rs-v0.2.20-skills/README.md", b"r"),+ ("cua-driver-rs-v0.2.20-skills/SKILL.md", b"s"),+ ("cua-driver-rs-v0.2.20-skills/WINDOWS.md", b"w"),+ ("cua-driver-rs-v0.2.20-skills/MACOS.md", b"m"),+ ("cua-driver-rs-v0.2.20-skills/LINUX.md", b"l"),+ ("cua-driver-rs-v0.2.20-skills/RECORDING.md", b"R"),+ ("cua-driver-rs-v0.2.20-skills/BROWSER.md", b"B"),+ ("cua-driver-rs-v0.2.20-skills/EMBEDDING.md", b"E"),]);let dest = tempdir().unwrap();extract_tar_gz(&bytes, dest.path(), /*all_platforms=*/ false).unwrap();// README + SKILL + cross-platform docs ALWAYS present.- for f in ["README.md", "SKILL.md", "RECORDING.md", "BROWSER.md", "EMBEDDING.md"] {- assert!(dest.path().join(f).exists(),- "{f} should be present after per-host extraction");+ for f in [+ "README.md",+ "SKILL.md",+ "RECORDING.md",+ "BROWSER.md",+ "EMBEDDING.md",+ ] {+ assert!(+ dest.path().join(f).exists(),+ "{f} should be present after per-host extraction"+ );}// Exactly one platform doc should land — whichever matches this// test's compile target. The other two must be absent.@@ -858,14 +958,16 @@ mod tests {fn extract_all_platforms_flag_keeps_every_platform_doc() {let bytes = build_tarball(&[("cua-driver-rs-v0.2.20-skills/WINDOWS.md", b"w"),- ("cua-driver-rs-v0.2.20-skills/MACOS.md", b"m"),- ("cua-driver-rs-v0.2.20-skills/LINUX.md", b"l"),+ ("cua-driver-rs-v0.2.20-skills/MACOS.md", b"m"),+ ("cua-driver-rs-v0.2.20-skills/LINUX.md", b"l"),]);let dest = tempdir().unwrap();extract_tar_gz(&bytes, dest.path(), /*all_platforms=*/ true).unwrap();for f in ["WINDOWS.md", "MACOS.md", "LINUX.md"] {- assert!(dest.path().join(f).exists(),- "--all-platforms should keep {f}");+ assert!(+ dest.path().join(f).exists(),+ "--all-platforms should keep {f}"+ );}}}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs b/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rsindex 2d1e03a378..6aa0f74fab 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs@@ -201,8 +201,9 @@ fn reset_id_in_homes(home: &Path, legacy: Option<&Path>) -> Result<(), String> {remove_file_if_exists(&legacy.join(TELEMETRY_INSTALL_CHANNEL_FILE_NAME))?;let legacy_releases = legacy.join(RELEASE_RECORDED_DIRECTORY);if legacy_releases.exists() {- std::fs::remove_dir_all(&legacy_releases)- .map_err(|error| format!("failed to remove {}: {error}", legacy_releases.display()))?;+ std::fs::remove_dir_all(&legacy_releases).map_err(|error| {+ format!("failed to remove {}: {error}", legacy_releases.display())+ })?;}}Ok(())@@ -246,7 +247,10 @@ pub fn inspect_event(event_name: &str) -> Result<Value, String> {("reported_provider", Value::String("unknown".into())),("reported_model", Value::String("unknown".into())),("reported_agent", Value::String("unknown".into())),- ("reported_agent_version_major", Value::String("unknown".into())),+ (+ "reported_agent_version_major",+ Value::String("unknown".into()),+ ),("execution_mode", Value::String(execution_mode().into())),]),event::MCP_TOOL_COMPLETED => bounded_properties(&[@@ -292,7 +296,10 @@ pub fn inspect_event(event_name: &str) -> Result<Value, String> {("cursor_outcome_observed", Value::Bool(true)),("cursor_overlay_enabled_at_end", Value::Bool(true)),("cursor_style", Value::String("default".into())),- ("cursor_color_source", Value::String("automatic_palette".into())),+ (+ "cursor_color_source",+ Value::String("automatic_palette".into()),+ ),("cursor_label_set", Value::Bool(false)),("cursor_motion_customized", Value::Bool(false)),("multi_cursor_bucket", Value::String("1".into())),@@ -323,9 +330,7 @@ pub fn inspect_event(event_name: &str) -> Result<Value, String> {| event::MCP_TOOL_COMPLETED| event::MCP_STARTUP_COMPLETED| event::AGENT_SESSION_STARTED- | event::AGENT_SESSION_ENDED => {- Transport::McpStdio- }+ | event::AGENT_SESSION_ENDED => Transport::McpStdio,event::SERVE_START_LEGACY| event::PERMISSIONS_GATE_STARTED| event::PERMISSIONS_GATE_DISMISSED@@ -494,13 +499,31 @@ impl AgentSessionState {};bounded_properties(&[("end_reason", Value::String(end_reason.into())),- ("duration_bucket", Value::String(agent_session_duration_bucket(self.started.elapsed()).into())),- ("tool_count_bucket", Value::String(agent_session_count_bucket(self.tool_count).into())),- ("computer_action_count_bucket", Value::String(agent_session_count_bucket(self.computer_action_count).into())),- ("error_count_bucket", Value::String(agent_session_error_bucket(self.error_count).into())),- ("browser_refusal_count_bucket", Value::String(agent_session_error_bucket(self.browser_refusal_count).into())),+ (+ "duration_bucket",+ Value::String(agent_session_duration_bucket(self.started.elapsed()).into()),+ ),+ (+ "tool_count_bucket",+ Value::String(agent_session_count_bucket(self.tool_count).into()),+ ),+ (+ "computer_action_count_bucket",+ Value::String(agent_session_count_bucket(self.computer_action_count).into()),+ ),+ (+ "error_count_bucket",+ Value::String(agent_session_error_bucket(self.error_count).into()),+ ),+ (+ "browser_refusal_count_bucket",+ Value::String(agent_session_error_bucket(self.browser_refusal_count).into()),+ ),("had_successful_tool", Value::Bool(self.had_successful_tool)),- ("had_successful_computer_action", Value::Bool(self.had_successful_computer_action)),+ (+ "had_successful_computer_action",+ Value::Bool(self.had_successful_computer_action),+ ),("used_page", Value::Bool(self.used_page)),("used_browser", Value::Bool(self.used_browser)),("used_cursor_tools", Value::Bool(self.used_cursor_tools)),@@ -509,11 +532,23 @@ impl AgentSessionState {("cursor_outcome_observed", Value::Bool(cursor.observed)),("cursor_overlay_enabled_at_end", Value::Bool(cursor.enabled)),("cursor_style", Value::String(cursor_style.into())),- ("cursor_color_source", Value::String(cursor_color_source.into())),+ (+ "cursor_color_source",+ Value::String(cursor_color_source.into()),+ ),("cursor_label_set", Value::Bool(cursor.label_set)),- ("cursor_motion_customized", Value::Bool(cursor.motion_customized)),- ("multi_cursor_bucket", Value::String(cursor_count_bucket(cursor.active_cursor_count).into())),- ("observed_multiple_transports", Value::Bool(self.transport_bits.count_ones() > 1)),+ (+ "cursor_motion_customized",+ Value::Bool(cursor.motion_customized),+ ),+ (+ "multi_cursor_bucket",+ Value::String(cursor_count_bucket(cursor.active_cursor_count).into()),+ ),+ (+ "observed_multiple_transports",+ Value::Bool(self.transport_bits.count_ones() > 1),+ ),("execution_mode", Value::String(execution_mode().into())),])}@@ -619,7 +654,10 @@ impl cua_driver_core::session::SessionObserver for TelemetryObserver {bounded_properties(&[("declaration", Value::String(declaration.into())),("revived", Value::Bool(observation.revived)),- ("concurrent_sessions_bucket", Value::String(concurrent_sessions_bucket(concurrent).into())),+ (+ "concurrent_sessions_bucket",+ Value::String(concurrent_sessions_bucket(concurrent).into()),+ ),("entry_transport", Value::String(transport.as_str().into())),("execution_mode", Value::String(execution_mode().into())),]),@@ -659,7 +697,9 @@ impl cua_driver_core::session::SessionObserver for TelemetryObserver {if !is_enabled() {return;}- let Some(state) = state else { return; };+ let Some(state) = state else {+ return;+ };let transport = state.entry_transport;capture_bounded(event::AGENT_SESSION_ENDED,@@ -698,18 +738,45 @@ pub(crate) fn capture_mcp_session_started(event::MCP_SESSION_STARTED,bounded_properties(&[("mcp_client", Value::String(mcp_client)),- ("mcp_client_version_major", Value::String(version_major(metadata.client_version.as_deref()))),- ("protocol_version", Value::String(normalize_protocol(metadata.protocol_version.as_deref()))),+ (+ "mcp_client_version_major",+ Value::String(version_major(metadata.client_version.as_deref())),+ ),+ (+ "protocol_version",+ Value::String(normalize_protocol(metadata.protocol_version.as_deref())),+ ),("capability_tools", Value::Bool(capabilities.tools)),("capability_roots", Value::Bool(capabilities.roots)),("capability_sampling", Value::Bool(capabilities.sampling)),- ("capability_experimental", Value::Bool(capabilities.experimental)),- ("capability_elicitation_form", Value::Bool(capabilities.elicitation_form)),- ("capability_elicitation_url", Value::Bool(capabilities.elicitation_url)),- ("reported_provider", Value::String(normalize_provider(context.provider.as_deref()))),- ("reported_model", Value::String(normalize_model(context.model.as_deref()))),- ("reported_agent", Value::String(normalize_client(context.agent_name.as_deref()))),- ("reported_agent_version_major", Value::String(version_major(context.agent_version.as_deref()))),+ (+ "capability_experimental",+ Value::Bool(capabilities.experimental),+ ),+ (+ "capability_elicitation_form",+ Value::Bool(capabilities.elicitation_form),+ ),+ (+ "capability_elicitation_url",+ Value::Bool(capabilities.elicitation_url),+ ),+ (+ "reported_provider",+ Value::String(normalize_provider(context.provider.as_deref())),+ ),+ (+ "reported_model",+ Value::String(normalize_model(context.model.as_deref())),+ ),+ (+ "reported_agent",+ Value::String(normalize_client(context.agent_name.as_deref())),+ ),+ (+ "reported_agent_version_major",+ Value::String(version_major(context.agent_version.as_deref())),+ ),("execution_mode", Value::String(execution_mode().into())),]),transport,@@ -725,11 +792,7 @@ pub(crate) fn capture_tool_completed("execution_mode".into(),Value::String(execution_mode().into()),);- capture_bounded(- event::MCP_TOOL_COMPLETED,- properties,- transport,- );+ capture_bounded(event::MCP_TOOL_COMPLETED, properties, transport);}fn tool_completion_properties(@@ -780,14 +843,23 @@ fn tool_completion_properties(};bounded_properties(&[("tool_name", Value::String(tool_name)),- ("operation", Value::String(outcome.operation.as_str().into())),+ (+ "operation",+ Value::String(outcome.operation.as_str().into()),+ ),("computer_action", Value::Bool(outcome.computer_action)),("success", Value::Bool(outcome.success)),("error_class", Value::String(error_class.into())),- ("refusal_code", Value::String(outcome.refusal_code.as_str().into())),+ (+ "refusal_code",+ Value::String(outcome.refusal_code.as_str().into()),+ ),("duration_bucket", Value::String(duration_bucket.into())),("output_type", Value::String(output_type.into())),- ("output_size_bucket", Value::String(output_size_bucket.into())),+ (+ "output_size_bucket",+ Value::String(output_size_bucket.into()),+ ),])}@@ -818,7 +890,10 @@ pub(crate) fn capture_mcp_startup_completed(("path", Value::String(path.into())),("daemon", Value::String(daemon.into())),("success", Value::Bool(success)),- ("duration_bucket", Value::String(duration_bucket(elapsed).into())),+ (+ "duration_bucket",+ Value::String(duration_bucket(elapsed).into()),+ ),("execution_mode", Value::String(execution_mode().into())),]),Transport::McpStdio,@@ -843,11 +918,17 @@ pub(crate) fn capture_permissions_gate_completed(event::PERMISSIONS_GATE_COMPLETED,bounded_properties(&[("missing_accessibility", Value::Bool(missing_accessibility)),- ("missing_screen_recording", Value::Bool(missing_screen_recording)),+ (+ "missing_screen_recording",+ Value::Bool(missing_screen_recording),+ ),("panel_shown", Value::Bool(panel_shown)),("dismissed", Value::Bool(dismissed)),("resolution", Value::String(resolution.into())),- ("duration_bucket", Value::String(duration_bucket(elapsed).into())),+ (+ "duration_bucket",+ Value::String(duration_bucket(elapsed).into()),+ ),]),Transport::Daemon,);@@ -874,7 +955,10 @@ pub(crate) fn capture_permissions_gate_started(event::PERMISSIONS_GATE_STARTED,bounded_properties(&[("missing_accessibility", Value::Bool(missing_accessibility)),- ("missing_screen_recording", Value::Bool(missing_screen_recording)),+ (+ "missing_screen_recording",+ Value::Bool(missing_screen_recording),+ ),]),Transport::Daemon,);@@ -889,8 +973,14 @@ pub(crate) fn capture_permissions_gate_dismissed(event::PERMISSIONS_GATE_DISMISSED,bounded_properties(&[("missing_accessibility", Value::Bool(missing_accessibility)),- ("missing_screen_recording", Value::Bool(missing_screen_recording)),- ("duration_bucket", Value::String(duration_bucket(elapsed).into())),+ (+ "missing_screen_recording",+ Value::Bool(missing_screen_recording),+ ),+ (+ "duration_bucket",+ Value::String(duration_bucket(elapsed).into()),+ ),]),Transport::Daemon,);@@ -899,17 +989,29 @@ pub(crate) fn capture_permissions_gate_dismissed(fn normalize_client(value: Option<&str>) -> String {let normalized = value.unwrap_or("").trim().to_ascii_lowercase();for (needle, canonical) in [- ("claude", "claude_code"), ("codex", "codex"), ("cursor", "cursor"),- ("windsurf", "windsurf"), ("vscode", "vscode"), ("visual studio code", "vscode"),- ("zed", "zed"), ("openclaw", "openclaw"), ("opencode", "opencode"),+ ("claude", "claude_code"),+ ("codex", "codex"),+ ("cursor", "cursor"),+ ("windsurf", "windsurf"),+ ("vscode", "vscode"),+ ("visual studio code", "vscode"),+ ("zed", "zed"),+ ("openclaw", "openclaw"),+ ("opencode", "opencode"),("hermes", "hermes"),] {- if normalized.contains(needle) { return canonical.into(); }+ if normalized.contains(needle) {+ return canonical.into();+ }}if normalized == "pi" || normalized.starts_with("pi/") || normalized.starts_with("pi ") {return "pi".into();}- if normalized.is_empty() { "unknown".into() } else { "other".into() }+ if normalized.is_empty() {+ "unknown".into()+ } else {+ "other".into()+ }}fn normalize_provider(value: Option<&str>) -> String {@@ -927,12 +1029,19 @@ fn normalize_provider(value: Option<&str>) -> String {fn normalize_model(value: Option<&str>) -> String {let raw = value.unwrap_or("").trim().to_ascii_lowercase();- if raw.is_empty() { return "unknown".into(); }+ if raw.is_empty() {+ return "unknown".into();+ }let category = if raw.starts_with("claude-") {- if raw.contains("opus") { "claude_opus" }- else if raw.contains("sonnet") { "claude_sonnet" }- else if raw.contains("haiku") { "claude_haiku" }- else { "claude_other" }+ if raw.contains("opus") {+ "claude_opus"+ } else if raw.contains("sonnet") {+ "claude_sonnet"+ } else if raw.contains("haiku") {+ "claude_haiku"+ } else {+ "claude_other"+ }} else if raw.starts_with("gpt-5") {"gpt_5"} else if raw.starts_with("gpt-4.1") {@@ -948,9 +1057,13 @@ fn normalize_model(value: Option<&str>) -> String {} else if raw == "o4" || raw.starts_with("o4-") {"openai_o4"} else if raw.starts_with("gemini-") {- if raw.contains("flash") { "gemini_flash" }- else if raw.contains("pro") { "gemini_pro" }- else { "gemini_other" }+ if raw.contains("flash") {+ "gemini_flash"+ } else if raw.contains("pro") {+ "gemini_pro"+ } else {+ "gemini_other"+ }} else if raw.starts_with("grok-") {"grok"} else if raw.starts_with("nova-") {@@ -965,7 +1078,9 @@ fn normalize_model(value: Option<&str>) -> String {fn normalize_protocol(value: Option<&str>) -> String {match value {- Some(value @ ("2024-11-05" | "2025-03-26" | "2025-06-18" | "2025-11-25")) => value.to_owned(),+ Some(value @ ("2024-11-05" | "2025-03-26" | "2025-06-18" | "2025-11-25")) => {+ value.to_owned()+ }_ => "unknown".into(),}}@@ -976,7 +1091,11 @@ fn version_major(value: Option<&str>) -> String {.split(|character: char| !character.is_ascii_digit()).find(|part| !part.is_empty()).unwrap_or("unknown");- if major.len() <= 4 { major.to_owned() } else { "unknown".into() }+ if major.len() <= 4 {+ major.to_owned()+ } else {+ "unknown".into()+ }}pub fn ensure_first_run_registration() {@@ -1020,7 +1139,9 @@ pub(crate) fn spawn_first_run_registration_worker() {eprintln!("Cua Driver sends content-free product telemetry by default. Run `cua-driver telemetry disable` to stop it; `cua-driver telemetry status` shows the current setting.");- let Ok(executable) = std::env::current_exe() else { return; };+ let Ok(executable) = std::env::current_exe() else {+ return;+ };let _ = std::process::Command::new(executable).env(ENV_LIFECYCLE_WORKER, "1").stdin(Stdio::null())@@ -1106,19 +1227,21 @@ where}fn lifecycle_is_current() -> bool {- let registered = marker_path(INSTALLATION_RECORDED_FILE_NAME)- .is_some_and(|path| path.exists());- let release = release_marker_path(&release_version())- .is_some_and(|path| path.exists());+ let registered = marker_path(INSTALLATION_RECORDED_FILE_NAME).is_some_and(|path| path.exists());+ let release = release_marker_path(&release_version()).is_some_and(|path| path.exists());registered && release}fn lifecycle_retry_deferred() -> bool {- let Some(path) = marker_path(TELEMETRY_RETRY_AFTER_FILE_NAME) else { return false; };+ let Some(path) = marker_path(TELEMETRY_RETRY_AFTER_FILE_NAME) else {+ return false;+ };let Some(retry_after) = std::fs::read_to_string(path).ok().and_then(|value| value.trim().parse::<u64>().ok())- else { return false; };+ else {+ return false;+ };let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|duration| duration.as_secs())@@ -1129,9 +1252,16 @@ fn lifecycle_retry_deferred() -> bool {fn defer_lifecycle_retry(home: &Path) {let retry_after = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)- .map(|duration| duration.as_secs().saturating_add(LIFECYCLE_RETRY_BACKOFF_SECS));+ .map(|duration| {+ duration+ .as_secs()+ .saturating_add(LIFECYCLE_RETRY_BACKOFF_SECS)+ });if let Ok(retry_after) = retry_after {- let _ = std::fs::write(home.join(TELEMETRY_RETRY_AFTER_FILE_NAME), retry_after.to_string());+ let _ = std::fs::write(+ home.join(TELEMETRY_RETRY_AFTER_FILE_NAME),+ retry_after.to_string(),+ );}}@@ -1142,11 +1272,15 @@ wherematch post(payload) {Ok(status) if (200..300).contains(&status) => true,Ok(status) => {- debug_log(format_args!("{event_name} returned {status}; marker not written"));+ debug_log(format_args!(+ "{event_name} returned {status}; marker not written"+ ));false}Err(error) => {- debug_log(format_args!("{event_name} failed: {error}; marker not written"));+ debug_log(format_args!(+ "{event_name} failed: {error}; marker not written"+ ));false}}@@ -1225,16 +1359,24 @@ pub(crate) fn capture_cli_completed(("command", Value::String(command.into())),("tool_name", Value::String(tool_name.into())),("operation", Value::String(operation.into())),- ("computer_action", Value::Bool(command == "call" && computer_action)),+ (+ "computer_action",+ Value::Bool(command == "call" && computer_action),+ ),("client_kind", Value::String(client_kind.into())),("success", Value::Bool(success)),("exit_class", Value::String(exit_class.into())),- ("duration_bucket", Value::String(duration_bucket(elapsed).into())),+ (+ "duration_bucket",+ Value::String(duration_bucket(elapsed).into()),+ ),]),&identity,Transport::Cli,);- if let Err(error) = post_to_posthog_with_timeout(&payload, Duration::from_secs(POSTHOG_TIMEOUT_SECS)) {+ if let Err(error) =+ post_to_posthog_with_timeout(&payload, Duration::from_secs(POSTHOG_TIMEOUT_SECS))+ {debug_log(format_args!("{} failed: {error}", event::CLI_COMPLETED));}}@@ -1293,16 +1435,30 @@ pub(crate) fn spawn_cli_completion_worker(if !is_enabled() {return;}- let Ok(executable) = std::env::current_exe() else { return; };+ let Ok(executable) = std::env::current_exe() else {+ return;+ };let mut worker = std::process::Command::new(executable);worker.env(ENV_CLI_COMPLETION_WORKER, "1").env(ENV_CLI_COMPLETION_COMMAND, fixed_cli_command(command))- .env(ENV_CLI_COMPLETION_COMPUTER_ACTION, if computer_action { "1" } else { "0" })- .env(ENV_CLI_COMPLETION_OPERATION, fixed_cli_operation(command, operation))- .env(ENV_CLI_COMPLETION_CLIENT_KIND, fixed_cli_client_kind(command, client_kind))+ .env(+ ENV_CLI_COMPLETION_COMPUTER_ACTION,+ if computer_action { "1" } else { "0" },+ )+ .env(+ ENV_CLI_COMPLETION_OPERATION,+ fixed_cli_operation(command, operation),+ )+ .env(+ ENV_CLI_COMPLETION_CLIENT_KIND,+ fixed_cli_client_kind(command, client_kind),+ ).env(ENV_CLI_COMPLETION_EXIT_CODE, exit_code.to_string())- .env(ENV_CLI_COMPLETION_DURATION_MS, elapsed.as_millis().to_string());+ .env(+ ENV_CLI_COMPLETION_DURATION_MS,+ elapsed.as_millis().to_string(),+ );if let Some(tool_name) = tool_name {worker.env(ENV_CLI_COMPLETION_TOOL, fixed_tool_name(tool_name));}@@ -1354,26 +1510,43 @@ fn fixed_tool_name(tool_name: &str) -> String {fn fixed_cli_operation(command: &str, operation: &str) -> &'static str {match command {"recording" => match operation {- "start" => "start", "stop" => "stop", "status" => "status",- "render" => "render", _ => "other",+ "start" => "start",+ "stop" => "stop",+ "status" => "status",+ "render" => "render",+ _ => "other",},"permissions" => match operation {- "status" => "status", "grant" => "grant", _ => "other",+ "status" => "status",+ "grant" => "grant",+ _ => "other",},"config" => match operation {- "show" => "show", "get" => "get", "set" => "set",- "reset" => "reset", _ => "other",+ "show" => "show",+ "get" => "get",+ "set" => "set",+ "reset" => "reset",+ _ => "other",},"autostart" => match operation {- "enable" => "enable", "disable" => "disable", "status" => "status",- "kick" => "kick", _ => "other",+ "enable" => "enable",+ "disable" => "disable",+ "status" => "status",+ "kick" => "kick",+ _ => "other",},"skills" => match operation {- "install" => "install", "update" => "update", "uninstall" => "uninstall",- "status" => "status", "path" => "path", _ => "other",+ "install" => "install",+ "update" => "update",+ "uninstall" => "uninstall",+ "status" => "status",+ "path" => "path",+ _ => "other",},"update" => match operation {- "apply" => "apply", "check_only" => "check_only", _ => "other",+ "apply" => "apply",+ "check_only" => "check_only",+ _ => "other",},_ => "not_applicable",}@@ -1434,11 +1607,17 @@ fn build_payload(Value::Bool(parse_env_bool(ENV_TELEMETRY_SYNTHETIC).unwrap_or(false)),);event_properties.insert("transport".into(), Value::String(transport.as_str().into()));- event_properties.insert("process_session_id".into(), Value::String(process_session_id()));+ event_properties.insert(+ "process_session_id".into(),+ Value::String(process_session_id()),+ );event_properties.insert("id_persisted".into(), Value::Bool(identity.persisted));event_properties.insert("$process_person_profile".into(), Value::Bool(false));event_properties.insert("$lib".into(), Value::String("cua-driver-rs".into()));- event_properties.insert("$lib_version".into(), Value::String(current_product_version().into()));+ event_properties.insert(+ "$lib_version".into(),+ Value::String(current_product_version().into()),+ );serde_json::json!({"api_key": POSTHOG_API_KEY,@@ -1459,7 +1638,11 @@ fn spawn_payload(event_name: &'static str, payload: Value) {if tokio::runtime::Handle::try_current().is_ok() {tokio::task::spawn_blocking(task);} else {- if std::thread::Builder::new().name("cua-telemetry".into()).spawn(task).is_err() {+ if std::thread::Builder::new()+ .name("cua-telemetry".into())+ .spawn(task)+ .is_err()+ {finish_pending_send();}}@@ -1494,13 +1677,18 @@ pub(crate) fn flush_pending(timeout: Duration) {}let wait = PENDING_WAIT.get_or_init(|| (Mutex::new(()), Condvar::new()));let deadline = std::time::Instant::now() + timeout;- let mut guard = wait.0.lock().unwrap_or_else(|poisoned| poisoned.into_inner());+ let mut guard = wait+ .0+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());while PENDING_SENDS.load(Ordering::SeqCst) > 0 {let now = std::time::Instant::now();if now >= deadline {break;}- let (next, result) = wait.1.wait_timeout(guard, deadline - now)+ let (next, result) = wait+ .1+ .wait_timeout(guard, deadline - now).unwrap_or_else(|poisoned| poisoned.into_inner());guard = next;if result.timed_out() {@@ -1552,7 +1740,9 @@ fn marker_path(name: &str) -> Option<PathBuf> {fn release_marker_path(version: &str) -> Option<PathBuf> {let safe: String = version.chars()- .filter(|character| character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_'))+ .filter(|character| {+ character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_')+ }).take(80).collect();telemetry_home_dir().map(|home| home.join(RELEASE_RECORDED_DIRECTORY).join(safe))@@ -1567,11 +1757,15 @@ fn read_config() -> Value {}fn persisted_enabled() -> Option<bool> {- read_config().get(CONFIG_ENABLED_KEY).and_then(Value::as_bool)+ read_config()+ .get(CONFIG_ENABLED_KEY)+ .and_then(Value::as_bool)}fn write_json_atomic(path: &Path, value: &Value) -> Result<(), String> {- let parent = path.parent().ok_or_else(|| "invalid config path".to_owned())?;+ let parent = path+ .parent()+ .ok_or_else(|| "invalid config path".to_owned())?;std::fs::create_dir_all(parent).map_err(|error| format!("failed to create {}: {error}", parent.display()))?;let temporary = path.with_extension(format!("tmp-{}", uuid::Uuid::new_v4()));@@ -1640,13 +1834,21 @@ fn migrate_legacy_telemetry_home() {if std::env::var_os(ENV_TELEMETRY_HOME).is_some() {return;}- let Some(root) = home_root() else { return; };+ let Some(root) = home_root() else {+ return;+ };let legacy = root.join(LEGACY_HOME_SUBDIRECTORY);let current = root.join(HOME_SUBDIRECTORY);- if !legacy.is_dir() { return; }+ if !legacy.is_dir() {+ return;+ }let _ = std::fs::create_dir_all(¤t);- let Ok(identity_lock) = open_lock_file(¤t, TELEMETRY_IDENTITY_LOCK_FILE_NAME) else { return; };- if identity_lock.lock().is_err() { return; }+ let Ok(identity_lock) = open_lock_file(¤t, TELEMETRY_IDENTITY_LOCK_FILE_NAME) else {+ return;+ };+ if identity_lock.lock().is_err() {+ return;+ }for name in [TELEMETRY_ID_FILE_NAME, INSTALLATION_RECORDED_FILE_NAME] {let source = legacy.join(name);let destination = current.join(name);@@ -1679,18 +1881,26 @@ fn get_or_create_install_id() -> Option<InstallationIdentity> {fn load_or_create_install_id_uncached() -> Option<InstallationIdentity> {if let Some(id) = read_install_id() {- return Some(InstallationIdentity { id, persisted: true });+ return Some(InstallationIdentity {+ id,+ persisted: true,+ });}let Some(path) = marker_path(TELEMETRY_ID_FILE_NAME) else {static EPHEMERAL_ID: OnceLock<String> = OnceLock::new();return Some(InstallationIdentity {- id: EPHEMERAL_ID.get_or_init(|| uuid::Uuid::new_v4().to_string()).clone(),+ id: EPHEMERAL_ID+ .get_or_init(|| uuid::Uuid::new_v4().to_string())+ .clone(),persisted: false,});};let candidate = uuid::Uuid::new_v4().to_string();match persist_install_id_if_absent(&path, &candidate) {- Ok(id) => Some(InstallationIdentity { id, persisted: true }),+ Ok(id) => Some(InstallationIdentity {+ id,+ persisted: true,+ }),Err(error) => {debug_log(format_args!("installation identity unavailable: {error}"));None@@ -1699,7 +1909,9 @@ fn load_or_create_install_id_uncached() -> Option<InstallationIdentity> {}fn persist_install_id_if_absent(path: &Path, candidate: &str) -> Result<String, String> {- let home = path.parent().ok_or_else(|| "invalid telemetry identity path".to_owned())?;+ let home = path+ .parent()+ .ok_or_else(|| "invalid telemetry identity path".to_owned())?;let identity_lock = open_lock_file(home, TELEMETRY_IDENTITY_LOCK_FILE_NAME)?;identity_lock.lock()@@ -1847,29 +2059,41 @@ fn os_family() -> &'static str {fn os_major() -> String {static OS_MAJOR: OnceLock<String> = OnceLock::new();- OS_MAJOR.get_or_init(|| {- let raw = os_version();- let start = raw.find(|character: char| character.is_ascii_digit());- let Some(start) = start else { return "unknown".into(); };- raw[start..]- .split(|character: char| !character.is_ascii_digit())- .next()- .filter(|value| !value.is_empty())- .unwrap_or("unknown")- .to_owned()- }).clone()+ OS_MAJOR+ .get_or_init(|| {+ let raw = os_version();+ let start = raw.find(|character: char| character.is_ascii_digit());+ let Some(start) = start else {+ return "unknown".into();+ };+ raw[start..]+ .split(|character: char| !character.is_ascii_digit())+ .next()+ .filter(|value| !value.is_empty())+ .unwrap_or("unknown")+ .to_owned()+ })+ .clone()}fn os_version() -> String {#[cfg(target_os = "macos")]- let command = std::process::Command::new("sw_vers").arg("-productVersion").output();+ let command = std::process::Command::new("sw_vers")+ .arg("-productVersion")+ .output();#[cfg(target_os = "windows")]- let command = std::process::Command::new("cmd").args(["/c", "ver"]).output();+ let command = std::process::Command::new("cmd")+ .args(["/c", "ver"])+ .output();#[cfg(target_os = "linux")]{return std::fs::read_to_string("/etc/os-release").ok()- .and_then(|contents| contents.lines().find_map(|line| line.strip_prefix("VERSION_ID=").map(str::to_owned)))+ .and_then(|contents| {+ contents+ .lines()+ .find_map(|line| line.strip_prefix("VERSION_ID=").map(str::to_owned))+ }).map(|value| value.trim_matches('"').to_owned()).unwrap_or_else(|| "unknown".into());}@@ -1892,12 +2116,26 @@ fn arch() -> &'static str {fn is_ci() -> bool {const VARIABLES: &[&str] = &[- "CI", "CONTINUOUS_INTEGRATION", "GITHUB_ACTIONS", "GITLAB_CI",- "JENKINS_URL", "CIRCLECI", "BUILDKITE", "TF_BUILD", "TEAMCITY_VERSION",- "TRAVIS", "APPVEYOR", "BITBUCKET_BUILD_NUMBER", "CODEBUILD_BUILD_ID",- "DRONE", "HUDSON_URL", "CI_NAME",+ "CI",+ "CONTINUOUS_INTEGRATION",+ "GITHUB_ACTIONS",+ "GITLAB_CI",+ "JENKINS_URL",+ "CIRCLECI",+ "BUILDKITE",+ "TF_BUILD",+ "TEAMCITY_VERSION",+ "TRAVIS",+ "APPVEYOR",+ "BITBUCKET_BUILD_NUMBER",+ "CODEBUILD_BUILD_ID",+ "DRONE",+ "HUDSON_URL",+ "CI_NAME",];- VARIABLES.iter().any(|name| std::env::var_os(name).is_some())+ VARIABLES+ .iter()+ .any(|name| std::env::var_os(name).is_some())}#[cfg(test)]@@ -1937,7 +2175,9 @@ mod tests {fn wait_for_path(path: &Path, timeout: Duration) -> bool {let deadline = Instant::now() + timeout;while Instant::now() < deadline {- if path.exists() { return true; }+ if path.exists() {+ return true;+ }std::thread::sleep(Duration::from_millis(10));}path.exists()@@ -1953,7 +2193,9 @@ mod tests {.filter_map(Result::ok).filter(|entry| entry.file_name().to_string_lossy().starts_with("ready-")).count();- if ready == count { return true; }+ if ready == count {+ return true;+ }std::thread::sleep(Duration::from_millis(10));}false@@ -1974,7 +2216,9 @@ mod tests {Command::new(std::env::current_exe().expect("current test executable")).arg(match kind {"identity" => "telemetry::tests::identity_process_child",- "lifecycle-winner" | "lifecycle-contender" => "telemetry::tests::lifecycle_process_child",+ "lifecycle-winner" | "lifecycle-contender" => {+ "telemetry::tests::lifecycle_process_child"+ }_ => panic!("unknown test child kind"),}).arg("--exact")@@ -1989,7 +2233,9 @@ mod tests {#[test]fn identity_process_child() {- if std::env::var(TEST_CHILD_KIND).ok().as_deref() != Some("identity") { return; }+ if std::env::var(TEST_CHILD_KIND).ok().as_deref() != Some("identity") {+ return;+ }let root = PathBuf::from(std::env::var_os(TEST_CHILD_ROOT).expect("test child root"));let index = std::env::var(TEST_CHILD_INDEX).expect("test child index");let candidate = std::env::var(TEST_CHILD_CANDIDATE).expect("test child candidate");@@ -2002,8 +2248,12 @@ mod tests {#[test]fn lifecycle_process_child() {- let Ok(kind) = std::env::var(TEST_CHILD_KIND) else { return; };- if !matches!(kind.as_str(), "lifecycle-winner" | "lifecycle-contender") { return; }+ let Ok(kind) = std::env::var(TEST_CHILD_KIND) else {+ return;+ };+ if !matches!(kind.as_str(), "lifecycle-winner" | "lifecycle-contender") {+ return;+ }let root = PathBuf::from(std::env::var_os(TEST_CHILD_ROOT).expect("test child root"));let index = std::env::var(TEST_CHILD_INDEX).expect("test child index");let mut call = 0usize;@@ -2012,7 +2262,8 @@ mod tests {std::fs::write(root.join(format!("event-{index}-{call}.json")),serde_json::to_vec(payload).expect("serialize captured event"),- ).expect("write captured event");+ )+ .expect("write captured event");if kind == "lifecycle-winner" && call == 1 {std::fs::write(root.join("winner-ready"), "1").expect("signal winner ready");if !wait_for_path(&root.join("release-winner"), Duration::from_secs(15)) {@@ -2024,7 +2275,8 @@ mod tests {std::fs::write(root.join(format!("observed-id-{index}")),read_install_id().unwrap_or_default(),- ).expect("write observed identity");+ )+ .expect("write observed identity");}#[test]@@ -2035,7 +2287,11 @@ mod tests {let mut children: Vec<_> = (0..CHILDREN).map(|index| spawn_test_child("identity", root, index)).collect();- assert!(wait_for_children_ready(root, CHILDREN, Duration::from_secs(15)));+ assert!(wait_for_children_ready(+ root,+ CHILDREN,+ Duration::from_secs(15)+ ));std::fs::write(root.join("go"), "1").unwrap();for child in &mut children {let status = wait_for_child(child, Duration::from_secs(15));@@ -2064,7 +2320,10 @@ mod tests {let _guard = ENV_LOCK.lock().unwrap();with_isolated_home(|root| {let mut winner = spawn_test_child("lifecycle-winner", root, 0);- assert!(wait_for_path(&root.join("winner-ready"), Duration::from_secs(15)));+ assert!(wait_for_path(+ &root.join("winner-ready"),+ Duration::from_secs(15)+ ));let mut contender = spawn_test_child("lifecycle-contender", root, 1);let contender_status = wait_for_child(&mut contender, Duration::from_secs(5));@@ -2093,12 +2352,26 @@ mod tests {.unwrap().filter_map(Result::ok).filter(|entry| entry.file_name().to_string_lossy().starts_with("event-"))- .map(|entry| serde_json::from_slice::<Value>(&std::fs::read(entry.path()).unwrap()).unwrap())+ .map(|entry| {+ serde_json::from_slice::<Value>(&std::fs::read(entry.path()).unwrap()).unwrap()+ }).collect::<Vec<_>>();events.sort_by_key(|event| event["event"].as_str().unwrap_or_default().to_owned());assert_eq!(events.len(), 2);- assert_eq!(events.iter().filter(|item| item["event"] == event::INSTALLATION_REGISTERED).count(), 1);- assert_eq!(events.iter().filter(|item| item["event"] == event::RELEASE_INSTALLED).count(), 1);+ assert_eq!(+ events+ .iter()+ .filter(|item| item["event"] == event::INSTALLATION_REGISTERED)+ .count(),+ 1+ );+ assert_eq!(+ events+ .iter()+ .filter(|item| item["event"] == event::RELEASE_INSTALLED)+ .count(),+ 1+ );let persisted = read_install_id().expect("persisted identity");assert!(events.iter().all(|item| item["distinct_id"] == persisted));for index in 0..=1 {@@ -2107,8 +2380,13 @@ mod tests {persisted);}- assert!(root.join(HOME_SUBDIRECTORY).join(INSTALLATION_RECORDED_FILE_NAME).exists());- assert!(release_marker_path(current_product_version()).unwrap().exists());+ assert!(root+ .join(HOME_SUBDIRECTORY)+ .join(INSTALLATION_RECORDED_FILE_NAME)+ .exists());+ assert!(release_marker_path(current_product_version())+ .unwrap()+ .exists());});}@@ -2119,9 +2397,13 @@ mod tests {assert_eq!(effective_enabled(), (true, "default"));set_enabled(false).unwrap();assert_eq!(effective_enabled(), (false, "persisted"));- unsafe { std::env::set_var(ENV_TELEMETRY_ENABLED, "true"); }+ unsafe {+ std::env::set_var(ENV_TELEMETRY_ENABLED, "true");+ }assert_eq!(effective_enabled(), (true, "environment"));- unsafe { std::env::remove_var(ENV_TELEMETRY_ENABLED); }+ unsafe {+ std::env::remove_var(ENV_TELEMETRY_ENABLED);+ }});}@@ -2138,9 +2420,13 @@ mod tests {.unwrap();assert_eq!(install_channel(), "install_script");- unsafe { std::env::set_var(ENV_INSTALL_CHANNEL, "update_apply"); }+ unsafe {+ std::env::set_var(ENV_INSTALL_CHANNEL, "update_apply");+ }assert_eq!(install_channel(), "update_apply");- unsafe { std::env::remove_var(ENV_INSTALL_CHANNEL); }+ unsafe {+ std::env::remove_var(ENV_INSTALL_CHANNEL);+ }std::fs::write(home.join(TELEMETRY_INSTALL_CHANNEL_FILE_NAME), "invalid").unwrap();assert_eq!(install_channel(), "first_run");@@ -2156,14 +2442,21 @@ mod tests {let id = uuid::Uuid::new_v4().to_string();std::fs::write(home.join(TELEMETRY_ID_FILE_NAME), &id).unwrap();set_enabled(false).unwrap();- unsafe { std::env::set_var(ENV_TELEMETRY_ENABLED, "false"); }+ unsafe {+ std::env::set_var(ENV_TELEMETRY_ENABLED, "false");+ }let mut calls = 0;- capture_install_with_poster(|_| { calls += 1; Ok(200) });+ capture_install_with_poster(|_| {+ calls += 1;+ Ok(200)+ });assert_eq!(calls, 0);assert_eq!(read_install_id().as_deref(), Some(id.as_str()));assert!(!home.join(INSTALLATION_RECORDED_FILE_NAME).exists());assert!(!home.join(TELEMETRY_RETRY_AFTER_FILE_NAME).exists());- unsafe { std::env::remove_var(ENV_TELEMETRY_ENABLED); }+ unsafe {+ std::env::remove_var(ENV_TELEMETRY_ENABLED);+ }});}@@ -2205,14 +2498,22 @@ mod tests {let mut calls = 0;capture_install_with_poster(|_| {calls += 1;- if calls == 1 { Ok(200) } else { Ok(500) }+ if calls == 1 {+ Ok(200)+ } else {+ Ok(500)+ }});assert!(home.join(INSTALLATION_RECORDED_FILE_NAME).exists());- assert!(!release_marker_path(current_product_version()).unwrap().exists());+ assert!(!release_marker_path(current_product_version())+ .unwrap()+ .exists());remove_file_if_exists(&home.join(TELEMETRY_RETRY_AFTER_FILE_NAME)).unwrap();capture_install_with_poster(|_| Ok(200));- assert!(release_marker_path(current_product_version()).unwrap().exists());+ assert!(release_marker_path(current_product_version())+ .unwrap()+ .exists());});}@@ -2234,7 +2535,10 @@ mod tests {calls += 1;Ok(200)});- assert_eq!(calls, 1, "retry backoff must prevent per-command network stalls");+ assert_eq!(+ calls, 1,+ "retry backoff must prevent per-command network stalls"+ );});}@@ -2244,7 +2548,11 @@ mod tests {with_isolated_home(|root| {set_enabled(false).unwrap();let home = root.join(HOME_SUBDIRECTORY);- std::fs::write(home.join(TELEMETRY_ID_FILE_NAME), uuid::Uuid::new_v4().to_string()).unwrap();+ std::fs::write(+ home.join(TELEMETRY_ID_FILE_NAME),+ uuid::Uuid::new_v4().to_string(),+ )+ .unwrap();write_marker(&home.join(INSTALLATION_RECORDED_FILE_NAME)).unwrap();write_marker(&release_marker_path("1.2.3").unwrap()).unwrap();reset_id().unwrap();@@ -2257,7 +2565,8 @@ mod tests {#[test]fn reset_erases_legacy_identity_before_migration_can_restore_it() {let _guard = ENV_LOCK.lock().unwrap();- let root = std::env::temp_dir().join(format!("cua-telemetry-reset-{}", uuid::Uuid::new_v4()));+ let root =+ std::env::temp_dir().join(format!("cua-telemetry-reset-{}", uuid::Uuid::new_v4()));let current = root.join(HOME_SUBDIRECTORY);let legacy = root.join(LEGACY_HOME_SUBDIRECTORY);std::fs::create_dir_all(&legacy).unwrap();@@ -2275,7 +2584,10 @@ mod tests {#[test]fn v3_payload_allows_server_geoip_without_sending_an_ip_or_client_timestamp() {let _guard = ENV_LOCK.lock().unwrap();- let identity = InstallationIdentity { id: "test-id".into(), persisted: true };+ let identity = InstallationIdentity {+ id: "test-id".into(),+ persisted: true,+ };let payload = build_payload(event::MCP_TOOL_COMPLETED,&bounded_properties(&[@@ -2288,10 +2600,21 @@ mod tests {assert!(payload.get("timestamp").is_none());let properties = payload["properties"].as_object().unwrap();for required in [- "telemetry_schema_version", "product_version", "os_family", "os_major",- "arch", "is_ci", "is_synthetic", "transport", "process_session_id", "id_persisted",- "$process_person_profile", "$lib", "$lib_version",- "tool_name", "success",+ "telemetry_schema_version",+ "product_version",+ "os_family",+ "os_major",+ "arch",+ "is_ci",+ "is_synthetic",+ "transport",+ "process_session_id",+ "id_persisted",+ "$process_person_profile",+ "$lib",+ "$lib_version",+ "tool_name",+ "success",] {assert!(properties.contains_key(required), "missing {required}");}@@ -2299,13 +2622,30 @@ mod tests {assert_eq!(properties["is_synthetic"], false);assert!(!properties.contains_key("$geoip_disable"));assert!(!properties.contains_key("$ip"));- let serialized = serde_json::to_string(&payload).unwrap().to_ascii_lowercase();+ let serialized = serde_json::to_string(&payload)+ .unwrap()+ .to_ascii_lowercase();for forbidden in [- "prompt", "task_text", "arguments", "result_text", "typed_text", "clipboard",- "screenshot", "accessibility_tree", "window_title", "application_name", "file_path",- "url", "raw_error", "stack_trace", "initialize_payload",+ "prompt",+ "task_text",+ "arguments",+ "result_text",+ "typed_text",+ "clipboard",+ "screenshot",+ "accessibility_tree",+ "window_title",+ "application_name",+ "file_path",+ "url",+ "raw_error",+ "stack_trace",+ "initialize_payload",] {- assert!(!serialized.contains(forbidden), "payload contains {forbidden}: {serialized}");+ assert!(+ !serialized.contains(forbidden),+ "payload contains {forbidden}: {serialized}"+ );}}@@ -2331,11 +2671,20 @@ mod tests {let session = inspect_event(event::MCP_SESSION_STARTED).unwrap();let session_properties = session["properties"].as_object().unwrap();for field in [- "mcp_client", "mcp_client_version_major", "protocol_version",- "capability_tools", "capability_roots", "capability_sampling",- "capability_experimental", "capability_elicitation_form",- "capability_elicitation_url", "reported_provider", "reported_model",- "reported_agent", "reported_agent_version_major", "execution_mode",+ "mcp_client",+ "mcp_client_version_major",+ "protocol_version",+ "capability_tools",+ "capability_roots",+ "capability_sampling",+ "capability_experimental",+ "capability_elicitation_form",+ "capability_elicitation_url",+ "reported_provider",+ "reported_model",+ "reported_agent",+ "reported_agent_version_major",+ "execution_mode",] {assert!(session_properties.contains_key(field), "missing {field}");}@@ -2371,14 +2720,13 @@ mod tests {.is_none());let permissions_dismissed = inspect_event(event::PERMISSIONS_GATE_DISMISSED).unwrap();assert_eq!(permissions_dismissed["properties"]["transport"], "daemon");- assert_eq!(permissions_dismissed["properties"]["duration_bucket"], "2s_9_999ms");+ assert_eq!(+ permissions_dismissed["properties"]["duration_bucket"],+ "2s_9_999ms"+ );let permissions = inspect_event(event::PERMISSIONS_GATE_COMPLETED).unwrap();assert_eq!(permissions["properties"]["resolution"], "granted");- for payload in [- permissions_started,- permissions_dismissed,- permissions,- ] {+ for payload in [permissions_started, permissions_dismissed, permissions] {assert_eq!(payload["properties"]["telemetry_schema_version"], 3);assert!(payload.get("timestamp").is_none());let serialized = serde_json::to_string(&payload)@@ -2453,8 +2801,7 @@ mod tests {#[test]fn agent_session_aggregate_is_bounded_content_free_and_multi_transport() {use cua_driver_core::server::{- DurationBucket, OutputSizeBucket, OutputType, ToolCompletionObservation,- ToolErrorClass,+ DurationBucket, OutputSizeBucket, OutputType, ToolCompletionObservation, ToolErrorClass,};let mut state = AgentSessionState::new(Transport::McpStdio);@@ -2517,7 +2864,9 @@ mod tests {assert_eq!(properties["multi_cursor_bucket"], "3_5");assert_eq!(properties["observed_multiple_transports"], true);- let serialized = serde_json::to_string(&properties).unwrap().to_ascii_lowercase();+ let serialized = serde_json::to_string(&properties)+ .unwrap()+ .to_ascii_lowercase();for forbidden in ["private-session-id","arguments",@@ -2528,7 +2877,10 @@ mod tests {"file_path","raw_error",] {- assert!(!serialized.contains(forbidden), "aggregate contains {forbidden}: {serialized}");+ assert!(+ !serialized.contains(forbidden),+ "aggregate contains {forbidden}: {serialized}"+ );}}@@ -2561,10 +2913,8 @@ mod tests {let mut state = AgentSessionState::new(Transport::McpStdio);state.observe(Transport::McpStdio, true, &outcome);- let session_properties = state.ended_properties(- cua_driver_core::session::SessionEndReason::Explicit,- None,- );+ let session_properties =+ state.ended_properties(cua_driver_core::session::SessionEndReason::Explicit, None);assert_eq!(session_properties["computer_action_count_bucket"], "0");assert_eq!(session_properties["error_count_bucket"], "0");assert_eq!(session_properties["browser_refusal_count_bucket"], "1");@@ -2625,14 +2975,18 @@ mod tests {#[test]fn agent_session_buckets_have_fixed_boundaries() {for (count, expected) in [- (0, "0"), (1, "1_4"), (4, "1_4"), (5, "5_19"),- (19, "5_19"), (20, "20_99"), (99, "20_99"), (100, "gte_100"),+ (0, "0"),+ (1, "1_4"),+ (4, "1_4"),+ (5, "5_19"),+ (19, "5_19"),+ (20, "20_99"),+ (99, "20_99"),+ (100, "gte_100"),] {assert_eq!(agent_session_count_bucket(count), expected);}- for (count, expected) in [- (0, "0"), (1, "1"), (2, "2_4"), (4, "2_4"), (5, "gte_5"),- ] {+ for (count, expected) in [(0, "0"), (1, "1"), (2, "2_4"), (4, "2_4"), (5, "gte_5")] {assert_eq!(agent_session_error_bucket(count), expected);}}@@ -2646,24 +3000,34 @@ mod tests {for forbidden_key in ["session", "session_id", "agent_session_id", "cursor_id"] {assert!(!properties.contains_key(forbidden_key));}- let serialized = serde_json::to_string(&payload).unwrap().to_ascii_lowercase();+ let serialized = serde_json::to_string(&payload)+ .unwrap()+ .to_ascii_lowercase();for forbidden in [- "arguments", "result_text", "file_path", "socket", "raw_error", "$ip",+ "arguments",+ "result_text",+ "file_path",+ "socket",+ "raw_error",+ "$ip",] {- assert!(!serialized.contains(forbidden), "inspect payload contains {forbidden}: {serialized}");+ assert!(+ !serialized.contains(forbidden),+ "inspect payload contains {forbidden}: {serialized}"+ );}}}#[test]fn disabled_agent_session_observation_creates_no_state_or_identity() {- use cua_driver_core::session::{- SessionDeclaration, SessionObserver, SessionStartObservation, SessionTransport,- };use cua_driver_core::server::{DurationBucket, OutputSizeBucket, OutputType, ToolCompletionObservation,ToolErrorClass, ToolOperation, ToolRefusalCode,};+ use cua_driver_core::session::{+ SessionDeclaration, SessionObserver, SessionStartObservation, SessionTransport,+ };let _guard = ENV_LOCK.lock().unwrap();with_isolated_home(|_| {@@ -2703,8 +3067,7 @@ mod tests {#[test]fn http_tool_completion_reaches_the_final_payload_as_mcp_http() {use cua_driver_core::server::{- DurationBucket, OutputSizeBucket, OutputType, ToolCompletionObservation,- ToolErrorClass,+ DurationBucket, OutputSizeBucket, OutputType, ToolCompletionObservation, ToolErrorClass,};let properties = tool_completion_properties(ToolCompletionObservation {@@ -2773,9 +3136,18 @@ mod tests {assert_eq!(fixed_cli_operation("recording", "start"), "start");assert_eq!(fixed_cli_operation("recording", "/private/path"), "other");assert_eq!(fixed_cli_operation("doctor", "start"), "not_applicable");- assert_eq!(fixed_cli_client_kind("mcp_config", "claude_code"), "claude_code");- assert_eq!(fixed_cli_client_kind("mcp_config", "/private/client"), "other");- assert_eq!(fixed_cli_client_kind("doctor", "claude_code"), "not_applicable");+ assert_eq!(+ fixed_cli_client_kind("mcp_config", "claude_code"),+ "claude_code"+ );+ assert_eq!(+ fixed_cli_client_kind("mcp_config", "/private/client"),+ "other"+ );+ assert_eq!(+ fixed_cli_client_kind("doctor", "claude_code"),+ "not_applicable"+ );}#[test]@@ -2825,7 +3197,10 @@ mod tests {#[test]fn release_versions_accept_strict_semver_and_drop_leading_v() {assert_eq!(strict_release_version("v1.2.3"), Some("1.2.3".into()));- assert_eq!(strict_release_version("1.2.3-rc.1"), Some("1.2.3-rc.1".into()));+ assert_eq!(+ strict_release_version("1.2.3-rc.1"),+ Some("1.2.3-rc.1".into())+ );assert_eq!(strict_release_version("1.2"), None);assert_eq!(strict_release_version("1.2.3+private"), None);}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/updater.rs b/libs/cua-driver/rust/crates/cua-driver/src/updater.rsindex 4e10dd05d3..541b036e98 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/updater.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/updater.rs@@ -27,11 +27,9 @@ use std::process::{Command, ExitStatus};/// command land at the exact same script. Per-OS gating keeps the unused/// constant from triggering `dead_code` on the platform that doesn't use it.#[cfg(not(windows))]-const CANONICAL_INSTALL_SH: &str =- "https://cua.ai/driver/install.sh";+const CANONICAL_INSTALL_SH: &str = "https://cua.ai/driver/install.sh";#[cfg(windows)]-const CANONICAL_INSTALL_PS1: &str =- "https://cua.ai/driver/install.ps1";+const CANONICAL_INSTALL_PS1: &str = "https://cua.ai/driver/install.ps1";/// The env var both scripts honour to pin the target release tag. Set to a/// bare version like `"0.2.18"` (no `cua-driver-rs-v` prefix). Seediff --git a/libs/cua-driver/rust/crates/cua-driver/src/version_check.rs b/libs/cua-driver/rust/crates/cua-driver/src/version_check.rsindex b64f36aee4..c7c935a5ab 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/version_check.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/version_check.rs@@ -65,8 +65,7 @@ pub const RELEASE_TAG_PREFIX: &str = "cua-driver-rs-v";/// GitHub releases API endpoint. Paginates newest-first; 40 entries is/// plenty of headroom past the most recent stable release even when/// pre-releases are sprinkled in between.-const RELEASES_URL: &str =- "https://api.github.com/repos/trycua/cua/releases?per_page=40";+const RELEASES_URL: &str = "https://api.github.com/repos/trycua/cua/releases?per_page=40";// ── Public API ───────────────────────────────────────────────────────────@@ -383,8 +382,7 @@ fn is_enabled() -> bool {/// the `cua-driver config set` subcommand writes to. Returns `None` when/// the file is missing, unreadable, or doesn't have the key.fn read_config_flag() -> Option<bool> {- let home = std::env::var_os("HOME")- .or_else(|| std::env::var_os("USERPROFILE"))?;+ let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;let path = PathBuf::from(home).join(".cua-driver").join("config.json");let raw = std::fs::read_to_string(&path).ok()?;let json: serde_json::Value = serde_json::from_str(&raw).ok()?;@@ -420,8 +418,12 @@ pub(crate) fn is_prerelease(version: &str) -> bool {/// available" banner. We'd rather miss a real update than nag the user/// about a phantom one.pub fn is_newer(latest: &str, current: &str) -> bool {- let Ok(l) = semver::Version::parse(latest) else { return false; };- let Ok(c) = semver::Version::parse(current) else { return false; };+ let Ok(l) = semver::Version::parse(latest) else {+ return false;+ };+ let Ok(c) = semver::Version::parse(current) else {+ return false;+ };l > c}@@ -472,9 +474,12 @@ fn write_cache(cache: &VersionCache) -> std::io::Result<()> {}fn cache_path() -> Option<PathBuf> {- let home = std::env::var_os("HOME")- .or_else(|| std::env::var_os("USERPROFILE"))?;- Some(PathBuf::from(home).join(HOME_SUBDIRECTORY).join(CACHE_FILE_NAME))+ let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;+ Some(+ PathBuf::from(home)+ .join(HOME_SUBDIRECTORY)+ .join(CACHE_FILE_NAME),+ )}// ── HTTP fetch (shared with the `update` subcommand) ─────────────────────@@ -504,7 +509,10 @@ pub fn fetch_latest_version() -> Result<String, String> {let response = agent.get(RELEASES_URL).header("Accept", "application/vnd.github+json")- .header("User-Agent", concat!("cua-driver-rs/", env!("CARGO_PKG_VERSION")))+ .header(+ "User-Agent",+ concat!("cua-driver-rs/", env!("CARGO_PKG_VERSION")),+ ).call().map_err(|e| format!("HTTP error: {e}"))?;@@ -595,18 +603,30 @@ mod tests {let tmp = tempfile::tempdir().expect("tempdir");let saved_home = std::env::var_os("HOME");let saved_userprofile = std::env::var_os("USERPROFILE");- unsafe { std::env::set_var("HOME", tmp.path()); }- unsafe { std::env::set_var("USERPROFILE", tmp.path()); }+ unsafe {+ std::env::set_var("HOME", tmp.path());+ }+ unsafe {+ std::env::set_var("USERPROFILE", tmp.path());+ }let result = f(tmp.path());match saved_home {- Some(s) => unsafe { std::env::set_var("HOME", s); },- None => unsafe { std::env::remove_var("HOME"); },+ Some(s) => unsafe {+ std::env::set_var("HOME", s);+ },+ None => unsafe {+ std::env::remove_var("HOME");+ },}match saved_userprofile {- Some(s) => unsafe { std::env::set_var("USERPROFILE", s); },- None => unsafe { std::env::remove_var("USERPROFILE"); },+ Some(s) => unsafe {+ std::env::set_var("USERPROFILE", s);+ },+ None => unsafe {+ std::env::remove_var("USERPROFILE");+ },}result}@@ -821,27 +841,37 @@ mod tests {let _g = ENV_LOCK.lock().unwrap();let saved = std::env::var_os(ENV_UPDATE_CHECK);- unsafe { std::env::set_var(ENV_UPDATE_CHECK, "false"); }+ unsafe {+ std::env::set_var(ENV_UPDATE_CHECK, "false");+ }// Use a separately-redirected HOME so any config file present on// the developer's machine can't influence the result.with_isolated_home(|_| {assert!(!is_enabled(), "explicit false env var must disable");});- unsafe { std::env::set_var(ENV_UPDATE_CHECK, "0"); }+ unsafe {+ std::env::set_var(ENV_UPDATE_CHECK, "0");+ }with_isolated_home(|_| {assert!(!is_enabled(), "0 must disable");});- unsafe { std::env::set_var(ENV_UPDATE_CHECK, "off"); }+ unsafe {+ std::env::set_var(ENV_UPDATE_CHECK, "off");+ }with_isolated_home(|_| {assert!(!is_enabled(), "off must disable");});// Restore.match saved {- Some(s) => unsafe { std::env::set_var(ENV_UPDATE_CHECK, s); },- None => unsafe { std::env::remove_var(ENV_UPDATE_CHECK); },+ Some(s) => unsafe {+ std::env::set_var(ENV_UPDATE_CHECK, s);+ },+ None => unsafe {+ std::env::remove_var(ENV_UPDATE_CHECK);+ },}}@@ -849,7 +879,9 @@ mod tests {fn config_flag_disables_check() {let _g = ENV_LOCK.lock().unwrap();let saved = std::env::var_os(ENV_UPDATE_CHECK);- unsafe { std::env::remove_var(ENV_UPDATE_CHECK); }+ unsafe {+ std::env::remove_var(ENV_UPDATE_CHECK);+ }with_isolated_home(|home| {// Write a config that disables the check.@@ -858,18 +890,25 @@ mod tests {std::fs::write(cfg_dir.join("config.json"),r#"{"update_check_enabled": false}"#,- ).unwrap();+ )+ .unwrap();// Build version is a normal release (this crate's pkg version// ships as "0.1.3", a stable release — see workspace Cargo.toml).// The env var is unset, so the config flag is the only signal.- assert!(!is_enabled(),- "persisted update_check_enabled=false must disable the check");+ assert!(+ !is_enabled(),+ "persisted update_check_enabled=false must disable the check"+ );});match saved {- Some(s) => unsafe { std::env::set_var(ENV_UPDATE_CHECK, s); },- None => unsafe { std::env::remove_var(ENV_UPDATE_CHECK); },+ Some(s) => unsafe {+ std::env::set_var(ENV_UPDATE_CHECK, s);+ },+ None => unsafe {+ std::env::remove_var(ENV_UPDATE_CHECK);+ },}}@@ -877,13 +916,17 @@ mod tests {fn config_flag_true_or_missing_leaves_check_on() {let _g = ENV_LOCK.lock().unwrap();let saved = std::env::var_os(ENV_UPDATE_CHECK);- unsafe { std::env::remove_var(ENV_UPDATE_CHECK); }+ unsafe {+ std::env::remove_var(ENV_UPDATE_CHECK);+ }with_isolated_home(|home| {// Case A: no config file at all → enabled.// CARGO_PKG_VERSION is "0.1.3" (stable), env unset, no config file.- assert!(is_enabled(),- "no config file + stable version + no env opt-out → enabled");+ assert!(+ is_enabled(),+ "no config file + stable version + no env opt-out → enabled"+ );// Case B: config file present but flag = true → still enabled.let cfg_dir = home.join(".cua-driver");@@ -891,14 +934,21 @@ mod tests {std::fs::write(cfg_dir.join("config.json"),r#"{"update_check_enabled": true, "other_key": 42}"#,- ).unwrap();- assert!(is_enabled(),- "explicit update_check_enabled=true must leave check on");+ )+ .unwrap();+ assert!(+ is_enabled(),+ "explicit update_check_enabled=true must leave check on"+ );});match saved {- Some(s) => unsafe { std::env::set_var(ENV_UPDATE_CHECK, s); },- None => unsafe { std::env::remove_var(ENV_UPDATE_CHECK); },+ Some(s) => unsafe {+ std::env::set_var(ENV_UPDATE_CHECK, s);+ },+ None => unsafe {+ std::env::remove_var(ENV_UPDATE_CHECK);+ },}}@@ -908,15 +958,19 @@ mod tests {fn banner_contains_required_lines() {let banner = format_banner("0.1.4", "0.1.3");// Headline.- assert!(banner.contains("cua-driver v0.1.4 is available"), "got: {banner:?}");+ assert!(+ banner.contains("cua-driver v0.1.4 is available"),+ "got: {banner:?}"+ );assert!(banner.contains("you have v0.1.3"), "got: {banner:?}");// Update instruction.- assert!(banner.contains("Update with: cua-driver update"), "got: {banner:?}");+ assert!(+ banner.contains("Update with: cua-driver update"),+ "got: {banner:?}"+ );// Release notes URL uses the correct tag prefix.assert!(- banner.contains(- "https://github.com/trycua/cua/releases/tag/cua-driver-rs-v0.1.4"- ),+ banner.contains("https://github.com/trycua/cua/releases/tag/cua-driver-rs-v0.1.4"),"got: {banner:?}",);}diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/cross_platform_behavior_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/cross_platform_behavior_test.rsindex 918ac8a545..86fb24c7f7 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/cross_platform_behavior_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/cross_platform_behavior_test.rs@@ -257,10 +257,9 @@ fn spawn_driver(recording_label: &str, cdp_port: Option<u16>) -> Option<McpDrive{let port = cdp_port.map(|value| value.to_string());match port.as_deref() {- Some(port) => McpDriver::spawn_named_with_env(- recording_label,- &[("CUA_DRIVER_CDP_PORT", port)],- ),+ Some(port) => {+ McpDriver::spawn_named_with_env(recording_label, &[("CUA_DRIVER_CDP_PORT", port)])+ }None => McpDriver::spawn_named(recording_label),}}@@ -295,8 +294,7 @@ fn launch_host_with_evidence(spec: &HostSpec, scenario: &str, evidence: &mut Evi}let recording_label = scenario.to_owned();- let cdp_port = matches!(spec.name, "electron" | "webview2")- .then(allocate_loopback_port);+ let cdp_port = matches!(spec.name, "electron" | "webview2").then(allocate_loopback_port);let mut driver = spawn_driver(&recording_label, cdp_port).unwrap_or_else(|| {panic!("cua-driver could not be started for the required {} fixture",@@ -1448,7 +1446,12 @@ fn run_browser_tool_refusal(fixture: &mut Fixture) -> Observation {let code = response.structured()["refusal"]["code"].as_str().and_then(RefusalCode::from_driver_code)- .unwrap_or_else(|| panic!("embedded browser did not refuse structurally: {}", response.raw));+ .unwrap_or_else(|| {+ panic!(+ "embedded browser did not refuse structurally: {}",+ response.raw+ )+ });assert_eq!(code,RefusalCode::BrowserRouteUnavailable,diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/desktop_scope_linux_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/desktop_scope_linux_test.rsindex ef05567943..98065d2c2d 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/desktop_scope_linux_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/desktop_scope_linux_test.rs@@ -189,7 +189,11 @@ fn desktop_scope_windowless_click_lands_on_control() {"bring_to_front",serde_json::json!({"session": window_session, "pid": pid as i64, "window_id": wid}),);- assert!(!posture.is_error(), "could not foreground GTK3 fixture: {}", posture.text());+ assert!(+ !posture.is_error(),+ "could not foreground GTK3 fixture: {}",+ posture.text()+ );std::thread::sleep(Duration::from_millis(300));driver.start_behavior_recording();@@ -205,9 +209,12 @@ fn desktop_scope_windowless_click_lands_on_control() {let mut post = pre;let mut first_text = String::new();for attempt in 0..12 {- let clicked = driver.call("click", serde_json::json!({- "session": desktop_session, "scope": "desktop", "x": cx, "y": cy- }));+ let clicked = driver.call(+ "click",+ serde_json::json!({+ "session": desktop_session, "scope": "desktop", "x": cx, "y": cy+ }),+ );if attempt == 0 {first_text = clicked.text().to_string();assert!(@@ -259,12 +266,14 @@ fn window_scope_rejects_windowless_click() {*evidence = recording_evidence(driver.recording_dir());start_scope(&mut driver, cell_id, "window");driver.start_behavior_recording();- let r = driver.call("click", serde_json::json!({- "session": cell_id, "scope": "desktop", "x": 100, "y": 100- }));+ let r = driver.call(+ "click",+ serde_json::json!({+ "session": cell_id, "scope": "desktop", "x": 100, "y": 100+ }),+ );assert!(- r.is_error()- && r.structured()["code"].as_str() == Some("desktop_scope_disabled"),+ r.is_error() && r.structured()["code"].as_str() == Some("desktop_scope_disabled"),"window-scope window-less click was NOT rejected: {}",r.text());diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/desktop_scope_macos_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/desktop_scope_macos_test.rsindex e508492937..13860aa49e 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/desktop_scope_macos_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/desktop_scope_macos_test.rs@@ -195,7 +195,11 @@ fn desktop_scope_windowless_click_lands_on_control() {"start_session",serde_json::json!({"session": session, "capture_scope": capture_scope}),);- assert!(!started.is_error(), "start_session failed: {}", started.text());+ assert!(+ !started.is_error(),+ "start_session failed: {}",+ started.text()+ );}let (pid, wid) = launch(&mut driver).expect("required AppKit harness did not launch");@@ -271,7 +275,11 @@ fn window_scope_rejects_windowless_click() {"start_session",serde_json::json!({"session": cell_id, "capture_scope": "window"}),);- assert!(!started.is_error(), "start_session failed: {}", started.text());+ assert!(+ !started.is_error(),+ "start_session failed: {}",+ started.text()+ );driver.start_behavior_recording();let r = driver.call("click",diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/desktop_scope_windows_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/desktop_scope_windows_test.rsindex b119e3de7f..a2a9029dc7 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/desktop_scope_windows_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/desktop_scope_windows_test.rs@@ -167,7 +167,11 @@ fn run_desktop_fixture_case("bring_to_front",serde_json::json!({"session": window_session, "pid": pid as i64, "window_id": wid}),);- assert!(!posture.is_error(), "could not foreground WPF fixture: {}", posture.text());+ assert!(+ !posture.is_error(),+ "could not foreground WPF fixture: {}",+ posture.text()+ );std::thread::sleep(Duration::from_millis(300));driver.start_behavior_recording();test(pid, wid, &window_session, &desktop_session, &mut driver);@@ -201,10 +205,7 @@ fn desktop_scope_capture_returns_screen_dims() {let session = "windows-desktop-state-px-not-applicable-desktop";start_scope(&mut driver, session, "desktop");driver.start_behavior_recording();- let response = driver.call(- "get_desktop_state",- serde_json::json!({"session": session}),- );+ let response = driver.call("get_desktop_state", serde_json::json!({"session": session}));assert!(!response.is_error(),"get_desktop_state errored: {}",@@ -231,9 +232,12 @@ fn desktop_scope_windowless_click_lands_on_control() {|pid, wid, window_session, desktop_session, driver| {let pre = snapshot(driver, window_session, pid, wid);let (x, y) = element_center(&pre, "border-click-target");- let response = driver.call("click", serde_json::json!({- "session": desktop_session, "scope": "desktop", "x": x, "y": y- }));+ let response = driver.call(+ "click",+ serde_json::json!({+ "session": desktop_session, "scope": "desktop", "x": x, "y": y+ }),+ );assert!(!response.is_error(),"desktop click failed: {}",@@ -310,9 +314,12 @@ fn window_scope_rejects_windowless_click() {let session = "windows-window-scope-gate-px-not-applicable";start_scope(&mut driver, session, "window");driver.start_behavior_recording();- let response = driver.call("click", serde_json::json!({- "session": session, "scope": "desktop", "x": 100, "y": 100- }));+ let response = driver.call(+ "click",+ serde_json::json!({+ "session": session, "scope": "desktop", "x": 100, "y": 100+ }),+ );assert!(response.is_error()&& response.structured()["code"].as_str() == Some("desktop_scope_disabled"),diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/harness_libreoffice_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/harness_libreoffice_test.rsindex 532531c053..53f401de65 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/harness_libreoffice_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/harness_libreoffice_test.rs@@ -64,14 +64,18 @@ use cua_driver_testkit::{Driver, McpDriver};fn swriter_exe() -> Option<PathBuf> {if let Ok(p) = std::env::var("LO_SWRITER_EXE") {let pb = PathBuf::from(p);- if pb.exists() { return Some(pb); }+ if pb.exists() {+ return Some(pb);+ }}for candidate in [r"C:\Program Files\LibreOffice\program\swriter.exe",r"C:\Program Files (x86)\LibreOffice\program\swriter.exe",] {let pb = PathBuf::from(candidate);- if pb.exists() { return Some(pb); }+ if pb.exists() {+ return Some(pb);+ }}None}@@ -80,14 +84,18 @@ fn swriter_exe() -> Option<PathBuf> {fn scalc_exe() -> Option<PathBuf> {if let Ok(p) = std::env::var("LO_SCALC_EXE") {let pb = PathBuf::from(p);- if pb.exists() { return Some(pb); }+ if pb.exists() {+ return Some(pb);+ }}for candidate in [r"C:\Program Files\LibreOffice\program\scalc.exe",r"C:\Program Files (x86)\LibreOffice\program\scalc.exe",] {let pb = PathBuf::from(candidate);- if pb.exists() { return Some(pb); }+ if pb.exists() {+ return Some(pb);+ }}None}@@ -109,7 +117,9 @@ impl Drop for LoSession {fn drop(&mut self) {// SAL/VCL soffice.bin daemon hangs around after the parent exits;// best-effort sweep via taskkill so the next test starts clean.- let _ = Command::new("taskkill").args(["/F", "/IM", "soffice.bin"]).output();+ let _ = Command::new("taskkill")+ .args(["/F", "/IM", "soffice.bin"])+ .output();std::thread::sleep(Duration::from_millis(800));}}@@ -125,7 +135,9 @@ fn setup() -> Option<LoSession> {// Sweep any leftover soffice.bin from a prior run so this test gets// a fresh writer pid + clean recovery state.- let _ = Command::new("taskkill").args(["/F", "/IM", "soffice.bin"]).output();+ let _ = Command::new("taskkill")+ .args(["/F", "/IM", "soffice.bin"])+ .output();std::thread::sleep(Duration::from_millis(800));let mut driver = McpDriver::spawn()?;@@ -162,7 +174,11 @@ fn setup() -> Option<LoSession> {let pid = w["pid"].as_u64().unwrap_or(0) as u32;let wid = w["window_id"].as_u64().unwrap_or(0);if pid > 0 && wid > 0 {- return Some(LoSession { driver, writer_pid: pid, writer_wid: wid });+ return Some(LoSession {+ driver,+ writer_pid: pid,+ writer_wid: wid,+ });}}}@@ -196,25 +212,40 @@ fn setup() -> Option<LoSession> {#[test]#[ignore]fn harness_lo_vcl_font_color_split_button_exposes_expand() {- let mut fx = match setup() { Some(s) => s, None => return };+ let mut fx = match setup() {+ Some(s) => s,+ None => return,+ };let (pid, wid) = (fx.writer_pid, fx.writer_wid);let driver = &mut fx.driver;- let snap = driver.call("get_window_state", serde_json::json!({- "pid": pid as i64, "window_id": wid,- "capture_mode": "ax", "query": "Font Color"- }));+ let snap = driver.call(+ "get_window_state",+ serde_json::json!({+ "pid": pid as i64, "window_id": wid,+ "capture_mode": "ax", "query": "Font Color"+ }),+ );let text = snap.text();- assert!(text.contains("SplitButton \"Font Color\""),- "Font Color SplitButton not found in tree: {text:?}");- let line = text.lines().find(|l| l.contains("\"Font Color\"")).unwrap_or("");- assert!(line.contains("expand"),+ assert!(+ text.contains("SplitButton \"Font Color\""),+ "Font Color SplitButton not found in tree: {text:?}"+ );+ let line = text+ .lines()+ .find(|l| l.contains("\"Font Color\""))+ .unwrap_or("");+ assert!(+ line.contains("expand"),"Expected `expand` in actions on Font Color SplitButton — got {line:?}. \The MSAA fallback may not be running for SALFRAME (check uia/mod.rs \- SAL class detection — should route ALL SAL* classes through msaa.rs).");- assert!(line.contains("invoke"),+ SAL class detection — should route ALL SAL* classes through msaa.rs)."+ );+ assert!(+ line.contains("invoke"),"Expected `invoke` to remain in actions alongside `expand` — got {line:?}. \- MSAA walker should expose both press and dropdown halves.");+ MSAA walker should expose both press and dropdown halves."+ );}// ── Test 2: action:"expand" actually opens the color picker ─────────────────@@ -240,72 +271,106 @@ fn harness_lo_vcl_font_color_split_button_exposes_expand() {#[test]#[ignore]fn harness_lo_vcl_font_color_expand_opens_picker() {- let mut fx = match setup() { Some(s) => s, None => return };+ let mut fx = match setup() {+ Some(s) => s,+ None => return,+ };let (pid, wid) = (fx.writer_pid, fx.writer_wid);let driver = &mut fx.driver;// Bring Writer to foreground so SendInput click lands on it.- let _ = driver.call("bring_to_front", serde_json::json!({- "pid": pid as i64, "window_id": wid- }));+ let _ = driver.call(+ "bring_to_front",+ serde_json::json!({+ "pid": pid as i64, "window_id": wid+ }),+ );std::thread::sleep(Duration::from_millis(400));- let snap = driver.call("get_window_state", serde_json::json!({- "pid": pid as i64, "window_id": wid,- "capture_mode": "ax", "query": "Font Color"- }));+ let snap = driver.call(+ "get_window_state",+ serde_json::json!({+ "pid": pid as i64, "window_id": wid,+ "capture_mode": "ax", "query": "Font Color"+ }),+ );let text = snap.text();- let line = text.lines()+ let line = text+ .lines().find(|l| l.contains("\"Font Color\"") && l.contains("expand"))- .unwrap_or_else(|| panic!("Font Color SplitButton with `expand` action not found: {text:?}"));+ .unwrap_or_else(|| {+ panic!("Font Color SplitButton with `expand` action not found: {text:?}")+ });let s = line.find('[').expect("element_index bracket open");let e = line[s..].find(']').expect("element_index bracket close") + s;- let idx: u64 = line[s+1..e].trim().parse()+ let idx: u64 = line[s + 1..e]+ .trim()+ .parse().unwrap_or_else(|_| panic!("could not parse element_index from line {line:?}"));// Snapshot windows under our pid BEFORE the click.- let before = driver.call("list_windows", serde_json::json!({- "pid": pid as i64- }));- let before_ids: std::collections::HashSet<u64> = before- .structured()["windows"].as_array()+ let before = driver.call(+ "list_windows",+ serde_json::json!({+ "pid": pid as i64+ }),+ );+ let before_ids: std::collections::HashSet<u64> = before.structured()["windows"]+ .as_array().map(|a| a.iter().filter_map(|w| w["window_id"].as_u64()).collect()).unwrap_or_default();- let resp = driver.call("click", serde_json::json!({- "pid": pid as i64, "window_id": wid,- "element_index": idx, "action": "expand"- }));+ let resp = driver.call(+ "click",+ serde_json::json!({+ "pid": pid as i64, "window_id": wid,+ "element_index": idx, "action": "expand"+ }),+ );let resp_text = resp.text();- assert!(resp_text.starts_with("✅"),- "click(action:expand) failed: {resp_text:?}");- assert!(resp_text.contains("dropdown half"),+ assert!(+ resp_text.starts_with("✅"),+ "click(action:expand) failed: {resp_text:?}"+ );+ assert!(+ resp_text.contains("dropdown half"),"Expected response to mention dropdown half — got {resp_text:?}. \- The MSAA dispatch path may not have triggered.");+ The MSAA dispatch path may not have triggered."+ );// Let the picker spawn.std::thread::sleep(Duration::from_millis(900));- let after = driver.call("list_windows", serde_json::json!({- "pid": pid as i64- }));- let new_wins: Vec<&serde_json::Value> = after- .structured()["windows"].as_array()- .map(|a| a.iter()- .filter(|w| {- let id = w["window_id"].as_u64();- id.map(|i| !before_ids.contains(&i)).unwrap_or(false)- })- .collect())+ let after = driver.call(+ "list_windows",+ serde_json::json!({+ "pid": pid as i64+ }),+ );+ let new_wins: Vec<&serde_json::Value> = after.structured()["windows"]+ .as_array()+ .map(|a| {+ a.iter()+ .filter(|w| {+ let id = w["window_id"].as_u64();+ id.map(|i| !before_ids.contains(&i)).unwrap_or(false)+ })+ .collect()+ }).unwrap_or_default();let picker = new_wins.iter().find(|w| {- w["title"].as_str().map(|t| t.contains("Font Color")).unwrap_or(false)+ w["title"]+ .as_str()+ .map(|t| t.contains("Font Color"))+ .unwrap_or(false)});- assert!(picker.is_some(),+ assert!(+ picker.is_some(),"No new window titled 'Font Color' appeared after click(action:expand). \new_windows={new_wins:?}. The right-edge dispatch may have hit the \wrong pixel (LO's toolbar scaled differently?) or the picker spawned \- as a child window instead of a top-level.");+ as a child window instead of a top-level."+ );}// ── Working path: SALSUBFRAME modal dialogs accept SendInput input ─────────@@ -336,39 +401,57 @@ fn harness_lo_vcl_font_color_expand_opens_picker() {#[test]#[ignore]fn harness_lo_vcl_modal_input_roundtrip_works() {- let mut fx = match setup() { Some(s) => s, None => return };+ let mut fx = match setup() {+ Some(s) => s,+ None => return,+ };let (pid, wid) = (fx.writer_pid, fx.writer_wid);let driver = &mut fx.driver;std::thread::sleep(Duration::from_millis(800));- let open_resp = driver.call("hotkey", serde_json::json!({- "pid": pid as i64, "window_id": wid,- "keys": ["ctrl", "h"], "delivery_mode": "foreground"- }));+ let open_resp = driver.call(+ "hotkey",+ serde_json::json!({+ "pid": pid as i64, "window_id": wid,+ "keys": ["ctrl", "h"], "delivery_mode": "foreground"+ }),+ );let open_text = open_resp.text();- assert!(open_text.starts_with("✅"),- "hotkey(ctrl+h, foreground) failed: {open_text:?}");+ assert!(+ open_text.starts_with("✅"),+ "hotkey(ctrl+h, foreground) failed: {open_text:?}"+ );let dialog_wid = {let deadline = std::time::Instant::now() + Duration::from_secs(8);loop {- let wins = driver.call("list_windows", serde_json::json!({- "pid": pid as i64- }));- let found = wins.structured()["windows"].as_array()- .and_then(|a| a.iter().find_map(|w| {+ let wins = driver.call(+ "list_windows",+ serde_json::json!({+ "pid": pid as i64+ }),+ );+ let found = wins.structured()["windows"].as_array().and_then(|a| {+ a.iter().find_map(|w| {let title = w["title"].as_str().unwrap_or("");let id = w["window_id"].as_u64();- if id != Some(wid)- && (title.contains("Find") || title.contains("Replace"))- { id } else { None }- }));- if let Some(id) = found { break id; }+ if id != Some(wid) && (title.contains("Find") || title.contains("Replace")) {+ id+ } else {+ None+ }+ })+ });+ if let Some(id) = found {+ break id;+ }if std::time::Instant::now() > deadline {- panic!("Find & Replace dialog did not appear after Ctrl+H — \+ panic!(+ "Find & Replace dialog did not appear after Ctrl+H — \Writer accelerator may have regressed under \- foreground SendInput on SALFRAME.");+ foreground SendInput on SALFRAME."+ );}std::thread::sleep(Duration::from_millis(300));}@@ -377,49 +460,76 @@ fn harness_lo_vcl_modal_input_roundtrip_works() {// Snapshot the dialog — MSAA walker should produce a real tree// with the dialog's buttons and edit fields, NOT the old skip// stub.- let dialog_ax = driver.call("get_window_state", serde_json::json!({- "pid": pid as i64, "window_id": dialog_wid, "capture_mode": "ax"- }));+ let dialog_ax = driver.call(+ "get_window_state",+ serde_json::json!({+ "pid": pid as i64, "window_id": dialog_wid, "capture_mode": "ax"+ }),+ );let dialog_text = dialog_ax.text();- assert!(!dialog_text.contains("SAL/VCL target, UIA walk skipped"),+ assert!(+ !dialog_text.contains("SAL/VCL target, UIA walk skipped"),"Got the old skip-stub message — MSAA fallback did not engage on \- this SALSUBFRAME. Snapshot was: {dialog_text:?}");- assert!(dialog_text.contains("Button \"Close\""),+ this SALSUBFRAME. Snapshot was: {dialog_text:?}"+ );+ assert!(+ dialog_text.contains("Button \"Close\""),"Expected MSAA walker to expose a 'Close' Button in the Find & Replace \- dialog tree (it's a documented child via accChild). Snapshot was: {dialog_text:?}");+ dialog tree (it's a documented child via accChild). Snapshot was: {dialog_text:?}"+ );// Sanity: should have several actionable element_indices, not zero.- let actionable_count = dialog_text.lines()+ let actionable_count = dialog_text+ .lines().filter(|l| l.contains("actions=[invoke")).count();- assert!(actionable_count >= 4,+ assert!(+ actionable_count >= 4,"Expected ≥4 actionable elements in Find & Replace via MSAA walker, \- got {actionable_count}. Tree: {dialog_text:?}");+ got {actionable_count}. Tree: {dialog_text:?}"+ );// Foreground Escape should close the dialog.- let esc_resp = driver.call("press_key", serde_json::json!({- "pid": pid as i64, "window_id": dialog_wid,- "key": "escape", "delivery_mode": "foreground"- }));+ let esc_resp = driver.call(+ "press_key",+ serde_json::json!({+ "pid": pid as i64, "window_id": dialog_wid,+ "key": "escape", "delivery_mode": "foreground"+ }),+ );let esc_text = esc_resp.text();- assert!(esc_text.starts_with("✅"),- "press_key(escape, foreground) returned an error: {esc_text:?}");+ assert!(+ esc_text.starts_with("✅"),+ "press_key(escape, foreground) returned an error: {esc_text:?}"+ );std::thread::sleep(Duration::from_millis(700));- let wins_after = driver.call("list_windows", serde_json::json!({- "pid": pid as i64- }));- let still_open = wins_after.structured()["windows"].as_array()- .map(|a| a.iter().any(|w| w["window_id"].as_u64() == Some(dialog_wid)))+ let wins_after = driver.call(+ "list_windows",+ serde_json::json!({+ "pid": pid as i64+ }),+ );+ let still_open = wins_after.structured()["windows"]+ .as_array()+ .map(|a| {+ a.iter()+ .any(|w| w["window_id"].as_u64() == Some(dialog_wid))+ }).unwrap_or(false);- assert!(!still_open,+ assert!(+ !still_open,"Find & Replace dialog stayed open after foreground Escape — \SAL modal input dispatch regressed. Check uia/mod.rs SAL-class \- handling and the press_key SendInput path.");+ handling and the press_key SendInput path."+ );// Cleanup: kill the LO process — Drop impl sweeps soffice.bin.- let _ = driver.call("kill_app", serde_json::json!({- "pid": pid as i64- }));+ let _ = driver.call(+ "kill_app",+ serde_json::json!({+ "pid": pid as i64+ }),+ );}// ── Test 4: All toolbar SplitButtons expose `expand` ────────────────────────@@ -442,36 +552,50 @@ fn harness_lo_vcl_modal_input_roundtrip_works() {#[test]#[ignore]fn harness_lo_vcl_all_toolbar_split_buttons_expose_expand() {- let mut fx = match setup() { Some(s) => s, None => return };+ let mut fx = match setup() {+ Some(s) => s,+ None => return,+ };let (pid, wid) = (fx.writer_pid, fx.writer_wid);let driver = &mut fx.driver;- let snap = driver.call("get_window_state", serde_json::json!({- "pid": pid as i64, "window_id": wid, "capture_mode": "ax"- }));+ let snap = driver.call(+ "get_window_state",+ serde_json::json!({+ "pid": pid as i64, "window_id": wid, "capture_mode": "ax"+ }),+ );let text = snap.text();let splitbutton_lines: Vec<&str> = text.lines().filter(|l| l.contains("SplitButton") && l.contains("actions=[")).collect();- let with_expand: Vec<&&str> = splitbutton_lines.iter()+ let with_expand: Vec<&&str> = splitbutton_lines+ .iter().filter(|l| l.contains("expand")).collect();- assert!(splitbutton_lines.len() >= 15,+ assert!(+ splitbutton_lines.len() >= 15,"Expected ≥15 SplitButtons in LO Writer toolbar tree, got {}. \Possible MSAA walker regression. Full snapshot first 1500 chars: {}",splitbutton_lines.len(),- &text.chars().take(1500).collect::<String>());- assert_eq!(with_expand.len(), splitbutton_lines.len(),+ &text.chars().take(1500).collect::<String>()+ );+ assert_eq!(+ with_expand.len(),+ splitbutton_lines.len(),"{}/{} SplitButtons report `expand`. The MSAA role→actions \mapping may have dropped one of BUTTONDROPDOWN / BUTTONMENU / \BUTTONDROPDOWNGRID / SPLITBUTTON. Missing-expand lines:\n{}",- with_expand.len(), splitbutton_lines.len(),- splitbutton_lines.iter()+ with_expand.len(),+ splitbutton_lines.len(),+ splitbutton_lines+ .iter().filter(|l| !l.contains("expand")).map(|l| l.trim()).collect::<Vec<_>>()- .join("\n"));+ .join("\n")+ );}// ── Test 5: End-to-end color-pick ───────────────────────────────────────────@@ -492,115 +616,171 @@ fn harness_lo_vcl_all_toolbar_split_buttons_expose_expand() {#[test]#[ignore]fn harness_lo_vcl_color_pick_green_end_to_end() {- let mut fx = match setup() { Some(s) => s, None => return };+ let mut fx = match setup() {+ Some(s) => s,+ None => return,+ };let (pid, wid) = (fx.writer_pid, fx.writer_wid);let driver = &mut fx.driver;// Foreground first so type_text + Ctrl+A land on Writer.- let _ = driver.call("bring_to_front", serde_json::json!({- "pid": pid as i64, "window_id": wid- }));+ let _ = driver.call(+ "bring_to_front",+ serde_json::json!({+ "pid": pid as i64, "window_id": wid+ }),+ );std::thread::sleep(Duration::from_millis(400));- let _ = driver.call("type_text", serde_json::json!({- "pid": pid as i64, "window_id": wid,- "text": "color pick regression"- }));+ let _ = driver.call(+ "type_text",+ serde_json::json!({+ "pid": pid as i64, "window_id": wid,+ "text": "color pick regression"+ }),+ );std::thread::sleep(Duration::from_millis(400));- let _ = driver.call("hotkey", serde_json::json!({- "pid": pid as i64, "window_id": wid,- "keys": ["ctrl", "a"], "delivery_mode": "foreground"- }));+ let _ = driver.call(+ "hotkey",+ serde_json::json!({+ "pid": pid as i64, "window_id": wid,+ "keys": ["ctrl", "a"], "delivery_mode": "foreground"+ }),+ );std::thread::sleep(Duration::from_millis(400));// Locate Font Color element_index in Writer's MSAA tree.- let snap = driver.call("get_window_state", serde_json::json!({- "pid": pid as i64, "window_id": wid,- "capture_mode": "ax", "query": "Font Color"- }));+ let snap = driver.call(+ "get_window_state",+ serde_json::json!({+ "pid": pid as i64, "window_id": wid,+ "capture_mode": "ax", "query": "Font Color"+ }),+ );let snap_text = snap.text();- let fc_line = snap_text.lines()+ let fc_line = snap_text+ .lines().find(|l| l.contains("\"Font Color\"") && l.contains("expand")).unwrap_or_else(|| panic!("Font Color with `expand` not found in tree: {snap_text:?}"));let s = fc_line.find('[').expect("[ in fc_line");let e = fc_line[s..].find(']').expect("] in fc_line") + s;- let fc_idx: u64 = fc_line[s+1..e].trim().parse().expect("fc element_index");+ let fc_idx: u64 = fc_line[s + 1..e].trim().parse().expect("fc element_index");// Snapshot which windows existed BEFORE opening the picker so// we can isolate the picker on appearance.- let before = driver.call("list_windows", serde_json::json!({- "pid": pid as i64- }));- let before_ids: std::collections::HashSet<u64> = before- .structured()["windows"].as_array()+ let before = driver.call(+ "list_windows",+ serde_json::json!({+ "pid": pid as i64+ }),+ );+ let before_ids: std::collections::HashSet<u64> = before.structured()["windows"]+ .as_array().map(|a| a.iter().filter_map(|w| w["window_id"].as_u64()).collect()).unwrap_or_default();// Open the dropdown.- let open_resp = driver.call("click", serde_json::json!({- "pid": pid as i64, "window_id": wid,- "element_index": fc_idx, "action": "expand"- }));+ let open_resp = driver.call(+ "click",+ serde_json::json!({+ "pid": pid as i64, "window_id": wid,+ "element_index": fc_idx, "action": "expand"+ }),+ );let open_text = open_resp.text();- assert!(open_text.contains("dropdown half"),- "click(action:expand) did not dispatch via MSAA dropdown path: {open_text:?}");+ assert!(+ open_text.contains("dropdown half"),+ "click(action:expand) did not dispatch via MSAA dropdown path: {open_text:?}"+ );std::thread::sleep(Duration::from_millis(900));// Find the picker window.- let after = driver.call("list_windows", serde_json::json!({- "pid": pid as i64- }));+ let after = driver.call(+ "list_windows",+ serde_json::json!({+ "pid": pid as i64+ }),+ );let picker_wid = after.structured()["windows"].as_array()- .and_then(|a| a.iter().find_map(|w| {- let id = w["window_id"].as_u64();- let title = w["title"].as_str().unwrap_or("");- if id.map(|i| !before_ids.contains(&i)).unwrap_or(false)- && title.contains("Font Color")- { id } else { None }- }))+ .and_then(|a| {+ a.iter().find_map(|w| {+ let id = w["window_id"].as_u64();+ let title = w["title"].as_str().unwrap_or("");+ if id.map(|i| !before_ids.contains(&i)).unwrap_or(false)+ && title.contains("Font Color")+ {+ id+ } else {+ None+ }+ })+ }).unwrap_or_else(|| panic!("No new 'Font Color' picker window appeared"));// Walk the picker tree to find a green color cell.- let psnap = driver.call("get_window_state", serde_json::json!({- "pid": pid as i64, "window_id": picker_wid, "capture_mode": "ax"- }));+ let psnap = driver.call(+ "get_window_state",+ serde_json::json!({+ "pid": pid as i64, "window_id": picker_wid, "capture_mode": "ax"+ }),+ );let psnap_text = psnap.text();- let green_line = psnap_text.lines()+ let green_line = psnap_text+ .lines().find(|l| l.contains("\"Green\"") && l.contains("[") && l.contains("actions=[invoke"))- .unwrap_or_else(|| panic!(- "No 'Green' ListItem in picker tree. The MSAA walker may have \+ .unwrap_or_else(|| {+ panic!(+ "No 'Green' ListItem in picker tree. The MSAA walker may have \truncated the color grid or LO's locale renamed the color. \First 1500 chars: {}",- &psnap_text.chars().take(1500).collect::<String>()));+ &psnap_text.chars().take(1500).collect::<String>()+ )+ });let s = green_line.find('[').expect("[ in green");let e = green_line[s..].find(']').expect("] in green") + s;- let green_idx: u64 = green_line[s+1..e].trim().parse().expect("green element_index");+ let green_idx: u64 = green_line[s + 1..e]+ .trim()+ .parse()+ .expect("green element_index");// Pick it. Default action (invoke) clicks center via MSAA dispatch.- let pick_resp = driver.call("click", serde_json::json!({- "pid": pid as i64, "window_id": picker_wid,- "element_index": green_idx- }));+ let pick_resp = driver.call(+ "click",+ serde_json::json!({+ "pid": pid as i64, "window_id": picker_wid,+ "element_index": green_idx+ }),+ );let pick_text = pick_resp.text();- assert!(pick_text.starts_with("✅"),- "click on Green color cell failed: {pick_text:?}");+ assert!(+ pick_text.starts_with("✅"),+ "click on Green color cell failed: {pick_text:?}"+ );std::thread::sleep(Duration::from_millis(700));// Verify the picker closed (LO closes the popup after a color is// selected — the canonical "color applied" signal). If it// didn't, the click didn't actually land on the cell.- let after2 = driver.call("list_windows", serde_json::json!({- "pid": pid as i64- }));+ let after2 = driver.call(+ "list_windows",+ serde_json::json!({+ "pid": pid as i64+ }),+ );let still_open = after2.structured()["windows"].as_array()- .map(|a| a.iter().any(|w| w["window_id"].as_u64() == Some(picker_wid)))+ .map(|a| {+ a.iter()+ .any(|w| w["window_id"].as_u64() == Some(picker_wid))+ }).unwrap_or(false);- assert!(!still_open,+ assert!(+ !still_open,"Picker stayed open after click on Green — the cell click \- didn't land. LO didn't apply the color.");+ didn't land. LO didn't apply the color."+ );}// ── Test 6: Recovery dialog walks via MSAA ──────────────────────────────────@@ -625,27 +805,38 @@ fn harness_lo_vcl_recovery_dialog_walks_via_msaa() {// First: launch Writer WITHOUT -norestore (we WANT recovery// behavior), type something, then force-kill so LO marks the// session as crashed.- let writer = match swriter_exe() { Some(p) => p, None => return };- let _ = Command::new("taskkill").args(["/F", "/IM", "soffice.bin"]).output();+ let writer = match swriter_exe() {+ Some(p) => p,+ None => return,+ };+ let _ = Command::new("taskkill")+ .args(["/F", "/IM", "soffice.bin"])+ .output();std::thread::sleep(Duration::from_millis(800));// Launch (no -norestore, no -nologo flag → default behavior).let mut crash_proc = match Command::new(&writer)- .stdout(Stdio::null()).stderr(Stdio::null())- .spawn() {- Ok(p) => p,- Err(_) => return,- };+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ {+ Ok(p) => p,+ Err(_) => return,+ };std::thread::sleep(Duration::from_secs(5));let _ = crash_proc.kill();let _ = crash_proc.wait();// Force-kill the actual soffice.bin worker too (the launcher is what// we just killed; the real LO process is a fork).- let _ = Command::new("taskkill").args(["/F", "/IM", "soffice.bin"]).output();+ let _ = Command::new("taskkill")+ .args(["/F", "/IM", "soffice.bin"])+ .output();std::thread::sleep(Duration::from_secs(2));// Re-launch Writer — Recovery dialog should appear.- let Some(mut driver) = McpDriver::spawn() else { return };+ let Some(mut driver) = McpDriver::spawn() else {+ return;+ };if driver.reaper().spawn(@@ -667,7 +858,10 @@ fn harness_lo_vcl_recovery_dialog_walks_via_msaa() {let resp = driver.call("list_windows", serde_json::json!({}));if let Some(wins) = resp.structured()["windows"].as_array() {if let Some(w) = wins.iter().find(|w| {- w["title"].as_str().map(|t| t.contains("Recovery")).unwrap_or(false)+ w["title"]+ .as_str()+ .map(|t| t.contains("Recovery"))+ .unwrap_or(false)}) {let id = w["window_id"].as_u64();let pid = w["pid"].as_u64().map(|p| p as u32);@@ -684,34 +878,46 @@ fn harness_lo_vcl_recovery_dialog_walks_via_msaa() {match recovery_wid_pid {None => {- eprintln!("Recovery dialog did not appear — LO didn't enter recovery \+ eprintln!(+ "Recovery dialog did not appear — LO didn't enter recovery \state (possibly disabled in user config, or our crash \trigger didn't take effect). Test cannot assert MSAA \walk on a dialog that doesn't exist; logging and \- returning OK.");+ returning OK."+ );}Some((rwid, rpid)) => {- let snap = driver.call("get_window_state",+ let snap = driver.call(+ "get_window_state",serde_json::json!({"pid": rpid as i64, "window_id": rwid, "capture_mode": "ax"- }));+ }),+ );let text = snap.text();- assert!(!text.contains("SAL/VCL target, UIA walk skipped"),+ assert!(+ !text.contains("SAL/VCL target, UIA walk skipped"),"Recovery dialog returned the old SAL-skip stub — MSAA fallback \- isn't engaging on SALFRAME Recovery dialogs.");- assert!(text.contains("Button \"Discard All\""),+ isn't engaging on SALFRAME Recovery dialogs."+ );+ assert!(+ text.contains("Button \"Discard All\""),"Recovery dialog tree should expose `Discard All` Button via MSAA. \- Got: {text:?}");- assert!(text.contains("Button \"Recover Selected\""),+ Got: {text:?}"+ );+ assert!(+ text.contains("Button \"Recover Selected\""),"Recovery dialog tree should expose `Recover Selected` Button via MSAA. \- Got: {text:?}");+ Got: {text:?}"+ );}}// Cleanup: reaper kills the MCP driver + the spawned writer on drop;// sweep the soffice.bin daemon that outlives the launcher.drop(driver);- let _ = Command::new("taskkill").args(["/F", "/IM", "soffice.bin"]).output();+ let _ = Command::new("taskkill")+ .args(["/F", "/IM", "soffice.bin"])+ .output();std::thread::sleep(Duration::from_millis(800));}@@ -728,12 +934,19 @@ fn harness_lo_vcl_recovery_dialog_walks_via_msaa() {#[test]#[ignore]fn harness_lo_vcl_calc_msaa_smoke() {- let scalc = match scalc_exe() { Some(p) => p, None => return };+ let scalc = match scalc_exe() {+ Some(p) => p,+ None => return,+ };- let _ = Command::new("taskkill").args(["/F", "/IM", "soffice.bin"]).output();+ let _ = Command::new("taskkill")+ .args(["/F", "/IM", "soffice.bin"])+ .output();std::thread::sleep(Duration::from_millis(800));- let Some(mut driver) = McpDriver::spawn() else { return };+ let Some(mut driver) = McpDriver::spawn() else {+ return;+ };if driver.reaper().spawn(@@ -756,7 +969,10 @@ fn harness_lo_vcl_calc_msaa_smoke() {let r = driver.call("list_windows", serde_json::json!({}));if let Some(wins) = r.structured()["windows"].as_array() {if let Some(w) = wins.iter().find(|w| {- w["title"].as_str().map(|t| t.contains("LibreOffice Calc")).unwrap_or(false)+ w["title"]+ .as_str()+ .map(|t| t.contains("LibreOffice Calc"))+ .unwrap_or(false)}) {let id = w["window_id"].as_u64();let pid = w["pid"].as_u64().map(|p| p as u32);@@ -774,32 +990,46 @@ fn harness_lo_vcl_calc_msaa_smoke() {let (cwid, cpid) = match calc_wid_pid {Some(v) => v,None => {- let _ = Command::new("taskkill").args(["/F", "/IM", "soffice.bin"]).output();+ let _ = Command::new("taskkill")+ .args(["/F", "/IM", "soffice.bin"])+ .output();panic!("LO Calc window did not appear within 20 s");}};- let snap = driver.call("get_window_state",+ let snap = driver.call(+ "get_window_state",serde_json::json!({"pid": cpid as i64, "window_id": cwid, "capture_mode": "ax"- }));+ }),+ );let text = snap.text();- assert!(!text.contains("SAL/VCL target, UIA walk skipped"),- "Calc returned the old SAL-skip stub — MSAA didn't engage.");- let sb_with_expand = text.lines()+ assert!(+ !text.contains("SAL/VCL target, UIA walk skipped"),+ "Calc returned the old SAL-skip stub — MSAA didn't engage."+ );+ let sb_with_expand = text+ .lines().filter(|l| l.contains("SplitButton") && l.contains("expand")).count();- assert!(sb_with_expand >= 15,+ assert!(+ sb_with_expand >= 15,"Expected ≥15 SplitButtons with `expand` in Calc toolbar (proves MSAA \generalizes beyond Writer). Got {sb_with_expand}. The MSAA role \- mapping may differ in Calc, or the toolbar config is unexpectedly slim.");+ mapping may differ in Calc, or the toolbar config is unexpectedly slim."+ );// Cleanup: reaper kills the MCP driver + the spawned calc on drop;// sweep the soffice.bin daemon that outlives the launcher.- let _ = driver.call("kill_app", serde_json::json!({- "pid": cpid as i64- }));+ let _ = driver.call(+ "kill_app",+ serde_json::json!({+ "pid": cpid as i64+ }),+ );drop(driver);- let _ = Command::new("taskkill").args(["/F", "/IM", "soffice.bin"]).output();+ let _ = Command::new("taskkill")+ .args(["/F", "/IM", "soffice.bin"])+ .output();std::thread::sleep(Duration::from_millis(800));}diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/harness_web_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/harness_web_test.rsindex 3e85411c51..4a87868558 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/harness_web_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/harness_web_test.rs@@ -23,7 +23,9 @@ use cua_driver_testkit::e2e::{};use cua_driver_testkit::observer::TargetWindow;use cua_driver_testkit::sentinel::run_with_background_oracles;-use cua_driver_testkit::{harness_app, spawn_in_job, Driver, FixtureJournal, McpDriver, ToolResponse};+use cua_driver_testkit::{+ harness_app, spawn_in_job, Driver, FixtureJournal, McpDriver, ToolResponse,+};// ── workspace paths ──────────────────────────────────────────────────────────diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_element_token_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_element_token_test.rsindex ca2fd05109..21a31d045e 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_element_token_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_element_token_test.rs@@ -49,14 +49,20 @@ fn fetch_tools_list() -> Option<serde_json::Value> {let stdin = child.stdin.as_mut().unwrap();let mut stdout = BufReader::new(child.stdout.as_mut().unwrap());- send_request(stdin, &serde_json::json!({- "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}- }));+ send_request(+ stdin,+ &serde_json::json!({+ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}+ }),+ );let _ = read_response(&mut stdout);- send_request(stdin, &serde_json::json!({- "jsonrpc": "2.0", "id": 2, "method": "tools/list"- }));+ send_request(+ stdin,+ &serde_json::json!({+ "jsonrpc": "2.0", "id": 2, "method": "tools/list"+ }),+ );let resp = read_response(&mut stdout);child.kill().ok();return Some(resp);@@ -74,7 +80,8 @@ fn token_accepting_tools_advertise_element_token_in_schema_and_capabilities() {Some(r) => r,None => return,};- let tools = resp["result"]["tools"].as_array()+ let tools = resp["result"]["tools"]+ .as_array().expect("tools/list response missing tools array");// Tools that gained `element_token` in Surface 6. Keep in sync with@@ -91,18 +98,21 @@ fn token_accepting_tools_advertise_element_token_in_schema_and_capabilities() {];for tool_name in TOKEN_TOOLS {- let tool = tools.iter()+ let tool = tools+ .iter().find(|t| t["name"].as_str() == Some(tool_name)).unwrap_or_else(|| panic!("tool {tool_name:?} missing from tools/list"));// (a) inputSchema.properties.element_token present, type=string.- let props = tool["inputSchema"]["properties"].as_object()+ let props = tool["inputSchema"]["properties"]+ .as_object().unwrap_or_else(|| panic!("{tool_name} has no inputSchema.properties"));- let et = props.get("element_token")- .unwrap_or_else(|| panic!(+ let et = props.get("element_token").unwrap_or_else(|| {+ panic!("Surface 6: {tool_name} must advertise an `element_token` input field — \missing from schema properties: {props:?}"- ));+ )+ });assert_eq!(et["type"].as_str(),Some("string"),@@ -110,7 +120,8 @@ fn token_accepting_tools_advertise_element_token_in_schema_and_capabilities() {);// (b) capabilities array includes `accessibility.element_tokens`.- let caps: Vec<&str> = tool["capabilities"].as_array()+ let caps: Vec<&str> = tool["capabilities"]+ .as_array().unwrap_or_else(|| panic!("{tool_name} capabilities missing")).iter().filter_map(|v| v.as_str())@@ -134,11 +145,16 @@ fn get_window_state_claims_element_tokens_capability() {None => return,};let tools = resp["result"]["tools"].as_array().expect("tools array");- let gws = tools.iter()+ let gws = tools+ .iter().find(|t| t["name"].as_str() == Some("get_window_state")).expect("get_window_state missing");- let caps: Vec<&str> = gws["capabilities"].as_array().unwrap()- .iter().filter_map(|v| v.as_str()).collect();+ let caps: Vec<&str> = gws["capabilities"]+ .as_array()+ .unwrap()+ .iter()+ .filter_map(|v| v.as_str())+ .collect();assert!(caps.contains(&"accessibility.element_tokens"),"Surface 6: get_window_state must claim accessibility.element_tokens \@@ -160,12 +176,18 @@ fn element_index_field_still_present_on_token_accepting_tools() {let tools = resp["result"]["tools"].as_array().expect("tools array");const TOKEN_TOOLS: &[&str] = &[- "click", "double_click", "right_click",- "scroll", "type_text", "press_key", "set_value",+ "click",+ "double_click",+ "right_click",+ "scroll",+ "type_text",+ "press_key",+ "set_value",];for tool_name in TOKEN_TOOLS {- let tool = tools.iter()+ let tool = tools+ .iter().find(|t| t["name"].as_str() == Some(tool_name)).unwrap_or_else(|| panic!("{tool_name} missing"));let props = tool["inputSchema"]["properties"].as_object().unwrap();diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_handshake_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_handshake_test.rsindex 5a7982cd75..63b65985eb 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_handshake_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_handshake_test.rs@@ -13,7 +13,9 @@ use cua_driver_testkit::RawDriver;#[test]#[cfg(any(target_os = "macos", target_os = "windows"))]fn initialize_handshake() {- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };// 1. Send initialize request.d.send(&serde_json::json!({@@ -47,13 +49,20 @@ fn initialize_handshake() {assert!(!tools.is_empty(), "Should have at least one tool");// Verify tool names match reference implementation.- let tool_names: Vec<&str> = tools.iter()- .filter_map(|t| t["name"].as_str())- .collect();- for expected in &["list_apps", "list_windows", "get_window_state", "click", "type_text", "press_key"] {+ let tool_names: Vec<&str> = tools.iter().filter_map(|t| t["name"].as_str()).collect();+ for expected in &[+ "list_apps",+ "list_windows",+ "get_window_state",+ "click",+ "type_text",+ "press_key",+ ] {assert!(tool_names.contains(expected),- "Missing tool: {} (have: {:?})", expected, tool_names+ "Missing tool: {} (have: {:?})",+ expected,+ tool_names);}@@ -69,7 +78,9 @@ fn initialize_handshake() {fn all_expected_tools_registered() {//! Verify that all tools from the reference implementation are registered.//! Adding a new tool to the reference requires adding it to this list.- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();@@ -77,26 +88,47 @@ fn all_expected_tools_registered() {d.send(&serde_json::json!({"jsonrpc":"2.0","id":2,"method":"tools/list"}));let resp = d.recv();let tools = resp["result"]["tools"].as_array().expect("tools array");- let names: std::collections::HashSet<&str> = tools.iter()- .filter_map(|t| t["name"].as_str())- .collect();+ let names: std::collections::HashSet<&str> =+ tools.iter().filter_map(|t| t["name"].as_str()).collect();// Baseline roster that must be registered on every platform. (The old// Windows mirror additionally listed type_text_chars + screenshot, which// the Windows build does NOT register — a stale, never-run assertion.)let expected: &[&str] = &[- "list_apps", "list_windows", "get_window_state", "launch_app",- "click", "double_click", "right_click", "type_text",- "press_key", "hotkey", "set_value", "scroll", "zoom",- "get_screen_size", "get_cursor_position",- "move_cursor", "set_agent_cursor_enabled", "set_agent_cursor_motion",- "get_agent_cursor_state", "check_permissions", "get_config", "set_config",+ "list_apps",+ "list_windows",+ "get_window_state",+ "launch_app",+ "click",+ "double_click",+ "right_click",+ "type_text",+ "press_key",+ "hotkey",+ "set_value",+ "scroll",+ "zoom",+ "get_screen_size",+ "get_cursor_position",+ "move_cursor",+ "set_agent_cursor_enabled",+ "set_agent_cursor_motion",+ "get_agent_cursor_state",+ "check_permissions",+ "get_config",+ "set_config","get_accessibility_tree",- "start_recording", "stop_recording", "get_recording_state", "replay_trajectory",+ "start_recording",+ "stop_recording",+ "get_recording_state",+ "replay_trajectory","page",];for name in expected {- assert!(names.contains(name), "Missing tool: {name} (registered: {names:?})");+ assert!(+ names.contains(name),+ "Missing tool: {name} (registered: {names:?})"+ );}}@@ -109,7 +141,9 @@ fn tools_list_includes_per_tool_capabilities() {//! by capability instead of hardcoding tool names, so this is the//! wire contract. Additive-only — existing keys must still be//! present.- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();@@ -125,37 +159,66 @@ fn tools_list_includes_per_tool_capabilities() {// without a mapping in `default_capabilities_for`).for tool in tools {let name = tool["name"].as_str().unwrap_or("<no name>");- assert!(tool["capabilities"].is_array(),- "tool {name:?} missing capabilities array: {tool:?}");+ assert!(+ tool["capabilities"].is_array(),+ "tool {name:?} missing capabilities array: {tool:?}"+ );}// Specifically: `click` claims input.pointer.click + .left, and// `type_text` claims input.keyboard.type — these are the contracts// Hermes' cua_backend.py is expected to route by.- let click = tools.iter().find(|t| t["name"] == "click")+ let click = tools+ .iter()+ .find(|t| t["name"] == "click").expect("click tool must be registered");- let click_caps: Vec<&str> = click["capabilities"].as_array().unwrap()- .iter().filter_map(|v| v.as_str()).collect();- assert!(click_caps.contains(&"input.pointer.click"),- "click missing input.pointer.click: {click_caps:?}");- assert!(click_caps.contains(&"input.pointer.click.left"),- "click missing input.pointer.click.left: {click_caps:?}");-- let type_text = tools.iter().find(|t| t["name"] == "type_text")+ let click_caps: Vec<&str> = click["capabilities"]+ .as_array()+ .unwrap()+ .iter()+ .filter_map(|v| v.as_str())+ .collect();+ assert!(+ click_caps.contains(&"input.pointer.click"),+ "click missing input.pointer.click: {click_caps:?}"+ );+ assert!(+ click_caps.contains(&"input.pointer.click.left"),+ "click missing input.pointer.click.left: {click_caps:?}"+ );++ let type_text = tools+ .iter()+ .find(|t| t["name"] == "type_text").expect("type_text tool must be registered");- let tt_caps: Vec<&str> = type_text["capabilities"].as_array().unwrap()- .iter().filter_map(|v| v.as_str()).collect();- assert!(tt_caps.contains(&"input.keyboard.type"),- "type_text missing input.keyboard.type: {tt_caps:?}");+ let tt_caps: Vec<&str> = type_text["capabilities"]+ .as_array()+ .unwrap()+ .iter()+ .filter_map(|v| v.as_str())+ .collect();+ assert!(+ tt_caps.contains(&"input.keyboard.type"),+ "type_text missing input.keyboard.type: {tt_caps:?}"+ );// Regression guard for additive-only contract: every pre-existing// top-level field on a tool entry must still be present.for tool in tools {let name = tool["name"].as_str().unwrap_or("<no name>");assert!(tool["name"].is_string(), "{name}: name missing");- assert!(tool["description"].is_string(), "{name}: description missing");- assert!(tool["inputSchema"].is_object(), "{name}: inputSchema missing");- assert!(tool["annotations"].is_object(), "{name}: annotations missing");+ assert!(+ tool["description"].is_string(),+ "{name}: description missing"+ );+ assert!(+ tool["inputSchema"].is_object(),+ "{name}: inputSchema missing"+ );+ assert!(+ tool["annotations"].is_object(),+ "{name}: annotations missing"+ );}}@@ -167,7 +230,9 @@ fn tools_list_includes_capability_and_schema_versions() {//! downstream consumers (Hermes' cua_backend.py, Codex) can gate//! strict-vs-tolerant capability matching by version. Both pinned//! at "1" on first ship.- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();@@ -178,24 +243,34 @@ fn tools_list_includes_capability_and_schema_versions() {// Both version fields default to "1" on first ship — the surface// is brand new, so there's no pre-existing contract to bump.- assert_eq!(result["capability_version"], "1",- "capability_version must default to \"1\" on first ship");- assert_eq!(result["schema_version"], "1",- "schema_version must default to \"1\" on first ship");+ assert_eq!(+ result["capability_version"], "1",+ "capability_version must default to \"1\" on first ship"+ );+ assert_eq!(+ result["schema_version"], "1",+ "schema_version must default to \"1\" on first ship"+ );// Additive guard: tools array must still be there alongside the// new envelope keys — old consumers that only read `tools` keep// working.- assert!(result["tools"].is_array(),- "tools array must still be present alongside version envelope");- assert!(!result["tools"].as_array().unwrap().is_empty(),- "tools array must be non-empty");+ assert!(+ result["tools"].is_array(),+ "tools array must still be present alongside version envelope"+ );+ assert!(+ !result["tools"].as_array().unwrap().is_empty(),+ "tools array must be non-empty"+ );}#[test]#[cfg(any(target_os = "macos", target_os = "windows"))]fn tools_call_unknown_tool() {- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();@@ -217,7 +292,9 @@ fn tools_call_unknown_tool() {fn page_unknown_action_error() {//! Verify the cross-platform `page` tool is registered and rejects an//! unknown action with a meaningful error.- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rsindex abc14b49db..59eab39d6a 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rs@@ -143,7 +143,13 @@ fn tools_list_schema_shape() {"persistent set_config.capture_scope must remain retired");for action in [- "click", "type_text", "press_key", "hotkey", "scroll", "drag", "move_cursor",+ "click",+ "type_text",+ "press_key",+ "hotkey",+ "scroll",+ "drag",+ "move_cursor",] {let scope = &properties(action)["scope"];assert!(diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_session_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_session_test.rsindex 40f88e2be0..c6903d7b9b 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_session_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_session_test.rs@@ -22,7 +22,9 @@ fn concurrent_clients() {//! the multi-cursor use case.let mut drivers: Vec<RawDriver> = Vec::new();for _ in 0..2 {- let Some(d) = RawDriver::spawn() else { return; };+ let Some(d) = RawDriver::spawn() else {+ return;+ };drivers.push(d);}@@ -36,8 +38,10 @@ fn concurrent_clients() {let resp = d.recv();assert_eq!(resp["id"], (i + 1) as i64);- assert!(resp["result"]["protocolVersion"].is_string(),- "Process {i} failed to initialize");+ assert!(+ resp["result"]["protocolVersion"].is_string(),+ "Process {i} failed to initialize"+ );}}@@ -48,7 +52,9 @@ fn concurrent_clients_with_cursor_moves() {//! This covers the multi-cursor use case where two Codex agents run simultaneously.let mut drivers: Vec<RawDriver> = Vec::new();for _ in 0..2 {- let Some(d) = RawDriver::spawn() else { return; };+ let Some(d) = RawDriver::spawn() else {+ return;+ };drivers.push(d);}@@ -67,8 +73,10 @@ fn concurrent_clients_with_cursor_moves() {"params":{"name":"move_cursor","arguments":{"x":px,"y":py}}}));let resp = d.recv();- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false),- "Process {i} move_cursor failed: {resp:?}");+ assert!(+ !resp["result"]["isError"].as_bool().unwrap_or(false),+ "Process {i} move_cursor failed: {resp:?}"+ );}std::thread::sleep(std::time::Duration::from_millis(100));@@ -81,7 +89,10 @@ fn concurrent_clients_with_cursor_moves() {"params":{"name":"get_agent_cursor_state","arguments":{}}}));let resp = d.recv();- assert_eq!(resp["id"], 99, "cua-driver process {i} crashed during concurrent cursor test");+ assert_eq!(+ resp["id"], 99,+ "cua-driver process {i} crashed during concurrent cursor test"+ );}}@@ -91,8 +102,12 @@ fn concurrent_multi_driver_isolation() {//! Two cua-driver processes running simultaneously with different cursor IDs.//! Verifies that concurrent sessions don't interfere — each tracks its own//! cursor state and the overlay stays alive under concurrent load.- let Some(mut child_a) = RawDriver::spawn() else { return; };- let Some(mut child_b) = RawDriver::spawn() else { return; };+ let Some(mut child_a) = RawDriver::spawn() else {+ return;+ };+ let Some(mut child_b) = RawDriver::spawn() else {+ return;+ };// Initialize both.child_a.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));@@ -111,8 +126,14 @@ fn concurrent_multi_driver_isolation() {}));let resp_a = child_a.recv();let resp_b = child_b.recv();- assert!(resp_a["error"].is_null(), "Driver A set_agent_cursor_enabled failed: {resp_a:?}");- assert!(resp_b["error"].is_null(), "Driver B set_agent_cursor_enabled failed: {resp_b:?}");+ assert!(+ resp_a["error"].is_null(),+ "Driver A set_agent_cursor_enabled failed: {resp_a:?}"+ );+ assert!(+ resp_b["error"].is_null(),+ "Driver B set_agent_cursor_enabled failed: {resp_b:?}"+ );// Each driver queries its own cursor state — should reflect what it set.// get_agent_cursor_state is session-scoped, so pass the cursor_id each@@ -127,8 +148,14 @@ fn concurrent_multi_driver_isolation() {}));let state_a = child_a.recv();let state_b = child_b.recv();- assert!(state_a["error"].is_null(), "Driver A get_agent_cursor_state failed: {state_a:?}");- assert!(state_b["error"].is_null(), "Driver B get_agent_cursor_state failed: {state_b:?}");+ assert!(+ state_a["error"].is_null(),+ "Driver A get_agent_cursor_state failed: {state_a:?}"+ );+ assert!(+ state_b["error"].is_null(),+ "Driver B get_agent_cursor_state failed: {state_b:?}"+ );// cursors is an array of { config: { cursor_id, enabled, ... }, x, y }.// Cursor alpha should be enabled (we set true), beta disabled (we set false).@@ -136,15 +163,29 @@ fn concurrent_multi_driver_isolation() {let cursors_a = state_a["result"]["structuredContent"]["cursors"].as_array();let cursors_b = state_b["result"]["structuredContent"]["cursors"].as_array();- let alpha_enabled = cursors_a.and_then(|arr| arr.iter().find(|c| {- c["config"]["cursor_id"].as_str() == Some("alpha")- })).and_then(|c| c["config"]["enabled"].as_bool());- let beta_enabled = cursors_b.and_then(|arr| arr.iter().find(|c| {- c["config"]["cursor_id"].as_str() == Some("beta")- })).and_then(|c| c["config"]["enabled"].as_bool());-- assert_eq!(alpha_enabled, Some(true), "Cursor alpha should be enabled in driver A");- assert_eq!(beta_enabled, Some(false), "Cursor beta should be disabled in driver B");+ let alpha_enabled = cursors_a+ .and_then(|arr| {+ arr.iter()+ .find(|c| c["config"]["cursor_id"].as_str() == Some("alpha"))+ })+ .and_then(|c| c["config"]["enabled"].as_bool());+ let beta_enabled = cursors_b+ .and_then(|arr| {+ arr.iter()+ .find(|c| c["config"]["cursor_id"].as_str() == Some("beta"))+ })+ .and_then(|c| c["config"]["enabled"].as_bool());++ assert_eq!(+ alpha_enabled,+ Some(true),+ "Cursor alpha should be enabled in driver A"+ );+ assert_eq!(+ beta_enabled,+ Some(false),+ "Cursor beta should be disabled in driver B"+ );// macOS additionally exercises move_cursor on both drivers to confirm// neither crashes the other (the Windows variant stops after the state check).@@ -159,8 +200,14 @@ fn concurrent_multi_driver_isolation() {}));let mv_a = child_a.recv();let mv_b = child_b.recv();- assert!(mv_a["error"].is_null(), "Driver A move_cursor failed: {mv_a:?}");- assert!(mv_b["error"].is_null(), "Driver B move_cursor failed: {mv_b:?}");+ assert!(+ mv_a["error"].is_null(),+ "Driver A move_cursor failed: {mv_a:?}"+ );+ assert!(+ mv_b["error"].is_null(),+ "Driver B move_cursor failed: {mv_b:?}"+ );}}@@ -168,7 +215,9 @@ fn concurrent_multi_driver_isolation() {#[cfg(any(target_os = "macos", target_os = "windows"))]fn multi_cursor_instance_state() {//! Two cursor instances can be created with different IDs; each has independent state.- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();@@ -217,18 +266,33 @@ fn multi_cursor_instance_state() {}));let resp1 = d.recv();assert!(!resp1["result"]["isError"].as_bool().unwrap_or(false));- let cursors1 = resp1["result"]["structuredContent"]["cursors"].as_array().cloned().unwrap_or_default();+ let cursors1 = resp1["result"]["structuredContent"]["cursors"]+ .as_array()+ .cloned()+ .unwrap_or_default();if cfg!(target_os = "windows") {// Windows returns the full cursor list; find agent1 within it.- let a1 = cursors1.iter()+ let a1 = cursors1+ .iter().find(|c| c["config"]["cursor_id"].as_str() == Some("agent1")).expect("agent1 in returned cursor list");- assert_eq!(a1["config"]["enabled"].as_bool(), Some(true), "agent1 was never disabled");+ assert_eq!(+ a1["config"]["enabled"].as_bool(),+ Some(true),+ "agent1 was never disabled"+ );} else {- assert_eq!(cursors1.len(), 1, "agent1 query must return exactly its own cursor, got: {cursors1:?}");+ assert_eq!(+ cursors1.len(),+ 1,+ "agent1 query must return exactly its own cursor, got: {cursors1:?}"+ );assert_eq!(cursors1[0]["config"]["cursor_id"].as_str(), Some("agent1"));- assert_eq!(resp1["result"]["structuredContent"]["enabled"].as_bool(), Some(true),- "agent1 was never disabled");+ assert_eq!(+ resp1["result"]["structuredContent"]["enabled"].as_bool(),+ Some(true),+ "agent1 was never disabled"+ );}d.send(&serde_json::json!({@@ -237,18 +301,33 @@ fn multi_cursor_instance_state() {}));let resp2 = d.recv();assert!(!resp2["result"]["isError"].as_bool().unwrap_or(false));- let cursors2 = resp2["result"]["structuredContent"]["cursors"].as_array().cloned().unwrap_or_default();+ let cursors2 = resp2["result"]["structuredContent"]["cursors"]+ .as_array()+ .cloned()+ .unwrap_or_default();if cfg!(target_os = "windows") {// Windows returns the full cursor list; find agent2 within it.- let a2 = cursors2.iter()+ let a2 = cursors2+ .iter().find(|c| c["config"]["cursor_id"].as_str() == Some("agent2")).expect("agent2 in returned cursor list");- assert_eq!(a2["config"]["enabled"].as_bool(), Some(false), "agent2 was hidden");+ assert_eq!(+ a2["config"]["enabled"].as_bool(),+ Some(false),+ "agent2 was hidden"+ );} else {- assert_eq!(cursors2.len(), 1, "agent2 query must return exactly its own cursor, got: {cursors2:?}");+ assert_eq!(+ cursors2.len(),+ 1,+ "agent2 query must return exactly its own cursor, got: {cursors2:?}"+ );assert_eq!(cursors2[0]["config"]["cursor_id"].as_str(), Some("agent2"));- assert_eq!(resp2["result"]["structuredContent"]["enabled"].as_bool(), Some(false),- "agent2 was hidden");+ assert_eq!(+ resp2["result"]["structuredContent"]["enabled"].as_bool(),+ Some(false),+ "agent2 was hidden"+ );}std::thread::sleep(std::time::Duration::from_millis(50));@@ -259,7 +338,10 @@ fn multi_cursor_instance_state() {"params":{"name":"get_agent_cursor_state","arguments":{"cursor_id":"agent1"}}}));let resp = d.recv();- assert_eq!(resp["id"], 99, "cua-driver crashed during multi-cursor test");+ assert_eq!(+ resp["id"], 99,+ "cua-driver crashed during multi-cursor test"+ );}#[test]@@ -270,13 +352,19 @@ fn overlay_move_cursor_stays_alive() {//! sends commands via the global channel. Any crash in the render thread (e.g. wrong//! GCD queue pointer, bad CGImage argument types) would cause this test to fail with//! an early EOF or a non-zero exit code.- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();// Call move_cursor several times to drive the overlay render loop.- for (id, (x, y)) in [(2u64, (100.0_f64, 200.0_f64)), (3, (400.0, 300.0)), (4, (800.0, 600.0))] {+ for (id, (x, y)) in [+ (2u64, (100.0_f64, 200.0_f64)),+ (3, (400.0, 300.0)),+ (4, (800.0, 600.0)),+ ] {d.send(&serde_json::json!({"jsonrpc": "2.0","id": id,@@ -313,7 +401,10 @@ fn overlay_move_cursor_stays_alive() {"params": { "name": "get_agent_cursor_state", "arguments": {} }}));let resp = d.recv();- assert_eq!(resp["id"], 99, "cua-driver crashed during overlay move_cursor test");+ assert_eq!(+ resp["id"], 99,+ "cua-driver crashed during overlay move_cursor test"+ );}#[test]@@ -321,7 +412,9 @@ fn overlay_move_cursor_stays_alive() {fn set_agent_cursor_motion_bezier_knobs() {//! set_agent_cursor_motion with Bezier/timing knobs — verifies schema accepts them//! and returns a non-error response with the updated values in the response text.- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();@@ -339,11 +432,18 @@ fn set_agent_cursor_motion_bezier_knobs() {}}}));let resp = d.recv();- assert!(resp["error"].is_null(), "Protocol error from set_agent_cursor_motion: {resp:?}");- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false),- "set_agent_cursor_motion returned isError: {resp:?}");+ assert!(+ resp["error"].is_null(),+ "Protocol error from set_agent_cursor_motion: {resp:?}"+ );+ assert!(+ !resp["result"]["isError"].as_bool().unwrap_or(false),+ "set_agent_cursor_motion returned isError: {resp:?}"+ );// Response text should mention the new glide duration.let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");- assert!(text.contains("500") || text.contains("motion"),- "Expected motion summary in response, got: {text}");+ assert!(+ text.contains("500") || text.contains("motion"),+ "Expected motion summary in response, got: {text}"+ );}diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_tools_call_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_tools_call_test.rsindex 1bba2c470f..1e7ae9a33b 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_tools_call_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_tools_call_test.rs@@ -16,7 +16,9 @@ use cua_driver_testkit::RawDriver;#[test]#[cfg(any(target_os = "macos", target_os = "windows"))]fn tools_call_list_apps() {- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };// Initialize.d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));@@ -34,23 +36,36 @@ fn tools_call_list_apps() {assert!(resp["result"]["content"].is_array());if cfg!(target_os = "windows") {let text = resp["result"]["content"][0]["text"].as_str().unwrap();- assert!(text.contains("Found"), "Expected process list text, got: {}", text);+ assert!(+ text.contains("Found"),+ "Expected process list text, got: {}",+ text+ );// Windows backend returns "processes" key.- assert!(resp["result"]["structuredContent"]["processes"].is_array(),- "Expected processes array: {:?}", resp["result"]["structuredContent"]);+ assert!(+ resp["result"]["structuredContent"]["processes"].is_array(),+ "Expected processes array: {:?}",+ resp["result"]["structuredContent"]+ );} else {let content = &resp["result"]["content"][0];assert_eq!(content["type"], "text");let text = content["text"].as_str().unwrap();// Should contain some running apps.- assert!(text.contains("Found"), "Expected app list text, got: {}", text);+ assert!(+ text.contains("Found"),+ "Expected app list text, got: {}",+ text+ );}}#[test]#[cfg(any(target_os = "macos", target_os = "windows"))]fn get_config_and_check_permissions() {- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();@@ -76,9 +91,18 @@ fn get_config_and_check_permissions() {if cfg!(target_os = "windows") {let sc = &resp["result"]["structuredContent"];// Windows returns elevated, uia, post_message booleans.- assert!(sc["uia"].as_bool().unwrap_or(false), "uia should be true: {sc:?}");- assert!(sc["post_message"].as_bool().unwrap_or(false), "post_message should be true: {sc:?}");- assert!(sc["elevated"].is_boolean(), "elevated should be a boolean: {sc:?}");+ assert!(+ sc["uia"].as_bool().unwrap_or(false),+ "uia should be true: {sc:?}"+ );+ assert!(+ sc["post_message"].as_bool().unwrap_or(false),+ "post_message should be true: {sc:?}"+ );+ assert!(+ sc["elevated"].is_boolean(),+ "elevated should be a boolean: {sc:?}"+ );} else {// Returns structured content with accessibility and screen_recording booleans.assert!(resp["result"]["structuredContent"]["accessibility"].is_boolean());@@ -93,7 +117,10 @@ fn get_config_and_check_permissions() {"params":{"name":"set_config","arguments":{"max_image_dimension": 1920}}}));let resp = d.recv();- assert!(resp["error"].is_null(), "Protocol error from set_config: {resp:?}");+ assert!(+ resp["error"].is_null(),+ "Protocol error from set_config: {resp:?}"+ );if !cfg!(target_os = "windows") {let content = resp["result"]["content"].as_array().expect("content array");assert!(!content.is_empty(), "set_config returned empty content");@@ -105,15 +132,19 @@ fn get_config_and_check_permissions() {"params":{"name":"get_config","arguments":{}}}));let resp = d.recv();- assert_eq!(resp["result"]["structuredContent"]["max_image_dimension"], 1920,- "get_config should reflect max_image_dimension change");+ assert_eq!(+ resp["result"]["structuredContent"]["max_image_dimension"], 1920,+ "get_config should reflect max_image_dimension change"+ );}#[test]#[cfg(any(target_os = "macos", target_os = "windows"))]fn get_accessibility_tree() {//! get_accessibility_tree returns a lightweight process+window snapshot.- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();@@ -124,18 +155,26 @@ fn get_accessibility_tree() {}));let resp = d.recv();assert!(resp["error"].is_null(), "Protocol error: {resp:?}");- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false),- "get_accessibility_tree returned error: {resp:?}");+ assert!(+ !resp["result"]["isError"].as_bool().unwrap_or(false),+ "get_accessibility_tree returned error: {resp:?}"+ );let sc = &resp["result"]["structuredContent"];if cfg!(target_os = "windows") {// Windows backend returns both "processes" and "windows" keys.- assert!(sc["processes"].is_array(), "Expected processes array: {sc:?}");+ assert!(+ sc["processes"].is_array(),+ "Expected processes array: {sc:?}"+ );assert!(sc["windows"].is_array(), "Expected windows array: {sc:?}");} else {// macOS backend returns "apps"; Linux returns "processes". Either key is valid.let has_apps = sc["apps"].is_array() || sc["processes"].is_array();- assert!(has_apps, "Expected apps or processes array in structured content, got: {sc:?}");+ assert!(+ has_apps,+ "Expected apps or processes array in structured content, got: {sc:?}"+ );}let content = resp["result"]["content"].as_array().expect("content array");@@ -146,7 +185,9 @@ fn get_accessibility_tree() {#[cfg(any(target_os = "macos", target_os = "windows"))]fn list_windows_structured_content() {//! Verify list_windows returns structuredContent.windows array with expected fields.- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();@@ -157,16 +198,24 @@ fn list_windows_structured_content() {}));let resp = d.recv();assert!(resp["error"].is_null(), "Protocol error: {resp:?}");- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false),- "list_windows returned error: {resp:?}");+ assert!(+ !resp["result"]["isError"].as_bool().unwrap_or(false),+ "list_windows returned error: {resp:?}"+ );let sc = &resp["result"]["structuredContent"];- assert!(sc["windows"].is_array(), "Expected windows array in structuredContent: {sc:?}");+ assert!(+ sc["windows"].is_array(),+ "Expected windows array in structuredContent: {sc:?}"+ );// If there are any windows, verify the expected fields are present.if let Some(wins) = sc["windows"].as_array() {if let Some(w) = wins.first() {- assert!(w["window_id"].is_number(), "window_id missing from window: {w:?}");+ assert!(+ w["window_id"].is_number(),+ "window_id missing from window: {w:?}"+ );assert!(w["pid"].is_number(), "pid missing from window: {w:?}");}}@@ -175,7 +224,9 @@ fn list_windows_structured_content() {#[test]#[cfg(any(target_os = "macos", target_os = "windows"))]fn get_screen_size_and_cursor_position() {- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();@@ -186,10 +237,19 @@ fn get_screen_size_and_cursor_position() {"params":{"name":"get_screen_size","arguments":{}}}));let resp = d.recv();- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false), "get_screen_size failed: {resp:?}");+ assert!(+ !resp["result"]["isError"].as_bool().unwrap_or(false),+ "get_screen_size failed: {resp:?}"+ );let sc = &resp["result"]["structuredContent"];- assert!(sc["width"].as_f64().unwrap_or(0.0) > 0.0, "width should be positive");- assert!(sc["height"].as_f64().unwrap_or(0.0) > 0.0, "height should be positive");+ assert!(+ sc["width"].as_f64().unwrap_or(0.0) > 0.0,+ "width should be positive"+ );+ assert!(+ sc["height"].as_f64().unwrap_or(0.0) > 0.0,+ "height should be positive"+ );// get_cursor_positiond.send(&serde_json::json!({@@ -197,10 +257,19 @@ fn get_screen_size_and_cursor_position() {"params":{"name":"get_cursor_position","arguments":{}}}));let resp = d.recv();- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false), "get_cursor_position failed: {resp:?}");+ assert!(+ !resp["result"]["isError"].as_bool().unwrap_or(false),+ "get_cursor_position failed: {resp:?}"+ );// x and y may be 0,0 or any value — just verify the keys exist and are numbers.- assert!(resp["result"]["structuredContent"]["x"].is_number(), "x should be a number");- assert!(resp["result"]["structuredContent"]["y"].is_number(), "y should be a number");+ assert!(+ resp["result"]["structuredContent"]["x"].is_number(),+ "x should be a number"+ );+ assert!(+ resp["result"]["structuredContent"]["y"].is_number(),+ "y should be a number"+ );}#[test]@@ -209,7 +278,9 @@ fn get_window_state_returns_both_with_opt_out() {//! Perception is mode-agnostic: get_window_state returns BOTH the tree AND a//! screenshot by default (the deprecated `capture_mode` arg is ignored), and//! `include_screenshot:false` is the opt-out that returns the tree only.- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();@@ -220,9 +291,10 @@ fn get_window_state_returns_both_with_opt_out() {}));let resp = d.recv();let windows = resp["result"]["structuredContent"]["windows"].as_array();- let first_win = windows.and_then(|a| a.iter().find(|w| {- w["pid"].as_i64().is_some() && w["window_id"].as_u64().is_some()- }));+ let first_win = windows.and_then(|a| {+ a.iter()+ .find(|w| w["pid"].as_i64().is_some() && w["window_id"].as_u64().is_some())+ });let Some(win) = first_win else {eprintln!("No windows found — skipping get_window_state perception test");@@ -239,21 +311,40 @@ fn get_window_state_returns_both_with_opt_out() {}}}));let resp = d.recv();- assert!(resp["error"].is_null(), "Protocol error from get_window_state: {resp:?}");+ assert!(+ resp["error"].is_null(),+ "Protocol error from get_window_state: {resp:?}"+ );let content = resp["result"]["content"].as_array().expect("content array");assert!(!content.is_empty(), "Expected at least one content item");let sc = &resp["result"]["structuredContent"];- assert_eq!(sc["window_id"].as_u64().unwrap_or(0), wid, "structuredContent.window_id mismatch");- assert_eq!(sc["pid"].as_i64().unwrap_or(0), pid, "structuredContent.pid mismatch");- assert!(sc["element_count"].is_number(), "expected element_count in structuredContent: {sc:?}");+ assert_eq!(+ sc["window_id"].as_u64().unwrap_or(0),+ wid,+ "structuredContent.window_id mismatch"+ );+ assert_eq!(+ sc["pid"].as_i64().unwrap_or(0),+ pid,+ "structuredContent.pid mismatch"+ );+ assert!(+ sc["element_count"].is_number(),+ "expected element_count in structuredContent: {sc:?}"+ );// The screenshot is delivered by default (skip the strict image assertion on// Windows, whose capture can vary, and when screen-recording isn't granted).if !cfg!(target_os = "windows") && !sc["screenshot_width"].is_null() {let has_image = content.iter().any(|c| c["type"] == "image");- assert!(has_image, "default get_window_state should deliver a screenshot image: {content:?}");- assert!(sc["screenshot_width"].as_f64().unwrap_or(0.0) > 0.0,- "default mode should report screenshot_width: {sc:?}");+ assert!(+ has_image,+ "default get_window_state should deliver a screenshot image: {content:?}"+ );+ assert!(+ sc["screenshot_width"].as_f64().unwrap_or(0.0) > 0.0,+ "default mode should report screenshot_width: {sc:?}"+ );}// OPT-OUT: include_screenshot:false → tree only, NO image / no screenshot_width.@@ -264,12 +355,22 @@ fn get_window_state_returns_both_with_opt_out() {}}}));let tree_only = d.recv();- assert!(tree_only["error"].is_null(), "Protocol error from tree-only get_window_state: {tree_only:?}");- let to_content = tree_only["result"]["content"].as_array().expect("content array");+ assert!(+ tree_only["error"].is_null(),+ "Protocol error from tree-only get_window_state: {tree_only:?}"+ );+ let to_content = tree_only["result"]["content"]+ .as_array()+ .expect("content array");let to_has_image = to_content.iter().any(|c| c["type"] == "image");- assert!(!to_has_image, "include_screenshot:false must NOT return an image, got: {to_content:?}");- assert!(tree_only["result"]["structuredContent"]["screenshot_width"].is_null(),- "include_screenshot:false must not report screenshot_width: {tree_only:?}");+ assert!(+ !to_has_image,+ "include_screenshot:false must NOT return an image, got: {to_content:?}"+ );+ assert!(+ tree_only["result"]["structuredContent"]["screenshot_width"].is_null(),+ "include_screenshot:false must not report screenshot_width: {tree_only:?}"+ );// DEPRECATED `capture_mode:"vision"` must be IGNORED — still returns the tree.d.send(&serde_json::json!({@@ -279,9 +380,14 @@ fn get_window_state_returns_both_with_opt_out() {}}}));let dep = d.recv();- assert!(dep["error"].is_null(), "Protocol error: deprecated capture_mode must be accepted, not rejected: {dep:?}");- assert!(dep["result"]["structuredContent"]["element_count"].is_number(),- "capture_mode=vision is ignored — the tree must still be present: {dep:?}");+ assert!(+ dep["error"].is_null(),+ "Protocol error: deprecated capture_mode must be accepted, not rejected: {dep:?}"+ );+ assert!(+ dep["result"]["structuredContent"]["element_count"].is_number(),+ "capture_mode=vision is ignored — the tree must still be present: {dep:?}"+ );}#[test]@@ -289,7 +395,9 @@ fn get_window_state_returns_both_with_opt_out() {fn scroll_tool() {//! scroll with direction=down, by=line, amount=1 against the first available window.//! Verifies the tool is accepted and returns content, not a protocol error.- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();@@ -323,7 +431,10 @@ fn scroll_tool() {"params":{"name":"scroll","arguments":{"pid": pid, "direction": "down", "amount": 1}}}));let resp = d.recv();- assert!(resp["error"].is_null(), "Protocol error from scroll: {resp:?}");+ assert!(+ resp["error"].is_null(),+ "Protocol error from scroll: {resp:?}"+ );let content = resp["result"]["content"].as_array().expect("content array");assert!(!content.is_empty(), "scroll returned empty content");}@@ -333,7 +444,9 @@ fn scroll_tool() {fn type_text_tool() {//! Opens TextEdit (or reuses it if already running) and types a short string via type_text.//! Skips gracefully if TextEdit is not available or has no window.- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();@@ -355,7 +468,10 @@ fn type_text_tool() {let apps = resp["result"]["structuredContent"]["apps"].as_array();let Some(app) = apps.and_then(|a| {a.iter().find(|a| {- a["name"].as_str().map(|n| n.eq_ignore_ascii_case("textedit")).unwrap_or(false)+ a["name"]+ .as_str()+ .map(|n| n.eq_ignore_ascii_case("textedit"))+ .unwrap_or(false)})}) else {eprintln!("TextEdit not found — skipping type_text test");@@ -382,7 +498,10 @@ fn type_text_tool() {"params":{"name":"type_text","arguments":{"pid": pid, "window_id": wid, "text": "cua-test"}}}));let resp = d.recv();- assert!(resp["error"].is_null(), "Protocol error from type_text: {resp:?}");+ assert!(+ resp["error"].is_null(),+ "Protocol error from type_text: {resp:?}"+ );let content = resp["result"]["content"].as_array().expect("content array");assert!(!content.is_empty(), "type_text returned empty content");}@@ -391,7 +510,9 @@ fn type_text_tool() {#[cfg(target_os = "windows")]fn type_text_notepad() {//! Launch Notepad, type a short string via type_text. Skips if Notepad unavailable.- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();@@ -413,7 +534,10 @@ fn type_text_notepad() {let procs = resp["result"]["structuredContent"]["processes"].as_array();let Some(proc_) = procs.and_then(|a| {a.iter().find(|p| {- p["name"].as_str().map(|n| n.to_lowercase().contains("notepad")).unwrap_or(false)+ p["name"]+ .as_str()+ .map(|n| n.to_lowercase().contains("notepad"))+ .unwrap_or(false)})}) else {eprintln!("Notepad not found — skipping type_text test");@@ -439,8 +563,14 @@ fn type_text_notepad() {"params":{"name":"type_text","arguments":{"pid":pid,"window_id":wid,"text":"cua-test"}}}));let resp = d.recv();- assert!(resp["error"].is_null(), "Protocol error from type_text: {resp:?}");- assert!(!resp["result"]["content"].as_array().map(|a| a.is_empty()).unwrap_or(true));+ assert!(+ resp["error"].is_null(),+ "Protocol error from type_text: {resp:?}"+ );+ assert!(!resp["result"]["content"]+ .as_array()+ .map(|a| a.is_empty())+ .unwrap_or(true));}#[test]@@ -449,7 +579,9 @@ fn type_text_chars_tool() {//! Verify type_text_chars with delay_ms is accepted without error (dry-run via TextEdit or//! a pid that accepts WM_CHAR). We just verify the tool responds with a non-error.//! Skips gracefully if no visible TextEdit window.- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();@@ -462,7 +594,8 @@ fn type_text_chars_tool() {let resp = d.recv();let apps = resp["result"]["structuredContent"]["apps"].as_array();let textedit_pid = apps.and_then(|arr| {- arr.iter().find(|a| a["name"].as_str().unwrap_or("").contains("TextEdit"))+ arr.iter()+ .find(|a| a["name"].as_str().unwrap_or("").contains("TextEdit")).and_then(|a| a["pid"].as_i64())});@@ -479,8 +612,10 @@ fn type_text_chars_tool() {}}}));let resp = d.recv();- assert!(!resp["result"]["isError"].as_bool().unwrap_or(false),- "type_text_chars returned error: {resp:?}");+ assert!(+ !resp["result"]["isError"].as_bool().unwrap_or(false),+ "type_text_chars returned error: {resp:?}"+ );let msg = resp["result"]["content"][0]["text"].as_str().unwrap_or("");// type_text reports "Inserted" when an AX read-back verified the text, and// "Sent (unverified)" when it dispatched but couldn't confirm (e.g. the field@@ -496,7 +631,9 @@ fn type_text_chars_tool() {#[cfg(any(target_os = "macos", target_os = "windows"))]fn hotkey_keys_array() {//! Verify hotkey accepts a keys array without a protocol error.- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();@@ -531,7 +668,10 @@ fn hotkey_keys_array() {}}}));let resp = d.recv();- assert!(resp["error"].is_null(), "Protocol error from hotkey: {resp:?}");+ assert!(+ resp["error"].is_null(),+ "Protocol error from hotkey: {resp:?}"+ );let content = resp["result"]["content"].as_array().expect("content array");assert!(!content.is_empty(), "hotkey should return content");}@@ -541,7 +681,9 @@ fn hotkey_keys_array() {fn press_key_harmless() {//! press_key with a harmless key (F24 — virtually no app responds to it) sent to the//! first available window. Just verifies the tool doesn't return a protocol error.- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();@@ -566,7 +708,10 @@ fn press_key_harmless() {"params":{"name":"press_key","arguments":{"pid": pid, "window_id": wid, "key": "F24"}}}));let resp = d.recv();- assert!(resp["error"].is_null(), "Protocol error from press_key: {resp:?}");+ assert!(+ resp["error"].is_null(),+ "Protocol error from press_key: {resp:?}"+ );// Tool may succeed or return an app error, but must NOT be a protocol-level error.let content = resp["result"]["content"].as_array().expect("content array");assert!(!content.is_empty(), "press_key returned empty content");@@ -577,7 +722,9 @@ fn press_key_harmless() {fn click_pixel_path() {//! click at window-local (5, 5) — title bar area, safe to click without disrupting UI.//! Verifies the pixel-coordinate path for click works without a protocol error.- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();@@ -602,7 +749,10 @@ fn click_pixel_path() {"params":{"name":"click","arguments":{"pid": pid, "window_id": wid, "x": 5.0, "y": 5.0}}}));let resp = d.recv();- assert!(resp["error"].is_null(), "Protocol error from click: {resp:?}");+ assert!(+ resp["error"].is_null(),+ "Protocol error from click: {resp:?}"+ );let content = resp["result"]["content"].as_array().expect("content array");assert!(!content.is_empty(), "click returned empty content");}@@ -610,7 +760,9 @@ fn click_pixel_path() {#[test]#[cfg(target_os = "windows")]fn double_click_and_right_click() {- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();@@ -633,23 +785,37 @@ fn double_click_and_right_click() {"params":{"name":"double_click","arguments":{"pid":pid,"window_id":wid,"x":5.0,"y":5.0}}}));let resp = d.recv();- assert!(resp["error"].is_null(), "Protocol error from double_click: {resp:?}");- assert!(!resp["result"]["content"].as_array().map(|a| a.is_empty()).unwrap_or(true));+ assert!(+ resp["error"].is_null(),+ "Protocol error from double_click: {resp:?}"+ );+ assert!(!resp["result"]["content"]+ .as_array()+ .map(|a| a.is_empty())+ .unwrap_or(true));d.send(&serde_json::json!({"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"right_click","arguments":{"pid":pid,"window_id":wid,"x":5.0,"y":5.0}}}));let resp = d.recv();- assert!(resp["error"].is_null(), "Protocol error from right_click: {resp:?}");- assert!(!resp["result"]["content"].as_array().map(|a| a.is_empty()).unwrap_or(true));+ assert!(+ resp["error"].is_null(),+ "Protocol error from right_click: {resp:?}"+ );+ assert!(!resp["result"]["content"]+ .as_array()+ .map(|a| a.is_empty())+ .unwrap_or(true));}#[test]#[cfg(target_os = "macos")]fn double_click_and_right_click_pixel_path() {//! double_click and right_click at title-bar coords — verifies both tools accept pixel path.- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();@@ -673,9 +839,17 @@ fn double_click_and_right_click_pixel_path() {"params":{"name":"double_click","arguments":{"pid": pid, "window_id": wid, "x": 5.0, "y": 5.0}}}));let resp = d.recv();- assert!(resp["error"].is_null(), "Protocol error from double_click: {resp:?}");- assert!(!resp["result"]["content"].as_array().map(|a| a.is_empty()).unwrap_or(true),- "double_click returned empty content");+ assert!(+ resp["error"].is_null(),+ "Protocol error from double_click: {resp:?}"+ );+ assert!(+ !resp["result"]["content"]+ .as_array()+ .map(|a| a.is_empty())+ .unwrap_or(true),+ "double_click returned empty content"+ );// right_click at same coords.d.send(&serde_json::json!({@@ -683,9 +857,17 @@ fn double_click_and_right_click_pixel_path() {"params":{"name":"right_click","arguments":{"pid": pid, "window_id": wid, "x": 5.0, "y": 5.0}}}));let resp = d.recv();- assert!(resp["error"].is_null(), "Protocol error from right_click: {resp:?}");- assert!(!resp["result"]["content"].as_array().map(|a| a.is_empty()).unwrap_or(true),- "right_click returned empty content");+ assert!(+ resp["error"].is_null(),+ "Protocol error from right_click: {resp:?}"+ );+ assert!(+ !resp["result"]["content"]+ .as_array()+ .map(|a| a.is_empty())+ .unwrap_or(true),+ "right_click returned empty content"+ );}#[test]@@ -693,7 +875,9 @@ fn double_click_and_right_click_pixel_path() {fn set_value_via_element_index() {//! get_window_state on TextEdit → find a text-area element → set_value on it.//! Skips gracefully if TextEdit is not available.- let Some(mut d) = RawDriver::spawn() else { return; };+ let Some(mut d) = RawDriver::spawn() else {+ return;+ };d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));d.recv();@@ -714,8 +898,12 @@ fn set_value_via_element_index() {let resp = d.recv();let apps = resp["result"]["structuredContent"]["apps"].as_array();let Some(app) = apps.and_then(|a| {- a.iter().find(|a| a["name"].as_str()- .map(|n| n.eq_ignore_ascii_case("textedit")).unwrap_or(false))+ a.iter().find(|a| {+ a["name"]+ .as_str()+ .map(|n| n.eq_ignore_ascii_case("textedit"))+ .unwrap_or(false)+ })}) else {eprintln!("TextEdit not found — skipping set_value test");return;@@ -741,8 +929,13 @@ fn set_value_via_element_index() {"params":{"name":"get_window_state","arguments":{"pid": pid, "window_id": wid, "capture_mode": "ax"}}}));let resp = d.recv();- assert!(resp["error"].is_null(), "Protocol error from get_window_state: {resp:?}");- let element_count = resp["result"]["structuredContent"]["element_count"].as_u64().unwrap_or(0);+ assert!(+ resp["error"].is_null(),+ "Protocol error from get_window_state: {resp:?}"+ );+ let element_count = resp["result"]["structuredContent"]["element_count"]+ .as_u64()+ .unwrap_or(0);if element_count == 0 {eprintln!("No AX elements — skipping set_value test");return;@@ -755,7 +948,10 @@ fn set_value_via_element_index() {}));let resp = d.recv();// set_value may fail if element 0 is not settable; accept tool-level errors but not protocol errors.- assert!(resp["error"].is_null(), "Protocol error from set_value: {resp:?}");+ assert!(+ resp["error"].is_null(),+ "Protocol error from set_value: {resp:?}"+ );let content = resp["result"]["content"].as_array().expect("content array");assert!(!content.is_empty(), "set_value returned empty content");}diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/session_capture_scope_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/session_capture_scope_test.rsindex 1feff78cff..b4fbdeb699 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/session_capture_scope_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/session_capture_scope_test.rs@@ -37,8 +37,7 @@ fn policies_are_isolated_immutable_and_enforced_over_mcp() {json!({"session": session, "capture_scope": scope}),);assert_eq!(- response["result"]["structuredContent"]["capture_scope"],- scope,+ response["result"]["structuredContent"]["capture_scope"], scope,"start_session failed: {response}");}diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/transport_config_persistence_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/transport_config_persistence_test.rsindex dba07dfd53..925c7ccc52 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/transport_config_persistence_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/transport_config_persistence_test.rs@@ -44,7 +44,10 @@ fn cli_set_config_persists_to_disk_across_invocations() {// Save the current value so we can restore it.let original = config_max_dim(cli.call("get_config", serde_json::json!({})).structured());- let set = cli.call("set_config", serde_json::json!({ "key": KEY, "value": PROBE }));+ let set = cli.call(+ "set_config",+ serde_json::json!({ "key": KEY, "value": PROBE }),+ );assert!(!set.is_error(), "CLI set_config errored: {}", set.text());// A fresh process must see the persisted value.@@ -58,7 +61,10 @@ fn cli_set_config_persists_to_disk_across_invocations() {// Restore.if let Some(orig) = original {- let _ = cli.call("set_config", serde_json::json!({ "key": KEY, "value": orig }));+ let _ = cli.call(+ "set_config",+ serde_json::json!({ "key": KEY, "value": orig }),+ );}}@@ -67,11 +73,20 @@ fn cli_set_config_persists_to_disk_across_invocations() {#[test]#[ignore]fn mcp_set_config_visible_within_session() {- let Some(mut driver) = McpDriver::spawn() else { return };+ let Some(mut driver) = McpDriver::spawn() else {+ return;+ };- let original = config_max_dim(driver.call("get_config", serde_json::json!({})).structured());+ let original = config_max_dim(+ driver+ .call("get_config", serde_json::json!({}))+ .structured(),+ );- let set = driver.call("set_config", serde_json::json!({ "key": KEY, "value": PROBE }));+ let set = driver.call(+ "set_config",+ serde_json::json!({ "key": KEY, "value": PROBE }),+ );assert!(!set.is_error(), "MCP set_config errored: {}", set.text());let after = driver.call("get_config", serde_json::json!({}));@@ -83,6 +98,9 @@ fn mcp_set_config_visible_within_session() {);if let Some(orig) = original {- let _ = driver.call("set_config", serde_json::json!({ "key": KEY, "value": orig }));+ let _ = driver.call(+ "set_config",+ serde_json::json!({ "key": KEY, "value": orig }),+ );}}diff --git a/libs/cua-driver/rust/crates/cursor-overlay/src/bezier.rs b/libs/cua-driver/rust/crates/cursor-overlay/src/bezier.rsindex af1a09a69d..e674586cbf 100644--- a/libs/cua-driver/rust/crates/cursor-overlay/src/bezier.rs+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/bezier.rs@@ -11,7 +11,9 @@ pub struct Point {impl Point {pub const ZERO: Self = Self { x: 0.0, y: 0.0 };- pub fn new(x: f64, y: f64) -> Self { Self { x, y } }+ pub fn new(x: f64, y: f64) -> Self {+ Self { x, y }+ }pub fn hypot(self, other: Self) -> f64 {let dx = self.x - other.x;let dy = self.y - other.y;@@ -32,7 +34,13 @@ pub struct CubicBezier {impl CubicBezier {pub fn new(start: Point, control1: Point, control2: Point, end: Point) -> Self {- let mut s = Self { start, control1, control2, end, length: 0.0 };+ let mut s = Self {+ start,+ control1,+ control2,+ end,+ length: 0.0,+ };s.length = s.measure_length();s}@@ -45,12 +53,12 @@ impl CubicBezier {let (tt, ttt) = (t * t, t * t * t);Point {x: uuu * self.start.x- + 3.0 * uu * t * self.control1.x- + 3.0 * u * tt * self.control2.x+ + 3.0 * uu * t * self.control1.x+ + 3.0 * u * tt * self.control2.x+ ttt * self.end.x,y: uuu * self.start.y- + 3.0 * uu * t * self.control1.y- + 3.0 * u * tt * self.control2.y+ + 3.0 * uu * t * self.control1.y+ + 3.0 * u * tt * self.control2.y+ ttt * self.end.y,}}@@ -116,19 +124,25 @@ pub fn build_motion_bezier(// Unit perpendicular (90° CCW of direction vector).let perp_x = -dy / length;- let perp_y = dx / length;+ let perp_y = dx / length;let deflection = length * arc_size;- let flow_bias = (arc_flow + 1.0) / 2.0; // map [-1,1] → [0,1]+ let flow_bias = (arc_flow + 1.0) / 2.0; // map [-1,1] → [0,1]let c1_deflect = deflection * (1.0 - 0.5 * flow_bias);let c2_deflect = deflection * (1.0 - 0.5 * (1.0 - flow_bias));let c1_base = Point::new(start.x + dx * start_handle, start.y + dy * start_handle);- let c2_base = Point::new(end.x - dx * end_handle, end.y - dy * end_handle);-- let control1 = Point::new(c1_base.x + perp_x * c1_deflect, c1_base.y + perp_y * c1_deflect);- let control2 = Point::new(c2_base.x + perp_x * c2_deflect, c2_base.y + perp_y * c2_deflect);+ let c2_base = Point::new(end.x - dx * end_handle, end.y - dy * end_handle);++ let control1 = Point::new(+ c1_base.x + perp_x * c1_deflect,+ c1_base.y + perp_y * c1_deflect,+ );+ let control2 = Point::new(+ c2_base.x + perp_x * c2_deflect,+ c2_base.y + perp_y * c2_deflect,+ );CubicBezier::new(start, control1, control2, end)}diff --git a/libs/cua-driver/rust/crates/cursor-overlay/src/capture_utils.rs b/libs/cua-driver/rust/crates/cursor-overlay/src/capture_utils.rsindex 174a0a0e73..931227bf3c 100644--- a/libs/cua-driver/rust/crates/cursor-overlay/src/capture_utils.rs+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/capture_utils.rs@@ -3,7 +3,7 @@//! All three platform crates depend on cursor-overlay, so this is the natural//! home for a pure-Rust crop + JPEG-encode helper.-use image::{DynamicImage, GenericImageView, imageops::FilterType};+use image::{imageops::FilterType, DynamicImage, GenericImageView};/// Result of a crop-and-encode operation; carries coordinate metadata so callers/// can translate zoom-image pixel coordinates back to full-window pixel coordinates.diff --git a/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rs b/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rsindex 530def570c..2997e96e26 100644--- a/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rs+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rs@@ -8,22 +8,24 @@//! - `CursorShape` — loaded and rasterised custom SVG / ICO / PNG asset//! - `OverlayCommand` — messages sent from MCP tools to the overlay thread-pub mod palette;-pub mod motion;pub mod bezier;+pub mod capture_utils;+pub mod motion;+pub mod palette;pub mod path_planner;+pub mod render_state;pub mod shape;-pub mod capture_utils;pub mod util;-pub mod render_state;pub mod z_order;-pub use palette::Palette;-pub use motion::{MotionConfig, Spring};pub use bezier::CubicBezier;-pub use path_planner::{PathPlanner, PlannedPath, PathState};+pub use motion::{MotionConfig, Spring};+pub use palette::Palette;+pub use path_planner::{PathPlanner, PathState, PlannedPath};+pub use render_state::{+ draw_default_arrow, paint_cursor, render_frame, FocusRect, RenderStateCore,+};pub use shape::{resolve_cursor_icon, BuiltinShape, CursorIconResolution, CursorShape};-pub use render_state::{RenderStateCore, FocusRect, render_frame, paint_cursor, draw_default_arrow};pub use z_order::ZOrderEnforcer;/// Configuration assembled from CLI arguments and passed to every@@ -204,22 +206,32 @@ pub struct CursorRegistry {impl CursorRegistry {pub fn new() -> Self {let mut map = HashMap::new();- map.insert("default".into(), CursorInstanceState {- config: CursorInstanceConfig::default(),- x: None,- y: None,- });- Self { inner: Mutex::new(map) }+ map.insert(+ "default".into(),+ CursorInstanceState {+ config: CursorInstanceConfig::default(),+ x: None,+ y: None,+ },+ );+ Self {+ inner: Mutex::new(map),+ }}pub fn get_or_create(&self, cursor_id: &str) -> CursorInstanceState {let mut inner = self.inner.lock().unwrap();- inner.entry(cursor_id.to_owned()).or_insert_with(|| CursorInstanceState {- config: CursorInstanceConfig {- cursor_id: cursor_id.to_owned(), ..Default::default()- },- x: None, y: None,- }).clone()+ inner+ .entry(cursor_id.to_owned())+ .or_insert_with(|| CursorInstanceState {+ config: CursorInstanceConfig {+ cursor_id: cursor_id.to_owned(),+ ..Default::default()+ },+ x: None,+ y: None,+ })+ .clone()}/// Read one cursor without materializing a new registry entry.@@ -229,29 +241,47 @@ impl CursorRegistry {pub fn update_position(&self, cursor_id: &str, x: f64, y: f64) {let mut inner = self.inner.lock().unwrap();- let state = inner.entry(cursor_id.to_owned()).or_insert_with(|| CursorInstanceState {- config: CursorInstanceConfig { cursor_id: cursor_id.to_owned(), ..Default::default() },- x: None, y: None,- });+ let state = inner+ .entry(cursor_id.to_owned())+ .or_insert_with(|| CursorInstanceState {+ config: CursorInstanceConfig {+ cursor_id: cursor_id.to_owned(),+ ..Default::default()+ },+ x: None,+ y: None,+ });state.x = Some(x);state.y = Some(y);}pub fn set_enabled(&self, cursor_id: &str, enabled: bool) {let mut inner = self.inner.lock().unwrap();- let state = inner.entry(cursor_id.to_owned()).or_insert_with(|| CursorInstanceState {- config: CursorInstanceConfig { cursor_id: cursor_id.to_owned(), ..Default::default() },- x: None, y: None,- });+ let state = inner+ .entry(cursor_id.to_owned())+ .or_insert_with(|| CursorInstanceState {+ config: CursorInstanceConfig {+ cursor_id: cursor_id.to_owned(),+ ..Default::default()+ },+ x: None,+ y: None,+ });state.config.enabled = enabled;}pub fn update_config(&self, cursor_id: &str, f: impl FnOnce(&mut CursorInstanceConfig)) {let mut inner = self.inner.lock().unwrap();- let state = inner.entry(cursor_id.to_owned()).or_insert_with(|| CursorInstanceState {- config: CursorInstanceConfig { cursor_id: cursor_id.to_owned(), ..Default::default() },- x: None, y: None,- });+ let state = inner+ .entry(cursor_id.to_owned())+ .or_insert_with(|| CursorInstanceState {+ config: CursorInstanceConfig {+ cursor_id: cursor_id.to_owned(),+ ..Default::default()+ },+ x: None,+ y: None,+ });f(&mut state.config);}@@ -271,7 +301,9 @@ impl CursorRegistry {}impl Default for CursorRegistry {- fn default() -> Self { Self::new() }+ fn default() -> Self {+ Self::new()+ }}/// Identifier for one owned cursor in the keyed render collection.@@ -308,9 +340,17 @@ pub enum OverlayMsg {#[derive(Debug, Clone)]pub enum OverlayCommand {/// Animate the cursor to a new screen position.- MoveTo { x: f64, y: f64, end_heading_radians: f64 },+ MoveTo {+ x: f64,+ y: f64,+ end_heading_radians: f64,+ },/// Snap the cursor immediately to a screen position, optionally updating heading.- SnapTo { x: f64, y: f64, heading_radians: Option<f64> },+ SnapTo {+ x: f64,+ y: f64,+ heading_radians: Option<f64>,+ },/// Start the click-press visual.ClickPulse { x: f64, y: f64 },/// Toggle the held-button visual state.diff --git a/libs/cua-driver/rust/crates/cursor-overlay/src/motion.rs b/libs/cua-driver/rust/crates/cursor-overlay/src/motion.rsindex eba976ca50..db51020f86 100644--- a/libs/cua-driver/rust/crates/cursor-overlay/src/motion.rs+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/motion.rs@@ -44,9 +44,9 @@ impl Default for MotionConfig {arc_size: 0.25,arc_flow: 0.0,spring: 0.72,- glide_duration_ms: 0.0, // 0 = speed-based mode+ glide_duration_ms: 0.0, // 0 = speed-based modedwell_after_click_ms: 80.0,- idle_hide_ms: 20_000.0, // fade 20s after last activity (matches .NET reference)+ idle_hide_ms: 20_000.0, // fade 20s after last activity (matches .NET reference)press_duration_ms: 120.0,peak_speed: 900.0,min_start_speed: 300.0,@@ -71,21 +71,35 @@ impl MotionConfig {press_duration_ms: Option<f64>,turn_radius: Option<f64>,) -> Self {- fn clamp(v: f64, lo: f64, hi: f64) -> f64 { v.clamp(lo, hi) }+ fn clamp(v: f64, lo: f64, hi: f64) -> f64 {+ v.clamp(lo, hi)+ }Self {- start_handle: clamp(start_handle.unwrap_or(self.start_handle), 0.0, 1.0),- end_handle: clamp(end_handle.unwrap_or(self.end_handle), 0.0, 1.0),- arc_size: clamp(arc_size.unwrap_or(self.arc_size), 0.0, 1.0),- arc_flow: clamp(arc_flow.unwrap_or(self.arc_flow), -1.0, 1.0),- spring: clamp(spring.unwrap_or(self.spring), 0.3, 1.0),- glide_duration_ms: clamp(glide_duration_ms.unwrap_or(self.glide_duration_ms), 0.0, 5000.0),- dwell_after_click_ms: clamp(dwell_after_click_ms.unwrap_or(self.dwell_after_click_ms), 0.0, 5000.0),- idle_hide_ms: clamp(idle_hide_ms.unwrap_or(self.idle_hide_ms), 0.0, 60_000.0),- press_duration_ms: clamp(press_duration_ms.unwrap_or(self.press_duration_ms), 0.0, 5000.0),- peak_speed: self.peak_speed,- min_start_speed: self.min_start_speed,- min_end_speed: self.min_end_speed,- turn_radius: clamp(turn_radius.unwrap_or(self.turn_radius), 1.0, 1000.0),+ start_handle: clamp(start_handle.unwrap_or(self.start_handle), 0.0, 1.0),+ end_handle: clamp(end_handle.unwrap_or(self.end_handle), 0.0, 1.0),+ arc_size: clamp(arc_size.unwrap_or(self.arc_size), 0.0, 1.0),+ arc_flow: clamp(arc_flow.unwrap_or(self.arc_flow), -1.0, 1.0),+ spring: clamp(spring.unwrap_or(self.spring), 0.3, 1.0),+ glide_duration_ms: clamp(+ glide_duration_ms.unwrap_or(self.glide_duration_ms),+ 0.0,+ 5000.0,+ ),+ dwell_after_click_ms: clamp(+ dwell_after_click_ms.unwrap_or(self.dwell_after_click_ms),+ 0.0,+ 5000.0,+ ),+ idle_hide_ms: clamp(idle_hide_ms.unwrap_or(self.idle_hide_ms), 0.0, 60_000.0),+ press_duration_ms: clamp(+ press_duration_ms.unwrap_or(self.press_duration_ms),+ 0.0,+ 5000.0,+ ),+ peak_speed: self.peak_speed,+ min_start_speed: self.min_start_speed,+ min_end_speed: self.min_end_speed,+ turn_radius: clamp(turn_radius.unwrap_or(self.turn_radius), 1.0, 1000.0),}}}diff --git a/libs/cua-driver/rust/crates/cursor-overlay/src/palette.rs b/libs/cua-driver/rust/crates/cursor-overlay/src/palette.rsindex 2efc42d1fc..ae5b2aecc9 100644--- a/libs/cua-driver/rust/crates/cursor-overlay/src/palette.rs+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/palette.rs@@ -20,36 +20,110 @@ pub struct Palette {}// Raw palette data as (&name, start, mid, end, bloom_outer, bloom_inner).-type PaletteData = (&'static str, [u8;4], [u8;4], [u8;4], [u8;4], [u8;4]);+type PaletteData = (&'static str, [u8; 4], [u8; 4], [u8; 4], [u8; 4], [u8; 4]);-const fn rgba(r: u8, g: u8, b: u8) -> [u8; 4] { [r, g, b, 255] }+const fn rgba(r: u8, g: u8, b: u8) -> [u8; 4] {+ [r, g, b, 255]+}const PALETTE_DATA: &[PaletteData] = &[- ("default_blue", rgba(219,238,255), rgba( 94,192,232), rgba( 84,205,160), rgba(188,232,252), rgba(238,248,255)),- ("soft_purple", rgba(238,226,255), rgba(178,132,255), rgba(118,194,255), rgba(214,188,255), rgba(246,238,255)),- ("rose_gold", rgba(255,231,238), rgba(247,132,170), rgba(255,181,108), rgba(255,190,211), rgba(255,243,232)),- ("mint_lime", rgba(226,255,240), rgba( 96,218,174), rgba(178,229, 72), rgba(178,245,217), rgba(241,255,231)),- ("amber", rgba(255,244,214), rgba(244,178, 66), rgba(255,126, 92), rgba(255,219,140), rgba(255,248,225)),- ("aqua", rgba(221,252,255), rgba( 76,204,224), rgba( 63,222,166), rgba(172,241,249), rgba(236,255,251)),- ("orchid", rgba(252,228,255), rgba(221,113,236), rgba(255,139,196), rgba(237,181,246), rgba(255,239,252)),- ("crimson", rgba(255,226,226), rgba(232, 82, 98), rgba(150, 94,255), rgba(255,168,178), rgba(255,240,241)),- ("chartreuse", rgba(247,255,218), rgba(184,220, 54), rgba( 72,190,119), rgba(224,247,128), rgba(249,255,232)),- ("cobalt", rgba(226,235,255), rgba( 80,126,236), rgba( 91,219,222), rgba(170,195,255), rgba(239,246,255)),+ (+ "default_blue",+ rgba(219, 238, 255),+ rgba(94, 192, 232),+ rgba(84, 205, 160),+ rgba(188, 232, 252),+ rgba(238, 248, 255),+ ),+ (+ "soft_purple",+ rgba(238, 226, 255),+ rgba(178, 132, 255),+ rgba(118, 194, 255),+ rgba(214, 188, 255),+ rgba(246, 238, 255),+ ),+ (+ "rose_gold",+ rgba(255, 231, 238),+ rgba(247, 132, 170),+ rgba(255, 181, 108),+ rgba(255, 190, 211),+ rgba(255, 243, 232),+ ),+ (+ "mint_lime",+ rgba(226, 255, 240),+ rgba(96, 218, 174),+ rgba(178, 229, 72),+ rgba(178, 245, 217),+ rgba(241, 255, 231),+ ),+ (+ "amber",+ rgba(255, 244, 214),+ rgba(244, 178, 66),+ rgba(255, 126, 92),+ rgba(255, 219, 140),+ rgba(255, 248, 225),+ ),+ (+ "aqua",+ rgba(221, 252, 255),+ rgba(76, 204, 224),+ rgba(63, 222, 166),+ rgba(172, 241, 249),+ rgba(236, 255, 251),+ ),+ (+ "orchid",+ rgba(252, 228, 255),+ rgba(221, 113, 236),+ rgba(255, 139, 196),+ rgba(237, 181, 246),+ rgba(255, 239, 252),+ ),+ (+ "crimson",+ rgba(255, 226, 226),+ rgba(232, 82, 98),+ rgba(150, 94, 255),+ rgba(255, 168, 178),+ rgba(255, 240, 241),+ ),+ (+ "chartreuse",+ rgba(247, 255, 218),+ rgba(184, 220, 54),+ rgba(72, 190, 119),+ rgba(224, 247, 128),+ rgba(249, 255, 232),+ ),+ (+ "cobalt",+ rgba(226, 235, 255),+ rgba(80, 126, 236),+ rgba(91, 219, 222),+ rgba(170, 195, 255),+ rgba(239, 246, 255),+ ),];fn from_data(d: &PaletteData) -> Palette {Palette {- name: d.0.to_owned(),+ name: d.0.to_owned(),cursor_start: d.1,- cursor_mid: d.2,- cursor_end: d.3,- bloom_outer: d.4,- bloom_inner: d.5,+ cursor_mid: d.2,+ cursor_end: d.3,+ bloom_outer: d.4,+ bloom_inner: d.5,}}impl Palette {- pub fn default_blue() -> Self { from_data(&PALETTE_DATA[0]) }+ pub fn default_blue() -> Self {+ from_data(&PALETTE_DATA[0])+ }/// Select a palette for an instance id using the same stable-hash/// logic as the C# `AgentCursorPalette.ForInstance`.@@ -88,9 +162,15 @@ fn lerp_rgba(a: [u8; 4], b: [u8; 4], t: f64) -> [u8; 4] {}fn stable_index(id: &str, count: usize) -> usize {- let suffix = id.rfind(|c| c == '-' || c == '_' || c == '.')- .map(|i| &id[i + 1..]).unwrap_or(id);- if let Ok(n) = suffix.parse::<usize>() { if n > 0 { return (n - 1) % count; } }+ let suffix = id+ .rfind(|c| c == '-' || c == '_' || c == '.')+ .map(|i| &id[i + 1..])+ .unwrap_or(id);+ if let Ok(n) = suffix.parse::<usize>() {+ if n > 0 {+ return (n - 1) % count;+ }+ }if suffix.len() == 1 {if let Some(c) = suffix.chars().next() {if c.is_ascii_alphabetic() {@@ -99,6 +179,9 @@ fn stable_index(id: &str, count: usize) -> usize {}}let mut hash: u32 = 2_166_136_261;- for c in id.chars() { hash ^= c as u32; hash = hash.wrapping_mul(16_777_619); }+ for c in id.chars() {+ hash ^= c as u32;+ hash = hash.wrapping_mul(16_777_619);+ }(hash as usize) % count}diff --git a/libs/cua-driver/rust/crates/cursor-overlay/src/path_planner.rs b/libs/cua-driver/rust/crates/cursor-overlay/src/path_planner.rsindex bfbfb75fe2..22a53a9596 100644--- a/libs/cua-driver/rust/crates/cursor-overlay/src/path_planner.rs+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/path_planner.rs@@ -18,11 +18,18 @@ pub struct PathState {/// The kind of path (Dubins arc–straight–arc, or linear fallback).#[derive(Debug, Clone, Copy, PartialEq)]-enum PathKind { Dubins, Linear }+enum PathKind {+ Dubins,+ Linear,+}/// The three Dubins segment types.#[derive(Debug, Clone, Copy, PartialEq)]-enum SegType { L, R, S }+enum SegType {+ L,+ R,+ S,+}/// A planned path (Dubins or linear fallback).#[derive(Debug, Clone)]@@ -31,12 +38,18 @@ pub struct PlannedPath {pub end_visual_heading: f64,kind: PathKind,// Dubins state- x0: f64, y0: f64, th0: f64,+ x0: f64,+ y0: f64,+ th0: f64,r: f64,- seg1: f64, seg2: f64, seg3: f64,+ seg1: f64,+ seg2: f64,+ seg3: f64,types: [SegType; 3],// Linear fallback- x1: f64, y1: f64, th1: f64,+ x1: f64,+ y1: f64,+ th1: f64,}impl PlannedPath {@@ -53,18 +66,26 @@ impl PlannedPath {let len = self.length.max(1.0);let u = (s / len).clamp(0.0, 1.0);let mut diff = self.th1 - self.th0;- while diff > PI { diff -= 2.0 * PI; }- while diff < -PI { diff += 2.0 * PI; }+ while diff > PI {+ diff -= 2.0 * PI;+ }+ while diff < -PI {+ diff += 2.0 * PI;+ }PathState {- x: self.x0 + (self.x1 - self.x0) * u,- y: self.y0 + (self.y1 - self.y0) * u,+ x: self.x0 + (self.x1 - self.x0) * u,+ y: self.y0 + (self.y1 - self.y0) * u,heading: self.th0 + diff * u,}}fn sample_dubins(&self, s_in: f64) -> PathState {if s_in <= 0.0 {- return PathState { x: self.x0, y: self.y0, heading: self.th0 };+ return PathState {+ x: self.x0,+ y: self.y0,+ heading: self.th0,+ };}let r = self.r;let l1 = self.seg1 * r;@@ -72,8 +93,8 @@ impl PlannedPath {let l3 = self.seg3 * r;let s = s_in.min(l1 + l2 + l3);- let mut x = self.x0;- let mut y = self.y0;+ let mut x = self.x0;+ let mut y = self.y0;let mut th = self.th0;let mut advance = |len: f64, seg: SegType| {@@ -82,7 +103,11 @@ impl PlannedPath {y += th.sin() * len;} else {let dth = (len / r) * if seg == SegType::L { 1.0 } else { -1.0 };- let perp = if seg == SegType::L { PI / 2.0 } else { -PI / 2.0 };+ let perp = if seg == SegType::L {+ PI / 2.0+ } else {+ -PI / 2.0+ };let cx = x + (th + perp).cos() * r;let cy = y + (th + perp).sin() * r;let ang = (y - cy).atan2(x - cx);@@ -117,8 +142,12 @@ impl PathPlanner {/// * `end_visual_heading` — the arrow heading at rest (for the rendered tip)./// * `turn_radius` — minimum turning radius in points (Swift default: 80).pub fn plan(- x0: f64, y0: f64, th0: f64,- x1: f64, y1: f64, th1: f64,+ x0: f64,+ y0: f64,+ th0: f64,+ x1: f64,+ y1: f64,+ th1: f64,end_visual_heading: f64,turn_radius: f64,) -> PlannedPath {@@ -132,10 +161,17 @@ impl PathPlanner {length: d,end_visual_heading,kind: PathKind::Linear,- x0, y0, th0, r,- seg1: 0.0, seg2: 0.0, seg3: 0.0,+ x0,+ y0,+ th0,+ r,+ seg1: 0.0,+ seg2: 0.0,+ seg3: 0.0,types: [SegType::S, SegType::S, SegType::S],- x1, y1, th1,+ x1,+ y1,+ th1,}}}@@ -145,25 +181,37 @@ impl PathPlanner {fn mod2pi(x: f64) -> f64 {let tau = 2.0 * PI;let r = x - tau * (x / tau).floor();- if r < 0.0 { r + tau } else { r }+ if r < 0.0 {+ r + tau+ } else {+ r+ }}struct DubinsSol {- t: f64, p: f64, q: f64,+ t: f64,+ p: f64,+ q: f64,types: [SegType; 3],}impl DubinsSol {- fn length(&self) -> f64 { self.t + self.p + self.q }+ fn length(&self) -> f64 {+ self.t + self.p + self.q+ }}fn dubins_lsl(d: f64, a: f64, b: f64) -> Option<DubinsSol> {let tmp0 = d + a.sin() - b.sin();let p2 = 2.0 + d * d - 2.0 * (a - b).cos() + 2.0 * d * (a.sin() - b.sin());- if p2 < 0.0 { return None; }+ if p2 < 0.0 {+ return None;+ }let tmp1 = (b.cos() - a.cos()).atan2(tmp0);Some(DubinsSol {- t: mod2pi(-a + tmp1), p: p2.sqrt(), q: mod2pi(b - tmp1),+ t: mod2pi(-a + tmp1),+ p: p2.sqrt(),+ q: mod2pi(b - tmp1),types: [SegType::L, SegType::S, SegType::L],})}@@ -171,69 +219,95 @@ fn dubins_lsl(d: f64, a: f64, b: f64) -> Option<DubinsSol> {fn dubins_rsr(d: f64, a: f64, b: f64) -> Option<DubinsSol> {let tmp0 = d - a.sin() + b.sin();let p2 = 2.0 + d * d - 2.0 * (a - b).cos() + 2.0 * d * (b.sin() - a.sin());- if p2 < 0.0 { return None; }+ if p2 < 0.0 {+ return None;+ }let tmp1 = (a.cos() - b.cos()).atan2(tmp0);Some(DubinsSol {- t: mod2pi(a - tmp1), p: p2.sqrt(), q: mod2pi(-b + tmp1),+ t: mod2pi(a - tmp1),+ p: p2.sqrt(),+ q: mod2pi(-b + tmp1),types: [SegType::R, SegType::S, SegType::R],})}fn dubins_lsr(d: f64, a: f64, b: f64) -> Option<DubinsSol> {let p2 = -2.0 + d * d + 2.0 * (a - b).cos() + 2.0 * d * (a.sin() + b.sin());- if p2 < 0.0 { return None; }+ if p2 < 0.0 {+ return None;+ }let p = p2.sqrt();let tmp1 = (-(a.cos() + b.cos())).atan2(d + a.sin() + b.sin()) - (-2.0_f64).atan2(p);Some(DubinsSol {- t: mod2pi(-a + tmp1), p, q: mod2pi(-mod2pi(b) + tmp1),+ t: mod2pi(-a + tmp1),+ p,+ q: mod2pi(-mod2pi(b) + tmp1),types: [SegType::L, SegType::S, SegType::R],})}fn dubins_rsl(d: f64, a: f64, b: f64) -> Option<DubinsSol> {let p2 = d * d - 2.0 + 2.0 * (a - b).cos() - 2.0 * d * (a.sin() + b.sin());- if p2 < 0.0 { return None; }+ if p2 < 0.0 {+ return None;+ }let p = p2.sqrt();let tmp1 = (a.cos() + b.cos()).atan2(d - a.sin() - b.sin()) - 2.0_f64.atan2(p);Some(DubinsSol {- t: mod2pi(a - tmp1), p, q: mod2pi(b - tmp1),+ t: mod2pi(a - tmp1),+ p,+ q: mod2pi(b - tmp1),types: [SegType::R, SegType::S, SegType::L],})}fn dubins_rlr(d: f64, a: f64, b: f64) -> Option<DubinsSol> {let tmp = (6.0 - d * d + 2.0 * (a - b).cos() + 2.0 * d * (a.sin() - b.sin())) / 8.0;- if tmp.abs() > 1.0 { return None; }+ if tmp.abs() > 1.0 {+ return None;+ }let p = mod2pi(2.0 * PI - tmp.acos());let t = mod2pi(a - (a.cos() - b.cos()).atan2(d - a.sin() + b.sin()) + p / 2.0);Some(DubinsSol {- t, p, q: mod2pi(a - b - t + p),+ t,+ p,+ q: mod2pi(a - b - t + p),types: [SegType::R, SegType::L, SegType::R],})}fn dubins_lrl(d: f64, a: f64, b: f64) -> Option<DubinsSol> {let tmp = (6.0 - d * d + 2.0 * (a - b).cos() + 2.0 * d * (b.sin() - a.sin())) / 8.0;- if tmp.abs() > 1.0 { return None; }+ if tmp.abs() > 1.0 {+ return None;+ }let p = mod2pi(2.0 * PI - tmp.acos());let t = mod2pi(-a + (-a.cos() + b.cos()).atan2(d + a.sin() - b.sin()) + p / 2.0);Some(DubinsSol {- t, p, q: mod2pi(mod2pi(b) - a - t + p),+ t,+ p,+ q: mod2pi(mod2pi(b) - a - t + p),types: [SegType::L, SegType::R, SegType::L],})}fn plan_dubins(- x0: f64, y0: f64, th0: f64,- x1: f64, y1: f64, th1: f64,+ x0: f64,+ y0: f64,+ th0: f64,+ x1: f64,+ y1: f64,+ th1: f64,r: f64,end_visual_heading: f64,) -> Option<PlannedPath> {let dx = x1 - x0;let dy = y1 - y0;let d_dist = dx.hypot(dy);- if d_dist < 0.5 { return None; }- let d = d_dist / r;+ if d_dist < 0.5 {+ return None;+ }+ let d = d_dist / r;let theta = mod2pi(dy.atan2(dx));let a = mod2pi(th0 - theta);let b = mod2pi(th1 - theta);@@ -259,9 +333,16 @@ fn plan_dubins(length: (sol.t + sol.p + sol.q) * r,end_visual_heading,kind: PathKind::Dubins,- x0, y0, th0, r,- seg1: sol.t, seg2: sol.p, seg3: sol.q,+ x0,+ y0,+ th0,+ r,+ seg1: sol.t,+ seg2: sol.p,+ seg3: sol.q,types: sol.types,- x1, y1, th1,+ x1,+ y1,+ th1,})}diff --git a/libs/cua-driver/rust/crates/cursor-overlay/src/render_state.rs b/libs/cua-driver/rust/crates/cursor-overlay/src/render_state.rsindex b9565020dc..3d11644d02 100644--- a/libs/cua-driver/rust/crates/cursor-overlay/src/render_state.rs+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/render_state.rs@@ -138,8 +138,7 @@ impl RenderStateCore {if let Some(ref p) = self.path {let path_len = p.length.max(1.0);let path_frac = (self.dist / path_len).clamp(0.0, 1.0);- let profile =- 16.0 * path_frac * path_frac * (1.0 - path_frac) * (1.0 - path_frac);+ let profile = 16.0 * path_frac * path_frac * (1.0 - path_frac) * (1.0 - path_frac);let floor = if path_frac < 0.5 {self.motion.min_start_speed} else {@@ -251,7 +250,11 @@ impl RenderStateCore {// Smootherstep speed profile (normalised: peak = 1.0).let profile = (30.0 * u * u * (1.0 - u) * (1.0 - u)) / 1.875;- let floor_speed = if u < 0.5 { MIN_START_SPEED } else { MIN_END_SPEED };+ let floor_speed = if u < 0.5 {+ MIN_START_SPEED+ } else {+ MIN_END_SPEED+ };let speed_based = floor_speed + (PEAK_SPEED - floor_speed) * profile;// Fixed-duration override: when `glide_duration_ms > 0` the move// takes exactly that long regardless of distance, so an orchestrator@@ -337,8 +340,7 @@ impl RenderStateCore {fn tick_idle(&mut self, dt: f64) {let idle_hide_ms = self.motion.idle_hide_ms;if idle_hide_ms > 0.0 {- let moving =- self.path.is_some() || self.spring.is_some() || self.click_t.is_some();+ let moving = self.path.is_some() || self.spring.is_some() || self.click_t.is_some();if moving {self.idle_secs = 0.0;self.idle_alpha = 1.0;@@ -402,16 +404,8 @@ impl RenderStateCore {let (x0, y0) = self.pos;let th0 = self.heading + std::f64::consts::PI;let th1 = end_heading_radians + std::f64::consts::PI;- let plan = PathPlanner::plan(- x0,- y0,- th0,- tx,- ty,- th1,- end_heading_radians,- turn_radius,- );+ let plan =+ PathPlanner::plan(x0, y0, th0, tx, ty, th1, end_heading_radians, turn_radius);self.path = Some(plan);self.dist = 0.0;self.spring = None;@@ -539,8 +533,8 @@ pub fn render_frame() -> tiny_skia::Pixmap {let w = width.max(1);let h = height.max(1);- let mut pm = tiny_skia::Pixmap::new(w, h)- .unwrap_or_else(|| tiny_skia::Pixmap::new(1, 1).unwrap());+ let mut pm =+ tiny_skia::Pixmap::new(w, h).unwrap_or_else(|| tiny_skia::Pixmap::new(1, 1).unwrap());paint_cursor(&mut pm, core, origin_x, origin_y, focus_rect, backing_scale);pm}@@ -638,8 +632,7 @@ pub fn paint_cursor(if core.pressed {let [pr, pg, pb, _] = core.palette.cursor_mid;- let ring_color =- tiny_skia::Color::from_rgba8(pr, pg, pb, (210.0 * alpha_scale) as u8);+ let ring_color = tiny_skia::Color::from_rgba8(pr, pg, pb, (210.0 * alpha_scale) as u8);let mut ring_paint = tiny_skia::Paint::default();ring_paint.shader = tiny_skia::Shader::SolidColor(ring_color);ring_paint.anti_alias = true;@@ -647,8 +640,7 @@ pub fn paint_cursor(width: 3.0 * sf,..Default::default()};- let core_fill =- tiny_skia::Color::from_rgba8(pr, pg, pb, (110.0 * alpha_scale) as u8);+ let core_fill = tiny_skia::Color::from_rgba8(pr, pg, pb, (110.0 * alpha_scale) as u8);let mut fill_paint = tiny_skia::Paint::default();fill_paint.shader = tiny_skia::Shader::SolidColor(core_fill);fill_paint.anti_alias = true;@@ -695,16 +687,14 @@ pub fn paint_cursor() {// Faint filllet mut fill_paint = tiny_skia::Paint::default();- fill_paint.shader = tiny_skia::Shader::SolidColor(- tiny_skia::Color::from_rgba8(cr, cg, cb, fill_a),- );+ fill_paint.shader =+ tiny_skia::Shader::SolidColor(tiny_skia::Color::from_rgba8(cr, cg, cb, fill_a));pm.fill_rect(rect, &fill_paint, tiny_skia::Transform::identity(), None);// Border stroke (2px glow)let mut border_paint = tiny_skia::Paint::default();- border_paint.shader = tiny_skia::Shader::SolidColor(- tiny_skia::Color::from_rgba8(cr, cg, cb, border_a),- );+ border_paint.shader =+ tiny_skia::Shader::SolidColor(tiny_skia::Color::from_rgba8(cr, cg, cb, border_a));border_paint.anti_alias = true;let stroke = tiny_skia::Stroke {width: 2.5 * sf,@@ -802,9 +792,7 @@ pub fn paint_cursor(// instead of upsampling a logical-pixel pixmap.let display_size = 26.0_f32 * sf;let scale = display_size / shape.width as f32;- if let Some(pix) =- tiny_skia::PixmapRef::from_bytes(&shape.pixels, shape.width, shape.height)- {+ if let Some(pix) = tiny_skia::PixmapRef::from_bytes(&shape.pixels, shape.width, shape.height) {// T = Translate(px, py) * Rotate(angle) * Scale(s) * Translate(-w/2, -h/2)// Centres the source on its own origin, scales to display_size, rotates// around the scaled centre, lands the centre at (px, py).@@ -850,9 +838,8 @@ pub fn draw_default_arrow(// Rotate by (heading + π) so tip points in the motion direction.let angle = heading + std::f64::consts::PI as f32;let (sa, ca) = (angle.sin(), angle.cos());- let transform_pt = |(vx, vy): (f32, f32)| -> (f32, f32) {- (px + ca * vx - sa * vy, py + sa * vx + ca * vy)- };+ let transform_pt =+ |(vx, vy): (f32, f32)| -> (f32, f32) { (px + ca * vx - sa * vy, py + sa * vx + ca * vy) };let pts: Vec<(f32, f32)> = verts.iter().map(|&v| transform_pt(v)).collect();@@ -870,24 +857,20 @@ pub fn draw_default_arrow(// Gradient fill: start color at tip, end color at tail.// Use runtime overrides when available, otherwise fall back to palette.let tip = pts[0];- let tail = (- (pts[1].0 + pts[3].0) / 2.0,- (pts[1].1 + pts[3].1) / 2.0,- );+ let tail = ((pts[1].0 + pts[3].0) / 2.0, (pts[1].1 + pts[3].1) / 2.0);let (r0, g0, b0) = if let Some(g) = gradient_override.and_then(|g| g.first()) {(g[0], g[1], g[2])} else {let [r, g, b, _] = palette.cursor_start;(r, g, b)};- let (r1, g1, b1) = if let Some(g) =- gradient_override.and_then(|g| g.get(1).or_else(|| g.first()))- {- (g[0], g[1], g[2])- } else {- let [r, g, b, _] = palette.cursor_mid;- (r, g, b)- };+ let (r1, g1, b1) =+ if let Some(g) = gradient_override.and_then(|g| g.get(1).or_else(|| g.first())) {+ (g[0], g[1], g[2])+ } else {+ let [r, g, b, _] = palette.cursor_mid;+ (r, g, b)+ };let (r2, g2, b2) = if let Some(g) = gradient_override.and_then(|g| g.last()) {(g[0], g[1], g[2])} else {@@ -909,9 +892,9 @@ pub fn draw_default_arrow(tiny_skia::SpreadMode::Pad,tiny_skia::Transform::identity(),)- .unwrap_or(tiny_skia::Shader::SolidColor(- tiny_skia::Color::from_rgba8(r1, g1, b1, a),- ));+ .unwrap_or(tiny_skia::Shader::SolidColor(tiny_skia::Color::from_rgba8(+ r1, g1, b1, a,+ )));p.anti_alias = true;p};@@ -956,14 +939,22 @@ mod glide_duration_tests {core.motion.idle_hide_ms = 0.0;core.pos = (0.0, 0.0);// Aligned headings → an effectively straight path of length ~dist_pts.- core.path = Some(PathPlanner::plan(0.0, 0.0, 0.0, dist_pts, 0.0, 0.0, 0.0, 80.0));+ core.path = Some(PathPlanner::plan(+ 0.0, 0.0, 0.0, dist_pts, 0.0, 0.0, 0.0, 80.0,+ ));core.dist = 0.0;let dt = 1.0 / 240.0;let mut t = 0.0;for _ in 0..200_000 {- let arrived = if swift { core.tick_swift_constants(dt) } else { core.tick_motion(dt) };+ let arrived = if swift {+ core.tick_swift_constants(dt)+ } else {+ core.tick_motion(dt)+ };t += dt;- if arrived { break; }+ if arrived {+ break;+ }}t}@@ -986,7 +977,10 @@ mod glide_duration_tests {for swift in [false, true] {let short = arrival_secs(0.0, 120.0, swift);let long = arrival_secs(0.0, 1400.0, swift);- assert!(long > short + 0.2, "swift={swift} short={short} long={long}");+ assert!(+ long > short + 0.2,+ "swift={swift} short={short} long={long}"+ );}}}@@ -999,10 +993,7 @@ mod backing_scale_tests {/// Count opaque (alpha > 0) pixels in the pixmap — a proxy for the/// cursor's on-pixmap footprint that's independent of palette / gradient.fn opaque_pixel_count(pm: &tiny_skia::Pixmap) -> u32 {- pm.data()- .chunks_exact(4)- .filter(|px| px[3] > 0)- .count() as u32+ pm.data().chunks_exact(4).filter(|px| px[3] > 0).count() as u32}fn render_at(backing_scale: f32, logical_size: u32) -> tiny_skia::Pixmap {diff --git a/libs/cua-driver/rust/crates/cursor-overlay/src/shape.rs b/libs/cua-driver/rust/crates/cursor-overlay/src/shape.rsindex 8f2e9e18a4..cf02061455 100644--- a/libs/cua-driver/rust/crates/cursor-overlay/src/shape.rs+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/shape.rs@@ -37,7 +37,10 @@ impl BuiltinShape {/// the default.pub fn parse(name: &str) -> Option<Self> {let lower = name.to_ascii_lowercase();- Self::TABLE.iter().find(|(n, _)| *n == lower).map(|(_, v)| *v)+ Self::TABLE+ .iter()+ .find(|(n, _)| *n == lower)+ .map(|(_, v)| *v)}/// The accepted built-in names in declaration order, e.g.@@ -56,7 +59,6 @@ impl BuiltinShape {.collect::<Vec<_>>().join(" | ")}-}impl Default for BuiltinShape {@@ -149,8 +151,7 @@ impl CursorShape {pub fn teardrop() -> &'static Self {static CACHE: std::sync::OnceLock<CursorShape> = std::sync::OnceLock::new();CACHE.get_or_init(|| {- Self::load_svg_bytes(TEARDROP_CURSOR_SVG)- .expect("embedded teardrop SVG should parse")+ Self::load_svg_bytes(TEARDROP_CURSOR_SVG).expect("embedded teardrop SVG should parse")})}@@ -163,16 +164,25 @@ impl CursorShape {let opts = usvg::Options::default();let tree = usvg::Tree::from_data(data, &opts)?;- let mut pixmap = tiny_skia::Pixmap::new(CURSOR_SIZE, CURSOR_SIZE)- .ok_or_else(|| anyhow::anyhow!("Failed to create {CURSOR_SIZE}×{CURSOR_SIZE} pixmap"))?;+ let mut pixmap = tiny_skia::Pixmap::new(CURSOR_SIZE, CURSOR_SIZE).ok_or_else(|| {+ anyhow::anyhow!("Failed to create {CURSOR_SIZE}×{CURSOR_SIZE} pixmap")+ })?;let sx = CURSOR_SIZE as f32 / tree.size().width();let sy = CURSOR_SIZE as f32 / tree.size().height();- resvg::render(&tree, tiny_skia::Transform::from_scale(sx, sy), &mut pixmap.as_mut());+ resvg::render(+ &tree,+ tiny_skia::Transform::from_scale(sx, sy),+ &mut pixmap.as_mut(),+ );let raw = pixmap.take();let pixels = unpremultiply(raw);- Ok(Self { pixels, width: CURSOR_SIZE, height: CURSOR_SIZE })+ Ok(Self {+ pixels,+ width: CURSOR_SIZE,+ height: CURSOR_SIZE,+ })}fn load_raster(path: &str) -> Result<Self> {@@ -214,9 +224,18 @@ mod tests {assert_eq!(BuiltinShape::parse("arrow"), Some(BuiltinShape::Arrow));assert_eq!(BuiltinShape::parse("ARROW"), Some(BuiltinShape::Arrow));assert_eq!(BuiltinShape::parse("Arrow"), Some(BuiltinShape::Arrow));- assert_eq!(BuiltinShape::parse("teardrop"), Some(BuiltinShape::Teardrop));- assert_eq!(BuiltinShape::parse("TEARDROP"), Some(BuiltinShape::Teardrop));- assert_eq!(BuiltinShape::parse("Teardrop"), Some(BuiltinShape::Teardrop));+ assert_eq!(+ BuiltinShape::parse("teardrop"),+ Some(BuiltinShape::Teardrop)+ );+ assert_eq!(+ BuiltinShape::parse("TEARDROP"),+ Some(BuiltinShape::Teardrop)+ );+ assert_eq!(+ BuiltinShape::parse("Teardrop"),+ Some(BuiltinShape::Teardrop)+ );}#[test]@@ -225,8 +244,8 @@ mod tests {assert_eq!(BuiltinShape::parse("diamond"), None);assert_eq!(BuiltinShape::parse("arrow "), None); // whitespace-significantassert_eq!(BuiltinShape::parse("cua_brand"), None); // legacy name no longer recognised- // The invented MCP names that never existed in the renderer must NOT parse —- // they were doc-only fiction and are gone now.+ // The invented MCP names that never existed in the renderer must NOT parse —+ // they were doc-only fiction and are gone now.assert_eq!(BuiltinShape::parse("crosshair"), None);assert_eq!(BuiltinShape::parse("hand"), None);assert_eq!(BuiltinShape::parse("dot"), None);@@ -239,7 +258,10 @@ mod tests {let help = BuiltinShape::names_help();for name in BuiltinShape::names() {assert!(help.contains(name), "names_help() missing {name}: {help}");- assert!(BuiltinShape::parse(name).is_some(), "{name} listed but unparseable");+ assert!(+ BuiltinShape::parse(name).is_some(),+ "{name} listed but unparseable"+ );}assert_eq!(help, "'arrow' | 'teardrop'");}@@ -248,11 +270,20 @@ mod tests {fn resolve_cursor_icon_matches_builtins_and_revert() {use CursorIconResolution::*;// Empty reverts to the configured default built-in (now teardrop).- assert!(matches!(resolve_cursor_icon("").unwrap(), Builtin(BuiltinShape::Teardrop)));+ assert!(matches!(+ resolve_cursor_icon("").unwrap(),+ Builtin(BuiltinShape::Teardrop)+ ));// Built-in names resolve to that built-in, case-insensitively —// crucially `arrow` stays reachable even though teardrop is the default.- assert!(matches!(resolve_cursor_icon("arrow").unwrap(), Builtin(BuiltinShape::Arrow)));- assert!(matches!(resolve_cursor_icon("TEARDROP").unwrap(), Builtin(BuiltinShape::Teardrop)));+ assert!(matches!(+ resolve_cursor_icon("arrow").unwrap(),+ Builtin(BuiltinShape::Arrow)+ ));+ assert!(matches!(+ resolve_cursor_icon("TEARDROP").unwrap(),+ Builtin(BuiltinShape::Teardrop)+ ));// A non-name, non-existent path is treated as a file and fails to load.assert!(resolve_cursor_icon("/no/such/cursor.png").is_err());}diff --git a/libs/cua-driver/rust/crates/pip-preview/src/lib.rs b/libs/cua-driver/rust/crates/pip-preview/src/lib.rsindex 9ea83e2a10..87e9a819a7 100644--- a/libs/cua-driver/rust/crates/pip-preview/src/lib.rs+++ b/libs/cua-driver/rust/crates/pip-preview/src/lib.rs@@ -23,7 +23,11 @@ use std::sync::OnceLock;pub fn default_config_path() -> Option<std::path::PathBuf> {std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))- .map(|h| std::path::PathBuf::from(h).join(".cua-driver").join("config.json"))+ .map(|h| {+ std::path::PathBuf::from(h)+ .join(".cua-driver")+ .join("config.json")+ })}/// Read a single key from `~/.cua-driver/config.json` as a raw JSON value,@@ -76,8 +80,12 @@ pub fn read_pip_keys_from_file() -> (bool, Option<String>) {Ok(v) => v,Err(_) => return (false, None),};- let enabled = json.get("experimental_pip").and_then(|v| v.as_bool()).unwrap_or(false);- let geometry = json.get("experimental_pip_geometry")+ let enabled = json+ .get("experimental_pip")+ .and_then(|v| v.as_bool())+ .unwrap_or(false);+ let geometry = json+ .get("experimental_pip_geometry").and_then(|v| v.as_str()).map(|s| s.to_owned());(enabled, geometry)@@ -212,7 +220,10 @@ impl PipConfig {if let Some(b) = json.get("experimental_pip").and_then(|v| v.as_bool()) {cfg.enabled = b;}- if let Some(s) = json.get("experimental_pip_geometry").and_then(|v| v.as_str()) {+ if let Some(s) = json+ .get("experimental_pip_geometry")+ .and_then(|v| v.as_str())+ {if let Some(g) = PipGeometry::parse(s) {cfg.geometry = g;}diff --git a/libs/cua-driver/rust/crates/platform-linux/examples/libei_input.rs b/libs/cua-driver/rust/crates/platform-linux/examples/libei_input.rsindex 5707047816..16ec7ef1f0 100644--- a/libs/cua-driver/rust/crates/platform-linux/examples/libei_input.rs+++ b/libs/cua-driver/rust/crates/platform-linux/examples/libei_input.rs@@ -34,7 +34,8 @@ fn main() {eprintln!("\n-- click(500, 400, Left) --");let t = std::time::Instant::now();match platform_linux::wayland::libei::click(- 500.0, 400.0,+ 500.0,+ 400.0,platform_linux::wayland::libei::Button::Left,) {Ok(()) => eprintln!(" OK in {:?}", t.elapsed()),diff --git a/libs/cua-driver/rust/crates/platform-linux/src/atspi/cache.rs b/libs/cua-driver/rust/crates/platform-linux/src/atspi/cache.rsindex 4c8ae061e4..78807c6ae9 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/atspi/cache.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/atspi/cache.rs@@ -10,7 +10,10 @@ use super::AtspiNode;use cua_driver_core::element_cache::ElementCacheCore;#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]-pub struct CacheKey { pub pid: u32, pub xid: u64 }+pub struct CacheKey {+ pub pid: u32,+ pub xid: u64,+}pub struct CachedSnapshot {/// element_index → element_key (opaque AT-SPI path hash).@@ -22,14 +25,20 @@ pub struct ElementCache {}impl ElementCache {- pub fn new() -> Self { Self { core: ElementCacheCore::new() } }+ pub fn new() -> Self {+ Self {+ core: ElementCacheCore::new(),+ }+ }pub fn update(&self, pid: u32, xid: u64, nodes: &[AtspiNode]) {- let elements: Vec<u64> = nodes.iter()+ let elements: Vec<u64> = nodes+ .iter().filter(|n| n.element_index.is_some()).map(|n| n.element_key).collect();- self.core.insert(CacheKey { pid, xid }, CachedSnapshot { elements });+ self.core+ .insert(CacheKey { pid, xid }, CachedSnapshot { elements });}pub fn get_element_key(&self, pid: u32, xid: u64, idx: usize) -> Option<u64> {@@ -45,4 +54,8 @@ impl ElementCache {}}-impl Default for ElementCache { fn default() -> Self { Self::new() } }+impl Default for ElementCache {+ fn default() -> Self {+ Self::new()+ }+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/health_report.rs b/libs/cua-driver/rust/crates/platform-linux/src/health_report.rsindex b7d21eb8c9..8f729d88bf 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/health_report.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/health_report.rs@@ -79,15 +79,13 @@ pub(crate) fn check_binary_version() -> CheckEntry {pub(crate) fn check_platform_supported() -> CheckEntry {let arch = arch_label();let os_version = os_release_pretty_name().unwrap_or_else(|| "Linux".to_owned());- CheckEntry::pass(- NAME_PLATFORM_SUPPORTED,- format!("{os_version} ({arch})"),+ CheckEntry::pass(NAME_PLATFORM_SUPPORTED, format!("{os_version} ({arch})")).with_data(+ CheckData {+ os_version: Some(os_version),+ architecture: Some(arch.to_owned()),+ ..Default::default()+ },)- .with_data(CheckData {- os_version: Some(os_version),- architecture: Some(arch.to_owned()),- ..Default::default()- })}pub(crate) fn check_session_active() -> CheckEntry {@@ -566,7 +564,9 @@ fn probe_portal_remote_desktop() -> anyhow::Result<bool> {let rt = tokio::runtime::Builder::new_current_thread().enable_all().build()- .map_err(|e| anyhow::anyhow!("failed to build tokio runtime for RemoteDesktop probe: {e}"))?;+ .map_err(|e| {+ anyhow::anyhow!("failed to build tokio runtime for RemoteDesktop probe: {e}")+ })?;rt.block_on(async {match RemoteDesktop::new().await {@@ -699,7 +699,11 @@ mod tests {assert_eq!(entry.status, CheckStatus::Fail);assert!(entry.message.contains("portal/libei"), "{}", entry.message);- assert!(entry.hint.as_deref().unwrap_or("").contains("xdg-desktop-portal"));+ assert!(entry+ .hint+ .as_deref()+ .unwrap_or("")+ .contains("xdg-desktop-portal"));}#[test]@@ -716,8 +720,16 @@ mod tests {let entry = classify_wayland_backend(&snap, true, true, false);assert_eq!(entry.status, CheckStatus::Fail);- assert!(entry.message.contains("target-activation"), "{}", entry.message);- assert!(entry.message.contains("wrong application"), "{}", entry.message);+ assert!(+ entry.message.contains("target-activation"),+ "{}",+ entry.message+ );+ assert!(+ entry.message.contains("wrong application"),+ "{}",+ entry.message+ );}#[tokio::test]@@ -753,10 +765,7 @@ mod tests {NAME_BUNDLE_IDENTITY,] {let entry = by_name[name];- assert_eq!(- entry["status"], "skip",- "{name} must be skipped on Linux"- );+ assert_eq!(entry["status"], "skip", "{name} must be skipped on Linux");assert_eq!(entry["message"], "not applicable on Linux");}}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/installed_apps.rs b/libs/cua-driver/rust/crates/platform-linux/src/installed_apps.rsindex 7738ae23c7..4268e0ad8f 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/installed_apps.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/installed_apps.rs@@ -38,13 +38,21 @@ pub fn list_installed_apps() -> Vec<InstalledApp> {let mut seen: std::collections::HashMap<String, InstalledApp> =std::collections::HashMap::new();for root in xdg_application_dirs() {- let Ok(entries) = fs::read_dir(&root) else { continue };+ let Ok(entries) = fs::read_dir(&root) else {+ continue;+ };for entry in entries.flatten() {let path = entry.path();- if path.extension().and_then(|e| e.to_str()) != Some("desktop") { continue }+ if path.extension().and_then(|e| e.to_str()) != Some("desktop") {+ continue;+ }let id = desktop_file_id(&root, &path);- if id.is_empty() { continue }- let Some(app) = parse_desktop_file(&path, &id) else { continue };+ if id.is_empty() {+ continue;+ }+ let Some(app) = parse_desktop_file(&path, &id) else {+ continue;+ };// Per the spec, user-scope files (XDG_DATA_HOME) override// system-scope ones with the same desktop file id.// xdg_application_dirs already yields user-scope first, so@@ -62,13 +70,17 @@ fn xdg_application_dirs() -> Vec<PathBuf> {let mut out = Vec::new();let home = std::env::var("HOME").unwrap_or_default();let xdg_data_home = std::env::var("XDG_DATA_HOME").unwrap_or_else(|_| {- if home.is_empty() { String::new() } else { format!("{home}/.local/share") }+ if home.is_empty() {+ String::new()+ } else {+ format!("{home}/.local/share")+ }});if !xdg_data_home.is_empty() {out.push(PathBuf::from(format!("{xdg_data_home}/applications")));}- let xdg_data_dirs = std::env::var("XDG_DATA_DIRS")- .unwrap_or_else(|_| "/usr/local/share:/usr/share".to_owned());+ let xdg_data_dirs =+ std::env::var("XDG_DATA_DIRS").unwrap_or_else(|_| "/usr/local/share:/usr/share".to_owned());for d in xdg_data_dirs.split(':').filter(|s| !s.is_empty()) {out.push(PathBuf::from(format!("{d}/applications")));}@@ -99,7 +111,8 @@ fn desktop_file_id(root: &Path, path: &Path) -> String {};// Use forward slash as the canonical separator (Linux only — `Path`// separators are always `/` here, but normalize defensively).- stem.replace(std::path::MAIN_SEPARATOR, "-").replace('/', "-")+ stem.replace(std::path::MAIN_SEPARATOR, "-")+ .replace('/', "-")}/// Parse a `.desktop` file. Returns `None` for entries the caller should skip@@ -161,7 +174,11 @@ fn extract_desktop_entry_section(text: &str) -> Option<String> {out.push('\n');}}- if out.is_empty() { None } else { Some(out) }+ if out.is_empty() {+ None+ } else {+ Some(out)+ }}fn string_key(section: &str, key: &str) -> Option<String> {@@ -174,11 +191,7 @@ fn string_key(section: &str, key: &str) -> Option<String> {.next().unwrap_or("").to_owned();- let lang_short: String = lang_root- .split('_')- .next()- .unwrap_or("")- .to_owned();+ let lang_short: String = lang_root.split('_').next().unwrap_or("").to_owned();let candidates = [format!("{key}[{lang_root}]="),@@ -186,7 +199,9 @@ fn string_key(section: &str, key: &str) -> Option<String> {format!("{key}="),];for cand in &candidates {- if cand.starts_with(&format!("{key}[]=")) { continue }+ if cand.starts_with(&format!("{key}[]=")) {+ continue;+ }for line in section.lines() {if let Some(rest) = line.strip_prefix(cand.as_str()) {let value = rest.trim_end_matches('\r').to_owned();@@ -243,7 +258,10 @@ fn unix_secs_to_rfc3339(secs: i64) -> String {let m = if mp < 10 { mp + 3 } else { mp - 9 };let y = if m <= 2 { y + 1 } else { y };- format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", y, m, d, hour, minute, second)+ format!(+ "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",+ y, m, d, hour, minute, second+ )}#[cfg(test)]@@ -253,7 +271,10 @@ mod tests {#[test]fn strips_field_codes() {assert_eq!(strip_exec_field_codes("firefox %U"), "firefox");- assert_eq!(strip_exec_field_codes("/usr/bin/gedit %f"), "/usr/bin/gedit");+ assert_eq!(+ strip_exec_field_codes("/usr/bin/gedit %f"),+ "/usr/bin/gedit"+ );assert_eq!(strip_exec_field_codes("xterm -e %F"), "xterm -e");}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/lib.rs b/libs/cua-driver/rust/crates/platform-linux/src/lib.rsindex 4f98d69563..cc756e787f 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/lib.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/lib.rs@@ -12,10 +12,10 @@use cua_driver_core::tool::ToolRegistry;-pub mod tools;+pub mod health_report;pub mod overlay;pub mod pip;-pub mod health_report;+pub mod tools;#[cfg(target_os = "linux")]pub mod x11;diff --git a/libs/cua-driver/rust/crates/platform-linux/src/proc_fs.rs b/libs/cua-driver/rust/crates/platform-linux/src/proc_fs.rsindex 16b758855f..d1bd686f35 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/proc_fs.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/proc_fs.rs@@ -36,13 +36,15 @@ pub fn list_processes() -> Vec<ProcessInfo> {Err(_) => continue,};- let proc_name = status.lines()+ let proc_name = status+ .lines().find(|l| l.starts_with("Name:")).map(|l| l[5..].trim().to_owned()).unwrap_or_default();let cmdline_path = proc_dir.join(&*pid_str).join("cmdline");- let cmdline = fs::read(cmdline_path).ok()+ let cmdline = fs::read(cmdline_path)+ .ok().map(|b| {// cmdline is NUL-separated; first entry is argv[0].let s = String::from_utf8_lossy(&b);@@ -50,7 +52,11 @@ pub fn list_processes() -> Vec<ProcessInfo> {}).unwrap_or_default();- result.push(ProcessInfo { pid, name: proc_name, cmdline });+ result.push(ProcessInfo {+ pid,+ name: proc_name,+ cmdline,+ });}result.sort_by_key(|p| p.pid);diff --git a/libs/cua-driver/rust/crates/platform-linux/src/session_bus.rs b/libs/cua-driver/rust/crates/platform-linux/src/session_bus.rsindex e0e9b6e60e..8b231ca8a5 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/session_bus.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/session_bus.rs@@ -94,7 +94,9 @@ fn discover_session_bus_address() -> Option<String> {/// misses and we go to the environ scan.fn current_uid() -> u32 {use std::os::unix::fs::MetadataExt;- std::fs::metadata("/proc/self").map(|m| m.uid()).unwrap_or(0)+ std::fs::metadata("/proc/self")+ .map(|m| m.uid())+ .unwrap_or(0)}/// Scan `/proc` for a desktop-session leader and return the@@ -163,7 +165,7 @@ mod tests {// Kernel-truncated comm (15 chars).assert!(is_session_process("gnome-session-b")); // gnome-session-binaryassert!(is_session_process("cinnamon-sessio")); // cinnamon-session- // Non-session processes are ignored.+ // Non-session processes are ignored.assert!(!is_session_process("bash"));assert!(!is_session_process("cua-driver"));assert!(!is_session_process(""));@@ -187,16 +189,25 @@ mod tests {);// Not anchored to the first entry, and tolerates a trailing NUL.let mid = b"A=1\0DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-xyz\0";- assert_eq!(dbus_address_from_environ(mid).as_deref(), Some("unix:abstract=/tmp/dbus-xyz"));+ assert_eq!(+ dbus_address_from_environ(mid).as_deref(),+ Some("unix:abstract=/tmp/dbus-xyz")+ );}#[test]fn dbus_address_absent_or_empty_is_none() {assert_eq!(dbus_address_from_environ(b"PATH=/usr/bin\0HOME=/x\0"), None);// Present but empty value must not match (avoids exporting "").- assert_eq!(dbus_address_from_environ(b"DBUS_SESSION_BUS_ADDRESS=\0"), None);+ assert_eq!(+ dbus_address_from_environ(b"DBUS_SESSION_BUS_ADDRESS=\0"),+ None+ );assert_eq!(dbus_address_from_environ(b""), None);// A key that merely contains the name as a substring must not match.- assert_eq!(dbus_address_from_environ(b"OLD_DBUS_SESSION_BUS_ADDRESS=x\0"), None);+ assert_eq!(+ dbus_address_from_environ(b"OLD_DBUS_SESSION_BUS_ADDRESS=x\0"),+ None+ );}}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/terminal.rs b/libs/cua-driver/rust/crates/platform-linux/src/terminal.rsindex 0e2db4dc15..fe43e5bd0b 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/terminal.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/terminal.rs@@ -25,7 +25,7 @@ pub const TERMINAL_WM_CLASS_SUBSTRINGS: &[&str] = &["iterm","kitty","konsole",- "terminal", // catches "Terminal", "xfce4-terminal-window", etc.+ "terminal", // catches "Terminal", "xfce4-terminal-window", etc."tilix","wezterm","xterm",@@ -102,14 +102,7 @@ mod tests {#[test]fn rejects_non_terminal_process_names() {- for n in [- "firefox",- "code",- "chrome",- "nautilus",- "gedit",- "",- ] {+ for n in ["firefox", "code", "chrome", "nautilus", "gedit", ""] {assert!(!is_terminal_process_name(n),"non-terminal {n:?} must not match"@@ -128,7 +121,7 @@ mod tests {("gnome-terminal-server", "Gnome-terminal"),("xterm", "XTerm"),("tilix", "Tilix"),- ("iterm", "iTerm"), // hypothetical port, but the substring matters+ ("iterm", "iTerm"), // hypothetical port, but the substring matters] {assert!(wm_class_matches_terminal(instance, class),diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/mod.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/mod.rsindex c8367a13d5..90dae84dbc 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/mod.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/mod.rs@@ -25,4 +25,6 @@ pub fn build_registry(compat: bool) -> ToolRegistry {}// Keep register_all as alias for backwards compat.-pub fn register_all() -> ToolRegistry { build_registry(false) }+pub fn register_all() -> ToolRegistry {+ build_registry(false)+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/page.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/page.rsindex 31c7341c14..401aa9dbee 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/page.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/page.rs@@ -27,11 +27,9 @@ impl PageBackend for LinuxPageBackend {async fn get_text(&self, pid: i32, window_id: u32) -> anyhow::Result<String> {let pid_u = pid as u32;let xid = window_id as u64;- let result = tokio::task::spawn_blocking(move || {- crate::atspi::walk_tree(pid_u, xid, None)- })- .await- .map_err(|e| anyhow::anyhow!("AT-SPI walk task failed: {e}"))?;+ let result = tokio::task::spawn_blocking(move || crate::atspi::walk_tree(pid_u, xid, None))+ .await+ .map_err(|e| anyhow::anyhow!("AT-SPI walk task failed: {e}"))?;Ok(extract_text_from_markdown(&result.tree_markdown))}@@ -45,11 +43,9 @@ impl PageBackend for LinuxPageBackend {let pid_u = pid as u32;let xid = window_id as u64;let selector = css_selector.to_owned();- let result = tokio::task::spawn_blocking(move || {- crate::atspi::walk_tree(pid_u, xid, None)- })- .await- .map_err(|e| anyhow::anyhow!("AT-SPI walk task failed: {e}"))?;+ let result = tokio::task::spawn_blocking(move || crate::atspi::walk_tree(pid_u, xid, None))+ .await+ .map_err(|e| anyhow::anyhow!("AT-SPI walk task failed: {e}"))?;if selector.contains("[data-") {anyhow::bail!(@@ -139,19 +135,20 @@ impl PageBackend for LinuxPageBackend {if cdp_port.is_none() && target_url_contains.is_none() {return self.execute_javascript(pid, window_id, javascript).await;}- let port = cdp_port.or_else(|| {- std::env::var("CUA_DRIVER_CDP_PORT")- .ok()- .and_then(|value| value.parse::<u16>().ok())- }).ok_or_else(|| anyhow::anyhow!(- "targeted execute_javascript on Linux requires cdp_port or CUA_DRIVER_CDP_PORT"- ))?;- let result = cua_driver_core::cdp::evaluate_targeted(- port,- javascript,- true,- target_url_contains,- ).await?;+ let port = cdp_port+ .or_else(|| {+ std::env::var("CUA_DRIVER_CDP_PORT")+ .ok()+ .and_then(|value| value.parse::<u16>().ok())+ })+ .ok_or_else(|| {+ anyhow::anyhow!(+ "targeted execute_javascript on Linux requires cdp_port or CUA_DRIVER_CDP_PORT"+ )+ })?;+ let result =+ cua_driver_core::cdp::evaluate_targeted(port, javascript, true, target_url_contains)+ .await?;Ok(format!("cdp.runtime.evaluate.user_gesture: {result}"))}}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/stubs.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/stubs.rsindex 5c820456fa..ade7b0b9c0 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/stubs.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/stubs.rs@@ -2,7 +2,10 @@//! Schemas match the macOS platform-macos implementations (cross-platform interface).use async_trait::async_trait;-use cua_driver_core::{protocol::ToolResult, tool::{Tool, ToolDef}};+use cua_driver_core::{+ protocol::ToolResult,+ tool::{Tool, ToolDef},+};use serde_json::Value;fn not_impl(name: &str) -> ToolResult {@@ -32,68 +35,120 @@ macro_rules! stub_tool {}#[async_trait]impl Tool for $struct_name {- fn def(&self) -> &ToolDef { Self::def_static() }- async fn invoke(&self, _args: Value) -> ToolResult { not_impl($tool_name) }+ fn def(&self) -> &ToolDef {+ Self::def_static()+ }+ async fn invoke(&self, _args: Value) -> ToolResult {+ not_impl($tool_name)+ }}}pub use $mod_name::$struct_name;};}-stub_tool!(list_apps_m, ListAppsTool, "list_apps",+stub_tool!(+ list_apps_m,+ ListAppsTool,+ "list_apps","List running regular-UI applications.",- serde_json::json!({"type":"object","properties":{},"additionalProperties":false}));+ serde_json::json!({"type":"object","properties":{},"additionalProperties":false})+);-stub_tool!(list_windows_m, ListWindowsTool, "list_windows",+stub_tool!(+ list_windows_m,+ ListWindowsTool,+ "list_windows","List top-level windows, optionally filtered by pid.",- serde_json::json!({"type":"object","properties":{"pid":{"type":"integer"}},"additionalProperties":false}));+ serde_json::json!({"type":"object","properties":{"pid":{"type":"integer"}},"additionalProperties":false})+);-stub_tool!(get_window_state_m, GetWindowStateTool, "get_window_state",+stub_tool!(+ get_window_state_m,+ GetWindowStateTool,+ "get_window_state","Walk a running app's AT-SPI tree and return BOTH the element tree AND a \screenshot — ground on both and cross-check (the tree lies on some surfaces). \Choose the modality at ACTION time: an element ax action (element_index) or an \element px action (x,y) off the screenshot. capture_mode is deprecated and ignored.",- serde_json::json!({"type":"object","required":["pid","window_id"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"window_id":{"type":"integer"},"query":{"type":"string"},"include_screenshot":{"type":"boolean","description":"Default true — returns a grounding screenshot alongside the tree. Set false to skip the grab and return tree only (the cheap path for re-indexing before an element ax action)."},"capture_mode": cua_driver_core::capture_mode::capture_mode_schema()},"additionalProperties":false}));+ serde_json::json!({"type":"object","required":["pid","window_id"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"window_id":{"type":"integer"},"query":{"type":"string"},"include_screenshot":{"type":"boolean","description":"Default true — returns a grounding screenshot alongside the tree. Set false to skip the grab and return tree only (the cheap path for re-indexing before an element ax action)."},"capture_mode": cua_driver_core::capture_mode::capture_mode_schema()},"additionalProperties":false})+);-stub_tool!(launch_app_m, LaunchAppTool, "launch_app",+stub_tool!(+ launch_app_m,+ LaunchAppTool,+ "launch_app","Launch an app in the background. Provide name or bundle_id.",- serde_json::json!({"type":"object","properties":{"bundle_id":{"type":"string"},"name":{"type":"string"},"urls":{"type":"array","items":{"type":"string"}}},"additionalProperties":false}));+ serde_json::json!({"type":"object","properties":{"bundle_id":{"type":"string"},"name":{"type":"string"},"urls":{"type":"array","items":{"type":"string"}}},"additionalProperties":false})+);stub_tool!(kill_app_m, KillAppTool, "kill_app","Force-terminate a process by pid (taskkill /F on Windows, kill -9 on macOS / Linux). Use as escalation when the cooperative close path didn't make the process exit.",serde_json::json!({"type":"object","required":["pid"],"properties":{"pid":{"type":"integer","description":"PID of the process to terminate."}},"additionalProperties":false}));-stub_tool!(click_m, ClickTool, "click",+stub_tool!(+ click_m,+ ClickTool,+ "click","Click at (x, y) or on an AT-SPI element by element_index + window_id.",- serde_json::json!({"type":"object","required":[],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"x":{"type":"number"},"y":{"type":"number"},"modifier": cua_driver_core::tool_schema::modifier_schema(),"from_zoom":{"type":"boolean"}},"additionalProperties":false}));+ serde_json::json!({"type":"object","required":[],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"x":{"type":"number"},"y":{"type":"number"},"modifier": cua_driver_core::tool_schema::modifier_schema(),"from_zoom":{"type":"boolean"}},"additionalProperties":false})+);-stub_tool!(double_click_m, DoubleClickTool, "double_click",+stub_tool!(+ double_click_m,+ DoubleClickTool,+ "double_click","Double-click at (x, y) or on an AT-SPI element by element_index + window_id.",- serde_json::json!({"type":"object","required":["pid"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"x":{"type":"number"},"y":{"type":"number"},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema()},"additionalProperties":false}));+ serde_json::json!({"type":"object","required":["pid"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"x":{"type":"number"},"y":{"type":"number"},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema()},"additionalProperties":false})+);-stub_tool!(right_click_m, RightClickTool, "right_click",+stub_tool!(+ right_click_m,+ RightClickTool,+ "right_click","Right-click (AT-SPI action on element, or synthesized event at x,y).",- serde_json::json!({"type":"object","required":["pid"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"window_id":{"type":"integer"},"x":{"type":"number"},"y":{"type":"number"},"modifier": cua_driver_core::tool_schema::modifier_schema()},"additionalProperties":false}));+ serde_json::json!({"type":"object","required":["pid"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"window_id":{"type":"integer"},"x":{"type":"number"},"y":{"type":"number"},"modifier": cua_driver_core::tool_schema::modifier_schema()},"additionalProperties":false})+);-stub_tool!(type_text_m, TypeTextTool, "type_text",+stub_tool!(+ type_text_m,+ TypeTextTool,+ "type_text","Insert text into the target pid via AT-SPI SetTextContents or XSendEvent keystrokes.",- serde_json::json!({"type":"object","required":["pid","text"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"text":{"type":"string"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"window_id":{"type":"integer"},"x":{"type":"number","description":"Screenshot-pixel X of the field to type into — the element px action form: pixel-click there to focus, then type. Pass with y, no element_index."},"y":{"type":"number","description":"Screenshot-pixel Y of the field (see x)."}},"additionalProperties":false}));+ serde_json::json!({"type":"object","required":["pid","text"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"text":{"type":"string"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"window_id":{"type":"integer"},"x":{"type":"number","description":"Screenshot-pixel X of the field to type into — the element px action form: pixel-click there to focus, then type. Pass with y, no element_index."},"y":{"type":"number","description":"Screenshot-pixel Y of the field (see x)."}},"additionalProperties":false})+);-stub_tool!(type_chars_m, TypeTextCharsTool, "type_text_chars",+stub_tool!(+ type_chars_m,+ TypeTextCharsTool,+ "type_text_chars","Type text character-by-character with configurable per-character delay.",- serde_json::json!({"type":"object","required":["pid","text"],"properties":{"pid":{"type":"integer"},"text":{"type":"string"},"delay_ms":{"type":"integer"},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema()},"additionalProperties":false}));+ serde_json::json!({"type":"object","required":["pid","text"],"properties":{"pid":{"type":"integer"},"text":{"type":"string"},"delay_ms":{"type":"integer"},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema()},"additionalProperties":false})+);-stub_tool!(press_key_m, PressKeyTool, "press_key",+stub_tool!(+ press_key_m,+ PressKeyTool,+ "press_key","Press and release a single key delivered directly to the target pid. No focus steal.",- serde_json::json!({"type":"object","required":["pid","key"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"key":{"type":"string"},"modifiers":{"type":"array","items":{"type":"string"}},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"x":{"type":"number","description":"Screenshot-pixel X — the element px action form: pixel-click there to focus, then send the key. Pass with y, no element_index."},"y":{"type":"number","description":"Screenshot-pixel Y (see x)."}},"additionalProperties":false}));+ serde_json::json!({"type":"object","required":["pid","key"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"key":{"type":"string"},"modifiers":{"type":"array","items":{"type":"string"}},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"x":{"type":"number","description":"Screenshot-pixel X — the element px action form: pixel-click there to focus, then send the key. Pass with y, no element_index."},"y":{"type":"number","description":"Screenshot-pixel Y (see x)."}},"additionalProperties":false})+);-stub_tool!(hotkey_m, HotkeyTool, "hotkey",+stub_tool!(+ hotkey_m,+ HotkeyTool,+ "hotkey","Press a combination of keys simultaneously, e.g. [\"ctrl\",\"c\"] for Copy.",- serde_json::json!({"type":"object","required":["pid","keys"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"keys":{"type":"array","items":{"type":"string"},"minItems":2},"x":{"type":"number","description":"Screenshot-pixel X — the element px action form: pixel-click there to focus, then send the combo. Pass with y."},"y":{"type":"number","description":"Screenshot-pixel Y (see x)."}},"additionalProperties":false}));+ serde_json::json!({"type":"object","required":["pid","keys"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"keys":{"type":"array","items":{"type":"string"},"minItems":2},"x":{"type":"number","description":"Screenshot-pixel X — the element px action form: pixel-click there to focus, then send the combo. Pass with y."},"y":{"type":"number","description":"Screenshot-pixel Y (see x)."}},"additionalProperties":false})+);-stub_tool!(set_value_m, SetValueTool, "set_value",+stub_tool!(+ set_value_m,+ SetValueTool,+ "set_value","Set the value of an AT-SPI element (text field, dropdown, checkbox).",- serde_json::json!({"type":"object","required":["pid","value"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"value":{"type":"string"}},"additionalProperties":false}));+ serde_json::json!({"type":"object","required":["pid","value"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"value":{"type":"string"}},"additionalProperties":false})+);stub_tool!(scroll_m, ScrollTool, "scroll","Scroll the target pid's focused region. direction required; by defaults to line, amount defaults to 3.",@@ -103,45 +158,77 @@ stub_tool!(screenshot_m, ScreenshotTool, "screenshot","Capture a screenshot. Without window_id captures the full display. Supports png and jpeg formats.",serde_json::json!({"type":"object","properties":{"window_id":{"type":"integer"},"format":{"type":"string","enum":["png","jpeg"]},"quality":{"type":"integer","minimum":1,"maximum":95}},"additionalProperties":false}));-stub_tool!(get_screen_size_m, GetScreenSizeTool, "get_screen_size",+stub_tool!(+ get_screen_size_m,+ GetScreenSizeTool,+ "get_screen_size","Return the main screen's width and height in points.",- serde_json::json!({"type":"object","properties":{},"additionalProperties":false}));+ serde_json::json!({"type":"object","properties":{},"additionalProperties":false})+);-stub_tool!(get_cursor_position_m, GetCursorPositionTool, "get_cursor_position",+stub_tool!(+ get_cursor_position_m,+ GetCursorPositionTool,+ "get_cursor_position","Return the current real mouse cursor position.",- serde_json::json!({"type":"object","properties":{},"additionalProperties":false}));+ serde_json::json!({"type":"object","properties":{},"additionalProperties":false})+);stub_tool!(cursor_motion_m, SetAgentCursorMotionTool, "set_agent_cursor_motion",format!("Configure the visual appearance of an agent cursor instance.\n\nExtended cursor customization for multi-cursor use cases:\n- cursor_id: instance name (default='default')\n- cursor_icon: built-in ({}) or a path to a PNG/JPEG/SVG/ICO file; '' reverts to the default cursor\n- cursor_color: hex color e.g. '#00FFFF' or CSS name\n- cursor_label: short text shown near the cursor\n- cursor_size: dot radius in points (default=16)\n- cursor_opacity: 0.0–1.0 (default=0.85)", cursor_overlay::BuiltinShape::names_help()),serde_json::json!({"type":"object","properties":{"cursor_id":{"type":"string"},"cursor_icon":{"type":"string"},"cursor_color":{"type":"string"},"cursor_label":{"type":"string"},"cursor_size":{"type":"number"},"cursor_opacity":{"type":"number"}},"additionalProperties":false}));-stub_tool!(get_cursor_state_m, GetAgentCursorStateTool, "get_agent_cursor_state",+stub_tool!(+ get_cursor_state_m,+ GetAgentCursorStateTool,+ "get_agent_cursor_state","Return the current state of all agent cursor instances.",- serde_json::json!({"type":"object","properties":{},"additionalProperties":false}));+ serde_json::json!({"type":"object","properties":{},"additionalProperties":false})+);-stub_tool!(set_cursor_style_m, SetAgentCursorStyleTool, "set_agent_cursor_style",+stub_tool!(+ set_cursor_style_m,+ SetAgentCursorStyleTool,+ "set_agent_cursor_style","Update the visual style of the agent cursor overlay.",- serde_json::json!({"type":"object","properties":{"cursor_id":{"type":"string"},"gradient_colors":{"type":"array","items":{"type":"string"}},"bloom_color":{"type":"string"},"image_path":{"type":"string"}},"additionalProperties":false}));+ serde_json::json!({"type":"object","properties":{"cursor_id":{"type":"string"},"gradient_colors":{"type":"array","items":{"type":"string"}},"bloom_color":{"type":"string"},"image_path":{"type":"string"}},"additionalProperties":false})+);-stub_tool!(check_perms_m, CheckPermissionsTool, "check_permissions",+stub_tool!(+ check_perms_m,+ CheckPermissionsTool,+ "check_permissions","Check required permissions.",- serde_json::json!({"type":"object","properties":{"prompt":{"type":"boolean"}},"additionalProperties":false}));+ serde_json::json!({"type":"object","properties":{"prompt":{"type":"boolean"}},"additionalProperties":false})+);-stub_tool!(get_config_m, GetConfigTool, "get_config",+stub_tool!(+ get_config_m,+ GetConfigTool,+ "get_config","Return current cua-driver-rs configuration.",- serde_json::json!({"type":"object","properties":{},"additionalProperties":false}));+ serde_json::json!({"type":"object","properties":{},"additionalProperties":false})+);-stub_tool!(set_config_m, SetConfigTool, "set_config",+stub_tool!(+ set_config_m,+ SetConfigTool,+ "set_config","Update cua-driver-rs configuration.",- serde_json::json!({"type":"object","properties":{"capture_mode":{"type":"string","enum":["ax","vision"]},"max_image_dimension":{"type":"integer"}},"additionalProperties":false}));+ serde_json::json!({"type":"object","properties":{"capture_mode":{"type":"string","enum":["ax","vision"]},"max_image_dimension":{"type":"integer"}},"additionalProperties":false})+);stub_tool!(get_ax_tree_m, GetAccessibilityTreeTool, "get_accessibility_tree","Lightweight desktop snapshot: running apps and visible windows. For per-window AT-SPI tree, use get_window_state.",serde_json::json!({"type":"object","properties":{},"additionalProperties":false}));-stub_tool!(zoom_m, ZoomTool, "zoom",+stub_tool!(+ zoom_m,+ ZoomTool,+ "zoom","Crop a window region to JPEG with 20% padding, max 500px wide.",- serde_json::json!({"type":"object","required":["window_id","x1","y1","x2","y2"],"properties":{"window_id":{"type":"integer"},"x1":{"type":"number"},"y1":{"type":"number"},"x2":{"type":"number"},"y2":{"type":"number"},"pid":{"type":"integer"}},"additionalProperties":false}));+ serde_json::json!({"type":"object","required":["window_id","x1","y1","x2","y2"],"properties":{"window_id":{"type":"integer"},"x1":{"type":"number"},"y1":{"type":"number"},"x2":{"type":"number"},"y2":{"type":"number"},"pid":{"type":"integer"}},"additionalProperties":false})+);// move_cursor and set_agent_cursor_enabled route through the overlay channel.@@ -162,13 +249,24 @@ mod move_cursor_m {}#[async_trait]impl Tool for MoveCursorTool {- fn def(&self) -> &ToolDef { Self::def_static() }+ fn def(&self) -> &ToolDef {+ Self::def_static()+ }async fn invoke(&self, args: Value) -> ToolResult {let x = args.get("x").and_then(|v| v.as_f64()).unwrap_or(0.0);let y = args.get("y").and_then(|v| v.as_f64()).unwrap_or(0.0);- let cursor_id = args.get("cursor_id").and_then(|v| v.as_str()).unwrap_or("default");- crate::overlay::send_command(cursor_overlay::OverlayCommand::MoveTo { x, y, end_heading_radians: 0.0 });- ToolResult::text(format!("Agent cursor '{cursor_id}' moved to ({x:.1}, {y:.1})."))+ let cursor_id = args+ .get("cursor_id")+ .and_then(|v| v.as_str())+ .unwrap_or("default");+ crate::overlay::send_command(cursor_overlay::OverlayCommand::MoveTo {+ x,+ y,+ end_heading_radians: 0.0,+ });+ ToolResult::text(format!(+ "Agent cursor '{cursor_id}' moved to ({x:.1}, {y:.1})."+ ))}}}@@ -190,12 +288,24 @@ mod set_enabled_m {}#[async_trait]impl Tool for SetAgentCursorEnabledTool {- fn def(&self) -> &ToolDef { Self::def_static() }+ fn def(&self) -> &ToolDef {+ Self::def_static()+ }async fn invoke(&self, args: Value) -> ToolResult {- let enabled = args.get("enabled").and_then(|v| v.as_bool()).unwrap_or(true);- let cursor_id = args.get("cursor_id").and_then(|v| v.as_str()).unwrap_or("default");+ let enabled = args+ .get("enabled")+ .and_then(|v| v.as_bool())+ .unwrap_or(true);+ let cursor_id = args+ .get("cursor_id")+ .and_then(|v| v.as_str())+ .unwrap_or("default");crate::overlay::send_command(cursor_overlay::OverlayCommand::SetEnabled(enabled));- ToolResult::text(format!("Agent cursor '{}' {}.", cursor_id, if enabled { "enabled" } else { "disabled" }))+ ToolResult::text(format!(+ "Agent cursor '{}' {}.",+ cursor_id,+ if enabled { "enabled" } else { "disabled" }+ ))}}}@@ -228,9 +338,11 @@ pub fn build_registry() -> cua_driver_core::tool::ToolRegistry {// health_report is cross-platform — the Linux provider here lets// non-Linux hosts running the stubbed registry still advertise// the documented schema_version="1" contract.- r.register(Box::new(cua_driver_core::health_report::HealthReportTool::new(- std::sync::Arc::new(crate::health_report::LinuxHealthProvider),- )));+ r.register(Box::new(+ cua_driver_core::health_report::HealthReportTool::new(std::sync::Arc::new(+ crate::health_report::LinuxHealthProvider,+ )),+ ));r.register(Box::new(GetConfigTool));r.register(Box::new(SetConfigTool));r.register(Box::new(GetAccessibilityTreeTool));diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/ext_screencopy.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/ext_screencopy.rsindex d4e313e47e..b103a21948 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/ext_screencopy.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/ext_screencopy.rs@@ -115,7 +115,9 @@ pub fn screenshot_via_ext_copy() -> anyhow::Result<Vec<u8>> {if !state.done || state.width == 0 || state.height == 0 || state.fmt.is_none() {anyhow::bail!("ext-image-copy-capture session never reported buffer specs (w={}, h={}, fmt={:?})",- state.width, state.height, state.fmt+ state.width,+ state.height,+ state.fmt);}@@ -126,9 +128,12 @@ pub fn screenshot_via_ext_copy() -> anyhow::Result<Vec<u8>> {let stride = if state.stride > 0 {state.stride} else {- state.width- .checked_mul(4)- .ok_or_else(|| anyhow::anyhow!("compositor advertised width that overflows stride: {}", state.width))?+ state.width.checked_mul(4).ok_or_else(|| {+ anyhow::anyhow!(+ "compositor advertised width that overflows stride: {}",+ state.width+ )+ })?};if stride < state.width.saturating_mul(4) {anyhow::bail!(@@ -141,7 +146,8 @@ pub fn screenshot_via_ext_copy() -> anyhow::Result<Vec<u8>> {.ok_or_else(|| {anyhow::anyhow!("compositor buffer size overflows usize: stride={} height={}",- stride, state.height+ stride,+ state.height)})?;@@ -151,7 +157,10 @@ pub fn screenshot_via_ext_copy() -> anyhow::Result<Vec<u8>> {let pool_fd = unsafe { super::borrowed_fd(fd) };let pool: WlShmPool = shm.create_pool(pool_fd.as_fd(), size as i32, &qh, ());let fmt: wl_shm::Format = wl_shm::Format::try_from(state.fmt.unwrap()).map_err(|_| {- anyhow::anyhow!("compositor advertised unsupported wl_shm format {:#x}", state.fmt.unwrap())+ anyhow::anyhow!(+ "compositor advertised unsupported wl_shm format {:#x}",+ state.fmt.unwrap()+ )})?;let buffer: WlBuffer = pool.create_buffer(0,@@ -225,11 +234,9 @@ fn encode_buffer_to_png(}}- use image::{ImageBuffer, Rgba, codecs::png::PngEncoder};- let img: ImageBuffer<Rgba<u8>, _> =- ImageBuffer::from_raw(width, height, rgba).ok_or_else(|| {- anyhow::anyhow!("internal: buffer dims mismatch ({}x{})", width, height)- })?;+ use image::{codecs::png::PngEncoder, ImageBuffer, Rgba};+ let img: ImageBuffer<Rgba<u8>, _> = ImageBuffer::from_raw(width, height, rgba)+ .ok_or_else(|| anyhow::anyhow!("internal: buffer dims mismatch ({}x{})", width, height))?;let mut out: Vec<u8> = Vec::new();use image::ImageEncoder;PngEncoder::new(&mut out).write_image(@@ -252,23 +259,34 @@ impl Dispatch<wl_registry::WlRegistry, ()> for CapState {_: &Connection,qh: &QueueHandle<Self>,) {- if let wl_registry::Event::Global { name, interface, version } = event {+ if let wl_registry::Event::Global {+ name,+ interface,+ version,+ } = event+ {match interface.as_str() {"wl_output" => {if state.output.is_none() {- state.output = Some(registry.bind::<WlOutput, _, _>(name, version.min(4), qh, ()));+ state.output =+ Some(registry.bind::<WlOutput, _, _>(name, version.min(4), qh, ()));}}"wl_shm" => {state.shm = Some(registry.bind::<WlShm, _, _>(name, 1, qh, ()));}"ext_output_image_capture_source_manager_v1" => {- state.source_mgr = Some(registry.bind::<ExtOutputImageCaptureSourceManagerV1, _, _>(- name, 1, qh, ()));+ state.source_mgr =+ Some(registry.bind::<ExtOutputImageCaptureSourceManagerV1, _, _>(+ name,+ 1,+ qh,+ (),+ ));}"ext_image_copy_capture_manager_v1" => {- state.copy_mgr = Some(registry.bind::<ExtImageCopyCaptureManagerV1, _, _>(- name, 1, qh, ()));+ state.copy_mgr =+ Some(registry.bind::<ExtImageCopyCaptureManagerV1, _, _>(name, 1, qh, ()));}_ => {}}@@ -277,25 +295,81 @@ impl Dispatch<wl_registry::WlRegistry, ()> for CapState {}impl Dispatch<WlOutput, ()> for CapState {- fn event(_: &mut Self, _: &WlOutput, _: <WlOutput as Proxy>::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) {}+ fn event(+ _: &mut Self,+ _: &WlOutput,+ _: <WlOutput as Proxy>::Event,+ _: &(),+ _: &Connection,+ _: &QueueHandle<Self>,+ ) {+ }}impl Dispatch<WlShm, ()> for CapState {- fn event(_: &mut Self, _: &WlShm, _: <WlShm as Proxy>::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) {}+ fn event(+ _: &mut Self,+ _: &WlShm,+ _: <WlShm as Proxy>::Event,+ _: &(),+ _: &Connection,+ _: &QueueHandle<Self>,+ ) {+ }}impl Dispatch<WlShmPool, ()> for CapState {- fn event(_: &mut Self, _: &WlShmPool, _: <WlShmPool as Proxy>::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) {}+ fn event(+ _: &mut Self,+ _: &WlShmPool,+ _: <WlShmPool as Proxy>::Event,+ _: &(),+ _: &Connection,+ _: &QueueHandle<Self>,+ ) {+ }}impl Dispatch<WlBuffer, ()> for CapState {- fn event(_: &mut Self, _: &WlBuffer, _: <WlBuffer as Proxy>::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) {}+ fn event(+ _: &mut Self,+ _: &WlBuffer,+ _: <WlBuffer as Proxy>::Event,+ _: &(),+ _: &Connection,+ _: &QueueHandle<Self>,+ ) {+ }}impl Dispatch<ExtOutputImageCaptureSourceManagerV1, ()> for CapState {- fn event(_: &mut Self, _: &ExtOutputImageCaptureSourceManagerV1, _: <ExtOutputImageCaptureSourceManagerV1 as Proxy>::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) {}+ fn event(+ _: &mut Self,+ _: &ExtOutputImageCaptureSourceManagerV1,+ _: <ExtOutputImageCaptureSourceManagerV1 as Proxy>::Event,+ _: &(),+ _: &Connection,+ _: &QueueHandle<Self>,+ ) {+ }}impl Dispatch<ExtImageCaptureSourceV1, ()> for CapState {- fn event(_: &mut Self, _: &ExtImageCaptureSourceV1, _: <ExtImageCaptureSourceV1 as Proxy>::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) {}+ fn event(+ _: &mut Self,+ _: &ExtImageCaptureSourceV1,+ _: <ExtImageCaptureSourceV1 as Proxy>::Event,+ _: &(),+ _: &Connection,+ _: &QueueHandle<Self>,+ ) {+ }}impl Dispatch<ExtImageCopyCaptureManagerV1, ()> for CapState {- fn event(_: &mut Self, _: &ExtImageCopyCaptureManagerV1, _: <ExtImageCopyCaptureManagerV1 as Proxy>::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) {}+ fn event(+ _: &mut Self,+ _: &ExtImageCopyCaptureManagerV1,+ _: <ExtImageCopyCaptureManagerV1 as Proxy>::Event,+ _: &(),+ _: &Connection,+ _: &QueueHandle<Self>,+ ) {+ }}impl Dispatch<ExtImageCopyCaptureSessionV1, ()> for CapState {fn event(diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/libei.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/libei.rsindex 745c0732f4..3eec5d6af2 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/libei.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/libei.rs@@ -50,9 +50,9 @@ pub enum Button {impl Button {fn to_evdev(self) -> u32 {match self {- Button::Left => 0x110, // BTN_LEFT- Button::Right => 0x111, // BTN_RIGHT- Button::Middle => 0x112, // BTN_MIDDLE+ Button::Left => 0x110, // BTN_LEFT+ Button::Right => 0x111, // BTN_RIGHT+ Button::Middle => 0x112, // BTN_MIDDLE}}}@@ -146,7 +146,8 @@ enum Cmd {static TX: OnceLock<Sender<Cmd>> = OnceLock::new();fn tx() -> anyhow::Result<&'static Sender<Cmd>> {- TX.get().ok_or_else(|| anyhow::anyhow!("libei worker not started; call ensure_started() first"))+ TX.get()+ .ok_or_else(|| anyhow::anyhow!("libei worker not started; call ensure_started() first"))}fn wait_for_reply(rx: Receiver<anyhow::Result<()>>) -> anyhow::Result<()> {@@ -168,7 +169,10 @@ fn restore_token_path() -> Option<PathBuf> {fn read_restore_token() -> Option<String> {let path = restore_token_path()?;- std::fs::read_to_string(path).ok().map(|s| s.trim().to_string()).filter(|s| !s.is_empty())+ std::fs::read_to_string(path)+ .ok()+ .map(|s| s.trim().to_string())+ .filter(|s| !s.is_empty())}fn write_restore_token(token: &str) -> anyhow::Result<()> {@@ -176,7 +180,10 @@ fn write_restore_token(token: &str) -> anyhow::Result<()> {.ok_or_else(|| anyhow::anyhow!("no config dir available for libei restore_token"))?;if let Some(parent) = path.parent() {std::fs::create_dir_all(parent).map_err(|e| {- anyhow::anyhow!("failed to create {} for restore_token: {e}", parent.display())+ anyhow::anyhow!(+ "failed to create {} for restore_token: {e}",+ parent.display()+ )})?;}use std::io::Write;@@ -189,10 +196,16 @@ fn write_restore_token(token: &str) -> anyhow::Result<()> {.mode(0o600).open(&path).map_err(|e| {- anyhow::anyhow!("failed to open libei restore_token at {}: {e}", path.display())+ anyhow::anyhow!(+ "failed to open libei restore_token at {}: {e}",+ path.display()+ )})?;file.write_all(token.as_bytes()).map_err(|e| {- anyhow::anyhow!("failed to write libei restore_token to {}: {e}", path.display())+ anyhow::anyhow!(+ "failed to write libei restore_token to {}: {e}",+ path.display()+ )})}@@ -250,7 +263,13 @@ pub fn wait_keyboard_ready() -> anyhow::Result<()> {pub fn click(x: f64, y: f64, button: Button) -> anyhow::Result<()> {ensure_started()?;let (tx_r, rx_r) = bounded(1);- tx()?.send(Cmd::Click { x, y, button, reply: tx_r })+ tx()?+ .send(Cmd::Click {+ x,+ y,+ button,+ reply: tx_r,+ }).map_err(|e| anyhow::anyhow!("libei worker channel closed: {e}"))?;wait_for_reply(rx_r)}@@ -260,7 +279,8 @@ pub fn click(x: f64, y: f64, button: Button) -> anyhow::Result<()> {pub fn move_absolute(x: f64, y: f64) -> anyhow::Result<()> {ensure_started()?;let (tx_r, rx_r) = bounded(1);- tx()?.send(Cmd::MoveAbsolute { x, y, reply: tx_r })+ tx()?+ .send(Cmd::MoveAbsolute { x, y, reply: tx_r }).map_err(|e| anyhow::anyhow!("libei worker channel closed: {e}"))?;wait_for_reply(rx_r)}@@ -269,7 +289,12 @@ pub fn move_absolute(x: f64, y: f64) -> anyhow::Result<()> {pub fn scroll(dx: f64, dy: f64) -> anyhow::Result<()> {ensure_started()?;let (tx_r, rx_r) = bounded(1);- tx()?.send(Cmd::Scroll { dx, dy, reply: tx_r })+ tx()?+ .send(Cmd::Scroll {+ dx,+ dy,+ reply: tx_r,+ }).map_err(|e| anyhow::anyhow!("libei worker channel closed: {e}"))?;wait_for_reply(rx_r)}@@ -279,7 +304,11 @@ pub fn scroll(dx: f64, dy: f64) -> anyhow::Result<()> {pub fn type_text(text: &str) -> anyhow::Result<()> {ensure_started()?;let (tx_r, rx_r) = bounded(1);- tx()?.send(Cmd::TypeText { text: text.to_string(), reply: tx_r })+ tx()?+ .send(Cmd::TypeText {+ text: text.to_string(),+ reply: tx_r,+ }).map_err(|e| anyhow::anyhow!("libei worker channel closed: {e}"))?;wait_for_reply(rx_r)}@@ -289,7 +318,11 @@ pub fn type_text(text: &str) -> anyhow::Result<()> {pub fn press_key(keycode: u32) -> anyhow::Result<()> {ensure_started()?;let (tx_r, rx_r) = bounded(1);- tx()?.send(Cmd::PressKey { keycode, reply: tx_r })+ tx()?+ .send(Cmd::PressKey {+ keycode,+ reply: tx_r,+ }).map_err(|e| anyhow::anyhow!("libei worker channel closed: {e}"))?;wait_for_reply(rx_r)}@@ -398,8 +431,8 @@ enum PortalKeepAlive {fn worker(rx: Receiver<Cmd>) -> anyhow::Result<()> {// Phase 1 — acquire an EIS context (plus, on the portal path, a keep-alive// that owns the ashpd RemoteDesktop session + its tokio runtime).- let (context, _portal_keepalive) = open_eis_context()- .map_err(|e| anyhow::anyhow!("failed to obtain EIS connection: {e}"))?;+ let (context, _portal_keepalive) =+ open_eis_context().map_err(|e| anyhow::anyhow!("failed to obtain EIS connection: {e}"))?;// Phase 2 — handshake. The reis API requires we call context.handshake()// and flush before the event loop starts polling.@@ -494,7 +527,14 @@ fn open_eis_context() -> anyhow::Result<(reis::ei::Context, PortalKeepAlive)> {let stream = UnixStream::from(fd);let ctx = reis::ei::Context::new(stream).map_err(|e| anyhow::anyhow!("reis ei::Context::new failed: {e}"))?;- Ok((ctx, PortalKeepAlive::Portal { _rt: rt, _proxy: proxy, _session: session }))+ Ok((+ ctx,+ PortalKeepAlive::Portal {+ _rt: rt,+ _proxy: proxy,+ _session: session,+ },+ ))}// ── calloop dispatch ────────────────────────────────────────────────────@@ -751,9 +791,16 @@ impl EisState {data.device_type = Some(device_type);}reis::ei::device::Event::Interface { object } => {- data.interfaces.insert(object.interface().to_owned(), object);+ data.interfaces+ .insert(object.interface().to_owned(), object);}- reis::ei::device::Event::Region { offset_x, offset_y, width, hight, scale: _ } => {+ reis::ei::device::Event::Region {+ offset_x,+ offset_y,+ width,+ hight,+ scale: _,+ } => {// reis 0.7 keeps the misspelled "hight" field name// for ABI compatibility — see the protocol comment.if width > 0 && hight > 0 {@@ -868,8 +915,7 @@ impl EisState {/// run before their device exists fail with "no EIS device negotiated yet",/// so `run_calloop` queues them until this holds (or READY_TIMEOUT elapses).fn cmd_ready(&self, cmd: &Cmd) -> bool {- const DEVICE_QUIET_PERIOD: std::time::Duration =- std::time::Duration::from_millis(200);+ const DEVICE_QUIET_PERIOD: std::time::Duration = std::time::Duration::from_millis(200);if self.last_device_event.is_none_or(|last| last.elapsed() < DEVICE_QUIET_PERIOD)@@ -897,14 +943,30 @@ impl EisState {let result = self.run_command(&cmd);// Send the reply on whichever channel this command carries.match cmd {- Cmd::WaitReady { reply, .. } => { let _ = reply.send(result); }- Cmd::Click { reply, .. } => { let _ = reply.send(result); }- Cmd::MoveAbsolute { reply, .. } => { let _ = reply.send(result); }- Cmd::Scroll { reply, .. } => { let _ = reply.send(result); }- Cmd::TypeText { reply, .. } => { let _ = reply.send(result); }- Cmd::PressKey { reply, .. } => { let _ = reply.send(result); }- Cmd::KeySequence { reply, .. } => { let _ = reply.send(result); }- Cmd::Drag { reply, .. } => { let _ = reply.send(result); }+ Cmd::WaitReady { reply, .. } => {+ let _ = reply.send(result);+ }+ Cmd::Click { reply, .. } => {+ let _ = reply.send(result);+ }+ Cmd::MoveAbsolute { reply, .. } => {+ let _ = reply.send(result);+ }+ Cmd::Scroll { reply, .. } => {+ let _ = reply.send(result);+ }+ Cmd::TypeText { reply, .. } => {+ let _ = reply.send(result);+ }+ Cmd::PressKey { reply, .. } => {+ let _ = reply.send(result);+ }+ Cmd::KeySequence { reply, .. } => {+ let _ = reply.send(result);+ }+ Cmd::Drag { reply, .. } => {+ let _ = reply.send(result);+ }Cmd::Shutdown => {}}}@@ -919,7 +981,8 @@ impl EisState {Cmd::Click { x, y, button, .. } => {let (device, rel_x, rel_y) = self.pointer_device_for(*x, *y)?;let serial = self.last_serial;- let ptr_abs = require_device_interface::<reis::ei::PointerAbsolute>(&self.devices, &device)?;+ let ptr_abs =+ require_device_interface::<reis::ei::PointerAbsolute>(&self.devices, &device)?;let btn = require_device_interface::<reis::ei::Button>(&self.devices, &device)?;ptr_abs.motion_absolute(rel_x, rel_y);@@ -949,11 +1012,12 @@ impl EisState {// correct only within one region, but avoids the cross-monitor// mis-mapping of blindly reusing the start offset.let (to_rx, to_ry) =- self.region_local_on(&device, *to_x, *to_y).unwrap_or_else(|| {- let off_x = *from_x as f32 - from_rx;- let off_y = *from_y as f32 - from_ry;- (*to_x as f32 - off_x, *to_y as f32 - off_y)- });+ self.region_local_on(&device, *to_x, *to_y)+ .unwrap_or_else(|| {+ let off_x = *from_x as f32 - from_rx;+ let off_y = *from_y as f32 - from_ry;+ (*to_x as f32 - off_x, *to_y as f32 - off_y)+ });ptr_abs.motion_absolute(from_rx, from_ry);device.frame(serial, event_time_us());@@ -976,14 +1040,16 @@ impl EisState {Cmd::MoveAbsolute { x, y, .. } => {let (device, rel_x, rel_y) = self.pointer_device_for(*x, *y)?;let serial = self.last_serial;- let ptr_abs = require_device_interface::<reis::ei::PointerAbsolute>(&self.devices, &device)?;+ let ptr_abs =+ require_device_interface::<reis::ei::PointerAbsolute>(&self.devices, &device)?;ptr_abs.motion_absolute(rel_x, rel_y);device.frame(serial, event_time_us());}Cmd::Scroll { dx, dy, .. } => {- let device = self.device_with_interface("ei_scroll")- .ok_or_else(|| anyhow::anyhow!("no EIS scroll device negotiated yet — wait for handshake"))?;+ let device = self.device_with_interface("ei_scroll").ok_or_else(|| {+ anyhow::anyhow!("no EIS scroll device negotiated yet — wait for handshake")+ })?;let serial = self.last_serial;let scroll = require_device_interface::<reis::ei::Scroll>(&self.devices, &device)?;@@ -999,16 +1065,20 @@ impl EisState {// support needs an xkb keymap, like reis's type-text example).if let Some(device) = self.device_with_interface("ei_text") {let serial = self.last_serial;- let text_iface = require_device_interface::<reis::ei::Text>(&self.devices, &device)?;+ let text_iface =+ require_device_interface::<reis::ei::Text>(&self.devices, &device)?;text_iface.utf8(text);device.frame(serial, event_time_us());} else {use reis::ei::keyboard::KeyState;let device = self.device_with_interface("ei_keyboard").ok_or_else(|| {- anyhow::anyhow!("no EIS keyboard device negotiated yet — wait for handshake")+ anyhow::anyhow!(+ "no EIS keyboard device negotiated yet — wait for handshake"+ )})?;let serial = self.last_serial;- let kb = require_device_interface::<reis::ei::Keyboard>(&self.devices, &device)?;+ let kb =+ require_device_interface::<reis::ei::Keyboard>(&self.devices, &device)?;let shift_code = self.keymap_shift.unwrap_or(42);let mut skipped = 0usize;for ch in text.chars() {@@ -1049,8 +1119,9 @@ impl EisState {}}Cmd::PressKey { keycode, .. } => {- let device = self.device_with_interface("ei_keyboard")- .ok_or_else(|| anyhow::anyhow!("no EIS keyboard device negotiated yet — wait for handshake"))?;+ let device = self.device_with_interface("ei_keyboard").ok_or_else(|| {+ anyhow::anyhow!("no EIS keyboard device negotiated yet — wait for handshake")+ })?;let serial = self.last_serial;let kb = require_device_interface::<reis::ei::Keyboard>(&self.devices, &device)?;@@ -1060,8 +1131,9 @@ impl EisState {device.frame(serial, event_time_us());}Cmd::KeySequence { transitions, .. } => {- let device = self.device_with_interface("ei_keyboard")- .ok_or_else(|| anyhow::anyhow!("no EIS keyboard device negotiated yet — wait for handshake"))?;+ let device = self.device_with_interface("ei_keyboard").ok_or_else(|| {+ anyhow::anyhow!("no EIS keyboard device negotiated yet — wait for handshake")+ })?;let serial = self.last_serial;let kb = require_device_interface::<reis::ei::Keyboard>(&self.devices, &device)?;@@ -1115,8 +1187,13 @@ impl EisState {}}// Fallback: first absolute-pointer device, raw coords (single-region).- let device = self.device_with_interface("ei_pointer_absolute")- .ok_or_else(|| anyhow::anyhow!("no EIS absolute-pointer device negotiated yet — wait for handshake"))?;+ let device = self+ .device_with_interface("ei_pointer_absolute")+ .ok_or_else(|| {+ anyhow::anyhow!(+ "no EIS absolute-pointer device negotiated yet — wait for handshake"+ )+ })?;Ok((device, x as f32, y as f32))}@@ -1126,9 +1203,10 @@ impl EisState {/// resolved to (a single EIS emulation session can't span devices).fn region_local_on(&self, device: &reis::ei::Device, x: f64, y: f64) -> Option<(f32, f32)> {let data = self.devices.get(device)?;- data.regions.iter().find(|r| r.contains(x, y)).map(|r| {- (x as f32 - r.offset_x, y as f32 - r.offset_y)- })+ data.regions+ .iter()+ .find(|r| r.contains(x, y))+ .map(|r| (x as f32 - r.offset_x, y as f32 - r.offset_y))}/// The negotiated device that exposes `iface` (e.g. `ei_pointer_absolute`,@@ -1140,13 +1218,10 @@ impl EisState {fn device_with_interface(&self, iface: &str) -> Option<reis::ei::Device> {self.devices.iter()- .filter(|(_, data)| {- data.resumed && data.interfaces.contains_key(iface)- })+ .filter(|(_, data)| data.resumed && data.interfaces.contains_key(iface)).max_by_key(|(_, data)| data.resumed_serial.unwrap_or(0)).map(|(d, _)| d.clone())}-}/// Map a character to a US-layout evdev keycode + whether Shift is needed.@@ -1254,7 +1329,8 @@ fn device_interface<T: reis::Interface>(devices: &HashMap<reis::ei::Device, DeviceData>,device: &reis::ei::Device,) -> Option<T> {- devices.get(device)?+ devices+ .get(device)?.interfaces.get(T::NAME)?.clone()diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rsindex fcaa88e8c3..cb040f39d1 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rs@@ -1437,12 +1437,7 @@ pub fn scroll_at(}/// Scroll at a desktop-absolute point without activating a named toplevel.-pub fn scroll_desktop(- x: i32,- y: i32,- direction: &str,- amount: u32,-) -> anyhow::Result<()> {+pub fn scroll_desktop(x: i32, y: i32, direction: &str, amount: u32) -> anyhow::Result<()> {let direction = direction.to_string();with_libei_fallback(|| scroll_vptr(None, Some((x, y)), &direction, amount),diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/portal_screencast.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/portal_screencast.rsindex cba0dd6c00..14f1712dce 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/portal_screencast.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/portal_screencast.rs@@ -25,8 +25,8 @@ use std::os::fd::AsRawFd;use std::sync::OnceLock;use ashpd::desktop::screencast::{- CursorMode, OpenPipeWireRemoteOptions, Screencast,- SelectSourcesOptions, SourceType, StartCastOptions, Streams,+ CursorMode, OpenPipeWireRemoteOptions, Screencast, SelectSourcesOptions, SourceType,+ StartCastOptions, Streams,};use ashpd::desktop::{CreateSessionOptions, PersistMode, Session};use ashpd::enumflags2::BitFlags;@@ -222,7 +222,12 @@ fn capture_one_frame(pipewire_fd: i32, node_id: u32) -> anyhow::Result<Vec<u8>>.process(move |stream, _user| {// Already captured? Drop further buffers (they'll be queued// back via Buffer::Drop) so the run loop can finish.- if frame_for_process.lock().ok().map(|g| g.is_some()).unwrap_or(false) {+ if frame_for_process+ .lock()+ .ok()+ .map(|g| g.is_some())+ .unwrap_or(false)+ {let _ = stream.dequeue_buffer();return;}@@ -312,9 +317,18 @@ fn capture_one_frame(pipewire_fd: i32, node_id: u32) -> anyhow::Result<Vec<u8>>Choice,Range,Rectangle,- pw::spa::utils::Rectangle { width: 1920, height: 1080 },- pw::spa::utils::Rectangle { width: 1, height: 1 },- pw::spa::utils::Rectangle { width: 7680, height: 4320 }+ pw::spa::utils::Rectangle {+ width: 1920,+ height: 1080+ },+ pw::spa::utils::Rectangle {+ width: 1,+ height: 1+ },+ pw::spa::utils::Rectangle {+ width: 7680,+ height: 4320+ }),pw::spa::pod::property!(pw::spa::param::format::FormatProperties::VideoFramerate,@@ -323,7 +337,10 @@ fn capture_one_frame(pipewire_fd: i32, node_id: u32) -> anyhow::Result<Vec<u8>>Fraction,pw::spa::utils::Fraction { num: 30, denom: 1 },pw::spa::utils::Fraction { num: 0, denom: 1 },- pw::spa::utils::Fraction { num: 1000, denom: 1 }+ pw::spa::utils::Fraction {+ num: 1000,+ denom: 1+ }),);let values: Vec<u8> = pw::spa::pod::serialize::PodSerializer::serialize(@@ -370,7 +387,13 @@ fn capture_one_frame(pipewire_fd: i32, node_id: u32) -> anyhow::Result<Vec<u8>>.take().ok_or_else(|| anyhow::anyhow!("portal ScreenCast: no frame arrived within timeout"))?;- encode_frame_to_png(&frame.bytes, frame.width, frame.height, frame.stride, frame.format)+ encode_frame_to_png(+ &frame.bytes,+ frame.width,+ frame.height,+ frame.stride,+ frame.format,+ )}/// Channel-swap a PipeWire video frame into RGBA8888 and PNG-encode it.@@ -404,10 +427,8 @@ fn encode_frame_to_png(}}use image::{codecs::png::PngEncoder, ImageBuffer, ImageEncoder, Rgba};- let img: ImageBuffer<Rgba<u8>, _> =- ImageBuffer::from_raw(width, height, rgba).ok_or_else(|| {- anyhow::anyhow!("internal: buffer dims mismatch ({}x{})", width, height)- })?;+ let img: ImageBuffer<Rgba<u8>, _> = ImageBuffer::from_raw(width, height, rgba)+ .ok_or_else(|| anyhow::anyhow!("internal: buffer dims mismatch ({}x{})", width, height))?;let mut out: Vec<u8> = Vec::new();PngEncoder::new(&mut out).write_image(img.as_raw(),diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/portal_screenshot.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/portal_screenshot.rsindex 887b4f8dac..0ccf4df24b 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/portal_screenshot.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/portal_screenshot.rs@@ -86,7 +86,9 @@ fn map_ashpd_err<E: std::fmt::Display>(e: E) -> anyhow::Error {if msg.contains("ServiceUnknown") || msg.contains("NotFound") {anyhow::anyhow!("xdg-desktop-portal is not running on this session ({msg}). Install xdg-desktop-portal-gnome / xdg-desktop-portal-kde / xdg-desktop-portal-wlr for your compositor.")} else if msg.contains("Cancelled") || msg.contains("denied") {- anyhow::anyhow!("xdg-desktop-portal Screenshot consent dialog was cancelled or denied: {msg}")+ anyhow::anyhow!(+ "xdg-desktop-portal Screenshot consent dialog was cancelled or denied: {msg}"+ )} else {anyhow::anyhow!(msg)}@@ -124,8 +126,11 @@ pub fn probe_portal() -> anyhow::Result<bool> {.await.map_err(|e| anyhow::anyhow!("dbus proxy creation failed: {e}"))?;let has_owner = proxy- .name_has_owner("org.freedesktop.portal.Desktop".try_into()- .map_err(|e| anyhow::anyhow!("bus name parse failed: {e}"))?)+ .name_has_owner(+ "org.freedesktop.portal.Desktop"+ .try_into()+ .map_err(|e| anyhow::anyhow!("bus name parse failed: {e}"))?,+ ).await.map_err(|e| anyhow::anyhow!("name_has_owner failed: {e}"))?;Ok(has_owner)diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/virtual_keyboard.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/virtual_keyboard.rsindex 50e8b7ee0f..5a57436ace 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/virtual_keyboard.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/virtual_keyboard.rs@@ -115,9 +115,10 @@ pub(super) fn hotkey(modifiers: &[String], key: &str) -> anyhow::Result<()> {.seat.clone().ok_or_else(|| anyhow::anyhow!("compositor exposes no wl_seat"))?;- let manager = state.manager.clone().ok_or_else(|| {- anyhow::anyhow!("compositor exposes no zwp_virtual_keyboard_manager_v1")- })?;+ let manager = state+ .manager+ .clone()+ .ok_or_else(|| anyhow::anyhow!("compositor exposes no zwp_virtual_keyboard_manager_v1"))?;let keyboard = manager.create_virtual_keyboard(&seat, &qh, ());let keymap = keymap_file()?;keyboard.keymap(1, keymap.as_fd(), XKB_KEYMAP.len() as u32 + 1);@@ -234,12 +235,36 @@ mod tests {assert_eq!(hotkey_transitions(&["ctrl".into(), "shift".into()], "7").unwrap(),[- KeyTransition { keycode: 29, pressed: true, modifier_mask: 4 },- KeyTransition { keycode: 42, pressed: true, modifier_mask: 5 },- KeyTransition { keycode: 8, pressed: true, modifier_mask: 5 },- KeyTransition { keycode: 8, pressed: false, modifier_mask: 5 },- KeyTransition { keycode: 42, pressed: false, modifier_mask: 4 },- KeyTransition { keycode: 29, pressed: false, modifier_mask: 0 },+ KeyTransition {+ keycode: 29,+ pressed: true,+ modifier_mask: 4+ },+ KeyTransition {+ keycode: 42,+ pressed: true,+ modifier_mask: 5+ },+ KeyTransition {+ keycode: 8,+ pressed: true,+ modifier_mask: 5+ },+ KeyTransition {+ keycode: 8,+ pressed: false,+ modifier_mask: 5+ },+ KeyTransition {+ keycode: 42,+ pressed: false,+ modifier_mask: 4+ },+ KeyTransition {+ keycode: 29,+ pressed: false,+ modifier_mask: 0+ },]);}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/x11/mod.rs b/libs/cua-driver/rust/crates/platform-linux/src/x11/mod.rsindex d13de7967b..2bb7accfcb 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/x11/mod.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/x11/mod.rs@@ -43,11 +43,15 @@ fn list_windows_inner(filter_pid: Option<u32>) -> Result<Vec<WindowInfo>> {for (z_index, xid) in windows.into_iter().enumerate() {let pid = get_window_pid(&conn, xid).ok().flatten();if let Some(fp) = filter_pid {- if pid != Some(fp) { continue; }+ if pid != Some(fp) {+ continue;+ }}let title = get_window_title(&conn, xid).unwrap_or_default();- if title.trim().is_empty() { continue; }+ if title.trim().is_empty() {+ continue;+ }let app_name = get_window_class(&conn, xid).map(|(instance, class)| if class.is_empty() { instance } else { class }).unwrap_or_default();@@ -61,7 +65,9 @@ fn list_windows_inner(filter_pid: Option<u32>) -> Result<Vec<WindowInfo>> {let (x, y, w, h) = if let Some(g) = geom {// Translate to root coordinates.let trans = conn.translate_coordinates(xid, root, 0, 0)?.reply().ok();- let (rx, ry) = trans.map(|t| (t.dst_x as i32, t.dst_y as i32)).unwrap_or((0, 0));+ let (rx, ry) = trans+ .map(|t| (t.dst_x as i32, t.dst_y as i32))+ .unwrap_or((0, 0));(rx, ry, g.width as u32, g.height as u32)} else {(0, 0, 0, 0)@@ -88,8 +94,12 @@ fn get_window_list(conn: &RustConnection, root: Window) -> Result<Vec<Window>> {let atom_names = ["_NET_CLIENT_LIST_STACKING", "_NET_CLIENT_LIST"];for name in &atom_names {if let Ok(atom) = get_atom(conn, name) {- if let Ok(reply) = conn.get_property(false, root, atom, AtomEnum::WINDOW, 0, u32::MAX)?.reply() {- let windows: Vec<Window> = reply.value32()+ if let Ok(reply) = conn+ .get_property(false, root, atom, AtomEnum::WINDOW, 0, u32::MAX)?+ .reply()+ {+ let windows: Vec<Window> = reply+ .value32().map(|iter| iter.collect()).unwrap_or_default();if client_list_property(reply.type_, windows.as_slice()).is_some() {@@ -130,7 +140,9 @@ fn get_atom(conn: &RustConnection, name: &str) -> Result<Atom> {fn get_window_pid(conn: &RustConnection, window: Window) -> Result<Option<u32>> {let atom = get_atom(conn, "_NET_WM_PID")?;- let reply = conn.get_property(false, window, atom, AtomEnum::CARDINAL, 0, 1)?.reply()?;+ let reply = conn+ .get_property(false, window, atom, AtomEnum::CARDINAL, 0, 1)?+ .reply()?;Ok(reply.value32().and_then(|mut i| i.next()))}@@ -138,7 +150,10 @@ fn get_window_title(conn: &RustConnection, window: Window) -> Result<String> {// Try _NET_WM_NAME (UTF-8) first.if let Ok(atom) = get_atom(conn, "_NET_WM_NAME") {if let Ok(utf8_atom) = get_atom(conn, "UTF8_STRING") {- if let Ok(reply) = conn.get_property(false, window, atom, utf8_atom, 0, 1024)?.reply() {+ if let Ok(reply) = conn+ .get_property(false, window, atom, utf8_atom, 0, 1024)?+ .reply()+ {if !reply.value.is_empty() {return Ok(String::from_utf8_lossy(&reply.value).into_owned());}@@ -146,7 +161,9 @@ fn get_window_title(conn: &RustConnection, window: Window) -> Result<String> {}}// Fallback: WM_NAME (latin-1 / ASCII).- let reply = conn.get_property(false, window, AtomEnum::WM_NAME, AtomEnum::STRING, 0, 1024)?.reply()?;+ let reply = conn+ .get_property(false, window, AtomEnum::WM_NAME, AtomEnum::STRING, 0, 1024)?+ .reply()?;Ok(String::from_utf8_lossy(&reply.value).into_owned())}@@ -167,14 +184,27 @@ pub fn wm_class_for_window(xid: u64) -> Option<(String, String)> {fn get_window_class(conn: &RustConnection, xid: Window) -> Option<(String, String)> {let reply = conn- .get_property(false, xid as u32, AtomEnum::WM_CLASS, AtomEnum::STRING, 0, 512)+ .get_property(+ false,+ xid as u32,+ AtomEnum::WM_CLASS,+ AtomEnum::STRING,+ 0,+ 512,+ ).ok()?.reply().ok()?;let raw = reply.value;let mut parts = raw.split(|&b| b == 0).filter(|s| !s.is_empty());- let instance = parts.next().map(|s| String::from_utf8_lossy(s).into_owned()).unwrap_or_default();- let class = parts.next().map(|s| String::from_utf8_lossy(s).into_owned()).unwrap_or_default();+ let instance = parts+ .next()+ .map(|s| String::from_utf8_lossy(s).into_owned())+ .unwrap_or_default();+ let class = parts+ .next()+ .map(|s| String::from_utf8_lossy(s).into_owned())+ .unwrap_or_default();if instance.is_empty() && class.is_empty() {return None;}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/apps/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/apps/mod.rsindex edf86c35e6..4e1f019d2e 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/apps/mod.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/apps/mod.rs@@ -2,8 +2,8 @@pub mod nsworkspace;-use std::process::Command;use serde::{Deserialize, Serialize};+use std::process::Command;#[derive(Debug, Clone, Serialize, Deserialize)]pub struct AppInfo {@@ -332,8 +332,13 @@ pub fn list_all_apps() -> Vec<AppInfo> {let installed = scan_installed_apps();// Lookup: bundle_id → (launch_path, last_used) from the installed scan.let installed_by_bundle: std::collections::HashMap<String, (Option<String>, Option<String>)> =- installed.iter()- .filter_map(|a| a.bundle_id.clone().map(|b| (b, (a.launch_path.clone(), a.last_used.clone()))))+ installed+ .iter()+ .filter_map(|a| {+ a.bundle_id+ .clone()+ .map(|b| (b, (a.launch_path.clone(), a.last_used.clone())))+ }).collect();// Backfill running entries with the launch_path the installed scan resolved.for app in running.iter_mut() {@@ -349,13 +354,16 @@ pub fn list_all_apps() -> Vec<AppInfo> {}}- let running_bundles: std::collections::HashSet<String> = running.iter()- .filter_map(|a| a.bundle_id.clone())- .collect();+ let running_bundles: std::collections::HashSet<String> =+ running.iter().filter_map(|a| a.bundle_id.clone()).collect();let mut installed = installed;// Remove apps already in running list.- installed.retain(|a| !a.bundle_id.as_ref().map_or(false, |b| running_bundles.contains(b)));+ installed.retain(|a| {+ !a.bundle_id+ .as_ref()+ .map_or(false, |b| running_bundles.contains(b))+ });let mut all = running;all.extend(installed);@@ -378,10 +386,14 @@ fn scan_installed_apps() -> Vec<AppInfo> {all_dirs.push(user_apps_str);for dir in all_dirs {- let Ok(entries) = std::fs::read_dir(dir) else { continue };+ let Ok(entries) = std::fs::read_dir(dir) else {+ continue;+ };for entry in entries.flatten() {let path = entry.path();- if path.extension().and_then(|e| e.to_str()) != Some("app") { continue }+ if path.extension().and_then(|e| e.to_str()) != Some("app") {+ continue;+ }let plist_path = path.join("Contents/Info.plist");if let Some(mut info) = read_app_plist(&plist_path) {info.launch_path = path.to_str().map(str::to_owned);@@ -435,17 +447,37 @@ pub(crate) fn unix_secs_to_rfc3339(secs: i64) -> String {fn read_app_plist(plist_path: &std::path::Path) -> Option<AppInfo> {let bundle_id_out = Command::new("plutil")- .args(["-extract", "CFBundleIdentifier", "raw", "-o", "-",- plist_path.to_str()?])- .output().ok()?;- if !bundle_id_out.status.success() { return None; }- let bundle_id = String::from_utf8_lossy(&bundle_id_out.stdout).trim().to_string();- if bundle_id.is_empty() { return None; }+ .args([+ "-extract",+ "CFBundleIdentifier",+ "raw",+ "-o",+ "-",+ plist_path.to_str()?,+ ])+ .output()+ .ok()?;+ if !bundle_id_out.status.success() {+ return None;+ }+ let bundle_id = String::from_utf8_lossy(&bundle_id_out.stdout)+ .trim()+ .to_string();+ if bundle_id.is_empty() {+ return None;+ }let name_out = Command::new("plutil")- .args(["-extract", "CFBundleDisplayName", "raw", "-o", "-",- plist_path.to_str()?])- .output().ok();+ .args([+ "-extract",+ "CFBundleDisplayName",+ "raw",+ "-o",+ "-",+ plist_path.to_str()?,+ ])+ .output()+ .ok();let name = name_out.filter(|o| o.status.success()).map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())@@ -453,14 +485,22 @@ fn read_app_plist(plist_path: &std::path::Path) -> Option<AppInfo> {.unwrap_or_else(|| {// Fallback: CFBundleName.Command::new("plutil")- .args(["-extract", "CFBundleName", "raw", "-o", "-",- plist_path.to_str().unwrap_or("")])- .output().ok()+ .args([+ "-extract",+ "CFBundleName",+ "raw",+ "-o",+ "-",+ plist_path.to_str().unwrap_or(""),+ ])+ .output()+ .ok().filter(|o| o.status.success()).map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()).filter(|s| !s.is_empty()).unwrap_or_else(|| {- plist_path.parent()+ plist_path+ .parent().and_then(|p| p.parent()).and_then(|p| p.file_stem()).and_then(|s| s.to_str())@@ -469,7 +509,9 @@ fn read_app_plist(plist_path: &std::path::Path) -> Option<AppInfo> {})});- if name.is_empty() { return None; }+ if name.is_empty() {+ return None;+ }Some(AppInfo {name,@@ -565,7 +607,11 @@ pub fn format_app_list(apps: &[AppInfo]) -> String {total - running.len())];for app in &running {- let bundle = app.bundle_id.as_deref().map(|b| format!(" [{b}]")).unwrap_or_default();+ let bundle = app+ .bundle_id+ .as_deref()+ .map(|b| format!(" [{b}]"))+ .unwrap_or_default();lines.push(format!("- {} (pid {}){}", app.name, app.pid, bundle));}lines.join("\n")@@ -603,7 +649,10 @@ mod tests {// 2019-02-28T00:00:00Z → 1551312000.assert_eq!(unix_secs_to_rfc3339(1_551_312_000), "2019-02-28T00:00:00Z");// The very next second is Mar 1, not Feb 29.- assert_eq!(unix_secs_to_rfc3339(1_551_312_000 + 86_400), "2019-03-01T00:00:00Z");+ assert_eq!(+ unix_secs_to_rfc3339(1_551_312_000 + 86_400),+ "2019-03-01T00:00:00Z"+ );}#[test]diff --git a/libs/cua-driver/rust/crates/platform-macos/src/apps/nsworkspace.rs b/libs/cua-driver/rust/crates/platform-macos/src/apps/nsworkspace.rsindex ec6bdf8e00..0cb96f5179 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/apps/nsworkspace.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/apps/nsworkspace.rs@@ -33,20 +33,13 @@ use std::time::Duration;use block2::RcBlock;use objc2::rc::Retained;-use objc2_app_kit::{- NSRunningApplication, NSWorkspace, NSWorkspaceOpenConfiguration,-};-use objc2_foundation::{- NSAppleEventDescriptor, NSArray, NSDictionary, NSError, NSString, NSURL,-};+use objc2_app_kit::{NSRunningApplication, NSWorkspace, NSWorkspaceOpenConfiguration};+use objc2_foundation::{NSAppleEventDescriptor, NSArray, NSDictionary, NSError, NSString, NSURL};/// FourCharCode helper — packs a 4-byte ASCII tag into a `u32` the same way/// Apple's CoreServices headers do (`kCoreEventClass = 'aevt'` etc).const fn fourcc(s: &[u8; 4]) -> u32 {- ((s[0] as u32) << 24)- | ((s[1] as u32) << 16)- | ((s[2] as u32) << 8)- | (s[3] as u32)+ ((s[0] as u32) << 24) | ((s[1] as u32) << 16) | ((s[2] as u32) << 8) | (s[3] as u32)}const K_CORE_EVENT_CLASS: u32 = fourcc(b"aevt"); // kCoreEventClass@@ -129,11 +122,7 @@ pub fn open_application(?app_url, "calling openApplicationAtURL");unsafe {- ws.openApplicationAtURL_configuration_completionHandler(- &url,- &config,- Some(&block),- );+ ws.openApplicationAtURL_configuration_completionHandler(&url, &config, Some(&block));}wait_for_completion(rx)@@ -344,8 +333,8 @@ fn wait_for_completion(/// is not exposed by `objc2-foundation 0.2.2`.mod apple_event {use super::{- NSAppleEventDescriptor, NSString, Retained, K_AE_OPEN_APPLICATION,- K_ANY_TRANSACTION_ID, K_AUTO_GENERATE_RETURN_ID, K_CORE_EVENT_CLASS,+ NSAppleEventDescriptor, NSString, Retained, K_AE_OPEN_APPLICATION, K_ANY_TRANSACTION_ID,+ K_AUTO_GENERATE_RETURN_ID, K_CORE_EVENT_CLASS,};use objc2::msg_send_id;use objc2::rc::Allocated;@@ -354,13 +343,11 @@ mod apple_event {/// Build an `aevt/oapp` AppleEvent addressed to the bundle id `bid`.pub fn open_application_event(bid: &str) -> Retained<NSAppleEventDescriptor> {let target_string = NSString::from_str(bid);- let target: Retained<NSAppleEventDescriptor> = unsafe {- NSAppleEventDescriptor::descriptorWithBundleIdentifier(&target_string)- };+ let target: Retained<NSAppleEventDescriptor> =+ unsafe { NSAppleEventDescriptor::descriptorWithBundleIdentifier(&target_string) };unsafe {- let alloc: Allocated<NSAppleEventDescriptor> =- NSAppleEventDescriptor::alloc();+ let alloc: Allocated<NSAppleEventDescriptor> = NSAppleEventDescriptor::alloc();// initWithEventClass:eventID:targetDescriptor:returnID:transactionID:let event: Retained<NSAppleEventDescriptor> = msg_send_id![alloc,@@ -374,4 +361,3 @@ mod apple_event {}}}-diff --git a/libs/cua-driver/rust/crates/platform-macos/src/ax/cache.rs b/libs/cua-driver/rust/crates/platform-macos/src/ax/cache.rsindex 84ce3acdfb..9f0f90b1aa 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/ax/cache.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/ax/cache.rs@@ -83,7 +83,9 @@ pub struct ElementCache {impl ElementCache {pub fn new() -> Self {- Self { core: ElementCacheCore::new() }+ Self {+ core: ElementCacheCore::new(),+ }}/// Replace the snapshot for (pid, window_id) with the nodes from a fresh walk.@@ -93,7 +95,8 @@ impl ElementCache {.filter(|n| n.element_index.is_some()).map(|n| n.element_ptr).collect();- self.core.insert(CacheKey { pid, window_id }, CachedSnapshot { elements });+ self.core+ .insert(CacheKey { pid, window_id }, CachedSnapshot { elements });}/// Look up + `CFRetain` the element for `element_index` in (pid, window_id),@@ -179,11 +182,21 @@ mod tests {unsafe { CFRetain(ptr as CFTypeRef) };let cache = ElementCache::new();cache.update(1, 2, &[node_with_ptr(ptr)]);- assert_eq!(unsafe { CFGetRetainCount(ptr as CFTypeRef) }, base + 1, "cache owns one retain");+ assert_eq!(+ unsafe { CFGetRetainCount(ptr as CFTypeRef) },+ base + 1,+ "cache owns one retain"+ );// Borrow the element out for an action.- let guard = cache.get_element_retained(1, 2, 0).expect("element is cached");- assert_eq!(unsafe { CFGetRetainCount(ptr as CFTypeRef) }, base + 2, "guard adds a retain");+ let guard = cache+ .get_element_retained(1, 2, 0)+ .expect("element is cached");+ assert_eq!(+ unsafe { CFGetRetainCount(ptr as CFTypeRef) },+ base + 2,+ "guard adds a retain"+ );// Concurrent get_window_state replaces the snapshot → old one dropped →// CFRelease of the cache's retain. The guard's retain must remain.@@ -196,7 +209,11 @@ mod tests {);drop(guard);- assert_eq!(unsafe { CFGetRetainCount(ptr as CFTypeRef) }, base, "guard drop releases its retain");+ assert_eq!(+ unsafe { CFGetRetainCount(ptr as CFTypeRef) },+ base,+ "guard drop releases its retain"+ );}/// A missing index returns None without retaining anything.diff --git a/libs/cua-driver/rust/crates/platform-macos/src/ax/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/ax/mod.rsindex 3d4c476763..fb8edc866d 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/ax/mod.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/ax/mod.rs@@ -17,8 +17,10 @@//! - 2-space indent per depth levelpub mod bindings;-pub mod tree;pub mod cache;+pub mod tree;-pub use tree::{walk_tree, walk_tree_bounded, AXNode, TreeWalkResult, DEFAULT_MAX_ELEMENTS, DEFAULT_MAX_DEPTH};pub use cache::ElementCache;+pub use tree::{+ walk_tree, walk_tree_bounded, AXNode, TreeWalkResult, DEFAULT_MAX_DEPTH, DEFAULT_MAX_ELEMENTS,+};diff --git a/libs/cua-driver/rust/crates/platform-macos/src/ax/tree.rs b/libs/cua-driver/rust/crates/platform-macos/src/ax/tree.rsindex 0927426beb..ce816356db 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/ax/tree.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/ax/tree.rs@@ -113,7 +113,13 @@ pub struct TreeWalkResult {/// # Safety/// Calls macOS AX API. Must be called on a thread that has a CF run loop.pub fn walk_tree(pid: i32, window_id: Option<u32>, query: Option<&str>) -> TreeWalkResult {- walk_tree_bounded(pid, window_id, query, DEFAULT_MAX_ELEMENTS, DEFAULT_MAX_DEPTH)+ walk_tree_bounded(+ pid,+ window_id,+ query,+ DEFAULT_MAX_ELEMENTS,+ DEFAULT_MAX_DEPTH,+ )}/// Walk the AX tree with caller-supplied caps. See [`walk_tree`] for the@@ -143,7 +149,11 @@ pub fn walk_tree_bounded(unsafe {let app_elem = AXUIElementCreateApplication(pid);if app_elem.is_null() {- return TreeWalkResult { tree_markdown: String::new(), nodes, truncated: false };+ return TreeWalkResult {+ tree_markdown: String::new(),+ nodes,+ truncated: false,+ };}set_messaging_timeout(app_elem);@@ -156,7 +166,10 @@ pub fn walk_tree_bounded(// read it. Native Cocoa apps reject the attribute, so they pay no// settle cost. This relies on the MAX_ELEMENTS node cap to keep the// now-materialized (potentially large) tree bounded.- let already_enabled = enabled_pids().lock().map(|s| s.contains(&pid)).unwrap_or(false);+ let already_enabled = enabled_pids()+ .lock()+ .map(|s| s.contains(&pid))+ .unwrap_or(false);if !already_enabled && enable_chromium_accessibility(app_elem) {crate::permissions::panel::pump_run_loop_briefly(CHROMIUM_SETTLE_SECONDS);if let Ok(mut set) = enabled_pids().lock() {@@ -189,15 +202,19 @@ pub fn walk_tree_bounded(// Filter: keep non-window children (menu bar) + the target window.let walk_these: Vec<AXUIElementRef> = if let Some(wid) = window_id {- top_level.iter().copied().filter(|&child| {- set_messaging_timeout(child);- let role = copy_string_attr(child, "AXRole").unwrap_or_default();- if role != "AXWindow" {- return true; // always keep menu bar and other non-window items- }- // Match AX window element → CGWindowID via private SPI.- ax_get_window_id(child) == Some(wid)- }).collect()+ top_level+ .iter()+ .copied()+ .filter(|&child| {+ set_messaging_timeout(child);+ let role = copy_string_attr(child, "AXRole").unwrap_or_default();+ if role != "AXWindow" {+ return true; // always keep menu bar and other non-window items+ }+ // Match AX window element → CGWindowID via private SPI.+ ax_get_window_id(child) == Some(wid)+ })+ .collect()} else {top_level.iter().copied().collect()};@@ -243,7 +260,11 @@ pub fn walk_tree_bounded());}- TreeWalkResult { tree_markdown, nodes, truncated: truncated_flag }+ TreeWalkResult {+ tree_markdown,+ nodes,+ truncated: truncated_flag,+ }}#[allow(clippy::too_many_arguments)]@@ -259,7 +280,9 @@ unsafe fn walk_element(max_elements: usize,max_depth: usize,) {- if depth > max_depth { return; }+ if depth > max_depth {+ return;+ }// Enforce total-node cap — mirrors Swift's maxElements guard.// Set the truncated flag only when we actually stop early.if *visited_count >= max_elements {@@ -272,8 +295,7 @@ unsafe fn walk_element(// element, so every descendant must be bounded before any attribute read.set_messaging_timeout(element);- let role = copy_string_attr(element, "AXRole")- .unwrap_or_else(|| "AXUnknown".into());+ let role = copy_string_attr(element, "AXRole").unwrap_or_else(|| "AXUnknown".into());// Skip pure layout containers that have no interesting content.if role == "AXScrollArea" || role == "AXGroup" {@@ -307,7 +329,8 @@ unsafe fn walk_element(let title = copy_string_attr(element, "AXTitle");let value = copy_string_attr(element, "AXValue");// AXPlaceholderValue as fallback for empty text fields.- let value = value.filter(|v| !v.trim().is_empty())+ let value = value+ .filter(|v| !v.trim().is_empty()).or_else(|| copy_string_attr(element, "AXPlaceholderValue"));let description = copy_string_attr(element, "AXDescription");let identifier = copy_string_attr(element, "AXIdentifier");@@ -318,9 +341,8 @@ unsafe fn walk_element(let visible_description = description.as_deref().unwrap_or("").trim().to_owned();let visible_value = value.as_deref().unwrap_or("").trim().to_owned();- let has_content = !visible_title.is_empty()- || !visible_description.is_empty()- || !visible_value.is_empty();+ let has_content =+ !visible_title.is_empty() || !visible_description.is_empty() || !visible_value.is_empty();let is_actionable = !actions.is_empty();if !is_actionable && !has_content && role != "AXWindow" && role != "AXSheet" {@@ -354,9 +376,21 @@ unsafe fn walk_element(AXNode {element_index: Some(idx),role: role.clone(),- title: if visible_title.is_empty() { None } else { Some(visible_title.clone()) },- value: if visible_value.is_empty() { None } else { Some(visible_value.clone()) },- description: if visible_description.is_empty() { None } else { Some(visible_description.clone()) },+ title: if visible_title.is_empty() {+ None+ } else {+ Some(visible_title.clone())+ },+ value: if visible_value.is_empty() {+ None+ } else {+ Some(visible_value.clone())+ },+ description: if visible_description.is_empty() {+ None+ } else {+ Some(visible_description.clone())+ },identifier: identifier.clone(),help: help.clone(),actions: actions.clone(),@@ -369,9 +403,21 @@ unsafe fn walk_element(AXNode {element_index: None,role: role.clone(),- title: if visible_title.is_empty() { None } else { Some(visible_title.clone()) },- value: if visible_value.is_empty() { None } else { Some(visible_value.clone()) },- description: if visible_description.is_empty() { None } else { Some(visible_description.clone()) },+ title: if visible_title.is_empty() {+ None+ } else {+ Some(visible_title.clone())+ },+ value: if visible_value.is_empty() {+ None+ } else {+ Some(visible_value.clone())+ },+ description: if visible_description.is_empty() {+ None+ } else {+ Some(visible_description.clone())+ },identifier: identifier.clone(),help: help.clone(),actions: vec![],@@ -443,7 +489,9 @@ fn format_node_line(node: &AXNode) -> String {attrs.push(format!("help=\"{}\"", h));}if !node.actions.is_empty() {- let action_str = node.actions.iter()+ let action_str = node+ .actions+ .iter().map(|a| a.strip_prefix("AX").unwrap_or(a).to_lowercase()).collect::<Vec<_>>().join(",");@@ -495,8 +543,12 @@ fn filter_tree(markdown: &str, query: &str) -> String {if line.to_lowercase().contains(&needle) {for ancestor_depth in 0..depth {let ancestor = current_ancestor[ancestor_depth];- if ancestor.is_empty() { continue; }- if last_emitted_at[ancestor_depth] == Some(ancestor) { continue; }+ if ancestor.is_empty() {+ continue;+ }+ if last_emitted_at[ancestor_depth] == Some(ancestor) {+ continue;+ }last_emitted_at[ancestor_depth] = Some(ancestor);output.push(ancestor);}@@ -516,7 +568,11 @@ fn filter_tree(markdown: &str, query: &str) -> String {fn leading_indent_depth(line: &str) -> usize {let mut count = 0;for ch in line.chars() {- if ch == ' ' { count += 1; } else { break; }+ if ch == ' ' {+ count += 1;+ } else {+ break;+ }}count / 2}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/browser/ax_page_reader.rs b/libs/cua-driver/rust/crates/platform-macos/src/browser/ax_page_reader.rsindex bbc4f12e27..8c35cfac7f 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/browser/ax_page_reader.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/browser/ax_page_reader.rs@@ -13,9 +13,16 @@ pub struct AXElement {/// Roles to skip when extracting plain text.const SKIP_ROLES: &[&str] = &[- "AXWindow", "AXApplication", "AXGroup", "AXScrollArea",- "AXSplitGroup", "AXSplitter", "AXMenuBar", "AXMenu",- "AXMenuBarItem", "AXUnknown",+ "AXWindow",+ "AXApplication",+ "AXGroup",+ "AXScrollArea",+ "AXSplitGroup",+ "AXSplitter",+ "AXMenuBar",+ "AXMenu",+ "AXMenuBarItem",+ "AXUnknown",];/// Roles whose text content is always extracted (without filtering).@@ -28,19 +35,27 @@ impl AXPageReader {let mut last: Option<String> = None;for line in tree_markdown.lines() {- let Some(el) = parse_ax_line(line) else { continue };+ let Some(el) = parse_ax_line(line) else {+ continue;+ };let is_text_role = TEXT_ROLES.contains(&el.role.as_str());let is_skipped = SKIP_ROLES.contains(&el.role.as_str());- if is_skipped && !is_text_role { continue; }+ if is_skipped && !is_text_role {+ continue;+ }// Pick the best text: title > value > description.let text = best_text(&el);- if text.is_empty() { continue; }+ if text.is_empty() {+ continue;+ }// Deduplicate consecutive identical lines.- if last.as_deref() == Some(&text) { continue; }+ if last.as_deref() == Some(&text) {+ continue;+ }last = Some(text.clone());lines_out.push(text);}@@ -55,7 +70,9 @@ impl AXPageReader {let mut result = Vec::new();for line in tree_markdown.lines() {- let Some(el) = parse_ax_line(line) else { continue };+ let Some(el) = parse_ax_line(line) else {+ continue;+ };if match_all || roles.iter().any(|r| *r == el.role) {result.push(el);}@@ -138,7 +155,13 @@ fn parse_ax_line(line: &str) -> Option<AXElement> {}}- Some(AXElement { role, title, value, description, index })+ Some(AXElement {+ role,+ title,+ value,+ description,+ index,+ })}/// Parse a double-quoted string starting at the beginning of `s`.@@ -153,12 +176,10 @@ fn parse_quoted_string(s: &str) -> (String, &str) {loop {match chars.next() {None => return (result, ""),- Some((i, '\\')) => {- match chars.next() {- Some((_, c)) => result.push(c),- None => return (result, &s[i + 1..]),- }- }+ Some((i, '\\')) => match chars.next() {+ Some((_, c)) => result.push(c),+ None => return (result, &s[i + 1..]),+ },Some((i, '"')) => {return (result, &s[i + 1..]);}@@ -173,24 +194,29 @@ fn split_first_word(s: &str) -> (&str, &str) {}fn best_text(el: &AXElement) -> String {- if !el.title.is_empty() { return el.title.clone(); }- if !el.value.is_empty() { return el.value.clone(); }- if !el.description.is_empty() { return el.description.clone(); }+ if !el.title.is_empty() {+ return el.title.clone();+ }+ if !el.value.is_empty() {+ return el.value.clone();+ }+ if !el.description.is_empty() {+ return el.description.clone();+ }String::new()}fn css_selector_to_ax_roles(selector: &str) -> Vec<&'static str> {match selector.trim() {- "a" | "link" => vec!["AXLink"],- "button" => vec!["AXButton"],- "input" => vec!["AXTextField", "AXCheckBox", "AXRadioButton"],- "h1" | "h2" | "h3"- | "h4" | "h5" | "h6" => vec!["AXHeading"],- "p" => vec!["AXStaticText"],- "img" => vec!["AXImage"],- "select" => vec!["AXPopUpButton", "AXComboBox"],- "li" => vec!["AXStaticText"],- "*" | "" => vec![],- _ => vec![],+ "a" | "link" => vec!["AXLink"],+ "button" => vec!["AXButton"],+ "input" => vec!["AXTextField", "AXCheckBox", "AXRadioButton"],+ "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => vec!["AXHeading"],+ "p" => vec!["AXStaticText"],+ "img" => vec!["AXImage"],+ "select" => vec!["AXPopUpButton", "AXComboBox"],+ "li" => vec!["AXStaticText"],+ "*" | "" => vec![],+ _ => vec![],}}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/browser/browser_js.rs b/libs/cua-driver/rust/crates/platform-macos/src/browser/browser_js.rsindex 2ed7f6cf2a..1adadd74bc 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/browser/browser_js.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/browser/browser_js.rs@@ -1,7 +1,7 @@//! BrowserJS: run JavaScript in Chrome/Brave/Edge/Safari via AppleScript/osascript.-use std::time::Duration;use anyhow::Context;+use std::time::Duration;use crate::windows::WindowBounds;@@ -18,12 +18,12 @@ struct NativeWindowTarget {fn app_name_for_bundle(bundle_id: &str) -> Option<&'static str> {match bundle_id {- "com.google.Chrome" => Some("Google Chrome"),- "com.brave.Browser" => Some("Brave Browser"),- "com.microsoft.edgemac" => Some("Microsoft Edge"),- "com.apple.Safari" => Some("Safari"),+ "com.google.Chrome" => Some("Google Chrome"),+ "com.brave.Browser" => Some("Brave Browser"),+ "com.microsoft.edgemac" => Some("Microsoft Edge"),+ "com.apple.Safari" => Some("Safari"),_ if bundle_id.starts_with(CHROME_APP_BUNDLE_PREFIX) => Some("Google Chrome"),- _ => None,+ _ => None,}}@@ -34,7 +34,11 @@ impl BrowserJs {}/// Execute JavaScript in the browser window identified by window_id.- pub async fn execute(javascript: &str, bundle_id: &str, window_id: u32) -> anyhow::Result<String> {+ pub async fn execute(+ javascript: &str,+ bundle_id: &str,+ window_id: u32,+ ) -> anyhow::Result<String> {let app_name = app_name_for_bundle(bundle_id).ok_or_else(|| anyhow::anyhow!("Unsupported browser bundle: {bundle_id}"))?;@@ -90,9 +94,13 @@ end tell"#// Find profile directory.let home = std::env::var("HOME").unwrap_or_default();let profiles_dir = match bundle_id {- "com.google.Chrome" => format!("{home}/Library/Application Support/Google/Chrome"),- _ if bundle_id.starts_with(CHROME_APP_BUNDLE_PREFIX) => format!("{home}/Library/Application Support/Google/Chrome"),- "com.brave.Browser" => format!("{home}/Library/Application Support/BraveSoftware/Brave-Browser"),+ "com.google.Chrome" => format!("{home}/Library/Application Support/Google/Chrome"),+ _ if bundle_id.starts_with(CHROME_APP_BUNDLE_PREFIX) => {+ format!("{home}/Library/Application Support/Google/Chrome")+ }+ "com.brave.Browser" => {+ format!("{home}/Library/Application Support/BraveSoftware/Brave-Browser")+ }"com.microsoft.edgemac" => format!("{home}/Library/Application Support/Microsoft Edge"),_ => anyhow::bail!("No profiles directory for {bundle_id}"),};@@ -203,7 +211,9 @@ fn rounded_i64(value: f64) -> i64 {}fn find_preferences_files(profiles_dir: &str) -> Vec<String> {- let Ok(entries) = std::fs::read_dir(profiles_dir) else { return vec![] };+ let Ok(entries) = std::fs::read_dir(profiles_dir) else {+ return vec![];+ };let mut result = Vec::new();for entry in entries.flatten() {let path = entry.path();@@ -218,33 +228,40 @@ fn find_preferences_files(profiles_dir: &str) -> Vec<String> {}fn patch_preferences_file(path: &str) -> anyhow::Result<()> {- let content = std::fs::read_to_string(path)- .with_context(|| format!("Reading {path}"))?;- let mut json: serde_json::Value = serde_json::from_str(&content)- .with_context(|| format!("Parsing {path}"))?;+ let content = std::fs::read_to_string(path).with_context(|| format!("Reading {path}"))?;+ let mut json: serde_json::Value =+ serde_json::from_str(&content).with_context(|| format!("Parsing {path}"))?;// Set browser.allow_javascript_apple_events = true.if let Some(obj) = json.as_object_mut() {- let browser = obj.entry("browser")+ let browser = obj+ .entry("browser").or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));if let Some(b) = browser.as_object_mut() {- b.insert("allow_javascript_apple_events".to_owned(), serde_json::Value::Bool(true));+ b.insert(+ "allow_javascript_apple_events".to_owned(),+ serde_json::Value::Bool(true),+ );}// Also set account_values.browser.allow_javascript_apple_events.- let account_values = obj.entry("account_values")+ let account_values = obj+ .entry("account_values").or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));if let Some(av) = account_values.as_object_mut() {- let av_browser = av.entry("browser")+ let av_browser = av+ .entry("browser").or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));if let Some(avb) = av_browser.as_object_mut() {- avb.insert("allow_javascript_apple_events".to_owned(), serde_json::Value::Bool(true));+ avb.insert(+ "allow_javascript_apple_events".to_owned(),+ serde_json::Value::Bool(true),+ );}}}let new_content = serde_json::to_string(&json)?;- std::fs::write(path, new_content)- .with_context(|| format!("Writing {path}"))?;+ std::fs::write(path, new_content).with_context(|| format!("Writing {path}"))?;Ok(())}@@ -256,7 +273,8 @@ fn escape_for_applescript_string(s: &str) -> String {/// Escape JS for embedding in an AppleScript string literal./// Multi-line JS is split by newline and concatenated with `& (ASCII character 10) &`.fn escape_js_for_applescript(js: &str) -> String {- let lines: Vec<String> = js.lines()+ let lines: Vec<String> = js+ .lines().map(|l| {let escaped = l.replace('\\', "\\\\").replace('"', "\\\"");format!("\"{escaped}\"")@@ -276,15 +294,17 @@ pub async fn run_osascript(script: &str) -> anyhow::Result<String> {let uuid = format!("{:x}", rand_u64());let path = format!("/tmp/{uuid}.applescript");- tokio::fs::write(&path, script).await+ tokio::fs::write(&path, script)+ .await.with_context(|| format!("Writing temp applescript to {path}"))?;let out = tokio::time::timeout(Duration::from_secs(15),tokio::process::Command::new("/usr/bin/osascript").arg(&path)- .output()- ).await+ .output(),+ )+ .await.context("osascript timed out after 15s")?.context("osascript failed to spawn")?;@@ -304,15 +324,21 @@ pub async fn run_osascript(script: &str) -> anyhow::Result<String> {anyhow::bail!("osascript error: {msg}");}- Ok(String::from_utf8_lossy(&out.stdout).trim_end_matches('\n').to_owned())+ Ok(String::from_utf8_lossy(&out.stdout)+ .trim_end_matches('\n')+ .to_owned())}fn rand_u64() -> u64 {use std::time::{SystemTime, UNIX_EPOCH};- let t = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();+ let t = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default();// Mix in thread id for uniqueness.let tid = std::thread::current().id();- t.subsec_nanos() as u64 ^ t.as_secs().wrapping_mul(6364136223846793005) ^ format!("{tid:?}").len() as u64+ t.subsec_nanos() as u64+ ^ t.as_secs().wrapping_mul(6364136223846793005)+ ^ format!("{tid:?}").len() as u64}#[cfg(test)]diff --git a/libs/cua-driver/rust/crates/platform-macos/src/browser/cdp_client.rs b/libs/cua-driver/rust/crates/platform-macos/src/browser/cdp_client.rsindex 546a38e124..0dbc8076af 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/browser/cdp_client.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/browser/cdp_client.rs@@ -23,9 +23,9 @@ impl CdpClient {if let Ok(json) = http_get_json(port).await {if let Ok(arr) = serde_json::from_str::<serde_json::Value>(&json) {if let Some(list) = arr.as_array() {- let has_page = list.iter().any(|t| {- t.get("type").and_then(|v| v.as_str()) == Some("page")- });+ let has_page = list+ .iter()+ .any(|t| t.get("type").and_then(|v| v.as_str()) == Some("page"));if has_page {return Some(port);}@@ -91,10 +91,16 @@ pub struct CdpSessionCache {impl CdpSessionCache {pub fn new() -> Self {- Self { sessions: AsyncMutex::new(HashMap::new()) }+ Self {+ sessions: AsyncMutex::new(HashMap::new()),+ }}- async fn get_or_connect(&self, port: u16, target_url_contains: Option<&str>) -> anyhow::Result<Arc<AsyncMutex<CdpSession>>> {+ async fn get_or_connect(+ &self,+ port: u16,+ target_url_contains: Option<&str>,+ ) -> anyhow::Result<Arc<AsyncMutex<CdpSession>>> {let mut map = self.sessions.lock().await;if let Some(existing) = map.get(&port) {return Ok(existing.clone());@@ -122,7 +128,11 @@ impl CdpSessionCache {let arc = self.get_or_connect(port, target_url_contains).await?;{let mut session = arc.lock().await;- if session.ensure_target(port, target_url_contains).await.is_ok() {+ if session+ .ensure_target(port, target_url_contains)+ .await+ .is_ok()+ {return do_evaluate(&mut session, javascript).await;}}@@ -151,7 +161,12 @@ impl CdpSessionCache {/// attached — a browser with more than one tab open has no other way to/// know which one the caller means (CDP target ids have no relation to/// a window_id).- pub async fn insert_text(&self, text: &str, port: u16, target_url_contains: Option<&str>) -> anyhow::Result<()> {+ pub async fn insert_text(+ &self,+ text: &str,+ port: u16,+ target_url_contains: Option<&str>,+ ) -> anyhow::Result<()> {let arc = self.get_or_connect(port, target_url_contains).await?;let first_attempt = {let mut session = arc.lock().await;@@ -190,7 +205,12 @@ impl CdpSessionCache {/// click) — this dispatches to whatever element currently has focus, the/// same as a hardware keyboard would. `target_url_contains` — see/// `insert_text`.- pub async fn dispatch_keystrokes(&self, text: &str, port: u16, target_url_contains: Option<&str>) -> anyhow::Result<()> {+ pub async fn dispatch_keystrokes(+ &self,+ text: &str,+ port: u16,+ target_url_contains: Option<&str>,+ ) -> anyhow::Result<()> {let arc = self.get_or_connect(port, target_url_contains).await?;let first_attempt = {let mut session = arc.lock().await;@@ -212,18 +232,24 @@ impl CdpSessionCache {}impl Default for CdpSessionCache {- fn default() -> Self { Self::new() }+ fn default() -> Self {+ Self::new()+ }}async fn do_evaluate(session: &mut CdpSession, javascript: &str) -> anyhow::Result<String> {let obj = tokio::time::timeout(Duration::from_secs(10),- session.call("Runtime.evaluate", serde_json::json!({- "expression": javascript,- "returnByValue": true,- "awaitPromise": true- })),- ).await+ session.call(+ "Runtime.evaluate",+ serde_json::json!({+ "expression": javascript,+ "returnByValue": true,+ "awaitPromise": true+ }),+ ),+ )+ .await.map_err(|_| anyhow::anyhow!("CDP evaluate timed out after 10s"))??;parse_cdp_result(&obj)@@ -233,7 +259,8 @@ async fn do_insert_text(session: &mut CdpSession, text: &str) -> anyhow::Result<tokio::time::timeout(Duration::from_secs(10),session.call("Input.insertText", serde_json::json!({ "text": text })),- ).await+ )+ .await.map_err(|_| anyhow::anyhow!("CDP insertText timed out after 10s"))??;Ok(())}@@ -264,7 +291,8 @@ async fn do_dispatch_keystrokes(session: &mut CdpSession, text: &str) -> anyhow:tokio::time::sleep(Duration::from_millis(15)).await;}Ok(())- }).await+ })+ .await.map_err(|_| anyhow::anyhow!("CDP keystroke dispatch timed out after 30s"))?}@@ -297,12 +325,20 @@ impl CdpSession {async fn connect(port: u16, target_url_contains: Option<&str>) -> anyhow::Result<Self> {match ws_url_for_page_target(port, target_url_contains).await {Ok((ws_url, target_url)) => {- let connection = Arc::new(CdpConnection::connect(&ws_url).await- .map_err(|e| anyhow::anyhow!("WebSocket connect failed: {e}"))?);- Ok(Self { connection, session_id: None, current_target_url: Some(target_url) })+ let connection = Arc::new(+ CdpConnection::connect(&ws_url)+ .await+ .map_err(|e| anyhow::anyhow!("WebSocket connect failed: {e}"))?,+ );+ Ok(Self {+ connection,+ session_id: None,+ current_target_url: Some(target_url),+ })}Err(page_discovery_err) => {- Self::connect_via_browser_endpoint(port, target_url_contains, page_discovery_err).await+ Self::connect_via_browser_endpoint(port, target_url_contains, page_discovery_err)+ .await}}}@@ -319,7 +355,11 @@ impl CdpSession {connecting to the browser-level endpoint also failed: {e}")})?);- let mut session = Self { connection, session_id: None, current_target_url: None };+ let mut session = Self {+ connection,+ session_id: None,+ current_target_url: None,+ };session.attach_to_target(port, target_url_contains).await?;Ok(session)}@@ -330,7 +370,11 @@ impl CdpSession {/// via `Target.getTargets`/`Target.attachToTarget` does NOT reopen the/// socket, so it doesn't re-trigger Chrome's confirmation popup —/// that's the whole reason this exists instead of always reconnecting.- async fn ensure_target(&mut self, port: u16, target_url_contains: Option<&str>) -> anyhow::Result<()> {+ async fn ensure_target(+ &mut self,+ port: u16,+ target_url_contains: Option<&str>,+ ) -> anyhow::Result<()> {if self.session_id.is_some() {// Flattened browser-endpoint mode: always re-resolve + reattach// on the SAME connection (Target.getTargets/attachToTarget,@@ -355,24 +399,44 @@ impl CdpSession {}}- async fn attach_to_target(&mut self, port: u16, target_url_contains: Option<&str>) -> anyhow::Result<()> {- let targets = self.call("Target.getTargets", serde_json::json!({})).await?;- let infos = targets["targetInfos"].as_array().cloned().unwrap_or_default();- let pages: Vec<&serde_json::Value> = infos.iter()+ async fn attach_to_target(+ &mut self,+ port: u16,+ target_url_contains: Option<&str>,+ ) -> anyhow::Result<()> {+ let targets = self+ .call("Target.getTargets", serde_json::json!({}))+ .await?;+ let infos = targets["targetInfos"]+ .as_array()+ .cloned()+ .unwrap_or_default();+ let pages: Vec<&serde_json::Value> = infos+ .iter().filter(|t| t.get("type").and_then(|v| v.as_str()) == Some("page")).collect();- let target = pick_target(&pages, target_url_contains)- .ok_or_else(|| anyhow::anyhow!("Target.getTargets returned no page target on port {port}"))?;- let target_id = target.get("targetId").and_then(|v| v.as_str())+ let target = pick_target(&pages, target_url_contains).ok_or_else(|| {+ anyhow::anyhow!("Target.getTargets returned no page target on port {port}")+ })?;+ let target_id = target+ .get("targetId")+ .and_then(|v| v.as_str()).ok_or_else(|| anyhow::anyhow!("Target.getTargets entry missing targetId"))?.to_owned();- let target_url = target.get("url").and_then(|v| v.as_str()).unwrap_or("").to_owned();+ let target_url = target+ .get("url")+ .and_then(|v| v.as_str())+ .unwrap_or("")+ .to_owned();- let attach = self.call(- "Target.attachToTarget",- serde_json::json!({ "targetId": target_id, "flatten": true }),- ).await?;- let session_id = attach["sessionId"].as_str()+ let attach = self+ .call(+ "Target.attachToTarget",+ serde_json::json!({ "targetId": target_id, "flatten": true }),+ )+ .await?;+ let session_id = attach["sessionId"]+ .as_str().ok_or_else(|| anyhow::anyhow!("Target.attachToTarget did not return a sessionId"))?.to_owned();self.session_id = Some(session_id);@@ -381,7 +445,11 @@ impl CdpSession {}/// Send one command through the shared event-aware CDP demultiplexer.- async fn call(&mut self, method: &str, params: serde_json::Value) -> anyhow::Result<serde_json::Value> {+ async fn call(+ &mut self,+ method: &str,+ params: serde_json::Value,+ ) -> anyhow::Result<serde_json::Value> {self.connection.call(self.session_id.as_deref(), method, params).await@@ -393,21 +461,37 @@ impl CdpSession {/// discovery. Errors (not just returns None) so `CdpSession::connect` can/// report exactly why the classic path failed if the browser-endpoint/// fallback also fails.-async fn ws_url_for_page_target(port: u16, target_url_contains: Option<&str>) -> anyhow::Result<(String, String)> {+async fn ws_url_for_page_target(+ port: u16,+ target_url_contains: Option<&str>,+) -> anyhow::Result<(String, String)> {let json = http_get_json(port).await?;- let targets: serde_json::Value = serde_json::from_str(&json)- .map_err(|e| anyhow::anyhow!("CDP /json parse error: {e}"))?;-- let pages: Vec<&serde_json::Value> = targets.as_array()- .map(|arr| arr.iter().filter(|t| t.get("type").and_then(|v| v.as_str()) == Some("page")).collect())+ let targets: serde_json::Value =+ serde_json::from_str(&json).map_err(|e| anyhow::anyhow!("CDP /json parse error: {e}"))?;++ let pages: Vec<&serde_json::Value> = targets+ .as_array()+ .map(|arr| {+ arr.iter()+ .filter(|t| t.get("type").and_then(|v| v.as_str()) == Some("page"))+ .collect()+ }).unwrap_or_default();let target = pick_target(&pages, target_url_contains).ok_or_else(|| anyhow::anyhow!("No page target found on port {port}"))?;- let ws_url = target.get("webSocketDebuggerUrl").and_then(|v| v.as_str())- .ok_or_else(|| anyhow::anyhow!("No page target with webSocketDebuggerUrl found on port {port}"))?+ let ws_url = target+ .get("webSocketDebuggerUrl")+ .and_then(|v| v.as_str())+ .ok_or_else(|| {+ anyhow::anyhow!("No page target with webSocketDebuggerUrl found on port {port}")+ })?+ .to_owned();+ let target_url = target+ .get("url")+ .and_then(|v| v.as_str())+ .unwrap_or("").to_owned();- let target_url = target.get("url").and_then(|v| v.as_str()).unwrap_or("").to_owned();Ok((ws_url, target_url))}@@ -418,7 +502,10 @@ async fn ws_url_for_page_target(port: u16, target_url_contains: Option<&str>) ->/// `Target.getTargets`) since a browser with more than one tab open is/// otherwise picked non-deterministically — CDP target ids carry no/// relationship to the caller's `window_id`.-fn pick_target<'a>(pages: &[&'a serde_json::Value], hint: Option<&str>) -> Option<&'a serde_json::Value> {+fn pick_target<'a>(+ pages: &[&'a serde_json::Value],+ hint: Option<&str>,+) -> Option<&'a serde_json::Value> {match hint {None => pages.first().copied(),Some(hint) => {@@ -517,7 +604,9 @@ mod tests {while evaluated < 2 {let message = websocket.next().await.unwrap().unwrap();- let Message::Text(text) = message else { continue };+ let Message::Text(text) = message else {+ continue;+ };let request: serde_json::Value = serde_json::from_str(&text).unwrap();let id = request["id"].as_u64().unwrap();let method = request["method"].as_str().unwrap();@@ -549,7 +638,10 @@ mod tests {}other => panic!("unexpected method {other}"),};- websocket.send(Message::Text(response.to_string().into())).await.unwrap();+ websocket+ .send(Message::Text(response.to_string().into()))+ .await+ .unwrap();}});@@ -589,7 +681,9 @@ mod tests {loop {let message = websocket.next().await.unwrap().unwrap();- let Message::Text(text) = message else { continue };+ let Message::Text(text) = message else {+ continue;+ };let request: serde_json::Value = serde_json::from_str(&text).unwrap();let id = request["id"].as_u64().unwrap();let method = request["method"].as_str().unwrap();@@ -611,7 +705,10 @@ mod tests {"Runtime.evaluate" => break,other => panic!("unexpected method {other}"),};- websocket.send(Message::Text(response.to_string().into())).await.unwrap();+ websocket+ .send(Message::Text(response.to_string().into()))+ .await+ .unwrap();}websocket.close(None).await.unwrap();@@ -624,7 +721,10 @@ mod tests {});let cache = CdpSessionCache::new();- assert!(cache.evaluate("sideEffect()", port, Some("#window-a")).await.is_err());+ assert!(cache+ .evaluate("sideEffect()", port, Some("#window-a"))+ .await+ .is_err());server.await.unwrap();assert_eq!(accepted.load(Ordering::SeqCst), 2);}@@ -632,7 +732,10 @@ mod tests {fn parse_cdp_result(obj: &serde_json::Value) -> anyhow::Result<String> {if let Some(err) = obj.get("error") {- let msg = err.get("message").and_then(|v| v.as_str()).unwrap_or("unknown error");+ let msg = err+ .get("message")+ .and_then(|v| v.as_str())+ .unwrap_or("unknown error");anyhow::bail!("CDP error: {msg}");}let result = &obj["result"];@@ -657,9 +760,12 @@ pub(super) async fn listening_ports(pid: i32) -> Vec<u16> {// ORs `-p` with `-iTCP -sTCP:LISTEN`, returning every listening// port on the whole system in addition to this pid's fds."-a",- "-p", &pid.to_string(),- "-iTCP", "-sTCP:LISTEN",- "-Fn", "-P",+ "-p",+ &pid.to_string(),+ "-iTCP",+ "-sTCP:LISTEN",+ "-Fn",+ "-P",]).output().await;@@ -671,7 +777,9 @@ pub(super) async fn listening_ports(pid: i32) -> Vec<u16> {for line in text.lines() {// Lines starting with 'n' contain the address e.g. n*:9222 or n127.0.0.1:9222let trimmed = line.trim();- if !trimmed.starts_with('n') { continue; }+ if !trimmed.starts_with('n') {+ continue;+ }if let Some(colon_pos) = trimmed.rfind(':') {let port_str = &trimmed[colon_pos + 1..];if let Ok(p) = port_str.parse::<u16>() {@@ -687,10 +795,12 @@ async fn http_get_json(port: u16) -> anyhow::Result<String> {// connect — see the read loop below for why a bare `read_to_end` isn't// safe here.tokio::time::timeout(Duration::from_secs(5), async {- let mut stream = tokio::net::TcpStream::connect(format!("127.0.0.1:{port}")).await+ let mut stream = tokio::net::TcpStream::connect(format!("127.0.0.1:{port}"))+ .await.map_err(|e| anyhow::anyhow!("TCP connect error: {e}"))?;- let req = format!("GET /json HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n");+ let req =+ format!("GET /json HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n");stream.write_all(req.as_bytes()).await?;// Chrome's CDP HTTP server ignores our `Connection: close` request@@ -717,7 +827,8 @@ async fn http_get_json(port: u16) -> anyhow::Result<String> {.lines().find_map(|l| {let (name, value) = l.split_once(':')?;- name.trim().eq_ignore_ascii_case("content-length")+ name.trim()+ .eq_ignore_ascii_case("content-length").then(|| value.trim().parse().unwrap_or(0))}).unwrap_or(0);@@ -726,13 +837,16 @@ async fn http_get_json(port: u16) -> anyhow::Result<String> {while body.len() < content_length {let mut chunk = [0u8; 4096];let n = stream.read(&mut chunk).await?;- if n == 0 { break; }+ if n == 0 {+ break;+ }body.extend_from_slice(&chunk[..n]);}if content_length > 0 && body.len() > content_length {body.truncate(content_length);}Ok(String::from_utf8_lossy(&body).to_string())- }).await+ })+ .await.map_err(|_| anyhow::anyhow!("HTTP request to CDP port {port} timed out after 5s"))?}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/browser/wk_web_view.rs b/libs/cua-driver/rust/crates/platform-macos/src/browser/wk_web_view.rsindex fdd2121f74..ceaba95460 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/browser/wk_web_view.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/browser/wk_web_view.rs@@ -5,9 +5,7 @@ pub fn is_wk_web_view_app(pid: i32) -> bool {let apps = crate::apps::list_running_apps();let app = apps.iter().find(|a| a.pid == pid);- let bundle_path: Option<String> = app.and_then(|a| {- find_bundle_path_for_app_name(&a.name)- });+ let bundle_path: Option<String> = app.and_then(|a| find_bundle_path_for_app_name(&a.name));if let Some(ref bp) = bundle_path {// If it has Electron Framework it's Electron, not WKWebView.diff --git a/libs/cua-driver/rust/crates/platform-macos/src/cursor/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/cursor/mod.rsindex 25b4c3ba4c..72c2ded15f 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/cursor/mod.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/cursor/mod.rs@@ -5,8 +5,8 @@//! - `overlay::run_on_main_thread()` — called from `main()` on the main thread//! - `overlay::send_command(cmd)` — called from tool implementations-pub mod state;pub mod overlay;+pub mod state;// Re-export the legacy per-instance cursor state (used by tools for multi-cursor tracking).pub use state::{CursorRegistry, CursorState};diff --git a/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs b/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rsindex 3da7561a6d..d5eaff0165 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/cursor/overlay.rs@@ -514,10 +514,8 @@ unsafe fn run_appkit(_cfg: CursorConfig, rx: std::sync::mpsc::Receiver<OverlayMsuse core_graphics::display::{CGDisplayBounds, CGMainDisplayID};let display_id = CGMainDisplayID();let bounds = CGDisplayBounds(display_id);- backing_scale = crate::tools::get_screen_size::get_backing_scale(- display_id,- bounds.size.width as i64,- );+ backing_scale =+ crate::tools::get_screen_size::get_backing_scale(display_id, bounds.size.width as i64);if !(backing_scale > 0.0) {backing_scale = 1.0;}@@ -736,7 +734,9 @@ fn render_loop(t: rs.focus_rect_t,});cursor_overlay::paint_cursor(- &mut pm, &rs.core, 0.0,+ &mut pm,+ &rs.core,+ 0.0,0.0, // macOS uses screen-local coords (no origin offset)focus,backing_scale_f32,diff --git a/libs/cua-driver/rust/crates/platform-macos/src/cursor/state.rs b/libs/cua-driver/rust/crates/platform-macos/src/cursor/state.rsindex 931673484f..d13db9799d 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/cursor/state.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/cursor/state.rs@@ -64,7 +64,9 @@ impl CursorRegistry {position: None,};map.insert("default".into(), default);- Self { inner: Mutex::new(map) }+ Self {+ inner: Mutex::new(map),+ }}pub fn get_or_create(&self, cursor_id: &str) -> CursorState {@@ -80,15 +82,27 @@ impl CursorRegistry {// they pass through unchanged. Return the live entry if one survives,// else a transient default so callers get a sane value without a write.if cua_driver_core::session::is_session_ended(cursor_id) {- return inner.get(cursor_id).cloned().unwrap_or_else(|| CursorState {- config: CursorConfig { cursor_id: cursor_id.to_owned(), ..Default::default() },- position: None,- });+ return inner+ .get(cursor_id)+ .cloned()+ .unwrap_or_else(|| CursorState {+ config: CursorConfig {+ cursor_id: cursor_id.to_owned(),+ ..Default::default()+ },+ position: None,+ });}- inner.entry(cursor_id.to_owned()).or_insert_with(|| CursorState {- config: CursorConfig { cursor_id: cursor_id.to_owned(), ..Default::default() },- position: None,- }).clone()+ inner+ .entry(cursor_id.to_owned())+ .or_insert_with(|| CursorState {+ config: CursorConfig {+ cursor_id: cursor_id.to_owned(),+ ..Default::default()+ },+ position: None,+ })+ .clone()}/// Non-creating read of a single cursor's state. Returns None when the id@@ -108,10 +122,12 @@ impl CursorRegistry {return;}let mut inner = self.inner.lock().unwrap();- let entry = inner.entry(config.cursor_id.clone()).or_insert_with(|| CursorState {- config: config.clone(),- position: None,- });+ let entry = inner+ .entry(config.cursor_id.clone())+ .or_insert_with(|| CursorState {+ config: config.clone(),+ position: None,+ });entry.config = config;}@@ -125,10 +141,15 @@ impl CursorRegistry {let mut inner = self.inner.lock().unwrap();// Get-or-create so a per-session cursor that moves before any explicit// enable/style call still shows up in get_agent_cursor_state.- let state = inner.entry(cursor_id.to_owned()).or_insert_with(|| CursorState {- config: CursorConfig { cursor_id: cursor_id.to_owned(), ..Default::default() },- position: None,- });+ let state = inner+ .entry(cursor_id.to_owned())+ .or_insert_with(|| CursorState {+ config: CursorConfig {+ cursor_id: cursor_id.to_owned(),+ ..Default::default()+ },+ position: None,+ });state.position = Some(CursorPosition { x, y });}@@ -140,10 +161,15 @@ impl CursorRegistry {return;}let mut inner = self.inner.lock().unwrap();- let state = inner.entry(cursor_id.to_owned()).or_insert_with(|| CursorState {- config: CursorConfig { cursor_id: cursor_id.to_owned(), ..Default::default() },- position: None,- });+ let state = inner+ .entry(cursor_id.to_owned())+ .or_insert_with(|| CursorState {+ config: CursorConfig {+ cursor_id: cursor_id.to_owned(),+ ..Default::default()+ },+ position: None,+ });state.config.enabled = enabled;}@@ -190,12 +216,18 @@ mod tests {reg.set_enabled(sid, true);reg.update_position(sid, 10.0, 20.0);- reg.update_config(CursorConfig { cursor_id: sid.to_owned(), ..Default::default() });+ reg.update_config(CursorConfig {+ cursor_id: sid.to_owned(),+ ..Default::default()+ });let got = reg.get_or_create(sid);// get_or_create returns a transient default value, but must NOT persist.assert_eq!(got.config.cursor_id, sid);- assert!(reg.get(sid).is_none(), "no entry may be created for an ended session");+ assert!(+ reg.get(sid).is_none(),+ "no entry may be created for an ended session"+ );assert!(!reg.all_states().iter().any(|s| s.config.cursor_id == sid),"ended session cursor must never appear in the registry"diff --git a/libs/cua-driver/rust/crates/platform-macos/src/focus_guard.rs b/libs/cua-driver/rust/crates/platform-macos/src/focus_guard.rsindex 5641d08c39..b94288ace6 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/focus_guard.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/focus_guard.rs@@ -183,13 +183,7 @@ mod tests {/// 50ms sleep doesn't deadlock.#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn arms_lease_when_target_differs_from_prior() {- let n = with_focus_suppressed(- Some(123),- Some(456),- "test.armed",- || async { 99 },- )- .await;+ let n = with_focus_suppressed(Some(123), Some(456), "test.armed", || async { 99 }).await;assert_eq!(n, 99);}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/input/ax_actions.rs b/libs/cua-driver/rust/crates/platform-macos/src/input/ax_actions.rsindex 18f2cddea2..6e5ca47190 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/input/ax_actions.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/input/ax_actions.rs@@ -5,9 +5,7 @@ use crate::ax::bindings::*;/// Perform an AX action on a cached element.pub fn perform_ax_action(element_ptr: usize, action: &str) -> anyhow::Result<()> {let ax_action = map_action(action);- let err = unsafe {- perform_action(element_ptr as AXUIElementRef, ax_action)- };+ let err = unsafe { perform_action(element_ptr as AXUIElementRef, ax_action) };if err == kAXErrorSuccess {Ok(())@@ -30,9 +28,7 @@ fn map_action(action: &str) -> &'static str {/// Set AXFocused=true on an element (for pre-focusing before key press).pub fn focus_element(element_ptr: usize) -> anyhow::Result<()> {- let err = unsafe {- set_bool_attr_true(element_ptr as AXUIElementRef, "AXFocused")- };+ let err = unsafe { set_bool_attr_true(element_ptr as AXUIElementRef, "AXFocused") };if err == kAXErrorSuccess {Ok(())} else {@@ -44,9 +40,7 @@ pub fn focus_element(element_ptr: usize) -> anyhow::Result<()> {/// Set the AXValue of an element (for dropdowns, text fields, etc.).pub fn set_ax_value(element_ptr: usize, value: &str) -> anyhow::Result<()> {- let err = unsafe {- set_string_attr(element_ptr as AXUIElementRef, "AXValue", value)- };+ let err = unsafe { set_string_attr(element_ptr as AXUIElementRef, "AXValue", value) };if err == kAXErrorSuccess {Ok(())} else {diff --git a/libs/cua-driver/rust/crates/platform-macos/src/input/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/input/mod.rsindex 3bb24ffe51..b4b311a723 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/input/mod.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/input/mod.rs@@ -8,11 +8,11 @@//! public `CGEventPostToPid` to reach Catalyst/Chromium apps and trigger//! the activity-monitor tickle required for live-input detection.-pub mod mouse;-pub mod keyboard;pub mod ax_actions;+pub mod keyboard;+pub mod mouse;pub mod skylight;pub use ax_actions::perform_ax_action;+pub use keyboard::{hotkey, press_key, type_text};pub use mouse::click_at_xy;-pub use keyboard::{press_key, type_text, hotkey};diff --git a/libs/cua-driver/rust/crates/platform-macos/src/input/skylight.rs b/libs/cua-driver/rust/crates/platform-macos/src/input/skylight.rsindex ec6dd54148..538e61d156 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/input/skylight.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/input/skylight.rs@@ -16,10 +16,10 @@//! If anything fails to resolve the functions return `false` and callers//! fall back to the public `CGEvent::post_to_pid`.-use std::ffi::{CStr, c_void};-use std::os::raw::{c_int, c_uint, c_char};-use std::sync::OnceLock;use libc::pid_t;+use std::ffi::{c_void, CStr};+use std::os::raw::{c_char, c_int, c_uint};+use std::sync::OnceLock;// ── Function-pointer typedefs ──────────────────────────────────────────────@@ -87,7 +87,10 @@ fn ensure_skylight_loaded() {LOADED.get_or_init(|| {let path = b"/System/Library/PrivateFrameworks/SkyLight.framework/SkyLight\0";unsafe {- libc::dlopen(path.as_ptr() as *const c_char, libc::RTLD_LAZY | libc::RTLD_GLOBAL);+ libc::dlopen(+ path.as_ptr() as *const c_char,+ libc::RTLD_LAZY | libc::RTLD_GLOBAL,+ );}});}@@ -96,10 +99,12 @@ fn ensure_skylight_loaded() {/// Returns `None` when the symbol doesn't resolve.fn find_sym(name: &[u8]) -> Option<*mut c_void> {ensure_skylight_loaded();- let ptr = unsafe {- libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr() as *const c_char)- };- if ptr.is_null() { None } else { Some(ptr) }+ let ptr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr() as *const c_char) };+ if ptr.is_null() {+ None+ } else {+ Some(ptr)+ }}/// Reinterpret a raw symbol pointer as a function pointer of type `T`.@@ -220,8 +225,8 @@ fn class_responds_to_selector(cls: *mut c_void, sel: *mut c_void) -> bool {}type RespondsToFn = unsafe extern "C" fn(*mut c_void, *mut c_void) -> bool;static SYM: OnceLock<Option<RespondsToFn>> = OnceLock::new();- let f = *SYM- .get_or_init(|| find_sym(b"class_respondsToSelector\0").map(|p| unsafe { as_fn(p) }));+ let f =+ *SYM.get_or_init(|| find_sym(b"class_respondsToSelector\0").map(|p| unsafe { as_fn(p) }));match f {Some(f) => unsafe { f(cls, sel) },None => false,@@ -238,9 +243,7 @@ fn class_responds_to_selector(cls: *mut c_void, sel: *mut c_void) -> bool {/// We probe offsets 24, 32, 16 for resilience across OS versions (same as Swift).unsafe fn extract_event_record(event_ptr: *mut c_void) -> *mut c_void {for &offset in &[24usize, 32, 16] {- let slot = (event_ptr as *const u8)- .add(offset)- .cast::<*mut c_void>();+ let slot = (event_ptr as *const u8).add(offset).cast::<*mut c_void>();let p = std::ptr::read_unaligned(slot);if !p.is_null() {return p;@@ -301,7 +304,10 @@ pub fn post_to_pid(pid: pid_t, event_ptr: *mut c_void, attach_auth_message: bool/// `CGEventSetWindowLocation` SPI. Returns `true` when the SPI resolved.pub fn set_window_location(event_ptr: *mut c_void, x: f64, y: f64) -> bool {match set_window_loc_fn() {- Some(f) => { unsafe { f(event_ptr, x, y) }; true }+ Some(f) => {+ unsafe { f(event_ptr, x, y) };+ true+ }None => false,}}@@ -310,7 +316,10 @@ pub fn set_window_location(event_ptr: *mut c_void, x: f64, y: f64) -> bool {/// `SLEventSetIntegerValueField`. Returns `false` when SPI absent.pub fn set_integer_field(event_ptr: *mut c_void, field: u32, value: i64) -> bool {match set_int_field_fn() {- Some(f) => { unsafe { f(event_ptr, field, value) }; true }+ Some(f) => {+ unsafe { f(event_ptr, field, value) };+ true+ }None => false,}}@@ -357,10 +366,14 @@ pub fn activate_without_raise(target_pid: pid_t, target_wid: u32) -> bool {let mut target_psn = [0u8; 8];let ok_prev = unsafe { get_front(prev_psn.as_mut_ptr() as *mut c_void) } == 0;- if !ok_prev { return false; }+ if !ok_prev {+ return false;+ }let ok_target = unsafe { get_pid_psn(target_pid, target_psn.as_mut_ptr() as *mut c_void) } == 0;- if !ok_target { return false; }+ if !ok_target {+ return false;+ }// Build the 248-byte event buffer.let mut buf = [0u8; 0xF8];@@ -374,15 +387,11 @@ pub fn activate_without_raise(target_pid: pid_t, target_wid: u32) -> bool {// Step 3: defocus previous front.buf[0x8A] = 0x02;- let defocus_ok = unsafe {- post_fn(prev_psn.as_ptr() as *const c_void, buf.as_ptr()) == 0- };+ let defocus_ok = unsafe { post_fn(prev_psn.as_ptr() as *const c_void, buf.as_ptr()) == 0 };// Step 4: focus target.buf[0x8A] = 0x01;- let focus_ok = unsafe {- post_fn(target_psn.as_ptr() as *const c_void, buf.as_ptr()) == 0- };+ let focus_ok = unsafe { post_fn(target_psn.as_ptr() as *const c_void, buf.as_ptr()) == 0 };defocus_ok && focus_ok}@@ -394,15 +403,19 @@ pub fn activate_without_raise(target_pid: pid_t, target_wid: u32) -> bool {/// Falls back to `GetProcessForPID(pid)` when the SkyLight path fails.pub fn get_process_psn_for_window(window_id: u32, pid: libc::pid_t, out_psn: &mut [u8; 8]) -> bool {// Try modern path: CGSMainConnectionID → SLSGetWindowOwner → SLSGetConnectionPSN- if let (Some(get_owner), Some(get_psn), Some(conn_id_fn)) =- (get_window_owner_fn(), get_connection_psn_fn(), connection_id_fn())- {+ if let (Some(get_owner), Some(get_psn), Some(conn_id_fn)) = (+ get_window_owner_fn(),+ get_connection_psn_fn(),+ connection_id_fn(),+ ) {let main_cid = unsafe { conn_id_fn() };let mut owner_cid: u32 = 0;let ok = unsafe { get_owner(main_cid, window_id, &mut owner_cid) } == 0;if ok && owner_cid != 0 {let psn_ok = unsafe { get_psn(owner_cid, out_psn.as_mut_ptr() as *mut c_void) } == 0;- if psn_ok { return true; }+ if psn_ok {+ return true;+ }}}// Fallback: GetProcessForPIDdiff --git a/libs/cua-driver/rust/crates/platform-macos/src/lib.rs b/libs/cua-driver/rust/crates/platform-macos/src/lib.rsindex f5015378ff..489f68a99f 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/lib.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/lib.rs@@ -6,40 +6,40 @@//! - NSRunningApplication / NSWorkspace for app enumeration and lifecycle//! - CGWindow / ScreenCaptureKit for window enumeration and screenshots-#[cfg(target_os = "macos")]-pub mod ax;#[cfg(target_os = "macos")]pub mod apps;#[cfg(target_os = "macos")]-pub mod windows;-#[cfg(target_os = "macos")]-pub mod input;+pub mod ax;#[cfg(target_os = "macos")]-pub mod cursor;+pub mod browser;#[cfg(target_os = "macos")]pub mod capture;#[cfg(target_os = "macos")]-pub mod browser;+pub mod cursor;+#[cfg(target_os = "macos")]+pub mod focus_guard;#[cfg(target_os = "macos")]pub mod focus_steal;#[cfg(target_os = "macos")]+pub mod input;+#[cfg(target_os = "macos")]pub mod permissions;#[cfg(target_os = "macos")]-pub mod focus_guard;+pub mod pip;#[cfg(target_os = "macos")]-pub mod window_change_detector;+pub mod recording_hooks;+#[cfg(target_os = "macos")]+pub mod session;#[cfg(target_os = "macos")]pub mod terminal;#[cfg(target_os = "macos")]pub mod tools;#[cfg(target_os = "macos")]-pub mod recording_hooks;-#[cfg(target_os = "macos")]pub mod video_sckit;#[cfg(target_os = "macos")]-pub mod pip;+pub mod window_change_detector;#[cfg(target_os = "macos")]-pub mod session;+pub mod windows;use cua_driver_core::tool::ToolRegistry;diff --git a/libs/cua-driver/rust/crates/platform-macos/src/permissions/gate.rs b/libs/cua-driver/rust/crates/platform-macos/src/permissions/gate.rsindex 523385b29a..b527fdcc45 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/permissions/gate.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/permissions/gate.rs@@ -62,12 +62,14 @@ impl MissingPermission {/// adapted from the Swift gate's SwiftUI subtitle copy.pub fn rationale(self) -> &'static str {match self {- Self::Accessibility =>+ Self::Accessibility => {"lets cua-driver read the accessibility tree of running apps and \- send clicks / keystrokes via AX RPC.",- Self::ScreenRecording =>+ send clicks / keystrokes via AX RPC."+ }+ Self::ScreenRecording => {"lets cua-driver capture per-window screenshots so agents can see \- the current UI state alongside the tree.",+ the current UI state alongside the tree."+ }}}@@ -75,10 +77,12 @@ impl MissingPermission {/// Privacy pane. Same strings the Swift gate uses.pub fn settings_url(self) -> &'static str {match self {- Self::Accessibility =>- "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility",- Self::ScreenRecording =>- "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture",+ Self::Accessibility => {+ "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"+ }+ Self::ScreenRecording => {+ "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture"+ }}}}@@ -266,18 +270,22 @@ pub fn telemetry_context() -> GateTelemetryContext {}).unwrap_or_default();GateTelemetryContext {- engaged: started.is_some() && engaged && (missing_accessibility || missing_screen_recording),+ engaged: started.is_some()+ && engaged+ && (missing_accessibility || missing_screen_recording),missing_accessibility,missing_screen_recording,- panel_shown: GATE_PANEL_SHOWN.load(Ordering::Relaxed) || has_internal_arg(GATE_PANEL_SHOWN_ARG),- dismissed: GATE_PANEL_DISMISSED.load(Ordering::Relaxed) || has_internal_arg(GATE_PANEL_DISMISSED_ARG),+ panel_shown: GATE_PANEL_SHOWN.load(Ordering::Relaxed)+ || has_internal_arg(GATE_PANEL_SHOWN_ARG),+ dismissed: GATE_PANEL_DISMISSED.load(Ordering::Relaxed)+ || has_internal_arg(GATE_PANEL_DISMISSED_ARG),elapsed,}}fn begin_gate_episode(initial: PermissionsStatus) {- let already_engaged = GATE_ENGAGED.swap(true, Ordering::Relaxed)- || has_internal_arg(GATE_ENGAGED_ARG);+ let already_engaged =+ GATE_ENGAGED.swap(true, Ordering::Relaxed) || has_internal_arg(GATE_ENGAGED_ARG);if !already_engaged {GATE_MISSING_ACCESSIBILITY.store(!initial.accessibility, Ordering::Relaxed);GATE_MISSING_SCREEN_RECORDING.store(!initial.screen_recording, Ordering::Relaxed);@@ -295,9 +303,7 @@ fn begin_gate_episode(initial: PermissionsStatus) {/// bounded hidden argv flags only at re-exec time. A returned `Started`/// transition belongs to this first probe and should be delivered before the/// caller performs other startup work.-pub fn prepare_telemetry_context(- opt_out: bool,-) -> Option<(GateProgress, GateTelemetryContext)> {+pub fn prepare_telemetry_context(opt_out: bool) -> Option<(GateProgress, GateTelemetryContext)> {if opt_out || is_gate_reexec() || std::env::var_os(GATE_START_ENV).is_some() {return None;}@@ -549,7 +555,10 @@ pub fn wait_for_grants(opts: &GateOpts) -> Result<()> {.duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);- match std::env::var(GATE_START_ENV).ok().and_then(|s| s.parse::<u64>().ok()) {+ match std::env::var(GATE_START_ENV)+ .ok()+ .and_then(|s| s.parse::<u64>().ok())+ {Some(orig) => Instant::now().checked_sub(Duration::from_secs(now_unix.saturating_sub(orig))).unwrap_or_else(Instant::now),@@ -669,10 +678,22 @@ fn reexec_self() {let mut raw_argv: Vec<std::ffi::OsString> = std::env::args_os().collect();for (enabled, flag) in [(GATE_ENGAGED.load(Ordering::Relaxed), GATE_ENGAGED_ARG),- (GATE_MISSING_ACCESSIBILITY.load(Ordering::Relaxed), GATE_MISSING_ACCESSIBILITY_ARG),- (GATE_MISSING_SCREEN_RECORDING.load(Ordering::Relaxed), GATE_MISSING_SCREEN_RECORDING_ARG),- (GATE_PANEL_SHOWN.load(Ordering::Relaxed), GATE_PANEL_SHOWN_ARG),- (GATE_PANEL_DISMISSED.load(Ordering::Relaxed), GATE_PANEL_DISMISSED_ARG),+ (+ GATE_MISSING_ACCESSIBILITY.load(Ordering::Relaxed),+ GATE_MISSING_ACCESSIBILITY_ARG,+ ),+ (+ GATE_MISSING_SCREEN_RECORDING.load(Ordering::Relaxed),+ GATE_MISSING_SCREEN_RECORDING_ARG,+ ),+ (+ GATE_PANEL_SHOWN.load(Ordering::Relaxed),+ GATE_PANEL_SHOWN_ARG,+ ),+ (+ GATE_PANEL_DISMISSED.load(Ordering::Relaxed),+ GATE_PANEL_DISMISSED_ARG,+ ),] {if enabled && !raw_argv.iter().any(|arg| arg == flag) {raw_argv.push(flag.into());@@ -688,8 +709,7 @@ fn reexec_self() {}// execvp takes a NULL-terminated argv. Build pointers + sentinel.- let mut argv_ptrs: Vec<*const libc::c_char> =- argv.iter().map(|s| s.as_ptr()).collect();+ let mut argv_ptrs: Vec<*const libc::c_char> = argv.iter().map(|s| s.as_ptr()).collect();argv_ptrs.push(std::ptr::null());let exe_c = match CString::new(exe.into_os_string().into_vec()) {@@ -970,8 +990,10 @@ mod tests {let opts = GateOpts::from_env_and_flag(false);// "TrUe" is in the list intentionally — it must NOT opt out// (it's not in the off-sentinel set), so split the assertion.- let expected_opt_out =- matches!(v.to_ascii_lowercase().as_str(), "0" | "false" | "no" | "off");+ let expected_opt_out = matches!(+ v.to_ascii_lowercase().as_str(),+ "0" | "false" | "no" | "off"+ );assert_eq!(opts.opt_out, expected_opt_out,"env={v:?} opt_out mismatch (expected {expected_opt_out})"diff --git a/libs/cua-driver/rust/crates/platform-macos/src/permissions/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/permissions/mod.rsindex ae054b3a56..d3f94a1a8f 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/permissions/mod.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/permissions/mod.rs@@ -22,10 +22,10 @@ pub mod status;#[cfg(target_os = "macos")]pub mod panel;-pub use status::{PermissionsStatus, current_status};pub use gate::{- GateOpts, GateProgress, MissingPermission, run_if_needed, run_if_needed_with_observer,+ run_if_needed, run_if_needed_with_observer, GateOpts, GateProgress, MissingPermission,};+pub use status::{current_status, PermissionsStatus};/// Crate-wide lock serializing tests that mutate process-global env vars./// Per-module locks are not enough: `gate` and `check_permissions` testsdiff --git a/libs/cua-driver/rust/crates/platform-macos/src/permissions/panel.rs b/libs/cua-driver/rust/crates/platform-macos/src/permissions/panel.rsindex 31c7ada6d3..21258a8153 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/permissions/panel.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/permissions/panel.rs@@ -135,8 +135,7 @@ pub fn panel_enabled() -> bool {/// Safety / threading: panics if invoked off the main thread. Callers/// should check [`panel_enabled`] first to avoid the panic.pub fn show_modal(opts: PanelOpts) -> PanelOutcome {- let _mtm = MainThreadMarker::new()- .expect("show_modal must be called from the main thread");+ let _mtm = MainThreadMarker::new().expect("show_modal must be called from the main thread");unsafe { show_modal_unsafe(&opts) }}@@ -170,8 +169,7 @@ pub fn pump_run_loop_briefly(seconds: f64) {return;}unsafe {- let run_loop: *mut AnyObject =- msg_send![class!(NSRunLoop), currentRunLoop];+ let run_loop: *mut AnyObject = msg_send![class!(NSRunLoop), currentRunLoop];if run_loop.is_null() {std::thread::sleep(std::time::Duration::from_secs_f64(seconds.max(0.0)));return;@@ -180,8 +178,7 @@ pub fn pump_run_loop_briefly(seconds: f64) {// deadline. `[NSRunLoop runMode:beforeDate:]` blocks up to// that deadline while dispatching pending input sources +// timers — including TCC notification taps.- let date: *mut AnyObject =- msg_send![class!(NSDate), dateWithTimeIntervalSinceNow: seconds];+ let date: *mut AnyObject = msg_send![class!(NSDate), dateWithTimeIntervalSinceNow: seconds];if date.is_null() {std::thread::sleep(std::time::Duration::from_secs_f64(seconds.max(0.0)));return;@@ -308,8 +305,7 @@ unsafe fn show_modal_unsafe(opts: &PanelOpts) -> PanelOutcome {);let _: () = msg_send![content_view, addSubview: subheading];// Subheading is secondary text — apply secondaryLabelColor.- let secondary_color: *mut AnyObject =- msg_send![class!(NSColor), secondaryLabelColor];+ let secondary_color: *mut AnyObject = msg_send![class!(NSColor), secondaryLabelColor];let _: () = msg_send![subheading, setTextColor: secondary_color];y -= 16.0; // gap before first row@@ -318,7 +314,10 @@ unsafe fn show_modal_unsafe(opts: &PanelOpts) -> PanelOutcome {let ax_row = build_row(MissingPermission::Accessibility,opts.initial_status.accessibility,- NSPoint { x: PAD, y: y - ROW_H },+ NSPoint {+ x: PAD,+ y: y - ROW_H,+ },NSSize {width: WIN_W - 2.0 * PAD,height: ROW_H,@@ -330,7 +329,10 @@ unsafe fn show_modal_unsafe(opts: &PanelOpts) -> PanelOutcome {let sr_row = build_row(MissingPermission::ScreenRecording,opts.initial_status.screen_recording,- NSPoint { x: PAD, y: y - ROW_H },+ NSPoint {+ x: PAD,+ y: y - ROW_H,+ },NSSize {width: WIN_W - 2.0 * PAD,height: ROW_H,@@ -340,7 +342,13 @@ unsafe fn show_modal_unsafe(opts: &PanelOpts) -> PanelOutcome {y -= ROW_H + 8.0;// ---- Ready strip (initially hidden; shown by poll on all-green) ----- let ready_strip = build_ready_strip(NSPoint { x: PAD, y: y - READY_STRIP_H }, WIN_W - 2.0 * PAD);+ let ready_strip = build_ready_strip(+ NSPoint {+ x: PAD,+ y: y - READY_STRIP_H,+ },+ WIN_W - 2.0 * PAD,+ );let _: () = msg_send![content_view, addSubview: ready_strip];let initially_all_green =opts.initial_status.accessibility && opts.initial_status.screen_recording;@@ -502,7 +510,9 @@ unsafe fn poll_tick_inner() {let mut should_stop = false;HANDLES.with(|cell| {let mut guard = cell.borrow_mut();- let Some(handles) = guard.as_mut() else { return };+ let Some(handles) = guard.as_mut() else {+ return;+ };if status == handles.last_status {// No change — skip the redraw. Avoids needlessly thrashing// the layout engine every second on a steady-state panel.@@ -789,10 +799,7 @@ fn panel_target_class() -> &'static objc2::runtime::AnyClass {objc2::sel!(openSettings:),on_open_settings as extern "C" fn(_, _, _),);- builder.add_method(- objc2::sel!(dismiss:),- on_dismiss as extern "C" fn(_, _, _),- );+ builder.add_method(objc2::sel!(dismiss:), on_dismiss as extern "C" fn(_, _, _));builder.add_method(objc2::sel!(pollTick:),on_poll_tick as extern "C" fn(_, _, _),diff --git a/libs/cua-driver/rust/crates/platform-macos/src/permissions/status.rs b/libs/cua-driver/rust/crates/platform-macos/src/permissions/status.rsindex 2721d17ff4..597577263f 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/permissions/status.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/permissions/status.rs@@ -76,11 +76,8 @@ pub fn request_accessibility() -> bool {let key = CFString::new("AXTrustedCheckOptionPrompt");let val = CFBoolean::true_value();- let options =- CFDictionary::from_CFType_pairs(&[(key.as_CFType(), val.as_CFType())]);- unsafe {- crate::ax::bindings::AXIsProcessTrustedWithOptions(options.as_concrete_TypeRef())- }+ let options = CFDictionary::from_CFType_pairs(&[(key.as_CFType(), val.as_CFType())]);+ unsafe { crate::ax::bindings::AXIsProcessTrustedWithOptions(options.as_concrete_TypeRef()) }}/// Raise the Screen Recording TCC prompt if not yet granted.diff --git a/libs/cua-driver/rust/crates/platform-macos/src/pip/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/pip/mod.rsindex 3184f84acd..bf873a403f 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/pip/mod.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/pip/mod.rs@@ -175,8 +175,8 @@ unsafe extern "C" fn push_frame_cb(ctx: *mut c_void) {}unsafe extern "C" fn shutdown_cb(_ctx: *mut c_void) {- use objc2::runtime::AnyObject;use objc2::msg_send;+ use objc2::runtime::AnyObject;let handles = HANDLES.lock().unwrap().take();if let Some(h) = handles {diff --git a/libs/cua-driver/rust/crates/platform-macos/src/recording_hooks.rs b/libs/cua-driver/rust/crates/platform-macos/src/recording_hooks.rsindex 101e17d6ad..09b635ec85 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/recording_hooks.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/recording_hooks.rs@@ -12,8 +12,8 @@use std::sync::{Arc, OnceLock};-use crate::ax::cache::ElementCache;use crate::ax::bindings::{element_screen_center, AXUIElementRef};+use crate::ax::cache::ElementCache;static ELEMENT_CACHE: OnceLock<Arc<ElementCache>> = OnceLock::new();@@ -31,7 +31,11 @@ pub fn app_state_json_for(window_id: Option<u64>, pid: Option<i64>) -> Option<VeNone => crate::windows::resolve_main_window_id(pid).ok()?,};let result = crate::ax::tree::walk_tree(pid, Some(resolved_wid), None);- let element_count = result.nodes.iter().filter(|n| n.element_index.is_some()).count();+ let element_count = result+ .nodes+ .iter()+ .filter(|n| n.element_index.is_some())+ .count();let payload = serde_json::json!({"pid": pid,"window_id": resolved_wid,@@ -60,9 +64,17 @@ pub fn element_window_local_xy(window_id: u64, pid: i64, element_index: u32) ->let scale = if let Ok(png) = crate::capture::screenshot_window_bytes(window_id_u32) {if png.len() >= 24 {let pw = u32::from_be_bytes([png[16], png[17], png[18], png[19]]) as f64;- if bounds.width > 0.0 && pw > bounds.width { pw / bounds.width } else { 1.0 }- } else { 1.0 }- } else { 1.0 };+ if bounds.width > 0.0 && pw > bounds.width {+ pw / bounds.width+ } else {+ 1.0+ }+ } else {+ 1.0+ }+ } else {+ 1.0+ };let wx = (sx - bounds.x) * scale;let wy = (sy - bounds.y) * scale;diff --git a/libs/cua-driver/rust/crates/platform-macos/src/terminal.rs b/libs/cua-driver/rust/crates/platform-macos/src/terminal.rsindex ac28d6ff8a..5986f3134c 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/terminal.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/terminal.rs@@ -23,16 +23,16 @@////// Add new terminals here. Keep alphabetical so diffs stay sane.pub const TERMINAL_BUNDLE_IDS: &[&str] = &[- "co.zeit.hyper", // Hyper- "com.apple.Terminal", // Apple Terminal.app- "com.github.wez.wezterm", // WezTerm- "com.googlecode.iterm2", // iTerm2- "com.mitchellh.ghostty", // Ghostty- "dev.warp.Warp-Stable", // Warp- "dev.zed.Zed.Helper", // Zed's embedded terminal helper- "io.alacritty", // Alacritty (newer bundle id)- "net.kovidgoyal.kitty", // kitty- "org.alacritty", // Alacritty (older bundle id)+ "co.zeit.hyper", // Hyper+ "com.apple.Terminal", // Apple Terminal.app+ "com.github.wez.wezterm", // WezTerm+ "com.googlecode.iterm2", // iTerm2+ "com.mitchellh.ghostty", // Ghostty+ "dev.warp.Warp-Stable", // Warp+ "dev.zed.Zed.Helper", // Zed's embedded terminal helper+ "io.alacritty", // Alacritty (newer bundle id)+ "net.kovidgoyal.kitty", // kitty+ "org.alacritty", // Alacritty (older bundle id)];/// Returns `true` when `bundle_id` matches a known terminal emulatordiff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/bring_to_front.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/bring_to_front.rsindex 7a067cb9de..7c2ac6c10f 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/bring_to_front.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/bring_to_front.rs@@ -20,7 +20,10 @@//! foreground — it is an explicit opt-in, never called by the input ladder.use async_trait::async_trait;-use cua_driver_core::{protocol::ToolResult, tool::{Tool, ToolDef}};+use cua_driver_core::{+ protocol::ToolResult,+ tool::{Tool, ToolDef},+};use objc2_app_kit::{NSApplicationActivationOptions, NSRunningApplication};use serde_json::Value;@@ -31,8 +34,7 @@ static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();fn def() -> &'static ToolDef {DEF.get_or_init(|| ToolDef {name: "bring_to_front".into(),- description:- "Persistently activate an app so it genuinely holds macOS foreground, \+ description: "Persistently activate an app so it genuinely holds macOS foreground, \then leave it there. Most input does NOT need this — every macOS \dispatch reaches backgrounded windows, and `dispatch:\"foreground\"` \does its own brief front→act→restore. Reach for `bring_to_front` only \@@ -62,7 +64,9 @@ fn def() -> &'static ToolDef {#[async_trait]impl Tool for BringToFrontTool {- fn def(&self) -> &ToolDef { def() }+ fn def(&self) -> &ToolDef {+ def()+ }async fn invoke(&self, args: Value) -> ToolResult {let pid = match args.get("pid").and_then(Value::as_i64) {@@ -122,11 +126,12 @@ impl Tool for BringToFrontTool {}));}- ToolResult::text(format!("Brought pid {pid} to the foreground."))- .with_structured(serde_json::json!({+ ToolResult::text(format!("Brought pid {pid} to the foreground.")).with_structured(+ serde_json::json!({"pid": pid,"window_id": window_id,"activated": true,- }))+ }),+ )}}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/check_permissions.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/check_permissions.rsindex 60d3f550b2..d81304ec3d 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/check_permissions.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/check_permissions.rs@@ -1,5 +1,8 @@use async_trait::async_trait;-use cua_driver_core::{protocol::ToolResult, tool::{Tool, ToolDef}};+use cua_driver_core::{+ protocol::ToolResult,+ tool::{Tool, ToolDef},+};use serde_json::Value;use crate::permissions::status::{@@ -44,16 +47,14 @@ fn permission_source() -> serde_json::Value {.and_then(|p| std::fs::canonicalize(p).ok()).and_then(|p| p.to_str().map(str::to_owned)).unwrap_or_default();- let disclaimed =- std::env::var_os(cua_driver_core::RESPONSIBILITY_DISCLAIMED_ENV).is_some();+ let disclaimed = std::env::var_os(cua_driver_core::RESPONSIBILITY_DISCLAIMED_ENV).is_some();// Embedded mode: the driver is a child in a host app's responsibility// chain, so the probes already answer for the host's TCC identity.// This branch only ever downgrades attribution (host, never// driver-daemon), so the caller-controlled env var can't spoof an// elevated identity. `host_bundle_id` is advisory, not a trust signal.if cua_driver_core::embedded_mode() {- let host_bundle_id = std::env::var(cua_driver_core::HOST_BUNDLE_ID_ENV)- .unwrap_or_default();+ let host_bundle_id = std::env::var(cua_driver_core::HOST_BUNDLE_ID_ENV).unwrap_or_default();return serde_json::json!({"attribution": "host","host_bundle_id": host_bundle_id,@@ -148,7 +149,9 @@ fn def() -> &'static ToolDef {#[async_trait]impl Tool for CheckPermissionsTool {- fn def(&self) -> &ToolDef { def() }+ fn def(&self) -> &ToolDef {+ def()+ }async fn invoke(&self, args: Value) -> ToolResult {use cua_driver_core::tool_args::ArgsExt;@@ -157,8 +160,7 @@ impl Tool for CheckPermissionsTool {// host owns the grant flow). This and the startup gate are the only// `request_*` call sites, so both being gated makes prompts// unreachable when embedded.- let should_prompt =- args.bool_or("prompt", true) && !cua_driver_core::embedded_mode();+ let should_prompt = args.bool_or("prompt", true) && !cua_driver_core::embedded_mode();if should_prompt {let _ = request_accessibility();let _ = request_screen_recording();@@ -173,10 +175,18 @@ impl Tool for CheckPermissionsTool {// Text format mirrors Swift 1:1:// "✅ Accessibility: granted.\n✅ Screen Recording: granted."- let ax_prefix = if accessibility { "✅" } else { "❌" };- let sr_prefix = if screen_recording { "✅" } else { "❌" };- let ax_state = if accessibility { "granted" } else { "NOT granted" };- let sr_state = if screen_recording { "granted" } else { "NOT granted" };+ let ax_prefix = if accessibility { "✅" } else { "❌" };+ let sr_prefix = if screen_recording { "✅" } else { "❌" };+ let ax_state = if accessibility {+ "granted"+ } else {+ "NOT granted"+ };+ let sr_state = if screen_recording {+ "granted"+ } else {+ "NOT granted"+ };let mut summary = format!("{ax_prefix} Accessibility: {ax_state}.\n{sr_prefix} Screen Recording: {sr_state}.");@@ -203,13 +213,12 @@ impl Tool for CheckPermissionsTool {);}- ToolResult::text(summary)- .with_structured(serde_json::json!({- "accessibility": accessibility,- "screen_recording": screen_recording,- "screen_recording_capturable": screen_recording_capturable,- "source": source,- }))+ ToolResult::text(summary).with_structured(serde_json::json!({+ "accessibility": accessibility,+ "screen_recording": screen_recording,+ "screen_recording_capturable": screen_recording_capturable,+ "source": source,+ }))}}@@ -266,7 +275,10 @@ mod tests {fn embedded_mode_reports_host_attribution() {let _guard = env_lock();let embedded = swap_env(cua_driver_core::EMBEDDED_ENV, Some("1"));- let host = swap_env(cua_driver_core::HOST_BUNDLE_ID_ENV, Some("com.example.host"));+ let host = swap_env(+ cua_driver_core::HOST_BUNDLE_ID_ENV,+ Some("com.example.host"),+ );let source = permission_source();assert_eq!(diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/cursor_tools.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/cursor_tools.rsindex 7f24506b76..71aeeb1230 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/cursor_tools.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/cursor_tools.rs@@ -5,7 +5,10 @@//! where codex wrapper wants control over the cursor icon.use async_trait::async_trait;-use cua_driver_core::{protocol::ToolResult, tool::{Tool, ToolDef}};+use cua_driver_core::{+ protocol::ToolResult,+ tool::{Tool, ToolDef},+};use serde_json::Value;use std::sync::Arc;@@ -42,7 +45,8 @@ pub(crate) fn resolve_cursor_key(args: &Value) -> String {/// call carries no session identity at all, so every such call shares one cursor.fn default_cursor_session() -> String {static ID: std::sync::OnceLock<String> = std::sync::OnceLock::new();- ID.get_or_init(|| format!("auto-{:x}", std::process::id())).clone()+ ID.get_or_init(|| format!("auto-{:x}", std::process::id()))+ .clone()}// ── SetAgentCursorEnabled ─────────────────────────────────────────────────────@@ -52,7 +56,9 @@ pub struct SetAgentCursorEnabledTool {}impl SetAgentCursorEnabledTool {- pub fn new(state: Arc<ToolState>) -> Self { Self { state } }+ pub fn new(state: Arc<ToolState>) -> Self {+ Self { state }+ }}static ENABLED_DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();@@ -84,11 +90,16 @@ fn enabled_def() -> &'static ToolDef {#[async_trait]impl Tool for SetAgentCursorEnabledTool {- fn def(&self) -> &ToolDef { enabled_def() }+ fn def(&self) -> &ToolDef {+ enabled_def()+ }async fn invoke(&self, args: Value) -> ToolResult {use cua_driver_core::tool_args::ArgsExt;- let enabled = match args.require_bool("enabled") { Ok(v) => v, Err(e) => return e };+ let enabled = match args.require_bool("enabled") {+ Ok(v) => v,+ Err(e) => return e,+ };let key = resolve_cursor_key(&args);self.state.cursor_registry.set_enabled(&key, enabled);// Drive the visual overlay for THIS session's cursor.@@ -96,7 +107,11 @@ impl Tool for SetAgentCursorEnabledTool {key.clone(),cursor_overlay::OverlayCommand::SetEnabled(enabled),);- ToolResult::text(format!("Agent cursor '{}' {}.", key, if enabled { "enabled" } else { "disabled" }))+ ToolResult::text(format!(+ "Agent cursor '{}' {}.",+ key,+ if enabled { "enabled" } else { "disabled" }+ ))}}@@ -107,7 +122,9 @@ pub struct SetAgentCursorMotionTool {}impl SetAgentCursorMotionTool {- pub fn new(state: Arc<ToolState>) -> Self { Self { state } }+ pub fn new(state: Arc<ToolState>) -> Self {+ Self { state }+ }}static MOTION_DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();@@ -198,7 +215,9 @@ fn motion_def() -> &'static ToolDef {#[async_trait]impl Tool for SetAgentCursorMotionTool {- fn def(&self) -> &ToolDef { motion_def() }+ fn def(&self) -> &ToolDef {+ motion_def()+ }async fn invoke(&self, args: Value) -> ToolResult {use cua_driver_core::tool_args::ArgsExt;@@ -219,7 +238,9 @@ impl Tool for SetAgentCursorMotionTool {let icon_owned = icon.clone();match tokio::task::spawn_blocking(move || {cursor_overlay::resolve_cursor_icon(&icon_owned)- }).await {+ })+ .await+ {Ok(Ok(resolution)) => {config.cursor_icon = Some(icon);shape_cmd = Some(cursor_overlay::OverlayCommand::from_cursor_icon(resolution));@@ -287,12 +308,16 @@ impl Tool for SetAgentCursorMotionTool {"Cursor '{}' updated. Motion: start={:.2} end={:.2} arc={:.2} flow={:.2} \spring={:.2} glide={}ms dwell={}ms idle={}ms",cursor_id,- new_motion.start_handle, new_motion.end_handle,- new_motion.arc_size, new_motion.arc_flow, new_motion.spring,+ new_motion.start_handle,+ new_motion.end_handle,+ new_motion.arc_size,+ new_motion.arc_flow,+ new_motion.spring,new_motion.glide_duration_ms as u32,new_motion.dwell_after_click_ms as u32,new_motion.idle_hide_ms as u32,- )).with_structured(serde_json::to_value(¤t.config).unwrap_or_default())+ ))+ .with_structured(serde_json::to_value(¤t.config).unwrap_or_default())} else {ToolResult::text(format!("Cursor '{}' config updated.", cursor_id)).with_structured(serde_json::to_value(¤t.config).unwrap_or_default())@@ -307,7 +332,9 @@ pub struct SetAgentCursorStyleTool {}impl SetAgentCursorStyleTool {- pub fn new(state: Arc<ToolState>) -> Self { Self { state } }+ pub fn new(state: Arc<ToolState>) -> Self {+ Self { state }+ }}static STYLE_DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();@@ -359,7 +386,9 @@ fn style_def() -> &'static ToolDef {#[async_trait]impl Tool for SetAgentCursorStyleTool {- fn def(&self) -> &ToolDef { style_def() }+ fn def(&self) -> &ToolDef {+ style_def()+ }async fn invoke(&self, args: Value) -> ToolResult {let cursor_id = resolve_cursor_key(&args);@@ -374,7 +403,9 @@ impl Tool for SetAgentCursorStyleTool {let path_owned = path.to_owned();match tokio::task::spawn_blocking(move || {cursor_overlay::CursorShape::load(&path_owned)- }).await {+ })+ .await+ {Ok(Ok(shape)) => {// Also persist to registry so it's available for state queries.let mut current = self.state.cursor_registry.get_or_create(&cursor_id);@@ -382,7 +413,9 @@ impl Tool for SetAgentCursorStyleTool {self.state.cursor_registry.update_config(current.config);Some(cursor_overlay::OverlayCommand::SetShape(Some(shape)))}- Ok(Err(e)) => return ToolResult::error(format!("Failed to load image_path: {e}")),+ Ok(Err(e)) => {+ return ToolResult::error(format!("Failed to load image_path: {e}"))+ }Err(e) => return ToolResult::error(format!("Task error: {e}")),}}@@ -391,35 +424,37 @@ impl Tool for SetAgentCursorStyleTool {};// ── gradient_colors ───────────────────────────────────────────────────- let gradient_colors: Vec<[u8; 4]> = if let Some(arr) = args.get("gradient_colors").and_then(|v| v.as_array()) {- let mut out = vec![];- for v in arr {- if let Some(hex) = v.as_str() {- match parse_hex_color(hex) {- Some(c) => out.push(c),- None => return ToolResult::error(format!("Invalid hex color: {hex}")),+ let gradient_colors: Vec<[u8; 4]> =+ if let Some(arr) = args.get("gradient_colors").and_then(|v| v.as_array()) {+ let mut out = vec![];+ for v in arr {+ if let Some(hex) = v.as_str() {+ match parse_hex_color(hex) {+ Some(c) => out.push(c),+ None => return ToolResult::error(format!("Invalid hex color: {hex}")),+ }}}- }- out- } else {- // Not provided — don't change.- vec![]- };+ out+ } else {+ // Not provided — don't change.+ vec![]+ };// ── bloom_color ───────────────────────────────────────────────────────- let bloom_color: Option<Option<[u8; 4]>> = if let Some(hex) = args.get("bloom_color").and_then(|v| v.as_str()) {- if hex.is_empty() {- Some(None) // revert- } else {- match parse_hex_color(hex) {- Some(c) => Some(Some(c)),- None => return ToolResult::error(format!("Invalid bloom_color: {hex}")),+ let bloom_color: Option<Option<[u8; 4]>> =+ if let Some(hex) = args.get("bloom_color").and_then(|v| v.as_str()) {+ if hex.is_empty() {+ Some(None) // revert+ } else {+ match parse_hex_color(hex) {+ Some(c) => Some(Some(c)),+ None => return ToolResult::error(format!("Invalid bloom_color: {hex}")),+ }}- }- } else {- None- };+ } else {+ None+ };// ── Dispatch to overlay (keyed to this session's cursor) ──────────────if let Some(cmd) = shape_cmd {@@ -439,23 +474,38 @@ impl Tool for SetAgentCursorStyleTool {}// Build response summary.- let grad_str = args.get("gradient_colors")+ let grad_str = args+ .get("gradient_colors").and_then(|v| v.as_array()).map(|arr| {- let strs: Vec<String> = arr.iter()+ let strs: Vec<String> = arr+ .iter().filter_map(|v| v.as_str().map(str::to_owned)).collect();format!("[{}]", strs.join(", "))}).unwrap_or_else(|| "(unchanged)".into());- let bloom_str = args.get("bloom_color")+ let bloom_str = args+ .get("bloom_color").and_then(|v| v.as_str())- .map(|s| if s.is_empty() { "(reverted)".to_owned() } else { s.to_owned() })+ .map(|s| {+ if s.is_empty() {+ "(reverted)".to_owned()+ } else {+ s.to_owned()+ }+ }).unwrap_or_else(|| "(unchanged)".into());let img_str = image_path- .map(|s| if s.is_empty() { "(reverted to default)".to_owned() } else { s.to_owned() })+ .map(|s| {+ if s.is_empty() {+ "(reverted to default)".to_owned()+ } else {+ s.to_owned()+ }+ }).unwrap_or_else(|| "(unchanged)".into());ToolResult::text(format!(@@ -491,7 +541,9 @@ pub struct GetAgentCursorStateTool {}impl GetAgentCursorStateTool {- pub fn new(state: Arc<ToolState>) -> Self { Self { state } }+ pub fn new(state: Arc<ToolState>) -> Self {+ Self { state }+ }}static STATE_DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();@@ -518,7 +570,9 @@ fn state_def() -> &'static ToolDef {#[async_trait]impl Tool for GetAgentCursorStateTool {- fn def(&self) -> &ToolDef { state_def() }+ fn def(&self) -> &ToolDef {+ state_def()+ }async fn invoke(&self, args: Value) -> ToolResult {// Scope to the CALLER's cursor (explicit cursor_id > injected@@ -536,8 +590,12 @@ impl Tool for GetAgentCursorStateTool {let enabled = state.as_ref().map(|s| s.config.enabled).unwrap_or(true);let cursors: Vec<&crate::cursor::CursorState> = state.iter().collect();let json = serde_json::to_value(&cursors).unwrap_or_default();- ToolResult::text(format!("{} cursor instance(s) for '{}'.", cursors.len(), key))- .with_structured(serde_json::json!({ "cursors": json, "enabled": enabled }))+ ToolResult::text(format!(+ "{} cursor instance(s) for '{}'.",+ cursors.len(),+ key+ ))+ .with_structured(serde_json::json!({ "cursors": json, "enabled": enabled }))}}@@ -557,20 +615,32 @@ mod tests {let b = resolve_cursor_key(&json!({ "x": 1 }));assert!(a.starts_with("auto-"), "got {a}");assert_ne!(a, "");- assert_eq!(a, b, "the anonymous default must stay the same across calls");+ assert_eq!(+ a, b,+ "the anonymous default must stay the same across calls"+ );// The minted per-run `_session_id` now DOES drive the cursor (consistent run id).- assert_eq!(resolve_cursor_key(&json!({ "_session_id": "mcp-1-2" })), "mcp-1-2");+ assert_eq!(+ resolve_cursor_key(&json!({ "_session_id": "mcp-1-2" })),+ "mcp-1-2"+ );}#[test]fn explicit_session_owns_a_cursor() {- assert_eq!(resolve_cursor_key(&json!({ "session": "research-run" })), "research-run");+ assert_eq!(+ resolve_cursor_key(&json!({ "session": "research-run" })),+ "research-run"+ );}#[test]fn cursor_id_is_a_legacy_alias() {// `cursor_id` still works (codex-wrapper use case); `session` wins if both.- assert_eq!(resolve_cursor_key(&json!({ "cursor_id": "user-handle" })), "user-handle");+ assert_eq!(+ resolve_cursor_key(&json!({ "cursor_id": "user-handle" })),+ "user-handle"+ );assert_eq!(resolve_cursor_key(&json!({ "session": "s1", "cursor_id": "c1" })),"s1"@@ -609,8 +679,10 @@ mod tests {let enable_key = resolve_cursor_key(&enable_args);let click_key = resolve_cursor_key(&ax_click_args);assert_eq!(enable_key, session);- assert_eq!(enable_key, click_key,- "set_agent_cursor_enabled and the AX click must drive the same session cursor");+ assert_eq!(+ enable_key, click_key,+ "set_agent_cursor_enabled and the AX click must drive the same session cursor"+ );}#[test]diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rsindex 3708e5ec61..f9fdafc0be 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs@@ -1,11 +1,13 @@use async_trait::async_trait;-use cua_driver_core::{protocol::ToolResult, tool::{Tool, ToolDef}};+use cua_driver_core::{+ protocol::ToolResult,+ tool::{Tool, ToolDef},+};use serde_json::Value;use std::sync::Arc;use crate::ax::bindings::{- copy_action_names, element_screen_center, perform_action, kAXErrorSuccess,- AXUIElementRef,+ copy_action_names, element_screen_center, kAXErrorSuccess, perform_action, AXUIElementRef,};use super::ToolState;@@ -15,7 +17,9 @@ pub struct DoubleClickTool {}impl DoubleClickTool {- pub fn new(state: Arc<ToolState>) -> Self { Self { state } }+ pub fn new(state: Arc<ToolState>) -> Self {+ Self { state }+ }}static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();@@ -54,11 +58,16 @@ fn def() -> &'static ToolDef {#[async_trait]impl Tool for DoubleClickTool {- fn def(&self) -> &ToolDef { def() }+ fn def(&self) -> &ToolDef {+ def()+ }async fn invoke(&self, args: Value) -> ToolResult {use cua_driver_core::tool_args::ArgsExt;- let pid = match args.require_i32("pid") { Ok(v) => v, Err(e) => return e };+ let pid = match args.require_i32("pid") {+ Ok(v) => v,+ Err(e) => return e,+ };// delivery_mode: foreground briefly fronts the window before the pixel// double-click (the explicit last resort for surfaces that drop// background CGEvents), via the same skylight assist click uses.@@ -67,7 +76,7 @@ impl Tool for DoubleClickTool {// Surface 6: token / index precedence — see click.rs for the// canonical comment.let element_token_arg = args.opt_str("element_token");- let window_id_arg = args.opt_u64("window_id").map(|v| v as u32);+ let window_id_arg = args.opt_u64("window_id").map(|v| v as u32);let element_index_arg = args.opt_u64("element_index").map(|v| v as usize);let resolved = match cua_driver_core::element_token::resolve_element_args(pid,@@ -82,7 +91,9 @@ impl Tool for DoubleClickTool {let (element_index, window_id) = match resolved {cua_driver_core::element_token::ResolvedElement::None => (None, window_id_arg),cua_driver_core::element_token::ResolvedElement::Element {- window_id: wid, element_index: idx, via_token: _,+ window_id: wid,+ element_index: idx,+ via_token: _,} => (Some(idx), wid),};@@ -92,9 +103,11 @@ impl Tool for DoubleClickTool {// free the element mid-action (use-after-free → daemon crash).let element_guard = match self.state.element_cache.get_element_retained(pid, wid, idx) {Some(e) => e,- None => return ToolResult::error(format!(- "Element index {idx} not found. Call get_window_state first."- )),+ None => {+ return ToolResult::error(format!(+ "Element index {idx} not found. Call get_window_state first."+ ))+ }};let element_ptr = element_guard.as_ptr();@@ -103,21 +116,24 @@ impl Tool for DoubleClickTool {let ck = cursor_key.clone();let result = tokio::task::spawn_blocking(move || {ax_double_click(pid, wid, element_ptr, idx, &ck)- }).await;+ })+ .await;return match result {- Ok(Ok(msg)) => ToolResult::text(msg),- Ok(Err(e)) => ToolResult::error(format!("double_click failed: {e}")),- Err(e) => ToolResult::error(format!("Task error: {e}")),+ Ok(Ok(msg)) => ToolResult::text(msg),+ Ok(Err(e)) => ToolResult::error(format!("double_click failed: {e}")),+ Err(e) => ToolResult::error(format!("Task error: {e}")),};}// ── Pixel path ───────────────────────────────────────────────────────let mut cx = match args.get("x").and_then(|v| v.as_f64()) {Some(v) => v,- None => return ToolResult::error(- "Either element_index + window_id or x + y must be provided."- ),+ None => {+ return ToolResult::error(+ "Either element_index + window_id or x + y must be provided.",+ )+ }};let mut cy = match args.get("y").and_then(|v| v.as_f64()) {Some(v) => v,@@ -138,14 +154,27 @@ impl Tool for DoubleClickTool {let scale: f64 = if let Some(ref b) = bounds {if let Ok(png) = crate::capture::screenshot_window_bytes(wid) {if png.len() >= 24 {- let pw = u32::from_be_bytes([png[16], png[17], png[18], png[19]]) as f64;+ let pw =+ u32::from_be_bytes([png[16], png[17], png[18], png[19]]) as f64;let lw = b.width;- if lw > 0.0 && pw > lw { pw / lw } else { 1.0 }- } else { 1.0 }- } else { 1.0 }- } else { 1.0 };+ if lw > 0.0 && pw > lw {+ pw / lw+ } else {+ 1.0+ }+ } else {+ 1.0+ }+ } else {+ 1.0+ }+ } else {+ 1.0+ };(bounds, scale)- }).await.unwrap_or((None, 1.0));+ })+ .await+ .unwrap_or((None, 1.0));if let (Some(b), scale) = result {let wx = cx / scale;let wy = cy / scale;@@ -168,7 +197,10 @@ impl Tool for DoubleClickTool {crate::cursor::overlay::animate_cursor_to(cursor_key.clone(), screen_x, screen_y).await;crate::cursor::overlay::send_command(cursor_key.clone(),- cursor_overlay::OverlayCommand::ClickPulse { x: screen_x, y: screen_y },+ cursor_overlay::OverlayCommand::ClickPulse {+ x: screen_x,+ y: screen_y,+ },);let fg = delivery_mode.is_foreground() && window_id.is_some();@@ -176,7 +208,14 @@ impl Tool for DoubleClickTool {let do_click = move || -> anyhow::Result<()> {if let Some(wid) = window_id {crate::input::mouse::click_at_xy_with_window_local(- pid, screen_x, screen_y, win_local_x, win_local_y, wid, 2, &[],+ pid,+ screen_x,+ screen_y,+ win_local_x,+ win_local_y,+ wid,+ 2,+ &[],)} else {crate::input::mouse::click_at_xy(pid, screen_x, screen_y, 2, &[])@@ -185,14 +224,23 @@ impl Tool for DoubleClickTool {// Foreground rung: brief front → double-click → restore prior frontmost.match (fg, window_id) {(true, Some(wid)) => {- crate::input::skylight::with_foreground_assist(pid as libc::pid_t, wid, do_click)?;+ crate::input::skylight::with_foreground_assist(+ pid as libc::pid_t,+ wid,+ do_click,+ )?;Ok(())}_ => do_click(),}- }).await;+ })+ .await;- let mode_label = if fg { " (delivery_mode:foreground)" } else { "" };+ let mode_label = if fg {+ " (delivery_mode:foreground)"+ } else {+ ""+ };match result {Ok(Ok(())) => ToolResult::text(format!("✅ Double-clicked at ({screen_x:.1}, {screen_y:.1}){mode_label}.")).with_structured(serde_json::json!({@@ -206,7 +254,13 @@ impl Tool for DoubleClickTool {// ── Blocking AX path ─────────────────────────────────────────────────────────-fn ax_double_click(pid: i32, wid: u32, element_ptr: usize, idx: usize, cursor_key: &str) -> anyhow::Result<String> {+fn ax_double_click(+ pid: i32,+ wid: u32,+ element_ptr: usize,+ idx: usize,+ cursor_key: &str,+) -> anyhow::Result<String> {let element = element_ptr as AXUIElementRef;// Try AXOpen first (Finder items, openable list rows, document cells).@@ -216,7 +270,9 @@ fn ax_double_click(pid: i32, wid: u32, element_ptr: usize, idx: usize, cursor_keif err == kAXErrorSuccess {return Ok(format!("AXOpen performed on element [{idx}]."));}- tracing::debug!("AXOpen returned {err} for element [{idx}], falling back to pixel double-click");+ tracing::debug!(+ "AXOpen returned {err} for element [{idx}], falling back to pixel double-click"+ );}// Resolve screen center and fall back to pixel double-click.@@ -239,10 +295,14 @@ fn ax_double_click(pid: i32, wid: u32, element_ptr: usize, idx: usize, cursor_ke// the wrong location while still routing to `wid`.let (wx, wy) = crate::windows::window_bounds_by_id(wid).map(|b| (cx - b.x, cy - b.y))- .ok_or_else(|| anyhow::anyhow!(- "Cannot resolve window bounds for window_id {wid}; refusing to stamp \+ .ok_or_else(|| {+ anyhow::anyhow!(+ "Cannot resolve window bounds for window_id {wid}; refusing to stamp \screen coordinates as window-local for element [{idx}]."- ))?;+ )+ })?;crate::input::mouse::click_at_xy_with_window_local(pid, cx, cy, wx, wy, wid, 2, &[])?;- Ok(format!("✅ Double-clicked element [{idx}] at ({cx:.1}, {cy:.1})."))+ Ok(format!(+ "✅ Double-clicked element [{idx}] at ({cx:.1}, {cy:.1})."+ ))}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_accessibility_tree.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_accessibility_tree.rsindex 79ffc0c3f5..c66c8d8cf1 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_accessibility_tree.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_accessibility_tree.rs@@ -5,7 +5,10 @@//! `get_window_state` with `capture_mode="ax"` to skip the screenshot).use async_trait::async_trait;-use cua_driver_core::{protocol::ToolResult, tool::{Tool, ToolDef}};+use cua_driver_core::{+ protocol::ToolResult,+ tool::{Tool, ToolDef},+};use serde_json::Value;use std::sync::Arc;@@ -16,7 +19,9 @@ pub struct GetAccessibilityTreeTool {}impl GetAccessibilityTreeTool {- pub fn new(state: Arc<ToolState>) -> Self { Self { state } }+ pub fn new(state: Arc<ToolState>) -> Self {+ Self { state }+ }}static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();@@ -24,8 +29,7 @@ static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();fn def() -> &'static ToolDef {DEF.get_or_init(|| ToolDef {name: "get_accessibility_tree".into(),- description:- "Return a lightweight snapshot of the desktop: running regular apps and \+ description: "Return a lightweight snapshot of the desktop: running regular apps and \on-screen visible windows with their bounds, z-order, and owner pid.\n\n\For the full AX subtree of a single window (with interactive element indices \you can click by), use `get_window_state` instead — that's the heavy per-window \@@ -36,30 +40,35 @@ fn def() -> &'static ToolDef {"properties": {},"additionalProperties": false}),- read_only: true,+ read_only: true,destructive: false,- idempotent: true,- open_world: false,+ idempotent: true,+ open_world: false,})}#[async_trait]impl Tool for GetAccessibilityTreeTool {- fn def(&self) -> &ToolDef { def() }+ fn def(&self) -> &ToolDef {+ def()+ }async fn invoke(&self, _args: Value) -> ToolResult {let _ = &self.state; // state not needed for this tool- let apps = crate::apps::list_running_apps();+ let apps = crate::apps::list_running_apps();let windows = crate::windows::visible_windows();let mut lines = vec![format!("{} running app(s), {} visible window(s)",- apps.len(), windows.len()+ apps.len(),+ windows.len())];for app in &apps {- let bid = app.bundle_id.as_deref()+ let bid = app+ .bundle_id+ .as_deref().map(|b| format!(" [{b}]")).unwrap_or_default();lines.push(format!("- {} (pid {}){}", app.name, app.pid, bid));@@ -80,7 +89,7 @@ impl Tool for GetAccessibilityTreeTool {));}lines.push(- "→ Call get_window_state(pid, window_id) to inspect a window's UI.".to_owned()+ "→ Call get_window_state(pid, window_id) to inspect a window's UI.".to_owned(),);}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_cursor_position.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_cursor_position.rsindex 5a33fb77a9..f0466c81b3 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_cursor_position.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_cursor_position.rs@@ -1,5 +1,8 @@use async_trait::async_trait;-use cua_driver_core::{protocol::ToolResult, tool::{Tool, ToolDef}};+use cua_driver_core::{+ protocol::ToolResult,+ tool::{Tool, ToolDef},+};use serde_json::Value;pub struct GetCursorPositionTool;@@ -20,7 +23,9 @@ fn def() -> &'static ToolDef {#[async_trait]impl Tool for GetCursorPositionTool {- fn def(&self) -> &ToolDef { def() }+ fn def(&self) -> &ToolDef {+ def()+ }async fn invoke(&self, _args: Value) -> ToolResult {// Create a null event and query its location to get cursor position.@@ -32,11 +37,11 @@ impl Tool for GetCursorPositionTool {let result = tokio::task::spawn_blocking(|| {let source = CGEventSource::new(CGEventSourceStateID::HIDSystemState).map_err(|_| anyhow::anyhow!("CGEventSource::new failed"))?;- let event = CGEvent::new(source)- .map_err(|_| anyhow::anyhow!("CGEvent::new failed"))?;+ let event = CGEvent::new(source).map_err(|_| anyhow::anyhow!("CGEvent::new failed"))?;let loc = event.location();Ok::<(f64, f64), anyhow::Error>((loc.x, loc.y))- }).await;+ })+ .await;match result {Ok(Ok((x, y))) => {diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_desktop_state.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_desktop_state.rsindex fa2da56381..18d424f527 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_desktop_state.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_desktop_state.rs@@ -12,7 +12,10 @@//! `structuredContent` object.use async_trait::async_trait;-use cua_driver_core::{protocol::{ToolResult, Content}, tool::{Tool, ToolDef}};+use cua_driver_core::{+ protocol::{Content, ToolResult},+ tool::{Tool, ToolDef},+};use serde_json::Value;use super::get_screen_size::main_screen_size;@@ -47,7 +50,9 @@ fn def() -> &'static ToolDef {#[async_trait]impl Tool for GetDesktopStateTool {- fn def(&self) -> &ToolDef { def() }+ fn def(&self) -> &ToolDef {+ def()+ }async fn invoke(&self, args: Value) -> ToolResult {use cua_driver_core::tool_args::ArgsExt;@@ -116,7 +121,11 @@ impl Tool for GetDesktopStateTool {structured["screenshot_file_path"] = serde_json::json!(fp);}- ToolResult { content, is_error: None, structured_content: Some(structured) }+ ToolResult {+ content,+ is_error: None,+ structured_content: Some(structured),+ }}}@@ -134,11 +143,20 @@ mod tests {let props = d.input_schema["properties"].as_object().unwrap();assert!(!props.contains_key("pid"), "must not accept pid");- assert!(!props.contains_key("window_id"), "must not accept window_id");- assert!(!props.contains_key("capture_mode"), "must not accept capture_mode");+ assert!(+ !props.contains_key("window_id"),+ "must not accept window_id"+ );+ assert!(+ !props.contains_key("capture_mode"),+ "must not accept capture_mode"+ );assert!(props.contains_key("session"));assert!(props.contains_key("screenshot_out_file"));- assert_eq!(d.input_schema["additionalProperties"], serde_json::json!(false));+ assert_eq!(+ d.input_schema["additionalProperties"],+ serde_json::json!(false)+ );}#[test]diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_screen_size.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_screen_size.rsindex dc39dee39a..85ec8792a4 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_screen_size.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_screen_size.rs@@ -1,5 +1,8 @@use async_trait::async_trait;-use cua_driver_core::{protocol::ToolResult, tool::{Tool, ToolDef}};+use cua_driver_core::{+ protocol::ToolResult,+ tool::{Tool, ToolDef},+};use serde_json::Value;pub struct GetScreenSizeTool;@@ -23,7 +26,9 @@ fn def() -> &'static ToolDef {#[async_trait]impl Tool for GetScreenSizeTool {- fn def(&self) -> &ToolDef { def() }+ fn def(&self) -> &ToolDef {+ def()+ }async fn invoke(&self, _args: Value) -> ToolResult {match main_screen_size() {@@ -46,7 +51,7 @@ impl Tool for GetScreenSizeTool {/// which always returns `None` on async tokio threads, causing the tool to/// return an error even when a display is attached.pub(crate) fn main_screen_size() -> Option<(i64, i64, f64)> {- use core_graphics::display::{CGMainDisplayID, CGDisplayBounds};+ use core_graphics::display::{CGDisplayBounds, CGMainDisplayID};// SAFETY: CGMainDisplayID / CGDisplayBounds are thread-safe CG APIs.let display_id = unsafe { CGMainDisplayID() };diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rsindex c1f86a39db..9e484ca337 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs@@ -1,5 +1,8 @@use async_trait::async_trait;-use cua_driver_core::{protocol::{ToolResult, Content}, tool::{Tool, ToolDef}};+use cua_driver_core::{+ protocol::{Content, ToolResult},+ tool::{Tool, ToolDef},+};use serde_json::Value;use std::sync::Arc;@@ -10,7 +13,9 @@ pub struct GetWindowStateTool {}impl GetWindowStateTool {- pub fn new(state: Arc<ToolState>) -> Self { Self { state } }+ pub fn new(state: Arc<ToolState>) -> Self {+ Self { state }+ }}static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();@@ -89,12 +94,20 @@ fn def() -> &'static ToolDef {#[async_trait]impl Tool for GetWindowStateTool {- fn def(&self) -> &ToolDef { def() }+ fn def(&self) -> &ToolDef {+ def()+ }async fn invoke(&self, args: Value) -> ToolResult {use cua_driver_core::tool_args::ArgsExt;- let pid = match args.require_i32("pid") { Ok(v) => v, Err(e) => return e };- let window_id = match args.require_u32("window_id") { Ok(v) => v, Err(e) => return e };+ let pid = match args.require_i32("pid") {+ Ok(v) => v,+ Err(e) => return e,+ };+ let window_id = match args.require_u32("window_id") {+ Ok(v) => v,+ Err(e) => return e,+ };let query = args.opt_str("query");let screenshot_out_file = args.opt_str("screenshot_out_file").map(|s| {// Expand ~ prefix.@@ -110,7 +123,9 @@ impl Tool for GetWindowStateTool {let session_id = args.opt_str("_session_id");let effective_max_dim = {let cfg = self.state.config.read().unwrap();- self.state.session_config.effective_max_image_dimension(session_id.as_deref(), &cfg)+ self.state+ .session_config+ .effective_max_image_dimension(session_id.as_deref(), &cfg)};// `capture_mode` is DEPRECATED and ignored — get_window_state always// returns BOTH the tree and a screenshot now, so the agent grounds on@@ -206,7 +221,9 @@ impl Tool for GetWindowStateTool {// Record resize ratio so ClickTool can scale coordinates back up.if let Some(ow) = orig_w {if w > 0 {- self.state.resize_registry.set_ratio(pid, ow as f64 / w as f64);+ self.state+ .resize_registry+ .set_ratio(pid, ow as f64 / w as f64);}} else {self.state.resize_registry.clear_ratio(pid);@@ -258,11 +275,16 @@ impl Tool for GetWindowStateTool {}if content.is_empty() {- return ToolResult::error("No content produced (neither AX tree nor screenshot succeeded)");+ return ToolResult::error(+ "No content produced (neither AX tree nor screenshot succeeded)",+ );}let element_count = self.state.element_cache.element_count(pid, window_id);- let tree_md = tree_result.as_ref().map(|r| r.tree_markdown.clone()).unwrap_or_default();+ let tree_md = tree_result+ .as_ref()+ .map(|r| r.tree_markdown.clone())+ .unwrap_or_default();// Surface 6: register a snapshot in the global token registry so// every actionable element gets an opaque `element_token` keyed@@ -275,8 +297,11 @@ impl Tool for GetWindowStateTool {.as_ref().map(|r| r.nodes.iter().filter(|n| n.element_index.is_some()).count()).unwrap_or(0);- let snapshot_id = cua_driver_core::element_token::global()- .register_snapshot(pid, window_id, elem_count_for_snapshot);+ let snapshot_id = cua_driver_core::element_token::global().register_snapshot(+ pid,+ window_id,+ elem_count_for_snapshot,+ );// Build the structured `elements` array — one entry per actionable// node, matching the order (and indices) of the markdown rendering.@@ -349,7 +374,11 @@ impl Tool for GetWindowStateTool {if let Some(ref fp) = screenshot_file_path {structured["screenshot_file_path"] = serde_json::json!(fp);}- ToolResult { content, is_error: None, structured_content: Some(structured) }+ ToolResult {+ content,+ is_error: None,+ structured_content: Some(structured),+ }}}@@ -380,9 +409,9 @@ pub(crate) fn build_elements_array_with_token(.or_else(|| node.description.clone()).or_else(|| node.value.clone()).or_else(|| node.identifier.clone());- let frame = node.frame.map(|[x, y, w, h]| {- serde_json::json!({ "x": x, "y": y, "w": w, "h": h })- });+ let frame = node+ .frame+ .map(|[x, y, w, h]| serde_json::json!({ "x": x, "y": y, "w": w, "h": h }));let mut entry = serde_json::json!({"element_index": idx,// Surface 6: opaque token paired to the integer index.@@ -444,7 +473,14 @@ mod tests {use super::*;use crate::ax::tree::AXNode;- fn node(idx: Option<usize>, role: &str, title: Option<&str>, depth: usize, parent: Option<usize>, frame: Option<[f64; 4]>) -> AXNode {+ fn node(+ idx: Option<usize>,+ role: &str,+ title: Option<&str>,+ depth: usize,+ parent: Option<usize>,+ frame: Option<[f64; 4]>,+ ) -> AXNode {AXNode {element_index: idx,role: role.into(),@@ -465,25 +501,59 @@ mod tests {fn elements_match_indexed_node_count() {// Mix of indexed + non-indexed nodes; only indexed should surface.let nodes = vec![- node(Some(0), "AXWindow", Some("Doc"), 0, None, Some([0.0, 0.0, 800.0, 600.0])),+ node(+ Some(0),+ "AXWindow",+ Some("Doc"),+ 0,+ None,+ Some([0.0, 0.0, 800.0, 600.0]),+ ),node(None, "AXStaticText", Some("hint"), 1, Some(0), None),- node(Some(1), "AXButton", Some("OK"), 1, Some(0), Some([10.0, 20.0, 60.0, 24.0])),- node(Some(2), "AXButton", Some("Cancel"), 1, Some(0), Some([80.0, 20.0, 60.0, 24.0])),+ node(+ Some(1),+ "AXButton",+ Some("OK"),+ 1,+ Some(0),+ Some([10.0, 20.0, 60.0, 24.0]),+ ),+ node(+ Some(2),+ "AXButton",+ Some("Cancel"),+ 1,+ Some(0),+ Some([80.0, 20.0, 60.0, 24.0]),+ ),];let elements = build_elements_array(&nodes);- assert_eq!(elements.len(), 3, "non-actionable rows must be filtered out");+ assert_eq!(+ elements.len(),+ 3,+ "non-actionable rows must be filtered out"+ );let indices: Vec<u64> = elements.iter().map(|e| e["element_index"].as_u64().unwrap()).collect();- assert_eq!(indices, vec![0, 1, 2], "ordering must match DFS / element_index assignment");+ assert_eq!(+ indices,+ vec![0, 1, 2],+ "ordering must match DFS / element_index assignment"+ );}#[test]fn elements_shape_carries_role_label_frame_parent_depth() {- let nodes = vec![- node(Some(7), "AXButton", Some("Go"), 3, Some(2), Some([1.5, 2.5, 33.0, 44.0])),- ];+ let nodes = vec![node(+ Some(7),+ "AXButton",+ Some("Go"),+ 3,+ Some(2),+ Some([1.5, 2.5, 33.0, 44.0]),+ )];let entry = &build_elements_array(&nodes)[0];assert_eq!(entry["element_index"], 7);assert_eq!(entry["role"], "AXButton");@@ -502,13 +572,21 @@ mod tests {// A field with BOTH a title and a value (e.g. WhatsApp's "Compose// message" box holding typed text): label is the title, but the typed// value must ALSO be exposed so the caller can verify what landed.- let mut nodes = vec![- node(Some(0), "AXTextArea", Some("Compose message"), 1, None, None),- ];+ let mut nodes = vec![node(+ Some(0),+ "AXTextArea",+ Some("Compose message"),+ 1,+ None,+ None,+ )];nodes[0].value = Some("i love u".into());let entry = &build_elements_array(&nodes)[0];assert_eq!(entry["label"], "Compose message", "label stays the title");- assert_eq!(entry["value"], "i love u", "value must be surfaced separately");+ assert_eq!(+ entry["value"], "i love u",+ "value must be surfaced separately"+ );}#[test]@@ -523,13 +601,20 @@ mod tests {#[test]fn elements_omit_optional_fields_when_missing() {- let nodes = vec![- node(Some(0), "AXUnknown", None, 0, None, None),- ];+ let nodes = vec![node(Some(0), "AXUnknown", None, 0, None, None)];let entry = &build_elements_array(&nodes)[0];- assert!(entry.get("label").is_none(), "label must be omitted when title/value/desc/id are all empty");- assert!(entry.get("frame").is_none(), "frame must be omitted when no rect was captured");- assert!(entry.get("parent_index").is_none(), "parent_index must be omitted at the root");+ assert!(+ entry.get("label").is_none(),+ "label must be omitted when title/value/desc/id are all empty"+ );+ assert!(+ entry.get("frame").is_none(),+ "frame must be omitted when no rect was captured"+ );+ assert!(+ entry.get("parent_index").is_none(),+ "parent_index must be omitted at the root"+ );assert_eq!(entry["role"], "AXUnknown");assert_eq!(entry["depth"], 0);}@@ -569,8 +654,13 @@ mod tests {assert_eq!(entries.len(), 3);// Every entry must have BOTH fields (additive contract).for e in &entries {- assert!(e.get("element_index").is_some(), "element_index must remain");- let tok = e.get("element_token").and_then(|v| v.as_str())+ assert!(+ e.get("element_index").is_some(),+ "element_index must remain"+ );+ let tok = e+ .get("element_token")+ .and_then(|v| v.as_str()).expect("element_token must be a string");assert!(tok.starts_with('s'), "token must use the 's' prefix: {tok}");assert!(tok.contains(':'), "token must be `s{{hex}}:{{idx}}`: {tok}");@@ -591,9 +681,7 @@ mod tests {/// through get a clean shape.#[test]fn build_elements_array_shim_skips_element_token() {- let nodes = vec![- node(Some(0), "AXButton", Some("A"), 1, None, None),- ];+ let nodes = vec![node(Some(0), "AXButton", Some("A"), 1, None, None)];let entries = build_elements_array(&nodes);assert_eq!(entries.len(), 1);assert!(@@ -617,12 +705,18 @@ mod tests {// exercises the early-return path; the assertion is that the call// honors the cap without overflowing or panicking.assert!(r1.nodes.len() <= 5, "max_elements=5 must cap nodes ≤ 5");- assert!(r1.nodes.iter().all(|n| n.depth <= 2), "max_depth=2 must cap depth ≤ 2");+ assert!(+ r1.nodes.iter().all(|n| n.depth <= 2),+ "max_depth=2 must cap depth ≤ 2"+ );// And the uncapped variant — same dead-pid path, just validating// walk_tree(...) (which delegates to walk_tree_bounded with// DEFAULT_MAX_*) returns the same empty/safe shape.let r2 = crate::ax::tree::walk_tree(i32::MAX, None, None);- assert_eq!(r1.nodes.len(), r2.nodes.len(),- "no-pid case: both bounded and unbounded must agree on the empty result");+ assert_eq!(+ r1.nodes.len(),+ r2.nodes.len(),+ "no-pid case: both bounded and unbounded must agree on the empty result"+ );}}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/health_report.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/health_report.rsindex c46e55aebe..a1dd789d0d 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/health_report.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/health_report.rs@@ -16,9 +16,7 @@ use cua_driver_core::health_report::{NAME_SESSION_ACTIVE, NAME_TCC_ACCESSIBILITY, NAME_TCC_SCREEN_RECORDING,};-use crate::permissions::status::{- accessibility_granted, current_status, screen_recording_granted,-};+use crate::permissions::status::{accessibility_granted, current_status, screen_recording_granted};/// macOS run order, in the order consumers see them reflected back in/// `report.checks[]`. Matches the Swift PR #1905 contract.diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/kill_app.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/kill_app.rsindex 428e214cee..3683d9480e 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/kill_app.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/kill_app.rs@@ -11,7 +11,10 @@//! agent can't interact with.use async_trait::async_trait;-use cua_driver_core::{protocol::ToolResult, tool::{Tool, ToolDef}};+use cua_driver_core::{+ protocol::ToolResult,+ tool::{Tool, ToolDef},+};use serde_json::Value;pub struct KillAppTool;@@ -21,8 +24,7 @@ static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();fn def() -> &'static ToolDef {DEF.get_or_init(|| ToolDef {name: "kill_app".into(),- description:- "Force-terminate a process by pid (kill -9 equivalent on macOS / Linux; \+ description: "Force-terminate a process by pid (kill -9 equivalent on macOS / Linux; \taskkill /F equivalent on Windows). Use as escalation when the cooperative \close path (hotkey cmd+q on macOS, click-the-X on Windows) failed to make \the process exit. Unsaved state is lost — prefer the cooperative path first."@@ -44,13 +46,21 @@ fn def() -> &'static ToolDef {#[async_trait]impl Tool for KillAppTool {- fn def(&self) -> &ToolDef { def() }+ fn def(&self) -> &ToolDef {+ def()+ }async fn invoke(&self, args: Value) -> ToolResult {let pid_i = match args.get("pid").and_then(|v| v.as_i64()) {Some(p) if p > 0 && p <= i32::MAX as i64 => p as i32,- Some(_) => return ToolResult::error("kill_app: `pid` must be a positive integer".to_string()),- None => return ToolResult::error("kill_app: missing required integer field `pid`".to_string()),+ Some(_) => {+ return ToolResult::error("kill_app: `pid` must be a positive integer".to_string())+ }+ None => {+ return ToolResult::error(+ "kill_app: missing required integer field `pid`".to_string(),+ )+ }};// libc::kill is fast and synchronous; no need to spawn_blocking.diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/list_apps.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/list_apps.rsindex df1f774bf3..79d60feb9b 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/list_apps.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/list_apps.rs@@ -1,5 +1,8 @@use async_trait::async_trait;-use cua_driver_core::{protocol::ToolResult, tool::{Tool, ToolDef}};+use cua_driver_core::{+ protocol::ToolResult,+ tool::{Tool, ToolDef},+};use serde_json::Value;pub struct ListAppsTool;@@ -26,7 +29,8 @@ fn def() -> &'static ToolDef {per-window state — on-screen, on-current-Space, minimized, \window titles — call list_windows instead. For just opening an \app — running or not — call launch_app({bundle_id: ...}) directly; \- list_apps is not a prerequisite.".into(),+ list_apps is not a prerequisite."+ .into(),input_schema: serde_json::json!({"type": "object","properties": {},@@ -41,10 +45,13 @@ fn def() -> &'static ToolDef {#[async_trait]impl Tool for ListAppsTool {- fn def(&self) -> &ToolDef { def() }+ fn def(&self) -> &ToolDef {+ def()+ }async fn invoke(&self, _args: Value) -> ToolResult {- let apps = tokio::task::spawn_blocking(crate::apps::list_all_apps).await+ let apps = tokio::task::spawn_blocking(crate::apps::list_all_apps)+ .await.unwrap_or_default();let text = crate::apps::format_app_list(&apps);// Single flat array. Each entry is the unified shape — existingdiff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/list_windows.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/list_windows.rsindex d8b512ede2..db2cab0e2d 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/list_windows.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/list_windows.rs@@ -1,5 +1,8 @@use async_trait::async_trait;-use cua_driver_core::{protocol::ToolResult, tool::{Tool, ToolDef}};+use cua_driver_core::{+ protocol::ToolResult,+ tool::{Tool, ToolDef},+};use serde_json::Value;pub struct ListWindowsTool;@@ -38,7 +41,9 @@ fn def() -> &'static ToolDef {#[async_trait]impl Tool for ListWindowsTool {- fn def(&self) -> &ToolDef { def() }+ fn def(&self) -> &ToolDef {+ def()+ }async fn invoke(&self, args: Value) -> ToolResult {use cua_driver_core::tool_args::ArgsExt;@@ -55,28 +60,34 @@ impl Tool for ListWindowsTool {windows.retain(|w| w.pid == pid);}- let windows_json: Vec<Value> = windows.iter().map(|w| serde_json::json!({- "window_id": w.window_id,- "pid": w.pid,- "app_name": w.app_name,- "title": w.title,- "bounds": {- "x": w.bounds.x,- "y": w.bounds.y,- "width": w.bounds.width,- "height": w.bounds.height- },- "layer": w.layer,- "z_index": w.z_index,- "is_on_screen": w.is_on_screen,- "on_current_space": w.on_current_space,- "space_ids": w.space_ids,- })).collect();+ let windows_json: Vec<Value> = windows+ .iter()+ .map(|w| {+ serde_json::json!({+ "window_id": w.window_id,+ "pid": w.pid,+ "app_name": w.app_name,+ "title": w.title,+ "bounds": {+ "x": w.bounds.x,+ "y": w.bounds.y,+ "width": w.bounds.width,+ "height": w.bounds.height+ },+ "layer": w.layer,+ "z_index": w.z_index,+ "is_on_screen": w.is_on_screen,+ "on_current_space": w.on_current_space,+ "space_ids": w.space_ids,+ })+ })+ .collect();- ToolResult::text(format!("Found {} window(s).", windows_json.len()))- .with_structured(serde_json::json!({+ ToolResult::text(format!("Found {} window(s).", windows_json.len())).with_structured(+ serde_json::json!({"windows": windows_json,"current_space_id": null- }))+ }),+ )}}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rsindex 3618a9c1ef..874133e993 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs@@ -1,47 +1,44 @@//! MCP tool implementations for macOS.-mod list_apps;-mod list_windows;-mod get_window_state;-mod launch_app;-mod kill_app;mod bring_to_front;mod click;mod double_click;-mod right_click;mod drag;-mod type_text;-mod press_key;+mod get_window_state;mod hotkey;-mod set_value;+mod kill_app;+mod launch_app;+mod list_apps;+mod list_windows;+mod press_key;+mod right_click;mod scroll;+mod set_value;+mod type_text;// `screenshot` / `screenshot_compat` modules removed in PR #1692 —// `get_window_state` capture_mode:"vision" is the canonical screenshot// path. The capture functions they wrapped (ScreenCaptureKit, CGWindow,// etc.) live elsewhere under CuaDriverCore::Capture and are reached// through GetWindowStateTool.-pub(crate) mod get_screen_size;-mod get_desktop_state;-mod get_cursor_position;-mod move_cursor;-mod cursor_tools;mod check_permissions;-mod get_config;-mod set_config;+mod cursor_tools;mod get_accessibility_tree;+mod get_config;+mod get_cursor_position;+mod get_desktop_state;+pub(crate) mod get_screen_size;mod health_report;-mod zoom;-mod type_text_chars;+mod move_cursor;mod page;+mod set_config;+mod type_text_chars;+mod zoom;use cua_driver_core::tool::ToolRegistry;-use std::sync::Arc;use std::collections::HashMap;+use std::sync::Arc;-use crate::{- ax::cache::ElementCache,- cursor::state::CursorRegistry,-};+use crate::{ax::cache::ElementCache, cursor::state::CursorRegistry};/// Per-process zoom context — stores the padded crop origin and resize scale/// from the most recent `zoom` call, so `click(from_zoom=true)` can translate@@ -93,7 +90,9 @@ impl DeliveryMode {}}- pub fn is_foreground(self) -> bool { matches!(self, Self::Foreground) }+ pub fn is_foreground(self) -> bool {+ matches!(self, Self::Foreground)+ }}/// px-focus for the keyboard family (type_text / press_key / hotkey): pixel-click@@ -119,11 +118,21 @@ pub(crate) async fn focus_by_pixel("delivery_mode": if foreground { "foreground" } else { "background" },"action": if foreground { "press" } else { "focus" },});- if let Some(wid) = window_id { click_args["window_id"] = serde_json::json!(wid); }- if let Some(s) = session { click_args["session"] = serde_json::json!(s); }- if let Some(s) = session_id { click_args["_session_id"] = serde_json::json!(s); }- if from_zoom { click_args["from_zoom"] = serde_json::json!(true); }- let focus = click::ClickTool::new(state.clone()).invoke(click_args).await;+ if let Some(wid) = window_id {+ click_args["window_id"] = serde_json::json!(wid);+ }+ if let Some(s) = session {+ click_args["session"] = serde_json::json!(s);+ }+ if let Some(s) = session_id {+ click_args["_session_id"] = serde_json::json!(s);+ }+ if from_zoom {+ click_args["from_zoom"] = serde_json::json!(true);+ }+ let focus = click::ClickTool::new(state.clone())+ .invoke(click_args)+ .await;if focus.is_error == Some(true) {return Err(cua_driver_core::protocol::ToolResult::error(format!("focus pixel-click at ({x:.0},{y:.0}) failed."@@ -140,7 +149,11 @@ pub struct ZoomRegistry {}impl ZoomRegistry {- pub fn new() -> Self { Self { inner: std::sync::Mutex::new(HashMap::new()) } }+ pub fn new() -> Self {+ Self {+ inner: std::sync::Mutex::new(HashMap::new()),+ }+ }pub fn set(&self, pid: i32, ctx: ZoomContext) {self.inner.lock().unwrap().insert(pid, ctx);@@ -161,7 +174,11 @@ pub struct ResizeRegistry {}impl ResizeRegistry {- pub fn new() -> Self { Self { inner: std::sync::Mutex::new(HashMap::new()) } }+ pub fn new() -> Self {+ Self {+ inner: std::sync::Mutex::new(HashMap::new()),+ }+ }/// Record that pid's screenshot was downscaled by `ratio`.pub fn set_ratio(&self, pid: i32, ratio: f64) {@@ -210,11 +227,11 @@ pub fn load_driver_config() -> DriverConfig {let path = config_file_path();let text = match std::fs::read_to_string(&path) {Ok(t) => t,- Err(_) => return cfg, // no file yet — use defaults+ Err(_) => return cfg, // no file yet — use defaults};let json: serde_json::Value = match serde_json::from_str(&text) {Ok(v) => v,- Err(_) => return cfg, // malformed file — use defaults+ Err(_) => return cfg, // malformed file — use defaults};// `capture_mode` is per-call now; old on-disk `capture_mode` and// `capture_scope` keys are intentionally inert.@@ -288,7 +305,11 @@ pub struct SessionConfigRegistry {}impl SessionConfigRegistry {- pub fn new() -> Self { Self { inner: std::sync::Mutex::new(HashMap::new()) } }+ pub fn new() -> Self {+ Self {+ inner: std::sync::Mutex::new(HashMap::new()),+ }+ }/// Merge `delta` into `session`'s overrides (only the `Some` fields of/// `delta` overwrite; existing overrides for unset fields are preserved).@@ -312,7 +333,11 @@ impl SessionConfigRegistry {/// Resolve the effective `max_image_dimension` for `session`, layering its/// override over the global `DriverConfig`. `session = None` (anonymous)/// returns the global value verbatim.- pub fn effective_max_image_dimension(&self, session: Option<&str>, global: &DriverConfig) -> u32 {+ pub fn effective_max_image_dimension(+ &self,+ session: Option<&str>,+ global: &DriverConfig,+ ) -> u32 {let ov = session.and_then(|s| self.inner.lock().unwrap().get(s).cloned());match ov {Some(ov) => ov.max_image_dimension.unwrap_or(global.max_image_dimension),@@ -328,7 +353,9 @@ impl SessionConfigRegistry {}impl Default for SessionConfigRegistry {- fn default() -> Self { Self::new() }+ fn default() -> Self {+ Self::new()+ }}/// Shared state passed to all tools.@@ -433,7 +460,9 @@ pub fn register_all(registry: &mut ToolRegistry, compat: bool) {registry.register(Box::new(list_apps::ListAppsTool));registry.register(Box::new(list_windows::ListWindowsTool));- registry.register(Box::new(get_window_state::GetWindowStateTool::new(state.clone())));+ registry.register(Box::new(get_window_state::GetWindowStateTool::new(+ state.clone(),+ )));registry.register(Box::new(launch_app::LaunchAppTool));registry.register(Box::new(kill_app::KillAppTool));registry.register(Box::new(bring_to_front::BringToFrontTool));@@ -459,22 +488,36 @@ pub fn register_all(registry: &mut ToolRegistry, compat: bool) {registry.register(Box::new(get_desktop_state::GetDesktopStateTool));registry.register(Box::new(get_cursor_position::GetCursorPositionTool));registry.register(Box::new(move_cursor::MoveCursorTool::new(state.clone())));- registry.register(Box::new(cursor_tools::SetAgentCursorEnabledTool::new(state.clone())));- registry.register(Box::new(cursor_tools::SetAgentCursorMotionTool::new(state.clone())));- registry.register(Box::new(cursor_tools::SetAgentCursorStyleTool::new(state.clone())));- registry.register(Box::new(cursor_tools::GetAgentCursorStateTool::new(state.clone())));+ registry.register(Box::new(cursor_tools::SetAgentCursorEnabledTool::new(+ state.clone(),+ )));+ registry.register(Box::new(cursor_tools::SetAgentCursorMotionTool::new(+ state.clone(),+ )));+ registry.register(Box::new(cursor_tools::SetAgentCursorStyleTool::new(+ state.clone(),+ )));+ registry.register(Box::new(cursor_tools::GetAgentCursorStateTool::new(+ state.clone(),+ )));registry.register(Box::new(check_permissions::CheckPermissionsTool));// `health_report` — single-call end-to-end diagnostics. Stable// schema_version="1" contract aimed at downstream consumers who must// not have to know cua-driver internals. Provider is platform-specific; tool plumbing is in// `cua_driver_core::health_report`.- registry.register(Box::new(cua_driver_core::health_report::HealthReportTool::new(- Arc::new(health_report::MacosHealthProvider),- )));+ registry.register(Box::new(+ cua_driver_core::health_report::HealthReportTool::new(Arc::new(+ health_report::MacosHealthProvider,+ )),+ ));registry.register(Box::new(get_config::GetConfigTool::new(state.clone())));registry.register(Box::new(set_config::SetConfigTool::new(state.clone())));- registry.register(Box::new(get_accessibility_tree::GetAccessibilityTreeTool::new(state.clone())));- registry.register(Box::new(zoom::ZoomTool { state: state.clone() }));+ registry.register(Box::new(+ get_accessibility_tree::GetAccessibilityTreeTool::new(state.clone()),+ ));+ registry.register(Box::new(zoom::ZoomTool {+ state: state.clone(),+ }));// `type_text_chars` is intentionally NOT registered — Swift treats it as// a deprecated alias for `type_text` resolved at invoke time in// mcp-server's `ToolRegistry::invoke`. Keeping it out of the registry@@ -482,12 +525,13 @@ pub fn register_all(registry: &mut ToolRegistry, compat: bool) {// ToolRegistry.swift (`type_text_chars` not in `handlers`) and the// platform-windows::build_registry which uses the same convention.// Touch the struct so it stays in this crate for the alias resolver.- let _: &type_text_chars::TypeTextCharsTool = &type_text_chars::TypeTextCharsTool::new(state.clone());+ let _: &type_text_chars::TypeTextCharsTool =+ &type_text_chars::TypeTextCharsTool::new(state.clone());// Cross-platform `page` tool definition lives in mcp-server; macOS plugs in// its Apple-Events / CDP / AX-tree backend here.- registry.register(Box::new(cua_driver_core::page::PageTool::new(- Arc::new(page::MacOsPageBackend::new(state.clone())),- )));+ registry.register(Box::new(cua_driver_core::page::PageTool::new(Arc::new(+ page::MacOsPageBackend::new(state.clone()),+ ))));let browser_engine = cua_driver_core::browser::BrowserEngine::new(Arc::new(crate::browser::MacOsBrowserPlatform,));@@ -503,7 +547,9 @@ mod session_config_guard_tests {use cua_driver_core::session::fire_session_end;fn overrides(max_dim: u32) -> ConfigOverrides {- ConfigOverrides { max_image_dimension: Some(max_dim) }+ ConfigOverrides {+ max_image_dimension: Some(max_dim),+ }}#[test]@@ -519,7 +565,10 @@ mod session_config_guard_tests {reg.set(sid, overrides(800));let dim = reg.effective_max_image_dimension(Some(sid), &global);- assert_eq!(dim, global.max_image_dimension, "ended session must not get an override entry");+ assert_eq!(+ dim, global.max_image_dimension,+ "ended session must not get an override entry"+ );}#[test]@@ -556,7 +605,10 @@ mod recording_start_guard_tests {let dir = std::env::temp_dir().join("wb-rec-ended");let err = rec.start(dir.to_str().unwrap(), false, Some(sid));assert!(err.is_err(), "start for an ended session owner must error");- assert!(!rec.current_state().enabled, "no recording may start for a dead session");+ assert!(+ !rec.current_state().enabled,+ "no recording may start for a dead session"+ );}#[test]diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/page.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/page.rsindex 0c3cafa0b8..e70b78fa14 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/page.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/page.rs@@ -111,7 +111,10 @@ impl PageBackend for MacOsPageBackend {return self.execute_javascript(pid, window_id, javascript).await;}let port = resolve_cdp_port(pid, cdp_port, "execute_javascript").await?;- self.state.cdp_sessions.evaluate(javascript, port, target_url_contains).await+ self.state+ .cdp_sessions+ .evaluate(javascript, port, target_url_contains)+ .await}async fn click_element(@@ -204,8 +207,14 @@ impl PageBackend for MacOsPageBackend {target_url_contains: Option<&str>,) -> anyhow::Result<String> {let port = resolve_cdp_port(pid, cdp_port, "insert_text").await?;- self.state.cdp_sessions.insert_text(text, port, target_url_contains).await?;- Ok(format!("Inserted {} character(s) via CDP Input.insertText.", text.chars().count()))+ self.state+ .cdp_sessions+ .insert_text(text, port, target_url_contains)+ .await?;+ Ok(format!(+ "Inserted {} character(s) via CDP Input.insertText.",+ text.chars().count()+ ))}async fn type_keystrokes(@@ -217,8 +226,14 @@ impl PageBackend for MacOsPageBackend {target_url_contains: Option<&str>,) -> anyhow::Result<String> {let port = resolve_cdp_port(pid, cdp_port, "type_keystrokes").await?;- self.state.cdp_sessions.dispatch_keystrokes(text, port, target_url_contains).await?;- Ok(format!("Typed {} character(s) via CDP keystroke events.", text.chars().count()))+ self.state+ .cdp_sessions+ .dispatch_keystrokes(text, port, target_url_contains)+ .await?;+ Ok(format!(+ "Typed {} character(s) via CDP keystroke events.",+ text.chars().count()+ ))}}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rsindex 4c31237493..338cda20d9 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs@@ -1,11 +1,13 @@use async_trait::async_trait;-use cua_driver_core::{protocol::ToolResult, tool::{Tool, ToolDef}};+use cua_driver_core::{+ protocol::ToolResult,+ tool::{Tool, ToolDef},+};use serde_json::Value;use std::sync::Arc;use crate::ax::bindings::{- copy_action_names, perform_action, kAXErrorSuccess, AXUIElementRef,- copy_string_attr,+ copy_action_names, copy_string_attr, kAXErrorSuccess, perform_action, AXUIElementRef,};use super::ToolState;@@ -15,7 +17,9 @@ pub struct RightClickTool {}impl RightClickTool {- pub fn new(state: Arc<ToolState>) -> Self { Self { state } }+ pub fn new(state: Arc<ToolState>) -> Self {+ Self { state }+ }}static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();@@ -79,11 +83,16 @@ fn def() -> &'static ToolDef {#[async_trait]impl Tool for RightClickTool {- fn def(&self) -> &ToolDef { def() }+ fn def(&self) -> &ToolDef {+ def()+ }async fn invoke(&self, args: Value) -> ToolResult {use cua_driver_core::tool_args::ArgsExt;- let pid = match args.require_i32("pid") { Ok(v) => v, Err(e) => return e };+ let pid = match args.require_i32("pid") {+ Ok(v) => v,+ Err(e) => return e,+ };// delivery_mode: foreground briefly fronts the window before the pixel// right-click (the explicit last resort for surfaces that drop// background CGEvents), via the same skylight assist click uses. The AX@@ -93,7 +102,7 @@ impl Tool for RightClickTool {// Surface 6: element_token / element_index precedence resolution.let element_token_arg = args.opt_str("element_token");- let window_id_arg = args.opt_u64("window_id").map(|v| v as u32);+ let window_id_arg = args.opt_u64("window_id").map(|v| v as u32);let element_index_arg = args.opt_u64("element_index").map(|v| v as usize);let resolved = match cua_driver_core::element_token::resolve_element_args(pid,@@ -108,13 +117,15 @@ impl Tool for RightClickTool {let (element_index, window_id) = match resolved {cua_driver_core::element_token::ResolvedElement::None => (None, window_id_arg),cua_driver_core::element_token::ResolvedElement::Element {- window_id: wid, element_index: idx, via_token: _,+ window_id: wid,+ element_index: idx,+ via_token: _,} => (Some(idx), wid),};- let x = args.opt_f64("x");- let y = args.opt_f64("y");- let has_xy = x.is_some() && y.is_some();- let partial_xy = x.is_some() != y.is_some();+ let x = args.opt_f64("x");+ let y = args.opt_f64("y");+ let has_xy = x.is_some() && y.is_some();+ let partial_xy = x.is_some() != y.is_some();let modifiers: Vec<String> = args.str_array("modifier");if partial_xy {@@ -125,13 +136,11 @@ impl Tool for RightClickTool {}if element_index.is_none() && !has_xy {return ToolResult::error(- "Provide element_index or (x, y) to address the right-click target."+ "Provide element_index or (x, y) to address the right-click target.",);}if element_index.is_some() && window_id.is_none() {- return ToolResult::error(- "window_id is required when element_index is used."- );+ return ToolResult::error("window_id is required when element_index is used.");}// ── AX element path ──────────────────────────────────────────────────@@ -140,20 +149,21 @@ impl Tool for RightClickTool {// free the element mid-action (use-after-free → daemon crash).let element_guard = match self.state.element_cache.get_element_retained(pid, wid, idx) {Some(e) => e,- None => return ToolResult::error(format!(- "Element index {idx} not found. Call get_window_state first."- )),+ None => {+ return ToolResult::error(format!(+ "Element index {idx} not found. Call get_window_state first."+ ))+ }};let element_ptr = element_guard.as_ptr();- let result = tokio::task::spawn_blocking(move || {- ax_show_menu(element_ptr, idx, pid, wid)- }).await;+ let result =+ tokio::task::spawn_blocking(move || ax_show_menu(element_ptr, idx, pid, wid)).await;return match result {- Ok(Ok(msg)) => ToolResult::text(msg),- Ok(Err(e)) => ToolResult::error(format!("Right-click failed: {e}")),- Err(e) => ToolResult::error(format!("Task error: {e}")),+ Ok(Ok(msg)) => ToolResult::text(msg),+ Ok(Err(e)) => ToolResult::error(format!("Right-click failed: {e}")),+ Err(e) => ToolResult::error(format!("Task error: {e}")),};}@@ -173,14 +183,27 @@ impl Tool for RightClickTool {let scale: f64 = if let Some(ref b) = bounds {if let Ok(png) = crate::capture::screenshot_window_bytes(wid) {if png.len() >= 24 {- let pw = u32::from_be_bytes([png[16], png[17], png[18], png[19]]) as f64;+ let pw =+ u32::from_be_bytes([png[16], png[17], png[18], png[19]]) as f64;let lw = b.width;- if lw > 0.0 && pw > lw { pw / lw } else { 1.0 }- } else { 1.0 }- } else { 1.0 }- } else { 1.0 };+ if lw > 0.0 && pw > lw {+ pw / lw+ } else {+ 1.0+ }+ } else {+ 1.0+ }+ } else {+ 1.0+ }+ } else {+ 1.0+ };(bounds, scale)- }).await.unwrap_or((None, 1.0));+ })+ .await+ .unwrap_or((None, 1.0));if let (Some(b), scale) = result {let wx = cx / scale;let wy = cy / scale;@@ -203,7 +226,10 @@ impl Tool for RightClickTool {crate::cursor::overlay::animate_cursor_to(cursor_key.clone(), screen_x, screen_y).await;crate::cursor::overlay::send_command(cursor_key.clone(),- cursor_overlay::OverlayCommand::ClickPulse { x: screen_x, y: screen_y },+ cursor_overlay::OverlayCommand::ClickPulse {+ x: screen_x,+ y: screen_y,+ },);let mod_suffix = if modifiers.is_empty() {@@ -218,7 +244,13 @@ impl Tool for RightClickTool {let m: Vec<&str> = modifiers.iter().map(String::as_str).collect();if let Some(wid) = window_id {crate::input::mouse::right_click_at_xy_with_window_local(- pid, screen_x, screen_y, win_local_x, win_local_y, wid, &m,+ pid,+ screen_x,+ screen_y,+ win_local_x,+ win_local_y,+ wid,+ &m,)} else {crate::input::mouse::right_click_at_xy(pid, screen_x, screen_y, &m)@@ -232,8 +264,13 @@ impl Tool for RightClickTool {}_ => do_it(),}- }).await;- let mode_label = if fg { " (delivery_mode:foreground)" } else { "" };+ })+ .await;+ let mode_label = if fg {+ " (delivery_mode:foreground)"+ } else {+ ""+ };match result {Ok(Ok(())) => ToolResult::text(format!("Right-clicked{mod_suffix} at ({screen_x:.1}, {screen_y:.1}){mode_label}.")).with_structured(serde_json::json!({@@ -250,7 +287,7 @@ impl Tool for RightClickTool {fn ax_show_menu(element_ptr: usize, idx: usize, pid: i32, wid: u32) -> anyhow::Result<String> {let element = element_ptr as AXUIElementRef;- let role = unsafe { copy_string_attr(element, "AXRole") }.unwrap_or_default();+ let role = unsafe { copy_string_attr(element, "AXRole") }.unwrap_or_default();let title = unsafe { copy_string_attr(element, "AXTitle") }.unwrap_or_default();let advertised = unsafe { copy_action_names(element) };@@ -267,7 +304,9 @@ fn ax_show_menu(element_ptr: usize, idx: usize, pid: i32, wid: u32) -> anyhow::Rif advertised.iter().any(|a| a == "AXShowMenu") {let err = unsafe { perform_action(element, "AXShowMenu") };if err == kAXErrorSuccess {- return Ok(format!("Shown menu for [{idx}] {role} \"{title}\" (AXShowMenu)."));+ return Ok(format!(+ "Shown menu for [{idx}] {role} \"{title}\" (AXShowMenu)."+ ));}// Advertised but the action failed — fall through to the pixel path// rather than erroring out.@@ -275,11 +314,13 @@ fn ax_show_menu(element_ptr: usize, idx: usize, pid: i32, wid: u32) -> anyhow::R}// Pixel right-click at the element's screen-space center.- let (cx, cy) = unsafe { crate::ax::bindings::element_screen_center(element) }- .ok_or_else(|| anyhow::anyhow!(- "[{idx}] {role} \"{title}\" advertises no AXShowMenu and has no resolvable \+ let (cx, cy) =+ unsafe { crate::ax::bindings::element_screen_center(element) }.ok_or_else(|| {+ anyhow::anyhow!(+ "[{idx}] {role} \"{title}\" advertises no AXShowMenu and has no resolvable \on-screen center for a pixel right-click. Pass x, y directly."- ))?;+ )+ })?;let (wx, wy) = crate::windows::window_bounds_by_id(wid).map(|b| (cx - b.x, cy - b.y)).unwrap_or((cx, cy));diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/set_config.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/set_config.rsindex 22aa0138fb..56c9e08378 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/set_config.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/set_config.rs@@ -1,5 +1,8 @@use async_trait::async_trait;-use cua_driver_core::{protocol::ToolResult, tool::{Tool, ToolDef}};+use cua_driver_core::{+ protocol::ToolResult,+ tool::{Tool, ToolDef},+};use serde_json::Value;use std::sync::Arc;@@ -10,7 +13,9 @@ pub struct SetConfigTool {}impl SetConfigTool {- pub fn new(state: Arc<ToolState>) -> Self { Self { state } }+ pub fn new(state: Arc<ToolState>) -> Self {+ Self { state }+ }}static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();@@ -63,7 +68,9 @@ fn def() -> &'static ToolDef {#[async_trait]impl Tool for SetConfigTool {- fn def(&self) -> &ToolDef { def() }+ fn def(&self) -> &ToolDef {+ def()+ }async fn invoke(&self, args: Value) -> ToolResult {use cua_driver_core::tool_args::ArgsExt;@@ -92,31 +99,46 @@ impl Tool for SetConfigTool {.opt_str("key").and_then(|k| args.get("value").map(|v| (k, v.clone())));let kv_u64 = |name: &str| -> Option<u64> {- kv.as_ref().filter(|(k, _)| k == name).and_then(|(_, v)| v.as_u64())+ kv.as_ref()+ .filter(|(k, _)| k == name)+ .and_then(|(_, v)| v.as_u64())};// Validate max_image_dimension up front so both branches share the// u32 check and we never half-apply.- let max_dim: Option<u32> = match args.opt_u64("max_image_dimension").or_else(|| kv_u64("max_image_dimension")) {+ let max_dim: Option<u32> = match args+ .opt_u64("max_image_dimension")+ .or_else(|| kv_u64("max_image_dimension"))+ {Some(dim) => match u32::try_from(dim) {Ok(d) => Some(d),- Err(_) => return ToolResult::error(format!("max_image_dimension {dim} exceeds u32::MAX")),+ Err(_) => {+ return ToolResult::error(format!("max_image_dimension {dim} exceeds u32::MAX"))+ }},None => None,};let effective_dim = if let Some(sid) = session_id.as_deref() {// Session-scoped override: in-memory only, no global write, no disk.- self.state.session_config.set(sid, ConfigOverrides {- max_image_dimension: max_dim,- });- self.state.session_config.effective_max_image_dimension(Some(sid), &self.state.config.read().unwrap())+ self.state.session_config.set(+ sid,+ ConfigOverrides {+ max_image_dimension: max_dim,+ },+ );+ self.state+ .session_config+ .effective_max_image_dimension(Some(sid), &self.state.config.read().unwrap())} else {// Anonymous/global session: write the shared global + persist.let mut cfg = self.state.config.write().unwrap();if let Some(dim32) = max_dim {cfg.max_image_dimension = dim32;- if let Err(e) = write_driver_config_key("max_image_dimension", &Value::Number(u64::from(dim32).into())) {+ if let Err(e) = write_driver_config_key(+ "max_image_dimension",+ &Value::Number(u64::from(dim32).into()),+ ) {tracing::warn!("set_config: failed to persist max_image_dimension: {e}");}}@@ -126,10 +148,12 @@ impl Tool for SetConfigTool {// next daemon restart — the backend is initialised once at startup.let mut pip_note = String::new();if let Some(enabled) = args.get("experimental_pip").and_then(|v| v.as_bool()) {- if let Err(e) = pip_preview::write_config_key("experimental_pip", Value::Bool(enabled)) {+ if let Err(e) = pip_preview::write_config_key("experimental_pip", Value::Bool(enabled))+ {return ToolResult::error(format!("failed to persist experimental_pip: {e}"));}- pip_note = format!(" — restart cua-driver for experimental_pip={enabled} to take effect");+ pip_note =+ format!(" — restart cua-driver for experimental_pip={enabled} to take effect");}if let Some(geom) = args.opt_str("experimental_pip_geometry") {// Validate before persisting so the user gets an immediate error.@@ -138,11 +162,18 @@ impl Tool for SetConfigTool {"experimental_pip_geometry `{geom}` is not a valid WxH or WxH+X+Y string"));}- if let Err(e) = pip_preview::write_config_key("experimental_pip_geometry", Value::String(geom.clone())) {- return ToolResult::error(format!("failed to persist experimental_pip_geometry: {e}"));+ if let Err(e) = pip_preview::write_config_key(+ "experimental_pip_geometry",+ Value::String(geom.clone()),+ ) {+ return ToolResult::error(format!(+ "failed to persist experimental_pip_geometry: {e}"+ ));}if pip_note.is_empty() {- pip_note = format!(" — restart cua-driver for experimental_pip_geometry={geom} to take effect");+ pip_note = format!(+ " — restart cua-driver for experimental_pip_geometry={geom} to take effect"+ );}}let scope_note = if session_id.is_some() {diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/set_value.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/set_value.rsindex 267cd0f8e0..d246dbffbf 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/set_value.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/set_value.rs@@ -12,14 +12,17 @@//! text fields that expose a settable AXValue).use async_trait::async_trait;-use cua_driver_core::{protocol::ToolResult, tool::{Tool, ToolDef}};+use cua_driver_core::{+ protocol::ToolResult,+ tool::{Tool, ToolDef},+};use serde_json::Value;use std::sync::Arc;use crate::apps;use crate::ax::bindings::{- copy_children, copy_number_attr, copy_string_attr, perform_action, set_number_attr,- set_string_attr, kAXErrorSuccess, AXUIElementRef,+ copy_children, copy_number_attr, copy_string_attr, kAXErrorSuccess, perform_action,+ set_number_attr, set_string_attr, AXUIElementRef,};use crate::focus_guard;use crate::window_change_detector::WindowChangeDetector;@@ -32,7 +35,9 @@ pub struct SetValueTool {}impl SetValueTool {- pub fn new(state: Arc<ToolState>) -> Self { Self { state } }+ pub fn new(state: Arc<ToolState>) -> Self {+ Self { state }+ }}static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();@@ -83,18 +88,26 @@ fn def() -> &'static ToolDef {#[async_trait]impl Tool for SetValueTool {- fn def(&self) -> &ToolDef { def() }+ fn def(&self) -> &ToolDef {+ def()+ }async fn invoke(&self, args: Value) -> ToolResult {use cua_driver_core::tool_args::ArgsExt;- let pid = match args.require_i32("pid") { Ok(v) => v, Err(e) => return e };- let value = match args.require_str("value") { Ok(v) => v, Err(e) => return e };+ let pid = match args.require_i32("pid") {+ Ok(v) => v,+ Err(e) => return e,+ };+ let value = match args.require_str("value") {+ Ok(v) => v,+ Err(e) => return e,+ };// Surface 6: element_token / element_index precedence. Neither// is now schema-required so the resolver can centralize the// "missing addressing" error message.let element_token_arg = args.opt_str("element_token");- let window_id_arg = args.opt_u64("window_id").map(|v| v as u32);+ let window_id_arg = args.opt_u64("window_id").map(|v| v as u32);let element_index_arg = args.opt_u64("element_index").map(|v| v as usize);let resolved = match cua_driver_core::element_token::resolve_element_args(pid,@@ -107,31 +120,43 @@ impl Tool for SetValueTool {Err(e) => return e,};let (element_index, window_id) = match resolved {- cua_driver_core::element_token::ResolvedElement::None =>+ cua_driver_core::element_token::ResolvedElement::None => {return ToolResult::error("set_value requires element_index (+ window_id) or element_token to \- address the target element."- ),+ address the target element.",+ )+ }cua_driver_core::element_token::ResolvedElement::Element {- window_id: Some(wid), element_index: idx, via_token: _,+ window_id: Some(wid),+ element_index: idx,+ via_token: _,} => (idx, wid),cua_driver_core::element_token::ResolvedElement::Element {window_id: None, ..- } => return ToolResult::error(- "set_value requires window_id when element_index is used \- (omit only when supplying element_token, which carries it)."- ),+ } => {+ return ToolResult::error(+ "set_value requires window_id when element_index is used \+ (omit only when supplying element_token, which carries it).",+ )+ }};// Retain out of the cache so a concurrent get_window_state can't free// the element mid-action (use-after-free → daemon crash). Guard lives// to the end of this method, past the AX write below.- let element_guard = match self.state.element_cache.get_element_retained(pid, window_id, element_index) {- Some(e) => e,- None => return ToolResult::error(format!(- "Element index {element_index} not found. Call get_window_state first."- )),- };+ let element_guard =+ match self+ .state+ .element_cache+ .get_element_retained(pid, window_id, element_index)+ {+ Some(e) => e,+ None => {+ return ToolResult::error(format!(+ "Element index {element_index} not found. Call get_window_state first."+ ))+ }+ };let element_ptr = element_guard.as_ptr();// ── Focus-suppression wrap (Swift WindowChangeDetector + FocusGuard) ──@@ -161,8 +186,8 @@ impl Tool for SetValueTool {msg.push_str(&changes.result_suffix());ToolResult::text(msg)}- Ok(Err(e)) => ToolResult::error(format!("set_value failed: {e}")),- Err(e) => ToolResult::error(format!("Task error: {e}")),+ Ok(Err(e)) => ToolResult::error(format!("set_value failed: {e}")),+ Err(e) => ToolResult::error(format!("Task error: {e}")),}}}@@ -177,12 +202,10 @@ fn set_value_blocking() -> anyhow::Result<String> {let element = element_ptr as AXUIElementRef;- let role = unsafe { copy_string_attr(element, "AXRole") }- .unwrap_or_default();+ let role = unsafe { copy_string_attr(element, "AXRole") }.unwrap_or_default();if role == "AXPopUpButton" {- let element_title = unsafe { copy_string_attr(element, "AXTitle") }- .unwrap_or_default();+ let element_title = unsafe { copy_string_attr(element, "AXTitle") }.unwrap_or_default();select_popup_option(element, element_index, pid, value, &element_title)} else {// Default path: write AXValue directly. Numeric controls (AXSlider /@@ -252,7 +275,11 @@ fn step_to_value(element: AXUIElementRef, target: f64) -> bool {return true;}- let action = if current < target { "AXIncrement" } else { "AXDecrement" };+ let action = if current < target {+ "AXIncrement"+ } else {+ "AXDecrement"+ };let _ = unsafe { perform_action(element, action) };let next = match unsafe { copy_number_attr(element, "AXValue") } {@@ -296,10 +323,8 @@ fn select_popup_option(let mut available: Vec<String> = Vec::with_capacity(children.len());for (i, &child) in children.iter().enumerate() {- let child_title = unsafe { copy_string_attr(child, "AXTitle") }- .unwrap_or_default();- let child_value = unsafe { copy_string_attr(child, "AXValue") }- .unwrap_or_default();+ let child_title = unsafe { copy_string_attr(child, "AXTitle") }.unwrap_or_default();+ let child_value = unsafe { copy_string_attr(child, "AXValue") }.unwrap_or_default();available.push(child_title.clone());if child_title.to_lowercase() == value_lower|| child_value.to_lowercase() == value_lower@@ -311,8 +336,8 @@ fn select_popup_option(let result = if let Some(i) = matched_idx {let child = children[i];- let opt_title = unsafe { copy_string_attr(child, "AXTitle") }- .unwrap_or_else(|| value.to_string());+ let opt_title =+ unsafe { copy_string_attr(child, "AXTitle") }.unwrap_or_else(|| value.to_string());let err = unsafe { perform_action(child, "AXPress") };if err == kAXErrorSuccess {Ok(format!(@@ -320,12 +345,11 @@ fn select_popup_option(\"{element_title}\" via AX child AXPress."))} else {- anyhow::bail!(- "AXPress on child option failed with error {err}"- )+ anyhow::bail!("AXPress on child option failed with error {err}")}} else {- let avail = available.iter()+ let avail = available+ .iter().map(|t| format!("\"{t}\"")).collect::<Vec<_>>().join(", ");@@ -337,7 +361,9 @@ fn select_popup_option(// Release children (copy_children retains each one).for &child in &children {- unsafe { CFRelease(child as _); }+ unsafe {+ CFRelease(child as _);+ }}return result;@@ -345,8 +371,7 @@ fn select_popup_option(// Strategy 2: Safari/WebKit — no AX children when popup is closed.// Use osascript do JavaScript to set the <select> element's DOM value.- let app_name = crate::apps::get_app_name_for_pid(pid)- .unwrap_or_default();+ let app_name = crate::apps::get_app_name_for_pid(pid).unwrap_or_default();if app_name != "Safari" {anyhow::bail!(@@ -393,9 +418,8 @@ fn set_select_via_js(}})()");- let apple_script = format!(- "tell application \"Safari\" to do JavaScript \"{js}\" in front document"- );+ let apple_script =+ format!("tell application \"Safari\" to do JavaScript \"{js}\" in front document");// Spawn osascript with a 10-second deadline. A stuck Safari permission// prompt or unresponsive renderer can cause wait() to block indefinitely,@@ -422,12 +446,11 @@ fn set_select_via_js(Err(e) => anyhow::bail!("osascript wait error: {e}"),}}- let out = child.wait_with_output()+ let out = child+ .wait_with_output().map_err(|e| anyhow::anyhow!("osascript output error: {e}"))?;- let raw = String::from_utf8_lossy(&out.stdout)- .trim()- .to_string();+ let raw = String::from_utf8_lossy(&out.stdout).trim().to_string();if raw.starts_with("SET:") {let dom_val = &raw[4..];@@ -472,8 +495,8 @@ fn percent_encode_unreserved(s: &str) -> String {fn hex_digit(n: u8) -> char {match n {- 0..=9 => (b'0' + n) as char,+ 0..=9 => (b'0' + n) as char,10..=15 => (b'A' + n - 10) as char,- _ => '0',+ _ => '0',}}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text_chars.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text_chars.rsindex 6838ad7651..5edbb1c8e2 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text_chars.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text_chars.rs@@ -1,5 +1,8 @@use async_trait::async_trait;-use cua_driver_core::{protocol::ToolResult, tool::{Tool, ToolDef}};+use cua_driver_core::{+ protocol::ToolResult,+ tool::{Tool, ToolDef},+};use serde_json::Value;use std::sync::Arc;@@ -10,7 +13,9 @@ pub struct TypeTextCharsTool {}impl TypeTextCharsTool {- pub fn new(state: Arc<ToolState>) -> Self { Self { state } }+ pub fn new(state: Arc<ToolState>) -> Self {+ Self { state }+ }}static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();@@ -44,12 +49,20 @@ fn def() -> &'static ToolDef {#[async_trait]impl Tool for TypeTextCharsTool {- fn def(&self) -> &ToolDef { def() }+ fn def(&self) -> &ToolDef {+ def()+ }async fn invoke(&self, args: Value) -> ToolResult {use cua_driver_core::tool_args::ArgsExt;- let pid = match args.require_i32("pid") { Ok(v) => v, Err(e) => return e };- let text_raw = match args.require_str("text") { Ok(v) => v, Err(e) => return e };+ let pid = match args.require_i32("pid") {+ Ok(v) => v,+ Err(e) => return e,+ };+ let text_raw = match args.require_str("text") {+ Ok(v) => v,+ Err(e) => return e,+ };// Same trailing-protocol-tag scrub as TypeTextTool — see// cua_driver_core::text_sanitize for rationale.let text = cua_driver_core::text_sanitize::strip_trailing_agent_protocol_tags(&text_raw)@@ -57,7 +70,7 @@ impl Tool for TypeTextCharsTool {let delay_ms = args.u64_or("delay_ms", 30);// Surface 6: element_token / element_index precedence resolution.let element_token_arg = args.opt_str("element_token");- let window_id_arg = args.opt_u64("window_id").map(|v| v as u32);+ let window_id_arg = args.opt_u64("window_id").map(|v| v as u32);let element_index_arg = args.opt_u64("element_index").map(|v| v as usize);let resolved = match cua_driver_core::element_token::resolve_element_args(pid,@@ -72,7 +85,9 @@ impl Tool for TypeTextCharsTool {let (element_index, window_id) = match resolved {cua_driver_core::element_token::ResolvedElement::None => (None, window_id_arg),cua_driver_core::element_token::ResolvedElement::Element {- window_id: wid, element_index: idx, via_token: _,+ window_id: wid,+ element_index: idx,+ via_token: _,} => (Some(idx), wid),};let type_chars_only = args.bool_or("type_chars_only", false);@@ -83,11 +98,14 @@ impl Tool for TypeTextCharsTool {// Retain so a concurrent get_window_state can't free the element// during the focus call (use-after-free → daemon crash). The// guard outlives the awaited spawn_blocking below.- if let Some(element_guard) = self.state.element_cache.get_element_retained(pid, wid, idx) {+ if let Some(element_guard) =+ self.state.element_cache.get_element_retained(pid, wid, idx)+ {let element_ptr = element_guard.as_ptr();let _ = tokio::task::spawn_blocking(move || {crate::input::ax_actions::focus_element(element_ptr)- }).await;+ })+ .await;drop(element_guard);tokio::time::sleep(std::time::Duration::from_millis(50)).await;}@@ -97,10 +115,13 @@ impl Tool for TypeTextCharsTool {let text_len = text.chars().count();let result = tokio::task::spawn_blocking(move || {crate::input::keyboard::type_text_with_delay(pid, &text, delay_ms)- }).await;+ })+ .await;match result {- Ok(Ok(())) => ToolResult::text(format!("Typed {text_len} character(s) with {delay_ms}ms delay.")),+ Ok(Ok(())) => ToolResult::text(format!(+ "Typed {text_len} character(s) with {delay_ms}ms delay."+ )),Ok(Err(e)) => ToolResult::error(format!("Type text chars failed: {e}")),Err(e) => ToolResult::error(format!("Task error: {e}")),}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/zoom.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/zoom.rsindex 81d6091bca..3dfe2fb1a8 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/zoom.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/zoom.rs@@ -1,6 +1,9 @@use async_trait::async_trait;use base64::{engine::general_purpose::STANDARD as BASE64, Engine};-use cua_driver_core::{protocol::{ToolResult, Content}, tool::{Tool, ToolDef}};+use cua_driver_core::{+ protocol::{Content, ToolResult},+ tool::{Tool, ToolDef},+};use serde_json::Value;use std::sync::Arc;@@ -42,16 +45,33 @@ fn def() -> &'static ToolDef {#[async_trait]impl Tool for ZoomTool {- fn def(&self) -> &ToolDef { def() }+ fn def(&self) -> &ToolDef {+ def()+ }async fn invoke(&self, args: Value) -> ToolResult {use cua_driver_core::tool_args::ArgsExt;- let window_id = match args.require_u32("window_id") { Ok(v) => v, Err(e) => return e };+ let window_id = match args.require_u32("window_id") {+ Ok(v) => v,+ Err(e) => return e,+ };let pid = args.opt_i64("pid").map(|v| v as i32);- let x1 = match args.require_f64("x1") { Ok(v) => v, Err(e) => return e };- let y1 = match args.require_f64("y1") { Ok(v) => v, Err(e) => return e };- let x2 = match args.require_f64("x2") { Ok(v) => v, Err(e) => return e };- let y2 = match args.require_f64("y2") { Ok(v) => v, Err(e) => return e };+ let x1 = match args.require_f64("x1") {+ Ok(v) => v,+ Err(e) => return e,+ };+ let y1 = match args.require_f64("y1") {+ Ok(v) => v,+ Err(e) => return e,+ };+ let x2 = match args.require_f64("x2") {+ Ok(v) => v,+ Err(e) => return e,+ };+ let y2 = match args.require_f64("y2") {+ Ok(v) => v,+ Err(e) => return e,+ };if x2 <= x1 || y2 <= y1 {return ToolResult::error("x2 must be > x1 and y2 must be > y1");@@ -61,17 +81,21 @@ impl Tool for ZoomTool {let result = tokio::task::spawn_blocking(move || {let png_bytes = crate::capture::screenshot_window_bytes(window_id)?;cursor_overlay::capture_utils::crop_png_to_jpeg(&png_bytes, x1, y1, x2, y2, 500)- }).await;+ })+ .await;match result {Ok(Ok(crop)) => {// Store zoom context so from_zoom clicks can translate back.if let Some(p) = pid {- state.zoom_registry.set(p, ZoomContext {- origin_x: crop.origin_x,- origin_y: crop.origin_y,- scale_inv: crop.scale_inv,- });+ state.zoom_registry.set(+ p,+ ZoomContext {+ origin_x: crop.origin_x,+ origin_y: crop.origin_y,+ scale_inv: crop.scale_inv,+ },+ );}let (w, h) = (crop.out_w, crop.out_h);let b64 = BASE64.encode(&crop.jpeg_bytes);diff --git a/libs/cua-driver/rust/crates/platform-macos/src/windows.rs b/libs/cua-driver/rust/crates/platform-macos/src/windows.rsindex 0785c6d46e..1ec45a52f3 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/windows.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/windows.rs@@ -69,17 +69,15 @@ pub fn visible_windows() -> Vec<WindowInfo> {fn enumerate_windows(options: u32) -> Vec<WindowInfo> {use core_foundation::{array::CFArray,- base::{CFGetTypeID, TCFType, CFTypeRef},+ base::{CFGetTypeID, CFTypeRef, TCFType},+ boolean::CFBoolean,dictionary::CFDictionary,- string::CFString,number::CFNumber,- boolean::CFBoolean,+ string::CFString,};use std::os::raw::c_void;- let raw_ref = unsafe {- CGWindowListCopyWindowInfo(options, kCGNullWindowID)- };+ let raw_ref = unsafe { CGWindowListCopyWindowInfo(options, kCGNullWindowID) };if raw_ref.is_null() {return vec![];}@@ -96,9 +94,8 @@ fn enumerate_windows(options: u32) -> Vec<WindowInfo> {continue;}- let dict: CFDictionary<*const c_void, *const c_void> = unsafe {- CFDictionary::wrap_under_get_rule(item as _)- };+ let dict: CFDictionary<*const c_void, *const c_void> =+ unsafe { CFDictionary::wrap_under_get_rule(item as _) };// Helper: get number from dict by key string.let get_num = |key: &str| -> i64 {@@ -108,7 +105,9 @@ fn enumerate_windows(options: u32) -> Vec<WindowInfo> {let v = *v;if CFGetTypeID(v) == CFNumber::type_id() {CFNumber::wrap_under_get_rule(v as _).to_i64()- } else { None }+ } else {+ None+ }}).unwrap_or(0)};@@ -120,7 +119,9 @@ fn enumerate_windows(options: u32) -> Vec<WindowInfo> {let v = *v;if CFGetTypeID(v) == CFString::type_id() {Some(CFString::wrap_under_get_rule(v as _).to_string())- } else { None }+ } else {+ None+ }}).unwrap_or_default()};@@ -132,7 +133,9 @@ fn enumerate_windows(options: u32) -> Vec<WindowInfo> {let v = *v;if CFGetTypeID(v) == CFBoolean::type_id() {bool::from(CFBoolean::wrap_under_get_rule(v as _))- } else { false }+ } else {+ false+ }}).unwrap_or(false)};@@ -145,7 +148,9 @@ fn enumerate_windows(options: u32) -> Vec<WindowInfo> {let is_on_screen = get_bool("kCGWindowIsOnscreen");// Only include layer-0 windows.- if layer != 0 { continue; }+ if layer != 0 {+ continue;+ }// Parse bounds dict.let bounds = {@@ -160,10 +165,22 @@ fn enumerate_windows(options: u32) -> Vec<WindowInfo> {let y = get_bounds_num(&bd, "Y");let w = get_bounds_num(&bd, "Width");let h = get_bounds_num(&bd, "Height");- Some(WindowBounds { x, y, width: w, height: h })- } else { None }+ Some(WindowBounds {+ x,+ y,+ width: w,+ height: h,+ })+ } else {+ None+ }+ })+ .unwrap_or(WindowBounds {+ x: 0.,+ y: 0.,+ width: 0.,+ height: 0.,})- .unwrap_or(WindowBounds { x: 0., y: 0., width: 0., height: 0. })};// z_index: CGWindowList front-to-back → assign reverse index.@@ -187,7 +204,10 @@ fn enumerate_windows(options: u32) -> Vec<WindowInfo> {}fn get_bounds_num(- dict: &core_foundation::dictionary::CFDictionary<*const std::os::raw::c_void, *const std::os::raw::c_void>,+ dict: &core_foundation::dictionary::CFDictionary<+ *const std::os::raw::c_void,+ *const std::os::raw::c_void,+ >,key: &str,) -> f64 {use core_foundation::{@@ -203,7 +223,9 @@ fn get_bounds_num(let v = *v;if CFGetTypeID(v) == CFNumber::type_id() {CFNumber::wrap_under_get_rule(v as _).to_f64()- } else { None }+ } else {+ None+ }}).unwrap_or(0.0)}@@ -234,7 +256,9 @@ pub fn resolve_main_window_id(pid: i32) -> anyhow::Result<u32> {let largest = pid_windows.iter().max_by(|a, b| {let area_a = a.bounds.width * a.bounds.height;let area_b = b.bounds.width * b.bounds.height;- area_a.partial_cmp(&area_b).unwrap_or(std::cmp::Ordering::Equal)+ area_a+ .partial_cmp(&area_b)+ .unwrap_or(std::cmp::Ordering::Equal)});Ok(largest.unwrap().window_id)}diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/agent_cursor_setters_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/agent_cursor_setters_parity.rsindex 719520cca4..ebeb96b7e4 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/agent_cursor_setters_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/agent_cursor_setters_parity.rs@@ -6,7 +6,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe");@@ -17,51 +18,82 @@ fn main() {let mut buf: Vec<u8> = vec![0u8; 64 * 1024];let deadline = Instant::now() + Duration::from_secs(4);loop {- if Instant::now() > deadline { panic!("timeout"); }+ if Instant::now() > deadline {+ panic!("timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}fn extract_text(v: &serde_json::Value) -> String {- v.pointer("/result/content/0/text").and_then(|t| t.as_str())+ v.pointer("/result/content/0/text")+ .and_then(|t| t.as_str()).or_else(|| v.pointer("/error").and_then(|e| e.as_str()))- .map(|s| s.to_owned()).unwrap_or_default()+ .map(|s| s.to_owned())+ .unwrap_or_default()}// 1. set_agent_cursor_enabled missing field error.- let r1 = req(&mut pipe, r#"{"method":"call","name":"set_agent_cursor_enabled","args":{}}"#);+ let r1 = req(+ &mut pipe,+ r#"{"method":"call","name":"set_agent_cursor_enabled","args":{}}"#,+ );let e1 = extract_text(&serde_json::from_str(r1.trim()).unwrap());- assert!(e1.to_lowercase().contains("enabled") && e1.to_lowercase().contains("required"),- "Missing-enabled wording wrong: {e1:?}");+ assert!(+ e1.to_lowercase().contains("enabled") && e1.to_lowercase().contains("required"),+ "Missing-enabled wording wrong: {e1:?}"+ );println!("Missing-enabled err OK");// 2. set_agent_cursor_enabled true.- let r2 = req(&mut pipe, r#"{"method":"call","name":"set_agent_cursor_enabled","args":{"enabled":true}}"#);+ let r2 = req(+ &mut pipe,+ r#"{"method":"call","name":"set_agent_cursor_enabled","args":{"enabled":true}}"#,+ );let t2 = extract_text(&serde_json::from_str(r2.trim()).unwrap());assert_eq!(t2, "✅ Agent cursor enabled.", "Enabled text wrong: {t2:?}");println!("Enabled OK");// 3. set_agent_cursor_enabled false.- let r3 = req(&mut pipe, r#"{"method":"call","name":"set_agent_cursor_enabled","args":{"enabled":false}}"#);+ let r3 = req(+ &mut pipe,+ r#"{"method":"call","name":"set_agent_cursor_enabled","args":{"enabled":false}}"#,+ );let t3 = extract_text(&serde_json::from_str(r3.trim()).unwrap());- assert_eq!(t3, "✅ Agent cursor disabled.", "Disabled text wrong: {t3:?}");+ assert_eq!(+ t3, "✅ Agent cursor disabled.",+ "Disabled text wrong: {t3:?}"+ );println!("Disabled OK");// Re-enable for subsequent tests.- let _ = req(&mut pipe, r#"{"method":"call","name":"set_agent_cursor_enabled","args":{"enabled":true}}"#);+ let _ = req(+ &mut pipe,+ r#"{"method":"call","name":"set_agent_cursor_enabled","args":{"enabled":true}}"#,+ );// 4. set_agent_cursor_motion — tune knobs.- let r4 = req(&mut pipe,- r#"{"method":"call","name":"set_agent_cursor_motion","args":{"start_handle":0.4,"arc_size":0.3,"spring":0.8,"glide_duration_ms":500}}"#);+ let r4 = req(+ &mut pipe,+ r#"{"method":"call","name":"set_agent_cursor_motion","args":{"start_handle":0.4,"arc_size":0.3,"spring":0.8,"glide_duration_ms":500}}"#,+ );let v4: serde_json::Value = serde_json::from_str(r4.trim()).unwrap();let t4 = extract_text(&v4);println!("Motion resp: {t4:?}");- assert!(t4.starts_with("✅ cursor motion: startHandle=0.4 endHandle=") && t4.contains("arcSize=0.3")- && t4.contains("spring=0.8") && t4.contains("glideDurationMs=500"),- "Motion text doesn't match Swift format: {t4:?}");+ assert!(+ t4.starts_with("✅ cursor motion: startHandle=0.4 endHandle=")+ && t4.contains("arcSize=0.3")+ && t4.contains("spring=0.8")+ && t4.contains("glideDurationMs=500"),+ "Motion text doesn't match Swift format: {t4:?}"+ );println!("\n✅ PASS: set_agent_cursor_enabled + set_agent_cursor_motion match Swift");}diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/click_domains.rs b/libs/cua-driver/rust/crates/platform-windows/examples/click_domains.rsindex db131bb8e1..f21c05036f 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/click_domains.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/click_domains.rs@@ -9,7 +9,8 @@ fn main() {let chrome_wid = 4464038u64;let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe");@@ -20,28 +21,40 @@ fn main() {let mut buf = [0u8; 65536];let deadline = Instant::now() + Duration::from_secs(8);loop {- if Instant::now() > deadline { break; }+ if Instant::now() > deadline {+ break;+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}// Enable cursor.- req(&mut pipe, r#"{"method":"call","name":"set_agent_cursor_enabled","args":{"enabled":true}}"#);+ req(+ &mut pipe,+ r#"{"method":"call","name":"set_agent_cursor_enabled","args":{"enabled":true}}"#,+ );// Get window state with "Domains" query filter.let state_req = format!(r#"{{"method":"call","name":"get_window_state","args":{{"pid":{},"window_id":{},"query":"Domains"}}}}"#,- chrome_pid, chrome_wid);+ chrome_pid, chrome_wid+ );let state_resp = req(&mut pipe, &state_req);// Find the Domains element index in the tree text. Tree format:// "- [N] Hyperlink \"Domains\" ..."// Find any clickable element whose name contains "Domains" — search the// \"Domains\" or "Domain" name.- let query = std::env::args().nth(1).unwrap_or_else(|| "Domains".to_owned());+ let query = std::env::args()+ .nth(1)+ .unwrap_or_else(|| "Domains".to_owned());let needle = format!("\"{}\"", query);let candidates: Vec<(u64, String)> = state_resp.split("\\n")@@ -51,11 +64,19 @@ fn main() {let n_str = after_bracket.split(']').next()?;let idx: u64 = n_str.parse().ok()?;Some((idx, l.to_owned()))- }).collect();+ })+ .collect();if candidates.is_empty() {eprintln!("No clickable element matching {needle}.");eprintln!("Tree dump (first 2000 chars):");- eprintln!("{}", &state_resp.replace("\\n", "\n").chars().take(2000).collect::<String>());+ eprintln!(+ "{}",+ &state_resp+ .replace("\\n", "\n")+ .chars()+ .take(2000)+ .collect::<String>()+ );std::process::exit(1);}for (i, (idx, line)) in candidates.iter().enumerate() {@@ -66,7 +87,8 @@ fn main() {let click_req = format!(r#"{{"method":"call","name":"click","args":{{"pid":{},"window_id":{},"element_index":{}}}}}"#,- chrome_pid, chrome_wid, idx);+ chrome_pid, chrome_wid, idx+ );let click_resp = req(&mut pipe, &click_req);println!("Click resp: {}", click_resp.trim());}diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/click_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/click_parity.rsindex 9e8474bf53..04ec1bd823 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/click_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/click_parity.rs@@ -14,7 +14,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe — start daemon first");@@ -25,11 +26,17 @@ fn main() {let mut buf = [0u8; 65536];let deadline = Instant::now() + Duration::from_secs(4);loop {- if Instant::now() > deadline { panic!("response timeout"); }+ if Instant::now() > deadline {+ panic!("response timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}@@ -53,30 +60,58 @@ fn main() {// 2. Pixel click — pick the first window we can find belonging to our own// daemon (cua-driver.exe doesn't have one, so use the foreground app).// Use list_windows to get a real pid + hwnd, then click on it.- let lw = req(&mut pipe, r#"{"method":"call","name":"list_windows","args":{}}"#);+ let lw = req(+ &mut pipe,+ r#"{"method":"call","name":"list_windows","args":{}}"#,+ );let lwv: serde_json::Value = serde_json::from_str(lw.trim()).expect("parse");- let wins = lwv.pointer("/result/structuredContent/windows").and_then(|w| w.as_array())+ let wins = lwv+ .pointer("/result/structuredContent/windows")+ .and_then(|w| w.as_array()).expect("no windows array");// Prefer Chrome — we already verified it accepts PostMessage clicks// earlier in the session. Skip windows that reject PostMessage// (e.g. parsecd, system processes).let preferred = ["chrome.exe", "msedge.exe", "firefox.exe", "notepad.exe"];- let target = wins.iter().find(|w| {- let name = w.pointer("/app_name").and_then(|s| s.as_str()).unwrap_or("").to_lowercase();- preferred.iter().any(|p| name.contains(p))- }).or_else(|| wins.iter().find(|w| {- let name = w.pointer("/app_name").and_then(|s| s.as_str()).unwrap_or("");- !name.contains("cua-driver") && !name.contains("parsecd")- && !name.contains("examples") && !name.contains("dwm")- })).expect("no suitable target window");+ let target = wins+ .iter()+ .find(|w| {+ let name = w+ .pointer("/app_name")+ .and_then(|s| s.as_str())+ .unwrap_or("")+ .to_lowercase();+ preferred.iter().any(|p| name.contains(p))+ })+ .or_else(|| {+ wins.iter().find(|w| {+ let name = w+ .pointer("/app_name")+ .and_then(|s| s.as_str())+ .unwrap_or("");+ !name.contains("cua-driver")+ && !name.contains("parsecd")+ && !name.contains("examples")+ && !name.contains("dwm")+ })+ })+ .expect("no suitable target window");let pid = target.pointer("/pid").and_then(|n| n.as_u64()).unwrap();- let wid = target.pointer("/window_id").and_then(|n| n.as_u64()).unwrap();- println!("Clicking pid={pid} window_id={wid} app={}", target.pointer("/app_name").and_then(|s| s.as_str()).unwrap_or("?"));+ let wid = target+ .pointer("/window_id")+ .and_then(|n| n.as_u64())+ .unwrap();+ println!(+ "Clicking pid={pid} window_id={wid} app={}",+ target+ .pointer("/app_name")+ .and_then(|s| s.as_str())+ .unwrap_or("?")+ );// 1. Missing-target wording (now that we have a real pid + window_id).- let missing_req = format!(- r#"{{"method":"call","name":"click","args":{{"pid":{pid},"window_id":{wid}}}}}"#- );+ let missing_req =+ format!(r#"{{"method":"call","name":"click","args":{{"pid":{pid},"window_id":{wid}}}}}"#);let r_m = req(&mut pipe, &missing_req);let v_m: serde_json::Value = serde_json::from_str(r_m.trim()).expect("parse");let err1 = extract_text(&v_m);diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/config_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/config_parity.rsindex 80784c64e0..abaee1b79f 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/config_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/config_parity.rs@@ -6,7 +6,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe");@@ -17,28 +18,44 @@ fn main() {let mut buf: Vec<u8> = vec![0u8; 64 * 1024];let deadline = Instant::now() + Duration::from_secs(4);loop {- if Instant::now() > deadline { panic!("timeout"); }+ if Instant::now() > deadline {+ panic!("timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}fn extract_text(v: &serde_json::Value) -> String {- v.pointer("/result/content/0/text").and_then(|t| t.as_str())+ v.pointer("/result/content/0/text")+ .and_then(|t| t.as_str()).or_else(|| v.pointer("/error").and_then(|e| e.as_str()))- .map(|s| s.to_owned()).unwrap_or_default()+ .map(|s| s.to_owned())+ .unwrap_or_default()}// 1. get_config — text starts with "✅ " followed by pretty JSON.- let r1 = req(&mut pipe, r#"{"method":"call","name":"get_config","args":{}}"#);+ let r1 = req(+ &mut pipe,+ r#"{"method":"call","name":"get_config","args":{}}"#,+ );let v1: serde_json::Value = serde_json::from_str(r1.trim()).unwrap();let t1 = extract_text(&v1);- assert!(t1.starts_with("✅ "), "get_config text should start with '✅ ': {t1:?}");+ assert!(+ t1.starts_with("✅ "),+ "get_config text should start with '✅ ': {t1:?}"+ );// Pretty JSON should contain schema_version and capture_mode keys.- assert!(t1.contains("\"schema_version\"") && t1.contains("\"capture_mode\""),- "get_config JSON missing keys: {t1:?}");+ assert!(+ t1.contains("\"schema_version\"") && t1.contains("\"capture_mode\""),+ "get_config JSON missing keys: {t1:?}"+ );// structuredContent should have the same fields.let sc1 = v1.pointer("/result/structuredContent").unwrap();assert!(sc1.get("schema_version").is_some());@@ -47,40 +64,66 @@ fn main() {println!("get_config OK");// 2. set_config Swift-style {key, value}.- let r2 = req(&mut pipe,- r#"{"method":"call","name":"set_config","args":{"key":"capture_mode","value":"vision"}}"#);+ let r2 = req(+ &mut pipe,+ r#"{"method":"call","name":"set_config","args":{"key":"capture_mode","value":"vision"}}"#,+ );let v2: serde_json::Value = serde_json::from_str(r2.trim()).unwrap();- let cm = v2.pointer("/result/structuredContent/capture_mode").and_then(|s| s.as_str());- assert_eq!(cm, Some("vision"), "set_config didn't update capture_mode via {{key, value}}");+ let cm = v2+ .pointer("/result/structuredContent/capture_mode")+ .and_then(|s| s.as_str());+ assert_eq!(+ cm,+ Some("vision"),+ "set_config didn't update capture_mode via {{key, value}}"+ );println!("set_config Swift-style OK (capture_mode=vision)");// 3. set_config legacy per-field shape.- let r3 = req(&mut pipe,- r#"{"method":"call","name":"set_config","args":{"capture_mode":"som","max_image_dimension":1024}}"#);+ let r3 = req(+ &mut pipe,+ r#"{"method":"call","name":"set_config","args":{"capture_mode":"som","max_image_dimension":1024}}"#,+ );let v3: serde_json::Value = serde_json::from_str(r3.trim()).unwrap();- let cm3 = v3.pointer("/result/structuredContent/capture_mode").and_then(|s| s.as_str());- let md3 = v3.pointer("/result/structuredContent/max_image_dimension").and_then(|n| n.as_u64());+ let cm3 = v3+ .pointer("/result/structuredContent/capture_mode")+ .and_then(|s| s.as_str());+ let md3 = v3+ .pointer("/result/structuredContent/max_image_dimension")+ .and_then(|n| n.as_u64());assert_eq!(cm3, Some("som"));assert_eq!(md3, Some(1024));println!("set_config legacy OK (capture_mode=som, max=1024)");// 4. set_config unknown key error.- let r4 = req(&mut pipe,- r#"{"method":"call","name":"set_config","args":{"key":"bogus","value":42}}"#);+ let r4 = req(+ &mut pipe,+ r#"{"method":"call","name":"set_config","args":{"key":"bogus","value":42}}"#,+ );let e4 = extract_text(&serde_json::from_str(r4.trim()).unwrap());- assert!(e4.contains("Unknown config key"), "Unknown-key wording wrong: {e4:?}");+ assert!(+ e4.contains("Unknown config key"),+ "Unknown-key wording wrong: {e4:?}"+ );println!("set_config unknown-key err OK");// 5. set_config missing inputs error.- let r5 = req(&mut pipe, r#"{"method":"call","name":"set_config","args":{}}"#);+ let r5 = req(+ &mut pipe,+ r#"{"method":"call","name":"set_config","args":{}}"#,+ );let e5 = extract_text(&serde_json::from_str(r5.trim()).unwrap());- assert!(e5.to_lowercase().contains("required") || e5.to_lowercase().contains("missing"),- "Missing-input wording should mention required/missing: {e5:?}");+ assert!(+ e5.to_lowercase().contains("required") || e5.to_lowercase().contains("missing"),+ "Missing-input wording should mention required/missing: {e5:?}"+ );println!("set_config missing-input err OK");// Restore defaults.- let _ = req(&mut pipe,- r#"{"method":"call","name":"set_config","args":{"capture_mode":"som","max_image_dimension":0}}"#);+ let _ = req(+ &mut pipe,+ r#"{"method":"call","name":"set_config","args":{"capture_mode":"som","max_image_dimension":0}}"#,+ );println!("\n✅ PASS: get_config + set_config (Swift-style and legacy) verified");}diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/cursor_visibility.rs b/libs/cua-driver/rust/crates/platform-windows/examples/cursor_visibility.rsindex 359197f19f..e392ce8202 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/cursor_visibility.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/cursor_visibility.rs@@ -18,7 +18,8 @@ fn main() {let target_y = 500i32;let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe — start daemon first");println!("[1] connected");@@ -30,24 +31,37 @@ fn main() {let mut buf = [0u8; 8192];let deadline = Instant::now() + Duration::from_secs(2);loop {- if Instant::now() > deadline { break; }+ if Instant::now() > deadline {+ break;+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}- let r2 = req(&mut pipe, r#"{"method":"call","name":"set_agent_cursor_enabled","args":{"enabled":true}}"#);+ let r2 = req(+ &mut pipe,+ r#"{"method":"call","name":"set_agent_cursor_enabled","args":{"enabled":true}}"#,+ );println!(" enabled resp: {}", r2.trim());// Set bright pure-magenta gradient — easy to find, won't match any normal screen content.- let r3 = req(&mut pipe, r##"{"method":"call","name":"set_agent_cursor_style","args":{"gradient_colors":["#FF00FF","#FF00FF","#FF00FF"],"bloom_color":"#FF00FF"}}"##);+ let r3 = req(+ &mut pipe,+ r##"{"method":"call","name":"set_agent_cursor_style","args":{"gradient_colors":["#FF00FF","#FF00FF","#FF00FF"],"bloom_color":"#FF00FF"}}"##,+ );println!(" style resp: {}", r3.trim());let cmd = format!(r#"{{"method":"call","name":"move_cursor","args":{{"x":{},"y":{}}}}}"#,- target_x, target_y);+ target_x, target_y+ );let r4 = req(&mut pipe, &cmd);println!(" move resp: {}", r4.trim());@@ -60,27 +74,44 @@ fn main() {let mut png;loop {std::thread::sleep(Duration::from_millis(150));- png = platform_windows::capture::screenshot_display_bytes()- .expect("screenshot");+ png = platform_windows::capture::screenshot_display_bytes().expect("screenshot");let img = image::load_from_memory(&png).expect("decode");let rgba = img.to_rgba8();let (iw, ih) = img.dimensions();- let mut count = 0u64; let mut sx = 0i64; let mut sy = 0i64;- for py in 0..ih { for px in 0..iw {- let p = rgba.get_pixel(px, py).0;- if p[0] > 180 && p[1] < 100 && p[2] > 180 {- count += 1; sx += px as i64; sy += py as i64;+ let mut count = 0u64;+ let mut sx = 0i64;+ let mut sy = 0i64;+ for py in 0..ih {+ for px in 0..iw {+ let p = rgba.get_pixel(px, py).0;+ if p[0] > 180 && p[1] < 100 && p[2] > 180 {+ count += 1;+ sx += px as i64;+ sy += py as i64;+ }}- }}+ }if count > 50 {let c = (sx / count as i64, sy / count as i64);let dist = ((c.0 - last_centroid.0).pow(2) + (c.1 - last_centroid.1).pow(2)) as f64;- if dist.sqrt() < 3.0 { stable_ticks += 1; } else { stable_ticks = 0; }- println!(" polling: centroid=({},{}) count={} stable={}", c.0, c.1, count, stable_ticks);+ if dist.sqrt() < 3.0 {+ stable_ticks += 1;+ } else {+ stable_ticks = 0;+ }+ println!(+ " polling: centroid=({},{}) count={} stable={}",+ c.0, c.1, count, stable_ticks+ );last_centroid = c;- if stable_ticks >= 3 { break; }+ if stable_ticks >= 3 {+ break;+ }+ }+ if Instant::now() > deadline {+ println!(" polling: deadline reached");+ break;}- if Instant::now() > deadline { println!(" polling: deadline reached"); break; }}let _ = std::fs::write("O:/tmp_cursor_screen.png", &png);let img = image::load_from_memory(&png).expect("decode");@@ -89,18 +120,24 @@ fn main() {// Search whole screen for magenta-ish pixels (R high, G low, B high).let mut magenta_count = 0u64;- let mut sx = 0i64; let mut sy = 0i64;- let mut min_x = w as i32; let mut max_x = 0i32;- let mut min_y = h as i32; let mut max_y = 0i32;+ let mut sx = 0i64;+ let mut sy = 0i64;+ let mut min_x = w as i32;+ let mut max_x = 0i32;+ let mut min_y = h as i32;+ let mut max_y = 0i32;for py in 0..h {for px in 0..w {let p = rgba.get_pixel(px, py).0;// Tolerate antialiasing: R > 180, G < 100, B > 180if p[0] > 180 && p[1] < 100 && p[2] > 180 {magenta_count += 1;- sx += px as i64; sy += py as i64;- min_x = min_x.min(px as i32); max_x = max_x.max(px as i32);- min_y = min_y.min(py as i32); max_y = max_y.max(py as i32);+ sx += px as i64;+ sy += py as i64;+ min_x = min_x.min(px as i32);+ max_x = max_x.max(px as i32);+ min_y = min_y.min(py as i32);+ max_y = max_y.max(py as i32);}}}diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/daemon_lifecycle_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/daemon_lifecycle_parity.rsindex 6ecb143808..b7a7485611 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/daemon_lifecycle_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/daemon_lifecycle_parity.rs@@ -5,50 +5,84 @@ use std::process::Command;#[cfg(target_os = "windows")]fn main() {let exe = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))- .parent().unwrap()- .parent().unwrap()+ .parent()+ .unwrap()+ .parent()+ .unwrap().join("target/debug/cua-driver.exe");// Assume a daemon is running for these tests.// 1. status — should match Swift's 3-line output format.let out = Command::new(&exe).arg("status").output().expect("status");- assert!(out.status.success(), "status should succeed when daemon is running");+ assert!(+ out.status.success(),+ "status should succeed when daemon is running"+ );let stdout = String::from_utf8_lossy(&out.stdout);let lines: Vec<&str> = stdout.lines().collect();- assert!(lines.len() >= 2, "status should print at least 2 lines, got: {stdout:?}");- assert_eq!(lines[0], "Cua Driver daemon is running",- "first line wrong: {:?}", lines[0]);- assert!(lines[1].trim_start().starts_with("socket:"),- "second line should start with 'socket:': {:?}", lines[1]);+ assert!(+ lines.len() >= 2,+ "status should print at least 2 lines, got: {stdout:?}"+ );+ assert_eq!(+ lines[0], "Cua Driver daemon is running",+ "first line wrong: {:?}",+ lines[0]+ );+ assert!(+ lines[1].trim_start().starts_with("socket:"),+ "second line should start with 'socket:': {:?}",+ lines[1]+ );if lines.len() >= 3 {- assert!(lines[2].trim_start().starts_with("pid:"),- "third line should start with 'pid:': {:?}", lines[2]);+ assert!(+ lines[2].trim_start().starts_with("pid:"),+ "third line should start with 'pid:': {:?}",+ lines[2]+ );}println!("status OK");// 2. stop — should produce silent stdout on success (Swift parity).let out2 = Command::new(&exe).arg("stop").output().expect("stop");- assert!(out2.status.success(), "stop should succeed when daemon is running");+ assert!(+ out2.status.success(),+ "stop should succeed when daemon is running"+ );let stdout2 = String::from_utf8_lossy(&out2.stdout);- assert!(stdout2.trim().is_empty(),- "Swift's stop is silent on success; got stdout: {stdout2:?}");+ assert!(+ stdout2.trim().is_empty(),+ "Swift's stop is silent on success; got stdout: {stdout2:?}"+ );println!("stop OK (silent stdout, matches Swift)");// 3. status after stop — exit code 1, stderr "not running".let out3 = Command::new(&exe).arg("status").output().expect("status2");- assert_eq!(out3.status.code(), Some(1), "status after stop should exit 1");+ assert_eq!(+ out3.status.code(),+ Some(1),+ "status after stop should exit 1"+ );let stderr3 = String::from_utf8_lossy(&out3.stderr);- assert!(stderr3.contains("Cua Driver daemon is not running"),- "stderr should say 'not running': {stderr3:?}");+ assert!(+ stderr3.contains("Cua Driver daemon is not running"),+ "stderr should say 'not running': {stderr3:?}"+ );println!("status-not-running OK");// 4. stop on dead daemon — exit 1, stderr "not running".let out4 = Command::new(&exe).arg("stop").output().expect("stop2");- assert_eq!(out4.status.code(), Some(1), "stop on dead daemon should exit 1");+ assert_eq!(+ out4.status.code(),+ Some(1),+ "stop on dead daemon should exit 1"+ );let stderr4 = String::from_utf8_lossy(&out4.stderr);- assert!(stderr4.contains("Cua Driver daemon is not running"),- "stderr should say 'not running': {stderr4:?}");+ assert!(+ stderr4.contains("Cua Driver daemon is not running"),+ "stderr should say 'not running': {stderr4:?}"+ );println!("stop-not-running OK");println!("\n✅ PASS: status + stop output + exit codes match Swift");diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/describe_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/describe_parity.rsindex 4164adab0a..f9e27e5cd9 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/describe_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/describe_parity.rs@@ -5,8 +5,10 @@ use std::process::Command;#[cfg(target_os = "windows")]fn main() {let exe = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))- .parent().unwrap()- .parent().unwrap()+ .parent()+ .unwrap()+ .parent()+ .unwrap().join("target/debug/cua-driver.exe");// 1. Known tool — describe `click`.@@ -16,13 +18,25 @@ fn main() {.expect("run cua-driver describe click");assert!(out.status.success(), "describe click failed: {:?}", out);let stdout = String::from_utf8_lossy(&out.stdout);- assert!(stdout.starts_with("name: click\n"),- "describe should start with 'name: click\\n', got: {:?}", &stdout[..stdout.len().min(40)]);- assert!(stdout.contains("\ndescription:\n"), "describe missing description: block");- assert!(stdout.contains("\ninput_schema:\n"), "describe missing input_schema: block");+ assert!(+ stdout.starts_with("name: click\n"),+ "describe should start with 'name: click\\n', got: {:?}",+ &stdout[..stdout.len().min(40)]+ );+ assert!(+ stdout.contains("\ndescription:\n"),+ "describe missing description: block"+ );+ assert!(+ stdout.contains("\ninput_schema:\n"),+ "describe missing input_schema: block"+ );// The JSON schema after should be pretty-printed (multi-line).let schema_section = stdout.split("\ninput_schema:\n").nth(1).unwrap_or("");- assert!(schema_section.contains("\n "), "input_schema should be pretty-printed JSON");+ assert!(+ schema_section.contains("\n "),+ "input_schema should be pretty-printed JSON"+ );println!("describe known-tool OK");// 2. Unknown tool — exit code 64, stderr lists tools alphabetically.@@ -30,19 +44,33 @@ fn main() {.args(["describe", "this_tool_does_not_exist"]).output().expect("run cua-driver describe missing");- assert_eq!(out2.status.code(), Some(64), "exit code should be 64 (EX_USAGE), got: {:?}", out2.status.code());+ assert_eq!(+ out2.status.code(),+ Some(64),+ "exit code should be 64 (EX_USAGE), got: {:?}",+ out2.status.code()+ );let stderr = String::from_utf8_lossy(&out2.stderr);- assert!(stderr.contains("Unknown tool: this_tool_does_not_exist"),- "stderr missing 'Unknown tool:' line: {stderr:?}");- assert!(stderr.contains("Available tools:"),- "stderr missing 'Available tools:' header");+ assert!(+ stderr.contains("Unknown tool: this_tool_does_not_exist"),+ "stderr missing 'Unknown tool:' line: {stderr:?}"+ );+ assert!(+ stderr.contains("Available tools:"),+ "stderr missing 'Available tools:' header"+ );// Parse the listed tools (each on its own indented line) and verify sort.- let listed: Vec<&str> = stderr.lines()+ let listed: Vec<&str> = stderr+ .lines().filter(|l| l.starts_with(" ") && !l.trim().is_empty()).map(|l| l.trim()).collect();- let mut sorted = listed.clone(); sorted.sort();- assert_eq!(listed, sorted, "available tools should be sorted alphabetically");+ let mut sorted = listed.clone();+ sorted.sort();+ assert_eq!(+ listed, sorted,+ "available tools should be sorted alphabetically"+ );println!("describe unknown-tool OK ({} tools listed)", listed.len());println!("\n✅ PASS: describe known/unknown paths + Swift sort verified");diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/double_click_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/double_click_parity.rsindex d8ceece23c..a23e3d209a 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/double_click_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/double_click_parity.rs@@ -6,7 +6,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe");@@ -17,78 +18,129 @@ fn main() {let mut buf = [0u8; 65536];let deadline = Instant::now() + Duration::from_secs(4);loop {- if Instant::now() > deadline { panic!("timeout"); }+ if Instant::now() > deadline {+ panic!("timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}fn extract_text(v: &serde_json::Value) -> String {- v.pointer("/result/content/0/text").and_then(|t| t.as_str())+ v.pointer("/result/content/0/text")+ .and_then(|t| t.as_str()).or_else(|| v.pointer("/error").and_then(|e| e.as_str()))- .map(|s| s.to_owned()).unwrap_or_default()+ .map(|s| s.to_owned())+ .unwrap_or_default()}// Find a Chrome window to click on (same approach as click_parity).- let lw = req(&mut pipe, r#"{"method":"call","name":"list_windows","args":{}}"#);+ let lw = req(+ &mut pipe,+ r#"{"method":"call","name":"list_windows","args":{}}"#,+ );let lwv: serde_json::Value = serde_json::from_str(lw.trim()).unwrap();- let wins = lwv.pointer("/result/structuredContent/windows").and_then(|w| w.as_array()).unwrap();- let target = wins.iter().find(|w| {- let n = w.pointer("/app_name").and_then(|s| s.as_str()).unwrap_or("").to_lowercase();- n.contains("chrome") || n.contains("notepad")- }).expect("no chrome/notepad");+ let wins = lwv+ .pointer("/result/structuredContent/windows")+ .and_then(|w| w.as_array())+ .unwrap();+ let target = wins+ .iter()+ .find(|w| {+ let n = w+ .pointer("/app_name")+ .and_then(|s| s.as_str())+ .unwrap_or("")+ .to_lowercase();+ n.contains("chrome") || n.contains("notepad")+ })+ .expect("no chrome/notepad");let pid = target.pointer("/pid").and_then(|n| n.as_u64()).unwrap();- let wid = target.pointer("/window_id").and_then(|n| n.as_u64()).unwrap();+ let wid = target+ .pointer("/window_id")+ .and_then(|n| n.as_u64())+ .unwrap();// 1. Missing target with valid pid+window_id.- let r1 = req(&mut pipe, &format!(- r#"{{"method":"call","name":"double_click","args":{{"pid":{pid},"window_id":{wid}}}}}"#));+ let r1 = req(+ &mut pipe,+ &format!(+ r#"{{"method":"call","name":"double_click","args":{{"pid":{pid},"window_id":{wid}}}}}"#+ ),+ );let v1: serde_json::Value = serde_json::from_str(r1.trim()).unwrap();let e1 = extract_text(&v1);- assert!(e1.contains("Provide element_index or (x, y) to address the double-click target"),- "Missing-target wording wrong: {e1:?}");+ assert!(+ e1.contains("Provide element_index or (x, y) to address the double-click target"),+ "Missing-target wording wrong: {e1:?}"+ );println!("Missing-target err OK");// 2. Partial xy: x without y.- let r2 = req(&mut pipe, &format!(- r#"{{"method":"call","name":"double_click","args":{{"pid":{pid},"window_id":{wid},"x":100}}}}"#));+ let r2 = req(+ &mut pipe,+ &format!(+ r#"{{"method":"call","name":"double_click","args":{{"pid":{pid},"window_id":{wid},"x":100}}}}"#+ ),+ );let v2: serde_json::Value = serde_json::from_str(r2.trim()).unwrap();let e2 = extract_text(&v2);- assert!(e2.contains("Provide both x and y together"),- "Partial-xy wording wrong: {e2:?}");+ assert!(+ e2.contains("Provide both x and y together"),+ "Partial-xy wording wrong: {e2:?}"+ );println!("Partial-xy err OK");// 3. Both element_index AND xy.- let r3 = req(&mut pipe, &format!(- r#"{{"method":"call","name":"double_click","args":{{"pid":{pid},"window_id":{wid},"element_index":0,"x":100,"y":100}}}}"#));+ let r3 = req(+ &mut pipe,+ &format!(+ r#"{{"method":"call","name":"double_click","args":{{"pid":{pid},"window_id":{wid},"element_index":0,"x":100,"y":100}}}}"#+ ),+ );let v3: serde_json::Value = serde_json::from_str(r3.trim()).unwrap();let e3 = extract_text(&v3);- assert!(e3.contains("Provide either element_index or (x, y), not both"),- "Both-modes wording wrong: {e3:?}");+ assert!(+ e3.contains("Provide either element_index or (x, y), not both"),+ "Both-modes wording wrong: {e3:?}"+ );println!("Both-modes err OK");// 4. element_index without window_id.- let r4 = req(&mut pipe, &format!(- r#"{{"method":"call","name":"double_click","args":{{"pid":{pid},"element_index":0}}}}"#));+ let r4 = req(+ &mut pipe,+ &format!(+ r#"{{"method":"call","name":"double_click","args":{{"pid":{pid},"element_index":0}}}}"#+ ),+ );let v4: serde_json::Value = serde_json::from_str(r4.trim()).unwrap();let e4 = extract_text(&v4);- assert!(e4.contains("window_id is required when element_index is used"),- "Element-without-window wording wrong: {e4:?}");+ assert!(+ e4.contains("window_id is required when element_index is used"),+ "Element-without-window wording wrong: {e4:?}"+ );println!("Element-without-window err OK");// 5. Real pixel double-click.let dc_req = format!(- r#"{{"method":"call","name":"double_click","args":{{"pid":{pid},"window_id":{wid},"x":300,"y":300}}}}"#);+ r#"{{"method":"call","name":"double_click","args":{{"pid":{pid},"window_id":{wid},"x":300,"y":300}}}}"#+ );let r5 = req(&mut pipe, &dc_req);let v5: serde_json::Value = serde_json::from_str(r5.trim()).unwrap();let t5 = extract_text(&v5);println!("Double-click resp: {t5:?}");- assert!(t5.starts_with("✅ Posted double-click to pid ")- && t5.contains(" at window-pixel (")- && t5.contains(" → screen-point ("),- "Pixel-path text doesn't match Swift format: {t5:?}");+ assert!(+ t5.starts_with("✅ Posted double-click to pid ")+ && t5.contains(" at window-pixel (")+ && t5.contains(" → screen-point ("),+ "Pixel-path text doesn't match Swift format: {t5:?}"+ );println!("\n✅ PASS: double_click validation + pixel-path text match Swift");}diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/drag_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/drag_parity.rsindex 4e6e0aa880..933f82cf14 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/drag_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/drag_parity.rs@@ -6,7 +6,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe");@@ -17,48 +18,84 @@ fn main() {let mut buf: Vec<u8> = vec![0u8; 64 * 1024];let deadline = Instant::now() + Duration::from_secs(6);loop {- if Instant::now() > deadline { panic!("timeout"); }+ if Instant::now() > deadline {+ panic!("timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}fn extract_text(v: &serde_json::Value) -> String {- v.pointer("/result/content/0/text").and_then(|t| t.as_str())+ v.pointer("/result/content/0/text")+ .and_then(|t| t.as_str()).or_else(|| v.pointer("/error").and_then(|e| e.as_str()))- .map(|s| s.to_owned()).unwrap_or_default()+ .map(|s| s.to_owned())+ .unwrap_or_default()}- let lw = req(&mut pipe, r#"{"method":"call","name":"list_windows","args":{}}"#);+ let lw = req(+ &mut pipe,+ r#"{"method":"call","name":"list_windows","args":{}}"#,+ );let lwv: serde_json::Value = serde_json::from_str(lw.trim()).unwrap();- let wins = lwv.pointer("/result/structuredContent/windows").and_then(|w| w.as_array()).unwrap();- let target = wins.iter().find(|w| {- let n = w.pointer("/app_name").and_then(|s| s.as_str()).unwrap_or("").to_lowercase();- n.contains("chrome")- }).expect("no chrome");+ let wins = lwv+ .pointer("/result/structuredContent/windows")+ .and_then(|w| w.as_array())+ .unwrap();+ let target = wins+ .iter()+ .find(|w| {+ let n = w+ .pointer("/app_name")+ .and_then(|s| s.as_str())+ .unwrap_or("")+ .to_lowercase();+ n.contains("chrome")+ })+ .expect("no chrome");let pid = target.pointer("/pid").and_then(|n| n.as_u64()).unwrap();- let wid = target.pointer("/window_id").and_then(|n| n.as_u64()).unwrap();+ let wid = target+ .pointer("/window_id")+ .and_then(|n| n.as_u64())+ .unwrap();// 1. Missing coordinates.- let r1 = req(&mut pipe, &format!(- r#"{{"method":"call","name":"drag","args":{{"pid":{pid},"window_id":{wid},"from_x":10}}}}"#));+ let r1 = req(+ &mut pipe,+ &format!(+ r#"{{"method":"call","name":"drag","args":{{"pid":{pid},"window_id":{wid},"from_x":10}}}}"#+ ),+ );let e1 = extract_text(&serde_json::from_str(r1.trim()).unwrap());- assert!(e1.contains("from_x, from_y, to_x, and to_y are all required"),- "Missing-coords wording wrong: {e1:?}");+ assert!(+ e1.contains("from_x, from_y, to_x, and to_y are all required"),+ "Missing-coords wording wrong: {e1:?}"+ );println!("Missing-coords err OK");// 2. Real drag — short, won't break Chrome.- let r2 = req(&mut pipe, &format!(- r#"{{"method":"call","name":"drag","args":{{"pid":{pid},"window_id":{wid},"from_x":100,"from_y":100,"to_x":102,"to_y":102,"duration_ms":50,"steps":2}}}}"#));+ let r2 = req(+ &mut pipe,+ &format!(+ r#"{{"method":"call","name":"drag","args":{{"pid":{pid},"window_id":{wid},"from_x":100,"from_y":100,"to_x":102,"to_y":102,"duration_ms":50,"steps":2}}}}"#+ ),+ );let t2 = extract_text(&serde_json::from_str(r2.trim()).unwrap());println!("Drag resp: {t2:?}");- assert!(t2.starts_with("✅ Posted drag to pid ")- && t2.contains("from window-pixel (")- && t2.contains("screen (")- && t2.contains("in 50ms / 2 steps."),- "Drag text format wrong: {t2:?}");+ assert!(+ t2.starts_with("✅ Posted drag to pid ")+ && t2.contains("from window-pixel (")+ && t2.contains("screen (")+ && t2.contains("in 50ms / 2 steps."),+ "Drag text format wrong: {t2:?}"+ );println!("\n✅ PASS: drag error wording + Swift-shape text format verified");}diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/dump_docs_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/dump_docs_parity.rsindex 008d25f4d2..2166202cf6 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/dump_docs_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/dump_docs_parity.rs@@ -5,8 +5,10 @@ use std::process::Command;#[cfg(target_os = "windows")]fn main() {let exe = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))- .parent().unwrap()- .parent().unwrap()+ .parent()+ .unwrap()+ .parent()+ .unwrap().join("target/debug/cua-driver.exe");// 1. Default: --type=all → {cli, mcp}.@@ -17,29 +19,61 @@ fn main() {assert!(v.get("cli").is_some(), "--type=all should have 'cli' key");assert!(v.get("mcp").is_some(), "--type=all should have 'mcp' key");assert!(v.pointer("/mcp/version").is_some(), "mcp.version missing");- let tools = v.pointer("/mcp/tools").and_then(|t| t.as_array()).expect("mcp.tools array");+ let tools = v+ .pointer("/mcp/tools")+ .and_then(|t| t.as_array())+ .expect("mcp.tools array");assert!(!tools.is_empty(), "mcp.tools should not be empty");println!("dump-docs (default) OK — {} tools", tools.len());// 2. --type=mcp → just {version, tools: [...]}.- let out2 = Command::new(&exe).args(["dump-docs", "--type", "mcp"]).output().expect("run");- let v2: serde_json::Value = serde_json::from_str(&String::from_utf8_lossy(&out2.stdout)).expect("valid JSON");- assert!(v2.get("cli").is_none(), "--type=mcp should NOT have 'cli' key");- assert!(v2.get("version").is_some(), "--type=mcp top-level should have version");- assert!(v2.get("tools").is_some(), "--type=mcp top-level should have tools");+ let out2 = Command::new(&exe)+ .args(["dump-docs", "--type", "mcp"])+ .output()+ .expect("run");+ let v2: serde_json::Value =+ serde_json::from_str(&String::from_utf8_lossy(&out2.stdout)).expect("valid JSON");+ assert!(+ v2.get("cli").is_none(),+ "--type=mcp should NOT have 'cli' key"+ );+ assert!(+ v2.get("version").is_some(),+ "--type=mcp top-level should have version"+ );+ assert!(+ v2.get("tools").is_some(),+ "--type=mcp top-level should have tools"+ );println!("dump-docs --type=mcp OK");// 3. --type=cli → CLI section only (stub on Rust).- let out3 = Command::new(&exe).args(["dump-docs", "--type", "cli"]).output().expect("run");- let v3: serde_json::Value = serde_json::from_str(&String::from_utf8_lossy(&out3.stdout)).expect("valid JSON");- assert!(v3.get("mcp").is_none(), "--type=cli should NOT have 'mcp' key");- assert!(v3.get("version").is_some(), "--type=cli should have version");+ let out3 = Command::new(&exe)+ .args(["dump-docs", "--type", "cli"])+ .output()+ .expect("run");+ let v3: serde_json::Value =+ serde_json::from_str(&String::from_utf8_lossy(&out3.stdout)).expect("valid JSON");+ assert!(+ v3.get("mcp").is_none(),+ "--type=cli should NOT have 'mcp' key"+ );+ assert!(+ v3.get("version").is_some(),+ "--type=cli should have version"+ );println!("dump-docs --type=cli OK");// 4. --pretty: should have multi-line output.- let out4 = Command::new(&exe).args(["dump-docs", "--pretty"]).output().expect("run");+ let out4 = Command::new(&exe)+ .args(["dump-docs", "--pretty"])+ .output()+ .expect("run");let stdout4 = String::from_utf8_lossy(&out4.stdout);- assert!(stdout4.lines().count() > 10, "--pretty should produce multi-line output");+ assert!(+ stdout4.lines().count() > 10,+ "--pretty should produce multi-line output"+ );println!("dump-docs --pretty OK ({} lines)", stdout4.lines().count());println!("\n✅ PASS: dump-docs --type cli/mcp/all + --pretty all work");diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/get_agent_cursor_state_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/get_agent_cursor_state_parity.rsindex 4dfd0c4d23..4ea2ca5427 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/get_agent_cursor_state_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/get_agent_cursor_state_parity.rs@@ -6,7 +6,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe");@@ -17,18 +18,30 @@ fn main() {let mut buf: Vec<u8> = vec![0u8; 64 * 1024];let deadline = Instant::now() + Duration::from_secs(4);loop {- if Instant::now() > deadline { panic!("timeout"); }+ if Instant::now() > deadline {+ panic!("timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}- let r = req(&mut pipe, r#"{"method":"call","name":"get_agent_cursor_state","args":{}}"#);+ let r = req(+ &mut pipe,+ r#"{"method":"call","name":"get_agent_cursor_state","args":{}}"#,+ );let v: serde_json::Value = serde_json::from_str(r.trim()).unwrap();- let text = v.pointer("/result/content/0/text").and_then(|t| t.as_str()).unwrap_or("");+ let text = v+ .pointer("/result/content/0/text")+ .and_then(|t| t.as_str())+ .unwrap_or("");println!("State text: {text:?}");// Verify Swift's exact key=value vocabulary.@@ -49,8 +62,18 @@ fn main() {// Verify structuredContent.let sc = v.pointer("/result/structuredContent").unwrap();- for k in &["enabled","start_handle","end_handle","arc_size","arc_flow","spring",- "glide_duration_ms","dwell_after_click_ms","idle_hide_ms","cursors"] {+ for k in &[+ "enabled",+ "start_handle",+ "end_handle",+ "arc_size",+ "arc_flow",+ "spring",+ "glide_duration_ms",+ "dwell_after_click_ms",+ "idle_hide_ms",+ "cursors",+ ] {assert!(sc.get(k).is_some(), "structuredContent missing {k}");}diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/get_cursor_position_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/get_cursor_position_parity.rsindex bcd2fbde19..2aac44a09f 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/get_cursor_position_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/get_cursor_position_parity.rs@@ -13,7 +13,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe — start daemon first");@@ -24,37 +25,54 @@ fn main() {let mut buf = [0u8; 8192];let deadline = Instant::now() + Duration::from_secs(4);loop {- if Instant::now() > deadline { panic!("response timeout"); }+ if Instant::now() > deadline {+ panic!("response timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}- let resp = req(&mut pipe, r#"{"method":"call","name":"get_cursor_position","args":{}}"#);+ let resp = req(+ &mut pipe,+ r#"{"method":"call","name":"get_cursor_position","args":{}}"#,+ );let v: serde_json::Value = serde_json::from_str(resp.trim()).expect("parse JSON");- let text = v.pointer("/result/content/0/text").and_then(|t| t.as_str())+ let text = v+ .pointer("/result/content/0/text")+ .and_then(|t| t.as_str()).expect("missing /result/content/0/text");println!("Response text: {text:?}");// Parse "✅ Cursor at (X, Y)" by hand — no regex crate dependency.- let stripped = text.strip_prefix("✅ Cursor at (")+ let stripped = text+ .strip_prefix("✅ Cursor at (").and_then(|s| s.strip_suffix(')'))- .unwrap_or_else(|| panic!(- "Text {text:?} does not match Swift format `✅ Cursor at (X, Y)`"- ));- let (xs, ys) = stripped.split_once(", ")+ .unwrap_or_else(|| {+ panic!("Text {text:?} does not match Swift format `✅ Cursor at (X, Y)`")+ });+ let (xs, ys) = stripped+ .split_once(", ").unwrap_or_else(|| panic!("missing `, ` between coords in {text:?}"));let tx: i64 = xs.parse().unwrap_or_else(|_| panic!("x not int: {xs}"));let ty: i64 = ys.parse().unwrap_or_else(|_| panic!("y not int: {ys}"));println!("Parsed text coords: ({tx}, {ty})");- let sx = v.pointer("/result/structuredContent/x").and_then(|n| n.as_i64())+ let sx = v+ .pointer("/result/structuredContent/x")+ .and_then(|n| n.as_i64()).expect("structuredContent.x not present or not integer");- let sy = v.pointer("/result/structuredContent/y").and_then(|n| n.as_i64())+ let sy = v+ .pointer("/result/structuredContent/y")+ .and_then(|n| n.as_i64()).expect("structuredContent.y not present or not integer");println!("Structured coords: ({sx}, {sy})");@@ -66,14 +84,25 @@ fn main() {use windows::Win32::Foundation::POINT;use windows::Win32::UI::WindowsAndMessaging::GetCursorPos;let mut pt = POINT { x: 0, y: 0 };- unsafe { let _ = GetCursorPos(&mut pt); }+ unsafe {+ let _ = GetCursorPos(&mut pt);+ }let dx = (pt.x as i64 - sx).abs();let dy = (pt.y as i64 - sy).abs();- println!("Native GetCursorPos: ({}, {}) — delta ({dx}, {dy})", pt.x, pt.y);- assert!(dx <= 5 && dy <= 5,- "get_cursor_position reports ({sx},{sy}) but native GetCursorPos says ({}, {})", pt.x, pt.y);+ println!(+ "Native GetCursorPos: ({}, {}) — delta ({dx}, {dy})",+ pt.x, pt.y+ );+ assert!(+ dx <= 5 && dy <= 5,+ "get_cursor_position reports ({sx},{sy}) but native GetCursorPos says ({}, {})",+ pt.x,+ pt.y+ );- println!("\n✅ PASS: text format matches Swift exactly, structuredContent agrees, native ≈ same");+ println!(+ "\n✅ PASS: text format matches Swift exactly, structuredContent agrees, native ≈ same"+ );}#[cfg(not(target_os = "windows"))]diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/get_screen_size_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/get_screen_size_parity.rsindex 558028a13e..c0002df69a 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/get_screen_size_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/get_screen_size_parity.rs@@ -14,7 +14,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe — start daemon first");@@ -25,29 +26,44 @@ fn main() {let mut buf = [0u8; 8192];let deadline = Instant::now() + Duration::from_secs(4);loop {- if Instant::now() > deadline { panic!("response timeout"); }+ if Instant::now() > deadline {+ panic!("response timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}- let resp = req(&mut pipe, r#"{"method":"call","name":"get_screen_size","args":{}}"#);+ let resp = req(+ &mut pipe,+ r#"{"method":"call","name":"get_screen_size","args":{}}"#,+ );let v: serde_json::Value = serde_json::from_str(resp.trim()).expect("parse JSON");- let text = v.pointer("/result/content/0/text").and_then(|t| t.as_str())+ let text = v+ .pointer("/result/content/0/text")+ .and_then(|t| t.as_str()).expect("missing text");println!("Response text: {text:?}");// Parse "✅ Main display: WxH pixels @ Sx" by hand.- let rest = text.strip_prefix("✅ Main display: ")+ let rest = text+ .strip_prefix("✅ Main display: ").unwrap_or_else(|| panic!("Text {text:?} missing prefix `✅ Main display: `"));- let (wh, scale_part) = rest.split_once(" pixels @ ")+ let (wh, scale_part) = rest+ .split_once(" pixels @ ").unwrap_or_else(|| panic!("Text {text:?} missing ` pixels @ `"));- let (w_str, h_str) = wh.split_once('x')+ let (w_str, h_str) = wh+ .split_once('x').unwrap_or_else(|| panic!("Text {text:?} missing `x` separator"));- let scale_str = scale_part.strip_suffix('x')+ let scale_str = scale_part+ .strip_suffix('x').unwrap_or_else(|| panic!("Text {text:?} missing trailing `x`"));let tw: i64 = w_str.parse().unwrap();let th: i64 = h_str.parse().unwrap();@@ -55,18 +71,32 @@ fn main() {println!("Parsed text: width={tw} height={th} scale={ts}");// Verify structuredContent.- let sw = v.pointer("/result/structuredContent/width").and_then(|n| n.as_i64()).expect("width");- let sh = v.pointer("/result/structuredContent/height").and_then(|n| n.as_i64()).expect("height");- let ss = v.pointer("/result/structuredContent/scale_factor").and_then(|n| n.as_f64()).expect("scale_factor");+ let sw = v+ .pointer("/result/structuredContent/width")+ .and_then(|n| n.as_i64())+ .expect("width");+ let sh = v+ .pointer("/result/structuredContent/height")+ .and_then(|n| n.as_i64())+ .expect("height");+ let ss = v+ .pointer("/result/structuredContent/scale_factor")+ .and_then(|n| n.as_f64())+ .expect("scale_factor");println!("Structured: width={sw} height={sh} scale_factor={ss}");assert_eq!((tw, th), (sw, sh));assert!((ts - ss).abs() < 0.001);// Sanity-check against native APIs.- use windows::Win32::UI::WindowsAndMessaging::{GetSystemMetrics, SM_CXSCREEN, SM_CYSCREEN};use windows::Win32::UI::HiDpi::GetDpiForSystem;- let (nw, nh) = unsafe { (GetSystemMetrics(SM_CXSCREEN) as i64, GetSystemMetrics(SM_CYSCREEN) as i64) };+ use windows::Win32::UI::WindowsAndMessaging::{GetSystemMetrics, SM_CXSCREEN, SM_CYSCREEN};+ let (nw, nh) = unsafe {+ (+ GetSystemMetrics(SM_CXSCREEN) as i64,+ GetSystemMetrics(SM_CYSCREEN) as i64,+ )+ };let dpi = unsafe { GetDpiForSystem() };let ns = if dpi == 0 { 1.0 } else { dpi as f64 / 96.0 };println!("Native: width={nw} height={nh} scale={ns}");diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/get_window_state_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/get_window_state_parity.rsindex 11736acd24..57a9f7f969 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/get_window_state_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/get_window_state_parity.rs@@ -6,7 +6,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe");@@ -17,43 +18,76 @@ fn main() {let mut buf: Vec<u8> = vec![0u8; 64 * 1024];let deadline = Instant::now() + Duration::from_secs(6);loop {- if Instant::now() > deadline { panic!("timeout"); }+ if Instant::now() > deadline {+ panic!("timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}fn extract_text(v: &serde_json::Value) -> String {- v.pointer("/result/content/0/text").and_then(|t| t.as_str())+ v.pointer("/result/content/0/text")+ .and_then(|t| t.as_str()).or_else(|| v.pointer("/error").and_then(|e| e.as_str()))- .map(|s| s.to_owned()).unwrap_or_default()+ .map(|s| s.to_owned())+ .unwrap_or_default()}// 1. Missing pid.- let r1 = req(&mut pipe, r#"{"method":"call","name":"get_window_state","args":{}}"#);+ let r1 = req(+ &mut pipe,+ r#"{"method":"call","name":"get_window_state","args":{}}"#,+ );let e1 = extract_text(&serde_json::from_str(r1.trim()).unwrap());- assert!(e1.to_lowercase().contains("pid") && e1.to_lowercase().contains("required"),- "Missing-pid wording wrong: {e1:?}");+ assert!(+ e1.to_lowercase().contains("pid") && e1.to_lowercase().contains("required"),+ "Missing-pid wording wrong: {e1:?}"+ );println!("Missing-pid err OK");// 2. Missing window_id (with valid pid).- let lw = req(&mut pipe, r#"{"method":"call","name":"list_windows","args":{}}"#);+ let lw = req(+ &mut pipe,+ r#"{"method":"call","name":"list_windows","args":{}}"#,+ );let lwv: serde_json::Value = serde_json::from_str(lw.trim()).unwrap();- let wins = lwv.pointer("/result/structuredContent/windows").and_then(|w| w.as_array()).unwrap();- let target = wins.iter().find(|w| {- let n = w.pointer("/app_name").and_then(|s| s.as_str()).unwrap_or("").to_lowercase();- n.contains("chrome")- }).expect("no chrome");+ let wins = lwv+ .pointer("/result/structuredContent/windows")+ .and_then(|w| w.as_array())+ .unwrap();+ let target = wins+ .iter()+ .find(|w| {+ let n = w+ .pointer("/app_name")+ .and_then(|s| s.as_str())+ .unwrap_or("")+ .to_lowercase();+ n.contains("chrome")+ })+ .expect("no chrome");let pid = target.pointer("/pid").and_then(|n| n.as_u64()).unwrap();- let wid = target.pointer("/window_id").and_then(|n| n.as_u64()).unwrap();+ let wid = target+ .pointer("/window_id")+ .and_then(|n| n.as_u64())+ .unwrap();- let r2 = req(&mut pipe, &format!(- r#"{{"method":"call","name":"get_window_state","args":{{"pid":{pid}}}}}"#));+ let r2 = req(+ &mut pipe,+ &format!(r#"{{"method":"call","name":"get_window_state","args":{{"pid":{pid}}}}}"#),+ );let e2 = extract_text(&serde_json::from_str(r2.trim()).unwrap());- assert!(e2.to_lowercase().contains("window_id") && e2.to_lowercase().contains("required"),- "Missing-window_id wording wrong: {e2:?}");+ assert!(+ e2.to_lowercase().contains("window_id") && e2.to_lowercase().contains("required"),+ "Missing-window_id wording wrong: {e2:?}"+ );println!("Missing-window_id err OK");// 3. Mismatched pid + window_id (pick another window's pid).@@ -63,20 +97,32 @@ fn main() {});if let Some(other) = other {let other_pid = other.pointer("/pid").and_then(|n| n.as_u64()).unwrap();- let r3 = req(&mut pipe, &format!(- r#"{{"method":"call","name":"get_window_state","args":{{"pid":{other_pid},"window_id":{wid}}}}}"#));+ let r3 = req(+ &mut pipe,+ &format!(+ r#"{{"method":"call","name":"get_window_state","args":{{"pid":{other_pid},"window_id":{wid}}}}}"#+ ),+ );let e3 = extract_text(&serde_json::from_str(r3.trim()).unwrap());- assert!(e3.contains("belongs to pid") || e3.contains("No window with window_id"),- "Mismatched-pid wording wrong: {e3:?}");+ assert!(+ e3.contains("belongs to pid") || e3.contains("No window with window_id"),+ "Mismatched-pid wording wrong: {e3:?}"+ );println!("Mismatched-pid err OK");}// 4. Bogus window_id.- let r4 = req(&mut pipe, &format!(- r#"{{"method":"call","name":"get_window_state","args":{{"pid":{pid},"window_id":99999999}}}}"#));+ let r4 = req(+ &mut pipe,+ &format!(+ r#"{{"method":"call","name":"get_window_state","args":{{"pid":{pid},"window_id":99999999}}}}"#+ ),+ );let e4 = extract_text(&serde_json::from_str(r4.trim()).unwrap());- assert!(e4.contains("No window with window_id"),- "Bogus-window_id wording wrong: {e4:?}");+ assert!(+ e4.contains("No window with window_id"),+ "Bogus-window_id wording wrong: {e4:?}"+ );println!("Bogus-window_id err OK");println!("\n✅ PASS: get_window_state error wording + validation guards verified");diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/hotkey_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/hotkey_parity.rsindex 0d11bea57d..b26fd9a1bc 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/hotkey_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/hotkey_parity.rs@@ -6,7 +6,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe");@@ -17,18 +18,26 @@ fn main() {let mut buf = [0u8; 65536];let deadline = Instant::now() + Duration::from_secs(4);loop {- if Instant::now() > deadline { panic!("timeout"); }+ if Instant::now() > deadline {+ panic!("timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}fn extract_text(v: &serde_json::Value) -> String {- v.pointer("/result/content/0/text").and_then(|t| t.as_str())+ v.pointer("/result/content/0/text")+ .and_then(|t| t.as_str()).or_else(|| v.pointer("/error").and_then(|e| e.as_str()))- .map(|s| s.to_owned()).unwrap_or_default()+ .map(|s| s.to_owned())+ .unwrap_or_default()}// 1. Missing pid — daemon's schema validator catches this before the@@ -37,36 +46,62 @@ fn main() {let r1 = req(&mut pipe, r#"{"method":"call","name":"hotkey","args":{}}"#);let v1: serde_json::Value = serde_json::from_str(r1.trim()).unwrap();let e1 = extract_text(&v1);- assert!(e1.to_lowercase().contains("pid") && e1.to_lowercase().contains("required"),- "Missing-pid error should mention pid + required, got: {e1:?}");+ assert!(+ e1.to_lowercase().contains("pid") && e1.to_lowercase().contains("required"),+ "Missing-pid error should mention pid + required, got: {e1:?}"+ );println!("Missing-pid err OK: {e1:?}");// 2. Missing keys.- let r2 = req(&mut pipe, r#"{"method":"call","name":"hotkey","args":{"pid":1}}"#);+ let r2 = req(+ &mut pipe,+ r#"{"method":"call","name":"hotkey","args":{"pid":1}}"#,+ );let v2: serde_json::Value = serde_json::from_str(r2.trim()).unwrap();let e2 = extract_text(&v2);- assert!(e2.to_lowercase().contains("keys") && e2.to_lowercase().contains("required"),- "Missing-keys error should mention keys + required, got: {e2:?}");+ assert!(+ e2.to_lowercase().contains("keys") && e2.to_lowercase().contains("required"),+ "Missing-keys error should mention keys + required, got: {e2:?}"+ );println!("Missing-keys err OK: {e2:?}");// 3. Real hotkey against Chrome — ctrl+end (scroll to bottom; harmless).- let lw = req(&mut pipe, r#"{"method":"call","name":"list_windows","args":{}}"#);+ let lw = req(+ &mut pipe,+ r#"{"method":"call","name":"list_windows","args":{}}"#,+ );let lwv: serde_json::Value = serde_json::from_str(lw.trim()).unwrap();- let wins = lwv.pointer("/result/structuredContent/windows").and_then(|w| w.as_array()).unwrap();- let target = wins.iter().find(|w| {- let n = w.pointer("/app_name").and_then(|s| s.as_str()).unwrap_or("").to_lowercase();- n.contains("chrome") || n.contains("notepad")- }).expect("no target");+ let wins = lwv+ .pointer("/result/structuredContent/windows")+ .and_then(|w| w.as_array())+ .unwrap();+ let target = wins+ .iter()+ .find(|w| {+ let n = w+ .pointer("/app_name")+ .and_then(|s| s.as_str())+ .unwrap_or("")+ .to_lowercase();+ n.contains("chrome") || n.contains("notepad")+ })+ .expect("no target");let pid = target.pointer("/pid").and_then(|n| n.as_u64()).unwrap();- let wid = target.pointer("/window_id").and_then(|n| n.as_u64()).unwrap();+ let wid = target+ .pointer("/window_id")+ .and_then(|n| n.as_u64())+ .unwrap();let hk = format!(- r#"{{"method":"call","name":"hotkey","args":{{"pid":{pid},"window_id":{wid},"keys":["ctrl","end"]}}}}"#);+ r#"{{"method":"call","name":"hotkey","args":{{"pid":{pid},"window_id":{wid},"keys":["ctrl","end"]}}}}"#+ );let r3 = req(&mut pipe, &hk);let v3: serde_json::Value = serde_json::from_str(r3.trim()).unwrap();let t3 = extract_text(&v3);println!("Hotkey resp: {t3:?}");- assert!(t3.starts_with("✅ Pressed ctrl+end on pid "),- "Expected Swift `✅ Pressed K1+K2 on pid X.`, got: {t3:?}");+ assert!(+ t3.starts_with("✅ Pressed ctrl+end on pid "),+ "Expected Swift `✅ Pressed K1+K2 on pid X.`, got: {t3:?}"+ );println!("\n✅ PASS: hotkey error wording + text format match Swift");}diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/launch_app_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/launch_app_parity.rsindex 8e5d2f1a38..a7978a249a 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/launch_app_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/launch_app_parity.rs@@ -22,7 +22,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe — start daemon first");@@ -33,19 +34,30 @@ fn main() {let mut buf = [0u8; 65536];let deadline = Instant::now() + Duration::from_secs(4);loop {- if Instant::now() > deadline { panic!("response timeout"); }+ if Instant::now() > deadline {+ panic!("response timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}// 1. Missing target error- let r0 = req(&mut pipe, r#"{"method":"call","name":"launch_app","args":{}}"#);+ let r0 = req(+ &mut pipe,+ r#"{"method":"call","name":"launch_app","args":{}}"#,+ );let v0: serde_json::Value = serde_json::from_str(r0.trim()).expect("parse");- let err0 = v0.pointer("/result/content/0/text").and_then(|t| t.as_str())+ let err0 = v0+ .pointer("/result/content/0/text")+ .and_then(|t| t.as_str()).or_else(|| v0.pointer("/error").and_then(|e| e.as_str())).unwrap_or("");assert!(@@ -55,35 +67,65 @@ fn main() {println!("Missing-target err OK: {err0:?}");// 2. Launch Notepad- let resp = req(&mut pipe, r#"{"method":"call","name":"launch_app","args":{"name":"notepad.exe"}}"#);+ let resp = req(+ &mut pipe,+ r#"{"method":"call","name":"launch_app","args":{"name":"notepad.exe"}}"#,+ );let v: serde_json::Value = serde_json::from_str(resp.trim()).expect("parse");- let text = v.pointer("/result/content/0/text").and_then(|t| t.as_str()).expect("missing text");+ let text = v+ .pointer("/result/content/0/text")+ .and_then(|t| t.as_str())+ .expect("missing text");println!("Launch resp text:\n{text}");let header = text.lines().next().unwrap_or("");assert!(- header.starts_with("✅ Launched ") && header.contains(" (pid ") && header.ends_with("in background."),+ header.starts_with("✅ Launched ")+ && header.contains(" (pid ")+ && header.ends_with("in background."),"Header {header:?} doesn't match Swift format `✅ Launched <name> (pid X) in background.`");- let pid = v.pointer("/result/structuredContent/pid").and_then(|n| n.as_u64()).expect("pid");- let name = v.pointer("/result/structuredContent/name").and_then(|s| s.as_str()).expect("name");- let running = v.pointer("/result/structuredContent/running").and_then(|b| b.as_bool()).expect("running");- let active = v.pointer("/result/structuredContent/active").and_then(|b| b.as_bool()).expect("active");- let windows = v.pointer("/result/structuredContent/windows").and_then(|w| w.as_array()).expect("windows");- let bundle_id = v.pointer("/result/structuredContent/bundle_id").expect("bundle_id key");+ let pid = v+ .pointer("/result/structuredContent/pid")+ .and_then(|n| n.as_u64())+ .expect("pid");+ let name = v+ .pointer("/result/structuredContent/name")+ .and_then(|s| s.as_str())+ .expect("name");+ let running = v+ .pointer("/result/structuredContent/running")+ .and_then(|b| b.as_bool())+ .expect("running");+ let active = v+ .pointer("/result/structuredContent/active")+ .and_then(|b| b.as_bool())+ .expect("active");+ let windows = v+ .pointer("/result/structuredContent/windows")+ .and_then(|w| w.as_array())+ .expect("windows");+ let bundle_id = v+ .pointer("/result/structuredContent/bundle_id")+ .expect("bundle_id key");println!("Structured: pid={pid} name={name:?} running={running} active={active} windows={} bundle_id={bundle_id}", windows.len());- assert!(pid > 0, "pid must be captured (ShellExecuteEx pid or packaged-app pid)");+ assert!(+ pid > 0,+ "pid must be captured (ShellExecuteEx pid or packaged-app pid)"+ );assert!(running, "running must be true");- assert!(!active, "active must be false (background launch — Swift's invariant)");+ assert!(+ !active,+ "active must be false (background launch — Swift's invariant)"+ );// bundle_id is either null (plain Win32 launch — Win10 / unpackaged// Notepad) or an AUMID string (Win11 — `notepad` resolved through// shell:AppsFolder to the packaged Notepad). Both are correct.assert!(- bundle_id.is_null()- || bundle_id.as_str().map(|s| s.contains('!')).unwrap_or(false),+ bundle_id.is_null() || bundle_id.as_str().map(|s| s.contains('!')).unwrap_or(false),"bundle_id must be null OR an AUMID (`pkg!app`); got {bundle_id}");@@ -92,7 +134,8 @@ fn main() {.args(["/PID", &pid.to_string(), "/F"]).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null())- .status().ok();+ .status()+ .ok();// 3. AUMID path (Win11 only — skipped silently on Win10 since the// AUMID won't be installed there).@@ -115,7 +158,8 @@ fn main() {.args(["/PID", &p.to_string(), "/F"]).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null())- .status().ok();+ .status()+ .ok();}match bundle_id_aumid {@@ -142,7 +186,11 @@ fn main() {let err_text = v_aumid.pointer("/error").and_then(|e| e.as_str())- .or_else(|| v_aumid.pointer("/result/content/0/text").and_then(|t| t.as_str()))+ .or_else(|| {+ v_aumid+ .pointer("/result/content/0/text")+ .and_then(|t| t.as_str())+ }).unwrap_or("");let err_lower = err_text.to_lowercase();// Windows surfaces "AUMID not registered for current user"@@ -160,8 +208,8 @@ fn main() {// sessions (services / SSH) fails fast with a descriptive// error rather than hanging. This is correct behavior, not a// regression — accept it the same way we accept "not installed".- let looks_like_session_0 = err_lower.contains("interactive session")- || err_lower.contains("session 0");+ let looks_like_session_0 =+ err_lower.contains("interactive session") || err_lower.contains("session 0");assert!(looks_like_not_installed || looks_like_session_0,"AUMID launch of {aumid:?} failed with an unexpected error \diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/list_apps_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/list_apps_parity.rsindex b473d89820..c2d62459ba 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/list_apps_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/list_apps_parity.rs@@ -22,7 +22,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe — start daemon first");@@ -33,19 +34,30 @@ fn main() {let mut buf = [0u8; 65536];let deadline = Instant::now() + Duration::from_secs(8);loop {- if Instant::now() > deadline { panic!("response timeout"); }+ if Instant::now() > deadline {+ panic!("response timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}- let resp = req(&mut pipe, r#"{"method":"call","name":"list_apps","args":{}}"#);+ let resp = req(+ &mut pipe,+ r#"{"method":"call","name":"list_apps","args":{}}"#,+ );let v: serde_json::Value = serde_json::from_str(resp.trim()).expect("parse JSON");- let text = v.pointer("/result/content/0/text").and_then(|t| t.as_str())+ let text = v+ .pointer("/result/content/0/text")+ .and_then(|t| t.as_str()).expect("missing text");let first_line = text.lines().next().unwrap_or("");println!("Header: {first_line:?}");@@ -55,34 +67,62 @@ fn main() {);// structuredContent — #1545 contract: array of mixed running + installed.- let apps = v.pointer("/result/structuredContent/apps").and_then(|a| a.as_array())+ let apps = v+ .pointer("/result/structuredContent/apps")+ .and_then(|a| a.as_array()).expect("structuredContent.apps is not an array");- assert!(!apps.is_empty(), "Expected at least one app (running or installed)");+ assert!(+ !apps.is_empty(),+ "Expected at least one app (running or installed)"+ );println!("Apps: {} entries", apps.len());let mut any_active = false;let mut running_count = 0;let mut installed_count = 0;for (i, app) in apps.iter().enumerate() {- let pid = app.pointer("/pid").and_then(|n| n.as_u64()).expect("pid");- let name = app.pointer("/name").and_then(|s| s.as_str()).expect("name");- let running = app.pointer("/running").and_then(|b| b.as_bool()).expect("running");- let active = app.pointer("/active").and_then(|b| b.as_bool()).expect("active");+ let pid = app.pointer("/pid").and_then(|n| n.as_u64()).expect("pid");+ let name = app.pointer("/name").and_then(|s| s.as_str()).expect("name");+ let running = app+ .pointer("/running")+ .and_then(|b| b.as_bool())+ .expect("running");+ let active = app+ .pointer("/active")+ .and_then(|b| b.as_bool())+ .expect("active");// bundle_id present (null on Windows for non-UWP, optional string on macOS).let _ = app.pointer("/bundle_id").expect("bundle_id key missing");// #1545 fields: kind, launch_path, last_used, windows.- let _ = app.pointer("/kind").expect("kind key missing (added by #1545)");- let _ = app.pointer("/launch_path").expect("launch_path key missing (added by #1545)");- let _ = app.pointer("/last_used").expect("last_used key missing (added by #1545)");- let _ = app.pointer("/windows").expect("windows key missing (added by #1545)");+ let _ = app+ .pointer("/kind")+ .expect("kind key missing (added by #1545)");+ let _ = app+ .pointer("/launch_path")+ .expect("launch_path key missing (added by #1545)");+ let _ = app+ .pointer("/last_used")+ .expect("last_used key missing (added by #1545)");+ let _ = app+ .pointer("/windows")+ .expect("windows key missing (added by #1545)");if i < 5 {println!(" [{i}] pid={pid} name={name:?} running={running} active={active}");}- if running { running_count += 1; } else { installed_count += 1; }+ if running {+ running_count += 1;+ } else {+ installed_count += 1;+ }// Running entries must have pid > 0; installed-not-running must have pid == 0.- if running { assert!(pid > 0, "running entry must have pid>0: {name:?}"); }- else { assert_eq!(pid, 0, "installed-not-running must have pid=0: {name:?}"); }- if active { any_active = true; }+ if running {+ assert!(pid > 0, "running entry must have pid>0: {name:?}");+ } else {+ assert_eq!(pid, 0, "installed-not-running must have pid=0: {name:?}");+ }+ if active {+ any_active = true;+ }}println!("Counts: {running_count} running, {installed_count} installed-not-running");@@ -91,10 +131,7 @@ fn main() {// (services / SSH-launched processes) where GetForegroundWindow returns// null and no app is reported as active — that's correct behavior, not// a regression.- let in_session_0 = matches!(- platform_windows::diagnostics::current_session_id(),- Some(0),- );+ let in_session_0 = matches!(platform_windows::diagnostics::current_session_id(), Some(0),);if in_session_0 {println!("(Session 0: skipping active-app assertion — no interactive desktop attached)");} else if running_count > 0 {diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/list_tools_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/list_tools_parity.rsindex 045a89203a..15f7467297 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/list_tools_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/list_tools_parity.rs@@ -10,8 +10,10 @@ use std::process::Command;#[cfg(target_os = "windows")]fn main() {let exe = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))- .parent().unwrap()- .parent().unwrap()+ .parent()+ .unwrap()+ .parent()+ .unwrap().join("target/debug/cua-driver.exe");let out = Command::new(&exe).arg("list-tools")@@ -26,27 +28,53 @@ fn main() {let names: Vec<&str> = lines.iter().map(|l| l.split(':').next().unwrap()).collect();let mut sorted = names.clone();sorted.sort();- assert_eq!(names, sorted, "tools are not sorted alphabetically (Swift parity)");+ assert_eq!(+ names, sorted,+ "tools are not sorted alphabetically (Swift parity)"+ );// All core tools are present.let expected = [- "click", "double_click", "right_click", "type_text", "press_key", "hotkey",- "scroll", "screenshot", "list_apps", "list_windows", "get_cursor_position",- "get_screen_size", "launch_app", "move_cursor", "set_agent_cursor_enabled",- "set_agent_cursor_motion", "get_agent_cursor_state", "set_value",- "get_config", "set_config", "check_permissions", "get_recording_state",- "start_recording", "stop_recording",+ "click",+ "double_click",+ "right_click",+ "type_text",+ "press_key",+ "hotkey",+ "scroll",+ "screenshot",+ "list_apps",+ "list_windows",+ "get_cursor_position",+ "get_screen_size",+ "launch_app",+ "move_cursor",+ "set_agent_cursor_enabled",+ "set_agent_cursor_motion",+ "get_agent_cursor_state",+ "set_value",+ "get_config",+ "set_config",+ "check_permissions",+ "get_recording_state",+ "start_recording",+ "stop_recording",];for tool in expected {- assert!(names.iter().any(|n| *n == tool), "missing tool `{tool}` in list-tools output");+ assert!(+ names.iter().any(|n| *n == tool),+ "missing tool `{tool}` in list-tools output"+ );}// Each non-empty line should have `name: <summary>` shape OR just `name`.for line in &lines {if line.contains(':') {let after = line.split_once(':').unwrap().1;- assert!(after.trim_start().chars().next().is_some(),- "empty description after colon in line: {line:?}");+ assert!(+ after.trim_start().chars().next().is_some(),+ "empty description after colon in line: {line:?}"+ );}}diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/list_windows_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/list_windows_parity.rsindex 8500ac835b..7dda9e6788 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/list_windows_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/list_windows_parity.rs@@ -6,7 +6,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe — start daemon first");@@ -17,18 +18,30 @@ fn main() {let mut buf = [0u8; 65536];let deadline = Instant::now() + Duration::from_secs(4);loop {- if Instant::now() > deadline { panic!("response timeout"); }+ if Instant::now() > deadline {+ panic!("response timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}- let resp = req(&mut pipe, r#"{"method":"call","name":"list_windows","args":{}}"#);+ let resp = req(+ &mut pipe,+ r#"{"method":"call","name":"list_windows","args":{}}"#,+ );let v: serde_json::Value = serde_json::from_str(resp.trim()).expect("parse JSON");- let text = v.pointer("/result/content/0/text").and_then(|t| t.as_str()).expect("missing text");+ let text = v+ .pointer("/result/content/0/text")+ .and_then(|t| t.as_str())+ .expect("missing text");let header = text.lines().next().unwrap_or("");println!("Header: {header:?}");assert!(@@ -40,7 +53,9 @@ fn main() {"Windows should append the SPI-unavailable note (matches Swift's else branch)");- let wins = v.pointer("/result/structuredContent/windows").and_then(|w| w.as_array())+ let wins = v+ .pointer("/result/structuredContent/windows")+ .and_then(|w| w.as_array()).expect("structuredContent.windows is not an array");// Window enumeration requires an attached interactive desktop. In@@ -48,42 +63,71 @@ fn main() {// scoped to the caller's window station which has no on-screen// windows, so an empty array here is correct behavior — not a// regression. Skip the "non-empty" assertion in that case.- let in_session_0 = matches!(- platform_windows::diagnostics::current_session_id(),- Some(0),- );+ let in_session_0 = matches!(platform_windows::diagnostics::current_session_id(), Some(0),);if in_session_0 {- println!("(Session 0: skipping non-empty-windows assertion — no interactive desktop attached)");+ println!(+ "(Session 0: skipping non-empty-windows assertion — no interactive desktop attached)"+ );} else {assert!(!wins.is_empty(), "expected at least one visible window");}for w in wins {- for key in &["window_id","pid","app_name","title","bounds","layer","z_index","is_on_screen"] {- assert!(w.pointer(&format!("/{key}")).is_some(),- "window record missing field {key}: {w}");+ for key in &[+ "window_id",+ "pid",+ "app_name",+ "title",+ "bounds",+ "layer",+ "z_index",+ "is_on_screen",+ ] {+ assert!(+ w.pointer(&format!("/{key}")).is_some(),+ "window record missing field {key}: {w}"+ );}// bounds shape- for k in &["x","y","width","height"] {- assert!(w.pointer(&format!("/bounds/{k}")).is_some(), "bounds missing {k}");+ for k in &["x", "y", "width", "height"] {+ assert!(+ w.pointer(&format!("/bounds/{k}")).is_some(),+ "bounds missing {k}"+ );}// Swift omits these on Windows (SPI unavailable); explicitly assert// they are NOT present.- assert!(w.get("on_current_space").is_none(), "on_current_space should be omitted on Windows");- assert!(w.get("space_ids").is_none(), "space_ids should be omitted on Windows");+ assert!(+ w.get("on_current_space").is_none(),+ "on_current_space should be omitted on Windows"+ );+ assert!(+ w.get("space_ids").is_none(),+ "space_ids should be omitted on Windows"+ );}let csi = v.pointer("/result/structuredContent/current_space_id");- assert!(csi.is_some() && csi.unwrap().is_null(),- "current_space_id should be null on Windows; got {:?}", csi);+ assert!(+ csi.is_some() && csi.unwrap().is_null(),+ "current_space_id should be null on Windows; got {:?}",+ csi+ );// Pid-filter warning path.- let resp2 = req(&mut pipe,- r#"{"method":"call","name":"list_windows","args":{"pid":4294967295}}"#);+ let resp2 = req(+ &mut pipe,+ r#"{"method":"call","name":"list_windows","args":{"pid":4294967295}}"#,+ );let v2: serde_json::Value = serde_json::from_str(resp2.trim()).expect("parse JSON");- let t2 = v2.pointer("/result/content/0/text").and_then(|t| t.as_str()).unwrap_or("");- assert!(t2.starts_with("⚠️ No windows found for pid"),- "Expected ⚠️-prefixed warning for bogus pid, got: {t2:?}");+ let t2 = v2+ .pointer("/result/content/0/text")+ .and_then(|t| t.as_str())+ .unwrap_or("");+ assert!(+ t2.starts_with("⚠️ No windows found for pid"),+ "Expected ⚠️-prefixed warning for bogus pid, got: {t2:?}"+ );println!("\n✅ PASS: text header, structuredContent fields + bounds shape, and pid-warning path all match Swift");}diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/mcp_config_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/mcp_config_parity.rsindex 4bee36f68c..249ba18d2d 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/mcp_config_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/mcp_config_parity.rs@@ -5,20 +5,48 @@ use std::process::Command;#[cfg(target_os = "windows")]fn main() {let exe = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))- .parent().unwrap()- .parent().unwrap()+ .parent()+ .unwrap()+ .parent()+ .unwrap().join("target/debug/cua-driver.exe");let cases = [// Each (args, expected substrings)- (vec![], vec!["\"mcpServers\"", "\"cua-driver\"", "\"command\":", "\"args\": [\"mcp\"]"]),- (vec!["--client", "claude"], vec!["claude mcp add --transport stdio cua-driver"]),- (vec!["--client", "codex"], vec!["codex mcp add cua-driver"]),- (vec!["--client", "cursor"], vec!["\"type\": \"stdio\"", "\"mcpServers\""]),- (vec!["--client", "openclaw"], vec!["openclaw mcp set cua-driver"]),- (vec!["--client", "opencode"], vec!["opencode.ai/config.json", "\"type\": \"local\""]),- (vec!["--client", "hermes"], vec!["mcp_servers:", "cua-driver:"]),- (vec!["--client", "pi"], vec!["does not support MCP natively"]),+ (+ vec![],+ vec![+ "\"mcpServers\"",+ "\"cua-driver\"",+ "\"command\":",+ "\"args\": [\"mcp\"]",+ ],+ ),+ (+ vec!["--client", "claude"],+ vec!["claude mcp add --transport stdio cua-driver"],+ ),+ (vec!["--client", "codex"], vec!["codex mcp add cua-driver"]),+ (+ vec!["--client", "cursor"],+ vec!["\"type\": \"stdio\"", "\"mcpServers\""],+ ),+ (+ vec!["--client", "openclaw"],+ vec!["openclaw mcp set cua-driver"],+ ),+ (+ vec!["--client", "opencode"],+ vec!["opencode.ai/config.json", "\"type\": \"local\""],+ ),+ (+ vec!["--client", "hermes"],+ vec!["mcp_servers:", "cua-driver:"],+ ),+ (+ vec!["--client", "pi"],+ vec!["does not support MCP natively"],+ ),];for (args, needles) in cases {@@ -28,18 +56,25 @@ fn main() {assert!(out.status.success(), "mcp-config {args:?} failed: {out:?}");let stdout = String::from_utf8_lossy(&out.stdout);for needle in &needles {- assert!(stdout.contains(needle),- "mcp-config {args:?} output missing {needle:?}\n--- stdout ---\n{stdout}");+ assert!(+ stdout.contains(needle),+ "mcp-config {args:?} output missing {needle:?}\n--- stdout ---\n{stdout}"+ );}println!("mcp-config {args:?} OK");}// Unknown client → exit 2, stderr names valid clients.- let out = Command::new(&exe).args(["mcp-config", "--client", "bogus"]).output().expect("run");+ let out = Command::new(&exe)+ .args(["mcp-config", "--client", "bogus"])+ .output()+ .expect("run");assert_eq!(out.status.code(), Some(2), "unknown client should exit 2");let stderr = String::from_utf8_lossy(&out.stderr);- assert!(stderr.contains("Unknown client 'bogus'") && stderr.contains("claude"),- "unknown-client stderr wrong: {stderr:?}");+ assert!(+ stderr.contains("Unknown client 'bogus'") && stderr.contains("claude"),+ "unknown-client stderr wrong: {stderr:?}"+ );println!("unknown-client err OK");println!("\n✅ PASS: mcp-config 8 client paths + unknown-client error verified");diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/overlay_dump.rs b/libs/cua-driver/rust/crates/platform-windows/examples/overlay_dump.rsindex 166d6bb961..33bf6dd735 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/overlay_dump.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/overlay_dump.rs@@ -5,16 +5,17 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {+ use std::ffi::OsStr;+ use std::os::windows::ffi::OsStrExt;use windows::Win32::Foundation::HWND;use windows::Win32::Graphics::Gdi::*;use windows::Win32::Storage::Xps::{PrintWindow, PRINT_WINDOW_FLAGS};use windows::Win32::UI::WindowsAndMessaging::*;- use std::ffi::OsStr;- use std::os::windows::ffi::OsStrExt;// Send the daemon a move command first.let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe");fn req(p: &mut std::fs::File, json: &str) {@@ -24,31 +25,57 @@ fn main() {let deadline = Instant::now() + Duration::from_secs(2);let mut out = Vec::new();loop {- if Instant::now() > deadline { break; }+ if Instant::now() > deadline {+ break;+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}}- req(&mut pipe, r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}"#);- req(&mut pipe, r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"set_agent_cursor_enabled","arguments":{"enabled":true}}}"#);- req(&mut pipe, r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"move_cursor","arguments":{"x":700.0,"y":500.0}}}"#);+ req(+ &mut pipe,+ r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}"#,+ );+ req(+ &mut pipe,+ r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"set_agent_cursor_enabled","arguments":{"enabled":true}}}"#,+ );+ req(+ &mut pipe,+ r#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"move_cursor","arguments":{"x":700.0,"y":500.0}}}"#,+ );std::thread::sleep(Duration::from_millis(1500));// Find overlay HWND (class name matches what overlay.rs registers).let class_name: Vec<u16> = OsStr::new("Cua.AgentCursorOverlay\0")- .encode_wide().collect();- let hwnd = unsafe { FindWindowW(- windows::core::PCWSTR(class_name.as_ptr()),- windows::core::PCWSTR::null(),- ) };- let hwnd = match hwnd { Ok(h) => h, Err(_) => { eprintln!("no overlay window"); std::process::exit(1); } };+ .encode_wide()+ .collect();+ let hwnd = unsafe {+ FindWindowW(+ windows::core::PCWSTR(class_name.as_ptr()),+ windows::core::PCWSTR::null(),+ )+ };+ let hwnd = match hwnd {+ Ok(h) => h,+ Err(_) => {+ eprintln!("no overlay window");+ std::process::exit(1);+ }+ };println!("overlay HWND: 0x{:X}", hwnd.0 as isize);let mut rect = windows::Win32::Foundation::RECT::default();- unsafe { let _ = GetWindowRect(hwnd, &mut rect); }+ unsafe {+ let _ = GetWindowRect(hwnd, &mut rect);+ }let w = rect.right - rect.left;let h = rect.bottom - rect.top;println!("rect: {},{} {}x{}", rect.left, rect.top, w, h);@@ -66,7 +93,10 @@ fn main() {let mut bmi = BITMAPINFO {bmiHeader: BITMAPINFOHEADER {biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,- biWidth: w, biHeight: -h, biPlanes: 1, biBitCount: 32,+ biWidth: w,+ biHeight: -h,+ biPlanes: 1,+ biBitCount: 32,biCompression: BI_RGB.0,biSizeImage: (w * h * 4) as u32,..Default::default()@@ -74,27 +104,47 @@ fn main() {bmiColors: [RGBQUAD::default(); 1],};let mut pixels = vec![0u8; (w * h * 4) as usize];- let got = GetDIBits(mem_dc, bitmap, 0, h as u32, Some(pixels.as_mut_ptr() as *mut _), &mut bmi, DIB_RGB_COLORS);+ let got = GetDIBits(+ mem_dc,+ bitmap,+ 0,+ h as u32,+ Some(pixels.as_mut_ptr() as *mut _),+ &mut bmi,+ DIB_RGB_COLORS,+ );println!("GetDIBits scanlines: {}", got);// Find non-zero pixels.let mut nonzero = 0u64;- let mut sum_x = 0i64; let mut sum_y = 0i64;+ let mut sum_x = 0i64;+ let mut sum_y = 0i64;let mut max_a = 0u8;for y in 0..h as usize {for x in 0..w as usize {let i = (y * w as usize + x) * 4;- let b = pixels[i]; let g = pixels[i+1]; let r = pixels[i+2]; let a = pixels[i+3];+ let b = pixels[i];+ let g = pixels[i + 1];+ let r = pixels[i + 2];+ let a = pixels[i + 3];max_a = max_a.max(a);if r as u32 + g as u32 + b as u32 > 30 {nonzero += 1;- sum_x += x as i64; sum_y += y as i64;+ sum_x += x as i64;+ sum_y += y as i64;}}}- println!("non-zero RGB pixels in overlay surface: {} max_alpha={}", nonzero, max_a);+ println!(+ "non-zero RGB pixels in overlay surface: {} max_alpha={}",+ nonzero, max_a+ );if nonzero > 0 {- println!("centroid: ({}, {})", sum_x / nonzero as i64, sum_y / nonzero as i64);+ println!(+ "centroid: ({}, {})",+ sum_x / nonzero as i64,+ sum_y / nonzero as i64+ );}SelectObject(mem_dc, old);diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/press_key_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/press_key_parity.rsindex 0d87fbace5..f29033f29f 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/press_key_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/press_key_parity.rs@@ -6,7 +6,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe");@@ -17,57 +18,93 @@ fn main() {let mut buf = [0u8; 65536];let deadline = Instant::now() + Duration::from_secs(4);loop {- if Instant::now() > deadline { panic!("timeout"); }+ if Instant::now() > deadline {+ panic!("timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}fn extract_text(v: &serde_json::Value) -> String {- v.pointer("/result/content/0/text").and_then(|t| t.as_str())+ v.pointer("/result/content/0/text")+ .and_then(|t| t.as_str()).or_else(|| v.pointer("/error").and_then(|e| e.as_str())).map(|s| s.to_owned()).unwrap_or_else(|| format!("(no text: {v})"))}// 1. Missing key error.- let r1 = req(&mut pipe, r#"{"method":"call","name":"press_key","args":{"pid":1}}"#);+ let r1 = req(+ &mut pipe,+ r#"{"method":"call","name":"press_key","args":{"pid":1}}"#,+ );let v1: serde_json::Value = serde_json::from_str(r1.trim()).unwrap();let err1 = extract_text(&v1);- assert!(err1.contains("Missing required string field key"),- "Expected Swift-style key error, got: {err1:?}");+ assert!(+ err1.contains("Missing required string field key"),+ "Expected Swift-style key error, got: {err1:?}"+ );println!("Missing-key err OK: {err1:?}");// 2. element_index without window_id should error per Swift.- let r2 = req(&mut pipe, r#"{"method":"call","name":"press_key","args":{"pid":1,"key":"a","element_index":0}}"#);+ let r2 = req(+ &mut pipe,+ r#"{"method":"call","name":"press_key","args":{"pid":1,"key":"a","element_index":0}}"#,+ );let v2: serde_json::Value = serde_json::from_str(r2.trim()).unwrap();let err2 = extract_text(&v2);- assert!(err2.contains("window_id is required when element_index is used"),- "Expected Swift-style element-without-window error, got: {err2:?}");+ assert!(+ err2.contains("window_id is required when element_index is used"),+ "Expected Swift-style element-without-window error, got: {err2:?}"+ );println!("Element-without-window err OK");// 3. Press a key against a real window.- let lw = req(&mut pipe, r#"{"method":"call","name":"list_windows","args":{}}"#);+ let lw = req(+ &mut pipe,+ r#"{"method":"call","name":"list_windows","args":{}}"#,+ );let lwv: serde_json::Value = serde_json::from_str(lw.trim()).unwrap();- let wins = lwv.pointer("/result/structuredContent/windows").and_then(|w| w.as_array()).unwrap();+ let wins = lwv+ .pointer("/result/structuredContent/windows")+ .and_then(|w| w.as_array())+ .unwrap();let preferred = ["chrome.exe", "notepad.exe"];- let target = wins.iter().find(|w| {- let name = w.pointer("/app_name").and_then(|s| s.as_str()).unwrap_or("").to_lowercase();- preferred.iter().any(|p| name.contains(p))- }).expect("no chrome/notepad");+ let target = wins+ .iter()+ .find(|w| {+ let name = w+ .pointer("/app_name")+ .and_then(|s| s.as_str())+ .unwrap_or("")+ .to_lowercase();+ preferred.iter().any(|p| name.contains(p))+ })+ .expect("no chrome/notepad");let pid = target.pointer("/pid").and_then(|n| n.as_u64()).unwrap();- let wid = target.pointer("/window_id").and_then(|n| n.as_u64()).unwrap();+ let wid = target+ .pointer("/window_id")+ .and_then(|n| n.as_u64())+ .unwrap();// Press End key (safe — scrolls to bottom of page; doesn't modify content).let press_req = format!(- r#"{{"method":"call","name":"press_key","args":{{"pid":{pid},"window_id":{wid},"key":"end"}}}}"#);+ r#"{{"method":"call","name":"press_key","args":{{"pid":{pid},"window_id":{wid},"key":"end"}}}}"#+ );let r3 = req(&mut pipe, &press_req);let v3: serde_json::Value = serde_json::from_str(r3.trim()).unwrap();let text3 = extract_text(&v3);println!("Press resp: {text3:?}");- assert!(text3.starts_with("✅ Pressed end on pid "),- "Expected Swift format `✅ Pressed KEY on pid X.`, got: {text3:?}");+ assert!(+ text3.starts_with("✅ Pressed end on pid "),+ "Expected Swift format `✅ Pressed KEY on pid X.`, got: {text3:?}"+ );println!("\n✅ PASS: press_key error wording + text format match Swift");}diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/recording_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/recording_parity.rsindex 88f4394eaa..7286340b9b 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/recording_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/recording_parity.rs@@ -11,7 +11,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe");@@ -22,57 +23,96 @@ fn main() {let mut buf: Vec<u8> = vec![0u8; 64 * 1024];let deadline = Instant::now() + Duration::from_secs(4);loop {- if Instant::now() > deadline { panic!("timeout"); }+ if Instant::now() > deadline {+ panic!("timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}fn extract_text(v: &serde_json::Value) -> String {- v.pointer("/result/content/0/text").and_then(|t| t.as_str())+ v.pointer("/result/content/0/text")+ .and_then(|t| t.as_str()).or_else(|| v.pointer("/error").and_then(|e| e.as_str()))- .map(|s| s.to_owned()).unwrap_or_default()+ .map(|s| s.to_owned())+ .unwrap_or_default()}// 1. Stop to start clean (idempotent).- let _ = req(&mut pipe, r#"{"method":"call","name":"stop_recording","args":{}}"#);+ let _ = req(+ &mut pipe,+ r#"{"method":"call","name":"stop_recording","args":{}}"#,+ );// 2. get_recording_state — disabled.- let r1 = req(&mut pipe, r#"{"method":"call","name":"get_recording_state","args":{}}"#);+ let r1 = req(+ &mut pipe,+ r#"{"method":"call","name":"get_recording_state","args":{}}"#,+ );let t1 = extract_text(&serde_json::from_str(r1.trim()).unwrap());assert_eq!(t1, "✅ recording: disabled", "Disabled text wrong: {t1:?}");println!("get_recording_state disabled OK");// 3. start_recording without output_dir → must error.- let r2 = req(&mut pipe, r#"{"method":"call","name":"start_recording","args":{}}"#);+ let r2 = req(+ &mut pipe,+ r#"{"method":"call","name":"start_recording","args":{}}"#,+ );let e2 = extract_text(&serde_json::from_str(r2.trim()).unwrap());- assert!(e2.to_lowercase().contains("output_dir") && e2.to_lowercase().contains("required"),- "Missing-output_dir wording wrong: {e2:?}");+ assert!(+ e2.to_lowercase().contains("output_dir") && e2.to_lowercase().contains("required"),+ "Missing-output_dir wording wrong: {e2:?}"+ );println!("Missing-output_dir err OK");// 4. Start with output_dir, opt out of video (no ffmpeg dependency).- let dir = std::env::temp_dir().join("cua-rec-parity").to_string_lossy().into_owned()+ let dir = std::env::temp_dir()+ .join("cua-rec-parity")+ .to_string_lossy()+ .into_owned().replace('\\', "\\\\");- let r4 = req(&mut pipe, &format!(- r#"{{"method":"call","name":"start_recording","args":{{"output_dir":"{dir}","record_video":false}}}}"#));+ let r4 = req(+ &mut pipe,+ &format!(+ r#"{{"method":"call","name":"start_recording","args":{{"output_dir":"{dir}","record_video":false}}}}"#+ ),+ );let t4 = extract_text(&serde_json::from_str(r4.trim()).unwrap());println!("Start resp: {t4:?}");- assert!(t4.starts_with("✅ Recording started -> "),- "Start text wrong: {t4:?}");+ assert!(+ t4.starts_with("✅ Recording started -> "),+ "Start text wrong: {t4:?}"+ );// 5. get_recording_state — enabled.- let r5 = req(&mut pipe, r#"{"method":"call","name":"get_recording_state","args":{}}"#);+ let r5 = req(+ &mut pipe,+ r#"{"method":"call","name":"get_recording_state","args":{}}"#,+ );let t5 = extract_text(&serde_json::from_str(r5.trim()).unwrap());println!("State enabled: {t5:?}");- assert!(t5.starts_with("✅ recording: enabled output_dir=") && t5.contains("next_turn="),- "Enabled state text wrong: {t5:?}");+ assert!(+ t5.starts_with("✅ recording: enabled output_dir=") && t5.contains("next_turn="),+ "Enabled state text wrong: {t5:?}"+ );// 6. Stop.- let r6 = req(&mut pipe, r#"{"method":"call","name":"stop_recording","args":{}}"#);+ let r6 = req(+ &mut pipe,+ r#"{"method":"call","name":"stop_recording","args":{}}"#,+ );let t6 = extract_text(&serde_json::from_str(r6.trim()).unwrap());- assert!(t6.starts_with("✅ Recording stopped."), "Stop text wrong: {t6:?}");+ assert!(+ t6.starts_with("✅ Recording stopped."),+ "Stop text wrong: {t6:?}"+ );println!("\n✅ PASS: start_recording + stop_recording + get_recording_state");}diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/replay_trajectory_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/replay_trajectory_parity.rsindex 8c09fa6ea4..3dfe48b656 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/replay_trajectory_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/replay_trajectory_parity.rs@@ -6,7 +6,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe");@@ -17,32 +18,50 @@ fn main() {let mut buf: Vec<u8> = vec![0u8; 64 * 1024];let deadline = Instant::now() + Duration::from_secs(4);loop {- if Instant::now() > deadline { panic!("timeout"); }+ if Instant::now() > deadline {+ panic!("timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}fn extract_text(v: &serde_json::Value) -> String {- v.pointer("/result/content/0/text").and_then(|t| t.as_str())+ v.pointer("/result/content/0/text")+ .and_then(|t| t.as_str()).or_else(|| v.pointer("/error").and_then(|e| e.as_str()))- .map(|s| s.to_owned()).unwrap_or_default()+ .map(|s| s.to_owned())+ .unwrap_or_default()}// 1. Empty `dir` string (schema-layer required, but should also be checked at tool layer).- let r1 = req(&mut pipe, r#"{"method":"call","name":"replay_trajectory","args":{"dir":""}}"#);+ let r1 = req(+ &mut pipe,+ r#"{"method":"call","name":"replay_trajectory","args":{"dir":""}}"#,+ );let e1 = extract_text(&serde_json::from_str(r1.trim()).unwrap());- assert!(e1.contains("`dir`") && e1.to_lowercase().contains("required"),- "Empty-dir wording wrong: {e1:?}");+ assert!(+ e1.contains("`dir`") && e1.to_lowercase().contains("required"),+ "Empty-dir wording wrong: {e1:?}"+ );println!("Empty-dir err OK");// 2. Nonexistent directory.- let r2 = req(&mut pipe, r#"{"method":"call","name":"replay_trajectory","args":{"dir":"C:\\does\\not\\exist"}}"#);+ let r2 = req(+ &mut pipe,+ r#"{"method":"call","name":"replay_trajectory","args":{"dir":"C:\\does\\not\\exist"}}"#,+ );let e2 = extract_text(&serde_json::from_str(r2.trim()).unwrap());- assert!(e2.contains("Trajectory directory does not exist"),- "Nonexistent-dir wording wrong: {e2:?}");+ assert!(+ e2.contains("Trajectory directory does not exist"),+ "Nonexistent-dir wording wrong: {e2:?}"+ );println!("Nonexistent-dir err OK");println!("\n✅ PASS: replay_trajectory error paths match Swift");diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/right_click_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/right_click_parity.rsindex a2edcb9b4a..ddd8109ba8 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/right_click_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/right_click_parity.rs@@ -6,7 +6,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe");@@ -17,66 +18,113 @@ fn main() {let mut buf = [0u8; 65536];let deadline = Instant::now() + Duration::from_secs(4);loop {- if Instant::now() > deadline { panic!("timeout"); }+ if Instant::now() > deadline {+ panic!("timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}fn extract_text(v: &serde_json::Value) -> String {- v.pointer("/result/content/0/text").and_then(|t| t.as_str())+ v.pointer("/result/content/0/text")+ .and_then(|t| t.as_str()).or_else(|| v.pointer("/error").and_then(|e| e.as_str()))- .map(|s| s.to_owned()).unwrap_or_default()+ .map(|s| s.to_owned())+ .unwrap_or_default()}- let lw = req(&mut pipe, r#"{"method":"call","name":"list_windows","args":{}}"#);+ let lw = req(+ &mut pipe,+ r#"{"method":"call","name":"list_windows","args":{}}"#,+ );let lwv: serde_json::Value = serde_json::from_str(lw.trim()).unwrap();- let wins = lwv.pointer("/result/structuredContent/windows").and_then(|w| w.as_array()).unwrap();- let target = wins.iter().find(|w| {- let n = w.pointer("/app_name").and_then(|s| s.as_str()).unwrap_or("").to_lowercase();- n.contains("chrome") || n.contains("notepad")- }).expect("no target");+ let wins = lwv+ .pointer("/result/structuredContent/windows")+ .and_then(|w| w.as_array())+ .unwrap();+ let target = wins+ .iter()+ .find(|w| {+ let n = w+ .pointer("/app_name")+ .and_then(|s| s.as_str())+ .unwrap_or("")+ .to_lowercase();+ n.contains("chrome") || n.contains("notepad")+ })+ .expect("no target");let pid = target.pointer("/pid").and_then(|n| n.as_u64()).unwrap();- let wid = target.pointer("/window_id").and_then(|n| n.as_u64()).unwrap();+ let wid = target+ .pointer("/window_id")+ .and_then(|n| n.as_u64())+ .unwrap();// 1. Missing target.- let r1 = req(&mut pipe, &format!(- r#"{{"method":"call","name":"right_click","args":{{"pid":{pid},"window_id":{wid}}}}}"#));+ let r1 = req(+ &mut pipe,+ &format!(+ r#"{{"method":"call","name":"right_click","args":{{"pid":{pid},"window_id":{wid}}}}}"#+ ),+ );let v1: serde_json::Value = serde_json::from_str(r1.trim()).unwrap();- assert!(extract_text(&v1).contains("Provide element_index or (x, y) to address the right-click target"));+ assert!(extract_text(&v1)+ .contains("Provide element_index or (x, y) to address the right-click target"));println!("Missing-target err OK");// 2. Partial xy.- let r2 = req(&mut pipe, &format!(- r#"{{"method":"call","name":"right_click","args":{{"pid":{pid},"window_id":{wid},"x":50}}}}"#));- assert!(extract_text(&serde_json::from_str(r2.trim()).unwrap()).contains("Provide both x and y together"));+ let r2 = req(+ &mut pipe,+ &format!(+ r#"{{"method":"call","name":"right_click","args":{{"pid":{pid},"window_id":{wid},"x":50}}}}"#+ ),+ );+ assert!(extract_text(&serde_json::from_str(r2.trim()).unwrap())+ .contains("Provide both x and y together"));println!("Partial-xy err OK");// 3. Both modes.- let r3 = req(&mut pipe, &format!(- r#"{{"method":"call","name":"right_click","args":{{"pid":{pid},"window_id":{wid},"element_index":0,"x":50,"y":50}}}}"#));- assert!(extract_text(&serde_json::from_str(r3.trim()).unwrap()).contains("Provide either element_index or (x, y), not both"));+ let r3 = req(+ &mut pipe,+ &format!(+ r#"{{"method":"call","name":"right_click","args":{{"pid":{pid},"window_id":{wid},"element_index":0,"x":50,"y":50}}}}"#+ ),+ );+ assert!(extract_text(&serde_json::from_str(r3.trim()).unwrap())+ .contains("Provide either element_index or (x, y), not both"));println!("Both-modes err OK");// 4. element_index without window_id.- let r4 = req(&mut pipe, &format!(- r#"{{"method":"call","name":"right_click","args":{{"pid":{pid},"element_index":0}}}}"#));- assert!(extract_text(&serde_json::from_str(r4.trim()).unwrap()).contains("window_id is required when element_index is used"));+ let r4 = req(+ &mut pipe,+ &format!(+ r#"{{"method":"call","name":"right_click","args":{{"pid":{pid},"element_index":0}}}}"#+ ),+ );+ assert!(extract_text(&serde_json::from_str(r4.trim()).unwrap())+ .contains("window_id is required when element_index is used"));println!("Element-without-window err OK");// 5. Real pixel right-click.let rc = format!(- r#"{{"method":"call","name":"right_click","args":{{"pid":{pid},"window_id":{wid},"x":300,"y":300}}}}"#);+ r#"{{"method":"call","name":"right_click","args":{{"pid":{pid},"window_id":{wid},"x":300,"y":300}}}}"#+ );let r5 = req(&mut pipe, &rc);let v5: serde_json::Value = serde_json::from_str(r5.trim()).unwrap();let t5 = extract_text(&v5);println!("Right-click resp: {t5:?}");- assert!(t5.starts_with("✅ Posted right-click to pid ")- && t5.contains(" at window-pixel (")- && t5.contains(" → screen-point ("),- "Pixel-path text doesn't match Swift format: {t5:?}");+ assert!(+ t5.starts_with("✅ Posted right-click to pid ")+ && t5.contains(" at window-pixel (")+ && t5.contains(" → screen-point ("),+ "Pixel-path text doesn't match Swift format: {t5:?}"+ );println!("\n✅ PASS: right_click validation + pixel-path text match Swift");}diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/screenshot_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/screenshot_parity.rsindex a7b56b99dd..5242707241 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/screenshot_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/screenshot_parity.rs@@ -6,7 +6,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe");@@ -19,55 +20,107 @@ fn main() {let mut buf: Vec<u8> = vec![0u8; 64 * 1024];let deadline = Instant::now() + Duration::from_secs(4);loop {- if Instant::now() > deadline { panic!("timeout"); }+ if Instant::now() > deadline {+ panic!("timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}// Window screenshot: find Chrome.- let lw = req(&mut pipe, r#"{"method":"call","name":"list_windows","args":{}}"#);+ let lw = req(+ &mut pipe,+ r#"{"method":"call","name":"list_windows","args":{}}"#,+ );let lwv: serde_json::Value = serde_json::from_str(lw.trim()).unwrap();- let wins = lwv.pointer("/result/structuredContent/windows").and_then(|w| w.as_array()).unwrap();- let target = wins.iter().find(|w| {- let n = w.pointer("/app_name").and_then(|s| s.as_str()).unwrap_or("").to_lowercase();- n.contains("chrome")- }).expect("no chrome");- let wid = target.pointer("/window_id").and_then(|n| n.as_u64()).unwrap();+ let wins = lwv+ .pointer("/result/structuredContent/windows")+ .and_then(|w| w.as_array())+ .unwrap();+ let target = wins+ .iter()+ .find(|w| {+ let n = w+ .pointer("/app_name")+ .and_then(|s| s.as_str())+ .unwrap_or("")+ .to_lowercase();+ n.contains("chrome")+ })+ .expect("no chrome");+ let wid = target+ .pointer("/window_id")+ .and_then(|n| n.as_u64())+ .unwrap();// 1. Window screenshot.let ss = format!(r#"{{"method":"call","name":"screenshot","args":{{"window_id":{wid}}}}}"#);let r1 = req(&mut pipe, &ss);let v1: serde_json::Value = serde_json::from_str(r1.trim()).unwrap();// Last content entry is text; first should be image.- let content = v1.pointer("/result/content").and_then(|c| c.as_array()).unwrap();- assert!(content.iter().any(|c| c.get("type").and_then(|t| t.as_str()) == Some("image")),- "Response should contain an image content block");- let text = content.iter().find_map(|c| {- if c.get("type").and_then(|t| t.as_str()) == Some("text") {- c.get("text").and_then(|t| t.as_str())- } else { None }- }).unwrap_or("");+ let content = v1+ .pointer("/result/content")+ .and_then(|c| c.as_array())+ .unwrap();+ assert!(+ content+ .iter()+ .any(|c| c.get("type").and_then(|t| t.as_str()) == Some("image")),+ "Response should contain an image content block"+ );+ let text = content+ .iter()+ .find_map(|c| {+ if c.get("type").and_then(|t| t.as_str()) == Some("text") {+ c.get("text").and_then(|t| t.as_str())+ } else {+ None+ }+ })+ .unwrap_or("");println!("Window resp: {text:?}");- assert!(text.starts_with("✅ Window screenshot — ") && text.contains(&format!("[window_id: {wid}]")),- "Window text doesn't match Swift format: {text:?}");+ assert!(+ text.starts_with("✅ Window screenshot — ")+ && text.contains(&format!("[window_id: {wid}]")),+ "Window text doesn't match Swift format: {text:?}"+ );let sc = v1.pointer("/result/structuredContent").unwrap();- assert!(sc.get("width").is_some() && sc.get("height").is_some() && sc.get("format").is_some(),- "structuredContent missing width/height/format");+ assert!(+ sc.get("width").is_some() && sc.get("height").is_some() && sc.get("format").is_some(),+ "structuredContent missing width/height/format"+ );// 2. JPEG format.let ss2 = format!(- r#"{{"method":"call","name":"screenshot","args":{{"window_id":{wid},"format":"jpeg","quality":50}}}}"#);+ r#"{{"method":"call","name":"screenshot","args":{{"window_id":{wid},"format":"jpeg","quality":50}}}}"#+ );let r2 = req(&mut pipe, &ss2);let v2: serde_json::Value = serde_json::from_str(r2.trim()).unwrap();- let c2 = v2.pointer("/result/content").and_then(|c| c.as_array()).unwrap();- let img = c2.iter().find(|c| c.get("type").and_then(|t| t.as_str()) == Some("image")).unwrap();+ let c2 = v2+ .pointer("/result/content")+ .and_then(|c| c.as_array())+ .unwrap();+ let img = c2+ .iter()+ .find(|c| c.get("type").and_then(|t| t.as_str()) == Some("image"))+ .unwrap();let mime = img.get("mimeType").and_then(|m| m.as_str()).unwrap_or("");- assert_eq!(mime, "image/jpeg", "jpeg format should set mimeType image/jpeg, got: {mime:?}");- let fmt = v2.pointer("/result/structuredContent/format").and_then(|f| f.as_str()).unwrap_or("");+ assert_eq!(+ mime, "image/jpeg",+ "jpeg format should set mimeType image/jpeg, got: {mime:?}"+ );+ let fmt = v2+ .pointer("/result/structuredContent/format")+ .and_then(|f| f.as_str())+ .unwrap_or("");assert_eq!(fmt, "jpeg", "structuredContent.format should be jpeg");println!("\n✅ PASS: screenshot text format + image + structuredContent + jpeg path verified");diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/scroll_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/scroll_parity.rsindex 450a4a5400..c5b56d279e 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/scroll_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/scroll_parity.rs@@ -6,7 +6,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe");@@ -17,51 +18,90 @@ fn main() {let mut buf: Vec<u8> = vec![0u8; 64 * 1024];let deadline = Instant::now() + Duration::from_secs(4);loop {- if Instant::now() > deadline { panic!("timeout"); }+ if Instant::now() > deadline {+ panic!("timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}fn extract_text(v: &serde_json::Value) -> String {- v.pointer("/result/content/0/text").and_then(|t| t.as_str())+ v.pointer("/result/content/0/text")+ .and_then(|t| t.as_str()).or_else(|| v.pointer("/error").and_then(|e| e.as_str()))- .map(|s| s.to_owned()).unwrap_or_default()+ .map(|s| s.to_owned())+ .unwrap_or_default()}// Missing direction error.- let r1 = req(&mut pipe, r#"{"method":"call","name":"scroll","args":{"pid":1}}"#);+ let r1 = req(+ &mut pipe,+ r#"{"method":"call","name":"scroll","args":{"pid":1}}"#,+ );let e1 = extract_text(&serde_json::from_str(r1.trim()).unwrap());- assert!(e1.contains("direction") && e1.to_lowercase().contains("required"),- "Missing-direction error should mention direction + required: {e1:?}");+ assert!(+ e1.contains("direction") && e1.to_lowercase().contains("required"),+ "Missing-direction error should mention direction + required: {e1:?}"+ );println!("Missing-direction err OK");// element_index without window_id.- let r2 = req(&mut pipe, r#"{"method":"call","name":"scroll","args":{"pid":1,"direction":"down","element_index":0}}"#);+ let r2 = req(+ &mut pipe,+ r#"{"method":"call","name":"scroll","args":{"pid":1,"direction":"down","element_index":0}}"#,+ );let e2 = extract_text(&serde_json::from_str(r2.trim()).unwrap());- assert!(e2.contains("window_id is required when element_index is used"),- "Element-without-window wording wrong: {e2:?}");+ assert!(+ e2.contains("window_id is required when element_index is used"),+ "Element-without-window wording wrong: {e2:?}"+ );println!("Element-without-window err OK");// Real scroll against Chrome.- let lw = req(&mut pipe, r#"{"method":"call","name":"list_windows","args":{}}"#);+ let lw = req(+ &mut pipe,+ r#"{"method":"call","name":"list_windows","args":{}}"#,+ );let lwv: serde_json::Value = serde_json::from_str(lw.trim()).unwrap();- let wins = lwv.pointer("/result/structuredContent/windows").and_then(|w| w.as_array()).unwrap();- let target = wins.iter().find(|w| {- let n = w.pointer("/app_name").and_then(|s| s.as_str()).unwrap_or("").to_lowercase();- n.contains("chrome") || n.contains("notepad")- }).expect("no target");+ let wins = lwv+ .pointer("/result/structuredContent/windows")+ .and_then(|w| w.as_array())+ .unwrap();+ let target = wins+ .iter()+ .find(|w| {+ let n = w+ .pointer("/app_name")+ .and_then(|s| s.as_str())+ .unwrap_or("")+ .to_lowercase();+ n.contains("chrome") || n.contains("notepad")+ })+ .expect("no target");let pid = target.pointer("/pid").and_then(|n| n.as_u64()).unwrap();- let wid = target.pointer("/window_id").and_then(|n| n.as_u64()).unwrap();+ let wid = target+ .pointer("/window_id")+ .and_then(|n| n.as_u64())+ .unwrap();let sc = format!(- r#"{{"method":"call","name":"scroll","args":{{"pid":{pid},"window_id":{wid},"direction":"down","by":"page","amount":2}}}}"#);+ r#"{{"method":"call","name":"scroll","args":{{"pid":{pid},"window_id":{wid},"direction":"down","by":"page","amount":2}}}}"#+ );let r3 = req(&mut pipe, &sc);let t3 = extract_text(&serde_json::from_str(r3.trim()).unwrap());println!("Scroll resp: {t3:?}");- assert!(t3.starts_with(&format!("✅ Scrolled pid {pid} down via 2× SB_PAGEDOWN message(s)")),- "Scroll text doesn't match Swift-shape format: {t3:?}");+ assert!(+ t3.starts_with(&format!(+ "✅ Scrolled pid {pid} down via 2× SB_PAGEDOWN message(s)"+ )),+ "Scroll text doesn't match Swift-shape format: {t3:?}"+ );println!("\n✅ PASS: scroll validation + Swift-shape text format verified");}diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/set_agent_cursor_style_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/set_agent_cursor_style_parity.rsindex 6f0c1a23f1..698289ab57 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/set_agent_cursor_style_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/set_agent_cursor_style_parity.rs@@ -6,7 +6,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe");@@ -17,37 +18,54 @@ fn main() {let mut buf: Vec<u8> = vec![0u8; 64 * 1024];let deadline = Instant::now() + Duration::from_secs(4);loop {- if Instant::now() > deadline { panic!("timeout"); }+ if Instant::now() > deadline {+ panic!("timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}fn extract_text(v: &serde_json::Value) -> String {- v.pointer("/result/content/0/text").and_then(|t| t.as_str())+ v.pointer("/result/content/0/text")+ .and_then(|t| t.as_str()).or_else(|| v.pointer("/error").and_then(|e| e.as_str()))- .map(|s| s.to_owned()).unwrap_or_default()+ .map(|s| s.to_owned())+ .unwrap_or_default()}// 1. Set gradient + bloom — text should reflect both.- let r1 = req(&mut pipe,- r##"{"method":"call","name":"set_agent_cursor_style","args":{"gradient_colors":["#FF6B6B","#FF8E53"],"bloom_color":"#A855F7"}}"##);+ let r1 = req(+ &mut pipe,+ r##"{"method":"call","name":"set_agent_cursor_style","args":{"gradient_colors":["#FF6B6B","#FF8E53"],"bloom_color":"#A855F7"}}"##,+ );let t1 = extract_text(&serde_json::from_str(r1.trim()).unwrap());println!("Style resp: {t1:?}");- assert!(t1.contains("✅ cursor style:") && t1.contains("gradient_colors=[#FF6B6B,#FF8E53]")- && t1.contains("bloom_color=#A855F7"),- "Set-style text doesn't match Swift format: {t1:?}");+ assert!(+ t1.contains("✅ cursor style:")+ && t1.contains("gradient_colors=[#FF6B6B,#FF8E53]")+ && t1.contains("bloom_color=#A855F7"),+ "Set-style text doesn't match Swift format: {t1:?}"+ );println!("Set OK");// 2. Revert all — should produce "✅ cursor style: reverted to default".- let r2 = req(&mut pipe,- r#"{"method":"call","name":"set_agent_cursor_style","args":{"gradient_colors":[],"bloom_color":"","image_path":""}}"#);+ let r2 = req(+ &mut pipe,+ r#"{"method":"call","name":"set_agent_cursor_style","args":{"gradient_colors":[],"bloom_color":"","image_path":""}}"#,+ );let t2 = extract_text(&serde_json::from_str(r2.trim()).unwrap());println!("Revert resp: {t2:?}");- assert_eq!(t2, "✅ cursor style: reverted to default",- "Revert text wrong: {t2:?}");+ assert_eq!(+ t2, "✅ cursor style: reverted to default",+ "Revert text wrong: {t2:?}"+ );println!("Revert OK");println!("\n✅ PASS: set_agent_cursor_style text format matches Swift");diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/set_value_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/set_value_parity.rsindex 1cd50b37fa..8c25982a3b 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/set_value_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/set_value_parity.rs@@ -11,7 +11,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe");@@ -22,50 +23,86 @@ fn main() {let mut buf: Vec<u8> = vec![0u8; 64 * 1024];let deadline = Instant::now() + Duration::from_secs(4);loop {- if Instant::now() > deadline { panic!("timeout"); }+ if Instant::now() > deadline {+ panic!("timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}fn extract_text(v: &serde_json::Value) -> String {- v.pointer("/result/content/0/text").and_then(|t| t.as_str())+ v.pointer("/result/content/0/text")+ .and_then(|t| t.as_str()).or_else(|| v.pointer("/error").and_then(|e| e.as_str()))- .map(|s| s.to_owned()).unwrap_or_default()+ .map(|s| s.to_owned())+ .unwrap_or_default()}// Missing value error (with all three integers present). Note: pid /// window_id / element_index are schema-required; we pick a real pid +// window_id to ensure the schema doesn't reject before our tool runs.- let lw = req(&mut pipe, r#"{"method":"call","name":"list_windows","args":{}}"#);+ let lw = req(+ &mut pipe,+ r#"{"method":"call","name":"list_windows","args":{}}"#,+ );let lwv: serde_json::Value = serde_json::from_str(lw.trim()).unwrap();- let wins = lwv.pointer("/result/structuredContent/windows").and_then(|w| w.as_array()).unwrap();- let target = wins.iter().find(|w| {- let n = w.pointer("/app_name").and_then(|s| s.as_str()).unwrap_or("").to_lowercase();- n.contains("chrome") || n.contains("notepad")- }).expect("no target");+ let wins = lwv+ .pointer("/result/structuredContent/windows")+ .and_then(|w| w.as_array())+ .unwrap();+ let target = wins+ .iter()+ .find(|w| {+ let n = w+ .pointer("/app_name")+ .and_then(|s| s.as_str())+ .unwrap_or("")+ .to_lowercase();+ n.contains("chrome") || n.contains("notepad")+ })+ .expect("no target");let pid = target.pointer("/pid").and_then(|n| n.as_u64()).unwrap();- let wid = target.pointer("/window_id").and_then(|n| n.as_u64()).unwrap();+ let wid = target+ .pointer("/window_id")+ .and_then(|n| n.as_u64())+ .unwrap();// schema layer requires `value` — daemon rejects with its own wording;// either Swift's tool-layer wording or schema-layer wording is acceptable// as long as `value` is named.- let r1 = req(&mut pipe, &format!(- r#"{{"method":"call","name":"set_value","args":{{"pid":{pid},"window_id":{wid},"element_index":0}}}}"#));+ let r1 = req(+ &mut pipe,+ &format!(+ r#"{{"method":"call","name":"set_value","args":{{"pid":{pid},"window_id":{wid},"element_index":0}}}}"#+ ),+ );let e1 = extract_text(&serde_json::from_str(r1.trim()).unwrap());- assert!(e1.to_lowercase().contains("value") && e1.to_lowercase().contains("required"),- "Missing-value wording wrong: {e1:?}");+ assert!(+ e1.to_lowercase().contains("value") && e1.to_lowercase().contains("required"),+ "Missing-value wording wrong: {e1:?}"+ );println!("Missing-value err OK: {e1:?}");// Element-not-in-cache (we haven't run get_window_state). Should fail// with an "Element X not in cache" wording, not a schema error.- let r2 = req(&mut pipe, &format!(- r#"{{"method":"call","name":"set_value","args":{{"pid":{pid},"window_id":{wid},"element_index":99999,"value":"x"}}}}"#));+ let r2 = req(+ &mut pipe,+ &format!(+ r#"{{"method":"call","name":"set_value","args":{{"pid":{pid},"window_id":{wid},"element_index":99999,"value":"x"}}}}"#+ ),+ );let e2 = extract_text(&serde_json::from_str(r2.trim()).unwrap());- assert!(e2.to_lowercase().contains("not in cache") || e2.to_lowercase().contains("element"),- "Cache-miss wording should mention element/cache: {e2:?}");+ assert!(+ e2.to_lowercase().contains("not in cache") || e2.to_lowercase().contains("element"),+ "Cache-miss wording should mention element/cache: {e2:?}"+ );println!("Cache-miss err OK: {e2:?}");println!("\n✅ PASS: set_value validation + Swift-shape error wording verified");diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/type_text_chars_alias_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/type_text_chars_alias_parity.rsindex 6c0f91a3ca..887e2709b1 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/type_text_chars_alias_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/type_text_chars_alias_parity.rs@@ -10,7 +10,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe");@@ -21,49 +22,86 @@ fn main() {let mut buf: Vec<u8> = vec![0u8; 64 * 1024];let deadline = Instant::now() + Duration::from_secs(4);loop {- if Instant::now() > deadline { panic!("timeout"); }+ if Instant::now() > deadline {+ panic!("timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}fn extract_text(v: &serde_json::Value) -> String {- v.pointer("/result/content/0/text").and_then(|t| t.as_str())+ v.pointer("/result/content/0/text")+ .and_then(|t| t.as_str()).or_else(|| v.pointer("/error").and_then(|e| e.as_str()))- .map(|s| s.to_owned()).unwrap_or_default()+ .map(|s| s.to_owned())+ .unwrap_or_default()}// 1. `tools/list` (or equivalent) should NOT include `type_text_chars`.// The daemon's pipe has a `list` method that returns all registered// tools — we look for the alias and assert it's absent.let r1 = req(&mut pipe, r#"{"method":"list"}"#);- println!("list resp (first 1000 chars): {:?}", r1.chars().take(1000).collect::<String>());- assert!(!r1.contains("\"type_text_chars\""),- "type_text_chars should NOT appear in tools/list (Swift alias convention)");- assert!(r1.contains("\"type_text\""),- "type_text should appear in tools/list");+ println!(+ "list resp (first 1000 chars): {:?}",+ r1.chars().take(1000).collect::<String>()+ );+ assert!(+ !r1.contains("\"type_text_chars\""),+ "type_text_chars should NOT appear in tools/list (Swift alias convention)"+ );+ assert!(+ r1.contains("\"type_text\""),+ "type_text should appear in tools/list"+ );println!("tools/list excludes type_text_chars ✓");// 2. Invoking `type_text_chars` should still work — resolves to `type_text`.- let lw = req(&mut pipe, r#"{"method":"call","name":"list_windows","args":{}}"#);+ let lw = req(+ &mut pipe,+ r#"{"method":"call","name":"list_windows","args":{}}"#,+ );let lwv: serde_json::Value = serde_json::from_str(lw.trim()).unwrap();- let wins = lwv.pointer("/result/structuredContent/windows").and_then(|w| w.as_array()).unwrap();- let target = wins.iter().find(|w| {- let n = w.pointer("/app_name").and_then(|s| s.as_str()).unwrap_or("").to_lowercase();- n.contains("chrome") || n.contains("notepad")- }).expect("no target");+ let wins = lwv+ .pointer("/result/structuredContent/windows")+ .and_then(|w| w.as_array())+ .unwrap();+ let target = wins+ .iter()+ .find(|w| {+ let n = w+ .pointer("/app_name")+ .and_then(|s| s.as_str())+ .unwrap_or("")+ .to_lowercase();+ n.contains("chrome") || n.contains("notepad")+ })+ .expect("no target");let pid = target.pointer("/pid").and_then(|n| n.as_u64()).unwrap();- let wid = target.pointer("/window_id").and_then(|n| n.as_u64()).unwrap();- let r2 = req(&mut pipe, &format!(- r#"{{"method":"call","name":"type_text_chars","args":{{"pid":{pid},"window_id":{wid},"text":"x"}}}}"#));+ let wid = target+ .pointer("/window_id")+ .and_then(|n| n.as_u64())+ .unwrap();+ let r2 = req(+ &mut pipe,+ &format!(+ r#"{{"method":"call","name":"type_text_chars","args":{{"pid":{pid},"window_id":{wid},"text":"x"}}}}"#+ ),+ );let t2 = extract_text(&serde_json::from_str(r2.trim()).unwrap());println!("type_text_chars resp: {t2:?}");// Should produce the same response as `type_text` (which uses// "✅ Typed N char(s) on pid X via PostMessage (Yms delay).").- assert!(t2.starts_with("✅ Typed 1 char(s) on pid "),- "type_text_chars should resolve to type_text response: {t2:?}");+ assert!(+ t2.starts_with("✅ Typed 1 char(s) on pid "),+ "type_text_chars should resolve to type_text response: {t2:?}"+ );println!("\n✅ PASS: type_text_chars excluded from list AND aliased to type_text on invoke");}diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/type_text_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/type_text_parity.rsindex 09b3afe6fa..190f9e07a9 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/type_text_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/type_text_parity.rs@@ -6,7 +6,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe");@@ -17,55 +18,92 @@ fn main() {let mut buf: Vec<u8> = vec![0u8; 64 * 1024];let deadline = Instant::now() + Duration::from_secs(4);loop {- if Instant::now() > deadline { panic!("timeout"); }+ if Instant::now() > deadline {+ panic!("timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}fn extract_text(v: &serde_json::Value) -> String {- v.pointer("/result/content/0/text").and_then(|t| t.as_str())+ v.pointer("/result/content/0/text")+ .and_then(|t| t.as_str()).or_else(|| v.pointer("/error").and_then(|e| e.as_str()))- .map(|s| s.to_owned()).unwrap_or_default()+ .map(|s| s.to_owned())+ .unwrap_or_default()}// 1. Missing text error.- let r1 = req(&mut pipe, r#"{"method":"call","name":"type_text","args":{"pid":1}}"#);+ let r1 = req(+ &mut pipe,+ r#"{"method":"call","name":"type_text","args":{"pid":1}}"#,+ );let e1 = extract_text(&serde_json::from_str(r1.trim()).unwrap());- assert!(e1.contains("text") && e1.to_lowercase().contains("required"),- "Missing-text wording wrong: {e1:?}");+ assert!(+ e1.contains("text") && e1.to_lowercase().contains("required"),+ "Missing-text wording wrong: {e1:?}"+ );println!("Missing-text err OK");// 2. element_index without window_id.- let r2 = req(&mut pipe, r#"{"method":"call","name":"type_text","args":{"pid":1,"text":"x","element_index":0}}"#);+ let r2 = req(+ &mut pipe,+ r#"{"method":"call","name":"type_text","args":{"pid":1,"text":"x","element_index":0}}"#,+ );let e2 = extract_text(&serde_json::from_str(r2.trim()).unwrap());- assert!(e2.contains("window_id is required when element_index is used"),- "Element-without-window wording wrong: {e2:?}");+ assert!(+ e2.contains("window_id is required when element_index is used"),+ "Element-without-window wording wrong: {e2:?}"+ );println!("Element-without-window err OK");// 3. Real type against Chrome address bar — we can't reliably target it// here; just send to Chrome's window and verify the response text format.- let lw = req(&mut pipe, r#"{"method":"call","name":"list_windows","args":{}}"#);+ let lw = req(+ &mut pipe,+ r#"{"method":"call","name":"list_windows","args":{}}"#,+ );let lwv: serde_json::Value = serde_json::from_str(lw.trim()).unwrap();- let wins = lwv.pointer("/result/structuredContent/windows").and_then(|w| w.as_array()).unwrap();- let target = wins.iter().find(|w| {- let n = w.pointer("/app_name").and_then(|s| s.as_str()).unwrap_or("").to_lowercase();- n.contains("chrome") || n.contains("notepad")- }).expect("no target");+ let wins = lwv+ .pointer("/result/structuredContent/windows")+ .and_then(|w| w.as_array())+ .unwrap();+ let target = wins+ .iter()+ .find(|w| {+ let n = w+ .pointer("/app_name")+ .and_then(|s| s.as_str())+ .unwrap_or("")+ .to_lowercase();+ n.contains("chrome") || n.contains("notepad")+ })+ .expect("no target");let pid = target.pointer("/pid").and_then(|n| n.as_u64()).unwrap();- let wid = target.pointer("/window_id").and_then(|n| n.as_u64()).unwrap();+ let wid = target+ .pointer("/window_id")+ .and_then(|n| n.as_u64())+ .unwrap();let tt = format!(- r#"{{"method":"call","name":"type_text","args":{{"pid":{pid},"window_id":{wid},"text":"hello","delay_ms":10}}}}"#);+ r#"{{"method":"call","name":"type_text","args":{{"pid":{pid},"window_id":{wid},"text":"hello","delay_ms":10}}}}"#+ );let r3 = req(&mut pipe, &tt);let t3 = extract_text(&serde_json::from_str(r3.trim()).unwrap());println!("Type resp: {t3:?}");// Swift format: "✅ Typed N char(s) on pid X via CGEvent (Yms delay)."// Windows variant: "✅ Typed N char(s) on pid X via PostMessage (Yms delay)."- assert!(t3.starts_with(&format!("✅ Typed 5 char(s) on pid {pid} via PostMessage"))- && t3.contains("10ms delay"),- "Type text response doesn't match Swift-shape format: {t3:?}");+ assert!(+ t3.starts_with(&format!("✅ Typed 5 char(s) on pid {pid} via PostMessage"))+ && t3.contains("10ms delay"),+ "Type text response doesn't match Swift-shape format: {t3:?}"+ );println!("\n✅ PASS: type_text validation + Swift-shape text format verified");}diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/update_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/update_parity.rsindex 8221b76378..c0227d7dc8 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/update_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/update_parity.rs@@ -5,20 +5,29 @@ use std::process::Command;#[cfg(target_os = "windows")]fn main() {let exe = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))- .parent().unwrap()- .parent().unwrap()+ .parent()+ .unwrap()+ .parent()+ .unwrap().join("target/debug/cua-driver.exe");- let out = Command::new(&exe).arg("update").output().expect("run update");+ let out = Command::new(&exe)+ .arg("update")+ .output()+ .expect("run update");let stdout = String::from_utf8_lossy(&out.stdout);println!("update stdout (first 500 chars):");println!("{}", stdout.chars().take(500).collect::<String>());// Always-present lines.- assert!(stdout.contains("Current version:"),- "missing 'Current version:' header");- assert!(stdout.contains("Checking for updates"),- "missing 'Checking for updates' line");+ assert!(+ stdout.contains("Current version:"),+ "missing 'Current version:' header"+ );+ assert!(+ stdout.contains("Checking for updates"),+ "missing 'Checking for updates' line"+ );// Outcome is one of:// - "Already up to date." (current ≥ latest published)@@ -27,13 +36,19 @@ fn main() {let outcome_present = stdout.contains("Already up to date")|| stdout.contains("New version available:")|| stdout.contains("Could not reach GitHub");- assert!(outcome_present, "no outcome line found in update output:\n{stdout}");+ assert!(+ outcome_present,+ "no outcome line found in update output:\n{stdout}"+ );// Critical: if a new version IS reported, the tag prefix must be the Rust-// port one (`cua-driver-rs-v*`) — otherwise we'd be recommending the// Swift binary's version which would be a real-user bug.if stdout.contains("New version available:") {- let line = stdout.lines().find(|l| l.contains("New version available:")).unwrap();+ let line = stdout+ .lines()+ .find(|l| l.contains("New version available:"))+ .unwrap();// The version printed should be numeric (e.g. "0.1.2"), not a// Swift-style version that exists on the same repo but is for a// different binary. We can't directly tell from the output, butdiff --git a/libs/cua-driver/rust/crates/platform-windows/examples/zdrop_probe.rs b/libs/cua-driver/rust/crates/platform-windows/examples/zdrop_probe.rsindex 8fbdef461c..e74eb330d1 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/zdrop_probe.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/zdrop_probe.rs@@ -47,18 +47,18 @@ mod probe {use windows::Win32::UI::HiDpi::{SetProcessDpiAwarenessContext, DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2,};+ use windows::Win32::UI::Input::KeyboardAndMouse::{+ SendInput, INPUT, INPUT_0, INPUT_MOUSE, MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP,+ MOUSEINPUT,+ };use windows::Win32::UI::Input::Pointer::{InitializeTouchInjection, InjectTouchInput, POINTER_FLAG_DOWN, POINTER_FLAG_INCONTACT,POINTER_FLAG_INRANGE, POINTER_FLAG_UP, POINTER_INFO, POINTER_TOUCH_INFO,TOUCH_FEEDBACK_DEFAULT,};- use windows::Win32::UI::Input::KeyboardAndMouse::{- SendInput, INPUT, INPUT_0, INPUT_MOUSE, MOUSEINPUT, MOUSEEVENTF_LEFTDOWN,- MOUSEEVENTF_LEFTUP,- };use windows::Win32::UI::WindowsAndMessaging::{- EnumWindows, GetClassNameW, GetCursorPos, GetForegroundWindow, GetWindow, GetWindowRect,- GetWindowTextW, GetWindowThreadProcessId, GetTopWindow, IsWindowVisible, SetCursorPos,+ EnumWindows, GetClassNameW, GetCursorPos, GetForegroundWindow, GetTopWindow, GetWindow,+ GetWindowRect, GetWindowTextW, GetWindowThreadProcessId, IsWindowVisible, SetCursorPos,SetForegroundWindow, GW_HWNDNEXT, PT_TOUCH,};@@ -93,7 +93,11 @@ mod probe {let baseline = HWND(baseline as *mut _);let target = HWND(target as *mut _);let deadline = Instant::now() + dur;- let mut r = PollResult { samples: 0, target_above: 0, fg_not_baseline: 0 };+ let mut r = PollResult {+ samples: 0,+ target_above: 0,+ fg_not_baseline: 0,+ };while Instant::now() < deadline {unsafe {r.samples += 1;@@ -124,13 +128,19 @@ mod probe {let down = INPUT {r#type: INPUT_MOUSE,Anonymous: INPUT_0 {- mi: MOUSEINPUT { dwFlags: MOUSEEVENTF_LEFTDOWN, ..Default::default() },+ mi: MOUSEINPUT {+ dwFlags: MOUSEEVENTF_LEFTDOWN,+ ..Default::default()+ },},};let up = INPUT {r#type: INPUT_MOUSE,Anonymous: INPUT_0 {- mi: MOUSEINPUT { dwFlags: MOUSEEVENTF_LEFTUP, ..Default::default() },+ mi: MOUSEINPUT {+ dwFlags: MOUSEEVENTF_LEFTUP,+ ..Default::default()+ },},};let events = [down, up];@@ -161,8 +171,18 @@ mod probe {},touchFlags: 0,touchMask: 0,- rcContact: RECT { left: x - 2, top: y - 2, right: x + 2, bottom: y + 2 },- rcContactRaw: RECT { left: x - 2, top: y - 2, right: x + 2, bottom: y + 2 },+ rcContact: RECT {+ left: x - 2,+ top: y - 2,+ right: x + 2,+ bottom: y + 2,+ },+ rcContactRaw: RECT {+ left: x - 2,+ top: y - 2,+ right: x + 2,+ bottom: y + 2,+ },orientation: 0,pressure: 512,};@@ -218,7 +238,13 @@ mod probe {let _ = (x, y);actuate();let r = poller.join().unwrap();- let pct = |n: u64| if r.samples == 0 { 0.0 } else { 100.0 * n as f64 / r.samples as f64 };+ let pct = |n: u64| {+ if r.samples == 0 {+ 0.0+ } else {+ 100.0 * n as f64 / r.samples as f64+ }+ };println!(" [{name:8}] samples={:4} target_above_baseline={:4} ({:5.1}%) fg!=baseline={:4} ({:5.1}%)",r.samples, r.target_above, pct(r.target_above), r.fg_not_baseline, pct(r.fg_not_baseline)@@ -252,13 +278,25 @@ mod probe {.collect();if mode == "list" || candidates.is_empty() {- println!("Foreground (baseline): pid={} class={:?} title={:?}", pid_of(fg), class_of(fg), title_of(fg));+ println!(+ "Foreground (baseline): pid={} class={:?} title={:?}",+ pid_of(fg),+ class_of(fg),+ title_of(fg)+ );println!("Candidate background windows:");for h in &candidates {- println!(" pid={:6} class={:24} title={:?}", pid_of(*h), class_of(*h), title_of(*h));+ println!(+ " pid={:6} class={:24} title={:?}",+ pid_of(*h),+ class_of(*h),+ title_of(*h)+ );}if candidates.is_empty() {- eprintln!("\nNo background candidate windows. Open one and focus a different window.");+ eprintln!(+ "\nNo background candidate windows. Open one and focus a different window."+ );}if mode == "list" {return;@@ -287,16 +325,26 @@ mod probe {return;};- println!("baseline (user fg): pid={} title={:?}", pid_of(fg), title_of(fg));+ println!(+ "baseline (user fg): pid={} title={:?}",+ pid_of(fg),+ title_of(fg)+ );println!("target (background): pid={} class={:?} title={:?} click@({x},{y})",- pid_of(target), class_of(target), title_of(target)+ pid_of(target),+ class_of(target),+ title_of(target)+ );+ println!(+ "Position your windows now — actuating in 2s. (target should stay BEHIND baseline)");- println!("Position your windows now — actuating in 2s. (target should stay BEHIND baseline)");thread::sleep(Duration::from_secs(2));if mode == "both" || mode == "control" {- run_trial("control", fg, target, x, y, || actuate_sendinput_swap(target.0 as usize, x, y));+ run_trial("control", fg, target, x, y, || {+ actuate_sendinput_swap(target.0 as usize, x, y)+ });thread::sleep(Duration::from_millis(400));}if mode == "both" || mode == "inject" {@@ -308,7 +356,11 @@ mod probe {}});}- println!("\nInterpretation: control should show a high target_above%/fg!=baseline% (the flash).");- println!("Track A (inject) showing ~0% target_above == background input with no visible raise.");+ println!(+ "\nInterpretation: control should show a high target_above%/fg!=baseline% (the flash)."+ );+ println!(+ "Track A (inject) showing ~0% target_above == background input with no visible raise."+ );}}diff --git a/libs/cua-driver/rust/crates/platform-windows/examples/zoom_parity.rs b/libs/cua-driver/rust/crates/platform-windows/examples/zoom_parity.rsindex 01ca66f25b..7ef7b60f4f 100644--- a/libs/cua-driver/rust/crates/platform-windows/examples/zoom_parity.rs+++ b/libs/cua-driver/rust/crates/platform-windows/examples/zoom_parity.rs@@ -6,7 +6,8 @@ use std::time::{Duration, Instant};#[cfg(target_os = "windows")]fn main() {let mut pipe = std::fs::OpenOptions::new()- .read(true).write(true)+ .read(true)+ .write(true).open(r"\\.\pipe\cua-driver").expect("open pipe");@@ -17,61 +18,113 @@ fn main() {let mut buf: Vec<u8> = vec![0u8; 64 * 1024];let deadline = Instant::now() + Duration::from_secs(4);loop {- if Instant::now() > deadline { panic!("timeout"); }+ if Instant::now() > deadline {+ panic!("timeout");+ }let n = p.read(&mut buf).unwrap_or(0);- if n == 0 { break; }+ if n == 0 {+ break;+ }out.extend_from_slice(&buf[..n]);- if out.contains(&b'\n') { break; }+ if out.contains(&b'\n') {+ break;+ }}String::from_utf8_lossy(&out).into_owned()}fn extract_text(v: &serde_json::Value) -> String {- v.pointer("/result/content/0/text").and_then(|t| t.as_str())+ v.pointer("/result/content/0/text")+ .and_then(|t| t.as_str()).or_else(|| v.pointer("/error").and_then(|e| e.as_str()))- .map(|s| s.to_owned()).unwrap_or_default()+ .map(|s| s.to_owned())+ .unwrap_or_default()}- let lw = req(&mut pipe, r#"{"method":"call","name":"list_windows","args":{}}"#);+ let lw = req(+ &mut pipe,+ r#"{"method":"call","name":"list_windows","args":{}}"#,+ );let lwv: serde_json::Value = serde_json::from_str(lw.trim()).unwrap();- let wins = lwv.pointer("/result/structuredContent/windows").and_then(|w| w.as_array()).unwrap();- let target = wins.iter().find(|w| {- let n = w.pointer("/app_name").and_then(|s| s.as_str()).unwrap_or("").to_lowercase();- n.contains("chrome")- }).expect("no chrome");+ let wins = lwv+ .pointer("/result/structuredContent/windows")+ .and_then(|w| w.as_array())+ .unwrap();+ let target = wins+ .iter()+ .find(|w| {+ let n = w+ .pointer("/app_name")+ .and_then(|s| s.as_str())+ .unwrap_or("")+ .to_lowercase();+ n.contains("chrome")+ })+ .expect("no chrome");let pid = target.pointer("/pid").and_then(|n| n.as_u64()).unwrap();- let wid = target.pointer("/window_id").and_then(|n| n.as_u64()).unwrap();+ let wid = target+ .pointer("/window_id")+ .and_then(|n| n.as_u64())+ .unwrap();// 1. Invalid region (x2 ≤ x1).- let r1 = req(&mut pipe, &format!(- r#"{{"method":"call","name":"zoom","args":{{"pid":{pid},"window_id":{wid},"x1":100,"y1":100,"x2":50,"y2":200}}}}"#));+ let r1 = req(+ &mut pipe,+ &format!(+ r#"{{"method":"call","name":"zoom","args":{{"pid":{pid},"window_id":{wid},"x1":100,"y1":100,"x2":50,"y2":200}}}}"#+ ),+ );let e1 = extract_text(&serde_json::from_str(r1.trim()).unwrap());- assert!(e1.contains("Invalid region: x2 must be > x1 and y2 must be > y1"),- "Invalid-region wording wrong: {e1:?}");+ assert!(+ e1.contains("Invalid region: x2 must be > x1 and y2 must be > y1"),+ "Invalid-region wording wrong: {e1:?}"+ );println!("Invalid-region err OK");// 2. Region too wide.- let r2 = req(&mut pipe, &format!(- r#"{{"method":"call","name":"zoom","args":{{"pid":{pid},"window_id":{wid},"x1":0,"y1":0,"x2":600,"y2":100}}}}"#));+ let r2 = req(+ &mut pipe,+ &format!(+ r#"{{"method":"call","name":"zoom","args":{{"pid":{pid},"window_id":{wid},"x1":0,"y1":0,"x2":600,"y2":100}}}}"#+ ),+ );let e2 = extract_text(&serde_json::from_str(r2.trim()).unwrap());- assert!(e2.contains("Zoom region too wide") && e2.contains("> 500 px max"),- "Too-wide wording wrong: {e2:?}");+ assert!(+ e2.contains("Zoom region too wide") && e2.contains("> 500 px max"),+ "Too-wide wording wrong: {e2:?}"+ );println!("Too-wide err OK");// 3. Real zoom — small region.- let r3 = req(&mut pipe, &format!(- r#"{{"method":"call","name":"zoom","args":{{"pid":{pid},"window_id":{wid},"x1":50,"y1":50,"x2":150,"y2":150}}}}"#));+ let r3 = req(+ &mut pipe,+ &format!(+ r#"{{"method":"call","name":"zoom","args":{{"pid":{pid},"window_id":{wid},"x1":50,"y1":50,"x2":150,"y2":150}}}}"#+ ),+ );let v3: serde_json::Value = serde_json::from_str(r3.trim()).unwrap();- let content = v3.pointer("/result/content").and_then(|c| c.as_array()).unwrap();- let img_present = content.iter().any(|c| c.get("type").and_then(|t| t.as_str()) == Some("image"));- let text = content.iter().find_map(|c| {- if c.get("type").and_then(|t| t.as_str()) == Some("text") {- c.get("text").and_then(|t| t.as_str())- } else { None }- }).unwrap_or("");+ let content = v3+ .pointer("/result/content")+ .and_then(|c| c.as_array())+ .unwrap();+ let img_present = content+ .iter()+ .any(|c| c.get("type").and_then(|t| t.as_str()) == Some("image"));+ let text = content+ .iter()+ .find_map(|c| {+ if c.get("type").and_then(|t| t.as_str()) == Some("text") {+ c.get("text").and_then(|t| t.as_str())+ } else {+ None+ }+ })+ .unwrap_or("");assert!(img_present, "zoom response should include image content");- assert!(text.starts_with("✅ Zoomed region captured at native resolution.")- && text.contains("from_zoom=true"),- "zoom text doesn't match Swift format: {text:?}");+ assert!(+ text.starts_with("✅ Zoomed region captured at native resolution.")+ && text.contains("from_zoom=true"),+ "zoom text doesn't match Swift format: {text:?}"+ );println!("Real zoom OK");println!("\n✅ PASS: zoom error wording + Swift text format verified");diff --git a/libs/cua-driver/rust/crates/platform-windows/src/capture.rs b/libs/cua-driver/rust/crates/platform-windows/src/capture.rsindex 95cb281913..1dbee84781 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/capture.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/capture.rs@@ -30,9 +30,8 @@ use anyhow::{bail, Result};use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};use windows::Win32::Foundation::HWND;use windows::Win32::Graphics::Gdi::{- BitBlt, CreateCompatibleBitmap, CreateCompatibleDC, DeleteDC, DeleteObject, GetDC,- GetDIBits, SelectObject, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS,- RGBQUAD, SRCCOPY,+ BitBlt, CreateCompatibleBitmap, CreateCompatibleDC, DeleteDC, DeleteObject, GetDC, GetDIBits,+ SelectObject, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS, RGBQUAD, SRCCOPY,};use windows::Win32::Graphics::Gdi::{GetWindowDC, ReleaseDC};use windows::Win32::Storage::Xps::{PrintWindow, PRINT_WINDOW_FLAGS};@@ -48,9 +47,13 @@ const PW_RENDERFULLCONTENT: PRINT_WINDOW_FLAGS = PRINT_WINDOW_FLAGS(2u32);/// all-zeros bitmaps, not just dark frames — so legitimate dark UI doesn't/// trip the fallback.fn is_mostly_black_bgra(bgra: &[u8]) -> bool {- if bgra.len() < 16 { return true; }+ if bgra.len() < 16 {+ return true;+ }let pixel_count = bgra.len() / 4;- if pixel_count == 0 { return true; }+ if pixel_count == 0 {+ return true;+ }let stride = (pixel_count / 1024).max(1);let mut sampled = 0usize;let mut black = 0usize;@@ -98,10 +101,10 @@ unsafe fn target_is_obscured(target: HWND) -> bool {}// 5 sample points: 4 corners (inset 2 px) + center.let pts: [(i32, i32); 5] = [- (rect.left + 2, rect.top + 2),- (rect.right - 3, rect.top + 2),- (rect.left + 2, rect.bottom - 3),- (rect.right - 3, rect.bottom - 3),+ (rect.left + 2, rect.top + 2),+ (rect.right - 3, rect.top + 2),+ (rect.left + 2, rect.bottom - 3),+ (rect.right - 3, rect.bottom - 3),((rect.left + rect.right) / 2, (rect.top + rect.bottom) / 2),];let target_root = GetAncestor(target, GA_ROOT);@@ -155,7 +158,17 @@ unsafe fn screenshot_via_screen_region(hwnd: HWND) -> Result<(Vec<u8>, i32, i32)let old_bitmap = SelectObject(mem_dc, bitmap);// Copy from physical screen coords into our memory DC at (0, 0).- let blt_ok = BitBlt(mem_dc, 0, 0, w, h, screen_dc, physical_left, physical_top, SRCCOPY);+ let blt_ok = BitBlt(+ mem_dc,+ 0,+ 0,+ w,+ h,+ screen_dc,+ physical_left,+ physical_top,+ SRCCOPY,+ );let mut bmi = BITMAPINFO {bmiHeader: BITMAPINFOHEADER {@@ -173,8 +186,13 @@ unsafe fn screenshot_via_screen_region(hwnd: HWND) -> Result<(Vec<u8>, i32, i32)let pixel_count = (w * h) as usize;let mut pixels = vec![0u8; pixel_count * 4];let ok = GetDIBits(- mem_dc, bitmap, 0, h as u32,- Some(pixels.as_mut_ptr() as *mut _), &mut bmi, DIB_RGB_COLORS,+ mem_dc,+ bitmap,+ 0,+ h as u32,+ Some(pixels.as_mut_ptr() as *mut _),+ &mut bmi,+ DIB_RGB_COLORS,);SelectObject(mem_dc, old_bitmap);@@ -216,9 +234,7 @@ pub fn screenshot_window_bytes_with_occlusion(hwnd: u64) -> Result<(Vec<u8>, boo// first fallback for this class of capture failure.match crate::wgc::screenshot_window_via_wgc(hwnd) {Ok((pixels, width, height)) => Ok((- cua_driver_core::image_utils::encode_bgra_to_png(- &pixels, width, height,- )?,+ cua_driver_core::image_utils::encode_bgra_to_png(&pixels, width, height)?,false,)),Err(wgc_error) => {@@ -252,7 +268,9 @@ pub fn screenshot_window_bytes_with_occlusion(hwnd: u64) -> Result<(Vec<u8>, boopub fn screenshot_window(hwnd: u64) -> Result<(String, u32, u32)> {let png_bytes = screenshot_window_bytes(hwnd)?;let (w, h) = {- if png_bytes.len() < 24 { bail!("PNG too small"); }+ if png_bytes.len() < 24 {+ bail!("PNG too small");+ }let w = u32::from_be_bytes([png_bytes[16], png_bytes[17], png_bytes[18], png_bytes[19]]);let h = u32::from_be_bytes([png_bytes[20], png_bytes[21], png_bytes[22], png_bytes[23]]);(w, h)@@ -261,8 +279,8 @@ pub fn screenshot_window(hwnd: u64) -> Result<(String, u32, u32)> {}unsafe fn screenshot_window_bytes_with_occlusion_unsafe(hwnd: u64) -> Result<(Vec<u8>, bool)> {- use windows::Win32::UI::WindowsAndMessaging::{GetWindowRect, IsIconic};use windows::Win32::Foundation::RECT;+ use windows::Win32::UI::WindowsAndMessaging::{GetWindowRect, IsIconic};let hwnd_raw = hwnd;let hwnd = HWND(hwnd as *mut _);@@ -385,9 +403,7 @@ unsafe fn screenshot_window_bytes_with_occlusion_unsafe(hwnd: u64) -> Result<(Ve// by some shell extension), we keep the full-window bitmap as-is —// user sees a small dark border but no clipping.let dwm_rect: Option<RECT> = {- use windows::Win32::Graphics::Dwm::{- DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS,- };+ use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};let mut r = RECT::default();let hr = DwmGetWindowAttribute(hwnd,@@ -414,14 +430,24 @@ unsafe fn screenshot_window_bytes_with_occlusion_unsafe(hwnd: u64) -> Result<(Velet pixel_count = (w * h) as usize;let mut pixels = vec![0u8; pixel_count * 4];- let ok = GetDIBits(mem_dc, bitmap, 0, h as u32, Some(pixels.as_mut_ptr() as *mut _), &mut bmi, DIB_RGB_COLORS);+ let ok = GetDIBits(+ mem_dc,+ bitmap,+ 0,+ h as u32,+ Some(pixels.as_mut_ptr() as *mut _),+ &mut bmi,+ DIB_RGB_COLORS,+ );SelectObject(mem_dc, old_bitmap);let _ = DeleteObject(bitmap);let _ = DeleteDC(mem_dc);ReleaseDC(hwnd, screen_dc);- if ok == 0 { bail!("GetDIBits returned 0"); }+ if ok == 0 {+ bail!("GetDIBits returned 0");+ }// Crop the bitmap to the DWM extended-frame bounds (computed above)// to remove the invisible-shadow margin PrintWindow doesn't paint.@@ -442,8 +468,12 @@ unsafe fn screenshot_window_bytes_with_occlusion_unsafe(hwnd: u64) -> Result<(Velet off_y = (dwm.top - win_rect.top) as i32 + DWM_CROP_INSET_PX;let crop_w = (dwm.right - dwm.left) as i32 - 2 * DWM_CROP_INSET_PX;let crop_h = (dwm.bottom - dwm.top) as i32 - 2 * DWM_CROP_INSET_PX;- if off_x >= 0 && off_y >= 0 && crop_w > 0 && crop_h > 0- && off_x + crop_w <= w && off_y + crop_h <= h+ if off_x >= 0+ && off_y >= 0+ && crop_w > 0+ && crop_h > 0+ && off_x + crop_w <= w+ && off_y + crop_h <= h{let stride_full = (w * 4) as usize;let stride_crop = (crop_w * 4) as usize;@@ -489,7 +519,11 @@ unsafe fn screenshot_window_bytes_with_occlusion_unsafe(hwnd: u64) -> Result<(Vematch screenshot_via_screen_region(hwnd) {Ok((alt_pixels, alt_w, alt_h)) => {return Ok((- cua_driver_core::image_utils::encode_bgra_to_png(&alt_pixels, alt_w as u32, alt_h as u32)?,+ cua_driver_core::image_utils::encode_bgra_to_png(+ &alt_pixels,+ alt_w as u32,+ alt_h as u32,+ )?,occluded,));}@@ -515,7 +549,10 @@ unsafe fn screenshot_window_bytes_with_occlusion_unsafe(hwnd: u64) -> Result<(Ve// PrintWindow itself reads from the target's own DC, so the bitmap// we return here is the target's pixels even when occluded — no// occluded warning needed on this path.- Ok((cua_driver_core::image_utils::encode_bgra_to_png(&pixels, w as u32, h as u32)?, false))+ Ok((+ cua_driver_core::image_utils::encode_bgra_to_png(&pixels, w as u32, h as u32)?,+ false,+ ))}// NOTE: previously this module carried a hand-rolled@@ -542,7 +579,9 @@ pub fn screenshot_display_bytes() -> Result<Vec<u8>> {// (issue #1879).let w = GetSystemMetrics(SM_CXSCREEN);let h = GetSystemMetrics(SM_CYSCREEN);- if w <= 0 || h <= 0 { bail!("Could not get screen metrics"); }+ if w <= 0 || h <= 0 {+ bail!("Could not get screen metrics");+ }let screen_dc = GetDC(HWND::default());let mem_dc = CreateCompatibleDC(screen_dc);let bitmap = CreateCompatibleBitmap(screen_dc, w, h);@@ -551,19 +590,33 @@ pub fn screenshot_display_bytes() -> Result<Vec<u8>> {let mut bmi = BITMAPINFO {bmiHeader: BITMAPINFOHEADER {biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,- biWidth: w, biHeight: -h, biPlanes: 1, biBitCount: 32,+ biWidth: w,+ biHeight: -h,+ biPlanes: 1,+ biBitCount: 32,biCompression: BI_RGB.0,- biSizeImage: (w * h * 4) as u32, ..Default::default()+ biSizeImage: (w * h * 4) as u32,+ ..Default::default()},bmiColors: [RGBQUAD::default(); 1],};let mut pixels = vec![0u8; (w * h * 4) as usize];- let ok = GetDIBits(mem_dc, bitmap, 0, h as u32, Some(pixels.as_mut_ptr() as *mut _), &mut bmi, DIB_RGB_COLORS);+ let ok = GetDIBits(+ mem_dc,+ bitmap,+ 0,+ h as u32,+ Some(pixels.as_mut_ptr() as *mut _),+ &mut bmi,+ DIB_RGB_COLORS,+ );SelectObject(mem_dc, old_bitmap);let _ = DeleteObject(bitmap);let _ = DeleteDC(mem_dc);ReleaseDC(HWND::default(), screen_dc);- if ok == 0 { bail!("GetDIBits returned 0"); }+ if ok == 0 {+ bail!("GetDIBits returned 0");+ }cua_driver_core::image_utils::encode_bgra_to_png(&pixels, w as u32, h as u32)}}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/diagnostics.rs b/libs/cua-driver/rust/crates/platform-windows/src/diagnostics.rsindex 3348409879..6914ada1f1 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/diagnostics.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/diagnostics.rs@@ -155,21 +155,18 @@ pub fn desktop_state() -> DesktopState {Err(e) => (None, Some(format!("GetThreadDesktop: {e}"))),};- let (input_desktop_name, input_desktop_error) = match OpenInputDesktop(- DESKTOP_CONTROL_FLAGS(0),- false,- DESKTOP_READOBJECTS,- ) {- Ok(h) => {- let name = desktop_name(h);- let _ = CloseDesktop(h);- match name {- Ok(name) => (Some(name), None),- Err(e) => (None, Some(format!("OpenInputDesktop name: {e}"))),+ let (input_desktop_name, input_desktop_error) =+ match OpenInputDesktop(DESKTOP_CONTROL_FLAGS(0), false, DESKTOP_READOBJECTS) {+ Ok(h) => {+ let name = desktop_name(h);+ let _ = CloseDesktop(h);+ match name {+ Ok(name) => (Some(name), None),+ Err(e) => (None, Some(format!("OpenInputDesktop name: {e}"))),+ }}- }- Err(e) => (None, Some(format!("OpenInputDesktop: {e}"))),- };+ Err(e) => (None, Some(format!("OpenInputDesktop: {e}"))),+ };let fg = GetForegroundWindow();let foreground_hwnd = (!fg.0.is_null()).then_some(fg.0 as usize);@@ -243,13 +240,10 @@ pub fn ui_automation_available() -> Result<(), String> {// we proceed to CoUninitialize. Holding the binding past// CoUninitialize and letting Drop run at function return// causes a use-after-free in the COM apartment.- let result = CoCreateInstance::<_, IUIAutomation>(- &CUIAutomation,- None,- CLSCTX_INPROC_SERVER,- )- .map(|_| ())- .map_err(|e| format!("{e}"));+ let result =+ CoCreateInstance::<_, IUIAutomation>(&CUIAutomation, None, CLSCTX_INPROC_SERVER)+ .map(|_| ())+ .map_err(|e| format!("{e}"));if need_uninit {CoUninitialize();@@ -338,8 +332,8 @@ mod tests {match ui_automation_available() {Ok(()) => {}Err(e) => {- let non_interactive = current_session_id() == Some(0)- || is_non_interactive_error(&e);+ let non_interactive =+ current_session_id() == Some(0) || is_non_interactive_error(&e);assert!(non_interactive,"ui_automation_available failed in what looks like an interactive session: {e}",diff --git a/libs/cua-driver/rust/crates/platform-windows/src/health_report.rs b/libs/cua-driver/rust/crates/platform-windows/src/health_report.rsindex 72628e2d6c..fe90fa39e6 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/health_report.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/health_report.rs@@ -153,8 +153,8 @@ fn probe_d3d11_device() -> Result<(), String> {use windows::Win32::Graphics::{Direct3D::{D3D_DRIVER_TYPE_HARDWARE, D3D_FEATURE_LEVEL_11_0},Direct3D11::{- D3D11CreateDevice, ID3D11Device, ID3D11DeviceContext,- D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_SDK_VERSION,+ D3D11CreateDevice, ID3D11Device, ID3D11DeviceContext, D3D11_CREATE_DEVICE_BGRA_SUPPORT,+ D3D11_SDK_VERSION,},};let mut device: Option<ID3D11Device> = None;@@ -189,7 +189,10 @@ fn probe_d3d11_device() -> Result<(), String> {fn ver_string() -> Option<String> {#[cfg(target_os = "windows")]{- let output = std::process::Command::new("cmd").args(["/c", "ver"]).output().ok()?;+ let output = std::process::Command::new("cmd")+ .args(["/c", "ver"])+ .output()+ .ok()?;if !output.status.success() {return None;}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/input/inject.rs b/libs/cua-driver/rust/crates/platform-windows/src/input/inject.rsindex ce8157fc58..50a85c9e08 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/input/inject.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/input/inject.rs@@ -154,7 +154,11 @@ impl NoActivateGuard {unsafe {let root = {let r = GetAncestor(hwnd, GA_ROOT);- if r.0.is_null() { hwnd } else { r }+ if r.0.is_null() {+ hwnd+ } else {+ r+ }};let prev = GetWindowLongPtrW(root, GWL_EXSTYLE);let want = WS_EX_NOACTIVATE.0 as isize;@@ -275,7 +279,13 @@ fn pen_taps(sx: i32, sy: i32, barrel: bool, count: usize) -> Result<()> {/// path for both buttons — `InjectTouchInput` proved unreliable for left-clicks/// on Chromium content (returned errors), whereas synthetic-pen injection lands/// reliably and routes by coordinate with no foreground dependency.-pub fn inject_click_screen(target: u64, sx: i32, sy: i32, count: usize, button: &str) -> Result<()> {+pub fn inject_click_screen(+ target: u64,+ sx: i32,+ sy: i32,+ count: usize,+ button: &str,+) -> Result<()> {if target == 0 {bail!("inject_click_screen: null target window");}@@ -405,7 +415,11 @@ fn pen_drag(sx0: i32, sy0: i32, sx1: i32, sy1: i32, steps: usize, barrel: bool)},};// Press at the start.- let down = mk(POINTER_FLAG_DOWN | POINTER_FLAG_INRANGE | POINTER_FLAG_INCONTACT, sx0, sy0);+ let down = mk(+ POINTER_FLAG_DOWN | POINTER_FLAG_INRANGE | POINTER_FLAG_INCONTACT,+ sx0,+ sy0,+ );let mut res = InjectSyntheticPointerInput(dev, &[down]);// Interpolated in-contact moves so frameworks that gate drag-tracking on// motion (rather than a single down→up) see a continuous stroke.@@ -415,7 +429,11 @@ fn pen_drag(sx0: i32, sy0: i32, sx1: i32, sy1: i32, steps: usize, barrel: bool)let t = i as f64 / steps as f64;let x = sx0 + ((sx1 - sx0) as f64 * t).round() as i32;let y = sy0 + ((sy1 - sy0) as f64 * t).round() as i32;- let mv = mk(POINTER_FLAG_UPDATE | POINTER_FLAG_INRANGE | POINTER_FLAG_INCONTACT, x, y);+ let mv = mk(+ POINTER_FLAG_UPDATE | POINTER_FLAG_INRANGE | POINTER_FLAG_INCONTACT,+ x,+ y,+ );res = res.and(InjectSyntheticPointerInput(dev, &[mv]));}// Release at the end.@@ -481,8 +499,18 @@ fn touch_drag(sx0: i32, sy0: i32, sx1: i32, sy1: i32, steps: usize) -> Result<()},touchFlags: 0,touchMask: 0,- rcContact: RECT { left: x - 2, top: y - 2, right: x + 2, bottom: y + 2 },- rcContactRaw: RECT { left: x - 2, top: y - 2, right: x + 2, bottom: y + 2 },+ rcContact: RECT {+ left: x - 2,+ top: y - 2,+ right: x + 2,+ bottom: y + 2,+ },+ rcContactRaw: RECT {+ left: x - 2,+ top: y - 2,+ right: x + 2,+ bottom: y + 2,+ },orientation: 0,pressure: 512,},@@ -492,7 +520,11 @@ fn touch_drag(sx0: i32, sy0: i32, sx1: i32, sy1: i32, steps: usize) -> Result<()// straight line between them), so a few in-contact frames with a tiny// dwell is plenty — and the shorter the stroke, the briefer the cursor// excursion before we snap it back.- let down = mk(POINTER_FLAG_DOWN | POINTER_FLAG_INRANGE | POINTER_FLAG_INCONTACT, sx0, sy0);+ let down = mk(+ POINTER_FLAG_DOWN | POINTER_FLAG_INRANGE | POINTER_FLAG_INCONTACT,+ sx0,+ sy0,+ );let mut res = InjectSyntheticPointerInput(dev, &[down]);let steps = steps.clamp(1, 3);for i in 1..=steps {@@ -500,7 +532,11 @@ fn touch_drag(sx0: i32, sy0: i32, sx1: i32, sy1: i32, steps: usize) -> Result<()let t = i as f64 / steps as f64;let x = sx0 + ((sx1 - sx0) as f64 * t).round() as i32;let y = sy0 + ((sy1 - sy0) as f64 * t).round() as i32;- let mv = mk(POINTER_FLAG_UPDATE | POINTER_FLAG_INRANGE | POINTER_FLAG_INCONTACT, x, y);+ let mv = mk(+ POINTER_FLAG_UPDATE | POINTER_FLAG_INRANGE | POINTER_FLAG_INCONTACT,+ x,+ y,+ );res = res.and(InjectSyntheticPointerInput(dev, &[mv]));}sleep(Duration::from_millis(2));@@ -579,7 +615,13 @@ pub fn inject_drag_screen(let prev_fg = unsafe { GetForegroundWindow() };// Left drag → touch contact (coordinate-routed). Right/barrel drag has no// touch equivalent, so fall back to a pen (rare).- let stroke = |()| if barrel { pen_drag(sx0, sy0, sx1, sy1, steps, true) } else { touch_drag(sx0, sy0, sx1, sy1, steps) };+ let stroke = |()| {+ if barrel {+ pen_drag(sx0, sy0, sx1, sy1, steps, true)+ } else {+ touch_drag(sx0, sy0, sx1, sy1, steps)+ }+ };// Chromium/GTK: pointer-aware, process injection in the background — hold// non-activatable (no raise), inject, then re-assert the user's foreground.let r = {diff --git a/libs/cua-driver/rust/crates/platform-windows/src/input/mod.rs b/libs/cua-driver/rust/crates/platform-windows/src/input/mod.rsindex 0501db47a1..1f22f7e20d 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/input/mod.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/input/mod.rs@@ -9,33 +9,32 @@//! For clicks, coordinates are window-client-relative (ScreenToClient applied//! if screen coords are given). We pack with MAKELPARAM(x,y).-pub mod mouse;-pub mod keyboard;pub mod delivery;pub mod inject;+pub mod keyboard;+pub mod mouse;+pub(crate) use inject::force_foreground_attached;pub use inject::{inject_click_screen, point_in_window_bounds, ForegroundLockGuard, NoActivateGuard,};-pub(crate) use inject::force_foreground_attached;+pub use keyboard::{+ is_xaml_host_hwnd, post_char, post_key, post_type_text, post_type_text_with_delay,+ send_key_synthesized, send_text_synthesized, wait_for_focused_descendant,+};pub use mouse::{has_chromium_descendant, is_chromium_target_window, post_click, post_click_screen,send_click_synthesized, send_click_synthesized_active_mods, send_click_synthesized_mods,send_wheel_synthesized,};-pub use keyboard::{- is_xaml_host_hwnd, post_char, post_key, post_type_text, post_type_text_with_delay,- send_key_synthesized, send_text_synthesized, wait_for_focused_descendant,-};use windows::Win32::Foundation::{CloseHandle, HANDLE, HWND};use windows::Win32::Security::{- GetSidSubAuthority, GetSidSubAuthorityCount, GetTokenInformation,- TokenIntegrityLevel, TOKEN_MANDATORY_LABEL, TOKEN_QUERY,+ GetSidSubAuthority, GetSidSubAuthorityCount, GetTokenInformation, TokenIntegrityLevel,+ TOKEN_MANDATORY_LABEL, TOKEN_QUERY,};use windows::Win32::System::Threading::{- GetCurrentProcess, OpenProcess, OpenProcessToken,- PROCESS_QUERY_LIMITED_INFORMATION,+ GetCurrentProcess, OpenProcess, OpenProcessToken, PROCESS_QUERY_LIMITED_INFORMATION,};use windows::Win32::UI::WindowsAndMessaging::GetWindowThreadProcessId;@@ -43,22 +42,22 @@ use windows::Win32::UI::WindowsAndMessaging::GetWindowThreadProcessId;/// https://learn.microsoft.com/en-us/windows/win32/secauthz/mandatory-integrity-control#[allow(dead_code)]mod il {- pub const UNTRUSTED: u32 = 0x0000;- pub const LOW: u32 = 0x1000;- pub const MEDIUM: u32 = 0x2000;+ pub const UNTRUSTED: u32 = 0x0000;+ pub const LOW: u32 = 0x1000;+ pub const MEDIUM: u32 = 0x2000;pub const MEDIUM_PLUS: u32 = 0x2100;- pub const HIGH: u32 = 0x3000;- pub const SYSTEM: u32 = 0x4000;+ pub const HIGH: u32 = 0x3000;+ pub const SYSTEM: u32 = 0x4000;}fn il_name(rid: u32) -> &'static str {match rid {- il::UNTRUSTED => "Untrusted",- il::LOW => "Low",- il::MEDIUM => "Medium",+ il::UNTRUSTED => "Untrusted",+ il::LOW => "Low",+ il::MEDIUM => "Medium",il::MEDIUM_PLUS => "Medium+",- il::HIGH => "High",- il::SYSTEM => "System",+ il::HIGH => "High",+ il::SYSTEM => "System",_ => "unknown",}}@@ -133,7 +132,8 @@ pub fn post_message_blocked_by_uipi(hwnd: u64) -> Option<String> {return None;}let own = unsafe { process_integrity_rid(GetCurrentProcess()) }?;- let target_handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) }.ok()?;+ let target_handle =+ unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) }.ok()?;let target = unsafe { process_integrity_rid(target_handle) };let _ = unsafe { CloseHandle(target_handle) };let target = target?;diff --git a/libs/cua-driver/rust/crates/platform-windows/src/input/mouse.rs b/libs/cua-driver/rust/crates/platform-windows/src/input/mouse.rsindex 320c528238..6b9aec6c7d 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/input/mouse.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/input/mouse.rs@@ -4,26 +4,25 @@//! (via ChildWindowFromPointEx), so the message never reaches the top-level//! chrome that would call SetForegroundWindow in response to WM_LBUTTONDOWN.-use anyhow::{Result, bail};+use anyhow::{bail, Result};use std::thread::sleep;use std::time::Duration;use windows::Win32::Foundation::{HWND, LPARAM, POINT, WPARAM};use windows::Win32::Graphics::Gdi::{ClientToScreen, ScreenToClient};use windows::Win32::UI::Input::KeyboardAndMouse::{- INPUT, INPUT_0, INPUT_MOUSE, MOUSEEVENTF_ABSOLUTE, MOUSEEVENTF_HWHEEL, MOUSEEVENTF_LEFTDOWN,- MOUSEEVENTF_LEFTUP, MOUSEEVENTF_MIDDLEDOWN, MOUSEEVENTF_MIDDLEUP, MOUSEEVENTF_MOVE,- MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP, MOUSEEVENTF_VIRTUALDESK, MOUSEEVENTF_WHEEL,- MOUSEINPUT, SendInput,+ SendInput, INPUT, INPUT_0, INPUT_MOUSE, MOUSEEVENTF_ABSOLUTE, MOUSEEVENTF_HWHEEL,+ MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP, MOUSEEVENTF_MIDDLEDOWN, MOUSEEVENTF_MIDDLEUP,+ MOUSEEVENTF_MOVE, MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP, MOUSEEVENTF_VIRTUALDESK,+ MOUSEEVENTF_WHEEL, MOUSEINPUT,};use windows::Win32::UI::WindowsAndMessaging::{ChildWindowFromPointEx, GetAncestor, GetClassLongPtrW, GetCursorPos, GetForegroundWindow,GetSystemMetrics, GetWindowLongPtrW, PostMessageW, SetCursorPos, SetWindowPos, CS_DBLCLKS,- CWP_SKIPDISABLED, CWP_SKIPINVISIBLE, GA_ROOT, GCL_STYLE,- CWP_SKIPTRANSPARENT, GWL_EXSTYLE, HWND_NOTOPMOST, HWND_TOP, HWND_TOPMOST,- SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SWP_NOACTIVATE,- SWP_NOMOVE, SWP_NOSIZE, WM_LBUTTONDBLCLK, WM_LBUTTONDOWN, WM_LBUTTONUP,- WM_MBUTTONDBLCLK, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MOUSEMOVE, WM_RBUTTONDBLCLK,- WM_RBUTTONDOWN, WM_RBUTTONUP, WS_EX_TOPMOST,+ CWP_SKIPDISABLED, CWP_SKIPINVISIBLE, CWP_SKIPTRANSPARENT, GA_ROOT, GCL_STYLE, GWL_EXSTYLE,+ HWND_NOTOPMOST, HWND_TOP, HWND_TOPMOST, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN,+ SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, WM_LBUTTONDBLCLK,+ WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDBLCLK, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MOUSEMOVE,+ WM_RBUTTONDBLCLK, WM_RBUTTONDOWN, WM_RBUTTONUP, WS_EX_TOPMOST,};const MK_LBUTTON: u32 = 0x0001;@@ -49,10 +48,13 @@ fn deepest_child(root: HWND, screen_pt: POINT) -> (HWND, POINT) {let mut current = root;for _ in 0..16 {let mut client = screen_pt;- unsafe { let _ = ScreenToClient(current, &mut client); }+ unsafe {+ let _ = ScreenToClient(current, &mut client);+ }let child = unsafe {ChildWindowFromPointEx(- current, client,+ current,+ client,CWP_SKIPINVISIBLE | CWP_SKIPDISABLED | CWP_SKIPTRANSPARENT,)};@@ -69,7 +71,9 @@ fn deepest_child(root: HWND, screen_pt: POINT) -> (HWND, POINT) {}// Return child-local client coordinates for `current`.let mut client = screen_pt;- unsafe { let _ = ScreenToClient(current, &mut client); }+ unsafe {+ let _ = ScreenToClient(current, &mut client);+ }(current, client)}@@ -82,7 +86,9 @@ pub fn post_click(root: u64, x: i32, y: i32, count: usize, button: &str) -> Resu// Convert root-local client → screen.let mut screen_pt = POINT { x, y };- unsafe { let _ = ClientToScreen(root_hwnd, &mut screen_pt); }+ unsafe {+ let _ = ClientToScreen(root_hwnd, &mut screen_pt);+ }// Find deepest child and its local client coordinates.let (target, client) = deepest_child(root_hwnd, screen_pt);@@ -110,23 +116,21 @@ fn post_click_on(hwnd: HWND, x: i32, y: i32, count: usize, button: &str) -> Resulet (down_msg, double_msg, up_msg, mk_flag) = match button {"right" => (WM_RBUTTONDOWN, WM_RBUTTONDBLCLK, WM_RBUTTONUP, MK_RBUTTON),- "middle" => (- WM_MBUTTONDOWN,- WM_MBUTTONDBLCLK,- WM_MBUTTONUP,- MK_MBUTTON,- ),+ "middle" => (WM_MBUTTONDOWN, WM_MBUTTONDBLCLK, WM_MBUTTONUP, MK_MBUTTON),_ => (WM_LBUTTONDOWN, WM_LBUTTONDBLCLK, WM_LBUTTONUP, MK_LBUTTON),};- let lparam = make_lparam(x, y);- let wdown = WPARAM(mk_flag as usize);- let wup = WPARAM(0);- let wants_double =- unsafe { (GetClassLongPtrW(hwnd, GCL_STYLE) as u32 & CS_DBLCLKS.0) != 0 };+ let lparam = make_lparam(x, y);+ let wdown = WPARAM(mk_flag as usize);+ let wup = WPARAM(0);+ let wants_double = unsafe { (GetClassLongPtrW(hwnd, GCL_STYLE) as u32 & CS_DBLCLKS.0) != 0 };let prev_fg = unsafe { GetForegroundWindow() };let target_root = unsafe {let root = GetAncestor(hwnd, GA_ROOT);- if root.0.is_null() { hwnd } else { root }+ if root.0.is_null() {+ hwnd+ } else {+ root+ }};// Posted pointer messages are normally non-activating, but WebView hosts can@@ -150,10 +154,7 @@ fn post_click_on(hwnd: HWND, x: i32, y: i32, count: usize, button: &str) -> Resu}sleep(Duration::from_millis(50));unsafe {- if !prev_fg.0.is_null()- && prev_fg != target_root- && GetForegroundWindow() == target_root- {+ if !prev_fg.0.is_null() && prev_fg != target_root && GetForegroundWindow() == target_root {crate::input::force_foreground_attached(prev_fg);sleep(Duration::from_millis(12));crate::input::force_foreground_attached(prev_fg);@@ -177,13 +178,17 @@ pub fn post_drag() -> Result<()> {let root = HWND(hwnd as *mut _);let (down_msg, up_msg, mk_flag) = match button {- "right" => (WM_RBUTTONDOWN, WM_RBUTTONUP, MK_RBUTTON),+ "right" => (WM_RBUTTONDOWN, WM_RBUTTONUP, MK_RBUTTON),"middle" => (WM_MBUTTONDOWN, WM_MBUTTONUP, MK_MBUTTON),- _ => (WM_LBUTTONDOWN, WM_LBUTTONUP, MK_LBUTTON),+ _ => (WM_LBUTTONDOWN, WM_LBUTTONUP, MK_LBUTTON),};let wparam = WPARAM(mk_flag as usize);let steps = steps.max(1);- let step_delay_ms = if steps > 1 { duration_ms / steps as u64 } else { duration_ms };+ let step_delay_ms = if steps > 1 {+ duration_ms / steps as u64+ } else {+ duration_ms+ };unsafe {PostMessageW(root, down_msg, wparam, make_lparam(from_x, from_y))?;@@ -229,23 +234,40 @@ pub fn post_drag_screen(button: &str,) -> Result<()> {let root_hwnd = HWND(root as *mut _);- let (target, c_from) = deepest_child(root_hwnd, POINT { x: sx_from, y: sy_from });+ let (target, c_from) = deepest_child(+ root_hwnd,+ POINT {+ x: sx_from,+ y: sy_from,+ },+ );let mut c_to = POINT { x: sx_to, y: sy_to };- unsafe { let _ = ScreenToClient(target, &mut c_to); }+ unsafe {+ let _ = ScreenToClient(target, &mut c_to);+ }if let Some(msg) = crate::input::post_message_blocked_by_uipi(target.0 as u64) {anyhow::bail!(msg);}let (down_msg, up_msg, mk_flag) = match button {- "right" => (WM_RBUTTONDOWN, WM_RBUTTONUP, MK_RBUTTON),+ "right" => (WM_RBUTTONDOWN, WM_RBUTTONUP, MK_RBUTTON),"middle" => (WM_MBUTTONDOWN, WM_MBUTTONUP, MK_MBUTTON),- _ => (WM_LBUTTONDOWN, WM_LBUTTONUP, MK_LBUTTON),+ _ => (WM_LBUTTONDOWN, WM_LBUTTONUP, MK_LBUTTON),};let wparam = WPARAM(mk_flag as usize);let steps = steps.max(1);- let step_delay_ms = if steps > 1 { duration_ms / steps as u64 } else { duration_ms };+ let step_delay_ms = if steps > 1 {+ duration_ms / steps as u64+ } else {+ duration_ms+ };unsafe {// Pre-drag MOUSEMOVE (wParam=0, no buttons down yet) then DOWN at from.- PostMessageW(target, WM_MOUSEMOVE, WPARAM(0), make_lparam(c_from.x, c_from.y))?;+ PostMessageW(+ target,+ WM_MOUSEMOVE,+ WPARAM(0),+ make_lparam(c_from.x, c_from.y),+ )?;PostMessageW(target, down_msg, wparam, make_lparam(c_from.x, c_from.y))?;}sleep(Duration::from_millis(CLICK_DELAY_MS));@@ -253,7 +275,9 @@ pub fn post_drag_screen(let t = i as f64 / steps as f64;let ix = c_from.x + ((c_to.x - c_from.x) as f64 * t).round() as i32;let iy = c_from.y + ((c_to.y - c_from.y) as f64 * t).round() as i32;- unsafe { PostMessageW(target, WM_MOUSEMOVE, wparam, make_lparam(ix, iy))?; }+ unsafe {+ PostMessageW(target, WM_MOUSEMOVE, wparam, make_lparam(ix, iy))?;+ }if step_delay_ms > 0 {sleep(Duration::from_millis(step_delay_ms));}@@ -289,8 +313,8 @@ fn make_lparam(x: i32, y: i32) -> LPARAM {let clamp = |v: i32| v.clamp(i16::MIN as i32, i16::MAX as i32);let cx = clamp(x);let cy = clamp(y);- let packed = crate::lparam::pack_xy(cx, cy)- .expect("clamped values always fit in i16 range");+ let packed =+ crate::lparam::pack_xy(cx, cy).expect("clamped values always fit in i16 range");LPARAM(packed as isize)}}@@ -463,9 +487,9 @@ fn send_click_synthesized_mods_impl(}let (down_flag, up_flag) = match button {- "right" => (MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP),+ "right" => (MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP),"middle" => (MOUSEEVENTF_MIDDLEDOWN, MOUSEEVENTF_MIDDLEUP),- _ => (MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP),+ _ => (MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP),};// Convert screen pixel coords to normalized absolute coords spanning the@@ -510,9 +534,12 @@ fn send_click_synthesized_mods_impl(r#type: INPUT_MOUSE,Anonymous: INPUT_0 {mi: MOUSEINPUT {- dx: 0, dy: 0, mouseData: 0,+ dx: 0,+ dy: 0,+ mouseData: 0,dwFlags: down_flag,- time: 0, dwExtraInfo: 0,+ time: 0,+ dwExtraInfo: 0,},},};@@ -520,9 +547,12 @@ fn send_click_synthesized_mods_impl(r#type: INPUT_MOUSE,Anonymous: INPUT_0 {mi: MOUSEINPUT {- dx: 0, dy: 0, mouseData: 0,+ dx: 0,+ dy: 0,+ mouseData: 0,dwFlags: up_flag,- time: 0, dwExtraInfo: 0,+ time: 0,+ dwExtraInfo: 0,},},};@@ -545,8 +575,7 @@ fn send_click_synthesized_mods_impl(// foreground still needs *real* focus; only pointer can be z-routed.)// Capture whether the target was ALREADY always-on-top so we don't strip// that state on restore — only demote below if WE promoted it.- let was_topmost =- (GetWindowLongPtrW(target, GWL_EXSTYLE) as u32) & WS_EX_TOPMOST.0 != 0;+ let was_topmost = (GetWindowLongPtrW(target, GWL_EXSTYLE) as u32) & WS_EX_TOPMOST.0 != 0;let foreground_attach_failed = activate && !crate::input::force_foreground_attached(target);let noactivate = (!activate).then(|| crate::input::NoActivateGuard::arm(target));if !activate || foreground_attach_failed {@@ -601,11 +630,27 @@ fn send_click_synthesized_mods_impl(// messages are still being dispatched.sleep(Duration::from_millis(if activate { 120 } else { 40 }));if !was_topmost && (!activate || foreground_attach_failed) {- let _ = SetWindowPos(target, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);+ let _ = SetWindowPos(+ target,+ HWND_NOTOPMOST,+ 0,+ 0,+ 0,+ 0,+ SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE,+ );}if !activate {if !prev_fg.0.is_null() && prev_fg != target {- let _ = SetWindowPos(prev_fg, HWND_TOP, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);+ let _ = SetWindowPos(+ prev_fg,+ HWND_TOP,+ 0,+ 0,+ 0,+ 0,+ SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE,+ );}let _ = SetCursorPos(prev_cursor.x, prev_cursor.y);}@@ -645,8 +690,10 @@ fn send_click_synthesized_mods_impl(/// for reliable operation.pub fn send_drag_synthesized(target: u64,- sx_from: i32, sy_from: i32,- sx_to: i32, sy_to: i32,+ sx_from: i32,+ sy_from: i32,+ sx_to: i32,+ sy_to: i32,duration_ms: u64,steps: usize,button: &str,@@ -660,9 +707,9 @@ pub fn send_drag_synthesized(}let (down_flag, up_flag) = match button {- "right" => (MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP),+ "right" => (MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP),"middle" => (MOUSEEVENTF_MIDDLEDOWN, MOUSEEVENTF_MIDDLEUP),- _ => (MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP),+ _ => (MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP),};let (vd_x, vd_y, vd_w, vd_h) = unsafe {@@ -682,15 +729,22 @@ pub fn send_drag_synthesized(r#type: INPUT_MOUSE,Anonymous: INPUT_0 {mi: MOUSEINPUT {- dx, dy, mouseData: 0,+ dx,+ dy,+ mouseData: 0,dwFlags: flags | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK,- time: 0, dwExtraInfo: 0,+ time: 0,+ dwExtraInfo: 0,},},};let steps = steps.max(1);- let step_delay_ms = if steps > 1 { duration_ms / steps as u64 } else { 0 };+ let step_delay_ms = if steps > 1 {+ duration_ms / steps as u64+ } else {+ 0+ };unsafe {let prev_fg = GetForegroundWindow();@@ -704,9 +758,16 @@ pub fn send_drag_synthesized(let _noact = crate::input::NoActivateGuard::arm(target);// Capture whether the target was ALREADY always-on-top so we only demote// below if WE promoted it (else we'd strip a legitimate topmost window).- let was_topmost =- (GetWindowLongPtrW(target, GWL_EXSTYLE) as u32) & WS_EX_TOPMOST.0 != 0;- let _ = SetWindowPos(target, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);+ let was_topmost = (GetWindowLongPtrW(target, GWL_EXSTYLE) as u32) & WS_EX_TOPMOST.0 != 0;+ let _ = SetWindowPos(+ target,+ HWND_TOPMOST,+ 0,+ 0,+ 0,+ 0,+ SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE,+ );// 1. Move + press at the start of the drag.let (nfx, nfy) = norm(sx_from, sy_from);@@ -718,13 +779,32 @@ pub fn send_drag_synthesized(let sent = SendInput(&prelude, std::mem::size_of::<INPUT>() as i32);if sent as usize != prelude.len() {if !was_topmost {- let _ = SetWindowPos(target, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);+ let _ = SetWindowPos(+ target,+ HWND_NOTOPMOST,+ 0,+ 0,+ 0,+ 0,+ SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE,+ );}if !prev_fg.0.is_null() && prev_fg != target {- let _ = SetWindowPos(prev_fg, HWND_TOP, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);+ let _ = SetWindowPos(+ prev_fg,+ HWND_TOP,+ 0,+ 0,+ 0,+ 0,+ SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE,+ );}let _ = SetCursorPos(prev_cursor.x, prev_cursor.y);- bail!("SendInput drag-prelude inserted {sent}/{} events", prelude.len());+ bail!(+ "SendInput drag-prelude inserted {sent}/{} events",+ prelude.len()+ );}// 2. Interpolate the path. SetCursorPos + MOUSEEVENTF_MOVE in lockstep@@ -753,10 +833,26 @@ pub fn send_drag_synthesized(// window — no activation) and the cursor.sleep(Duration::from_millis(40));if !was_topmost {- let _ = SetWindowPos(target, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);+ let _ = SetWindowPos(+ target,+ HWND_NOTOPMOST,+ 0,+ 0,+ 0,+ 0,+ SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE,+ );}if !prev_fg.0.is_null() && prev_fg != target {- let _ = SetWindowPos(prev_fg, HWND_TOP, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);+ let _ = SetWindowPos(+ prev_fg,+ HWND_TOP,+ 0,+ 0,+ 0,+ 0,+ SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE,+ );}let _ = SetCursorPos(prev_cursor.x, prev_cursor.y);drop(_noact);@@ -795,7 +891,11 @@ fn wheel_mouse_data(ticks: i32) -> u32 {/// delivery follows the cursor, so positioning the cursor is sufficient. The/// cursor is restored to its previous position afterward.pub fn send_wheel_synthesized(sx: i32, sy: i32, ticks: i32, horizontal: bool) -> Result<()> {- let flag = if horizontal { MOUSEEVENTF_HWHEEL } else { MOUSEEVENTF_WHEEL };+ let flag = if horizontal {+ MOUSEEVENTF_HWHEEL+ } else {+ MOUSEEVENTF_WHEEL+ };let mouse_data = wheel_mouse_data(ticks);let wheel_input = INPUT {diff --git a/libs/cua-driver/rust/crates/platform-windows/src/launch_uwp.rs b/libs/cua-driver/rust/crates/platform-windows/src/launch_uwp.rsindex c8d3dac908..53f8d65a6e 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/launch_uwp.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/launch_uwp.rs@@ -43,8 +43,8 @@ use windows::Win32::System::Com::{};use windows::Win32::UI::Shell::PropertiesSystem::PROPERTYKEY;use windows::Win32::UI::Shell::{- ApplicationActivationManager, IApplicationActivationManager, IEnumShellItems, IShellItem,- IShellItem2, SHCreateItemFromParsingName, AO_NONE, BHID_EnumItems, SIGDN_NORMALDISPLAY,+ ApplicationActivationManager, BHID_EnumItems, IApplicationActivationManager, IEnumShellItems,+ IShellItem, IShellItem2, SHCreateItemFromParsingName, AO_NONE, SIGDN_NORMALDISPLAY,};use windows::Win32::UI::WindowsAndMessaging::GetForegroundWindow;@@ -108,9 +108,8 @@ pub fn launch_uwp(aumid: &str, args: &str) -> windows::core::Result<u32> {// CoCreateInstance call will surface a clear error.let _ = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };- let manager: IApplicationActivationManager = unsafe {- CoCreateInstance(&ApplicationActivationManager, None, CLSCTX_LOCAL_SERVER)?- };+ let manager: IApplicationActivationManager =+ unsafe { CoCreateInstance(&ApplicationActivationManager, None, CLSCTX_LOCAL_SERVER)? };let aumid_h = HSTRING::from(aumid);let args_h = HSTRING::from(args);@@ -120,11 +119,7 @@ pub fn launch_uwp(aumid: &str, args: &str) -> windows::core::Result<u32> {let prior_foreground = unsafe { GetForegroundWindow() };let pid = unsafe {- manager.ActivateApplication(- PCWSTR(aumid_h.as_ptr()),- PCWSTR(args_h.as_ptr()),- AO_NONE,- )?+ manager.ActivateApplication(PCWSTR(aumid_h.as_ptr()), PCWSTR(args_h.as_ptr()), AO_NONE)?};// Restore the prior foreground window. AppX activation has already@@ -343,14 +338,12 @@ fn enumerate_apps_folder() -> windows::core::Result<Vec<AppsFolderEntry>> {// folder that backs the Start Menu's "all apps" list. It enumerates// every activatable app on the system, packaged or not.let folder_path = HSTRING::from("shell:AppsFolder");- let apps_folder: IShellItem = unsafe {- SHCreateItemFromParsingName(PCWSTR(folder_path.as_ptr()), None::<&IBindCtx>)?- };+ let apps_folder: IShellItem =+ unsafe { SHCreateItemFromParsingName(PCWSTR(folder_path.as_ptr()), None::<&IBindCtx>)? };// Bind to the `BHID_EnumItems` handler to iterate children.- let enumerator: IEnumShellItems = unsafe {- apps_folder.BindToHandler(None::<&IBindCtx>, &BHID_EnumItems)?- };+ let enumerator: IEnumShellItems =+ unsafe { apps_folder.BindToHandler(None::<&IBindCtx>, &BHID_EnumItems)? };let mut entries = Vec::with_capacity(256);loop {@@ -360,13 +353,13 @@ fn enumerate_apps_folder() -> windows::core::Result<Vec<AppsFolderEntry>> {// — the documented sentinel for "iterator exhausted".let mut slot: [Option<IShellItem>; 1] = [None];let mut fetched: u32 = 0;- let _ = unsafe {- enumerator.Next(&mut slot, Some(&mut fetched as *mut u32))- };+ let _ = unsafe { enumerator.Next(&mut slot, Some(&mut fetched as *mut u32)) };if fetched == 0 {break;}- let Some(item) = slot[0].take() else { break; };+ let Some(item) = slot[0].take() else {+ break;+ };// Cast to IShellItem2 to access PKEY_AppUserModel_ID; if the// entry doesn't expose AAM (rare; pure-Win32 shortcut), skip.@@ -392,7 +385,11 @@ fn enumerate_apps_folder() -> windows::core::Result<Vec<AppsFolderEntry>> {}let lowercase_display_name = display_name.to_lowercase();- entries.push(AppsFolderEntry { display_name, lowercase_display_name, aumid });+ entries.push(AppsFolderEntry {+ display_name,+ lowercase_display_name,+ aumid,+ });}Ok(entries)diff --git a/libs/cua-driver/rust/crates/platform-windows/src/lib.rs b/libs/cua-driver/rust/crates/platform-windows/src/lib.rsindex 06164cf7cc..d328b02956 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/lib.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/lib.rs@@ -18,13 +18,13 @@use cua_driver_core::tool::ToolRegistry;-pub mod tools;-pub mod overlay;pub mod diagnostics;pub mod health_report;-pub mod recording_hooks;+pub mod overlay;pub mod pip;+pub mod recording_hooks;pub mod terminal;+pub mod tools;// Cross-platform: pure math for MOUSEEVENTF_VIRTUALDESK absolute-coord// normalization. Lives outside the Windows-only `input` module so itsdiff --git a/libs/cua-driver/rust/crates/platform-windows/src/lparam.rs b/libs/cua-driver/rust/crates/platform-windows/src/lparam.rsindex 0042d18d0a..3a97749a16 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/lparam.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/lparam.rs@@ -145,8 +145,8 @@ mod tests {(-1198, 292),(-1795, 383),(38, 40),- (-39, 383), // representative post-ScreenToClient coord on the- // secondary-monitor window edge+ (-39, 383), // representative post-ScreenToClient coord on the+ // secondary-monitor window edge]);}@@ -235,8 +235,8 @@ mod tests {for sx in window_origin_x..(window_origin_x + 1920) {let local_x = sx - window_origin_x; // 0..1920 — well inside i16let local_y = 383 - window_origin_y;- let lp = pack_xy(local_x, local_y)- .expect("post-ScreenToClient coords always fit in i16");+ let lp =+ pack_xy(local_x, local_y).expect("post-ScreenToClient coords always fit in i16");let rx = unpack_x(lp);if let Some(p) = prev {assert_eq!(diff --git a/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs b/libs/cua-driver/rust/crates/platform-windows/src/overlay.rsindex c1232af4d2..f51e8ee270 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs@@ -293,7 +293,11 @@ pub fn current_position(key: &str) -> (f64, f64) {RENDER.lock().ok()- .and_then(|g| g.as_ref().and_then(|m| m.cursors.get(key)).map(|rs| rs.core.pos))+ .and_then(|g| {+ g.as_ref()+ .and_then(|m| m.cursors.get(key))+ .map(|rs| rs.core.pos)+ }).unwrap_or((-200.0, -200.0))}@@ -304,7 +308,9 @@ pub fn current_position(key: &str) -> (f64, f64) {/// seed was applied. Mirrors `platform_macos::cursor::overlay::seed_start_*`.fn seed_start_if_sentinel(key: &CursorKey, target_x: f64, target_y: f64) -> bool {let mut guard = RENDER.lock().unwrap();- let Some(map) = guard.as_mut() else { return false };+ let Some(map) = guard.as_mut() else {+ return false;+ };seed_start_in_map(map, key, target_x, target_y)}@@ -491,10 +497,10 @@ fn render_map_needs_frame_tick(map: &RenderMap) -> bool {#[cfg(target_os = "windows")]fn run_overlay_thread(cfg: CursorConfig, rx: std::sync::mpsc::Receiver<OverlayMsg>) {+ use windows::core::PCWSTR;use windows::Win32::Media::timeBeginPeriod;use windows::Win32::System::LibraryLoader::GetModuleHandleW;use windows::Win32::UI::WindowsAndMessaging::*;- use windows::core::PCWSTR;// Raise multimedia timer resolution to 1ms so SetTimer can deliver// WM_TIMER messages at ~8ms intervals (default is ~15ms).@@ -662,7 +668,9 @@ unsafe extern "system" fn wnd_proc(static FPS_PATH: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();static FPS_FRAMES: AtomicU64 = AtomicU64::new(0);static FPS_LAST: AtomicU64 = AtomicU64::new(0);- if let Some(path) = FPS_PATH.get_or_init(|| std::env::var("CUA_DRIVER_RS_OVERLAY_FPS_FILE").ok()) {+ if let Some(path) =+ FPS_PATH.get_or_init(|| std::env::var("CUA_DRIVER_RS_OVERLAY_FPS_FILE").ok())+ {let n = FPS_FRAMES.fetch_add(1, Relaxed) + 1;let last = FPS_LAST.load(Relaxed);if last == 0 {@@ -670,11 +678,22 @@ unsafe extern "system" fn wnd_proc(} else if now_ms.wrapping_sub(last) >= 1000 {let secs = (now_ms - last) as f64 / 1000.0;let fps = n as f64 / secs.max(1e-3);- let cursors = RENDER.lock().ok()- .and_then(|g| g.as_ref().map(|m| m.cursors.len())).unwrap_or(0);- if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(path) {+ let cursors = RENDER+ .lock()+ .ok()+ .and_then(|g| g.as_ref().map(|m| m.cursors.len()))+ .unwrap_or(0);+ if let Ok(mut f) = std::fs::OpenOptions::new()+ .create(true)+ .append(true)+ .open(path)+ {use std::io::Write;- let _ = writeln!(f, "overlay fps={fps:.1} avg_dt_ms={:.1} cursors={cursors}", secs * 1000.0 / n as f64);+ let _ = writeln!(+ f,+ "overlay fps={fps:.1} avg_dt_ms={:.1} cursors={cursors}",+ secs * 1000.0 / n as f64+ );}FPS_FRAMES.store(0, Relaxed);FPS_LAST.store(now_ms, Relaxed);@@ -837,7 +856,8 @@ unsafe extern "system" fn wnd_proc(} else {TIMER_MS_IDLE};- if TIMER_PERIOD_MS.swap(desired_ms, std::sync::atomic::Ordering::Relaxed) != desired_ms {+ if TIMER_PERIOD_MS.swap(desired_ms, std::sync::atomic::Ordering::Relaxed) != desired_ms+ {unsafe {SetTimer(hwnd, TIMER_ID, desired_ms, None);}@@ -927,7 +947,10 @@ unsafe fn update_layered_window(}let pt_src = POINT { x: 0, y: 0 };- let pt_dst = POINT { x: virt_x, y: virt_y };+ let pt_dst = POINT {+ x: virt_x,+ y: virt_y,+ };let sz = SIZE { cx: w, cy: h };let blend = BLENDFUNCTION {BlendOp: 0, // AC_SRC_OVER@@ -971,10 +994,14 @@ struct WinZOrderEnforcer {unsafe fn topmost_of(ids: &[u64]) -> Option<u64> {use windows::Win32::Foundation::HWND;use windows::Win32::UI::WindowsAndMessaging::{GetTopWindow, GetWindow, GW_HWNDNEXT};- if ids.is_empty() { return None; }+ if ids.is_empty() {+ return None;+ }let mut h = GetTopWindow(None).unwrap_or(HWND(std::ptr::null_mut()));while !h.0.is_null() {- if ids.contains(&(h.0 as u64)) { return Some(h.0 as u64); }+ if ids.contains(&(h.0 as u64)) {+ return Some(h.0 as u64);+ }h = GetWindow(h, GW_HWNDNEXT).unwrap_or(HWND(std::ptr::null_mut()));}ids.first().copied()@@ -991,7 +1018,11 @@ impl ZOrderEnforcer for WinZOrderEnforcer {let pinned_target = target.and_then(|wid| {let h = HWND(wid as *mut _);- if IsWindow(h).as_bool() { Some(h) } else { None }+ if IsWindow(h).as_bool() {+ Some(h)+ } else {+ None+ }});// The overlay must sit JUST above the pinned target window so the@@ -1035,7 +1066,11 @@ impl ZOrderEnforcer for WinZOrderEnforcer {let insert_after = match pinned_target {Some(target) => {let prev = GetWindow(target, GW_HWNDPREV).unwrap_or(HWND(std::ptr::null_mut()));- if !prev.0.is_null() { prev } else { HWND_TOP }+ if !prev.0.is_null() {+ prev+ } else {+ HWND_TOP+ }}None => HWND_TOP,};@@ -1067,7 +1102,10 @@ mod tests {fn empty_map() -> RenderMap {let mut cursors = IndexMap::new();- cursors.insert("default".to_owned(), RenderState::new(CursorConfig::default()));+ cursors.insert(+ "default".to_owned(),+ RenderState::new(CursorConfig::default()),+ );RenderMap {cursors,virt_x: 0,@@ -1084,7 +1122,11 @@ mod tests {fn move_msg(key: &str, x: f64, y: f64) -> OverlayMsg {OverlayMsg::Cmd(KeyedOverlayCommand {key: key.to_owned(),- cmd: OverlayCommand::MoveTo { x, y, end_heading_radians: 0.0 },+ cmd: OverlayCommand::MoveTo {+ x,+ y,+ end_heading_radians: 0.0,+ },})}@@ -1162,8 +1204,14 @@ mod tests {// A late in-flight Cmd for the ended session must be dropped WITHOUT// re-inserting (no get-or-create resurrection).let resolved = apply_msg(&mut map, move_msg("sessA", 99.0, 99.0));- assert!(resolved.is_none(), "ended-session Cmd must be dropped, not resolved");- assert!(!map.cursors.contains_key("sessA"), "tombstone must block resurrection");+ assert!(+ resolved.is_none(),+ "ended-session Cmd must be dropped, not resolved"+ );+ assert!(+ !map.cursors.contains_key("sessA"),+ "tombstone must block resurrection"+ );assert_eq!(map.cursors.len(), 1);}@@ -1182,11 +1230,14 @@ mod tests {#[test]fn seed_moves_sentinel_cursor_on_screen_for_first_action() {let mut map = empty_map(); // 100x100 frame at origin- // No "sessA" cursor exists yet — the seed must get-or-create it.+ // No "sessA" cursor exists yet — the seed must get-or-create it.let seeded = seed_start_in_map(&mut map, &"sessA".to_owned(), 60.0, 60.0);assert!(seeded, "sentinel cursor must be seeded");let pos = map.cursors["sessA"].core.pos;- assert!(pos.0 > -50.0 && pos.1 > -50.0, "seed must be on-screen, got {pos:?}");+ assert!(+ pos.0 > -50.0 && pos.1 > -50.0,+ "seed must be on-screen, got {pos:?}"+ );assert!((pos.0 - 60.0).abs() > 4.0 || (pos.1 - 60.0).abs() > 4.0,"seed must differ from target to produce a visible glide, got {pos:?}"@@ -1200,7 +1251,11 @@ mod tests {map.cursors.get_mut("sessA").unwrap().core.pos = (30.0, 30.0);let seeded_again = seed_start_in_map(&mut map, &"sessA".to_owned(), 80.0, 80.0);assert!(!seeded_again, "on-screen cursor must not be re-seeded");- assert_eq!(map.cursors["sessA"].core.pos, (30.0, 30.0), "pos must be untouched");+ assert_eq!(+ map.cursors["sessA"].core.pos,+ (30.0, 30.0),+ "pos must be untouched"+ );}#[test]@@ -1209,7 +1264,10 @@ mod tests {map.ended.insert("sessA".to_owned());let seeded = seed_start_in_map(&mut map, &"sessA".to_owned(), 60.0, 60.0);assert!(!seeded, "ended session must not be seeded");- assert!(!map.cursors.contains_key("sessA"), "ended session must not be resurrected");+ assert!(+ !map.cursors.contains_key("sessA"),+ "ended session must not be resurrected"+ );}#[test]@@ -1282,6 +1340,9 @@ mod tests {map.last_active = k;assert_eq!(map.last_active.as_deref(), Some("sessA"));apply_msg(&mut map, OverlayMsg::Remove("sessA".to_owned()));- assert_eq!(map.last_active, None, "removing the active cursor must clear last_active");+ assert_eq!(+ map.last_active, None,+ "removing the active cursor must clear last_active"+ );}}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/recording_hooks.rs b/libs/cua-driver/rust/crates/platform-windows/src/recording_hooks.rsindex 4a94156bad..f6e4cbb5a9 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/recording_hooks.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/recording_hooks.rs@@ -64,10 +64,7 @@ pub fn resolve_window_for_recording(window_id: Option<u64>, pid: Option<i64>) ->}#[cfg(target_os = "windows")]-pub fn screenshot_for_recording(- window_id: Option<u64>,- pid: Option<i64>,-) -> ScreenshotCapture {+pub fn screenshot_for_recording(window_id: Option<u64>, pid: Option<i64>) -> ScreenshotCapture {if window_id.is_none() && pid.is_none() {return crate::capture::screenshot_display_bytes().map(ScreenshotCapture::captured)@@ -127,10 +124,7 @@ pub fn resolve_window_for_recording(_window_id: Option<u64>, _pid: Option<i64>)None}#[cfg(not(target_os = "windows"))]-pub fn screenshot_for_recording(- _window_id: Option<u64>,- _pid: Option<i64>,-) -> ScreenshotCapture {+pub fn screenshot_for_recording(_window_id: Option<u64>, _pid: Option<i64>) -> ScreenshotCapture {ScreenshotCapture::unavailable("unsupported_platform")}#[cfg(not(target_os = "windows"))]diff --git a/libs/cua-driver/rust/crates/platform-windows/src/terminal.rs b/libs/cua-driver/rust/crates/platform-windows/src/terminal.rsindex e23c6525a8..24f61c5cb4 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/terminal.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/terminal.rs@@ -76,7 +76,7 @@ mod tests {// Real-world class names observed in the wild.for name in ["CASCADIA_HOSTING_WINDOW_CLASS",- "CASCADIA_HOSTING_WINDOW_CLASS_0", // suffixed instance+ "CASCADIA_HOSTING_WINDOW_CLASS_0", // suffixed instance"mintty","mintty_window","ConsoleWindowClass",@@ -97,8 +97,8 @@ mod tests {"Chrome_WidgetWin_1","Notepad","WordPadClass",- "HwndWrapper[default;;abc-123]", // WPF- "gdkWindowToplevel", // GTK+ "HwndWrapper[default;;abc-123]", // WPF+ "gdkWindowToplevel", // GTK"Edit","Static","",diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/page.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/page.rsindex 4b4ee0f156..7d184c7d77 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/page.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/page.rs@@ -36,13 +36,12 @@ use windows::Win32::System::Com::{CoCreateInstance, CoInitializeEx, CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED,};use windows::Win32::UI::Accessibility::{- UIA_ComboBoxControlTypeId,CUIAutomation, IUIAutomation, IUIAutomationElement, IUIAutomationTextPattern,- TreeScope_Subtree, UIA_ButtonControlTypeId, UIA_CONTROLTYPE_ID, UIA_ControlTypePropertyId,- UIA_DocumentControlTypeId, UIA_EditControlTypeId, UIA_HeaderControlTypeId,- UIA_HyperlinkControlTypeId, UIA_ImageControlTypeId, UIA_ListItemControlTypeId,- UIA_NamePropertyId, UIA_PaneControlTypeId, UIA_TextControlTypeId, UIA_TextPatternId,- UIA_ValueValuePropertyId,+ TreeScope_Subtree, UIA_ButtonControlTypeId, UIA_ComboBoxControlTypeId,+ UIA_ControlTypePropertyId, UIA_DocumentControlTypeId, UIA_EditControlTypeId,+ UIA_HeaderControlTypeId, UIA_HyperlinkControlTypeId, UIA_ImageControlTypeId,+ UIA_ListItemControlTypeId, UIA_NamePropertyId, UIA_PaneControlTypeId, UIA_TextControlTypeId,+ UIA_TextPatternId, UIA_ValueValuePropertyId, UIA_CONTROLTYPE_ID,};pub struct WindowsPageBackend;@@ -140,19 +139,20 @@ impl PageBackend for WindowsPageBackend {if cdp_port.is_none() && target_url_contains.is_none() {return self.execute_javascript(pid, window_id, javascript).await;}- let port = cdp_port.or_else(|| {- std::env::var("CUA_DRIVER_CDP_PORT")- .ok()- .and_then(|value| value.parse::<u16>().ok())- }).ok_or_else(|| anyhow::anyhow!(+ let port = cdp_port+ .or_else(|| {+ std::env::var("CUA_DRIVER_CDP_PORT")+ .ok()+ .and_then(|value| value.parse::<u16>().ok())+ })+ .ok_or_else(|| {+ anyhow::anyhow!("targeted execute_javascript on Windows requires cdp_port or CUA_DRIVER_CDP_PORT"- ))?;- let result = cua_driver_core::cdp::evaluate_targeted(- port,- javascript,- true,- target_url_contains,- ).await?;+ )+ })?;+ let result =+ cua_driver_core::cdp::evaluate_targeted(port, javascript, true, target_url_contains)+ .await?;Ok(format!("cdp.runtime.evaluate.user_gesture: {result}"))}@@ -204,16 +204,18 @@ impl PageBackend for WindowsPageBackend {// only fires on a hard parse error. Inspect the parsed value and// re-decode when it's a String.let parsed: serde_json::Value = {- let first = serde_json::from_str::<serde_json::Value>(&probe_json)- .map_err(|e| anyhow::anyhow!(+ let first = serde_json::from_str::<serde_json::Value>(&probe_json).map_err(|e| {+ anyhow::anyhow!("click_element: could not parse coord JSON from probe (raw: {probe_raw:?}): {e}"- ))?;+ )+ })?;match first {- serde_json::Value::String(inner) => serde_json::from_str(&inner)- .map_err(|e| anyhow::anyhow!(+ serde_json::Value::String(inner) => serde_json::from_str(&inner).map_err(|e| {+ anyhow::anyhow!("click_element: inner JSON parse failed for double-encoded probe \response (raw: {probe_raw:?}): {e}"- ))?,+ )+ })?,other => other,}};@@ -228,17 +230,24 @@ impl PageBackend for WindowsPageBackend {// genuinely optional on the JS side (older webviews / unusual// contexts may not expose it).let require = |key: &str| -> Result<f64, anyhow::Error> {- parsed.get(key).and_then(|v| v.as_f64()).filter(|f| f.is_finite())- .ok_or_else(|| anyhow::anyhow!(- "click_element: probe JSON missing/invalid required field '{key}' \+ parsed+ .get(key)+ .and_then(|v| v.as_f64())+ .filter(|f| f.is_finite())+ .ok_or_else(|| {+ anyhow::anyhow!(+ "click_element: probe JSON missing/invalid required field '{key}' \(raw: {probe_raw:?}). All four of vx/vy/sx/sy must be finite numbers."- ))+ )+ })};let vx = require("vx")?;let vy = require("vy")?;let sx = require("sx")?;let sy = require("sy")?;- let dpr = parsed.get("dpr").and_then(|v| v.as_f64())+ let dpr = parsed+ .get("dpr")+ .and_then(|v| v.as_f64()).filter(|f| f.is_finite() && *f > 0.0).unwrap_or(1.0);@@ -254,7 +263,11 @@ impl PageBackend for WindowsPageBackend {use windows::Win32::Foundation::HWND;use windows::Win32::UI::WindowsAndMessaging::{GetAncestor, GA_ROOT};let root = unsafe { GetAncestor(HWND(hwnd as *mut _), GA_ROOT) };- let pin_wid = if !root.0.is_null() { root.0 as u64 } else { hwnd };+ let pin_wid = if !root.0.is_null() {+ root.0 as u64+ } else {+ hwnd+ };crate::overlay::send_command_default(cursor_overlay::OverlayCommand::PinAbove(pin_wid));}// The cross-platform `PageBackend::click_element` trait carries no@@ -349,10 +362,7 @@ unsafe fn query_dom_blocking(// Build a UIA condition for the ControlType (if any) and FindAll.let condition = match parsed.control_type {- Some(ct) => automation.CreatePropertyCondition(- UIA_ControlTypePropertyId,- &ct.0.into(),- )?,+ Some(ct) => automation.CreatePropertyCondition(UIA_ControlTypePropertyId, &ct.0.into())?,None => automation.CreateTrueCondition()?,};@@ -369,7 +379,9 @@ unsafe fn query_dom_blocking(// Post-filter by id/class. Skip elements that don't satisfy.if !parsed.id_filter.is_empty() {let aid = read_string(&elem, |e| {- e.CurrentAutomationId().map(|b| b.to_string()).map_err(|e| e.into())+ e.CurrentAutomationId()+ .map(|b| b.to_string())+ .map_err(|e| e.into())});if aid.as_deref().unwrap_or_default() != parsed.id_filter {continue;@@ -388,7 +400,9 @@ unsafe fn query_dom_blocking(let v = match a.as_str() {"name" => Some(name.clone()),"id" => read_string(&elem, |e| {- e.CurrentAutomationId().map(|b| b.to_string()).map_err(|e| e.into())+ e.CurrentAutomationId()+ .map(|b| b.to_string())+ .map_err(|e| e.into())}),"value" => read_value_value(&elem),"href" => {@@ -408,7 +422,11 @@ unsafe fn query_dom_blocking(let line = if attr_parts.is_empty() {format!("- {ct} \"{}\"", escape_attr(&name))} else {- format!("- {ct} \"{}\" [{}]", escape_attr(&name), attr_parts.join(" "))+ format!(+ "- {ct} \"{}\" [{}]",+ escape_attr(&name),+ attr_parts.join(" ")+ )};formatted.push(line);}@@ -502,8 +520,8 @@ unsafe fn walk_text_blocking(root: &IUIAutomationElement) -> String {acc}-unsafe fn create_true_condition_or_fallback() -> Option<windows::Win32::UI::Accessibility::IUIAutomationCondition>-{+unsafe fn create_true_condition_or_fallback(+) -> Option<windows::Win32::UI::Accessibility::IUIAutomationCondition> {let automation: IUIAutomation =CoCreateInstance(&CUIAutomation, None, CLSCTX_INPROC_SERVER).ok()?;automation.CreateTrueCondition().ok()@@ -550,7 +568,9 @@ unsafe fn read_control_type(elem: &IUIAutomationElement) -> Option<String> {}unsafe fn read_value_value(elem: &IUIAutomationElement) -> Option<String> {- let v = elem.GetCurrentPropertyValue(UIA_ValueValuePropertyId).ok()?;+ let v = elem+ .GetCurrentPropertyValue(UIA_ValueValuePropertyId)+ .ok()?;let raw = v.as_raw();if raw.Anonymous.Anonymous.vt != 8 {// VT_BSTR = 8 — anything else (empty, VT_EMPTY=0) means no value.diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/page_bookmark.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/page_bookmark.rsindex 57f91bdccf..921a8cfd20 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/page_bookmark.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/page_bookmark.rs@@ -66,10 +66,10 @@ use windows::Win32::System::Com::{use windows::Win32::UI::Accessibility::{CUIAutomation, IUIAutomation, IUIAutomationElement, IUIAutomationInvokePattern,IUIAutomationValuePattern, TreeScope_Children, TreeScope_Descendants, TreeScope_Subtree,- UIA_ButtonControlTypeId, UIA_ControlTypePropertyId, UIA_EditControlTypeId,- UIA_InvokePatternId, UIA_ListItemControlTypeId, UIA_MenuItemControlTypeId,- UIA_NamePropertyId, UIA_TabItemControlTypeId, UIA_ToolBarControlTypeId,- UIA_ValuePatternId, UIA_WindowControlTypeId,+ UIA_ButtonControlTypeId, UIA_ControlTypePropertyId, UIA_EditControlTypeId, UIA_InvokePatternId,+ UIA_ListItemControlTypeId, UIA_MenuItemControlTypeId, UIA_NamePropertyId,+ UIA_TabItemControlTypeId, UIA_ToolBarControlTypeId, UIA_ValuePatternId,+ UIA_WindowControlTypeId,};use windows::Win32::UI::WindowsAndMessaging::GetWindowThreadProcessId;@@ -108,11 +108,7 @@ mod budget {/// and not summonable, bookmark creation pre-conditions not met, title/// poll exceeds [`budget::TITLE_RESULT`]) returns `Err` so the caller/// can fall back to CDP.-pub async fn try_bookmark_exec(- pid: i32,- window_id: u32,- javascript: &str,-) -> Result<String> {+pub async fn try_bookmark_exec(pid: i32, window_id: u32, javascript: &str) -> Result<String> {if javascript.is_empty() {bail!("javascript expression is empty");}@@ -176,11 +172,7 @@ setTimeout(function(){{ document.title = _orig; }}, 500);\// ── blocking implementation ───────────────────────────────────────────────-unsafe fn try_bookmark_exec_blocking(- pid: i32,- window_id: u32,- javascript: &str,-) -> Result<String> {+unsafe fn try_bookmark_exec_blocking(pid: i32, window_id: u32, javascript: &str) -> Result<String> {let automation = init_uia()?;let hwnd_raw = window_id as u64;@@ -273,9 +265,8 @@ unsafe fn try_bookmark_exec_blocking(// we log at trace level and continue — the brief activation is// unavoidable without forking Chromium, but the dwell time on the// browser is < ~150 ms instead of "until next user action".- let prev_fg_for_invoke = unsafe {- windows::Win32::UI::WindowsAndMessaging::GetForegroundWindow()- };+ let prev_fg_for_invoke =+ unsafe { windows::Win32::UI::WindowsAndMessaging::GetForegroundWindow() };invoke_element(&bookmark).context("InvokePattern.Invoke on bookmark failed")?;// Restore in a tight loop — at this point the bookmark URL is firing// and Chromium is about to activate. Poll for ~600 ms; once we see@@ -283,10 +274,7 @@ unsafe fn try_bookmark_exec_blocking(// (not via tokio::spawn) because we WANT to block the poll-marker// step below until the foreground is restored — otherwise a slow// restore leaves the browser frontmost while we read the title.- restore_foreground_after_browser_activation(- prev_fg_for_invoke,- pid as u32,- );+ restore_foreground_after_browser_activation(prev_fg_for_invoke, pid as u32);// 7) Poll the active tab's title until it starts with CUA: / CUA_ERR:let result = poll_for_marker(&automation, &edge_window, &original_title)?;@@ -331,9 +319,7 @@ unsafe fn root_for_window(let mut actual_pid: u32 = 0;let _ = GetWindowThreadProcessId(hwnd, Some(&mut actual_pid));if actual_pid as i32 != expected_pid {- bail!(- "hwnd 0x{hwnd_raw:x} belongs to pid {actual_pid}, not the expected {expected_pid}"- );+ bail!("hwnd 0x{hwnd_raw:x} belongs to pid {actual_pid}, not the expected {expected_pid}");}automation.ElementFromHandle(hwnd)@@ -350,10 +336,7 @@ unsafe fn find_favorites_bar(// Cheap path: a single Name lookup. Chromium has used "Favorites bar"// as the bar's Name for years across Edge/Chrome.let name_cond = automation- .CreatePropertyCondition(- UIA_NamePropertyId,- &BSTR::from("Favorites bar").into(),- )+ .CreatePropertyCondition(UIA_NamePropertyId, &BSTR::from("Favorites bar").into()).ok()?;if let Ok(bar) = root.FindFirst(TreeScope_Subtree, &name_cond) {return Some(bar);@@ -373,7 +356,9 @@ unsafe fn find_favorites_bar(Err(_) => continue,};if let Some(name) = read_name(&elem) {- if name.eq_ignore_ascii_case("favorites bar") || name.eq_ignore_ascii_case("bookmarks bar") {+ if name.eq_ignore_ascii_case("favorites bar")+ || name.eq_ignore_ascii_case("bookmarks bar")+ {return Some(elem);}}@@ -482,9 +467,8 @@ unsafe fn set_bookmark_url(// popup windows, not children of the bookmark in the UIA tree).// Edge labels this "Edit"; Chrome labels it "Edit..." (and may show// additional context depending on profile state). Match either.- let edit_item =- wait_for_menu_item(automation, &["Edit", "Edit..."], budget::DIALOG_APPEAR)- .context("Edit menu item did not appear after right-click on bookmark")?;+ let edit_item = wait_for_menu_item(automation, &["Edit", "Edit..."], budget::DIALOG_APPEAR)+ .context("Edit menu item did not appear after right-click on bookmark")?;invoke_element(&edit_item).context("InvokePattern.Invoke on Edit menu item failed")?;// The Edit dialog is a top-level UIA Window. Edge 148 names it@@ -565,7 +549,9 @@ unsafe fn wait_for_menu_item(}std::thread::sleep(Duration::from_millis(60));}- Err(anyhow!("MenuItem matching {accepted_names:?} not found within {budget:?}"))+ Err(anyhow!(+ "MenuItem matching {accepted_names:?} not found within {budget:?}"+ ))}unsafe fn wait_for_window(@@ -603,7 +589,9 @@ unsafe fn wait_for_window(}std::thread::sleep(Duration::from_millis(80));}- Err(anyhow!("Window matching {accepted_names:?} not found within {budget:?}"))+ Err(anyhow!(+ "Window matching {accepted_names:?} not found within {budget:?}"+ ))}unsafe fn find_edit_in_dialog(@@ -612,10 +600,7 @@ unsafe fn find_edit_in_dialog(accepted_names: &[&str],) -> Result<IUIAutomationElement> {let cond = automation- .CreatePropertyCondition(- UIA_ControlTypePropertyId,- &(UIA_EditControlTypeId.0).into(),- )+ .CreatePropertyCondition(UIA_ControlTypePropertyId, &(UIA_EditControlTypeId.0).into()).map_err(|e| anyhow!("CreatePropertyCondition(Edit) failed: {e}"))?;let edits = dialog.FindAll(TreeScope_Descendants, &cond)@@ -627,10 +612,10 @@ unsafe fn find_edit_in_dialog(Err(_) => continue,};let name = read_name(&elem).unwrap_or_default();- if accepted_names- .iter()- .any(|n| name.eq_ignore_ascii_case(n) || name.to_ascii_lowercase().contains(&n.to_ascii_lowercase()))- {+ if accepted_names.iter().any(|n| {+ name.eq_ignore_ascii_case(n)+ || name.to_ascii_lowercase().contains(&n.to_ascii_lowercase())+ }) {return Ok(elem);}// Edge 148: the URL edit's AutomationId is sometimes "control".@@ -965,18 +950,9 @@ mod tests {#[test]fn extract_marker_strips_chromium_suffix() {assert_eq!(extract_marker("CUA:42", "CUA:"), "CUA:42");- assert_eq!(- extract_marker("CUA:42 - Microsoft Edge", "CUA:"),- "CUA:42"- );- assert_eq!(- extract_marker("CUA:42 - Google Chrome", "CUA:"),- "CUA:42"- );- assert_eq!(- extract_marker("Foo CUA:42 - Edge", "CUA:"),- "CUA:42"- );+ assert_eq!(extract_marker("CUA:42 - Microsoft Edge", "CUA:"), "CUA:42");+ assert_eq!(extract_marker("CUA:42 - Google Chrome", "CUA:"), "CUA:42");+ assert_eq!(extract_marker("Foo CUA:42 - Edge", "CUA:"), "CUA:42");assert_eq!(extract_marker("CUA_ERR:not defined - Edge", "CUA_ERR:"),"CUA_ERR:not defined"diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/stubs.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/stubs.rsindex 3445a88c96..03065c3a3e 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/stubs.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/stubs.rs@@ -2,7 +2,10 @@//! Schemas match the macOS platform-macos implementations (cross-platform interface).use async_trait::async_trait;-use cua_driver_core::{protocol::ToolResult, tool::{Tool, ToolDef, ToolRegistry}};+use cua_driver_core::{+ protocol::ToolResult,+ tool::{Tool, ToolDef, ToolRegistry},+};use serde_json::Value;fn not_impl(name: &str) -> ToolResult {@@ -32,65 +35,109 @@ macro_rules! stub_tool {}#[async_trait]impl Tool for $struct_name {- fn def(&self) -> &ToolDef { Self::def_static() }- async fn invoke(&self, _args: Value) -> ToolResult { not_impl($tool_name) }+ fn def(&self) -> &ToolDef {+ Self::def_static()+ }+ async fn invoke(&self, _args: Value) -> ToolResult {+ not_impl($tool_name)+ }}}pub use $mod_name::$struct_name;};}-stub_tool!(list_apps_m, ListAppsTool, "list_apps",+stub_tool!(+ list_apps_m,+ ListAppsTool,+ "list_apps","List running regular-UI applications.",- serde_json::json!({"type":"object","properties":{},"additionalProperties":false}));+ serde_json::json!({"type":"object","properties":{},"additionalProperties":false})+);-stub_tool!(list_windows_m, ListWindowsTool, "list_windows",+stub_tool!(+ list_windows_m,+ ListWindowsTool,+ "list_windows","List top-level windows, optionally filtered by pid.",- serde_json::json!({"type":"object","properties":{"pid":{"type":"integer"}},"additionalProperties":false}));+ serde_json::json!({"type":"object","properties":{"pid":{"type":"integer"}},"additionalProperties":false})+);stub_tool!(get_window_state_m, GetWindowStateTool, "get_window_state","Always returns BOTH the element tree AND a screenshot — ground on both and cross-check (the tree lies on some surfaces). Choose the modality at ACTION time: an element ax action (element_index/element_token → accessibility rung) or an element px action (x,y → pixel rung off this screenshot). capture_mode is deprecated and ignored.",serde_json::json!({"type":"object","required":["pid","window_id"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"window_id":{"type":"integer"},"query":{"type":"string"},"capture_mode": cua_driver_core::capture_mode::capture_mode_schema(),"include_screenshot":{"type":"boolean","description":"Default true — returns a grounding screenshot alongside the tree. Set false to skip the grab and return tree only (the cheap path for re-indexing before an element ax action)."}},"additionalProperties":false}));-stub_tool!(launch_app_m, LaunchAppTool, "launch_app",+stub_tool!(+ launch_app_m,+ LaunchAppTool,+ "launch_app","Launch an app in the background. Provide bundle_id (macOS) or name.",- serde_json::json!({"type":"object","properties":{"bundle_id":{"type":"string"},"name":{"type":"string"},"urls":{"type":"array","items":{"type":"string"}}},"additionalProperties":false}));+ serde_json::json!({"type":"object","properties":{"bundle_id":{"type":"string"},"name":{"type":"string"},"urls":{"type":"array","items":{"type":"string"}}},"additionalProperties":false})+);stub_tool!(kill_app_m, KillAppTool, "kill_app","Force-terminate a process by pid (taskkill /F equivalent on Windows). Use as escalation when the cooperative close path didn't make the process exit — typical for UWP / WinUI3 apps that route WM_CLOSE into a suspended-but-resident state.",serde_json::json!({"type":"object","required":["pid"],"properties":{"pid":{"type":"integer","description":"PID of the process to terminate."}},"additionalProperties":false}));-stub_tool!(click_m, ClickTool, "click",+stub_tool!(+ click_m,+ ClickTool,+ "click","Click at (x, y) or on an AX/UIA element by element_index + window_id.",- serde_json::json!({"type":"object","required":[],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"element_token": cua_driver_core::tool_schema::element_token_schema(),"x":{"type":"number"},"y":{"type":"number"},"button": cua_driver_core::tool_schema::button_schema(),"modifier": cua_driver_core::tool_schema::modifier_schema(),"from_zoom":{"type":"boolean"}},"additionalProperties":false}));+ serde_json::json!({"type":"object","required":[],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"element_token": cua_driver_core::tool_schema::element_token_schema(),"x":{"type":"number"},"y":{"type":"number"},"button": cua_driver_core::tool_schema::button_schema(),"modifier": cua_driver_core::tool_schema::modifier_schema(),"from_zoom":{"type":"boolean"}},"additionalProperties":false})+);-stub_tool!(double_click_m, DoubleClickTool, "double_click",+stub_tool!(+ double_click_m,+ DoubleClickTool,+ "double_click","Double-click at (x, y) or on an AX/UIA element by element_index + window_id.",- serde_json::json!({"type":"object","required":["pid"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"x":{"type":"number"},"y":{"type":"number"},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema()},"additionalProperties":false}));+ serde_json::json!({"type":"object","required":["pid"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"x":{"type":"number"},"y":{"type":"number"},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema()},"additionalProperties":false})+);-stub_tool!(right_click_m, RightClickTool, "right_click",+stub_tool!(+ right_click_m,+ RightClickTool,+ "right_click","Right-click (AXShowMenu on element, or synthesized event at x,y).",- serde_json::json!({"type":"object","required":["pid"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"window_id":{"type":"integer"},"x":{"type":"number"},"y":{"type":"number"},"modifier": cua_driver_core::tool_schema::modifier_schema()},"additionalProperties":false}));+ serde_json::json!({"type":"object","required":["pid"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"window_id":{"type":"integer"},"x":{"type":"number"},"y":{"type":"number"},"modifier": cua_driver_core::tool_schema::modifier_schema()},"additionalProperties":false})+);stub_tool!(type_text_m, TypeTextTool, "type_text","Insert text into the target pid via AXSelectedText or WM_CHAR. Falls back to CGEvent/keystrokes.",serde_json::json!({"type":"object","required":["pid","text"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"text":{"type":"string"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"window_id":{"type":"integer"},"x":{"type":"number"},"y":{"type":"number"}},"additionalProperties":false}));-stub_tool!(type_chars_m, TypeTextCharsTool, "type_text_chars",+stub_tool!(+ type_chars_m,+ TypeTextCharsTool,+ "type_text_chars","Type text character-by-character with configurable per-character delay.",- serde_json::json!({"type":"object","required":["pid","text"],"properties":{"pid":{"type":"integer"},"text":{"type":"string"},"delay_ms":{"type":"integer"},"window_id":{"type":"integer"},"element_index":{"type":"integer"}},"additionalProperties":false}));+ serde_json::json!({"type":"object","required":["pid","text"],"properties":{"pid":{"type":"integer"},"text":{"type":"string"},"delay_ms":{"type":"integer"},"window_id":{"type":"integer"},"element_index":{"type":"integer"}},"additionalProperties":false})+);-stub_tool!(press_key_m, PressKeyTool, "press_key",+stub_tool!(+ press_key_m,+ PressKeyTool,+ "press_key","Press and release a single key delivered directly to the target pid. No focus steal.",- serde_json::json!({"type":"object","required":["pid","key"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"key":{"type":"string"},"modifiers":{"type":"array","items":{"type":"string"}},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"x":{"type":"number"},"y":{"type":"number"}},"additionalProperties":false}));+ serde_json::json!({"type":"object","required":["pid","key"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"key":{"type":"string"},"modifiers":{"type":"array","items":{"type":"string"}},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"x":{"type":"number"},"y":{"type":"number"}},"additionalProperties":false})+);-stub_tool!(hotkey_m, HotkeyTool, "hotkey",+stub_tool!(+ hotkey_m,+ HotkeyTool,+ "hotkey","Press a combination of keys simultaneously, e.g. [\"cmd\",\"c\"] for Copy.",- serde_json::json!({"type":"object","required":["pid","keys"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"keys":{"type":"array","items":{"type":"string"},"minItems":2},"x":{"type":"number"},"y":{"type":"number"}},"additionalProperties":false}));+ serde_json::json!({"type":"object","required":["pid","keys"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"keys":{"type":"array","items":{"type":"string"},"minItems":2},"x":{"type":"number"},"y":{"type":"number"}},"additionalProperties":false})+);-stub_tool!(set_value_m, SetValueTool, "set_value",+stub_tool!(+ set_value_m,+ SetValueTool,+ "set_value","Set the value of an AX/UIA element (text field, dropdown, checkbox).",- serde_json::json!({"type":"object","required":["pid","window_id","element_index","value"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"value":{"type":"string"}},"additionalProperties":false}));+ serde_json::json!({"type":"object","required":["pid","window_id","element_index","value"],"properties":{"session": cua_driver_core::tool_schema::session_schema(),"pid":{"type":"integer"},"window_id":{"type":"integer"},"element_index": cua_driver_core::tool_schema::element_index_schema(),"value":{"type":"string"}},"additionalProperties":false})+);stub_tool!(scroll_m, ScrollTool, "scroll","Scroll the target pid's focused region. direction required; by defaults to line, amount defaults to 3.",@@ -100,45 +147,77 @@ stub_tool!(screenshot_m, ScreenshotTool, "screenshot","Capture a screenshot. Without window_id captures the full display. Supports png and jpeg formats.",serde_json::json!({"type":"object","properties":{"window_id":{"type":"integer"},"format":{"type":"string","enum":["png","jpeg"]},"quality":{"type":"integer","minimum":1,"maximum":95}},"additionalProperties":false}));-stub_tool!(get_screen_size_m, GetScreenSizeTool, "get_screen_size",+stub_tool!(+ get_screen_size_m,+ GetScreenSizeTool,+ "get_screen_size","Return the main screen's width and height in points.",- serde_json::json!({"type":"object","properties":{},"additionalProperties":false}));+ serde_json::json!({"type":"object","properties":{},"additionalProperties":false})+);-stub_tool!(get_cursor_position_m, GetCursorPositionTool, "get_cursor_position",+stub_tool!(+ get_cursor_position_m,+ GetCursorPositionTool,+ "get_cursor_position","Return the current real mouse cursor position.",- serde_json::json!({"type":"object","properties":{},"additionalProperties":false}));+ serde_json::json!({"type":"object","properties":{},"additionalProperties":false})+);stub_tool!(cursor_motion_m, SetAgentCursorMotionTool, "set_agent_cursor_motion",format!("Configure the visual appearance of an agent cursor instance.\n\nExtended cursor customization for multi-cursor use cases:\n- cursor_id: instance name (default='default')\n- cursor_icon: built-in ({}) or a path to a PNG/JPEG/SVG/ICO file; '' reverts to the default cursor\n- cursor_color: hex color e.g. '#00FFFF' or CSS name\n- cursor_label: short text shown near the cursor\n- cursor_size: dot radius in points (default=16)\n- cursor_opacity: 0.0–1.0 (default=0.85)", cursor_overlay::BuiltinShape::names_help()),serde_json::json!({"type":"object","properties":{"cursor_id":{"type":"string"},"cursor_icon":{"type":"string"},"cursor_color":{"type":"string"},"cursor_label":{"type":"string"},"cursor_size":{"type":"number"},"cursor_opacity":{"type":"number"}},"additionalProperties":false}));-stub_tool!(get_cursor_state_m, GetAgentCursorStateTool, "get_agent_cursor_state",+stub_tool!(+ get_cursor_state_m,+ GetAgentCursorStateTool,+ "get_agent_cursor_state","Return the current state of all agent cursor instances.",- serde_json::json!({"type":"object","properties":{},"additionalProperties":false}));+ serde_json::json!({"type":"object","properties":{},"additionalProperties":false})+);-stub_tool!(set_cursor_style_m, SetAgentCursorStyleTool, "set_agent_cursor_style",+stub_tool!(+ set_cursor_style_m,+ SetAgentCursorStyleTool,+ "set_agent_cursor_style","Update the visual style of the agent cursor overlay.",- serde_json::json!({"type":"object","properties":{"cursor_id":{"type":"string"},"gradient_colors":{"type":"array","items":{"type":"string"}},"bloom_color":{"type":"string"},"image_path":{"type":"string"}},"additionalProperties":false}));+ serde_json::json!({"type":"object","properties":{"cursor_id":{"type":"string"},"gradient_colors":{"type":"array","items":{"type":"string"}},"bloom_color":{"type":"string"},"image_path":{"type":"string"}},"additionalProperties":false})+);-stub_tool!(check_perms_m, CheckPermissionsTool, "check_permissions",+stub_tool!(+ check_perms_m,+ CheckPermissionsTool,+ "check_permissions","Check required permissions (Accessibility, Screen Recording).",- serde_json::json!({"type":"object","properties":{"prompt":{"type":"boolean"}},"additionalProperties":false}));+ serde_json::json!({"type":"object","properties":{"prompt":{"type":"boolean"}},"additionalProperties":false})+);-stub_tool!(get_config_m, GetConfigTool, "get_config",+stub_tool!(+ get_config_m,+ GetConfigTool,+ "get_config","Return current cua-driver-rs configuration.",- serde_json::json!({"type":"object","properties":{},"additionalProperties":false}));+ serde_json::json!({"type":"object","properties":{},"additionalProperties":false})+);-stub_tool!(set_config_m, SetConfigTool, "set_config",+stub_tool!(+ set_config_m,+ SetConfigTool,+ "set_config","Update cua-driver-rs configuration.",- serde_json::json!({"type":"object","properties":{"capture_mode":{"type":"string","enum":["ax","vision"]},"max_image_dimension":{"type":"integer"}},"additionalProperties":false}));+ serde_json::json!({"type":"object","properties":{"capture_mode":{"type":"string","enum":["ax","vision"]},"max_image_dimension":{"type":"integer"}},"additionalProperties":false})+);stub_tool!(get_ax_tree_m, GetAccessibilityTreeTool, "get_accessibility_tree","Lightweight desktop snapshot: running apps and visible windows. For per-window AX tree, use get_window_state.",serde_json::json!({"type":"object","properties":{},"additionalProperties":false}));-stub_tool!(zoom_m, ZoomTool, "zoom",+stub_tool!(+ zoom_m,+ ZoomTool,+ "zoom","Crop a window region to JPEG with 20% padding, max 500px wide.",- serde_json::json!({"type":"object","required":["window_id","x1","y1","x2","y2"],"properties":{"window_id":{"type":"integer"},"x1":{"type":"number"},"y1":{"type":"number"},"x2":{"type":"number"},"y2":{"type":"number"},"pid":{"type":"integer"}},"additionalProperties":false}));+ serde_json::json!({"type":"object","required":["window_id","x1","y1","x2","y2"],"properties":{"window_id":{"type":"integer"},"x1":{"type":"number"},"y1":{"type":"number"},"x2":{"type":"number"},"y2":{"type":"number"},"pid":{"type":"integer"}},"additionalProperties":false})+);// move_cursor and set_agent_cursor_enabled route through the overlay channel.@@ -159,13 +238,27 @@ mod move_cursor_m {}#[async_trait]impl Tool for MoveCursorTool {- fn def(&self) -> &ToolDef { Self::def_static() }+ fn def(&self) -> &ToolDef {+ Self::def_static()+ }async fn invoke(&self, args: Value) -> ToolResult {let x = args.get("x").and_then(|v| v.as_f64()).unwrap_or(0.0);let y = args.get("y").and_then(|v| v.as_f64()).unwrap_or(0.0);- let cursor_id = args.get("cursor_id").and_then(|v| v.as_str()).unwrap_or("default");- crate::overlay::send_command(cursor_id.to_owned(), cursor_overlay::OverlayCommand::MoveTo { x, y, end_heading_radians: 0.0 });- ToolResult::text(format!("Agent cursor '{cursor_id}' moved to ({x:.1}, {y:.1})."))+ let cursor_id = args+ .get("cursor_id")+ .and_then(|v| v.as_str())+ .unwrap_or("default");+ crate::overlay::send_command(+ cursor_id.to_owned(),+ cursor_overlay::OverlayCommand::MoveTo {+ x,+ y,+ end_heading_radians: 0.0,+ },+ );+ ToolResult::text(format!(+ "Agent cursor '{cursor_id}' moved to ({x:.1}, {y:.1})."+ ))}}}@@ -187,12 +280,27 @@ mod set_enabled_m {}#[async_trait]impl Tool for SetAgentCursorEnabledTool {- fn def(&self) -> &ToolDef { Self::def_static() }+ fn def(&self) -> &ToolDef {+ Self::def_static()+ }async fn invoke(&self, args: Value) -> ToolResult {- let enabled = args.get("enabled").and_then(|v| v.as_bool()).unwrap_or(true);- let cursor_id = args.get("cursor_id").and_then(|v| v.as_str()).unwrap_or("default");- crate::overlay::send_command(cursor_id.to_owned(), cursor_overlay::OverlayCommand::SetEnabled(enabled));- ToolResult::text(format!("Agent cursor '{}' {}.", cursor_id, if enabled { "enabled" } else { "disabled" }))+ let enabled = args+ .get("enabled")+ .and_then(|v| v.as_bool())+ .unwrap_or(true);+ let cursor_id = args+ .get("cursor_id")+ .and_then(|v| v.as_str())+ .unwrap_or("default");+ crate::overlay::send_command(+ cursor_id.to_owned(),+ cursor_overlay::OverlayCommand::SetEnabled(enabled),+ );+ ToolResult::text(format!(+ "Agent cursor '{}' {}.",+ cursor_id,+ if enabled { "enabled" } else { "disabled" }+ ))}}}@@ -225,9 +333,11 @@ pub fn build_registry() -> cua_driver_core::tool::ToolRegistry {// health_report is cross-platform — the Windows provider here lets// non-Windows hosts running the stubbed registry still advertise// the documented schema_version="1" contract.- r.register(Box::new(cua_driver_core::health_report::HealthReportTool::new(- std::sync::Arc::new(crate::health_report::WindowsHealthProvider),- )));+ r.register(Box::new(+ cua_driver_core::health_report::HealthReportTool::new(std::sync::Arc::new(+ crate::health_report::WindowsHealthProvider,+ )),+ ));r.register(Box::new(GetConfigTool));r.register(Box::new(SetConfigTool));r.register(Box::new(GetAccessibilityTreeTool));diff --git a/libs/cua-driver/rust/crates/platform-windows/src/uia/cache_uaf_repro.rs b/libs/cua-driver/rust/crates/platform-windows/src/uia/cache_uaf_repro.rsindex b20e897108..16f29d4198 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/uia/cache_uaf_repro.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/uia/cache_uaf_repro.rs@@ -46,7 +46,8 @@ use windows::Win32::UI::Accessibility::IUIAutomationElement;#[repr(C)]struct FakeVtbl {- query_interface: unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> HRESULT,+ query_interface:+ unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> HRESULT,add_ref: unsafe extern "system" fn(*mut c_void) -> u32,release: unsafe extern "system" fn(*mut c_void) -> u32,}@@ -163,7 +164,13 @@ fn run_forced_interleave(use_retained: bool, poison_on_zero: bool) -> usize {let cache = Arc::new(ElementCache::new());let ptr = make_fake(uaf_hits, poison_on_zero);- cache.core.insert(CacheKey { pid: PID, hwnd: HWND }, snapshot_with(vec![ptr]));+ cache.core.insert(+ CacheKey {+ pid: PID,+ hwnd: HWND,+ },+ snapshot_with(vec![ptr]),+ );let (b_looked_up_tx, b_looked_up_rx) = mpsc::channel::<()>();let (a_replaced_tx, a_replaced_rx) = mpsc::channel::<()>();@@ -193,9 +200,13 @@ fn run_forced_interleave(use_retained: bool, poison_on_zero: bool) -> usize {b_looked_up_rx.recv().unwrap();// get_window_state on the same (pid, hwnd): replace the snapshot. The// old snapshot's Drop fires COM Release on `ptr`.- cache_a- .core- .insert(CacheKey { pid: PID, hwnd: HWND }, snapshot_with(vec![]));+ cache_a.core.insert(+ CacheKey {+ pid: PID,+ hwnd: HWND,+ },+ snapshot_with(vec![]),+ );a_replaced_tx.send(()).unwrap();});@@ -220,7 +231,10 @@ fn fixed_path_survives_concurrent_replace() {#[test]fn prefix_path_commits_use_after_free() {let uaf = run_forced_interleave(/* use_retained */ false, /* poison */ false);- assert!(uaf > 0, "pre-fix path must hit the released element (the UAF)");+ assert!(+ uaf > 0,+ "pre-fix path must hit the released element (the UAF)"+ );}/// AFTER, under real (unforced) concurrency: hammer get_element_retained +@@ -232,7 +246,13 @@ fn fixed_path_stress_no_uaf() {// Seed a snapshot of several elements.let seed: Vec<usize> = (0..8).map(|_| make_fake(uaf_hits, false)).collect();- cache.core.insert(CacheKey { pid: PID, hwnd: HWND }, snapshot_with(seed));+ cache.core.insert(+ CacheKey {+ pid: PID,+ hwnd: HWND,+ },+ snapshot_with(seed),+ );const ITERS: usize = 4000;let mut handles = Vec::new();@@ -243,9 +263,13 @@ fn fixed_path_stress_no_uaf() {handles.push(thread::spawn(move || {for _ in 0..ITERS {let fresh: Vec<usize> = (0..8).map(|_| make_fake(uaf_hits, false)).collect();- cache_r- .core- .insert(CacheKey { pid: PID, hwnd: HWND }, snapshot_with(fresh));+ cache_r.core.insert(+ CacheKey {+ pid: PID,+ hwnd: HWND,+ },+ snapshot_with(fresh),+ );}}));}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/uia/fg_bypass.rs b/libs/cua-driver/rust/crates/platform-windows/src/uia/fg_bypass.rsindex 97703124d8..34e83bd1f3 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/uia/fg_bypass.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/uia/fg_bypass.rs@@ -31,7 +31,7 @@use windows::Win32::Foundation::HWND;use windows::Win32::UI::Input::KeyboardAndMouse::EnableWindow;-use windows::Win32::UI::WindowsAndMessaging::{GA_ROOT, GetAncestor};+use windows::Win32::UI::WindowsAndMessaging::{GetAncestor, GA_ROOT};/// RAII guard that disables a window on construction and restores its/// previous enabled-state on Drop. Always re-arms on Drop even if the@@ -46,13 +46,21 @@ impl DisabledHwndGuard {/// Disable `hwnd` for the lifetime of the guard. No-op for null HWND.pub fn disable(hwnd: HWND) -> Self {if hwnd.0.is_null() {- return Self { hwnd, was_enabled: false, armed: false };+ return Self {+ hwnd,+ was_enabled: false,+ armed: false,+ };}// `EnableWindow` returns nonzero iff the window was *previously// disabled* — invert to get the "was enabled" state we want to// restore at Drop time.let was_disabled = unsafe { EnableWindow(hwnd, false).as_bool() };- Self { hwnd, was_enabled: !was_disabled, armed: true }+ Self {+ hwnd,+ was_enabled: !was_disabled,+ armed: true,+ }}}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/uia/windows_enum.rs b/libs/cua-driver/rust/crates/platform-windows/src/uia/windows_enum.rsindex b18c2317f7..4c284eda3d 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/uia/windows_enum.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/uia/windows_enum.rs@@ -21,6 +21,7 @@use std::cell::RefCell;use anyhow::{bail, Context};+use windows::core::{Interface, BSTR};use windows::Win32::Foundation::{HWND, RECT};use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};use windows::Win32::System::Com::{@@ -30,12 +31,11 @@ use windows::Win32::UI::Accessibility::{CUIAutomation, IUIAutomation, IUIAutomationElement, IUIAutomationInvokePattern,IUIAutomationTogglePattern, TreeScope_Children, TreeScope_Subtree,UIA_AcceleratorKeyPropertyId, UIA_ButtonControlTypeId, UIA_CheckBoxControlTypeId,- UIA_CONTROLTYPE_ID, UIA_HyperlinkControlTypeId, UIA_InvokePatternId,- UIA_ListItemControlTypeId, UIA_MenuItemControlTypeId, UIA_PROPERTY_ID,- UIA_RadioButtonControlTypeId, UIA_SplitButtonControlTypeId, UIA_TabItemControlTypeId,- UIA_TogglePatternId, UIA_TreeItemControlTypeId,+ UIA_HyperlinkControlTypeId, UIA_InvokePatternId, UIA_ListItemControlTypeId,+ UIA_MenuItemControlTypeId, UIA_RadioButtonControlTypeId, UIA_SplitButtonControlTypeId,+ UIA_TabItemControlTypeId, UIA_TogglePatternId, UIA_TreeItemControlTypeId, UIA_CONTROLTYPE_ID,+ UIA_PROPERTY_ID,};-use windows::core::{BSTR, Interface};use windows::Win32::UI::WindowsAndMessaging::{GetWindowRect, GetWindowTextLengthW, GetWindowTextW, GetWindowThreadProcessId,};@@ -265,9 +265,7 @@ pub fn try_invoke_in_window_at_point(hwnd: isize, sx: i32, sy: i32) -> bool {// returned ✅ but the menu never opened.)let has_invoke = elem.GetCurrentPattern(UIA_InvokePatternId).is_ok();let has_expand = elem- .GetCurrentPattern(- windows::Win32::UI::Accessibility::UIA_ExpandCollapsePatternId,- )+ .GetCurrentPattern(windows::Win32::UI::Accessibility::UIA_ExpandCollapsePatternId).is_ok();if !has_invoke && !has_expand {continue;@@ -314,9 +312,7 @@ pub fn try_invoke_in_window_at_point(hwnd: isize, sx: i32, sy: i32) -> bool {// in that case. Pure-Invoke leaves (buttons, links, etc.) go// through Invoke as before.let winner_has_expand = winner- .GetCurrentPattern(- windows::Win32::UI::Accessibility::UIA_ExpandCollapsePatternId,- )+ .GetCurrentPattern(windows::Win32::UI::Accessibility::UIA_ExpandCollapsePatternId).is_ok();let winner_has_invoke = winner.GetCurrentPattern(UIA_InvokePatternId).is_ok();// UWP foreground-steal bypass: gate the entire activation block on@@ -375,10 +371,7 @@ pub fn try_invoke_in_window_at_point(hwnd: isize, sx: i32, sy: i32) -> bool {/// their keyboard accelerators are surfaced through UI Automation instead./// This helper keeps that routing narrow by requiring an advertised/// AcceleratorKey match before invoking anything.-pub fn try_invoke_accelerator_in_window(- hwnd: isize,- combo: &str,-) -> anyhow::Result<(bool, usize)> {+pub fn try_invoke_accelerator_in_window(hwnd: isize, combo: &str) -> anyhow::Result<(bool, usize)> {if hwnd == 0 {bail!("invalid target hwnd 0");}@@ -412,14 +405,17 @@ pub fn try_invoke_accelerator_in_window(};// Primary match: the UIA AcceleratorKey property — the conventional// place a WinUI / XAML control advertises its shortcut.- let mut accelerator: Option<String> = read_current_bstr(&elem, UIA_AcceleratorKeyPropertyId);+ let mut accelerator: Option<String> =+ read_current_bstr(&elem, UIA_AcceleratorKeyPropertyId);// Fallback match: many shipping XAML apps (e.g. modern Notepad)// don't set AcceleratorKey at all and instead encode the shortcut// in the visible element name as a parenthetical hint like// "Bold (Ctrl+B)". Scan the Name property for that pattern so// toolbar buttons remain reachable via hotkey.if accelerator.is_none() {- if let Some(name) = read_current_bstr(&elem, windows::Win32::UI::Accessibility::UIA_NamePropertyId) {+ if let Some(name) =+ read_current_bstr(&elem, windows::Win32::UI::Accessibility::UIA_NamePropertyId)+ {if let Some(extracted) = extract_shortcut_from_name(&name) {accelerator = Some(extracted);}@@ -603,9 +599,10 @@ fn extract_shortcut_from_name(name: &str) -> Option<String> {// parentheticals (e.g. "(2)" or "(beta)").let has_modifier = inner.split('+').any(|tok| {let t = tok.trim().to_ascii_lowercase();- matches!(t.as_str(),- "ctrl" | "control" | "shift" | "alt" |- "win" | "windows" | "meta" | "cmd" | "command")+ matches!(+ t.as_str(),+ "ctrl" | "control" | "shift" | "alt" | "win" | "windows" | "meta" | "cmd" | "command"+ )});if has_modifier {Some(inner.to_owned())@@ -690,6 +687,11 @@ fn window_bounds(hwnd: HWND) -> (i32, i32, i32, i32) {if ok.is_err() {let _ = GetWindowRect(hwnd, &mut rect);}- (rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top)+ (+ rect.left,+ rect.top,+ rect.right - rect.left,+ rect.bottom - rect.top,+ )}}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/virtualdesk.rs b/libs/cua-driver/rust/crates/platform-windows/src/virtualdesk.rsindex 7241203f16..8c6d8b462f 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/virtualdesk.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/virtualdesk.rs@@ -110,72 +110,78 @@ mod tests {// The reporter's setup: secondary to the LEFT of primary, both 1920x1080.// Primary occupies (0..1920, 0..1080); secondary occupies (-1920..0, 0..1080)."secondary-left-of-primary",- -1920, 0, 3840, 1080,+ -1920,+ 0,+ 3840,+ 1080,vec![- (-1920, 0), // top-left of virtual desk (top-left of secondary)- (1919, 1079), // bottom-right of virtual desk (bottom-right of primary)- (-1, 0), // last pixel of secondary on the X seam- (0, 0), // first pixel of primary on the X seam- (-1795, 383), // the exact pixel from issue #1979- (-1198, 292), // the second pixel from issue #1979+ (-1920, 0), // top-left of virtual desk (top-left of secondary)+ (1919, 1079), // bottom-right of virtual desk (bottom-right of primary)+ (-1, 0), // last pixel of secondary on the X seam+ (0, 0), // first pixel of primary on the X seam+ (-1795, 383), // the exact pixel from issue #1979+ (-1198, 292), // the second pixel from issue #1979],),(// Secondary to the RIGHT of primary. Virt origin at (0, 0), width 3840."secondary-right-of-primary",- 0, 0, 3840, 1080,+ 0,+ 0,+ 3840,+ 1080,vec![(0, 0),(3839, 1079),- (1919, 0), // last pixel of primary on seam- (1920, 0), // first pixel of secondary on seam- (2125, 383), // mirror of the reporter's pixel onto the right layout+ (1919, 0), // last pixel of primary on seam+ (1920, 0), // first pixel of secondary on seam+ (2125, 383), // mirror of the reporter's pixel onto the right layout],),(// Secondary ABOVE primary. Virt origin at (0, -1080), height 2160."secondary-above-primary",- 0, -1080, 1920, 2160,- vec![- (0, -1080),- (1919, 1079),- (0, -1),- (0, 0),- (960, -540),- ],+ 0,+ -1080,+ 1920,+ 2160,+ vec![(0, -1080), (1919, 1079), (0, -1), (0, 0), (960, -540)],),(// Secondary BELOW primary. Virt origin at (0, 0), height 2160."secondary-below-primary",- 0, 0, 1920, 2160,- vec![- (0, 0),- (1919, 2159),- (0, 1079),- (0, 1080),- (960, 1620),- ],+ 0,+ 0,+ 1920,+ 2160,+ vec![(0, 0), (1919, 2159), (0, 1079), (0, 1080), (960, 1620)],),(// Three horizontal monitors: [-1920..0, 0..1920, 1920..3840], all 1080 tall.// virt rect (-1920, 0, 5760, 1080)."three-horiz-mixed-signs",- -1920, 0, 5760, 1080,+ -1920,+ 0,+ 5760,+ 1080,vec![- (-1920, 0), (-1, 0), (0, 0), (1919, 0), (1920, 0), (3839, 1079),- (-1795, 383), // reporter's pixel still on leftmost monitor+ (-1920, 0),+ (-1, 0),+ (0, 0),+ (1919, 0),+ (1920, 0),+ (3839, 1079),+ (-1795, 383), // reporter's pixel still on leftmost monitor],),(// Single monitor — the baseline. No offsets."single-monitor-1920x1080",- 0, 0, 1920, 1080,- vec![- (0, 0),- (1919, 1079),- (960, 540),- (1, 1),- ],+ 0,+ 0,+ 1920,+ 1080,+ vec![(0, 0), (1919, 1079), (960, 540), (1, 1)],),(// HiDPI secondary. cua-driver runs Per-Monitor-V2 DPI-aware (see@@ -189,10 +195,13 @@ mod tests {// (-2560..0, 0..1440), primary occupies (0..1920, 0..1080) inside// the same virt height band."hidpi-secondary-left-2560x1440",- -2560, 0, 4480, 1440,+ -2560,+ 0,+ 4480,+ 1440,vec![(-2560, 0),- (4479 - 2560, 1439), // bottom-right of virtual desk+ (4479 - 2560, 1439), // bottom-right of virtual desk(-1, 0),(0, 0),(-2000, 720),@@ -204,7 +213,10 @@ mod tests {// below, mixed with one to the right of primary. Just a sanity// case for a virt rect spanning both positive and negative."mixed-vertical-and-horizontal",- -1920, -1080, 3840, 2160,+ -1920,+ -1080,+ 3840,+ 2160,vec![(-1920, -1080),(1919, 1079),@@ -288,8 +300,7 @@ mod tests {let (tl_x, tl_y) = to_virtualdesk_absolute(vx, vy, vx, vy, vw, vh);assert_eq!(tl_x, 0, "{label}: top-left x ≠ 0 (got {tl_x})");assert_eq!(tl_y, 0, "{label}: top-left y ≠ 0 (got {tl_y})");- let (br_x, br_y) =- to_virtualdesk_absolute(vx + vw - 1, vy + vh - 1, vx, vy, vw, vh);+ let (br_x, br_y) = to_virtualdesk_absolute(vx + vw - 1, vy + vh - 1, vx, vy, vw, vh);assert_eq!(br_x, 65535, "{label}: bottom-right x ≠ 65535 (got {br_x})");assert_eq!(br_y, 65535, "{label}: bottom-right y ≠ 65535 (got {br_y})");}@@ -319,7 +330,10 @@ mod tests {);// Round-trip recovers the input within ±1 (the strongest guarantee).let (rx, ry) = from_virtualdesk_absolute(dx, dy, -1920, 0, 3840, 1080);- assert!((rx - (-1795)).abs() <= 1, "round-trip x drift: {rx} vs -1795");+ assert!(+ (rx - (-1795)).abs() <= 1,+ "round-trip x drift: {rx} vs -1795"+ );assert!((ry - 383).abs() <= 1, "round-trip y drift: {ry} vs 383");}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/wgc.rs b/libs/cua-driver/rust/crates/platform-windows/src/wgc.rsindex c614a55225..cd46956c63 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/wgc.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/wgc.rs@@ -22,6 +22,7 @@ use anyhow::{bail, Context, Result};use std::time::Duration;use windows::{+ core::Interface,Graphics::{Capture::{Direct3D11CaptureFramePool, GraphicsCaptureItem},DirectX::{Direct3D11::IDirect3DDevice, DirectXPixelFormat},@@ -32,9 +33,8 @@ use windows::{Direct3D::{D3D_DRIVER_TYPE_HARDWARE, D3D_FEATURE_LEVEL_11_0},Direct3D11::{D3D11CreateDevice, ID3D11Device, ID3D11DeviceContext, ID3D11Texture2D,- D3D11_CPU_ACCESS_READ, D3D11_CREATE_DEVICE_BGRA_SUPPORT,- D3D11_MAPPED_SUBRESOURCE, D3D11_MAP_READ, D3D11_SDK_VERSION,- D3D11_TEXTURE2D_DESC, D3D11_USAGE_STAGING,+ D3D11_CPU_ACCESS_READ, D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_MAPPED_SUBRESOURCE,+ D3D11_MAP_READ, D3D11_SDK_VERSION, D3D11_TEXTURE2D_DESC, D3D11_USAGE_STAGING,},Dxgi::IDXGIDevice,},@@ -44,7 +44,6 @@ use windows::{},UI::WindowsAndMessaging::IsIconic,},- core::Interface,};/// Capture a window via WGC, returning BGRA pixels + (width, height).@@ -85,7 +84,9 @@ unsafe fn wgc_capture_impl(hwnd: HWND) -> Result<(Vec<u8>, u32, u32)> {// 2. DXGI device interface for the D3D11 device, then the WinRT// IDirect3DDevice wrapper that GraphicsCaptureFramePool needs.- let dxgi_device: IDXGIDevice = d3d_device.cast().context("ID3D11Device → IDXGIDevice cast")?;+ let dxgi_device: IDXGIDevice = d3d_device+ .cast()+ .context("ID3D11Device → IDXGIDevice cast")?;let inspectable = CreateDirect3D11DeviceFromDXGIDevice(&dxgi_device).context("CreateDirect3D11DeviceFromDXGIDevice failed")?;let direct3d_device: IDirect3DDevice = inspectable@@ -96,12 +97,10 @@ unsafe fn wgc_capture_impl(hwnd: HWND) -> Result<(Vec<u8>, u32, u32)> {let interop_factory: IGraphicsCaptureItemInterop =windows::core::factory::<GraphicsCaptureItem, IGraphicsCaptureItemInterop>().context("IGraphicsCaptureItemInterop activation factory")?;- let item: GraphicsCaptureItem = interop_factory- .CreateForWindow(hwnd)- .context(- "IGraphicsCaptureItemInterop::CreateForWindow failed — \+ let item: GraphicsCaptureItem = interop_factory.CreateForWindow(hwnd).context(+ "IGraphicsCaptureItemInterop::CreateForWindow failed — \requires Win10 1903+ and the target window must exist",- )?;+ )?;let item_size = item.Size().context("GraphicsCaptureItem::Size")?;if item_size.Width <= 0 || item_size.Height <= 0 {bail!(@@ -153,13 +152,18 @@ unsafe fn wgc_capture_impl(hwnd: HWND) -> Result<(Vec<u8>, u32, u32)> {// NULL until one's available. 50 ms polling interval keeps the// "frame finally arrived" detection latency low without burning// CPU on a tight spin.- session.StartCapture().context("GraphicsCaptureSession::StartCapture")?;+ session+ .StartCapture()+ .context("GraphicsCaptureSession::StartCapture")?;let deadline = std::time::Instant::now() + Duration::from_millis(1500);let mut frame_opt = None;while std::time::Instant::now() < deadline {match pool.TryGetNextFrame() {- Ok(f) => { frame_opt = Some(f); break; }+ Ok(f) => {+ frame_opt = Some(f);+ break;+ }Err(_) => {// TryGetNextFrame returns an error when no frame is// available yet. Wait briefly, retry.@@ -167,11 +171,13 @@ unsafe fn wgc_capture_impl(hwnd: HWND) -> Result<(Vec<u8>, u32, u32)> {}}}- let frame = frame_opt.ok_or_else(|| anyhow::anyhow!(- "WGC TryGetNextFrame returned no frame within 1500 ms — \+ let frame = frame_opt.ok_or_else(|| {+ anyhow::anyhow!(+ "WGC TryGetNextFrame returned no frame within 1500 ms — \DWM may not be compositing this window (cloaked / not actually \rendered). Fall through to screen-region BitBlt."- ))?;+ )+ })?;// 8. Pull the underlying ID3D11Texture2D out of the WinRT frame// surface via the IDirect3DDxgiInterfaceAccess shim.diff --git a/libs/cua-driver/rust/crates/platform-windows/src/win32/apps.rs b/libs/cua-driver/rust/crates/platform-windows/src/win32/apps.rsindex 98dba9e432..c49f66325e 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/win32/apps.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/win32/apps.rs@@ -5,8 +5,7 @@use windows::Win32::Foundation::CloseHandle;use windows::Win32::System::Diagnostics::ToolHelp::{- CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W,- TH32CS_SNAPPROCESS,+ CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W, TH32CS_SNAPPROCESS,};#[derive(Debug, Clone)]@@ -124,10 +123,16 @@ fn strip_version_suffix(basename: &str) -> String {let mut cut = bytes.len();while cut > 0 {let c = bytes[cut - 1] as char;- if c.is_ascii_digit() || c == '.' || c == '-' { cut -= 1; } else { break; }+ if c.is_ascii_digit() || c == '.' || c == '-' {+ cut -= 1;+ } else {+ break;+ }}// Avoid stripping an entire name (e.g. "7z" → "" would lose information).// If everything past cut is purely digits/dots/dashes AND cut > 0, accept.- if cut == 0 { return s; }+ if cut == 0 {+ return s;+ }s[..cut].to_string()}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/win32/windows.rs b/libs/cua-driver/rust/crates/platform-windows/src/win32/windows.rsindex 8db8e571b5..8e4c1220e5 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/win32/windows.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/win32/windows.rs@@ -22,9 +22,7 @@use std::collections::HashSet;use std::sync::Mutex;use windows::Win32::Foundation::{BOOL, HWND, LPARAM, RECT, TRUE};-use windows::Win32::Graphics::Dwm::{- DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS,-};+use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};use windows::Win32::UI::WindowsAndMessaging::{EnumChildWindows, EnumWindows, GetClassNameW, GetWindowRect, GetWindowTextLengthW,GetWindowTextW, GetWindowThreadProcessId, IsIconic, IsWindowVisible,@@ -89,7 +87,9 @@ pub fn list_windows(filter_pid: Option<u32>) -> Vec<WindowInfo> {/// top-level window. No pid filter is applied here — the caller does that on/// the merged list.fn enumerate_via_enum_windows() -> Vec<WindowInfo> {- let state = Mutex::new(EnumState { windows: Vec::new() });+ let state = Mutex::new(EnumState {+ windows: Vec::new(),+ });let state_ptr = &state as *const Mutex<EnumState> as isize;unsafe {let _ = EnumWindows(Some(enum_windows_cb), LPARAM(state_ptr));@@ -113,14 +113,18 @@ unsafe extern "system" fn enum_windows_cb(hwnd: HWND, lparam: LPARAM) -> BOOL {// Get title (skip empty).let title_len = GetWindowTextLengthW(hwnd);- if title_len == 0 { return TRUE; }+ if title_len == 0 {+ return TRUE;+ }let mut buf = vec![0u16; (title_len + 1) as usize];GetWindowTextW(hwnd, &mut buf);let title = {let len = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());String::from_utf16_lossy(&buf[..len])};- if title.trim().is_empty() { return TRUE; }+ if title.trim().is_empty() {+ return TRUE;+ }// Get bounds — prefer DWM extended frame bounds (includes shadow), fallback to GetWindowRect.let (x, y, w, h) = get_window_bounds(hwnd);@@ -154,7 +158,12 @@ fn get_window_bounds(hwnd: HWND) -> (i32, i32, i32, i32) {// Fallback to GetWindowRect.let _ = GetWindowRect(hwnd, &mut rect);}- (rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top)+ (+ rect.left,+ rect.top,+ rect.right - rect.left,+ rect.bottom - rect.top,+ )}}@@ -272,10 +281,7 @@ pub fn resolve_uwp_host_window(app_pid: u32) -> Option<WindowInfo> {matched_frame: None,};unsafe {- let _ = EnumWindows(- Some(frame_cb),- LPARAM(&mut scan as *mut FrameScan as isize),- );+ let _ = EnumWindows(Some(frame_cb), LPARAM(&mut scan as *mut FrameScan as isize));}let frame = scan.matched_frame?;diff --git a/libs/cua-driver/rust/rust-toolchain.toml b/libs/cua-driver/rust/rust-toolchain.tomlnew file mode 100644index 0000000000..a46af26fb5--- /dev/null+++ b/libs/cua-driver/rust/rust-toolchain.toml@@ -0,0 +1,4 @@+[toolchain]+channel = "1.97.1"+components = ["rustfmt"]+profile = "minimal"