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.

feat(launch_app): UWP/packaged-app support on Windows (#1544)

Francesco Bonacci7a4d908942b2
diff --git a/libs/cua-driver-rs/PARITY.md b/libs/cua-driver-rs/PARITY.md
index 4ef3cddca9..bd5d3043c8 100644
--- a/libs/cua-driver-rs/PARITY.md
+++ b/libs/cua-driver-rs/PARITY.md
@@ -502,10 +502,27 @@ Windows's `click` takes `{button: enum}` instead. Rationale:
listing per-window `"- <title|(no title)> [window_id: ID]"` lines
and a `→ Call get_window_state(...)` hint, matching Swift verbatim.
4. **`bundle_id` parameter** — accepted as an alias for `name` (Windows
- has no bundle-identifier concept). Cross-platform callers can use
- the same field name.
+ has no bundle-identifier concept), with one extra meaning on Win11:
+ when the value matches an AUMID (`{PackageFamilyName}!{ApplicationId}`,
+ contains `!`), `launch_app` routes through
+ `IApplicationActivationManager::ActivateApplication` and returns
+ the real packaged-app pid. Without this routing, Win11 launches of
+ built-in apps (Notepad, Calculator, Paint, …) return the pid of
+ the ~7 KB System32 stub that exits within milliseconds — useless
+ for `list_windows`, `get_window_state`, etc.
+4a. **`name` → packaged-app lookup (Win11)** — `name` is now first
+ resolved against `shell:AppsFolder` (the Start Menu's "all apps"
+ index, cached for the lifetime of the driver process). On a hit
+ the lookup yields an AUMID and goes through the packaged path
+ (see #4); on a miss it falls back to `ShellExecuteExW`'s PATH
+ search. `.exe` suffix is stripped before matching so `"notepad"`
+ and `"notepad.exe"` both resolve to the packaged Notepad.
+4b. **`aumid` parameter** — optional explicit AUMID; cleaner than
+ overloading `bundle_id` when the caller has the AUMID in hand.
+ Takes precedence over `bundle_id`/`name`.
5. **`additional_arguments`** — honored, passed as `lpParameters` to
- `ShellExecuteExW`.
+ `ShellExecuteExW` (Win32 path) or as the activation `arguments`
+ string to `ActivateApplication` (packaged path).
6. **Window-resolution retry** — ports Swift's 5-attempt 100/200ms
retry to absorb Win32 window-creation lag after `ShellExecuteEx`
returns.
@@ -527,9 +544,15 @@ Windows's `click` takes `{button: enum}` instead. Rationale:
`launch_app_parity.exe` launches Notepad:
- Header `"✅ Launched notepad.exe (pid 30612) in background."` ✓
-- `structuredContent.pid` is the actual ShellExecuteEx pid ✓
-- `bundle_id: null`, `running: true`, `active: false` ✓
+- `structuredContent.pid` is the actual ShellExecuteEx pid (Win10)
+ or the real packaged-app pid (Win11, after AppsFolder lookup) ✓
+- `bundle_id: null` on Win10 / unpackaged Notepad; AUMID string on
+ Win11 packaged Notepad ✓
+- `running: true`, `active: false` ✓
- Notepad killed on test exit. ✓
+- On Win11 the parity binary additionally exercises an explicit-AUMID
+ launch via `bundle_id="Microsoft.WindowsNotepad_8wekyb3d8bbwe!App"`
+ and asserts `bundle_id` round-trips identically. ✓
### Fixed (macOS)
diff --git a/libs/cua-driver-rs/crates/platform-windows/Cargo.toml b/libs/cua-driver-rs/crates/platform-windows/Cargo.toml
index 7dd6da7fb6..4273015054 100644
--- a/libs/cua-driver-rs/crates/platform-windows/Cargo.toml
+++ b/libs/cua-driver-rs/crates/platform-windows/Cargo.toml
@@ -34,6 +34,9 @@ windows = { version = "0.58", features = [
"Win32_System_Com",
"Win32_Storage_Xps",
"Win32_UI_Shell",
+ # IShellItem2::GetString — used by launch_uwp::resolve_aumid_by_name to
+ # read PKEY_AppUserModel_ID off entries enumerated from shell:AppsFolder.
+ "Win32_UI_Shell_PropertiesSystem",
"Win32_Media",
"Win32_System_Registry",
# `cua-driver doctor` interactive-session probe:
diff --git a/libs/cua-driver-rs/crates/platform-windows/examples/launch_app_parity.rs b/libs/cua-driver-rs/crates/platform-windows/examples/launch_app_parity.rs
index 38a4e882b1..4667014995 100644
--- a/libs/cua-driver-rs/crates/platform-windows/examples/launch_app_parity.rs
+++ b/libs/cua-driver-rs/crates/platform-windows/examples/launch_app_parity.rs
@@ -7,6 +7,13 @@
//! - At least one entry in `windows` array OR `windows: []` if the window
//! didn't materialize within the 5×200ms retry budget.
//!
+//! On Win11 we additionally try the packaged-app path: an explicit AUMID
+//! via `bundle_id` should return a non-stub pid (i.e. the real Notepad
+//! UWP process). The legacy `notepad.exe` smoke-test above stays for
+//! Win10 / non-packaged-Notepad coverage; both should pass on Win11
+//! because the plain `name` path now goes through the AppsFolder
+//! lookup first.
+//!
//! Cleans up: terminates the launched pid before exit.
use std::io::{Read, Write};
@@ -68,10 +75,17 @@ fn main() {
println!("Structured: pid={pid} name={name:?} running={running} active={active} windows={} bundle_id={bundle_id}", windows.len());
- assert!(pid > 0, "pid must be captured from ShellExecuteEx");
+ assert!(pid > 0, "pid must be captured (ShellExecuteEx pid or packaged-app pid)");
assert!(running, "running must be true");
assert!(!active, "active must be false (background launch — Swift's invariant)");
- assert!(bundle_id.is_null(), "bundle_id must be null on Windows");
+ // bundle_id is either null (plain Win32 launch — Win10 / unpackaged
+ // Notepad) or an AUMID string (Win11 — `notepad` resolved through
+ // shell:AppsFolder to the packaged Notepad). Both are correct.
+ assert!(
+ bundle_id.is_null()
+ || bundle_id.as_str().map(|s| s.contains('!')).unwrap_or(false),
+ "bundle_id must be null OR an AUMID (`pkg!app`); got {bundle_id}"
+ );
// Cleanup: kill notepad.
std::process::Command::new("taskkill")
@@ -80,6 +94,77 @@ fn main() {
.stderr(std::process::Stdio::null())
.status().ok();
+ // 3. AUMID path (Win11 only — skipped silently on Win10 since the
+ // AUMID won't be installed there).
+ let aumid = "Microsoft.WindowsNotepad_8wekyb3d8bbwe!App";
+ let resp_aumid = req(
+ &mut pipe,
+ &format!(r#"{{"method":"call","name":"launch_app","args":{{"bundle_id":"{aumid}"}}}}"#),
+ );
+ let v_aumid: serde_json::Value = serde_json::from_str(resp_aumid.trim()).expect("parse");
+ let pid_aumid = v_aumid
+ .pointer("/result/structuredContent/pid")
+ .and_then(|n| n.as_u64());
+ let bundle_id_aumid = v_aumid.pointer("/result/structuredContent/bundle_id");
+
+ // Always reap the pid first — even if the bundle_id round-trip
+ // check below fails, leaving Notepad running across runs would
+ // pollute later parity invocations.
+ if let Some(p) = pid_aumid.filter(|p| *p > 0) {
+ std::process::Command::new("taskkill")
+ .args(["/PID", &p.to_string(), "/F"])
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .status().ok();
+ }
+
+ match bundle_id_aumid {
+ Some(b) => {
+ let p = pid_aumid.expect("pid must be present when bundle_id is");
+ assert!(p > 0, "AUMID launch returned bundle_id but pid={p}");
+ println!("AUMID launch returned pid={p}, bundle_id={b}");
+ assert_eq!(
+ b.as_str(),
+ Some(aumid),
+ "bundle_id must round-trip the AUMID passed in"
+ );
+ }
+ None => {
+ // No bundle_id in structuredContent — the AUMID launch
+ // returned an error (the daemon serialises tool errors as
+ // {ok:false, error:"…"}, no `result` field). Inspect the
+ // error text: the *only* acceptable cause for skipping is
+ // "this AUMID is not installed on this host" (Win10, or a
+ // stripped Win11 image without packaged Notepad). Anything
+ // else — COM init failure, IApplicationActivationManager
+ // broken, packaging metadata corrupt — is a real regression
+ // that must surface, not be swallowed.
+ let err_text = v_aumid
+ .pointer("/error")
+ .and_then(|e| e.as_str())
+ .or_else(|| v_aumid.pointer("/result/content/0/text").and_then(|t| t.as_str()))
+ .unwrap_or("");
+ let err_lower = err_text.to_lowercase();
+ // Windows surfaces "AUMID not registered for current user"
+ // as E_INVALIDARG (HRESULT 0x80070057, "The parameter is
+ // incorrect."). That HRESULT *is* the canonical sentinel for
+ // "not installed" from ActivateApplication. Also accept the
+ // human-readable substrings in case a wrapper rephrases.
+ let looks_like_not_installed = err_lower.contains("not installed")
+ || err_lower.contains("not found")
+ || err_lower.contains("not registered")
+ || err_text.contains("0x80070057")
+ || err_text.contains("E_INVALIDARG")
+ || err_lower.contains("the parameter is incorrect");
+ assert!(
+ looks_like_not_installed,
+ "AUMID launch of {aumid:?} failed with an unexpected error \
+ (not a 'not installed' signal): {err_text:?}"
+ );
+ println!("AUMID path: packaged Notepad not installed on this host; skipped ({err_text:?})");
+ }
+ }
+
println!("\n✅ PASS: launch_app text format, pid capture, and Swift invariants verified");
}
diff --git a/libs/cua-driver-rs/crates/platform-windows/src/launch_uwp.rs b/libs/cua-driver-rs/crates/platform-windows/src/launch_uwp.rs
new file mode 100644
index 0000000000..fad6bfaf18
--- /dev/null
+++ b/libs/cua-driver-rs/crates/platform-windows/src/launch_uwp.rs
@@ -0,0 +1,326 @@
+//! Launch packaged (Microsoft Store / UWP / MSIX) apps on Windows via
+//! `IApplicationActivationManager::ActivateApplication`.
+//!
+//! ## Why this exists
+//!
+//! On Win11 many built-in apps (Notepad, Calculator, Paint, …) ship as
+//! packaged apps. The legacy `notepad.exe` / `calc.exe` / `mspaint.exe`
+//! in `C:\Windows\System32\` are now ~7 KB stubs that activate the
+//! packaged equivalent and exit almost immediately. Calling
+//! `ShellExecuteExW("notepad")` and reading `GetProcessId(hProcess)`
+//! therefore returns the **stub's** pid — gone within milliseconds —
+//! rather than the pid of the actual UWP process the user can see.
+//! `list_windows(pid)` for that stub pid is always empty.
+//!
+//! `IApplicationActivationManager::ActivateApplication` is the
+//! Microsoft-canonical API for launching packaged apps from outside a
+//! packaged context. It returns the **real** UWP process pid via its
+//! `pid` out-parameter — the pid whose `MainWindowHandle` is the
+//! window the user interacts with.
+//!
+//! ## Two entry points
+//!
+//! - [`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`.
+//!
+//! Both functions are no-ops / compile errors on non-Windows targets;
+//! the module is `#[cfg(target_os = "windows")]`-gated at the crate
+//! root.
+
+use std::sync::{OnceLock, RwLock};
+
+use windows::core::{Interface, GUID, HSTRING, PCWSTR, PWSTR};
+use windows::Win32::System::Com::{
+ CoCreateInstance, CoInitializeEx, CoTaskMemFree, IBindCtx, CLSCTX_LOCAL_SERVER,
+ COINIT_APARTMENTTHREADED,
+};
+use windows::Win32::UI::Shell::PropertiesSystem::PROPERTYKEY;
+use windows::Win32::UI::Shell::{
+ ApplicationActivationManager, IApplicationActivationManager, IEnumShellItems, IShellItem,
+ IShellItem2, SHCreateItemFromParsingName, AO_NONE, BHID_EnumItems, SIGDN_NORMALDISPLAY,
+};
+
+/// `PKEY_AppUserModel_ID` (System.AppUserModel.ID) — the property key whose
+/// string value on each `shell:AppsFolder` entry is the AUMID we need to
+/// hand to `ActivateApplication`.
+///
+/// Defined inline (rather than pulled from `Win32_Storage_EnhancedStorage`)
+/// to keep the windows-rs feature surface narrow — adding an entire
+/// `Storage` feature subtree just for one constant is not worth the
+/// build-time + binary-size cost.
+///
+/// Reference: `propkey.h` —
+/// `DEFINE_PROPERTYKEY(PKEY_AppUserModel_ID,
+/// 0x9F4C2855, 0x9F79, 0x4B39, 0xA8,0xD0, 0xE1,0xD4,0x2D,0xE1,0xD5,0xF3, 5);`
+const PKEY_APP_USER_MODEL_ID: PROPERTYKEY = PROPERTYKEY {
+ fmtid: GUID::from_u128(0x9F4C2855_9F79_4B39_A8D0_E1D42DE1D5F3),
+ pid: 5,
+};
+
+/// Activate a packaged app by AUMID. Returns the **real** process id of
+/// the spawned UWP / MSIX process (not a stub pid).
+///
+/// `args` is forwarded verbatim as the activation `arguments` string;
+/// pass `""` if the app takes no launch arguments. `AO_NONE` keeps
+/// behavior identical to a user-driven Start Menu click — splash screen
+/// shown, error UI shown on failure, default activation kind.
+///
+/// Errors propagate the `HRESULT` from `ActivateApplication`. The most
+/// common failures:
+/// - `E_INVALIDARG` — AUMID not installed for the current user
+/// - `HRESULT 0x80073D54` (`ERROR_INSTALL_RESOLVE_DEPENDENCY_FAILED`) —
+/// packaged dependency unresolved (rare)
+/// - Any COM-init failure on a thread that has previously been
+/// initialized with a conflicting apartment model
+pub fn launch_uwp(aumid: &str, args: &str) -> windows::core::Result<u32> {
+ // Apartment model: AAM is a local-server COM object that historically
+ // requires STA on the calling thread. `CoInitializeEx` is idempotent
+ // per-thread; its HRESULT is intentionally discarded — if the thread
+ // was previously initialized with a different model, the subsequent
+ // CoCreateInstance call will surface a clear error.
+ let _ = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
+
+ let manager: IApplicationActivationManager = unsafe {
+ CoCreateInstance(&ApplicationActivationManager, None, CLSCTX_LOCAL_SERVER)?
+ };
+
+ let aumid_h = HSTRING::from(aumid);
+ let args_h = HSTRING::from(args);
+
+ let pid = unsafe {
+ manager.ActivateApplication(
+ PCWSTR(aumid_h.as_ptr()),
+ PCWSTR(args_h.as_ptr()),
+ AO_NONE,
+ )?
+ };
+
+ Ok(pid)
+}
+
+/// Heuristic for "this string looks like an AUMID".
+///
+/// An AUMID is `{PackageFamilyName}!{ApplicationId}`, e.g.
+/// `Microsoft.WindowsNotepad_8wekyb3d8bbwe!App`. The unambiguous
+/// marker is the literal `!` separator — no Win32 path or executable
+/// name legitimately contains `!`, so its presence is a safe signal
+/// the caller intends packaged-app activation.
+pub fn is_aumid(s: &str) -> bool {
+ // Must contain exactly one `!`, with non-empty halves on each side.
+ let mut parts = s.split('!');
+ match (parts.next(), parts.next(), parts.next()) {
+ (Some(pfn), Some(app_id), None) => !pfn.is_empty() && !app_id.is_empty(),
+ _ => false,
+ }
+}
+
+/// Single AppsFolder entry: display name + AUMID.
+///
+/// `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
+/// 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
+/// path into a borrow.
+#[derive(Clone)]
+struct AppsFolderEntry {
+ display_name: String,
+ lowercase_display_name: String,
+ aumid: String,
+}
+
+/// Cached snapshot of all `shell:AppsFolder` entries.
+///
+/// Enumeration is slow (~200 ms cold on a stock Win11 install — the
+/// folder has ~150–300 entries and each `BindToHandler` round-trips
+/// through the shell namespace). We cache the result for the lifetime
+/// of the driver process. The pid returned by `ActivateApplication`
+/// is the real packaged-app pid regardless of cache staleness, so the
+/// only correctness cost of cache staleness is: an app installed after
+/// the driver started will be invisible to name-based lookup until the
+/// driver restarts. That is acceptable — explicit AUMID via
+/// `bundle_id` always works regardless of cache state.
+static APPS_FOLDER_CACHE: OnceLock<RwLock<Option<Vec<AppsFolderEntry>>>> = OnceLock::new();
+
+fn cache() -> &'static RwLock<Option<Vec<AppsFolderEntry>>> {
+ APPS_FOLDER_CACHE.get_or_init(|| RwLock::new(None))
+}
+
+/// Resolve a packaged-app display name to its AUMID.
+///
+/// Lookup order, all case-insensitive against the display name shown
+/// in the Start Menu:
+/// 1. Exact match (e.g. `"Notepad"` → `Microsoft.WindowsNotepad_8wekyb3d8bbwe!App`).
+/// 2. Case-insensitive prefix match — picks the shortest display name
+/// that starts with the query, so `"calc"` resolves to `"Calculator"`
+/// rather than `"Calculator Plus"`.
+///
+/// `"notepad.exe"` and `"notepad"` both resolve identically — the
+/// `.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> {
+ let entries = load_or_get_cache()?;
+ let query = display_name.trim().to_lowercase();
+ if query.is_empty() {
+ return None;
+ }
+
+ // Strip an optional `.exe` suffix so callers passing `"notepad.exe"`
+ // (a Win32 idiom) still resolve to the packaged display name `"Notepad"`.
+ let query_stripped = query.strip_suffix(".exe").unwrap_or(&query);
+
+ // Pass 1: exact case-insensitive match.
+ if let Some(hit) = entries
+ .iter()
+ .find(|e| e.display_name.eq_ignore_ascii_case(query_stripped))
+ {
+ return Some(hit.aumid.clone());
+ }
+
+ // Pass 2: shortest case-insensitive prefix match. Uses the
+ // precomputed `lowercase_display_name` to avoid a fresh allocation
+ // per entry per call (see `AppsFolderEntry` docs for rationale).
+ let mut best: Option<&AppsFolderEntry> = None;
+ for entry in entries.iter() {
+ if entry.lowercase_display_name.starts_with(query_stripped) {
+ match best {
+ None => best = Some(entry),
+ Some(current) if entry.display_name.len() < current.display_name.len() => {
+ best = Some(entry)
+ }
+ _ => {}
+ }
+ }
+ }
+ best.map(|e| e.aumid.clone())
+}
+
+fn load_or_get_cache() -> Option<Vec<AppsFolderEntry>> {
+ {
+ let guard = cache().read().ok()?;
+ if let Some(cached) = guard.as_ref() {
+ return Some(cached.clone());
+ }
+ }
+
+ // Double-checked init — if two threads race here both enumerate; the
+ // second discards its result. AppsFolder enumeration is read-only, so
+ // the duplicated work is wasted CPU only, not a correctness hazard.
+ let fresh = enumerate_apps_folder().unwrap_or_default();
+ if let Ok(mut guard) = cache().write() {
+ if guard.is_none() {
+ *guard = Some(fresh.clone());
+ }
+ }
+ 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.
+fn enumerate_apps_folder() -> windows::core::Result<Vec<AppsFolderEntry>> {
+ let _ = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
+
+ // `shell:AppsFolder` is the well-known parsing path for the virtual
+ // folder that backs the Start Menu's "all apps" list. It enumerates
+ // every activatable app on the system, packaged or not.
+ let folder_path = HSTRING::from("shell:AppsFolder");
+ let apps_folder: IShellItem = unsafe {
+ SHCreateItemFromParsingName(PCWSTR(folder_path.as_ptr()), None::<&IBindCtx>)?
+ };
+
+ // Bind to the `BHID_EnumItems` handler to iterate children.
+ let enumerator: IEnumShellItems = unsafe {
+ apps_folder.BindToHandler(None::<&IBindCtx>, &BHID_EnumItems)?
+ };
+
+ let mut entries = Vec::with_capacity(256);
+ loop {
+ // Request one item at a time. windows-rs surfaces `S_FALSE`
+ // (the natural end-of-enumeration HRESULT) as `Err`, so we
+ // intentionally ignore the Result and gate on `fetched == 0`
+ // — the documented sentinel for "iterator exhausted".
+ let mut slot: [Option<IShellItem>; 1] = [None];
+ let mut fetched: u32 = 0;
+ let _ = unsafe {
+ enumerator.Next(&mut slot, Some(&mut fetched as *mut u32))
+ };
+ if fetched == 0 {
+ break;
+ }
+ let Some(item) = slot[0].take() else { break; };
+
+ // Cast to IShellItem2 to access PKEY_AppUserModel_ID; if the
+ // entry doesn't expose AAM (rare; pure-Win32 shortcut), skip.
+ let item2: IShellItem2 = match item.cast() {
+ Ok(i) => i,
+ Err(_) => continue,
+ };
+
+ let aumid = 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.
+ };
+ if aumid.is_empty() {
+ continue;
+ }
+
+ let display_name = match unsafe { item2.GetDisplayName(SIGDN_NORMALDISPLAY) } {
+ Ok(pwstr) => pwstr_to_string_and_free(pwstr),
+ Err(_) => String::new(),
+ };
+ if display_name.is_empty() {
+ continue;
+ }
+
+ let lowercase_display_name = display_name.to_lowercase();
+ entries.push(AppsFolderEntry { display_name, lowercase_display_name, aumid });
+ }
+
+ Ok(entries)
+}
+
+/// Drain a COM-allocated wide string (`PWSTR` returned by `GetString` /
+/// `GetDisplayName`) into a Rust `String`, then free the underlying
+/// COM-task-allocated buffer with `CoTaskMemFree` as the shell requires.
+fn pwstr_to_string_and_free(p: PWSTR) -> String {
+ if p.is_null() {
+ return String::new();
+ }
+ let s = unsafe { p.to_string().unwrap_or_default() };
+ unsafe { CoTaskMemFree(Some(p.0 as *const core::ffi::c_void)) };
+ s
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn is_aumid_recognises_canonical_form() {
+ assert!(is_aumid("Microsoft.WindowsNotepad_8wekyb3d8bbwe!App"));
+ assert!(is_aumid("Microsoft.WindowsCalculator_8wekyb3d8bbwe!App"));
+ }
+
+ #[test]
+ fn is_aumid_rejects_plain_names_and_paths() {
+ assert!(!is_aumid("notepad"));
+ assert!(!is_aumid("notepad.exe"));
+ assert!(!is_aumid(r"C:\Windows\System32\notepad.exe"));
+ assert!(!is_aumid(""));
+ assert!(!is_aumid("!App")); // empty PFN half
+ assert!(!is_aumid("Pkg!")); // empty AppId half
+ assert!(!is_aumid("a!b!c")); // two bangs
+ }
+}
diff --git a/libs/cua-driver-rs/crates/platform-windows/src/lib.rs b/libs/cua-driver-rs/crates/platform-windows/src/lib.rs
index 413e36e6b4..3cca789895 100644
--- a/libs/cua-driver-rs/crates/platform-windows/src/lib.rs
+++ b/libs/cua-driver-rs/crates/platform-windows/src/lib.rs
@@ -27,6 +27,9 @@ pub mod input;
#[cfg(target_os = "windows")]
pub mod capture;
+#[cfg(target_os = "windows")]
+pub mod launch_uwp;
+
pub fn register_tools() -> ToolRegistry {
tools::build_registry()
}
diff --git a/libs/cua-driver-rs/crates/platform-windows/src/tools/impl_.rs b/libs/cua-driver-rs/crates/platform-windows/src/tools/impl_.rs
index c1605e19de..131d3efdbd 100644
--- a/libs/cua-driver-rs/crates/platform-windows/src/tools/impl_.rs
+++ b/libs/cua-driver-rs/crates/platform-windows/src/tools/impl_.rs
@@ -491,29 +491,46 @@ impl Tool for LaunchAppTool {
name: "launch_app".into(),
// Description ported from Swift `LaunchAppTool.swift` with
// Windows-specific notes. `bundle_id` is accepted as an alias
- // for `name` (Windows has no bundle-identifier concept).
+ // for `name` on Windows, with one extra behavior: if the
+ // string looks like an AUMID (App User Model ID — contains
+ // `!`, e.g. `Microsoft.WindowsNotepad_8wekyb3d8bbwe!App`) we
+ // route through `IApplicationActivationManager` so packaged
+ // (Microsoft Store / UWP / MSIX) apps return the real
+ // process pid instead of a stub-redirect pid.
description: "Launch a Windows app hidden — the driver never brings the target to \
the foreground, the target's window is launched with SW_SHOWNOACTIVATE so it \
does not steal focus from whatever is currently frontmost.\n\n\
- Provide either `bundle_id` / `name` (resolved via ShellExecuteEx's PATH search) \
- or `path` (full path to an executable). If both `name` and `path` are given, \
- `path` wins. `urls` opens each URL in the default browser without activating it.\n\n\
+ Provide either `bundle_id` / `name` / `aumid` (resolved as below) or `path` \
+ (full path to an executable). If both `name` and `path` are given, `path` wins. \
+ `urls` opens each URL in the default browser without activating it.\n\n\
+ Routing order: explicit `aumid` (or a `bundle_id` containing `!`) activates the \
+ packaged app via `IApplicationActivationManager::ActivateApplication`, returning \
+ 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\
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 — \
- call `list_windows(pid)` explicitly a moment later.\n\n\
+ call `list_windows(pid)` explicitly a moment later. `bundle_id` in the \
+ response is set to the AUMID actually used for packaged-app launches and \
+ `null` for ShellExecuteEx launches.\n\n\
Windows-only field: `path` (Swift uses `bundle_id` since macOS apps resolve via \
LaunchServices; Windows has no LaunchServices, so `path` is the canonical form). \
The macOS-specific `electron_debugging_port`, `webkit_inspector_port`, \
`creates_new_application_instance`, and `additional_arguments` fields are \
- accepted; `additional_arguments` is honored, the others currently no-op on \
- Windows.".into(),
+ accepted; `additional_arguments` is honored (forwarded as ShellExecuteEx \
+ parameters or as the AUMID activation arguments string), the others currently \
+ no-op on Windows.".into(),
input_schema: json!({"type":"object","properties":{
- "bundle_id":{"type":"string","description":"Alias for `name` on Windows (no bundle-id concept). Either bundle_id or name must be provided when path is absent."},
- "name":{"type":"string","description":"App display name passed to ShellExecuteEx."},
- "path":{"type":"string","description":"Full path to executable. Windows-only; takes precedence over name/bundle_id."},
+ "bundle_id":{"type":"string","description":"App User Model ID (AUMID) for a packaged app — pattern `{PackageFamilyName}!{ApplicationId}`, e.g. `Microsoft.WindowsNotepad_8wekyb3d8bbwe!App`. Falls back to a `name` alias if no `!` is present. Either bundle_id, name, aumid, or path must be provided."},
+ "aumid":{"type":"string","description":"Explicit AUMID for a packaged app. Cleaner alternative to overloading `bundle_id`. Takes precedence over `bundle_id` / `name` when present."},
+ "name":{"type":"string","description":"App display name. Tried against the `shell:AppsFolder` index first for packaged-app lookup; on a miss, passed to ShellExecuteEx's PATH search."},
+ "path":{"type":"string","description":"Full path to executable. Windows-only; takes precedence over name/bundle_id/aumid."},
"urls":{"type":"array","items":{"type":"string"},"description":"URLs to open in the default browser via ShellExecuteEx (no activation)."},
- "additional_arguments":{"type":"array","items":{"type":"string"},"description":"Extra command-line arguments passed to the launched process."},
+ "additional_arguments":{"type":"array","items":{"type":"string"},"description":"Extra command-line arguments passed to the launched process (or activation arguments for packaged apps)."},
"electron_debugging_port":{"type":"integer","description":"Accepted for cross-platform parity; currently no-op on Windows."},
"webkit_inspector_port":{"type":"integer","description":"Accepted for cross-platform parity; no-op on Windows."},
"creates_new_application_instance":{"type":"boolean","description":"Accepted for parity; no-op on Windows (ShellExecuteEx always creates a new process)."}
@@ -526,6 +543,7 @@ impl Tool for LaunchAppTool {
let path_opt = args.get("path").and_then(|v| v.as_str()).map(str::to_owned);
let name_opt = args.get("name").and_then(|v| v.as_str()).map(str::to_owned);
let bundle_id_opt = args.get("bundle_id").and_then(|v| v.as_str()).map(str::to_owned);
+ let aumid_opt = args.get("aumid").and_then(|v| v.as_str()).map(str::to_owned);
let urls: Vec<String> = args.get("urls").and_then(|v| v.as_array())
.map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect())
.unwrap_or_default();
@@ -533,8 +551,9 @@ impl Tool for LaunchAppTool {
.map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect())
.unwrap_or_default();
- // Resolve target — path > name > bundle_id (alias of name on Windows).
+ // Resolve target — path > aumid > name > bundle_id (alias of name on Windows).
let target = path_opt.clone()
+ .or(aumid_opt.clone())
.or(name_opt.clone())
.or(bundle_id_opt.clone());
@@ -543,67 +562,164 @@ impl Tool for LaunchAppTool {
return ToolResult::error("Provide either bundle_id or name to identify the app to launch.");
}
- // Single launch path: use ShellExecuteExW with SEE_MASK_NOCLOSEPROCESS
- // so we can read the spawned process's pid back.
- let display = target.clone().unwrap_or_else(|| urls.join(", "));
+ // ── Packaged-app (UWP / MSIX) routing decision ──────────────────────
+ //
+ // Routing precedence — most explicit signal wins:
+ // 1. `aumid` parameter (any value): packaged path, AUMID = value.
+ // 2. `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).
+ // 3. `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. 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 aumid_for_uwp: Option<String> = if path_opt.is_some() {
+ None
+ } else if let Some(a) = aumid_opt.clone() {
+ Some(a)
+ } else if let Some(b) = bundle_id_opt.clone().filter(|s| crate::launch_uwp::is_aumid(s)) {
+ Some(b)
+ } else if let Some(n) = name_opt.clone() {
+ // Run the (cached) AppsFolder lookup on a blocking thread to
+ // avoid stalling the async runtime on the cold-enumeration
+ // path (~200 ms first call, ~µs after).
+ tokio::task::spawn_blocking(move || crate::launch_uwp::resolve_aumid_by_name(&n))
+ .await
+ .unwrap_or(None)
+ } else {
+ None
+ };
+
+ // 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())
+ .unwrap_or_else(|| urls.join(", "));
let extra_joined = extra_args.join(" ");
- let urls_clone = urls.clone();
- let result = tokio::task::spawn_blocking(move || -> anyhow::Result<u32> {
- use windows::Win32::UI::Shell::{
- ShellExecuteExW, SHELLEXECUTEINFOW, SEE_MASK_NOCLOSEPROCESS,
- };
- use windows::Win32::UI::WindowsAndMessaging::SW_SHOWNOACTIVATE;
- use windows::Win32::System::Threading::GetProcessId;
- use windows::Win32::Foundation::CloseHandle;
- use windows::core::PCWSTR;
- fn to_wide(s: &str) -> Vec<u16> {
- s.encode_utf16().chain(std::iter::once(0)).collect()
+ // Branch: AUMID activation if we resolved one; else legacy
+ // ShellExecuteExW. Both branches still need to handle `urls`
+ // (additional URLs always go through ShellExecuteExW since the
+ // Start Menu doesn't activate by URL).
+ let pid = if let Some(aumid) = aumid_for_uwp.clone() {
+ let aumid_clone = aumid.clone();
+ let args_clone = extra_joined.clone();
+ let activation = tokio::task::spawn_blocking(move || {
+ crate::launch_uwp::launch_uwp(&aumid_clone, &args_clone)
+ })
+ .await;
+ match activation {
+ Ok(Ok(p)) => p,
+ Ok(Err(e)) => return ToolResult::error(format!(
+ "Failed to activate packaged app {aumid:?}: {e}"
+ )),
+ Err(e) => return ToolResult::error(format!("Task error: {e}")),
}
- let op_w = to_wide("open");
- let file_w = to_wide(if let Some(t) = target.as_deref() { t } else { urls_clone.first().map(|s| s.as_str()).unwrap_or("") });
- let args_w = to_wide(&extra_joined);
-
- let mut info = SHELLEXECUTEINFOW {
- cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
- fMask: SEE_MASK_NOCLOSEPROCESS,
- lpVerb: PCWSTR(op_w.as_ptr()),
- lpFile: PCWSTR(file_w.as_ptr()),
- lpParameters: if extra_joined.is_empty() { PCWSTR::null() } else { PCWSTR(args_w.as_ptr()) },
- nShow: SW_SHOWNOACTIVATE.0,
- ..Default::default()
- };
- unsafe { ShellExecuteExW(&mut info)?; }
- let pid = if !info.hProcess.is_invalid() {
- let p = unsafe { GetProcessId(info.hProcess) };
- unsafe { let _ = CloseHandle(info.hProcess); }
- p
- } else { 0 };
-
- // 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)..] {
- let file = to_wide(url);
- let mut url_info = SHELLEXECUTEINFOW {
- cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
- lpVerb: PCWSTR(op_w.as_ptr()),
- lpFile: PCWSTR(file.as_ptr()),
- nShow: SW_SHOWNOACTIVATE.0,
+ } else {
+ // Legacy ShellExecuteExW path — unchanged behavior for plain
+ // Win32 apps and for callers passing an explicit `path`.
+ let urls_clone = urls.clone();
+ let target_for_shell = target.clone();
+ let extra_for_shell = extra_joined.clone();
+ let result = tokio::task::spawn_blocking(move || -> anyhow::Result<u32> {
+ use windows::Win32::UI::Shell::{
+ ShellExecuteExW, SHELLEXECUTEINFOW, SEE_MASK_NOCLOSEPROCESS,
+ };
+ use windows::Win32::UI::WindowsAndMessaging::SW_SHOWNOACTIVATE;
+ use windows::Win32::System::Threading::GetProcessId;
+ use windows::Win32::Foundation::CloseHandle;
+ use windows::core::PCWSTR;
+
+ fn to_wide(s: &str) -> Vec<u16> {
+ s.encode_utf16().chain(std::iter::once(0)).collect()
+ }
+ let op_w = to_wide("open");
+ let file_w = to_wide(if let Some(t) = target_for_shell.as_deref() {
+ t
+ } else {
+ urls_clone.first().map(|s| s.as_str()).unwrap_or("")
+ });
+ let args_w = to_wide(&extra_for_shell);
+
+ let mut info = SHELLEXECUTEINFOW {
+ cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
+ fMask: SEE_MASK_NOCLOSEPROCESS,
+ lpVerb: PCWSTR(op_w.as_ptr()),
+ lpFile: PCWSTR(file_w.as_ptr()),
+ lpParameters: if extra_for_shell.is_empty() {
+ PCWSTR::null()
+ } else {
+ PCWSTR(args_w.as_ptr())
+ },
+ nShow: SW_SHOWNOACTIVATE.0,
..Default::default()
};
- unsafe { let _ = ShellExecuteExW(&mut url_info); }
- }
+ unsafe { ShellExecuteExW(&mut info)?; }
+ let pid = if !info.hProcess.is_invalid() {
+ let p = unsafe { GetProcessId(info.hProcess) };
+ unsafe { let _ = CloseHandle(info.hProcess); }
+ p
+ } else { 0 };
+
+ // 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)..] {
+ let file = to_wide(url);
+ let mut url_info = SHELLEXECUTEINFOW {
+ cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
+ lpVerb: PCWSTR(op_w.as_ptr()),
+ lpFile: PCWSTR(file.as_ptr()),
+ nShow: SW_SHOWNOACTIVATE.0,
+ ..Default::default()
+ };
+ unsafe { let _ = ShellExecuteExW(&mut url_info); }
+ }
- Ok(pid)
- }).await;
+ Ok(pid)
+ }).await;
- let pid = match result {
- Ok(Ok(p)) => p,
- Ok(Err(e)) => return ToolResult::error(format!("Failed to launch: {e}")),
- Err(e) => return ToolResult::error(format!("Task error: {e}")),
+ match result {
+ Ok(Ok(p)) => p,
+ Ok(Err(e)) => return ToolResult::error(format!("Failed to launch: {e}")),
+ Err(e) => return ToolResult::error(format!("Task error: {e}")),
+ }
};
+ // When the packaged path was taken we still need to fan out any
+ // extra URLs to the default browser (ShellExecuteEx — no pid
+ // capture, mirroring Swift's NSWorkspace secondary-URL flow).
+ if aumid_for_uwp.is_some() && !urls.is_empty() {
+ let urls_clone = urls.clone();
+ let _ = tokio::task::spawn_blocking(move || {
+ use windows::Win32::UI::Shell::{ShellExecuteExW, SHELLEXECUTEINFOW};
+ use windows::Win32::UI::WindowsAndMessaging::SW_SHOWNOACTIVATE;
+ use windows::core::PCWSTR;
+ fn to_wide(s: &str) -> Vec<u16> {
+ s.encode_utf16().chain(std::iter::once(0)).collect()
+ }
+ let op_w = to_wide("open");
+ for url in &urls_clone {
+ let file = to_wide(url);
+ let mut url_info = SHELLEXECUTEINFOW {
+ cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
+ lpVerb: PCWSTR(op_w.as_ptr()),
+ lpFile: PCWSTR(file.as_ptr()),
+ nShow: SW_SHOWNOACTIVATE.0,
+ ..Default::default()
+ };
+ unsafe { let _ = ShellExecuteExW(&mut url_info); }
+ }
+ })
+ .await;
+ }
+
// Resolve the pid's windows so the caller can skip a list_windows
// round-trip — same approach as Swift's `resolveWindows`. Retry
// 5×200ms; Win32 window registration can lag the launch.
@@ -636,9 +752,17 @@ impl Tool for LaunchAppTool {
}
summary.push_str(&format!("\n→ Call get_window_state(pid: {pid}, window_id) to inspect."));
}
+ // `bundle_id` is the AUMID when we went through the packaged-app
+ // path (so the caller can round-trip the same value to relaunch),
+ // and `null` for plain Win32 launches (which truly have no bundle
+ // identifier concept on Windows).
+ let bundle_id_response = match aumid_for_uwp.as_ref() {
+ Some(a) => serde_json::Value::String(a.clone()),
+ None => serde_json::Value::Null,
+ };
let structured = json!({
"pid": pid,
- "bundle_id": serde_json::Value::Null,
+ "bundle_id": bundle_id_response,
"name": display,
"running": true,
"active": false, // SW_SHOWNOACTIVATE — Swift's background-launch invariant