diff --git a/apps/docs/content/docs/ffi/ownership-and-threading.mdx b/apps/docs/content/docs/ffi/ownership-and-threading.mdx index dc8e077897..2b1817c0e2 100644 --- a/apps/docs/content/docs/ffi/ownership-and-threading.mdx +++ b/apps/docs/content/docs/ffi/ownership-and-threading.mdx @@ -56,7 +56,7 @@ Snapshots, finds, listings, screenshots, clipboard reads, status, and trace read - `ad_adapter_destroy` revokes the adapter. Calls already in flight finish; calls that start afterward return `AD_RESULT_ERR_INVALID_ARGS`. - `ad_wait` blocks its calling thread for at most `scope.timeout_ms`. -- The `ad_set_log_callback` callback may run on any thread that calls an `ad_*` function, concurrently, and may still fire briefly after you unregister it. Keep it alive for the process lifetime and never let it unwind across the C ABI. +- The `ad_set_log_callback` callback may run on any thread that calls an `ad_*` function, concurrently, and may still fire briefly after you unregister it. Keep it alive for the process lifetime and never let it unwind across the C ABI. It may call `ad_*` functions itself; events from those nested calls are not delivered to it. The calls that take the interaction lock through the FFI layer are `ad_mouse_event`, `ad_mouse_event_with_modifiers`, `ad_mouse_wheel`, `ad_drag`, `ad_set_clipboard`, `ad_clear_clipboard`, `ad_execute_action`, `ad_execute_action_with_policy`, `ad_execute_by_ref`, `ad_execute_by_ref_timeout`, `ad_launch_app_exact`, `ad_close_app`, `ad_focus_window_exact`, `ad_window_op_exact`, `ad_notification_action`, `ad_dismiss_notification` and `ad_dismiss_all_notifications`. One of them made from the callback while the call that logged is one of them and holds the lock fails at once with `AD_RESULT_ERR_POLICY_DENIED`, details kind `reentrant_interaction_lease`; for `ad_execute_by_ref*` and `ad_close_app` as the call that logged, that holds for the whole call, including its work before the lock is taken. Any other nested call that needs the lock while the outer call holds it, including an observation that takes the lock internally, waits for a release that comes only after the callback returns and can time out, so do not make it from the callback. Other threads, including one still waiting for the lock, wait as usual. - A language runtime's global lock does not give thread affinity; keep native handles in thread-confined objects, or use refs. - On macOS, `ad_check_permissions` reports Accessibility trust for the host executable (`python3`, `node`, your app), not for the library. diff --git a/crates/ffi/include/agent_desktop.h b/crates/ffi/include/agent_desktop.h index 152bbeb72f..f7c90f290b 100644 --- a/crates/ffi/include/agent_desktop.h +++ b/crates/ffi/include/agent_desktop.h @@ -1756,6 +1756,24 @@ AdResult ad_mouse_wheel(const struct AdAdapter *adapter, * it is cleared, each call already in flight on another thread may still * invoke it once. * + * The callback may call other `ad_*` functions. Events those nested calls emit + * are not delivered to it. The calls that take the interaction lease through + * this library's FFI layer are `ad_mouse_event`, `ad_mouse_event_with_modifiers`, + * `ad_mouse_wheel`, `ad_drag`, `ad_set_clipboard`, `ad_clear_clipboard`, + * `ad_execute_action`, `ad_execute_action_with_policy`, `ad_execute_by_ref`, + * `ad_execute_by_ref_timeout`, `ad_launch_app_exact`, `ad_close_app`, + * `ad_focus_window_exact`, `ad_window_op_exact`, `ad_notification_action`, + * `ad_dismiss_notification` and `ad_dismiss_all_notifications`. One of these + * made from the callback while the call that logged is one of them and holds + * the lease fails at once with `AD_RESULT_ERR_POLICY_DENIED` and details kind + * `reentrant_interaction_lease`. For `ad_execute_by_ref*` and `ad_close_app` + * as the call that logged, the refusal applies for the whole call, including + * its work before the lease is taken. Any other nested call that needs the + * lease while the call that logged holds it, including an observation that + * takes the lease internally, waits for a release that happens only after the + * callback returns, so it can time out. Do not make such calls from the + * callback. + * * The message pointer is valid only until the callback returns. The callback * must not unwind across this C ABI boundary; C++ exceptions and Rust panics * must be caught inside the callback. Violating that contract may abort the diff --git a/crates/ffi/src/apps/close.rs b/crates/ffi/src/apps/close.rs index f4639a0a99..97ca83e4ee 100644 --- a/crates/ffi/src/apps/close.rs +++ b/crates/ffi/src/apps/close.rs @@ -29,6 +29,12 @@ pub unsafe extern "C" fn ad_close_app( } }; let adapter = crate::adapter::acquire_adapter!(adapter); + let _lease_marker = match crate::lease_marker::mark_core_mutation() { + Ok(marker) => marker, + Err(error) => { + return set_last_error(&error); + } + }; match agent_desktop_core::commands::close_app::execute( agent_desktop_core::commands::close_app::CloseAppArgs { app: id_str, force }, adapter.inner.as_ref(), diff --git a/crates/ffi/src/apps/launch.rs b/crates/ffi/src/apps/launch.rs index 7c93637db5..2c0bf46efb 100644 --- a/crates/ffi/src/apps/launch.rs +++ b/crates/ffi/src/apps/launch.rs @@ -63,7 +63,9 @@ pub unsafe extern "C" fn ad_launch_app_exact( return set_last_error(&error); } }; - let lease = match adapter.inner.acquire_interaction_lease(deadline) { + let lease = match crate::ffi_lease::FfiLease::take(|| { + adapter.inner.acquire_interaction_lease(deadline) + }) { Ok(lease) => lease, Err(error) => { return set_last_error(&error); diff --git a/crates/ffi/src/commands/execute_by_ref_timeout.rs b/crates/ffi/src/commands/execute_by_ref_timeout.rs index dcaff696e1..4fedf25e16 100644 --- a/crates/ffi/src/commands/execute_by_ref_timeout.rs +++ b/crates/ffi/src/commands/execute_by_ref_timeout.rs @@ -73,6 +73,12 @@ pub unsafe extern "C" fn ad_execute_by_ref_timeout( let caller_ip = caller_policy.to_interaction_policy(); let adapter_ref = crate::adapter::acquire_adapter!(adapter); + let _lease_marker = match crate::lease_marker::mark_core_mutation() { + Ok(marker) => marker, + Err(error) => { + return set_last_error(&error); + } + }; let context = match adapter_ref.command_context() { Ok(ctx) => ctx, Err(e) => { diff --git a/crates/ffi/src/ffi_lease.rs b/crates/ffi/src/ffi_lease.rs new file mode 100644 index 0000000000..f1735b5592 --- /dev/null +++ b/crates/ffi/src/ffi_lease.rs @@ -0,0 +1,35 @@ +use std::ops::Deref; + +use agent_desktop_core::{AdapterError, InteractionLease}; + +use crate::lease_marker::{LeaseMarker, refuse_reentrant_mutation}; + +/// An interaction lease taken by an FFI operation, with this thread marked as holding it for as long as +/// the lease lives. +pub(crate) struct FfiLease { + lease: InteractionLease, + _marker: LeaseMarker, +} + +impl FfiLease { + /// Takes the lease with `acquire` and marks this thread once it is held, so a thread still waiting for + /// another thread's lease is not marked. A reentrant mutation is refused before `acquire` runs. + pub(crate) fn take( + acquire: impl FnOnce() -> Result, + ) -> Result { + refuse_reentrant_mutation()?; + let lease = acquire()?; + Ok(Self { + lease, + _marker: LeaseMarker::hold(), + }) + } +} + +impl Deref for FfiLease { + type Target = InteractionLease; + + fn deref(&self) -> &InteractionLease { + &self.lease + } +} diff --git a/crates/ffi/src/lease_marker.rs b/crates/ffi/src/lease_marker.rs new file mode 100644 index 0000000000..6962f9e378 --- /dev/null +++ b/crates/ffi/src/lease_marker.rs @@ -0,0 +1,57 @@ +use std::cell::Cell; + +use agent_desktop_core::{AdapterError, DeliverySemantics, ErrorCode}; + +thread_local! { + static OPERATION_HOLDS_LEASE: Cell = const { Cell::new(false) }; +} + +/// Marks this thread's running FFI operation as holding the interaction lease until it is dropped. +pub(crate) struct LeaseMarker { + _private: (), +} + +impl LeaseMarker { + pub(crate) fn hold() -> Self { + OPERATION_HOLDS_LEASE.set(true); + Self { _private: () } + } +} + +impl Drop for LeaseMarker { + fn drop(&mut self) { + OPERATION_HOLDS_LEASE.set(false); + } +} + +/// Refuses a mutation started from a log callback while this thread's running FFI operation holds the +/// interaction lease, which only this thread can release once the callback returns. +pub(crate) fn refuse_reentrant_mutation() -> Result<(), AdapterError> { + if crate::log_callback::in_callback() && OPERATION_HOLDS_LEASE.get() { + return Err(reentrant()); + } + Ok(()) +} + +/// Marks a mutation whose lease core takes internally. Core offers no hook at the moment it acquires, +/// so the mark covers the whole call, including the work before the lease is taken. +pub(crate) fn mark_core_mutation() -> Result { + refuse_reentrant_mutation()?; + Ok(LeaseMarker::hold()) +} + +fn reentrant() -> AdapterError { + AdapterError::new( + ErrorCode::PolicyDenied, + "A log callback cannot start an interaction while the call that logged holds the interaction lease", + ) + .with_suggestion( + "Return from the log callback and make the call after the running ad_* call returns, \ + or queue it for another thread that does not wait on this one", + ) + .with_details(serde_json::json!({ + "kind": "reentrant_interaction_lease", + "retryable": false, + })) + .with_disposition(DeliverySemantics::not_delivered()) +} diff --git a/crates/ffi/src/lib.rs b/crates/ffi/src/lib.rs index 58dffaedd2..fadd74866e 100644 --- a/crates/ffi/src/lib.rs +++ b/crates/ffi/src/lib.rs @@ -46,8 +46,10 @@ pub(crate) mod convert; pub(crate) mod displays; pub(crate) mod enum_validation; pub mod error; +pub(crate) mod ffi_lease; pub(crate) mod ffi_try; pub(crate) mod input; +pub(crate) mod lease_marker; pub(crate) mod log_callback; pub(crate) mod notifications; pub(crate) mod observation; diff --git a/crates/ffi/src/log_callback.rs b/crates/ffi/src/log_callback.rs index a5d6a2afd6..79e58091c4 100644 --- a/crates/ffi/src/log_callback.rs +++ b/crates/ffi/src/log_callback.rs @@ -112,8 +112,12 @@ fn format_event(event: &Event<'_>) -> Option { CString::new(serde_json::to_string(&sanitized).ok()?).ok() } +pub(crate) fn in_callback() -> bool { + IN_CALLBACK.get() +} + pub(crate) fn with_dispatch(body: impl FnOnce() -> R) -> R { - if current_callback().is_none() { + if IN_CALLBACK.get() || current_callback().is_none() { return body(); } let subscriber = tracing_subscriber::registry().with(CallbackLayer); @@ -129,6 +133,24 @@ pub(crate) fn with_dispatch(body: impl FnOnce() -> R) -> R { /// it is cleared, each call already in flight on another thread may still /// invoke it once. /// +/// The callback may call other `ad_*` functions. Events those nested calls emit +/// are not delivered to it. The calls that take the interaction lease through +/// this library's FFI layer are `ad_mouse_event`, `ad_mouse_event_with_modifiers`, +/// `ad_mouse_wheel`, `ad_drag`, `ad_set_clipboard`, `ad_clear_clipboard`, +/// `ad_execute_action`, `ad_execute_action_with_policy`, `ad_execute_by_ref`, +/// `ad_execute_by_ref_timeout`, `ad_launch_app_exact`, `ad_close_app`, +/// `ad_focus_window_exact`, `ad_window_op_exact`, `ad_notification_action`, +/// `ad_dismiss_notification` and `ad_dismiss_all_notifications`. One of these +/// made from the callback while the call that logged is one of them and holds +/// the lease fails at once with `AD_RESULT_ERR_POLICY_DENIED` and details kind +/// `reentrant_interaction_lease`. For `ad_execute_by_ref*` and `ad_close_app` +/// as the call that logged, the refusal applies for the whole call, including +/// its work before the lease is taken. Any other nested call that needs the +/// lease while the call that logged holds it, including an observation that +/// takes the lease internally, waits for a release that happens only after the +/// callback returns, so it can time out. Do not make such calls from the +/// callback. +/// /// The message pointer is valid only until the callback returns. The callback /// must not unwind across this C ABI boundary; C++ exceptions and Rust panics /// must be caught inside the callback. Violating that contract may abort the @@ -152,6 +174,12 @@ mod tests { static MESSAGES: Mutex> = Mutex::new(Vec::new()); static LOG_TEST_LOCK: Mutex<()> = Mutex::new(()); + pub(super) fn log_test_serialization() -> std::sync::MutexGuard<'static, ()> { + LOG_TEST_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + unsafe extern "C" fn record(_level: i32, message: *const c_char) { let message = unsafe { CStr::from_ptr(message) } .to_string_lossy() @@ -161,7 +189,7 @@ mod tests { #[test] fn scoped_dispatch_delivers_and_redacts() { - let _guard = LOG_TEST_LOCK.lock().unwrap(); + let _guard = log_test_serialization(); MESSAGES.lock().unwrap().clear(); assert_eq!(ad_set_log_callback(Some(record)), AdResult::Ok); with_dispatch(|| { @@ -183,7 +211,7 @@ mod tests { #[test] fn callback_does_not_capture_outside_scope() { - let _guard = LOG_TEST_LOCK.lock().unwrap(); + let _guard = log_test_serialization(); MESSAGES.lock().unwrap().clear(); assert_eq!(ad_set_log_callback(Some(record)), AdResult::Ok); tracing::error!(operation = "outside"); @@ -191,3 +219,7 @@ mod tests { assert!(MESSAGES.lock().unwrap().is_empty()); } } + +#[cfg(test)] +#[path = "log_callback_reentrancy_tests.rs"] +mod reentrancy_tests; diff --git a/crates/ffi/src/log_callback_reentrancy_tests.rs b/crates/ffi/src/log_callback_reentrancy_tests.rs new file mode 100644 index 0000000000..fefcb5fdbc --- /dev/null +++ b/crates/ffi/src/log_callback_reentrancy_tests.rs @@ -0,0 +1,292 @@ +use std::cell::{Cell, RefCell}; +use std::ffi::{CStr, CString, c_char}; +use std::sync::MutexGuard; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use agent_desktop_core::{ + ActionOps, AdapterError, Deadline, DisplayInfo, InputOps, InteractionLease, MouseEvent, + ObservationOps, OperationReport, ProcessLeaseGuard, SystemOps, +}; + +use super::ad_set_log_callback; +use crate::adapter::{AdAdapter, ad_adapter_destroy, register_adapter}; +use crate::apps::close::ad_close_app; +use crate::apps::launch::ad_launch_app_exact; +use crate::commands::execute_by_ref_timeout::ad_execute_by_ref_timeout; +use crate::displays::list::ad_list_displays; +use crate::error::{AdResult, ad_last_error_details}; +use crate::input::clipboard::ad_free_string; +use crate::input::mouse::ad_mouse_event; +use crate::types::{AdAction, AdExactWindowInfo, AdMouseEvent, AdPoint}; + +const CALLBACK_HOLD: Duration = Duration::from_millis(150); + +struct LoggingAdapter { + takes_process_lease: bool, + logs_while_acquiring: bool, +} + +impl ObservationOps for LoggingAdapter {} + +impl ActionOps for LoggingAdapter {} + +impl SystemOps for LoggingAdapter { + fn acquire_interaction_lease( + &self, + deadline: Deadline, + ) -> Result { + if self.logs_while_acquiring { + tracing::warn!(operation = "acquire_interaction_lease"); + } + if self.takes_process_lease { + return InteractionLease::guarded(deadline, ProcessLeaseGuard::acquire(deadline)?); + } + InteractionLease::guarded(deadline, ()) + } + + fn list_displays(&self, _deadline: Deadline) -> Result, AdapterError> { + tracing::warn!(operation = "list_displays"); + Err(AdapterError::not_supported("list_displays")) + } +} + +impl InputOps for LoggingAdapter { + fn mouse_event( + &self, + event: MouseEvent, + _lease: &InteractionLease, + ) -> Result { + tracing::warn!(operation = "mouse_event"); + Ok(OperationReport::pointer_dispatched(&event, false)) + } +} + +type InnerCall = (AdResult, Duration, String); +type ContenderOutcome = (AdResult, Duration, Option); +type Action = fn(*mut AdAdapter); + +thread_local! { + static ARMED: Cell> = const { Cell::new(None) }; + static CALLBACK_RUNS: Cell = const { Cell::new(0) }; + static INNER_CALL: RefCell> = const { RefCell::new(None) }; + static SECOND_ADAPTER: Cell = const { Cell::new(0) }; + static CONTENDER: RefCell>> = const { RefCell::new(None) }; +} + +unsafe extern "C" fn run_armed_action(_level: i32, _message: *const c_char) { + CALLBACK_RUNS.set(CALLBACK_RUNS.get().saturating_add(1)); + if let Some((action, adapter)) = ARMED.take() { + action(adapter); + } +} + +struct LoggingSession { + adapters: Vec<*mut AdAdapter>, + _serial: MutexGuard<'static, ()>, +} + +impl LoggingSession { + fn start() -> Option { + #[cfg(unix)] + if std::env::var_os(agent_desktop_core::INTERACTION_LEASE_FD_ENV).is_some() { + eprintln!("skipped: an inherited lease fd routes FFI leases past the test adapter"); + return None; + } + let session = Self { + adapters: Vec::new(), + _serial: super::tests::log_test_serialization(), + }; + CALLBACK_RUNS.set(0); + assert_eq!(ad_set_log_callback(Some(run_armed_action)), AdResult::Ok); + Some(session) + } + + fn adapter(&mut self, takes_process_lease: bool, logs_while_acquiring: bool) -> *mut AdAdapter { + let adapter = register_adapter(AdAdapter { + inner: Box::new(LoggingAdapter { + takes_process_lease, + logs_while_acquiring, + }), + session_id: None, + _session_lease: None, + }) + .unwrap(); + self.adapters.push(adapter); + adapter + } +} + +impl Drop for LoggingSession { + fn drop(&mut self) { + let _ = ad_set_log_callback(None); + ARMED.set(None); + for adapter in self.adapters.drain(..) { + unsafe { ad_adapter_destroy(adapter) }; + } + } +} + +fn move_event() -> AdMouseEvent { + AdMouseEvent { + kind: 0, + point: AdPoint { x: 1.0, y: 1.0 }, + button: 0, + click_count: 0, + } +} + +fn mouse_event(adapter: *mut AdAdapter) -> AdResult { + unsafe { ad_mouse_event(adapter, &move_event()) } +} + +fn last_error_kind() -> String { + let details = ad_last_error_details(); + if details.is_null() { + return String::new(); + } + let text = unsafe { CStr::from_ptr(details) }.to_string_lossy(); + serde_json::from_str::(&text) + .ok() + .and_then(|value| value["kind"].as_str().map(str::to_owned)) + .unwrap_or_default() +} + +fn record(call: impl FnOnce() -> AdResult) { + let started = Instant::now(); + let result = call(); + let elapsed = started.elapsed(); + INNER_CALL.set(Some((result, elapsed, last_error_kind()))); +} + +fn reenter_mouse_event(adapter: *mut AdAdapter) { + record(|| mouse_event(adapter)); +} + +fn reenter_launch_app_exact(adapter: *mut AdAdapter) { + let id = CString::new("org.example.app").unwrap(); + let mut out: AdExactWindowInfo = unsafe { std::mem::zeroed() }; + record(|| unsafe { ad_launch_app_exact(adapter, id.as_ptr(), 1_000, &mut out) }); +} + +fn reenter_execute_by_ref_timeout(adapter: *mut AdAdapter) { + let ref_id = CString::new("@s8f3k2p9:e1").unwrap(); + let action: AdAction = unsafe { std::mem::zeroed() }; + let mut out: *mut c_char = std::ptr::null_mut(); + record(|| unsafe { + ad_execute_by_ref_timeout(adapter, ref_id.as_ptr(), &action, 0, -1, &mut out) + }); + unsafe { ad_free_string(out) }; +} + +fn reenter_close_app(adapter: *mut AdAdapter) { + let id = CString::new("org.example.app").unwrap(); + record(|| unsafe { ad_close_app(adapter, id.as_ptr(), false) }); +} + +fn spawn_contender(address: usize, inner: Option) -> JoinHandle { + std::thread::spawn(move || { + let adapter = std::ptr::with_exposed_provenance_mut(address); + ARMED.set(inner.map(|action| (action, adapter))); + let started = Instant::now(); + let result = mouse_event(adapter); + (result, started.elapsed(), INNER_CALL.take()) + }) +} + +fn start_contender(adapter: *mut AdAdapter) { + CONTENDER.set(Some(spawn_contender(adapter.expose_provenance(), None))); + std::thread::sleep(CALLBACK_HOLD); +} + +fn start_waiting_reentrant_contender(_adapter: *mut AdAdapter) { + let contender = spawn_contender(SECOND_ADAPTER.get(), Some(reenter_mouse_event)); + CONTENDER.set(Some(contender)); + std::thread::sleep(CALLBACK_HOLD); +} + +fn joined_contender() -> ContenderOutcome { + CONTENDER + .take() + .expect("the log callback must start the contender inside the outer call") + .join() + .unwrap() +} + +fn inner_call() -> InnerCall { + INNER_CALL + .take() + .expect("the log callback must run inside the outer call") +} + +#[test] +fn a_log_callback_can_call_back_into_the_library() { + let Some(mut session) = LoggingSession::start() else { + return; + }; + let adapter = session.adapter(false, false); + ARMED.set(Some((reenter_mouse_event, adapter))); + let mut displays = std::ptr::null_mut(); + let outer = unsafe { ad_list_displays(adapter, &mut displays) }; + let (inner, elapsed, kind) = inner_call(); + assert_eq!(inner, AdResult::Ok, "kind {kind:?} after {elapsed:?}"); + assert_ne!(outer, AdResult::ErrInternal); + assert_eq!(CALLBACK_RUNS.get(), 1); +} + +#[test] +fn every_lease_taking_mutation_from_a_log_callback_inside_a_mutation_is_refused_at_once() { + let entry_points: [(&str, Action); 4] = [ + ("ad_mouse_event", reenter_mouse_event), + ("ad_launch_app_exact", reenter_launch_app_exact), + ("ad_execute_by_ref_timeout", reenter_execute_by_ref_timeout), + ("ad_close_app", reenter_close_app), + ]; + for (name, action) in entry_points { + let Some(mut session) = LoggingSession::start() else { + return; + }; + let adapter = session.adapter(true, false); + ARMED.set(Some((action, adapter))); + let outer = mouse_event(adapter); + let (inner, elapsed, kind) = inner_call(); + assert_eq!(outer, AdResult::Ok, "{name}"); + assert_eq!(inner, AdResult::ErrPolicyDenied, "{name} after {elapsed:?}"); + assert_eq!(kind, "reentrant_interaction_lease", "{name}"); + assert!( + elapsed < Duration::from_millis(100), + "{name} took {elapsed:?}" + ); + } +} + +#[test] +fn another_thread_waits_for_the_lease_a_logging_mutation_holds() { + let Some(mut session) = LoggingSession::start() else { + return; + }; + let adapter = session.adapter(true, false); + ARMED.set(Some((start_contender, adapter))); + let outer = mouse_event(adapter); + let (result, waited, _) = joined_contender(); + assert_eq!(outer, AdResult::Ok); + assert_eq!(result, AdResult::Ok, "after {waited:?}"); + assert!(waited >= CALLBACK_HOLD / 2, "waited only {waited:?}"); +} + +#[test] +fn a_thread_still_waiting_for_the_lease_is_not_refused_from_its_callback() { + let Some(mut session) = LoggingSession::start() else { + return; + }; + let holder = session.adapter(true, false); + let waiter = session.adapter(true, true); + SECOND_ADAPTER.set(waiter.expose_provenance()); + ARMED.set(Some((start_waiting_reentrant_contender, holder))); + let outer = mouse_event(holder); + let (result, waited, inner) = joined_contender(); + let (inner, inner_elapsed, kind) = inner.expect("the waiting thread's callback must run"); + assert_eq!(outer, AdResult::Ok); + assert_eq!(inner, AdResult::Ok, "kind {kind:?} after {inner_elapsed:?}"); + assert_eq!(result, AdResult::Ok, "after {waited:?}"); +} diff --git a/crates/ffi/src/operation.rs b/crates/ffi/src/operation.rs index 32d7fc2ed7..0eccf716eb 100644 --- a/crates/ffi/src/operation.rs +++ b/crates/ffi/src/operation.rs @@ -1,12 +1,18 @@ use agent_desktop_core::{AdapterError, Deadline, InteractionLease, PlatformAdapter}; +use crate::ffi_lease::FfiLease; + pub(crate) const DEFAULT_FFI_TIMEOUT_MS: u64 = 5_000; pub(crate) fn deadline() -> Result { Deadline::after(DEFAULT_FFI_TIMEOUT_MS) } -pub(crate) fn lease(adapter: &dyn PlatformAdapter) -> Result { +pub(crate) fn lease(adapter: &dyn PlatformAdapter) -> Result { + FfiLease::take(|| acquire(adapter)) +} + +fn acquire(adapter: &dyn PlatformAdapter) -> Result { let deadline = deadline()?; #[cfg(unix)] if let Some(raw_fd) = inherited_lease_fd()? { diff --git a/skills/agent-desktop-ffi/references/threading.md b/skills/agent-desktop-ffi/references/threading.md index b2628c66a6..1151e5c726 100644 --- a/skills/agent-desktop-ffi/references/threading.md +++ b/skills/agent-desktop-ffi/references/threading.md @@ -20,6 +20,7 @@ finite deadline and do not take the interaction lease. | read + read | Both may run concurrently; neither waits for the interaction lease | | read + mutation | The read does not wait for the lease and may overlap the mutation; its result is a point-in-time observation, not a transaction | | mutation + mutation | One lease holder runs at a time for the same OS user; the waiter consumes its command deadline and returns a structured timeout if it cannot acquire the lease | +| lease-taking call from a log callback while the same thread's lease-taking call holds the lease | Refused at once with `AD_RESULT_ERR_POLICY_DENIED`, details kind `reentrant_interaction_lease`; see Log callback threading for the list | | native-handle call on another thread | Rejected with `AD_RESULT_ERR_INVALID_ARGS`; use a qualified ref instead | Snapshots, finds, gets, display/window/app listings, screenshots, clipboard @@ -80,6 +81,25 @@ to cross an async task or thread boundary. `ad_set_log_callback(cb)` may be called from any thread. The callback may be invoked from any thread that calls an `ad_*` function. +The callback may itself call `ad_*` functions. Events those nested calls emit +are not delivered to the callback. + +These calls take the interaction lease through the FFI layer: `ad_mouse_event`, `ad_mouse_event_with_modifiers`, `ad_mouse_wheel`, `ad_drag`, `ad_set_clipboard`, `ad_clear_clipboard`, `ad_execute_action`, `ad_execute_action_with_policy`, `ad_execute_by_ref`, `ad_execute_by_ref_timeout`, `ad_launch_app_exact`, `ad_close_app`, `ad_focus_window_exact`, `ad_window_op_exact`, `ad_notification_action`, `ad_dismiss_notification` and `ad_dismiss_all_notifications`. +One of them made from the callback while the call that logged is one of them +and holds the lease fails at once with `AD_RESULT_ERR_POLICY_DENIED`, details +kind `reentrant_interaction_lease` and `retryable: false`. When the call that +logged is `ad_execute_by_ref*` or `ad_close_app`, whose lease core takes +internally, the refusal covers the whole call, including the auto-wait and ref +resolution before the lease is taken. + +Any other nested call that needs the interaction lease while the call that +logged holds it, including an observation that takes the lease internally (for +example to switch on a Chromium or Electron renderer's accessibility), waits +for a release that happens only after the callback returns, and can time out. +Do not make such calls from the callback; queue them for after the outer call +returns. Another host thread, or a thread still waiting for the lease, is not +refused and waits for the lease as usual. + A callback unregistered via `NULL` may still receive an invocation already in flight on another thread. Keep the callback and captured state alive for the process lifetime, or quiesce active adapter calls before unregistering it.