Skip to content

A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.

TypeScript

fix(desktop): one active entry and typed COM for minimized Store apps

Marcelitoc9ff3d9cc050
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index 8eaccc6..81d3fa9 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -39,9 +39,10 @@ bzip2 = "0.6"
# Private daemon transport/lifecycle (T1); pinned to the version already in Cargo.lock.
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "=0.61.2", features = ["Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_Security_Authorization", "Win32_Security_Cryptography", "Win32_UI_Shell", "Win32_System_Com", "Win32_System_Diagnostics_ToolHelp", "Win32_Storage_FileSystem", "Win32_System_Pipes", "Win32_System_Threading", "Win32_System_JobObjects", "Win32_System_IO", "Win32_System_Registry", "Win32_UI_Controls", "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_UI_HiDpi", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] }
-# Voice capture through WASAPI and computer control through UI Automation and shell links (COM interfaces
-# windows-sys does not bind); the version Tauri already uses.
-windows = { version = "=0.62.2", features = ["Win32_Media_Audio", "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_Storage_FileSystem", "Win32_System_Variant", "Win32_UI_Accessibility", "Win32_UI_Shell"] }
+# Voice capture through WASAPI and computer control through UI Automation, shell links, and window
+# properties (a minimized Store app's name): COM interfaces windows-sys does not bind; the version
+# Tauri already uses.
+windows = { version = "=0.62.2", features = ["Win32_Media_Audio", "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_Storage_FileSystem", "Win32_System_Variant", "Win32_UI_Accessibility", "Win32_UI_Shell", "Win32_UI_Shell_PropertiesSystem"] }
# The computer-control helper (S24) is macOS only.
[target.'cfg(target_os = "macos")'.dependencies]
diff --git a/apps/desktop/src-tauri/src/computer/win.rs b/apps/desktop/src-tauri/src/computer/win.rs
index 04fb3c7..57bc653 100644
--- a/apps/desktop/src-tauri/src/computer/win.rs
+++ b/apps/desktop/src-tauri/src/computer/win.rs
@@ -29,8 +29,8 @@ use super::risk::{AxElement, Focus};
use super::glow::Frame;
use super::winaccess::{element, is_default, known_chain, unreadable, UIA_BUTTON, UIA_WINDOW};
use super::winapps::{
- answers_to, executable_target, fronts_same_app, hosted_page, listed_name, listed_windows, request, shortcut_named,
- strip_ci, Request, TopWindow,
+ active_entries, answers_to, distinct_names, executable_target, fronts_same_app, hosted_page, listed_name,
+ listed_windows, request, shortcut_named, strip_ci, Request, TopWindow,
};
use super::winput::{checks_typing_target, releases, send_batches, settles, steps, Step, VirtualScreen};
use super::{
@@ -915,76 +915,45 @@ pub fn window_owner_at(at: Point) -> Option<AppIdentity> {
(!root.is_null()).then(|| target_of(root))
}
-/// The shell display name for the AppUserModelID stored on a frame. These shell COM interfaces
-/// are used only here; all returned objects and strings are released before leaving the apartment.
+/// The shell display name for the AppUserModelID stored on a frame (the name Start shows for the
+/// app), or none when the shell does not give one. Every interface is released and every
+/// PROPVARIANT and string the shell allocated is freed before the apartment is left.
fn frame_app_name(hwnd: HWND) -> Option<String> {
- use windows_sys::core::GUID;
-
- #[repr(C)]
- struct PropertyKey { fmtid: GUID, pid: u32 }
- // PROPVARIANT: the value union has room for two pointers on either supported pointer width.
- #[repr(C)]
- struct PropVariant { vt: u16, reserved: [u16; 3], value: [usize; 2] }
- #[repr(C)]
- struct PropertyStoreVtable {
- prefix: [*const c_void; 5],
- get_value: unsafe extern "system" fn(*mut c_void, *const PropertyKey, *mut PropVariant) -> i32,
- }
- #[repr(C)]
- struct ShellItemVtable {
- prefix: [*const c_void; 5],
- get_display_name: unsafe extern "system" fn(*mut c_void, u32, *mut *mut u16) -> i32,
- }
- #[link(name = "shell32")]
- extern "system" {
- fn SHGetPropertyStoreForWindow(hwnd: HWND, iid: *const GUID, out: *mut *mut c_void) -> i32;
- fn SHCreateItemInKnownFolder(folder: *const GUID, flags: u32, path: *const u16, iid: *const GUID, out: *mut *mut c_void) -> i32;
- }
- #[link(name = "ole32")]
- extern "system" {
- fn PropVariantClear(value: *mut PropVariant) -> i32;
- fn CoTaskMemFree(ptr: *mut c_void);
- }
- struct ComPtr(*mut c_void);
- impl Drop for ComPtr {
- fn drop(&mut self) {
- // SAFETY: all ComPtr values hold a live interface with IUnknown as its first vtable.
- unsafe {
- let vtable = *(self.0 as *const *const *const c_void);
- let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*vtable.add(2));
- release(self.0);
- }
+ use windows::core::{GUID, PCWSTR, PWSTR};
+ use windows::Win32::Foundation::{HWND as ComHwnd, PROPERTYKEY};
+ use windows::Win32::System::Com::CoTaskMemFree;
+ use windows::Win32::System::Com::StructuredStorage::{PropVariantClear, PropVariantToStringAlloc};
+ use windows::Win32::System::Variant::VT_LPWSTR;
+ use windows::Win32::UI::Shell::PropertiesSystem::{IPropertyStore, SHGetPropertyStoreForWindow};
+ use windows::Win32::UI::Shell::{IShellItem, SHCreateItemInKnownFolder, FOLDERID_AppsFolder, KF_FLAG_DEFAULT, SIGDN_NORMALDISPLAY};
+ /// `PKEY_AppUserModel_ID` (propkey.h): declared here rather than enabling the Enhanced
+ /// Storage bindings for one constant.
+ const AUMID: PROPERTYKEY = PROPERTYKEY { fmtid: GUID::from_u128(0x9f4c2855_9f79_4b39_a8d0_e1d42de1d5f3), pid: 5 };
+ /// A string the shell allocated, copied and then freed exactly once.
+ fn take(text: PWSTR) -> Option<String> {
+ // SAFETY: `text` is null or a terminated string from CoTaskMemAlloc, not used afterwards.
+ unsafe {
+ let copied = if text.is_null() { None } else { text.to_string().ok() };
+ CoTaskMemFree(Some(text.0 as *const c_void));
+ copied
}
}
- const STORE: GUID = GUID::from_u128(0x886d8eeb_8cf2_4446_8d02_cdba1dbdcf99);
- const ITEM: GUID = GUID::from_u128(0x43826d1e_e718_42ee_bc55_a1e261c37bfe);
- const APPS: GUID = GUID::from_u128(0x1e87508d_89c2_42f0_8a7e_645a0f50ca58);
- const AUMID: PropertyKey = PropertyKey { fmtid: GUID::from_u128(0x9f4c2855_9f79_4b39_a8d0_e1d42de1d5f3), pid: 5 };
+ // Declared first so every interface below is released before COM is left.
let _apartment = Apartment::join(Apartment::SHELL);
- // SAFETY: shell calls fill the indicated out-pointers; successful interfaces are released,
- // the PROPVARIANT is cleared, and the shell-allocated display name is freed.
+ // SAFETY: typed shell calls on a window handle and on the interfaces they return; each
+ // HRESULT is checked by the binding, and the PROPVARIANT is cleared once it is read.
unsafe {
- let mut raw = null_mut();
- if SHGetPropertyStoreForWindow(hwnd, &STORE, &mut raw) < 0 || raw.is_null() { return None; }
- let store = ComPtr(raw);
- let vtable = &**(store.0 as *const *const PropertyStoreVtable);
- let mut value: PropVariant = zeroed();
- let result = (vtable.get_value)(store.0, &AUMID, &mut value);
- let mut item_raw = null_mut();
- if result >= 0 && value.vt == 31 && value.value[0] != 0 {
- SHCreateItemInKnownFolder(&APPS, 0, value.value[0] as *const u16, &ITEM, &mut item_raw);
+ let store: IPropertyStore = SHGetPropertyStoreForWindow(ComHwnd(hwnd)).ok()?;
+ let mut value = store.GetValue(&AUMID).ok()?;
+ let aumid = if value.Anonymous.Anonymous.vt == VT_LPWSTR { PropVariantToStringAlloc(&value).ok() } else { None };
+ let _ = PropVariantClear(&mut value);
+ let aumid = take(aumid?)?;
+ if aumid.trim().is_empty() {
+ return None;
}
- PropVariantClear(&mut value);
- if item_raw.is_null() { return None; }
- let item = ComPtr(item_raw);
- let vtable = &**(item.0 as *const *const ShellItemVtable);
- let mut name = null_mut();
- if (vtable.get_display_name)(item.0, 0, &mut name) < 0 || name.is_null() { return None; }
- let mut len = 0;
- while *name.add(len) != 0 { len += 1; }
- let result = String::from_utf16_lossy(std::slice::from_raw_parts(name, len));
- CoTaskMemFree(name.cast());
- Some(result)
+ let path = wide(&aumid);
+ let item: IShellItem = SHCreateItemInKnownFolder(&FOLDERID_AppsFolder, KF_FLAG_DEFAULT, PCWSTR(path.as_ptr())).ok()?;
+ take(item.GetDisplayName(SIGDN_NORMALDISPLAY).ok()?).filter(|name| !name.trim().is_empty())
}
}
@@ -992,22 +961,34 @@ fn frame_app_name(hwnd: HWND) -> Option<String> {
/// apps that are not running).
pub fn list_apps() -> Result<Vec<AppInfo>, String> {
let active = frontmost_app().map(|app| app.pid);
+ // SAFETY: plain queries.
+ let front_root = unsafe { GetAncestor(GetForegroundWindow(), GA_ROOT) } as usize;
let windows = top_windows()?;
let listing: Vec<(TopWindow, bool)> = windows.iter().map(|(hwnd, window)| {
let detached = class_name(*hwnd).as_deref() == Some(FRAME_CLASS)
&& app_pid(*hwnd).is_none() && is_frame_host(&identity(window.pid));
(window.clone(), detached)
}).collect();
- Ok(listed_windows(&listing).into_iter().map(|index| {
- let (hwnd, _) = &windows[index];
- let (window, detached) = &listing[index];
+ let shown = listed_windows(&listing);
+ // A detached frame is only named for listing; it cannot be acted on until restored and
+ // identified. target_of and every blocklist/activation check keep their existing identity.
+ let ids: Vec<(AppIdentity, String)> = shown.iter().map(|&index| {
+ let ((hwnd, _), (window, detached)) = (&windows[index], &listing[index]);
let id = identity(window.pid);
- // A detached frame is only named for listing; it cannot be acted on until restored and
- // identified. target_of and every blocklist/activation check keep their existing identity.
let name = listed_name(*detached, if *detached { frame_app_name(*hwnd) } else { None },
- if *detached { Some(window.title.clone()) } else { None }, id.name);
- AppInfo { name, bundle_id: id.bundle_id, active: active == Some(window.pid) }
- }).collect())
+ if *detached { Some(window.title.clone()) } else { None }, id.name.clone());
+ (id, name)
+ }).collect();
+ // Frames share the frame host's process: the one in front is told by its window handle.
+ let actives = active_entries(
+ &shown.iter().map(|&index| (listing[index].0.pid, listing[index].1, windows[index].0 as usize)).collect::<Vec<_>>(),
+ active,
+ front_root,
+ );
+ let names = distinct_names(
+ shown.iter().zip(&ids).map(|(&index, (_, name))| (name.clone(), listing[index].1, listing[index].0.title.clone())).collect(),
+ );
+ Ok(ids.into_iter().zip(names).zip(actives).map(|(((id, _), name), active)| AppInfo { name, bundle_id: id.bundle_id, active }).collect())
}
/// Brings a window to the front. Windows lets only the process that received the last input
diff --git a/apps/desktop/src-tauri/src/computer/winapps.rs b/apps/desktop/src-tauri/src/computer/winapps.rs
index aa9a8d6..712c467 100644
--- a/apps/desktop/src-tauri/src/computer/winapps.rs
+++ b/apps/desktop/src-tauri/src/computer/winapps.rs
@@ -25,18 +25,6 @@ impl TopWindow {
}
}
-/// The processes with an app window, front to back, each once.
-#[cfg(test)]
-pub fn app_pids(windows: &[TopWindow]) -> Vec<i32> {
- let mut pids = Vec::new();
- for window in windows.iter().filter(|w| w.is_app()) {
- if !pids.contains(&window.pid) {
- pids.push(window.pid);
- }
- }
- pids
-}
-
/// Indices to list, given each window and whether its Store frame is detached.
pub fn listed_windows(windows: &[(TopWindow, bool)]) -> Vec<usize> {
let mut pids = Vec::new();
@@ -62,6 +50,40 @@ pub fn listed_name(detached: bool, aumid_name: Option<String>, title: Option<Str
.unwrap_or(original)
}
+/// Which listed entries (process, detached Store frame, window handle) are the app in front. A
+/// detached frame's process is the frame host, shared by every minimized Store app, so a frame is
+/// in front only when it is the foreground root window itself; any other entry is in front by its
+/// process, as before. Entries other than frames are listed once per process, so at most one is.
+pub fn active_entries(entries: &[(i32, bool, usize)], front_pid: Option<i32>, front_root: usize) -> Vec<bool> {
+ let front_frame = entries.iter().position(|&(_, detached, handle)| detached && front_root != 0 && handle == front_root);
+ entries
+ .iter()
+ .enumerate()
+ .map(|(index, &(pid, detached, _))| match front_frame {
+ Some(front) => index == front,
+ None => !detached && front_pid == Some(pid),
+ })
+ .collect()
+}
+
+/// The listed names (name, detached Store frame, frame title). Detached frames that share a name
+/// (two minimized windows of one Store app) get their title appended, so the agent can tell them
+/// apart; a title that is blank or only repeats the name adds nothing.
+pub fn distinct_names(entries: Vec<(String, bool, String)>) -> Vec<String> {
+ let shared = |name: &str| entries.iter().filter(|(other, detached, _)| *detached && other == name).count() > 1;
+ entries
+ .iter()
+ .map(|(name, detached, title)| {
+ let title = title.trim();
+ if *detached && shared(name) && !title.is_empty() && title != name {
+ format!("{name} — {title}")
+ } else {
+ name.clone()
+ }
+ })
+ .collect()
+}
+
/// What `open_app` was asked for: an app's name, or a local program or shortcut by path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Request {
@@ -175,6 +197,48 @@ pub fn fronts_same_app(front_pid: i32, pid: i32, front_owner: usize, owner: usiz
mod tests {
use super::*;
+ /// The processes with an app window, front to back, each once.
+ fn app_pids(windows: &[TopWindow]) -> Vec<i32> {
+ let mut pids = Vec::new();
+ for window in windows.iter().filter(|w| w.is_app()) {
+ if !pids.contains(&window.pid) {
+ pids.push(window.pid);
+ }
+ }
+ pids
+ }
+
+ #[test]
+ fn only_the_detached_frame_in_front_is_active_not_every_frame_of_its_host() {
+ // Two minimized Store apps share the frame host's process (40); the second is in front.
+ let entries = [(40, true, 0x100), (40, true, 0x200), (7, false, 0x300)];
+ assert_eq!(active_entries(&entries, Some(40), 0x200), [false, true, false]);
+ // A detached frame never counts as in front by its host's process alone.
+ assert_eq!(active_entries(&entries, Some(40), 0x999), [false, false, false]);
+ // Other apps stay active by their process, as before.
+ assert_eq!(active_entries(&entries, Some(7), 0x300), [false, false, true]);
+ assert_eq!(active_entries(&entries, Some(7), 0x301), [false, false, true]);
+ assert_eq!(active_entries(&entries, None, 0), [false, false, false]);
+ }
+
+ #[test]
+ fn detached_frames_with_the_same_name_are_told_apart_by_their_titles() {
+ let entry = |name: &str, detached: bool, title: &str| (name.to_string(), detached, title.to_string());
+ let names = distinct_names(vec![
+ entry("Fotos", true, "img.jpg"),
+ entry("Fotos", true, "beach.png"),
+ entry("Calculator", true, "Calculator"),
+ entry("Notepad", false, "notes.txt - Notepad"),
+ ]);
+ assert_eq!(names, ["Fotos — img.jpg", "Fotos — beach.png", "Calculator", "Notepad"]);
+ // A title that only repeats the name, or is blank, adds nothing.
+ let names = distinct_names(vec![entry("Fotos", true, "Fotos"), entry("Fotos", true, " "), entry("Fotos", true, "a.jpg")]);
+ assert_eq!(names, ["Fotos", "Fotos", "Fotos — a.jpg"]);
+ // Only detached frames are renamed; a desktop app with the same name keeps its own.
+ let names = distinct_names(vec![entry("Fotos", true, "img.jpg"), entry("Fotos", false, "Fotos")]);
+ assert_eq!(names, ["Fotos", "Fotos"]);
+ }
+
fn window(pid: i32, title: &str) -> TopWindow {
TopWindow { pid, title: title.into(), visible: true, cloaked: false, tool: false, app_window: false, owned: false }
}
diff --git a/docs/design.md b/docs/design.md
index 23213b9..470cca3 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -170,7 +170,7 @@ The UI shows one endless chat: no conversations list, no new conversation, and t
The assistant can see the screen and operate apps through a built-in MCP server that the desktop app serves. macOS (L59) and Windows (S24.11); Linux, the web page and a VPS never offer it.
- S24.1 Helper: native Rust inside the Tauri app (`apps/desktop/src-tauri`), never in the daemon or the engine. It serves MCP (JSON-RPC 2.0 over streamable HTTP) on `http://127.0.0.1:<random port>/mcp` and requires `Authorization: Bearer <key>`, a fresh random key per app launch.
-- S24.2 Tools: `screenshot`, `click`, `move`, `drag`, `scroll`, `type`, `key`, `open_app`, `list_apps`, `wait`, each with an optional `intent`. Screenshots of the display under the pointer are downscaled to a long edge of 1280 px; coordinates are pixels of the latest screenshot; actions return a fresh one; Gentle Dot's own windows are left out. On Windows, a detached Store app frame is listed by its shell display name (or its window title, or the frame host when neither is available), separately from other detached frames. This name is for listing only: the minimized app cannot be acted on until it is restored and identified; the action blocklist is unchanged.
+- S24.2 Tools: `screenshot`, `click`, `move`, `drag`, `scroll`, `type`, `key`, `open_app`, `list_apps`, `wait`, each with an optional `intent`. Screenshots of the display under the pointer are downscaled to a long edge of 1280 px; coordinates are pixels of the latest screenshot; actions return a fresh one; Gentle Dot's own windows are left out. On Windows, a detached Store app frame is listed by its shell display name (or its window title, or the frame host when neither is available), separately from other detached frames; two of them with the same name get their window titles appended (`Fotos — img.jpg`), and one is marked active only when it is the foreground window itself. This name is for listing only: the minimized app cannot be acted on until it is restored and identified; the action blocklist is unchanged.
- S24.3 Session grant: the first call without a session shows a native dialog ("Allow Gentle Dot to see and control this Mac for 30 minutes?"). A session ends on timeout, Stop, the tray item, or the panic shortcut ⌥⇧Esc, and queued actions are dropped.
- S24.4 Guards: a fixed blocklist (Gentle Dot itself, System Settings, SecurityAgent, loginwindow, Keychain Access, password managers), 10 actions per second, and a native per-action confirmation for risky actions (send, pay, buy, delete, submit, confirm, transfer, and their Spanish equivalents, by Accessibility role and title, by `return` on a default button, or by the declared `intent`). Keyboard actions go only to the app that was steadily in front during the latest screenshot; their recipient is fixed when they are checked and confirmed and rechecked before each chunk of text, each Return, and the key, and a change stops the input with the count of characters already sent. After a confirmation, the app in front before the dialog must be back in front within 500 ms, or nothing is done.
- S24.5 Permissions: the app reports and requests Accessibility and Screen Recording (`computer_permissions`, `computer_request_permission {kind}`). The Connectors screen shows a built-in "Computer" entry with both statuses, Grant buttons, Check again, the note that debug builds lose the grants on every rebuild (macOS ties them to the code signature), and a note when the current model does not accept images (`ConnectorInfo.noImages`, from the model's `input` in the engine's `get_state` and `set_model` answers).