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(list_apps): unify running + installed apps across platforms (#1545)

Francesco Bonaccid891621756dd
diff --git a/docs/content/docs/cua-driver/reference/mcp-tools.mdx b/docs/content/docs/cua-driver/reference/mcp-tools.mdx
index 244226ba14..0cc266a5bb 100644
--- a/docs/content/docs/cua-driver/reference/mcp-tools.mdx
+++ b/docs/content/docs/cua-driver/reference/mcp-tools.mdx
@@ -479,22 +479,67 @@ later to resolve a target.
### list_apps
-List macOS apps — both currently running and installed-but-not-running —
-with per-app state flags:
-
-- running: is a process for this app live? (pid is 0 when false)
-- active: is it the system-frontmost app? (implies running)
-
-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.
+List every app — currently running **and** installed-but-not-running —
+in a single flat array. Each entry self-describes which state it's in.
+
+Per-entry fields (same shape on macOS, Windows, Linux; platform-specific
+values are explicitly `null` rather than omitted):
+
+- `pid` (integer): the live process id when `running=true`, else `0`.
+- `name` (string): display name.
+- `bundle_id` (string|null): platform-stable identifier. macOS = bundle id
+ (`com.apple.calculator`), Windows desktop = the resolved `.exe` path,
+ Windows UWP = `{PackageFamilyName}` (e.g. `Microsoft.WindowsCalculator_8wekyb3d8bbwe`),
+ Linux = the XDG "desktop file id" — the `.desktop` file's path relative
+ to its `applications/` root with the `.desktop` suffix stripped and any
+ path separators replaced with `-` (e.g. `kde4/konqbrowser.desktop` →
+ `kde4-konqbrowser`).
+- `running` (bool): true when a process matching this app is live.
+- `active` (bool): true for the single system-frontmost app (always
+ implies running). Always false on Linux — X11/Wayland focus is
+ per-window, not per-app.
+- `kind` (string|null): `"desktop"` for `.app`/`.exe`/`.desktop`
+ launchers, `"uwp"` for Windows packaged apps.
+- `launch_path` (string|null): what `launch_app` would consume to start
+ this app cold. macOS = `.app` bundle path; Windows desktop = full
+ `.exe` commandline (path plus any arguments preserved from the source
+ `.lnk`); Windows UWP = `shell:appsFolder\{family}!{appId}` where
+ `{appId}` may fall back to `App` when the package manifest does not
+ expose a specific `Application.Id`; Linux = the command from `Exec=`
+ with XDG field codes stripped.
+- `last_used` (string|null): RFC3339 timestamp from the launcher's
+ filesystem mtime, when readable; otherwise `null`.
+- `windows` (array): reserved — empty by design to keep the call cheap.
+ Use `list_windows` for per-window state.
+
+Enumeration sources per platform:
+
+- macOS: NSWorkspace running list + filesystem scan of `/Applications`,
+ `/Applications/Utilities`, `/System/Applications`,
+ `/System/Applications/Utilities`, `~/Applications`. Only apps with
+ `NSApplicationActivationPolicyRegular` are included — background
+ helpers and system UI agents are filtered out.
+- Windows: visible top-level windows (running set) + Start-Menu
+ `.lnk` resolution via `IShellLinkW::GetPath` (desktop installed set)
+ + WinRT `PackageManager::FindPackagesWithPackageTypes(Main)`
+ (UWP installed set).
+- Linux: `/proc` walk (running set) + XDG `.desktop` files in
+ `$XDG_DATA_HOME/applications` and each `$XDG_DATA_DIRS` entry's
+ `applications/` subdir (installed set). `NoDisplay=true` and
+ `Hidden=true` entries are filtered.
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.
+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.
+
+Legacy `processes` alias: alongside the unified `apps` array, the
+Linux and Windows backends also return a `processes` field containing
+just the running subset (one record per live pid with `pid` and
+`name`). It exists so callers written against the pre-unification
+shape (running processes only) keep working without changes; new
+callers should read `apps` and filter on `running` instead.
**Arguments:** none.
diff --git a/libs/cua-driver-rs/PARITY.md b/libs/cua-driver-rs/PARITY.md
index b08f5d14d2..e3ff3436d0 100644
--- a/libs/cua-driver-rs/PARITY.md
+++ b/libs/cua-driver-rs/PARITY.md
@@ -308,50 +308,109 @@ terminal-only flow proves insufficient; the CLI is the MVP.
- Rust:
- macOS=`crates/platform-macos/src/tools/list_apps.rs` + `apps.rs:format_app_list`
- windows=`crates/platform-windows/src/tools/impl_.rs` (ListAppsTool)
+ + `crates/platform-windows/src/win32/installed_apps.rs`
- linux=`crates/platform-linux/src/tools/impl_.rs` (ListAppsTool)
+ + `crates/platform-linux/src/installed_apps.rs`
- Status:
- - macOS: code fixed (✅ checkmark added, description copied from Swift); pending macOS run
- - windows: VERIFIED (text format + structured shape + `active` flag)
- - linux: OPEN (subagent currently fixing pre-existing compile errors)
-- Test: `crates/platform-windows/examples/list_apps_parity.rs`
+ - macOS: VERIFIED — unified shape + installed-app scan + running merge
+ - windows: VERIFIED for Win32 path (cross-target check), live-run pending on a Windows host
+ - linux: code ready (cross-target check pending Linux host)
+- Test: `tests/integration/test_api_parity.py::RustParityTests::test_call_list_apps_*`
+ + `crates/platform-windows/examples/list_apps_parity.rs`
-### Fixed divergences
+### Unified response shape (cross-platform)
-1. **Windows: returned every OS process** (System, Registry, csrss, etc.)
- instead of "apps". Now filters to processes that own at least one
- visible top-level window — the closest analogue to Swift's
- `NSApplicationActivationPolicyRegular` filter (excludes background
- helpers / agents).
-2. **Structured shape**: Swift returns `Output { apps: [AppInfo] }` with
- `AppInfo = {pid, bundle_id, name, running, active}`. Windows was
- returning `{ processes: [{pid, name}] }`. Now returns both keys —
- `apps` (Swift shape) for new callers, `processes` (legacy shape) as a
- transitional alias.
-3. **Text format**: Swift starts with `"✅ Found N app(s): R running, I installed-not-running."`.
- macOS Rust was missing the `✅` prefix; Windows had a different
- wording entirely (`"Found N processes:"`). Both now match Swift 1:1.
-4. **`active` flag** — Windows resolves it via `GetForegroundWindow` +
- `GetWindowThreadProcessId` (only one app is `active` at a time).
-5. **Description** — copied verbatim from Swift on macOS; adapted with
- Windows-specific caveats on Windows (no bundle_id, no installed-apps
- enumeration yet).
-
-### Known limitation (Windows / Linux)
-
-Neither Rust port enumerates *installed but not running* apps yet — Swift
-scans `/Applications`, `~/Applications`, `/System/Applications`, etc.
-Windows would need to scan Start Menu shortcuts and the Registry
-Uninstall keys; Linux would need to scan `.desktop` files in
-`/usr/share/applications` and `~/.local/share/applications`. Marked as
-follow-up work; the running-app view is still useful and matches Swift's
-running subset exactly.
+Single flat array. Every entry carries the same fields on every
+platform; values that don't apply to a given platform are `null`.
-### Verified on Windows
+```jsonc
+{
+ "apps": [
+ {
+ "pid": 47291, // 0 when running=false
+ "name": "Visual Studio Code",
+ "bundle_id": "com.microsoft.VSCode", // macOS bundle id, Win32 .exe path, or Linux desktop file id
+ "running": true,
+ "active": false, // true for the system-frontmost app (only one at a time)
+ "kind": "desktop", // "desktop" | "uwp" | null
+ "launch_path": "/Applications/Visual Studio Code.app",
+ "last_used": "2026-05-15T12:34:56Z", // RFC3339, null if unreadable
+ "windows": [] // reserved — kept cheap; query list_windows for per-window state
+ }
+ ]
+}
+```
+
+### Per-platform enumeration
+
+- **macOS**: running set from `NSWorkspace` (via the existing
+ AppleScript bridge), installed set from a filesystem scan of
+ `/Applications`, `/Applications/Utilities`, `/System/Applications`,
+ `/System/Applications/Utilities`, `~/Applications`. Bundle metadata
+ read from each `.app/Contents/Info.plist` via `plutil`. Merged by
+ bundle id; `launch_path` and `last_used` (bundle mtime) are
+ backfilled onto running entries when the bundle id matches.
+- **Windows**: running set from visible top-level windows
+ (`EnumWindows` → owner pids) + `CreateToolhelp32Snapshot` for the
+ pid→exe table. Installed set is the union of Start-Menu
+ `.lnk` shortcuts (resolved via `IShellLinkW::GetPath`) and WinRT
+ `Management::Deployment::PackageManager::FindPackagesWithPackageTypes(Main)`.
+ Merged by exe basename. UWP entries carry
+ `launch_path = "shell:appsFolder\\{PackageFamilyName}!App"`.
+- **Linux**: running set from `/proc/<pid>/status` + `cmdline`.
+ Installed set from XDG `.desktop` files in `$XDG_DATA_HOME/applications`
+ and each `$XDG_DATA_DIRS` entry's `applications/` subdir. Entries
+ with `NoDisplay=true`, `Hidden=true`, or `Type!=Application` are
+ filtered. Merged by exe basename (after stripping `env`-style
+ prefixes and `Exec=` field codes).
+
+### Backwards compatibility
+
+The unified shape is **additive**. `pid`, `name`, `bundle_id`,
+`running`, `active` keep their pre-change positions and types.
+The new keys (`launch_path`, `kind`, `last_used`, `windows`) are
+new. The legacy `processes` key (Linux/Windows) remains as a thin
+alias over the running subset so older callers that read the old
+running-only shape keep working.
+
+### Verification recipes
+
+**macOS** (verified live):
+```bash
+cargo build --release -p cua-driver
+./target/release/cua-driver call list_apps | python3 -c "
+import json, sys
+d = json.load(sys.stdin)
+running = [a for a in d['apps'] if a['running']]
+installed = [a for a in d['apps'] if not a['running']]
+print(f'{len(d[\"apps\"])} total: {len(running)} running, {len(installed)} installed-only')
+for a in d['apps'][:1]:
+ for k in ('pid','name','bundle_id','running','active','kind','launch_path','last_used','windows'):
+ assert k in a, f'missing field {k!r}'
+print('shape OK')
+"
+```
-`list_apps_parity.exe`: header line matches `"✅ Found N app(s): R
-running, 0 installed-not-running."`; `structuredContent.apps` is an
-array of `{pid, bundle_id (null on Windows), name, running, active}`;
-at least one entry has `active: true` (the foreground app).
+**Windows** (cross-target check on macOS host succeeds; live run on a Windows host):
+```powershell
+cargo build --release -p cua-driver
+.\target\release\cua-driver.exe call list_apps | ConvertFrom-Json | ForEach-Object {
+ $_.apps | Group-Object kind | Format-Table Name, Count
+}
+```
+Expect at least one `desktop` group (Start-Menu hits) and on Win10+
+at least one `uwp` group (WinRT packages). Every entry should have
+a `launch_path` that's either an absolute `.exe` path or
+`shell:appsFolder\...`.
+
+**Linux**:
+```bash
+cargo build --release -p cua-driver
+./target/release/cua-driver call list_apps | jq '.apps | group_by(.running) | map({running: .[0].running, n: length})'
+```
+Expect two groups: one with `running: true` (live processes that
+matched a `.desktop` launcher), one with `running: false` (the
+installed-but-not-running tail).
---
diff --git a/libs/cua-driver-rs/crates/platform-linux/src/installed_apps.rs b/libs/cua-driver-rs/crates/platform-linux/src/installed_apps.rs
new file mode 100644
index 0000000000..7738ae23c7
--- /dev/null
+++ b/libs/cua-driver-rs/crates/platform-linux/src/installed_apps.rs
@@ -0,0 +1,331 @@
+//! Linux installed-app enumeration via the XDG Desktop Entry Specification.
+//!
+//! Scans `.desktop` files in the standard XDG application directories and
+//! parses each `[Desktop Entry]` section for `Name`, `Exec`, `NoDisplay`,
+//! `Hidden`, and `Type` per
+//! <https://specifications.freedesktop.org/desktop-entry-spec/latest/>.
+
+use std::fs;
+use std::path::{Path, PathBuf};
+
+/// Parsed metadata for an installed application's `.desktop` launcher.
+#[derive(Debug, Clone)]
+pub struct InstalledApp {
+ /// Display name from the `Name=` key (best localized variant we can read).
+ pub name: String,
+ /// The freedesktop "desktop file id" — the `.desktop` file's path
+ /// relative to its XDG `applications/` root, with the `.desktop`
+ /// suffix stripped and path separators replaced with `-`.
+ /// E.g. `org.gnome.Calculator.desktop` → `org.gnome.Calculator`;
+ /// `kde4/konqbrowser.desktop` → `kde4-konqbrowser`.
+ pub bundle_id: String,
+ /// Path the launcher would run — the unexpanded first token of `Exec=`
+ /// (field codes like `%U`, `%f` stripped). Pass to `launch_app(launch_path=...)`.
+ pub launch_path: String,
+ /// RFC3339 timestamp from the `.desktop` file's filesystem mtime, or
+ /// `None` if the metadata could not be read.
+ pub last_used: Option<String>,
+}
+
+/// Return every visible application installed on the system.
+///
+/// Filters out entries with `NoDisplay=true`, `Hidden=true`, or `Type!=Application`.
+/// XDG search order: `$XDG_DATA_HOME/applications` (defaults to
+/// `~/.local/share/applications`), then each `$XDG_DATA_DIRS` entry's
+/// `applications/` subdir (defaults to
+/// `/usr/local/share/applications:/usr/share/applications`).
+pub fn list_installed_apps() -> Vec<InstalledApp> {
+ let mut seen: std::collections::HashMap<String, InstalledApp> =
+ std::collections::HashMap::new();
+ for root in xdg_application_dirs() {
+ let Ok(entries) = fs::read_dir(&root) else { continue };
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if path.extension().and_then(|e| e.to_str()) != Some("desktop") { continue }
+ let id = desktop_file_id(&root, &path);
+ if id.is_empty() { continue }
+ let Some(app) = parse_desktop_file(&path, &id) else { continue };
+ // Per the spec, user-scope files (XDG_DATA_HOME) override
+ // system-scope ones with the same desktop file id.
+ // xdg_application_dirs already yields user-scope first, so
+ // insert-if-absent gives us the precedence right.
+ seen.entry(app.bundle_id.clone()).or_insert(app);
+ }
+ }
+ let mut out: Vec<InstalledApp> = seen.into_values().collect();
+ out.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
+ out
+}
+
+/// Build the search-path list per the XDG Base Directory Specification.
+fn xdg_application_dirs() -> Vec<PathBuf> {
+ let mut out = Vec::new();
+ let home = std::env::var("HOME").unwrap_or_default();
+ let xdg_data_home = std::env::var("XDG_DATA_HOME").unwrap_or_else(|_| {
+ if home.is_empty() { String::new() } else { format!("{home}/.local/share") }
+ });
+ if !xdg_data_home.is_empty() {
+ out.push(PathBuf::from(format!("{xdg_data_home}/applications")));
+ }
+ let xdg_data_dirs = std::env::var("XDG_DATA_DIRS")
+ .unwrap_or_else(|_| "/usr/local/share:/usr/share".to_owned());
+ for d in xdg_data_dirs.split(':').filter(|s| !s.is_empty()) {
+ out.push(PathBuf::from(format!("{d}/applications")));
+ }
+ out
+}
+
+/// Compute the canonical "desktop file id" per the freedesktop Desktop Entry
+/// spec: the path of the `.desktop` file relative to its XDG `applications/`
+/// root, with the `.desktop` suffix stripped and any path separators replaced
+/// with `-`. This is what associations/launchers reference and guarantees
+/// uniqueness across nested category dirs (e.g. `category/foo.desktop` →
+/// `category-foo`, distinct from a sibling `foo.desktop` → `foo`).
+///
+/// Returns an empty string when `path` is not under `root` or has no
+/// `.desktop` suffix.
+fn desktop_file_id(root: &Path, path: &Path) -> String {
+ let rel = match path.strip_prefix(root) {
+ Ok(r) => r,
+ Err(_) => return String::new(),
+ };
+ let rel_str = match rel.to_str() {
+ Some(s) => s,
+ None => return String::new(),
+ };
+ let stem = match rel_str.strip_suffix(".desktop") {
+ Some(s) => s,
+ None => return String::new(),
+ };
+ // Use forward slash as the canonical separator (Linux only — `Path`
+ // separators are always `/` here, but normalize defensively).
+ stem.replace(std::path::MAIN_SEPARATOR, "-").replace('/', "-")
+}
+
+/// Parse a `.desktop` file. Returns `None` for entries the caller should skip
+/// (`NoDisplay=true`, `Hidden=true`, `Type!=Application`, missing `Exec` or `Name`).
+///
+/// `bundle_id` is the precomputed desktop file id (see `desktop_file_id`).
+fn parse_desktop_file(path: &Path, bundle_id: &str) -> Option<InstalledApp> {
+ let text = fs::read_to_string(path).ok()?;
+ let entry = extract_desktop_entry_section(&text)?;
+
+ if bool_key(&entry, "NoDisplay") || bool_key(&entry, "Hidden") {
+ return None;
+ }
+ let type_ = string_key(&entry, "Type").unwrap_or_default();
+ if !type_.is_empty() && type_ != "Application" {
+ return None;
+ }
+
+ let name = string_key(&entry, "Name")?;
+ let exec_raw = string_key(&entry, "Exec")?;
+ let launch_path = strip_exec_field_codes(&exec_raw);
+ if launch_path.is_empty() {
+ return None;
+ }
+
+ if bundle_id.is_empty() {
+ return None;
+ }
+ let bundle_id = bundle_id.to_owned();
+
+ let last_used = fs::metadata(path)
+ .ok()
+ .and_then(|m| m.modified().ok())
+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
+ .map(|d| unix_secs_to_rfc3339(d.as_secs() as i64));
+
+ Some(InstalledApp {
+ name,
+ bundle_id,
+ launch_path,
+ last_used,
+ })
+}
+
+/// Return the `[Desktop Entry]` section's key/value lines as one blob.
+/// We only need a flat string lookup, so a Vec<(String, String)> is overkill —
+/// pull the section into a `String` and let `string_key` re-scan it.
+fn extract_desktop_entry_section(text: &str) -> Option<String> {
+ let mut in_section = false;
+ let mut out = String::new();
+ for line in text.lines() {
+ let trimmed = line.trim();
+ if let Some(header) = trimmed.strip_prefix('[').and_then(|h| h.strip_suffix(']')) {
+ in_section = header == "Desktop Entry";
+ continue;
+ }
+ if in_section && !trimmed.is_empty() && !trimmed.starts_with('#') {
+ out.push_str(line);
+ out.push('\n');
+ }
+ }
+ if out.is_empty() { None } else { Some(out) }
+}
+
+fn string_key(section: &str, key: &str) -> Option<String> {
+ // Prefer a localized variant matching $LANG when present (`Key[xx]=...`).
+ // Fall back to the bare `Key=...`. We only look at the language root
+ // (everything before the first `.` or `_`), so `en_US.UTF-8` matches `en`.
+ let lang = std::env::var("LANG").unwrap_or_default();
+ let lang_root: String = lang
+ .split(|c: char| c == '.' || c == '@')
+ .next()
+ .unwrap_or("")
+ .to_owned();
+ let lang_short: String = lang_root
+ .split('_')
+ .next()
+ .unwrap_or("")
+ .to_owned();
+
+ let candidates = [
+ format!("{key}[{lang_root}]="),
+ format!("{key}[{lang_short}]="),
+ format!("{key}="),
+ ];
+ for cand in &candidates {
+ if cand.starts_with(&format!("{key}[]=")) { continue }
+ for line in section.lines() {
+ if let Some(rest) = line.strip_prefix(cand.as_str()) {
+ let value = rest.trim_end_matches('\r').to_owned();
+ if !value.is_empty() {
+ return Some(value);
+ }
+ }
+ }
+ }
+ None
+}
+
+fn bool_key(section: &str, key: &str) -> bool {
+ string_key(section, key)
+ .map(|v| v.eq_ignore_ascii_case("true"))
+ .unwrap_or(false)
+}
+
+/// Strip XDG `Exec=` field codes (`%f`, `%F`, `%u`, `%U`, `%i`, `%c`, `%k`)
+/// and return only the program token. We deliberately don't try to honor
+/// quoted argv reconstruction — the caller passes the result to
+/// `launch_app(launch_path=...)`, which spawns it through `sh -c`.
+fn strip_exec_field_codes(exec: &str) -> String {
+ let mut out = String::with_capacity(exec.len());
+ let mut chars = exec.chars().peekable();
+ while let Some(c) = chars.next() {
+ if c == '%' {
+ // Consume the field-code letter, drop both.
+ chars.next();
+ continue;
+ }
+ out.push(c);
+ }
+ out.trim().to_owned()
+}
+
+/// Format Unix epoch seconds as `YYYY-MM-DDTHH:MM:SSZ` (UTC).
+fn unix_secs_to_rfc3339(secs: i64) -> String {
+ let days = secs.div_euclid(86_400);
+ let seconds_of_day = secs.rem_euclid(86_400);
+ let hour = seconds_of_day / 3600;
+ let minute = (seconds_of_day % 3600) / 60;
+ let second = seconds_of_day % 60;
+
+ // Howard Hinnant's civil-from-days algorithm.
+ let z = days + 719_468;
+ let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
+ let doe = (z - era * 146_097) as u64;
+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
+ let y = yoe as i64 + era * 400;
+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
+ let mp = (5 * doy + 2) / 153;
+ let d = doy - (153 * mp + 2) / 5 + 1;
+ let m = if mp < 10 { mp + 3 } else { mp - 9 };
+ let y = if m <= 2 { y + 1 } else { y };
+
+ format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", y, m, d, hour, minute, second)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn strips_field_codes() {
+ assert_eq!(strip_exec_field_codes("firefox %U"), "firefox");
+ assert_eq!(strip_exec_field_codes("/usr/bin/gedit %f"), "/usr/bin/gedit");
+ assert_eq!(strip_exec_field_codes("xterm -e %F"), "xterm -e");
+ }
+
+ #[test]
+ fn skips_nodisplay_entry() {
+ let body = "\
+[Desktop Entry]
+Type=Application
+Name=Hidden Helper
+Exec=/usr/libexec/helper
+NoDisplay=true
+";
+ let dir = std::env::temp_dir().join(format!("cua-driver-rs-test-{}", std::process::id()));
+ let _ = std::fs::create_dir_all(&dir);
+ let path = dir.join("hidden-helper.desktop");
+ std::fs::write(&path, body).unwrap();
+ assert!(parse_desktop_file(&path, "hidden-helper").is_none());
+ let _ = std::fs::remove_file(&path);
+ }
+
+ #[test]
+ fn parses_minimal_entry() {
+ let body = "\
+[Desktop Entry]
+Type=Application
+Name=Demo App
+Exec=/opt/demo/bin/demo %U
+";
+ let dir = std::env::temp_dir().join(format!("cua-driver-rs-test-{}", std::process::id()));
+ let _ = std::fs::create_dir_all(&dir);
+ let path = dir.join("demo-app.desktop");
+ std::fs::write(&path, body).unwrap();
+ let parsed = parse_desktop_file(&path, "demo-app").expect("parses");
+ assert_eq!(parsed.name, "Demo App");
+ assert_eq!(parsed.launch_path, "/opt/demo/bin/demo");
+ assert_eq!(parsed.bundle_id, "demo-app");
+ let _ = std::fs::remove_file(&path);
+ }
+
+ #[test]
+ fn desktop_file_id_flat() {
+ let root = Path::new("/usr/share/applications");
+ let path = Path::new("/usr/share/applications/firefox.desktop");
+ assert_eq!(desktop_file_id(root, path), "firefox");
+ }
+
+ #[test]
+ fn desktop_file_id_nested_disambiguates() {
+ // Two distinct .desktop files that would have collided under the
+ // old `file_stem()`-only scheme now get unique ids.
+ let root = Path::new("/usr/share/applications");
+ let flat = Path::new("/usr/share/applications/foo.desktop");
+ let nested = Path::new("/usr/share/applications/category/foo.desktop");
+ assert_eq!(desktop_file_id(root, flat), "foo");
+ assert_eq!(desktop_file_id(root, nested), "category-foo");
+ assert_ne!(
+ desktop_file_id(root, flat),
+ desktop_file_id(root, nested),
+ "nested .desktop entries must not collide with flat ones"
+ );
+ }
+
+ #[test]
+ fn desktop_file_id_returns_empty_outside_root() {
+ let root = Path::new("/usr/share/applications");
+ let other = Path::new("/opt/something.desktop");
+ assert_eq!(desktop_file_id(root, other), "");
+ }
+
+ #[test]
+ fn rfc3339_known_epoch() {
+ // 1234567890 → 2009-02-13T23:31:30Z
+ assert_eq!(unix_secs_to_rfc3339(1_234_567_890), "2009-02-13T23:31:30Z");
+ }
+}
diff --git a/libs/cua-driver-rs/crates/platform-linux/src/lib.rs b/libs/cua-driver-rs/crates/platform-linux/src/lib.rs
index 3fb693590c..77b73de282 100644
--- a/libs/cua-driver-rs/crates/platform-linux/src/lib.rs
+++ b/libs/cua-driver-rs/crates/platform-linux/src/lib.rs
@@ -24,6 +24,9 @@ pub mod input;
#[cfg(target_os = "linux")]
pub mod proc_fs;
+#[cfg(target_os = "linux")]
+pub mod installed_apps;
+
#[cfg(target_os = "linux")]
pub mod capture;
diff --git a/libs/cua-driver-rs/crates/platform-linux/src/tools/impl_.rs b/libs/cua-driver-rs/crates/platform-linux/src/tools/impl_.rs
index 77daee7832..838a02dcf8 100644
--- a/libs/cua-driver-rs/crates/platform-linux/src/tools/impl_.rs
+++ b/libs/cua-driver-rs/crates/platform-linux/src/tools/impl_.rs
@@ -88,26 +88,192 @@ impl Tool for ListAppsTool {
fn def(&self) -> &ToolDef {
LIST_APPS_DEF.get_or_init(|| ToolDef {
name: "list_apps".into(),
- description: "List running processes via /proc filesystem.".into(),
+ description: "List Linux apps — both currently running and installed-but-not-running — \
+ with per-app state flags:\n\n\
+ - running: is a process for this app live? (pid is 0 when false)\n\
+ - active: reserved (Linux X11/Wayland focus model differs from frontmost-app); \
+ always false.\n\
+ - kind: `\"desktop\"` for XDG `.desktop` launcher entries.\n\
+ - launch_path: the launcher command from `Exec=` (field codes stripped). \
+ Pass to `launch_app(launch_path=...)`.\n\
+ - bundle_id: the XDG \"desktop file id\" — the `.desktop` file's path \
+ relative to its XDG `applications/` root with the `.desktop` suffix \
+ stripped and path separators replaced with `-` \
+ (e.g. `kde4/konqbrowser.desktop` → `kde4-konqbrowser`).\n\
+ - last_used: RFC3339 mtime of the `.desktop` file, when readable.\n\n\
+ Running apps come from `/proc`. Installed apps come from XDG Desktop Entry \
+ files in $XDG_DATA_HOME/applications and each $XDG_DATA_DIRS entry's \
+ applications/ subdir. Entries with `NoDisplay=true` or `Hidden=true` are \
+ filtered. A `.desktop` file whose launcher matches a running process \
+ (by basename) is merged into a single entry with `running: true`.\n\n\
+ Use this for \"is X installed?\" as well as \"is X running?\". For per-window \
+ state — visibility, geometry, titles — call list_windows instead.".into(),
input_schema: json!({"type":"object","properties":{},"additionalProperties":false}),
read_only: true, destructive: false, idempotent: true, open_world: false,
})
}
async fn invoke(&self, _args: Value) -> ToolResult {
- let procs = tokio::task::spawn_blocking(|| crate::proc_fs::list_processes()).await.unwrap_or_default();
- let mut lines = vec![format!("Found {} processes:", procs.len())];
- for p in &procs {
- let cmd = if p.cmdline.is_empty() { p.name.clone() } else { p.cmdline.clone() };
- lines.push(format!(" {} (pid {})", cmd, p.pid));
+ let apps = tokio::task::spawn_blocking(|| -> Vec<serde_json::Value> {
+ let procs = crate::proc_fs::list_processes();
+ let installed = crate::installed_apps::list_installed_apps();
+
+ // Match running processes to installed apps by executable
+ // basename (Exec=firefox %u → "firefox"; cmdline /usr/bin/firefox
+ // → "firefox"). Many distros register multiple .desktop entries
+ // sharing the same basename (e.g. several `firefox` profiles, a
+ // `code` and a `code-insiders` both shelling `code`), so the
+ // bucket is `Vec<usize>` — we pick a winner per running process
+ // via `disambiguate_installed_match` instead of overwriting.
+ let mut by_exe: std::collections::HashMap<String, Vec<usize>> =
+ std::collections::HashMap::new();
+ for (i, app) in installed.iter().enumerate() {
+ let basename = exec_basename(&app.launch_path);
+ if !basename.is_empty() {
+ by_exe.entry(basename).or_default().push(i);
+ }
+ }
+
+ let mut consumed: std::collections::HashSet<usize> =
+ std::collections::HashSet::new();
+ let mut out = Vec::new();
+ for p in &procs {
+ let key_source = if !p.cmdline.is_empty() { &p.cmdline } else { &p.name };
+ let basename = exec_basename(key_source);
+ if basename.is_empty() { continue }
+ let candidates = by_exe.get(&basename).map(|v| v.as_slice()).unwrap_or(&[]);
+ let merged = disambiguate_installed_match(candidates, &installed, key_source);
+ if let Some(idx) = merged { consumed.insert(idx); }
+ let (name, bundle_id, launch_path, kind, last_used) = match merged {
+ Some(idx) => {
+ let a = &installed[idx];
+ (
+ a.name.clone(),
+ Some(a.bundle_id.clone()),
+ Some(a.launch_path.clone()),
+ Some("desktop".to_owned()),
+ a.last_used.clone(),
+ )
+ }
+ None => (
+ if !p.name.is_empty() { p.name.clone() } else { basename.clone() },
+ None,
+ None,
+ None,
+ None,
+ ),
+ };
+ out.push(json!({
+ "pid": p.pid,
+ "bundle_id": bundle_id,
+ "name": name,
+ "running": true,
+ "active": false,
+ "kind": kind,
+ "launch_path": launch_path,
+ "last_used": last_used,
+ "windows": Vec::<serde_json::Value>::new(),
+ }));
+ }
+ for (i, app) in installed.iter().enumerate() {
+ if consumed.contains(&i) { continue }
+ out.push(json!({
+ "pid": 0,
+ "bundle_id": app.bundle_id.clone(),
+ "name": app.name.clone(),
+ "running": false,
+ "active": false,
+ "kind": "desktop",
+ "launch_path": app.launch_path.clone(),
+ "last_used": app.last_used.clone(),
+ "windows": Vec::<serde_json::Value>::new(),
+ }));
+ }
+ out
+ }).await.unwrap_or_default();
+
+ let running_count = apps.iter().filter(|a| a["running"].as_bool().unwrap_or(false)).count();
+ let total = apps.len();
+ let installed_only = total - running_count;
+ let mut lines = vec![format!(
+ "✅ Found {total} app(s): {running_count} running, {installed_only} installed-not-running."
+ )];
+ for app in apps.iter().filter(|a| a["running"].as_bool().unwrap_or(false)) {
+ let name = app["name"].as_str().unwrap_or("?");
+ let pid = app["pid"].as_u64().unwrap_or(0);
+ lines.push(format!("- {name} (pid {pid})"));
}
- let structured = json!({ "processes": procs.iter().map(|p| json!({
- "pid": p.pid, "name": p.name, "cmdline": p.cmdline
- })).collect::<Vec<_>>() });
+ // Unified `apps` array + legacy `processes` alias for older callers.
+ let structured = json!({
+ "apps": apps,
+ "processes": apps.iter().filter(|a| a["running"].as_bool().unwrap_or(false))
+ .map(|a| json!({
+ "pid": a["pid"], "name": a["name"]
+ })).collect::<Vec<_>>(),
+ });
ToolResult::text(lines.join("\n")).with_structured(structured)
}
}
+/// Pick which of several `.desktop`-derived installed apps best matches a
+/// running process whose basename collided. Precedence:
+/// 1. exact full-launch-path equality with the process's cmdline token
+/// (so `/usr/bin/firefox` beats `/snap/firefox/current/firefox`)
+/// 2. most recently modified launcher (`last_used` desc, RFC3339 string
+/// ordering is lexicographic-safe for our format)
+/// 3. first candidate (deterministic by source order)
+fn disambiguate_installed_match(
+ candidates: &[usize],
+ installed: &[crate::installed_apps::InstalledApp],
+ proc_key_source: &str,
+) -> Option<usize> {
+ if candidates.is_empty() { return None; }
+ if candidates.len() == 1 { return Some(candidates[0]); }
+
+ // Look for an exact path match against the cmdline's first token.
+ let proc_path = proc_key_source.split_whitespace().next().unwrap_or("");
+ if !proc_path.is_empty() {
+ if let Some(&idx) = candidates.iter().find(|&&i| installed[i].launch_path == proc_path) {
+ return Some(idx);
+ }
+ }
+
+ // Fall back to the candidate with the most recent `last_used`.
+ candidates
+ .iter()
+ .copied()
+ .max_by(|&a, &b| {
+ installed[a]
+ .last_used
+ .as_deref()
+ .unwrap_or("")
+ .cmp(installed[b].last_used.as_deref().unwrap_or(""))
+ })
+ .or_else(|| candidates.first().copied())
+}
+
+/// Return the lowercase basename of an executable token, stripping any
+/// leading shell-wrapper words and quoting. `env FOO=1 /usr/bin/firefox %U`
+/// → `firefox`. `firefox %u` → `firefox`.
+fn exec_basename(s: &str) -> String {
+ // Take the first whitespace-separated token that looks like a binary,
+ // skipping `env`-style prefixes and `K=V` assignments.
+ for tok in s.split_whitespace() {
+ if tok == "env" { continue }
+ if tok.contains('=') && !tok.starts_with('/') && !tok.starts_with('-') {
+ // `FOO=bar` env-var assignment — skip.
+ continue;
+ }
+ let cleaned = tok.trim_matches(|c| c == '"' || c == '\'');
+ let basename = std::path::Path::new(cleaned)
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or(cleaned);
+ return basename.to_ascii_lowercase();
+ }
+ String::new()
+}
+
// ── list_windows ─────────────────────────────────────────────────────────────
pub struct ListWindowsTool;
@@ -260,9 +426,12 @@ impl Tool for LaunchAppTool {
fn def(&self) -> &ToolDef {
LAUNCH_DEF.get_or_init(|| ToolDef {
name: "launch_app".into(),
- description: "Launch a Linux app in the background. Provide name (app name, launched via \
- xdg-open or direct exec), bundle_id (ignored on Linux), or urls (list of URLs to open).".into(),
+ description: "Launch a Linux app in the background. Provide launch_path (preferred — \
+ round-trip the value from list_apps), name (app name, launched via xdg-open or \
+ direct exec), bundle_id (ignored on Linux), or urls (list of URLs to open). \
+ Resolution precedence: launch_path > name > bundle_id.".into(),
input_schema: json!({"type":"object","properties":{
+ "launch_path":{"type":"string","description":"Round-trip the `launch_path` returned by `list_apps` — the Exec= command from the .desktop file with XDG field codes already stripped. Highest precedence on Linux; spawned directly via the system shell."},
"name":{"type":"string","description":"App name or command to launch."},
"bundle_id":{"type":"string","description":"Ignored on Linux (macOS/Windows concept)."},
"urls":{"type":"array","items":{"type":"string"},"description":"URLs to open via xdg-open."}
@@ -272,13 +441,14 @@ impl Tool for LaunchAppTool {
}
async fn invoke(&self, args: Value) -> ToolResult {
+ let launch_path_opt = args.get("launch_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 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();
- if name_opt.is_none() && urls.is_empty() {
- return ToolResult::error("Provide at least one of: name or urls.");
+ if launch_path_opt.is_none() && name_opt.is_none() && urls.is_empty() {
+ return ToolResult::error("Provide at least one of: launch_path, name, or urls.");
}
let result = tokio::task::spawn_blocking(move || -> anyhow::Result<String> {
@@ -289,17 +459,20 @@ impl Tool for LaunchAppTool {
}
return Ok(format!("Opened {} URL(s) via xdg-open.", urls.len()));
}
- // Launch by name — try direct exec, then xdg-open.
- if let Some(name) = name_opt {
- let mut parts = name.split_whitespace();
- let prog = parts.next().unwrap_or(&name);
+ // launch_path > name. Both go through the same direct-exec path
+ // (so XDG `Exec=` commands round-trip), but launch_path is the
+ // canonical form preferred by list_apps callers.
+ let command = launch_path_opt.as_deref().or(name_opt.as_deref());
+ if let Some(cmd) = command {
+ let mut parts = cmd.split_whitespace();
+ let prog = parts.next().unwrap_or(cmd);
let rest: Vec<&str> = parts.collect();
match std::process::Command::new(prog).args(&rest).spawn() {
- Ok(child) => return Ok(format!("Launched '{}' with pid {}.", name, child.id())),
+ Ok(child) => return Ok(format!("Launched '{}' with pid {}.", cmd, child.id())),
Err(_) => {
// Fall back to xdg-open for .desktop app names.
- std::process::Command::new("xdg-open").arg(&name).spawn()?;
- return Ok(format!("Opened '{}' via xdg-open.", name));
+ std::process::Command::new("xdg-open").arg(cmd).spawn()?;
+ return Ok(format!("Opened '{}' via xdg-open.", cmd));
}
}
}
diff --git a/libs/cua-driver-rs/crates/platform-macos/src/apps/mod.rs b/libs/cua-driver-rs/crates/platform-macos/src/apps/mod.rs
index 19c197adc2..b6c3a4b618 100644
--- a/libs/cua-driver-rs/crates/platform-macos/src/apps/mod.rs
+++ b/libs/cua-driver-rs/crates/platform-macos/src/apps/mod.rs
@@ -12,6 +12,22 @@ pub struct AppInfo {
pub bundle_id: Option<String>,
pub running: bool,
pub active: bool,
+ /// Per-platform "how launch_app would consume this entry".
+ ///
+ /// On macOS: filesystem path to the `.app` bundle (e.g. `/Applications/Safari.app`)
+ /// when known. `None` for entries that came only from `NSWorkspace`'s
+ /// runtime list and whose bundle path could not be resolved.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub launch_path: Option<String>,
+ /// Kind discriminator. macOS reports `"desktop"` for every `.app` bundle.
+ /// Reserved for future use on platforms with packaged-app distinctions
+ /// (e.g. Windows UWP packages).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub kind: Option<String>,
+ /// RFC3339 timestamp of the launcher's filesystem `LastAccessTime` /
+ /// `mtime`, when available. `None` when the field could not be read.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub last_used: Option<String>,
}
/// Enumerate running apps with NSApplicationActivationPolicyRegular.
@@ -73,7 +89,16 @@ fn parse_osascript_app_list(text: &str) -> Vec<AppInfo> {
};
let active = parts.get(3).map(|s| s.trim() == "1").unwrap_or(false);
if name.is_empty() || pid == 0 { continue; }
- apps.push(AppInfo { name, pid, bundle_id, running: true, active });
+ apps.push(AppInfo {
+ name,
+ pid,
+ bundle_id,
+ running: true,
+ active,
+ launch_path: None,
+ kind: Some("desktop".to_owned()),
+ last_used: None,
+ });
}
apps
}
@@ -325,13 +350,39 @@ fn bundle_id_for_app_path(app_path: &str) -> Option<String> {
}
/// Return all apps: running apps merged with installed-but-not-running apps.
+///
+/// Single flat array. Each entry carries:
+/// * `running` (true for currently-live processes, false for installed-only),
+/// * `pid` (live pid when running, `0` otherwise),
+/// * `launch_path` (filesystem `.app` path when known, else `None`),
+/// * `kind` (`"desktop"` on macOS).
pub fn list_all_apps() -> Vec<AppInfo> {
- let running = list_running_apps();
+ let mut running = list_running_apps();
+ let installed = scan_installed_apps();
+ // Lookup: bundle_id → (launch_path, last_used) from the installed scan.
+ let installed_by_bundle: std::collections::HashMap<String, (Option<String>, Option<String>)> =
+ installed.iter()
+ .filter_map(|a| a.bundle_id.clone().map(|b| (b, (a.launch_path.clone(), a.last_used.clone()))))
+ .collect();
+ // Backfill running entries with the launch_path the installed scan resolved.
+ for app in running.iter_mut() {
+ if let Some(bid) = &app.bundle_id {
+ if let Some((path, last_used)) = installed_by_bundle.get(bid) {
+ if app.launch_path.is_none() {
+ app.launch_path = path.clone();
+ }
+ if app.last_used.is_none() {
+ app.last_used = last_used.clone();
+ }
+ }
+ }
+ }
+
let running_bundles: std::collections::HashSet<String> = running.iter()
.filter_map(|a| a.bundle_id.clone())
.collect();
- let mut installed = scan_installed_apps();
+ let mut installed = installed;
// Remove apps already in running list.
installed.retain(|a| !a.bundle_id.as_ref().map_or(false, |b| running_bundles.contains(b)));
@@ -361,7 +412,10 @@ fn scan_installed_apps() -> Vec<AppInfo> {
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("app") { continue }
let plist_path = path.join("Contents/Info.plist");
- if let Some(info) = read_app_plist(&plist_path) {
+ if let Some(mut info) = read_app_plist(&plist_path) {
+ info.launch_path = path.to_str().map(str::to_owned);
+ info.kind = Some("desktop".to_owned());
+ info.last_used = fs_last_used(&path);
result.push(info);
}
}
@@ -369,6 +423,45 @@ fn scan_installed_apps() -> Vec<AppInfo> {
result
}
+/// Read the bundle's filesystem `mtime` and serialize as RFC3339.
+/// Used as `last_used` heuristic — macOS doesn't reliably surface
+/// LaunchServices' true "last launched" timestamp without entitlements,
+/// so we approximate with whichever of `atime`/`mtime` the filesystem
+/// preserves (mtime is the more portable of the two).
+fn fs_last_used(path: &std::path::Path) -> Option<String> {
+ let meta = std::fs::metadata(path).ok()?;
+ let modified = meta.modified().ok()?;
+ let duration = modified.duration_since(std::time::UNIX_EPOCH).ok()?;
+ Some(unix_secs_to_rfc3339(duration.as_secs() as i64))
+}
+
+/// Format a Unix epoch seconds value as `YYYY-MM-DDTHH:MM:SSZ` (UTC).
+/// Hand-rolled to avoid pulling in a date/time crate just for this.
+pub(crate) fn unix_secs_to_rfc3339(secs: i64) -> String {
+ // Days since 1970-01-01 + civil date breakdown per Howard Hinnant's algorithm.
+ let days = secs.div_euclid(86_400);
+ let seconds_of_day = secs.rem_euclid(86_400);
+ let hour = seconds_of_day / 3600;
+ let minute = (seconds_of_day % 3600) / 60;
+ let second = seconds_of_day % 60;
+
+ let z = days + 719_468;
+ let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
+ let doe = (z - era * 146_097) as u64; // [0, 146096]
+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399]
+ let y = yoe as i64 + era * 400;
+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
+ let mp = (5 * doy + 2) / 153; // [0, 11]
+ let d = doy - (153 * mp + 2) / 5 + 1; // [1, 31]
+ let m = if mp < 10 { mp + 3 } else { mp - 9 }; // [1, 12]
+ let y = if m <= 2 { y + 1 } else { y };
+
+ format!(
+ "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
+ y, m, d, hour, minute, second
+ )
+}
+
fn read_app_plist(plist_path: &std::path::Path) -> Option<AppInfo> {
let bundle_id_out = Command::new("plutil")
.args(["-extract", "CFBundleIdentifier", "raw", "-o", "-",
@@ -413,6 +506,9 @@ fn read_app_plist(plist_path: &std::path::Path) -> Option<AppInfo> {
bundle_id: Some(bundle_id),
running: false,
active: false,
+ launch_path: None,
+ kind: None,
+ last_used: None,
})
}
@@ -483,3 +579,58 @@ pub fn format_app_list(apps: &[AppInfo]) -> String {
}
lines.join("\n")
}
+
+#[cfg(test)]
+mod tests {
+ use super::unix_secs_to_rfc3339;
+
+ #[test]
+ fn rfc3339_epoch() {
+ assert_eq!(unix_secs_to_rfc3339(0), "1970-01-01T00:00:00Z");
+ }
+
+ #[test]
+ fn rfc3339_negative_pre_epoch() {
+ // 1969-12-31T23:59:59Z = epoch - 1 second.
+ assert_eq!(unix_secs_to_rfc3339(-1), "1969-12-31T23:59:59Z");
+ // 1969-01-01T00:00:00Z = epoch - 365 days.
+ assert_eq!(unix_secs_to_rfc3339(-365 * 86_400), "1969-01-01T00:00:00Z");
+ }
+
+ #[test]
+ fn rfc3339_leap_day_in_leap_year() {
+ // 2020-02-29T12:00:00Z. Days from 1970-01-01:
+ // 50 years * 365 + 13 leap days (1972..=2020 inclusive of 13) - 1
+ // (Feb 29 is the 60th day of 2020, so 59 prior days in 2020).
+ // Use the known timestamp instead of recomputing.
+ // `date -d "2020-02-29T12:00:00Z" +%s` = 1582977600.
+ assert_eq!(unix_secs_to_rfc3339(1_582_977_600), "2020-02-29T12:00:00Z");
+ }
+
+ #[test]
+ fn rfc3339_feb_28_non_leap_year() {
+ // 2019-02-28T00:00:00Z → 1551312000.
+ assert_eq!(unix_secs_to_rfc3339(1_551_312_000), "2019-02-28T00:00:00Z");
+ // The very next second is Mar 1, not Feb 29.
+ assert_eq!(unix_secs_to_rfc3339(1_551_312_000 + 86_400), "2019-03-01T00:00:00Z");
+ }
+
+ #[test]
+ fn rfc3339_end_of_year_wrap() {
+ // 2023-12-31T23:59:59Z = 1704067199; +1 second wraps to 2024-01-01.
+ assert_eq!(unix_secs_to_rfc3339(1_704_067_199), "2023-12-31T23:59:59Z");
+ assert_eq!(unix_secs_to_rfc3339(1_704_067_200), "2024-01-01T00:00:00Z");
+ }
+
+ #[test]
+ fn rfc3339_recent_arbitrary_timestamp() {
+ // 2024-06-15T13:45:30Z → 1718459130.
+ assert_eq!(unix_secs_to_rfc3339(1_718_459_130), "2024-06-15T13:45:30Z");
+ }
+
+ #[test]
+ fn rfc3339_known_pre_2000_timestamp() {
+ // 1990-07-04T15:30:00Z → 647105400.
+ assert_eq!(unix_secs_to_rfc3339(647_105_400), "1990-07-04T15:30:00Z");
+ }
+}
diff --git a/libs/cua-driver-rs/crates/platform-macos/src/tools/list_apps.rs b/libs/cua-driver-rs/crates/platform-macos/src/tools/list_apps.rs
index 49837980e1..293ab7b6e4 100644
--- a/libs/cua-driver-rs/crates/platform-macos/src/tools/list_apps.rs
+++ b/libs/cua-driver-rs/crates/platform-macos/src/tools/list_apps.rs
@@ -9,11 +9,15 @@ static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();
fn def() -> &'static ToolDef {
DEF.get_or_init(|| ToolDef {
name: "list_apps".into(),
- // Description matches Swift `ListAppsTool.swift` verbatim.
description: "List macOS apps — both currently running and installed-but-not-running — \
with per-app state flags:\n\n\
- running: is a process for this app live? (pid is 0 when false)\n\
- - active: is it the system-frontmost app? (implies running)\n\n\
+ - active: is it the system-frontmost app? (implies running)\n\
+ - launch_path: filesystem path to the `.app` bundle, when known. \
+ Pass this to `launch_app` to start the app cold.\n\
+ - 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, \
@@ -43,13 +47,21 @@ impl Tool for ListAppsTool {
let apps = tokio::task::spawn_blocking(crate::apps::list_all_apps).await
.unwrap_or_default();
let text = crate::apps::format_app_list(&apps);
+ // Single flat array. Each entry is the unified shape — existing
+ // fields (`pid`, `name`, `bundle_id`, `running`, `active`) are
+ // unchanged for backwards compatibility; the new fields
+ // (`launch_path`, `kind`, `last_used`, `windows`) are additive.
let structured = serde_json::json!({
"apps": apps.iter().map(|a| serde_json::json!({
"pid": a.pid,
"name": a.name,
"bundle_id": a.bundle_id,
"active": a.active,
- "running": a.running
+ "running": a.running,
+ "launch_path": a.launch_path,
+ "kind": a.kind,
+ "last_used": a.last_used,
+ "windows": Vec::<serde_json::Value>::new(),
})).collect::<Vec<_>>()
});
ToolResult::text(text).with_structured(structured)
diff --git a/libs/cua-driver-rs/crates/platform-windows/Cargo.toml b/libs/cua-driver-rs/crates/platform-windows/Cargo.toml
index 4273015054..2d79fba608 100644
--- a/libs/cua-driver-rs/crates/platform-windows/Cargo.toml
+++ b/libs/cua-driver-rs/crates/platform-windows/Cargo.toml
@@ -33,10 +33,13 @@ windows = { version = "0.58", features = [
"Win32_Security",
"Win32_System_Com",
"Win32_Storage_Xps",
+ "Win32_Storage_FileSystem",
"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_Common",
"Win32_UI_Shell_PropertiesSystem",
+ "Win32_System_Com_StructuredStorage",
"Win32_Media",
"Win32_System_Registry",
# `cua-driver doctor` interactive-session probe:
@@ -44,5 +47,9 @@ windows = { version = "0.58", features = [
# - Win32_System_StationsAndDesktops → OpenWindowStationW
"Win32_System_RemoteDesktop",
"Win32_System_StationsAndDesktops",
+ # WinRT for UWP package enumeration via PackageManager.
+ "Management_Deployment",
+ "ApplicationModel",
+ "Foundation_Collections",
] }
base64 = { workspace = true }
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 144dc87997..61ddb5788d 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
@@ -115,35 +115,53 @@ impl Tool for ListAppsTool {
fn def(&self) -> &ToolDef {
LIST_APPS_DEF.get_or_init(|| ToolDef {
name: "list_apps".into(),
- // Description copied from Swift `ListAppsTool.swift` and adapted —
- // notes Windows-specific limitations (no bundle_id, no installed
- // enumeration yet). Same semantics for running/active state flags.
- description: "List Windows apps that are currently running, with per-app state flags:\n\n\
+ description: "List Windows apps — both currently running and installed-but-not-running — \
+ with per-app state flags:\n\n\
- running: is a process for this app live? (pid is 0 when false)\n\
- - active: is it the system-frontmost app? (implies running)\n\n\
- Only processes that own at least one visible top-level window are included — \
- background services and console processes are filtered out (mirrors Swift's \
- NSApplicationActivationPolicyRegular filter).\n\n\
- Use this for \"is X running?\". For per-window state — on-screen, minimized, \
- window titles — call list_windows instead. For just opening an app — running \
- or not — call launch_app({path: ...}) directly; list_apps is not a prerequisite.".into(),
+ - active: is it the system-frontmost app? (implies running)\n\
+ - kind: `\"desktop\"` for `.exe`-backed apps (resolved from Start-Menu \
+ shortcuts) or `\"uwp\"` for packaged store apps.\n\
+ - launch_path: what `launch_app` would consume.\n\
+ * desktop: full `.exe` commandline (path + any arguments preserved from \
+ the source `.lnk`; the exe is quoted when it contains whitespace).\n\
+ * uwp: `shell:appsFolder\\{PackageFamilyName}!{AppId}` where `{AppId}` \
+ falls back to `App` when the package manifest does not expose a \
+ specific Application.Id.\n\
+ - last_used: RFC3339 mtime of the launcher (`.lnk` for desktop, \
+ package install location for UWP), when readable.\n\n\
+ Running apps are derived from visible top-level windows + the foreground \
+ pid (mirrors NSApplicationActivationPolicyRegular's intent: background \
+ services and console processes are excluded). Installed apps are merged \
+ from Start-Menu `.lnk` enumeration and the WinRT PackageManager — running \
+ processes whose executable matches a Start-Menu target are folded into a \
+ single entry with `running: true`.\n\n\
+ Use this for \"is X installed?\" as well as \"is X running?\". For per-window \
+ state — on-screen, minimized, window titles — call list_windows instead. \
+ For just opening an app — running or not — call launch_app({path: ...}) \
+ directly; list_apps is not a prerequisite.".into(),
input_schema: json!({"type":"object","properties":{},"additionalProperties":false}),
read_only: true, destructive: false, idempotent: true, open_world: false,
})
}
async fn invoke(&self, _args: Value) -> ToolResult {
- // Strategy (port of `AppEnumerator.apps()` semantics):
- // 1. Enumerate top-level visible windows; their owner pids are the
- // "running apps with a user-facing surface".
- // 2. Look up each pid's executable name via the process table.
- // 3. Mark `active` for the pid that owns GetForegroundWindow.
+ // Strategy:
+ // 1. Enumerate top-level visible windows → derive the set of running pids
+ // that have a user-facing surface.
+ // 2. Enumerate the process table to map pid → executable name and full
+ // path (used to merge against Start-Menu / UWP launch_paths).
+ // 3. Enumerate installed apps from Start-Menu shortcuts + WinRT
+ // PackageManager. Each installed entry has a launch_path.
+ // 4. Merge: a running pid whose executable path matches an installed
+ // desktop launch_path becomes a single entry with running=true and
+ // that launch_path. Remaining installed entries are emitted with
+ // running=false, pid=0. Remaining running pids (no installed-app
+ // match) are emitted as running=true with launch_path=null.
let apps = tokio::task::spawn_blocking(|| -> Vec<serde_json::Value> {
use windows::Win32::UI::WindowsAndMessaging::GetForegroundWindow;
use windows::Win32::UI::WindowsAndMessaging::GetWindowThreadProcessId;
let wins = crate::win32::list_windows(None);
- // Deduplicate by pid — one app may own several top-level windows.
let mut seen_pids = std::collections::HashSet::new();
let mut running_pids: Vec<u32> = Vec::new();
for w in &wins {
@@ -158,46 +176,139 @@ impl Tool for ListAppsTool {
};
let procs = crate::win32::list_processes();
- let pid_to_name: std::collections::HashMap<u32, &str> =
- procs.iter().map(|p| (p.pid, p.name.as_str())).collect();
-
- running_pids.iter().map(|&pid| {
- let name = pid_to_name.get(&pid).copied().unwrap_or("<unknown>");
- json!({
- "pid": pid,
- "bundle_id": serde_json::Value::Null, // Windows has no bundle ID concept
- "name": name,
- "running": true,
- "active": pid == foreground_pid,
- })
- }).collect()
+ let pid_to_name: std::collections::HashMap<u32, String> =
+ procs.iter().map(|p| (p.pid, p.name.clone())).collect();
+
+ let installed = crate::win32::list_installed_apps();
+ // Lowercase-exe-basename → installed-app indices. We match running
+ // processes by basename rather than full path because the process
+ // table's executable name is `notepad.exe` while the Start-Menu
+ // shortcut target is `C:\Windows\System32\notepad.exe` — both
+ // sides need to be normalised to compare. Multiple Start-Menu
+ // shortcuts often target the same basename (different `chrome.exe`
+ // launchers, multiple `code.exe` profiles, …), so we bucket as
+ // `Vec<usize>` and let `disambiguate_installed_match` pick a
+ // winner per running pid rather than letting the last write win.
+ let mut by_exe: std::collections::HashMap<String, Vec<usize>> =
+ std::collections::HashMap::new();
+ for (i, app) in installed.iter().enumerate() {
+ if app.kind == "desktop" {
+ let basename = std::path::Path::new(&app.launch_path)
+ .file_name()
+ .and_then(|s| s.to_str())
+ .unwrap_or("")
+ .to_ascii_lowercase();
+ if !basename.is_empty() {
+ by_exe.entry(basename).or_default().push(i);
+ }
+ }
+ }
+
+ let mut consumed_installed: std::collections::HashSet<usize> =
+ std::collections::HashSet::new();
+ let mut out: Vec<serde_json::Value> = Vec::new();
+
+ for &pid in &running_pids {
+ let name = pid_to_name.get(&pid).cloned().unwrap_or_else(|| "<unknown>".into());
+ let key = name.to_ascii_lowercase();
+ let candidates = by_exe.get(&key).map(|v| v.as_slice()).unwrap_or(&[]);
+ let merged = disambiguate_installed_match(candidates, &installed, &name);
+ if let Some(idx) = merged { consumed_installed.insert(idx); }
+ let (display_name, bundle_id, launch_path, kind, last_used) = match merged {
+ Some(idx) => {
+ let a = &installed[idx];
+ (
+ a.name.clone(),
+ Some(a.bundle_id.clone()),
+ Some(a.launch_path.clone()),
+ Some(a.kind.clone()),
+ a.last_used.clone(),
+ )
+ }
+ None => (name, None, None, Some("desktop".to_owned()), None),
+ };
+ out.push(json!({
+ "pid": pid,
+ "bundle_id": bundle_id,
+ "name": display_name,
+ "running": true,
+ "active": pid == foreground_pid,
+ "kind": kind,
+ "launch_path": launch_path,
+ "last_used": last_used,
+ "windows": Vec::<serde_json::Value>::new(),
+ }));
+ }
+ for (i, app) in installed.iter().enumerate() {
+ if consumed_installed.contains(&i) { continue }
+ out.push(json!({
+ "pid": 0,
+ "bundle_id": app.bundle_id.clone(),
+ "name": app.name.clone(),
+ "running": false,
+ "active": false,
+ "kind": app.kind.clone(),
+ "launch_path": app.launch_path.clone(),
+ "last_used": app.last_used.clone(),
+ "windows": Vec::<serde_json::Value>::new(),
+ }));
+ }
+ out
}).await.unwrap_or_default();
let running_count = apps.iter().filter(|a| a["running"].as_bool().unwrap_or(false)).count();
let total = apps.len();
let installed_only = total - running_count;
- // Match Swift's text format: header line + bullet per running app.
let mut lines = vec![format!(
"✅ Found {total} app(s): {running_count} running, {installed_only} installed-not-running."
)];
for app in apps.iter().filter(|a| a["running"].as_bool().unwrap_or(false)) {
let name = app["name"].as_str().unwrap_or("?");
let pid = app["pid"].as_u64().unwrap_or(0);
- // Windows lacks bundle_id; omit the trailing [bundle] segment.
lines.push(format!("- {name} (pid {pid})"));
}
- // `apps` key (matches Swift `Output.apps`); `processes` key kept as
- // an alias for any pre-existing Rust callers that read the old shape.
+ // `apps` is the unified shape; `processes` retained for any pre-existing
+ // callers that consumed the old running-only shape.
let structured = json!({
"apps": apps,
- "processes": apps.iter().map(|a| json!({
- "pid": a["pid"], "name": a["name"]
- })).collect::<Vec<_>>(),
+ "processes": apps.iter().filter(|a| a["running"].as_bool().unwrap_or(false))
+ .map(|a| json!({
+ "pid": a["pid"], "name": a["name"]
+ })).collect::<Vec<_>>(),
});
ToolResult::text(lines.join("\n")).with_structured(structured)
}
}
+/// Pick which of several Start-Menu / UWP-derived installed apps best matches
+/// a running pid whose exe basename collided. Precedence:
+/// 1. exact case-insensitive equality between `proc_exe_basename` and the
+/// installed app's launch_path basename (always true here; left for
+/// future per-path matches if we ever bucket on something coarser)
+/// 2. most recently modified launcher (`last_used` desc — RFC3339 strings
+/// are lexicographically ordered the same as chronologically)
+/// 3. first candidate (deterministic by source order)
+fn disambiguate_installed_match(
+ candidates: &[usize],
+ installed: &[crate::win32::InstalledApp],
+ _proc_exe_basename: &str,
+) -> Option<usize> {
+ if candidates.is_empty() { return None; }
+ if candidates.len() == 1 { return Some(candidates[0]); }
+
+ candidates
+ .iter()
+ .copied()
+ .max_by(|&a, &b| {
+ installed[a]
+ .last_used
+ .as_deref()
+ .unwrap_or("")
+ .cmp(installed[b].last_used.as_deref().unwrap_or(""))
+ })
+ .or_else(|| candidates.first().copied())
+}
+
// ── list_windows ─────────────────────────────────────────────────────────────
pub struct ListWindowsTool;
@@ -484,6 +595,48 @@ impl Tool for GetWindowStateTool {
}
}
+/// Split a `launch_path` round-tripped from `list_apps` into a single
+/// ShellExecuteEx `lpFile` token plus a trailing arguments string. Handles
+/// three input shapes:
+/// - bare path (`C:\Windows\notepad.exe`): returns `(path, "")`
+/// - quoted-exe + args (`"C:\Path\chrome.exe" --foo --bar`): returns the
+/// unquoted path + the rest
+/// - AUMID / shell launch token (`shell:appsFolder\..!..`): returns the
+/// whole string as the file token with empty args (the shell resolver
+/// handles these directly)
+///
+/// Args are returned trimmed; their internal quoting is preserved as-is so
+/// `--profile-directory="Profile 2"` survives.
+fn split_launchable_target(s: &str) -> (String, String) {
+ let trimmed = s.trim();
+ if trimmed.is_empty() { return (String::new(), String::new()); }
+ // AUMID / shell launch tokens go through unchanged.
+ if trimmed.starts_with("shell:") || trimmed.contains('!') {
+ return (trimmed.to_owned(), String::new());
+ }
+ if let Some(rest) = trimmed.strip_prefix('"') {
+ if let Some(close) = rest.find('"') {
+ let path = &rest[..close];
+ let args = rest[close + 1..].trim_start().to_owned();
+ return (path.to_owned(), args);
+ }
+ // Unterminated quote — fall through and hand the whole thing back.
+ return (trimmed.to_owned(), String::new());
+ }
+ // No quoting: be permissive. If the input contains a space and the
+ // first whitespace-separated token names a `.exe`, treat it as
+ // `<exe> <args>`. Otherwise hand the string back whole (lets bare paths
+ // with embedded spaces still work — most installs put `Program Files`
+ // shortcuts through the quoted branch above).
+ if let Some(first_space) = trimmed.find(char::is_whitespace) {
+ let (first, rest) = trimmed.split_at(first_space);
+ if first.to_ascii_lowercase().ends_with(".exe") {
+ return (first.to_owned(), rest.trim_start().to_owned());
+ }
+ }
+ (trimmed.to_owned(), String::new())
+}
+
// ── launch_app ───────────────────────────────────────────────────────────────
pub struct LaunchAppTool;
@@ -530,10 +683,11 @@ impl Tool for LaunchAppTool {
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":"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."},
+ "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, path, or launch_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."},
+ "path":{"type":"string","description":"Full path to executable. Windows-only; takes precedence over name/bundle_id/aumid (but not over `launch_path`)."},
+ "launch_path":{"type":"string","description":"Round-trip the `launch_path` returned by `list_apps`. Highest precedence — when set, this exact string is handed to ShellExecuteEx unchanged. For Windows desktop apps it's the full `.exe` commandline (path + arguments preserved from the source shortcut); for UWP apps it's `shell:appsFolder\\{PackageFamilyName}!{AppId}`. For precise UWP pid capture, prefer `aumid` over `launch_path`."},
"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 (or activation arguments for packaged apps)."},
"electron_debugging_port":{"type":"integer","description":"Accepted for cross-platform parity; currently no-op on Windows."},
@@ -545,6 +699,7 @@ impl Tool for LaunchAppTool {
}
async fn invoke(&self, args: Value) -> ToolResult {
+ let launch_path_opt = args.get("launch_path").and_then(|v| v.as_str()).map(str::to_owned);
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);
@@ -556,8 +711,12 @@ 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 > aumid > name > bundle_id (alias of name on Windows).
- let target = path_opt.clone()
+ // Resolve target — launch_path > path > aumid > name > bundle_id
+ // (alias of name on Windows). launch_path is highest precedence for
+ // round-trip with list_apps; the value is handed to ShellExecuteEx
+ // unchanged (UWP routing below is bypassed when launch_path is set).
+ let target = launch_path_opt.clone()
+ .or(path_opt.clone())
.or(aumid_opt.clone())
.or(name_opt.clone())
.or(bundle_id_opt.clone());
@@ -570,19 +729,23 @@ impl Tool for LaunchAppTool {
// ── 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
+ // 1. `launch_path` set: skip UWP routing entirely — round-trip
+ // semantics demand the value be handed to ShellExecuteEx
+ // unchanged. Callers wanting precise UWP pid capture should
+ // pass `aumid` instead.
+ // 2. `aumid` parameter (any value): packaged path, AUMID = value.
+ // 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).
- // 3. `name` with no `path`: try `shell:AppsFolder` lookup; on a
+ // 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. Anything else: existing ShellExecuteExW 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 aumid_for_uwp: Option<String> = if path_opt.is_some() {
+ 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() {
Some(a)
@@ -606,7 +769,35 @@ impl Tool for LaunchAppTool {
.clone()
.or_else(|| target.clone())
.unwrap_or_else(|| urls.join(", "));
- let extra_joined = extra_args.join(" ");
+
+ // When the resolved target came from `launch_path` it may carry
+ // shortcut arguments (e.g. `"C:\Path\chrome.exe" --profile-directory="Profile 2"`).
+ // Split it into a file token + arguments tail so ShellExecuteEx
+ // sees them separately — passing the whole string as lpFile would
+ // fail because the shell only resolves a single filesystem path
+ // there. No-op for AUMID tokens / plain paths without args / UWP
+ // `shell:appsFolder\..!..` tokens.
+ 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() {
+ let (file, args_tail) = split_launchable_target(t);
+ let combined = if args_tail.is_empty() {
+ base_extra
+ } else if base_extra.is_empty() {
+ args_tail
+ } else {
+ format!("{args_tail} {base_extra}")
+ };
+ let file_opt = if file.is_empty() { None } else { Some(file) };
+ (file_opt, combined)
+ } else {
+ (None, base_extra)
+ }
+ } else {
+ (target.clone(), base_extra)
+ }
+ };
// Branch: AUMID activation if we resolved one; else legacy
// ShellExecuteExW. Both branches still need to handle `urls`
@@ -628,9 +819,10 @@ impl Tool for LaunchAppTool {
}
} else {
// Legacy ShellExecuteExW path — unchanged behavior for plain
- // Win32 apps and for callers passing an explicit `path`.
+ // Win32 apps and for callers passing an explicit `path` /
+ // `launch_path`.
let urls_clone = urls.clone();
- let target_for_shell = target.clone();
+ let target_for_shell = target_file_opt.clone();
let extra_for_shell = extra_joined.clone();
let result = tokio::task::spawn_blocking(move || -> anyhow::Result<u32> {
use windows::Win32::UI::Shell::{
diff --git a/libs/cua-driver-rs/crates/platform-windows/src/win32/installed_apps.rs b/libs/cua-driver-rs/crates/platform-windows/src/win32/installed_apps.rs
new file mode 100644
index 0000000000..24ea4dbea8
--- /dev/null
+++ b/libs/cua-driver-rs/crates/platform-windows/src/win32/installed_apps.rs
@@ -0,0 +1,301 @@
+//! Windows installed-app enumeration.
+//!
+//! Two sources:
+//!
+//! 1. **Start Menu shortcuts**: walks `[CSIDL_COMMON_PROGRAMS]\` and
+//! `[CSIDL_PROGRAMS]\` recursively, resolves each `.lnk` via
+//! `IShellLinkW::GetPath`, and emits one entry per `.exe` target.
+//!
+//! 2. **UWP / packaged apps**: queries WinRT
+//! `PackageManager::FindPackagesWithPackageTypes(Main)` for every
+//! `Main` package installed in the current context. Builds the
+//! `shell:appsFolder\{PackageFamilyName}!{AppId}` launch token so
+//! callers can hand it to `launch_app`; `{AppId}` falls back to `App`
+//! when the package manifest does not surface a specific
+//! Application.Id.
+
+use std::path::{Path, PathBuf};
+use windows::core::{Interface, PCWSTR};
+use windows::Win32::Foundation::MAX_PATH;
+use windows::Win32::System::Com::{
+ CoCreateInstance, CoInitializeEx, CoUninitialize, IPersistFile,
+ CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, STGM,
+};
+use windows::Win32::UI::Shell::{IShellLinkW, ShellLink, SLGP_RAWPATH};
+
+/// Parsed metadata for an installed Windows application.
+#[derive(Debug, Clone)]
+pub struct InstalledApp {
+ /// Display name. For Start-Menu apps: the `.lnk` basename (sans extension).
+ /// For UWP apps: the package `DisplayName` from the manifest, falling back
+ /// to the package family name when not surfaced.
+ pub name: String,
+ /// Stable identifier. For Start-Menu apps: the resolved `.exe` path.
+ /// For UWP apps: the package family name (e.g. `Microsoft.WindowsCalculator_8wekyb3d8bbwe`).
+ pub bundle_id: String,
+ /// `"desktop"` for `.lnk`-backed apps, `"uwp"` for packaged apps.
+ pub kind: String,
+ /// What `launch_app(path=...)` would consume.
+ /// - Desktop: absolute `.exe` path, plus any commandline arguments the
+ /// source `.lnk` carries (e.g.
+ /// `"C:\\Path\\chrome.exe" --profile-directory="Profile 2"`).
+ /// The exe path is quoted when it contains whitespace.
+ /// - UWP: `shell:appsFolder\{PackageFamilyName}!{AppId}` — `{AppId}`
+ /// falls back to `App` when the package manifest doesn't surface a
+ /// specific `Application.Id`.
+ pub launch_path: String,
+ /// RFC3339 mtime of the launcher (`.lnk` for desktop, package install
+ /// path for UWP), when readable; `None` otherwise.
+ pub last_used: Option<String>,
+}
+
+/// Aggregate Start-Menu shortcuts and UWP packages into one list.
+///
+/// Errors from either source are swallowed — the goal is best-effort
+/// enumeration, not a guaranteed-complete catalog.
+pub fn list_installed_apps() -> Vec<InstalledApp> {
+ let mut out = Vec::new();
+ out.extend(scan_start_menu());
+ out.extend(scan_uwp_packages());
+
+ // Dedupe by (kind, bundle_id) — Start Menu may list both a per-user and a
+ // machine-wide shortcut for the same .exe target.
+ let mut seen = std::collections::HashSet::new();
+ out.retain(|a| seen.insert((a.kind.clone(), a.bundle_id.clone())));
+ out.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
+ out
+}
+
+// ── Start Menu (.lnk) scan ───────────────────────────────────────────────────
+
+fn scan_start_menu() -> Vec<InstalledApp> {
+ let mut out = Vec::new();
+ let roots = start_menu_roots();
+ // COM init for IShellLinkW. Best-effort — if Apartment-threaded init
+ // fails (already-initialized as MTA on this thread), the calls below
+ // still succeed because IShellLinkW is registered for both apartments.
+ let init = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
+ for root in roots {
+ let _ = walk_for_lnks(&root, &mut out);
+ }
+ if init.is_ok() {
+ unsafe { CoUninitialize() };
+ }
+ out
+}
+
+fn start_menu_roots() -> Vec<PathBuf> {
+ let mut out = Vec::new();
+ if let Ok(p) = std::env::var("ProgramData") {
+ // CSIDL_COMMON_PROGRAMS — machine-wide Start Menu.
+ out.push(PathBuf::from(format!("{p}\\Microsoft\\Windows\\Start Menu\\Programs")));
+ }
+ if let Ok(p) = std::env::var("APPDATA") {
+ // CSIDL_PROGRAMS — per-user Start Menu.
+ out.push(PathBuf::from(format!("{p}\\Microsoft\\Windows\\Start Menu\\Programs")));
+ }
+ out
+}
+
+fn walk_for_lnks(dir: &Path, sink: &mut Vec<InstalledApp>) -> std::io::Result<()> {
+ let entries = std::fs::read_dir(dir)?;
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if path.is_dir() {
+ let _ = walk_for_lnks(&path, sink);
+ continue;
+ }
+ if path.extension().and_then(|e| e.to_str()).map(|s| s.eq_ignore_ascii_case("lnk")) != Some(true) {
+ continue;
+ }
+ if let Some(app) = resolve_lnk(&path) {
+ sink.push(app);
+ }
+ }
+ Ok(())
+}
+
+/// Resolve a `.lnk` to its target via IShellLinkW. Returns `None` if the
+/// target isn't a `.exe` or the resolve failed.
+///
+/// The `launch_path` is the full commandline — the resolved executable path
+/// followed by `IShellLinkW::GetArguments` when non-empty. Many real-world
+/// shortcuts encode behavior in their arguments (Chrome profile launchers,
+/// per-workspace VS Code shortcuts), so dropping the args would break
+/// `launch_app(path=...)` round-trips. The `bundle_id` stays as the exe
+/// path alone so the by-basename merge logic in list_apps still works.
+fn resolve_lnk(lnk_path: &Path) -> Option<InstalledApp> {
+ let (target, args) = unsafe { read_lnk_target(lnk_path) }.ok()?;
+ if !target.to_ascii_lowercase().ends_with(".exe") {
+ return None;
+ }
+ let name = lnk_path
+ .file_stem()
+ .and_then(|s| s.to_str())
+ .unwrap_or("")
+ .to_owned();
+ if name.is_empty() { return None; }
+
+ let last_used = std::fs::metadata(lnk_path)
+ .ok()
+ .and_then(|m| m.modified().ok())
+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
+ .map(|d| unix_secs_to_rfc3339(d.as_secs() as i64));
+
+ let launch_path = if args.trim().is_empty() {
+ target.clone()
+ } else {
+ // Quote the exe path if it contains whitespace so a shell-style
+ // parse round-trips correctly. Arguments are passed through as
+ // received from the shortcut — Windows preserves their own quoting.
+ let exe_token = if target.contains(' ') {
+ format!("\"{target}\"")
+ } else {
+ target.clone()
+ };
+ format!("{exe_token} {}", args.trim())
+ };
+
+ Some(InstalledApp {
+ name,
+ bundle_id: target,
+ kind: "desktop".to_owned(),
+ launch_path,
+ last_used,
+ })
+}
+
+/// COM-call into IShellLinkW / IPersistFile to read the target `.exe` path and
+/// any commandline arguments encoded in the shortcut. Returns `(target, args)`
+/// — `args` is the empty string when the shortcut carries no arguments.
+unsafe fn read_lnk_target(lnk_path: &Path) -> windows::core::Result<(String, String)> {
+ let shell_link: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER)?;
+ let persist: IPersistFile = shell_link.cast()?;
+
+ let wide_path = to_wide_nul(lnk_path.to_string_lossy().as_ref());
+ persist.Load(PCWSTR(wide_path.as_ptr()), STGM(0))?;
+
+ let mut path_buf = vec![0u16; MAX_PATH as usize + 1];
+ shell_link.GetPath(&mut path_buf, std::ptr::null_mut(), SLGP_RAWPATH.0 as u32)?;
+
+ // INFOTIPSIZE (1024) is the documented upper bound for the LNK
+ // arguments field; allocate one extra slot for the NUL terminator.
+ let mut args_buf = vec![0u16; 1025];
+ // GetArguments succeeds with an empty string when no args are set —
+ // we don't need to special-case that case.
+ let args_res = shell_link.GetArguments(&mut args_buf);
+ let args = if args_res.is_ok() { decode_wstr(&args_buf) } else { String::new() };
+
+ Ok((decode_wstr(&path_buf), args))
+}
+
+fn to_wide_nul(s: &str) -> Vec<u16> {
+ let mut v: Vec<u16> = s.encode_utf16().collect();
+ v.push(0);
+ v
+}
+
+fn decode_wstr(buf: &[u16]) -> String {
+ let len = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
+ String::from_utf16_lossy(&buf[..len])
+}
+
+// ── UWP / packaged-app enumeration via WinRT PackageManager ──────────────────
+
+fn scan_uwp_packages() -> Vec<InstalledApp> {
+ // Wrapped in catch_unwind because the WinRT activation path can panic on
+ // very old Windows builds (pre-1809) that lack PackageManager altogether.
+ let result = std::panic::catch_unwind(|| -> windows::core::Result<Vec<InstalledApp>> {
+ use windows::ApplicationModel::Package;
+ use windows::Management::Deployment::{PackageManager, PackageTypes};
+
+ let pm = PackageManager::new()?;
+ let packages = pm.FindPackagesWithPackageTypes(PackageTypes::Main)?;
+
+ let mut out = Vec::new();
+ for pkg in packages {
+ // `pkg: Package` — annotate locally to satisfy the type
+ // inference paths through `id.FamilyName()` and friends.
+ let pkg: Package = pkg;
+ let id = match pkg.Id() {
+ Ok(v) => v,
+ Err(_) => continue,
+ };
+ let family_name = match id.FamilyName() {
+ Ok(h) => h.to_string(),
+ Err(_) => continue,
+ };
+ if family_name.is_empty() { continue }
+
+ let display = match pkg.DisplayName() {
+ Ok(h) => {
+ let s = h.to_string();
+ if s.is_empty() { family_name.clone() } else { s }
+ }
+ Err(_) => family_name.clone(),
+ };
+
+ // ApplicationModel::Package doesn't surface the per-app
+ // Application.Id list directly in the stable WinRT API; the
+ // canonical shell launch token "shell:appsFolder\{family}!{appid}"
+ // needs the AppId from the package manifest, which we don't
+ // fetch here to keep this enumeration cheap.
+ //
+ // Falling back to "shell:appsFolder\{family}!App" works for the
+ // overwhelming majority of single-entry packages (the manifest's
+ // default Application Id is literally "App"); for multi-entry
+ // packages the caller can read the manifest itself.
+ let launch_path = format!("shell:appsFolder\\{family_name}!App");
+ let last_used = read_install_mtime(&pkg);
+
+ out.push(InstalledApp {
+ name: display,
+ bundle_id: family_name,
+ kind: "uwp".to_owned(),
+ launch_path,
+ last_used,
+ });
+ }
+ Ok(out)
+ });
+
+ match result {
+ Ok(Ok(v)) => v,
+ _ => Vec::new(),
+ }
+}
+
+/// Resolve a UWP package's install-path mtime to an RFC3339 string.
+fn read_install_mtime(pkg: &windows::ApplicationModel::Package) -> Option<String> {
+ let path_hstring = pkg.InstalledPath().ok()?;
+ let path = path_hstring.to_string();
+ if path.is_empty() { return None }
+ let meta = std::fs::metadata(&path).ok()?;
+ let modified = meta.modified().ok()?;
+ let duration = modified.duration_since(std::time::UNIX_EPOCH).ok()?;
+ Some(unix_secs_to_rfc3339(duration.as_secs() as i64))
+}
+
+// ── Date helper ──────────────────────────────────────────────────────────────
+
+/// Format Unix epoch seconds as `YYYY-MM-DDTHH:MM:SSZ` (UTC).
+fn unix_secs_to_rfc3339(secs: i64) -> String {
+ let days = secs.div_euclid(86_400);
+ let seconds_of_day = secs.rem_euclid(86_400);
+ let hour = seconds_of_day / 3600;
+ let minute = (seconds_of_day % 3600) / 60;
+ let second = seconds_of_day % 60;
+
+ let z = days + 719_468;
+ let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
+ let doe = (z - era * 146_097) as u64;
+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
+ let y = yoe as i64 + era * 400;
+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
+ let mp = (5 * doy + 2) / 153;
+ let d = doy - (153 * mp + 2) / 5 + 1;
+ let m = if mp < 10 { mp + 3 } else { mp - 9 };
+ let y = if m <= 2 { y + 1 } else { y };
+
+ format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", y, m, d, hour, minute, second)
+}
diff --git a/libs/cua-driver-rs/crates/platform-windows/src/win32/mod.rs b/libs/cua-driver-rs/crates/platform-windows/src/win32/mod.rs
index 704682a1e6..8bfec092bc 100644
--- a/libs/cua-driver-rs/crates/platform-windows/src/win32/mod.rs
+++ b/libs/cua-driver-rs/crates/platform-windows/src/win32/mod.rs
@@ -1,7 +1,9 @@
//! Win32 API wrappers for window/process enumeration.
pub mod apps;
+pub mod installed_apps;
pub mod windows;
pub use apps::{list_processes, ProcessInfo};
+pub use installed_apps::{list_installed_apps, InstalledApp};
pub use windows::{list_windows, WindowInfo};