Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
fix: make the permission guide offer the launching app, see each grant, and leave no stale host (#330)
Lahfire378cf1a6896
diff --git a/crates/core/src/response/adapter_error.rs b/crates/core/src/response/adapter_error.rsindex 762f28701..5f24244f9 100644--- a/crates/core/src/response/adapter_error.rs+++ b/crates/core/src/response/adapter_error.rs@@ -221,7 +221,7 @@ impl AdapterError {"Accessibility permission not granted",).with_suggestion(- "Open System Settings > Privacy & Security > Accessibility and add the app that launches agent-desktop",+ "Run agent-desktop permissions to see which permission is denied and how to grant it. On macOS, agent-desktop permissions --guide opens System Settings with a guide",).with_disposition(DeliverySemantics::not_delivered())}diff --git a/crates/macos/src/system/permissions/mod.rs b/crates/macos/src/system/permissions/mod.rsindex 734daa817..a54a82529 100644--- a/crates/macos/src/system/permissions/mod.rs+++ b/crates/macos/src/system/permissions/mod.rs@@ -1,7 +1,7 @@use agent_desktop_core::{AdapterError, Deadline, PermissionReport, PermissionState};-const ACCESSIBILITY_SUGGESTION: &str = "Open System Settings > Privacy & Security > Accessibility and add the app that launches agent-desktop, such as Terminal, iTerm, or Codex. If macOS lists the built binary separately, add that binary too.";-const SCREEN_RECORDING_SUGGESTION: &str = "Open System Settings > Privacy & Security > Screen Recording and add the app that launches agent-desktop, such as Terminal, iTerm, or Codex. If macOS lists the built binary separately, add that binary too.";+const ACCESSIBILITY_SUGGESTION: &str = "Run agent-desktop permissions --guide. It opens System Settings > Privacy & Security > Accessibility (Device Control and Data Access on macOS 27 and later) with a guide that shows which app to drag into the list: the app that launches agent-desktop, such as Terminal, iTerm, or Codex. If macOS lists the built binary separately, add that binary too.";+const SCREEN_RECORDING_SUGGESTION: &str = "Run agent-desktop permissions --guide. It opens System Settings > Privacy & Security > Screen Recording with a guide that shows which app to drag into the list: the app that launches agent-desktop, such as Terminal, iTerm, or Codex. If macOS lists the built binary separately, add that binary too.";pub(crate) const AUTOMATION_SUGGESTION: &str = "Open System Settings > Privacy & Security > Automation and allow the app that launches agent-desktop, such as Terminal, iTerm, or Codex, to control System Events. If macOS lists the built binary separately, add that binary too.";const NO_ERR: i32 = 0;diff --git a/crates/macos/src/system/permissions/permission_guide.rs b/crates/macos/src/system/permissions/permission_guide.rsindex b4228fb5d..030b2523d 100644--- a/crates/macos/src/system/permissions/permission_guide.rs+++ b/crates/macos/src/system/permissions/permission_guide.rs@@ -1,5 +1,5 @@use agent_desktop_core::AdapterError;-use std::ffi::{CStr, CString, c_char};+use std::ffi::{CString, c_char};use std::fs::File;use std::os::fd::AsRawFd;use std::os::unix::process::CommandExt;@@ -10,11 +10,12 @@ 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 PROBE_ENV: &str = "AGENT_DESKTOP_PERMISSION_GUIDE_PROBE";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 MAX_ANCESTORS: usize = 64;const COMMAND_HOST_ENVS: [&str; 3] = ["AGENT_DESKTOP_INTERNAL_COMMAND_HOST","AGENT_DESKTOP_INTERNAL_HOST_SOCKET",@@ -66,6 +67,9 @@ pub(crate) fn start() -> Result<&'static str, AdapterError> {}pub fn entry_from_env() -> Option<u8> {+ if let Ok(step) = std::env::var(PROBE_ENV) {+ return Some(if probe(&step) { 0 } else { 1 });+ }let steps = std::env::var(STEPS_ENV).ok()?;Some(if run_child(&steps) { 0 } else { 1 })}@@ -87,28 +91,31 @@ fn run_child(steps: &str) -> bool {unsafe { agent_desktop_permission_guide_run(steps, host.as_ptr(), granted) == 0 }}+/// Each poll runs in a fresh process: a long-lived process keeps the Screen+/// Recording answer it read at launch, and the command host may belong to+/// another terminal app.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);+ command+ .env_remove(STEPS_ENV)+ .env(PROBE_ENV, step.to_string());crate::system::process::run_with_deadline(&mut command,"macOS permission guide probe",Instant::now() + PROBE_TIMEOUT,)- .is_ok_and(|output| reports_granted(&output.stdout, key))+ .is_ok_and(|output| output.status.success())}-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 probe(step: &str) -> bool {+ match step.parse::<u8>() {+ Ok(ACCESSIBILITY) => crate::system::permissions::preflight_accessibility(),+ Ok(SCREEN_RECORDING) => crate::system::permissions::preflight_screen_recording(),+ _ => false,+ }}fn missing_steps(accessibility: bool, screen_recording: bool) -> u8 {@@ -129,13 +136,55 @@ fn parse_steps(value: &str) -> Option<u8> {.filter(|steps| (1..=(ACCESSIBILITY | SCREEN_RECORDING)).contains(steps))}+/// TCC charges a command-line tool to the app that launched its process+/// tree, so the guide shows the nearest ancestor that runs from an app+/// bundle. Terminal servers such as Rex Server are not registered with+/// LaunchServices, so the bundle comes from the executable path.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()) } {+ let mut pid = i32::try_from(std::process::id()).ok()?;+ for _ in 0..MAX_ANCESTORS {+ if pid <= 1 {+ return None;+ }+ let app = crate::system::renderer_kind::executable_path(pid)+ .as_deref()+ .and_then(outermost_app);+ if app.is_some() {+ return app;+ }+ pid = parent_pid(pid)?;+ }+ None+}++/// A helper such as `Code Helper (Plugin).app` sits inside the app that TCC+/// names, so the outermost bundle wins.+fn outermost_app(executable: &Path) -> Option<PathBuf> {+ executable+ .ancestors()+ .filter(|path| path.extension().is_some_and(|extension| extension == "app"))+ .last()+ .map(Path::to_path_buf)+}++/// The short BSD record, unlike the full one, is readable for processes of+/// another user, such as the root-owned `/usr/bin/login` a terminal starts.+fn parent_pid(pid: i32) -> Option<i32> {+ let mut info = std::mem::MaybeUninit::<libc::proc_bsdshortinfo>::zeroed();+ let size = i32::try_from(std::mem::size_of::<libc::proc_bsdshortinfo>()).ok()?;+ let read = unsafe {+ libc::proc_pidinfo(+ pid,+ libc::PROC_PIDT_SHORTBSDINFO,+ 0,+ info.as_mut_ptr().cast(),+ size,+ )+ };+ if read != size {return None;}- let path = unsafe { CStr::from_ptr(buffer.as_ptr()) };- path.to_str().ok().map(PathBuf::from)+ i32::try_from(unsafe { info.assume_init() }.pbsi_ppid).ok()}fn hand_over(command: &mut Command, lock: &File) {@@ -180,7 +229,6 @@ fn lock_file(path: &Path) -> std::io::Result<Option<File>> {}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,@@ -236,10 +284,56 @@ mod tests {}#[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"));+ fn the_guide_offers_the_outermost_app_bundle_of_the_launching_process() {+ let rex = Path::new(+ "/Users/me/Library/Application Support/com.superlogical.rex/RexServer/Versions/Current/Rex Server.app/Contents/MacOS/rex",+ );+ assert_eq!(+ outermost_app(rex),+ Some(PathBuf::from(+ "/Users/me/Library/Application Support/com.superlogical.rex/RexServer/Versions/Current/Rex Server.app"+ ))+ );+ let code_helper = Path::new(+ "/Applications/Visual Studio Code.app/Contents/Frameworks/Code Helper (Plugin).app/Contents/MacOS/Code Helper (Plugin)",+ );+ assert_eq!(+ outermost_app(code_helper),+ Some(PathBuf::from("/Applications/Visual Studio Code.app"))+ );+ assert_eq!(+ outermost_app(Path::new(+ "/System/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal"+ )),+ Some(PathBuf::from("/System/Applications/Utilities/Terminal.app"))+ );+ assert_eq!(+ outermost_app(Path::new("/usr/local/bin/agent-desktop")),+ None+ );+ }++ #[test]+ fn the_host_walk_passes_through_a_process_of_another_user() {+ let parent = parent_pid(i32::try_from(std::process::id()).unwrap());+ assert_eq!(parent, Some(unsafe { libc::getppid() }));+ let launchd_child = std::process::Command::new("/bin/ps")+ .args(["-axo", "pid=,ppid=,uid="])+ .output()+ .unwrap();+ let root_child = String::from_utf8(launchd_child.stdout)+ .unwrap()+ .lines()+ .filter_map(|line| {+ let fields: Vec<i32> = line+ .split_whitespace()+ .filter_map(|field| field.parse().ok())+ .collect();+ (fields.len() == 3 && fields[0] > 1 && fields[1] == 1 && fields[2] == 0)+ .then_some(fields[0])+ })+ .next()+ .unwrap();+ assert_eq!(parent_pid(root_child), Some(1));}}diff --git a/crates/macos/src/system/permissions/permission_guide_bridge.m b/crates/macos/src/system/permissions/permission_guide_bridge.mindex 858134f3b..2b5f53690 100644--- a/crates/macos/src/system/permissions/permission_guide_bridge.m+++ b/crates/macos/src/system/permissions/permission_guide_bridge.m@@ -2,7 +2,6 @@#import <QuartzCore/QuartzCore.h>#import <stdbool.h>#import <stdint.h>-#import <sys/sysctl.h>typedef bool (*ADGuideGranted)(uint8_t step);@@ -12,38 +11,12 @@ 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 CGFloat ADGuideAuroraHeight = 96;+static const float ADGuideAuroraOpacity = 0.55;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 =@@ -191,6 +164,7 @@ static NSColor *ADGuideGray(CGFloat white) {self = [super initWithFrame:NSZeroRect];if (self != nil) {self.layer = [CALayer layer];+ self.layer.opacity = ADGuideAuroraOpacity;self.wantsLayer = YES;self.layerUsesCoreImageFilters = YES;}@@ -279,13 +253,13 @@ static NSColor *ADGuideGray(CGFloat white) {@property(nonatomic, strong) NSTextField *stepLabel;@property(nonatomic, strong) NSTextField *titleLabel;@property(nonatomic, strong) NSTextField *bodyLabel;+@property(nonatomic, strong) NSTextField *reasonLabel;@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;@@ -304,7 +278,6 @@ static NSColor *ADGuideGray(CGFloat white) {}_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];@@ -332,7 +305,9 @@ static NSColor *ADGuideGray(CGFloat white) {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 = [NSTextField wrappingLabelWithString:@""];+ self.titleLabel.alignment = NSTextAlignmentCenter;+ self.titleLabel.preferredMaxLayoutWidth = ADGuideWidth - 56;self.titleLabel.font = [NSFont systemFontOfSize:22 weight:NSFontWeightBold];self.titleLabel.textColor = NSColor.whiteColor;self.icon = [[ADGuideIcon alloc] init];@@ -353,10 +328,15 @@ static NSColor *ADGuideGray(CGFloat white) {self.bodyLabel.preferredMaxLayoutWidth = ADGuideWidth - 56;self.bodyLabel.textColor = ADGuideGray(0.86);self.bodyLabel.font = [NSFont systemFontOfSize:13 weight:NSFontWeightMedium];+ self.reasonLabel = [NSTextField wrappingLabelWithString:@""];+ self.reasonLabel.alignment = NSTextAlignmentCenter;+ self.reasonLabel.preferredMaxLayoutWidth = ADGuideWidth - 56;+ self.reasonLabel.textColor = ADGuideGray(0.56);+ self.reasonLabel.font = [NSFont systemFontOfSize:11.5 weight:NSFontWeightRegular];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+ tile, self.captionLabel, self.stepLabel, self.titleLabel, self.bodyLabel, self.reasonLabel, close]];stack.orientation = NSUserInterfaceLayoutOrientationVertical;stack.alignment = NSLayoutAttributeCenterX;@@ -365,7 +345,8 @@ static NSColor *ADGuideGray(CGFloat white) {[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 setCustomSpacing:6 afterView:self.bodyLabel];+ [stack setCustomSpacing:30 afterView:self.reasonLabel];stack.translatesAutoresizingMaskIntoConstraints = NO;[self.card addSubview:stack];[NSLayoutConstraint activateConstraints:@[@@ -469,7 +450,15 @@ static NSColor *ADGuideGray(CGFloat white) {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";+ NSOperatingSystemVersion renamed = {27, 0, 0};+ NSString *accessibilityList = [NSProcessInfo.processInfo isOperatingSystemAtLeastVersion:renamed]+ ? @"Device Control and Data Access"+ : @"Accessibility";+ self.titleLabel.stringValue = accessibility ? [@"Allow " stringByAppendingString:accessibilityList]+ : @"Allow Screen Recording";+ self.reasonLabel.stringValue = accessibility ? @"agent-desktop needs this to see and use your apps."+ : @"agent-desktop needs this to take screenshots of your apps.";+ self.reasonLabel.hidden = NO;[self showInstructions];NSString *pane = accessibility ? @"Privacy_Accessibility" : @"Privacy_ScreenCapture";NSOperatingSystemVersion ventura = {13, 0, 0};@@ -626,18 +615,53 @@ static NSColor *ADGuideGray(CGFloat white) {[NSImageSymbolConfiguration configurationWithPointSize:48 weight:NSFontWeightRegular];self.icon.image = [check imageWithSymbolConfiguration:config];self.icon.contentTintColor = NSColor.systemGreenColor;+ [self animateTick];}#pragma clang diagnostic popself.bodyLabel.stringValue = @"Done.";[self resizePanel];}+- (void)animateTick {+ if (NSWorkspace.sharedWorkspace.accessibilityDisplayShouldReduceMotion) {+ return;+ }+ CGFloat half = ADGuideIconSize / 2;+ CATransform3D small = CATransform3DConcat(+ CATransform3DConcat(CATransform3DMakeTranslation(-half, -half, 0), CATransform3DMakeScale(0.3, 0.3, 1)),+ CATransform3DMakeTranslation(half, half, 0));+ CASpringAnimation *pop = [CASpringAnimation animationWithKeyPath:@"transform"];+ pop.fromValue = [NSValue valueWithCATransform3D:small];+ pop.toValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];+ pop.mass = 1;+ pop.stiffness = 220;+ pop.damping = 12;+ pop.duration = pop.settlingDuration;+ CABasicAnimation *fade = [CABasicAnimation animationWithKeyPath:@"opacity"];+ fade.fromValue = @0;+ fade.toValue = @1;+ fade.duration = 0.18;+ [self.icon.layer addAnimation:pop forKey:@"pop"];+ [self.icon.layer addAnimation:fade forKey:@"fade"];+ Class drawOn = NSClassFromString(@"NSSymbolDrawOnEffect");+ Class drawOff = NSClassFromString(@"NSSymbolDrawOffEffect");+ Class options = NSClassFromString(@"NSSymbolEffectOptions");+ if (drawOn == nil || drawOff == nil || options == nil ||+ ![self.icon respondsToSelector:@selector(addSymbolEffect:options:animated:)]) {+ return;+ }+#pragma clang diagnostic push+#pragma clang diagnostic ignored "-Wunguarded-availability-new"+ [self.icon addSymbolEffect:[drawOff effect] options:[options options] animated:NO];+ [self.icon addSymbolEffect:[drawOn effect] options:[options options] animated:YES];+#pragma clang diagnostic pop+}+- (void)showDone {+ self.reasonLabel.hidden = YES;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.bodyLabel.stringValue = @"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];diff --git a/crates/macos/src/system/renderer_kind.rs b/crates/macos/src/system/renderer_kind.rsindex 151a6d7b4..01bbb14f0 100644--- a/crates/macos/src/system/renderer_kind.rs+++ b/crates/macos/src/system/renderer_kind.rs@@ -43,7 +43,7 @@ pub(crate) fn detect_chromium(_pid: i32) -> Option<RendererKind> {}#[cfg(target_os = "macos")]-fn executable_path(pid: i32) -> Option<PathBuf> {+pub(crate) fn executable_path(pid: i32) -> Option<PathBuf> {let mut buffer = [0_u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize];let capacity = u32::try_from(buffer.len()).ok()?;let written = unsafe { libc::proc_pidpath(pid, buffer.as_mut_ptr().cast(), capacity) };diff --git a/crates/macos/src/system/screenshot.rs b/crates/macos/src/system/screenshot.rsindex b6f43f4f6..2217f0472 100644--- a/crates/macos/src/system/screenshot.rs+++ b/crates/macos/src/system/screenshot.rs@@ -274,7 +274,7 @@ mod imp {{return AdapterError::new(ErrorCode::PermDenied, "Screen Recording permission denied").with_suggestion(- "Open System Settings > Privacy & Security > Screen Recording and add the app that launches agent-desktop.",+ "Run agent-desktop permissions --guide. It opens System Settings > Privacy & Security > Screen Recording with a guide that shows which app to add.",).with_platform_detail(combined.trim());}diff --git a/skills/agent-desktop-macos/SKILL.md b/skills/agent-desktop-macos/SKILL.mdindex 1dbaa8513..03deb4d3f 100644--- a/skills/agent-desktop-macos/SKILL.md+++ b/skills/agent-desktop-macos/SKILL.md@@ -19,7 +19,7 @@ Read the core skill first (`agent-desktop skills get desktop`) for the observe,## Requirements- macOS 13 or later, Intel or Apple Silicon.-- Accessibility permission for the app that launches agent-desktop (Terminal, iTerm2, Warp, VS Code, Codex). If System Settings lists the `agent-desktop` binary separately, grant it too.+- Accessibility permission for the app that launches agent-desktop (Terminal, iTerm2, Warp, VS Code, Codex). macOS 27 and later name this list Device Control and Data Access. If System Settings lists the `agent-desktop` binary separately, grant it too.- Screen Recording permission, only for `screenshot` and for `session start --screenshots` artifacts.- Automation permission for System Events, only where a command reports it missing.@@ -27,9 +27,9 @@ Read the core skill first (`agent-desktop skills get desktop`) for the observe,1. Run `agent-desktop permissions`.2. If a permission is denied, run `agent-desktop permissions --guide`. It opens the correct System Settings page with a panel that shows the user which app to drag into the list. The user confirms with Touch ID or a password, and 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.-3. Open System Settings > Privacy & Security > Accessibility. Turn on the launching app.-4. Restart the launching app. A running process does not pick up a new grant.-5. Run `agent-desktop snapshot --app Finder -i` to confirm.+3. If the guide cannot run, open System Settings > Privacy & Security > Accessibility (Device Control and Data Access on macOS 27 and later). Add the launching app and turn it on.+4. Run `agent-desktop permissions` to confirm `granted`. The next agent-desktop call sees a new grant, so the launching app does not need a restart.+5. Run `agent-desktop snapshot -i` to confirm. It reads the focused app. `snapshot --app Finder -i` returns `WINDOW_NOT_FOUND` when Finder has no open window.`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.diff --git a/skills/agent-desktop-macos/references/troubleshooting.md b/skills/agent-desktop-macos/references/troubleshooting.mdindex 171b31209..ee56496d6 100644--- a/skills/agent-desktop-macos/references/troubleshooting.md+++ b/skills/agent-desktop-macos/references/troubleshooting.md@@ -8,7 +8,9 @@ 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.** Follow "First contact" in the macOS skill: `permissions --guide`, turn on the launching app (and the `agent-desktop` binary if it is listed on its own) in System Settings > Privacy & Security > Accessibility or Screen Recording, restart the launching app, then run `agent-desktop permissions` to confirm `granted`.+**Fix.** Follow "First contact" in the macOS skill: `permissions --guide`, turn on the launching app (and the `agent-desktop` binary if it is listed on its own) in System Settings > Privacy & Security > Accessibility or Screen Recording, then run `agent-desktop permissions` to confirm `granted`. The launching app does not need a restart.++The guide offers the app bundle of the nearest process above agent-desktop. Under a tmux server or an SSH session, no such app exists, so the guide offers the `agent-desktop` binary. In that case, add the terminal app that started tmux by hand. macOS 27 and later name the Accessibility list Device Control and Data Access.For Automation, open Privacy & Security > Automation and allow the launching app to control System Events.diff --git a/skills/agent-desktop/references/workflows.md b/skills/agent-desktop/references/workflows.mdindex 8c463a869..b476f2810 100644--- a/skills/agent-desktop/references/workflows.md+++ b/skills/agent-desktop/references/workflows.md@@ -11,7 +11,7 @@ agent-desktop statusagent-desktop permissions```-- On macOS, the terminal needs Accessibility permission, and Screen Recording for screenshots. If `permissions` reports `denied`, run `agent-desktop permissions --request` and grant the permission in System Settings.+- On macOS, the terminal needs Accessibility permission, and Screen Recording for screenshots. If `permissions` reports `denied`, run `agent-desktop permissions --guide`. It opens System Settings at the missing permission with a panel that shows the user which app to drag into the list.- On Windows, there is no permission dialog for same-integrity targets. Input into an elevated target needs an equally elevated terminal.- On Linux, there is no permission dialog. The session needs a running AT-SPI bus and `status` must report `accessibility` as `granted`. Run the tool in the same desktop session as the target app. If `status` reports it denied, read the bus section of the Linux skill.diff --git a/src/command_host/command_host_socket.rs b/src/command_host/command_host_socket.rsindex 68d1c32a5..bae7ad3ee 100644--- a/src/command_host/command_host_socket.rs+++ b/src/command_host/command_host_socket.rs@@ -6,7 +6,11 @@ use std::os::unix::net::{UnixListener, UnixStream};use std::path::Path;use std::time::Instant;-pub(super) fn run(path: &Path, mut execute: impl FnMut(&[u8]) -> Response) -> Result<(), AppError> {+pub(super) fn run(+ path: &Path,+ mut execute: impl FnMut(&[u8]) -> Response,+ stop_after_reply: impl Fn() -> bool,+) -> Result<(), AppError> {validate_parent(path)?;let _owner = agent_desktop_core::FileLock::acquire(&path.with_extension("owner.lock"),@@ -36,6 +40,9 @@ pub(super) fn run(path: &Path, mut execute: impl FnMut(&[u8]) -> Response) -> Reif let Err(error) = serve_connection(stream, &mut execute) {tracing::warn!(%error, "command host connection ended without a complete reply");}+ if stop_after_reply() {+ return Ok(());+ }}}@@ -89,6 +96,39 @@ mod tests {use super::*;use std::io::{Read, Write};+ #[test]+ fn the_host_returns_after_a_reply_that_asks_it_to_stop() {+ let scratch = super::super::test_dir::TestDir::new();+ std::fs::set_permissions(scratch.path(), std::fs::Permissions::from_mode(0o700)).unwrap();+ let path = scratch.path().join("h.sock");+ let (finished, result) = std::sync::mpsc::channel();+ let server_path = path.clone();+ std::thread::spawn(move || {+ let outcome = run(+ &server_path,+ |_| Response::ok("version", serde_json::json!({})),+ || true,+ );+ finished.send(outcome.is_ok()).unwrap();+ });+ let give_up = Instant::now() + std::time::Duration::from_secs(10);+ let mut client = loop {+ if let Ok(stream) = UnixStream::connect(&path) {+ break stream;+ }+ assert!(Instant::now() < give_up, "host did not bind");+ std::thread::sleep(std::time::Duration::from_millis(10));+ };+ client.write_all(b"[]\n").unwrap();+ let mut reply = Vec::new();+ client.read_to_end(&mut reply).unwrap();+ assert!(!reply.is_empty());+ assert_eq!(+ result.recv_timeout(std::time::Duration::from_secs(10)),+ Ok(true)+ );+ }+#[test]fn each_connection_dispatches_only_one_request() {let (server, mut client) = UnixStream::pair().unwrap();diff --git a/src/command_host/mod.rs b/src/command_host/mod.rsindex 2308299b6..130981b25 100644--- a/src/command_host/mod.rs+++ b/src/command_host/mod.rs@@ -54,6 +54,7 @@ pub(crate) fn run() -> Result<(), AppError> {let mut next_prune = RETAINED_PRUNE_INTERVAL;let identity = endpoint::identity(session.as_deref())?;let socket_path = std::env::var_os("AGENT_DESKTOP_INTERNAL_HOST_SOCKET");+ let reported_missing_permission = std::cell::Cell::new(false);let execute = |bytes: &[u8]| {if owner.capture_count() >= next_prune {match store.retained_object_tokens() {@@ -66,14 +67,20 @@ pub(crate) fn run() -> Result<(), AppError> {.capture_count().saturating_add(RETAINED_PRUNE_INTERVAL);}- if socket_path.is_some() {+ let response = if socket_path.is_some() {request::execute(bytes, &identity, session.as_deref())} else {execute_request(bytes, session.as_deref())+ };+ if reports_missing_permission(&response) {+ reported_missing_permission.set(true);}+ response};if let Some(ref path) = socket_path {- return socket::run(std::path::Path::new(&path), execute);+ return socket::run(std::path::Path::new(&path), execute, || {+ reported_missing_permission.get()+ });}let input = std::io::stdin();let output = std::fs::File::from(std::io::stdout().as_fd().try_clone_to_owned()?);@@ -93,6 +100,21 @@ pub(crate) fn run() -> Result<(), AppError> {Ok(())}+/// macOS keeps the Accessibility answer a process read before a grant, so a+/// host that told a caller a permission is missing exits after that reply and+/// the next call starts a host that sees the new grant.+fn reports_missing_permission(response: &Response) -> bool {+ let denied = |report: &serde_json::Value| report["accessibility"]["state"] == "denied";+ response+ .error+ .as_ref()+ .is_some_and(|error| error.code == "PERM_DENIED")+ || response+ .data+ .as_ref()+ .is_some_and(|data| denied(data) || denied(&data["permissions"]))+}+fn execute_request(bytes: &[u8], session: Option<&str>) -> Response {let result = parse_request(bytes, session);match result {@@ -200,6 +222,33 @@ fn serve_frames(mod tests {use super::*;+ #[test]+ fn a_host_stops_after_it_reports_a_missing_permission() {+ let report = |accessibility: &str| serde_json::json!({ "accessibility": { "state": accessibility } });+ assert!(reports_missing_permission(&Response::ok(+ "permissions",+ report("denied")+ )));+ assert!(reports_missing_permission(&Response::ok(+ "status",+ serde_json::json!({ "permissions": report("denied") })+ )));+ assert!(reports_missing_permission(&crate::response(+ "snapshot",+ Err(AppError::Adapter(+ agent_desktop_core::AdapterError::permission_denied()+ ))+ )));+ assert!(!reports_missing_permission(&Response::ok(+ "permissions",+ report("granted")+ )));+ assert!(!reports_missing_permission(&Response::ok(+ "version",+ serde_json::json!({})+ )));+ }+#[test]fn repeated_commands_reuse_dispatch_and_preserve_envelopes() {let mut output = Vec::new();