Skip to content

Computer use CLI for AI agents

feat(core): move the cursor before taking the interaction lease (#347)

Chris Tatea25d593595c3
diff --git a/CONCEPTS.md b/CONCEPTS.md
index 5a2f80559..5afd37f84 100644
--- a/CONCEPTS.md
+++ b/CONCEPTS.md
@@ -228,7 +228,7 @@ Core owns the precondition each action declares: a focused window for keyboard o
### Agent Cursor Overlay
An optional presentation-only cursor driven by verified action destinations. Its whole configuration (label, colours, size, and click effects) is set once per session with `session start --cursor` or `cursor-overlay enable`; action and batch commands inherit it and take no cursor flags. Motion models a human hand and the cursor never rotates or resizes. The renderer acknowledges arrival before the action dispatches, under a bounded timeout, so the picture and the real effect stay in step. A click plays a ripple and flashes an outline around the element. A `--headed` mutating command hides the overlay before it dispatches and shows it again afterwards; on Windows the renderer stays suppressed for headed input and draws only for headless semantic actions. It never moves or replaces the OS pointer and never changes Interaction Policy, action delivery, or response semantics. Configuration, motion, and effect timing live in `agent-desktop-core`; macOS, Windows and Linux (X11 only) supply native renderers, and an adapter that does not override `update_cursor_overlay` refuses with `PLATFORM_NOT_SUPPORTED`, which dispatch treats as `rendered: false`.
-For harness subagents, `session start --cursor --multi-agent` enables a cursor per `(session-id, agent-id)` (macOS, Windows, and Linux X11). The harness assigns each subagent a stable global `--agent-id` or `AGENT_DESKTOP_AGENT_ID`. The CLI requires this identity for desktop UI actions in that mode. The interaction lease still serializes physical input on the shared OS pointer. Each cursor reuses the same rendering and fade behavior; snapshots remain shared by session. Optional agent profiles override presentation only, and session disable/end removes every cursor.
+For harness subagents, `session start --cursor --multi-agent` enables a cursor per `(session-id, agent-id)` (macOS, Windows, and Linux X11). The harness assigns each subagent a stable global `--agent-id` or `AGENT_DESKTOP_AGENT_ID`. The CLI requires this identity for desktop UI actions in that mode. The interaction lease still serializes physical input on the shared OS pointer. A headless action moves its cursor before it takes the lease, so several agents' cursors travel at the same time while their actions take turns. Commands that draw the same cursor take turns from its travel to its click effect. Each cursor reuses the same rendering and fade behavior; snapshots remain shared by session. Optional agent profiles override presentation only, and session disable/end removes every cursor.
### Headless Ref Action
A ref-based action that uses semantic accessibility operations without implicit focus stealing, cursor movement, synthetic keyboard input, or pasteboard use. This is the default mode.
diff --git a/apps/docs/content/docs/sessions.mdx b/apps/docs/content/docs/sessions.mdx
index f07d27f1c..f1e838d9c 100644
--- a/apps/docs/content/docs/sessions.mdx
+++ b/apps/docs/content/docs/sessions.mdx
@@ -99,7 +99,7 @@ Several agents may share one session id. Each should act on refs from its own sn
`--agent-id <id>` (or `AGENT_DESKTOP_AGENT_ID`) names the harness subagent that is running a command. The flag wins over the variable. An id is 1 to 64 letters, digits, `-` or `_`, and an invalid id fails with `INVALID_ARGS`. It is scoped by session.
-The identity matters in one mode: a session started with `session start --cursor --multi-agent`. There, desktop actions such as `click` and `type` require an agent id and fail with `INVALID_ARGS` without one. Observation, clipboard and session commands do not. Each distinct id gets its own cursor, and a reused id reuses its cursor. Snapshots stay shared by session.
+The identity matters in one mode: a session started with `session start --cursor --multi-agent`. There, desktop actions such as `click` and `type` require an agent id and fail with `INVALID_ARGS` without one. Observation, clipboard and session commands do not. Each distinct id gets its own cursor, and a reused id reuses its cursor. A headless action moves its cursor before it takes the interaction lease, so several agents' cursors travel at the same time while their actions take turns. Commands that draw the same cursor take turns from its travel to its click effect, so a shared cursor never clicks while showing another command's target. Snapshots stay shared by session.
## Sessions, traces, and the cursor overlay
diff --git a/crates/core/src/commands/drag.rs b/crates/core/src/commands/drag.rs
index db3fd9404..dcb7fe0ad 100644
--- a/crates/core/src/commands/drag.rs
+++ b/crates/core/src/commands/drag.rs
@@ -66,6 +66,7 @@ pub fn execute(
headed_requirement: crate::HeadedRequirement::None,
};
let auto_wait = args.timeout_ms.is_some_and(|timeout_ms| timeout_ms > 0);
+ let cursor = crate::cursor_overlay::hold_cursor(context, deadline);
let (from, to, lease, params) = before_first_event(|| {
if auto_wait {
wait_for_point_with_deadline(from_args, deadline, adapter, context)?;
@@ -183,6 +184,7 @@ pub fn execute(
response["focused"] = json!(true);
}
drop(lease);
+ drop(cursor);
let wait_entry = match args.wait_for_scope {
WaitForScope::To => to.source_entry.as_ref().or(from.source_entry.as_ref()),
WaitForScope::From => from.source_entry.as_ref().or(to.source_entry.as_ref()),
diff --git a/crates/core/src/commands/hover.rs b/crates/core/src/commands/hover.rs
index 3e09dbc44..95e10a4d4 100644
--- a/crates/core/src/commands/hover.rs
+++ b/crates/core/src/commands/hover.rs
@@ -46,6 +46,7 @@ pub fn execute(
headed_requirement: crate::HeadedRequirement::FocusedWindowAndCursor,
};
let auto_wait = args.timeout_ms.is_some_and(|timeout_ms| timeout_ms > 0);
+ let cursor = crate::cursor_overlay::hold_cursor(context, deadline);
let (resolved, lease) = before_first_event(|| {
if auto_wait {
wait_for_point_with_deadline(point_args, deadline, adapter, context)?;
@@ -108,6 +109,7 @@ pub fn execute(
response["focused"] = json!(true);
}
drop(lease);
+ drop(cursor);
apply_post_action_wait(response, resolved.source_entry.as_ref(), adapter, context)
}
diff --git a/crates/core/src/commands/mouse_click.rs b/crates/core/src/commands/mouse_click.rs
index 5caa5e2ca..08cb09eae 100644
--- a/crates/core/src/commands/mouse_click.rs
+++ b/crates/core/src/commands/mouse_click.rs
@@ -25,6 +25,7 @@ pub fn execute(
require_cursor_policy(context, "mouse-click")?;
require_pointer_capability(adapter)?;
crate::validate_mouse_click_count(args.count)?;
+ let _cursor = crate::cursor_overlay::hold_cursor(context, crate::Deadline::standard()?);
let lease = crate::commands::helpers::acquire_interaction_lease(adapter)?;
let point = Point {
x: args.x,
diff --git a/crates/core/src/commands/mouse_click_cursor_tests.rs b/crates/core/src/commands/mouse_click_cursor_tests.rs
new file mode 100644
index 000000000..7ded794cf
--- /dev/null
+++ b/crates/core/src/commands/mouse_click_cursor_tests.rs
@@ -0,0 +1,87 @@
+use super::super::{MouseClickArgs, execute};
+use crate::adapter::{ActionOps, InputOps, ObservationOps, SystemOps};
+use crate::{AdapterError, CommandContext, MouseButton, MouseEvent};
+use std::sync::Mutex;
+use std::time::{Duration, Instant};
+
+#[derive(Default)]
+struct TimedLeaseAdapter {
+ leased_at: Mutex<Option<Instant>>,
+}
+
+impl ObservationOps for TimedLeaseAdapter {}
+impl ActionOps for TimedLeaseAdapter {}
+
+impl SystemOps for TimedLeaseAdapter {
+ fn acquire_interaction_lease(
+ &self,
+ deadline: crate::Deadline,
+ ) -> Result<crate::InteractionLease, AdapterError> {
+ *self.leased_at.lock().unwrap() = Some(Instant::now());
+ crate::InteractionLease::guarded(deadline, ())
+ }
+
+ fn update_cursor_overlay(
+ &self,
+ _control: &crate::CursorOverlayControl,
+ ) -> Result<(), AdapterError> {
+ Ok(())
+ }
+}
+
+impl InputOps for TimedLeaseAdapter {
+ fn mouse_event(
+ &self,
+ _event: MouseEvent,
+ _lease: &crate::InteractionLease,
+ ) -> Result<crate::OperationReport, AdapterError> {
+ Ok(crate::adapter::test_report())
+ }
+}
+
+/// A ref action in the same session is between its travel and its click.
+/// A raw mouse click moves the same drawn cursor, so it waits for that action
+/// to finish rather than moving the cursor away before the action clicks.
+#[test]
+fn a_mouse_click_waits_for_the_command_already_using_the_cursor() {
+ let _guard = crate::refs::refs_test_support::HomeGuard::new();
+ let session = crate::session::start_session(Default::default()).expect("session starts");
+ let config = crate::CursorOverlayConfig::enabled(None, 6).expect("valid config");
+ crate::session::set_cursor_overlay(&session.id, config).expect("overlay enabled");
+ let context = CommandContext::new(Some(session.id), None, false)
+ .expect("context loads")
+ .with_headed(true);
+ let lock = crate::cursor_overlay::hold_cursor(&context, crate::Deadline::after(1_000).unwrap())
+ .expect("the cursor lock")
+ .expect("a shared cursor");
+ let hold = Duration::from_millis(150);
+ let released = Instant::now() + hold;
+ std::thread::spawn(move || {
+ std::thread::sleep(hold);
+ drop(lock);
+ });
+ let adapter = TimedLeaseAdapter::default();
+
+ execute(
+ MouseClickArgs {
+ x: 10.0,
+ y: 20.0,
+ button: MouseButton::Left,
+ count: 1,
+ modifiers: Vec::new(),
+ },
+ &adapter,
+ &context,
+ )
+ .expect("mouse click succeeds");
+
+ let leased_at = adapter
+ .leased_at
+ .lock()
+ .unwrap()
+ .expect("the lease was taken");
+ assert!(
+ leased_at >= released,
+ "the click took the lease while the cursor was in use"
+ );
+}
diff --git a/crates/core/src/commands/mouse_click_tests.rs b/crates/core/src/commands/mouse_click_tests.rs
index 87a5b2ce2..d3f8b51df 100644
--- a/crates/core/src/commands/mouse_click_tests.rs
+++ b/crates/core/src/commands/mouse_click_tests.rs
@@ -170,3 +170,6 @@ fn excessive_click_count_fails_before_dispatch() {
assert_eq!(err.code(), "INVALID_ARGS");
assert!(adapter.captured.lock().unwrap().is_none());
}
+
+#[path = "mouse_click_cursor_tests.rs"]
+mod cursor;
diff --git a/crates/core/src/commands/mouse_move.rs b/crates/core/src/commands/mouse_move.rs
index ac11f06df..502727dba 100644
--- a/crates/core/src/commands/mouse_move.rs
+++ b/crates/core/src/commands/mouse_move.rs
@@ -21,6 +21,7 @@ pub fn execute(
) -> Result<Value, AppError> {
require_cursor_policy(context, "mouse-move")?;
require_pointer_capability(adapter)?;
+ let _cursor = crate::cursor_overlay::hold_cursor(context, crate::Deadline::standard()?);
let lease = crate::commands::helpers::acquire_interaction_lease(adapter)?;
let point = Point {
x: args.x,
diff --git a/crates/core/src/commands/mouse_wheel.rs b/crates/core/src/commands/mouse_wheel.rs
index fbc9cfe48..48d401b99 100644
--- a/crates/core/src/commands/mouse_wheel.rs
+++ b/crates/core/src/commands/mouse_wheel.rs
@@ -24,6 +24,7 @@ pub fn execute(
"mouse-wheel coordinates and line deltas must be finite numbers",
));
}
+ let _cursor = crate::cursor_overlay::hold_cursor(context, crate::Deadline::standard()?);
let lease = crate::commands::helpers::acquire_interaction_lease(adapter)?;
let point = Point {
x: args.x,
diff --git a/crates/core/src/cursor_overlay/cursor_hold.rs b/crates/core/src/cursor_overlay/cursor_hold.rs
new file mode 100644
index 000000000..e3efe1966
--- /dev/null
+++ b/crates/core/src/cursor_overlay/cursor_hold.rs
@@ -0,0 +1,42 @@
+//! One command at a time per drawn cursor.
+//!
+//! A session's cursor, or one agent's cursor in a `--multi-agent` session, is
+//! a single picture that every command routed to it moves. A ref action moves
+//! it toward its target before taking the interaction lease, so two commands
+//! sharing it could each move it and then click while it shows the other's
+//! target. Holding this lock from that travel until the action's effect has
+//! played lets one command at a time use a cursor, while commands for
+//! different cursors, such as separate sessions or separate agents, still
+//! travel in parallel. Every ref action takes it before the interaction lease
+//! and never while holding it, so the two locks cannot deadlock.
+
+use crate::{AdapterError, CommandContext, Deadline, storage::file_lock::FileLock};
+
+/// Takes the lock for the cursor this command draws, waiting for another
+/// command using the same cursor until `deadline`. `Ok(None)` when there is no
+/// cursor to share: the overlay is off, or the session keeps no state on disk.
+pub(crate) fn hold_cursor(
+ context: &CommandContext,
+ deadline: Deadline,
+) -> Result<Option<FileLock>, AdapterError> {
+ let Some(session_id) = context
+ .session_id()
+ .filter(|_| context.cursor_overlay().is_enabled())
+ else {
+ return Ok(None);
+ };
+ let Ok(store) = crate::refs::refs_store::RefStore::for_session(Some(session_id)) else {
+ return Ok(None);
+ };
+ if !store.base_dir().is_dir() {
+ return Ok(None);
+ }
+ let directory = store.base_dir().join("cursor");
+ crate::storage::private_file_parent::ensure_private(&directory)
+ .map_err(|error| AdapterError::internal(format!("cursor lock directory: {error}")))?;
+ let name = match super::submit::agent_route(context) {
+ Some(agent_id) => format!("agent-{agent_id}.lock"),
+ None => "session.lock".to_owned(),
+ };
+ FileLock::acquire(&directory.join(name), deadline, "agent cursor").map(Some)
+}
diff --git a/crates/core/src/cursor_overlay/mod.rs b/crates/core/src/cursor_overlay/mod.rs
index 66b8af110..b0fc65810 100644
--- a/crates/core/src/cursor_overlay/mod.rs
+++ b/crates/core/src/cursor_overlay/mod.rs
@@ -1,5 +1,6 @@
mod config;
mod control;
+mod cursor_hold;
mod hand_path;
mod image;
mod images;
@@ -16,6 +17,7 @@ mod timing;
pub use config::{CursorOverlayConfig, MAX_CURSOR_LABEL_BYTES, MAX_CURSOR_LABEL_WORDS};
pub use control::{CURSOR_OVERLAY_GREETING, CursorOverlayControl};
+pub(crate) use cursor_hold::hold_cursor;
pub use image::{
CursorImage, MAX_CURSOR_IMAGE_BYTES, MAX_CURSOR_IMAGE_PATH_BYTES, MAX_CURSOR_IMAGE_PIXELS,
};
@@ -29,7 +31,7 @@ pub use pose::CursorPose;
pub use style::CursorOverlayStyle;
pub(crate) use submit::{
cancel_drag, confirms_delivery, dispatch_mouse_event_with_cursor, input_was_delivered, submit,
- submit_drag, submit_drag_effect, submit_travel,
+ submit_drag, submit_drag_effect, submit_travel, submit_travel_before_lease,
};
pub use timing::{
CURSOR_ARRIVAL_TIMEOUT_MS, CURSOR_HIGHLIGHT_HOLD_MS, CURSOR_IDLE_REST_MS,
diff --git a/crates/core/src/cursor_overlay/submit.rs b/crates/core/src/cursor_overlay/submit.rs
index fc5ceb1b9..2cf7735f5 100644
--- a/crates/core/src/cursor_overlay/submit.rs
+++ b/crates/core/src/cursor_overlay/submit.rs
@@ -9,16 +9,33 @@ const DISPATCH_RESERVE_MS: u64 = 100;
pub(crate) fn travel_scope(
lease: &crate::InteractionLease,
) -> Option<crate::wait::deadline::DeadlineScope> {
- if lease.deadline().remaining_ms()
+ travel_scope_within(lease.deadline())
+}
+
+fn travel_scope_within(deadline: crate::Deadline) -> Option<crate::wait::deadline::DeadlineScope> {
+ if deadline.remaining_ms()
<= crate::CURSOR_ARRIVAL_TIMEOUT_MS.saturating_add(DISPATCH_RESERVE_MS)
{
return None;
}
- Some(crate::wait::deadline::enter_scope(Some(
- lease.deadline().capped(std::time::Duration::from_millis(
- crate::CURSOR_ARRIVAL_TIMEOUT_MS,
- )),
- )))
+ Some(crate::wait::deadline::enter_scope(Some(deadline.capped(
+ std::time::Duration::from_millis(crate::CURSOR_ARRIVAL_TIMEOUT_MS),
+ ))))
+}
+
+/// Moves the drawn cursor toward an action's target before the interaction
+/// lease is held. Travel is presentation only, so holding the machine-wide
+/// lease across it would serialize every other caller behind an animation;
+/// the travel submitted under the lease then only covers any distance the
+/// live target moved since the snapshot.
+pub(crate) fn submit_travel_before_lease(
+ adapter: &dyn PlatformAdapter,
+ context: &CommandContext,
+ destination: Point,
+ deadline: crate::Deadline,
+ pointer: bool,
+) -> bool {
+ travel_within(adapter, context, destination, deadline, pointer)
}
/// Moves the drawn cursor to `destination` before an action; `pointer` arrives showing the
@@ -32,8 +49,18 @@ pub(crate) fn submit_travel(
lease: &crate::InteractionLease,
pointer: bool,
) {
- let Some(_scope) = travel_scope(lease) else {
- return;
+ travel_within(adapter, context, destination, lease.deadline(), pointer);
+}
+
+fn travel_within(
+ adapter: &dyn PlatformAdapter,
+ context: &CommandContext,
+ destination: Point,
+ deadline: crate::Deadline,
+ pointer: bool,
+) -> bool {
+ let Some(_scope) = travel_scope_within(deadline) else {
+ return false;
};
let instruction =
super::CursorOverlayInstruction::new(destination, context.cursor_overlay(), false).map(
@@ -43,7 +70,7 @@ pub(crate) fn submit_travel(
)
},
);
- let _ = send(adapter, context, instruction);
+ send(adapter, context, instruction)
}
pub(crate) fn input_was_delivered(result: &Result<OperationReport, AdapterError>) -> bool {
@@ -153,7 +180,7 @@ fn send(
update(adapter, &control)
}
-fn agent_route(context: &CommandContext) -> Option<String> {
+pub(super) fn agent_route(context: &CommandContext) -> Option<String> {
context
.cursor_overlay()
.is_multi_agent()
diff --git a/crates/core/src/ref_action/presentation.rs b/crates/core/src/ref_action/presentation.rs
index 300882ec9..0936060a0 100644
--- a/crates/core/src/ref_action/presentation.rs
+++ b/crates/core/src/ref_action/presentation.rs
@@ -1,7 +1,15 @@
+use std::cell::Cell;
+
use super::{ActionabilityPreflight, ResolvedRefAction};
use crate::cursor_overlay::CursorPhase;
use crate::{Action, CommandContext, PlatformAdapter};
+const SAME_POINT: f64 = 1.5;
+
+thread_local! {
+ static TRAVELLED_BEFORE_LEASE: Cell<Option<(f64, f64)>> = const { Cell::new(None) };
+}
+
pub(super) fn before_dispatch(
target: &ResolvedRefAction<'_>,
preflight: &ActionabilityPreflight,
@@ -11,6 +19,11 @@ pub(super) fn before_dispatch(
let Some(destination) = destination(preflight) else {
return;
};
+ let travelled = TRAVELLED_BEFORE_LEASE.get();
+ if travelled.is_some_and(|(x, y)| (destination.x - x).hypot(destination.y - y) < SAME_POINT) {
+ return;
+ }
+ TRAVELLED_BEFORE_LEASE.set(None);
let pointer = shows_pointer(&target.entry.identity.role, action);
crate::cursor_overlay::submit_travel(
target.adapter,
@@ -21,6 +34,73 @@ pub(super) fn before_dispatch(
);
}
+/// Starts the drawn cursor's travel toward the target before the interaction
+/// lease is taken, from a read-only resolution of the element. Whatever this
+/// observes is re-resolved under the lease before dispatch, so it only decides
+/// where the cursor heads. Headed actions keep their travel under the lease,
+/// because they move the real pointer. `holds_cursor` says no other command
+/// can move this cursor until the action's effect has played (see
+/// `cursor_overlay::hold_cursor`); without it the travel waits for the lease.
+pub(super) fn before_lease(
+ context: super::ref_action_wait_context::RefActionWaitContext<'_>,
+ request: &crate::ActionRequest,
+ deadline: crate::Deadline,
+ holds_cursor: bool,
+) {
+ TRAVELLED_BEFORE_LEASE.set(None);
+ if !holds_cursor || request.policy.is_headed() || !context.context.cursor_overlay().is_enabled()
+ {
+ return;
+ }
+ let Some(destination) = target_center(context, deadline) else {
+ return;
+ };
+ let pointer = shows_pointer(&context.entry.identity.role, &request.action);
+ if crate::cursor_overlay::submit_travel_before_lease(
+ context.adapter,
+ context.context,
+ destination.clone(),
+ deadline,
+ pointer,
+ ) {
+ TRAVELLED_BEFORE_LEASE.set(Some((destination.x, destination.y)));
+ }
+}
+
+fn target_center(
+ context: super::ref_action_wait_context::RefActionWaitContext<'_>,
+ deadline: crate::Deadline,
+) -> Option<crate::Point> {
+ let geometry = &context.entry.geometry;
+ let stored = matches!(
+ geometry.bounds_space,
+ None | Some(crate::BoundsSpace::Screen)
+ )
+ .then_some(geometry.bounds.as_ref())
+ .flatten()
+ .and_then(center_of);
+ stored.or_else(|| {
+ let handle = context
+ .adapter
+ .resolve_element_strict(context.entry, deadline)
+ .ok()?;
+ let bounds = context
+ .adapter
+ .get_element_bounds(&handle, deadline)
+ .ok()
+ .flatten()?;
+ center_of(&bounds)
+ })
+}
+
+fn center_of(bounds: &crate::Rect) -> Option<crate::Point> {
+ bounds.validate().ok()?;
+ (bounds.width > 0.0 && bounds.height > 0.0).then(|| crate::Point {
+ x: bounds.x + bounds.width / 2.0,
+ y: bounds.y + bounds.height / 2.0,
+ })
+}
+
/// A pressable control shows the pointer however it is reached; any other element shows it
/// only when clicked, and text entry never does.
pub(super) fn shows_pointer(role: &str, action: &Action) -> bool {
@@ -39,10 +119,14 @@ pub(super) fn after_dispatch(
Ok(result) => result.disposition(),
Err(error) => error.disposition,
};
+ let travelled = TRAVELLED_BEFORE_LEASE.take();
if !crate::cursor_overlay::confirms_delivery(disposition) {
return;
}
- let Some(destination) = destination(preflight) else {
+ let Some(destination) = travelled
+ .map(|(x, y)| crate::Point { x, y })
+ .or_else(|| destination(preflight))
+ else {
return;
};
crate::cursor_overlay::submit(
diff --git a/crates/core/src/ref_action/presentation_lease_tests.rs b/crates/core/src/ref_action/presentation_lease_tests.rs
new file mode 100644
index 000000000..47d62d653
--- /dev/null
+++ b/crates/core/src/ref_action/presentation_lease_tests.rs
@@ -0,0 +1,164 @@
+use crate::adapter::{ActionOps, InputOps, NativeHandle, ObservationOps, SystemOps};
+use crate::ref_action::execute_entry_with_context;
+use crate::{
+ Action, ActionRequest, ActionResult, AdapterError, CommandContext, CursorOverlayControl, Point,
+ Rect, RefEntry, actions::capability,
+};
+use std::sync::Mutex;
+
+#[derive(Debug, PartialEq)]
+enum Event {
+ Travel(Point),
+ Lease,
+ Dispatch,
+ Effect(Point),
+}
+
+#[derive(Default)]
+struct LeaseOrderAdapter {
+ events: Mutex<Vec<Event>>,
+}
+
+impl ObservationOps for LeaseOrderAdapter {
+ fn resolve_element_strict(
+ &self,
+ _entry: &RefEntry,
+ _deadline: crate::Deadline,
+ ) -> Result<NativeHandle, AdapterError> {
+ Ok(NativeHandle::null())
+ }
+
+ crate::adapter::complete_live_observation!("button", "Run", [capability::CLICK]);
+}
+
+impl ActionOps for LeaseOrderAdapter {
+ fn execute_action(
+ &self,
+ _handle: &NativeHandle,
+ _request: ActionRequest,
+ _lease: &crate::InteractionLease,
+ ) -> Result<ActionResult, AdapterError> {
+ self.events.lock().unwrap().push(Event::Dispatch);
+ Ok(ActionResult::delivered_unverified("click"))
+ }
+}
+
+impl InputOps for LeaseOrderAdapter {}
+
+impl SystemOps for LeaseOrderAdapter {
+ crate::adapter::exact_window_focus!();
+
+ fn acquire_interaction_lease(
+ &self,
+ deadline: crate::Deadline,
+ ) -> Result<crate::InteractionLease, AdapterError> {
+ self.events.lock().unwrap().push(Event::Lease);
+ crate::InteractionLease::guarded(deadline, ())
+ }
+
+ fn update_cursor_overlay(&self, control: &CursorOverlayControl) -> Result<(), AdapterError> {
+ let destination = control.instruction().unwrap().destination().clone();
+ self.events.lock().unwrap().push(if control.is_travel() {
+ Event::Travel(destination)
+ } else {
+ Event::Effect(destination)
+ });
+ Ok(())
+ }
+}
+
+fn button_at(bounds: Rect) -> RefEntry {
+ let mut entry = crate::adapter::minimal_ref_entry("button", Some("Run"));
+ entry.geometry.bounds = Some(bounds);
+ entry.geometry.bounds_hash = bounds.bounds_hash();
+ entry.capabilities.available_actions = vec![capability::CLICK.into()];
+ entry.source.source_app = Some("Fixture".into());
+ entry.source.source_window_id = Some("w-42".into());
+ entry.source.source_window_title = Some("Fixture".into());
+ entry
+}
+
+fn live_bounds() -> Rect {
+ Rect {
+ x: 1.0,
+ y: 1.0,
+ width: 20.0,
+ height: 20.0,
+ }
+}
+
+fn overlay_context() -> CommandContext {
+ let config = crate::CursorOverlayConfig::enabled(None, 6).expect("valid config");
+ CommandContext::default().with_cursor_overlay_session("test-session", config)
+}
+
+#[test]
+fn headless_travel_runs_before_the_lease_so_cursors_do_not_queue_behind_it() {
+ let adapter = LeaseOrderAdapter::default();
+
+ execute_entry_with_context(
+ &adapter,
+ &button_at(live_bounds()),
+ ActionRequest::headless(Action::Click),
+ &overlay_context(),
+ )
+ .expect("click succeeds");
+
+ let center = Point { x: 11.0, y: 11.0 };
+ assert_eq!(
+ *adapter.events.lock().unwrap(),
+ [
+ Event::Travel(center.clone()),
+ Event::Lease,
+ Event::Dispatch,
+ Event::Effect(center),
+ ],
+ "the cursor that already reached the target does not travel again under the lease"
+ );
+}
+
+#[test]
+fn a_target_that_moved_since_the_snapshot_gets_a_short_travel_under_the_lease() {
+ let adapter = LeaseOrderAdapter::default();
+ let stored = Rect {
+ x: 101.0,
+ ..live_bounds()
+ };
+
+ execute_entry_with_context(
+ &adapter,
+ &button_at(stored),
+ ActionRequest::headless(Action::Click),
+ &overlay_context(),
+ )
+ .expect("click succeeds");
+
+ let live_center = Point { x: 11.0, y: 11.0 };
+ assert_eq!(
+ *adapter.events.lock().unwrap(),
+ [
+ Event::Travel(Point { x: 111.0, y: 11.0 }),
+ Event::Lease,
+ Event::Travel(live_center.clone()),
+ Event::Dispatch,
+ Event::Effect(live_center),
+ ]
+ );
+}
+
+#[test]
+fn headed_travel_stays_under_the_lease_because_it_moves_the_real_pointer() {
+ let adapter = LeaseOrderAdapter::default();
+
+ execute_entry_with_context(
+ &adapter,
+ &button_at(live_bounds()),
+ ActionRequest::headed(Action::Click),
+ &overlay_context().with_headed(true),
+ )
+ .expect("click succeeds");
+
+ let events = adapter.events.lock().unwrap();
+ assert_eq!(events.first(), Some(&Event::Lease));
+ assert!(matches!(events.get(1), Some(Event::Travel(_))));
+}
diff --git a/crates/core/src/ref_action/presentation_shared_cursor_tests.rs b/crates/core/src/ref_action/presentation_shared_cursor_tests.rs
new file mode 100644
index 000000000..d0a2866aa
--- /dev/null
+++ b/crates/core/src/ref_action/presentation_shared_cursor_tests.rs
@@ -0,0 +1,167 @@
+use crate::adapter::{ActionOps, InputOps, NativeHandle, ObservationOps, SystemOps};
+use crate::ref_action::execute_entry_with_context;
+use crate::refs::refs_test_support::HomeGuard;
+use crate::{
+ Action, ActionRequest, ActionResult, AdapterError, CommandContext, CursorOverlayControl, Rect,
+ RefEntry, actions::capability,
+};
+use std::sync::Mutex;
+use std::time::{Duration, Instant};
+
+#[derive(Debug, Clone, Copy, PartialEq)]
+enum Event {
+ Travel,
+ Lease,
+ Dispatch,
+ Effect,
+}
+
+#[derive(Default)]
+struct TimedAdapter {
+ events: Mutex<Vec<(Event, Instant)>>,
+}
+
+impl TimedAdapter {
+ fn record(&self, event: Event) {
+ self.events.lock().unwrap().push((event, Instant::now()));
+ }
+
+ fn first(&self, wanted: Event) -> Instant {
+ self.events
+ .lock()
+ .unwrap()
+ .iter()
+ .find(|(event, _)| *event == wanted)
+ .map(|(_, at)| *at)
+ .expect("the event happened")
+ }
+}
+
+impl ObservationOps for TimedAdapter {
+ fn resolve_element_strict(
+ &self,
+ _entry: &RefEntry,
+ _deadline: crate::Deadline,
+ ) -> Result<NativeHandle, AdapterError> {
+ Ok(NativeHandle::null())
+ }
+
+ crate::adapter::complete_live_observation!("button", "Run", [capability::CLICK]);
+}
+
+impl ActionOps for TimedAdapter {
+ fn execute_action(
+ &self,
+ _handle: &NativeHandle,
+ _request: ActionRequest,
+ _lease: &crate::InteractionLease,
+ ) -> Result<ActionResult, AdapterError> {
+ self.record(Event::Dispatch);
+ Ok(ActionResult::delivered_unverified("click"))
+ }
+}
+
+impl InputOps for TimedAdapter {}
+
+impl SystemOps for TimedAdapter {
+ crate::adapter::exact_window_focus!();
+
+ fn acquire_interaction_lease(
+ &self,
+ deadline: crate::Deadline,
+ ) -> Result<crate::InteractionLease, AdapterError> {
+ self.record(Event::Lease);
+ crate::InteractionLease::guarded(deadline, ())
+ }
+
+ fn update_cursor_overlay(&self, control: &CursorOverlayControl) -> Result<(), AdapterError> {
+ self.record(if control.is_travel() {
+ Event::Travel
+ } else {
+ Event::Effect
+ });
+ Ok(())
+ }
+}
+
+fn button() -> RefEntry {
+ let bounds = Rect {
+ x: 1.0,
+ y: 1.0,
+ width: 20.0,
+ height: 20.0,
+ };
+ let mut entry = crate::adapter::minimal_ref_entry("button", Some("Run"));
+ entry.geometry.bounds = Some(bounds);
+ entry.geometry.bounds_hash = bounds.bounds_hash();
+ entry.capabilities.available_actions = vec![capability::CLICK.into()];
+ entry.source.source_app = Some("Fixture".into());
+ entry.source.source_window_id = Some("w-42".into());
+ entry.source.source_window_title = Some("Fixture".into());
+ entry
+}
+
+/// A session whose state is on disk, so its cursor can be shared and locked.
+fn session(id: &str) -> CommandContext {
+ let store = crate::refs::refs_store::RefStore::for_session(Some(id)).expect("a session store");
+ std::fs::create_dir_all(store.base_dir()).expect("the session directory");
+ let config = crate::CursorOverlayConfig::enabled(None, 6).expect("valid config");
+ CommandContext::default().with_cursor_overlay_session(id, config)
+}
+
+fn hold_elsewhere_for(context: &CommandContext, hold: Duration) -> Instant {
+ let deadline = crate::Deadline::after(1_000).expect("a deadline");
+ let lock = crate::cursor_overlay::hold_cursor(context, deadline)
+ .expect("the cursor lock")
+ .expect("a shared cursor");
+ let released = Instant::now() + hold;
+ std::thread::spawn(move || {
+ std::thread::sleep(hold);
+ drop(lock);
+ });
+ released
+}
+
+/// Another command in the same session is between its travel and its click.
+/// This one must not move their shared cursor until that command is done, or
+/// the other click would land while the cursor shows this target.
+#[test]
+fn a_command_sharing_the_cursor_waits_for_the_one_already_using_it() {
+ let _home = HomeGuard::new();
+ let context = session("run-shared");
+ let released = hold_elsewhere_for(&context, Duration::from_millis(150));
+ let adapter = TimedAdapter::default();
+
+ execute_entry_with_context(
+ &adapter,
+ &button(),
+ ActionRequest::headless(Action::Click),
+ &context,
+ )
+ .expect("click succeeds");
+
+ assert!(adapter.first(Event::Travel) >= released);
+ assert!(adapter.first(Event::Travel) <= adapter.first(Event::Lease));
+}
+
+/// Separate sessions draw separate cursors, so one session's command in
+/// flight does not hold back another session's travel.
+#[test]
+fn a_command_in_another_session_travels_without_waiting() {
+ let _home = HomeGuard::new();
+ let busy = session("run-busy");
+ let other = session("run-other");
+ let released = hold_elsewhere_for(&busy, Duration::from_millis(400));
+ let adapter = TimedAdapter::default();
+
+ execute_entry_with_context(
+ &adapter,
+ &button(),
+ ActionRequest::headless(Action::Click),
+ &other,
+ )
+ .expect("click succeeds");
+
+ assert!(adapter.first(Event::Travel) < released);
+ assert!(adapter.first(Event::Travel) <= adapter.first(Event::Lease));
+}
diff --git a/crates/core/src/ref_action/presentation_tests.rs b/crates/core/src/ref_action/presentation_tests.rs
index 71401e5d1..45634a823 100644
--- a/crates/core/src/ref_action/presentation_tests.rs
+++ b/crates/core/src/ref_action/presentation_tests.rs
@@ -44,3 +44,9 @@ fn other_elements_show_the_pointer_only_when_clicked() {
);
}
}
+
+#[path = "presentation_lease_tests.rs"]
+mod lease;
+
+#[path = "presentation_shared_cursor_tests.rs"]
+mod shared_cursor;
diff --git a/crates/core/src/ref_action/ref_action_wait.rs b/crates/core/src/ref_action/ref_action_wait.rs
index 6025c2947..acbba4ad0 100644
--- a/crates/core/src/ref_action/ref_action_wait.rs
+++ b/crates/core/src/ref_action/ref_action_wait.rs
@@ -88,6 +88,8 @@ fn execute_with_deadline(
context.entry,
deadline,
);
+ let cursor = crate::cursor_overlay::hold_cursor(context.context, deadline);
+ crate::ref_action::presentation::before_lease(context, &request, deadline, cursor.is_ok());
let lease = context
.adapter
.acquire_interaction_lease(deadline)
diff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.md
index b9f6211cb..bd0bde384 100644
--- a/skills/agent-desktop/references/commands-system.md
+++ b/skills/agent-desktop/references/commands-system.md
@@ -202,6 +202,7 @@ Multi-agent cursors (macOS and Windows): start with `session start --cursor --mu
- Desktop UI actions then require an agent id: global `--agent-id <id>` or `AGENT_DESKTOP_AGENT_ID`. The flag wins. Observations, clipboard commands and session administration do not need one.
- An id has 1 to 64 letters, digits, `-` or `_`. It is scoped by session. Each distinct id gets its own cursor, and a reused id reuses its cursor.
+- A headless action moves its cursor before it takes the interaction lease, so several agents' cursors travel at the same time. The actions still take turns, and commands that draw the same cursor take turns from its travel to its click effect.
- `--agent-id <id> cursor-overlay enable` saves a style for that agent. Do not add `--multi-agent` to it.
- `cursor-overlay disable` and `session end` stop every cursor in the session, even when you pass an agent id.