Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/docs/content/docs/ffi/ownership-and-threading.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
18 changes: 18 additions & 0 deletions crates/ffi/include/agent_desktop.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions crates/ffi/src/apps/close.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
4 changes: 3 additions & 1 deletion crates/ffi/src/apps/launch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
6 changes: 6 additions & 0 deletions crates/ffi/src/commands/execute_by_ref_timeout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
35 changes: 35 additions & 0 deletions crates/ffi/src/ffi_lease.rs
Original file line number Diff line number Diff line change
@@ -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<InteractionLease, AdapterError>,
) -> Result<Self, AdapterError> {
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
}
}
57 changes: 57 additions & 0 deletions crates/ffi/src/lease_marker.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use std::cell::Cell;

use agent_desktop_core::{AdapterError, DeliverySemantics, ErrorCode};

thread_local! {
static OPERATION_HOLDS_LEASE: Cell<bool> = 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<LeaseMarker, AdapterError> {
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())
}
2 changes: 2 additions & 0 deletions crates/ffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
38 changes: 35 additions & 3 deletions crates/ffi/src/log_callback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,12 @@ fn format_event(event: &Event<'_>) -> Option<CString> {
CString::new(serde_json::to_string(&sanitized).ok()?).ok()
}

pub(crate) fn in_callback() -> bool {
IN_CALLBACK.get()
}

pub(crate) fn with_dispatch<R>(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);
Expand All @@ -129,6 +133,24 @@ pub(crate) fn with_dispatch<R>(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
Expand All @@ -152,6 +174,12 @@ mod tests {
static MESSAGES: Mutex<Vec<String>> = 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()
Expand All @@ -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(|| {
Expand All @@ -183,11 +211,15 @@ 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");
assert_eq!(ad_set_log_callback(None), AdResult::Ok);
assert!(MESSAGES.lock().unwrap().is_empty());
}
}

#[cfg(test)]
#[path = "log_callback_reentrancy_tests.rs"]
mod reentrancy_tests;
Loading
Loading