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): launch desktop AppsFolder apps on Windows (#2862)

Francesco Bonaccifb2a6f60522e
diff --git a/.github/workflows/ci-rust-windows.yml b/.github/workflows/ci-rust-windows.yml
index b75085f3bf..be06bb67e6 100644
--- a/.github/workflows/ci-rust-windows.yml
+++ b/.github/workflows/ci-rust-windows.yml
@@ -77,12 +77,15 @@ jobs:
- name: Run Windows installed-app discovery unit tests
working-directory: libs/cua-driver/rust
run: "cargo test -p platform-windows win32::installed_apps::tests:: --lib --locked"
- - name: Run Windows app-name lookup deadline tests
+ - name: Run Windows app-name lookup tests
working-directory: libs/cua-driver/rust
- run: "cargo test -p platform-windows launch_uwp::tests::apps_folder_lookup_timeout_is_single_flight_and_recovers_after_cooldown --lib --locked -- --exact"
+ run: "cargo test -p platform-windows launch_uwp::tests:: --lib --locked"
- name: Prove unknown app launch stays bounded and responsive
working-directory: libs/cua-driver/rust
run: "cargo test -p cua-driver --test protocol_tools_call_test launch_unknown_app_is_bounded_and_keeps_mcp_session_responsive --locked -- --exact --nocapture"
+ - name: Validate desktop AppsFolder launch with Microsoft Edge
+ working-directory: libs/cua-driver/rust
+ run: "cargo test -p cua-driver --test protocol_tools_call_test launch_edge_from_apps_folder_registration --locked -- --ignored --exact --nocapture"
- name: Run transport-independent authorization and SDK tests
working-directory: libs/cua-driver/rust
run: |
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.rs
index d10a8ca023..3fe4c0cf32 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
@@ -126,6 +126,38 @@ fn launch_unknown_app_is_bounded_and_keeps_mcp_session_responsive() {
);
}
+#[test]
+#[cfg(target_os = "windows")]
+#[ignore = "requires an interactive Windows desktop with Microsoft Edge installed"]
+fn launch_edge_from_apps_folder_registration() {
+ let Some(mut driver) = McpDriver::spawn_with_env(&[
+ ("CUA_DRIVER_PERMISSION_MODE", "unrestricted"),
+ ("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS", "1"),
+ ]) else {
+ return;
+ };
+
+ let launch = driver.call(
+ "launch_app",
+ serde_json::json!({
+ "name": "Microsoft Edge",
+ "urls": ["https://example.com"]
+ }),
+ );
+ assert!(
+ !launch.is_error(),
+ "Edge AppsFolder launch failed: {:?}",
+ launch.raw
+ );
+ assert!(
+ launch.structured()["pid"]
+ .as_u64()
+ .is_some_and(|pid| pid > 0),
+ "Edge AppsFolder launch returned no process id: {:?}",
+ launch.raw
+ );
+}
+
#[test]
#[cfg(any(target_os = "macos", target_os = "windows"))]
fn get_config_and_check_permissions() {
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.rs
index 1564f12baf..673920751d 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
@@ -23,11 +23,11 @@
//! - [`launch_uwp`] — given an AUMID (App User Model ID, the
//! `{PackageFamilyName}!{ApplicationId}` form a packaged app exposes),
//! activate it and return the real pid.
-//! - [`resolve_aumid_by_name`] — given a display name (e.g. `"Notepad"`),
-//! walk `shell:AppsFolder` (the same virtual folder the Start Menu
-//! reads) and return the matching AUMID. Used as the fallback when a
-//! caller passes a plain name and we want to route through the
-//! packaged-app path instead of `ShellExecuteExW`.
+//! - [`resolve_apps_folder_target_by_name`] — given a display name (e.g.
+//! `"Notepad"`), walk `shell:AppsFolder` (the same virtual folder the
+//! Start Menu reads) and return the matching launch target. Packaged apps
+//! use `ActivateApplication`; desktop registrations use their
+//! `shell:AppsFolder` parsing path with `ShellExecuteExW`.
//!
//! Both functions are no-ops / compile errors on non-Windows targets;
//! the module is `#[cfg(target_os = "windows")]`-gated at the crate
@@ -209,11 +209,31 @@ pub fn is_aumid(s: &str) -> bool {
}
}
-/// Single AppsFolder entry: display name + AUMID.
+/// How an entry discovered through `shell:AppsFolder` must be launched.
+///
+/// `PKEY_AppUserModel_ID` is exposed by both packaged and desktop apps. Only
+/// packaged IDs have the `{PackageFamilyName}!{ApplicationId}` shape accepted
+/// by `IApplicationActivationManager`; desktop IDs must be handed back to the
+/// shell namespace that supplied them.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum AppsFolderLaunchTarget {
+ PackagedAumid(String),
+ ShellLaunchPath(String),
+}
+
+fn classify_apps_folder_app_id(app_id: &str) -> AppsFolderLaunchTarget {
+ if is_aumid(app_id) {
+ AppsFolderLaunchTarget::PackagedAumid(app_id.to_owned())
+ } else {
+ AppsFolderLaunchTarget::ShellLaunchPath(format!(r"shell:AppsFolder\{app_id}"))
+ }
+}
+
+/// Single AppsFolder entry: display name + application model ID.
///
/// `lowercase_display_name` is a one-time precomputation of
/// `display_name.to_lowercase()`, populated at enumeration time. The
-/// prefix-match pass in [`resolve_aumid_by_name`] runs over every cached
+/// prefix-match pass in [`resolve_apps_folder_target_by_name`] runs over every cached
/// entry on every lookup; without this field the loop would allocate a
/// fresh lowercased `String` per entry per call (~150–300 allocations
/// per resolve on a stock Win11 install). Caching it once turns the hot
@@ -222,7 +242,7 @@ pub fn is_aumid(s: &str) -> bool {
struct AppsFolderEntry {
display_name: String,
lowercase_display_name: String,
- aumid: String,
+ app_id: String,
}
/// Cached snapshot of all `shell:AppsFolder` entries.
@@ -361,12 +381,12 @@ fn cache() -> &'static RwLock<Option<Vec<AppsFolderEntry>>> {
/// Resolve a display name without allowing an unhealthy shell broker to wedge
/// the async tool stream.
-pub async fn resolve_aumid_by_name_bounded(
+pub async fn resolve_apps_folder_target_by_name_bounded(
display_name: String,
-) -> Result<Option<String>, AppsFolderLookupError> {
+) -> Result<Option<AppsFolderLaunchTarget>, AppsFolderLookupError> {
let result = apps_folder_lookup_gate()
.run(APPS_FOLDER_LOOKUP_TIMEOUT, move || {
- resolve_aumid_by_name(&display_name)
+ resolve_apps_folder_target_by_name(&display_name)
})
.await;
match result {
@@ -397,9 +417,9 @@ pub async fn resolve_aumid_by_name_bounded(
/// `.exe` suffix is stripped before matching so callers carrying a
/// Win32 idiom still hit the packaged display name.
///
-/// Returns `None` if no packaged app matches. The caller should fall
-/// back to `ShellExecuteExW` for plain Win32 apps in that case.
-pub fn resolve_aumid_by_name(display_name: &str) -> Option<String> {
+/// Returns `None` if no AppsFolder entry matches. The caller should fall back
+/// to `ShellExecuteExW` PATH/association lookup in that case.
+pub fn resolve_apps_folder_target_by_name(display_name: &str) -> Option<AppsFolderLaunchTarget> {
// Session 0 short-circuit: `shell:AppsFolder` enumeration goes through
// the interactive shell broker, which doesn't exist in services /
// SSH-launched contexts and causes the underlying COM call to hang
@@ -430,7 +450,7 @@ pub fn resolve_aumid_by_name(display_name: &str) -> Option<String> {
.iter()
.find(|e| e.display_name.eq_ignore_ascii_case(query_stripped))
{
- return Some(hit.aumid.clone());
+ return Some(classify_apps_folder_app_id(&hit.app_id));
}
// Pass 2: shortest case-insensitive prefix match. Uses the
@@ -448,7 +468,7 @@ pub fn resolve_aumid_by_name(display_name: &str) -> Option<String> {
}
}
}
- best.map(|e| e.aumid.clone())
+ best.map(|e| classify_apps_folder_app_id(&e.app_id))
}
fn load_or_get_cache() -> Option<Vec<AppsFolderEntry>> {
@@ -471,10 +491,10 @@ fn load_or_get_cache() -> Option<Vec<AppsFolderEntry>> {
Some(fresh)
}
-/// Walk `shell:AppsFolder` and collect `(display_name, AUMID)` for every
-/// entry that exposes `PKEY_AppUserModel_ID`. Entries without an AUMID
-/// (legacy Win32 shortcuts that happen to be indexed in AppsFolder) are
-/// skipped — those are reachable via `ShellExecuteExW` anyway.
+/// Walk `shell:AppsFolder` and collect `(display_name, app_id)` for every
+/// entry that exposes `PKEY_AppUserModel_ID`. Despite the property name,
+/// desktop apps can expose an explicit application model ID here too; those
+/// entries remain launchable through their `shell:AppsFolder` parsing path.
fn enumerate_apps_folder() -> windows::core::Result<Vec<AppsFolderEntry>> {
let _ = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
@@ -512,11 +532,11 @@ fn enumerate_apps_folder() -> windows::core::Result<Vec<AppsFolderEntry>> {
Err(_) => continue,
};
- let aumid = match unsafe { item2.GetString(&PKEY_APP_USER_MODEL_ID) } {
+ let app_id = match unsafe { item2.GetString(&PKEY_APP_USER_MODEL_ID) } {
Ok(pwstr) => pwstr_to_string_and_free(pwstr),
- Err(_) => continue, // No AUMID → not a packaged/registered app.
+ Err(_) => continue, // No app ID → not a packaged/registered app.
};
- if aumid.is_empty() {
+ if app_id.is_empty() {
continue;
}
@@ -532,7 +552,7 @@ fn enumerate_apps_folder() -> windows::core::Result<Vec<AppsFolderEntry>> {
entries.push(AppsFolderEntry {
display_name,
lowercase_display_name,
- aumid,
+ app_id,
});
}
@@ -622,4 +642,22 @@ mod tests {
assert!(!is_aumid("Pkg!")); // empty AppId half
assert!(!is_aumid("a!b!c")); // two bangs
}
+
+ #[test]
+ fn apps_folder_routes_packaged_ids_to_activation_manager() {
+ assert_eq!(
+ classify_apps_folder_app_id("Microsoft.WindowsNotepad_8wekyb3d8bbwe!App"),
+ AppsFolderLaunchTarget::PackagedAumid(
+ "Microsoft.WindowsNotepad_8wekyb3d8bbwe!App".to_owned()
+ )
+ );
+ }
+
+ #[test]
+ fn apps_folder_routes_desktop_ids_back_through_shell_namespace() {
+ assert_eq!(
+ classify_apps_folder_app_id("MSEdge"),
+ AppsFolderLaunchTarget::ShellLaunchPath(r"shell:AppsFolder\MSEdge".to_owned())
+ );
+ }
}
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_.rs
index 69da996fb6..44c99290bd 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
@@ -1562,6 +1562,12 @@ fn split_launchable_target(s: &str) -> (String, String) {
(trimmed.to_owned(), String::new())
}
+/// Index of the first URL not already consumed as the primary shell target.
+/// An explicit app target consumes no URL; a URLs-only launch consumes index 0.
+fn first_unopened_shell_url_index(has_app_target: bool) -> usize {
+ usize::from(!has_app_target)
+}
+
/// Returns `true` when the launch target names a Chromium-based browser
/// — i.e. one whose hidden launch under `SW_SHOWNOACTIVATE` will trigger
/// renderer-occlusion throttling unless we inject the anti-throttling flags
@@ -1891,9 +1897,9 @@ impl Tool for LaunchAppTool {
the real packaged-process pid — required on Win11 for built-in apps like \
Notepad, Calculator, and Paint, which now ship as Microsoft Store packages \
where the legacy .exe in System32 is a ~7 KB stub that exits immediately. A \
- plain `name` first attempts a `shell:AppsFolder` lookup; on a match it goes \
- through the packaged-app path, otherwise it falls back to ShellExecuteEx's \
- PATH search.\n\n\
+ plain `name` first attempts a `shell:AppsFolder` lookup; packaged matches use \
+ the activation manager while desktop registrations are launched through their \
+ shell parsing path. A miss falls back to ShellExecuteEx's PATH search.\n\n\
Returns the launched app's pid, name, active flag, AND a `windows` array — \
same per-window shape `list_windows` returns. When the launch settles but no \
window has materialized yet (transient; rare), `windows` comes back empty — \
@@ -2093,15 +2099,17 @@ impl Tool for LaunchAppTool {
// 3. `bundle_id` containing `!`: packaged path, AUMID = value
// (Win32 PATH lookups never produce a `!` in the executable
// name, so this is a safe marker of caller intent).
- // 4. `name` with no `path`: try `shell:AppsFolder` lookup; on a
- // hit, packaged path with the resolved AUMID. On miss, fall
- // through to ShellExecuteExW (existing Win32 path).
+ // 4. `name` with no `path`: try `shell:AppsFolder` lookup. A
+ // packaged hit uses the resolved AUMID; a desktop registration
+ // uses `shell:AppsFolder\<AppUserModelID>` via ShellExecuteExW.
+ // On miss, fall through to the existing Win32 path.
// 5. Anything else: existing ShellExecuteExW path.
//
// `path` is intentionally excluded from packaged routing — when
// the caller has a concrete executable in mind they want
// CreateProcess semantics, not Start Menu activation.
let mut name_lookup_missed = false;
+ let mut shell_target_from_name: Option<String> = None;
let aumid_for_uwp: Option<String> = if launch_path_opt.is_some() || path_opt.is_some() {
None
} else if let Some(a) = aumid_opt.clone() {
@@ -2116,10 +2124,19 @@ impl Tool for LaunchAppTool {
// interactive shell broker is unhealthy. Bound it before the
// separate ShellExecuteEx deadline below; the resolver keeps a
// timed-out worker single-flight until COM really returns.
- match crate::launch_uwp::resolve_aumid_by_name_bounded(n.clone()).await {
- Ok(resolved) => {
- name_lookup_missed = resolved.is_none();
- resolved
+ match crate::launch_uwp::resolve_apps_folder_target_by_name_bounded(n.clone()).await {
+ Ok(Some(crate::launch_uwp::AppsFolderLaunchTarget::PackagedAumid(aumid))) => {
+ Some(aumid)
+ }
+ Ok(Some(crate::launch_uwp::AppsFolderLaunchTarget::ShellLaunchPath(
+ launch_path,
+ ))) => {
+ shell_target_from_name = Some(launch_path);
+ None
+ }
+ Ok(None) => {
+ name_lookup_missed = true;
+ None
}
Err(crate::launch_uwp::AppsFolderLookupError::Timeout) => {
return ToolResult::error(format!(
@@ -2140,13 +2157,14 @@ impl Tool for LaunchAppTool {
} else {
None
};
+ let resolved_target = shell_target_from_name.or(target);
// Single launch path. `display` is the human-readable identifier
// we report in the success header; for the packaged path it's
// the AUMID, which is more informative than the display name.
let display = aumid_for_uwp
.clone()
- .or_else(|| target.clone())
+ .or_else(|| resolved_target.clone())
.unwrap_or_else(|| urls.join(", "));
// When the resolved target came from `launch_path` it may carry
@@ -2159,7 +2177,7 @@ impl Tool for LaunchAppTool {
let (target_file_opt, extra_joined) = {
let base_extra = extra_args.join(" ");
if launch_path_opt.is_some() {
- if let Some(t) = target.as_deref() {
+ if let Some(t) = resolved_target.as_deref() {
let (file, args_tail) = split_launchable_target(t);
let combined = if args_tail.is_empty() {
base_extra
@@ -2174,7 +2192,7 @@ impl Tool for LaunchAppTool {
(None, base_extra)
}
} else {
- (target.clone(), base_extra)
+ (resolved_target.clone(), base_extra)
}
};
@@ -2334,7 +2352,11 @@ impl Tool for LaunchAppTool {
// Open any additional URLs in the default browser (no focus
// steal, no pid capture for these — Swift's NSWorkspace flow
// behaves the same way for secondary URLs).
- for url in &urls_clone[urls_clone.len().min(1)..] {
+ // When an app target was launched above, none of the URLs has
+ // been consumed yet. URLs-only launches use the first URL as
+ // `lpFile`, so only their remaining URLs belong here.
+ let first_unopened_url = first_unopened_shell_url_index(target_for_shell.is_some());
+ for url in &urls_clone[first_unopened_url.min(urls_clone.len())..] {
let file = to_wide(url);
let mut url_info = SHELLEXECUTEINFOW {
cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
@@ -9541,7 +9563,9 @@ mod cursor_key_resolution_tests {
#[cfg(test)]
mod launch_focus_restore_decision_tests {
- use super::{should_restore_foreground_after_launch, LaunchTargetShape};
+ use super::{
+ first_unopened_shell_url_index, should_restore_foreground_after_launch, LaunchTargetShape,
+ };
fn empty() -> LaunchTargetShape {
LaunchTargetShape {
@@ -9656,6 +9680,16 @@ mod launch_focus_restore_decision_tests {
// restore needed because nothing was launched.
assert!(!should_restore_foreground_after_launch(empty()));
}
+
+ #[test]
+ fn named_app_launch_forwards_every_url() {
+ assert_eq!(first_unopened_shell_url_index(true), 0);
+ }
+
+ #[test]
+ fn urls_only_launch_does_not_reopen_primary_url() {
+ assert_eq!(first_unopened_shell_url_index(false), 1);
+ }
}
#[cfg(test)]