Skip to content

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

TypeScript

fix(computer): close the verifier's guard gaps and disclaim TCC for the daemon

Alan Buscaglia3e29886e6155
diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock
index ccf1e16..f8d1ac0 100644
--- a/apps/desktop/src-tauri/Cargo.lock
+++ b/apps/desktop/src-tauri/Cargo.lock
@@ -2325,6 +2325,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69282c2b5bc58fba07cb9de2113619532eb551e98efe3d8d695509ef45fbd53b"
dependencies = [
"bitflags 2.13.2",
+ "libc",
"objc2-core-foundation",
]
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index 3222dc7..f04b6e0 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -35,5 +35,5 @@ objc2-foundation = { version = "0.3", default-features = false, features = ["std
objc2-core-foundation = { version = "0.3", default-features = false, features = ["std", "CFArray", "CFCGTypes", "CFData", "CFDictionary", "CFNumber", "CFString"] }
objc2-core-graphics = { version = "0.3", default-features = false, features = ["std", "CGDataProvider", "CGDirectDisplay", "CGError", "CGEvent", "CGEventTypes", "CGImage", "CGRemoteOperation", "CGWindow"] }
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "libc", "NSRunningApplication", "NSWorkspace"] }
-objc2-application-services = { version = "0.3", default-features = false, features = ["std", "AXError", "AXUIElement", "HIServices"] }
+objc2-application-services = { version = "0.3", default-features = false, features = ["std", "libc", "AXError", "AXUIElement", "HIServices"] }
objc2-screen-capture-kit = { version = "0.3", default-features = false, features = ["std", "block2", "libc", "objc2-core-foundation", "objc2-core-graphics", "SCScreenshotManager", "SCShareableContent", "SCStream"] }
diff --git a/apps/desktop/src-tauri/src/computer/blocklist.rs b/apps/desktop/src-tauri/src/computer/blocklist.rs
index 2c64e94..d7d99f4 100644
--- a/apps/desktop/src-tauri/src/computer/blocklist.rs
+++ b/apps/desktop/src-tauri/src/computer/blocklist.rs
@@ -28,6 +28,23 @@ const BLOCKED: &[Entry] = &[
},
Entry { label: "SecurityAgent", bundles: &["com.apple.SecurityAgent"], names: &["SecurityAgent"] },
Entry { label: "loginwindow", bundles: &["com.apple.loginwindow"], names: &["loginwindow"] },
+ // System prompts: permission (TCC) requests, Touch ID and password sheets, and the
+ // "open this app?" confirmations.
+ Entry {
+ label: "UserNotificationCenter",
+ bundles: &["com.apple.UserNotificationCenter"],
+ names: &["UserNotificationCenter"],
+ },
+ Entry {
+ label: "LocalAuthentication",
+ bundles: &["com.apple.LocalAuthentication.UIAgent"],
+ names: &["LocalAuthenticationUIAgent"],
+ },
+ Entry {
+ label: "CoreServicesUIAgent",
+ bundles: &["com.apple.CoreServicesUIAgent"],
+ names: &["CoreServicesUIAgent"],
+ },
Entry { label: "Keychain Access", bundles: &["com.apple.keychainaccess"], names: &["Keychain Access"] },
Entry {
label: "1Password",
@@ -94,6 +111,9 @@ mod tests {
("com.lastpass.LastPass", "LastPass"),
("com.apple.Passwords", "Passwords"),
("dev.gentleman.gentle-dot", "Gentle Dot"),
+ ("com.apple.UserNotificationCenter", "UserNotificationCenter"),
+ ("com.apple.LocalAuthentication.UIAgent", "LocalAuthentication"),
+ ("com.apple.CoreServicesUIAgent", "CoreServicesUIAgent"),
];
for (bundle, label) in cases {
assert_eq!(blocked_reason(&app(Some(bundle), "x"), OWN_PID), Some(label), "{bundle}");
@@ -131,6 +151,8 @@ mod tests {
#[test]
fn an_app_without_a_bundle_id_is_checked_by_name() {
assert_eq!(blocked_reason(&app(None, "SecurityAgent"), OWN_PID), Some("SecurityAgent"));
+ assert_eq!(blocked_reason(&app(None, "UserNotificationCenter"), OWN_PID), Some("UserNotificationCenter"));
+ assert_eq!(blocked_reason(&app(None, "CoreServicesUIAgent"), OWN_PID), Some("CoreServicesUIAgent"));
}
#[test]
diff --git a/apps/desktop/src-tauri/src/computer/fake.rs b/apps/desktop/src-tauri/src/computer/fake.rs
index 5e887ff..d3abc1e 100644
--- a/apps/desktop/src-tauri/src/computer/fake.rs
+++ b/apps/desktop/src-tauri/src/computer/fake.rs
@@ -17,6 +17,7 @@ pub struct FakeDesktop {
pub events: Mutex<Vec<InputEvent>>,
pub permissions: Mutex<Permissions>,
pub frontmost: Mutex<Option<AppIdentity>>,
+ pub focused_app: Mutex<Option<AppIdentity>>,
pub owner_at: Mutex<OwnerAt>,
pub elements: Mutex<Vec<AxElement>>,
pub focus: Mutex<Option<Focus>>,
@@ -35,6 +36,7 @@ impl Default for FakeDesktop {
events: Mutex::new(Vec::new()),
permissions: Mutex::new(Permissions { accessibility: true, screen_recording: true, screenshots_supported: true }),
frontmost: Mutex::new(Some(safari)),
+ focused_app: Mutex::new(None),
owner_at: Mutex::new(Box::new(move |_| Some(owner.clone()))),
elements: Mutex::new(Vec::new()),
focus: Mutex::new(None),
@@ -91,6 +93,10 @@ impl Desktop for FakeDesktop {
self.frontmost.lock().unwrap().clone()
}
+ fn focused_app(&self) -> Option<AppIdentity> {
+ self.focused_app.lock().unwrap().clone()
+ }
+
fn window_owner_at(&self, at: Point) -> Option<AppIdentity> {
(self.owner_at.lock().unwrap())(at)
}
diff --git a/apps/desktop/src-tauri/src/computer/keys.rs b/apps/desktop/src-tauri/src/computer/keys.rs
index 8792e98..9e354a8 100644
--- a/apps/desktop/src-tauri/src/computer/keys.rs
+++ b/apps/desktop/src-tauri/src/computer/keys.rs
@@ -24,6 +24,11 @@ impl KeyCombo {
pub fn is_return(&self) -> bool {
self.key == "return"
}
+
+ /// Space with any modifiers: it presses the focused button.
+ pub fn is_space(&self) -> bool {
+ self.key == "space"
+ }
}
/// Named keys and their virtual key codes. Single characters use the ANSI layout.
diff --git a/apps/desktop/src-tauri/src/computer/macos.rs b/apps/desktop/src-tauri/src/computer/macos.rs
index 698871f..97b5543 100644
--- a/apps/desktop/src-tauri/src/computer/macos.rs
+++ b/apps/desktop/src-tauri/src/computer/macos.rs
@@ -6,6 +6,7 @@ use super::coords::{fit_long_edge, Point, ScreenshotGeometry, MAX_LONG_EDGE};
use super::encode::{bgra_to_jpeg, JPEG_QUALITY};
use super::keys::KeyCombo;
use super::risk::{AxElement, Focus};
+use super::windows::{owner_row_at, WindowRow};
use super::{AppInfo, Capture, Desktop, InputEvent, MouseButton, PermissionKind, Permissions};
use block2::RcBlock;
use objc2::rc::Retained;
@@ -14,7 +15,8 @@ use objc2_app_kit::{NSApplicationActivationOptions, NSApplicationActivationPolic
use objc2_application_services::{AXError, AXIsProcessTrusted, AXIsProcessTrustedWithOptions, AXUIElement};
use objc2_core_foundation::{CFBoolean, CFDictionary, CFRetained, CFString, CFType, CGPoint, CGRect, CGSize};
use objc2_core_graphics::{
- kCGNullWindowID, kCGWindowAlpha, kCGWindowBounds, kCGWindowOwnerName, kCGWindowOwnerPID, CGDataProvider, CGDirectDisplayID, CGError, CGEvent, CGEventField, CGEventFlags,
+ kCGNullWindowID, kCGWindowAlpha, kCGWindowBounds, kCGWindowLayer, kCGWindowOwnerName, kCGWindowOwnerPID,
+ CGDataProvider, CGDirectDisplayID, CGError, CGEvent, CGEventField, CGEventFlags,
CGEventTapLocation, CGEventType, CGGetDisplaysWithPoint, CGImage, CGMouseButton,
CGPreflightScreenCaptureAccess, CGRequestScreenCaptureAccess, CGScrollEventUnit, CGWindowListCopyWindowInfo,
CGWindowListOption,
@@ -60,6 +62,17 @@ fn identity(app: &NSRunningApplication) -> AppIdentity {
}
}
+/// The running app with `pid`; a process without one (an agent) keeps `name`.
+fn identity_of(pid: i32, name: &str) -> AppIdentity {
+ match NSRunningApplication::runningApplicationWithProcessIdentifier(pid) {
+ Some(app) => identity(&app),
+ None => {
+ let name = if name.is_empty() { format!("process {pid}") } else { name.to_string() };
+ AppIdentity { pid, bundle_id: None, name }
+ }
+ }
+}
+
fn post_event(event: Option<CFRetained<CGEvent>>) -> Result<(), String> {
let event = event.ok_or("macOS could not create the input event")?;
CGEvent::post(CGEventTapLocation::HIDEventTap, Some(&event));
@@ -236,6 +249,23 @@ fn ax_element(element: &AXUIElement, attribute: &str) -> Option<CFRetained<AXUIE
ax_value(element, attribute)?.downcast::<AXUIElement>().ok()
}
+fn ax_pid(element: &AXUIElement) -> Option<i32> {
+ let mut pid: libc::pid_t = 0;
+ // SAFETY: `pid` is a valid out-pointer.
+ let error = unsafe { element.pid(NonNull::from(&mut pid)) };
+ (error == AXError::Success && pid > 0).then_some(pid)
+}
+
+/// The Accessibility element at a global point, as hit-tested by the app that owns it.
+fn ax_element_at(at: Point) -> Option<CFRetained<AXUIElement>> {
+ let mut found: *const AXUIElement = std::ptr::null();
+ // SAFETY: `found` is a valid out-pointer; on success it holds a +1 reference.
+ let out = NonNull::from(&mut found);
+ let error = unsafe { system_wide().copy_element_at_position(at.x as f32, at.y as f32, out) };
+ let found = NonNull::new(found.cast_mut()).filter(|_| error == AXError::Success)?;
+ Some(unsafe { CFRetained::from_raw(found) })
+}
+
fn describe(element: &AXUIElement) -> AxElement {
AxElement {
role: ax_string(element, "AXRole").unwrap_or_default(),
@@ -274,6 +304,39 @@ fn window_bounds(entry: &WindowInfo) -> Option<CGRect> {
Some(CGRect::new(origin, CGSize::new(number("Width")?, number("Height")?)))
}
+/// The on-screen windows, front to back, desktop windows included (the desktop is Finder's).
+fn window_rows() -> Vec<WindowRow> {
+ let Some(list) = CGWindowListCopyWindowInfo(CGWindowListOption::OptionOnScreenOnly, kCGNullWindowID) else {
+ return Vec::new();
+ };
+ // SAFETY: CFArray of CFDictionary is toll-free bridged to NSArray of NSDictionary.
+ let list: &NSArray<WindowInfo> = unsafe { &*(CFRetained::as_ptr(&list).as_ptr() as *const _) };
+ // SAFETY: extern constants provided by CoreGraphics.
+ let (alpha_key, layer_key, pid_key, name_key) = unsafe {
+ (info_key(kCGWindowAlpha), info_key(kCGWindowLayer), info_key(kCGWindowOwnerPID), info_key(kCGWindowOwnerName))
+ };
+ let number = |entry: &WindowInfo, key| entry.objectForKey(key).and_then(|n| n.downcast::<NSNumber>().ok());
+ list.iter()
+ .filter_map(|entry| {
+ let bounds = window_bounds(&entry)?;
+ Some(WindowRow {
+ pid: number(&entry, pid_key)?.intValue(),
+ owner_name: entry
+ .objectForKey(name_key)
+ .and_then(|n| n.downcast::<NSString>().ok())
+ .map(|n| n.to_string())
+ .unwrap_or_default(),
+ layer: number(&entry, layer_key).map_or(0, |l| l.longLongValue()),
+ alpha: number(&entry, alpha_key).map_or(1.0, |a| a.doubleValue()),
+ x: bounds.origin.x,
+ y: bounds.origin.y,
+ width: bounds.size.width,
+ height: bounds.size.height,
+ })
+ })
+ .collect()
+}
+
impl Desktop for MacDesktop {
fn permissions(&self) -> Permissions {
Permissions {
@@ -358,14 +421,9 @@ impl Desktop for MacDesktop {
}
fn element_at(&self, at: Point) -> Vec<AxElement> {
- let mut found: *const AXUIElement = std::ptr::null();
- // SAFETY: `found` is a valid out-pointer; on success it holds a +1 reference.
- let out = NonNull::from(&mut found);
- let error = unsafe { system_wide().copy_element_at_position(at.x as f32, at.y as f32, out) };
- let Some(found) = NonNull::new(found.cast_mut()).filter(|_| error == AXError::Success) else {
+ let Some(mut element) = ax_element_at(at) else {
return Vec::new();
};
- let mut element = unsafe { CFRetained::from_raw(found) };
let mut chain = vec![describe(&element)];
while chain.len() <= AX_ANCESTORS {
let Some(parent) = ax_element(&element, "AXParent") else { break };
@@ -386,42 +444,19 @@ impl Desktop for MacDesktop {
NSWorkspace::sharedWorkspace().frontmostApplication().map(|app| identity(&app))
}
+ fn focused_app(&self) -> Option<AppIdentity> {
+ let focused = ax_element(&system_wide(), "AXFocusedUIElement")?;
+ ax_pid(&focused).map(|pid| identity_of(pid, ""))
+ }
+
+ /// The owner of the frontmost app window under the point (the pointer and other window
+ /// server layers skipped), else the app whose Accessibility element is there.
fn window_owner_at(&self, at: Point) -> Option<AppIdentity> {
- let options = CGWindowListOption::OptionOnScreenOnly | CGWindowListOption::ExcludeDesktopElements;
- let list = CGWindowListCopyWindowInfo(options, kCGNullWindowID)?;
- // SAFETY: CFArray of CFDictionary is toll-free bridged to NSArray of NSDictionary.
- let list: &NSArray<WindowInfo> = unsafe { &*(CFRetained::as_ptr(&list).as_ptr() as *const _) };
- // SAFETY: extern constants provided by CoreGraphics.
- let (alpha_key, pid_key, name_key) =
- unsafe { (info_key(kCGWindowAlpha), info_key(kCGWindowOwnerPID), info_key(kCGWindowOwnerName)) };
- let point = CGPoint { x: at.x, y: at.y };
- // Front to back: the first visible window containing the point owns it.
- let entry = list.iter().find(|entry| {
- let alpha = entry
- .objectForKey(alpha_key)
- .and_then(|a| a.downcast::<NSNumber>().ok())
- .map_or(1.0, |a| a.doubleValue());
- let bounds = window_bounds(entry);
- alpha > 0.0
- && bounds.is_some_and(|b| {
- point.x >= b.origin.x
- && point.y >= b.origin.y
- && point.x < b.origin.x + b.size.width
- && point.y < b.origin.y + b.size.height
- })
- })?;
- let pid = entry.objectForKey(pid_key)?.downcast::<NSNumber>().ok()?.intValue();
- match NSRunningApplication::runningApplicationWithProcessIdentifier(pid) {
- Some(app) => Some(identity(&app)),
- None => {
- let name = entry
- .objectForKey(name_key)
- .and_then(|n| n.downcast::<NSString>().ok())
- .map(|n| n.to_string())
- .unwrap_or_default();
- Some(AppIdentity { pid, bundle_id: None, name })
- }
+ if let Some(row) = owner_row_at(&window_rows(), at) {
+ return Some(identity_of(row.pid, &row.owner_name));
}
+ let element = ax_element_at(at)?;
+ ax_pid(&element).map(|pid| identity_of(pid, ""))
}
fn activate(&self, pid: i32) {
diff --git a/apps/desktop/src-tauri/src/computer/mcp.rs b/apps/desktop/src-tauri/src/computer/mcp.rs
index 58b0f84..77364f2 100644
--- a/apps/desktop/src-tauri/src/computer/mcp.rs
+++ b/apps/desktop/src-tauri/src/computer/mcp.rs
@@ -29,6 +29,8 @@ const NOT_ALLOWED: &str = "Computer control was not allowed by the user. Nothing
const NEEDS_PERMISSION: &str = "Gentle Dot needs the";
const GRANT_IT: &str = "Ask the user to grant it in Connectors → Computer.";
const NEEDS_SCREENSHOT: &str = "Take a screenshot first: coordinates are pixels of the latest screenshot.";
+const UNKNOWN_TARGET: &str = "Cannot tell which app is under that point, so the action was refused. \
+Take a new screenshot and try again.";
const INSTRUCTIONS: &str = "Controls this Mac. Take a screenshot first; x and y are pixels of the latest \
screenshot. Every action returns a fresh screenshot. The user must allow a session, risky actions ask \
@@ -181,7 +183,14 @@ fn parse_call(name: &str, args: &Value) -> Option<Result<Call, String>> {
let delta = |key| integer(args, key).and_then(|v| i32::try_from(v).map_err(|e| e.to_string()));
Tool::Scroll { x, y, dx: delta("dx")?, dy: delta("dy")? }
}
- "type" => Tool::Type { text: string(args, "text")? },
+ "type" => {
+ let text = string(args, "text")?;
+ // Newlines press Return (and are checked); tabs move the focus. Nothing else.
+ if text.chars().any(|c| c.is_ascii_control() && !matches!(c, '\n' | '\r' | '\t')) {
+ return Err("`text` must not contain control characters other than newline and tab".into());
+ }
+ Tool::Type { text }
+ }
"key" => Tool::Key { combo: parse_combo(&string(args, "combo")?)? },
"open_app" => {
let name = string(args, "name")?.trim().to_string();
@@ -336,6 +345,8 @@ impl Helper {
return Err(STOPPED.into());
}
if !self.control.is_active(self.clock.now_ms()) {
+ // The screenshot of an ended session no longer describes the screen.
+ *latest = None;
if !self.with_dialog(|| self.dialogs.ask_grant()) {
return Err(NOT_ALLOWED.into());
}
@@ -399,18 +410,21 @@ impl Helper {
}
}
- /// The app owning the window under `at`, refused when blocked. Its name, for messages.
+ /// The app owning the window under `at`, refused when blocked or unknown. Its name, for messages.
fn pointer_target(&self, at: Point) -> Result<String, String> {
- match self.desktop.window_owner_at(at) {
- Some(app) => self.refuse_blocked(&app).map(|()| app.name),
- None => Ok("the desktop".into()),
- }
+ let app = self.desktop.window_owner_at(at).ok_or(UNKNOWN_TARGET)?;
+ self.refuse_blocked(&app).map(|()| app.name)
}
- /// The frontmost app, refused when blocked. Its name, for messages.
+ /// The frontmost app and the app owning the focused element (they differ for a
+ /// non-activating panel), each refused when blocked. The one receiving the keys, for messages.
fn keyboard_target(&self) -> Result<String, String> {
- let app = self.desktop.frontmost_app().ok_or("Cannot tell which app is in front.")?;
- self.refuse_blocked(&app).map(|()| app.name)
+ let front = self.desktop.frontmost_app().ok_or("Cannot tell which app is in front.")?;
+ self.refuse_blocked(&front)?;
+ match self.desktop.focused_app().filter(|focused| focused.pid != front.pid) {
+ Some(focused) => self.refuse_blocked(&focused).map(|()| focused.name),
+ None => Ok(front.name),
+ }
}
fn confirm_if_risky(&self, risk: Option<String>, action: &str, target: &str) -> Result<(), String> {
@@ -486,7 +500,8 @@ impl Helper {
let destination = self.pointer_target(end)?;
let action = format!("Drag from ({}, {}) to ({}, {})", from.0, from.1, to.0, to.1);
let target = if source == destination { source } else { format!("{source} and {destination}") };
- self.confirm_if_risky(assess(Act::Other, intent), &action, &target)?;
+ let (from_chain, to_chain) = (self.desktop.element_at(start), self.desktop.element_at(end));
+ self.confirm_if_risky(assess(Act::Drag(&from_chain, &to_chain), intent), &action, &target)?;
self.post(epoch, InputEvent::Drag { from: start, to: end })?;
self.after(latest, format!("{action}: done."), SETTLE_MS)
}
@@ -502,9 +517,8 @@ impl Helper {
let target = self.keyboard_target()?;
let typed = typed.replace("\r\n", "\n").replace('\r', "\n");
let focus = self.desktop.focused_element();
- let act = if typed.contains('\n') { Act::Return(focus.as_ref()) } else { Act::Other };
let action = format!("Type {} characters", typed.chars().count());
- self.confirm_if_risky(assess(act, intent), &action, &target)?;
+ self.confirm_if_risky(assess(Act::Type(&typed, focus.as_ref()), intent), &action, &target)?;
let return_key = parse_combo("return")?;
for (i, line) in typed.split('\n').enumerate() {
if i > 0 {
@@ -519,7 +533,13 @@ impl Helper {
Tool::Key { combo } => {
let target = self.keyboard_target()?;
let focus = self.desktop.focused_element();
- let act = if combo.is_return() { Act::Return(focus.as_ref()) } else { Act::Other };
+ let act = if combo.is_return() {
+ Act::Return(focus.as_ref())
+ } else if combo.is_space() {
+ Act::Space(focus.as_ref())
+ } else {
+ Act::Other
+ };
let action = format!("Press {}", combo.key);
self.confirm_if_risky(assess(act, intent), &action, &target)?;
self.post(epoch, InputEvent::Key(combo))?;
@@ -816,6 +836,26 @@ mod tests {
assert!(rig.desktop.events().is_empty());
}
+ #[test]
+ fn a_new_session_needs_a_new_screenshot() {
+ for end in ["stop", "timeout"] {
+ let rig = rig();
+ rig.ready();
+ match end {
+ "stop" => rig.control.end(Reason::Stopped),
+ _ => rig.clock.advance(SESSION_MS),
+ }
+ let result = rig.call("click", json!({"x": 10, "y": 10}));
+ assert!(is_error(&result), "{end}");
+ assert!(first_text(&result).contains("screenshot"), "{result}");
+ // The grant comes first; only then is the missing screenshot reported.
+ assert_eq!(rig.dialogs.grants.load(Ordering::SeqCst), 2, "{end}");
+ assert!(rig.desktop.events().is_empty());
+ rig.ready();
+ assert!(!is_error(&rig.call("click", json!({"x": 10, "y": 10}))));
+ }
+ }
+
#[test]
fn click_maps_pixels_to_points_and_returns_a_fresh_screenshot() {
let rig = rig();
@@ -938,6 +978,36 @@ mod tests {
assert!(rig.desktop.events().is_empty());
}
+ #[test]
+ fn keyboard_actions_check_the_focused_app_too() {
+ let rig = rig();
+ rig.ready();
+ // A non-activating panel takes the keys while Safari stays frontmost.
+ *rig.desktop.focused_app.lock().unwrap() = Some(app(303, "com.1password.1password", "1Password"));
+ let result = rig.call("type", json!({"text": "hello"}));
+ assert!(first_text(&result).contains("1Password"), "{result}");
+ assert!(is_error(&rig.call("key", json!({"combo": "return"}))));
+ assert!(rig.desktop.events().is_empty());
+ }
+
+ #[test]
+ fn pointer_actions_where_no_app_owns_the_point_are_refused() {
+ let rig = rig();
+ rig.ready();
+ *rig.desktop.owner_at.lock().unwrap() = Box::new(|_| None);
+ for (name, args) in [
+ ("click", json!({"x": 10, "y": 10})),
+ ("move", json!({"x": 10, "y": 10})),
+ ("scroll", json!({"x": 10, "y": 10, "dx": 0, "dy": 10})),
+ ("drag", json!({"fromX": 10, "fromY": 10, "toX": 20, "toY": 20})),
+ ] {
+ let result = rig.call(name, args);
+ assert!(is_error(&result), "{name}");
+ assert!(first_text(&result).contains("which app"), "{result}");
+ }
+ assert!(rig.desktop.events().is_empty());
+ }
+
#[test]
fn opening_a_blocked_app_is_refused() {
let rig = rig();
@@ -1000,6 +1070,29 @@ mod tests {
assert_eq!(rig.desktop.events().len(), 2);
}
+ #[test]
+ fn a_drag_over_a_risky_button_is_confirmed() {
+ let rig = rig_with(true, false);
+ rig.ready();
+ *rig.desktop.elements.lock().unwrap() = send_button();
+ let result = rig.call("drag", json!({"fromX": 10, "fromY": 10, "toX": 10, "toY": 10}));
+ assert!(first_text(&result).contains("declined"), "{result}");
+ assert_eq!(rig.dialogs.confirmations.lock().unwrap().len(), 1);
+ assert!(rig.desktop.events().is_empty());
+ }
+
+ #[test]
+ fn space_on_a_focused_send_button_is_confirmed() {
+ let rig = rig_with(true, false);
+ rig.ready();
+ *rig.desktop.focus.lock().unwrap() = Some(Focus { element: send_button().remove(0), ..Focus::default() });
+ assert!(is_error(&rig.call("key", json!({"combo": "space"}))));
+ assert!(is_error(&rig.call("type", json!({"text": " "}))));
+ assert!(rig.desktop.events().is_empty());
+ assert!(!is_error(&rig.call("type", json!({"text": "ok"}))));
+ assert_eq!(rig.dialogs.confirmations.lock().unwrap().len(), 2);
+ }
+
#[test]
fn return_in_a_send_like_field_is_confirmed() {
let rig = rig_with(true, false);
@@ -1056,6 +1149,20 @@ mod tests {
assert!(rig.desktop.events().is_empty());
}
+ #[test]
+ fn typing_control_characters_is_refused() {
+ let rig = rig();
+ rig.ready();
+ for text in ["\u{1b}[A", "a\u{0}b", "\u{7f}", "\u{8}\u{8}"] {
+ let result = rig.call("type", json!({"text": text}));
+ assert!(is_error(&result), "{text:?}");
+ assert!(first_text(&result).contains("control character"), "{result}");
+ }
+ assert!(rig.desktop.events().is_empty());
+ assert!(!is_error(&rig.call("type", json!({"text": "a\tb"}))));
+ assert_eq!(rig.desktop.events(), vec![InputEvent::Text("a\tb".into())]);
+ }
+
#[test]
fn long_text_is_sent_in_chunks_of_twenty_utf16_units() {
let rig = rig();
diff --git a/apps/desktop/src-tauri/src/computer/mod.rs b/apps/desktop/src-tauri/src/computer/mod.rs
index ee36b2a..13bda4c 100644
--- a/apps/desktop/src-tauri/src/computer/mod.rs
+++ b/apps/desktop/src-tauri/src/computer/mod.rs
@@ -20,6 +20,7 @@ pub mod rate;
pub mod risk;
pub mod server;
pub mod session;
+pub mod windows;
use blocklist::AppIdentity;
use coords::{Point, ScreenshotGeometry};
@@ -97,6 +98,9 @@ pub trait Desktop: Send + Sync {
fn element_at(&self, at: Point) -> Vec<AxElement>;
fn focused_element(&self) -> Option<Focus>;
fn frontmost_app(&self) -> Option<AppIdentity>;
+ /// The app owning the focused Accessibility element, which can differ from the frontmost
+ /// app (a non-activating panel such as a password manager's quick access).
+ fn focused_app(&self) -> Option<AppIdentity>;
/// The app owning the topmost window under a point.
fn window_owner_at(&self, at: Point) -> Option<AppIdentity>;
/// Brings an app back to the front (after a dialog took the focus).
diff --git a/apps/desktop/src-tauri/src/computer/risk.rs b/apps/desktop/src-tauri/src/computer/risk.rs
index 049d8a6..4c72c56 100644
--- a/apps/desktop/src-tauri/src/computer/risk.rs
+++ b/apps/desktop/src-tauri/src/computer/risk.rs
@@ -40,8 +40,14 @@ pub struct Focus {
pub enum Act<'a> {
/// A click: the element under the point first, then its ancestors.
Click(&'a [AxElement]),
- /// Return (or Enter), from `key` or a newline in `type`.
+ /// A drag: the chains under the start point and under the end point.
+ Drag(&'a [AxElement], &'a [AxElement]),
+ /// Return (or Enter), from `key`.
Return(Option<&'a Focus>),
+ /// Space, from `key`: it presses a focused button.
+ Space(Option<&'a Focus>),
+ /// Text from `type`: a newline presses Return and a space presses a focused button.
+ Type(&'a str, Option<&'a Focus>),
/// Every other action: only the intent can make it risky.
Other,
}
@@ -115,11 +121,35 @@ fn risky_return(focus: &Focus) -> Option<String> {
risky_word(&default).map(|_| format!("Return may press the default button “{default}”"))
}
+/// Space presses the focused button; in a field it only types a space.
+fn risky_space(focus: &Focus) -> Option<String> {
+ let element = &focus.element;
+ let label = element.label();
+ if focus.is_default_button {
+ return Some(format!("Space presses the default button “{label}”"));
+ }
+ if element.is_pressable() && risky_word(&label).is_some() {
+ return Some(format!("Space presses the {} “{label}”", kind(&element.role)));
+ }
+ None
+}
+
+fn risky_typing(text: &str, focus: &Focus) -> Option<String> {
+ let newline = text.contains('\n').then(|| risky_return(focus)).flatten();
+ newline.or_else(|| text.contains(' ').then(|| risky_space(focus)).flatten())
+}
+
/// Why `act` needs a confirmation, or `None` when it does not.
pub fn assess(act: Act<'_>, intent: Option<&str>) -> Option<String> {
let target = match act {
Act::Click(chain) => risky_click(chain),
+ Act::Drag(from, to) => match (risky_click(from), risky_click(to)) {
+ (Some(from), Some(to)) if from != to => Some(format!("{from} and {to}")),
+ (from, to) => from.or(to),
+ },
Act::Return(focus) => focus.and_then(risky_return),
+ Act::Space(focus) => focus.and_then(risky_space),
+ Act::Type(text, focus) => focus.and_then(|focus| risky_typing(text, focus)),
Act::Other => None,
};
let intent = intent.filter(|i| risky_word(i).is_some()).map(|i| format!("the declared intent “{}”", i.trim()));
@@ -223,6 +253,47 @@ mod tests {
assert_eq!(assess(Act::Return(None), None), None);
}
+ #[test]
+ fn a_drag_from_or_onto_a_risky_button_is_risky() {
+ let send = [element("AXButton", "Send")];
+ let open = [element("AXButton", "Open")];
+ assert!(assess(Act::Drag(&send, &send), None).is_some());
+ assert!(assess(Act::Drag(&send, &open), None).is_some());
+ assert!(assess(Act::Drag(&open, &send), None).is_some());
+ assert_eq!(assess(Act::Drag(&open, &[]), None), None);
+ }
+
+ #[test]
+ fn space_on_a_focused_risky_or_default_button_is_risky() {
+ assert!(assess(Act::Space(Some(&focus(element("AXButton", "Send")))), None).is_some());
+ let default = Focus { element: element("AXButton", "OK"), is_default_button: true, default_button: None };
+ assert!(assess(Act::Space(Some(&default)), None).is_some());
+ }
+
+ #[test]
+ fn space_elsewhere_is_not_risky() {
+ assert_eq!(assess(Act::Space(Some(&focus(element("AXButton", "Open")))), None), None);
+ // Space types in a field, even a send-like one or one with a risky default button.
+ let composer = Focus {
+ element: element("AXTextArea", "Message"),
+ is_default_button: false,
+ default_button: Some(element("AXButton", "Send")),
+ };
+ assert_eq!(assess(Act::Space(Some(&composer)), None), None);
+ assert_eq!(assess(Act::Space(None), None), None);
+ }
+
+ #[test]
+ fn typed_text_checks_its_spaces_and_newlines() {
+ let send = focus(element("AXButton", "Send"));
+ assert!(assess(Act::Type(" ", Some(&send)), None).is_some());
+ assert_eq!(assess(Act::Type("ok", Some(&send)), None), None);
+ let composer = focus(element("AXTextArea", "Message"));
+ assert_eq!(assess(Act::Type("hello there", Some(&composer)), None), None);
+ assert!(assess(Act::Type("hello\n", Some(&composer)), None).is_some());
+ assert_eq!(assess(Act::Type("a b\n", None), None), None);
+ }
+
#[test]
fn a_risky_intent_makes_any_action_risky() {
assert!(assess(Act::Other, Some("borrar el archivo")).is_some());
diff --git a/apps/desktop/src-tauri/src/computer/windows.rs b/apps/desktop/src-tauri/src/computer/windows.rs
new file mode 100644
index 0000000..bf7ecf2
--- /dev/null
+++ b/apps/desktop/src-tauri/src/computer/windows.rs
@@ -0,0 +1,103 @@
+//! Which window owns a point (S24.4), decided from the on-screen window list, front to back.
+//! The list also holds windows no app owns (the pointer, the menu bar backdrop), which must
+//! never stand in for the app underneath.
+
+use super::coords::Point;
+
+/// `kCGCursorWindowLevel`: the pointer and everything above it are never a target.
+pub const CURSOR_WINDOW_LEVEL: i64 = 2_147_483_630;
+
+/// One entry of `CGWindowListCopyWindowInfo`, in global points.
+#[derive(Debug, Clone, PartialEq)]
+pub struct WindowRow {
+ pub pid: i32,
+ pub owner_name: String,
+ pub layer: i64,
+ pub alpha: f64,
+ pub x: f64,
+ pub y: f64,
+ pub width: f64,
+ pub height: f64,
+}
+
+impl WindowRow {
+ fn contains(&self, at: Point) -> bool {
+ at.x >= self.x && at.y >= self.y && at.x < self.x + self.width && at.y < self.y + self.height
+ }
+
+ /// The window server draws the pointer, the menu bar backdrop, and other system layers.
+ fn is_window_server(&self) -> bool {
+ let owner: String = self.owner_name.chars().filter(|c| !c.is_whitespace()).collect();
+ owner.eq_ignore_ascii_case("WindowServer")
+ }
+
+ fn belongs_to_an_app(&self) -> bool {
+ self.pid > 0 && self.layer < CURSOR_WINDOW_LEVEL && !self.is_window_server()
+ }
+}
+
+/// The frontmost visible window under `at` that belongs to an app, or `None` when there is none.
+pub fn owner_row_at(rows: &[WindowRow], at: Point) -> Option<&WindowRow> {
+ rows.iter().find(|row| row.alpha > 0.0 && row.belongs_to_an_app() && row.contains(at))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const AT: Point = Point { x: 500.0, y: 400.0 };
+
+ fn row(pid: i32, owner: &str, layer: i64, (x, y, width, height): (f64, f64, f64, f64)) -> WindowRow {
+ WindowRow { pid, owner_name: owner.into(), layer, alpha: 1.0, x, y, width, height }
+ }
+
+ /// The pointer window as a real Mac lists it, right under the pointer and first in the list.
+ fn cursor() -> WindowRow {
+ row(412, "Window Server", CURSOR_WINDOW_LEVEL, (496.0, 396.0, 32.0, 32.0))
+ }
+
+ fn safari() -> WindowRow {
+ row(200, "Safari", 0, (0.0, 25.0, 1440.0, 875.0))
+ }
+
+ #[test]
+ fn the_pointer_window_is_skipped_for_the_app_underneath() {
+ let rows = [cursor(), safari()];
+ assert_eq!(owner_row_at(&rows, AT).map(|r| r.pid), Some(200));
+ }
+
+ #[test]
+ fn windows_owned_by_the_window_server_are_skipped() {
+ let backdrop = row(412, "WindowServer", 0, (0.0, 0.0, 1440.0, 900.0));
+ let rows = [row(412, "Window Server", 24, (0.0, 0.0, 1440.0, 900.0)), backdrop, safari()];
+ assert_eq!(owner_row_at(&rows, AT).map(|r| r.pid), Some(200));
+ }
+
+ #[test]
+ fn invisible_windows_and_windows_elsewhere_are_skipped() {
+ let clear = WindowRow { alpha: 0.0, ..row(300, "Overlay", 0, (0.0, 0.0, 1440.0, 900.0)) };
+ let elsewhere = row(301, "Notes", 0, (900.0, 600.0, 200.0, 200.0));
+ let rows = [clear, elsewhere, safari()];
+ assert_eq!(owner_row_at(&rows, AT).map(|r| r.pid), Some(200));
+ }
+
+ #[test]
+ fn rows_without_a_process_are_skipped() {
+ let rows = [row(0, "", 0, (0.0, 0.0, 1440.0, 900.0)), safari()];
+ assert_eq!(owner_row_at(&rows, AT).map(|r| r.pid), Some(200));
+ }
+
+ #[test]
+ fn high_system_prompts_still_own_their_point() {
+ // A lock or authorization prompt sits above every app window but below the pointer.
+ let prompt = row(150, "loginwindow", 2_147_483_628, (0.0, 0.0, 1440.0, 900.0));
+ let rows = [cursor(), prompt, safari()];
+ assert_eq!(owner_row_at(&rows, AT).map(|r| r.pid), Some(150));
+ }
+
+ #[test]
+ fn only_the_pointer_under_the_point_resolves_to_nothing() {
+ assert_eq!(owner_row_at(&[cursor()], AT), None);
+ assert_eq!(owner_row_at(&[], AT), None);
+ }
+}
diff --git a/apps/desktop/src-tauri/src/daemon.rs b/apps/desktop/src-tauri/src/daemon.rs
index dc662fc..4f6ff3e 100644
--- a/apps/desktop/src-tauri/src/daemon.rs
+++ b/apps/desktop/src-tauri/src/daemon.rs
@@ -5,7 +5,7 @@ use std::fs::{self, File, OpenOptions};
use std::io;
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
use std::path::{Path, PathBuf};
-use std::process::{Child, Command, Stdio};
+use std::process::{Child, ExitStatus};
use std::sync::Mutex;
use std::thread;
use std::time::{Duration, Instant};
@@ -48,8 +48,58 @@ pub fn open_private_log(data_dir: &Path) -> io::Result<File> {
Ok(log)
}
+/// A spawned process the app polls, stops, and reaps: a `std::process::Child`, or on macOS a
+/// daemon spawned with its TCC responsibility disclaimed (`disclaimed`).
+pub trait ChildProcess: Send {
+ fn id(&self) -> u32;
+ /// The exit status once the process ended (reaping it), `None` while it runs.
+ fn try_wait(&mut self) -> io::Result<Option<ExitStatus>>;
+ /// Sends SIGKILL unless the process was already reaped.
+ fn kill(&mut self) -> io::Result<()>;
+ fn wait(&mut self) -> io::Result<ExitStatus>;
+}
+
+impl ChildProcess for Child {
+ fn id(&self) -> u32 {
+ Child::id(self)
+ }
+
+ fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
+ Child::try_wait(self)
+ }
+
+ fn kill(&mut self) -> io::Result<()> {
+ Child::kill(self)
+ }
+
+ fn wait(&mut self) -> io::Result<ExitStatus> {
+ Child::wait(self)
+ }
+}
+
+/// Starts the daemon with stdin from `/dev/null` and its output in `log`. On macOS the app
+/// disclaims responsibility for it, so it never inherits the app's TCC grants (S24.1).
+#[cfg(target_os = "macos")]
+fn spawn_daemon(spec: &LaunchSpec, log: File) -> io::Result<Box<dyn ChildProcess>> {
+ let child = crate::disclaimed::spawn_disclaimed(&spec.program, &spec.args, &spec.envs, &log)?;
+ Ok(Box::new(child))
+}
+
+#[cfg(not(target_os = "macos"))]
+fn spawn_daemon(spec: &LaunchSpec, log: File) -> io::Result<Box<dyn ChildProcess>> {
+ use std::process::{Command, Stdio};
+ let child = Command::new(&spec.program)
+ .args(&spec.args)
+ .envs(spec.envs.iter().map(|(k, v)| (k, v)))
+ .stdin(Stdio::null())
+ .stdout(log.try_clone()?)
+ .stderr(log)
+ .spawn()?;
+ Ok(Box::new(child))
+}
+
/// Sends SIGTERM, waits up to `grace` for a clean exit, then kills.
-pub fn stop_child(child: &mut Child, grace: Duration) {
+pub fn stop_child(child: &mut dyn ChildProcess, grace: Duration) {
if !matches!(child.try_wait(), Ok(None)) {
return;
}
@@ -82,7 +132,7 @@ pub enum RestartOutcome {
pub struct Daemon {
port: u16,
data_dir: PathBuf,
- child: Mutex<Option<Child>>,
+ child: Mutex<Option<Box<dyn ChildProcess>>>,
}
impl Daemon {
@@ -130,14 +180,7 @@ impl Daemon {
}
let spec = launch_spec(|key| std::env::var(key).ok(), cfg!(debug_assertions));
let log = open_private_log(&self.data_dir).map_err(|e| format!("cannot open daemon.log: {e}"))?;
- let child = Command::new(&spec.program)
- .args(&spec.args)
- .envs(spec.envs.iter().map(|(k, v)| (k, v)))
- .stdin(Stdio::null())
- .stdout(log.try_clone().map_err(|e| e.to_string())?)
- .stderr(log)
- .spawn()
- .map_err(|e| format!("cannot start {}: {e}", spec.program))?;
+ let child = spawn_daemon(&spec, log).map_err(|e| format!("cannot start {}: {e}", spec.program))?;
*slot = Some(child);
Ok(())
}
@@ -151,7 +194,7 @@ impl Daemon {
/// Stops the daemon only if this app spawned it.
pub fn stop(&self) {
if let Some(mut child) = self.child.lock().unwrap().take() {
- stop_child(&mut child, STOP_GRACE);
+ stop_child(child.as_mut(), STOP_GRACE);
}
}
@@ -171,6 +214,7 @@ impl Daemon {
#[cfg(test)]
mod tests {
use super::*;
+ use std::process::Command;
fn env_of(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {
move |key| pairs.iter().find(|(k, _)| *k == key).map(|(_, v)| v.to_string())
diff --git a/apps/desktop/src-tauri/src/disclaimed.rs b/apps/desktop/src-tauri/src/disclaimed.rs
new file mode 100644
index 0000000..7856c10
--- /dev/null
+++ b/apps/desktop/src-tauri/src/disclaimed.rs
@@ -0,0 +1,286 @@
+//! Spawns the daemon on macOS with its TCC responsibility disclaimed (S24.1).
+//!
+//! A plain spawn makes Gentle Dot.app the "responsible process" of the daemon, so the daemon,
+//! the engine, and the agent's shell would inherit the app's Accessibility and Screen Recording
+//! grants and could drive the Mac without the helper. With the responsibility disclaimed, the
+//! daemon answers for itself and holds no grant.
+
+use crate::daemon::ChildProcess;
+use std::collections::BTreeMap;
+use std::ffi::{CString, OsStr, OsString};
+use std::fs::File;
+use std::io;
+use std::os::fd::AsRawFd;
+use std::os::unix::ffi::{OsStrExt, OsStringExt};
+use std::os::unix::process::ExitStatusExt;
+use std::path::PathBuf;
+use std::process::ExitStatus;
+
+extern "C" {
+ /// libSystem (macOS 10.14+): the spawned process becomes responsible for itself. Chromium
+ /// and LLDB use it for the same reason.
+ fn responsibility_spawnattrs_setdisclaim(attrs: *mut libc::posix_spawnattr_t, disclaim: libc::c_int)
+ -> libc::c_int;
+}
+
+/// A process spawned by `spawn_disclaimed`, reaped by its owner like `std::process::Child`.
+#[derive(Debug)]
+pub struct DisclaimedChild {
+ pid: libc::pid_t,
+ status: Option<ExitStatus>,
+}
+
+impl DisclaimedChild {
+ fn wait_with(&mut self, flags: libc::c_int) -> io::Result<Option<ExitStatus>> {
+ if let Some(status) = self.status {
+ return Ok(Some(status));
+ }
+ let mut raw = 0;
+ loop {
+ // SAFETY: `raw` is a valid out-pointer and `pid` is our unreaped child.
+ match unsafe { libc::waitpid(self.pid, &mut raw, flags) } {
+ 0 => return Ok(None),
+ -1 if io::Error::last_os_error().kind() == io::ErrorKind::Interrupted => continue,
+ -1 => return Err(io::Error::last_os_error()),
+ _ => {
+ self.status = Some(ExitStatus::from_raw(raw));
+ return Ok(self.status);
+ }
+ }
+ }
+ }
+}
+
+impl ChildProcess for DisclaimedChild {
+ fn id(&self) -> u32 {
+ self.pid as u32
+ }
+
+ fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
+ self.wait_with(libc::WNOHANG)
+ }
+
+ fn kill(&mut self) -> io::Result<()> {
+ if self.status.is_some() {
+ return Ok(());
+ }
+ // SAFETY: the pid is our unreaped child, so it cannot have been reused.
+ if unsafe { libc::kill(self.pid, libc::SIGKILL) } == -1 {
+ return Err(io::Error::last_os_error());
+ }
+ Ok(())
+ }
+
+ fn wait(&mut self) -> io::Result<ExitStatus> {
+ self.wait_with(0)?.ok_or_else(|| io::Error::other("waitpid returned no status"))
+ }
+}
+
+fn check(code: libc::c_int) -> io::Result<()> {
+ if code == 0 {
+ Ok(())
+ } else {
+ Err(io::Error::from_raw_os_error(code))
+ }
+}
+
+fn c_string(bytes: &[u8]) -> io::Result<CString> {
+ CString::new(bytes).map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "a NUL byte in the command"))
+}
+
+/// `program` itself when it has a `/`, otherwise the first executable match in `path`.
+fn resolve(program: &str, path: Option<&OsStr>) -> PathBuf {
+ if program.contains('/') {
+ return program.into();
+ }
+ let found = path.into_iter().flat_map(std::env::split_paths).map(|dir| dir.join(program)).find(|candidate| {
+ c_string(candidate.as_os_str().as_bytes())
+ // SAFETY: a NUL-terminated path.
+ .is_ok_and(|c| unsafe { libc::access(c.as_ptr(), libc::X_OK) } == 0)
+ });
+ found.unwrap_or_else(|| program.into())
+}
+
+struct Attributes(libc::posix_spawnattr_t);
+
+impl Drop for Attributes {
+ fn drop(&mut self) {
+ // SAFETY: initialized by `posix_spawnattr_init`.
+ unsafe { libc::posix_spawnattr_destroy(&mut self.0) };
+ }
+}
+
+struct FileActions(libc::posix_spawn_file_actions_t);
+
+impl Drop for FileActions {
+ fn drop(&mut self) {
+ // SAFETY: initialized by `posix_spawn_file_actions_init`.
+ unsafe { libc::posix_spawn_file_actions_destroy(&mut self.0) };
+ }
+}
+
+/// Runs `program` with `args` and the app's environment plus `envs`, stdin from `/dev/null`,
+/// and stdout and stderr appended to `log`. A program without a `/` is looked up in the
+/// child's `PATH`. No other descriptor of the app reaches the child.
+pub fn spawn_disclaimed(
+ program: &str,
+ args: &[String],
+ envs: &[(String, String)],
+ log: &File,
+) -> io::Result<DisclaimedChild> {
+ let mut env: BTreeMap<OsString, OsString> = std::env::vars_os().collect();
+ env.extend(envs.iter().map(|(k, v)| (OsString::from(k), OsString::from(v))));
+ let path = resolve(program, env.get(OsStr::new("PATH")).map(OsString::as_os_str));
+ let path = c_string(path.as_os_str().as_bytes())?;
+ let argv = std::iter::once(program)
+ .chain(args.iter().map(String::as_str))
+ .map(|arg| c_string(arg.as_bytes()))
+ .collect::<io::Result<Vec<_>>>()?;
+ let envp = env
+ .into_iter()
+ .map(|(key, value)| {
+ let mut entry = key.into_vec();
+ entry.push(b'=');
+ entry.extend(value.into_vec());
+ c_string(&entry)
+ })
+ .collect::<io::Result<Vec<_>>>()?;
+ let mut argv_ptrs: Vec<*mut libc::c_char> = argv.iter().map(|a| a.as_ptr().cast_mut()).collect();
+ argv_ptrs.push(std::ptr::null_mut());
+ let mut envp_ptrs: Vec<*mut libc::c_char> = envp.iter().map(|e| e.as_ptr().cast_mut()).collect();
+ envp_ptrs.push(std::ptr::null_mut());
+ let dev_null = c"/dev/null";
+
+ // SAFETY: every pointer handed to posix_spawn outlives the call, and the attribute and
+ // file-action objects are initialized before use and destroyed by their guards.
+ unsafe {
+ let mut attributes = Attributes(std::ptr::null_mut());
+ check(libc::posix_spawnattr_init(&mut attributes.0))?;
+ // Like `std::process::Command`: an empty signal mask and the default SIGPIPE. Every
+ // descriptor not named below is closed in the child.
+ let mut empty: libc::sigset_t = 0;
+ libc::sigemptyset(&mut empty);
+ check(libc::posix_spawnattr_setsigmask(&mut attributes.0, &empty))?;
+ let mut pipe: libc::sigset_t = 0;
+ libc::sigemptyset(&mut pipe);
+ libc::sigaddset(&mut pipe, libc::SIGPIPE);
+ check(libc::posix_spawnattr_setsigdefault(&mut attributes.0, &pipe))?;
+ let flags = libc::POSIX_SPAWN_SETSIGMASK | libc::POSIX_SPAWN_SETSIGDEF | libc::POSIX_SPAWN_CLOEXEC_DEFAULT;
+ check(libc::posix_spawnattr_setflags(&mut attributes.0, flags as libc::c_short))?;
+ check(responsibility_spawnattrs_setdisclaim(&mut attributes.0, 1))?;
+
+ let mut actions = FileActions(std::ptr::null_mut());
+ check(libc::posix_spawn_file_actions_init(&mut actions.0))?;
+ check(libc::posix_spawn_file_actions_addopen(&mut actions.0, 0, dev_null.as_ptr(), libc::O_RDONLY, 0))?;
+ check(libc::posix_spawn_file_actions_adddup2(&mut actions.0, log.as_raw_fd(), 1))?;
+ check(libc::posix_spawn_file_actions_adddup2(&mut actions.0, log.as_raw_fd(), 2))?;
+
+ let mut pid: libc::pid_t = 0;
+ check(libc::posix_spawn(
+ &mut pid,
+ path.as_ptr(),
+ &actions.0,
+ &attributes.0,
+ argv_ptrs.as_ptr(),
+ envp_ptrs.as_ptr(),
+ ))?;
+ Ok(DisclaimedChild { pid, status: None })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::daemon::stop_child;
+ use std::os::unix::process::ExitStatusExt;
+ use std::path::PathBuf;
+ use std::thread;
+ use std::time::{Duration, Instant};
+
+ extern "C" {
+ /// The process macOS holds responsible for `pid` (private libSystem call, read-only).
+ fn responsibility_get_pid_responsible_for_pid(pid: libc::pid_t) -> libc::pid_t;
+ }
+
+ fn scratch_log(name: &str) -> (PathBuf, File) {
+ let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
+ let dir = std::env::temp_dir().join(format!("gentle-dot-{name}-{}-{nanos}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("daemon.log");
+ let log = std::fs::OpenOptions::new().create(true).append(true).open(&path).unwrap();
+ (path, log)
+ }
+
+ fn sh(script: &str, envs: &[(String, String)], log: &File) -> DisclaimedChild {
+ spawn_disclaimed("/bin/sh", &["-c".into(), script.into()], envs, log).unwrap()
+ }
+
+ #[test]
+ fn the_child_answers_for_itself() {
+ let (_, log) = scratch_log("disclaim");
+ let mut child = spawn_disclaimed("/bin/sleep", &["30".into()], &[], &log).unwrap();
+ thread::sleep(Duration::from_millis(100));
+ let pid = child.id() as libc::pid_t;
+ // SAFETY: a read-only query about a live child.
+ let responsible = unsafe { responsibility_get_pid_responsible_for_pid(pid) };
+ assert_eq!(responsible, pid);
+ stop_child(&mut child, Duration::from_secs(5));
+ }
+
+ #[test]
+ fn output_goes_to_the_log_with_the_extra_env_and_no_stdin() {
+ let (path, log) = scratch_log("output");
+ let envs = [("GENTLE_DOT_TEST".to_string(), "from-spec".to_string())];
+ let script = "echo out; echo err >&2; echo \"$GENTLE_DOT_TEST\"; if read x; then echo input; else echo eof; fi";
+ let mut child = sh(script, &envs, &log);
+ assert!(child.wait().unwrap().success());
+ assert_eq!(std::fs::read_to_string(path).unwrap(), "out\nerr\nfrom-spec\neof\n");
+ }
+
+ #[test]
+ fn a_bare_program_name_is_found_in_the_child_path() {
+ let (path, log) = scratch_log("path");
+ let envs = [("PATH".to_string(), "/usr/bin:/bin".to_string())];
+ let mut child = spawn_disclaimed("echo", &["found".into()], &envs, &log).unwrap();
+ assert!(child.wait().unwrap().success());
+ assert_eq!(std::fs::read_to_string(path).unwrap(), "found\n");
+ }
+
+ #[test]
+ fn try_wait_reports_running_then_the_exit_code() {
+ let (_, log) = scratch_log("status");
+ let mut child = sh("sleep 0.3; exit 3", &[], &log);
+ assert!(child.try_wait().unwrap().is_none());
+ let deadline = Instant::now() + Duration::from_secs(5);
+ let status = loop {
+ if let Some(status) = child.try_wait().unwrap() {
+ break status;
+ }
+ assert!(Instant::now() < deadline);
+ thread::sleep(Duration::from_millis(20));
+ };
+ assert_eq!(status.code(), Some(3));
+ // Reaped once; later calls keep answering.
+ assert_eq!(child.try_wait().unwrap().and_then(|s| s.code()), Some(3));
+ assert_eq!(child.wait().unwrap().code(), Some(3));
+ child.kill().unwrap();
+ }
+
+ #[test]
+ fn stop_child_terminates_then_kills_after_the_grace() {
+ let (_, log) = scratch_log("stop");
+ let mut child = spawn_disclaimed("/bin/sleep", &["30".into()], &[], &log).unwrap();
+ stop_child(&mut child, Duration::from_secs(5));
+ assert_eq!(child.try_wait().unwrap().and_then(|s| s.signal()), Some(libc::SIGTERM));
+ let mut stubborn = sh("trap '' TERM; sleep 30", &[], &log);
+ thread::sleep(Duration::from_millis(100));
+ stop_child(&mut stubborn, Duration::from_millis(300));
+ assert_eq!(stubborn.try_wait().unwrap().and_then(|s| s.signal()), Some(libc::SIGKILL));
+ }
+
+ #[test]
+ fn a_missing_program_is_an_error() {
+ let (_, log) = scratch_log("missing");
+ assert!(spawn_disclaimed("/nonexistent/gentle-dot-node", &[], &[], &log).is_err());
+ }
+}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 37e517c..4625c68 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -1,6 +1,8 @@
pub mod computer;
pub mod config;
pub mod daemon;
+#[cfg(target_os = "macos")]
+pub mod disclaimed;
pub mod geometry;
pub mod health;
pub mod platform;
diff --git a/packages/daemon/src/connectors.ts b/packages/daemon/src/connectors.ts
index 7daf3bd..b37243a 100644
--- a/packages/daemon/src/connectors.ts
+++ b/packages/daemon/src/connectors.ts
@@ -525,7 +525,9 @@ export class ConnectorStore {
this.file = join(options.dataDir, "connectors.json");
this.mcpFile = join(options.agentHome, "mcp.json");
this.authFile = join(options.agentHome, "mcp-auth.json");
- this.saved = this.load();
+ const { state, renamed } = this.load();
+ this.saved = state;
+ if (renamed) writePrivate(this.file, this.recordText());
}
get agentHome(): string {
@@ -711,16 +713,29 @@ export class ConnectorStore {
return `${JSON.stringify({ version: 1, connectors: this.saved.connectors }, null, 2)}\n`;
}
- private load(): ConnectorsState {
+ /** The saved state; a connector saved as `computer` (the built-in helper's name) gets `computer-2`. */
+ private load(): { state: ConnectorsState; renamed: boolean } {
try {
const saved = JSON.parse(readFileSync(this.file, "utf8")) as {
connectors?: Record<string, Record<string, unknown> | undefined>;
};
const connectors: ConnectorsState["connectors"] = {};
- for (const [id, value] of Object.entries(saved.connectors ?? {})) {
- if (id === COMPUTER_ID) continue;
+ const entries = Object.entries(saved.connectors ?? {});
+ const ordered = [
+ ...entries.filter(([id]) => id !== COMPUTER_ID),
+ ...entries.filter(([id]) => id === COMPUTER_ID),
+ ];
+ let renamed = false;
+ for (const [savedId, value] of ordered) {
+ let id = savedId;
+ if (id === COMPUTER_ID) {
+ let n = 2;
+ while (`${COMPUTER_ID}-${n}` in connectors || catalogEntry(`${COMPUTER_ID}-${n}`)) n++;
+ id = `${COMPUTER_ID}-${n}`;
+ }
const custom = catalogEntry(id) ? undefined : parseCustom(value?.custom);
if (!catalogEntry(id) && !custom) continue;
+ renamed ||= id !== savedId;
const entry: SavedConnector = {
enabled: value?.enabled === true,
mode: value?.mode === "read_write" ? "read_write" : "read_only",
@@ -730,9 +745,9 @@ export class ConnectorStore {
if (custom) entry.custom = custom;
connectors[id] = entry;
}
- return { connectors };
+ return { state: { connectors }, renamed };
} catch {
- return { connectors: {} };
+ return { state: { connectors: {} }, renamed: false };
}
}
}
diff --git a/packages/daemon/test/computer.test.ts b/packages/daemon/test/computer.test.ts
index e38b60b..554f580 100644
--- a/packages/daemon/test/computer.test.ts
+++ b/packages/daemon/test/computer.test.ts
@@ -216,7 +216,7 @@ describe("computer control registration (S24.7)", () => {
expect(computerOf(await second.list())).toBeUndefined();
});
- it("cannot be changed or removed through the connector messages, and no saved connector takes its name", async () => {
+ it("cannot be changed or removed through the connector messages, and a saved connector with its name is renamed", async () => {
const { servers, send, messages, list } = await setup({
saved: {
version: 1,
@@ -231,6 +231,11 @@ describe("computer control registration (S24.7)", () => {
});
expect(computerOf(await list())).toBeUndefined();
expect(servers().computer).toBeUndefined();
+ expect((await list()).find((c) => c.id === "computer-2")).toMatchObject({
+ name: "Computer",
+ enabled: true,
+ });
+ expect(servers()["computer-2"]).toMatchObject({ url: "http://127.0.0.1:9/mcp" });
send({ type: "computer_register", url: HELPER, token: KEY });
await waitFor(() => servers().computer);
diff --git a/packages/daemon/test/connectors.test.ts b/packages/daemon/test/connectors.test.ts
index 589820f..8496ed6 100644
--- a/packages/daemon/test/connectors.test.ts
+++ b/packages/daemon/test/connectors.test.ts
@@ -166,6 +166,40 @@ describe("connector store", () => {
expect(next.state()).toEqual({ connectors: { notion: { enabled: true, mode: "read_only" } } });
});
+ it("renames a saved connector called `computer` (the helper's name) instead of dropping it, and keeps the rename", () => {
+ const { dataDir, agentHome, workspace } = store();
+ const custom = (name: string) => ({
+ name,
+ origin: "x",
+ server: { url: "http://127.0.0.1:9/mcp" },
+ fields: [],
+ });
+ writeFileSync(
+ join(dataDir, "connectors.json"),
+ JSON.stringify({
+ version: 1,
+ connectors: {
+ computer: { enabled: true, mode: "read_write", custom: custom("Computer") },
+ "computer-2": { enabled: false, mode: "read_only", custom: custom("Computer 2") },
+ },
+ }),
+ );
+ const s = new ConnectorStore({ dataDir, agentHome, workspace });
+ stores.push(s);
+ const { connectors } = s.state();
+ expect(Object.keys(connectors).sort()).toEqual(["computer-2", "computer-3"]);
+ expect(connectors["computer-3"]).toMatchObject({
+ enabled: true,
+ mode: "read_write",
+ custom: { name: "Computer" },
+ });
+ const saved = JSON.parse(readFileSync(join(dataDir, "connectors.json"), "utf8"));
+ expect(Object.keys(saved.connectors).sort()).toEqual(["computer-2", "computer-3"]);
+ const next = new ConnectorStore({ dataDir, agentHome, workspace });
+ stores.push(next);
+ expect(next.state()).toEqual(s.state());
+ });
+
it("rewrites an older record (with a hash) quietly at start", () => {
const { dataDir, agentHome, workspace } = store();
writeFileSync(