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): report the current frontmost app on macOS without the overlay (#6182)
injaneity337c62c9a41e
diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/frontmost_app_macos_test.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/frontmost_app_macos_test.rsnew file mode 100644index 0000000000..42e4b6d2c6--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/frontmost_app_macos_test.rs@@ -0,0 +1,126 @@+//! A long-lived macOS daemon without the cursor overlay must report the app+//! that is in front now, not the one that was in front at its first read+//! (#5045). The testkit daemon is `serve --no-overlay` started as a child+//! process, which runs no AppKit main run loop. The oracle is LaunchServices+//! through `lsappinfo`, which does not depend on this process's run loop.+//!+//! Run with:+//! `cargo test -p cua-driver-e2e --test frontmost_app_macos_test -- --ignored --nocapture --test-threads=1`++#![cfg(target_os = "macos")]++use std::process::Command;+use std::time::{Duration, Instant};++use cua_driver_testkit::{Driver, McpDriver};++fn lsappinfo(args: &[&str]) -> String {+ let output = Command::new("lsappinfo")+ .args(args)+ .output()+ .expect("run lsappinfo");+ assert!(output.status.success(), "lsappinfo {args:?} failed");+ String::from_utf8_lossy(&output.stdout).trim().to_owned()+}++/// LaunchServices' frontmost application pid, e.g. `"pid"=468`.+fn front_pid() -> Option<i64> {+ let asn = lsappinfo(&["front"]);+ lsappinfo(&["info", "-only", "pid", &asn])+ .rsplit('=')+ .next()?+ .trim()+ .parse()+ .ok()+}++fn pid_of_app(name: &str) -> Option<i64> {+ let info = lsappinfo(&["info", "-only", "pid", name]);+ info.rsplit('=').next()?.trim().parse().ok()+}++/// Bring `app` to the front through LaunchServices and return its pid once+/// it holds the front.+fn bring_app_to_front(app: &str) -> i64 {+ let deadline = Instant::now() + Duration::from_secs(20);+ loop {+ assert!(+ Command::new("open")+ .args(["-a", app])+ .status()+ .expect("run open")+ .success(),+ "open -a {app} failed"+ );+ std::thread::sleep(Duration::from_millis(500));+ if let Some(pid) = pid_of_app(app).filter(|pid| front_pid() == Some(*pid)) {+ return pid;+ }+ assert!(+ Instant::now() < deadline,+ "{app} did not take the front; front pid is {:?}",+ front_pid()+ );+ }+}++/// The pid `list_apps` marks `active`, read while the oracle front pid holds+/// still around the call. Returns `(reported, oracle)`.+fn active_pid(driver: &mut McpDriver) -> (Option<i64>, i64) {+ let deadline = Instant::now() + Duration::from_secs(10);+ loop {+ let before = front_pid();+ let response = driver.call("list_apps", serde_json::json!({}));+ assert!(+ !response.is_error(),+ "list_apps failed: {}",+ response.text()+ );+ if let Some(oracle) = before.filter(|pid| front_pid() == Some(*pid)) {+ let reported = response.structured()["apps"]+ .as_array()+ .expect("list_apps apps array")+ .iter()+ .find(|app| app["active"] == true)+ .and_then(|app| app["pid"].as_i64());+ return (reported, oracle);+ }+ assert!(+ Instant::now() < deadline,+ "the front app kept changing around list_apps"+ );+ }+}++struct QuitCalculator;++impl Drop for QuitCalculator {+ fn drop(&mut self) {+ let _ = Command::new("pkill").args(["-x", "Calculator"]).status();+ }+}++#[test]+#[ignore = "needs a logged-in macOS desktop; switches the frontmost app"]+fn no_overlay_daemon_reports_the_current_frontmost_app() {+ bring_app_to_front("Finder");+ let mut driver = McpDriver::spawn().expect("start a no-overlay cua-driver daemon");++ let (reported, finder) = active_pid(&mut driver);+ assert_eq!(reported, Some(finder), "first read: Finder is in front");++ let _quit = QuitCalculator;+ let calculator = bring_app_to_front("Calculator");+ let (reported, oracle) = active_pid(&mut driver);+ assert_eq!(oracle, calculator);+ assert_eq!(+ reported,+ Some(calculator),+ "list_apps kept the app that was in front at the daemon's first read"+ );++ let finder = bring_app_to_front("Finder");+ let (reported, oracle) = active_pid(&mut driver);+ assert_eq!(oracle, finder);+ assert_eq!(reported, Some(finder), "switch back to Finder");+}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 f2727365c0..227e893db2 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@@ -166,13 +166,11 @@ fn list_running_apps_from_process_table() -> Vec<AppInfo> {// unreadable; either way there is nothing to act on..filter_map(|pid| path_of_pid(pid).map(|path| (pid, path))).collect();- // `active` has the same staleness exposure as the running list:- // `NSWorkspace.frontmostApplication` is maintained by the same- // notification machinery. So AppKit's answer is used only when the kernel- // agrees that pid is still alive, and the fallback is the window server's- // own front-to-back order — which the Space evidence showed to be accurate- // when the app list was not (`list_space_windows` over rcdp reported- // reality while `list_apps` did not).+ // The front pid is used only when the kernel agrees it is still alive,+ // and the fallback is the window server's own front-to-back order — which+ // the Space evidence showed to be accurate when the app list was not+ // (`list_space_windows` over rcdp reported reality while `list_apps` did+ // not).let front = frontmost_pid().filter(|p| live.contains(p)).or_else(|| {crate::windows::visible_windows().into_iter()@@ -935,17 +933,15 @@ fn read_app_plist(plist_path: &std::path::Path) -> Option<AppInfo> {})}-/// Return the pid of the current frontmost application via-/// `NSWorkspace.shared.frontmostApplication`. `None` if there isn't one-/// (rare — e.g. screensaver).+/// Return the pid of the process WindowServer has frontmost now. `None` if+/// there isn't one (rare — e.g. screensaver).+///+/// Not `NSWorkspace.frontmostApplication`: AppKit updates that value only when+/// this process's main run loop delivers activation notices. A daemon without+/// the cursor overlay (`serve --no-overlay`, `mcp --direct`) runs no such loop,+/// so it kept the app that was in front at its first read (#5045).pub fn frontmost_pid() -> Option<i32> {- use objc2_app_kit::NSWorkspace;- unsafe {- let ws = NSWorkspace::sharedWorkspace();- let app = ws.frontmostApplication()?;- let pid: i32 = app.processIdentifier();- Some(pid)- }+ crate::input::skylight::front_process_pid()}/// Re-activate the app with `pid` viadiff --git a/scripts/ci/macos/run-rust-e2e.sh b/scripts/ci/macos/run-rust-e2e.shindex c2e9f0928e..de7a7ae1c8 100755--- a/scripts/ci/macos/run-rust-e2e.sh+++ b/scripts/ci/macos/run-rust-e2e.sh@@ -425,6 +425,9 @@ EOFrun_test bring-to-front env -u CUA_E2E_RECORDINGS_ROOT \cargo test -p cua-driver-e2e --test bring_to_front_macos_test -- \--ignored --nocapture --test-threads=1+ run_test frontmost-app env -u CUA_E2E_RECORDINGS_ROOT \+ cargo test -p cua-driver-e2e --test frontmost_app_macos_test -- \+ --ignored --nocapture --test-threads=1# Tk derives click locations from the hardware pointer. The rows skip with# an explicit reason when python3 lacks tkinter (hosted images may not ship# it); set CUA_TEST_REQUIRE_TK=1 where Tk is provisioned.