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
fix(cua-driver): reject ambiguous PID-only targets (#2763)
Francesco Bonacci5b95f2a888b8
diff --git a/docs/content/docs/reference/cua-driver/mcp-tool-notes.mdx b/docs/content/docs/reference/cua-driver/mcp-tool-notes.mdxindex 8ea017ada2..572096066a 100644--- a/docs/content/docs/reference/cua-driver/mcp-tool-notes.mdx+++ b/docs/content/docs/reference/cua-driver/mcp-tool-notes.mdx@@ -21,6 +21,10 @@ Several parameters are a **shared cross-platform contract**: the same JSON shapeThe `required` set is uniform across platforms: `click` requires nothing, `scroll` requires `direction`, and `zoom` requires `window_id` plus `x1`/`y1`/`x2`/`y2`. `pid` is **conditionally** required. Every per-window action needs it; a windowless desktop-scope call omits it. Code validates that rule with a clear error rather than pinning it in the schema, so a client that omits `pid` for a desktop-scope action is not schema-rejected.+### PID-only window targets++A window-scoped action may omit `window_id` only when its `pid` owns exactly one eligible top-level window. The driver resolves that unique window before dispatch. When the PID owns multiple windows, it sends no input and returns `code: "ambiguous_window_target"`, `effect: "refused"`, and candidate metadata. Select a candidate from that result or `list_windows({pid})`, then retry with the exact `window_id`. A PID with no eligible windows returns `window_target_not_found`. Explicit `(pid, window_id)` and `element_token` targets keep their exact resolution behavior.+### Platform-specific parametersA few parameters are platform-specific by design and are intentionally NOT part of the shared contract:diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdxindex 92d55d10f7..cda929fe87 100644--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx@@ -308,7 +308,7 @@ When `from_zoom` is true, coordinates are in the last zoom image for this pid; t- `steps` (integer, optional): Number of intermediate mouseDragged events linearly interpolated along the path. Default: 20. range: 1–200- `to_x` (number, required): Drag-end X in window-local screenshot pixels.- `to_y` (number, required): Drag-end Y in window-local screenshot pixels.-- `window_id` (integer, optional): CGWindowID for the window the pixel coordinates were measured against. Optional — when omitted the driver picks the frontmost window of pid.+- `window_id` (integer, optional): CGWindowID for the window the pixel coordinates were measured against. Optional only when pid owns exactly one eligible top-level window; otherwise the action refuses with ambiguous_window_target.```json{"from_x":100,"from_y":200,"to_x":100,"to_y":200}diff --git a/libs/cua-driver/docs/action-result-contract.md b/libs/cua-driver/docs/action-result-contract.mdindex 6b8889364a..06b0c39413 100644--- a/libs/cua-driver/docs/action-result-contract.md+++ b/libs/cua-driver/docs/action-result-contract.md@@ -54,6 +54,21 @@ The invariants are:- `partial` has `delivery.delivered_count`;- `refused` has neither delivery nor evidence.+## Window target resolution++Window-scoped actions accept a PID without `window_id` only when that process+has exactly one eligible top-level window. The driver promotes that unique+match to an exact `(pid, window_id)` target before dispatch. If the PID owns+multiple eligible windows, the action fails before sending input with+`code: "ambiguous_window_target"`, `effect: "refused"`, and a `candidates`+array containing each candidate's `window_id`, title, application name when+available, and on-screen state. Call `list_windows({pid})`, select the intended+candidate, and retry with its explicit `window_id`.++A PID with no eligible windows fails with `code: "window_target_not_found"`.+Explicit `window_id` targets and `element_token` targets retain their exact+resolution semantics; the guard does not replace or reinterpret them.+An action that reached an actuator but lacks a trusted readback is`unverifiable`, not `confirmed`. Screenshot change, native API acceptance,event receipt, and operator observation may remain useful internal diagnostics,diff --git a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md b/libs/cua-driver/rust/Skills/cua-driver/SKILL.mdindex 27dd800c56..fbfa6353c7 100644--- a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md+++ b/libs/cua-driver/rust/Skills/cua-driver/SKILL.md@@ -893,6 +893,7 @@ doesn't-survive-across-sessions caveat.| `No cached AX state for pid X window_id W` | You either skipped `get_window_state` this turn, or passed a different `window_id` to the click than the one the snapshot cached against | Call `get_window_state({pid: X, window_id: W})` first — the same window_id you intend to click in || `Invalid element_index N for pid X window_id W` | Index is stale or out of range | Re-run `get_window_state` with the same window_id, pick a fresh index from the new tree || `window_id W belongs to pid P, not …` | Passed a window_id that's owned by a different process | Use `list_windows({pid: X})` to enumerate this pid's own windows |+| `ambiguous_window_target` | A PID-only window action matched multiple eligible top-level windows | Use the returned candidates or `list_windows({pid: X})`, select the intended sibling, and retry with its explicit `window_id` || `AX action … failed with code …` / `UIA invoke failed` | Element doesn't support the default action | Try `show_menu`, `confirm`, `cancel`, `pick`, or fall through to a pixel click on the element's center || `The user doesn't want to proceed with this tool use. The tool use was rejected …` | The harness uses this _exact_ string for BOTH a permission-prompt denial AND a manual interrupt (Esc / stop) of a running tool — they are indistinguishable from the tool result | Treat as "tool canceled, no result, await the user." Do NOT paraphrase ("you stopped me") — quote the literal message and name the canceled tool + its args, so the user can tell what was in flight vs. what landed |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 872cc106fc..882958b947 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@@ -83,6 +83,7 @@ pub mod tool_schema;pub mod video;pub mod video_ffmpeg;pub mod window_inspection;+pub mod window_target;pub use cua_driver_contract::{CaptureScope, EscalationReason};pub use recording::RecordingSession;diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/window_target.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/window_target.rsnew file mode 100644index 0000000000..6203bb4b4b--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/window_target.rs@@ -0,0 +1,265 @@+//! Fail-closed resolution for actions addressed only by process id.++use std::collections::HashSet;+use std::sync::Arc;++use async_trait::async_trait;+use serde::{Deserialize, Serialize};+use serde_json::Value;++use crate::protocol::ToolResult;+use crate::tool::{ProtectedResourceOwnership, Tool, ToolDef};++/// Caller-recoverable metadata for an eligible top-level window.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+pub struct WindowTargetCandidate {+ pub window_id: u64,+ pub title: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub app_name: Option<String>,+ pub is_on_screen: bool,+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub enum PidWindowTargetResolution {+ NotFound,+ Resolved(WindowTargetCandidate),+ Ambiguous(Vec<WindowTargetCandidate>),+}++/// Resolve the cardinality of eligible windows for one pid.+///+/// Duplicate ids are ignored defensively because some platforms merge more+/// than one native enumeration source.+pub fn resolve_pid_window_target(+ candidates: impl IntoIterator<Item = WindowTargetCandidate>,+) -> PidWindowTargetResolution {+ let mut seen = HashSet::new();+ let candidates: Vec<_> = candidates+ .into_iter()+ .filter(|candidate| seen.insert(candidate.window_id))+ .collect();+ match candidates.as_slice() {+ [] => PidWindowTargetResolution::NotFound,+ [candidate] => PidWindowTargetResolution::Resolved(candidate.clone()),+ _ => PidWindowTargetResolution::Ambiguous(candidates),+ }+}++pub type WindowTargetCandidates =+ Arc<dyn Fn(i64) -> Vec<WindowTargetCandidate> + Send + Sync + 'static>;++/// Tool decorator that resolves PID-only calls before an action can send input.+/// Explicit `window_id` and `element_token` targets pass through unchanged.+pub struct PidOnlyWindowTargetGuard {+ inner: Box<dyn Tool>,+ candidates: WindowTargetCandidates,+}++impl PidOnlyWindowTargetGuard {+ pub fn new(inner: Box<dyn Tool>, candidates: WindowTargetCandidates) -> Self {+ Self { inner, candidates }+ }+}++#[async_trait]+impl Tool for PidOnlyWindowTargetGuard {+ fn def(&self) -> &ToolDef {+ self.inner.def()+ }++ async fn protected_resource_ownership(+ &self,+ adapter_id: &str,+ args: &Value,+ ) -> ProtectedResourceOwnership {+ self.inner+ .protected_resource_ownership(adapter_id, args)+ .await+ }++ async fn protected_resource_scope(+ &self,+ adapter_id: &str,+ args: &Value,+ ) -> Result<Option<Value>, String> {+ self.inner.protected_resource_scope(adapter_id, args).await+ }++ async fn validate_protected_resource_scope(+ &self,+ adapter_id: &str,+ args: &Value,+ approved_scope: &Value,+ ) -> Result<(), String> {+ self.inner+ .validate_protected_resource_scope(adapter_id, args, approved_scope)+ .await+ }++ async fn invoke(&self, mut args: Value) -> ToolResult {+ if args.get("scope").and_then(Value::as_str) == Some("desktop")+ || args.get("window_id").is_some_and(|value| !value.is_null())+ || args+ .get("element_token")+ .is_some_and(|value| !value.is_null())+ {+ return self.inner.invoke(args).await;+ }++ let Some(pid) = args.get("pid").and_then(Value::as_i64) else {+ return self.inner.invoke(args).await;+ };+ let candidates = self.candidates.clone();+ let candidates = match tokio::task::spawn_blocking(move || candidates(pid)).await {+ Ok(candidates) => candidates,+ Err(error) => {+ return ToolResult::error(format!(+ "Could not enumerate eligible windows for pid {pid}: {error}"+ ))+ .with_structured(serde_json::json!({+ "code": "window_target_resolution_failed",+ "effect": "refused",+ "pid": pid+ }))+ }+ };+ match resolve_pid_window_target(candidates) {+ PidWindowTargetResolution::NotFound => ToolResult::error(format!(+ "No eligible top-level windows found for pid {pid}."+ ))+ .with_structured(serde_json::json!({+ "code": "window_target_not_found",+ "effect": "refused",+ "pid": pid,+ "candidates": []+ })),+ PidWindowTargetResolution::Resolved(candidate) => {+ if let Some(object) = args.as_object_mut() {+ object.insert("window_id".to_owned(), candidate.window_id.into());+ }+ self.inner.invoke(args).await+ }+ PidWindowTargetResolution::Ambiguous(candidates) => ToolResult::error(format!(+ "pid {pid} owns more than one eligible top-level window; provide window_id."+ ))+ .with_structured(serde_json::json!({+ "code": "ambiguous_window_target",+ "effect": "refused",+ "pid": pid,+ "candidates": candidates+ })),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::sync::atomic::{AtomicUsize, Ordering};++ struct EchoTool {+ calls: Arc<AtomicUsize>,+ }++ static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();++ #[async_trait]+ impl Tool for EchoTool {+ fn def(&self) -> &ToolDef {+ DEF.get_or_init(|| ToolDef {+ name: "echo".into(),+ description: "test".into(),+ input_schema: serde_json::json!({"type": "object"}),+ read_only: false,+ destructive: true,+ idempotent: false,+ open_world: false,+ })+ }++ async fn invoke(&self, args: Value) -> ToolResult {+ self.calls.fetch_add(1, Ordering::SeqCst);+ ToolResult::text("called").with_structured(args)+ }+ }++ fn candidate(window_id: u64) -> WindowTargetCandidate {+ WindowTargetCandidate {+ window_id,+ title: format!("Window {window_id}"),+ app_name: Some("Editor".into()),+ is_on_screen: true,+ }+ }++ #[test]+ fn resolver_reports_zero_one_and_many() {+ assert_eq!(+ resolve_pid_window_target([]),+ PidWindowTargetResolution::NotFound+ );+ assert_eq!(+ resolve_pid_window_target([candidate(7)]),+ PidWindowTargetResolution::Resolved(candidate(7))+ );+ assert_eq!(+ resolve_pid_window_target([candidate(7), candidate(8)]),+ PidWindowTargetResolution::Ambiguous(vec![candidate(7), candidate(8)])+ );+ }++ #[tokio::test]+ async fn ambiguity_refuses_before_invoking_action_with_recovery_metadata() {+ let calls = Arc::new(AtomicUsize::new(0));+ let guard = PidOnlyWindowTargetGuard::new(+ Box::new(EchoTool {+ calls: calls.clone(),+ }),+ Arc::new(|_| vec![candidate(7), candidate(8)]),+ );+ let result = guard.invoke(serde_json::json!({"pid": 42})).await;++ assert_eq!(calls.load(Ordering::SeqCst), 0);+ assert_eq!(result.is_error, Some(true));+ let structured = result.structured_content.unwrap();+ assert_eq!(structured["code"], "ambiguous_window_target");+ assert_eq!(structured["effect"], "refused");+ assert_eq!(structured["candidates"][1]["window_id"], 8);+ }++ #[tokio::test]+ async fn unique_pid_target_is_promoted_to_explicit_window_id() {+ let calls = Arc::new(AtomicUsize::new(0));+ let guard = PidOnlyWindowTargetGuard::new(+ Box::new(EchoTool {+ calls: calls.clone(),+ }),+ Arc::new(|_| vec![candidate(7)]),+ );+ let result = guard.invoke(serde_json::json!({"pid": 42})).await;++ assert_eq!(calls.load(Ordering::SeqCst), 1);+ assert_eq!(result.structured_content.unwrap()["window_id"], 7);+ }++ #[tokio::test]+ async fn explicit_window_and_element_token_targets_pass_through() {+ for args in [+ serde_json::json!({"pid": 42, "window_id": 9}),+ serde_json::json!({"pid": 42, "element_token": "explicit"}),+ ] {+ let calls = Arc::new(AtomicUsize::new(0));+ let guard = PidOnlyWindowTargetGuard::new(+ Box::new(EchoTool {+ calls: calls.clone(),+ }),+ Arc::new(|_| panic!("explicit targets must not enumerate windows")),+ );+ let expected = args.clone();+ let result = guard.invoke(args).await;+ assert_eq!(calls.load(Ordering::SeqCst), 1);+ assert_eq!(result.structured_content.unwrap(), expected);+ }+ }+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rsindex cc408ff563..c16494f78f 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs@@ -9,6 +9,7 @@ use cua_driver_core::{protocol::ToolResult,tool::{Tool, ToolDef, ToolRegistry},tool_args::{parse_typed_input, parse_typed_projection, ArgsExt},+ window_target::{PidOnlyWindowTargetGuard, WindowTargetCandidate, WindowTargetCandidates},};use serde_json::{json, Value};use std::fs;@@ -18,6 +19,39 @@ use std::sync::{Arc, RwLock};use crate::atspi::ElementCache;use cursor_overlay::CursorRegistry;+fn window_target_candidates_for_pid(+ windows: impl IntoIterator<Item = crate::x11::WindowInfo>,+ pid: u32,+) -> Vec<WindowTargetCandidate> {+ windows+ .into_iter()+ .filter(|window| window.pid == Some(pid))+ .map(|window| WindowTargetCandidate {+ window_id: window.xid,+ title: window.title,+ app_name: Some(window.app_name),+ is_on_screen: window.is_on_screen,+ })+ .collect()+}++fn pid_window_target_candidates(pid: i64) -> Vec<WindowTargetCandidate> {+ let Ok(pid) = u32::try_from(pid) else {+ return Vec::new();+ };+ window_target_candidates_for_pid(crate::wayland::list_windows_dispatch(Some(pid)), pid)+}++fn pid_window_guarded<T: Tool + 'static>(+ tool: T,+ candidates: &WindowTargetCandidates,+) -> Box<dyn Tool> {+ Box::new(PidOnlyWindowTargetGuard::new(+ Box::new(tool),+ candidates.clone(),+ ))+}+// ── DriverConfig + ResizeRegistry + ZoomRegistry ─────────────────────────────#[derive(Clone)]@@ -7066,42 +7100,73 @@ pub fn build_registry_with_provider());r.register(Box::new(LaunchAppTool));r.register(Box::new(KillAppTool));- r.register(Box::new(BringToFrontTool));- r.register(Box::new(ClickTool {- state: state.clone(),- }));- r.register(Box::new(DoubleClickTool {- state: state.clone(),- }));- r.register(Box::new(RightClickTool {- state: state.clone(),- }));- r.register(Box::new(DragTool {- state: state.clone(),- }));- r.register(Box::new(MouseButtonDownTool {- state: state.clone(),- }));- r.register(Box::new(MouseDragTool {- state: state.clone(),- }));- r.register(Box::new(MouseButtonUpTool {- state: state.clone(),- }));+ let pid_window_candidates: WindowTargetCandidates = Arc::new(pid_window_target_candidates);+ r.register(pid_window_guarded(BringToFrontTool, &pid_window_candidates));+ r.register(pid_window_guarded(+ ClickTool {+ state: state.clone(),+ },+ &pid_window_candidates,+ ));+ r.register(pid_window_guarded(+ DoubleClickTool {+ state: state.clone(),+ },+ &pid_window_candidates,+ ));+ r.register(pid_window_guarded(+ RightClickTool {+ state: state.clone(),+ },+ &pid_window_candidates,+ ));+ r.register(pid_window_guarded(+ DragTool {+ state: state.clone(),+ },+ &pid_window_candidates,+ ));+ r.register(pid_window_guarded(+ MouseButtonDownTool {+ state: state.clone(),+ },+ &pid_window_candidates,+ ));+ r.register(pid_window_guarded(+ MouseDragTool {+ state: state.clone(),+ },+ &pid_window_candidates,+ ));+ r.register(pid_window_guarded(+ MouseButtonUpTool {+ state: state.clone(),+ },+ &pid_window_candidates,+ ));r.register(Box::new(ParallelMouseDragTool {state: state.clone(),}));- r.register(Box::new(TypeTextTool {- state: state.clone(),- }));- r.register(Box::new(PressKeyTool {- state: state.clone(),- }));- r.register(Box::new(HotkeyTool {- state: state.clone(),- }));- r.register(Box::new(SetValueTool));- r.register(Box::new(ScrollTool));+ r.register(pid_window_guarded(+ TypeTextTool {+ state: state.clone(),+ },+ &pid_window_candidates,+ ));+ r.register(pid_window_guarded(+ PressKeyTool {+ state: state.clone(),+ },+ &pid_window_candidates,+ ));+ r.register(pid_window_guarded(+ HotkeyTool {+ state: state.clone(),+ },+ &pid_window_candidates,+ ));+ r.register(pid_window_guarded(SetValueTool, &pid_window_candidates));+ r.register(pid_window_guarded(ScrollTool, &pid_window_candidates));// `screenshot` removed - see the matching comment in// platform-windows/src/tools/impl_.rs::build_registry. Canonical// screenshot path is `get_window_state` (it always returns a screenshot now).@@ -7235,3 +7300,35 @@ mod browser_launch_guard_tests {));}}++#[cfg(test)]+mod pid_window_target_tests {+ use super::*;+ use cua_driver_core::window_target::{resolve_pid_window_target, PidWindowTargetResolution};++ fn window(xid: u64, pid: u32) -> crate::x11::WindowInfo {+ crate::x11::WindowInfo {+ xid,+ pid: Some(pid),+ app_name: "editor".into(),+ title: format!("Document {xid}"),+ is_on_screen: true,+ z_index: Some(1),+ x: 0,+ y: 0,+ width: 640,+ height: 480,+ }+ }++ #[test]+ fn same_pid_sibling_windows_are_ambiguous() {+ let candidates =+ window_target_candidates_for_pid([window(7, 42), window(8, 42), window(9, 99)], 42);+ assert!(matches!(+ resolve_pid_window_target(candidates),+ PidWindowTargetResolution::Ambiguous(windows)+ if windows.iter().map(|window| window.window_id).collect::<Vec<_>>() == [7, 8]+ ));+ }+}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rsindex 4d7b690e09..8eb5638fd3 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rs@@ -60,7 +60,7 @@ fn def() -> &'static ToolDef {"pid": { "type": "integer", "description": "Target process ID." },"window_id": {"type": "integer",- "description": "CGWindowID for the window the pixel coordinates were measured against. Optional — when omitted the driver picks the frontmost window of pid."+ "description": "CGWindowID for the window the pixel coordinates were measured against. Optional only when pid owns exactly one eligible top-level window; otherwise the action refuses with ambiguous_window_target."},"from_x": { "type": "number", "description": "Drag-start X in window-local screenshot pixels. Top-left origin." },"from_y": { "type": "number", "description": "Drag-start Y in window-local screenshot pixels. Top-left origin." },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 b3ff1c2421..3a3115eae9 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@@ -35,12 +35,85 @@ mod set_config;mod type_text_chars;mod zoom;-use cua_driver_core::tool::ToolRegistry;+use cua_driver_core::{+ tool::{Tool, ToolRegistry},+ window_target::{PidOnlyWindowTargetGuard, WindowTargetCandidate, WindowTargetCandidates},+};use std::collections::HashMap;use std::sync::Arc;use crate::{ax::cache::ElementCache, cursor::state::CursorRegistry};+fn pid_window_target_candidates(pid: i64) -> Vec<WindowTargetCandidate> {+ let Ok(pid) = i32::try_from(pid) else {+ return Vec::new();+ };+ window_target_candidates_for_pid(crate::windows::all_windows(), pid)+}++fn window_target_candidates_for_pid(+ windows: impl IntoIterator<Item = crate::windows::WindowInfo>,+ pid: i32,+) -> Vec<WindowTargetCandidate> {+ windows+ .into_iter()+ .filter(|window| window.pid == pid)+ .map(|window| WindowTargetCandidate {+ window_id: u64::from(window.window_id),+ title: window.title,+ app_name: Some(window.app_name),+ is_on_screen: window.is_on_screen,+ })+ .collect()+}++#[cfg(test)]+mod pid_window_target_tests {+ use super::*;+ use cua_driver_core::window_target::{resolve_pid_window_target, PidWindowTargetResolution};++ fn window(window_id: u32, pid: i32) -> crate::windows::WindowInfo {+ crate::windows::WindowInfo {+ window_id,+ pid,+ app_name: "Editor".into(),+ title: format!("Document {window_id}"),+ bounds: crate::windows::WindowBounds {+ x: 0.0,+ y: 0.0,+ width: 640.0,+ height: 480.0,+ },+ layer: 0,+ z_index: 1,+ is_on_screen: true,+ on_current_space: None,+ space_ids: None,+ }+ }++ #[test]+ fn same_pid_sibling_windows_are_ambiguous() {+ let candidates =+ window_target_candidates_for_pid([window(7, 42), window(8, 42), window(9, 99)], 42);+ assert!(matches!(+ resolve_pid_window_target(candidates),+ PidWindowTargetResolution::Ambiguous(windows)+ if windows.iter().map(|window| window.window_id).collect::<Vec<_>>() == [7, 8]+ ));+ }+}++fn pid_window_guarded<T: Tool + 'static>(+ tool: T,+ candidates: &WindowTargetCandidates,+) -> Box<dyn Tool> {+ Box::new(PidOnlyWindowTargetGuard::new(+ Box::new(tool),+ candidates.clone(),+ ))+}+pub use check_permissions::{request_from_launchservices_host as request_permissions_from_launchservices_host,PERMISSIONS_HOST_REQUEST_ARG,@@ -649,16 +722,47 @@ pub fn register_all());registry.register(Box::new(launch_app::LaunchAppTool));registry.register(Box::new(kill_app::KillAppTool));- registry.register(Box::new(bring_to_front::BringToFrontTool));- registry.register(Box::new(click::ClickTool::new(state.clone())));- registry.register(Box::new(double_click::DoubleClickTool::new(state.clone())));- registry.register(Box::new(right_click::RightClickTool::new(state.clone())));- registry.register(Box::new(drag::DragTool::new(state.clone())));- registry.register(Box::new(type_text::TypeTextTool::new(state.clone())));- registry.register(Box::new(press_key::PressKeyTool::new(state.clone())));- registry.register(Box::new(hotkey::HotkeyTool::new(state.clone())));- registry.register(Box::new(set_value::SetValueTool::new(state.clone())));- registry.register(Box::new(scroll::ScrollTool::new(state.clone())));+ let pid_window_candidates: WindowTargetCandidates = Arc::new(pid_window_target_candidates);+ registry.register(pid_window_guarded(+ bring_to_front::BringToFrontTool,+ &pid_window_candidates,+ ));+ registry.register(pid_window_guarded(+ click::ClickTool::new(state.clone()),+ &pid_window_candidates,+ ));+ registry.register(pid_window_guarded(+ double_click::DoubleClickTool::new(state.clone()),+ &pid_window_candidates,+ ));+ registry.register(pid_window_guarded(+ right_click::RightClickTool::new(state.clone()),+ &pid_window_candidates,+ ));+ registry.register(pid_window_guarded(+ drag::DragTool::new(state.clone()),+ &pid_window_candidates,+ ));+ registry.register(pid_window_guarded(+ type_text::TypeTextTool::new(state.clone()),+ &pid_window_candidates,+ ));+ registry.register(pid_window_guarded(+ press_key::PressKeyTool::new(state.clone()),+ &pid_window_candidates,+ ));+ registry.register(pid_window_guarded(+ hotkey::HotkeyTool::new(state.clone()),+ &pid_window_candidates,+ ));+ registry.register(pid_window_guarded(+ set_value::SetValueTool::new(state.clone()),+ &pid_window_candidates,+ ));+ registry.register(pid_window_guarded(+ scroll::ScrollTool::new(state.clone()),+ &pid_window_candidates,+ ));// The standalone `screenshot` tool was removed (#1692). The pixel-grounding// screenshot the Claude Code computer-use compat loop relies on now comes// from `get_window_state` (which always returns BOTH the tree AND adiff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rsindex 2c207ee5f1..18d932f139 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs@@ -245,6 +245,7 @@ use cua_driver_core::{protocol::ToolResult,tool::{Tool, ToolDef, ToolRegistry},tool_args::{parse_typed_input, parse_typed_projection},+ window_target::{PidOnlyWindowTargetGuard, WindowTargetCandidate, WindowTargetCandidates},};use serde_json::{json, Value};use std::sync::{Arc, RwLock};@@ -253,6 +254,39 @@ use crate::uia::ElementCache;use cursor_overlay::CursorRegistry;use windows::core::Interface as _;+fn window_target_candidates_for_pid(+ windows: impl IntoIterator<Item = crate::win32::WindowInfo>,+ pid: u32,+) -> Vec<WindowTargetCandidate> {+ windows+ .into_iter()+ .filter(|window| window.pid == pid)+ .map(|window| WindowTargetCandidate {+ window_id: window.hwnd,+ title: window.title,+ app_name: None,+ is_on_screen: window.is_on_screen,+ })+ .collect()+}++fn pid_window_target_candidates(pid: i64) -> Vec<WindowTargetCandidate> {+ let Ok(pid) = u32::try_from(pid) else {+ return Vec::new();+ };+ window_target_candidates_for_pid(crate::win32::list_windows(Some(pid)), pid)+}++fn pid_window_guarded<T: Tool + 'static>(+ tool: T,+ candidates: &WindowTargetCandidates,+) -> Box<dyn Tool> {+ Box::new(PidOnlyWindowTargetGuard::new(+ Box::new(tool),+ candidates.clone(),+ ))+}+/// The cursor key for an anonymous (cursor-less) call. A run opts into a cursor/// by declaring a `session`; without one, every cursor op short-circuits on/// this empty key (see `overlay::send_command` / `overlay_glide_to`).@@ -8645,35 +8679,63 @@ pub fn build_registry_with_provider());r.register(Box::new(LaunchAppTool));r.register(Box::new(KillAppTool));- r.register(Box::new(BringToFrontTool));+ let pid_window_candidates: WindowTargetCandidates = Arc::new(pid_window_target_candidates);+ r.register(pid_window_guarded(BringToFrontTool, &pid_window_candidates));r.register(Box::new(DebugWindowInfoTool));- r.register(Box::new(ClickTool {- state: state.clone(),- }));- r.register(Box::new(DoubleClickTool {- state: state.clone(),- }));- r.register(Box::new(RightClickTool {- state: state.clone(),- }));- r.register(Box::new(DragTool {- state: state.clone(),- }));- r.register(Box::new(TypeTextTool {- state: state.clone(),- }));- r.register(Box::new(PressKeyTool {- state: state.clone(),- }));- r.register(Box::new(HotkeyTool {- state: state.clone(),- }));- r.register(Box::new(SetValueTool {- state: state.clone(),- }));- r.register(Box::new(ScrollTool {- state: state.clone(),- }));+ r.register(pid_window_guarded(+ ClickTool {+ state: state.clone(),+ },+ &pid_window_candidates,+ ));+ r.register(pid_window_guarded(+ DoubleClickTool {+ state: state.clone(),+ },+ &pid_window_candidates,+ ));+ r.register(pid_window_guarded(+ RightClickTool {+ state: state.clone(),+ },+ &pid_window_candidates,+ ));+ r.register(pid_window_guarded(+ DragTool {+ state: state.clone(),+ },+ &pid_window_candidates,+ ));+ r.register(pid_window_guarded(+ TypeTextTool {+ state: state.clone(),+ },+ &pid_window_candidates,+ ));+ r.register(pid_window_guarded(+ PressKeyTool {+ state: state.clone(),+ },+ &pid_window_candidates,+ ));+ r.register(pid_window_guarded(+ HotkeyTool {+ state: state.clone(),+ },+ &pid_window_candidates,+ ));+ r.register(pid_window_guarded(+ SetValueTool {+ state: state.clone(),+ },+ &pid_window_candidates,+ ));+ r.register(pid_window_guarded(+ ScrollTool {+ state: state.clone(),+ },+ &pid_window_candidates,+ ));// `screenshot` / `ScreenshotCompatTool` removed from the tool surface// — `get_window_state` (which now always returns a screenshot) is the// single canonical path for getting a window screenshot. Reasons:@@ -9172,3 +9234,34 @@ mod browser_launch_guard_tests {));}}++#[cfg(test)]+mod pid_window_target_tests {+ use super::*;+ use cua_driver_core::window_target::{resolve_pid_window_target, PidWindowTargetResolution};++ fn window(hwnd: u64, pid: u32) -> crate::win32::WindowInfo {+ crate::win32::WindowInfo {+ hwnd,+ pid,+ title: format!("Document {hwnd}"),+ x: 0,+ y: 0,+ width: 640,+ height: 480,+ is_on_screen: true,+ minimized: false,+ }+ }++ #[test]+ fn same_pid_sibling_windows_are_ambiguous() {+ let candidates =+ window_target_candidates_for_pid([window(7, 42), window(8, 42), window(9, 99)], 42);+ assert!(matches!(+ resolve_pid_window_target(candidates),+ PidWindowTargetResolution::Ambiguous(windows)+ if windows.iter().map(|window| window.window_id).collect::<Vec<_>>() == [7, 8]+ ));+ }+}