A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
feat(desktop): refuse keyboard input to apps the platform says cannot take it
Marcelito056dc70e0f6e
diff --git a/apps/desktop/src-tauri/src/computer/fake.rs b/apps/desktop/src-tauri/src/computer/fake.rsindex c5abbd3..d984101 100644--- a/apps/desktop/src-tauri/src/computer/fake.rs+++ b/apps/desktop/src-tauri/src/computer/fake.rs@@ -21,6 +21,10 @@ pub struct FakeDesktop {pub focused_app: Mutex<Option<AppIdentity>>,/// Changes the foreground app after this many recorded posts; disabled by default.pub front_after_posts: Mutex<Option<(usize, AppIdentity)>>,+ /// Apps that run as administrator, refused for keyboard input.+ pub elevated: Mutex<Vec<i32>>,+ /// Marks an app as elevated after this many recorded posts; disabled by default.+ pub elevated_after_posts: Mutex<Option<(usize, i32)>>,/// What comes to the front while the next capture is taken (once).pub front_during_capture: Mutex<Option<AppIdentity>>,pub focused_after_posts: Mutex<Option<(usize, AppIdentity)>>,@@ -54,6 +58,8 @@ impl Default for FakeDesktop {frontmost: Mutex::new(Some(safari)),focused_app: Mutex::new(None),front_after_posts: Mutex::new(None),+ elevated: Mutex::new(Vec::new()),+ elevated_after_posts: Mutex::new(None),front_during_capture: Mutex::new(None),focused_after_posts: Mutex::new(None),during_focused_element: Mutex::new(None),@@ -78,6 +84,11 @@ impl FakeDesktop {}impl Desktop for FakeDesktop {+ fn keyboard_refusal(&self, app: &AppIdentity) -> Option<String> {+ self.elevated.lock().unwrap().contains(&app.pid)+ .then(|| format!("{} runs as administrator, so Gentle Dot cannot send it keys.", app.name))+ }+fn permissions(&self) -> Permissions {*self.permissions.lock().unwrap()}@@ -101,6 +112,11 @@ impl Desktop for FakeDesktop {events.push(event.clone());events.len()};+ if let Some((posts, pid)) = *self.elevated_after_posts.lock().unwrap() {+ if count == posts {+ self.elevated.lock().unwrap().push(pid);+ }+ }if let Some((posts, app)) = self.front_after_posts.lock().unwrap().as_ref() {if count == *posts {*self.frontmost.lock().unwrap() = Some(app.clone());diff --git a/apps/desktop/src-tauri/src/computer/mcp.rs b/apps/desktop/src-tauri/src/computer/mcp.rsindex 7f10937..df00d1b 100644--- a/apps/desktop/src-tauri/src/computer/mcp.rs+++ b/apps/desktop/src-tauri/src/computer/mcp.rs@@ -25,7 +25,10 @@ use super::keys::{parse_combo, KeyCombo};use super::rate::{RateLimiter, MAX_ACTIONS_PER_SECOND};use super::risk::{assess, Act};use super::working::{NoPreparation, Preparation};-use super::{Clock, Desktop, Dialogs, InputEvent, KeyboardRecipient, MouseButton};+use super::{+ Clock, Desktop, Dialogs, InputEvent, KeyboardRecipient, MouseButton, KEYS_CHANGED_BEFORE_TYPING,+ KEYS_CHANGED_WHILE_TYPING,+};use base64::Engine as _;use serde_json::{json, Map, Value};use std::sync::{Arc, Mutex, MutexGuard};@@ -577,6 +580,9 @@ impl Helper {fn keyboard_target(&self, sent: bool) -> Result<(String, KeyboardRecipient), String> {let front = self.desktop.frontmost_app().ok_or("Cannot tell which app is in front.")?;self.refuse_blocked(&front)?;+ if let Some(reason) = self.desktop.keyboard_refusal(&front) {+ return Err(reason);+ }// The user may have switched apps since the agent last looked: it looks again first.if *lock(&self.seen_front) != Some(front.pid) {return Err(format!(@@ -588,6 +594,9 @@ impl Helper {let focused = self.desktop.focused_app().filter(|focused| focused.pid != front.pid);if let Some(focused) = &focused {self.refuse_blocked(focused)?;+ if let Some(reason) = self.desktop.keyboard_refusal(focused) {+ return Err(reason);+ }}let recipient = KeyboardRecipient { front_pid: front.pid, focused_pid: focused.as_ref().map(|app| app.pid) };Ok((focused.map_or(front.name, |app| app.name), recipient))@@ -807,9 +816,9 @@ impl Helper {let mut post_typed = |event, characters| -> Result<(), String> {self.keyboard_target(posted > 0).and_then(|(_, current)| {if current != recipient && posted > 0 {- Err("The app receiving the keys changed while typing, so the rest was not sent.".into())+ Err(KEYS_CHANGED_WHILE_TYPING.into())} else if current != recipient {- Err("The app receiving the keys changed before typing, so nothing was sent.".into())+ Err(KEYS_CHANGED_BEFORE_TYPING.into())} else {Ok(())}@@ -1592,6 +1601,70 @@ mod tests {]);}+ fn elevated_front_refuses(tool: &str, args: Value) {+ let rig = rig();+ rig.ready();+ rig.desktop.elevated.lock().unwrap().push(200);+ let result = rig.call(tool, args);+ assert!(is_error(&result), "{result}");+ assert_eq!(first_text(&result), "Safari runs as administrator, so Gentle Dot cannot send it keys.");+ assert!(rig.desktop.events().is_empty());+ assert!(rig.desktop.typed_posts.lock().unwrap().is_empty());+ }++ #[test]+ fn elevated_front_refuses_type() {+ elevated_front_refuses("type", json!({"text": "hello"}));+ }++ #[test]+ fn elevated_front_refuses_key() {+ elevated_front_refuses("key", json!({"combo": "cmd+a"}));+ }++ #[test]+ fn elevated_focused_panel_refuses_type() {+ let rig = rig();+ rig.ready();+ *rig.desktop.focused_app.lock().unwrap() = Some(app(401, "panel.exe", "Panel"));+ rig.desktop.elevated.lock().unwrap().push(401);+ let result = rig.call("type", json!({"text": "hello"}));+ assert!(is_error(&result), "{result}");+ assert_eq!(first_text(&result), "Panel runs as administrator, so Gentle Dot cannot send it keys.");+ assert!(rig.desktop.events().is_empty());+ assert!(rig.desktop.typed_posts.lock().unwrap().is_empty());+ }++ #[test]+ fn elevated_after_first_chunk_stops_typing() {+ let rig = rig();+ rig.ready();+ *rig.desktop.elevated_after_posts.lock().unwrap() = Some((1, 200));+ let result = rig.call("type", json!({"text": "a".repeat(45)}));+ assert!(is_error(&result), "{result}");+ assert_eq!(first_text(&result), "Safari runs as administrator, so Gentle Dot cannot send it keys. Typing stopped after 20 of 45 characters.");+ let event = InputEvent::Text("a".repeat(20));+ assert_eq!(rig.desktop.events(), vec![event.clone()]);+ assert_eq!(*rig.desktop.typed_posts.lock().unwrap(), vec![(event, KeyboardRecipient { front_pid: 200, focused_pid: None })]);+ }++ #[test]+ fn elevated_app_stops_batch() {+ let rig = rig();+ rig.ready();+ *rig.desktop.elevated_after_posts.lock().unwrap() = Some((1, 200));+ let result = rig.call("batch", batch(json!([+ {"tool": "type", "text": "hi"},+ {"tool": "type", "text": "never"},+ {"tool": "type", "text": "later"}+ ])));+ assert!(is_error(&result), "{result}");+ assert_eq!(first_text(&result), "Stopped at step 2 of 3 (type): Safari runs as administrator, so Gentle Dot cannot send it keys.\nRan 1 of 3 steps:\n1. Type 2 characters in Safari: done.");+ let event = InputEvent::Text("hi".into());+ assert_eq!(rig.desktop.events(), vec![event.clone()]);+ assert_eq!(*rig.desktop.typed_posts.lock().unwrap(), vec![(event, KeyboardRecipient { front_pid: 200, focused_pid: None })]);+ }+#[test]fn keyboard_actions_check_the_frontmost_app() {let rig = rig();diff --git a/apps/desktop/src-tauri/src/computer/mod.rs b/apps/desktop/src-tauri/src/computer/mod.rsindex 8c92d79..2f62730 100644--- a/apps/desktop/src-tauri/src/computer/mod.rs+++ b/apps/desktop/src-tauri/src/computer/mod.rs@@ -102,6 +102,11 @@ pub enum PermissionKind {ScreenRecording,}+/// Why typing stopped when the app receiving the keys changed, once part of the text was sent and+/// before any of it was (shared by the helper and the Windows backend).+pub const KEYS_CHANGED_WHILE_TYPING: &str = "The app receiving the keys changed while typing, so the rest was not sent.";+pub const KEYS_CHANGED_BEFORE_TYPING: &str = "The app receiving the keys changed before typing, so nothing was sent.";+/// The approved front app and any distinct process receiving its keys.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct KeyboardRecipient {@@ -111,6 +116,11 @@ pub struct KeyboardRecipient {/// The Mac, as the helper sees it.pub trait Desktop: Send + Sync {+ /// Why keyboard input must not go to `app` on this platform (an elevated app on Windows, which+ /// silently drops input from Gentle Dot), or none.+ fn keyboard_refusal(&self, _app: &AppIdentity) -> Option<String> {+ None+ }fn permissions(&self) -> Permissions;/// A screenshot of the display under the pointer, downscaled to `coords::MAX_LONG_EDGE`.fn capture(&self) -> Result<Capture, String>;diff --git a/apps/desktop/src-tauri/src/computer/win.rs b/apps/desktop/src-tauri/src/computer/win.rsindex dca4e5e..02f54a5 100644--- a/apps/desktop/src-tauri/src/computer/win.rs+++ b/apps/desktop/src-tauri/src/computer/win.rs@@ -197,15 +197,17 @@ fn typing_windows() -> Option<(HWND, HWND)> {/// reporting the error. Binding keys to the recipient the shared guard approved (`post_typed`)/// needs the app identities of the apps part of this backend, so it comes with it.pub fn post(event: &InputEvent) -> Result<(), String> {- const CHANGED: &str = "The app receiving the keys changed while typing, so the rest was not sent.";let typing_target = matches!(event, InputEvent::Text(_)).then(typing_windows);+ if typing_target == Some(None) {+ return Err("Cannot tell which window is in front, so nothing was sent.".into());+ }let plan = steps(event, &virtual_screen())?;let mut done = 0;for batch in send_batches(&plan) {let changed = checks_typing_target(&batch[0])&& typing_target.is_some_and(|target| target.is_none() || typing_windows() != target);let failed = if changed {- Some((done, CHANGED.to_string()))+ Some((done, super::KEYS_CHANGED_WHILE_TYPING.to_string()))} else {match send_batch(batch) {Err((sent, error)) => Some((done + sent, error)),