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): define list_windows z-index contract (#2768)
Francesco Bonacci5fe669ff4389
diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdxindex cda929fe87..2b58ca955a 100644--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx@@ -48,7 +48,7 @@ Use this for "is X installed?" as well as "is X running?". For per-window stateList all layer-0 top-level windows currently known to WindowServer. Includes off-screen windows (minimized, on another Space, hidden-launched). Use this to find a window_id before calling get_window_state.-Per-record fields: window_id, pid, app_name, title, bounds (x/y/width/height, top-left origin), z_index (higher = frontmost), is_on_screen, on_current_space.+Per-record fields: window_id, pid, app_name, title, bounds (x/y/width/height, top-left origin), z_index (integer or null; higher values are closer to the front; null means stacking order is unavailable and callers must not infer one), is_on_screen, on_current_space. To select a frontmost candidate, take the maximum integer z_index; if every value is null, use an explicit fallback instead of relying on array order.**Arguments:**diff --git a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md b/libs/cua-driver/rust/Skills/cua-driver/SKILL.mdindex fbfa6353c7..179d7ae597 100644--- a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md+++ b/libs/cua-driver/rust/Skills/cua-driver/SKILL.md@@ -687,6 +687,13 @@ against a specific window.| Send key to pid | `press_key({pid, key, modifiers})` | no focus change; key goes to pid's current focus || Modifier combo | `hotkey({pid, keys})` (no focus) or `hotkey({pid, x, y, keys})` (px) | e.g. `["cmd","c"]` / `["ctrl","c"]`; posted per-pid, not HID tap. **px** pixel-clicks `(x,y)` to focus a field first, e.g. `["cmd","v"]` to paste into it |+`list_windows.z_index` uses one portable convention: higher integer+values are closer to the front. Select a frontmost candidate with the+maximum non-null value. If all values are `null` (as they can be on+native Wayland), use an explicit fallback; never treat `null` as zero+or infer stacking from array order. The `windows` records returned by+`launch_app` use the same convention.+In effective desktop scope, the foreground/system equivalents omit`pid`/`window_id` and pass `scope:"desktop"`: `click`, `scroll`, `drag`,`move_cursor`, `type_text`, `press_key`, and `hotkey`. Coordinates arediff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/desktop.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/desktop.rsindex ecbcca7e5a..fffcdea163 100644--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/desktop.rs+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/desktop.rs@@ -32,6 +32,54 @@ pub fn contracts() -> Vec<ToolContract> {]}+const Z_INDEX_DESCRIPTION: &str = "Higher values are closer to the front. Null means the provider cannot observe stacking order; callers must not infer an order from array position or treat null as zero.";++// Keep this schema deliberately narrow: platform window records have additive+// fields and are still converging, while z_index has one portable meaning that+// consumers need in order to sort safely. This runtime schema intentionally+// stays outside the typed SDK manifest until that broader shape converges.+pub(crate) fn list_windows_success_output_schema() -> serde_json::Value {+ serde_json::json!({+ "type": "object",+ "properties": {+ "windows": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "z_index": {+ "type": ["integer", "null"],+ "description": Z_INDEX_DESCRIPTION+ }+ },+ "required": ["z_index"],+ "additionalProperties": true+ }+ }+ },+ "required": ["windows"],+ "additionalProperties": true+ })+}++pub(crate) fn validate_list_windows_output(value: serde_json::Value) -> Result<(), String> {+ let windows = value+ .get("windows")+ .and_then(serde_json::Value::as_array)+ .ok_or_else(|| "windows must be an array".to_owned())?;+ for (index, window) in windows.iter().enumerate() {+ let z_index = window+ .get("z_index")+ .ok_or_else(|| format!("windows[{index}].z_index is required"))?;+ if !(z_index.is_null() || z_index.is_u64() || z_index.is_i64()) {+ return Err(format!(+ "windows[{index}].z_index must be an integer or null"+ ));+ }+ }+ Ok(())+}+fn contract<I: ToolInput, O: ToolOutput>(name: &str,description: &str,diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/lib.rsindex 8c34e1c01d..8c598f904f 100644--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/lib.rs+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/lib.rs@@ -247,6 +247,16 @@ pub fn tool_input_fields(name: &str) -> Option<&'static BTreeSet<String>> {tool_index().get(name).map(|entry| &entry.input_fields)}+/// Return the successful `structuredContent` schema advertised by the live+/// MCP tool. Runtime-only tools can define a narrow shared schema here without+/// committing every generated SDK to their broader platform-specific shape.+pub fn tool_success_output_schema(name: &str) -> Option<Value> {+ if name == "list_windows" {+ return Some(desktop::list_windows_success_output_schema());+ }+ tool_contract(name).and_then(|contract| contract.success_output_schema)+}+/// Validate a successful structured payload against the Rust output type that/// also generates its SDK schema. Returns `Ok(false)` for non-SDK tools.pub fn validate_success_output(name: &str, value: Value) -> Result<bool, String> {@@ -254,6 +264,10 @@ pub fn validate_success_output(name: &str, value: Value) -> Result<bool, String>validate_typed_output::<ActionResult>(value)?;return Ok(true);}+ if name == "list_windows" {+ desktop::validate_list_windows_output(value)?;+ return Ok(true);+ }if let Some(entry) = tool_index().get(name) {(entry.output_validator)(value)?;Ok(true)@@ -360,6 +374,36 @@ mod tests {}}+ #[test]+ fn list_windows_defines_nullable_higher_is_frontmost_z_index() {+ assert!(tool_contract("list_windows").is_none());+ let schema = tool_success_output_schema("list_windows").expect("runtime schema");+ let z_index = &schema["properties"]["windows"]["items"]["properties"]["z_index"];+ assert_eq!(z_index["type"], serde_json::json!(["integer", "null"]));+ let description = z_index["description"].as_str().expect("description");+ assert!(description.contains("Higher values are closer to the front"));+ assert!(description.contains("must not infer an order"));++ assert_eq!(+ validate_success_output(+ "list_windows",+ serde_json::json!({+ "windows": [+ {"z_index": 4, "platform_field": true},+ {"z_index": null}+ ],+ "current_space_id": null+ }),+ ),+ Ok(true)+ );+ assert!(validate_success_output(+ "list_windows",+ serde_json::json!({"windows": [{"z_index": "unknown"}]}),+ )+ .is_err());+ }+#[test]fn desktop_action_contracts_share_the_strict_action_result() {let expected = ActionResult::output_schema();diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rsindex 0884521d70..809adf8c21 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs@@ -184,8 +184,7 @@ impl ToolDef {),)} else {- cua_driver_contract::tool_contract(&self.name)- .and_then(|contract| contract.success_output_schema)+ cua_driver_contract::tool_success_output_schema(&self.name)};if let Some(output_schema) = output_schema {entry@@ -4386,6 +4385,27 @@ mod capability_tests {assert!(runtime_only.get("outputSchema").is_none());}+ #[test]+ fn list_windows_advertises_the_shared_z_index_contract() {+ let entry = ToolDef {+ name: "list_windows".into(),+ description: "List windows.".into(),+ input_schema: serde_json::json!({"type":"object","properties":{}}),+ read_only: true,+ destructive: false,+ idempotent: true,+ open_world: false,+ }+ .to_list_entry();+ let z_index =+ &entry["outputSchema"]["properties"]["windows"]["items"]["properties"]["z_index"];+ assert_eq!(z_index["type"], serde_json::json!(["integer", "null"]));+ assert!(z_index["description"]+ .as_str()+ .expect("description")+ .contains("Higher values are closer to the front"));+ }+#[test]fn type_text_claims_terminal_safe_capability() {// The terminal-emulator fallback shipped per platform must bediff --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 c16494f78f..57b4184c9f 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@@ -421,7 +421,11 @@ impl Tool for ListWindowsTool {fn def(&self) -> &ToolDef {LIST_WINDOWS_DEF.get_or_init(|| ToolDef {name: "list_windows".into(),- description: "List top-level X11 windows via _NET_CLIENT_LIST.".into(),+ description: "List top-level windows. Each record includes z_index (integer or null; \+ higher values are closer to the front; null means stacking order is unavailable \+ and callers must not infer one). To select a frontmost candidate, take the maximum \+ integer z_index; if every value is null, use an explicit fallback instead of \+ relying on array order.".into(),input_schema: json!({"type":"object","properties":{"pid":{"type":"integer"},"on_screen_only":{"type":"boolean","description":"When true, filter to visible windows only. Default false."}@@ -525,6 +529,24 @@ mod list_windows_tests {assert_eq!(rec["title"], json!("Example"));}+ #[test]+ fn unavailable_wayland_order_serializes_as_null() {+ let w = crate::x11::WindowInfo {+ xid: 43,+ pid: Some(1234),+ app_name: "native-wayland-app".to_owned(),+ title: "Example".to_owned(),+ is_on_screen: true,+ z_index: None,+ x: 0,+ y: 0,+ width: 300,+ height: 400,+ };++ assert_eq!(window_record_json(&w)["z_index"], Value::Null);+ }+#[test]fn chromium_launch_detection_uses_executable_basename() {assert!(chromium_family_program("/usr/bin/google-chrome-stable"));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 2bb7accfcb..e65dc18f84 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@@ -79,7 +79,7 @@ fn list_windows_inner(filter_pid: Option<u32>) -> Result<Vec<WindowInfo>> {app_name,title,is_on_screen,- z_index: Some(z_index),+ z_index: Some(z_index_from_bottom_to_top(z_index)),x,y,width: w,@@ -90,6 +90,10 @@ fn list_windows_inner(filter_pid: Option<u32>) -> Result<Vec<WindowInfo>> {Ok(result)}+fn z_index_from_bottom_to_top(position: usize) -> usize {+ position+}+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 {@@ -231,4 +235,11 @@ mod tests {assert!(!fallback_window_is_listable(MapState::UNMAPPED));assert!(!fallback_window_is_listable(MapState::UNVIEWABLE));}++ #[test]+ fn ewmh_bottom_to_top_order_normalizes_to_higher_is_frontmost() {+ let indices: Vec<_> = (0..3).map(z_index_from_bottom_to_top).collect();+ assert_eq!(indices, vec![0, 1, 2]);+ assert!(indices[2] > indices[0]);+ }}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/launch_app.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/launch_app.rsindex 0d50c35a86..a08d6ba03d 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/launch_app.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/launch_app.rs@@ -457,19 +457,7 @@ impl Tool for LaunchAppTool {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- },- "is_on_screen": w.is_on_screen,- })- })+ .map(super::list_windows::window_record_json).collect();let mut structured = serde_json::json!({diff --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 db2cab0e2d..fa41046681 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@@ -16,8 +16,11 @@ fn def() -> &'static ToolDef {Includes off-screen windows (minimized, on another Space, hidden-launched). \Use this to find a window_id before calling get_window_state.\n\n\Per-record fields: window_id, pid, app_name, title, bounds \- (x/y/width/height, top-left origin), z_index (higher = frontmost), \- is_on_screen, on_current_space.".into(),+ (x/y/width/height, top-left origin), z_index (integer or null; higher values are \+ closer to the front; null means stacking order is unavailable and callers must not \+ infer one), is_on_screen, on_current_space. To select a frontmost candidate, take the \+ maximum integer z_index; if every value is null, use an explicit fallback instead of \+ relying on array order.".into(),input_schema: serde_json::json!({"type": "object","properties": {@@ -60,28 +63,7 @@ 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(window_record_json).collect();ToolResult::text(format!("Found {} window(s).", windows_json.len())).with_structured(serde_json::json!({@@ -91,3 +73,51 @@ impl Tool for ListWindowsTool {)}}++pub(super) fn window_record_json(w: &crate::windows::WindowInfo) -> Value {+ 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,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn window_record_includes_observed_z_index() {+ let window = crate::windows::WindowInfo {+ window_id: 42,+ pid: 123,+ app_name: "Example".into(),+ title: "Document".into(),+ bounds: crate::windows::WindowBounds {+ x: 1.0,+ y: 2.0,+ width: 300.0,+ height: 200.0,+ },+ layer: 0,+ z_index: 7,+ is_on_screen: true,+ on_current_space: Some(true),+ space_ids: Some(vec![1]),+ };++ assert_eq!(window_record_json(&window)["z_index"], serde_json::json!(7));+ }+}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/windows.rs b/libs/cua-driver/rust/crates/platform-macos/src/windows.rsindex 740b8a9dfa..0bff25eeb6 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/windows.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/windows.rs@@ -209,7 +209,7 @@ fn enumerate_windows(options: u32, layers: LayerFilter) -> Vec<WindowInfo> {};// z_index: CGWindowList front-to-back → assign reverse index.- let z_index = total - idx;+ let z_index = z_index_from_front_to_back(total, idx);result.push(WindowInfo {window_id,@@ -228,6 +228,10 @@ fn enumerate_windows(options: u32, layers: LayerFilter) -> Vec<WindowInfo> {result}+fn z_index_from_front_to_back(total: usize, position: usize) -> usize {+ total.saturating_sub(position)+}+fn get_bounds_num(dict: &core_foundation::dictionary::CFDictionary<*const std::os::raw::c_void,@@ -336,6 +340,15 @@ pub fn resolve_main_window_id(pid: i32) -> anyhow::Result<u32> {mod tests {use super::*;+ #[test]+ fn cg_front_to_back_order_normalizes_to_higher_is_frontmost() {+ let indices: Vec<_> = (0..3)+ .map(|position| z_index_from_front_to_back(3, position))+ .collect();+ assert_eq!(indices, vec![3, 2, 1]);+ assert!(indices[0] > indices[2]);+ }+fn window(window_id: u32, pid: i32, app_name: &str) -> WindowInfo {WindowInfo {window_id,diff --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 18d932f139..adbd7e8db1 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@@ -704,8 +704,12 @@ impl Tool for ListWindowsTool {have a visible window right now?\", \"which of this pid's windows is the main \one?\".\n\n\Per-record fields: window_id (HWND), pid + app_name, title, \- bounds {x, y, width, height}, layer (always 0), z_index (stacking order), \- is_on_screen, minimized. The macOS-specific on_current_space / space_ids fields are \+ bounds {x, y, width, height}, layer (always 0), z_index (integer or null; higher \+ values are closer to the front; null means stacking order is unavailable and \+ callers must not infer one), is_on_screen, minimized. To select a frontmost \+ candidate, take the maximum integer z_index; if every value is null, use an \+ explicit fallback instead of relying on array order. The macOS-specific \+ on_current_space / space_ids fields are \omitted on Windows; current_space_id is null.\n\n\Inputs: pid (optional pid filter), on_screen_only (bool, default false).".into(),input_schema: json!({"type":"object","properties":{@@ -771,7 +775,7 @@ impl Tool for ListWindowsTool {.enumerate().map(|(i, w)| {let app_name = pid_to_name.get(&w.pid).cloned().unwrap_or_default();- let z_index = (n.saturating_sub(1).saturating_sub(i)) as i64;+ let z_index = z_index_from_front_to_back(n, i) as i64;json!({"window_id": w.hwnd,"pid": w.pid,@@ -847,6 +851,24 @@ impl Tool for ListWindowsTool {}}+fn z_index_from_front_to_back(total: usize, position: usize) -> usize {+ total.saturating_sub(1).saturating_sub(position)+}++#[cfg(test)]+mod list_windows_z_index_tests {+ use super::z_index_from_front_to_back;++ #[test]+ fn enum_windows_front_to_back_order_normalizes_to_higher_is_frontmost() {+ let indices: Vec<_> = (0..3)+ .map(|position| z_index_from_front_to_back(3, position))+ .collect();+ assert_eq!(indices, vec![2, 1, 0]);+ assert!(indices[0] > indices[2]);+ }+}+// ── get_window_state ─────────────────────────────────────────────────────────pub struct GetWindowStateTool {@@ -2243,12 +2265,13 @@ impl Tool for LaunchAppTool {.await.unwrap_or_default();if !wins.is_empty() {- windows_json = wins.iter().map(|w| json!({+ let window_count = wins.len();+ windows_json = wins.iter().enumerate().map(|(position, w)| json!({"window_id": w.hwnd, "title": w.title,"bounds": { "x": w.x, "y": w.y, "width": w.width, "height": w.height },"layer": 0,- "z_index": 0, // single-window context; per-record z_index already in list_windows- "is_on_screen": true,+ "z_index": z_index_from_front_to_back(window_count, position),+ "is_on_screen": w.is_on_screen,})).collect();break;}@@ -2303,12 +2326,13 @@ impl Tool for LaunchAppTool {.await.unwrap_or_default();if !wins.is_empty() {- windows_json = wins.iter().map(|w| json!({+ let window_count = wins.len();+ windows_json = wins.iter().enumerate().map(|(position, w)| json!({"window_id": w.hwnd, "title": w.title,"bounds": { "x": w.x, "y": w.y, "width": w.width, "height": w.height },"layer": 0,- "z_index": 0,- "is_on_screen": true,+ "z_index": z_index_from_front_to_back(window_count, position),+ "is_on_screen": w.is_on_screen,})).collect();resolved_pid = candidate_pid;break 'outer;