Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
feat(macos,core): harden adapter and core foundation with caller-controllable guardrails (#82)
Lahfir94ce6c551fff
diff --git a/crates/core/src/action.rs b/crates/core/src/action.rsindex 0e05d6ec3..aa046ec82 100644--- a/crates/core/src/action.rs+++ b/crates/core/src/action.rs@@ -101,10 +101,8 @@ pub struct DragParams {pub to: Point,#[serde(skip_serializing_if = "Option::is_none")]pub duration_ms: Option<u64>,- /// Time to hold the dragged item over the destination before releasing.- /// macOS drop targets often need the drag to dwell over them before they- /// register as the drop destination; too short and the gesture lands as a- /// drag with no drop. `None` uses the adapter default.+ /// Time to hold over the destination before releasing. Some platforms require+ /// a minimum dwell before the drop registers; `None` uses the adapter default.#[serde(skip_serializing_if = "Option::is_none")]pub drop_delay_ms: Option<u64>,}@@ -148,26 +146,5 @@ pub enum Modifier {}#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn action_names_do_not_include_payloads() {- let cases = [- (Action::SetValue("private".into()), "set-value"),- (Action::Select("private".into()), "select"),- (Action::TypeText("private".into()), "type"),- (- Action::PressKey(KeyCombo {- key: "A".into(),- modifiers: vec![Modifier::Cmd],- }),- "press",- ),- ];-- for (action, expected) in cases {- assert_eq!(action.name(), expected);- }- }-}+#[path = "action_tests.rs"]+mod tests;diff --git a/crates/core/src/action_tests.rs b/crates/core/src/action_tests.rsnew file mode 100644index 000000000..960b635eb--- /dev/null+++ b/crates/core/src/action_tests.rs@@ -0,0 +1,125 @@+use super::*;+use crate::interaction_policy::InteractionPolicy;++fn dummy_key() -> KeyCombo {+ KeyCombo {+ key: "a".into(),+ modifiers: vec![],+ }+}++fn dummy_drag() -> DragParams {+ DragParams {+ from: Point { x: 0.0, y: 0.0 },+ to: Point { x: 1.0, y: 1.0 },+ duration_ms: None,+ drop_delay_ms: None,+ }+}++#[test]+fn action_names_do_not_include_payloads() {+ let cases = [+ (Action::SetValue("private".into()), "set-value"),+ (Action::Select("private".into()), "select"),+ (Action::TypeText("private".into()), "type"),+ (+ Action::PressKey(KeyCombo {+ key: "A".into(),+ modifiers: vec![Modifier::Cmd],+ }),+ "press",+ ),+ ];++ for (action, expected) in cases {+ assert_eq!(action.name(), expected);+ }+}++#[test]+fn pure_ax_actions_base_policy_is_headless() {+ let headless = InteractionPolicy::headless();+ let pure_ax: &[Action] = &[+ Action::Click,+ Action::DoubleClick,+ Action::RightClick,+ Action::TripleClick,+ Action::SetFocus,+ Action::Expand,+ Action::Collapse,+ Action::Toggle,+ Action::Check,+ Action::Uncheck,+ Action::ScrollTo,+ Action::Clear,+ Action::Scroll(Direction::Down, 3),+ Action::SetValue("v".into()),+ Action::Select("s".into()),+ ];+ for action in pure_ax {+ assert_eq!(+ action.base_interaction_policy(),+ headless,+ "{} must use headless base policy",+ action.name()+ );+ }+}++#[test]+fn press_key_and_type_text_base_policy_is_focus_fallback() {+ let focus = InteractionPolicy::focus_fallback();+ assert_eq!(+ Action::PressKey(KeyCombo {+ key: "a".into(),+ modifiers: vec![Modifier::Cmd],+ })+ .base_interaction_policy(),+ focus,+ "PressKey must request focus_fallback to land in the right field"+ );+ assert_eq!(+ Action::TypeText("hello".into()).base_interaction_policy(),+ focus,+ "TypeText must request focus_fallback"+ );+}++#[test]+fn key_down_and_key_up_base_policy_is_headless_unlike_press_key() {+ let headless = InteractionPolicy::headless();+ assert_eq!(+ Action::KeyDown(dummy_key()).base_interaction_policy(),+ headless,+ "KeyDown must be headless; raw key-down events do not need focus theft"+ );+ assert_eq!(+ Action::KeyUp(dummy_key()).base_interaction_policy(),+ headless,+ "KeyUp must be headless"+ );+}++#[test]+fn hover_and_drag_base_policy_is_headless_independent_of_cursor_requirement() {+ let headless = InteractionPolicy::headless();+ assert_eq!(+ Action::Hover.base_interaction_policy(),+ headless,+ "Hover base_interaction_policy is headless even though requires_cursor_policy is true"+ );+ assert_eq!(+ Action::Drag(dummy_drag()).base_interaction_policy(),+ headless,+ "Drag base_interaction_policy is headless even though requires_cursor_policy is true"+ );+ assert!(+ Action::Hover.requires_cursor_policy(),+ "Hover.requires_cursor_policy() must still be true"+ );+ assert!(+ Action::Drag(dummy_drag()).requires_cursor_policy(),+ "Drag.requires_cursor_policy() must still be true"+ );+}diff --git a/crates/core/src/adapter.rs b/crates/core/src/adapter.rsindex a5056a2c3..668acc53f 100644--- a/crates/core/src/adapter.rs+++ b/crates/core/src/adapter.rs@@ -16,6 +16,7 @@ pub struct WindowFilter {pub app: Option<String>,}+#[non_exhaustive]#[derive(Debug, Clone, Copy, Default, serde::Serialize, serde::Deserialize, PartialEq, Eq)]#[serde(rename_all = "snake_case")]pub enum SnapshotSurface {@@ -196,12 +197,10 @@ pub trait PlatformAdapter: Send + Sync {self.resolve_element_strict(entry)}- /// Releases a platform-specific element handle returned from- /// `resolve_element`. Adapter methods that receive `&NativeHandle`- /// borrow it only; they must not consume or release it. macOS- /// implementations must `CFRelease` here to balance the `CFRetain`- /// that happened during resolve. Windows/Linux consumers can leave- /// this as the default no-op.+ /// Releases a platform handle that an implementation took ownership of during resolve.+ /// Adapter methods that receive `&NativeHandle` borrow it only; they must not consume+ /// or release it. The default no-op is correct for adapters whose handles are owned+ /// or freed elsewhere.fn release_handle(&self, _handle: &NativeHandle) -> Result<(), AdapterError> {Ok(())}@@ -252,6 +251,17 @@ pub trait PlatformAdapter: Send + Sync {false}+ /// Reports whether `combo` is a platform-dangerous keyboard shortcut that+ /// should be refused unless the caller explicitly forces it (for example+ /// macOS Cmd+Q quit, Ctrl+Cmd+Q lock, Cmd+Alt+Esc force-quit). Which+ /// combos are dangerous — and how key names alias to physical keys — is+ /// platform-specific, so each adapter owns its own list; core only asks+ /// and lets the caller override via `--force`. The default blocks nothing,+ /// leaving the decision entirely to the calling agent.+ fn is_blocked_combo(&self, _combo: &KeyCombo) -> bool {+ false+ }+fn screenshot(&self, _target: ScreenshotTarget) -> Result<ImageBuffer, AdapterError> {Err(AdapterError::not_supported("screenshot"))}diff --git a/crates/core/src/commands/combo.rs b/crates/core/src/commands/combo.rsnew file mode 100644index 000000000..e2bc3cd65--- /dev/null+++ b/crates/core/src/commands/combo.rs@@ -0,0 +1,60 @@+use crate::{+ action::{KeyCombo, Modifier},+ adapter::PlatformAdapter,+ error::{AdapterError, AppError},+};++/// Refuses `combo` when the platform adapter reports it as dangerous, unless+/// the caller forced it. Whether a combo is dangerous is the adapter's+/// decision (`is_blocked_combo`); core only enforces the verdict and honors+/// the `--force` override, so the calling agent always retains control.+pub fn ensure_combo_allowed(+ combo: &KeyCombo,+ raw: &str,+ force: bool,+ adapter: &dyn PlatformAdapter,+) -> Result<(), AppError> {+ if !force && adapter.is_blocked_combo(combo) {+ return Err(AppError::Adapter(AdapterError::policy_denied(format!(+ "Key combo '{raw}' is blocked for safety; pass --force to override"+ ))));+ }+ Ok(())+}++pub fn parse_combo_normalized(raw: &str) -> Result<KeyCombo, AppError> {+ let normalized = raw.to_lowercase().replace(' ', "");+ parse_combo(&normalized)+}++pub fn parse_combo(s: &str) -> Result<KeyCombo, AppError> {+ let parts: Vec<&str> = s.split('+').collect();+ let key = parts+ .last()+ .copied()+ .filter(|k| !k.is_empty())+ .ok_or_else(|| AppError::invalid_input("Empty key combo"))?+ .to_string();+ let mut modifiers = Vec::new();++ for &part in &parts[..parts.len() - 1] {+ let modifier = match part {+ "cmd" | "command" => Modifier::Cmd,+ "ctrl" | "control" => Modifier::Ctrl,+ "alt" | "option" => Modifier::Alt,+ "shift" => Modifier::Shift,+ other => {+ return Err(AppError::invalid_input(format!(+ "Unknown modifier: '{other}'"+ )));+ }+ };+ modifiers.push(modifier);+ }++ Ok(KeyCombo { key, modifiers })+}++#[cfg(test)]+#[path = "combo_tests.rs"]+mod tests;diff --git a/crates/core/src/commands/combo_tests.rs b/crates/core/src/commands/combo_tests.rsnew file mode 100644index 000000000..371fff35b--- /dev/null+++ b/crates/core/src/commands/combo_tests.rs@@ -0,0 +1,62 @@+use super::parse_combo;+use crate::action::Modifier;++#[test]+fn parse_combo_single_modifier_and_key() {+ let combo = parse_combo("cmd+k").expect("cmd+k is valid");+ assert_eq!(combo.key, "k");+ assert_eq!(combo.modifiers, vec![Modifier::Cmd]);+}++#[test]+fn parse_combo_two_modifiers_preserved_in_declaration_order() {+ let combo = parse_combo("cmd+shift+t").expect("cmd+shift+t is valid");+ assert_eq!(combo.key, "t");+ assert_eq!(combo.modifiers, vec![Modifier::Cmd, Modifier::Shift]);+}++#[test]+fn parse_combo_bare_key_yields_empty_modifier_list() {+ let combo = parse_combo("return").expect("bare key is valid");+ assert_eq!(combo.key, "return");+ assert!(combo.modifiers.is_empty());+}++#[test]+fn parse_combo_accepts_long_form_modifier_aliases() {+ let cmd = parse_combo("command+a").expect("command alias");+ assert_eq!(cmd.modifiers, vec![Modifier::Cmd]);++ let alt = parse_combo("option+x").expect("option alias");+ assert_eq!(alt.modifiers, vec![Modifier::Alt]);++ let ctrl = parse_combo("control+y").expect("control alias");+ assert_eq!(ctrl.modifiers, vec![Modifier::Ctrl]);+}++#[test]+fn parse_combo_rejects_unknown_modifier_with_invalid_args_code() {+ let err = parse_combo("win+k").expect_err("unknown modifier must fail");+ assert_eq!(err.code(), "INVALID_ARGS");+ assert!(+ err.to_string().contains("win"),+ "error must name the unknown modifier, got: {}",+ err+ );+}++#[test]+fn parse_combo_rejects_empty_trailing_key() {+ let err = parse_combo("cmd+").expect_err("trailing + with no key must fail");+ assert_eq!(err.code(), "INVALID_ARGS");+}++#[test]+fn parse_combo_key_is_preserved_verbatim_without_lowercasing() {+ let combo = parse_combo("cmd+K").expect("uppercase key is valid after lowercase modifier");+ assert_eq!(+ combo.key, "K",+ "parse_combo must NOT lowercase the key — normalization is the caller's responsibility"+ );+ assert_eq!(combo.modifiers, vec![Modifier::Cmd]);+}diff --git a/crates/core/src/commands/key_down.rs b/crates/core/src/commands/key_down.rsindex 5a1933310..25a4bbe26 100644--- a/crates/core/src/commands/key_down.rs+++ b/crates/core/src/commands/key_down.rs@@ -1,12 +1,18 @@-use crate::{adapter::PlatformAdapter, commands::press::parse_combo, error::AppError};+use crate::{+ adapter::PlatformAdapter,+ commands::combo::{ensure_combo_allowed, parse_combo_normalized},+ error::AppError,+};use serde_json::{Value, json};pub struct KeyDownArgs {pub combo: String,+ pub force: bool,}pub fn execute(args: KeyDownArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- let combo = parse_combo(&args.combo)?;+ let combo = parse_combo_normalized(&args.combo)?;+ ensure_combo_allowed(&combo, &args.combo, args.force, adapter)?;adapter.key_event(&combo, true)?;Ok(json!({ "key_down": args.combo }))}diff --git a/crates/core/src/commands/key_up.rs b/crates/core/src/commands/key_up.rsindex c595f40d6..377fd659a 100644--- a/crates/core/src/commands/key_up.rs+++ b/crates/core/src/commands/key_up.rs@@ -1,12 +1,18 @@-use crate::{adapter::PlatformAdapter, commands::press::parse_combo, error::AppError};+use crate::{+ adapter::PlatformAdapter,+ commands::combo::{ensure_combo_allowed, parse_combo_normalized},+ error::AppError,+};use serde_json::{Value, json};pub struct KeyUpArgs {pub combo: String,+ pub force: bool,}pub fn execute(args: KeyUpArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- let combo = parse_combo(&args.combo)?;+ let combo = parse_combo_normalized(&args.combo)?;+ ensure_combo_allowed(&combo, &args.combo, args.force, adapter)?;adapter.key_event(&combo, false)?;Ok(json!({ "key_up": args.combo }))}diff --git a/crates/core/src/commands/mod.rs b/crates/core/src/commands/mod.rsindex 94cceb8cd..55fe992b0 100644--- a/crates/core/src/commands/mod.rs+++ b/crates/core/src/commands/mod.rs@@ -7,6 +7,7 @@ pub mod clipboard_get;pub mod clipboard_set;pub mod close_app;pub mod collapse;+pub(crate) mod combo;pub mod dismiss_all_notifications;pub mod dismiss_notification;pub mod double_click;diff --git a/crates/core/src/commands/press.rs b/crates/core/src/commands/press.rsindex 48dfe6a57..942470f78 100644--- a/crates/core/src/commands/press.rs+++ b/crates/core/src/commands/press.rs@@ -1,34 +1,21 @@use crate::{- action::{Action, KeyCombo, Modifier},+ action::Action,action_request::ActionRequest,adapter::PlatformAdapter,+ commands::combo::{ensure_combo_allowed, parse_combo_normalized},error::AppError,};use serde_json::Value;-const BLOCKED_COMBOS: &[&str] = &[- "cmd+q",- "cmd+shift+q",- "cmd+alt+esc",- "ctrl+cmd+q",- "cmd+shift+delete",-];-pub struct PressArgs {pub combo: String,pub app: Option<String>,+ pub force: bool,}pub fn execute(args: PressArgs, adapter: &dyn PlatformAdapter) -> Result<Value, AppError> {- let normalized = args.combo.to_lowercase().replace(' ', "");- if BLOCKED_COMBOS.contains(&normalized.as_str()) {- return Err(AppError::invalid_input(format!(- "Key combo '{}' is blocked for safety",- args.combo- )));- }-- let combo = parse_combo(&normalized)?;+ let combo = parse_combo_normalized(&args.combo)?;+ ensure_combo_allowed(&combo, &args.combo, args.force, adapter)?;if let Some(app_name) = &args.app {let result = adapter.press_key_for_app(app_name, &combo)?;@@ -40,30 +27,6 @@ pub fn execute(args: PressArgs, adapter: &dyn PlatformAdapter) -> Result<Value,Ok(serde_json::to_value(result)?)}-pub fn parse_combo(s: &str) -> Result<KeyCombo, AppError> {- let parts: Vec<&str> = s.split('+').collect();- let key = parts- .last()- .copied()- .filter(|k| !k.is_empty())- .ok_or_else(|| AppError::invalid_input("Empty key combo"))?- .to_string();- let mut modifiers = Vec::new();-- for &part in &parts[..parts.len() - 1] {- let modifier = match part {- "cmd" | "command" => Modifier::Cmd,- "ctrl" | "control" => Modifier::Ctrl,- "alt" | "option" => Modifier::Alt,- "shift" => Modifier::Shift,- other => {- return Err(AppError::invalid_input(format!(- "Unknown modifier: '{other}'"- )));- }- };- modifiers.push(modifier);- }-- Ok(KeyCombo { key, modifiers })-}+#[cfg(test)]+#[path = "press_tests.rs"]+mod tests;diff --git a/crates/core/src/commands/press_tests.rs b/crates/core/src/commands/press_tests.rsnew file mode 100644index 000000000..863124753--- /dev/null+++ b/crates/core/src/commands/press_tests.rs@@ -0,0 +1,64 @@+use super::{PressArgs, execute};+use crate::action::KeyCombo;+use crate::action_request::ActionRequest;+use crate::action_result::ActionResult;+use crate::adapter::{NativeHandle, PlatformAdapter};+use crate::error::AdapterError;++struct BlockingAdapter;++impl PlatformAdapter for BlockingAdapter {+ fn is_blocked_combo(&self, _combo: &KeyCombo) -> bool {+ true+ }++ fn execute_action(+ &self,+ _handle: &NativeHandle,+ _request: ActionRequest,+ ) -> Result<ActionResult, AdapterError> {+ Ok(ActionResult::new("PressKey"))+ }+}++struct AllowingAdapter;++impl PlatformAdapter for AllowingAdapter {+ fn execute_action(+ &self,+ _handle: &NativeHandle,+ _request: ActionRequest,+ ) -> Result<ActionResult, AdapterError> {+ Ok(ActionResult::new("PressKey"))+ }+}++fn args(combo: &str, force: bool) -> PressArgs {+ PressArgs {+ combo: combo.to_owned(),+ app: None,+ force,+ }+}++#[test]+fn adapter_blocked_combo_is_refused_when_not_forced() {+ let err = execute(args("cmd+q", false), &BlockingAdapter).unwrap_err();+ assert_eq!(err.code(), "POLICY_DENIED");+ assert!(+ err.to_string().contains("--force"),+ "the refusal must tell the caller how to override, got: {err}"+ );+}++#[test]+fn force_bypasses_the_adapter_block() {+ execute(args("cmd+q", true), &BlockingAdapter)+ .expect("--force must let the agent send a blocked combo");+}++#[test]+fn core_blocks_nothing_by_default() {+ execute(args("cmd+q", false), &AllowingAdapter)+ .expect("core must not hardcode any block; the default adapter allows everything");+}diff --git a/crates/core/src/commands/skills.rs b/crates/core/src/commands/skills.rsindex b70be8d4f..914e22cce 100644--- a/crates/core/src/commands/skills.rs+++ b/crates/core/src/commands/skills.rs@@ -10,6 +10,8 @@ const SKILL_DESKTOP_REF_SYSTEM: &str =include_str!("../../../../skills/agent-desktop/references/commands-system.md");const SKILL_DESKTOP_REF_WORKFLOWS: &str =include_str!("../../../../skills/agent-desktop/references/workflows.md");++#[cfg(target_os = "macos")]const SKILL_DESKTOP_REF_MACOS: &str =include_str!("../../../../skills/agent-desktop/references/macos.md");@@ -33,16 +35,16 @@ struct Skill {aliases: &'static [&'static str],summary: &'static str,main: &'static str,- refs: &'static [SkillRef],+ refs: fn() -> &'static [SkillRef],}-const SKILLS: &[Skill] = &[- Skill {- canonical: "agent-desktop",- aliases: &["desktop", "agent-desktop"],- summary: "Primary guide. Snapshot/ref loop, JSON envelope, 54 commands across observation, interaction, keyboard/mouse, app lifecycle, notifications, clipboard, wait.",- main: SKILL_DESKTOP_MAIN,- refs: &[+/// Returns the four platform-agnostic desktop refs, plus the macOS ref on macOS targets.+/// Built once via OnceLock so the base entries are never duplicated.+fn skill_desktop_refs() -> &'static [SkillRef] {+ use std::sync::OnceLock;+ static REFS: OnceLock<Vec<SkillRef>> = OnceLock::new();+ REFS.get_or_init(|| {+ let mut v = vec![SkillRef {rel_path: "references/commands-observation.md",body: SKILL_DESKTOP_REF_OBSERVATION,@@ -59,35 +61,53 @@ const SKILLS: &[Skill] = &[rel_path: "references/workflows.md",body: SKILL_DESKTOP_REF_WORKFLOWS,},- SkillRef {- rel_path: "references/macos.md",- body: SKILL_DESKTOP_REF_MACOS,- },- ],+ ];+ #[cfg(target_os = "macos")]+ v.push(SkillRef {+ rel_path: "references/macos.md",+ body: SKILL_DESKTOP_REF_MACOS,+ });+ v+ })+}++const SKILL_FFI_REFS: &[SkillRef] = &[+ SkillRef {+ rel_path: "references/build-and-link.md",+ body: SKILL_FFI_REF_BUILD,+ },+ SkillRef {+ rel_path: "references/error-handling.md",+ body: SKILL_FFI_REF_ERRORS,+ },+ SkillRef {+ rel_path: "references/ownership.md",+ body: SKILL_FFI_REF_OWNERSHIP,+ },+ SkillRef {+ rel_path: "references/threading.md",+ body: SKILL_FFI_REF_THREADING,+ },+];++fn skill_ffi_refs() -> &'static [SkillRef] {+ SKILL_FFI_REFS+}++const SKILLS: &[Skill] = &[+ Skill {+ canonical: "agent-desktop",+ aliases: &["desktop", "agent-desktop"],+ summary: "Primary guide. Snapshot/ref loop, JSON envelope, 54 commands across observation, interaction, keyboard/mouse, app lifecycle, notifications, clipboard, wait.",+ main: SKILL_DESKTOP_MAIN,+ refs: skill_desktop_refs,},Skill {canonical: "agent-desktop-ffi",aliases: &["ffi", "agent-desktop-ffi"],summary: "Embedding agent-desktop in another process via the C ABI. Build/link, error propagation, handle ownership, threading rules.",main: SKILL_FFI_MAIN,- refs: &[- SkillRef {- rel_path: "references/build-and-link.md",- body: SKILL_FFI_REF_BUILD,- },- SkillRef {- rel_path: "references/error-handling.md",- body: SKILL_FFI_REF_ERRORS,- },- SkillRef {- rel_path: "references/ownership.md",- body: SKILL_FFI_REF_OWNERSHIP,- },- SkillRef {- rel_path: "references/threading.md",- body: SKILL_FFI_REF_THREADING,- },- ],+ refs: skill_ffi_refs,},];@@ -105,7 +125,7 @@ pub fn list() -> Result<Value, AppError> {"name": s.canonical,"aliases": s.aliases,"summary": s.summary,- "references": s.refs.iter().map(|r| r.rel_path).collect::<Vec<_>>(),+ "references": (s.refs)().iter().map(|r| r.rel_path).collect::<Vec<_>>(),})}).collect();@@ -116,12 +136,12 @@ pub fn get(args: GetArgs) -> Result<Value, AppError> {let skill = find_skill(&args.name)?;if let Some(rel) = args.reference {- let r = skill- .refs+ let refs = (skill.refs)();+ let r = refs.iter().find(|r| matches_ref(r.rel_path, &rel)).ok_or_else(|| {- let available: Vec<&str> = skill.refs.iter().map(|r| r.rel_path).collect();+ let available: Vec<&str> = refs.iter().map(|r| r.rel_path).collect();AppError::invalid_input(format!("Unknown reference '{rel}' for skill '{}'. Available: {}",skill.canonical,@@ -186,11 +206,12 @@ fn matches_ref(rel_path: &str, query: &str) -> bool {}fn render_full(skill: &Skill) -> String {+ let refs = (skill.refs)();let mut out = String::with_capacity(- skill.main.len() + skill.refs.iter().map(|r| r.body.len() + 64).sum::<usize>(),+ skill.main.len() + refs.iter().map(|r| r.body.len() + 64).sum::<usize>(),);out.push_str(skill.main);- for r in skill.refs {+ for r in refs {if !out.ends_with('\n') {out.push('\n');}diff --git a/crates/core/src/error.rs b/crates/core/src/error.rsindex 645cd4be2..b3fd50491 100644--- a/crates/core/src/error.rs+++ b/crates/core/src/error.rs@@ -250,13 +250,6 @@ mod tests {assert!(err.suggestion.is_some());}- #[test]- fn error_code_serialization() {- let code = ErrorCode::NotificationNotFound;- let json = serde_json::to_string(&code).unwrap();- assert_eq!(json, "\"NOTIFICATION_NOT_FOUND\"");- }-#[test]fn stale_ref_suggestion_is_transport_neutral() {let err = AdapterError::stale_ref("@e7");@@ -295,4 +288,55 @@ mod tests {AdapterError::policy_denied_for_policy("blocked", InteractionPolicy::focus_fallback());assert!(focus_fallback.suggestion.unwrap().contains("--headed"));}++ #[test]+ fn all_error_codes_as_str_and_serde_are_consistent() {+ let cases = [+ (ErrorCode::PermDenied, "PERM_DENIED"),+ (ErrorCode::ElementNotFound, "ELEMENT_NOT_FOUND"),+ (ErrorCode::AppNotFound, "APP_NOT_FOUND"),+ (ErrorCode::ActionFailed, "ACTION_FAILED"),+ (ErrorCode::ActionNotSupported, "ACTION_NOT_SUPPORTED"),+ (ErrorCode::StaleRef, "STALE_REF"),+ (ErrorCode::AmbiguousTarget, "AMBIGUOUS_TARGET"),+ (ErrorCode::WindowNotFound, "WINDOW_NOT_FOUND"),+ (ErrorCode::PlatformNotSupported, "PLATFORM_NOT_SUPPORTED"),+ (ErrorCode::Timeout, "TIMEOUT"),+ (ErrorCode::InvalidArgs, "INVALID_ARGS"),+ (ErrorCode::NotificationNotFound, "NOTIFICATION_NOT_FOUND"),+ (ErrorCode::SnapshotNotFound, "SNAPSHOT_NOT_FOUND"),+ (ErrorCode::PolicyDenied, "POLICY_DENIED"),+ (ErrorCode::Internal, "INTERNAL"),+ ];+ for (code, expected) in cases {+ assert_eq!(code.as_str(), expected, "as_str() mismatch for {expected}");+ let serialized = serde_json::to_string(&code).expect("serializable");+ assert_eq!(+ serialized,+ format!("\"{expected}\""),+ "serde output mismatch for {expected}"+ );+ }+ }++ #[test]+ fn non_adapter_app_errors_yield_internal_code_and_no_suggestion() {+ let io_err = AppError::Io(std::io::Error::new(std::io::ErrorKind::NotFound, "missing"));+ let json_err =+ AppError::Json(serde_json::from_str::<serde_json::Value>("not json").unwrap_err());+ let internal_err = AppError::Internal("unexpected state".into());++ for err in [&io_err, &json_err, &internal_err] {+ assert_eq!(+ err.code(),+ "INTERNAL",+ "expected INTERNAL code, got {}",+ err.code()+ );+ assert!(+ err.suggestion().is_none(),+ "non-adapter AppError must not carry a suggestion"+ );+ }+ }}diff --git a/crates/core/src/interaction_policy.rs b/crates/core/src/interaction_policy.rsindex 637bd4ee6..6c33fe825 100644--- a/crates/core/src/interaction_policy.rs+++ b/crates/core/src/interaction_policy.rs@@ -47,54 +47,5 @@ impl Default for InteractionPolicy {}#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn join_headless_with_headless_stays_headless() {- assert_eq!(- InteractionPolicy::headless().join(InteractionPolicy::headless()),- InteractionPolicy::headless()- );- }-- #[test]- fn join_headless_with_focus_fallback_gives_focus_fallback() {- assert_eq!(- InteractionPolicy::headless().join(InteractionPolicy::focus_fallback()),- InteractionPolicy::focus_fallback()- );- }-- #[test]- fn join_focus_fallback_with_headless_gives_focus_fallback() {- assert_eq!(- InteractionPolicy::focus_fallback().join(InteractionPolicy::headless()),- InteractionPolicy::focus_fallback()- );- }-- #[test]- fn join_headless_with_headed_gives_headed() {- assert_eq!(- InteractionPolicy::headless().join(InteractionPolicy::headed()),- InteractionPolicy::headed()- );- }-- #[test]- fn join_focus_fallback_with_headed_gives_headed() {- assert_eq!(- InteractionPolicy::focus_fallback().join(InteractionPolicy::headed()),- InteractionPolicy::headed()- );- }-- #[test]- fn join_headed_with_headless_gives_headed() {- assert_eq!(- InteractionPolicy::headed().join(InteractionPolicy::headless()),- InteractionPolicy::headed()- );- }-}+#[path = "interaction_policy_tests.rs"]+mod tests;diff --git a/crates/core/src/interaction_policy_tests.rs b/crates/core/src/interaction_policy_tests.rsnew file mode 100644index 000000000..ccfa830d9--- /dev/null+++ b/crates/core/src/interaction_policy_tests.rs@@ -0,0 +1,122 @@+use super::*;++#[test]+fn join_headless_with_headless_stays_headless() {+ assert_eq!(+ InteractionPolicy::headless().join(InteractionPolicy::headless()),+ InteractionPolicy::headless()+ );+}++#[test]+fn join_headless_with_focus_fallback_gives_focus_fallback() {+ assert_eq!(+ InteractionPolicy::headless().join(InteractionPolicy::focus_fallback()),+ InteractionPolicy::focus_fallback()+ );+}++#[test]+fn join_focus_fallback_with_headless_gives_focus_fallback() {+ assert_eq!(+ InteractionPolicy::focus_fallback().join(InteractionPolicy::headless()),+ InteractionPolicy::focus_fallback()+ );+}++#[test]+fn join_headless_with_headed_gives_headed() {+ assert_eq!(+ InteractionPolicy::headless().join(InteractionPolicy::headed()),+ InteractionPolicy::headed()+ );+}++#[test]+fn join_focus_fallback_with_headed_gives_headed() {+ assert_eq!(+ InteractionPolicy::focus_fallback().join(InteractionPolicy::headed()),+ InteractionPolicy::headed()+ );+}++#[test]+fn join_headed_with_headless_gives_headed() {+ assert_eq!(+ InteractionPolicy::headed().join(InteractionPolicy::headless()),+ InteractionPolicy::headed()+ );+}++/// The three named presets never have `focus_steal=false` with `cursor=true`.+/// This unnamed policy exercises that both fields are handled independently.+fn cursor_only() -> InteractionPolicy {+ InteractionPolicy {+ allow_focus_steal: false,+ allow_cursor_move: true,+ }+}++fn all_four_policies() -> [InteractionPolicy; 4] {+ [+ InteractionPolicy::headless(),+ InteractionPolicy::focus_fallback(),+ InteractionPolicy::headed(),+ cursor_only(),+ ]+}++#[test]+fn join_is_idempotent_for_all_policies_including_cursor_only() {+ for p in all_four_policies() {+ assert_eq!(p.join(p), p, "join(p, p) must equal p: {:?}", p);+ }+}++#[test]+fn join_is_commutative_over_all_policy_pairs() {+ for a in all_four_policies() {+ for b in all_four_policies() {+ assert_eq!(+ a.join(b),+ b.join(a),+ "join must be commutative: {:?} vs {:?}",+ a,+ b+ );+ }+ }+}++#[test]+fn join_never_downgrades_either_operand_on_any_field() {+ for a in all_four_policies() {+ for b in all_four_policies() {+ let result = a.join(b);+ assert!(+ result.allow_focus_steal >= a.allow_focus_steal,+ "join lowered allow_focus_steal below a: a={:?} b={:?}",+ a,+ b+ );+ assert!(+ result.allow_focus_steal >= b.allow_focus_steal,+ "join lowered allow_focus_steal below b: a={:?} b={:?}",+ a,+ b+ );+ assert!(+ result.allow_cursor_move >= a.allow_cursor_move,+ "join lowered allow_cursor_move below a: a={:?} b={:?}",+ a,+ b+ );+ assert!(+ result.allow_cursor_move >= b.allow_cursor_move,+ "join lowered allow_cursor_move below b: a={:?} b={:?}",+ a,+ b+ );+ }+ }+}diff --git a/crates/core/src/node.rs b/crates/core/src/node.rsindex 2140c15ab..950fd0bbf 100644--- a/crates/core/src/node.rs+++ b/crates/core/src/node.rs@@ -84,6 +84,7 @@ pub struct WindowInfo {pub struct AppInfo {pub name: String,pub pid: i32,+ #[serde(default, skip_serializing_if = "Option::is_none")]pub bundle_id: Option<String>,}@@ -98,82 +99,5 @@ pub struct SurfaceInfo {}#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn test_rect_null_fields_deserialize() {- let json = r#"{"x": null, "y": null, "width": 0.0, "height": 0.0}"#;- let rect: Rect = serde_json::from_str(json).unwrap();- assert_eq!(rect.x, 0.0);- assert_eq!(rect.y, 0.0);- }-- #[test]- fn test_rect_missing_fields_deserialize() {- let json = r#"{"width": 100.0, "height": 50.0}"#;- let rect: Rect = serde_json::from_str(json).unwrap();- assert_eq!(rect.x, 0.0);- assert_eq!(rect.y, 0.0);- assert_eq!(rect.width, 100.0);- }-- #[test]- fn test_children_count_omitted_when_none() {- let node = AccessibilityNode {- ref_id: None,- role: "group".into(),- name: Some("Sidebar".into()),- value: None,- description: None,- hint: None,- states: vec![],- available_actions: vec![],- bounds: None,- children_count: None,- children: vec![],- };- let json = serde_json::to_string(&node).unwrap();- assert!(!json.contains("children_count"));- }-- #[test]- fn test_children_count_present_when_set() {- let node = AccessibilityNode {- ref_id: None,- role: "group".into(),- name: Some("Sidebar".into()),- value: None,- description: None,- hint: None,- states: vec![],- available_actions: vec![],- bounds: None,- children_count: Some(47),- children: vec![],- };- let json = serde_json::to_string(&node).unwrap();- assert!(json.contains("\"children_count\":47"));- }-- #[test]- fn test_children_count_backward_compat() {- let json = r#"{"role":"button","name":"OK"}"#;- let node: AccessibilityNode = serde_json::from_str(json).unwrap();- assert!(node.children_count.is_none());- }-- #[test]- fn test_rect_normal_roundtrip() {- let rect = Rect {- x: 10.5,- y: 20.3,- width: 100.0,- height: 50.0,- };- let json = serde_json::to_string(&rect).unwrap();- let back: Rect = serde_json::from_str(&json).unwrap();- assert_eq!(back.x, 10.5);- assert_eq!(back.width, 100.0);- }-}+#[path = "node_tests.rs"]+mod tests;diff --git a/crates/core/src/node_tests.rs b/crates/core/src/node_tests.rsnew file mode 100644index 000000000..3b6f47b1c--- /dev/null+++ b/crates/core/src/node_tests.rs@@ -0,0 +1,187 @@+use super::*;++#[test]+fn test_rect_null_fields_deserialize() {+ let json = r#"{"x": null, "y": null, "width": 0.0, "height": 0.0}"#;+ let rect: Rect = serde_json::from_str(json).unwrap();+ assert_eq!(rect.x, 0.0);+ assert_eq!(rect.y, 0.0);+}++#[test]+fn test_rect_missing_fields_deserialize() {+ let json = r#"{"width": 100.0, "height": 50.0}"#;+ let rect: Rect = serde_json::from_str(json).unwrap();+ assert_eq!(rect.x, 0.0);+ assert_eq!(rect.y, 0.0);+ assert_eq!(rect.width, 100.0);+}++#[test]+fn test_children_count_omitted_when_none() {+ let node = AccessibilityNode {+ ref_id: None,+ role: "group".into(),+ name: Some("Sidebar".into()),+ value: None,+ description: None,+ hint: None,+ states: vec![],+ available_actions: vec![],+ bounds: None,+ children_count: None,+ children: vec![],+ };+ let json = serde_json::to_string(&node).unwrap();+ assert!(!json.contains("children_count"));+}++#[test]+fn test_children_count_present_when_set() {+ let node = AccessibilityNode {+ ref_id: None,+ role: "group".into(),+ name: Some("Sidebar".into()),+ value: None,+ description: None,+ hint: None,+ states: vec![],+ available_actions: vec![],+ bounds: None,+ children_count: Some(47),+ children: vec![],+ };+ let json = serde_json::to_string(&node).unwrap();+ assert!(json.contains("\"children_count\":47"));+}++#[test]+fn test_children_count_backward_compat() {+ let json = r#"{"role":"button","name":"OK"}"#;+ let node: AccessibilityNode = serde_json::from_str(json).unwrap();+ assert!(node.children_count.is_none());+}++#[test]+fn test_rect_normal_roundtrip() {+ let rect = Rect {+ x: 10.5,+ y: 20.3,+ width: 100.0,+ height: 50.0,+ };+ let json = serde_json::to_string(&rect).unwrap();+ let back: Rect = serde_json::from_str(&json).unwrap();+ assert_eq!(back.x, 10.5);+ assert_eq!(back.width, 100.0);+}++/// AppInfo.bundle_id is annotated skip_serializing_if = "Option::is_none".+/// When absent it must not appear in the JSON — agents must tolerate its+/// absence rather than fail on a missing key.+#[test]+fn app_info_bundle_id_none_omitted_from_json() {+ let info = AppInfo {+ name: "Finder".into(),+ pid: 42,+ bundle_id: None,+ };+ let json = serde_json::to_string(&info).unwrap();+ assert!(+ !json.contains("\"bundle_id\":"),+ "bundle_id must be absent when None, json={json}"+ );+}++/// When bundle_id is Some it must appear in the JSON with the correct value.+#[test]+fn app_info_bundle_id_some_present_in_json() {+ let info = AppInfo {+ name: "Safari".into(),+ pid: 7,+ bundle_id: Some("com.apple.Safari".into()),+ };+ let json = serde_json::to_string(&info).unwrap();+ assert!(+ json.contains("\"bundle_id\":\"com.apple.Safari\""),+ "bundle_id must be present when Some, json={json}"+ );+}++/// AppInfo round-trips through serde with all fields intact.+/// Uses field-by-field comparison because AppInfo does not derive PartialEq.+#[test]+fn app_info_roundtrip_preserves_all_fields() {+ let original = AppInfo {+ name: "TextEdit".into(),+ pid: 1234,+ bundle_id: Some("com.apple.TextEdit".into()),+ };+ let json = serde_json::to_string(&original).unwrap();+ let back: AppInfo = serde_json::from_str(&json).unwrap();+ assert_eq!(back.name, original.name);+ assert_eq!(back.pid, original.pid);+ assert_eq!(back.bundle_id, original.bundle_id);+}++/// Agents may produce AppInfo JSON without a bundle_id key (e.g. non-macOS adapters+/// or older protocol versions). Deserialization must succeed and yield None.+/// This pins the JSON backward-compat contract: bundle_id is always optional on the wire.+#[test]+fn app_info_bundle_id_missing_key_deserializes_to_none() {+ let json = r#"{"name":"Finder","pid":42}"#;+ let info: AppInfo =+ serde_json::from_str(json).expect("deserialize AppInfo without bundle_id key");+ assert_eq!(info.bundle_id, None);+ assert_eq!(info.name, "Finder");+ assert_eq!(info.pid, 42);+}++/// AccessibilityNode.bounds is annotated skip_serializing_if = "Option::is_none".+/// When the adapter or ref-alloc pipeline strips bounds, the key must not+/// appear in the JSON, keeping token counts low.+#[test]+fn accessibility_node_bounds_none_omitted_from_json() {+ let node = AccessibilityNode {+ ref_id: None,+ role: "button".into(),+ name: Some("OK".into()),+ value: None,+ description: None,+ hint: None,+ states: vec![],+ available_actions: vec![],+ bounds: None,+ children_count: None,+ children: vec![],+ };+ let json = serde_json::to_string(&node).unwrap();+ assert!(+ !json.contains("\"bounds\":"),+ "bounds must be absent when None, json={json}"+ );+}++/// AccessibilityNode.hint is annotated skip_serializing_if = "Option::is_none".+/// When not provided by the platform adapter, it must not appear in the JSON.+#[test]+fn accessibility_node_hint_none_omitted_from_json() {+ let node = AccessibilityNode {+ ref_id: None,+ role: "textfield".into(),+ name: None,+ value: None,+ description: None,+ hint: None,+ states: vec![],+ available_actions: vec![],+ bounds: None,+ children_count: None,+ children: vec![],+ };+ let json = serde_json::to_string(&node).unwrap();+ assert!(+ !json.contains("\"hint\":"),+ "hint must be absent when None, json={json}"+ );+}diff --git a/crates/core/src/output.rs b/crates/core/src/output.rsindex b8990400d..99d205afd 100644--- a/crates/core/src/output.rs+++ b/crates/core/src/output.rs@@ -181,4 +181,89 @@ mod tests {);}}++ #[test]+ fn ok_response_json_shape_has_version_ok_command_data_and_no_error_field() {+ let resp = Response::ok("snapshot", json!({"app": "Finder"}));+ let map: serde_json::Map<String, serde_json::Value> =+ serde_json::from_value(serde_json::to_value(&resp).expect("serializable"))+ .expect("map");++ assert_eq!(map["version"].as_str(), Some("2.0"), "version must be 2.0");+ assert_eq!(map["ok"].as_bool(), Some(true), "ok must be true");+ assert_eq!(+ map["command"].as_str(),+ Some("snapshot"),+ "command must match"+ );+ assert!(map.contains_key("data"), "ok response must have data field");+ assert!(+ !map.contains_key("error"),+ "ok response must not serialize an error field (skip_serializing_if = is_none)"+ );+ }++ #[test]+ fn err_response_json_shape_has_version_ok_command_error_and_no_data_field() {+ let payload =+ ErrorPayload::new("STALE_REF", "ref @e1 is stale").with_suggestion("re-run snapshot");+ let resp = Response::err("click", payload);+ let map: serde_json::Map<String, serde_json::Value> =+ serde_json::from_value(serde_json::to_value(&resp).expect("serializable"))+ .expect("map");++ assert_eq!(map["version"].as_str(), Some("2.0"), "version must be 2.0");+ assert_eq!(map["ok"].as_bool(), Some(false), "ok must be false");+ assert_eq!(map["command"].as_str(), Some("click"), "command must match");+ assert!(+ !map.contains_key("data"),+ "err response must not serialize a data field (skip_serializing_if = is_none)"+ );+ assert!(+ map.contains_key("error"),+ "err response must have error field"+ );+ assert_eq!(+ map["error"]["code"].as_str(),+ Some("STALE_REF"),+ "error code must round-trip"+ );+ assert_eq!(+ map["error"]["message"].as_str(),+ Some("ref @e1 is stale"),+ "error message must round-trip"+ );+ assert_eq!(+ map["error"]["suggestion"].as_str(),+ Some("re-run snapshot"),+ "suggestion must be present when set"+ );+ }++ #[test]+ fn err_response_omits_optional_error_subfields_when_absent() {+ let payload = ErrorPayload::new("INTERNAL", "something broke");+ let resp = Response::err("snapshot", payload);+ let map: serde_json::Map<String, serde_json::Value> =+ serde_json::from_value(serde_json::to_value(&resp).expect("serializable"))+ .expect("map");++ let error = map["error"].as_object().expect("error must be an object");+ assert!(+ !error.contains_key("suggestion"),+ "absent suggestion must be omitted from JSON"+ );+ assert!(+ !error.contains_key("retry_command"),+ "absent retry_command must be omitted from JSON"+ );+ assert!(+ !error.contains_key("platform_detail"),+ "absent platform_detail must be omitted from JSON"+ );+ assert!(+ !error.contains_key("details"),+ "absent details must be omitted from JSON"+ );+ }}diff --git a/crates/core/src/ref_alloc_tests.rs b/crates/core/src/ref_alloc_tests.rsindex 4d8684de1..37c8442a0 100644--- a/crates/core/src/ref_alloc_tests.rs+++ b/crates/core/src/ref_alloc_tests.rs@@ -218,6 +218,89 @@ fn entry_hash() -> u64 {.bounds_hash()}+/// Refs must be assigned in depth-first document order.+/// Given: window → [button("A"), group → [button("B"), button("C")]],+/// DFS visits A then B then C, so @e1=A, @e2=B, @e3=C.+/// A regression that allocates in BFS order (A, then skipping group to find B+/// last) would violate the contract the CLI documents and agents depend on.+#[test]+fn allocate_refs_assigns_refs_in_depth_first_order() {+ let btn_a = node("button", Some("A"));+ let btn_b = node("button", Some("B"));+ let btn_c = node("button", Some("C"));+ let mut group = node("group", None);+ group.children = vec![btn_b, btn_c];+ let mut root = node("window", Some("w"));+ root.children = vec![btn_a, group];++ let mut refmap = RefMap::new();+ let config = RefAllocConfig {+ include_bounds: false,+ interactive_only: false,+ compact: false,+ pid: 1,+ source_app: None,+ source_window_id: None,+ source_window_title: None,+ source_surface: crate::adapter::SnapshotSurface::Window,+ root_ref_id: None,+ path_prefix: &[],+ };+ let out = allocate_refs(root, &mut refmap, &config);++ let a_ref = out.children[0].ref_id.as_deref().unwrap();+ let b_ref = out.children[1].children[0].ref_id.as_deref().unwrap();+ let c_ref = out.children[1].children[1].ref_id.as_deref().unwrap();++ assert_eq!(a_ref, "@e1", "first DFS interactive node must be @e1");+ assert_eq!(b_ref, "@e2", "second DFS interactive node must be @e2");+ assert_eq!(c_ref, "@e3", "third DFS interactive node must be @e3");+}++/// A node whose available_actions list contains SetFocus alongside a real+/// primary action must be ref-able, because advertises_primary_action+/// filters to actions that are not SetFocus.+#[test]+fn node_with_primary_action_alongside_set_focus_is_ref_able() {+ let mut panel = node("group", Some("Panel"));+ panel.available_actions = vec!["SetFocus".into(), "Scroll".into()];+ assert!(+ is_ref_able(&panel),+ "group with SetFocus+Scroll must be ref-able via the primary action path"+ );+}++/// Each role in the hardcoded list must be ref-able by role alone (no actions+/// needed). Using a literal list rather than iterating INTERACTIVE_ROLES means+/// removing any of these from the constant will actually fail this test.+#[test]+fn representative_interactive_roles_are_ref_able_by_role_alone() {+ for role in [+ "button",+ "textfield",+ "checkbox",+ "link",+ "slider",+ "combobox",+ "treeitem",+ "cell",+ "radiobutton",+ "tab",+ "menuitem",+ "switch",+ "colorwell",+ "menubutton",+ "incrementor",+ "dockitem",+ ] {+ let n = node(role, None);+ assert!(+ is_ref_able(&n),+ "'{role}' must be ref-able by role alone with no available_actions"+ );+ }+}+#[test]fn allocate_refs_keeps_bounds_in_refmap_when_snapshot_includes_bounds() {let mut root = node("window", Some("w"));diff --git a/crates/core/src/refs.rs b/crates/core/src/refs.rsindex 08b22525a..85da3cd28 100644--- a/crates/core/src/refs.rs+++ b/crates/core/src/refs.rs@@ -285,3 +285,7 @@ pub(crate) fn set_home_override(home: Option<PathBuf>) -> Option<PathBuf> {#[cfg(test)]#[path = "refs_tests.rs"]mod tests;++#[cfg(test)]+#[path = "refs_serde_tests.rs"]+mod serde_tests;diff --git a/crates/core/src/refs_serde_tests.rs b/crates/core/src/refs_serde_tests.rsnew file mode 100644index 000000000..e7b57a89b--- /dev/null+++ b/crates/core/src/refs_serde_tests.rs@@ -0,0 +1,174 @@+use super::*;+use crate::adapter::SnapshotSurface;++fn minimal_entry(role: &str) -> RefEntry {+ RefEntry {+ pid: 1,+ role: role.into(),+ name: None,+ value: None,+ description: None,+ states: vec![],+ bounds: None,+ bounds_hash: None,+ available_actions: vec![],+ source_app: None,+ source_window_id: None,+ source_window_title: None,+ source_surface: SnapshotSurface::Window,+ root_ref: None,+ path_is_absolute: false,+ path: smallvec::SmallVec::new(),+ }+}++/// Fields annotated with `skip_serializing_if` must be absent from the JSON+/// when they hold their zero/empty/default value. Agents parsing the wire+/// format must not break if any of these keys are missing.+#[test]+fn ref_entry_skip_fields_absent_when_none_empty_or_default() {+ let e = minimal_entry("button");+ let json = serde_json::to_string(&e).unwrap();++ assert!(+ !json.contains("\"value\":"),+ "value absent when None, json={json}"+ );+ assert!(+ !json.contains("\"description\":"),+ "description absent when None, json={json}"+ );+ assert!(+ !json.contains("\"states\":"),+ "states absent when empty, json={json}"+ );+ assert!(+ !json.contains("\"bounds\":"),+ "bounds absent when None, json={json}"+ );+ assert!(+ !json.contains("\"source_window_id\":"),+ "source_window_id absent when None, json={json}"+ );+ assert!(+ !json.contains("\"source_window_title\":"),+ "source_window_title absent when None, json={json}"+ );+ assert!(+ !json.contains("\"source_surface\":"),+ "source_surface absent for Window default, json={json}"+ );+ assert!(+ !json.contains("\"root_ref\":"),+ "root_ref absent when None, json={json}"+ );+ assert!(+ !json.contains("\"path_is_absolute\":"),+ "path_is_absolute absent when false, json={json}"+ );+ assert!(+ !json.contains("\"path\":"),+ "path absent when empty, json={json}"+ );+}++/// SnapshotSurface::Window is omitted from RefEntry JSON because it is the+/// default surface. A non-Window surface must appear as its snake_case string.+/// This pins the #[serde(skip_serializing_if = "SnapshotSurface::is_window")]+/// annotation on RefEntry.source_surface.+#[test]+fn ref_entry_source_surface_omitted_for_window_present_for_non_window() {+ let window_entry = minimal_entry("button");+ let window_json = serde_json::to_string(&window_entry).unwrap();+ assert!(+ !window_json.contains("\"source_surface\":"),+ "Window surface must be omitted as the default, json={window_json}"+ );++ let alert_entry = RefEntry {+ source_surface: SnapshotSurface::Alert,+ ..minimal_entry("button")+ };+ let alert_json = serde_json::to_string(&alert_entry).unwrap();+ assert!(+ alert_json.contains("\"source_surface\":\"alert\""),+ "Alert surface must serialize to 'alert', json={alert_json}"+ );++ let menu_entry = RefEntry {+ source_surface: SnapshotSurface::Menu,+ ..minimal_entry("button")+ };+ let menu_json = serde_json::to_string(&menu_entry).unwrap();+ assert!(+ menu_json.contains("\"source_surface\":\"menu\""),+ "Menu surface must serialize to 'menu', json={menu_json}"+ );+}++/// Every SnapshotSurface variant must serialize to its snake_case string+/// and round-trip through serde. This pins the wire format against accidental+/// rename and confirms #[non_exhaustive] has not changed existing variant names.+#[test]+fn snapshot_surface_serializes_to_snake_case_and_roundtrips() {+ let cases = [+ (SnapshotSurface::Window, "\"window\""),+ (SnapshotSurface::Focused, "\"focused\""),+ (SnapshotSurface::Menu, "\"menu\""),+ (SnapshotSurface::Menubar, "\"menubar\""),+ (SnapshotSurface::Sheet, "\"sheet\""),+ (SnapshotSurface::Popover, "\"popover\""),+ (SnapshotSurface::Alert, "\"alert\""),+ ];+ for (variant, expected_json) in cases {+ let serialized = serde_json::to_string(&variant).unwrap();+ assert_eq!(+ serialized, expected_json,+ "wrong wire string for {variant:?}"+ );+ let back: SnapshotSurface = serde_json::from_str(&serialized).unwrap();+ assert_eq!(back, variant, "round-trip failed for {variant:?}");+ }+}++/// RefEntry serializes and deserializes back to the same field values.+/// Uses field-by-field comparison because RefEntry does not derive PartialEq.+#[test]+fn ref_entry_full_roundtrip_preserves_all_fields() {+ let original = RefEntry {+ pid: 99,+ role: "textfield".into(),+ name: Some("Email".into()),+ value: Some("[email protected]".into()),+ description: Some("Enter email".into()),+ states: vec!["focused".into()],+ bounds: None,+ bounds_hash: Some(0xDEAD_BEEF),+ available_actions: vec!["SetValue".into(), "Click".into()],+ source_app: Some("Mail".into()),+ source_window_id: Some("w-7".into()),+ source_window_title: Some("Compose".into()),+ source_surface: SnapshotSurface::Sheet,+ root_ref: Some("@e5".into()),+ path_is_absolute: true,+ path: smallvec::SmallVec::from_slice(&[2, 0, 1]),+ };+ let json = serde_json::to_string(&original).unwrap();+ let back: RefEntry = serde_json::from_str(&json).unwrap();++ assert_eq!(back.pid, original.pid);+ assert_eq!(back.role, original.role);+ assert_eq!(back.name, original.name);+ assert_eq!(back.value, original.value);+ assert_eq!(back.description, original.description);+ assert_eq!(back.states, original.states);+ assert_eq!(back.bounds_hash, original.bounds_hash);+ assert_eq!(back.available_actions, original.available_actions);+ assert_eq!(back.source_app, original.source_app);+ assert_eq!(back.source_window_id, original.source_window_id);+ assert_eq!(back.source_window_title, original.source_window_title);+ assert_eq!(back.source_surface, original.source_surface);+ assert_eq!(back.root_ref, original.root_ref);+ assert_eq!(back.path_is_absolute, original.path_is_absolute);+ assert_eq!(back.path.as_slice(), original.path.as_slice());+}diff --git a/crates/ffi/src/commands/mod.rs b/crates/ffi/src/commands/mod.rsindex 1b79ca097..5b3d093af 100644--- a/crates/ffi/src/commands/mod.rs+++ b/crates/ffi/src/commands/mod.rs@@ -14,3 +14,48 @@ pub(crate) fn app_error_to_adapter(err: AppError) -> AdapterError {AppError::Internal(msg) => AdapterError::new(ErrorCode::Internal, msg),}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn adapter_variant_passes_through_with_original_code_and_message() {+ let ae = AdapterError::stale_ref("@e42");+ let original_code = ae.code.clone();+ let original_msg = ae.message.clone();+ let result = app_error_to_adapter(AppError::Adapter(ae));+ assert_eq!(result.code, original_code);+ assert_eq!(result.message, original_msg);+ }++ #[test]+ fn io_error_collapses_to_internal_and_embeds_os_message() {+ let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file gone");+ let result = app_error_to_adapter(AppError::Io(io_err));+ assert_eq!(result.code, ErrorCode::Internal);+ assert!(+ result.message.contains("file gone"),+ "IO message must be forwarded; got: {:?}",+ result.message+ );+ }++ #[test]+ fn json_error_collapses_to_internal_with_non_empty_message() {+ let json_err = serde_json::from_str::<serde_json::Value>("not json").unwrap_err();+ let result = app_error_to_adapter(AppError::Json(json_err));+ assert_eq!(result.code, ErrorCode::Internal);+ assert!(+ !result.message.is_empty(),+ "JSON parse error message must be forwarded"+ );+ }++ #[test]+ fn internal_string_collapses_to_internal_preserving_exact_message() {+ let result = app_error_to_adapter(AppError::Internal("unexpected state".into()));+ assert_eq!(result.code, ErrorCode::Internal);+ assert_eq!(result.message, "unexpected state");+ }+}diff --git a/crates/ffi/src/convert/notification.rs b/crates/ffi/src/convert/notification.rsindex bedadb996..44cfb3c37 100644--- a/crates/ffi/src/convert/notification.rs+++ b/crates/ffi/src/convert/notification.rs@@ -57,3 +57,78 @@ unsafe fn free_c_string_array(arr: *mut *mut c_char, count: u32) {)));}}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::convert::string::c_to_string;+ use agent_desktop_core::notification::NotificationInfo;+ use std::os::raw::c_char;++ fn make_info(body: Option<&str>, actions: &[&str]) -> NotificationInfo {+ NotificationInfo {+ index: 3,+ app_name: "Messages".into(),+ title: "Hello".into(),+ body: body.map(str::to_owned),+ actions: actions.iter().map(|s| s.to_string()).collect(),+ }+ }++ #[test]+ fn full_notification_maps_all_fields_to_c() {+ let info = make_info(Some("world"), &["Reply", "Mark as Read"]);+ let mut c = notification_info_to_c(&info);+ assert_eq!(c.index, 3);+ assert_eq!(+ unsafe { c_to_string(c.app_name) }.as_deref(),+ Some("Messages")+ );+ assert_eq!(unsafe { c_to_string(c.title) }.as_deref(), Some("Hello"));+ assert_eq!(unsafe { c_to_string(c.body) }.as_deref(), Some("world"));+ assert_eq!(c.action_count, 2);+ assert!(!c.actions.is_null());+ let actions = unsafe { std::slice::from_raw_parts(c.actions, c.action_count as usize) };+ assert_eq!(+ unsafe { c_to_string(actions[0] as *const c_char) }.as_deref(),+ Some("Reply")+ );+ assert_eq!(+ unsafe { c_to_string(actions[1] as *const c_char) }.as_deref(),+ Some("Mark as Read")+ );+ unsafe { free_notification_info_fields(&mut c) };+ }++ #[test]+ fn body_none_maps_to_null_body_pointer() {+ let info = make_info(None, &[]);+ let mut c = notification_info_to_c(&info);+ assert!(c.body.is_null(), "None body must yield null body pointer");+ unsafe { free_notification_info_fields(&mut c) };+ }++ #[test]+ fn empty_actions_maps_to_null_pointer_and_zero_count() {+ let info = make_info(None, &[]);+ let mut c = notification_info_to_c(&info);+ assert!(+ c.actions.is_null(),+ "empty actions slice must yield null actions pointer"+ );+ assert_eq!(c.action_count, 0);+ unsafe { free_notification_info_fields(&mut c) };+ }++ #[test]+ fn free_notification_info_fields_nulls_all_pointer_fields() {+ let info = make_info(Some("body text"), &["Open"]);+ let mut c = notification_info_to_c(&info);+ unsafe { free_notification_info_fields(&mut c) };+ assert!(c.app_name.is_null());+ assert!(c.title.is_null());+ assert!(c.body.is_null());+ assert!(c.actions.is_null());+ assert_eq!(c.action_count, 0);+ }+}diff --git a/crates/ffi/src/convert/string.rs b/crates/ffi/src/convert/string.rsindex c549653f8..8e86c1d5a 100644--- a/crates/ffi/src/convert/string.rs+++ b/crates/ffi/src/convert/string.rs@@ -253,4 +253,42 @@ mod tests {.starts_with("name exceeds AD_MAX_STRING_BYTES"));}++ #[test]+ fn empty_c_string_decodes_as_some_empty_not_none() {+ let c = string_to_c("");+ assert!(!c.is_null());+ let result = unsafe { try_c_to_string(c) };+ assert!(+ matches!(result, Ok(Some(ref s)) if s.is_empty()),+ "empty C string must be Some(\"\"), not None (null) or Err"+ );+ unsafe { free_c_string(c) };+ }++ #[test]+ fn c_to_string_empty_string_is_some_empty_not_none() {+ let c = string_to_c("");+ assert_eq!(+ unsafe { c_to_string(c) }.as_deref(),+ Some(""),+ "c_to_string on \"\" must yield Some(\"\"), distinguishable from null→None"+ );+ unsafe { free_c_string(c) };+ }++ #[test]+ fn required_adapter_string_null_ptr_returns_err_naming_the_field() {+ let err = required_adapter_string(ptr::null(), "app_name").unwrap_err();+ assert_eq!(err.code, agent_desktop_core::error::ErrorCode::InvalidArgs);+ assert_eq!(err.message, "app_name is null");+ }++ #[test]+ fn optional_adapter_string_invalid_utf8_returns_err_naming_the_field() {+ let bad: [u8; 3] = [0xFF, 0xFE, 0x00];+ let err = optional_adapter_string(bad.as_ptr() as *const c_char, "role").unwrap_err();+ assert_eq!(err.code, agent_desktop_core::error::ErrorCode::InvalidArgs);+ assert_eq!(err.message, "role is not valid UTF-8");+ }}diff --git a/crates/ffi/src/convert/surface.rs b/crates/ffi/src/convert/surface.rsindex 93fbf9916..212586646 100644--- a/crates/ffi/src/convert/surface.rs+++ b/crates/ffi/src/convert/surface.rs@@ -78,4 +78,70 @@ mod tests {assert_eq!(err.code, ErrorCode::InvalidArgs);assert_eq!(err.message, "invalid source_surface discriminant");}++ #[test]+ fn item_count_none_maps_to_sentinel_minus_one() {+ let s = SurfaceInfo {+ kind: "menu".into(),+ title: None,+ item_count: None,+ };+ let c = surface_info_to_c(&s);+ assert_eq!(c.item_count, -1);+ let mut c = c;+ unsafe { free_surface_info_fields(&mut c) };+ }++ #[test]+ fn item_count_some_zero_maps_to_zero_not_to_absent_sentinel() {+ let s = SurfaceInfo {+ kind: "popover".into(),+ title: None,+ item_count: Some(0),+ };+ let c = surface_info_to_c(&s);+ assert_eq!(+ c.item_count, 0,+ "Some(0) must map to 0, not to the -1 absent sentinel"+ );+ let mut c = c;+ unsafe { free_surface_info_fields(&mut c) };+ }++ #[test]+ fn title_some_maps_to_non_null_c_string_with_correct_value() {+ let s = SurfaceInfo {+ kind: "sheet".into(),+ title: Some("Save Panel".into()),+ item_count: None,+ };+ let c = surface_info_to_c(&s);+ assert!(!c.title.is_null());+ assert_eq!(+ unsafe { c_to_string(c.title) }.as_deref(),+ Some("Save Panel")+ );+ let mut c = c;+ unsafe { free_surface_info_fields(&mut c) };+ }++ #[test]+ fn snapshot_surface_from_c_maps_all_seven_variants_exactly() {+ let cases: [(i32, SnapshotSurface); 7] = [+ (0, SnapshotSurface::Window),+ (1, SnapshotSurface::Focused),+ (2, SnapshotSurface::Menu),+ (3, SnapshotSurface::Menubar),+ (4, SnapshotSurface::Sheet),+ (5, SnapshotSurface::Popover),+ (6, SnapshotSurface::Alert),+ ];+ for (raw, expected) in cases {+ assert_eq!(+ snapshot_surface_from_c(raw, "kind").unwrap(),+ expected,+ "raw discriminant {raw} must map to {expected:?}"+ );+ }+ }}diff --git a/crates/ffi/src/convert/window.rs b/crates/ffi/src/convert/window.rsindex 4f14dccf5..601acd9bb 100644--- a/crates/ffi/src/convert/window.rs+++ b/crates/ffi/src/convert/window.rs@@ -78,4 +78,28 @@ mod tests {let mut c = c;unsafe { free_window_info_fields(&mut c) };}++ #[test]+ fn window_info_to_c_bounds_none_sets_false_flag_and_zeroed_rect() {+ let w = WindowInfo {+ id: "w-7".into(),+ title: "Untitled".into(),+ app: "TextEdit".into(),+ pid: 99,+ bounds: None,+ is_focused: false,+ };+ let c = window_info_to_c(&w);+ assert!(+ !c.has_bounds,+ "has_bounds must be false when bounds is None"+ );+ assert!(!c.is_focused);+ assert_eq!(c.bounds.x, 0.0);+ assert_eq!(c.bounds.y, 0.0);+ assert_eq!(c.bounds.width, 0.0);+ assert_eq!(c.bounds.height, 0.0);+ let mut c = c;+ unsafe { free_window_info_fields(&mut c) };+ }}diff --git a/crates/ffi/src/enum_validation.rs b/crates/ffi/src/enum_validation.rsindex b2430b9a0..fd11ed939 100644--- a/crates/ffi/src/enum_validation.rs+++ b/crates/ffi/src/enum_validation.rs@@ -180,4 +180,64 @@ mod tests {let _ = AdScreenshotKind::from_c(raw);}}++ #[test]+ fn action_kind_boundary_discriminants_map_to_exact_variants() {+ assert_eq!(AdActionKind::from_c(0), Some(AdActionKind::Click));+ assert_eq!(AdActionKind::from_c(20), Some(AdActionKind::Drag));+ }++ #[test]+ fn direction_boundary_discriminants_map_to_exact_variants() {+ assert_eq!(AdDirection::from_c(0), Some(AdDirection::Up));+ assert_eq!(AdDirection::from_c(3), Some(AdDirection::Right));+ }++ #[test]+ fn policy_kind_boundary_discriminants_map_to_exact_variants() {+ assert_eq!(AdPolicyKind::from_c(0), Some(AdPolicyKind::Headless));+ assert_eq!(AdPolicyKind::from_c(2), Some(AdPolicyKind::Headed));+ }++ #[test]+ fn modifier_boundary_discriminants_map_to_exact_variants() {+ assert_eq!(AdModifier::from_c(0), Some(AdModifier::Cmd));+ assert_eq!(AdModifier::from_c(3), Some(AdModifier::Shift));+ }++ #[test]+ fn mouse_button_boundary_discriminants_map_to_exact_variants() {+ assert_eq!(AdMouseButton::from_c(0), Some(AdMouseButton::Left));+ assert_eq!(AdMouseButton::from_c(2), Some(AdMouseButton::Middle));+ }++ #[test]+ fn mouse_event_kind_boundary_discriminants_map_to_exact_variants() {+ assert_eq!(AdMouseEventKind::from_c(0), Some(AdMouseEventKind::Move));+ assert_eq!(AdMouseEventKind::from_c(3), Some(AdMouseEventKind::Click));+ }++ #[test]+ fn window_op_kind_boundary_discriminants_map_to_exact_variants() {+ assert_eq!(AdWindowOpKind::from_c(0), Some(AdWindowOpKind::Resize));+ assert_eq!(AdWindowOpKind::from_c(4), Some(AdWindowOpKind::Restore));+ }++ #[test]+ fn screenshot_kind_boundary_discriminants_map_to_exact_variants() {+ assert_eq!(AdScreenshotKind::from_c(0), Some(AdScreenshotKind::Screen));+ assert_eq!(+ AdScreenshotKind::from_c(2),+ Some(AdScreenshotKind::FullScreen)+ );+ }++ #[test]+ fn snapshot_surface_boundary_discriminants_map_to_exact_variants() {+ assert_eq!(+ AdSnapshotSurface::from_c(0),+ Some(AdSnapshotSurface::Window)+ );+ assert_eq!(AdSnapshotSurface::from_c(6), Some(AdSnapshotSurface::Alert));+ }}diff --git a/crates/macos/src/actions/ax_helpers.rs b/crates/macos/src/actions/ax_helpers.rsindex 48989830f..068e9c0cf 100644--- a/crates/macos/src/actions/ax_helpers.rs+++ b/crates/macos/src/actions/ax_helpers.rs@@ -164,7 +164,13 @@ mod imp {}pub(crate) fn set_messaging_timeout(el: &AXElement, seconds: f32) {- unsafe { AXUIElementSetMessagingTimeout(el.0, seconds) };+ let err = unsafe { AXUIElementSetMessagingTimeout(el.0, seconds) };+ if err != kAXErrorSuccess {+ tracing::warn!(+ err,+ "AXUIElementSetMessagingTimeout failed; AX calls may use the default timeout"+ );+ }}pub(crate) fn ax_focus_or_err(el: &AXElement) -> Result<bool, AdapterError> {@@ -248,6 +254,14 @@ mod imp {.map(|r| crate::tree::roles::ax_role_to_str(&r).to_string())}+ /// Soft-error gate for AX API return codes.+ ///+ /// Only `kAXErrorAPIDisabled` is promoted to a hard error (permission denied).+ /// All other codes — including `kAXErrorInvalidUIElement` — intentionally+ /// return `Ok(())` so that action-chain steps fall through to the next+ /// strategy or physical fallback instead of aborting the whole chain.+ /// Genuine staleness is caught earlier at resolve time (`STALE_REF`);+ /// re-escalating other codes here requires a chain-level stale detector first.fn ax_error_result(operation: &str, err: i32) -> Result<(), AdapterError> {if err == kAXErrorAPIDisabled {return Err(AdapterError::permission_denied()@@ -255,6 +269,43 @@ mod imp {}Ok(())}++ #[cfg(test)]+ mod tests {+ use accessibility_sys::{+ kAXErrorAPIDisabled, kAXErrorCannotComplete, kAXErrorInvalidUIElement, kAXErrorSuccess,+ };+ use agent_desktop_core::error::ErrorCode;++ use super::ax_error_result;++ #[test]+ fn success_code_is_ok() {+ ax_error_result("op", kAXErrorSuccess).unwrap();+ }++ #[test]+ fn api_disabled_yields_perm_denied() {+ let err = ax_error_result("press", kAXErrorAPIDisabled).unwrap_err();+ assert_eq!(err.code, ErrorCode::PermDenied);+ assert!(+ err.platform_detail+ .as_deref()+ .unwrap()+ .contains("kAXErrorAPIDisabled")+ );+ }++ #[test]+ fn invalid_ui_element_is_soft_ok_so_chains_fall_through() {+ ax_error_result("press", kAXErrorInvalidUIElement).unwrap();+ }++ #[test]+ fn unrecognised_ax_code_is_soft_ok() {+ ax_error_result("op", kAXErrorCannotComplete).unwrap();+ }+ }}#[cfg(not(target_os = "macos"))]diff --git a/crates/macos/src/actions/chain_defs.rs b/crates/macos/src/actions/chain_defs.rsindex f2f80fea2..c406cbb8d 100644--- a/crates/macos/src/actions/chain_defs.rs+++ b/crates/macos/src/actions/chain_defs.rs@@ -190,6 +190,10 @@ mod imp {crate::actions::dispatch::click_via_bounds(el, MouseButton::Left, 2, policy)}+ /// Triple-click has no AX semantic equivalent on macOS and is therefore+ /// unconditionally physical: it always requires cursor-move + focus-steal+ /// policy. Callers that gate on `allow_cursor_move` will receive a+ /// `PolicyDenied` error from `click_via_bounds` rather than a silent no-op.pub(crate) fn triple_click(el: &AXElement,policy: InteractionPolicy,diff --git a/crates/macos/src/actions/chain_steps.rs b/crates/macos/src/actions/chain_steps.rsindex 7b35debd6..7bdc4ae3e 100644--- a/crates/macos/src/actions/chain_steps.rs+++ b/crates/macos/src/actions/chain_steps.rs@@ -93,7 +93,9 @@ mod imp {std::thread::sleep(std::time::Duration::from_millis(150));if !ax_helpers::try_ax_action_retried_or_err(&owner, "AXConfirm")? {if let Some(o) = &orig {- let _ = ax_helpers::set_ax_string_or_err(&owner, "AXValue", o);+ if let Err(e) = ax_helpers::set_ax_string_or_err(&owner, "AXValue", o) {+ tracing::warn!(error = %e, "value_relay: rollback write failed; control may have corrupted value");+ }}return Ok(false);}diff --git a/crates/macos/src/actions/dispatch.rs b/crates/macos/src/actions/dispatch.rsindex 3767cb9ee..9c8e8e48c 100644--- a/crates/macos/src/actions/dispatch.rs+++ b/crates/macos/src/actions/dispatch.rs@@ -30,7 +30,7 @@ mod imp {));}if let Some(pid) = crate::system::app_ops::pid_from_element(el) {- let _ = crate::system::app_ops::ensure_app_focused(pid);+ crate::system::app_ops::focus_best_effort(pid);}if let Some(window) = crate::tree::copy_element_attr(el, "AXWindow") {crate::system::window_ops::raise_window(&window);diff --git a/crates/macos/src/actions/scroll.rs b/crates/macos/src/actions/scroll.rsindex 9b0a102ba..3ad906248 100644--- a/crates/macos/src/actions/scroll.rs+++ b/crates/macos/src/actions/scroll.rs@@ -24,7 +24,14 @@ pub(crate) fn ax_scroll(let target = scroll_area.as_ref().unwrap_or(el);let scroll_visible = CFString::new("AXScrollToVisible");- unsafe { AXUIElementPerformAction(el.0, scroll_visible.as_concrete_TypeRef()) };+ let scroll_visible_err =+ unsafe { AXUIElementPerformAction(el.0, scroll_visible.as_concrete_TypeRef()) };+ if scroll_visible_err != kAXErrorSuccess {+ tracing::debug!(+ ax_error = scroll_visible_err,+ "AXScrollToVisible returned non-success; continuing to next scroll strategy"+ );+ }let (bar_attr, inc_action) = match direction {Direction::Down => ("AXVerticalScrollBar", "AXIncrement"),@@ -95,7 +102,7 @@ pub(crate) fn ax_scroll(Direction::Right => 124,Direction::Left => 123,};- let _ = crate::system::app_ops::ensure_app_focused(pid);+ crate::system::app_ops::focus_best_effort(pid);let cf_focused = CFString::new("AXFocused");let focus_err = unsafe {AXUIElementSetAttributeValue(@@ -114,7 +121,7 @@ pub(crate) fn ax_scroll(if policy.allow_focus_steal && policy.allow_cursor_move {if let Some(pid) = crate::system::app_ops::pid_from_element(el) {- let _ = crate::system::app_ops::ensure_app_focused(pid);+ crate::system::app_ops::focus_best_effort(pid);if let Some(b) = crate::tree::read_bounds(target) {let (dy, dx) = scroll_wheel_delta(direction, amount);return crate::input::mouse::synthesize_scroll_at(diff --git a/crates/macos/src/actions/type_text.rs b/crates/macos/src/actions/type_text.rsindex 6c3f50439..4e7f47b5d 100644--- a/crates/macos/src/actions/type_text.rs+++ b/crates/macos/src/actions/type_text.rs@@ -41,7 +41,9 @@ struct ClipboardRestore {#[cfg(target_os = "macos")]impl Drop for ClipboardRestore {fn drop(&mut self) {- let _ = self.previous.restore();+ if let Err(e) = self.previous.restore() {+ tracing::warn!(error = %e, "clipboard restore failed after type_text; prior clipboard may not be restored");+ }}}@@ -126,9 +128,24 @@ fn readable_value(el: &AXElement) -> Option<String> {}}+/// Checks whether a clipboard paste changed the element's visible value.+///+/// When `before` was readable but `after` is `None`, returns `Ok(())` rather+/// than an error: the post-paste read reuses the same element handle, which+/// can go stale after a successful paste in re-rendering UIs (Electron/web —+/// documented targets). Failing here would cause false-failure → agent retry+/// → double-paste corruption. The unverifiable case is therefore treated as+/// success; revisit only by re-resolving the element before failing.#[cfg(target_os = "macos")]fn verify_paste_effect(before: Option<&str>, after: Option<&str>) -> Result<(), AdapterError> {- if before.is_none() || after.is_none() || before != after {+ if before.is_none() {+ return Ok(());+ }+ if after.is_none() {+ tracing::warn!("paste could not be verified: post-paste field value is unreadable");+ return Ok(());+ }+ if before != after {return Ok(());}Err(AdapterError::new(diff --git a/crates/macos/src/adapter.rs b/crates/macos/src/adapter.rsindex f7e1716d1..5e9623dd0 100644--- a/crates/macos/src/adapter.rs+++ b/crates/macos/src/adapter.rs@@ -61,6 +61,7 @@ impl PlatformAdapter for MacOSAdapter {.ok_or_else(|| AdapterError::element_not_found("No visible popover"))?,SnapshotSurface::Alert => crate::tree::surfaces::alert_for_pid(win.pid).ok_or_else(|| AdapterError::element_not_found("No open alert or dialog"))?,+ _ => return Err(AdapterError::not_supported("snapshot surface")),};let mut visited = FxHashSet::default();let context = crate::tree::TreeBuildContext::for_pid(win.pid, opts.include_bounds);@@ -135,6 +136,10 @@ impl PlatformAdapter for MacOSAdapter {crate::system::app_ops::is_protected_process(identifier)}+ fn is_blocked_combo(&self, combo: &agent_desktop_core::action::KeyCombo) -> bool {+ crate::input::blocked_combo::is_blocked(combo)+ }+fn screenshot(&self, target: ScreenshotTarget) -> Result<ImageBuffer, AdapterError> {match target {ScreenshotTarget::Window(pid) => crate::system::screenshot::capture_app(pid),diff --git a/crates/macos/src/input/blocked_combo.rs b/crates/macos/src/input/blocked_combo.rsnew file mode 100644index 000000000..6105c729f--- /dev/null+++ b/crates/macos/src/input/blocked_combo.rs@@ -0,0 +1,69 @@+use agent_desktop_core::action::{KeyCombo, Modifier};++const BLOCKED: &[&str] = &[+ "cmd+q",+ "cmd+shift+q",+ "cmd+alt+esc",+ "ctrl+cmd+q",+ "cmd+shift+delete",+];++/// Reports whether `combo` is one of the macOS shortcuts that would quit, log+/// out, force-quit, or lock the session. Comparison is canonical, so every+/// modifier order and key-name alias of a blocked shortcut is caught. The+/// calling agent can still send any of these by passing `--force`.+pub(crate) fn is_blocked(combo: &KeyCombo) -> bool {+ let target = canonical(&combo_to_string(combo));+ BLOCKED.iter().any(|entry| canonical(entry) == target)+}++fn combo_to_string(combo: &KeyCombo) -> String {+ let mut parts: Vec<&str> = combo.modifiers.iter().map(modifier_name).collect();+ parts.push(combo.key.as_str());+ parts.join("+")+}++fn modifier_name(modifier: &Modifier) -> &'static str {+ match modifier {+ Modifier::Cmd => "cmd",+ Modifier::Ctrl => "ctrl",+ Modifier::Alt => "alt",+ Modifier::Shift => "shift",+ }+}++/// Canonicalizes a `mod+...+key` string for safety comparison: modifier names+/// are normalized and sorted (order-independent), and key names are folded to a+/// single spelling per physical key (macOS aliases esc/escape, delete/backspace,+/// enter/return), so every spelling and ordering of a blocked shortcut matches.+fn canonical(raw: &str) -> String {+ let lower = raw.to_lowercase();+ let mut mods: Vec<&str> = Vec::new();+ let mut key = "";+ for part in lower.split('+') {+ match part {+ "cmd" | "command" => mods.push("cmd"),+ "ctrl" | "control" => mods.push("ctrl"),+ "alt" | "option" => mods.push("alt"),+ "shift" => mods.push("shift"),+ other => key = canonical_key(other),+ }+ }+ mods.sort_unstable();+ mods.dedup();+ mods.push(key);+ mods.join("+")+}++fn canonical_key(key: &str) -> &str {+ match key {+ "escape" | "esc" => "esc",+ "backspace" | "delete" => "delete",+ "enter" | "return" => "return",+ other => other,+ }+}++#[cfg(test)]+#[path = "blocked_combo_tests.rs"]+mod tests;diff --git a/crates/macos/src/input/blocked_combo_tests.rs b/crates/macos/src/input/blocked_combo_tests.rsnew file mode 100644index 000000000..b1194426c--- /dev/null+++ b/crates/macos/src/input/blocked_combo_tests.rs@@ -0,0 +1,60 @@+use super::is_blocked;+use agent_desktop_core::action::{KeyCombo, Modifier};++fn combo(modifiers: Vec<Modifier>, key: &str) -> KeyCombo {+ KeyCombo {+ key: key.to_owned(),+ modifiers,+ }+}++#[test]+fn dangerous_shortcuts_are_blocked() {+ assert!(is_blocked(&combo(vec![Modifier::Cmd], "q")));+ assert!(is_blocked(&combo(+ vec![Modifier::Cmd, Modifier::Shift],+ "q"+ )));+ assert!(is_blocked(&combo(+ vec![Modifier::Cmd, Modifier::Alt],+ "esc"+ )));+ assert!(is_blocked(&combo(vec![Modifier::Ctrl, Modifier::Cmd], "q")));+ assert!(is_blocked(&combo(+ vec![Modifier::Cmd, Modifier::Shift],+ "delete"+ )));+}++#[test]+fn modifier_order_does_not_matter() {+ assert!(+ is_blocked(&combo(vec![Modifier::Cmd, Modifier::Ctrl], "q")),+ "cmd+ctrl+q must match the blocked ctrl+cmd+q regardless of order"+ );+}++#[test]+fn key_aliases_are_blocked() {+ assert!(+ is_blocked(&combo(vec![Modifier::Cmd, Modifier::Alt], "escape")),+ "escape is the same physical key as esc"+ );+ assert!(+ is_blocked(&combo(vec![Modifier::Cmd, Modifier::Shift], "backspace")),+ "backspace is the same physical key as delete"+ );+}++#[test]+fn benign_combos_are_not_blocked() {+ assert!(!is_blocked(&combo(vec![Modifier::Cmd], "c")));+ assert!(!is_blocked(&combo(vec![Modifier::Cmd], "v")));+ assert!(!is_blocked(&combo(vec![Modifier::Cmd], "w")));+ assert!(!is_blocked(&combo(+ vec![Modifier::Cmd, Modifier::Shift],+ "r"+ )));+ assert!(!is_blocked(&combo(vec![Modifier::Ctrl], "s")));+ assert!(!is_blocked(&combo(vec![], "return")));+}diff --git a/crates/macos/src/input/clipboard.rs b/crates/macos/src/input/clipboard.rsindex c4fc89275..f2acd5b7c 100644--- a/crates/macos/src/input/clipboard.rs+++ b/crates/macos/src/input/clipboard.rs@@ -26,7 +26,7 @@ mod imp {unsafe {let pb = pasteboard()?;Ok(Self {- items: retain_pasteboard_items(pb),+ items: deep_copy_pasteboard_items(pb),})}}@@ -36,6 +36,9 @@ mod imp {let pb = pasteboard()?;clear_pasteboard(pb);if !self.items.is_null() && !write_objects(pb, self.items) {+ tracing::warn!(+ "clipboard restore failed after clearContents; original clipboard content is lost"+ );return Err(AdapterError::internal("NSPasteboard writeObjects: failed"));}Ok(())@@ -120,24 +123,109 @@ mod imp {}}- unsafe fn retain_pasteboard_items(pb: Id) -> Id {+ unsafe fn deep_copy_pasteboard_items(pb: Id) -> Id {unsafe {- let items_sel = sel_registerName(c"pasteboardItems".as_ptr());+ let alloc_sel = sel_registerName(c"alloc".as_ptr());+ let init_sel = sel_registerName(c"init".as_ptr());let send: unsafe extern "C" fn(Id, Sel) -> Id =std::mem::transmute(objc_msgSend as *const c_void);- retain_object(send(pb, items_sel))- }- }- unsafe fn retain_object(object: Id) -> Id {- if object.is_null() {- return object;- }- unsafe {- let sel = sel_registerName(c"retain".as_ptr());- let send: unsafe extern "C" fn(Id, Sel) -> Id =+ let ma_cls = objc_getClass(c"NSMutableArray".as_ptr());+ if ma_cls.is_null() {+ return std::ptr::null_mut();+ }+ let ma_alloc = send(ma_cls as Id, alloc_sel);+ if ma_alloc.is_null() {+ return std::ptr::null_mut();+ }+ let mutable_array = send(ma_alloc, init_sel);+ if mutable_array.is_null() {+ return std::ptr::null_mut();+ }++ let items_sel = sel_registerName(c"pasteboardItems".as_ptr());+ let pb_items = send(pb, items_sel);+ if pb_items.is_null() {+ release_object(mutable_array);+ return std::ptr::null_mut();+ }++ let count_sel = sel_registerName(c"count".as_ptr());+ let send_usize: unsafe extern "C" fn(Id, Sel) -> usize =+ std::mem::transmute(objc_msgSend as *const c_void);+ let item_count = send_usize(pb_items, count_sel);++ let idx_sel = sel_registerName(c"objectAtIndex:".as_ptr());+ let send_at_idx: unsafe extern "C" fn(Id, Sel, usize) -> Id =+ std::mem::transmute(objc_msgSend as *const c_void);++ let types_sel = sel_registerName(c"types".as_ptr());+ let data_sel = sel_registerName(c"dataForType:".as_ptr());+ let send_with_id: unsafe extern "C" fn(Id, Sel, Id) -> Id =+ std::mem::transmute(objc_msgSend as *const c_void);++ let set_data_sel = sel_registerName(c"setData:forType:".as_ptr());+ let send_set_data: unsafe extern "C" fn(Id, Sel, Id, Id) -> bool =std::mem::transmute(objc_msgSend as *const c_void);- send(object, sel)++ let add_sel = sel_registerName(c"addObject:".as_ptr());+ let send_add: unsafe extern "C" fn(Id, Sel, Id) =+ std::mem::transmute(objc_msgSend as *const c_void);++ let pbi_cls = objc_getClass(c"NSPasteboardItem".as_ptr());+ if pbi_cls.is_null() {+ release_object(mutable_array);+ return std::ptr::null_mut();+ }++ let mut added = false;+ for i in 0..item_count {+ let orig_item = send_at_idx(pb_items, idx_sel, i);+ if orig_item.is_null() {+ continue;+ }++ let types = send(orig_item, types_sel);+ if types.is_null() {+ continue;+ }++ let type_count = send_usize(types, count_sel);+ if type_count == 0 {+ continue;+ }++ let fresh_alloc = send(pbi_cls as Id, alloc_sel);+ if fresh_alloc.is_null() {+ continue;+ }+ let fresh_item = send(fresh_alloc, init_sel);+ if fresh_item.is_null() {+ continue;+ }++ for j in 0..type_count {+ let type_str = send_at_idx(types, idx_sel, j);+ if type_str.is_null() {+ continue;+ }+ let data = send_with_id(orig_item, data_sel, type_str);+ if data.is_null() {+ continue;+ }+ let _ = send_set_data(fresh_item, set_data_sel, data, type_str);+ }++ send_add(mutable_array, add_sel, fresh_item);+ release_object(fresh_item);+ added = true;+ }++ if !added {+ release_object(mutable_array);+ return std::ptr::null_mut();+ }+ mutable_array}}diff --git a/crates/macos/src/input/keyboard.rs b/crates/macos/src/input/keyboard.rsindex 50d905980..fdaad9951 100644--- a/crates/macos/src/input/keyboard.rs+++ b/crates/macos/src/input/keyboard.rs@@ -39,18 +39,18 @@ mod imp {));}- if !combo.modifiers.is_empty() {- for m in &combo.modifiers {- let mod_code = modifier_keycode(m);- let err = unsafe { AXUIElementPostKeyboardEvent(sys_wide, 0, mod_code, true) };- if err != kAXErrorSuccess {- release_modifiers(sys_wide, &combo.modifiers);- unsafe { core_foundation::base::CFRelease(sys_wide as _) };- return Err(AdapterError::internal(format!(- "AXUIElementPostKeyboardEvent modifier-down failed (err={err})"- )));- }+ let mut pressed_mods = Vec::new();+ for m in &combo.modifiers {+ let mod_code = modifier_keycode(m);+ let err = unsafe { AXUIElementPostKeyboardEvent(sys_wide, 0, mod_code, true) };+ if err != kAXErrorSuccess {+ release_modifiers(sys_wide, &pressed_mods);+ unsafe { core_foundation::base::CFRelease(sys_wide as _) };+ return Err(AdapterError::internal(format!(+ "AXUIElementPostKeyboardEvent modifier-down failed (err={err})"+ )));}+ pressed_mods.push(m.clone());}let err_down = post_event(sys_wide, key_code, true);@@ -68,6 +68,7 @@ mod imp {)));}if err_up != kAXErrorSuccess {+ release_key_system_wide(key_code);return Err(AdapterError::internal(format!("AXUIElementPostKeyboardEvent key-up failed (err={err_up})")));@@ -90,16 +91,33 @@ mod imp {let result = (|| {if down {+ let mut pressed_mods = Vec::new();for m in &combo.modifiers {- post_checked(sys_wide, modifier_keycode(m), true, 0, 1)?;+ if let Err(err) = post_checked(sys_wide, modifier_keycode(m), true, 0, 1) {+ release_modifiers(sys_wide, &pressed_mods);+ return Err(err);+ }+ pressed_mods.push(m.clone());}- post_checked(sys_wide, key_code, true, 0, 1)+ if let Err(err) = post_checked(sys_wide, key_code, true, 0, 1) {+ release_modifiers(sys_wide, &pressed_mods);+ return Err(err);+ }+ Ok(())} else {let key_result = post_checked(sys_wide, key_code, false, 0, 1);+ if key_result.is_err() {+ release_key_system_wide(key_code);+ }+ let mut first_mod_err: Option<AdapterError> = None;for m in combo.modifiers.iter().rev() {- post_checked(sys_wide, modifier_keycode(m), false, 0, 1)?;+ if let Err(err) = post_checked(sys_wide, modifier_keycode(m), false, 0, 1) {+ if first_mod_err.is_none() {+ first_mod_err = Some(err);+ }+ }}- key_result+ key_result.and(first_mod_err.map_or(Ok(()), Err))}})();@@ -191,6 +209,9 @@ mod imp {}}}+ if key_result.is_err() {+ release_key_system_wide(key_code);+ }if key_result.is_err() || release_result.is_err() {release_modifiers_system_wide(&pressed);}@@ -216,6 +237,15 @@ mod imp {unsafe { core_foundation::base::CFRelease(sys_wide as _) };}+ fn release_key_system_wide(key_code: u16) {+ let sys_wide = unsafe { AXUIElementCreateSystemWide() };+ if sys_wide.is_null() {+ return;+ }+ unsafe { AXUIElementPostKeyboardEvent(sys_wide, 0, key_code, false) };+ unsafe { core_foundation::base::CFRelease(sys_wide as _) };+ }+fn post_char_key(el: accessibility_sys::AXUIElementRef,code: u16,diff --git a/crates/macos/src/input/keyboard_map.rs b/crates/macos/src/input/keyboard_map.rsindex fbebb5893..a5a7eeb7f 100644--- a/crates/macos/src/input/keyboard_map.rs+++ b/crates/macos/src/input/keyboard_map.rs@@ -172,3 +172,78 @@ pub(crate) fn key_name_to_code(key: &str) -> Result<u16, AdapterError> {};Ok(code)}++#[cfg(test)]+mod tests {+ use agent_desktop_core::{action::Modifier, error::ErrorCode};++ use super::{char_to_keycode, is_shifted_char, key_name_to_code, modifier_keycode};++ #[test]+ fn modifier_keycodes_match_macos_virtual_key_codes() {+ assert_eq!(modifier_keycode(&Modifier::Cmd), 55);+ assert_eq!(modifier_keycode(&Modifier::Shift), 56);+ assert_eq!(modifier_keycode(&Modifier::Alt), 58);+ assert_eq!(modifier_keycode(&Modifier::Ctrl), 59);+ }++ #[test]+ fn shifted_chars_are_detected() {+ assert!(is_shifted_char('!'));+ assert!(is_shifted_char('@'));+ assert!(is_shifted_char('~'));+ assert!(is_shifted_char('_'));+ assert!(!is_shifted_char('a'));+ assert!(!is_shifted_char('1'));+ assert!(!is_shifted_char('A'));+ assert!(!is_shifted_char(' '));+ }++ #[test]+ fn char_to_keycode_lowercases_before_lookup() {+ assert_eq!(char_to_keycode('a'), Some(0));+ assert_eq!(char_to_keycode('A'), Some(0));+ assert_eq!(char_to_keycode('z'), Some(6));+ assert_eq!(char_to_keycode(' '), Some(49));+ assert_eq!(char_to_keycode('\t'), Some(48));+ }++ #[test]+ fn char_to_keycode_returns_none_for_unmapped_chars() {+ assert_eq!(char_to_keycode('€'), None);+ assert_eq!(char_to_keycode('\n'), None);+ }++ #[test]+ fn named_key_aliases_resolve_to_same_code() {+ assert_eq!(key_name_to_code("return").unwrap(), 36);+ assert_eq!(key_name_to_code("enter").unwrap(), 36);+ assert_eq!(key_name_to_code("escape").unwrap(), 53);+ assert_eq!(key_name_to_code("esc").unwrap(), 53);+ assert_eq!(key_name_to_code("alt").unwrap(), 58);+ assert_eq!(key_name_to_code("option").unwrap(), 58);+ assert_eq!(key_name_to_code("cmd").unwrap(), 55);+ assert_eq!(key_name_to_code("command").unwrap(), 55);+ assert_eq!(key_name_to_code("ctrl").unwrap(), 59);+ assert_eq!(key_name_to_code("control").unwrap(), 59);+ }++ #[test]+ fn navigation_and_function_keys_map_to_expected_codes() {+ assert_eq!(key_name_to_code("f1").unwrap(), 122);+ assert_eq!(key_name_to_code("f12").unwrap(), 111);+ assert_eq!(key_name_to_code("tab").unwrap(), 48);+ assert_eq!(key_name_to_code("delete").unwrap(), 51);+ assert_eq!(key_name_to_code("backspace").unwrap(), 51);+ assert_eq!(key_name_to_code("left").unwrap(), 123);+ assert_eq!(key_name_to_code("up").unwrap(), 126);+ }++ #[test]+ fn unknown_key_name_returns_invalid_args_error_with_suggestion() {+ let err = key_name_to_code("hyperkey").unwrap_err();+ assert_eq!(err.code, ErrorCode::InvalidArgs);+ assert!(err.message.contains("hyperkey"));+ assert!(err.suggestion.is_some());+ }+}diff --git a/crates/macos/src/input/mod.rs b/crates/macos/src/input/mod.rsindex 3b7208696..b8291ff6e 100644--- a/crates/macos/src/input/mod.rs+++ b/crates/macos/src/input/mod.rs@@ -1,3 +1,4 @@+pub(crate) mod blocked_combo;pub mod clipboard;pub mod keyboard;pub(crate) mod keyboard_map;diff --git a/crates/macos/src/input/mouse.rs b/crates/macos/src/input/mouse.rsindex 42c25219b..a9410330d 100644--- a/crates/macos/src/input/mouse.rs+++ b/crates/macos/src/input/mouse.rs@@ -6,7 +6,9 @@ use agent_desktop_core::{#[cfg(target_os = "macos")]mod imp {use super::*;- use core_graphics::event::{CGEvent, CGEventTapLocation, CGEventType, CGMouseButton};+ use core_graphics::event::{+ CGEvent, CGEventTapLocation, CGEventType, CGMouseButton, EventField, ScrollEventUnit,+ };use core_graphics::event_source::{CGEventSource, CGEventSourceStateID};use core_graphics::geometry::CGPoint;@@ -201,17 +203,7 @@ mod imp {}fn set_click_count(event: &CGEvent, count: i64) {- unsafe {- CGEventSetIntegerValueField(- event as *const CGEvent as *const std::ffi::c_void,- 1,- count,- );- }- }-- unsafe extern "C" {- fn CGEventSetIntegerValueField(event: *const std::ffi::c_void, field: u32, value: i64);+ event.set_integer_value_field(EventField::MOUSE_EVENT_CLICK_STATE, count);}fn create_event(@@ -299,7 +291,9 @@ mod imp {fn CGEventPost(tap: u32, event: *mut std::ffi::c_void);}- let event = unsafe { CGEventCreateScrollWheelEvent(std::ptr::null(), 0, 2, dy, dx) };+ let event = unsafe {+ CGEventCreateScrollWheelEvent(std::ptr::null(), ScrollEventUnit::LINE, 2, dy, dx)+ };if event.is_null() {return Err(AdapterError::internal("scroll event creation failed"));}diff --git a/crates/macos/src/notifications/actions.rs b/crates/macos/src/notifications/actions.rsindex 9fb55980c..bbdf088b8 100644--- a/crates/macos/src/notifications/actions.rs+++ b/crates/macos/src/notifications/actions.rs@@ -4,7 +4,7 @@ use agent_desktop_core::{notification::{NotificationFilter, NotificationIdentity, NotificationInfo},};-use super::nc_session::NcSession;+use super::nc_session::{NcSession, close_session};pub fn dismiss_notification(index: usize,@@ -33,18 +33,6 @@ pub fn notification_action(close_session(session, result)}-fn close_session<T>(- session: NcSession,- result: Result<T, AdapterError>,-) -> Result<T, AdapterError> {- let close_result = session.close();- match (result, close_result) {- (Ok(value), Ok(())) => Ok(value),- (Ok(_), Err(err)) => Err(err),- (Err(err), _) => Err(err),- }-}-#[cfg(target_os = "macos")]fn dismiss_impl(index: usize, app_filter: Option<&str>) -> Result<NotificationInfo, AdapterError> {let filter = build_filter(app_filter);@@ -96,6 +84,10 @@ fn dismiss_entry(element: &crate::tree::AXElement) -> Result<(), AdapterError> {return Ok(());}+ if !crate::system::permissions::report().accessibility_granted() {+ return Err(AdapterError::permission_denied());+ }+hover_over(element)?;std::thread::sleep(std::time::Duration::from_millis(300));diff --git a/crates/macos/src/notifications/list.rs b/crates/macos/src/notifications/list.rsindex 5dc5275a6..b1d2b8bbd 100644--- a/crates/macos/src/notifications/list.rs+++ b/crates/macos/src/notifications/list.rs@@ -3,15 +3,14 @@ use agent_desktop_core::{notification::{NotificationFilter, NotificationInfo},};-use super::nc_session::NcSession;+use super::nc_session::{NcSession, close_session};pub fn list_notifications(filter: &NotificationFilter,) -> Result<Vec<NotificationInfo>, AdapterError> {let session = NcSession::open()?;let result = list_from_nc(filter);- session.close()?;- result+ close_session(session, result)}#[cfg(target_os = "macos")]diff --git a/crates/macos/src/notifications/nc_session.rs b/crates/macos/src/notifications/nc_session.rsindex 1c99de3d5..5eec7cdac 100644--- a/crates/macos/src/notifications/nc_session.rs+++ b/crates/macos/src/notifications/nc_session.rs@@ -1,8 +1,24 @@use agent_desktop_core::error::AdapterError;+pub(crate) fn close_session<T>(+ session: NcSession,+ result: Result<T, AdapterError>,+) -> Result<T, AdapterError> {+ let close_result = session.close();+ match (result, close_result) {+ (Ok(value), Ok(())) => Ok(value),+ (Ok(value), Err(close_err)) => {+ tracing::warn!(error = %close_err, "notification center close failed after a successful operation");+ Ok(value)+ }+ (Err(err), _) => Err(err),+ }+}+pub(crate) struct NcSession {was_already_open: bool,previous_app: Option<String>,+ closed: bool,}impl NcSession {@@ -16,10 +32,11 @@ impl NcSession {Ok(Self {was_already_open,previous_app,+ closed: false,})}- pub(crate) fn close(self) -> Result<(), AdapterError> {+ pub(crate) fn close(mut self) -> Result<(), AdapterError> {let close_result = if self.was_already_open {Ok(())} else {@@ -28,13 +45,16 @@ impl NcSession {if let Some(ref app) = self.previous_app {reactivate_app(app);}- std::mem::forget(self);+ self.closed = true;close_result}}impl Drop for NcSession {fn drop(&mut self) {+ if self.closed {+ return;+ }if !self.was_already_open {if let Err(e) = close_nc() {tracing::warn!("Failed to close NC in Drop: {e}");@@ -77,11 +97,13 @@ fn reactivate_app(name: &str) {let script = format!("tell application {} to activate", applescript_string(name));let mut command = std::process::Command::new("/usr/bin/osascript");command.arg("-e").arg(script);- let _ = crate::system::process::run_with_timeout(+ if let Err(e) = crate::system::process::run_with_timeout(&mut command,"reactivate-app osascript",std::time::Duration::from_secs(1),- );+ ) {+ tracing::warn!("reactivate_app osascript failed for app {:?}: {e}", name);+ }}#[cfg(target_os = "macos")]@@ -89,6 +111,9 @@ fn applescript_string(value: &str) -> String {let mut escaped = String::with_capacity(value.len() + 2);escaped.push('"');for ch in value.chars() {+ if ch.is_control() {+ continue;+ }if matches!(ch, '\\' | '"') {escaped.push('\\');}@@ -145,11 +170,11 @@ fn open_nc() -> Result<(), AdapterError> {let mut command = std::process::Command::new("/usr/bin/osascript");command.arg("-e").arg(script);- let _ = crate::system::process::run_with_timeout(+ crate::system::process::run_with_timeout(&mut command,"osascript open-nc",std::time::Duration::from_secs(2),- );+ )?;std::thread::sleep(std::time::Duration::from_millis(500));Ok(())}@@ -184,6 +209,14 @@ mod tests {r#""Bad \\ \"Name\"""#);}++ #[test]+ fn applescript_string_strips_control_chars() {+ assert_eq!(applescript_string("a\nb"), r#""ab""#);+ assert_eq!(applescript_string("a\tb"), r#""ab""#);+ assert_eq!(applescript_string("a\\\nb"), r#""a\\b""#);+ assert_eq!(applescript_string("a\"b\nc"), r#""a\"bc""#);+ }}#[cfg(not(target_os = "macos"))]diff --git a/crates/macos/src/system/app_ops.rs b/crates/macos/src/system/app_ops.rsindex 89520092f..5c2c162d4 100644--- a/crates/macos/src/system/app_ops.rs+++ b/crates/macos/src/system/app_ops.rs@@ -47,6 +47,15 @@ pub fn ensure_app_focused(pid: i32) -> Result<(), AdapterError> {Ok(())}+/// Focuses the app identified by `pid` on a best-effort basis; if the focus+/// attempt fails the warning is emitted and the caller proceeds unchanged.+#[cfg(target_os = "macos")]+pub(crate) fn focus_best_effort(pid: i32) {+ if let Err(e) = ensure_app_focused(pid) {+ tracing::warn!(error = %e, "failed to focus app before physical input");+ }+}+/// Polls `AXFrontmost` until the app actually reports frontmost instead of a/// fixed settle sleep, so an already-frontmost app costs one read and a slow/// activation gets the full window. Best-effort: timing out just means thediff --git a/crates/macos/src/system/window_ops.rs b/crates/macos/src/system/window_ops.rsindex dde0c1aa2..c7e2b448f 100644--- a/crates/macos/src/system/window_ops.rs+++ b/crates/macos/src/system/window_ops.rs@@ -126,13 +126,16 @@ mod raise {let raise_err = unsafe { AXUIElementPerformAction(window.0, raise.as_concrete_TypeRef()) };if raise_err != kAXErrorSuccess {let main_attr = CFString::new("AXMain");- unsafe {+ let ax_err = unsafe {AXUIElementSetAttributeValue(window.0,main_attr.as_concrete_TypeRef(),CFBoolean::true_value().as_CFTypeRef(),)};+ if ax_err != kAXErrorSuccess {+ tracing::debug!("raise_window: AXMain fallback returned err={ax_err}");+ }}wait_until_main(window);}diff --git a/crates/macos/src/tree/builder.rs b/crates/macos/src/tree/builder.rsindex b62870e68..90f1733d2 100644--- a/crates/macos/src/tree/builder.rs+++ b/crates/macos/src/tree/builder.rs@@ -81,6 +81,9 @@ pub fn build_subtree(return None;}if raw_depth >= ABSOLUTE_MAX_DEPTH {+ if ancestors.contains(&(el.0 as usize)) {+ return None;+ }let attrs = fetch_node_attrs(el);let role = attrs.rolediff --git a/crates/macos/src/tree/element.rs b/crates/macos/src/tree/element.rsindex 69008c725..c6e3ec1d0 100644--- a/crates/macos/src/tree/element.rs+++ b/crates/macos/src/tree/element.rs@@ -218,24 +218,20 @@ mod imp {}pub fn count_children(element: &AXElement, ax_role: Option<&str>) -> u32 {- unsafe {- for attr_name in child_attributes(ax_role) {- let mut count: core_foundation_sys::base::CFIndex = 0;- let attr = CFString::from_static_string(attr_name);- let err = AXUIElementGetAttributeValueCount(- element.0,- attr.as_concrete_TypeRef(),- &mut count,- );- if err != kAXErrorSuccess {- continue;- }- if count > 0 {- return count as u32;- }+ for attr_name in child_attributes(ax_role) {+ let mut count: core_foundation_sys::base::CFIndex = 0;+ let attr = CFString::from_static_string(attr_name);+ let err = unsafe {+ AXUIElementGetAttributeValueCount(element.0, attr.as_concrete_TypeRef(), &mut count)+ };+ if err != kAXErrorSuccess {+ continue;+ }+ if count > 0 {+ return count as u32;}- 0}+ 0}}diff --git a/crates/macos/src/tree/resolve_bounds.rs b/crates/macos/src/tree/resolve_bounds.rsindex 658e61a62..2e83046d7 100644--- a/crates/macos/src/tree/resolve_bounds.rs+++ b/crates/macos/src/tree/resolve_bounds.rs@@ -35,3 +35,51 @@ fn rects_overlap(candidate: &Rect, target: &Rect) -> bool {&& candidate.y <= target_bottom&& candidate_bottom >= target.y}++#[cfg(test)]+mod tests {+ use agent_desktop_core::node::Rect;++ use super::rects_overlap;++ fn r(x: f64, y: f64, w: f64, h: f64) -> Rect {+ Rect {+ x,+ y,+ width: w,+ height: h,+ }+ }++ #[test]+ fn overlapping_rects_intersect() {+ assert!(rects_overlap(+ &r(0.0, 0.0, 10.0, 10.0),+ &r(5.0, 5.0, 10.0, 10.0)+ ));+ }++ #[test]+ fn touching_edge_rects_are_considered_overlapping() {+ assert!(rects_overlap(+ &r(0.0, 0.0, 10.0, 10.0),+ &r(10.0, 0.0, 10.0, 10.0)+ ));+ }++ #[test]+ fn non_overlapping_rects_do_not_intersect() {+ assert!(!rects_overlap(+ &r(0.0, 0.0, 5.0, 5.0),+ &r(10.0, 10.0, 5.0, 5.0)+ ));+ }++ #[test]+ fn contained_rect_is_always_overlapping() {+ assert!(rects_overlap(+ &r(2.0, 2.0, 3.0, 3.0),+ &r(0.0, 0.0, 10.0, 10.0)+ ));+ }+}diff --git a/crates/macos/src/tree/resolve_deadline.rs b/crates/macos/src/tree/resolve_deadline.rsindex 4895380a4..5e13a73db 100644--- a/crates/macos/src/tree/resolve_deadline.rs+++ b/crates/macos/src/tree/resolve_deadline.rs@@ -24,6 +24,8 @@ pub(super) fn timeout_error() -> AdapterError {#[cfg(target_os = "macos")]pub(super) fn sleep_before_retry(deadline: Instant) {if let Ok(remaining) = remaining_before_deadline(deadline) {- std::thread::sleep(remaining.min(Duration::from_millis(75)));+ if remaining > Duration::from_millis(100) {+ std::thread::sleep(remaining.min(Duration::from_millis(75)));+ }}}diff --git a/crates/macos/src/tree/resolve_roots.rs b/crates/macos/src/tree/resolve_roots.rsindex d6a4d482d..c4fc1d0bc 100644--- a/crates/macos/src/tree/resolve_roots.rs+++ b/crates/macos/src/tree/resolve_roots.rs@@ -132,6 +132,7 @@ fn scoped_surface_root(SnapshotSurface::Sheet => crate::tree::sheet_for_pid(entry.pid),SnapshotSurface::Popover => crate::tree::popover_for_pid(entry.pid),SnapshotSurface::Alert => crate::tree::alert_for_pid(entry.pid),+ _ => return Err(AdapterError::not_supported("snapshot surface")),};Ok(root)}diff --git a/crates/macos/src/tree/resolve_search.rs b/crates/macos/src/tree/resolve_search.rsindex 3e28ed86c..c5d4425e8 100644--- a/crates/macos/src/tree/resolve_search.rs+++ b/crates/macos/src/tree/resolve_search.rs@@ -57,6 +57,7 @@ fn element_at_path(let mut seen = FxHashSet::default();for idx in path {ensure_before_deadline(deadline)?;+ set_messaging_timeout(¤t, remaining_before_deadline(deadline)?);let ax_role = copy_string_attr(¤t, accessibility_sys::kAXRoleAttribute);let children = resolve_children(¤t, ax_role.as_deref(), deadline, &mut seen)?;let Some(child) = children.get(*idx) else {diff --git a/crates/macos/src/tree/roles.rs b/crates/macos/src/tree/roles.rsindex 4b899aa91..ef614d019 100644--- a/crates/macos/src/tree/roles.rs+++ b/crates/macos/src/tree/roles.rs@@ -91,3 +91,45 @@ pub fn promoted_item_label(ax_role: Option<&str>, el: &crate::tree::AXElement) -}pub use agent_desktop_core::roles::is_toggleable_role;++#[cfg(test)]+mod tests {+ use super::ax_role_to_str;++ #[test]+ fn interactive_ax_roles_map_to_exact_normalized_roles() {+ assert_eq!(ax_role_to_str("AXButton"), "button");+ assert_eq!(ax_role_to_str("AXLink"), "link");+ assert_eq!(ax_role_to_str("AXCheckBox"), "checkbox");+ assert_eq!(ax_role_to_str("AXMenuItem"), "menuitem");+ assert_eq!(ax_role_to_str("AXMenuBarItem"), "menuitem");+ assert_eq!(ax_role_to_str("AXScrollArea"), "scrollarea");+ assert_eq!(ax_role_to_str("AXDisclosureTriangle"), "disclosure");+ assert_eq!(ax_role_to_str("AXComboBox"), "combobox");+ assert_eq!(ax_role_to_str("AXColorWell"), "colorwell");+ assert_eq!(ax_role_to_str("AXDockItem"), "dockitem");+ }++ #[test]+ fn aliased_ax_roles_collapse_to_one_normalized_role() {+ assert_eq!(ax_role_to_str("AXTextField"), "textfield");+ assert_eq!(ax_role_to_str("AXTextArea"), "textfield");+ assert_eq!(ax_role_to_str("AXSearchField"), "textfield");+ assert_eq!(ax_role_to_str("AXSecureTextField"), "textfield");++ assert_eq!(ax_role_to_str("AXSwitch"), "switch");+ assert_eq!(ax_role_to_str("AXToggle"), "switch");++ assert_eq!(ax_role_to_str("AXOutlineRow"), "treeitem");+ assert_eq!(ax_role_to_str("AXRow"), "treeitem");++ assert_eq!(ax_role_to_str("AXScrollBar"), "scrollarea");+ }++ #[test]+ fn unknown_ax_role_maps_to_unknown_fallback() {+ assert_eq!(ax_role_to_str("AXCustomWidget"), "unknown");+ assert_eq!(ax_role_to_str(""), "unknown");+ assert_eq!(ax_role_to_str("button"), "unknown");+ }+}diff --git a/skills/agent-desktop/references/commands-interaction.md b/skills/agent-desktop/references/commands-interaction.mdindex d36e35d59..cb861844b 100644--- a/skills/agent-desktop/references/commands-interaction.md+++ b/skills/agent-desktop/references/commands-interaction.md@@ -175,17 +175,19 @@ agent-desktop press cmd+a --app "TextEdit"**Key names:** `return`, `escape`, `tab`, `space`, `delete`, `up`, `down`, `left`, `right`, `f1`-`f12`**Modifiers:** `cmd`, `ctrl`, `alt`, `shift` — combine with `+`+Dangerous shortcuts (e.g. `cmd+q`, `ctrl+cmd+q`, `cmd+alt+esc`, `cmd+shift+delete`) are refused with `POLICY_DENIED`. Normalization covers modifier order and key-name aliases (`escape`/`esc`, `backspace`/`delete`). The block is the **platform adapter's** decision, not core's — the calling agent stays in control: pass `--force` to send a flagged combo anyway (`agent-desktop press cmd+q --force`). `--force` is available on `press`, `key-down`, and `key-up`.+### key-down```bashagent-desktop key-down shift```-Holds a key or modifier down. Must be paired with `key-up`.+Holds a key or modifier down. Must be paired with `key-up`. The blocked-combo guard (same set as `press`) is enforced per invocation. **Known limitation:** because the tool is stateless per call, an agent could hold modifiers across separate `key-down` calls to assemble a blocked combo; that cross-invocation case is not guarded — a stateful guard arrives with the Phase-4 daemon.### key-up```bashagent-desktop key-up shift```-Releases a held key or modifier.+Releases a held key or modifier. The blocked-combo guard (same set as `press`) applies per invocation.## Mousediff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.mdindex 49145e526..16c54bfcd 100644--- a/skills/agent-desktop/references/commands-system.md+++ b/skills/agent-desktop/references/commands-system.md@@ -78,6 +78,8 @@ Restores a minimized or maximized window to its previous size.## Notifications+If Notification Center fails to close after a successful list or dismiss operation, the command still returns its completed result; the close failure is logged internally and is never surfaced as an error, so a cleanup hiccup never discards a completed action.+### list-notifications```bashagent-desktop list-notificationsdiff --git a/src/cli/contract_tests.rs b/src/cli/contract_tests.rsindex 40230fbf5..4a620baae 100644--- a/src/cli/contract_tests.rs+++ b/src/cli/contract_tests.rs@@ -4,6 +4,7 @@ use std::collections::BTreeSet;use std::path::{Path, PathBuf};const NON_COMMAND_MODULES: &[&str] = &[+ "combo","execute_by_ref","helpers","helpers_test_support",diff --git a/src/cli_args/actions.rs b/src/cli_args/actions.rsindex b18184087..056b1476b 100644--- a/src/cli_args/actions.rs+++ b/src/cli_args/actions.rs@@ -99,6 +99,12 @@ pub(crate) struct PressArgs {pub combo: String,#[arg(long, help = "Target application name (focuses app before pressing)")]pub app: Option<String>,+ #[arg(+ long,+ help = "Send the combo even if the adapter flags it as a dangerous shortcut"+ )]+ #[serde(default)]+ pub force: bool,}#[derive(Parser, Debug, Deserialize)]@@ -109,6 +115,12 @@ pub(crate) struct KeyComboArgs {help = "Key or modifier to hold/release: shift, cmd, ctrl ...")]pub combo: String,+ #[arg(+ long,+ help = "Send the combo even if the adapter flags it as a dangerous shortcut"+ )]+ #[serde(default)]+ pub force: bool,}#[derive(Parser, Debug, Deserialize)]diff --git a/src/dispatch/mod.rs b/src/dispatch/mod.rsindex c535af5f9..db94cba24 100644--- a/src/dispatch/mod.rs+++ b/src/dispatch/mod.rs@@ -156,15 +156,26 @@ pub(crate) fn dispatch(press::PressArgs {combo: a.combo,app: a.app,+ force: a.force,},adapter,),- Commands::KeyDown(a) => {- key_down::execute(key_down::KeyDownArgs { combo: a.combo }, adapter)- }+ Commands::KeyDown(a) => key_down::execute(+ key_down::KeyDownArgs {+ combo: a.combo,+ force: a.force,+ },+ adapter,+ ),- Commands::KeyUp(a) => key_up::execute(key_up::KeyUpArgs { combo: a.combo }, adapter),+ Commands::KeyUp(a) => key_up::execute(+ key_up::KeyUpArgs {+ combo: a.combo,+ force: a.force,+ },+ adapter,+ ),Commands::Hover(a) => hover::execute(hover::HoverArgs {