Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
feat: add an on-screen permission guide for macOS onboarding (#299)
Lahfir02afee6700ec
diff --git a/README.md b/README.mdindex 45c8eb5a8..d25d1dc48 100644--- a/README.md+++ b/README.md@@ -54,7 +54,7 @@ cargo build --release -p agent-desktop### Permissions-macOS needs Accessibility permission. Screenshots also need Screen Recording, and opening Notification Center needs Automation permission for System Events. `agent-desktop permissions` reports the state without prompting; `agent-desktop permissions --request` asks for what is missing.+macOS needs Accessibility permission. Screenshots also need Screen Recording, and opening Notification Center needs Automation permission for System Events. `agent-desktop permissions` reports the state without prompting; `agent-desktop permissions --request` asks for what is missing; `agent-desktop permissions --guide` opens System Settings at the missing permission with an on-screen guide that shows what to drag.Windows needs no grant for apps at your terminal's integrity level. An app running as administrator can be read, but only an elevated agent can send it input. The binary is unsigned, so SmartScreen may warn on a browser download, antivirus may quarantine it, and Smart App Control on a clean Windows 11 install blocks it. The npm install path does not trigger SmartScreen.diff --git a/crates/core/src/adapter/system.rs b/crates/core/src/adapter/system.rsindex abcaea777..3c9c18816 100644--- a/crates/core/src/adapter/system.rs+++ b/crates/core/src/adapter/system.rs@@ -58,6 +58,13 @@ pub trait SystemOps: Send + Sync {self.permission_report(lease.deadline())}+ /// Starts a detached, on-screen guide that walks the user through granting+ /// the missing permissions, and returns without waiting for it. The result+ /// is `started`, `already_running`, or `not_needed`.+ fn start_permission_guide(&self) -> Result<&'static str, AdapterError> {+ Err(AdapterError::not_supported("start_permission_guide"))+ }+/// Performs the platform-native focus/raise operation for the exact window./// Core decides when focus is required; implementations must return only/// after that window is confirmed focused, or return an error.diff --git a/crates/core/src/commands/permissions.rs b/crates/core/src/commands/permissions.rsindex 3fd32a5c3..05ca1d999 100644--- a/crates/core/src/commands/permissions.rs+++ b/crates/core/src/commands/permissions.rs@@ -3,6 +3,7 @@ use serde_json::{Value, json};pub struct PermissionsArgs {pub request: bool,+ pub guide: bool,}pub fn execute_with_report(@@ -16,9 +17,13 @@ pub fn execute_with_report(} else {report.clone()};- Ok(json!({+ let mut data = json!({"accessibility": report.accessibility,"screen_recording": report.screen_recording,"automation": report.automation- }))+ });+ if args.guide {+ data["guide"] = json!(adapter.start_permission_guide()?);+ }+ Ok(data)}diff --git a/crates/core/src/commands/status.rs b/crates/core/src/commands/status.rsindex cdad7f3e4..e2ec8e66c 100644--- a/crates/core/src/commands/status.rs+++ b/crates/core/src/commands/status.rs@@ -12,8 +12,14 @@ pub fn execute_with_report_with_context(report: &PermissionReport,context: &CommandContext,) -> Result<Value, AppError> {- let permissions =- permissions::execute_with_report(PermissionsArgs { request: false }, adapter, report)?;+ let permissions = permissions::execute_with_report(+ PermissionsArgs {+ request: false,+ guide: false,+ },+ adapter,+ report,+ )?;let store = RefStore::for_session(context.session_id())?;let snapshot_id = store.latest_snapshot_id()?;diff --git a/crates/macos/build.rs b/crates/macos/build.rsindex 405142ff7..7aaff16a8 100644--- a/crates/macos/build.rs+++ b/crates/macos/build.rs@@ -10,6 +10,7 @@ fn main() {println!("cargo:rerun-if-changed=src/system/cursor_overlay_chrome.h");println!("cargo:rerun-if-changed=src/system/cursor_overlay_display_bridge.m");println!("cargo:rerun-if-changed=src/system/cursor_overlay_image_bridge.m");+ println!("cargo:rerun-if-changed=src/system/permission_guide_bridge.m");println!("cargo:rerun-if-env-changed=TARGET");println!("cargo:rerun-if-env-changed=MACOSX_DEPLOYMENT_TARGET");if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("macos") {@@ -30,6 +31,7 @@ fn main() {let cursor_overlay_chrome_object = out_dir.join("cursor_overlay_chrome_bridge.o");let cursor_overlay_display_object = out_dir.join("cursor_overlay_display_bridge.o");let cursor_overlay_image_object = out_dir.join("cursor_overlay_image_bridge.o");+ let permission_guide_object = out_dir.join("permission_guide_bridge.o");let archive = out_dir.join("libagent_desktop_launch_bridge.a");run(Command::new("xcrun")@@ -143,6 +145,22 @@ fn main() {.arg(&screen_object),"compile Objective-C screen bridge",);+ run(+ Command::new("xcrun")+ .args(["--sdk", "macosx", "clang"])+ .args(["-fobjc-arc", "-fblocks", "-target", &target])+ .arg(format!("-mmacosx-version-min={deployment}"))+ .args([+ "-Wall",+ "-Wextra",+ "-Werror",+ "-c",+ "src/system/permission_guide_bridge.m",+ "-o",+ ])+ .arg(&permission_guide_object),+ "compile Objective-C permission guide bridge",+ );run(Command::new("xcrun").args(["--sdk", "macosx", "ar", "rcs"])@@ -153,7 +171,8 @@ fn main() {.arg(&cursor_overlay_object).arg(&cursor_overlay_display_object).arg(&cursor_overlay_chrome_object)- .arg(&cursor_overlay_image_object),+ .arg(&cursor_overlay_image_object)+ .arg(&permission_guide_object),"archive Objective-C launch bridge",);println!("cargo:rustc-link-search=native={}", out_dir.display());diff --git a/crates/macos/src/lib.rs b/crates/macos/src/lib.rsindex 7f63e0729..e2d94ae64 100644--- a/crates/macos/src/lib.rs+++ b/crates/macos/src/lib.rs@@ -11,5 +11,6 @@ mod tree;pub use adapter::MacOSAdapter;pub use input::clipboard::helper_entry_from_env as clipboard_helper_from_env;pub use system::cocoa_runtime::ensure_cocoa_multithreaded;+pub use system::permission_guide::entry_from_env as permission_guide_from_env;pub use system::permission_helper::entry_from_env as permission_prompt_helper_from_env;pub use tree::retained::RetainedRefSession;diff --git a/crates/macos/src/system/adapter.rs b/crates/macos/src/system/adapter.rsindex a96a95557..2be915672 100644--- a/crates/macos/src/system/adapter.rs+++ b/crates/macos/src/system/adapter.rs@@ -58,6 +58,10 @@ impl SystemOps for MacOSAdapter {crate::system::permissions::request_report(lease.deadline())}+ fn start_permission_guide(&self) -> Result<&'static str, AdapterError> {+ crate::system::permission_guide::start()+ }+fn unknown_accessibility_means_unsupported(&self) -> bool {false}diff --git a/crates/macos/src/system/mod.rs b/crates/macos/src/system/mod.rsindex 3cc2011df..c2fc60cb0 100644--- a/crates/macos/src/system/mod.rs+++ b/crates/macos/src/system/mod.rs@@ -14,6 +14,7 @@ pub(crate) mod launch;pub(crate) mod launch_callback_result;pub(crate) mod launch_completion;pub(crate) mod launch_workspace;+pub(crate) mod permission_guide;pub(crate) mod permission_helper;pub(crate) mod permission_operation;pub(crate) mod permissions;diff --git a/crates/macos/src/system/permission_guide.rs b/crates/macos/src/system/permission_guide.rsnew file mode 100644index 000000000..d8700e1d2--- /dev/null+++ b/crates/macos/src/system/permission_guide.rs@@ -0,0 +1,232 @@+use agent_desktop_core::AdapterError;+use std::ffi::{CStr, CString, c_char};+use std::fs::File;+use std::os::fd::AsRawFd;+use std::os::unix::process::CommandExt;+use std::path::{Path, PathBuf};+use std::process::{Command, Stdio};+use std::time::{Duration, Instant};++const STEPS_ENV: &str = "AGENT_DESKTOP_PERMISSION_GUIDE";+const HOST_ENV: &str = "AGENT_DESKTOP_PERMISSION_GUIDE_HOST";+const LOCK_ENV: &str = "AGENT_DESKTOP_PERMISSION_GUIDE_LOCK";+const LOCK_NAME: &str = "agent-desktop-permission-guide.lock";+const ACCESSIBILITY: u8 = 1;+const SCREEN_RECORDING: u8 = 2;+const PROBE_TIMEOUT: Duration = Duration::from_secs(3);+const HOST_PATH_CAPACITY: usize = 4096;+const COMMAND_HOST_ENVS: [&str; 3] = [+ "AGENT_DESKTOP_INTERNAL_COMMAND_HOST",+ "AGENT_DESKTOP_INTERNAL_HOST_SOCKET",+ "AGENT_DESKTOP_INTERNAL_HOST_CLIENT",+];++pub(crate) fn start() -> Result<&'static str, AdapterError> {+ let steps = missing_steps(+ super::permissions::preflight_accessibility(),+ super::permissions::preflight_screen_recording(),+ );+ if steps == 0 {+ return Ok("not_needed");+ }+ let lock = match single_instance_lock() {+ Ok(Some(lock)) => lock,+ Ok(None) => return Ok("already_running"),+ Err(error) => {+ return Err(+ AdapterError::internal("Could not open the permission guide lock")+ .with_platform_detail(error.to_string()),+ );+ }+ };+ let executable = std::env::current_exe().map_err(|error| {+ AdapterError::internal("Could not locate the agent-desktop executable")+ .with_platform_detail(error.to_string())+ })?;+ let host = host_app().unwrap_or_else(|| executable.clone());+ let mut command = Command::new(&executable);+ for name in COMMAND_HOST_ENVS {+ command.env_remove(name);+ }+ hand_over(&mut command, &lock);+ let mut child = command+ .env(STEPS_ENV, steps.to_string())+ .env(HOST_ENV, host)+ .process_group(0)+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .map_err(|error| {+ AdapterError::internal("Could not start the macOS permission guide")+ .with_platform_detail(error.to_string())+ })?;+ std::thread::spawn(move || child.wait());+ Ok("started")+}++pub fn entry_from_env() -> Option<u8> {+ let steps = std::env::var(STEPS_ENV).ok()?;+ Some(if run_child(&steps) { 0 } else { 1 })+}++fn run_child(steps: &str) -> bool {+ let Some(steps) = parse_steps(steps) else {+ return false;+ };+ let Some(host) = std::env::var(HOST_ENV)+ .ok()+ .filter(|path| std::path::Path::new(path).exists())+ .and_then(|path| CString::new(path).ok())+ else {+ return false;+ };+ if !keep_inherited_lock() {+ return false;+ }+ unsafe { agent_desktop_permission_guide_run(steps, host.as_ptr(), granted) == 0 }+}++extern "C" fn granted(step: u8) -> bool {+ let key = match step {+ ACCESSIBILITY => "accessibility",+ SCREEN_RECORDING => "screen_recording",+ _ => return false,+ };+ let Ok(executable) = std::env::current_exe() else {+ return false;+ };+ let mut command = Command::new(executable);+ command.arg("permissions").env_remove(STEPS_ENV);+ super::process::run_with_deadline(+ &mut command,+ "macOS permission guide probe",+ Instant::now() + PROBE_TIMEOUT,+ )+ .is_ok_and(|output| reports_granted(&output.stdout, key))+}++fn reports_granted(stdout: &[u8], key: &str) -> bool {+ serde_json::from_slice::<serde_json::Value>(stdout)+ .is_ok_and(|response| response["data"][key]["state"] == "granted")+}++fn missing_steps(accessibility: bool, screen_recording: bool) -> u8 {+ let mut steps = 0;+ if !accessibility {+ steps |= ACCESSIBILITY;+ }+ if !screen_recording {+ steps |= SCREEN_RECORDING;+ }+ steps+}++fn parse_steps(value: &str) -> Option<u8> {+ value+ .parse::<u8>()+ .ok()+ .filter(|steps| (1..=(ACCESSIBILITY | SCREEN_RECORDING)).contains(steps))+}++fn host_app() -> Option<PathBuf> {+ let mut buffer = [0 as c_char; HOST_PATH_CAPACITY];+ if !unsafe { agent_desktop_permission_guide_host(buffer.as_mut_ptr(), buffer.len()) } {+ return None;+ }+ let path = unsafe { CStr::from_ptr(buffer.as_ptr()) };+ path.to_str().ok().map(PathBuf::from)+}++fn hand_over(command: &mut Command, lock: &File) {+ let fd = lock.as_raw_fd();+ command.env(LOCK_ENV, fd.to_string());+ unsafe {+ command.pre_exec(move || {+ if libc::fcntl(fd, libc::F_SETFD, 0) == -1 {+ return Err(std::io::Error::last_os_error());+ }+ Ok(())+ });+ }+}++fn keep_inherited_lock() -> bool {+ std::env::var(LOCK_ENV)+ .ok()+ .and_then(|fd| fd.parse::<i32>().ok())+ .is_some_and(|fd| unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) } == 0)+}++fn single_instance_lock() -> std::io::Result<Option<File>> {+ lock_file(&std::env::temp_dir().join(LOCK_NAME))+}++fn lock_file(path: &Path) -> std::io::Result<Option<File>> {+ let file = File::options()+ .create(true)+ .truncate(false)+ .write(true)+ .open(path)?;+ if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 {+ return Ok(Some(file));+ }+ let error = std::io::Error::last_os_error();+ if error.raw_os_error() == Some(libc::EWOULDBLOCK) {+ Ok(None)+ } else {+ Err(error)+ }+}++unsafe extern "C" {+ fn agent_desktop_permission_guide_host(output: *mut c_char, capacity: usize) -> bool;+ fn agent_desktop_permission_guide_run(+ steps: u8,+ host_path: *const c_char,+ granted: extern "C" fn(u8) -> bool,+ ) -> i32;+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn guide_covers_only_missing_permissions() {+ assert_eq!(missing_steps(true, true), 0);+ assert_eq!(missing_steps(false, true), ACCESSIBILITY);+ assert_eq!(missing_steps(true, false), SCREEN_RECORDING);+ assert_eq!(+ missing_steps(false, false),+ ACCESSIBILITY | SCREEN_RECORDING+ );+ assert_eq!(parse_steps("3"), Some(3));+ assert_eq!(parse_steps("0"), None);+ assert_eq!(parse_steps("4"), None);+ }++ #[test]+ fn the_guide_lock_stays_held_from_the_check_through_the_child() {+ let path = std::env::temp_dir().join(format!("{LOCK_NAME}.{}.test", std::process::id()));+ let lock = lock_file(&path).unwrap().unwrap();+ let mut command = Command::new("/bin/sleep");+ command.arg("30");+ hand_over(&mut command, &lock);+ let mut child = command.spawn().unwrap();+ drop(lock);+ assert!(lock_file(&path).unwrap().is_none());+ child.kill().unwrap();+ child.wait().unwrap();+ assert!(lock_file(&path).unwrap().is_some());+ std::fs::remove_file(&path).unwrap();+ }++ #[test]+ fn grant_probe_reads_only_the_requested_permission() {+ let stdout = br#"{"ok":true,"data":{"accessibility":{"state":"granted"},"screen_recording":{"state":"denied"}}}"#;+ assert!(reports_granted(stdout, "accessibility"));+ assert!(!reports_granted(stdout, "screen_recording"));+ assert!(!reports_granted(b"not json", "accessibility"));+ }+}diff --git a/crates/macos/src/system/permission_guide_bridge.m b/crates/macos/src/system/permission_guide_bridge.mnew file mode 100644index 000000000..858134f3b--- /dev/null+++ b/crates/macos/src/system/permission_guide_bridge.m@@ -0,0 +1,665 @@+#import <AppKit/AppKit.h>+#import <QuartzCore/QuartzCore.h>+#import <stdbool.h>+#import <stdint.h>+#import <sys/sysctl.h>++typedef bool (*ADGuideGranted)(uint8_t step);++static const uint8_t ADGuideAccessibility = 1;+static const uint8_t ADGuideScreenRecording = 2;+static const NSTimeInterval ADGuideLifetime = 600;+static const NSTimeInterval ADGuideDropRetry = 15;+static const CGFloat ADGuideWidth = 340;+static const CGFloat ADGuideGap = 16;+static const CGFloat ADGuideAuroraHeight = 130;+static const int ADGuideRayCount = 64;+static const CGFloat ADGuideIconSize = 48;+static const CGFloat ADGuideTileSize = 76;+static const CGFloat ADGuideGhostSize = 48;+static const int ADGuideMaxAncestors = 64;++static pid_t ADGuideParent(pid_t pid) {+ struct kinfo_proc info;+ size_t size = sizeof(info);+ int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};+ if (sysctl(mib, 4, &info, &size, NULL, 0) != 0 || size == 0) {+ return 0;+ }+ return info.kp_eproc.e_ppid;+}++bool agent_desktop_permission_guide_host(char *output, size_t capacity) {+ @autoreleasepool {+ pid_t pid = getpid();+ for (int depth = 0; depth < ADGuideMaxAncestors && pid > 1; depth++) {+ NSRunningApplication *app =+ [NSRunningApplication runningApplicationWithProcessIdentifier:pid];+ NSString *path = app.bundleURL.path;+ if ([path.pathExtension isEqualToString:@"app"]) {+ return [path getCString:output maxLength:capacity encoding:NSUTF8StringEncoding];+ }+ pid = ADGuideParent(pid);+ }+ return false;+ }+}++static NSRect ADGuideSettingsFrame(void) {+ NSArray<NSRunningApplication *> *apps =+ [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.systempreferences"];+ if (apps.count == 0) {+ return NSZeroRect;+ }+ pid_t pid = apps.firstObject.processIdentifier;+ CFArrayRef list = CGWindowListCopyWindowInfo(+ kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements, kCGNullWindowID);+ if (list == NULL) {+ return NSZeroRect;+ }+ NSRect best = NSZeroRect;+ for (NSDictionary *window in (__bridge NSArray *)list) {+ if ([window[(id)kCGWindowOwnerPID] intValue] != pid ||+ [window[(id)kCGWindowLayer] intValue] != 0) {+ continue;+ }+ CGRect bounds;+ if (!CGRectMakeWithDictionaryRepresentation(+ (__bridge CFDictionaryRef)window[(id)kCGWindowBounds], &bounds)) {+ continue;+ }+ if (bounds.size.width * bounds.size.height > best.size.width * best.size.height) {+ best = bounds;+ }+ }+ CFRelease(list);+ if (NSIsEmptyRect(best)) {+ return NSZeroRect;+ }+ CGFloat primaryHeight = NSScreen.screens.firstObject.frame.size.height;+ best.origin.y = primaryHeight - best.origin.y - best.size.height;+ return best;+}++static NSScreen *ADGuideScreenFor(NSRect frame) {+ NSPoint center = NSMakePoint(NSMidX(frame), NSMidY(frame));+ for (NSScreen *screen in NSScreen.screens) {+ if (NSPointInRect(center, screen.frame)) {+ return screen;+ }+ }+ return NSScreen.mainScreen;+}++@interface ADGuideIcon : NSImageView <NSDraggingSource>+@property(nonatomic, copy) NSURL *fileURL;+@property(nonatomic, copy) void (^onDrop)(void);+@end++@implementation ADGuideIcon+- (BOOL)acceptsFirstMouse:(NSEvent *)__unused event {+ return YES;+}++- (void)resetCursorRects {+ [self addCursorRect:self.bounds cursor:NSCursor.openHandCursor];+}++- (NSDragOperation)draggingSession:(NSDraggingSession *)__unused session+ sourceOperationMaskForDraggingContext:(NSDraggingContext)__unused context {+ return NSDragOperationCopy | NSDragOperationLink | NSDragOperationGeneric;+}++- (void)mouseDown:(NSEvent *)event {+ if (self.fileURL == nil) {+ return;+ }+ NSDraggingItem *item = [[NSDraggingItem alloc] initWithPasteboardWriter:self.fileURL];+ [item setDraggingFrame:self.bounds contents:self.image];+ [self beginDraggingSessionWithItems:@[ item ] event:event source:self];+}++- (void)draggingSession:(NSDraggingSession *)__unused session+ endedAtPoint:(NSPoint)__unused point+ operation:(NSDragOperation)operation {+ if (operation != NSDragOperationNone && self.onDrop != nil) {+ self.onDrop();+ }+}+@end++@interface ADGuidePanel : NSPanel+@end++@implementation ADGuidePanel+- (BOOL)canBecomeKeyWindow {+ return YES;+}++- (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)__unused screen {+ return frameRect;+}+@end++static NSColor *ADGuideGray(CGFloat white) {+ return [NSColor colorWithWhite:white alpha:1];+}++@interface ADGuideButton : NSButton+@end++@implementation ADGuideButton+- (instancetype)initWithTitle:(NSString *)title target:(id)target action:(SEL)action {+ self = [super initWithFrame:NSZeroRect];+ if (self == nil) {+ return nil;+ }+ self.target = target;+ self.action = action;+ self.bordered = NO;+ self.wantsLayer = YES;+ self.layer.backgroundColor = NSColor.blackColor.CGColor;+ self.layer.borderColor = ADGuideGray(0.45).CGColor;+ self.layer.borderWidth = 1;+ self.layer.cornerRadius = 8;+ self.attributedTitle = [[NSAttributedString alloc]+ initWithString:title+ attributes:@{+ NSForegroundColorAttributeName : NSColor.whiteColor,+ NSFontAttributeName : [NSFont systemFontOfSize:13 weight:NSFontWeightSemibold],+ }];+ [self.widthAnchor constraintEqualToConstant:104].active = YES;+ [self.heightAnchor constraintEqualToConstant:34].active = YES;+ return self;+}++- (BOOL)acceptsFirstMouse:(NSEvent *)__unused event {+ return YES;+}++- (void)mouseDown:(NSEvent *)__unused event {+ [self sendAction:self.action to:self.target];+}+@end++@interface ADGuideAurora : NSView+@property(nonatomic) CGFloat builtWidth;+@end++@implementation ADGuideAurora+- (instancetype)init {+ self = [super initWithFrame:NSZeroRect];+ if (self != nil) {+ self.layer = [CALayer layer];+ self.wantsLayer = YES;+ self.layerUsesCoreImageFilters = YES;+ }+ return self;+}++- (NSView *)hitTest:(NSPoint)__unused point {+ return nil;+}++- (void)layout {+ [super layout];+ CGRect bounds = NSRectToCGRect(self.bounds);+ if (bounds.size.width <= 0 || bounds.size.width == self.builtWidth) {+ return;+ }+ self.builtWidth = bounds.size.width;+ self.layer.sublayers = nil;+ BOOL still = NSWorkspace.sharedWorkspace.accessibilityDisplayShouldReduceMotion;+ CAGradientLayer *colors = [CAGradientLayer layer];+ colors.frame = bounds;+ colors.startPoint = CGPointMake(0, 0.5);+ colors.endPoint = CGPointMake(1, 0.5);+ colors.colors = @[+ (id)[NSColor colorWithRed:1.00 green:0.13 blue:0.30 alpha:1].CGColor,+ (id)[NSColor colorWithRed:0.93 green:0.20 blue:0.85 alpha:1].CGColor,+ (id)[NSColor colorWithRed:0.52 green:0.27 blue:1.00 alpha:1].CGColor,+ (id)[NSColor colorWithRed:0.20 green:0.42 blue:1.00 alpha:1].CGColor,+ (id)[NSColor colorWithRed:0.35 green:0.70 blue:1.00 alpha:1].CGColor,+ ];+ CALayer *rays = [CALayer layer];+ rays.frame = bounds;+ CGFloat step = bounds.size.width / ADGuideRayCount;+ for (int index = 0; index < ADGuideRayCount; index++) {+ [rays addSublayer:[self rayAt:index * step width:step * 1.8 height:bounds.size.height still:still]];+ }+ colors.mask = rays;+ [self.layer addSublayer:colors];+ CIFilter *blur = [CIFilter filterWithName:@"CIGaussianBlur"];+ [blur setValue:@3 forKey:kCIInputRadiusKey];+ self.layer.filters = blur == nil ? nil : @[ blur ];+ if (!still) {+ CABasicAnimation *drift = [CABasicAnimation animationWithKeyPath:@"locations"];+ drift.fromValue = @[ @0.0, @0.25, @0.5, @0.75, @1.0 ];+ drift.toValue = @[ @0.0, @0.32, @0.58, @0.8, @1.0 ];+ drift.duration = 6;+ drift.autoreverses = YES;+ drift.repeatCount = HUGE_VALF;+ drift.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];+ [colors addAnimation:drift forKey:@"drift"];+ }+}++- (CALayer *)rayAt:(CGFloat)x width:(CGFloat)width height:(CGFloat)height still:(BOOL)still {+ CAGradientLayer *ray = [CAGradientLayer layer];+ ray.anchorPoint = CGPointMake(0.5, 0);+ ray.bounds = CGRectMake(0, 0, width, height);+ ray.position = CGPointMake(x + width / 4, 0);+ ray.colors = @[ (id)NSColor.whiteColor.CGColor, (id)[NSColor colorWithWhite:1 alpha:0].CGColor ];+ ray.startPoint = CGPointMake(0.5, 0);+ ray.endPoint = CGPointMake(0.5, 1);+ CGFloat low = 0.25 + arc4random_uniform(40) / 100.0;+ CGFloat high = MIN(0.92, low + 0.2 + arc4random_uniform(35) / 100.0);+ ray.opacity = 0.55 + arc4random_uniform(45) / 100.0;+ ray.transform = CATransform3DMakeScale(1, high, 1);+ if (!still) {+ CABasicAnimation *flicker = [CABasicAnimation animationWithKeyPath:@"transform.scale.y"];+ flicker.fromValue = @(low);+ flicker.toValue = @(high);+ flicker.duration = 1.2 + arc4random_uniform(220) / 100.0;+ flicker.beginTime = CACurrentMediaTime() - arc4random_uniform(300) / 100.0;+ flicker.autoreverses = YES;+ flicker.repeatCount = HUGE_VALF;+ flicker.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];+ [ray addAnimation:flicker forKey:@"flicker"];+ }+ return ray;+}+@end++@interface ADGuide : NSObject+@property(nonatomic, strong) NSPanel *panel;+@property(nonatomic, strong) NSView *card;+@property(nonatomic, strong) NSWindow *stage;+@property(nonatomic, strong) CALayer *carrier;+@property(nonatomic, strong) NSTextField *stepLabel;+@property(nonatomic, strong) NSTextField *titleLabel;+@property(nonatomic, strong) NSTextField *bodyLabel;+@property(nonatomic, strong) NSTextField *captionLabel;+@property(nonatomic, strong) ADGuideIcon *icon;+@property(nonatomic, strong) NSImage *hostImage;+@property(nonatomic, copy) NSString *hostName;+@property(nonatomic, strong) NSDate *deadline;+@property(nonatomic, strong) NSDate *droppedAt;+@property(nonatomic) BOOL coversScreenRecording;+@property(nonatomic) ADGuideGranted granted;+@property(nonatomic) uint8_t remaining;+@property(nonatomic) uint8_t current;+@property(nonatomic) int total;+@property(nonatomic) int completed;+@property(nonatomic) BOOL advancing;+@property(nonatomic) BOOL probing;+@property(nonatomic) NSRect lastSettings;+@end++@implementation ADGuide+- (instancetype)initWithSteps:(uint8_t)steps host:(NSString *)hostPath granted:(ADGuideGranted)granted {+ self = [super init];+ if (self == nil) {+ return nil;+ }+ _granted = granted;+ _remaining = steps;+ _coversScreenRecording = (steps & ADGuideScreenRecording) != 0;+ _total = ((steps & ADGuideAccessibility) ? 1 : 0) + ((steps & ADGuideScreenRecording) ? 1 : 0);+ _deadline = [NSDate dateWithTimeIntervalSinceNow:ADGuideLifetime];+ _hostImage = [NSWorkspace.sharedWorkspace iconForFile:hostPath];+ _hostName = [[NSFileManager.defaultManager displayNameAtPath:hostPath] stringByDeletingPathExtension];+ [self buildPanel:[NSURL fileURLWithPath:hostPath]];+ [self buildStage];+ return self;+}++- (void)buildPanel:(NSURL *)hostURL {+ self.panel = [[ADGuidePanel alloc] initWithContentRect:NSMakeRect(0, 0, ADGuideWidth, 300)+ styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel+ backing:NSBackingStoreBuffered+ defer:NO];+ self.panel.level = NSFloatingWindowLevel;+ self.panel.opaque = NO;+ self.panel.backgroundColor = NSColor.clearColor;+ self.panel.hasShadow = YES;+ self.panel.appearance = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];+ self.panel.movableByWindowBackground = YES;+ self.panel.hidesOnDeactivate = NO;+ self.panel.collectionBehavior =+ NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary;+ [self buildFrame];+ self.stepLabel = [NSTextField labelWithString:@""];+ self.stepLabel.font = [NSFont monospacedSystemFontOfSize:10.5 weight:NSFontWeightMedium];+ self.stepLabel.textColor = ADGuideGray(0.56);+ self.titleLabel = [NSTextField labelWithString:@""];+ self.titleLabel.font = [NSFont systemFontOfSize:22 weight:NSFontWeightBold];+ self.titleLabel.textColor = NSColor.whiteColor;+ self.icon = [[ADGuideIcon alloc] init];+ self.icon.fileURL = hostURL;+ self.icon.image = self.hostImage;+ self.icon.imageScaling = NSImageScaleProportionallyUpOrDown;+ [self.icon.widthAnchor constraintEqualToConstant:ADGuideIconSize].active = YES;+ [self.icon.heightAnchor constraintEqualToConstant:ADGuideIconSize].active = YES;+ __weak ADGuide *weakSelf = self;+ self.icon.onDrop = ^{+ [weakSelf showDropped];+ };+ self.captionLabel = [NSTextField labelWithString:[NSString stringWithFormat:@"Drag %@", self.hostName]];+ self.captionLabel.font = [NSFont monospacedSystemFontOfSize:10.5 weight:NSFontWeightRegular];+ self.captionLabel.textColor = ADGuideGray(0.56);+ self.bodyLabel = [NSTextField wrappingLabelWithString:@""];+ self.bodyLabel.alignment = NSTextAlignmentCenter;+ self.bodyLabel.preferredMaxLayoutWidth = ADGuideWidth - 56;+ self.bodyLabel.textColor = ADGuideGray(0.86);+ self.bodyLabel.font = [NSFont systemFontOfSize:13 weight:NSFontWeightMedium];+ NSButton *close = [[ADGuideButton alloc] initWithTitle:@"Not Now" target:self action:@selector(finish)];+ NSView *tile = [self tileFor:self.icon];+ NSStackView *stack = [NSStackView stackViewWithViews:@[+ tile, self.captionLabel, self.stepLabel, self.titleLabel, self.bodyLabel, close+ ]];+ stack.orientation = NSUserInterfaceLayoutOrientationVertical;+ stack.alignment = NSLayoutAttributeCenterX;+ stack.spacing = 8;+ stack.edgeInsets = NSEdgeInsetsMake(30, 28, 52, 28);+ [stack setCustomSpacing:20 afterView:self.captionLabel];+ [stack setCustomSpacing:6 afterView:self.stepLabel];+ [stack setCustomSpacing:10 afterView:self.titleLabel];+ [stack setCustomSpacing:30 afterView:self.bodyLabel];+ stack.translatesAutoresizingMaskIntoConstraints = NO;+ [self.card addSubview:stack];+ [NSLayoutConstraint activateConstraints:@[+ [stack.leadingAnchor constraintEqualToAnchor:self.card.leadingAnchor],+ [stack.trailingAnchor constraintEqualToAnchor:self.card.trailingAnchor],+ [stack.topAnchor constraintEqualToAnchor:self.card.topAnchor],+ [stack.bottomAnchor constraintEqualToAnchor:self.card.bottomAnchor],+ [stack.widthAnchor constraintEqualToConstant:ADGuideWidth],+ ]];+}++- (void)buildFrame {+ self.card = [[NSView alloc] init];+ self.card.wantsLayer = YES;+ self.card.layer.backgroundColor = NSColor.blackColor.CGColor;+ self.card.layer.cornerRadius = 14;+ self.card.layer.masksToBounds = YES;+ self.card.layer.borderWidth = 1;+ self.card.layer.borderColor = ADGuideGray(0.16).CGColor;+ self.panel.contentView = self.card;+ ADGuideAurora *aurora = [[ADGuideAurora alloc] init];+ aurora.translatesAutoresizingMaskIntoConstraints = NO;+ [self.card addSubview:aurora];+ [NSLayoutConstraint activateConstraints:@[+ [aurora.leadingAnchor constraintEqualToAnchor:self.card.leadingAnchor],+ [aurora.trailingAnchor constraintEqualToAnchor:self.card.trailingAnchor],+ [aurora.bottomAnchor constraintEqualToAnchor:self.card.bottomAnchor],+ [aurora.heightAnchor constraintEqualToConstant:ADGuideAuroraHeight],+ ]];+}++- (NSView *)tileFor:(NSView *)icon {+ NSView *tile = [[NSView alloc] init];+ tile.wantsLayer = YES;+ tile.layer.backgroundColor = NSColor.blackColor.CGColor;+ tile.layer.cornerRadius = 18;+ tile.layer.borderWidth = 1.5;+ tile.layer.borderColor = ADGuideGray(0.85).CGColor;+ icon.translatesAutoresizingMaskIntoConstraints = NO;+ [tile addSubview:icon];+ [NSLayoutConstraint activateConstraints:@[+ [tile.widthAnchor constraintEqualToConstant:ADGuideTileSize],+ [tile.heightAnchor constraintEqualToConstant:ADGuideTileSize],+ [icon.centerXAnchor constraintEqualToAnchor:tile.centerXAnchor],+ [icon.centerYAnchor constraintEqualToAnchor:tile.centerYAnchor],+ ]];+ return tile;+}++- (void)buildStage {+ self.stage = [[NSWindow alloc] initWithContentRect:NSZeroRect+ styleMask:NSWindowStyleMaskBorderless+ backing:NSBackingStoreBuffered+ defer:NO];+ self.stage.opaque = NO;+ self.stage.backgroundColor = NSColor.clearColor;+ self.stage.ignoresMouseEvents = YES;+ self.stage.hasShadow = NO;+ self.stage.level = NSStatusWindowLevel;+ self.stage.collectionBehavior = self.panel.collectionBehavior;+ self.stage.contentView.wantsLayer = YES;+ self.carrier = [CALayer layer];+ self.carrier.bounds = CGRectMake(0, 0, ADGuideGhostSize, ADGuideGhostSize);+ self.carrier.opacity = 0;+ CALayer *ghost = [CALayer layer];+ ghost.frame = self.carrier.bounds;+ ghost.contents = self.hostImage;+ ghost.opacity = 0.85;+ CALayer *hand = [CALayer layer];+ NSImage *handImage = NSCursor.closedHandCursor.image;+ hand.contents = handImage;+ hand.frame = CGRectMake(ADGuideGhostSize / 2, ADGuideGhostSize / 2 - handImage.size.height,+ handImage.size.width, handImage.size.height);+ [self.carrier addSublayer:ghost];+ [self.carrier addSublayer:hand];+ [self.stage.contentView.layer addSublayer:self.carrier];+}++- (void)start {+ [self beginStep];+ [self.panel center];+ [self follow:ADGuideSettingsFrame()];+ [self.panel orderFrontRegardless];+ [NSNotificationCenter.defaultCenter addObserverForName:NSWindowDidMoveNotification+ object:self.panel+ queue:nil+ usingBlock:^(NSNotification *__unused note) {+ if (!NSIsEmptyRect(self.lastSettings)) {+ [self animateInto:self.lastSettings];+ }+ }];+ [NSTimer scheduledTimerWithTimeInterval:1+ repeats:YES+ block:^(NSTimer *__unused timer) {+ [self tick];+ }];+}++- (void)beginStep {+ self.current = (self.remaining & ADGuideAccessibility) ? ADGuideAccessibility : ADGuideScreenRecording;+ BOOL accessibility = self.current == ADGuideAccessibility;+ self.stepLabel.stringValue =+ [NSString stringWithFormat:@"STEP %d OF %d", self.completed + 1, self.total];+ self.titleLabel.stringValue = accessibility ? @"Allow Accessibility" : @"Allow Screen Recording";+ [self showInstructions];+ NSString *pane = accessibility ? @"Privacy_Accessibility" : @"Privacy_ScreenCapture";+ NSOperatingSystemVersion ventura = {13, 0, 0};+ NSString *anchor = [NSProcessInfo.processInfo isOperatingSystemAtLeastVersion:ventura]+ ? @"x-apple.systempreferences:com.apple.settings.PrivacySecurity.extension?"+ : @"x-apple.systempreferences:com.apple.preference.security?";+ NSString *link = [anchor stringByAppendingString:pane];+ [NSWorkspace.sharedWorkspace openURL:[NSURL URLWithString:link]];+ self.advancing = NO;+}++- (void)showInstructions {+ self.bodyLabel.stringValue = [NSString stringWithFormat:@"Drag %@ into the list.", self.hostName];+ self.icon.image = self.hostImage;+ self.icon.contentTintColor = nil;+ self.captionLabel.hidden = NO;+ self.droppedAt = nil;+ self.lastSettings = NSZeroRect;+ [self resizePanel];+}++- (void)retryStalledDrop {+ if (self.droppedAt != nil && [self.droppedAt timeIntervalSinceNow] < -ADGuideDropRetry) {+ [self showInstructions];+ }+}++- (void)resizePanel {+ NSRect frame = self.panel.frame;+ NSSize size = self.card.fittingSize;+ frame.origin.y += frame.size.height - size.height;+ frame.size = size;+ [self.panel setFrame:frame display:YES];+}++- (void)tick {+ if ([self.deadline timeIntervalSinceNow] <= 0) {+ [self finish];+ return;+ }+ [self follow:ADGuideSettingsFrame()];+ if (self.advancing || self.probing) {+ return;+ }+ self.probing = YES;+ uint8_t step = self.current;+ ADGuideGranted granted = self.granted;+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{+ bool done = granted(step);+ dispatch_async(dispatch_get_main_queue(), ^{+ self.probing = NO;+ if (self.advancing || step != self.current) {+ return;+ }+ if (done) {+ [self advance];+ } else {+ [self retryStalledDrop];+ }+ });+ });+}++- (void)advance {+ self.advancing = YES;+ [self showGranted];+ self.remaining &= (uint8_t)~self.current;+ self.completed += 1;+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ if (self.remaining == 0) {+ [self showDone];+ } else {+ [self beginStep];+ }+ });+}++- (void)follow:(NSRect)settings {+ if (NSEqualRects(settings, self.lastSettings)) {+ return;+ }+ self.lastSettings = settings;+ if (NSIsEmptyRect(settings)) {+ [self.stage orderOut:nil];+ return;+ }+ NSRect area = ADGuideScreenFor(settings).visibleFrame;+ NSRect frame = self.panel.frame;+ frame.origin.x = NSMaxX(settings) + ADGuideGap;+ if (NSMaxX(frame) > NSMaxX(area)) {+ frame.origin.x = NSMinX(settings) - ADGuideGap - frame.size.width;+ }+ frame.origin.x = MAX(NSMinX(area), MIN(frame.origin.x, NSMaxX(area) - frame.size.width));+ frame.origin.y = MAX(NSMinY(area), NSMaxY(settings) - frame.size.height);+ [self.panel setFrame:frame display:YES];+ [self animateInto:settings];+}++- (void)animateInto:(NSRect)settings {+ if (self.captionLabel.isHidden || NSWorkspace.sharedWorkspace.accessibilityDisplayShouldReduceMotion) {+ [self.stage orderOut:nil];+ return;+ }+ NSRect screen = ADGuideScreenFor(settings).frame;+ [self.stage setFrame:screen display:NO];+ NSRect iconRect = [self.panel convertRectToScreen:[self.icon convertRect:self.icon.bounds toView:nil]];+ NSPoint from = NSMakePoint(NSMidX(iconRect) - screen.origin.x, NSMidY(iconRect) - screen.origin.y);+ NSPoint to = NSMakePoint(NSMinX(settings) + settings.size.width * 0.62 - screen.origin.x,+ NSMinY(settings) + settings.size.height * 0.55 - screen.origin.y);+ CAKeyframeAnimation *move = [CAKeyframeAnimation animationWithKeyPath:@"position"];+ move.values = @[+ [NSValue valueWithPoint:from], [NSValue valueWithPoint:from], [NSValue valueWithPoint:to],+ [NSValue valueWithPoint:to]+ ];+ move.keyTimes = @[ @0, @0.15, @0.7, @1 ];+ move.timingFunctions = @[+ [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear],+ [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],+ [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear],+ ];+ CAKeyframeAnimation *fade = [CAKeyframeAnimation animationWithKeyPath:@"opacity"];+ fade.values = @[ @0, @1, @1, @0 ];+ fade.keyTimes = @[ @0, @0.1, @0.8, @1 ];+ CAKeyframeAnimation *lift = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];+ lift.values = @[ @1, @1.12, @1.12, @0.9 ];+ lift.keyTimes = @[ @0, @0.15, @0.7, @1 ];+ CAAnimationGroup *group = [CAAnimationGroup animation];+ group.animations = @[ move, fade, lift ];+ group.duration = 2.8;+ group.repeatCount = HUGE_VALF;+ [self.carrier removeAllAnimations];+ [self.carrier addAnimation:group forKey:@"guide"];+ [self.stage orderFrontRegardless];+}++- (void)showDropped {+ self.droppedAt = [NSDate date];+ self.captionLabel.hidden = YES;+ [self.stage orderOut:nil];+ self.bodyLabel.stringValue =+ @"Confirm with Touch ID or your password.";+ [self resizePanel];+}++- (void)showGranted {+ [self.stage orderOut:nil];+ self.captionLabel.hidden = YES;+#pragma clang diagnostic push+#pragma clang diagnostic ignored "-Wunguarded-availability-new"+ if ([NSImage respondsToSelector:@selector(imageWithSystemSymbolName:accessibilityDescription:)]) {+ NSImage *check = [NSImage imageWithSystemSymbolName:@"checkmark.circle.fill"+ accessibilityDescription:@"Granted"];+ NSImageSymbolConfiguration *config =+ [NSImageSymbolConfiguration configurationWithPointSize:48 weight:NSFontWeightRegular];+ self.icon.image = [check imageWithSymbolConfiguration:config];+ self.icon.contentTintColor = NSColor.systemGreenColor;+ }+#pragma clang diagnostic pop+ self.bodyLabel.stringValue = @"Done.";+ [self resizePanel];+}++- (void)showDone {+ self.stepLabel.stringValue = @"";+ self.titleLabel.stringValue = @"You are all set";+ self.bodyLabel.stringValue = self.coversScreenRecording+ ? [NSString stringWithFormat:@"Quit and reopen %@ before agent-desktop takes screenshots.", self.hostName]+ : @"agent-desktop can now see and use your apps.";+ [self resizePanel];+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{+ [self finish];+ });+}++- (void)finish {+ [NSApp terminate:nil];+}+@end++int agent_desktop_permission_guide_run(uint8_t steps, const char *host_path, ADGuideGranted granted) {+ @autoreleasepool {+ NSString *host = host_path == NULL ? nil : [NSString stringWithUTF8String:host_path];+ if (steps == 0 || host.length == 0 || granted == NULL) {+ return 1;+ }+ NSApplication *app = NSApplication.sharedApplication;+ [app setActivationPolicy:NSApplicationActivationPolicyAccessory];+ ADGuide *guide = [[ADGuide alloc] initWithSteps:steps host:host granted:granted];+ [guide start];+ [app run];+ return 0;+ }+}diff --git a/docs/phases.md b/docs/phases.mdindex 962600ae6..80415819a 100644--- a/docs/phases.md+++ b/docs/phases.md@@ -337,6 +337,7 @@ crates/macos/src/- Screen Recording: platform screen-capture preflight/request path- Automation: probed against System Events without prompting for `permissions` / `status`; `permissions --request` may prompt through the bounded isolated permission helper. The probe is truthful (Phase 1.6 U4) rather than optimistically assumed.- `status`, `permissions`, preflight, and `batch` share the same report; `permissions --request` invokes the request path+- `permissions --guide` starts a detached copy of the binary as an AppKit accessory process (the cursor-overlay pattern; no separate app). It covers Accessibility and Screen Recording, never calls a prompt API, and opens System Settings by deep link (`com.apple.settings.PrivacySecurity.extension` on macOS 13+, `com.apple.preference.security` before; on macOS 26 the older form lands on the Privacy & Security root, not the list). A floating panel beside the Settings window shows the launching app (the nearest `.app` ancestor of the process, else the binary) as a draggable file URL, and an animated hand drags its icon into the list on a loop; the user does the real drag, because the prompt APIs do not add a new app to either list. Each step polls the grant once a second with a fresh `permissions` subprocess, then advances. A drop that adds no grant within 15 seconds (for example, a cancelled password prompt) brings the drag instructions and the animation back. The done screen tells the user to reopen the launching app when Screen Recording was a step, because a running process does not pick up that grant. One guide runs at a time, "Not Now" closes it, and it exits after ten minutes. The full step sequence, the single-instance lock, "Not Now" and the drop retry were driven on macOS 26 only. Other platforms return `PLATFORM_NOT_SUPPORTED`.**Notification management:**- Open Notification Center through the guarded System Events path to Control Center's Clock item; authorization is probed without prompting before the Apple Event is sent@@ -2961,7 +2962,7 @@ All Phase 2/3 pins above were recorded at 2026-04 research time; re-verify again| ID | Risk | Likelihood | Impact | Mitigation ||----|------|------------|--------|------------|-| R1 | macOS TCC friction deters adoption | High | High | Clear first-run guidance. Detect before any op. One-command setup: `permissions --request`. |+| R1 | macOS TCC friction deters adoption | High | High | Clear first-run guidance. Detect before any op. One-command setup: `permissions --request`, or `permissions --guide` for an on-screen walkthrough of System Settings. || R2 | Electron/Chromium a11y tree gaps on legacy builds | Medium | Medium | Chromium 138+ (Aug 2025) auto-enables native UIA for UIA clients. Detect Chromium windows; re-read past a settle before judging a tree thin, since a first read lands on the pre-activation shell; print `--force-renderer-accessibility` guidance for pre-138/pinned builds or trees still thin afterwards. || R3 | Custom-rendered UIs invisible to a11y | Medium | High | Phase 5 stretch: vision fallback. Short-term: document limitation in README and skills. || R4 | Wayland a11y gaps | Medium | Medium | Focus on GNOME (best AT-SPI2 support). Prefer AT-SPI actions over coordinate input. Document gaps. |diff --git a/skills/agent-desktop-macos/SKILL.md b/skills/agent-desktop-macos/SKILL.mdindex 59b258789..781b4bd94 100644--- a/skills/agent-desktop-macos/SKILL.md+++ b/skills/agent-desktop-macos/SKILL.md@@ -28,12 +28,12 @@ Read the core skill first (`agent-desktop skills get desktop`) for the observe,1. Run `agent-desktop status`. It includes the permission report and the state root.2. Run `agent-desktop permissions`. It reports `accessibility`, `screen_recording` and `automation`. Each is `granted`, `denied`, `not_required` or `unknown`. A denied entry carries a `suggestion`.-3. If a permission is denied, run `agent-desktop permissions --request`. It shows the system prompt.+3. If a permission is denied, run `agent-desktop permissions --guide`. It opens the correct System Settings page and a small panel next to it. The panel shows the launching app's icon and an animation of the drag into the list. The user drags the icon into the list and confirms with Touch ID or a password, which turns the permission on; the panel moves to the next missing permission by itself. The command returns at once with `"guide": "started"`, `"already_running"` or `"not_needed"`. `agent-desktop permissions --request` shows the system prompts instead.4. Open System Settings > Privacy & Security > Accessibility. Turn on the launching app.5. Restart the launching app. A running process does not pick up a new grant.6. Run `agent-desktop snapshot --app Finder -i` to confirm.-`permissions` does not prompt. `permissions --request` can prompt, including for Automation. Automation reports `unknown` when macOS would need to prompt.+`permissions` does not prompt. `permissions --request` can prompt, including for Automation. `permissions --guide` does not prompt and covers Accessibility and Screen Recording only. Automation reports `unknown` when macOS would need to prompt.## What differs on macOSdiff --git a/skills/agent-desktop-macos/references/troubleshooting.md b/skills/agent-desktop-macos/references/troubleshooting.mdindex a642e370d..2b1b8b440 100644--- a/skills/agent-desktop-macos/references/troubleshooting.md+++ b/skills/agent-desktop-macos/references/troubleshooting.md@@ -9,8 +9,8 @@ Each entry is a symptom, its cause, and the fix. Read `error.code`, `error.sugge**Cause.** The app that launched agent-desktop has no Accessibility permission (or Screen Recording, for `screenshot` and `session start --screenshots`). The grant belongs to the launching app, not to the shell. A new launcher, such as a different terminal or an IDE, needs its own grant.**Fix.**-1. Run `agent-desktop permissions --request`.-2. Open System Settings > Privacy & Security > Accessibility (or Screen Recording).+1. Run `agent-desktop permissions --guide`. It opens the correct page in System Settings with a panel that shows what to drag. Without it, run `agent-desktop permissions --request` and open the page yourself.+2. In System Settings > Privacy & Security > Accessibility (or Screen Recording), drag the launching app into the list if it is not there.3. Turn on the launching app. If the built `agent-desktop` binary is listed on its own, turn it on too.4. Restart the launching app.5. Run `agent-desktop permissions` to confirm `granted`.diff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.mdindex 77b9f85b2..d28e40fde 100644--- a/skills/agent-desktop/references/commands-system.md+++ b/skills/agent-desktop/references/commands-system.md@@ -182,7 +182,7 @@ Multi-agent cursors (macOS and Windows): start with `session start --cursor --mu## status, permissions, version- `status` returns adapter health, platform, the permission report, `supported_surfaces`, the latest snapshot (`snapshot_id`, `ref_count`), `session_id`, `tracing`, `state_root`.-- `permissions` returns `accessibility`, `screen_recording` and `automation`, each as `{ "state": "granted" | "denied" | "not_required" | "unknown" }`, with a `suggestion` when denied. It is cached per process. `permissions --request` asks the OS to prompt, through a bounded isolated helper so a stalled prompt cannot hang the command. It is the only path that prompts. What to grant is in the platform skill.+- `permissions` returns `accessibility`, `screen_recording` and `automation`, each as `{ "state": "granted" | "denied" | "not_required" | "unknown" }`, with a `suggestion` when denied. It is cached per process. `permissions --request` asks the OS to prompt, through a bounded isolated helper so a stalled prompt cannot hang the command. It is the only path that prompts. On macOS, `permissions --guide` opens System Settings at the missing permission with an on-screen guide, adds `"guide": "started" | "already_running" | "not_needed"` to the result, and returns without waiting. Other platforms return `PLATFORM_NOT_SUPPORTED` for `--guide`. What to grant is in the platform skill.- `version` returns `{ version, target, os }`.## skillsdiff --git a/src/cli/mod.rs b/src/cli/mod.rsindex eb61abe0d..5e85d5856 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -259,6 +259,13 @@ impl Commands {self.metadata().post_action_wait}+ #[cfg(target_os = "macos")]+ /// The permission guide offers the caller's own app to drag into the+ /// Privacy list, so it cannot run inside a detached command host.+ pub(crate) fn needs_caller_process(&self) -> bool {+ matches!(self, Self::Permissions(args) if args.guide)+ }+pub(crate) fn is_mutating(&self) -> bool {match self {Self::Click(_)diff --git a/src/cli/wait_for_cli_tests.rs b/src/cli/wait_for_cli_tests.rsindex cdcdb0736..ebb04ff4a 100644--- a/src/cli/wait_for_cli_tests.rs+++ b/src/cli/wait_for_cli_tests.rs@@ -139,6 +139,15 @@ fn typed_metadata_couples_name_and_wait_support_to_each_variant() {assert!(!find.supports_post_action_wait());}+#[cfg(target_os = "macos")]+#[test]+fn only_the_permission_guide_stays_in_the_caller_process() {+ assert!(command(&["permissions", "--guide"]).needs_caller_process());+ assert!(!command(&["permissions"]).needs_caller_process());+ assert!(!command(&["permissions", "--request"]).needs_caller_process());+ assert!(!command(&["click", "@e1"]).needs_caller_process());+}+#[test]fn mutation_metadata_distinguishes_read_only_and_file_writing_forms() {assert!(command(&["click", "@e1"]).is_mutating());diff --git a/src/cli_args/system.rs b/src/cli_args/system.rsindex a42959bb8..836ea32e8 100644--- a/src/cli_args/system.rs+++ b/src/cli_args/system.rs@@ -314,6 +314,12 @@ pub(crate) struct PermissionsArgs {)]#[serde(default)]pub request: bool,+ #[arg(+ long,+ help = "Open System Settings with an on-screen guide for granting the missing permissions (macOS)"+ )]+ #[serde(default)]+ pub guide: bool,}#[cfg(test)]diff --git a/src/dispatch/system.rs b/src/dispatch/system.rsindex 9d9528a35..26d24e090 100644--- a/src/dispatch/system.rs+++ b/src/dispatch/system.rs@@ -55,6 +55,7 @@ pub(super) fn permissions(permissions_command::execute_with_report(permissions_command::PermissionsArgs {request: args.request,+ guide: args.guide,},adapter,permission_report,diff --git a/src/main.rs b/src/main.rsindex 18dd3c007..91ffe6a07 100644--- a/src/main.rs+++ b/src/main.rs@@ -45,6 +45,10 @@ fn main() -> ExitCode {return exit_code;}#[cfg(target_os = "macos")]+ if let Some(exit_code) = agent_desktop_macos::permission_guide_from_env() {+ return ExitCode::from(exit_code);+ }+ #[cfg(target_os = "macos")]if command_host::is_host_process() {init_tracing(false);return match command_host::run() {@@ -116,7 +120,9 @@ fn run() -> ExitCode {let cmd_name = cmd.name();#[cfg(target_os = "macos")]- if std::env::var("AGENT_DESKTOP_INTERNAL_HOST_CLIENT").as_deref() == Ok("1") {+ if std::env::var("AGENT_DESKTOP_INTERNAL_HOST_CLIENT").as_deref() == Ok("1")+ && !cmd.needs_caller_process()+ {return match command_host::forward(&cli, &cmd) {Ok(response) => match emit_response(&response) {Err(error) => report_output_failure(error),