Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-driver): report live running state for accessory apps (#3456)

Mike Evdokimov0d61146a4c6b
diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
index e4c8207a23..ce362d4f03 100644
--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx
+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
@@ -42,7 +42,7 @@ List macOS apps — both currently running and installed-but-not-running — wit
- kind: `"desktop"` for `.app` bundles on macOS.
- last_used: RFC3339 timestamp from the bundle's filesystem mtime, when readable; otherwise null.
-Only apps with NSApplicationActivationPolicyRegular are included — background helpers and system UI agents are filtered out. Installed apps come from scanning /Applications, /Applications/Utilities, ~/Applications, /System/Applications, and /System/Applications/Utilities.
+Standalone running entries include only apps with NSApplicationActivationPolicyRegular — background helpers and system UI agents are filtered out. Installed apps resolve their running/pid state against all live processes by bundle identifier, so an installed app whose process runs as an accessory (LSUIElement / menu-bar apps, e.g. Cua Driver itself) still reports its live pid. Installed apps come from scanning /Applications, /Applications/Utilities, ~/Applications, /System/Applications, and /System/Applications/Utilities.
Use this for "is X installed?" as well as "is X running?". For 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.
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.rs
index a4e8bfc296..0903d2aa9a 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
@@ -41,43 +41,79 @@ pub struct AppInfo {
/// This stays entirely inside AppKit so listing or classifying an application
/// never triggers the macOS Automation permission for System Events.
pub fn list_running_apps() -> Vec<AppInfo> {
- list_running_apps_native()
+ enumerate_running_apps().0
}
-fn list_running_apps_native() -> Vec<AppInfo> {
+/// Live `(pid, active, bundle path)` entries per bundle identifier.
+type RunningAppStates = std::collections::HashMap<String, Vec<(i32, bool, Option<String>)>>;
+
+/// Single walk over `NSWorkspace.runningApplications` producing both views the
+/// app listing needs from ONE snapshot:
+///
+/// * standalone entries — `Regular`-policy apps only, so background helpers
+/// and system UI agents stay out of the list. This stays entirely inside
+/// AppKit so listing or classifying an application never triggers the
+/// macOS Automation permission for System Events.
+/// * live `(pid, active)` state for every process that reports a bundle
+/// identifier, across ALL activation policies. The `Regular`-only filter
+/// above must not decide whether an *installed* app is running: bundles
+/// shipped with `LSUIElement = true` (Cua Driver itself, many menu-bar
+/// apps) run as `Accessory`, never enter the standalone list, and would
+/// otherwise surface as `running = false / pid = 0` while windows and the
+/// accessibility tree see the live process (#3060).
+fn enumerate_running_apps() -> (Vec<AppInfo>, RunningAppStates) {
use objc2_app_kit::{NSApplicationActivationPolicy, NSWorkspace};
- let mut apps = Vec::new();
+ let mut standalone = Vec::new();
+ let mut states = std::collections::HashMap::new();
unsafe {
let workspace = NSWorkspace::sharedWorkspace();
let running = workspace.runningApplications();
for index in 0..running.count() {
let app = running.objectAtIndex(index);
- if app.isTerminated()
- || app.activationPolicy() != NSApplicationActivationPolicy::Regular
- {
+ if app.isTerminated() {
+ continue;
+ }
+ let pid = app.processIdentifier();
+ if pid <= 0 {
+ continue;
+ }
+ let bundle_id = app.bundleIdentifier().map(|value| value.to_string());
+ let launch_path = app
+ .bundleURL()
+ .and_then(|url| url.path())
+ .map(|path| path.to_string());
+ if let Some(bid) = bundle_id.as_deref() {
+ if !bid.is_empty() {
+ states.entry(bid.to_owned()).or_insert_with(Vec::new).push((
+ pid,
+ app.isActive(),
+ launch_path.clone(),
+ ));
+ }
+ }
+ if app.activationPolicy() != NSApplicationActivationPolicy::Regular {
continue;
}
let Some(name) = app.localizedName().map(|value| value.to_string()) else {
continue;
};
- let pid = app.processIdentifier();
- if name.is_empty() || pid <= 0 {
+ if name.is_empty() {
continue;
}
- apps.push(AppInfo {
+ standalone.push(AppInfo {
name,
pid,
- bundle_id: app.bundleIdentifier().map(|value| value.to_string()),
+ bundle_id,
running: true,
active: app.isActive(),
- launch_path: None,
+ launch_path,
kind: Some("desktop".to_owned()),
last_used: None,
});
}
}
- apps
+ (standalone, states)
}
/// Launch an app by bundle ID via NSWorkspace, background only (no focus
@@ -425,8 +461,30 @@ fn bundle_id_for_app_path(app_path: &str) -> Option<String> {
/// * `launch_path` (filesystem `.app` path when known, else `None`),
/// * `kind` (`"desktop"` on macOS).
pub fn list_all_apps() -> Vec<AppInfo> {
- let mut running = list_running_apps();
+ let (running, running_states) = enumerate_running_apps();
let installed = scan_installed_apps();
+ merge_app_lists(running, installed, &running_states)
+}
+
+/// Pure merge behind [`list_all_apps`] — extracted so the identity rules
+/// are testable without a live NSWorkspace:
+///
+/// * standalone entries keep the `Regular`-only contract of
+/// [`list_running_apps`] (helpers and UI agents stay out of the list);
+/// * installed entries resolve `running` / `pid` / `active` against the
+/// all-policies running-state map by bundle id and bundle path, so an installed `.app`
+/// whose process runs as an accessory reports its live state instead
+/// of the `pid = 0` scan defaults (#3060). Exact bundle paths distinguish
+/// installed copies that share an identifier. Bundle-id-only fallback is
+/// allowed only when the installed copy is unambiguous;
+/// * installed entries already covered by a standalone running entry are
+/// dropped — the standalone entry wins and is backfilled with the
+/// `launch_path` / `last_used` the installed scan resolved.
+pub(crate) fn merge_app_lists(
+ mut running: Vec<AppInfo>,
+ mut installed: Vec<AppInfo>,
+ running_states: &RunningAppStates,
+) -> Vec<AppInfo> {
// Lookup: bundle_id → (launch_path, last_used) from the installed scan.
let installed_by_bundle: std::collections::HashMap<String, (Option<String>, Option<String>)> =
installed
@@ -451,10 +509,47 @@ pub fn list_all_apps() -> Vec<AppInfo> {
}
}
+ let installed_bundle_counts = installed
+ .iter()
+ .filter_map(|app| app.bundle_id.clone())
+ .fold(
+ std::collections::HashMap::<String, usize>::new(),
+ |mut counts, bundle| {
+ *counts.entry(bundle).or_default() += 1;
+ counts
+ },
+ );
+
+ // Upgrade installed entries whose live process runs outside the Regular
+ // list. Prefer the exact bundle path so duplicate debug/release copies do
+ // not all inherit one process's live state.
+ for app in installed.iter_mut() {
+ let Some(bundle_id) = app.bundle_id.as_deref() else {
+ continue;
+ };
+ let Some(candidates) = running_states.get(bundle_id) else {
+ continue;
+ };
+ let exact = app.launch_path.as_deref().and_then(|installed_path| {
+ candidates
+ .iter()
+ .find(|(_, _, live_path)| live_path.as_deref() == Some(installed_path))
+ });
+ let selected = exact.or_else(|| {
+ (installed_bundle_counts.get(bundle_id) == Some(&1))
+ .then(|| candidates.last())
+ .flatten()
+ });
+ if let Some(&(pid, active, _)) = selected {
+ app.running = true;
+ app.pid = pid;
+ app.active = active;
+ }
+ }
+
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
@@ -462,9 +557,8 @@ pub fn list_all_apps() -> Vec<AppInfo> {
.is_some_and(|b| running_bundles.contains(b))
});
- let mut all = running;
- all.extend(installed);
- all
+ running.extend(installed);
+ running
}
fn scan_installed_apps() -> Vec<AppInfo> {
@@ -689,7 +783,135 @@ pub fn format_app_list(apps: &[AppInfo]) -> String {
#[cfg(test)]
mod tests {
- use super::finder_folder_handoff;
+ use super::{finder_folder_handoff, merge_app_lists, AppInfo};
+
+ fn app(name: &str, pid: i32, bundle: Option<&str>, running: bool) -> AppInfo {
+ AppInfo {
+ name: name.to_owned(),
+ pid,
+ bundle_id: bundle.map(str::to_owned),
+ running,
+ active: false,
+ launch_path: None,
+ kind: None,
+ last_used: None,
+ }
+ }
+
+ fn states(pairs: &[(&str, i32, bool, Option<&str>)]) -> super::RunningAppStates {
+ pairs.iter().fold(
+ super::RunningAppStates::new(),
+ |mut states, (bundle, pid, active, path)| {
+ states.entry((*bundle).to_owned()).or_default().push((
+ *pid,
+ *active,
+ path.map(str::to_owned),
+ ));
+ states
+ },
+ )
+ }
+
+ #[test]
+ fn installed_app_running_as_accessory_reports_live_state() {
+ // The #3060 shape: CuaDriver.app ships LSUIElement=true, so its live
+ // process runs as Accessory and never enters the Regular list.
+ let mut entry = app("Cua Driver", 0, Some("com.trycua.driver"), false);
+ entry.launch_path = Some("/Applications/CuaDriver.app".to_owned());
+ let merged = merge_app_lists(
+ vec![],
+ vec![entry],
+ &states(&[(
+ "com.trycua.driver",
+ 31438,
+ false,
+ Some("/Applications/CuaDriver.app"),
+ )]),
+ );
+ assert_eq!(merged.len(), 1);
+ assert!(merged[0].running);
+ assert_eq!(merged[0].pid, 31438);
+ // The upgrade must not clobber the fields the installed scan owns.
+ assert_eq!(
+ merged[0].launch_path.as_deref(),
+ Some("/Applications/CuaDriver.app")
+ );
+ }
+
+ #[test]
+ fn installed_app_not_running_keeps_scan_defaults() {
+ let merged = merge_app_lists(
+ vec![],
+ vec![app("TextEdit", 0, Some("com.apple.TextEdit"), false)],
+ &states(&[]),
+ );
+ assert_eq!(merged.len(), 1);
+ assert!(!merged[0].running);
+ assert_eq!(merged[0].pid, 0);
+ }
+
+ #[test]
+ fn regular_running_app_wins_over_installed_entry() {
+ let running = vec![app("Safari", 100, Some("com.apple.Safari"), true)];
+ let installed = vec![{
+ let mut entry = app("Safari", 0, Some("com.apple.Safari"), false);
+ entry.launch_path = Some("/Applications/Safari.app".to_owned());
+ entry
+ }];
+ let merged = merge_app_lists(
+ running,
+ installed,
+ &states(&[(
+ "com.apple.Safari",
+ 100,
+ true,
+ Some("/Applications/Safari.app"),
+ )]),
+ );
+ assert_eq!(merged.len(), 1);
+ assert!(merged[0].running);
+ assert_eq!(merged[0].pid, 100);
+ assert_eq!(
+ merged[0].launch_path.as_deref(),
+ Some("/Applications/Safari.app")
+ );
+ }
+
+ #[test]
+ fn accessory_process_without_installed_bundle_adds_no_entry() {
+ // A background helper with a bundle id but no installed .app must not
+ // materialize a row just because it appears in the states map.
+ let merged = merge_app_lists(
+ vec![],
+ vec![],
+ &states(&[("dev.helper.agent", 9, false, None)]),
+ );
+ assert!(merged.is_empty());
+ }
+
+ #[test]
+ fn duplicate_bundle_ids_upgrade_only_the_live_bundle_path() {
+ let mut release = app("Cua Driver", 0, Some("com.trycua.driver"), false);
+ release.launch_path = Some("/Applications/CuaDriver.app".to_owned());
+ let mut debug = app("Cua Driver", 0, Some("com.trycua.driver"), false);
+ debug.launch_path = Some("/Users/test/CuaDriver.app".to_owned());
+
+ let merged = merge_app_lists(
+ vec![],
+ vec![release, debug],
+ &states(&[(
+ "com.trycua.driver",
+ 42,
+ false,
+ Some("/Users/test/CuaDriver.app"),
+ )]),
+ );
+
+ assert!(!merged[0].running);
+ assert_eq!(merged[0].pid, 0);
+ assert!(merged[1].running);
+ assert_eq!(merged[1].pid, 42);
+ }
#[test]
fn finder_folder_handoff_is_narrowly_selected() {
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.rs
index 79d60feb9b..e9fac6683d 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
@@ -21,10 +21,15 @@ fn def() -> &'static ToolDef {
- kind: `\"desktop\"` for `.app` bundles on macOS.\n\
- last_used: RFC3339 timestamp from the bundle's filesystem mtime, \
when readable; otherwise null.\n\n\
- Only apps with NSApplicationActivationPolicyRegular are included — \
- background helpers and system UI agents are filtered out. Installed \
- apps come from scanning /Applications, /Applications/Utilities, \
- ~/Applications, /System/Applications, and /System/Applications/Utilities.\n\n\
+ Standalone running entries include only apps with \
+ NSApplicationActivationPolicyRegular — background helpers and \
+ system UI agents are filtered out. Installed apps resolve their \
+ running/pid state against all live processes by bundle identifier, \
+ so an installed app whose process runs as an accessory \
+ (LSUIElement / menu-bar apps, e.g. Cua Driver itself) still reports \
+ its live pid. Installed apps come from scanning /Applications, \
+ /Applications/Utilities, ~/Applications, /System/Applications, and \
+ /System/Applications/Utilities.\n\n\
Use this for \"is X installed?\" as well as \"is X running?\". For \
per-window state — on-screen, on-current-Space, minimized, \
window titles — call list_windows instead. For just opening an \